trtc-sdk-v5 5.15.0-beta.20 → 5.15.0-beta.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/assets/debug-dialog.js +2 -2
  2. package/assets/videodec.wasm +0 -0
  3. package/assets/videodec_simd.wasm +0 -0
  4. package/index.d.ts +8 -2
  5. package/package.json +1 -1
  6. package/plugins/cdn-streaming/package.json +1 -1
  7. package/plugins/chorus/package.json +1 -1
  8. package/plugins/cross-room/package.json +1 -1
  9. package/plugins/custom-encryption/package.json +1 -1
  10. package/plugins/device-detector/package.json +1 -1
  11. package/plugins/fast-webrtc/fast-webrtc.esm.d.ts +27 -0
  12. package/plugins/fast-webrtc/fast-webrtc.esm.js +1 -0
  13. package/plugins/fast-webrtc/fast-webrtc.umd.js +1 -0
  14. package/plugins/fast-webrtc/package.json +29 -0
  15. package/plugins/lebplayer/lebplayer.esm.d.ts +260 -0
  16. package/plugins/lebplayer/lebplayer.esm.js +1 -0
  17. package/plugins/lebplayer/lebplayer.umd.js +1 -0
  18. package/plugins/lebplayer/package.json +29 -0
  19. package/plugins/small-stream-auto-switcher/package.json +1 -1
  20. package/plugins/video-decoder/package.json +1 -1
  21. package/plugins/video-decoder/video-decoder.esm.js +1 -1
  22. package/plugins/video-decoder/video-decoder.umd.js +1 -1
  23. package/plugins/video-effect/basic-beauty/package.json +1 -1
  24. package/plugins/video-effect/beauty/package.json +1 -1
  25. package/plugins/video-effect/video-mixer/package.json +1 -1
  26. package/plugins/video-effect/video-mixer/video-mixer.esm.d.ts +2 -0
  27. package/plugins/video-effect/video-mixer/video-mixer.esm.js +1 -1
  28. package/plugins/video-effect/video-mixer/video-mixer.umd.js +1 -1
  29. package/plugins/video-effect/virtual-background/package.json +1 -1
  30. package/plugins/video-effect/watermark/package.json +1 -1
  31. package/plugins/voice-changer/package.json +1 -1
  32. package/trtc.esm.js +42 -38
  33. package/trtc.js +1 -1
package/trtc.esm.js CHANGED
@@ -1,16 +1,16 @@
1
- var Q_=Object.create;var Os=Object.defineProperty,Y_=Object.defineProperties,cm=Object.getOwnPropertyDescriptor,Z_=Object.getOwnPropertyDescriptors,K_=Object.getOwnPropertyNames,sa=Object.getOwnPropertySymbols,lm=Object.getPrototypeOf,Bc=Object.prototype.hasOwnProperty,um=Object.prototype.propertyIsEnumerable,eg=Reflect.get;var hr=Math.pow,Fc=(o,i,e)=>i in o?Os(o,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[i]=e,M=(o,i)=>{for(var e in i||(i={}))Bc.call(i,e)&&Fc(o,e,i[e]);if(sa)for(var e of sa(i))um.call(i,e)&&Fc(o,e,i[e]);return o},w=(o,i)=>Y_(o,Z_(i));var na=(o,i)=>{var e={};for(var t in o)Bc.call(o,t)&&i.indexOf(t)<0&&(e[t]=o[t]);if(o!=null&&sa)for(var t of sa(o))i.indexOf(t)<0&&um.call(o,t)&&(e[t]=o[t]);return e};var Fi=(o,i)=>()=>(i||o((i={exports:{}}).exports,i),i.exports),Bi=(o,i)=>{for(var e in i)Os(o,e,{get:i[e],enumerable:!0})},tg=(o,i,e,t)=>{if(i&&typeof i=="object"||typeof i=="function")for(let r of K_(i))!Bc.call(o,r)&&r!==e&&Os(o,r,{get:()=>i[r],enumerable:!(t=cm(i,r))||t.enumerable});return o};var Je=(o,i,e)=>(e=o!=null?Q_(lm(o)):{},tg(i||!o||!o.__esModule?Os(e,"default",{value:o,enumerable:!0}):e,o));var D=(o,i,e,t)=>{for(var r=t>1?void 0:t?cm(i,e):i,s=o.length-1,n;s>=0;s--)(n=o[s])&&(r=(t?n(i,e,r):n(r))||r);return t&&r&&Os(i,e,r),r};var c=(o,i,e)=>Fc(o,typeof i!="symbol"?i+"":i,e);var Le=(o,i,e)=>eg(lm(o),e,i);var f=(o,i,e)=>new Promise((t,r)=>{var s=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(s,n);a((e=e.apply(o,i)).next())});var nt=Fi((OI,Hc)=>{"use strict";var ig=Object.prototype.hasOwnProperty,ut="~";function ks(){}Object.create&&(ks.prototype=Object.create(null),new ks().__proto__||(ut=!1));function rg(o,i,e){this.fn=o,this.context=i,this.once=e||!1}function hm(o,i,e,t,r){if(typeof e!="function")throw new TypeError("The listener must be a function");var s=new rg(e,t||o,r),n=ut?ut+i:i;return o._events[n]?o._events[n].fn?o._events[n]=[o._events[n],s]:o._events[n].push(s):(o._events[n]=s,o._eventsCount++),o}function aa(o,i){--o._eventsCount===0?o._events=new ks:delete o._events[i]}function st(){this._events=new ks,this._eventsCount=0}st.prototype.eventNames=function(){var i=[],e,t;if(this._eventsCount===0)return i;for(t in e=this._events)ig.call(e,t)&&i.push(ut?t.slice(1):t);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i};st.prototype.listeners=function(i){var e=ut?ut+i:i,t=this._events[e];if(!t)return[];if(t.fn)return[t.fn];for(var r=0,s=t.length,n=new Array(s);r<s;r++)n[r]=t[r].fn;return n};st.prototype.listenerCount=function(i){var e=ut?ut+i:i,t=this._events[e];return t?t.fn?1:t.length:0};st.prototype.emit=function(i,e,t,r,s,n){var a=ut?ut+i:i;if(!this._events[a])return!1;var d=this._events[a],l=arguments.length,u,h;if(d.fn){switch(d.once&&this.removeListener(i,d.fn,void 0,!0),l){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,e),!0;case 3:return d.fn.call(d.context,e,t),!0;case 4:return d.fn.call(d.context,e,t,r),!0;case 5:return d.fn.call(d.context,e,t,r,s),!0;case 6:return d.fn.call(d.context,e,t,r,s,n),!0}for(h=1,u=new Array(l-1);h<l;h++)u[h-1]=arguments[h];d.fn.apply(d.context,u)}else{var p=d.length,m;for(h=0;h<p;h++)switch(d[h].once&&this.removeListener(i,d[h].fn,void 0,!0),l){case 1:d[h].fn.call(d[h].context);break;case 2:d[h].fn.call(d[h].context,e);break;case 3:d[h].fn.call(d[h].context,e,t);break;case 4:d[h].fn.call(d[h].context,e,t,r);break;default:if(!u)for(m=1,u=new Array(l-1);m<l;m++)u[m-1]=arguments[m];d[h].fn.apply(d[h].context,u)}}return!0};st.prototype.on=function(i,e,t){return hm(this,i,e,t,!1)};st.prototype.once=function(i,e,t){return hm(this,i,e,t,!0)};st.prototype.removeListener=function(i,e,t,r){var s=ut?ut+i:i;if(!this._events[s])return this;if(!e)return aa(this,s),this;var n=this._events[s];if(n.fn)n.fn===e&&(!r||n.once)&&(!t||n.context===t)&&aa(this,s);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[s]=d.length===1?d[0]:d:aa(this,s)}return this};st.prototype.removeAllListeners=function(i){var e;return i?(e=ut?ut+i:i,this._events[e]&&aa(this,e)):(this._events=new ks,this._eventsCount=0),this};st.prototype.off=st.prototype.removeListener;st.prototype.addListener=st.prototype.on;st.prefixed=ut;st.EventEmitter=st;typeof Hc!="undefined"&&(Hc.exports=st)});var dd=Fi((rC,np)=>{"use strict";var sp=np.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(o){return o.encoding?"rtpmap:%d %s/%s/%s":o.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(o){return o.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(o){return o.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(o){return"extmap:%d"+(o.direction?"/%s":"%v")+(o["encrypt-uri"]?" %s":"%v")+" %s"+(o.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(o){return o.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(o){var i="candidate:%s %d %s %d %s %d typ %s";return i+=o.raddr!=null?" raddr %s rport %d":"%v%v",i+=o.tcptype!=null?" tcptype %s":"%v",o.generation!=null&&(i+=" generation %d"),i+=o["network-id"]!=null?" network-id %d":"%v",i+=o["network-cost"]!=null?" network-cost %d":"%v",i}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(o){var i="ssrc:%d";return o.attribute!=null&&(i+=" %s",o.value!=null&&(i+=":%s")),i}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(o){return o.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(o){return o.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(o){return"imageattr:%s %s %s"+(o.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(o){return"simulcast:%s %s"+(o.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(o){return"ts-refclk:%s"+(o.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(o){var i="mediaclk:";return i+=o.id!=null?"id=%s %s":"%v%s",i+=o.mediaClockValue!=null?"=%s":"",i+=o.rateNumerator!=null?" rate=%s":"",i+=o.rateDenominator!=null?"/%s":"",i}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(sp).forEach(function(o){var i=sp[o];i.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var cp=Fi(Yi=>{"use strict";var is=function(o){return String(Number(o))===o?Number(o):o},uT=function(o,i,e,t){if(t&&!e)i[t]=is(o[1]);else for(var r=0;r<e.length;r+=1)o[r+1]!=null&&(i[e[r]]=is(o[r+1]))},hT=function(o,i,e){var t=o.name&&o.names;o.push&&!i[o.push]?i[o.push]=[]:t&&!i[o.name]&&(i[o.name]={});var r=o.push?{}:t?i[o.name]:i;uT(e.match(o.reg),r,o.names,o.name),o.push&&i[o.push].push(r)},ap=dd(),mT=RegExp.prototype.test.bind(/^([a-z])=(.*)/);Yi.parse=function(o){var i={},e=[],t=i;return o.split(/(\r\n|\r|\n)/).filter(mT).forEach(function(r){var s=r[0],n=r.slice(2);s==="m"&&(e.push({rtp:[],fmtp:[]}),t=e[e.length-1]);for(var a=0;a<(ap[s]||[]).length;a+=1){var d=ap[s][a];if(d.reg.test(n))return hT(d,t,n)}}),i.media=e,i};var dp=function(o,i){var e=i.split(/=(.+)/,2);return e.length===2?o[e[0]]=is(e[1]):e.length===1&&i.length>1&&(o[e[0]]=void 0),o};Yi.parseParams=function(o){return o.split(/;\s?/).reduce(dp,{})};Yi.parseFmtpConfig=Yi.parseParams;Yi.parsePayloads=function(o){return o.toString().split(" ").map(Number)};Yi.parseRemoteCandidates=function(o){for(var i=[],e=o.split(" ").map(is),t=0;t<e.length;t+=3)i.push({component:e[t],ip:e[t+1],port:e[t+2]});return i};Yi.parseImageAttributes=function(o){return o.split(" ").map(function(i){return i.substring(1,i.length-1).split(",").reduce(dp,{})})};Yi.parseSimulcastStreamList=function(o){return o.split(";").map(function(i){return i.split(",").map(function(e){var t,r=!1;return e[0]!=="~"?t=is(e):(t=is(e.substring(1,e.length)),r=!0),{scid:t,paused:r}})})}});var up=Fi((sC,lp)=>{"use strict";var Ql=dd(),pT=/%[sdv%]/g,fT=function(o){var i=1,e=arguments,t=e.length;return o.replace(pT,function(r){if(i>=t)return r;var s=e[i];switch(i+=1,r){case"%%":return"%";case"%s":return String(s);case"%d":return Number(s);case"%v":return""}})},hn=function(o,i,e){var t=i.format instanceof Function?i.format(i.push?e:e[i.name]):i.format,r=[o+"="+t];if(i.names)for(var s=0;s<i.names.length;s+=1){var n=i.names[s];i.name?r.push(e[i.name][n]):r.push(e[i.names[s]])}else r.push(e[i.name]);return fT.apply(null,r)},_T=["v","o","s","i","u","e","p","c","b","t","r","z","a"],gT=["i","c","b","a"];lp.exports=function(o,i){i=i||{},o.version==null&&(o.version=0),o.name==null&&(o.name=" "),o.media.forEach(function(s){s.payloads==null&&(s.payloads="")});var e=i.outerOrder||_T,t=i.innerOrder||gT,r=[];return e.forEach(function(s){Ql[s].forEach(function(n){n.name in o&&o[n.name]!=null?r.push(hn(s,n,o)):n.push in o&&o[n.push]!=null&&o[n.push].forEach(function(a){r.push(hn(s,n,a))})})}),o.media.forEach(function(s){r.push(hn("m",Ql.m[0],s)),t.forEach(function(n){Ql[n].forEach(function(a){a.name in s&&s[a.name]!=null?r.push(hn(n,a,s)):a.push in s&&s[a.push]!=null&&s[a.push].forEach(function(d){r.push(hn(n,a,d))})})})}),r.join(`\r
1
+ var ig=Object.create;var ws=Object.defineProperty,rg=Object.defineProperties,Em=Object.getOwnPropertyDescriptor,og=Object.getOwnPropertyDescriptors,sg=Object.getOwnPropertyNames,da=Object.getOwnPropertySymbols,Sm=Object.getPrototypeOf,Xd=Object.prototype.hasOwnProperty,Im=Object.prototype.propertyIsEnumerable,ng=Reflect.get;var hr=Math.pow,jd=(o,i,e)=>i in o?ws(o,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[i]=e,O=(o,i)=>{for(var e in i||(i={}))Xd.call(i,e)&&jd(o,e,i[e]);if(da)for(var e of da(i))Im.call(i,e)&&jd(o,e,i[e]);return o},L=(o,i)=>rg(o,og(i));var la=(o,i)=>{var e={};for(var t in o)Xd.call(o,t)&&i.indexOf(t)<0&&(e[t]=o[t]);if(o!=null&&da)for(var t of da(o))i.indexOf(t)<0&&Im.call(o,t)&&(e[t]=o[t]);return e};var Ui=(o,i)=>()=>(i||o((i={exports:{}}).exports,i),i.exports),Vi=(o,i)=>{for(var e in i)ws(o,e,{get:i[e],enumerable:!0})},ag=(o,i,e,t)=>{if(i&&typeof i=="object"||typeof i=="function")for(let r of sg(i))!Xd.call(o,r)&&r!==e&&ws(o,r,{get:()=>i[r],enumerable:!(t=Em(i,r))||t.enumerable});return o};var Je=(o,i,e)=>(e=o!=null?ig(Sm(o)):{},ag(i||!o||!o.__esModule?ws(e,"default",{value:o,enumerable:!0}):e,o));var M=(o,i,e,t)=>{for(var r=t>1?void 0:t?Em(i,e):i,s=o.length-1,n;s>=0;s--)(n=o[s])&&(r=(t?n(i,e,r):n(r))||r);return t&&r&&ws(i,e,r),r};var d=(o,i,e)=>jd(o,typeof i!="symbol"?i+"":i,e);var we=(o,i,e)=>ng(Sm(o),e,i);var f=(o,i,e)=>new Promise((t,r)=>{var s=c=>{try{a(e.next(c))}catch(l){r(l)}},n=c=>{try{a(e.throw(c))}catch(l){r(l)}},a=c=>c.done?t(c.value):Promise.resolve(c.value).then(s,n);a((e=e.apply(o,i)).next())});var at=Ui((VI,zd)=>{"use strict";var cg=Object.prototype.hasOwnProperty,ht="~";function Ls(){}Object.create&&(Ls.prototype=Object.create(null),new Ls().__proto__||(ht=!1));function dg(o,i,e){this.fn=o,this.context=i,this.once=e||!1}function Am(o,i,e,t,r){if(typeof e!="function")throw new TypeError("The listener must be a function");var s=new dg(e,t||o,r),n=ht?ht+i:i;return o._events[n]?o._events[n].fn?o._events[n]=[o._events[n],s]:o._events[n].push(s):(o._events[n]=s,o._eventsCount++),o}function ua(o,i){--o._eventsCount===0?o._events=new Ls:delete o._events[i]}function nt(){this._events=new Ls,this._eventsCount=0}nt.prototype.eventNames=function(){var i=[],e,t;if(this._eventsCount===0)return i;for(t in e=this._events)cg.call(e,t)&&i.push(ht?t.slice(1):t);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i};nt.prototype.listeners=function(i){var e=ht?ht+i:i,t=this._events[e];if(!t)return[];if(t.fn)return[t.fn];for(var r=0,s=t.length,n=new Array(s);r<s;r++)n[r]=t[r].fn;return n};nt.prototype.listenerCount=function(i){var e=ht?ht+i:i,t=this._events[e];return t?t.fn?1:t.length:0};nt.prototype.emit=function(i,e,t,r,s,n){var a=ht?ht+i:i;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,h,m;if(c.fn){switch(c.once&&this.removeListener(i,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,e),!0;case 3:return c.fn.call(c.context,e,t),!0;case 4:return c.fn.call(c.context,e,t,r),!0;case 5:return c.fn.call(c.context,e,t,r,s),!0;case 6:return c.fn.call(c.context,e,t,r,s,n),!0}for(m=1,h=new Array(l-1);m<l;m++)h[m-1]=arguments[m];c.fn.apply(c.context,h)}else{var u=c.length,_;for(m=0;m<u;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(!h)for(_=1,h=new Array(l-1);_<l;_++)h[_-1]=arguments[_];c[m].fn.apply(c[m].context,h)}}return!0};nt.prototype.on=function(i,e,t){return Am(this,i,e,t,!1)};nt.prototype.once=function(i,e,t){return Am(this,i,e,t,!0)};nt.prototype.removeListener=function(i,e,t,r){var s=ht?ht+i:i;if(!this._events[s])return this;if(!e)return ua(this,s),this;var n=this._events[s];if(n.fn)n.fn===e&&(!r||n.once)&&(!t||n.context===t)&&ua(this,s);else{for(var a=0,c=[],l=n.length;a<l;a++)(n[a].fn!==e||r&&!n[a].once||t&&n[a].context!==t)&&c.push(n[a]);c.length?this._events[s]=c.length===1?c[0]:c:ua(this,s)}return this};nt.prototype.removeAllListeners=function(i){var e;return i?(e=ht?ht+i:i,this._events[e]&&ua(this,e)):(this._events=new Ls,this._eventsCount=0),this};nt.prototype.off=nt.prototype.removeListener;nt.prototype.addListener=nt.prototype.on;nt.prefixed=ht;nt.EventEmitter=nt;typeof zd!="undefined"&&(zd.exports=nt)});var pc=Ui((lC,_p)=>{"use strict";var fp=_p.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(o){return o.encoding?"rtpmap:%d %s/%s/%s":o.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(o){return o.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(o){return o.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(o){return"extmap:%d"+(o.direction?"/%s":"%v")+(o["encrypt-uri"]?" %s":"%v")+" %s"+(o.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(o){return o.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(o){var i="candidate:%s %d %s %d %s %d typ %s";return i+=o.raddr!=null?" raddr %s rport %d":"%v%v",i+=o.tcptype!=null?" tcptype %s":"%v",o.generation!=null&&(i+=" generation %d"),i+=o["network-id"]!=null?" network-id %d":"%v",i+=o["network-cost"]!=null?" network-cost %d":"%v",i}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(o){var i="ssrc:%d";return o.attribute!=null&&(i+=" %s",o.value!=null&&(i+=":%s")),i}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(o){return o.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(o){return o.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(o){return"imageattr:%s %s %s"+(o.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(o){return"simulcast:%s %s"+(o.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(o){return"ts-refclk:%s"+(o.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(o){var i="mediaclk:";return i+=o.id!=null?"id=%s %s":"%v%s",i+=o.mediaClockValue!=null?"=%s":"",i+=o.rateNumerator!=null?" rate=%s":"",i+=o.rateDenominator!=null?"/%s":"",i}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(fp).forEach(function(o){var i=fp[o];i.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var Ep=Ui(Yi=>{"use strict";var os=function(o){return String(Number(o))===o?Number(o):o},TT=function(o,i,e,t){if(t&&!e)i[t]=os(o[1]);else for(var r=0;r<e.length;r+=1)o[r+1]!=null&&(i[e[r]]=os(o[r+1]))},ET=function(o,i,e){var t=o.name&&o.names;o.push&&!i[o.push]?i[o.push]=[]:t&&!i[o.name]&&(i[o.name]={});var r=o.push?{}:t?i[o.name]:i;TT(e.match(o.reg),r,o.names,o.name),o.push&&i[o.push].push(r)},gp=pc(),ST=RegExp.prototype.test.bind(/^([a-z])=(.*)/);Yi.parse=function(o){var i={},e=[],t=i;return o.split(/(\r\n|\r|\n)/).filter(ST).forEach(function(r){var s=r[0],n=r.slice(2);s==="m"&&(e.push({rtp:[],fmtp:[]}),t=e[e.length-1]);for(var a=0;a<(gp[s]||[]).length;a+=1){var c=gp[s][a];if(c.reg.test(n))return ET(c,t,n)}}),i.media=e,i};var Tp=function(o,i){var e=i.split(/=(.+)/,2);return e.length===2?o[e[0]]=os(e[1]):e.length===1&&i.length>1&&(o[e[0]]=void 0),o};Yi.parseParams=function(o){return o.split(/;\s?/).reduce(Tp,{})};Yi.parseFmtpConfig=Yi.parseParams;Yi.parsePayloads=function(o){return o.toString().split(" ").map(Number)};Yi.parseRemoteCandidates=function(o){for(var i=[],e=o.split(" ").map(os),t=0;t<e.length;t+=3)i.push({component:e[t],ip:e[t+1],port:e[t+2]});return i};Yi.parseImageAttributes=function(o){return o.split(" ").map(function(i){return i.substring(1,i.length-1).split(",").reduce(Tp,{})})};Yi.parseSimulcastStreamList=function(o){return o.split(";").map(function(i){return i.split(",").map(function(e){var t,r=!1;return e[0]!=="~"?t=os(e):(t=os(e.substring(1,e.length)),r=!0),{scid:t,paused:r}})})}});var Ip=Ui((hC,Sp)=>{"use strict";var ou=pc(),IT=/%[sdv%]/g,AT=function(o){var i=1,e=arguments,t=e.length;return o.replace(IT,function(r){if(i>=t)return r;var s=e[i];switch(i+=1,r){case"%%":return"%";case"%s":return String(s);case"%d":return Number(s);case"%v":return""}})},_n=function(o,i,e){var t=i.format instanceof Function?i.format(i.push?e:e[i.name]):i.format,r=[o+"="+t];if(i.names)for(var s=0;s<i.names.length;s+=1){var n=i.names[s];i.name?r.push(e[i.name][n]):r.push(e[i.names[s]])}else r.push(e[i.name]);return AT.apply(null,r)},CT=["v","o","s","i","u","e","p","c","b","t","r","z","a"],RT=["i","c","b","a"];Sp.exports=function(o,i){i=i||{},o.version==null&&(o.version=0),o.name==null&&(o.name=" "),o.media.forEach(function(s){s.payloads==null&&(s.payloads="")});var e=i.outerOrder||CT,t=i.innerOrder||RT,r=[];return e.forEach(function(s){ou[s].forEach(function(n){n.name in o&&o[n.name]!=null?r.push(_n(s,n,o)):n.push in o&&o[n.push]!=null&&o[n.push].forEach(function(a){r.push(_n(s,n,a))})})}),o.media.forEach(function(s){r.push(_n("m",ou.m[0],s)),t.forEach(function(n){ou[n].forEach(function(a){a.name in s&&s[a.name]!=null?r.push(_n(n,a,s)):a.push in s&&s[a.push]!=null&&s[a.push].forEach(function(c){r.push(_n(n,a,c))})})})}),r.join(`\r
2
2
  `)+`\r
3
- `}});var hp=Fi(bi=>{"use strict";var io=cp(),TT=up(),ET=dd();bi.grammar=ET;bi.write=TT;bi.parse=io.parse;bi.parseParams=io.parseParams;bi.parseFmtpConfig=io.parseFmtpConfig;bi.parsePayloads=io.parsePayloads;bi.parseRemoteCandidates=io.parseRemoteCandidates;bi.parseImageAttributes=io.parseImageAttributes;bi.parseSimulcastStreamList=io.parseSimulcastStreamList});var qh=Fi((_F,r_)=>{"use strict";var i_=r_.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(o){return o.encoding?"rtpmap:%d %s/%s/%s":o.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(o){return o.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(o){return o.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(o){return"extmap:%d"+(o.direction?"/%s":"%v")+(o["encrypt-uri"]?" %s":"%v")+" %s"+(o.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(o){return o.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(o){var i="candidate:%s %d %s %d %s %d typ %s";return i+=o.raddr!=null?" raddr %s rport %d":"%v%v",i+=o.tcptype!=null?" tcptype %s":"%v",o.generation!=null&&(i+=" generation %d"),i+=o["network-id"]!=null?" network-id %d":"%v",i+=o["network-cost"]!=null?" network-cost %d":"%v",i}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(o){var i="ssrc:%d";return o.attribute!=null&&(i+=" %s",o.value!=null&&(i+=":%s")),i}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(o){return o.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(o){return o.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(o){return"imageattr:%s %s %s"+(o.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(o){return"simulcast:%s %s"+(o.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(o){return"ts-refclk:%s"+(o.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(o){var i="mediaclk:";return i+=o.id!=null?"id=%s %s":"%v%s",i+=o.mediaClockValue!=null?"=%s":"",i+=o.rateNumerator!=null?" rate=%s":"",i+=o.rateDenominator!=null?"/%s":"",i}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(i_).forEach(function(o){var i=i_[o];i.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var n_=Fi(cr=>{"use strict";var bs=function(o){return String(Number(o))===o?Number(o):o},tI=function(o,i,e,t){if(t&&!e)i[t]=bs(o[1]);else for(var r=0;r<e.length;r+=1)o[r+1]!=null&&(i[e[r]]=bs(o[r+1]))},iI=function(o,i,e){var t=o.name&&o.names;o.push&&!i[o.push]?i[o.push]=[]:t&&!i[o.name]&&(i[o.name]={});var r=o.push?{}:t?i[o.name]:i;tI(e.match(o.reg),r,o.names,o.name),o.push&&i[o.push].push(r)},o_=qh(),rI=RegExp.prototype.test.bind(/^([a-z])=(.*)/);cr.parse=function(o){var i={},e=[],t=i;return o.split(/(\r\n|\r|\n)/).filter(rI).forEach(function(r){var s=r[0],n=r.slice(2);s==="m"&&(e.push({rtp:[],fmtp:[]}),t=e[e.length-1]);for(var a=0;a<(o_[s]||[]).length;a+=1){var d=o_[s][a];if(d.reg.test(n))return iI(d,t,n)}}),i.media=e,i};var s_=function(o,i){var e=i.split(/=(.+)/,2);return e.length===2?o[e[0]]=bs(e[1]):e.length===1&&i.length>1&&(o[e[0]]=void 0),o};cr.parseParams=function(o){return o.split(/;\s?/).reduce(s_,{})};cr.parseFmtpConfig=cr.parseParams;cr.parsePayloads=function(o){return o.toString().split(" ").map(Number)};cr.parseRemoteCandidates=function(o){for(var i=[],e=o.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};cr.parseImageAttributes=function(o){return o.split(" ").map(function(i){return i.substring(1,i.length-1).split(",").reduce(s_,{})})};cr.parseSimulcastStreamList=function(o){return o.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 d_=Fi((TF,a_)=>{"use strict";var jh=qh(),oI=/%[sdv%]/g,sI=function(o){var i=1,e=arguments,t=e.length;return o.replace(oI,function(r){if(i>=t)return r;var s=e[i];switch(i+=1,r){case"%%":return"%";case"%s":return String(s);case"%d":return Number(s);case"%v":return""}})},ea=function(o,i,e){var t=i.format instanceof Function?i.format(i.push?e:e[i.name]):i.format,r=[o+"="+t];if(i.names)for(var s=0;s<i.names.length;s+=1){var n=i.names[s];i.name?r.push(e[i.name][n]):r.push(e[i.names[s]])}else r.push(e[i.name]);return sI.apply(null,r)},nI=["v","o","s","i","u","e","p","c","b","t","r","z","a"],aI=["i","c","b","a"];a_.exports=function(o,i){i=i||{},o.version==null&&(o.version=0),o.name==null&&(o.name=" "),o.media.forEach(function(s){s.payloads==null&&(s.payloads="")});var e=i.outerOrder||nI,t=i.innerOrder||aI,r=[];return e.forEach(function(s){jh[s].forEach(function(n){n.name in o&&o[n.name]!=null?r.push(ea(s,n,o)):n.push in o&&o[n.push]!=null&&o[n.push].forEach(function(a){r.push(ea(s,n,a))})})}),o.media.forEach(function(s){r.push(ea("m",jh.m[0],s)),t.forEach(function(n){jh[n].forEach(function(a){a.name in s&&s[a.name]!=null?r.push(ea(n,a,s)):a.push in s&&s[a.push]!=null&&s[a.push].forEach(function(d){r.push(ea(n,a,d))})})})}),r.join(`\r
3
+ `}});var Ap=Ui(yi=>{"use strict";var io=Ep(),yT=Ip(),bT=pc();yi.grammar=bT;yi.write=yT;yi.parse=io.parse;yi.parseParams=io.parseParams;yi.parseFmtpConfig=io.parseFmtpConfig;yi.parsePayloads=io.parsePayloads;yi.parseRemoteCandidates=io.parseRemoteCandidates;yi.parseImageAttributes=io.parseImageAttributes;yi.parseSimulcastStreamList=io.parseSimulcastStreamList});var im=Ui((WF,p_)=>{"use strict";var m_=p_.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(o){return o.encoding?"rtpmap:%d %s/%s/%s":o.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(o){return o.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(o){return o.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(o){return"extmap:%d"+(o.direction?"/%s":"%v")+(o["encrypt-uri"]?" %s":"%v")+" %s"+(o.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(o){return o.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(o){var i="candidate:%s %d %s %d %s %d typ %s";return i+=o.raddr!=null?" raddr %s rport %d":"%v%v",i+=o.tcptype!=null?" tcptype %s":"%v",o.generation!=null&&(i+=" generation %d"),i+=o["network-id"]!=null?" network-id %d":"%v",i+=o["network-cost"]!=null?" network-cost %d":"%v",i}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(o){var i="ssrc:%d";return o.attribute!=null&&(i+=" %s",o.value!=null&&(i+=":%s")),i}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(o){return o.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(o){return o.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(o){return"imageattr:%s %s %s"+(o.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(o){return"simulcast:%s %s"+(o.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(o){return"ts-refclk:%s"+(o.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(o){var i="mediaclk:";return i+=o.id!=null?"id=%s %s":"%v%s",i+=o.mediaClockValue!=null?"=%s":"",i+=o.rateNumerator!=null?" rate=%s":"",i+=o.rateDenominator!=null?"/%s":"",i}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(m_).forEach(function(o){var i=m_[o];i.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var g_=Ui(dr=>{"use strict";var Ds=function(o){return String(Number(o))===o?Number(o):o},cI=function(o,i,e,t){if(t&&!e)i[t]=Ds(o[1]);else for(var r=0;r<e.length;r+=1)o[r+1]!=null&&(i[e[r]]=Ds(o[r+1]))},dI=function(o,i,e){var t=o.name&&o.names;o.push&&!i[o.push]?i[o.push]=[]:t&&!i[o.name]&&(i[o.name]={});var r=o.push?{}:t?i[o.name]:i;cI(e.match(o.reg),r,o.names,o.name),o.push&&i[o.push].push(r)},f_=im(),lI=RegExp.prototype.test.bind(/^([a-z])=(.*)/);dr.parse=function(o){var i={},e=[],t=i;return o.split(/(\r\n|\r|\n)/).filter(lI).forEach(function(r){var s=r[0],n=r.slice(2);s==="m"&&(e.push({rtp:[],fmtp:[]}),t=e[e.length-1]);for(var a=0;a<(f_[s]||[]).length;a+=1){var c=f_[s][a];if(c.reg.test(n))return dI(c,t,n)}}),i.media=e,i};var __=function(o,i){var e=i.split(/=(.+)/,2);return e.length===2?o[e[0]]=Ds(e[1]):e.length===1&&i.length>1&&(o[e[0]]=void 0),o};dr.parseParams=function(o){return o.split(/;\s?/).reduce(__,{})};dr.parseFmtpConfig=dr.parseParams;dr.parsePayloads=function(o){return o.toString().split(" ").map(Number)};dr.parseRemoteCandidates=function(o){for(var i=[],e=o.split(" ").map(Ds),t=0;t<e.length;t+=3)i.push({component:e[t],ip:e[t+1],port:e[t+2]});return i};dr.parseImageAttributes=function(o){return o.split(" ").map(function(i){return i.substring(1,i.length-1).split(",").reduce(__,{})})};dr.parseSimulcastStreamList=function(o){return o.split(";").map(function(i){return i.split(",").map(function(e){var t,r=!1;return e[0]!=="~"?t=Ds(e):(t=Ds(e.substring(1,e.length)),r=!0),{scid:t,paused:r}})})}});var E_=Ui((JF,T_)=>{"use strict";var rm=im(),uI=/%[sdv%]/g,hI=function(o){var i=1,e=arguments,t=e.length;return o.replace(uI,function(r){if(i>=t)return r;var s=e[i];switch(i+=1,r){case"%%":return"%";case"%s":return String(s);case"%d":return Number(s);case"%v":return""}})},oa=function(o,i,e){var t=i.format instanceof Function?i.format(i.push?e:e[i.name]):i.format,r=[o+"="+t];if(i.names)for(var s=0;s<i.names.length;s+=1){var n=i.names[s];i.name?r.push(e[i.name][n]):r.push(e[i.names[s]])}else r.push(e[i.name]);return hI.apply(null,r)},mI=["v","o","s","i","u","e","p","c","b","t","r","z","a"],pI=["i","c","b","a"];T_.exports=function(o,i){i=i||{},o.version==null&&(o.version=0),o.name==null&&(o.name=" "),o.media.forEach(function(s){s.payloads==null&&(s.payloads="")});var e=i.outerOrder||mI,t=i.innerOrder||pI,r=[];return e.forEach(function(s){rm[s].forEach(function(n){n.name in o&&o[n.name]!=null?r.push(oa(s,n,o)):n.push in o&&o[n.push]!=null&&o[n.push].forEach(function(a){r.push(oa(s,n,a))})})}),o.media.forEach(function(s){r.push(oa("m",rm.m[0],s)),t.forEach(function(n){rm[n].forEach(function(a){a.name in s&&s[a.name]!=null?r.push(oa(n,a,s)):a.push in s&&s[a.push]!=null&&s[a.push].forEach(function(c){r.push(oa(n,a,c))})})})}),r.join(`\r
4
4
  `)+`\r
5
- `}});var Xh=Fi(lr=>{"use strict";var Co=n_(),dI=d_();lr.write=dI;lr.parse=Co.parse;lr.parseParams=Co.parseParams;lr.parseFmtpConfig=Co.parseFmtpConfig;lr.parsePayloads=Co.parsePayloads;lr.parseRemoteCandidates=Co.parseRemoteCandidates;lr.parseImageAttributes=Co.parseImageAttributes;lr.parseSimulcastStreamList=Co.parseSimulcastStreamList});import D4 from"webrtc-adapter";var Xf=Je(nt());var mm=(H=>(H[H.INVALID_PARAMETER=4096]="INVALID_PARAMETER",H[H.INVALID_OPERATION=4097]="INVALID_OPERATION",H[H.NOT_SUPPORTED=4098]="NOT_SUPPORTED",H[H.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",H[H.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",H[H.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",H[H.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",H[H.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",H[H.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",H[H.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",H[H.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",H[H.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",H[H.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",H[H.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",H[H.CLIENT_BANNED=16448]="CLIENT_BANNED",H[H.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",H[H.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",H[H.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",H[H.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",H[H.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",H[H.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",H[H.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",H[H.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",H[H.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",H[H.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",H[H.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",H[H.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",H[H.API_CALL_ABORTED=16461]="API_CALL_ABORTED",H[H.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",H[H.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",H[H.SWITCH_ROOM_FAILED=16464]="SWITCH_ROOM_FAILED",H[H.VIDEO_ENCODE_FAILED=16465]="VIDEO_ENCODE_FAILED",H[H.AUDIO_ENCODE_FAILED=16466]="AUDIO_ENCODE_FAILED",H[H.UNKNOWN=65535]="UNKNOWN",H))(mm||{}),I=mm;var og=function(o){for(let i in I)if(I[i]===o)return i;return"UNKNOWN"},Ps=class extends Error{constructor({name:e="RtcError",message:t,code:r=I.UNKNOWN,extraCode:s=0,constraint:n}){let a=`<${og(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=s,this.name=e,this.message=d,this.constraint=n,this.originMessage=t}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},v=Ps;var $c=0,pm=!0,da=function(o){$c=o;let i=new Date;i.setTime(i.getTime()+o),R[pm?"info":"debug"](`baseTime from server: ${i} offset: ${o}`),pm=!1},fm=function(){return $c},Hi=function(){return Date.now()+$c},ca=function(){let o=new Date;return o.setTime(Hi()),o.toLocaleString()},vo=function(o){let i=String(o.getMilliseconds());return"padStart"in String.prototype&&(i=i.toString().padStart(3,"0")),`${o.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")}:${i}`};var Nt={};Bi(Nt,{REPORT_TYPE:()=>$o,buildSSOPackage:()=>qi,bytes2ms:()=>bm,calculateScaleResolutionDownNumber:()=>Ho,concatArrayBuffers:()=>Oa,convertObjectNumberToInt:()=>Js,copyProperties:()=>ym,deepClone:()=>Gr,deepCloneBasic:()=>Ra,deepMerge:()=>ei,delay:()=>Ke,fibonacci:()=>qr,formatedTime:()=>xm,getConstructorName:()=>wo,getContainerFromElement:()=>Lm,getEnv:()=>Am,getFirst16Bits:()=>Um,getInternalVersion:()=>km,getLast16Bits:()=>ka,getLoggerUrl:()=>Ji,getMediaStreamTrackInfo:()=>Ma,getMuteStateFromFlag:()=>Kt,getNetworkType:()=>ya,getNumNetworkType:()=>Jr,getReconnectionTimeout:()=>Zt,getStringByteLength:()=>Gs,getTurnServer:()=>Pm,getUint32Version:()=>Na,getValueType:()=>Me,getViewListFromView:()=>Fo,glog:()=>pl,ipv4ToUint32:()=>Vo,isArray:()=>Ae,isAudioWorkletSupported:()=>Mm,isBoolean:()=>ue,isConstructor:()=>jr,isEmpty:()=>Uo,isFunction:()=>le,isLangChinese:()=>Yt,isMediaStreamTrack:()=>vm,isNumber:()=>Q,isObject:()=>yt,isOverseaSdkAppId:()=>Ut,isPlainObject:()=>dt,isPortrait:()=>fl,isPromise:()=>Tr,isRemoteTrack:()=>Dm,isRotate90Or270:()=>bt,isSetSinkIdSupported:()=>Om,isString:()=>ie,isUndefined:()=>T,loadImage:()=>Bo,loadVideo:()=>wm,ms2bytes:()=>Nm,ms2samples:()=>ml,normalizeUrl:()=>Da,performanceNow:()=>V,promiseAny:()=>Xr,samples2ms:()=>hl,setNetworkTypeFromWebRTC:()=>ba,stringify:()=>gt,stringifyIncludeValue:()=>Ws,throttlePromise:()=>va});var il={};Bi(il,{AUDIO_MUTE_BIT:()=>ga,AUDIO_STAT_BIT:()=>_r,AUX_STAT_BIT:()=>Br,AUX_STREAM_MSID:()=>zc,BACKEND_ENV:()=>_a,BASE_DOC_URL:()=>_t,BASE_HOST:()=>_m,CAPABILITIES_KEYS:()=>Sa,CLASS_NAME:()=>bg,CLOUD_CONSOLE_URL:()=>dg,CROSS_ROOM_BIT:()=>Xc,DATA_FREEZE_TIMING:()=>Ea,DOC_BILLING_CN:()=>la,DOC_BILLING_OVERSEA:()=>ua,DOC_URL:()=>cg,DTLS_STATE_UNKNOWN:()=>Qt,ENV_NAME:()=>$i,EXCHANGE_SDP_TIMEOUT:()=>el,IS_WORKER:()=>Do,IS_WORKLET:()=>xs,KIBANA_EVENT:()=>Ze,LOCAL_STREAM_PUBLISH_STATE:()=>Tm,LOGGER_CMD_TYPE:()=>mr,LOGGER_DOMAIN:()=>Gc,LOGGER_DOMAIN_OVERSEA:()=>Jc,LOG_LEVEL:()=>Xt,LOG_LEVEL_NAME:()=>vg,MAIN_STREAM_MSID:()=>Vs,MAX_RTT:()=>Hs,MICROPHONE_COMMUNICATIONS:()=>Ng,MICROPHONE_DEFAULT:()=>Wr,MUTE_ALL_BIT:()=>hg,NAME:()=>_,NETWORK_TYPE:()=>ha,NOT_SUPPORTED_H264:()=>Hr,PAUSED_RETRY_COUNT:()=>$r,PEERCONNECTION_CONNECTING_TIMEOUT:()=>Fs,PEER_CONNECTION_STATE:()=>Ce,PEER_LEAVE_REASON:()=>tl,RECOVER_CAPTURE_INTERVAL:()=>ko,REMOTE_STREAM_TYPE_AUX:()=>Yc,REMOTE_STREAM_TYPE_MAIN:()=>Qc,RENDER_FREEZE_TIMING:()=>Ag,SCHEDULE_DOMAIN:()=>Gi,SCHEDULE_TIMEOUT:()=>yg,SDP_SEMANTICS_PLAN_B:()=>Mo,SDP_SEMANTICS_UNIFIED_PLAN:()=>gr,SECOND_HOST:()=>ng,SIGNAL_PING_PONG_INTERVAL:()=>ug,SIGNAL_PING_TIMEOUT:()=>lg,SIGNAL_RECONNECTION_COUNT:()=>Sg,SMALL_STAT_BIT:()=>Us,SPEAKER_DEFAULT:()=>Bs,STORAGE_EXPIRES_TIME:()=>ma,STREAM_TYPE_BIG:()=>Cg,STREAM_TYPE_SMALL:()=>Rg,SUBSCRIBE_SMALL_RETRY_COUNT:()=>Oo,SYNC_USER_LIST_INTERVAL:()=>Ig,Scene:()=>Ii,THIRD_HOST:()=>ag,TRANSPORT_DIRECTION:()=>ne,TRTC_ERROR_ASSISTANCE:()=>qc,TRTC_QUALITY_BAD:()=>gg,TRTC_QUALITY_DISCONNECTED:()=>Eg,TRTC_QUALITY_EXCELLENT:()=>pg,TRTC_QUALITY_GOOD:()=>fg,TRTC_QUALITY_POOR:()=>_g,TRTC_QUALITY_UNKNOWN:()=>mg,TRTC_QUALITY_VERY_BAD:()=>Tg,UPDATE_OFFER_TIMEOUT:()=>Kc,VIDEO_MUTE_BIT:()=>Ta,VIDEO_STAT_BIT:()=>fr,audioProfileMap:()=>pa,defaultBigVideoProfile:()=>pr,defaultSmallVideoProfile:()=>jc,getRetryCount:()=>Wi,getScriptDir:()=>sg,innerVersion:()=>Ls,loggerProxy:()=>ws,screenProfileMap:()=>fa,setLoggerProxy:()=>Fr,setRetryCount:()=>Zc,setVersion:()=>Wc,version:()=>He,videoProfileMap:()=>zt});var Ls="4.15.00.1600",He="5.0.0";function Wc(o){He=o;let[i,e,t]=o.split(".").map(r=>parseInt(r,10));Ls=`${i}.${Math.min(15,e)}.${Math.min(15,t)}.${e.toString().padStart(2,"0")}${t.toString().padStart(2,"0")}`}var Do=typeof importScripts!="undefined",xs=typeof registerProcessor!="undefined",sg=()=>{let o=Do?self.location.href:document.currentScript.src;return o.substring(0,o.lastIndexOf("/")+1)},ws="",Fr=o=>ws=o,_m="web.sdk.qcloud.com",ng="web.sdk.tencent.cn",ag="web.sdk.cloud.tencent.cn",dg="https://console.cloud.tencent.com/trtc",_t=`https://${_m}/trtc/webrtc/doc`,cg=`${_t}/zh-cn/`,la="https://cloud.tencent.com/document/product/647/85386",ua="https://trtc.io/document/56025",Gc="https://yun.tim.qq.com",Jc="https://apisgp.my-imcloud.com",qc="trtc_error_assistance",mr={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"},Xt=(n=>(n[n.TRACE=0]="TRACE",n[n.DEBUG=1]="DEBUG",n[n.INFO=2]="INFO",n[n.WARN=3]="WARN",n[n.ERROR=4]="ERROR",n[n.NONE=5]="NONE",n))(Xt||{}),lg=18e3,ug=2e3,ha={unknown:0,wifi:1,"4g":2,"3g":3,"2g":4,wired:5,"5g":6},ma=7*24*3600*1e3,pa={standard:{sampleRate:48e3,channelCount:1,bitrate:40},"standard-stereo":{sampleRate:48e3,channelCount:2,bitrate:64},high:{sampleRate:48e3,channelCount:1,bitrate:128},"high-stereo":{sampleRate:48e3,channelCount:2,bitrate:192}},zt={"120p":{width:160,height:120,frameRate:15,bitrate:200},"120p_2":{width:160,height:120,frameRate:15,bitrate:100},"180p":{width:320,height:180,frameRate:15,bitrate:350},"180p_2":{width:320,height:180,frameRate:15,bitrate:150},"240p":{width:320,height:240,frameRate:15,bitrate:400},"240p_2":{width:320,height:240,frameRate:15,bitrate:200},"360p":{width:640,height:360,frameRate:15,bitrate:800},"360p_2":{width:640,height:360,frameRate:15,bitrate:400},"480p":{width:640,height:480,frameRate:15,bitrate:900},"480p_2":{width:640,height:480,frameRate:15,bitrate:500},"720p":{width:1280,height:720,frameRate:15,bitrate:1500},"1080p":{width:1920,height:1080,frameRate:15,bitrate:2e3},"1440p":{width:2560,height:1440,frameRate:30,bitrate:4860},"4K":{width:3840,height:2160,frameRate:30,bitrate:9e3}},pr=zt["480p_2"],jc=zt["120p_2"],fa={"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}},_={CANVAS:"canvas",AUDIO:"audio",VIDEO:"video",SCREEN:"screen",SMALL:"small",BIG:"big",AUXILIARY:"auxiliary",SMALL_VIDEO:"smallVideo",FACING_MODE_USER:"user",FACING_MODE_ENVIRONMENT:"environment",MUTE:"mute",UNMUTE:"unmute",ENDED:"ended",PLAYING:"playing",PAUSE:"pause",ERROR:"error",LOADEDDATA:"loadeddata",LOADEDMETADATA:"loadedmetadata",AUDIO_INPUT:"audioinput",VIDEO_INPUT:"videoinput",DETAIL:"detail",TEXT:"text",MAIN:"main",BACKUP:"backup",BANNED:"banned",KICK:"kick",USER_TIME_OUT:"user_time_out",ROOM_DISBAND:"room_disband",SEI_MESSAGE:"sei-message",ADD:"add",REMOVE:"remove",REPLACE:"replace",TRACK:"track",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",TRANSCEIVER_DIRECTION_SENDONLY:"sendonly",TRANSCEIVER_DIRECTION_RECVONLY:"recvonly",ENTER_PICTURE_IN_PICTURE:"enterpictureinpicture",LEAVE_PICTURE_IN_PICTURE:"leavepictureinpicture",RESIZE:"resize",TIME_UPDATE:"timeupdate"},ne={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},_a={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},Ii=(e=>(e.LIVE="live",e.RTC="rtc",e))(Ii||{}),fr=1,Us=2,Br=4,_r=8,ga=64,Ta=16,hg=112,Xc=128,Vs="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",zc="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",Qc=_.MAIN,Yc=_.AUXILIARY,mg=0,pg=1,fg=2,_g=3,gg=4,Tg=5,Eg=6,Qt="unknown",Ce={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},gm=1/0;function Zc(o){gm=o}function Wi(){return gm}var Sg=30,Ze={JOIN:"join",DELTA_JOIN:"delta-join",REJOIN:"rejoin",LEAVE:"leave",DELTA_LEAVE:"delta-leave",PUBLISH:"publish",DELTA_PUBLISH:"delta-publish",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",UPLINK_CONNECTION:"uplink-connection",UPLINK_RECONNECTION:"uplink-reconnection",DOWNLINK_CONNECTION:"downlink-connection",DOWNLINK_RECONNECTION:"downlink-reconnection",ON_TRACK:"ontrack",ICE_CONNECTION_STATE:"iceConnectionState",LOCAL_STREAM_INITIALIZE:"stream-initialize",SIGNAL_CONNECTION:"websocketConnectionState",SIGNAL_RECONNECTION:"websocketReconnectionState",UPDATE_STREAM:"update-stream",RECOVER_LOCAL_AUDIO_TRACK:"recover-local-audio-track",RECOVER_LOCAL_VIDEO_TRACK:"recover-local-video-track",RECOVER_SUBSCRIPTION:"recover-subscription",START_MIX_TRANSCODE:"start-mix-transcode",STOP_MIX_TRANSCODE:"stop-mix-transcode",PLAYER_ERROR:"player-error",SCHEDULE:"schedule",LOAD_WORKLET:"load-worklet",VIDEO_FROZEN_COUNT:"videoFrozenCount",GET_USER_MEDIA_RETRY:"getUserMedia-retry",VIDEO_ENCODE_FAILED_DURING_CALL:"video-encode-failed-during-call",AUDIO_ENCODE_FAILED_DURING_CALL:"audio-encode-failed-during-call"},Ig=1e4,Kc=1e4,el=1e4,gr="unified-plan",Mo="plan-b",Hr=1028,Tm=(t=>(t[t.UNPUBLISH=-1]="UNPUBLISH",t[t.PUBLISHING=0]="PUBLISHING",t[t.PUBLISHED=1]="PUBLISHED",t))(Tm||{}),Ea=500,Ag=1e3,Cg=_.BIG,Rg=_.SMALL,Fs=10*1e3,Gi={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"},yg=2e3,bg={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},$r=5,Wr="default",Bs=Wr,Ng="communications",vg=Object.keys(Xt),tl=["normal leave","timeout leave","kick","role change"],Oo=10,ko=2e3,Sa=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],Hs=10*1e3;var Dg=function(o,i,e,t){function r(s){return s instanceof e?s:new e(function(n){n(s)})}return new(e||(e=Promise))(function(s,n){function a(u){try{l(t.next(u))}catch(h){n(h)}}function d(u){try{l(t.throw(u))}catch(h){n(h)}}function l(u){u.done?s(u.value):r(u.value).then(a,d)}l((t=t.apply(o,i||[])).next())})},rl=Symbol(32),ol=Symbol(16),sl=Symbol(8),Ai=class{constructor(i){this.g=i,this.consumed=0,i&&(this.need=i.next().value)}setG(i){this.g=i,this.demand(i.next().value,!0)}consume(){this.buffer&&this.consumed&&(this.buffer.copyWithin(0,this.consumed),this.buffer=this.buffer.subarray(0,this.buffer.length-this.consumed),this.consumed=0)}demand(i,e){return e&&this.consume(),this.need=i,this.flush()}read(i){return Dg(this,void 0,void 0,function*(){return this.lastReadPromise&&(yield this.lastReadPromise),this.lastReadPromise=new Promise((e,t)=>{var r;this.reject=t,this.resolve=n=>{delete this.lastReadPromise,delete this.resolve,delete this.need,e(n)},this.demand(i,!0)||(r=this.pull)===null||r===void 0||r.call(this,i)})})}readU32(){return this.read(rl)}readU16(){return this.read(ol)}readU8(){return this.read(sl)}close(){var i;this.g&&this.g.return(),this.buffer&&this.buffer.subarray(0,0),(i=this.reject)===null||i===void 0||i.call(this,new Error("EOF")),delete this.lastReadPromise}flush(){if(!this.buffer||!this.need)return;let i=null,e=this.buffer.subarray(this.consumed),t=0,r=s=>e.length<(t=s);if(typeof this.need=="number"){if(r(this.need))return;i=e.subarray(0,t)}else if(this.need===rl){if(r(4))return;i=e[0]<<24|e[1]<<16|e[2]<<8|e[3]}else if(this.need===ol){if(r(2))return;i=e[0]<<8|e[1]}else if(this.need===sl){if(r(1))return;i=e[0]}else if("buffer"in this.need){if("byteOffset"in this.need){if(r(this.need.byteLength-this.need.byteOffset))return;new Uint8Array(this.need.buffer,this.need.byteOffset).set(e.subarray(0,t)),i=this.need}else if(this.g){this.g.throw(new Error("Unsupported type"));return}}else{if(r(this.need.byteLength))return;new Uint8Array(this.need).set(e.subarray(0,t)),i=this.need}return this.consumed+=t,this.g?this.demand(this.g.next(i).value,!0):this.resolve&&this.resolve(i),i}write(i){if(i instanceof Uint8Array?this.malloc(i.length).set(i):"buffer"in i?this.malloc(i.byteLength).set(new Uint8Array(i.buffer,i.byteOffset,i.byteLength)):this.malloc(i.byteLength).set(new Uint8Array(i)),this.g||this.resolve)this.flush();else return new Promise(e=>this.pull=e)}writeU32(i){this.malloc(4).set([i>>24&255,i>>16&255,i>>8&255,i&255]),this.flush()}writeU16(i){this.malloc(2).set([i>>8&255,i&255]),this.flush()}writeU8(i){this.malloc(1)[0]=i,this.flush()}malloc(i){if(this.buffer){let e=this.buffer.length,t=e+i;if(t<=this.buffer.buffer.byteLength-this.buffer.byteOffset)this.buffer=new Uint8Array(this.buffer.buffer,this.buffer.byteOffset,t);else{let r=new Uint8Array(t);r.set(this.buffer),this.buffer=r}return this.buffer.subarray(e,t)}else return this.buffer=new Uint8Array(i),this.buffer}};Ai.U32=rl;Ai.U16=ol;Ai.U8=sl;var Mg=128,Og=127,BI=~Og,HI=Math.pow(2,31);function nl(o){let i=new Ai;for(;o>=128;)i.malloc(1)[0]=o&255|Mg,o>>>=7;return i.malloc(1)[0]=o&255,i.buffer||new Uint8Array(0)}function Ia(o,i=0){let e=new Ai,t=i<<3;switch(typeof o){case"boolean":let r=e.malloc(2);r[0]=t,r[1]=o?1:0;break;case"number":e.malloc(1)[0]=t,e.write(nl(o));break;case"string":e.malloc(1)[0]=t|2;let s=new TextEncoder().encode(o);e.write(nl(s.length));let n=e.malloc(s.length);for(let d=0;d<s.length;d++)n[d]=s[d];break;case"object":let a=new Ai;if(Array.isArray(o))for(let d=0;d<o.length;d++){let l=Ia(o[d],d+1);l&&a.write(l)}else{let d=1;for(let l in o){let u=Ia(o[l],d++);u&&a.write(u)}}i===0?a.buffer&&e.write(a.buffer):(e.malloc(1)[0]=t|2,a.buffer&&(e.write(nl(a.buffer.length)),e.write(a.buffer)))}return e.buffer||new Uint8Array(0)}var $s=class{constructor(){c(this,"buffer");this.buffer=[]}get data(){return this.buffer}get length(){return this.buffer.length}writeInt32(i){this.buffer.push(i>>>24&255),this.buffer.push(i>>>16&255),this.buffer.push(i>>>8&255),this.buffer.push(i&255)}writeInt16(i){this.buffer.push(i>>>8&255),this.buffer.push(i&255)}writeByte(i){this.buffer.push(i&255)}writeBytes(i){for(let e=0;e<i.length;e++)this.buffer.push(i[e])}};function al(o,i,e){o[e]=i>>>24&255,o[e+1]=i>>>16&255,o[e+2]=i>>>8&255,o[e+3]=i&255}function at(o,i){return o[i]<<24|o[i+1]<<16|o[i+2]<<8|o[i+3]}function dl(o,i){return o[i]}function Po(o,i,e){return new TextDecoder().decode(kg(o,i,e))}function kg(o,i,e){return o.slice(i,i+e)}var cl=0,Aa=2654435769,Ca=16,ul=4,Lo=2,xo=7;function Pg(o,i,e,t="AVQualityReportSvc.C2S",r=2e3,s=2,n=30){return{version:r,encryption:s,d2:"",d2Len:0,uinType:n,uin:"",uinLen:0,reqHead:{seqNumber:e,appId:o,appidAtThird:new Uint8Array(0),a2:"",a2Len:0,serviceCmd:t,serviceCmdLen:0,cookie:"",cookieLen:0,imei:"",imeiLen:0,ksid:"",ksidLen:0,clientVersionInfo:"",clientVersionInfoLen:0},busiBuff:i}}function Em(o,i){let e=new $s,t=Pg(i,o,cl);cl=cl+1&2147483647,e.writeInt32(0),e.writeInt32(t.version),e.writeByte(t.encryption);let r=new TextEncoder().encode(t.d2);e.writeInt32(r.length+4),r&&e.writeBytes(r),e.writeByte(t.uinType);let s=new TextEncoder().encode(t.uin);e.writeInt32(s.length+4),s.length&&e.writeBytes(s);let n=new $s;n.writeInt32(0),n.writeInt32(t.reqHead.seqNumber),n.writeInt32(t.reqHead.appId),n.writeByte(t.reqHead.appId>>>24&255),n.writeByte(t.reqHead.appId>>>16&255),n.writeByte(t.reqHead.appId>>>8&255),n.writeByte(t.reqHead.appId&255);for(let re=4;re<16;re++)n.writeByte(0);let a=new TextEncoder().encode(t.reqHead.a2);n.writeInt32(a.length+4),a.length&&n.writeBytes(a);let d=new TextEncoder().encode(t.reqHead.serviceCmd);n.writeInt32(d.length+4),d.length&&n.writeBytes(d);let l=new TextEncoder().encode(t.reqHead.cookie);n.writeInt32(l.length+4),l.length&&n.writeBytes(l);let u=new TextEncoder().encode(t.reqHead.imei);n.writeInt32(u.length+4),u.length&&n.writeBytes(u);let h=new TextEncoder().encode(t.reqHead.ksid);n.writeInt32(h.length+4),h.length&&n.writeBytes(h);let p=new TextEncoder().encode(t.reqHead.clientVersionInfo);n.writeInt16(p.length+2),p.length&&n.writeBytes(p);let m=n.length;n.data[0]=m>>>24&255,n.data[1]=m>>>16&255,n.data[2]=m>>>8&255,n.data[3]=m&255,ie(o)&&(o=new TextEncoder().encode(o)),n.writeInt32(o.length+4),o.length&&n.writeBytes(o);let g=new Uint8Array(n.data),E=null;t.encryption===1?E=new TextEncoder().encode(t.uin):t.encryption===2&&(E=new Uint8Array(16)),E&&(g=Lg(g,E)),e.writeBytes(g);let C=new Uint8Array(e.data),P=C.length;return C[0]=P>>>24&255,C[1]=P>>>16&255,C[2]=P>>>8&255,C[3]=P&255,C}function Lg(o,i){let e=o.length,r=(e+1+Lo+xo)%8;r&&(r=8-r);let s=e+1+Lo+xo+r,n=new Uint8Array(s),a=0,d=new Uint8Array(8),l=new Uint8Array(8),u=new Uint8Array(8),h=0;d[0]=Math.floor(Math.random()*256)&248|r,h=1;for(let m=0;m<r;m++)d[h]=Math.floor(Math.random()*256)&255,h+=1;for(let m=0;m<Lo;)if(h<8&&(d[h]=Math.floor(Math.random()*256)&255,h+=1,m+=1),h===8){ll(d,i,l,u,n,a),a+=8,h=0;for(let g=0;g<8;g++)u[g]=n[a-8+g]}let p=0;for(;p<e;)if(h<8&&(d[h]=o[p],h+=1,p+=1),h===8){ll(d,i,l,u,n,a),a+=8,h=0;for(let m=0;m<8;m++)u[m]=n[a-8+m]}for(let m=0;m<xo;)if(h<8&&(d[h]=0,h+=1,m+=1),h===8){ll(d,i,l,u,n,a),a+=8,h=0;for(let g=0;g<8;g++)u[g]=n[a-8+g]}return n}function ll(o,i,e,t,r,s){for(let n=0;n<8;n++)o[n]^=t[n];xg(o,i,r,s);for(let n=0;n<8;n++)r[s+n]^=e[n];for(let n=0;n<8;n++)e[n]=o[n]}function xg(o,i,e,t){let r=at(o,0),s=at(o,4),n=[];for(let d=0;d<4;d++)n[d]=at(i,d*4);let a=0;for(let d=0;d<Ca;d++)a+=Aa,a=a>>>0,r+=(s<<4)+n[0]^s+a^(s>>>5)+n[1],r=r>>>0,s+=(r<<4)+n[2]^r+a^(r>>>5)+n[3],s=s>>>0;al(e,r,t),al(e,s,t+4)}var Am=function(){return new URLSearchParams(location.search).get("trtc_env")||""},Ut=o=>Number(o)<14e8,Ji=function(o,i){let e;ws?e=ws:e=Ut(o)?Jc:Gc;let t=Math.floor(Math.random()*hr(2,31));return`${e}/v5/AVQualityReportSvc/C2S?random=${t}&sdkappid=${o}&cmdtype=${i}`},Cm="unknown";function ya(){Ug();let{userAgent:o,connection:i}=navigator,e=(o.match(/NetType\/\S+/)||[])[0]||"";e=e.toLowerCase().replace("nettype/",""),e==="3gnet"&&(e="3g");let t=i&&i.type&&i.type.toLowerCase(),r=i&&i.effectiveType&&i.effectiveType.toLowerCase();return r==="slow-2"&&(r="2g"),t?Rm(t,r):Cm}function wg(){R.warn("netType changed",ya())}var Sm=!1;function Ug(){var o;Sm||(Sm=!0,(o=navigator.connection)==null||o.addEventListener("typechange",wg))}function Rm(o,i){if(ha[o])return o;switch(o){case"cellular":case"wimax":return i||"unknown";case"ethernet":return"wired";case"none":case"other":default:return"unknown"}}function ba(o){Cm=Rm(o)}function Jr(){return ha[ya()]}function ym(o,i){for(let e of Reflect.ownKeys(i))if(e!=="constructor"&&e!=="prototype"&&e!=="name"){let t=Object.getOwnPropertyDescriptor(i,e)||"";Object.defineProperty(o,e,t)}return o}function bm(o,i=48e3){return hl(o/4,i)}function hl(o,i=48e3){return o*1e3/i}function Nm(o,i=48e3){return ml(o,i)*4}function ml(o,i=48e3){return o*i/1e3}var pl=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},Yt=()=>{let o=navigator.language;return o=o.substring(0,2),o==="zh"},dt=function(o){if(!o||typeof o!="object"||Object.prototype.toString.call(o)!="[object Object]")return!1;let i=Object.getPrototypeOf(o);if(i===null)return!0;let e=Object.prototype.hasOwnProperty.call(i,"constructor")&&i.constructor;return typeof e=="function"&&e instanceof e&&Function.prototype.toString.call(e)===Function.prototype.toString.call(Object)};function qr(o,i=1,e=1){return o<=1?e:qr(o-1,e,i+e)}function Zt(o){return o>8?30*1e3:qr(o)*1e3}function Me(o){return Reflect.apply(Object.prototype.toString,o,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var le=o=>typeof o=="function",T=o=>typeof o=="undefined",ie=o=>typeof o=="string",Q=o=>typeof o=="number",ue=o=>typeof o=="boolean",yt=o=>Me(o)==="object",Ae=o=>Me(o)==="array",vm=o=>Me(o)==="MediaStreamTrack".toLowerCase(),Dm=o=>o.isRemote,Tr=o=>Me(o)==="promise",jr=o=>le(o)&&o.prototype.constructor===o,wo=o=>jr(o)?o.prototype.constructor.name:"",Mm=typeof AudioWorkletNode!="undefined",Om=typeof HTMLMediaElement!="undefined"&&"setSinkId"in HTMLMediaElement.prototype;function Xr(o){return new Promise((i,e)=>{let t=[];o.forEach(r=>{r.then(i).catch(s=>{t.push(s),t.length===o.length&&e(t)})})})}function V(){return!performance||!performance.now?Date.now():Math.floor(performance.now())}var Im=o=>+o<10?`0${o}`:o,km=o=>{let i=o.match(/^\d+\.\d+\.\d+/)[0];if(!i)return o;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}`},Vg=Object.prototype.hasOwnProperty,{toString:eA}=Object.prototype;function Uo(o){if(o==null)return!0;if(typeof o=="boolean")return!1;if(typeof o=="number")return o===0;if(typeof o=="string"||typeof o=="function"||Array.isArray(o))return o.length===0;if(o instanceof Error)return o.message==="";if(dt(o))switch(Object.prototype.toString.call(o)){case"[object File]":case"[object Map]":case"[object Set]":return o.size===0;case"[object Object]":{for(let i in o)if(Vg.call(o,i))return!1;return!0}}return!1}function Kt(o,i){return{userId:i,hasAudio:!!(o&_r),hasVideo:!!(o&fr),hasAuxiliary:!!(o&Br),hasSmall:!!(o&Us),audioMuted:!!(o&ga),videoMuted:!!(o&Ta),audioAvailable:!!(o&_r)&&!(o&ga),videoAvailable:!!(o&fr)&&!(o&Ta)}}function Pm(o){let i={urls:o.url.startsWith("turn:")||o.url.startsWith("turns:")?o.url:`turn:${o.url}`};return!T(o.username)&&!T(o.credential)&&(i.username=o.username,i.credential=o.credential,i.credentialType="password",T(o.credentialType)||(i.credentialType=o.credentialType)),i}function Vo(o,i=!0){if(!ie(o))return 0;let e=o.split(".");return i?(Number(e[0])<<24|Number(e[1])<<16|Number(e[2])<<8|Number(e[3]))>>>0:(Number(e[3])<<24|Number(e[2])<<16|Number(e[1])<<8|Number(e[0]))>>>0}var ei=function(o,i,e,t){if(!(yt(o)&&yt(i)))return 0;let r=0,s=Object.keys(i),n;for(let a=0,d=s.length;a<d;a++)if(n=s[a],!(T(i[n])||e&&e.includes(n)))if(yt(o[n])&&yt(i[n]))r+=ei(o[n],i[n],e,t);else{if(t&&t.includes(i[n]))continue;o[n]!==i[n]&&(o[n]=Gr(i[n]),r+=1)}return r};function Gr(o){if(Ae(o)){let i=[];return o.forEach((e,t)=>{i[t]=Gr(e)}),i}if(yt(o)){let i={};return Object.keys(o).forEach(e=>{i[e]=Gr(o[e])}),i}return o}var Fo=o=>{let i=[];if(Ae(o))i=[...o];else if(ie(o)){let e=document.getElementById(o);e&&i.push(e)}else o&&i.push(o);return i},Lm=o=>ie(o)?document.getElementById(o):o,Fg=o=>{let i=d=>d<10?`0${d}`:`${d}`,e=o.getFullYear(),t=o.getMonth()+1,r=o.getDate(),s=i(o.getHours()),n=i(o.getMinutes()),a=i(o.getSeconds());return`${e}/${t}/${r} ${s}:${n}:${a}`},xm=()=>Fg(new Date);function gt(o,{keysToInclude:i,keysToExclude:e}){try{if(Ae(o))return`[${o.map(n=>gt(n,{keysToInclude:i,keysToExclude:e})).join(",")}]`;if(!dt(o)||!Ae(i)&&!Ae(e))return JSON.stringify(o);let t={},r=new Set(i),s=new Set(e);return Object.keys(o).forEach(n=>{(s.size===0&&r.has(n)||r.size===0&&!s.has(n))&&(t[n]=dt(o[n])||Ae(o[n])?JSON.parse(gt(o[n],{keysToExclude:e,keysToInclude:i})):o[n])}),JSON.stringify(t)}catch(t){return"{}"}}function Ws(o,i=!1){let e=[];return Object.keys(o).forEach(t=>{i===o[t]&&e.push(t)}),gt(o,{keysToInclude:e})}function Gs(o){return o.replace(/[\u4e00-\u9fa5]/g,"aa").length}var fl=()=>{var o,i,e,t;return(o=window.screen)!=null&&o.orientation?!!((t=(e=(i=window.screen)==null?void 0:i.orientation)==null?void 0:e.type)!=null&&t.includes("portrait")):window.orientation===0||window.orientation===180},Bo=o=>f(void 0,null,function*(){return new Promise((i,e)=>{let t;if(ie(o))t=new Image,t.crossOrigin="anonymous",t.src=o;else if(t=o,t.complete){i(t);return}t.onload=()=>i(t),t.onerror=()=>{e(new v({code:I.INVALID_PARAMETER,message:`load image failed, url: ${o}`}))}})}),Na=o=>{let i=o.split(".");return+i[0]<<24|+i[1]<<16|+i[2]<<8|+i[3]<<0},Js=o=>(Object.keys(o).forEach(i=>{Q(o[i])&&(i.startsWith("uint")||i.startsWith("int"))?o[i]=Math.floor(o[i]):(dt(o[i])||Ae(o[i]))&&Js(o[i])}),o);function Ke(o,i){return new Promise(e=>{let t=setTimeout(e,o);i&&i(t)})}function va(o,i){let e=null;return function(...t){return e||(e=o.apply(i||this,t),e.finally(()=>e=null),e)}}function Da(o){return o.replace(/(^|[^:])\/{2,}/g,"$1/")}function Ma(o){var i;try{let{width:e,height:t,frameRate:r,sampleRate:s,sampleSize:n,channelCount:a}=(i=o.getSettings)==null?void 0:i.call(o),d=o.kind===_.AUDIO?`${s}x${n}@${a}`:`${e}x${t}@${r}`,l=o.stats?` stats: ${JSON.stringify(o.stats).replaceAll('"',"")}`:"";return`${o.id} ${o.readyState} muted:${o.muted} ${o.kind} ${o.label} ${d}${l}`}catch(e){return""}}function Ho(o,i){return o.width*o.height===i.width*i.height?1:fl()&&i.width>i.height&&o.height>i.width?Math.max(o.width/i.height,o.height/i.width,1):Math.max(o.width/i.width,o.height/i.height,1)}function bt(o){return o===90||o===270}function wm(o){return f(this,null,function*(){return new Promise((i,e)=>{let t=document.createElement("video");t.crossOrigin="anonymous",t.src=o,t.muted=!0,t.loop=!0,t.playsInline=!0,t.play().then(()=>i(t)),t.onerror=()=>{e(t.error)}})})}function Ra(o,i=new WeakMap){if(typeof o!="object"||o===null)return o;if(i.has(o))return i.get(o);if(Array.isArray(o)){let e=[];return i.set(o,e),o.forEach((t,r)=>{e[r]=Ra(t,i)}),e}if(Object.prototype.toString.call(o)==="[object Object]"){let e={};return i.set(o,e),Reflect.ownKeys(o).forEach(t=>{e[t]=Ra(o[t],i)}),e}return o}var $o=(t=>(t[t.END_REPORT=2001]="END_REPORT",t[t.LOG=2002]="LOG",t[t.KEY_METRIC_REPORT=2003]="KEY_METRIC_REPORT",t))($o||{});function Bg(o,i,e,t){let r={data:o,random:Math.floor(Math.random()*2147483648),sdkAppId:e};return T(t)||(r=w(M({},r),{gzip:+t})),{uint32_sdkappid:0,uint64_from_uin:0,uint32_timestamp:0,uint32_seq:0,msg_common_info:{msg_device_info:{enum_device_type:0,str_device_brand:"",str_device_model:"",str_device_board:"",str_device_cpu_abi:""},msg_system_info:{enum_os_type:0,str_os_version:"",msg_network_info:0},msg_network_info:{enum_network_type:0}},msg_report_content:{uint32_type:i,bytes_report_data:JSON.stringify(r)}}}function qi(o,i,e,t){try{let r=Bg(o,i,e,t),s=Ia(r);return Em(s,e)}catch(r){return JSON.stringify(o)}}function Oa(o,i){let e=new Uint8Array(o.byteLength+i.byteLength);return e.set(new Uint8Array(o),0),e.set(new Uint8Array(i),o.byteLength),e.buffer}function ka(o){return(o&65535)>>>0}function Um(o){return(o&4294901760)>>>0}function Vm(o){let i=Hg(o);return i==null?void 0:i.busiBuff}function Hg(o){try{let i={},e=0;i.totalLength=at(o,e),e+=4,i.version=at(o,e),e+=4,i.encryption=dl(o,e),e+=1,i.uinType=dl(o,e),e+=1,i.uinLength=at(o,e),e+=4,i.uin=i.uinLength>4?Po(o,e,i.uinLength-4):"",e+=i.uinLength-4;let t=o.slice(e);if(i.encryption===2){let r=new Uint8Array(16).fill(0);o=$g(t,r),i.decrypted=!0,e=0}else o=t,e=0;return i.rspHeadLength=at(o,e),e+=4,i.seqNo=at(o,e),e+=4,i.retCode=at(o,e),e+=4,i.retStrLength=at(o,e),e+=4,i.retStr=i.retStrLength?Po(o,e,i.retStrLength-4):"",e+=i.retStrLength-4,i.serviceCmdLength=at(o,e),e+=4,i.serviceCmd=i.serviceCmdLength?Po(o,e,i.serviceCmdLength-4):"",e+=i.serviceCmdLength-4,i.cookieLength=at(o,e),e+=4,i.cookie=i.cookieLength?Po(o,e,i.cookieLength-4):"",e+=i.cookieLength-4,i.flag=at(o,e),e+=4,i.busiBuffLength=at(o,e),e+=4,i.busiBuff=i.busiBuffLength?Po(o,e,i.busiBuffLength-4):"",e+=i.busiBuffLength-4,i}catch(i){}}function Fm(o,i){let e=o[0]<<24|o[1]<<16|o[2]<<8|o[3],t=o[4]<<24|o[5]<<16|o[6]<<8|o[7];e=e>>>0,t=t>>>0;let r=Aa*Ca>>>0;for(let s=0;s<Ca;s++)t-=(e<<ul)+i[2]^e+r^(e>>>5)+i[3],t=t>>>0,e-=(t<<ul)+i[0]^t+r^(t>>>5)+i[1],e=e>>>0,r-=Aa,r=r>>>0;return new Uint8Array([e>>>24&255,e>>>16&255,e>>>8&255,e&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255])}function $g(o,i){let e=0,t=new Uint8Array(8).fill(0),r=new Uint8Array(o.slice(0,8)),s=Fm(r,i),n=s[0]&7,a=o.length-1-n-Lo-xo,d=new Uint8Array(a),l=0,u=t,h=o.slice(0,8);e=8;let p=1;p+=n;for(let g=1;g<=Lo;)if(p<8)p++,g++;else if(p===8){let E=_l(o,e,u,h,s,i);u=E.ivPreCrypt,h=E.ivCurCrypt,s=E.debiBuf,e=E.bufPos,p=0}let m=a;for(;m>0;)if(p<8)d[l++]=s[p]^u[p],p++,m--;else if(p===8){let g=_l(o,e,u,h,s,i);u=g.ivPreCrypt,h=g.ivCurCrypt,s=g.debiBuf,e=g.bufPos,p=0}for(let g=1;g<=xo;)if(p<8)s[p]^u[p],p++,g++;else if(p===8){if(e>=o.length)break;let E=_l(o,e,u,h,s,i);if(!E.success)break;u=E.ivPreCrypt,h=E.ivCurCrypt,s=E.debiBuf,e=E.bufPos,p=0}return d}function _l(o,i,e,t,r,s){if(i+8>o.length)return{success:!1};let n=new Uint8Array(t),a=o.slice(i,i+8),d=new Uint8Array(8);for(let u=0;u<8;u++)d[u]=r[u]^a[u];let l=Fm(d,s);return{success:!0,ivPreCrypt:n,ivCurCrypt:a,debiBuf:l,bufPos:i+8}}var Bm=typeof TextDecoder!="undefined"?new TextDecoder:void 0;function ji({url:o,body:i,method:e="POST",timeout:t,priority:r}){return new Promise((s,n)=>{if("fetch"in window)return fetch(o,{method:e,body:i,priority:r}).then(d=>d.clone().json().then(l=>({data:l}),()=>d.arrayBuffer().then(l=>({data:Vm(new Uint8Array(l))||(Bm?Bm.decode(l):l)})))).then(s,n);let a=new XMLHttpRequest;a.onreadystatechange=()=>{if(a.readyState===4)if(a.status>=200&&a.status<300)try{let d=JSON.parse(a.response);s({data:d})}catch(d){s({data:a.response})}else n({status:a.status,statusText:a.statusText||"request failed!"})},a.timeout=t||5e3,a.open(e,o,!0),a.send(i)})}function gl(o){return f(this,null,function*(){let i=V(),e=JSON.stringify(o);try{if(!CompressionStream||e.length<=2800)return e;let r=new Blob([e],{type:"application/json"}).stream().pipeThrough(new CompressionStream("gzip")),a=yield(yield(yield new Response(r)).blob()).arrayBuffer();return R.debug(`compressJSON ${e.length} -> ${a.byteLength} ${V()-i}ms`),a}catch(t){return e}})}var Wg=Object.prototype.hasOwnProperty;var Ci=o=>typeof o=="function",Tt=o=>typeof o=="undefined";var Pa=o=>typeof o=="boolean";var La=o=>o.isRemote;var Tl=function(o){if(!o||typeof o!="object"||Object.prototype.toString.call(o)!="[object Object]")return!1;let i=Object.getPrototypeOf(o);if(i===null)return!0;let e=Object.prototype.hasOwnProperty.call(i,"constructor")&&i.constructor;return typeof e=="function"&&e instanceof e&&Function.prototype.toString.call(e)===Function.prototype.toString.call(Object)};function Hm(o){if(o==null)return!0;if(typeof o=="boolean")return!1;if(typeof o=="number")return o===0;if(typeof o=="string"||typeof o=="function"||Array.isArray(o))return o.length===0;if(o instanceof Error)return o.message==="";if(Tl(o))switch(Object.prototype.toString.call(o)){case"[object File]":case"[object Map]":case"[object Set]":return o.size===0;case"[object Object]":{for(let i in o)if(Wg.call(o,i))return!1;return!0}}return!1}var Gg=0,Jg=1,$m=2;function qg({retryFunction:o,settings:i,onError:e,onRetrying:t,onRetryFailed:r,onRetrySuccess:s,context:n}){return function(...a){let{retries:d=5,timeout:l=1e3}=i,u=0,h=-1,p=Gg,m=(g,E)=>f(this,null,function*(){let C=n||this;try{let P=yield o.apply(C,a);u>0&&s&&s.call(this,u),u=0,g(P)}catch(P){let re=()=>{clearTimeout(h),u=0,p=$m,E(P)},L=()=>{p!==$m&&u<(Ci(d)?d():d)?(u++,p=Jg,Ci(t)&&t.call(this,u,re),h=window.setTimeout(()=>{h=-1,m(g,E)},Ci(l)?l(u):l)):(re(),Ci(r)&&r.call(this,P))};Ci(e)?e.call(this,{error:P,retry:L,reject:E,retryFuncArgs:a,retriedCount:u}):L()}});return new Promise(m)}}var Ri=qg;var Er=class o{constructor(i){c(this,"_parentPath");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=Pa(i.isLocal)?i.isLocal:!0,this.type=this.isLocal?"":i.type}getFullId(){return this._parentPath&&this.id?`${this._parentPath}-${this.id}`:this._parentPath?this._parentPath:this.id}createChild(i){let e=new o({id:i.id,userId:Tt(i.userId)?this.userId:i.userId,sdkAppId:Tt(i.sdkAppId)?this.sdkAppId:i.sdkAppId,type:Tt(i.type)?this.type:i.type,isLocal:Tt(i.isLocal)?this.isLocal:i.isLocal,remoteUserId:Tt(i.remoteUserId)?this.remoteUserId:i.remoteUserId});return e.bindParent(this),e}bindParent(i){let e=i.getFullId();this._parentPath!==e&&(this.debug(`bind logger parent: ${i.id}`),this._parentPath=e,this.userId=i.userId||this.userId,this.sdkAppId=i.sdkAppId||this.sdkAppId)}setUserId(i){this.userId=i}setSdkAppId(i){this.sdkAppId=i}log(i,e){let t=this.isLocal?this.userId:this.remoteUserId,r=this.getFullId();e.unshift(`[${this.isLocal?"\u2191":"\u2193"}${this.type&&this.type!=="main"?"*":""}${r}${t?`|${t}`:""}]`),R.log(i,e,Tt(this.userId)||Hm(this.userId),this.userId,this.sdkAppId)}info(...i){this.log(2,i)}debug(...i){this.log(1,i)}warn(...i){this.log(3,i)}error(...i){this.log(4,i)}};var Ko={};Bi(Ko,{ANDROID_VERSION:()=>wa,CHROME_MAJOR_VERSION:()=>$e,CHROME_VERSION:()=>Ka,EDGE_VERSION:()=>Va,EDG_MAJOR_VERSION:()=>Sl,EDG_VERSION:()=>Fa,ELECTRON_MAJOR_VERSION:()=>yl,FIREFOX_MAJOR_VERSION:()=>Jo,FIREFOX_VERSION:()=>Ua,HUAWEI_VERSION:()=>za,IE_VERSION:()=>Yg,IOS_MAIN_VERSION:()=>et,IOS_VERSION:()=>ht,IPADQQB_VERSION:()=>ja,IS_ANDROID:()=>_e,IS_ANDROID_WEBVIEW:()=>tT,IS_ANY_SAFARI:()=>Ft,IS_CHROME:()=>Zo,IS_CHROME_OS:()=>Il,IS_CHROMIUM_BASE:()=>Ve,IS_DESKTOP_IOS_CHROME:()=>Dl,IS_EDG:()=>qo,IS_EDGE:()=>zr,IS_ELECTRON:()=>Kg,IS_FIREFOX:()=>ee,IS_HEADLESS_CHROME:()=>Rl,IS_HONOR:()=>Cl,IS_HUAWEI:()=>tn,IS_HUAWEIBROWSER:()=>en,IS_IE:()=>qm,IS_IE8:()=>Qg,IS_IOS:()=>ge,IS_IOS_13_OR_14:()=>vl,IS_IOS_15_1:()=>Nl,IS_IOS_CHROME:()=>qs,IS_IPAD:()=>Go,IS_IPADQQB:()=>Ys,IS_IPAD_PRO:()=>El,IS_IPHONE:()=>Sr,IS_IPOD:()=>Jm,IS_LINUX:()=>Zs,IS_LOCAL:()=>ni,IS_MAC:()=>si,IS_MACQQB:()=>Qs,IS_MIBROWSER:()=>Ks,IS_MQQB:()=>Xo,IS_NATIVE_ANDROID:()=>zg,IS_OLD_ANDROID:()=>Xg,IS_OPENHARMONY:()=>Qo,IS_OPPOBROWSER:()=>zo,IS_SAFARI:()=>Re,IS_SAFARI_15_1:()=>iT,IS_SAMSUNGBROWSER:()=>rn,IS_SOGOU:()=>Xs,IS_SOGOUM:()=>js,IS_TBS:()=>ii,IS_UCBROWSER:()=>Al,IS_VIVOBROWSER:()=>on,IS_WECHAT:()=>oi,IS_WIN:()=>Qr,IS_WQQB:()=>zs,IS_WX:()=>Zg,IS_X5MQQB:()=>jo,IS_XWEB:()=>ri,MACQQB_VERSION:()=>qa,MI_VERSION:()=>Xa,MQQB_VERSION:()=>Wo,OPENHARMONY_VERSION:()=>eT,OPPO_VERSION:()=>Ya,SAFARI_VERSION:()=>Xi,SAMSUNG_VERSION:()=>Qa,SOGOUM_VERSION:()=>Ba,SOGOU_VERSION:()=>Ha,TBS_VERSION:()=>$a,UA_DATA_STRING:()=>ti,USER_AGENT:()=>Vt,VIVO_VERSION:()=>Za,WECHAT_VERSION:()=>Ga,WQQB_VERSION:()=>Ja,XWEB_VERSION:()=>Wa,browserInfo:()=>yi,getBrowserCoreNumber:()=>Ol,getBrowserInfo:()=>jm,getChromeMajorVersion:()=>Yo,getDeviceModel:()=>ai,getDeviceModelFromUA:()=>ed,getGPUInfo:()=>Ml,getOSName:()=>td,getOSNumber:()=>Zr,getOSString:()=>di,getOSType:()=>rT,getTerminalType:()=>kl,getUserAgentData:()=>Yr,isLocalStorageEnabled:()=>zi,isMobile:()=>nn,isVersionLargerThan:()=>bl,isVersionSmallerThan:()=>sn});var Vt=typeof navigator=="undefined"?"":navigator.userAgent,K=o=>new RegExp(o,"i").test(Vt),xe=o=>{if(K(o)){let i=new RegExp(`${o}\\/([\\d.]+)`),e=Vt.match(i);if(e&&e[1])return e[1]}return""},xa=o=>{if(K(o)){let i=new RegExp(`${o}\\/(\\d+)`),e=Vt.match(i);if(e&&e[1])return parseFloat(e[1])}return NaN},Wm=/AppleWebKit\/([\d.]+)/i.exec(Vt),jg=Wm?parseFloat(Wm[1]):NaN,Go=K("iPad"),El=typeof navigator!="undefined"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&K("Macintosh"),Sr=K("iPhone")&&!Go,Jm=K("iPod"),ge=Sr||Go||Jm||El,_e=K("Android"),wa=function(){if(_e){let o=Vt.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(o){let i=o[1]&&parseFloat(o[1]),e=o[2]&&parseFloat(o[2]);if(i&&e)return parseFloat(`${o[1]}.${o[2]}`);if(i)return i}}return NaN}(),Xg=_e&&K("webkit")&&wa<2.3,zg=_e&&wa<5&&jg<537,ee=K("Firefox"),Ua=xe("Firefox"),Jo=xa("Firefox"),zr=K("Edge"),Va=xe("Edge"),qo=K("Edg"),Fa=xe("Edg"),Sl=xa("Edg"),js=K("SogouMobileBrowser"),Ba=xe("SogouMobileBrowser"),Xs=K("MetaSr\\s"),Ha=xe("MetaSr\\s"),ii=K("TBS"),$a=xe("TBS"),ri=K("XWEB"),Wa=xe("XWEB"),Qg=K("MSIE\\s8\\.0"),qm=K("MSIE\\/\\d+"),Yg=function(){if(qm){let o=/MSIE\s(\d+)\.\d/.exec(Vt),i=o&&parseFloat(o[1]);return!i&&/Trident\/7.0/i.test(Vt)&&/rv:11.0/.test(Vt)&&(i=11),i}return NaN}(),oi=K("(micromessenger|webbrowser)"),Ga=xe("MicroMessenger"),jo=!ii&&K("MQQBrowser")&&K("COVC"),Xo=!ii&&K("MQQBrowser")&&!K("COVC"),Wo=Xo||jo?xe("MQQBrowser"):"",zs=!ii&&K(" QQBrowser"),Ja=xe(" QQBrowser"),Qs=!ii&&K("QQBrowserLite"),qa=xe("QQBrowserLite"),Ys=!ii&&K("MQBHD"),ja=xe("MQBHD"),Qr=K("Windows"),si=!ge&&K("MAC OS X"),Zs=!_e&&K("Linux"),Il=K("CrOS"),Zg=K("MicroMessenger"),Al=K("UCBrowser"),Kg=K("Electron"),Ks=K("MiuiBrowser"),Xa=xe("MiuiBrowser"),en=K("HuaweiBrowser"),tn=K("Huawei")||K("HUAWEI"),Cl=K("Honor")||K("HONOR"),za=xe("HuaweiBrowser"),rn=K("SamsungBrowser"),Qa=xe("SamsungBrowser"),zo=K("HeyTapBrowser"),Ya=xe("HeyTapBrowser"),on=K("VivoBrowser"),Za=xe("VivoBrowser"),Qo=K("OpenHarmony"),eT=xe("OpenHarmony"),Yo=()=>xa("Chrome"),qs=K("CriOS"),Ve=K("Chrome"),Zo=!zr&&!Xs&&!js&&!ii&&!ri&&!qo&&!zs&&!Ks&&!en&&!rn&&!zo&&!on&&Ve,Rl=K("HeadlessChrome"),$e=Yo(),Ka=xe("Chrome"),yl=xa("Electron"),Re=!Ve&&!Xo&&!jo&&!Qs&&!Ys&&K("Safari"),Ft=Re||ge,Xi=xe("Version"),tT=/Android.*(wv|.0.0.0)/.test(Vt),ht=(()=>{if(El)return Xi;if(ge){let o=Vt.match(/OS (\d+)_(\d+)/i);if(o&&o[1]){let i=o[1];return o[2]&&(i+=`.${o[2]}`),i}}return""})();function sn(o,i){let e=o.split(".").map(r=>Number(r)),t=i.split(".").map(r=>Number(r));for(let r=0;r<Math.max(e.length,t.length);r++){let s=e[r]||0,n=t[r]||0;if(s<n)return!0;if(s>n)return!1}return!1}function bl(o,i,e=!1){let t=o.split(".").map(s=>Number(s)),r=i.split(".").map(s=>Number(s));for(let s=0;s<Math.max(t.length,r.length);s++){let n=t[s]||0,a=r[s]||0;if(n>a)return!0;if(n<a)return!1}return e}var et=Number(ht.split(".")[0]),iT=Xi==="15.1",Nl=ht==="15.1",vl=(()=>{let o=Number(ht.split(".")[0]);return o===14||o===13})(),Dl=qs&&Xi==="11.1.1",ni=typeof location=="undefined"?!1:location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1",zi=(()=>{let o;return()=>{if(typeof o=="undefined")try{o=!!window.localStorage}catch(i){o=!1}return o}})(),yi=jm();function jm(){let o=new Map([[ee,["Firefox",Ua]],[qo,["Edg",Fa]],[Zo,["Chrome",Ka]],[qs,["ChiOS",xe("CriOS")]],[Re&&!qs,["Safari",Xi]],[ii,["TBS",$a]],[ri,["XWEB",Wa]],[oi&&Sr,["WeChat",Ga]],[zs,["QQ(Win)",Ja]],[Xo,["QQ(Mobile)",Wo]],[jo,["QQ(Mobile X5)",Wo]],[Qs,["QQ(Mac)",qa]],[Ys,["QQ(iPad)",ja]],[Ks,["MI",Xa]],[en,["HW",za]],[rn,["Samsung",Qa]],[zo,["OPPO",Ya]],[on,["VIVO",Za]],[zr,["EDGE",Va]],[js,["SogouMobile",Ba]],[Xs,["Sogou",Ha]]]),i="unknown",e="unknown";return o.has(!0)&&([i,e]=o.get(!0)),{name:i,version:e}}var me=null;function nn(){return me&&typeof me.mobile=="boolean"?me.mobile:_e||ge||Sr||Go||Qo}var ti="";function Yr(){return f(this,null,function*(){if(me)return me;if(!navigator.userAgentData||typeof navigator.userAgentData.getHighEntropyValues!="function")return null;try{return me=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]),me&&!ti&&(ti=`UAData: ${me.platform}/${me.platformVersion}`,me.architecture&&me.bitness&&(ti+=` ${me.architecture}/${me.bitness}`),me.mobile&&(ti+=" mobile"),me.model&&(ti+=` model: ${me.model.replace(/\s+/g,"/")}`),me.fullVersionList&&(ti+=` ${me.fullVersionList.filter(o=>o.brand!=="Not/A)Brand").map(o=>`${o.brand}/${o.version}`).join(",")}`)),me}catch(o){return null}})}function Ml(){try{let o=document.createElement("canvas"),i=o.getContext("webgl")||o.getContext("experimental-webgl");if(!i)return"";let e=i.getExtension("WEBGL_debug_renderer_info");if(e){let t=i.getParameter(e.UNMASKED_VENDOR_WEBGL),r=i.getParameter(e.UNMASKED_RENDERER_WEBGL);return`${t} ${r}`}return""}catch(o){return""}}function ai(){return(me==null?void 0:me.model)||ed()||""}function ed(){let o=/;\s*([^;)]+)\s+Build\//,i=Vt.match(o);return i!=null&&i[1]?i[1].trim():null}var Gm=new Map([[_e,"Android"],[ge,"iOS"],[Qr,"Windows"],[si,"MacOS"],[Zs,"Linux"],[Il,"ChromeOS"]]),td=function(){return Gm.get(!0)?Gm.get(!0):me?me.platform:"unknown"};function Zr(){return Qr?1:_e?2:si?3:ge?4:Zs?5:Il?6:Qo?7:0}function Ol(){return oi||ri?4:Ve?1:Re?2:ee?3:0}var di=()=>{let o=td();return me!=null&&me.platformVersion?o+=`/${me.platformVersion}`:ge?o+=`/${ht}`:_e&&(o+=`/${wa}`),o+=`/${yi.name}/${Re&&!qs?yi.version:yi.version.split(".")[0]}`,me!=null&&me.architecture&&(o+=`/${me.architecture}`),o};function kl(){return _e?4:Sr?2:Go?3:si?12:Qr?5:Zs?13:Qo?22:1}function rT(){return _e?"Android":Sr?"iPhone":Go?"iPad":si?"Mac":Qr?"Windows":Zs?"Linux":"unknown"}var Xm=Je(nt(),1),oT=new Xm.default,S=oT;var mt=(G=>(G.ROOM_DESTROY="1",G.JOIN_START="21",G.JOIN_SCHEDULE_SUCCESS="22",G.JOIN_SIGNAL_CONNECTION_START="23",G.JOIN_SIGNAL_CONNECTION_END="24",G.JOIN_SEND_CMD="25",G.JOIN_RECEIVED_CMD_RES="26",G.JOIN_SUCCESS="27",G.JOIN_FAILED="28",G.LEAVE_START="51",G.LEAVE_SEND_CMD="52",G.LEAVE_SUCCESS="53",G.PUBLISH_START="61",G.SEND_FIRST_VIDEO_FRAME="62",G.PUBLISH_FAILED="63",G.SUBSCRIBE_START="81",G.SUBSCRIBE_SUCCESS="82",G.SUBSCRIBE_FAILED="84",G.UNSUBSCRIBE_SUCCESS="83",G.LOCAL_TRACK_CAPTURE_START="101",G.LOCAL_TRACK_CAPTURE_SUCCESS="102",G.LOCAL_TRACK_CAPTURE_FAILED="103",G.LOCAL_TRACK_PUBLISHED="104",G.LOCAL_TRACK_UNPUBLISHED="105",G.LOCAL_TRACK_REPLACED="106",G.SWITCH_DEVICE_SUCCESS="107",G.TRACK_MUTED="108",G.TRACK_UNMUTED="109",G.REMOTE_TRACK_SUBSCRIBED="110",G.REMOTE_TRACK_UNSUBSCRIBED="111",G.LOCAL_TRACK_RECAPTURE="112",G.LOCAL_AUDIO_STARTED="113",G.LOCAL_AUDIO_STOPPED="114",G.REMOTE_AUDIO_STARTED="115",G.REMOTE_AUDIO_STOPPED="116",G.PLAY_TRACK_START="151",G.PLAYER_STATE_CHANGED="152",G.VIDEO_LOADED_DATA="153",G.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",G.AUDIO_CONTEXT_LONG_SUSPENDED="155",G.REMOTE_VIDEO_PLAY_START="156",G.REMOTE_VIDEO_PLAY_FINISH="157",G.SIGNAL_CONNECTION_STATE_CHANGED="201",G.PEER_CONNECTION_STATE_CHANGED="202",G.SINGLE_CONNECTION_STAT="203",G.SPC_RECONNECTED="204",G.HEARTBEAT_REPORT="251",G.RECEIVED_PUBLISHED_USER_LIST="252",G.REMOTE_PUBLISH_STATE_CHANGED="253",G.AUDIO_LEVEL_INTERVAL="260",G.NETWORK_QUALITY="261",G.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",G.QUALITY_LIMITATION_CHANGED="263",G.LOG="264",G.AUDIO_PROCESSOR_DEBUG="265",G.SSO_SWITCH="266",G.SWITCH_ROOM_START="401",G.SWITCH_ROOM_SUCCESS="407",G.SWITCH_ROOM_FAILED="408",G))(mt||{});var A=mt;var Pl=class{constructor(){c(this,"enable",!1);c(this,"ssoFailCount",0);S.on("22",({schedule:i})=>{var e;(e=i==null?void 0:i.config)!=null&&e.sso&&S.emit("266",{enable:!0})}),S.on("266",({enable:i})=>{this.enable=i})}handleUploadFailed(){this.ssoFailCount++,this.ssoFailCount>3&&S.emit("266",{enable:!1})}},Ir=new Pl;var sT="%cTRTC%c%s",nT="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",aT="display: inline",id=class id{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);!Do&&!xs&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){S.on(A.JOIN_SCHEDULE_SUCCESS,({schedule:i})=>{var e;(e=i==null?void 0:i.config)!=null&&e.logLevelToUpload&&Xt[i.config.logLevelToUpload]&&(this._logLevelToUpload=i.config.logLevelToUpload)}),S.on(A.JOIN_START,({params:i})=>{this.addJoinedUser({userId:i.userId,sdkAppId:i.sdkAppId}),this.startUpload()}),S.on(A.LEAVE_SUCCESS,({room:i})=>{this.deleteJoinedUser(i.userId)})}startUpload(){this._timeoutId===-1&&this.uploadInterval()}addJoinedUser(i){this._localJoinedUser.set(i.userId,i),this.startUpload()}deleteJoinedUser(i){this._localJoinedUser.delete(i)}uploadInterval(){this.upload().catch(()=>{}),this._timeoutId=window.setTimeout(()=>this.uploadInterval(),5e3)}getLogsToUpload(){let i={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&this._localJoinedUser.size===0)return i;let e=0;for(;e<this._queue.length&&e!==50;e++){let t=this._queue[e];if(t.forAllJoinedClients)this._localJoinedUser.forEach(({userId:r,sdkAppId:s})=>{i.map.has(r)?i.map.get(r).logs.push(t):i.map.set(r,{userId:r,sdkAppId:s,logs:[t]})});else if(ie(t.userId)&&Q(t.sdkAppId)){let{userId:r,sdkAppId:s}=t;i.map.has(r)?i.map.get(r).logs.push(t):i.map.set(r,{userId:r,sdkAppId:s,logs:[t]})}}return i.map.size>0&&(i.splicedQueue=this._queue.splice(0,e)),i}upload(){return f(this,null,function*(){if(this._queue.length===0||!this._isEnableUploadLog)return;let{map:i,splicedQueue:e}=this.getLogsToUpload();if(i.size===0)return;try{let r=[...i.values()];for(let s=0;s<r.length;s++){let{userId:n,sdkAppId:a,logs:d}=r[s],l={timestamp:ca(),sdkAppId:String(a),userId:n,version:He,log:d.map(p=>p.log).join(`
6
- `)},u=JSON.stringify(l),h=Ir.enable?qi(l,2002,a):u;yield this.uploadLogWithRetry(h,a,h instanceof Uint8Array,u),d.forEach(p=>p.uploaded=!0)}}catch(r){}let t=e.filter(r=>!r.uploaded);t.length>0&&(this._queue=t.concat(this._queue))})}uploadLogWithRetry(i,e,t,r){return Ri({retryFunction:()=>ji({url:Ji(e,mr.LOG),body:i,timeout:5e3,priority:"low"}).then(s=>{t&&s.data!=="ok"&&(Ir.handleUploadFailed(),this.uploadLogWithRetry(r,e,!1,r))}),settings:{retries:3,timeout:2e3},onError:({retry:s})=>{s()}})()}getPrefix(i){let e=new Date;return e.setTime(Hi()),`[${vo(e)}] <${Xt[i]}>`}getLogLevel(){return this._logLevel}setLogLevel(i){T(Xt[i])||(this._logLevel!==i&&this.info("setLogLevel",i),this._logLevel=i)}enableUploadLog(){this._isEnableUploadLog=!0}disableUploadLog(){this.warn("disableUploadLog"),this._isEnableUploadLog=!1}logChunkToString(i){if(ie(i))return i;try{return i instanceof Error?i.toString():JSON.stringify(i)}catch(e){return""}}addLogToQueue(i,e,t=!0,r,s){let n={log:e.reduce((a,d)=>`${a} ${this.logChunkToString(d)}`.trim(),""),level:i,userId:r,sdkAppId:s,forAllJoinedClients:t};S.emit(A.LOG,{log:n}),this._isEnableUploadLog&&i>=this._logLevelToUpload&&this._queue.push(n)}log(i,e,t=!0,r,s){var a;if(e.unshift(this.getPrefix(i)),this.addLogToQueue(i,e,t,r,s),i<this._logLevel)return;let n=((a=Xt[i])==null?void 0:a.toLowerCase())||"info";id.PRINT_LOG_TAG?console[n](sT,nT,aT,...e):console[n](...e)}debug(...i){this.log(1,i)}info(...i){this.log(2,i)}warn(...i){this.log(3,i)}error(...i){this.log(4,i)}createLogger(i){if(i.parent instanceof Er){let e=i,{parent:t}=e,r=na(e,["parent"]),s=new Er(r);return s.bindParent(t),s}return new Er(i)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;Xt[t]&&(this._logLevelToUpload=t)}getQueue(){return this._queue}};c(id,"PRINT_LOG_TAG",!(ge||_e||Rl));var Ll=id,R=new Ll;var dT=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,o=>{let i=Math.random()*16|0;return(o=="x"?i:i&3|8).toString(16)})},an=dT;var xl=class{constructor(){c(this,"_prefix","TRTC");c(this,"_queue",new Map)}getRealKey(i){return`${this._prefix}_${i}`}checkStorage(){if(!zi())return;setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter(t=>{if(t.startsWith(this._prefix))try{let r=localStorage.getItem(t);if(!r)return!1;let s=JSON.parse(r);if(s&&s.expiresIn<Date.now())return!0}catch(r){return!1}return!1}).forEach(t=>localStorage.removeItem(t))}doFlush(){if(zi())try{for(let[i,e]of this._queue)localStorage.setItem(i,JSON.stringify(e))}catch(i){R.warn(i)}}getItem(i){if(!zi())return null;try{let e=localStorage.getItem(this.getRealKey(i));if(!e)return null;let t=JSON.parse(e);return t&&t.expiresIn>=Date.now()?t.value:null}catch(e){R.warn(e)}}setItem(i,e){if(zi())try{let t={expiresIn:Date.now()+ma,value:e};this._queue.set(this.getRealKey(i),t)}catch(t){R.warn(t)}}deleteItem(i){if(!zi())return!1;try{return i=this.getRealKey(i),this._queue.delete(i),localStorage.removeItem(i),!0}catch(e){return R.warn(e),!1}}clear(){if(zi())try{localStorage.clear()}catch(i){R.warn(i)}}},es=new xl;var vi={};Bi(vi,{HTTPS_API:()=>OT,IS_GET_CAPABILITIES_FROM_INPUTDEVICE_SUPPORTED:()=>au,IS_GET_CAPABILITIES_SUPPORTED:()=>nu,IS_GET_SETTINGS_SUPPORTED:()=>Ni,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>su,IS_INSERTABLE_STREAM_SUPPORTED:()=>pi,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>Ed,IS_RTC_RTP_SENDER_SUPPORTED:()=>_n,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>ss,IS_SEI_SUPPORTED:()=>Tn,IS_SPC_SUPPORTED:()=>os,basis:()=>LT,capabilityCheck:()=>lu,checkSystemRequirementsInternal:()=>fd,decodeSupportStatus:()=>pd,detectVideoCodecCapabilities:()=>uu,detectVideoDecoderCapabilities:()=>bp,detectVideoEncoderCapabilities:()=>yp,encodeSupportStatus:()=>ru,getBrowserInfo:()=>RT,getDisplayResolution:()=>gp,getH264ProfileLevelIds:()=>Np,isAddTransceiverSupported:()=>St,isBrowserSupported:()=>iu,isCanvasCaptureStreamAPISupported:()=>Sp,isCanvasSmallStreamSupported:()=>_d,isGetReceiversSupported:()=>oo,isGetSendersSupported:()=>Rr,isGetTransceiversSupported:()=>yr,isGetUserMediaSupported:()=>Tp,isMediaDevicesSupported:()=>md,isMediaSessionSupported:()=>Ap,isMediaStreamTrackGeneratorSupported:()=>yT,isMediaStreamTrackProcessorSupported:()=>pn,isReplaceTrackSupported:()=>ou,isRequestVideoFrameCallbackSupported:()=>Ki,isSIMDSupported:()=>cu,isScaleResolutionDownBySupported:()=>Ip,isScreenCaptureApiAvailable:()=>fn,isSelectedCandidatePair:()=>Cr,isSetParametersSupported:()=>gn,isSetSinkIdSupported:()=>vT,isSmallStreamSupported:()=>gd,isStopTransceiverSupported:()=>PT,isTRTCSupported:()=>NT,isUnifiedPlanDefault:()=>kT,isUsedInHttpProtocol:()=>Zi,isWebAudioSupported:()=>Ep,isWebCodecSupported:()=>Td,isWebCodecsSupported:()=>mn,isWebRTCSupported:()=>du,isWebTransportSupported:()=>Cp});var zl={};Bi(zl,{AUDIO_LEVEL_SCALE:()=>Dt,AlphaStitchingType:()=>un,AudioCodecPipelineType:()=>cn,AudioDecoderDowngradeState:()=>Fl,AudioPlayerMode:()=>Wl,AudioType:()=>Zm,BASIC_TYPE:()=>Qi,BannedReason:()=>Gl,CONNECTION_CLOSED_REASON:()=>Ul,CheckPermissionType:()=>Xl,ClientEvent:()=>zm,CodecType:()=>rp,ConnectionEvent:()=>ci,ConnectionState:()=>vt,DECODE_FAILED_ERROR_CODE:()=>jl,DenoiserMode:()=>Jl,DeviceType:()=>ad,FacingMode:()=>sd,FrameWorkType:()=>rd,LeaveReason:()=>ip,LocalTrackEvent:()=>Kr,MULTI_VIDEO_DATA_TYPE:()=>hi,MediaType:()=>We,MediaTypeLabel:()=>cT,MonitorEventId:()=>dn,MutedFlag:()=>Ym,NetworkQualityValue:()=>$l,PlayerState:()=>Ar,ReceiveMode:()=>tp,RemoteStreamType:()=>Et,RemoteTrackEvent:()=>eo,RoomEvent:()=>li,SMALL_MODE:()=>ln,SceneNumber:()=>Vl,StreamEvent:()=>Qm,StreamType:()=>ep,SubscribeMediaType:()=>wl,TIMER_TYPE:()=>mi,TRACK_ACTION:()=>Hl,TRACK_KIND:()=>Bl,TrackEvent:()=>ui,UserRole:()=>ct,UserRoleNumber:()=>to,VideoCodec:()=>Bt,VideoCodecPipelineType:()=>ql,VideoContentHint:()=>ts,VideoDecoderDowngradeState:()=>od,VideoPlayerMode:()=>nd,VideoType:()=>Km});var rd=(e=>(e[e.WEBRTC=30]="WEBRTC",e[e.WASM=37]="WASM",e))(rd||{}),ci=(E=>(E.TRACK_ADDED="track-added",E.TRACK_UPDATED="track-updated",E.TRACK_SUBSCRIBED="track-subscribed",E.STREAM_ADDED="stream-added",E.STREAM_REMOVED="stream-removed",E.STREAM_UPDATED="stream-updated",E.STREAM_PUBLISHED="stream-published",E.STREAM_SUBSCRIBED="stream-subscribed",E.STREAM_UNSUBSCRIBED="stream-unsubscribed",E.STATE_CHANGED="state-changed",E.ERROR="error",E.CONNECTION_STATE_CHANGED="connection-state-changed",E.FIREWALL_RESTRICTION="firewall-restriction",E.SEI_MESSAGE="sei-message",E.CLOSED="closed",E))(ci||{}),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||{}),zm=(C=>(C.STREAM_ADDED="stream-added",C.STREAM_REMOVED="stream-removed",C.STREAM_UPDATED="stream-updated",C.STREAM_SUBSCRIBED="stream-subscribed",C.CONNECTION_STATE_CHANGED="connection-state-changed",C.PEER_JOIN="peer-join",C.PEER_LEAVE="peer-leave",C.MUTE_AUDIO="mute-audio",C.MUTE_VIDEO="mute-video",C.UNMUTE_AUDIO="unmute-audio",C.UNMUTE_VIDEO="unmute-video",C.CLIENT_BANNED="client-banned",C.NETWORK_QUALITY="network-quality",C.AUDIO_VOLUME="audio-volume",C.SEI_MESSAGE="sei-message",C.ERROR="error",C))(zm||{}),Qm=(s=>(s.PLAYER_STATE_CHANGED="player-state-changed",s.SCREEN_SHARING_STOPPED="screen-sharing-stopped",s.CONNECTION_STATE_CHANGED="connection-state-changed",s.DEVICE_AUTO_RECOVERED="device-auto-recovered",s.ERROR="error",s))(Qm||{}),Kr=(d=>(d.DEVICE_AUTO_RECOVERED="1",d.DEVICE_RECOVER_FAILED="5",d.DEVICE_CHANGED="2",d.ERROR="3",d.PUBLISH_STATE_CHANGED="4",d.ENCODE_FAILED="6",d.TRACK_ENDED="7",d.RENDER="render",d))(Kr||{}),Ar=(t=>(t.PAUSED="PAUSED",t.PLAYING="PLAYING",t.STOPPED="STOPPED",t))(Ar||{}),li=(k=>(k.PEER_JOIN="peer-join",k.PEER_LEAVE="peer-leave",k.SIGNAL_CONNECTION_STATE_CHANGED="signal-connection-state-changed",k.MEDIA_CONNECTION_STATE_CHANGED="media-connection-state-changed",k.BANNED="banned",k.NETWORK_QUALITY="network-quality",k.AUDIO_VOLUME="audio-volume",k.SEI_MESSAGE="sei-message",k.ERROR="error",k.REMOTE_PUBLISH_STATE_CHANGED="remote-publish-state-changed",k.REMOTE_PUBLISHED="remote-published",k.REMOTE_UNPUBLISHED="remote-unpublished",k.FIREWALL_RESTRICTION="firewall-restriction",k.HEARTBEAT_REPORT="heartbeat-report",k.CUSTOM_MESSAGE="custom-message",k.LAYER_DATA="layerData",k.FIRST_VIDEO_FRAME="first-video-frame",k.DUMP="dump",k.AUDIO_FRAME="audio-frame",k.SUBSCRIBE_SMALL_VIDEO_CHANGED="subscribe-small-video-changed",k.LOCAL_PUBLISH_FLAG_CHANGED="local-publish-flag-changed",k.NTP_TIME_UPDATED="ntp-time-updated",k))(li||{}),ui=(d=>(d.PLAYER_STATE_CHANGED="player-state-changed",d.MUTE="mute",d.UNMUTE="unmute",d.ERROR="error",d.INPUT_MEDIA_TRACK_CHANGED="input-media-track-changed",d.OUTPUT_MEDIA_TRACK_CHANGED="output-media-track-changed",d.FIRST_VIDEO_FRAME="first-video-frame",d.VIDEO_SIZE_CHANGED="video-size-changed",d))(ui||{}),eo=(r=>(r.DECODE_FAILED="decode-failed",r.DECODE_DOWNGRADE_STATE_CHANGED="decode-downgrade-state-changed",r.REMOTE_PUBLISH_CHANGED="remote-publish-changed",r.AUDIO_FRAME_WITH_NTP="audio-frame-with-ntp",r))(eo||{}),Ym=(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))(Ym||{}),Vl=(e=>(e[e.RTC=1]="RTC",e[e.LIVE=2]="LIVE",e))(Vl||{}),to=(e=>(e[e.ANCHOR=20]="ANCHOR",e[e.AUDIENCE=21]="AUDIENCE",e))(to||{}),ct=(e=>(e.ANCHOR="anchor",e.AUDIENCE="audience",e))(ct||{}),vt=(s=>(s.CONNECTED="CONNECTED",s.DISCONNECTED="DISCONNECTED",s.CONNECTING="CONNECTING",s.RECONNECTED="RECONNECTED",s.RECONNECTING="RECONNECTING",s))(vt||{}),Fl=(r=>(r.INITIALIZED="INITIALIZED",r.STARTING="STARTING",r.STARTED="STARTED",r.FAILED="FAILED",r))(Fl||{}),od=(r=>(r.INITIALIZED="INITIALIZED",r.STARTING="STARTING",r.STARTED="STARTED",r.FAILED="FAILED",r))(od||{}),Bl=(t=>(t.AUDIO="audio",t.VIDEO="video",t.AUXILIARY="auxVideo",t))(Bl||{}),Hl=(e=>(e.ADD="add",e.REMOVE="remove",e))(Hl||{}),We=(s=>(s[s.NULL=0]="NULL",s[s.AUDIO=1]="AUDIO",s[s.AUX_VIDEO=2]="AUX_VIDEO",s[s.BIG_VIDEO=4]="BIG_VIDEO",s[s.SMALL_VIDEO=8]="SMALL_VIDEO",s))(We||{}),cT={1:"audio",2:"auxVideo",4:"video"},Zm=(i=>(i[i.opus=111]="opus",i))(Zm||{}),Km=(e=>(e[e.h264=100]="h264",e[e.vp8=101]="vp8",e))(Km||{}),ep=(e=>(e.Big="big",e.Small="small",e))(ep||{}),Et=(e=>(e.Main="main",e.Aux="auxiliary",e))(Et||{}),hi=(s=>(s[s.MULTI_DATA_AUDIO=1]="MULTI_DATA_AUDIO",s[s.MULTI_DATA_BIG_IMG=2]="MULTI_DATA_BIG_IMG",s[s.MULTI_DATA_SMALL_IMG=3]="MULTI_DATA_SMALL_IMG",s[s.MULTI_DATA_AUX_IMG=7]="MULTI_DATA_AUX_IMG",s[s.MULTI_DATA_TYPE_BUTT=12]="MULTI_DATA_TYPE_BUTT",s))(hi||{}),dn=(x=>(x[x.PUBLISH_VIDEO=32768]="PUBLISH_VIDEO",x[x.PUBLISH_AUDIO=32769]="PUBLISH_AUDIO",x[x.UNPUBLISH_VIDEO=32770]="UNPUBLISH_VIDEO",x[x.UNPUBLISH_AUDIO=32771]="UNPUBLISH_AUDIO",x[x.MUTE_AUDIO=32772]="MUTE_AUDIO",x[x.MUTE_VIDEO=32773]="MUTE_VIDEO",x[x.UNMUTE_AUDIO=32774]="UNMUTE_AUDIO",x[x.UNMUTE_VIDEO=32775]="UNMUTE_VIDEO",x[x.SUBSCRIBE_VIDEO=32776]="SUBSCRIBE_VIDEO",x[x.SUBSCRIBE_AUDIO=32777]="SUBSCRIBE_AUDIO",x[x.UNSUBSCRIBE_VIDEO=32778]="UNSUBSCRIBE_VIDEO",x[x.UNSUBSCRIBE_AUDIO=32779]="UNSUBSCRIBE_AUDIO",x[x.SWITCH_CAMERA=32780]="SWITCH_CAMERA",x[x.SWITCH_MICROPHONE=32781]="SWITCH_MICROPHONE",x[x.REPLACE_VIDEO=32782]="REPLACE_VIDEO",x[x.REPLACE_AUDIO=32783]="REPLACE_AUDIO",x[x.MUTE_REMOTE_VIDEO=32784]="MUTE_REMOTE_VIDEO",x[x.MUTE_REMOTE_AUDIO=32785]="MUTE_REMOTE_AUDIO",x[x.UNMUTE_REMOTE_VIDEO=32786]="UNMUTE_REMOTE_VIDEO",x[x.UNMUTE_REMOTE_AUDIO=32787]="UNMUTE_REMOTE_AUDIO",x[x.JOIN=32788]="JOIN",x[x.LEAVE=32789]="LEAVE",x[x.SIGNAL_DISCONNECTED=32790]="SIGNAL_DISCONNECTED",x[x.SIGNAL_CONNECTED=32791]="SIGNAL_CONNECTED",x[x.TRANSPORT_UPLINK_CONNECTED=32792]="TRANSPORT_UPLINK_CONNECTED",x[x.TRANSPORT_DOWNLINK_CONNECTED=32793]="TRANSPORT_DOWNLINK_CONNECTED",x[x.SIGNAl_RECONNECTING=32794]="SIGNAl_RECONNECTING",x[x.SIGNAL_RECONNECT_SUCCESS=32795]="SIGNAL_RECONNECT_SUCCESS",x[x.SIGNAL_RECONNECT_FAIL=32796]="SIGNAL_RECONNECT_FAIL",x[x.TRANSPORT_UPLINK_RECONNECTING=32797]="TRANSPORT_UPLINK_RECONNECTING",x[x.TRANSPORT_UPLINK_RECONNECT_SUCCESS=32798]="TRANSPORT_UPLINK_RECONNECT_SUCCESS",x[x.TRANSPORT_UPLINK_RECONNECT_FAIL=32799]="TRANSPORT_UPLINK_RECONNECT_FAIL",x[x.TRANSPORT_DOWNLINK_RECONNECTING=32800]="TRANSPORT_DOWNLINK_RECONNECTING",x[x.TRANSPORT_DOWNLINK_RECONNECT_SUCCESS=32801]="TRANSPORT_DOWNLINK_RECONNECT_SUCCESS",x[x.TRANSPORT_DOWNLINK_RECONNECT_FAIL=32802]="TRANSPORT_DOWNLINK_RECONNECT_FAIL",x[x.SUBSCRIBE_SMALL_VIDEO=32803]="SUBSCRIBE_SMALL_VIDEO",x[x.UNSUBSCRIBE_SMALL_VIDEO=32804]="UNSUBSCRIBE_SMALL_VIDEO",x[x.PUBLISH_AUX=32805]="PUBLISH_AUX",x[x.UNPUBLISH_AUX=32806]="UNPUBLISH_AUX",x[x.DEVICE_CAPTURE=2003]="DEVICE_CAPTURE",x[x.VIDEO_ENCODER=4004]="VIDEO_ENCODER",x[x.VIDEO_DECODER=4005]="VIDEO_DECODER",x))(dn||{}),$l=(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))($l||{}),tp=(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))(tp||{}),sd=(e=>(e.user="user",e.environment="environment",e))(sd||{}),nd=(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))(nd||{}),Wl=(e=>(e[e.ELEMENT=0]="ELEMENT",e[e.CONTEXT=1]="CONTEXT",e))(Wl||{}),Gl=(r=>(r.BANNED="banned",r.KICK="kick",r.USER_TIME_OUT="user_time_out",r.ROOM_DISBAND="room_disband",r))(Gl||{}),ip=(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))(ip||{}),Dt=1e8,Jl=(e=>(e[e.NORMAL=0]="NORMAL",e[e.FAR_FIELD_REDUCTION=1]="FAR_FIELD_REDUCTION",e))(Jl||{}),wl=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)}},Qi=(s=>(s.String="string",s.Number="number",s.Boolean="boolean",s.Array="array",s.Object="object",s))(Qi||{}),Bt=(s=>(s.H264="h264",s.H265="h265",s.VP8="vp8",s.VP9="vp9",s.AV1="av1",s))(Bt||{}),ql=(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))(ql||{}),cn=(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))(cn||{}),rp=(t=>(t.WebRTC="webrtc",t.WebCodecs="webcodecs",t.WebAssembly="webassembly",t))(rp||{}),jl=(p=>(p[p.SUCCESS=0]="SUCCESS",p[p.FAILED=1]="FAILED",p[p.WEBCODEC_INIT=2]="WEBCODEC_INIT",p[p.WEBCODEC_CONFIG_NOT_SUPPORT=3]="WEBCODEC_CONFIG_NOT_SUPPORT",p[p.WEBCODEC_DECODER_ERROR=4]="WEBCODEC_DECODER_ERROR",p[p.WEBCODEC_TRACK_MUTE=5]="WEBCODEC_TRACK_MUTE",p[p.WASM_INIT=6]="WASM_INIT",p[p.WASM_WEBGL_UNAVALIABLE=7]="WASM_WEBGL_UNAVALIABLE",p[p.WASM_DECODER_ERROR=8]="WASM_DECODER_ERROR",p[p.WASM_TRACK_MUTE=9]="WASM_TRACK_MUTE",p[p.TEST=10]="TEST",p[p.RENDER_2D_ERROR=11]="RENDER_2D_ERROR",p))(jl||{}),ts=(r=>(r.NONE="",r.DETAIL="detail",r.MOTION="motion",r.TEXT="text",r))(ts||{}),mi=(s=>(s.INTERVAL="interval",s.TIMEOUT="timeout",s.RAF="raf",s.RIC="ric",s.INTERVAL_IN_WORKER="intervalInWorker",s))(mi||{}),ln=(e=>(e.CANVAS="canvas",e.API="api",e))(ln||{}),Xl=(r=>(r[r.NONE=0]="NONE",r[r.MICROPHONE=1]="MICROPHONE",r[r.CAMERA=2]="CAMERA",r[r.BOTH=3]="BOTH",r))(Xl||{}),ad=(e=>(e.CAMERA="camera",e.MICROPHONE="microphone",e))(ad||{}),un=(t=>(t[t.none=0]="none",t[t.horizontal=1]="horizontal",t[t.vertical=2]="vertical",t))(un||{});var B={AVOID_REPEATED_CALL:"AVOID_REPEATED_CALL",INVALID_PARAMETER_REQUIRED:"INVALID_PARAMETER_REQUIRED",INVALID_PARAMETER_TYPE:"INVALID_PARAMETER_TYPE",INVALID_PARAMETER_EMPTY:"INVALID_PARAMETER_EMPTY",INVALID_PARAMETER_INSTANCE:"INVALID_PARAMETER_INSTANCE",INVALID_PARAMETER_RANGE:"INVALID_PARAMETER_RANGE",INVALID_PARAMETER_MIN:"INVALID_PARAMETER_MIN",INVALID_PARAMETER_MAX:"INVALID_PARAMETER_MAX",INVALID_PARAMETER_STREAMTYPE:"INVALID_PARAMETER_STREAMTYPE",API_CALL_TIMEOUT:"API_CALL_TIMEOUT",SIGNAL_CHANNEL_RECONNECTION_FAILED:"SIGNAL_CHANNEL_RECONNECTION_FAILED",SIGNAL_CHANNEL_SETUP_FAILED:"SIGNAL_CHANNEL_SETUP_FAILED",ERROR_MESSAGE:"ERROR_MESSAGE",EXCHANGE_SDP_TIMEOUT:"EXCHANGE_SDP_TIMEOUT",DOWNLINK_RECONNECTION_FAILED:"DOWNLINK_RECONNECTION_FAILED",EXCHANGE_SDP_FAILED:"EXCHANGE_SDP_FAILED",UPDATE_OFFER_TIMEOUT:"UPDATE_OFFER_TIMEOUT",UPLINK_RECONNECTION_FAILED:"UPLINK_RECONNECTION_FAILED",INVALID_RECORDID:"INVALID_RECORDID",INVALID_PURE_AUDIO:"INVALID_PURE_AUDIO",INVALID_STREAMID:"INVALID_STREAMID",INVALID_USER_DEFINE_RECORDID:"INVALID_USER_DEFINE_RECORDID",INVALID_USER_DEFINE_PUSH_ARGS:"INVALID_USER_DEFINE_PUSH_ARGS",INVALID_PROXY:"INVALID_PROXY",INVALID_JOIN:"INVALID_JOIN",INVALID_ROOMID_STRING:"INVALID_ROOMID_STRING",INVALID_ROOMID_INTEGER:"INVALID_ROOMID_INTEGER",INVALID_SIGNAL_CHANNEL:"INVALID_SIGNAL_CHANNEL",JOIN_ROOM_TIMEOUT:"JOIN_ROOM_TIMEOUT",JOIN_ROOM_FAILED:"JOIN_ROOM_FAILED",REJOIN_ROOM_FAILED:"REJOIN_ROOM_FAILED",INVALID_DESTROY:"INVALID_DESTROY",INVALID_PUBLISH:"INVALID_PUBLISH",INVALID_UNPUBLISH:"INVALID_UNPUBLISH",INVALID_AUDIENCE:"INVALID_AUDIENCE",INVALID_INITIALIZE:"INVALID_INITIALIZE",INVALID_DUPLICATE_PUBLISHING:"INVALID_DUPLICATE_PUBLISHING",INVALID_SUBSCRIBE_UNDEFINED:"INVALID_SUBSCRIBE_UNDEFINED",INVALID_SUBSCRIBE_LOCAL:"INVALID_SUBSCRIBE_LOCAL",INVALID_REMOTE_STREAM:"INVALID_REMOTE_STREAM",SUBSCRIBE_FAILED:"SUBSCRIBE_FAILED",INVALID_ROLE:"INVALID_ROLE",INVALID_PARAMETER_SWITCH_ROLE:"INVALID_PARAMETER_SWITCH_ROLE",INVALID_OPERATION_SWITCH_ROLE:"INVALID_OPERATION_SWITCH_ROLE",SWITCH_ROLE_TIMEOUT:"SWITCH_ROLE_TIMEOUT",SWITCH_ROLE_FAILED:"SWITCH_ROLE_FAILED",CLIENT_BANNED:"CLIENT_BANNED",INVALID_OPERATION_START_PUBLISH_CDN:"INVALID_OPERATION_START_PUBLISH_CDN",INVALID_OPERATION_STOP_PUBLISH_CDN:"INVALID_OPERATION_STOP_PUBLISH_CDN",INVALID_STREAM_ID:"INVALID_STREAM_ID",START_PUBLISH_CDN_FAILED:"START_PUBLISH_CDN_FAILED",STOP_PUBLISH_CDN_FAILED:"STOP_PUBLISH_CDN_FAILED",START_MIX_TRANSCODE:"START_MIX_TRANSCODE",STOP_MIX_TRANSCODE:"STOP_MIX_TRANSCODE",INVALID_AUDIO_VOLUME:"INVALID_AUDIO_VOLUME",ENABLE_SMALL_STREAM_PUBLISHED:"ENABLE_SMALL_STREAM_PUBLISHED",DISABLE_SMALL_STREAM_PUBLISHED:"DISABLE_SMALL_STREAM_PUBLISHED",NOT_SUPPORTED_SMALL_STREAM:"NOT_SUPPORTED_SMALL_STREAM",INVALID_SMALL_STREAM_PROFILE:"INVALID_SMALL_STREAM_PROFILE",INVALID_PARAMETER_REMOTE_STREAM:"INVALID_PARAMETER_REMOTE_STREAM",INVALID_OPERATION_CHANGE_SMALL:"INVALID_OPERATION_CHANGE_SMALL",REMOTE_NOT_PUBLISH_SMALL_STREAM:"REMOTE_NOT_PUBLISH_SMALL_STREAM",INVALID_SWITCH_DEVICE:"INVALID_SWITCH_DEVICE",INVALID_SWITCH_DEVICE_PUBLISHING:"INVALID_SWITCH_DEVICE_PUBLISHING",INVALID_REPLACE_TRACK:"INVALID_REPLACE_TRACK",INVALID_INITIALIZE_LOCAL_STREAM:"INVALID_INITIALIZE_LOCAL_STREAM",INVALID_ADD_TRACK_REPETITIVE:"INVALID_ADD_TRACK_REPETITIVE",INVALID_ADD_TRACK_REMOVING:"INVALID_ADD_TRACK_REMOVING",INVALID_ADD_TRACK_PUBLISHING:"INVALID_ADD_TRACK_PUBLISHING",INVALID_STREAM_INITIALIZED:"INVALID_STREAM_INITIALIZED",INVALID_ADD_TRACK_NUMBER:"INVALID_ADD_TRACK_NUMBER",INVALID_REMOVE_AUDIO_TRACK:"INVALID_REMOVE_AUDIO_TRACK",INVALID_REMOVE_AUDIO_ADDING:"INVALID_REMOVE_AUDIO_ADDING",INVALID_REMOVE_AUDIO_ON:"INVALID_REMOVE_AUDIO_ON",INVALID_REMOVE_TRACK_PUBLISHING:"INVALID_REMOVE_TRACK_PUBLISHING",INVALID_REMOVE_TRACK_NOT_TRACK:"INVALID_REMOVE_TRACK_NOT_TRACK",INVALID_REMOVE_TRACK_NUMBER:"INVALID_REMOVE_TRACK_NUMBER",INVALID_REPLACE_TRACK_NO_TRACK:"INVALID_REPLACE_TRACK_NO_TRACK",REPEAT_JOIN:"REPEAT_JOIN",CLIENT_DESTROYED:"CLIENT_DESTROYED",NOT_BUG_PACKAGE:"NOT_BUG_PACKAGE",START_MIX_TRANSCODE_FAILED:"START_MIX_TRANSCODE_FAILED",STOP_MIX_TRANSCODE_FAILED:"STOP_MIX_TRANSCODE_FAILED",MIX_TRANSCODE_NOT_STARTED:"MIX_TRANSCODE_NOT_STARTED",CANNOT_LESS_THAN_ZERO:"CANNOT_LESS_THAN_ZERO",MIX_PARAMS_VIDEO_FRAMERATE:"MIX_PARAMS_VIDEO_FRAMERATE",MIX_PARAMS_VIDEO_GOP:"MIX_PARAMS_VIDEO_GOP",MIX_PARAMS_AUDIO_BITRATE:"MIX_PARAMS_AUDIO_BITRATE",MIX_PARAMS_USER_Z_ORDER:"MIX_PARAMS_USER_Z_ORDER",MIX_PARAMS_NOT_SELF:"MIX_PARAMS_NOT_SELF",MIX_PARAMS_USER_STREAM:"MIX_PARAMS_USER_STREAM",INVALID_PLAY:"INVALID_PLAY",INVALID_ELEMENT_ID:"INVALID_ELEMENT_ID",INVALID_ELEMENT_ID_TYPE:"INVALID_ELEMENT_ID_TYPE",PLAY_FAILED:"PLAY_FAILED",INVALID_USERID:"INVALID_USERID",INVALID_CREATE_STREAM_SOURCE:"INVALID_CREATE_STREAM_SOURCE",INVALID_CREATE_STREAM_SCREEN:"INVALID_CREATE_STREAM_SCREEN",INVALID_CREATE_STREAM_AUDIO:"INVALID_CREATE_STREAM_AUDIO",INVALID_CREATE_STREAM_SCREEN_AUDIO:"INVALID_CREATE_STREAM_SCREEN_AUDIO",NOT_SUPPORTED_HTTP:"NOT_SUPPORTED_HTTP",NOT_SUPPORTED_WEBRTC:"NOT_SUPPORTED_WEBRTC",NOT_SUPPORTED_PROFILE:"NOT_SUPPORTED_PROFILE",NOT_SUPPORTED_MEDIA:"NOT_SUPPORTED_MEDIA",NOT_SUPPORTED_H264ENCODE:"NOT_SUPPORTED_H264ENCODE",NOT_SUPPORTED_H264DECODE:"NOT_SUPPORTED_H264DECODE",NOT_SUPPORTED_TRACK:"NOT_SUPPORTED_TRACK",NOT_SUPPORTED_SWITCH_DEVICE:"NOT_SUPPORTED_SWITCH_DEVICE",NOT_SUPPORTED_CAPTURE:"NOT_SUPPORTED_CAPTURE",NOT_SUPPORTED_AUX:"NOT_SUPPORTED_AUX",MICROPHONE_NOT_FOUND:"MICROPHONE_NOT_FOUND",CAMERA_NOT_FOUND:"CAMERA_NOT_FOUND",SIGNAL_RESPONSE_FAILED:"SIGNAL_RESPONSE_FAILED",CATCH_HANDLER_ERROR:"CATCH_HANDLER_ERROR",API_NOT_EXIST:"API_NOT_EXIST",CONNECTION_CLOSED:"CONNECTION_CLOSED",SUBSCRIBE_ALL_FALSE:"SUBSCRIBE_ALL_FALSE",SEI_NOT_SUPPORT:"SEI_NOT_SUPPORT",SEI_DISABLED:"SEI_DISABLED",SEI_BEFORE_PUBLISH:"SEI_BEFORE_PUBLISH",SEI_NOT_VIDEO:"SEI_NOT_VIDEO",CALL_FREQUENCY_LIMIT:"CALL_FREQUENCY_LIMIT",CONNECTION_ABORTED:"CONNECTION_ABORTED",API_CALL_ABORTED:"API_CALL_ABORTED",DUPLICATE_AUX:"DUPLICATE_AUX"},qe={AVOID_REPEATED_CALL(o){return`previous ${o.name}() is ongoing, please avoid repeated calls.`},INVALID_PARAMETER_REQUIRED({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' is a required param when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_TYPE({key:o,rule:i,fnName:e,value:t}){let r=`${o||i.name}`,s="";return Array.isArray(i.type)?s=i.type.join("|"):s=i.type,`'${r}' must be type of ${s} when calling ${e}(), received type: ${Me(t)}.`},INVALID_PARAMETER_EMPTY({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' cannot be '${t}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:o,rule:i,fnName:e,value:t}){let r=`${o||i.name}`,s=`${i.instanceOf.name||i.instanceOf}`;return`'${r}' must be instanceof ${s} when calling ${e}(), received type: ${Me(t)}.`},INVALID_PARAMETER_RANGE({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' must be one of ${i.values.join("|")} when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_MIN({key:o,rule:i,fnName:e,value:t}){return`the min value of ${o||i.name} is ${i.min}, received: ${t}.`},INVALID_PARAMETER_MAX({key:o,rule:i,fnName:e,value:t}){return`the max value of ${o||i.name} is ${i.max}, received: ${t}.`},API_CALL_TIMEOUT(o){return`${o.commandDesc||o.command} timeout observed.`},SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED(o){return`SignalChannel setup failure: (errorCode: ${o.errorCode}, errorMsg: ${o.errorMsg} }).`},ERROR_MESSAGE(o){let i=`${o.type} failed`;return o.message&&(i=`${i}: ${o.message}.`),i},EXCHANGE_SDP_TIMEOUT:"exchange sdp timeout.",DOWNLINK_RECONNECTION_FAILED:"downlink reconnection failed, please check your network and re-join room.",EXCHANGE_SDP_FAILED(o){return`exchange sdp failed ${o.errMsg}.`},UPDATE_OFFER_TIMEOUT:"update offer timeout observed.",UPLINK_RECONNECTION_FAILED:"uplink reconnection failed, please check your network and publish again.",INVALID_RECORDID:"recordId must be an integer number.",INVALID_PURE_AUDIO:"pureAudioPushMode must be 1 or 2.",INVALID_STREAMID:"streamId must be a sting literal within 64 bytes, and not be empty.",INVALID_USER_DEFINE_RECORDID:"userDefineRecordId must be a sting literal contains (a-zA-Z),(0-9), underline and hyphen, within 64 bytes, and not be empty.",INVALID_USER_DEFINE_PUSH_ARGS:"userDefinePushArgs must be a sting literal within 256 bytes, and not be empty.",INVALID_PROXY:'proxy server url must start with "wss://".',INVALID_JOIN:"duplicate join() called.",INVALID_ROOMID_STRING(o){return`'${o}' must be validate string when useStringRoomId is true.`},INVALID_ROOMID_INTEGER(o){return`'${o}' must be an integer between [1, 4294967294] when useStringRoomId is false.`},INVALID_SIGNAL_CHANNEL:"SignalChannel is not ready yet.",JOIN_ROOM_TIMEOUT:"join room timeout.",JOIN_ROOM_FAILED({error:o,code:i}){return`Failed to join room - ${o} code: ${i}`},REJOIN_ROOM_FAILED(o){return`reJoin room: ${o.roomId} failed, please check your network.`},INVALID_DESTROY:"please call leave() before destroy().",INVALID_PUBLISH:"please call join() before publish().",INVALID_UNPUBLISH:"stream has not been published yet.",INVALID_AUDIENCE:'no permission to publish() under live/audience, please call switchRole("anchor") firstly before publish().',INVALID_INITIALIZE:"cannot publish stream because stream is not initialized, is switching device, or has been closed.",INVALID_DUPLICATE_PUBLISHING(o){return`duplicate ${o} stream publishing, please unpublish your prev ${o} stream and then re-publish.`},INVALID_SUBSCRIBE_UNDEFINED:"stream is undefined or null.",INVALID_SUBSCRIBE_LOCAL:"stream cannot be LocalStream.",INVALID_REMOTE_STREAM:"remoteStream does not exist because it has been unpublished by remote peer.",SUBSCRIBE_FAILED({message:o,userId:i,streamType:e}){return`failed to subscribe ${i} ${e} stream, reason: ${o}.`},INVALID_ROLE:"switchRole can only be called in live mode.",INVALID_PARAMETER_SWITCH_ROLE:"role could only be set to a value as anchor or audience.",INVALID_OPERATION_SWITCH_ROLE:"please call join() before switchRole().",SWITCH_ROLE_TIMEOUT:"switchRole timeout.",SWITCH_ROLE_FAILED(o){return`switchRole failed, errCode: ${o.code} errMsg: ${o.message}.`},CLIENT_BANNED(o){return`client was banned because of ${o.message}.`},INVALID_OPERATION_START_PUBLISH_CDN:"please call startPublishCDNStream() after join room and publish the local stream.",INVALID_OPERATION_STOP_PUBLISH_CDN:"please call startPublishCDNStream() before stopPublishCDNStream().",START_PUBLISH_CDN_FAILED(o){return`startPublishCDNStream failed, errMsg: ${o.message}.`},STOP_PUBLISH_CDN_FAILED(o){return`stopPublishCDNStream failed, errMsg: ${o.message}.`},INVALID_STREAM_ID(o){return`'${o}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},START_MIX_TRANSCODE:"please call startMixTranscode() after join().",STOP_MIX_TRANSCODE:"please call stopMixTranscode() after startMixTranscode().",INVALID_AUDIO_VOLUME:"interval must be a number.",ENABLE_SMALL_STREAM_PUBLISHED:"Cannot enable small stream after localStream published.",DISABLE_SMALL_STREAM_PUBLISHED:"Cannot disable small stream after localStream published.",NOT_SUPPORTED_SMALL_STREAM:"your browser does not support opening small stream.",INVALID_SMALL_STREAM_PROFILE:"small stream profile is invalid.",INVALID_PARAMETER_REMOTE_STREAM:"remoteStream is invalid.",INVALID_OPERATION_CHANGE_SMALL:"cannot switch to the small stream without subscribing to the video of remoteStream.",REMOTE_NOT_PUBLISH_SMALL_STREAM:"remote peer does not publish small stream.",INVALID_SWITCH_DEVICE:"cannot switch device on current stream.",INVALID_SWITCH_DEVICE_PUBLISHING:"cannot switch device when publishing localStream.",INVALID_REPLACE_TRACK:"cannot replace track when publishing localStream.",INVALID_INITIALIZE_LOCAL_STREAM:"local stream has not initialized yet.",INVALID_ADD_TRACK_REPETITIVE:"previous addTrack is ongoing, please avoid repetitive execution.",INVALID_ADD_TRACK_REMOVING:"cannot add track when a track is removing.",INVALID_ADD_TRACK_PUBLISHING:"cannot add track when publishing localStream.",INVALID_STREAM_INITIALIZED:"your local stream haven't been initialized yet.",INVALID_ADD_TRACK_NUMBER:"a Stream has at most one audio track and one video track.",INVALID_REMOVE_AUDIO_TRACK:"remove audio track is not supported on your browser.",INVALID_REMOVE_AUDIO_ADDING:"cannot remove track when a track is adding.",INVALID_REMOVE_AUDIO_ON:"previous removeTrack is ongoing, please avoid repetitive execution.",INVALID_REMOVE_TRACK_PUBLISHING:"cannot remove track when publishing localStream.",INVALID_REMOVE_TRACK_NOT_TRACK:"localStream has not this track.",INVALID_REMOVE_TRACK_NUMBER:"remove the only video track is not supported, please use replaceTrack or muteVideo.",INVALID_REPLACE_TRACK_NO_TRACK(o){return`cannot replace ${o.kind} track because stream has not ${o.kind} track`},NOT_BUG_PACKAGE:"You need to buy packages, refer to tencent console.",START_MIX_TRANSCODE_FAILED(o){return`startMixTranscode failed, errMsg: ${o.message}.`},STOP_MIX_TRANSCODE_FAILED(o){return`stopMixTranscode failed, errMsg: ${o.message}.`},MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' cannot be less than 0 when calling ${e}().`},MIX_PARAMS_VIDEO_FRAMERATE:"'config.videoFramerate' should be an integer between 0 and 30, excluding 0.",MIX_PARAMS_VIDEO_GOP:"'config.videoGOP' should be an integer between 1 and 8.",MIX_PARAMS_AUDIO_BITRATE:"'config.audioBitrate' should be an integer between 32 and 192.",MIX_PARAMS_USER_Z_ORDER(o){return`'${o}' is required and must be between 1 and 15.`},MIX_PARAMS_NOT_SELF:"'config.mixUsers' must contain self.",MIX_PARAMS_USER_STREAM:"'config.videoWidth' and 'config.videoHeight' of output stream should be contain all mix stream.",INVALID_PLAY:"duplicate play() call observed, please stop() firstly.",INVALID_ELEMENT_ID:({key:o,fnName:i})=>`'${o}' is not found in the document object when calling ${i}().`,INVALID_ELEMENT_ID_TYPE:({key:o,fnName:i,type:e})=>`the element corresponding to '${o}' must be instanceof HTMLElement when calling ${i}(), received: ${e}.`,PLAY_FAILED:o=>`${o.media} play failed, browser exception: ${o.error.toString()}`,INVALID_USERID:"userId cannot be all spaces.",INVALID_CREATE_STREAM_SOURCE:"LocalStream must be created by createStream() with either audio/video or audioSource/videoSource, but can not be mixed with audio/video and audioSource/videoSource.",INVALID_CREATE_STREAM_SCREEN:"screen/video cannot be both true.",INVALID_CREATE_STREAM_AUDIO:"audio/screenAudio cannot be both true.",INVALID_CREATE_STREAM_SCREEN_AUDIO:"when screen is true, screenAudio can be configured.",NOT_SUPPORTED_HTTP:"http protocol does not support the ability to capture microphone, camera and screen. please use https to deploy your page.",NOT_SUPPORTED_WEBRTC:"your browser or environment does not support full WebRTC capabilities.",NOT_SUPPORTED_PROFILE:"your browser does not support setVideoProfile.",NOT_SUPPORTED_MEDIA:"your browser or environment does not support navigator.mediaDevices.",NOT_SUPPORTED_H264ENCODE:"your device does not support H.264 encoding.",NOT_SUPPORTED_H264DECODE:"your device does not support H.264 decoding.",NOT_SUPPORTED_TRACK(o){return`${o}Track is not supported on your browser.`},NOT_SUPPORTED_SWITCH_DEVICE:"switchDevice is not supported on your browser.",NOT_SUPPORTED_CAPTURE:"Your browser or environment does not support screen sharing, please check whether the browser version.",MICROPHONE_NOT_FOUND:"no microphone detected, please check your microphone.",CAMERA_NOT_FOUND:"no camera detected, please check your camera.",SIGNAL_RESPONSE_FAILED(o){return`${o.signalResponse} failed, response code is ${o.code} , errMsg: ${o.message}.`},CATCH_HANDLER_ERROR({name:o,event:i}){return`an error was caught in ${o}.on('${i}', handler), please check your code in 'handler'.`},API_NOT_EXIST({name:o}){return`experimental api ${o} does not exist.`},REPEAT_JOIN:o=>"please avoid repeated join.",CONNECTION_CLOSED:"remoteStream has been unsubscribed or unpublished by remote user.",SUBSCRIBE_ALL_FALSE:"cannot subscribe when both audio & video are false, use client.unsubscribe() instead",CLIENT_DESTROYED({funName:o}){return`failed to call ${o}() because client was destroyed.`},SEI_NOT_SUPPORT:o=>`not support to sendSEIMessage${o===!1?" without using h264 codec":""}`,SEI_DISABLED:"SEI is disabled",SEI_BEFORE_PUBLISH:"please call sendSEIMessage() after publish() success",SEI_NOT_VIDEO:"cannot send sei when localStream has not video.",CALL_FREQUENCY_LIMIT:({isSize:o,name:i,timesInSecond:e,maxSizeInSecond:t})=>`api ${i} call ${o?"size":"times"} is over ${o?`${t} bytes`:e} in a second.`,CONNECTION_ABORTED(o){return`connection aborted due to: ${o}`},API_CALL_ABORTED(o){let i;return o.message.includes("REMOTE_STREAM_NOT_EXIST")?i=`Subscribe ${o.userId} ${o.streamType} stream aborted, reason: remote user ${o.userId} unpublished stream.`:i=`API aborted, reason: ${o.message}`,i},DUPLICATE_AUX:"only one auxiliary stream can be published in a room.",NOT_SUPPORTED_AUX:"publish auxiliary stream is not supported on your browser.",INVALID_PARAMETER_STREAMTYPE:o=>`'streamType' is required when 'userId' is not '*', calling ${o}()`};var op=(o,i)=>i?`${_t}/${o}/${i}`:`${_t}/${o}/index.html`;var lT=()=>{if(window.TRTC_ERROR_INFO&&window.TRTC_ERROR_LINK)return{TRTC_ERROR_INFO:window.TRTC_ERROR_INFO,TRTC_ERROR_LINK:window.TRTC_ERROR_LINK};let o=localStorage==null?void 0:localStorage.getItem(qc);if(o){o=JSON.parse(o);let i=document.createElement("script");i.type="text/javascript",i.text=o.message,document.body.appendChild(i);let e=window.TRTC_ERROR_INFO,t=window.TRTC_ERROR_LINK;return document.body.removeChild(i),{TRTC_ERROR_INFO:e,TRTC_ERROR_LINK:t}}return{}};function $(o){let{key:i,data:e,link:t,addDocLink:r=!0}=o,s="",n="",a="";le(qe[i])?s=qe[i](e):ie(qe[i])&&(s=qe[i]);let{TRTC_ERROR_INFO:d,TRTC_ERROR_LINK:l}=lT();t?a=`${t.className}.html#${t.fnName}`:l&&l[i]&&(le(l[i])?a=l[i](e):ie(l[i])&&(a=l[i]));let u=s;return Yt()&&(d&&d[i]&&(le(d[i])?n=d[i](e):ie(d[i])&&(n=d[i])),n&&(r?u=`${n}
7
- \u8BF7\u67E5\u770B\u6587\u6863: ${op("zh-cn",a)}
5
+ `}});var om=Ui(lr=>{"use strict";var Co=g_(),fI=E_();lr.write=fI;lr.parse=Co.parse;lr.parseParams=Co.parseParams;lr.parseFmtpConfig=Co.parseFmtpConfig;lr.parsePayloads=Co.parsePayloads;lr.parseRemoteCandidates=Co.parseRemoteCandidates;lr.parseImageAttributes=Co.parseImageAttributes;lr.parseSimulcastStreamList=Co.parseSimulcastStreamList});import o5 from"webrtc-adapter";var s_=Je(at());var Cm=(H=>(H[H.INVALID_PARAMETER=4096]="INVALID_PARAMETER",H[H.INVALID_OPERATION=4097]="INVALID_OPERATION",H[H.NOT_SUPPORTED=4098]="NOT_SUPPORTED",H[H.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",H[H.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",H[H.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",H[H.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",H[H.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",H[H.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",H[H.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",H[H.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",H[H.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",H[H.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",H[H.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",H[H.CLIENT_BANNED=16448]="CLIENT_BANNED",H[H.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",H[H.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",H[H.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",H[H.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",H[H.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",H[H.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",H[H.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",H[H.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",H[H.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",H[H.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",H[H.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",H[H.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",H[H.API_CALL_ABORTED=16461]="API_CALL_ABORTED",H[H.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",H[H.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",H[H.SWITCH_ROOM_FAILED=16464]="SWITCH_ROOM_FAILED",H[H.VIDEO_ENCODE_FAILED=16465]="VIDEO_ENCODE_FAILED",H[H.AUDIO_ENCODE_FAILED=16466]="AUDIO_ENCODE_FAILED",H[H.UNKNOWN=65535]="UNKNOWN",H))(Cm||{}),I=Cm;var lg=function(o){for(let i in I)if(I[i]===o)return i;return"UNKNOWN"},xs=class extends Error{constructor({name:e="RtcError",message:t,code:r=I.UNKNOWN,extraCode:s=0,constraint:n}){let a=`<${lg(r)} 0x${r.toString(16)}>`,c=`${t}${n?` constraint: ${n}`:""}${t!=null&&t.includes(a)?"":` ${a}`}`;super(c);d(this,"code");d(this,"extraCode");d(this,"message");d(this,"originMessage");d(this,"name");d(this,"constraint");this.code=r,this.extraCode=s,this.name=e,this.message=c,this.constraint=n,this.originMessage=t}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},D=xs;var Qd=0,Rm=!0,ha=function(o){Qd=o;let i=new Date;i.setTime(i.getTime()+o),R[Rm?"info":"debug"](`baseTime from server: ${i} offset: ${o}`),Rm=!1},ym=function(){return Qd},Fi=function(){return Date.now()+Qd},ma=function(){let o=new Date;return o.setTime(Fi()),o.toLocaleString()},Mo=function(o){let i=String(o.getMilliseconds());return"padStart"in String.prototype&&(i=i.toString().padStart(3,"0")),`${o.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")}:${i}`};var vt={};Vi(vt,{REPORT_TYPE:()=>Wo,buildSSOPackage:()=>Wi,bytes2ms:()=>xm,calculateScaleResolutionDownNumber:()=>Go,concatArrayBuffers:()=>La,convertObjectNumberToInt:()=>Xs,copyProperties:()=>Lm,deepClone:()=>Wr,deepCloneBasic:()=>Na,deepMerge:()=>ti,delay:()=>Ge,fibonacci:()=>Jr,formatedTime:()=>qm,getConstructorName:()=>Vo,getContainerFromElement:()=>Wm,getEnv:()=>km,getFirst16Bits:()=>jm,getInternalVersion:()=>$m,getLast16Bits:()=>xa,getLoggerUrl:()=>Gi,getMediaStreamTrackInfo:()=>wa,getMuteStateFromFlag:()=>ei,getNetworkType:()=>Da,getNumNetworkType:()=>qr,getReconnectionTimeout:()=>Kt,getStringByteLength:()=>js,getTurnServer:()=>Gm,getUint32Version:()=>Oa,getValueType:()=>Oe,getViewListFromView:()=>Ho,glog:()=>Al,ipv4ToUint32:()=>Bo,isArray:()=>Ae,isAudioWorkletSupported:()=>Bm,isBoolean:()=>he,isConstructor:()=>jr,isEmpty:()=>Fo,isFunction:()=>me,isLangChinese:()=>Zt,isMediaStreamTrack:()=>Vm,isNumber:()=>Q,isObject:()=>yt,isOverseaSdkAppId:()=>Vt,isPlainObject:()=>dt,isPortrait:()=>Cl,isPromise:()=>Er,isRemoteTrack:()=>Fm,isRotate90Or270:()=>bt,isSetSinkIdSupported:()=>Hm,isString:()=>re,isUndefined:()=>T,loadImage:()=>$o,loadVideo:()=>Jm,ms2bytes:()=>Um,ms2samples:()=>Il,normalizeUrl:()=>Pa,performanceNow:()=>V,promiseAny:()=>Xr,samples2ms:()=>Sl,setNetworkTypeFromWebRTC:()=>Ma,stringify:()=>_t,stringifyIncludeValue:()=>Js,throttlePromise:()=>ka});var ll={};Vi(ll,{AUDIO_MUTE_BIT:()=>Ia,AUDIO_STAT_BIT:()=>_r,AUX_STAT_BIT:()=>Hr,AUX_STREAM_MSID:()=>rl,BACKEND_ENV:()=>Sa,BASE_DOC_URL:()=>ft,BASE_HOST:()=>bm,CAPABILITIES_KEYS:()=>Ra,CLASS_NAME:()=>kg,CLOUD_CONSOLE_URL:()=>pg,CROSS_ROOM_BIT:()=>il,DATA_FREEZE_TIMING:()=>Ca,DOC_BILLING_CN:()=>pa,DOC_BILLING_OVERSEA:()=>fa,DOC_URL:()=>fg,DTLS_STATE_UNKNOWN:()=>Yt,ENV_NAME:()=>Bi,EXCHANGE_SDP_TIMEOUT:()=>cl,IS_WORKER:()=>Oo,IS_WORKLET:()=>Vs,KIBANA_EVENT:()=>Ke,LOCAL_STREAM_PUBLISH_STATE:()=>Nm,LOGGER_CMD_TYPE:()=>mr,LOGGER_DOMAIN:()=>Zd,LOGGER_DOMAIN_OVERSEA:()=>Kd,LOG_LEVEL:()=>zt,LOG_LEVEL_NAME:()=>wg,MAIN_STREAM_MSID:()=>Hs,MAX_RTT:()=>Ws,MICROPHONE_COMMUNICATIONS:()=>Pg,MICROPHONE_DEFAULT:()=>Gr,MUTE_ALL_BIT:()=>Tg,NAME:()=>p,NETWORK_TYPE:()=>_a,NOT_SUPPORTED_H264:()=>$r,PAUSED_RETRY_COUNT:()=>Tr,PEERCONNECTION_CONNECTING_TIMEOUT:()=>$s,PEER_CONNECTION_STATE:()=>ye,PEER_LEAVE_REASON:()=>dl,RECOVER_CAPTURE_INTERVAL:()=>wo,REMOTE_STREAM_TYPE_AUX:()=>sl,REMOTE_STREAM_TYPE_MAIN:()=>ol,RENDER_FREEZE_TIMING:()=>Ng,SCHEDULE_DOMAIN:()=>$i,SCHEDULE_TIMEOUT:()=>Og,SDP_SEMANTICS_PLAN_B:()=>ko,SDP_SEMANTICS_UNIFIED_PLAN:()=>gr,SECOND_HOST:()=>hg,SIGNAL_PING_PONG_INTERVAL:()=>gg,SIGNAL_PING_TIMEOUT:()=>_g,SIGNAL_RECONNECTION_COUNT:()=>bg,SMALL_STAT_BIT:()=>Bs,SPEAKER_DEFAULT:()=>Gs,STORAGE_EXPIRES_TIME:()=>ga,STREAM_TYPE_BIG:()=>Dg,STREAM_TYPE_SMALL:()=>Mg,SUBSCRIBE_SMALL_RETRY_COUNT:()=>Po,SYNC_USER_LIST_INTERVAL:()=>vg,Scene:()=>Si,THIRD_HOST:()=>mg,TRANSPORT_DIRECTION:()=>ae,TRTC_ERROR_ASSISTANCE:()=>el,TRTC_QUALITY_BAD:()=>Cg,TRTC_QUALITY_DISCONNECTED:()=>yg,TRTC_QUALITY_EXCELLENT:()=>Sg,TRTC_QUALITY_GOOD:()=>Ig,TRTC_QUALITY_POOR:()=>Ag,TRTC_QUALITY_UNKNOWN:()=>Eg,TRTC_QUALITY_VERY_BAD:()=>Rg,UPDATE_OFFER_TIMEOUT:()=>al,VIDEO_MUTE_BIT:()=>Aa,VIDEO_STAT_BIT:()=>fr,audioProfileMap:()=>Ta,defaultBigVideoProfile:()=>pr,defaultSmallVideoProfile:()=>tl,getRetryCount:()=>Hi,getScriptDir:()=>ug,innerVersion:()=>Us,loggerProxy:()=>Fs,screenProfileMap:()=>Ea,setLoggerProxy:()=>Br,setRetryCount:()=>nl,setVersion:()=>Yd,version:()=>$e,videoProfileMap:()=>Qt});var Us="4.15.00.1600",$e="5.0.0";function Yd(o){$e=o;let[i,e,t]=o.split(".").map(r=>parseInt(r,10));Us=`${i}.${Math.min(15,e)}.${Math.min(15,t)}.${e.toString().padStart(2,"0")}${t.toString().padStart(2,"0")}`}var Oo=typeof importScripts!="undefined",Vs=typeof registerProcessor!="undefined",ug=()=>{let o=Oo?self.location.href:document.currentScript.src;return o.substring(0,o.lastIndexOf("/")+1)},Fs="",Br=o=>Fs=o,bm="web.sdk.qcloud.com",hg="web.sdk.tencent.cn",mg="web.sdk.cloud.tencent.cn",pg="https://console.cloud.tencent.com/trtc",ft=`https://${bm}/trtc/webrtc/doc`,fg=`${ft}/zh-cn/`,pa="https://cloud.tencent.com/document/product/647/85386",fa="https://trtc.io/document/56025",Zd="https://yun.tim.qq.com",Kd="https://apisgp.my-imcloud.com",el="trtc_error_assistance",mr={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},Bi={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},zt=(n=>(n[n.TRACE=0]="TRACE",n[n.DEBUG=1]="DEBUG",n[n.INFO=2]="INFO",n[n.WARN=3]="WARN",n[n.ERROR=4]="ERROR",n[n.NONE=5]="NONE",n))(zt||{}),_g=18e3,gg=2e3,_a={unknown:0,wifi:1,"4g":2,"3g":3,"2g":4,wired:5,"5g":6},ga=7*24*3600*1e3,Ta={standard:{sampleRate:48e3,channelCount:1,bitrate:40},"standard-stereo":{sampleRate:48e3,channelCount:2,bitrate:64},high:{sampleRate:48e3,channelCount:1,bitrate:128},"high-stereo":{sampleRate:48e3,channelCount:2,bitrate:192}},Qt={"120p":{width:160,height:120,frameRate:15,bitrate:200},"120p_2":{width:160,height:120,frameRate:15,bitrate:100},"180p":{width:320,height:180,frameRate:15,bitrate:350},"180p_2":{width:320,height:180,frameRate:15,bitrate:150},"240p":{width:320,height:240,frameRate:15,bitrate:400},"240p_2":{width:320,height:240,frameRate:15,bitrate:200},"360p":{width:640,height:360,frameRate:15,bitrate:800},"360p_2":{width:640,height:360,frameRate:15,bitrate:400},"480p":{width:640,height:480,frameRate:15,bitrate:900},"480p_2":{width:640,height:480,frameRate:15,bitrate:500},"720p":{width:1280,height:720,frameRate:15,bitrate:1500},"1080p":{width:1920,height:1080,frameRate:15,bitrate:2e3},"1440p":{width:2560,height:1440,frameRate:30,bitrate:4860},"4K":{width:3840,height:2160,frameRate:30,bitrate:9e3}},pr=Qt["480p_2"],tl=Qt["120p_2"],Ea={"480p":{width:640,height:480,frameRate:5,bitrate:900},"480p_2":{width:640,height:480,frameRate:30,bitrate:1e3},"720p":{width:1280,height:720,frameRate:5,bitrate:1200},"720p_2":{width:1280,height:720,frameRate:30,bitrate:3e3},"1080p":{width:1920,height:1080,frameRate:5,bitrate:1600},"1080p_2":{width:1920,height:1080,frameRate:30,bitrate:4e3}},p={CANVAS:"canvas",AUDIO:"audio",VIDEO:"video",SCREEN:"screen",SMALL:"small",BIG:"big",AUXILIARY:"auxiliary",SMALL_VIDEO:"smallVideo",FACING_MODE_USER:"user",FACING_MODE_ENVIRONMENT:"environment",MUTE:"mute",UNMUTE:"unmute",ENDED:"ended",PLAYING:"playing",PAUSE:"pause",ERROR:"error",LOADSTART:"loadstart",LOADEDDATA:"loadeddata",LOADEDMETADATA:"loadedmetadata",AUDIO_INPUT:"audioinput",VIDEO_INPUT:"videoinput",DETAIL:"detail",TEXT:"text",MAIN:"main",BACKUP:"backup",BANNED:"banned",KICK:"kick",USER_TIME_OUT:"user_time_out",ROOM_DISBAND:"room_disband",SEI_MESSAGE:"sei-message",ADD:"add",REMOVE:"remove",REPLACE:"replace",TRACK:"track",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",TRANSCEIVER_DIRECTION_SENDONLY:"sendonly",TRANSCEIVER_DIRECTION_RECVONLY:"recvonly",ENTER_PICTURE_IN_PICTURE:"enterpictureinpicture",LEAVE_PICTURE_IN_PICTURE:"leavepictureinpicture",RESIZE:"resize",TIME_UPDATE:"timeupdate"},ae={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},Sa={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},Si=(e=>(e.LIVE="live",e.RTC="rtc",e))(Si||{}),fr=1,Bs=2,Hr=4,_r=8,Ia=64,Aa=16,Tg=112,il=128,Hs="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",rl="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",ol=p.MAIN,sl=p.AUXILIARY,Eg=0,Sg=1,Ig=2,Ag=3,Cg=4,Rg=5,yg=6,Yt="unknown",ye={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},vm=1/0;function nl(o){vm=o}function Hi(){return vm}var bg=30,Ke={JOIN:"join",DELTA_JOIN:"delta-join",REJOIN:"rejoin",LEAVE:"leave",DELTA_LEAVE:"delta-leave",PUBLISH:"publish",DELTA_PUBLISH:"delta-publish",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",UPLINK_CONNECTION:"uplink-connection",UPLINK_RECONNECTION:"uplink-reconnection",DOWNLINK_CONNECTION:"downlink-connection",DOWNLINK_RECONNECTION:"downlink-reconnection",ON_TRACK:"ontrack",ICE_CONNECTION_STATE:"iceConnectionState",LOCAL_STREAM_INITIALIZE:"stream-initialize",SIGNAL_CONNECTION:"websocketConnectionState",SIGNAL_RECONNECTION:"websocketReconnectionState",UPDATE_STREAM:"update-stream",RECOVER_LOCAL_AUDIO_TRACK:"recover-local-audio-track",RECOVER_LOCAL_VIDEO_TRACK:"recover-local-video-track",RECOVER_SUBSCRIPTION:"recover-subscription",START_MIX_TRANSCODE:"start-mix-transcode",STOP_MIX_TRANSCODE:"stop-mix-transcode",PLAYER_ERROR:"player-error",SCHEDULE:"schedule",LOAD_WORKLET:"load-worklet",VIDEO_FROZEN_COUNT:"videoFrozenCount",GET_USER_MEDIA_RETRY:"getUserMedia-retry",VIDEO_ENCODE_FAILED_DURING_CALL:"video-encode-failed-during-call",AUDIO_ENCODE_FAILED_DURING_CALL:"audio-encode-failed-during-call"},vg=1e4,al=1e4,cl=1e4,gr="unified-plan",ko="plan-b",$r=1028,Nm=(t=>(t[t.UNPUBLISH=-1]="UNPUBLISH",t[t.PUBLISHING=0]="PUBLISHING",t[t.PUBLISHED=1]="PUBLISHED",t))(Nm||{}),Ca=500,Ng=1e3,Dg=p.BIG,Mg=p.SMALL,$s=10*1e3,$i={MAIN:"schedule.cloud-rtc.com",BACKUP:"schedule.cloud-rtc.net",MAIN_OVERSEA:"schedule.rtc-web.com",BACKUP_OVERSEA:"schedule.rtc-web.io",MAIN_OVERSEA_BACKUP:"intl-schedule.cloud-rtc.com"},Og=2e3,kg={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},Tr=5,Gr="default",Gs=Gr,Pg="communications",wg=Object.keys(zt),dl=["normal leave","timeout leave","kick","role change"],Po=10,wo=2e3,Ra=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],Ws=10*1e3;var Lg=function(o,i,e,t){function r(s){return s instanceof e?s:new e(function(n){n(s)})}return new(e||(e=Promise))(function(s,n){function a(h){try{l(t.next(h))}catch(m){n(m)}}function c(h){try{l(t.throw(h))}catch(m){n(m)}}function l(h){h.done?s(h.value):r(h.value).then(a,c)}l((t=t.apply(o,i||[])).next())})},ul=Symbol(32),hl=Symbol(16),ml=Symbol(8),Ii=class{constructor(i){this.g=i,this.consumed=0,i&&(this.need=i.next().value)}setG(i){this.g=i,this.demand(i.next().value,!0)}consume(){this.buffer&&this.consumed&&(this.buffer.copyWithin(0,this.consumed),this.buffer=this.buffer.subarray(0,this.buffer.length-this.consumed),this.consumed=0)}demand(i,e){return e&&this.consume(),this.need=i,this.flush()}read(i){return Lg(this,void 0,void 0,function*(){return this.lastReadPromise&&(yield this.lastReadPromise),this.lastReadPromise=new Promise((e,t)=>{var r;this.reject=t,this.resolve=n=>{delete this.lastReadPromise,delete this.resolve,delete this.need,e(n)},this.demand(i,!0)||(r=this.pull)===null||r===void 0||r.call(this,i)})})}readU32(){return this.read(ul)}readU16(){return this.read(hl)}readU8(){return this.read(ml)}close(){var i;this.g&&this.g.return(),this.buffer&&this.buffer.subarray(0,0),(i=this.reject)===null||i===void 0||i.call(this,new Error("EOF")),delete this.lastReadPromise}flush(){if(!this.buffer||!this.need)return;let i=null,e=this.buffer.subarray(this.consumed),t=0,r=s=>e.length<(t=s);if(typeof this.need=="number"){if(r(this.need))return;i=e.subarray(0,t)}else if(this.need===ul){if(r(4))return;i=e[0]<<24|e[1]<<16|e[2]<<8|e[3]}else if(this.need===hl){if(r(2))return;i=e[0]<<8|e[1]}else if(this.need===ml){if(r(1))return;i=e[0]}else if("buffer"in this.need){if("byteOffset"in this.need){if(r(this.need.byteLength-this.need.byteOffset))return;new Uint8Array(this.need.buffer,this.need.byteOffset).set(e.subarray(0,t)),i=this.need}else if(this.g){this.g.throw(new Error("Unsupported type"));return}}else{if(r(this.need.byteLength))return;new Uint8Array(this.need).set(e.subarray(0,t)),i=this.need}return this.consumed+=t,this.g?this.demand(this.g.next(i).value,!0):this.resolve&&this.resolve(i),i}write(i){if(i instanceof Uint8Array?this.malloc(i.length).set(i):"buffer"in i?this.malloc(i.byteLength).set(new Uint8Array(i.buffer,i.byteOffset,i.byteLength)):this.malloc(i.byteLength).set(new Uint8Array(i)),this.g||this.resolve)this.flush();else return new Promise(e=>this.pull=e)}writeU32(i){this.malloc(4).set([i>>24&255,i>>16&255,i>>8&255,i&255]),this.flush()}writeU16(i){this.malloc(2).set([i>>8&255,i&255]),this.flush()}writeU8(i){this.malloc(1)[0]=i,this.flush()}malloc(i){if(this.buffer){let e=this.buffer.length,t=e+i;if(t<=this.buffer.buffer.byteLength-this.buffer.byteOffset)this.buffer=new Uint8Array(this.buffer.buffer,this.buffer.byteOffset,t);else{let r=new Uint8Array(t);r.set(this.buffer),this.buffer=r}return this.buffer.subarray(e,t)}else return this.buffer=new Uint8Array(i),this.buffer}};Ii.U32=ul;Ii.U16=hl;Ii.U8=ml;var xg=128,Ug=127,jI=~Ug,XI=Math.pow(2,31);function pl(o){let i=new Ii;for(;o>=128;)i.malloc(1)[0]=o&255|xg,o>>>=7;return i.malloc(1)[0]=o&255,i.buffer||new Uint8Array(0)}function ya(o,i=0){let e=new Ii,t=i<<3;switch(typeof o){case"boolean":let r=e.malloc(2);r[0]=t,r[1]=o?1:0;break;case"number":e.malloc(1)[0]=t,e.write(pl(o));break;case"string":e.malloc(1)[0]=t|2;let s=new TextEncoder().encode(o);e.write(pl(s.length));let n=e.malloc(s.length);for(let c=0;c<s.length;c++)n[c]=s[c];break;case"object":let a=new Ii;if(Array.isArray(o))for(let c=0;c<o.length;c++){let l=ya(o[c],c+1);l&&a.write(l)}else{let c=1;for(let l in o){let h=ya(o[l],c++);h&&a.write(h)}}i===0?a.buffer&&e.write(a.buffer):(e.malloc(1)[0]=t|2,a.buffer&&(e.write(pl(a.buffer.length)),e.write(a.buffer)))}return e.buffer||new Uint8Array(0)}var qs=class{constructor(){d(this,"buffer");this.buffer=[]}get data(){return this.buffer}get length(){return this.buffer.length}writeInt32(i){this.buffer.push(i>>>24&255),this.buffer.push(i>>>16&255),this.buffer.push(i>>>8&255),this.buffer.push(i&255)}writeInt16(i){this.buffer.push(i>>>8&255),this.buffer.push(i&255)}writeByte(i){this.buffer.push(i&255)}writeBytes(i){for(let e=0;e<i.length;e++)this.buffer.push(i[e])}};function fl(o,i,e){o[e]=i>>>24&255,o[e+1]=i>>>16&255,o[e+2]=i>>>8&255,o[e+3]=i&255}function ct(o,i){return o[i]<<24|o[i+1]<<16|o[i+2]<<8|o[i+3]}function _l(o,i){return o[i]}function Lo(o,i,e){return new TextDecoder().decode(Vg(o,i,e))}function Vg(o,i,e){return o.slice(i,i+e)}var gl=0,ba=2654435769,va=16,El=4,xo=2,Uo=7;function Fg(o,i,e,t="AVQualityReportSvc.C2S",r=2e3,s=2,n=30){return{version:r,encryption:s,d2:"",d2Len:0,uinType:n,uin:"",uinLen:0,reqHead:{seqNumber:e,appId:o,appidAtThird:new Uint8Array(0),a2:"",a2Len:0,serviceCmd:t,serviceCmdLen:0,cookie:"",cookieLen:0,imei:"",imeiLen:0,ksid:"",ksidLen:0,clientVersionInfo:"",clientVersionInfoLen:0},busiBuff:i}}function Dm(o,i){let e=new qs,t=Fg(i,o,gl);gl=gl+1&2147483647,e.writeInt32(0),e.writeInt32(t.version),e.writeByte(t.encryption);let r=new TextEncoder().encode(t.d2);e.writeInt32(r.length+4),r&&e.writeBytes(r),e.writeByte(t.uinType);let s=new TextEncoder().encode(t.uin);e.writeInt32(s.length+4),s.length&&e.writeBytes(s);let n=new qs;n.writeInt32(0),n.writeInt32(t.reqHead.seqNumber),n.writeInt32(t.reqHead.appId),n.writeByte(t.reqHead.appId>>>24&255),n.writeByte(t.reqHead.appId>>>16&255),n.writeByte(t.reqHead.appId>>>8&255),n.writeByte(t.reqHead.appId&255);for(let se=4;se<16;se++)n.writeByte(0);let a=new TextEncoder().encode(t.reqHead.a2);n.writeInt32(a.length+4),a.length&&n.writeBytes(a);let c=new TextEncoder().encode(t.reqHead.serviceCmd);n.writeInt32(c.length+4),c.length&&n.writeBytes(c);let l=new TextEncoder().encode(t.reqHead.cookie);n.writeInt32(l.length+4),l.length&&n.writeBytes(l);let h=new TextEncoder().encode(t.reqHead.imei);n.writeInt32(h.length+4),h.length&&n.writeBytes(h);let m=new TextEncoder().encode(t.reqHead.ksid);n.writeInt32(m.length+4),m.length&&n.writeBytes(m);let u=new TextEncoder().encode(t.reqHead.clientVersionInfo);n.writeInt16(u.length+2),u.length&&n.writeBytes(u);let _=n.length;n.data[0]=_>>>24&255,n.data[1]=_>>>16&255,n.data[2]=_>>>8&255,n.data[3]=_&255,re(o)&&(o=new TextEncoder().encode(o)),n.writeInt32(o.length+4),o.length&&n.writeBytes(o);let g=new Uint8Array(n.data),E=null;t.encryption===1?E=new TextEncoder().encode(t.uin):t.encryption===2&&(E=new Uint8Array(16)),E&&(g=Bg(g,E)),e.writeBytes(g);let A=new Uint8Array(e.data),k=A.length;return A[0]=k>>>24&255,A[1]=k>>>16&255,A[2]=k>>>8&255,A[3]=k&255,A}function Bg(o,i){let e=o.length,r=(e+1+xo+Uo)%8;r&&(r=8-r);let s=e+1+xo+Uo+r,n=new Uint8Array(s),a=0,c=new Uint8Array(8),l=new Uint8Array(8),h=new Uint8Array(8),m=0;c[0]=Math.floor(Math.random()*256)&248|r,m=1;for(let _=0;_<r;_++)c[m]=Math.floor(Math.random()*256)&255,m+=1;for(let _=0;_<xo;)if(m<8&&(c[m]=Math.floor(Math.random()*256)&255,m+=1,_+=1),m===8){Tl(c,i,l,h,n,a),a+=8,m=0;for(let g=0;g<8;g++)h[g]=n[a-8+g]}let u=0;for(;u<e;)if(m<8&&(c[m]=o[u],m+=1,u+=1),m===8){Tl(c,i,l,h,n,a),a+=8,m=0;for(let _=0;_<8;_++)h[_]=n[a-8+_]}for(let _=0;_<Uo;)if(m<8&&(c[m]=0,m+=1,_+=1),m===8){Tl(c,i,l,h,n,a),a+=8,m=0;for(let g=0;g<8;g++)h[g]=n[a-8+g]}return n}function Tl(o,i,e,t,r,s){for(let n=0;n<8;n++)o[n]^=t[n];Hg(o,i,r,s);for(let n=0;n<8;n++)r[s+n]^=e[n];for(let n=0;n<8;n++)e[n]=o[n]}function Hg(o,i,e,t){let r=ct(o,0),s=ct(o,4),n=[];for(let c=0;c<4;c++)n[c]=ct(i,c*4);let a=0;for(let c=0;c<va;c++)a+=ba,a=a>>>0,r+=(s<<4)+n[0]^s+a^(s>>>5)+n[1],r=r>>>0,s+=(r<<4)+n[2]^r+a^(r>>>5)+n[3],s=s>>>0;fl(e,r,t),fl(e,s,t+4)}var km=function(){return new URLSearchParams(location.search).get("trtc_env")||""},Vt=o=>Number(o)<14e8,Gi=function(o,i){let e;Fs?e=Fs:e=Vt(o)?Kd:Zd;let t=Math.floor(Math.random()*hr(2,31));return`${e}/v5/AVQualityReportSvc/C2S?random=${t}&sdkappid=${o}&cmdtype=${i}`},Pm="unknown";function Da(){Gg();let{userAgent:o,connection:i}=navigator,e=(o.match(/NetType\/\S+/)||[])[0]||"";e=e.toLowerCase().replace("nettype/",""),e==="3gnet"&&(e="3g");let t=i&&i.type&&i.type.toLowerCase(),r=i&&i.effectiveType&&i.effectiveType.toLowerCase();return r==="slow-2"&&(r="2g"),t?wm(t,r):Pm}function $g(){R.warn("netType changed",Da())}var Mm=!1;function Gg(){var o;Mm||(Mm=!0,(o=navigator.connection)==null||o.addEventListener("typechange",$g))}function wm(o,i){if(_a[o])return o;switch(o){case"cellular":case"wimax":return i||"unknown";case"ethernet":return"wired";case"none":case"other":default:return"unknown"}}function Ma(o){Pm=wm(o)}function qr(){return _a[Da()]}function Lm(o,i){for(let e of Reflect.ownKeys(i))if(e!=="constructor"&&e!=="prototype"&&e!=="name"){let t=Object.getOwnPropertyDescriptor(i,e)||"";Object.defineProperty(o,e,t)}return o}function xm(o,i=48e3){return Sl(o/4,i)}function Sl(o,i=48e3){return o*1e3/i}function Um(o,i=48e3){return Il(o,i)*4}function Il(o,i=48e3){return o*i/1e3}var Al=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},Zt=()=>{let o=navigator.language;return o=o.substring(0,2),o==="zh"},dt=function(o){if(!o||typeof o!="object"||Object.prototype.toString.call(o)!="[object Object]")return!1;let i=Object.getPrototypeOf(o);if(i===null)return!0;let e=Object.prototype.hasOwnProperty.call(i,"constructor")&&i.constructor;return typeof e=="function"&&e instanceof e&&Function.prototype.toString.call(e)===Function.prototype.toString.call(Object)};function Jr(o,i=1,e=1){return o<=1?e:Jr(o-1,e,i+e)}function Kt(o){return o>8?30*1e3:Jr(o)*1e3}function Oe(o){return Reflect.apply(Object.prototype.toString,o,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var me=o=>typeof o=="function",T=o=>typeof o=="undefined",re=o=>typeof o=="string",Q=o=>typeof o=="number",he=o=>typeof o=="boolean",yt=o=>Oe(o)==="object",Ae=o=>Oe(o)==="array",Vm=o=>Oe(o)==="MediaStreamTrack".toLowerCase(),Fm=o=>o.isRemote,Er=o=>Oe(o)==="promise",jr=o=>me(o)&&o.prototype.constructor===o,Vo=o=>jr(o)?o.prototype.constructor.name:"",Bm=typeof AudioWorkletNode!="undefined",Hm=typeof HTMLMediaElement!="undefined"&&"setSinkId"in HTMLMediaElement.prototype;function Xr(o){return new Promise((i,e)=>{let t=[];o.forEach(r=>{r.then(i).catch(s=>{t.push(s),t.length===o.length&&e(t)})})})}function V(){return!performance||!performance.now?Date.now():Math.floor(performance.now())}var Om=o=>+o<10?`0${o}`:o,$m=o=>{let i=o.match(/^\d+\.\d+\.\d+/)[0];if(!i)return o;let e=i.split("."),t=Om(e[1])+Om(e[2]);return e[1]-15>0&&(e[1]="15"),e[2]-15>0&&(e[2]="15"),`${e.join(".")}.${t}`},Wg=Object.prototype.hasOwnProperty,{toString:aA}=Object.prototype;function Fo(o){if(o==null)return!0;if(typeof o=="boolean")return!1;if(typeof o=="number")return o===0;if(typeof o=="string"||typeof o=="function"||Array.isArray(o))return o.length===0;if(o instanceof Error)return o.message==="";if(dt(o))switch(Object.prototype.toString.call(o)){case"[object File]":case"[object Map]":case"[object Set]":return o.size===0;case"[object Object]":{for(let i in o)if(Wg.call(o,i))return!1;return!0}}return!1}function ei(o,i){return{userId:i,hasAudio:!!(o&_r),hasVideo:!!(o&fr),hasAuxiliary:!!(o&Hr),hasSmall:!!(o&Bs),audioMuted:!!(o&Ia),videoMuted:!!(o&Aa),audioAvailable:!!(o&_r)&&!(o&Ia),videoAvailable:!!(o&fr)&&!(o&Aa)}}function Gm(o){let i={urls:o.url.startsWith("turn:")||o.url.startsWith("turns:")?o.url:`turn:${o.url}`};return!T(o.username)&&!T(o.credential)&&(i.username=o.username,i.credential=o.credential,i.credentialType="password",T(o.credentialType)||(i.credentialType=o.credentialType)),i}function Bo(o,i=!0){if(!re(o))return 0;let e=o.split(".");return i?(Number(e[0])<<24|Number(e[1])<<16|Number(e[2])<<8|Number(e[3]))>>>0:(Number(e[3])<<24|Number(e[2])<<16|Number(e[1])<<8|Number(e[0]))>>>0}var ti=function(o,i,e,t){if(!(yt(o)&&yt(i)))return 0;let r=0,s=Object.keys(i),n;for(let a=0,c=s.length;a<c;a++)if(n=s[a],!(T(i[n])||e&&e.includes(n)))if(yt(o[n])&&yt(i[n]))r+=ti(o[n],i[n],e,t);else{if(t&&t.includes(i[n]))continue;o[n]!==i[n]&&(o[n]=Wr(i[n]),r+=1)}return r};function Wr(o){if(Ae(o)){let i=[];return o.forEach((e,t)=>{i[t]=Wr(e)}),i}if(yt(o)){let i={};return Object.keys(o).forEach(e=>{i[e]=Wr(o[e])}),i}return o}var Ho=o=>{let i=[];if(Ae(o))i=[...o];else if(re(o)){let e=document.getElementById(o);e&&i.push(e)}else o&&i.push(o);return i},Wm=o=>re(o)?document.getElementById(o):o,qg=o=>{let i=c=>c<10?`0${c}`:`${c}`,e=o.getFullYear(),t=o.getMonth()+1,r=o.getDate(),s=i(o.getHours()),n=i(o.getMinutes()),a=i(o.getSeconds());return`${e}/${t}/${r} ${s}:${n}:${a}`},qm=()=>qg(new Date);function _t(o,{keysToInclude:i,keysToExclude:e}){try{if(Ae(o))return`[${o.map(n=>_t(n,{keysToInclude:i,keysToExclude:e})).join(",")}]`;if(!dt(o)||!Ae(i)&&!Ae(e))return JSON.stringify(o);let t={},r=new Set(i),s=new Set(e);return Object.keys(o).forEach(n=>{(s.size===0&&r.has(n)||r.size===0&&!s.has(n))&&(t[n]=dt(o[n])||Ae(o[n])?JSON.parse(_t(o[n],{keysToExclude:e,keysToInclude:i})):o[n])}),JSON.stringify(t)}catch(t){return"{}"}}function Js(o,i=!1){let e=[];return Object.keys(o).forEach(t=>{i===o[t]&&e.push(t)}),_t(o,{keysToInclude:e})}function js(o){return o.replace(/[\u4e00-\u9fa5]/g,"aa").length}var Cl=()=>{var o,i,e,t;return(o=window.screen)!=null&&o.orientation?!!((t=(e=(i=window.screen)==null?void 0:i.orientation)==null?void 0:e.type)!=null&&t.includes("portrait")):window.orientation===0||window.orientation===180},$o=o=>f(void 0,null,function*(){return new Promise((i,e)=>{let t;if(re(o))t=new Image,t.crossOrigin="anonymous",t.src=o;else if(t=o,t.complete){i(t);return}t.onload=()=>i(t),t.onerror=()=>{e(new D({code:I.INVALID_PARAMETER,message:`load image failed, url: ${o}`}))}})}),Oa=o=>{let i=o.split(".");return+i[0]<<24|+i[1]<<16|+i[2]<<8|+i[3]<<0},Xs=o=>(Object.keys(o).forEach(i=>{Q(o[i])&&(i.startsWith("uint")||i.startsWith("int"))?o[i]=Math.floor(o[i]):(dt(o[i])||Ae(o[i]))&&Xs(o[i])}),o);function Ge(o,i){return new Promise(e=>{let t=setTimeout(e,o);i&&i(t)})}function ka(o,i){let e=null;return function(...t){return e||(e=o.apply(i||this,t),e.finally(()=>e=null),e)}}function Pa(o){return o.replace(/(^|[^:])\/{2,}/g,"$1/")}function wa(o){var i;try{let{width:e,height:t,frameRate:r,sampleRate:s,sampleSize:n,channelCount:a}=(i=o.getSettings)==null?void 0:i.call(o),c=o.kind===p.AUDIO?`${s}x${n}@${a}`:`${e}x${t}@${r}`,l=o.stats?` stats: ${JSON.stringify(o.stats).replaceAll('"',"")}`:"";return`${o.id} ${o.readyState} muted:${o.muted} ${o.kind} ${o.label} ${c}${l}`}catch(e){return""}}function Go(o,i){return o.width*o.height===i.width*i.height?1:Cl()&&i.width>i.height&&o.height>i.width?Math.max(o.width/i.height,o.height/i.width,1):Math.max(o.width/i.width,o.height/i.height,1)}function bt(o){return o===90||o===270}function Jm(o){return f(this,null,function*(){return new Promise((i,e)=>{let t=document.createElement("video");t.crossOrigin="anonymous",t.src=o,t.muted=!0,t.loop=!0,t.playsInline=!0,t.play().then(()=>i(t)),t.onerror=()=>{e(t.error)}})})}function Na(o,i=new WeakMap){if(typeof o!="object"||o===null)return o;if(i.has(o))return i.get(o);if(Array.isArray(o)){let e=[];return i.set(o,e),o.forEach((t,r)=>{e[r]=Na(t,i)}),e}if(Object.prototype.toString.call(o)==="[object Object]"){let e={};return i.set(o,e),Reflect.ownKeys(o).forEach(t=>{e[t]=Na(o[t],i)}),e}return o}var Wo=(t=>(t[t.END_REPORT=2001]="END_REPORT",t[t.LOG=2002]="LOG",t[t.KEY_METRIC_REPORT=2003]="KEY_METRIC_REPORT",t))(Wo||{});function Jg(o,i,e,t){let r={data:o,random:Math.floor(Math.random()*2147483648),sdkAppId:e};return T(t)||(r=L(O({},r),{gzip:+t})),{uint32_sdkappid:0,uint64_from_uin:0,uint32_timestamp:0,uint32_seq:0,msg_common_info:{msg_device_info:{enum_device_type:0,str_device_brand:"",str_device_model:"",str_device_board:"",str_device_cpu_abi:""},msg_system_info:{enum_os_type:0,str_os_version:"",msg_network_info:0},msg_network_info:{enum_network_type:0}},msg_report_content:{uint32_type:i,bytes_report_data:JSON.stringify(r)}}}function Wi(o,i,e,t){try{let r=Jg(o,i,e,t),s=ya(r);return Dm(s,e)}catch(r){return JSON.stringify(o)}}function La(o,i){let e=new Uint8Array(o.byteLength+i.byteLength);return e.set(new Uint8Array(o),0),e.set(new Uint8Array(i),o.byteLength),e.buffer}function xa(o){return(o&65535)>>>0}function jm(o){return(o&4294901760)>>>0}function Xm(o){let i=jg(o);return i==null?void 0:i.busiBuff}function jg(o){try{let i={},e=0;i.totalLength=ct(o,e),e+=4,i.version=ct(o,e),e+=4,i.encryption=_l(o,e),e+=1,i.uinType=_l(o,e),e+=1,i.uinLength=ct(o,e),e+=4,i.uin=i.uinLength>4?Lo(o,e,i.uinLength-4):"",e+=i.uinLength-4;let t=o.slice(e);if(i.encryption===2){let r=new Uint8Array(16).fill(0);o=Xg(t,r),i.decrypted=!0,e=0}else o=t,e=0;return i.rspHeadLength=ct(o,e),e+=4,i.seqNo=ct(o,e),e+=4,i.retCode=ct(o,e),e+=4,i.retStrLength=ct(o,e),e+=4,i.retStr=i.retStrLength?Lo(o,e,i.retStrLength-4):"",e+=i.retStrLength-4,i.serviceCmdLength=ct(o,e),e+=4,i.serviceCmd=i.serviceCmdLength?Lo(o,e,i.serviceCmdLength-4):"",e+=i.serviceCmdLength-4,i.cookieLength=ct(o,e),e+=4,i.cookie=i.cookieLength?Lo(o,e,i.cookieLength-4):"",e+=i.cookieLength-4,i.flag=ct(o,e),e+=4,i.busiBuffLength=ct(o,e),e+=4,i.busiBuff=i.busiBuffLength?Lo(o,e,i.busiBuffLength-4):"",e+=i.busiBuffLength-4,i}catch(i){}}function zm(o,i){let e=o[0]<<24|o[1]<<16|o[2]<<8|o[3],t=o[4]<<24|o[5]<<16|o[6]<<8|o[7];e=e>>>0,t=t>>>0;let r=ba*va>>>0;for(let s=0;s<va;s++)t-=(e<<El)+i[2]^e+r^(e>>>5)+i[3],t=t>>>0,e-=(t<<El)+i[0]^t+r^(t>>>5)+i[1],e=e>>>0,r-=ba,r=r>>>0;return new Uint8Array([e>>>24&255,e>>>16&255,e>>>8&255,e&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255])}function Xg(o,i){let e=0,t=new Uint8Array(8).fill(0),r=new Uint8Array(o.slice(0,8)),s=zm(r,i),n=s[0]&7,a=o.length-1-n-xo-Uo,c=new Uint8Array(a),l=0,h=t,m=o.slice(0,8);e=8;let u=1;u+=n;for(let g=1;g<=xo;)if(u<8)u++,g++;else if(u===8){let E=Rl(o,e,h,m,s,i);h=E.ivPreCrypt,m=E.ivCurCrypt,s=E.debiBuf,e=E.bufPos,u=0}let _=a;for(;_>0;)if(u<8)c[l++]=s[u]^h[u],u++,_--;else if(u===8){let g=Rl(o,e,h,m,s,i);h=g.ivPreCrypt,m=g.ivCurCrypt,s=g.debiBuf,e=g.bufPos,u=0}for(let g=1;g<=Uo;)if(u<8)s[u]^h[u],u++,g++;else if(u===8){if(e>=o.length)break;let E=Rl(o,e,h,m,s,i);if(!E.success)break;h=E.ivPreCrypt,m=E.ivCurCrypt,s=E.debiBuf,e=E.bufPos,u=0}return c}function Rl(o,i,e,t,r,s){if(i+8>o.length)return{success:!1};let n=new Uint8Array(t),a=o.slice(i,i+8),c=new Uint8Array(8);for(let h=0;h<8;h++)c[h]=r[h]^a[h];let l=zm(c,s);return{success:!0,ivPreCrypt:n,ivCurCrypt:a,debiBuf:l,bufPos:i+8}}var Qm=typeof TextDecoder!="undefined"?new TextDecoder:void 0;function qi({url:o,body:i,method:e="POST",timeout:t,priority:r}){return new Promise((s,n)=>{if("fetch"in window)return fetch(o,{method:e,body:i,priority:r}).then(c=>c.clone().json().then(l=>({data:l}),()=>c.arrayBuffer().then(l=>({data:Xm(new Uint8Array(l))||(Qm?Qm.decode(l):l)})))).then(s,n);let a=new XMLHttpRequest;a.onreadystatechange=()=>{if(a.readyState===4)if(a.status>=200&&a.status<300)try{let c=JSON.parse(a.response);s({data:c})}catch(c){s({data:a.response})}else n({status:a.status,statusText:a.statusText||"request failed!"})},a.timeout=t||5e3,a.open(e,o,!0),a.send(i)})}function yl(o){return f(this,null,function*(){let i=V(),e=JSON.stringify(o);try{if(!CompressionStream||e.length<=2800)return e;let r=new Blob([e],{type:"application/json"}).stream().pipeThrough(new CompressionStream("gzip")),a=yield(yield(yield new Response(r)).blob()).arrayBuffer();return R.debug(`compressJSON ${e.length} -> ${a.byteLength} ${V()-i}ms`),a}catch(t){return e}})}var zg=Object.prototype.hasOwnProperty;var Ai=o=>typeof o=="function",gt=o=>typeof o=="undefined";var Ua=o=>typeof o=="boolean";var bl=o=>o.isRemote;var vl=function(o){if(!o||typeof o!="object"||Object.prototype.toString.call(o)!="[object Object]")return!1;let i=Object.getPrototypeOf(o);if(i===null)return!0;let e=Object.prototype.hasOwnProperty.call(i,"constructor")&&i.constructor;return typeof e=="function"&&e instanceof e&&Function.prototype.toString.call(e)===Function.prototype.toString.call(Object)};function Ym(o){if(o==null)return!0;if(typeof o=="boolean")return!1;if(typeof o=="number")return o===0;if(typeof o=="string"||typeof o=="function"||Array.isArray(o))return o.length===0;if(o instanceof Error)return o.message==="";if(vl(o))switch(Object.prototype.toString.call(o)){case"[object File]":case"[object Map]":case"[object Set]":return o.size===0;case"[object Object]":{for(let i in o)if(zg.call(o,i))return!1;return!0}}return!1}var Qg=0,Yg=1,Zm=2;function Zg({retryFunction:o,settings:i,onError:e,onRetrying:t,onRetryFailed:r,onRetrySuccess:s,context:n}){return function(...a){let{retries:c=5,timeout:l=1e3}=i,h=0,m=-1,u=Qg,_=(g,E)=>f(this,null,function*(){let A=n||this;try{let k=yield o.apply(A,a);h>0&&s&&s.call(this,h),h=0,g(k)}catch(k){let se=()=>{clearTimeout(m),h=0,u=Zm,E(k)},w=()=>{u!==Zm&&h<(Ai(c)?c():c)?(h++,u=Yg,Ai(t)&&t.call(this,h,se),m=window.setTimeout(()=>{m=-1,_(g,E)},Ai(l)?l(h):l)):(se(),Ai(r)&&r.call(this,k))};Ai(e)?e.call(this,{error:k,retry:w,reject:E,retryFuncArgs:a,retriedCount:h}):w()}});return new Promise(_)}}var Ci=Zg;var Sr=class o{constructor(i){d(this,"_parentPath");d(this,"userId");d(this,"remoteUserId");d(this,"id");d(this,"sdkAppId");d(this,"type");d(this,"isLocal");this.id=i.id,this.userId=i.userId,this.sdkAppId=i.sdkAppId,this.remoteUserId=i.remoteUserId,this.isLocal=Ua(i.isLocal)?i.isLocal:!0,this.type=this.isLocal?"":i.type}getFullId(){return this._parentPath&&this.id?`${this._parentPath}-${this.id}`:this._parentPath?this._parentPath:this.id}createChild(i){let e=new o({id:i.id,userId:gt(i.userId)?this.userId:i.userId,sdkAppId:gt(i.sdkAppId)?this.sdkAppId:i.sdkAppId,type:gt(i.type)?this.type:i.type,isLocal:gt(i.isLocal)?this.isLocal:i.isLocal,remoteUserId:gt(i.remoteUserId)?this.remoteUserId:i.remoteUserId});return e.bindParent(this),e}bindParent(i){let e=i.getFullId();this._parentPath!==e&&(this.debug(`bind logger parent: ${i.id}`),this._parentPath=e,this.userId=i.userId||this.userId,this.sdkAppId=i.sdkAppId||this.sdkAppId)}setUserId(i){this.userId=i}setSdkAppId(i){this.sdkAppId=i}log(i,e){let t=this.isLocal?this.userId:this.remoteUserId,r=this.getFullId();e.unshift(`[${this.isLocal?"\u2191":"\u2193"}${this.type&&this.type!=="main"?"*":""}${r}${t?`|${t}`:""}]`),R.log(i,e,gt(this.userId)||Ym(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 ts={};Vi(ts,{ANDROID_VERSION:()=>Ha,CHROME_MAJOR_VERSION:()=>je,CHROME_VERSION:()=>oc,EDGE_VERSION:()=>Ga,EDG_MAJOR_VERSION:()=>Dl,EDG_VERSION:()=>Wa,ELECTRON_MAJOR_VERSION:()=>wl,FIREFOX_MAJOR_VERSION:()=>jo,FIREFOX_VERSION:()=>$a,HUAWEI_VERSION:()=>ec,IE_VERSION:()=>rT,IOS_MAIN_VERSION:()=>et,IOS_VERSION:()=>Tt,IPADQQB_VERSION:()=>Za,IS_ANDROID:()=>fe,IS_ANDROID_WEBVIEW:()=>aT,IS_ANY_SAFARI:()=>Bt,IS_CHROME:()=>es,IS_CHROME_OS:()=>Ml,IS_CHROMIUM_BASE:()=>We,IS_DESKTOP_IOS_CHROME:()=>Vl,IS_EDG:()=>Xo,IS_EDGE:()=>zr,IS_ELECTRON:()=>sT,IS_FIREFOX:()=>te,IS_HEADLESS_CHROME:()=>Pl,IS_HONOR:()=>kl,IS_HUAWEI:()=>sn,IS_HUAWEIBROWSER:()=>on,IS_IE:()=>ip,IS_IE8:()=>iT,IS_IOS:()=>Ee,IS_IOS_13_OR_14:()=>Ul,IS_IOS_15_1:()=>xl,IS_IOS_CHROME:()=>zs,IS_IPAD:()=>Jo,IS_IPADQQB:()=>en,IS_IPAD_PRO:()=>Nl,IS_IPHONE:()=>Ir,IS_IPOD:()=>tp,IS_LINUX:()=>tn,IS_LOCAL:()=>si,IS_MAC:()=>oi,IS_MACQQB:()=>Ks,IS_MIBROWSER:()=>rn,IS_MQQB:()=>Qo,IS_NATIVE_ANDROID:()=>tT,IS_OLD_ANDROID:()=>eT,IS_OPENHARMONY:()=>Zo,IS_OPPOBROWSER:()=>Yo,IS_SAFARI:()=>Ce,IS_SAFARI_15_1:()=>cT,IS_SAMSUNGBROWSER:()=>nn,IS_SOGOU:()=>Ys,IS_SOGOUM:()=>Qs,IS_TBS:()=>ri,IS_UCBROWSER:()=>Ol,IS_VIVOBROWSER:()=>an,IS_WECHAT:()=>ji,IS_WIN:()=>Qr,IS_WQQB:()=>Zs,IS_WX:()=>oT,IS_X5MQQB:()=>zo,IS_XWEB:()=>Ji,MACQQB_VERSION:()=>Ya,MI_VERSION:()=>Ka,MQQB_VERSION:()=>qo,OPENHARMONY_VERSION:()=>nT,OPPO_VERSION:()=>ic,SAFARI_VERSION:()=>Xi,SAMSUNG_VERSION:()=>tc,SOGOUM_VERSION:()=>qa,SOGOU_VERSION:()=>Ja,TBS_VERSION:()=>ja,UA_DATA_STRING:()=>ii,USER_AGENT:()=>Ft,VIVO_VERSION:()=>rc,WECHAT_VERSION:()=>za,WQQB_VERSION:()=>Qa,XWEB_VERSION:()=>Xa,browserInfo:()=>Ri,getBrowserCoreNumber:()=>Bl,getBrowserInfo:()=>rp,getChromeMajorVersion:()=>Ko,getDeviceModel:()=>ni,getDeviceModelFromUA:()=>sc,getGPUInfo:()=>ln,getOSName:()=>nc,getOSNumber:()=>Zr,getOSString:()=>ai,getOSType:()=>lT,getTerminalType:()=>Hl,getUserAgentData:()=>Yr,isAMDGPU:()=>Fl,isLocalStorageEnabled:()=>zi,isMobile:()=>dn,isNvidiaGPU:()=>dT,isRealIOS:()=>Ba,isVersionLargerThan:()=>Ll,isVersionSmallerThan:()=>cn});var Ft=typeof navigator=="undefined"?"":navigator.userAgent,ee=o=>new RegExp(o,"i").test(Ft),Le=o=>{if(ee(o)){let i=new RegExp(`${o}\\/([\\d.]+)`),e=Ft.match(i);if(e&&e[1])return e[1]}return""},Fa=o=>{if(ee(o)){let i=new RegExp(`${o}\\/(\\d+)`),e=Ft.match(i);if(e&&e[1])return parseFloat(e[1])}return NaN},Km=/AppleWebKit\/([\d.]+)/i.exec(Ft),Kg=Km?parseFloat(Km[1]):NaN,Jo=ee("iPad"),Nl=typeof navigator!="undefined"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&ee("Macintosh"),Ir=ee("iPhone")&&!Jo,tp=ee("iPod"),Ee=Ir||Jo||tp||Nl,Ba=()=>{try{return Ee&&navigator.maxTouchPoints>1&&navigator.vendor.includes("Apple")}catch(o){return Ee}},fe=ee("Android"),Ha=function(){if(fe){let o=Ft.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(o){let i=o[1]&&parseFloat(o[1]),e=o[2]&&parseFloat(o[2]);if(i&&e)return parseFloat(`${o[1]}.${o[2]}`);if(i)return i}}return NaN}(),eT=fe&&ee("webkit")&&Ha<2.3,tT=fe&&Ha<5&&Kg<537,te=ee("Firefox"),$a=Le("Firefox"),jo=Fa("Firefox"),zr=ee("Edge"),Ga=Le("Edge"),Xo=ee("Edg"),Wa=Le("Edg"),Dl=Fa("Edg"),Qs=ee("SogouMobileBrowser"),qa=Le("SogouMobileBrowser"),Ys=ee("MetaSr\\s"),Ja=Le("MetaSr\\s"),ri=ee("TBS"),ja=Le("TBS"),Ji=ee("XWEB"),Xa=Le("XWEB"),iT=ee("MSIE\\s8\\.0"),ip=ee("MSIE\\/\\d+"),rT=function(){if(ip){let o=/MSIE\s(\d+)\.\d/.exec(Ft),i=o&&parseFloat(o[1]);return!i&&/Trident\/7.0/i.test(Ft)&&/rv:11.0/.test(Ft)&&(i=11),i}return NaN}(),ji=ee("(micromessenger|webbrowser)"),za=Le("MicroMessenger"),zo=!ri&&ee("MQQBrowser")&&ee("COVC"),Qo=!ri&&ee("MQQBrowser")&&!ee("COVC"),qo=Qo||zo?Le("MQQBrowser"):"",Zs=!ri&&ee(" QQBrowser"),Qa=Le(" QQBrowser"),Ks=!ri&&ee("QQBrowserLite"),Ya=Le("QQBrowserLite"),en=!ri&&ee("MQBHD"),Za=Le("MQBHD"),Qr=ee("Windows"),oi=!Ee&&ee("MAC OS X"),tn=!fe&&ee("Linux"),Ml=ee("CrOS"),oT=ee("MicroMessenger"),Ol=ee("UCBrowser"),sT=ee("Electron"),rn=ee("MiuiBrowser"),Ka=Le("MiuiBrowser"),on=ee("HuaweiBrowser"),sn=ee("Huawei")||ee("HUAWEI"),kl=ee("Honor")||ee("HONOR"),ec=Le("HuaweiBrowser"),nn=ee("SamsungBrowser"),tc=Le("SamsungBrowser"),Yo=ee("HeyTapBrowser"),ic=Le("HeyTapBrowser"),an=ee("VivoBrowser"),rc=Le("VivoBrowser"),Zo=ee("OpenHarmony"),nT=Le("OpenHarmony"),Ko=()=>Fa("Chrome"),zs=ee("CriOS"),We=ee("Chrome"),es=!zr&&!Ys&&!Qs&&!ri&&!Ji&&!Xo&&!Zs&&!rn&&!on&&!nn&&!Yo&&!an&&We,Pl=ee("HeadlessChrome"),je=Ko(),oc=Le("Chrome"),wl=Fa("Electron"),Ce=!We&&!Qo&&!zo&&!Ks&&!en&&ee("Safari"),Bt=Ce||Ee,Xi=Le("Version"),aT=/Android.*(wv|.0.0.0)/.test(Ft),Tt=(()=>{if(Nl)return Xi;if(Ee){let o=Ft.match(/OS (\d+)_(\d+)/i);if(o&&o[1]){let i=o[1];return o[2]&&(i+=`.${o[2]}`),i}}return""})();function cn(o,i){let e=o.split(".").map(r=>Number(r)),t=i.split(".").map(r=>Number(r));for(let r=0;r<Math.max(e.length,t.length);r++){let s=e[r]||0,n=t[r]||0;if(s<n)return!0;if(s>n)return!1}return!1}function Ll(o,i,e=!1){let t=o.split(".").map(s=>Number(s)),r=i.split(".").map(s=>Number(s));for(let s=0;s<Math.max(t.length,r.length);s++){let n=t[s]||0,a=r[s]||0;if(n>a)return!0;if(n<a)return!1}return e}var et=Number(Tt.split(".")[0]),cT=Xi==="15.1",xl=Tt==="15.1",Ul=(()=>{let o=Number(Tt.split(".")[0]);return o===14||o===13})(),Vl=zs&&Xi==="11.1.1",si=typeof location=="undefined"?!1:location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1",zi=(()=>{let o;return()=>{if(typeof o=="undefined")try{o=!!window.localStorage}catch(i){o=!1}return o}})(),Ri=rp();function rp(){let o=new Map([[te,["Firefox",$a]],[Xo,["Edg",Wa]],[es,["Chrome",oc]],[zs,["ChiOS",Le("CriOS")]],[Ce&&!zs,["Safari",Xi]],[ri,["TBS",ja]],[Ji,["XWEB",Xa]],[ji&&Ir,["WeChat",za]],[Zs,["QQ(Win)",Qa]],[Qo,["QQ(Mobile)",qo]],[zo,["QQ(Mobile X5)",qo]],[Ks,["QQ(Mac)",Ya]],[en,["QQ(iPad)",Za]],[rn,["MI",Ka]],[on,["HW",ec]],[nn,["Samsung",tc]],[Yo,["OPPO",ic]],[an,["VIVO",rc]],[zr,["EDGE",Ga]],[Qs,["SogouMobile",qa]],[Ys,["Sogou",Ja]]]),i="unknown",e="unknown";return o.has(!0)&&([i,e]=o.get(!0)),{name:i,version:e}}var pe=null;function dn(){return pe&&typeof pe.mobile=="boolean"?pe.mobile:fe||Ee||Ir||Jo||Zo}var ii="";function Yr(){return f(this,null,function*(){if(pe)return pe;if(!navigator.userAgentData||typeof navigator.userAgentData.getHighEntropyValues!="function")return null;try{return pe=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]),pe&&!ii&&(ii=`UAData: ${pe.platform}/${pe.platformVersion}`,pe.architecture&&pe.bitness&&(ii+=` ${pe.architecture}/${pe.bitness}`),pe.mobile&&(ii+=" mobile"),pe.model&&(ii+=` model: ${pe.model.replace(/\s+/g,"/")}`),pe.fullVersionList&&(ii+=` ${pe.fullVersionList.filter(o=>o.brand!=="Not/A)Brand").map(o=>`${o.brand}/${o.version}`).join(",")}`)),pe}catch(o){return null}})}var Va="";function ln(){try{if(Va)return Va;let o=document.createElement("canvas"),i=o.getContext("webgl")||o.getContext("experimental-webgl");if(!i)return"";let e=i.getExtension("WEBGL_debug_renderer_info");if(e){let t=i.getParameter(e.UNMASKED_VENDOR_WEBGL),r=i.getParameter(e.UNMASKED_RENDERER_WEBGL);return Va=`${t} ${r}`,Va}return""}catch(o){return""}}function Fl(){try{let o=ln();return o.includes("AMD")||o.includes("ATI")}catch(o){return!1}}function dT(){try{let o=ln();return o.includes("NVIDIA")||o.includes("GeForce")}catch(o){return!1}}function ni(){return(pe==null?void 0:pe.model)||sc()||""}function sc(){let o=/;\s*([^;)]+)\s+Build\//,i=Ft.match(o);return i!=null&&i[1]?i[1].trim():null}var ep=new Map([[fe,"Android"],[Ee,"iOS"],[Qr,"Windows"],[oi,"MacOS"],[tn,"Linux"],[Ml,"ChromeOS"]]),nc=function(){return ep.get(!0)?ep.get(!0):pe?pe.platform:"unknown"};function Zr(){return Qr?1:fe?2:oi?3:Ee?4:tn?5:Ml?6:Zo?7:0}function Bl(){return ji||Ji?4:We?1:Ce?2:te?3:0}var ai=()=>{let o=nc();return pe!=null&&pe.platformVersion?o+=`/${pe.platformVersion}`:Ee?o+=`/${Tt}`:fe&&(o+=`/${Ha}`),o+=`/${Ri.name}/${Ce&&!zs?Ri.version:Ri.version.split(".")[0]}`,pe!=null&&pe.architecture&&(o+=`/${pe.architecture}`),o};function Hl(){return fe?4:Ir?2:Jo?3:oi?12:Qr?5:tn?13:Zo?22:1}function lT(){return fe?"Android":Ir?"iPhone":Jo?"iPad":oi?"Mac":Qr?"Windows":tn?"Linux":"unknown"}var op=Je(at(),1),uT=new op.default,S=uT;var mt=(G=>(G.ROOM_DESTROY="1",G.JOIN_START="21",G.JOIN_SCHEDULE_SUCCESS="22",G.JOIN_SIGNAL_CONNECTION_START="23",G.JOIN_SIGNAL_CONNECTION_END="24",G.JOIN_SEND_CMD="25",G.JOIN_RECEIVED_CMD_RES="26",G.JOIN_SUCCESS="27",G.JOIN_FAILED="28",G.LEAVE_START="51",G.LEAVE_SEND_CMD="52",G.LEAVE_SUCCESS="53",G.PUBLISH_START="61",G.SEND_FIRST_VIDEO_FRAME="62",G.PUBLISH_FAILED="63",G.SUBSCRIBE_START="81",G.SUBSCRIBE_SUCCESS="82",G.SUBSCRIBE_FAILED="84",G.UNSUBSCRIBE_SUCCESS="83",G.LOCAL_TRACK_CAPTURE_START="101",G.LOCAL_TRACK_CAPTURE_SUCCESS="102",G.LOCAL_TRACK_CAPTURE_FAILED="103",G.LOCAL_TRACK_PUBLISHED="104",G.LOCAL_TRACK_UNPUBLISHED="105",G.LOCAL_TRACK_REPLACED="106",G.SWITCH_DEVICE_SUCCESS="107",G.TRACK_MUTED="108",G.TRACK_UNMUTED="109",G.REMOTE_TRACK_SUBSCRIBED="110",G.REMOTE_TRACK_UNSUBSCRIBED="111",G.LOCAL_TRACK_RECAPTURE="112",G.LOCAL_AUDIO_STARTED="113",G.LOCAL_AUDIO_STOPPED="114",G.REMOTE_AUDIO_STARTED="115",G.REMOTE_AUDIO_STOPPED="116",G.PLAY_TRACK_START="151",G.PLAYER_STATE_CHANGED="152",G.VIDEO_LOADED_DATA="153",G.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",G.AUDIO_CONTEXT_LONG_SUSPENDED="155",G.REMOTE_VIDEO_PLAY_START="156",G.REMOTE_VIDEO_PLAY_FINISH="157",G.SIGNAL_CONNECTION_STATE_CHANGED="201",G.PEER_CONNECTION_STATE_CHANGED="202",G.SINGLE_CONNECTION_STAT="203",G.SPC_RECONNECTED="204",G.HEARTBEAT_REPORT="251",G.RECEIVED_PUBLISHED_USER_LIST="252",G.REMOTE_PUBLISH_STATE_CHANGED="253",G.AUDIO_LEVEL_INTERVAL="260",G.NETWORK_QUALITY="261",G.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",G.QUALITY_LIMITATION_CHANGED="263",G.LOG="264",G.AUDIO_PROCESSOR_DEBUG="265",G.SSO_SWITCH="266",G.SEI_MESSAGE="267",G.USER_PAUSE_IN_PIP="268",G.USER_RESUME_IN_PIP="269",G.ENTER_PICTURE_IN_PICTURE="270",G.LEAVE_PICTURE_IN_PICTURE="271",G.SWITCH_ROOM_START="401",G.SWITCH_ROOM_SUCCESS="407",G.SWITCH_ROOM_FAILED="408",G))(mt||{});var C=mt;var $l=class{constructor(){d(this,"enable",!1);d(this,"ssoFailCount",0);S.on("22",({schedule:i})=>{var e;(e=i==null?void 0:i.config)!=null&&e.sso&&S.emit("266",{enable:!0})}),S.on("266",({enable:i})=>{this.enable=i})}handleUploadFailed(){this.ssoFailCount++,this.ssoFailCount>3&&S.emit("266",{enable:!1})}},Ar=new $l;var hT="%cTRTC%c%s",mT="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",pT="display: inline",ac=class ac{constructor(){d(this,"_isEnableUploadLog",!0);d(this,"_localJoinedUser",new Map);d(this,"_queue",[]);d(this,"_timeoutId",-1);d(this,"_logLevel",1);d(this,"_logLevelToUpload",2);!Oo&&!Vs&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){S.on(C.JOIN_SCHEDULE_SUCCESS,({schedule:i})=>{var e;(e=i==null?void 0:i.config)!=null&&e.logLevelToUpload&&zt[i.config.logLevelToUpload]&&(this._logLevelToUpload=i.config.logLevelToUpload)}),S.on(C.JOIN_START,({params:i})=>{this.addJoinedUser({userId:i.userId,sdkAppId:i.sdkAppId}),this.startUpload()}),S.on(C.LEAVE_SUCCESS,({room:i})=>{this.deleteJoinedUser(i.userId)})}startUpload(){this._timeoutId===-1&&this.uploadInterval()}addJoinedUser(i){this._localJoinedUser.set(i.userId,i),this.startUpload()}deleteJoinedUser(i){this._localJoinedUser.delete(i)}uploadInterval(){this.upload().catch(()=>{}),this._timeoutId=window.setTimeout(()=>this.uploadInterval(),5e3)}getLogsToUpload(){let i={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&this._localJoinedUser.size===0)return i;let e=0;for(;e<this._queue.length&&e!==50;e++){let t=this._queue[e];if(t.forAllJoinedClients)this._localJoinedUser.forEach(({userId:r,sdkAppId:s})=>{i.map.has(r)?i.map.get(r).logs.push(t):i.map.set(r,{userId:r,sdkAppId:s,logs:[t]})});else if(re(t.userId)&&Q(t.sdkAppId)){let{userId:r,sdkAppId:s}=t;i.map.has(r)?i.map.get(r).logs.push(t):i.map.set(r,{userId:r,sdkAppId:s,logs:[t]})}}return i.map.size>0&&(i.splicedQueue=this._queue.splice(0,e)),i}upload(){return f(this,null,function*(){if(this._queue.length===0||!this._isEnableUploadLog)return;let{map:i,splicedQueue:e}=this.getLogsToUpload();if(i.size===0)return;try{let r=[...i.values()];for(let s=0;s<r.length;s++){let{userId:n,sdkAppId:a,logs:c}=r[s],l={timestamp:ma(),sdkAppId:String(a),userId:n,version:$e,log:c.map(u=>u.log).join(`
6
+ `)},h=JSON.stringify(l),m=Ar.enable?Wi(l,2002,a):h;yield this.uploadLogWithRetry(m,a,m instanceof Uint8Array,h),c.forEach(u=>u.uploaded=!0)}}catch(r){}let t=e.filter(r=>!r.uploaded);t.length>0&&(this._queue=t.concat(this._queue))})}uploadLogWithRetry(i,e,t,r){return Ci({retryFunction:()=>qi({url:Gi(e,mr.LOG),body:i,timeout:5e3,priority:"low"}).then(s=>{t&&s.data!=="ok"&&(Ar.handleUploadFailed(),this.uploadLogWithRetry(r,e,!1,r))}),settings:{retries:3,timeout:2e3},onError:({retry:s})=>{s()}})()}getPrefix(i){let e=new Date;return e.setTime(Fi()),`[${Mo(e)}] <${zt[i]}>`}getLogLevel(){return this._logLevel}setLogLevel(i){T(zt[i])||(this._logLevel!==i&&this.info("setLogLevel",i),this._logLevel=i)}enableUploadLog(){this._isEnableUploadLog=!0}disableUploadLog(){this.warn("disableUploadLog"),this._isEnableUploadLog=!1}logChunkToString(i){if(re(i))return i;try{return i instanceof Error?i.toString():JSON.stringify(i)}catch(e){return""}}addLogToQueue(i,e,t=!0,r,s){let n={log:e.reduce((a,c)=>`${a} ${this.logChunkToString(c)}`.trim(),""),level:i,userId:r,sdkAppId:s,forAllJoinedClients:t};S.emit(C.LOG,{log:n}),this._isEnableUploadLog&&i>=this._logLevelToUpload&&this._queue.push(n)}log(i,e,t=!0,r,s){var a;if(e.unshift(this.getPrefix(i)),this.addLogToQueue(i,e,t,r,s),i<this._logLevel)return;let n=((a=zt[i])==null?void 0:a.toLowerCase())||"info";ac.PRINT_LOG_TAG?console[n](hT,mT,pT,...e):console[n](...e)}debug(...i){this.log(1,i)}info(...i){this.log(2,i)}warn(...i){this.log(3,i)}error(...i){this.log(4,i)}createLogger(i){if(i.parent instanceof Sr){let e=i,{parent:t}=e,r=la(e,["parent"]),s=new Sr(r);return s.bindParent(t),s}return new Sr(i)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;zt[t]&&(this._logLevelToUpload=t)}getQueue(){return this._queue}};d(ac,"PRINT_LOG_TAG",!(Ee||fe||Pl));var Gl=ac,R=new Gl;var fT=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,o=>{let i=Math.random()*16|0;return(o=="x"?i:i&3|8).toString(16)})},un=fT;var Wl=class{constructor(){d(this,"_prefix","TRTC");d(this,"_queue",new Map)}getRealKey(i){return`${this._prefix}_${i}`}checkStorage(){if(!zi())return;setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter(t=>{if(t.startsWith(this._prefix))try{let r=localStorage.getItem(t);if(!r)return!1;let s=JSON.parse(r);if(s&&s.expiresIn<Date.now())return!0}catch(r){return!1}return!1}).forEach(t=>localStorage.removeItem(t))}doFlush(){if(zi())try{for(let[i,e]of this._queue)localStorage.setItem(i,JSON.stringify(e))}catch(i){R.warn(i)}}getItem(i){if(!zi())return null;try{let e=localStorage.getItem(this.getRealKey(i));if(!e)return null;let t=JSON.parse(e);return t&&t.expiresIn>=Date.now()?t.value:null}catch(e){R.warn(e)}}setItem(i,e){if(zi())try{let t={expiresIn:Date.now()+ga,value:e};this._queue.set(this.getRealKey(i),t)}catch(t){R.warn(t)}}deleteItem(i){if(!zi())return!1;try{return i=this.getRealKey(i),this._queue.delete(i),localStorage.removeItem(i),!0}catch(e){return R.warn(e),!1}}clear(){if(zi())try{localStorage.clear()}catch(i){R.warn(i)}}},is=new Wl;var vi={};Vi(vi,{HTTPS_API:()=>VT,IS_GET_CAPABILITIES_FROM_INPUTDEVICE_SUPPORTED:()=>fu,IS_GET_CAPABILITIES_SUPPORTED:()=>pu,IS_GET_SETTINGS_SUPPORTED:()=>bi,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>mu,IS_INSERTABLE_STREAM_SUPPORTED:()=>mi,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>yc,IS_RTC_RTP_SENDER_SUPPORTED:()=>Sn,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>as,IS_SEI_SUPPORTED:()=>An,IS_SPC_SUPPORTED:()=>ns,basis:()=>HT,capabilityCheck:()=>Tu,checkSystemRequirementsInternal:()=>Ic,decodeSupportStatus:()=>Sc,detectVideoCodecCapabilities:()=>Eu,detectVideoDecoderCapabilities:()=>xp,detectVideoEncoderCapabilities:()=>Lp,encodeSupportStatus:()=>uu,getBrowserInfo:()=>OT,getDisplayResolution:()=>vp,getH264ProfileLevelIds:()=>Up,isAddTransceiverSupported:()=>St,isBrowserSupported:()=>lu,isCanvasCaptureStreamAPISupported:()=>Mp,isCanvasSmallStreamSupported:()=>Ac,isGetReceiversSupported:()=>oo,isGetSendersSupported:()=>yr,isGetTransceiversSupported:()=>br,isGetUserMediaSupported:()=>Np,isMediaDevicesSupported:()=>Ec,isMediaSessionSupported:()=>kp,isMediaStreamTrackGeneratorSupported:()=>kT,isMediaStreamTrackProcessorSupported:()=>Tn,isReplaceTrackSupported:()=>hu,isRequestVideoFrameCallbackSupported:()=>Ki,isSIMDSupported:()=>gu,isScaleResolutionDownBySupported:()=>Op,isScreenCaptureApiAvailable:()=>En,isSelectedCandidatePair:()=>Rr,isSetParametersSupported:()=>In,isSetSinkIdSupported:()=>LT,isSmallStreamSupported:()=>Cc,isStopTransceiverSupported:()=>BT,isTRTCSupported:()=>wT,isUnifiedPlanDefault:()=>FT,isUsedInHttpProtocol:()=>Zi,isWebAudioSupported:()=>Dp,isWebCodecSupported:()=>Rc,isWebCodecsSupported:()=>gn,isWebRTCSupported:()=>_u,isWebTransportSupported:()=>Pp});var ru={};Vi(ru,{AUDIO_LEVEL_SCALE:()=>Dt,AlphaStitchingType:()=>fn,AudioCodecPipelineType:()=>mn,AudioDecoderDowngradeState:()=>Xl,AudioPlayerMode:()=>Zl,AudioType:()=>cp,BASIC_TYPE:()=>Qi,BannedReason:()=>Kl,CONNECTION_CLOSED_REASON:()=>Jl,CheckPermissionType:()=>iu,ClientEvent:()=>sp,CodecType:()=>mp,ConnectionEvent:()=>ci,ConnectionState:()=>Nt,DECODE_FAILED_ERROR_CODE:()=>tu,DenoiserMode:()=>eu,DeviceType:()=>mc,FacingMode:()=>lc,FrameWorkType:()=>cc,LeaveReason:()=>hp,LocalTrackEvent:()=>Kr,MULTI_VIDEO_DATA_TYPE:()=>ui,MediaType:()=>Fe,MediaTypeLabel:()=>_T,MonitorEventId:()=>hn,MutedFlag:()=>ap,NetworkQualityValue:()=>Yl,PlayerState:()=>Cr,ReceiveMode:()=>up,RemoteStreamType:()=>Et,RemoteTrackEvent:()=>eo,RoomEvent:()=>di,SMALL_MODE:()=>pn,SceneNumber:()=>jl,StreamEvent:()=>np,StreamType:()=>lp,SubscribeMediaType:()=>ql,TIMER_TYPE:()=>hi,TRACK_ACTION:()=>Ql,TRACK_KIND:()=>zl,TrackEvent:()=>li,UserRole:()=>lt,UserRoleNumber:()=>to,VideoCodec:()=>Ht,VideoCodecPipelineType:()=>hc,VideoContentHint:()=>rs,VideoDecoderDowngradeState:()=>dc,VideoPlayerMode:()=>uc,VideoType:()=>dp});var cc=(e=>(e[e.WEBRTC=30]="WEBRTC",e[e.WASM=37]="WASM",e))(cc||{}),ci=(E=>(E.TRACK_ADDED="track-added",E.TRACK_UPDATED="track-updated",E.TRACK_SUBSCRIBED="track-subscribed",E.STREAM_ADDED="stream-added",E.STREAM_REMOVED="stream-removed",E.STREAM_UPDATED="stream-updated",E.STREAM_PUBLISHED="stream-published",E.STREAM_SUBSCRIBED="stream-subscribed",E.STREAM_UNSUBSCRIBED="stream-unsubscribed",E.STATE_CHANGED="state-changed",E.ERROR="error",E.CONNECTION_STATE_CHANGED="connection-state-changed",E.FIREWALL_RESTRICTION="firewall-restriction",E.SEI_MESSAGE="sei-message",E.CLOSED="closed",E))(ci||{}),Jl=(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))(Jl||{}),sp=(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))(sp||{}),np=(s=>(s.PLAYER_STATE_CHANGED="player-state-changed",s.SCREEN_SHARING_STOPPED="screen-sharing-stopped",s.CONNECTION_STATE_CHANGED="connection-state-changed",s.DEVICE_AUTO_RECOVERED="device-auto-recovered",s.ERROR="error",s))(np||{}),Kr=(c=>(c.DEVICE_AUTO_RECOVERED="1",c.DEVICE_RECOVER_FAILED="5",c.DEVICE_CHANGED="2",c.ERROR="3",c.PUBLISH_STATE_CHANGED="4",c.ENCODE_FAILED="6",c.TRACK_ENDED="7",c.RENDER="render",c))(Kr||{}),Cr=(t=>(t.PAUSED="PAUSED",t.PLAYING="PLAYING",t.STOPPED="STOPPED",t))(Cr||{}),di=(y=>(y.PEER_JOIN="peer-join",y.PEER_LEAVE="peer-leave",y.SIGNAL_CONNECTION_STATE_CHANGED="signal-connection-state-changed",y.MEDIA_CONNECTION_STATE_CHANGED="media-connection-state-changed",y.BANNED="banned",y.NETWORK_QUALITY="network-quality",y.AUDIO_VOLUME="audio-volume",y.SEI_MESSAGE="sei-message",y.ERROR="error",y.REMOTE_PUBLISH_STATE_CHANGED="remote-publish-state-changed",y.REMOTE_PUBLISHED="remote-published",y.REMOTE_UNPUBLISHED="remote-unpublished",y.FIREWALL_RESTRICTION="firewall-restriction",y.HEARTBEAT_REPORT="heartbeat-report",y.CUSTOM_MESSAGE="custom-message",y.LAYER_DATA="layerData",y.FIRST_VIDEO_FRAME="first-video-frame",y.DUMP="dump",y.AUDIO_FRAME="audio-frame",y.SUBSCRIBE_SMALL_VIDEO_CHANGED="subscribe-small-video-changed",y.LOCAL_PUBLISH_FLAG_CHANGED="local-publish-flag-changed",y.NTP_TIME_UPDATED="ntp-time-updated",y))(di||{}),li=(c=>(c.PLAYER_STATE_CHANGED="player-state-changed",c.MUTE="mute",c.UNMUTE="unmute",c.ERROR="error",c.INPUT_MEDIA_TRACK_CHANGED="input-media-track-changed",c.OUTPUT_MEDIA_TRACK_CHANGED="output-media-track-changed",c.FIRST_VIDEO_FRAME="first-video-frame",c.VIDEO_SIZE_CHANGED="video-size-changed",c))(li||{}),eo=(r=>(r.DECODE_FAILED="decode-failed",r.DECODE_DOWNGRADE_STATE_CHANGED="decode-downgrade-state-changed",r.REMOTE_PUBLISH_CHANGED="remote-publish-changed",r.AUDIO_FRAME_WITH_NTP="audio-frame-with-ntp",r))(eo||{}),ap=(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))(ap||{}),jl=(e=>(e[e.RTC=1]="RTC",e[e.LIVE=2]="LIVE",e))(jl||{}),to=(e=>(e[e.ANCHOR=20]="ANCHOR",e[e.AUDIENCE=21]="AUDIENCE",e))(to||{}),lt=(e=>(e.ANCHOR="anchor",e.AUDIENCE="audience",e))(lt||{}),Nt=(s=>(s.CONNECTED="CONNECTED",s.DISCONNECTED="DISCONNECTED",s.CONNECTING="CONNECTING",s.RECONNECTED="RECONNECTED",s.RECONNECTING="RECONNECTING",s))(Nt||{}),Xl=(r=>(r.INITIALIZED="INITIALIZED",r.STARTING="STARTING",r.STARTED="STARTED",r.FAILED="FAILED",r))(Xl||{}),dc=(r=>(r.INITIALIZED="INITIALIZED",r.STARTING="STARTING",r.STARTED="STARTED",r.FAILED="FAILED",r))(dc||{}),zl=(t=>(t.AUDIO="audio",t.VIDEO="video",t.AUXILIARY="auxVideo",t))(zl||{}),Ql=(e=>(e.ADD="add",e.REMOVE="remove",e))(Ql||{}),Fe=(s=>(s[s.NULL=0]="NULL",s[s.AUDIO=1]="AUDIO",s[s.AUX_VIDEO=2]="AUX_VIDEO",s[s.BIG_VIDEO=4]="BIG_VIDEO",s[s.SMALL_VIDEO=8]="SMALL_VIDEO",s))(Fe||{}),_T={1:"audio",2:"auxVideo",4:"video"},cp=(i=>(i[i.opus=111]="opus",i))(cp||{}),dp=(e=>(e[e.h264=100]="h264",e[e.vp8=101]="vp8",e))(dp||{}),lp=(e=>(e.Big="big",e.Small="small",e))(lp||{}),Et=(e=>(e.Main="main",e.Aux="auxiliary",e))(Et||{}),ui=(s=>(s[s.MULTI_DATA_AUDIO=1]="MULTI_DATA_AUDIO",s[s.MULTI_DATA_BIG_IMG=2]="MULTI_DATA_BIG_IMG",s[s.MULTI_DATA_SMALL_IMG=3]="MULTI_DATA_SMALL_IMG",s[s.MULTI_DATA_AUX_IMG=7]="MULTI_DATA_AUX_IMG",s[s.MULTI_DATA_TYPE_BUTT=12]="MULTI_DATA_TYPE_BUTT",s))(ui||{}),hn=(P=>(P[P.PUBLISH_VIDEO=32768]="PUBLISH_VIDEO",P[P.PUBLISH_AUDIO=32769]="PUBLISH_AUDIO",P[P.UNPUBLISH_VIDEO=32770]="UNPUBLISH_VIDEO",P[P.UNPUBLISH_AUDIO=32771]="UNPUBLISH_AUDIO",P[P.MUTE_AUDIO=32772]="MUTE_AUDIO",P[P.MUTE_VIDEO=32773]="MUTE_VIDEO",P[P.UNMUTE_AUDIO=32774]="UNMUTE_AUDIO",P[P.UNMUTE_VIDEO=32775]="UNMUTE_VIDEO",P[P.SUBSCRIBE_VIDEO=32776]="SUBSCRIBE_VIDEO",P[P.SUBSCRIBE_AUDIO=32777]="SUBSCRIBE_AUDIO",P[P.UNSUBSCRIBE_VIDEO=32778]="UNSUBSCRIBE_VIDEO",P[P.UNSUBSCRIBE_AUDIO=32779]="UNSUBSCRIBE_AUDIO",P[P.SWITCH_CAMERA=32780]="SWITCH_CAMERA",P[P.SWITCH_MICROPHONE=32781]="SWITCH_MICROPHONE",P[P.REPLACE_VIDEO=32782]="REPLACE_VIDEO",P[P.REPLACE_AUDIO=32783]="REPLACE_AUDIO",P[P.MUTE_REMOTE_VIDEO=32784]="MUTE_REMOTE_VIDEO",P[P.MUTE_REMOTE_AUDIO=32785]="MUTE_REMOTE_AUDIO",P[P.UNMUTE_REMOTE_VIDEO=32786]="UNMUTE_REMOTE_VIDEO",P[P.UNMUTE_REMOTE_AUDIO=32787]="UNMUTE_REMOTE_AUDIO",P[P.JOIN=32788]="JOIN",P[P.LEAVE=32789]="LEAVE",P[P.SIGNAL_DISCONNECTED=32790]="SIGNAL_DISCONNECTED",P[P.SIGNAL_CONNECTED=32791]="SIGNAL_CONNECTED",P[P.TRANSPORT_UPLINK_CONNECTED=32792]="TRANSPORT_UPLINK_CONNECTED",P[P.TRANSPORT_DOWNLINK_CONNECTED=32793]="TRANSPORT_DOWNLINK_CONNECTED",P[P.SIGNAl_RECONNECTING=32794]="SIGNAl_RECONNECTING",P[P.SIGNAL_RECONNECT_SUCCESS=32795]="SIGNAL_RECONNECT_SUCCESS",P[P.SIGNAL_RECONNECT_FAIL=32796]="SIGNAL_RECONNECT_FAIL",P[P.TRANSPORT_UPLINK_RECONNECTING=32797]="TRANSPORT_UPLINK_RECONNECTING",P[P.TRANSPORT_UPLINK_RECONNECT_SUCCESS=32798]="TRANSPORT_UPLINK_RECONNECT_SUCCESS",P[P.TRANSPORT_UPLINK_RECONNECT_FAIL=32799]="TRANSPORT_UPLINK_RECONNECT_FAIL",P[P.TRANSPORT_DOWNLINK_RECONNECTING=32800]="TRANSPORT_DOWNLINK_RECONNECTING",P[P.TRANSPORT_DOWNLINK_RECONNECT_SUCCESS=32801]="TRANSPORT_DOWNLINK_RECONNECT_SUCCESS",P[P.TRANSPORT_DOWNLINK_RECONNECT_FAIL=32802]="TRANSPORT_DOWNLINK_RECONNECT_FAIL",P[P.SUBSCRIBE_SMALL_VIDEO=32803]="SUBSCRIBE_SMALL_VIDEO",P[P.UNSUBSCRIBE_SMALL_VIDEO=32804]="UNSUBSCRIBE_SMALL_VIDEO",P[P.PUBLISH_AUX=32805]="PUBLISH_AUX",P[P.UNPUBLISH_AUX=32806]="UNPUBLISH_AUX",P[P.DEVICE_CAPTURE=2003]="DEVICE_CAPTURE",P[P.VIDEO_ENCODER=4004]="VIDEO_ENCODER",P[P.VIDEO_DECODER=4005]="VIDEO_DECODER",P))(hn||{}),Yl=(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))(Yl||{}),up=(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))(up||{}),lc=(e=>(e.user="user",e.environment="environment",e))(lc||{}),uc=(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))(uc||{}),Zl=(e=>(e[e.ELEMENT=0]="ELEMENT",e[e.CONTEXT=1]="CONTEXT",e))(Zl||{}),Kl=(r=>(r.BANNED="banned",r.KICK="kick",r.USER_TIME_OUT="user_time_out",r.ROOM_DISBAND="room_disband",r))(Kl||{}),hp=(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))(hp||{}),Dt=1e8,eu=(e=>(e[e.NORMAL=0]="NORMAL",e[e.FAR_FIELD_REDUCTION=1]="FAR_FIELD_REDUCTION",e))(eu||{}),ql=class{constructor(){d(this,"mediaType",0)}set audio(i){i?this.mediaType|=1:this.mediaType&=-2}get audio(){return!!(this.mediaType&1)}set video(i){i?this.mediaType|=4:this.mediaType&=-5}get video(){return!!(this.mediaType&4)}set auxiliary(i){i?this.mediaType|=2:this.mediaType&=-3}get auxiliary(){return!!(this.mediaType&2)}set smallVideo(i){i?this.mediaType|=8:this.mediaType&=-9}get smallVideo(){return!!(this.mediaType&8)}},Qi=(s=>(s.String="string",s.Number="number",s.Boolean="boolean",s.Array="array",s.Object="object",s))(Qi||{}),Ht=(s=>(s.H264="h264",s.H265="h265",s.VP8="vp8",s.VP9="vp9",s.AV1="av1",s))(Ht||{}),hc=(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))(hc||{}),mn=(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))(mn||{}),mp=(t=>(t.WebRTC="webrtc",t.WebCodecs="webcodecs",t.WebAssembly="webassembly",t))(mp||{}),tu=(u=>(u[u.SUCCESS=0]="SUCCESS",u[u.FAILED=1]="FAILED",u[u.WEBCODEC_INIT=2]="WEBCODEC_INIT",u[u.WEBCODEC_CONFIG_NOT_SUPPORT=3]="WEBCODEC_CONFIG_NOT_SUPPORT",u[u.WEBCODEC_DECODER_ERROR=4]="WEBCODEC_DECODER_ERROR",u[u.WEBCODEC_TRACK_MUTE=5]="WEBCODEC_TRACK_MUTE",u[u.WASM_INIT=6]="WASM_INIT",u[u.WASM_WEBGL_UNAVALIABLE=7]="WASM_WEBGL_UNAVALIABLE",u[u.WASM_DECODER_ERROR=8]="WASM_DECODER_ERROR",u[u.WASM_TRACK_MUTE=9]="WASM_TRACK_MUTE",u[u.TEST=10]="TEST",u[u.RENDER_2D_ERROR=11]="RENDER_2D_ERROR",u))(tu||{}),rs=(r=>(r.NONE="",r.DETAIL="detail",r.MOTION="motion",r.TEXT="text",r))(rs||{}),hi=(s=>(s.INTERVAL="interval",s.TIMEOUT="timeout",s.RAF="raf",s.RIC="ric",s.INTERVAL_IN_WORKER="intervalInWorker",s))(hi||{}),pn=(e=>(e.CANVAS="canvas",e.API="api",e))(pn||{}),iu=(r=>(r[r.NONE=0]="NONE",r[r.MICROPHONE=1]="MICROPHONE",r[r.CAMERA=2]="CAMERA",r[r.BOTH=3]="BOTH",r))(iu||{}),mc=(e=>(e.CAMERA="camera",e.MICROPHONE="microphone",e))(mc||{}),fn=(t=>(t[t.none=0]="none",t[t.horizontal=1]="horizontal",t[t.vertical=2]="vertical",t))(fn||{});var B={AVOID_REPEATED_CALL:"AVOID_REPEATED_CALL",INVALID_PARAMETER_REQUIRED:"INVALID_PARAMETER_REQUIRED",INVALID_PARAMETER_TYPE:"INVALID_PARAMETER_TYPE",INVALID_PARAMETER_EMPTY:"INVALID_PARAMETER_EMPTY",INVALID_PARAMETER_INSTANCE:"INVALID_PARAMETER_INSTANCE",INVALID_PARAMETER_RANGE:"INVALID_PARAMETER_RANGE",INVALID_PARAMETER_MIN:"INVALID_PARAMETER_MIN",INVALID_PARAMETER_MAX:"INVALID_PARAMETER_MAX",INVALID_PARAMETER_STREAMTYPE:"INVALID_PARAMETER_STREAMTYPE",API_CALL_TIMEOUT:"API_CALL_TIMEOUT",SIGNAL_CHANNEL_RECONNECTION_FAILED:"SIGNAL_CHANNEL_RECONNECTION_FAILED",SIGNAL_CHANNEL_SETUP_FAILED:"SIGNAL_CHANNEL_SETUP_FAILED",ERROR_MESSAGE:"ERROR_MESSAGE",EXCHANGE_SDP_TIMEOUT:"EXCHANGE_SDP_TIMEOUT",DOWNLINK_RECONNECTION_FAILED:"DOWNLINK_RECONNECTION_FAILED",EXCHANGE_SDP_FAILED:"EXCHANGE_SDP_FAILED",UPDATE_OFFER_TIMEOUT:"UPDATE_OFFER_TIMEOUT",UPLINK_RECONNECTION_FAILED:"UPLINK_RECONNECTION_FAILED",INVALID_RECORDID:"INVALID_RECORDID",INVALID_PURE_AUDIO:"INVALID_PURE_AUDIO",INVALID_STREAMID:"INVALID_STREAMID",INVALID_USER_DEFINE_RECORDID:"INVALID_USER_DEFINE_RECORDID",INVALID_USER_DEFINE_PUSH_ARGS:"INVALID_USER_DEFINE_PUSH_ARGS",INVALID_PROXY:"INVALID_PROXY",INVALID_JOIN:"INVALID_JOIN",INVALID_ROOMID_STRING:"INVALID_ROOMID_STRING",INVALID_ROOMID_INTEGER:"INVALID_ROOMID_INTEGER",INVALID_SIGNAL_CHANNEL:"INVALID_SIGNAL_CHANNEL",JOIN_ROOM_TIMEOUT:"JOIN_ROOM_TIMEOUT",JOIN_ROOM_FAILED:"JOIN_ROOM_FAILED",REJOIN_ROOM_FAILED:"REJOIN_ROOM_FAILED",INVALID_DESTROY:"INVALID_DESTROY",INVALID_PUBLISH:"INVALID_PUBLISH",INVALID_UNPUBLISH:"INVALID_UNPUBLISH",INVALID_AUDIENCE:"INVALID_AUDIENCE",INVALID_INITIALIZE:"INVALID_INITIALIZE",INVALID_DUPLICATE_PUBLISHING:"INVALID_DUPLICATE_PUBLISHING",INVALID_SUBSCRIBE_UNDEFINED:"INVALID_SUBSCRIBE_UNDEFINED",INVALID_SUBSCRIBE_LOCAL:"INVALID_SUBSCRIBE_LOCAL",INVALID_REMOTE_STREAM:"INVALID_REMOTE_STREAM",SUBSCRIBE_FAILED:"SUBSCRIBE_FAILED",INVALID_ROLE:"INVALID_ROLE",INVALID_PARAMETER_SWITCH_ROLE:"INVALID_PARAMETER_SWITCH_ROLE",INVALID_OPERATION_SWITCH_ROLE:"INVALID_OPERATION_SWITCH_ROLE",SWITCH_ROLE_TIMEOUT:"SWITCH_ROLE_TIMEOUT",SWITCH_ROLE_FAILED:"SWITCH_ROLE_FAILED",CLIENT_BANNED:"CLIENT_BANNED",INVALID_OPERATION_START_PUBLISH_CDN:"INVALID_OPERATION_START_PUBLISH_CDN",INVALID_OPERATION_STOP_PUBLISH_CDN:"INVALID_OPERATION_STOP_PUBLISH_CDN",INVALID_STREAM_ID:"INVALID_STREAM_ID",START_PUBLISH_CDN_FAILED:"START_PUBLISH_CDN_FAILED",STOP_PUBLISH_CDN_FAILED:"STOP_PUBLISH_CDN_FAILED",START_MIX_TRANSCODE:"START_MIX_TRANSCODE",STOP_MIX_TRANSCODE:"STOP_MIX_TRANSCODE",INVALID_AUDIO_VOLUME:"INVALID_AUDIO_VOLUME",ENABLE_SMALL_STREAM_PUBLISHED:"ENABLE_SMALL_STREAM_PUBLISHED",DISABLE_SMALL_STREAM_PUBLISHED:"DISABLE_SMALL_STREAM_PUBLISHED",NOT_SUPPORTED_SMALL_STREAM:"NOT_SUPPORTED_SMALL_STREAM",INVALID_SMALL_STREAM_PROFILE:"INVALID_SMALL_STREAM_PROFILE",INVALID_PARAMETER_REMOTE_STREAM:"INVALID_PARAMETER_REMOTE_STREAM",INVALID_OPERATION_CHANGE_SMALL:"INVALID_OPERATION_CHANGE_SMALL",REMOTE_NOT_PUBLISH_SMALL_STREAM:"REMOTE_NOT_PUBLISH_SMALL_STREAM",INVALID_SWITCH_DEVICE:"INVALID_SWITCH_DEVICE",INVALID_SWITCH_DEVICE_PUBLISHING:"INVALID_SWITCH_DEVICE_PUBLISHING",INVALID_REPLACE_TRACK:"INVALID_REPLACE_TRACK",INVALID_INITIALIZE_LOCAL_STREAM:"INVALID_INITIALIZE_LOCAL_STREAM",INVALID_ADD_TRACK_REPETITIVE:"INVALID_ADD_TRACK_REPETITIVE",INVALID_ADD_TRACK_REMOVING:"INVALID_ADD_TRACK_REMOVING",INVALID_ADD_TRACK_PUBLISHING:"INVALID_ADD_TRACK_PUBLISHING",INVALID_STREAM_INITIALIZED:"INVALID_STREAM_INITIALIZED",INVALID_ADD_TRACK_NUMBER:"INVALID_ADD_TRACK_NUMBER",INVALID_REMOVE_AUDIO_TRACK:"INVALID_REMOVE_AUDIO_TRACK",INVALID_REMOVE_AUDIO_ADDING:"INVALID_REMOVE_AUDIO_ADDING",INVALID_REMOVE_AUDIO_ON:"INVALID_REMOVE_AUDIO_ON",INVALID_REMOVE_TRACK_PUBLISHING:"INVALID_REMOVE_TRACK_PUBLISHING",INVALID_REMOVE_TRACK_NOT_TRACK:"INVALID_REMOVE_TRACK_NOT_TRACK",INVALID_REMOVE_TRACK_NUMBER:"INVALID_REMOVE_TRACK_NUMBER",INVALID_REPLACE_TRACK_NO_TRACK:"INVALID_REPLACE_TRACK_NO_TRACK",REPEAT_JOIN:"REPEAT_JOIN",CLIENT_DESTROYED:"CLIENT_DESTROYED",NOT_BUG_PACKAGE:"NOT_BUG_PACKAGE",START_MIX_TRANSCODE_FAILED:"START_MIX_TRANSCODE_FAILED",STOP_MIX_TRANSCODE_FAILED:"STOP_MIX_TRANSCODE_FAILED",MIX_TRANSCODE_NOT_STARTED:"MIX_TRANSCODE_NOT_STARTED",CANNOT_LESS_THAN_ZERO:"CANNOT_LESS_THAN_ZERO",MIX_PARAMS_VIDEO_FRAMERATE:"MIX_PARAMS_VIDEO_FRAMERATE",MIX_PARAMS_VIDEO_GOP:"MIX_PARAMS_VIDEO_GOP",MIX_PARAMS_AUDIO_BITRATE:"MIX_PARAMS_AUDIO_BITRATE",MIX_PARAMS_USER_Z_ORDER:"MIX_PARAMS_USER_Z_ORDER",MIX_PARAMS_NOT_SELF:"MIX_PARAMS_NOT_SELF",MIX_PARAMS_USER_STREAM:"MIX_PARAMS_USER_STREAM",INVALID_PLAY:"INVALID_PLAY",INVALID_ELEMENT_ID:"INVALID_ELEMENT_ID",INVALID_ELEMENT_ID_TYPE:"INVALID_ELEMENT_ID_TYPE",PLAY_FAILED:"PLAY_FAILED",INVALID_USERID:"INVALID_USERID",INVALID_CREATE_STREAM_SOURCE:"INVALID_CREATE_STREAM_SOURCE",INVALID_CREATE_STREAM_SCREEN:"INVALID_CREATE_STREAM_SCREEN",INVALID_CREATE_STREAM_AUDIO:"INVALID_CREATE_STREAM_AUDIO",INVALID_CREATE_STREAM_SCREEN_AUDIO:"INVALID_CREATE_STREAM_SCREEN_AUDIO",NOT_SUPPORTED_HTTP:"NOT_SUPPORTED_HTTP",NOT_SUPPORTED_WEBRTC:"NOT_SUPPORTED_WEBRTC",NOT_SUPPORTED_PROFILE:"NOT_SUPPORTED_PROFILE",NOT_SUPPORTED_MEDIA:"NOT_SUPPORTED_MEDIA",NOT_SUPPORTED_H264ENCODE:"NOT_SUPPORTED_H264ENCODE",NOT_SUPPORTED_H264DECODE:"NOT_SUPPORTED_H264DECODE",NOT_SUPPORTED_TRACK:"NOT_SUPPORTED_TRACK",NOT_SUPPORTED_SWITCH_DEVICE:"NOT_SUPPORTED_SWITCH_DEVICE",NOT_SUPPORTED_CAPTURE:"NOT_SUPPORTED_CAPTURE",NOT_SUPPORTED_AUX:"NOT_SUPPORTED_AUX",MICROPHONE_NOT_FOUND:"MICROPHONE_NOT_FOUND",CAMERA_NOT_FOUND:"CAMERA_NOT_FOUND",SIGNAL_RESPONSE_FAILED:"SIGNAL_RESPONSE_FAILED",CATCH_HANDLER_ERROR:"CATCH_HANDLER_ERROR",API_NOT_EXIST:"API_NOT_EXIST",CONNECTION_CLOSED:"CONNECTION_CLOSED",SUBSCRIBE_ALL_FALSE:"SUBSCRIBE_ALL_FALSE",SEI_NOT_SUPPORT:"SEI_NOT_SUPPORT",SEI_DISABLED:"SEI_DISABLED",SEI_BEFORE_PUBLISH:"SEI_BEFORE_PUBLISH",SEI_NOT_VIDEO:"SEI_NOT_VIDEO",CALL_FREQUENCY_LIMIT:"CALL_FREQUENCY_LIMIT",CONNECTION_ABORTED:"CONNECTION_ABORTED",API_CALL_ABORTED:"API_CALL_ABORTED",DUPLICATE_AUX:"DUPLICATE_AUX"},Xe={AVOID_REPEATED_CALL(o){return`previous ${o.name}() is ongoing, please avoid repeated calls.`},INVALID_PARAMETER_REQUIRED({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' is a required param when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_TYPE({key:o,rule:i,fnName:e,value:t}){let r=`${o||i.name}`,s="";return Array.isArray(i.type)?s=i.type.join("|"):s=i.type,`'${r}' must be type of ${s} when calling ${e}(), received type: ${Oe(t)}.`},INVALID_PARAMETER_EMPTY({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' cannot be '${t}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:o,rule:i,fnName:e,value:t}){let r=`${o||i.name}`,s=`${i.instanceOf.name||i.instanceOf}`;return`'${r}' must be instanceof ${s} when calling ${e}(), received type: ${Oe(t)}.`},INVALID_PARAMETER_RANGE({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' must be one of ${i.values.join("|")} when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_MIN({key:o,rule:i,fnName:e,value:t}){return`the min value of ${o||i.name} is ${i.min}, received: ${t}.`},INVALID_PARAMETER_MAX({key:o,rule:i,fnName:e,value:t}){return`the max value of ${o||i.name} is ${i.max}, received: ${t}.`},API_CALL_TIMEOUT(o){return`${o.commandDesc||o.command} timeout observed.`},SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED(o){return`SignalChannel setup failure: (errorCode: ${o.errorCode}, errorMsg: ${o.errorMsg} }).`},ERROR_MESSAGE(o){let i=`${o.type} failed`;return o.message&&(i=`${i}: ${o.message}.`),i},EXCHANGE_SDP_TIMEOUT:"exchange sdp timeout.",DOWNLINK_RECONNECTION_FAILED:"downlink reconnection failed, please check your network and re-join room.",EXCHANGE_SDP_FAILED(o){return`exchange sdp failed ${o.errMsg}.`},UPDATE_OFFER_TIMEOUT:"update offer timeout observed.",UPLINK_RECONNECTION_FAILED:"uplink reconnection failed, please check your network and publish again.",INVALID_RECORDID:"recordId must be an integer number.",INVALID_PURE_AUDIO:"pureAudioPushMode must be 1 or 2.",INVALID_STREAMID:"streamId must be a sting literal within 64 bytes, and not be empty.",INVALID_USER_DEFINE_RECORDID:"userDefineRecordId must be a sting literal contains (a-zA-Z),(0-9), underline and hyphen, within 64 bytes, and not be empty.",INVALID_USER_DEFINE_PUSH_ARGS:"userDefinePushArgs must be a sting literal within 256 bytes, and not be empty.",INVALID_PROXY:'proxy server url must start with "wss://".',INVALID_JOIN:"duplicate join() called.",INVALID_ROOMID_STRING(o){return`'${o}' must be validate string when useStringRoomId is true.`},INVALID_ROOMID_INTEGER(o){return`'${o}' must be an integer between [1, 4294967294] when useStringRoomId is false.`},INVALID_SIGNAL_CHANNEL:"SignalChannel is not ready yet.",JOIN_ROOM_TIMEOUT:"join room timeout.",JOIN_ROOM_FAILED({error:o,code:i}){return`Failed to join room - ${o} code: ${i}`},REJOIN_ROOM_FAILED(o){return`reJoin room: ${o.roomId} failed, please check your network.`},INVALID_DESTROY:"please call leave() before destroy().",INVALID_PUBLISH:"please call join() before publish().",INVALID_UNPUBLISH:"stream has not been published yet.",INVALID_AUDIENCE:'no permission to publish() under live/audience, please call switchRole("anchor") firstly before publish().',INVALID_INITIALIZE:"cannot publish stream because stream is not initialized, is switching device, or has been closed.",INVALID_DUPLICATE_PUBLISHING(o){return`duplicate ${o} stream publishing, please unpublish your prev ${o} stream and then re-publish.`},INVALID_SUBSCRIBE_UNDEFINED:"stream is undefined or null.",INVALID_SUBSCRIBE_LOCAL:"stream cannot be LocalStream.",INVALID_REMOTE_STREAM:"remoteStream does not exist because it has been unpublished by remote peer.",SUBSCRIBE_FAILED({message:o,userId:i,streamType:e}){return`failed to subscribe ${i} ${e} stream, reason: ${o}.`},INVALID_ROLE:"switchRole can only be called in live mode.",INVALID_PARAMETER_SWITCH_ROLE:"role could only be set to a value as anchor or audience.",INVALID_OPERATION_SWITCH_ROLE:"please call join() before switchRole().",SWITCH_ROLE_TIMEOUT:"switchRole timeout.",SWITCH_ROLE_FAILED(o){return`switchRole failed, errCode: ${o.code} errMsg: ${o.message}.`},CLIENT_BANNED(o){return`client was banned because of ${o.message}.`},INVALID_OPERATION_START_PUBLISH_CDN:"please call startPublishCDNStream() after join room and publish the local stream.",INVALID_OPERATION_STOP_PUBLISH_CDN:"please call startPublishCDNStream() before stopPublishCDNStream().",START_PUBLISH_CDN_FAILED(o){return`startPublishCDNStream failed, errMsg: ${o.message}.`},STOP_PUBLISH_CDN_FAILED(o){return`stopPublishCDNStream failed, errMsg: ${o.message}.`},INVALID_STREAM_ID(o){return`'${o}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},START_MIX_TRANSCODE:"please call startMixTranscode() after join().",STOP_MIX_TRANSCODE:"please call stopMixTranscode() after startMixTranscode().",INVALID_AUDIO_VOLUME:"interval must be a number.",ENABLE_SMALL_STREAM_PUBLISHED:"Cannot enable small stream after localStream published.",DISABLE_SMALL_STREAM_PUBLISHED:"Cannot disable small stream after localStream published.",NOT_SUPPORTED_SMALL_STREAM:"your browser does not support opening small stream.",INVALID_SMALL_STREAM_PROFILE:"small stream profile is invalid.",INVALID_PARAMETER_REMOTE_STREAM:"remoteStream is invalid.",INVALID_OPERATION_CHANGE_SMALL:"cannot switch to the small stream without subscribing to the video of remoteStream.",REMOTE_NOT_PUBLISH_SMALL_STREAM:"remote peer does not publish small stream.",INVALID_SWITCH_DEVICE:"cannot switch device on current stream.",INVALID_SWITCH_DEVICE_PUBLISHING:"cannot switch device when publishing localStream.",INVALID_REPLACE_TRACK:"cannot replace track when publishing localStream.",INVALID_INITIALIZE_LOCAL_STREAM:"local stream has not initialized yet.",INVALID_ADD_TRACK_REPETITIVE:"previous addTrack is ongoing, please avoid repetitive execution.",INVALID_ADD_TRACK_REMOVING:"cannot add track when a track is removing.",INVALID_ADD_TRACK_PUBLISHING:"cannot add track when publishing localStream.",INVALID_STREAM_INITIALIZED:"your local stream haven't been initialized yet.",INVALID_ADD_TRACK_NUMBER:"a Stream has at most one audio track and one video track.",INVALID_REMOVE_AUDIO_TRACK:"remove audio track is not supported on your browser.",INVALID_REMOVE_AUDIO_ADDING:"cannot remove track when a track is adding.",INVALID_REMOVE_AUDIO_ON:"previous removeTrack is ongoing, please avoid repetitive execution.",INVALID_REMOVE_TRACK_PUBLISHING:"cannot remove track when publishing localStream.",INVALID_REMOVE_TRACK_NOT_TRACK:"localStream has not this track.",INVALID_REMOVE_TRACK_NUMBER:"remove the only video track is not supported, please use replaceTrack or muteVideo.",INVALID_REPLACE_TRACK_NO_TRACK(o){return`cannot replace ${o.kind} track because stream has not ${o.kind} track`},NOT_BUG_PACKAGE:"You need to buy packages, refer to tencent console.",START_MIX_TRANSCODE_FAILED(o){return`startMixTranscode failed, errMsg: ${o.message}.`},STOP_MIX_TRANSCODE_FAILED(o){return`stopMixTranscode failed, errMsg: ${o.message}.`},MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' cannot be less than 0 when calling ${e}().`},MIX_PARAMS_VIDEO_FRAMERATE:"'config.videoFramerate' should be an integer between 0 and 30, excluding 0.",MIX_PARAMS_VIDEO_GOP:"'config.videoGOP' should be an integer between 1 and 8.",MIX_PARAMS_AUDIO_BITRATE:"'config.audioBitrate' should be an integer between 32 and 192.",MIX_PARAMS_USER_Z_ORDER(o){return`'${o}' is required and must be between 1 and 15.`},MIX_PARAMS_NOT_SELF:"'config.mixUsers' must contain self.",MIX_PARAMS_USER_STREAM:"'config.videoWidth' and 'config.videoHeight' of output stream should be contain all mix stream.",INVALID_PLAY:"duplicate play() call observed, please stop() firstly.",INVALID_ELEMENT_ID:({key:o,fnName:i})=>`'${o}' is not found in the document object when calling ${i}().`,INVALID_ELEMENT_ID_TYPE:({key:o,fnName:i,type:e})=>`the element corresponding to '${o}' must be instanceof HTMLElement when calling ${i}(), received: ${e}.`,PLAY_FAILED:o=>`${o.media} play failed, browser exception: ${o.error.toString()}`,INVALID_USERID:"userId cannot be all spaces.",INVALID_CREATE_STREAM_SOURCE:"LocalStream must be created by createStream() with either audio/video or audioSource/videoSource, but can not be mixed with audio/video and audioSource/videoSource.",INVALID_CREATE_STREAM_SCREEN:"screen/video cannot be both true.",INVALID_CREATE_STREAM_AUDIO:"audio/screenAudio cannot be both true.",INVALID_CREATE_STREAM_SCREEN_AUDIO:"when screen is true, screenAudio can be configured.",NOT_SUPPORTED_HTTP:"http protocol does not support the ability to capture microphone, camera and screen. please use https to deploy your page.",NOT_SUPPORTED_WEBRTC:"your browser or environment does not support full WebRTC capabilities.",NOT_SUPPORTED_PROFILE:"your browser does not support setVideoProfile.",NOT_SUPPORTED_MEDIA:"your browser or environment does not support navigator.mediaDevices.",NOT_SUPPORTED_H264ENCODE:"your device does not support H.264 encoding.",NOT_SUPPORTED_H264DECODE:"your device does not support H.264 decoding.",NOT_SUPPORTED_TRACK(o){return`${o}Track is not supported on your browser.`},NOT_SUPPORTED_SWITCH_DEVICE:"switchDevice is not supported on your browser.",NOT_SUPPORTED_CAPTURE:"Your browser or environment does not support screen sharing, please check whether the browser version.",MICROPHONE_NOT_FOUND:"no microphone detected, please check your microphone.",CAMERA_NOT_FOUND:"no camera detected, please check your camera.",SIGNAL_RESPONSE_FAILED(o){return`${o.signalResponse} failed, response code is ${o.code} , errMsg: ${o.message}.`},CATCH_HANDLER_ERROR({name:o,event:i}){return`an error was caught in ${o}.on('${i}', handler), please check your code in 'handler'.`},API_NOT_EXIST({name:o}){return`experimental api ${o} does not exist.`},REPEAT_JOIN:o=>"please avoid repeated join.",CONNECTION_CLOSED:"remoteStream has been unsubscribed or unpublished by remote user.",SUBSCRIBE_ALL_FALSE:"cannot subscribe when both audio & video are false, use client.unsubscribe() instead",CLIENT_DESTROYED({funName:o}){return`failed to call ${o}() because client was destroyed.`},SEI_NOT_SUPPORT:o=>`not support to sendSEIMessage${o===!1?" without using h264 codec":""}`,SEI_DISABLED:"SEI is disabled",SEI_BEFORE_PUBLISH:"please call sendSEIMessage() after publish() success",SEI_NOT_VIDEO:"cannot send sei when localStream has not video.",CALL_FREQUENCY_LIMIT:({isSize:o,name:i,timesInSecond:e,maxSizeInSecond:t})=>`api ${i} call ${o?"size":"times"} is over ${o?`${t} bytes`:e} in a second.`,CONNECTION_ABORTED(o){return`connection aborted due to: ${o}`},API_CALL_ABORTED(o){let i;return o.message.includes("REMOTE_STREAM_NOT_EXIST")?i=`Subscribe ${o.userId} ${o.streamType} stream aborted, reason: remote user ${o.userId} unpublished stream.`:i=`API aborted, reason: ${o.message}`,i},DUPLICATE_AUX:"only one auxiliary stream can be published in a room.",NOT_SUPPORTED_AUX:"publish auxiliary stream is not supported on your browser.",INVALID_PARAMETER_STREAMTYPE:o=>`'streamType' is required when 'userId' is not '*', calling ${o}()`};var pp=(o,i)=>i?`${ft}/${o}/${i}`:`${ft}/${o}/index.html`;var gT=()=>{if(window.TRTC_ERROR_INFO&&window.TRTC_ERROR_LINK)return{TRTC_ERROR_INFO:window.TRTC_ERROR_INFO,TRTC_ERROR_LINK:window.TRTC_ERROR_LINK};let o=localStorage==null?void 0:localStorage.getItem(el);if(o){o=JSON.parse(o);let i=document.createElement("script");i.type="text/javascript",i.text=o.message,document.body.appendChild(i);let e=window.TRTC_ERROR_INFO,t=window.TRTC_ERROR_LINK;return document.body.removeChild(i),{TRTC_ERROR_INFO:e,TRTC_ERROR_LINK:t}}return{}};function $(o){let{key:i,data:e,link:t,addDocLink:r=!0}=o,s="",n="",a="";me(Xe[i])?s=Xe[i](e):re(Xe[i])&&(s=Xe[i]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:l}=gT();t?a=`${t.className}.html#${t.fnName}`:l&&l[i]&&(me(l[i])?a=l[i](e):re(l[i])&&(a=l[i]));let h=s;return Zt()&&(c&&c[i]&&(me(c[i])?n=c[i](e):re(c[i])&&(n=c[i])),n&&(r?h=`${n}
7
+ \u8BF7\u67E5\u770B\u6587\u6863: ${pp("zh-cn",a)}
8
8
 
9
- `:u=`${n}
9
+ `:h=`${n}
10
10
 
11
- `,u+=s)),r&&(u+=`
12
- Refer to: ${op("en",a)}
13
- `),u}var eu=Je(hp(),1);var ST=1,IT=0,cd=class{constructor(i=!0){c(this,"countMap",new Map);c(this,"distributionMap",new Map);c(this,"version");c(this,"log",R.createLogger({id:"kv"}));i&&(S.on("102",({track:e,cost:t})=>{this.addSuccessEvent({key:e.kind===_.AUDIO?501700:511700,cost:t})}),S.on("103",({track:e,error:t})=>{this.addFailedEvent({key:e.kind===_.AUDIO?501700:511700,error:t})}),S.on("266",({enable:e})=>{this.log.info(`${e?"enable":"disable"} sso`),e?this.addSuccessEvent({key:525701}):this.addFailedEvent({key:525701})}))}getReportData(i,e){let t={msg_sdk_basic_info:{uint32_sdk_version:Na(this.version||He),uint32_terminal_type:15,bytes_device_name:"",bytes_os_version:"",uint32_framework:30,uint32_network_type:0},stats_count:[...this.countMap.entries()].map(([r,s])=>({uint32_key:r,uint32_count:s})),stats_distribution:[...this.distributionMap.entries()].map(([r,s])=>({uint32_key:r,distribution_items:[...s.entries()].map(([n,a])=>({uint32_item_key:n,uint32_item_value:a}))})),str_user_sig:i,bytes_report_token:e};return this.countMap.clear(),this.distributionMap.clear(),t}clear(){this.countMap.clear(),this.distributionMap.clear()}isEnumKey(i){let e=+String(i).slice(-3);return e>=700&&e<799}isErrorCodeKey(i){let e=+String(i).slice(-3);return e>=600&&e<699}isCountKey(i){let e=+String(i).slice(-3);return e>=0&&e<599}isNumberKey(i){let e=+String(i).slice(-3);return e>=800&&e<899}addCount({key:i,useUV:e=!1}){if(!this.isCountKey(i)){this.log.debug(`${i} is not count key, last 3 number should be 0~599`);return}e&&this.countMap.has(i)||this.countMap.set(i,(this.countMap.get(i)||0)+1)}addEnum({key:i,value:e,useUV:t=!0}){var s;if(!this.isEnumKey(i))return this.log.debug(`${i} is not enum key, last 3 number should be 700~799`);if(t&&this.countMap.has(i))return;this.countMap.set(i,(this.countMap.get(i)||0)+1);let r=((s=this.distributionMap)==null?void 0:s.get(i))||new Map;r.set(e,(r.get(e)||0)+1),this.distributionMap.set(i,r)}addNumber({key:i,value:e,split:t=100,useUV:r=!1,max:s=5e3}){var d;if(!this.isNumberKey(i))return this.log.debug(`${i} is not number key, last 3 number should be 800~899`);if(r&&this.countMap.has(i))return;e>s&&(e=s),this.countMap.set(i,(this.countMap.get(i)||0)+1);let n=((d=this.distributionMap)==null?void 0:d.get(i))||new Map,a=0;if(Q(t))a=Math.floor(e/t);else for(let l=t.length-1;l>0;l--)if(e>t[l]){a=l;break}n.set(a,(n.get(a)||0)+1),this.distributionMap.set(i,n)}addSuccessEvent({key:i,cost:e,timeKey:t,split:r}){if(i&&(this.addEnum({key:i,value:ST,useUV:!1}),e)){let s=+String(i).slice(-3);s<800&&s>=700?this.addNumber({key:t||i+100,value:e,split:r}):t||this.log.debug(`time stat ignored, ${i}`)}}addFailedEvent({key:i,error:e}){if(!i)return;let t=I.UNKNOWN;e&&(Q(e)?t=e:(!T(e.extraCode)||!T(e.code))&&(t=e.extraCode||e.code)),this.addEnum({key:i,value:IT,useUV:!1}),this.addEnum({key:i,value:Math.abs(t),useUV:!1})}},ld=(O=>(O[O.enterRoom=500700]="enterRoom",O[O.exitRoom=500701]="exitRoom",O[O.switchRole=500702]="switchRole",O[O.destroy=500703]="destroy",O[O.startLocalAudio=500704]="startLocalAudio",O[O.updateLocalAudio=500705]="updateLocalAudio",O[O.stopLocalAudio=500706]="stopLocalAudio",O[O.startLocalVideo=500707]="startLocalVideo",O[O.updateLocalVideo=500708]="updateLocalVideo",O[O.stopLocalVideo=500709]="stopLocalVideo",O[O.startScreenShare=500710]="startScreenShare",O[O.updateScreenShare=500711]="updateScreenShare",O[O.stopScreenShare=500712]="stopScreenShare",O[O.startRemoteVideo=500713]="startRemoteVideo",O[O.updateRemoteVideo=500714]="updateRemoteVideo",O[O.stopRemoteVideo=500715]="stopRemoteVideo",O[O.muteRemoteAudio=500716]="muteRemoteAudio",O[O.setRemoteAudioVolume=500717]="setRemoteAudioVolume",O[O.use=500718]="use",O[O.switchRoom=500719]="switchRoom",O[O.getPermissions=500720]="getPermissions",O[O.sendSEIMessage=5e5]="sendSEIMessage",O[O.sendCustomMessage=500001]="sendCustomMessage",O))(ld||{}),Yl=(m=>(m[m.AudioMixer=550700]="AudioMixer",m[m.AIDenoiser=551700]="AIDenoiser",m[m.VirtualBackground=570700]="VirtualBackground",m[m.Beauty=571700]="Beauty",m[m.Watermark=572700]="Watermark",m[m.BasicBeauty=574700]="BasicBeauty",m[m.FaceDetector=575700]="FaceDetector",m[m.CDNStreaming=590700]="CDNStreaming",m[m.DeviceDetector=591700]="DeviceDetector",m[m.Debug=592700]="Debug",m[m.SmallStreamAutoSwitcher=593700]="SmallStreamAutoSwitcher",m[m.VideoMixer=594700]="VideoMixer",m[m.AudioProcessor=595700]="AudioProcessor",m))(Yl||{}),Zl=(m=>(m[m.AudioMixer=550701]="AudioMixer",m[m.AIDenoiser=551701]="AIDenoiser",m[m.VirtualBackground=570701]="VirtualBackground",m[m.Beauty=571701]="Beauty",m[m.Watermark=572701]="Watermark",m[m.BasicBeauty=574701]="BasicBeauty",m[m.FaceDetector=575701]="FaceDetector",m[m.CDNStreaming=590701]="CDNStreaming",m[m.DeviceDetector=591701]="DeviceDetector",m[m.Debug=592701]="Debug",m[m.SmallStreamAutoSwitcher=593701]="SmallStreamAutoSwitcher",m[m.VideoMixer=594701]="VideoMixer",m[m.AudioProcessor=595701]="AudioProcessor",m))(Zl||{}),Kl=(m=>(m[m.AudioMixer=550702]="AudioMixer",m[m.AIDenoiser=551702]="AIDenoiser",m[m.VirtualBackground=570702]="VirtualBackground",m[m.Beauty=571702]="Beauty",m[m.Watermark=572702]="Watermark",m[m.BasicBeauty=574702]="BasicBeauty",m[m.FaceDetector=575702]="FaceDetector",m[m.CDNStreaming=590702]="CDNStreaming",m[m.DeviceDetector=591702]="DeviceDetector",m[m.Debug=592702]="Debug",m[m.SmallStreamAutoSwitcher=593702]="SmallStreamAutoSwitcher",m[m.VideoMixer=594702]="VideoMixer",m[m.AudioProcessor=595702]="AudioProcessor",m))(Kl||{});var rs=(L=>(L[L.DECODER_TYPE=514700]="DECODER_TYPE",L[L.DECODER_HW_SW=514701]="DECODER_HW_SW",L[L.DECODE_RESULT=514702]="DECODE_RESULT",L[L.DECODE_FAILED_OS=514703]="DECODE_FAILED_OS",L[L.DOWNGRADE_RESULT=514704]="DOWNGRADE_RESULT",L[L.DOWNGRADE_WEBCODECS_VIDEO=514705]="DOWNGRADE_WEBCODECS_VIDEO",L[L.DOWNGRADE_WEBCODECS_2D=514706]="DOWNGRADE_WEBCODECS_2D",L[L.DOWNGRADE_WASM_WEGBL=514707]="DOWNGRADE_WASM_WEGBL",L[L.DOWNGRADE_WASM_VIDEO=514708]="DOWNGRADE_WASM_VIDEO",L[L.DOWNGRADE_WASM_2D=514709]="DOWNGRADE_WASM_2D",L[L.DECODE_H264_RESULT=514710]="DECODE_H264_RESULT",L[L.DECODE_H265_RESULT=514711]="DECODE_H265_RESULT",L[L.DECODE_VP8_RESULT=514712]="DECODE_VP8_RESULT",L[L.DECODE_CAPABILITIES=514713]="DECODE_CAPABILITIES",L[L.H264_PROFILE_LEVEL_ID_HIGH=514714]="H264_PROFILE_LEVEL_ID_HIGH",L[L.H264_PROFILE_LEVEL_ID_MAIN=514715]="H264_PROFILE_LEVEL_ID_MAIN",L[L.RENDER_FREEZE_RATE=514850]="RENDER_FREEZE_RATE",L[L.DATA_FREEZE_RATE=514851]="DATA_FREEZE_RATE",L[L.VIDEO_CONSUME_RENDER_RATE=514852]="VIDEO_CONSUME_RENDER_RATE",L))(rs||{});var AT=new cd(!0),ro=new cd(!1);var y=AT;var te={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}},CT=new Map([[ee,["Firefox",Ua]],[qo,["Edg",Fa]],[Zo,["Chrome",Ka]],[Re,["Safari",Xi]],[ii,["TBS",$a]],[ri,["XWEB",Wa]],[oi&&Sr,["WeChat",Ga]],[zs,["QQ(Win)",Ja]],[Xo,["QQ(Mobile)",Wo]],[jo,["QQ(Mobile X5)",Wo]],[Qs,["QQ(Mac)",qa]],[Ys,["QQ(iPad)",ja]],[Ks,["MI",Xa]],[en,["HW",za]],[rn,["Samsung",Qa]],[zo,["OPPO",Ya]],[on,["VIVO",Za]],[zr,["EDGE",Va]],[js,["SogouMobile",Ba]],[Xs,["Sogou",Ha]]]);function RT(){let o=CT.get(!0),i=o?o[0]:"unknown",e=o?o[1]:"unknown";return{browserName:i,browserVersion:e}}var iu=function(){return!(Al||zr||qo&&Sl<80||ee&&Jo<56)},mn=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder"].every(i=>i in window)},md=function(){if(!navigator.mediaDevices)return Zi()||R.error(qe.NOT_SUPPORTED_MEDIA),!1;let o=["getUserMedia","enumerateDevices"];return o.filter(i=>i in navigator.mediaDevices).length===o.length},mp=!1;function Zi(){return location.protocol==="http:"&&!ni?(mp||R.error($({key:B.NOT_SUPPORTED_HTTP})),mp=!0,!0):!1}var pn=function(){return(window==null?void 0:window.OffscreenCanvas)&&(window==null?void 0:window.MediaStreamTrackProcessor)&&(window==null?void 0:window.MediaStreamTrackGenerator)},yT=function(){return!!(window!=null&&window.MediaStreamTrackGenerator)},ru=function(){return f(this,null,function*(){var r,s,n;if(te.detail.isH264EncodeSupported&&te.detail.isVp8EncodeSupported)return{isH264EncodeSupported:te.detail.isH264EncodeSupported,isVp8EncodeSupported:te.detail.isVp8EncodeSupported,isH265EncodeSupported:te.detail.isH265EncodeSupported};let o,i=!1,e=!1,t=!1;try{let a=new RTCPeerConnection,d=document.createElement(_.CANVAS);d.getContext("2d");let l=d.captureStream(0);return a.addTrack(l.getVideoTracks()[0],l),o=yield a.createOffer(),i=((r=o.sdp)==null?void 0:r.toLowerCase().indexOf("h264"))!==-1,e=((s=o.sdp)==null?void 0:s.toLowerCase().indexOf("vp8"))!==-1,t=((n=o.sdp)==null?void 0:n.toLowerCase().indexOf("h265"))!==-1,a.close(),{isH264EncodeSupported:i,isVp8EncodeSupported:e,isH265EncodeSupported:t}}catch(a){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1}}})},pd=function(){return f(this,null,function*(){var t;if(te.detail.isH264DecodeSupported&&te.detail.isVp8DecodeSupported)return{isH264DecodeSupported:te.detail.isH264DecodeSupported,isVp8DecodeSupported:te.detail.isVp8DecodeSupported,isH265DecodeSupported:te.detail.isH265DecodeSupported};let o,i=!1,e=!1;try{let r=new RTCPeerConnection;St()?(r.addTransceiver(_.VIDEO,{direction:"recvonly"}),o=yield r.createOffer()):o=yield r.createOffer({offerToReceiveVideo:!0}),o.sdp.toLowerCase().indexOf("h264")!==-1&&(i=!0),o.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0);let s=((t=o.sdp)==null?void 0:t.toLowerCase().indexOf("h265"))!==-1;return r.close(),{isH264DecodeSupported:i,isVp8DecodeSupported:e,isH265DecodeSupported:s}}catch(r){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}}})};function bT(){return f(this,null,function*(){let[o,i]=yield Promise.all([ru(),pd()]);return{encode:{h264:o.isH264EncodeSupported,vp8:o.isVp8EncodeSupported,h265:o.isH265EncodeSupported},decode:{h264:i.isH264DecodeSupported,vp8:i.isVp8DecodeSupported,h265:i.isH265DecodeSupported}}})}var fd=va(o=>f(void 0,null,function*(){let i=Date.now(),e=du(),t=md(),r=mn();if(te.detail.isWebRTCSupported=e,te.detail.isMediaDevicesSupported=t,te.detail.isWebCodecsSupported=r,te.detail.isScreenShareSupported=fn(),te.detail.isSmallStreamSupported=gd(),o===37)return Object.assign(te.detail,yield MT()),te.detail.isBrowserSupported=r,te.result=t&&r,te.result||R.error(`${navigator.userAgent} ${Ws(te.detail,!1)}`),pp(o),y.addNumber({key:523800,value:Date.now()-i}),te;if(te.result&&te.detail.isH264EncodeSupported&&te.detail.isVp8EncodeSupported&&te.detail.isH265EncodeSupported&&te.detail.isH264DecodeSupported&&te.detail.isVp8DecodeSupported&&te.detail.isH265DecodeSupported)return te;let s=iu(),{encode:n,decode:a}=yield bT(),{h264:d,vp8:l}=n,{h264:u}=a,{h265:h}=n,{vp8:p,h265:m}=a;if(!d||!l){let g=yield ru();R.warn(`detect encode again h264:${d} vp8:${l} result: ${JSON.stringify(g)}`),d=g.isH264EncodeSupported,l=g.isVp8EncodeSupported}if(d&&u&&_e&&Ve&&!ri&&!ii&&!(zo&&$e===115)){let{encode:g,decode:E}=yield DT();d=g,u=E}return te.result=s&&e&&t&&(d||l)&&(u||p),te.detail.isBrowserSupported=s,te.detail.isWebRTCSupported=e,te.detail.isH264EncodeSupported=d,te.detail.isVp8EncodeSupported=l,te.detail.isH265EncodeSupported=h,te.detail.isH264DecodeSupported=u,te.detail.isVp8DecodeSupported=p,te.detail.isH265DecodeSupported=m,te.result||R.error(`${navigator.userAgent} ${Ws(te.detail,!1)}`),pp(),y.addNumber({key:523800,value:Date.now()-i}),te})),NT=function(){return te.result},fn=function(){return!!(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)},vT=typeof HTMLMediaElement!="undefined"&&"setSinkId"in HTMLMediaElement.prototype,ud=null;function DT(){return f(this,null,function*(){return ud||(ud=new Promise(o=>f(this,null,function*(){let i={encode:!1,decode:!1},e=()=>{};try{let t=document.createElement("canvas"),r=t.getContext("2d");t.width=640,t.height=480;let s=setInterval(()=>{r.fillText("test",Math.floor(Math.random()*640),Math.floor(Math.random()*480))},66),n=-1,a=-1;e=()=>{clearInterval(n),clearInterval(s),clearTimeout(a),l.close(),u.close(),d.getTracks().forEach(E=>E.stop())},a=setTimeout(()=>{e(),o(i)},2*1e3);let d=t.captureStream(),l=new RTCPeerConnection({}),u=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});l.addEventListener("icecandidate",E=>u.addIceCandidate(E.candidate)),u.addEventListener("icecandidate",E=>l.addIceCandidate(E.candidate)),l.addTrack(d.getVideoTracks()[0],d);let h=yield l.createOffer();yield l.setLocalDescription(h),yield u.setRemoteDescription(h);let p=yield u.createAnswer(),m=eu.default.parse(p.sdp),g=m.media[0].rtp.findIndex(E=>E.codec==="H264");m.media[0].rtp=[m.media[0].rtp[g]],m.media[0].fmtp=m.media[0].fmtp.filter(E=>E.payload===m.media[0].rtp[0].payload),m.media[0].rtcpFb&&(m.media[0].rtcpFb=m.media[0].rtcpFb.filter(E=>E.payload===m.media[0].rtp[0].payload)),p.sdp=eu.default.write(m),yield u.setLocalDescription(p),yield l.setRemoteDescription(p),n=setInterval(()=>f(this,null,function*(){i.encode&&i.decode&&(e(),o(i));let[E,C]=yield Promise.all([l.getSenders()[0].getStats(),u.getReceivers()[0].getStats()]);i.encode||E.forEach(P=>{P.type==="outbound-rtp"&&P.mediaType===_.VIDEO&&P.bytesSent>0&&(i.encode=!0)}),i.decode||C.forEach(P=>{P.type==="inbound-rtp"&&P.mediaType===_.VIDEO&&P.bytesReceived>0&&(i.decode=!0)})}),100)}catch(t){e(),R.warn("detectH264Supported failed",t),o({encode:!0,decode:!0})}})).then(o=>(o.encode||(o.decode=!0),(!o.encode||!o.decode)&&R.warn(`detectH264Supported encode: ${o.encode} decode: ${o.decode} ${ti}`),o)),ud)})}var hd=null;function MT(){return f(this,null,function*(){return hd||(hd=new Promise(o=>f(this,null,function*(){let i={isH264EncodeSupported:!1,isH264DecodeSupported:!1,isVp8EncodeSupported:!1,isVp8DecodeSupported:!1};if(!mn()){o(i);return}let e=null,t=null,r=null,s=()=>{r&&clearTimeout(r),e=null,t=null};try{e=document.createElement("canvas"),t=e.getContext("2d"),e.width=320,e.height=240;let n=0,a=()=>{!t||!e||(t.fillStyle=`hsl(${n%360}, 50%, 50%)`,t.fillRect(0,0,e.width,e.height),t.fillStyle="white",t.font="20px Arial",t.fillText(`Frame ${n}`,10,30),n++)};r=setTimeout(()=>{s(),o(i)},5e3);let d=[{type:"h264",encodeConfig:{codec:"avc1.42E01E",avc:{format:"annexb"},width:320,height:240,bitrate:1e6},decodeConfig:{codec:"avc1.42E01E",avc:{format:"annexb"}}},{type:"vp8",encodeConfig:{codec:"vp8",width:320,height:240,bitrate:1e6},decodeConfig:{codec:"vp8"}}];(yield Promise.all(d.map(u=>f(this,null,function*(){let h={type:u.type,encodeSupported:!1,decodeSupported:!1},p;try{p=yield new Promise((m,g)=>f(this,null,function*(){try{let E=new VideoEncoder({output:P=>{m(P),h.encodeSupported=!0},error:g});E.configure(u.encodeConfig),a();let C=new VideoFrame(e,{timestamp:0});E.encode(C,{keyFrame:!0}),C.close(),yield E.flush(),E.close()}catch(E){g(E)}}))}catch(m){return R.warn(`${u.type} encoder error:`,m),h}try{yield new Promise((m,g)=>f(this,null,function*(){try{let E=new VideoDecoder({output:C=>{h.decodeSupported=!0,m(0),C.close()},error:g});E.configure(u.decodeConfig),E.decode(p),yield E.flush(),E.close()}catch(E){g(E)}}))}catch(m){R.warn(`${u.type} decoder error:`,m)}return h})))).forEach(u=>{u.type==="h264"?(i.isH264EncodeSupported=u.encodeSupported,i.isH264DecodeSupported=u.decodeSupported):u.type==="vp8"&&(i.isVp8EncodeSupported=u.encodeSupported,i.isVp8DecodeSupported=u.decodeSupported)}),s(),o(i)}catch(n){s(),R.warn("detectWebCodecsSupported failed:",n),o(i)}})),hd)})}var OT=(o,i,e)=>{location.protocol==="http:"&&!ni&&(o[i]=()=>{throw new v({code:I.INVALID_OPERATION,message:qe.NOT_SUPPORTED_HTTP})})},Cr=function(o){return o.type==="candidate-pair"&&o.nominated&&(o.state==="in-progress"||o.state==="succeeded")?!(ue(o.selected)&&!o.selected):!1};function gp(){let o="";if(screen.width){let i=screen.width?screen.width*window.devicePixelRatio:"",e=screen.height?screen.height*window.devicePixelRatio:"";o+=`${i} * ${e}`}return o}function Tp(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function Ep(){let o={isSupported:!1},i=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"];for(let e=0;e<i.length;e++)if(i[e]in window){o.isSupported=!0;break}return o.isSupported}function Sp(){return"captureStream"in HTMLCanvasElement.prototype}function _d(){return oi||ge||$e&&$e<63?!1:!!(iu()&&Sp())}function Ip(){return!($e<74||zr||et<11||Jo<46)}function gd(){return _d()||Ip()}var kT=function(){if(T(window.RTCRtpTransceiver)||!St()||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let o=null,i=!1;try{o=new RTCPeerConnection({sdpSemantics:gr}),o.addTransceiver(_.AUDIO),i=!0}catch(e){}return o==null||o.close(),i};function oo(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function Rr(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function yr(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function St(){return et===11&&!Dl?!1:"RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype}var os=!(!St()||Ve&&$e<86);function PT(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}var _n="RTCRtpSender"in window;function ou(){return _n&&"replaceTrack"in window.RTCRtpSender.prototype}function gn(){return _n&&"setParameters"in window.RTCRtpSender.prototype&&Rr()}var su="RTCRtpReceiver"in window&&"getSynchronizationSources"in window.RTCRtpReceiver.prototype,Ni=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,nu=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,au=typeof InputDeviceInfo!="undefined"&&"getCapabilities"in InputDeviceInfo.prototype,pi=_n&&"createEncodedStreams"in window.RTCRtpSender.prototype&&Yo()>=86,ss="RTCRtpScriptTransform"in window,Tn=_n&&(pi||ss),du=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(i=>i in window).length>0};function Td(){let o={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return T(window.AudioDecoder)||(o.AudioDecoder=!0),T(window.AudioEncoder)||(o.AudioEncoder=!0),T(window.VideoDecoder)||(o.VideoDecoder=!0),T(window.VideoEncoder)||(o.VideoEncoder=!0),T(window.ImageDecoder)||(o.ImageDecoder=!0),o}function Ap(){return"mediaSession"in navigator&&!T(navigator.mediaSession.setActionHandler)}function Cp(){return!T(window.WebTransport)}function cu(){return typeof WebAssembly=="undefined"?!1:WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]))}function LT(){let o={browser:`${yi.name}/${yi.version}`,os:td(),displayResolution:gp(),isScreenShareSupported:fn(),isWebRTCSupported:du(),isGetUserMediaSupported:Tp(),isWebAudioSupported:Ep(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:Td(),isMediaSessionSupported:Ap(),isWebTransportSupported:Cp()};return navigator.userAgent.includes("miniProgram")&&(o.browser=`mini/${o.browser}`),o}var Rp="checkResult";function pp(o=30){es.setItem(Rp+o,{ua:navigator.userAgent,checkResult:te})}function lu(o){Zi();let i=es.getItem(Rp+o);i&&i.ua===navigator.userAgent&&i.checkResult&&xT(i.checkResult.detail,te.detail)&&(te=i.checkResult),fd(o)}function xT(o,i){return yt(o)?Object.keys(i).every(e=>e in o):!1}function Ki(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var Ed="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype;function fp(o){return{h264:1,h265:2,vp8:3,vp9:4,av1:5}[o]}var _p=!1;function uu(){return f(this,null,function*(){var o;try{if(_p||!((o=navigator==null?void 0:navigator.mediaCapabilities)!=null&&o.encodingInfo))return;let i=Zr(),e=Ol();if(i===0||e===0)return;_p=!0;let t=["H264","VP8","VP9","AV1","H265"],[r,s]=yield Promise.all([yp(t),bp(t)]);r&&Object.keys(r).forEach(d=>{let l=fp(d.toLowerCase());y.addEnum({key:513707,value:+`${l}${+r[d].supported}${+r[d].powerEfficient}${i}${e}`,useUV:!1})}),s&&Object.keys(s).forEach(d=>{let l=fp(d.toLowerCase());y.addEnum({key:514713,value:+`${l}${+s[d].supported}${+s[d].powerEfficient}${i}${e}`,useUV:!1})});let{sender:n,receiver:a}=Np();y.addEnum({key:513708,value:+`${i}${e}${+n.high}`,useUV:!1}),y.addEnum({key:513709,value:+`${i}${e}${+n.main}`,useUV:!1}),y.addEnum({key:514714,value:+`${i}${e}${+a.high}`,useUV:!1}),y.addEnum({key:514715,value:+`${i}${e}${+a.main}`,useUV:!1})}catch(i){R.info("detectVideoCodecCapabilities failed",i)}})}function yp(o,i=1920,e=1080,t=30,r=3e3){return f(this,null,function*(){let s={};try{for(let n of o){let a=yield navigator.mediaCapabilities.encodingInfo({type:"webrtc",video:{contentType:`video/${n}`,width:i,height:e,bitrate:r,framerate:t}});s[n]=a}}catch(n){}return s})}function bp(o,i=1920,e=1080,t=30,r=3e3){return f(this,null,function*(){let s={};try{for(let n of o){let a=yield navigator.mediaCapabilities.decodingInfo({type:"webrtc",video:{contentType:`video/${n}`,width:i,height:e,bitrate:r,framerate:t}});s[n]=a}}catch(n){}return s})}function Np(){let o={sender:{base:!1,main:!1,high:!1},receiver:{base:!1,main:!1,high:!1}};try{if(RTCRtpSender&&typeof RTCRtpSender.getCapabilities=="function"){let i=RTCRtpSender.getCapabilities("video");i&&i.codecs&&i.codecs.filter(t=>t.mimeType.toLowerCase()==="video/h264").forEach(t=>{if(t.sdpFmtpLine){let r=t.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(r&&r[1])switch(r[1].slice(0,2)){case"42":o.sender.base=!0;break;case"4d":o.sender.main=!0;break;case"64":o.sender.high=!0;break}}})}if(RTCRtpReceiver&&typeof RTCRtpReceiver.getCapabilities=="function"){let i=RTCRtpReceiver.getCapabilities("video");i&&i.codecs&&i.codecs.filter(t=>t.mimeType.toLowerCase()==="video/h264").forEach(t=>{if(t.sdpFmtpLine){let r=t.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(r&&r[1])switch(r[1].slice(0,2)){case"42":o.receiver.base=!0;break;case"4d":o.receiver.main=!0;break;case"64":o.receiver.high=!0;break}}})}}catch(i){R.warn("get H264 profile levelId failed",i)}return o}var Dp=Je(nt(),1);var vp=Symbol("instance"),DC=Symbol("abortCtrl"),Sd=Symbol("cacheResult"),En=class{constructor(i,e,t){this.oldState=i,this.newState=e,this.action=t,this.aborted=!1}abort(i){this.aborted=!0,An.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},Sn=class extends Error{constructor(i,e,t){super(e),this.state=i,this.message=e,this.cause=t}};function wT(o){return typeof o=="object"&&o&&"then"in o}var In=new Map;function ye(o,i,e={}){return(t,r,s)=>{let n=e.action||r;if(!e.context){let d=In.get(t)||[];In.has(t)||In.set(t,d),d.push({from:o,to:i,action:n})}let a=s.value;s.value=function(...d){let l=this;if(e.context&&(l=j.get(typeof e.context=="function"?e.context.call(this,...d):e.context)),l.state===i)return e.sync?l[Sd]:Promise.resolve(l[Sd]);l.state instanceof En&&l.state.action==e.abortAction&&l.state.abort(l);let u=null;Array.isArray(o)?o.length==0?l.state instanceof En&&l.state.abort(l):(typeof l.state!="string"||!o.includes(l.state))&&(u=new Sn(l._state,`${l.name} ${n} to ${i} failed: current state ${l._state} not from ${o.join("|")}`)):o!==l.state&&(u=new Sn(l._state,`${l.name} ${n} to ${i} failed: current state ${l._state} not from ${o}`));let h=C=>{if(e.fail&&e.fail.call(this,C),e.sync){if(e.ignoreError)return C;throw C}else return e.ignoreError?Promise.resolve(C):Promise.reject(C)};if(u)return h(u);let p=l.state,m=new En(p,i,n);An.call(l,m);let g=C=>{var P;return l[Sd]=C,m.aborted||(An.call(l,i),(P=e.success)===null||P===void 0||P.call(this,l[Sd])),C},E=C=>(An.call(l,p,C),h(C));try{let C=a.apply(this,d);return wT(C)?C.then(g).catch(E):e.sync?g(C):Promise.resolve(g(C))}catch(C){return E(new Sn(l._state,`${l.name} ${n} from ${o} to ${i} failed: ${C}`,C instanceof Error?C:new Error(String(C))))}}}}var UT=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 An(o,i){let e=this._state;this._state=o;let t=o.toString();o&&this.emit(t,e),this.emit(j.STATECHANGED,o,e,i),this.updateDevTools({value:o,old:e,err:i instanceof Error?i.message:String(i)})}var j=class o extends Dp.default{constructor(i,e,t){super(),this.name=i,this.groupName=e,this._state=o.INIT,i||(i=Date.now().toString(36)),t?Object.setPrototypeOf(this,t):t=Object.getPrototypeOf(this),e||(this.groupName=this.constructor.name);let r=t[vp];r?this.name=r.name+"-"+r.count++:t[vp]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let i=Object.getPrototypeOf(this),e=In.get(i)||[],t=new Set,r=[],s=[],n=new Set,a=Object.getPrototypeOf(i);In.has(a)&&(a.stateDiagram.forEach(l=>t.add(l)),a.allStates.forEach(l=>n.add(l))),e.forEach(({from:l,to:u,action:h})=>{typeof l=="string"?r.push({from:l,to:u,action:h}):l.length?l.forEach(p=>{r.push({from:p,to:u,action:h})}):s.push({to:u,action:h})}),r.forEach(({from:l,to:u,action:h})=>{n.add(l),n.add(u),n.add(h+"ing"),t.add(`${l} --> ${h}ing : ${h}`),t.add(`${h}ing --> ${u} : ${h} \u{1F7E2}`),t.add(`${h}ing --> ${l} : ${h} \u{1F534}`)}),s.forEach(({to:l,action:u})=>{t.add(`${u}ing --> ${l} : ${u} \u{1F7E2}`),n.forEach(h=>{h!==l&&t.add(`${h} --> ${u}ing : ${u}`)})});let d=[...t];return Object.defineProperties(i,{stateDiagram:{value:d},allStates:{value:n}}),d}static get(i){let e;return typeof i=="string"?(e=o.instances.get(i),e||o.instances.set(i,e=new o(i,void 0,Object.create(o.prototype)))):(e=o.instances2.get(i),e||o.instances2.set(i,e=new o(i.constructor.name,void 0,Object.create(o.prototype)))),e}static getState(i){var e;return(e=o.get(i))===null||e===void 0?void 0:e.state}updateDevTools(i={}){UT(o.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){An.call(this,i)}};j.STATECHANGED="stateChanged";j.UPDATEAFSM="updateAFSM";j.INIT="[*]";j.ON="on";j.OFF="off";j.instances=new Map;j.instances2=new WeakMap;var mu=typeof window!="undefined",Mp=mu&&window.requestIdleCallback||function(o){let i=Date.now();return setTimeout(()=>{o({didTimeout:!1,timeRemaining(){return Math.max(0,50-(Date.now()-i))}})},1e3)},VT=mu&&window.cancelIdleCallback||function(o){clearTimeout(o)},Op=mu&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),Fe=class Fe{static generateTaskID(){return this.currentTaskID++}static run(i,e,t){t!=null&&t.fps&&(t.delay=t.delay||Number((1e3/t.fps).toFixed(2))),i==="interval"?t=M({delay:2e3,count:0,backgroundTask:!0},t):i==="ric"?t=M({delay:1e4,count:0},t):i==="raf"?t=M({fps:60,delay:16.6,count:0,backgroundTask:!0},t):t=M({delay:2e3,count:0,backgroundTask:!0},t);let r=w(M({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:i,callback:e},t),{delay:t.delay});return this.taskMap.set(r.taskID,r),this[i](r),r.taskID}static interval(i){let e=()=>{i.callback(),i.loopCount+=1,Fe.isBreakLoop(i)};return i.intervalID=setInterval(e,i.delay)}static intervalInWorker(i){Fe.sharedWorker||(Fe.sharedWorker=new Worker(URL.createObjectURL(new Blob([`
11
+ `,h+=s)),r&&(h+=`
12
+ Refer to: ${pp("en",a)}
13
+ `),h}var cu=Je(Ap(),1);var vT=1,NT=0,fc=class{constructor(i=!0){d(this,"countMap",new Map);d(this,"distributionMap",new Map);d(this,"version");d(this,"log",R.createLogger({id:"kv"}));i&&(S.on("102",({track:e,cost:t})=>{this.addSuccessEvent({key:e.kind===p.AUDIO?501700:511700,cost:t})}),S.on("103",({track:e,error:t})=>{this.addFailedEvent({key:e.kind===p.AUDIO?501700:511700,error:t})}),S.on("266",({enable:e})=>{this.log.info(`${e?"enable":"disable"} sso`),e?this.addSuccessEvent({key:525701}):this.addFailedEvent({key:525701})}))}getReportData(i,e){let t={msg_sdk_basic_info:{uint32_sdk_version:Oa(this.version||$e),uint32_terminal_type:15,bytes_device_name:"",bytes_os_version:"",uint32_framework:30,uint32_network_type:0},stats_count:[...this.countMap.entries()].map(([r,s])=>({uint32_key:r,uint32_count:s})),stats_distribution:[...this.distributionMap.entries()].map(([r,s])=>({uint32_key:r,distribution_items:[...s.entries()].map(([n,a])=>({uint32_item_key:n,uint32_item_value:a}))})),str_user_sig:i,bytes_report_token:e};return this.countMap.clear(),this.distributionMap.clear(),t}clear(){this.countMap.clear(),this.distributionMap.clear()}isEnumKey(i){let e=+String(i).slice(-3);return e>=700&&e<799}isErrorCodeKey(i){let e=+String(i).slice(-3);return e>=600&&e<699}isCountKey(i){let e=+String(i).slice(-3);return e>=0&&e<599}isNumberKey(i){let e=+String(i).slice(-3);return e>=800&&e<899}addCount({key:i,useUV:e=!1}){if(!this.isCountKey(i)){this.log.debug(`${i} is not count key, last 3 number should be 0~599`);return}e&&this.countMap.has(i)||this.countMap.set(i,(this.countMap.get(i)||0)+1)}addEnum({key:i,value:e,useUV:t=!0}){var s;if(!this.isEnumKey(i))return this.log.debug(`${i} is not enum key, last 3 number should be 700~799`);if(t&&this.countMap.has(i))return;this.countMap.set(i,(this.countMap.get(i)||0)+1);let r=((s=this.distributionMap)==null?void 0:s.get(i))||new Map;r.set(e,(r.get(e)||0)+1),this.distributionMap.set(i,r)}addNumber({key:i,value:e,split:t=100,useUV:r=!1,max:s=5e3}){var c;if(!this.isNumberKey(i))return this.log.debug(`${i} is not number key, last 3 number should be 800~899`);if(r&&this.countMap.has(i))return;e>s&&(e=s),this.countMap.set(i,(this.countMap.get(i)||0)+1);let n=((c=this.distributionMap)==null?void 0:c.get(i))||new Map,a=0;if(Q(t))a=Math.floor(e/t);else for(let l=t.length-1;l>0;l--)if(e>t[l]){a=l;break}n.set(a,(n.get(a)||0)+1),this.distributionMap.set(i,n)}addSuccessEvent({key:i,cost:e,timeKey:t,split:r}){if(i&&(this.addEnum({key:i,value:vT,useUV:!1}),e)){let s=+String(i).slice(-3);s<800&&s>=700?this.addNumber({key:t||i+100,value:e,split:r}):t||this.log.debug(`time stat ignored, ${i}`)}}addFailedEvent({key:i,error:e}){if(!i)return;let t=I.UNKNOWN;e&&(Q(e)?t=e:(!T(e.extraCode)||!T(e.code))&&(t=e.extraCode||e.code)),this.addEnum({key:i,value:NT,useUV:!1}),this.addEnum({key:i,value:Math.abs(t),useUV:!1})}},_c=(y=>(y[y.enterRoom=500700]="enterRoom",y[y.exitRoom=500701]="exitRoom",y[y.switchRole=500702]="switchRole",y[y.destroy=500703]="destroy",y[y.startLocalAudio=500704]="startLocalAudio",y[y.updateLocalAudio=500705]="updateLocalAudio",y[y.stopLocalAudio=500706]="stopLocalAudio",y[y.startLocalVideo=500707]="startLocalVideo",y[y.updateLocalVideo=500708]="updateLocalVideo",y[y.stopLocalVideo=500709]="stopLocalVideo",y[y.startScreenShare=500710]="startScreenShare",y[y.updateScreenShare=500711]="updateScreenShare",y[y.stopScreenShare=500712]="stopScreenShare",y[y.startRemoteVideo=500713]="startRemoteVideo",y[y.updateRemoteVideo=500714]="updateRemoteVideo",y[y.stopRemoteVideo=500715]="stopRemoteVideo",y[y.muteRemoteAudio=500716]="muteRemoteAudio",y[y.setRemoteAudioVolume=500717]="setRemoteAudioVolume",y[y.use=500718]="use",y[y.switchRoom=500719]="switchRoom",y[y.sendSEIMessage=5e5]="sendSEIMessage",y[y.sendCustomMessage=500001]="sendCustomMessage",y))(_c||{}),su=(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[u.VideoMixer=594700]="VideoMixer",u[u.AudioProcessor=595700]="AudioProcessor",u))(su||{}),nu=(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[u.VideoMixer=594701]="VideoMixer",u[u.AudioProcessor=595701]="AudioProcessor",u))(nu||{}),au=(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[u.VideoMixer=594702]="VideoMixer",u[u.AudioProcessor=595702]="AudioProcessor",u))(au||{});var ss=(w=>(w[w.DECODER_TYPE=514700]="DECODER_TYPE",w[w.DECODER_HW_SW=514701]="DECODER_HW_SW",w[w.DECODE_RESULT=514702]="DECODE_RESULT",w[w.DECODE_FAILED_OS=514703]="DECODE_FAILED_OS",w[w.DOWNGRADE_RESULT=514704]="DOWNGRADE_RESULT",w[w.DOWNGRADE_WEBCODECS_VIDEO=514705]="DOWNGRADE_WEBCODECS_VIDEO",w[w.DOWNGRADE_WEBCODECS_2D=514706]="DOWNGRADE_WEBCODECS_2D",w[w.DOWNGRADE_WASM_WEGBL=514707]="DOWNGRADE_WASM_WEGBL",w[w.DOWNGRADE_WASM_VIDEO=514708]="DOWNGRADE_WASM_VIDEO",w[w.DOWNGRADE_WASM_2D=514709]="DOWNGRADE_WASM_2D",w[w.DECODE_H264_RESULT=514710]="DECODE_H264_RESULT",w[w.DECODE_H265_RESULT=514711]="DECODE_H265_RESULT",w[w.DECODE_VP8_RESULT=514712]="DECODE_VP8_RESULT",w[w.DECODE_CAPABILITIES=514713]="DECODE_CAPABILITIES",w[w.H264_PROFILE_LEVEL_ID_HIGH=514714]="H264_PROFILE_LEVEL_ID_HIGH",w[w.H264_PROFILE_LEVEL_ID_MAIN=514715]="H264_PROFILE_LEVEL_ID_MAIN",w[w.RENDER_FREEZE_RATE=514850]="RENDER_FREEZE_RATE",w[w.DATA_FREEZE_RATE=514851]="DATA_FREEZE_RATE",w[w.VIDEO_CONSUME_RENDER_RATE=514852]="VIDEO_CONSUME_RENDER_RATE",w))(ss||{});var DT=new fc(!0),ro=new fc(!1);var v=DT;var ie={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}},MT=new Map([[te,["Firefox",$a]],[Xo,["Edg",Wa]],[es,["Chrome",oc]],[Ce,["Safari",Xi]],[ri,["TBS",ja]],[Ji,["XWEB",Xa]],[ji&&Ir,["WeChat",za]],[Zs,["QQ(Win)",Qa]],[Qo,["QQ(Mobile)",qo]],[zo,["QQ(Mobile X5)",qo]],[Ks,["QQ(Mac)",Ya]],[en,["QQ(iPad)",Za]],[rn,["MI",Ka]],[on,["HW",ec]],[nn,["Samsung",tc]],[Yo,["OPPO",ic]],[an,["VIVO",rc]],[zr,["EDGE",Ga]],[Qs,["SogouMobile",qa]],[Ys,["Sogou",Ja]]]);function OT(){let o=MT.get(!0),i=o?o[0]:"unknown",e=o?o[1]:"unknown";return{browserName:i,browserVersion:e}}var lu=function(){return!(Ol||zr||Xo&&Dl<80||te&&jo<56)},gn=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder"].every(i=>i in window)},Ec=function(){if(!navigator.mediaDevices)return Zi()||R.error(Xe.NOT_SUPPORTED_MEDIA),!1;let o=["getUserMedia","enumerateDevices"];return o.filter(i=>i in navigator.mediaDevices).length===o.length},Cp=!1;function Zi(){return location.protocol==="http:"&&!si?(Cp||R.error($({key:B.NOT_SUPPORTED_HTTP})),Cp=!0,!0):!1}var Tn=function(){return(window==null?void 0:window.OffscreenCanvas)&&(window==null?void 0:window.MediaStreamTrackProcessor)&&(window==null?void 0:window.MediaStreamTrackGenerator)},kT=function(){return!!(window!=null&&window.MediaStreamTrackGenerator)},uu=function(){return f(this,null,function*(){var r,s,n;if(ie.detail.isH264EncodeSupported&&ie.detail.isVp8EncodeSupported)return{isH264EncodeSupported:ie.detail.isH264EncodeSupported,isVp8EncodeSupported:ie.detail.isVp8EncodeSupported,isH265EncodeSupported:ie.detail.isH265EncodeSupported};let o,i=!1,e=!1,t=!1;try{let a=new RTCPeerConnection,c=document.createElement(p.CANVAS);c.getContext("2d");let l=c.captureStream(0);return a.addTrack(l.getVideoTracks()[0],l),o=yield a.createOffer(),i=((r=o.sdp)==null?void 0:r.toLowerCase().indexOf("h264"))!==-1,e=((s=o.sdp)==null?void 0:s.toLowerCase().indexOf("vp8"))!==-1,t=((n=o.sdp)==null?void 0:n.toLowerCase().indexOf("h265"))!==-1,a.close(),{isH264EncodeSupported:i,isVp8EncodeSupported:e,isH265EncodeSupported:t}}catch(a){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1}}})},Sc=function(){return f(this,null,function*(){var t;if(ie.detail.isH264DecodeSupported&&ie.detail.isVp8DecodeSupported)return{isH264DecodeSupported:ie.detail.isH264DecodeSupported,isVp8DecodeSupported:ie.detail.isVp8DecodeSupported,isH265DecodeSupported:ie.detail.isH265DecodeSupported};let o,i=!1,e=!1;try{let r=new RTCPeerConnection;St()?(r.addTransceiver(p.VIDEO,{direction:"recvonly"}),o=yield r.createOffer()):o=yield r.createOffer({offerToReceiveVideo:!0}),o.sdp.toLowerCase().indexOf("h264")!==-1&&(i=!0),o.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0);let s=((t=o.sdp)==null?void 0:t.toLowerCase().indexOf("h265"))!==-1;return r.close(),{isH264DecodeSupported:i,isVp8DecodeSupported:e,isH265DecodeSupported:s}}catch(r){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}}})};function PT(){return f(this,null,function*(){let[o,i]=yield Promise.all([uu(),Sc()]);return{encode:{h264:o.isH264EncodeSupported,vp8:o.isVp8EncodeSupported,h265:o.isH265EncodeSupported},decode:{h264:i.isH264DecodeSupported,vp8:i.isVp8DecodeSupported,h265:i.isH265DecodeSupported}}})}var Ic=ka(o=>f(void 0,null,function*(){let i=Date.now(),e=_u(),t=Ec(),r=gn();if(ie.detail.isWebRTCSupported=e,ie.detail.isMediaDevicesSupported=t,ie.detail.isWebCodecsSupported=r,ie.detail.isScreenShareSupported=En(),ie.detail.isSmallStreamSupported=Cc(),o===37)return Object.assign(ie.detail,yield UT()),ie.detail.isBrowserSupported=r,ie.result=t&&r,ie.result||R.error(`${navigator.userAgent} ${Js(ie.detail,!1)}`),Rp(o),v.addNumber({key:523800,value:Date.now()-i}),ie;if(ie.result&&ie.detail.isH264EncodeSupported&&ie.detail.isVp8EncodeSupported&&ie.detail.isH265EncodeSupported&&ie.detail.isH264DecodeSupported&&ie.detail.isVp8DecodeSupported&&ie.detail.isH265DecodeSupported)return ie;let s=lu(),{encode:n,decode:a}=yield PT(),{h264:c,vp8:l}=n,{h264:h}=a,{h265:m}=n,{vp8:u,h265:_}=a;if(!c||!l){let g=yield uu();R.warn(`detect encode again h264:${c} vp8:${l} result: ${JSON.stringify(g)}`),c=g.isH264EncodeSupported,l=g.isVp8EncodeSupported}if(c&&h&&fe&&We&&!Ji&&!ri&&!(Yo&&je===115)){let{encode:g,decode:E}=yield xT();c=g,h=E}return ie.result=s&&e&&t&&(c||l)&&(h||u),ie.detail.isBrowserSupported=s,ie.detail.isWebRTCSupported=e,ie.detail.isH264EncodeSupported=c,ie.detail.isVp8EncodeSupported=l,ie.detail.isH265EncodeSupported=m,ie.detail.isH264DecodeSupported=h,ie.detail.isVp8DecodeSupported=u,ie.detail.isH265DecodeSupported=_,ie.result||R.error(`${navigator.userAgent} ${Js(ie.detail,!1)}`),Rp(),v.addNumber({key:523800,value:Date.now()-i}),ie})),wT=function(){return ie.result},En=function(){return!!(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)},LT=typeof HTMLMediaElement!="undefined"&&"setSinkId"in HTMLMediaElement.prototype,gc=null;function xT(){return f(this,null,function*(){return gc||(gc=new Promise(o=>f(this,null,function*(){let i={encode:!1,decode:!1},e=()=>{};try{let t=document.createElement("canvas"),r=t.getContext("2d");t.width=640,t.height=480;let s=setInterval(()=>{r.fillText("test",Math.floor(Math.random()*640),Math.floor(Math.random()*480))},66),n=-1,a=-1;e=()=>{clearInterval(n),clearInterval(s),clearTimeout(a),l.close(),h.close(),c.getTracks().forEach(E=>E.stop())},a=setTimeout(()=>{e(),o(i)},2*1e3);let c=t.captureStream(),l=new RTCPeerConnection({}),h=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});l.addEventListener("icecandidate",E=>h.addIceCandidate(E.candidate)),h.addEventListener("icecandidate",E=>l.addIceCandidate(E.candidate)),l.addTrack(c.getVideoTracks()[0],c);let m=yield l.createOffer();yield l.setLocalDescription(m),yield h.setRemoteDescription(m);let u=yield h.createAnswer(),_=cu.default.parse(u.sdp),g=_.media[0].rtp.findIndex(E=>E.codec==="H264");_.media[0].rtp=[_.media[0].rtp[g]],_.media[0].fmtp=_.media[0].fmtp.filter(E=>E.payload===_.media[0].rtp[0].payload),_.media[0].rtcpFb&&(_.media[0].rtcpFb=_.media[0].rtcpFb.filter(E=>E.payload===_.media[0].rtp[0].payload)),u.sdp=cu.default.write(_),yield h.setLocalDescription(u),yield l.setRemoteDescription(u),n=setInterval(()=>f(this,null,function*(){i.encode&&i.decode&&(e(),o(i));let[E,A]=yield Promise.all([l.getSenders()[0].getStats(),h.getReceivers()[0].getStats()]);i.encode||E.forEach(k=>{k.type==="outbound-rtp"&&k.mediaType===p.VIDEO&&k.bytesSent>0&&(i.encode=!0)}),i.decode||A.forEach(k=>{k.type==="inbound-rtp"&&k.mediaType===p.VIDEO&&k.bytesReceived>0&&(i.decode=!0)})}),100)}catch(t){e(),R.warn("detectH264Supported failed",t),o({encode:!0,decode:!0})}})).then(o=>(o.encode||(o.decode=!0),(!o.encode||!o.decode)&&R.warn(`detectH264Supported encode: ${o.encode} decode: ${o.decode} ${ii}`),o)),gc)})}var Tc=null;function UT(){return f(this,null,function*(){return Tc||(Tc=new Promise(o=>f(this,null,function*(){let i={isH264EncodeSupported:!1,isH264DecodeSupported:!1,isVp8EncodeSupported:!1,isVp8DecodeSupported:!1};if(!gn()){o(i);return}let e=null,t=null,r=null,s=()=>{r&&clearTimeout(r),e=null,t=null};try{e=document.createElement("canvas"),t=e.getContext("2d"),e.width=320,e.height=240;let n=0,a=()=>{!t||!e||(t.fillStyle=`hsl(${n%360}, 50%, 50%)`,t.fillRect(0,0,e.width,e.height),t.fillStyle="white",t.font="20px Arial",t.fillText(`Frame ${n}`,10,30),n++)};r=setTimeout(()=>{s(),o(i)},5e3);let c=[{type:"h264",encodeConfig:{codec:"avc1.42E01E",avc:{format:"annexb"},width:320,height:240,bitrate:1e6},decodeConfig:{codec:"avc1.42E01E",avc:{format:"annexb"}}},{type:"vp8",encodeConfig:{codec:"vp8",width:320,height:240,bitrate:1e6},decodeConfig:{codec:"vp8"}}];(yield Promise.all(c.map(h=>f(this,null,function*(){let m={type:h.type,encodeSupported:!1,decodeSupported:!1},u;try{u=yield new Promise((_,g)=>f(this,null,function*(){try{let E=new VideoEncoder({output:k=>{_(k),m.encodeSupported=!0},error:g});E.configure(h.encodeConfig),a();let A=new VideoFrame(e,{timestamp:0});E.encode(A,{keyFrame:!0}),A.close(),yield E.flush(),E.close()}catch(E){g(E)}}))}catch(_){return R.warn(`${h.type} encoder error:`,_),m}try{yield new Promise((_,g)=>f(this,null,function*(){try{let E=new VideoDecoder({output:A=>{m.decodeSupported=!0,_(0),A.close()},error:g});E.configure(h.decodeConfig),E.decode(u),yield E.flush(),E.close()}catch(E){g(E)}}))}catch(_){R.warn(`${h.type} decoder error:`,_)}return m})))).forEach(h=>{h.type==="h264"?(i.isH264EncodeSupported=h.encodeSupported,i.isH264DecodeSupported=h.decodeSupported):h.type==="vp8"&&(i.isVp8EncodeSupported=h.encodeSupported,i.isVp8DecodeSupported=h.decodeSupported)}),s(),o(i)}catch(n){s(),R.warn("detectWebCodecsSupported failed:",n),o(i)}})),Tc)})}var VT=(o,i,e)=>{location.protocol==="http:"&&!si&&(o[i]=()=>{throw new D({code:I.INVALID_OPERATION,message:Xe.NOT_SUPPORTED_HTTP})})},Rr=function(o){return o.type==="candidate-pair"&&o.nominated&&(o.state==="in-progress"||o.state==="succeeded")?!(he(o.selected)&&!o.selected):!1};function vp(){let o="";if(screen.width){let i=screen.width?screen.width*window.devicePixelRatio:"",e=screen.height?screen.height*window.devicePixelRatio:"";o+=`${i} * ${e}`}return o}function Np(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function Dp(){let o={isSupported:!1},i=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"];for(let e=0;e<i.length;e++)if(i[e]in window){o.isSupported=!0;break}return o.isSupported}function Mp(){return"captureStream"in HTMLCanvasElement.prototype}function Ac(){return ji||Ee||je&&je<63?!1:!!(lu()&&Mp())}function Op(){return!(je<74||zr||et<11||jo<46)}function Cc(){return Ac()||Op()}var FT=function(){if(T(window.RTCRtpTransceiver)||!St()||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let o=null,i=!1;try{o=new RTCPeerConnection({sdpSemantics:gr}),o.addTransceiver(p.AUDIO),i=!0}catch(e){}return o==null||o.close(),i};function oo(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function yr(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function br(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function St(){return et===11&&!Vl?!1:"RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype}var ns=!(!St()||We&&je<86);function BT(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}var Sn="RTCRtpSender"in window;function hu(){return Sn&&"replaceTrack"in window.RTCRtpSender.prototype}function In(){return Sn&&"setParameters"in window.RTCRtpSender.prototype&&yr()}var mu="RTCRtpReceiver"in window&&"getSynchronizationSources"in window.RTCRtpReceiver.prototype,bi=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,pu=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,fu=typeof InputDeviceInfo!="undefined"&&"getCapabilities"in InputDeviceInfo.prototype,mi=Sn&&"createEncodedStreams"in window.RTCRtpSender.prototype&&Ko()>=86,as="RTCRtpScriptTransform"in window,An=Sn&&(mi||as),_u=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(i=>i in window).length>0};function Rc(){let o={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return T(window.AudioDecoder)||(o.AudioDecoder=!0),T(window.AudioEncoder)||(o.AudioEncoder=!0),T(window.VideoDecoder)||(o.VideoDecoder=!0),T(window.VideoEncoder)||(o.VideoEncoder=!0),T(window.ImageDecoder)||(o.ImageDecoder=!0),o}function kp(){return"mediaSession"in navigator&&!T(navigator.mediaSession.setActionHandler)}function Pp(){return!T(window.WebTransport)}function gu(){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 HT(){let o={browser:`${Ri.name}/${Ri.version}`,os:nc(),displayResolution:vp(),isScreenShareSupported:En(),isWebRTCSupported:_u(),isGetUserMediaSupported:Np(),isWebAudioSupported:Dp(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:Rc(),isMediaSessionSupported:kp(),isWebTransportSupported:Pp()};return navigator.userAgent.includes("miniProgram")&&(o.browser=`mini/${o.browser}`),o}var wp="checkResult";function Rp(o=30){is.setItem(wp+o,{ua:navigator.userAgent,checkResult:ie})}function Tu(o){Zi();let i=is.getItem(wp+o);i&&i.ua===navigator.userAgent&&i.checkResult&&$T(i.checkResult.detail,ie.detail)&&(ie=i.checkResult),Ic(o)}function $T(o,i){return yt(o)?Object.keys(i).every(e=>e in o):!1}function Ki(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var yc="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype;function yp(o){return{h264:1,h265:2,vp8:3,vp9:4,av1:5}[o]}var bp=!1;function Eu(){return f(this,null,function*(){var o;try{if(bp||!((o=navigator==null?void 0:navigator.mediaCapabilities)!=null&&o.encodingInfo))return;let i=Zr(),e=Bl();if(i===0||e===0)return;bp=!0;let t=["H264","VP8","VP9","AV1","H265"],[r,s]=yield Promise.all([Lp(t),xp(t)]);r&&Object.keys(r).forEach(c=>{let l=yp(c.toLowerCase());v.addEnum({key:513707,value:+`${l}${+r[c].supported}${+r[c].powerEfficient}${i}${e}`,useUV:!1})}),s&&Object.keys(s).forEach(c=>{let l=yp(c.toLowerCase());v.addEnum({key:514713,value:+`${l}${+s[c].supported}${+s[c].powerEfficient}${i}${e}`,useUV:!1})});let{sender:n,receiver:a}=Up();v.addEnum({key:513708,value:+`${i}${e}${+n.high}`,useUV:!1}),v.addEnum({key:513709,value:+`${i}${e}${+n.main}`,useUV:!1}),v.addEnum({key:514714,value:+`${i}${e}${+a.high}`,useUV:!1}),v.addEnum({key:514715,value:+`${i}${e}${+a.main}`,useUV:!1})}catch(i){R.info("detectVideoCodecCapabilities failed",i)}})}function Lp(o,i=1920,e=1080,t=30,r=3e3){return f(this,null,function*(){let s={};try{for(let n of o){let a=yield navigator.mediaCapabilities.encodingInfo({type:"webrtc",video:{contentType:`video/${n}`,width:i,height:e,bitrate:r,framerate:t}});s[n]=a}}catch(n){}return s})}function xp(o,i=1920,e=1080,t=30,r=3e3){return f(this,null,function*(){let s={};try{for(let n of o){let a=yield navigator.mediaCapabilities.decodingInfo({type:"webrtc",video:{contentType:`video/${n}`,width:i,height:e,bitrate:r,framerate:t}});s[n]=a}}catch(n){}return s})}function Up(){let o={sender:{base:!1,main:!1,high:!1},receiver:{base:!1,main:!1,high:!1}};try{if(RTCRtpSender&&typeof RTCRtpSender.getCapabilities=="function"){let i=RTCRtpSender.getCapabilities("video");i&&i.codecs&&i.codecs.filter(t=>t.mimeType.toLowerCase()==="video/h264").forEach(t=>{if(t.sdpFmtpLine){let r=t.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(r&&r[1])switch(r[1].slice(0,2)){case"42":o.sender.base=!0;break;case"4d":o.sender.main=!0;break;case"64":o.sender.high=!0;break}}})}if(RTCRtpReceiver&&typeof RTCRtpReceiver.getCapabilities=="function"){let i=RTCRtpReceiver.getCapabilities("video");i&&i.codecs&&i.codecs.filter(t=>t.mimeType.toLowerCase()==="video/h264").forEach(t=>{if(t.sdpFmtpLine){let r=t.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(r&&r[1])switch(r[1].slice(0,2)){case"42":o.receiver.base=!0;break;case"4d":o.receiver.main=!0;break;case"64":o.receiver.high=!0;break}}})}}catch(i){R.warn("get H264 profile levelId failed",i)}return o}var Fp=Je(at(),1);var Vp=Symbol("instance"),xC=Symbol("abortCtrl"),bc=Symbol("cacheResult"),Cn=class{constructor(i,e,t){this.oldState=i,this.newState=e,this.action=t,this.aborted=!1}abort(i){this.aborted=!0,bn.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},Rn=class extends Error{constructor(i,e,t){super(e),this.state=i,this.message=e,this.cause=t}};function GT(o){return typeof o=="object"&&o&&"then"in o}var yn=new Map;function be(o,i,e={}){return(t,r,s)=>{let n=e.action||r;if(!e.context){let c=yn.get(t)||[];yn.has(t)||yn.set(t,c),c.push({from:o,to:i,action:n})}let a=s.value;s.value=function(...c){let l=this;if(e.context&&(l=j.get(typeof e.context=="function"?e.context.call(this,...c):e.context)),l.state===i)return e.sync?l[bc]:Promise.resolve(l[bc]);l.state instanceof Cn&&l.state.action==e.abortAction&&l.state.abort(l);let h=null;Array.isArray(o)?o.length==0?l.state instanceof Cn&&l.state.abort(l):(typeof l.state!="string"||!o.includes(l.state))&&(h=new Rn(l._state,`${l.name} ${n} to ${i} failed: current state ${l._state} not from ${o.join("|")}`)):o!==l.state&&(h=new Rn(l._state,`${l.name} ${n} to ${i} failed: current state ${l._state} not from ${o}`));let m=A=>{if(e.fail&&e.fail.call(this,A),e.sync){if(e.ignoreError)return A;throw A}else return e.ignoreError?Promise.resolve(A):Promise.reject(A)};if(h)return m(h);let u=l.state,_=new Cn(u,i,n);bn.call(l,_);let g=A=>{var k;return l[bc]=A,_.aborted||(bn.call(l,i),(k=e.success)===null||k===void 0||k.call(this,l[bc])),A},E=A=>(bn.call(l,u,A),m(A));try{let A=a.apply(this,c);return GT(A)?A.then(g).catch(E):e.sync?g(A):Promise.resolve(g(A))}catch(A){return E(new Rn(l._state,`${l.name} ${n} from ${o} to ${i} failed: ${A}`,A instanceof Error?A:new Error(String(A))))}}}}var WT=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 bn(o,i){let e=this._state;this._state=o;let t=o.toString();o&&this.emit(t,e),this.emit(j.STATECHANGED,o,e,i),this.updateDevTools({value:o,old:e,err:i instanceof Error?i.message:String(i)})}var j=class o extends Fp.default{constructor(i,e,t){super(),this.name=i,this.groupName=e,this._state=o.INIT,i||(i=Date.now().toString(36)),t?Object.setPrototypeOf(this,t):t=Object.getPrototypeOf(this),e||(this.groupName=this.constructor.name);let r=t[Vp];r?this.name=r.name+"-"+r.count++:t[Vp]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let i=Object.getPrototypeOf(this),e=yn.get(i)||[],t=new Set,r=[],s=[],n=new Set,a=Object.getPrototypeOf(i);yn.has(a)&&(a.stateDiagram.forEach(l=>t.add(l)),a.allStates.forEach(l=>n.add(l))),e.forEach(({from:l,to:h,action:m})=>{typeof l=="string"?r.push({from:l,to:h,action:m}):l.length?l.forEach(u=>{r.push({from:u,to:h,action:m})}):s.push({to:h,action:m})}),r.forEach(({from:l,to:h,action:m})=>{n.add(l),n.add(h),n.add(m+"ing"),t.add(`${l} --> ${m}ing : ${m}`),t.add(`${m}ing --> ${h} : ${m} \u{1F7E2}`),t.add(`${m}ing --> ${l} : ${m} \u{1F534}`)}),s.forEach(({to:l,action:h})=>{t.add(`${h}ing --> ${l} : ${h} \u{1F7E2}`),n.forEach(m=>{m!==l&&t.add(`${m} --> ${h}ing : ${h}`)})});let c=[...t];return Object.defineProperties(i,{stateDiagram:{value:c},allStates:{value:n}}),c}static get(i){let e;return typeof i=="string"?(e=o.instances.get(i),e||o.instances.set(i,e=new o(i,void 0,Object.create(o.prototype)))):(e=o.instances2.get(i),e||o.instances2.set(i,e=new o(i.constructor.name,void 0,Object.create(o.prototype)))),e}static getState(i){var e;return(e=o.get(i))===null||e===void 0?void 0:e.state}updateDevTools(i={}){WT(o.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){bn.call(this,i)}};j.STATECHANGED="stateChanged";j.UPDATEAFSM="updateAFSM";j.INIT="[*]";j.ON="on";j.OFF="off";j.instances=new Map;j.instances2=new WeakMap;var Iu=typeof window!="undefined",Bp=Iu&&window.requestIdleCallback||function(o){let i=Date.now();return setTimeout(()=>{o({didTimeout:!1,timeRemaining(){return Math.max(0,50-(Date.now()-i))}})},1e3)},qT=Iu&&window.cancelIdleCallback||function(o){clearTimeout(o)},Hp=Iu&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),Be=class Be{static generateTaskID(){return this.currentTaskID++}static run(i,e,t){t!=null&&t.fps&&(t.delay=t.delay||Number((1e3/t.fps).toFixed(2))),i==="interval"?t=O({delay:2e3,count:0,backgroundTask:!0},t):i==="ric"?t=O({delay:1e4,count:0},t):i==="raf"?t=O({fps:60,delay:16.6,count:0,backgroundTask:!0},t):t=O({delay:2e3,count:0,backgroundTask:!0},t);let r=L(O({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:i,callback:e},t),{delay:t.delay});return this.taskMap.set(r.taskID,r),this[i](r),r.taskID}static interval(i){let e=()=>{i.callback(),i.loopCount+=1,Be.isBreakLoop(i)};return i.intervalID=setInterval(e,i.delay)}static intervalInWorker(i){Be.sharedWorker||(Be.sharedWorker=new Worker(URL.createObjectURL(new Blob([`
14
14
  const timers = new Map();
15
15
  self.onmessage = function(e) {
16
16
  const { taskId, delay, type } = e.data;
@@ -23,15 +23,15 @@ Refer to: ${op("en",a)}
23
23
  timers.delete(taskId);
24
24
  }
25
25
  };
26
- `],{type:"application/javascript"}))),Fe.sharedWorker.onmessage=e=>{var t;if(e.data.type==="tick"){let r=Fe.workerTasks.get(e.data.taskId);r&&(Fe.isBreakLoop(r)?((t=Fe.sharedWorker)==null||t.postMessage({type:"stop",taskId:r.taskID}),Fe.workerTasks.delete(r.taskID)):(r.callback(),r.loopCount+=1))}}),Fe.workerTasks.set(i.taskID,i),Fe.sharedWorker.postMessage({taskId:i.taskID,delay:i.delay,type:"start"})}static timeout(i){let e=()=>{if(i.callback(),i.loopCount+=1,!Fe.isBreakLoop(i))return i.timeoutID=setTimeout(e,i.delay)};return i.timeoutID=setTimeout(e,i.delay)}static ric(i){let e=V(),t,r=()=>{if(t=V()-e,t>=i.delay&&(e=V()-Math.floor(t%i.delay),i.callback(),i.loopCount+=1),!Fe.isBreakLoop(i))return i.ricID=Mp(r,{timeout:i.delay})};return i.ricID=Mp(r,{timeout:i.delay})}static raf(i){let e=V(),t,r=()=>{if(document.hidden&&i.backgroundTask)return t=V()-e,e=V(),i.callback(),i.loopCount+=1,Fe.isBreakLoop(i)?void 0:i.timeoutID=setTimeout(r,i.delay-Math.floor(t%i.delay));if(t=V()-e,t>=i.delay&&(e=V()-Math.floor(t%i.delay),i.callback(),i.loopCount+=1),!Fe.isBreakLoop(i))return i.rafID=requestAnimationFrame(r)};if(i.rafID=requestAnimationFrame(r),i.backgroundTask){let s=()=>{if(document.hidden){let n=V()-e;n>=i.delay?r():i.timeoutID=setTimeout(r,i.delay-n)}};document.addEventListener("visibilitychange",s),i.onVisibilitychange=s,document.hidden&&s()}return i.taskID}static hasTask(i){return this.taskMap.has(i)}static clearTask(i){if(!this.taskMap.has(i))return!0;let{intervalID:e,timeoutID:t,rafID:r,ricID:s,onVisibilitychange:n}=this.taskMap.get(i);return e&&clearInterval(e),t&&clearTimeout(t),r&&Op&&Op(r),s&&VT(s),n&&document.removeEventListener("visibilitychange",n),this.taskMap.delete(i),!0}static isBreakLoop(i){return this.hasTask(i.taskID)?i.count!==0&&i.loopCount>=i.count?(this.clearTask(i.taskID),!0):!1:!0}};c(Fe,"taskMap",new Map),c(Fe,"currentTaskID",1),c(Fe,"sharedWorker",null),c(Fe,"workerTasks",new Map);var hu=Fe,oe=hu;var FC={STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",STREAM_UPDATED:"stream-updated",STREAM_SUBSCRIBED:"stream-subscribed",CONNECTION_STATE_CHANGED:"connection-state-changed",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",MUTE_AUDIO:"mute-audio",MUTE_VIDEO:"mute-video",UNMUTE_AUDIO:"unmute-audio",UNMUTE_VIDEO:"unmute-video",CLIENT_BANNED:"client-banned",NETWORK_QUALITY:"network-quality",AUDIO_VOLUME:"audio-volume",SEI_MESSAGE:_.SEI_MESSAGE,ERROR:"error"};var he={LOADED_DATA:_.LOADEDDATA,LOADED_META_DATA:_.LOADEDMETADATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error",RESIZE:_.RESIZE,TIME_UPDATE:"time-update"};var Di={};Bi(Di,{create:()=>tt,remove:()=>we});var Cn=new WeakMap;function tt(o,i){Cn.has(o)||Cn.set(o,[]);let e=Cn.get(o),r={add:(s,n)=>("addEventListener"in i?(e.push(i.removeEventListener.bind(i,s,n)),i.addEventListener(s,n)):(e.push(i.off.bind(i,s,n)),i.on(s,n)),r)};return r}function we(o){let i=Cn.get(o);i&&(i.forEach(e=>e()),Cn.delete(o))}var pu=class{constructor(){c(this,"_roomIdMap",new Map);c(this,"_configs");typeof registerProcessor=="undefined"&&(this._configs={sdkAppId:"",userId:"",version:He,env:$i.QCLOUD,browserVersion:yi.name+yi.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){ni||!R.isAbleToUpload||this._configs.env===$i.QCLOUD&&this.uploadEventToKibana(w(M({},i),{result:"success"}))}logFailedEvent(i){if(ni||!R.isAbleToUpload)return;let{eventType:e,code:t,error:r,userId:s}=i,n={roomId:this._roomIdMap.get(s||this._configs.userId),userId:s,eventType:e,result:"failed",code:t||(r==null?void 0:r.extraCode)||(r==null?void 0:r.code)||I.UNKNOWN};this._configs.env===$i.QCLOUD&&this.uploadEventToKibana(w(M({},n),{error:r}))}uploadEventToKibana(i){let e=`stat-${i.eventType}-${i.result}`;(i.eventType==="delta-join"||i.eventType==="delta-leave"||i.eventType==="delta-publish")&&(e=`${i.eventType}:${i.delta}`),this.uploadEvent({log:e,userId:i.userId}),i.result==="failed"&&(e=`stat-${i.eventType}-${i.result}-${i.code}`,this.uploadEvent({log:e,userId:i.userId,error:i.error}))}uploadEvent({log:i,userId:e,error:t}){let r={timestamp:ca(),sdkAppId:this._configs.sdkAppId,userId:e||this._configs.userId,version:He,log:i};t&&(r.errorInfo=t.message,t.stack&&(r.errorInfo+=`
27
- ${t.stack}`));let s=Ir.enable?qi(r,2002,Number(this._configs.sdkAppId)):JSON.stringify(r);this.sendRequest(Ji(this._configs.sdkAppId,mr.LOG),s)}sendRequest(i,e){setTimeout(()=>ji({url:i,body:e,priority:"low"}).catch(()=>{}),2e3)}},se=new pu;var Mi=new WeakMap;function Mt({settings:o={retries:5,timeout:2e3},onError:i,onRetrying:e,onRetryFailed:t}){return function(r,s,n){let a=Ri({retryFunction:n.value,settings:o,onError({error:d,retry:l,reject:u,retryFuncArgs:h}){var p;i?i.call(this,d,()=>{var m;(m=Mi.get(r))!=null&&m.has(s)?l():u(d)},u,h):(p=Mi.get(r))!=null&&p.has(s)?l():u(d)},onRetrying(d,l){var u;Ci(e)&&e.call(this,d,l),(u=Mi.get(r))!=null&&u.has(s)&&(Mi.get(r).get(s).stopRetry=l)},onRetryFailed:t});return n.value=function(...d){let l=Mi.get(r);return l?l.set(s,{args:d}):Mi.set(r,new Map([[s,{args:d}]])),a.apply(this,d).finally(()=>{var u;return(u=Mi.get(r))==null?void 0:u.delete(s)})},n}}function Rn({fnName:o,callback:i,validateArgs:e=!0}){return function(t,r,s){let n=s.value;return s.value=function(...a){var d,l;if((d=Mi.get(t))!=null&&d.has(o)){let{stopRetry:u,args:h}=Mi.get(t).get(o),p=!0;if(e){for(let m of h)if(!a.find(g=>g===m)){p=!1;break}}p&&(i&&i.apply(this,a),u&&u(),(l=Mi.get(t))==null||l.delete(o))}return n.apply(this,a)},s}}var fi=class extends j{constructor(e,t){super(e.id,`${t}-player`);this.options=e;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,"_isPausedByUserCall",!1);c(this,"_pausedRetryCount");c(this,"_isElementPlayingFired",!1);c(this,"_interval");c(this,"_delayDestroyTimeoutId",0);c(this,"_playSuccessResolve");c(this,"_isReplayByRecreateMediaStreamCalled",!1);c(this,"isPlayCalled",!1);c(this,"isInAutoPlayFailedState",!1);this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=$r,this._state="STOPPED",this.bindTrackEvents(),this._log.info(`create ${t}-player ${this.id}`)}get isPlaying(){var e;return this._state==="PLAYING"&&((e=this.element)==null?void 0:e.paused)===!1}get isPaused(){var e;return this._state==="PAUSED"||((e=this.element)==null?void 0:e.paused)===!0}get isStopped(){return this._state==="STOPPED"}setAttr(e){this.attr=e}setUrl(e){this.track&&(this.unbindTrackEvents(),this.element&&(this.element.srcObject=null),this.track=null),e!==this.url&&(this.url=e,e!==null&&this.element&&(this.element.crossOrigin="anonymous",this.element.src=e))}play(){return f(this,null,function*(){if(!this.isPlaying)try{this.isPlayCalled=!0,this._delayDestroyTimeoutId&&(clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0,this.bindTrackEvents(),this.bindElementEvents()),this.bindAutoPlayEvent(),yield new Promise((e,t)=>{this._playSuccessResolve=e,this.element.play().then(e,t)})}catch(e){let t=$({key:B.PLAY_FAILED,data:{media:this.kind,error:e}});if(this._log.warn(e),t.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new v({code:I.PLAY_NOT_ALLOWED,message:t})}})}stop(e=0){var t;this.isPlayCalled=!1,this._isElementPlayingFired=!1,this.unbindEvents(),e>0&&!Ft?this._delayDestroyTimeoutId||((t=this.element)==null||t.remove(),this._log.info(`destroy element after 3 * ${e}`),this._delayDestroyTimeoutId=setTimeout(()=>this.destroyElement(),3*e)):this.destroyElement(),this.handleStopped(_.ENDED),this._interval>0&&oe.clearTask(this._interval)}destroyElement(){this.element&&(this._log.debug("destroy element"),this.element.remove(),this.element.src="",this.element.srcObject=null,this.element=null),clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0}pause(){var e;this._log.info("pause"),this._isPausedByUserCall=!0,(e=this.element)==null||e.pause()}resume(){return this._isPausedByUserCall=!1,this.doResume()}doResume(){return this._log.info("resume"),this._isPausedByUserCall||this.isPlaying?Promise.resolve():Nl?this.replay():(this.element&&this.track&&Ve&&$e>=128&&(this.element.srcObject=new MediaStream([this.track])),this.play().catch(()=>{}))}setMuted(e){this.element&&(this.element.muted=e),this.muted=e}replay(){return this.stop(),this.play().catch(()=>{})}bindElementEvents(){if(this.element){let e=this.handleElementEvent.bind(this);return tt(this.element,this.element).add(_.PLAYING,e).add(_.ENDED,e).add(_.PAUSE,e).add(_.ERROR,e).add(_.LOADEDDATA,e).add(_.LOADEDMETADATA,e)}}bindTrackEvents(e=this.track){if(e){let t=this.handleTrackEvent.bind(this);Di==null||Di.create(e,e).add(_.ENDED,t).add(_.MUTE,t).add(_.UNMUTE,t),e.readyState===_.ENDED&&this.handleTrackEvent({type:_.ENDED}),e.muted&&this.handleTrackEvent({type:_.MUTE})}}bindAutoPlayEvent(){S.on(A.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(e=this.track){e&&we(e)}unbindEvents(){this.element&&we(this.element),this.unbindTrackEvents(),S.off(A.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case _.PLAYING:br()||(this.isInAutoPlayFailedState=!1),this._isElementPlayingFired=!0,this._log.info(`${this.kind} player is playing`),this.handlePlaying(_.PLAYING),this._interval&&(oe.clearTask(this._interval),this._interval=-1);break;case _.ENDED:this._log.info(`${this.kind} player is ended`),this.handleStopped(_.ENDED);break;case _.PAUSE:this._log.info(`${this.kind} player is paused`),this.handlePaused(_.PAUSE),ge&&(this._interval=oe.run("timeout",()=>{this.element&&this._state==="PAUSED"&&this.doResume()},{delay:3e3}));break;case _.ERROR:if(this.element&&this.element.error){this.handlePaused(_.ERROR);let{code:r,message:s}=this.element.error;this._log.error(`${this.kind} ${this._log.isLocal?"local":"remote"} MediaError code: ${r} message: ${s} userAgent: ${navigator.userAgent}`),se.uploadEvent({log:`stat-${this.kind}-${Ze.PLAYER_ERROR}-${r}-${navigator.userAgent}`,error:this.element.error}),Cl||tn?this.emit(he.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case _.LOADEDDATA:this.kind===_.VIDEO&&this.emit(he.LOADED_DATA);break;case _.LOADEDMETADATA:this.kind===_.VIDEO&&this.emit(he.LOADED_META_DATA);break}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then(()=>{this._log.warn("replayByRecreateMediaStream success"),se.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),y.addSuccessEvent({key:this.kind===_.AUDIO?506700:516700})}).catch(()=>{var t;this._log.error("replayByRecreateMediaStream failed"),se.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),y.addFailedEvent({key:this.kind===_.AUDIO?506700:516700,error:(t=this.element)==null?void 0:t.error}),this.emit(he.ERROR,e)})}doReplayByRecreateMediaStream(e){return this._log.warn(`delay ${e}ms to recreate mediaStream`),new Promise((t,r)=>{Ke(e).then(()=>{this.element&&(this.element.srcObject=null,this.element.srcObject=new MediaStream([this.track]),this._log.warn("recreated mediaStream"),this.element.onerror=()=>{var s,n,a;this._log.warn(`element onerror ${(n=(s=this.element)==null?void 0:s.error)==null?void 0:n.code} fired after recreated mediaStream`),r((a=this.element)==null?void 0:a.error)}),Ke(5e3).then(()=>{var s,n;(!this.isPlaying||(s=this.element)!=null&&s.error)&&r((n=this.element)==null?void 0:n.error),t()})})}).finally(()=>{this.element&&(this.element.onerror=null)})}handleTrackEvent(e){return f(this,null,function*(){switch(e.type){case _.ENDED:this.handleStopped(_.ENDED);break;case _.MUTE:this.handlePaused(_.MUTE);break;case _.UNMUTE:this.mode>0?this.handlePlaying(this.mode.toString()):this.element&&(this.element.paused&&(this._log.warn("track unmuted and element is paused, resume"),yield this.doResume()),this.element&&!this.element.paused&&this._isElementPlayingFired&&this.handlePlaying(_.UNMUTE));break}})}handlePlaying(e){var t;return this._log.debug("handlePlaying",e),(t=this._playSuccessResolve)==null||t.call(this,e),e}handlePaused(e){return this._log.debug("handlePaused",e),e}handleStopped(e){return this._log.debug("handleStopped",e),e}getElement(){return this.element}};c(fi,"PlayerEvent",he),D([Mt({settings:{retries:2,timeout:0},onError(e,t,r,s){s[0]=(s[0]||1e3)+1e3,t()}})],fi.prototype,"doReplayByRecreateMediaStream",1),D([ye([],"PLAYING",{sync:!0,success(e){this.emit(he.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}})],fi.prototype,"handlePlaying",1),D([ye("PLAYING","PAUSED",{ignoreError:!0,sync:!0,success(e){this.emit(he.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}})],fi.prototype,"handlePaused",1),D([ye([],"STOPPED",{sync:!0,success(e){this.emit(he.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}})],fi.prototype,"handleStopped",1);var er="trtc_autoplay",fu=`${er}_mask`,yn=`${er}_wrapper`,kp=`${er}_header`,_u=`${er}_content`,Id=`${er}_action_wrapper`,gu=`${er}_question`,Tu=`${er}_collapse`,Ad=`${er}_action_confirm`,Pp=`${er}_detail`,Lp="#2473E8",Iu="dialog",BT=`${Iu}-show`,HT=`${Iu}-1`,$T=`${Iu}-2`,xp=!1,Eu=!1,br=()=>Eu,Up=`${_t}/${Yt()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,wp=`<br><a href='${Up}' target='_blank'>${Yt()?"\u5176\u4ED6\u65B9\u6848\uFF1F":"Any other solution?"}</a>`,WT=`${Yt()?`\u6D4F\u89C8\u5668\u81EA\u52A8\u64AD\u653E\u7B56\u7565\uFF1A\u5728\u7528\u6237\u4E0E\u9875\u9762\u4EA7\u751F\u4EA4\u4E92\uFF08\u70B9\u51FB\u3001\u89E6\u6478\uFF09\u4E4B\u524D\uFF0C\u6D4F\u89C8\u5668\u7981\u6B62\u64AD\u653E\u6709\u58F0\u5A92\u4F53\u3002\u8BE5\u5F39\u7A97\u7528\u4E8E\u5E2E\u52A9\u7528\u6237\u6062\u590D\u97F3\u89C6\u9891\u64AD\u653E\u3002${wp}`:`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. ${wp}`}`,Su=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(Yt()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!xp){let i=document.createElement("style");i.innerHTML=`.${fu}{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;}.${fu} div:not(.${Id}){display:block !important;}.${yn}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${yn} a{color:${Lp};}.${kp}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${_u}{margin:8px 0;}.${Id}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${Tu}{margin-right:auto;cursor:pointer}.${gu}{height:100%;line-height:16px;cursor:pointer;}.${Ad}{margin-left:8px;color:#fff;background:${Lp};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${Ad}:hover{opacity:0.9;}.${Tu},.${Ad},.${_u},.${gu}{font-size:14px;}@media screen and (max-width:750px){.${yn}{width:80vw;}}`,document.head.appendChild(i),xp=!0}this.addDiaLog()}createDiaLog(){let i=document.createElement("template");i.innerHTML=`<div class="${fu}"><div class='${yn}'><div class='${kp}'>${location.host}</div><div class='${_u}'>${this.content}</div><div class='${Pp}' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">${WT}</div><div class='${Id}'></div></div></div>`.trim();let e=document.createElement("button");e.className=Ad,e.innerText=Yt()?"\u6062\u590D\u64AD\u653E":"Resume",e.onclick=this.onConfirm.bind(this);let t=document.createElement("div");t.className=gu,t.innerHTML=`<?xml version="1.0" encoding="UTF-8"?>
26
+ `],{type:"application/javascript"}))),Be.sharedWorker.onmessage=e=>{var t;if(e.data.type==="tick"){let r=Be.workerTasks.get(e.data.taskId);r&&(Be.isBreakLoop(r)?((t=Be.sharedWorker)==null||t.postMessage({type:"stop",taskId:r.taskID}),Be.workerTasks.delete(r.taskID)):(r.callback(),r.loopCount+=1))}}),Be.workerTasks.set(i.taskID,i),Be.sharedWorker.postMessage({taskId:i.taskID,delay:i.delay,type:"start"})}static timeout(i){let e=()=>{if(i.callback(),i.loopCount+=1,!Be.isBreakLoop(i))return i.timeoutID=setTimeout(e,i.delay)};return i.timeoutID=setTimeout(e,i.delay)}static ric(i){let e=V(),t,r=()=>{if(t=V()-e,t>=i.delay&&(e=V()-Math.floor(t%i.delay),i.callback(),i.loopCount+=1),!Be.isBreakLoop(i))return i.ricID=Bp(r,{timeout:i.delay})};return i.ricID=Bp(r,{timeout:i.delay})}static raf(i){let e=V(),t,r=()=>{if(document.hidden&&i.backgroundTask)return t=V()-e,e=V(),i.callback(),i.loopCount+=1,Be.isBreakLoop(i)?void 0:i.timeoutID=setTimeout(r,i.delay-Math.floor(t%i.delay));if(t=V()-e,t>=i.delay&&(e=V()-Math.floor(t%i.delay),i.callback(),i.loopCount+=1),!Be.isBreakLoop(i))return i.rafID=requestAnimationFrame(r)};if(i.rafID=requestAnimationFrame(r),i.backgroundTask){let s=()=>{if(document.hidden){let n=V()-e;n>=i.delay?r():i.timeoutID=setTimeout(r,i.delay-n)}};document.addEventListener("visibilitychange",s),i.onVisibilitychange=s,document.hidden&&s()}return i.taskID}static hasTask(i){return this.taskMap.has(i)}static clearTask(i){if(!this.taskMap.has(i))return!0;let{intervalID:e,timeoutID:t,rafID:r,ricID:s,onVisibilitychange:n}=this.taskMap.get(i);return e&&clearInterval(e),t&&clearTimeout(t),r&&Hp&&Hp(r),s&&qT(s),n&&document.removeEventListener("visibilitychange",n),this.taskMap.delete(i),!0}static isBreakLoop(i){return this.hasTask(i.taskID)?i.count!==0&&i.loopCount>=i.count?(this.clearTask(i.taskID),!0):!1:!0}};d(Be,"taskMap",new Map),d(Be,"currentTaskID",1),d(Be,"sharedWorker",null),d(Be,"workerTasks",new Map);var Su=Be,oe=Su;var JC={STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",STREAM_UPDATED:"stream-updated",STREAM_SUBSCRIBED:"stream-subscribed",CONNECTION_STATE_CHANGED:"connection-state-changed",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",MUTE_AUDIO:"mute-audio",MUTE_VIDEO:"mute-video",UNMUTE_AUDIO:"unmute-audio",UNMUTE_VIDEO:"unmute-video",CLIENT_BANNED:"client-banned",NETWORK_QUALITY:"network-quality",AUDIO_VOLUME:"audio-volume",SEI_MESSAGE:p.SEI_MESSAGE,ERROR:"error"};var K={LOAD_START:p.LOADSTART,LOADED_DATA:p.LOADEDDATA,LOADED_META_DATA:p.LOADEDMETADATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",RESIZE:p.RESIZE,TIME_UPDATE:"time-update",LEAVE_PICTURE_IN_PICTURE:p.LEAVE_PICTURE_IN_PICTURE,ENTER_PICTURE_IN_PICTURE:p.ENTER_PICTURE_IN_PICTURE,USER_RESUME_IN_PIP:"user-resume-in-pip",USER_PAUSE_IN_PIP:"user-pause-in-pip"};var Ni={};Vi(Ni,{create:()=>tt,remove:()=>xe});var vn=new WeakMap;function tt(o,i){vn.has(o)||vn.set(o,[]);let e=vn.get(o),r={add:(s,n)=>("addEventListener"in i?(e.push(i.removeEventListener.bind(i,s,n)),i.addEventListener(s,n)):(e.push(i.off.bind(i,s,n)),i.on(s,n)),r)};return r}function xe(o){let i=vn.get(o);i&&(i.forEach(e=>e()),vn.delete(o))}var Au=class{constructor(){d(this,"_roomIdMap",new Map);d(this,"_configs");typeof registerProcessor=="undefined"&&(this._configs={sdkAppId:"",userId:"",version:$e,env:Bi.QCLOUD,browserVersion:Ri.name+Ri.version,ua:navigator.userAgent})}setConfig({sdkAppId:i,env:e,userId:t,roomId:r}){i!==this._configs.sdkAppId&&(this._configs.sdkAppId=String(i)),this._configs.env=e,this._configs.userId=t,this._roomIdMap.set(t,String(r))}logSuccessEvent(i){si||!R.isAbleToUpload||this._configs.env===Bi.QCLOUD&&this.uploadEventToKibana(L(O({},i),{result:"success"}))}logFailedEvent(i){if(si||!R.isAbleToUpload)return;let{eventType:e,code:t,error:r,userId:s}=i,n={roomId:this._roomIdMap.get(s||this._configs.userId),userId:s,eventType:e,result:"failed",code:t||(r==null?void 0:r.extraCode)||(r==null?void 0:r.code)||I.UNKNOWN};this._configs.env===Bi.QCLOUD&&this.uploadEventToKibana(L(O({},n),{error:r}))}uploadEventToKibana(i){let e=`stat-${i.eventType}-${i.result}`;(i.eventType==="delta-join"||i.eventType==="delta-leave"||i.eventType==="delta-publish")&&(e=`${i.eventType}:${i.delta}`),this.uploadEvent({log:e,userId:i.userId}),i.result==="failed"&&(e=`stat-${i.eventType}-${i.result}-${i.code}`,this.uploadEvent({log:e,userId:i.userId,error:i.error}))}uploadEvent({log:i,userId:e,error:t}){let r={timestamp:ma(),sdkAppId:this._configs.sdkAppId,userId:e||this._configs.userId,version:$e,log:i};t&&(r.errorInfo=t.message,t.stack&&(r.errorInfo+=`
27
+ ${t.stack}`));let s=Ar.enable?Wi(r,2002,Number(this._configs.sdkAppId)):JSON.stringify(r);this.sendRequest(Gi(this._configs.sdkAppId,mr.LOG),s)}sendRequest(i,e){setTimeout(()=>qi({url:i,body:e,priority:"low"}).catch(()=>{}),2e3)}},ne=new Au;var Di=new WeakMap;function Mt({settings:o={retries:5,timeout:2e3},onError:i,onRetrying:e,onRetryFailed:t}){return function(r,s,n){let a=Ci({retryFunction:n.value,settings:o,onError({error:c,retry:l,reject:h,retryFuncArgs:m}){var u;i?i.call(this,c,()=>{var _;(_=Di.get(r))!=null&&_.has(s)?l():h(c)},h,m):(u=Di.get(r))!=null&&u.has(s)?l():h(c)},onRetrying(c,l){var h;Ai(e)&&e.call(this,c,l),(h=Di.get(r))!=null&&h.has(s)&&(Di.get(r).get(s).stopRetry=l)},onRetryFailed:t});return n.value=function(...c){let l=Di.get(r);return l?l.set(s,{args:c}):Di.set(r,new Map([[s,{args:c}]])),a.apply(this,c).finally(()=>{var h;return(h=Di.get(r))==null?void 0:h.delete(s)})},n}}function Nn({fnName:o,callback:i,validateArgs:e=!0}){return function(t,r,s){let n=s.value;return s.value=function(...a){var c,l;if((c=Di.get(t))!=null&&c.has(o)){let{stopRetry:h,args:m}=Di.get(t).get(o),u=!0;if(e){for(let _ of m)if(!a.find(g=>g===_)){u=!1;break}}u&&(i&&i.apply(this,a),h&&h(),(l=Di.get(t))==null||l.delete(o))}return n.apply(this,a)},s}}var pi=class extends j{constructor(e,t){super(e.id,`${t}-player`);this.options=e;this.kind=t;d(this,"id");d(this,"element",null);d(this,"track");d(this,"url");d(this,"attr");d(this,"mode");d(this,"muted");d(this,"_log");d(this,"isPausedByUserCall",!1);d(this,"_pausedRetryCount");d(this,"_isElementPlayingFired",!1);d(this,"_interval");d(this,"_delayDestroyTimeoutId",0);d(this,"_playSuccessResolve");d(this,"_isReplayByRecreateMediaStreamCalled",!1);d(this,"isPlayCalled",!1);d(this,"isInAutoPlayFailedState",!1);this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=Tr,this._state="STOPPED",this.bindTrackEvents(),this._log.info(`create ${t}-player ${this.id}`)}get isPlaying(){var e;return this._state==="PLAYING"&&((e=this.element)==null?void 0:e.paused)===!1}get isPaused(){var e;return this._state==="PAUSED"||((e=this.element)==null?void 0:e.paused)===!0}get isStopped(){return this._state==="STOPPED"}setAttr(e){this.attr=e}setUrl(e){this.track&&(this.unbindTrackEvents(),this.element&&(this.element.srcObject=null),this.track=null),e!==this.url&&(this.url=e,e!==null&&this.element&&(this.element.crossOrigin="anonymous",this.element.src=e))}play(){return f(this,null,function*(){if(!this.isPlaying)try{this.isPlayCalled=!0,this._delayDestroyTimeoutId&&(clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0,this.bindTrackEvents(),this.bindElementEvents()),this.bindAutoPlayEvent(),yield new Promise((e,t)=>{this._playSuccessResolve=e,this.element.play().then(e,t)})}catch(e){let t=$({key:B.PLAY_FAILED,data:{media:this.kind,error:e}});if(this._log.warn(e),t.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new D({code:I.PLAY_NOT_ALLOWED,message:t})}})}stop(e=0){var t;this.isPlayCalled=!1,this._isElementPlayingFired=!1,this.unbindEvents(),e>0&&!Bt?this._delayDestroyTimeoutId||((t=this.element)==null||t.remove(),this._log.info(`destroy element after 3 * ${e}`),this._delayDestroyTimeoutId=setTimeout(()=>this.destroyElement(),3*e)):this.destroyElement(),this.handleStopped(p.ENDED),this._interval>0&&oe.clearTask(this._interval)}destroyElement(){this.element&&(this._log.debug("destroy element"),this.element.remove(),this.element.src="",this.element.srcObject=null,this.element=null),clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0}pause(){this._log.info("pause"),this.isPausedByUserCall=!0,this.doPause()}doPause(){var e;(e=this.element)==null||e.pause()}resume(e=!1){return this.isPausedByUserCall=!1,this.doResume(e)}doResume(e=!1){return this._log.info("resume"),this.isPausedByUserCall||this.isPlaying?Promise.resolve():xl?this.replay():this.play().catch(()=>{})}setMuted(e){this.element&&(this.element.muted=e),this.muted=e}replay(){return this.stop(),this.play().catch(()=>{})}bindElementEvents(){if(this.element){let e=this.handleElementEvent.bind(this);return tt(this.element,this.element).add(p.PLAYING,e).add(p.ENDED,e).add(p.PAUSE,e).add(p.ERROR,e).add(p.LOADSTART,e).add(p.LOADEDDATA,e).add(p.LOADEDMETADATA,e)}}bindTrackEvents(e=this.track){if(e){let t=this.handleTrackEvent.bind(this);Ni==null||Ni.create(e,e).add(p.ENDED,t).add(p.MUTE,t).add(p.UNMUTE,t),e.readyState===p.ENDED&&this.handleTrackEvent({type:p.ENDED}),e.muted&&this.handleTrackEvent({type:p.MUTE})}}bindAutoPlayEvent(){S.on(C.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(e=this.track){e&&xe(e)}unbindEvents(){this.element&&xe(this.element),this.unbindTrackEvents(),S.off(C.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case p.PLAYING:vr()||(this.isInAutoPlayFailedState=!1),this._isElementPlayingFired=!0,this._log.info(`${this.kind} player is playing`),this.handlePlaying(p.PLAYING),this._interval&&(oe.clearTask(this._interval),this._interval=-1);break;case p.ENDED:this._log.info(`${this.kind} player is ended`),this.handleStopped(p.ENDED);break;case p.PAUSE:this._log.info(`${this.kind} player is paused`),this.handlePaused(p.PAUSE);break;case p.ERROR:if(this.element&&this.element.error){this.handlePaused(p.ERROR);let{code:r,message:s}=this.element.error;this._log.error(`${this.kind} ${this._log.isLocal?"local":"remote"} MediaError code: ${r} message: ${s} userAgent: ${navigator.userAgent}`),ne.uploadEvent({log:`stat-${this.kind}-${Ke.PLAYER_ERROR}-${r}-${navigator.userAgent}`,error:this.element.error}),kl||sn?this.emit(K.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case p.LOADEDDATA:this.kind===p.VIDEO&&this.emit(K.LOADED_DATA);break;case p.LOADEDMETADATA:this.kind===p.VIDEO&&this.emit(K.LOADED_META_DATA);break;case p.LOADSTART:this.emit(K.LOAD_START);break}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then(()=>{this._log.warn("replayByRecreateMediaStream success"),ne.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),v.addSuccessEvent({key:this.kind===p.AUDIO?506700:516700})}).catch(()=>{var t;this._log.error("replayByRecreateMediaStream failed"),ne.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),v.addFailedEvent({key:this.kind===p.AUDIO?506700:516700,error:(t=this.element)==null?void 0:t.error}),this.emit(K.ERROR,e)})}doReplayByRecreateMediaStream(e){return this._log.warn(`delay ${e}ms to recreate mediaStream`),new Promise((t,r)=>{Ge(e).then(()=>{this.element&&(this.element.srcObject=null,this.element.srcObject=new MediaStream([this.track]),this._log.warn("recreated mediaStream"),this.element.onerror=()=>{var s,n,a;this._log.warn(`element onerror ${(n=(s=this.element)==null?void 0:s.error)==null?void 0:n.code} fired after recreated mediaStream`),r((a=this.element)==null?void 0:a.error)}),Ge(5e3).then(()=>{var s,n;(!this.isPlaying||(s=this.element)!=null&&s.error)&&r((n=this.element)==null?void 0:n.error),t()})})}).finally(()=>{this.element&&(this.element.onerror=null)})}handleTrackEvent(e){return f(this,null,function*(){let t=e.type;switch(this.options.enableLogTrackState&&this._log[t===p.UNMUTE?"info":"warn"](`track ${t}`),t){case p.ENDED:this.handleStopped(p.ENDED);break;case p.MUTE:this.handlePaused(p.MUTE);break;case p.UNMUTE:this.mode>0?this.handlePlaying(this.mode.toString()):this.element&&(this.element.paused&&!this.isPausedByUserCall&&(this._log.warn("track unmuted and element is paused, resume"),yield this.doResume()),this.element&&!this.element.paused&&this._isElementPlayingFired&&this.handlePlaying(p.UNMUTE));break}})}handlePlaying(e){var t;return this._log.debug("handlePlaying",e),(t=this._playSuccessResolve)==null||t.call(this,e),e}handlePaused(e){return this._log.debug("handlePaused",e),e}handleStopped(e){return this._log.debug("handleStopped",e),e}getElement(){return this.element}};d(pi,"PlayerEvent",K),M([Mt({settings:{retries:2,timeout:0},onError(e,t,r,s){s[0]=(s[0]||1e3)+1e3,t()}})],pi.prototype,"doReplayByRecreateMediaStream",1),M([be([],"PLAYING",{sync:!0,success(e){this.emit(K.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}})],pi.prototype,"handlePlaying",1),M([be("PLAYING","PAUSED",{ignoreError:!0,sync:!0,success(e){this.emit(K.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}})],pi.prototype,"handlePaused",1),M([be([],"STOPPED",{sync:!0,success(e){this.emit(K.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}})],pi.prototype,"handleStopped",1);var er="trtc_autoplay",Cu=`${er}_mask`,Dn=`${er}_wrapper`,$p=`${er}_header`,Ru=`${er}_content`,vc=`${er}_action_wrapper`,yu=`${er}_question`,bu=`${er}_collapse`,Nc=`${er}_action_confirm`,Gp=`${er}_detail`,Wp="#2473E8",Du="dialog",jT=`${Du}-show`,XT=`${Du}-1`,zT=`${Du}-2`,qp=!1,vu=!1,vr=()=>vu,jp=`${ft}/${Zt()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,Jp=`<br><a href='${jp}' target='_blank'>${Zt()?"\u5176\u4ED6\u65B9\u6848\uFF1F":"Any other solution?"}</a>`,QT=`${Zt()?`\u6D4F\u89C8\u5668\u81EA\u52A8\u64AD\u653E\u7B56\u7565\uFF1A\u5728\u7528\u6237\u4E0E\u9875\u9762\u4EA7\u751F\u4EA4\u4E92\uFF08\u70B9\u51FB\u3001\u89E6\u6478\uFF09\u4E4B\u524D\uFF0C\u6D4F\u89C8\u5668\u7981\u6B62\u64AD\u653E\u6709\u58F0\u5A92\u4F53\u3002\u8BE5\u5F39\u7A97\u7528\u4E8E\u5E2E\u52A9\u7528\u6237\u6062\u590D\u97F3\u89C6\u9891\u64AD\u653E\u3002${Jp}`:`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. ${Jp}`}`,Nu=class{constructor(){d(this,"content","\u97F3\u89C6\u9891\u64AD\u653E\u88AB\u6D4F\u89C8\u5668\u62E6\u622A\uFF0C\u8BF7\u70B9\u51FB\u201C\u6062\u590D\u64AD\u653E\u201D\u3002");d(this,"_dialogNode",null);d(this,"_bodyPosition","");d(this,"_showDetail",!1);d(this,"_isCollapseClicked",!1);d(this,"_isQuestionClicked",!1);if(Zt()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!qp){let i=document.createElement("style");i.innerHTML=`.${Cu}{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;}.${Cu} div:not(.${vc}){display:block !important;}.${Dn}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${Dn} a{color:${Wp};}.${$p}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${Ru}{margin:8px 0;}.${vc}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${bu}{margin-right:auto;cursor:pointer}.${yu}{height:100%;line-height:16px;cursor:pointer;}.${Nc}{margin-left:8px;color:#fff;background:${Wp};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${Nc}:hover{opacity:0.9;}.${bu},.${Nc},.${Ru},.${yu}{font-size:14px;}@media screen and (max-width:750px){.${Dn}{width:80vw;}}`,document.head.appendChild(i),qp=!0}this.addDiaLog()}createDiaLog(){let i=document.createElement("template");i.innerHTML=`<div class="${Cu}"><div class='${Dn}'><div class='${$p}'>${location.host}</div><div class='${Ru}'>${this.content}</div><div class='${Gp}' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">${QT}</div><div class='${vc}'></div></div></div>`.trim();let e=document.createElement("button");e.className=Nc,e.innerText=Zt()?"\u6062\u590D\u64AD\u653E":"Resume",e.onclick=this.onConfirm.bind(this);let t=document.createElement("div");t.className=yu,t.innerHTML=`<?xml version="1.0" encoding="UTF-8"?>
28
28
  <svg class="icon" width="18" height="18" p-id="2030" t="1639646523624" version="1.1" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
29
29
  <path d="m464 784.35c0 26.51 21.49 48 48 48s48-21.49 48-48-21.49-48-48-48-48 21.49-48 48z" p-id="2031"/>
30
30
  <path d="m512 960c-247.04 0-448-200.96-448-448s200.96-448 448-448 448 200.96 448 448-200.96 448-448 448zm0-831.71c-211.58 0-383.71 172.13-383.71 383.71 0 211.55 172.13 383.71 383.71 383.71 211.55 0 383.71-172.16 383.71-383.71 0-211.58-172.16-383.71-383.71-383.71z" p-id="2032"/>
31
31
  <path d="m512 673.7c-17.665 0-32.001-14.336-32.001-31.999v-54.112c0-52.353 40-92.352 75.328-127.65 25.887-25.92 52.672-52.672 52.672-74.017 0-53.343-43.072-96.735-95.999-96.735-53.823 0-95.999 41.536-95.999 94.559 0 17.665-14.336 31.999-32.001 31.999s-32.001-14.336-32.001-31.999c0-87.424 71.775-158.56 160-158.56s160 72.095 160 160.74c0 47.904-36.32 84.192-71.424 119.3-27.84 27.776-56.576 56.512-56.576 82.336v54.112c0 17.665-14.336 32.032-32.001 32.032z" p-id="2033"/>
32
32
  </svg>
33
- `,t.onclick=this.onQuestionClick.bind(this);let r=document.createElement("div");r.className=Tu,r.innerText=`${Yt()?"\u8BE6\u60C5 >":"Detail >"}`,r.onclick=this.onCollapseClick.bind(this);let s=i.content.firstChild,n=s.querySelector(`.${Id}`);return n.appendChild(r),n.appendChild(t),n.appendChild(e),s}addDiaLog(){br()||(Eu=!0,this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${yn}`).onclick=i=>i.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",R.info("show autoplay dialog"),se.uploadEvent({log:BT}))}deleteDialog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null,Eu=!1),bn=null}onConfirm(){R.warn("confirm clicked, try resume stream"),S.emit(A.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDialog()}onCollapseClick(){let i=this._dialogNode.querySelector(`.${Pp}`);i.style.visibility=`${this._showDetail?"hidden":"visible"}`,i.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||se.uploadEvent({log:HT}),this._isCollapseClicked=!0}onQuestionClick(){window.open(Up,"_blank"),this._isQuestionClicked||se.uploadEvent({log:$T}),this._isQuestionClicked=!0}},bn=null;function ns(){bn||(bn=new Su)}function Vp(){bn&&bn.deleteDialog()}var pt=class o extends fi{constructor(e){super(e,_.VIDEO);c(this,"stat",{});c(this,"_calculateTimeout",-1);c(this,"viewMirror",!1);c(this,"objectFit");c(this,"container");c(this,"canvas");c(this,"shouldRenderAlpha",!1);c(this,"_preSize",{width:0,height:0});c(this,"posterImg");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(_.VIDEO);this.track&&this.mode!==2&&(e.srcObject=new MediaStream([this.track])),e.muted=!0,e.setAttribute("id",`video_${this.id}`),e.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),e.setAttribute("autoplay","autoplay"),e.setAttribute("playsinline","playsinline"),this.element=e,_e&&(e.poster="noposter"),(t=this.container)==null||t.appendChild(this.elementToRender),this.bindElementEvents(),this.calculateStat()}get styleAttribute(){let e=`width: 100%; height: 100%; object-fit: ${this.objectFit};${this.shouldRenderAlpha?"":"background-color: black"};`;return this.viewMirror&&(e+="transform: scaleX(-1);"),e}setContainer(e){var t;this.container=e,this.track&&this.elementToRender&&((t=this.container)==null||t.appendChild(this.elementToRender))}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),e&&e.add(_.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(_.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent).add(_.RESIZE,this.handleElementEvent)}handleTrackEvent(e){var t;return e.type===_.MUTE&&((t=this.stat)!=null&&t.fps)&&(this.stat.fps=0),super.handleTrackEvent(e)}handleElementEvent(e){var r,s,n,a,d,l;if(this.mode===2)return;super.handleElementEvent(e);let t=e.type;if(t===_.PAUSE&&(this.container&&!this.container.isConnected&&(this._log.warn(`${this.kind} player has been remove, element ID: ${this.container.id}`),Ke(500).then(()=>{var u;(u=this.container)!=null&&u.isConnected&&(this._pausedRetryCount=$r,this._log.info(`view container ${this.container.id} is in dom, reset pausedRetryCount`))})),this._pausedRetryCount>0&&!br()&&!this._isPausedByUserCall&&(this._log.info(`[${$r-this._pausedRetryCount+1}/${$r}] ${this.kind} player auto resume when paused`),this.doResume(),this._pausedRetryCount--),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){let u=this.element.style.transform;t===_.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=u.replace("scaleX(-1)",""):t===_.LEAVE_PICTURE_IN_PICTURE&&!u.includes("scaleX")&&(this.element.style.transform=`${u} scaleX(-1)`)}t===_.RESIZE&&(this._preSize.height!==((r=this.element)==null?void 0:r.videoHeight)||this._preSize.width!==((s=this.element)==null?void 0:s.videoWidth))&&(this._log.info(`video size changed to ${(n=this.element)==null?void 0:n.videoWidth}x${(a=this.element)==null?void 0:a.videoHeight}`),this._preSize.height=((d=this.element)==null?void 0:d.videoHeight)||0,this._preSize.width=((l=this.element)==null?void 0:l.videoWidth)||0,this.emit(he.RESIZE,{newWidth:this._preSize.width,newHeight:this._preSize.height}))}setCanvas(e,t=1){var r,s,n,a;this.canvas!==e&&((r=this.canvas)==null||r.remove(),e==null||e.setAttribute("style",this.styleAttribute),this.canvas=e,this.mode=e?t:0,this.mode===2&&this.setTrack(e.captureStream().getVideoTracks()[0]),e?((s=this.element)==null||s.remove(),(n=this.container)==null||n.appendChild(e)):this.element&&((a=this.container)==null||a.appendChild(this.element)))}setAttr(e){let t=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},e);t.style=Object.assign({width:"100%",height:"100%"},t.style),super.setAttr(t)}get mirror(){return this.viewMirror}setRect(e,t){this.elementToRender&&(this.elementToRender.style.width=`${e}px`,this.elementToRender.style.height=`${t}px`)}setViewMirror(e){this.elementToRender&&(this.elementToRender.style.transform=e?"scaleX(-1)":""),this.viewMirror=e}setObjectFit(e){this.elementToRender&&(this.elementToRender.style.objectFit=`${e}`),this.objectFit=e}setPoster(e,t=!1){return new Promise(r=>{if(this.element)if(this._log.info("setPoster",e.slice(0,10)),this.element.poster=e,t&&(Re||ee)){if(e==="")this.removePosterImg();else if(!this.posterImg){let s=document.createElement("img");s.src=e,s.style=`position:absolute;top:0;left:0;${this.styleAttribute}`,s.onload=()=>f(this,null,function*(){var n;s.decode&&(yield s.decode()),this.posterImg=s,(n=this.container)==null||n.appendChild(s),r()})}}else r()})}removePosterImg(){this.posterImg&&(this.posterImg.remove(),URL.revokeObjectURL(this.posterImg.src),delete this.posterImg)}pause(){return f(this,null,function*(){return(Ve&&$e>=128||ee||Re)&&(yield this.setPoster(this.getVideoFrame(),!0)),Le(o.prototype,this,"pause").call(this)})}resume(){return this.posterImg&&this.setPoster("",!0),super.resume()}stop(e=0){var t;super.stop(e),(t=this.canvas)==null||t.remove(),this.removePosterImg()}play(){return this.element?this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender):this.initializeElement(),this.mode===2?Promise.resolve():super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(he.MEDIA_TRACK_CHANGED,e),e!==null&&(this.bindTrackEvents(),this.element&&this.mode!==2&&(this.element.srcObject=new MediaStream([e]),this.element.remove()),this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender)))}getVideoFrame(){if(this.canvas)return this.canvas.toDataURL("image/png");if(!this.element)return"";let e=document.createElement("canvas");return e.width=this.element.videoWidth,e.height=this.element.videoHeight,e.getContext("2d").drawImage(this.element,0,0),e.toDataURL("image/png")}getElement(){return this.element}calculateStat(){try{if(Ki()&&this.element&&this._calculateTimeout<0){let e=0,t=null,r=(s,n)=>{this.stat.width=n.width,this.stat.height=n.height,t&&(this.stat.fps=Math.round((n.presentedFrames-t.presentedFrames)/(s-e)*1e3)),e=s,t=n,this._calculateTimeout=-1,this.element&&(this._calculateTimeout=setTimeout(()=>{var a;return(a=this.element)==null?void 0:a.requestVideoFrameCallback(r)},2e3))};this.element.requestVideoFrameCallback(r)}}catch(e){this._log.warn("init stat failed",e)}}};function tr(o,i){return f(this,null,function*(){if(!o.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield o.audioWorklet.addModule(i),R.info("worklet addModule success")}catch(e){throw R.info(`worklet addModule catch error. ${e.message}`),e}})}var Nn;typeof AudioContext!="undefined"?Nn=AudioContext:typeof webkitAudioContext!="undefined"?Nn=webkitAudioContext:typeof mozAudioContext!="undefined"&&(Nn=mozAudioContext);var yu=1500,it,Fp=-1,Cd=0,vn=-1,Ru=!1,Bp=0,Hp=-1,$p=-1;Wp();function Wp(){try{if(it)return;it=new Nn({sampleRate:48e3}),it.onstatechange=()=>{R.info(`context state: ${it.state}${it.state!=="running"?` visibilityState: ${document.visibilityState}`:""}`),as()},clearTimeout(Fp)}catch(o){R.error(`initAudioContext failed: ${o} typeof AudioContextClass: ${typeof Nn}`),Fp=setTimeout(Wp,1e3)}}var as=()=>{it.state==="suspended"?(Cd=V(),GT(),Nr(),document.addEventListener("click",as)):it.state==="interrupted"?Nr():(Cd&&(y.addNumber({key:507800,value:V()-Cd,split:[0,500,1e3,1500,2e3,3e3,4e3,5e3,1e4,3e4],max:6e4}),Cd=0),JT(),document.removeEventListener("visibilitychange",as),document.removeEventListener("click",as))},Au=0,Cu=-1;function Nr(){return new Promise((o,i)=>{if(it.state==="running")return o();Date.now()-Au<1e3?(clearTimeout(Cu),Cu=setTimeout(()=>{Au=Date.now(),it.resume().then(o,i)},1e3)):(clearTimeout(Cu),Au=Date.now(),it.resume().then(o,i))}).catch(o=>{R.warn(`context resume failed: ${o}`),document.addEventListener("visibilitychange",as)})}document.addEventListener("click",as);function GT(){vn===-1&&(vn=setTimeout(()=>{it.state==="suspended"&&(Ru=!0,S.emit("155",{isSuspended:!0}))},yu))}function JT(){vn!==-1&&(clearTimeout(vn),vn=-1,Ru&&(Ru=!1,S.emit("155",{isSuspended:!1})))}function Gp(){if(!ge||$p!==-1)return;let o=()=>{V()-Bp<500||(it&&it.state==="running"&&it.currentTime===Hp&&(R.warn("context is fake running, auto resume"),it.suspend().catch(i=>{R.warn(`context suspend failed: ${i}`)})),Hp=it.currentTime,Bp=V())};$p=setInterval(()=>{o()},2e3),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&o()})}var Ee=o=>it;var Ue=class{constructor(i){this.name=i;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)}get channelCount(){return this._channelCount}set channelCount(i){this._channelCount=i,this.setChannelCount(this.node,i),this.setChannelCount(this.node2,i),this.next.forEach(e=>e.channelCount=i)}setChannelCount(i,e){!i||i instanceof ScriptProcessorNode||(i.channelCountMode="explicit",i.channelCount=e||this.channelCount||1)}setContext(i){this.context=i,this.node&&i.addMixWeight()}removeContext(){var i;this.node&&((i=this.context)==null||i.reduceMixWeight()),delete this.context}replaceNode(i){var e;if(i!==this.node)try{this.node?this._disconnect():(e=this.context)==null||e.addMixWeight(),this.node=i,this.setChannelCount(this.node),this.preNodeReconnect(),this.reconnect()}catch(t){R.error(t)}}setNode(i,e){var t;if(!this.node)try{(t=this.context)==null||t.addMixWeight(),this.node=i,this.setChannelCount(this.node),e&&(this.node2=e,this.setChannelCount(this.node2)),this.preNodeReconnect(),this.reconnect(),y.addSuccessEvent({key:502701})}catch(r){R.error(r),y.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(),y.addSuccessEvent({key:502702})}catch(e){R.error(e),y.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}},Rd=class extends Ue{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,s=0,n=`M${r},${s}`;for(let a=0;a<e.length;a++)s=e[a]/128*100/2,n+=`L${r},${s}`,r+=t;return n}},Dn=class{constructor(){c(this,"source",new Ue);c(this,"gain",new Ue);c(this,"destination",new Ue)}get volume(){var i;return((i=this.gain.node)==null?void 0:i.gain.value)||1}setVolume(i){if(i===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(Ee().createGain()),this.gain.node.gain.value=i}replaceSource(i){let e=Mn(i);e&&this.source.replaceNode(e)}get track(){var i;return(i=this.stream)==null?void 0:i.getAudioTracks()[0]}get stream(){var i;return(i=this.destination.node)==null?void 0:i.stream}},ds=class extends Dn{constructor(e){super();this.context=e;c(this,"aec",new Ue("aec"));c(this,"mixNode",new Ue("mixNode"));c(this,"silentNode",new Ue("silentNode"));c(this,"denoiser",new Ue("denoiser"));c(this,"voiceChanger",new Ue("voiceChanger"));this.source.pipeTo(this.aec).pipeTo(this.denoiser).pipeTo(this.voiceChanger).pipeTo(this.gain).pipeTo(this.destination),this.silentNode.pipeTo(this.mixNode).pipeTo(this.aec,1)}get isProcessEnabled(){return this.aec.node||this.denoiser.node||this.voiceChanger.node||this.gain.node}connect(){this.context.inputs.has(this)||(this.destination.setNode(this.context.destination),this.source.setContext(this.context),this.aec.setContext(this.context),this.silentNode.setContext(this.context),this.mixNode.setContext(this.context),this.denoiser.setContext(this.context),this.voiceChanger.setContext(this.context),this.gain.setContext(this.context),this.context.inputs.add(this))}disconnect(){this.context.inputs.has(this)&&(this.destination.deleteNode(),this.source.removeContext(),this.aec.removeContext(),this.silentNode.removeContext(),this.mixNode.removeContext(),this.denoiser.removeContext(),this.voiceChanger.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.aec.deleteNode(),this.silentNode.deleteNode(),this.mixNode.deleteNode(),this.denoiser.deleteNode(),this.voiceChanger.deleteNode(),this.source.deleteNode(),this.disconnect()}setVolume(e){if(e===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(this.context.audioContext.createGain()),this.gain.node.gain.value=e}},yd=class{constructor(){c(this,"audioContext",Ee("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]}},Jp=new WeakMap;function Mn(o){try{let i=Jp.get(o);if(i)return i;let e=Ee();if(o instanceof HTMLAudioElement)i=e.createMediaElementSource(o);else if(o instanceof MediaStreamTrack)i=e.createMediaStreamSource(new MediaStream([o]));else return o;return Jp.set(o,i),i}catch(i){if(ee&&i instanceof Error&&i.name==="NotSupportedError")R.warn(i);else throw i}}var Ot=class Ot{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,S.on(A.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-Ot.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!Ot.workletReady){let i='class VolumeMeterWorklet extends AudioWorkletProcessor{constructor(){super(),this.volume=0,this.intervalTime=200,this.tick=200,this.isStop=!1,this.cache=[],this.sentFirstInfo1=!1,this.unmute=!1,this.port.onmessage=t=>{var e=t.data;switch(e.name){case"chunk":this.cache.push(...e.data),this.sentFirstInfo1||(this.port.postMessage({cl:e.data.length}),this.sentFirstInfo1=!0);break;case"setIntervalTime":this.intervalTime=e.intervalTime;break;case"unmute":this.unmute=!0;break;case"stop":this.isStop=!0}}}process(t,s){t=t[0],s=s[0];if(t||s){if(this.isStop)return!1;var i=s&&s[0]?s[0].length:0,h=this.cache.length,a=(i<h?(s[0].set(this.cache.slice(0,i)),this.cache=this.cache.slice(i)):this.unmute&&s[0].set(t[0]),(i<h?s:t)[0]);if(a){let e=0;for(let t=0;t<a.length;++t)e=Math.max(Math.abs(a[t]),e);s=a.reduce((t,e)=>t+e*e,0)/a.length;this.volume=e,this.tick-=a.length,this.tick<0&&(this.tick+=this.intervalTime/1e3*sampleRate,this.port.postMessage({volume:this.volume,volumeDb:Math.max(10*Math.log10(s)+100,0)/100,cacheLen:h,outputLen:i}))}}return!0}}registerProcessor("volume-meter",VolumeMeterWorklet);';Ot.workletReady=tr(Ot.audioContext,URL.createObjectURL(new Blob([i],{type:"application/javascript"})))}return Ot.workletReady.then(()=>this.initAudioWorklet()).catch(i=>(this._log.error(`volumeMeter preload error: ${i}`),this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(Ot.audioContext,"volume-meter");let i=!1;this._audioWorkletNode.port.onmessage=e=>{Ot.lastMessageTime=Date.now(),this._volume=e.data.volume||0,this._volumeDb=e.data.volumeDb||0,!i&&e.data.cacheLen&&e.data.outputLen&&(this._log.warn("worklet play success"),i=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(i){this._log.error(`volumeMeter init audio worklet error: ${i}`),se.logFailedEvent({userId:this._log.userId,eventType:Ze.LOAD_WORKLET,error:i}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=Ee("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=i=>{Ot.lastMessageTime=Date.now();let e=i.inputBuffer.getChannelData(0),t=0;for(let r=0;r<e.length;++r)t+=e[r]*e[r];this._volume=Math.sqrt(t/e.length)||0}}catch(i){this._log.error(`volumeMeter init script processor error: ${i}`)}}destroy(){this._scriptProcessorNode&&(this._scriptProcessorNode.onaudioprocess=null),this._audioWorkletNode&&(this._audioWorkletNode.port.postMessage({name:"stop"}),this._audioWorkletNode.port.onmessage=null),this._audioWorkletNode=null,this._scriptProcessorNode=null,S.off(A.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}getVolumeDb(){return Math.floor(this._volumeDb*100)}handleAudioLevelInterval(i){var t;let{interval:e}=i;this._interval=e,(t=this._audioWorkletNode)==null||t.port.postMessage({name:"setIntervalTime",intervalTime:e})}};c(Ot,"lastMessageTime",0),c(Ot,"audioContext",Ee("volume-meter")),c(Ot,"workletReady");var bd=Ot,On=class extends Ue{constructor(e){super();c(this,"_volumeMeter");this._volumeMeter=new bd(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return f(this,null,function*(){yield this._volumeMeter.preload(),this.setNode(this._volumeMeter.node)})}getCalculatedVolume(){return this._volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this._volumeMeter.getInternalAudioLevel()}getVolumeDb(){return this._volumeMeter.getVolumeDb()}write(e){if(this.node){let t=e.allocationSize({planeIndex:0}),r=new Float32Array(t>>2);e.copyTo(r,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:r},[r.buffer]),e.close()}}},so=bd;var zp=Je(nt(),1);var jp=o=>i=>i.deviceId===o;var kn=class{constructor(i,e){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&&ls(this.devices[0])){this.devices=t;return}e&&(t.forEach(r=>{if(r.deviceId&&!this.devices.find(jp(r.deviceId))){let s=`${this.kind}${this.type}Added`;R.warn(`${s}: ${JSON.stringify(r)}`),e.emit(s,r)}}),this.devices.forEach(r=>{if(r.deviceId&&!t.find(jp(r.deviceId))){let s=`${this.kind}${this.type}Removed`;R.warn(`${s}: ${JSON.stringify(r)}`),e.emit(s,r)}})),this.devices=t}hasDevice(i){return!!this.devices.find(e=>e.deviceId===i)}},bu=class extends zp.EventEmitter{constructor(){super();c(this,"audioInputs",new kn(_.AUDIO,"Input"));c(this,"videoInputs",new kn(_.VIDEO,"Input"));c(this,"audioOutputs",new kn(_.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(){cs().then(e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)})}update(){return f(this,arguments,function*(e=0){let t=yield cs(e);return this.audioInputs.update(t,this),this.videoInputs.update(t,this),this.audioOutputs.update(t,this),this})}hasBlueTooth(){var t;if(((t=Ee())==null?void 0:t.outputLatency)*1e3>150)return!0;let e=["bluetooth","air","wireless","bt","tws","buds","headset","headphone"];return this.audioOutputs.devices.some(r=>e.some(s=>r.label.toLowerCase().includes(s)))||this.audioInputs.devices.some(r=>e.some(s=>r.label.toLowerCase().includes(s)))}},be=xs||Do?null:new bu;function ls(o){return o.deviceId===o.groupId&&o.groupId===""}function cs(){return f(this,arguments,function*(o=0){if(Zi()||!md())return[];let i=yield navigator.mediaDevices.enumerateDevices();if(o!==0){let e={audio:!1,video:!1};if(i.forEach(t=>{ls(t)&&(t.kind===_.AUDIO_INPUT?e.audio=!0:t.kind===_.VIDEO_INPUT&&(e.video=!0))}),o===2&&(e.audio=!1),o===1&&(e.video=!1),e.audio||e.video){let t;try{t=yield navigator.mediaDevices.getUserMedia(e),e.audio&&Nr()}catch(r){R.debug("capture before getDevices failed: ",r)}i=yield navigator.mediaDevices.enumerateDevices(),t==null||t.getTracks().forEach(r=>r.stop())}}return i.map((e,t)=>{let r={kind:e.kind,deviceId:e.deviceId,groupId:e.groupId,label:e.label||`${e.kind}_${t}`};return e.deviceId.length>0&&Nu.add(`${e.deviceId}_${e.kind}`),e.getCapabilities&&(r.getCapabilities=()=>e.getCapabilities()),r})})}function It(o=!1){return be.update(o?1:0).then(i=>i.audioInputs.devices)}function At(o=!1){return be.update(o?2:0).then(i=>i.videoInputs.devices)}var Xp=!1;function Qp(){return f(this,null,function*(){try{Xp||(Xp=!0,R.info(`speakers:${(yield vr()).map(o=>` ${o.deviceId.slice(0,8)}: ${o.label}`)}`))}catch(o){}})}function vr(o=!1){return f(this,null,function*(){return(ge||Re)&&(o=!1),be.update(o?1:0).then(i=>i.audioOutputs.devices)})}var Nu=new Set;function Yp(o){if(o instanceof CanvasCaptureMediaStreamTrack||!(o instanceof MediaStreamTrack))return!1;let i=o.label.toLocaleLowerCase();if(i.includes("camera")||i.includes("webcam"))return!0;let t=`${((o==null?void 0:o.getSettings())||{}).deviceId}_${_.VIDEO_INPUT}`;return!!Nu.has(t)}function Zp(o){if(o instanceof CanvasCaptureMediaStreamTrack||!(o instanceof MediaStreamTrack))return!1;let i=o.label.toLocaleLowerCase();if(i.includes("mic")||i.includes("\u9EA6\u514B\u98CE"))return!0;let t=`${((o==null?void 0:o.getSettings())||{}).deviceId}_${_.AUDIO_INPUT}`;return!!Nu.has(t)}function vu(o,i){return f(this,null,function*(){let t=(yield It()).find(r=>r.deviceId===Wr);return!i&&(t==null?void 0:t.groupId)===o||(t==null?void 0:t.groupId)===o&&t.label===i})}function Kp(s){return f(this,arguments,function*({newDeviceId:o,oldDeviceId:i,oldGroupId:e,oldLabel:t,kind:r}){return o!==i?!1:r===_.AUDIO&&o===Wr?yield vu(e,t):!0})}var Nd,Du=class extends Dn{constructor(e){super();this.log=e;c(this,"volumeMeter");c(this,"volumeMeterAfter3A");c(this,"volumeDestination");c(this,"analyser",new Rd);this.volumeMeter=new On({log:this.log}),this.volumeMeterAfter3A=new On({log:this.log}),this.volumeDestination=new Ue,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},us=class o extends fi{constructor(e){super(e,_.AUDIO);c(this,"_outputDeviceId");c(this,"_volume",1);c(this,"_destination",Ee("player").createMediaStreamDestination());c(this,"pipeline");c(this,"volumeMeterMode","worklet");c(this,"enableVolumeControlInIOS");this.enableVolumeControlInIOS=e.enableVolumeControlInIOS,this.mode=0,e.url&&(this.url=e.url),this.pipeline=new Du(this._log)}setTrack(e){}get duration(){var e;return Math.floor((((e=this.element)==null?void 0:e.duration)||0)*1e3)}get currentTime(){var e;return Math.floor((((e=this.element)==null?void 0:e.currentTime)||0)*1e3)}set currentTime(e){this.element&&(this.element.currentTime=e/1e3)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(e){if((ht==="15.2"||ht==="15.3"||ht==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}(ri||oi)&&ht>="18.7"&&this.bindAutoPlayEvent();let r=Nd||new Audio;r.setAttribute("autoplay","autoplay"),r.srcObject=this.getMediaStream(),r.muted=this.muted,this.url&&(r.crossOrigin="anonymous",r.src=this.url),this.element=r,Q(e)&&(this.element.volume=Math.min(Math.max(e,0),1)),r===Nd&&(Nd=void 0),this.options.enableTimeupdateEvent&&(this.element.ontimeupdate=()=>this.emit(he.TIME_UPDATE,this.currentTime)),this.bindElementEvents(),this._log.info("initializeElement success")}play(e){return f(this,null,function*(){if(!(!this.track&&!this.url))return!this.pipeline.source.node&&this.track&&this.pipeline.replaceSource(this.track),this.element||this.initializeElement(e==null?void 0:e.volume),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),this.volumeMeterMode==="worklet"?(this.pipeline.volumeMeter.init(),this.pipeline.volumeMeterAfter3A.init(),this._log.info("volumeMeter init success")):this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(Ee("player").createAnalyser()),Qp(),Le(o.prototype,this,"play").call(this)})}stop(e=0){this.pipeline.destroy(),super.stop(e)}setVolume(e){this._volume=e,this.element&&(this.element.volume=e)}setSinkId(e){return f(this,null,function*(){var t,r;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield(r=(t=this.element).setSinkId)==null?void 0:r.call(t,e))})}get useDestination(){return!!this.pipeline.stream}setLoop(e){this.element&&(this.element.loop=e)}getAudioLevel(){return this.pipeline.volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this.pipeline.volumeMeter.getInternalAudioLevel()}getInternalAudioLevelAfter3A(){return this.pipeline.volumeMeterAfter3A.getInternalAudioLevel()}},vd=class extends us{setTrack(i){this.track!==i&&(this.unbindTrackEvents(),this.track=i,this.emit(he.MEDIA_TRACK_CHANGED,i),i&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([i]))))}},Dd=class extends us{constructor(e){super(e);c(this,"_sourceElement");c(this,"_output",new Ue);this.pipeline.source.pipeTo(this.pipeline.gain),this.pipeline.gain.pipeTo(this.pipeline.volumeMeter).pipeTo(this._output),this.pipeline.gain.pipeTo(this.pipeline.destination)}setOutput(){this.mode=1,this._output.setNode(Ee("player").destination)}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var t,r,s;((r=(t=this.element)==null?void 0:t.error)==null?void 0:r.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(he.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([e]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e])),this.pipeline.source.channelCount=((s=e.getSettings())==null?void 0:s.channelCount)||1,this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){if(this._volume=e,this.useDestination)this.pipeline.setVolume(e),this._log.info(`set pipeline volume: ${e}`);else if(e<=1&&!ge)this.element?(this._log.info(`set element volume: ${e}`),this.element.volume=e):this._log.info("set element volume: no element");else{if(ge)if(this.enableVolumeControlInIOS)Gp();else return;if(ee&&!this.pipeline.source.node){this._log.warn("set pipeline volume failed: no source node");return}this._log.info(`start set pipeline volume: ${e}`),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),we(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play())}}stop(e=0){this.pipeline.destroy();let t=this._sourceElement||this.element;t&&Ft&&(Nd=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}};var no=class extends j{constructor({userId:e,sdkAppId:t,mediaType:r,room:s,PlayerClass:n=r===1?Dd:pt}){var a;super();c(this,"id",an());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,"rotation");c(this,"isScreen",!1);c(this,"manager");c(this,"trackSettings");c(this,"isFirstVideoFrameEmitted",!1);this.userId=e||"",this.mediaType=r,this._log=R.createLogger({parent:s==null?void 0:s.getLogger(),id:`${this.kind[0]}t`,userId:(a=s||this.room)==null?void 0:a.userId,remoteUserId:this instanceof _i?void 0:this.userId,sdkAppId:t,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof _i}),this.player=new n({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log,enableVolumeControlInIOS:s==null?void 0:s.enableVolumeControlInIOS}),this.player.on(he.PLAYER_STATE_CHANGED,d=>{if(S.emit(A.PLAYER_STATE_CHANGED,M({track:this},d)),this.emit("player-state-changed",d),d.state==="PLAYING"&&this.room){let l=!0;for(let{remoteAudioTrack:u,remoteVideoTrack:h,remoteAuxiliaryTrack:p}of[...this.room.remotePublishedUserMap.values()])if(u.isAvailable&&!u.player.isPlaying||h.isAvailable&&!h.player.isPlaying||p.isAvailable&&!p.player.isPlaying){l=!1;break}l&&br()&&Vp()}}),this.kind===_.VIDEO&&(this.player.on(he.LOADED_DATA,()=>{this.emitFirstVideoFrameEvent(he.LOADED_DATA),S.emit(A.VIDEO_LOADED_DATA,{track:this})}),this.player.on(he.LOADED_META_DATA,()=>{this.emitFirstVideoFrameEvent(he.LOADED_META_DATA)}),this.player.on(he.MEDIA_TRACK_CHANGED,d=>{var l;(l=this.subVideoPlayerMap)==null||l.forEach(u=>u.setTrack(d))}),this.player.on(he.RESIZE,d=>{this.emitFirstVideoFrameEvent(he.RESIZE),this.emit("video-size-changed",M({userId:this.userId,streamType:this.mediaType===2?"auxiliary":"main"},d))})),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(he.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||R}get kind(){return this.mediaType===1?_.AUDIO:_.VIDEO}get isAudio(){return this.kind===_.AUDIO}get strMediaType(){return this.mediaType===4?_.VIDEO:this.mediaType===2?_.SCREEN:_.AUDIO}get streamType(){return(this.mediaType&2)===0?"main":"auxiliary"}get isMediaTrackActive(){return this.mediaTrack?!this.mediaTrack.muted&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled:!1}play(e,t){return f(this,null,function*(){let r=Ae(e)?e[0]:e;if(this.isPlayCalled){this.log.info(`play update options: ${JSON.stringify(t)}`),t&&!T(t.muted)&&this.setPlayerMute(t.muted),t&&!T(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof pt&&(this.player.setObjectFit(this.objectFit),this.container!==r&&r&&(this.container=r,this.player.setContainer(r)),Ae(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t)));return}if(t&&!T(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===_.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)),S.emit(A.PLAY_TRACK_START,{track:this}),!this._outputTrack){this.log.info("play has not mediaTrack, abort");return}this._log.info(`play with options: ${JSON.stringify(t)}`);try{this.player.setTrack(this.playerMediaTrack),yield this.player.play(t),Ae(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(s){throw this.handleAutoPlayFailed(s),s}})}setMirror(e,t){if(this.isScreen||this.kind!==_.VIDEO||T(e)||e===this.mirror)return;this.mirror=e;let r=this.player;t&&(r=t);let s=this.manager;if(ue(this.mirror)){r.setViewMirror(this.mirror),!this.isRemote&&s&&(s.mirror=!1);return}switch(this.mirror){case"view":{s&&(s.mirror=!1),r.setViewMirror(!0);break}case"publish":{s&&(s.mirror=!0),r.setViewMirror(!0);break}case"both":s&&(s.mirror=!0),r.setViewMirror(!1)}}playSubContainer(e,t){return f(this,null,function*(){if(!this._outputTrack||this.kind===_.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((s,n)=>{var a;e.find(d=>n===d)||(s.stop(),(a=this.subVideoPlayerMap)==null||a.delete(n))});for(let[s,n]of e.entries()){let a=this.subVideoPlayerMap.get(n);a?t&&(T(t.objectFit)||a.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new 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${s+1}`})}))}let r=[...this.subVideoPlayerMap.values()];for(let s of r)s.setViewMirror(this.player.mirror),yield s.play()})}setAudioOutput(e){return this.player.setSinkId(e)}setAudioVolume(e){this.player.setVolume(e)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var e;return((e=this.player)==null?void 0:e.getInternalAudioLevel())||0}stop(e=!1){this.isPlayCalled&&(this.isPlayCalled=!1,this.isFirstVideoFrameEmitted=!1,this.player&&(this.log.info(`stop ${this.kind} player`),this.player.stop(La(this)&&!e?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(t=>{t.stop()}),this.container=null)}resume(){return f(this,null,function*(){var e;this.isPlayCalled&&(yield(e=this.player)==null?void 0:e.resume())})}close(){this.log.info("close"),this.isPlayCalled&&this.stop(!0)}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),S.emit(e?A.TRACK_MUTED:A.TRACK_UNMUTED,{track:this})}setPlayerMute(e){this.player.setMuted(e)}get mediaTrack(){return this._inputTrack||null}get outMediaTrack(){return this._outputTrack||null}get playerMediaTrack(){return this.outMediaTrack}installTrackEvent(e){tt(e,e).add(_.MUTE,this.onTrackMuted).add(_.UNMUTE,this.onTrackUnmuted).add(_.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===_.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){we(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){var t,r;if(this.isPlayCalled){if(e){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped){this.player.play().catch(s=>this.handleAutoPlayFailed(s)),this.log.info(`playing state updated, play ${this.kind}`);return}}else if(!this.player.isStopped){if(La(this)&&this.isAudio&&((t=this.user)!=null&&t.muteState.hasAudio)&&((r=this.user)!=null&&r.muteState.audioMuted))return;this.player.stop(La(this)?this.jitterBufferDelay:0),this.log.info(`playing state updated, stop ${this.kind}`);return}}this.log.debug(`updatePlayingState abort ${this.isPlayCalled} ${e} ${this.player.isStopped}`)}handleAutoPlayFailed(e){return f(this,null,function*(){var r;this.log.warn("handleAutoPlayFailed",e);let t=()=>{this.resume().then(()=>{document.removeEventListener("click",t,!0)})};if(this.room&&this.room.enableAutoPlayDialog){if((ri||oi)&&(yield Ke(100),(r=this.player)!=null&&r.isPlaying))return;ns()}else document.addEventListener("click",t,!0);S.once(A.LOCAL_TRACK_CAPTURE_SUCCESS,({track:s})=>{s.kind==="audio"&&br()&&!this.player.isPlaying&&this.isRemote&&this.isAvailable&&t()}),this.emit("error",e)})}getVideoFrame(){return this.player instanceof pt?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,s=(t==null?void 0:t.height)||((d=this.player.element)==null?void 0:d.videoHeight)||0;e===he.RESIZE&&!r&&!s||e===he.LOADED_META_DATA&&!r&&!s||(e===he.LOADED_DATA&&!r&&!s&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,bt(this.rotation)&&([r,s]=[s,r]),this.emit("first-video-frame",{width:r,height:s,streamType:this.streamType,userId:this.isRemote?this.userId:""}))}onTrackMuted(){this._log.warn(`${this.kind} track is unable to provide media output`)}onTrackUnmuted(){this._log.info(`${this.kind} track is able to provide media output`)}onTrackEnded(){this._log.warn(`${this.kind} track ended`)}};D([ye([],j.INIT,{sync:!0})],no.prototype,"close",1);var qT=Object.prototype.hasOwnProperty,{toString:yb}=Object.prototype;function jT(o){if(o==null)return!0;if(typeof o=="boolean")return!1;if(typeof o=="number")return o===0;if(typeof o=="string"||typeof o=="function"||Array.isArray(o))return o.length===0;if(o instanceof Error)return o.message==="";if(dt(o))switch(Object.prototype.toString.call(o)){case"[object File]":case"[object Map]":case"[object Set]":return o.size===0;case"[object Object]":{for(let i in o)if(qT.call(o,i))return!1;return!0}}return!1}var gi=jT;var XT=function(o){return f(this,null,function*(){let i=QT(o);R.info(`getUserMedia with constraints: ${JSON.stringify(i)}`);let e=[],t=[],r=["label","deviceId","groupId"];if(i.audio&&(e=yield It(),R.info(`microphones: ${gt(e.map(s=>w(M({},s),{groupId:s.groupId.substring(0,8)})),{keysToInclude:r})}`)),i.video&&(t=yield At(),R.info(`cameras: ${gt(t,{keysToInclude:r})}`),!ue(i.video)&&i.video.facingMode==="user"&&!i.video.deviceId)){let n=t.filter(a=>!a.label.includes("infrared")).find(a=>a.label.includes("facing front"));n&&(i.video.deviceId=n.deviceId,R.info(`exclude infrared camera: ${JSON.stringify(i)}`))}try{let s=yield navigator.mediaDevices.getUserMedia(i);return nu&&s.getTracks().forEach(n=>{var d;let a=n.getCapabilities();R.info(`${n.kind} capabilities: ${gt(a,{keysToInclude:Sa})}`),!T(o.echoCancellation)&&((d=a.echoCancellation)==null?void 0:d.indexOf(o.echoCancellation))===-1&&R.warn(`Invalid argument for 'echoCancellation'. Expected one of [${JSON.stringify(a.echoCancellation)}], but received '${o.echoCancellation}'`)}),i.audio&&Nr(),s}catch(s){let{message:n}=s;throw s.name==="NotFoundError"&&(o.video&&t&&t.length===0&&(n=$({key:B.CAMERA_NOT_FOUND})),o.audio&&e&&e.length===0&&(n=$({key:B.MICROPHONE_NOT_FOUND}))),new v({code:I.INITIALIZE_FAILED,name:s.name,message:n,constraint:s.constraint})}})},zT=Ri({retryFunction:XT,settings:{retries:3,timeout:500},onError:({error:o,retry:i,reject:e,retryFuncArgs:t,retriedCount:r})=>{let s=r+1;o.name==="NotReadableError"||o.name==="OverconstrainedError"||o.name==="AbortError"?(s===1?(t[0].video&&(t[0].maxResolution=!1,(!Re||t[0].width*t[0].height<=1920*1080)&&t[0].frameRate&&(t[0].frameRate=t[0].frameRate>10?10:5)),t[0].retryWhenExactFailed&&t[0].useExactDeviceId&&(t[0].useExactDeviceId=!1)):s===2?t[0].useDeviceIdOnly=!0:s===3&&!t[0].useExactDeviceId&&(t[0].useTrueAsConstraint=!0),i()):e(o),t[0].microphoneId&&ef(t[0].microphoneId,!1),t[0].cameraId&&ef(t[0].cameraId,!0)},onRetrying:o=>{R.warn(`getUserMedia NotReadableError observed, retrying [${o}/3]`)},onRetryFailed:o=>{se.logFailedEvent({eventType:Ze.GET_USER_MEDIA_RETRY,error:o})},onRetrySuccess:o=>{se.logSuccessEvent({eventType:Ze.GET_USER_MEDIA_RETRY}),se.uploadEvent({log:`stat-${Ze.GET_USER_MEDIA_RETRY}-success-${o}`})}});function ef(o,i){return f(this,null,function*(){let t=(i?yield At():yield It()).find(r=>r.deviceId===o);t&&le(t.getCapabilities)&&R.warn(gt(t.getCapabilities(),{keysToInclude:Sa}))})}function QT(o){return{audio:YT(o),video:ZT(o)}}function YT(o){if(!o.audio)return!1;if(o.useTrueAsConstraint)return!0;let i={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:o.sampleRate};return!gi(o.microphoneId)&&(i.deviceId=o.useExactDeviceId?{exact:o.microphoneId}:o.microphoneId,o.useDeviceIdOnly)?i:(Q(o.channelCount)&&(i.channelCount=o.channelCount),(ue(o.echoCancellation)||o.echoCancellation==="remote-only"||o.echoCancellation==="all")&&(i.echoCancellation=o.echoCancellation),ue(o.noiseSuppression)&&!o.noiseSuppression&&(i.noiseSuppression=!1),ue(o.autoGainControl)&&!o.autoGainControl&&(i.autoGainControl=!1),gi(i)?!0:i)}function ZT(o){if(!o.video)return!1;if(o.useTrueAsConstraint)return!0;let{maxResolution:i=!0}=o,e={};return o.cameraId?e.deviceId=o.useExactDeviceId?{exact:o.cameraId}:o.cameraId:o.facingMode&&(e.facingMode=o.facingMode),o.useDeviceIdOnly&&!gi(e)?e:(o.width&&(e.width={ideal:o.width},i&&!ee&&(e.width.max=o.width)),o.height&&(e.height={ideal:o.height},i&&!ee&&(e.height.max=o.height)),ee&&si&&o.width&&o.height&&o.width*o.height<352*288&&(e.width=o.width,e.height=o.height),o.frameRate&&(e.frameRate=o.frameRate),gi(e)?!0:e)}var tf=zT;function Md(o){return Y((i,e)=>function(...t){return f(this,null,function*(){return yield o.apply(this,t),i.apply(this,t)})})}function Ct(o){return Y((i,e)=>function(...t){return f(this,null,function*(){let r=yield i.apply(this,t);return yield o.call(this,...t),r})})}function Od(o){return Y((i,e)=>function(...t){return f(this,null,function*(){try{return yield i.apply(this,t)}catch(r){o.call(this,r)}})})}function Y(o){return function(i,e,t){return t.value=o(t.value,e),t}}var rf=(()=>{let o=!1,i=document.visibilityState;return()=>{document.visibilityState!==i&&R.info(`visibility change: ${document.visibilityState}`),!o&&(document.addEventListener("visibilitychange",()=>{R.info(`visibility change: ${document.visibilityState}`),i=document.visibilityState}),o=!0)}})();var KT=0,kd=class{constructor(){c(this,"log",R.createLogger({id:`fq${++KT}`}));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 s,n;let t=M({},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=(s=this.lastQueueItem)==null?void 0:s.promise)==null||n.then(t.resolve,t.reject):this.queue.push(t),this.log.debug(`push ${this.length}`),this.isRunning||this.callNext(),r}shift(){let i=this.queue.shift();return this.log.debug(`shift ${this.length}`),i}callNext(){if(this.isRunning||this.length===0)return;this.log.debug("callNext ",this.length);let{fn:i,args:e,context:t,resolve:r,reject:s}=this.queue[0];this.isRunning=!0,i.apply(t,e).then(r,s).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},Pd=new WeakMap,Ld=new WeakMap;function ir(o=!1){return function(i,e,t){let r=t.value;return t.value=function(...s){let n=Pd.get(this)||new kd;return Pd.set(this,n),n.push({fn:r,args:s,context:this},o)},t}}function xd(o){return function(i,e,t){let r=t.value;return t.value=function(...s){var a,d,l;let n=[];return(d=(a=Pd.get(this))==null?void 0:a.queue)==null||d.forEach(u=>n.push(u)),(l=Ld.get(this))==null||l.forEach(u=>u==null?void 0:u.queue.forEach(h=>n.push(h))),n.forEach(u=>{u.reject(new v({code:I.API_CALL_ABORTED,message:o}))}),Pd.delete(this),Ld.delete(this),r.apply(this,s)},t}}function Ti(o){return function(i,e,t){let r=t.value,s=n=>o(...n);return t.value=function(...n){let a=Ld.get(this)||new Map,d=a.get(s(n))||new kd;return a.set(s(n),d),Ld.set(this,a),d.push({fn:r,args:n,context:this})},t}}function Rt(o,i){return Y((e,t)=>function(...r){let s=o;try{let n=e.apply(this,r),a=V();return Tr(n)?n.then(d=>(i?y.addSuccessEvent({key:s,cost:V()-a}):y.addSuccessEvent({key:s}),d)).catch(d=>{throw y.addFailedEvent({key:s,error:d}),d}):(y.addSuccessEvent({key:s}),n)}catch(n){throw y.addFailedEvent({key:s,error:n}),n}})}var fh={};Bi(fh,{Events:()=>Oe,Inspect:()=>Ht,LastSink:()=>ao,Sink:()=>X,Subscribe:()=>co,TimeoutError:()=>Pn,audit:()=>wE,bindCallback:()=>IE,bindNodeCallback:()=>AE,buffer:()=>dE,bufferCount:()=>aE,bufferTime:()=>tS,call:()=>of,catchError:()=>hh,combineLatest:()=>nf,concat:()=>iE,concatMap:()=>jE,concatMapTo:()=>XE,count:()=>yE,create:()=>ae,debounce:()=>UE,debounceTime:()=>VE,defer:()=>af,delay:()=>iS,deliver:()=>z,dispose:()=>wd,elementAt:()=>FE,empty:()=>Un,every:()=>GE,exhaustMap:()=>YE,exhaustMapTo:()=>ZE,expand:()=>rS,filter:()=>$t,find:()=>BE,findIndex:()=>HE,first:()=>$E,fromAnimationFrame:()=>EE,fromArray:()=>mE,fromEvent:()=>de,fromEventPattern:()=>pE,fromFetch:()=>fE,fromIterable:()=>_E,fromPromise:()=>lf,fromReadableStream:()=>TE,fromReader:()=>gE,groupBy:()=>KE,identity:()=>eE,ignoreElements:()=>DE,iif:()=>oE,inspect:()=>sf,interval:()=>wu,last:()=>WE,map:()=>Vn,mapTo:()=>qE,max:()=>bE,merge:()=>Ln,mergeMap:()=>zE,mergeMapTo:()=>QE,min:()=>NE,never:()=>CE,nothing:()=>pe,of:()=>hE,pairwise:()=>JE,pipe:()=>ce,race:()=>Lu,range:()=>SE,reduce:()=>Uu,retry:()=>aS,scan:()=>uh,setAsapScheduler:()=>uE,share:()=>rr,shareReplay:()=>rE,skip:()=>OE,skipUntil:()=>kE,skipWhile:()=>Hd,startWith:()=>xn,subject:()=>rt,subscribe:()=>Te,sum:()=>vE,switchMap:()=>Mr,switchMapTo:()=>mo,take:()=>or,takeLast:()=>ME,takeUntil:()=>ke,takeWhile:()=>uf,tap:()=>Fn,throttle:()=>LE,throwError:()=>RE,timeInterval:()=>eS,timeout:()=>nS,timer:()=>wn,toPromise:()=>oS,toReadableStream:()=>sS,withLatestFrom:()=>nE,zip:()=>sE});function pe(...o){}var of=o=>o(),eE=o=>o;function wd(){this.dispose()}var sf=()=>typeof __FASTRX_DEVTOOLS__!="undefined",tE=1,Ht=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(i){let e=new Mu(i,this,this.streamId++);return Oe.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},ao=class{constructor(){this.defers=new Set,this.disposed=!1}next(i){}complete(){this.dispose()}error(i){this.dispose()}get bindDispose(){return()=>this.dispose()}dispose(){this.disposed=!0,this.complete=pe,this.error=pe,this.next=pe,this.dispose=pe,this.subscribe=pe,this.doDefer()}subscribe(i){return i instanceof Ht?i.subscribe(this):i(this),this}get bindSubscribe(){return i=>this.subscribe(i)}doDefer(){this.defers.forEach(of),this.defers.clear()}defer(i){this.defers.add(i)}removeDefer(i){this.defers.delete(i)}reset(){this.disposed=!1,delete this.complete,delete this.next,delete this.dispose,delete this.next,delete this.subscribe}resetNext(){delete this.next}resetComplete(){delete this.complete}resetError(){delete this.error}},X=class extends ao{constructor(i){super(),this.sink=i,i.defer(this.bindDispose)}next(i){this.sink.next(i)}complete(){this.sink.complete()}error(i){this.sink.error(i)}},co=class extends ao{constructor(i,e=pe,t=pe,r=pe){if(super(),this._next=e,this._error=t,this._complete=r,this.then=pe,i instanceof Ht){let s={toString:()=>"subscribe",id:0,source:i};this.defer(()=>{Oe.defer(s,0)}),Oe.create(s),Oe.pipe(s),this.sourceId=s.id,this.subscribe(i),Oe.subscribe({id:s.id,end:!0}),e==pe?this._next=n=>Oe.next(s,0,n):this.next=n=>{Oe.next(s,0,n),e(n)},r==pe?this._complete=()=>Oe.complete(s,0):this.complete=()=>{this.dispose(),Oe.complete(s,0),r()},t==pe?this._error=n=>Oe.complete(s,0,n):this.error=n=>{this.dispose(),Oe.complete(s,0,n),t(n)}}else this.subscribe(i)}next(i){this._next(i)}complete(){this.dispose(),this._complete()}error(i){this.dispose(),this._error(i)}};function ce(o,...i){return i.reduce((e,t)=>t(e),o)}function ae(o,i,e){if(sf()){let t=Object.defineProperties(Object.setPrototypeOf(o,Ht.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:i,writable:!0,configurable:!0},args:{value:e,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});Oe.create(t);for(let r=0;r<e.length;r++){let s=e[r];typeof s=="function"&&s instanceof Ht&&Oe.addSource(t,s)}return t}return o}function z(o,i){return function(...e){return t=>{if(t instanceof Ht){let r=ae(s=>{let n=new o(s,...e);n.sourceId=r.id,n.subscribe(t)},i,arguments);return r.source=t,Oe.pipe(r),r}else return r=>t(new o(r,...e))}}}function Dr(o,i){window.postMessage({source:"fastrx-devtools-backend",payload:{event:o,payload:i}})}var Mu=class extends X{constructor(i,e,t){super(i),this.source=e,this.id=t,this.sourceId=i.sourceId,this.defer(()=>{Oe.defer(this.source,this.id)})}next(i){Oe.next(this.source,this.id,i),this.sink.next(i)}complete(){Oe.complete(this.source,this.id),this.sink.complete()}error(i){Oe.complete(this.source,this.id,i),this.sink.error(i)}},Oe={addSource(o,i){Dr("addSource",{id:o.id,name:o.toString(),source:{id:i.id,name:i.toString()}})},next(o,i,e){Dr("next",{id:o.id,streamId:i,data:e&&e.toString()})},subscribe({id:o,end:i},e){Dr("subscribe",{id:o,end:i,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(o,i,e){Dr("complete",{id:o.id,streamId:i,err:e?e.toString():null})},defer(o,i){Dr("defer",{id:o.id,streamId:i})},pipe(o){Dr("pipe",{name:o.toString(),id:o.id,source:{id:o.source.id,name:o.source.toString()}})},update(o){Dr("update",{id:o.id,name:o.toString()})},create(o){o.id||(o.id=tE++),Dr("create",{name:o.toString(),id:o.id})}},Pn=class extends Error{constructor(i){super(`timeout after ${i}ms`),this.timeout=i}};var Ud=class extends ao{constructor(i){super(),this.source=i,this.sinks=new Set}add(i){i.defer(()=>this.remove(i)),this.sinks.add(i).size===1&&(this.reset(),this.subscribe(this.source))}remove(i){this.sinks.delete(i),this.sinks.size===0&&this.dispose()}next(i){this.sinks.forEach(e=>e.next(i))}complete(){this.sinks.forEach(i=>i.complete()),this.sinks.clear()}error(i){this.sinks.forEach(e=>e.error(i)),this.sinks.clear()}};function rr(){return o=>{let i=new Ud(o);if(o instanceof Ht){let e=ae(t=>{i.add(t)},"share",arguments);return i.sourceId=e.id,e.source=o,Oe.pipe(e),e}return ae(i.add.bind(i),"share",arguments)}}function Ln(...o){return ae(i=>{let e=new X(i),t=o.length;e.complete=()=>{--t===0&&i.complete()},o.forEach(e.bindSubscribe)},"merge",arguments)}function Lu(...o){return ae(i=>{let e=new Map;o.forEach(t=>{let r=new X(i);e.set(t,r),r.complete=()=>{e.delete(t),e.size===0?i.complete():r.dispose()},r.next=s=>{e.delete(t),e.forEach(n=>n.dispose()),r.resetNext(),r.resetComplete(),r.next(s)}}),o.forEach(t=>e.get(t).subscribe(t))},"race",arguments)}function iE(...o){return ae(i=>{let e=0,t=o.length,r=new X(i);r.complete=()=>{e<t&&!r.disposed?(r.doDefer(),r.subscribe(o[e++])):i.complete()},r.complete()},"concat",arguments)}function rE(o){return i=>{let e=new Ud(i),t=[];return e.next=function(r){t.push(r),t.length>o&&t.shift(),this.sinks.forEach(s=>s.next(r))},ae(r=>{r.defer(()=>e.remove(r)),t.forEach(s=>r.next(s)),e.add(r)},"shareReplay",arguments)}}function oE(o,i,e){return ae(t=>o()?i(t):e(t),"iif",arguments)}function nf(...o){return ae(i=>{let e=o.length,t=e,r=e,s=new Array(e),n=()=>{--r===0&&i.complete()},a=(d,l)=>{let u=new X(i);u.next=h=>{t--,u.next=p=>{s[l]=p,t===0&&i.next(s)},u.next(h)},u.complete=n,u.subscribe(d)};o.forEach(a)},"combineLatest",arguments)}function sE(...o){return ae(i=>{let e=o.length,t=e,r=new Array(e),s=()=>{--t===0&&i.complete()},n=(a,d)=>{let l=new X(i),u=[];r[d]=u,l.next=h=>{u.push(h),r.every(p=>p.length)&&i.next(r.map(p=>p.shift()))},l.complete=s,l.subscribe(a)};o.forEach(n)},"zip",arguments)}function xn(...o){return i=>ae((e,t=0,r=o.length)=>{for(;t<r&&!e.disposed;)e.next(o[t++]);e.disposed||e.subscribe(i)},"startWith",arguments)}var Ou=class extends X{constructor(i,...e){super(i);let t=new X(this.sink);t.next=r=>this.buffer=r,t.complete=pe,t.subscribe(nf(...e))}next(i){this.buffer&&this.sink.next([i,...this.buffer])}},nE=z(Ou,"withLatestFrom"),ku=class extends X{constructor(i,e,t){super(i),this.bufferSize=e,this.startBufferEvery=t,this.buffer=[],this.count=0,this.startBufferEvery&&(this.buffers=[[]])}next(i){this.startBufferEvery?(this.count++===this.startBufferEvery&&(this.buffers.push([]),this.count=1),this.buffers.forEach(e=>{e.push(i)}),this.buffers[0].length===this.bufferSize&&this.sink.next(this.buffers.shift())):(this.buffer.push(i),this.buffer.length===this.bufferSize&&(this.sink.next(this.buffer),this.buffer=[]))}complete(){this.buffer.length?this.sink.next(this.buffer):this.buffers.length&&this.buffers.forEach(i=>this.sink.next(i)),super.complete()}},aE=z(ku,"bufferCount"),Pu=class extends X{constructor(i,e){super(i),this.buffer=[];let t=new X(i);t.next=r=>{i.next(this.buffer),this.buffer=[]},t.complete=pe,t.subscribe(e)}next(i){this.buffer.push(i)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},dE=z(Pu,"buffer");var cE=function(o,i,e,t){function r(s){return s instanceof e?s:new e(function(n){n(s)})}return new(e||(e=Promise))(function(s,n){function a(u){try{l(t.next(u))}catch(h){n(h)}}function d(u){try{l(t.throw(u))}catch(h){n(h)}}function l(u){u.done?s(u.value):r(u.value).then(a,d)}l((t=t.apply(o,i||[])).next())})};function rt(o){let i=arguments,e=rr()(ae(t=>{e.next=r=>t.next(r),e.complete=()=>t.complete(),e.error=r=>t.error(r),o&&t.subscribe(o)},"subject",i));return e.next=pe,e.complete=pe,e.error=pe,e}function af(o){return ae(i=>i.subscribe(o()),"defer",arguments)}var hs={promise:o=>{Promise.resolve().then(o)},setImmediate:typeof setImmediate!="undefined"?o=>setImmediate(o):null,setTimeout:o=>setTimeout(o,0)},lE=()=>typeof Promise!="undefined"?hs.promise:hs.setImmediate?hs.setImmediate:hs.setTimeout,xu=lE(),df=o=>i=>{xu(()=>o(i))},uE=o=>{typeof o=="function"?xu=o:hs[o]&&(xu=hs[o])};var cf=o=>df(i=>{for(let e=0;!i.disposed&&e<o.length;e++)i.next(o[e]);i.complete()});function hE(...o){return ae(cf(o),"of",arguments)}function mE(o){return ae(cf(o),"fromArray",arguments)}function wu(o){return ae(i=>{let e=0,t=setInterval(()=>i.next(e++),o);return i.defer(()=>{clearInterval(t)}),"interval"},"interval",arguments)}function wn(o,i){return ae(e=>{let t=0,r=setTimeout(()=>{if(e.removeDefer(s),e.next(t++),i){let n=setInterval(()=>e.next(t++),i);e.defer(()=>{clearInterval(n)})}else e.complete()},o),s=()=>clearTimeout(r);e.defer(s)},"timer",arguments)}function Vd(o,i){return e=>{let t=r=>e.next(r);e.defer(()=>i(t)),o(t)}}function pE(o,i){return ae(Vd(o,i),"fromEventPattern",arguments)}function de(o,i){if("on"in o&&"off"in o)return ae(Vd(e=>o.on(i,e),e=>o.off(i,e)),"fromEvent",arguments);if("addListener"in o&&"removeListener"in o)return ae(Vd(e=>o.addListener(i,e),e=>o.removeListener(i,e)),"fromEvent",arguments);if("addEventListener"in o)return ae(Vd(e=>o.addEventListener(i,e),e=>o.removeEventListener(i,e)),"fromEvent",arguments);throw"target is not a EventDispachter"}function lf(o){return ae(i=>{o.then(i.next.bind(i),i.error.bind(i))},"fromPromise",arguments)}function fE(o,i){return ae(af(()=>lf(fetch(o,i))),"fromFetch",arguments)}function _E(o){return ae(df(i=>{try{for(let e of o){if(i.disposed)return;i.next(e)}i.complete()}catch(e){i.error(e)}}),"fromIterable",arguments)}function gE(o){let i=e=>cE(this,void 0,void 0,function*(){if(e.disposed)return;let{done:t,value:r}=yield o.read();if(t){e.complete();return}else e.next(r),i(e)});return ae(e=>{i(e)},"fromReader",arguments)}function TE(o){return ae(i=>{let e=new AbortController,t=e.signal;i.defer(()=>e.abort("cancelled")),o.pipeTo(new WritableStream({write(r){i.next(r)},close(){i.complete()},abort(r){i.error(r)}}),{signal:t}).then(()=>i.complete(),r=>i.error(r))},"fromReadableStream",arguments)}function EE(){return ae(o=>{let i=requestAnimationFrame(function e(t){o.disposed||(o.next(t),i=requestAnimationFrame(e))});o.defer(()=>cancelAnimationFrame(i))},"fromAnimationFrame",arguments)}function SE(o,i){return ae((e,t=o,r=i+o)=>{for(;t<r&&!e.disposed;)e.next(t++);return e.complete(),"range"},"range",arguments)}function IE(o,i,...e){return ae(t=>{let r=e.concat(s=>(t.next(s),t.complete()));o.apply(i,r)},"bindCallback",arguments)}function AE(o,i,...e){return ae(t=>{let r=e.concat((s,n)=>s?t.error(s):(t.next(n),t.complete()));o.apply(i,r)},"bindNodeCallback",arguments)}function CE(){return ae(()=>{},"never",arguments)}function RE(o){return ae(i=>i.error(o),"throwError",arguments)}function Un(){return ae(o=>o.complete(),"empty",arguments)}var lo=class extends X{constructor(i,e,t){super(i),this.f=e;let r=()=>{this.sink.next(this.acc),this.sink.complete()};typeof t=="undefined"?this.next=s=>{this.acc=s,this.complete=r,this.resetNext()}:(this.acc=t,this.complete=r)}next(i){this.acc=this.f(this.acc,i)}},Uu=z(lo,"reduce"),yE=o=>z(lo,"count")((i,e)=>o(e)?i+1:i,0),bE=()=>z(lo,"max")(Math.max),NE=()=>z(lo,"min")(Math.min),vE=()=>z(lo,"sum")((o,i)=>o+i,0);var Vu=class extends X{constructor(i,e,t){super(i),this.filter=e,this.thisArg=t}next(i){this.filter.call(this.thisArg,i)&&this.sink.next(i)}},$t=z(Vu,"filter"),Fu=class extends X{next(i){}},DE=z(Fu,"ignoreElements"),Bu=class extends X{constructor(i,e){super(i),this.count=e}next(i){this.sink.next(i),--this.count===0&&(this.doDefer(),this.complete())}},or=z(Bu,"take"),Hu=class extends X{constructor(i,e){super(i);let t=new X(i);t.next=()=>{t.doDefer(),i.complete()},t.complete=wd,t.subscribe(e)}},ke=z(Hu,"takeUntil"),$u=class extends X{constructor(i,e){super(i),this.f=e}next(i){this.f(i)?this.sink.next(i):(this.doDefer(),this.complete())}},uf=z($u,"takeWhile"),ME=o=>Uu((i,e)=>(i.push(e),i.length>o&&i.shift(),i),[]),Wu=class extends X{constructor(i,e){super(i),this.count=e}next(i){--this.count===0&&(this.next=super.next)}},OE=z(Wu,"skip"),Gu=class extends X{constructor(i,e){super(i),i.next=pe;let t=new X(i);t.next=()=>{t.doDefer(),i.resetNext()},t.complete=wd,t.subscribe(e)}},kE=z(Gu,"skipUntil"),Ju=class extends X{constructor(i,e){super(i),this.f=e}next(i){this.f(i)||(this.next=super.next,this.next(i))}},Hd=z(Ju,"skipWhile"),PE={leading:!0,trailing:!1},qu=class extends X{constructor(i,e,t){super(i),this.durationSelector=e,this.trailing=t}cacheValue(i){this.last=i,this.disposed&&this.throttle(i)}send(i){this.sink.next(i),this.throttle(i)}throttle(i){this.reset(),this.subscribe(this.durationSelector(i))}next(){this.complete()}complete(){this.dispose(),this.trailing&&this.send(this.last)}},Fd=class extends X{constructor(i,e,t=PE){super(i),this.durationSelector=e,this.config=t,this._throttle=new qu(this.sink,this.durationSelector,this.config.trailing),this._throttle.dispose()}next(i){this._throttle.disposed&&this.config.leading?this._throttle.send(i):this._throttle.cacheValue(i)}complete(){this._throttle.throttle=pe,this._throttle.complete(),super.complete()}},LE=z(Fd,"throttle"),xE={leading:!1,trailing:!0},wE=o=>z(Fd,"audit")(o,xE),ju=class extends X{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},Bd=class extends X{constructor(i,e){super(i),this.durationSelector=e,this._debounce=new ju(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()}},UE=z(Bd,"debounce"),VE=o=>z(Bd,"debounceTime")(i=>wn(o)),Xu=class extends X{constructor(i,e,t){super(i),this.count=e,this.defaultValue=t}next(i){this.count--===0&&(this.defaultValue=i,this.doDefer(),this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("not enough elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},FE=z(Xu,"elementAt"),BE=o=>i=>or(1)(Hd(e=>!o(e))(i)),zu=class extends X{constructor(i,e){super(i),this.f=e,this.i=0}next(i){this.f(i)?(this.sink.next(this.i++),this.doDefer(),this.complete()):++this.i}},HE=z(zu,"findIndex"),Qu=class extends X{constructor(i,e,t){super(i),this.f=e,this.defaultValue=t,this.index=0}next(i){(!this.f||this.f(i,this.index++))&&(this.defaultValue=i,this.doDefer(),this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},$E=z(Qu,"first"),Yu=class extends X{constructor(i,e,t){super(i),this.f=e,this.defaultValue=t,this.index=0}next(i){(!this.f||this.f(i,this.index++))&&(this.defaultValue=i)}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},WE=z(Yu,"last"),Zu=class extends X{constructor(i,e){super(i),this.predicate=e,this.index=0}next(i){this.predicate(i,this.index++)?this.result=!0:(this.result=!1,this.doDefer(),this.complete())}complete(){if(this.result===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.result);super.complete()}},GE=z(Zu,"every");var Ku=class extends X{constructor(i,e,t){super(i),this.f=e,typeof t=="undefined"?this.next=r=>{this.acc=r,this.resetNext(),this.sink.next(this.acc)}:this.acc=t}next(i){this.sink.next(this.acc=this.f(this.acc,i))}},uh=z(Ku,"scan"),eh=class extends X{constructor(){super(...arguments),this.hasLast=!1}next(i){this.hasLast?this.sink.next([this.last,i]):this.hasLast=!0,this.last=i}},JE=z(eh,"pairwise"),$d=class extends X{constructor(i,e,t){super(i),this.mapper=e,this.thisArg=t}next(i){super.next(this.mapper.call(this.thisArg,i))}},Vn=z($d,"map"),qE=o=>z($d,"mapTo")(i=>o),uo=class extends X{constructor(i,e,t){super(i),this.data=e,this.context=t}next(i){let e=this.context.combineResults;e?this.sink.next(e(this.data,i)):this.sink.next(i)}tryComplete(){this.context.resetComplete(),this.dispose()}},ho=class o extends X{constructor(i,e,t){super(i),this.makeSource=e,this.combineResults=t,this.index=0}subInner(i,e){let t=this.currentSink=new e(this.sink,i,this);this.complete===o.prototype.complete&&(this.complete=this.tryComplete),t.complete=t.tryComplete,t.subscribe(this.makeSource(i,this.index++))}complete(){this.sink.complete()}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},Wd=class extends uo{},Gd=class extends ho{next(i){this.subInner(i,Wd),this.next=e=>{this.currentSink.dispose(),this.subInner(e,Wd)}}},Mr=z(Gd,"switchMap");function Xd(o){return(i,e)=>o(()=>i,e)}var mo=Xd(z(Gd,"switchMapTo")),th=class extends uo{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},Jd=class extends ho{constructor(){super(...arguments),this.sources=[],this.next2=this.sources.push.bind(this.sources)}next(i){this.next2(i),this.subNext()}subNext(){this.next=this.next2,this.subInner(this.sources.shift(),th),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},jE=z(Jd,"concatMap"),XE=Xd(z(Jd,"concatMapTo")),ih=class extends uo{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},qd=class extends ho{constructor(){super(...arguments),this.inners=new Set}next(i){this.subInner(i,ih),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(i=>i.resetComplete()):this.dispose()}},zE=z(qd,"mergeMap"),QE=Xd(z(qd,"mergeMapTo")),rh=class extends uo{dispose(){this.context.resetNext(),super.dispose()}},jd=class extends ho{next(i){this.next=pe,this.subInner(i,rh)}},YE=z(jd,"exhaustMap"),ZE=Xd(z(jd,"exhaustMapTo")),oh=class extends X{constructor(i,e){super(i),this.f=e,this.groups=new Map}next(i){let e=this.f(i),t=this.groups.get(e);typeof t=="undefined"&&(t=rt(),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)}},KE=z(oh,"groupBy"),sh=class extends X{constructor(){super(...arguments),this.start=new Date}next(i){this.sink.next({value:i,interval:Number(new Date)-Number(this.start)}),this.start=new Date}},eS=z(sh,"timeInterval"),nh=class extends X{constructor(i,e){super(i),this.miniseconds=e,this.buffer=[],this.id=setInterval(()=>{this.sink.next(this.buffer.concat()),this.buffer.length=0},this.miniseconds)}next(i){this.buffer.push(i)}complete(){this.sink.next(this.buffer),super.complete()}dispose(){clearInterval(this.id),super.dispose()}},tS=z(nh,"bufferTime"),ah=class extends X{constructor(i,e){super(i),this.buffer=[],this.delayTime=e}dispose(){clearTimeout(this.timeoutId),super.dispose()}delay(i){this.timeoutId=setTimeout(()=>{let e=this.buffer.shift();if(e){let{time:t,data:r}=e;super.next(r),this.buffer.length&&this.delay(Number(this.buffer[0].time)-Number(t))}},i)}next(i){this.buffer.length||this.delay(this.delayTime),this.buffer.push({time:new Date,data:i})}complete(){this.timeoutId=setTimeout(()=>super.complete(),this.delayTime)}},iS=z(ah,"delay"),dh=class extends X{constructor(i,e){super(i),this.selector=e}error(i){this.dispose(),this.selector(i)(this.sink)}},hh=z(dh,"catchError"),ch=class extends uo{tryComplete(){let i=this.context.inners.delete(this);super.dispose(),i&&this.context.checkComplete()}next(i){this.sink.next(i),this.context.expandValue(i)}},lh=class extends ho{constructor(i,e){super(i,e),this.project=e,this.inners=new Set,this.sourceCompleted=!1}next(i){this.sink.next(i),this.expandValue(i)}expandValue(i){let e=new ch(this.sink,i,this);this.currentSink=e,this.complete=this.tryComplete,e.complete=e.tryComplete,this.inners.add(e),e.subscribe(this.makeSource(i,this.index++))}complete(){this.sourceCompleted=!0,this.checkComplete()}checkComplete(){this.sourceCompleted&&this.inners.size===0&&(this.resetComplete(),super.complete())}tryComplete(){this.sourceCompleted=!0,this.checkComplete()}},rS=z(lh,"expand");var oS=()=>o=>new Promise((i,e)=>{let t;new co(o,r=>t=r,e,()=>i(t))}),sS=()=>o=>{let i;return new ReadableStream({start(e){i=new co(o,e.enqueue.bind(e),e.error.bind(e),e.close.bind(e))},cancel(){i.dispose()}})},Te=(o=pe,i=pe,e=pe)=>t=>new co(t,o,i,e),mh=class extends X{constructor(i,e){super(i),e instanceof Function?this.next=t=>{e(t),i.next(t)}:(e.next&&(this.next=t=>{e.next(t),i.next(t)}),e.complete&&(this.complete=()=>{e.complete(),i.complete()}),e.error&&(this.error=t=>{e.error(t),i.error(t)}))}},Fn=z(mh,"tap"),ph=class extends X{constructor(i,e){super(i),this.timeout=e,this.id=setTimeout(()=>this.error(new Pn(this.timeout)),this.timeout)}next(i){super.next(i),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},nS=z(ph,"timeout"),aS=(o=1/0)=>i=>{if(i instanceof Ht){let e=ae(t=>{let r=o,s=new X(t);s.error=n=>{r-- >0?s.subscribe(i):t.error(n)},s.sourceId=e.id,s.subscribe(i)},"retry",[o]);return e.source=i,Oe.pipe(e),e}else return e=>{let t=o,r=new X(e);r.error=s=>{t-- >0?i(r):e.error(s)},i(r)}};var ms=(e=>(e[e.AUTO_SWITCH_NEW_DEVICE=0]="AUTO_SWITCH_NEW_DEVICE",e[e.WAIT_CURRENT_DEVICE=1]="WAIT_CURRENT_DEVICE",e))(ms||{}),po=class po extends no{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,"enableAutoSwitchWhenRecapturing",!0);c(this,"_isRecapturing",!1);c(this,"_lastRecaptureTime",0);c(this,"_onMuteTimeoutId",-1);c(this,"_encodeCheckTimeoutId",-1);c(this,"recaptureMode",0);c(this,"profile");c(this,"retryEncodeFailed")}get enableEncodeFrame(){return!1}get isPublishing(){return this.state.toString()==="publishing"}get isPublished(){return this.state==="publish"}get isUseCustomSource(){return this.sourceTrack&&this.mediaTrack&&this.sourceTrack!==this.mediaTrack}encodeFrame(e,t){throw new Error("Method not implemented.")}installTrackEvent(e){e.addEventListener(_.MUTE,this.onTrackMuted),e.addEventListener(_.UNMUTE,this.onTrackUnmuted),e.addEventListener(_.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===_.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){e.removeEventListener(_.MUTE,this.onTrackMuted),e.removeEventListener(_.UNMUTE,this.onTrackUnmuted),e.removeEventListener(_.ENDED,this.onTrackEnded)}setStateToReady(){}capture(e,t=!1){return f(this,null,function*(){var s;let r=this.sourceTrack;try{let n=V();S.emit(A.LOCAL_TRACK_CAPTURE_START,{track:this});let a;e.customSource?(a=new MediaStream,a.addTrack(e.customSource)):(t||(s=this.sourceTrack)==null||s.stop(),a=yield tf(e));let d=a.getTracks()[0];return yield this.setInputMediaStreamTrack(d),e.customSource||(this.sourceTrack=d,this.updateDeviceIdInUse(),this.listenDeviceChange()),S.emit(A.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:V()-n}),a}catch(n){throw S.emit(A.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:n}),this.log.error(`getUserMedia error observed ${n}`),n}finally{t&&(r==null||r.stop())}})}setOutputMediaStreamTrack(e){var t;if(super.setOutputMediaStreamTrack(e),this.setStateToReady(),this.isPublishing||this.isPublished)return(t=this.room)==null?void 0:t.replaceTrack(this)}get hasFlag(){var t,r;let e=Kt(((t=this.room)==null?void 0:t.localPublishFlag)||0,((r=this.room)==null?void 0:r.userId)||"");return this.mediaType===4&&e.hasVideo||this.mediaType===1&&e.hasAudio||this.mediaType===2&&e.hasAuxiliary}publish(e,t){return f(this,null,function*(){return this.room=e,this.room.localTracks.add(this),this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.bindParent(e.getLogger()),yield t,this._checkPublishFlag(e)})}_checkPublishFlag(e){return new Promise((t,r)=>f(this,null,function*(){var l,u,h,p;let s=()=>r(new v({code:I.API_CALL_ABORTED,message:"publish aborted"}));if(this.hasFlag||this.muted?t():((this.state===j.INIT||this.state==="ready")&&s(),ce(de(e,"local-publish-flag-changed"),$t(()=>this.hasFlag),ke(Ln(de(this,j.INIT),de(this,"ready"))),Te(t,r,s))),(((u=(l=this.room)==null?void 0:l.networkQuality)==null?void 0:u.uplinkNetworkQuality)||0)>3)return t();let a=e.heartbeatCount,d=((p=(h=this.mediaTrack)==null?void 0:h.stats)==null?void 0:p.totalFrames)||0;this._encodeCheckTimeoutId=setTimeout(()=>f(this,null,function*(){var g,E,C,P,re,L,Qe;if((((E=(g=this.room)==null?void 0:g.networkQuality)==null?void 0:E.uplinkNetworkQuality)||0)>3||e.heartbeatCount-a<3)return t();if((this.isPublished||this.isPublishing)&&this.isMediaTrackActive){if((C=this.mediaTrack)!=null&&C.stats){let O=this.mediaTrack.stats.totalFrames||0;O-d===0&&this.log.warn("capture totalFrames is 0 during encode check, totalFrames",O)}let N=this.kind===_.AUDIO,k=this.stat.bytesSent>0;if(y[k?"addSuccessEvent":"addFailedEvent"]({key:N?503700:513702}),!N){let O=((re=(P=this.room)==null?void 0:P.videoCodec)==null?void 0:re.toUpperCase())||"H264",Ne={H264:513704,H265:513705,VP8:513706}[O];Ne&&y[k?"addSuccessEvent":"addFailedEvent"]({key:Ne})}if(!k){if(y.addEnum({key:N?503701:513703,value:Zr()}),se.uploadEvent({log:`stat-encode-failed-${this.kind}-${ai()||di()}`,userId:this.userId}),this.log.warn(N?"encode failed":`${(Qe=(L=this.room)==null?void 0:L.videoCodec)==null?void 0:Qe.toUpperCase()} encode failed`),this.retryEncodeFailed&&(this.log.warn("retry encode"),yield this.retryEncodeFailed(this),this.stat.bytesSent>0||this.hasFlag||(yield Ke(5e3),this.stat.bytesSent>0||this.hasFlag)))return t();this.emit("6",this),r(new v({message:`${this.strMediaType} encode failed`,code:N?I.AUDIO_ENCODE_FAILED:I.VIDEO_ENCODE_FAILED}))}}}),1e4)}))}unpublish(){this.room&&this.room.localTracks.delete(this),this.log.info("unpublish"),S.emit(A.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return f(this,null,function*(){if(this.sourceTrack&&Ni){let{deviceId:e,groupId:t}=this.sourceTrack.getSettings(),{label:r}=this.sourceTrack;(yield Kp({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=r,t&&(this.groupId=t),cs().then(n=>{let a=n.find(d=>{let l=d.deviceId===e;return t&&(l=l&&d.groupId===t),l});a&&this.emit("2",a)}))}})}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(e=!1){return!(!this.deviceId||!this.sourceTrack||this.kind===_.AUDIO&&!Zp(this.sourceTrack)||this.kind===_.VIDEO&&!Yp(this.sourceTrack)||this._isRecapturing||e&&si&&Re)}onTrackMuted(){if(super.onTrackMuted(),rf(),!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<ko){setTimeout(()=>this.onTrackMuted(),ko);return}this._onMuteTimeoutId=setTimeout(()=>f(this,null,function*(){var e;if((e=this.sourceTrack)!=null&&e.muted){if((ge||_e)&&document.visibilityState!=="visible")return;this.recapture(yield this.getRecoverCaptureDeviceId())}}),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return f(this,null,function*(){if(Le(po.prototype,this,"onTrackEnded").call(this),!!this.isNeedToRecapture()&&this.recaptureMode===0){if(Date.now()-this._lastRecaptureTime<ko){setTimeout(()=>this.onTrackEnded(),ko);return}this.emit("7"),this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e,t=!1){return f(this,null,function*(){var n;if(this._isRecapturing||!this.sourceTrack)return;this.log.warn("recapture trying");let r=this.sourceTrack;t||(n=this.sourceTrack)==null||n.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let s={useExactDeviceId:!0};if(e==="user"||e==="environment")s.facingMode=e;else{let a;(this.kind==="audio"?yield It():yield At()).find(l=>l.deviceId===e)&&(a=e),s.deviceId=a}return this.capture(s,t).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),S.emit(A.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(a=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${a.message}`),this.emit("5",a),S.emit(A.LOCAL_TRACK_RECAPTURE,{track:this,error:a})}).finally(()=>{t&&(r==null||r.stop())})})}getRecoverCaptureDeviceId(){return f(this,null,function*(){let e=this instanceof je;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let r=(Bn.get(t)||0)+1;if(Bn.set(t,r),r>=3&&this.enableAutoSwitchWhenRecapturing){let s=e?(yield At()).find(n=>!Bn.has(n.deviceId)):(yield It()).find(n=>!Bn.has(n.deviceId));s&&(this.log.warn(`${t} capture fail ${r} times, change new ${s.deviceId}`),t=s.deviceId)}}return t})}stopCapture(){var e;this.sourceTrack&&(this.sourceTrack.stop(),this.uninstallTrackEvent(this.sourceTrack)),this._inputTrack&&this.uninstallTrackEvent(this._inputTrack),(e=this.manager)==null||e.removeInput(this)}close(){super.close(),this.stopCapture()}};D([ye(j.INIT,"ready",{ignoreError:!0,sync:!0})],po.prototype,"setStateToReady",1),D([ir()],po.prototype,"capture",1),D([ye("ready","publish",{ignoreError:!0,success(){S.emit(A.LOCAL_TRACK_PUBLISHED,{track:this,room:this.room}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),this.log.info("published")},fail(e){var n;(n=this.room)==null||n.localTracks.delete(this);let t="error",r=e instanceof v?e:e.cause instanceof v?e.cause:e,s=!1;r instanceof v&&(r.message.includes("timeout")?t="timeout":r.code===I.API_CALL_ABORTED&&(s=!0,t="api-call")),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:t,error:r}),this.log[s?"info":"error"]("publish failed",r)}}),Rt(521714,!1)],po.prototype,"publish",1),D([Y(e=>function(){return f(this,null,function*(){let t=this.state==="publish"?"started":"starting";e.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:t,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)})}),ye([],"ready",{sync:!0})],po.prototype,"unpublish",1);var _i=po,Bn=new Map;S.on(A.SWITCH_DEVICE_SUCCESS,o=>{o.track.deviceId&&Bn.delete(o.track.deviceId)});var kt=class o extends _i{constructor(e){super(1,vd);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 Ue);c(this,"_output",new Ue);c(this,"codecPipeline",[]);c(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0});c(this,"mixedAudioReferenceMap",new Map);c(this,"isAudioContextLongSuspended",!1);c(this,"after3aSilenceStartTime",0);this.manager=e,this.pipeline=new ds(e),this.pipeline.source.pipeTo(this.player.pipeline.volumeMeter),this.pipeline.gain.pipeTo(this.earMonitorGainNode).pipeTo(this._output),this.pipeline.gain.pipeTo(this.player.pipeline.volumeMeterAfter3A),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this),S.on(A.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this)}get dbVolume(){return so.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}getInternalAudioLevelAfter3A(){if(this.pipeline.isProcessEnabled)return this.player.getInternalAudioLevelAfter3A()}updateAfter3aSilenceStartTime(e){T(e)||(e===0&&!this.after3aSilenceStartTime?this.after3aSilenceStartTime=V():e>0&&(this.after3aSilenceStartTime=0))}setInputMediaStreamTrack(e){return f(this,null,function*(){let t=this.trackSettings||{};y.addEnum({key:501701,value:t.channelCount||0,useUV:!1}),y.addEnum({key:501702,value:t.sampleRate||0,useUV:!1}),y.addEnum({key:502700,value:0});let{sampleRate:r,channelCount:s}=t;this._log.info(`local audio track input ${JSON.stringify({sampleRate:r,channelCount:s})}`),this.pipeline.source.channelCount=s||1,this.pipeline.replaceSource(e),yield Le(o.prototype,this,"setInputMediaStreamTrack").call(this,e),this.updatePlayingState(!!e)})}capture(a){return f(this,arguments,function*({deviceId:e,customSource:t,useExactDeviceId:r=!0,retryWhenExactFailed:s},n=!1){let d=yield Le(o.prototype,this,"capture").call(this,{video:!1,audio:!0,microphoneId:e,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:r,retryWhenExactFailed:s,customSource:t},n);return Nr(),d})}switchDevice(e){return f(this,null,function*(){if(this.mediaTrack){if(this.deviceId===e&&!this.isUseCustomSource)if(e===Wr){if(yield vu(this.groupId,this.label))return}else return;try{this.log.info(`switchDevice audio to: ${e}`),this.sourceTrack&&this.sourceTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0,retryWhenExactFailed:!1}),S.emit(A.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(t){throw this.log.error(`switch microphone failed ${t}`),this.deviceId&&this.recapture(this.deviceId),t}}})}listenDeviceChange(){be&&!be.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&be.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return f(this,null,function*(){if(e.deviceId===this.deviceId){let t=this.recaptureMode===1;if(this.log.warn(`RecaptureMode: ${ms[this.recaptureMode]}. Current microphone is lost: ${JSON.stringify(e)}`),this.recaptureMode===0){ve(this.userId,{eventId:2003,param1:6,streamType:1});let r=yield It();r[0]?this.recapture(r[0].deviceId):t=!0}t&&be.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.recaptureMode===1&&e.deviceId!==this.deviceId||(be.off("audioInputAdded",this.handleMicrophoneAdded,this),this.log.warn(`microphone added: ${JSON.stringify(e)}`),this.recapture(e.deviceId))}update3A(s){return f(this,arguments,function*({echoCancellation:e,noiseSuppression:t,autoGainControl:r}){let n=this.sourceTrack||this.mediaTrack;if(!n)return;let a=n.getConstraints(),d=!1;!T(e)&&e!==this.profile.echoCancellation&&(this.profile.echoCancellation=e,a.echoCancellation=e,d=!0),!T(t)&&t!==this.profile.noiseSuppression&&(this.profile.noiseSuppression=t,a.noiseSuppression=t,d=!0),!T(r)&&r!==this.profile.autoGainControl&&(this.profile.autoGainControl=r,a.autoGainControl=r,d=!0),d&&(ee||Re?yield n.applyConstraints(a).catch(l=>this._log.warn("update3A failed: ",l)):this.deviceId&&(yield this.recapture(this.deviceId,!0)))})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&y.addEnum({key:502700,value:2})}setAudioVolume(e){super.setAudioVolume(0),ge&&this.player.setMuted(!0),this.earMonitorGainNode.node||(this.earMonitorGainNode.setNode(Ee().createGain()),this._output.setNode(Ee().destination)),this.earMonitorGainNode.node.gain.value=e}enableTrackANS(e){return this.update3A({noiseSuppression:e})}enableTrackAEC(e){if(this.sourceTrack&&!(Re||ge))return this.update3A({echoCancellation:e})}addDenoiser(e){var t;if($e<=92&&((t=this.trackSettings)==null?void 0:t.sampleRate)!==48e3){this._log.warn("denoiser only support sampleRate 48000 before chrome 93");return}y.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.enableTrackANS(!1)}mixAudioReference(e,t){if(this.mixedAudioReferenceMap.has(t))return;this.log.info(`mixAudioReference() => ${t}`);let r=Mn(e);if(!r)return;let s=new Ue,n=Ee().createGain();n.gain.value=1;let a=new Ue;s.pipeTo(a).pipeTo(this.pipeline.mixNode),s.setNode(r),a.setNode(n),this.mixedAudioReferenceMap.set(t,[s,a])}unMixAudioReference(e){let[t,r]=this.mixedAudioReferenceMap.get(e)||[];t&&(this.log.info(`unMixAudioReference() => ${e}`),t.deleteNode(),r==null||r.deleteNode(),this.mixedAudioReferenceMap.delete(e))}setAudioReferenceVolume(e,t){let[r,s]=this.mixedAudioReferenceMap.get(e)||[];s!=null&&s.node&&(s.node.gain.value=t/100,this.log.info(`setAudioReferenceVolume() => ${e} ${s.node.gain.value}`))}addAudioProcessor(e,t,r){this.pipeline.silentNode.setNode(r),this.pipeline.mixNode.setNode(t),this.pipeline.aec.setNode(e)}removeDenoiser(e){if(this.pipeline.denoiser.node===e)return this.pipeline.denoiser.deleteNode(),this.enableTrackANS(!0)}removeAudioProcessor(e){this.pipeline.aec.node===e&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode())}close(){this.mixedAudioReferenceMap.forEach(([e,t])=>{e.deleteNode(),t.deleteNode()}),this.mixedAudioReferenceMap.clear(),this.pipeline.remove(),this.earMonitorGainNode.deleteNode(),this._output.deleteNode(),be.off("audioInputAdded",this.handleMicrophoneAdded,this),be.off("audioInputRemoved",this.handleMicrophoneRemoved,this),S.off(A.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this),super.close()}recapture(e,t=!1){return f(this,null,function*(){try{yield Le(o.prototype,this,"recapture").call(this,e,t)}catch(r){let s=(yield It()).find(n=>n.deviceId!==e);if(s)yield Le(o.prototype,this,"recapture").call(this,s.deviceId);else throw r}})}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduceRight((t,r)=>r?r({frame:t,ntp:Hi()}):t,e):e}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}get enableEncryptFrame(){return this.manager&&!!this.manager.encodePipeline[0]}handleAudioContextLongSuspended({isSuspended:e}){if(this.pipeline.isProcessEnabled)if(e){this.isAudioContextLongSuspended=!0,this.log.warn(`context has suspended for ${yu/1e3} seconds, change to source audio${Ft?"":", non-Safari"}`);let t=this.sourceTrack||this.mediaTrack;t&&this.setOutputMediaStreamTrack(t)}else this.isAudioContextLongSuspended=!1,this.log.warn("context has resumed, change to processed audio"),this.pipeline.track&&this.setOutputMediaStreamTrack(this.pipeline.track)}setOutputMediaStreamTrack(e){if(this.isAudioContextLongSuspended){let t=this.sourceTrack||this.mediaTrack;t&&(e=t)}super.setOutputMediaStreamTrack(e)}};var sr=class{constructor(i,e=!1){this.dataView=i;this.isSEI&&(e?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let i=this.seiPayloadStartIndex,e=this.dataView.byteLength-2,t=[],r=0;for(let n=i;n<=e;n++){let a=this.dataView.getInt8(n);switch(a){case 0:case 1:case 2:case 3:r===2&&(t.push(3),r=0),a==0?r++:r=0,t.push(a);break;default:r=0,t.push(a);break}}t.push(this.dataView.getInt8(this.dataView.byteLength-1));let s=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=s}removePreventionByte(){let i=this.seiPayloadStartIndex,e=this.dataView.byteLength-1,t=[],r=0;for(let n=i;n<=e;n++)switch(this.dataView.getInt8(n)){case 0:r++,t.push(this.dataView.getInt8(n));break;case 3:r!==2&&t.push(this.dataView.getInt8(n)),r=0;break;default:t.push(this.dataView.getInt8(n)),r=0;break}let s=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=s}get isSEI(){return this.dataView.getUint8(4)===6}get seiPayloadStartIndex(){let i=6;for(let e=6;e<this.dataView.buffer.byteLength&&(i++,this.dataView.getUint8(e)===255);e++);return i}get seiPayloadType(){return this.isSEI?this.dataView.getUint8(5):null}get seiPayload(){if(!this.isSEI)return null;let i=0,e=6;for(let s=6;s<this.dataView.buffer.byteLength;s++){let n=this.dataView.getUint8(s);if(e++,n===255)i+=255;else{i+=n;break}}let t=new ArrayBuffer(i),r=new DataView(t);for(let s=0;s<t.byteLength;s++,e++)r.setInt8(s,this.dataView.getInt8(e));return r}};var zd=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,s=[];s.push(0,0,0,1,6,this._seiPayloadType);for(let a=0;a<t;a++)s.push(255);s.push(r);let n=new DataView(i);return s.push(...new Uint8Array(n.buffer)),s.push(128),new sr(new DataView(new Uint8Array(s).buffer),!0)}sendSEI(i,e){e!=null&&e.seiPayloadType&&(this._seiPayloadType=e.seiPayloadType),this._seiMessageList.push(i),e!=null&&e.small&&this._smallSeiMessageList.push(i)}isEmpty(){return!this._seiMessageList.length}getNaluCount(i){let e=0,t=0,r=new DataView(i);for(let s=0;s<i.byteLength;s++)switch(r.getUint8(s)){case 0:e++;break;case 1:(e===2||e===3)&&t++,e=0;break;default:e=0;break}return t}encode(i,e){let t=e?this._smallSeiMessageList:this._seiMessageList;if(t.length>0&&i.data.byteLength>0){let s=9-this.getNaluCount(i.data);if(s<=0)return 0;let n=t.splice(0,s).reverse().map(this.encodeSEINalu.bind(this)),a=n.reduce((p,m)=>p+m.dataView.byteLength,0),d=new ArrayBuffer(a+i.data.byteLength),l=new DataView(d),u=new DataView(i.data),h=0;for(let p=0;p<n.length;p++)for(let m=0;m<n[p].dataView.byteLength;m++)l.setInt8(h++,n[p].dataView.getInt8(m));for(let p=0;p<i.data.byteLength;p++)l.setInt8(h++,u.getInt8(p));return i.data=d,n.length}return 0}};var Or=class Or extends _i{constructor(e,t=4){super(t,pt);c(this,"profile",M({},pr));c(this,"avoidCropping",!1);c(this,"_scaleResolutionDownBy");c(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0,framesCaptured:0});c(this,"small");c(this,"isNeedToSetBandwidth");c(this,"muteImage");c(this,"manager");c(this,"_seiCodec",new zd);this.manager=e;let r=()=>{var s;if(this.isAllowed2k4k(this.profile))this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1});else{let n=Ut(((s=this.room)==null?void 0:s.sdkAppId)||0)?ua:la;this.log.warn(`Resolution is reset to 1080p, need to upgrade ability here ${n}`),this.setProfile(w(M({},this.profile),{width:1920,height:1080})),this.applyProfile()}};this.on("input-media-track-changed",r),this.on("publish",r),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(!(!Ni||!this.mediaTrack))return this.mediaTrack.getSettings().facingMode}get contentHint(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)||""}get isQosClearFirst(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)==="detail"}get hasSmall(){var e;return!!((e=this.manager)!=null&&e.hasSmall)}setMute(e){return f(this,null,function*(){var t,r,s;if(ie(e)){if(this.muteImage===e)return;yield(t=this.manager)==null?void 0:t.deleteWatermark("mute"),yield(r=this.manager)==null?void 0:r.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:e,fillVideo:!0}),this.muteImage=e,Le(Or.prototype,this,"setMute").call(this,!1)}else this.muteImage&&(yield(s=this.manager)==null?void 0:s.deleteWatermark("mute"),this.muteImage=void 0),Le(Or.prototype,this,"setMute").call(this,e)})}capture(a){return f(this,arguments,function*({deviceId:e,facingMode:t,useExactDeviceId:r=!0,customSource:s,retryWhenExactFailed:n=!0}){let d={audio:!1,video:!0,facingMode:t||this.facingMode,cameraId:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:r,retryWhenExactFailed:n,customSource:s};if(d.facingMode==="environment"){let l=yield this.getDeviceIdWhenUsingBackCamera();l&&(d.cameraId=l)}return Le(Or.prototype,this,"capture").call(this,d)})}setProfile(e){var r;let t=this.fallbackProfile(e);if(t.bitrate&&(this.isNeedToSetBandwidth=t.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile))super.setProfile(t);else{let s=Ut(((r=this.room)==null?void 0:r.sdkAppId)||0)?ua:la;this.log.warn(`Resolution is reset to 1080p, need to upgrade ability here ${s}`),super.setProfile(w(M({},this.profile),{width:1920,height:1080}))}}applyProfile(){return f(this,null,function*(){var a;if(!this.mediaTrack)return;let{width:e=0,height:t=0}=(this.sourceTrack||this.mediaTrack).getSettings(),r=e*t,s=this.settings,n=s.height!==this.profile.height||s.width!==this.profile.width||s.frameRate!==this.profile.frameRate;if(n&&(et===16&&this.deviceId?yield this.recapture(this.deviceId):(yield(a=this.sourceTrack||this.mediaTrack)==null?void 0:a.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}),this.manager&&this.manager.changeInput(this)),this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1})),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth){this.isNeedToSetBandwidth=!1;let{width:d=0,height:l=0}=(this.sourceTrack||this.mediaTrack).getSettings(),u=d*l;if(n&&u&&r&&u===r){this.log.warn("set bandwidth failed: resolution is not changed");return}return this.room.setBandWidth({bandwidth:this.profile.bitrate,type:_.VIDEO,videoType:_.BIG})}})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},t=this.sourceTrack||this.mediaTrack;return Ni&&t&&Object.assign(e,t.getSettings()),e}get scaleResolutionDownBy(){return this._scaleResolutionDownBy?this._scaleResolutionDownBy:Ho(this.settings,this.profile)}isAllowed2k4k(e){var t;return!this.room||!this.room.scheduleResult||this.isScreen||e.height*e.width<2560*1440?!0:((t=this.room.scheduleResult.trtcAutoConf)==null?void 0:t["2k4k"])===1}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}switchDevice(e){return f(this,null,function*(){try{if(!this.isNeedToSwitchDevice(e)&&!this.isUseCustomSource)return;let t={useExactDeviceId:!0,retryWhenExactFailed:!1};e==="user"||e==="environment"?t.facingMode=e:t.deviceId=e,this.sourceTrack&&this.sourceTrack.stop(),yield this.capture(t),S.emit(A.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(t){throw this.log.error(`switch camera failed ${t}`),this.deviceId&&this.recapture(this.deviceId),t}})}getDeviceIdWhenUsingBackCamera(){return f(this,null,function*(){let e;try{if(tn&&!Qo&&au){let r=(yield At(!0)).map(n=>{var a;return w(M({},n),{capabilities:(a=n.getCapabilities)==null?void 0:a.call(n)})}).filter(n=>{var a,d;return(d=(a=n.capabilities)==null?void 0:a.facingMode)==null?void 0:d.includes("environment")}),s=r[0];r.forEach(n=>{var u,h,p,m;let{capabilities:a}=n,d=(u=a.width)!=null&&u.max&&((h=a.height)!=null&&h.max)?a.width.max*a.height.max:0,l=(p=s.capabilities.width)!=null&&p.max&&((m=s.capabilities.height)!=null&&m.max)?s.capabilities.width.max*s.capabilities.height.max:0;d>l&&(s=n)}),s!=null&&s.capabilities&&(this._log.info("use max resolution back camera",s),e=s.deviceId)}}catch(t){this._log.warn("get max res camera failed",t)}return e})}updateSmallConfig(e){return f(this,null,function*(){var r,s;this._log.info(`update small stream config: ${JSON.stringify(e)}`);let t=!this.small;this.small=this.fallbackProfile(e,!0),yield(r=this.manager)==null?void 0:r.update(),t&&(yield(s=this.room)==null?void 0:s.enableSmall(!0)),this.log.info("update small stream config success")})}fallbackProfile(e,t=!1){let r=e.width>e.height,s=M({},e);return e.width*e.height<=160*120&&_e&&Ve&&(this.log.warn(`${t?"small ":""}resolution is ${e.width}*${e.height}, fallback to 240*180 for android chrome`),s.width=r?240:180,s.height=r?180:240,s.bitrate=Math.max(e.bitrate,150)),e.width*e.height>1280*720&&vl&&(s.width=r?1280:720,s.height=r?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),sn(ht,"14.3")&&bl(ht,"14.0",!0)&&this.on("7",()=>{let n=this.profile.width>this.profile.height;this.profile.width*this.profile.height>640*480?(this.profile.width=n?640:480,this.profile.height=n?480:640,this.log.warn("reduce the resolution to 480p on iOS 14.0 ~ 14.2")):this.profile.width*this.profile.height>640*360&&(this.profile.width=n?640:360,this.profile.height=n?360:640,this.log.warn("reduce the resolution to 360p on iOS 14.0 ~ 14.2"))}),!t&&this.avoidCropping&&(Ve||ee)&&!nn()&&e.width*e.height<=640*360&&e.width/e.height===16/9&&(this._scaleResolutionDownBy=1280/e.width,e.width=1280,e.height=720,this.log.warn(`capture 720p, scale: ${this._scaleResolutionDownBy}`)),s}stopSmall(){var e,t;this.small&&(delete this.small,(e=this.manager)==null||e.update(),(t=this.room)==null||t.enableSmall(!1))}listenDeviceChange(){be&&!be.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&be.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return f(this,null,function*(){if(e.deviceId===this.deviceId){let t=this.recaptureMode===1;if(this.log.warn(`RecaptureMode: ${ms[this.recaptureMode]}. Current camera is lost: ${JSON.stringify(e)}`),this.recaptureMode===0){ve(this.userId,{eventId:2003,param1:7,streamType:2});let r=yield At();r[0]?this.recapture(r[0].deviceId):t=!0}t&&be.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return f(this,null,function*(){this.recaptureMode===1&&e.deviceId!==this.deviceId||(be.off("videoInputAdded",this.handleCameraAdded,this),this.log.warn(`camera added: ${JSON.stringify(e)}`),this.recapture(e.deviceId))})}encodeFrame(e,t){if(!this.manager)return e;let r=t?8:this.mediaType;return this.manager.encodePipeline.reduceRight((s,n)=>n?n({frame:s,mediaType:r}):s,e)}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}play(e,t){return T(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,t)}close(){be.off("videoInputAdded",this.handleCameraAdded,this),be.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return f(this,null,function*(){try{yield Le(Or.prototype,this,"recapture").call(this,e)}catch(t){let r=(yield At()).find(s=>s.deviceId!==e);if(r)yield Le(Or.prototype,this,"recapture").call(this,r.deviceId);else throw t}})}setContentHint(e){this.mediaTrack&&"contentHint"in this.mediaTrack&&(this.mediaTrack.contentHint!==e&&(this.log.info(`setContentHint ${e}`),this.mediaTrack.contentHint=e),this.outMediaTrack&&this.outMediaTrack.contentHint!==e&&(this.outMediaTrack.contentHint=e))}setRotation(e){this.manager&&(this.isScreen||T(e)||e!==this.rotation&&(this.rotation=e,this.manager.rotation=e))}};D([Ct(function(e){this.setContentHint(e.contentHint||"motion")})],Or.prototype,"capture",1);var je=Or;var gh={};Bi(gh,{REPORT_TYPE:()=>$o,buildSSOPackage:()=>qi,bytes2ms:()=>bm,calculateScaleResolutionDownNumber:()=>Ho,concatArrayBuffers:()=>Oa,convertObjectNumberToInt:()=>Js,copyProperties:()=>ym,deepClone:()=>Gr,deepCloneBasic:()=>Ra,deepMerge:()=>ei,delay:()=>Ke,fibonacci:()=>qr,formatedTime:()=>xm,getConstructorName:()=>wo,getContainerFromElement:()=>Lm,getEnv:()=>Am,getFirst16Bits:()=>Um,getInternalVersion:()=>km,getLast16Bits:()=>ka,getLoggerUrl:()=>Ji,getMediaStreamTrackInfo:()=>Ma,getMuteStateFromFlag:()=>Kt,getNetworkType:()=>ya,getNumNetworkType:()=>Jr,getReconnectionTimeout:()=>Zt,getStringByteLength:()=>Gs,getTurnServer:()=>Pm,getUint32Version:()=>Na,getValueType:()=>Me,getViewListFromView:()=>Fo,glog:()=>pl,ipv4ToUint32:()=>Vo,isArray:()=>Ae,isAudioWorkletSupported:()=>Mm,isBoolean:()=>ue,isConstructor:()=>jr,isEmpty:()=>Uo,isFunction:()=>le,isLangChinese:()=>Yt,isMediaStreamTrack:()=>vm,isNumber:()=>Q,isObject:()=>yt,isOverseaSdkAppId:()=>Ut,isPlainObject:()=>dt,isPortrait:()=>fl,isPromise:()=>Tr,isRemoteTrack:()=>Dm,isRotate90Or270:()=>bt,isSetSinkIdSupported:()=>Om,isString:()=>ie,isUndefined:()=>T,loadImage:()=>Bo,loadVideo:()=>wm,ms2bytes:()=>Nm,ms2samples:()=>ml,normalizeUrl:()=>Da,performanceNow:()=>V,promiseAny:()=>Xr,samples2ms:()=>hl,setNetworkTypeFromWebRTC:()=>ba,stringify:()=>gt,stringifyIncludeValue:()=>Ws,throttlePromise:()=>va});var lS=[-1,-1,1,-1,-1,1,1,1],uS=[0,0,1,0,0,1,1,1];var kr=class kr extends j{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 Xe){e.ctx&&t.create2d&&(typeof OffscreenCanvas=="function"&&et!==16?this._canvas=new OffscreenCanvas(this.width,this.height):(this._canvas=document.createElement("canvas"),this._canvas.width=this.width,this._canvas.height=this.height),this.ctx2d=this._canvas.getContext("2d"),this._image=this._canvas);return}try{let r=e.ctx;this.texCoordBuffer=this.createBuffer(uS),this.positionBuffer=this.createBuffer(lS),t.createTexture!==!1&&(this.texture=r.createTexture(),this.useTexture(),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.pixelStorei(r.UNPACK_ALIGNMENT,1)),t.useFbo&&(this.fbo=r.createFramebuffer(),this.useBufferFrame(),this.useTexture(),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,this.width,this.height,0,r.RGBA,r.UNSIGNED_BYTE,null),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,this.texture,0)),t.useDefaultProgram?this.program=e.defaultProgam:(t.vertexShaderSource||t.fragmentShaderSource)&&(this.vertexShader=t.vertexShaderSource?e.createShader(r.VERTEX_SHADER,t.vertexShaderSource):e.defaultVShader,this.fragmentShader=t.fragmentShaderSource?e.createShader(r.FRAGMENT_SHADER,t.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(r){this.context.destroy(new v({code:I.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${r.message||r}`}))}}get image(){return this._image}set image(e){this._image=e}createFramebuffer(e){let t=this.context.ctx,r=t.createFramebuffer();return t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0),r}connect(e,...t){return e.addInput(this,...t),this.output=e,e}addInput(e,...t){this.input=e,this.matchInputSize&&e.width&&e.height&&this.resize(e.width,e.height)}requestFrame(e){let t=Date.now();if(this.context instanceof Be&&this.render(e)||this.context instanceof Xe&&this.render2d(e))this.totalFrames++;else return!1;return this.cost=Date.now()-t,!0}render2d(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?this.draw2d(this.input.image,0,0,this.width,this.height):!1}update(e=0){var t;(t=this.output)==null||t.update(e)}disconnect(...e){var t;(t=this.output)==null||t.removeInput(this,...e),delete this.output}removeInput(e,...t){delete this.input}close(){var e,t;if(this.context.off("disconnect",this.close,this),(e=this.output)==null||e.removeInput(this),delete this.output,(t=this.input)==null||t.disconnect(),this.context instanceof Be){let r=this.context.ctx;r.deleteBuffer(this.texCoordBuffer),r.deleteBuffer(this.positionBuffer),this.fbo&&r.deleteFramebuffer(this.fbo),this.texture&&r.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&r.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&r.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&r.deleteProgram(this.program)}this._canvas&&(this._canvas.width=0,this._canvas.height=0,this.ctx2d=null),this.removeAllListeners()}useTexture(){this.useTextures(this.texture)}useInputTexture(){var e;this.useTextures((e=this.input)==null?void 0:e.texture)}useTextures(...e){let t=this.context.ctx;e.forEach((r,s)=>{r&&(t.activeTexture(t.TEXTURE0+s),t.bindTexture(t.TEXTURE_2D,r))})}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}createBuffer(e){let t=this.context.ctx,r=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,r),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW),r}setTexBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}setPosBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}changeBufferData(e,t){let r=this.context.ctx;r.bindBuffer(r.ARRAY_BUFFER,e),r.bufferData(r.ARRAY_BUFFER,new Float32Array(t),r.STATIC_DRAW)}setAttributes(...e){let t=this.context.ctx;e.forEach((r,s)=>{t.enableVertexAttribArray(s),t.bindBuffer(t.ARRAY_BUFFER,r),t.vertexAttribPointer(s,2,t.FLOAT,!1,0,0)})}getVertexPoint(e,t){return[e/this.width*2-1,t/this.height*2-1]}layout2texCoords(e){return[...this.getVertexPoint(e.x,e.y),...this.getVertexPoint(e.x+e.width,e.y),...this.getVertexPoint(e.x,e.y+e.height),...this.getVertexPoint(e.x+e.width,e.y+e.height)]}resize(e,t){if(!(this.width===e&&this.height===t)){if(this.width=e,this.height=t,this._canvas&&(this._canvas.width=e,this._canvas.height=t),this.texture&&this.fbo){this.useTexture();let r=this.context.ctx;r.texImage2D(r.TEXTURE_2D,0,r.RGBA,e,t,0,r.RGBA,r.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(e,t)}}draw(e,t){this.setAttributes(e||this.positionBuffer,t||this.texCoordBuffer);let r=this.context.ctx;r.drawArrays(r.TRIANGLE_STRIP,0,4)}draw2d(e,t,r,s,n,a,d,l,u){let h=!T(a)&&!T(d)&&!T(l)&&!T(u);return this.ctx2d&&e?(e instanceof ImageData?(h?this.ctx2d.putImageData(e,t,r,a,d,l,u):this.ctx2d.putImageData(e,t,r),this.emit(kr.RENDER,this.ctx2d.canvas)):(h?this.ctx2d.drawImage(e,a,d,l,u,t,r,s,n):this.ctx2d.drawImage(e,t,r,s,n),this.emit(kr.RENDER,e)),typeof VideoFrame!="undefined"&&e instanceof VideoFrame&&e.close(),!0):!1}drawBackGround2d(e){this.ctx2d&&(this.ctx2d.save(),this.ctx2d.fillStyle=e,this.ctx2d.fillRect(0,0,this.width,this.height),this.ctx2d.restore())}getInfo(){var h;let{totalFrames:e,x:t,y:r,width:s,height:n,name:a,cost:d}=this,l=Date.now(),u=(e-this.lastInfo.totalFrames)/((l-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:r,width:s,height:n,timestamp:l,fps:u,name:a,cost:d},M({parent:(h=this.input)==null?void 0:h.getInfo()},this.lastInfo)}createTexture(e){let t=this.context.ctx,r=t.createTexture();return this.useTextures(r),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.pixelStorei(t.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),r}};c(kr,"RENDER","render"),D([ye(j.INIT,"connected",{sync:!0})],kr.prototype,"connect",1),D([ye("connected",j.INIT,{ignoreError:!0,sync:!0})],kr.prototype,"disconnect",1),D([ye([],"closed",{sync:!0})],kr.prototype,"close",1);var Pe=kr;var hS=ce(wu(250),Vn(()=>performance.now()),rr());var hf=o=>i=>{let e=performance.now();ce(hS,Hd(t=>t-e<o),or(1))(i)};var pS=[0,1,1,1,0,0,1,0],fo=class extends Pe{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 Xe?this.ctx2d=e.ctx||null:e.available&&(t!=null&&t.mirrorUpAndDown)&&this.setTexBuffer(pS)}start(e){this.log.info(`${this.name} start render ${e} fps`),oe.clearTask(this._intervalId),this._intervalId=oe.run("intervalInWorker",()=>{if(e!==this.context.frameRate&&(oe.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof Be){let r=this.context.ctx.getError();r&&this.context.destroy(new v({code:I.VIDEO_MANAGER_ERROR,extraCode:5,message:`${this.name} req ${this._sequence} render ${this.totalFrames} faild ${r}`}))}},{fps:this.context.frameRate})}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),this.emit(Pe.RENDER,this.context._canvas),!0):!1}addInput(e,...t){super.addInput(e,...t),this.start(this.context.frameRate)}update(e=0){this.state!=="closed"&&(this._intervalId&&(oe.clearTask(this._intervalId),this._intervalId=0,e===1&&(this.log.info(`${this.name} use requestVideoFrameCallback`),this.checkVisibilityChange=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info(`${this.name} use timer`),document.removeEventListener("visibilitychange",this.checkVisibilityChange))},document.addEventListener("visibilitychange",this.checkVisibilityChange))),this.requestFrame(this._sequence++))}removeInput(e){super.removeInput(e),oe.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}close(){super.close(),oe.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},ps=class extends fo{constructor(e,t){super(e,t);c(this,"_videoTrack");c(this,"_muteOb");c(this,"_closedOb",de(this,"closed"));c(this,"_subscription");c(this,"_canvasContainer");Number(Xi)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e.canvas.captureStream().getVideoTracks(),this._muteOb=de(this._videoTrack,"mute"),ce(de(this._videoTrack,"ended"),ke(this._closedOb),Te(()=>{this.context.destroy(new v({code:I.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){this._subscription=ce(this._muteOb,ke(this._closedOb),mo(hf(5e3)),$t(()=>{var e;return!!((e=this._videoTrack)!=null&&e.muted)&&!document.hidden}),Te(()=>{this.context.destroy(new v({code:I.VIDEO_MANAGER_ERROR,extraCode:7,message:"video track muted"}))}))}disableCheckMute(){var e;(e=this._subscription)==null||e.dispose()}get videoTrack(){return this._videoTrack}putCanvasIntoDom(){!this.context._canvas||!this._canvasContainer||document.getElementById(this.context._canvas.id)||(this.log.info(`${this.name} put canvas to body`),document.body.appendChild(this._canvasContainer),this._canvasContainer.appendChild(this.context._canvas))}render(e){return this.putCanvasIntoDom(),super.render(e)}render2d(e){return this.putCanvasIntoDom(),super.render2d(e)}close(){var e,t;super.close(),(e=this._videoTrack)==null||e.stop(),delete this._videoTrack,(t=this._canvasContainer)==null||t.remove()}},Qd=class extends ps{render(i){var t;let e=!!((t=this.input)!=null&&t.requestFrame(i));if(this.context._canvas2d){let r=this.context._canvas2d.getContext("2d");r.clearRect(0,0,this.context._canvas2d.width,this.context._canvas2d.height),r.drawImage(this.context._canvas,0,0,this.context._canvas2d.width,this.context._canvas2d.height),this.emit(Pe.RENDER,this.context._canvas2d)}else this.emit(Pe.RENDER,this.context._canvas);return e}};var Yd=class extends ps{constructor(e,t,r){super(e,{name:"smallDestination",logger:r});this.resolution=t}resize(e,t){let r,s=e*t,n=this.resolution.width*this.resolution.height;this.log.info(`big res: ${e}*${t} small res: ${this.resolution.width}*${this.resolution.height} `),s>n?r=s/n:(this.log.warn(`Small stream resolution is not smaller than big stream, which is invalid. big: ${e} * ${t} small: ${this.resolution.width} * ${this.resolution.height}`),r=s/(160*120)),super.resize(e/Math.sqrt(r),t/Math.sqrt(r))}};var Hn=class extends Pe{constructor(e,t){super(e,M({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);c(this,"shouldUpdate",!0);this._autoResize=(t==null?void 0:t.autoResize)!==!1,et===16&&(this._canvasRendered=rt(),ce(this._canvasRendered,xn(this._image),Mr(r=>r instanceof HTMLCanvasElement?de(r,"rendered"):Un()),ke(de(this,"closed")),Te(()=>{this.update()})))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){if(!this.shouldUpdate)return;let e=this.image;this.videoCallbackId&&e.cancelVideoFrameCallback(this.videoCallbackId),Ki()&&!document.hidden&&(this.videoCallbackId=e.requestVideoFrameCallback((t,r)=>{this.waitingFirstFrame&&this.onFirstFrame(),document.hidden||(this._totalFrames=r.presentedFrames,this.update(1))}))}_render(e,t){var a;let{width:r,height:s}=this,{image:n}=this;if(n instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(),{videoWidth:r,videoHeight:s}=n,!r||!s)return!1;n.width=r,n.height=s}else if(n instanceof HTMLImageElement||n instanceof ImageData||n instanceof ImageBitmap){if({width:r,height:s}=n,n!==this._lastImage)this._lastImage=n;else if(r===this.width&&s===this.height)return!0}else n instanceof HTMLCanvasElement||n instanceof OffscreenCanvas?({width:r,height:s}=n,this._lastImage=n):typeof VideoFrame!="undefined"&&n instanceof VideoFrame&&({displayWidth:r,displayHeight:s}=n,(a=this._lastImage)==null||a.close(),this._lastImage=n);if(!this._autoResize)return!0;if(this.width===r&&this.height===s&&this.totalFrames){if(t){this.useTexture();let 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,s)}return!0}get image(){return this._image}set image(e){var t;(t=this._canvasRendered)==null||t.next(e),this._image=e}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},$n=class extends Hn{constructor(e,t,r){super(e,r);this._player=t;this.name="videoPlayerSource",ce(de(this._player,he.PLAYER_STATE_CHANGED),ke(de(this,"closed")),$t(({state:s})=>s==="PLAYING"),Te(()=>{this.tryVideoFrameCallback()}))}get image(){return this._player.element}},Wt=class extends $n{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()}},Zd=class extends Pe{constructor(e,t,r){super(e,w(M({name:"textSource"},r),{create2d:!0}));c(this,"hasChange",!0);c(this,"content","");this.ctx2d.textBaseline="top",this.content=t.content||"",t.font&&(this.font=t.font),t.color&&(this.color=t.color)}set font(e){this.ctx2d&&(this.ctx2d.font=e,this.hasChange=!0)}get font(){var e;return((e=this.ctx2d)==null?void 0:e.font)||""}set color(e){this.ctx2d&&(this.ctx2d.fillStyle=e,this.hasChange=!0)}get color(){var e;return((e=this.ctx2d)==null?void 0:e.fillStyle)||""}render2d(e){return this.ctx2d&&this.hasChange?(this.ctx2d.clearRect(0,0,this.width,this.height),this.drawMultilineText(0,0),this.hasChange=!1,!0):!1}render(e){return!1}resize(e,t){if(!this.ctx2d)return;let{color:r,font:s}=this;super.resize(e,t),this.color=r,this.font=s}drawMultilineText(e=0,t=0,r=1.2){if(!this.ctx2d)return;let s=this.ctx2d.measureText(this.content);t+=s.fontBoundingBoxAscent||s.actualBoundingBoxAscent||0;let n=this.font.match(/(\d+)px/),d=(n?parseInt(n[1],10):16)*r,l=this.content.split(`
34
- `);for(let u=0;u<l.length;u++)this.ctx2d.fillText(l[u],e,t+u*d)}};var _S=`
33
+ `,t.onclick=this.onQuestionClick.bind(this);let r=document.createElement("div");r.className=bu,r.innerText=`${Zt()?"\u8BE6\u60C5 >":"Detail >"}`,r.onclick=this.onCollapseClick.bind(this);let s=i.content.firstChild,n=s.querySelector(`.${vc}`);return n.appendChild(r),n.appendChild(t),n.appendChild(e),s}addDiaLog(){vr()||(vu=!0,this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${Dn}`).onclick=i=>i.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",R.info("show autoplay dialog"),ne.uploadEvent({log:jT}))}deleteDialog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null,vu=!1)}onConfirm(){R.warn("confirm clicked, try resume stream"),S.emit(C.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDialog()}onCollapseClick(){let i=this._dialogNode.querySelector(`.${Gp}`);i.style.visibility=`${this._showDetail?"hidden":"visible"}`,i.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||ne.uploadEvent({log:XT}),this._isCollapseClicked=!0}onQuestionClick(){window.open(jp,"_blank"),this._isQuestionClicked||ne.uploadEvent({log:zT}),this._isQuestionClicked=!0}},Mn=null;function cs(){Mn||(Mn=new Nu)}function Xp(){Mn&&(Mn.deleteDialog(),Mn=null)}var it=class o extends pi{constructor(e){super(e,p.VIDEO);d(this,"stat",{});d(this,"_calculateTimeout",-1);d(this,"viewMirror",!1);d(this,"objectFit","cover");d(this,"container");d(this,"canvas");d(this,"shouldRenderAlpha",!1);d(this,"_preSize",{width:0,height:0});d(this,"posterImg");d(this,"_originContainerPosition");this.mode=e.canvas?1:0,this.container=e.container,this.canvas=e.canvas,T(e.viewMirror)||(this.viewMirror=e.viewMirror),T(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}get isPlaying(){var e;return this._state!=="PLAYING"||this.element&&this.element.paused?!1:((e=this.track)==null?void 0:e.readyState)==="live"&&!this.track.muted}initializeElement(){var t;let e=document.createElement(p.VIDEO);this.track&&this.mode!==2&&(e.srcObject=new MediaStream([this.track])),e.muted=!0,e.setAttribute("id",`video_${this.id}`),e.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),e.setAttribute("autoplay","autoplay"),e.setAttribute("playsinline","playsinline"),this.element=e,fe&&(e.poster="noposter"),(t=this.container)==null||t.appendChild(this.elementToRender),this.bindElementEvents(),this.calculateStat()}get styleAttribute(){let e=`width:100%;height:100%;object-fit:${this.objectFit};${this.shouldRenderAlpha?"":"background-color:black"};`;return this.viewMirror&&(e+="transform:scaleX(-1);"),e}setContainer(e){var t;this.container=e,this.track&&this.elementToRender&&((t=this.container)==null||t.appendChild(this.elementToRender))}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),e&&e.add(p.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(p.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent).add(p.RESIZE,this.handleElementEvent)}handleTrackEvent(e){var t;return e.type===p.MUTE&&((t=this.stat)!=null&&t.fps)&&(this.stat.fps=0),super.handleTrackEvent(e)}handleElementEvent(e){var s,n,a,c,l,h;if(this.mode===2)return;super.handleElementEvent(e);let t=e.type,r=this.isPictureInPicture()&&e.isTrusted&&Ce;if(t===p.PLAYING&&r&&(this._log.warn("user resume in pip"),this.emit(K.USER_RESUME_IN_PIP)),t===p.PAUSE&&(r&&(this._log.warn("user pause in pip"),this.emit(K.USER_PAUSE_IN_PIP)),this.container&&!this.container.isConnected&&(this._log.warn(`${this.kind} player has been remove, element ID: ${this.container.id}`),Ge(500).then(()=>{var m;(m=this.container)!=null&&m.isConnected&&(this._pausedRetryCount=Tr,this._log.info(`view container ${this.container.id} is in dom, reset pausedRetryCount`))})),this._pausedRetryCount>0&&!vr()&&!this.isPausedByUserCall&&!r&&(this._log.info(`[${Tr-this._pausedRetryCount+1}/${Tr}] ${this.kind} player auto resume when paused`),this.doResume(),this._pausedRetryCount--),Ee&&!r&&(this._interval=oe.run("timeout",()=>{this.element&&this._state==="PAUSED"&&!this.isPausedByUserCall&&this.doResume()},{delay:3e3})),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){let m=this.element.style.transform;t===p.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=m.replace("scaleX(-1)",""):t===p.LEAVE_PICTURE_IN_PICTURE&&!m.includes("scaleX")&&(this.element.style.transform=`${m} scaleX(-1)`)}t===p.RESIZE&&(this._preSize.height!==((s=this.element)==null?void 0:s.videoHeight)||this._preSize.width!==((n=this.element)==null?void 0:n.videoWidth))&&(this._log.info(`video size changed to ${(a=this.element)==null?void 0:a.videoWidth}x${(c=this.element)==null?void 0:c.videoHeight}`),this._preSize.height=((l=this.element)==null?void 0:l.videoHeight)||0,this._preSize.width=((h=this.element)==null?void 0:h.videoWidth)||0,this.emit(K.RESIZE,{newWidth:this._preSize.width,newHeight:this._preSize.height})),t===p.LEAVE_PICTURE_IN_PICTURE&&(this._log.warn("exit pip"),this.isPaused&&!this.isPausedByUserCall&&(this._log.warn("resume after exit pip"),this.doResume()),this.emit(K.LEAVE_PICTURE_IN_PICTURE)),t===p.ENTER_PICTURE_IN_PICTURE&&(this._log.warn("enter pip"),this.emit(K.ENTER_PICTURE_IN_PICTURE))}setCanvas(e,t=1){var r,s,n,a;this.canvas!==e&&((r=this.canvas)==null||r.remove(),e==null||e.setAttribute("style",this.styleAttribute),this.canvas=e,this.mode=e?t:0,this.mode===2&&this.setTrack(e.captureStream().getVideoTracks()[0]),e?((s=this.element)==null||s.remove(),(n=this.container)==null||n.appendChild(e)):this.element&&((a=this.container)==null||a.appendChild(this.element)))}setAttr(e){let t=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},e);t.style=Object.assign({width:"100%",height:"100%"},t.style),super.setAttr(t)}get mirror(){return this.viewMirror}setRect(e,t){this.elementToRender&&(this.elementToRender.style.width=`${e}px`,this.elementToRender.style.height=`${t}px`)}setViewMirror(e){this.elementToRender&&(this.elementToRender.style.transform=e?"scaleX(-1)":""),this.viewMirror=e}setObjectFit(e){this.elementToRender&&(this.elementToRender.style.objectFit=`${e}`),this.objectFit=e}setPoster(e,t=!1){return new Promise(r=>{if(!this.element||(this._log.info("setPoster",e.slice(0,10)),e===""?this.element.removeAttribute("poster"):this.element.poster=e,!(t&&(Ce||te))))return r();if(e==="")return this.removePosterImg(),r();if(this.posterImg)return r();let n=document.createElement("img");n.src=e;let c=window.getComputedStyle(this.element).objectFit||this.objectFit;n.style=`position:absolute;top:0;left:0;width:100%;height:100%;object-fit:${c};`,n.onload=()=>f(this,null,function*(){var l;try{n.decode&&(yield n.decode()),this.container&&window.getComputedStyle(this.container).position==="static"&&(this._originContainerPosition=this.container.style.position,this.container.style.position="relative"),this.posterImg=n,(l=this.container)==null||l.appendChild(n)}catch(h){this._log.warn("decode poster image error",h)}return r()}),n.onerror=()=>(this._log.warn("load poster image error"),r())})}removePosterImg(){this.posterImg&&(this.posterImg.remove(),URL.revokeObjectURL(this.posterImg.src),this.container&&!T(this._originContainerPosition)&&this.container.style.position==="relative"&&(this.container.style.position=this._originContainerPosition),delete this.posterImg)}get hasPoster(){var e;return!!this.posterImg||!!((e=this.element)!=null&&e.getAttribute("poster"))}pause(e=!0){return f(this,null,function*(){we(o.prototype,this,"pause").call(this),!this.isPictureInPicture()&&!this.hasPoster&&(We&&je>=128||e&&(te||Ce))&&(yield this.setPoster(this.getVideoFrame(),!0))})}resume(e=!1){return super.resume(e).then(()=>{var t;(this.posterImg||(t=this.element)!=null&&t.poster)&&this.setPoster("",!0)})}doResume(e=!1){return this.isPaused&&e&&this.element&&this.track&&We&&je>=128&&this.track.kind==="video"&&(this.element.srcObject=new MediaStream([this.track])),super.doResume()}stop(e=0){var t;this.isPictureInPicture()&&this.exitPictureInPicture().catch(r=>{}),this.isFullscreen()&&this.exitFullscreen().catch(r=>{}),super.stop(e),(t=this.canvas)==null||t.remove(),this.removePosterImg()}play(){return this.element?this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender):this.initializeElement(),this.mode===2?Promise.resolve():super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(K.MEDIA_TRACK_CHANGED,e),e!==null&&(this.bindTrackEvents(),this.element&&this.mode!==2&&(this.element.srcObject=new MediaStream([e]),this.element.remove()),this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender)))}getVideoFrame(){if(this.canvas)return this.canvas.toDataURL("image/png");if(!this.element)return"";let e=document.createElement("canvas");return e.width=this.element.videoWidth,e.height=this.element.videoHeight,e.getContext("2d").drawImage(this.element,0,0),e.toDataURL("image/png")}getElement(){return this.element}calculateStat(){try{if(Ki()&&this.element&&this._calculateTimeout<0){let e=0,t=null,r=(s,n)=>{this.stat.width=n.width,this.stat.height=n.height,t&&(this.stat.fps=Math.round((n.presentedFrames-t.presentedFrames)/(s-e)*1e3)),e=s,t=n,this._calculateTimeout=-1,this.element&&(this._calculateTimeout=setTimeout(()=>{var a;return(a=this.element)==null?void 0:a.requestVideoFrameCallback(r)},2e3))};this.element.requestVideoFrameCallback(r)}}catch(e){this._log.warn("init stat failed",e)}}enterFullscreen(){return f(this,null,function*(){let e=this.elementToRender;if(!e)throw this._log.warn("no element to render, cannot enter fullscreen"),new Error("No element available for fullscreen");try{if(e.requestFullscreen)yield e.requestFullscreen();else if(e.webkitRequestFullscreen)yield e.webkitRequestFullscreen();else if(e.webkitEnterFullscreen)yield e.webkitEnterFullscreen();else if(e.mozRequestFullScreen)yield e.mozRequestFullScreen();else if(e.msRequestFullscreen)yield e.msRequestFullscreen();else throw this._log.warn("fullscreen API not supported"),new Error("Fullscreen API not supported");this._log.info("entered fullscreen mode")}catch(t){throw this._log.error("failed to enter fullscreen:",t),t}})}exitFullscreen(){return f(this,null,function*(){try{if(document.exitFullscreen)yield document.exitFullscreen();else if(document.webkitExitFullscreen)yield document.webkitExitFullscreen();else if(document.mozCancelFullScreen)yield document.mozCancelFullScreen();else if(document.msExitFullscreen)yield document.msExitFullscreen();else throw this._log.warn("exit fullscreen API not supported"),new Error("Exit fullscreen API not supported");this._log.info("exited fullscreen mode")}catch(e){throw this._log.error("failed to exit fullscreen:",e),e}})}isFullscreen(){let e=this.elementToRender;return e?(document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement)===e:!1}toggleFullscreen(){return f(this,null,function*(){this.isFullscreen()?yield this.exitFullscreen():yield this.enterFullscreen()})}enterPictureInPicture(){return f(this,null,function*(){var e;try{if(!this.element)throw new Error("No video element available for pip");if(this.canvas&&this.mode!==1)throw new Error("pip is not supported for canvas-only mode");let{element:t}=this;if(t.requestPictureInPicture){this._log.info("requestPictureInPicture");let r=yield t.requestPictureInPicture();return this._log.info("entered pip mode"),this.elementToRender===this.canvas&&(this.canvas.remove(),(e=this.container)==null||e.appendChild(this.element)),r}if(t.webkitSetPresentationMode)return this._log.info("webkitSetPresentationMode"),yield t.webkitSetPresentationMode("picture-in-picture"),this._log.info("entered picture-in-picture mode (webkit)"),{};throw new Error("Picture-in-picture API not supported")}catch(t){throw this._log.error("failed to enter picture-in-picture:",t.name,t.message),t}})}exitPictureInPicture(){return f(this,null,function*(){var e,t;try{if(document.pictureInPictureElement&&document.exitPictureInPicture)yield document.exitPictureInPicture(),this.elementToRender===this.canvas&&((e=this.element)==null||e.remove(),this._pausedRetryCount=Tr,(t=this.container)==null||t.appendChild(this.canvas)),this._log.info("exited pip mode");else if(this.element&&this.element.webkitSetPresentationMode)yield this.element.webkitSetPresentationMode("inline"),this._log.info("exited picture-in-picture mode (webkit)");else throw this._log.warn("exit picture-in-picture API not supported or not in PiP mode"),new Error("Exit picture-in-picture API not supported or not in PiP mode")}catch(r){throw this._log.error("failed to exit picture-in-picture:",r),r}})}isPictureInPicture(){if(!this.element)return!1;let{element:e}=this;return document.pictureInPictureElement?document.pictureInPictureElement===e:e.webkitPresentationMode?e.webkitPresentationMode==="picture-in-picture":!1}togglePictureInPicture(){return f(this,null,function*(){this.isPictureInPicture()?yield this.exitPictureInPicture():yield this.enterPictureInPicture()})}};function tr(o,i){return f(this,null,function*(){if(!o.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield o.audioWorklet.addModule(i),R.info("worklet addModule success")}catch(e){throw R.info(`worklet addModule catch error. ${e.message}`),e}})}var On;typeof AudioContext!="undefined"?On=AudioContext:typeof webkitAudioContext!="undefined"?On=webkitAudioContext:typeof mozAudioContext!="undefined"&&(On=mozAudioContext);var Pu=1500,rt,zp=-1,Dc=0,kn=-1,ku=!1,Qp=0,Yp=-1,Zp=-1;Kp();function Kp(){try{if(rt)return;rt=new On({sampleRate:48e3}),rt.onstatechange=()=>{R.info(`context state: ${rt.state}${rt.state!=="running"?` visibilityState: ${document.visibilityState}`:""}`),ds()},clearTimeout(zp)}catch(o){R.error(`initAudioContext failed: ${o} typeof AudioContextClass: ${typeof On}`),zp=setTimeout(Kp,1e3)}}var ds=()=>{rt.state==="suspended"?(Dc=V(),YT(),Nr(),document.addEventListener("click",ds)):rt.state==="interrupted"?Nr():(Dc&&(v.addNumber({key:507800,value:V()-Dc,split:[0,500,1e3,1500,2e3,3e3,4e3,5e3,1e4,3e4],max:6e4}),Dc=0),ZT(),document.removeEventListener("visibilitychange",ds),document.removeEventListener("click",ds))},Mu=0,Ou=-1;function Nr(){return new Promise((o,i)=>{if(rt.state==="running")return o();Date.now()-Mu<1e3?(clearTimeout(Ou),Ou=setTimeout(()=>{Mu=Date.now(),rt.resume().then(o,i)},1e3)):(clearTimeout(Ou),Mu=Date.now(),rt.resume().then(o,i))}).catch(o=>{R.warn(`context resume failed: ${o}`),document.addEventListener("visibilitychange",ds)})}document.addEventListener("click",ds);function YT(){kn===-1&&(kn=setTimeout(()=>{rt.state==="suspended"&&(ku=!0,S.emit("155",{isSuspended:!0}))},Pu))}function ZT(){kn!==-1&&(clearTimeout(kn),kn=-1,ku&&(ku=!1,S.emit("155",{isSuspended:!1})))}function ef(){if(!Ee||Zp!==-1)return;let o=()=>{V()-Qp<500||(rt&&rt.state==="running"&&rt.currentTime===Yp&&(R.warn("context is fake running, auto resume"),rt.suspend().catch(i=>{R.warn(`context suspend failed: ${i}`)})),Yp=rt.currentTime,Qp=V())};Zp=setInterval(()=>{o()},2e3),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&o()})}var Se=o=>rt;var Ue=class{constructor(i){this.name=i;d(this,"node");d(this,"node2");d(this,"pre",new Set);d(this,"next",new Set);d(this,"context");d(this,"connectedNodes",new Set);d(this,"nextInputChannelMap",new Map);d(this,"_channelCount",1)}get channelCount(){return this._channelCount}set channelCount(i){this._channelCount=i,this.setChannelCount(this.node,i),this.setChannelCount(this.node2,i),this.next.forEach(e=>e.channelCount=i)}setChannelCount(i,e){!i||i instanceof ScriptProcessorNode||(i.channelCountMode="explicit",i.channelCount=e||this.channelCount||1)}setContext(i){this.context=i,this.node&&i.addMixWeight()}removeContext(){var i;this.node&&((i=this.context)==null||i.reduceMixWeight()),delete this.context}replaceNode(i){var e;if(i!==this.node)try{this.node?this._disconnect():(e=this.context)==null||e.addMixWeight(),this.node=i,this.setChannelCount(this.node),this.preNodeReconnect(),this.reconnect()}catch(t){R.error(t)}}setNode(i,e){var t;if(!this.node)try{(t=this.context)==null||t.addMixWeight(),this.node=i,this.setChannelCount(this.node),e&&(this.node2=e,this.setChannelCount(this.node2)),this.preNodeReconnect(),this.reconnect(),v.addSuccessEvent({key:502701})}catch(r){R.error(r),v.addFailedEvent({key:502701,error:r})}}deleteNode(){var i;if(this.node)try{this._disconnect(),delete this.node,delete this.node2,(i=this.context)==null||i.reduceMixWeight(),this.preNodeReconnect(),v.addSuccessEvent({key:502702})}catch(e){R.error(e),v.addFailedEvent({key:502702,error:e})}}preNodeReconnect(){this.pre.forEach(i=>{i.node?i.reconnect():i.preNodeReconnect()})}connectNext(i){this.next.forEach(e=>{let t=this.nextInputChannelMap.get(e);i._connect(e.node,t)||e.connectNext(i)})}_connect(i,e=0){return!this.node||!i?!1:((this.node2||this.node).connect(i,0,e),this.connectedNodes.add(i),!0)}_disconnect(){this.connectedNodes.forEach(i=>{var e;return(e=this.node2||this.node)==null?void 0:e.disconnect(i)}),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(i,e=0){return this.next.add(i),i.pre.add(this),this.nextInputChannelMap.set(i,e),i}},Mc=class extends Ue{constructor(e=256){super();this.fftSize=e;d(this,"dataArray",new Uint8Array(0))}setNode(e){e.fftSize=this.fftSize,this.dataArray=new Uint8Array(e.frequencyBinCount),super.setNode(e)}getByteTimeDomainData(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),this.dataArray}get level(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),Math.max(...this.dataArray)/128-1}get timeDomainPathData(){let e=this.getByteTimeDomainData(),t=1,r=0,s=0,n=`M${r},${s}`;for(let a=0;a<e.length;a++)s=e[a]/128*100/2,n+=`L${r},${s}`,r+=t;return n}},Pn=class{constructor(){d(this,"source",new Ue);d(this,"gain",new Ue);d(this,"destination",new Ue)}get volume(){var i;return((i=this.gain.node)==null?void 0:i.gain.value)||1}setVolume(i){if(i===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(Se().createGain()),this.gain.node.gain.value=i}replaceSource(i){let e=wn(i);e&&this.source.replaceNode(e)}get track(){var i;return(i=this.stream)==null?void 0:i.getAudioTracks()[0]}get stream(){var i;return(i=this.destination.node)==null?void 0:i.stream}},ls=class extends Pn{constructor(e){super();this.context=e;d(this,"aec",new Ue("aec"));d(this,"mixNode",new Ue("mixNode"));d(this,"silentNode",new Ue("silentNode"));d(this,"denoiser",new Ue("denoiser"));d(this,"voiceChanger",new Ue("voiceChanger"));this.source.pipeTo(this.aec).pipeTo(this.denoiser).pipeTo(this.voiceChanger).pipeTo(this.gain).pipeTo(this.destination),this.silentNode.pipeTo(this.mixNode).pipeTo(this.aec,1)}get isProcessEnabled(){return this.aec.node||this.denoiser.node||this.voiceChanger.node||this.gain.node}connect(){this.context.inputs.has(this)||(this.destination.setNode(this.context.destination),this.source.setContext(this.context),this.aec.setContext(this.context),this.silentNode.setContext(this.context),this.mixNode.setContext(this.context),this.denoiser.setContext(this.context),this.voiceChanger.setContext(this.context),this.gain.setContext(this.context),this.context.inputs.add(this))}disconnect(){this.context.inputs.has(this)&&(this.destination.deleteNode(),this.source.removeContext(),this.aec.removeContext(),this.silentNode.removeContext(),this.mixNode.removeContext(),this.denoiser.removeContext(),this.voiceChanger.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.aec.deleteNode(),this.silentNode.deleteNode(),this.mixNode.deleteNode(),this.denoiser.deleteNode(),this.voiceChanger.deleteNode(),this.source.deleteNode(),this.disconnect()}setVolume(e){if(e===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(this.context.audioContext.createGain()),this.gain.node.gain.value=e}},Oc=class{constructor(){d(this,"audioContext",Se("audio-mixer"));d(this,"destination",this.audioContext.createMediaStreamDestination());d(this,"inputs",new Set);d(this,"mixWeight",0);this.destination.channelCount=1}addMixWeight(i=1){this.mixWeight+=i,this.mixWeight-1===i+1>>1&&this.mixOnChange()}reduceMixWeight(i=1){this.addMixWeight(-i)}close(){this.inputs.forEach(i=>i.remove())}get mixTrack(){return this.destination.stream.getAudioTracks()[0]}},tf=new WeakMap;function wn(o){try{let i=tf.get(o);if(i)return i;let e=Se();if(o instanceof HTMLAudioElement)i=e.createMediaElementSource(o);else if(o instanceof MediaStreamTrack)i=e.createMediaStreamSource(new MediaStream([o]));else return o;return tf.set(o,i),i}catch(i){if(te&&i instanceof Error&&i.name==="NotSupportedError")R.warn(i);else throw i}}var Ot=class Ot{constructor(i){d(this,"_volume",0);d(this,"_volumeDb",0);d(this,"_log");d(this,"_scriptProcessorNode",null);d(this,"_audioWorkletNode",null);d(this,"_interval",200);d(this,"ready",this.preload());let{log:e}=i;this._log=e,S.on(C.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-Ot.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!Ot.workletReady){let i='class VolumeMeterWorklet extends AudioWorkletProcessor{constructor(){super(),this.volume=0,this.intervalTime=200,this.tick=200,this.isStop=!1,this.cache=[],this.sentFirstInfo1=!1,this.unmute=!1,this.port.onmessage=t=>{var e=t.data;switch(e.name){case"chunk":this.cache.push(...e.data),this.sentFirstInfo1||(this.port.postMessage({cl:e.data.length}),this.sentFirstInfo1=!0);break;case"setIntervalTime":this.intervalTime=e.intervalTime;break;case"unmute":this.unmute=!0;break;case"stop":this.isStop=!0}}}process(t,s){t=t[0],s=s[0];if(t||s){if(this.isStop)return!1;var i=s&&s[0]?s[0].length:0,h=this.cache.length,a=(i<h?(s[0].set(this.cache.slice(0,i)),this.cache=this.cache.slice(i)):this.unmute&&s[0].set(t[0]),(i<h?s:t)[0]);if(a){let e=0;for(let t=0;t<a.length;++t)e=Math.max(Math.abs(a[t]),e);s=a.reduce((t,e)=>t+e*e,0)/a.length;this.volume=e,this.tick-=a.length,this.tick<0&&(this.tick+=this.intervalTime/1e3*sampleRate,this.port.postMessage({volume:this.volume,volumeDb:Math.max(10*Math.log10(s)+100,0)/100,cacheLen:h,outputLen:i}))}}return!0}}registerProcessor("volume-meter",VolumeMeterWorklet);';Ot.workletReady=tr(Ot.audioContext,URL.createObjectURL(new Blob([i],{type:"application/javascript"})))}return Ot.workletReady.then(()=>this.initAudioWorklet()).catch(i=>(this._log.error(`volumeMeter preload error: ${i}`),this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(Ot.audioContext,"volume-meter");let i=!1;this._audioWorkletNode.port.onmessage=e=>{Ot.lastMessageTime=Date.now(),this._volume=e.data.volume||0,this._volumeDb=e.data.volumeDb||0,!i&&e.data.cacheLen&&e.data.outputLen&&(this._log.warn("worklet play success"),i=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(i){this._log.error(`volumeMeter init audio worklet error: ${i}`),ne.logFailedEvent({userId:this._log.userId,eventType:Ke.LOAD_WORKLET,error:i}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=Se("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=i=>{Ot.lastMessageTime=Date.now();let e=i.inputBuffer.getChannelData(0),t=0;for(let r=0;r<e.length;++r)t+=e[r]*e[r];this._volume=Math.sqrt(t/e.length)||0}}catch(i){this._log.error(`volumeMeter init script processor error: ${i}`)}}destroy(){this._scriptProcessorNode&&(this._scriptProcessorNode.onaudioprocess=null),this._audioWorkletNode&&(this._audioWorkletNode.port.postMessage({name:"stop"}),this._audioWorkletNode.port.onmessage=null),this._audioWorkletNode=null,this._scriptProcessorNode=null,S.off(C.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}getVolumeDb(){return Math.floor(this._volumeDb*100)}handleAudioLevelInterval(i){var t;let{interval:e}=i;this._interval=e,(t=this._audioWorkletNode)==null||t.port.postMessage({name:"setIntervalTime",intervalTime:e})}};d(Ot,"lastMessageTime",0),d(Ot,"audioContext",Se("volume-meter")),d(Ot,"workletReady");var kc=Ot,Ln=class extends Ue{constructor(e){super();d(this,"_volumeMeter");this._volumeMeter=new kc(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return f(this,null,function*(){yield this._volumeMeter.preload(),this.setNode(this._volumeMeter.node)})}getCalculatedVolume(){return this._volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this._volumeMeter.getInternalAudioLevel()}getVolumeDb(){return this._volumeMeter.getVolumeDb()}write(e){if(this.node){let t=e.allocationSize({planeIndex:0}),r=new Float32Array(t>>2);e.copyTo(r,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:r},[r.buffer]),e.close()}}},so=kc;var nf=Je(at(),1);var of=o=>i=>i.deviceId===o;var xn=class{constructor(i,e){d(this,"kind");d(this,"type");d(this,"devices",[]);this.kind=i,this.type=e}update(i,e){let t=i.filter(r=>r.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);if(this.devices.length===1&&hs(this.devices[0])){this.devices=t;return}e&&(t.forEach(r=>{if(r.deviceId&&!this.devices.find(of(r.deviceId))){let s=`${this.kind}${this.type}Added`;R.warn(`${s}: ${JSON.stringify(r)}`),e.emit(s,r)}}),this.devices.forEach(r=>{if(r.deviceId&&!t.find(of(r.deviceId))){let s=`${this.kind}${this.type}Removed`;R.warn(`${s}: ${JSON.stringify(r)}`),e.emit(s,r)}})),this.devices=t}hasDevice(i){return!!this.devices.find(e=>e.deviceId===i)}},wu=class extends nf.EventEmitter{constructor(){super();d(this,"audioInputs",new xn(p.AUDIO,"Input"));d(this,"videoInputs",new xn(p.VIDEO,"Input"));d(this,"audioOutputs",new xn(p.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(){us().then(e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)})}update(){return f(this,arguments,function*(e=0){let t=yield us(e);return this.audioInputs.update(t,this),this.videoInputs.update(t,this),this.audioOutputs.update(t,this),this})}hasBlueTooth(){var t;if(((t=Se())==null?void 0:t.outputLatency)*1e3>150)return!0;let e=["bluetooth","air","wireless","bt","tws","buds","headset","headphone"];return this.audioOutputs.devices.some(r=>e.some(s=>r.label.toLowerCase().includes(s)))||this.audioInputs.devices.some(r=>e.some(s=>r.label.toLowerCase().includes(s)))}},ve=Vs||Oo?null:new wu;function hs(o){return o.deviceId===o.groupId&&o.groupId===""}function us(){return f(this,arguments,function*(o=0){if(Zi()||!Ec())return[];let i=yield navigator.mediaDevices.enumerateDevices();if(o!==0){let e={audio:!1,video:!1};if(i.forEach(t=>{hs(t)&&(t.kind===p.AUDIO_INPUT?e.audio=!0:t.kind===p.VIDEO_INPUT&&(e.video=!0))}),o===2&&(e.audio=!1),o===1&&(e.video=!1),e.audio||e.video){let t;try{t=yield navigator.mediaDevices.getUserMedia(e),e.audio&&Nr()}catch(r){R.debug("capture before getDevices failed: ",r)}i=yield navigator.mediaDevices.enumerateDevices(),t==null||t.getTracks().forEach(r=>r.stop())}}return i.map((e,t)=>{let r={kind:e.kind,deviceId:e.deviceId,groupId:e.groupId,label:e.label||`${e.kind}_${t}`};return e.deviceId.length>0&&Lu.add(`${e.deviceId}_${e.kind}`),e.getCapabilities&&(r.getCapabilities=()=>e.getCapabilities()),r})})}function It(o=!1){return ve.update(o?1:0).then(i=>i.audioInputs.devices)}function At(o=!1){return ve.update(o?2:0).then(i=>i.videoInputs.devices)}var sf=!1;function af(){return f(this,null,function*(){try{sf||(sf=!0,R.info(`speakers:${(yield Dr()).map(o=>` ${o.deviceId.slice(0,8)}: ${o.label}`)}`))}catch(o){}})}function Dr(o=!1){return f(this,null,function*(){return(Ee||Ce)&&(o=!1),ve.update(o?1:0).then(i=>i.audioOutputs.devices)})}var Lu=new Set;function cf(o){if(o instanceof CanvasCaptureMediaStreamTrack||!(o instanceof MediaStreamTrack))return!1;let i=o.label.toLocaleLowerCase();if(i.includes("camera")||i.includes("webcam"))return!0;let t=`${((o==null?void 0:o.getSettings())||{}).deviceId}_${p.VIDEO_INPUT}`;return!!Lu.has(t)}function df(o){if(o instanceof CanvasCaptureMediaStreamTrack||!(o instanceof MediaStreamTrack))return!1;let i=o.label.toLocaleLowerCase();if(i.includes("mic")||i.includes("\u9EA6\u514B\u98CE"))return!0;let t=`${((o==null?void 0:o.getSettings())||{}).deviceId}_${p.AUDIO_INPUT}`;return!!Lu.has(t)}function xu(o,i){return f(this,null,function*(){let t=(yield It()).find(r=>r.deviceId===Gr);return!i&&(t==null?void 0:t.groupId)===o||(t==null?void 0:t.groupId)===o&&t.label===i})}function lf(s){return f(this,arguments,function*({newDeviceId:o,oldDeviceId:i,oldGroupId:e,oldLabel:t,kind:r}){return o!==i?!1:r===p.AUDIO&&o===Gr?yield xu(e,t):!0})}var Pc,Uu=class extends Pn{constructor(e){super();this.log=e;d(this,"volumeMeter");d(this,"volumeMeterAfter3A");d(this,"volumeDestination");d(this,"analyser",new Mc);this.volumeMeter=new Ln({log:this.log}),this.volumeMeterAfter3A=new Ln({log:this.log}),this.volumeDestination=new Ue,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},ms=class o extends pi{constructor(e){super(e,p.AUDIO);d(this,"_outputDeviceId");d(this,"_floatVolume",1);d(this,"_destination");d(this,"pipeline");d(this,"volumeMeterMode","worklet");d(this,"enableVolumeControlInIOS");this.enableVolumeControlInIOS=e.enableVolumeControlInIOS,this.mode=0,e.url&&(this.url=e.url),this.pipeline=new Uu(this._log)}setTrack(e){}get duration(){var e;return Math.floor((((e=this.element)==null?void 0:e.duration)||0)*1e3)}get currentTime(){var e;return Math.floor((((e=this.element)==null?void 0:e.currentTime)||0)*1e3)}set currentTime(e){this.element&&(this.element.currentTime=e/1e3)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(e){if((Tt==="15.2"||Tt==="15.3"||Tt==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}let r=Pc||new Audio;r.setAttribute("autoplay","autoplay"),r.srcObject=this.getMediaStream(),r.muted=this.muted,this.url&&(r.crossOrigin="anonymous",r.src=this.url),this.element=r,this.setVolume(Q(e)?e/100:this._floatVolume),r===Pc&&(Pc=void 0),this.options.enableTimeupdateEvent&&(this.element.ontimeupdate=()=>this.emit(K.TIME_UPDATE,this.currentTime)),this.bindElementEvents()}play(e){return f(this,null,function*(){if(!(!this.track&&!this.url))return!this.pipeline.source.node&&this.track&&this.pipeline.replaceSource(this.track),this.element||this.initializeElement(e==null?void 0:e.volume),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),this.volumeMeterMode==="worklet"?(this.pipeline.volumeMeter.init(),this.pipeline.volumeMeterAfter3A.init()):this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(Se("player").createAnalyser()),af(),we(o.prototype,this,"play").call(this)})}stop(e=0){this.pipeline.destroy(),super.stop(e)}setVolume(e){this._floatVolume=e,this.element&&(this.element.volume=e)}setSinkId(e){return f(this,null,function*(){var t,r;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield(r=(t=this.element).setSinkId)==null?void 0:r.call(t,e))})}get useDestination(){return!!this.pipeline.stream}setLoop(e){this.element&&(this.element.loop=e)}getAudioLevel(){return this.pipeline.volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this.pipeline.volumeMeter.getInternalAudioLevel()}getInternalAudioLevelAfter3A(){return this.pipeline.volumeMeterAfter3A.getInternalAudioLevel()}},wc=class extends ms{setTrack(i){this.track!==i&&(this.unbindTrackEvents(),this.track=i,this.emit(K.MEDIA_TRACK_CHANGED,i),i&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([i]))))}},ps=class extends ms{constructor(e){super(e);d(this,"_sourceElement");d(this,"_output",new Ue);this.pipeline.source.pipeTo(this.pipeline.gain),this.pipeline.gain.pipeTo(this.pipeline.volumeMeter).pipeTo(this._output),this.pipeline.gain.pipeTo(this.pipeline.destination)}setOutput(){this.mode=1,this._output.setNode(Se("player").destination)}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var t,r,s;((r=(t=this.element)==null?void 0:t.error)==null?void 0:r.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(K.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([e]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e])),this.pipeline.source.channelCount=((s=e.getSettings())==null?void 0:s.channelCount)||1,this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){var r;let t=e<=1&&!Ba();if(!(this._floatVolume===e&&(t&&((r=this.element)==null?void 0:r.volume)===e||!t&&this.pipeline.volume===e)))if(this._floatVolume=e,this.useDestination)this.pipeline.setVolume(e),this._log.info(`set pipeline volume: ${e}`);else if(t)this.element?(this._log.info(`set element volume: ${e}`),this.element.volume=e):this._log.info("set element volume: no element");else{if(Ba())if(this.enableVolumeControlInIOS)ef();else return;if(te&&!this.pipeline.source.node){this._log.warn("set pipeline volume failed: no source node");return}this._log.info(`start set pipeline volume: ${e}`),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this._destination||(this._destination=Se("player").createMediaStreamDestination()),this.pipeline.destination.setNode(this._destination),xe(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play().catch(s=>{this.emit(K.AUTOPLAY_FAILED,s)}))}}stop(e=0){this.pipeline.destroy();let t=this._sourceElement||this.element;t&&Bt&&(Pc=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}};var no=class extends j{constructor({userId:e,sdkAppId:t,mediaType:r,room:s,PlayerClass:n=r===1?ps:it}){var a;super();d(this,"id",un());d(this,"userId","");d(this,"isRemote");d(this,"mediaType");d(this,"room");d(this,"user");d(this,"_log");d(this,"_inputTrack");d(this,"_outputTrack");d(this,"isPlayCalled");d(this,"container",null);d(this,"player");d(this,"subVideoPlayerMap");d(this,"muted",!1);d(this,"abortCtrl");d(this,"objectFit","cover");d(this,"mirror");d(this,"rotation");d(this,"isScreen",!1);d(this,"manager");d(this,"trackSettings");d(this,"isFirstVideoFrameEmitted",!1);this.userId=e||"",this.mediaType=r,this._log=R.createLogger({parent:s==null?void 0:s.getLogger(),id:`${this.kind[0]}t`,userId:(a=s||this.room)==null?void 0:a.userId,remoteUserId:this instanceof fi?void 0:this.userId,sdkAppId:t,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof fi}),this.player=new n({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log,enableVolumeControlInIOS:s==null?void 0:s.enableVolumeControlInIOS}),this.player.on(K.PLAYER_STATE_CHANGED,c=>{if(S.emit(C.PLAYER_STATE_CHANGED,O({track:this},c)),this.emit("player-state-changed",c),c.state==="PLAYING"&&this.room){let l=!0;for(let{remoteAudioTrack:h,remoteVideoTrack:m,remoteAuxiliaryTrack:u}of[...this.room.remotePublishedUserMap.values()])if(h.isAvailable&&!h.player.isPlaying||m.isAvailable&&!m.player.isPlaying||u.isAvailable&&!u.player.isPlaying){l=!1;break}l&&vr()&&Xp()}}),this.kind===p.VIDEO&&(this.player.on(K.LOADED_DATA,()=>{this.emitFirstVideoFrameEvent(K.LOADED_DATA),S.emit(C.VIDEO_LOADED_DATA,{track:this})}),this.player.on(K.LOADED_META_DATA,()=>{this.emitFirstVideoFrameEvent(K.LOADED_META_DATA)}),this.player.on(K.MEDIA_TRACK_CHANGED,c=>{var l;(l=this.subVideoPlayerMap)==null||l.forEach(h=>h.setTrack(c))}),this.player.on(K.RESIZE,c=>{this.emitFirstVideoFrameEvent(K.RESIZE),this.emit("video-size-changed",O({userId:this.userId,streamType:this.mediaType===2?"auxiliary":"main"},c))})),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(K.ERROR,this.onPlayerError.bind(this)),this.player.on(K.AUTOPLAY_FAILED,this.handleAutoPlayFailed,this)}get log(){return this._log||R}get kind(){return this.mediaType===1?p.AUDIO:p.VIDEO}get isAudio(){return this.kind===p.AUDIO}get strMediaType(){return this.mediaType===4?p.VIDEO:this.mediaType===2?p.SCREEN:p.AUDIO}get streamType(){return(this.mediaType&2)===0?"main":"auxiliary"}get isMediaTrackActive(){return this.mediaTrack?!this.mediaTrack.muted&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled:!1}play(e,t){return f(this,null,function*(){let r=Ae(e)?e[0]:e;if(this.isPlayCalled){this.log.info(`play update options: ${JSON.stringify(t)}`),t&&!T(t.muted)&&this.setPlayerMute(t.muted),t&&!T(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof it&&(this.player.setObjectFit(this.objectFit),this.container!==r&&r&&(this.container=r,this.player.setContainer(r)),Ae(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t)));return}if(t&&!T(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===p.VIDEO)&&this.setPlayerMute(!0),t&&!T(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof it&&(this.player.setObjectFit(this.objectFit),t&&!T(t.poster)&&this.player.setPoster(t.poster)),this.isPlayCalled=!0,r&&(this.container=r,this.player instanceof it&&this.player.setContainer(r)),S.emit(C.PLAY_TRACK_START,{track:this}),!this._outputTrack){this.log.info("play has not mediaTrack, abort");return}this._log.info(`play with options: ${JSON.stringify(t)}`);try{this.player.setTrack(this.playerMediaTrack),yield this.player.play(t),Ae(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(s){throw this.handleAutoPlayFailed(s),s}})}setMirror(e,t){if(this.isScreen||this.kind!==p.VIDEO||T(e)||e===this.mirror)return;this.mirror=e;let r=this.player;t&&(r=t);let s=this.manager;if(he(this.mirror)){r.setViewMirror(this.mirror),!this.isRemote&&s&&(s.mirror=!1);return}switch(this.mirror){case"view":{s&&(s.mirror=!1),r.setViewMirror(!0);break}case"publish":{s&&(s.mirror=!0),r.setViewMirror(!0);break}case"both":s&&(s.mirror=!0),r.setViewMirror(!1)}}playSubContainer(e,t){return f(this,null,function*(){if(!this._outputTrack||this.kind===p.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((s,n)=>{var a;e.find(c=>n===c)||(s.stop(),(a=this.subVideoPlayerMap)==null||a.delete(n))});for(let[s,n]of e.entries()){let a=this.subVideoPlayerMap.get(n);a?t&&(T(t.objectFit)||a.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new it({id:this.userId||this.id,track:this.playerMediaTrack,container:n,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:`vp-sub${s+1}`})}))}let r=[...this.subVideoPlayerMap.values()];for(let s of r)s.setViewMirror(this.player.mirror),yield s.play()})}setAudioOutput(e){return this.player.setSinkId(e)}setAudioVolume(e){this.player.setVolume(e)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var e;return((e=this.player)==null?void 0:e.getInternalAudioLevel())||0}stop(e=!1){this.isPlayCalled&&(this.isPlayCalled=!1,this.isFirstVideoFrameEmitted=!1,this.player&&(this.log.info(`stop ${this.kind} player`),this.player.stop(bl(this)&&!e?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(t=>{t.stop()}),this.container=null)}resume(){return f(this,null,function*(){var e;this.isPlayCalled&&(yield(e=this.player)==null?void 0:e.resume())})}close(){this.log.info("close"),this.isPlayCalled&&this.stop(!0)}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),S.emit(e?C.TRACK_MUTED:C.TRACK_UNMUTED,{track:this})}setPlayerMute(e){this.player.setMuted(e)}get mediaTrack(){return this._inputTrack||null}get outMediaTrack(){return this._outputTrack||null}get playerMediaTrack(){return this.outMediaTrack}installTrackEvent(e){tt(e,e).add(p.MUTE,this.onTrackMuted).add(p.UNMUTE,this.onTrackUnmuted).add(p.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===p.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){xe(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(bl(this)?this.jitterBufferDelay:0),this.log.info(`playing state updated, stop ${this.kind}`);return}}this.log.debug(`updatePlayingState abort ${this.isPlayCalled} ${e} ${this.player.isStopped}`)}handleAutoPlayFailed(e){return f(this,null,function*(){var r;this.log.warn("handleAutoPlayFailed",e);let t=()=>{this.resume().then(()=>{document.removeEventListener("click",t,!0)})};if(this.room&&this.room.enableAutoPlayDialog){if((Ji||ji)&&(yield Ge(100),(r=this.player)!=null&&r.isPlaying))return;cs()}else document.addEventListener("click",t,!0);S.once(C.LOCAL_TRACK_CAPTURE_SUCCESS,({track:s})=>{s.kind==="audio"&&vr()&&!this.player.isPlaying&&this.isRemote&&this.isAvailable&&t()}),this.emit("error",e)})}getVideoFrame(){return this.player instanceof it?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(e){var n,a,c;if(this.isFirstVideoFrameEmitted)return;let t=(n=this.mediaTrack)==null?void 0:n.getSettings(),r=(t==null?void 0:t.width)||((a=this.player.element)==null?void 0:a.videoWidth)||0,s=(t==null?void 0:t.height)||((c=this.player.element)==null?void 0:c.videoHeight)||0;e===K.RESIZE&&!r&&!s||e===K.LOADED_META_DATA&&!r&&!s||(e===K.LOADED_DATA&&!r&&!s&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,bt(this.rotation)&&([r,s]=[s,r]),this.emit("first-video-frame",{width:r,height:s,streamType:this.streamType,userId:this.isRemote?this.userId:""}))}onTrackMuted(){this._log.warn(`${this.kind} track is unable to provide media output`)}onTrackUnmuted(){this._log.info(`${this.kind} track is able to provide media output`)}onTrackEnded(){this._log.warn(`${this.kind} track ended`)}};M([be([],j.INIT,{sync:!0})],no.prototype,"close",1);var KT=Object.prototype.hasOwnProperty,{toString:Fb}=Object.prototype;function eE(o){if(o==null)return!0;if(typeof o=="boolean")return!1;if(typeof o=="number")return o===0;if(typeof o=="string"||typeof o=="function"||Array.isArray(o))return o.length===0;if(o instanceof Error)return o.message==="";if(dt(o))switch(Object.prototype.toString.call(o)){case"[object File]":case"[object Map]":case"[object Set]":return o.size===0;case"[object Object]":{for(let i in o)if(KT.call(o,i))return!1;return!0}}return!1}var _i=eE;var tE=function(o){return f(this,null,function*(){let i=rE(o);R.info(`getUserMedia with constraints: ${JSON.stringify(i)}`);let e=[],t=[],r=["label","deviceId","groupId"];if(i.audio&&(e=yield It(),R.info(`microphones: ${_t(e.map(s=>L(O({},s),{groupId:s.groupId.substring(0,8)})),{keysToInclude:r})}`)),i.video&&(t=yield At(),R.info(`cameras: ${_t(t,{keysToInclude:r})}`),!he(i.video)&&i.video.facingMode==="user"&&!i.video.deviceId)){let n=t.filter(a=>!a.label.includes("infrared")).find(a=>a.label.includes("facing front"));n&&(i.video.deviceId=n.deviceId,R.info(`exclude infrared camera: ${JSON.stringify(i)}`))}try{let s=yield navigator.mediaDevices.getUserMedia(i);return pu&&s.getTracks().forEach(n=>{var c;let a=n.getCapabilities();R.info(`${n.kind} capabilities: ${_t(a,{keysToInclude:Ra})}`),!T(o.echoCancellation)&&((c=a.echoCancellation)==null?void 0:c.indexOf(o.echoCancellation))===-1&&R.warn(`Invalid argument for 'echoCancellation'. Expected one of [${JSON.stringify(a.echoCancellation)}], but received '${o.echoCancellation}'`)}),i.audio&&Nr(),s}catch(s){let{message:n}=s;throw s.name==="NotFoundError"&&(o.video&&t&&t.length===0&&(n=$({key:B.CAMERA_NOT_FOUND})),o.audio&&e&&e.length===0&&(n=$({key:B.MICROPHONE_NOT_FOUND}))),new D({code:I.INITIALIZE_FAILED,name:s.name,message:n,constraint:s.constraint})}})},iE=Ci({retryFunction:tE,settings:{retries:3,timeout:500},onError:({error:o,retry:i,reject:e,retryFuncArgs:t,retriedCount:r})=>{let s=r+1;o.name==="NotReadableError"||o.name==="OverconstrainedError"||o.name==="AbortError"?(s===1?(t[0].video&&(t[0].maxResolution=!1,(!Ce||t[0].width*t[0].height<=1920*1080)&&t[0].frameRate&&(t[0].frameRate=t[0].frameRate>10?10:5)),t[0].retryWhenExactFailed&&t[0].useExactDeviceId&&(t[0].useExactDeviceId=!1)):s===2?t[0].useDeviceIdOnly=!0:s===3&&!t[0].useExactDeviceId&&(t[0].useTrueAsConstraint=!0),i()):e(o),t[0].microphoneId&&uf(t[0].microphoneId,!1),t[0].cameraId&&uf(t[0].cameraId,!0)},onRetrying:o=>{R.warn(`getUserMedia NotReadableError observed, retrying [${o}/3]`)},onRetryFailed:o=>{ne.logFailedEvent({eventType:Ke.GET_USER_MEDIA_RETRY,error:o})},onRetrySuccess:o=>{ne.logSuccessEvent({eventType:Ke.GET_USER_MEDIA_RETRY}),ne.uploadEvent({log:`stat-${Ke.GET_USER_MEDIA_RETRY}-success-${o}`})}});function uf(o,i){return f(this,null,function*(){let t=(i?yield At():yield It()).find(r=>r.deviceId===o);t&&me(t.getCapabilities)&&R.warn(_t(t.getCapabilities(),{keysToInclude:Ra}))})}function rE(o){return{audio:oE(o),video:sE(o)}}function oE(o){if(!o.audio)return!1;if(o.useTrueAsConstraint)return!0;let i={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:o.sampleRate};return!_i(o.microphoneId)&&(i.deviceId=o.useExactDeviceId?{exact:o.microphoneId}:o.microphoneId,o.useDeviceIdOnly)?i:(Q(o.channelCount)&&(i.channelCount=o.channelCount),(he(o.echoCancellation)||o.echoCancellation==="remote-only"||o.echoCancellation==="all")&&(i.echoCancellation=o.echoCancellation),he(o.noiseSuppression)&&!o.noiseSuppression&&(i.noiseSuppression=!1),he(o.autoGainControl)&&!o.autoGainControl&&(i.autoGainControl=!1),_i(i)?!0:i)}function sE(o){if(!o.video)return!1;if(o.useTrueAsConstraint)return!0;let{maxResolution:i=!0}=o,e={};return o.cameraId?e.deviceId=o.useExactDeviceId?{exact:o.cameraId}:o.cameraId:o.facingMode&&(e.facingMode=o.facingMode),o.useDeviceIdOnly&&!_i(e)?e:(o.width&&(e.width={ideal:o.width},i&&!te&&(e.width.max=o.width)),o.height&&(e.height={ideal:o.height},i&&!te&&(e.height.max=o.height)),te&&oi&&o.width&&o.height&&o.width*o.height<352*288&&(e.width=o.width,e.height=o.height),o.frameRate&&(e.frameRate=o.frameRate),_i(e)?!0:e)}var hf=iE;function Lc(o){return Y((i,e)=>function(...t){return f(this,null,function*(){return yield o.apply(this,t),i.apply(this,t)})})}function Ct(o){return Y((i,e)=>function(...t){return f(this,null,function*(){let r=yield i.apply(this,t);return yield o.call(this,...t),r})})}function xc(o){return Y((i,e)=>function(...t){return f(this,null,function*(){try{return yield i.apply(this,t)}catch(r){o.call(this,r)}})})}function Y(o){return function(i,e,t){return t.value=o(t.value,e),t}}var mf=(()=>{let o=!1,i=document.visibilityState;return()=>{document.visibilityState!==i&&R.info(`visibility change: ${document.visibilityState}`),!o&&(document.addEventListener("visibilitychange",()=>{R.info(`visibility change: ${document.visibilityState}`),i=document.visibilityState}),o=!0)}})();var nE=0,Uc=class{constructor(){d(this,"log",R.createLogger({id:`fq${++nE}`}));d(this,"isRunning",!1);d(this,"queue",[])}get length(){return this.queue.length}get lastQueueItem(){return this.length===0?null:this.queue[this.length-1]}push(i,e=!1){var s,n;let t=O({},i),r=new Promise((a,c)=>{t.resolve=a,t.reject=c});return t.promise=r,e?this.length<=1?this.queue.push(t):(n=(s=this.lastQueueItem)==null?void 0:s.promise)==null||n.then(t.resolve,t.reject):this.queue.push(t),this.log.debug(`push ${this.length}`),this.isRunning||this.callNext(),r}shift(){let i=this.queue.shift();return this.log.debug(`shift ${this.length}`),i}callNext(){if(this.isRunning||this.length===0)return;this.log.debug("callNext ",this.length);let{fn:i,args:e,context:t,resolve:r,reject:s}=this.queue[0];this.isRunning=!0,i.apply(t,e).then(r,s).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},Vc=new WeakMap,Fc=new WeakMap;function ir(o=!1){return function(i,e,t){let r=t.value;return t.value=function(...s){let n=Vc.get(this)||new Uc;return Vc.set(this,n),n.push({fn:r,args:s,context:this},o)},t}}function Bc(o){return function(i,e,t){let r=t.value;return t.value=function(...s){var a,c,l;let n=[];return(c=(a=Vc.get(this))==null?void 0:a.queue)==null||c.forEach(h=>n.push(h)),(l=Fc.get(this))==null||l.forEach(h=>h==null?void 0:h.queue.forEach(m=>n.push(m))),n.forEach(h=>{h.reject(new D({code:I.API_CALL_ABORTED,message:o}))}),Vc.delete(this),Fc.delete(this),r.apply(this,s)},t}}function gi(o){return function(i,e,t){let r=t.value,s=n=>o(...n);return t.value=function(...n){let a=Fc.get(this)||new Map,c=a.get(s(n))||new Uc;return a.set(s(n),c),Fc.set(this,a),c.push({fn:r,args:n,context:this})},t}}function Rt(o,i){return Y((e,t)=>function(...r){let s=o;try{let n=e.apply(this,r),a=V();return Er(n)?n.then(c=>(i?v.addSuccessEvent({key:s,cost:V()-a}):v.addSuccessEvent({key:s}),c)).catch(c=>{throw v.addFailedEvent({key:s,error:c}),c}):(v.addSuccessEvent({key:s}),n)}catch(n){throw v.addFailedEvent({key:s,error:n}),n}})}var Ch={};Vi(Ch,{Events:()=>ke,Inspect:()=>$t,LastSink:()=>ao,Sink:()=>X,Subscribe:()=>co,TimeoutError:()=>Un,audit:()=>GE,bindCallback:()=>NE,bindNodeCallback:()=>DE,buffer:()=>fE,bufferCount:()=>pE,bufferTime:()=>cS,call:()=>pf,catchError:()=>Sh,combineLatest:()=>_f,concat:()=>dE,concatMap:()=>eS,concatMapTo:()=>tS,count:()=>kE,create:()=>ce,debounce:()=>WE,debounceTime:()=>qE,defer:()=>gf,delay:()=>dS,deliver:()=>z,dispose:()=>Hc,elementAt:()=>JE,empty:()=>Hn,every:()=>YE,exhaustMap:()=>oS,exhaustMapTo:()=>sS,expand:()=>lS,filter:()=>Gt,find:()=>jE,findIndex:()=>XE,first:()=>zE,fromAnimationFrame:()=>bE,fromArray:()=>SE,fromEvent:()=>le,fromEventPattern:()=>IE,fromFetch:()=>AE,fromIterable:()=>CE,fromPromise:()=>Sf,fromReadableStream:()=>yE,fromReader:()=>RE,groupBy:()=>nS,identity:()=>aE,ignoreElements:()=>xE,iif:()=>uE,inspect:()=>ff,interval:()=>Wu,last:()=>QE,map:()=>$n,mapTo:()=>KE,max:()=>PE,merge:()=>Vn,mergeMap:()=>iS,mergeMapTo:()=>rS,min:()=>wE,never:()=>ME,nothing:()=>_e,of:()=>EE,pairwise:()=>ZE,pipe:()=>ue,race:()=>$u,range:()=>vE,reduce:()=>qu,retry:()=>pS,scan:()=>Eh,setAsapScheduler:()=>TE,share:()=>rr,shareReplay:()=>lE,skip:()=>VE,skipUntil:()=>FE,skipWhile:()=>Jc,startWith:()=>Fn,subject:()=>ot,subscribe:()=>Te,sum:()=>LE,switchMap:()=>Or,switchMapTo:()=>mo,take:()=>or,takeLast:()=>UE,takeUntil:()=>Pe,takeWhile:()=>If,tap:()=>Gn,throttle:()=>HE,throwError:()=>OE,timeInterval:()=>aS,timeout:()=>mS,timer:()=>Bn,toPromise:()=>uS,toReadableStream:()=>hS,withLatestFrom:()=>mE,zip:()=>hE});function _e(...o){}var pf=o=>o(),aE=o=>o;function Hc(){this.dispose()}var ff=()=>typeof __FASTRX_DEVTOOLS__!="undefined",cE=1,$t=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(i){let e=new Vu(i,this,this.streamId++);return ke.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},ao=class{constructor(){this.defers=new Set,this.disposed=!1}next(i){}complete(){this.dispose()}error(i){this.dispose()}get bindDispose(){return()=>this.dispose()}dispose(){this.disposed=!0,this.complete=_e,this.error=_e,this.next=_e,this.dispose=_e,this.subscribe=_e,this.doDefer()}subscribe(i){return i instanceof $t?i.subscribe(this):i(this),this}get bindSubscribe(){return i=>this.subscribe(i)}doDefer(){this.defers.forEach(pf),this.defers.clear()}defer(i){this.defers.add(i)}removeDefer(i){this.defers.delete(i)}reset(){this.disposed=!1,delete this.complete,delete this.next,delete this.dispose,delete this.next,delete this.subscribe}resetNext(){delete this.next}resetComplete(){delete this.complete}resetError(){delete this.error}},X=class extends ao{constructor(i){super(),this.sink=i,i.defer(this.bindDispose)}next(i){this.sink.next(i)}complete(){this.sink.complete()}error(i){this.sink.error(i)}},co=class extends ao{constructor(i,e=_e,t=_e,r=_e){if(super(),this._next=e,this._error=t,this._complete=r,this.then=_e,i instanceof $t){let s={toString:()=>"subscribe",id:0,source:i};this.defer(()=>{ke.defer(s,0)}),ke.create(s),ke.pipe(s),this.sourceId=s.id,this.subscribe(i),ke.subscribe({id:s.id,end:!0}),e==_e?this._next=n=>ke.next(s,0,n):this.next=n=>{ke.next(s,0,n),e(n)},r==_e?this._complete=()=>ke.complete(s,0):this.complete=()=>{this.dispose(),ke.complete(s,0),r()},t==_e?this._error=n=>ke.complete(s,0,n):this.error=n=>{this.dispose(),ke.complete(s,0,n),t(n)}}else this.subscribe(i)}next(i){this._next(i)}complete(){this.dispose(),this._complete()}error(i){this.dispose(),this._error(i)}};function ue(o,...i){return i.reduce((e,t)=>t(e),o)}function ce(o,i,e){if(ff()){let t=Object.defineProperties(Object.setPrototypeOf(o,$t.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:i,writable:!0,configurable:!0},args:{value:e,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});ke.create(t);for(let r=0;r<e.length;r++){let s=e[r];typeof s=="function"&&s instanceof $t&&ke.addSource(t,s)}return t}return o}function z(o,i){return function(...e){return t=>{if(t instanceof $t){let r=ce(s=>{let n=new o(s,...e);n.sourceId=r.id,n.subscribe(t)},i,arguments);return r.source=t,ke.pipe(r),r}else return r=>t(new o(r,...e))}}}function Mr(o,i){window.postMessage({source:"fastrx-devtools-backend",payload:{event:o,payload:i}})}var Vu=class extends X{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(o,i){Mr("addSource",{id:o.id,name:o.toString(),source:{id:i.id,name:i.toString()}})},next(o,i,e){Mr("next",{id:o.id,streamId:i,data:e&&e.toString()})},subscribe({id:o,end:i},e){Mr("subscribe",{id:o,end:i,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(o,i,e){Mr("complete",{id:o.id,streamId:i,err:e?e.toString():null})},defer(o,i){Mr("defer",{id:o.id,streamId:i})},pipe(o){Mr("pipe",{name:o.toString(),id:o.id,source:{id:o.source.id,name:o.source.toString()}})},update(o){Mr("update",{id:o.id,name:o.toString()})},create(o){o.id||(o.id=cE++),Mr("create",{name:o.toString(),id:o.id})}},Un=class extends Error{constructor(i){super(`timeout after ${i}ms`),this.timeout=i}};var $c=class extends ao{constructor(i){super(),this.source=i,this.sinks=new Set}add(i){i.defer(()=>this.remove(i)),this.sinks.add(i).size===1&&(this.reset(),this.subscribe(this.source))}remove(i){this.sinks.delete(i),this.sinks.size===0&&this.dispose()}next(i){this.sinks.forEach(e=>e.next(i))}complete(){this.sinks.forEach(i=>i.complete()),this.sinks.clear()}error(i){this.sinks.forEach(e=>e.error(i)),this.sinks.clear()}};function rr(){return o=>{let i=new $c(o);if(o instanceof $t){let e=ce(t=>{i.add(t)},"share",arguments);return i.sourceId=e.id,e.source=o,ke.pipe(e),e}return ce(i.add.bind(i),"share",arguments)}}function Vn(...o){return ce(i=>{let e=new X(i),t=o.length;e.complete=()=>{--t===0&&i.complete()},o.forEach(e.bindSubscribe)},"merge",arguments)}function $u(...o){return ce(i=>{let e=new Map;o.forEach(t=>{let r=new X(i);e.set(t,r),r.complete=()=>{e.delete(t),e.size===0?i.complete():r.dispose()},r.next=s=>{e.delete(t),e.forEach(n=>n.dispose()),r.resetNext(),r.resetComplete(),r.next(s)}}),o.forEach(t=>e.get(t).subscribe(t))},"race",arguments)}function dE(...o){return ce(i=>{let e=0,t=o.length,r=new X(i);r.complete=()=>{e<t&&!r.disposed?(r.doDefer(),r.subscribe(o[e++])):i.complete()},r.complete()},"concat",arguments)}function lE(o){return i=>{let e=new $c(i),t=[];return e.next=function(r){t.push(r),t.length>o&&t.shift(),this.sinks.forEach(s=>s.next(r))},ce(r=>{r.defer(()=>e.remove(r)),t.forEach(s=>r.next(s)),e.add(r)},"shareReplay",arguments)}}function uE(o,i,e){return ce(t=>o()?i(t):e(t),"iif",arguments)}function _f(...o){return ce(i=>{let e=o.length,t=e,r=e,s=new Array(e),n=()=>{--r===0&&i.complete()},a=(c,l)=>{let h=new X(i);h.next=m=>{t--,h.next=u=>{s[l]=u,t===0&&i.next(s)},h.next(m)},h.complete=n,h.subscribe(c)};o.forEach(a)},"combineLatest",arguments)}function hE(...o){return ce(i=>{let e=o.length,t=e,r=new Array(e),s=()=>{--t===0&&i.complete()},n=(a,c)=>{let l=new X(i),h=[];r[c]=h,l.next=m=>{h.push(m),r.every(u=>u.length)&&i.next(r.map(u=>u.shift()))},l.complete=s,l.subscribe(a)};o.forEach(n)},"zip",arguments)}function Fn(...o){return i=>ce((e,t=0,r=o.length)=>{for(;t<r&&!e.disposed;)e.next(o[t++]);e.disposed||e.subscribe(i)},"startWith",arguments)}var Fu=class extends X{constructor(i,...e){super(i);let t=new X(this.sink);t.next=r=>this.buffer=r,t.complete=_e,t.subscribe(_f(...e))}next(i){this.buffer&&this.sink.next([i,...this.buffer])}},mE=z(Fu,"withLatestFrom"),Bu=class extends X{constructor(i,e,t){super(i),this.bufferSize=e,this.startBufferEvery=t,this.buffer=[],this.count=0,this.startBufferEvery&&(this.buffers=[[]])}next(i){this.startBufferEvery?(this.count++===this.startBufferEvery&&(this.buffers.push([]),this.count=1),this.buffers.forEach(e=>{e.push(i)}),this.buffers[0].length===this.bufferSize&&this.sink.next(this.buffers.shift())):(this.buffer.push(i),this.buffer.length===this.bufferSize&&(this.sink.next(this.buffer),this.buffer=[]))}complete(){this.buffer.length?this.sink.next(this.buffer):this.buffers.length&&this.buffers.forEach(i=>this.sink.next(i)),super.complete()}},pE=z(Bu,"bufferCount"),Hu=class extends X{constructor(i,e){super(i),this.buffer=[];let t=new X(i);t.next=r=>{i.next(this.buffer),this.buffer=[]},t.complete=_e,t.subscribe(e)}next(i){this.buffer.push(i)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},fE=z(Hu,"buffer");var _E=function(o,i,e,t){function r(s){return s instanceof e?s:new e(function(n){n(s)})}return new(e||(e=Promise))(function(s,n){function a(h){try{l(t.next(h))}catch(m){n(m)}}function c(h){try{l(t.throw(h))}catch(m){n(m)}}function l(h){h.done?s(h.value):r(h.value).then(a,c)}l((t=t.apply(o,i||[])).next())})};function ot(o){let i=arguments,e=rr()(ce(t=>{e.next=r=>t.next(r),e.complete=()=>t.complete(),e.error=r=>t.error(r),o&&t.subscribe(o)},"subject",i));return e.next=_e,e.complete=_e,e.error=_e,e}function gf(o){return ce(i=>i.subscribe(o()),"defer",arguments)}var fs={promise:o=>{Promise.resolve().then(o)},setImmediate:typeof setImmediate!="undefined"?o=>setImmediate(o):null,setTimeout:o=>setTimeout(o,0)},gE=()=>typeof Promise!="undefined"?fs.promise:fs.setImmediate?fs.setImmediate:fs.setTimeout,Gu=gE(),Tf=o=>i=>{Gu(()=>o(i))},TE=o=>{typeof o=="function"?Gu=o:fs[o]&&(Gu=fs[o])};var Ef=o=>Tf(i=>{for(let e=0;!i.disposed&&e<o.length;e++)i.next(o[e]);i.complete()});function EE(...o){return ce(Ef(o),"of",arguments)}function SE(o){return ce(Ef(o),"fromArray",arguments)}function Wu(o){return ce(i=>{let e=0,t=setInterval(()=>i.next(e++),o);return i.defer(()=>{clearInterval(t)}),"interval"},"interval",arguments)}function Bn(o,i){return ce(e=>{let t=0,r=setTimeout(()=>{if(e.removeDefer(s),e.next(t++),i){let n=setInterval(()=>e.next(t++),i);e.defer(()=>{clearInterval(n)})}else e.complete()},o),s=()=>clearTimeout(r);e.defer(s)},"timer",arguments)}function Gc(o,i){return e=>{let t=r=>e.next(r);e.defer(()=>i(t)),o(t)}}function IE(o,i){return ce(Gc(o,i),"fromEventPattern",arguments)}function le(o,i){if("on"in o&&"off"in o)return ce(Gc(e=>o.on(i,e),e=>o.off(i,e)),"fromEvent",arguments);if("addListener"in o&&"removeListener"in o)return ce(Gc(e=>o.addListener(i,e),e=>o.removeListener(i,e)),"fromEvent",arguments);if("addEventListener"in o)return ce(Gc(e=>o.addEventListener(i,e),e=>o.removeEventListener(i,e)),"fromEvent",arguments);throw"target is not a EventDispachter"}function Sf(o){return ce(i=>{o.then(i.next.bind(i),i.error.bind(i))},"fromPromise",arguments)}function AE(o,i){return ce(gf(()=>Sf(fetch(o,i))),"fromFetch",arguments)}function CE(o){return ce(Tf(i=>{try{for(let e of o){if(i.disposed)return;i.next(e)}i.complete()}catch(e){i.error(e)}}),"fromIterable",arguments)}function RE(o){let i=e=>_E(this,void 0,void 0,function*(){if(e.disposed)return;let{done:t,value:r}=yield o.read();if(t){e.complete();return}else e.next(r),i(e)});return ce(e=>{i(e)},"fromReader",arguments)}function yE(o){return ce(i=>{let e=new AbortController,t=e.signal;i.defer(()=>e.abort("cancelled")),o.pipeTo(new WritableStream({write(r){i.next(r)},close(){i.complete()},abort(r){i.error(r)}}),{signal:t}).then(()=>i.complete(),r=>i.error(r))},"fromReadableStream",arguments)}function bE(){return ce(o=>{let i=requestAnimationFrame(function e(t){o.disposed||(o.next(t),i=requestAnimationFrame(e))});o.defer(()=>cancelAnimationFrame(i))},"fromAnimationFrame",arguments)}function vE(o,i){return ce((e,t=o,r=i+o)=>{for(;t<r&&!e.disposed;)e.next(t++);return e.complete(),"range"},"range",arguments)}function NE(o,i,...e){return ce(t=>{let r=e.concat(s=>(t.next(s),t.complete()));o.apply(i,r)},"bindCallback",arguments)}function DE(o,i,...e){return ce(t=>{let r=e.concat((s,n)=>s?t.error(s):(t.next(n),t.complete()));o.apply(i,r)},"bindNodeCallback",arguments)}function ME(){return ce(()=>{},"never",arguments)}function OE(o){return ce(i=>i.error(o),"throwError",arguments)}function Hn(){return ce(o=>o.complete(),"empty",arguments)}var lo=class extends X{constructor(i,e,t){super(i),this.f=e;let r=()=>{this.sink.next(this.acc),this.sink.complete()};typeof t=="undefined"?this.next=s=>{this.acc=s,this.complete=r,this.resetNext()}:(this.acc=t,this.complete=r)}next(i){this.acc=this.f(this.acc,i)}},qu=z(lo,"reduce"),kE=o=>z(lo,"count")((i,e)=>o(e)?i+1:i,0),PE=()=>z(lo,"max")(Math.max),wE=()=>z(lo,"min")(Math.min),LE=()=>z(lo,"sum")((o,i)=>o+i,0);var Ju=class extends X{constructor(i,e,t){super(i),this.filter=e,this.thisArg=t}next(i){this.filter.call(this.thisArg,i)&&this.sink.next(i)}},Gt=z(Ju,"filter"),ju=class extends X{next(i){}},xE=z(ju,"ignoreElements"),Xu=class extends X{constructor(i,e){super(i),this.count=e}next(i){this.sink.next(i),--this.count===0&&(this.doDefer(),this.complete())}},or=z(Xu,"take"),zu=class extends X{constructor(i,e){super(i);let t=new X(i);t.next=()=>{t.doDefer(),i.complete()},t.complete=Hc,t.subscribe(e)}},Pe=z(zu,"takeUntil"),Qu=class extends X{constructor(i,e){super(i),this.f=e}next(i){this.f(i)?this.sink.next(i):(this.doDefer(),this.complete())}},If=z(Qu,"takeWhile"),UE=o=>qu((i,e)=>(i.push(e),i.length>o&&i.shift(),i),[]),Yu=class extends X{constructor(i,e){super(i),this.count=e}next(i){--this.count===0&&(this.next=super.next)}},VE=z(Yu,"skip"),Zu=class extends X{constructor(i,e){super(i),i.next=_e;let t=new X(i);t.next=()=>{t.doDefer(),i.resetNext()},t.complete=Hc,t.subscribe(e)}},FE=z(Zu,"skipUntil"),Ku=class extends X{constructor(i,e){super(i),this.f=e}next(i){this.f(i)||(this.next=super.next,this.next(i))}},Jc=z(Ku,"skipWhile"),BE={leading:!0,trailing:!1},eh=class extends X{constructor(i,e,t){super(i),this.durationSelector=e,this.trailing=t}cacheValue(i){this.last=i,this.disposed&&this.throttle(i)}send(i){this.sink.next(i),this.throttle(i)}throttle(i){this.reset(),this.subscribe(this.durationSelector(i))}next(){this.complete()}complete(){this.dispose(),this.trailing&&this.send(this.last)}},Wc=class extends X{constructor(i,e,t=BE){super(i),this.durationSelector=e,this.config=t,this._throttle=new eh(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()}},HE=z(Wc,"throttle"),$E={leading:!1,trailing:!0},GE=o=>z(Wc,"audit")(o,$E),th=class extends X{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},qc=class extends X{constructor(i,e){super(i),this.durationSelector=e,this._debounce=new th(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()}},WE=z(qc,"debounce"),qE=o=>z(qc,"debounceTime")(i=>Bn(o)),ih=class extends X{constructor(i,e,t){super(i),this.count=e,this.defaultValue=t}next(i){this.count--===0&&(this.defaultValue=i,this.doDefer(),this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("not enough elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},JE=z(ih,"elementAt"),jE=o=>i=>or(1)(Jc(e=>!o(e))(i)),rh=class extends X{constructor(i,e){super(i),this.f=e,this.i=0}next(i){this.f(i)?(this.sink.next(this.i++),this.doDefer(),this.complete()):++this.i}},XE=z(rh,"findIndex"),oh=class extends X{constructor(i,e,t){super(i),this.f=e,this.defaultValue=t,this.index=0}next(i){(!this.f||this.f(i,this.index++))&&(this.defaultValue=i,this.doDefer(),this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},zE=z(oh,"first"),sh=class extends X{constructor(i,e,t){super(i),this.f=e,this.defaultValue=t,this.index=0}next(i){(!this.f||this.f(i,this.index++))&&(this.defaultValue=i)}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},QE=z(sh,"last"),nh=class extends X{constructor(i,e){super(i),this.predicate=e,this.index=0}next(i){this.predicate(i,this.index++)?this.result=!0:(this.result=!1,this.doDefer(),this.complete())}complete(){if(this.result===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.result);super.complete()}},YE=z(nh,"every");var ah=class extends X{constructor(i,e,t){super(i),this.f=e,typeof t=="undefined"?this.next=r=>{this.acc=r,this.resetNext(),this.sink.next(this.acc)}:this.acc=t}next(i){this.sink.next(this.acc=this.f(this.acc,i))}},Eh=z(ah,"scan"),ch=class extends X{constructor(){super(...arguments),this.hasLast=!1}next(i){this.hasLast?this.sink.next([this.last,i]):this.hasLast=!0,this.last=i}},ZE=z(ch,"pairwise"),jc=class extends X{constructor(i,e,t){super(i),this.mapper=e,this.thisArg=t}next(i){super.next(this.mapper.call(this.thisArg,i))}},$n=z(jc,"map"),KE=o=>z(jc,"mapTo")(i=>o),uo=class extends X{constructor(i,e,t){super(i),this.data=e,this.context=t}next(i){let e=this.context.combineResults;e?this.sink.next(e(this.data,i)):this.sink.next(i)}tryComplete(){this.context.resetComplete(),this.dispose()}},ho=class o extends X{constructor(i,e,t){super(i),this.makeSource=e,this.combineResults=t,this.index=0}subInner(i,e){let t=this.currentSink=new e(this.sink,i,this);this.complete===o.prototype.complete&&(this.complete=this.tryComplete),t.complete=t.tryComplete,t.subscribe(this.makeSource(i,this.index++))}complete(){this.sink.complete()}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},Xc=class extends uo{},zc=class extends ho{next(i){this.subInner(i,Xc),this.next=e=>{this.currentSink.dispose(),this.subInner(e,Xc)}}},Or=z(zc,"switchMap");function Kc(o){return(i,e)=>o(()=>i,e)}var mo=Kc(z(zc,"switchMapTo")),dh=class extends uo{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},Qc=class extends ho{constructor(){super(...arguments),this.sources=[],this.next2=this.sources.push.bind(this.sources)}next(i){this.next2(i),this.subNext()}subNext(){this.next=this.next2,this.subInner(this.sources.shift(),dh),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},eS=z(Qc,"concatMap"),tS=Kc(z(Qc,"concatMapTo")),lh=class extends uo{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},Yc=class extends ho{constructor(){super(...arguments),this.inners=new Set}next(i){this.subInner(i,lh),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(i=>i.resetComplete()):this.dispose()}},iS=z(Yc,"mergeMap"),rS=Kc(z(Yc,"mergeMapTo")),uh=class extends uo{dispose(){this.context.resetNext(),super.dispose()}},Zc=class extends ho{next(i){this.next=_e,this.subInner(i,uh)}},oS=z(Zc,"exhaustMap"),sS=Kc(z(Zc,"exhaustMapTo")),hh=class extends X{constructor(i,e){super(i),this.f=e,this.groups=new Map}next(i){let e=this.f(i),t=this.groups.get(e);typeof t=="undefined"&&(t=ot(),t.key=e,this.groups.set(e,t),super.next(t)),t.next(i)}complete(){this.groups.forEach(i=>i.complete()),super.complete()}error(i){this.groups.forEach(e=>e.error(i)),super.error(i)}},nS=z(hh,"groupBy"),mh=class extends X{constructor(){super(...arguments),this.start=new Date}next(i){this.sink.next({value:i,interval:Number(new Date)-Number(this.start)}),this.start=new Date}},aS=z(mh,"timeInterval"),ph=class extends X{constructor(i,e){super(i),this.miniseconds=e,this.buffer=[],this.id=setInterval(()=>{this.sink.next(this.buffer.concat()),this.buffer.length=0},this.miniseconds)}next(i){this.buffer.push(i)}complete(){this.sink.next(this.buffer),super.complete()}dispose(){clearInterval(this.id),super.dispose()}},cS=z(ph,"bufferTime"),fh=class extends X{constructor(i,e){super(i),this.buffer=[],this.delayTime=e}dispose(){clearTimeout(this.timeoutId),super.dispose()}delay(i){this.timeoutId=setTimeout(()=>{let e=this.buffer.shift();if(e){let{time:t,data:r}=e;super.next(r),this.buffer.length&&this.delay(Number(this.buffer[0].time)-Number(t))}},i)}next(i){this.buffer.length||this.delay(this.delayTime),this.buffer.push({time:new Date,data:i})}complete(){this.timeoutId=setTimeout(()=>super.complete(),this.delayTime)}},dS=z(fh,"delay"),_h=class extends X{constructor(i,e){super(i),this.selector=e}error(i){this.dispose(),this.selector(i)(this.sink)}},Sh=z(_h,"catchError"),gh=class extends uo{tryComplete(){let i=this.context.inners.delete(this);super.dispose(),i&&this.context.checkComplete()}next(i){this.sink.next(i),this.context.expandValue(i)}},Th=class extends ho{constructor(i,e){super(i,e),this.project=e,this.inners=new Set,this.sourceCompleted=!1}next(i){this.sink.next(i),this.expandValue(i)}expandValue(i){let e=new gh(this.sink,i,this);this.currentSink=e,this.complete=this.tryComplete,e.complete=e.tryComplete,this.inners.add(e),e.subscribe(this.makeSource(i,this.index++))}complete(){this.sourceCompleted=!0,this.checkComplete()}checkComplete(){this.sourceCompleted&&this.inners.size===0&&(this.resetComplete(),super.complete())}tryComplete(){this.sourceCompleted=!0,this.checkComplete()}},lS=z(Th,"expand");var uS=()=>o=>new Promise((i,e)=>{let t;new co(o,r=>t=r,e,()=>i(t))}),hS=()=>o=>{let i;return new ReadableStream({start(e){i=new co(o,e.enqueue.bind(e),e.error.bind(e),e.close.bind(e))},cancel(){i.dispose()}})},Te=(o=_e,i=_e,e=_e)=>t=>new co(t,o,i,e),Ih=class extends X{constructor(i,e){super(i),e instanceof Function?this.next=t=>{e(t),i.next(t)}:(e.next&&(this.next=t=>{e.next(t),i.next(t)}),e.complete&&(this.complete=()=>{e.complete(),i.complete()}),e.error&&(this.error=t=>{e.error(t),i.error(t)}))}},Gn=z(Ih,"tap"),Ah=class extends X{constructor(i,e){super(i),this.timeout=e,this.id=setTimeout(()=>this.error(new Un(this.timeout)),this.timeout)}next(i){super.next(i),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},mS=z(Ah,"timeout"),pS=(o=1/0)=>i=>{if(i instanceof $t){let e=ce(t=>{let r=o,s=new X(t);s.error=n=>{r-- >0?s.subscribe(i):t.error(n)},s.sourceId=e.id,s.subscribe(i)},"retry",[o]);return e.source=i,ke.pipe(e),e}else return e=>{let t=o,r=new X(e);r.error=s=>{t-- >0?i(r):e.error(s)},i(r)}};var _s=(e=>(e[e.AUTO_SWITCH_NEW_DEVICE=0]="AUTO_SWITCH_NEW_DEVICE",e[e.WAIT_CURRENT_DEVICE=1]="WAIT_CURRENT_DEVICE",e))(_s||{}),po=class po extends no{constructor(e,t){super({mediaType:e,PlayerClass:t});d(this,"isRemote",!1);d(this,"deviceId");d(this,"groupId","");d(this,"label","");d(this,"sourceTrack");d(this,"enableAutoSwitchWhenRecapturing",!0);d(this,"_isRecapturing",!1);d(this,"_lastRecaptureTime",0);d(this,"_onMuteTimeoutId",-1);d(this,"_encodeCheckTimeoutId",-1);d(this,"recaptureMode",0);d(this,"profile");d(this,"retryEncodeFailed")}get enableEncodeFrame(){return!1}get isPublishing(){return this.state.toString()==="publishing"}get isPublished(){return this.state==="publish"}get isUseCustomSource(){return this.sourceTrack&&this.mediaTrack&&this.sourceTrack!==this.mediaTrack}encodeFrame(e,t){throw new Error("Method not implemented.")}installTrackEvent(e){e.addEventListener(p.MUTE,this.onTrackMuted),e.addEventListener(p.UNMUTE,this.onTrackUnmuted),e.addEventListener(p.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===p.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){e.removeEventListener(p.MUTE,this.onTrackMuted),e.removeEventListener(p.UNMUTE,this.onTrackUnmuted),e.removeEventListener(p.ENDED,this.onTrackEnded)}setStateToReady(){}capture(e,t=!1){return f(this,null,function*(){var s;let r=this.sourceTrack;try{let n=V();S.emit(C.LOCAL_TRACK_CAPTURE_START,{track:this});let a;e.customSource?(a=new MediaStream,a.addTrack(e.customSource)):(t||(s=this.sourceTrack)==null||s.stop(),a=yield hf(e));let c=a.getTracks()[0];return yield this.setInputMediaStreamTrack(c),e.customSource||(this.sourceTrack=c,this.updateDeviceIdInUse(),this.listenDeviceChange()),S.emit(C.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:V()-n}),a}catch(n){throw S.emit(C.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:n}),this.log.error(`getUserMedia error observed ${n}`),n}finally{t&&(r==null||r.stop())}})}setOutputMediaStreamTrack(e){var t;if(super.setOutputMediaStreamTrack(e),this.setStateToReady(),this.isPublishing||this.isPublished)return(t=this.room)==null?void 0:t.replaceTrack(this)}get hasFlag(){var t,r;let e=ei(((t=this.room)==null?void 0:t.localPublishFlag)||0,((r=this.room)==null?void 0:r.userId)||"");return this.mediaType===4&&e.hasVideo||this.mediaType===1&&e.hasAudio||this.mediaType===2&&e.hasAuxiliary}publish(e,t){return f(this,null,function*(){return this.room=e,this.room.localTracks.add(this),this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.bindParent(e.getLogger()),yield t,this._checkPublishFlag(e)})}_checkPublishFlag(e){return new Promise((t,r)=>f(this,null,function*(){var l,h,m,u;let s=()=>r(new D({code:I.API_CALL_ABORTED,message:"publish aborted"}));if(this.hasFlag||this.muted?t():((this.state===j.INIT||this.state==="ready")&&s(),ue(le(e,"local-publish-flag-changed"),Gt(()=>this.hasFlag),Pe(Vn(le(this,j.INIT),le(this,"ready"))),Te(t,r,s))),(((h=(l=this.room)==null?void 0:l.networkQuality)==null?void 0:h.uplinkNetworkQuality)||0)>3)return t();let a=e.heartbeatCount,c=((u=(m=this.mediaTrack)==null?void 0:m.stats)==null?void 0:u.totalFrames)||0;this._encodeCheckTimeoutId=setTimeout(()=>f(this,null,function*(){var g,E,A,k,se,w,Ze;if((((E=(g=this.room)==null?void 0:g.networkQuality)==null?void 0:E.uplinkNetworkQuality)||0)>3||e.heartbeatCount-a<3)return t();if((this.isPublished||this.isPublishing)&&this.isMediaTrackActive){if((A=this.mediaTrack)!=null&&A.stats){let q=this.mediaTrack.stats.totalFrames||0;q-c===0&&this.log.warn("capture totalFrames is 0 during encode check, totalFrames",q)}let N=this.kind===p.AUDIO,y=this.stat.bytesSent>0;if(v[y?"addSuccessEvent":"addFailedEvent"]({key:N?503700:513702}),!N){let q=((se=(k=this.room)==null?void 0:k.videoCodec)==null?void 0:se.toUpperCase())||"H264",ge={H264:513704,H265:513705,VP8:513706}[q];ge&&v[y?"addSuccessEvent":"addFailedEvent"]({key:ge})}if(!y){if(v.addEnum({key:N?503701:513703,value:Zr()}),ne.uploadEvent({log:`stat-encode-failed-${this.kind}-${ni()||ai()}`,userId:this.userId}),this.log.warn(N?"encode failed":`${(Ze=(w=this.room)==null?void 0:w.videoCodec)==null?void 0:Ze.toUpperCase()} encode failed`),this.retryEncodeFailed&&(this.log.warn("retry encode"),yield this.retryEncodeFailed(this),this.stat.bytesSent>0||this.hasFlag||(yield Ge(5e3),this.stat.bytesSent>0||this.hasFlag)))return t();this.emit("6",this),r(new D({message:`${this.strMediaType} encode failed`,code:N?I.AUDIO_ENCODE_FAILED:I.VIDEO_ENCODE_FAILED}))}}}),1e4)}))}unpublish(){this.room&&this.room.localTracks.delete(this),this.log.info("unpublish"),S.emit(C.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return f(this,null,function*(){if(this.sourceTrack&&bi){let{deviceId:e,groupId:t}=this.sourceTrack.getSettings(),{label:r}=this.sourceTrack;(yield lf({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=r,t&&(this.groupId=t),us().then(n=>{let a=n.find(c=>{let l=c.deviceId===e;return t&&(l=l&&c.groupId===t),l});a&&this.emit("2",a)}))}})}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(e=!1){return!(!this.deviceId||!this.sourceTrack||this.kind===p.AUDIO&&!df(this.sourceTrack)||this.kind===p.VIDEO&&!cf(this.sourceTrack)||this._isRecapturing||e&&oi&&Ce)}onTrackMuted(){if(super.onTrackMuted(),mf(),!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<wo){setTimeout(()=>this.onTrackMuted(),wo);return}this._onMuteTimeoutId=setTimeout(()=>f(this,null,function*(){var e;if((e=this.sourceTrack)!=null&&e.muted){if((Ee||fe)&&document.visibilityState!=="visible")return;this.recapture(yield this.getRecoverCaptureDeviceId())}}),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return f(this,null,function*(){if(we(po.prototype,this,"onTrackEnded").call(this),!!this.isNeedToRecapture()&&this.recaptureMode===0){if(Date.now()-this._lastRecaptureTime<wo){setTimeout(()=>this.onTrackEnded(),wo);return}this.emit("7"),this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e,t=!1){return f(this,null,function*(){var n;if(this._isRecapturing||!this.sourceTrack)return;this.log.warn("recapture trying");let r=this.sourceTrack;t||(n=this.sourceTrack)==null||n.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let s={useExactDeviceId:!0};if(e==="user"||e==="environment")s.facingMode=e;else{let a;(this.kind==="audio"?yield It():yield At()).find(l=>l.deviceId===e)&&(a=e),s.deviceId=a}return this.capture(s,t).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),S.emit(C.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(a=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${a.message}`),this.emit("5",a),S.emit(C.LOCAL_TRACK_RECAPTURE,{track:this,error:a})}).finally(()=>{t&&(r==null||r.stop())})})}getRecoverCaptureDeviceId(){return f(this,null,function*(){let e=this instanceof ze;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let r=(Wn.get(t)||0)+1;if(Wn.set(t,r),r>=3&&this.enableAutoSwitchWhenRecapturing){let s=e?(yield At()).find(n=>!Wn.has(n.deviceId)):(yield It()).find(n=>!Wn.has(n.deviceId));s&&(this.log.warn(`${t} capture fail ${r} times, change new ${s.deviceId}`),t=s.deviceId)}}return t})}stopCapture(){var e;this.sourceTrack&&(this.sourceTrack.stop(),this.uninstallTrackEvent(this.sourceTrack)),this._inputTrack&&this.uninstallTrackEvent(this._inputTrack),(e=this.manager)==null||e.removeInput(this)}close(){super.close(),this.stopCapture()}};M([be(j.INIT,"ready",{ignoreError:!0,sync:!0})],po.prototype,"setStateToReady",1),M([ir()],po.prototype,"capture",1),M([be("ready","publish",{ignoreError:!0,success(){S.emit(C.LOCAL_TRACK_PUBLISHED,{track:this,room:this.room}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),this.log.info("published")},fail(e){var n;(n=this.room)==null||n.localTracks.delete(this);let t="error",r=e instanceof D?e:e.cause instanceof D?e.cause:e,s=!1;r instanceof D&&(r.message.includes("timeout")?t="timeout":r.code===I.API_CALL_ABORTED&&(s=!0,t="api-call")),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:t,error:r}),this.log[s?"info":"error"]("publish failed",r)}}),Rt(521714,!1)],po.prototype,"publish",1),M([Y(e=>function(){return f(this,null,function*(){let t=this.state==="publish"?"started":"starting";e.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:t,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)})}),be([],"ready",{sync:!0})],po.prototype,"unpublish",1);var fi=po,Wn=new Map;S.on(C.SWITCH_DEVICE_SUCCESS,o=>{o.track.deviceId&&Wn.delete(o.track.deviceId)});var kt=class o extends fi{constructor(e){super(1,wc);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 Ue);d(this,"_output",new Ue);d(this,"codecPipeline",[]);d(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0});d(this,"mixedAudioReferenceMap",new Map);d(this,"isAudioContextLongSuspended",!1);d(this,"after3aSilenceStartTime",0);this.manager=e,this.pipeline=new ls(e),this.pipeline.source.pipeTo(this.player.pipeline.volumeMeter),this.pipeline.gain.pipeTo(this.earMonitorGainNode).pipeTo(this._output),this.pipeline.gain.pipeTo(this.player.pipeline.volumeMeterAfter3A),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this),S.on(C.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this)}get dbVolume(){return so.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}getInternalAudioLevelAfter3A(){if(this.pipeline.aec.node||this.pipeline.denoiser.node)return this.player.getInternalAudioLevelAfter3A()}updateAfter3aSilenceStartTime(e){T(e)||(e===0&&!this.after3aSilenceStartTime?this.after3aSilenceStartTime=V():e>0&&(this.after3aSilenceStartTime=0))}setInputMediaStreamTrack(e){return f(this,null,function*(){let t=this.trackSettings||{};v.addEnum({key:501701,value:t.channelCount||0,useUV:!1}),v.addEnum({key:501702,value:t.sampleRate||0,useUV:!1}),v.addEnum({key:502700,value:0});let{sampleRate:r,channelCount:s}=t;this._log.info(`local audio track input ${JSON.stringify({sampleRate:r,channelCount:s})}`),this.pipeline.source.channelCount=s||1,this.pipeline.replaceSource(e),yield we(o.prototype,this,"setInputMediaStreamTrack").call(this,e),this.updatePlayingState(!!e)})}capture(a){return f(this,arguments,function*({deviceId:e,customSource:t,useExactDeviceId:r=!0,retryWhenExactFailed:s},n=!1){let c=yield we(o.prototype,this,"capture").call(this,{video:!1,audio:!0,microphoneId:e,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:r,retryWhenExactFailed:s,customSource:t},n);return Nr(),c})}switchDevice(e){return f(this,null,function*(){if(this.mediaTrack){if(this.deviceId===e&&!this.isUseCustomSource)if(e===Gr){if(yield xu(this.groupId,this.label))return}else return;try{this.log.info(`switchDevice audio to: ${e}`),this.sourceTrack&&this.sourceTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0,retryWhenExactFailed:!1}),S.emit(C.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(t){throw this.log.error(`switch microphone failed ${t}`),this.deviceId&&this.recapture(this.deviceId),t}}})}listenDeviceChange(){ve&&!ve.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&ve.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return f(this,null,function*(){if(e.deviceId===this.deviceId){let t=this.recaptureMode===1;if(this.log.warn(`RecaptureMode: ${_s[this.recaptureMode]}. Current microphone is lost: ${JSON.stringify(e)}`),this.recaptureMode===0){Ne(this.userId,{eventId:2003,param1:6,streamType:1});let r=yield It();r[0]?this.recapture(r[0].deviceId):t=!0}t&&ve.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.recaptureMode===1&&e.deviceId!==this.deviceId||(ve.off("audioInputAdded",this.handleMicrophoneAdded,this),this.log.warn(`microphone added: ${JSON.stringify(e)}`),this.recapture(e.deviceId))}update3A(s){return f(this,arguments,function*({echoCancellation:e,noiseSuppression:t,autoGainControl:r}){let n=this.sourceTrack||this.mediaTrack;if(!n)return;let a=n.getConstraints(),c=!1;!T(e)&&e!==this.profile.echoCancellation&&(this.profile.echoCancellation=e,a.echoCancellation=e,c=!0),!T(t)&&t!==this.profile.noiseSuppression&&(this.profile.noiseSuppression=t,a.noiseSuppression=t,c=!0),!T(r)&&r!==this.profile.autoGainControl&&(this.profile.autoGainControl=r,a.autoGainControl=r,c=!0),c&&(te||Ce?yield n.applyConstraints(a).catch(l=>this._log.warn("update3A failed: ",l)):this.deviceId&&(yield this.recapture(this.deviceId,!0)))})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&v.addEnum({key:502700,value:2})}setAudioVolume(e){super.setAudioVolume(0),Ee&&this.player.setMuted(!0),this.earMonitorGainNode.node||(this.earMonitorGainNode.setNode(Se().createGain()),this._output.setNode(Se().destination)),this.earMonitorGainNode.node.gain.value=e}enableTrackANS(e){return this.update3A({noiseSuppression:e})}enableTrackAEC(e){if(this.sourceTrack&&!(Ce||Ee))return this.update3A({echoCancellation:e})}addDenoiser(e){var t;if(je<=92&&((t=this.trackSettings)==null?void 0:t.sampleRate)!==48e3){this._log.warn("denoiser only support sampleRate 48000 before chrome 93");return}v.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.enableTrackANS(!1)}mixAudioReference(e,t){if(this.mixedAudioReferenceMap.has(t))return;this.log.info(`mixAudioReference() => ${t}`);let r=wn(e);if(!r)return;let s=new Ue,n=Se().createGain();n.gain.value=1;let a=new Ue;s.pipeTo(a).pipeTo(this.pipeline.mixNode),s.setNode(r),a.setNode(n),this.mixedAudioReferenceMap.set(t,[s,a])}unMixAudioReference(e){let[t,r]=this.mixedAudioReferenceMap.get(e)||[];t&&(this.log.info(`unMixAudioReference() => ${e}`),t.deleteNode(),r==null||r.deleteNode(),this.mixedAudioReferenceMap.delete(e))}setAudioReferenceVolume(e,t){let[r,s]=this.mixedAudioReferenceMap.get(e)||[];s!=null&&s.node&&(s.node.gain.value=t/100,this.log.info(`setAudioReferenceVolume() => ${e} ${s.node.gain.value}`))}addAudioProcessor(e,t,r){this.pipeline.silentNode.setNode(r),this.pipeline.mixNode.setNode(t),this.pipeline.aec.setNode(e)}removeDenoiser(e){if(this.pipeline.denoiser.node===e)return this.pipeline.denoiser.deleteNode(),this.enableTrackANS(!0)}removeAudioProcessor(e){this.pipeline.aec.node===e&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode())}close(){this.mixedAudioReferenceMap.forEach(([e,t])=>{e.deleteNode(),t.deleteNode()}),this.mixedAudioReferenceMap.clear(),this.pipeline.remove(),this.earMonitorGainNode.deleteNode(),this._output.deleteNode(),ve.off("audioInputAdded",this.handleMicrophoneAdded,this),ve.off("audioInputRemoved",this.handleMicrophoneRemoved,this),S.off(C.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this),super.close()}recapture(e,t=!1){return f(this,null,function*(){try{yield we(o.prototype,this,"recapture").call(this,e,t)}catch(r){let s=(yield It()).find(n=>n.deviceId!==e);if(s)yield we(o.prototype,this,"recapture").call(this,s.deviceId);else throw r}})}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduceRight((t,r)=>r?r({frame:t,ntp:Fi()}):t,e):e}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}get enableEncryptFrame(){return this.manager&&!!this.manager.encodePipeline[0]}handleAudioContextLongSuspended({isSuspended:e}){if(this.pipeline.isProcessEnabled)if(e){this.isAudioContextLongSuspended=!0,this.log.warn(`context has suspended for ${Pu/1e3} seconds, change to source audio${Bt?"":", non-Safari"}`);let t=this.sourceTrack||this.mediaTrack;t&&this.setOutputMediaStreamTrack(t)}else this.isAudioContextLongSuspended=!1,this.log.warn("context has resumed, change to processed audio"),this.pipeline.track&&this.setOutputMediaStreamTrack(this.pipeline.track)}setOutputMediaStreamTrack(e){if(this.isAudioContextLongSuspended){let t=this.sourceTrack||this.mediaTrack;t&&(e=t)}super.setOutputMediaStreamTrack(e)}};function ed(o,i=!1){let e=new DataView(o),t=[],r=0;for(;r<e.byteLength;){let s=0;if(r+4<=e.byteLength&&e.getUint8(r)===0&&e.getUint8(r+1)===0&&e.getUint8(r+2)===0&&e.getUint8(r+3)===1)s=4;else if(r+3<=e.byteLength&&e.getUint8(r)===0&&e.getUint8(r+1)===0&&e.getUint8(r+2)===1)s=3;else{r+=1;continue}let n=-1;for(let m=r+s;m<e.byteLength;m+=1){if(m+4<=e.byteLength&&e.getUint8(m)===0&&e.getUint8(m+1)===0&&e.getUint8(m+2)===0&&e.getUint8(m+3)===1){n=m;break}if(m+3<=e.byteLength&&e.getUint8(m)===0&&e.getUint8(m+1)===0&&e.getUint8(m+2)===1){n=m;break}}let a=n===-1?e.byteLength:n,c=a-r,l=new ArrayBuffer(c),h=new DataView(l);for(let m=0;m<c;m+=1)h.setUint8(m,e.getUint8(r+m));t.push(new sr(h,i)),r=a}return t}var sr=class{constructor(i,e=!1){this.dataView=i;this.isSEI&&(e?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let{seiPayloadStartIndex:i}=this,e=this.dataView.byteLength-2,t=[],r=0;for(let n=i;n<=e;n++){let a=this.dataView.getInt8(n);switch(a){case 0:case 1:case 2:case 3:r===2&&(t.push(3),r=0),a===0?r+=1:r=0,t.push(a);break;default:r=0,t.push(a);break}}t.push(this.dataView.getInt8(this.dataView.byteLength-1));let s=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=s}removePreventionByte(){let{seiPayloadStartIndex:i}=this,e=this.dataView.byteLength-1,t=[],r=0;for(let n=i;n<=e;n++)switch(this.dataView.getInt8(n)){case 0:r++,t.push(this.dataView.getInt8(n));break;case 3:r!==2&&t.push(this.dataView.getInt8(n)),r=0;break;default:t.push(this.dataView.getInt8(n)),r=0;break}let s=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=s}get seiPayloadStartIndex(){let i=6;for(let e=6;e<this.dataView.buffer.byteLength&&(i+=1,this.dataView.getUint8(e)===255);e+=1);return i}get seiPayloadType(){return this.isSEI?this.dataView.getUint8(5):null}get seiPayload(){if(!this.isSEI)return null;let i=0,e=6;for(let n=6;n<this.dataView.buffer.byteLength;n+=1){let a=this.dataView.getUint8(n);if(e+=1,a===255)i+=255;else{i+=a;break}}let t=new ArrayBuffer(i),r=new DataView(t),s=e;for(let n=0;n<t.byteLength;n+=1)r.setInt8(n,this.dataView.getInt8(s+n));return r}get naluType(){let i=this.getStartCodeLength();return i>=this.dataView.byteLength?0:this.dataView.getUint8(i)&31}getStartCodeLength(){return this.dataView.byteLength>=4&&this.dataView.getUint8(0)===0&&this.dataView.getUint8(1)===0&&this.dataView.getUint8(2)===0&&this.dataView.getUint8(3)===1?4:this.dataView.byteLength>=3&&this.dataView.getUint8(0)===0&&this.dataView.getUint8(1)===0&&this.dataView.getUint8(2)===1?3:0}get isIDR(){return this.naluType===5}get isSPS(){return this.naluType===7}get isPPS(){return this.naluType===8}get isSEI(){return this.naluType===6}};var td=class{constructor(){d(this,"_seiMessageList",[]);d(this,"_smallSeiMessageList",[]);d(this,"_seiPayloadType",243)}encodeSEINalu(i){let e=i.byteLength,t=parseInt(String(e/255),10),r=e%255,s=[];s.push(0,0,0,1,6,this._seiPayloadType);for(let a=0;a<t;a++)s.push(255);s.push(r);let n=new DataView(i);return s.push(...new Uint8Array(n.buffer)),s.push(128),new sr(new DataView(new Uint8Array(s).buffer),!0)}sendSEI(i,e){e!=null&&e.seiPayloadType&&(this._seiPayloadType=e.seiPayloadType),this._seiMessageList.push(i),e!=null&&e.small&&this._smallSeiMessageList.push(i)}isEmpty(){return!this._seiMessageList.length}getNaluCount(i){let e=0,t=0,r=new DataView(i);for(let s=0;s<i.byteLength;s++)switch(r.getUint8(s)){case 0:e++;break;case 1:(e===2||e===3)&&t++,e=0;break;default:e=0;break}return t}encode(i,e){let t=e?this._smallSeiMessageList:this._seiMessageList;if(t.length>0&&i.data.byteLength>0){let s=9-this.getNaluCount(i.data);if(s<=0)return 0;let n=t.splice(0,s).reverse().map(this.encodeSEINalu.bind(this)),a=n.reduce((u,_)=>u+_.dataView.byteLength,0),c=new ArrayBuffer(a+i.data.byteLength),l=new DataView(c),h=new DataView(i.data),m=0;for(let u=0;u<n.length;u++)for(let _=0;_<n[u].dataView.byteLength;_++)l.setInt8(m++,n[u].dataView.getInt8(_));for(let u=0;u<i.data.byteLength;u++)l.setInt8(m++,h.getInt8(u));return i.data=c,n.length}return 0}};var kr=class kr extends fi{constructor(e,t=4){super(t,it);d(this,"profile",O({},pr));d(this,"avoidCropping",!1);d(this,"_scaleResolutionDownBy");d(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0,framesCaptured:0});d(this,"small");d(this,"isNeedToSetBandwidth");d(this,"muteImage");d(this,"manager");d(this,"_seiCodec",new td);this.manager=e;let r=()=>{var s;if(this.isAllowed2k4k(this.profile))this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1});else{let n=Vt(((s=this.room)==null?void 0:s.sdkAppId)||0)?fa:pa;this.log.warn(`Resolution is reset to 1080p, need to upgrade ability here ${n}`),this.setProfile(L(O({},this.profile),{width:1920,height:1080})),this.applyProfile()}};this.on("input-media-track-changed",r),this.on("publish",r),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(!(!bi||!this.mediaTrack))return this.mediaTrack.getSettings().facingMode}get contentHint(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)||""}get isQosClearFirst(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)==="detail"}get hasSmall(){var e;return!!((e=this.manager)!=null&&e.hasSmall)}setMute(e){return f(this,null,function*(){var t,r,s;if(re(e)){if(this.muteImage===e)return;yield(t=this.manager)==null?void 0:t.deleteWatermark("mute"),yield(r=this.manager)==null?void 0:r.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:e,fillVideo:!0}),this.muteImage=e,we(kr.prototype,this,"setMute").call(this,!1)}else this.muteImage&&(yield(s=this.manager)==null?void 0:s.deleteWatermark("mute"),this.muteImage=void 0),we(kr.prototype,this,"setMute").call(this,e)})}capture(a){return f(this,arguments,function*({deviceId:e,facingMode:t,useExactDeviceId:r=!0,customSource:s,retryWhenExactFailed:n=!0}){let c={audio:!1,video:!0,facingMode:t||this.facingMode,cameraId:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:r,retryWhenExactFailed:n,customSource:s};if(c.facingMode==="environment"){let l=yield this.getDeviceIdWhenUsingBackCamera();l&&(c.cameraId=l)}return we(kr.prototype,this,"capture").call(this,c)})}setProfile(e){var r;let t=this.fallbackProfile(e);if(t.bitrate&&(this.isNeedToSetBandwidth=t.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile))super.setProfile(t);else{let s=Vt(((r=this.room)==null?void 0:r.sdkAppId)||0)?fa:pa;this.log.warn(`Resolution is reset to 1080p, need to upgrade ability here ${s}`),super.setProfile(L(O({},this.profile),{width:1920,height:1080}))}}applyProfile(){return f(this,null,function*(){var a;if(!this.mediaTrack)return;let{width:e=0,height:t=0}=(this.sourceTrack||this.mediaTrack).getSettings(),r=e*t,s=this.settings,n=s.height!==this.profile.height||s.width!==this.profile.width||s.frameRate!==this.profile.frameRate;if(n&&(et===16&&this.deviceId?yield this.recapture(this.deviceId):(yield(a=this.sourceTrack||this.mediaTrack)==null?void 0:a.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}),this.manager&&this.manager.changeInput(this)),this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1})),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth){this.isNeedToSetBandwidth=!1;let{width:c=0,height:l=0}=(this.sourceTrack||this.mediaTrack).getSettings(),h=c*l;if(n&&h&&r&&h===r){this.log.warn("set bandwidth failed: resolution is not changed");return}return this.room.setBandWidth({bandwidth:this.profile.bitrate,type:p.VIDEO,videoType:p.BIG})}})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},t=this.sourceTrack||this.mediaTrack;return bi&&t&&Object.assign(e,t.getSettings()),e}get scaleResolutionDownBy(){return this._scaleResolutionDownBy?this._scaleResolutionDownBy:Go(this.settings,this.profile)}isAllowed2k4k(e){var t;return!this.room||!this.room.scheduleResult||this.isScreen||e.height*e.width<2560*1440?!0:((t=this.room.scheduleResult.trtcAutoConf)==null?void 0:t["2k4k"])===1}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}switchDevice(e){return f(this,null,function*(){try{if(!this.isNeedToSwitchDevice(e)&&!this.isUseCustomSource)return;let t={useExactDeviceId:!0,retryWhenExactFailed:!1};e==="user"||e==="environment"?t.facingMode=e:t.deviceId=e,this.sourceTrack&&this.sourceTrack.stop(),yield this.capture(t),S.emit(C.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(t){throw this.log.error(`switch camera failed ${t}`),this.deviceId&&this.recapture(this.deviceId),t}})}getDeviceIdWhenUsingBackCamera(){return f(this,null,function*(){let e;try{if(sn&&!Zo&&fu){let r=(yield At(!0)).map(n=>{var a;return L(O({},n),{capabilities:(a=n.getCapabilities)==null?void 0:a.call(n)})}).filter(n=>{var a,c;return(c=(a=n.capabilities)==null?void 0:a.facingMode)==null?void 0:c.includes("environment")}),s=r[0];r.forEach(n=>{var h,m,u,_;let{capabilities:a}=n,c=(h=a.width)!=null&&h.max&&((m=a.height)!=null&&m.max)?a.width.max*a.height.max:0,l=(u=s.capabilities.width)!=null&&u.max&&((_=s.capabilities.height)!=null&&_.max)?s.capabilities.width.max*s.capabilities.height.max:0;c>l&&(s=n)}),s!=null&&s.capabilities&&(this._log.info("use max resolution back camera",s),e=s.deviceId)}}catch(t){this._log.warn("get max res camera failed",t)}return e})}updateSmallConfig(e){var r,s;this._log.info(`update small stream config: ${JSON.stringify(e)}`);let t=!this.small;this.small=this.fallbackProfile(e,!0),(r=this.manager)==null||r.update(),t&&((s=this.room)==null||s.enableSmall(!0)),this.log.info("update small stream config success")}fallbackProfile(e,t=!1){let r=e.width>e.height,s=O({},e);return e.width*e.height<=160*120&&fe&&We&&(this.log.warn(`${t?"small ":""}resolution is ${e.width}*${e.height}, fallback to 240*180 for android chrome`),s.width=r?240:180,s.height=r?180:240,s.bitrate=Math.max(e.bitrate,150)),e.width*e.height>1280*720&&Ul&&(s.width=r?1280:720,s.height=r?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),cn(Tt,"14.3")&&Ll(Tt,"14.0",!0)&&this.on("7",()=>{let n=this.profile.width>this.profile.height;this.profile.width*this.profile.height>640*480?(this.profile.width=n?640:480,this.profile.height=n?480:640,this.log.warn("reduce the resolution to 480p on iOS 14.0 ~ 14.2")):this.profile.width*this.profile.height>640*360&&(this.profile.width=n?640:360,this.profile.height=n?360:640,this.log.warn("reduce the resolution to 360p on iOS 14.0 ~ 14.2"))}),!t&&this.avoidCropping&&(We||te)&&!dn()&&e.width*e.height<=640*360&&e.width/e.height===16/9&&(this._scaleResolutionDownBy=1280/e.width,e.width=1280,e.height=720,this.log.warn(`capture 720p, scale: ${this._scaleResolutionDownBy}`)),s}stopSmall(){var e,t;this.small&&(delete this.small,(e=this.manager)==null||e.update(),(t=this.room)==null||t.enableSmall(!1))}listenDeviceChange(){ve&&!ve.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&ve.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return f(this,null,function*(){if(e.deviceId===this.deviceId){let t=this.recaptureMode===1;if(this.log.warn(`RecaptureMode: ${_s[this.recaptureMode]}. Current camera is lost: ${JSON.stringify(e)}`),this.recaptureMode===0){Ne(this.userId,{eventId:2003,param1:7,streamType:2});let r=yield At();r[0]?this.recapture(r[0].deviceId):t=!0}t&&ve.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return f(this,null,function*(){this.recaptureMode===1&&e.deviceId!==this.deviceId||(ve.off("videoInputAdded",this.handleCameraAdded,this),this.log.warn(`camera added: ${JSON.stringify(e)}`),this.recapture(e.deviceId))})}encodeFrame(e,t){if(!this.manager)return e;let r=t?8:this.mediaType;return this.manager.encodePipeline.reduceRight((s,n)=>n?n({frame:s,mediaType:r}):s,e)}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}play(e,t){return T(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,t)}close(){ve.off("videoInputAdded",this.handleCameraAdded,this),ve.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return f(this,null,function*(){try{yield we(kr.prototype,this,"recapture").call(this,e)}catch(t){let r=(yield At()).find(s=>s.deviceId!==e);if(r)yield we(kr.prototype,this,"recapture").call(this,r.deviceId);else throw t}})}setContentHint(e){this.mediaTrack&&"contentHint"in this.mediaTrack&&(this.mediaTrack.contentHint!==e&&(this.log.info(`setContentHint ${e}`),this.mediaTrack.contentHint=e),this.outMediaTrack&&this.outMediaTrack.contentHint!==e&&(this.outMediaTrack.contentHint=e))}setRotation(e){this.manager&&(this.isScreen||T(e)||e!==this.rotation&&(this.rotation=e,this.manager.rotation=e))}};M([Ct(function(e){this.setContentHint(e.contentHint||"motion")})],kr.prototype,"capture",1);var ze=kr;var yh={};Vi(yh,{REPORT_TYPE:()=>Wo,buildSSOPackage:()=>Wi,bytes2ms:()=>xm,calculateScaleResolutionDownNumber:()=>Go,concatArrayBuffers:()=>La,convertObjectNumberToInt:()=>Xs,copyProperties:()=>Lm,deepClone:()=>Wr,deepCloneBasic:()=>Na,deepMerge:()=>ti,delay:()=>Ge,fibonacci:()=>Jr,formatedTime:()=>qm,getConstructorName:()=>Vo,getContainerFromElement:()=>Wm,getEnv:()=>km,getFirst16Bits:()=>jm,getInternalVersion:()=>$m,getLast16Bits:()=>xa,getLoggerUrl:()=>Gi,getMediaStreamTrackInfo:()=>wa,getMuteStateFromFlag:()=>ei,getNetworkType:()=>Da,getNumNetworkType:()=>qr,getReconnectionTimeout:()=>Kt,getStringByteLength:()=>js,getTurnServer:()=>Gm,getUint32Version:()=>Oa,getValueType:()=>Oe,getViewListFromView:()=>Ho,glog:()=>Al,ipv4ToUint32:()=>Bo,isArray:()=>Ae,isAudioWorkletSupported:()=>Bm,isBoolean:()=>he,isConstructor:()=>jr,isEmpty:()=>Fo,isFunction:()=>me,isLangChinese:()=>Zt,isMediaStreamTrack:()=>Vm,isNumber:()=>Q,isObject:()=>yt,isOverseaSdkAppId:()=>Vt,isPlainObject:()=>dt,isPortrait:()=>Cl,isPromise:()=>Er,isRemoteTrack:()=>Fm,isRotate90Or270:()=>bt,isSetSinkIdSupported:()=>Hm,isString:()=>re,isUndefined:()=>T,loadImage:()=>$o,loadVideo:()=>Jm,ms2bytes:()=>Um,ms2samples:()=>Il,normalizeUrl:()=>Pa,performanceNow:()=>V,promiseAny:()=>Xr,samples2ms:()=>Sl,setNetworkTypeFromWebRTC:()=>Ma,stringify:()=>_t,stringifyIncludeValue:()=>Js,throttlePromise:()=>ka});var gS=[-1,-1,1,-1,-1,1,1,1],TS=[0,0,1,0,0,1,1,1];var Pr=class Pr extends j{constructor(e,t){super();this.context=e;d(this,"name");d(this,"input");d(this,"output");d(this,"texture");d(this,"ctx2d",null);d(this,"fbo");d(this,"width",0);d(this,"height",0);d(this,"x",0);d(this,"y",0);d(this,"program");d(this,"vertexShader");d(this,"fragmentShader");d(this,"totalFrames",0);d(this,"dropFrames",0);d(this,"matchInputSize",!0);d(this,"texCoordBuffer");d(this,"positionBuffer");d(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0});d(this,"cost",0);d(this,"_canvas",null);d(this,"_image");d(this,"log");if(this.context.on("disconnect",this.close,this),this.name=t.name,this.log=t.logger,this.matchInputSize=t.matchInputSize!==!1,this.width=t.width||e.width,this.height=t.height||e.height,this._image=t.image,e instanceof Qe){e.ctx&&t.create2d&&(typeof OffscreenCanvas=="function"&&et!==16?this._canvas=new OffscreenCanvas(this.width,this.height):(this._canvas=document.createElement("canvas"),this._canvas.width=this.width,this._canvas.height=this.height),this.ctx2d=this._canvas.getContext("2d"),this._image=this._canvas);return}try{let r=e.ctx;this.texCoordBuffer=this.createBuffer(TS),this.positionBuffer=this.createBuffer(gS),t.createTexture!==!1&&(this.texture=r.createTexture(),this.useTexture(),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.pixelStorei(r.UNPACK_ALIGNMENT,1)),t.useFbo&&(this.fbo=r.createFramebuffer(),this.useBufferFrame(),this.useTexture(),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,this.width,this.height,0,r.RGBA,r.UNSIGNED_BYTE,null),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,this.texture,0)),t.useDefaultProgram?this.program=e.defaultProgam:(t.vertexShaderSource||t.fragmentShaderSource)&&(this.vertexShader=t.vertexShaderSource?e.createShader(r.VERTEX_SHADER,t.vertexShaderSource):e.defaultVShader,this.fragmentShader=t.fragmentShaderSource?e.createShader(r.FRAGMENT_SHADER,t.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(r){this.context.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${r.message||r}`}))}}get image(){return this._image}set image(e){this._image=e}createFramebuffer(e){let t=this.context.ctx,r=t.createFramebuffer();return t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0),r}connect(e,...t){return e.addInput(this,...t),this.output=e,e}addInput(e,...t){this.input=e,this.matchInputSize&&e.width&&e.height&&this.resize(e.width,e.height)}requestFrame(e){let t=Date.now();if(this.context instanceof He&&this.render(e)||this.context instanceof Qe&&this.render2d(e))this.totalFrames++;else return!1;return this.cost=Date.now()-t,!0}render2d(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?this.draw2d(this.input.image,0,0,this.width,this.height):!1}update(e=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 He){let r=this.context.ctx;r.deleteBuffer(this.texCoordBuffer),r.deleteBuffer(this.positionBuffer),this.fbo&&r.deleteFramebuffer(this.fbo),this.texture&&r.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&r.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&r.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&r.deleteProgram(this.program)}this._canvas&&(this._canvas.width=0,this._canvas.height=0,this.ctx2d=null),this.removeAllListeners()}useTexture(){this.useTextures(this.texture)}useInputTexture(){var e;this.useTextures((e=this.input)==null?void 0:e.texture)}useTextures(...e){let t=this.context.ctx;e.forEach((r,s)=>{r&&(t.activeTexture(t.TEXTURE0+s),t.bindTexture(t.TEXTURE_2D,r))})}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}createBuffer(e){let t=this.context.ctx,r=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,r),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW),r}setTexBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}setPosBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}changeBufferData(e,t){let r=this.context.ctx;r.bindBuffer(r.ARRAY_BUFFER,e),r.bufferData(r.ARRAY_BUFFER,new Float32Array(t),r.STATIC_DRAW)}setAttributes(...e){let t=this.context.ctx;e.forEach((r,s)=>{t.enableVertexAttribArray(s),t.bindBuffer(t.ARRAY_BUFFER,r),t.vertexAttribPointer(s,2,t.FLOAT,!1,0,0)})}getVertexPoint(e,t){return[e/this.width*2-1,t/this.height*2-1]}layout2texCoords(e){return[...this.getVertexPoint(e.x,e.y),...this.getVertexPoint(e.x+e.width,e.y),...this.getVertexPoint(e.x,e.y+e.height),...this.getVertexPoint(e.x+e.width,e.y+e.height)]}resize(e,t){if(!(this.width===e&&this.height===t)){if(this.width=e,this.height=t,this._canvas&&(this._canvas.width=e,this._canvas.height=t),this.texture&&this.fbo){this.useTexture();let r=this.context.ctx;r.texImage2D(r.TEXTURE_2D,0,r.RGBA,e,t,0,r.RGBA,r.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(e,t)}}draw(e,t){this.setAttributes(e||this.positionBuffer,t||this.texCoordBuffer);let r=this.context.ctx;r.drawArrays(r.TRIANGLE_STRIP,0,4)}draw2d(e,t,r,s,n,a,c,l,h){let m=!T(a)&&!T(c)&&!T(l)&&!T(h);return this.ctx2d&&e?(e instanceof ImageData?(m?this.ctx2d.putImageData(e,t,r,a,c,l,h):this.ctx2d.putImageData(e,t,r),this.emit(Pr.RENDER,this.ctx2d.canvas)):(m?this.ctx2d.drawImage(e,a,c,l,h,t,r,s,n):this.ctx2d.drawImage(e,t,r,s,n),this.emit(Pr.RENDER,e)),typeof VideoFrame!="undefined"&&e instanceof VideoFrame&&e.close(),!0):!1}drawBackGround2d(e){this.ctx2d&&(this.ctx2d.save(),this.ctx2d.fillStyle=e,this.ctx2d.fillRect(0,0,this.width,this.height),this.ctx2d.restore())}getInfo(){var m;let{totalFrames:e,x:t,y:r,width:s,height:n,name:a,cost:c}=this,l=Date.now(),h=(e-this.lastInfo.totalFrames)/((l-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:r,width:s,height:n,timestamp:l,fps:h,name:a,cost:c},O({parent:(m=this.input)==null?void 0:m.getInfo()},this.lastInfo)}createTexture(e){let t=this.context.ctx,r=t.createTexture();return this.useTextures(r),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.pixelStorei(t.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),r}};d(Pr,"RENDER","render"),M([be(j.INIT,"connected",{sync:!0})],Pr.prototype,"connect",1),M([be("connected",j.INIT,{ignoreError:!0,sync:!0})],Pr.prototype,"disconnect",1),M([be([],"closed",{sync:!0})],Pr.prototype,"close",1);var Ve=Pr;var ES=ue(Wu(250),$n(()=>performance.now()),rr());var Af=o=>i=>{let e=performance.now();ue(ES,Jc(t=>t-e<o),or(1))(i)};var IS=[0,1,1,1,0,0,1,0],fo=class extends Ve{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 Qe?this.ctx2d=e.ctx||null:e.available&&(t!=null&&t.mirrorUpAndDown)&&this.setTexBuffer(IS)}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 He){let r=this.context.ctx.getError();r&&this.context.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:5,message:`${this.name} req ${this._sequence} render ${this.totalFrames} faild ${r}`}))}},{fps:this.context.frameRate})}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),this.emit(Ve.RENDER,this.context._canvas),!0):!1}addInput(e,...t){super.addInput(e,...t),this.start(this.context.frameRate)}update(e=0){this.state!=="closed"&&(this._intervalId&&(oe.clearTask(this._intervalId),this._intervalId=0,e===1&&(this.log.info(`${this.name} use requestVideoFrameCallback`),this.checkVisibilityChange=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info(`${this.name} use timer`),document.removeEventListener("visibilitychange",this.checkVisibilityChange))},document.addEventListener("visibilitychange",this.checkVisibilityChange))),this.requestFrame(this._sequence++))}removeInput(e){super.removeInput(e),oe.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}close(){super.close(),oe.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},gs=class extends fo{constructor(e,t){super(e,t);d(this,"_videoTrack");d(this,"_muteOb");d(this,"_closedOb",le(this,"closed"));d(this,"_subscription");d(this,"_canvasContainer");Number(Xi)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e.canvas.captureStream().getVideoTracks(),this._muteOb=le(this._videoTrack,"mute"),ue(le(this._videoTrack,"ended"),Pe(this._closedOb),Te(()=>{this.context.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){this._subscription=ue(this._muteOb,Pe(this._closedOb),mo(Af(5e3)),Gt(()=>{var e;return!!((e=this._videoTrack)!=null&&e.muted)&&!document.hidden}),Te(()=>{this.context.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:7,message:"video track muted"}))}))}disableCheckMute(){var e;(e=this._subscription)==null||e.dispose()}get videoTrack(){return this._videoTrack}putCanvasIntoDom(){!this.context._canvas||!this._canvasContainer||document.getElementById(this.context._canvas.id)||(this.log.info(`${this.name} put canvas to body`),document.body.appendChild(this._canvasContainer),this._canvasContainer.appendChild(this.context._canvas))}render(e){return this.putCanvasIntoDom(),super.render(e)}render2d(e){return this.putCanvasIntoDom(),super.render2d(e)}close(){var e,t;super.close(),(e=this._videoTrack)==null||e.stop(),delete this._videoTrack,(t=this._canvasContainer)==null||t.remove()}},id=class extends gs{render(i){var t;let e=!!((t=this.input)!=null&&t.requestFrame(i));if(this.context._canvas2d){let r=this.context._canvas2d.getContext("2d");r.clearRect(0,0,this.context._canvas2d.width,this.context._canvas2d.height),r.drawImage(this.context._canvas,0,0,this.context._canvas2d.width,this.context._canvas2d.height)}return e}};var rd=class extends gs{constructor(e,t,r){super(e,{name:"smallDestination",logger:r});this.resolution=t}resize(e,t){let r,s=e*t,n=this.resolution.width*this.resolution.height;this.log.info(`big res: ${e}*${t} small res: ${this.resolution.width}*${this.resolution.height} `),s>n?r=s/n:(this.log.warn(`Small stream resolution is not smaller than big stream, which is invalid. big: ${e} * ${t} small: ${this.resolution.width} * ${this.resolution.height}`),r=s/(160*120)),super.resize(e/Math.sqrt(r),t/Math.sqrt(r))}};var qn=class extends Ve{constructor(e,t){super(e,O({name:"imageSource"},t));d(this,"_lastImage");d(this,"_totalFrames",0);d(this,"_autoResize",!1);d(this,"_canvasRendered");d(this,"videoCallbackId",0);d(this,"waitingFirstFrame",!0);d(this,"shouldUpdate",!0);this._autoResize=(t==null?void 0:t.autoResize)!==!1,et===16&&(this._canvasRendered=ot(),ue(this._canvasRendered,Fn(this._image),Or(r=>r instanceof HTMLCanvasElement?le(r,"rendered"):Hn()),Pe(le(this,"closed")),Te(()=>{this.update()})))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){if(!this.shouldUpdate)return;let e=this.image;this.videoCallbackId&&e.cancelVideoFrameCallback(this.videoCallbackId),Ki()&&!document.hidden&&(this.videoCallbackId=e.requestVideoFrameCallback((t,r)=>{this.waitingFirstFrame&&this.onFirstFrame(),document.hidden||(this._totalFrames=r.presentedFrames,this.update(1))}))}_render(e,t){var a;let{width:r,height:s}=this,{image:n}=this;if(n instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(),{videoWidth:r,videoHeight:s}=n,!r||!s)return!1;n.width=r,n.height=s}else if(n instanceof HTMLImageElement||n instanceof ImageData||n instanceof ImageBitmap){if({width:r,height:s}=n,n!==this._lastImage)this._lastImage=n;else if(r===this.width&&s===this.height)return!0}else n instanceof HTMLCanvasElement||n instanceof OffscreenCanvas?({width:r,height:s}=n,this._lastImage=n):typeof VideoFrame!="undefined"&&n instanceof VideoFrame&&({displayWidth:r,displayHeight:s}=n,(a=this._lastImage)==null||a.close(),this._lastImage=n);if(!this._autoResize)return!0;if(this.width===r&&this.height===s&&this.totalFrames){if(t){this.useTexture();let c=this.context.ctx;c.texSubImage2D(c.TEXTURE_2D,0,0,0,c.RGBA,c.UNSIGNED_BYTE,n)}}else{if(t){this.useTexture();let c=this.context.ctx;c.texImage2D(c.TEXTURE_2D,0,c.RGBA,c.RGBA,c.UNSIGNED_BYTE,n)}this.resize(r,s)}return!0}get image(){return this._image}set image(e){var t;(t=this._canvasRendered)==null||t.next(e),this._image=e}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},Jn=class extends qn{constructor(e,t,r){super(e,r);this._player=t;this.name="videoPlayerSource",ue(le(this._player,K.PLAYER_STATE_CHANGED),Pe(le(this,"closed")),Gt(({state:s})=>s==="PLAYING"),Te(()=>{this.tryVideoFrameCallback()}))}get image(){return this._player.element}},Wt=class extends Jn{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(i,e,t){super(i,new it({id:t.name,track:e,muted:!0,container:null,objectFit:"contain",log:t.logger}),t),this.name="videoTrackSource",this._player.play()}replaceTrack(i){this.waitingFirstFrame=!0,this._player.setTrack(i),this._player.play()}close(){super.close(),this._player.stop()}},od=class extends Ve{constructor(e,t,r){super(e,L(O({name:"textSource"},r),{create2d:!0}));d(this,"hasChange",!0);d(this,"content","");this.ctx2d.textBaseline="top",this.content=t.content||"",t.font&&(this.font=t.font),t.color&&(this.color=t.color)}set font(e){this.ctx2d&&(this.ctx2d.font=e,this.hasChange=!0)}get font(){var e;return((e=this.ctx2d)==null?void 0:e.font)||""}set color(e){this.ctx2d&&(this.ctx2d.fillStyle=e,this.hasChange=!0)}get color(){var e;return((e=this.ctx2d)==null?void 0:e.fillStyle)||""}render2d(e){return this.ctx2d&&this.hasChange?(this.ctx2d.clearRect(0,0,this.width,this.height),this.drawMultilineText(0,0),this.hasChange=!1,!0):!1}render(e){return!1}resize(e,t){if(!this.ctx2d)return;let{color:r,font:s}=this;super.resize(e,t),this.color=r,this.font=s}drawMultilineText(e=0,t=0,r=1.2){if(!this.ctx2d)return;let s=this.ctx2d.measureText(this.content);t+=s.fontBoundingBoxAscent||s.actualBoundingBoxAscent||0;let n=this.font.match(/(\d+)px/),c=(n?parseInt(n[1],10):16)*r,l=this.content.split(`
34
+ `);for(let h=0;h<l.length;h++)this.ctx2d.fillText(l[h],e,t+h*c)}};var CS=`
35
35
  // \u9876\u70B9\u7740\u8272\u5668
36
36
  attribute vec4 a_position;
37
37
  attribute vec2 a_texCoord;
@@ -41,7 +41,7 @@ void main() {
41
41
  gl_Position = a_position;
42
42
  v_texCoord = a_texCoord;
43
43
  }
44
- `,gS=`
44
+ `,RS=`
45
45
  // \u7247\u5143\u7740\u8272\u5668
46
46
  precision mediump float;
47
47
  varying vec2 v_texCoord;
@@ -49,28 +49,38 @@ uniform sampler2D u_texture;
49
49
 
50
50
  void main() {
51
51
  gl_FragColor = texture2D(u_texture, v_texCoord);
52
- } `;var _o=class extends j{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}get canvas(){return this._canvas}set width(e){this._canvas&&(this._canvas.width=e)}get width(){var e;return((e=this._canvas)==null?void 0:e.width)||0}set height(e){this._canvas&&(this._canvas.height=e)}get height(){var e;return((e=this._canvas)==null?void 0:e.height)||0}setSize(e,t){this._canvas&&(this._canvas.width=e,this._canvas.height=t)}createVideoTrackSource(e,t){return new Wt(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new ps(this,e)}createVideoImageSource(e,t){return new Hn(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new $n(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}createTextSource(e,t){return new Zd(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}};c(_o,"_ids",0);var TS={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},fs=class fs extends _o{constructor(){super(...arguments);c(this,"defaultProgam");c(this,"defaultVShader");c(this,"defaultFShader");c(this,"ctx");c(this,"_canvas2d")}get canvas(){return this._canvas2d||this._canvas}create(e=!1){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${_o._ids++}`),e&&(this._canvas2d=document.createElement("canvas")),this.ctx=this._canvas.getContext("webgl2",TS),!this.ctx)throw new v({code:I.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,_S),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,gS),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new v({code:I.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})}destroy(e){let t="";return e&&(t=e.message,this.error=e,y.addFailedEvent({key:512702,error:e})),this.disconnect(),this.log.info(`video context destroy${t}`?`: ${t}`:""),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),e}set width(e){var t;(t=this.ctx)==null||t.viewport(0,0,e,this.height),super.width=e,this._canvas2d&&(this._canvas2d.width=e)}set height(e){var t;(t=this.ctx)==null||t.viewport(0,0,this.width,e),super.height=e,this._canvas2d&&(this._canvas2d.height=e)}setSize(e,t){var r;(r=this.ctx)==null||r.viewport(0,0,e,t),super.setSize(e,t),this._canvas2d&&(this._canvas2d.width=e,this._canvas2d.height=t)}createShader(e,t){let r=this.ctx,s=r.createShader(e);return r.shaderSource(s,t),r.compileShader(s),s}createProgram(e,t){let r=this.ctx,s=r.createProgram();return r.attachShader(s,e),r.attachShader(s,t),r.linkProgram(s),r.getProgramParameter(s,r.LINK_STATUS)||this.log.error(r.getProgramInfoLog(s)),s}};c(fs,"UNAVAILABLE","unavailable"),D([ye(j.INIT,"created",{sync:!0,fail(e){this.log.error("video gl context create failed",e.cause),y.addFailedEvent({key:512700,error:e.cause||e})},success(){this.log.info("video context created use webgl"),y.addSuccessEvent({key:512700})}})],fs.prototype,"create",1),D([ye("created",j.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(fs.UNAVAILABLE,e),this.removeAllListeners()}})],fs.prototype,"destroy",1);var Be=fs,Xe=class extends _o{constructor(){super(...arguments);c(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${_o._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:e.alpha,willReadFrequently:e.willReadFrequently}),!this.ctx)throw new v({code:I.VIDEO_MANAGER_ERROR,extraCode:2,message:"2d context not supported"});this._canvas.addEventListener("contextlost",()=>{this.log.error("2d context lost")}),this._canvas.addEventListener("contextrestored",()=>{this.log.warn("2d context restored")})}destroy(e){let t="";e&&(t=e.message,this.error=e,y.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(),y.addSuccessEvent({key:512703})}};D([ye(j.INIT,"created",{sync:!0,fail(e){this.log.error("video 2d context create failed",e.cause),y.addFailedEvent({key:512701,error:e.cause||e})},success(){this.log.info("video context created use 2d"),y.addSuccessEvent({key:512701})}})],Xe.prototype,"create",1),D([ye("created",j.INIT,{ignoreError:!0,sync:!0})],Xe.prototype,"destroy",1);function ES(o,i,e,t,r,s=!1){s&&([e,t]=[t,e]);let n={sWidth:o,sHeight:i,dWidth:e,dHeight:t,sx:0,sy:0,dx:0,dy:0};if(o===0||i===0)return n;switch(r){case void 0:case"fill":break;case"contain":{let a=Math.min(e/o,t/i);n.dWidth=o*a,n.dHeight=i*a,n.dx=(e-n.dWidth)/2,n.dy=(t-n.dHeight)/2;break}case"cover":{let a=Math.max(e/o,t/i),d=e/a,l=t/a;n.sx=(o-d)/2,n.sy=(i-l)/2,n.sWidth=d,n.sHeight=l;break}}return n}var Eh=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}get fillMode(){return this.layout.fillMode}get rotation(){return this.layout.rotation}get hidden(){return!!this.layout.hidden}},_s=class extends Pe{constructor(e,t){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:t});c(this,"inputs",[]);c(this,"backgroundColor","black")}addInput(e,t){let r=0,s=this.inputs.length;for(;r<s;){let a=Math.floor((r+s)/2);if(this.inputs[a].layout.zIndex<t.zIndex)r=a+1;else if(this.inputs[a].layout.zIndex>t.zIndex)s=a;else throw new Error(`input already exists at zIndex ${t.zIndex}`)}let n=new Eh(e,t);this.inputs.splice(r,0,n)}changeInputLayout(e,t){let r=this.inputs.findIndex(g=>g.node===e);if(r<0)return;let{x:s,y:n,width:a,height:d,zIndex:l,fillMode:u,rotation:h,hidden:p}=t;if(!T(l)&&this.inputs.some(g=>g.layout.zIndex===l&&g.node!==e))throw new Error(`input already exists at zIndex ${t.zIndex}`);let m=this.inputs[r];T(s)||(m.layout.x=s),T(n)||(m.layout.y=n),T(a)||(m.layout.width=a),T(d)||(m.layout.height=d),T(h)||(m.layout.rotation=h),T(p)||(m.layout.hidden=p),u&&(m.layout.fillMode=u),!T(l)&&l!==m.layout.zIndex&&(m.layout.zIndex=l,this.inputs.sort((g,E)=>g.layout.zIndex-E.layout.zIndex))}hasInput(e){return this.inputs.some(t=>t.node===e)}hasNoInput(){return this.inputs.length===0}resize(e,t){if(!this.matchInputSize){super.resize(e,t);return}let r=this.inputs.reduce((s,n)=>n?Object.assign(s,{width:Math.max(s.width,n.right),height:Math.max(s.height,n.bottom)}):s,{width:0,height:0});super.resize(r.width,r.height),this.context instanceof Be&&this.inputs.forEach(s=>{if(s){let n=this.layout2texCoords(s);s.positionBuffer?this.changeBufferData(s.positionBuffer,n):s.positionBuffer=this.createBuffer(n)}})}connect(e,...t){return super.connect(e,...t),this.drawBackGround2d(this.backgroundColor),this.matchInputSize&&this.resize(0,0),e}removeInput(e){this.inputs=this.inputs.filter(t=>t.node!==e),this.inputs.length===0&&this.drawBackGround2d(this.backgroundColor)}render(e){let t=this.context.ctx;if(t.clearColor(0,0,0,0),this.inputs.reduce((s,n)=>n.node.requestFrame(e)||s,!1)&&t){this.useProgram(),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let s=0;s<this.inputs.length;s++){let n=this.inputs[s];n&&(n.node.useTexture(),this.draw(n.positionBuffer))}return!0}return!1}render2d(e){if(this.inputs.forEach(t=>t.node.requestFrame(e)),this.ctx2d){this.drawBackGround2d(this.backgroundColor);for(let t=0;t<this.inputs.length;t++){let r=this.inputs[t];if(r.hidden)continue;let s=ES(r.node.width,r.node.height,r.width,r.height,r.fillMode,bt(r.rotation));this.draw2d(r.node.image,r.x+s.dx,r.y+s.dy,s.dWidth,s.dHeight,s.sx,s.sy,s.sWidth,s.sHeight)}return!0}return!1}debugLayout(e,t,r,s,n=!1){this.ctx2d&&(n&&([r,s]=[s,r]),this.ctx2d.save(),this.ctx2d.strokeStyle="red",this.ctx2d.lineWidth=2,this.ctx2d.strokeRect(e,t,r,s),this.ctx2d.restore())}getInfo(){let{totalFrames:e,x:t,y:r,width:s,height:n,name:a}=this,d=Date.now(),l=(e-this.lastInfo.totalFrames)/((d-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:r,width:s,height:n,timestamp:d,fps:l,name:a},M({parent:this.inputs.filter(u=>u).map(u=>u.node.getInfo())},this.lastInfo)}removeAllInputs(){this.inputs.forEach(e=>{var t;if(e.node.disconnect(),e.positionBuffer&&this.context instanceof Be)try{(t=this.context.ctx)==null||t.deleteBuffer(e.positionBuffer)}catch(r){}})}close(){super.close(),this.removeAllInputs()}};var SS=[1,0,0,0,1,1,0,1],Gt=class extends Pe{constructor(e,t,r,s){super(e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"transform",logger:t});c(this,"mirror",!1);c(this,"rotation",0);if(r&&(this.mirror=r),s&&(this.rotation=s),e instanceof Be)try{this.setTexBuffer(SS)}catch(n){e.destroy(new v({code:I.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${n.message||n}`}))}}draw2d(e,t,r,s,n){if(this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height),this.ctx2d.save(),this.mirror&&(this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0)),this.rotation===90?(this.ctx2d.translate(s,0),this.ctx2d.rotate(Math.PI/2),this.ctx2d.scale(n/s,s/n)):this.rotation===180?(this.ctx2d.translate(this.width,this.height),this.ctx2d.rotate(Math.PI)):this.rotation===270&&(this.ctx2d.translate(0,n),this.ctx2d.rotate(3*Math.PI/2),this.ctx2d.scale(n/s,s/n));let a=super.draw2d(e,t,r,s,n);return this.ctx2d.restore(),a}return!1}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}resize(e,t){bt(this.rotation)&&([e,t]=[t,e]),super.resize(e,t)}};var go=class extends _i{constructor(e,t=4){super(t,pt);c(this,"inputLocalVideoTracks",new Map);c(this,"inputLocalScreenTracks",new Map);c(this,"cameraNodeMap",new Map);c(this,"screenNodeMap",new Map);c(this,"textNodeMap",new Map);c(this,"imageNodeMap",new Map);c(this,"videoNodeMap",new Map);c(this,"endedIds",new Set);c(this,"videoContext");c(this,"mixNode");c(this,"destination");c(this,"manager");c(this,"stat");c(this,"_checkId",0);c(this,"autoSetFps",!0);this.manager=e,this.log.id+="mix",this.create2dVideoContext(),this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log}),this.destination.on(Pe.RENDER,r=>{this.emit("render",r)}),this.mixNode=new _s(this.videoContext,this.log),this.mixNode.matchInputSize=!1}listenDeviceChange(){throw new Error("Method not implemented.")}enablePrintDetail(e=2e3){this._checkId=oe.run("interval",()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:e})}create2dVideoContext(){this.videoContext?this.videoContext.destroy():this.videoContext=new Xe({frameRate:15,logger:this.log,name:"mix-ctx"}),this.videoContext.create({alpha:!1})}setFps(e){this.autoSetFps=!1,this.videoContext.frameRate=e;for(let t of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])t.shouldUpdate=!1;setTimeout(()=>{var t;return(t=this.destination)==null?void 0:t.start(this.videoContext.frameRate)},500)}setFpsAuto(){var s;if(!this.autoSetFps)return;for(let n of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])n.shouldUpdate=!1;let e=null,t=0,r=!0;for(let[n,a]of this.inputLocalVideoTracks)if(a.profile.frameRate>t){if(this.endedIds.has(n)){let d=this.cameraNodeMap.get(n);d&&d.image.cancelVideoFrameCallback(d.videoCallbackId);continue}t=a.profile.frameRate,e=n}for(let[n,a]of this.inputLocalScreenTracks)if(a.profile.frameRate>t){if(this.endedIds.has(n)){let d=this.screenNodeMap.get(n);d&&d.image.cancelVideoFrameCallback(d.videoCallbackId);continue}t=a.profile.frameRate,e=n,r=!1}if(e!==null){let n=r?this.cameraNodeMap.get(e):this.screenNodeMap.get(e);n&&(n.shouldUpdate=!0,n.tryVideoFrameCallback()),this.log.info("set mix fps: ",t)}else(s=this.destination)==null||s.start(this.videoContext.frameRate),this.log.info("fallback to timer, fps: ",this.videoContext.frameRate)}setMixBackground(e){this.mixNode&&(this.mixNode.backgroundColor=e)}resizeMixCanvas(e,t){var r;(r=this.mixNode)==null||r.resize(e,t)}startMix(){return f(this,null,function*(){var e;if(!this.mixNode||!this.destination)throw new Error("can't mix without necessary conditions");this.mixNode.disconnect(),this.mixNode.connect(this.destination),Ft&&this.player.setCanvas(this.videoContext._canvas),this.setOutputMediaStreamTrack(this.destination.videoTrack),(e=this.manager)==null||e.changeInput(this)})}addCameraSource(e,t,r){if(this.inputLocalVideoTracks.has(e)||this.cameraNodeMap.has(e))throw new Error(`There is already a cameraSource with the same ID: ${e}`);let{mediaTrack:s}=t;if(!s)throw new Error("no mediaTrack, add cameraSource failed");t.recaptureMode=1,tt(this,be).add("videoInputRemoved",a=>{a.deviceId===t.deviceId&&(this.endedIds.add(e),this.setFpsAuto())}),t.on("output-media-track-changed",()=>{this.endedIds.delete(e),this.updateCameraSource(e,r,t.mediaTrack)});let n;et===16&&s instanceof CanvasCaptureMediaStreamTrack?n=this.videoContext.createVideoImageSource(s.canvas,{name:"cameraCanvasSource",logger:this.log}):n=this.videoContext.createVideoTrackSource(s,"cameraNodeSource"),n.resize(t.settings.width,t.settings.height),n.shouldUpdate=!1,this._connectMix(n,r,"cover"),this.inputLocalVideoTracks.set(e,t),this.cameraNodeMap.set(e,n),this.setFpsAuto()}addScreenSource(e,t,r){if(this.inputLocalScreenTracks.has(e)||this.screenNodeMap.has(e))throw new Error(`There is already a screenSource with the same ID: ${e}`);let{mediaTrack:s}=t;if(!s)throw new Error("no mediaTrack, add cameraSource failed");let n=this.videoContext.createVideoTrackSource(s,"screenNodeSource");n.resize(t.settings.width,t.settings.height),n.shouldUpdate=!1,this._connectMix(n,r),this.inputLocalScreenTracks.set(e,t),this.screenNodeMap.set(e,n),this.setFpsAuto()}addTextSource(e){let{id:t,content:r="",font:s,color:n,layout:a}=e;if(this.textNodeMap.has(t))throw new Error(`There is already a textSource with the same ID: ${t}`);let d=this.videoContext.createTextSource({content:r,font:s,color:n});d.resize(a.width,a.height),this._connectMix(d,a),this.textNodeMap.set(t,d)}addImageSource(e,t,r){if(this.imageNodeMap.has(e))throw new Error(`There is already a imageSource with the same ID: ${e}`);let s=this.videoContext.createVideoImageSource(t,{autoResize:!1,logger:this.log});s.resize(t.width,t.height),this._connectMix(s,r),this.imageNodeMap.set(e,s)}addVideoSource(e,t,r){if(this.videoNodeMap.has(e))throw new Error(`There is already a videoSource with the same ID: ${e}`);let s=this.videoContext.createVideoImageSource(t,{autoResize:!1,logger:this.log});s.resize(t.videoWidth,t.videoHeight),s.shouldUpdate=!1,this._connectMix(s,r),this.videoNodeMap.set(e,s)}updateCameraSource(e,t,r=null,s){let n=this.cameraNodeMap.get(e);if(n){if(r){if(et===16&&r instanceof CanvasCaptureMediaStreamTrack)if(n instanceof Wt){let l=n.output;n.close(),n=this.videoContext.createVideoImageSource(r.canvas,{name:"cameraCanvasSource",logger:this.log}),n.connect(l),this.cameraNodeMap.set(e,n)}else n.image=r.canvas;else if(n instanceof Wt)n.replaceTrack(r);else{let l=n.output;n.close(),n=this.videoContext.createVideoTrackSource(r,"cameraNodeSource"),n.connect(l),this.cameraNodeMap.set(e,n)}let{width:a,height:d}=r.getSettings();a&&d&&n.resize(a,d)}s&&n.resize(s.width,s.height),(s||r)&&this.setFpsAuto(),this._changeMixLayout(n,t)}}updateScreenSource(e,t){let r=this.screenNodeMap.get(e);r&&this._changeMixLayout(r,t)}updateTextSource(e){let{id:t,content:r,font:s,color:n,layout:a}=e,d=this.textNodeMap.get(t);d&&(T(r)||(d.content=r),T(s)||(d.font=s),T(n)||(d.color=n),d.resize(a.width,a.height),this._changeMixLayout(d,a))}updateImageSource(e,t,r){let s=this.imageNodeMap.get(e);s&&(r&&(s.image=r,s.resize(r.width,r.height)),this._changeMixLayout(s,t))}updateVideoSource(e,t,r){let s=this.videoNodeMap.get(e);if(s){if(r){let n=s.image;n instanceof HTMLVideoElement&&this.stopVideoElement(n),s.image=r,s.resize(r.videoWidth,r.videoHeight)}this._changeMixLayout(s,t)}}_connectMix(e,t,r="contain"){if(!this.mixNode)return;let{mirror:s,rotation:n}=t;e.disconnect();let a=new Gt(this.videoContext,this.log,s,n);a=e.connect(a),t.fillMode||(t.fillMode=r),a.connect(this.mixNode,t)}_changeMixLayout(e,t){if(!this.mixNode)return;let{mirror:r,rotation:s}=t,n=e.output||e;n instanceof Gt&&(T(r)||(n.mirror=r),T(s)||(n.rotation=s),n.resize(e.width,e.height)),this.mixNode.changeInputLayout(n,t)}removeCameraSource(e){let t=this.inputLocalVideoTracks.get(e);if(!t)return;t.close(),this.inputLocalVideoTracks.delete(e);let r=this.cameraNodeMap.get(e);r&&(r.output instanceof Gt&&r.output.close(),r.close(),this.cameraNodeMap.delete(e)),this.checkAfterRemove(!0)}removeScreenSource(e){let t=this.inputLocalScreenTracks.get(e);if(!t)return;t.close(),this.inputLocalScreenTracks.delete(e);let r=this.screenNodeMap.get(e);r&&(r.output instanceof Gt&&r.output.close(),r.close(),this.screenNodeMap.delete(e)),this.checkAfterRemove(!0)}removeTextSource(e){let t=this.textNodeMap.get(e);t&&(t.output instanceof Gt&&t.output.close(),t.close(),this.textNodeMap.delete(e)),this.checkAfterRemove()}removeImageSource(e){let t=this.imageNodeMap.get(e);t&&(t.output instanceof Gt&&t.output.close(),t.close(),this.imageNodeMap.delete(e)),this.checkAfterRemove()}removeVideoSource(e){let t=this.videoNodeMap.get(e);t&&(t.output instanceof Gt&&t.output.close(),t.image instanceof HTMLVideoElement&&this.stopVideoElement(t.image),t.close(),this.videoNodeMap.delete(e)),this.checkAfterRemove()}checkAfterRemove(e=!1){e&&this.setFpsAuto()}stopVideoElement(e){e.pause(),e.src="",e.srcObject=null,e.remove()}close(){var e;super.close(),oe.clearTask(this._checkId),(e=this.videoContext)==null||e.destroy(),delete this.mixNode,delete this.destination;for(let t of[...this.inputLocalVideoTracks.values(),...this.inputLocalScreenTracks.values()])t.close();this.inputLocalVideoTracks.clear(),this.inputLocalScreenTracks.clear(),this.cameraNodeMap.clear(),this.screenNodeMap.clear(),this.textNodeMap.clear(),this.imageNodeMap.clear(),we(this);for(let t of this.videoNodeMap.values())t.image instanceof HTMLVideoElement&&this.stopVideoElement(t.image);this.videoNodeMap.clear(),this.log.info("localMixVideoTrack close, stop mix")}};var Kd=an();if(typeof navigator!="undefined"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:Kd,exposeOrigin:!0,permittedOrigins:["*"]})}catch(o){}var IS=function(o){return f(this,null,function*(){let i=null,e=RS(o);R.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let t=yield navigator.mediaDevices.getDisplayMedia(e);o.systemAudio&&t.getAudioTracks().length===0&&(Zo&&$e<74||Re||ee)&&R.warn("Your browser not support capture system audio");let r=t.getVideoTracks()[0];if(r){if(o.frameRate)try{yield r.applyConstraints({frameRate:{min:o.frameRate,ideal:o.frameRate},width:o.width,height:o.height})}catch(s){R.warn(`screen applyConstraints failed: ${s}`)}o.captureElement&&(yield AS(r,o.captureElement))}if(o.audio){let s=CS(o);R.info(`getUserMedia with constraints: ${JSON.stringify(s)}`),i=yield navigator.mediaDevices.getUserMedia(s),t.addTrack(i.getAudioTracks()[0])}return t})};function AS(o,i){return f(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&le(o.cropTo))try{if(!(((e=o.getCaptureHandle())==null?void 0:e.handle)===Kd))return;let r=yield CropTarget.fromElement(i);yield o.cropTo(r)}catch(t){R.warn(`cropTo target failed ${t}`)}})}function CS(o){let i={echoCancellation:o.echoCancellation,autoGainControl:o.autoGainControl,noiseSuppression:o.noiseSuppression,sampleRate:o.sampleRate,channelCount:o.channelCount};return T(o.microphoneId)||(i.deviceId=o.microphoneId),{audio:i,video:!1}}function RS(o){let i={preferCurrentTab:o.preferDisplaySurface==="current-tab"||!!o.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:Re?{max:o.width}:{ideal:o.width,max:o.width},height:Re?{max:o.height}:{ideal:o.height,max:o.height},frameRate:o.frameRate,displaySurface:o.preferDisplaySurface||"monitor"};if(i.video=e,o.systemAudio){let{echoCancellation:t=!0,noiseSuppression:r=!1,autoGainControl:s=!1}=o;i.audio={echoCancellation:t,noiseSuppression:r,autoGainControl:s,sampleRate:48e3}}return i}var mf=IS;var Pt=class extends je{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}`}get isShareCurrentTab(){var e,t;try{return Kd===((t=(e=this.mediaTrack)==null?void 0:e.getCaptureHandle())==null?void 0:t.handle)}catch(r){return}}capture(u){return f(this,arguments,function*({systemAudio:e=!1,autoGainControl:t,echoCancellation:r,noiseSuppression:s,audioTrack:n,videoTrack:a,captureElement:d,preferDisplaySurface:l}){try{let h;return a||n?(h=new MediaStream,a&&h.addTrack(a),n&&h.addTrack(n)):(h=yield mf({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:t,echoCancellation:r,noiseSuppression:s,captureElement:d,preferDisplaySurface:l}),this.sourceTrack=h.getVideoTracks()[0]),yield this.setInputMediaStreamTrack(h.getVideoTracks()[0]),h}catch(h){throw this.log.error(`getDisplayMedia error observed ${h}`),h instanceof v?h:new v({code:I.INITIALIZE_FAILED,name:h.name,message:h.message})}})}switchDevice(e){return f(this,null,function*(){throw new Error("Method not implemented.")})}};D([Ct(function(e){this.setContentHint(e.contentHint||"detail")})],Pt.prototype,"capture",1);var To=class extends kt{constructor(i){super(i),this._log.id=`s-${this._log.id}`,this.isScreen=!0}addAudioProcessor(i,e,t){this.pipeline.silentNode.setNode(t),this.pipeline.mixNode.setNode(e),this.pipeline.aec.setNode(i),this.enableTrackAEC(!1)}removeAudioProcessor(i){this.pipeline.aec.node===i&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode(),this.enableTrackAEC(!0))}};var yS='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}});',Sh;function Wn(o,i=48e3,e=1,t){return f(this,null,function*(){let r=Ee("dump");Sh||(Sh=tr(r,URL.createObjectURL(new Blob([yS],{type:"application/javascript"})))),yield Sh;let s=r.sampleRate,n=new AudioWorkletNode(r,"dumper",{numberOfInputs:o.length,numberOfOutputs:0,processorOptions:{sourceSampleRate:s,targetSampleRate:i}});return n.channelCountMode="explicit",n.channelCount=e,t&&n.port.postMessage({port:t},[t]),o.forEach((a,d)=>a.connect(n,0,d)),new ReadableStream({start(a){n.port.onmessage=d=>{a.enqueue(d.data)}},cancel(){o.forEach(a=>a.disconnect(n)),n.port.close()}})})}var ec=class extends yd{constructor(e){super();this.room=e;c(this,"_localAudioTrack");c(this,"_localScreenAudioTrack");c(this,"log");c(this,"denoiser");c(this,"voiceChanger");c(this,"mixChangedDebounce");c(this,"audioProcessor");c(this,"encodePipeline",[]);c(this,"decodePipeline",[]);c(this,"getPCMAbortCtrlMap",new Map);c(this,"audioFrameEventConfigMap",new Map);c(this,"audioReferenceMap",new Map);c(this,"isLocalAudioNeedAudioProcess",!1);c(this,"isScreenAudioNeedAudioProcess",!1);this.log=R.createLogger({parent:e==null?void 0:e.getLogger(),id:"am",userId:e==null?void 0:e.userId,sdkAppId:e==null?void 0:e.sdkAppId}),this.installEvent()}get localAudioTrack(){return this._localAudioTrack}get _localAudioPipline(){var e;return(e=this._localAudioTrack)==null?void 0:e.pipeline}get _localScreenAudioPipeline(){var e;return(e=this._localScreenAudioTrack)==null?void 0:e.pipeline}dump(e){var u,h;if(!this._localAudioTrack)return;let t=[],r=[];(u=this._localAudioPipline)!=null&&u.source.node&&(t.push(this._localAudioPipline.source.node),r.push("mic")),(h=this._localAudioPipline)!=null&&h.denoiser.node&&(t.push(this._localAudioPipline.denoiser.node),r.push("mic-processed")),this.mixWeight>1&&(t.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),r.push("mix")),this.log.info(`dump audio track ${r}, duration: ${e}`);let s=new AbortController,n=[],a=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),s.abort("timeout")},e*1e3),d=()=>{for(let p=0;p<r.length;p++){let m=URL.createObjectURL(new Blob(n[p])),g=document.createElement("a");g.href=m,g.download=`${r[p]}.pcm`,g.style.display="none",document.body.appendChild(g),g.click(),URL.revokeObjectURL(m),g.remove()}clearTimeout(a),s.abort("download")},l=Wn(t).then(p=>p.pipeTo(new WritableStream({write(m){m.forEach((g,E)=>n[E]=n[E]?n[E].concat(g[0]):[g[0]])}}),s).catch(m=>d));return{then:l.then.bind(l),download:d}}getPCM(e,t){var P,re,L;if(typeof WritableStream=="undefined"){this.log.warn("getPCM failed: browser not support WritableStream");return}let{enable:r,sampleRate:s=48e3,channelCount:n=1,port:a}=(t===""?this.audioFrameEventConfigMap.get(""):this.audioFrameEventConfigMap.get(t)||this.audioFrameEventConfigMap.get("*"))||{};if(!r)return;this.log.info(`getPCM ${t||"local"}`);let d=Math.floor(s*.04),l=new Float32Array(d),u=new Float32Array(d),h,p,m=0,g=new AbortController,E=t===""?(P=this._localAudioTrack)==null?void 0:P.mediaTrack:(L=(re=this.room)==null?void 0:re.remotePublishedUserMap.get(t))==null?void 0:L.remoteAudioTrack.mediaTrack;if(!E){this.log.info(`getPCM failed: ${t||"local"} has no audio track`);return}let C=Ee().createMediaStreamSource(new MediaStream([E]));return Wn([C],s,n,a).then(Qe=>Qe.pipeTo(new WritableStream({write(N){N[0][0]&&(m+N[0][0].length>d?(l.set(N[0][0].subarray(0,d-m),m),h=N[0][0].subarray(d-m),N[0][1]&&(u.set(N[0][1].subarray(0,d-m),m),p=N[0][1].subarray(d-m)),m+=d-m):(h&&(l.set(h,m),m+=h.length,h=void 0),p&&(u.set(p,m),p=void 0),l.set(N[0][0],m),N[0][1]&&u.set(N[0][1],m),m+=N[0][0].length),m>=d&&(m=0,e({userId:t,sampleRate:s,channelCount:n,data:n===1?l:[l,u]}),l=new Float32Array(d),u=new Float32Array(d)))}}),g).catch(N=>this.log.warn(`stop getPCM reason:${N}`))),g}get hasScreenAudioTrack(){return!T(this._localScreenAudioTrack)}get hasAudioTrack(){return!T(this._localAudioTrack)}changeInput(e){var t,r;if(e instanceof To)return this._localScreenAudioTrack=e,this.isScreenAudioNeedAudioProcess&&((t=this.audioProcessor)!=null&&t.screenAudioWorkletNode)&&(e.addAudioProcessor(this.audioProcessor.screenAudioWorkletNode,this.audioProcessor.mixNode,this.audioProcessor.silentNode),this.audioReferenceMap.forEach((s,n)=>{e.mixAudioReference(s,n)})),e.pipeline.connect(),this.mixOnChange();if(e instanceof kt)return this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),this.isLocalAudioNeedAudioProcess&&((r=this.audioProcessor)!=null&&r.localAudioWorkletNode)&&(e.addAudioProcessor(this.audioProcessor.localAudioWorkletNode,this.audioProcessor.mixNode,this.audioProcessor.silentNode),this.audioReferenceMap.forEach((s,n)=>{e.mixAudioReference(s,n)})),e.pipeline.connect(),this.mixOnChange();if(e instanceof Ei)return e.setOutputMediaStreamTrack(e.mediaTrack)}mixAudioReference(e,t){var r;(r=this._localAudioTrack)==null||r.mixAudioReference(e,t)}unMixAudioReference(e){var t;(t=this._localAudioTrack)==null||t.unMixAudioReference(e)}setAudioReferenceVolume(e,t){var r;(r=this._localAudioTrack)==null||r.setAudioReferenceVolume(e,t)}mixOnChange(){return this.mixChangedDebounce||(this.mixChangedDebounce=Promise.resolve().then(()=>{var e,t;return delete this.mixChangedDebounce,Promise.all([(e=this._localAudioTrack)==null?void 0:e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),(t=this._localScreenAudioTrack)==null?void 0:t.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)])})),this.mixChangedDebounce}removeInput(e){e instanceof To?delete this._localScreenAudioTrack:e instanceof kt?delete this._localAudioTrack:e instanceof Ei}addDenoiser(e){var t;this.denoiser=e,(t=this._localAudioTrack)==null||t.addDenoiser(e)}addAudioProcessor(e,t,r,s){var n;this.audioProcessor={localAudioWorkletNode:r,mixNode:e,silentNode:t,screenAudioWorkletNode:s},this.isLocalAudioNeedAudioProcess&&this._localAudioTrack&&r&&(this._localAudioTrack.addAudioProcessor(r,e,t),this.audioReferenceMap.forEach((a,d)=>{var l;(l=this._localAudioTrack)==null||l.mixAudioReference(a,d)})),this.isScreenAudioNeedAudioProcess&&this._localScreenAudioTrack&&s&&((n=this._localScreenAudioTrack)==null||n.addAudioProcessor(s,e,t),this.audioReferenceMap.forEach((a,d)=>{var l;(l=this._localScreenAudioTrack)==null||l.mixAudioReference(a,d)}))}removeDenoiser(e){var t;return delete this.denoiser,(t=this._localAudioTrack)==null?void 0:t.removeDenoiser(e)}addVoiceChanger(e,t){var r;this.voiceChanger=[e,t],(r=this._localAudioTrack)==null||r.pipeline.voiceChanger.setNode(e,t)}removeVoiceChanger(){var e;delete this.voiceChanger,(e=this._localAudioTrack)==null||e.pipeline.voiceChanger.deleteNode()}removeAudioProcessor(e,t){var r,s;delete this.audioProcessor,(r=this._localAudioTrack)==null||r.removeAudioProcessor(e),(s=this._localScreenAudioTrack)==null||s.removeAudioProcessor(t)}destroy(){this.close(),this.audioReferenceMap.clear(),this.getPCMAbortCtrlMap.forEach(e=>e==null?void 0:e.abort("destroy")),this.getPCMAbortCtrlMap.clear(),this.audioFrameEventConfigMap.clear(),this.uninstallEvent()}addEncodeProcessor({processor:e,type:t}){var r;this.encodePipeline.includes(e)||(this.encodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}addDecodeProcessor({processor:e,type:t}){var r;this.decodePipeline.includes(e)||(this.decodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}handleLocalTrackStarted({room:e,userId:t}){var s;if(e!==this.room||this.getPCMAbortCtrlMap.get(t))return;let r=this.getPCM(n=>{var a;(a=this.room)==null||a.emit("audio-frame",n)},"");this.getPCMAbortCtrlMap.set(t,r),this.getPCMAbortCtrlMap.get(t)&&((s=this._localAudioTrack)==null||s.on("input-media-track-changed",()=>{let n=this.getPCMAbortCtrlMap.get(t);n&&(n.abort("inputMediaTrackChanged"),n=this.getPCM(a=>{var d;(d=this.room)==null||d.emit("audio-frame",a)},""),this.getPCMAbortCtrlMap.set(t,n))}))}handleLocalTrackStopped({room:e,userId:t}){if(e!==this.room)return;let r=this.getPCMAbortCtrlMap.get(t);r&&(r.abort("stopLocalAudio"),this.getPCMAbortCtrlMap.delete(t))}handleRemoteTrackStarted({room:e,userId:t}){if(e===this.room&&!this.getPCMAbortCtrlMap.get(t)){let r=this.room.audioManager.getPCM(s=>{var n;(n=this.room)==null||n.emit("audio-frame",s)},t);this.getPCMAbortCtrlMap.set(t,r)}}handleRemoteTrackStopped({room:e,userId:t}){if(e!==this.room)return;let r=this.getPCMAbortCtrlMap.get(t);r&&(r.abort("stopRemoteAudio"),this.getPCMAbortCtrlMap.delete(t))}installEvent(){S.on("113",this.handleLocalTrackStarted,this),S.on("114",this.handleLocalTrackStopped,this),S.on("115",this.handleRemoteTrackStarted,this),S.on("116",this.handleRemoteTrackStopped,this)}uninstallEvent(){S.off("113",this.handleLocalTrackStarted),S.off("114",this.handleLocalTrackStopped),S.off("115",this.handleRemoteTrackStarted),S.off("116",this.handleRemoteTrackStopped)}updateAudioReference({type:e,audioReference:t,refId:r,volume:s}){if(e==="add"){if(this.audioReferenceMap.get(r)||!t||(this.audioReferenceMap.set(r,t),!this.audioProcessor))return;this.mixAudioReference(t,r)}else if(e==="remove")this.audioReferenceMap.get(r)&&(this.audioReferenceMap.delete(r),this.unMixAudioReference(r));else if(e==="updateVolume"){if(!this.audioProcessor||T(s))return;this.setAudioReferenceVolume(r,s)}}};function Eo(o=30,i=2){return Y((e,t)=>function(...r){return new Promise((s,n)=>{let a=setTimeout(()=>{let d=new v({code:I.API_CALL_TIMEOUT,message:`checkPendingPromise ${t}() timeout ${o}s`});(this.log||this._log||R).warn(d),i===2?n(d):i===1&&s()},o*1e3);this._checkPendingPromiseSet||(this._checkPendingPromiseSet=new Set),this._checkPendingPromiseSet.add(a),e.apply(this,r).then(s,n).finally(()=>{clearTimeout(a),this._checkPendingPromiseSet&&a&&this._checkPendingPromiseSet.delete(a)})})})}function pf(){return Y((o,i)=>function(...e){return this._checkPendingPromiseSet&&(this._checkPendingPromiseSet.forEach(t=>clearTimeout(t)),this._checkPendingPromiseSet.clear()),o.apply(this,e)})}var ki=class ki extends no{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",rt(de(this,ki.STATE_SUBSCRIBE)));c(this,"ignoreUpdatePlayingState");this.tinyId=t.tinyId,this.availableState=new j(`${t.userId}-${this.mediaType}-available`,"remote-track-available"),this.remotePublishState=new j(`${t.userId}-${this.mediaType}-remote-publish`,"remote-track-publish"),ce(Ln(de(this,j.STATECHANGED),de(this.remotePublishState,j.STATECHANGED)),Vn(()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing)),Te(d=>{this.availableState.state!==(d?j.ON:j.OFF)&&(this.availableState.state=d?j.ON:j.OFF),!(this.isRemotePublished&&this.ignoreUpdatePlayingState)&&this.updatePlayingState(d)}));let s=ce(de(this.player,he.ERROR),$t(d=>d.code===MediaError.MEDIA_ERR_DECODE)),n=ce(wn(5e3),$t(()=>this.ignoreDecodeError||!this.isSubscribed||!this.isPlayCalled||!this.stat.bytesReceived?!1:this.player.isPlaying||(this.kind===_.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)?(this.reportDecodeResult(!0),!1):!0)),a=ce(Lu(s,n),ke(de(this,j.INIT)));ce(this._triggerCheckDecodeSubject,$t(()=>!this.ignoreDecodeError),mo(a),Te(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===j.ON}get isNeedPlay(){return this.isAvailable&&this.isPlayCalled}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}reportDecodeResult(e,t){var s,n;let r=this.kind===_.AUDIO;if(y[e?"addSuccessEvent":"addFailedEvent"]({key:r?504700:514702}),!r){let a=((s=this.room)==null?void 0:s.downlinkVideoCodec.toUpperCase())||"H264";y[e?"addSuccessEvent":"addFailedEvent"]({key:rs[`DECODE_${a}_RESULT`]}),e||this.log.warn(`${(n=this.room)==null?void 0:n.downlinkVideoCodec} decode failed`)}e||(y.addEnum({key:r?504701:514703,value:Zr()}),se.uploadEvent({log:`stat-decode-failed-${this.kind}-${ai()||di()}`,userId:this.room.userId}),this._log.warn(`decode failed: isPlaying: ${this.player.isPlaying} ${this.kind===_.AUDIO?`audioLevel: ${this.getAudioLevel()}`:`framesDecoded: ${this.stat.framesDecoded>0}`}`),this.emit("decode-failed",{error:t}))}updatePlayingState(e){if(this.player.isPlayCalled&&this.player.setTrack(this.playerMediaTrack),this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.isRemotePublished||!this.outMediaTrack)){this.log.info(`abort play, isSubscribed: ${this.isSubscribed} isAvailable: ${this.isRemotePublished} hasTrack: ${!!this.outMediaTrack} `);return}super.updatePlayingState(e)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.remotePublishState.state=this.isRemotePublished?j.ON:j.OFF,this.emit("remote-publish-changed",this.isRemotePublished)}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};c(ki,"STATE_SUBSCRIBE","subscribe"),D([Eo(5,1)],ki.prototype,"waitHasMediaTrack",1),D([ye(j.INIT,ki.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),S.emit(A.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),Rt(521716,!1)],ki.prototype,"subscribe",1),D([ye(ki.STATE_SUBSCRIBE,j.INIT,{sync:!0,success(){this.log.info("unsubscribed"),S.emit(A.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],ki.prototype,"unsubscribe",1);var gs=ki;var Ei=class extends gs{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 so.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}onPlayerError(e){this.enableDecodeFrame&&(this._log.warn("use audio decoder"),this.room.enableInsertableStreams())}get enableDecodeFrame(){var e,t;return this.manager?this.manager.decodePipeline.some(r=>r)||((t=(e=this.player.element)==null?void 0:e.error)==null?void 0:t.code)===MediaError.MEDIA_ERR_DECODE&&Td().AudioDecoder&&pi:!1}get enableDecryptFrame(){return this.manager&&!!this.manager.decodePipeline[0]}decodeFrame(e){if(!this.manager)return e;let t=e;for(let[r,s]of this.manager.decodePipeline.entries()){if(!s)continue;let n={frame:e,track:this};if(r===1&&this.isAvailable&&this.room.role==="audience"&&(n.onAudioFrameNTPTime=({ntp:a,frame:d,hasLeavingTag:l})=>{this.emit("audio-frame-with-ntp",{ntp:a,frame:d,hasLeavingTag:l})}),t=s(n),!t)return}return t}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get isRemotePublished(){return this.user.muteState.audioAvailable}};var tc=class extends Pe{constructor(e,t,r,s,n){super(e,{useDefaultProgram:!0,useFbo:!0,name:"alpha",create2d:!0,logger:t});this.setContainer=s;c(this,"initStat",{alphaStitchingType:1});c(this,"end",rt());c(this,"minSize",320);c(this,"maxSize",1280);c(this,"draggable",!1);c(this,"startDragX",0);c(this,"startDragY",0);c(this,"left",0);c(this,"top",0);c(this,"baseWidth",320);c(this,"baseRatio");c(this,"container");this.initStat=n,this.draggable=r,this.bindDragEvents(),y.addEnum({key:515700,value:1}),this.draggable&&y.addEnum({key:515700,value:11})}bindDragEvents(){let e=this.context._canvas;if(e)if(this.draggable){let t=ke(this.end);ce(de(e,"mousedown"),Fn(this.startDrag.bind(this)),Mr(()=>ce(de(window,"mousemove"),ke(de(window,"mouseup")))),t,Te(this.doDrag.bind(this))),ce(de(e,"dblclick"),t,Te(this.resetPosition.bind(this))),ce(de(e,"wheel"),t,Te(this.handleZoom.bind(this))),this.renderCanvas()}else{if(!this.container)return;this.container.style.removeProperty("left"),this.container.style.removeProperty("top"),this.end.next()}}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}startDrag(e){e.preventDefault(),e.button===0&&(this.startDragX=e.clientX-this.left,this.startDragY=e.clientY-this.top)}renderCanvas(){let{container:e}=this;e||this.setContainer(),!(!e||!this.baseRatio||!this.draggable)&&(e.style.setProperty("width",`${this.baseWidth}px`),e.style.setProperty("height",`${this.baseWidth/this.baseRatio}px`),e.style.setProperty("position","fixed"),e.style.setProperty("left",`${this.left}px`),e.style.setProperty("top",`${this.top}px`))}doDrag(e){e.preventDefault(),this.left=e.clientX-this.startDragX,this.top=e.clientY-this.startDragY,this.renderCanvas()}handleZoom(e){e.preventDefault();let t=.1,r=e.deltaY,s=this.context._canvas;s&&(this.baseWidth||(this.baseWidth=s.offsetWidth),r<0?this.baseWidth=Math.min(this.baseWidth*(1+t),this.maxSize):this.baseWidth=Math.max(this.baseWidth*(1-t),this.minSize),this.renderCanvas())}resetPosition(){this.left=0,this.top=0,this.renderCanvas()}onRatioReset(){this.renderCanvas()}draw2d(e,t,r,s,n){var m;let{ctx2d:a}=this,d=this.context._canvas;if(!a||!d)return!1;let l=super.draw2d(e,t,r,s,n),u=a.getImageData(0,0,s,n),{data:h}=u,p=!1;if(this.initStat.alphaStitchingType===1){let g=Math.floor(s/2);for(let E=0;E<n;E++)for(let C=0;C<g;C++){let P=(E*s+C)*4,re=C+g,L=(E*s+re)*4,Qe=h[L];h[L+3]=0;let N=Qe>=100;h[P+3]=N?255:0}p=super.draw2d(u,0,0,0,0,g,n),d.width=g}else if(this.initStat.alphaStitchingType===2){let g=Math.floor(n/2);for(let E=0;E<g;E++)for(let C=0;C<s;C++){let P=(E*s+C)*4,L=((E+g)*s+C)*4,Qe=h[L];h[L+3]=0;let N=Qe>=100;h[P+3]=N?255:0}p=super.draw2d(u,0,0,0,0,s,g),d.height=g}return(m=this.context.ctx)==null||m.clearRect(0,0,s,n),l&&p}close(){this.baseRatio=void 0,this.end.next(),this.end.complete()}};function vS(o){return[15,30,45,60].reduce((e,t)=>Math.abs(t-o)<Math.abs(e-o)?t:e)}var Pi=class extends gs{constructor(e,t,r=4){super(e,t,r);c(this,"mediaType",4);c(this,"source");c(this,"shouldRenderAlpha",!1);c(this,"alphaNode");c(this,"shouldBeDraggable",!0);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.on("first-video-frame",s=>{this.room.emit("first-video-frame",s)})}isAlphaSei(e){if(this.userId!==e.userId||e.seiPayloadType!==50)return!1;let t=new Uint8Array(e.data);return t.length%3!==0||t[0]!==0||t[1]!==1?!1:t}play(e,t){return(ue(t==null?void 0:t.canvasRender)?t.canvasRender:et===17)&&!this.source&&this.useCanvasPlayer(),super.play(e,t).then(()=>{this.player.calculateStat(),S.emit("156",{track:this,player:this.player})})}updateAlphaRenderInfo(e){let t=this.isAlphaSei(e);if(t)if(!this.alphaNode)this.shouldRenderAlpha=!0,this.player.shouldRenderAlpha=!0,this.useCanvasPlayer(t[2]);else{let r=t[2];if(this.alphaNode.baseRatio&&this.alphaNode.initStat.alphaStitchingType===r)return;this.alphaNode.initStat={alphaStitchingType:r};let s=this.player.getElement();if(s){let n=s.videoWidth/s.videoHeight;n&&(this.alphaNode.baseRatio=n*(r===1?.5:2),this.alphaNode.onRatioReset())}this.player.canvas&&(this.player.canvas.id=this.generateAlphaCanvasName(r))}}generateAlphaCanvasName(e){let t="alpha",r=un[e];return`${t}_${r}_${this.userId}`}useCanvasPlayer(e){if(this.log.info(`useCanvasPlayer(), has element:${!!this.player.element}`),!this.player.element)return;let t=new Xe({frameRate:15,logger:this.log,name:this.shouldRenderAlpha&&e?this.generateAlphaCanvasName(e):this.userId});t.create({alpha:this.shouldRenderAlpha,willReadFrequently:this.shouldRenderAlpha});let r=new fo(t,{name:"remotePlayer",logger:this.log});if(this.source=t.createVideoPlayerSource(this.player),this.player.setCanvas(t._canvas),this.shouldRenderAlpha&&e){let s=()=>{!this.player.container||!this.alphaNode||(this.alphaNode.container=this.player.container,this.alphaNode.renderCanvas())},n=new tc(t,this.log,this.shouldBeDraggable,s,{alphaStitchingType:e});this.source.connect(n),n.connect(r),this.alphaNode=n}else this.source.connect(r);Ki()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,t),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let t=this.decodeFPS,r=vS(t);if(!Q(t)||t<=0){this.log.debug(`updateCanvasPlayerFPS() ignore decoder: ${t} `);return}if(r===e.frameRate){this.log.debug(`updateCanvasPlayerFPS() ignore ClosestFPS ${r} == ${e.frameRate}`);return}this.log.info(`updateCanvasPlayerFPS() decoder: ${t}, closest: ${r}, current: ${e.frameRate}`),e.frameRate=r}get decodeFPS(){var n;let{msg_video_status:e}=((n=this.room.heartbeatReport)==null?void 0:n.msg_down_stream_info.find(a=>a.msg_user_info.str_identifier===this.userId))||{},t=this.mediaType===2?7:this.isSmall?3:2;if(!e||e.length===0)return 0;let r=e.find(a=>a.uint32_video_stream_type===t);return(r==null?void 0:r.uint32_video_dec_fps)||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),S.emit("157",{track:this,player:this.player}),this.alphaNode&&this.alphaNode.close(),super.stop()}decodeFrame(e){if(!this.manager)return e;for(let t of this.manager.decodePipeline)if(t&&(e=t({frame:e,track:this}),!e))return;return e}get isBig(){return this.mediaType===4}get isSmall(){return this.mediaType===8}changeType(e){this.room.changeType(e,this.user)}get isRemotePublished(){return this.user.muteState.videoAvailable}setMirror(e){e==="publish"||e==="both"||super.setMirror(e)}setDraggable(e){this.shouldBeDraggable=e,this.alphaNode&&(this.alphaNode.draggable=e,this.alphaNode.bindDragEvents())}onDecodeDowngradeStateChanged(e){this.emit("decode-downgrade-state-changed",e)}},Ts=class extends Pi{constructor(e,t){super(e,t,2);c(this,"mediaType",2);c(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}};var Es=new Map;S.on(A.JOIN_SUCCESS,({room:o})=>{ve(o.userId,{eventId:32788})});S.on(A.LEAVE_START,({room:o})=>{ve(o.userId,{eventId:32789})});S.on(A.LOCAL_TRACK_PUBLISHED,({track:o})=>{if(o.room){let i=32769;o.mediaType===4?i=32768:o.mediaType===2&&(i=32805),ve(o.room.userId,{eventId:i})}});S.on(A.LOCAL_TRACK_UNPUBLISHED,({track:o})=>{if(o.room){let i=32771;o.mediaType===4?i=32770:o.mediaType===2&&(i=32806),ve(o.room.userId,{eventId:i})}});S.on(A.TRACK_MUTED,({track:o})=>{o.room&&(o.kind===_.AUDIO?ve(o.room.userId,{eventId:o.isRemote?32785:32772,remoteUserId:o.isRemote?o.userId:void 0}):ve(o.room.userId,{eventId:o.isRemote?32784:32773,remoteUserId:o.isRemote?o.userId:void 0}))});S.on(A.TRACK_UNMUTED,({track:o})=>{o.room&&(o.kind===_.AUDIO?ve(o.room.userId,{eventId:o.isRemote?32787:32774,remoteUserId:o.isRemote?o.userId:void 0}):ve(o.room.userId,{eventId:o.isRemote?32786:32775,remoteUserId:o.isRemote?o.userId:void 0}))});S.on(A.REMOTE_TRACK_SUBSCRIBED,({track:o})=>{o.room&&(o.mediaType===1&&ve(o.room.userId,{eventId:32777,remoteUserId:o.userId}),o.mediaType===4&&ve(o.room.userId,{eventId:32776,remoteUserId:o.userId}),o.mediaType===8&&ve(o.room.userId,{eventId:32803,remoteUserId:o.userId}))});S.on(A.REMOTE_TRACK_UNSUBSCRIBED,({track:o})=>{o.room&&(o.mediaType===1&&ve(o.room.userId,{eventId:32779,remoteUserId:o.userId}),o.mediaType===4&&ve(o.room.userId,{eventId:32778,remoteUserId:o.userId}),o.mediaType===8&&ve(o.room.userId,{eventId:32804,remoteUserId:o.userId}))});S.on(A.SWITCH_DEVICE_SUCCESS,({track:o})=>{o.room&&ve(o.room.userId,{eventId:o.kind===_.VIDEO?32780:32781})});S.on(A.LOCAL_TRACK_REPLACED,({track:o})=>{o.room&&ve(o.room.userId,{eventId:o.kind===_.VIDEO?32782:32783})});S.on(A.SIGNAL_CONNECTION_STATE_CHANGED,({room:o,prevState:i,state:e})=>{let t;switch(e){case"CONNECTED":i==="RECONNECTING"?t=32795:t=32791;break;case"DISCONNECTED":i==="RECONNECTING"?t=32796:t=32790;break;case"RECONNECTING":t=32794;break}t&&ve(o.userId,{eventId:t})});S.on(A.PEER_CONNECTION_STATE_CHANGED,({room:o,prevState:i,state:e,remoteUserId:t})=>{let r=!!t,s;switch(e){case"CONNECTED":i==="RECONNECTING"?s=r?32801:32798:s=r?32793:32792;break;case"DISCONNECTED":i==="RECONNECTING"&&(s=r?32802:32799);break;case"RECONNECTING":s=r?32800:32797;break}s&&ve(o.userId,{eventId:s,remoteUserId:t})});S.on(A.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({implementation:o,userId:i,remoteUserId:e,codec:t,isHWCodec:r,prevImplementation:s,streamType:n})=>{let a=r?1:0;s||(a=r?3:2);let d={H264:0,H265:1,VP8:2}[t.toUpperCase()],l={eventId:4004,param1:a,param2:d,streamType:n||2};e&&(l.remoteUserId=e,l.eventId=4005),ve(i,l),y.addEnum({key:e?514701:513701,value:a}),y.addEnum({key:e?514700:513700,value:d})});S.on(A.LOCAL_TRACK_RECAPTURE,({track:o,error:i})=>{if(o.userId){let e={eventId:2003,param1:0};o.kind===_.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType=o.streamType==="auxiliary"?7:2,i&&(e.param1=8)),ve(o.userId,e)}});function ve(o,i){let e=w(M({},i),{timestamp:Hi()});Es.has(o)?Es.get(o).push(e):Es.set(o,[e])}function ff(o){if(Es.has(o)){let i=Es.get(o).map(e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,uint32_param1:e.param1,uint32_param2:e.param2,uint32_video_stream_type:e.streamType}));return Es.delete(o),i}return[]}function _f(...o){return Y((i,e)=>function(...t){return DS.call(this,o,t,e,this._name),i.apply(this,t)})}function DS(o,i,e,t){try{if(Ae(o))for(let r=0;r<o.length;r++)ic.call(this,{rule:o[r],value:i[r],key:o[r].name,fnName:e,className:t});else ic.call(this,{rule:o,value:i[0],key:o.name,fnName:e,className:t})}catch(r){throw R.error(r),r}}function ic({rule:o,value:i,key:e,fnName:t,className:r}){if(T(i)){if(o.required)throw new v({code:I.INVALID_PARAMETER,message:$({key:B.INVALID_PARAMETER_REQUIRED,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(T(o.defaultValue))return;i=o.defaultValue}if(Array.isArray(o.type)){let a=!1;for(let d=0;d<o.type.length;d++)o.type[d]===null&&i===null&&(a=!0),le(o.type[d])&&i instanceof o.type[d]&&(a=!0),ie(o.type[d])&&Me(i)===o.type[d].toLowerCase()&&(a=!0);if(!a)throw new v({code:I.INVALID_PARAMETER,message:$({key:B.INVALID_PARAMETER_TYPE,data:{key:e,rule:{type:o.type.map(d=>jr(d)?wo(d):ie(d)?d:Me(d))},fnName:t,value:i},link:{className:r,fnName:t}})})}else if(!T(o.type)&&Me(i)!==o.type)throw new v({code:I.INVALID_PARAMETER,message:$({key:B.INVALID_PARAMETER_TYPE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(o.allowEmpty===!1){let a=Q(i)&&(i===0||Number.isNaN(i)),d=ie(i)&&i.trim()==="";if(a||d)throw new v({code:I.INVALID_PARAMETER,message:$({key:B.INVALID_PARAMETER_EMPTY,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})})}if(o.notLessThanZero&&Q(i)&&i<0)throw new v({code:I.INVALID_PARAMETER,message:$({key:B.CANNOT_LESS_THAN_ZERO,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(!T(o.min)&&Q(i)&&i<o.min)throw new v({code:I.INVALID_PARAMETER,message:$({key:B.INVALID_PARAMETER_MIN,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(!T(o.max)&&Q(i)&&i>o.max)throw new v({code:I.INVALID_PARAMETER,message:$({key:B.INVALID_PARAMETER_MAX,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(ie(o.instanceOf)){if(!i||i._name!==o.instanceOf)throw new v({code:I.INVALID_PARAMETER,message:$({key:B.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})})}else if(le(o.instanceOf)&&!(i instanceof o.instanceOf))throw new v({code:I.INVALID_PARAMETER,message:$({key:B.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(o.values&&!o.values.includes(i))throw new v({code:I.INVALID_PARAMETER,message:$({key:B.INVALID_PARAMETER_RANGE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});let{properties:s}=o;dt(s)&&yt(i)&&Object.keys(s).forEach(a=>{ic.call(this,{rule:s[a],value:i&&i[a],key:`${e}.${a}`,fnName:t,className:r})});let{arrayItem:n}=o;dt(n)&&Ae(i)&&i.forEach((a,d)=>{ic.call(this,{rule:n,value:a,key:`${e}[${d}]`,fnName:t,className:r})}),le(o.validate)&&o.validate.call(this,i,e,t,r,this)}var gf=Je(nt(),1);var rc=class extends gf.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:s,role:n}=e;if(this.userMap.has(t))return;let a={userId:r,tinyId:s,role:n===20?"anchor":"audience"};this.userMap.set(t,a),this.emit("1",a)}deleteUser(e,t){let r=this.userMap.get(e);if(!r)return;let s=`peer leave [${e}]`;T(t)||(s+=`:${tl[t]}`),this._log.info(s);let n=this.remotePublishedUserMap.get(e);if(n){let a=n.muteState;n.flag=0,this.emit("5",n.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:a,muteState:n.muteState,flag:0})}this.userMap.delete(e),this.emit("2",r.userId)}setUserList(e){this.userMap.forEach(t=>{e.findIndex(r=>r[this.key]===t[this.key])<0&&this.deleteUser(t[this.key],0)}),e.forEach(t=>{!this.userMap.has(t[this.key])&&t[this.key]!==this.mySelfId&&this.addUser(t)})}addRemotePublishedUser(e){this.remotePublishedUserMap.has(e[this.key])||this.remotePublishedUserMap.set(e[this.key],e)}deleteRemotePublishedUser(e){this.remotePublishedUserMap.has(e)&&this.remotePublishedUserMap.delete(e)}setRemotePublishedUserList(e){this.remotePublishedUserMap.forEach(t=>{let r=t[this.key];if(e.findIndex(s=>s[this.key]===t[this.key])<0){this._log.info(`remote [${r}] unpublish`);let s=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(r),this.emit("6",{prevMuteState:s,muteState:t.muteState,flag:0})}}),e.forEach(t=>{var u;let r=t[this.key];if(r===this.mySelfId){this.emit("7",t);return}let{flag:s,userId:n,tinyId:a}=t,d=Kt(s,n),l=(u=this.remotePublishedUserMap.get(r))==null?void 0:u.muteState;if(l){let h=this.remotePublishedUserMap.get(r);h&&h.flag!==s&&(h.flag=s,this._log.info(`remote publish updated: ${JSON.stringify(h.muteState)}`),this.emit("6",{prevMuteState:l,muteState:d,flag:s}))}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:Kt(0,n),muteState:d,flag:s})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function Ih({timesInSecond:o,maxSizeInSecond:i,getSize:e}){return Y((t,r)=>{let s=new WeakMap;return S.on(A.ROOM_DESTROY,({room:n})=>s.delete(n)),function(...n){let a=s.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},s.set(this,a)),a.timestamp===0?a.timestamp=Date.now():Date.now()-a.timestamp>1e3&&(a.timestamp=Date.now(),a.callCountInSecond=0,a.totalSizeInSecond=0),e&&(a.totalSizeInSecond+=e(...n)),a.timestamp!==0&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=o||a.totalSizeInSecond>i))throw new v({code:I.INVALID_OPERATION,message:$({key:B.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=o,isSize:a.totalSizeInSecond>i,name:r,timesInSecond:o,maxSizeInSecond:i}})});a.callCountInSecond++,t.call(this,...n)}})}var MS="2025-12-18 14:33:09",Tf=!0,Ef=function(){var o;if(Tf){Tf=!1,R.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${_t}/en/index.html`),console.info(`* Changelog: ${_t}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),R.info("TRTC Web SDK Version:",He),ni||R.debug("Build Time:",MS);let i=`UA: ${navigator.userAgent}
53
- CPU core: ${navigator.hardwareConcurrency}, GPU: ${Ml()}`,e=navigator.deviceMemory;e&&(i+=`, minRAM: ${e}GB`),R.info(i),R.info(`URL: ${location.href}${((o=self.frameElement)==null?void 0:o.tagName)==="IFRAME"?" in iframe":""}`),Yr().then(t=>{t&&R.info(ti)})}};var So={SCENE_LIVE:"live",SCENE_RTC:"rtc",ROLE_ANCHOR:"anchor",ROLE_AUDIENCE:"audience",STREAM_TYPE_MAIN:"main",STREAM_TYPE_SUB:"sub",AUDIO_PROFILE_STANDARD:"standard",AUDIO_PROFILE_STANDARD_STEREO:"standard-stereo",AUDIO_PROFILE_HIGH:"high",AUDIO_PROFILE_HIGH_STEREO:"high-stereo",QOS_PREFERENCE_SMOOTH:"smooth",QOS_PREFERENCE_CLEAR:"clear",SPEAKER:"Speakerphone",HEADSET:"Headset earpiece"};var W={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},Lt=(b=>(b[b.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",b[b.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",b[b.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",b[b.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",b[b.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",b[b.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",b[b.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",b[b.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",b[b.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",b[b.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",b[b.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",b[b.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",b[b.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",b[b.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",b[b.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",b[b.INVALID_ROOM_ID_REQUIRED=5015]="INVALID_ROOM_ID_REQUIRED",b[b.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",b[b.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",b[b.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",b[b.INVALID_ROOM_ID_TYPE_MISMATCH=5019]="INVALID_ROOM_ID_TYPE_MISMATCH",b[b.INVALID_ROOM_ID_DUPLICATE=5020]="INVALID_ROOM_ID_DUPLICATE",b[b.INVALID_OPERATION=5100]="INVALID_OPERATION",b[b.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",b[b.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",b[b.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",b[b.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",b[b.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",b[b.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",b[b.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",b[b.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",b[b.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",b[b.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",b[b.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",b[b.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",b[b.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",b[b.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",b[b.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",b[b.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",b[b.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",b[b.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",b[b.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",b[b.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",b[b.DEVICE_ERROR=5300]="DEVICE_ERROR",b[b.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",b[b.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",b[b.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",b[b.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",b[b.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",b[b.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",b[b.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",b[b.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",b[b.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",b[b.NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX=5310]="NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX",b[b.SERVER_ERROR=5400]="SERVER_ERROR",b[b.NEED_TO_BUY=5401]="NEED_TO_BUY",b[b.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",b[b.OPERATION_FAILED=5500]="OPERATION_FAILED",b[b.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",b[b.REJOIN_FAILED=5502]="REJOIN_FAILED",b[b.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",b[b.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",b[b.VIDEO_ENCODE_FAILED=5505]="VIDEO_ENCODE_FAILED",b[b.AUDIO_ENCODE_FAILED=5506]="AUDIO_ENCODE_FAILED",b[b.VIDEO_DECODE_FAILED=5507]="VIDEO_DECODE_FAILED",b[b.AUDIO_DECODE_FAILED=5508]="AUDIO_DECODE_FAILED",b[b.OPERATION_ABORT=5998]="OPERATION_ABORT",b[b.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",b))(Lt||{});function If({code:o,params:i,enableDocLink:e=!1}){let t="",r,s=Lt[o];try{r=Sf[s]}catch(n){r=Sf.UNKNOWN_ERROR}return le(r)?t=r(i):ie(r)&&(t=r),i.fnName&&!t.includes(i.fnName)&&(t[t.length-1]!=="."&&(t+="."),t+=` thrown from ${i.fnName}()`),e&&(t+=" doc:"),t}var Sf=w(M({},qe),{INVALID_PARAMETER({fnName:o}){return`the parameters of the '${o}' you called does not meet the requirements, please check the API documentation.`},INVALID_PARAMETER_REQUIRED({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' is a required param when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_TYPE({key:o,rule:i,fnName:e,value:t}){let r=`${o||i.name}`,s="";return Array.isArray(i.type)?s=i.type.join("|"):s=i.type,`'${r}' must be type of ${s} when calling ${e}(), received type: ${Me(t)}.`},INVALID_PARAMETER_EMPTY({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' cannot be '${t}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:o,rule:i,fnName:e,value:t}){let r=`${o||i.name}`,s=`${i.instanceOf.name||i.instanceOf}`;return`'${r}' must be instanceof ${s} when calling ${e}(), received type: ${Me(t)}.`},INVALID_PARAMETER_RANGE({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' must be one of ${i.values.join("|")} when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_LESS_THAN_ZERO({key:o,rule:i,fnName:e}){return`'${o||i.name}' cannot be less than 0 when calling ${e}().`},INVALID_PARAMETER_MIN({key:o,rule:i,value:e}){return`the min value of ${o||i.name} is ${i.min}, received: ${e}.`},INVALID_PARAMETER_MAX({key:o,rule:i,value:e}){return`the max value of ${o||i.name} is ${i.max}, received: ${e}.`},INVALID_ELEMENT_ID({key:o,fnName:i}){return`'${o}' is not found in the document object when calling ${i}().`},INVALID_ELEMENT_ID_TYPE({key:o,fnName:i,type:e}){return`the element corresponding to '${o}' must be instanceof HTMLElement when calling ${i}(), received: ${e}.`},INVALID_STREAM_ID({key:o}){return`'${o}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},INVALID_ROOM_ID_STRING({key:o}){return`'${o}' must be a valid string.`},INVALID_ROOM_ID_INTEGER({key:o}){return`'${o}' must be an integer between [1, 4294967294].`},INVALID_ROOM_ID_INTEGER_STRING({key:o}){return`'${o}' must be an integer but go a string, use 'parseInt' to convert it or use 'strRoomId' instead.`},INVALID_ROOM_ID_REQUIRED(){return"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required."},INVALID_ROOM_ID_TYPE_MISMATCH({key:o}){return`The type of target roomId must match the current roomId. Current room is using '${o}', but received '${o==="strRoomId"?"roomId":"strRoomId"}'.`},INVALID_ROOM_ID_DUPLICATE({key:o}){return`the target '${o}' must not be the same as the current '${o}'.`},INVALID_STREAM_TYPE:({fnName:o})=>`'streamType' is required when 'userId' is not '*', calling ${o}()`,INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION({fnName:o}){return`the API '${o}' you called does not meet the requirements, please check the API documentation.`},INVALID_OPERATION_NOT_JOINED({fnName:o}){return`cannot ${o} because you are not enter room yet.`},INVALID_OPERATION_REMOTE_USER_NOT_EXIST({fnName:o,value:i}){return`cannot ${o} because remote user(userId: ${i.userId}) does not publishing stream.`},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST({fnName:o,value:i}){return`cannot ${o} because remote user(userId: ${i.userId}) does not publishing ${i.streamType} video.`},INVALID_OPERATION_REPEAT_CALL({fnName:o}){return`you are already ${o}(), cannot repeated call '${o}'.`},INVALID_OPERATION_NEED_VIDEO({fnName:o}){return`cannot call '${o}' because the camera is not turned on.`},INVALID_OPERATION_NEED_AUDIO({fnName:o}){return`cannot call '${o}' because the microphone or screen share is not turned on.`},INVALID_BUFFER_EMPTY:({key:o})=>`the buffer size of paramerter '${o}' cannot be empty`,INVALID_BUFFER_OVERSIZE:()=>"buffer size is over 1000 Bytes",INVALID_ROLE_AUDIENCE:()=>"role: 'audience' cannot call this api.",INVALID_NOT_ENABLE_SEI:()=>"you need to enable SEI in TRTC.create({ enableSEI: true })",INVALID_NEED_CALL_PUBLISHED:({fnName:o})=>`you need to call ${o}() after publish stream.`,ENV_NOT_SUPPORTED({fnName:o}){return`the current browser does not support the capability of the function '${o}' you are calling, please check the API documentation.`},NOT_SUPPORTED_WEBRTC:"the current browser does not support WebRTC capability, please check the SDK documentation.",NOT_SUPPORTED_H264_ENCODE:"this browser does not support H264 encode.",NOT_SUPPORTED_H264_DECODE:"this browser does not support H264 decode.",NOT_SUPPORTED_SCREEN_SHARE:"this browser does not support screen share, please check the browser version.",NOT_SUPPORTED_SMALL_VIDEO:"this browser does not support small video, please check the browser version.",NOT_SUPPORTED_SEI:"this browser does not support SEI, please check the browser version.",NOT_SUPPORTED_WEBGL:"this browser does not support WebGL, please check the browser version.",NOT_SUPPORTED_CHROME_VERSION({fnName:o}){return`cannot call ${o} because the browser version is too low, please upgrade to the latest version`},DEVICE_ERROR({fnName:o,error:i}){return`'${o}' got device exception${i?`, error: ${i.toString()}.`:"."}`},DEVICE_NOT_FOUND_ERROR({fnName:o,deviceType:i=Io(o),error:e}){return`NotFoundError, no ${i} detected, please check your device and the configuration on '${o}'${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_ALLOWED_ERROR({fnName:o,deviceType:i=Io(o),error:e}){return`NotAllowedError, you have disabled ${i} access, please allow the current application to use the ${i}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_READABLE_ERROR({fnName:o,deviceType:i=Io(o),error:e}){return`NotReadableError, the ${i} maybe in use by another APP, please check if the device is pre-occupied by another APP.`},DEVICE_OVERCONSTRAINED_ERROR({fnName:o,deviceType:i=Io(o),error:e}){return`OverconstrainedError, the device ID is incorrect, please check whether the device ID passed in is correct${e?`, error: ${e.toString()}.`:"."}`},DEVICE_INVALID_STATE_ERROR({fnName:o,deviceType:i=Io(o),error:e}){return`InvalidStateError, after the user clicks and interacts with the page, turn on the ${i}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_SECURITY_ERROR({fnName:o,deviceType:i=Io(o),error:e}){return`SecurityError, check whether the system security policy restricts the use of the ${i}, and it is recommended to turn on the ${i} after the user interacts with the page${e?`, error: ${e.toString()}.`:"."}`},DEVICE_ABORT_ERROR({fnName:o,deviceType:i=Io(o),error:e}){return`AbortError, an unknown exception in the system makes the device unusable, recommended to change the device or browser and re-check whether the device is normal${e?` error: ${e.toString()}.`:"."}`},CAMERA_RECOVER_FAILED({error:o}){return`camera recover capture failed ${(o==null?void 0:o.name)||""}: ${(o==null?void 0:o.originMessage)||(o==null?void 0:o.message)}`},MICROPHONE_RECOVER_FAILED({error:o}){return`microphone recover capture failed ${(o==null?void 0:o.name)||""}: ${(o==null?void 0:o.originMessage)||(o==null?void 0:o.message)}`},OPERATION_FAILED({fnName:o,error:i}){return`'${o}' failed, reason: ${i==null?void 0:i.toString()}`},FIREWALL_RESTRICTION(){return"media connection failure due to firewall restrictions, please try to change your network."},EVENT_HANDLER_ERROR({eventName:o}){return`an error was caught on trtc.on('${o}', handler), please check your code on 'handler'.`},VIDEO_CONTEXT_ERROR({reason:o,error:i}){return`video context error ${o} ${(i==null?void 0:i.name)||""} ${(i==null?void 0:i.message)||""}`},SERVER_ERROR({fnName:o,error:i}){return`'${o}' got server error: ${i==null?void 0:i.toString()}, please check the SDK documentation.`},NEED_TO_BUY({value:o,url:i}){return`You need to buy packages for ${o}. Refer to: ${i}`},ACCOUNT_NO_MONEY:({fnParams:o})=>`your TRTC account run out of credit, please recharge.${o.sdkAppId?` SDKAppId: ${o.sdkAppId}`:""}`,OPERATION_ABORT({fnName:o}){return`'${o}' abort`},UNKNOWN_ERROR({fnName:o,error:i}){return`'${o}' throw unknown exception${i?`, error: ${i.toString()}.`:"."}`}});function Io(o){if(!o)return"camera";let i=o.toLowerCase();return i.includes("screen")?"screen share":i.includes("audio")?"microphone":"camera"}var Ah=class o extends Error{constructor({code:e,extraCode:t,message:r="",messageParams:s,fnName:n="",originError:a,data:d}){var u;let l;r?l=r:l=If({code:e===W.SERVER_ERROR?e:t||e,params:M({fnName:n,error:a},s)});super(l);c(this,"name","RtcError");c(this,"code");c(this,"extraCode");c(this,"functionName");c(this,"message");c(this,"data");c(this,"handler");c(this,"originError");this.name=Lt[e],this.code=e,this.extraCode=t,this.functionName=n,this.originError=a,this.message=l,this.data=d,this.extraCode===5302&&((u=this.originError)!=null&&u.message.includes("system"))&&(this.handler=()=>{let h={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},p={startLocalVideo:"webcam",startLocalAudio:"microphone"},m=document.createElement("a");Qr?m.href=`ms-settings:privacy-${p[this.functionName]}`:si&&(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 s=e;if(e instanceof v){let{stack:n}=e,a={code:W.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case I.INVALID_PARAMETER:a.code=W.INVALID_PARAMETER,a.message=e.message;break;case I.INVALID_OPERATION:a.code=W.INVALID_OPERATION;break;case I.NOT_SUPPORTED:case I.NOT_SUPPORTED_H264:a.code=W.ENV_NOT_SUPPORTED,e.getCode()===I.NOT_SUPPORTED_H264&&(a.extraCode=e.message.includes(qe.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case I.JOIN_ROOM_FAILED:a.messageParams={fnParams:r};case I.SERVER_TIMEOUT:case I.SWITCH_ROLE_FAILED:case I.SWITCH_ROOM_FAILED:a.code=W.SERVER_ERROR,a.extraCode=e.getExtraCode();break;case I.API_CALL_ABORTED:a.code=W.OPERATION_ABORT;break;case I.DEVICE_NOT_FOUND:case I.DEVICE_AUTO_RECOVER_FAILED:case I.INITIALIZE_FAILED:a.code=5300,e.name&&(a.extraCode=OS(e.name));break;case I.VIDEO_ENCODE_FAILED:a.extraCode=5505;case I.AUDIO_ENCODE_FAILED:a.extraCode=5506,a.code=W.OPERATION_FAILED;break;case I.UNKNOWN:break;default:a.code=W.OPERATION_FAILED}s=new o(a),n&&(s.stack+=n.substr(n.indexOf(`
54
- `)))}else{if(e instanceof o)return e;s=new o({code:W.UNKNOWN_ERROR,fnName:t,originError:e})}return s}};function OS(o){let i;switch(o){case"NotFoundError":i=5301;break;case"NotAllowedError":i=5302;break;case"NotReadableError":i=5303;break;case"OverconstrainedError":i=5304;break;case"InvalidStateError":i=5305;break;case"SecurityError":i=5306;break;case"AbortError":i=5307;break;default:i=5300}return i}var F=Ah;function Li(o){return o==="sub"?"auxiliary":o==="auxiliary"?"sub":"main"}function Gn(o){return o===So.QOS_PREFERENCE_CLEAR?"detail":o===So.QOS_PREFERENCE_SMOOTH?"motion":""}function Ss(o,i){let e=i?jc:pr;return Tl(o)?M(M({},e),o):zt[o]?zt[o]:e}var Af={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}}},Cf={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}}},Is={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(o,i,e){if(ie(o)&&!document.getElementById(o))throw new F({code:W.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:i}})}},Rf={name:"userId",required:!0,type:"string"},yf={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{type:["string","object"],properties:{bitrate:{type:"number"},channelCount:{type:"number"}}},echoCancellation:{values:[!0,!1,"remote-only","all"]},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function As(o,i){if(!o)throw new F({code:W.INVALID_OPERATION,extraCode:5101,fnName:i})}function bf(o,i,e){if(!o)throw new F({code:W.INVALID_OPERATION,extraCode:5102,fnName:i,messageParams:{value:e}})}function Nf(o,i,e){if(!(/^[1-9]\d*$/.test(String(o))&&o<4294967295))throw new F({code:W.INVALID_PARAMETER,extraCode:5013,fnName:i,messageParams:{key:e}})}function vf(o,i,e){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(o))throw new F({code:W.INVALID_PARAMETER,extraCode:5012,fnName:i,messageParams:{key:e}})}var FL={type:"number",notLessThanZero:!0},kS=(o,i)=>o.width*o.height>=i.width*i.height&&o.frameRate>=i.frameRate&&o.bitrate>=i.bitrate;function Df(o){var t;if(!((t=o==null?void 0:o.option)!=null&&t.small))return;if(!gd()){R.warn("small stream is not supported"),delete o.option.small;return}let i=Ss(o.option.profile),e=Ss(o.option.small,!0);if(!kS(i,e)){R.warn(`small stream profile must be less than big stream profile. Big: ${JSON.stringify(i)}, Small: ${JSON.stringify(e)}`),delete o.option.small;return}}var PS={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(o,i,e){if(this._room.isJoined)throw new F({code:W.INVALID_OPERATION,extraCode:5104,fnName:e});if(o.roomId){if(ie(o.roomId))throw new F({code:W.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:i}});Nf(o.roomId,e,i)}else if(o.strRoomId)vf(o.strRoomId,e,i);else throw new F({code:W.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:Is,mute:{type:["boolean","string"]},publish:{type:"boolean"},capture:{required:!1,type:"boolean"},option:Af},validate(o){var i,e;if(!((i=o==null?void 0:o.option)!=null&&i.videoTrack)&&Zi())throw new F({code:W.ENV_NOT_SUPPORTED,extraCode:5201});(e=o==null?void 0:o.option)!=null&&e.small&&Df(o)}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:w(M({},Is),{required:!1}),publish:{type:"boolean"},capture:{required:!1,type:"boolean"},mute:{type:["boolean","string"]},option:Af},validate(o){var i;(i=o==null?void 0:o.option)!=null&&i.small&&Df(o)}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:yf},validate(o){var i;if(!((i=o==null?void 0:o.option)!=null&&i.audioTrack)&&Zi())throw new F({code:W.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:yf}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:Is,publish:{type:"boolean"},option:Cf},validate(o,i,e,t,r){var s;if(!((s=o==null?void 0:o.option)!=null&&s.videoTrack)){if(Zi())throw new F({code:W.ENV_NOT_SUPPORTED,extraCode:5201});if(!fn())throw new F({code:W.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:Is,publish:{type:"boolean"},option:Cf}},muteRemoteAudio:[Rf,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[Rf,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:Is,userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(o,i,e){As(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(o.userId);if(bf(!!t,e,o),t&&(o.streamType==="main"&&!t.muteState.videoAvailable||o.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new F({code:W.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:o}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:w(M({},Is),{required:!1}),userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(o,i,e){As(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(o.userId);if(bf(!!t,e,o),t&&(o.streamType==="main"&&!t.muteState.videoAvailable||o.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new F({code:W.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:o}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(o,i,e){if(o.userId!=="*"&&T(o.streamType))throw new F({code:W.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(o,i,e){As(this._room.isJoining||this._room.isJoined,e)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(o,i,e,t){if(!Tn)throw new F({code:W.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new F({code:W.INVALID_OPERATION,fnName:e,extraCode:5108});if(o.byteLength>1e3)throw new F({code:W.INVALID_PARAMETER,extraCode:5018,fnName:e});if(o.byteLength===0)throw new F({code:W.INVALID_PARAMETER,extraCode:5017,messageParams:{key:i},fnName:e});As(this._room.isJoined,e)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(o,i,e){if(!o&&!this._room.isMainStreamPublished||o&&!this._room.isAuxStreamPublished)throw new F({code:W.INVALID_OPERATION,extraCode:5109,messageParams:{key:i},fnName:e})}}}}],sendCustomMessage:{name:"message",required:!0,type:"object",properties:{cmdId:{type:"number",required:!0,min:1,max:10},data:{instanceOf:ArrayBuffer,required:!0,validate(o,i,e,t){if(o.byteLength>1e3)throw new F({code:W.INVALID_PARAMETER,extraCode:5018,fnName:e});if(o.byteLength===0)throw new F({code:W.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:i}})}}},validate(o,i,e){if(As(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new F({code:W.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:i}})}},switchRoom:{name:"switchRoomConfig",type:"object",required:!0,validate(o,i,e){if(As(this._room.isJoined,e),this._room.useStringRoomId&&o.strRoomId===this._room.roomId||!this._room.useStringRoomId&&o.roomId===Number(this._room.roomId))throw new F({code:W.INVALID_PARAMETER,extraCode:5020,fnName:e,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(o.roomId&&this._room.useStringRoomId||!o.roomId&&o.strRoomId&&!this._room.useStringRoomId)throw new F({code:W.INVALID_PARAMETER,extraCode:5019,fnName:e,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(o.roomId)Nf(o.roomId,e,i);else if(o.strRoomId)vf(o.strRoomId,e,i);else throw new F({code:W.INVALID_PARAMETER,extraCode:5015,fnName:e})},properties:{roomId:{type:"number"},strRoomId:{type:"string"},privateMapKey:{type:"string"},userSig:{type:"string",required:!0},autoSubscribeCount:{type:"number",min:0,max:50}}}},Ge={TRTC:PS};var lt=class extends Error{};function LS(o,i){let e=Gr(o);for(let t=0;t<i.length;t++)ei(e[t],i[t]);return e}function xS(o){this._resolve=Promise.resolve(o)}function wS(o){this._reject=Promise.reject(o)}var Pr=class Pr{constructor(i,e){this.instance=i;this.group=e;c(this,"started",!1);c(this,"ops",[]);c(this,"startSame",()=>!0);c(this,"mergeUpdate",LS);let t=Pr.instances.get(i);t?t.set(e,this):Pr.instances.set(i,new Map([[e,this]]))}static get(i,e){if(!e)return;let t=Pr.instances.get(i);return t&&t.get(e)||new Pr(i,e)}static gets(i,e){let t=Pr.instances.get(i),r=[];return t&&t.forEach((s,n)=>{e.test(n)&&r.push(s)}),r}action(i,e,t){let r=a=>{var d;return i===0?this.started=!0:i===3&&(this.started=!1),this.ops.shift(),(d=this.currentOp)==null||d.action(),a},s=a=>{var d,l;throw this.ops.shift(),i===0&&((d=this.currentOp)==null?void 0:d.type)===2&&this.ops.shift().reject(new lt("start failed")),(l=this.currentOp)==null||l.action(),a},n={type:i,action:()=>e(...n.args).then(r,s),args:t,resolve:xS,reject:wS};try{switch(this.state){case 1:if(i===0)throw new lt("already started");break;case 4:if(i===2)throw new lt("not started");break;default:return this.cacheOp(n)}}catch(a){return Promise.reject(a)}return this.ops.push(n),n.promise=e(...n.args).then(r,s)}cacheOp(i){if(this.ops.length===1)switch(this.state){case 0:case 2:if(i.type===0)throw new lt("already start");break;case 3:switch(i.type){case 2:throw new lt("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new lt("unknown state")}else switch(i.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let t=new lt("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 lt("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new lt("start not allowed after update");case 0:throw new lt("duplicate start");case 3:if(this.startSame(this.currentOp.args,i.args))throw this.ops.pop().reject(new lt("keep start")),new lt("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(Pr,"instances",new WeakMap);var nr=Pr;var sc=new WeakMap,nc=(o,i)=>{if(i instanceof lt){let{stack:e}=i;i=new F({code:W.OPERATION_ABORT,message:`${o} abort: ${i.message}`,fnName:o}),e&&(i.stack+=e.substr(e.indexOf(`
55
- `)))}throw i};function Lr(o,i){return Y((e,t)=>function(...r){let s=nr.get(this,typeof o=="string"?o:o.call(this,...r));return s?(i&&(s.startSame=i.bind(this)),s.action(0,e.bind(this),r).catch(nc.bind(null,t))):e.apply(this,r)})}function Ao(o,i){let{merge:e,debounce:t}=i||{};return Y((r,s)=>function(...n){let a=nr.get(this,typeof o=="string"?o:o.call(this,...n));if(!a)return r.apply(this,n);if(e&&(a.mergeUpdate=e.bind(this)),t&&t.isNeedToDebounce.apply(this,n)){let{delay:d,getKey:l}=t;return new Promise((u,h)=>{var g,E;let p=(g=sc.get(this))==null?void 0:g.get(l(...n));if(p){let{timeoutId:C,resolve:P}=p;clearTimeout(C),P()}let m=setTimeout(()=>{if(a.state===3||a.state===4)return u();a.action(2,r.bind(this),n).catch(nc.bind(null,s)).then(u,h)},d);sc.has(this)?(E=sc.get(this))==null||E.set(l(...n),{timeoutId:m,resolve:u}):sc.set(this,new Map([[l(...n),{timeoutId:m,resolve:u}]]))})}return a.action(2,r.bind(this),n).catch(nc.bind(null,s))})}function xr(o){return Y((i,e)=>function(...t){let r=typeof o=="function"?o.call(this,...t):o;if(r instanceof RegExp)return Promise.all(nr.gets(this,r).map(n=>n.action(3,()=>Promise.resolve(),t))).then(()=>i.call(this,...t));let s=nr.get(this,r);return s?s.action(3,i.bind(this),t).catch(nc.bind(null,e)):i.apply(this,t)})}function wr(){return function(o,i,e){return o.prototype[i]=function(){let t=this._log||console,r=`"${i}" is a static method. Use TRTC.${i}() instead. See: ${_t}/en/TRTC.html#.${i}`;t.warn(r)},e}}var U={ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",KICKED_OUT:"kicked-out",REMOTE_USER_ENTER:"remote-user-enter",REMOTE_USER_EXIT:"remote-user-exit",REMOTE_AUDIO_AVAILABLE:"remote-audio-available",REMOTE_AUDIO_UNAVAILABLE:"remote-audio-unavailable",REMOTE_VIDEO_AVAILABLE:"remote-video-available",REMOTE_VIDEO_UNAVAILABLE:"remote-video-unavailable",AUDIO_VOLUME:"audio-volume",AUDIO_FRAME:"audio-frame",NETWORK_QUALITY:"network-quality",CONNECTION_STATE_CHANGED:"connection-state-changed",AUDIO_PLAY_STATE_CHANGED:"audio-play-state-changed",VIDEO_PLAY_STATE_CHANGED:"video-play-state-changed",SCREEN_SHARE_STOPPED:"screen-share-stopped",DEVICE_CHANGED:"device-changed",PUBLISH_STATE_CHANGED:"publish-state-changed",TRACK:"track",STATISTICS:"statistics",SEI_MESSAGE:"sei-message",CUSTOM_MESSAGE:"custom-message",VIDEO_DECODE_DOWNGRADE_STATE_CHANGED:"video-decode-downgrade-state-changed",LAYER_DATA:"layerData",FIRST_VIDEO_FRAME:"first-video-frame",PERMISSION_STATE_CHANGE:"permission-state-change",VIDEO_SIZE_CHANGED:"video-size-changed"},Mf=new Set([U.AUDIO_VOLUME,U.AUDIO_FRAME,U.NETWORK_QUALITY,U.STATISTICS,U.SEI_MESSAGE,U.CUSTOM_MESSAGE,U.LAYER_DATA]);var yh={};Bi(yh,{ScheduleRequestType:()=>Pf,getAbilityConfig:()=>FS,getScheduleDomain:()=>cc,isNeedToSchedule:()=>ac,scheduleProxy:()=>xi,sendScheduleRequest:()=>Rh,setIsNeedToSchedule:()=>xt,setScheduleProxy:()=>dc});var Ch=null,kf=0,US=48*3600*1e3,ac=!0;typeof document!="undefined"&&document.head.insertAdjacentHTML("beforeend",Object.values(Gi).map(o=>`<link rel="dns-prefetch" href="https://${o}">`).join(`\r
56
- `));function xt(o){ue(o)&&o!==ac&&(ac=o,R.info(`setIsNeedToSchedule ${o}`),o||(kf=Date.now()+US))}S.on("28",()=>xt(!0));S.on("63",()=>xt(!0));S.on("84",()=>xt(!0));S.on("201",o=>{o.state==="RECONNECTING"&&xt(!0)});S.on("202",o=>{o.state==="RECONNECTING"&&xt(!0)});function VS(o,i,e){let t={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let r=performance.getEntriesByType("resource"),s=Ur(o,"config",_.MAIN),n=Ur(o,"config",_.BACKUP);for(let a of r)if(a.startTime>=e&&(a.name===s||a.name===n)&&a.transferSize>0){let d=a.name===s?_.MAIN:_.BACKUP,l=Math.round(a.duration),u=Math.round(a.domainLookupStart-a.startTime),h=a.redirectStart>0?Math.round(a.redirectEnd-a.redirectStart):0,p=a.fetchStart>0?Math.round(a.domainLookupStart-a.fetchStart):0,m=Math.round(a.domainLookupEnd-a.domainLookupStart),g=Math.round(a.requestStart-a.secureConnectionStart),E=Math.round(a.secureConnectionStart-a.connectStart),C=Math.round(a.responseStart-a.requestStart),P=Math.round(a.responseEnd-a.responseStart),re=[m,g,E,C,P];se.uploadEvent({log:`stat-schedule-net:${l}(${u}(${h}->${p})->${re.join("->")}) ${d}`,userId:i}),t=w(M({},t),{totalCost:l,local:u,dns:m,tcp:E,tls:g,request:C,response:P});break}}catch(r){R.error("getScheduleDetailCost error",r)}return t}function Rh(l){return f(this,arguments,function*({userId:o,sdkAppId:i,useStringRoomId:e,roomId:t,userSig:r,version:s,frameWorkType:n,role:a,latencyLevel:d}){var h;if(!ac&&Ch&&kf>Date.now())return{isCached:!0,result:Ch};let u={delta:0,count:[1,1],msg:[],detail:[]};try{let p=new FormData;p.append("userId",String(o)),p.append("sdkAppId",String(i)),p.append("isStrGroupId",String(e)),p.append("groupId",String(t)),p.append("sdkVersion",s),p.append("userSig",String(r));let m=((h=yield Yr())==null?void 0:h.model)||ed();m&&p.append("model",m);let g=di();g&&p.append("osString",g),a&&p.append("role",String(a)),d&&p.append("latencyLevel",String(d)),n&&p.append("frameWorkType",String(n));let E=V(),C=yield HS(p,u,i);C.config&&(C.config.loggerDomain&&Fr(C.config.loggerDomain),ue(C.config.scheduleCache)&&xt(!C.config.scheduleCache)),u.delta=V()-E;let P=VS(Number(i),o,E);return Ch=C,{isCached:!1,result:C,detailCost:P}}catch(p){let m=Ae(p)?p[0]:p,g=Q(m.code)?m.code:0,E=`schedule failed${m.message?`: ${m.message}`:""}`,C=new v({code:I.SCHEDULE_FAILED,extraCode:g,message:$({key:B.JOIN_ROOM_FAILED,data:{error:E,code:g}})});throw R.error(E,g),C}})}var xi={main:"",backup:""};function dc(o){Ae(o)?(xi.main=o[0],xi.backup=o[1]):xi.main=o}var Pf=(t=>(t.CONFIG="config",t.TRTC_AUTO_CONF="trtcAutoConf",t.AUDIO_AI_AUTH="audioAiAuth",t))(Pf||{});function Ur(o,i,e=_.MAIN,t=!1){return`https://${xi[e]||cc(o,e,t)}/api/v1/${i}`}function FS(o,i,e){let t=Ur(o,i),r=Ur(o,i,_.BACKUP),s=new URLSearchParams(e).toString(),n=fetch(`${t}?${s}`).then(d=>d.json()),a=fetch(`${r}?${s}`).then(d=>d.json());return Xr([n,a])}function cc(o,i=_.MAIN,e=!1){let t;return Ut(o)?e?t=i===_.MAIN?Gi.MAIN_OVERSEA_BACKUP:Gi.BACKUP_OVERSEA:t=i===_.MAIN?Gi.MAIN_OVERSEA:Gi.BACKUP_OVERSEA:t=i===_.MAIN?Gi.MAIN:Gi.BACKUP,t}function BS(o,i,e){return new Promise((t,r)=>{ji({url:o,body:i,timeout:e.timeout,priority:"high"}).then(s=>{s.data.code===0?t(s.data.data):r({code:s.data.code,message:s.data.msg})}).catch(r)})}var Of=(o,i)=>Ri({retryFunction:BS,settings:{retries:3,timeout:0},onError:i,onRetrying:o});function HS(o,i,e){return new Promise((t,r)=>{let s=null;Xr([Of(n=>i.count[0]=n+1,({error:n,retry:a,retriedCount:d,retryFuncArgs:l})=>{i.msg[0]=n.message,s||(d>=1&&(l[0]=Ur(e,"config",_.MAIN,!0)),a())})(Ur(e,"config",_.MAIN),o,{get timeout(){return qr(2+i.count[0])*1e3}}),Of(n=>i.count[1]=n+1,({error:n,retry:a,retriedCount:d,retryFuncArgs:l})=>{i.msg[1]=n.message,s||(d>=2&&(l[0]=Ur(e,"config",_.BACKUP,!0)),a())})(Ur(e,"config",_.BACKUP),o,{get timeout(){return qr(2+i.count[1])*1e3}})]).then(n=>{s=n,t(s)}).catch(r)})}var $S=o=>o.startsWith("data:application/octet-stream;base64,"),WS=o=>o.startsWith("file://"),Jn=class{constructor(){c(this,"_log");this._log=R.createLogger({id:"fd"})}download(i,e){return f(this,null,function*(){let{type:t="blob"}=e||{};i=Da(i);try{let r=V(),s;if(le(fetch)?s=yield this.downloadWithFetch(i,t):s=yield this.downloadWithXHR(i,t),!s||!s.data)throw new Error("data is empty");let n=V()-r;return this._log.info(`downloaded: ${i}, return type: ${t}, cost: ${n}ms`),y.addSuccessEvent({key:522700,cost:V()-r}),s.data}catch(r){throw this._log.error(`failed to download: ${i}, error: ${r}`),y.addFailedEvent({key:522700,error:r}),r}})}downloadWithFetch(i,e){return f(this,null,function*(){this._log.info(`download with fetch: ${i}, return type: ${e}`);try{let t=yield fetch(i);if(!t.ok){let s=new Error(`network response was not ok: ${t.status}`);throw s.status=t.status,s}let r;return e==="arraybuffer"?r=yield t.arrayBuffer():r=yield t.blob(),{data:r}}catch(t){throw t}})}downloadWithXHR(i,e){return this._log.info(`download with xhr: ${i}, return type: ${e}`),new Promise((t,r)=>{let s=new XMLHttpRequest;s.open("GET",i,!0),s.responseType=e,s.onload=()=>{if(s.status===200||s.status===0&&s.response)t({data:s.response});else{let n=new Error(`XHR failed, status: ${s.status}`);n.status=s.status,r(n)}},s.onerror=r,s.send(null)})}loadWasm(i,e){return f(this,null,function*(){this._log.info(`loadWasm ${i}, importObject: ${JSON.stringify(e)}`);let t=V(),r=null,s=null;if(le(WebAssembly.instantiateStreaming)&&!$S(i)&&!WS(i)&&le(fetch))try{let n=fetch(i);r=(yield WebAssembly.instantiateStreaming(n,e)).instance}catch(n){s=n}if(!r)try{let n=yield this.download(i,{type:"arraybuffer"});r=(yield WebAssembly.instantiate(n,e)).instance}catch(n){s=n}if(r){let n=V()-t;return this._log.info(`loadedWasm ${i}, cost: ${n}ms`),y.addSuccessEvent({key:522701,cost:n}),r}throw this._log.error(`failed to loadWasm ${i}, error: ${s}`),y.addFailedEvent({key:522701,error:s}),s})}loadScript(i){this._log.info(`loadScript ${i}`);let e=V();return new Promise((t,r)=>{let s=document.createElement("script");s.type="text/javascript",s.onload=()=>{this._log.info(`loadedScript ${i}, cost: ${V()-e}ms`),y.addSuccessEvent({key:522702,cost:V()-e,split:1e3}),t(s)},s.onerror=n=>{this._log.error(`failed to loadScript ${i}, error: ${(n==null?void 0:n.message)||JSON.stringify(n)}`),y.addFailedEvent({key:522702}),r(n)},s.crossOrigin="anonymous",s.src=i,document.head.append?document.head.append(s):document.getElementsByTagName("head")[0].appendChild(s)})}};D([Mt({settings:{timeout:0,retries:3},onError(i,e,t){var r;(i==null?void 0:i.status)===404||(r=i==null?void 0:i.message)!=null&&r.includes("404")?(this._log.warn("download 404, stop retry"),t(i)):e()},onRetrying(i){this._log.warn(`download retrying: ${i}`)}})],Jn.prototype,"download",1),D([Mt({settings:{timeout:3e3,retries:3},onRetrying(i){this._log.warn(`loadScript retrying: ${i}`)}})],Jn.prototype,"loadScript",1);var qn=new Jn;var Lf=!1,xf;function wf({TRTC:o,room:i,errorModule:e,assetsPath:t}){return{TRTC:o,LocalMixVideoTrack:go,LocalVideoTrack:je,LocalScreenTrack:Pt,room:i,assetsPath:t,fileDownloader:qn,innerEmitter:S,INNER_EVENT:A,constants:il,environment:Ko,utils:gh,eventLogger:se,log:this.room.getLogger(),loggerManager:R,errorModule:e,kvStatManager:y,rtcDectection:vi,trtc:this,rx:fh,enums:zl,schedule:yh,getDevices:cs,initVisionTaskRegistry:(r,s,n="/mediapipe/vision.js")=>f(this,null,function*(){!window.VisionTaskRegistry&&!Lf&&(Lf=!0,xf=qn.loadScript(`${r}/${n}`.replace(/([^:]\/)\/+/g,"$1"))),yield xf,yield(yield window.VisionTaskRegistry.getInstance(r)).preloadModels(s)}),audioContext:Ee(),deviceDetector:be,AudioPlayer:us,showAutoPlayDialog:ns,Timer:oe,clearStarted:(r,s)=>{let n=r.getAlias(),a=nr.instances.get(this);if(a)if(s){let d=a.get(n+s);if(!d)return;d.started=!1}else a.forEach((d,l)=>{l.startsWith(n)&&(d.started=!1)})},startGetPCM:Wn,createAudioNode:Mn,getNetworkTimeOffset:fm,validateSourceNode:()=>{var r;if(ee&&!((r=this.room.audioManager._localAudioPipline)!=null&&r.source.node))throw new F({code:W.DEVICE_ERROR,extraCode:5310,message:"The audio processing plugin cannot be used due to the microphone's sampling rate is not 48KHz in Firefox. Please switch to another browser such as Chrome."})}}}var Uf=(o,i)=>{let{emit:e}=o;return o.emit=(...t)=>{try{return e.apply(o,t)}catch(r){let s=$({key:B.CATCH_HANDLER_ERROR,data:{name:i,event:t[0]},addDocLink:!1});return R.warn(`${s}
52
+ } `;var _o=class extends j{constructor(e){super();d(this,"frameRate");d(this,"_canvas");d(this,"log");d(this,"hasAlpha",!1);d(this,"name");d(this,"error");this.name=e.name,this.log=e.logger.createChild({id:`vc-${this.name}`}),this.frameRate=e.frameRate}get canvas(){return this._canvas}set width(e){this._canvas&&(this._canvas.width=e)}get width(){var e;return((e=this._canvas)==null?void 0:e.width)||0}set height(e){this._canvas&&(this._canvas.height=e)}get height(){var e;return((e=this._canvas)==null?void 0:e.height)||0}setSize(e,t){this._canvas&&(this._canvas.width=e,this._canvas.height=t)}createVideoTrackSource(e,t){return new Wt(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new gs(this,e)}createVideoImageSource(e,t){return new qn(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new Jn(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}createTextSource(e,t){return new od(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}};d(_o,"_ids",0);var yS={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},Ts=class Ts extends _o{constructor(){super(...arguments);d(this,"defaultProgam");d(this,"defaultVShader");d(this,"defaultFShader");d(this,"ctx");d(this,"_canvas2d")}get canvas(){return this._canvas2d||this._canvas}create(e=!1){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${_o._ids++}`),e&&(this._canvas2d=document.createElement("canvas")),this.ctx=this._canvas.getContext("webgl2",yS),!this.ctx)throw new D({code:I.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,CS),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,RS),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})}destroy(e){let t="";return e&&(t=e.message,this.error=e,v.addFailedEvent({key:512702,error:e})),this.disconnect(),this.log.info(`video context destroy${t}`?`: ${t}`:""),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),e}set width(e){var t;(t=this.ctx)==null||t.viewport(0,0,e,this.height),super.width=e,this._canvas2d&&(this._canvas2d.width=e)}set height(e){var t;(t=this.ctx)==null||t.viewport(0,0,this.width,e),super.height=e,this._canvas2d&&(this._canvas2d.height=e)}setSize(e,t){var r;(r=this.ctx)==null||r.viewport(0,0,e,t),super.setSize(e,t),this._canvas2d&&(this._canvas2d.width=e,this._canvas2d.height=t)}createShader(e,t){let r=this.ctx,s=r.createShader(e);return r.shaderSource(s,t),r.compileShader(s),s}createProgram(e,t){let r=this.ctx,s=r.createProgram();return r.attachShader(s,e),r.attachShader(s,t),r.linkProgram(s),r.getProgramParameter(s,r.LINK_STATUS)||this.log.error(r.getProgramInfoLog(s)),s}};d(Ts,"UNAVAILABLE","unavailable"),M([be(j.INIT,"created",{sync:!0,fail(e){this.log.error("video gl context create failed",e.cause),v.addFailedEvent({key:512700,error:e.cause||e})},success(){this.log.info("video context created use webgl"),v.addSuccessEvent({key:512700})}})],Ts.prototype,"create",1),M([be("created",j.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(Ts.UNAVAILABLE,e),this.removeAllListeners()}})],Ts.prototype,"destroy",1);var He=Ts,Qe=class extends _o{constructor(){super(...arguments);d(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${_o._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:e.alpha,willReadFrequently:e.willReadFrequently}),!this.ctx)throw new D({code:I.VIDEO_MANAGER_ERROR,extraCode:2,message:"2d context not supported"});this._canvas.addEventListener("contextlost",()=>{this.log.error("2d context lost")}),this._canvas.addEventListener("contextrestored",()=>{this.log.warn("2d context restored")})}destroy(e){let t="";e&&(t=e.message,this.error=e,v.addFailedEvent({key:512703,error:e})),this.disconnect(),this.log.info(`video context destroy ${t?`: ${t}`:""}`),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners(),v.addSuccessEvent({key:512703})}};M([be(j.INIT,"created",{sync:!0,fail(e){this.log.error("video 2d context create failed",e.cause),v.addFailedEvent({key:512701,error:e.cause||e})},success(){this.log.info("video context created use 2d"),v.addSuccessEvent({key:512701})}})],Qe.prototype,"create",1),M([be("created",j.INIT,{ignoreError:!0,sync:!0})],Qe.prototype,"destroy",1);function bS(o,i,e,t,r,s=!1){s&&([e,t]=[t,e]);let n={sWidth:o,sHeight:i,dWidth:e,dHeight:t,sx:0,sy:0,dx:0,dy:0};if(o===0||i===0)return n;switch(r){case void 0:case"fill":break;case"contain":{let a=Math.min(e/o,t/i);n.dWidth=o*a,n.dHeight=i*a,n.dx=(e-n.dWidth)/2,n.dy=(t-n.dHeight)/2;break}case"cover":{let a=Math.max(e/o,t/i),c=e/a,l=t/a;n.sx=(o-c)/2,n.sy=(i-l)/2,n.sWidth=c,n.sHeight=l;break}}return n}var vh=class{constructor(i,e){this.node=i;this.layout=e;d(this,"positionBuffer")}get x(){return this.layout.x||this.node.x}get y(){return this.layout.y||this.node.y}get width(){return this.layout.width||this.node.width}get height(){return this.layout.height||this.node.height}get right(){return this.x+this.width}get bottom(){return this.y+this.height}get fillMode(){return this.layout.fillMode}get rotation(){return this.layout.rotation}get hidden(){return!!this.layout.hidden}},Es=class extends Ve{constructor(e,t){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:t});d(this,"inputs",[]);d(this,"backgroundColor","black")}addInput(e,t){let r=0,s=this.inputs.length;for(;r<s;){let a=Math.floor((r+s)/2);if(this.inputs[a].layout.zIndex<t.zIndex)r=a+1;else if(this.inputs[a].layout.zIndex>t.zIndex)s=a;else throw new Error(`input already exists at zIndex ${t.zIndex}`)}let n=new vh(e,t);this.inputs.splice(r,0,n)}changeInputLayout(e,t){let r=this.inputs.findIndex(g=>g.node===e);if(r<0)return;let{x:s,y:n,width:a,height:c,zIndex:l,fillMode:h,rotation:m,hidden:u}=t;if(!T(l)&&this.inputs.some(g=>g.layout.zIndex===l&&g.node!==e))throw new Error(`input already exists at zIndex ${t.zIndex}`);let _=this.inputs[r];T(s)||(_.layout.x=s),T(n)||(_.layout.y=n),T(a)||(_.layout.width=a),T(c)||(_.layout.height=c),T(m)||(_.layout.rotation=m),T(u)||(_.layout.hidden=u),h&&(_.layout.fillMode=h),!T(l)&&l!==_.layout.zIndex&&(_.layout.zIndex=l,this.inputs.sort((g,E)=>g.layout.zIndex-E.layout.zIndex))}hasInput(e){return this.inputs.some(t=>t.node===e)}hasNoInput(){return this.inputs.length===0}resize(e,t){if(!this.matchInputSize){super.resize(e,t);return}let r=this.inputs.reduce((s,n)=>n?Object.assign(s,{width:Math.max(s.width,n.right),height:Math.max(s.height,n.bottom)}):s,{width:0,height:0});super.resize(r.width,r.height),this.context instanceof He&&this.inputs.forEach(s=>{if(s){let n=this.layout2texCoords(s);s.positionBuffer?this.changeBufferData(s.positionBuffer,n):s.positionBuffer=this.createBuffer(n)}})}connect(e,...t){return super.connect(e,...t),this.drawBackGround2d(this.backgroundColor),this.matchInputSize&&this.resize(0,0),e}removeInput(e){this.inputs=this.inputs.filter(t=>t.node!==e),this.inputs.length===0&&this.drawBackGround2d(this.backgroundColor)}render(e){let t=this.context.ctx;if(t.clearColor(0,0,0,0),this.inputs.reduce((s,n)=>n.node.requestFrame(e)||s,!1)&&t){this.useProgram(),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let s=0;s<this.inputs.length;s++){let n=this.inputs[s];n&&(n.node.useTexture(),this.draw(n.positionBuffer))}return!0}return!1}render2d(e){if(this.inputs.forEach(t=>t.node.requestFrame(e)),this.ctx2d){this.drawBackGround2d(this.backgroundColor);for(let t=0;t<this.inputs.length;t++){let r=this.inputs[t];if(r.hidden)continue;let s=bS(r.node.width,r.node.height,r.width,r.height,r.fillMode,bt(r.rotation));this.draw2d(r.node.image,r.x+s.dx,r.y+s.dy,s.dWidth,s.dHeight,s.sx,s.sy,s.sWidth,s.sHeight)}return!0}return!1}debugLayout(e,t,r,s,n=!1){this.ctx2d&&(n&&([r,s]=[s,r]),this.ctx2d.save(),this.ctx2d.strokeStyle="red",this.ctx2d.lineWidth=2,this.ctx2d.strokeRect(e,t,r,s),this.ctx2d.restore())}getInfo(){let{totalFrames:e,x:t,y:r,width:s,height:n,name:a}=this,c=Date.now(),l=(e-this.lastInfo.totalFrames)/((c-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:r,width:s,height:n,timestamp:c,fps:l,name:a},O({parent:this.inputs.filter(h=>h).map(h=>h.node.getInfo())},this.lastInfo)}removeAllInputs(){this.inputs.forEach(e=>{var t;if(e.node.disconnect(),e.positionBuffer&&this.context instanceof He)try{(t=this.context.ctx)==null||t.deleteBuffer(e.positionBuffer)}catch(r){}})}close(){super.close(),this.removeAllInputs()}};var vS=[1,0,0,0,1,1,0,1],qt=class extends Ve{constructor(e,t,r,s){super(e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"transform",logger:t});d(this,"mirror",!1);d(this,"rotation",0);if(r&&(this.mirror=r),s&&(this.rotation=s),e instanceof He)try{this.setTexBuffer(vS)}catch(n){e.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${n.message||n}`}))}}draw2d(e,t,r,s,n){if(this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height),this.ctx2d.save(),this.mirror&&(this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0)),this.rotation===90?(this.ctx2d.translate(s,0),this.ctx2d.rotate(Math.PI/2),this.ctx2d.scale(n/s,s/n)):this.rotation===180?(this.ctx2d.translate(this.width,this.height),this.ctx2d.rotate(Math.PI)):this.rotation===270&&(this.ctx2d.translate(0,n),this.ctx2d.rotate(3*Math.PI/2),this.ctx2d.scale(n/s,s/n));let a=super.draw2d(e,t,r,s,n);return this.ctx2d.restore(),a}return!1}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}resize(e,t){bt(this.rotation)&&([e,t]=[t,e]),super.resize(e,t)}};var go=class extends fi{constructor(e,t=4){super(t,it);d(this,"inputLocalVideoTracks",new Map);d(this,"inputLocalScreenTracks",new Map);d(this,"cameraNodeMap",new Map);d(this,"screenNodeMap",new Map);d(this,"textNodeMap",new Map);d(this,"imageNodeMap",new Map);d(this,"videoNodeMap",new Map);d(this,"endedIds",new Set);d(this,"videoContext");d(this,"mixNode");d(this,"destination");d(this,"manager");d(this,"stat");d(this,"_checkId",0);d(this,"autoSetFps",!0);this.manager=e,this.log.id+="mix",this.create2dVideoContext(),this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log}),this.destination.on(Ve.RENDER,r=>{this.emit("render",r)}),this.mixNode=new Es(this.videoContext,this.log),this.mixNode.matchInputSize=!1}listenDeviceChange(){throw new Error("Method not implemented.")}enablePrintDetail(e=2e3){this._checkId=oe.run("interval",()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:e})}create2dVideoContext(){this.videoContext?this.videoContext.destroy():this.videoContext=new Qe({frameRate:15,logger:this.log,name:"mix-ctx"}),this.videoContext.create({alpha:!1})}setFps(e){this.autoSetFps=!1,this.videoContext.frameRate=e;for(let t of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])t.shouldUpdate=!1;setTimeout(()=>{var t;return(t=this.destination)==null?void 0:t.start(this.videoContext.frameRate)},500)}setFpsAuto(){var s;if(!this.autoSetFps)return;for(let n of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])n.shouldUpdate=!1;let e=null,t=0,r=!0;for(let[n,a]of this.inputLocalVideoTracks)if(a.profile.frameRate>t){if(this.endedIds.has(n)){let c=this.cameraNodeMap.get(n);c&&c.image.cancelVideoFrameCallback(c.videoCallbackId);continue}t=a.profile.frameRate,e=n}for(let[n,a]of this.inputLocalScreenTracks)if(a.profile.frameRate>t){if(this.endedIds.has(n)){let c=this.screenNodeMap.get(n);c&&c.image.cancelVideoFrameCallback(c.videoCallbackId);continue}t=a.profile.frameRate,e=n,r=!1}if(e!==null){let n=r?this.cameraNodeMap.get(e):this.screenNodeMap.get(e);n&&(n.shouldUpdate=!0,n.tryVideoFrameCallback()),this.log.info("set mix fps: ",t)}else(s=this.destination)==null||s.start(this.videoContext.frameRate),this.log.info("fallback to timer, fps: ",this.videoContext.frameRate)}setMixBackground(e){this.mixNode&&(this.mixNode.backgroundColor=e)}resizeMixCanvas(e,t){var r;(r=this.mixNode)==null||r.resize(e,t)}startMix(){return f(this,null,function*(){var e;if(!this.mixNode||!this.destination)throw new Error("can't mix without necessary conditions");this.mixNode.disconnect(),this.mixNode.connect(this.destination),Bt&&this.player.setCanvas(this.videoContext._canvas),this.setOutputMediaStreamTrack(this.destination.videoTrack),(e=this.manager)==null||e.changeInput(this)})}addCameraSource(e,t,r){if(this.inputLocalVideoTracks.has(e)||this.cameraNodeMap.has(e))throw new Error(`There is already a cameraSource with the same ID: ${e}`);let{mediaTrack:s}=t;if(!s)throw new Error("no mediaTrack, add cameraSource failed");t.recaptureMode=1,tt(this,ve).add("videoInputRemoved",a=>{a.deviceId===t.deviceId&&(this.endedIds.add(e),this.setFpsAuto())}),t.on("output-media-track-changed",()=>{this.endedIds.delete(e),this.updateCameraSource(e,r,t.mediaTrack)});let n;et===16&&s instanceof CanvasCaptureMediaStreamTrack?n=this.videoContext.createVideoImageSource(s.canvas,{name:"cameraCanvasSource",logger:this.log}):n=this.videoContext.createVideoTrackSource(s,"cameraNodeSource"),n.resize(t.settings.width,t.settings.height),n.shouldUpdate=!1,this._connectMix(n,r,"cover"),this.inputLocalVideoTracks.set(e,t),this.cameraNodeMap.set(e,n),this.setFpsAuto()}addScreenSource(e,t,r){if(this.inputLocalScreenTracks.has(e)||this.screenNodeMap.has(e))throw new Error(`There is already a screenSource with the same ID: ${e}`);let{mediaTrack:s}=t;if(!s)throw new Error("no mediaTrack, add cameraSource failed");let n=this.videoContext.createVideoTrackSource(s,"screenNodeSource");n.resize(t.settings.width,t.settings.height),n.shouldUpdate=!1,this._connectMix(n,r),this.inputLocalScreenTracks.set(e,t),this.screenNodeMap.set(e,n),this.setFpsAuto()}addTextSource(e){let{id:t,content:r="",font:s,color:n,layout:a}=e;if(this.textNodeMap.has(t))throw new Error(`There is already a textSource with the same ID: ${t}`);let c=this.videoContext.createTextSource({content:r,font:s,color:n});c.resize(a.width,a.height),this._connectMix(c,a),this.textNodeMap.set(t,c)}addImageSource(e,t,r){if(this.imageNodeMap.has(e))throw new Error(`There is already a imageSource with the same ID: ${e}`);let s=this.videoContext.createVideoImageSource(t,{autoResize:!1,logger:this.log});s.resize(t.width,t.height),this._connectMix(s,r),this.imageNodeMap.set(e,s)}addVideoSource(e,t,r){if(this.videoNodeMap.has(e))throw new Error(`There is already a videoSource with the same ID: ${e}`);let s=this.videoContext.createVideoImageSource(t,{autoResize:!1,logger:this.log});s.resize(t.videoWidth,t.videoHeight),s.shouldUpdate=!1,this._connectMix(s,r),this.videoNodeMap.set(e,s)}updateCameraSource(e,t,r=null,s){let n=this.cameraNodeMap.get(e);if(n){if(r){if(et===16&&r instanceof CanvasCaptureMediaStreamTrack)if(n instanceof Wt){let l=n.output;n.close(),n=this.videoContext.createVideoImageSource(r.canvas,{name:"cameraCanvasSource",logger:this.log}),n.connect(l),this.cameraNodeMap.set(e,n)}else n.image=r.canvas;else if(n instanceof Wt)n.replaceTrack(r);else{let l=n.output;n.close(),n=this.videoContext.createVideoTrackSource(r,"cameraNodeSource"),n.connect(l),this.cameraNodeMap.set(e,n)}let{width:a,height:c}=r.getSettings();a&&c&&n.resize(a,c)}s&&n.resize(s.width,s.height),(s||r)&&this.setFpsAuto(),this._changeMixLayout(n,t)}}updateScreenSource(e,t){let r=this.screenNodeMap.get(e);r&&this._changeMixLayout(r,t)}updateTextSource(e){let{id:t,content:r,font:s,color:n,layout:a}=e,c=this.textNodeMap.get(t);c&&(T(r)||(c.content=r),T(s)||(c.font=s),T(n)||(c.color=n),c.resize(a.width,a.height),this._changeMixLayout(c,a))}updateImageSource(e,t,r){let s=this.imageNodeMap.get(e);s&&(r&&(s.image=r,s.resize(r.width,r.height)),this._changeMixLayout(s,t))}updateVideoSource(e,t,r){let s=this.videoNodeMap.get(e);if(s){if(r){let n=s.image;n instanceof HTMLVideoElement&&this.stopVideoElement(n),s.image=r,s.resize(r.videoWidth,r.videoHeight)}this._changeMixLayout(s,t)}}_connectMix(e,t,r="contain"){if(!this.mixNode)return;let{mirror:s,rotation:n}=t;e.disconnect();let a=new qt(this.videoContext,this.log,s,n);a=e.connect(a),t.fillMode||(t.fillMode=r),a.connect(this.mixNode,t)}_changeMixLayout(e,t){if(!this.mixNode)return;let{mirror:r,rotation:s}=t,n=e.output||e;n instanceof qt&&(T(r)||(n.mirror=r),T(s)||(n.rotation=s),n.resize(e.width,e.height)),this.mixNode.changeInputLayout(n,t)}removeCameraSource(e){let t=this.inputLocalVideoTracks.get(e);if(!t)return;t.close(),this.inputLocalVideoTracks.delete(e);let r=this.cameraNodeMap.get(e);r&&(r.output instanceof qt&&r.output.close(),r.close(),this.cameraNodeMap.delete(e)),this.checkAfterRemove(!0)}removeScreenSource(e){let t=this.inputLocalScreenTracks.get(e);if(!t)return;t.close(),this.inputLocalScreenTracks.delete(e);let r=this.screenNodeMap.get(e);r&&(r.output instanceof qt&&r.output.close(),r.close(),this.screenNodeMap.delete(e)),this.checkAfterRemove(!0)}removeTextSource(e){let t=this.textNodeMap.get(e);t&&(t.output instanceof qt&&t.output.close(),t.close(),this.textNodeMap.delete(e)),this.checkAfterRemove()}removeImageSource(e){let t=this.imageNodeMap.get(e);t&&(t.output instanceof qt&&t.output.close(),t.close(),this.imageNodeMap.delete(e)),this.checkAfterRemove()}removeVideoSource(e){let t=this.videoNodeMap.get(e);t&&(t.output instanceof qt&&t.output.close(),t.image instanceof HTMLVideoElement&&this.stopVideoElement(t.image),t.close(),this.videoNodeMap.delete(e)),this.checkAfterRemove()}checkAfterRemove(e=!1){e&&this.setFpsAuto()}stopVideoElement(e){e.pause(),e.src="",e.srcObject=null,e.remove()}close(){var e;super.close(),oe.clearTask(this._checkId),(e=this.videoContext)==null||e.destroy(),delete this.mixNode,delete this.destination;for(let t of[...this.inputLocalVideoTracks.values(),...this.inputLocalScreenTracks.values()])t.close();this.inputLocalVideoTracks.clear(),this.inputLocalScreenTracks.clear(),this.cameraNodeMap.clear(),this.screenNodeMap.clear(),this.textNodeMap.clear(),this.imageNodeMap.clear(),xe(this);for(let t of this.videoNodeMap.values())t.image instanceof HTMLVideoElement&&this.stopVideoElement(t.image);this.videoNodeMap.clear(),this.log.info("localMixVideoTrack close, stop mix")}};var sd=un();if(typeof navigator!="undefined"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:sd,exposeOrigin:!0,permittedOrigins:["*"]})}catch(o){}var NS=function(o){return f(this,null,function*(){let i=null,e=OS(o);R.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let t=yield navigator.mediaDevices.getDisplayMedia(e);o.systemAudio&&t.getAudioTracks().length===0&&(es&&je<74||Ce||te)&&R.warn("Your browser not support capture system audio");let r=t.getVideoTracks()[0];if(r){if(o.frameRate)try{yield r.applyConstraints({frameRate:{min:o.frameRate,ideal:o.frameRate},width:o.width,height:o.height})}catch(s){R.warn(`screen applyConstraints failed: ${s}`)}o.captureElement&&(yield DS(r,o.captureElement))}if(o.audio){let s=MS(o);R.info(`getUserMedia with constraints: ${JSON.stringify(s)}`),i=yield navigator.mediaDevices.getUserMedia(s),t.addTrack(i.getAudioTracks()[0])}return t})};function DS(o,i){return f(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&me(o.cropTo))try{if(!(((e=o.getCaptureHandle())==null?void 0:e.handle)===sd))return;let r=yield CropTarget.fromElement(i);yield o.cropTo(r)}catch(t){R.warn(`cropTo target failed ${t}`)}})}function MS(o){let i={echoCancellation:o.echoCancellation,autoGainControl:o.autoGainControl,noiseSuppression:o.noiseSuppression,sampleRate:o.sampleRate,channelCount:o.channelCount};return T(o.microphoneId)||(i.deviceId=o.microphoneId),{audio:i,video:!1}}function OS(o){let i={preferCurrentTab:o.preferDisplaySurface==="current-tab"||!!o.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:Ce?{max:o.width}:{ideal:o.width,max:o.width},height:Ce?{max:o.height}:{ideal:o.height,max:o.height},frameRate:o.frameRate,displaySurface:o.preferDisplaySurface||"monitor"};if(i.video=e,o.systemAudio){let{echoCancellation:t=!0,noiseSuppression:r=!1,autoGainControl:s=!1}=o;i.audio={echoCancellation:t,noiseSuppression:r,autoGainControl:s,sampleRate:48e3}}return i}var Cf=NS;var Pt=class extends ze{constructor(e){super(e,2);d(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600});d(this,"objectFit","contain");d(this,"isScreen",!0);this._log.id=`s-${this._log.id}`}get isShareCurrentTab(){var e,t;try{return sd===((t=(e=this.mediaTrack)==null?void 0:e.getCaptureHandle())==null?void 0:t.handle)}catch(r){return}}capture(h){return f(this,arguments,function*({systemAudio:e=!1,autoGainControl:t,echoCancellation:r,noiseSuppression:s,audioTrack:n,videoTrack:a,captureElement:c,preferDisplaySurface:l}){try{let m;return a||n?(m=new MediaStream,a&&m.addTrack(a),n&&m.addTrack(n)):(m=yield Cf({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:t,echoCancellation:r,noiseSuppression:s,captureElement:c,preferDisplaySurface:l}),this.sourceTrack=m.getVideoTracks()[0]),yield this.setInputMediaStreamTrack(m.getVideoTracks()[0]),m}catch(m){throw this.log.error(`getDisplayMedia error observed ${m}`),m instanceof D?m:new D({code:I.INITIALIZE_FAILED,name:m.name,message:m.message})}})}switchDevice(e){return f(this,null,function*(){throw new Error("Method not implemented.")})}};M([Ct(function(e){this.setContentHint(e.contentHint||"detail")})],Pt.prototype,"capture",1);var To=class extends kt{constructor(i){super(i),this._log.id=`s-${this._log.id}`,this.isScreen=!0}addAudioProcessor(i,e,t){this.pipeline.silentNode.setNode(t),this.pipeline.mixNode.setNode(e),this.pipeline.aec.setNode(i),this.enableTrackAEC(!1)}removeAudioProcessor(i){this.pipeline.aec.node===i&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode(),this.enableTrackAEC(!0))}};var kS='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}});',Nh;function jn(o,i=48e3,e=1,t){return f(this,null,function*(){let r=Se("dump");Nh||(Nh=tr(r,URL.createObjectURL(new Blob([kS],{type:"application/javascript"})))),yield Nh;let s=r.sampleRate,n=new AudioWorkletNode(r,"dumper",{numberOfInputs:o.length,numberOfOutputs:0,processorOptions:{sourceSampleRate:s,targetSampleRate:i}});return n.channelCountMode="explicit",n.channelCount=e,t&&n.port.postMessage({port:t},[t]),o.forEach((a,c)=>a.connect(n,0,c)),new ReadableStream({start(a){n.port.onmessage=c=>{a.enqueue(c.data)}},cancel(){o.forEach(a=>a.disconnect(n)),n.port.close()}})})}var nd=class extends Oc{constructor(e){super();this.room=e;d(this,"_localAudioTrack");d(this,"_localScreenAudioTrack");d(this,"log");d(this,"denoiser");d(this,"voiceChanger");d(this,"mixChangedDebounce");d(this,"audioProcessor");d(this,"encodePipeline",[]);d(this,"decodePipeline",[]);d(this,"getPCMAbortCtrlMap",new Map);d(this,"audioFrameEventConfigMap",new Map);d(this,"audioReferenceMap",new Map);d(this,"isLocalAudioNeedAudioProcess",!1);d(this,"isScreenAudioNeedAudioProcess",!1);this.log=R.createLogger({parent:e==null?void 0:e.getLogger(),id:"am",userId:e==null?void 0:e.userId,sdkAppId:e==null?void 0:e.sdkAppId}),this.installEvent()}get localAudioTrack(){return this._localAudioTrack}get _localAudioPipline(){var e;return(e=this._localAudioTrack)==null?void 0:e.pipeline}get _localScreenAudioPipeline(){var e;return(e=this._localScreenAudioTrack)==null?void 0:e.pipeline}dump(e){var h,m;if(!this._localAudioTrack)return;let t=[],r=[];(h=this._localAudioPipline)!=null&&h.source.node&&(t.push(this._localAudioPipline.source.node),r.push("mic")),(m=this._localAudioPipline)!=null&&m.denoiser.node&&(t.push(this._localAudioPipline.denoiser.node),r.push("mic-processed")),this.mixWeight>1&&(t.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),r.push("mix")),this.log.info(`dump audio track ${r}, duration: ${e}`);let s=new AbortController,n=[],a=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),s.abort("timeout")},e*1e3),c=()=>{for(let u=0;u<r.length;u++){let _=URL.createObjectURL(new Blob(n[u])),g=document.createElement("a");g.href=_,g.download=`${r[u]}.pcm`,g.style.display="none",document.body.appendChild(g),g.click(),URL.revokeObjectURL(_),g.remove()}clearTimeout(a),s.abort("download")},l=jn(t).then(u=>u.pipeTo(new WritableStream({write(_){_.forEach((g,E)=>n[E]=n[E]?n[E].concat(g[0]):[g[0]])}}),s).catch(_=>c));return{then:l.then.bind(l),download:c}}getPCM(e,t){var k,se,w;if(typeof WritableStream=="undefined"){this.log.warn("getPCM failed: browser not support WritableStream");return}let{enable:r,sampleRate:s=48e3,channelCount:n=1,port:a}=(t===""?this.audioFrameEventConfigMap.get(""):this.audioFrameEventConfigMap.get(t)||this.audioFrameEventConfigMap.get("*"))||{};if(!r)return;this.log.info(`getPCM ${t||"local"}`);let c=Math.floor(s*.04),l=new Float32Array(c),h=new Float32Array(c),m,u,_=0,g=new AbortController,E=t===""?(k=this._localAudioTrack)==null?void 0:k.mediaTrack:(w=(se=this.room)==null?void 0:se.remotePublishedUserMap.get(t))==null?void 0:w.remoteAudioTrack.mediaTrack;if(!E){this.log.info(`getPCM failed: ${t||"local"} has no audio track`);return}let A=Se().createMediaStreamSource(new MediaStream([E]));return jn([A],s,n,a).then(Ze=>Ze.pipeTo(new WritableStream({write(N){N[0][0]&&(_+N[0][0].length>c?(l.set(N[0][0].subarray(0,c-_),_),m=N[0][0].subarray(c-_),N[0][1]&&(h.set(N[0][1].subarray(0,c-_),_),u=N[0][1].subarray(c-_)),_+=c-_):(m&&(l.set(m,_),_+=m.length,m=void 0),u&&(h.set(u,_),u=void 0),l.set(N[0][0],_),N[0][1]&&h.set(N[0][1],_),_+=N[0][0].length),_>=c&&(_=0,e({userId:t,sampleRate:s,channelCount:n,data:n===1?l:[l,h]}),l=new Float32Array(c),h=new Float32Array(c)))}}),g).catch(N=>this.log.warn(`stop getPCM reason:${N}`))),g}get hasScreenAudioTrack(){return!T(this._localScreenAudioTrack)}get hasAudioTrack(){return!T(this._localAudioTrack)}changeInput(e){var t,r;if(e instanceof To)return this._localScreenAudioTrack=e,this.isScreenAudioNeedAudioProcess&&((t=this.audioProcessor)!=null&&t.screenAudioWorkletNode)&&(e.addAudioProcessor(this.audioProcessor.screenAudioWorkletNode,this.audioProcessor.mixNode,this.audioProcessor.silentNode),this.audioReferenceMap.forEach((s,n)=>{e.mixAudioReference(s,n)})),e.pipeline.connect(),this.mixOnChange();if(e instanceof kt)return this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),this.isLocalAudioNeedAudioProcess&&((r=this.audioProcessor)!=null&&r.localAudioWorkletNode)&&(e.addAudioProcessor(this.audioProcessor.localAudioWorkletNode,this.audioProcessor.mixNode,this.audioProcessor.silentNode),this.audioReferenceMap.forEach((s,n)=>{e.mixAudioReference(s,n)})),e.pipeline.connect(),this.mixOnChange();if(e instanceof Ti)return e.setOutputMediaStreamTrack(e.mediaTrack)}mixAudioReference(e,t){var r;(r=this._localAudioTrack)==null||r.mixAudioReference(e,t)}unMixAudioReference(e){var t;(t=this._localAudioTrack)==null||t.unMixAudioReference(e)}setAudioReferenceVolume(e,t){var r;(r=this._localAudioTrack)==null||r.setAudioReferenceVolume(e,t)}mixOnChange(){return this.mixChangedDebounce||(this.mixChangedDebounce=Promise.resolve().then(()=>{var e,t;return delete this.mixChangedDebounce,Promise.all([(e=this._localAudioTrack)==null?void 0:e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),(t=this._localScreenAudioTrack)==null?void 0:t.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)])})),this.mixChangedDebounce}removeInput(e){e instanceof To?delete this._localScreenAudioTrack:e instanceof kt?delete this._localAudioTrack:e instanceof Ti}addDenoiser(e){var t;this.denoiser=e,(t=this._localAudioTrack)==null||t.addDenoiser(e)}addAudioProcessor(e,t,r,s){var n;this.audioProcessor={localAudioWorkletNode:r,mixNode:e,silentNode:t,screenAudioWorkletNode:s},this.isLocalAudioNeedAudioProcess&&this._localAudioTrack&&r&&(this._localAudioTrack.addAudioProcessor(r,e,t),this.audioReferenceMap.forEach((a,c)=>{var l;(l=this._localAudioTrack)==null||l.mixAudioReference(a,c)})),this.isScreenAudioNeedAudioProcess&&this._localScreenAudioTrack&&s&&((n=this._localScreenAudioTrack)==null||n.addAudioProcessor(s,e,t),this.audioReferenceMap.forEach((a,c)=>{var l;(l=this._localScreenAudioTrack)==null||l.mixAudioReference(a,c)}))}removeDenoiser(e){var t;return delete this.denoiser,(t=this._localAudioTrack)==null?void 0:t.removeDenoiser(e)}addVoiceChanger(e,t){var r;this.voiceChanger=[e,t],(r=this._localAudioTrack)==null||r.pipeline.voiceChanger.setNode(e,t)}removeVoiceChanger(){var e;delete this.voiceChanger,(e=this._localAudioTrack)==null||e.pipeline.voiceChanger.deleteNode()}removeAudioProcessor(e,t){var r,s;delete this.audioProcessor,(r=this._localAudioTrack)==null||r.removeAudioProcessor(e),(s=this._localScreenAudioTrack)==null||s.removeAudioProcessor(t)}destroy(){this.close(),this.audioReferenceMap.clear(),this.getPCMAbortCtrlMap.forEach(e=>e==null?void 0:e.abort("destroy")),this.getPCMAbortCtrlMap.clear(),this.audioFrameEventConfigMap.clear(),this.uninstallEvent()}addEncodeProcessor({processor:e,type:t}){var r;this.encodePipeline.includes(e)||(this.encodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}addDecodeProcessor({processor:e,type:t}){var r;this.decodePipeline.includes(e)||(this.decodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}handleLocalTrackStarted({room:e,userId:t}){var s;if(e!==this.room||this.getPCMAbortCtrlMap.get(t))return;let r=this.getPCM(n=>{var a;(a=this.room)==null||a.emit("audio-frame",n)},"");this.getPCMAbortCtrlMap.set(t,r),this.getPCMAbortCtrlMap.get(t)&&((s=this._localAudioTrack)==null||s.on("input-media-track-changed",()=>{let n=this.getPCMAbortCtrlMap.get(t);n&&(n.abort("inputMediaTrackChanged"),n=this.getPCM(a=>{var c;(c=this.room)==null||c.emit("audio-frame",a)},""),this.getPCMAbortCtrlMap.set(t,n))}))}handleLocalTrackStopped({room:e,userId:t}){if(e!==this.room)return;let r=this.getPCMAbortCtrlMap.get(t);r&&(r.abort("stopLocalAudio"),this.getPCMAbortCtrlMap.delete(t))}handleRemoteTrackStarted({room:e,userId:t}){if(e===this.room&&!this.getPCMAbortCtrlMap.get(t)){let r=this.room.audioManager.getPCM(s=>{var n;(n=this.room)==null||n.emit("audio-frame",s)},t);this.getPCMAbortCtrlMap.set(t,r)}}handleRemoteTrackStopped({room:e,userId:t}){if(e!==this.room)return;let r=this.getPCMAbortCtrlMap.get(t);r&&(r.abort("stopRemoteAudio"),this.getPCMAbortCtrlMap.delete(t))}installEvent(){S.on("113",this.handleLocalTrackStarted,this),S.on("114",this.handleLocalTrackStopped,this),S.on("115",this.handleRemoteTrackStarted,this),S.on("116",this.handleRemoteTrackStopped,this)}uninstallEvent(){S.off("113",this.handleLocalTrackStarted),S.off("114",this.handleLocalTrackStopped),S.off("115",this.handleRemoteTrackStarted),S.off("116",this.handleRemoteTrackStopped)}updateAudioReference({type:e,audioReference:t,refId:r,volume:s}){if(e==="add"){if(this.audioReferenceMap.get(r)||!t||(this.audioReferenceMap.set(r,t),!this.audioProcessor))return;this.mixAudioReference(t,r)}else if(e==="remove")this.audioReferenceMap.get(r)&&(this.audioReferenceMap.delete(r),this.unMixAudioReference(r));else if(e==="updateVolume"){if(!this.audioProcessor||T(s))return;this.setAudioReferenceVolume(r,s)}}};function Eo(o=30,i=2){return Y((e,t)=>function(...r){return new Promise((s,n)=>{let a=setTimeout(()=>{let c=new D({code:I.API_CALL_TIMEOUT,message:`checkPendingPromise ${t}() timeout ${o}s`});(this.log||this._log||R).warn(c),i===2?n(c):i===1&&s()},o*1e3);this._checkPendingPromiseSet||(this._checkPendingPromiseSet=new Set),this._checkPendingPromiseSet.add(a),e.apply(this,r).then(s,n).finally(()=>{clearTimeout(a),this._checkPendingPromiseSet&&a&&this._checkPendingPromiseSet.delete(a)})})})}function Rf(){return Y((o,i)=>function(...e){return this._checkPendingPromiseSet&&(this._checkPendingPromiseSet.forEach(t=>clearTimeout(t)),this._checkPendingPromiseSet.clear()),o.apply(this,e)})}var Oi=class Oi extends no{constructor(e,t,r){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:r,room:e});this.room=e;this.user=t;d(this,"tinyId");d(this,"isRemote",!0);d(this,"jitterBufferDelay",0);d(this,"availableState");d(this,"remotePublishState");d(this,"_triggerCheckDecodeSubject",ot(le(this,Oi.STATE_SUBSCRIBE)));d(this,"ignoreUpdatePlayingState");this.tinyId=t.tinyId,this.availableState=new j(`${t.userId}-${this.mediaType}-available`,"remote-track-available"),this.remotePublishState=new j(`${t.userId}-${this.mediaType}-remote-publish`,"remote-track-publish"),ue(Vn(le(this,j.STATECHANGED),le(this.remotePublishState,j.STATECHANGED)),$n(()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing)),Te(c=>{this.availableState.state!==(c?j.ON:j.OFF)&&(this.availableState.state=c?j.ON:j.OFF),!(this.isRemotePublished&&this.ignoreUpdatePlayingState)&&this.updatePlayingState(c)}));let s=ue(le(this.player,K.ERROR),Gt(c=>c.code===MediaError.MEDIA_ERR_DECODE)),n=ue(Bn(5e3),Gt(()=>this.ignoreDecodeError||!this.isSubscribed||!this.isPlayCalled||!this.stat.bytesReceived?!1:this.player.isPlaying||(this.kind===p.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)?(this.reportDecodeResult(!0),!1):!0)),a=ue($u(s,n),Pe(le(this,j.INIT)));ue(this._triggerCheckDecodeSubject,Gt(()=>!this.ignoreDecodeError),mo(a),Te(c=>{this.reportDecodeResult(!1,c)}))}setMute(e){this.isRemotePublished&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.isRemotePublished&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}checkDecodeResult(){this._triggerCheckDecodeSubject.next(!0)}waitHasMediaTrack(){return new Promise(e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)})}get ignoreDecodeError(){var t,r;return(((r=(t=this.room)==null?void 0:t.networkQuality)==null?void 0:r.downlinkNetworkQuality)||0)>3||this.player.isInAutoPlayFailedState}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===Oi.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===j.ON}get isNeedPlay(){return this.isAvailable&&this.isPlayCalled}subscribe(e){return e}unsubscribe(){this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}reportDecodeResult(e,t){var s,n;let r=this.kind===p.AUDIO;if(v[e?"addSuccessEvent":"addFailedEvent"]({key:r?504700:514702}),!r){let a=((s=this.room)==null?void 0:s.downlinkVideoCodec.toUpperCase())||"H264";v[e?"addSuccessEvent":"addFailedEvent"]({key:ss[`DECODE_${a}_RESULT`]}),e||this.log.warn(`${(n=this.room)==null?void 0:n.downlinkVideoCodec} decode failed`)}e||(v.addEnum({key:r?504701:514703,value:Zr()}),ne.uploadEvent({log:`stat-decode-failed-${this.kind}-${ni()||ai()}`,userId:this.room.userId}),this._log.warn(`decode failed: isPlaying: ${this.player.isPlaying} ${this.kind===p.AUDIO?`audioLevel: ${this.getAudioLevel()}`:`framesDecoded: ${this.stat.framesDecoded>0}`}`),this.emit("decode-failed",{error:t}))}updatePlayingState(e){if(this.player.isPlayCalled&&this.player.setTrack(this.playerMediaTrack),this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.isRemotePublished||!this.outMediaTrack)){this.log.info(`abort play, isSubscribed: ${this.isSubscribed} isAvailable: ${this.isRemotePublished} hasTrack: ${!!this.outMediaTrack} `);return}super.updatePlayingState(e)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.remotePublishState.state=this.isRemotePublished?j.ON:j.OFF,this.emit("remote-publish-changed",this.isRemotePublished)}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};d(Oi,"STATE_SUBSCRIBE","subscribe"),M([Eo(5,1)],Oi.prototype,"waitHasMediaTrack",1),M([be(j.INIT,Oi.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),S.emit(C.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),Rt(521716,!1)],Oi.prototype,"subscribe",1),M([be(Oi.STATE_SUBSCRIBE,j.INIT,{sync:!0,success(){this.log.info("unsubscribed"),S.emit(C.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],Oi.prototype,"unsubscribe",1);var Ss=Oi;var Ti=class extends Ss{constructor(e,t){super(e,t,1);d(this,"volume",0);d(this,"mediaType",1);d(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.audioManager}get dbVolume(){return so.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}onPlayerError(e){this.enableDecodeFrame&&(this._log.warn("use audio decoder"),this.room.enableInsertableStreams())}get enableDecodeFrame(){var e,t;return this.manager?this.manager.decodePipeline.some(r=>r)||((t=(e=this.player.element)==null?void 0:e.error)==null?void 0:t.code)===MediaError.MEDIA_ERR_DECODE&&Rc().AudioDecoder&&mi:!1}get enableDecryptFrame(){return this.manager&&!!this.manager.decodePipeline[0]}decodeFrame(e){if(!this.manager)return e;let t=e;for(let[r,s]of this.manager.decodePipeline.entries()){if(!s)continue;let n={frame:e,track:this};if(r===1&&this.isAvailable&&this.room.role==="audience"&&(n.onAudioFrameNTPTime=({ntp:a,frame:c,hasLeavingTag:l})=>{this.emit("audio-frame-with-ntp",{ntp:a,frame:c,hasLeavingTag:l})}),t=s(n),!t)return}return t}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get isRemotePublished(){return this.user.muteState.audioAvailable}};var ad=class extends Ve{constructor(e,t,r,s,n){super(e,{useDefaultProgram:!0,useFbo:!0,name:"alpha",create2d:!0,logger:t});this.setContainer=s;d(this,"initStat",{alphaStitchingType:1});d(this,"end",ot());d(this,"minSize",320);d(this,"maxSize",1280);d(this,"draggable",!1);d(this,"startDragX",0);d(this,"startDragY",0);d(this,"left",0);d(this,"top",0);d(this,"baseWidth",320);d(this,"baseRatio");d(this,"container");this.initStat=n,this.draggable=r,this.bindDragEvents()}bindDragEvents(){let e=this.context._canvas;if(e)if(this.draggable){let t=Pe(this.end);ue(le(e,"mousedown"),Gn(this.startDrag.bind(this)),Or(()=>ue(le(window,"mousemove"),Pe(le(window,"mouseup")))),t,Te(this.doDrag.bind(this))),ue(le(e,"dblclick"),t,Te(this.resetPosition.bind(this))),ue(le(e,"wheel"),t,Te(this.handleZoom.bind(this))),this.renderCanvas()}else{if(!this.container)return;this.container.style.removeProperty("left"),this.container.style.removeProperty("top"),this.end.next()}}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}startDrag(e){e.preventDefault(),e.button===0&&(this.startDragX=e.clientX-this.left,this.startDragY=e.clientY-this.top)}renderCanvas(){let{container:e}=this;e||this.setContainer(),!(!e||!this.baseRatio||!this.draggable)&&(e.style.setProperty("width",`${this.baseWidth}px`),e.style.setProperty("height",`${this.baseWidth/this.baseRatio}px`),e.style.setProperty("position","fixed"),e.style.setProperty("left",`${this.left}px`),e.style.setProperty("top",`${this.top}px`))}doDrag(e){e.preventDefault(),this.left=e.clientX-this.startDragX,this.top=e.clientY-this.startDragY,this.renderCanvas()}handleZoom(e){e.preventDefault();let t=.1,r=e.deltaY,s=this.context._canvas;s&&(this.baseWidth||(this.baseWidth=s.offsetWidth),r<0?this.baseWidth=Math.min(this.baseWidth*(1+t),this.maxSize):this.baseWidth=Math.max(this.baseWidth*(1-t),this.minSize),this.renderCanvas())}resetPosition(){this.left=0,this.top=0,this.renderCanvas()}onRatioReset(){this.renderCanvas()}draw2d(e,t,r,s,n){var _;let{ctx2d:a}=this,c=this.context._canvas;if(!a||!c)return!1;let l=super.draw2d(e,t,r,s,n),h=a.getImageData(0,0,s,n),{data:m}=h,u=!1;if(this.initStat.alphaStitchingType===1){let g=Math.floor(s/2);for(let E=0;E<n;E++)for(let A=0;A<g;A++){let k=(E*s+A)*4,se=A+g,w=(E*s+se)*4,Ze=m[w];m[w+3]=0;let N=Ze>=100;m[k+3]=N?255:0}u=super.draw2d(h,0,0,0,0,g,n),c.width=g}else if(this.initStat.alphaStitchingType===2){let g=Math.floor(n/2);for(let E=0;E<g;E++)for(let A=0;A<s;A++){let k=(E*s+A)*4,w=((E+g)*s+A)*4,Ze=m[w];m[w+3]=0;let N=Ze>=100;m[k+3]=N?255:0}u=super.draw2d(h,0,0,0,0,s,g),c.height=g}return(_=this.context.ctx)==null||_.clearRect(0,0,s,n),l&&u}close(){this.baseRatio=void 0,this.end.next(),this.end.complete()}};function LS(o){return[15,30,45,60].reduce((e,t)=>Math.abs(t-o)<Math.abs(e-o)?t:e)}var ki=class extends Ss{constructor(e,t,r=4){super(e,t,r);d(this,"mediaType",4);d(this,"source");d(this,"shouldRenderAlpha",!1);d(this,"alphaNode");d(this,"shouldBeDraggable",!0);d(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.videoManager,this.on("first-video-frame",s=>{this.room.emit("first-video-frame",s)})}isAlphaSei(e){if(this.userId!==e.userId||e.seiPayloadType!==50)return!1;let t=new Uint8Array(e.data);return t.length%3!==0||t[0]!==0||t[1]!==1?!1:t}play(e,t){return(he(t==null?void 0:t.canvasRender)?t.canvasRender:et===17)&&!this.source&&this.useCanvasPlayer(),super.play(e,t).then(()=>{this.player.calculateStat(),S.emit("156",{track:this,player:this.player})})}updateAlphaRenderInfo(e){let t=this.isAlphaSei(e);if(t)if(!this.alphaNode)this.shouldRenderAlpha=!0,this.player.shouldRenderAlpha=!0,this.useCanvasPlayer(t[2]);else{let r=t[2];if(this.alphaNode.baseRatio&&this.alphaNode.initStat.alphaStitchingType===r)return;this.alphaNode.initStat={alphaStitchingType:r};let s=this.player.getElement();if(s){let n=s.videoWidth/s.videoHeight;n&&(this.alphaNode.baseRatio=n*(r===1?.5:2),this.alphaNode.onRatioReset())}this.player.canvas&&(this.player.canvas.id=this.generateAlphaCanvasName(r))}}generateAlphaCanvasName(e){let t="alpha",r=fn[e];return`${t}_${r}_${this.userId}`}useCanvasPlayer(e){if(this.log.info(`useCanvasPlayer(), has element:${!!this.player.element}`),!this.player.element)return;let t=new Qe({frameRate:15,logger:this.log,name:this.shouldRenderAlpha&&e?this.generateAlphaCanvasName(e):this.userId});t.create({alpha:this.shouldRenderAlpha,willReadFrequently:this.shouldRenderAlpha});let r=new fo(t,{name:"remotePlayer",logger:this.log});if(this.source=t.createVideoPlayerSource(this.player),this.player.setCanvas(t._canvas),this.shouldRenderAlpha&&e){let s=()=>{!this.player.container||!this.alphaNode||(this.alphaNode.container=this.player.container,this.alphaNode.renderCanvas())},n=new ad(t,this.log,this.shouldBeDraggable,s,{alphaStitchingType:e});this.source.connect(n),n.connect(r),this.alphaNode=n}else this.source.connect(r);Ki()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,t),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let t=this.decodeFPS,r=LS(t);if(!Q(t)||t<=0){this.log.debug(`updateCanvasPlayerFPS() ignore decoder: ${t} `);return}if(r===e.frameRate){this.log.debug(`updateCanvasPlayerFPS() ignore ClosestFPS ${r} == ${e.frameRate}`);return}this.log.info(`updateCanvasPlayerFPS() decoder: ${t}, closest: ${r}, current: ${e.frameRate}`),e.frameRate=r}get decodeFPS(){var n;let{msg_video_status:e}=((n=this.room.heartbeatReport)==null?void 0:n.msg_down_stream_info.find(a=>a.msg_user_info.str_identifier===this.userId))||{},t=this.mediaType===2?7:this.isSmall?3:2;if(!e||e.length===0)return 0;let r=e.find(a=>a.uint32_video_stream_type===t);return(r==null?void 0:r.uint32_video_dec_fps)||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),S.emit("157",{track:this,player:this.player}),this.alphaNode&&this.alphaNode.close(),super.stop()}decodeFrame(e){if(!this.manager)return e;for(let t of this.manager.decodePipeline)if(t&&(e=t({frame:e,track:this}),!e))return;return e}get isBig(){return this.mediaType===4}get isSmall(){return this.mediaType===8}changeType(e){this.room.changeType(e,this.user)}get isRemotePublished(){return this.user.muteState.videoAvailable}setMirror(e){e==="publish"||e==="both"||super.setMirror(e)}setDraggable(e){this.shouldBeDraggable=e,this.alphaNode&&(this.alphaNode.draggable=e,this.alphaNode.bindDragEvents())}onDecodeDowngradeStateChanged(e){this.emit("decode-downgrade-state-changed",e)}},Is=class extends ki{constructor(e,t){super(e,t,2);d(this,"mediaType",2);d(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}};var As=new Map;S.on(C.JOIN_SUCCESS,({room:o})=>{Ne(o.userId,{eventId:32788})});S.on(C.LEAVE_START,({room:o})=>{Ne(o.userId,{eventId:32789})});S.on(C.LOCAL_TRACK_PUBLISHED,({track:o})=>{if(o.room){let i=32769;o.mediaType===4?i=32768:o.mediaType===2&&(i=32805),Ne(o.room.userId,{eventId:i})}});S.on(C.LOCAL_TRACK_UNPUBLISHED,({track:o})=>{if(o.room){let i=32771;o.mediaType===4?i=32770:o.mediaType===2&&(i=32806),Ne(o.room.userId,{eventId:i})}});S.on(C.TRACK_MUTED,({track:o})=>{o.room&&(o.kind===p.AUDIO?Ne(o.room.userId,{eventId:o.isRemote?32785:32772,remoteUserId:o.isRemote?o.userId:void 0}):Ne(o.room.userId,{eventId:o.isRemote?32784:32773,remoteUserId:o.isRemote?o.userId:void 0}))});S.on(C.TRACK_UNMUTED,({track:o})=>{o.room&&(o.kind===p.AUDIO?Ne(o.room.userId,{eventId:o.isRemote?32787:32774,remoteUserId:o.isRemote?o.userId:void 0}):Ne(o.room.userId,{eventId:o.isRemote?32786:32775,remoteUserId:o.isRemote?o.userId:void 0}))});S.on(C.REMOTE_TRACK_SUBSCRIBED,({track:o})=>{o.room&&(o.mediaType===1&&Ne(o.room.userId,{eventId:32777,remoteUserId:o.userId}),o.mediaType===4&&Ne(o.room.userId,{eventId:32776,remoteUserId:o.userId}),o.mediaType===8&&Ne(o.room.userId,{eventId:32803,remoteUserId:o.userId}))});S.on(C.REMOTE_TRACK_UNSUBSCRIBED,({track:o})=>{o.room&&(o.mediaType===1&&Ne(o.room.userId,{eventId:32779,remoteUserId:o.userId}),o.mediaType===4&&Ne(o.room.userId,{eventId:32778,remoteUserId:o.userId}),o.mediaType===8&&Ne(o.room.userId,{eventId:32804,remoteUserId:o.userId}))});S.on(C.SWITCH_DEVICE_SUCCESS,({track:o})=>{o.room&&Ne(o.room.userId,{eventId:o.kind===p.VIDEO?32780:32781})});S.on(C.LOCAL_TRACK_REPLACED,({track:o})=>{o.room&&Ne(o.room.userId,{eventId:o.kind===p.VIDEO?32782:32783})});S.on(C.SIGNAL_CONNECTION_STATE_CHANGED,({room:o,prevState:i,state:e})=>{let t;switch(e){case"CONNECTED":i==="RECONNECTING"?t=32795:t=32791;break;case"DISCONNECTED":i==="RECONNECTING"?t=32796:t=32790;break;case"RECONNECTING":t=32794;break}t&&Ne(o.userId,{eventId:t})});S.on(C.PEER_CONNECTION_STATE_CHANGED,({room:o,prevState:i,state:e,remoteUserId:t})=>{let r=!!t,s;switch(e){case"CONNECTED":i==="RECONNECTING"?s=r?32801:32798:s=r?32793:32792;break;case"DISCONNECTED":i==="RECONNECTING"&&(s=r?32802:32799);break;case"RECONNECTING":s=r?32800:32797;break}s&&Ne(o.userId,{eventId:s,remoteUserId:t})});S.on(C.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({implementation:o,userId:i,remoteUserId:e,codec:t,isHWCodec:r,prevImplementation:s,streamType:n})=>{let a=r?1:0;s||(a=r?3:2);let c={H264:0,H265:1,VP8:2}[t.toUpperCase()],l={eventId:4004,param1:a,param2:c,streamType:n||2};e&&(l.remoteUserId=e,l.eventId=4005),Ne(i,l),v.addEnum({key:e?514701:513701,value:a}),v.addEnum({key:e?514700:513700,value:c})});S.on(C.LOCAL_TRACK_RECAPTURE,({track:o,error:i})=>{if(o.userId){let e={eventId:2003,param1:0};o.kind===p.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType=o.streamType==="auxiliary"?7:2,i&&(e.param1=8)),Ne(o.userId,e)}});function Ne(o,i){let e=L(O({},i),{timestamp:Fi()});As.has(o)?As.get(o).push(e):As.set(o,[e])}function yf(o){if(As.has(o)){let i=As.get(o).map(e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,uint32_param1:e.param1,uint32_param2:e.param2,uint32_video_stream_type:e.streamType}));return As.delete(o),i}return[]}function bf(...o){return Y((i,e)=>function(...t){return xS.call(this,o,t,e,this._name),i.apply(this,t)})}function xS(o,i,e,t){try{if(Ae(o))for(let r=0;r<o.length;r++)cd.call(this,{rule:o[r],value:i[r],key:o[r].name,fnName:e,className:t});else cd.call(this,{rule:o,value:i[0],key:o.name,fnName:e,className:t})}catch(r){throw R.error(r),r}}function cd({rule:o,value:i,key:e,fnName:t,className:r}){if(T(i)){if(o.required)throw new D({code:I.INVALID_PARAMETER,message:$({key:B.INVALID_PARAMETER_REQUIRED,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(T(o.defaultValue))return;i=o.defaultValue}if(Array.isArray(o.type)){let a=!1;for(let c=0;c<o.type.length;c++)o.type[c]===null&&i===null&&(a=!0),me(o.type[c])&&i instanceof o.type[c]&&(a=!0),re(o.type[c])&&Oe(i)===o.type[c].toLowerCase()&&(a=!0);if(!a)throw new D({code:I.INVALID_PARAMETER,message:$({key:B.INVALID_PARAMETER_TYPE,data:{key:e,rule:{type:o.type.map(c=>jr(c)?Vo(c):re(c)?c:Oe(c))},fnName:t,value:i},link:{className:r,fnName:t}})})}else if(!T(o.type)&&Oe(i)!==o.type)throw new D({code:I.INVALID_PARAMETER,message:$({key:B.INVALID_PARAMETER_TYPE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(o.allowEmpty===!1){let a=Q(i)&&(i===0||Number.isNaN(i)),c=re(i)&&i.trim()==="";if(a||c)throw new D({code:I.INVALID_PARAMETER,message:$({key:B.INVALID_PARAMETER_EMPTY,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})})}if(o.notLessThanZero&&Q(i)&&i<0)throw new D({code:I.INVALID_PARAMETER,message:$({key:B.CANNOT_LESS_THAN_ZERO,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(!T(o.min)&&Q(i)&&i<o.min)throw new D({code:I.INVALID_PARAMETER,message:$({key:B.INVALID_PARAMETER_MIN,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(!T(o.max)&&Q(i)&&i>o.max)throw new D({code:I.INVALID_PARAMETER,message:$({key:B.INVALID_PARAMETER_MAX,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(re(o.instanceOf)){if(!i||i._name!==o.instanceOf)throw new D({code:I.INVALID_PARAMETER,message:$({key:B.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})})}else if(me(o.instanceOf)&&!(i instanceof o.instanceOf))throw new D({code:I.INVALID_PARAMETER,message:$({key:B.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(o.values&&!o.values.includes(i))throw new D({code:I.INVALID_PARAMETER,message:$({key:B.INVALID_PARAMETER_RANGE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});let{properties:s}=o;dt(s)&&yt(i)&&Object.keys(s).forEach(a=>{cd.call(this,{rule:s[a],value:i&&i[a],key:`${e}.${a}`,fnName:t,className:r})});let{arrayItem:n}=o;dt(n)&&Ae(i)&&i.forEach((a,c)=>{cd.call(this,{rule:n,value:a,key:`${e}[${c}]`,fnName:t,className:r})}),me(o.validate)&&o.validate.call(this,i,e,t,r,this)}var vf=Je(at(),1);var dd=class extends vf.EventEmitter{constructor(e,t,r="userId"){super();this.mySelfId=e;this._log=t;this.key=r;d(this,"userMap",new Map);d(this,"remotePublishedUserMap",new Map)}get hasRobotUser(){return!![...this.remotePublishedUserMap.values()].find(e=>e.isRobot)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:r,tinyId:s,role:n}=e;if(this.userMap.has(t))return;let a={userId:r,tinyId:s,role:n===20?"anchor":"audience"};this.userMap.set(t,a),this.emit("1",a)}deleteUser(e,t){let r=this.userMap.get(e);if(!r)return;let s=`peer leave [${e}]`;T(t)||(s+=`:${dl[t]}`),this._log.info(s);let n=this.remotePublishedUserMap.get(e);if(n){let a=n.muteState;n.flag=0,this.emit("5",n.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:a,muteState:n.muteState,flag:0})}this.userMap.delete(e),this.emit("2",r.userId)}setUserList(e){this.userMap.forEach(t=>{e.findIndex(r=>r[this.key]===t[this.key])<0&&this.deleteUser(t[this.key],0)}),e.forEach(t=>{!this.userMap.has(t[this.key])&&t[this.key]!==this.mySelfId&&this.addUser(t)})}addRemotePublishedUser(e){this.remotePublishedUserMap.has(e[this.key])||this.remotePublishedUserMap.set(e[this.key],e)}deleteRemotePublishedUser(e){this.remotePublishedUserMap.has(e)&&this.remotePublishedUserMap.delete(e)}setRemotePublishedUserList(e){this.remotePublishedUserMap.forEach(t=>{let r=t[this.key];if(e.findIndex(s=>s[this.key]===t[this.key])<0){this._log.info(`remote [${r}] unpublish`);let s=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(r),this.emit("6",{prevMuteState:s,muteState:t.muteState,flag:0})}}),e.forEach(t=>{var h;let r=t[this.key];if(r===this.mySelfId){this.emit("7",t);return}let{flag:s,userId:n,tinyId:a}=t,c=ei(s,n),l=(h=this.remotePublishedUserMap.get(r))==null?void 0:h.muteState;if(l){let m=this.remotePublishedUserMap.get(r);m&&m.flag!==s&&(m.flag=s,this._log.info(`remote publish updated: ${JSON.stringify(m.muteState)}`),this.emit("6",{prevMuteState:l,muteState:c,flag:s}))}else this._log.info(`remote publish. state: ${JSON.stringify(c)}`),this.addUser({userId:n,tinyId:a,role:20}),this.emit("3",t),this.emit("6",{prevMuteState:ei(0,n),muteState:c,flag:s})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function Dh({timesInSecond:o,maxSizeInSecond:i,getSize:e}){return Y((t,r)=>{let s=new WeakMap;return S.on(C.ROOM_DESTROY,({room:n})=>s.delete(n)),function(...n){let a=s.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},s.set(this,a)),a.timestamp===0?a.timestamp=Date.now():Date.now()-a.timestamp>1e3&&(a.timestamp=Date.now(),a.callCountInSecond=0,a.totalSizeInSecond=0),e&&(a.totalSizeInSecond+=e(...n)),a.timestamp!==0&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=o||a.totalSizeInSecond>i))throw new D({code:I.INVALID_OPERATION,message:$({key:B.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=o,isSize:a.totalSizeInSecond>i,name:r,timesInSecond:o,maxSizeInSecond:i}})});a.callCountInSecond++,t.call(this,...n)}})}var US="2025-12-19 18:56:25",Nf=!0,Df=function(){var o;if(Nf){Nf=!1,R.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${ft}/en/index.html`),console.info(`* Changelog: ${ft}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),R.info("TRTC Web SDK Version:",$e),si||R.debug("Build Time:",US);let i=`UA: ${navigator.userAgent}
53
+ CPU core: ${navigator.hardwareConcurrency}, GPU: ${ln()}`,e=navigator.deviceMemory;e&&(i+=`, minRAM: ${e}GB`),R.info(i),R.info(`URL: ${location.href}${((o=self.frameElement)==null?void 0:o.tagName)==="IFRAME"?" in iframe":""}`),Yr().then(t=>{t&&R.info(ii)})}};var So={SCENE_LIVE:"live",SCENE_RTC:"rtc",ROLE_ANCHOR:"anchor",ROLE_AUDIENCE:"audience",STREAM_TYPE_MAIN:"main",STREAM_TYPE_SUB:"sub",AUDIO_PROFILE_STANDARD:"standard",AUDIO_PROFILE_STANDARD_STEREO:"standard-stereo",AUDIO_PROFILE_HIGH:"high",AUDIO_PROFILE_HIGH_STEREO:"high-stereo",QOS_PREFERENCE_SMOOTH:"smooth",QOS_PREFERENCE_CLEAR:"clear",SPEAKER:"Speakerphone",HEADSET:"Headset earpiece"};var x={INVALID_PARAMETER:5e3,INVALID_OPERATION:5100,ENV_NOT_SUPPORTED:5200,DEVICE_ERROR:5300,SERVER_ERROR:5400,OPERATION_FAILED:5500,OPERATION_ABORT:5998,UNKNOWN_ERROR:5999},wt=(b=>(b[b.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",b[b.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",b[b.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",b[b.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",b[b.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",b[b.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",b[b.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",b[b.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",b[b.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",b[b.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",b[b.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",b[b.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",b[b.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",b[b.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",b[b.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",b[b.INVALID_ROOM_ID_REQUIRED=5015]="INVALID_ROOM_ID_REQUIRED",b[b.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",b[b.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",b[b.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",b[b.INVALID_ROOM_ID_TYPE_MISMATCH=5019]="INVALID_ROOM_ID_TYPE_MISMATCH",b[b.INVALID_ROOM_ID_DUPLICATE=5020]="INVALID_ROOM_ID_DUPLICATE",b[b.INVALID_OPERATION=5100]="INVALID_OPERATION",b[b.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",b[b.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",b[b.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",b[b.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",b[b.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",b[b.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",b[b.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",b[b.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",b[b.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",b[b.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",b[b.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",b[b.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",b[b.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",b[b.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",b[b.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",b[b.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",b[b.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",b[b.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",b[b.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",b[b.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",b[b.DEVICE_ERROR=5300]="DEVICE_ERROR",b[b.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",b[b.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",b[b.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",b[b.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",b[b.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",b[b.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",b[b.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",b[b.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",b[b.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",b[b.NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX=5310]="NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX",b[b.SERVER_ERROR=5400]="SERVER_ERROR",b[b.NEED_TO_BUY=5401]="NEED_TO_BUY",b[b.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",b[b.OPERATION_FAILED=5500]="OPERATION_FAILED",b[b.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",b[b.REJOIN_FAILED=5502]="REJOIN_FAILED",b[b.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",b[b.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",b[b.VIDEO_ENCODE_FAILED=5505]="VIDEO_ENCODE_FAILED",b[b.AUDIO_ENCODE_FAILED=5506]="AUDIO_ENCODE_FAILED",b[b.VIDEO_DECODE_FAILED=5507]="VIDEO_DECODE_FAILED",b[b.AUDIO_DECODE_FAILED=5508]="AUDIO_DECODE_FAILED",b[b.OPERATION_ABORT=5998]="OPERATION_ABORT",b[b.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",b))(wt||{});function Of({code:o,params:i,enableDocLink:e=!1}){let t="",r,s=wt[o];try{r=Mf[s]}catch(n){r=Mf.UNKNOWN_ERROR}return me(r)?t=r(i):re(r)&&(t=r),i.fnName&&!t.includes(i.fnName)&&(t[t.length-1]!=="."&&(t+="."),t+=` thrown from ${i.fnName}()`),e&&(t+=" doc:"),t}var Mf=L(O({},Xe),{INVALID_PARAMETER({fnName:o}){return`the parameters of the '${o}' you called does not meet the requirements, please check the API documentation.`},INVALID_PARAMETER_REQUIRED({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' is a required param when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_TYPE({key:o,rule:i,fnName:e,value:t}){let r=`${o||i.name}`,s="";return Array.isArray(i.type)?s=i.type.join("|"):s=i.type,`'${r}' must be type of ${s} when calling ${e}(), received type: ${Oe(t)}.`},INVALID_PARAMETER_EMPTY({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' cannot be '${t}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:o,rule:i,fnName:e,value:t}){let r=`${o||i.name}`,s=`${i.instanceOf.name||i.instanceOf}`;return`'${r}' must be instanceof ${s} when calling ${e}(), received type: ${Oe(t)}.`},INVALID_PARAMETER_RANGE({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' must be one of ${i.values.join("|")} when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_LESS_THAN_ZERO({key:o,rule:i,fnName:e}){return`'${o||i.name}' cannot be less than 0 when calling ${e}().`},INVALID_PARAMETER_MIN({key:o,rule:i,value:e}){return`the min value of ${o||i.name} is ${i.min}, received: ${e}.`},INVALID_PARAMETER_MAX({key:o,rule:i,value:e}){return`the max value of ${o||i.name} is ${i.max}, received: ${e}.`},INVALID_ELEMENT_ID({key:o,fnName:i}){return`'${o}' is not found in the document object when calling ${i}().`},INVALID_ELEMENT_ID_TYPE({key:o,fnName:i,type:e}){return`the element corresponding to '${o}' must be instanceof HTMLElement when calling ${i}(), received: ${e}.`},INVALID_STREAM_ID({key:o}){return`'${o}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},INVALID_ROOM_ID_STRING({key:o}){return`'${o}' must be a valid string.`},INVALID_ROOM_ID_INTEGER({key:o}){return`'${o}' must be an integer between [1, 4294967294].`},INVALID_ROOM_ID_INTEGER_STRING({key:o}){return`'${o}' must be an integer but go a string, use 'parseInt' to convert it or use 'strRoomId' instead.`},INVALID_ROOM_ID_REQUIRED(){return"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required."},INVALID_ROOM_ID_TYPE_MISMATCH({key:o}){return`The type of target roomId must match the current roomId. Current room is using '${o}', but received '${o==="strRoomId"?"roomId":"strRoomId"}'.`},INVALID_ROOM_ID_DUPLICATE({key:o}){return`the target '${o}' must not be the same as the current '${o}'.`},INVALID_STREAM_TYPE:({fnName:o})=>`'streamType' is required when 'userId' is not '*', calling ${o}()`,INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION({fnName:o}){return`the API '${o}' you called does not meet the requirements, please check the API documentation.`},INVALID_OPERATION_NOT_JOINED({fnName:o}){return`cannot ${o} because you are not enter room yet.`},INVALID_OPERATION_REMOTE_USER_NOT_EXIST({fnName:o,value:i}){return`cannot ${o} because remote user(userId: ${i.userId}) does not publishing stream.`},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST({fnName:o,value:i}){return`cannot ${o} because remote user(userId: ${i.userId}) does not publishing ${i.streamType} video.`},INVALID_OPERATION_REPEAT_CALL({fnName:o}){return`you are already ${o}(), cannot repeated call '${o}'.`},INVALID_OPERATION_NEED_VIDEO({fnName:o}){return`cannot call '${o}' because the camera is not turned on.`},INVALID_OPERATION_NEED_AUDIO({fnName:o}){return`cannot call '${o}' because the microphone or screen share is not turned on.`},INVALID_BUFFER_EMPTY:({key:o})=>`the buffer size of paramerter '${o}' cannot be empty`,INVALID_BUFFER_OVERSIZE:()=>"buffer size is over 1000 Bytes",INVALID_ROLE_AUDIENCE:()=>"role: 'audience' cannot call this api.",INVALID_NOT_ENABLE_SEI:()=>"you need to enable SEI in TRTC.create({ enableSEI: true })",INVALID_NEED_CALL_PUBLISHED:({fnName:o})=>`you need to call ${o}() after publish stream.`,ENV_NOT_SUPPORTED({fnName:o}){return`the current browser does not support the capability of the function '${o}' you are calling, please check the API documentation.`},NOT_SUPPORTED_WEBRTC:"the current browser does not support WebRTC capability, please check the SDK documentation.",NOT_SUPPORTED_H264_ENCODE:"this browser does not support H264 encode.",NOT_SUPPORTED_H264_DECODE:"this browser does not support H264 decode.",NOT_SUPPORTED_SCREEN_SHARE:"this browser does not support screen share, please check the browser version.",NOT_SUPPORTED_SMALL_VIDEO:"this browser does not support small video, please check the browser version.",NOT_SUPPORTED_SEI:"this browser does not support SEI, please check the browser version.",NOT_SUPPORTED_WEBGL:"this browser does not support WebGL, please check the browser version.",NOT_SUPPORTED_CHROME_VERSION({fnName:o}){return`cannot call ${o} because the browser version is too low, please upgrade to the latest version`},DEVICE_ERROR({fnName:o,error:i}){return`'${o}' got device exception${i?`, error: ${i.toString()}.`:"."}`},DEVICE_NOT_FOUND_ERROR({fnName:o,deviceType:i=Io(o),error:e}){return`NotFoundError, no ${i} detected, please check your device and the configuration on '${o}'${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_ALLOWED_ERROR({fnName:o,deviceType:i=Io(o),error:e}){return`NotAllowedError, you have disabled ${i} access, please allow the current application to use the ${i}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_READABLE_ERROR({fnName:o,deviceType:i=Io(o),error:e}){return`NotReadableError, the ${i} maybe in use by another APP, please check if the device is pre-occupied by another APP.`},DEVICE_OVERCONSTRAINED_ERROR({fnName:o,deviceType:i=Io(o),error:e}){return`OverconstrainedError, the device ID is incorrect, please check whether the device ID passed in is correct${e?`, error: ${e.toString()}.`:"."}`},DEVICE_INVALID_STATE_ERROR({fnName:o,deviceType:i=Io(o),error:e}){return`InvalidStateError, after the user clicks and interacts with the page, turn on the ${i}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_SECURITY_ERROR({fnName:o,deviceType:i=Io(o),error:e}){return`SecurityError, check whether the system security policy restricts the use of the ${i}, and it is recommended to turn on the ${i} after the user interacts with the page${e?`, error: ${e.toString()}.`:"."}`},DEVICE_ABORT_ERROR({fnName:o,deviceType:i=Io(o),error:e}){return`AbortError, an unknown exception in the system makes the device unusable, recommended to change the device or browser and re-check whether the device is normal${e?` error: ${e.toString()}.`:"."}`},CAMERA_RECOVER_FAILED({error:o}){return`camera recover capture failed ${(o==null?void 0:o.name)||""}: ${(o==null?void 0:o.originMessage)||(o==null?void 0:o.message)}`},MICROPHONE_RECOVER_FAILED({error:o}){return`microphone recover capture failed ${(o==null?void 0:o.name)||""}: ${(o==null?void 0:o.originMessage)||(o==null?void 0:o.message)}`},OPERATION_FAILED({fnName:o,error:i}){return`'${o}' failed, reason: ${i==null?void 0:i.toString()}`},FIREWALL_RESTRICTION(){return"media connection failure due to firewall restrictions, please try to change your network."},EVENT_HANDLER_ERROR({eventName:o}){return`an error was caught on trtc.on('${o}', handler), please check your code on 'handler'.`},VIDEO_CONTEXT_ERROR({reason:o,error:i}){return`video context error ${o} ${(i==null?void 0:i.name)||""} ${(i==null?void 0:i.message)||""}`},SERVER_ERROR({fnName:o,error:i}){return`'${o}' got server error: ${i==null?void 0:i.toString()}, please check the SDK documentation.`},NEED_TO_BUY({value:o,url:i}){return`You need to buy packages for ${o}. Refer to: ${i}`},ACCOUNT_NO_MONEY:({fnParams:o})=>`your TRTC account run out of credit, please recharge.${o.sdkAppId?` SDKAppId: ${o.sdkAppId}`:""}`,OPERATION_ABORT({fnName:o}){return`'${o}' abort`},UNKNOWN_ERROR({fnName:o,error:i}){return`'${o}' throw unknown exception${i?`, error: ${i.toString()}.`:"."}`}});function Io(o){if(!o)return"camera";let i=o.toLowerCase();return i.includes("screen")?"screen share":i.includes("audio")?"microphone":"camera"}var Mh=class o extends Error{constructor({code:e,extraCode:t,message:r="",messageParams:s,fnName:n="",originError:a,data:c}){var h;let l;r?l=r:l=Of({code:e===x.SERVER_ERROR?e:t||e,params:O({fnName:n,error:a},s)});super(l);d(this,"name","RtcError");d(this,"code");d(this,"extraCode");d(this,"functionName");d(this,"message");d(this,"data");d(this,"handler");d(this,"originError");this.name=wt[e],this.code=e,this.extraCode=t,this.functionName=n,this.originError=a,this.message=l,this.data=c,this.extraCode===5302&&((h=this.originError)!=null&&h.message.includes("system"))&&(this.handler=()=>{let m={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},u={startLocalVideo:"webcam",startLocalAudio:"microphone"},_=document.createElement("a");Qr?_.href=`ms-settings:privacy-${u[this.functionName]}`:oi&&(_.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${m[this.functionName]}`),_.href.length>0&&_.click()})}static convertFrom(e,t,r){let s=e;if(e instanceof D){let{stack:n}=e,a={code:x.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case I.INVALID_PARAMETER:a.code=x.INVALID_PARAMETER,a.message=e.message;break;case I.INVALID_OPERATION:a.code=x.INVALID_OPERATION;break;case I.NOT_SUPPORTED:case I.NOT_SUPPORTED_H264:a.code=x.ENV_NOT_SUPPORTED,e.getCode()===I.NOT_SUPPORTED_H264&&(a.extraCode=e.message.includes(Xe.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case I.JOIN_ROOM_FAILED:a.messageParams={fnParams:r};case I.SERVER_TIMEOUT:case I.SWITCH_ROLE_FAILED:case I.SWITCH_ROOM_FAILED:a.code=x.SERVER_ERROR,a.extraCode=e.getExtraCode();break;case I.API_CALL_ABORTED:a.code=x.OPERATION_ABORT;break;case I.DEVICE_NOT_FOUND:case I.DEVICE_AUTO_RECOVER_FAILED:case I.INITIALIZE_FAILED:a.code=5300,e.name&&(a.extraCode=VS(e.name));break;case I.VIDEO_ENCODE_FAILED:a.extraCode=5505;case I.AUDIO_ENCODE_FAILED:a.extraCode=5506,a.code=x.OPERATION_FAILED;break;case I.UNKNOWN:break;default:a.code=x.OPERATION_FAILED}s=new o(a),n&&(s.stack+=n.substr(n.indexOf(`
54
+ `)))}else{if(e instanceof o)return e;s=new o({code:x.UNKNOWN_ERROR,fnName:t,originError:e})}return s}};function VS(o){let i;switch(o){case"NotFoundError":i=5301;break;case"NotAllowedError":i=5302;break;case"NotReadableError":i=5303;break;case"OverconstrainedError":i=5304;break;case"InvalidStateError":i=5305;break;case"SecurityError":i=5306;break;case"AbortError":i=5307;break;default:i=5300}return i}var F=Mh;function Pi(o){return o==="sub"?"auxiliary":o==="auxiliary"?"sub":"main"}function Xn(o){return o===So.QOS_PREFERENCE_CLEAR?"detail":o===So.QOS_PREFERENCE_SMOOTH?"motion":""}function Cs(o,i){let e=i?tl:pr;return vl(o)?O(O({},e),o):Qt[o]?Qt[o]:e}var kf={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}}},Pf={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}}},Rs={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(o,i,e){if(re(o)&&!document.getElementById(o))throw new F({code:x.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:i}})}},wf={name:"userId",required:!0,type:"string"},Lf={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{type:["string","object"],properties:{bitrate:{type:"number"},channelCount:{type:"number"}}},echoCancellation:{values:[!0,!1,"remote-only","all"]},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function ys(o,i){if(!o)throw new F({code:x.INVALID_OPERATION,extraCode:5101,fnName:i})}function xf(o,i,e){if(!o)throw new F({code:x.INVALID_OPERATION,extraCode:5102,fnName:i,messageParams:{value:e}})}function Uf(o,i,e){if(!(/^[1-9]\d*$/.test(String(o))&&o<4294967295))throw new F({code:x.INVALID_PARAMETER,extraCode:5013,fnName:i,messageParams:{key:e}})}function Vf(o,i,e){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(o))throw new F({code:x.INVALID_PARAMETER,extraCode:5012,fnName:i,messageParams:{key:e}})}var eL={type:"number",notLessThanZero:!0},FS=(o,i)=>o.width*o.height>=i.width*i.height&&o.frameRate>=i.frameRate&&o.bitrate>=i.bitrate;function Ff(o){var t;if(!((t=o==null?void 0:o.option)!=null&&t.small))return;if(!Cc()){R.warn("small stream is not supported"),delete o.option.small;return}let i=Cs(o.option.profile),e=Cs(o.option.small,!0);if(!FS(i,e)){R.warn(`small stream profile must be less than big stream profile. Big: ${JSON.stringify(i)}, Small: ${JSON.stringify(e)}`),delete o.option.small;return}}var BS={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(o,i,e){if(this._room.isJoined)throw new F({code:x.INVALID_OPERATION,extraCode:5104,fnName:e});if(o.roomId){if(re(o.roomId))throw new F({code:x.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:i}});Uf(o.roomId,e,i)}else if(o.strRoomId)Vf(o.strRoomId,e,i);else throw new F({code:x.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:Rs,mute:{type:["boolean","string"]},publish:{type:"boolean"},capture:{required:!1,type:"boolean"},option:kf},validate(o){var i,e;if(!((i=o==null?void 0:o.option)!=null&&i.videoTrack)&&Zi())throw new F({code:x.ENV_NOT_SUPPORTED,extraCode:5201});(e=o==null?void 0:o.option)!=null&&e.small&&Ff(o)}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:L(O({},Rs),{required:!1}),publish:{type:"boolean"},capture:{required:!1,type:"boolean"},mute:{type:["boolean","string"]},option:kf},validate(o){var i;(i=o==null?void 0:o.option)!=null&&i.small&&Ff(o)}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:Lf},validate(o){var i;if(!((i=o==null?void 0:o.option)!=null&&i.audioTrack)&&Zi())throw new F({code:x.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:Lf}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:Rs,publish:{type:"boolean"},option:Pf},validate(o,i,e,t,r){var s;if(!((s=o==null?void 0:o.option)!=null&&s.videoTrack)){if(Zi())throw new F({code:x.ENV_NOT_SUPPORTED,extraCode:5201});if(!En())throw new F({code:x.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:Rs,publish:{type:"boolean"},option:Pf}},muteRemoteAudio:[wf,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[wf,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:Rs,userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(o,i,e){ys(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(o.userId);if(xf(!!t,e,o),t&&(o.streamType==="main"&&!t.muteState.videoAvailable||o.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new F({code:x.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:o}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:L(O({},Rs),{required:!1}),userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(o,i,e){ys(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(o.userId);if(xf(!!t,e,o),t&&(o.streamType==="main"&&!t.muteState.videoAvailable||o.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new F({code:x.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:o}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(o,i,e){if(o.userId!=="*"&&T(o.streamType))throw new F({code:x.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(o,i,e){ys(this._room.isJoining||this._room.isJoined,e)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(o,i,e,t){if(!An)throw new F({code:x.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new F({code:x.INVALID_OPERATION,fnName:e,extraCode:5108});if(o.byteLength>1e3)throw new F({code:x.INVALID_PARAMETER,extraCode:5018,fnName:e});if(o.byteLength===0)throw new F({code:x.INVALID_PARAMETER,extraCode:5017,messageParams:{key:i},fnName:e});ys(this._room.isJoined,e)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(o,i,e){if(!o&&!this._room.isMainStreamPublished||o&&!this._room.isAuxStreamPublished)throw new F({code:x.INVALID_OPERATION,extraCode:5109,messageParams:{key:i},fnName:e})}}}}],sendCustomMessage:{name:"message",required:!0,type:"object",properties:{cmdId:{type:"number",required:!0,min:1,max:10},data:{instanceOf:ArrayBuffer,required:!0,validate(o,i,e,t){if(o.byteLength>1e3)throw new F({code:x.INVALID_PARAMETER,extraCode:5018,fnName:e});if(o.byteLength===0)throw new F({code:x.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:i}})}}},validate(o,i,e){if(ys(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new F({code:x.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:i}})}},switchRoom:{name:"switchRoomConfig",type:"object",required:!0,validate(o,i,e){if(ys(this._room.isJoined,e),this._room.useStringRoomId&&o.strRoomId===this._room.roomId||!this._room.useStringRoomId&&o.roomId===Number(this._room.roomId))throw new F({code:x.INVALID_PARAMETER,extraCode:5020,fnName:e,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(o.roomId&&this._room.useStringRoomId||!o.roomId&&o.strRoomId&&!this._room.useStringRoomId)throw new F({code:x.INVALID_PARAMETER,extraCode:5019,fnName:e,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(o.roomId)Uf(o.roomId,e,i);else if(o.strRoomId)Vf(o.strRoomId,e,i);else throw new F({code:x.INVALID_PARAMETER,extraCode:5015,fnName:e})},properties:{roomId:{type:"number"},strRoomId:{type:"string"},privateMapKey:{type:"string"},userSig:{type:"string",required:!0},autoSubscribeCount:{type:"number",min:0,max:50}}}},qe={TRTC:BS};var ut=class extends Error{};function HS(o,i){let e=Wr(o);for(let t=0;t<i.length;t++)ti(e[t],i[t]);return e}function $S(o){this._resolve=Promise.resolve(o)}function GS(o){this._reject=Promise.reject(o)}var wr=class wr{constructor(i,e){this.instance=i;this.group=e;d(this,"started",!1);d(this,"ops",[]);d(this,"startSame",()=>!0);d(this,"mergeUpdate",HS);let t=wr.instances.get(i);t?t.set(e,this):wr.instances.set(i,new Map([[e,this]]))}static get(i,e){if(!e)return;let t=wr.instances.get(i);return t&&t.get(e)||new wr(i,e)}static gets(i,e){let t=wr.instances.get(i),r=[];return t&&t.forEach((s,n)=>{e.test(n)&&r.push(s)}),r}action(i,e,t){let r=a=>{var c;return i===0?this.started=!0:i===3&&(this.started=!1),this.ops.shift(),(c=this.currentOp)==null||c.action(),a},s=a=>{var c,l;throw this.ops.shift(),i===0&&((c=this.currentOp)==null?void 0:c.type)===2&&this.ops.shift().reject(new ut("start failed")),(l=this.currentOp)==null||l.action(),a},n={type:i,action:()=>e(...n.args).then(r,s),args:t,resolve:$S,reject:GS};try{switch(this.state){case 1:if(i===0)throw new ut("already started");break;case 4:if(i===2)throw new ut("not started");break;default:return this.cacheOp(n)}}catch(a){return Promise.reject(a)}return this.ops.push(n),n.promise=e(...n.args).then(r,s)}cacheOp(i){if(this.ops.length===1)switch(this.state){case 0:case 2:if(i.type===0)throw new ut("already start");break;case 3:switch(i.type){case 2:throw new ut("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new ut("unknown state")}else switch(i.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let t=new ut("keep stop");if(this.ops.slice(1).forEach(r=>r.reject(t)),this.ops=this.ops.slice(0,1),this.state===3)return this.currentOp.promise}break;case 2:switch(this.lastOpType){case 2:return this.lastOp.args=this.mergeUpdate(this.lastOp.args,i.args),this.lastOp.promise;case 3:throw new ut("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new ut("start not allowed after update");case 0:throw new ut("duplicate start");case 3:if(this.startSame(this.currentOp.args,i.args))throw this.ops.pop().reject(new ut("keep start")),new ut("already start")}}i.promise=new Promise((t,r)=>{i._resolve?i._resolve.then(t):i.resolve=t,i._reject?i._reject.catch(r):i.reject=r});let{action:e}=i;return i.action=()=>e().then(i.resolve,i.reject),this.ops.push(i),i.promise}get lastOp(){return this.ops[this.ops.length-1]}get lastOpType(){return this.lastOp.type}get currentOp(){return this.ops[0]}get state(){return this.currentOp?this.currentOp.type:this.started?1:4}};d(wr,"instances",new WeakMap);var nr=wr;var ud=new WeakMap,hd=(o,i)=>{if(i instanceof ut){let{stack:e}=i;i=new F({code:x.OPERATION_ABORT,message:`${o} abort: ${i.message}`,fnName:o}),e&&(i.stack+=e.substr(e.indexOf(`
55
+ `)))}throw i};function Lr(o,i){return Y((e,t)=>function(...r){let s=nr.get(this,typeof o=="string"?o:o.call(this,...r));return s?(i&&(s.startSame=i.bind(this)),s.action(0,e.bind(this),r).catch(hd.bind(null,t))):e.apply(this,r)})}function Ao(o,i){let{merge:e,debounce:t}=i||{};return Y((r,s)=>function(...n){let a=nr.get(this,typeof o=="string"?o:o.call(this,...n));if(!a)return r.apply(this,n);if(e&&(a.mergeUpdate=e.bind(this)),t&&t.isNeedToDebounce.apply(this,n)){let{delay:c,getKey:l}=t;return new Promise((h,m)=>{var g,E;let u=(g=ud.get(this))==null?void 0:g.get(l(...n));if(u){let{timeoutId:A,resolve:k}=u;clearTimeout(A),k()}let _=setTimeout(()=>{if(a.state===3||a.state===4)return h();a.action(2,r.bind(this),n).catch(hd.bind(null,s)).then(h,m)},c);ud.has(this)?(E=ud.get(this))==null||E.set(l(...n),{timeoutId:_,resolve:h}):ud.set(this,new Map([[l(...n),{timeoutId:_,resolve:h}]]))})}return a.action(2,r.bind(this),n).catch(hd.bind(null,s))})}function xr(o){return Y((i,e)=>function(...t){let r=typeof o=="function"?o.call(this,...t):o;if(r instanceof RegExp)return Promise.all(nr.gets(this,r).map(n=>n.action(3,()=>Promise.resolve(),t))).then(()=>i.call(this,...t));let s=nr.get(this,r);return s?s.action(3,i.bind(this),t).catch(hd.bind(null,e)):i.apply(this,t)})}function Ur(){return function(o,i,e){return o.prototype[i]=function(){let t=this._log||console,r=`"${i}" is a static method. Use TRTC.${i}() instead. See: ${ft}/en/TRTC.html#.${i}`;t.warn(r)},e}}var U={ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",KICKED_OUT:"kicked-out",REMOTE_USER_ENTER:"remote-user-enter",REMOTE_USER_EXIT:"remote-user-exit",REMOTE_AUDIO_AVAILABLE:"remote-audio-available",REMOTE_AUDIO_UNAVAILABLE:"remote-audio-unavailable",REMOTE_VIDEO_AVAILABLE:"remote-video-available",REMOTE_VIDEO_UNAVAILABLE:"remote-video-unavailable",AUDIO_VOLUME:"audio-volume",AUDIO_FRAME:"audio-frame",NETWORK_QUALITY:"network-quality",CONNECTION_STATE_CHANGED:"connection-state-changed",AUDIO_PLAY_STATE_CHANGED:"audio-play-state-changed",VIDEO_PLAY_STATE_CHANGED:"video-play-state-changed",SCREEN_SHARE_STOPPED:"screen-share-stopped",DEVICE_CHANGED:"device-changed",PUBLISH_STATE_CHANGED:"publish-state-changed",TRACK:"track",STATISTICS:"statistics",SEI_MESSAGE:"sei-message",CUSTOM_MESSAGE:"custom-message",VIDEO_DECODE_DOWNGRADE_STATE_CHANGED:"video-decode-downgrade-state-changed",LAYER_DATA:"layerData",FIRST_VIDEO_FRAME:"first-video-frame",PERMISSION_STATE_CHANGE:"permission-state-change",VIDEO_SIZE_CHANGED:"video-size-changed"},Bf=new Set([U.AUDIO_VOLUME,U.AUDIO_FRAME,U.NETWORK_QUALITY,U.STATISTICS,U.SEI_MESSAGE,U.CUSTOM_MESSAGE,U.LAYER_DATA]);var Ph={};Vi(Ph,{ScheduleRequestType:()=>Gf,getAbilityConfig:()=>JS,getScheduleDomain:()=>fd,isNeedToSchedule:()=>md,scheduleProxy:()=>wi,sendScheduleRequest:()=>kh,setIsNeedToSchedule:()=>Lt,setScheduleProxy:()=>pd});var Oh=null,$f=0,WS=48*3600*1e3,md=!0;typeof document!="undefined"&&document.head.insertAdjacentHTML("beforeend",Object.values($i).map(o=>`<link rel="dns-prefetch" href="https://${o}">`).join(`\r
56
+ `));function Lt(o){he(o)&&o!==md&&(md=o,R.info(`setIsNeedToSchedule ${o}`),o||($f=Date.now()+WS))}S.on("28",()=>Lt(!0));S.on("63",()=>Lt(!0));S.on("84",()=>Lt(!0));S.on("201",o=>{o.state==="RECONNECTING"&&Lt(!0)});S.on("202",o=>{o.state==="RECONNECTING"&&Lt(!0)});function qS(o,i,e){let t={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let r=performance.getEntriesByType("resource"),s=Vr(o,"config",p.MAIN),n=Vr(o,"config",p.BACKUP);for(let a of r)if(a.startTime>=e&&(a.name===s||a.name===n)&&a.transferSize>0){let c=a.name===s?p.MAIN:p.BACKUP,l=Math.round(a.duration),h=Math.round(a.domainLookupStart-a.startTime),m=a.redirectStart>0?Math.round(a.redirectEnd-a.redirectStart):0,u=a.fetchStart>0?Math.round(a.domainLookupStart-a.fetchStart):0,_=Math.round(a.domainLookupEnd-a.domainLookupStart),g=Math.round(a.requestStart-a.secureConnectionStart),E=Math.round(a.secureConnectionStart-a.connectStart),A=Math.round(a.responseStart-a.requestStart),k=Math.round(a.responseEnd-a.responseStart),se=[_,g,E,A,k];ne.uploadEvent({log:`stat-schedule-net:${l}(${h}(${m}->${u})->${se.join("->")}) ${c}`,userId:i}),t=L(O({},t),{totalCost:l,local:h,dns:_,tcp:E,tls:g,request:A,response:k});break}}catch(r){R.error("getScheduleDetailCost error",r)}return t}function kh(l){return f(this,arguments,function*({userId:o,sdkAppId:i,useStringRoomId:e,roomId:t,userSig:r,version:s,frameWorkType:n,role:a,latencyLevel:c}){var m;if(!md&&Oh&&$f>Date.now())return{isCached:!0,result:Oh};let h={delta:0,count:[1,1],msg:[],detail:[]};try{let u=new FormData;u.append("userId",String(o)),u.append("sdkAppId",String(i)),u.append("isStrGroupId",String(e)),u.append("groupId",String(t)),u.append("sdkVersion",s),u.append("userSig",String(r));let _=((m=yield Yr())==null?void 0:m.model)||sc();_&&u.append("model",_);let g=ai();g&&u.append("osString",g),a&&u.append("role",String(a)),c&&u.append("latencyLevel",String(c)),n&&u.append("frameWorkType",String(n));let E=V(),A=yield XS(u,h,i);A.config&&(A.config.loggerDomain&&Br(A.config.loggerDomain),he(A.config.scheduleCache)&&Lt(!A.config.scheduleCache)),h.delta=V()-E;let k=qS(Number(i),o,E);return Oh=A,{isCached:!1,result:A,detailCost:k}}catch(u){let _=Ae(u)?u[0]:u,g=Q(_.code)?_.code:0,E=`schedule failed${_.message?`: ${_.message}`:""}`,A=new D({code:I.SCHEDULE_FAILED,extraCode:g,message:$({key:B.JOIN_ROOM_FAILED,data:{error:E,code:g}})});throw R.error(E,g),A}})}var wi={main:"",backup:""};function pd(o){Ae(o)?(wi.main=o[0],wi.backup=o[1]):wi.main=o}var Gf=(t=>(t.CONFIG="config",t.TRTC_AUTO_CONF="trtcAutoConf",t.AUDIO_AI_AUTH="audioAiAuth",t))(Gf||{});function Vr(o,i,e=p.MAIN,t=!1){return`https://${wi[e]||fd(o,e,t)}/api/v1/${i}`}function JS(o,i,e){let t=Vr(o,i),r=Vr(o,i,p.BACKUP),s=new URLSearchParams(e).toString(),n=fetch(`${t}?${s}`).then(c=>c.json()),a=fetch(`${r}?${s}`).then(c=>c.json());return Xr([n,a])}function fd(o,i=p.MAIN,e=!1){let t;return Vt(o)?e?t=i===p.MAIN?$i.MAIN_OVERSEA_BACKUP:$i.BACKUP_OVERSEA:t=i===p.MAIN?$i.MAIN_OVERSEA:$i.BACKUP_OVERSEA:t=i===p.MAIN?$i.MAIN:$i.BACKUP,t}function jS(o,i,e){return new Promise((t,r)=>{qi({url:o,body:i,timeout:e.timeout,priority:"high"}).then(s=>{s.data.code===0?t(s.data.data):r({code:s.data.code,message:s.data.msg})}).catch(r)})}var Hf=(o,i)=>Ci({retryFunction:jS,settings:{retries:3,timeout:0},onError:i,onRetrying:o});function XS(o,i,e){return new Promise((t,r)=>{let s=null;Xr([Hf(n=>i.count[0]=n+1,({error:n,retry:a,retriedCount:c,retryFuncArgs:l})=>{i.msg[0]=n.message,s||(c>=1&&(l[0]=Vr(e,"config",p.MAIN,!0)),a())})(Vr(e,"config",p.MAIN),o,{get timeout(){return Jr(2+i.count[0])*1e3}}),Hf(n=>i.count[1]=n+1,({error:n,retry:a,retriedCount:c,retryFuncArgs:l})=>{i.msg[1]=n.message,s||(c>=2&&(l[0]=Vr(e,"config",p.BACKUP,!0)),a())})(Vr(e,"config",p.BACKUP),o,{get timeout(){return Jr(2+i.count[1])*1e3}})]).then(n=>{s=n,t(s)}).catch(r)})}var zS=o=>o.startsWith("data:application/octet-stream;base64,"),QS=o=>o.startsWith("file://"),zn=class{constructor(){d(this,"_log");this._log=R.createLogger({id:"fd"})}download(i,e){return f(this,null,function*(){let{type:t="blob"}=e||{};i=Pa(i);try{let r=V(),s;if(me(fetch)?s=yield this.downloadWithFetch(i,t):s=yield this.downloadWithXHR(i,t),!s||!s.data)throw new Error("data is empty");let n=V()-r;return this._log.info(`downloaded: ${i}, return type: ${t}, cost: ${n}ms`),v.addSuccessEvent({key:522700,cost:V()-r}),s.data}catch(r){throw this._log.error(`failed to download: ${i}, error: ${r}`),v.addFailedEvent({key:522700,error:r}),r}})}downloadWithFetch(i,e){return f(this,null,function*(){this._log.info(`download with fetch: ${i}, return type: ${e}`);try{let t=yield fetch(i);if(!t.ok){let s=new Error(`network response was not ok: ${t.status}`);throw s.status=t.status,s}let r;return e==="arraybuffer"?r=yield t.arrayBuffer():r=yield t.blob(),{data:r}}catch(t){throw t}})}downloadWithXHR(i,e){return this._log.info(`download with xhr: ${i}, return type: ${e}`),new Promise((t,r)=>{let s=new XMLHttpRequest;s.open("GET",i,!0),s.responseType=e,s.onload=()=>{if(s.status===200||s.status===0&&s.response)t({data:s.response});else{let n=new Error(`XHR failed, status: ${s.status}`);n.status=s.status,r(n)}},s.onerror=r,s.send(null)})}loadWasm(i,e){return f(this,null,function*(){this._log.info(`loadWasm ${i}, importObject: ${JSON.stringify(e)}`);let t=V(),r=null,s=null;if(me(WebAssembly.instantiateStreaming)&&!zS(i)&&!QS(i)&&me(fetch))try{let n=fetch(i);r=(yield WebAssembly.instantiateStreaming(n,e)).instance}catch(n){s=n}if(!r)try{let n=yield this.download(i,{type:"arraybuffer"});r=(yield WebAssembly.instantiate(n,e)).instance}catch(n){s=n}if(r){let n=V()-t;return this._log.info(`loadedWasm ${i}, cost: ${n}ms`),v.addSuccessEvent({key:522701,cost:n}),r}throw this._log.error(`failed to loadWasm ${i}, error: ${s}`),v.addFailedEvent({key:522701,error:s}),s})}loadScript(i){this._log.info(`loadScript ${i}`);let e=V();return new Promise((t,r)=>{let s=document.createElement("script");s.type="text/javascript",s.onload=()=>{this._log.info(`loadedScript ${i}, cost: ${V()-e}ms`),v.addSuccessEvent({key:522702,cost:V()-e,split:1e3}),t(s)},s.onerror=n=>{this._log.error(`failed to loadScript ${i}, error: ${(n==null?void 0:n.message)||JSON.stringify(n)}`),v.addFailedEvent({key:522702}),r(n)},s.crossOrigin="anonymous",s.src=i,document.head.append?document.head.append(s):document.getElementsByTagName("head")[0].appendChild(s)})}};M([Mt({settings:{timeout:0,retries:3},onError(i,e,t){var r;(i==null?void 0:i.status)===404||(r=i==null?void 0:i.message)!=null&&r.includes("404")?(this._log.warn("download 404, stop retry"),t(i)):e()},onRetrying(i){this._log.warn(`download retrying: ${i}`)}})],zn.prototype,"download",1),M([Mt({settings:{timeout:3e3,retries:3},onRetrying(i){this._log.warn(`loadScript retrying: ${i}`)}})],zn.prototype,"loadScript",1);var Qn=new zn;function wh([o,i]){let e=i.byteLength,t=parseInt(String(e/255),10),r=e%255,s=[];s.push(0,0,0,1,6,o);for(let a=0;a<t;a++)s.push(255);s.push(r);let n=new DataView(i);return s.push(...new Uint8Array(n.buffer)),s.push(128),new sr(new DataView(new Uint8Array(s).buffer),!0)}function Lh(o){return o.type==="empty"||o.data.byteLength===0}function xh(o){let i=new DataView(o),e=0;for(;e<i.byteLength;){let t=0;if(e+4<=i.byteLength&&i.getUint8(e)===0&&i.getUint8(e+1)===0&&i.getUint8(e+2)===0&&i.getUint8(e+3)===1)t=4;else if(e+3<=i.byteLength&&i.getUint8(e)===0&&i.getUint8(e+1)===0&&i.getUint8(e+2)===1)t=3;else{e+=1;continue}let r=e+t;if(r<i.byteLength&&(i.getUint8(r)&31)===6)return!0;let s=-1;for(let n=e+t;n<i.byteLength;n+=1){if(n+4<=i.byteLength&&i.getUint8(n)===0&&i.getUint8(n+1)===0&&i.getUint8(n+2)===0&&i.getUint8(n+3)===1){s=n;break}if(n+3<=i.byteLength&&i.getUint8(n)===0&&i.getUint8(n+1)===0&&i.getUint8(n+2)===1){s=n;break}}e=s===-1?i.byteLength:s}return!1}function Uh(o){let i=0,e=0,t=new DataView(o);for(let r=0;r<o.byteLength;r++)switch(t.getUint8(r)){case 0:i++;break;case 1:(i===2||i===3)&&e++,i=0;break;default:i=0;break}return e}function Vh({frame:o,seiMessageList:i}){if(!i||i.length===0||o.data.byteLength===0)return o;let t=9-Uh(o.data);if(t<=0)return o;let r=i.splice(0,t).reverse().map(wh),s=r.reduce((h,m)=>h+m.dataView.byteLength,0),n=new ArrayBuffer(s+o.data.byteLength),a=new DataView(n),c=new DataView(o.data),l=0;for(let h=0;h<r.length;h++)for(let m=0;m<r[h].dataView.byteLength;m++)a.setInt8(l++,r[h].dataView.getInt8(m));for(let h=0;h<o.data.byteLength;h++)a.setInt8(l++,c.getInt8(h));return o.data=n,o}function Fh({frame:o,onSEI:i}){try{if(Lh(o)||!xh(o.data))return o;let e=ed(o.data,!1).filter(t=>t.isSEI);i==null||i(e.reverse())}catch(e){}return o}function Wf({seiMessageList:o,isAudio:i,getNtpTime:e,isMain:t}){return new TransformStream({transform(r,s){let n=r;i?audioEncodePipeline.forEach(a=>{n=a({frame:n,ntp:e()})}):videoEncodePipeline.forEach(a=>{n=a({frame:n,seiMessageList:o,onDump:()=>{self.postMessage({type:"dump",isAudio:i,data:n.data,userId:"",streamType:t?"main":"auxiliary"})}})}),s.enqueue(n)}})}function qf({userId:o,streamType:i,isAudio:e}){return new TransformStream({transform(t,r){let s=t;e?(audioDecodePipeline.forEach(n=>{s=n({frame:s,onAudioFrameNTPTime:a=>{self.postMessage({type:"audio-ntp",data:a,userId:o,streamType:i})},onDump:()=>{self.postMessage({type:"dump",isAudio:e,data:s.data,userId:o,streamType:i})}})}),r.enqueue(s)):videoDecodePipeline.forEach(n=>{s=n({frame:s,onSEI:a=>{a.forEach(c=>{self.postMessage({type:"sei",seiPayloadType:c.seiPayloadType,data:c.seiPayload.buffer,userId:o,streamType:i})})}})}),r.enqueue(s)}})}function _d(o){let i=[sr],e=[Uh,Lh,ed,xh,wh,Wf,qf,xa,La],t=()=>{let l=[],h=[],m=[],u=0;self.onmessage=_=>{switch(_.data.type){case"sei":_.data.isMain?(l.push(_.data.data),_.data.small&&m.push(_.data.data)):h.push(_.data.data);break;case"ntp-offset":u=_.data.data;break}},self.onrtctransform=_=>{let{options:g}=_.transformer,E=g.isReceiver?qf({userId:g.userId,streamType:g.streamType,isAudio:g.isAudio}):Wf({getNtpTime:()=>Date.now()+u,isAudio:g.isAudio,isMain:g.isMain,seiMessageList:g.isMain?g.small?m:l:h});_.transformer.readable.pipeThrough(E).pipeTo(_.transformer.writable)}},r=`const videoEncodePipeline=[${o.videoEncodePipeline.toString()}];
57
+ const videoDecodePipeline=[${o.videoDecodePipeline.toString()}];
58
+ const audioEncodePipeline = [${o.audioEncodePipeline.toString()}];
59
+ const audioDecodePipeline = [${o.audioDecodePipeline.toString()}];`,s=`(()=>{${i.map(l=>`const ${l.name}=(()=>${l.toString()})()`).join(`
60
+ `)}
61
+ ${e.map(l=>l.toString()).join(`
62
+ `)};(${t})();${r}})()`,n=new Blob([s],{type:"text/javascript"}),a=URL.createObjectURL(n),c=new Worker(a);return URL.revokeObjectURL(a),c}function Jf({TRTC:o,room:i,errorModule:e,assetsPath:t}){return{TRTC:o,LocalMixVideoTrack:go,LocalVideoTrack:ze,LocalScreenTrack:Pt,room:i,assetsPath:t,fileDownloader:Qn,innerEmitter:S,INNER_EVENT:C,constants:ll,environment:ts,utils:yh,eventLogger:ne,log:this.room.getLogger(),loggerManager:R,errorModule:e,kvStatManager:v,rtcDectection:vi,trtc:this,rx:Ch,enums:ru,schedule:Ph,getDevices:us,initVisionTaskRegistry:(r,s="/mediapipe/vision.js")=>f(this,null,function*(){window.VisionTaskRegistry||(yield Qn.loadScript(`${r}/${s}`.replace(/([^:]\/)\/+/g,"$1"))),yield(yield window.VisionTaskRegistry.getInstance(r)).preloadModels([window.VisionTaskType.ImageSegmenter])}),audioContext:Se(),deviceDetector:ve,AudioPlayer:ms,RemoteAudioPlayer:ps,VideoPlayer:it,showAutoPlayDialog:cs,Timer:oe,clearStarted:(r,s)=>{let n=r.getAlias(),a=nr.instances.get(this);if(a)if(s){let c=a.get(n+s);if(!c)return;c.started=!1}else a.forEach((c,l)=>{l.startsWith(n)&&(c.started=!1)})},startGetPCM:jn,createAudioNode:wn,getNetworkTimeOffset:ym,validateSourceNode:()=>{var r;if(te&&!((r=this.room.audioManager._localAudioPipline)!=null&&r.source.node))throw new F({code:x.DEVICE_ERROR,extraCode:5310,message:"The audio processing plugin cannot be used due to the microphone's sampling rate is not 48KHz in Firefox. Please switch to another browser such as Chrome."})},createScriptTransformWorker:_d}}var jf=(o,i)=>{let{emit:e}=o;return o.emit=(...t)=>{try{return e.apply(o,t)}catch(r){let s=$({key:B.CATCH_HANDLER_ERROR,data:{name:i,event:t[0]},addDocLink:!1});return R.warn(`${s}
57
63
 
58
- ${r.stack}`),!1}},o};var Cs=new WeakMap;function Vf(o){let i=Cs.get(o);i&&(i.forEach(e=>clearTimeout(e)),Cs.delete(o))}function Ff(o,i){return Y((e,t)=>function(...r){let s=Cs.get(this);s||(s=new Map,Cs.set(this,s));let n=i(...r),a=s.get(n);if(!a||a<=0){e.apply(this,r);let d=setTimeout(()=>{var l;(l=Cs.get(this))==null||l.delete(n)},o);s.set(n,d)}else{clearTimeout(a);let d=window.setTimeout(()=>{var l;e.apply(this,r),(l=Cs.get(this))==null||l.delete(n)},o);s.set(n,d)}})}var Hf="trtc-sdk-v5",bh="5.15.0-beta.20";function ot(...o){return Y((i,e)=>function(...t){try{uc.call(this,o,t,e,this._name)}catch(r){return Promise.reject(r)}return i.apply(this,t)})}function Nh(...o){return Y((i,e)=>function(...t){try{uc.call(this,o,t,e,this._name)}catch(r){throw r}return i.apply(this,t)})}function uc(o,i,e,t){if(Ae(o))for(let r=0;r<o.length;r++)lc.call(this,{rule:o[r],value:i[r],key:o[r].name,fnName:e,className:t});else lc.call(this,{rule:o,value:i[0],key:o.name,fnName:e,className:t})}function lc({rule:o,value:i,key:e,fnName:t,className:r}){function s(d){return{code:W.INVALID_PARAMETER,extraCode:d,fnName:t,messageParams:{key:e,rule:o,value:i}}}if(T(i)){if(o.required)throw new F(s(5001));if(T(o.defaultValue)){le(o.validate)&&o.validate.call(this,i,e,t,r,this);return}i=o.defaultValue}if(Array.isArray(o.type)){let d=!1;for(let l=0;l<o.type.length;l++)o.type[l]===null&&i===null&&(d=!0),le(o.type[l])&&i instanceof o.type[l]&&(d=!0),ie(o.type[l])&&Me(i)===o.type[l].toLowerCase()&&(d=!0);if(!d)throw new F({code:W.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:o.type.map(l=>jr(l)?wo(l):ie(l)?l:Me(l))},value:i}})}else if(!T(o.type)&&Me(i)!==o.type)throw new F(s(5002));if(o.allowEmpty===!1){let d=Q(i)&&(i===0||Number.isNaN(i)),l=ie(i)&&i.trim()==="";if(d||l)throw new F(s(5003))}if(o.notLessThanZero&&Q(i)&&i<0)throw new F(s(5006));if(!T(o.min)&&Q(i)&&i<o.min)throw new F(s(5007));if(!T(o.max)&&Q(i)&&i>o.max)throw new F(s(5008));if(ie(o.instanceOf)){if(!i||i._name!==o.instanceOf)throw new F(s(5004))}else if(le(o.instanceOf)&&!(i instanceof o.instanceOf))throw new F(s(5004));if(Array.isArray(o.values)&&!o.values.includes(i))throw new F(s(5005));let{properties:n}=o;dt(n)&&yt(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}=o;dt(a)&&Ae(i)&&i.forEach((d,l)=>{lc.call(this,{rule:a,value:d,key:`${e}[${l}]`,fnName:t,className:r})}),le(o.validate)&&o.validate.call(this,i,e,t,r,this)}function Se(o={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t,ignoreLog:r,ignoreErrorLog:s}=o;return Y((n,a)=>function(...d){var m,g,E;function l(C,P,re){if(re&&re.includes(C))return"hided";if(e){let L=e(...d);if(d[L.argIndex]===P)return L.value}if(P===d||C in d)return P;try{return P instanceof HTMLElement?`id: ${P.id} type:${Me(P)}`:P instanceof MediaStreamTrack?Ma(P):(JSON.stringify(P),P)}catch(L){return`type:${Me(P)}`}}let u=(this==null?void 0:this._log)||R;if(r!=null&&r(...d))return n.apply(this,d);d.length>0?u.info(`${a}() ${JSON.stringify(d,(C,P)=>l(C,P,["userSig","privateMapKey"]))}`):u.info(`${a}()`);let h=t?t(...d):ld[a],p=(s==null?void 0:s(...d))||!1;try{let C=n.apply(this,d),P=V();if(Tr(C)){let re=`${a.includes("Plugin")?`${((g=(m=d[0]).getName)==null?void 0:g.call(m))||""} `:" "}`;return C.then(L=>(u.info(`${a}() success ${re}${i.call(this,...d)}`),y.addSuccessEvent({key:h,cost:V()-P}),L)).catch(L=>{var k;L=F.convertFrom.call(this,L,a,d.length===1?d[0]:d);let Qe=L.extraCode||L.code,N=(k=L.message)!=null&&k.includes(Qe)?"":` code:${Qe}`;throw p||u.error(`${a}() failed ${re}${i.call(this,...d)} ${L}${N} params: ${JSON.stringify(d,l)}`),y.addFailedEvent({key:h,error:L}),L})}return y.addSuccessEvent({key:h}),C}catch(C){C=F.convertFrom.call(this,C,a);let P=C.extraCode||C.code,re=(E=C.message)!=null&&E.includes(P)?"":` code:${P}`;throw p||u.error(`${a}() failed ${C}${re} params: ${JSON.stringify(d,l)}`),y.addFailedEvent({key:h,error:C}),C}})}var hc=o=>Y((i,e)=>function(t,r){return f(this,null,function*(){let s=this._plugins.get(t);if(!s)throw this._log.error(`plugin ${String(t)} is not found`),new F({code:W.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});if(le(s.constructor.isSupported)&&!s.constructor.isSupported())throw this._log.error(`plugin ${String(t)} is not supported`),new F({code:W.ENV_NOT_SUPPORTED,message:`plugin ${String(t)} is not supported`,extraCode:5210,fnName:e});return uc.call(this,s.getValidateRule(o),[r],e,"TRTC"),i.call(this,s,r)})});var mc=0,vh,ar=class ar{constructor(i){this.core=i;c(this,"log");c(this,"customAudioReferenceMap",new Map);c(this,"audioRefId",0);c(this,"audioContext",Ee());c(this,"localAudioWorkletNode");c(this,"screenAudioWorkletNode");c(this,"mixNode");c(this,"silentNode");mc=mc+1,this.log=i.log.createChild({id:`${this.getAlias()}${mc}`}),this.log.info(`created id=${this.getAlias()}${mc}`),this.installEvent()}static getStartValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,t,r,s){if(!i.room.audioManager.hasAudioTrack&&!i.room.audioManager.hasScreenAudioTrack)throw new F({code:W.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return vh||(vh=this.doPreload(i)),vh}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield tr(this.audioContext,t)}catch(r){this.log.error(`preload audioProcessor failed. ${r}`)}finally{URL.revokeObjectURL(t)}})}getName(){return ar.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(i){switch(i){case"start":return ar.getStartValidateRule(this.core);case"update":return ar.updateValidateRule;case"stop":return ar.stopValidateRule}}start(i){return f(this,null,function*(){var p,m,g,E;let{room:e}=this.core,{sdkAppId:t,userId:r,userSig:s,assetsPath:n=this.core.assetsPath,audioReference:a,processLevel:d,enableDump:l,isLocalAudioNeedAudioProcess:u=!0,isScreenAudioNeedAudioProcess:h=!1}=i;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=u,this.core.room.audioManager.isScreenAudioNeedAudioProcess=h,!n)throw new F({code:W.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload(`${n}/audioProcessor-wasm.js`),u&&!this.localAudioWorkletNode){let{sign:C,status:P,timestamp:re}=yield this.getAuthData(t,r,s);this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",t,r,re,C,P,e)}if(h&&!this.screenAudioWorkletNode){let{sign:C,status:P,timestamp:re}=yield this.getAuthData(t,r,s);this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",t,r,re,C,P,e)}this.mixNode||(this.mixNode=this.audioContext.createGain(),this.mixNode.gain.value=1),this.silentNode||(this.silentNode=this.audioContext.createConstantSource(),this.silentNode.offset.setValueAtTime(0,this.audioContext.currentTime),this.silentNode.start()),(p=this.localAudioWorkletNode)==null||p.port.postMessage({type:"enable"}),(m=this.screenAudioWorkletNode)==null||m.port.postMessage({type:"enable"}),e.audioManager.addAudioProcessor(this.mixNode,this.silentNode,this.localAudioWorkletNode,this.screenAudioWorkletNode),T(a)||a.forEach(C=>{this.customAudioReferenceMap.set(C,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:C,refId:`o-${this.audioRefId++}`})}),T(d)||(g=this.localAudioWorkletNode)==null||g.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:d}}),T(l)||(E=this.localAudioWorkletNode)==null||E.port.postMessage({type:"dump",data:{enable:l}})})}update(i){return f(this,null,function*(){var s,n,a;let{audioReference:e,enableDump:t,processLevel:r}=i;T(e)||(this.customAudioReferenceMap.forEach((d,l)=>{this.customAudioReferenceMap.delete(l),this.core.room.audioManager.updateAudioReference({type:"remove",refId:d})}),e.forEach(d=>{this.customAudioReferenceMap.set(d,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:d,refId:`o-${this.audioRefId++}`})})),T(r)||(s=this.localAudioWorkletNode)==null||s.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:r}}),T(t)||((n=this.localAudioWorkletNode)==null||n.port.postMessage({type:"dump",data:{enable:t}}),(a=this.screenAudioWorkletNode)==null||a.port.postMessage({type:"dump",data:{enable:t}}))})}stop(){return f(this,null,function*(){var e,t;let{room:i}=this.core;(e=this.localAudioWorkletNode)==null||e.port.postMessage({type:"disable"}),(t=this.screenAudioWorkletNode)==null||t.port.postMessage({type:"disable"}),yield i.audioManager.removeAudioProcessor(this.localAudioWorkletNode,this.screenAudioWorkletNode)})}destroy(){this.localAudioWorkletNode&&(this.localAudioWorkletNode.port.onmessage=null),this.screenAudioWorkletNode&&(this.screenAudioWorkletNode.port.onmessage=null),this.uninstallEvent()}getAuthData(i,e,t){return f(this,null,function*(){let r=String(Date.now()).slice(0,-3),{auth:s,sign:n,status:a,message:d}=yield JS({sdkAppId:i,userSig:t,userId:e,timestamp:r});if(!s)throw this.log.info(`audioProcessor: ${e} auth result: ${s}. Message: ${d}`),new F({code:W.INVALID_PARAMETER,message:d});return{sign:n,status:a,timestamp:r}})}initWorkletNode(i,e,t,r,s,n,a,d){i.port.postMessage({type:"init",data:{sdkAppId:String(t),userId:r,timestamp:s,sign:n,status:a}}),i.port.onmessage=l=>{var h;let{data:u}=l;switch(u.type){case"cost":let p=(u==null?void 0:u.value)>10?"info":"debug";this.log[p](`${e==="localAudio"?"":`[${e}] `}avg cost: ${u.value} max: ${u==null?void 0:u.max}(${vo(new Date(u==null?void 0:u.maxCostTimestamp))}) hist: ${(h=u==null?void 0:u.hist)==null?void 0:h.join(" ")}`);return;case"log":this.log[u.logLevel](`${e==="localAudio"?"":`[${e}] `}${u.value}`);return;case"dump":S.emit("265",{room:d,data:u.value,type:e==="localAudio"?"dump":"dump-screen-audio"});return}}}handleLocalAudioStarted(i){return f(this,null,function*(){var e;if(!(!this.hitTest(i.room)||((e=this.core.room.scheduleResult.config)==null?void 0:e.audioProcessor)!==!0))try{yield this.core.trtc.startPlugin("AudioProcessor",{sdkAppId:this.core.room.sdkAppId,userId:this.core.room.userId,userSig:this.core.room.userSig}),this.log.warn("audio processor auto start success")}catch(t){this.log.warn(`audio processor auto start failed, error: ${t}`)}})}handleLocalAudioStopped(i){return f(this,null,function*(){var e;!this.hitTest(i.room)||((e=this.core.room.scheduleResult.config)==null?void 0:e.audioProcessor)!==!0||(yield this.core.trtc.stopPlugin("AudioProcessor"))})}installEvent(){this.core.innerEmitter.on("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.on("114",this.handleLocalAudioStopped,this)}uninstallEvent(){this.core.innerEmitter.off("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.off("114",this.handleLocalAudioStopped,this)}hitTest(i){return i===this.core.room}};c(ar,"updateValidateRule",{type:"object"}),c(ar,"stopValidateRule",{type:"object"}),c(ar,"Name","AudioProcessor");var pc=ar;function GS(o,i=_.MAIN){return`https://${xi[i]||cc(o,i)}/api/v1/audioAiAuth`}function JS(r){return f(this,arguments,function*({sdkAppId:o,userId:i,userSig:e,timestamp:t}){let n=`${GS(o)}?sdkAppId=${o}&userId=${i}&userSig=${e}&timestamp=${t}`,a=yield fetch(n),{data:{errCode:d,errMsg:l,sign:u,status:h}}=yield a.json();if(h==="1")return{auth:!0,sign:u,status:h,message:l};let p=Ut(o)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",m="Init RTCAudioProcessor failed.",g="";switch(d){case 1:g="Please check your params.";break;case 2:g=`You need to buy packages. Refer to: ${p}`;break;case 3:g="Server is invalid. Please contact our engineer. ";break;case 4:g=`Your packages is not active. Refer to: ${p}`;break;case 5:g=`Your packages is expired. Refer to: ${p}`;break;case 6:g="Your version is not supported.";break}return{auth:!1,status:h,message:l?`${m} Reason: ${l}. ${g}`:`${m}, ${g}`}})}var fc=0,Dh=class{constructor(i,e){c(this,"audioObjectURL");c(this,"player");c(this,"publisher");c(this,"mixInput");this.mixInput=new ds(e),i.url?(this.player=new Audio(i.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(i.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(i.track),this.mixInput.connect()}updateSettings(i){this.player&&(T(i.volume)||(this.volume=i.volume),T(i.loop)||(this.loop=i.loop),T(i.playbackRate)||(this.playbackRate=i.playbackRate))}updateListener(i){if(this.player){if(i.onDurationChange){let{onDurationChange:e}=i;this.player.ondurationchange=t=>{e(t.target.duration)}}if(i.onTimeUpdate){let e=i.onTimeUpdate,{player:t}=this;t.ontimeupdate=()=>{e(t.currentTime,t.duration)}}i.onEnded&&(this.player.onended=i.onEnded)}}reload(i){return f(this,null,function*(){if(i.url){let e=yield qn.download(i.url,{retries:3,type:"blob"});this.audioObjectURL&&URL.revokeObjectURL(this.audioObjectURL),this.audioObjectURL=URL.createObjectURL(e),this.player&&this.publisher?(this.player.src=this.audioObjectURL,this.publisher.src=this.audioObjectURL):(this.player=new Audio(this.audioObjectURL),this.player.crossOrigin="anonymous",this.publisher=new Audio(this.audioObjectURL),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher),this.updateListener(i),this.updateSettings(i))}else this.mixInput.replaceSource(i.track)})}reset(){this.seek(0),this.mixInput.connect()}seek(i){this.player&&(i<0&&i>this.player.duration||(this.player.currentTime=i,this.publisher.currentTime=i))}play(){var i,e;return Promise.all([(i=this.player)==null?void 0:i.play(),(e=this.publisher)==null?void 0:e.play()])}pause(){var i,e;(i=this.player)==null||i.pause(),(e=this.publisher)==null||e.pause()}stop(){var i;(i=this.player)==null||i.pause(),this.mixInput.disconnect()}setOperation(i){i==="pause"&&this.pause(),i==="resume"&&(this.pause(),this.play()),i==="stop"&&(this.pause(),this.seek(0))}set volume(i){!this.player||!this.publisher||(this.player.volume=i,this.publisher.volume=i)}set loop(i){!this.player||!this.publisher||(this.player.loop=i,this.publisher.loop=i)}set playbackRate(i){!this.player||!this.publisher||(this.player.playbackRate=i,this.publisher.playbackRate=i)}};function Rs(o,i){if(i&&typeof i!="function")throw new F({code:W.INVALID_PARAMETER,message:`start audioMixer plugin: param ${o} should be a function.`})}var wi=class wi{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 wi.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return wi.startValidateRule;case"update":return wi.updateValidateRule;case"stop":return wi.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e}=this.core;this.core.validateSourceNode(),this.log.info(`add music source, id: ${i.id} url: ${i.url}, track: ${i.track}`);let{id:t,url:r}=i;if(this.mixedMusicMap.has(t))return;let s=this.cacheMusicMap.get(t);s?i.url?s.reset():(s.mixInput.replaceSource(i.track),s.mixInput.connect()):(s=new Dh(i,e.audioManager),this.cacheMusicMap.set(t,s)),s.updateListener(i),s.updateSettings(i);try{yield s.play()}catch(n){yield this.handleAutoPlayFailed(s,i,n)}this.mixedMusicMap.set(t,s),s.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"add",audioReference:s.mixInput.source.node,refId:`ax-${t}`}),this.log.info(`start mix audio track ${t} success.`),y.addEnum({key:502700,value:3}),this.kvUpload(i)})}handleAutoPlayFailed(i,e,t){return f(this,null,function*(){if(t.name==="NotSupportedError")this.log.error(`play failed, try to reload source. error: ${t}`),yield i.reload(e),yield i.play();else if(t.name==="NotAllowedError")if(this.core.room.enableAutoPlayDialog){let r=()=>{var s;(s=i.play())==null||s.finally(()=>{S.off("154",r,this)})};S.on("154",r,this),ns()}else this.core.trtc.emit(U.AUTOPLAY_FAILED,{userId:"",mediaType:"audio",resume:()=>f(this,null,function*(){return i.play()})});else throw t})}update(i){return f(this,null,function*(){let{id:e,operation:t,seekFrom:r,playbackRate:s}=i;this.log.info(`update music source, ${JSON.stringify(i)}`);let n=this.mixedMusicMap.get(e);if(!n){this.log.warn(`update music source failed, music id: ${e} not found.`);return}n.updateSettings(i),n.updateListener(i),T(t)||n.setOperation(t),T(r)||n.seek(r),this.kvUpload(i)})}stop(e){return f(this,arguments,function*({id:i}){if(this.mixedMusicMap.has(i)){this.log.info(`remove music source, music id: ${i}`);let t=this.mixedMusicMap.get(i);t!=null&&t.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:t.mixInput.source.node,refId:`ax-${i}`}),t==null||t.stop(),this.mixedMusicMap.delete(i)}i==="*"&&this.destroyAllMusic()})}kvUpload(i){let{track:e,loop:t,volume:r,playbackRate:s,operation:n,seekFrom:a,onTimeUpdate:d,onDurationChange:l,onEnded:u}=i;e&&y.addCount({key:502009}),t&&y.addCount({key:502001}),r&&y.addCount({key:502002}),s&&y.addCount({key:502003}),n&&y.addCount({key:502004}),a&&y.addCount({key:502005}),typeof d!="function"&&y.addCount({key:502007}),typeof u!="function"&&y.addCount({key:502008}),typeof l!="function"&&y.addCount({key:502006})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((i,e)=>{i!=null&&i.mixInput.track&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:i.mixInput.track,refId:e}),this.stop({id:e})})}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}};c(wi,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(i,e,t){if(i.url&&i.url!=="*"){let r=i.url.split("?")[0],s=["mp3","ogg","wav","flac"],n=r.split(".").pop(),a=s.indexOf(n)>=0,d=r.startsWith("blob"),l=r.startsWith("data");if(!(a||d||l))throw new F({code:W.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new F({code:W.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});Rs("onTimeUpdate",i.onTimeUpdate),Rs("onEnded",i.onEnded),Rs("onDurationChange",i.onDurationChange)}}),c(wi,"updateValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},loop:{type:"boolean"},volume:{type:"number"},seekFrom:{type:"number"},operation:{type:"string",values:["pause","resume","stop"]}},validate(i,e,t){Rs("onTimeUpdate",i.onTimeUpdate),Rs("onEnded",i.onEnded),Rs("onDurationChange",i.onDurationChange)}}),c(wi,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),c(wi,"Name","AudioMixer");var _c=wi;var gc=0,Mh,dr=class dr{constructor(i){this.core=i;c(this,"log");c(this,"audioContext",Ee("denoiser"));c(this,"workletNode");c(this,"config",{enableFarFieldReduce:!1,farFieldReduceThreshold:.5});gc=gc+1,this.log=i.log.createChild({id:`${this.getAlias()}${gc}`}),this.log.info(`created id=${this.getAlias()}${gc}`)}static startValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0},mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}},validate(e,t,r,s){if(!i.room.audioManager.hasAudioTrack)throw new F({code:W.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return Mh||(Mh=this.doPreload(i)),Mh}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield tr(this.audioContext,t)}catch(r){throw this.log.error("load worklet failed",r),r}finally{URL.revokeObjectURL(t)}})}getName(){return dr.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser"}getValidateRule(i){switch(i){case"start":return dr.startValidateRule(this.core);case"update":return dr.updateValidateRule;case"stop":return dr.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e,schedule:t}=this.core,{assetsPath:r=this.core.assetsPath}=i;if(!r)throw new F({code:W.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload(`${r}/denoiser-wasm${cu()?"":"-nosimd"}.js`),!this.workletNode){let s=String(Date.now()).slice(0,-3),{auth:n,sign:a,status:d,message:l}=yield jS(t,w(M({},i),{timestamp:s}));if(!n)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${n}. Message: ${l}`),new F({code:W.INVALID_PARAMETER,message:l});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(i.sdkAppId),userId:i.userId,timestamp:s,sign:a,status:d}}),this.workletNode.port.onmessage=u=>{var p;let{data:h}=u;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}(${vo(new Date(h==null?void 0:h.maxCostTimestamp))}) hist: ${(p=h==null?void 0:h.hist)==null?void 0:p.join(" ")}`)}else h.type==="log"&&this.log[h.logLevel](`${h.value}`)}}this.updateConfig(i),this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(i){return f(this,null,function*(){this.updateConfig(i)})}stop(){return f(this,null,function*(){if(!this.workletNode)return;let{room:i}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield i.audioManager.removeDenoiser(this.workletNode)})}updateConfig(i){if(!this.workletNode)return;let e=!1;T(i.mode)||(i.mode===0?this.config.enableFarFieldReduce=!1:i.mode===1&&(this.config.enableFarFieldReduce=!0),e=!0),T(i.farFieldReduceThreshold)||(this.config.farFieldReduceThreshold=i.farFieldReduceThreshold,e=!0),e&&this.workletNode.port.postMessage({type:"setConfig",data:this.config})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};c(dr,"updateValidateRule",{type:"object",properties:{mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}}}),c(dr,"stopValidateRule",{type:"object"}),c(dr,"Name","AIDenoiser");var Tc=dr;function jS(s,n){return f(this,arguments,function*(o,{sdkAppId:i,userId:e,userSig:t,timestamp:r}){try{let{data:{errCode:a,errMsg:d,sign:l,status:u}}=yield o.getAbilityConfig(i,o.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:i,userId:e,userSig:t,timestamp:r});if(u==="1")return{auth:!0,sign:l,status:u,message:d};let h=Ut(i)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",p="Init RTCAIDenoiser failed.",m="";switch(a){case 1:m="Please check your params.";break;case 2:m=`You need to buy packages. Refer to: ${h}`;break;case 3:m="Server is invalid. Please contact our engineer. ";break;case 4:m=`Your packages is not active. Refer to: ${h}`;break;case 5:m=`Your packages is expired. Refer to: ${h}`;break;case 6:m="Your version is not supported.";break}return{auth:!1,status:u,message:d?`${p} Reason: ${d}. ${m}`:`${p}, ${m}`}}catch(a){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${a}`}}})}var Wf=Je(nt(),1);var Oh=class extends Wf.EventEmitter{constructor(){super();c(this,"observer");c(this,"state","nominal");this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return f(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!_e&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){se.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let t=this.stateNum,r=e[e.length-1];this.state=r.state,(this.stateNum>3||t>3)&&R.info(`${r.source}: ${r.state}`),this.emit("state-changed",{type:r.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(t){se.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},XS=new Oh,kh=XS;function Ph([o,i]){let e=i.byteLength,t=parseInt(String(e/255),10),r=e%255,s=[];s.push(0,0,0,1,6,o);for(let a=0;a<t;a++)s.push(255);s.push(r);let n=new DataView(i);return s.push(...new Uint8Array(n.buffer)),s.push(128),new sr(new DataView(new Uint8Array(s).buffer),!0)}function Lh(o){return o.type==="empty"||o.data.byteLength===0}function xh(o){return o.getInt32(0)===1&&o.getInt8(4)===6}function wh(o){let i=0,e=0,t=new DataView(o);for(let r=0;r<o.byteLength;r++)switch(t.getUint8(r)){case 0:i++;break;case 1:(i===2||i===3)&&e++,i=0;break;default:i=0;break}return e}function Uh({frame:o,seiMessageList:i}){if(!i||i.length===0||o.data.byteLength===0)return o;let t=9-wh(o.data);if(t<=0)return o;let r=i.splice(0,t).reverse().map(Ph),s=r.reduce((u,h)=>u+h.dataView.byteLength,0),n=new ArrayBuffer(s+o.data.byteLength),a=new DataView(n),d=new DataView(o.data),l=0;for(let u=0;u<r.length;u++)for(let h=0;h<r[u].dataView.byteLength;h++)a.setInt8(l++,r[u].dataView.getInt8(h));for(let u=0;u<o.data.byteLength;u++)a.setInt8(l++,d.getInt8(u));return o.data=n,o}function Vh({frame:o,onSEI:i}){try{let e=new DataView(o.data);if(Lh(o)||!xh(e))return o;let t=[],r=0,s=-1,n=-1;for(let a=0;a<o.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(s===-1?s=l:n===-1&&(n=l,t.push(new sr(new DataView(e.buffer.slice(s,n)))),s=l,n=-1),!(e.getUint8(a+1)===6)){o.data=e.buffer.slice(l);break}}r=0}else r=0}i==null||i(t.reverse())}catch(e){}return o}var Fh=0,jn=class jn{constructor(i){this.core=i;c(this,"log");c(this,"_seiMessageList",[]);c(this,"_smallSeiMessageList",[]);c(this,"_subStreamSeiMessageList",[]);Fh++,this.log=i.log.createChild({id:`${this.getAlias()}${Fh}`}),this.log.info(`[sei] created id=${this.getAlias()}${Fh}`),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 Uh({frame:i,seiMessageList:t})}catch(t){this.log.warn(t)}return i}decode({frame:i,track:e}){return Vh({frame:i,onSEI:t=>{t.forEach(r=>{this.core.trtc.emit(U.SEI_MESSAGE,{seiPayloadType:r.seiPayloadType,data:r.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"})})}})}destroy(){this.log.debug("destroy"),this.stop(),delete this.core}getValidateRule(i){switch(i){case"start":return{type:"object"};case"update":return{type:"object"};case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:pi?this.encode:Uh,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:pi?this.decode:Vh,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update({buffer:i,options:e}){var s;let t=[e.seiPayloadType,i],r=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(t):(this._seiMessageList.push(t),r&&this._smallSeiMessageList.push(t)),(s=this.core.room.scriptTransformWorker)==null||s.postMessage({type:"sei",data:t,isMain:!e.toSubStream,small:r})}getName(){return jn.Name}getAlias(){return"sei"}getGroup(){return"sei"}};c(jn,"autoStart",!0),c(jn,"Name","SEI");var Ec=jn;var zS=0,Sc,Xn=class Xn{constructor(i){this.core=i;c(this,"_core");c(this,"log");c(this,"dialog");this._core=i,this.log=i.log.createChild({id:`${this.getAlias()}${++zS}`}),this.log.info("created")}getName(){return Xn.Name}getAlias(){return"dm"}getGroup(){return"dm"}getValidateRule(i){switch(i){case"start":return{name:"StartDebugOptions",required:!1};case"update":return{name:"UpdateDebugOptions",required:!1};case"stop":return{name:"StopDebugOptions",required:!1}}}start(){return f(this,null,function*(){var e;!new URLSearchParams(location.search).has("trtcDebug")&&((e=window.sessionStorage)==null?void 0:e.getItem("TRTC_ENABLE_DEBUG_PLUGIN"))!=="true"||(yield this.openDebugDiaLog())})}update(e){return f(this,arguments,function*({visible:i}){i?yield this.openDebugDiaLog():this.closeDebugDiaLog()})}stop(){this.closeDebugDiaLog()}destroy(){this.stop()}openDebugDiaLog(){return f(this,null,function*(){var i;if(!this.dialog)try{if(Sc)yield Sc;else{let e=new URLSearchParams(location.search).get("trtcDebugDialogPath")||((i=window.sessionStorage)==null?void 0:i.getItem("TRTC_DEBUG_DIALOG_PATH"))||`https://unpkg.com/${Hf}@${He}/assets/debug-dialog.js`;Sc=this._core.fileDownloader.loadScript(e),yield Sc}this.dialog=new TRTCDebugDialog(this._core,this.log),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(e){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(e))}})}closeDebugDiaLog(){this.dialog&&(this.dialog.closeDialog(),this.dialog=null)}};c(Xn,"Name","Debug"),c(Xn,"autoStart",!0);var Ic=Xn;var Gf=o=>{switch(o){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},Ac=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:s}=i;this.config=t.config,this.trackDoneOB=de(e,j.INIT),this.stopOB=rt(),this.startOB=rt(),t.type==="auto"?this.type="webCodecs":this.type=t.type;let n=rt(),a=d=>{let l=this.pipe(e);return n.next("STARTING"),e.log.info(`decoder type: ${this.type}`),ce(l,ke(this.stopOB),Te(()=>{},u=>{e.log.error(u),r.addFailedEvent({key:Gf(this.type),error:u}),d>4?this.startOB.error(u):this.startOB.next(d+1)})),ce(l,or(1),hh(Un))};ce(this.startOB,xn(0),Mr(a),ke(this.stopOB),Te(()=>{e.player.setOutput(),n.next("STARTED")},d=>{n.next("FAILED")},()=>{r.addSuccessEvent({key:Gf(this.type)}),r.addSuccessEvent({key:504702})}))}mock(i){this._decodeSink?this._decodeSink.error(i):this.startOB.next(0)}close(i){this.stopOB.next(i)}pipe(i){return rr()(e=>f(this,null,function*(){this._decodeSink=e,e.defer(()=>{var r;(r=this.decoder)==null||r.close()});let{type:t}=this;try{switch(t){case"webCodecs":this.decoder=new AudioDecoder({error:r=>{i.log.error(r),e.error(4)},output:r=>{this.decodedFrameCount++,e.next(r),i.player.write(r)}});break;case"wasm":break}this.decoder.configure(this.config)}catch(r){i.log.error(r),e.error(t==="webCodecs"?2:6)}}))}decodeFrame(i){var e;this.inputFrameCount++,((e=this.decoder)==null?void 0:e.state)==="configured"&&this.decoder.decode(new EncodedAudioChunk({data:i.data,timestamp:i.timestamp,type:"key"}))}},QS={type:"object"},zn=class zn{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 zn.Name}getGroup(i){return i.track.userId+i.track.streamType}getName(){return zn.Name}getValidateRule(i){return QS}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 Ac(this.core,t,i);return ce(r.trackDoneOB,or(1),Te(()=>{this.core.clearStarted(this,this.getGroup(i)),this.stop({track:t})})),this.contextMap.set(t,r),r.decodeFrame(e)}}stop({track:i}){let e=this.contextMap.get(i);e&&(e.close("stop"),this.contextMap.delete(i),this.contextMap.size===0&&this.core.room.audioManager.removeDecodeProcessor({type:3}))}update(i){let e=this.contextMap.get(i.track);if(e){if(i.type==="mock"){e.mock(10);return}e.close("update"),this.contextMap.set(i.track,new Ac(this.core,i.track,i))}}};c(zn,"Name","TRTCAudioDecoder");var Qn=zn;var Cc=class{constructor(){c(this,"log");this.log=R.createLogger({id:"exp"})}call(i,e){return f(this,null,function*(){return le(this[i])?this[i](e):Promise.reject(new v({code:I.INVALID_PARAMETER,message:$({key:B.API_NOT_EXIST,data:{name:i}})}))})}enableAudioFrameEvent(i){return f(this,null,function*(){let{trtcInstance:e,enable:t,userId:r,sampleRate:s=48e3,channelCount:n=1,port:a}=i,{audioManager:d}=e.room,{getPCMAbortCtrlMap:l,audioFrameEventConfigMap:u}=d;if(u.set(r,{enable:t,sampleRate:s,channelCount:n,port:a}),t)if(r==="*")e.room.remotePublishedUserMap.forEach(h=>{if(h.remoteAudioTrack.isAvailable){if(l.get(h.userId))return;let p=d.getPCM(m=>{e.emit(U.AUDIO_FRAME,m)},h.userId);l.set(h.userId,p)}});else{if(l.get(r))return;let h=d.getPCM(p=>{e.emit(U.AUDIO_FRAME,p)},r);l.set(r,h)}else if(r==="*")e.room.remotePublishedUserMap.forEach(h=>{if(h.remoteAudioTrack.isSubscribed){let{userId:p}=h,m=l.get(p);m==null||m.abort("disable"),l.delete(p)}});else{let h=l.get(r);h==null||h.abort("disable"),l.delete(r)}})}resumeRemotePlayer(i){return f(this,null,function*(){if(i.userId==="*"){let t=[];return i.trtcInstance.room.remotePublishedUserMap.forEach(r=>{let{remoteAudioTrack:s,remoteVideoTrack:n,remoteAuxiliaryTrack:a}=r;i.streamType?i.streamType==="main"?(s.isAvailable&&t.push(s.player.resume()),n.isAvailable&&t.push(n.player.resume())):a.isAvailable&&t.push(a.player.resume()):(s.isAvailable&&t.push(s.player.resume()),n.isAvailable&&t.push(n.player.resume()),a.isAvailable&&t.push(a.player.resume()))}),Promise.all(t)}let e=i.trtcInstance.room.remotePublishedUserMap.get(i.userId);if(e)return i.streamType==="main"?Promise.all([e.remoteAudioTrack.player.resume(),e.remoteVideoTrack.player.resume()]):e.remoteAuxiliaryTrack.player.resume()})}pauseRemotePlayer(i){if(i.userId==="*")i.trtcInstance.room.remotePublishedUserMap.forEach(e=>{let{remoteAudioTrack:t,remoteVideoTrack:r,remoteAuxiliaryTrack:s}=e;i.streamType?i.streamType==="main"?(t.isAvailable&&t.player.pause(),r.isAvailable&&r.player.pause()):s.isAvailable&&s.player.pause():(t.isAvailable&&t.player.pause(),r.isAvailable&&r.player.pause(),s.isAvailable&&s.player.pause())});else{let e=i.trtcInstance.room.remotePublishedUserMap.get(i.userId);e&&(i.streamType==="main"?(e.remoteAudioTrack.player.pause(),e.remoteVideoTrack.player.pause()):e.remoteAuxiliaryTrack.player.pause())}}};D([_f({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"}}})],Cc.prototype,"enableAudioFrameEvent",1);var Jf=new Cc;var qf=Je(nt(),1);var Bh=class extends qf.EventEmitter{constructor(){super();c(this,"states",{});c(this,"permissionChangeHandler");c(this,"log");this.log=R.createLogger({id:"pm"}),this.permissionChangeHandler=()=>{var e,t;this.emit("permission-state-change",{camera:(e=this.states.camera)==null?void 0:e.state,microphone:(t=this.states.microphone)==null?void 0:t.state})}}request(e){return f(this,null,function*(){if(this.log.info(`request ${e.join(", ")}`),e.length===0)return Promise.resolve();(yield navigator.mediaDevices.getUserMedia({video:e.includes("camera"),audio:e.includes("microphone")})).getTracks().forEach(r=>r.stop())})}get(e){return f(this,null,function*(){try{return this.states[e]||(this.states[e]=yield navigator.permissions.query({name:e}),this.states[e].addEventListener("change",this.permissionChangeHandler)),this.log.info(`get ${e} permission state: ${this.states[e].state}`),this.states[e].state}catch(t){return this.log.error(`get ${e} permission failed, error: ${t instanceof Error?t.message:t}`),null}})}destroy(){Object.values(this.states).forEach(e=>{e==null||e.removeEventListener("change",this.permissionChangeHandler)}),this.states={}}},Yn=new Bh;var jf=0,Zn=new Set,ze=null;Wc(bh);es.checkStorage();var q=class q extends Xf.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",R.createLogger({id:`t${++jf}`}));c(this,"_plugins",new Map);c(this,"_networkQuality",null);c(this,"_speakerId");c(this,"enterRoomParams");c(this,"_enableAutoSwitchWhenRecapturing",!0);this._room=new e(M({logger:this._log,frameWorkType:q.frameWorkType},t)),this._room.videoDecodeFallbackType=t.videoDecodeFallback,ue(t.enableAutoSwitchWhenRecapturing)&&(this._enableAutoSwitchWhenRecapturing=t.enableAutoSwitchWhenRecapturing),this._log.info(`create() ${JSON.stringify(t,(r,s)=>r==="plugins"?s.map(n=>n.Name):s)}`),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(r){return this._room.audioManager.dump(r)}}}),t.plugins&&t.plugins.forEach(r=>{this._use(r,t.assetsPath)}),this._use(_c,t.assetsPath),this._use(pc,t.assetsPath),this._use(Tc,t.assetsPath),this._use(Qn,t.assetsPath),this._use(Ic),t.enableSEI&&Tn&&this._use(Ec),this._room.on("audio-volume",r=>{var s,n;!r.find(a=>a.userId==="")&&this._localAudioTrack&&r.push({userId:"",volume:Math.floor(((s=this._localAudioTrack.getInternalAudioLevelAfter3A())!=null?s:this._localAudioTrack.getAudioLevel())*100),floatVolume:(n=this._localAudioTrack.getInternalAudioLevelAfter3A())!=null?n:this._localAudioTrack.getInternalAudioLevel()}),t.volumeType===1&&r.forEach(a=>{var l;let d=a.userId===""?this._localAudioTrack:(l=this.room.remotePublishedUserMap.get(a.userId))==null?void 0:l.remoteAudioTrack;d&&(a.volume=d.dbVolume)}),t.enableDbVolume&&r.forEach(a=>{var l;let d=a.userId===""?this._localAudioTrack:(l=this.room.remotePublishedUserMap.get(a.userId))==null?void 0:l.remoteAudioTrack;d&&(a.volume=d.dbVolume)}),this.emit(U.AUDIO_VOLUME,{result:r.sort((a,d)=>d.volume-a.volume)})}),this._room.videoManager.on("error",r=>{this._log.error(new F({code:W.OPERATION_FAILED,extraCode:5504,message:r.message,originError:r}))}),this._listenEvents(),this._initActiveSpeaker(),Uf(this,"trtc")}static create(e){}static _create(e,t){Ef();let r=new q(e,t||{});return Zn.add(r),r.__v_skip=!0,r}get room(){return this._room}_listenEvents(){tt(this,this._room).add("peer-join",e=>{let{userId:t}=e;this.emit(U.REMOTE_USER_ENTER,{userId:t})}).add("peer-leave",e=>{this.emit(U.REMOTE_USER_EXIT,{userId:e})}).add("banned",e=>{xt(!0),this._exitRoom().finally(()=>{this.emit(U.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().finally(()=>{this.emit(U.ERROR,F.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(U.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let t=w(M({},e),{uplinkRTT:Math.min(e.uplinkRTT,Hs),downlinkRTT:Math.min(e.downlinkRTT,Hs)});this.emit(U.NETWORK_QUALITY,t)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(r=>{tt(r,r).add("player-state-changed",s=>{let n=w(M({},s),{userId:e.userId});r.kind===_.VIDEO&&(n.streamType=Li(r.streamType)),this.emit(r.kind===_.AUDIO?U.AUDIO_PLAY_STATE_CHANGED:U.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",s=>{s.getCode()===I.PLAY_NOT_ALLOWED&&this.emit(U.AUTOPLAY_FAILED,{userId:r.userId,mediaType:r.strMediaType,resume:()=>r.player.resume()})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(r=>{we(r)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:t})=>{let{userId:r}=t,s=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?U.REMOTE_VIDEO_AVAILABLE:U.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"main"})),s!==a&&(a?this._onAudioAvailable({userId:r}):this._onAudioUnavailable({userId:r,muteState:t}),this.emit(a?U.REMOTE_AUDIO_AVAILABLE:U.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?U.REMOTE_VIDEO_AVAILABLE:U.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"sub"}))}).add("sei-message",e=>{this.emit(U.SEI_MESSAGE,w(M({},e),{streamType:Li(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(U.ERROR,new F({code:W.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var s,n,a,d,l,u,h;let t={2:"big",3:"small",7:"sub"},r={rtt:Math.min(e.msg_up_stream_info.msg_network_status.uint32_rtt||((s=e.msg_down_stream_info[0])==null?void 0:s.msg_network_status.uint32_rtt)||((n=this._networkQuality)==null?void 0:n.uplinkRTT)||((a=this._networkQuality)==null?void 0:a.downlinkRTT)||0,Hs),upLoss:((d=this._networkQuality)==null?void 0:d.uplinkLoss)||0,downLoss:((l=this._networkQuality)==null?void 0:l.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((u=e.msg_up_stream_info.msg_audio_status)==null?void 0:u.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((h=e.msg_up_stream_info.msg_audio_status)==null?void 0:h.uint32_audio_level)||0)/Dt},video:e.msg_up_stream_info.msg_video_status.filter(p=>t[p.uint32_video_stream_type]).map(p=>({bitrate:(p.uint32_video_codec_bitrate||0)/1e3,width:p.uint32_video_width,height:p.uint32_video_height,frameRate:p.uint32_video_enc_fps,videoType:t[p.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(p=>({userId:p.msg_user_info.str_identifier,audio:{bitrate:(p.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(p.msg_audio_status.uint32_audio_level||0)/Dt,point2pointDelay:(p.msg_audio_status.uint32_audio_p2p_delay||0)+(p.msg_audio_status.uint32_audio_cache_ms||0),jitterBufferDelay:p.msg_audio_status.uint32_audio_cache_ms||0},video:p.msg_video_status.map(m=>({bitrate:(m.uint32_video_codec_bitrate||0)/1e3,width:m.uint32_video_width,height:m.uint32_video_height,frameRate:m.uint32_video_dec_fps,videoType:t[m.uint32_video_stream_type],point2pointDelay:(m.uint32_video_p2p_delay||0)+(m.uint32_video_cache_ms||0),jitterBufferDelay:m.uint32_video_cache_ms||0,codec:m.uint32_video_codec}))}))};this.emit(U.STATISTICS,r)}).add("custom-message",e=>{this.emit(U.CUSTOM_MESSAGE,e)}).add("layerData",e=>this.emit(U.LAYER_DATA,e)).add("first-video-frame",e=>{this.emit(U.FIRST_VIDEO_FRAME,w(M({},e),{streamType:Li(e.streamType)}))}).add("audio-frame",e=>{this.emit(U.AUDIO_FRAME,e)}),tt(this,be).add("audioInputAdded",e=>{this.emit(U.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(U.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(U.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(U.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>f(this,null,function*(){if(this.emit(U.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),ze&&ze.deviceId===Bs){let t=(yield vr()).find(r=>r.deviceId===Bs);t&&ze.groupId!==t.groupId&&(ze=t,this.emit(U.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}})).add("audioOutputRemoved",e=>f(this,null,function*(){this.emit(U.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield vr())[0];if(!t||!ze||ze.groupId===t.groupId)return;let r=ze.deviceId===e.deviceId,s=ze.deviceId===Bs&&ze.deviceId===t.deviceId;(r||s)&&(ze=t,this.emit(U.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))})),tt(this,Yn).add("permission-state-change",e=>{this.emit(U.PERMISSION_STATE_CHANGE,e)}),this.room.enableSEI&&this.on(U.SEI_MESSAGE,e=>{var r;let t=(r=this.room.remotePublishedUserMap.get(e.userId))==null?void 0:r.remoteVideoTrack;t&&t.updateAlphaRenderInfo(e)})}getNetworkTime(){return Hi()}use(e){let t,r;return"plugin"in e?(t=e.plugin,r=e.assetsPath):t=e,t.Name==="Chorus"&&(this.room.enableChorus=!0),this._use(t,r)}_use(e,t){let r=this._plugins.get(e.Name);if(r)return this._log.warn("duplicate install plugin",e.Name),r;let s=new e(wf.call(this,{TRTC:q,room:this._room,assetsPath:t,errorModule:{RtcError:F,ErrorCode:W,CoreErrorCode:I,ErrorCodeDictionary:Lt}}));return this._plugins.set(e.Name,s),s.__v_skip=!0,e.autoStart&&this.startPlugin(e.Name),s}enterRoom(e){return f(this,null,function*(){var d,l;this.enterRoomParams=e;let{scene:t="rtc",enableAutoPlayDialog:r=!0,autoReceiveAudio:s=!0,autoReceiveVideo:n=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!ie(e.proxy)&&e.proxy.turnServer&&((l=(d=this._room).setTurnServer)==null||l.call(d,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=r,this._room.autoReceiveAudio=s,this._room.autoReceiveVideo=n,ue(e.preferHW)&&(this._room.preferHW=e.preferHW),e.playoutDelay&&(this._room.playoutDelay=e.playoutDelay),e.jitterBufferDelay&&(this._room.jitterBufferDelay=e.jitterBufferDelay);let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:e.role==="audience"?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language,priority:e.priority,useVp8:e.useVp8,useH265:e.useH265||!1,keepAlive:e.keepAlive};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(a,t,q.frameWorkType),this._checkTrackToPublish(),kh.start()})}exitRoom(){return f(this,null,function*(){return yield this._exitRoom()})}switchRoom(e){return f(this,null,function*(){if(this.room.isSwitchRoomSupported())try{this._clearRemoteTracks(),yield this._room.switchRoom(e)}catch(t){if(t instanceof Ps&&(t.code===I.API_CALL_TIMEOUT||t.code===I.SWITCH_ROOM_FAILED))this._log.warn(`switchRoom ${t.code===I.API_CALL_TIMEOUT?"timeout":"failed"}, fallback to exitRoom() and enterRoom()`),yield this._rejoinRoom(e);else throw t}else yield this._rejoinRoom(e)})}_rejoinRoom(e){return f(this,null,function*(){yield this.exitRoom();let t=M(M({},this.enterRoomParams),e);yield this.enterRoom(t)})}_clearRemoteTracks(){new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(e=>{this._stopRemoteAudio({userId:e}).catch(()=>{})}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let t=e.includes("main")?"main":"sub",r=e.split(`_${t}`)[0];r&&this._stopRemoteVideo({userId:r,streamType:t}).catch(()=>{})}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),Vf(this),this._room.remotePublishedUserMap.forEach(e=>{we(e.remoteAudioTrack),we(e.remoteVideoTrack),we(e.remoteAuxiliaryTrack)})}switchRole(e,t){return f(this,null,function*(){t!=null&&t.privateMapKey&&(this._room.privateMapKey=t.privateMapKey),t!=null&&t.latencyLevel&&(this._room.latencyLevel=t.latencyLevel),yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){this._plugins.forEach(e=>{var t;return(t=e.destroy)==null?void 0:t.call(e)}),this._plugins.clear(),we(this),this.removeAllListeners(),this._room.destroy(),Zn.delete(this),Zn.size===0&&kh.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),S.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return f(this,arguments,function*(e={publish:!0}){if(this._localAudioTrack){this._log.warn("local audio is already started");return}let{publish:t=!0,mute:r,option:s}=e,n=new kt(this._room.audioManager),a={},d={muted:!0};s&&(T(s.microphoneId)?T(s.audioTrack)||(a.customSource=s.audioTrack):a.deviceId=s.microphoneId,s&&Q(s.captureVolume)&&n.setCaptureVolume(s.captureVolume),T(s.profile)||(ie(s.profile)?pa[s.profile]&&n.setProfile(pa[s.profile]):n.setProfile(s.profile)),Q(s.earMonitorVolume)&&(d.muted=!(s.earMonitorVolume>0),d.volume=s.earMonitorVolume),T(s.echoCancellation)||(n.profile.echoCancellation=s.echoCancellation),T(s.noiseSuppression)||(n.profile.noiseSuppression=s.noiseSuppression),T(s.autoGainControl)||(n.profile.autoGainControl=s.autoGainControl),ue(this._enableAutoSwitchWhenRecapturing)&&(n.enableAutoSwitchWhenRecapturing=this._enableAutoSwitchWhenRecapturing)),n.on("5",l=>{this.emit(U.ERROR,new F({code:W.DEVICE_ERROR,extraCode:5309,messageParams:{error:l}}))}),n.on("2",l=>{this.emit(U.DEVICE_CHANGED,{type:"microphone",action:"active",device:l})}),n.on("4",l=>{let u;l.error&&(u=F.convertFrom(l.error)),this.emit(U.PUBLISH_STATE_CHANGED,w(M({},l),{error:u}))}),n.on("6",()=>{}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId),yield n.capture(a),T(r)||n.setMute(r),tt(n,n).add("player-state-changed",l=>{this.emit(U.AUDIO_PLAY_STATE_CHANGED,w(M({},l),{userId:""}))}),t&&this._room.isJoined&&this._room.publish(n).catch(()=>{}),this._localAudioTrack=n,this._localAudioConfig=w(M({},e),{publish:t}),yield this._updateAudioPlayOption({playOption:d,track:n}),S.emit("113",{userId:"",room:this.room})})}updateLocalAudio(e){return f(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:r,option:s}=e,n={};s&&(s.microphoneId?yield this._localAudioTrack.switchDevice(s.microphoneId):T(s.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(s.audioTrack)),T(s.captureVolume)||this._localAudioTrack.setCaptureVolume(s.captureVolume),T(s.earMonitorVolume)||(n.muted=!(s.earMonitorVolume>0),n.volume=s.earMonitorVolume),yield this._localAudioTrack.update3A(s)),this._room.isJoined&&!T(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),T(r)||this._localAudioTrack.setMute(r),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),ei(this._localAudioConfig,e)})}stopLocalAudio(){return f(this,null,function*(){this._localAudioTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),S.emit("114",{userId:"",room:this.room}),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),we(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)})}startLocalVideo(){return f(this,arguments,function*(e={publish:!0,view:null,capture:!0}){var h;if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:t,publish:r=!0,capture:s=!0,mute:n,option:a}=e,d=new je(this._room.videoManager),l={},u={};a&&(ue(a.avoidCropping)&&(d.avoidCropping=a.avoidCropping),a.cameraId?l.deviceId=a.cameraId:T(a.useFrontCamera)?T(a.videoTrack)||(l.customSource=a.videoTrack):l.facingMode=a.useFrontCamera?_.FACING_MODE_USER:_.FACING_MODE_ENVIRONMENT,T(a.retryWhenExactFailed)||(l.retryWhenExactFailed=a.retryWhenExactFailed),a.qosPreference&&(l.contentHint=Gn(a.qosPreference)),T(a.profile)||(ie(a.profile)?zt[a.profile]&&d.setProfile(zt[a.profile]):d.setProfile(a.profile)),T(a.fillMode)||(u.objectFit=a.fillMode),T(a.mirror)||(u.mirror=a.mirror),T(a.small)||(T(a.smallMode)||(this._room.smallMode=a.smallMode),ue(a.small)&&a.small===!1?d.stopSmall():d.updateSmallConfig(Ss(a.small,!0))),T(a.rotation)||d.setRotation(a.rotation),ue(this._enableAutoSwitchWhenRecapturing)&&(d.enableAutoSwitchWhenRecapturing=this._enableAutoSwitchWhenRecapturing)),d.once("first-video-frame",p=>{this.emit(U.FIRST_VIDEO_FRAME,w(M({},p),{streamType:Li(p.streamType)}))}),d.on("5",p=>{this.emit(U.ERROR,new F({code:W.DEVICE_ERROR,extraCode:5308,messageParams:{error:p}}))}),d.on("2",p=>{this.emit(U.DEVICE_CHANGED,{type:"camera",action:"active",device:p})}),d.on("4",p=>{let m;p.error&&(m=F.convertFrom(p.error)),this.emit(U.PUBLISH_STATE_CHANGED,w(M({},p),{error:m}))}),d.on("6",()=>{}),this._listenOutputTrackChanged(d),s?yield d.capture(l):(h=d.manager)==null||h.changeInput(d),T(n)||(yield d.setMute(n)),tt(d,d).add("player-state-changed",p=>{this.emit(U.VIDEO_PLAY_STATE_CHANGED,w(M({},p),{userId:"",streamType:"main"}))}).add("video-size-changed",p=>{this.emit(U.VIDEO_SIZE_CHANGED,w(M({},p),{streamType:Li(p.streamType)}))}),r&&this._room.isJoined&&this._room.publish(d).catch(()=>{}),this._localVideoTrack=d,this._localVideoConfig=w(M({},e),{view:t,publish:r,capture:s}),yield this._updateVideoPlayOption({view:t,playOption:u,track:d})})}updateLocalVideo(e){return f(this,null,function*(){var l,u,h;if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:r,mute:s,capture:n,option:a}=e,d={};if(this._localVideoConfig.capture)n!==!1?a!=null&&a.cameraId?yield this._localVideoTrack.switchDevice(a==null?void 0:a.cameraId):T(a==null?void 0:a.useFrontCamera)?T(a==null?void 0:a.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(a==null?void 0:a.videoTrack)):yield this._localVideoTrack.switchDevice(a!=null&&a.useFrontCamera?_.FACING_MODE_USER:_.FACING_MODE_ENVIRONMENT):this._localVideoTrack.stopCapture();else if(n){let p={};p.deviceId=(a==null?void 0:a.cameraId)||((l=this._localVideoConfig.option)==null?void 0:l.cameraId),p.facingMode=a!=null&&a.useFrontCamera||(u=this._localVideoConfig.option)!=null&&u.useFrontCamera?_.FACING_MODE_USER:_.FACING_MODE_ENVIRONMENT,p.customSource=(a==null?void 0:a.videoTrack)||((h=this._localVideoConfig.option)==null?void 0:h.videoTrack),yield this._localVideoTrack.capture(p)}a&&(T(a.profile)||(ie(a.profile)?zt[a.profile]&&this._localVideoTrack.setProfile(zt[a.profile]):this._localVideoTrack.setProfile(a.profile),(!a.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(a.cameraId))&&T(a.useFrontCamera)&&(yield this._localVideoTrack.applyProfile())),T(a.fillMode)||(d.objectFit=a.fillMode),T(a.mirror)||(d.mirror=a.mirror),T(a.rotation)||this._localVideoTrack.setRotation(a.rotation),a.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(Gn(a.qosPreference)),T(a.small)||(ue(a.small)&&!a.small?this._localVideoTrack.stopSmall():this._localVideoTrack.updateSmallConfig(Ss(a.small,!0)))),this._room.isJoined&&T(r)&&this._localVideoConfig.publish&&n&&!this._localVideoConfig.capture&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._room.isJoined&&((r!=null?r:this._localVideoConfig.publish)?this._room.publish(this._localVideoTrack).catch(()=>{}):this._room.unpublish(this._localVideoTrack).catch(()=>{})),T(s)||(yield this._localVideoTrack.setMute(s)),yield this._updateVideoPlayOption({view:t,playOption:d,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),ei(this._localVideoConfig,e)})}stopLocalVideo(){return f(this,null,function*(){this._localVideoTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),we(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return f(this,arguments,function*(e={publish:!0,view:null}){var p,m;if(this._localScreenTrack){this._log.warn("screen share is already started");return}let{view:t=null,publish:r=!0,muteSystemAudio:s,option:n}=e,a=new Pt(this._room.videoManager);a.on("4",g=>{let E;g.error&&(E=F.convertFrom(g.error)),this.emit(U.PUBLISH_STATE_CHANGED,w(M({},g),{error:E}))}),a.once("first-video-frame",g=>{this.emit(U.FIRST_VIDEO_FRAME,w(M({},g),{streamType:Li(g.streamType)}))}),this._listenOutputTrackChanged(a),e.streamType==="main"&&(a.mediaType=4);let d=null,l={},u={};n&&(T(n.profile)||(ie(n.profile)?fa[n.profile]&&a.setProfile(fa[n.profile]):a.setProfile(n.profile)),n.systemAudio&&(l.systemAudio=!0,l.echoCancellation=n.echoCancellation,l.noiseSuppression=n.noiseSuppression,l.autoGainControl=n.autoGainControl),T(n.fillMode)||(u.objectFit=n.fillMode),n.videoTrack&&(l.videoTrack=n.videoTrack),n.audioTrack&&(l.audioTrack=n.audioTrack),n.captureElement&&(l.captureElement=n.captureElement),n.preferDisplaySurface&&(l.preferDisplaySurface=n.preferDisplaySurface),n.qosPreference&&(l.contentHint=Gn(n.qosPreference)));let h=yield a.capture(l);if(a.mediaTrack.addEventListener(_.ENDED,()=>{this._stopScreenShare(),this.emit(U.SCREEN_SHARE_STOPPED)}),h.getAudioTracks()[0]){d=new To(this._room.audioManager);let g=h.getAudioTracks()[0];(p=e.option)!=null&&p.systemAudio&&!((m=e.option)!=null&&m.audioTrack)&&(d.sourceTrack=g),yield d.setInputMediaStreamTrack(g),ue(s)&&d.mediaTrack&&(d.mediaTrack.enabled=!s),this._speakerId&&d.setAudioOutput(this._speakerId)}if(tt(a,a).add("player-state-changed",g=>{this.emit(U.VIDEO_PLAY_STATE_CHANGED,w(M({},g),{userId:"",streamType:"sub"}))}),r&&this._room.isJoined){let g=[a];d&&(g.push(d),this._checkScreenAudioEchoCancellation(a,d)),g.forEach(E=>this._room.publish(E).catch(()=>{}))}this._localScreenTrack=a,this._localScreenAudioTrack=d,this._localScreenConfig=w(M({},e),{view:t,publish:r}),yield this._updateVideoPlayOption({view:t,playOption:u,track:a})})}updateScreenShare(e){return f(this,null,function*(){var d;if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:r,muteSystemAudio:s,option:n}=e,a={};if(n&&(T(n.fillMode)||(a.objectFit=n.fillMode),n.qosPreference)){let l=Gn(n.qosPreference);this._localScreenTrack.setContentHint(l)}if(this._room.isJoined&&!T(r)){if(r&&!this._localScreenConfig.publish){let l=[this._localScreenTrack];this._localScreenAudioTrack&&l.push(this._localScreenAudioTrack),l.forEach(u=>this._room.publish(u).catch(()=>{}))}if(this._localScreenConfig.publish&&!r){let l=[this._localScreenTrack];this._localScreenAudioTrack&&l.push(this._localScreenAudioTrack),l.forEach(u=>this._room.unpublish(u).catch(()=>{}))}}(d=this._localScreenAudioTrack)!=null&&d.mediaTrack&&ue(s)&&(this._localScreenAudioTrack.mediaTrack.enabled=!s),yield this._updateVideoPlayOption({view:t,playOption:a,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),ei(this._localScreenConfig,e)})}stopScreenShare(){return f(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return f(this,null,function*(){let{view:t,userId:r,streamType:s,option:n}=e,a=`${r}_${s}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${r}, streamType:${s}`);return}let d=this._room.remotePublishedUserMap.get(r);if(!d)return;let l={},u=s==="main"?d.remoteVideoTrack:d.remoteAuxiliaryTrack;u.on("decode-failed",h=>{this.emit(U.ERROR,new F({code:W.OPERATION_FAILED,extraCode:5507,message:"video decode failed"}))}),u.on("video-size-changed",h=>{this.emit(U.VIDEO_SIZE_CHANGED,w(M({},h),{streamType:Li(h.streamType)}))}),this._listenOutputTrackChanged(u),n&&(T(n.fillMode)||(l.objectFit=n.fillMode),T(n.mirror)||(l.mirror=n.mirror),T(n.poster)||(l.poster=n.poster),l.canvasRender=n.canvasRender,s==="main"&&!T(n.small)&&(!d.remoteVideoTrack.isSubscribing&&!d.remoteVideoTrack.isSubscribed&&d.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,u.user)),T(n.draggable)||u.setDraggable(n.draggable)),yield this._room.subscribe(u),yield this._enableVideoDecodeFallback(u,s),yield this._updateVideoPlayOption({view:t,playOption:l,track:u}),this._emitTrackEvent(u),this._remoteVideoConfigMap.set(a,{config:e}),n&&!T(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:u,view:t,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:n==null?void 0:n.viewRoot})})}updateRemoteVideo(e){return f(this,null,function*(){var P,re;let{view:t,userId:r,streamType:s,option:n,mute:a}=e,d=`${r}_${s}`,l=this._remoteVideoConfigMap.get(d);if(!l||!this._room.remotePublishedUserMap.has(r))return;let u={};n&&(T(n.fillMode)||(u.objectFit=n.fillMode),T(n.mirror)||(u.mirror=n.mirror));let h=null,p=this._room.remotePublishedUserMap.get(r);if(s==="main"&&(p!=null&&p.muteState.hasVideo)&&(h=p.remoteVideoTrack),s==="sub"&&(p!=null&&p.muteState.hasAuxiliary)&&(h=p.remoteAuxiliaryTrack),!h)return;let{config:m}=l;s==="main"&&n&&!T(n.small)&&this._room.changeType(n.small,h.user),n&&!T(n.draggable)&&h.setDraggable(n.draggable),ue(a)&&(h.ignoreUpdatePlayingState=!0,a?(yield h.player.pause(),yield this.room.unsubscribe(h)):(yield this.room.subscribe(h),yield h.player.resume())),yield this._updateVideoPlayOption({view:t,playOption:u,track:h,prevConfig:m}),ei(m,e);let g=T(n==null?void 0:n.receiveWhenViewVisible)?(P=m.option)==null?void 0:P.receiveWhenViewVisible:n.receiveWhenViewVisible,E=T(t)?m.view:t,C=T(n==null?void 0:n.viewRoot)?(re=m.option)==null?void 0:re.viewRoot:n.viewRoot;this._observeView({remoteTrack:h,view:E,receiveWhenViewVisible:g,viewRoot:C})})}stopRemoteVideo(e){return f(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,t=!0){return f(this,null,function*(){let r=[],s=this._room.remotePublishedUserMap.get(e.userId);if(s){let{muteState:n,remoteVideoTrack:a,remoteAuxiliaryTrack:d}=s;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&&(delete n.ignoreUpdatePlayingState,yield this._room.unsubscribe(n),this._mediaTrackMap.delete(n.outMediaTrack));this._removeRemoteVideoConfig(e.userId,e.streamType)})}_removeRemoteVideoConfig(e,t){let r=`${e}_${t}`,s=this._remoteVideoConfigMap.get(r);s&&s.observer&&s.observer.disconnect(),this._remoteVideoConfigMap.delete(r)}muteRemoteAudio(e,t){return f(this,null,function*(){this._remoteAudioMuteMap.set(e,t);try{if(e==="*")if(t)yield this._stopRemoteAudio({userId:e});else{let r=[...this._room.remotePublishedUserMap.values()];for(let s of r)s.muteState.hasAudio&&!this._remoteAudioConfigMap.has(s.userId)&&(yield this._startRemoteAudio({userId:s.userId}))}else t?yield this._stopRemoteAudio({userId:e}):this._remoteAudioConfigMap.has(e)||(yield this._startRemoteAudio({userId:e}))}catch(r){throw r.code!==W.OPERATION_ABORT&&this._remoteAudioMuteMap.delete(e),r}})}setRemoteAudioVolume(e,t){if(e==="*"){this._remoteAudioVolumeMap.set("*",t),this._remoteAudioVolumeMap.forEach((s,n)=>this._remoteAudioVolumeMap.set(n,t));let r=[...this._room.remotePublishedUserMap.values()];for(let s of r)this._remoteAudioVolumeMap.set(s.userId,t),s.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:s.remoteAudioTrack})}else if(e){let r=this._room.remotePublishedUserMap.get(e);this._remoteAudioVolumeMap.set(e,t),r&&r.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:r.remoteAudioTrack})}}startPlugin(e,t){return f(this,null,function*(){return e.start(t)})}updatePlugin(e,t){return f(this,null,function*(){return e.update(t)})}stopPlugin(e,t){return f(this,null,function*(){return e.stop(t)})}enableAudioVolumeEvaluation(e=2e3,t=!1){this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,r){if(this.listeners(e).includes(t))return this;if(this._log.debug("on",e),super.on(e,t,r),this._eventListened.add(e),this.listeners(U.AUDIO_FRAME).length>0){let{audioFrameEventConfigMap:s}=this.room.audioManager;s.get("")||s.set("",{enable:!0}),this._localAudioTrack&&this.room.audioManager.handleLocalTrackStarted({userId:"",room:this.room})}return this}emit(e,...t){try{Mf.has(e)||this._log.debug(`emit ${e} ${JSON.stringify(t)}`)}catch(r){}return super.emit(e,...t)}off(e,t,r){if(this._log.debug("off",e),e==="*"?(this._eventListened.clear(),this.removeAllListeners()):super.off(e,t,r),(e===q.EVENT.AUDIO_FRAME||e==="*")&&this.listeners(q.EVENT.AUDIO_FRAME).length===0){let{getPCMAbortCtrlMap:s}=this.room.audioManager;s.forEach(n=>{n==null||n.abort("off")}),s.clear()}return this}getAudioTrack(e={userId:"",streamType:"main"}){let t,r=null,s="main",n=!1;if(ie(e)?t=e:(t=e.userId,n=e.processed===!0,e.streamType&&(s=e.streamType)),t){let a=this._room.remotePublishedUserMap.get(t);a&&(r=a.remoteAudioTrack)}else r=s==="sub"?this._localScreenAudioTrack:this._localAudioTrack;return r?n&&r.outMediaTrack&&r.outMediaTrack!==r.mediaTrack?r.outMediaTrack.clone():r.mediaTrack:null}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:t="",streamType:r="main",processed:s=!1}=e,n=null;if(t==="")r==="main"&&this._localVideoTrack&&(n=this._localVideoTrack),r==="sub"&&this._localScreenTrack&&(n=this._localScreenTrack);else{let a=this._room.remotePublishedUserMap.get(t);a&&(n=r==="main"?a.remoteVideoTrack:a.remoteAuxiliaryTrack)}return n?s&&n.outMediaTrack&&n.outMediaTrack!==n.mediaTrack?n.outMediaTrack.clone():n.mediaTrack:null}getVideoSnapshot(e={}){let{userId:t,streamType:r="main"}=e;if(t){let s=this._room.remotePublishedUserMap.get(t);if(r==="main"&&(s!=null&&s.muteState.hasVideo))return s.remoteVideoTrack.getVideoFrame();if(r==="sub"&&(s!=null&&s.muteState.hasAuxiliary))return s.remoteAuxiliaryTrack.getVideoFrame()}else{if(r==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(r==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(e){var t,r;this._speakerId=e,(t=this._localAudioTrack)==null||t.setAudioOutput(e),(r=this._localScreenAudioTrack)==null||r.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(s=>s.remoteAudioTrack.setAudioOutput(e))}setCurrentSpeaker(e){return f(this,null,function*(){(yield vr()).forEach(r=>{r.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(U.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}),ze=r)}),this._log.warn(`the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: ${_t}/en/TRTC.html#.setCurrentSpeaker`)})}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return f(this,null,function*(){var a;let{userId:t}=e;if(this._remoteAudioConfigMap.has(t)){this._log.warn(`remote audio has already started. userId:${t}`);return}let r=this._room.remotePublishedUserMap.get(t);if(!r)return;let s={},n=r.remoteAudioTrack;n.on("decode-failed",d=>{this.emit(U.ERROR,new F({code:W.OPERATION_FAILED,extraCode:5508,message:"audio decode failed"}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId);try{let d=(a=this._remoteAudioVolumeMap.get(t))!=null?a:this._remoteAudioVolumeMap.get("*"),l=Q(d)?d:100;s.volume=l,this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(n),ce(de(n,"decode-failed"),ke(de(n,j.INIT)),Te(()=>{this.startPlugin(Qn.Name,{track:n,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:s,track:n}),S.emit("115",{userId:t,room:this.room}),n.outMediaTrack&&this.room.audioManager.updateAudioReference({type:"add",audioReference:n.outMediaTrack,refId:`ra-${t}`})}catch(d){throw this._remoteAudioConfigMap.delete(t),d}this._emitTrackEvent(n)})}_stopRemoteAudio(e,t=!0){return f(this,null,function*(){let r=this._room.remotePublishedUserMap.get(e.userId);r&&(r.remoteAudioTrack.stop(),r.muteState.hasAudio&&t&&(yield this._room.unsubscribe(r.remoteAudioTrack)),this._mediaTrackMap.delete(r.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete(`${e.userId}`),S.emit("116",{userId:e.userId,room:this.room}),this.room.audioManager.updateAudioReference({type:"remove",refId:`ra-${e.userId}`})})}_enableVideoDecodeFallback(e,t){let r=this._room.videoDecodeFallbackType;if(!r||!this._plugins.has("TRTCVideoDecoder"))return;e.log.debug("remote video will fall back when decode failed",e.id);let s;ce(de(e,"decode-failed"),ke(de(e,j.INIT)),Fn(()=>{this._room.downlinkVideoCodec!=="h265"&&this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:r})}),mo(de(e,"decode-downgrade-state-changed")),Te(n=>{s=n.state,this.emit(U.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,w(M({},n),{streamType:t,userId:e.userId}))},n=>{e.log.error("fallback",n)},()=>{s==="STARTED"&&e.log.info("fallback complete")}))}_updateVideoPlayOption(n){return f(this,arguments,function*({view:e,playOption:t,track:r,prevConfig:s}){if(r.setMirror(t.mirror),T(e)&&s&&s.view&&!Uo(t)){let a=Fo(s.view);a.length>0&&(yield r.play(a,t))}if(!T(e)){let a=Fo(e);a.length>0?yield r.play(a,t):r.stop()}})}_updateAudioPlayOption(s){return f(this,arguments,function*({playOption:e={},track:t,prevConfig:r}){if(!t.isPlayCalled)try{yield t.play(null,e)}catch(n){}if(T(e.muted)||t.setPlayerMute(e.muted),T(e.volume)||t.setAudioVolume(e.volume/100),t instanceof kt&&t.mediaTrack){let n=e.muted===!1&&!T(e.volume)&&e.volume>0?"add":"remove";this.room.audioManager.updateAudioReference({type:n,audioReference:t.mediaTrack,refId:"em"})}else if(t instanceof Ei){let n=e.muted?0:e.volume;if(T(n))return;this.room.audioManager.updateAudioReference({type:"updateVolume",refId:`ra-${t.userId}`,volume:e.volume})}})}_listenOutputTrackChanged(e){e.listeners("output-media-track-changed").length===0&&e.on("output-media-track-changed",()=>this._emitTrackEvent(e,!1))}_emitTrackEvent(e,t=!0){let r=e.isRemote?e.userId:"";e.outMediaTrack&&(t&&this._mediaTrackMap.get(e.outMediaTrack)===r||(this._mediaTrackMap.set(e.outMediaTrack,r),this.emit(U.TRACK,{userId:r,streamType:Li(e.streamType),track:e.outMediaTrack,sourceTrack:e.mediaTrack})))}_checkTrackToPublish(){var t,r,s;let e=[];if((t=this._localAudioConfig)!=null&&t.publish&&this._localAudioTrack&&e.push(this._localAudioTrack),(r=this._localVideoConfig)!=null&&r.publish&&this._localVideoTrack&&e.push(this._localVideoTrack),(s=this._localScreenConfig)!=null&&s.publish&&(this._localScreenTrack&&e.push(this._localScreenTrack),this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack),this._checkScreenAudioEchoCancellation(this._localScreenTrack,this._localScreenAudioTrack)),e.length!==0)return Promise.all(e.map(n=>this._room.publish(n).catch(()=>{})))}_observeView({remoteTrack:e,view:t,receiveWhenViewVisible:r,viewRoot:s}){if(T(t)||T(r))return;let n=this._remoteVideoConfigMap.get(`${e.userId}_${Li(e.streamType)}`);if(!n)return;let a=n.observer||void 0;if(t===null||Ae(t)&&t.length===0||!r){a==null||a.disconnect(),e.isSubscribed||(this._log.info("_observeView observer disconnect, resubscribe",e.userId,e.strMediaType),this._room.subscribe(e).catch(()=>{}));return}let l=n.visibleViewMap||new Map,u=-1;(!a||a.root!==s)&&(a==null||a.disconnect(),l.clear(),a=new IntersectionObserver(p=>{p.forEach(m=>{l.set(m.target,m.isIntersecting),e.log.info(`view ${m.target.id} is${m.isIntersecting?"":" not"} visible`)}),clearTimeout(u),u=window.setTimeout(()=>{[...l.values()].find(g=>g)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:s}));let h=new Set(Fo(t));l.forEach((p,m)=>{h.has(m)||(a.unobserve(m),l.delete(m))}),h.forEach(p=>{l.set(p,!0),a.observe(p)}),a.takeRecords().forEach(p=>{l.set(p.target,p.isIntersecting)}),n.visibleViewMap=l,n.observer=a}_exitRoom(){return f(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),this._clearRemoteTracks()})}_stopScreenShare(){return f(this,null,function*(){var e;if(this._localScreenTrack){if(this._room.isJoined){let t=[this._localScreenTrack];this._localScreenAudioTrack&&t.push(this._localScreenAudioTrack),yield Promise.all(t.map(r=>this._room.unpublish(r).catch(()=>{})))}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(((e=this._localScreenAudioTrack.trackSettings)==null?void 0:e.echoCancellation)===!1&&this.stopPlugin("AudioProcessor"),this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),we(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_checkScreenAudioEchoCancellation(e,t){return f(this,null,function*(){var s,n;if(!e||!t)return;let r=(s=e.trackSettings)==null?void 0:s.displaySurface;if(((n=t.trackSettings)==null?void 0:n.echoCancellation)===!1&&(r==="monitor"||r==="browser"&&e.isShareCurrentTab)){this._log.warn("echoCancellation of screen audio track is disable. Try starting audioProcessor plugin");try{yield this.startPlugin("AudioProcessor",{sdkAppId:Number(this.room.sdkAppId),userId:this._room.userId,userSig:this.room.userSig,isScreenAudioNeedAudioProcess:!0,isLocalAudioNeedAudioProcess:!1})}catch(a){this._log.warn("start audioProcessor plugin failed: ",a)}}})}_onLocalTrackCaptured({track:e}){e.kind==="audio"&&(!ze||ls(ze))&&(this._initActiveSpeaker(),S.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return f(this,null,function*(){if(ze&&!ls(ze))this.emit(U.DEVICE_CHANGED,{type:"speaker",action:"active",device:ze});else{let e=yield vr();e[0]&&!ls(e[0])?(ze=e[0],this.emit(U.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):S.on("102",this._onLocalTrackCaptured,this)}})}_onAudioAvailable({userId:e}){let t=this._remoteAudioMuteMap.has(e)?this._remoteAudioMuteMap.get(e):this._remoteAudioMuteMap.get("*");(t===!1||this._room.autoReceiveAudio&&!t)&&this._doStartRemoteAudio({userId:e}).catch(()=>{})}_onVideoAvailable({userId:e,streamType:t}){if(!this._room.autoReceiveVideo)return;let r=this._room.remotePublishedUserMap.get(e);if(r){let s=t==="main"?r.remoteVideoTrack:r.remoteAuxiliaryTrack,n=[s];this._room.autoReceiveAudio&&r.remoteAudioTrack.isAvailable&&n.push(r.remoteAudioTrack),this._room.subscribe(...n).then(()=>{this._emitTrackEvent(s)}).catch(()=>{})}}_onAudioUnavailable({userId:e,muteState:t}){t.hasAudio&&t.audioMuted||this._stopRemoteAudio({userId:e},!1).catch(()=>{})}_onVideoUnavailable({userId:e,streamType:t}){this._stopRemoteVideo({userId:e,streamType:t},!1).catch(()=>{})}sendSEIMessage(e,t){var s;let r=this._plugins.get("SEI");r&&(r.update({buffer:e,options:w(M({seiPayloadType:243},t),{small:!!((s=this._localVideoTrack)!=null&&s.small)})}),y.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,r;(r=(t=this._room).sendCustomMessage)==null||r.call(t,e),y.addCount({key:500001,useUV:!0})}callExperimentalAPI(e,t){return f(this,null,function*(){return this._log.info(`callExperimentalAPI(${e}, ${JSON.stringify(t)})`),Jf.call(e,M({trtcInstance:this},t))})}static setLogLevel(e,t){R.setLogLevel(e),T(t)||(t?R.enableUploadLog():R.disableUploadLog())}static isSupported(){return fd(q.frameWorkType)}static getPermissions(r){return f(this,arguments,function*({request:e=!0,types:t=["camera","microphone"]}){e&&(yield Yn.request(t).catch(a=>{var d;return R.error(`getPermissions request failed, error: ${(d=a==null?void 0:a.message)!=null?d:a}`)}));let[s,n]=yield Promise.all([Yn.get("camera"),Yn.get("microphone")]);return{camera:s,microphone:n}})}static getCameraList(e=!0){return At(e)}static getMicrophoneList(e=!0){return It(e)}static getSpeakerList(e=!0){return vr(e)}static setCurrentSpeaker(e){return f(this,null,function*(){if(_e&&(e===So.SPEAKER||e===So.HEADSET)){let r=yield q.getMicrophoneList(),s="";if(r.forEach(n=>{n.label===e&&(s=n.deviceId)}),!s)return;Zn.forEach(n=>f(this,null,function*(){n._localAudioTrack&&(yield n.updateLocalAudio({option:{microphoneId:s}}))}));return}(yield vr()).forEach(r=>{r.deviceId===e&&(Zn.forEach(s=>{s._setCurrentSpeaker(e),s.emit(U.DEVICE_CHANGED,{type:"speaker",action:"active",device:r})}),ze=r)})})}static _addKVStat({type:e,key:t,value:r,base:s,useUV:n,version:a,max:d}){switch(a&&(ro.version=a),e){case"count":ro.addCount({key:t,useUV:n});break;case"enum":ro.addEnum({key:t,value:r,useUV:n});break;case"number":ro.addNumber({key:t,value:r,split:s,max:d});break}}};c(q,"VERSION",bh),c(q,"_loggerManager",R),c(q,"EVENT",U),c(q,"ERROR_CODE",W),c(q,"TYPE",So),c(q,"frameWorkType",30),D([Se({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),D([ot(Ge.TRTC.enterRoom),Lr("room",([e],[t])=>(e.roomId||e.strRoomId)===(t.roomId||t.strRoomId)&&e.userId===t.userId&&e.sdkAppId===t.sdkAppId),Y(e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)}),Se()],q.prototype,"enterRoom",1),D([Se()],q.prototype,"exitRoom",1),D([ot(Ge.TRTC.switchRoom),Se(),ir()],q.prototype,"switchRoom",1),D([ot(Ge.TRTC.switchRole),Ao("room",{merge:(e,t)=>t}),Se()],q.prototype,"switchRole",1),D([Se()],q.prototype,"destroy",1),D([ot(Ge.TRTC.startLocalAudio),Lr("audio",([e],[t])=>{var r,s;return((r=e==null?void 0:e.option)==null?void 0:r.microphoneId)===((s=t==null?void 0:t.option)==null?void 0:s.microphoneId)}),Se()],q.prototype,"startLocalAudio",1),D([ot(Ge.TRTC.updateLocalAudio),Ao("audio",{debounce:{delay:200,getKey:()=>`${jf}-localAudio`,isNeedToDebounce:e=>{var t;return!T((t=e.option)==null?void 0:t.captureVolume)}}}),Se()],q.prototype,"updateLocalAudio",1),D([xr("audio"),Se()],q.prototype,"stopLocalAudio",1),D([ot(Ge.TRTC.startLocalVideo),Lr("video",([e],[t])=>{var r,s;return((r=e==null?void 0:e.option)==null?void 0:r.cameraId)===((s=t==null?void 0:t.option)==null?void 0:s.cameraId)}),Se()],q.prototype,"startLocalVideo",1),D([ot(Ge.TRTC.updateLocalVideo),Ao("video"),Se()],q.prototype,"updateLocalVideo",1),D([xr("video"),Se()],q.prototype,"stopLocalVideo",1),D([ot(Ge.TRTC.startScreenShare),Lr("screen",()=>!0),Se()],q.prototype,"startScreenShare",1),D([ot(Ge.TRTC.updateScreenShare),Ao("screen"),Se()],q.prototype,"updateScreenShare",1),D([Se()],q.prototype,"stopScreenShare",1),D([ot(Ge.TRTC.startRemoteVideo),Lr(e=>`v${e.userId}${e.streamType}`,()=>!0),Se({getRemoteId:e=>`${e.userId}_${e.streamType}`})],q.prototype,"startRemoteVideo",1),D([ot(Ge.TRTC.updateRemoteVideo),Ao(e=>`v${e.userId}${e.streamType}`),Se({getRemoteId:e=>`${e.userId}_${e.streamType}`})],q.prototype,"updateRemoteVideo",1),D([ot(Ge.TRTC.stopRemoteVideo),Y(e=>function(t){return f(this,null,function*(){if(t.userId==="*"){let r=[];return this._room.remotePublishedUserMap.forEach(s=>{this._remoteVideoConfigMap.has(`${s.userId}_main`)&&r.push(this.stopRemoteVideo({streamType:"main",userId:s.userId}).catch(()=>{})),this._remoteVideoConfigMap.has(`${s.userId}_sub`)&&r.push(this.stopRemoteVideo({streamType:"sub",userId:s.userId}).catch(()=>{}))}),Promise.all(r)}return e.call(this,t)})}),Se({getRemoteId:e=>`${e.userId}_${e.streamType}`})],q.prototype,"stopRemoteVideo",1),D([xr(e=>`v${e.userId}${e.streamType}`)],q.prototype,"_stopRemoteVideo",1),D([ot(...Ge.TRTC.muteRemoteAudio),Se({getRemoteId:e=>e})],q.prototype,"muteRemoteAudio",1),D([Nh(...Ge.TRTC.setRemoteAudioVolume),Ff(200,e=>e),Se({getRemoteId:e=>e})],q.prototype,"setRemoteAudioVolume",1),D([hc("start"),Ct(e=>{var t;return(t=e.afterStart)==null?void 0:t.call(e)}),Lr((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t)),Se({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Yl[e.getName()],ignoreLog:e=>e.getName()==="Debug",ignoreErrorLog:e=>e.getName()==="AudioProcessor"})],q.prototype,"startPlugin",1),D([hc("update"),Ao((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t),{merge:(e,t)=>(ei(e[1],t[1]),e)}),Se({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Zl[e.getName()]})],q.prototype,"updatePlugin",1),D([hc("stop"),xr((e,t)=>{if(e.disableRandomCall)return null;let r=e.getGroup(t),s=e.getAlias();return r==="*"?new RegExp(`${s}.*`):s+r}),Se({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Kl[e.getName()]})],q.prototype,"stopPlugin",1),D([Nh(...Ge.TRTC.enableAudioVolumeEvaluation)],q.prototype,"enableAudioVolumeEvaluation",1),D([Se()],q.prototype,"getVideoSnapshot",1),D([Se()],q.prototype,"_setCurrentSpeaker",1),D([Lr(e=>`a${e.userId}`,()=>!0)],q.prototype,"_startRemoteAudio",1),D([Y(e=>function(t){return f(this,null,function*(){return t.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(r=>this._stopRemoteAudio(w(M({},t),{userId:r.userId})).catch(()=>{}))):e.call(this,t)})}),xr(e=>`a${e.userId}`)],q.prototype,"_stopRemoteAudio",1),D([xr("room")],q.prototype,"_exitRoom",1),D([xr("screen")],q.prototype,"_stopScreenShare",1),D([ot(...Ge.TRTC.sendSEIMessage),Ih({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...e)=>e[0].byteLength})],q.prototype,"sendSEIMessage",1),D([ot(Ge.TRTC.sendCustomMessage),Ih({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],q.prototype,"sendCustomMessage",1),D([wr()],q,"create",1),D([ot(Ge.TRTC.create)],q,"_create",1),D([wr()],q,"setLogLevel",1),D([wr()],q,"isSupported",1),D([wr(),Se()],q,"getPermissions",1),D([wr()],q,"getCameraList",1),D([wr()],q,"getMicrophoneList",1),D([wr()],q,"getSpeakerList",1);var Hh=q,Kn=Hh;var $h=class{constructor(){c(this,"_set",new Set);S.on(A.LEAVE_SUCCESS,this.delete,this),S.on(A.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess,this)}add({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,e||i.roomId,i.sdkAppId,i.useStringRoomId);this._set.add(t)}delete({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,i.roomId||e,i.sdkAppId,i.useStringRoomId);this._set.delete(t)}getKey(i,e,t,r){return`${t}_${e}_${i}_${r}`}isJoined({userId:i,roomId:e,sdkAppId:t,room:r}){return r.scene==="rtc"?!1:this._set.has(this.getKey(i,e,t,r.useStringRoomId))}handleSwitchRoomSuccess({room:i,currentRoomId:e,targetRoomId:t}){i.scene!=="rtc"&&(this._set.delete(this.getKey(i.userId,e,i.sdkAppId,i.useStringRoomId)),this._set.add(this.getKey(i.userId,t,i.sdkAppId,i.useStringRoomId)))}};function YS(){return f(this,null,function*(){let o,i;try{let m=yield It();o=m&&m.length}catch(m){}try{let m=yield At();i=m&&m.length}catch(m){}let e={microphone:o,camera:i},{isH264EncodeSupported:t,isVp8EncodeSupported:r,isH264DecodeSupported:s,isVp8DecodeSupported:n,isH265EncodeSupported:a,isH265DecodeSupported:d}=this.checkSystemResult.detail,l=vi.basis(),u={webRTC:l.isWebRTCSupported,getUserMedia:l.isGetUserMediaSupported,webSocket:l.isWebSocketsSupported,screenShare:l.isScreenShareSupported,webAudio:l.isWebAudioSupported,h264Encode:t,h264Decode:s,vp8Encode:r,vp8Decode:n,h265Encode:a,h265Decode:d},h={browser:l.browser,os:l.os,trtc:u,devices:e},p={isWebCodecSupported:l.isWebCodecSupported,isMediaSessionSupported:l.isMediaSessionSupported,isWebTransportSupported:l.isWebTransportSupported};se.uploadEvent({log:`trtcstats-${JSON.stringify(h)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(h)}`),se.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(p)}`,userId:this.userId}),uu()})}function zf(){return Y(o=>{let i=new $h;return function(e,t,r){return f(this,null,function*(){let s=String(e.roomId||e.strRoomId);if(this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.userSig=e.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=t,e.privateMapKey=e.privateMapKey||"",this.isJoined)throw new v({code:I.INVALID_OPERATION,message:$({key:B.INVALID_JOIN})});if(this.checkDestroy(),i.isJoined({userId:this.userId,roomId:s,sdkAppId:this.sdkAppId,room:this}))throw new v({code:I.INVALID_OPERATION,message:$({key:B.REPEAT_JOIN,data:this.userId})});i.add({room:this,roomId:s}),this.role=e.role===21?"audience":"anchor",this._log.info(`Join() => joining room: ${s} useStringRoomId: ${this.useStringRoomId} scene: ${this.scene} role: ${this.role}`),S.emit(A.JOIN_START,{room:this,roomId:s,params:e});let n=Nt.getEnv();n||(n=$i.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(_a.OLD_CLOUD_LADDER)?n=$i.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(_a.WEBRTC)&&(n=$i.WEBRTC))),se.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:s}),vi.checkSystemRequirementsInternal(r).then(a=>{this.checkSystemResult=a,YS.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Nt.getEnv()&&(yield this.schedule(e,r));let a=yield o.call(this,e,t,r);return this.roomId=s,this._joinedTimestamp=Nt.performanceNow(),S.emit(A.JOIN_SUCCESS,{room:this}),r===30&&!e.component&&se.uploadEvent({log:`stat-conv-${Number(ni)}-${location.hostname}`,userId:this.userId}),a}catch(a){throw i.delete({room:this,roomId:s}),S.emit(A.JOIN_FAILED,{room:this,error:a}),a}})}})}var Qf=()=>Y(o=>function(...i){return f(this,null,function*(){S.emit(A.LEAVE_START,{room:this}),yield o.call(this,...i),S.emit(A.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function Yf(){return Y(o=>function(...i){let e=o.apply(this,i);return i.forEach(t=>!t.isSubscribed&&t.subscribe(e)),e})}var Kf=Je(nt());var Ie={SETUP_SUCCESS:"1",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",RECONNECT_FAILED:"4",SETUP_FAILED:"5",DISCONNECTED:"6",CLOSE:"7",ONLINE:"8"};var Jt={CLIENT_BANNED:9,CHANNEL_SETUP_RESULT:19,CHANNEL_RECONNECT_RESULT:514,JOIN_ROOM_RESULT:20,PEER_JOIN:4134,PEER_LEAVE:4135,STREAM_ADDED:16,STREAM_REMOVED:18,UPLINK_NETWORK_STATS:22,UPDATE_REMOTE_MUTE_STAT:23,PUBLISH_RESULT:4098,PUBLISH_STATE_CHANGE_RESULT:4112,UNPUBLISH_RESULT:4100,SUBSCRIBE_RESULT:4102,UNSUBSCRIBE_RESULT:4104,SUBSCRIBE_CHANGE_RESULT:4106,MUTE_RESULT:4108,UPDATE_OFFER_RESULT:4128,START_PUBLISH_TENCENT_CDN_RES:1286,STOP_PUBLISH_TENCENT_CDN_RES:1288,START_PUBLISH_GIVEN_CDN_RES:777,STOP_PUBLISH_GIVEN_CDN_RES:779,START_MIX_TRANSCODE_RES:781,STOP_MIX_TRANSCODE_RES:783,START_PUBLISH_CDN_STREAM_RES:8196,UPDATE_PUBLISH_CDN_STREAM_RES:8198,STOP_PUBLISH_CDN_STREAM_RES:8200,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772,REBUILD_PEER_CONNECTION_RES:4150,SPC_PUBLISH_RESULT:4146,SPC_SUBSCRIBE_RESULT:4156,ABILITY_STATUS_REPORT_RESULT:4158,SERVER_FIRST_PACKAGE_RECEIVED:5e3,RECEIVE_CUSTOM_MSG:4140,FALLBACK_CODEC:66,SEND_SWITCH_ROOM_RES:4160,SEND_SWITCH_ROOM_SUBED_REQ:4161,UPDATE_NETWORK_TIME_RESULT:5001,CUSTOM_CMD_RES:8220},Zf=[Jt.UPDATE_REMOTE_MUTE_STAT,Jt.UPLINK_NETWORK_STATS,Jt.USER_LIST_RES,Jt.MUTE_RESULT,Jt.SERVER_FIRST_PACKAGE_RECEIVED,Jt.RECEIVE_CUSTOM_MSG,Jt.UPDATE_NETWORK_TIME_RESULT],J={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",START_PUBLISH_CDN_STREAM_RES:"start-publish-cdn-stream-res",UPDATE_PUBLISH_CDN_STREAM_RES:"update-publish-cdn-stream-res",STOP_PUBLISH_CDN_STREAM_RES:"stop-publish-cdn-stream-res",USER_LIST_RES:"user-list-res",SWITCH_ROLE_RES:"switch_role_res",MUTE_RESULT:"mute-result",UPDATE_CONSTRAINT_CONFIG_RES:"update-contraint-config-res",REBUILD_PEER_CONNECTION_RES:"rebuild-pc-res",SPC_PUBLISH_RESULT:"spc-publish-result",SPC_SUBSCRIBE_RESULT:"spc-subscribe-result",ABILITY_STATUS_REPORT_RESULT:"ability-status-report",SERVER_FIRST_PACKAGE_RECEIVED:"first-pkg-received",RECEIVE_CUSTOM_MSG:"receive-custom-msg",FALLBACK_CODEC:"fallback-codec",SEND_SWITCH_ROOM_RES:"send-switch-room-res",SEND_SWITCH_ROOM_SUBED_REQ:"send-switch-room-subed-res",UPDATE_NETWORK_TIME_RESULT:"update_network_time_result",CUSTOM_CMD_RES:"custom-cmd-res"},Z={PUBLISH_CHANGE:"publish_change",JOIN_ROOM:"join",LEAVE_ROOM:"leave",ON_QUALITY_REPORT:"quality_report",UPDATE_MUTE_STAT:"mute_uplink",PUBLISH:"publish",PUBLISH_STATE_CHANGE:"publish_state_change",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",RECEIVE_DATA_USER_LIST:"receive_data_userlist",UNSUBSCRIBE:"unsubscribe",SUBSCRIBE_CHANGE:"subscribe_change",START_PUBLISH_TENCENT_CDN:"start_publishing",STOP_PUBLISH_TENCENT_CDN:"stop_publishing",START_PUBLISH_GIVEN_CDN:"start_push_user_cdn",STOP_PUBLISH_GIVEN_CDN:"stop_push_user_cdn",START_MIX_TRANSCODE:"start_mcu_mix",STOP_MIX_TRANSCODE:"stop_mcu_mix",START_PUBLISH_CDN_STREAM:"start_publish_cdn_stream",UPDATE_PUBLISH_CDN_STREAM:"update_publish_cdn_stream",STOP_PUBLISH_CDN_STREAM:"stop_publish_cdn_stream",GET_USER_LIST:"get_user_list",SWITCH_ROLE:"change_role",UPDATE_CONSTRAINT_CONFIG:"update_constraint_config",REBUILD_PEER_CONNECTION:"rebuild_pc",READY_TO_RECEIVE_DATA:"ready_to_receive",SPC_JOIN_ROOM:"join/v2",SPC_PUBLISH:"publish/v2",SPC_SUBSCRIBE:"subscribe/v3",ABILITY_STATUS_REPORT:"ability_status_report",RECONNECT_WS:"reconnect",SEND_CUSTOM_MSG:"channel_msg",SWITCH_ROOM:"switch_room",UPDATE_NETWORK_TIME:"update_network_time",CUSTOM_CMD:"abstract_cmd"};var Rc=new Set;function e_(o){let i=[...Rc.values()].find(e=>e.room.userId===o&&!e.room.isJoined);return i||null}var KS=["autoTest","relayInnerIp","relayOuterIp","mcd","newRelay","clientIp"],ys=class extends Kf.default{constructor(e){var r,s,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:[],reportToken:void 0});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,"_isFirstConnect",!0);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=((s=(r=this.room.scheduleResult)==null?void 0:r.config)==null?void 0:s.keepAliveClient)||0;(n=this.room.joinParams)!=null&&n.keepAlive&&!t&&(t=1),t-Rc.size>0&&this.room.enableSPC&&(this.keepAlive=!0,Rc.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=R.createLogger({parent:this.room.getLogger(),id:"ws",userId:this.userId,sdkAppId:this.sdkAppId}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get race(){return this.room.enableSPC&&!this.room.proxy_ws}get urlParam(){let e=`?sdkAppId=${encodeURIComponent(this.sdkAppId)}&userId=${encodeURIComponent(this.userId)}&userSig=${encodeURIComponent(this.userSig)}&keepAlive=${encodeURIComponent(Number(this.keepAlive))}`;this.signalDomainWhenUnifiedProxy&&(e+=`&signalDomain=${encodeURIComponent(this.signalDomainWhenUnifiedProxy)}`);let t=new URLSearchParams(location.search);return KS.forEach(r=>{let s=t.get(`trtc_${r}`);s&&(e+=`&${r}=${encodeURIComponent(s)}`)}),this.race?`${e}&race=1`:e}get _urlWithParam(){return`${this.url}${this.race?"/v2/ws":""}${this.urlParam}`}get _backupUrlWithParam(){return`${this.backupUrl}${this.race?"/v2/ws":""}${this.urlParam}`}get isConnected(){return this._currentState==="CONNECTED"}get isConnecting(){return this._currentState==="CONNECTING"}get isOnline(){return this._currentState==="CONNECTED"&&Date.now()-this._lastMessageTime<12*1e3}connect(){return f(this,arguments,function*(e=10*1e3){if(this.isConnected)return Promise.resolve();this._log.info(`connect to [${this.url}, ${this.backupUrl}] ${this.race?"race":""}${e?` timeout: ${e}`:""} keepAlive: ${Number(this.keepAlive)}`),this.emitConnectionStateChanged("CONNECTING"),this._connectStartTime=V();let t=[this.connectWS({url:this._urlWithParam,isMain:!0,timeout:e})];this.race&&this._backupUrlWithParam!==this._urlWithParam&&t.push(this.connectWS({url:this._backupUrlWithParam,isMain:!1,timeout:e})),this._socketInUse=yield Xr(t),this.unbindAndCloseSocket(this._socketInUse===this._socket?_.BACKUP:_.MAIN),this._isFirstConnect&&(y.addSuccessEvent({key:521720}),this._isFirstConnect=!1),this.emitConnectionStateChanged("CONNECTED")})}connectWS({url:e,timeout:t,isMain:r}){let s=new WebSocket(e);this.bindSocket(s),r?this._socket=s:this._backupSocket=s;let n=-1;return new Promise((a,d)=>{s.onclose=d,s.onerror=d,s.onopen=()=>a(s),t&&(n=setTimeout(()=>{this.unbindAndCloseSocket(r?_.MAIN:_.BACKUP),d(new v({code:I.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))},t))}).finally(()=>{s.onclose=null,s.onerror=null,s.onopen=null,clearTimeout(n)})}bindSocket(e){e.addEventListener("close",this.onclose),e.addEventListener("error",this.onerror),e.addEventListener("message",this.onmessage)}unbindSocket(e){e.removeEventListener("close",this.onclose),e.removeEventListener("error",this.onerror),e.removeEventListener("message",this.onmessage)}unbindAndCloseSocket(e){if(e===_.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(t){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(t){}this._backupSocket=null}}onclose(e){e.target===this._socketInUse&&(this._log.warn(`${e.target===this._socket?"main":"backup"} is closed code:${e.code} ${e.reason}`),this.emitConnectionStateChanged("DISCONNECTED"),(!e.wasClean||e.code!==1e3)&&this.startReconnection(),this.room.isJoining&&this.emit(Ie.SETUP_FAILED,new v({code:I.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onclose"})))}onerror(e){this._log.error(`${e.target===this._socket?"main":"backup"} error observed`),this.emitConnectionStateChanged("DISCONNECTED"),e.target===this._socketInUse&&(this.unbindAndCloseSocket(_.MAIN),this.unbindAndCloseSocket(_.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(Ie.SETUP_FAILED,new v({code:I.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(e){if(!this.isConnected)return;let{isOnline:t}=this;this._lastMessageTime=Date.now(),t||this.emit(Ie.ONLINE),this.bytesReceived+=Gs(e.data);let r=JSON.parse(e.data),{cmd:s,data:n}=r,a=Object.values(Jt),l=Object.keys(Jt)[a.indexOf(s)],u=J[l]||s;switch(Zf.includes(s)||(this._log.debug(`received ${s} msg: ${e.data}`),u&&this._log.info(`Received event: [ ${u} ]`)),s){case Jt.CHANNEL_SETUP_RESULT:{if(r.code===0)this._signalInfo.clientIp=n.clientIp,this._signalInfo.signalIp=n.signalInnerIp,n.svrTime&&da(n.svrTime-new Date().getTime()),this._log.info(`ChannelSetup Success ${V()-this._connectStartTime}`),y.addSuccessEvent({key:521701,cost:V()-this._connectStartTime}),this._connectStartTime=-1,this.emit(Ie.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let h=new v({code:I.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:r.code,message:$({key:B.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:r.code,errorMsg:r.message}})});this._log.error(`${r.code}, ${r.message}`),this.close(),y.addFailedEvent({key:521701,error:h}),this.emit(Ie.SETUP_FAILED,h)}break}case Jt.JOIN_ROOM_RESULT:{r.code===0&&(this._signalInfo.relayIp=n.relayOuterIp,this._signalInfo.relayInnerIp=n.relayInnerIp,this._signalInfo.bakRelayIps=n.bakRelayIps,this._signalInfo.relayPort=n.relayPort,this._signalInfo.tinyId=r.tinyId,this._signalInfo.endReportExtend=n.endReportExtend,this._signalInfo.reportToken=n.reportToken,this._log.info(`signalIp:${this._signalInfo.signalIp} clientIp:${this._signalInfo.clientIp} relayIp: ${this._signalInfo.relayIp}`)),this.emit(u,{data:r});break}default:this.emit(String(u),{data:r});break}}reGetSignalChannelUrl(){return f(this,null,function*(){try{if(!this.room.joinParams)return;xt(!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?_.MAIN:_.BACKUP),this._socketInUse=null,this.emitConnectionStateChanged("DISCONNECTED"),this.reconnect()}reconnect(){return f(this,null,function*(){if(!this._isReconnecting){if(!this.room.isJoined&&this.keepAlive){this.close();return}this._isReconnecting=!0;try{this._log.warn("reconnect"),yield this.connect();let{roomId:e,useStringRoomId:t}=this.room,{relayIp:r,relayInnerIp:s,relayPort:n}=this._signalInfo,{data:a}=yield this.sendWaitForResponse({command:Z.RECONNECT_WS,data:{roomId:e,useStringRoomId:t,relayInnerIp:s,relayOuterIp:r,relayPort:n},responseCommand:J.CHANNEL_RECONNECT_RESULT});a.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),y.addSuccessEvent({key:521702,cost:V()-this._connectStartTime}),this._connectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(y.addFailedEvent({key:521702,error:a.code}),this._log.warn(`reconnect failed, ${a.code} ${a.message}`),this.room.reJoin())}catch(e){this._log.error(e),this.room.reJoin()}}})}send(e,t={}){if(this.isConnected&&!this.room.isLeft){let r={cmd:e,data:t,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},s=JSON.stringify(r);return this._socketInUse.send(s),this.bytesSent+=Gs(s),r.seq}}sendWaitForResponse({command:e,data:t,timeout:r=5e3,responseCommand:s,commandDesc:n,enableLog:a=!0,addReceiveTime:d=!1}){return new Promise((l,u)=>{let h=()=>{clearTimeout(p),u(new v({code:I.API_CALL_ABORTED,message:`${e} aborted due to connection closed`}))};this.once(Ie.CLOSE,h);let p=setTimeout(()=>{this.off(s,m),this.off(Ie.CLOSE,h);let E=new v({code:I.API_CALL_TIMEOUT,message:$({key:B.API_CALL_TIMEOUT,data:{commandDesc:n,command:e}})});a&&this._log.warn(E),u(E)},r),m=E=>{E.data.seq===g&&(clearTimeout(p),this.off(s,m),this.off(Ie.CLOSE,h),d&&(E.data.receiveTime=Date.now()),l(E))};this.on(s,m);let g=this.send(e,t)})}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:r,retries:s=0,retryTimeout:n=0}=e;return Ri({retryFunction:this.sendWaitForResponse,onError:({retry:a,reject:d,error:l})=>{!this.room.isJoined||this.destroyed||l.code===I.API_CALL_ABORTED?d(l):this.isOnline?a():(this._log.warn(`retry ${r} when connected`),this.once(Ie.ONLINE,a))},onRetrying:a=>{this._log.warn(`${t||r} timeout observed, retrying [${a}/${s}]`)},settings:{retries:s,timeout:n},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),clearTimeout(this.stopKeepAliveTimeout),Rc.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,bakRelayIps:[],endReportExtend:void 0,reportToken:void 0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(_.MAIN),this.unbindAndCloseSocket(_.BACKUP),this.emitConnectionStateChanged("DISCONNECTED"),this.emit(Ie.CLOSE)}destroy(){this.close(),this.destroyed=!0}getBackupRelayIpPair(){var t;let e=(t=this._signalInfo.bakRelayIps)==null?void 0:t.shift();return e&&(e.relayPort=e.relayPort||this._signalInfo.relayPort),e}clearBakRelayIps(){this._signalInfo.bakRelayIps=[]}stopKeepAliveIn(e=3600){if(this.keepAlive){this._log.info(`stopKeepAlive in ${e}s`),this.stopKeepAliveTimeout=setTimeout(()=>{this.keepAlive=!1,this._log.info(`close due to not used ${e}s`),this.close(),this.off(J.JOIN_ROOM_RESULT,t)},e*1e3);let t=r=>{r.data.code===0&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(J.JOIN_ROOM_RESULT,t))};this.on(J.JOIN_ROOM_RESULT,t)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info(`${this._currentState} -> ${e}`),this.emit(Ie.CONNECTION_STATE_CHANGED,{prevState:this._currentState,state:e}),this._currentState=e,e==="CONNECTED"?this.emit(Ie.CONNECTED):e==="DISCONNECTED"&&this.emit(Ie.DISCONNECTED))}};D([Mt({settings:{retries:1/0,timeout:2e3},onError(e,t){!this.room.isDestroyed&&!this.destroyed&&(this._isFirstConnect&&(y.addFailedEvent({key:521720,error:e}),this._isFirstConnect=!1),t())},onRetrying(e,t){this._log.warn(`retrying to connect ${e}`),e>=3&&e%3===0&&this.reGetSignalChannelUrl(),t&&(this._stopConnectRetry=t,(this.room.isDestroyed||this.destroyed)&&t())}})],ys.prototype,"connect",1);var t_=Je(nt());var Wh=0,Gh=!1,yc=new Set,eI=o=>Wh>2&&!Gh&&yc.size===0&&o,Jh=!1,ft=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 t_.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=i.room.getLogger().createChild({id:"n-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=i.signalChannel}beforeConnect(){this._prevTime<0&&(this._prevTime=V())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,y.addSuccessEvent({key:521705,cost:Math.min(V()-this._prevTime,30*1e3)})):this._isReconnecting&&y.addSuccessEvent({key:521706,cost:V()-this._prevTime}),this._prevTime=-1}catch(i){throw this._isFirstConnection?(this._isFirstConnection=!1,y.addFailedEvent({key:521705,error:i})):this._isReconnecting&&this._reconnectionCount>=3&&y.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(),yc.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 v({code:I.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return Qt;let i=null;if(this._isUplink){if(!Rr()||this._peerConnection.getSenders().length===0)return Qt;i=this._peerConnection.getSenders()[0].transport}else{if(!oo()||this._peerConnection.getReceivers().length===0)return Qt;i=this._peerConnection.getReceivers()[0].transport}return i?i.state:Qt}onConnectionStateChange(i){let e=this._peerConnection.iceConnectionState,t=this.getDTLSTransportState();if(this._log.info(`connectionState: ${i.target.connectionState}, ICE: ${e}, DTLS: ${t}`),i.target.connectionState===Ce.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),i.target.connectionState===Ce.FAILED||i.target.connectionState===Ce.CLOSED){let r=`connection ${i.target.connectionState}. ICE Transport state: ${e}, DTLS Transport state: ${t}`,s=new v({message:r,code:I.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",s)}(i.target.connectionState===Ce.CONNECTED||i.target.connectionState===Ce.COMPLETED)&&(this.logSelectedCandidate(),se.logSuccessEvent({userId:this._room.userId,eventType:Ze.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(i){return i===this._currentState?!1:(i==="CONNECTED"?(Wh=0,Gh=!1,Jh=!0,yc.add(this)):yc.delete(this),S.emit(A.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:i,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:i}),this._currentState=i,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}logSelectedCandidate(){return f(this,null,function*(){if(!this._peerConnection)return;let i=yield this._peerConnection.getStats();for(let[,e]of i)if(Cr(e)){let t=i.get(e.localCandidateId),r=i.get(e.remoteCandidateId);t&&(this._log.info(`local candidate: ${t.candidateType} ${t.protocol}:${t.ip||t.address}:${t.port} ${t.networkType||""} ${t.candidateType==="relay"?`relayProtocol:${t.relayProtocol}`:""}`),this._localAddress=`${t.ip||t.address}:${t.port}`),r&&(this._log.info(`remote candidate: ${r.candidateType} ${r.protocol}:${r.ip||r.address}:${r.port}`),this._remoteAddress=`${r.protocol}:${r.ip||r.address}`);break}})}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise?this._waitForPeerConnectionConnectedPromise:(this._waitForPeerConnectionConnectedPromise=new Promise((i,e)=>{if(this._currentState==="CONNECTED")return i();this._waitForPeerConnectionConnectedPromiseReject=e;let t=a=>{a.state==="CONNECTED"&&(clearTimeout(n),s(),i())},r=({room:a})=>{a===this._room&&(clearTimeout(n),s(),e(new v({code:I.API_CALL_ABORTED,message:$({key:B.CONNECTION_ABORTED,data:"leave room"})})))},s=()=>{S.off(A.LEAVE_SUCCESS,r,this),this._emitter.off("connection-state-changed",t,this)},n=setTimeout(()=>{s();let a=new v({code:I.API_CALL_TIMEOUT,message:"connection timeout"});Wh+=1,eI(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),Gh=!0,this._emitter.emit("firewall-restriction")),e(a)},Fs);S.on(A.LEAVE_SUCCESS,r,this),this._emitter.on("connection-state-changed",t,this)}),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally(()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null}),this._waitForPeerConnectionConnectedPromise)}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(Ie.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=Wi()){this._log.warn(`SDK has tried reconnect for ${this._reconnectionCount} times, but all failed, please check your network`),this.stopReconnection();let i=new v({code:this._isUplink?I.UPLINK_RECONNECTION_FAILED:I.DOWNLINK_RECONNECTION_FAILED,message:$({key:this._isUplink?B.UPLINK_RECONNECTION_FAILED:B.DOWNLINK_RECONNECTION_FAILED})});return this.emitConnectionStateChangedEvent("DISCONNECTED"),this._emitter.emit("error",i),-1}return this._signalChannel.isConnected?(this._reconnectionCount+=1,this._log.warn(`reconnect() trying [${this._reconnectionCount}]`),1):(this._log.warn("reconnect() signal channel is not connected, suspend reconnection until signal is connected"),this._signalChannel.once(Ie.CONNECTED,this.reconnect,this),-1)}on(i,e,t){this._emitter.on(i,e,t)}off(i,e,t){this._emitter.off(i,e,t)}getIsReconnecting(){return this._isReconnecting}get isH264(){var i,e;return!!((e=(i=this._peerConnection)==null?void 0:i.remoteDescription)!=null&&e.sdp.includes("H264"))}setOffer(i){var e;return(e=this._peerConnection)==null?void 0:e.setLocalDescription(i)}setAnswer(i){var e;return(e=this._peerConnection)==null?void 0:e.setRemoteDescription(i)}};D([Rt(521712,!1)],ft.prototype,"setOffer",1),D([Rt(521713,!1)],ft.prototype,"setAnswer",1);var zh=Je(Xh());var De=function(o){return zh.default.parse(o)},qt=function(o){return zh.default.write(o)},c_=function(o){let i=De(o);return i.media.forEach(e=>{e.type===_.AUDIO&&e.fmtp.forEach(t=>{t.config+=";sprop-stereo=1;stereo=1"})}),qt(i)};function l_(o){let i=De(o);return i.media.forEach(e=>{var t,r;if(e.type===_.VIDEO){let s=new Set;e.rtp.forEach(({payload:a,codec:d})=>d==="H264"&&s.add(a)),e.fmtp.forEach(({payload:a,config:d})=>{let l=d.match(/apt=(\d+)/);l&&l[1]&&s.has(Number(l[1]))&&s.add(a)});let n=({payload:a})=>!s.has(a);e.rtp=e.rtp.filter(n),e.rtcpFb=(t=e.rtcpFb)==null?void 0:t.filter(n),e.fmtp=e.fmtp.filter(n),e.payloads=(r=e.payloads)==null?void 0:r.split(" ").filter(a=>!s.has(Number(a))).join(" ")}}),qt(i)}function bc(o){return Object.keys(o).filter(i=>o[i])}var Ns=class Ns extends ft{constructor(e){super(w(M({},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);c(this,"_videoCodec");this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=e.remoteAudioTrack||new Ei(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new Pi(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new Ts(this._room,this)}get videoCodec(){var t,r;let e=(r=(t=this._peerConnection)==null?void 0:t.remoteDescription)==null?void 0:r.sdp;return e?e.includes("H264")?"h264":"vp8":this._videoCodec||"h264"}set videoCodec(e){this._videoCodec=e}get subscribeState(){let e={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(this.remoteVideoTrack.mediaType&8?e.smallVideo=!0:e.video=!0),this.remoteAudioTrack.isSubscribed&&(e.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(e.auxiliary=!0),e}get muteState(){return Kt(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,r,s;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(r=this.remoteVideoTrack)==null||r.onFlagChanged(),(s=this.remoteAuxiliaryTrack)==null||s.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===_.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var s,n;let t=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&t!==e&&((s=this.remoteVideoTrack)==null||s.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),r}onTrack(e){let t=e.streams[0],{track:r}=e,s=t.id===Vs?_.MAIN:_.AUXILIARY;this._log.debug(`ontrack ${s} ${r.kind}`);let n=_.AUDIO;r.kind===_.VIDEO&&(n=s===_.MAIN?_.VIDEO:_.AUXILIARY);let a=this.remoteAudioTrack;n===_.VIDEO?a=this.remoteVideoTrack:n===_.AUXILIARY&&(a=this.remoteAuxiliaryTrack),a.setInputMediaStreamTrack(r)}addRRTRLine(e){let t=e.split(`\r
59
- `),r=new Map;t.forEach((n,a)=>{/^a=rtcp-fb:/.test(n)&&t[a+1]&&!/^a=rtcp-fb:/.test(t[a+1])&&r.set(a+1,`${n.match(/^a=rtcp-fb:\d+/)[0]} rrtr`)});let s=[...r];for(let n=0;n<s.length;n++){let[a,d]=s[n];t.splice(a+n,0,d)}return t.join(`\r
60
- `)}addSPSDescription(e){let t=De(e);return t.media.forEach(r=>{r.type===_.VIDEO&&r.fmtp.forEach(s=>{s.config+=";sps-pps-idr-in-keyframe=1"})}),qt(t)}removeSDESDescription(e){let t=["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"],r=De(e);return r.media.forEach(s=>{s.ext&&(s.ext=s.ext.filter(n=>!t.includes(n.uri)))}),qt(r)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return f(this,null,function*(){var r,s;try{if((((r=this._peerConnection)==null?void 0:r.connectionState)===Ce.NEW||((s=this._peerConnection)==null?void 0:s.connectionState)===Ce.CONNECTING)&&(yield this.waitForPeerConnectionConnected()),this.isSubscriptionStateNotChanged(e)){this._peerConnection||(this.initialize(),yield this.connect(e));return}if(this._log.info(`subscribe ${t} ${JSON.stringify(e)}`),this._peerConnection||this._isSDPExchanging){let n="subscribe_change";Object.values(e).find(a=>a===!0)||(n="unsubscribe"),yield this.sendSubscription(n,e)}else this.initialize(),yield this.connect(e)}catch(n){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${n.message} ${JSON.stringify(this.muteState)}`),new v({code:I.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):n}})}unsubscribe(r){return f(this,arguments,function*({remoteTracks:e,streamType:t}){if(this._currentState==="CONNECTED"&&(t==="main"&&!this.isMainStreamSubscribed||t==="auxiliary"&&!this.isAuxStreamSubscribed)){this._log.info(`${t} stream already unsubscribed`);return}let s=M({},this.subscribeState);e.forEach(a=>{switch(a.mediaType){case 1:s.audio=!1;break;case 4:s.video=!1;break;case 8:s.smallVideo=!1;break;case 2:s.auxiliary=!1;break;default:break}});let n="subscribe_change";Object.values(s).find(a=>a===!0)||(n="unsubscribe"),this._log.info(`${n==="unsubscribe"?n:"subscribe"} ${t} [${bc(s)}]`),yield this.sendSubscription(n,s),n==="unsubscribe"&&(this.closePeerConnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"))})}sendSubscription(e,t=this.subscribeState){let r={srcTinyId:this.tinyId,srcUserId:this.userId},s=Z.UNSUBSCRIBE,n=J.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(r={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},s=Z.SUBSCRIBE_CHANGE,n=J.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:s,data:r,responseCommand:n,timeout:1e4}).then(({data:a})=>{if(a.code!==0){let d=new v({code:a.code,message:$({key:B.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(d),d}})}connect(){return f(this,arguments,function*(e=this.subscribeState){try{yield this.exchangeSDP(e),yield this.waitForPeerConnectionConnected()}catch(t){throw this.closePeerConnection(!0),t}})}exchangeSDP(e){return f(this,null,function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info("createOffer success, sending offer");let{type:t,sdp:r}=this._peerConnection.localDescription,s={type:t,sdp:r,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},n=yield this._signalChannel.sendWaitForResponse({command:Z.SUBSCRIBE,commandDesc:"exchange sdp",data:s,responseCommand:J.SUBSCRIBE_RESULT,timeout:el});if(!this._peerConnection){let a=new v({code:I.INVALID_OPERATION,message:$({key:B.CONNECTION_CLOSED})});throw this._log.warn(a),a}yield this.onSubscribeResult(n),this._isSDPExchanging=!1}catch(t){throw this._isSDPExchanging=!1,t}})}createOffer(){return f(this,null,function*(){let e={voiceActivityDetection:!1};St()&&this._sdpSemantics===gr?(this._peerConnection.addTransceiver(_.AUDIO,{direction:ne.RECVONLY}),this._peerConnection.addTransceiver(_.VIDEO,{direction:ne.RECVONLY}),this._peerConnection.addTransceiver(_.VIDEO,{direction:ne.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:r}=yield pd();r||(this._log.warn("remove h264 desc from sdp"),t.sdp=l_(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=c_(t.sdp),this._sdpSemantics===gr&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this.setOffer(t)})}onSubscribeResult(e){return f(this,null,function*(){let{code:t,message:r=""}=e&&e.data||{},{type:s,sdp:n}=e&&e.data&&e.data.data||{};if(t===Hr)throw new v({code:I.NOT_SUPPORTED_H264,message:$({key:B.NOT_SUPPORTED_H264DECODE})});try{if(t!==0)throw new v({code:t,message:$({key:B.EXCHANGE_SDP_FAILED,data:{errMsg:r}})});this._log.debug(`accept remote answer: ${n}`),yield this.setAnswer({type:s,sdp:n}),this.updateSSRC(n)}catch(a){throw this._log.error(a),a}})}updateSSRC(e){try{De(e).media.forEach(r=>{if(r.ssrcs)if(r.type===_.AUDIO){let s=r.ssrcs.find(n=>{var a;return(a=n.value)==null?void 0:a.includes(Vs)});s&&(this.ssrc.audio=Number(s.id))}else{let s=r.ssrcs.find(a=>{var d;return(d=a.value)==null?void 0:d.includes(Vs)}),n=r.ssrcs.find(a=>{var d;return(d=a.value)==null?void 0:d.includes(zc)});s&&(this.ssrc.video=Number(s.id)),n&&(this.ssrc.auxiliary=Number(n.id))}})}catch(t){}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return f(this,null,function*(){if(!(Le(Ns.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch(t){let r=Zt(this._reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${r/1e3}s`),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},r)}})}getIsReconnecting(){return this._isReconnecting}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}getCurrentState(){return this._currentState}setDelay({audioDelay:e,videoDelay:t}){this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=t}get audioReceiver(){var e;return((e=this._peerConnection)==null?void 0:e.getReceivers()[0])||null}};D([Y(e=>function(...t){return new Promise((r,s)=>{let n=a=>{this._emitter.off("closed",n),s(new v({code:I.API_CALL_ABORTED,message:$({key:B.CONNECTION_ABORTED,data:a})}))};this._emitter.on("closed",n),e.apply(this,t).then(r,s).finally(()=>{this._emitter.off("closed",n)})})})],Ns.prototype,"subscribe",1),D([Rt(521717,!1)],Ns.prototype,"unsubscribe",1),D([Ct(ft.prototype.afterConnect),Md(ft.prototype.beforeConnect)],Ns.prototype,"connect",1);var Qh=Ns,Yh=Qh;var h_={voiceActivityDetection:!1},vs=class vs extends ft{constructor(e){super(w(M({},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)}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,s=super.emitConnectionStateChangedEvent(e);return s&&r!==e&&(t?t.emit("connection-state-changed",{prevState:r,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:r,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:r,state:e}),(d=this._publishingLocalVideoTrack)==null||d.emit("connection-state-changed",{prevState:r,state:e}))),s}publish(s){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:r}){this._peerConnection||this.initialize(),e&&(this._publishingLocalAudioTrack=e),t&&(this._publishingLocalVideoTrack=t),this._isPublishingAux=r;let n;t&&!r&&t.small&&(n=this._room.videoManager.smallTrack),this.sendMediaSettings(),St()?yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:n,isAuxiliary:r}):yield this.publishByAddTrack({localAudioTrack:e,localVideoTrack:t,smallTrack:n}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,r?(t&&(this.localAuxVideoTrack=t),e&&(this.localAuxAudioTrack=e)):(t&&(this.localMainVideoTrack=t),e&&(this.localMainAudioTrack=e)),this.installTrackMuteEvents(e,t),this.sendMutedFlag()})}publishByTransceiver(n){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:r,isAuxiliary:s}){this._log.info("publish by transceiver");let a=new MediaStream,d=t==null?void 0:t.outMediaTrack,l=e==null?void 0:e.outMediaTrack;l&&a.addTrack(l),d&&a.addTrack(d);let u=this._peerConnection.getTransceivers();if(u.length===0)this._peerConnection.addTransceiver(l||_.AUDIO,{direction:ne.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(s?_.VIDEO:d||_.VIDEO,{direction:ne.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(r||_.VIDEO,{direction:ne.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(s?d||_.VIDEO:_.VIDEO,{direction:ne.SENDONLY,streams:[a]}),yield this.connect();else{let h=[];if(l&&(u[0].sender.track||h.push(0),yield u[0].sender.replaceTrack(l),yield this.setBandwidth({bandwidth:(e==null?void 0:e.profile.bitrate)||40,type:_.AUDIO})),d){let p=s?3:1;yield u[p].sender.replaceTrack(d),yield this.setBandwidth({bandwidth:t.profile.bitrate,type:_.VIDEO,videoType:s?_.AUXILIARY:_.BIG}),h.push(p),r&&(yield u[2].sender.replaceTrack(r),yield this.setBandwidth({bandwidth:t.small.bitrate,type:_.VIDEO,videoType:_.SMALL}),h.push(2))}yield this.setTransceiverDirection(ne.SENDONLY,h),yield this.doPublishChange(),t==null||t.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),t==null||t.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"})}})}publishByAddTrack(s){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:r}){this._log.info("publish by addtrack");let n=t==null?void 0:t.outMediaTrack,a=e==null?void 0:e.outMediaTrack;if(this._peerConnection&&this._peerConnection.connectionState!=="new"){e&&a&&(yield this.addTrack(e)),n&&(yield this.addTrack(t));return}let d=new MediaStream;if(a&&d.addTrack(a),n&&d.addTrack(n),a&&this._peerConnection.addTrack(a,d),n&&(this._peerConnection.addTrack(n,d),r)){let l=new MediaStream;l.addTrack(r),this._peerConnection.addTrack(r,l)}yield this.connect()})}enableSmall(e){return f(this,null,function*(){let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.setTransceiverDirection(ne.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(ne.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()})}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(r){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){if(!yr()){if(e&&e.outMediaTrack&&!t&&this.localMainVideoTrack){yield this.removeTrack(e),this.localMainAudioTrack=null;return}if(t&&t.outMediaTrack&&!e&&this.localMainAudioTrack){yield this.removeTrack(t),this.localMainVideoTrack=null;return}yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),this.emitConnectionStateChangedEvent("DISCONNECTED",t);return}let s=t&&t===this.localAuxVideoTrack,n=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),d=[];e&&(s?this.localAuxAudioTrack=null:this.localMainAudioTrack=null,!this.localAuxAudioTrack&&!this.localMainAudioTrack&&(yield a[0].replaceTrack(null),d.push(0))),n&&(s?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=w(M({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),d.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=w(M({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),d.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.setTransceiverDirection(ne.INACTIVE,d),yield this.doPublishChange(!1)):yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),t==null||t.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return f(this,null,function*(){let t={state:this._room.publishState,constraintConfig:this._mediaSettings},r=yield this._signalChannel.sendWaitForResponse({command:Z.PUBLISH_STATE_CHANGE,data:t,responseCommand:J.PUBLISH_STATE_CHANGE_RESULT,enableLog:e});this.checkPublishResultCode(r.data.code,r.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:Z.UNPUBLISH,commandDesc:"unpublish",responseCommand:J.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===I.API_CALL_TIMEOUT)return Promise.resolve();throw t})}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let r=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:s,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:s=this._publishingLocalVideoTrack),Ni){if(r&&r.outMediaTrack){let a=r.outMediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=r.profile.bitrate*1e3,this._mediaSettings.audioFs=a.sampleRate||0}if(s&&s.outMediaTrack){let a=s.outMediaTrack.getSettings();this._mediaSettings.videoWidth=a.width||0,this._mediaSettings.videoHeight=a.height||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=s.profile.bitrate*1e3,s.small&&(this._mediaSettings.smallVideoWidth=s.small.width,this._mediaSettings.smallVideoHeight=s.small.height,this._mediaSettings.smallVideoFps=s.small.frameRate,this._mediaSettings.smallVideoBps=s.small.bitrate*1e3)}if(n&&n.outMediaTrack){let a=n.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=a.width||0,this._mediaSettings.auxVideoHeight=a.height||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=n.profile.bitrate*1e3}}else r&&r.outMediaTrack&&(this._mediaSettings.audioChannel=r.profile.channelCount,this._mediaSettings.audioBps=r.profile.bitrate*1e3,this._mediaSettings.audioFs=r.profile.sampleRate),s&&s.outMediaTrack&&(this._mediaSettings.videoWidth=s.profile.width,this._mediaSettings.videoHeight=s.profile.height,this._mediaSettings.videoFps=s.profile.frameRate,this._mediaSettings.videoBps=s.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:Z.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:J.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return f(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is adding ${e.kind} track to current published local ${t?_.AUXILIARY:_.MAIN} stream`),St()?yield this.addTrackByTransceiver(e,t):yield this.addTrackBySender(e)})}addTrackByTransceiver(e,t){return f(this,null,function*(){var s;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===_.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),n===1&&((s=this.localMainVideoTrack)!=null&&s.small)&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===ne.INACTIVE&&(yield this.setTransceiverDirection(ne.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}addTrackBySender(e){return f(this,null,function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;yr()&&this._peerConnection.getTransceivers().findIndex(s=>s.direction==="stopped")>=0&&(this._log.warn("transceiver is stopping, negotiate sdp first"),yield this.updateOffer("remove",t));let r=this._peerConnection.getSenders().find(s=>s.track&&s.track.kind===t.kind);if(r&&r.track){this._log.warn("sender already exists, remove sender first");let s=r.track;this.removeSender(r),yield this.updateOffer("remove",s)}if(t&&this._peerConnection.addTrack(t,new MediaStream([t])),t.kind===_.VIDEO&&e instanceof je&&e.small){let s=new MediaStream,{smallTrack:n}=this._room.videoManager;s.addTrack(n),this._peerConnection.addTrack(n,s)}yield this.updateOffer("add",t)})}isNeedToResetOfferOrder(){if(this._sdpSemantics===Mo||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=De(e);for(let r=0;r<t.media.length;r++)if(Number(t.media[r].mid)===0&&t.media[r].type===_.VIDEO)return!0;return!1}removeSender(e){let t=null;yr()&&(t=this._peerConnection.getTransceivers().find(r=>r.sender&&r.sender.track===e.track)),this._peerConnection.removeTrack(e),t&&le(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return f(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${t?_.AUXILIARY:_.MAIN} stream`),St()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)})}removeTrackByTransceiver(e,t){return f(this,null,function*(){if(!e.outMediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===_.AUDIO)yield r[0].sender.replaceTrack(null);else{let s=t?3:1;yield r[s].sender.replaceTrack(null),s===1&&e.small&&(yield r[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(ne.INACTIVE,[s])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,t){return f(this,null,function*(){if(!ee)return;let r=!1,s=!1;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let n=this._peerConnection.getTransceivers();if(t.forEach(l=>{n[l].direction!==e&&(n[l].direction=e,r=!0)}),r){this._log.info("updating offer");let l=yield this._peerConnection.createOffer();yield this.setOffer(l)}let a=-1,d=this._peerConnection.remoteDescription.sdp.split(`\r
61
- `).map(l=>{if(l.match(new RegExp(`a=(${ne.INACTIVE}|${ne.RECVONLY}|${ne.SENDONLY})`))&&a++,t.includes(a)){if(e===ne.INACTIVE&&l.includes(`a=${ne.RECVONLY}`))return s=!0,`a=${e}`;if(e===ne.SENDONLY&&l.includes(`a=${ne.INACTIVE}`))return s=!0,`a=${ne.RECVONLY}`}return l}).join(`\r
62
- `);s&&(this._log.info("updating answer"),yield this.setAnswer({type:"answer",sdp:d}))})}removeTrackBySender(e){return f(this,null,function*(){if(!e.outMediaTrack)return;if(e.kind===_.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===_.VIDEO&&e.small&&this._peerConnection.getSenders().forEach(r=>{r.track&&r.track.kind===_.VIDEO&&this.removeSender(r)})),yield this.updateOffer("remove",e.outMediaTrack)})}replaceTrack(e){return f(this,null,function*(){var n;let t=(n=this._peerConnection)==null?void 0:n.getSenders();if(!t||t.length===0||!e.mediaTrack)return!1;let r;if(St()?r=e.kind===_.AUDIO?t[0]:t[1]:r=t.find(a=>a.track&&a.track.kind===e.kind),!r)return!1;let s=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info(`is replacing ${e.kind} track on ${s?_.AUXILIARY:_.MAIN} stream`),e.kind===_.AUDIO?yield r.replaceTrack(e.outMediaTrack):e.kind===_.VIDEO&&(s?t[3]&&(yield t[3].replaceTrack(e.outMediaTrack)):yield r.replaceTrack(e.outMediaTrack)),!0})}updateOffer(e,t){return f(this,null,function*(){try{let r=yield this._peerConnection.createOffer(h_);ee&&r.sdp&&(r.sdp=this.setSDPDirection(r.sdp,"sendrecv")),yield this.setOffer(r);let s=this.updateMediaSettings(),n={action:e,trackId:t.id,kind:t.kind===_.VIDEO?"bigVideo":t.kind,type:"offer",sdp:this._peerConnection.localDescription.sdp,constraintConfig:s,state:this._room.publishState};this._log.info("createOffer success, sending updated offer to remote server"),this._log.debug(`updatedOffer: ${n.sdp}`);let a=yield this._signalChannel.sendWaitForResponse({command:Z.PUBLISH_CHANGE,data:n,responseCommand:J.UPDATE_OFFER_RESULT,timeout:Kc,commandDesc:"update offer"}),{code:d,message:l}=a.data;d!==0&&this.checkPublishResultCode(d,l),yield this.acceptAnswer(a.data.data),r.sdp&&this.updateSSRC(r.sdp)}catch(r){throw this._log.error(r),r}})}setBandwidth(n){return f(this,arguments,function*({bandwidth:e,type:t,videoType:r,sdp:s}){if(!gn())return s?t===_.VIDEO?this.updateVideoBandwidthRestriction(s,e,r):this.updateAudioBandwidthRestriction(s,e):void 0;let a,d=this._peerConnection.getSenders();if(St()){let l=0;t===_.VIDEO&&(r===_.SMALL?l=2:r===_.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`),s}catch(u){if(this._log.info(`failed to set bandwidth by setting maxBitrate: ${u}`),s)return t===_.VIDEO?this.updateVideoBandwidthRestriction(s,e,r):this.updateAudioBandwidthRestriction(s,e)}}return s})}updateVideoBandwidthRestriction(e,t,r){let s="AS";ee&&(s="TIAS",t=t*1e3);let n=0,a=-1;return r===_.SMALL?n=1:r===_.AUXILIARY&&(n=2),e=e.replace(/m=video (.*)\r\nc=IN (.*)\r\n/g,d=>(a+=1,a===n?`${d}b=${s}:${t}\r
63
- `:d)),e}updateAudioBandwidthRestriction(e,t){let r="AS";return ee&&(r="TIAS",t=t*1e3),e=e.replace(/m=audio (.*)\r\nc=IN (.*)\r\n/,`m=audio $1\r
64
+ ${r.stack}`),!1}},o};var bs=new WeakMap;function Xf(o){let i=bs.get(o);i&&(i.forEach(e=>clearTimeout(e)),bs.delete(o))}function zf(o,i){return Y((e,t)=>function(...r){let s=bs.get(this);s||(s=new Map,bs.set(this,s));let n=i(...r),a=s.get(n);if(!a||a<=0){e.apply(this,r);let c=setTimeout(()=>{var l;(l=bs.get(this))==null||l.delete(n)},o);s.set(n,c)}else{clearTimeout(a);let c=window.setTimeout(()=>{var l;e.apply(this,r),(l=bs.get(this))==null||l.delete(n)},o);s.set(n,c)}})}var Yf="trtc-sdk-v5",Bh="5.15.0-beta.21";function st(...o){return Y((i,e)=>function(...t){try{Td.call(this,o,t,e,this._name)}catch(r){return Promise.reject(r)}return i.apply(this,t)})}function Hh(...o){return Y((i,e)=>function(...t){try{Td.call(this,o,t,e,this._name)}catch(r){throw r}return i.apply(this,t)})}function Td(o,i,e,t){if(Ae(o))for(let r=0;r<o.length;r++)gd.call(this,{rule:o[r],value:i[r],key:o[r].name,fnName:e,className:t});else gd.call(this,{rule:o,value:i[0],key:o.name,fnName:e,className:t})}function gd({rule:o,value:i,key:e,fnName:t,className:r}){function s(c){return{code:x.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:o,value:i}}}if(T(i)){if(o.required)throw new F(s(5001));if(T(o.defaultValue)){me(o.validate)&&o.validate.call(this,i,e,t,r,this);return}i=o.defaultValue}if(Array.isArray(o.type)){let c=!1;for(let l=0;l<o.type.length;l++)o.type[l]===null&&i===null&&(c=!0),me(o.type[l])&&i instanceof o.type[l]&&(c=!0),re(o.type[l])&&Oe(i)===o.type[l].toLowerCase()&&(c=!0);if(!c)throw new F({code:x.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:o.type.map(l=>jr(l)?Vo(l):re(l)?l:Oe(l))},value:i}})}else if(!T(o.type)&&Oe(i)!==o.type)throw new F(s(5002));if(o.allowEmpty===!1){let c=Q(i)&&(i===0||Number.isNaN(i)),l=re(i)&&i.trim()==="";if(c||l)throw new F(s(5003))}if(o.notLessThanZero&&Q(i)&&i<0)throw new F(s(5006));if(!T(o.min)&&Q(i)&&i<o.min)throw new F(s(5007));if(!T(o.max)&&Q(i)&&i>o.max)throw new F(s(5008));if(re(o.instanceOf)){if(!i||i._name!==o.instanceOf)throw new F(s(5004))}else if(me(o.instanceOf)&&!(i instanceof o.instanceOf))throw new F(s(5004));if(Array.isArray(o.values)&&!o.values.includes(i))throw new F(s(5005));let{properties:n}=o;dt(n)&&yt(i)&&Object.keys(n).forEach(c=>{gd.call(this,{rule:n[c],value:i&&i[c],key:`${c}`,fnName:t,className:r})});let{arrayItem:a}=o;dt(a)&&Ae(i)&&i.forEach((c,l)=>{gd.call(this,{rule:a,value:c,key:`${e}[${l}]`,fnName:t,className:r})}),me(o.validate)&&o.validate.call(this,i,e,t,r,this)}function Re(o={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t,ignoreLog:r,ignoreErrorLog:s}=o;return Y((n,a)=>function(...c){var _,g,E;function l(A,k,se){if(se&&se.includes(A))return"hided";if(e){let w=e(...c);if(c[w.argIndex]===k)return w.value}if(k===c||A in c)return k;try{return k instanceof HTMLElement?`id: ${k.id} type:${Oe(k)}`:k instanceof MediaStreamTrack?wa(k):(JSON.stringify(k),k)}catch(w){return`type:${Oe(k)}`}}let h=this._log||R;if(r!=null&&r(...c))return n.apply(this,c);c.length>0?h.info(`${a}() ${JSON.stringify(c,(A,k)=>l(A,k,["userSig","privateMapKey"]))}`):h.info(`${a}()`);let m=t?t(...c):_c[a],u=(s==null?void 0:s(...c))||!1;try{let A=n.apply(this,c),k=V();if(Er(A)){let se=`${a.includes("Plugin")?`${((g=(_=c[0]).getName)==null?void 0:g.call(_))||""} `:" "}`;return A.then(w=>(h.info(`${a}() success ${se}${i.call(this,...c)}`),v.addSuccessEvent({key:m,cost:V()-k}),w)).catch(w=>{var q;w=F.convertFrom.call(this,w,a,c.length===1?c[0]:c);let Ze=w.extraCode||w.code,N=(q=w.message)!=null&&q.includes(Ze)?"":` code:${Ze}`,y=(w==null?void 0:w.code)===x.OPERATION_ABORT;throw u||h[y?"warn":"error"](`${a}() failed ${se}${i.call(this,...c)} ${w}${N} params: ${JSON.stringify(c,l)}`),v.addFailedEvent({key:m,error:w}),w})}return v.addSuccessEvent({key:m}),A}catch(A){A=F.convertFrom.call(this,A,a);let k=A.extraCode||A.code,se=(E=A.message)!=null&&E.includes(k)?"":` code:${k}`,w=(A==null?void 0:A.code)===x.OPERATION_ABORT;throw u||h[w?"warn":"error"](`${a}() failed ${A}${se} params: ${JSON.stringify(c,l)}`),v.addFailedEvent({key:m,error:A}),A}})}var Ed=o=>Y((i,e)=>function(t,r){return f(this,null,function*(){let s=this._plugins.get(t);if(!s)throw this._log.error(`plugin ${String(t)} is not found`),new F({code:x.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});if(me(s.constructor.isSupported)&&!s.constructor.isSupported())throw this._log.error(`plugin ${String(t)} is not supported`),new F({code:x.ENV_NOT_SUPPORTED,message:`plugin ${String(t)} is not supported`,extraCode:5210,fnName:e});return Td.call(this,s.getValidateRule(o),[r],e,"TRTC"),i.call(this,s,r)})});var Sd=0,$h,ar=class ar{constructor(i){this.core=i;d(this,"log");d(this,"customAudioReferenceMap",new Map);d(this,"audioRefId",0);d(this,"audioContext",Se());d(this,"localAudioWorkletNode");d(this,"screenAudioWorkletNode");d(this,"mixNode");d(this,"silentNode");Sd=Sd+1,this.log=i.log.createChild({id:`${this.getAlias()}${Sd}`}),this.log.info(`created id=${this.getAlias()}${Sd}`),this.installEvent()}static getStartValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,t,r,s){if(!i.room.audioManager.hasAudioTrack&&!i.room.audioManager.hasScreenAudioTrack)throw new F({code:x.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return $h||($h=this.doPreload(i)),$h}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield tr(this.audioContext,t)}catch(r){this.log.error(`preload audioProcessor failed. ${r}`)}finally{URL.revokeObjectURL(t)}})}getName(){return ar.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(i){switch(i){case"start":return ar.getStartValidateRule(this.core);case"update":return ar.updateValidateRule;case"stop":return ar.stopValidateRule}}start(i){return f(this,null,function*(){var u,_,g,E;let{room:e}=this.core,{sdkAppId:t,userId:r,userSig:s,assetsPath:n=this.core.assetsPath,audioReference:a,processLevel:c,enableDump:l,isLocalAudioNeedAudioProcess:h=!0,isScreenAudioNeedAudioProcess:m=!1}=i;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=h,this.core.room.audioManager.isScreenAudioNeedAudioProcess=m,!n)throw new F({code:x.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload(`${n}/audioProcessor-wasm.js`),h&&!this.localAudioWorkletNode){let{sign:A,status:k,timestamp:se}=yield this.getAuthData(t,r,s);this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",t,r,se,A,k,e)}if(m&&!this.screenAudioWorkletNode){let{sign:A,status:k,timestamp:se}=yield this.getAuthData(t,r,s);this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",t,r,se,A,k,e)}this.mixNode||(this.mixNode=this.audioContext.createGain(),this.mixNode.gain.value=1),this.silentNode||(this.silentNode=this.audioContext.createConstantSource(),this.silentNode.offset.setValueAtTime(0,this.audioContext.currentTime),this.silentNode.start()),(u=this.localAudioWorkletNode)==null||u.port.postMessage({type:"enable"}),(_=this.screenAudioWorkletNode)==null||_.port.postMessage({type:"enable"}),e.audioManager.addAudioProcessor(this.mixNode,this.silentNode,this.localAudioWorkletNode,this.screenAudioWorkletNode),T(a)||a.forEach(A=>{this.customAudioReferenceMap.set(A,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:A,refId:`o-${this.audioRefId++}`})}),T(c)||(g=this.localAudioWorkletNode)==null||g.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:c}}),T(l)||(E=this.localAudioWorkletNode)==null||E.port.postMessage({type:"dump",data:{enable:l}})})}update(i){return f(this,null,function*(){var s,n,a;let{audioReference:e,enableDump:t,processLevel:r}=i;T(e)||(this.customAudioReferenceMap.forEach((c,l)=>{this.customAudioReferenceMap.delete(l),this.core.room.audioManager.updateAudioReference({type:"remove",refId:c})}),e.forEach(c=>{this.customAudioReferenceMap.set(c,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:c,refId:`o-${this.audioRefId++}`})})),T(r)||(s=this.localAudioWorkletNode)==null||s.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:r}}),T(t)||((n=this.localAudioWorkletNode)==null||n.port.postMessage({type:"dump",data:{enable:t}}),(a=this.screenAudioWorkletNode)==null||a.port.postMessage({type:"dump",data:{enable:t}}))})}stop(){return f(this,null,function*(){var e,t;let{room:i}=this.core;(e=this.localAudioWorkletNode)==null||e.port.postMessage({type:"disable"}),(t=this.screenAudioWorkletNode)==null||t.port.postMessage({type:"disable"}),yield i.audioManager.removeAudioProcessor(this.localAudioWorkletNode,this.screenAudioWorkletNode)})}destroy(){this.localAudioWorkletNode&&(this.localAudioWorkletNode.port.onmessage=null),this.screenAudioWorkletNode&&(this.screenAudioWorkletNode.port.onmessage=null),this.uninstallEvent()}getAuthData(i,e,t){return f(this,null,function*(){let r=String(Date.now()).slice(0,-3),{auth:s,sign:n,status:a,message:c}=yield ZS({sdkAppId:i,userSig:t,userId:e,timestamp:r});if(!s)throw this.log.info(`audioProcessor: ${e} auth result: ${s}. Message: ${c}`),new F({code:x.INVALID_PARAMETER,message:c});return{sign:n,status:a,timestamp:r}})}initWorkletNode(i,e,t,r,s,n,a,c){i.port.postMessage({type:"init",data:{sdkAppId:String(t),userId:r,timestamp:s,sign:n,status:a}}),i.port.onmessage=l=>{var m;let{data:h}=l;switch(h.type){case"cost":let u=(h==null?void 0:h.value)>10?"info":"debug";this.log[u](`${e==="localAudio"?"":`[${e}] `}avg cost: ${h.value} max: ${h==null?void 0:h.max}(${Mo(new Date(h==null?void 0:h.maxCostTimestamp))}) hist: ${(m=h==null?void 0:h.hist)==null?void 0:m.join(" ")}`);return;case"log":this.log[h.logLevel](`${e==="localAudio"?"":`[${e}] `}${h.value}`);return;case"dump":S.emit("265",{room:c,data:h.value,type:e==="localAudio"?"dump":"dump-screen-audio"});return}}}handleLocalAudioStarted(i){return f(this,null,function*(){var e;if(!(!this.hitTest(i.room)||((e=this.core.room.scheduleResult.config)==null?void 0:e.audioProcessor)!==!0))try{yield this.core.trtc.startPlugin("AudioProcessor",{sdkAppId:this.core.room.sdkAppId,userId:this.core.room.userId,userSig:this.core.room.userSig}),this.log.warn("audio processor auto start success")}catch(t){this.log.warn(`audio processor auto start failed, error: ${t}`)}})}handleLocalAudioStopped(i){return f(this,null,function*(){var e;!this.hitTest(i.room)||((e=this.core.room.scheduleResult.config)==null?void 0:e.audioProcessor)!==!0||(yield this.core.trtc.stopPlugin("AudioProcessor"))})}installEvent(){this.core.innerEmitter.on("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.on("114",this.handleLocalAudioStopped,this)}uninstallEvent(){this.core.innerEmitter.off("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.off("114",this.handleLocalAudioStopped,this)}hitTest(i){return i===this.core.room}};d(ar,"updateValidateRule",{type:"object"}),d(ar,"stopValidateRule",{type:"object"}),d(ar,"Name","AudioProcessor");var Id=ar;function YS(o,i=p.MAIN){return`https://${wi[i]||fd(o,i)}/api/v1/audioAiAuth`}function ZS(r){return f(this,arguments,function*({sdkAppId:o,userId:i,userSig:e,timestamp:t}){let n=`${YS(o)}?sdkAppId=${o}&userId=${i}&userSig=${e}&timestamp=${t}`,a=yield fetch(n),{data:{errCode:c,errMsg:l,sign:h,status:m}}=yield a.json();if(m==="1")return{auth:!0,sign:h,status:m,message:l};let u=Vt(o)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",_="Init RTCAudioProcessor failed.",g="";switch(c){case 1:g="Please check your params.";break;case 2:g=`You need to buy packages. Refer to: ${u}`;break;case 3:g="Server is invalid. Please contact our engineer. ";break;case 4:g=`Your packages is not active. Refer to: ${u}`;break;case 5:g=`Your packages is expired. Refer to: ${u}`;break;case 6:g="Your version is not supported.";break}return{auth:!1,status:m,message:l?`${_} Reason: ${l}. ${g}`:`${_}, ${g}`}})}var Ad=0,Gh=class{constructor(i,e){d(this,"audioObjectURL");d(this,"player");d(this,"publisher");d(this,"mixInput");this.mixInput=new ls(e),i.url?(this.player=new Audio(i.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(i.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(i.track),this.mixInput.connect()}updateSettings(i){this.player&&(T(i.volume)||(this.volume=i.volume),T(i.loop)||(this.loop=i.loop),T(i.playbackRate)||(this.playbackRate=i.playbackRate))}updateListener(i){if(this.player){if(i.onDurationChange){let{onDurationChange:e}=i;this.player.ondurationchange=t=>{e(t.target.duration)}}if(i.onTimeUpdate){let e=i.onTimeUpdate,{player:t}=this;t.ontimeupdate=()=>{e(t.currentTime,t.duration)}}i.onEnded&&(this.player.onended=i.onEnded)}}reload(i){return f(this,null,function*(){if(i.url){let e=yield Qn.download(i.url,{retries:3,type:"blob"});this.audioObjectURL&&URL.revokeObjectURL(this.audioObjectURL),this.audioObjectURL=URL.createObjectURL(e),this.player&&this.publisher?(this.player.src=this.audioObjectURL,this.publisher.src=this.audioObjectURL):(this.player=new Audio(this.audioObjectURL),this.player.crossOrigin="anonymous",this.publisher=new Audio(this.audioObjectURL),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher),this.updateListener(i),this.updateSettings(i))}else this.mixInput.replaceSource(i.track)})}reset(){this.seek(0),this.mixInput.connect()}seek(i){this.player&&(i<0&&i>this.player.duration||(this.player.currentTime=i,this.publisher.currentTime=i))}play(){var i,e;return Promise.all([(i=this.player)==null?void 0:i.play(),(e=this.publisher)==null?void 0:e.play()])}pause(){var i,e;(i=this.player)==null||i.pause(),(e=this.publisher)==null||e.pause()}stop(){var i;(i=this.player)==null||i.pause(),this.mixInput.disconnect()}setOperation(i){i==="pause"&&this.pause(),i==="resume"&&(this.pause(),this.play()),i==="stop"&&(this.pause(),this.seek(0))}set volume(i){!this.player||!this.publisher||(this.player.volume=i,this.publisher.volume=i)}set loop(i){!this.player||!this.publisher||(this.player.loop=i,this.publisher.loop=i)}set playbackRate(i){!this.player||!this.publisher||(this.player.playbackRate=i,this.publisher.playbackRate=i)}};function vs(o,i){if(i&&typeof i!="function")throw new F({code:x.INVALID_PARAMETER,message:`start audioMixer plugin: param ${o} should be a function.`})}var Li=class Li{constructor(i){this.core=i;d(this,"log");d(this,"mixedMusicMap",new Map);d(this,"cacheMusicMap",new Map);Ad=Ad+1,this.log=i.log.createChild({id:`${this.getAlias()}${Ad}`}),this.log.info(`created id=${this.getAlias()}${Ad}`)}getName(){return Li.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return Li.startValidateRule;case"update":return Li.updateValidateRule;case"stop":return Li.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e}=this.core;this.core.validateSourceNode(),this.log.info(`add music source, id: ${i.id} url: ${i.url}, track: ${i.track}`);let{id:t,url:r}=i;if(this.mixedMusicMap.has(t))return;let s=this.cacheMusicMap.get(t);s?i.url?s.reset():(s.mixInput.replaceSource(i.track),s.mixInput.connect()):(s=new Gh(i,e.audioManager),this.cacheMusicMap.set(t,s)),s.updateListener(i),s.updateSettings(i);try{yield s.play()}catch(n){yield this.handleAutoPlayFailed(s,i,n)}this.mixedMusicMap.set(t,s),s.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"add",audioReference:s.mixInput.source.node,refId:`ax-${t}`}),this.log.info(`start mix audio track ${t} success.`),v.addEnum({key:502700,value:3}),this.kvUpload(i)})}handleAutoPlayFailed(i,e,t){return f(this,null,function*(){if(t.name==="NotSupportedError")this.log.error(`play failed, try to reload source. error: ${t}`),yield i.reload(e),yield i.play();else if(t.name==="NotAllowedError")if(this.core.room.enableAutoPlayDialog){let r=()=>{var s;(s=i.play())==null||s.finally(()=>{S.off("154",r,this)})};S.on("154",r,this),cs()}else this.core.trtc.emit(U.AUTOPLAY_FAILED,{userId:"",mediaType:"audio",resume:()=>f(this,null,function*(){return i.play()})});else throw t})}update(i){return f(this,null,function*(){let{id:e,operation:t,seekFrom:r,playbackRate:s}=i;this.log.info(`update music source, ${JSON.stringify(i)}`);let n=this.mixedMusicMap.get(e);if(!n){this.log.warn(`update music source failed, music id: ${e} not found.`);return}n.updateSettings(i),n.updateListener(i),T(t)||n.setOperation(t),T(r)||n.seek(r),this.kvUpload(i)})}stop(e){return f(this,arguments,function*({id:i}){if(this.mixedMusicMap.has(i)){this.log.info(`remove music source, music id: ${i}`);let t=this.mixedMusicMap.get(i);t!=null&&t.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:t.mixInput.source.node,refId:`ax-${i}`}),t==null||t.stop(),this.mixedMusicMap.delete(i)}i==="*"&&this.destroyAllMusic()})}kvUpload(i){let{track:e,loop:t,volume:r,playbackRate:s,operation:n,seekFrom:a,onTimeUpdate:c,onDurationChange:l,onEnded:h}=i;e&&v.addCount({key:502009}),t&&v.addCount({key:502001}),r&&v.addCount({key:502002}),s&&v.addCount({key:502003}),n&&v.addCount({key:502004}),a&&v.addCount({key:502005}),typeof c!="function"&&v.addCount({key:502007}),typeof h!="function"&&v.addCount({key:502008}),typeof l!="function"&&v.addCount({key:502006})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((i,e)=>{i!=null&&i.mixInput.track&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:i.mixInput.track,refId:e}),this.stop({id:e})})}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}};d(Li,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(i,e,t){if(i.url&&i.url!=="*"){let r=i.url.split("?")[0],s=["mp3","ogg","wav","flac"],n=r.split(".").pop(),a=s.indexOf(n)>=0,c=r.startsWith("blob"),l=r.startsWith("data");if(!(a||c||l))throw new F({code:x.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new F({code:x.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});vs("onTimeUpdate",i.onTimeUpdate),vs("onEnded",i.onEnded),vs("onDurationChange",i.onDurationChange)}}),d(Li,"updateValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},loop:{type:"boolean"},volume:{type:"number"},seekFrom:{type:"number"},operation:{type:"string",values:["pause","resume","stop"]}},validate(i,e,t){vs("onTimeUpdate",i.onTimeUpdate),vs("onEnded",i.onEnded),vs("onDurationChange",i.onDurationChange)}}),d(Li,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),d(Li,"Name","AudioMixer");var Cd=Li;var Rd=0,Wh,cr=class cr{constructor(i){this.core=i;d(this,"log");d(this,"audioContext",Se("denoiser"));d(this,"workletNode");d(this,"config",{enableFarFieldReduce:!1,farFieldReduceThreshold:.5});Rd=Rd+1,this.log=i.log.createChild({id:`${this.getAlias()}${Rd}`}),this.log.info(`created id=${this.getAlias()}${Rd}`)}static startValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0},mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}},validate(e,t,r,s){if(!i.room.audioManager.hasAudioTrack)throw new F({code:x.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return Wh||(Wh=this.doPreload(i)),Wh}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield tr(this.audioContext,t)}catch(r){throw this.log.error("load worklet failed",r),r}finally{URL.revokeObjectURL(t)}})}getName(){return cr.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser"}getValidateRule(i){switch(i){case"start":return cr.startValidateRule(this.core);case"update":return cr.updateValidateRule;case"stop":return cr.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e,schedule:t}=this.core,{assetsPath:r=this.core.assetsPath}=i;if(!r)throw new F({code:x.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload(`${r}/denoiser-wasm${gu()?"":"-nosimd"}.js`),!this.workletNode){let s=String(Date.now()).slice(0,-3),{auth:n,sign:a,status:c,message:l}=yield eI(t,L(O({},i),{timestamp:s}));if(!n)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${n}. Message: ${l}`),new F({code:x.INVALID_PARAMETER,message:l});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(i.sdkAppId),userId:i.userId,timestamp:s,sign:a,status:c}}),this.workletNode.port.onmessage=h=>{var u;let{data:m}=h;if(m.type==="cost"){let _=(m==null?void 0:m.max)>20?"warn":(m==null?void 0:m.max)>10?"info":"debug";this.log[_](`avg cost: ${m.value} max: ${m==null?void 0:m.max}(${Mo(new Date(m==null?void 0:m.maxCostTimestamp))}) hist: ${(u=m==null?void 0:m.hist)==null?void 0:u.join(" ")}`)}else m.type==="log"&&this.log[m.logLevel](`${m.value}`)}}this.updateConfig(i),this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(i){return f(this,null,function*(){this.updateConfig(i)})}stop(){return f(this,null,function*(){if(!this.workletNode)return;let{room:i}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield i.audioManager.removeDenoiser(this.workletNode)})}updateConfig(i){if(!this.workletNode)return;let e=!1;T(i.mode)||(i.mode===0?this.config.enableFarFieldReduce=!1:i.mode===1&&(this.config.enableFarFieldReduce=!0),e=!0),T(i.farFieldReduceThreshold)||(this.config.farFieldReduceThreshold=i.farFieldReduceThreshold,e=!0),e&&this.workletNode.port.postMessage({type:"setConfig",data:this.config})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};d(cr,"updateValidateRule",{type:"object",properties:{mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}}}),d(cr,"stopValidateRule",{type:"object"}),d(cr,"Name","AIDenoiser");var yd=cr;function eI(s,n){return f(this,arguments,function*(o,{sdkAppId:i,userId:e,userSig:t,timestamp:r}){try{let{data:{errCode:a,errMsg:c,sign:l,status:h}}=yield o.getAbilityConfig(i,o.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:i,userId:e,userSig:t,timestamp:r});if(h==="1")return{auth:!0,sign:l,status:h,message:c};let m=Vt(i)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",u="Init RTCAIDenoiser failed.",_="";switch(a){case 1:_="Please check your params.";break;case 2:_=`You need to buy packages. Refer to: ${m}`;break;case 3:_="Server is invalid. Please contact our engineer. ";break;case 4:_=`Your packages is not active. Refer to: ${m}`;break;case 5:_=`Your packages is expired. Refer to: ${m}`;break;case 6:_="Your version is not supported.";break}return{auth:!1,status:h,message:c?`${u} Reason: ${c}. ${_}`:`${u}, ${_}`}}catch(a){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${a}`}}})}var Kf=Je(at(),1);var qh=class extends Kf.EventEmitter{constructor(){super();d(this,"observer");d(this,"state","nominal");this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return f(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!fe&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){ne.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let t=this.stateNum,r=e[e.length-1];this.state=r.state,(this.stateNum>3||t>3)&&R.info(`${r.source}: ${r.state}`),this.emit("state-changed",{type:r.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(t){ne.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},tI=new qh,Jh=tI;var jh=0,Yn=class Yn{constructor(i){this.core=i;d(this,"log");d(this,"_seiMessageList",[]);d(this,"_smallSeiMessageList",[]);d(this,"_subStreamSeiMessageList",[]);jh++,this.log=i.log.createChild({id:`${this.getAlias()}${jh}`}),this.log.info(`[sei] created id=${this.getAlias()}${jh}`),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 Fh({frame:i,onSEI:t=>{t.forEach(r=>{e!=null&&e.userId?this.core.trtc.emit(U.SEI_MESSAGE,{seiPayloadType:r.seiPayloadType,data:r.seiPayload.buffer,userId:(e==null?void 0:e.userId)||"",streamType:(e==null?void 0:e.mediaType)===2?"sub":"main"}):this.core.innerEmitter.emit(this.core.INNER_EVENT.SEI_MESSAGE,{room:this.core.room,nalu:r})})}})}destroy(){this.log.debug("destroy"),this.stop(),delete this.core}getValidateRule(i){switch(i){case"start":return{type:"object"};case"update":return{type:"object"};case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:mi?this.encode:Vh,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:mi?this.decode:Fh,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update({buffer:i,options:e}){var s;let t=[e.seiPayloadType,i],r=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(t):(this._seiMessageList.push(t),r&&this._smallSeiMessageList.push(t)),(s=this.core.room.scriptTransformWorker)==null||s.postMessage({type:"sei",data:t,isMain:!e.toSubStream,small:r})}getName(){return Yn.Name}getAlias(){return"sei"}getGroup(){return"sei"}};d(Yn,"autoStart",!0),d(Yn,"Name","SEI");var bd=Yn;function Xh({frame:o,onDump:i}){return i==null||i(),o}function zh({frame:o,onDump:i}){return i==null||i(),o}var e_={"play() error: NotAllowedError:":{tips:o=>o.includes("main <video>")||o.includes("main <audio>")?"Remote stream auto play is restricted and playback fails":"Local stream playback failure, generally only occurs in Android WeChat devices, no need to handle",color:"red",class:"red"},"updateStream() try to recover local stream":{tips:"Device acquisition exception, automatic recovery is in progress"},"updateStream() recover local stream successfully":{tips:"Device acquisition exception, automatic recovery is successful"},"updateStream() failed to recover local stream":{tips:"Device acquisition exception, automatic recovery failed"},"main stream - video track is muted":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is muted":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is muted":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unable to provide media output":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is unable to provide media output":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is unable to provide media output":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unmuted":{tips:"Received enough playback video data"},"main stream - audio track is unmuted":{tips:"Received enough playback audio data"},"auxiliary stream - video track is unmuted":{tips:"Received enough playback screen sharing data"},"main stream - audio player track is ended":{tips:"Remote audio track stopped"},"main stream - video player track is ended":{tips:"Remote video track stopped"},"auxiliary stream - video player track is ended":{tips:"Received enough playback screen sharing data"},"stream - video track is muted":{tips:"Camera capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"stream - video track is unable to provide media output":{tips:"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked, and the customer needs to re-acquire. SDK v4.11.4+ will automatically resume acquisition without customer intervention",color:"orange"},"video track is unable to provide media output":{tips:o=>o.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"stream - audio track is muted":{tips:"Microphone capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"audio track is unable to provide media output":{tips:o=>o.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"Microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio track is unable to provide media output":{tips:"The microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"is adding audio track to current published local stream":{tips:"add audio track",color:"orange"},"is removing audio track from current published local stream":{tips:"remove audio track",color:"orange"},"is removing video track from current published local stream":{tips:"remove video track",color:"orange"},"is adding video track to current published local stream":{tips:"add video track",color:"orange"},"is replacing audio track to current published local main stream":{tips:"replace audio track",color:"orange"},"is replacing video track to current published local main stream":{tips:"replace video track",color:"orange"},"downlink network quality change":{tips:"Downstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"uplink network quality change":{tips:"Upstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"localStream mute video":{tips:"mute upstream video stream",color:"orange"},"localStream unmute video":{tips:"unmute upstream video stream",color:"orange"},"localStream mute audio":{tips:"mute upstream audio stream",color:"orange"},"localStream unmute audio":{tips:"unmute upstream audio stream",color:"orange"},"black detected":{tips:"Detect black screen, which means fps = 0. It is usually caused by network, and the network will be recovered after a while. If the network is normal but has not been restored, it is an abnormal situation."},'main stream start to play with options: {"muted":true}':{tips:"Play the remote stream in silent mode. Generally, the remote stream does not need to be played in silent mode. You need to confirm whether the parameters passed in the client stream.play API call are correct.",color:"orange"},"main stream - audio player is starting playing":{tips:"Remote stream audio playback success",color:"#0dd90d",class:"success"},"main stream - video player is starting playing":{tips:"Remote stream video playback success",color:"#0dd90d",class:"success"},"video player is playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"audio player is playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"stream - video player is starting playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"stream - audio player is starting playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"switch camera success":{tips:"Switch camera success",color:"#0dd90d",class:"success"},"switch microphone success":{tips:"Switch microphone success",color:"#0dd90d",class:"success"},gotStream:{tips:"Local stream capture success"},"local stream is published successfully":{tips:"Publish success",color:"#0dd90d",class:"success"},"encoderImplementation change to OpenH264":{tips:"Use software encoding"},"encoderImplementation change to ExternalEncoder":{tips:"Use hardware encoding"},"getUserMedia with constraints":{tips:"Start media (camera/microphone) capture"},"getDisplayMedia with constraints":{tips:"Start screen sharing capture"},"client-banned":{tips:"Kicked out of the room",color:"red",class:"red",textColor:"#fff"},user_timeout:{tips:"The backend is too long without receiving SDK heartbeat, which is usually caused by the JS thread being blocked for a long time. If the reproduction probability is high, the application browser Performance tool analyzes where the JS thread is blocked.",color:"red",class:"red",textColor:"#fff"},"schedule failed":{tips:"Signaling request failed, does not affect the normal room entry process, SDK will connect to the default signaling domain."},"updateStream() video flag is true, but no camera detected, set video to false":{tips:"When trying to resume camera acquisition, the camera acquisition is not resumed because it is detected that there is no camera.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to bandwidth":{tips:"bandwidth estimation is not enough to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to cpu":{tips:"cpu load is too high to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: hidden":{tips:"User page switched to backend, in mobile devices, this will cause the device to pause the capture, and it will be restored when the user switches backend to the frontend.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: visible":{tips:"User page switched to frontend",color:"orange",class:"orange",textColor:"#fff"},"main stream - audio player is paused":{tips:`The remote stream audio playback is paused, which usually has two possibilities:
65
+ 1. The business side passes in the div tag container for playing audio and video to be removed by the business side from the DOM.
66
+ 2. If the user is in Chrome 70 and below, when the div container is moved, the playback will be paused.`,color:"orange",class:"orange",textColor:"#fff"},"main stream - video player is paused":{tips:`The remote stream video playback is paused, which usually has two possibilities:
67
+ 1. The business side passes in the div tag container for playing audio and video to be removed by the business side from the DOM.
68
+ 2. If the user is in Chrome 70 and below, when the div container is moved, the playback will be paused.`,color:"orange",class:"orange",textColor:"#fff"},'"displaySurface":"window"':{tips:"Screen sharing captures the application window",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"monitor"':{tips:"Screen sharing captures the entire screen",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"browser"':{tips:"Screen sharing captures a certain tab page",color:"blue",class:"blue",textColor:"#fff"},updateMediaSettings:{tips:"The resolution and frame rate below are the actual resolution and frame rate captured",color:"blue",class:"blue",textColor:"#fff"},"main stream start to play with":{tips:"Call remoteStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"stream start to play with":{tips:"Call localStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"main setAudioVolume to 0":{tips:"Business side calls remoteStream.setAudioVolume(0) interface to set the playback volume to 0, which will cause the playback to be silent",color:"orange",class:"orange",textColor:"#fff"},"screen sharing was stopped because the video track is ended":{tips:"Screen sharing capture stopped, possible reasons: user clicks the stop button, the window/page shared by the user is closed, etc.",color:"orange",class:"orange",textColor:"#fff"},"Join() => joining room":{tips:"Call client.join interface",color:"blue",class:"blue",textColor:"#fff"},"publish() => publishing local stream":{tips:"Call client.publish interface",color:"blue",class:"blue",textColor:"#fff"},"subscribe() => subscribe to":{tips:"Call client.subscribe interface",color:"blue",class:"blue",textColor:"#fff"},"switchRole() => switch role":{tips:"Call client.switchRole interface",color:"blue",class:"blue",textColor:"#fff"}};["enterRoom","exitRoom","switchRole","destroy","startLocalAudio","updateLocalAudio","stopLocalAudio","startLocalVideo","updateLocalVideo","stopLocalVideo","startScreenShare","updateScreenShare","stopScreenShare","startRemoteVideo","updateRemoteVideo","stopRemoteVideo","muteRemoteAudio","setRemoteAudioVolume"].forEach(o=>{e_[`${o}()`]={tips:`Call trtc.${o}`,color:"blue",class:"blue",textColor:"#fff"}});var iU=Object.keys(e_);var iI=0,vd,Zn=class Zn{constructor(i){this.core=i;d(this,"_core");d(this,"log");d(this,"dumpLocalVideoMap",{});d(this,"dumpRemoteVideoMap",{});d(this,"dialog");this._core=i,this.log=i.log.createChild({id:`${this.getAlias()}${++iI}`}),this.log.info("created")}getName(){return Zn.Name}getAlias(){return"dm"}getGroup(){return"dm"}getValidateRule(i){switch(i){case"start":return{name:"StartDebugOptions",required:!1};case"update":return{name:"UpdateDebugOptions",required:!1};case"stop":return{name:"StopDebugOptions",required:!1}}}start(){return f(this,null,function*(){var e;!new URLSearchParams(location.search).has("trtcDebug")&&((e=window.sessionStorage)==null?void 0:e.getItem("TRTC_ENABLE_DEBUG_PLUGIN"))!=="true"||(yield this.openDebugDiaLog(),this.addVideoProcessor())})}update(e){return f(this,arguments,function*({visible:i}){i?(yield this.openDebugDiaLog(),this.addVideoProcessor()):(this.closeDebugDiaLog(),this.removeVideoProcessor())})}stop(){this.closeDebugDiaLog(),this.removeVideoProcessor()}destroy(){this.stop()}openDebugDiaLog(){return f(this,null,function*(){var i;if(!this.dialog)try{if(vd)yield vd;else{let e=new URLSearchParams(location.search).get("trtcDebugDialogPath")||((i=window.sessionStorage)==null?void 0:i.getItem("TRTC_DEBUG_DIALOG_PATH"))||`https://unpkg.com/${Yf}@${$e}/assets/debug-dialog.js`;vd=this._core.fileDownloader.loadScript(e),yield vd}this.dialog=new TRTCDebugDialog(this._core,this.log,this.dumpLocalVideoMap,this.dumpRemoteVideoMap),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(e){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(e))}})}closeDebugDiaLog(){this.dialog&&(this.dialog.closeDialog(),this.dialog=null)}addVideoProcessor(){this._core.room.videoManager.addEncodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.encodeVideo.bind(this):Xh,type:1}),this._core.room.videoManager.addDecodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.decodeVideo.bind(this):zh,type:1})}removeVideoProcessor(){this._core.room.videoManager.removeEncodeProcessor({type:1}),this._core.room.videoManager.removeDecodeProcessor({type:1})}encodeVideo({frame:i,mediaType:e}){return Xh({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 zh({frame:i,onDump:()=>{if(!e)return;let t=this.dumpRemoteVideoMap[`${e.userId}-${e.streamType}`];t&&(t.data.push(i.data.slice(0)),t.duration>0&&Date.now()-t.startTimestamp>t.duration*1e3&&t.onDumpEnd())}})}};d(Zn,"Name","Debug"),d(Zn,"autoStart",!0);var Nd=Zn;var t_=o=>{switch(o){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},Dd=class{constructor(i,e,t){d(this,"trackDoneOB");d(this,"startOB");d(this,"stopOB");d(this,"inputFrameCount",0);d(this,"decodedFrameCount",0);d(this,"type","auto");d(this,"config");d(this,"decoder");d(this,"_decodeSink");let{kvStatManager:r,trtc:s}=i;this.config=t.config,this.trackDoneOB=le(e,j.INIT),this.stopOB=ot(),this.startOB=ot(),t.type==="auto"?this.type="webCodecs":this.type=t.type;let n=ot(),a=c=>{let l=this.pipe(e);return n.next("STARTING"),e.log.info(`decoder type: ${this.type}`),ue(l,Pe(this.stopOB),Te(()=>{},h=>{e.log.error(h),r.addFailedEvent({key:t_(this.type),error:h}),c>4?this.startOB.error(h):this.startOB.next(c+1)})),ue(l,or(1),Sh(Hn))};ue(this.startOB,Fn(0),Or(a),Pe(this.stopOB),Te(()=>{e.player.setOutput(),n.next("STARTED")},c=>{n.next("FAILED")},()=>{r.addSuccessEvent({key:t_(this.type)}),r.addSuccessEvent({key:504702})}))}mock(i){this._decodeSink?this._decodeSink.error(i):this.startOB.next(0)}close(i){this.stopOB.next(i)}pipe(i){return rr()(e=>f(this,null,function*(){this._decodeSink=e,e.defer(()=>{var r;(r=this.decoder)==null||r.close()});let{type:t}=this;try{switch(t){case"webCodecs":this.decoder=new AudioDecoder({error:r=>{i.log.error(r),e.error(4)},output:r=>{this.decodedFrameCount++,e.next(r),i.player.write(r)}});break;case"wasm":break}this.decoder.configure(this.config)}catch(r){i.log.error(r),e.error(t==="webCodecs"?2:6)}}))}decodeFrame(i){var e;this.inputFrameCount++,((e=this.decoder)==null?void 0:e.state)==="configured"&&this.decoder.decode(new EncodedAudioChunk({data:i.data,timestamp:i.timestamp,type:"key"}))}},rI={type:"object"},Kn=class Kn{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 Kn.Name}getGroup(i){return i.track.userId+i.track.streamType}getName(){return Kn.Name}getValidateRule(i){return rI}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 Dd(this.core,t,i);return ue(r.trackDoneOB,or(1),Te(()=>{this.core.clearStarted(this,this.getGroup(i)),this.stop({track:t})})),this.contextMap.set(t,r),r.decodeFrame(e)}}stop({track:i}){let e=this.contextMap.get(i);e&&(e.close("stop"),this.contextMap.delete(i),this.contextMap.size===0&&this.core.room.audioManager.removeDecodeProcessor({type:3}))}update(i){let e=this.contextMap.get(i.track);if(e){if(i.type==="mock"){e.mock(10);return}e.close("update"),this.contextMap.set(i.track,new Dd(this.core,i.track,i))}}};d(Kn,"Name","TRTCAudioDecoder");var ea=Kn;var Md=class{constructor(){d(this,"log");this.log=R.createLogger({id:"exp"})}call(i,e){return f(this,null,function*(){return me(this[i])?this[i](e):Promise.reject(new D({code:I.INVALID_PARAMETER,message:$({key:B.API_NOT_EXIST,data:{name:i}})}))})}enableAudioFrameEvent(i){return f(this,null,function*(){let{trtcInstance:e,enable:t,userId:r,sampleRate:s=48e3,channelCount:n=1,port:a}=i,{audioManager:c}=e.room,{getPCMAbortCtrlMap:l,audioFrameEventConfigMap:h}=c;if(h.set(r,{enable:t,sampleRate:s,channelCount:n,port:a}),t)if(r==="*")e.room.remotePublishedUserMap.forEach(m=>{if(m.remoteAudioTrack.isAvailable){if(l.get(m.userId))return;let u=c.getPCM(_=>{e.emit(U.AUDIO_FRAME,_)},m.userId);l.set(m.userId,u)}});else{if(l.get(r))return;let m=c.getPCM(u=>{e.emit(U.AUDIO_FRAME,u)},r);l.set(r,m)}else if(r==="*")e.room.remotePublishedUserMap.forEach(m=>{if(m.remoteAudioTrack.isSubscribed){let{userId:u}=m,_=l.get(u);_==null||_.abort("disable"),l.delete(u)}});else{let m=l.get(r);m==null||m.abort("disable"),l.delete(r)}})}resumeRemotePlayer(i){return f(this,null,function*(){if(i.userId==="*"){let t=[];return i.trtcInstance.room.remotePublishedUserMap.forEach(r=>{let{remoteAudioTrack:s,remoteVideoTrack:n,remoteAuxiliaryTrack:a}=r;i.streamType?i.streamType==="main"?(s.isAvailable&&t.push(s.player.resume()),n.isAvailable&&t.push(n.player.resume())):a.isAvailable&&t.push(a.player.resume()):(s.isAvailable&&t.push(s.player.resume()),n.isAvailable&&t.push(n.player.resume()),a.isAvailable&&t.push(a.player.resume()))}),Promise.all(t)}let e=i.trtcInstance.room.remotePublishedUserMap.get(i.userId);if(e)return i.streamType==="main"?Promise.all([e.remoteAudioTrack.player.resume(),e.remoteVideoTrack.player.resume()]):e.remoteAuxiliaryTrack.player.resume()})}pauseRemotePlayer(i){if(i.userId==="*")i.trtcInstance.room.remotePublishedUserMap.forEach(e=>{let{remoteAudioTrack:t,remoteVideoTrack:r,remoteAuxiliaryTrack:s}=e;i.streamType?i.streamType==="main"?(t.isAvailable&&t.player.pause(),r.isAvailable&&r.player.pause(!1)):s.isAvailable&&s.player.pause(!1):(t.isAvailable&&t.player.pause(),r.isAvailable&&r.player.pause(!1),s.isAvailable&&s.player.pause(!1))});else{let e=i.trtcInstance.room.remotePublishedUserMap.get(i.userId);e&&(i.streamType==="main"?(e.remoteAudioTrack.player.pause(),e.remoteVideoTrack.player.pause(!1)):e.remoteAuxiliaryTrack.player.pause(!1))}}};M([bf({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"}}})],Md.prototype,"enableAudioFrameEvent",1);var i_=new Md;var r_=Je(at(),1);var Qh=class extends r_.EventEmitter{constructor(){super();d(this,"states",{});d(this,"permissionChangeHandler");d(this,"log");this.log=R.createLogger({id:"pm"}),this.permissionChangeHandler=()=>{var e,t;this.emit("permission-state-change",{camera:(e=this.states.camera)==null?void 0:e.state,microphone:(t=this.states.microphone)==null?void 0:t.state})}}request(e){return f(this,null,function*(){if(this.log.info(`request ${e.join(", ")}`),e.length===0)return Promise.resolve();(yield navigator.mediaDevices.getUserMedia({video:e.includes("camera"),audio:e.includes("microphone")})).getTracks().forEach(r=>r.stop())})}get(e){return f(this,null,function*(){try{return this.states[e]||(this.states[e]=yield navigator.permissions.query({name:e}),this.states[e].addEventListener("change",this.permissionChangeHandler)),this.log.info(`get ${e} permission state: ${this.states[e].state}`),this.states[e].state}catch(t){return this.log.error(`get ${e} permission failed, error: ${t instanceof Error?t.message:t}`),null}})}destroy(){Object.values(this.states).forEach(e=>{e==null||e.removeEventListener("change",this.permissionChangeHandler)}),this.states={}}},ta=new Qh;var o_=0,ia=new Set,Ye=null;Yd(Bh);is.checkStorage();var J=class J extends s_.EventEmitter{constructor(e,t){super();d(this,"_room");d(this,"_eventListened",new Set);d(this,"_localVideoTrack",null);d(this,"_localAudioTrack",null);d(this,"_localScreenTrack",null);d(this,"_localScreenAudioTrack",null);d(this,"_localVideoConfig",null);d(this,"_localScreenConfig",null);d(this,"_localAudioConfig",null);d(this,"_remoteVideoConfigMap",new Map);d(this,"_remoteAudioConfigMap",new Map);d(this,"_remoteAudioVolumeMap",new Map);d(this,"_remoteAudioMuteMap",new Map);d(this,"_mediaTrackMap",new WeakMap);d(this,"_log",R.createLogger({id:`t${++o_}`}));d(this,"_plugins",new Map);d(this,"_networkQuality",null);d(this,"_speakerId");d(this,"enterRoomParams");d(this,"_enableAutoSwitchWhenRecapturing",!0);this._room=new e(O({logger:this._log,frameWorkType:J.frameWorkType},t)),this._room.videoDecodeFallbackType=t.videoDecodeFallback,he(t.enableAutoSwitchWhenRecapturing)&&(this._enableAutoSwitchWhenRecapturing=t.enableAutoSwitchWhenRecapturing),this._log.info(`create() ${JSON.stringify(t,(r,s)=>r==="plugins"?s.map(n=>n.Name):s)}`),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(r){return this._room.audioManager.dump(r)}}}),t.plugins&&t.plugins.forEach(r=>{this._use(r,t.assetsPath)}),this._use(Cd,t.assetsPath),this._use(Id,t.assetsPath),this._use(yd,t.assetsPath),this._use(ea,t.assetsPath),this._use(Nd),t.enableSEI&&An&&this._use(bd),this._room.on("audio-volume",r=>{var s,n;!r.find(a=>a.userId==="")&&this._localAudioTrack&&r.push({userId:"",volume:Math.floor(((s=this._localAudioTrack.getInternalAudioLevelAfter3A())!=null?s:this._localAudioTrack.getAudioLevel())*100),floatVolume:(n=this._localAudioTrack.getInternalAudioLevelAfter3A())!=null?n:this._localAudioTrack.getInternalAudioLevel()}),t.volumeType===1&&r.forEach(a=>{var l;let c=a.userId===""?this._localAudioTrack:(l=this.room.remotePublishedUserMap.get(a.userId))==null?void 0:l.remoteAudioTrack;c&&(a.volume=c.dbVolume)}),t.enableDbVolume&&r.forEach(a=>{var l;let c=a.userId===""?this._localAudioTrack:(l=this.room.remotePublishedUserMap.get(a.userId))==null?void 0:l.remoteAudioTrack;c&&(a.volume=c.dbVolume)}),this.emit(U.AUDIO_VOLUME,{result:r.sort((a,c)=>c.volume-a.volume)})}),this._room.videoManager.on("error",r=>{this._log.error(new F({code:x.OPERATION_FAILED,extraCode:5504,message:r.message,originError:r}))}),this._listenEvents(),this._initActiveSpeaker(),jf(this,"trtc")}static create(e){}static _create(e,t){Df();let r=new J(e,t||{});return ia.add(r),r.__v_skip=!0,r}get room(){return this._room}_listenEvents(){tt(this,this._room).add("peer-join",e=>{let{userId:t}=e;this.emit(U.REMOTE_USER_ENTER,{userId:t})}).add("peer-leave",e=>{this.emit(U.REMOTE_USER_EXIT,{userId:e})}).add("banned",e=>{Lt(!0),this._exitRoom().finally(()=>{this.emit(U.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().finally(()=>{this.emit(U.ERROR,F.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(U.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let t=L(O({},e),{uplinkRTT:Math.min(e.uplinkRTT,Ws),downlinkRTT:Math.min(e.downlinkRTT,Ws)});this.emit(U.NETWORK_QUALITY,t)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(r=>{tt(r,r).add("player-state-changed",s=>{let n=L(O({},s),{userId:e.userId});r.kind===p.VIDEO&&(n.streamType=Pi(r.streamType)),this.emit(r.kind===p.AUDIO?U.AUDIO_PLAY_STATE_CHANGED:U.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",s=>{s.getCode()===I.PLAY_NOT_ALLOWED&&this.emit(U.AUTOPLAY_FAILED,{userId:r.userId,mediaType:r.strMediaType,resume:()=>r.player.resume()})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(r=>{xe(r)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:t})=>{let{userId:r}=t,s=e.audioAvailable,n=e.videoAvailable,{audioAvailable:a,videoAvailable:c}=t;a||this._remoteAudioConfigMap.delete(r),c||this._removeRemoteVideoConfig(r,"main"),t.hasAuxiliary||this._removeRemoteVideoConfig(r,"sub"),n!==c&&(c?this._onVideoAvailable({userId:r,streamType:"main"}):this._onVideoUnavailable({userId:r,streamType:"main"}),this.emit(c?U.REMOTE_VIDEO_AVAILABLE:U.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"main"})),s!==a&&(a?this._onAudioAvailable({userId:r}):this._onAudioUnavailable({userId:r,muteState:t}),this.emit(a?U.REMOTE_AUDIO_AVAILABLE:U.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?U.REMOTE_VIDEO_AVAILABLE:U.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"sub"}))}).add("sei-message",e=>{this.emit(U.SEI_MESSAGE,L(O({},e),{streamType:Pi(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(U.ERROR,new F({code:x.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var s,n,a,c,l,h,m;let t={2:"big",3:"small",7:"sub"},r={rtt:Math.min(e.msg_up_stream_info.msg_network_status.uint32_rtt||((s=e.msg_down_stream_info[0])==null?void 0:s.msg_network_status.uint32_rtt)||((n=this._networkQuality)==null?void 0:n.uplinkRTT)||((a=this._networkQuality)==null?void 0:a.downlinkRTT)||0,Ws),upLoss:((c=this._networkQuality)==null?void 0:c.uplinkLoss)||0,downLoss:((l=this._networkQuality)==null?void 0:l.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((h=e.msg_up_stream_info.msg_audio_status)==null?void 0:h.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((m=e.msg_up_stream_info.msg_audio_status)==null?void 0:m.uint32_audio_level)||0)/Dt},video:e.msg_up_stream_info.msg_video_status.filter(u=>t[u.uint32_video_stream_type]).map(u=>({bitrate:(u.uint32_video_codec_bitrate||0)/1e3,width:u.uint32_video_width,height:u.uint32_video_height,frameRate:u.uint32_video_enc_fps,videoType:t[u.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(u=>({userId:u.msg_user_info.str_identifier,audio:{bitrate:(u.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(u.msg_audio_status.uint32_audio_level||0)/Dt,point2pointDelay:(u.msg_audio_status.uint32_audio_p2p_delay||0)+(u.msg_audio_status.uint32_audio_cache_ms||0),jitterBufferDelay:u.msg_audio_status.uint32_audio_cache_ms||0},video:u.msg_video_status.map(_=>({bitrate:(_.uint32_video_codec_bitrate||0)/1e3,width:_.uint32_video_width,height:_.uint32_video_height,frameRate:_.uint32_video_dec_fps,videoType:t[_.uint32_video_stream_type],point2pointDelay:(_.uint32_video_p2p_delay||0)+(_.uint32_video_cache_ms||0),jitterBufferDelay:_.uint32_video_cache_ms||0,codec:_.uint32_video_codec}))}))};this.emit(U.STATISTICS,r)}).add("custom-message",e=>{this.emit(U.CUSTOM_MESSAGE,e)}).add("layerData",e=>this.emit(U.LAYER_DATA,e)).add("first-video-frame",e=>{this.emit(U.FIRST_VIDEO_FRAME,L(O({},e),{streamType:Pi(e.streamType)}))}).add("audio-frame",e=>{this.emit(U.AUDIO_FRAME,e)}),tt(this,ve).add("audioInputAdded",e=>{this.emit(U.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(U.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(U.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(U.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>f(this,null,function*(){if(this.emit(U.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Ye&&Ye.deviceId===Gs){let t=(yield Dr()).find(r=>r.deviceId===Gs);t&&Ye.groupId!==t.groupId&&(Ye=t,this.emit(U.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}})).add("audioOutputRemoved",e=>f(this,null,function*(){this.emit(U.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield Dr())[0];if(!t||!Ye||Ye.groupId===t.groupId)return;let r=Ye.deviceId===e.deviceId,s=Ye.deviceId===Gs&&Ye.deviceId===t.deviceId;(r||s)&&(Ye=t,this.emit(U.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))})),tt(this,ta).add("permission-state-change",e=>{this.emit(U.PERMISSION_STATE_CHANGE,e)}),this.room.enableSEI&&this.on(U.SEI_MESSAGE,e=>{var r;let t=(r=this.room.remotePublishedUserMap.get(e.userId))==null?void 0:r.remoteVideoTrack;t&&t.updateAlphaRenderInfo(e)})}getNetworkTime(){return Fi()}use(e){let t,r;return"plugin"in e?(t=e.plugin,r=e.assetsPath):t=e,t.Name==="Chorus"&&(this.room.enableChorus=!0),this._use(t,r)}_use(e,t){let r=this._plugins.get(e.Name);if(r)return this._log.warn("duplicate install plugin",e.Name),r;let s=new e(Jf.call(this,{TRTC:J,room:this._room,assetsPath:t,errorModule:{RtcError:F,ErrorCode:x,CoreErrorCode:I,ErrorCodeDictionary:wt}}));return this._plugins.set(e.Name,s),s.__v_skip=!0,e.autoStart&&this.startPlugin(e.Name),s}enterRoom(e){return f(this,null,function*(){var c,l;this.enterRoomParams=e;let{scene:t="rtc",enableAutoPlayDialog:r=!0,autoReceiveAudio:s=!0,autoReceiveVideo:n=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!re(e.proxy)&&e.proxy.turnServer&&((l=(c=this._room).setTurnServer)==null||l.call(c,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=r,this._room.autoReceiveAudio=s,this._room.autoReceiveVideo=n,he(e.preferHW)&&(this._room.preferHW=e.preferHW),e.playoutDelay&&(this._room.playoutDelay=e.playoutDelay),e.jitterBufferDelay&&(this._room.jitterBufferDelay=e.jitterBufferDelay);let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:e.role==="audience"?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language,priority:e.priority,useVp8:e.useVp8,useH265:e.useH265||!1,keepAlive:e.keepAlive,videoProfileLevel:e.videoProfileLevel};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(a,t,J.frameWorkType),this._checkTrackToPublish(),Jh.start()})}exitRoom(){return f(this,null,function*(){return yield this._exitRoom()})}switchRoom(e){return f(this,null,function*(){if(this.room.isSwitchRoomSupported())try{this._clearRemoteTracks(),yield this._room.switchRoom(e)}catch(t){if(t instanceof xs&&(t.code===I.API_CALL_TIMEOUT||t.code===I.SWITCH_ROOM_FAILED))this._log.warn(`switchRoom ${t.code===I.API_CALL_TIMEOUT?"timeout":"failed"}, fallback to exitRoom() and enterRoom()`),yield this._rejoinRoom(e);else throw t}else yield this._rejoinRoom(e)})}_rejoinRoom(e){return f(this,null,function*(){yield this.exitRoom();let t=O(O({},this.enterRoomParams),e);yield this.enterRoom(t)})}_clearRemoteTracks(){new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(e=>{this._stopRemoteAudio({userId:e}).catch(()=>{})}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let t=e.includes("main")?"main":"sub",r=e.split(`_${t}`)[0];r&&this._stopRemoteVideo({userId:r,streamType:t}).catch(()=>{})}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),Xf(this),this._room.remotePublishedUserMap.forEach(e=>{xe(e.remoteAudioTrack),xe(e.remoteVideoTrack),xe(e.remoteAuxiliaryTrack)})}switchRole(e,t){return f(this,null,function*(){t!=null&&t.privateMapKey&&(this._room.privateMapKey=t.privateMapKey),t!=null&&t.latencyLevel&&(this._room.latencyLevel=t.latencyLevel),yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){this._plugins.forEach(e=>{var t;return(t=e.destroy)==null?void 0:t.call(e)}),this._plugins.clear(),xe(this),this.removeAllListeners(),this._room.destroy(),ia.delete(this),ia.size===0&&Jh.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),S.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return f(this,arguments,function*(e={publish:!0}){if(this._localAudioTrack){this._log.warn("local audio is already started");return}let{publish:t=!0,mute:r,option:s}=e,n=new kt(this._room.audioManager),a={},c={muted:!0};s&&(T(s.microphoneId)?T(s.audioTrack)||(a.customSource=s.audioTrack):a.deviceId=s.microphoneId,s&&Q(s.captureVolume)&&n.setCaptureVolume(s.captureVolume),T(s.profile)||(re(s.profile)?Ta[s.profile]&&n.setProfile(Ta[s.profile]):n.setProfile(s.profile)),Q(s.earMonitorVolume)&&(c.muted=!(s.earMonitorVolume>0),c.volume=s.earMonitorVolume),T(s.echoCancellation)||(n.profile.echoCancellation=s.echoCancellation),T(s.noiseSuppression)||(n.profile.noiseSuppression=s.noiseSuppression),T(s.autoGainControl)||(n.profile.autoGainControl=s.autoGainControl),he(this._enableAutoSwitchWhenRecapturing)&&(n.enableAutoSwitchWhenRecapturing=this._enableAutoSwitchWhenRecapturing)),n.on("5",l=>{this.emit(U.ERROR,new F({code:x.DEVICE_ERROR,extraCode:5309,messageParams:{error:l}}))}),n.on("2",l=>{this.emit(U.DEVICE_CHANGED,{type:"microphone",action:"active",device:l})}),n.on("4",l=>{let h;l.error&&(h=F.convertFrom(l.error)),this.emit(U.PUBLISH_STATE_CHANGED,L(O({},l),{error:h}))}),n.on("6",()=>{}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId),yield n.capture(a),T(r)||n.setMute(r),tt(n,n).add("player-state-changed",l=>{this.emit(U.AUDIO_PLAY_STATE_CHANGED,L(O({},l),{userId:""}))}),t&&this._room.isJoined&&this._room.publish(n).catch(()=>{}),this._localAudioTrack=n,this._localAudioConfig=L(O({},e),{publish:t}),yield this._updateAudioPlayOption({playOption:c,track:n}),S.emit("113",{userId:"",room:this.room})})}updateLocalAudio(e){return f(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:r,option:s}=e,n={};s&&(s.microphoneId?yield this._localAudioTrack.switchDevice(s.microphoneId):T(s.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(s.audioTrack)),T(s.captureVolume)||this._localAudioTrack.setCaptureVolume(s.captureVolume),T(s.earMonitorVolume)||(n.muted=!(s.earMonitorVolume>0),n.volume=s.earMonitorVolume),yield this._localAudioTrack.update3A(s)),this._room.isJoined&&!T(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),T(r)||this._localAudioTrack.setMute(r),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),ti(this._localAudioConfig,e)})}stopLocalAudio(){return f(this,null,function*(){this._localAudioTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),S.emit("114",{userId:"",room:this.room}),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),xe(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)})}startLocalVideo(){return f(this,arguments,function*(e={publish:!0,view:null,capture:!0}){var m;if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:t,publish:r=!0,capture:s=!0,mute:n,option:a}=e,c=new ze(this._room.videoManager),l={},h={};a&&(he(a.avoidCropping)&&(c.avoidCropping=a.avoidCropping),a.cameraId?l.deviceId=a.cameraId:T(a.useFrontCamera)?T(a.videoTrack)||(l.customSource=a.videoTrack):l.facingMode=a.useFrontCamera?p.FACING_MODE_USER:p.FACING_MODE_ENVIRONMENT,T(a.retryWhenExactFailed)||(l.retryWhenExactFailed=a.retryWhenExactFailed),a.qosPreference&&(l.contentHint=Xn(a.qosPreference)),T(a.profile)||(re(a.profile)?Qt[a.profile]&&c.setProfile(Qt[a.profile]):c.setProfile(a.profile)),T(a.fillMode)||(h.objectFit=a.fillMode),T(a.mirror)||(h.mirror=a.mirror),T(a.small)||(T(a.smallMode)||(this._room.smallMode=a.smallMode),he(a.small)&&a.small===!1?c.stopSmall():c.updateSmallConfig(Cs(a.small,!0))),T(a.rotation)||c.setRotation(a.rotation),he(this._enableAutoSwitchWhenRecapturing)&&(c.enableAutoSwitchWhenRecapturing=this._enableAutoSwitchWhenRecapturing)),c.once("first-video-frame",u=>{this.emit(U.FIRST_VIDEO_FRAME,L(O({},u),{streamType:Pi(u.streamType)}))}),c.on("5",u=>{this.emit(U.ERROR,new F({code:x.DEVICE_ERROR,extraCode:5308,messageParams:{error:u}}))}),c.on("2",u=>{this.emit(U.DEVICE_CHANGED,{type:"camera",action:"active",device:u})}),c.on("4",u=>{let _;u.error&&(_=F.convertFrom(u.error)),this.emit(U.PUBLISH_STATE_CHANGED,L(O({},u),{error:_}))}),c.on("6",()=>{}),this._listenOutputTrackChanged(c),s?yield c.capture(l):(m=c.manager)==null||m.changeInput(c),T(n)||(yield c.setMute(n)),tt(c,c).add("player-state-changed",u=>{this.emit(U.VIDEO_PLAY_STATE_CHANGED,L(O({},u),{userId:"",streamType:"main"}))}).add("video-size-changed",u=>{this.emit(U.VIDEO_SIZE_CHANGED,L(O({},u),{streamType:Pi(u.streamType)}))}),r&&this._room.isJoined&&this._room.publish(c).catch(()=>{}),this._localVideoTrack=c,this._localVideoConfig=L(O({},e),{view:t,publish:r,capture:s}),yield this._updateVideoPlayOption({view:t,playOption:h,track:c})})}updateLocalVideo(e){return f(this,null,function*(){var l,h,m;if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:r,mute:s,capture:n,option:a}=e,c={};if(this._localVideoConfig.capture)n!==!1?a!=null&&a.cameraId?yield this._localVideoTrack.switchDevice(a==null?void 0:a.cameraId):T(a==null?void 0:a.useFrontCamera)?T(a==null?void 0:a.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(a==null?void 0:a.videoTrack)):yield this._localVideoTrack.switchDevice(a!=null&&a.useFrontCamera?p.FACING_MODE_USER:p.FACING_MODE_ENVIRONMENT):this._localVideoTrack.stopCapture();else if(n){let u={};u.deviceId=(a==null?void 0:a.cameraId)||((l=this._localVideoConfig.option)==null?void 0:l.cameraId),u.facingMode=a!=null&&a.useFrontCamera||(h=this._localVideoConfig.option)!=null&&h.useFrontCamera?p.FACING_MODE_USER:p.FACING_MODE_ENVIRONMENT,u.customSource=(a==null?void 0:a.videoTrack)||((m=this._localVideoConfig.option)==null?void 0:m.videoTrack),yield this._localVideoTrack.capture(u)}a&&(T(a.profile)||(re(a.profile)?Qt[a.profile]&&this._localVideoTrack.setProfile(Qt[a.profile]):this._localVideoTrack.setProfile(a.profile),(!a.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(a.cameraId))&&T(a.useFrontCamera)&&(yield this._localVideoTrack.applyProfile())),T(a.fillMode)||(c.objectFit=a.fillMode),T(a.mirror)||(c.mirror=a.mirror),T(a.rotation)||this._localVideoTrack.setRotation(a.rotation),a.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(Xn(a.qosPreference)),T(a.small)||(he(a.small)&&!a.small?this._localVideoTrack.stopSmall():this._localVideoTrack.updateSmallConfig(Cs(a.small,!0)))),this._room.isJoined&&T(r)&&this._localVideoConfig.publish&&n&&!this._localVideoConfig.capture&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._room.isJoined&&((r!=null?r:this._localVideoConfig.publish)?this._room.publish(this._localVideoTrack).catch(()=>{}):this._room.unpublish(this._localVideoTrack).catch(()=>{})),T(s)||(yield this._localVideoTrack.setMute(s)),yield this._updateVideoPlayOption({view:t,playOption:c,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),ti(this._localVideoConfig,e)})}stopLocalVideo(){return f(this,null,function*(){this._localVideoTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),xe(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return f(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,muteSystemAudio:s,option:n}=e,a=new Pt(this._room.videoManager);a.on("4",g=>{let E;g.error&&(E=F.convertFrom(g.error)),this.emit(U.PUBLISH_STATE_CHANGED,L(O({},g),{error:E}))}),a.once("first-video-frame",g=>{this.emit(U.FIRST_VIDEO_FRAME,L(O({},g),{streamType:Pi(g.streamType)}))}),this._listenOutputTrackChanged(a),e.streamType==="main"&&(a.mediaType=4);let c=null,l={},h={};n&&(T(n.profile)||(re(n.profile)?Ea[n.profile]&&a.setProfile(Ea[n.profile]):a.setProfile(n.profile)),n.systemAudio&&(l.systemAudio=!0,l.echoCancellation=n.echoCancellation,l.noiseSuppression=n.noiseSuppression,l.autoGainControl=n.autoGainControl),T(n.fillMode)||(h.objectFit=n.fillMode),n.videoTrack&&(l.videoTrack=n.videoTrack),n.audioTrack&&(l.audioTrack=n.audioTrack),n.captureElement&&(l.captureElement=n.captureElement),n.preferDisplaySurface&&(l.preferDisplaySurface=n.preferDisplaySurface),n.qosPreference&&(l.contentHint=Xn(n.qosPreference)));let m=yield a.capture(l);if(a.mediaTrack.addEventListener(p.ENDED,()=>{this._stopScreenShare(),this.emit(U.SCREEN_SHARE_STOPPED)}),m.getAudioTracks()[0]){c=new To(this._room.audioManager);let g=m.getAudioTracks()[0];(u=e.option)!=null&&u.systemAudio&&!((_=e.option)!=null&&_.audioTrack)&&(c.sourceTrack=g),yield c.setInputMediaStreamTrack(g),he(s)&&c.mediaTrack&&(c.mediaTrack.enabled=!s),this._speakerId&&c.setAudioOutput(this._speakerId)}if(tt(a,a).add("player-state-changed",g=>{this.emit(U.VIDEO_PLAY_STATE_CHANGED,L(O({},g),{userId:"",streamType:"sub"}))}),r&&this._room.isJoined){let g=[a];c&&(g.push(c),this._checkScreenAudioEchoCancellation(a,c)),g.forEach(E=>this._room.publish(E).catch(()=>{}))}this._localScreenTrack=a,this._localScreenAudioTrack=c,this._localScreenConfig=L(O({},e),{view:t,publish:r}),yield this._updateVideoPlayOption({view:t,playOption:h,track:a})})}updateScreenShare(e){return f(this,null,function*(){var c;if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:r,muteSystemAudio:s,option:n}=e,a={};if(n&&(T(n.fillMode)||(a.objectFit=n.fillMode),n.qosPreference)){let l=Xn(n.qosPreference);this._localScreenTrack.setContentHint(l)}if(this._room.isJoined&&!T(r)){if(r&&!this._localScreenConfig.publish){let l=[this._localScreenTrack];this._localScreenAudioTrack&&l.push(this._localScreenAudioTrack),l.forEach(h=>this._room.publish(h).catch(()=>{}))}if(this._localScreenConfig.publish&&!r){let l=[this._localScreenTrack];this._localScreenAudioTrack&&l.push(this._localScreenAudioTrack),l.forEach(h=>this._room.unpublish(h).catch(()=>{}))}}(c=this._localScreenAudioTrack)!=null&&c.mediaTrack&&he(s)&&(this._localScreenAudioTrack.mediaTrack.enabled=!s),yield this._updateVideoPlayOption({view:t,playOption:a,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),ti(this._localScreenConfig,e)})}stopScreenShare(){return f(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return f(this,null,function*(){let{view:t,userId:r,streamType:s,option:n}=e,a=`${r}_${s}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${r}, streamType:${s}`);return}let c=this._room.remotePublishedUserMap.get(r);if(!c)return;let l={},h=s==="main"?c.remoteVideoTrack:c.remoteAuxiliaryTrack;h.on("decode-failed",m=>{this.emit(U.ERROR,new F({code:x.OPERATION_FAILED,extraCode:5507,message:"video decode failed"}))}),h.on("video-size-changed",m=>{this.emit(U.VIDEO_SIZE_CHANGED,L(O({},m),{streamType:Pi(m.streamType)}))}),this._listenOutputTrackChanged(h),n&&(T(n.fillMode)||(l.objectFit=n.fillMode),T(n.mirror)||(l.mirror=n.mirror),T(n.poster)||(l.poster=n.poster),l.canvasRender=n.canvasRender,s==="main"&&!T(n.small)&&(!c.remoteVideoTrack.isSubscribing&&!c.remoteVideoTrack.isSubscribed&&c.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,h.user)),T(n.draggable)||h.setDraggable(n.draggable)),yield this._room.subscribe(h),yield this._enableVideoDecodeFallback(h,s),yield this._updateVideoPlayOption({view:t,playOption:l,track:h}),this._emitTrackEvent(h),this._remoteVideoConfigMap.set(a,{config:e}),n&&!T(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:h,view:t,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:n==null?void 0:n.viewRoot})})}updateRemoteVideo(e){return f(this,null,function*(){var k,se;let{view:t,userId:r,streamType:s,option:n,mute:a}=e,c=`${r}_${s}`,l=this._remoteVideoConfigMap.get(c);if(!l||!this._room.remotePublishedUserMap.has(r))return;let h={};n&&(T(n.fillMode)||(h.objectFit=n.fillMode),T(n.mirror)||(h.mirror=n.mirror));let m=null,u=this._room.remotePublishedUserMap.get(r);if(s==="main"&&(u!=null&&u.muteState.hasVideo)&&(m=u.remoteVideoTrack),s==="sub"&&(u!=null&&u.muteState.hasAuxiliary)&&(m=u.remoteAuxiliaryTrack),!m)return;let{config:_}=l;s==="main"&&n&&!T(n.small)&&this._room.changeType(n.small,m.user),n&&!T(n.draggable)&&m.setDraggable(n.draggable),n&&(he(n.pictureInPicture)&&(n.pictureInPicture?yield m.player.enterPictureInPicture():yield m.player.exitPictureInPicture()),he(n.fullScreen)&&(n.fullScreen?yield m.player.enterFullscreen():yield m.player.exitFullscreen())),he(a)&&(m.ignoreUpdatePlayingState=!0,a?(yield m.player.pause(),yield this.room.unsubscribe(m)):(yield this.room.subscribe(m),yield m.player.resume(!0))),yield this._updateVideoPlayOption({view:t,playOption:h,track:m,prevConfig:_}),ti(_,e);let g=T(n==null?void 0:n.receiveWhenViewVisible)?(k=_.option)==null?void 0:k.receiveWhenViewVisible:n.receiveWhenViewVisible,E=T(t)?_.view:t,A=T(n==null?void 0:n.viewRoot)?(se=_.option)==null?void 0:se.viewRoot:n.viewRoot;this._observeView({remoteTrack:m,view:E,receiveWhenViewVisible:g,viewRoot:A})})}stopRemoteVideo(e){return f(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,t=!0){return f(this,null,function*(){let r=[],s=this._room.remotePublishedUserMap.get(e.userId);if(s){let{muteState:n,remoteVideoTrack:a,remoteAuxiliaryTrack:c}=s;e.streamType==="main"&&(a.stop(),n.hasVideo&&r.push(a)),e.streamType==="sub"&&(c.stop(),n.hasAuxiliary&&r.push(c))}for(let n of r)t&&(delete n.ignoreUpdatePlayingState,yield this._room.unsubscribe(n),this._mediaTrackMap.delete(n.outMediaTrack));this._removeRemoteVideoConfig(e.userId,e.streamType)})}_removeRemoteVideoConfig(e,t){let r=`${e}_${t}`,s=this._remoteVideoConfigMap.get(r);s&&s.observer&&s.observer.disconnect(),this._remoteVideoConfigMap.delete(r)}muteRemoteAudio(e,t){return f(this,null,function*(){this._remoteAudioMuteMap.set(e,t);try{if(e==="*")if(t)yield this._stopRemoteAudio({userId:e});else{let r=[...this._room.remotePublishedUserMap.values()];for(let s of r)s.muteState.hasAudio&&!this._remoteAudioConfigMap.has(s.userId)&&(yield this._startRemoteAudio({userId:s.userId}))}else t?yield this._stopRemoteAudio({userId:e}):this._remoteAudioConfigMap.has(e)||(yield this._startRemoteAudio({userId:e}))}catch(r){throw r.code!==x.OPERATION_ABORT&&this._remoteAudioMuteMap.delete(e),r}})}setRemoteAudioVolume(e,t){if(e==="*"){this._remoteAudioVolumeMap.set("*",t),this._remoteAudioVolumeMap.forEach((s,n)=>this._remoteAudioVolumeMap.set(n,t));let r=[...this._room.remotePublishedUserMap.values()];for(let s of r)this._remoteAudioVolumeMap.set(s.userId,t),s.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:s.remoteAudioTrack})}else if(e){let r=this._room.remotePublishedUserMap.get(e);this._remoteAudioVolumeMap.set(e,t),r&&r.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:r.remoteAudioTrack})}}startPlugin(e,t){return f(this,null,function*(){return e.start(t)})}updatePlugin(e,t){return f(this,null,function*(){return e.update(t)})}stopPlugin(e,t){return f(this,null,function*(){return e.stop(t)})}enableAudioVolumeEvaluation(e=2e3,t=!1){this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,r){if(this.listeners(e).includes(t))return this;if(this._log.debug("on",e),super.on(e,t,r),this._eventListened.add(e),this.listeners(U.AUDIO_FRAME).length>0){let{audioFrameEventConfigMap:s}=this.room.audioManager;s.get("")||s.set("",{enable:!0}),this._localAudioTrack&&this.room.audioManager.handleLocalTrackStarted({userId:"",room:this.room})}return this}emit(e,...t){try{Bf.has(e)||this._log.debug(`emit ${e} ${JSON.stringify(t)}`)}catch(r){}return super.emit(e,...t)}off(e,t,r){if(this._log.debug("off",e),e==="*"?(this._eventListened.clear(),this.removeAllListeners()):super.off(e,t,r),(e===J.EVENT.AUDIO_FRAME||e==="*")&&this.listeners(J.EVENT.AUDIO_FRAME).length===0){let{getPCMAbortCtrlMap:s}=this.room.audioManager;s.forEach(n=>{n==null||n.abort("off")}),s.clear()}return this}getAudioTrack(e={userId:"",streamType:"main"}){let t,r=null,s="main",n=!1;if(re(e)?t=e:(t=e.userId,n=e.processed===!0,e.streamType&&(s=e.streamType)),t){let a=this._room.remotePublishedUserMap.get(t);a&&(r=a.remoteAudioTrack)}else r=s==="sub"?this._localScreenAudioTrack:this._localAudioTrack;return r?n&&r.outMediaTrack&&r.outMediaTrack!==r.mediaTrack?r.outMediaTrack.clone():r.mediaTrack:null}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:t="",streamType:r="main",processed:s=!1}=e,n=null;if(t==="")r==="main"&&this._localVideoTrack&&(n=this._localVideoTrack),r==="sub"&&this._localScreenTrack&&(n=this._localScreenTrack);else{let a=this._room.remotePublishedUserMap.get(t);a&&(n=r==="main"?a.remoteVideoTrack:a.remoteAuxiliaryTrack)}return n?s&&n.outMediaTrack&&n.outMediaTrack!==n.mediaTrack?n.outMediaTrack.clone():n.mediaTrack:null}getVideoSnapshot(e={}){let{userId:t,streamType:r="main"}=e;if(t){let s=this._room.remotePublishedUserMap.get(t);if(r==="main"&&(s!=null&&s.muteState.hasVideo))return s.remoteVideoTrack.getVideoFrame();if(r==="sub"&&(s!=null&&s.muteState.hasAuxiliary))return s.remoteAuxiliaryTrack.getVideoFrame()}else{if(r==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(r==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(e){var t,r;this._speakerId=e,(t=this._localAudioTrack)==null||t.setAudioOutput(e),(r=this._localScreenAudioTrack)==null||r.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(s=>s.remoteAudioTrack.setAudioOutput(e))}setCurrentSpeaker(e){return f(this,null,function*(){(yield Dr()).forEach(r=>{r.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(U.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}),Ye=r)}),this._log.warn(`the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: ${ft}/en/TRTC.html#.setCurrentSpeaker`)})}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return f(this,null,function*(){var a;let{userId:t}=e;if(this._remoteAudioConfigMap.has(t)){this._log.warn(`remote audio has already started. userId:${t}`);return}let r=this._room.remotePublishedUserMap.get(t);if(!r)return;let s={},n=r.remoteAudioTrack;n.on("decode-failed",c=>{this.emit(U.ERROR,new F({code:x.OPERATION_FAILED,extraCode:5508,message:"audio decode failed"}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId);try{let c=(a=this._remoteAudioVolumeMap.get(t))!=null?a:this._remoteAudioVolumeMap.get("*"),l=Q(c)?c:100;s.volume=l,this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(n),ue(le(n,"decode-failed"),Pe(le(n,j.INIT)),Te(()=>{this.startPlugin(ea.Name,{track:n,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:s,track:n}),S.emit("115",{userId:t,room:this.room}),n.outMediaTrack&&this.room.audioManager.updateAudioReference({type:"add",audioReference:n.outMediaTrack,refId:`ra-${t}`})}catch(c){throw this._remoteAudioConfigMap.delete(t),c}this._emitTrackEvent(n)})}_stopRemoteAudio(e,t=!0){return f(this,null,function*(){let r=this._room.remotePublishedUserMap.get(e.userId);r&&(r.remoteAudioTrack.stop(),r.muteState.hasAudio&&t&&(yield this._room.unsubscribe(r.remoteAudioTrack)),this._mediaTrackMap.delete(r.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete(`${e.userId}`),S.emit("116",{userId:e.userId,room:this.room}),this.room.audioManager.updateAudioReference({type:"remove",refId:`ra-${e.userId}`})})}_enableVideoDecodeFallback(e,t){let r=this._room.videoDecodeFallbackType;if(!r||!this._plugins.has("TRTCVideoDecoder"))return;e.log.debug("remote video will fall back when decode failed",e.id);let s;ue(le(e,"decode-failed"),Pe(le(e,j.INIT)),Gn(()=>{this._room.downlinkVideoCodec!=="h265"&&this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:r})}),mo(le(e,"decode-downgrade-state-changed")),Te(n=>{s=n.state,this.emit(U.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,L(O({},n),{streamType:t,userId:e.userId}))},n=>{e.log.error("fallback",n)},()=>{s==="STARTED"&&e.log.info("fallback complete")}))}_updateVideoPlayOption(n){return f(this,arguments,function*({view:e,playOption:t,track:r,prevConfig:s}){if(r.setMirror(t.mirror),T(e)&&s&&s.view&&!Fo(t)){let a=Ho(s.view);a.length>0&&(yield r.play(a,t))}if(!T(e)){let a=Ho(e);a.length>0?yield r.play(a,t):r.stop()}})}_updateAudioPlayOption(s){return f(this,arguments,function*({playOption:e={},track:t,prevConfig:r}){if(!t.isPlayCalled)try{yield t.play(null,e)}catch(n){}if(T(e.muted)||t.setPlayerMute(e.muted),T(e.volume)||t.setAudioVolume(e.volume/100),t instanceof kt&&t.mediaTrack){let n=e.muted===!1&&!T(e.volume)&&e.volume>0?"add":"remove";this.room.audioManager.updateAudioReference({type:n,audioReference:t.mediaTrack,refId:"em"})}else if(t instanceof Ti){let n=e.muted?0:e.volume;if(T(n))return;this.room.audioManager.updateAudioReference({type:"updateVolume",refId:`ra-${t.userId}`,volume:e.volume})}})}_listenOutputTrackChanged(e){e.listeners("output-media-track-changed").length===0&&e.on("output-media-track-changed",()=>this._emitTrackEvent(e,!1))}_emitTrackEvent(e,t=!0){let r=e.isRemote?e.userId:"";e.outMediaTrack&&(t&&this._mediaTrackMap.get(e.outMediaTrack)===r||(this._mediaTrackMap.set(e.outMediaTrack,r),this.emit(U.TRACK,{userId:r,streamType:Pi(e.streamType),track:e.outMediaTrack,sourceTrack:e.mediaTrack})))}_checkTrackToPublish(){var t,r,s;let e=[];if((t=this._localAudioConfig)!=null&&t.publish&&this._localAudioTrack&&e.push(this._localAudioTrack),(r=this._localVideoConfig)!=null&&r.publish&&this._localVideoTrack&&e.push(this._localVideoTrack),(s=this._localScreenConfig)!=null&&s.publish&&(this._localScreenTrack&&e.push(this._localScreenTrack),this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack),this._checkScreenAudioEchoCancellation(this._localScreenTrack,this._localScreenAudioTrack)),e.length!==0)return Promise.all(e.map(n=>this._room.publish(n).catch(()=>{})))}_observeView({remoteTrack:e,view:t,receiveWhenViewVisible:r,viewRoot:s}){if(T(t)||T(r))return;let n=this._remoteVideoConfigMap.get(`${e.userId}_${Pi(e.streamType)}`);if(!n)return;let a=n.observer||void 0;if(t===null||Ae(t)&&t.length===0||!r){a==null||a.disconnect(),e.isSubscribed||(this._log.info("_observeView observer disconnect, resubscribe",e.userId,e.strMediaType),this._room.subscribe(e).catch(()=>{}));return}let l=n.visibleViewMap||new Map,h=-1;(!a||a.root!==s)&&(a==null||a.disconnect(),l.clear(),a=new IntersectionObserver(u=>{u.forEach(_=>{l.set(_.target,_.isIntersecting),e.log.info(`view ${_.target.id} is${_.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:s}));let m=new Set(Ho(t));l.forEach((u,_)=>{m.has(_)||(a.unobserve(_),l.delete(_))}),m.forEach(u=>{l.set(u,!0),a.observe(u)}),a.takeRecords().forEach(u=>{l.set(u.target,u.isIntersecting)}),n.visibleViewMap=l,n.observer=a}_exitRoom(){return f(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),this._clearRemoteTracks()})}_stopScreenShare(){return f(this,null,function*(){var e;if(this._localScreenTrack){if(this._room.isJoined){let t=[this._localScreenTrack];this._localScreenAudioTrack&&t.push(this._localScreenAudioTrack),yield Promise.all(t.map(r=>this._room.unpublish(r).catch(()=>{})))}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(((e=this._localScreenAudioTrack.trackSettings)==null?void 0:e.echoCancellation)===!1&&this.stopPlugin("AudioProcessor"),this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),xe(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_checkScreenAudioEchoCancellation(e,t){return f(this,null,function*(){var s,n;if(!e||!t)return;let r=(s=e.trackSettings)==null?void 0:s.displaySurface;if(((n=t.trackSettings)==null?void 0:n.echoCancellation)===!1&&(r==="monitor"||r==="browser"&&e.isShareCurrentTab)){this._log.warn("echoCancellation of screen audio track is disable. Try starting audioProcessor plugin");try{yield this.startPlugin("AudioProcessor",{sdkAppId:Number(this.room.sdkAppId),userId:this._room.userId,userSig:this.room.userSig,isScreenAudioNeedAudioProcess:!0,isLocalAudioNeedAudioProcess:!1})}catch(a){this._log.warn("start audioProcessor plugin failed: ",a)}}})}_onLocalTrackCaptured({track:e}){e.kind==="audio"&&(!Ye||hs(Ye))&&(this._initActiveSpeaker(),S.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return f(this,null,function*(){if(Ye&&!hs(Ye))this.emit(U.DEVICE_CHANGED,{type:"speaker",action:"active",device:Ye});else{let e=yield Dr();e[0]&&!hs(e[0])?(Ye=e[0],this.emit(U.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):S.on("102",this._onLocalTrackCaptured,this)}})}_onAudioAvailable({userId:e}){let t=this._remoteAudioMuteMap.has(e)?this._remoteAudioMuteMap.get(e):this._remoteAudioMuteMap.get("*");(t===!1||this._room.autoReceiveAudio&&!t)&&this._doStartRemoteAudio({userId:e}).catch(()=>{})}_onVideoAvailable({userId:e,streamType:t}){if(!this._room.autoReceiveVideo)return;let r=this._room.remotePublishedUserMap.get(e);if(r){let s=t==="main"?r.remoteVideoTrack:r.remoteAuxiliaryTrack,n=[s];this._room.autoReceiveAudio&&r.remoteAudioTrack.isAvailable&&n.push(r.remoteAudioTrack),this._room.subscribe(...n).then(()=>{this._emitTrackEvent(s)}).catch(()=>{})}}_onAudioUnavailable({userId:e,muteState:t}){t.hasAudio&&t.audioMuted||this._stopRemoteAudio({userId:e},!1).catch(()=>{})}_onVideoUnavailable({userId:e,streamType:t}){this._stopRemoteVideo({userId:e,streamType:t},!1).catch(()=>{})}sendSEIMessage(e,t){var s;let r=this._plugins.get("SEI");r&&(r.update({buffer:e,options:L(O({seiPayloadType:243},t),{small:!!((s=this._localVideoTrack)!=null&&s.small)})}),v.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,r;(r=(t=this._room).sendCustomMessage)==null||r.call(t,e),v.addCount({key:500001,useUV:!0})}callExperimentalAPI(e,t){return f(this,null,function*(){return this._log.info(`callExperimentalAPI(${e}, ${JSON.stringify(t)})`),i_.call(e,O({trtcInstance:this},t))})}static setLogLevel(e,t){R.setLogLevel(e),T(t)||(t?R.enableUploadLog():R.disableUploadLog())}static isSupported(){return Ic(J.frameWorkType)}static getPermissions(r){return f(this,arguments,function*({request:e=!0,types:t=["camera","microphone"]}){e&&(yield ta.request(t).catch(a=>{var c;return R.error(`getPermissions request failed, error: ${(c=a==null?void 0:a.message)!=null?c:a}`)}));let[s,n]=yield Promise.all([ta.get("camera"),ta.get("microphone")]);return{camera:s,microphone:n}})}static getCameraList(e=!0){return At(e)}static getMicrophoneList(e=!0){return It(e)}static getSpeakerList(e=!0){return Dr(e)}static setCurrentSpeaker(e){return f(this,null,function*(){if(fe&&(e===So.SPEAKER||e===So.HEADSET)){let r=yield J.getMicrophoneList(),s="";if(r.forEach(n=>{n.label===e&&(s=n.deviceId)}),!s)return;ia.forEach(n=>f(this,null,function*(){n._localAudioTrack&&(yield n.updateLocalAudio({option:{microphoneId:s}}))}));return}(yield Dr()).forEach(r=>{r.deviceId===e&&(ia.forEach(s=>{s._setCurrentSpeaker(e),s.emit(U.DEVICE_CHANGED,{type:"speaker",action:"active",device:r})}),Ye=r)})})}static _addKVStat({type:e,key:t,value:r,base:s,useUV:n,version:a,max:c}){switch(a&&(ro.version=a),e){case"count":ro.addCount({key:t,useUV:n});break;case"enum":ro.addEnum({key:t,value:r,useUV:n});break;case"number":ro.addNumber({key:t,value:r,split:s,max:c});break}}};d(J,"VERSION",Bh),d(J,"_loggerManager",R),d(J,"EVENT",U),d(J,"ERROR_CODE",x),d(J,"TYPE",So),d(J,"frameWorkType",30),M([Re({replaceArg:e=>({argIndex:0,value:{name:"plugin"in e?e.plugin.Name:e.Name,assetsPath:"assetsPath"in e?e==null?void 0:e.assetsPath:"default"}})})],J.prototype,"use",1),M([st(qe.TRTC.enterRoom),Lr("room",([e],[t])=>(e.roomId||e.strRoomId)===(t.roomId||t.strRoomId)&&e.userId===t.userId&&e.sdkAppId===t.sdkAppId),Y(e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)}),Re()],J.prototype,"enterRoom",1),M([Re()],J.prototype,"exitRoom",1),M([st(qe.TRTC.switchRoom),Re(),ir()],J.prototype,"switchRoom",1),M([st(qe.TRTC.switchRole),Ao("room",{merge:(e,t)=>t}),Re()],J.prototype,"switchRole",1),M([Re()],J.prototype,"destroy",1),M([st(qe.TRTC.startLocalAudio),Lr("audio",([e],[t])=>{var r,s;return((r=e==null?void 0:e.option)==null?void 0:r.microphoneId)===((s=t==null?void 0:t.option)==null?void 0:s.microphoneId)}),Re()],J.prototype,"startLocalAudio",1),M([st(qe.TRTC.updateLocalAudio),Ao("audio",{debounce:{delay:200,getKey:()=>`${o_}-localAudio`,isNeedToDebounce:e=>{var t;return!T((t=e.option)==null?void 0:t.captureVolume)}}}),Re()],J.prototype,"updateLocalAudio",1),M([xr("audio"),Re()],J.prototype,"stopLocalAudio",1),M([st(qe.TRTC.startLocalVideo),Lr("video",([e],[t])=>{var r,s;return((r=e==null?void 0:e.option)==null?void 0:r.cameraId)===((s=t==null?void 0:t.option)==null?void 0:s.cameraId)}),Re()],J.prototype,"startLocalVideo",1),M([st(qe.TRTC.updateLocalVideo),Ao("video"),Re()],J.prototype,"updateLocalVideo",1),M([xr("video"),Re()],J.prototype,"stopLocalVideo",1),M([st(qe.TRTC.startScreenShare),Lr("screen",()=>!0),Re()],J.prototype,"startScreenShare",1),M([st(qe.TRTC.updateScreenShare),Ao("screen"),Re()],J.prototype,"updateScreenShare",1),M([Re()],J.prototype,"stopScreenShare",1),M([st(qe.TRTC.startRemoteVideo),Lr(e=>`v${e.userId}${e.streamType}`,()=>!0),Re({getRemoteId:e=>`${e.userId}_${e.streamType}`})],J.prototype,"startRemoteVideo",1),M([st(qe.TRTC.updateRemoteVideo),Ao(e=>`v${e.userId}${e.streamType}`),Re({getRemoteId:e=>`${e.userId}_${e.streamType}`})],J.prototype,"updateRemoteVideo",1),M([st(qe.TRTC.stopRemoteVideo),Y(e=>function(t){return f(this,null,function*(){if(t.userId==="*"){let r=[];return this._room.remotePublishedUserMap.forEach(s=>{this._remoteVideoConfigMap.has(`${s.userId}_main`)&&r.push(this.stopRemoteVideo({streamType:"main",userId:s.userId}).catch(()=>{})),this._remoteVideoConfigMap.has(`${s.userId}_sub`)&&r.push(this.stopRemoteVideo({streamType:"sub",userId:s.userId}).catch(()=>{}))}),Promise.all(r)}return e.call(this,t)})}),Re({getRemoteId:e=>`${e.userId}_${e.streamType}`})],J.prototype,"stopRemoteVideo",1),M([xr(e=>`v${e.userId}${e.streamType}`)],J.prototype,"_stopRemoteVideo",1),M([st(...qe.TRTC.muteRemoteAudio),Re({getRemoteId:e=>e})],J.prototype,"muteRemoteAudio",1),M([Hh(...qe.TRTC.setRemoteAudioVolume),zf(200,e=>e),Re({getRemoteId:e=>e})],J.prototype,"setRemoteAudioVolume",1),M([Ed("start"),Ct(e=>{var t;return(t=e.afterStart)==null?void 0:t.call(e)}),Lr((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t)),Re({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>su[e.getName()],ignoreLog:e=>e.getName()==="Debug",ignoreErrorLog:e=>e.getName()==="AudioProcessor"})],J.prototype,"startPlugin",1),M([Ed("update"),Ao((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t),{merge:(e,t)=>(ti(e[1],t[1]),e)}),Re({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>nu[e.getName()]})],J.prototype,"updatePlugin",1),M([Ed("stop"),xr((e,t)=>{if(e.disableRandomCall)return null;let r=e.getGroup(t),s=e.getAlias();return r==="*"?new RegExp(`${s}.*`):s+r}),Re({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>au[e.getName()]})],J.prototype,"stopPlugin",1),M([Hh(...qe.TRTC.enableAudioVolumeEvaluation)],J.prototype,"enableAudioVolumeEvaluation",1),M([Re()],J.prototype,"getVideoSnapshot",1),M([Re()],J.prototype,"_setCurrentSpeaker",1),M([Lr(e=>`a${e.userId}`,()=>!0)],J.prototype,"_startRemoteAudio",1),M([Y(e=>function(t){return f(this,null,function*(){return t.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(r=>this._stopRemoteAudio(L(O({},t),{userId:r.userId})).catch(()=>{}))):e.call(this,t)})}),xr(e=>`a${e.userId}`)],J.prototype,"_stopRemoteAudio",1),M([xr("room")],J.prototype,"_exitRoom",1),M([xr("screen")],J.prototype,"_stopScreenShare",1),M([st(...qe.TRTC.sendSEIMessage),Dh({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...e)=>e[0].byteLength})],J.prototype,"sendSEIMessage",1),M([st(qe.TRTC.sendCustomMessage),Dh({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],J.prototype,"sendCustomMessage",1),M([Ur()],J,"create",1),M([st(qe.TRTC.create)],J,"_create",1),M([Ur()],J,"setLogLevel",1),M([Ur()],J,"isSupported",1),M([Ur()],J,"getPermissions",1),M([Ur()],J,"getCameraList",1),M([Ur()],J,"getMicrophoneList",1),M([Ur()],J,"getSpeakerList",1);var Yh=J,ra=Yh;var Zh=class{constructor(){d(this,"_set",new Set);S.on(C.LEAVE_SUCCESS,this.delete,this),S.on(C.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess,this)}add({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,e||i.roomId,i.sdkAppId,i.useStringRoomId);this._set.add(t)}delete({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,i.roomId||e,i.sdkAppId,i.useStringRoomId);this._set.delete(t)}getKey(i,e,t,r){return`${t}_${e}_${i}_${r}`}isJoined({userId:i,roomId:e,sdkAppId:t,room:r}){return r.scene==="rtc"?!1:this._set.has(this.getKey(i,e,t,r.useStringRoomId))}handleSwitchRoomSuccess({room:i,currentRoomId:e,targetRoomId:t}){i.scene!=="rtc"&&(this._set.delete(this.getKey(i.userId,e,i.sdkAppId,i.useStringRoomId)),this._set.add(this.getKey(i.userId,t,i.sdkAppId,i.useStringRoomId)))}};function oI(){return f(this,null,function*(){let o,i;try{let _=yield It();o=_&&_.length}catch(_){}try{let _=yield At();i=_&&_.length}catch(_){}let e={microphone:o,camera:i},{isH264EncodeSupported:t,isVp8EncodeSupported:r,isH264DecodeSupported:s,isVp8DecodeSupported:n,isH265EncodeSupported:a,isH265DecodeSupported:c}=this.checkSystemResult.detail,l=vi.basis(),h={webRTC:l.isWebRTCSupported,getUserMedia:l.isGetUserMediaSupported,webSocket:l.isWebSocketsSupported,screenShare:l.isScreenShareSupported,webAudio:l.isWebAudioSupported,h264Encode:t,h264Decode:s,vp8Encode:r,vp8Decode:n,h265Encode:a,h265Decode:c},m={browser:l.browser,os:l.os,trtc:h,devices:e},u={isWebCodecSupported:l.isWebCodecSupported,isMediaSessionSupported:l.isMediaSessionSupported,isWebTransportSupported:l.isWebTransportSupported};ne.uploadEvent({log:`trtcstats-${JSON.stringify(m)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(m)}`),ne.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(u)}`,userId:this.userId}),Eu()})}function n_(){return Y(o=>{let i=new Zh;return function(e,t,r){return f(this,null,function*(){let s=String(e.roomId||e.strRoomId);if(this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.userSig=e.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=t,e.privateMapKey=e.privateMapKey||"",this.isJoined)throw new D({code:I.INVALID_OPERATION,message:$({key:B.INVALID_JOIN})});if(this.checkDestroy(),i.isJoined({userId:this.userId,roomId:s,sdkAppId:this.sdkAppId,room:this}))throw new D({code:I.INVALID_OPERATION,message:$({key:B.REPEAT_JOIN,data:this.userId})});i.add({room:this,roomId:s}),this.role=e.role===21?"audience":"anchor",this._log.info(`Join() => joining room: ${s} useStringRoomId: ${this.useStringRoomId} scene: ${this.scene} role: ${this.role}`),S.emit(C.JOIN_START,{room:this,roomId:s,params:e});let n=vt.getEnv();n||(n=Bi.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(Sa.OLD_CLOUD_LADDER)?n=Bi.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(Sa.WEBRTC)&&(n=Bi.WEBRTC))),ne.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:s}),vi.checkSystemRequirementsInternal(r).then(a=>{this.checkSystemResult=a,oI.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!vt.getEnv()&&(yield this.schedule(e,r));let a=yield o.call(this,e,t,r);return this.roomId=s,this._joinedTimestamp=vt.performanceNow(),S.emit(C.JOIN_SUCCESS,{room:this}),r===30&&!e.component&&ne.uploadEvent({log:`stat-conv-${Number(si)}-${location.hostname}`,userId:this.userId}),a}catch(a){throw i.delete({room:this,roomId:s}),S.emit(C.JOIN_FAILED,{room:this,error:a}),a}})}})}var a_=()=>Y(o=>function(...i){return f(this,null,function*(){S.emit(C.LEAVE_START,{room:this}),yield o.call(this,...i),S.emit(C.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function c_(){return Y(o=>function(...i){let e=o.apply(this,i);return i.forEach(t=>!t.isSubscribed&&t.subscribe(e)),e})}var l_=Je(at());var Ie={SETUP_SUCCESS:"1",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",RECONNECT_FAILED:"4",SETUP_FAILED:"5",DISCONNECTED:"6",CLOSE:"7",ONLINE:"8"};var Jt={CLIENT_BANNED:9,CHANNEL_SETUP_RESULT:19,CHANNEL_RECONNECT_RESULT:514,JOIN_ROOM_RESULT:20,PEER_JOIN:4134,PEER_LEAVE:4135,STREAM_ADDED:16,STREAM_REMOVED:18,UPLINK_NETWORK_STATS:22,UPDATE_REMOTE_MUTE_STAT:23,PUBLISH_RESULT:4098,PUBLISH_STATE_CHANGE_RESULT:4112,UNPUBLISH_RESULT:4100,SUBSCRIBE_RESULT:4102,UNSUBSCRIBE_RESULT:4104,SUBSCRIBE_CHANGE_RESULT:4106,MUTE_RESULT:4108,UPDATE_OFFER_RESULT:4128,START_PUBLISH_TENCENT_CDN_RES:1286,STOP_PUBLISH_TENCENT_CDN_RES:1288,START_PUBLISH_GIVEN_CDN_RES:777,STOP_PUBLISH_GIVEN_CDN_RES:779,START_MIX_TRANSCODE_RES:781,STOP_MIX_TRANSCODE_RES:783,START_PUBLISH_CDN_STREAM_RES:8196,UPDATE_PUBLISH_CDN_STREAM_RES:8198,STOP_PUBLISH_CDN_STREAM_RES:8200,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772,REBUILD_PEER_CONNECTION_RES:4150,SPC_PUBLISH_RESULT:4146,SPC_SUBSCRIBE_RESULT:4156,ABILITY_STATUS_REPORT_RESULT:4158,SERVER_FIRST_PACKAGE_RECEIVED:5e3,RECEIVE_CUSTOM_MSG:4140,FALLBACK_CODEC:66,SEND_SWITCH_ROOM_RES:4160,SEND_SWITCH_ROOM_SUBED_REQ:4161,UPDATE_NETWORK_TIME_RESULT:5001,CUSTOM_CMD_RES:8220},d_=[Jt.UPDATE_REMOTE_MUTE_STAT,Jt.UPLINK_NETWORK_STATS,Jt.USER_LIST_RES,Jt.MUTE_RESULT,Jt.SERVER_FIRST_PACKAGE_RECEIVED,Jt.RECEIVE_CUSTOM_MSG,Jt.UPDATE_NETWORK_TIME_RESULT],W={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",START_PUBLISH_CDN_STREAM_RES:"start-publish-cdn-stream-res",UPDATE_PUBLISH_CDN_STREAM_RES:"update-publish-cdn-stream-res",STOP_PUBLISH_CDN_STREAM_RES:"stop-publish-cdn-stream-res",USER_LIST_RES:"user-list-res",SWITCH_ROLE_RES:"switch_role_res",MUTE_RESULT:"mute-result",UPDATE_CONSTRAINT_CONFIG_RES:"update-contraint-config-res",REBUILD_PEER_CONNECTION_RES:"rebuild-pc-res",SPC_PUBLISH_RESULT:"spc-publish-result",SPC_SUBSCRIBE_RESULT:"spc-subscribe-result",ABILITY_STATUS_REPORT_RESULT:"ability-status-report",SERVER_FIRST_PACKAGE_RECEIVED:"first-pkg-received",RECEIVE_CUSTOM_MSG:"receive-custom-msg",FALLBACK_CODEC:"fallback-codec",SEND_SWITCH_ROOM_RES:"send-switch-room-res",SEND_SWITCH_ROOM_SUBED_REQ:"send-switch-room-subed-res",UPDATE_NETWORK_TIME_RESULT:"update_network_time_result",CUSTOM_CMD_RES:"custom-cmd-res"},Z={PUBLISH_CHANGE:"publish_change",JOIN_ROOM:"join",LEAVE_ROOM:"leave",ON_QUALITY_REPORT:"quality_report",UPDATE_MUTE_STAT:"mute_uplink",PUBLISH:"publish",PUBLISH_STATE_CHANGE:"publish_state_change",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",RECEIVE_DATA_USER_LIST:"receive_data_userlist",UNSUBSCRIBE:"unsubscribe",SUBSCRIBE_CHANGE:"subscribe_change",START_PUBLISH_TENCENT_CDN:"start_publishing",STOP_PUBLISH_TENCENT_CDN:"stop_publishing",START_PUBLISH_GIVEN_CDN:"start_push_user_cdn",STOP_PUBLISH_GIVEN_CDN:"stop_push_user_cdn",START_MIX_TRANSCODE:"start_mcu_mix",STOP_MIX_TRANSCODE:"stop_mcu_mix",START_PUBLISH_CDN_STREAM:"start_publish_cdn_stream",UPDATE_PUBLISH_CDN_STREAM:"update_publish_cdn_stream",STOP_PUBLISH_CDN_STREAM:"stop_publish_cdn_stream",GET_USER_LIST:"get_user_list",SWITCH_ROLE:"change_role",UPDATE_CONSTRAINT_CONFIG:"update_constraint_config",REBUILD_PEER_CONNECTION:"rebuild_pc",READY_TO_RECEIVE_DATA:"ready_to_receive",SPC_JOIN_ROOM:"join/v2",SPC_PUBLISH:"publish/v2",SPC_SUBSCRIBE:"subscribe/v3",ABILITY_STATUS_REPORT:"ability_status_report",RECONNECT_WS:"reconnect",SEND_CUSTOM_MSG:"channel_msg",SWITCH_ROOM:"switch_room",UPDATE_NETWORK_TIME:"update_network_time",CUSTOM_CMD:"abstract_cmd"};var Od=new Set;function u_(o){let i=[...Od.values()].find(e=>e.room.userId===o&&!e.room.isJoined);return i||null}var nI=["autoTest","relayInnerIp","relayOuterIp","mcd","newRelay","clientIp"],Ns=class extends l_.default{constructor(e){var r,s,n;super();d(this,"room");d(this,"sdkAppId");d(this,"userId");d(this,"userSig");d(this,"url");d(this,"backupUrl");d(this,"destroyed",!1);d(this,"_socketInUse");d(this,"_socket");d(this,"_backupSocket");d(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,bakRelayIps:[],reportToken:void 0});d(this,"_currentState","DISCONNECTED");d(this,"_isReconnecting",!1);d(this,"_seq",0);d(this,"_log");d(this,"_lastMessageTime",-1);d(this,"_connectStartTime",-1);d(this,"_stopConnectRetry");d(this,"_isFirstConnect",!0);d(this,"bytesSent",0);d(this,"bytesReceived",0);d(this,"keepAlive",!1);d(this,"signalDomainWhenUnifiedProxy");d(this,"stopKeepAliveTimeout");d(this,"rtt",0);this.room=e.room,this.sdkAppId=e.sdkAppId,this.userId=e.userId,this.userSig=e.userSig,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy;let t=((s=(r=this.room.scheduleResult)==null?void 0:r.config)==null?void 0:s.keepAliveClient)||0;(n=this.room.joinParams)!=null&&n.keepAlive&&!t&&(t=1),t-Od.size>0&&this.room.enableSPC&&(this.keepAlive=!0,Od.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=R.createLogger({parent:this.room.getLogger(),id:"ws",userId:this.userId,sdkAppId:this.sdkAppId}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get race(){return this.room.enableSPC&&!this.room.proxy_ws}get urlParam(){let e=`?sdkAppId=${encodeURIComponent(this.sdkAppId)}&userId=${encodeURIComponent(this.userId)}&userSig=${encodeURIComponent(this.userSig)}&keepAlive=${encodeURIComponent(Number(this.keepAlive))}`;this.signalDomainWhenUnifiedProxy&&(e+=`&signalDomain=${encodeURIComponent(this.signalDomainWhenUnifiedProxy)}`);let t=new URLSearchParams(location.search);return nI.forEach(r=>{let s=t.get(`trtc_${r}`);s&&(e+=`&${r}=${encodeURIComponent(s)}`)}),this.race?`${e}&race=1`:e}get _urlWithParam(){return`${this.url}${this.race?"/v2/ws":""}${this.urlParam}`}get _backupUrlWithParam(){return`${this.backupUrl}${this.race?"/v2/ws":""}${this.urlParam}`}get isConnected(){return this._currentState==="CONNECTED"}get isConnecting(){return this._currentState==="CONNECTING"}get isOnline(){return this._currentState==="CONNECTED"&&Date.now()-this._lastMessageTime<12*1e3}connect(){return f(this,arguments,function*(e=10*1e3){if(this.isConnected)return Promise.resolve();this._log.info(`connect to [${this.url}, ${this.backupUrl}] ${this.race?"race":""}${e?` timeout: ${e}`:""} keepAlive: ${Number(this.keepAlive)}`),this.emitConnectionStateChanged("CONNECTING"),this._connectStartTime=V();let t=[this.connectWS({url:this._urlWithParam,isMain:!0,timeout:e})];this.race&&this._backupUrlWithParam!==this._urlWithParam&&t.push(this.connectWS({url:this._backupUrlWithParam,isMain:!1,timeout:e})),this._socketInUse=yield Xr(t),this.unbindAndCloseSocket(this._socketInUse===this._socket?p.BACKUP:p.MAIN),this._isFirstConnect&&(v.addSuccessEvent({key:521720}),this._isFirstConnect=!1),this.emitConnectionStateChanged("CONNECTED")})}connectWS({url:e,timeout:t,isMain:r}){let s=new WebSocket(e);this.bindSocket(s),r?this._socket=s:this._backupSocket=s;let n=-1;return new Promise((a,c)=>{s.onclose=c,s.onerror=c,s.onopen=()=>a(s),t&&(n=setTimeout(()=>{this.unbindAndCloseSocket(r?p.MAIN:p.BACKUP),c(new D({code:I.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))},t))}).finally(()=>{s.onclose=null,s.onerror=null,s.onopen=null,clearTimeout(n)})}bindSocket(e){e.addEventListener("close",this.onclose),e.addEventListener("error",this.onerror),e.addEventListener("message",this.onmessage)}unbindSocket(e){e.removeEventListener("close",this.onclose),e.removeEventListener("error",this.onerror),e.removeEventListener("message",this.onmessage)}unbindAndCloseSocket(e){if(e===p.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(t){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(t){}this._backupSocket=null}}onclose(e){e.target===this._socketInUse&&(this._log.warn(`${e.target===this._socket?"main":"backup"} is closed code:${e.code} ${e.reason}`),this.emitConnectionStateChanged("DISCONNECTED"),(!e.wasClean||e.code!==1e3)&&this.startReconnection(),this.room.isJoining&&this.emit(Ie.SETUP_FAILED,new D({code:I.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onclose"})))}onerror(e){this._log.error(`${e.target===this._socket?"main":"backup"} error observed`),this.emitConnectionStateChanged("DISCONNECTED"),e.target===this._socketInUse&&(this.unbindAndCloseSocket(p.MAIN),this.unbindAndCloseSocket(p.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(Ie.SETUP_FAILED,new D({code:I.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(e){if(!this.isConnected)return;let{isOnline:t}=this;this._lastMessageTime=Date.now(),t||this.emit(Ie.ONLINE),this.bytesReceived+=js(e.data);let r=JSON.parse(e.data),{cmd:s,data:n}=r,a=Object.values(Jt),l=Object.keys(Jt)[a.indexOf(s)],h=W[l]||s;switch(d_.includes(s)||(this._log.debug(`received ${s} msg: ${e.data}`),h&&this._log.info(`Received event: [ ${h} ]`)),s){case Jt.CHANNEL_SETUP_RESULT:{if(r.code===0)this._signalInfo.clientIp=n.clientIp,this._signalInfo.signalIp=n.signalInnerIp,n.svrTime&&ha(n.svrTime-new Date().getTime()),this._log.info(`ChannelSetup Success ${V()-this._connectStartTime}`),v.addSuccessEvent({key:521701,cost:V()-this._connectStartTime}),this._connectStartTime=-1,this.emit(Ie.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let m=new D({code:I.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:r.code,message:$({key:B.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:r.code,errorMsg:r.message}})});this._log.error(`${r.code}, ${r.message}`),this.close(),v.addFailedEvent({key:521701,error:m}),this.emit(Ie.SETUP_FAILED,m)}break}case Jt.JOIN_ROOM_RESULT:{r.code===0&&(this._signalInfo.relayIp=n.relayOuterIp,this._signalInfo.relayInnerIp=n.relayInnerIp,this._signalInfo.bakRelayIps=n.bakRelayIps,this._signalInfo.relayPort=n.relayPort,this._signalInfo.tinyId=r.tinyId,this._signalInfo.endReportExtend=n.endReportExtend,this._signalInfo.reportToken=n.reportToken,this._log.info(`signalIp:${this._signalInfo.signalIp} clientIp:${this._signalInfo.clientIp} relayIp: ${this._signalInfo.relayIp}`)),this.emit(h,{data:r});break}default:this.emit(String(h),{data:r});break}}reGetSignalChannelUrl(){return f(this,null,function*(){try{if(!this.room.joinParams)return;Lt(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(e){}})}startReconnection(){if(!this._socketInUse)return;this._socketInUse.onclose=null,this._socketInUse.close(4011);let e=this._socketInUse===this._socket;this.unbindAndCloseSocket(e?p.MAIN:p.BACKUP),this._socketInUse=null,this.emitConnectionStateChanged("DISCONNECTED"),this.reconnect()}reconnect(){return f(this,null,function*(){if(!this._isReconnecting){if(!this.room.isJoined&&this.keepAlive){this.close();return}this._isReconnecting=!0;try{this._log.warn("reconnect"),yield this.connect();let{roomId:e,useStringRoomId:t}=this.room,{relayIp:r,relayInnerIp:s,relayPort:n}=this._signalInfo,{data:a}=yield this.sendWaitForResponse({command:Z.RECONNECT_WS,data:{roomId:e,useStringRoomId:t,relayInnerIp:s,relayOuterIp:r,relayPort:n},responseCommand:W.CHANNEL_RECONNECT_RESULT});a.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),v.addSuccessEvent({key:521702,cost:V()-this._connectStartTime}),this._connectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(v.addFailedEvent({key:521702,error:a.code}),this._log.warn(`reconnect failed, ${a.code} ${a.message}`),this.room.reJoin())}catch(e){this._log.error(e),this.room.reJoin()}}})}send(e,t={}){if(this.isConnected&&!this.room.isLeft){let r={cmd:e,data:t,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},s=JSON.stringify(r);return this._socketInUse.send(s),this.bytesSent+=js(s),r.seq}}sendWaitForResponse({command:e,data:t,timeout:r=5e3,responseCommand:s,commandDesc:n,enableLog:a=!0,addReceiveTime:c=!1}){return new Promise((l,h)=>{let m=()=>{clearTimeout(u),h(new D({code:I.API_CALL_ABORTED,message:`${e} aborted due to connection closed`}))};this.once(Ie.CLOSE,m);let u=setTimeout(()=>{this.off(s,_),this.off(Ie.CLOSE,m);let E=new D({code:I.API_CALL_TIMEOUT,message:$({key:B.API_CALL_TIMEOUT,data:{commandDesc:n,command:e}})});a&&this._log.warn(E),h(E)},r),_=E=>{E.data.seq===g&&(clearTimeout(u),this.off(s,_),this.off(Ie.CLOSE,m),c&&(E.data.receiveTime=Date.now()),l(E))};this.on(s,_);let g=this.send(e,t)})}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:r,retries:s=0,retryTimeout:n=0}=e;return Ci({retryFunction:this.sendWaitForResponse,onError:({retry:a,reject:c,error:l})=>{!this.room.isJoined||this.destroyed||l.code===I.API_CALL_ABORTED?c(l):this.isOnline?a():(this._log.warn(`retry ${r} when connected`),this.once(Ie.ONLINE,a))},onRetrying:a=>{this._log.warn(`${t||r} timeout observed, retrying [${a}/${s}]`)},settings:{retries:s,timeout:n},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),clearTimeout(this.stopKeepAliveTimeout),Od.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,bakRelayIps:[],endReportExtend:void 0,reportToken:void 0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(p.MAIN),this.unbindAndCloseSocket(p.BACKUP),this.emitConnectionStateChanged("DISCONNECTED"),this.emit(Ie.CLOSE)}destroy(){this.close(),this.destroyed=!0}getBackupRelayIpPair(){var t;let e=(t=this._signalInfo.bakRelayIps)==null?void 0:t.shift();return e&&(e.relayPort=e.relayPort||this._signalInfo.relayPort),e}clearBakRelayIps(){this._signalInfo.bakRelayIps=[]}stopKeepAliveIn(e=3600){if(this.keepAlive){this._log.info(`stopKeepAlive in ${e}s`),this.stopKeepAliveTimeout=setTimeout(()=>{this.keepAlive=!1,this._log.info(`close due to not used ${e}s`),this.close(),this.off(W.JOIN_ROOM_RESULT,t)},e*1e3);let t=r=>{r.data.code===0&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(W.JOIN_ROOM_RESULT,t))};this.on(W.JOIN_ROOM_RESULT,t)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info(`${this._currentState} -> ${e}`),this.emit(Ie.CONNECTION_STATE_CHANGED,{prevState:this._currentState,state:e}),this._currentState=e,e==="CONNECTED"?this.emit(Ie.CONNECTED):e==="DISCONNECTED"&&this.emit(Ie.DISCONNECTED))}};M([Mt({settings:{retries:1/0,timeout:2e3},onError(e,t){!this.room.isDestroyed&&!this.destroyed&&(this._isFirstConnect&&(v.addFailedEvent({key:521720,error:e}),this._isFirstConnect=!1),t())},onRetrying(e,t){this._log.warn(`retrying to connect ${e}`),e>=3&&e%3===0&&this.reGetSignalChannelUrl(),t&&(this._stopConnectRetry=t,(this.room.isDestroyed||this.destroyed)&&t())}})],Ns.prototype,"connect",1);var h_=Je(at());var Kh=0,em=!1,kd=new Set,aI=o=>Kh>2&&!em&&kd.size===0&&o,tm=!1,pt=class{constructor(i){d(this,"userId");d(this,"tinyId");d(this,"_sdpSemantics");d(this,"_isUplink");d(this,"_room");d(this,"_log");d(this,"_signalChannel");d(this,"_isErrorObserved",!1);d(this,"_waitForPeerConnectionConnectedPromise");d(this,"_waitForPeerConnectionConnectedPromiseReject",null);d(this,"_peerConnection",null);d(this,"_emitter",new h_.default);d(this,"_currentState","DISCONNECTED");d(this,"_isReconnecting",!1);d(this,"_reconnectionCount",0);d(this,"_reconnectionTimer",-1);d(this,"_isFirstConnection",!0);d(this,"_prevTime",-1);d(this,"_localAddress");d(this,"_remoteAddress");this.userId=i.userId,this.tinyId=i.tinyId,this._room=i.room,this._sdpSemantics=i.room.sdpSemantics,this._isUplink=i.isUplink,this._log=i.room.getLogger().createChild({id:"n-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=i.signalChannel}beforeConnect(){this._prevTime<0&&(this._prevTime=V())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,v.addSuccessEvent({key:521705,cost:Math.min(V()-this._prevTime,30*1e3)})):this._isReconnecting&&v.addSuccessEvent({key:521706,cost:V()-this._prevTime}),this._prevTime=-1}catch(i){throw this._isFirstConnection?(this._isFirstConnection=!1,v.addFailedEvent({key:521705,error:i})):this._isReconnecting&&this._reconnectionCount>=3&&v.addFailedEvent({key:521706,error:i}),i}}initialize(){let i={iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"};this._peerConnection=new RTCPeerConnection(i),this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this)}close(i){this._log.info("close connection"),this._emitter.emit("closed",i),this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),kd.delete(this)}closePeerConnection(i=!1){this._peerConnection&&(this._log.info("close pc"),this._peerConnection.onconnectionstatechange=null,this._peerConnection.close(),this._peerConnection=null,i&&this.emitConnectionStateChangedEvent("DISCONNECTED")),this._waitForPeerConnectionConnectedPromiseReject&&this._waitForPeerConnectionConnectedPromiseReject(new D({code:I.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return Yt;let i=null;if(this._isUplink){if(!yr()||this._peerConnection.getSenders().length===0)return Yt;i=this._peerConnection.getSenders()[0].transport}else{if(!oo()||this._peerConnection.getReceivers().length===0)return Yt;i=this._peerConnection.getReceivers()[0].transport}return i?i.state:Yt}onConnectionStateChange(i){let e=this._peerConnection.iceConnectionState,t=this.getDTLSTransportState();if(this._log.info(`connectionState: ${i.target.connectionState}, ICE: ${e}, DTLS: ${t}`),i.target.connectionState===ye.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),i.target.connectionState===ye.FAILED||i.target.connectionState===ye.CLOSED){let r=`connection ${i.target.connectionState}. ICE Transport state: ${e}, DTLS Transport state: ${t}`,s=new D({message:r,code:I.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",s)}(i.target.connectionState===ye.CONNECTED||i.target.connectionState===ye.COMPLETED)&&(this.logSelectedCandidate(),ne.logSuccessEvent({userId:this._room.userId,eventType:Ke.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(i){return i===this._currentState?!1:(i==="CONNECTED"?(Kh=0,em=!1,tm=!0,kd.add(this)):kd.delete(this),S.emit(C.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:i,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:i}),this._currentState=i,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}logSelectedCandidate(){return f(this,null,function*(){if(!this._peerConnection)return;let i=yield this._peerConnection.getStats();for(let[,e]of i)if(Rr(e)){let t=i.get(e.localCandidateId),r=i.get(e.remoteCandidateId);t&&(this._log.info(`local candidate: ${t.candidateType} ${t.protocol}:${t.ip||t.address}:${t.port} ${t.networkType||""} ${t.candidateType==="relay"?`relayProtocol:${t.relayProtocol}`:""}`),this._localAddress=`${t.ip||t.address}:${t.port}`),r&&(this._log.info(`remote candidate: ${r.candidateType} ${r.protocol}:${r.ip||r.address}:${r.port}`),this._remoteAddress=`${r.protocol}:${r.ip||r.address}`);break}})}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise?this._waitForPeerConnectionConnectedPromise:(this._waitForPeerConnectionConnectedPromise=new Promise((i,e)=>{if(this._currentState==="CONNECTED")return i();this._waitForPeerConnectionConnectedPromiseReject=e;let t=a=>{a.state==="CONNECTED"&&(clearTimeout(n),s(),i())},r=({room:a})=>{a===this._room&&(clearTimeout(n),s(),e(new D({code:I.API_CALL_ABORTED,message:$({key:B.CONNECTION_ABORTED,data:"leave room"})})))},s=()=>{S.off(C.LEAVE_SUCCESS,r,this),this._emitter.off("connection-state-changed",t,this)},n=setTimeout(()=>{s();let a=new D({code:I.API_CALL_TIMEOUT,message:"connection timeout"});Kh+=1,aI(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),em=!0,this._emitter.emit("firewall-restriction")),e(a)},$s);S.on(C.LEAVE_SUCCESS,r,this),this._emitter.on("connection-state-changed",t,this)}),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally(()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null}),this._waitForPeerConnectionConnectedPromise)}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(Ie.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=Hi()){this._log.warn(`SDK has tried reconnect for ${this._reconnectionCount} times, but all failed, please check your network`),this.stopReconnection();let i=new D({code:this._isUplink?I.UPLINK_RECONNECTION_FAILED:I.DOWNLINK_RECONNECTION_FAILED,message:$({key:this._isUplink?B.UPLINK_RECONNECTION_FAILED:B.DOWNLINK_RECONNECTION_FAILED})});return this.emitConnectionStateChangedEvent("DISCONNECTED"),this._emitter.emit("error",i),-1}return this._signalChannel.isConnected?(this._reconnectionCount+=1,this._log.warn(`reconnect() trying [${this._reconnectionCount}]`),1):(this._log.warn("reconnect() signal channel is not connected, suspend reconnection until signal is connected"),this._signalChannel.once(Ie.CONNECTED,this.reconnect,this),-1)}on(i,e,t){this._emitter.on(i,e,t)}off(i,e,t){this._emitter.off(i,e,t)}getIsReconnecting(){return this._isReconnecting}get isH264(){var i,e;return!!((e=(i=this._peerConnection)==null?void 0:i.remoteDescription)!=null&&e.sdp.includes("H264"))}setOffer(i){var e;return(e=this._peerConnection)==null?void 0:e.setLocalDescription(i)}setAnswer(i){var e;return(e=this._peerConnection)==null?void 0:e.setRemoteDescription(i)}};M([Rt(521712,!1)],pt.prototype,"setOffer",1),M([Rt(521713,!1)],pt.prototype,"setAnswer",1);var sm=Je(om());var De=function(o){return sm.default.parse(o)},jt=function(o){return sm.default.write(o)},S_=function(o){let i=De(o);return i.media.forEach(e=>{e.type===p.AUDIO&&e.fmtp.forEach(t=>{t.config+=";sprop-stereo=1;stereo=1"})}),jt(i)};function I_(o){let i=De(o);return i.media.forEach(e=>{var t,r;if(e.type===p.VIDEO){let s=new Set;e.rtp.forEach(({payload:a,codec:c})=>c==="H264"&&s.add(a)),e.fmtp.forEach(({payload:a,config:c})=>{let l=c.match(/apt=(\d+)/);l&&l[1]&&s.has(Number(l[1]))&&s.add(a)});let n=({payload:a})=>!s.has(a);e.rtp=e.rtp.filter(n),e.rtcpFb=(t=e.rtcpFb)==null?void 0:t.filter(n),e.fmtp=e.fmtp.filter(n),e.payloads=(r=e.payloads)==null?void 0:r.split(" ").filter(a=>!s.has(Number(a))).join(" ")}}),jt(i)}var Ro=class{constructor(i){d(this,"remoteVideoTrack");d(this,"remoteAudioTrack");d(this,"log");this.remoteVideoTrack=i.remoteVideoTrack,this.remoteAudioTrack=i.remoteAudioTrack,this.log=i.log.createChild({id:"pip"}),this.videoPlayer.on(K.USER_RESUME_IN_PIP,this.handleUserResumeInPIP,this),this.videoPlayer.on(K.USER_PAUSE_IN_PIP,this.handleUserPauseInPIP,this),this.videoPlayer.on(K.LEAVE_PICTURE_IN_PICTURE,this.handleLeavePIP,this)}get audioPlayer(){return this.remoteAudioTrack.player}get videoPlayer(){return this.remoteVideoTrack.player}handleUserResumeInPIP(){this.audioPlayer.isPaused&&(this.log.warn("resume when in pip"),this.audioPlayer.doResume())}handleUserPauseInPIP(){this.audioPlayer.isPaused||(this.log.warn("pause when in pip"),this.audioPlayer.doPause())}handleLeavePIP(){var e;this.audioPlayer.isPaused&&!this.audioPlayer.isPausedByUserCall&&(this.log.warn("resume after leave pip"),this.audioPlayer.doResume());let i=()=>f(this,null,function*(){var t;fe&&((t=this.remoteVideoTrack.outMediaTrack)!=null&&t.muted)&&this.remoteVideoTrack.isSubscribed&&(this.log.warn("video decode failed after exit pip, resubscribe"),yield this.remoteVideoTrack.room.unsubscribe(this.remoteVideoTrack),yield this.remoteVideoTrack.room.subscribe(this.remoteVideoTrack))});fe&&((e=this.remoteVideoTrack.outMediaTrack)==null||e.addEventListener("mute",i)),Ge(5e3).then(()=>{var t;(t=this.remoteVideoTrack.outMediaTrack)==null||t.removeEventListener("mute",i)})}destroy(){this.videoPlayer.off(K.USER_RESUME_IN_PIP,this.handleUserResumeInPIP,this),this.videoPlayer.off(K.USER_PAUSE_IN_PIP,this.handleUserPauseInPIP,this),this.videoPlayer.off(K.LEAVE_PICTURE_IN_PICTURE,this.handleLeavePIP,this)}};function Pd(o){return Object.keys(o).filter(i=>o[i])}var Ms=class Ms extends pt{constructor(e){super(L(O({},e),{isUplink:!1}));d(this,"_flag",0);d(this,"isRobot",!1);d(this,"role","anchor");d(this,"remoteAudioTrack");d(this,"remoteVideoTrack");d(this,"remoteAuxiliaryTrack");d(this,"pipSyncManager");d(this,"ssrc",{audio:0,video:0,auxiliary:0});d(this,"_isSDPExchanging",!1);d(this,"_videoCodec");this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=e.remoteAudioTrack||new Ti(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new ki(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new Is(this._room,this),this.pipSyncManager=new Ro({log:this._log,remoteVideoTrack:this.remoteVideoTrack,remoteAudioTrack:this.remoteAudioTrack})}get videoCodec(){var t,r;let e=(r=(t=this._peerConnection)==null?void 0:t.remoteDescription)==null?void 0:r.sdp;return e?e.includes("H264")?"h264":"vp8":this._videoCodec||"h264"}set videoCodec(e){this._videoCodec=e}get subscribeState(){let e={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(this.remoteVideoTrack.mediaType&8?e.smallVideo=!0:e.video=!0),this.remoteAudioTrack.isSubscribed&&(e.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(e.auxiliary=!0),e}get muteState(){return ei(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,r,s;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(r=this.remoteVideoTrack)==null||r.onFlagChanged(),(s=this.remoteAuxiliaryTrack)==null||s.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===p.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.pipSyncManager.destroy(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var s,n;let t=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&t!==e&&((s=this.remoteVideoTrack)==null||s.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),r}onTrack(e){let t=e.streams[0],{track:r}=e,s=t.id===Hs?p.MAIN:p.AUXILIARY;this._log.debug(`ontrack ${s} ${r.kind}`);let n=p.AUDIO;r.kind===p.VIDEO&&(n=s===p.MAIN?p.VIDEO:p.AUXILIARY);let a=this.remoteAudioTrack;n===p.VIDEO?a=this.remoteVideoTrack:n===p.AUXILIARY&&(a=this.remoteAuxiliaryTrack),a.setInputMediaStreamTrack(r)}addRRTRLine(e){let t=e.split(`\r
69
+ `),r=new Map;t.forEach((n,a)=>{/^a=rtcp-fb:/.test(n)&&t[a+1]&&!/^a=rtcp-fb:/.test(t[a+1])&&r.set(a+1,`${n.match(/^a=rtcp-fb:\d+/)[0]} rrtr`)});let s=[...r];for(let n=0;n<s.length;n++){let[a,c]=s[n];t.splice(a+n,0,c)}return t.join(`\r
70
+ `)}addSPSDescription(e){let t=De(e);return t.media.forEach(r=>{r.type===p.VIDEO&&r.fmtp.forEach(s=>{s.config+=";sps-pps-idr-in-keyframe=1"})}),jt(t)}removeSDESDescription(e){let t=["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"],r=De(e);return r.media.forEach(s=>{s.ext&&(s.ext=s.ext.filter(n=>!t.includes(n.uri)))}),jt(r)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return f(this,null,function*(){var r,s;try{if((((r=this._peerConnection)==null?void 0:r.connectionState)===ye.NEW||((s=this._peerConnection)==null?void 0:s.connectionState)===ye.CONNECTING)&&(yield this.waitForPeerConnectionConnected()),this.isSubscriptionStateNotChanged(e)){this._peerConnection||(this.initialize(),yield this.connect(e));return}if(this._log.info(`subscribe ${t} ${JSON.stringify(e)}`),this._peerConnection||this._isSDPExchanging){let n="subscribe_change";Object.values(e).find(a=>a===!0)||(n="unsubscribe"),yield this.sendSubscription(n,e)}else this.initialize(),yield this.connect(e)}catch(n){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${n.message} ${JSON.stringify(this.muteState)}`),new D({code:I.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):n}})}unsubscribe(r){return f(this,arguments,function*({remoteTracks:e,streamType:t}){if(this._currentState==="CONNECTED"&&(t==="main"&&!this.isMainStreamSubscribed||t==="auxiliary"&&!this.isAuxStreamSubscribed)){this._log.info(`${t} stream already unsubscribed`);return}let s=O({},this.subscribeState);e.forEach(a=>{switch(a.mediaType){case 1:s.audio=!1;break;case 4:s.video=!1;break;case 8:s.smallVideo=!1;break;case 2:s.auxiliary=!1;break;default:break}});let n="subscribe_change";Object.values(s).find(a=>a===!0)||(n="unsubscribe"),this._log.info(`${n==="unsubscribe"?n:"subscribe"} ${t} [${Pd(s)}]`),yield this.sendSubscription(n,s),n==="unsubscribe"&&(this.closePeerConnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"))})}sendSubscription(e,t=this.subscribeState){let r={srcTinyId:this.tinyId,srcUserId:this.userId},s=Z.UNSUBSCRIBE,n=W.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(r={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},s=Z.SUBSCRIBE_CHANGE,n=W.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:s,data:r,responseCommand:n,timeout:1e4}).then(({data:a})=>{if(a.code!==0){let c=new D({code:a.code,message:$({key:B.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(c),c}})}connect(){return f(this,arguments,function*(e=this.subscribeState){try{yield this.exchangeSDP(e),yield this.waitForPeerConnectionConnected()}catch(t){throw this.closePeerConnection(!0),t}})}exchangeSDP(e){return f(this,null,function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info("createOffer success, sending offer");let{type:t,sdp:r}=this._peerConnection.localDescription,s={type:t,sdp:r,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},n=yield this._signalChannel.sendWaitForResponse({command:Z.SUBSCRIBE,commandDesc:"exchange sdp",data:s,responseCommand:W.SUBSCRIBE_RESULT,timeout:cl});if(!this._peerConnection){let a=new D({code:I.INVALID_OPERATION,message:$({key:B.CONNECTION_CLOSED})});throw this._log.warn(a),a}yield this.onSubscribeResult(n),this._isSDPExchanging=!1}catch(t){throw this._isSDPExchanging=!1,t}})}createOffer(){return f(this,null,function*(){let e={voiceActivityDetection:!1};St()&&this._sdpSemantics===gr?(this._peerConnection.addTransceiver(p.AUDIO,{direction:ae.RECVONLY}),this._peerConnection.addTransceiver(p.VIDEO,{direction:ae.RECVONLY}),this._peerConnection.addTransceiver(p.VIDEO,{direction:ae.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:r}=yield Sc();r||(this._log.warn("remove h264 desc from sdp"),t.sdp=I_(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=S_(t.sdp),this._sdpSemantics===gr&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this.setOffer(t)})}onSubscribeResult(e){return f(this,null,function*(){let{code:t,message:r=""}=e&&e.data||{},{type:s,sdp:n}=e&&e.data&&e.data.data||{};if(t===$r)throw new D({code:I.NOT_SUPPORTED_H264,message:$({key:B.NOT_SUPPORTED_H264DECODE})});try{if(t!==0)throw new D({code:t,message:$({key:B.EXCHANGE_SDP_FAILED,data:{errMsg:r}})});this._log.debug(`accept remote answer: ${n}`),yield this.setAnswer({type:s,sdp:n}),this.updateSSRC(n)}catch(a){throw this._log.error(a),a}})}updateSSRC(e){try{De(e).media.forEach(r=>{if(r.ssrcs)if(r.type===p.AUDIO){let s=r.ssrcs.find(n=>{var a;return(a=n.value)==null?void 0:a.includes(Hs)});s&&(this.ssrc.audio=Number(s.id))}else{let s=r.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(Hs)}),n=r.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(rl)});s&&(this.ssrc.video=Number(s.id)),n&&(this.ssrc.auxiliary=Number(n.id))}})}catch(t){}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return f(this,null,function*(){if(!(we(Ms.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch(t){let r=Kt(this._reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${r/1e3}s`),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},r)}})}getIsReconnecting(){return this._isReconnecting}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}getCurrentState(){return this._currentState}setDelay({audioDelay:e,videoDelay:t}){this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=t}get audioReceiver(){var e;return((e=this._peerConnection)==null?void 0:e.getReceivers()[0])||null}};M([Y(e=>function(...t){return new Promise((r,s)=>{let n=a=>{this._emitter.off("closed",n),s(new D({code:I.API_CALL_ABORTED,message:$({key:B.CONNECTION_ABORTED,data:a})}))};this._emitter.on("closed",n),e.apply(this,t).then(r,s).finally(()=>{this._emitter.off("closed",n)})})})],Ms.prototype,"subscribe",1),M([Rt(521717,!1)],Ms.prototype,"unsubscribe",1),M([Ct(pt.prototype.afterConnect),Lc(pt.prototype.beforeConnect)],Ms.prototype,"connect",1);var nm=Ms,am=nm;var C_={voiceActivityDetection:!1},Os=class Os extends pt{constructor(e){super(L(O({},e),{isUplink:!0}));d(this,"localMainAudioTrack",null);d(this,"localMainVideoTrack",null);d(this,"localAuxAudioTrack",null);d(this,"localAuxVideoTrack",null);d(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0});d(this,"_isPublishingAux",!1);d(this,"_publishingLocalAudioTrack");d(this,"_publishingLocalVideoTrack");d(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0});d(this,"flag",0)}get videoCodec(){return this._mediaSettings.videoCodec.toLowerCase()||"h264"}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}initialize(){super.initialize(),this.installEvents()}reset(){this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this.uninstallEvents()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this._emitter.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this._emitter.on("connection-state-changed",this.handleConnectionStateChange,this)}uninstallEvents(){this._emitter.off("connection-state-changed",this.handleConnectionStateChange,this)}emitConnectionStateChangedEvent(e,t){var n,a,c;let r=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&r!==e&&(t?t.emit("connection-state-changed",{prevState:r,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:r,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:r,state:e}),(c=this._publishingLocalVideoTrack)==null||c.emit("connection-state-changed",{prevState:r,state:e}))),s}publish(s){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:r}){this._peerConnection||this.initialize(),e&&(this._publishingLocalAudioTrack=e),t&&(this._publishingLocalVideoTrack=t),this._isPublishingAux=r;let n;t&&!r&&t.small&&(n=this._room.videoManager.smallTrack),this.sendMediaSettings(),St()?yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:n,isAuxiliary:r}):yield this.publishByAddTrack({localAudioTrack:e,localVideoTrack:t,smallTrack:n}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,r?(t&&(this.localAuxVideoTrack=t),e&&(this.localAuxAudioTrack=e)):(t&&(this.localMainVideoTrack=t),e&&(this.localMainAudioTrack=e)),this.installTrackMuteEvents(e,t),this.sendMutedFlag()})}publishByTransceiver(n){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:r,isAuxiliary:s}){this._log.info("publish by transceiver");let a=new MediaStream,c=t==null?void 0:t.outMediaTrack,l=e==null?void 0:e.outMediaTrack;l&&a.addTrack(l),c&&a.addTrack(c);let h=this._peerConnection.getTransceivers();if(h.length===0)this._peerConnection.addTransceiver(l||p.AUDIO,{direction:ae.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(s?p.VIDEO:c||p.VIDEO,{direction:ae.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(r||p.VIDEO,{direction:ae.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(s?c||p.VIDEO:p.VIDEO,{direction:ae.SENDONLY,streams:[a]}),yield this.connect();else{let m=[];if(l&&(h[0].sender.track||m.push(0),yield h[0].sender.replaceTrack(l),yield this.setBandwidth({bandwidth:(e==null?void 0:e.profile.bitrate)||40,type:p.AUDIO})),c){let u=s?3:1;yield h[u].sender.replaceTrack(c),yield this.setBandwidth({bandwidth:t.profile.bitrate,type:p.VIDEO,videoType:s?p.AUXILIARY:p.BIG}),m.push(u),r&&(yield h[2].sender.replaceTrack(r),yield this.setBandwidth({bandwidth:t.small.bitrate,type:p.VIDEO,videoType:p.SMALL}),m.push(2))}yield this.setTransceiverDirection(ae.SENDONLY,m),yield this.doPublishChange(),t==null||t.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),t==null||t.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"})}})}publishByAddTrack(s){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:r}){this._log.info("publish by addtrack");let n=t==null?void 0:t.outMediaTrack,a=e==null?void 0:e.outMediaTrack;if(this._peerConnection&&this._peerConnection.connectionState!=="new"){e&&a&&(yield this.addTrack(e)),n&&(yield this.addTrack(t));return}let c=new MediaStream;if(a&&c.addTrack(a),n&&c.addTrack(n),a&&this._peerConnection.addTrack(a,c),n&&(this._peerConnection.addTrack(n,c),r)){let l=new MediaStream;l.addTrack(r),this._peerConnection.addTrack(r,l)}yield this.connect()})}enableSmall(e){return f(this,null,function*(){let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.setTransceiverDirection(ae.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(ae.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()})}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(r){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){if(!br()){if(e&&e.outMediaTrack&&!t&&this.localMainVideoTrack){yield this.removeTrack(e),this.localMainAudioTrack=null;return}if(t&&t.outMediaTrack&&!e&&this.localMainAudioTrack){yield this.removeTrack(t),this.localMainVideoTrack=null;return}yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),this.emitConnectionStateChangedEvent("DISCONNECTED",t);return}let s=t&&t===this.localAuxVideoTrack,n=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),c=[];e&&(s?this.localAuxAudioTrack=null:this.localMainAudioTrack=null,!this.localAuxAudioTrack&&!this.localMainAudioTrack&&(yield a[0].replaceTrack(null),c.push(0))),n&&(s?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=L(O({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),c.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=L(O({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),c.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.setTransceiverDirection(ae.INACTIVE,c),yield this.doPublishChange(!1)):yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),t==null||t.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return f(this,null,function*(){let t={state:this._room.publishState,constraintConfig:this._mediaSettings},r=yield this._signalChannel.sendWaitForResponse({command:Z.PUBLISH_STATE_CHANGE,data:t,responseCommand:W.PUBLISH_STATE_CHANGE_RESULT,enableLog:e});this.checkPublishResultCode(r.data.code,r.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:Z.UNPUBLISH,commandDesc:"unpublish",responseCommand:W.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===I.API_CALL_TIMEOUT)return Promise.resolve();throw t})}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let r=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:s,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:s=this._publishingLocalVideoTrack),bi){if(r&&r.outMediaTrack){let a=r.outMediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=r.profile.bitrate*1e3,this._mediaSettings.audioFs=a.sampleRate||0}if(s&&s.outMediaTrack){let a=s.outMediaTrack.getSettings();this._mediaSettings.videoWidth=a.width||0,this._mediaSettings.videoHeight=a.height||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=s.profile.bitrate*1e3,s.small&&(this._mediaSettings.smallVideoWidth=s.small.width,this._mediaSettings.smallVideoHeight=s.small.height,this._mediaSettings.smallVideoFps=s.small.frameRate,this._mediaSettings.smallVideoBps=s.small.bitrate*1e3)}if(n&&n.outMediaTrack){let a=n.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=a.width||0,this._mediaSettings.auxVideoHeight=a.height||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=n.profile.bitrate*1e3}}else r&&r.outMediaTrack&&(this._mediaSettings.audioChannel=r.profile.channelCount,this._mediaSettings.audioBps=r.profile.bitrate*1e3,this._mediaSettings.audioFs=r.profile.sampleRate),s&&s.outMediaTrack&&(this._mediaSettings.videoWidth=s.profile.width,this._mediaSettings.videoHeight=s.profile.height,this._mediaSettings.videoFps=s.profile.frameRate,this._mediaSettings.videoBps=s.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:Z.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:W.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return f(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is adding ${e.kind} track to current published local ${t?p.AUXILIARY:p.MAIN} stream`),St()?yield this.addTrackByTransceiver(e,t):yield this.addTrackBySender(e)})}addTrackByTransceiver(e,t){return f(this,null,function*(){var s;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===p.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),n===1&&((s=this.localMainVideoTrack)!=null&&s.small)&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===ae.INACTIVE&&(yield this.setTransceiverDirection(ae.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}addTrackBySender(e){return f(this,null,function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;br()&&this._peerConnection.getTransceivers().findIndex(s=>s.direction==="stopped")>=0&&(this._log.warn("transceiver is stopping, negotiate sdp first"),yield this.updateOffer("remove",t));let r=this._peerConnection.getSenders().find(s=>s.track&&s.track.kind===t.kind);if(r&&r.track){this._log.warn("sender already exists, remove sender first");let s=r.track;this.removeSender(r),yield this.updateOffer("remove",s)}if(t&&this._peerConnection.addTrack(t,new MediaStream([t])),t.kind===p.VIDEO&&e instanceof ze&&e.small){let s=new MediaStream,{smallTrack:n}=this._room.videoManager;s.addTrack(n),this._peerConnection.addTrack(n,s)}yield this.updateOffer("add",t)})}isNeedToResetOfferOrder(){if(this._sdpSemantics===ko||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=De(e);for(let r=0;r<t.media.length;r++)if(Number(t.media[r].mid)===0&&t.media[r].type===p.VIDEO)return!0;return!1}removeSender(e){let t=null;br()&&(t=this._peerConnection.getTransceivers().find(r=>r.sender&&r.sender.track===e.track)),this._peerConnection.removeTrack(e),t&&me(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return f(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${t?p.AUXILIARY:p.MAIN} stream`),St()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)})}removeTrackByTransceiver(e,t){return f(this,null,function*(){if(!e.outMediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===p.AUDIO)yield r[0].sender.replaceTrack(null);else{let s=t?3:1;yield r[s].sender.replaceTrack(null),s===1&&e.small&&(yield r[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(ae.INACTIVE,[s])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,t){return f(this,null,function*(){if(!te)return;let r=!1,s=!1;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let n=this._peerConnection.getTransceivers();if(t.forEach(l=>{n[l].direction!==e&&(n[l].direction=e,r=!0)}),r){this._log.info("updating offer");let l=yield this._peerConnection.createOffer();yield this.setOffer(l)}let a=-1,c=this._peerConnection.remoteDescription.sdp.split(`\r
71
+ `).map(l=>{if(l.match(new RegExp(`a=(${ae.INACTIVE}|${ae.RECVONLY}|${ae.SENDONLY})`))&&a++,t.includes(a)){if(e===ae.INACTIVE&&l.includes(`a=${ae.RECVONLY}`))return s=!0,`a=${e}`;if(e===ae.SENDONLY&&l.includes(`a=${ae.INACTIVE}`))return s=!0,`a=${ae.RECVONLY}`}return l}).join(`\r
72
+ `);s&&(this._log.info("updating answer"),yield this.setAnswer({type:"answer",sdp:c}))})}removeTrackBySender(e){return f(this,null,function*(){if(!e.outMediaTrack)return;if(e.kind===p.VIDEO&&this.isNeedToResetOfferOrder()&&this.localMainAudioTrack){this.reset(),this.initialize(),yield this.publish({localAudioTrack:this.localMainAudioTrack,isAuxiliary:!1});return}let t=this._peerConnection.getSenders().find(r=>r.track===e.outMediaTrack);t&&(this.removeSender(t),e.kind===p.VIDEO&&e.small&&this._peerConnection.getSenders().forEach(r=>{r.track&&r.track.kind===p.VIDEO&&this.removeSender(r)})),yield this.updateOffer("remove",e.outMediaTrack)})}replaceTrack(e){return f(this,null,function*(){var n;let t=(n=this._peerConnection)==null?void 0:n.getSenders();if(!t||t.length===0||!e.mediaTrack)return!1;let r;if(St()?r=e.kind===p.AUDIO?t[0]:t[1]:r=t.find(a=>a.track&&a.track.kind===e.kind),!r)return!1;let s=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info(`is replacing ${e.kind} track on ${s?p.AUXILIARY:p.MAIN} stream`),e.kind===p.AUDIO?yield r.replaceTrack(e.outMediaTrack):e.kind===p.VIDEO&&(s?t[3]&&(yield t[3].replaceTrack(e.outMediaTrack)):yield r.replaceTrack(e.outMediaTrack)),!0})}updateOffer(e,t){return f(this,null,function*(){try{let r=yield this._peerConnection.createOffer(C_);te&&r.sdp&&(r.sdp=this.setSDPDirection(r.sdp,"sendrecv")),yield this.setOffer(r);let s=this.updateMediaSettings(),n={action:e,trackId:t.id,kind:t.kind===p.VIDEO?"bigVideo":t.kind,type:"offer",sdp:this._peerConnection.localDescription.sdp,constraintConfig:s,state:this._room.publishState};this._log.info("createOffer success, sending updated offer to remote server"),this._log.debug(`updatedOffer: ${n.sdp}`);let a=yield this._signalChannel.sendWaitForResponse({command:Z.PUBLISH_CHANGE,data:n,responseCommand:W.UPDATE_OFFER_RESULT,timeout:al,commandDesc:"update offer"}),{code:c,message:l}=a.data;c!==0&&this.checkPublishResultCode(c,l),yield this.acceptAnswer(a.data.data),r.sdp&&this.updateSSRC(r.sdp)}catch(r){throw this._log.error(r),r}})}setBandwidth(n){return f(this,arguments,function*({bandwidth:e,type:t,videoType:r,sdp:s}){if(!In())return s?t===p.VIDEO?this.updateVideoBandwidthRestriction(s,e,r):this.updateAudioBandwidthRestriction(s,e):void 0;let a,c=this._peerConnection.getSenders();if(St()){let l=0;t===p.VIDEO&&(r===p.SMALL?l=2:r===p.AUXILIARY?l=3:l=1),a=c[l]}else a=c.find(l=>l.track&&l.track.kind===t);if(a){let l=a.getParameters();(!l.encodings||l.encodings.length===0)&&(l.encodings=[{}]),l.encodings[0].maxBitrate=e*1e3;try{return yield a.setParameters(l),this._log.info(`${r||""}${t} bandwidth ${e} kbps`),s}catch(h){if(this._log.info(`failed to set bandwidth by setting maxBitrate: ${h}`),s)return t===p.VIDEO?this.updateVideoBandwidthRestriction(s,e,r):this.updateAudioBandwidthRestriction(s,e)}}return s})}updateVideoBandwidthRestriction(e,t,r){let s="AS";te&&(s="TIAS",t=t*1e3);let n=0,a=-1;return r===p.SMALL?n=1:r===p.AUXILIARY&&(n=2),e=e.replace(/m=video (.*)\r\nc=IN (.*)\r\n/g,c=>(a+=1,a===n?`${c}b=${s}:${t}\r
73
+ `:c)),e}updateAudioBandwidthRestriction(e,t){let r="AS";return te&&(r="TIAS",t=t*1e3),e=e.replace(/m=audio (.*)\r\nc=IN (.*)\r\n/,`m=audio $1\r
64
74
  c=IN $2\r
65
75
  b=${r}:${t}\r
66
- `),e}removeBandwidthRestriction(e){return e.replace(/b=AS:.*\r\n/,"").replace(/b=TIAS:.*\r\n/,"")}removeVideoOrientation(e){return e.replace(/urn:3gpp:video-orientation/,"")}connect(){return f(this,null,function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(e){throw this.closePeerConnection(!0),this.uninstallEvents(),e}})}exchangeSDP(){return f(this,null,function*(){try{yield this.createOffer(),this._log.info("createOffer success, sending offer to remote server"),yield this.doExchangeSDP()}catch(e){throw e}})}createOffer(){return f(this,null,function*(){try{let e=yield this._peerConnection.createOffer(h_);yield this.setOffer(e),e.sdp&&this.updateSSRC(e.sdp)}catch(e){throw e}})}doExchangeSDP(){let e={command:Z.PUBLISH,responseCommand:J.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof Pt||this.localAuxVideoTrack instanceof Pt,state:this._room.publishState,constraintConfig:this._mediaSettings},enableLog:!1};return this._log.debug(`sending sdp offer: ${e.data.sdp}`),this._signalChannel.sendWaitForResponse(e).then(t=>{let{code:r,message:s,data:n}=t.data;return r===0?this.acceptAnswer(n):this.checkPublishResultCode(r,s)})}setSDPDirection(e,t,r="all"){let s=De(e);return s.media.forEach(n=>{(r==="all"||n.type===r)&&(n.direction=t)}),qt(s)}acceptAnswer(e){return f(this,null,function*(){var t,r,s,n,a;try{let d;if(this._publishingLocalAudioTrack||this._publishingLocalVideoTrack||this.isMainStreamPublished){let h=((t=this._publishingLocalVideoTrack)==null?void 0:t.profile.bitrate)||((r=this.localMainVideoTrack)==null?void 0:r.profile.bitrate),p=((s=this._publishingLocalAudioTrack)==null?void 0:s.profile.bitrate)||((n=this.localMainAudioTrack)==null?void 0:n.profile.bitrate);if(h){let m=this._isPublishingAux?_.AUXILIARY:_.BIG;d=yield this.setBandwidth({bandwidth:h,type:_.VIDEO,sdp:d,videoType:m})}p&&(d=yield this.setBandwidth({bandwidth:p,type:_.AUDIO,sdp:d}))}if(d=this.removeVideoOrientation(e.sdp),(a=this._publishingLocalVideoTrack)!=null&&a.small){let{smallStreamConfig:h}=this._room;d=yield this.setBandwidth({bandwidth:this._publishingLocalVideoTrack.small.bitrate||h.bitrate,type:_.VIDEO,videoType:_.SMALL,sdp:d})}let u={type:e.type,sdp:d};yield this.setAnswer(u),this._log.debug(`accepted answer: ${d}`)}catch(d){throw this._log.error(`failed to accept remote answer ${d}`),d}})}sendMutedFlag(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info(`send muted state: ${JSON.stringify(this._room.muteState)}`),this._signalChannel.send(Z.UPDATE_MUTE_STAT,this._room.muteState))}getIsReconnecting(){return this._isReconnecting}reconnect(){return f(this,null,function*(){if(!(Le(vs.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:Z.UNPUBLISH,responseCommand:J.UNPUBLISH_RESULT,enableLog:!1}),this.closePeerConnection(),this.initialize(),this.isMainStreamPublished&&(yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0})),this._log.warn("reconnect() uplink reconnect successfully"),this.stopReconnection()}catch(t){let r=Zt(this._reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${r/1e3}s`),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},r)}})}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&S.emit(A.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{De(e).media.forEach((r,s)=>{if(r.type===_.AUDIO){let n=r.ssrcs&&r.ssrcs[0];n&&(this.ssrc.audio=Number(n.id))}else{if(this._sdpSemantics===Mo&&r.ssrcGroups){r.ssrcGroups.forEach((a,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(s){case 1:this.ssrc.video=Number(n.id);break;case 2:this.ssrc.small=Number(n.id);break;case 3:this.ssrc.auxiliary=Number(n.id);break;default:break}}})}catch(t){}}getVideoTrackId(e=_.VIDEO){if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===_.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===_.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===_.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===_.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(qe.NOT_SUPPORTED_H264ENCODE),new v({code:I.NOT_SUPPORTED_H264,message:$({key:B.NOT_SUPPORTED_H264ENCODE})})):new v({code:I.UNKNOWN,message:$({key:B.SIGNAL_RESPONSE_FAILED,data:{signalResponse:J.PUBLISH_RESULT,code:e,message:t}})})}};D([Y(e=>function(...t){return new Promise((r,s)=>{let n=a=>{this._emitter.off("closed",n),s(new v({code:I.API_CALL_ABORTED,message:$({key:B.CONNECTION_ABORTED,data:a})}))};this._emitter.on("closed",n),e.apply(this,t).then(r,s).finally(()=>{this._emitter.off("closed",n)})})})],vs.prototype,"publish",1),D([Rt(521715,!1)],vs.prototype,"unpublish",1),D([Ct(ft.prototype.afterConnect),Md(ft.prototype.beforeConnect)],vs.prototype,"connect",1);var Zh=vs,ta=Zh;var ia=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,"_decodeMap",new Map);c(this,"totalBytesSent",0);c(this,"totalBytesReceived",0);c(this,"_spcStats",null);this._log=e}get statInterval(){return this._prevReportTime===0?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(i){return f(this,null,function*(){var s;let e={audio:{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0},video:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},small:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},auxiliary:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},rtt:0},t=i.getPeerConnection(),r=i.getSSRC();if(t)try{if((this._spcStats||(yield t.getStats())).forEach(a=>{var u,h,p,m,g,E,C,P,re;let d,l;if(a.type==="outbound-rtp")if((a.mediaType||a.kind)===_.VIDEO){if(a.ssrc===r.video?(d=_.VIDEO,l=i.localMainVideoTrack):a.ssrc===r.small?d=_.SMALL:a.ssrc===r.auxiliary&&(l=i.localAuxVideoTrack,d=_.AUXILIARY),!d)return;if(e[d].bytesSent=a.bytesSent,e[d].packetsSent=a.packetsSent,e[d].framesEncoded=a.framesEncoded,T(a.keyFramesEncoded)||(e[d].keyFramesEncoded=a.keyFramesEncoded),T(a.nackCount)||(e[d].nackCount=a.nackCount),T(a.pliCount)||(e[d].pliCount=a.pliCount),T(a.retransmittedPacketsSent)||(e[d].retransmittedPacketsSent=a.retransmittedPacketsSent),T(a.totalEncodeTime)||(e[d].totalEncodeTime=a.totalEncodeTime),T(a.totalPacketSendDelay)||(e[d].totalPacketSendDelay=a.totalPacketSendDelay),!T(a.encoderImplementation)&&(d===_.VIDEO&&this._prevEncoderImplementation!==a.encoderImplementation||d===_.AUXILIARY&&this._prevAuxEncoderImpl!==a.encoderImplementation)){let Qe=2,N=this._prevEncoderImplementation;d===_.AUXILIARY&&(Qe=7,N=this._prevAuxEncoderImpl),S.emit("262",{userId:i.userId,streamType:Qe,prevImplementation:N,implementation:a.encoderImplementation,codec:i.videoCodec,isHWCodec:a.powerEfficientEncoder}),this[d===_.VIDEO?"_prevEncoderImplementation":"_prevAuxEncoderImpl"]=a.encoderImplementation,this._log.info(`${d===_.AUXILIARY?"aux ":""}encoderImplementation change to ${a.encoderImplementation}(${i.videoCodec}) HWEncoder: ${a.powerEfficientEncoder}`)}a.ssrc===r.video?!T(a.qualityLimitationReason)&&a.bytesSent!==0&&this._prevQualityLimitationReason!==a.qualityLimitationReason&&(this._log.info(`qualityLimitationReason change to ${a.qualityLimitationReason}`),S.emit("263",{userId:i.userId,reason:a.qualityLimitationReason,prevReason:this._prevQualityLimitationReason,streamType:2,isQosClearFirst:(u=i.localMainVideoTrack)==null?void 0:u.isQosClearFirst}),this._prevQualityLimitationReason=a.qualityLimitationReason):a.ssrc===r.auxiliary&&!T(a.qualityLimitationReason)&&a.bytesSent!==0&&this._prevAuxQualityLimitationReason!==a.qualityLimitationReason&&(this._log.info(`aux qualityLimitationReason change to ${a.qualityLimitationReason}`),S.emit("263",{userId:i.userId,reason:a.qualityLimitationReason,prevReason:this._prevAuxQualityLimitationReason,streamType:7,isQosClearFirst:(h=i.localAuxVideoTrack)==null?void 0:h.isQosClearFirst}),this._prevAuxQualityLimitationReason=a.qualityLimitationReason)}else e.audio.bytesSent=a.bytesSent,e.audio.packetsSent=a.packetsSent;else if(a.type==="candidate-pair")Cr(a)&&(this.totalBytesSent=a.bytesSent,Q(a.currentRoundTripTime)&&(e.rtt=Math.floor(a.currentRoundTripTime*1e3)));else if(a.type==="media-source"){if(a.kind===_.AUDIO)e.audio.audioLevel=a.audioLevel||0,e.audio.totalAudioEnergy=a.totalAudioEnergy||0,a.echoReturnLoss,T((g=(m=(p=i.localMainAudioTrack)==null?void 0:p.sourceTrack)==null?void 0:m.stats)==null?void 0:g.deliveredFramesDuration)?a.totalSamplesDuration&&(e.audio.totalSamplesDuration=a.totalSamplesDuration):e.audio.totalSamplesDuration=i.localMainAudioTrack.sourceTrack.stats.deliveredFramesDuration/1e3;else if(a.kind===_.VIDEO)if(a.trackIdentifier===i.getVideoTrackId(_.VIDEO))if((P=(C=(E=i.localMainVideoTrack)==null?void 0:E.sourceTrack)==null?void 0:C.stats)!=null&&P.deliveredFrames){let{deliveredFrames:L}=i.localMainVideoTrack.sourceTrack.stats;e.video.framesCaptured=L,i.localMainVideoTrack.stat.framesCaptured&&i.localMainVideoTrack.stat.framesCaptured>0&&L>=i.localMainVideoTrack.stat.framesCaptured?e.video.fpsCapture=Math.floor((L-i.localMainVideoTrack.stat.framesCaptured)/this.statInterval):e.video.fpsCapture=a.framesPerSecond}else e.video.fpsCapture=a.framesPerSecond;else a.trackIdentifier===i.getVideoTrackId(_.AUXILIARY)?e.auxiliary.fpsCapture=a.framesPerSecond:e.small.fpsCapture=a.framesPerSecond}if(!T(a.audioLevel)&&((re=i.localMainAudioTrack)!=null&&re.mediaTrack)&&a.trackIdentifier===i.localMainAudioTrack.mediaTrack.id&&(e.audio.audioLevel=a.audioLevel||0),!T(a.frameWidth)){let L=_.SMALL;a.trackIdentifier===i.getVideoTrackId(_.VIDEO)||a.ssrc===r.video?L=_.VIDEO:(a.trackIdentifier===i.getVideoTrackId(_.AUXILIARY)||a.ssrc===r.auxiliary)&&(L=_.AUXILIARY),e[L].frameWidth=a.frameWidth,e[L].frameHeight=a.frameHeight,e[L].framesSent=a.framesSent}}),i.localMainAudioTrack){let a=i.localMainAudioTrack.getInternalAudioLevel(),d=i.localMainAudioTrack.getInternalAudioLevelAfter3A();e.audio.audioCaptureEnergyAfter3a=d,e.audio.micAudioLevel=a,e.audio.audioLevel===0&&(e.audio.audioLevel=d!=null?d:a)}this.totalBytesSent||(this.totalBytesSent+=e.audio.bytesSent+e.video.bytesSent+e.auxiliary.bytesSent),Object.keys(e).forEach(a=>{a===_.AUDIO?(i.localMainAudioTrack&&(i.localMainAudioTrack.stat=e[a]),i.localAuxAudioTrack&&(i.localAuxAudioTrack.stat=e[a])):a===_.VIDEO?i.localMainVideoTrack&&(i.localMainVideoTrack.stat=e[a]):a===_.AUXILIARY&&i.localAuxVideoTrack&&(i.localAuxVideoTrack.stat=e[a])})}catch(n){this._log.warn(`failed to getStats on sender connection ${n}`)}return e.rtt===0&&(e.rtt=((s=this.room.networkQuality)==null?void 0:s.uplinkRTT)||0),e})}getReceiverStats(i){return f(this,null,function*(){var r,s,n;let e={tinyId:i.tinyId,userId:i.userId,rtt:0,hasAudio:!1,hasVideo:!1,hasAuxiliary:!1,isSmallSubscribed:!1,audio:{bytesReceived:0,packetsReceived:0,packetsLost:0,p2pDelay:0,totalJitter:0,totalJitterCount:0,audioLevel:0,totalAudioEnergy:0,insertedSamplesForDeceleration:0,removedSamplesForAcceleration:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,freezeCount:0,totalFreezesDuration:0,totalJitter:0,totalJitterCount:0,p2pDelay:0,codec:""},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,totalJitter:0,totalJitterCount:0,p2pDelay:0,codec:""}},t=i.getPeerConnection();if(t)try{let{ssrc:a}=i,{muteState:d,subscribeState:l}=i;(this._spcStats||(yield t.getStats())).forEach(h=>{var p,m;if(h.type==="codec"&&this._decodeMap.set(h.id,h),h.type==="inbound-rtp"){let g=(h.mediaType||h.kind)===_.AUDIO;if(g){if(h.ssrc!==a.audio||!d.hasAudio)return;e.audio.packetsReceived=h.packetsReceived,e.audio.bytesReceived=h.bytesReceived,e.audio.packetsLost=h.packetsLost,h.insertedSamplesForDeceleration&&(e.audio.insertedSamplesForDeceleration=h.insertedSamplesForDeceleration),h.removedSamplesForAcceleration&&(e.audio.removedSamplesForAcceleration=h.removedSamplesForAcceleration),h.totalSamplesDuration&&(e.audio.totalSamplesDuration=h.totalSamplesDuration),h.totalSamplesReceived&&(e.audio.totalSamplesReceived=h.totalSamplesReceived),h.concealedSamples&&(e.audio.concealedSamples=h.concealedSamples),h.silentConcealedSamples&&(e.audio.silentConcealedSamples=h.silentConcealedSamples);let{remoteAudioTrack:E}=i;E.stat.packetsReceived=h.packetsReceived,E.stat.bytesReceived=h.bytesReceived,E.stat.packetsLost=h.packetsLost,e.audio.p2pDelay=E.stat.end2EndDelay,e.hasAudio=!0}else{if(ee&&h.bytesReceived===0)return;let E;h.ssrc===a.video&&d.hasVideo&&(e.video.packetsReceived=h.packetsReceived,e.video.bytesReceived=h.bytesReceived,e.video.packetsLost=h.packetsLost,e.video.framesReceived=h.framesReceived,e.video.framesDecoded=h.framesDecoded,e.video.fpsDecoded=h.framesPerSecond,e.hasVideo=!0,i.videoCodec=Bt[(p=this._decodeMap.get(h.codecId))==null?void 0:p.mimeType.split("/")[1]]||"h264",e.video.codec=i.videoCodec,E=i.remoteVideoTrack,d.hasSmall&&l.smallVideo&&(e.isSmallSubscribed=!0),h.decoderImplementation&&(!this._prevDecoderImplementationMap.has(e.userId)||this._prevDecoderImplementationMap.get(e.userId)!==h.decoderImplementation)&&(this._log.info(`${e.userId} decoderImplementation change to ${h.decoderImplementation}(${i.videoCodec}) HWDecoder: ${h.powerEfficientDecoder}`),S.emit("262",{userId:this.room.userId,remoteUserId:e.userId,prevImplementation:this._prevDecoderImplementationMap.get(e.userId),implementation:h.decoderImplementation,codec:i.videoCodec,isHWCodec:h.powerEfficientDecoder}),this._prevDecoderImplementationMap.set(e.userId,h.decoderImplementation))),h.ssrc===a.auxiliary&&d.hasAuxiliary&&(e.auxiliary.packetsReceived=h.packetsReceived,e.auxiliary.bytesReceived=h.bytesReceived,e.auxiliary.packetsLost=h.packetsLost,e.auxiliary.framesReceived=h.framesReceived,e.auxiliary.framesDecoded=h.framesDecoded,e.auxiliary.fpsDecoded=h.framesPerSecond,E=i.remoteAuxiliaryTrack,e.auxiliary.p2pDelay=E.stat.end2EndDelay,e.hasAuxiliary=!0,e.video.codec=((m=this._decodeMap.get(h.codecId))==null?void 0:m.mimeType.split("/")[1].toLowerCase())||"h264"),E&&(E.stat.packetsReceived=h.packetsReceived,E.stat.bytesReceived=h.bytesReceived,E.stat.packetsLost=h.packetsLost,E.stat.framesReceived=h.framesReceived,E.stat.framesDecoded=h.framesDecoded,h.jitterBufferDelay&&(E.stat.jitterBufferDelay=Math.floor(h.jitterBufferDelay/h.jitterBufferEmittedCount*1e3)),e.video.p2pDelay=E.stat.end2EndDelay)}h.jitterBufferDelay&&(g?(e.audio.totalJitter=h.jitterBufferDelay,e.audio.totalJitterCount=h.jitterBufferEmittedCount):h.ssrc===a.video&&d.hasVideo?(e.video.totalJitter=h.jitterBufferDelay,e.video.totalJitterCount=h.jitterBufferEmittedCount):h.ssrc===a.auxiliary&&d.hasAuxiliary&&(e.auxiliary.totalJitter=h.jitterBufferDelay,e.auxiliary.totalJitterCount=h.jitterBufferEmittedCount))}else h.type==="candidate-pair"&&Cr(h)&&(this.totalBytesReceived=h.bytesReceived,Q(h.currentRoundTripTime)&&(e.rtt=Math.floor(h.currentRoundTripTime*1e3)));T(h.frameWidth)||((h.trackIdentifier===i.getMainStreamVideoTrackId()||h.ssrc===a.video)&&(e.video.frameWidth=h.frameWidth,e.video.frameHeight=h.frameHeight,i.remoteVideoTrack.stat.frameWidth=h.frameWidth,i.remoteVideoTrack.stat.frameHeight=h.frameHeight),(h.trackIdentifier===i.getAuxStreamVideoTrackId()||h.ssrc===a.auxiliary)&&(e.auxiliary.frameWidth=h.frameWidth,e.auxiliary.frameHeight=h.frameHeight,i.remoteAuxiliaryTrack.stat.frameWidth=h.frameWidth,i.remoteAuxiliaryTrack.stat.frameHeight=h.frameHeight)),!T(h.audioLevel)&&i.muteState.audioAvailable&&i.remoteAudioTrack.mediaTrack&&h.trackIdentifier===i.remoteAudioTrack.mediaTrack.id&&(e.audio.audioLevel=h.audioLevel||0,e.audio.totalAudioEnergy=h.totalAudioEnergy||0)}),e.audio.audioLevel===0&&i.muteState.audioAvailable&&(e.audio.audioLevel=i.remoteAudioTrack.getInternalAudioLevel()||0),this.totalBytesReceived||(this.totalBytesReceived+=e.audio.bytesReceived+e.video.bytesReceived+e.auxiliary.bytesReceived),T((r=i.remoteVideoTrack.player.stat)==null?void 0:r.fps)||(e.video.fpsRender=i.remoteVideoTrack.player.stat.fps),T((s=i.remoteAuxiliaryTrack.player.stat)==null?void 0:s.fps)||(e.auxiliary.fpsRender=i.remoteAuxiliaryTrack.player.stat.fps)}catch(a){this._log.warn(`failed to getStats on receiver connection ${a}`)}return e.rtt===0&&(e.rtt=((n=this.room.networkQuality)==null?void 0:n.uplinkRTT)||0),e})}getStats(i,e){return f(this,null,function*(){let t={},r,s=[];if(this.room.singlePC){let n=this.room.singlePC.getPeerConnection();if(!n)return{senderStats:t,receiverStats:s};let a=V(),d=yield n.getStats(),l=V();l-a>2e3&&this._log.warn(`getStats cost ${l-a}ms`);let u=[],h=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source","codec","media-playout"]);d.forEach(p=>h.has(p.type)&&u.push(p)),this._spcStats=u}i&&(t=yield this.getSenderStats(i));for(let[n,a]of e){let d=yield this.getReceiverStats(a);s.push(d)}return e.size&&(r=this.getMediaPlayoutStats(this._spcStats)),{senderStats:t,receiverStats:s,mediaPlayoutStats:r}})}getDifferenceValue(i,e){if(gi(i))return e;let t=e-i;return t<0?0:t}prepareReport({stats:i,report:e,freezeMap:t,uplinkConnection:r}){var p,m,g,E,C,P,re,L,Qe;if(!gi(i.senderStats)){let N={uint32_audio_level:i.senderStats.audio.audioLevel*Dt,uint32_audio_energy:(i.senderStats.audio.totalAudioEnergy||0)*1e6,uint32_audio_codec_bitrate:i.senderStats.audio.bytesSent};i.senderStats.audio.micAudioLevel&&(N.uint32_mic_audio_level=i.senderStats.audio.micAudioLevel*Dt),T(i.senderStats.audio.audioCaptureEnergyAfter3a)||(N.uint32_audio_capture_energy_after3a=i.senderStats.audio.audioCaptureEnergyAfter3a*Dt),i.senderStats.audio.totalSamplesDuration&&(e.msg_device_info.uint32_audio_capture_cost=i.senderStats.audio.totalSamplesDuration);let k=[];if(i.senderStats.video.bytesSent){let Ne={uint32_video_stream_type:2,uint32_video_codec_fps:i.senderStats.video.framesSent,uint32_video_capture_fps:i.senderStats.video.fpsCapture,uint32_video_width:i.senderStats.video.frameWidth,uint32_video_height:i.senderStats.video.frameHeight,uint32_video_codec_bitrate:i.senderStats.video.bytesSent,uint32_video_enc_fps:i.senderStats.video.framesEncoded,uint32_key_frame_count:i.senderStats.video.keyFramesEncoded,uint32_nack_count:i.senderStats.video.nackCount,uint32_pli_count:i.senderStats.video.pliCount,uint32_encode_cost:(i.senderStats.video.totalEncodeTime||0)*1e3,uint32_send_packet_cost:(i.senderStats.video.totalPacketSendDelay||0)*1e3,uint32_video_arq_packets:i.senderStats.video.retransmittedPacketsSent};k.push(Ne)}if(i.senderStats.small.bytesSent){let Ne={uint32_video_stream_type:3,uint32_video_codec_fps:i.senderStats.small.framesSent||0,uint32_video_capture_fps:i.senderStats.small.fpsCapture||0,uint32_video_width:i.senderStats.small.frameWidth||0,uint32_video_height:i.senderStats.small.frameHeight||0,uint32_video_codec_bitrate:i.senderStats.small.bytesSent,uint32_video_enc_fps:i.senderStats.small.framesEncoded||0,uint32_key_frame_count:i.senderStats.small.keyFramesEncoded,uint32_nack_count:i.senderStats.small.nackCount,uint32_pli_count:i.senderStats.small.pliCount,uint32_encode_cost:(i.senderStats.small.totalEncodeTime||0)*1e3,uint32_send_packet_cost:(i.senderStats.small.totalPacketSendDelay||0)*1e3,uint32_video_arq_packets:i.senderStats.small.retransmittedPacketsSent};k.push(Ne)}if(i.senderStats.auxiliary.bytesSent){let Ne={uint32_video_stream_type:7,uint32_video_codec_fps:i.senderStats.auxiliary.framesSent||0,uint32_video_capture_fps:i.senderStats.auxiliary.fpsCapture||0,uint32_video_width:i.senderStats.auxiliary.frameWidth||0,uint32_video_height:i.senderStats.auxiliary.frameHeight||0,uint32_video_codec_bitrate:i.senderStats.auxiliary.bytesSent,uint32_video_enc_fps:i.senderStats.auxiliary.framesEncoded||0,uint32_key_frame_count:i.senderStats.auxiliary.keyFramesEncoded,uint32_nack_count:i.senderStats.auxiliary.nackCount,uint32_pli_count:i.senderStats.auxiliary.pliCount,uint32_encode_cost:(i.senderStats.auxiliary.totalEncodeTime||0)*1e3,uint32_send_packet_cost:(i.senderStats.auxiliary.totalPacketSendDelay||0)*1e3,uint32_video_arq_packets:i.senderStats.auxiliary.retransmittedPacketsSent};k.push(Ne)}let O={uint32_bitrate:0,uint32_lost:0,uint32_rtt:i.senderStats.rtt};e.msg_up_stream_info={msg_audio_status:N,msg_video_status:k,msg_network_status:O}}let{statInterval:s}=this;e.msg_down_stream_info=[],i.receiverStats.forEach(N=>{let k={msg_user_info:{str_identifier:N.userId,uint64_tinyid:N.tinyId},msg_network_status:{uint32_rtt:N.rtt,uint32_bitrate:0,uint32_lost:0},msg_audio_status:{},msg_video_status:[]};if(N.hasAudio){let O={uint32_audio_p2p_delay:N.audio.p2pDelay,uint32_audio_cache_ms:N.audio.totalJitter,uint32_audio_cache_ms_count:N.audio.totalJitterCount,uint32_audio_codec_bitrate:N.audio.bytesReceived,uint32_audio_total_bitrate:N.audio.bytesReceived,uint32_audio_level:N.audio.audioLevel*1e8,uint32_audio_energy:N.audio.totalAudioEnergy*1e6,uint32_audio_receive:N.audio.packetsReceived,uint32_audio_origin_lost:N.audio.packetsLost};k.msg_audio_status=O}if(N.hasVideo){let O=t.get(`${N.userId}_${Qc}`),Ne=O?O.duration:0,fe={uint32_video_stream_type:N.isSmallSubscribed?3:2,uint32_video_receive_fps:N.video.framesReceived,uint32_video_width:N.video.frameWidth,uint32_video_height:N.video.frameHeight,uint32_video_codec_bitrate:N.video.bytesReceived,uint32_video_receive:N.video.packetsReceived,uint32_video_origin_lost:N.video.packetsLost,uint32_video_block_time:Ne,uint32_video_dec_fps:N.video.framesDecoded,uint32_video_codec_fps:N.video.fpsRender,uint32_video_cache_ms:N.video.totalJitter,uint32_video_cache_ms_count:N.video.totalJitterCount,uint32_video_p2p_delay:N.video.p2pDelay,uint32_video_codec:N.video.codec};k.msg_video_status.push(fe)}if(N.hasAuxiliary){let O=t.get(`${N.userId}_${Yc}`),Ne=O?O.duration:0,fe={uint32_video_stream_type:7,uint32_video_receive_fps:N.auxiliary.framesReceived,uint32_video_width:N.auxiliary.frameWidth,uint32_video_height:N.auxiliary.frameHeight,uint32_video_codec_bitrate:N.auxiliary.bytesReceived,uint32_video_receive:N.auxiliary.packetsReceived+N.auxiliary.packetsLost,uint32_video_origin_lost:N.auxiliary.packetsLost,uint32_video_block_time:Ne,uint32_video_dec_fps:N.auxiliary.framesDecoded,uint32_video_codec_fps:N.video.fpsRender,uint32_video_cache_ms:N.auxiliary.totalJitter,uint32_video_cache_ms_count:N.auxiliary.totalJitterCount,uint32_video_p2p_delay:N.auxiliary.p2pDelay,uint32_video_codec:N.video.codec};k.msg_video_status.push(fe)}e.msg_down_stream_info.push(k)}),i.mediaPlayoutStats&&!gi(i.mediaPlayoutStats)&&(i.mediaPlayoutStats.synthesizedSamplesDuration*=1e3,i.mediaPlayoutStats.totalSamplesDuration*=1e3);let n=this._prevReport,a=this._prevStats;if(this._prevReport=JSON.parse(JSON.stringify(e)),this._prevStats=JSON.parse(JSON.stringify(i)),e.msg_up_stream_info.msg_audio_status&&n.msg_up_stream_info.msg_audio_status){let N=n.msg_up_stream_info.msg_audio_status,k=e.msg_up_stream_info.msg_audio_status;if(N.uint32_audio_codec_bitrate===0)k.uint32_audio_codec_bitrate=0;else{let O=this.getDifferenceValue(N.uint32_audio_codec_bitrate,k.uint32_audio_codec_bitrate);k.uint32_audio_codec_bitrate=Math.round(O*8/s),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=k.uint32_audio_codec_bitrate}(p=n.msg_device_info)!=null&&p.uint32_audio_capture_cost?(e.msg_device_info.uint32_audio_capture_cost=2*Math.floor(this.getDifferenceValue(n.msg_device_info.uint32_audio_capture_cost,e.msg_device_info.uint32_audio_capture_cost)*1e3/s),e.msg_device_info.uint32_audio_capture_cost>0&&((g=r==null?void 0:r.localMainAudioTrack)==null||g.updateAfter3aSilenceStartTime((m=i.senderStats.audio.audioCaptureEnergyAfter3a)!=null?m:i.senderStats.audio.micAudioLevel))):delete e.msg_device_info.uint32_audio_capture_cost}let d=n.msg_up_stream_info.msg_video_status;e.msg_up_stream_info.msg_video_status.forEach(N=>{let k=d.find(Vi=>Vi.uint32_video_stream_type===N.uint32_video_stream_type);if(!k||k.uint32_video_codec_bitrate===0){N.uint32_video_codec_bitrate=0,N.uint32_video_enc_fps=0,N.uint32_video_codec_fps=0;return}let O=0,Ne=0,fe=0;k&&N.uint32_video_codec_bitrate>=k.uint32_video_codec_bitrate&&(O=k.uint32_video_codec_bitrate,Ne=k.uint32_video_enc_fps,fe=k.uint32_video_codec_fps);let Ye=this.getDifferenceValue(O,N.uint32_video_codec_bitrate);N.uint32_video_codec_bitrate=Math.round(Ye*8/s),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=N.uint32_video_codec_bitrate,N.uint32_video_enc_fps=Math.round(this.getDifferenceValue(Ne,N.uint32_video_enc_fps)/s),N.uint32_video_codec_fps=Math.round(this.getDifferenceValue(fe,N.uint32_video_codec_fps)/s),k.uint32_video_width===0&&k.uint32_video_height===0&&k.uint32_video_codec_fps===0&&(N.uint32_video_codec_fps=N.uint32_video_enc_fps),T(k.uint32_key_frame_count)||(N.uint32_key_frame_count=Math.round(this.getDifferenceValue(k.uint32_key_frame_count,N.uint32_key_frame_count))),T(k.uint32_nack_count)||(N.uint32_nack_count=Math.round(this.getDifferenceValue(k.uint32_nack_count,N.uint32_nack_count))),T(k.uint32_pli_count)||(N.uint32_pli_count=Math.round(this.getDifferenceValue(k.uint32_pli_count,N.uint32_pli_count))),T(k.uint32_video_arq_packets)||(N.uint32_video_arq_packets=Math.round(this.getDifferenceValue(k.uint32_video_arq_packets,N.uint32_video_arq_packets))),T(k.uint32_encode_cost)||(N.uint32_encode_cost=Math.round(this.getDifferenceValue(k.uint32_encode_cost,N.uint32_encode_cost)/s)),T(k.uint32_send_packet_cost)||(N.uint32_send_packet_cost=Math.round(this.getDifferenceValue(k.uint32_send_packet_cost,N.uint32_send_packet_cost)/s))});let u=n.msg_down_stream_info;e.msg_down_stream_info=e.msg_down_stream_info.filter(N=>u.find(k=>k.msg_user_info.uint64_tinyid===N.msg_user_info.uint64_tinyid));let h=e.msg_down_stream_info;if(h.forEach(N=>{let k=u.find(O=>O.msg_user_info.uint64_tinyid===N.msg_user_info.uint64_tinyid);if(!gi(N.msg_audio_status)&&!gi(k.msg_audio_status)){let O=N.msg_audio_status,Ne=k.msg_audio_status,fe=this.getDifferenceValue(Ne.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(Ne.uint32_audio_cache_ms,O.uint32_audio_cache_ms)/fe)||0;let Ye=this.room.remotePublishedUserMap.get(N.msg_user_info.str_identifier);Ye&&(Ye.remoteAudioTrack.stat.jitterBufferDelay=O.uint32_audio_cache_ms),O.uint32_audio_origin_lost=this.getDifferenceValue(Ne.uint32_audio_origin_lost,O.uint32_audio_origin_lost),O.uint32_audio_receive=this.getDifferenceValue(Ne.uint32_audio_receive,O.uint32_audio_receive),O.uint32_audio_receive+=O.uint32_audio_origin_lost;let Vi=this.getDifferenceValue(Ne.uint32_audio_codec_bitrate,O.uint32_audio_codec_bitrate);O.uint32_audio_codec_bitrate=Math.round(Vi*8/s),O.uint32_audio_total_bitrate=Math.round(Vi*8/s)}else N.msg_audio_status={};if(N.msg_video_status&&k.msg_video_status){let O=k.msg_video_status;N.msg_video_status=N.msg_video_status.filter(fe=>O.find(Ye=>Ye.uint32_video_stream_type===fe.uint32_video_stream_type)),N.msg_video_status.forEach(fe=>{let Ye=O.find(z_=>z_.uint32_video_stream_type===fe.uint32_video_stream_type),Vi=Ye.uint32_video_receive,Vc=Ye.uint32_video_origin_lost,G_=Ye.uint32_video_codec_bitrate,J_=Ye.uint32_video_receive_fps,q_=Ye.uint32_video_dec_fps;fe.uint32_video_origin_lost=this.getDifferenceValue(Vc,fe.uint32_video_origin_lost),fe.uint32_video_receive=this.getDifferenceValue(Vi,fe.uint32_video_receive)+fe.uint32_video_origin_lost;let j_=this.getDifferenceValue(G_,fe.uint32_video_codec_bitrate);fe.uint32_video_codec_bitrate=Math.round(j_*8/s);let X_=this.getDifferenceValue(J_,fe.uint32_video_receive_fps);fe.uint32_video_receive_fps=Math.round(X_/s),fe.uint32_video_dec_fps=Math.round(this.getDifferenceValue(q_,fe.uint32_video_dec_fps)/s);let H=this.getDifferenceValue(Ye.uint32_video_cache_ms_count,fe.uint32_video_cache_ms_count);delete fe.uint32_video_cache_ms_count,fe.uint32_video_cache_ms=Math.floor(1e3*this.getDifferenceValue(Ye.uint32_video_cache_ms,fe.uint32_video_cache_ms)/H)||0})}}),!T((E=a==null?void 0:a.mediaPlayoutStats)==null?void 0:E.totalSamplesDuration)&&!T((C=i.mediaPlayoutStats)==null?void 0:C.totalSamplesDuration)){let N=2*Math.floor(this.getDifferenceValue((P=a==null?void 0:a.mediaPlayoutStats)==null?void 0:P.synthesizedSamplesDuration,(re=i.mediaPlayoutStats)==null?void 0:re.synthesizedSamplesDuration)/s),k=2*Math.floor(this.getDifferenceValue((L=a==null?void 0:a.mediaPlayoutStats)==null?void 0:L.totalSamplesDuration,(Qe=i.mediaPlayoutStats)==null?void 0:Qe.totalSamplesDuration)/s);e.msg_device_info.uint32_audio_play_cost=k-N}return a&&i.receiverStats.forEach(N=>{if(N.audio.concealedSamples&&N.audio.totalSamplesReceived){let k=a.receiverStats.find(O=>O.userId===N.userId);if(k&&k.audio.concealedSamples&&k.audio.totalSamplesReceived){let O=(N.audio.silentConcealedSamples||0)-(k.audio.silentConcealedSamples||0),Ne=N.audio.concealedSamples-k.audio.concealedSamples,fe=N.audio.totalSamplesReceived-k.audio.totalSamplesReceived,Ye=Math.floor((Ne-O)/fe*1e3*s);if(Ye>s*1e3/5){let Vi=h.find(Vc=>Vc.msg_user_info.str_identifier===N.userId);Vi&&(Vi.msg_audio_status.uint32_audio_block_time=Ye)}}}}),e.msg_down_stream_info.forEach(N=>{N.msg_video_status.forEach(k=>{k.uint32_video_codec_bitrate===0&&k.uint32_video_receive_fps===0&&(k.uint32_video_width=0,k.uint32_video_height=0)})}),e}getStatsReport(r){return f(this,arguments,function*({uplinkConnection:i,downlinkConnections:e,freezeMap:t}){let s={msg_device_info:{},msg_up_stream_info:{msg_audio_status:{uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_capture_energy_after3a:0},msg_video_status:[],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}},msg_down_stream_info:[{msg_user_info:{str_identifier:"",uint64_tinyid:0},msg_audio_status:{uint32_audio_cache_ms:0,uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_total_bitrate:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_final_lost:0},msg_video_status:[{uint32_video_cache_ms:0,uint32_video_stream_type:0,uint32_video_receive_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_codec_bitrate:0,uint32_video_receive:0,uint32_video_origin_lost:0,uint32_video_block_time:0,uint32_video_dec_fps:0}],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}}]},n=yield this.getStats(i,e);return JSON.stringify(this._prevReport)==="{}"&&(this._prevReport=JSON.parse(JSON.stringify(s))),this.prepareReport({stats:n,report:s,freezeMap:t,uplinkConnection:i}),this._prevReportTime=Date.now(),s})}getMediaPlayoutStats(i){let e;if(Ae(i)){for(let t of i)if(t.type==="media-playout"){let{synthesizedSamplesDuration:r,totalSamplesDuration:s}=t;e={synthesizedSamplesDuration:r,totalSamplesDuration:s};break}return e}}reset(){var i;this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map,(i=this.room.localMainVideoTrack)!=null&&i.stat&&(this.room.localMainVideoTrack.stat.framesCaptured=0)}};var f_=Je(nt());function m_(o){let i={totalCost:0,local:0,redirect:0,httpCache:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let e=performance.getEntriesByType("resource").reverse();for(let t of e)if(t.name===o){let r=Math.round(t.duration),s=Math.max(Math.round(t.domainLookupStart-t.startTime),0),n=t.redirectStart>0?Math.max(Math.round(t.redirectEnd-t.redirectStart),0):0,a=t.fetchStart>0?Math.max(Math.round(t.domainLookupStart-t.fetchStart),0):0,d=Math.round(t.domainLookupEnd-t.domainLookupStart),l=Math.round(t.requestStart-t.secureConnectionStart),u=Math.round(t.secureConnectionStart-t.connectStart),h=Math.round(t.responseStart-t.requestStart),p=Math.round(t.responseEnd-(t.responseStart||t.startTime));i=w(M({},i),{totalCost:r,local:s,redirect:n,httpCache:a,dns:d,tcp:u,tls:l,request:h,response:p});break}}catch(e){}return i}function p_(o){return new Promise(i=>f(this,null,function*(){let e=setTimeout(()=>{i({totalCost:1e4,local:0,dns:0,tcp:0,tls:0,request:0,response:0})},1e4),t=Date.now(),r=`https://${o}/?t=${t}`;try{yield fetch(r)}catch(n){}clearTimeout(e);let s=m_(r);s.totalCost===0&&(s.totalCost=Date.now()-t),i(s)}))}var lI=700,Ro=class Ro extends f_.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=R.createLogger({parent:t.getLogger(),id:"q",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this.initialize()}get uplinkNetworkQuality(){return this._uplinkNetworkQuality}set uplinkNetworkQuality(e){e!==this._uplinkNetworkQuality&&this._log.info(`uplink ${this.uplinkNetworkQuality} -> ${e}, rtt: ${this.uplinkRTT}, loss: ${this.uplinkLoss} ws-rtt: ${this._signalChannel.rtt}`),this._uplinkNetworkQuality=e}get downlinkNetworkQuality(){return this._downlinkNetworkQuality}set downlinkNetworkQuality(e){if(e!==this._downlinkNetworkQuality){let{rtt:t,loss:r}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._log.info(`downlink ${this.downlinkNetworkQuality} -> ${e}, rtt: ${t}, loss: ${r} ws-rtt: ${this._signalChannel.rtt}`)}this._downlinkNetworkQuality=e}initialize(){this._signalChannel.on(J.UPLINK_NETWORK_STATS,e=>{this.handleUplinkNetworkQuality(e)}),this._signalChannel.on(Ie.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 s=t.expectAudPkg+t.expectVidPkg,n=t.recvAudPkg+t.recvVidPkg,a=s-n;s===0&&n===0||(a<=0?this.uplinkLoss=0:this.uplinkLoss=Math.round(a/s*100),this.uplinkRTT=t.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this.uplinkLoss,this.uplinkRTT))}handleDownlinkNetworkQuality(){return f(this,null,function*(){if(this._room.remotePublishedUserMap.size===0){this.downlinkNetworkQuality=0;return}let e=[...this._room.remotePublishedUserMap.values()],t=e.filter(a=>{var d;return((d=a.getPeerConnection())==null?void 0:d.connectionState)===Ce.CONNECTED});if(e.filter(a=>this.isPeerConnectionDisconnected(a.getPeerConnection())).length===e.length){this.downlinkNetworkQuality=6;return}for(let a=0;a<t.length;a++){let d=t[a].getPeerConnection();if(!d)return;let{rtt:l,totalPacketsLost:u,totalPacketsReceived:h}=yield this.getStat(d);if(!this._downlinkPrevStatMap.has(d)){this._downlinkPrevStatMap.set(d,{totalPacketsLost:u,totalPacketsReceived:h});continue}let p=0,m=this._downlinkPrevStatMap.get(d),g=u-m.totalPacketsLost,E=h-m.totalPacketsReceived;g<=0||E<0?p=0:p=Math.round(g/(g+E)*100),this._downlinkPrevStatMap.set(d,{totalPacketsLost:u,totalPacketsReceived:h}),this._downlinkLossAndRTTMap.set(d,{rtt:l,loss:p,userId:t[a].getUserId(),audioDelay:t[a].remoteAudioTrack.stat.end2EndDelay,videoDelay:t[a].remoteVideoTrack.stat.end2EndDelay})}if([...this._downlinkPrevStatMap.keys()].forEach(a=>{this.isPeerConnectionDisconnected(a)&&(this._downlinkPrevStatMap.delete(a),this._downlinkLossAndRTTMap.delete(a))}),this._downlinkLossAndRTTMap.size===0){this.downlinkRTT=0,this.downlinkLoss=0,this.downlinkNetworkQuality=0;return}let{rtt:s,loss:n}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this.downlinkRTT=s,this.downlinkLoss=n,this.downlinkNetworkQuality=this.getNetworkQuality(n,s)})}getStat(e){return f(this,null,function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!oo())return t;let r=e.getReceivers();try{for(let s=0;s<r.length;s++)(yield r[s].getStats()).forEach(d=>{d.type==="candidate-pair"&&Q(d.currentRoundTripTime)&&(t.rtt=Math.round(d.currentRoundTripTime*1e3)),d.type==="inbound-rtp"&&(d.mediaType===_.AUDIO||d.mediaType===_.VIDEO)&&(t.totalPacketsLost+=d.packetsLost,t.totalPacketsReceived+=d.packetsReceived)});return t.rtt===0&&(t.rtt=this.uplinkRTT),t}catch(s){return t}})}getAverageLossAndRTT(e){let t={rtt:0,loss:0};return Array.isArray(e)&&e.length>0&&(e.forEach(r=>{t.rtt+=r.rtt,t.loss+=r.loss}),Object.keys(t).forEach(r=>{t[r]=Math.round(t[r]/e.length)})),t}getNetworkQuality(e,t){return e>50||t>500?5:e>30||t>350?4:e>20||t>200?3:e>10||t>100?2:e>=0||t>=0?1:0}handleSignalConnectionStateChange(e){e.state==="DISCONNECTED"?(this.uplinkRTT=0,this.uplinkLoss=0,this.uplinkNetworkQuality=6):e.state==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=5)}handleUplinkConnectionStateChange({state:e}){e==="DISCONNECTED"?(this.uplinkLoss=0,this.uplinkRTT=0,this.uplinkNetworkQuality=6):e==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=5)}isPeerConnectionDisconnected(e){return!!(e&&(e.connectionState===Ce.DISCONNECTED||e.connectionState===Ce.FAILED||e.connectionState===Ce.CLOSED))}setUplinkConnection(e){this._room.uplinkConnection=e,this._room.uplinkConnection?this._room.uplinkConnection.on("connection-state-changed",this.handleUplinkConnectionStateChange.bind(this)):(this.uplinkNetworkQuality=0,this.uplinkRTT=0,this.uplinkLoss=0)}start(){if(this._interval!==-1){this._log.info("network quality calculating is already started");return}this._log.debug("start network quality calculating"),this._interval=oe.run("ric",()=>{var n;this.handleDownlinkNetworkQuality();let e=[...this._downlinkLossAndRTTMap.values()];S.emit(A.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this.uplinkRTT,loss:this.uplinkLoss},downlinks:e});let t=(n=this._room.scheduleResult.config)==null?void 0:n.pingDomainInfo,r={uplinkNetworkQuality:this.uplinkNetworkQuality,downlinkNetworkQuality:this.downlinkNetworkQuality,uplinkRTT:this.uplinkRTT,uplinkLoss:this.uplinkLoss,downlinkRTT:this.downlinkRTT,downlinkLoss:this.downlinkLoss};t&&(r=w(M({},r),{pingResults:this.uplinkRTT>t.rttThreshold||this.downlinkRTT>t.rttThreshold?this.pingResults:{}})),this.emit(Ro.EVENT_NETWORK_QUALITY,r);let s=Date.now();if(t&&(this.uplinkRTT>t.rttThreshold||this.downlinkRTT>t.rttThreshold)&&s-Ro.lastPingTime>t.interval*1e3){Ro.lastPingTime=Date.now();let a=t.domain.map(d=>p_(d).then(l=>({domain:d,cost:l.totalCost})));Promise.all(a).then(d=>{this.pingResults.isPoorNetwork=d.some(l=>l.cost>lI),this.pingResults.timestamp=s,this.pingResults.data=d,d.forEach(l=>{y.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&&(oe.clearTask(this._interval),this._interval=-1),this._downlinkLossAndRTTMap.clear(),this._downlinkPrevStatMap.clear()}updateDelay(e){let{tinyIdToUserIdMap:t}=this._room;e.forEach(({srcTinyId:r,videoDelay:s,audioDelay:n})=>{let a=t.get(r);if(a){let d=this._room.remotePublishedUserMap.get(a);d==null||d.setDelay({videoDelay:s,audioDelay:n})}})}};c(Ro,"EVENT_NETWORK_QUALITY","0"),c(Ro,"lastPingTime",0);var Ds=Ro;function uI({fn:o,context:i}){return function(...e){try{let t=o.apply(i,e);return Tr(t)?t.catch(r=>R.error(`${o.name}() error observed ${r}`)):t}catch(t){R.error(`${o.name}() error observed ${t}`)}}}var Nc=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,reportToken: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=R.createLogger({parent:this._room.getLogger(),id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(e=>{e.startsWith("handle")&&le(this[e])&&(this[e]=uI({fn:this[e],context:this}))}),this.initData(),this.installEvents()}initData(){this._firstPublishedUserList=[],this._networkQuality={totalUplinkRTT:0,totalUplinkLoss:0,count:0,totalDownlinkRTTAndLossMap:new Map},this._basicInfo={string_sdk_version:He,uint32_os_type:15,string_device_name:"",string_http_user_agent:navigator.userAgent,string_os_version:"",uint32_avg_rtt:0,uint32_avg_up_loss:0,uint32_scene:this._room.scene==="live"?1:0,uint32_joining_duration:0,uint32_networkType:0,uint32_framework:this._frameWorkType,uint32_component:this._component,uint32_connection_type:this.connectionType,uint32_caller_coding_language:this._language,string_domain:location.hostname},this._pathJoinRoom={uint64_start_time:0,uint64_send_request_acc_ip_cmd_start_time:0,uint64_send_request_acc_ip_cmd_end_time:0,uint64_send_request_enter_room_cmd_start_time:0,uint64_send_request_enter_room_cmd_end_time:0,uint64_send_first_video_frame_time:0,uint64_recv_userlist_time:0,uint64_end_time:0,int32_send_request_acc_ip_cmd_ret:0,int32_send_request_enter_room_cmd_ret:0,int32_end_ret:0},this._pathLeaveRoom={uint64_start_time:0,uint64_send_request_exit_room_cmd_start_time:0,uint64_send_request_exit_room_cmd_end_time:0,uint64_end_time:0,int32_send_request_exit_room_cmd_ret:0,int32_end_ret:0},this._localStreamStat={totalVideoBitrate:0,totalVideoFPS:0,totalVideoHeight:0,totalVideoWidth:0,totalAudioLevel:0,videoCount:0,audioLevelCount:0,publishStartTime:0,statsToReport:{uint32_audio_capture_db:0,uint32_video_big_capture_fps:0,uint32_video_big_bitrate:0,uint32_video_big_resolution:0,uint32_audio_capture_thread_health_zero_cnt:0,uint32_after3a_silence_duration:0}},this._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,Yr().then(()=>{this._basicInfo.string_os_version=di(),this._basicInfo.string_device_name=ai()||this._basicInfo.string_os_version})}addEvent(i,e){return this._eventMap.set(i,e),S.on(i,e),this}installEvents(){this.handleUnload=this.handleUnload.bind(this),window.addEventListener("pagehide",this.handleUnload),this._room.once("banned",()=>this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})),this.addEvent(A.JOIN_START,this.handleJoinStart).addEvent(A.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(A.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(A.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(A.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(A.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(A.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(A.JOIN_FAILED,this.handleJoinFailed).addEvent(A.LEAVE_START,this.handleLeaveStart).addEvent(A.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(A.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(A.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(A.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(A.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(A.PUBLISH_START,this.handlePublishStart).addEvent(A.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(A.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(A.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(A.PLAY_TRACK_START,this.handlePlayStart).addEvent(A.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(A.PLAYER_STATE_CHANGED,({track:i,state:e,type:t})=>{!i.isRemote||!this.hitTest(i.room)||e==="PLAYING"&&(t===_.AUDIO?this.handleAudioPlaying(i):this.handleVideoPlaying(i))}).addEvent(A.SWITCH_ROOM_START,this.handleSwitchRoomStart).addEvent(A.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess).addEvent(A.SWITCH_ROOM_FAILED,this.handleSwitchRoomFailed).addEvent(A.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(A.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(A.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(A.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{if(!this.hitTest(i))return;let r=e.hasAudio||e.hasVideo||e.hasSmall,s=e.hasAuxiliary,n=t.hasAudio||t.hasVideo||t.hasSmall,a=t.hasAuxiliary;!r&&n&&this.handleRemoteStreamAdded(t.userId,"main"),!s&&a&&this.handleRemoteStreamAdded(t.userId,"auxiliary")}).addEvent(A.SINGLE_CONNECTION_STAT,({room:i,stat:e})=>{this.hitTest(i)&&(this._pathJoinRoom.int32_ice_cost=e.ice,this._pathJoinRoom.int32_dtls_cost=e.dtls,this._pathJoinRoom.int32_peer_connection_cost=e.peerConnection)})}uninstallEvents(){window.removeEventListener("pagehide",this.handleUnload),this._eventMap.forEach((i,e)=>S.off(e,i)),this._eventMap.clear()}destroy(){this.uninstallEvents(),oe.clearTask(this._intervalId),this._pathJoinRoom.uint64_start_time===0&&(this._room=null),this.isDestroyed=!0}handleUnload(){this._room.isJoined&&this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})}handleJoinStart(i){this.hitTest(i.room)&&(this._pathJoinRoom.uint64_start_time===0&&(this._pathJoinRoom.uint64_start_time=Date.now()),i.params&&(T(i.params.frameWorkType)||(this._frameWorkType=i.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),T(i.params.component)||(this._component=i.params.component,this._basicInfo.uint32_component=this._component),T(i.params.language)||(this._language=i.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleJoinScheduleSuccess({room:i,detailCost:e}){if(this.hitTest(i)&&e){let{totalCost:t,local:r,dns:s,tcp:n,tls:a,request:d,response:l}=e;this._pathJoinRoom.int32_schedule_cost=t,this._pathJoinRoom.int32_schedule_local=r,this._pathJoinRoom.int32_schedule_dns=s,this._pathJoinRoom.int32_schedule_tcp=n,this._pathJoinRoom.int32_schedule_tls=a,this._pathJoinRoom.int32_schedule_request=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 v?Number(e.getExtraCode()||e.getCode()):I.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}handleJoinSendCMD(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now())}handleJoinReceivedCMDResponce(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=i.code,i.code!==0&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}handleJoinSuccess(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_end_time===0&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=i.room.getSignalInfo())}handleJoinFailed({room:i,error:e}){this.hitTest(i)&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret===0&&(this._pathJoinRoom.int32_end_ret=e.code||this._pathJoinRoom.int32_send_request_enter_room_cmd_ret||this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret),setTimeout(()=>{this.report()}))}handleReceivedPublishUserList(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_recv_userlist_time===0&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=i.publishedUserList||[])}handleSendFirstVideoFrame({room:i}){this.hitTest(i)&&this._pathJoinRoom.uint64_send_first_video_frame_time===0&&this._pathJoinRoom.uint64_start_time!==0&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now())}handleLeaveStart(i){this.hitTest(i.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(i){var e;if(this.hitTest(i.room)&&this._pathLeaveRoom.uint64_end_time===0){if(this._pathLeaveRoom.uint64_end_time=Date.now(),this._pathJoinRoom.uint64_end_time!==0){this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time;let t=(e=this._room.audioManager.localAudioTrack)==null?void 0:e.after3aSilenceStartTime;t&&(this._localStreamStat.statsToReport.uint32_after3a_silence_duration=V()-t)}else this._log.warn("pathJoinRoom endTime is 0");this.report()}}handleLeaveSendCMD(i){this.hitTest(i.room)&&(this._pathLeaveRoom.uint64_send_request_exit_room_cmd_start_time=Date.now(),this._pathLeaveRoom.uint64_send_request_exit_room_cmd_end_time=Date.now())}handleSwitchRoomStart(i){if(this.hitTest(i.room)){let e=Date.now();this.report().then(()=>{this._pathJoinRoom.uint64_start_time=e,this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=e})}}handleSwitchRoomSuccess({room:i}){if(this.hitTest(i)&&this._pathJoinRoom.uint64_end_time===0){let e=Date.now();this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=e,this._pathJoinRoom.uint64_end_time=e,this._pathJoinRoom.int32_end_ret}}handleSwitchRoomFailed({room:i,error:e}){if(this.hitTest(i)){let t=Date.now();this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=t,this._pathJoinRoom.uint64_end_time=t,e&&(this._pathJoinRoom.int32_end_ret=e instanceof v?Number(e.getExtraCode()||e.getCode()):I.UNKNOWN)}}handleRemoteStreamAdded(i,e){var r;let t=`${i}_${e}`;if(!this._remoteStreamStatMap.has(t)){let s={userId:i,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:w(M({},hI),{msg_user_info:new ra({userId:i,tinyId:(r=this._room.remotePublishedUserMap.get(i))==null?void 0:r.tinyId,role:20})})};s.statsToReport.uint32_stream_type=e==="main"?2:7,this._remoteStreamStatMap.set(t,s)}}handleSubscribeStart({room:i,remotePublishedUser:e,streamType:t,subscribeState:r}){if(!this.hitTest(i))return;let{userId:s,tinyId:n,role:a}=e,d=new ra({userId:s,tinyId:n,role:a==="anchor"?20:21}),l=Date.now(),u=`${s}_${t}`,h=this._remoteStreamStatMap.get(u);h&&h.subscribeStartTime===0&&(h.subscribeStartTime=l),t==="main"?(e.muteState.hasVideo&&(r.video||r.smallVideo)&&!this._pathMainVideoMap.has(u)&&this._pathMainVideoMap.set(u,{statsToReport:{msg_user_info:d,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:s,sendSubscribeCMDTime:l}),e.muteState.hasAudio&&r.audio&&!this._pathMainAudioMap.has(u)&&this._pathMainAudioMap.set(u,{statsToReport:{msg_user_info:d,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:s,sendSubscribeCMDTime:l})):e.muteState.hasAuxiliary&&r.auxiliary&&!this._pathAuxiliaryMap.has(u)&&this._pathAuxiliaryMap.set(u,{sendSubscribeCMDTime:l})}handleSubscribed({room:i,remotePublishedUser:e,streamType:t}){if(this.hitTest(i)){let r=`${e.userId}_${t}`,s=this._remoteStreamStatMap.get(r);s&&s.subscribedTime===0&&(s.subscribedTime=Date.now())}}handlePlayStart({track:i}){if(!i.isRemote||!this.hitTest(i.room))return;let e=`${i.userId}_${i.streamType}`,t=this._remoteStreamStatMap.get(e);(t==null?void 0:t.playStreamTime)===0&&(t.playStreamTime=Date.now())}handleVideoLoadedData({track:i}){if(!i.isRemote||!this.hitTest(i.room))return;let e=`${i.userId}_${i.streamType}`,t=this._pathMainVideoMap.get(e);t&&t.statsToReport.uint64_combine_first_frame_time===0&&(t.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(i){let e=`${i.userId}_${i.streamType}`,t=Date.now(),r=this._pathMainVideoMap.get(e),s=this._remoteStreamStatMap.get(e);if(s){let{statsToReport:n}=s;if(!n.uint32_video_render_first&&i.streamType==="main"?this.hasVideoFlag(i.userId):this.hasAuxFlag(i.userId)){let a=t-this._pathJoinRoom.uint64_start_time;n.uint32_video_render_first=a,y.addNumber({key:516820,value:a})}}(r==null?void 0:r.statsToReport.uint64_render_first_frame_time)===0&&(r.statsToReport.uint64_render_first_frame_time=t)}handleAudioPlaying(i){let e=`${i.userId}_${i.streamType}`,t=this._pathMainAudioMap.get(e);t&&t.statsToReport.uint64_play_first_frame_time===0&&(t.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(i){this.hitTest(i.room)&&(this._networkQuality.totalUplinkLoss+=i.uplink.loss,this._networkQuality.totalUplinkRTT+=i.uplink.rtt,this._networkQuality.count++,i.downlinks.forEach(({rtt:e,loss:t,userId:r,videoDelay:s,audioDelay:n})=>{let a=this._networkQuality.totalDownlinkRTTAndLossMap.get(r);if(a)a.totalRTT+=e,a.totalLoss+=t,s&&(a.totalVideoDelay=(a.totalVideoDelay||0)+s,a.videoDelayCount=(a.videoDelayCount||0)+1),n&&(a.totalAudioDelay=(a.totalAudioDelay||0)+n,a.audioDelayCount=(a.audioDelayCount||0)+1),a.count++;else{let d,l,u,h;s&&(l=s,u=1),n&&(d=n,h=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(r,{totalRTT:e,totalLoss:t,count:1,totalAudioDelay:d,totalVideoDelay:l,audioDelayCount:h,videoDelayCount:u})}}))}handleHeartbeatStats(i){var e;if(this.hitTest(i.room)){let{msg_device_info:t,msg_up_stream_info:r,msg_down_stream_info:s}=i.report;if(r.msg_video_status[0]){let{uint32_video_codec_bitrate:n,uint32_video_enc_fps:a,uint32_video_width:d,uint32_video_height:l}=r.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=n,this._localStreamStat.totalVideoFPS+=a,this._localStreamStat.totalVideoWidth+=d,this._localStreamStat.totalVideoHeight+=l,this._localStreamStat.videoCount++}if(r.msg_audio_status){let{uint32_audio_level:n}=r.msg_audio_status;Math.floor(n/Dt*100)>0&&(this._localStreamStat.totalAudioLevel+=n/Dt,this._localStreamStat.audioLevelCount++)}s.forEach(n=>{let{msg_user_info:a,msg_audio_status:d,msg_video_status:l}=n,u=a.str_identifier,h=this._room.remotePublishedUserMap.get(u);if(l.forEach(p=>{let m=p.uint32_video_stream_type===2,g=p.uint32_video_stream_type===7,E=`${u}_${m?"main":"auxiliary"}`,C=this._remoteStreamStatMap.get(E);if(C&&(m&&(h!=null&&h.remoteVideoTrack.isSubscribed)||g&&(h!=null&&h.remoteAuxiliaryTrack))){C.totalVideoFPS+=p.uint32_video_receive_fps,C.totalVideoBitrate+=p.uint32_video_codec_bitrate,C.videoCount++,C.statsToReport.uint32_video_width===0&&(C.statsToReport.uint32_video_width=p.uint32_video_width),C.statsToReport.uint32_video_height===0&&(C.statsToReport.uint32_video_height=p.uint32_video_height);let P=m?h.remoteVideoTrack:h.remoteAuxiliaryTrack;P.stat.jitterBufferDelay&&(C.videoJitterBufferDelay=P.stat.jitterBufferDelay),P.stat.framesReceived&&(C.statsToReport.uint32_video_consume_render_rate=Math.floor(P.stat.framesDecoded/P.stat.framesReceived*hr(10,6)))}}),!Uo(d)){let p=`${u}_main`,m=this._remoteStreamStatMap.get(p);this._remoteStreamStatMap.has(p)&&m&&h!=null&&h.remoteAudioTrack.isSubscribed&&(m.totalAudioBitrate+=d.uint32_audio_codec_bitrate,m.audioCount++,h.remoteAudioTrack.stat.jitterBufferDelay&&(m.audioJitterBufferDelay=h.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(d.uint32_audio_level/Dt*100)>0&&(m.totalAudioLevel+=d.uint32_audio_level/Dt,m.audioLevelCount++),d.uint32_audio_block_time&&(m.statsToReport.uint32_audio_block_time+=d.uint32_audio_block_time))}}),t.uint32_audio_capture_cost&&(this._captureCostSum+=t.uint32_audio_capture_cost,this._captureCostCount+=1,this._captureCostCount>=100&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0)),t.uint32_audio_capture_cost===0&&((e=this._room.audioManager.localAudioTrack)==null?void 0:e.muted)===!1&&(this._localStreamStat.statsToReport.uint32_audio_capture_thread_health_zero_cnt+=1)}}handlePublishStart({room:i}){this.hitTest(i)&&this._localStreamStat.publishStartTime===0&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart({track:i}){i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess({track:i}){i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=0,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=0,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed({track:i,error:e}){let r={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[e.name]||(e instanceof v?e.getExtraCode()||e.getCode():I.UNKNOWN);i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=r,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=r,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}hasVideoFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&fr)>=0}hasAudioFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&_r)>=0}hasAuxFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&Br)>=0}hitTest(i){return i===this._room}prepareReport(){if(this._captureCostCount>0&&!this._basicInfo.uint32_audio_capture_cost&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0),this._networkQuality.count>0&&(this._basicInfo.uint32_avg_rtt=Math.floor(this._networkQuality.totalUplinkRTT/this._networkQuality.count),this._basicInfo.uint32_avg_up_loss=Math.floor(this._networkQuality.totalUplinkLoss/this._networkQuality.count)),this._localStreamStat.videoCount>0){this._localStreamStat.statsToReport.uint32_video_big_capture_fps=Math.floor(this._localStreamStat.totalVideoFPS/this._localStreamStat.videoCount),this._localStreamStat.statsToReport.uint32_video_big_bitrate=Math.floor(this._localStreamStat.totalVideoBitrate/this._localStreamStat.videoCount);let i=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),e=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=i<<16|e}this._localStreamStat.audioLevelCount>0&&(this._localStreamStat.statsToReport.uint32_audio_capture_db=Math.floor(this._localStreamStat.totalAudioLevel/this._localStreamStat.audioLevelCount*100)),this._remoteStreamStatMap.forEach((i,e)=>{let{userId:t}=i,r=this._networkQuality.totalDownlinkRTTAndLossMap.get(t);if(r){let{totalLoss:u,count:h,audioDelayCount:p,videoDelayCount:m,totalAudioDelay:g,totalVideoDelay:E}=r;i.statsToReport.uint32_avg_down_loss=Math.floor(u/h),p&&g&&(i.statsToReport.uint32_audio_network_p2p_delay=Math.floor(g/p),i.audioJitterBufferDelay&&(i.statsToReport.uint32_p2p_delay=Math.floor(i.statsToReport.uint32_audio_network_p2p_delay+i.audioJitterBufferDelay))),m&&E&&(i.statsToReport.uint32_video_network_p2p_delay=Math.floor(E/m))}i.videoCount>0&&(i.statsToReport.uint32_video_avg_fps=Math.floor(i.totalVideoFPS/i.videoCount),i.statsToReport.uint32_video_avg_bitrate=Math.floor(i.totalVideoBitrate/i.videoCount)),i.audioCount>0&&(i.statsToReport.uint32_audio_recv_bitrate=i.statsToReport.uint32_audio_bitrate=Math.floor(i.totalAudioBitrate/i.audioCount)),i.audioLevelCount>0&&(i.statsToReport.uint32_audio_play_db=Math.floor(i.totalAudioLevel/i.audioLevelCount*100));let{callDurationCalculator:s}=this._room;s&&(i.statsToReport.uint32_audio_play_time=s.getDuration(e,_.AUDIO),i.statsToReport.uint32_video_play_time=s.getDuration(e,_.VIDEO)),i.statsToReport.uint32_video_render_first&&(i.statsToReport.uint32_video_render_first=Math.min(i.statsToReport.uint32_video_render_first,yo));let{badCaseDetector:n}=this._room,{dataFreeze:a,count: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),i.statsToReport.uint32_audio_block_time=Math.min(i.statsToReport.uint32_audio_block_time,i.statsToReport.uint32_audio_play_time),n.isBlackStream(e)&&i.statsToReport.uint32_video_avg_fps===0?i.statsToReport.uint32_video_black_screen_subjective=1:i.statsToReport.uint32_video_black_screen_subjective=0}),this._pathMainAudioMap.forEach((i,e)=>{if(!this.hasAudioFlag(i.userId)){this._pathMainAudioMap.delete(e);return}i.statsToReport.uint64_play_first_frame_time-i.statsToReport.uint64_start_enter_time>yo&&(i.statsToReport.uint64_play_first_frame_time=i.statsToReport.uint64_start_enter_time+yo)}),this._pathMainVideoMap.forEach((i,e)=>{if(!this.hasVideoFlag(i.userId)){this._pathMainVideoMap.delete(e);return}i.statsToReport.uint64_render_first_frame_time-i.statsToReport.uint64_start_enter_time>yo&&(i.statsToReport.uint64_render_first_frame_time=i.statsToReport.uint64_start_enter_time+yo)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>yo&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+yo)}getReportData(){this._basicInfo.uint32_networkType=Jr();let i={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new ra({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:Vo(this._signalInfo.relayIp),uint32_client_ip:Vo(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*hr(2,31)),msg_path_enter_room:this._pathJoinRoom,msg_path_exit_room:this._pathLeaveRoom,msg_path_recv_video:[...this._pathMainVideoMap.values()].map(e=>e.statsToReport),msg_quality_statistics:[...this._remoteStreamStatMap.values()].map(e=>e.statsToReport),str_room_name:String(this._room.roomId||0),msg_path_recv_audio:[...this._pathMainAudioMap.values()].map(e=>e.statsToReport),uint32_info_client_ip:Vo(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,bytes_report_buf_from_0x1:this._signalInfo.endReportExtend,str_user_sig:this._room.userSig,bytes_report_token:this._signalInfo.reportToken};return Js(i),i}report(){return f(this,null,function*(){try{this.prepareReport();let i=this.getReportData();yield this.upload(i),this.initData()}catch(i){this._log.warn(i)}finally{this.isDestroyed&&(this._room=null)}})}upload(i){return f(this,null,function*(){if(i.msg_path_enter_room.uint64_start_time===0)return;let e=Number(this._room.sdkAppId),t=Ir.enable?qi(i,2001,e):yield gl(i),r=t instanceof ArrayBuffer,s=`${Ji(e,mr.KEY_POINT)}&gzip=${+r}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(s,t));let a=[this.uploadKVStat(y),this.uploadKVStat(ro)];n||a.push(ji({url:s,body:t,priority:"low"})),yield Promise.all(a)})}setConnectionType(i){this.connectionType=i,this._basicInfo.uint32_connection_type=i}uploadKVStat(i){return f(this,null,function*(){let e=i.getReportData(this._room.userSig,this._signalInfo.reportToken);if(e.stats_count.length===0&&e.stats_distribution.length===0)return;e.msg_sdk_basic_info=w(M({},e.msg_sdk_basic_info),{bytes_device_name:this._basicInfo.string_device_name||"",bytes_os_version:this._basicInfo.string_os_version||"",uint32_framework:this._frameWorkType,uint32_network_type:this._basicInfo.uint32_networkType||0}),this._log.debug(e);let t=Ir.enable?qi(e,2003,this._room.sdkAppId):yield gl(e),r=t instanceof ArrayBuffer,s=`${Ji(+this._room.sdkAppId,mr.KV_STAT)}&gzip=${+r}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(s,t)),n||ji({url:s,body:t})})}};D([Mt({settings:{timeout:500,retries:3}})],Nc.prototype,"upload",1);var yo=5e3,hI={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},ra=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}},__=Nc;var Kh=class{constructor(){c(this,"_startTime");c(this,"_endTime");this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=V())}stop(){this._endTime===0&&(this._endTime=V())}getDuration(){return this._endTime===0?V()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},vc=Kh;var em=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(A.REMOTE_TRACK_SUBSCRIBED,this.handleSubscribed).set(A.REMOTE_TRACK_UNSUBSCRIBED,this.handleUnsubscribed).set(A.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{var n;let{userId:r}=t;if(!this.hitTest(i))return;e.hasAudio&&!t.hasAudio&&this.stopDurationItem(`${r}_main`,_.AUDIO),e.hasVideo&&!t.hasVideo&&this.stopDurationItem(`${r}_main`,_.VIDEO),e.hasAuxiliary&&!t.hasAuxiliary&&this.stopDurationItem(`${r}_auxiliary`,_.VIDEO);let s=(n=this._room)==null?void 0:n.remotePublishedUserMap.get(r);s&&(!e.hasAudio&&t.hasAudio&&s.remoteAudioTrack.isSubscribed&&this.addDuractionItem(r,_.AUDIO,"main"),!e.hasVideo&&t.hasVideo&&s.remoteVideoTrack.isSubscribed&&this.addDuractionItem(r,_.VIDEO,"main"),!e.hasAuxiliary&&t.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(r,_.VIDEO,"auxiliary"))}),this._eventMap.forEach((i,e)=>S.on(e,i,this))}uninstallEvents(){this._eventMap.forEach((i,e)=>S.off(e,i,this)),this._eventMap.clear()}handleSubscribed({track:i}){if(!this.hitTest(i.room))return;let{userId:e,streamType:t,kind:r}=i;i.isSubscribed?this.addDuractionItem(e,r,t):this.stopDurationItem(`${e}_${t}`,r)}handleUnsubscribed({track:i}){this.hitTest(i.room)&&this.stopDurationItem(`${i.userId}_${i.streamType}`,i.kind)}isRecording(i){return i.findIndex(e=>e.endTime===0)>=0}addDuractionItem(i,e,t){let r=`${i}_${t}`,s=new vc,n=this._durationMap.get(r);n?this.isRecording(n[e])||n[e].push(s):this._durationMap.set(r,{userId:i,type:t,audio:e===_.AUDIO?[s]:[],video:e===_.AUDIO?[]:[s]})}stopDurationItem(i,e){if(this._durationMap.has(i)){let r=this._durationMap.get(i)[e].find(s=>s.endTime===0);r&&r.stop()}}hitTest(i){return this._room===i}getDuration(i,e){return this._durationMap.has(i)?this._durationMap.get(i)[e].reduce((r,s)=>r+s.getDuration(),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},g_=em;var tm=class{constructor(){c(this,"renderFreezeMap",new Map);c(this,"dataFreezeMap",new Map)}get(i,e){let t=this.renderFreezeMap.get(i),r=this.dataFreezeMap.get(i);return e?e==="data"?r:t:(Re||ee)&&t&&r&&t.duration>r.duration?t:r}set(i,e,t){t==="data"?this.dataFreezeMap.set(i,e):this.renderFreezeMap.set(i,e)}clear(){this.renderFreezeMap.clear(),this.dataFreezeMap.clear()}},im=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 tm);c(this,"_eventMap",new Map);c(this,"_videoEncodeFailedCount",0);c(this,"_audioEncodeFailedCount",0);c(this,"_encodeFailedThreshold",3);c(this,"eventListenerMap",new Map);this._room=i.room,this.installEvents()}getRenderFreezeMap(){return this._renderFreezeMap}getDataFreezeMap(){return this._dataFreezeMap}installEvents(){this._eventMap.set(A.LEAVE_SUCCESS,({room:i})=>{this.hitTest(i)&&this.stop()}).set(A.PLAY_TRACK_START,this.onPlayTrackStart).set(A.UNSUBSCRIBE_SUCCESS,({room:i,streamType:e,remotePublishedUser:t})=>{if(!this.hitTest(i))return;let{userId:r}=t,s=`${r}_${e}`;this.stopDataFreeze({key:s,userId:r,type:e})}).set(A.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{if(!this.hitTest(i))return;let{userId:r}=t;if(e.hasVideo&&!t.hasVideo){let s="main",n=`${t.userId}_${s}`;this.stopDataFreeze({key:n,userId:r,type:s})}if(e.hasAuxiliary&&!t.hasAuxiliary){let s="auxiliary",n=`${t.userId}_${s}`;this.stopDataFreeze({key:n,userId:r,type:s})}}).set(A.PLAYER_STATE_CHANGED,({track:i,state:e,reason:t,type:r})=>{if(!(!i.isRemote||!i.room||!this.hitTest(i.room)||r!==_.VIDEO)){if(e==="PLAYING"){let s=`${i.userId}_${i.streamType}`;this._isVideoPlayingEventFiredMap.set(s,!0)}t===_.MUTE?this.onVideoTrackMuted(i):t===_.UNMUTE&&this.onVideoTrackUnmuted(i)}}).set(A.HEARTBEAT_REPORT,this.onHearBeatReport).set(A.REMOTE_VIDEO_PLAY_START,this.onRemoteVideoPlayStart).set(A.REMOTE_VIDEO_PLAY_FINISH,this.onRemoteVideoPlayEnd),this._eventMap.forEach((i,e)=>S.on(e,i,this))}uninstallEvents(){this._eventMap.forEach((i,e)=>S.off(e,i,this)),this._eventMap.clear()}stop(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}onVideoTrackMuted(i){if(!i.isSubscribed)return;let{userId:e,streamType:t}=i,r=`${e}_${t}`,s=this._dataFreezeMap.get(r),n=new vc;s?s.durationItemList.push(n):this._dataFreezeMap.set(r,{userId:e,type:t,durationItemList:[n],isFreezing(){let a=this.durationItemList[this.durationItemList.length-1];return a&&a.endTime===0}})}onVideoTrackUnmuted(i){if(!i.isSubscribed)return;let{userId:e,streamType:t}=i,r=`${e}_${t}`;this.stopDataFreeze({key:r,userId:e,type:t})}onHearBeatReport({room:i,report:e}){if(this.hitTest(i)){if(e.msg_up_stream_info.msg_video_status){let t=e.msg_up_stream_info.msg_video_status,r=Array.from(this._room.localTracks).find(n=>n.kind==="video"&&!n.isScreen),s=(r==null?void 0:r.stat.bytesSent)||0;if((r==null?void 0:r.isMediaTrackActive)===!1||s<=0||r!=null&&r.isUseCustomSource)return;t.forEach(n=>{n.uint32_video_stream_type===2&&(n.uint32_video_capture_fps!==0&&n.uint32_video_codec_bitrate===0&&n.uint32_video_enc_fps===0&&(r!=null&&r.isPublished)?(this._videoEncodeFailedCount+=1,this._videoEncodeFailedCount===this._encodeFailedThreshold&&se.uploadEvent({userId:this._room.userId,log:`stat-${Ze.VIDEO_ENCODE_FAILED_DURING_CALL}`})):this._videoEncodeFailedCount=0)})}if(e.msg_up_stream_info.msg_audio_status){let t=e.msg_up_stream_info.msg_audio_status,r=Array.from(this._room.localTracks).find(n=>n.kind==="audio"),s=(r==null?void 0:r.stat.bytesSent)||0;if((r==null?void 0:r.isMediaTrackActive)===!1||s<=0)return;t.uint32_audio_codec_bitrate===0&&(r!=null&&r.isPublished)?(this._audioEncodeFailedCount+=1,this._audioEncodeFailedCount===this._encodeFailedThreshold&&se.uploadEvent({userId:this._room.userId,log:`stat-${Ze.AUDIO_ENCODE_FAILED_DURING_CALL}`})):this._audioEncodeFailedCount=0}}}stopDataFreeze({key:i,userId:e,type:t}){let r=this._dataFreezeMap.get(i);if(!r||!r.isFreezing())return;let s=r.durationItemList[r.durationItemList.length-1];s.stop();let n=s.getDuration();if(n>Ea){let a=this._monitorFreezeData.get(i,"data");this._monitorFreezeData.set(i,{userId:e,type:t,duration:a?a.duration+n:n},"data")}else r.durationItemList.pop()}getTotalDuration(i){return i.reduce((e,t)=>{let r=t.getDuration();return e+Math.min(r,5e3)},0)}onPlayTrackStart({track:i}){if(!i.isRemote||!this.hitTest(i.room)||i.kind!==_.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()<Ea&&t.durationItemList.pop()}e.dataFreeze=this.getTotalDuration(t.durationItemList),e.count=t.durationItemList.length}return e}getRenderFreezeDuration(i){let e={renderFreeze:0,count:0},t=this._renderFreezeMap.get(i);return t&&(e.renderFreeze=t.totalDuration,e.count=t.count),e}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(i){return this._isVideoPlayingEventFiredMap.has(i)?!this._isVideoPlayingEventFiredMap.get(i):!1}onRemoteVideoPlayStart({track:i,player:e}){var n;if(!Ki())return;let t=0,r=()=>{document.hidden||(t=0)};document.addEventListener("visibilitychange",r);let s=(a,d)=>{var l;if(t){let u=i.decodeFPS,h=u>0&&u<=5?600+1e3/u:600,p=d.presentationTime-t;if(p>h){p=Math.min(p,5e3);let m=`${i.userId}_${i.streamType}`,g=this._monitorFreezeData.get(m,"render");g?g.duration+=p:this._monitorFreezeData.set(m,{userId:i.userId,type:i.streamType,duration:p},"render");let E=this._renderFreezeMap.get(m);E?(E.totalDuration+=p,E.count+=1):this._renderFreezeMap.set(m,{userId:i.userId,type:i.streamType,totalDuration:p,count:1})}}t=d.presentationTime,(l=e.element)==null||l.requestVideoFrameCallback(s)};(n=e.element)==null||n.requestVideoFrameCallback(s),this.eventListenerMap.set(`${i.userId}_${i.streamType}`,{onVisibilityChange:r})}onRemoteVideoPlayEnd({track:i,player:e}){let t=`${i.userId}_${i.streamType}`,r=this.eventListenerMap.get(t);r&&document.removeEventListener("visibilitychange",r.onVisibilityChange)}resetMonitor(){this._monitorFreezeData.clear()}hitTest(i){return i===this._room}destroy(){this.uninstallEvents()}},T_=im;var I_=Je(nt(),1);var Dc=class{constructor(i,e,t,r,s,n=4/3){this.vbMode=i;this.faceDetectorHash=t;this.visionTaskRegistry=r;this.logger=s;c(this,"animationState");c(this,"originalAspect");c(this,"totalOffsetX",0);c(this,"totalOffsetY",0);c(this,"defaultScaleRatio",.1);c(this,"isRecovering",!1);c(this,"boundaryY",280);c(this,"lastActionTime",0);c(this,"restTime",400);this.animationState={current:null,target:null,animating:!1,debounceTimer:null,startTime:0,duration:3e3,debounceTime:150,movementThreshold:30,debounceThreshold:15},this.addEvent(this.vbMode,!!this.faceDetectorHash),this.originalAspect=n||4/3,this.visionTaskRegistry.setVideo(this.faceDetectorHash,e)}addEvent(i,e,t){let s=[{key:570704,error:t!=null?t:e?void 0:11},{key:570705,error:t!=null?t:e?void 0:22}][i-1];s&&(e?y.addSuccessEvent({key:s.key}):y.addFailedEvent({key:s.key,error:s.error}))}actionCentering(i){let e=Date.now();if(this.animation(),!this.faceDetectorHash||e-this.lastActionTime<this.restTime||this.animationState.animating)return;let{videoWidth:t,videoHeight:r}=i;this.animationState.debounceThreshold=t/30,this.animationState.movementThreshold=t/20,this.boundaryY=r*.6;try{let s=this.visionTaskRegistry.getResult(this.faceDetectorHash);if(s.detections.length<=0){this.vbMode===1&&this.recoverOriginal(t,r);return}let n=s.detections[0].boundingBox,a=n.originX,d=n.originY,l=n.width,u=n.height;this.vbMode===1?this.dualStageCropping(t,r,a,d,l,u):this.vbMode===2&&this.movingPortrait(t,r,a,d,l,u)}catch(s){this.logger.error(s)}this.lastActionTime=e}calculateBoundary(i,e,t,r){let s,n;return i>e/2?(s=e-t-r,n=t-s):(s=t,n=0),{min:s,offset:n}}calculateTargetPosition(i,e,t,r,s,n,a=.4){let d=i+t/2,l=e+r/2,u,h,{min:p,offset:m}=this.calculateBoundary(d,s,i,t),{min:g,offset:E}=this.calculateBoundary(l,n,e,r);return u=2*p+t,h=2*g+r,u/h>this.originalAspect?(u=h*this.originalAspect,m=d-u/2):(h=u/this.originalAspect,E=l-h/2),t/s>a&&(m=0,E=0,u=s,h=n),m=Math.max(0,Math.min(m,s-u)),E=Math.max(0,Math.min(E,n-h)),{sx:m,sy:E,cropWidth:u,cropHeight:h,timestamp:Date.now()}}processFacePositionCrop(i,e,t){if(!this.animationState.current||!this.animationState.target){let a={sx:0,sy:0,cropWidth:e,cropHeight:t,timestamp:Date.now()};this.animationState.current=a,this.animationState.target=a;return}let r=this.positionDistance(this.animationState.target,i),s=this.positionDistance(this.animationState.current,i),n=this.animationState.current.cropWidth/e;r>this.animationState.debounceThreshold*n&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&s>this.animationState.movementThreshold*n&&(this.animationState.target=i,this.animationState.debounceTimer=setTimeout(()=>{this.animationState.startTime=Date.now(),this.animationState.animating=!0},this.animationState.debounceTime))}processFacePositionPortrait(i){if(!this.animationState.current||!this.animationState.target){this.animationState.current=M({},i),this.animationState.target=M({},i);return}let e=this.positionDistance(this.animationState.current,i),t=this.positionDistance(this.animationState.target,i);e>this.animationState.debounceThreshold&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&t>this.animationState.movementThreshold&&(this.animationState.current=i,this.animationState.debounceTimer=setTimeout(()=>{this.animationState.startTime=Date.now(),this.animationState.animating=!0},this.animationState.debounceTime))}animation(){if(!this.animationState.animating)return;let i=Date.now()-this.animationState.startTime,e=Math.min(i/this.animationState.duration,1),t=r=>r<.5?2*r*r:-1+(4-2*r)*r;if(this.animationState.current&&this.animationState.target){let r=(this.animationState.target.sx-this.animationState.current.sx)*t(e);this.animationState.current.sx+=r,this.totalOffsetX+=r;let s=(this.animationState.target.sy-this.animationState.current.sy)*t(e);if(this.animationState.current.sy+=s,this.totalOffsetY+=s,this.animationState.current.cropWidth+=(this.animationState.target.cropWidth-this.animationState.current.cropWidth)*t(e),this.animationState.current.cropHeight+=(this.animationState.target.cropHeight-this.animationState.current.cropHeight)*t(e),this.animationState.current.scaleRatio&&this.animationState.target.scaleRatio&&(this.animationState.current.scaleRatio+=(this.animationState.target.scaleRatio-this.animationState.current.scaleRatio)*t(e)),Q(this.animationState.current.scaleOffsetX)&&Q(this.animationState.target.scaleOffsetX)&&Q(this.animationState.current.scaleOffsetY)&&Q(this.animationState.target.scaleOffsetY)){let n=(this.animationState.target.scaleOffsetX-this.animationState.current.scaleOffsetX)*t(e);this.animationState.current.scaleOffsetX+=n;let a=(this.animationState.target.scaleOffsetY-this.animationState.current.scaleOffsetY)*t(e);this.animationState.current.scaleOffsetY+=a}}e>=1&&(this.animationState.animating=!1,this.animationState.current=this.animationState.target,this.isRecovering=!1)}positionDistance(i,e){return Math.sqrt(hr(i.sx-e.sx,2)+hr(i.sy-e.sy,2))}recoverOriginal(i,e){this.animationState.target={sx:0,sy:0,cropWidth:i,cropHeight:e,timestamp:Date.now()},this.animationState.animating=!0,this.animationState.startTime=Date.now(),this.isRecovering=!0}dualStageCropping(i,e,t,r,s,n,a=.3){if(this.isRecovering)return;let d=this.calculateTargetPosition(t,r,s,n,i,e);this.processFacePositionCrop(d,i,e),s*n/d.cropWidth/d.cropHeight>a&&this.recoverOriginal(i,e)}movingPortrait(i,e,t,r,s,n){var d,l,u,h,p,m,g,E,C,P,re,L;let a={sx:t+s/2+this.totalOffsetX,sy:r+n/2+this.totalOffsetY,cropWidth:i,cropHeight:e,scaleRatio:(l=(d=this.animationState.current)==null?void 0:d.scaleRatio)!=null?l:1,scaleOffsetX:(h=(u=this.animationState.current)==null?void 0:u.scaleOffsetX)!=null?h:0,scaleOffsetY:(m=(p=this.animationState.current)==null?void 0:p.scaleOffsetY)!=null?m:0,timestamp:Date.now()};this.animationState.target={sx:i/2,sy:r+n/2,cropWidth:i,cropHeight:e,scaleRatio:(E=(g=this.animationState.target)==null?void 0:g.scaleRatio)!=null?E:1,scaleOffsetX:(P=(C=this.animationState.target)==null?void 0:C.scaleOffsetX)!=null?P:0,scaleOffsetY:(L=(re=this.animationState.target)==null?void 0:re.scaleOffsetY)!=null?L:0,timestamp:Date.now()},this.animationState.animating||(this.animationState.target.scaleRatio=Math.sqrt(s*n/i/e/this.defaultScaleRatio),this.animationState.target.scaleOffsetX=-this.animationState.target.scaleRatio/2+.5,this.animationState.target.scaleOffsetY=-this.animationState.target.scaleRatio+1,(this.animationState.target.sy-this.animationState.target.scaleOffsetY*this.animationState.target.cropHeight)/this.animationState.target.scaleRatio<this.boundaryY&&(this.animationState.target.scaleOffsetY=(this.animationState.target.sy-this.boundaryY*this.animationState.target.scaleRatio)/this.animationState.target.cropHeight)),this.processFacePositionPortrait(a)}set aspectRatio(i){this.originalAspect=i}get current(){return this.animationState.current}get offset(){return{offsetX:this.totalOffsetX,offsetY:this.totalOffsetY}}get targetCrop(){return this.animationState.target}};var mI=`#version 300 es
76
+ `),e}removeBandwidthRestriction(e){return e.replace(/b=AS:.*\r\n/,"").replace(/b=TIAS:.*\r\n/,"")}removeVideoOrientation(e){return e.replace(/urn:3gpp:video-orientation/,"")}connect(){return f(this,null,function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(e){throw this.closePeerConnection(!0),this.uninstallEvents(),e}})}exchangeSDP(){return f(this,null,function*(){try{yield this.createOffer(),this._log.info("createOffer success, sending offer to remote server"),yield this.doExchangeSDP()}catch(e){throw e}})}createOffer(){return f(this,null,function*(){try{let e=yield this._peerConnection.createOffer(C_);yield this.setOffer(e),e.sdp&&this.updateSSRC(e.sdp)}catch(e){throw e}})}doExchangeSDP(){let e={command:Z.PUBLISH,responseCommand:W.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof Pt||this.localAuxVideoTrack instanceof Pt,state:this._room.publishState,constraintConfig:this._mediaSettings},enableLog:!1};return this._log.debug(`sending sdp offer: ${e.data.sdp}`),this._signalChannel.sendWaitForResponse(e).then(t=>{let{code:r,message:s,data:n}=t.data;return r===0?this.acceptAnswer(n):this.checkPublishResultCode(r,s)})}setSDPDirection(e,t,r="all"){let s=De(e);return s.media.forEach(n=>{(r==="all"||n.type===r)&&(n.direction=t)}),jt(s)}acceptAnswer(e){return f(this,null,function*(){var t,r,s,n,a;try{let c;if(this._publishingLocalAudioTrack||this._publishingLocalVideoTrack||this.isMainStreamPublished){let m=((t=this._publishingLocalVideoTrack)==null?void 0:t.profile.bitrate)||((r=this.localMainVideoTrack)==null?void 0:r.profile.bitrate),u=((s=this._publishingLocalAudioTrack)==null?void 0:s.profile.bitrate)||((n=this.localMainAudioTrack)==null?void 0:n.profile.bitrate);if(m){let _=this._isPublishingAux?p.AUXILIARY:p.BIG;c=yield this.setBandwidth({bandwidth:m,type:p.VIDEO,sdp:c,videoType:_})}u&&(c=yield this.setBandwidth({bandwidth:u,type:p.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:p.VIDEO,videoType:p.SMALL,sdp:c})}let h={type:e.type,sdp:c};yield this.setAnswer(h),this._log.debug(`accepted answer: ${c}`)}catch(c){throw this._log.error(`failed to accept remote answer ${c}`),c}})}sendMutedFlag(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info(`send muted state: ${JSON.stringify(this._room.muteState)}`),this._signalChannel.send(Z.UPDATE_MUTE_STAT,this._room.muteState))}getIsReconnecting(){return this._isReconnecting}reconnect(){return f(this,null,function*(){if(!(we(Os.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:Z.UNPUBLISH,responseCommand:W.UNPUBLISH_RESULT,enableLog:!1}),this.closePeerConnection(),this.initialize(),this.isMainStreamPublished&&(yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0})),this._log.warn("reconnect() uplink reconnect successfully"),this.stopReconnection()}catch(t){let r=Kt(this._reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${r/1e3}s`),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},r)}})}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&S.emit(C.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{De(e).media.forEach((r,s)=>{if(r.type===p.AUDIO){let n=r.ssrcs&&r.ssrcs[0];n&&(this.ssrc.audio=Number(n.id))}else{if(this._sdpSemantics===ko&&r.ssrcGroups){r.ssrcGroups.forEach((a,c)=>{let l=Number(a.ssrcs.split(" ")[0]);c===0?this.ssrc.video=l:c===1&&(this.ssrc.small=l)});return}let n=r.ssrcs&&r.ssrcs[0];if(!n)return;switch(s){case 1:this.ssrc.video=Number(n.id);break;case 2:this.ssrc.small=Number(n.id);break;case 3:this.ssrc.auxiliary=Number(n.id);break;default:break}}})}catch(t){}}getVideoTrackId(e=p.VIDEO){if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===p.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===p.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===p.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===p.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===$r?(this._log.error(Xe.NOT_SUPPORTED_H264ENCODE),new D({code:I.NOT_SUPPORTED_H264,message:$({key:B.NOT_SUPPORTED_H264ENCODE})})):new D({code:I.UNKNOWN,message:$({key:B.SIGNAL_RESPONSE_FAILED,data:{signalResponse:W.PUBLISH_RESULT,code:e,message:t}})})}};M([Y(e=>function(...t){return new Promise((r,s)=>{let n=a=>{this._emitter.off("closed",n),s(new D({code:I.API_CALL_ABORTED,message:$({key:B.CONNECTION_ABORTED,data:a})}))};this._emitter.on("closed",n),e.apply(this,t).then(r,s).finally(()=>{this._emitter.off("closed",n)})})})],Os.prototype,"publish",1),M([Rt(521715,!1)],Os.prototype,"unpublish",1),M([Ct(pt.prototype.afterConnect),Lc(pt.prototype.beforeConnect)],Os.prototype,"connect",1);var cm=Os,sa=cm;var na=class{constructor(i,e){this.room=i;d(this,"_log");d(this,"_prevReportTime",0);d(this,"_prevReport",{});d(this,"_prevStats",null);d(this,"_prevEncoderImplementation","");d(this,"_prevAuxEncoderImpl","");d(this,"_prevQualityLimitationReason","");d(this,"_prevAuxQualityLimitationReason","");d(this,"_prevDecoderImplementationMap",new Map);d(this,"_decodeMap",new Map);d(this,"_prevQpSum",0);d(this,"_prevAuxQpSum",0);d(this,"totalBytesSent",0);d(this,"totalBytesReceived",0);d(this,"_spcStats",null);this._log=e}get statInterval(){return this._prevReportTime===0?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(i){return f(this,null,function*(){var s;let e={audio:{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0},video:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},small:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},auxiliary:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},rtt:0},t=i.getPeerConnection(),r=i.getSSRC();if(t)try{if((this._spcStats||(yield t.getStats())).forEach(a=>{var h,m,u,_,g,E,A,k,se,w,Ze,N,y;let c,l;if(a.type==="outbound-rtp")if((a.mediaType||a.kind)===p.VIDEO){if(a.ssrc===r.video?(c=p.VIDEO,l=i.localMainVideoTrack):a.ssrc===r.small?c=p.SMALL:a.ssrc===r.auxiliary&&(l=i.localAuxVideoTrack,c=p.AUXILIARY),!c)return;e[c].bytesSent=a.bytesSent,e[c].packetsSent=a.packetsSent,e[c].framesEncoded=a.framesEncoded,T(a.keyFramesEncoded)||(e[c].keyFramesEncoded=a.keyFramesEncoded),T(a.nackCount)||(e[c].nackCount=a.nackCount),T(a.pliCount)||(e[c].pliCount=a.pliCount),T(a.retransmittedPacketsSent)||(e[c].retransmittedPacketsSent=a.retransmittedPacketsSent),T(a.totalEncodeTime)||(e[c].totalEncodeTime=a.totalEncodeTime),T(a.totalPacketSendDelay)||(e[c].totalPacketSendDelay=a.totalPacketSendDelay);let ge=0;if(!T(a.qpSum)&&!T(a.framesEncoded)&&a.framesEncoded>0){let de=a.qpSum,Me=a.framesEncoded,Ut=c===p.VIDEO?this._prevQpSum:this._prevAuxQpSum,Do=c===p.VIDEO?((m=(h=i.localMainVideoTrack)==null?void 0:h.stat)==null?void 0:m.framesEncoded)||0:((_=(u=i.localAuxVideoTrack)==null?void 0:u.stat)==null?void 0:_.framesEncoded)||0;if(Me>Do&&de>Ut){let qd=de-Ut,Jd=Me-Do;ge=Math.round(qd/Jd),ge>35&&this._log.warn(`${c===p.AUXILIARY?"aux ":""}video encoder QP is high: ${ge}, resolution: ${a.frameWidth}x${a.frameHeight}, codec: ${i.videoCodec}, `)}c===p.VIDEO?this._prevQpSum=de:c===p.AUXILIARY&&(this._prevAuxQpSum=de)}if(!T(a.encoderImplementation)&&(c===p.VIDEO&&this._prevEncoderImplementation!==a.encoderImplementation||c===p.AUXILIARY&&this._prevAuxEncoderImpl!==a.encoderImplementation)){let de=2,Me=this._prevEncoderImplementation;c===p.AUXILIARY&&(de=7,Me=this._prevAuxEncoderImpl),S.emit("262",{userId:i.userId,streamType:de,prevImplementation:Me,implementation:a.encoderImplementation,codec:i.videoCodec,isHWCodec:a.powerEfficientEncoder}),this[c===p.VIDEO?"_prevEncoderImplementation":"_prevAuxEncoderImpl"]=a.encoderImplementation,this._log.info(`${c===p.AUXILIARY?"aux ":""}encoderImplementation change to ${a.encoderImplementation}(${i.videoCodec}) HWEncoder: ${a.powerEfficientEncoder}`)}a.ssrc===r.video?!T(a.qualityLimitationReason)&&a.bytesSent!==0&&this._prevQualityLimitationReason!==a.qualityLimitationReason&&(this._log.info(`qualityLimitationReason change to ${a.qualityLimitationReason}`),S.emit("263",{userId:i.userId,reason:a.qualityLimitationReason,prevReason:this._prevQualityLimitationReason,streamType:2,isQosClearFirst:(g=i.localMainVideoTrack)==null?void 0:g.isQosClearFirst}),this._prevQualityLimitationReason=a.qualityLimitationReason):a.ssrc===r.auxiliary&&!T(a.qualityLimitationReason)&&a.bytesSent!==0&&this._prevAuxQualityLimitationReason!==a.qualityLimitationReason&&(this._log.info(`aux qualityLimitationReason change to ${a.qualityLimitationReason}`),S.emit("263",{userId:i.userId,reason:a.qualityLimitationReason,prevReason:this._prevAuxQualityLimitationReason,streamType:7,isQosClearFirst:(E=i.localAuxVideoTrack)==null?void 0:E.isQosClearFirst}),this._prevAuxQualityLimitationReason=a.qualityLimitationReason)}else e.audio.bytesSent=a.bytesSent,e.audio.packetsSent=a.packetsSent;else if(a.type==="candidate-pair")Rr(a)&&(this.totalBytesSent=a.bytesSent,Q(a.currentRoundTripTime)&&(e.rtt=Math.floor(a.currentRoundTripTime*1e3)));else if(a.type==="media-source"){if(a.kind===p.AUDIO)e.audio.audioLevel=a.audioLevel||0,e.audio.totalAudioEnergy=a.totalAudioEnergy||0,a.echoReturnLoss,T((se=(k=(A=i.localMainAudioTrack)==null?void 0:A.sourceTrack)==null?void 0:k.stats)==null?void 0:se.deliveredFramesDuration)?a.totalSamplesDuration&&(e.audio.totalSamplesDuration=a.totalSamplesDuration):e.audio.totalSamplesDuration=i.localMainAudioTrack.sourceTrack.stats.deliveredFramesDuration/1e3;else if(a.kind===p.VIDEO)if(a.trackIdentifier===i.getVideoTrackId(p.VIDEO))if((N=(Ze=(w=i.localMainVideoTrack)==null?void 0:w.sourceTrack)==null?void 0:Ze.stats)!=null&&N.deliveredFrames){let{deliveredFrames:q}=i.localMainVideoTrack.sourceTrack.stats;e.video.framesCaptured=q,i.localMainVideoTrack.stat.framesCaptured&&i.localMainVideoTrack.stat.framesCaptured>0&&q>=i.localMainVideoTrack.stat.framesCaptured?e.video.fpsCapture=Math.floor((q-i.localMainVideoTrack.stat.framesCaptured)/this.statInterval):e.video.fpsCapture=a.framesPerSecond}else e.video.fpsCapture=a.framesPerSecond;else a.trackIdentifier===i.getVideoTrackId(p.AUXILIARY)?e.auxiliary.fpsCapture=a.framesPerSecond:e.small.fpsCapture=a.framesPerSecond}if(!T(a.audioLevel)&&((y=i.localMainAudioTrack)!=null&&y.mediaTrack)&&a.trackIdentifier===i.localMainAudioTrack.mediaTrack.id&&(e.audio.audioLevel=a.audioLevel||0),!T(a.frameWidth)){let q=p.SMALL;a.trackIdentifier===i.getVideoTrackId(p.VIDEO)||a.ssrc===r.video?q=p.VIDEO:(a.trackIdentifier===i.getVideoTrackId(p.AUXILIARY)||a.ssrc===r.auxiliary)&&(q=p.AUXILIARY),e[q].frameWidth=a.frameWidth,e[q].frameHeight=a.frameHeight,e[q].framesSent=a.framesSent}}),i.localMainAudioTrack){let a=i.localMainAudioTrack.getInternalAudioLevel(),c=i.localMainAudioTrack.getInternalAudioLevelAfter3A();e.audio.audioCaptureEnergyAfter3a=c,e.audio.micAudioLevel=a,e.audio.audioLevel===0&&(e.audio.audioLevel=a)}this.totalBytesSent||(this.totalBytesSent+=e.audio.bytesSent+e.video.bytesSent+e.auxiliary.bytesSent),Object.keys(e).forEach(a=>{a===p.AUDIO?(i.localMainAudioTrack&&(i.localMainAudioTrack.stat=e[a]),i.localAuxAudioTrack&&(i.localAuxAudioTrack.stat=e[a])):a===p.VIDEO?i.localMainVideoTrack&&(i.localMainVideoTrack.stat=e[a]):a===p.AUXILIARY&&i.localAuxVideoTrack&&(i.localAuxVideoTrack.stat=e[a])})}catch(n){this._log.warn(`failed to getStats on sender connection ${n}`)}return e.rtt===0&&(e.rtt=((s=this.room.networkQuality)==null?void 0:s.uplinkRTT)||0),e})}getReceiverStats(i){return f(this,null,function*(){var r,s,n;let e={tinyId:i.tinyId,userId:i.userId,rtt:0,hasAudio:!1,hasVideo:!1,hasAuxiliary:!1,isSmallSubscribed:!1,audio:{bytesReceived:0,packetsReceived:0,packetsLost:0,p2pDelay:0,totalJitter:0,totalJitterCount:0,audioLevel:0,totalAudioEnergy:0,insertedSamplesForDeceleration:0,removedSamplesForAcceleration:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,freezeCount:0,totalFreezesDuration:0,totalJitter:0,totalJitterCount:0,p2pDelay:0,codec:""},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,totalJitter:0,totalJitterCount:0,p2pDelay:0,codec:""}},t=i.getPeerConnection();if(t)try{let{ssrc:a}=i,{muteState:c,subscribeState:l}=i;(this._spcStats||(yield t.getStats())).forEach(u=>{var _,g;if(u.type==="codec"&&this._decodeMap.set(u.id,u),u.type==="inbound-rtp"){let E=(u.mediaType||u.kind)===p.AUDIO;if(E){if(u.ssrc!==a.audio||!c.hasAudio)return;e.audio.packetsReceived=u.packetsReceived,e.audio.bytesReceived=u.bytesReceived,e.audio.packetsLost=u.packetsLost,u.insertedSamplesForDeceleration&&(e.audio.insertedSamplesForDeceleration=u.insertedSamplesForDeceleration),u.removedSamplesForAcceleration&&(e.audio.removedSamplesForAcceleration=u.removedSamplesForAcceleration),u.totalSamplesDuration&&(e.audio.totalSamplesDuration=u.totalSamplesDuration),u.totalSamplesReceived&&(e.audio.totalSamplesReceived=u.totalSamplesReceived),u.concealedSamples&&(e.audio.concealedSamples=u.concealedSamples),u.silentConcealedSamples&&(e.audio.silentConcealedSamples=u.silentConcealedSamples);let{remoteAudioTrack:A}=i;A.stat.packetsReceived=u.packetsReceived,A.stat.bytesReceived=u.bytesReceived,A.stat.packetsLost=u.packetsLost,e.audio.p2pDelay=A.stat.end2EndDelay,e.hasAudio=!0}else{if(te&&u.bytesReceived===0)return;let A;u.ssrc===a.video&&c.hasVideo&&(e.video.packetsReceived=u.packetsReceived,e.video.bytesReceived=u.bytesReceived,e.video.packetsLost=u.packetsLost,e.video.framesReceived=u.framesReceived,e.video.framesDecoded=u.framesDecoded,e.video.fpsDecoded=u.framesPerSecond,e.hasVideo=!0,i.videoCodec=Ht[(_=this._decodeMap.get(u.codecId))==null?void 0:_.mimeType.split("/")[1]]||"h264",e.video.codec=i.videoCodec,A=i.remoteVideoTrack,c.hasSmall&&l.smallVideo&&(e.isSmallSubscribed=!0),u.decoderImplementation&&(!this._prevDecoderImplementationMap.has(e.userId)||this._prevDecoderImplementationMap.get(e.userId)!==u.decoderImplementation)&&(this._log.info(`${e.userId} decoderImplementation change to ${u.decoderImplementation}(${i.videoCodec}) HWDecoder: ${u.powerEfficientDecoder}`),S.emit("262",{userId:this.room.userId,remoteUserId:e.userId,prevImplementation:this._prevDecoderImplementationMap.get(e.userId),implementation:u.decoderImplementation,codec:i.videoCodec,isHWCodec:u.powerEfficientDecoder}),this._prevDecoderImplementationMap.set(e.userId,u.decoderImplementation))),u.ssrc===a.auxiliary&&c.hasAuxiliary&&(e.auxiliary.packetsReceived=u.packetsReceived,e.auxiliary.bytesReceived=u.bytesReceived,e.auxiliary.packetsLost=u.packetsLost,e.auxiliary.framesReceived=u.framesReceived,e.auxiliary.framesDecoded=u.framesDecoded,e.auxiliary.fpsDecoded=u.framesPerSecond,A=i.remoteAuxiliaryTrack,e.auxiliary.p2pDelay=A.stat.end2EndDelay,e.hasAuxiliary=!0,e.video.codec=((g=this._decodeMap.get(u.codecId))==null?void 0:g.mimeType.split("/")[1].toLowerCase())||"h264"),A&&(A.stat.packetsReceived=u.packetsReceived,A.stat.bytesReceived=u.bytesReceived,A.stat.packetsLost=u.packetsLost,A.stat.framesReceived=u.framesReceived,A.stat.framesDecoded=u.framesDecoded,u.jitterBufferDelay&&(A.stat.jitterBufferDelay=Math.floor(u.jitterBufferDelay/u.jitterBufferEmittedCount*1e3)),e.video.p2pDelay=A.stat.end2EndDelay)}u.jitterBufferDelay&&(E?(e.audio.totalJitter=u.jitterBufferDelay,e.audio.totalJitterCount=u.jitterBufferEmittedCount,e.audio.estimatedPlayoutTimestamp=u.estimatedPlayoutTimestamp):u.ssrc===a.video&&c.hasVideo?(e.video.totalJitter=u.jitterBufferDelay,e.video.totalJitterCount=u.jitterBufferEmittedCount,e.video.estimatedPlayoutTimestamp=u.estimatedPlayoutTimestamp):u.ssrc===a.auxiliary&&c.hasAuxiliary&&(e.auxiliary.totalJitter=u.jitterBufferDelay,e.auxiliary.totalJitterCount=u.jitterBufferEmittedCount))}else u.type==="candidate-pair"&&Rr(u)&&(this.totalBytesReceived=u.bytesReceived,Q(u.currentRoundTripTime)&&(e.rtt=Math.floor(u.currentRoundTripTime*1e3)));T(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)),!T(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),T((r=i.remoteVideoTrack.player.stat)==null?void 0:r.fps)||(e.video.fpsRender=i.remoteVideoTrack.player.stat.fps),T((s=i.remoteAuxiliaryTrack.player.stat)==null?void 0:s.fps)||(e.auxiliary.fpsRender=i.remoteAuxiliaryTrack.player.stat.fps);let m=(e.audio.estimatedPlayoutTimestamp||0)-(e.video.estimatedPlayoutTimestamp||0);Math.abs(m)>150&&this._log.warn("av sync delay",m)}catch(a){this._log.warn(`failed to getStats on receiver connection ${a}`)}return e.rtt===0&&(e.rtt=((n=this.room.networkQuality)==null?void 0:n.uplinkRTT)||0),e})}getStats(i,e){return f(this,null,function*(){let t={},r,s=[];if(this.room.singlePC){let n=this.room.singlePC.getPeerConnection();if(!n)return{senderStats:t,receiverStats:s};let a=V(),c=yield n.getStats(),l=V();l-a>2e3&&this._log.warn(`getStats cost ${l-a}ms`);let h=[],m=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source","codec","media-playout"]);c.forEach(u=>m.has(u.type)&&h.push(u)),this._spcStats=h}i&&(t=yield this.getSenderStats(i));for(let[n,a]of e){let c=yield this.getReceiverStats(a);s.push(c)}return e.size&&(r=this.getMediaPlayoutStats(this._spcStats)),{senderStats:t,receiverStats:s,mediaPlayoutStats:r}})}getDifferenceValue(i,e){if(_i(i))return e;let t=e-i;return t<0?0:t}prepareReport({stats:i,report:e,freezeMap:t,uplinkConnection:r}){var u,_,g,E,A,k,se,w,Ze;if(!_i(i.senderStats)){let N={uint32_audio_level:i.senderStats.audio.audioLevel*Dt,uint32_audio_energy:(i.senderStats.audio.totalAudioEnergy||0)*1e6,uint32_audio_codec_bitrate:i.senderStats.audio.bytesSent};i.senderStats.audio.micAudioLevel&&(N.uint32_mic_audio_level=i.senderStats.audio.micAudioLevel*Dt),T(i.senderStats.audio.audioCaptureEnergyAfter3a)||(N.uint32_audio_capture_energy_after3a=i.senderStats.audio.audioCaptureEnergyAfter3a*Dt),i.senderStats.audio.totalSamplesDuration&&(e.msg_device_info.uint32_audio_capture_cost=i.senderStats.audio.totalSamplesDuration);let y=[];if(i.senderStats.video.bytesSent){let ge={uint32_video_stream_type:2,uint32_video_codec_fps:i.senderStats.video.framesSent,uint32_video_capture_fps:i.senderStats.video.fpsCapture,uint32_video_width:i.senderStats.video.frameWidth,uint32_video_height:i.senderStats.video.frameHeight,uint32_video_codec_bitrate:i.senderStats.video.bytesSent,uint32_video_enc_fps:i.senderStats.video.framesEncoded,uint32_key_frame_count:i.senderStats.video.keyFramesEncoded,uint32_nack_count:i.senderStats.video.nackCount,uint32_pli_count:i.senderStats.video.pliCount,uint32_encode_cost:(i.senderStats.video.totalEncodeTime||0)*1e3,uint32_send_packet_cost:(i.senderStats.video.totalPacketSendDelay||0)*1e3,uint32_video_arq_packets:i.senderStats.video.retransmittedPacketsSent};y.push(ge)}if(i.senderStats.small.bytesSent){let ge={uint32_video_stream_type:3,uint32_video_codec_fps:i.senderStats.small.framesSent||0,uint32_video_capture_fps:i.senderStats.small.fpsCapture||0,uint32_video_width:i.senderStats.small.frameWidth||0,uint32_video_height:i.senderStats.small.frameHeight||0,uint32_video_codec_bitrate:i.senderStats.small.bytesSent,uint32_video_enc_fps:i.senderStats.small.framesEncoded||0,uint32_key_frame_count:i.senderStats.small.keyFramesEncoded,uint32_nack_count:i.senderStats.small.nackCount,uint32_pli_count:i.senderStats.small.pliCount,uint32_encode_cost:(i.senderStats.small.totalEncodeTime||0)*1e3,uint32_send_packet_cost:(i.senderStats.small.totalPacketSendDelay||0)*1e3,uint32_video_arq_packets:i.senderStats.small.retransmittedPacketsSent};y.push(ge)}if(i.senderStats.auxiliary.bytesSent){let ge={uint32_video_stream_type:7,uint32_video_codec_fps:i.senderStats.auxiliary.framesSent||0,uint32_video_capture_fps:i.senderStats.auxiliary.fpsCapture||0,uint32_video_width:i.senderStats.auxiliary.frameWidth||0,uint32_video_height:i.senderStats.auxiliary.frameHeight||0,uint32_video_codec_bitrate:i.senderStats.auxiliary.bytesSent,uint32_video_enc_fps:i.senderStats.auxiliary.framesEncoded||0,uint32_key_frame_count:i.senderStats.auxiliary.keyFramesEncoded,uint32_nack_count:i.senderStats.auxiliary.nackCount,uint32_pli_count:i.senderStats.auxiliary.pliCount,uint32_encode_cost:(i.senderStats.auxiliary.totalEncodeTime||0)*1e3,uint32_send_packet_cost:(i.senderStats.auxiliary.totalPacketSendDelay||0)*1e3,uint32_video_arq_packets:i.senderStats.auxiliary.retransmittedPacketsSent};y.push(ge)}let q={uint32_bitrate:0,uint32_lost:0,uint32_rtt:i.senderStats.rtt};e.msg_up_stream_info={msg_audio_status:N,msg_video_status:y,msg_network_status:q}}let{statInterval:s}=this;e.msg_down_stream_info=[],i.receiverStats.forEach(N=>{let y={msg_user_info:{str_identifier:N.userId,uint64_tinyid:N.tinyId},msg_network_status:{uint32_rtt:N.rtt,uint32_bitrate:0,uint32_lost:0},msg_audio_status:{},msg_video_status:[]};if(N.hasAudio){let q={uint32_audio_p2p_delay:N.audio.p2pDelay,uint32_audio_cache_ms:N.audio.totalJitter,uint32_audio_cache_ms_count:N.audio.totalJitterCount,uint32_audio_codec_bitrate:N.audio.bytesReceived,uint32_audio_total_bitrate:N.audio.bytesReceived,uint32_audio_level:N.audio.audioLevel*1e8,uint32_audio_energy:N.audio.totalAudioEnergy*1e6,uint32_audio_receive:N.audio.packetsReceived,uint32_audio_origin_lost:N.audio.packetsLost};y.msg_audio_status=q}if(N.hasVideo){let q=t.get(`${N.userId}_${ol}`),ge=q?q.duration:0,de={uint32_video_stream_type:N.isSmallSubscribed?3:2,uint32_video_receive_fps:N.video.framesReceived,uint32_video_width:N.video.frameWidth,uint32_video_height:N.video.frameHeight,uint32_video_codec_bitrate:N.video.bytesReceived,uint32_video_receive:N.video.packetsReceived,uint32_video_origin_lost:N.video.packetsLost,uint32_video_block_time:ge,uint32_video_dec_fps:N.video.framesDecoded,uint32_video_codec_fps:N.video.fpsRender,uint32_video_cache_ms:N.video.totalJitter,uint32_video_cache_ms_count:N.video.totalJitterCount,uint32_video_p2p_delay:N.video.p2pDelay,uint32_video_codec:N.video.codec};y.msg_video_status.push(de)}if(N.hasAuxiliary){let q=t.get(`${N.userId}_${sl}`),ge=q?q.duration:0,de={uint32_video_stream_type:7,uint32_video_receive_fps:N.auxiliary.framesReceived,uint32_video_width:N.auxiliary.frameWidth,uint32_video_height:N.auxiliary.frameHeight,uint32_video_codec_bitrate:N.auxiliary.bytesReceived,uint32_video_receive:N.auxiliary.packetsReceived+N.auxiliary.packetsLost,uint32_video_origin_lost:N.auxiliary.packetsLost,uint32_video_block_time:ge,uint32_video_dec_fps:N.auxiliary.framesDecoded,uint32_video_codec_fps:N.video.fpsRender,uint32_video_cache_ms:N.auxiliary.totalJitter,uint32_video_cache_ms_count:N.auxiliary.totalJitterCount,uint32_video_p2p_delay:N.auxiliary.p2pDelay,uint32_video_codec:N.video.codec};y.msg_video_status.push(de)}e.msg_down_stream_info.push(y)}),i.mediaPlayoutStats&&!_i(i.mediaPlayoutStats)&&(i.mediaPlayoutStats.synthesizedSamplesDuration*=1e3,i.mediaPlayoutStats.totalSamplesDuration*=1e3);let n=this._prevReport,a=this._prevStats;if(this._prevReport=JSON.parse(JSON.stringify(e)),this._prevStats=JSON.parse(JSON.stringify(i)),e.msg_up_stream_info.msg_audio_status&&n.msg_up_stream_info.msg_audio_status){let N=n.msg_up_stream_info.msg_audio_status,y=e.msg_up_stream_info.msg_audio_status;if(N.uint32_audio_codec_bitrate===0)y.uint32_audio_codec_bitrate=0;else{let q=this.getDifferenceValue(N.uint32_audio_codec_bitrate,y.uint32_audio_codec_bitrate);y.uint32_audio_codec_bitrate=Math.round(q*8/s),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=y.uint32_audio_codec_bitrate}(u=n.msg_device_info)!=null&&u.uint32_audio_capture_cost?(e.msg_device_info.uint32_audio_capture_cost=2*Math.floor(this.getDifferenceValue(n.msg_device_info.uint32_audio_capture_cost,e.msg_device_info.uint32_audio_capture_cost)*1e3/s),e.msg_device_info.uint32_audio_capture_cost>0&&((g=r==null?void 0:r.localMainAudioTrack)==null||g.updateAfter3aSilenceStartTime((_=i.senderStats.audio.audioCaptureEnergyAfter3a)!=null?_:i.senderStats.audio.micAudioLevel))):delete e.msg_device_info.uint32_audio_capture_cost}let c=n.msg_up_stream_info.msg_video_status;e.msg_up_stream_info.msg_video_status.forEach(N=>{let y=c.find(Ut=>Ut.uint32_video_stream_type===N.uint32_video_stream_type);if(!y||y.uint32_video_codec_bitrate===0){N.uint32_video_codec_bitrate=0,N.uint32_video_enc_fps=0,N.uint32_video_codec_fps=0;return}let q=0,ge=0,de=0;y&&N.uint32_video_codec_bitrate>=y.uint32_video_codec_bitrate&&(q=y.uint32_video_codec_bitrate,ge=y.uint32_video_enc_fps,de=y.uint32_video_codec_fps);let Me=this.getDifferenceValue(q,N.uint32_video_codec_bitrate);N.uint32_video_codec_bitrate=Math.round(Me*8/s),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=N.uint32_video_codec_bitrate,N.uint32_video_enc_fps=Math.round(this.getDifferenceValue(ge,N.uint32_video_enc_fps)/s),N.uint32_video_codec_fps=Math.round(this.getDifferenceValue(de,N.uint32_video_codec_fps)/s),y.uint32_video_width===0&&y.uint32_video_height===0&&y.uint32_video_codec_fps===0&&(N.uint32_video_codec_fps=N.uint32_video_enc_fps),T(y.uint32_key_frame_count)||(N.uint32_key_frame_count=Math.round(this.getDifferenceValue(y.uint32_key_frame_count,N.uint32_key_frame_count))),T(y.uint32_nack_count)||(N.uint32_nack_count=Math.round(this.getDifferenceValue(y.uint32_nack_count,N.uint32_nack_count))),T(y.uint32_pli_count)||(N.uint32_pli_count=Math.round(this.getDifferenceValue(y.uint32_pli_count,N.uint32_pli_count))),T(y.uint32_video_arq_packets)||(N.uint32_video_arq_packets=Math.round(this.getDifferenceValue(y.uint32_video_arq_packets,N.uint32_video_arq_packets))),T(y.uint32_encode_cost)||(N.uint32_encode_cost=Math.round(this.getDifferenceValue(y.uint32_encode_cost,N.uint32_encode_cost)/s)),T(y.uint32_send_packet_cost)||(N.uint32_send_packet_cost=Math.round(this.getDifferenceValue(y.uint32_send_packet_cost,N.uint32_send_packet_cost)/s))});let h=n.msg_down_stream_info;e.msg_down_stream_info=e.msg_down_stream_info.filter(N=>h.find(y=>y.msg_user_info.uint64_tinyid===N.msg_user_info.uint64_tinyid));let m=e.msg_down_stream_info;if(m.forEach(N=>{let y=h.find(q=>q.msg_user_info.uint64_tinyid===N.msg_user_info.uint64_tinyid);if(!_i(N.msg_audio_status)&&!_i(y.msg_audio_status)){let q=N.msg_audio_status,ge=y.msg_audio_status,de=this.getDifferenceValue(ge.uint32_audio_cache_ms_count,q.uint32_audio_cache_ms_count);delete q.uint32_audio_cache_ms_count,q.uint32_audio_cache_ms=Math.floor(1e3*this.getDifferenceValue(ge.uint32_audio_cache_ms,q.uint32_audio_cache_ms)/de)||0;let Me=this.room.remotePublishedUserMap.get(N.msg_user_info.str_identifier);Me&&(Me.remoteAudioTrack.stat.jitterBufferDelay=q.uint32_audio_cache_ms),q.uint32_audio_origin_lost=this.getDifferenceValue(ge.uint32_audio_origin_lost,q.uint32_audio_origin_lost),q.uint32_audio_receive=this.getDifferenceValue(ge.uint32_audio_receive,q.uint32_audio_receive),q.uint32_audio_receive+=q.uint32_audio_origin_lost;let Ut=this.getDifferenceValue(ge.uint32_audio_codec_bitrate,q.uint32_audio_codec_bitrate);q.uint32_audio_codec_bitrate=Math.round(Ut*8/s),q.uint32_audio_total_bitrate=Math.round(Ut*8/s)}else N.msg_audio_status={};if(N.msg_video_status&&y.msg_video_status){let q=y.msg_video_status;N.msg_video_status=N.msg_video_status.filter(de=>q.find(Me=>Me.uint32_video_stream_type===de.uint32_video_stream_type)),N.msg_video_status.forEach(de=>{let Me=q.find(tg=>tg.uint32_video_stream_type===de.uint32_video_stream_type),Ut=Me.uint32_video_receive,Do=Me.uint32_video_origin_lost,qd=Me.uint32_video_codec_bitrate,Jd=Me.uint32_video_receive_fps,Z_=Me.uint32_video_dec_fps;de.uint32_video_origin_lost=this.getDifferenceValue(Do,de.uint32_video_origin_lost),de.uint32_video_receive=this.getDifferenceValue(Ut,de.uint32_video_receive)+de.uint32_video_origin_lost;let K_=this.getDifferenceValue(qd,de.uint32_video_codec_bitrate);de.uint32_video_codec_bitrate=Math.round(K_*8/s);let eg=this.getDifferenceValue(Jd,de.uint32_video_receive_fps);de.uint32_video_receive_fps=Math.round(eg/s),de.uint32_video_dec_fps=Math.round(this.getDifferenceValue(Z_,de.uint32_video_dec_fps)/s);let H=this.getDifferenceValue(Me.uint32_video_cache_ms_count,de.uint32_video_cache_ms_count);delete de.uint32_video_cache_ms_count,de.uint32_video_cache_ms=Math.floor(1e3*this.getDifferenceValue(Me.uint32_video_cache_ms,de.uint32_video_cache_ms)/H)||0})}}),!T((E=a==null?void 0:a.mediaPlayoutStats)==null?void 0:E.totalSamplesDuration)&&!T((A=i.mediaPlayoutStats)==null?void 0:A.totalSamplesDuration)){let N=2*Math.floor(this.getDifferenceValue((k=a==null?void 0:a.mediaPlayoutStats)==null?void 0:k.synthesizedSamplesDuration,(se=i.mediaPlayoutStats)==null?void 0:se.synthesizedSamplesDuration)/s),y=2*Math.floor(this.getDifferenceValue((w=a==null?void 0:a.mediaPlayoutStats)==null?void 0:w.totalSamplesDuration,(Ze=i.mediaPlayoutStats)==null?void 0:Ze.totalSamplesDuration)/s);e.msg_device_info.uint32_audio_play_cost=y-N}return a&&i.receiverStats.forEach(N=>{if(N.audio.concealedSamples&&N.audio.totalSamplesReceived){let y=a.receiverStats.find(q=>q.userId===N.userId);if(y&&y.audio.concealedSamples&&y.audio.totalSamplesReceived){let q=(N.audio.silentConcealedSamples||0)-(y.audio.silentConcealedSamples||0),ge=N.audio.concealedSamples-y.audio.concealedSamples,de=N.audio.totalSamplesReceived-y.audio.totalSamplesReceived,Me=Math.floor((ge-q)/de*1e3*s);if(Me>s*1e3/5){let Ut=m.find(Do=>Do.msg_user_info.str_identifier===N.userId);Ut&&(Ut.msg_audio_status.uint32_audio_block_time=Me)}}}}),e.msg_down_stream_info.forEach(N=>{N.msg_video_status.forEach(y=>{y.uint32_video_codec_bitrate===0&&y.uint32_video_receive_fps===0&&(y.uint32_video_width=0,y.uint32_video_height=0)})}),e}getStatsReport(r){return f(this,arguments,function*({uplinkConnection:i,downlinkConnections:e,freezeMap:t}){let s={msg_device_info:{},msg_up_stream_info:{msg_audio_status:{uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_capture_energy_after3a:0},msg_video_status:[],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}},msg_down_stream_info:[{msg_user_info:{str_identifier:"",uint64_tinyid:0},msg_audio_status:{uint32_audio_cache_ms:0,uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_total_bitrate:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_final_lost:0},msg_video_status:[{uint32_video_cache_ms:0,uint32_video_stream_type:0,uint32_video_receive_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_codec_bitrate:0,uint32_video_receive:0,uint32_video_origin_lost:0,uint32_video_block_time:0,uint32_video_dec_fps:0}],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}}]},n=yield this.getStats(i,e);return JSON.stringify(this._prevReport)==="{}"&&(this._prevReport=JSON.parse(JSON.stringify(s))),this.prepareReport({stats:n,report:s,freezeMap:t,uplinkConnection:i}),this._prevReportTime=Date.now(),s})}getMediaPlayoutStats(i){let e;if(Ae(i)){for(let t of i)if(t.type==="media-playout"){let{synthesizedSamplesDuration:r,totalSamplesDuration:s}=t;e={synthesizedSamplesDuration:r,totalSamplesDuration:s};break}return e}}reset(){var i;this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map,(i=this.room.localMainVideoTrack)!=null&&i.stat&&(this.room.localMainVideoTrack.stat.framesCaptured=0)}};var b_=Je(at());function R_(o){let i={totalCost:0,local:0,redirect:0,httpCache:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let e=performance.getEntriesByType("resource").reverse();for(let t of e)if(t.name===o){let r=Math.round(t.duration),s=Math.max(Math.round(t.domainLookupStart-t.startTime),0),n=t.redirectStart>0?Math.max(Math.round(t.redirectEnd-t.redirectStart),0):0,a=t.fetchStart>0?Math.max(Math.round(t.domainLookupStart-t.fetchStart),0):0,c=Math.round(t.domainLookupEnd-t.domainLookupStart),l=Math.round(t.requestStart-t.secureConnectionStart),h=Math.round(t.secureConnectionStart-t.connectStart),m=Math.round(t.responseStart-t.requestStart),u=Math.round(t.responseEnd-(t.responseStart||t.startTime));i=L(O({},i),{totalCost:r,local:s,redirect:n,httpCache:a,dns:c,tcp:h,tls:l,request:m,response:u});break}}catch(e){}return i}function y_(o){return new Promise(i=>f(this,null,function*(){let e=setTimeout(()=>{i({totalCost:1e4,local:0,dns:0,tcp:0,tls:0,request:0,response:0})},1e4),t=Date.now(),r=`https://${o}/?t=${t}`;try{yield fetch(r)}catch(n){}clearTimeout(e);let s=R_(r);s.totalCost===0&&(s.totalCost=Date.now()-t),i(s)}))}var gI=700,yo=class yo extends b_.default{constructor({signalChannel:e,room:t}){super();d(this,"_room");d(this,"_signalChannel");d(this,"_log");d(this,"uplinkRTT",0);d(this,"uplinkLoss",0);d(this,"downlinkRTT",0);d(this,"downlinkLoss",0);d(this,"pingResults",{});d(this,"_downlinkPrevStatMap",new Map);d(this,"_downlinkLossAndRTTMap",new Map);d(this,"_interval",-1);d(this,"_uplinkNetworkQuality",0);d(this,"_downlinkNetworkQuality",0);this._room=t,this._signalChannel=e,this._log=R.createLogger({parent:t.getLogger(),id:"q",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this.initialize()}get uplinkNetworkQuality(){return this._uplinkNetworkQuality}set uplinkNetworkQuality(e){e!==this._uplinkNetworkQuality&&this._log.info(`uplink ${this.uplinkNetworkQuality} -> ${e}, rtt: ${this.uplinkRTT}, loss: ${this.uplinkLoss} ws-rtt: ${this._signalChannel.rtt}`),this._uplinkNetworkQuality=e}get downlinkNetworkQuality(){return this._downlinkNetworkQuality}set downlinkNetworkQuality(e){if(e!==this._downlinkNetworkQuality){let{rtt:t,loss:r}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._log.info(`downlink ${this.downlinkNetworkQuality} -> ${e}, rtt: ${t}, loss: ${r} ws-rtt: ${this._signalChannel.rtt}`)}this._downlinkNetworkQuality=e}initialize(){this._signalChannel.on(W.UPLINK_NETWORK_STATS,e=>{this.handleUplinkNetworkQuality(e)}),this._signalChannel.on(Ie.CONNECTION_STATE_CHANGED,this.handleSignalConnectionStateChange.bind(this)),this.start()}handleUplinkNetworkQuality(e){var c,l;if(e.data.code!==0)return;let t=e.data.data;if(t.delay&&this.updateDelay(t.delay),this._room.signalChannel&&t.wsRtt&&(this._room.signalChannel.rtt=t.wsRtt),!this._room.uplinkConnection){this.uplinkNetworkQuality=0,this.uplinkLoss=0,this.uplinkRTT=0;return}let r=(l=(c=this._room)==null?void 0:c.uplinkConnection)==null?void 0:l.getPeerConnection();if(r&&this.isPeerConnectionDisconnected(r)){this.uplinkNetworkQuality=6,this.uplinkLoss=0,this.uplinkRTT=0;return}let s=t.expectAudPkg+t.expectVidPkg,n=t.recvAudPkg+t.recvVidPkg,a=s-n;s===0&&n===0||(a<=0?this.uplinkLoss=0:this.uplinkLoss=Math.round(a/s*100),this.uplinkRTT=t.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this.uplinkLoss,this.uplinkRTT))}handleDownlinkNetworkQuality(){return f(this,null,function*(){if(this._room.remotePublishedUserMap.size===0){this.downlinkNetworkQuality=0;return}let e=[...this._room.remotePublishedUserMap.values()],t=e.filter(a=>{var c;return((c=a.getPeerConnection())==null?void 0:c.connectionState)===ye.CONNECTED});if(e.filter(a=>this.isPeerConnectionDisconnected(a.getPeerConnection())).length===e.length){this.downlinkNetworkQuality=6;return}for(let a=0;a<t.length;a++){let c=t[a].getPeerConnection();if(!c)return;let{rtt:l,totalPacketsLost:h,totalPacketsReceived:m}=yield this.getStat(c);if(!this._downlinkPrevStatMap.has(c)){this._downlinkPrevStatMap.set(c,{totalPacketsLost:h,totalPacketsReceived:m});continue}let u=0,_=this._downlinkPrevStatMap.get(c),g=h-_.totalPacketsLost,E=m-_.totalPacketsReceived;g<=0||E<0?u=0:u=Math.round(g/(g+E)*100),this._downlinkPrevStatMap.set(c,{totalPacketsLost:h,totalPacketsReceived:m}),this._downlinkLossAndRTTMap.set(c,{rtt:l,loss:u,userId:t[a].getUserId(),audioDelay:t[a].remoteAudioTrack.stat.end2EndDelay,videoDelay:t[a].remoteVideoTrack.stat.end2EndDelay})}if([...this._downlinkPrevStatMap.keys()].forEach(a=>{this.isPeerConnectionDisconnected(a)&&(this._downlinkPrevStatMap.delete(a),this._downlinkLossAndRTTMap.delete(a))}),this._downlinkLossAndRTTMap.size===0){this.downlinkRTT=0,this.downlinkLoss=0,this.downlinkNetworkQuality=0;return}let{rtt:s,loss:n}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this.downlinkRTT=s,this.downlinkLoss=n,this.downlinkNetworkQuality=this.getNetworkQuality(n,s)})}getStat(e){return f(this,null,function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!oo())return t;let r=e.getReceivers();try{for(let s=0;s<r.length;s++)(yield r[s].getStats()).forEach(c=>{c.type==="candidate-pair"&&Q(c.currentRoundTripTime)&&(t.rtt=Math.round(c.currentRoundTripTime*1e3)),c.type==="inbound-rtp"&&(c.mediaType===p.AUDIO||c.mediaType===p.VIDEO)&&(t.totalPacketsLost+=c.packetsLost,t.totalPacketsReceived+=c.packetsReceived)});return t.rtt===0&&(t.rtt=this.uplinkRTT),t}catch(s){return t}})}getAverageLossAndRTT(e){let t={rtt:0,loss:0};return Array.isArray(e)&&e.length>0&&(e.forEach(r=>{t.rtt+=r.rtt,t.loss+=r.loss}),Object.keys(t).forEach(r=>{t[r]=Math.round(t[r]/e.length)})),t}getNetworkQuality(e,t){return e>50||t>500?5:e>30||t>350?4:e>20||t>200?3:e>10||t>100?2:e>=0||t>=0?1:0}handleSignalConnectionStateChange(e){e.state==="DISCONNECTED"?(this.uplinkRTT=0,this.uplinkLoss=0,this.uplinkNetworkQuality=6):e.state==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=5)}handleUplinkConnectionStateChange({state:e}){e==="DISCONNECTED"?(this.uplinkLoss=0,this.uplinkRTT=0,this.uplinkNetworkQuality=6):e==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=5)}isPeerConnectionDisconnected(e){return!!(e&&(e.connectionState===ye.DISCONNECTED||e.connectionState===ye.FAILED||e.connectionState===ye.CLOSED))}setUplinkConnection(e){this._room.uplinkConnection=e,this._room.uplinkConnection?this._room.uplinkConnection.on("connection-state-changed",this.handleUplinkConnectionStateChange.bind(this)):(this.uplinkNetworkQuality=0,this.uplinkRTT=0,this.uplinkLoss=0)}start(){if(this._interval!==-1){this._log.info("network quality calculating is already started");return}this._log.debug("start network quality calculating"),this._interval=oe.run("ric",()=>{var n;this.handleDownlinkNetworkQuality();let e=[...this._downlinkLossAndRTTMap.values()];S.emit(C.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this.uplinkRTT,loss:this.uplinkLoss},downlinks:e});let t=(n=this._room.scheduleResult.config)==null?void 0:n.pingDomainInfo,r={uplinkNetworkQuality:this.uplinkNetworkQuality,downlinkNetworkQuality:this.downlinkNetworkQuality,uplinkRTT:this.uplinkRTT,uplinkLoss:this.uplinkLoss,downlinkRTT:this.downlinkRTT,downlinkLoss:this.downlinkLoss};t&&(r=L(O({},r),{pingResults:this.uplinkRTT>t.rttThreshold||this.downlinkRTT>t.rttThreshold?this.pingResults:{}})),this.emit(yo.EVENT_NETWORK_QUALITY,r);let s=Date.now();if(t&&(this.uplinkRTT>t.rttThreshold||this.downlinkRTT>t.rttThreshold)&&s-yo.lastPingTime>t.interval*1e3){yo.lastPingTime=Date.now();let a=t.domain.map(c=>y_(c).then(l=>({domain:c,cost:l.totalCost})));Promise.all(a).then(c=>{this.pingResults.isPoorNetwork=c.some(l=>l.cost>gI),this.pingResults.timestamp=s,this.pingResults.data=c,c.forEach(l=>{v.addSuccessEvent({key:521718,cost:l.cost})}),this._log.warn(`All ping results: ${JSON.stringify(c)}`)}).catch(c=>{this._log.warn(`Error during pinging domains: ${c}`)})}},{delay:2e3})}stop(){this._log.debug("stopped"),this._interval!==-1&&(oe.clearTask(this._interval),this._interval=-1),this._downlinkLossAndRTTMap.clear(),this._downlinkPrevStatMap.clear()}updateDelay(e){let{tinyIdToUserIdMap:t}=this._room;e.forEach(({srcTinyId:r,videoDelay:s,audioDelay:n})=>{let a=t.get(r);if(a){let c=this._room.remotePublishedUserMap.get(a);c==null||c.setDelay({videoDelay:s,audioDelay:n})}})}};d(yo,"EVENT_NETWORK_QUALITY","0"),d(yo,"lastPingTime",0);var ks=yo;function TI({fn:o,context:i}){return function(...e){try{let t=o.apply(i,e);return Er(t)?t.catch(r=>R.error(`${o.name}() error observed ${r}`)):t}catch(t){R.error(`${o.name}() error observed ${t}`)}}}var wd=class{constructor(i){d(this,"_frameWorkType");d(this,"_component");d(this,"_language");d(this,"connectionType");d(this,"_room");d(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,reportToken:void 0});d(this,"_keyPrefix");d(this,"_log");d(this,"_intervalId");d(this,"_firstPublishedUserList");d(this,"_networkQuality");d(this,"_basicInfo");d(this,"_pathJoinRoom");d(this,"_pathLeaveRoom");d(this,"_pathMainVideoMap");d(this,"_pathMainAudioMap");d(this,"_pathAuxiliaryMap");d(this,"_remoteStreamStatMap");d(this,"_localStreamStat");d(this,"_eventMap",new Map);d(this,"_captureCostSum",0);d(this,"_captureCostCount",0);d(this,"isDestroyed",!1);this._frameWorkType=i.frameWorkType||30,this._component=i.component||0,this.connectionType=i.connectionType||1,this._language=i.language||0,this._room=i.room,this._keyPrefix="key_point",this._log=R.createLogger({parent:this._room.getLogger(),id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(e=>{e.startsWith("handle")&&me(this[e])&&(this[e]=TI({fn:this[e],context:this}))}),this.initData(),this.installEvents()}initData(){this._firstPublishedUserList=[],this._networkQuality={totalUplinkRTT:0,totalUplinkLoss:0,count:0,totalDownlinkRTTAndLossMap:new Map},this._basicInfo={string_sdk_version:$e,uint32_os_type:15,string_device_name:"",string_http_user_agent:navigator.userAgent,string_os_version:"",uint32_avg_rtt:0,uint32_avg_up_loss:0,uint32_scene:this._room.scene==="live"?1:0,uint32_joining_duration:0,uint32_networkType:0,uint32_framework:this._frameWorkType,uint32_component:this._component,uint32_connection_type:this.connectionType,uint32_caller_coding_language:this._language,string_domain:location.hostname},this._pathJoinRoom={uint64_start_time:0,uint64_send_request_acc_ip_cmd_start_time:0,uint64_send_request_acc_ip_cmd_end_time:0,uint64_send_request_enter_room_cmd_start_time:0,uint64_send_request_enter_room_cmd_end_time:0,uint64_send_first_video_frame_time:0,uint64_recv_userlist_time:0,uint64_end_time:0,int32_send_request_acc_ip_cmd_ret:0,int32_send_request_enter_room_cmd_ret:0,int32_end_ret:0},this._pathLeaveRoom={uint64_start_time:0,uint64_send_request_exit_room_cmd_start_time:0,uint64_send_request_exit_room_cmd_end_time:0,uint64_end_time:0,int32_send_request_exit_room_cmd_ret:0,int32_end_ret:0},this._localStreamStat={totalVideoBitrate:0,totalVideoFPS:0,totalVideoHeight:0,totalVideoWidth:0,totalAudioLevel:0,videoCount:0,audioLevelCount:0,publishStartTime:0,statsToReport:{uint32_audio_capture_db:0,uint32_video_big_capture_fps:0,uint32_video_big_bitrate:0,uint32_video_big_resolution:0,uint32_audio_capture_thread_health_zero_cnt:0,uint32_after3a_silence_duration:0}},this._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,Yr().then(()=>{this._basicInfo.string_os_version=ai(),this._basicInfo.string_device_name=ni()||this._basicInfo.string_os_version})}addEvent(i,e){return this._eventMap.set(i,e),S.on(i,e),this}installEvents(){this.handleUnload=this.handleUnload.bind(this),window.addEventListener("pagehide",this.handleUnload),this._room.once("banned",()=>this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})),this.addEvent(C.JOIN_START,this.handleJoinStart).addEvent(C.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(C.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(C.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(C.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(C.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(C.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(C.JOIN_FAILED,this.handleJoinFailed).addEvent(C.LEAVE_START,this.handleLeaveStart).addEvent(C.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(C.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(C.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(C.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(C.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(C.PUBLISH_START,this.handlePublishStart).addEvent(C.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(C.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(C.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(C.PLAY_TRACK_START,this.handlePlayStart).addEvent(C.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(C.PLAYER_STATE_CHANGED,({track:i,state:e,type:t})=>{!i.isRemote||!this.hitTest(i.room)||e==="PLAYING"&&(t===p.AUDIO?this.handleAudioPlaying(i):this.handleVideoPlaying(i))}).addEvent(C.SWITCH_ROOM_START,this.handleSwitchRoomStart).addEvent(C.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess).addEvent(C.SWITCH_ROOM_FAILED,this.handleSwitchRoomFailed).addEvent(C.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(C.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(C.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(C.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{if(!this.hitTest(i))return;let r=e.hasAudio||e.hasVideo||e.hasSmall,s=e.hasAuxiliary,n=t.hasAudio||t.hasVideo||t.hasSmall,a=t.hasAuxiliary;!r&&n&&this.handleRemoteStreamAdded(t.userId,"main"),!s&&a&&this.handleRemoteStreamAdded(t.userId,"auxiliary")}).addEvent(C.SINGLE_CONNECTION_STAT,({room:i,stat:e})=>{this.hitTest(i)&&(this._pathJoinRoom.int32_ice_cost=e.ice,this._pathJoinRoom.int32_dtls_cost=e.dtls,this._pathJoinRoom.int32_peer_connection_cost=e.peerConnection)})}uninstallEvents(){window.removeEventListener("pagehide",this.handleUnload),this._eventMap.forEach((i,e)=>S.off(e,i)),this._eventMap.clear()}destroy(){this.uninstallEvents(),oe.clearTask(this._intervalId),this._pathJoinRoom.uint64_start_time===0&&(this._room=null),this.isDestroyed=!0}handleUnload(){this._room.isJoined&&this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})}handleJoinStart(i){this.hitTest(i.room)&&(this._pathJoinRoom.uint64_start_time===0&&(this._pathJoinRoom.uint64_start_time=Date.now()),i.params&&(T(i.params.frameWorkType)||(this._frameWorkType=i.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),T(i.params.component)||(this._component=i.params.component,this._basicInfo.uint32_component=this._component),T(i.params.language)||(this._language=i.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleJoinScheduleSuccess({room:i,detailCost:e}){if(this.hitTest(i)&&e){let{totalCost:t,local:r,dns:s,tcp:n,tls:a,request:c,response:l}=e;this._pathJoinRoom.int32_schedule_cost=t,this._pathJoinRoom.int32_schedule_local=r,this._pathJoinRoom.int32_schedule_dns=s,this._pathJoinRoom.int32_schedule_tcp=n,this._pathJoinRoom.int32_schedule_tls=a,this._pathJoinRoom.int32_schedule_request=c,this._pathJoinRoom.int32_schedule_response=l}}handleSignalConnectionStart({room:i}){this.hitTest(i)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time=Date.now())}handleSignalConnectionEnd({room:i,error:e}){this.hitTest(i)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time=Date.now(),e&&(this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret=e instanceof D?Number(e.getExtraCode()||e.getCode()):I.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}handleJoinSendCMD(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now())}handleJoinReceivedCMDResponce(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=i.code,i.code!==0&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}handleJoinSuccess(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_end_time===0&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=i.room.getSignalInfo())}handleJoinFailed({room:i,error:e}){this.hitTest(i)&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret===0&&(this._pathJoinRoom.int32_end_ret=e.code||this._pathJoinRoom.int32_send_request_enter_room_cmd_ret||this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret),setTimeout(()=>{this.report()}))}handleReceivedPublishUserList(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_recv_userlist_time===0&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=i.publishedUserList||[])}handleSendFirstVideoFrame({room:i}){this.hitTest(i)&&this._pathJoinRoom.uint64_send_first_video_frame_time===0&&this._pathJoinRoom.uint64_start_time!==0&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now())}handleLeaveStart(i){this.hitTest(i.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(i){var e;if(this.hitTest(i.room)&&this._pathLeaveRoom.uint64_end_time===0){if(this._pathLeaveRoom.uint64_end_time=Date.now(),this._pathJoinRoom.uint64_end_time!==0){this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time;let t=(e=this._room.audioManager.localAudioTrack)==null?void 0:e.after3aSilenceStartTime;t&&(this._localStreamStat.statsToReport.uint32_after3a_silence_duration=V()-t)}else this._log.warn("pathJoinRoom endTime is 0");this.report()}}handleLeaveSendCMD(i){this.hitTest(i.room)&&(this._pathLeaveRoom.uint64_send_request_exit_room_cmd_start_time=Date.now(),this._pathLeaveRoom.uint64_send_request_exit_room_cmd_end_time=Date.now())}handleSwitchRoomStart(i){if(this.hitTest(i.room)){let e=Date.now();this.report().then(()=>{this._pathJoinRoom.uint64_start_time=e,this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=e})}}handleSwitchRoomSuccess({room:i}){if(this.hitTest(i)&&this._pathJoinRoom.uint64_end_time===0){let e=Date.now();this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=e,this._pathJoinRoom.uint64_end_time=e,this._pathJoinRoom.int32_end_ret}}handleSwitchRoomFailed({room:i,error:e}){if(this.hitTest(i)){let t=Date.now();this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=t,this._pathJoinRoom.uint64_end_time=t,e&&(this._pathJoinRoom.int32_end_ret=e instanceof D?Number(e.getExtraCode()||e.getCode()):I.UNKNOWN)}}handleRemoteStreamAdded(i,e){var r;let t=`${i}_${e}`;if(!this._remoteStreamStatMap.has(t)){let s={userId:i,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:L(O({},EI),{msg_user_info:new aa({userId:i,tinyId:(r=this._room.remotePublishedUserMap.get(i))==null?void 0:r.tinyId,role:20})})};s.statsToReport.uint32_stream_type=e==="main"?2:7,this._remoteStreamStatMap.set(t,s)}}handleSubscribeStart({room:i,remotePublishedUser:e,streamType:t,subscribeState:r}){if(!this.hitTest(i))return;let{userId:s,tinyId:n,role:a}=e,c=new aa({userId:s,tinyId:n,role:a==="anchor"?20:21}),l=Date.now(),h=`${s}_${t}`,m=this._remoteStreamStatMap.get(h);m&&m.subscribeStartTime===0&&(m.subscribeStartTime=l),t==="main"?(e.muteState.hasVideo&&(r.video||r.smallVideo)&&!this._pathMainVideoMap.has(h)&&this._pathMainVideoMap.set(h,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:s,sendSubscribeCMDTime:l}),e.muteState.hasAudio&&r.audio&&!this._pathMainAudioMap.has(h)&&this._pathMainAudioMap.set(h,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:s,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}`,s=this._remoteStreamStatMap.get(r);s&&s.subscribedTime===0&&(s.subscribedTime=Date.now())}}handlePlayStart({track:i}){if(!i.isRemote||!this.hitTest(i.room))return;let e=`${i.userId}_${i.streamType}`,t=this._remoteStreamStatMap.get(e);(t==null?void 0:t.playStreamTime)===0&&(t.playStreamTime=Date.now())}handleVideoLoadedData({track:i}){if(!i.isRemote||!this.hitTest(i.room))return;let e=`${i.userId}_${i.streamType}`,t=this._pathMainVideoMap.get(e);t&&t.statsToReport.uint64_combine_first_frame_time===0&&(t.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(i){let e=`${i.userId}_${i.streamType}`,t=Date.now(),r=this._pathMainVideoMap.get(e),s=this._remoteStreamStatMap.get(e);if(s){let{statsToReport:n}=s;if(!n.uint32_video_render_first&&i.streamType==="main"?this.hasVideoFlag(i.userId):this.hasAuxFlag(i.userId)){let a=t-this._pathJoinRoom.uint64_start_time;n.uint32_video_render_first=a,v.addNumber({key:516820,value:a})}}(r==null?void 0:r.statsToReport.uint64_render_first_frame_time)===0&&(r.statsToReport.uint64_render_first_frame_time=t)}handleAudioPlaying(i){let e=`${i.userId}_${i.streamType}`,t=this._pathMainAudioMap.get(e);t&&t.statsToReport.uint64_play_first_frame_time===0&&(t.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(i){this.hitTest(i.room)&&(this._networkQuality.totalUplinkLoss+=i.uplink.loss,this._networkQuality.totalUplinkRTT+=i.uplink.rtt,this._networkQuality.count++,i.downlinks.forEach(({rtt:e,loss:t,userId:r,videoDelay:s,audioDelay:n})=>{let a=this._networkQuality.totalDownlinkRTTAndLossMap.get(r);if(a)a.totalRTT+=e,a.totalLoss+=t,s&&(a.totalVideoDelay=(a.totalVideoDelay||0)+s,a.videoDelayCount=(a.videoDelayCount||0)+1),n&&(a.totalAudioDelay=(a.totalAudioDelay||0)+n,a.audioDelayCount=(a.audioDelayCount||0)+1),a.count++;else{let c,l,h,m;s&&(l=s,h=1),n&&(c=n,m=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(r,{totalRTT:e,totalLoss:t,count:1,totalAudioDelay:c,totalVideoDelay:l,audioDelayCount:m,videoDelayCount:h})}}))}handleHeartbeatStats(i){var e;if(this.hitTest(i.room)){let{msg_device_info:t,msg_up_stream_info:r,msg_down_stream_info:s}=i.report;if(r.msg_video_status[0]){let{uint32_video_codec_bitrate:n,uint32_video_enc_fps:a,uint32_video_width:c,uint32_video_height:l}=r.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=n,this._localStreamStat.totalVideoFPS+=a,this._localStreamStat.totalVideoWidth+=c,this._localStreamStat.totalVideoHeight+=l,this._localStreamStat.videoCount++}if(r.msg_audio_status){let{uint32_audio_level:n}=r.msg_audio_status;Math.floor(n/Dt*100)>0&&(this._localStreamStat.totalAudioLevel+=n/Dt,this._localStreamStat.audioLevelCount++)}s.forEach(n=>{let{msg_user_info:a,msg_audio_status:c,msg_video_status:l}=n,h=a.str_identifier,m=this._room.remotePublishedUserMap.get(h);if(l.forEach(u=>{let _=u.uint32_video_stream_type===2,g=u.uint32_video_stream_type===7,E=`${h}_${_?"main":"auxiliary"}`,A=this._remoteStreamStatMap.get(E);if(A&&(_&&(m!=null&&m.remoteVideoTrack.isSubscribed)||g&&(m!=null&&m.remoteAuxiliaryTrack))){A.totalVideoFPS+=u.uint32_video_receive_fps,A.totalVideoBitrate+=u.uint32_video_codec_bitrate,A.videoCount++,A.statsToReport.uint32_video_width===0&&(A.statsToReport.uint32_video_width=u.uint32_video_width),A.statsToReport.uint32_video_height===0&&(A.statsToReport.uint32_video_height=u.uint32_video_height);let k=_?m.remoteVideoTrack:m.remoteAuxiliaryTrack;k.stat.jitterBufferDelay&&(A.videoJitterBufferDelay=k.stat.jitterBufferDelay),k.stat.framesReceived&&(A.statsToReport.uint32_video_consume_render_rate=Math.floor(k.stat.framesDecoded/k.stat.framesReceived*hr(10,6)))}}),!Fo(c)){let u=`${h}_main`,_=this._remoteStreamStatMap.get(u);this._remoteStreamStatMap.has(u)&&_&&m!=null&&m.remoteAudioTrack.isSubscribed&&(_.totalAudioBitrate+=c.uint32_audio_codec_bitrate,_.audioCount++,m.remoteAudioTrack.stat.jitterBufferDelay&&(_.audioJitterBufferDelay=m.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(c.uint32_audio_level/Dt*100)>0&&(_.totalAudioLevel+=c.uint32_audio_level/Dt,_.audioLevelCount++),c.uint32_audio_block_time&&(_.statsToReport.uint32_audio_block_time+=c.uint32_audio_block_time))}}),t.uint32_audio_capture_cost&&(this._captureCostSum+=t.uint32_audio_capture_cost,this._captureCostCount+=1,this._captureCostCount>=100&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0)),t.uint32_audio_capture_cost===0&&((e=this._room.audioManager.localAudioTrack)==null?void 0:e.muted)===!1&&(this._localStreamStat.statsToReport.uint32_audio_capture_thread_health_zero_cnt+=1)}}handlePublishStart({room:i}){this.hitTest(i)&&this._localStreamStat.publishStartTime===0&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart({track:i}){i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess({track:i}){i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=0,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=0,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed({track:i,error:e}){let r={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[e.name]||(e instanceof D?e.getExtraCode()||e.getCode():I.UNKNOWN);i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=r,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=r,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}hasVideoFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&fr)>=0}hasAudioFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&_r)>=0}hasAuxFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&Hr)>=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:m,audioDelayCount:u,videoDelayCount:_,totalAudioDelay:g,totalVideoDelay:E}=r;i.statsToReport.uint32_avg_down_loss=Math.floor(h/m),u&&g&&(i.statsToReport.uint32_audio_network_p2p_delay=Math.floor(g/u),i.audioJitterBufferDelay&&(i.statsToReport.uint32_p2p_delay=Math.floor(i.statsToReport.uint32_audio_network_p2p_delay+i.audioJitterBufferDelay))),_&&E&&(i.statsToReport.uint32_video_network_p2p_delay=Math.floor(E/_))}i.videoCount>0&&(i.statsToReport.uint32_video_avg_fps=Math.floor(i.totalVideoFPS/i.videoCount),i.statsToReport.uint32_video_avg_bitrate=Math.floor(i.totalVideoBitrate/i.videoCount)),i.audioCount>0&&(i.statsToReport.uint32_audio_recv_bitrate=i.statsToReport.uint32_audio_bitrate=Math.floor(i.totalAudioBitrate/i.audioCount)),i.audioLevelCount>0&&(i.statsToReport.uint32_audio_play_db=Math.floor(i.totalAudioLevel/i.audioLevelCount*100));let{callDurationCalculator:s}=this._room;s&&(i.statsToReport.uint32_audio_play_time=s.getDuration(e,p.AUDIO),i.statsToReport.uint32_video_play_time=s.getDuration(e,p.VIDEO)),i.statsToReport.uint32_video_render_first&&(i.statsToReport.uint32_video_render_first=Math.min(i.statsToReport.uint32_video_render_first,bo));let{badCaseDetector:n}=this._room,{dataFreeze:a,count:c}=n.getDataFreezeDuration(e),{renderFreeze:l}=n.getRenderFreezeDuration(e);i.statsToReport.uint32_video_block_count=c,i.statsToReport.uint32_video_block_time=Math.min(a,i.statsToReport.uint32_video_play_time),i.statsToReport.uint32_video_external_block_time=Math.min(l,i.statsToReport.uint32_video_play_time),i.statsToReport.uint32_audio_block_time=Math.min(i.statsToReport.uint32_audio_block_time,i.statsToReport.uint32_audio_play_time),n.isBlackStream(e)&&i.statsToReport.uint32_video_avg_fps===0?i.statsToReport.uint32_video_black_screen_subjective=1:i.statsToReport.uint32_video_black_screen_subjective=0}),this._pathMainAudioMap.forEach((i,e)=>{if(!this.hasAudioFlag(i.userId)){this._pathMainAudioMap.delete(e);return}i.statsToReport.uint64_play_first_frame_time-i.statsToReport.uint64_start_enter_time>bo&&(i.statsToReport.uint64_play_first_frame_time=i.statsToReport.uint64_start_enter_time+bo)}),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>bo&&(i.statsToReport.uint64_render_first_frame_time=i.statsToReport.uint64_start_enter_time+bo)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>bo&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+bo)}getReportData(){this._basicInfo.uint32_networkType=qr();let i={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new aa({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:Bo(this._signalInfo.relayIp),uint32_client_ip:Bo(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*hr(2,31)),msg_path_enter_room:this._pathJoinRoom,msg_path_exit_room:this._pathLeaveRoom,msg_path_recv_video:[...this._pathMainVideoMap.values()].map(e=>e.statsToReport),msg_quality_statistics:[...this._remoteStreamStatMap.values()].map(e=>e.statsToReport),str_room_name:String(this._room.roomId||0),msg_path_recv_audio:[...this._pathMainAudioMap.values()].map(e=>e.statsToReport),uint32_info_client_ip:Bo(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,bytes_report_buf_from_0x1:this._signalInfo.endReportExtend,str_user_sig:this._room.userSig,bytes_report_token:this._signalInfo.reportToken};return Xs(i),i}report(){return f(this,null,function*(){try{this.prepareReport();let i=this.getReportData();yield this.upload(i),this.initData()}catch(i){this._log.warn(i)}finally{this.isDestroyed&&(this._room=null)}})}upload(i){return f(this,null,function*(){if(i.msg_path_enter_room.uint64_start_time===0)return;let e=Number(this._room.sdkAppId),t=Ar.enable?Wi(i,2001,e):yield yl(i),r=t instanceof ArrayBuffer,s=`${Gi(e,mr.KEY_POINT)}&gzip=${+r}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(s,t));let a=[this.uploadKVStat(v),this.uploadKVStat(ro)];n||a.push(qi({url:s,body:t,priority:"low"})),yield Promise.all(a)})}setConnectionType(i){this.connectionType=i,this._basicInfo.uint32_connection_type=i}uploadKVStat(i){return f(this,null,function*(){let e=i.getReportData(this._room.userSig,this._signalInfo.reportToken);if(e.stats_count.length===0&&e.stats_distribution.length===0)return;e.msg_sdk_basic_info=L(O({},e.msg_sdk_basic_info),{bytes_device_name:this._basicInfo.string_device_name||"",bytes_os_version:this._basicInfo.string_os_version||"",uint32_framework:this._frameWorkType,uint32_network_type:this._basicInfo.uint32_networkType||0}),this._log.debug(e);let t=Ar.enable?Wi(e,2003,this._room.sdkAppId):yield yl(e),r=t instanceof ArrayBuffer,s=`${Gi(+this._room.sdkAppId,mr.KV_STAT)}&gzip=${+r}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(s,t)),n||qi({url:s,body:t})})}};M([Mt({settings:{timeout:500,retries:3}})],wd.prototype,"upload",1);var bo=5e3,EI={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},aa=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}},v_=wd;var dm=class{constructor(){d(this,"_startTime");d(this,"_endTime");this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=V())}stop(){this._endTime===0&&(this._endTime=V())}getDuration(){return this._endTime===0?V()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},Ld=dm;var lm=class{constructor(i){d(this,"_room",null);d(this,"_durationMap");d(this,"_eventMap",new Map);this._room=i.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(C.REMOTE_TRACK_SUBSCRIBED,this.handleSubscribed).set(C.REMOTE_TRACK_UNSUBSCRIBED,this.handleUnsubscribed).set(C.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{var n;let{userId:r}=t;if(!this.hitTest(i))return;e.hasAudio&&!t.hasAudio&&this.stopDurationItem(`${r}_main`,p.AUDIO),e.hasVideo&&!t.hasVideo&&this.stopDurationItem(`${r}_main`,p.VIDEO),e.hasAuxiliary&&!t.hasAuxiliary&&this.stopDurationItem(`${r}_auxiliary`,p.VIDEO);let s=(n=this._room)==null?void 0:n.remotePublishedUserMap.get(r);s&&(!e.hasAudio&&t.hasAudio&&s.remoteAudioTrack.isSubscribed&&this.addDuractionItem(r,p.AUDIO,"main"),!e.hasVideo&&t.hasVideo&&s.remoteVideoTrack.isSubscribed&&this.addDuractionItem(r,p.VIDEO,"main"),!e.hasAuxiliary&&t.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(r,p.VIDEO,"auxiliary"))}),this._eventMap.forEach((i,e)=>S.on(e,i,this))}uninstallEvents(){this._eventMap.forEach((i,e)=>S.off(e,i,this)),this._eventMap.clear()}handleSubscribed({track:i}){if(!this.hitTest(i.room))return;let{userId:e,streamType:t,kind:r}=i;i.isSubscribed?this.addDuractionItem(e,r,t):this.stopDurationItem(`${e}_${t}`,r)}handleUnsubscribed({track:i}){this.hitTest(i.room)&&this.stopDurationItem(`${i.userId}_${i.streamType}`,i.kind)}isRecording(i){return i.findIndex(e=>e.endTime===0)>=0}addDuractionItem(i,e,t){let r=`${i}_${t}`,s=new Ld,n=this._durationMap.get(r);n?this.isRecording(n[e])||n[e].push(s):this._durationMap.set(r,{userId:i,type:t,audio:e===p.AUDIO?[s]:[],video:e===p.AUDIO?[]:[s]})}stopDurationItem(i,e){if(this._durationMap.has(i)){let r=this._durationMap.get(i)[e].find(s=>s.endTime===0);r&&r.stop()}}hitTest(i){return this._room===i}getDuration(i,e){return this._durationMap.has(i)?this._durationMap.get(i)[e].reduce((r,s)=>r+s.getDuration(),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},N_=lm;var um=class{constructor(){d(this,"renderFreezeMap",new Map);d(this,"dataFreezeMap",new Map)}get(i,e){let t=this.renderFreezeMap.get(i),r=this.dataFreezeMap.get(i);return e?e==="data"?r:t:(Ce||te)&&t&&r&&t.duration>r.duration?t:r}set(i,e,t){t==="data"?this.dataFreezeMap.set(i,e):this.renderFreezeMap.set(i,e)}clear(){this.renderFreezeMap.clear(),this.dataFreezeMap.clear()}},hm=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 um);d(this,"_eventMap",new Map);d(this,"_videoEncodeFailedCount",0);d(this,"_audioEncodeFailedCount",0);d(this,"_encodeFailedThreshold",3);d(this,"eventListenerMap",new Map);this._room=i.room,this.installEvents()}getRenderFreezeMap(){return this._renderFreezeMap}getDataFreezeMap(){return this._dataFreezeMap}installEvents(){this._eventMap.set(C.LEAVE_SUCCESS,({room:i})=>{this.hitTest(i)&&this.stop()}).set(C.PLAY_TRACK_START,this.onPlayTrackStart).set(C.UNSUBSCRIBE_SUCCESS,({room:i,streamType:e,remotePublishedUser:t})=>{if(!this.hitTest(i))return;let{userId:r}=t,s=`${r}_${e}`;this.stopDataFreeze({key:s,userId:r,type:e})}).set(C.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{if(!this.hitTest(i))return;let{userId:r}=t;if(e.hasVideo&&!t.hasVideo){let s="main",n=`${t.userId}_${s}`;this.stopDataFreeze({key:n,userId:r,type:s})}if(e.hasAuxiliary&&!t.hasAuxiliary){let s="auxiliary",n=`${t.userId}_${s}`;this.stopDataFreeze({key:n,userId:r,type:s})}}).set(C.PLAYER_STATE_CHANGED,({track:i,state:e,reason:t,type:r})=>{if(!(!i.isRemote||!i.room||!this.hitTest(i.room)||r!==p.VIDEO)){if(e==="PLAYING"){let s=`${i.userId}_${i.streamType}`;this._isVideoPlayingEventFiredMap.set(s,!0)}t===p.MUTE?this.onVideoTrackMuted(i):t===p.UNMUTE&&this.onVideoTrackUnmuted(i)}}).set(C.HEARTBEAT_REPORT,this.onHearBeatReport).set(C.REMOTE_VIDEO_PLAY_START,this.onRemoteVideoPlayStart).set(C.REMOTE_VIDEO_PLAY_FINISH,this.onRemoteVideoPlayEnd),this._eventMap.forEach((i,e)=>S.on(e,i,this))}uninstallEvents(){this._eventMap.forEach((i,e)=>S.off(e,i,this)),this._eventMap.clear()}stop(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}onVideoTrackMuted(i){if(!i.isSubscribed)return;let{userId:e,streamType:t}=i,r=`${e}_${t}`,s=this._dataFreezeMap.get(r),n=new Ld;s?s.durationItemList.push(n):this._dataFreezeMap.set(r,{userId:e,type:t,durationItemList:[n],isFreezing(){let a=this.durationItemList[this.durationItemList.length-1];return a&&a.endTime===0}})}onVideoTrackUnmuted(i){if(!i.isSubscribed)return;let{userId:e,streamType:t}=i,r=`${e}_${t}`;this.stopDataFreeze({key:r,userId:e,type:t})}onHearBeatReport({room:i,report:e}){if(this.hitTest(i)){if(e.msg_up_stream_info.msg_video_status){let t=e.msg_up_stream_info.msg_video_status,r=Array.from(this._room.localTracks).find(n=>n.kind==="video"&&!n.isScreen),s=(r==null?void 0:r.stat.bytesSent)||0;if((r==null?void 0:r.isMediaTrackActive)===!1||s<=0||r!=null&&r.isUseCustomSource)return;t.forEach(n=>{n.uint32_video_stream_type===2&&(n.uint32_video_capture_fps!==0&&n.uint32_video_codec_bitrate===0&&n.uint32_video_enc_fps===0&&(r!=null&&r.isPublished)?(this._videoEncodeFailedCount+=1,this._videoEncodeFailedCount===this._encodeFailedThreshold&&ne.uploadEvent({userId:this._room.userId,log:`stat-${Ke.VIDEO_ENCODE_FAILED_DURING_CALL}`})):this._videoEncodeFailedCount=0)})}if(e.msg_up_stream_info.msg_audio_status){let t=e.msg_up_stream_info.msg_audio_status,r=Array.from(this._room.localTracks).find(n=>n.kind==="audio"),s=(r==null?void 0:r.stat.bytesSent)||0;if((r==null?void 0:r.isMediaTrackActive)===!1||s<=0)return;t.uint32_audio_codec_bitrate===0&&(r!=null&&r.isPublished)?(this._audioEncodeFailedCount+=1,this._audioEncodeFailedCount===this._encodeFailedThreshold&&ne.uploadEvent({userId:this._room.userId,log:`stat-${Ke.AUDIO_ENCODE_FAILED_DURING_CALL}`})):this._audioEncodeFailedCount=0}}}stopDataFreeze({key:i,userId:e,type:t}){let r=this._dataFreezeMap.get(i);if(!r||!r.isFreezing())return;let s=r.durationItemList[r.durationItemList.length-1];s.stop();let n=s.getDuration();if(n>Ca){let a=this._monitorFreezeData.get(i,"data");this._monitorFreezeData.set(i,{userId:e,type:t,duration:a?a.duration+n:n},"data")}else r.durationItemList.pop()}getTotalDuration(i){return i.reduce((e,t)=>{let r=t.getDuration();return e+Math.min(r,5e3)},0)}onPlayTrackStart({track:i}){if(!i.isRemote||!this.hitTest(i.room)||i.kind!==p.VIDEO||!i.isRemotePublished)return;let e=`${i.userId}_${i.streamType}`;this._isVideoPlayingEventFiredMap.has(e)||this._isVideoPlayingEventFiredMap.set(e,!1)}getDataFreezeDuration(i){let e={dataFreeze:0,count:0},t=this._dataFreezeMap.get(i);if(t){if(t.isFreezing()){let r=t.durationItemList[t.durationItemList.length-1];r.stop(),r.getDuration()<Ca&&t.durationItemList.pop()}e.dataFreeze=this.getTotalDuration(t.durationItemList),e.count=t.durationItemList.length}return e}getRenderFreezeDuration(i){let e={renderFreeze:0,count:0},t=this._renderFreezeMap.get(i);return t&&(e.renderFreeze=t.totalDuration,e.count=t.count),e}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(i){return this._isVideoPlayingEventFiredMap.has(i)?!this._isVideoPlayingEventFiredMap.get(i):!1}onRemoteVideoPlayStart({track:i,player:e}){var n;if(!Ki())return;let t=0,r=()=>{document.hidden||(t=0)};document.addEventListener("visibilitychange",r);let s=(a,c)=>{var l;if(t){let h=i.decodeFPS,m=h>0&&h<=5?600+1e3/h:600,u=c.presentationTime-t;if(u>m){u=Math.min(u,5e3);let _=`${i.userId}_${i.streamType}`,g=this._monitorFreezeData.get(_,"render");g?g.duration+=u:this._monitorFreezeData.set(_,{userId:i.userId,type:i.streamType,duration:u},"render");let E=this._renderFreezeMap.get(_);E?(E.totalDuration+=u,E.count+=1):this._renderFreezeMap.set(_,{userId:i.userId,type:i.streamType,totalDuration:u,count:1})}}t=c.presentationTime,(l=e.element)==null||l.requestVideoFrameCallback(s)};(n=e.element)==null||n.requestVideoFrameCallback(s),this.eventListenerMap.set(`${i.userId}_${i.streamType}`,{onVisibilityChange:r})}onRemoteVideoPlayEnd({track:i,player:e}){let t=`${i.userId}_${i.streamType}`,r=this.eventListenerMap.get(t);r&&document.removeEventListener("visibilitychange",r.onVisibilityChange)}resetMonitor(){this._monitorFreezeData.clear()}hitTest(i){return i===this._room}destroy(){this.uninstallEvents()}},D_=hm;var k_=Je(at(),1);var xd=class{constructor(i,e,t,r,s,n=4/3){this.vbMode=i;this.faceDetectorHash=t;this.visionTaskRegistry=r;this.logger=s;d(this,"animationState");d(this,"originalAspect");d(this,"totalOffsetX",0);d(this,"totalOffsetY",0);d(this,"defaultScaleRatio",.1);d(this,"isRecovering",!1);d(this,"boundaryY",280);d(this,"lastActionTime",0);d(this,"restTime",400);this.animationState={current:null,target:null,animating:!1,debounceTimer:null,startTime:0,duration:3e3,debounceTime:150,movementThreshold:30,debounceThreshold:15},this.addEvent(this.vbMode,!!this.faceDetectorHash),this.originalAspect=n||4/3,this.visionTaskRegistry.setVideo(this.faceDetectorHash,e)}addEvent(i,e,t){let s=[{key:570704,error:t!=null?t:e?void 0:11},{key:570705,error:t!=null?t:e?void 0:22}][i-1];s&&(e?v.addSuccessEvent({key:s.key}):v.addFailedEvent({key:s.key,error:s.error}))}actionCentering(i){let e=Date.now();if(this.animation(),!this.faceDetectorHash||e-this.lastActionTime<this.restTime||this.animationState.animating)return;let{videoWidth:t,videoHeight:r}=i;this.animationState.debounceThreshold=t/30,this.animationState.movementThreshold=t/20,this.boundaryY=r*.6;try{let s=this.visionTaskRegistry.getResult(this.faceDetectorHash);if(s.detections.length<=0){this.vbMode===1&&this.recoverOriginal(t,r);return}let n=s.detections[0].boundingBox,a=n.originX,c=n.originY,l=n.width,h=n.height;this.vbMode===1?this.dualStageCropping(t,r,a,c,l,h):this.vbMode===2&&this.movingPortrait(t,r,a,c,l,h)}catch(s){this.logger.error(s)}this.lastActionTime=e}calculateBoundary(i,e,t,r){let s,n;return i>e/2?(s=e-t-r,n=t-s):(s=t,n=0),{min:s,offset:n}}calculateTargetPosition(i,e,t,r,s,n,a=.4){let c=i+t/2,l=e+r/2,h,m,{min:u,offset:_}=this.calculateBoundary(c,s,i,t),{min:g,offset:E}=this.calculateBoundary(l,n,e,r);return h=2*u+t,m=2*g+r,h/m>this.originalAspect?(h=m*this.originalAspect,_=c-h/2):(m=h/this.originalAspect,E=l-m/2),t/s>a&&(_=0,E=0,h=s,m=n),_=Math.max(0,Math.min(_,s-h)),E=Math.max(0,Math.min(E,n-m)),{sx:_,sy:E,cropWidth:h,cropHeight:m,timestamp:Date.now()}}processFacePositionCrop(i,e,t){if(!this.animationState.current||!this.animationState.target){let a={sx:0,sy:0,cropWidth:e,cropHeight:t,timestamp:Date.now()};this.animationState.current=a,this.animationState.target=a;return}let r=this.positionDistance(this.animationState.target,i),s=this.positionDistance(this.animationState.current,i),n=this.animationState.current.cropWidth/e;r>this.animationState.debounceThreshold*n&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&s>this.animationState.movementThreshold*n&&(this.animationState.target=i,this.animationState.debounceTimer=setTimeout(()=>{this.animationState.startTime=Date.now(),this.animationState.animating=!0},this.animationState.debounceTime))}processFacePositionPortrait(i){if(!this.animationState.current||!this.animationState.target){this.animationState.current=O({},i),this.animationState.target=O({},i);return}let e=this.positionDistance(this.animationState.current,i),t=this.positionDistance(this.animationState.target,i);e>this.animationState.debounceThreshold&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&t>this.animationState.movementThreshold&&(this.animationState.current=i,this.animationState.debounceTimer=setTimeout(()=>{this.animationState.startTime=Date.now(),this.animationState.animating=!0},this.animationState.debounceTime))}animation(){if(!this.animationState.animating)return;let i=Date.now()-this.animationState.startTime,e=Math.min(i/this.animationState.duration,1),t=r=>r<.5?2*r*r:-1+(4-2*r)*r;if(this.animationState.current&&this.animationState.target){let r=(this.animationState.target.sx-this.animationState.current.sx)*t(e);this.animationState.current.sx+=r,this.totalOffsetX+=r;let s=(this.animationState.target.sy-this.animationState.current.sy)*t(e);if(this.animationState.current.sy+=s,this.totalOffsetY+=s,this.animationState.current.cropWidth+=(this.animationState.target.cropWidth-this.animationState.current.cropWidth)*t(e),this.animationState.current.cropHeight+=(this.animationState.target.cropHeight-this.animationState.current.cropHeight)*t(e),this.animationState.current.scaleRatio&&this.animationState.target.scaleRatio&&(this.animationState.current.scaleRatio+=(this.animationState.target.scaleRatio-this.animationState.current.scaleRatio)*t(e)),Q(this.animationState.current.scaleOffsetX)&&Q(this.animationState.target.scaleOffsetX)&&Q(this.animationState.current.scaleOffsetY)&&Q(this.animationState.target.scaleOffsetY)){let n=(this.animationState.target.scaleOffsetX-this.animationState.current.scaleOffsetX)*t(e);this.animationState.current.scaleOffsetX+=n;let a=(this.animationState.target.scaleOffsetY-this.animationState.current.scaleOffsetY)*t(e);this.animationState.current.scaleOffsetY+=a}}e>=1&&(this.animationState.animating=!1,this.animationState.current=this.animationState.target,this.isRecovering=!1)}positionDistance(i,e){return Math.sqrt(hr(i.sx-e.sx,2)+hr(i.sy-e.sy,2))}recoverOriginal(i,e){this.animationState.target={sx:0,sy:0,cropWidth:i,cropHeight:e,timestamp:Date.now()},this.animationState.animating=!0,this.animationState.startTime=Date.now(),this.isRecovering=!0}dualStageCropping(i,e,t,r,s,n,a=.3){if(this.isRecovering)return;let c=this.calculateTargetPosition(t,r,s,n,i,e);this.processFacePositionCrop(c,i,e),s*n/c.cropWidth/c.cropHeight>a&&this.recoverOriginal(i,e)}movingPortrait(i,e,t,r,s,n){var c,l,h,m,u,_,g,E,A,k,se,w;let a={sx:t+s/2+this.totalOffsetX,sy:r+n/2+this.totalOffsetY,cropWidth:i,cropHeight:e,scaleRatio:(l=(c=this.animationState.current)==null?void 0:c.scaleRatio)!=null?l:1,scaleOffsetX:(m=(h=this.animationState.current)==null?void 0:h.scaleOffsetX)!=null?m:0,scaleOffsetY:(_=(u=this.animationState.current)==null?void 0:u.scaleOffsetY)!=null?_:0,timestamp:Date.now()};this.animationState.target={sx:i/2,sy:r+n/2,cropWidth:i,cropHeight:e,scaleRatio:(E=(g=this.animationState.target)==null?void 0:g.scaleRatio)!=null?E:1,scaleOffsetX:(k=(A=this.animationState.target)==null?void 0:A.scaleOffsetX)!=null?k:0,scaleOffsetY:(w=(se=this.animationState.target)==null?void 0:se.scaleOffsetY)!=null?w:0,timestamp:Date.now()},this.animationState.animating||(this.animationState.target.scaleRatio=Math.sqrt(s*n/i/e/this.defaultScaleRatio),this.animationState.target.scaleOffsetX=-this.animationState.target.scaleRatio/2+.5,this.animationState.target.scaleOffsetY=-this.animationState.target.scaleRatio+1,(this.animationState.target.sy-this.animationState.target.scaleOffsetY*this.animationState.target.cropHeight)/this.animationState.target.scaleRatio<this.boundaryY&&(this.animationState.target.scaleOffsetY=(this.animationState.target.sy-this.boundaryY*this.animationState.target.scaleRatio)/this.animationState.target.cropHeight)),this.processFacePositionPortrait(a)}set aspectRatio(i){this.originalAspect=i}get current(){return this.animationState.current}get offset(){return{offsetX:this.totalOffsetX,offsetY:this.totalOffsetY}}get targetCrop(){return this.animationState.target}};var SI=`#version 300 es
67
77
  in vec2 a_position;
68
78
  in vec2 a_texCoord;
69
79
  out vec2 v_texCoord;
70
80
  void main() {
71
81
  gl_Position = vec4(a_position.x, a_position.y, 0, 1);
72
82
  v_texCoord = a_texCoord;
73
- }`,pI=`#version 300 es
83
+ }`,II=`#version 300 es
74
84
  precision highp float;
75
85
  uniform sampler2D u_texture;
76
86
  uniform sampler2D mask;
@@ -79,7 +89,7 @@ in vec2 v_texCoord;
79
89
  out vec4 outColor;
80
90
  void main() {
81
91
  outColor = vec4(texture(u_texture, v_texCoord).rgb, texture(mask, v_texCoord).a);
82
- }`,Mc=class extends Wt{constructor(e,t){super(e,t.input,{name:"vb",create2d:!1,useDefaultProgram:!1,useFbo:!1,createTexture:!0,width:t.width,height:t.height,logger:e.log});c(this,"_bgTexture");c(this,"_waterMarkTexture");c(this,"_lastMaskTexture");c(this,"_lastMaskFbo");c(this,"_textureValid",!1);c(this,"_selfieTextureValid",!1);c(this,"_selfieSegmentationHash");c(this,"wasm");c(this,"predictReady");c(this,"_color");c(this,"_prePrograme");c(this,"_segmentationMask");c(this,"_weixin",!1);c(this,"_centerFace");c(this,"_textureMatrixLocation");c(this,"_offsetMatrixLocation");c(this,"_colorLocation");c(this,"_enableFaceCentering",!1);c(this,"_enableEffectOptimization",!1);c(this,"_mat4");c(this,"_postProcessing");c(this,"_onAbort");c(this,"_visionTaskRegistry");c(this,"resolvePreditReady");this.init(t).catch(r=>{e.log.error(r),e.destroy(new v({code:I.VIDEO_MANAGER_ERROR,extraCode:6,message:`init vb node error ${r.message||r}`})),this.resolvePreditReady()})}init(e){return f(this,null,function*(){var n,a,d;this.predictReady=new Promise(l=>{this.resolvePreditReady=l});let t=e.Wasm,r=this.context.ctx;if(e.color&&(this._color=e.color),e.mat4&&(this._mat4=e.mat4),e.postProcessing&&(this._postProcessing=e.postProcessing),this._enableFaceCentering=(n=e.enableFaceCentering)!=null?n:!1,this._enableEffectOptimization=(a=e.enableEffectOptimization)!=null?a:!1,this.wasm=new t.AllIn1(r),this.wasm.blurRadius=e.blurRadius||3,this.wasm.mirror=!!e.mirror,this.wasm.rotation=e.rotation||0,this.wasm.vbMode=e.bg==="blur"?1:e.bg instanceof HTMLImageElement?2:e.bg==="color"?3:0,this._onAbort=e.onAbort,e.bg||this.resolvePreditReady(),e.waterMark){let{x:l,y:u,width:h,height:p}=e.waterMark;this.wasm.setWaterMark(l,u,h,p)}if(e.beautyParams){let{beauty:l,brightness:u,ruddy:h}=e.beautyParams;this.wasm.setBeauty(l,u,h,e==null?void 0:e.width,e==null?void 0:e.height)}this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),r.uniform1i(r.getUniformLocation(this.program,"mask"),1),e.bg instanceof HTMLImageElement&&(r.uniform1i(r.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(e.bg)),e.waterMark&&(r.uniform1i(r.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(e.waterMark.image));let s=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);if(this._textureMatrixLocation=r.getUniformLocation(this.program,"u_textureMatrix"),r.uniformMatrix4fv(this._textureMatrixLocation,!1,s),this._offsetMatrixLocation=r.getUniformLocation(this.program,"u_offsetMatrix"),r.uniformMatrix4fv(this._offsetMatrixLocation,!1,s),this._colorLocation=r.getUniformLocation(this.program,"u_color"),r.uniform1i(r.getUniformLocation(this.program,"lastMask"),4),this._weixin){let l=this.context.createShader(r.FRAGMENT_SHADER,pI),u=this.context.createShader(r.VERTEX_SHADER,mI);this._prePrograme=this.context.createProgram(u,l),r.useProgram(this._prePrograme),this.setAttributes(this.positionBuffer,this.texCoordBuffer),r.uniform1i(r.getUniformLocation(this._prePrograme,"mask"),1)}this._enableEffectOptimization&&(this.wasm.vbMode===2||this.wasm.vbMode===3)?nn()?(this._postProcessing=void 0,this.log.warn("Virtual background post-processing isn't allowed on mobile.")):(d=this._postProcessing)==null||d.init(r,this.positionBuffer,this.texCoordBuffer,4/3):this._postProcessing=void 0,yield this.initVisionTasks(e)})}initVisionTasks(e){return f(this,null,function*(){if(e.bg){if(this._visionTaskRegistry=yield window.VisionTaskRegistry.getInstance(),!window.VisionTaskRegistry||!this._visionTaskRegistry||!this._visionTaskRegistry.visionWasm)throw new Error("Virtual background assets not found. Please redeploy the assets of the npm package.");if(this._selfieSegmentationHash=yield this._visionTaskRegistry.register(window.VisionTaskType.ImageSegmenter,{canvas:this.context._canvas}),this._visionTaskRegistry.setVideo(this._selfieSegmentationHash,this.image),this._enableFaceCentering)try{this._visionTaskRegistry.models.has(window.VisionTaskType.FaceDetector)||(yield this._visionTaskRegistry.preloadModels([window.VisionTaskType.FaceDetector]));let t=yield this._visionTaskRegistry.register(window.VisionTaskType.FaceDetector);if(!t)return;this._centerFace=new Dc(this.wasm.vbMode,this.image,t,this._visionTaskRegistry,this.context.log)}catch(t){this.log.error("Face detector model not found. Please redeploy the assets of the npm package.")}}})}onPredict(e){let t=this.context.ctx;this._weixin&&(this._lastMaskTexture||(this._lastMaskTexture=this.createTexture(this.image),this._lastMaskFbo=this.createFramebuffer(this._lastMaskTexture)));let r=this.getMaskTexture(e);if(!r)return;let s=r;this._postProcessing&&(this._postProcessing.ratio=this.image.videoWidth/this.image.videoHeight,s=this._postProcessing.postProcessing(r)),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),this.useTexture(),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,s||null),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),this.wasm.vbMode===3&&t.uniform3fv(this._colorLocation,this._color),this.useBufferFrame(),this._segmentationMask=e,this.totalFrames++,this.centerFace(),bt(this.wasm.rotation)&&this.resize(this.image.height,this.image.width),t.viewport(0,0,t.canvas.width,t.canvas.height),t.drawArrays(t.TRIANGLE_STRIP,0,4),e.close()}getMaskTexture(e){return e.confidenceMasks?e.confidenceMasks[0].getAsWebGLTexture():void 0}onFirstFrame(){this.waitingFirstFrame=!1;let e=this.context.ctx;this.useTexture(),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,this.image)}render(e){let t=this.context.ctx,{image:r}=this;this.tryVideoFrameCallback();let{videoWidth:s,videoHeight:n}=r;if(bt(this.wasm.rotation)&&!this._visionTaskRegistry&&([s,n]=[n,s]),s===0||n===0||!this.available)return!1;r.width=s,r.height=n;let a=!1;if(this.totalFrames)this.useTexture(),a=this._selfieTextureValid,this._selfieTextureValid=!0;else{if(this.program)this.useTexture();else return!1;a=this._textureValid,this._textureValid=!0}if(this.width!==s||this.height!==n||!a?(this.resize(s,n),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,r)):t.texSubImage2D(t.TEXTURE_2D,0,0,0,t.RGBA,t.UNSIGNED_BYTE,r),this._weixin){if(t.useProgram(this._prePrograme),this.useTexture(),this._segmentationMask){let d=this.getMaskTexture(this._segmentationMask);t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,d||null),t.bindFramebuffer(t.FRAMEBUFFER,this._lastMaskFbo||null)}t.drawArrays(t.TRIANGLE_STRIP,0,4),this.useTexture(),this._segmentationMask?t.copyTexSubImage2D(t.TEXTURE_2D,0,0,0,0,0,s,n):t.copyTexImage2D(t.TEXTURE_2D,0,t.RGBA,0,0,s,n,0)}try{if(this._selfieSegmentationHash&&this._visionTaskRegistry){let d=this._visionTaskRegistry.getResult(this._selfieSegmentationHash);this.totalFrames===1&&this.context._canvas&&this.resolvePreditReady(),this.onPredict(d)}}catch(d){this._onAbort&&this._onAbort(d)}return this.totalFrames||(t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),t.drawArrays(t.TRIANGLE_STRIP,0,4)),this._visionTaskRegistry&&this._visionTaskRegistry.resetHashResults(),!1}centerFace(){if(!this._centerFace||!this._enableFaceCentering)return;let e=this.context.ctx;this._centerFace.aspectRatio=e.canvas.width/e.canvas.height,this._centerFace.actionCentering(this.image);let{current:t,offset:r}=this._centerFace;if(t&&(this.wasm.vbMode===1&&this.drawImage(t.sx,t.sy,t.cropWidth,t.cropHeight),r&&this.wasm.vbMode===2)){if(!this._mat4)return;let s=this._mat4.create(),{scaleRatio:n=1,scaleOffsetX:a=0,scaleOffsetY:d=0}=t;this._mat4.fromTranslation(s,[-r.offsetX/e.canvas.width+a,d,0]),this._mat4.scale(s,s,[n,n,1]),e.uniformMatrix4fv(this._offsetMatrixLocation,!1,s)}}drawImage(e,t,r,s){let n=this.context.ctx;if(!this._mat4)return;let{width:a,height:d}=n.canvas,l=this._mat4.create();this._mat4.fromTranslation(l,[e/a,1-(t+s)/d,0]),this._mat4.scale(l,l,[r/a,s/d,1]),n.uniformMatrix4fv(this._textureMatrixLocation,!1,l)}close(){var t;super.close();let e=this.context.ctx;this._bgTexture&&e.deleteTexture(this._bgTexture),this._waterMarkTexture&&e.deleteTexture(this._waterMarkTexture),this._lastMaskTexture&&e.deleteTexture(this._lastMaskTexture),this._lastMaskFbo&&e.deleteFramebuffer(this._lastMaskFbo),this._prePrograme&&e.deleteProgram(this._prePrograme),this._postProcessing&&this._postProcessing.close(),(t=this.wasm)==null||t.close()}};var Oc=class extends Pe{constructor(e){super(e,{name:"yuv-source",useDefaultProgram:!1,create2d:!1,useFbo:!1,createTexture:!1,logger:e.log,fragmentShaderSource:`
92
+ }`,Ud=class extends Wt{constructor(e,t){super(e,t.input,{name:"vb",create2d:!1,useDefaultProgram:!1,useFbo:!1,createTexture:!0,width:t.width,height:t.height,logger:e.log});d(this,"_bgTexture");d(this,"_waterMarkTexture");d(this,"_lastMaskTexture");d(this,"_lastMaskFbo");d(this,"_textureValid",!1);d(this,"_selfieTextureValid",!1);d(this,"_selfieSegmentationHash");d(this,"wasm");d(this,"predictReady");d(this,"_color");d(this,"_prePrograme");d(this,"_segmentationMask");d(this,"_weixin",!1);d(this,"_centerFace");d(this,"_textureMatrixLocation");d(this,"_offsetMatrixLocation");d(this,"_colorLocation");d(this,"_enableFaceCentering",!1);d(this,"_enableEffectOptimization",!1);d(this,"_mat4");d(this,"_postProcessing");d(this,"_onAbort");d(this,"_visionTaskRegistry");d(this,"resolvePreditReady");this.init(t).catch(r=>{e.log.error(r),e.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:6,message:`init vb node error ${r.message||r}`})),this.resolvePreditReady()})}init(e){return f(this,null,function*(){var n,a,c;this.predictReady=new Promise(l=>{this.resolvePreditReady=l});let t=e.Wasm,r=this.context.ctx;if(e.color&&(this._color=e.color),e.mat4&&(this._mat4=e.mat4),e.postProcessing&&(this._postProcessing=e.postProcessing),this._enableFaceCentering=(n=e.enableFaceCentering)!=null?n:!1,this._enableEffectOptimization=(a=e.enableEffectOptimization)!=null?a:!1,this.wasm=new t.AllIn1(r),this.wasm.blurRadius=e.blurRadius||3,this.wasm.mirror=!!e.mirror,this.wasm.rotation=e.rotation||0,this.wasm.vbMode=e.bg==="blur"?1:e.bg instanceof HTMLImageElement?2:e.bg==="color"?3:0,this._onAbort=e.onAbort,e.bg||this.resolvePreditReady(),e.waterMark){let{x:l,y:h,width:m,height:u}=e.waterMark;this.wasm.setWaterMark(l,h,m,u)}if(e.beautyParams){let{beauty:l,brightness:h,ruddy:m}=e.beautyParams;this.wasm.setBeauty(l,h,m,e==null?void 0:e.width,e==null?void 0:e.height)}this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),r.uniform1i(r.getUniformLocation(this.program,"mask"),1),e.bg instanceof HTMLImageElement&&(r.uniform1i(r.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(e.bg)),e.waterMark&&(r.uniform1i(r.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(e.waterMark.image));let s=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);if(this._textureMatrixLocation=r.getUniformLocation(this.program,"u_textureMatrix"),r.uniformMatrix4fv(this._textureMatrixLocation,!1,s),this._offsetMatrixLocation=r.getUniformLocation(this.program,"u_offsetMatrix"),r.uniformMatrix4fv(this._offsetMatrixLocation,!1,s),this._colorLocation=r.getUniformLocation(this.program,"u_color"),r.uniform1i(r.getUniformLocation(this.program,"lastMask"),4),this._weixin){let l=this.context.createShader(r.FRAGMENT_SHADER,II),h=this.context.createShader(r.VERTEX_SHADER,SI);this._prePrograme=this.context.createProgram(h,l),r.useProgram(this._prePrograme),this.setAttributes(this.positionBuffer,this.texCoordBuffer),r.uniform1i(r.getUniformLocation(this._prePrograme,"mask"),1)}this._enableEffectOptimization&&(this.wasm.vbMode===2||this.wasm.vbMode===3)?dn()?(this._postProcessing=void 0,this.log.warn("Virtual background post-processing isn't allowed on mobile.")):(c=this._postProcessing)==null||c.init(r,this.positionBuffer,this.texCoordBuffer,4/3):this._postProcessing=void 0,yield this.initVisionTasks(e)})}initVisionTasks(e){return f(this,null,function*(){if(e.bg){if(this._visionTaskRegistry=yield window.VisionTaskRegistry.getInstance(),!window.VisionTaskRegistry||!this._visionTaskRegistry||!this._visionTaskRegistry.visionWasm)throw new Error("Virtual background assets not found. Please redeploy the assets of the npm package.");if(this._selfieSegmentationHash=yield this._visionTaskRegistry.register(window.VisionTaskType.ImageSegmenter,{canvas:this.context._canvas}),this._visionTaskRegistry.setVideo(this._selfieSegmentationHash,this.image),this._enableFaceCentering)try{this._visionTaskRegistry.models.has(window.VisionTaskType.FaceDetector)||(yield this._visionTaskRegistry.preloadModels([window.VisionTaskType.FaceDetector]));let t=yield this._visionTaskRegistry.register(window.VisionTaskType.FaceDetector);if(!t)return;this._centerFace=new xd(this.wasm.vbMode,this.image,t,this._visionTaskRegistry,this.context.log)}catch(t){this.log.error("Face detector model not found. Please redeploy the assets of the npm package.")}}})}onPredict(e){let t=this.context.ctx;this._weixin&&(this._lastMaskTexture||(this._lastMaskTexture=this.createTexture(this.image),this._lastMaskFbo=this.createFramebuffer(this._lastMaskTexture)));let r=this.getMaskTexture(e);if(!r)return;let s=r;this._postProcessing&&(this._postProcessing.ratio=this.image.videoWidth/this.image.videoHeight,s=this._postProcessing.postProcessing(r)),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),this.useTexture(),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,s||null),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),this.wasm.vbMode===3&&t.uniform3fv(this._colorLocation,this._color),this.useBufferFrame(),this._segmentationMask=e,this.totalFrames++,this.centerFace(),bt(this.wasm.rotation)&&this.resize(this.image.height,this.image.width),t.viewport(0,0,t.canvas.width,t.canvas.height),t.drawArrays(t.TRIANGLE_STRIP,0,4),e.close()}getMaskTexture(e){return e.confidenceMasks?e.confidenceMasks[0].getAsWebGLTexture():void 0}onFirstFrame(){this.waitingFirstFrame=!1;let e=this.context.ctx;this.useTexture(),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,this.image)}render(e){let t=this.context.ctx,{image:r}=this;this.tryVideoFrameCallback();let{videoWidth:s,videoHeight:n}=r;if(bt(this.wasm.rotation)&&!this._visionTaskRegistry&&([s,n]=[n,s]),s===0||n===0||!this.available)return!1;r.width=s,r.height=n;let a=!1;if(this.totalFrames)this.useTexture(),a=this._selfieTextureValid,this._selfieTextureValid=!0;else{if(this.program)this.useTexture();else return!1;a=this._textureValid,this._textureValid=!0}if(this.width!==s||this.height!==n||!a?(this.resize(s,n),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,r)):t.texSubImage2D(t.TEXTURE_2D,0,0,0,t.RGBA,t.UNSIGNED_BYTE,r),this._weixin){if(t.useProgram(this._prePrograme),this.useTexture(),this._segmentationMask){let c=this.getMaskTexture(this._segmentationMask);t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,c||null),t.bindFramebuffer(t.FRAMEBUFFER,this._lastMaskFbo||null)}t.drawArrays(t.TRIANGLE_STRIP,0,4),this.useTexture(),this._segmentationMask?t.copyTexSubImage2D(t.TEXTURE_2D,0,0,0,0,0,s,n):t.copyTexImage2D(t.TEXTURE_2D,0,t.RGBA,0,0,s,n,0)}try{if(this._selfieSegmentationHash&&this._visionTaskRegistry){let c=this._visionTaskRegistry.getResult(this._selfieSegmentationHash);this.totalFrames===1&&this.context._canvas&&this.resolvePreditReady(),this.onPredict(c)}}catch(c){this._onAbort&&this._onAbort(c)}return this.totalFrames||(t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),t.drawArrays(t.TRIANGLE_STRIP,0,4)),this._visionTaskRegistry&&this._visionTaskRegistry.resetHashResults(),!1}centerFace(){if(!this._centerFace||!this._enableFaceCentering)return;let e=this.context.ctx;this._centerFace.aspectRatio=e.canvas.width/e.canvas.height,this._centerFace.actionCentering(this.image);let{current:t,offset:r}=this._centerFace;if(t&&(this.wasm.vbMode===1&&this.drawImage(t.sx,t.sy,t.cropWidth,t.cropHeight),r&&this.wasm.vbMode===2)){if(!this._mat4)return;let s=this._mat4.create(),{scaleRatio:n=1,scaleOffsetX:a=0,scaleOffsetY:c=0}=t;this._mat4.fromTranslation(s,[-r.offsetX/e.canvas.width+a,c,0]),this._mat4.scale(s,s,[n,n,1]),e.uniformMatrix4fv(this._offsetMatrixLocation,!1,s)}}drawImage(e,t,r,s){let n=this.context.ctx;if(!this._mat4)return;let{width:a,height:c}=n.canvas,l=this._mat4.create();this._mat4.fromTranslation(l,[e/a,1-(t+s)/c,0]),this._mat4.scale(l,l,[r/a,s/c,1]),n.uniformMatrix4fv(this._textureMatrixLocation,!1,l)}close(){var t;super.close();let e=this.context.ctx;this._bgTexture&&e.deleteTexture(this._bgTexture),this._waterMarkTexture&&e.deleteTexture(this._waterMarkTexture),this._lastMaskTexture&&e.deleteTexture(this._lastMaskTexture),this._lastMaskFbo&&e.deleteFramebuffer(this._lastMaskFbo),this._prePrograme&&e.deleteProgram(this._prePrograme),this._postProcessing&&this._postProcessing.close(),(t=this.wasm)==null||t.close()}};var Vd=class extends Ve{constructor(e){super(e,{name:"yuv-source",useDefaultProgram:!1,create2d:!1,useFbo:!1,createTexture:!1,logger:e.log,fragmentShaderSource:`
83
93
  precision highp float;
84
94
  uniform sampler2D ySampler;
85
95
  uniform sampler2D uSampler;
@@ -104,15 +114,9 @@ void main() {
104
114
  void main() {
105
115
  gl_Position = vertexPos;
106
116
  textureCoord = texturePos;
107
- }`});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,s=r.createTexture();return r.bindTexture(r.TEXTURE_2D,s),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.bindTexture(r.TEXTURE_2D,null),r.uniform1i(r.getUniformLocation(this.program,e),t),s}render(e){let t=this.context.ctx,r=this.width,s=this.height;return this.useProgram(),t.viewport(0,0,r,s),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,this.yTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,r,s,t.LUMINANCE,t.UNSIGNED_BYTE,this.Y),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,this.uTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,r/2,s/2,t.LUMINANCE,t.UNSIGNED_BYTE,this.U),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this.vTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,r/2,s/2,t.LUMINANCE,t.UNSIGNED_BYTE,this.V),this.draw(),!0}resize(e,t){super.resize(e,t);let r=this.context.ctx;r.activeTexture(r.TEXTURE0),r.bindTexture(r.TEXTURE_2D,this.yTextureRef),r.texImage2D(r.TEXTURE_2D,0,r.LUMINANCE,e,t,0,r.LUMINANCE,r.UNSIGNED_BYTE,null),r.activeTexture(r.TEXTURE1),r.bindTexture(r.TEXTURE_2D,this.uTextureRef),r.texImage2D(r.TEXTURE_2D,0,r.LUMINANCE,e/2,t/2,0,r.LUMINANCE,r.UNSIGNED_BYTE,null),r.activeTexture(r.TEXTURE2),r.bindTexture(r.TEXTURE_2D,this.vTextureRef),r.texImage2D(r.TEXTURE_2D,0,r.LUMINANCE,e/2,t/2,0,r.LUMINANCE,r.UNSIGNED_BYTE,null)}};var E_=(o,i)=>{switch(o){case"webCodecs":return i==="videoFrame"?514705:514706;case"wasm":return i==="webgl"?514707:i==="videoFrame"?514708:514709}throw new Error("decoder type not supported")};function fI(o){return o[0]===0&&o[1]===0&&o[2]===0&&o[3]===1}var _I=0,kc=class{constructor(i){c(this,"id",_I++);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=rt(),this.track=e,this.createDecoder=t,this.wasmOption={yuvMode:i.renderer==="webgl",wasmPath:i.wasmPath,workerMode:i.workerMode,canvas:i.canvas},this.config=i.config,this.videoElement=i.videoElement,this.renderer=i.renderer,this.trackDoneOB=de(e.availableState,j.OFF),this.stopOB=rt(),i.type==="auto"){switch(i.fallback){case"wasm":this.type="wasm",this.renderer="webgl";break;case"wasm_2d":this.type="wasm",this.renderer="2d";break;case"wasm_video":this.type="wasm",this.renderer="videoFrame";break;default:this.type="webCodecs"}this.wasmOption.yuvMode=this.renderer==="webgl"}else this.type=i.type;this.changeRenderer(this.renderer),ce(this.stateChangeOB,uh((r,s)=>(r!==s&&e.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:this.failedReason,prevState:r,state:s}),s),"INITIALIZED"),ke(this.stopOB),Te()),this.start()}start(i=0){this.waitFirstKeyFrame=!0,this.stateChangeOB.next("STARTING");let e=ce(this.pipe(this.track),ke(this.stopOB),rr());ce(e,Te(()=>{this.track.stat.framesDecoded++},t=>{if(this.track.log.error(`${this.id} play failed: ${t} retryCount: ${i}`),y.addFailedEvent({key:E_(this.type,this.renderer),error:t}),i>4)this.failedReason=t,this.stateChangeOB.next("FAILED"),y.addFailedEvent({key:514704});else{if(this.goodType){this.start(i);return}switch(this.type){case"webCodecs":this.type="wasm",this.changeRenderer("webgl");break;case"wasm":switch(this.renderer){case"webgl":this.changeRenderer("videoFrame");break}}this.start(i+1)}},()=>{this.track.log.warn(`${this.id} decoderOB completed`),y.addSuccessEvent({key:E_(this.type,this.renderer)}),y.addSuccessEvent({key:514704})})),ce(e,or(1),Te(()=>{this.track.player.handlePlaying("canvas"),this.goodType=this.type,this.stateChangeOB.next("STARTED")}))}mock(i){this._decodeSink?this._decodeSink.error(i):this.start()}close(i){this.stopOB.next(i)}changeRenderer(i){this.renderer=i,this.renderer==="videoFrame"&&!pn()&&(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(!fI(t)||t.length<5)return this.stateChangeOB.next("FAILED"),this.close(`not h26x frame ${t.subarray(0,5)}`),i;let r=t[4]&31,s=!1;switch(r){case 5:case 7:s=!0;break}if(((a=this.decoder)==null?void 0:a.state)!=="configured")return this.track.log.debug(`not configured ${this.inputFrameCount}`),s&&(this.gop_before_configure=[]),this.gop_before_configure.push({data:i.data,timestamp:i.timestamp,type:i.type}),i;this.gop_before_configure.length>0&&!e&&(this.gop_before_configure.forEach(l=>this.decode(l,!0)),this.gop_before_configure=[]);let{timestamp:n}=i;if(s?(this.gop=this.gop_helper,this.gop_helper=0):this.gop_helper++,this.decoder){if(this.waitFirstKeyFrame)if(s)this.waitFirstKeyFrame=!1,this.startTimestamp=n,this.startTime=Date.now(),this.startPerformanceTime=V();else{this.track.log.debug(`wait first key frame ${this.inputFrameCount} ${t.subarray(0,5).join(" ")}`);return}switch(this.downgradeLevel){case 0:break;case 1:break;case 2:if(this.gop_helper>this.gop>>1)return;break;case 3:if(this.gop_helper>0)return;break;default:return}(this.decodeFrameCount<10||this.decodeFrameCount%500===0)&&this.track.log.debug(`decode ${this.decodeFrameCount} gop: ${this.gop} ${n} ${(d=i.getMetadata)==null?void 0:d.call(i).rtpTimestamp}`),this.decodeFrameCount++,this.lastDecodeFrameTimestamp=n,this.decoder.decode({data:i.data,type:i.type,timestamp:this.lastDecodeFrameTimestamp});return}return i}checkDowngradeByFrameDiff(){let i=this.downgradeLevel,e=this.decodeFrameCount-this.decodedFrameCount;e>this.lastFrameDiff?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):e<=this.lastFrameDiff&&this.downgradeLevel>0&&this.downgradeLevel--,this.downgradeLevel!==i&&this.track.log.debug(`downgrade level ${i} to ${this.downgradeLevel} ${this.decodeFrameCount} frameDiff: ${e}, lastFrameDiff: ${this.lastFrameDiff}`),this.lastFrameDiff=e,this.lastDowngradeTime=Date.now()}checkDowngradeByTimestampDiff(i){let e=this.downgradeLevel;this.lastDecodeFrameTimestamp-i>9e4?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):this.downgradeLevel>0&&this.downgradeLevel--,this.downgradeLevel!==e&&this.track.log.debug(`downgrade level ${e} to ${this.downgradeLevel}`)}pipe(i){return e=>f(this,null,function*(){this._decodeSink=e;let t,r=i.mediaTrack;e.defer(()=>{var a;r&&(i.player.setCanvas(),i.setInputMediaStreamTrack(r)),t==null||t.close(),(a=this.videoContext)==null||a.destroy(),delete this._decodeSink});let{renderer:s,type:n}=this;i.log.info(`decoder type: ${this.type} renderer: ${this.renderer}`);try{switch(n){case"wasm":t=this.createDecoder(n,this.wasmOption);break;case"webCodecs":t=this.createDecoder(n);break;default:throw new Error("not supported yet")}let a=0;if(t.on("videoFrame",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"&&s==="webgl"){this.videoContext=new Be({frameRate:15,logger:i.log,name:i.userId}),this.videoContext.create(),this.videoContext.on(Be.UNAVAILABLE,l=>{i.log.error(l),e.error(7)});let d=new Oc(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(s==="videoFrame"){i.player.setCanvas();let d=new MediaStreamTrackGenerator({kind:"video"}),l=d.writable.getWriter();i.setInputMediaStreamTrack(d),t.on("videoFrame",u=>l.write(u))}else{this.videoContext=new Xe({frameRate:15,logger:i.log,name:i.userId}),this.videoContext.create({alpha:!1});let d=this.videoContext.createVideoImageSource();t.on("videoFrame",u=>{try{d.image=u,d.update()}catch(h){delete this.goodType,i.log.error(h),e.error(11)}});let l=new fo(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 S_=Promise.resolve(),oa=class extends I_.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,"_rotation",0);c(this,"cameraTrack");c(this,"cameraNode");c(this,"transformNode");c(this,"mixNode");c(this,"screenTrack");c(this,"screenNode");c(this,"selfModel",!1);c(this,"blurRadius",3);c(this,"arTrack");c(this,"_enableFaceCentering",!1);c(this,"_enableEffectOptimization",!1);c(this,"onAbort");c(this,"_color");c(this,"Wasm");c(this,"waterMarkNode");c(this,"_waterMarkOption");c(this,"watermarkImageList",[]);c(this,"_beautyParams");c(this,"isUsingArTrack",!1);c(this,"mixTrack");c(this,"_isMixScreen",!1);c(this,"_virtualBackground");c(this,"_virtualBackgroundAbortCallback");c(this,"virtualBackgroundInstance");c(this,"_bgAssetPath");c(this,"log");c(this,"_mat4");c(this,"_postProcessing");c(this,"_checkId",0);c(this,"_use2d",!1);c(this,"_autoSwitchRenderMode",!0);c(this,"encodePipeline",[]);c(this,"decodePipeline",[]);c(this,"updated",S_);c(this,"_updateFlag",!1);this.log=R.createLogger({parent:e==null?void 0:e.getLogger(),id:"vm",userId:e==null?void 0:e.userId,sdkAppId:e==null?void 0:e.sdkAppId}),this.smallVideoContext=new Xe({frameRate:15,logger:this.log,name:"s"}),this.enablePrintDetail()}get smallMode(){var e;return((e=this.room)==null?void 0:e.smallMode)||"canvas"}get _hasVirtualBg(){return!!this._virtualBackground}get _hasWaterMark(){return this.watermarkImageList.length>0}get _isRotate(){return this._rotation!==0}get _isTransform(){return this._isMirror||this._isRotate}get renderMode(){return this._autoSwitchRenderMode?"auto":this._use2d?"2d":"webgl"}set renderMode(e){if(this._autoSwitchRenderMode=e==="auto",this._autoSwitchRenderMode)return;let t=e==="2d";this._use2d!==t&&(this._use2d=t,this.clear(),this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.update())}get cameraResolution(){var r;let{width:e,height:t}=((r=this.cameraTrack)==null?void 0:r.settings)||{};return bt(this._rotation)?{width:t,height:e}:{width:e,height:t}}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new Xe({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this._2dVideoContext}getGlVideoContext(){if(!this._glVideoContext)this._glVideoContext=new Be({frameRate:15,logger:this.log,name:"m"});else if(this._glVideoContext.available)return this._glVideoContext;return this.initializeGlVideoContext(),this._glVideoContext}initializeGlVideoContext(){try{this._glVideoContext.create(yl<=22),this._glVideoContext.on(Be.UNAVAILABLE,e=>{var t;this.emit("error",e),this.log.warn("video context unavailable",e),(t=this._virtualBackgroundAbortCallback)==null||t.call(this,e),this.update().catch(r=>{this.log.error(r)})})}catch(e){this.emit("error",e)}}initVirtualBackground(e,t,r){this.onAbort=e,this._mat4=t,this._postProcessing=r}enablePrintDetail(e=2e3){this._checkId=oe.run("interval",()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:e})}destroy(){var e,t;(e=this._2dVideoContext)==null||e.destroy(),(t=this._glVideoContext)==null||t.destroy(),this.smallVideoContext.destroy(),oe.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(Ft||this._isMixScreen||this._isTransform||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}sendCreateResult(e="videoCtxGl",t){let r=e==="videoCtxGl"?512700:512701;t?y.addFailedEvent({key:r,error:t}):y.addSuccessEvent({key:r})}checkOrCreateVideoContext(){let e=this._use2d;if(this._autoSwitchRenderMode&&(this._use2d=!this._hasVirtualBg),this.videoContext)if(this.videoContext.available){let t=!this.videoContext.hasAlpha&&this.needAlpha;if(this._autoSwitchRenderMode&&e===this._hasVirtualBg)this.clear();else if(t)if(this._use2d)this.clear();else return!0;else return!0}else{if(this._glVideoContext=new Be({frameRate:15,logger:this.log,name:"m"}),this.initializeGlVideoContext(),this._glVideoContext.available)return this.videoContext=this._glVideoContext,this.videoContext.available;this.log.warn("webgl is still not available"),this.clear(),this._use2d=!0}return this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.videoContext.available}get smallTrack(){var e;return(e=this.smallDestination)==null?void 0:e.videoTrack}get hasSmall(){return!!this.smallTrack}get initialTrack(){var e;return(e=this.cameraTrack)==null?void 0:e.mediaTrack}setSmallVideo(e,t){if(this.smallMode!=="api")if(e){if(!this.smallVideoContext.available){if(this.smallVideoContext.create({alpha:!1}),!this.smallVideoContext.available)return;this.smallDestination=new Yd(this.smallVideoContext,e,this.log),this.smallVideoContext.on(Be.UNAVAILABLE,r=>{this.log.warn("small video context lost",r)})}if(this.smallVideoContext.frameRate=e.frameRate,this.smallDestination.resolution=e,t)this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=t:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(t),this.smallImageSource.resize(t.width,t.height),this.smallImageSource.connect(this.smallDestination));else if(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource)this.smallTrackSource.replaceTrack(this.initialTrack);else{this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack,"smallTrackSource");let{width:r,height:s}=this.cameraTrack.settings;this.smallTrackSource.resize(r,s),this.smallTrackSource.connect(this.smallDestination)}}else this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource)}_setMainOutput(e){var t;try{let r=this.cameraTrack,{small:s,player:n}=r;Ft&&n.setCanvas(e);let a=e&&((t=this.destination)==null?void 0:t.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),a=this.arTrack),this.log.info(`set main output ${a?a.label:"no output track"}`),this.setSmallVideo(s,e),r.setOutputMediaStreamTrack(a)}catch(r){this.log.error("set main output failed",r)}}update(e=!1){return f(this,null,function*(){var s;if(!this.cameraTrack||!this.initialTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:t,profile:r}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams)this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log}),this.destination.on(Pe.RENDER,n=>{var a;(a=this.cameraTrack)==null||a.emit("render",n)})),et===16?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof Wt?(this.cameraNode.close(),delete this.cameraNode):this.cameraNode.image=this.initialTrack.canvas),this.cameraNode||(this.cameraNode=this.videoContext.createVideoImageSource(this.initialTrack.canvas,{name:"cameraCanvasSource",logger:this.log}))):(this.cameraNode&&(this.cameraNode instanceof Wt?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode.close(),delete this.cameraNode)),this.cameraNode||(this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraTrackSource"))):this.cameraNode?this.cameraNode.replaceTrack(this.initialTrack):this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraNodeSource"),this.cameraNode.resize(t.width,t.height);else if(e&&this.cameraNode&&this.destination)this.cameraNode.replaceTrack(this.initialTrack);else{this.cameraNode&&this.cameraNode.close(),this.destination?this.destination.disableCheckMute():(this.destination=new Qd(this.videoContext,{name:"mainDestination",logger:this.log}),this.destination.on(Pe.RENDER,l=>{var u;(u=this.cameraTrack)==null||u.emit("render",l)}));let{width:n,height:a}=this.cameraResolution,d=yield this.getWatermarkImage(n,a);this._waterMarkOption={x:0,y:0,width:d.width,height:d.height,image:d},this.cameraNode=new Mc(this.videoContext,{input:this.initialTrack,width:n,height:a,mirror:this._isMirror,rotation:this._rotation,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,beautyParams:this._beautyParams,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,Wasm:this.Wasm,enableFaceCentering:this._enableFaceCentering,enableEffectOptimization:this._enableEffectOptimization,onAbort:this.onAbort,mat4:this._mat4,postProcessing:this._postProcessing,color:this._color}),this.cameraNode.connect(this.destination),this.destination.enableCheckMute(),yield this.cameraNode.predictReady}if(this.videoContext.frameRate=r.frameRate,this._use2d){let n=this.cameraNode;if(n.disconnect(),this._isTransform&&(this.transformNode?(this.transformNode.mirror=this._isMirror,this.transformNode.rotation=this._rotation):this.transformNode=new Gt(this.videoContext,this.log,this._isMirror,this._rotation),n=n.connect(this.transformNode),n.disconnect(),this.log.info(`start mirror ${this._isMirror} rotate ${this.rotation}`)),this.mixNode&&this.mixNode.close(),delete this.mixNode,this._isMixScreen||this._hasWaterMark){if(this.mixNode=new _s(this.videoContext,this.log),n.connect(this.mixNode,{zIndex:1}),this._hasWaterMark&&!this.waterMarkNode&&this._waterMarkOption)this.waterMarkNode=this.videoContext.createVideoImageSource(this._waterMarkOption.image,{autoResize:!1,logger:this.log}),this.waterMarkNode.resize(this._waterMarkOption.width,this._waterMarkOption.height),this.waterMarkNode.x=this._waterMarkOption.x,this.waterMarkNode.y=this._waterMarkOption.y;else if(this.waterMarkNode){let{width:d,height:l}=this.cameraResolution;this.waterMarkNode.image=yield this.getWatermarkImage(d,l),d&&l&&this.waterMarkNode.resize(d,l)}(s=this.waterMarkNode)==null||s.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&(this.screenNode||(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource"),this.screenNode.resize(this.screenTrack.settings.width,this.screenTrack.settings.height)),this.screenNode.shouldUpdate=!1,this.screenNode.connect(this.mixNode,{zIndex:0})),n=this.mixNode,this.log.info("start mix",`${this.mixNode.width}x${this.mixNode.height}`)}n.connect(this.destination)}return this.log.info(`update ${this._use2d?"2d":"webgl"}`),this._setMainOutput(this.videoContext.canvas)})}clearLastFrame(){var e;this.destination&&((e=this.destination.ctx2d)==null||e.clearRect(0,0,this.destination.width,this.destination.height))}changeInput(e){var t,r,s,n,a;if(e instanceof Pt)return this.log.info("change screen input",(t=e.mediaTrack)==null?void 0:t.label),this.setScreenTrack(e);if(e instanceof je)return this.log.info("change video input",(r=e.mediaTrack)==null?void 0:r.label),this.setCameraTrack(e);if(e instanceof Pi){this.log.info("change remote input",(s=e.mediaTrack)==null?void 0:s.label);let d=e.mediaTrack;return e.setOutputMediaStreamTrack(d)}if(e instanceof go)return this.log.info("change mix input",(n=e.outMediaTrack)==null?void 0:n.label),this.setMixTrack(e);this.log.warn("change unknown input",(a=e.mediaTrack)==null?void 0:a.label)}removeInput(e){var t;e instanceof Pt?((t=this.screenNode)==null||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof je?this._isMixScreen?(delete this.cameraNode,this.cameraTrack._inputTrack=null,this.update()):(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof Pi?e.source&&e.source.context.destroy():e instanceof go&&(delete this.mixTrack,this.update())}setMixTrack(e){this.mixTrack=e}setCameraTrack(e){return this.cameraTrack=e,this.update(!0)}setScreenTrack(e){return f(this,null,function*(){return this.screenTrack=e,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):yield this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)})}getWatermarkImage(e,t){return f(this,null,function*(){let r=document.createElement("canvas");t&&e&&(r.height=t,r.width=e);let s=r.getContext("2d");if(!s)throw new v({code:I.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort((n,a)=>n.zIndex-a.zIndex),this.watermarkImageList.forEach(({image:n,x:a,y:d,width:l,height:u,fillVideo:h})=>{let p=h&&e||l,m=h&&t||u,g=h?0:a,E=h?0:d;s.drawImage(n,g,E,p,m)}),Bo(r.toDataURL())})}pushWaterMarkImageList(e){let{type:t}=e;this.watermarkImageList.some(s=>s.imageUrl===e.imageUrl&&s.height===e.height&&s.width===e.width&&s.x===e.x&&s.y===e.y&&s.type===e.type&&s.zIndex===e.zIndex&&s.fillVideo===e.fillVideo)||((t==="mute"||t==="watermark")&&(this.watermarkImageList=this.watermarkImageList.filter(s=>s.type!==t)),this.watermarkImageList.push(e))}setBeautyParams(e){return f(this,null,function*(){this._beautyParams=e,this.update()})}stopBeauty(){return f(this,null,function*(){this._beautyParams=void 0,this.update()})}setWatermark(e){return f(this,null,function*(){let t;try{t=yield Bo((e==null?void 0:e.imageElement)||e.imageUrl)}catch(p){throw new v({code:I.INVALID_PARAMETER,message:`load image failed, url: ${e.imageUrl}`})}let{x:r=0,y:s=0,width:n=t.width,height:a=t.height,type:d="watermark",zIndex:l=2,fillVideo:u=!1}=e;this.watermarkImageList.some(p=>p.type===d)?(this.watermarkImageList=this.watermarkImageList.filter(p=>p.type!==d),this.pushWaterMarkImageList({x:r,y:s,width:n,height:a,image:t,zIndex:l,type:d,imageUrl:e.imageUrl,fillVideo:u}),t=yield this.getWatermarkImage(this.cameraResolution.width,this.cameraResolution.height),this._waterMarkOption={x:0,y:0,width:t.width,height:t.height,image:t},this.waterMarkNode?(this.waterMarkNode.x=0,this.waterMarkNode.y=0,this.waterMarkNode.resize(t.width,t.height),this.waterMarkNode.image=t):this.update()):(this.pushWaterMarkImageList({x:r,y:s,width:n,height:a,image:t,zIndex:l,type:d,imageUrl:e.imageUrl,fillVideo:u}),yield this.freshWatermark()),this.log.info("set watermark",JSON.stringify(this.watermarkImageList,(p,m)=>p==="imageUrl"?void 0:m))})}deleteWatermark(e="watermark"){return f(this,null,function*(){this.watermarkImageList=this.watermarkImageList.filter(t=>t.type!==e),this.log.info("delete watermark",e,JSON.stringify(this.watermarkImageList,(t,r)=>t==="imageUrl"?void 0:r)),yield this.freshWatermark()})}freshWatermark(){return f(this,null,function*(){var s;(s=this.waterMarkNode)==null||s.close(),delete this.waterMarkNode,delete this._waterMarkOption;let{width:e,height:t}=this.cameraResolution,r=yield this.getWatermarkImage(e,t);this._waterMarkOption={x:0,y:0,width:r.width,height:r.height,image:r},this.update()})}setVirtualBackground(e){return f(this,null,function*(){var t,r,s;if(!e)delete this._virtualBackground,delete this._virtualBackgroundAbortCallback;else{if(e.onAbort&&(this._virtualBackgroundAbortCallback=e.onAbort),this._use2d&&!this._autoSwitchRenderMode)return Promise.reject(new Error("not support virtual background in 2d mode"));this._bgAssetPath=e.assetPath,e.type==="image"?this._virtualBackground=yield Bo(e.imageUrl):(this.blurRadius=e.blurLevel||this.blurRadius||3,this._virtualBackground=e.type),this._enableFaceCentering=(t=e.enableFaceCentering)!=null?t:this._enableFaceCentering,this._enableEffectOptimization=(r=e.enableEffectOptimization)!=null?r:this._enableEffectOptimization,this._color=(s=e.color)!=null?s:[0,1,0]}if(this.log.info(`${this._virtualBackground?"start":"stop"} virtual background, ${(e==null?void 0:e.type)||""}, ${this.blurRadius||""}`),yield this.update(),this._virtualBackground&&!this._glVideoContext.available)throw new v({code:I.INVALID_OPERATION,message:`webgl context create failed, ${this._glVideoContext.error}`})})}get mixScreen(){return this._isMixScreen}set mixScreen(e){var t;this._isMixScreen=e,this._isMixScreen||((t=this.screenNode)==null||t.close(),delete this.screenNode),this.update()}set mirror(e){var t;this._isMirror!==e&&(this._isMirror=e,this._isTransform||((t=this.transformNode)==null||t.close(),delete this.transformNode),this.update())}get mirror(){return this._isMirror}set rotation(e){var t;this._rotation!==e&&(this._rotation=e,this._isTransform||((t=this.transformNode)==null||t.close(),delete this.transformNode),this.update())}get rotation(){return this._rotation}enableAr(e){this.arTrack=e,this.isUsingArTrack=!0,this.update()}updateAr(){return f(this,null,function*(){var e;(e=this.cameraTrack)!=null&&e.mediaTrack&&(yield this.virtualBackgroundInstance.ar.updateInputTrack(this.cameraTrack.mediaTrack.clone()))})}disableAr(){var e;this.isUsingArTrack=!1,(e=this.arTrack)==null||e.stop(),this.arTrack=void 0,this.update()}createDecodeContext(e){return new kc(e)}clear(){var e,t;(e=this.videoContext)==null||e.disconnect(),(t=this.destination)==null||t.removeAllListeners(),delete this.destination,delete this.cameraNode,delete this.transformNode,delete this.screenNode,delete this.waterMarkNode}addEncodeProcessor({processor:e,type:t}){var r;this.encodePipeline.includes(e)||(this.encodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}addDecodeProcessor({processor:e,type:t}){var r;this.decodePipeline.includes(e)||(this.decodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}};D([Od(function(e){this.log.error("update failed",e)}),Y(e=>function(...t){return f(this,null,function*(){this._updateFlag||(this._updateFlag=!0,yield S_,this.updated=new Promise((r,s)=>{e.apply(this,t).then(r,s),setTimeout(s,5e3,new v({code:I.API_CALL_TIMEOUT,message:"update timeout"}))}),this._updateFlag=!1,yield this.updated)})})],oa.prototype,"update",1);var gI=0;var Pc=class extends j{constructor(e){super("room");c(this,"seq",++gI);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,"localPublishFlag",0);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,isH265EncodeSupported:!0,isH265DecodeSupported:!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,"smallMode","canvas");c(this,"enableChorus",!1);c(this,"_isUsingCachedSchedule",!1);c(this,"_log");c(this,"_joinedTimestamp",0);c(this,"_sdkType");c(this,"heartbeatReport");c(this,"heartbeatCount",0);c(this,"quality");c(this,"enableSEI");c(this,"isDestroyed",!1);this._log=R.createLogger({parent:e.logger,id:`r${this.seq}`}),this.useStringRoomId=!!e.useStringRoomId,ue(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),ue(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),ue(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new __({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new g_({room:this}),this.badCaseDetector=new T_({room:this}),this.audioManager=new ec(this),this.videoManager=new oa(this)}get videoCodec(){return"h264"}get scriptTransformWorker(){}get isMainStreamPublished(){for(let e of this.localTracks)if(e.mediaType&4)return!0;return!1}get isAuxStreamPublished(){for(let e of this.localTracks)if(e.mediaType&2)return!0;return!1}get hasAuxStream(){for(let e of this.remotePublishedUserMap.values())if(e.muteState.hasAuxiliary)return!0;return this.isAuxStreamPublished}get localMainAudioTrack(){for(let e of this.localTracks)if(e.mediaType&1)return e;return null}get localMainVideoTrack(){for(let e of this.localTracks)if(e.mediaType&4)return e;return null}get localAuxVideoTrack(){for(let e of this.localTracks)if(e.mediaType&2)return e;return null}get publishState(){let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};return this.localTracks.forEach(t=>{if(t.isPublished||t.isPublishing)switch(t.mediaType){case 1:e.audio=!0;break;case 4:e.bigVideo=!0,e.smallVideo=t.hasSmall;break;case 2:e.auxVideo=!0;default:break}}),e}get muteState(){var e,t,r;return{audio:!!((e=this.localMainAudioTrack)!=null&&e.muted),bigVideo:!!((t=this.localMainVideoTrack)!=null&&t.muted),auxVideo:!!((r=this.localAuxVideoTrack)!=null&&r.muted)}}getLogger(){return this._log}get isJoining(){return this.state.toString()==="joining"}get isJoined(){return this.state==="joined"}get isLeft(){return this.state==="left"}addTrack(e){return f(this,null,function*(){return this.publish(e)})}removeTrack(e){return f(this,null,function*(){return this.unpublish(e)})}replaceTrack(e){return f(this,null,function*(){})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(ie(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(dt(e)){let{websocketProxy:t,webtransportProxy:r,loggerProxy:s,scheduleProxy:n,unifiedProxy:a}=e;this.proxy_ws=t,this.proxy_wt=r,this.proxy_unified=a,a?(dc([a,a]),Fr(`https://${a}`)):(s&&Fr(s),n&&dc(n))}S.once(A.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:xi.main,sched_back_domain:xi.backup,signal_domain:this.proxy_ws||this.proxy_wt||""}))}getRemoteAudioStats(){return f(this,null,function*(){let e={};return this.remotePublishedUserMap.forEach(t=>{e[t.userId]=t.remoteAudioTrack.stat}),e})}getTransportStats(){return f(this,null,function*(){var t;let e={rtt:((t=this.quality)==null?void 0:t.uplinkRTT)||0,downlinksRTT:{}};if(this.quality)for(let r of this.quality.downlinkInfo)e.downlinksRTT[r.userId]=r.rtt;return e})}getRemoteVideoStats(){return f(this,arguments,function*(e="main"){let t={};return this.remotePublishedUserMap.forEach(r=>{let s=e==="auxiliary"?r.remoteAuxiliaryTrack:r.remoteVideoTrack;t[r.userId]=s.stat}),t})}checkDestroy(){if(this.isDestroyed)throw new v({code:I.INVALID_OPERATION,message:$({key:B.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(qe.INVALID_DESTROY),new v({code:I.INVALID_OPERATION,message:$({key:B.INVALID_DESTROY})});this._log.info("destroy room"),this.audioManager.destroy(),this.videoManager.destroy(),this.keyPointManager.destroy(),this.callDurationCalculator.destroy(),this.badCaseDetector.destroy(),this.isDestroyed=!0,S.emit(A.ROOM_DESTROY,{room:this})}schedule(e,t){return f(this,null,function*(){var s,n,a,d;let r=V();try{let{isCached:l,result:u,detailCost:h}=yield Rh({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:He,userSig:this.userSig,role:this.scene==="live"?e.role:void 0,frameWorkType:t,latencyLevel:e.latencyLevel});this._isUsingCachedSchedule=l,this._log.info(`schedule cache:${+l} ${gt(u,{keysToExclude:["username","credential"]})}`),l&&S.once(A.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=M(M({},this.scheduleResult),u),Q((s=u.config)==null?void 0:s.retryCount)&&Zc(u.config.retryCount),ie((n=u.config)==null?void 0:n.loggerDomain)&&Fr(u.config.loggerDomain),this.videoDecodeFallbackType=((a=u.config)==null?void 0:a.videoDecodeFallback)||this.videoDecodeFallbackType,this.smallMode=((d=u.config)==null?void 0:d.smallMode)||this.smallMode,S.emit(A.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:h}),y.addSuccessEvent({key:521700,cost:V()-r})}catch(l){throw y.addFailedEvent({key:521700,error:l}),l}})}sendAbilityStatus(e){}enableInsertableStreams(){return Promise.resolve()}switchRoom(e){return Promise.reject()}isSwitchRoomSupported(){return!1}};var P_=Je(nt());var rm=Je(Xh());var A_=o=>{let i=De(o),e={audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0};return i.media.forEach((t,r)=>{var s;if(t.ssrcs&&!T(t.ssrcs[0].id)){let n=Number(t.ssrcs[0].id),a=Number((s=t.ssrcs.filter(d=>d.attribute==="cname")[1])==null?void 0:s.id);switch(r){case 0:e.audioSsrc=n;break;case 1:e.bigVideoSsrc=n,e.bigVideoRtxSsrc=a;break;case 2:e.smallVideoSsrc=n,e.smallVideoRtxSsrc=a;break;case 3:e.auxVideoSsrc=n,e.auxVideoRtxSsrc=a;break}}}),e};function C_(o){var e;let i=[];for(let t=0;t<o.rtp.length;t++){if(["rtx","red","ulpfec"].includes(o.rtp[t].codec))continue;let r=o.fmtp.filter(s=>s.payload===o.rtp[t].payload)[0];i.push({payload:o.rtp[t].payload,codec:o.rtp[t].codec,fmtp:r?r.config:"",rate:o.rtp[t].rate,rtx:((e=o.rtp[t+1])==null?void 0:e.codec)==="rtx"?o.rtp[t+1].payload:0,rtcpfb:((o==null?void 0:o.rtcpFb)||[]).filter(s=>s.payload===o.rtp[t].payload).map(({type:s,subtype:n})=>({id:s,params:n?[n]:[]}))})}return i}function TI(){return f(this,null,function*(){let o=new RTCPeerConnection;o.addTransceiver(_.VIDEO,{direction:_.TRANSCEIVER_DIRECTION_RECVONLY});let i=yield o.createOffer();if(!i.sdp)return[];let e=De(i.sdp),t=C_(e.media[0]);return o.close(),t})}var R_=(o,i)=>f(void 0,null,function*(){var a;let e=De(o),t={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],decoders:[],extensions:[]},useDataChannel:!1};t.ice.ufrag=String(e.media[0].iceUfrag),t.ice.password=e.media[0].icePwd||"",e.fingerprint&&(t.dtls.hash=e.fingerprint.type,t.dtls.fingerprint=e.fingerprint.hash,t.dtls.setup=e.setup||""),e.media[0].fingerprint&&(t.dtls.hash=e.media[0].fingerprint.type,t.dtls.fingerprint=e.media[0].fingerprint.hash),t.dtls.setup=e.media[0].setup||"";let r=e.media[0],s=e.media[1];r.ext&&(t.audio.extensions=r.ext.map(d=>({id:d.value,uri:d.uri}))),s.ext&&(t.video.extensions=s.ext.map(d=>({id:d.value,uri:d.uri})));for(let d of r.rtp){if(d.codec!=="opus")continue;let l=r.fmtp.find(h=>h.payload===d.payload);if(!l)continue;let u={codec:d.codec,fmtp:l.config,payload:l.payload,rate:d.rate,channels:d.encoding,rtcpfb:[],rtx:0};(a=r.rtcpFb)==null||a.forEach(({payload:h,type:p,subtype:m})=>{if(h===u.payload){let g={id:p,params:[]};m&&g.params.push(m),u.rtcpfb.push(g)}}),t.audio.codecs.push(u);break}let n=["h264","vp8","h265"];return i&&n.shift(),t.video.codecs=[...C_(s)].filter(d=>n.includes(d.codec.toLocaleLowerCase())),t.video.decoders=(yield TI()).filter(d=>["h264","vp8","h265"].includes(d.codec.toLocaleLowerCase())),t}),y_=({serverAbility:o,clientAbility:i,offerSDP:e,enableCustomMessage:t})=>{let r=De(e),s={extmapAllowMixed:"extmap-allow-mixed",groups:r.groups,icelite:"ice-lite",media:[],msidSemantic:{semantic:"",token:"WMS"},name:"-",origin:{address:"127.0.0.1",username:"-",sessionId:String(Date.now()),sessionVersion:1,netType:"IN",ipVer:4},timing:{start:0,stop:0},version:0},n={candidates:o.candidates.map(a=>({component:1,foundation:"1",generation:0,ip:a.ip,port:a.port,priority:a.priority,transport:a.foundation,type:a.type})),connection:{version:4,ip:"0.0.0.0"},direction:_.TRANSCEIVER_DIRECTION_RECVONLY,ext:o.audio.extensions.map(a=>({value:a.id,uri:a.uri})),fingerprint:{type:o.dtls.hash,hash:o.dtls.fingerprint},fmtp:[{payload:o.audio.codecs[0].payload,config:o.audio.codecs[0].fmtp}],icePwd:o.ice.password,iceUfrag:o.ice.ufrag,mid:"0",payloads:String(o.audio.codecs[0].payload),port:r.media[0].port,protocol:r.media[0].protocol,type:_.AUDIO,setup:o.dtls.setup,rtcpFb:o.audio.codecs[0].rtcpfb.map(a=>({payload:o.audio.codecs[0].payload,type:a.id,subtype:a.params[0]})),rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[{payload:o.audio.codecs[0].payload,codec:o.audio.codecs[0].codec,rate:o.audio.codecs[0].rate,encoding:o.audio.codecs[0].channels}]};return s.media.push(n),[1,2,3].forEach(a=>{s.media.push(om({mid:a,serverAbility:o,clientAbility:i,parsedOffer:r}))}),t&&s.media.push(r.media.find(a=>a.mid==="dc")),qt(s)},om=({mid:o,serverAbility:i,clientAbility:e,parsedOffer:t,isDownlink:r=!1})=>{let s={candidates:i.candidates.map(n=>({component:1,foundation:"1",generation:0,ip:n.ip,port:n.port,priority:n.priority,transport:n.foundation,type:n.type})),connection:{version:4,ip:"0.0.0.0"},direction:_.TRANSCEIVER_DIRECTION_RECVONLY,ext:i.video.extensions.map(n=>({value:n.id,uri:n.uri})),fingerprint:{type:i.dtls.hash,hash:i.dtls.fingerprint},fmtp:[],icePwd:i.ice.password,iceUfrag:i.ice.ufrag,mid:String(o),payloads:"",port:t.media[0].port,protocol:t.media[0].protocol,type:_.VIDEO,setup:i.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(r){let n=i.video.decoders;(!n||n.length===0)&&(n=i.video.codecs),(!n||n.length===0)&&(n=e.video.decoders),n.forEach(a=>{Vr(s,a)})}else{let n;i.useH265?n=i.video.codecs.findIndex(d=>d.codec.toLowerCase()==="h265"):n=i.video.codecs.findIndex(d=>d.codec.toLowerCase()===(i.useVp8?"vp8":"h264"));let a=i.video.codecs[n]||e.video.codecs[0];Vr(s,a)}return s},Vr=(o,i)=>{o.payloads=`${o.payloads} ${i.payload}`.trim(),o.fmtp.push({payload:i.payload,config:i.fmtp}),o.rtcpFb=[...o.rtcpFb||[],...i.rtcpfb.map(e=>({payload:i.payload,type:e.id,subtype:e.params[0]}))],o.rtp.push({payload:i.payload,codec:i.codec.toUpperCase(),rate:i.rate}),i.rtx&&(o.payloads=`${o.payloads} ${i.rtx}`,o.fmtp.push({payload:i.rtx,config:`apt=${i.payload}`}),o.rtp.push({payload:i.rtx,codec:"rtx",rate:i.rate}))};function EI(o){let i=new Set(["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"]);o.ext&&(o.ext=o.ext.filter(e=>!i.has(e.uri)))}function SI(o){if(!o.rtcpFb)return;let i=[];o.rtcpFb.forEach((e,t)=>{var r;i.push(e),o.rtcpFb&&((r=o.rtcpFb[t+1])==null?void 0:r.payload)!==e.payload&&e.type!=="rrtr"&&i.push({payload:e.payload,type:"rrtr"})}),o.rtcpFb=i}function II(o){o.type===_.VIDEO&&o.fmtp&&o.fmtp.forEach(i=>{i.config.includes("apt")||(i.config+=";sps-pps-idr-in-keyframe=1")})}function AI(o){o.type===_.AUDIO&&o.fmtp&&o.fmtp.forEach(i=>{i.config+=";sprop-stereo=1;stereo=1"})}var b_=(o,i,e)=>{let t=rm.default.parse(o);return t.media.forEach((r,s)=>{var n;if((r.type===_.AUDIO||r.type===_.VIDEO)&&(SI(r),II(r),AI(r),EI(r),r.type===_.VIDEO)){if(s<4)r.payloads="",r.fmtp=[],r.rtp=[],r.rtcpFb=[],i.video.codecs.forEach(a=>Vr(r,a));else if(e){r.payloads="",r.fmtp=[],r.rtp=[],r.rtcpFb=[];let a=e.video.decoders;(!a||a.length===0)&&(a=e.video.codecs),(!a||a.length===0)&&(a=i.video.decoders),a.forEach(d=>Vr(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 N_=Je(nt());var Lc=class extends N_.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");!_e&&Ve&&S.on("262",this.onVideoCodecChanged,this),this.log=e.getLogger().createChild({id:"h-d"})}onVideoCodecChanged({remoteUserId:e,streamType:t,isHWCodec:r,codec:s}){if(!(e||t===7||s!=="h264")){if(!r){this.room.off("heartbeat-report",this.onHeartbeatReport,this);return}this.room.listeners("heartbeat-report").includes(this.onHeartbeatReport)||this.room.on("heartbeat-report",this.onHeartbeatReport,this)}}onHeartbeatReport(e){Date.now()-this.lastEmitBadHealthTime<30*1e3||(e.msg_up_stream_info.msg_video_status.forEach(t=>{if(t.uint32_video_enc_fps&&t.uint32_video_capture_fps){let r=t.uint32_video_enc_fps/t.uint32_video_capture_fps;t.uint32_video_stream_type===2&&(this.mainFpsHealth=r)}if(t.uint32_video_codec_bitrate&&t.uint32_video_stream_type===2){let{localMainVideoTrack:r}=this.room;r&&(this.mainBitrateHealth=t.uint32_video_codec_bitrate/1e3/r.profile.bitrate)}}),this.log.debug(`mainBitrateHealth: ${this.mainBitrateHealth} mainFpsHealth: ${this.mainFpsHealth}`),this.mainBitrateHealth>.5&&(this.badMainBitrateHealthCount=0),this.mainFpsHealth>.9&&this.mainBitrateHealth<.5&&(this.badMainBitrateHealthCount++,this.badMainBitrateHealthCount>3&&(this.badMainBitrateHealthCount=0,this.lastEmitBadHealthTime=Date.now(),this.log.warn(`bad main bitrate health: ${this.mainBitrateHealth}`),this.emit("1",{isAux:!1}))))}destroy(){S.off("262",this.onVideoCodecChanged,this),this.room.off("heartbeat-report",this.onHeartbeatReport,this)}};c(Lc,"EVENT_BAD_HEALTH","bad_health");var v_=Lc;function D_({seiMessageList:o,isAudio:i,getNtpTime:e,isMain:t}){return new TransformStream({transform(r,s){let n=r;i?audioEncodePipeline.forEach(a=>{n=a({frame:n,ntp:e(),onDump:()=>{self.postMessage({type:"dump",isAudio:i,data:n.data,userId:""})}})}):videoEncodePipeline.forEach(a=>{n=a({frame:n,seiMessageList:o,onDump:()=>{self.postMessage({type:"dump",isAudio:i,data:n.data,userId:"",streamType:t?"main":"auxiliary"})}})}),s.enqueue(n)}})}function M_({userId:o,streamType:i,isAudio:e}){return new TransformStream({transform(t,r){let s=t;e?(audioDecodePipeline.forEach(n=>{s=n({frame:s,onAudioFrameNTPTime:a=>{self.postMessage({type:"audio-ntp",data:a,userId:o,streamType:i})},onDump:()=>{self.postMessage({type:"dump",isAudio:e,data:s.data,userId:o})}})}),r.enqueue(s)):videoDecodePipeline.forEach(n=>{s=n({frame:s,onSEI:a=>{a.forEach(d=>{self.postMessage({type:"sei",seiPayloadType:d.seiPayloadType,data:d.seiPayload.buffer,userId:o,streamType:i})})},onDump:()=>{self.postMessage({type:"dump",isAudio:e,data:s.data,userId:o,streamType:i})}})}),r.enqueue(s)}})}function O_(o){let i=[sr],e=[wh,Lh,xh,Ph,D_,M_,ka,Oa],t=()=>{let l=[],u=[],h=[],p=0;self.onmessage=m=>{switch(m.data.type){case"sei":m.data.isMain?(l.push(m.data.data),m.data.small&&h.push(m.data.data)):u.push(m.data.data);break;case"ntp-offset":p=m.data.data;break}},self.onrtctransform=m=>{let{options:g}=m.transformer,E=g.isReceiver?M_({userId:g.userId,streamType:g.streamType,isAudio:g.isAudio}):D_({getNtpTime:()=>Date.now()+p,isAudio:g.isAudio,isMain:g.isMain,seiMessageList:g.isMain?g.small?h:l:u});m.transformer.readable.pipeThrough(E).pipeTo(m.transformer.writable)}},r=`const videoEncodePipeline=[${o.videoEncodePipeline.toString()}];
108
- const videoDecodePipeline=[${o.videoDecodePipeline.toString()}];
109
- const audioEncodePipeline = [${o.audioEncodePipeline.toString()}];
110
- const audioDecodePipeline = [${o.audioDecodePipeline.toString()}];`,s=`(()=>{${i.map(l=>`const ${l.name}=(()=>${l.toString()})()`).join(`
111
- `)}
112
- ${e.map(l=>l.toString()).join(`
113
- `)};(${t})();${r}})()`,n=new Blob([s],{type:"text/javascript"}),a=URL.createObjectURL(n),d=new Worker(a);return URL.revokeObjectURL(a),d}var Ui=(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))(Ui||{}),L_=0,x_=!1,CI=new Set,RI=o=>L_>2&&!x_&&CI.size===0&&o,yI=1,jt=class extends P_.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,"isDestroyed",!1);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);c(this,"autoSubscribedSsrcGroups",new Map);c(this,"autoSubscribedUserMap",new Map);c(this,"_h265DecodeFailed",!1);this._room=t,this._enableCustomMessage=r,this._signalChannel=e,this._log=R.createLogger({parent:this._room.getLogger(),id:`spc${yI++}`,userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableCodecPipeline&&(pi?this.enableInsertableStreams=!0:this.initScriptTransformWorker()),this._room.healthDetector.on("1",this.onBadHealth,this)}get isH264EncodeSupported(){let e=this._room.checkSystemResult.detail.isH264EncodeSupported;return this._serverAbility&&(e=e&&!!this._serverAbility.video.codecs.find(t=>t.codec.toLowerCase()==="h264")),e}addAbortController(e,t){var r;(r=this.insertableStreamsAbortMap.get(e))==null||r.abort("destroy"),this.insertableStreamsAbortMap.set(e,t)}get isVP8EncodeSupported(){let e=this._room.checkSystemResult.detail.isVp8EncodeSupported;return this._serverAbility&&(e=e&&this._serverAbility.video.codecs.find(t=>t.codec.toLowerCase()==="vp8")),e}get isH265EncodeSupported(){let e=this._room.checkSystemResult.detail.isH265EncodeSupported;return this._serverAbility&&(e=e&&!!this._serverAbility.video.codecs.find(t=>t.codec.toLowerCase()==="h265")),e}get videoCodec(){var t,r,s;let e=(t=this._parsedAnswer)==null?void 0:t.media[1].rtp.find(n=>["h264","vp8","h265"].includes(n.codec.toLowerCase()));return e?e.codec.toLowerCase():(r=this._serverAbility)!=null&&r.useH265?"h265":(s=this._serverAbility)!=null&&s.useVp8?"vp8":"h264"}get downlinkVideoCodec(){var e,t,r;return(e=this._serverAbility)!=null&&e.useH265&&((t=this._serverAbility)!=null&&t.video.decoders.find(s=>s.codec.toLowerCase()==="h265"))&&!this._h265DecodeFailed?"h265":(r=this._serverAbility)!=null&&r.video.decoders.find(s=>s.codec.toLowerCase()==="h264")?"h264":"vp8"}get isUsingH264(){return this.videoCodec==="h264"}get isUsingH265(){return this.videoCodec==="h265"}get isUsingVP8(){return this.videoCodec==="vp8"}get is42001fSupported(){return this.clientAbility?!!this.clientAbility.video.codecs.find(e=>e.fmtp.includes("42001f")):!1}get uplinkSSRC(){return this._peerConnection&&this._peerConnection.localDescription?A_(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=O_({videoEncodePipeline:this._room.videoManager.encodePipeline,videoDecodePipeline:this._room.videoManager.decodePipeline,audioEncodePipeline:this._room.audioManager.encodePipeline,audioDecodePipeline:this._room.audioManager.decodePipeline}),this.scriptTransformWorker.onmessage=e=>{e.data.type==="sei"?this.emit("sei-message",e.data):e.data.type,e.data.type==="dump"&&this.emit("dump",e.data)},this.scriptTransformWorker.onerror=e=>{this._log.error("scriptTransformWorker error: ",e.message)})}get isReconnecting(){return this.currentState==="RECONNECTING"||this._reconnectionTimer>0||this.reconnectionCount>0}get dtlsTransport(){if(!this._peerConnection)return null;let e=this._peerConnection.getSenders();return e.length===0?null:e[0].transport}getPeerConnectionConfig(e){var s;let t={encodedInsertableStreams:this.enableInsertableStreams,offerExtmapAllowMixed:!0,iceServers:e,iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._room.sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"},r=(s=this._peerConnection)==null?void 0:s.getConfiguration().encodedInsertableStreams;return Pa(r)&&(t.encodedInsertableStreams=r),this._log.debug("getPeerConnectionConfig",JSON.stringify(t)),t}initialize(e){return f(this,null,function*(){var r;let t;try{return this._peerConnection=new RTCPeerConnection(this.getPeerConnectionConfig(e)),this._peerConnection.oniceconnectionstatechange=()=>{if(!this._peerConnection)return;let s=this._peerConnection.iceConnectionState;this._log.debug(`ice state: ${s}`),s==="checking"&&this.stat.iceStartTime===0?this.stat.iceStartTime=Date.now():s==="connected"&&this.stat.iceEndTime===0?(this.stat.iceEndTime=Date.now(),this._signalChannel.clearBakRelayIps(),y.addSuccessEvent({key:521711,cost:this.stat.iceEndTime-this.stat.iceStartTime})):s==="failed"&&y.addFailedEvent({key:521711})},this._peerConnection.onsignalingstatechange=()=>{var n;let s=((n=this._peerConnection)==null?void 0:n.signalingState)||"";this._log[s==="closed"?"debug":"info"](`signaling state: ${s}`)},this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this._peerConnection.ontrack=s=>this.emit("track",s),this._enableCustomMessage&&(this._datachannel=this._peerConnection.createDataChannel(`${this._room.userId}dc`),this._datachannel.binaryType="arraybuffer",this._datachannel.onopen=()=>{this._log.info("datachannel open")},this._datachannel.onclose=()=>{this._log.warn("datachannel close")},this._datachannel.onmessage=s=>{let n=new nm(s.data);this.emit("data_channel_msg",{data:n})},this._datachannel.onerror=s=>{this._log.warn("datachannel error",s)}),this._peerConnection.addTransceiver(_.AUDIO,{direction:_.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(_.VIDEO,{direction:_.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(_.VIDEO,{direction:_.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(_.VIDEO,{direction:_.TRANSCEIVER_DIRECTION_SENDONLY}),t=yield this._peerConnection.createOffer(),this.clientAbility=yield R_(t.sdp,((r=this._room.scheduleResult.config)==null?void 0:r.remove264FromSDP)||!1),this.originOffer=t,this.dtlsTransport&&(this.dtlsTransport.onstatechange=()=>{let{dtlsTransport:s}=this;s&&(this._log.debug(`dtls state: ${s.state}`),s.state==="connecting"&&this.stat.dtlsStartTime===0?this.stat.dtlsStartTime=Date.now():s.state==="connected"&&this.stat.dtlsEndTime===0&&(this.stat.dtlsEndTime=Date.now()))}),y.addSuccessEvent({key:521707}),this.clientAbility}catch(s){throw y.addFailedEvent({key:521707,error:s}),this._log.error(`initialize failed ${s}
114
- offer: ${t==null?void 0:t.sdp}`),s}})}setIceServers(e){return f(this,null,function*(){var t;if(!(!this._peerConnection||e.length===0))try{if(this._log.info("setIceServers",JSON.stringify(e,(r,s)=>r==="username"||r==="credential"?"hided":s)),this._peerConnection.setConfiguration(this.getPeerConnectionConfig(e)),(t=this._peerConnection)!=null&&t.localDescription||!this.originOffer){this._log.warn("setIceServers already has localDescription or no origin Offer");return}yield this.setOffer(this.originOffer)}catch(r){this._log.warn("setIceServers error ",r)}})}setPriority(e="high"){if(this._peerConnection)try{this._peerConnection.getSenders().forEach(r=>{let s=r.getParameters();s.encodings[0]&&(s.encodings[0].priority=e,s.encodings[0].networkPriority=e,r.setParameters(s).catch(n=>{this._log.warn("setPriority error ",n)}))})}catch(t){this._log.warn("setPriority error ",t)}}connect(e,t=!1){return f(this,null,function*(){var r,s,n;try{if(this.currentState==="CONNECTED")return;!((r=this._peerConnection)!=null&&r.localDescription)&&this.originOffer&&(yield this.setOffer(this.originOffer));let a=V(),d={type:"answer",sdp:y_({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=((s=this._room.scheduleResult.config)==null?void 0:s.priority)||((n=this._room.joinParams)==null?void 0:n.priority)||new URLSearchParams(location.search).get("priority");l&&this.setPriority(l),t||y.addSuccessEvent({key:521703,cost:V()-a})}catch(a){let d=a instanceof v&&a.code===I.API_CALL_ABORTED;throw d||this._log.error(`connect failed: ${a}`,e),this.reset(),!d&&!this.isReconnecting&&!this.isDestroyed&&(y.addFailedEvent({key:521703,error:a}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),a}})}reconnect(){return f(this,null,function*(){if(this._reconnectionTimer!==-1){this._log.warn("reconnect() is reconnecting, ignore current reconnection");return}if(!this._signalChannel.isConnected){this._log.warn("reconnect() wait signal channel is connected"),this._signalChannel.once(Ie.CONNECTED,this.reconnect,this);return}try{this.reconnectionCount+=1,this._log.warn(`reconnect() trying [${this.reconnectionCount}]`),this.reset();let e=this._signalChannel.getBackupRelayIpPair(),t=yield this.initialize(this._room.getIceServers(e!=null&&e.iceServer?[e.iceServer]:[])),r=M({ability:t},e),s=yield this._signalChannel.sendWaitForResponse({command:Z.REBUILD_PEER_CONNECTION,responseCommand:J.REBUILD_PEER_CONNECTION_RES,data:r,enableLog:!1});if(s.data.code!==0)throw new v({code:s.data.code,message:s.data.message});yield this.connect(s.data.data.ability,!0),y.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),S.emit(A.SPC_RECONNECTED,{room:this._room}),this.emit("spc-reconnected")}catch(e){if(!this.isReconnecting||this.isDestroyed)return;if(e!=null&&e.message.includes("timeout")){let t=Zt(this.reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${t/1e3}s`),yield Ke(t,r=>{this._reconnectionTimer=r}),this.clearReconnectionTimer(),yield this.reconnect()}else this._log.error(`reconnect() failed ${e==null?void 0:e.code} ${e}`),y.addFailedEvent({key:521704,error:e}),this.reconnectionCount>=Wi()&&this._log.warn(`SDK has tried reconnect for ${Wi()} times, but all failed, please check your network`),this.stopReconnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.emit("error")}})}getPeerConnection(){return this._peerConnection}startReconnection(){return f(this,null,function*(){this.isReconnecting||(this._log.warn("start reconnect"),this._updateSDPPromise=null,this.emitConnectionStateChangedEvent("RECONNECTING"),yield this.reconnect())})}stopReconnection(){var e;this.isReconnecting&&(this._log.info("stop reconnect"),this.reconnectionCount=0,this.clearReconnectionTimer(),(e=this.clearConnectTimeout)==null||e.call(this),this._signalChannel.off(Ie.CONNECTED,this.reconnect,this),this.currentState==="RECONNECTING"&&this.emitConnectionStateChangedEvent("DISCONNECTED"))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&((e=this._peerConnection)==null?void 0:e.connectionState)===Ce.CLOSED&&this.startReconnection()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}onConnectionStateChange(e){var s;let t=((s=this._peerConnection)==null?void 0:s.iceConnectionState)||"closed",r=this.getDTLSTransportState();this._log.info(`connectionState: ${e.target.connectionState} ICE: ${t} DTLS: ${r}`),e.target.connectionState===Ce.CONNECTING&&(this.stat.peerConnectionStartTime===0&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(e.target.connectionState===Ce.FAILED||e.target.connectionState===Ce.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this._room.forceRelay?this.switchRelay(!1):this.startReconnection()),(e.target.connectionState===Ce.CONNECTED||e.target.connectionState===Ce.COMPLETED)&&(this.stat.peerConnectionEndTime===0&&(this.stat.peerConnectionEndTime=Date.now()),S.emit(A.SINGLE_CONNECTION_STAT,{room:this._room,stat:{ice:this.stat.iceEndTime-this.stat.iceStartTime,dtls:this.stat.dtlsEndTime-this.stat.dtlsStartTime,peerConnection:this.stat.peerConnectionEndTime-this.stat.peerConnectionStartTime}}),this.logSelectedCandidate(),this.emitConnectionStateChangedEvent("CONNECTED"))}getDTLSTransportState(){if(!this._peerConnection)return Qt;let e=null;return!Rr()||this._peerConnection.getSenders().length===0?Qt:(e=this._peerConnection.getSenders()[0].transport,!oo()||this._peerConnection.getReceivers().length===0?Qt:e?e.state:Qt)}emitConnectionStateChangedEvent(e){e!==this.currentState&&(this.currentState==="RECONNECTING"&&e==="CONNECTING"||(this.emit(Ui.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:e}),this.currentState=e))}logSelectedCandidate(){return f(this,null,function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[t,r]of e)if(Cr(r)){let s=e.get(r.localCandidateId),n=e.get(r.remoteCandidateId);s&&(this._log.info(`local candidate: ${s.candidateType} ${s.protocol}:${s.ip||s.address}:${s.port} ${s.networkType||""} ${s.relayProtocol?`relayProtocol:${s.relayProtocol} url: ${s.url}`:""}`),s.networkType&&ba(s.networkType)),n&&this._log.info(`remote candidate: ${n.candidateType} ${n.protocol}:${n.ip||n.address}:${n.port}`);break}})}waitForPeerConnectionConnected(){return this._waitForPCConnectedPromise?this._waitForPCConnectedPromise:(this._waitForPCConnectedPromise=new Promise((e,t)=>{if(this.currentState==="CONNECTED")return e();let r=d=>{d.state==="CONNECTED"&&(clearTimeout(a),n(),e())},s=({room:d})=>{d===this._room&&(clearTimeout(a),n(),t(new v({code:I.API_CALL_ABORTED,message:$({key:B.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{S.off(A.LEAVE_SUCCESS,s,this),this.off(Ui.CONNECTION_STATE_CHANGED,r,this)},a=setTimeout(()=>{n();let d=new v({code:I.API_CALL_TIMEOUT,message:"connection timeout"});L_+=1,RI(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),x_=!0,this.emit(Ui.FIREWALL_RESTRICTION)),t(d)},Fs);this.clearConnectTimeout=()=>{n(),clearTimeout(a),delete this.clearConnectTimeout},this.clearWaitForConnectedPromise=()=>{this._waitForPCConnectedPromise=null,t(new v({code:I.API_CALL_TIMEOUT,message:"connection timeout"}))},S.on(A.LEAVE_SUCCESS,s,this),this.on(Ui.CONNECTION_STATE_CHANGED,r,this)}),this._waitForPCConnectedPromise=this._waitForPCConnectedPromise.finally(()=>{this._waitForPCConnectedPromise=null,delete this.clearConnectTimeout}),this._waitForPCConnectedPromise)}waitForReconnected(){return this.isReconnecting?new Promise((e,t)=>{this.once("spc-reconnected",e),this.once("error",t)}):Promise.resolve()}addDownlink(e){return f(this,null,function*(){if(this._log.info(`addDownlink(${e.userId}) trying`),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise),this.updateLocalAndRemoteSDPConfig(e),this.addDownlinkQueue.size===0)try{yield this.updateSDP(),this._log.info(`addDownlink(${e.userId}) done`)}catch(t){this._log.error(`addDownlink(${e.userId}) failed ${t}`),yield this.startReconnection()}})}updateLocalAndRemoteSDPConfig({ssrc:e,userId:t,tinyId:r}){if(!this._peerConnection)return;this._log.info(`updateLocalAndRemoteSDPConfig ${t} ${JSON.stringify(e)}`);let s=this._peerConnection.getTransceivers().slice(4).filter(p=>p.direction==="inactive").slice(0,3).map(p=>(p.direction=_.TRANSCEIVER_DIRECTION_RECVONLY,Number(p.mid)));this._parsedAnswer||(this._parsedAnswer=De(this._peerConnection.remoteDescription.sdp));let n=this._parsedAnswer.media.filter(p=>{var m;return(m=p.ssrcs)==null?void 0:m.find(g=>{var E;return(E=g.value)==null?void 0:E.includes(r)})}),a,d,l;if(n.length===3)a=n[0],d=n[1],l=n[2];else if(s.length===3)a=this._parsedAnswer.media.find(p=>Number(p.mid)===Number(s[0])),d=this._parsedAnswer.media.find(p=>Number(p.mid)===Number(s[1])),l=this._parsedAnswer.media.find(p=>Number(p.mid)===Number(s[2]));else if(s.length===0){this._peerConnection.addTransceiver(_.AUDIO,{direction:_.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(_.VIDEO,{direction:_.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(_.VIDEO,{direction:_.TRANSCEIVER_DIRECTION_RECVONLY}),a=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let p=om({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:De(this._peerConnection.localDescription.sdp),isDownlink:!0});d=JSON.parse(JSON.stringify(p)),l=JSON.parse(JSON.stringify(p)),a.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(a),d.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(d),l.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(l)}a.direction=_.TRANSCEIVER_DIRECTION_SENDONLY;let u=`${r}-${e.audio}`;a.ssrcs=[{id:e.audio,attribute:"cname",value:`${u}`},{id:e.audio,attribute:"msid",value:`${u}-${_.MAIN} ${u}-audio`}],d.direction=_.TRANSCEIVER_DIRECTION_SENDONLY,d.ssrcs=[{id:e.video,attribute:"cname",value:`${u}`},{id:e.video,attribute:"msid",value:`${u}-${_.MAIN} ${u}-bigvideo`},{id:e.videoRtx,attribute:"cname",value:`${u}`},{id:e.videoRtx,attribute:"msid",value:`${u}-${_.MAIN} ${u}-bigvideo`}],d.ssrcGroups=[{semantics:"FID",ssrcs:`${e.video} ${e.videoRtx}`}],l.direction=_.TRANSCEIVER_DIRECTION_SENDONLY;let h=`${u}-aux`;l.ssrcs=[{id:e.auxiliary,attribute:"cname",value:h},{id:e.auxiliary,attribute:"msid",value:`${h} ${u}-aux${_.VIDEO}`},{id:e.auxiliaryRtx,attribute:"cname",value:`${h} ${u}-aux${_.VIDEO}`},{id:e.auxiliaryRtx,attribute:"msid",value:`${h} ${u}-aux${_.VIDEO}`}],l.ssrcGroups=[{semantics:"FID",ssrcs:`${e.auxiliary} ${e.auxiliaryRtx}`}],this._parsedAnswer.groups&&(this._parsedAnswer.groups[0].mids=this._parsedAnswer.media.map(p=>p.mid).join(" ")),this._downlinkMIDMap.set(t,[a.mid,d.mid,l.mid]),this._downlinkMIDUserIDMap.set(a.mid,t),this._downlinkMIDUserIDMap.set(d.mid,t),this._downlinkMIDUserIDMap.set(l.mid,t)}removeDownlink(e){return f(this,null,function*(){if(!this._downlinkMIDMap.has(e)||!this._peerConnection)return;this._log.info(`removeDownlink(${e}) trying`),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise);let t=this._downlinkMIDMap.get(e),r=!1;this._peerConnection.getTransceivers().forEach(s=>{t!=null&&t.includes(Number(s.mid))&&(r=!0,s.direction="inactive")}),this._parsedAnswer||(this._parsedAnswer=De(this._peerConnection.remoteDescription.sdp)),this._parsedAnswer.media.forEach(s=>{t!=null&&t.includes(Number(s.mid))&&(r=!0,s.direction="inactive",s.ssrcs=[],s.ssrcGroups=[])}),this.removeDownlinkQueue.size===0&&r&&(yield this.updateSDP()),this._downlinkMIDMap.delete(e),t==null||t.forEach(s=>this._downlinkMIDUserIDMap.delete(s)),this._log.info(`removeDownlink(${e}) done`)})}setBandwidth(e){return f(this,null,function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:r,smallVideo:s,auxVideo:n}=e;try{if(gn()){let a=this._peerConnection.getSenders().slice(0,4);for(let l=0;l<a.length;l++){let u=a[l],h;l===0&&t?h=t:l===1&&r?h=r:l===2&&s?h=s:l===3&&n&&(h=n),h&&(yield this.setSenderMaxBitrate(u,h))}let 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,s;return(r=this._peerConnection)!=null&&r.remoteDescription&&(this._parsedAnswer||(this._parsedAnswer=De(this._peerConnection.remoteDescription.sdp)),(s=this._parsedAnswer.media[e])!=null&&s.fmtp[0])?(this._parsedAnswer.media[e].fmtp[0].config+=`;x-google-start-bitrate=${t>5e3?5e3:t}`,!0):!1}setSenderMaxBitrate(e,t){let r=e.getParameters();if((!r.encodings||r.encodings.length===0)&&(r.encodings=[{}]),t==="unlimited")delete r.encodings[0].maxBitrate;else{if(r.encodings[0].maxBitrate===t*1e3)return;r.encodings[0].maxBitrate=t*1e3}return e.setParameters(r)}setBandwidthBySDP({audio:e,bigVideo:t,smallVideo:r,auxVideo:s}){if(!this._peerConnection||!this._peerConnection.localDescription)return;let n=De(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=De(this._peerConnection.remoteDescription.sdp));let a=ee?"TIAS":"AS";e&&(n.media[0].bandwidth=[{type:a,limit:ee?e*1e3:e}],this._parsedAnswer.media[0].bandwidth=[{type:a,limit:ee?e*1e3:e}]),t&&(n.media[1].bandwidth=[{type:a,limit:ee?t*1e3:t}],this._parsedAnswer.media[1].bandwidth=[{type:a,limit:ee?t*1e3:t}]),r&&(n.media[2].bandwidth=[{type:a,limit:ee?r*1e3:r}],this._parsedAnswer.media[2].bandwidth=[{type:a,limit:ee?r*1e3:r}]),s&&(n.media[3].bandwidth=[{type:a,limit:ee?s*1e3:s}],this._parsedAnswer.media[3].bandwidth=[{type:a,limit:ee?s*1e3:s}]);let d={type:"offer",sdp:qt(n)};return this.updateSDP({localDescription:d})}setScaleResolutionDownBy(e,t,r){let s=e.getParameters();(!s.encodings||s.encodings.length===0)&&(s.encodings=[{}]);let n=s.encodings[0].scaleResolutionDownBy;if(T(n)?t===1:t===n)return;let a=`setScaleResolutionDownBy ${r} ${t}`;return n&&(a+=` prevScale: ${n}`),this._log.warn(a),s.encodings[0].scaleResolutionDownBy=t,e.setParameters(s)}setDegradationPreference(e,t,r){if(Ve&&$e<83||ge&&sn(ht,"12.1")||ee&&Jo<138)return;let s=e.getParameters(),n="balanced";if(t==="motion"?n="maintain-framerate":t==="detail"&&(n="maintain-resolution"),s.degradationPreference===n)return;let a=`setDegradationPreference ${r} ${n}`;return this._log.info(a),s.degradationPreference=n,e.setParameters(s).catch(d=>this._log.warn(`${a} failed: ${d}`))}updateSDP({localDescription:e}={}){if(!this._parsedAnswer)return Promise.resolve();let t=qt(this._parsedAnswer);return this._updateSDPPromise=new Promise((r,s)=>f(this,null,function*(){var n,a;try{!e&&this._peerConnection&&(this._log.info("creating offer"),e=yield this._peerConnection.createOffer()),e&&(yield this.setOffer(e)),yield this.setAnswer({type:"answer",sdp:t}),this._updateSDPPromise=null,r()}catch(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)}
117
+ }`});d(this,"yTextureRef");d(this,"uTextureRef");d(this,"vTextureRef");d(this,"Y");d(this,"U");d(this,"V");this.useProgram();let t=this.context.ctx;t.pixelStorei(t.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),this.setTexBuffer([0,1,1,1,0,0,1,0]),this.yTextureRef=this._initTexture("ySampler",0),this.uTextureRef=this._initTexture("uSampler",1),this.vTextureRef=this._initTexture("vSampler",2),this._canvas=e._canvas}_initTexture(e,t){let r=this.context.ctx,s=r.createTexture();return r.bindTexture(r.TEXTURE_2D,s),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.bindTexture(r.TEXTURE_2D,null),r.uniform1i(r.getUniformLocation(this.program,e),t),s}render(e){let t=this.context.ctx,r=this.width,s=this.height;return this.useProgram(),t.viewport(0,0,r,s),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,this.yTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,r,s,t.LUMINANCE,t.UNSIGNED_BYTE,this.Y),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,this.uTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,r/2,s/2,t.LUMINANCE,t.UNSIGNED_BYTE,this.U),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this.vTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,r/2,s/2,t.LUMINANCE,t.UNSIGNED_BYTE,this.V),this.draw(),!0}resize(e,t){super.resize(e,t);let r=this.context.ctx;r.activeTexture(r.TEXTURE0),r.bindTexture(r.TEXTURE_2D,this.yTextureRef),r.texImage2D(r.TEXTURE_2D,0,r.LUMINANCE,e,t,0,r.LUMINANCE,r.UNSIGNED_BYTE,null),r.activeTexture(r.TEXTURE1),r.bindTexture(r.TEXTURE_2D,this.uTextureRef),r.texImage2D(r.TEXTURE_2D,0,r.LUMINANCE,e/2,t/2,0,r.LUMINANCE,r.UNSIGNED_BYTE,null),r.activeTexture(r.TEXTURE2),r.bindTexture(r.TEXTURE_2D,this.vTextureRef),r.texImage2D(r.TEXTURE_2D,0,r.LUMINANCE,e/2,t/2,0,r.LUMINANCE,r.UNSIGNED_BYTE,null)}};var M_=(o,i)=>{switch(o){case"webCodecs":return i==="videoFrame"?514705:514706;case"wasm":return i==="webgl"?514707:i==="videoFrame"?514708:514709}throw new Error("decoder type not supported")};function AI(o){return o[0]===0&&o[1]===0&&o[2]===0&&o[3]===1}var CI=0,Fd=class{constructor(i){d(this,"id",CI++);d(this,"trackDoneOB");d(this,"startOB");d(this,"stopOB");d(this,"decoder");d(this,"videoContext");d(this,"gop",0);d(this,"gop_helper",0);d(this,"waitFirstKeyFrame",!0);d(this,"startTimestamp",0);d(this,"startTime",0);d(this,"startPerformanceTime",0);d(this,"inputFrameCount",0);d(this,"decodedFrameCount",0);d(this,"decodeFrameCount",0);d(this,"downgradeLevel",0);d(this,"lastDowngradeTime",0);d(this,"lastFrameDiff",0);d(this,"lastDecodeFrameTimestamp",0);d(this,"config");d(this,"gop_before_configure",[]);d(this,"videoElement");d(this,"type","wasm");d(this,"goodType");d(this,"renderer","2d");d(this,"wasmOption");d(this,"createDecoder");d(this,"_decodeSink");d(this,"isReported",!1);d(this,"track");d(this,"stateChangeOB");d(this,"failedReason");let{track:e,createDecoder:t}=i;if(this.stateChangeOB=ot(),this.track=e,this.createDecoder=t,this.wasmOption={yuvMode:i.renderer==="webgl",wasmPath:i.wasmPath,workerMode:i.workerMode,canvas:i.canvas},this.config=i.config,this.videoElement=i.videoElement,this.renderer=i.renderer,this.trackDoneOB=le(e.availableState,j.OFF),this.stopOB=ot(),i.type==="auto"){switch(i.fallback){case"wasm":this.type="wasm",this.renderer="webgl";break;case"wasm_2d":this.type="wasm",this.renderer="2d";break;case"wasm_video":this.type="wasm",this.renderer="videoFrame";break;default:this.type="webCodecs"}this.wasmOption.yuvMode=this.renderer==="webgl"}else this.type=i.type;this.changeRenderer(this.renderer),ue(this.stateChangeOB,Eh((r,s)=>(r!==s&&e.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:this.failedReason,prevState:r,state:s}),s),"INITIALIZED"),Pe(this.stopOB),Te()),this.start()}start(i=0){this.waitFirstKeyFrame=!0,this.stateChangeOB.next("STARTING");let e=ue(this.pipe(this.track),Pe(this.stopOB),rr());ue(e,Te(()=>{this.track.stat.framesDecoded++},t=>{if(this.track.log.error(`${this.id} play failed: ${t} retryCount: ${i}`),v.addFailedEvent({key:M_(this.type,this.renderer),error:t}),i>4)this.failedReason=t,this.stateChangeOB.next("FAILED"),v.addFailedEvent({key:514704});else{if(this.goodType){this.start(i);return}switch(this.type){case"webCodecs":this.type="wasm",this.changeRenderer("webgl");break;case"wasm":switch(this.renderer){case"webgl":this.changeRenderer("videoFrame");break}}this.start(i+1)}},()=>{this.track.log.warn(`${this.id} decoderOB completed`),v.addSuccessEvent({key:M_(this.type,this.renderer)}),v.addSuccessEvent({key:514704})})),ue(e,or(1),Te(()=>{this.track.player.handlePlaying("canvas"),this.goodType=this.type,this.stateChangeOB.next("STARTED")}))}mock(i){this._decodeSink?this._decodeSink.error(i):this.start()}close(i){this.stopOB.next(i)}changeRenderer(i){this.renderer=i,this.renderer==="videoFrame"&&!Tn()&&(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(!AI(t)||t.length<5)return this.stateChangeOB.next("FAILED"),this.close(`not h26x frame ${t.subarray(0,5)}`),i;let r=t[4]&31,s=!1;switch(r){case 5:case 7:s=!0;break}if(((a=this.decoder)==null?void 0:a.state)!=="configured")return this.track.log.debug(`not configured ${this.inputFrameCount}`),s&&(this.gop_before_configure=[]),this.gop_before_configure.push({data:i.data,timestamp:i.timestamp,type:i.type}),i;this.gop_before_configure.length>0&&!e&&(this.gop_before_configure.forEach(l=>this.decode(l,!0)),this.gop_before_configure=[]);let{timestamp:n}=i;if(s?(this.gop=this.gop_helper,this.gop_helper=0):this.gop_helper++,this.decoder){if(this.waitFirstKeyFrame)if(s)this.waitFirstKeyFrame=!1,this.startTimestamp=n,this.startTime=Date.now(),this.startPerformanceTime=V();else{this.track.log.debug(`wait first key frame ${this.inputFrameCount} ${t.subarray(0,5).join(" ")}`);return}switch(this.downgradeLevel){case 0:break;case 1:break;case 2:if(this.gop_helper>this.gop>>1)return;break;case 3:if(this.gop_helper>0)return;break;default:return}(this.decodeFrameCount<10||this.decodeFrameCount%500===0)&&this.track.log.debug(`decode ${this.decodeFrameCount} gop: ${this.gop} ${n} ${(c=i.getMetadata)==null?void 0:c.call(i).rtpTimestamp}`),this.decodeFrameCount++,this.lastDecodeFrameTimestamp=n,this.decoder.decode({data:i.data,type:i.type,timestamp:this.lastDecodeFrameTimestamp});return}return i}checkDowngradeByFrameDiff(){let i=this.downgradeLevel,e=this.decodeFrameCount-this.decodedFrameCount;e>this.lastFrameDiff?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):e<=this.lastFrameDiff&&this.downgradeLevel>0&&this.downgradeLevel--,this.downgradeLevel!==i&&this.track.log.debug(`downgrade level ${i} to ${this.downgradeLevel} ${this.decodeFrameCount} frameDiff: ${e}, lastFrameDiff: ${this.lastFrameDiff}`),this.lastFrameDiff=e,this.lastDowngradeTime=Date.now()}checkDowngradeByTimestampDiff(i){let e=this.downgradeLevel;this.lastDecodeFrameTimestamp-i>9e4?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):this.downgradeLevel>0&&this.downgradeLevel--,this.downgradeLevel!==e&&this.track.log.debug(`downgrade level ${e} to ${this.downgradeLevel}`)}pipe(i){return e=>f(this,null,function*(){this._decodeSink=e;let t,r=i.mediaTrack;e.defer(()=>{var a;r&&(i.player.setCanvas(),i.setInputMediaStreamTrack(r)),t==null||t.close(),(a=this.videoContext)==null||a.destroy(),delete this._decodeSink});let{renderer:s,type:n}=this;i.log.info(`decoder type: ${this.type} renderer: ${this.renderer}`);try{switch(n){case"wasm":t=this.createDecoder(n,this.wasmOption);break;case"webCodecs":t=this.createDecoder(n);break;default:throw new Error("not supported yet")}let a=0;if(t.on("videoFrame",c=>{this.decodedFrameCount++,a++,(a<=10||a%500===0)&&i.log.debug(`frame ${a} ${this.decodedFrameCount}/${this.decodeFrameCount} decoded ${c.timestamp}`),Date.now()-this.lastDowngradeTime>5e3&&(this.type==="webCodecs"?this.checkDowngradeByFrameDiff():this.type==="wasm"&&this.checkDowngradeByTimestampDiff(c.timestamp)),e.next(c)}),t.on("error",c=>{i.log.error(c),e.error(n==="webCodecs"?4:8)}),yield t.initialize(this.videoElement),!this._decodeSink)return;if(t.configure(this.config),n==="wasm"&&s==="webgl"){this.videoContext=new He({frameRate:15,logger:i.log,name:i.userId}),this.videoContext.create(),this.videoContext.on(He.UNAVAILABLE,l=>{i.log.error(l),e.error(7)});let c=new Vd(this.videoContext);t.on("videoCodecInfo",l=>c.resize(l.width,l.height)),t.on("videoFrame",l=>{({y:c.Y,u:c.U,v:c.V}=l),this.downgradeLevel===1?this.decodedFrameCount%2===0&&c.render(this.decodedFrameCount):c.render(this.decodedFrameCount)}),i.source=c,i.player.setCanvas(this.videoContext._canvas,2)}else if(s==="videoFrame"){i.player.setCanvas();let c=new MediaStreamTrackGenerator({kind:"video"}),l=c.writable.getWriter();i.setInputMediaStreamTrack(c),t.on("videoFrame",h=>l.write(h))}else{this.videoContext=new Qe({frameRate:15,logger:i.log,name:i.userId}),this.videoContext.create({alpha:!1});let c=this.videoContext.createVideoImageSource();t.on("videoFrame",h=>{try{c.image=h,c.update()}catch(m){delete this.goodType,i.log.error(m),e.error(11)}});let l=new fo(this.videoContext,{name:"remotePlayer",logger:i.log});c.connect(l),i.source=c,i.player.setCanvas(this.videoContext._canvas,2)}this.decoder=t}catch(a){i.log.error(a),e.error(n==="webCodecs"?2:6)}})}};var O_=Promise.resolve(),ca=class extends k_.EventEmitter{constructor(e){super();this.room=e;d(this,"videoContext");d(this,"_glVideoContext");d(this,"_2dVideoContext");d(this,"destination");d(this,"smallVideoContext");d(this,"smallDestination");d(this,"smallTrackSource");d(this,"smallImageSource");d(this,"_isMirror",!1);d(this,"_rotation",0);d(this,"cameraTrack");d(this,"cameraNode");d(this,"transformNode");d(this,"mixNode");d(this,"screenTrack");d(this,"screenNode");d(this,"selfModel",!1);d(this,"blurRadius",3);d(this,"arTrack");d(this,"_enableFaceCentering",!1);d(this,"_enableEffectOptimization",!1);d(this,"onAbort");d(this,"_color");d(this,"Wasm");d(this,"waterMarkNode");d(this,"_waterMarkOption");d(this,"watermarkImageList",[]);d(this,"_beautyParams");d(this,"isUsingArTrack",!1);d(this,"mixTrack");d(this,"_isMixScreen",!1);d(this,"_virtualBackground");d(this,"_virtualBackgroundAbortCallback");d(this,"virtualBackgroundInstance");d(this,"_bgAssetPath");d(this,"log");d(this,"_mat4");d(this,"_postProcessing");d(this,"_checkId",0);d(this,"_use2d",!1);d(this,"_autoSwitchRenderMode",!0);d(this,"encodePipeline",[]);d(this,"decodePipeline",[]);d(this,"updated",O_);d(this,"_updateFlag",!1);this.log=R.createLogger({parent:e==null?void 0:e.getLogger(),id:"vm",userId:e==null?void 0:e.userId,sdkAppId:e==null?void 0:e.sdkAppId}),this.smallVideoContext=new Qe({frameRate:15,logger:this.log,name:"s"}),this.enablePrintDetail()}get smallMode(){var e;return((e=this.room)==null?void 0:e.smallMode)||"canvas"}get _hasVirtualBg(){return!!this._virtualBackground}get _hasWaterMark(){return this.watermarkImageList.length>0}get _isRotate(){return this._rotation!==0}get _isTransform(){return this._isMirror||this._isRotate}get renderMode(){return this._autoSwitchRenderMode?"auto":this._use2d?"2d":"webgl"}set renderMode(e){if(this._autoSwitchRenderMode=e==="auto",this._autoSwitchRenderMode)return;let t=e==="2d";this._use2d!==t&&(this._use2d=t,this.clear(),this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.update())}get cameraResolution(){var r;let{width:e,height:t}=((r=this.cameraTrack)==null?void 0:r.settings)||{};return bt(this._rotation)?{width:t,height:e}:{width:e,height:t}}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new Qe({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this._2dVideoContext}getGlVideoContext(){if(!this._glVideoContext)this._glVideoContext=new He({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(wl<=22),this._glVideoContext.on(He.UNAVAILABLE,e=>{var t;this.emit("error",e),this.log.warn("video context unavailable",e),(t=this._virtualBackgroundAbortCallback)==null||t.call(this,e),this.update().catch(r=>{this.log.error(r)})})}catch(e){this.emit("error",e)}}initVirtualBackground(e,t,r){this.onAbort=e,this._mat4=t,this._postProcessing=r}enablePrintDetail(e=2e3){this._checkId=oe.run("interval",()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:e})}destroy(){var e,t;(e=this._2dVideoContext)==null||e.destroy(),(t=this._glVideoContext)==null||t.destroy(),this.smallVideoContext.destroy(),oe.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(Bt||this._isMixScreen||this._isTransform||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}sendCreateResult(e="videoCtxGl",t){let r=e==="videoCtxGl"?512700:512701;t?v.addFailedEvent({key:r,error:t}):v.addSuccessEvent({key:r})}checkOrCreateVideoContext(){let e=this._use2d;if(this._autoSwitchRenderMode&&(this._use2d=!this._hasVirtualBg),this.videoContext)if(this.videoContext.available){let t=!this.videoContext.hasAlpha&&this.needAlpha;if(this._autoSwitchRenderMode&&e===this._hasVirtualBg)this.clear();else if(t)if(this._use2d)this.clear();else return!0;else return!0}else{if(this._glVideoContext=new He({frameRate:15,logger:this.log,name:"m"}),this.initializeGlVideoContext(),this._glVideoContext.available)return this.videoContext=this._glVideoContext,this.videoContext.available;this.log.warn("webgl is still not available"),this.clear(),this._use2d=!0}return this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.videoContext.available}get smallTrack(){var e;return(e=this.smallDestination)==null?void 0:e.videoTrack}get hasSmall(){return!!this.smallTrack}get initialTrack(){var e;return(e=this.cameraTrack)==null?void 0:e.mediaTrack}setSmallVideo(e,t){if(this.smallMode!=="api")if(e){if(!this.smallVideoContext.available){if(this.smallVideoContext.create({alpha:!1}),!this.smallVideoContext.available)return;this.smallDestination=new rd(this.smallVideoContext,e,this.log),this.smallVideoContext.on(He.UNAVAILABLE,r=>{this.log.warn("small video context lost",r)})}if(this.smallVideoContext.frameRate=e.frameRate,this.smallDestination.resolution=e,t)this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=t:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(t),this.smallImageSource.resize(t.width,t.height),this.smallImageSource.connect(this.smallDestination));else if(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource)this.smallTrackSource.replaceTrack(this.initialTrack);else{this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack,"smallTrackSource");let{width:r,height:s}=this.cameraTrack.settings;this.smallTrackSource.resize(r,s),this.smallTrackSource.connect(this.smallDestination)}}else this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource)}_setMainOutput(e){var t;try{let r=this.cameraTrack,{small:s,player:n}=r;Bt&&n.setCanvas(e);let a=e&&((t=this.destination)==null?void 0:t.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),a=this.arTrack),this.log.info(`set main output ${a?a.label:"no output track"}`),this.setSmallVideo(s,e),r.setOutputMediaStreamTrack(a)}catch(r){this.log.error("set main output failed",r)}}update(e=!1){return f(this,null,function*(){var s;if(!this.cameraTrack||!this.initialTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:t,profile:r}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams)this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log}),this.destination.on(Ve.RENDER,n=>{var a;(a=this.cameraTrack)==null||a.emit("render",n)})),et===16?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof Wt?(this.cameraNode.close(),delete this.cameraNode):this.cameraNode.image=this.initialTrack.canvas),this.cameraNode||(this.cameraNode=this.videoContext.createVideoImageSource(this.initialTrack.canvas,{name:"cameraCanvasSource",logger:this.log}))):(this.cameraNode&&(this.cameraNode instanceof Wt?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode.close(),delete this.cameraNode)),this.cameraNode||(this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraTrackSource"))):this.cameraNode?this.cameraNode.replaceTrack(this.initialTrack):this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraNodeSource"),this.cameraNode.resize(t.width,t.height);else if(e&&this.cameraNode&&this.destination)this.cameraNode.replaceTrack(this.initialTrack);else{this.cameraNode&&this.cameraNode.close(),this.destination?this.destination.disableCheckMute():(this.destination=new id(this.videoContext,{name:"mainDestination",logger:this.log}),this.destination.on(Ve.RENDER,l=>{var h;(h=this.cameraTrack)==null||h.emit("render",l)}));let{width:n,height:a}=this.cameraResolution,c=yield this.getWatermarkImage(n,a);this._waterMarkOption={x:0,y:0,width:c.width,height:c.height,image:c},this.cameraNode=new Ud(this.videoContext,{input:this.initialTrack,width:n,height:a,mirror:this._isMirror,rotation:this._rotation,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,beautyParams:this._beautyParams,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,Wasm:this.Wasm,enableFaceCentering:this._enableFaceCentering,enableEffectOptimization:this._enableEffectOptimization,onAbort:this.onAbort,mat4:this._mat4,postProcessing:this._postProcessing,color:this._color}),this.cameraNode.connect(this.destination),this.destination.enableCheckMute(),yield this.cameraNode.predictReady}if(this.videoContext.frameRate=r.frameRate,this._use2d){let n=this.cameraNode;if(n.disconnect(),this._isTransform&&(this.transformNode?(this.transformNode.mirror=this._isMirror,this.transformNode.rotation=this._rotation):this.transformNode=new qt(this.videoContext,this.log,this._isMirror,this._rotation),n=n.connect(this.transformNode),n.disconnect(),this.log.info(`start mirror ${this._isMirror} rotate ${this.rotation}`)),this.mixNode&&this.mixNode.close(),delete this.mixNode,this._isMixScreen||this._hasWaterMark){if(this.mixNode=new Es(this.videoContext,this.log),n.connect(this.mixNode,{zIndex:1}),this._hasWaterMark&&!this.waterMarkNode&&this._waterMarkOption)this.waterMarkNode=this.videoContext.createVideoImageSource(this._waterMarkOption.image,{autoResize:!1,logger:this.log}),this.waterMarkNode.resize(this._waterMarkOption.width,this._waterMarkOption.height),this.waterMarkNode.x=this._waterMarkOption.x,this.waterMarkNode.y=this._waterMarkOption.y;else if(this.waterMarkNode){let{width:c,height:l}=this.cameraResolution;this.waterMarkNode.image=yield this.getWatermarkImage(c,l),c&&l&&this.waterMarkNode.resize(c,l)}(s=this.waterMarkNode)==null||s.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&(this.screenNode||(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource"),this.screenNode.resize(this.screenTrack.settings.width,this.screenTrack.settings.height)),this.screenNode.shouldUpdate=!1,this.screenNode.connect(this.mixNode,{zIndex:0})),n=this.mixNode,this.log.info("start mix",`${this.mixNode.width}x${this.mixNode.height}`)}n.connect(this.destination)}return this.log.info(`update ${this._use2d?"2d":"webgl"}`),this._setMainOutput(this.videoContext.canvas)})}clearLastFrame(){var e;this.destination&&((e=this.destination.ctx2d)==null||e.clearRect(0,0,this.destination.width,this.destination.height))}changeInput(e){var t,r,s,n,a;if(e instanceof Pt)return this.log.info("change screen input",(t=e.mediaTrack)==null?void 0:t.label),this.setScreenTrack(e);if(e instanceof ze)return this.log.info("change video input",(r=e.mediaTrack)==null?void 0:r.label),this.setCameraTrack(e);if(e instanceof ki){this.log.info("change remote input",(s=e.mediaTrack)==null?void 0:s.label);let c=e.mediaTrack;return e.setOutputMediaStreamTrack(c)}if(e instanceof go)return this.log.info("change mix input",(n=e.outMediaTrack)==null?void 0:n.label),this.setMixTrack(e);this.log.warn("change unknown input",(a=e.mediaTrack)==null?void 0:a.label)}removeInput(e){var t;e instanceof Pt?((t=this.screenNode)==null||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof ze?this._isMixScreen?(delete this.cameraNode,this.cameraTrack._inputTrack=null,this.update()):(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof ki?e.source&&e.source.context.destroy():e instanceof go&&(delete this.mixTrack,this.update())}setMixTrack(e){this.mixTrack=e}setCameraTrack(e){return this.cameraTrack=e,this.update(!0)}setScreenTrack(e){return f(this,null,function*(){return this.screenTrack=e,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):yield this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)})}getWatermarkImage(e,t){return f(this,null,function*(){let r=document.createElement("canvas");t&&e&&(r.height=t,r.width=e);let s=r.getContext("2d");if(!s)throw new D({code:I.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort((n,a)=>n.zIndex-a.zIndex),this.watermarkImageList.forEach(({image:n,x:a,y:c,width:l,height:h,fillVideo:m})=>{let u=m&&e||l,_=m&&t||h,g=m?0:a,E=m?0:c;s.drawImage(n,g,E,u,_)}),$o(r.toDataURL())})}pushWaterMarkImageList(e){let{type:t}=e;this.watermarkImageList.some(s=>s.imageUrl===e.imageUrl&&s.height===e.height&&s.width===e.width&&s.x===e.x&&s.y===e.y&&s.type===e.type&&s.zIndex===e.zIndex&&s.fillVideo===e.fillVideo)||((t==="mute"||t==="watermark")&&(this.watermarkImageList=this.watermarkImageList.filter(s=>s.type!==t)),this.watermarkImageList.push(e))}setBeautyParams(e){return f(this,null,function*(){this._beautyParams=e,this.update()})}stopBeauty(){return f(this,null,function*(){this._beautyParams=void 0,this.update()})}setWatermark(e){return f(this,null,function*(){let t;try{t=yield $o((e==null?void 0:e.imageElement)||e.imageUrl)}catch(u){throw new D({code:I.INVALID_PARAMETER,message:`load image failed, url: ${e.imageUrl}`})}let{x:r=0,y:s=0,width:n=t.width,height:a=t.height,type:c="watermark",zIndex:l=2,fillVideo:h=!1}=e;this.watermarkImageList.some(u=>u.type===c)?(this.watermarkImageList=this.watermarkImageList.filter(u=>u.type!==c),this.pushWaterMarkImageList({x:r,y:s,width:n,height:a,image:t,zIndex:l,type:c,imageUrl:e.imageUrl,fillVideo:h}),t=yield this.getWatermarkImage(this.cameraResolution.width,this.cameraResolution.height),this._waterMarkOption={x:0,y:0,width:t.width,height:t.height,image:t},this.waterMarkNode?(this.waterMarkNode.x=0,this.waterMarkNode.y=0,this.waterMarkNode.resize(t.width,t.height),this.waterMarkNode.image=t):this.update()):(this.pushWaterMarkImageList({x:r,y:s,width:n,height:a,image:t,zIndex:l,type:c,imageUrl:e.imageUrl,fillVideo:h}),yield this.freshWatermark()),this.log.info("set watermark",JSON.stringify(this.watermarkImageList,(u,_)=>u==="imageUrl"?void 0:_))})}deleteWatermark(e="watermark"){return f(this,null,function*(){this.watermarkImageList=this.watermarkImageList.filter(t=>t.type!==e),this.log.info("delete watermark",e,JSON.stringify(this.watermarkImageList,(t,r)=>t==="imageUrl"?void 0:r)),yield this.freshWatermark()})}freshWatermark(){return f(this,null,function*(){var s;(s=this.waterMarkNode)==null||s.close(),delete this.waterMarkNode,delete this._waterMarkOption;let{width:e,height:t}=this.cameraResolution,r=yield this.getWatermarkImage(e,t);this._waterMarkOption={x:0,y:0,width:r.width,height:r.height,image:r},this.update()})}setVirtualBackground(e){return f(this,null,function*(){var t,r,s;if(!e)delete this._virtualBackground,delete this._virtualBackgroundAbortCallback;else{if(e.onAbort&&(this._virtualBackgroundAbortCallback=e.onAbort),this._use2d&&!this._autoSwitchRenderMode)return Promise.reject(new Error("not support virtual background in 2d mode"));this._bgAssetPath=e.assetPath,e.type==="image"?this._virtualBackground=yield $o(e.imageUrl):(this.blurRadius=e.blurLevel||this.blurRadius||3,this._virtualBackground=e.type),this._enableFaceCentering=(t=e.enableFaceCentering)!=null?t:this._enableFaceCentering,this._enableEffectOptimization=(r=e.enableEffectOptimization)!=null?r:this._enableEffectOptimization,this._color=(s=e.color)!=null?s:[0,1,0]}if(this.log.info(`${this._virtualBackground?"start":"stop"} virtual background, ${(e==null?void 0:e.type)||""}, ${this.blurRadius||""}`),yield this.update(),this._virtualBackground&&!this._glVideoContext.available)throw new D({code:I.INVALID_OPERATION,message:`webgl context create failed, ${this._glVideoContext.error}`})})}get mixScreen(){return this._isMixScreen}set mixScreen(e){var t;this._isMixScreen=e,this._isMixScreen||((t=this.screenNode)==null||t.close(),delete this.screenNode),this.update()}set mirror(e){var t;this._isMirror!==e&&(this._isMirror=e,this._isTransform||((t=this.transformNode)==null||t.close(),delete this.transformNode),this.update())}get mirror(){return this._isMirror}set rotation(e){var t;this._rotation!==e&&(this._rotation=e,this._isTransform||((t=this.transformNode)==null||t.close(),delete this.transformNode),this.update())}get rotation(){return this._rotation}enableAr(e){this.arTrack=e,this.isUsingArTrack=!0,this.update()}updateAr(){return f(this,null,function*(){var e;(e=this.cameraTrack)!=null&&e.mediaTrack&&(yield this.virtualBackgroundInstance.ar.updateInputTrack(this.cameraTrack.mediaTrack.clone()))})}disableAr(){var e;this.isUsingArTrack=!1,(e=this.arTrack)==null||e.stop(),this.arTrack=void 0,this.update()}createDecodeContext(e){return new Fd(e)}clear(){var e,t;(e=this.videoContext)==null||e.disconnect(),(t=this.destination)==null||t.removeAllListeners(),delete this.destination,delete this.cameraNode,delete this.transformNode,delete this.screenNode,delete this.waterMarkNode}addEncodeProcessor({processor:e,type:t}){var r;this.encodePipeline.includes(e)||(this.encodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}addDecodeProcessor({processor:e,type:t}){var r;this.decodePipeline.includes(e)||(this.decodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}};M([xc(function(e){this.log.error("update failed",e)}),Y(e=>function(...t){return f(this,null,function*(){this._updateFlag||(this._updateFlag=!0,yield O_,this.updated=new Promise((r,s)=>{e.apply(this,t).then(r,s),setTimeout(s,5e3,new D({code:I.API_CALL_TIMEOUT,message:"update timeout"}))}),this._updateFlag=!1,yield this.updated)})})],ca.prototype,"update",1);var RI=0;var Bd=class extends j{constructor(e){super("room");d(this,"seq",++RI);d(this,"sdkAppId");d(this,"userId");d(this,"userSig");d(this,"privateMapKey");d(this,"latencyLevel");d(this,"tinyId");d(this,"scene");d(this,"roomId");d(this,"useStringRoomId");d(this,"role","anchor");d(this,"joinParams",null);d(this,"localPublishFlag",0);d(this,"localTracks",new Set);d(this,"enableAutoPlayDialog",!0);d(this,"autoReceiveAudio",!0);d(this,"autoReceiveVideo",!0);d(this,"proxy_ws");d(this,"proxy_wt");d(this,"proxy_unified");d(this,"checkSystemResult",{result:!0,detail:{isBrowserSupported:!0,isWebRTCSupported:!0,isWebCodecsSupported:!0,isMediaDevicesSupported:!0,isScreenShareSupported:!0,isSmallStreamSupported:!0,isH264EncodeSupported:!0,isVp8EncodeSupported:!0,isH264DecodeSupported:!0,isVp8DecodeSupported:!0,isH265EncodeSupported:!0,isH265DecodeSupported:!0}});d(this,"keyPointManager");d(this,"audioManager");d(this,"videoManager");d(this,"callDurationCalculator");d(this,"badCaseDetector");d(this,"scheduleResult",{domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null});d(this,"videoDecodeFallbackType");d(this,"smallMode","canvas");d(this,"enableChorus",!1);d(this,"_isUsingCachedSchedule",!1);d(this,"_log");d(this,"_joinedTimestamp",0);d(this,"_sdkType");d(this,"heartbeatReport");d(this,"heartbeatCount",0);d(this,"quality");d(this,"enableSEI");d(this,"isDestroyed",!1);this._log=R.createLogger({parent:e.logger,id:`r${this.seq}`}),this.useStringRoomId=!!e.useStringRoomId,he(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),he(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),he(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new v_({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new N_({room:this}),this.badCaseDetector=new D_({room:this}),this.audioManager=new nd(this),this.videoManager=new ca(this)}get videoCodec(){return"h264"}get scriptTransformWorker(){}get isMainStreamPublished(){for(let e of this.localTracks)if(e.mediaType&4)return!0;return!1}get isAuxStreamPublished(){for(let e of this.localTracks)if(e.mediaType&2)return!0;return!1}get hasAuxStream(){for(let e of this.remotePublishedUserMap.values())if(e.muteState.hasAuxiliary)return!0;return this.isAuxStreamPublished}get localMainAudioTrack(){for(let e of this.localTracks)if(e.mediaType&1)return e;return null}get localMainVideoTrack(){for(let e of this.localTracks)if(e.mediaType&4)return e;return null}get localAuxVideoTrack(){for(let e of this.localTracks)if(e.mediaType&2)return e;return null}get publishState(){let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};return this.localTracks.forEach(t=>{if(t.isPublished||t.isPublishing)switch(t.mediaType){case 1:e.audio=!0;break;case 4:e.bigVideo=!0,e.smallVideo=t.hasSmall;break;case 2:e.auxVideo=!0;default:break}}),e}get muteState(){var e,t,r;return{audio:!!((e=this.localMainAudioTrack)!=null&&e.muted),bigVideo:!!((t=this.localMainVideoTrack)!=null&&t.muted),auxVideo:!!((r=this.localAuxVideoTrack)!=null&&r.muted)}}getLogger(){return this._log}get isJoining(){return this.state.toString()==="joining"}get isJoined(){return this.state==="joined"}get isLeft(){return this.state==="left"}addTrack(e){return f(this,null,function*(){return this.publish(e)})}removeTrack(e){return f(this,null,function*(){return this.unpublish(e)})}replaceTrack(e){return f(this,null,function*(){})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(re(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(dt(e)){let{websocketProxy:t,webtransportProxy:r,loggerProxy:s,scheduleProxy:n,unifiedProxy:a}=e;this.proxy_ws=t,this.proxy_wt=r,this.proxy_unified=a,a?(pd([a,a]),Br(`https://${a}`)):(s&&Br(s),n&&pd(n))}S.once(C.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:wi.main,sched_back_domain:wi.backup,signal_domain:this.proxy_ws||this.proxy_wt||""}))}getRemoteAudioStats(){return f(this,null,function*(){let e={};return this.remotePublishedUserMap.forEach(t=>{e[t.userId]=t.remoteAudioTrack.stat}),e})}getTransportStats(){return f(this,null,function*(){var t;let e={rtt:((t=this.quality)==null?void 0:t.uplinkRTT)||0,downlinksRTT:{}};if(this.quality)for(let r of this.quality.downlinkInfo)e.downlinksRTT[r.userId]=r.rtt;return e})}getRemoteVideoStats(){return f(this,arguments,function*(e="main"){let t={};return this.remotePublishedUserMap.forEach(r=>{let s=e==="auxiliary"?r.remoteAuxiliaryTrack:r.remoteVideoTrack;t[r.userId]=s.stat}),t})}checkDestroy(){if(this.isDestroyed)throw new D({code:I.INVALID_OPERATION,message:$({key:B.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(Xe.INVALID_DESTROY),new D({code:I.INVALID_OPERATION,message:$({key:B.INVALID_DESTROY})});this._log.info("destroy room"),this.audioManager.destroy(),this.videoManager.destroy(),this.keyPointManager.destroy(),this.callDurationCalculator.destroy(),this.badCaseDetector.destroy(),this.isDestroyed=!0,S.emit(C.ROOM_DESTROY,{room:this})}schedule(e,t){return f(this,null,function*(){var s,n,a,c;let r=V();try{let{isCached:l,result:h,detailCost:m}=yield kh({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:$e,userSig:this.userSig,role:this.scene==="live"?e.role:void 0,frameWorkType:t,latencyLevel:e.latencyLevel});this._isUsingCachedSchedule=l,this._log.info(`schedule cache:${+l} ${_t(h,{keysToExclude:["username","credential"]})}`),l&&S.once(C.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=O(O({},this.scheduleResult),h),Q((s=h.config)==null?void 0:s.retryCount)&&nl(h.config.retryCount),re((n=h.config)==null?void 0:n.loggerDomain)&&Br(h.config.loggerDomain),this.videoDecodeFallbackType=((a=h.config)==null?void 0:a.videoDecodeFallback)||this.videoDecodeFallbackType,this.smallMode=((c=h.config)==null?void 0:c.smallMode)||this.smallMode,S.emit(C.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:m}),v.addSuccessEvent({key:521700,cost:V()-r})}catch(l){throw v.addFailedEvent({key:521700,error:l}),l}})}sendAbilityStatus(e){}enableInsertableStreams(){return Promise.resolve()}switchRoom(e){return Promise.reject()}isSwitchRoomSupported(){return!1}};var H_=Je(at());var mm=Je(om());var P_=o=>{let i=De(o),e={audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0};return i.media.forEach((t,r)=>{var s;if(t.ssrcs&&!T(t.ssrcs[0].id)){let n=Number(t.ssrcs[0].id),a=Number((s=t.ssrcs.filter(c=>c.attribute==="cname")[1])==null?void 0:s.id);switch(r){case 0:e.audioSsrc=n;break;case 1:e.bigVideoSsrc=n,e.bigVideoRtxSsrc=a;break;case 2:e.smallVideoSsrc=n,e.smallVideoRtxSsrc=a;break;case 3:e.auxVideoSsrc=n,e.auxVideoRtxSsrc=a;break}}}),e};function w_(o){var e;let i=[];for(let t=0;t<o.rtp.length;t++){if(["rtx","red","ulpfec"].includes(o.rtp[t].codec))continue;let r=o.fmtp.filter(s=>s.payload===o.rtp[t].payload)[0];i.push({payload:o.rtp[t].payload,codec:o.rtp[t].codec,fmtp:r?r.config:"",rate:o.rtp[t].rate,rtx:((e=o.rtp[t+1])==null?void 0:e.codec)==="rtx"?o.rtp[t+1].payload:0,rtcpfb:((o==null?void 0:o.rtcpFb)||[]).filter(s=>s.payload===o.rtp[t].payload).map(({type:s,subtype:n})=>({id:s,params:n?[n]:[]}))})}return i}function yI(){return f(this,null,function*(){let o=new RTCPeerConnection;o.addTransceiver(p.VIDEO,{direction:p.TRANSCEIVER_DIRECTION_RECVONLY});let i=yield o.createOffer();if(!i.sdp)return[];let e=De(i.sdp),t=w_(e.media[0]);return o.close(),t})}var L_=(o,i)=>f(void 0,null,function*(){var a;let e=De(o),t={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],decoders:[],extensions:[]},useDataChannel:!1};t.ice.ufrag=String(e.media[0].iceUfrag),t.ice.password=e.media[0].icePwd||"",e.fingerprint&&(t.dtls.hash=e.fingerprint.type,t.dtls.fingerprint=e.fingerprint.hash,t.dtls.setup=e.setup||""),e.media[0].fingerprint&&(t.dtls.hash=e.media[0].fingerprint.type,t.dtls.fingerprint=e.media[0].fingerprint.hash),t.dtls.setup=e.media[0].setup||"";let r=e.media[0],s=e.media[1];r.ext&&(t.audio.extensions=r.ext.map(c=>({id:c.value,uri:c.uri}))),s.ext&&(t.video.extensions=s.ext.map(c=>({id:c.value,uri:c.uri})));for(let c of r.rtp){if(c.codec!=="opus")continue;let l=r.fmtp.find(m=>m.payload===c.payload);if(!l)continue;let h={codec:c.codec,fmtp:l.config,payload:l.payload,rate:c.rate,channels:c.encoding,rtcpfb:[],rtx:0};(a=r.rtcpFb)==null||a.forEach(({payload:m,type:u,subtype:_})=>{if(m===h.payload){let g={id:u,params:[]};_&&g.params.push(_),h.rtcpfb.push(g)}}),t.audio.codecs.push(h);break}let n=["h264","vp8","h265"];return i&&n.shift(),t.video.codecs=[...w_(s)].filter(c=>n.includes(c.codec.toLocaleLowerCase())),t.video.decoders=(yield yI()).filter(c=>["h264","vp8","h265"].includes(c.codec.toLocaleLowerCase())),t}),x_=({serverAbility:o,clientAbility:i,offerSDP:e,enableCustomMessage:t})=>{let r=De(e),s={extmapAllowMixed:"extmap-allow-mixed",groups:r.groups,icelite:"ice-lite",media:[],msidSemantic:{semantic:"",token:"WMS"},name:"-",origin:{address:"127.0.0.1",username:"-",sessionId:String(Date.now()),sessionVersion:1,netType:"IN",ipVer:4},timing:{start:0,stop:0},version:0},n={candidates:o.candidates.map(a=>({component:1,foundation:"1",generation:0,ip:a.ip,port:a.port,priority:a.priority,transport:a.foundation,type:a.type})),connection:{version:4,ip:"0.0.0.0"},direction:p.TRANSCEIVER_DIRECTION_RECVONLY,ext:o.audio.extensions.map(a=>({value:a.id,uri:a.uri})),fingerprint:{type:o.dtls.hash,hash:o.dtls.fingerprint},fmtp:[{payload:o.audio.codecs[0].payload,config:o.audio.codecs[0].fmtp}],icePwd:o.ice.password,iceUfrag:o.ice.ufrag,mid:"0",payloads:String(o.audio.codecs[0].payload),port:r.media[0].port,protocol:r.media[0].protocol,type:p.AUDIO,setup:o.dtls.setup,rtcpFb:o.audio.codecs[0].rtcpfb.map(a=>({payload:o.audio.codecs[0].payload,type:a.id,subtype:a.params[0]})),rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[{payload:o.audio.codecs[0].payload,codec:o.audio.codecs[0].codec,rate:o.audio.codecs[0].rate,encoding:o.audio.codecs[0].channels}]};return s.media.push(n),[1,2,3].forEach(a=>{s.media.push(pm({mid:a,serverAbility:o,clientAbility:i,parsedOffer:r}))}),t&&s.media.push(r.media.find(a=>a.mid==="dc")),jt(s)},pm=({mid:o,serverAbility:i,clientAbility:e,parsedOffer:t,isDownlink:r=!1})=>{let s={candidates:i.candidates.map(n=>({component:1,foundation:"1",generation:0,ip:n.ip,port:n.port,priority:n.priority,transport:n.foundation,type:n.type})),connection:{version:4,ip:"0.0.0.0"},direction:p.TRANSCEIVER_DIRECTION_RECVONLY,ext:i.video.extensions.map(n=>({value:n.id,uri:n.uri})),fingerprint:{type:i.dtls.hash,hash:i.dtls.fingerprint},fmtp:[],icePwd:i.ice.password,iceUfrag:i.ice.ufrag,mid:String(o),payloads:"",port:t.media[0].port,protocol:t.media[0].protocol,type:p.VIDEO,setup:i.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(r){let n=i.video.decoders;(!n||n.length===0)&&(n=i.video.codecs),(!n||n.length===0)&&(n=e.video.decoders),n.forEach(a=>{Fr(s,a)})}else{let n;i.useH265?n=i.video.codecs.findIndex(c=>c.codec.toLowerCase()==="h265"):n=i.video.codecs.findIndex(c=>c.codec.toLowerCase()===(i.useVp8?"vp8":"h264"));let a=i.video.codecs[n]||e.video.codecs[0];Fr(s,a)}return s},Fr=(o,i)=>{o.payloads=`${o.payloads} ${i.payload}`.trim(),o.fmtp.push({payload:i.payload,config:i.fmtp}),o.rtcpFb=[...o.rtcpFb||[],...i.rtcpfb.map(e=>({payload:i.payload,type:e.id,subtype:e.params[0]}))],o.rtp.push({payload:i.payload,codec:i.codec.toUpperCase(),rate:i.rate}),i.rtx&&(o.payloads=`${o.payloads} ${i.rtx}`,o.fmtp.push({payload:i.rtx,config:`apt=${i.payload}`}),o.rtp.push({payload:i.rtx,codec:"rtx",rate:i.rate}))};function bI(o){let i=new Set(["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"]);o.ext&&(o.ext=o.ext.filter(e=>!i.has(e.uri)))}function vI(o){if(!o.rtcpFb)return;let i=[];o.rtcpFb.forEach((e,t)=>{var r;i.push(e),o.rtcpFb&&((r=o.rtcpFb[t+1])==null?void 0:r.payload)!==e.payload&&e.type!=="rrtr"&&i.push({payload:e.payload,type:"rrtr"})}),o.rtcpFb=i}function NI(o){o.type===p.VIDEO&&o.fmtp&&o.fmtp.forEach(i=>{i.config.includes("apt")||(i.config+=";sps-pps-idr-in-keyframe=1")})}function DI(o){o.type===p.AUDIO&&o.fmtp&&o.fmtp.forEach(i=>{i.config+=";sprop-stereo=1;stereo=1"})}var U_=(o,i,e)=>{let t=mm.default.parse(o);return t.media.forEach((r,s)=>{var n;if((r.type===p.AUDIO||r.type===p.VIDEO)&&(vI(r),NI(r),DI(r),bI(r),r.type===p.VIDEO)){if(s<4)r.payloads="",r.fmtp=[],r.rtp=[],r.rtcpFb=[],i.video.codecs.forEach(a=>Fr(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=>Fr(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")}),mm.default.write(t)};var V_=Je(at());var Hd=class extends V_.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");!fe&&We&&S.on("262",this.onVideoCodecChanged,this),this.log=e.getLogger().createChild({id:"h-d"})}onVideoCodecChanged({remoteUserId:e,streamType:t,isHWCodec:r,codec:s}){if(!(e||t===7||s!=="h264")){if(!r){this.room.off("heartbeat-report",this.onHeartbeatReport,this);return}this.room.listeners("heartbeat-report").includes(this.onHeartbeatReport)||this.room.on("heartbeat-report",this.onHeartbeatReport,this)}}onHeartbeatReport(e){Date.now()-this.lastEmitBadHealthTime<30*1e3||(e.msg_up_stream_info.msg_video_status.forEach(t=>{if(t.uint32_video_enc_fps&&t.uint32_video_capture_fps){let r=t.uint32_video_enc_fps/t.uint32_video_capture_fps;t.uint32_video_stream_type===2&&(this.mainFpsHealth=r)}if(t.uint32_video_codec_bitrate&&t.uint32_video_stream_type===2){let{localMainVideoTrack:r}=this.room;r&&(this.mainBitrateHealth=t.uint32_video_codec_bitrate/1e3/r.profile.bitrate)}}),this.log.debug(`mainBitrateHealth: ${this.mainBitrateHealth} mainFpsHealth: ${this.mainFpsHealth}`),this.mainBitrateHealth>.5&&(this.badMainBitrateHealthCount=0),this.mainFpsHealth>.9&&this.mainBitrateHealth<.5&&(this.badMainBitrateHealthCount++,this.badMainBitrateHealthCount>3&&(this.badMainBitrateHealthCount=0,this.lastEmitBadHealthTime=Date.now(),this.log.warn(`bad main bitrate health: ${this.mainBitrateHealth} fps health: ${this.mainFpsHealth}`),this.emit("1",{isAux:!1}))))}destroy(){S.off("262",this.onVideoCodecChanged,this),this.room.off("heartbeat-report",this.onHeartbeatReport,this)}};d(Hd,"EVENT_BAD_HEALTH","bad_health");var F_=Hd;var xi=(l=>(l.TRACK="track",l.DATA_CHANNEL_MESSAGE="data_channel_msg",l[l.CONNECTION_STATE_CHANGED="connection-state-changed"]="CONNECTION_STATE_CHANGED",l[l.FIREWALL_RESTRICTION="firewall-restriction"]="FIREWALL_RESTRICTION",l.RECONNECTED="spc-reconnected",l.RECONNECT_FAILED="spc-reconnect-failed",l.ERROR="error",l.SEI_MESSAGE="sei-message",l.DUMP="dump",l))(xi||{}),$_=0,G_=!1,MI=new Set,OI=o=>$_>2&&!G_&&MI.size===0&&o,kI=1,Xt=class extends H_.default{constructor({signalChannel:e,room:t,enableCustomMessage:r}){super();d(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0});d(this,"isDestroyed",!1);d(this,"currentState","DISCONNECTED");d(this,"_room");d(this,"_signalChannel");d(this,"_peerConnection",null);d(this,"_datachannel",null);d(this,"_enableCustomMessage");d(this,"_log");d(this,"_downlinkMIDMap",new Map);d(this,"_downlinkMIDUserIDMap",new Map);d(this,"_reconnectionTimer",-1);d(this,"reconnectionCount",0);d(this,"clientAbility");d(this,"_serverAbility",null);d(this,"addDownlinkQueue",new Set);d(this,"removeDownlinkQueue",new Set);d(this,"_parsedAnswer",null);d(this,"_updateSDPPromise",null);d(this,"_waitForPCConnectedPromise");d(this,"clearWaitForConnectedPromise");d(this,"clearConnectTimeout");d(this,"_isSDPLogged",!1);d(this,"enableInsertableStreams",!1);d(this,"insertableStreamsAbortMap",new Map);d(this,"receiverRemoteTrackMap",new WeakMap);d(this,"scriptTransformWorker");d(this,"_isRelayTried",!1);d(this,"_rttOverCount",0);d(this,"originOffer",null);d(this,"autoSubscribedSsrcGroups",new Map);d(this,"autoSubscribedUserMap",new Map);d(this,"_h265DecodeFailed",!1);this._room=t,this._enableCustomMessage=r,this._signalChannel=e,this._log=R.createLogger({parent:this._room.getLogger(),id:`spc${kI++}`,userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableCodecPipeline&&(mi?this.enableInsertableStreams=!0:this.initScriptTransformWorker()),this._room.healthDetector.on("1",this.onBadHealth,this)}get isH264EncodeSupported(){let e=this._room.checkSystemResult.detail.isH264EncodeSupported;return this._serverAbility&&(e=e&&!!this._serverAbility.video.codecs.find(t=>t.codec.toLowerCase()==="h264")),e}addAbortController(e,t){var r;(r=this.insertableStreamsAbortMap.get(e))==null||r.abort("destroy"),this.insertableStreamsAbortMap.set(e,t)}get isVP8EncodeSupported(){let e=this._room.checkSystemResult.detail.isVp8EncodeSupported;return this._serverAbility&&(e=e&&this._serverAbility.video.codecs.find(t=>t.codec.toLowerCase()==="vp8")),e}get isH265EncodeSupported(){let e=this._room.checkSystemResult.detail.isH265EncodeSupported;return this._serverAbility&&(e=e&&!!this._serverAbility.video.codecs.find(t=>t.codec.toLowerCase()==="h265")),e}get videoCodec(){var t,r,s;let e=(t=this._parsedAnswer)==null?void 0:t.media[1].rtp.find(n=>["h264","vp8","h265"].includes(n.codec.toLowerCase()));return e?e.codec.toLowerCase():(r=this._serverAbility)!=null&&r.useH265?"h265":(s=this._serverAbility)!=null&&s.useVp8?"vp8":"h264"}get downlinkVideoCodec(){var e,t,r;return(e=this._serverAbility)!=null&&e.useH265&&((t=this._serverAbility)!=null&&t.video.decoders.find(s=>s.codec.toLowerCase()==="h265"))&&!this._h265DecodeFailed?"h265":(r=this._serverAbility)!=null&&r.video.decoders.find(s=>s.codec.toLowerCase()==="h264")?"h264":"vp8"}get isUsingH264(){return this.videoCodec==="h264"}get isUsingH265(){return this.videoCodec==="h265"}get isUsingVP8(){return this.videoCodec==="vp8"}get is42001fSupported(){return this.clientAbility?!!this.clientAbility.video.codecs.find(e=>e.fmtp.includes("42001f")):!1}get uplinkSSRC(){return this._peerConnection&&this._peerConnection.localDescription?P_(this._peerConnection.localDescription.sdp):{audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0}}onBadHealth({isAux:e}){}initScriptTransformWorker(){as&&(this.scriptTransformWorker=_d({videoEncodePipeline:this._room.videoManager.encodePipeline,videoDecodePipeline:this._room.videoManager.decodePipeline,audioEncodePipeline:this._room.audioManager.encodePipeline,audioDecodePipeline:this._room.audioManager.decodePipeline}),this.scriptTransformWorker.onmessage=e=>{e.data.type==="sei"?this.emit("sei-message",e.data):e.data.type,e.data.type==="dump"&&this.emit("dump",e.data)},this.scriptTransformWorker.onerror=e=>{this._log.error("scriptTransformWorker error: ",e.message)})}get isReconnecting(){return this.currentState==="RECONNECTING"||this._reconnectionTimer>0||this.reconnectionCount>0}get dtlsTransport(){if(!this._peerConnection)return null;let e=this._peerConnection.getSenders();return e.length===0?null:e[0].transport}getPeerConnectionConfig(e){var s;let t={encodedInsertableStreams:this.enableInsertableStreams,offerExtmapAllowMixed:!0,iceServers:e,iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._room.sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"},r=(s=this._peerConnection)==null?void 0:s.getConfiguration().encodedInsertableStreams;return Ua(r)&&(t.encodedInsertableStreams=r),this._log.debug("getPeerConnectionConfig",JSON.stringify(t)),t}initialize(e){return f(this,null,function*(){var r;let t;try{return this._peerConnection=new RTCPeerConnection(this.getPeerConnectionConfig(e)),this._peerConnection.oniceconnectionstatechange=()=>{if(!this._peerConnection)return;let s=this._peerConnection.iceConnectionState;this._log.debug(`ice state: ${s}`),s==="checking"&&this.stat.iceStartTime===0?this.stat.iceStartTime=Date.now():s==="connected"&&this.stat.iceEndTime===0?(this.stat.iceEndTime=Date.now(),this._signalChannel.clearBakRelayIps(),v.addSuccessEvent({key:521711,cost:this.stat.iceEndTime-this.stat.iceStartTime})):s==="failed"&&v.addFailedEvent({key:521711})},this._peerConnection.onsignalingstatechange=()=>{var n;let s=((n=this._peerConnection)==null?void 0:n.signalingState)||"";this._log[s==="closed"?"debug":"info"](`signaling state: ${s}`)},this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this._peerConnection.ontrack=s=>this.emit("track",s),this._enableCustomMessage&&(this._datachannel=this._peerConnection.createDataChannel(`${this._room.userId}dc`),this._datachannel.binaryType="arraybuffer",this._datachannel.onopen=()=>{this._log.info("datachannel open")},this._datachannel.onclose=()=>{this._log.warn("datachannel close")},this._datachannel.onmessage=s=>{let n=new _m(s.data);this.emit("data_channel_msg",{data:n})},this._datachannel.onerror=s=>{this._log.warn("datachannel error",s)}),this._peerConnection.addTransceiver(p.AUDIO,{direction:p.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(p.VIDEO,{direction:p.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(p.VIDEO,{direction:p.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(p.VIDEO,{direction:p.TRANSCEIVER_DIRECTION_SENDONLY}),t=yield this._peerConnection.createOffer(),this.clientAbility=yield L_(t.sdp,((r=this._room.scheduleResult.config)==null?void 0:r.remove264FromSDP)||!1),this.originOffer=t,this.dtlsTransport&&(this.dtlsTransport.onstatechange=()=>{let{dtlsTransport:s}=this;s&&(this._log.debug(`dtls state: ${s.state}`),s.state==="connecting"&&this.stat.dtlsStartTime===0?this.stat.dtlsStartTime=Date.now():s.state==="connected"&&this.stat.dtlsEndTime===0&&(this.stat.dtlsEndTime=Date.now()))}),v.addSuccessEvent({key:521707}),this.clientAbility}catch(s){throw v.addFailedEvent({key:521707,error:s}),this._log.error(`initialize failed ${s}
118
+ offer: ${t==null?void 0:t.sdp}`),s}})}setIceServers(e){return f(this,null,function*(){var t;if(!(!this._peerConnection||e.length===0))try{if(this._log.info("setIceServers",JSON.stringify(e,(r,s)=>r==="username"||r==="credential"?"hided":s)),this._peerConnection.setConfiguration(this.getPeerConnectionConfig(e)),(t=this._peerConnection)!=null&&t.localDescription||!this.originOffer){this._log.warn("setIceServers already has localDescription or no origin Offer");return}yield this.setOffer(this.originOffer)}catch(r){this._log.warn("setIceServers error ",r)}})}setPriority(e="high"){if(this._peerConnection)try{this._peerConnection.getSenders().forEach(r=>{let s=r.getParameters();s.encodings[0]&&(s.encodings[0].priority=e,s.encodings[0].networkPriority=e,r.setParameters(s).catch(n=>{this._log.warn("setPriority error ",n)}))})}catch(t){this._log.warn("setPriority error ",t)}}connect(e,t=!1){return f(this,null,function*(){var r,s,n,a;try{if(this.currentState==="CONNECTED")return;!((r=this._peerConnection)!=null&&r.localDescription)&&this.originOffer&&(yield this.setOffer(this.originOffer));let c=V();if(((s=this._room.joinParams)==null?void 0:s.videoProfileLevel)==="high"&&!Fl()){let m=this.clientAbility.video.codecs.find(u=>u.fmtp.includes("profile-level-id=64"));if(m){let u=e.video.codecs.findIndex(_=>_.codec.toLowerCase()===m.codec.toLowerCase());e.video.codecs[u]=JSON.parse(JSON.stringify(m)),this._log.warn("set new profile level id",m)}}let l={type:"answer",sdp:x_({serverAbility:e,clientAbility:this.clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(l),yield this.waitForPeerConnectionConnected();let h=((n=this._room.scheduleResult.config)==null?void 0:n.priority)||((a=this._room.joinParams)==null?void 0:a.priority)||new URLSearchParams(location.search).get("priority");h&&this.setPriority(h),t||v.addSuccessEvent({key:521703,cost:V()-c})}catch(c){let l=c instanceof D&&c.code===I.API_CALL_ABORTED;throw l||this._log.error(`connect failed: ${c}`,e),this.reset(),!l&&!this.isReconnecting&&!this.isDestroyed&&(v.addFailedEvent({key:521703,error:c}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),c}})}reconnect(){return f(this,null,function*(){if(this._reconnectionTimer!==-1){this._log.warn("reconnect() is reconnecting, ignore current reconnection");return}if(!this._signalChannel.isConnected){this._log.warn("reconnect() wait signal channel is connected"),this._signalChannel.once(Ie.CONNECTED,this.reconnect,this);return}try{this.reconnectionCount+=1,this._log.warn(`reconnect() trying [${this.reconnectionCount}]`),this.reset();let e=this._signalChannel.getBackupRelayIpPair(),t=yield this.initialize(this._room.getIceServers(e!=null&&e.iceServer?[e.iceServer]:[])),r=O({ability:t},e),s=yield this._signalChannel.sendWaitForResponse({command:Z.REBUILD_PEER_CONNECTION,responseCommand:W.REBUILD_PEER_CONNECTION_RES,data:r,enableLog:!1});if(s.data.code!==0)throw new D({code:s.data.code,message:s.data.message});yield this.connect(s.data.data.ability,!0),v.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),S.emit(C.SPC_RECONNECTED,{room:this._room}),this.emit("spc-reconnected")}catch(e){if(!this.isReconnecting||this.isDestroyed)return;if(e!=null&&e.message.includes("timeout")){let t=Kt(this.reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${t/1e3}s`),yield Ge(t,r=>{this._reconnectionTimer=r}),this.clearReconnectionTimer(),yield this.reconnect()}else this._log.error(`reconnect() failed ${e==null?void 0:e.code} ${e}`),v.addFailedEvent({key:521704,error:e}),this.reconnectionCount>=Hi()&&this._log.warn(`SDK has tried reconnect for ${Hi()} times, but all failed, please check your network`),this.stopReconnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.emit("error")}})}getPeerConnection(){return this._peerConnection}startReconnection(){return f(this,null,function*(){this.isReconnecting||(this._log.warn("start reconnect"),this._updateSDPPromise=null,this.emitConnectionStateChangedEvent("RECONNECTING"),yield this.reconnect())})}stopReconnection(){var e;this.isReconnecting&&(this._log.info("stop reconnect"),this.reconnectionCount=0,this.clearReconnectionTimer(),(e=this.clearConnectTimeout)==null||e.call(this),this._signalChannel.off(Ie.CONNECTED,this.reconnect,this),this.currentState==="RECONNECTING"&&this.emitConnectionStateChangedEvent("DISCONNECTED"))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&((e=this._peerConnection)==null?void 0:e.connectionState)===ye.CLOSED&&this.startReconnection()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}onConnectionStateChange(e){var s;let t=((s=this._peerConnection)==null?void 0:s.iceConnectionState)||"closed",r=this.getDTLSTransportState();this._log.info(`connectionState: ${e.target.connectionState} ICE: ${t} DTLS: ${r}`),e.target.connectionState===ye.CONNECTING&&(this.stat.peerConnectionStartTime===0&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(e.target.connectionState===ye.FAILED||e.target.connectionState===ye.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this._room.forceRelay?this.switchRelay(!1):this.startReconnection()),(e.target.connectionState===ye.CONNECTED||e.target.connectionState===ye.COMPLETED)&&(this.stat.peerConnectionEndTime===0&&(this.stat.peerConnectionEndTime=Date.now()),S.emit(C.SINGLE_CONNECTION_STAT,{room:this._room,stat:{ice:this.stat.iceEndTime-this.stat.iceStartTime,dtls:this.stat.dtlsEndTime-this.stat.dtlsStartTime,peerConnection:this.stat.peerConnectionEndTime-this.stat.peerConnectionStartTime}}),this.logSelectedCandidate(),this.emitConnectionStateChangedEvent("CONNECTED"))}getDTLSTransportState(){if(!this._peerConnection)return Yt;let e=null;return!yr()||this._peerConnection.getSenders().length===0?Yt:(e=this._peerConnection.getSenders()[0].transport,!oo()||this._peerConnection.getReceivers().length===0?Yt:e?e.state:Yt)}emitConnectionStateChangedEvent(e){e!==this.currentState&&(this.currentState==="RECONNECTING"&&e==="CONNECTING"||(this.emit(xi.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:e}),this.currentState=e))}logSelectedCandidate(){return f(this,null,function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[t,r]of e)if(Rr(r)){let s=e.get(r.localCandidateId),n=e.get(r.remoteCandidateId);s&&(this._log.info(`local candidate: ${s.candidateType} ${s.protocol}:${s.ip||s.address}:${s.port} ${s.networkType||""} ${s.relayProtocol?`relayProtocol:${s.relayProtocol} url: ${s.url}`:""}`),s.networkType&&Ma(s.networkType)),n&&this._log.info(`remote candidate: ${n.candidateType} ${n.protocol}:${n.ip||n.address}:${n.port}`);break}})}waitForPeerConnectionConnected(){return this._waitForPCConnectedPromise?this._waitForPCConnectedPromise:(this._waitForPCConnectedPromise=new Promise((e,t)=>{if(this.currentState==="CONNECTED")return e();let r=c=>{c.state==="CONNECTED"&&(clearTimeout(a),n(),e())},s=({room:c})=>{c===this._room&&(clearTimeout(a),n(),t(new D({code:I.API_CALL_ABORTED,message:$({key:B.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{S.off(C.LEAVE_SUCCESS,s,this),this.off(xi.CONNECTION_STATE_CHANGED,r,this)},a=setTimeout(()=>{n();let c=new D({code:I.API_CALL_TIMEOUT,message:"connection timeout"});$_+=1,OI(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),G_=!0,this.emit(xi.FIREWALL_RESTRICTION)),t(c)},$s);this.clearConnectTimeout=()=>{n(),clearTimeout(a),delete this.clearConnectTimeout},this.clearWaitForConnectedPromise=()=>{this._waitForPCConnectedPromise=null,t(new D({code:I.API_CALL_TIMEOUT,message:"connection timeout"}))},S.on(C.LEAVE_SUCCESS,s,this),this.on(xi.CONNECTION_STATE_CHANGED,r,this)}),this._waitForPCConnectedPromise=this._waitForPCConnectedPromise.finally(()=>{this._waitForPCConnectedPromise=null,delete this.clearConnectTimeout}),this._waitForPCConnectedPromise)}waitForReconnected(){return this.isReconnecting?new Promise((e,t)=>{this.once("spc-reconnected",e),this.once("error",t)}):Promise.resolve()}addDownlink(e){return f(this,null,function*(){if(this._log.info(`addDownlink(${e.userId}) trying`),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise),this.updateLocalAndRemoteSDPConfig(e),this.addDownlinkQueue.size===0)try{yield this.updateSDP(),this._log.info(`addDownlink(${e.userId}) done`)}catch(t){this._log.error(`addDownlink(${e.userId}) failed ${t}`),yield this.startReconnection()}})}updateLocalAndRemoteSDPConfig({ssrc:e,userId:t,tinyId:r}){if(!this._peerConnection)return;this._log.info(`updateLocalAndRemoteSDPConfig ${t} ${JSON.stringify(e)}`);let s=this._peerConnection.getTransceivers().slice(4).filter(u=>u.direction==="inactive").slice(0,3).map(u=>(u.direction=p.TRANSCEIVER_DIRECTION_RECVONLY,Number(u.mid)));this._parsedAnswer||(this._parsedAnswer=De(this._peerConnection.remoteDescription.sdp));let n=this._parsedAnswer.media.filter(u=>{var _;return(_=u.ssrcs)==null?void 0:_.find(g=>{var E;return(E=g.value)==null?void 0:E.includes(r)})}),a,c,l;if(n.length===3)a=n[0],c=n[1],l=n[2];else if(s.length===3)a=this._parsedAnswer.media.find(u=>Number(u.mid)===Number(s[0])),c=this._parsedAnswer.media.find(u=>Number(u.mid)===Number(s[1])),l=this._parsedAnswer.media.find(u=>Number(u.mid)===Number(s[2]));else if(s.length===0){this._peerConnection.addTransceiver(p.AUDIO,{direction:p.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(p.VIDEO,{direction:p.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(p.VIDEO,{direction:p.TRANSCEIVER_DIRECTION_RECVONLY}),a=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let u=pm({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:De(this._peerConnection.localDescription.sdp),isDownlink:!0});c=JSON.parse(JSON.stringify(u)),l=JSON.parse(JSON.stringify(u)),a.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(a),c.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(c),l.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(l)}a.direction=p.TRANSCEIVER_DIRECTION_SENDONLY;let h=`${r}-${e.audio}`;a.ssrcs=[{id:e.audio,attribute:"cname",value:`${h}`},{id:e.audio,attribute:"msid",value:`${h}-${p.MAIN} ${h}-audio`}],c.direction=p.TRANSCEIVER_DIRECTION_SENDONLY,c.ssrcs=[{id:e.video,attribute:"cname",value:`${h}`},{id:e.video,attribute:"msid",value:`${h}-${p.MAIN} ${h}-bigvideo`},{id:e.videoRtx,attribute:"cname",value:`${h}`},{id:e.videoRtx,attribute:"msid",value:`${h}-${p.MAIN} ${h}-bigvideo`}],c.ssrcGroups=[{semantics:"FID",ssrcs:`${e.video} ${e.videoRtx}`}],l.direction=p.TRANSCEIVER_DIRECTION_SENDONLY;let m=`${h}-aux`;l.ssrcs=[{id:e.auxiliary,attribute:"cname",value:m},{id:e.auxiliary,attribute:"msid",value:`${m} ${h}-aux${p.VIDEO}`},{id:e.auxiliaryRtx,attribute:"cname",value:`${m} ${h}-aux${p.VIDEO}`},{id:e.auxiliaryRtx,attribute:"msid",value:`${m} ${h}-aux${p.VIDEO}`}],l.ssrcGroups=[{semantics:"FID",ssrcs:`${e.auxiliary} ${e.auxiliaryRtx}`}],this._parsedAnswer.groups&&(this._parsedAnswer.groups[0].mids=this._parsedAnswer.media.map(u=>u.mid).join(" ")),this._downlinkMIDMap.set(t,[a.mid,c.mid,l.mid]),this._downlinkMIDUserIDMap.set(a.mid,t),this._downlinkMIDUserIDMap.set(c.mid,t),this._downlinkMIDUserIDMap.set(l.mid,t)}removeDownlink(e){return f(this,null,function*(){if(!this._downlinkMIDMap.has(e)||!this._peerConnection)return;this._log.info(`removeDownlink(${e}) trying`),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise);let t=this._downlinkMIDMap.get(e),r=!1;this._peerConnection.getTransceivers().forEach(s=>{t!=null&&t.includes(Number(s.mid))&&(r=!0,s.direction="inactive")}),this._parsedAnswer||(this._parsedAnswer=De(this._peerConnection.remoteDescription.sdp)),this._parsedAnswer.media.forEach(s=>{t!=null&&t.includes(Number(s.mid))&&(r=!0,s.direction="inactive",s.ssrcs=[],s.ssrcGroups=[])}),this.removeDownlinkQueue.size===0&&r&&(yield this.updateSDP()),this._downlinkMIDMap.delete(e),t==null||t.forEach(s=>this._downlinkMIDUserIDMap.delete(s)),this._log.info(`removeDownlink(${e}) done`)})}setBandwidth(e){return f(this,null,function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:r,smallVideo:s,auxVideo:n}=e;try{if(In()){let a=this._peerConnection.getSenders().slice(0,4);for(let l=0;l<a.length;l++){let h=a[l],m;l===0&&t?m=t:l===1&&r?m=r:l===2&&s?m=s:l===3&&n&&(m=n),m&&(yield this.setSenderMaxBitrate(h,m))}let c=!1;r&&a[1].track&&(c=this.setStartBitrate(1,r)),n&&a[3].track&&(c=this.setStartBitrate(3,n)||c),c&&(yield this.updateSDP())}else yield this.setBandwidthBySDP(e);this._log.info(`setBandwidth ${JSON.stringify(e)}`)}catch(a){this._log.error(`failed to set bandwidth: ${a}`)}})}setStartBitrate(e,t){var r,s;return(r=this._peerConnection)!=null&&r.remoteDescription&&(this._parsedAnswer||(this._parsedAnswer=De(this._peerConnection.remoteDescription.sdp)),(s=this._parsedAnswer.media[e])!=null&&s.fmtp[0])?(this._parsedAnswer.media[e].fmtp[0].config+=`;x-google-start-bitrate=${t>5e3?5e3:t}`,!0):!1}setSenderMaxBitrate(e,t){let r=e.getParameters();if((!r.encodings||r.encodings.length===0)&&(r.encodings=[{}]),t==="unlimited")delete r.encodings[0].maxBitrate;else{if(r.encodings[0].maxBitrate===t*1e3)return;r.encodings[0].maxBitrate=t*1e3}return e.setParameters(r)}setBandwidthBySDP({audio:e,bigVideo:t,smallVideo:r,auxVideo:s}){if(!this._peerConnection||!this._peerConnection.localDescription)return;let n=De(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=De(this._peerConnection.remoteDescription.sdp));let a=te?"TIAS":"AS";e&&(n.media[0].bandwidth=[{type:a,limit:te?e*1e3:e}],this._parsedAnswer.media[0].bandwidth=[{type:a,limit:te?e*1e3:e}]),t&&(n.media[1].bandwidth=[{type:a,limit:te?t*1e3:t}],this._parsedAnswer.media[1].bandwidth=[{type:a,limit:te?t*1e3:t}]),r&&(n.media[2].bandwidth=[{type:a,limit:te?r*1e3:r}],this._parsedAnswer.media[2].bandwidth=[{type:a,limit:te?r*1e3:r}]),s&&(n.media[3].bandwidth=[{type:a,limit:te?s*1e3:s}],this._parsedAnswer.media[3].bandwidth=[{type:a,limit:te?s*1e3:s}]);let c={type:"offer",sdp:jt(n)};return this.updateSDP({localDescription:c})}setScaleResolutionDownBy(e,t,r){let s=e.getParameters();(!s.encodings||s.encodings.length===0)&&(s.encodings=[{}]);let n=s.encodings[0].scaleResolutionDownBy;if(T(n)?t===1:t===n)return;let a=`setScaleResolutionDownBy ${r} ${t}`;return n&&(a+=` prevScale: ${n}`),this._log.warn(a),s.encodings[0].scaleResolutionDownBy=t,e.setParameters(s)}setDegradationPreference(e,t,r){if(We&&je<83||Ee&&cn(Tt,"12.1")||te&&jo<138)return;let s=e.getParameters(),n="balanced";if(t==="motion"?n="maintain-framerate":t==="detail"&&(n="maintain-resolution"),s.degradationPreference===n)return;let a=`setDegradationPreference ${r} ${n}`;return this._log.info(a),s.degradationPreference=n,e.setParameters(s).catch(c=>this._log.warn(`${a} failed: ${c}`))}updateSDP({localDescription:e}={}){if(!this._parsedAnswer)return Promise.resolve();let t=jt(this._parsedAnswer);return this._updateSDPPromise=new Promise((r,s)=>f(this,null,function*(){var n,a;try{!e&&this._peerConnection&&(this._log.info("creating offer"),e=yield this._peerConnection.createOffer()),e&&(yield this.setOffer(e)),yield this.setAnswer({type:"answer",sdp:t}),this._updateSDPPromise=null,r()}catch(c){this._log.error(c),!this._isSDPLogged&&this._peerConnection&&(this._log.warn(`current offer: ${this.filterSDPDirection((n=this._peerConnection.localDescription)==null?void 0:n.sdp)}
115
119
  next offer: ${this.filterSDPDirection(e==null?void 0:e.sdp)}`),this._log.warn(`current answer: ${this.filterSDPDirection((a=this._peerConnection.remoteDescription)==null?void 0:a.sdp)}
116
- next answer: ${this.filterSDPDirection(t)}`),this._log.warn(`offer: ${e==null?void 0:e.sdp}`),this._log.warn(`answer: ${t}`),this._log.warn(`transceivers: ${JSON.stringify(this._peerConnection.getTransceivers().map(({mid:l,currentDirection:u,direction:h,stopped:p})=>({mid:l,currentDirection:u,direction:h,stopped:p})))}`),this._log.warn(`parsedAnswer: ${JSON.stringify(this._parsedAnswer)}`),this._isSDPLogged=!0),this._updateSDPPromise=null,s(d)}})),this._updateSDPPromise}setTransceiverDirection(e,t){return f(this,null,function*(){if(!ee||!this._peerConnection||!this._parsedAnswer)return;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let r=this._peerConnection.getTransceivers();t.forEach(s=>{r[s].direction!==e&&(r[s].direction=e)});for(let s of t){let n=this._parsedAnswer.media[s].direction;e===ne.INACTIVE&&n===ne.RECVONLY&&(this._parsedAnswer.media[s].direction=e),e===ne.SENDONLY&&n===ne.INACTIVE&&(this._parsedAnswer.media[s].direction=ne.RECVONLY)}yield this.updateSDP()})}filterSDPDirection(e=""){return De(e).media.map(r=>r.direction)}setOffer(e){this._log.info("setting offer");let t=b_(e.sdp,this.clientAbility,this._serverAbility);return this._log.debug(t),this._peerConnection.setLocalDescription({type:"offer",sdp:t})}setAnswer(e){return this._log.info("setting answer"),this._log.debug(e.sdp),this._peerConnection.setRemoteDescription(e)}switchVideoEncoder(e){return f(this,null,function*(){if(e==="h265"&&!this._parsedAnswer&&(this._parsedAnswer=De(this._peerConnection.remoteDescription.sdp)),!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let t=!1;this._parsedAnswer.media.forEach(r=>{var s;if(r.type===_.VIDEO){let n=this._serverAbility.video.codecs.find(a=>a.codec.toLowerCase()===e);n&&!((s=r.payloads)!=null&&s.includes(String(n.payload)))&&(r.fmtp=[],r.payloads="",r.rtp=[],r.rtcpFb=[],Vr(r,n),t=!0)}}),t&&(this._log.warn(`switch video encoder to ${e}`),yield this.updateSDP())})}useHWEncoder(e=!0,t){return f(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let r=!1,s=[];T(t)?s=this._parsedAnswer.media.slice(1,4):t===2?s.push(this._parsedAnswer.media[1]):t===3?s.push(this._parsedAnswer.media[2]):t===7&&s.push(this._parsedAnswer.media[3]),s.forEach(n=>{var a;if(n.type===_.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=[],Vr(n,d),r=!0)}}),r&&(this._log.warn(`use ${e?"hw":"sw"} encoder`),yield this.updateSDP())})}setProfileLevelId(e="42e01f",t){return f(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let r=!1,s=[];T(t)?s=this._parsedAnswer.media.slice(1,4):t===2?s.push(this._parsedAnswer.media[1]):t===3?s.push(this._parsedAnswer.media[2]):t===7&&s.push(this._parsedAnswer.media[3]),s.forEach(n=>{var a;if(n.type===_.VIDEO){let d;e&&(d=this.clientAbility.video.codecs.find(l=>l.fmtp.includes(e))),d&&!((a=n.payloads)!=null&&a.includes(String(d.payload)))&&(n.fmtp=[],n.payloads="",n.rtp=[],n.rtcpFb=[],Vr(n,d),r=!0)}}),r&&(this._log.warn(`use ${e}`),yield this.updateSDP())})}sendDataChannelMessage(e){var t;(t=this._datachannel)==null||t.send(e)}reset(){var e;this._peerConnection&&(this._peerConnection.close(),this._peerConnection.removeEventListener("track",this._peerConnection._onaddstreampoly,this),this._peerConnection._onaddstreampoly=null,this._peerConnection=null),(e=this.clearWaitForConnectedPromise)==null||e.call(this),this._parsedAnswer=null,this.originOffer=null}close(){this._log.info("close pc"),this.isDestroyed=!0,this.removeRTCListener(),this.insertableStreamsAbortMap.forEach(e=>Ci(e.abort)&&e.abort("destroy")),this.insertableStreamsAbortMap.clear(),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners(),this._room.healthDetector.off("1",this.onBadHealth,this)}getReceiversByUserId(e){if(!this._peerConnection)return[];let t=this._peerConnection.getReceivers();return(this._downlinkMIDMap.get(e)||[]).map(r=>t[r])}get isUsingRelay(){return this._room.getIceTransportPolicy()==="relay"}detectTCPAndUDP({uplinkRTT:e,downlinkRTT:t}){var u;if(this.currentState!=="CONNECTED"||this._isRelayTried&&!this._room.forceRelay||this._room.getIceServers().length===0)return;let r=this._signalChannel.rtt,s=Math.max(e,t),{rttRatioThreshold:n,rttThreshold:a}=((u=this._room.scheduleResult.config)==null?void 0:u.useTurnTcpInfo)||{};if(!n||!a||!r||!s)return;let d=Math.floor(s/r),l=(this._isRelayTried||d>n)&&s>a;if(!l){this._rttOverCount=0;return}++this._rttOverCount<5||(this._log.warn(`detectTCPAndUDP ws-rtt: ${r} upRTT: ${e} downRTT: ${t} ratio: ${d} over-count: ${this._rttOverCount} isOver: ${l} isRelayTried: ${this._isRelayTried} force-relay: ${this._room.forceRelay}`),!this.isUsingRelay&&!this._isRelayTried?(this._isRelayTried=!0,this._rttOverCount=0,this.switchRelay(!0)):this._room.forceRelay&&this.switchRelay(!1))}switchRelay(e,t=!1){return f(this,null,function*(){if(this.isUsingRelay===e)return;let r=e?"relay":"udp",s=e?521709:521710;try{this._room.forceRelay=e,this._log.warn(`switchRelay ${r}`);let n=Date.now();yield this.doSwitchRelay(r),this._log.warn(`switchRelay ${r} success`),y.addSuccessEvent({key:s,cost:Date.now()-n})}catch(n){this._log.warn(`switchRelay ${r} failed`,n),y.addFailedEvent({key:s,error:n}),t?this._room.reJoin():yield this.switchRelay(!e,!0)}})}doSwitchRelay(e){return new Promise((t,r)=>{let s=setTimeout(()=>{this.stopReconnection(),r(new Error(`switch ${e} timeout`))},1e4);this.startReconnection().then(t,r).finally(()=>clearTimeout(s))})}removeRTCListener(){this._peerConnection&&(this._peerConnection.oniceconnectionstatechange=null,this._peerConnection.onconnectionstatechange=null,this._peerConnection.onsignalingstatechange=null,this._peerConnection.ontrack=null),this.dtlsTransport&&(this.dtlsTransport.onstatechange=null)}requestRemoteFallbackToH264(){this._log.warn("H265 decode failed, remote need to fallback h264"),this._h265DecodeFailed=!0,this._signalChannel.sendWaitForResponse({command:Z.UPDATE_CONSTRAINT_CONFIG,data:{videoDecCodec:"h264"},responseCommand:J.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)})}};D([xd("reconnect")],jt.prototype,"startReconnection",1),D([Ti(e=>e.userId)],jt.prototype,"addDownlink",1),D([Ti(e=>e)],jt.prototype,"removeDownlink",1),D([ir(!0)],jt.prototype,"updateSDP",1),D([Rt(521712,!1),Eo(10,0)],jt.prototype,"setOffer",1),D([Rt(521713,!1),Eo(10,0)],jt.prototype,"setAnswer",1),D([pf()],jt.prototype,"close",1);var sm=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 s=e.getUint16(t+2),n=new sm(new Uint8Array(i).slice(t,t+2+2+s).buffer);r.push(n),t+=4+s}r.forEach(s=>{s.tag===1?this.tinyId=new TextDecoder().decode(s.data):s.tag===2&&(this.data=s.data)})}},k_=new Set;function wt(){let o=Math.floor(Math.random()*4294967296);return k_.has(o)?wt():(k_.add(o),o)}var w_=Je(nt());var bo=class extends w_.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);c(this,"_blackSmallVideoDetectionId");this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=R.createLogger({parent:this._room.getLogger(),id:"n",userId:this._room.userId,remoteUserId:this._isUplink?void 0:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink})}get _peerConnection(){var e;return((e=this.singlePC)==null?void 0:e.getPeerConnection())||null}get singlePC(){return this._room.singlePC}get _signalChannel(){return this._room.signalChannel}close(e){this._log.info("close connection"),this.emit("closed",e)}emitConnectionStateChangedEvent(e){return e===this._currentState?!1:(S.emit(A.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:e,remoteUserId:this._isUplink?void 0:this.userId}),this.emit("connection-state-changed",{prevState:this._currentState,state:e}),this._currentState=e,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}getCurrentState(){return this._currentState}get isH264(){var e,t;return!!((t=(e=this._peerConnection)==null?void 0:e.remoteDescription)!=null&&t.sdp.includes("H264"))}};var am=class{constructor(){c(this,"worker");c(this,"callbacks",new Map);c(this,"_log");c(this,"sleep",{});c(this,"heartbeatListenerCleaner",new Map);c(this,"userIdMap",new Map);this._log=R.createLogger({id:"bvd"})}getWorker(){if(!this.worker){let i=`
120
+ next answer: ${this.filterSDPDirection(t)}`),this._log.warn(`offer: ${e==null?void 0:e.sdp}`),this._log.warn(`answer: ${t}`),this._log.warn(`transceivers: ${JSON.stringify(this._peerConnection.getTransceivers().map(({mid:l,currentDirection:h,direction:m,stopped:u})=>({mid:l,currentDirection:h,direction:m,stopped:u})))}`),this._log.warn(`parsedAnswer: ${JSON.stringify(this._parsedAnswer)}`),this._isSDPLogged=!0),this._updateSDPPromise=null,s(c)}})),this._updateSDPPromise}setTransceiverDirection(e,t){return f(this,null,function*(){if(!te||!this._peerConnection||!this._parsedAnswer)return;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let r=this._peerConnection.getTransceivers();t.forEach(s=>{r[s].direction!==e&&(r[s].direction=e)});for(let s of t){let n=this._parsedAnswer.media[s].direction;e===ae.INACTIVE&&n===ae.RECVONLY&&(this._parsedAnswer.media[s].direction=e),e===ae.SENDONLY&&n===ae.INACTIVE&&(this._parsedAnswer.media[s].direction=ae.RECVONLY)}yield this.updateSDP()})}filterSDPDirection(e=""){return De(e).media.map(r=>r.direction)}setOffer(e){this._log.info("setting offer");let t=U_(e.sdp,this.clientAbility,this._serverAbility);return this._log.debug(t),this._peerConnection.setLocalDescription({type:"offer",sdp:t})}setAnswer(e){return this._log.info("setting answer"),this._log.debug(e.sdp),this._peerConnection.setRemoteDescription(e)}switchVideoEncoder(e){return f(this,null,function*(){if(e==="h265"&&!this._parsedAnswer&&(this._parsedAnswer=De(this._peerConnection.remoteDescription.sdp)),!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let t=!1;this._parsedAnswer.media.forEach(r=>{var s;if(r.type===p.VIDEO){let n=this._serverAbility.video.codecs.find(a=>a.codec.toLowerCase()===e);n&&!((s=r.payloads)!=null&&s.includes(String(n.payload)))&&(r.fmtp=[],r.payloads="",r.rtp=[],r.rtcpFb=[],Fr(r,n),t=!0)}}),t&&(this._log.warn(`switch video encoder to ${e}`),yield this.updateSDP())})}useHWEncoder(e=!0,t){return f(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let r=!1,s=[];T(t)?s=this._parsedAnswer.media.slice(1,4):t===2?s.push(this._parsedAnswer.media[1]):t===3?s.push(this._parsedAnswer.media[2]):t===7&&s.push(this._parsedAnswer.media[3]),s.forEach(n=>{var a;if(n.type===p.VIDEO){let c;e&&this.is42001fSupported?c=this.clientAbility.video.codecs.find(l=>l.fmtp.includes("42001f")):e||(c=this._serverAbility.video.codecs.find(l=>l.codec.toLowerCase()===(this._serverAbility.useVp8?"vp8":"h264"))),c&&!((a=n.payloads)!=null&&a.includes(String(c.payload)))&&(n.fmtp=[],n.payloads="",n.rtp=[],n.rtcpFb=[],Fr(n,c),r=!0)}}),r&&(this._log.warn(`use ${e?"hw":"sw"} encoder`),yield this.updateSDP())})}setProfileLevelId(e="42e01f",t){return f(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let r=!1,s=[];T(t)?s=this._parsedAnswer.media.slice(1,4):t===2?s.push(this._parsedAnswer.media[1]):t===3?s.push(this._parsedAnswer.media[2]):t===7&&s.push(this._parsedAnswer.media[3]),s.forEach(n=>{var a;if(n.type===p.VIDEO){let c;e&&(c=this.clientAbility.video.codecs.find(l=>l.fmtp.includes(e))),c&&!((a=n.payloads)!=null&&a.includes(String(c.payload)))&&(n.fmtp=[],n.payloads="",n.rtp=[],n.rtcpFb=[],Fr(n,c),r=!0)}}),r&&(this._log.warn(`use ${e}`),yield this.updateSDP())})}sendDataChannelMessage(e){var t;(t=this._datachannel)==null||t.send(e)}reset(){var e;this._peerConnection&&(this._peerConnection.close(),this._peerConnection.removeEventListener("track",this._peerConnection._onaddstreampoly,this),this._peerConnection._onaddstreampoly=null,this._peerConnection=null),(e=this.clearWaitForConnectedPromise)==null||e.call(this),this._parsedAnswer=null,this.originOffer=null}close(){this._log.info("close pc"),this.isDestroyed=!0,this.removeRTCListener(),this.insertableStreamsAbortMap.forEach(e=>Ai(e.abort)&&e.abort("destroy")),this.insertableStreamsAbortMap.clear(),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners(),this._room.healthDetector.off("1",this.onBadHealth,this)}getReceiversByUserId(e){if(!this._peerConnection)return[];let t=this._peerConnection.getReceivers();return(this._downlinkMIDMap.get(e)||[]).map(r=>t[r])}get isUsingRelay(){return this._room.getIceTransportPolicy()==="relay"}detectTCPAndUDP({uplinkRTT:e,downlinkRTT:t}){var h;if(this.currentState!=="CONNECTED"||this._isRelayTried&&!this._room.forceRelay||this._room.getIceServers().length===0)return;let r=this._signalChannel.rtt,s=Math.max(e,t),{rttRatioThreshold:n,rttThreshold:a}=((h=this._room.scheduleResult.config)==null?void 0:h.useTurnTcpInfo)||{};if(!n||!a||!r||!s)return;let c=Math.floor(s/r),l=(this._isRelayTried||c>n)&&s>a;if(!l){this._rttOverCount=0;return}++this._rttOverCount<5||(this._log.warn(`detectTCPAndUDP ws-rtt: ${r} upRTT: ${e} downRTT: ${t} ratio: ${c} over-count: ${this._rttOverCount} isOver: ${l} isRelayTried: ${this._isRelayTried} force-relay: ${this._room.forceRelay}`),!this.isUsingRelay&&!this._isRelayTried?(this._isRelayTried=!0,this._rttOverCount=0,this.switchRelay(!0)):this._room.forceRelay&&this.switchRelay(!1))}switchRelay(e,t=!1){return f(this,null,function*(){if(this.isUsingRelay===e)return;let r=e?"relay":"udp",s=e?521709:521710;try{this._room.forceRelay=e,this._log.warn(`switchRelay ${r}`);let n=Date.now();yield this.doSwitchRelay(r),this._log.warn(`switchRelay ${r} success`),v.addSuccessEvent({key:s,cost:Date.now()-n})}catch(n){this._log.warn(`switchRelay ${r} failed`,n),v.addFailedEvent({key:s,error:n}),t?this._room.reJoin():yield this.switchRelay(!e,!0)}})}doSwitchRelay(e){return new Promise((t,r)=>{let s=setTimeout(()=>{this.stopReconnection(),r(new Error(`switch ${e} timeout`))},1e4);this.startReconnection().then(t,r).finally(()=>clearTimeout(s))})}removeRTCListener(){this._peerConnection&&(this._peerConnection.oniceconnectionstatechange=null,this._peerConnection.onconnectionstatechange=null,this._peerConnection.onsignalingstatechange=null,this._peerConnection.ontrack=null),this.dtlsTransport&&(this.dtlsTransport.onstatechange=null)}requestRemoteFallbackToH264(){this._log.warn("H265 decode failed, remote need to fallback h264"),this._h265DecodeFailed=!0,this._signalChannel.sendWaitForResponse({command:Z.UPDATE_CONSTRAINT_CONFIG,data:{videoDecCodec:"h264"},responseCommand:W.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)})}};M([Bc("reconnect")],Xt.prototype,"startReconnection",1),M([gi(e=>e.userId)],Xt.prototype,"addDownlink",1),M([gi(e=>e)],Xt.prototype,"removeDownlink",1),M([ir(!0)],Xt.prototype,"updateSDP",1),M([Rt(521712,!1),Eo(10,0)],Xt.prototype,"setOffer",1),M([Rt(521713,!1),Eo(10,0)],Xt.prototype,"setAnswer",1),M([Rf()],Xt.prototype,"close",1);var fm=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}},_m=class{constructor(i){d(this,"tinyId");d(this,"data");let e=new DataView(i),t=0,r=[];for(;t<e.byteLength;){let s=e.getUint16(t+2),n=new fm(new Uint8Array(i).slice(t,t+2+2+s).buffer);r.push(n),t+=4+s}r.forEach(s=>{s.tag===1?this.tinyId=new TextDecoder().decode(s.data):s.tag===2&&(this.data=s.data)})}},B_=new Set;function xt(){let o=Math.floor(Math.random()*4294967296);return B_.has(o)?xt():(B_.add(o),o)}var W_=Je(at());var vo=class extends W_.default{constructor(e){super();d(this,"userId");d(this,"tinyId");d(this,"_sdpSemantics");d(this,"_isUplink");d(this,"_room");d(this,"_log");d(this,"_currentState","DISCONNECTED");d(this,"_prevTime",-1);d(this,"_blackSmallVideoDetectionId");this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=R.createLogger({parent:this._room.getLogger(),id:"n",userId:this._room.userId,remoteUserId:this._isUplink?void 0:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink})}get _peerConnection(){var e;return((e=this.singlePC)==null?void 0:e.getPeerConnection())||null}get singlePC(){return this._room.singlePC}get _signalChannel(){return this._room.signalChannel}close(e){this._log.info("close connection"),this.emit("closed",e)}emitConnectionStateChangedEvent(e){return e===this._currentState?!1:(S.emit(C.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:e,remoteUserId:this._isUplink?void 0:this.userId}),this.emit("connection-state-changed",{prevState:this._currentState,state:e}),this._currentState=e,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}getCurrentState(){return this._currentState}get isH264(){var e,t;return!!((t=(e=this._peerConnection)==null?void 0:e.remoteDescription)!=null&&t.sdp.includes("H264"))}};var gm=class{constructor(){d(this,"worker");d(this,"callbacks",new Map);d(this,"_log");d(this,"sleep",{});d(this,"heartbeatListenerCleaner",new Map);d(this,"userIdMap",new Map);this._log=R.createLogger({id:"bvd"})}getWorker(){if(!this.worker){let i=`
117
121
  const tracks=new Map;let canvas,ctx;const log=(...t)=>postMessage({type:"log",message:"[worker] "+t.join(" ")});function startDetection(e,t,a){if(!tracks.has(e)){const c={reader:a.getReader(),blackCount:0,timeoutId:null,intervalId:null};tracks.set(e,c),c.timeoutId=setTimeout(()=>stopDetection(e,"timeout"),t),c.intervalId=setInterval(async()=>{try{await isFrameBlack(e)?(c.blackCount++,postMessage({type:"blackCount",trackId:e,count:c.blackCount}),3<=c.blackCount&&(postMessage({type:"black",trackId:e}),stopDetection(e,"black"))):c.blackCount=0}catch(t){log("check black video error:",t.message),stopDetection(e,"error")}},1e3)}}function stopDetection(t,e){var a=tracks.get(t);a&&(a.timeoutId&&clearTimeout(a.timeoutId),a.intervalId&&clearInterval(a.intervalId),a.reader&&a.reader.cancel(),tracks.delete(t),postMessage({type:e,trackId:t}))}async function isFrameBlack(t){t=tracks.get(t);if(!t)return!1;var t=t.reader,{done:t,value:e}=await t.read();if(!e||t)return!1;canvas||(canvas=new OffscreenCanvas(e.codedWidth,e.codedHeight),ctx=canvas.getContext("2d",{willReadFrequently:!0})),canvas.width===e.codedWidth&&canvas.height===e.codedHeight||(canvas.width=e.codedWidth,canvas.height=e.codedHeight,ctx=canvas.getContext("2d",{willReadFrequently:!0})),ctx.drawImage(e,0,0,canvas.width,canvas.height);t=getFrameBlackRatio(ctx.getImageData(0,0,canvas.width,canvas.height));return e.close(),1===t}function getFrameBlackRatio(t){var e=t.data;let a=0;for(let t=0;t<100;t++){var c=4*Math.floor(Math.random()*(e.length/4)),[c,r,n,o]=[e[c],e[1+c],e[2+c],e[3+c]];0<o&&0===c&&0===r&&0===n&&a++}return a/100}self.onmessage=t=>{var{type:t,trackId:e,timeout:a,readable:c}=t.data;"addTrack"===t&&startDetection(e,a,c),"removeTrack"===t&&stopDetection(e)};
118
- `,e=new Blob([i],{type:"application/javascript"}),t=URL.createObjectURL(e);this.worker=new Worker(t),URL.revokeObjectURL(t),this.worker.onerror=r=>this._log.warn("worker error:",r.message,r.filename||"unknown",r.lineno||"unknown"),this.worker.onmessage=r=>{var l;let{type:s,trackId:n,message:a,count:d}=r.data;if(s==="black")(l=this.callbacks.get(n))==null||l();else if(s==="log")this._log.warn(a);else if(s==="blackCount"){let u=this.userIdMap.get(n);this._log.warn(`${u||n} black count: ${d}`)}}}return this.worker}start({track:i,isUplink:e,room:t,userId:r,onBlack:s}){if(this._log.debug("start detect black video",i.id),!pn()||!s||!i||typeof Worker=="undefined"){this._log.warn("black video detector not supported");return}let n=a=>{var l,u,h,p;let d;if(e)d=(u=(l=a.msg_up_stream_info)==null?void 0:l.msg_video_status)==null?void 0:u.filter(m=>m.uint32_video_stream_type===3)[0];else{let m=(h=a.msg_down_stream_info)==null?void 0:h.filter(g=>{var E;return((E=g.msg_user_info)==null?void 0:E.str_identifier)===r})[0];d=(p=m==null?void 0:m.msg_video_status)==null?void 0:p.filter(g=>g.uint32_video_stream_type===3)[0]}if(d){let m=(d.uint32_video_codec_bitrate||0)/1e3;if(this.sleep[i.id]&&this.sleep[i.id]>0){this.sleep[i.id]-=1;return}m>0&&m<10&&(this.sleep[i.id]=30,this._log.info("track bitrate",m,"start check"),this.checkOnce(i,30*1e3))}};return t.on("heartbeat-report",n),this.heartbeatListenerCleaner.set(i.id,()=>t.off("heartbeat-report",n)),this.callbacks.set(i.id,s),this.userIdMap.set(i.id,r),i.id}checkOnce(i,e){try{let t=this.getWorker();if(!t)throw new Error("Worker not available");let r=new MediaStreamTrackProcessor({track:i});t.postMessage({type:"addTrack",trackId:i.id,timeout:e,readable:r.readable},[r.readable])}catch(t){this._log.warn("check error:",t),this.stop(i.id)}}stop(i){if(i){this.worker&&this.worker.postMessage({type:"removeTrack",trackId:i}),this.callbacks.delete(i),delete this.sleep[i];let e=this.heartbeatListenerCleaner.get(i);e&&e(),this.heartbeatListenerCleaner.delete(i),this.userIdMap.delete(i)}}destroy(){this.callbacks.forEach((i,e)=>this.stop(e)),this.worker&&(this.worker.terminate(),this.worker=null)}},ur=new am;var xc=class extends bo{constructor(e){super(w(M({},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,videoDecCodec:"",audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0});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:s,smallVideoRtxSsrc:n,auxVideoSsrc:a,auxVideoRtxSsrc:d}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:r||0,small:s||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){try{if(!e&&this._checkPublishStateTimeoutId>0)return;let{serverPublishState:t}=this,{publishState:r}=this._room,s=Object.keys(r).filter(n=>{if(r[n]!==t[n]&&r[n])switch(n){case"audio":return!(!this.localMainAudioTrack||!this.localMainAudioTrack.isMediaTrackActive);case"bigVideo":case"smallVideo":return!(!this.localMainVideoTrack||!this.localMainVideoTrack.isMediaTrackActive);case"auxVideo":return!(!this.localAuxVideoTrack||!this.localAuxVideoTrack.isMediaTrackActive)}return!1});if(s.length>0){if(e)y.addCount({key:521e3}),s.forEach(n=>{this._log.warn(`${n} publish failed during call ${di()} ${ai()}`),y.addEnum({key:521719,value:U_[n]})});else{this._checkPublishStateTimeoutId=oe.run("timeout",()=>this.checkPublishState(!0),{delay:10*1e3,count:1});return}oe.clearTask(this._checkPublishStateTimeoutId),this._checkPublishStateTimeoutId=-1}}catch(t){this._log.warn("checkPublishState failed",t)}}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}get serverPublishState(){return{audio:!!(this.flag&_r),bigVideo:!!(this.flag&fr),smallVideo:!!(this.flag&Us),auxVideo:!!(this.flag&Br)}}initialize(){this.installEvents()}close(e){var r;let t=((r=this._peerConnection)==null?void 0:r.getSenders())||[];for(let s of t)s.replaceTrack(null);super.close(e),this.uninstallEvents(),this.uninstallTrackMuteEvents(this.localMainAudioTrack,this.localMainVideoTrack,this.localAuxVideoTrack),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),this.installSPCEvents()}installSPCEvents(){var e,t;(e=this.singlePC)!=null&&e.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||(t=this.singlePC)==null||t.on("spc-reconnected",this.onSinglePCReconnected,this)}uninstallSPCEvents(){var e;(e=this.singlePC)==null||e.off("spc-reconnected",this.onSinglePCReconnected,this)}uninstallEvents(){this.off("connection-state-changed",this.handleConnectionStateChange,this),this.uninstallSPCEvents()}emitConnectionStateChangedEvent(e,t){var n,a,d;let r=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&r!==e&&(t?t.emit("connection-state-changed",{prevState:r,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:r,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:r,state:e}),(d=this._publishingLocalVideoTrack)==null||d.emit("connection-state-changed",{prevState:r,state:e}))),s}onVideoEncodeFailed(e){return f(this,null,function*(){if(!e||!e.isMediaTrackActive)return;let{videoCodec:t,singlePC:r}=this;if(!r)return;let s={h265:{supported:r.isH264EncodeSupported,target:"h264",log:"h265 encoder not working"},h264:{supported:r.isVP8EncodeSupported,target:"vp8",log:"h264 encoder not working"},vp8:{supported:!1,target:"vp8",log:"vp8 encoder not working, no fallback available"}};if(t==="vp9"||t==="av1")return;let n=s[t];this._log.warn(n.log),n!=null&&n.supported&&(yield r.switchVideoEncoder(n.target))})}publish(s){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:r}){var d,l,u,h,p,m,g;if(!this.singlePC)return;if(this.installEvents(),this.installTrackMuteEvents(e,t),t&&(t.retryEncodeFailed=this.onVideoEncodeFailed.bind(this)),yield this.singlePC.waitForPeerConnectionConnected(),e&&(this._publishingLocalAudioTrack=e),t){if(!this.singlePC.isH264EncodeSupported&&!this.singlePC.isVP8EncodeSupported)throw new v({code:I.NOT_SUPPORTED_H264,message:$({key:B.NOT_SUPPORTED_H264ENCODE})});this.singlePC.isUsingH264&&!this.singlePC.isH264EncodeSupported&&this.singlePC.isVP8EncodeSupported&&(this._log.warn("h264 encoder not supported"),yield this.singlePC.switchVideoEncoder("vp8")),_e&&Yo()===115&&t.profile.width*t.profile.height<=640*360&&(this._log.warn(`fallback video to defaultBigVideoProfile: ${JSON.stringify(pr)}`),t.setProfile(pr),yield t.applyProfile()),this._publishingLocalVideoTrack=t}this._isPublishingAux=r;let n;if(t&&!r&&t.small&&(n=this._room.videoManager.smallTrack),yield this._signalChannel.sendWaitForResponseWithRetry({command:Z.SPC_PUBLISH,responseCommand:J.SPC_PUBLISH_RESULT,data:w(M({},this.singlePC.uplinkSSRC),{state:this._room.publishState,muteState:this._room.muteState}),retries:3}),yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:n,isAuxiliary:r}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,t){this[r?"localAuxVideoTrack":"localMainVideoTrack"]=t,yield this.singlePC.setDegradationPreference(this._peerConnection.getSenders()[r?3:1],t.contentHint,t.streamType);let{scaleResolutionDownBy:E}=t;yield this.singlePC.setScaleResolutionDownBy(this._peerConnection.getSenders()[r?3:1],E,t.streamType)}e&&(this[r?"localAuxAudioTrack":"localMainAudioTrack"]=e),yield this.singlePC.setBandwidth({audio:((d=this.localMainAudioTrack)==null?void 0:d.profile.bitrate)||((l=this.localAuxAudioTrack)==null?void 0:l.profile.bitrate),bigVideo:(u=this.localMainVideoTrack)==null?void 0:u.profile.bitrate,smallVideo:(p=(h=this.localMainVideoTrack)==null?void 0:h.small)==null?void 0:p.bitrate,auxVideo:(m=this.localAuxVideoTrack)==null?void 0:m.profile.bitrate}),this.sendMediaSettings(),(this._room.preferHW||(g=this._room.scheduleResult.config)!=null&&g.preferHW)&&t&&t.profile.width*t.profile.height>=1280*720&&this.singlePC.useHWEncoder(!0,r?7:2);let a=new URLSearchParams(location.search).get("profileLevelId");a&&this.singlePC.setProfileLevelId(a)})}publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:r,isAuxiliary:s}){if(!St())return;this._log.info("publish by transceiver");let n=t==null?void 0:t.outMediaTrack,a=e==null?void 0:e.outMediaTrack,d=this._peerConnection.getTransceivers(),l=[],u=[],h=(m,g,E)=>{var P;let C=d[g].sender.replaceTrack(E);u.push(g),(P=this.singlePC)!=null&&P.enableInsertableStreams&&C.then(()=>this.createEncodedStreams(d[g].sender,m)),this.initSenderTransform(d[g].sender,m),l.push(C)};a&&h(e.mediaType,0,a),n&&h(t.mediaType,s?3:1,n),t!=null&&t.small&&l.push(this.publishSmall(this._room.videoManager.smallMode,t));let p=this.singlePC.setTransceiverDirection(ne.SENDONLY,u);return l.push(p),Promise.all(l)}getTrackByMediaType(e){switch(e){case 1:return this.localMainAudioTrack||this._room.localMainAudioTrack;case 4:case 8:return this.localMainVideoTrack||this._room.localMainVideoTrack;case 2:return this.localAuxVideoTrack||this._room.localAuxVideoTrack;default:return null}}createEncodedStreams(e,t){var a,d;if(this.singlePC.insertableStreamsAbortMap.has(e))return;let r=e.createEncodedStreams(),s=new AbortController;(a=this.singlePC)==null||a.addAbortController(e,s),((d=this.getTrackByMediaType(t))!=null&&d.enableEncodeFrame?r.readable.pipeThrough(new TransformStream({transform:(l,u)=>{var p,m;let h=this.getTrackByMediaType(t);if(!h||!h.encodeFrame)return u.enqueue(l);h.isAudio?u.enqueue(h.enableEncodeFrame?h.encodeFrame(l):l):u.enqueue((p=this.singlePC)!=null&&p.isUsingH264||(m=this.singlePC)!=null&&m.isUsingH265?h.encodeFrame(l,t===8):l)}}),s):r.readable).pipeTo(r.writable,s).catch(l=>{this._log.debug("encoded stream error",l),l!=="destroy"&&this._log.warn(l)})}initSenderTransform(e,t){if(!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker||!ss)return;let r=t!==2,s=t===8;e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!1,isAudio:t===1,isMain:r,isSmall:s}))}enableSmall(e){return f(this,null,function*(){e?yield this.publishSmall(this._room.videoManager.smallMode):yield this.unpublishSmall()})}publishSmall(r){return f(this,arguments,function*(e,t=this.localMainVideoTrack){var l;if(!this.singlePC)return;if(e==="canvas"&&!_d()){this._log.warn("canvas mode small stream is not supported");return}let s=this._peerConnection.getTransceivers(),{sender:n}=s[2],a=yield this.doPublishSmall(e,t),d=e==="canvas"?524700:524701;if(y.addSuccessEvent({key:d}),!a){y.addFailedEvent({key:d,error:10001});return}(l=this.singlePC)!=null&&l.enableInsertableStreams&&this.createEncodedStreams(n,8),this.initSenderTransform(n,8),yield this.singlePC.setTransceiverDirection(ne.SENDONLY,[2]),this.updateMediaSettings(),yield this.doPublishChange(),n.track&&(this._blackSmallVideoDetectionId=ur.start({track:n.track,room:this._room,isUplink:!0,userId:this.userId,onBlack:()=>{this._log.warn("small video is black");let u=e==="canvas"?524700:524701;y.addFailedEvent({key:u,error:10002}),ur.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0}}))})}doPublishSmall(r){return f(this,arguments,function*(e,t=this.localMainVideoTrack){if(!this.singlePC)return null;this._log.info("publish small",e);let s=this._peerConnection.getTransceivers(),{sender:n}=s[2];if(e==="canvas"&&this._room.videoManager.smallTrack)return yield n.replaceTrack(this._room.videoManager.smallTrack),"canvas";if(e==="api"&&(t!=null&&t.outMediaTrack)&&(t!=null&&t.small)){yield n.replaceTrack(t==null?void 0:t.outMediaTrack);let a=n.getParameters(),d=Ho(t==null?void 0:t.profile,t==null?void 0:t.small);return this._log.info("small scaleResolutionDownBy",d),a.encodings[0].scaleResolutionDownBy=d,n.setParameters(a),"api"}return this._log.warn(`small track can not be enabled, smallMode: ${this._room.videoManager.smallMode}, smallTrack: ${!!this._room.videoManager.smallTrack}, bigVideoTrack: ${!!(t!=null&&t.outMediaTrack)}`),null})}unpublishSmall(){return f(this,null,function*(){if(!this.singlePC)return;this._log.info("unpublish small"),yield this._peerConnection.getTransceivers()[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(ne.INACTIVE,[2]),this.updateMediaSettings(),yield this.doPublishChange(),ur.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0})}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(r){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){var l;yield(l=this.singlePC)==null?void 0:l.waitForPeerConnectionConnected();let s=t&&t===this.localAuxVideoTrack||e&&e===this.localAuxAudioTrack,n=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),d=[];e&&(s?this.localAuxAudioTrack=null:this.localMainAudioTrack=null,!this.localMainAudioTrack&&!this.localAuxAudioTrack&&(yield a[0].replaceTrack(null),d.push(0))),n&&(s?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=w(M({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),d.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=w(M({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),d.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.singlePC.setTransceiverDirection(ne.INACTIVE,d),yield this.doPublishChange(!1)):yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),t==null||t.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return f(this,null,function*(){let t={state:this._room.publishState,constraintConfig:this._mediaSettings},r=yield this._signalChannel.sendWaitForResponseWithRetry({command:Z.PUBLISH_STATE_CHANGE,data:t,responseCommand:J.PUBLISH_STATE_CHANGE_RESULT,enableLog:e,retries:3});this.checkPublishResultCode(r.data.code,r.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:Z.UNPUBLISH,commandDesc:"unpublish",responseCommand:J.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===I.API_CALL_TIMEOUT||t.getCode()===I.API_CALL_ABORTED)return Promise.resolve();throw t})}updateMediaSettings(){var s,n;this._mediaSettings.videoCodec=((s=this.singlePC)==null?void 0:s.videoCodec)||"h264",this._mediaSettings.videoDecCodec=((n=this.singlePC)==null?void 0:n.downlinkVideoCodec)||"h264";let e=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:t,localAuxVideoTrack:r}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?r=this._publishingLocalVideoTrack:t=this._publishingLocalVideoTrack),Ni){if(e&&e.outMediaTrack){let a=e.outMediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=e.profile.bitrate*1e3,this._mediaSettings.audioFs=a.sampleRate||0}if(t&&t.outMediaTrack){let a=t.outMediaTrack.getSettings(),{scaleResolutionDownBy:d}=t;this._mediaSettings.videoWidth=(a.width||0)/d||0,this._mediaSettings.videoHeight=(a.height||0)/d||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=t.profile.bitrate*1e3,t.small&&(this._mediaSettings.smallVideoWidth=t.small.width,this._mediaSettings.smallVideoHeight=t.small.height,this._mediaSettings.smallVideoFps=t.small.frameRate,this._mediaSettings.smallVideoBps=t.small.bitrate*1e3)}if(r&&r.outMediaTrack){let a=r.outMediaTrack.getSettings(),{scaleResolutionDownBy:d}=r;this._mediaSettings.auxVideoWidth=(a.width||0)/d||0,this._mediaSettings.auxVideoHeight=(a.height||0)/d||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=r.profile.bitrate*1e3}}else e&&e.outMediaTrack&&(this._mediaSettings.audioChannel=e.profile.channelCount,this._mediaSettings.audioBps=e.profile.bitrate*1e3,this._mediaSettings.audioFs=e.profile.sampleRate),t&&t.outMediaTrack&&(this._mediaSettings.videoWidth=t.profile.width,this._mediaSettings.videoHeight=t.profile.height,this._mediaSettings.videoFps=t.profile.frameRate,this._mediaSettings.videoBps=t.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:Z.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:J.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return f(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is adding ${e.kind} track to current published local ${t?_.AUXILIARY:_.MAIN} stream`),yr()&&(yield this.addTrackByTransceiver(e,t))})}addTrackByTransceiver(e,t){return f(this,null,function*(){var s;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===_.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),n===1&&((s=this.localMainVideoTrack)!=null&&s.small)&&this._room.videoManager.smallTrack&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===ne.INACTIVE&&(yield this.singlePC.setTransceiverDirection(ne.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}removeTrack(e){return f(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${t?_.AUXILIARY:_.MAIN} stream`),yr()&&(yield this.removeTrackByTransceiver(e,t))})}removeTrackByTransceiver(e,t){return f(this,null,function*(){if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===_.AUDIO)yield r[0].sender.replaceTrack(null);else{let s=t?3:1;yield r[s].sender.replaceTrack(null),s===1&&this._room.videoManager.hasSmall&&(yield r[2].sender.replaceTrack(null)),yield this.singlePC.setTransceiverDirection(ne.INACTIVE,[s])}this.updateMediaSettings(),yield this.doPublishChange()})}replaceTrack(e){return f(this,null,function*(){var n;let t=(n=this._peerConnection)==null?void 0:n.getSenders(),r=e.outMediaTrack||e.mediaTrack;if(!t||t.length===0||!r||t.find(a=>a.track===r))return!1;let s=e.mediaType===2||e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info(`is replacing ${r.kind} track ${r.id} ${r.label} on ${s?_.AUXILIARY:_.MAIN} stream`),r.kind===_.AUDIO&&t[0]&&(yield t[0].replaceTrack(r)),r.kind===_.VIDEO&&(!s&&t[1]&&(yield t[1].replaceTrack(r)),s&&t[3]&&(yield t[3].replaceTrack(r))),!0})}setBandwidth(s){return f(this,arguments,function*({bandwidth:e,type:t,videoType:r}){if(this.singlePC){let n={};t===_.AUDIO?n.audio=e:r==="big"?n.bigVideo=e:r==="small"?n.smallVideo=e:n.auxVideo=e,yield this.singlePC.setBandwidth(n)}})}sendMutedFlag(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info(`send muted state: ${JSON.stringify(this._room.muteState)}`),this._signalChannel.sendWaitForResponseWithRetry({command:Z.UPDATE_MUTE_STAT,responseCommand:J.MUTE_RESULT,data:this._room.muteState,retries:3}).catch(()=>{}))}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&S.emit(A.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(e=_.VIDEO){if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===_.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===_.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===_.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===_.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(qe.NOT_SUPPORTED_H264ENCODE),new v({code:I.NOT_SUPPORTED_H264,message:$({key:B.NOT_SUPPORTED_H264ENCODE})})):new v({code:I.UNKNOWN,message:$({key:B.SIGNAL_RESPONSE_FAILED,data:{signalResponse:J.PUBLISH_RESULT,code:e,message:t}})})}onSinglePCReconnected(){return f(this,null,function*(){this.isMainStreamPublished&&(this._log.warn("republish main stream"),yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(this._log.warn("republish aux stream"),yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0}))})}};D([Ct(({localVideoTrack:e})=>{e==null||delete e.retryEncodeFailed})],xc.prototype,"unpublish",1);var U_=(r=>(r[r.audio=1]="audio",r[r.bigVideo=2]="bigVideo",r[r.smallVideo=3]="smallVideo",r[r.auxVideo=4]="auxVideo",r))(U_||{}),dm=xc;function V_(o){return Object.keys(o).filter(i=>o[i])}var Ms=class extends bo{constructor(e){super(w(M({},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);c(this,"_videoCodec");this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=new Ei(this._room,this),this.remoteVideoTrack=new Pi(this._room,this),this.remoteAuxiliaryTrack=new Ts(this._room,this),this.initialize()}get videoCodec(){var e;return this._videoCodec||((e=this.singlePC)==null?void 0:e.downlinkVideoCodec)||"h264"}set videoCodec(e){this._videoCodec=e}get subscribeState(){return{audio:this.remoteAudioTrack.isSubscribed||this.remoteAudioTrack.isSubscribing,video:this.remoteVideoTrack.isBig&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),smallVideo:this.remoteVideoTrack.isSmall&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),auxiliary:this.remoteAuxiliaryTrack.isSubscribed||this.remoteAuxiliaryTrack.isSubscribing}}get muteState(){return Kt(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,r,s;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(r=this.remoteVideoTrack)==null||r.onFlagChanged(),(s=this.remoteAuxiliaryTrack)==null||s.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===_.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){clearTimeout(this.jitterBufferTimeoutId),super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents(),this.removeDownlink()}installEvents(){this.singlePC&&(this.listeners("track").includes(this.onTrack)||this.singlePC.on("track",this.onTrack,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||this.singlePC.on("spc-reconnected",this.onSinglePCReconnected,this),this.remoteVideoTrack.on("decode-failed",this.onDecodeFailed,this))}uninstallEvents(){this.singlePC&&(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this),this.remoteVideoTrack.off("decode-failed",this.onDecodeFailed,this))}emitConnectionStateChangedEvent(e){var s,n;let t=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&t!==e&&((s=this.remoteVideoTrack)==null||s.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),r}onTrack(e){var u,h;let t=e.streams[0],{track:r,receiver:s}=e;if(!t.id.includes(this.tinyId))return;let a=t.id.includes("aux")?"auxiliary":"main";this._log.debug(`ontrack ${a} ${r.kind}`);let d=_.AUDIO;r.kind===_.VIDEO&&(d=a===_.MAIN?_.VIDEO:_.AUXILIARY);let l=this.remoteAudioTrack;d===_.VIDEO?l=this.remoteVideoTrack:d===_.AUXILIARY&&(l=this.remoteAuxiliaryTrack),(u=this.singlePC)==null||u.receiverRemoteTrackMap.set(s,l),(h=this.singlePC)!=null&&h.scriptTransformWorker&&this.initReceiverTransform(s,a,r.kind===_.AUDIO),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(s),l.setInputMediaStreamTrack(r)}createEncodedStreams(e){if(!this.singlePC.insertableStreamsAbortMap.has(e)){let t=e.createEncodedStreams(),r=new AbortController,s={abortController:r,enqueue:n=>{var d,l,u;let a=(d=this.singlePC)==null?void 0:d.receiverRemoteTrackMap.get(e);return!a||a.kind==="video"&&!((l=this.singlePC)!=null&&l.isUsingH264)&&!((u=this.singlePC)!=null&&u.isUsingH265)?n:a.decodeFrame(n)}};t.readable.pipeThrough(new TransformStream({transform:(n,a)=>{let d=s.enqueue(n);d&&a.enqueue(d)}})).pipeTo(t.writable,r).catch(n=>{n!=="destroy"&&this._log.warn(n)}),this.singlePC.addAbortController(e,r)}}initReceiverTransform(e,t,r){!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker||e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!0,isAudio:r,userId:this.userId,streamType:t}))}subscribe(e,t){return f(this,null,function*(){var r,s;try{let n=!0;if(this._log.info(`subscribe ${t} ${V_(e)}`),this.hasSSRC){let l="subscribe_change";Object.values(e).find(u=>u===!0)||(l="unsubscribe"),yield this.sendSubscription(l,e)}else{if(yield this._room.switchRoomSubedReq,(r=this.singlePC)!=null&&r.autoSubscribedUserMap.size){let l=this.singlePC.autoSubscribedUserMap.get(this.userId);if(l){this.singlePC.autoSubscribedUserMap.delete(this.userId);let u=(s=this.singlePC.autoSubscribedSsrcGroups.get(this._room.roomId))==null?void 0:s[l.groupIndex];u&&(this.ssrc={audio:u.audioSsrc,video:u.bigVideoSsrc,videoRtx:u.bigVideoRtxSsrc,auxiliary:u.auxVideoSsrc,auxiliaryRtx:u.auxVideoRtxSsrc},n=!1)}}yield this.doSubscribe(e,n),this.checkTrackEnded(e)}let{user:a,mediaTrack:d}=this.remoteVideoTrack;e.smallVideo&&d?(y.addSuccessEvent({key:524702}),this._blackSmallVideoDetectionId=ur.start({track:d,isUplink:!1,room:this._room,userId:this.userId,onBlack:()=>{this._log.warn("small video is black, auto change to big"),this._room.changeType(!1,a),y.addFailedEvent({key:524702}),ur.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0}})):(ur.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0)}catch(n){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${n.message} ${JSON.stringify(this.muteState)}`),new v({code:I.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):n}})}checkTrackEnded(e){var t,r,s;if((e.audio&&((t=this.remoteAudioTrack.mediaTrack)==null?void 0:t.readyState)==="ended"||e.video&&((r=this.remoteVideoTrack.mediaTrack)==null?void 0:r.readyState)==="ended"||e.auxiliary&&((s=this.remoteAuxiliaryTrack.mediaTrack)==null?void 0:s.readyState)==="ended")&&this.singlePC&&!this.singlePC.isReconnecting){if(this._log.warn("remote track ended start spc reconnect"),Ve&&$e<92)return;this.singlePC.startReconnection()}}unsubscribe(r){return f(this,arguments,function*({remoteTracks:e,streamType:t}){var a;if(t==="main"&&!this.isMainStreamSubscribed||t==="auxiliary"&&!this.isAuxStreamSubscribed){this._log.info(`${t} stream already unsubscribed`);return}let s=M({},this.subscribeState);e.forEach(d=>{switch(d.mediaType){case 1:s.audio=!1;break;case 4:s.video=!1;break;case 8:s.smallVideo=!1;break;case 2:s.auxiliary=!1;break;default:break}});let n="subscribe_change";Object.values(s).find(d=>d===!0)||(n="unsubscribe"),this._log.info(`${n==="unsubscribe"?n:"subscribe"} ${t} [${V_(s)}]`),n==="unsubscribe"&&((a=this.singlePC)==null||a.removeDownlinkQueue.add(this.tinyId)),yield this.sendSubscription(n,s),t==="main"&&(ur.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0),n==="unsubscribe"&&(yield this.removeDownlink())})}sendSubscription(e,t=this.subscribeState){let r={srcTinyId:this.tinyId,srcUserId:this.userId},s=Z.UNSUBSCRIBE,n=J.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(r={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},s=Z.SUBSCRIBE_CHANGE,n=J.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponseWithRetry({command:s,data:r,responseCommand:n,timeout:1e4,retries:3}).then(({data:a})=>{if(a.code!==0){let d=new v({code:a.code,message:$({key:B.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(d),d}})}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}setDelay({audioDelay:e,videoDelay:t}){this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=t}onSinglePCReconnected(){return f(this,null,function*(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary)&&(this._log.warn(`resubscribe ${JSON.stringify(this.subscribeState)}`),yield this.doSubscribe(this.subscribeState),this.remoteAudioTrack.checkDecodeResult(),this.remoteVideoTrack.checkDecodeResult(),this.remoteAuxiliaryTrack.checkDecodeResult())})}get hasSSRC(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}doSubscribe(){return f(this,arguments,function*(e=this.subscribeState,t=!0){if(this.singlePC){this.singlePC.addDownlinkQueue.add(this.tinyId),yield this.singlePC.waitForPeerConnectionConnected();try{if(t||!this.hasSSRC){let r={audioSsrc:wt(),bigVideoSsrc:wt(),bigVideoRtxSsrc:wt(),auxVideoSsrc:wt(),auxVideoRtxSsrc:wt()},{audioSsrc:s,bigVideoSsrc:n,bigVideoRtxSsrc:a,auxVideoSsrc:d,auxVideoRtxSsrc:l}=r;this.ssrc={audio:s,video:n,videoRtx:a,auxiliary:d,auxiliaryRtx:l},this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc});try{let u=yield this._signalChannel.sendWaitForResponseWithRetry({command:Z.SPC_SUBSCRIBE,responseCommand:J.SPC_SUBSCRIBE_RESULT,data:{srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo,customData:!1,ssrc:r},retries:3,retryTimeout:0});if(u.data.code!==0&&u.data.code!==-10036)throw new v({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(!Ed)return;let{main:r,aux:s}=this._room.jitterBufferDelay||{},{jitterDelay:n=r,jitterDelayAux:a=s}=this._room.scheduleResult.config||{};(Q(n)||Q(a))&&this.setJitterBufferDelay({mainDelay:n,auxDelay:a})}}})}removeDownlink(){return f(this,null,function*(){if(!this.singlePC)return;this.ssrc={audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0},this.singlePC.removeDownlinkQueue.delete(this.tinyId);let e=this._room.scheduleResult.config;(e!=null&&e.jitterDelay||e!=null&&e.jitterDelayAux)&&this.setJitterBufferDelay({mainDelay:0,auxDelay:0}),yield this.singlePC.removeDownlink(this.userId)})}setJitterBufferDelay({mainDelay:e,auxDelay:t}){if(!Ed||!this.singlePC||!this._peerConnection||Tt(e)&&Tt(t))return Promise.resolve();this._log.info(`set jitterBuffer main: ${e} aux: ${t}`);let r=this.singlePC.getReceiversByUserId(this.userId);return Q(e)&&(this.remoteAudioTrack.jitterBufferDelay=e,this.remoteVideoTrack.jitterBufferDelay=e),Q(t)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=t,Tt(e)&&(this.remoteAudioTrack.jitterBufferDelay=t)),new Promise(s=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:s})})}doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:s}){try{if(e===0&&t===0)return r.forEach(a=>a.jitterBufferTarget=0),s();if(r.forEach(a=>{var h;let d=a.track===this.remoteAuxiliaryTrack.outMediaTrack||Tt(e)&&a.track===this.remoteAudioTrack.outMediaTrack;if(d&&Tt(t)||!d&&Tt(e))return;let l=d?t||0:e,u=(a.jitterBufferTarget||0)+100;u>l||(a.jitterBufferTarget=u,this._log.debug(`set ${d?"aux ":""}${(h=a==null?void 0:a.track)==null?void 0:h.kind} jitterBuffer delay ${u} -> ${l}`))}),!r.find(a=>{let d=a.track===this.remoteAuxiliaryTrack.outMediaTrack?t||0:e;return a.jitterBufferTarget<d}))return this._log.info(`set jitterBuffer main: ${e} aux: ${t} done`),s();this.jitterBufferTimeoutId=setTimeout(()=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:s})},1e3)}catch(n){this._log.warn(`set jitterBuffer delay error: ${n}`),clearTimeout(this.jitterBufferTimeoutId),s()}}get audioReceiver(){var e;return((e=this.singlePC)==null?void 0:e.getReceiversByUserId(this.userId)[0])||null}onDecodeFailed(){this._room.downlinkVideoCodec==="h265"&&this._room.requestRemoteFallbackToH264()}};D([ir(),Y(e=>function(...t){return new Promise((r,s)=>{let n=a=>{this.off("closed",n),s(new v({code:I.API_CALL_ABORTED,message:$({key:B.CONNECTION_ABORTED,data:a})}))};this.on("closed",n),e.apply(this,t).then(r,s).finally(()=>{this.off("closed",n)})})})],Ms.prototype,"subscribe",1),D([ir()],Ms.prototype,"unsubscribe",1),D([Ti(()=>"jitter")],Ms.prototype,"setJitterBufferDelay",1);var F_=Ms;function B_(){return Y(o=>function(...i){return f(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(i=i.filter(t=>t.outMediaTrack&&t.state==="ready"),!i.length))return;S.emit("61",{room:this});let e=o.apply(this,i);return Promise.all(i.map(t=>t.publish(this,e)))})})}function H_(){return Y(o=>function(...i){let e=o.apply(this,i);return i.forEach(t=>t.unpublish()),e})}var $_=Je(nt());function NI(){return Math.floor(Math.random()*16383)}var Uc=class Uc extends $_.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=R.createLogger({parent:e.getLogger(),id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),t.on(J.RECEIVE_CUSTOM_MSG,this.onReceiveMsg),this.room.on("peer-leave",r=>{[...this.messageMap.keys()].forEach(s=>{s.split("_").slice(0,-1).join("_")===r&&this.messageMap.delete(s)})})}send({cmdId:e,data:t}){let r=this.cmdIdSeqMap.get(e)||NI(),s={cmdId:e,msg:btoa(String.fromCharCode(...new Uint8Array(t))),ordered:!0,reliable:!0,streamSeq:r};this.cmdIdSeqMap.set(e,r+1),this.signalChannel.send(Z.SEND_CUSTOM_MSG,s),this.log.debug(`send custom msg: ${JSON.stringify(s)}`)}onReceiveMsg(e){let{data:t}=e.data,r=this.room.tinyIdToUserIdMap.get(t.srcTinyId);if(r){let s={userId:r,cmdId:t.cmdId,seq:t.streamSeq,data:Uint8Array.from(atob(t.msg),n=>n.charCodeAt(0)).buffer};if(t.ordered){let n=`${r}_${s.cmdId}`,a=this.messageMap.get(n);if(!a||a.lastSeq===0)a||(a={lastSeq:0,cachedMessageMap:new Map},this.messageMap.set(n,a),setTimeout(()=>this.emitMessage(s,!0),100)),a.cachedMessageMap.set(s.seq,{message:s});else if(Math.abs(a.lastSeq-s.seq)>Uc.SEQ_INTERVAL)this.messageMap.set(n,{lastSeq:s.seq,cachedMessageMap:new Map}),this.emitMessage(s);else if(s.seq>a.lastSeq){if(s.seq===a.lastSeq+1)this.emitMessage(s);else if(!a.cachedMessageMap.has(s.seq)){let d=setTimeout(()=>this.emitMessage(s,!0),5e3);a.cachedMessageMap.set(s.seq,{message:s,timeoutId:d})}}else this.log.debug(`drop message ${s.userId}-${s.cmdId}-${s.seq}`)}else this.emit("message",s)}else{this.log.warn(`receive msg from unknown user, wait peer-join tinyId: ${t.srcTinyId}`);let s=n=>{n.tinyId===t.srcTinyId&&(this.room.off("peer-join",s),this.onReceiveMsg(e))};this.room.on("peer-join",s),Ke(2e3).then(()=>this.room.off("peer-join",s))}}emitMessage(e,t=!1){var a;let r=this.messageMap.get(`${e.userId}_${e.cmdId}`),s=e;if(r){if(t){let d=[...r.cachedMessageMap.values()].sort((l,u)=>l.message.seq-u.message.seq);d[0]&&(s=d[0].message)}r.lastSeq!==0&&s.seq-r.lastSeq>1&&this.log.debug(`msg lost userId: ${s.userId} seq: ${r.lastSeq} -> ${s.seq}`),r.lastSeq=s.seq,clearTimeout((a=r.cachedMessageMap.get(s.seq))==null?void 0:a.timeoutId),r.cachedMessageMap.delete(s.seq)}this.log.debug(`receive custom msg: ${JSON.stringify(s)}`),this.emit("message",s);let n=r==null?void 0:r.cachedMessageMap.get(s.seq+1);n&&this.emitMessage(n.message)}};c(Uc,"SEQ_INTERVAL",300);var wc=Uc;var{isString:W_,isUndefined:No,getNetworkType:vI,isEmpty:DI}=Nt,Si=class extends Pc{constructor(e){super(e);c(this,"_businessInfo");c(this,"userManager");c(this,"_version");c(this,"_heartbeat",-1);c(this,"_lastHeartBeatTime",-1);c(this,"_stats");c(this,"_joinTimeout",-1);c(this,"_firstPublishedList",null);c(this,"_joinReject",null);c(this,"_isRelayChanged",!1);c(this,"sdpSemantics");c(this,"signalChannel",null);c(this,"uplinkConnection",null);c(this,"singlePC",null);c(this,"enableSPC",os);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);c(this,"switchRoomSubedReq");c(this,"resolveSwitchRoomSubedReq");c(this,"enableVolumeControlInIOS");this._stats=new ia(this,this._log),this.userManager=new rc(this.userId,this._log),this._version=He,this.sdpSemantics=Mo,No(e.sdpSemantics)?vi.isUnifiedPlanDefault()&&(this.sdpSemantics=gr):this.sdpSemantics=e.sdpSemantics,this._log.info(`sdpSemantics: ${this.sdpSemantics}, netType: ${vI()}`),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=No(e.enableMultiAuxStream)?!1:e.enableMultiAuxStream,this.enableSEI=e.enableSEI&&os,!No(e.enableSPC)&&os&&(this.enableSPC=e.enableSPC),this.preferHW=!!e.preferHW,this.enableVolumeControlInIOS=e.enableVolumeControlInIOS,this._initBusinessInfo(e),this.healthDetector=new v_(this)}get isMainStreamPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.isMainStreamPublished)}get isMainAudioPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.localMainAudioTrack)}get isAuxStreamPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.isAuxStreamPublished)}get hasAuxStream(){return[...this.remotePublishedUserMap.values()].findIndex(e=>e.muteState.hasAuxiliary)>=0}get userMap(){return this.userManager.userMap}get remotePublishedUserMap(){return this.userManager.remotePublishedUserMap}get tinyIdToUserIdMap(){return new Map([...this.userMap.values()].map(e=>[e.tinyId,e.userId]))}get videoCodec(){var e;return((e=this.singlePC)==null?void 0:e.videoCodec)||"h264"}get downlinkVideoCodec(){var e;return((e=this.singlePC)==null?void 0:e.downlinkVideoCodec)||"h264"}join(e,t,r){return f(this,null,function*(){return this.userManager.mySelfId=this.userId,this.userManager.on("1",s=>{this.emit("peer-join",s)}),this.userManager.on("2",s=>{this.closeDownLinkConnection(s,"remote user exitRoom"),this.emit("peer-leave",s)}),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",n=>{var s=na(n,[]);S.emit(A.REMOTE_PUBLISH_STATE_CHANGED,M({room:this},s)),this.emit("remote-publish-state-changed",M({},s))}),this.joinParams=e,new Promise((s,n)=>f(this,null,function*(){var a,d;this._joinReject=n;try{this.checkDestroy();try{yield Promise.all([this.initialize(),this.initSinglePC()])}catch(u){if(u instanceof v&&u.code===I.SPC_INITIALIZED_FAILED)(a=this.signalChannel)==null||a.destroy(),yield this.initialize();else return n(u)}let l=V();yield this.doJoin(e,(d=this.singlePC)==null?void 0:d.clientAbility),y.addSuccessEvent({key:521708,cost:V()-l}),s(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(l){y.addFailedEvent({key:521708,error:l}),n(l)}this._joinReject=null}))})}initSinglePC(){return f(this,null,function*(){if(!(!this.enableSPC||this.singlePC)){this.singlePC=new jt({signalChannel:this.signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.on("sei-message",e=>this.emit("sei-message",e)),this.singlePC.on("dump",e=>this.emit("dump",e)),this.singlePC.once("error",()=>this.fallbackToMPC());try{return yield this.singlePC.initialize()}catch(e){throw this.fallbackToMPC(),new v({code:I.SPC_INITIALIZED_FAILED,message:e==null?void 0:e.message})}}})}doJoin(e,t){return new Promise((r,s)=>f(this,null,function*(){var d,l,u;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this.signalChannel.once(Ie.SETUP_FAILED,h=>{this.clearJoinTimeout(),S.emit(A.JOIN_SIGNAL_CONNECTION_END,{room:this,error:h}),s(h)}),ue((l=(d=this.scheduleResult)==null?void 0:d.config)==null?void 0:l.singlePC)&&os&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2),t&&this.playoutDelay&&(t.playoutDelay=this.playoutDelay);let n={roomId:String(e.roomId||e.strRoomId),useStringRoomId:this.useStringRoomId,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel,trtcRole:e.role,trtcScene:this.scene==="live"?2:1,sdpSemantics:this.sdpSemantics,version:this._version,ua:navigator&&navigator.userAgent||"",terminalType:kl(),netType:Jr(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig,receiveMix:!0,isChorus:!!this.enableChorus,enableNtpAudioFrame:!!this.enableChorus&&mn()};this._log.debug(`join room signal data: ${JSON.stringify(n)}`);let a=5e3;(u=this.scheduleResult.config)!=null&&u.enterRoomTimeout&&this.scheduleResult.config.enterRoomTimeout>=1&&(a=this.scheduleResult.config.enterRoomTimeout*1e3),this._joinTimeout=window.setTimeout(()=>{s(new v({code:I.JOIN_ROOM_FAILED,message:$({key:B.JOIN_ROOM_TIMEOUT})}))},a),S.emit(A.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?Z.SPC_JOIN_ROOM:Z.JOIN_ROOM,n),this.signalChannel.once(J.JOIN_ROOM_RESULT,h=>f(this,null,function*(){this.clearJoinTimeout();let{code:p,message:m,data:g,tinyId:E}=h.data;S.emit(A.JOIN_RECEIVED_CMD_RES,{room:this,code:p}),p===0?(this._log.info("Join room success, start heartbeat"),E&&(this.tinyId=E),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=g.publishers,this._iceServersFromJoin=g.iceServer?[g.iceServer]:[],this.singlePC&&this.singlePC.setIceServers(this.getIceServers()).then(()=>{var C;(C=this.singlePC)==null||C.connect(w(M({},g.ability),{useVp8:g.ability.useVp8||!!e.useVp8,useH265:g.ability.useH265&&!!e.useH265})).catch(()=>{})}),r()):(this._log.error(`Join room failed result: ${p} error: ${m}`),s(new v({code:I.JOIN_ROOM_FAILED,extraCode:p,message:$({key:B.JOIN_ROOM_FAILED,data:{error:m,code:p}})})))}))}))}reJoin(){return f(this,null,function*(){if(!this.isJoined){this._log.warn("reJoin abort");return}try{this._log.warn(`reJoin pending: ${this.joinParams.roomId}`);let e,t=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,t.push(this.initSinglePC().then(r=>(e=r,r)))),this.signalChannel&&(this.signalChannel.close(),t.push(this.signalChannel.connect())),yield Promise.all(t),yield this.doJoin(w(M({},this.joinParams),{role:this.role==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),e),this._log.warn("reJoin success"),se.logSuccessEvent({userId:this.userId,eventType:Ze.REJOIN}),this.singlePC){let r=s=>{var n;s.state==="CONNECTED"&&((n=this.singlePC)==null||n.off(Ui.CONNECTION_STATE_CHANGED,r),this.uplinkConnection instanceof dm&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach(a=>{a.installEvents(),a.onSinglePCReconnected()}))};this.singlePC.on(Ui.CONNECTION_STATE_CHANGED,r),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof ta&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(e){this._log.warn(`reJoin fail ${e}`),this.reset(),se.logFailedEvent({userId:this.userId,eventType:Ze.REJOIN,error:e}),this.emit("error",new v({code:I.JOIN_ROOM_FAILED,message:$({key:B.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}})}initialize(){return f(this,null,function*(){let{mainUrl:e,backupUrl:t}=this.getSignalChannelUrl(),r=this.signalChannel||e_(this.userId),s=!!(r&&r.isConnected&&r.keepAlive&&r.userId===this.userId&&r.room===this),n;return Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(n=this.scheduleResult.domains[0]),this._log.info(`${s?"reuse":"setup"} signal channel`),s?(r.url=e,r.backupUrl=t,r.room=this,this.signalChannel=r):(r&&r.close(),this.signalChannel=new ys({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 Ds({signalChannel:this.signalChannel,room:this}),this.networkQuality.on(Ds.EVENT_NETWORK_QUALITY,a=>{var d;this.emit("network-quality",a),(d=this.singlePC)==null||d.detectTCPAndUDP(a)})),tt(this,this.signalChannel).add(Ie.CONNECTION_STATE_CHANGED,a=>{S.emit(A.SIGNAL_CONNECTION_STATE_CHANGED,M({room:this},a)),this.emit("signal-connection-state-changed",a)}).add(Ie.RECONNECT_FAILED,a=>{this.reset(),this.emit("error",a)}).add(J.PEER_JOIN,a=>{let{srcTinyId:d,userId:l,role:u}=a.data.data;this.userManager.addUser({userId:l,tinyId:d,role:u})}).add(J.PEER_LEAVE,a=>{let{userId:d,reason:l=0}=a.data.data;this.userManager.deleteUser(d,l)}).add(J.UPDATE_REMOTE_MUTE_STAT,a=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=10*1e3&&this.doHeartbeat(),this.onPublishedUserList(a.data)}).add(J.CLIENT_BANNED,a=>{let d=a.data.data,{reason:l}=d;if(se.uploadEvent({log:`stat-banned:${l}`,userId:this.userId}),l==="user_time_out"){this._log.warn(`${l} last heart beat time: ${this._lastHeartBeatTime} interval: ${Date.now()-this._lastHeartBeatTime}, visibility: ${document.visibilityState}`),this.reJoin();return}this._log[l==="kick"?"error":"info"](`user was banned because of [${l}]`),this.reset(),this.emit("banned",{reason:l})}).add(J.SEND_SWITCH_ROOM_SUBED_REQ,a=>{if(!this.singlePC)return;let{subList:d}=a.data.data;this._log.info(`auto subscribe ${gt(d,{keysToInclude:["userId"]})}`),d.forEach(l=>{this.singlePC.autoSubscribedUserMap.set(l.userId,l)}),this.resolveSwitchRoomSubedReq()}).add(J.FALLBACK_CODEC,a=>f(this,null,function*(){var l,u,h,p,m;let d=a.data.data;((l=d.videoControlInfo)==null?void 0:l.enableH265Enc)===0&&((u=this.singlePC)==null?void 0:u.videoCodec)==="h265"&&(this._log.warn(`fallback codec enableH265Enc: ${(h=d.videoControlInfo)==null?void 0:h.enableH265Enc}`),y.addCount({key:513e3}),yield(p=this.singlePC)==null?void 0:p.switchVideoEncoder("h264"),yield(m=this.uplinkConnection)==null?void 0:m.sendMediaSettings())})),this.signalChannel.once(Ie.SETUP_SUCCESS,a=>{this.tinyId=a.signalInfo.tinyId,S.emit(A.JOIN_SIGNAL_CONNECTION_END,{room:this})}),S.emit(A.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),s&&S.emit(A.JOIN_SIGNAL_CONNECTION_END,{room:this}),s})}setSignalChannel(e){this.signalChannel=e,e||we(this)}leave(){return f(this,null,function*(){var e;try{yield this.doHeartbeat()}catch(t){}this._log.info("leave() => leaving room"),S.emit(A.LEAVE_SEND_CMD,{room:this}),(e=this.signalChannel)==null||e.send(Z.LEAVE_ROOM),this.switchRoomSubedReq=void 0})}clearNetworkQuality(){this.networkQuality&&(this.networkQuality.stop(),delete this.networkQuality)}closeConnections(){this.remotePublishedUserMap.forEach(e=>{this.closeDownLinkConnection(e.userId,"you exitRoom")})}clearJoinTimeout(){clearTimeout(this._joinTimeout),this._joinTimeout=-1}startHeartbeat(){this._heartbeat===-1&&(this._heartbeat=oe.run("ric",this.doHeartbeat.bind(this),{delay:2e3}),this.enableChorus&&this.startUpdateNTPTime())}stopHeartbeat(){this._heartbeat!==-1&&(this._log.info("stopHeartbeat"),oe.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return f(this,null,function*(){var n;let e=this.badCaseDetector.getMonitorFreeze(),t=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:e});this.badCaseDetector.resetMonitor();let r=(n=this.signalChannel)!=null&&n.isConnected?ff(this.userId):[],s=w(M({str_sdk_version:Ls,uint64_datetime:new Date().getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_event_msg:r,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},t),{msg_device_info:M({uint32_terminal_type:15,str_device_name:ai(),str_os_version:"",uint32_net_type:Jr()},t.msg_device_info)});if(this.heartbeatReport=s,this.heartbeatCount++,S.emit(A.HEARTBEAT_REPORT,{room:this,report:s}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(Z.ON_QUALITY_REPORT,s);let a=Date.now();this._lastHeartBeatTime>0&&a-this._lastHeartBeatTime>1e4&&this._log.warn(`heartbeat took ${a-this._lastHeartBeatTime}`),this._lastHeartBeatTime=a,this.signalChannel.isOnline||(this._log.warn("signal channel is not online"),this.signalChannel.startReconnection())}this.emit("heartbeat-report",w(M({},s),{bytes_sent:this._stats.totalBytesSent+this.signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this.signalChannel.bytesReceived}))}!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)})}onPublishedUserList(e){if(!this.isJoined)return;let t=!1,r=e.data.userList||[],s=e.data.mixRobotList||[],n=[];for(let l of r){if(l.flag===Xc)continue;let{userId:u,srcTinyId:h,flag:p}=l;u===this.userId&&(t=!0,this.uplinkConnection&&(this.uplinkConnection.flag=p),this.localPublishFlag!==p&&(this.localPublishFlag=p,this.emit("local-publish-flag-changed",p))),n.push({userId:u,tinyId:h,flag:p})}let d=[...s.map(({userId:l,srcTinyId:u,flag:h,mixUserList:p})=>({userId:l,tinyId:u,flag:h,isRobot:!0,mixUserList:p})),...n];d.forEach(({userId:l})=>{let u=this.remotePublishedUserMap.get(l);u&&this.checkSubscribeBigSmallVideo(u)}),e.data.fakeMixUser&&(e.data.fakeMixUser.tinyId=e.data.fakeMixUser.srcTinyId,d.push(e.data.fakeMixUser)),S.emit(A.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:d}),t||(this.localPublishFlag=0,this.emit("local-publish-flag-changed",0)),this.userManager.setRemotePublishedUserList(d)}closeUplink(e="you unpublished"){this.uplinkConnection&&(this.localTracks.size>0&&this.uplinkConnection.doUnpublish().catch(()=>{}),this.uplinkConnection.close(e),this.uplinkConnection instanceof ta&&(this.uplinkConnection=null)),this.localTracks.forEach(t=>t.unpublish()),this.localTracks.clear()}createDownlinkConnection({userId:e,tinyId:t,flag:r,isRobot:s}){let n=new(this.singlePC?F_:Yh)({userId:e,tinyId:t,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:r,isRobot:s});this.userManager.addRemotePublishedUser(n),this.installDownlinkEvents(n,e),this.emit("remote-published",n)}closeDownLinkConnection(e,t="remote user unpublished"){let r=this.remotePublishedUserMap.get(e);r&&(r.close(t),this.emit("remote-unpublished",r))}installDownlinkEvents(e,t){e.on("error",r=>{let s=r.getCode();s!==I.ICE_TRANSPORT_ERROR&&(s===I.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",r))}),e.on("connection-state-changed",r=>{this.emit("media-connection-state-changed",w(M({},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:Z.GET_USER_LIST,responseCommand:J.USER_LIST_RES,enableLog:!1,timeout:2e3}).then(({data:t})=>{let{code:r,message:s}=t;if(r===0)return(t.data&&t.data.userList||[]).map(({userId:a,srcTinyId:d,role:l})=>({userId:a,tinyId:d,role:l}));throw $({key:B.SIGNAL_RESPONSE_FAILED,data:{signalResponse:J.USER_LIST_RES,code:r,message:s}})}):Promise.reject("not connected")}getAllConnections(){let e=[...this.remotePublishedUserMap.values()];return this.uplinkConnection&&e.push(this.uplinkConnection),e}isRelayMaybeFailed(){if(this.signalChannel&&!this.signalChannel.isOnline||!Jh)return!1;if(this.singlePC)return this.singlePC.reconnectionCount>6;let e=this.getAllConnections();if(e.length===0)return!1;for(let t=0;t<e.length;t++)if(e[t].getReconnectionCount()<6)return!1;return!0}checkConnectionsToReconnect(){var e;this.singlePC?((e=this.singlePC.getPeerConnection())==null?void 0:e.connectionState)===Ce.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach(r=>{if(r instanceof ft&&!r.getIsReconnecting()){let s=r.getPeerConnection();s&&s.connectionState===Ce.CLOSED&&(this._log.warn(`[${r.getUserId()}] pc is closed but not reconnect`),r.startReconnection())}})}fallbackToMPC(){return f(this,null,function*(){var e;if(this._log.warn("fallback to multi pc"),se.uploadEvent({log:"stat-fallback",userId:this.userId}),this.enableSPC=!1,(e=this.singlePC)==null||e.close(),this.singlePC=null,this.isJoined&&(yield this.reJoin()),this.uplinkConnection){let t=this.uplinkConnection;this.uplinkConnection=new ta({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 Yh({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 v({code:I.INVALID_OPERATION,message:$({key:B.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners(),this.healthDetector.destroy(),oe.clearTask(this._audioVolumeIntervalId))}switchRole(e){return f(this,null,function*(){this.role!==e&&(e==="audience"&&this.uplinkConnection&&this.closeUplink("you switch role to audience"),yield this.doSwitchRole(e))})}doSwitchRole(e){let t={command:Z.SWITCH_ROLE,data:{role:e==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:J.SWITCH_ROLE_RES,retries:1};return this._log.info(`switchRole signal data: ${JSON.stringify(t.data)}`),this.signalChannel.sendWaitForResponseWithRetry(t).then(r=>{let{code:s,message:n}=r.data;if(s!==0)throw new v({code:I.SWITCH_ROLE_FAILED,message:$({key:B.SWITCH_ROLE_FAILED,data:{message:n,code:s}})});this.role=e}).catch(r=>{throw r instanceof v&&r.getCode()===I.API_CALL_TIMEOUT&&(r=new v({code:I.SWITCH_ROLE_FAILED,message:$({key:B.SWITCH_ROLE_TIMEOUT})})),this._log.error(r),r})}_initUplinkConnection(){this.uplinkConnection=this.singlePC?new dm({userId:this.userId,tinyId:this.tinyId,room:this}):new ta({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),this.uplinkConnection.on("connection-state-changed",e=>{this.emit("media-connection-state-changed",w(M({},e),{userId:this.userId}))}),this.uplinkConnection.on("firewall-restriction",()=>{this.emit("firewall-restriction")}),this.uplinkConnection.on("error",e=>{let t=e.getCode();t!==I.ICE_TRANSPORT_ERROR&&(t===I.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",e))})}publish(e){return f(this,null,function*(){var r;this.uplinkConnection||this._initUplinkConnection();let t=`${e.streamType} ${e.isAudio&&e.isScreen?"screen":""}${e.kind}`;this._log.info(`publish() => ${t}`),yield(r=this.singlePC)==null?void 0:r.waitForPeerConnectionConnected(),yield this.uplinkConnection.publish({localAudioTrack:e instanceof kt?e:null,localVideoTrack:e instanceof je?e:null,isAuxiliary:e.streamType==="auxiliary"||e.isScreen})})}unpublish(e){return f(this,null,function*(){if(!(this.scene==="live"&&this.role!=="anchor"||!this.isMainStreamPublished&&!this.isAuxStreamPublished||!this.uplinkConnection)){try{let t=`${e.streamType} ${e.isAudio&&e.isScreen?"screen":""}${e.kind}`;this._log.info(`unpublish() => ${t}`),yield this.uplinkConnection.unpublish({localAudioTrack:e instanceof kt?e:null,localVideoTrack:e instanceof je?e:null})}catch(t){}this.localTracks.size===0&&this.closeUplink("you unpublished")}})}addTrack(e){if(!this.uplinkConnection||!e.mediaTrack)return Promise.resolve();let t=this.uplinkConnection.addTrack(e);return e.publish(this,t),t}removeTrack(e){return!this.uplinkConnection||!e.mediaTrack?Promise.resolve():(e.unpublish(),this.uplinkConnection.removeTrack(e))}replaceTrack(e){return!this.uplinkConnection||!e.mediaTrack||!ou()?Promise.resolve():this.uplinkConnection.replaceTrack(e).then(t=>{t&&S.emit(A.LOCAL_TRACK_REPLACED,{track:e})})}setBandWidth(e){return f(this,null,function*(){this.uplinkConnection&&(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())})}enableSmall(e){return f(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:_.VIDEO,videoType:_.SMALL,bandwidth:this.uplinkConnection.localMainVideoTrack.small.bitrate})),yield this.uplinkConnection.enableSmall(e)})}subscribe(...e){return f(this,null,function*(){if(e=e.filter(n=>!n.isSubscribed),e.length===0)return;let{userId:t}=e[0],r=this.remotePublishedUserMap.get(t);if(!r)return;let s=e.find(n=>n.mediaType===2)?"auxiliary":"main";try{let n=M({},r.subscribeState);e.forEach(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),S.emit(A.SUBSCRIBE_START,{room:this,streamType:s,remotePublishedUser:r,subscribeState:n}),this._log.info(`subscribe() => ${t} ${s} [${bc(n)}] prev: [${bc(r.subscribeState)}]`),yield r.subscribe(n,s),this._log.info(`subscribe ${t} ${s} done`);for(let d of e)d.mediaTrack||(yield d.waitHasMediaTrack());S.emit(A.SUBSCRIBE_SUCCESS,{room:this,streamType:s,remotePublishedUser:r})}catch(n){let a=n instanceof v?n.getCode():I.UNKNOWN,d=n;throw n instanceof v?a===I.REMOTE_STREAM_NOT_EXIST&&(d=new v({code:I.API_CALL_ABORTED,message:$({key:B.API_CALL_ABORTED,data:{message:n.message,userId:t,streamType:s}})}),this._log.warn(d)):(d=new v({code:a,message:$({key:B.SUBSCRIBE_FAILED,data:{message:n.message,userId:t,streamType:s}})}),this._log.error(d)),d}})}unsubscribe(...e){return f(this,null,function*(){let{userId:t}=e[0],r=this.remotePublishedUserMap.get(t);if(!r)return;let s=e.find(n=>n.mediaType===2)?"auxiliary":"main";this._log.info(`unsubscribe() => ${t} ${s}`);try{yield r.unsubscribe({remoteTracks:e,streamType:s})}catch(n){this._log.warn(`unsubscribe() => failed ${n}`)}e.forEach(n=>{n.unsubscribe(),n.mediaType===8&&n.setMediaType(4)}),S.emit(A.UNSUBSCRIBE_SUCCESS,{room:this,streamType:s,remotePublishedUser:r})})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAudioVolumeEvaluation(e=2e3,t){if(e<=0){this._enableAudioVolumeEvaluation=!1,oe.clearTask(this._audioVolumeIntervalId);return}e=Math.floor(Math.max(e,100)),S.emit(A.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&oe.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=oe.run("intervalInWorker",()=>{var s;so.isRunning?this.stopUpdateAudioLevelFromSenderStat():this.updateAudioLevelFromSenderStat(e,t);let r=[];(s=this.remotePublishedUserMap)==null||s.forEach(n=>{if(n.muteState.hasAudio){!so.isRunning&&n.muteState.audioAvailable&&n.remoteAudioTrack.isSubscribed?this.updateDownlinkAudioLevelFromReceiver(n):n.remoteAudioTrack.volume=0;let a=Math.floor(n.remoteAudioTrack.getAudioLevel()*100);r.push({userId:n.userId,volume:a,floatVolume:n.remoteAudioTrack.getInternalAudioLevel()})}}),this.emit("audio-volume",r)},{delay:e,backgroundTask:t})}updateAudioLevelFromSenderStat(e,t){return f(this,null,function*(){var n;if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack||this._updateAudioLevelTaskId!==-1)return;let r=(n=this.uplinkConnection.getPeerConnection())==null?void 0:n.getSenders()[0];if(!r)return;let s=Math.max(e,500);this._log.warn(`updateAudioLevelFromSenderStat ${s}`),this._updateAudioLevelTaskId=oe.run("intervalInWorker",()=>f(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack){this.stopUpdateAudioLevelFromSenderStat();return}let a=yield r.getStats();if(this._updateAudioLevelTaskId<0)return;let{localMainAudioTrack:d}=this.uplinkConnection;a.forEach(l=>{l.type==="media-source"&&l.audioLevel&&(d.volume=l.audioLevel)})}),{delay:s,backgroundTask:t})})}stopUpdateAudioLevelFromSenderStat(){var e;this._updateAudioLevelTaskId!==-1&&(this._log.warn("stopUpdateAudioLevelFromSenderStat"),oe.clearTask(this._updateAudioLevelTaskId),this._updateAudioLevelTaskId=-1,(e=this.uplinkConnection)!=null&&e.localMainAudioTrack&&(this.uplinkConnection.localMainAudioTrack.volume=0))}updateDownlinkAudioLevelFromReceiver(e){var s;let{audioReceiver:t}=e;if(!su||!t)return;let r=(s=t.getSynchronizationSources()[0])==null?void 0:s.audioLevel;Q(r)?e.remoteAudioTrack.volume=Math.min(r*2,1):t.getStats().then(n=>{n.forEach(a=>{a.type==="inbound-rtp"&&Q(a.audioLevel)&&(e.remoteAudioTrack.volume=a.audioLevel)})})}getLocalAudioStats(){return f(this,null,function*(){var t;let e={};return e[this.userId]={bytesSent:0,packetsSent:0,audioLevel:0},(t=this.uplinkConnection)!=null&&t.localMainAudioTrack&&(e[this.userId]=this.uplinkConnection.localMainAudioTrack.stat),e})}getLocalVideoStats(){return f(this,null,function*(){var t,r;let e={};return e[this.userId]=((r=(t=this.uplinkConnection)==null?void 0:t.localMainVideoTrack)==null?void 0:r.stat)||{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0},e})}getTransportStats(){return f(this,null,function*(){let e={rtt:0,downlinksRTT:{}};if(this.uplinkConnection){let t=yield this._stats.getSenderStats(this.uplinkConnection);e.rtt=t.rtt}for(let[,t]of this.remotePublishedUserMap){let r=yield this._stats.getReceiverStats(t);e.downlinksRTT[r.userId]=r.rtt}return e})}getRemoteVideoStats(e){return f(this,null,function*(){let t={};for(let[r,s]of this.remotePublishedUserMap)e==="main"&&s.muteState.hasVideo&&(t[r]=s.remoteVideoTrack.stat),e==="auxiliary"&&s.muteState.hasAuxiliary&&(t[r]=s.remoteAuxiliaryTrack.stat);return t})}getRemoteAudioStats(){return f(this,null,function*(){let e={};for(let[t,r]of this.remotePublishedUserMap)r.muteState.hasAudio&&(e[t]=r.remoteAudioTrack.stat);return e})}setTurnServer(e,t){this._log.info(`set turn server: ${JSON.stringify(e)} ${t||""}`);let r=[];Array.isArray(e)?e.forEach(s=>r.push(Nt.getTurnServer(s))):Nt.isPlainObject(e)&&r.push(Nt.getTurnServer(e)),this._turnServers=r,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:Z.START_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:J.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"}).catch(t=>{if(t.code!==I.API_CALL_ABORTED)throw t})}sendStopMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:Z.STOP_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:J.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"}).catch(t=>{if(t.code!==I.API_CALL_ABORTED)throw t})}sendStartPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?Z.START_PUBLISH_TENCENT_CDN:Z.START_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?J.START_PUBLISH_TENCENT_CDN_RES:J.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"}).catch(r=>{if(r.code!==I.API_CALL_ABORTED)throw r})}sendStopPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?Z.STOP_PUBLISH_TENCENT_CDN:Z.STOP_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?J.STOP_PUBLISH_TENCENT_CDN_RES:J.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"}).catch(r=>{if(r.code!==I.API_CALL_ABORTED)throw r})}sendStartPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Z.START_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:J.START_PUBLISH_CDN_STREAM_RES,commandDesc:"startPublishCDNStream"}).catch(t=>{if(t.code!==I.API_CALL_ABORTED)throw t})}sendUpdatePushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Z.UPDATE_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:J.UPDATE_PUBLISH_CDN_STREAM_RES,commandDesc:"updatePublishCDNStream"}).catch(t=>{if(t.code!==I.API_CALL_ABORTED)throw t})}sendStopPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Z.STOP_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:J.STOP_PUBLISH_CDN_STREAM_RES,commandDesc:"stopPublishCDNStream"}).catch(t=>{if(t.code!==I.API_CALL_ABORTED)throw t})}sendAbilityStatus(e){var t;(t=this.signalChannel)==null||t.sendWaitForResponse({command:Z.ABILITY_STATUS_REPORT,data:e,timeout:5e3,responseCommand:J.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=Nt.getEnv();return t?(e.mainUrl=`wss://${t}.rtc.qq.com`,e.backupUrl=e.mainUrl):this.proxy_ws?(e.mainUrl=this.proxy_ws,e.backupUrl=e.mainUrl):this.proxy_unified?(e.mainUrl=`wss://${this.proxy_unified}`,e.backupUrl=e.mainUrl):Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(e.mainUrl=`wss://${this.scheduleResult.domains[0]}`,e.backupUrl=e.mainUrl,this.scheduleResult.domains[1]&&(e.backupUrl=`wss://${this.scheduleResult.domains[1]}`)),e}getSignalInfo(){var e;return((e=this.signalChannel)==null?void 0:e.getSignalInfo())||{clientIp:"",relayIp:""}}reset(e=!1){this.stopSyncUserListInterval(),this.stopHeartbeat(),this.closeConnections(),this.clearNetworkQuality(),this.closeUplink("you exitRoom"),this.signalChannel&&(e&&this.signalChannel.keepAlive&&this.signalChannel.isConnected?this.signalChannel.stopKeepAliveIn(3600):(this.signalChannel.close(),this.setSignalChannel(null))),this.localPublishFlag=0,this.heartbeatCount=0,this._stats.reset(),this.userManager.clear(),this.userManager.removeAllListeners(),this.singlePC&&(this.singlePC.close(),this.singlePC=null),this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}}checkSubscribeBigSmallVideo(e){return f(this,null,function*(){let{subscribeState:t,userId:r,muteState:{hasSmall:s,hasVideo:n}}=e;if(!s&&!n||!t.video&&!t.smallVideo)return;let a=this._changeBigSmallRecords.get(r);if(!a||a.isSubscribing||a.reSubscribeCount<=0)return;let{options:d,reSubscribeCount:l}=a;if(d.video&&t.video||d.smallVideo&&t.smallVideo&&s)return;let u={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:d.video,smallVideo:d.smallVideo};try{if(!s&&u.smallVideo&&(u.video=!0,u.smallVideo=!1),u.smallVideo===t.smallVideo&&u.video===t.video)return;a.isSubscribing=!0,a.reSubscribeCount=l-1,yield e.subscribe(u,"main"),e.remoteVideoTrack.setMediaType(u.smallVideo?8:4),this._log.info(`change [${r}] to ${u.smallVideo?"small":"big"} video successfully. count ${Oo-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount=Oo}catch(h){this._log.info(`change [${r}] to ${u.smallVideo?"small":"big"} video failed. count ${Oo-a.reSubscribeCount}. reason: ${h}`),a.isSubscribing=!1,a.reSubscribeCount===0&&this._changeBigSmallRecords.delete(r)}})}changeType(e,t){let s={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:Oo};this._changeBigSmallRecords.set(t.userId,s),this._log.info(`set [${t.userId}] video prefer type: ${e?"small":"big"}`),this.emit("subscribe-small-video-changed",{userId:t.userId,isSmall:e});let n=this.remotePublishedUserMap.get(t.userId);n&&this.checkSubscribeBigSmallVideo(n)}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(e){this._businessInfo=e.businessInfo;let t={};if(W_(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!No(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new v({code:I.INVALID_PARAMETER,message:$({key:B.INVALID_PURE_AUDIO})});this._pureAudioPushMode=e.pureAudioPushMode,t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.pure_audio_push_mod=this._pureAudioPushMode}if(!No(e.userDefineRecordId)){let r=/^[A-Za-z0-9_-]{1,64}$/gi;if(e.userDefineRecordId.match(r)===null)throw new v({code:I.INVALID_PARAMETER,message:$({key:B.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!No(e.userDefinePushArgs))if(W_(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 v({code:I.INVALID_PARAMETER,message:$({key:B.INVALID_USER_DEFINE_PUSH_ARGS})});DI(t)||(this._businessInfo=JSON.stringify(t))}sendCustomMessage(e){var t;(t=this._customMessageManager)==null||t.send(e)}enableInsertableStreams(){return f(this,null,function*(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&pi)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 v({code:I.INVALID_OPERATION,message:"not join"}))}get enableCodecPipeline(){return this.videoManager.encodePipeline.length>0||this.videoManager.decodePipeline.length>0||this.audioManager.encodePipeline.length>0||this.audioManager.decodePipeline.length>0}get scriptTransformWorker(){var e;return(e=this.singlePC)==null?void 0:e.scriptTransformWorker}switchRoom(e){return f(this,null,function*(){var m;if(!this.signalChannel||!this.singlePC)return;let{roomId:t,strRoomId:r,userSig:s,privateMapKey:n}=e,a=((m=this.scheduleResult.config)==null?void 0:m.autoSubscribeCount)||(e==null?void 0:e.autoSubscribeCount)||1,d=String(this.useStringRoomId?r:t),l=[];for(let g=0;g<a;g++)l.push({audioSsrc:wt(),bigVideoSsrc:wt(),bigVideoRtxSsrc:wt(),auxVideoSsrc:wt(),auxVideoRtxSsrc:wt()});let u={currRoomId:this.roomId,targetRoomId:d,useStringRoomId:this.useStringRoomId,ability:this.singlePC.clientAbility,userSig:s,privateMapKey:n!=null?n:this.privateMapKey,subscribe:l};this.singlePC.autoSubscribedUserMap.clear(),this.singlePC.autoSubscribedSsrcGroups.clear(),this.singlePC.autoSubscribedSsrcGroups.set(d,l);let h=this.roomId;this.roomId=this.useStringRoomId?r:String(t),this.switchRoomSubedReq=new Promise(g=>{this.resolveSwitchRoomSubedReq=g,Ke(5e3).then(g)}),S.emit(A.SWITCH_ROOM_START,{room:this}),yield this.singlePC.waitForPeerConnectionConnected();let p;try{this.userManager.clear(),p=yield this.signalChannel.sendWaitForResponse({command:Z.SWITCH_ROOM,responseCommand:J.SEND_SWITCH_ROOM_RES,data:u});let{code:g,message:E}=p.data;if(g===0)this.userSig=s,No(n)||(this.privateMapKey=n),S.emit(A.SWITCH_ROOM_SUCCESS,{room:this,currentRoomId:h,targetRoomId:d});else{this._log.error(`switch room failed. result: ${g} error: ${E}`);let C=new v({code:I.SWITCH_ROOM_FAILED,extraCode:g,message:E});throw S.emit(A.SWITCH_ROOM_FAILED,{room:this,error:C}),C}}catch(g){throw this.singlePC.autoSubscribedSsrcGroups.clear(),this.roomId=h,this.resolveSwitchRoomSubedReq(),g}})}isSwitchRoomSupported(){var t;let e="unable to use switchRoom API, fallback to exitRoom and enterRoom.";return((t=this.scheduleResult.config)==null?void 0:t.switchRoom)!==!0?(this._log.warn(`${e} Reason: this sdkAppId is not supported, please contact us [https://trtc.io/contact] to enable it.`),!1):this.scene!=="live"?(this._log.warn(`${e} Reason: the scene is not 'live'.`),!1):this.role!=="audience"?(this._log.warn(`${e} Reason: the role is not 'audience'.`),!1):this.singlePC?!0:(this._log.warn(`${e} Reason: is not using single peerConnection.`),!1)}requestRemoteFallbackToH264(){var e;(e=this.singlePC)==null||e.requestRemoteFallbackToH264()}startUpdateNTPTime(){if(!this.signalChannel)return;let e=[];for(let t=0;t<5;t++)e.push(this.updateNTPTime());return Promise.all(e).then(t=>{var d;let r=t[0].offset,s=t[0].offset;t.forEach(l=>{r=Math.min(l.offset,r),s=Math.max(l.offset,s)});let n=Math.floor(t.reduce((l,u)=>l+u.rtt,0)/t.length),a=Math.floor(t.reduce((l,u)=>l+u.offset,0)/t.length);(s-r>30||n>50)&&setTimeout(()=>this.startUpdateNTPTime(),5e3),da(a),(d=this.scriptTransformWorker)==null||d.postMessage({type:"ntp-offset",data:a}),this._log.debug(`ntp updated offset: ${a}`),this.emit("ntp-time-updated")}).catch(t=>{this._log.warn(`ntp updated failed: ${t}`)})}updateNTPTime(){let e=Date.now();return this.signalChannel.sendWaitForResponse({command:Z.UPDATE_NETWORK_TIME,responseCommand:J.UPDATE_NETWORK_TIME_RESULT,addReceiveTime:!0,data:{clientSendTime:String(e)},enableLog:!1}).then(t=>{let r=Number(t.data.data.serverSendTime),s=Number(t.data.data.serverRecvTime),n=t.data.receiveTime||Date.now(),a=(s-e+(r-n))/2;return{rtt:n-e-(s-r),offset:a}})}};D([ye(["left",j.INIT],"joined"),Mt({settings:{retries:1,timeout:0},onRetrying(e){this._log.warn(`join retry ${e}`)},onRetryFailed(e){this._log.error("join failed",e)},onError(e,t){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),xt(!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()],Si.prototype,"join",1),D([ye("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),Qf(),xd("leave room"),Rn({fnName:"publish",validateArgs:!1}),Rn({fnName:"unsubscribe",validateArgs:!1})],Si.prototype,"leave",1),D([Ti(e=>e.mediaType),B_(),Mt({settings:{retries:Wi,timeout:e=>Zt(e)},onError(e,t,r,[s]){var n;(n=e.message)!=null&&n.includes("timeout")?(this._log.warn(`publish ${s.strMediaType} timeout`,e),t()):(this._log.error(`publish ${s.strMediaType} failed: ${e}`),r(e),S.emit(A.PUBLISH_FAILED,{room:this}))}})],Si.prototype,"publish",1),D([Rn({fnName:"publish"}),Ti(e=>e.mediaType),H_(),Ct(function(){var e,t;this.localTracks.size===0&&Rr()&&((t=(e=this.singlePC)==null?void 0:e.getPeerConnection())==null||t.getSenders().forEach(r=>r.track&&r.replaceTrack(null)))})],Si.prototype,"unpublish",1),D([Od(e=>{if(e.code!==I.API_CALL_ABORTED)throw e}),Ti(e=>e.userId)],Si.prototype,"replaceTrack",1),D([Ti((...e)=>e[0].userId),Eo(),Yf(),Mt({settings:{retries:Wi,timeout:e=>Zt(e)},onError(e,t,r,s){e.message.includes("timeout")?(this._log.warn("subscribe timeout"),t()):(this._log.error(`subscribe failed: ${e}`),r(e),S.emit(A.SUBSCRIBE_FAILED,{room:this,remoteTracks:s}))}})],Si.prototype,"subscribe",1),D([Rn({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")})}}),Ti((...e)=>e[0].userId)],Si.prototype,"unsubscribe",1);Kn.create=Kn._create.bind(Kn,Si);lu(30);var L4=Kn;export{L4 as default};
122
+ `,e=new Blob([i],{type:"application/javascript"}),t=URL.createObjectURL(e);this.worker=new Worker(t),URL.revokeObjectURL(t),this.worker.onerror=r=>this._log.warn("worker error:",r.message,r.filename||"unknown",r.lineno||"unknown"),this.worker.onmessage=r=>{var l;let{type:s,trackId:n,message:a,count:c}=r.data;if(s==="black")(l=this.callbacks.get(n))==null||l();else if(s==="log")this._log.warn(a);else if(s==="blackCount"){let h=this.userIdMap.get(n);this._log.warn(`${h||n} black count: ${c}`)}}}return this.worker}start({track:i,isUplink:e,room:t,userId:r,onBlack:s}){if(this._log.debug("start detect black video",i.id),!Tn()||!s||!i||typeof Worker=="undefined"){this._log.warn("black video detector not supported");return}let n=a=>{var l,h,m,u;let c;if(e)c=(h=(l=a.msg_up_stream_info)==null?void 0:l.msg_video_status)==null?void 0:h.filter(_=>_.uint32_video_stream_type===3)[0];else{let _=(m=a.msg_down_stream_info)==null?void 0:m.filter(g=>{var E;return((E=g.msg_user_info)==null?void 0:E.str_identifier)===r})[0];c=(u=_==null?void 0:_.msg_video_status)==null?void 0:u.filter(g=>g.uint32_video_stream_type===3)[0]}if(c){let _=(c.uint32_video_codec_bitrate||0)/1e3;if(this.sleep[i.id]&&this.sleep[i.id]>0){this.sleep[i.id]-=1;return}_>0&&_<10&&(this.sleep[i.id]=30,this._log.info("track bitrate",_,"start check"),this.checkOnce(i,30*1e3))}};return t.on("heartbeat-report",n),this.heartbeatListenerCleaner.set(i.id,()=>t.off("heartbeat-report",n)),this.callbacks.set(i.id,s),this.userIdMap.set(i.id,r),i.id}checkOnce(i,e){try{let t=this.getWorker();if(!t)throw new Error("Worker not available");let r=new MediaStreamTrackProcessor({track:i});t.postMessage({type:"addTrack",trackId:i.id,timeout:e,readable:r.readable},[r.readable])}catch(t){this._log.warn("check error:",t),this.stop(i.id)}}stop(i){if(i){this.worker&&this.worker.postMessage({type:"removeTrack",trackId:i}),this.callbacks.delete(i),delete this.sleep[i];let e=this.heartbeatListenerCleaner.get(i);e&&e(),this.heartbeatListenerCleaner.delete(i),this.userIdMap.delete(i)}}destroy(){this.callbacks.forEach((i,e)=>this.stop(e)),this.worker&&(this.worker.terminate(),this.worker=null)}},ur=new gm;var $d=class extends vo{constructor(e){super(L(O({},e),{isUplink:!0}));d(this,"localMainAudioTrack",null);d(this,"localMainVideoTrack",null);d(this,"localAuxAudioTrack",null);d(this,"localAuxVideoTrack",null);d(this,"_isPublishingAux",!1);d(this,"_publishingLocalAudioTrack");d(this,"_publishingLocalVideoTrack");d(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,videoDecCodec:"",audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0});d(this,"_flag",0);d(this,"_checkPublishStateTimeoutId",-1);this.initialize()}get videoCodec(){var e;return((e=this.singlePC)==null?void 0:e.videoCodec)||"h264"}get ssrc(){if(!this.singlePC)return{audio:0,video:0,videoRtx:0,small:0,smallRtx:0,auxiliary:0,auxiliaryRtx:0};let{audioSsrc:e,bigVideoSsrc:t,bigVideoRtxSsrc:r,smallVideoSsrc:s,smallVideoRtxSsrc:n,auxVideoSsrc:a,auxVideoRtxSsrc:c}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:r||0,small:s||0,smallRtx:n||0,auxiliary:a||0,auxiliaryRtx:c||0}}get flag(){return this._flag}set flag(e){this._flag!==e&&(this._flag=e,this.checkPublishState())}checkPublishState(e=!1){try{if(!e&&this._checkPublishStateTimeoutId>0)return;let{serverPublishState:t}=this,{publishState:r}=this._room,s=Object.keys(r).filter(n=>{if(r[n]!==t[n]&&r[n])switch(n){case"audio":return!(!this.localMainAudioTrack||!this.localMainAudioTrack.isMediaTrackActive);case"bigVideo":case"smallVideo":return!(!this.localMainVideoTrack||!this.localMainVideoTrack.isMediaTrackActive);case"auxVideo":return!(!this.localAuxVideoTrack||!this.localAuxVideoTrack.isMediaTrackActive)}return!1});if(s.length>0){if(e)v.addCount({key:521e3}),s.forEach(n=>{this._log.warn(`${n} publish failed during call ${ai()} ${ni()}`),v.addEnum({key:521719,value:q_[n]})});else{this._checkPublishStateTimeoutId=oe.run("timeout",()=>this.checkPublishState(!0),{delay:10*1e3,count:1});return}oe.clearTask(this._checkPublishStateTimeoutId),this._checkPublishStateTimeoutId=-1}}catch(t){this._log.warn("checkPublishState failed",t)}}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}get serverPublishState(){return{audio:!!(this.flag&_r),bigVideo:!!(this.flag&fr),smallVideo:!!(this.flag&Bs),auxVideo:!!(this.flag&Hr)}}initialize(){this.installEvents()}close(e){var r;let t=((r=this._peerConnection)==null?void 0:r.getSenders())||[];for(let s of t)s.replaceTrack(null);super.close(e),this.uninstallEvents(),this.uninstallTrackMuteEvents(this.localMainAudioTrack,this.localMainVideoTrack,this.localAuxVideoTrack),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),this.installSPCEvents()}installSPCEvents(){var e,t;(e=this.singlePC)!=null&&e.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||(t=this.singlePC)==null||t.on("spc-reconnected",this.onSinglePCReconnected,this)}uninstallSPCEvents(){var e;(e=this.singlePC)==null||e.off("spc-reconnected",this.onSinglePCReconnected,this)}uninstallEvents(){this.off("connection-state-changed",this.handleConnectionStateChange,this),this.uninstallSPCEvents()}emitConnectionStateChangedEvent(e,t){var n,a,c;let r=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&r!==e&&(t?t.emit("connection-state-changed",{prevState:r,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:r,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:r,state:e}),(c=this._publishingLocalVideoTrack)==null||c.emit("connection-state-changed",{prevState:r,state:e}))),s}onVideoEncodeFailed(e){return f(this,null,function*(){if(!e||!e.isMediaTrackActive)return;let{videoCodec:t,singlePC:r}=this;if(!r)return;let s={h265:{supported:r.isH264EncodeSupported,target:"h264",log:"h265 encoder not working"},h264:{supported:r.isVP8EncodeSupported,target:"vp8",log:"h264 encoder not working"},vp8:{supported:!1,target:"vp8",log:"vp8 encoder not working, no fallback available"}};if(t==="vp9"||t==="av1")return;let n=s[t];this._log.warn(n.log),n!=null&&n.supported&&(yield r.switchVideoEncoder(n.target))})}publish(s){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:r}){var c,l,h,m,u,_,g;if(!this.singlePC)return;if(this.installEvents(),this.installTrackMuteEvents(e,t),t&&(t.retryEncodeFailed=this.onVideoEncodeFailed.bind(this)),yield this.singlePC.waitForPeerConnectionConnected(),e&&(this._publishingLocalAudioTrack=e),t){if(!this.singlePC.isH264EncodeSupported&&!this.singlePC.isVP8EncodeSupported)throw new D({code:I.NOT_SUPPORTED_H264,message:$({key:B.NOT_SUPPORTED_H264ENCODE})});this.singlePC.isUsingH264&&!this.singlePC.isH264EncodeSupported&&this.singlePC.isVP8EncodeSupported&&(this._log.warn("h264 encoder not supported"),yield this.singlePC.switchVideoEncoder("vp8")),fe&&Ko()===115&&t.profile.width*t.profile.height<=640*360&&(this._log.warn(`fallback video to defaultBigVideoProfile: ${JSON.stringify(pr)}`),t.setProfile(pr),yield t.applyProfile()),this._publishingLocalVideoTrack=t}this._isPublishingAux=r;let n;if(t&&!r&&t.small&&(n=this._room.videoManager.smallTrack),yield this._signalChannel.sendWaitForResponseWithRetry({command:Z.SPC_PUBLISH,responseCommand:W.SPC_PUBLISH_RESULT,data:L(O({},this.singlePC.uplinkSSRC),{state:this._room.publishState,muteState:this._room.muteState}),retries:3}),yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:n,isAuxiliary:r}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,t){this[r?"localAuxVideoTrack":"localMainVideoTrack"]=t,yield this.singlePC.setDegradationPreference(this._peerConnection.getSenders()[r?3:1],t.contentHint,t.streamType);let{scaleResolutionDownBy:E}=t;yield this.singlePC.setScaleResolutionDownBy(this._peerConnection.getSenders()[r?3:1],E,t.streamType)}e&&(this[r?"localAuxAudioTrack":"localMainAudioTrack"]=e),yield this.singlePC.setBandwidth({audio:((c=this.localMainAudioTrack)==null?void 0:c.profile.bitrate)||((l=this.localAuxAudioTrack)==null?void 0:l.profile.bitrate),bigVideo:(h=this.localMainVideoTrack)==null?void 0:h.profile.bitrate,smallVideo:(u=(m=this.localMainVideoTrack)==null?void 0:m.small)==null?void 0:u.bitrate,auxVideo:(_=this.localAuxVideoTrack)==null?void 0:_.profile.bitrate}),this.sendMediaSettings(),(this._room.preferHW||(g=this._room.scheduleResult.config)!=null&&g.preferHW)&&t&&t.profile.width*t.profile.height>=1280*720&&this.singlePC.useHWEncoder(!0,r?7:2);let a=new URLSearchParams(location.search).get("profileLevelId");a&&this.singlePC.setProfileLevelId(a)})}publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:r,isAuxiliary:s}){if(!St())return;this._log.info("publish by transceiver");let n=t==null?void 0:t.outMediaTrack,a=e==null?void 0:e.outMediaTrack,c=this._peerConnection.getTransceivers(),l=[],h=[],m=(_,g,E)=>{var k;let A=c[g].sender.replaceTrack(E);h.push(g),(k=this.singlePC)!=null&&k.enableInsertableStreams&&A.then(()=>this.createEncodedStreams(c[g].sender,_)),this.initSenderTransform(c[g].sender,_),l.push(A)};a&&m(e.mediaType,0,a),n&&m(t.mediaType,s?3:1,n),t!=null&&t.small&&l.push(this.publishSmall(this._room.videoManager.smallMode,t));let u=this.singlePC.setTransceiverDirection(ae.SENDONLY,h);return l.push(u),Promise.all(l)}getTrackByMediaType(e){switch(e){case 1:return this.localMainAudioTrack||this._room.localMainAudioTrack;case 4:case 8:return this.localMainVideoTrack||this._room.localMainVideoTrack;case 2:return this.localAuxVideoTrack||this._room.localAuxVideoTrack;default:return null}}createEncodedStreams(e,t){var a,c;if(this.singlePC.insertableStreamsAbortMap.has(e))return;let r=e.createEncodedStreams(),s=new AbortController;(a=this.singlePC)==null||a.addAbortController(e,s),((c=this.getTrackByMediaType(t))!=null&&c.enableEncodeFrame?r.readable.pipeThrough(new TransformStream({transform:(l,h)=>{var u,_;let m=this.getTrackByMediaType(t);if(!m||!m.encodeFrame)return h.enqueue(l);m.isAudio?h.enqueue(m.enableEncodeFrame?m.encodeFrame(l):l):h.enqueue((u=this.singlePC)!=null&&u.isUsingH264||(_=this.singlePC)!=null&&_.isUsingH265?m.encodeFrame(l,t===8):l)}}),s):r.readable).pipeTo(r.writable,s).catch(l=>{this._log.debug("encoded stream error",l),l!=="destroy"&&this._log.warn(l)})}initSenderTransform(e,t){if(!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker||!as)return;let r=t!==2,s=t===8;e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!1,isAudio:t===1,isMain:r,isSmall:s}))}enableSmall(e){return f(this,null,function*(){e?yield this.publishSmall(this._room.videoManager.smallMode):yield this.unpublishSmall()})}publishSmall(r){return f(this,arguments,function*(e,t=this.localMainVideoTrack){var l;if(!this.singlePC)return;if(e==="canvas"&&!Ac()){this._log.warn("canvas mode small stream is not supported");return}let s=this._peerConnection.getTransceivers(),{sender:n}=s[2],a=yield this.doPublishSmall(e,t),c=e==="canvas"?524700:524701;if(v.addSuccessEvent({key:c}),!a){v.addFailedEvent({key:c,error:10001});return}(l=this.singlePC)!=null&&l.enableInsertableStreams&&this.createEncodedStreams(n,8),this.initSenderTransform(n,8),yield this.singlePC.setTransceiverDirection(ae.SENDONLY,[2]),this.updateMediaSettings(),yield this.doPublishChange(),n.track&&(this._blackSmallVideoDetectionId=ur.start({track:n.track,room:this._room,isUplink:!0,userId:this.userId,onBlack:()=>{this._log.warn("small video is black");let h=e==="canvas"?524700:524701;v.addFailedEvent({key:h,error:10002}),ur.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0}}))})}doPublishSmall(r){return f(this,arguments,function*(e,t=this.localMainVideoTrack){if(!this.singlePC)return null;this._log.info("publish small",e);let s=this._peerConnection.getTransceivers(),{sender:n}=s[2];if(e==="canvas"&&this._room.videoManager.smallTrack)return yield n.replaceTrack(this._room.videoManager.smallTrack),"canvas";if(e==="api"&&(t!=null&&t.outMediaTrack)&&(t!=null&&t.small)){yield n.replaceTrack(t==null?void 0:t.outMediaTrack);let a=n.getParameters(),c=Go(t==null?void 0:t.profile,t==null?void 0:t.small);return this._log.info("small scaleResolutionDownBy",c),a.encodings[0].scaleResolutionDownBy=c,n.setParameters(a),"api"}return this._log.warn(`small track can not be enabled, smallMode: ${this._room.videoManager.smallMode}, smallTrack: ${!!this._room.videoManager.smallTrack}, bigVideoTrack: ${!!(t!=null&&t.outMediaTrack)}`),null})}unpublishSmall(){return f(this,null,function*(){if(!this.singlePC)return;this._log.info("unpublish small"),yield this._peerConnection.getTransceivers()[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(ae.INACTIVE,[2]),this.updateMediaSettings(),yield this.doPublishChange(),ur.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0})}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(r){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){var l;yield(l=this.singlePC)==null?void 0:l.waitForPeerConnectionConnected();let s=t&&t===this.localAuxVideoTrack||e&&e===this.localAuxAudioTrack,n=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),c=[];e&&(s?this.localAuxAudioTrack=null:this.localMainAudioTrack=null,!this.localMainAudioTrack&&!this.localAuxAudioTrack&&(yield a[0].replaceTrack(null),c.push(0))),n&&(s?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=L(O({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),c.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=L(O({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),c.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.singlePC.setTransceiverDirection(ae.INACTIVE,c),yield this.doPublishChange(!1)):yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),t==null||t.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return f(this,null,function*(){let t={state:this._room.publishState,constraintConfig:this._mediaSettings},r=yield this._signalChannel.sendWaitForResponseWithRetry({command:Z.PUBLISH_STATE_CHANGE,data:t,responseCommand:W.PUBLISH_STATE_CHANGE_RESULT,enableLog:e,retries:3});this.checkPublishResultCode(r.data.code,r.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:Z.UNPUBLISH,commandDesc:"unpublish",responseCommand:W.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===I.API_CALL_TIMEOUT||t.getCode()===I.API_CALL_ABORTED)return Promise.resolve();throw t})}updateMediaSettings(){var s,n;this._mediaSettings.videoCodec=((s=this.singlePC)==null?void 0:s.videoCodec)||"h264",this._mediaSettings.videoDecCodec=((n=this.singlePC)==null?void 0:n.downlinkVideoCodec)||"h264";let e=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:t,localAuxVideoTrack:r}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?r=this._publishingLocalVideoTrack:t=this._publishingLocalVideoTrack),bi){if(e&&e.outMediaTrack){let a=e.outMediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=e.profile.bitrate*1e3,this._mediaSettings.audioFs=a.sampleRate||0}if(t&&t.outMediaTrack){let a=t.outMediaTrack.getSettings(),{scaleResolutionDownBy:c}=t;this._mediaSettings.videoWidth=(a.width||0)/c||0,this._mediaSettings.videoHeight=(a.height||0)/c||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=t.profile.bitrate*1e3,t.small&&(this._mediaSettings.smallVideoWidth=t.small.width,this._mediaSettings.smallVideoHeight=t.small.height,this._mediaSettings.smallVideoFps=t.small.frameRate,this._mediaSettings.smallVideoBps=t.small.bitrate*1e3)}if(r&&r.outMediaTrack){let a=r.outMediaTrack.getSettings(),{scaleResolutionDownBy:c}=r;this._mediaSettings.auxVideoWidth=(a.width||0)/c||0,this._mediaSettings.auxVideoHeight=(a.height||0)/c||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=r.profile.bitrate*1e3}}else e&&e.outMediaTrack&&(this._mediaSettings.audioChannel=e.profile.channelCount,this._mediaSettings.audioBps=e.profile.bitrate*1e3,this._mediaSettings.audioFs=e.profile.sampleRate),t&&t.outMediaTrack&&(this._mediaSettings.videoWidth=t.profile.width,this._mediaSettings.videoHeight=t.profile.height,this._mediaSettings.videoFps=t.profile.frameRate,this._mediaSettings.videoBps=t.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:Z.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:W.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return f(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is adding ${e.kind} track to current published local ${t?p.AUXILIARY:p.MAIN} stream`),br()&&(yield this.addTrackByTransceiver(e,t))})}addTrackByTransceiver(e,t){return f(this,null,function*(){var s;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===p.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),n===1&&((s=this.localMainVideoTrack)!=null&&s.small)&&this._room.videoManager.smallTrack&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===ae.INACTIVE&&(yield this.singlePC.setTransceiverDirection(ae.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}removeTrack(e){return f(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${t?p.AUXILIARY:p.MAIN} stream`),br()&&(yield this.removeTrackByTransceiver(e,t))})}removeTrackByTransceiver(e,t){return f(this,null,function*(){if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===p.AUDIO)yield r[0].sender.replaceTrack(null);else{let s=t?3:1;yield r[s].sender.replaceTrack(null),s===1&&this._room.videoManager.hasSmall&&(yield r[2].sender.replaceTrack(null)),yield this.singlePC.setTransceiverDirection(ae.INACTIVE,[s])}this.updateMediaSettings(),yield this.doPublishChange()})}replaceTrack(e){return f(this,null,function*(){var n;let t=(n=this._peerConnection)==null?void 0:n.getSenders(),r=e.outMediaTrack||e.mediaTrack;if(!t||t.length===0||!r||t.find(a=>a.track===r))return!1;let s=e.mediaType===2||e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info(`is replacing ${r.kind} track ${r.id} ${r.label} on ${s?p.AUXILIARY:p.MAIN} stream`),r.kind===p.AUDIO&&t[0]&&(yield t[0].replaceTrack(r)),r.kind===p.VIDEO&&(!s&&t[1]&&(yield t[1].replaceTrack(r)),s&&t[3]&&(yield t[3].replaceTrack(r))),!0})}setBandwidth(s){return f(this,arguments,function*({bandwidth:e,type:t,videoType:r}){if(this.singlePC){let n={};t===p.AUDIO?n.audio=e:r==="big"?n.bigVideo=e:r==="small"?n.smallVideo=e:n.auxVideo=e,yield this.singlePC.setBandwidth(n)}})}sendMutedFlag(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info(`send muted state: ${JSON.stringify(this._room.muteState)}`),this._signalChannel.sendWaitForResponseWithRetry({command:Z.UPDATE_MUTE_STAT,responseCommand:W.MUTE_RESULT,data:this._room.muteState,retries:3}).catch(()=>{}))}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&S.emit(C.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(e=p.VIDEO){if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===p.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===p.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===p.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===p.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===$r?(this._log.error(Xe.NOT_SUPPORTED_H264ENCODE),new D({code:I.NOT_SUPPORTED_H264,message:$({key:B.NOT_SUPPORTED_H264ENCODE})})):new D({code:I.UNKNOWN,message:$({key:B.SIGNAL_RESPONSE_FAILED,data:{signalResponse:W.PUBLISH_RESULT,code:e,message:t}})})}onSinglePCReconnected(){return f(this,null,function*(){this.isMainStreamPublished&&(this._log.warn("republish main stream"),yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(this._log.warn("republish aux stream"),yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0}))})}};M([Ct(({localVideoTrack:e})=>{e==null||delete e.retryEncodeFailed})],$d.prototype,"unpublish",1);var q_=(r=>(r[r.audio=1]="audio",r[r.bigVideo=2]="bigVideo",r[r.smallVideo=3]="smallVideo",r[r.auxVideo=4]="auxVideo",r))(q_||{}),Tm=$d;function J_(o){return Object.keys(o).filter(i=>o[i])}var Ps=class extends vo{constructor(e){super(L(O({},e),{isUplink:!1}));d(this,"_flag",0);d(this,"isRobot",!1);d(this,"role","anchor");d(this,"remoteAudioTrack");d(this,"remoteVideoTrack");d(this,"remoteAuxiliaryTrack");d(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0});d(this,"jitterBufferTimeoutId",-1);d(this,"_videoCodec");d(this,"pipSyncManager");this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=new Ti(this._room,this),this.remoteVideoTrack=new ki(this._room,this),this.remoteAuxiliaryTrack=new Is(this._room,this),this.pipSyncManager=new Ro({log:this._log,remoteVideoTrack:this.remoteVideoTrack,remoteAudioTrack:this.remoteAudioTrack}),this.initialize()}get videoCodec(){var e;return this._videoCodec||((e=this.singlePC)==null?void 0:e.downlinkVideoCodec)||"h264"}set videoCodec(e){this._videoCodec=e}get subscribeState(){return{audio:this.remoteAudioTrack.isSubscribed||this.remoteAudioTrack.isSubscribing,video:this.remoteVideoTrack.isBig&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),smallVideo:this.remoteVideoTrack.isSmall&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),auxiliary:this.remoteAuxiliaryTrack.isSubscribed||this.remoteAuxiliaryTrack.isSubscribing}}get muteState(){return ei(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,r,s;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(r=this.remoteVideoTrack)==null||r.onFlagChanged(),(s=this.remoteAuxiliaryTrack)==null||s.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===p.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){clearTimeout(this.jitterBufferTimeoutId),super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.pipSyncManager.destroy(),this.uninstallEvents(),this.removeDownlink()}installEvents(){this.singlePC&&(this.listeners("track").includes(this.onTrack)||this.singlePC.on("track",this.onTrack,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||this.singlePC.on("spc-reconnected",this.onSinglePCReconnected,this),this.remoteVideoTrack.on("decode-failed",this.onDecodeFailed,this))}uninstallEvents(){this.singlePC&&(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this),this.remoteVideoTrack.off("decode-failed",this.onDecodeFailed,this))}emitConnectionStateChangedEvent(e){var s,n;let t=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&t!==e&&((s=this.remoteVideoTrack)==null||s.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),r}onTrack(e){var h,m;let t=e.streams[0],{track:r,receiver:s}=e;if(!t.id.includes(this.tinyId))return;let a=t.id.includes("aux")?"auxiliary":"main";this._log.debug(`ontrack ${a} ${r.kind}`);let c=p.AUDIO;r.kind===p.VIDEO&&(c=a===p.MAIN?p.VIDEO:p.AUXILIARY);let l=this.remoteAudioTrack;c===p.VIDEO?l=this.remoteVideoTrack:c===p.AUXILIARY&&(l=this.remoteAuxiliaryTrack),(h=this.singlePC)==null||h.receiverRemoteTrackMap.set(s,l),(m=this.singlePC)!=null&&m.scriptTransformWorker&&this.initReceiverTransform(s,a,r.kind===p.AUDIO),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(s),l.setInputMediaStreamTrack(r)}createEncodedStreams(e){if(!this.singlePC.insertableStreamsAbortMap.has(e)){let t=e.createEncodedStreams(),r=new AbortController,s={abortController:r,enqueue:n=>{var c,l,h;let a=(c=this.singlePC)==null?void 0:c.receiverRemoteTrackMap.get(e);return!a||a.kind==="video"&&!((l=this.singlePC)!=null&&l.isUsingH264)&&!((h=this.singlePC)!=null&&h.isUsingH265)?n:a.decodeFrame(n)}};t.readable.pipeThrough(new TransformStream({transform:(n,a)=>{let c=s.enqueue(n);c&&a.enqueue(c)}})).pipeTo(t.writable,r).catch(n=>{n!=="destroy"&&this._log.warn(n)}),this.singlePC.addAbortController(e,r)}}initReceiverTransform(e,t,r){!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker||e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!0,isAudio:r,userId:this.userId,streamType:t}))}subscribe(e,t){return f(this,null,function*(){var r,s;try{let n=!0;if(this._log.info(`subscribe ${t} ${J_(e)}`),this.hasSSRC){let l="subscribe_change";Object.values(e).find(h=>h===!0)||(l="unsubscribe"),yield this.sendSubscription(l,e)}else{if(yield this._room.switchRoomSubedReq,(r=this.singlePC)!=null&&r.autoSubscribedUserMap.size){let l=this.singlePC.autoSubscribedUserMap.get(this.userId);if(l){this.singlePC.autoSubscribedUserMap.delete(this.userId);let h=(s=this.singlePC.autoSubscribedSsrcGroups.get(this._room.roomId))==null?void 0:s[l.groupIndex];h&&(this.ssrc={audio:h.audioSsrc,video:h.bigVideoSsrc,videoRtx:h.bigVideoRtxSsrc,auxiliary:h.auxVideoSsrc,auxiliaryRtx:h.auxVideoRtxSsrc},n=!1)}}yield this.doSubscribe(e,n),this.checkTrackEnded(e)}let{user:a,mediaTrack:c}=this.remoteVideoTrack;e.smallVideo&&c?(v.addSuccessEvent({key:524702}),this._blackSmallVideoDetectionId=ur.start({track:c,isUplink:!1,room:this._room,userId:this.userId,onBlack:()=>{this._log.warn("small video is black, auto change to big"),this._room.changeType(!1,a),v.addFailedEvent({key:524702}),ur.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0}})):(ur.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0)}catch(n){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${n.message} ${JSON.stringify(this.muteState)}`),new D({code:I.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):n}})}checkTrackEnded(e){var t,r,s;if((e.audio&&((t=this.remoteAudioTrack.mediaTrack)==null?void 0:t.readyState)==="ended"||e.video&&((r=this.remoteVideoTrack.mediaTrack)==null?void 0:r.readyState)==="ended"||e.auxiliary&&((s=this.remoteAuxiliaryTrack.mediaTrack)==null?void 0:s.readyState)==="ended")&&this.singlePC&&!this.singlePC.isReconnecting){if(this._log.warn("remote track ended start spc reconnect"),We&&je<92)return;this.singlePC.startReconnection()}}unsubscribe(r){return f(this,arguments,function*({remoteTracks:e,streamType:t}){var a;if(t==="main"&&!this.isMainStreamSubscribed||t==="auxiliary"&&!this.isAuxStreamSubscribed){this._log.info(`${t} stream already unsubscribed`);return}let s=O({},this.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:s.audio=!1;break;case 4:s.video=!1;break;case 8:s.smallVideo=!1;break;case 2:s.auxiliary=!1;break;default:break}});let n="subscribe_change";Object.values(s).find(c=>c===!0)||(n="unsubscribe"),this._log.info(`${n==="unsubscribe"?n:"subscribe"} ${t} [${J_(s)}]`),n==="unsubscribe"&&((a=this.singlePC)==null||a.removeDownlinkQueue.add(this.tinyId)),yield this.sendSubscription(n,s),t==="main"&&(ur.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0),n==="unsubscribe"&&(yield this.removeDownlink())})}sendSubscription(e,t=this.subscribeState){let r={srcTinyId:this.tinyId,srcUserId:this.userId},s=Z.UNSUBSCRIBE,n=W.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(r={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},s=Z.SUBSCRIBE_CHANGE,n=W.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponseWithRetry({command:s,data:r,responseCommand:n,timeout:1e4,retries:3}).then(({data:a})=>{if(a.code!==0){let c=new D({code:a.code,message:$({key:B.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(c),c}})}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}setDelay({audioDelay:e,videoDelay:t}){this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=t}onSinglePCReconnected(){return f(this,null,function*(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary)&&(this._log.warn(`resubscribe ${JSON.stringify(this.subscribeState)}`),yield this.doSubscribe(this.subscribeState),this.remoteAudioTrack.checkDecodeResult(),this.remoteVideoTrack.checkDecodeResult(),this.remoteAuxiliaryTrack.checkDecodeResult())})}get hasSSRC(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}doSubscribe(){return f(this,arguments,function*(e=this.subscribeState,t=!0){if(this.singlePC){this.singlePC.addDownlinkQueue.add(this.tinyId),yield this.singlePC.waitForPeerConnectionConnected();try{if(t||!this.hasSSRC){let r={audioSsrc:xt(),bigVideoSsrc:xt(),bigVideoRtxSsrc:xt(),auxVideoSsrc:xt(),auxVideoRtxSsrc:xt()},{audioSsrc:s,bigVideoSsrc:n,bigVideoRtxSsrc:a,auxVideoSsrc:c,auxVideoRtxSsrc:l}=r;this.ssrc={audio:s,video:n,videoRtx:a,auxiliary:c,auxiliaryRtx:l},this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc});try{let h=yield this._signalChannel.sendWaitForResponseWithRetry({command:Z.SPC_SUBSCRIBE,responseCommand:W.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&&h.data.code!==-10036)throw new D({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(!yc)return;let{main:r,aux:s}=this._room.jitterBufferDelay||{},{jitterDelay:n=r,jitterDelayAux:a=s}=this._room.scheduleResult.config||{};(Q(n)||Q(a))&&this.setJitterBufferDelay({mainDelay:n,auxDelay:a})}}})}removeDownlink(){return f(this,null,function*(){if(!this.singlePC)return;this.ssrc={audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0},this.singlePC.removeDownlinkQueue.delete(this.tinyId);let e=this._room.scheduleResult.config;(e!=null&&e.jitterDelay||e!=null&&e.jitterDelayAux)&&this.setJitterBufferDelay({mainDelay:0,auxDelay:0}),yield this.singlePC.removeDownlink(this.userId)})}setJitterBufferDelay({mainDelay:e,auxDelay:t}){if(!yc||!this.singlePC||!this._peerConnection||gt(e)&&gt(t))return Promise.resolve();this._log.info(`set jitterBuffer main: ${e} aux: ${t}`);let r=this.singlePC.getReceiversByUserId(this.userId);return Q(e)&&(this.remoteAudioTrack.jitterBufferDelay=e,this.remoteVideoTrack.jitterBufferDelay=e),Q(t)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=t,gt(e)&&(this.remoteAudioTrack.jitterBufferDelay=t)),new Promise(s=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:s})})}doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:s}){try{if(e===0&&t===0)return r.forEach(a=>a.jitterBufferTarget=0),s();if(r.forEach(a=>{var m;let c=a.track===this.remoteAuxiliaryTrack.outMediaTrack||gt(e)&&a.track===this.remoteAudioTrack.outMediaTrack;if(c&&gt(t)||!c&&gt(e))return;let l=c?t||0:e,h=(a.jitterBufferTarget||0)+100;h>l||(a.jitterBufferTarget=h,this._log.debug(`set ${c?"aux ":""}${(m=a==null?void 0:a.track)==null?void 0:m.kind} jitterBuffer delay ${h} -> ${l}`))}),!r.find(a=>{let c=a.track===this.remoteAuxiliaryTrack.outMediaTrack?t||0:e;return a.jitterBufferTarget<c}))return this._log.info(`set jitterBuffer main: ${e} aux: ${t} done`),s();this.jitterBufferTimeoutId=setTimeout(()=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:s})},1e3)}catch(n){this._log.warn(`set jitterBuffer delay error: ${n}`),clearTimeout(this.jitterBufferTimeoutId),s()}}get audioReceiver(){var e;return((e=this.singlePC)==null?void 0:e.getReceiversByUserId(this.userId)[0])||null}onDecodeFailed(){this._room.downlinkVideoCodec==="h265"&&this._room.requestRemoteFallbackToH264()}};M([ir(),Y(e=>function(...t){return new Promise((r,s)=>{let n=a=>{this.off("closed",n),s(new D({code:I.API_CALL_ABORTED,message:$({key:B.CONNECTION_ABORTED,data:a})}))};this.on("closed",n),e.apply(this,t).then(r,s).finally(()=>{this.off("closed",n)})})})],Ps.prototype,"subscribe",1),M([ir()],Ps.prototype,"unsubscribe",1),M([gi(()=>"jitter")],Ps.prototype,"setJitterBufferDelay",1);var j_=Ps;function X_(){return Y(o=>function(...i){return f(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(i=i.filter(t=>t.outMediaTrack&&t.state==="ready"),!i.length))return;S.emit("61",{room:this});let e=o.apply(this,i);return Promise.all(i.map(t=>t.publish(this,e)))})})}function z_(){return Y(o=>function(...i){let e=o.apply(this,i);return i.forEach(t=>t.unpublish()),e})}var Q_=Je(at());function wI(){return Math.floor(Math.random()*16383)}var Wd=class Wd extends Q_.EventEmitter{constructor(e,t){super();this.room=e;this.signalChannel=t;d(this,"log");d(this,"cmdIdSeqMap",new Map);d(this,"messageMap",new Map);this.log=R.createLogger({parent:e.getLogger(),id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),t.on(W.RECEIVE_CUSTOM_MSG,this.onReceiveMsg),this.room.on("peer-leave",r=>{[...this.messageMap.keys()].forEach(s=>{s.split("_").slice(0,-1).join("_")===r&&this.messageMap.delete(s)})})}send({cmdId:e,data:t}){let r=this.cmdIdSeqMap.get(e)||wI(),s={cmdId:e,msg:btoa(String.fromCharCode(...new Uint8Array(t))),ordered:!0,reliable:!0,streamSeq:r};this.cmdIdSeqMap.set(e,r+1),this.signalChannel.send(Z.SEND_CUSTOM_MSG,s),this.log.debug(`send custom msg: ${JSON.stringify(s)}`)}onReceiveMsg(e){let{data:t}=e.data,r=this.room.tinyIdToUserIdMap.get(t.srcTinyId);if(r){let s={userId:r,cmdId:t.cmdId,seq:t.streamSeq,data:Uint8Array.from(atob(t.msg),n=>n.charCodeAt(0)).buffer};if(t.ordered){let n=`${r}_${s.cmdId}`,a=this.messageMap.get(n);if(!a||a.lastSeq===0)a||(a={lastSeq:0,cachedMessageMap:new Map},this.messageMap.set(n,a),setTimeout(()=>this.emitMessage(s,!0),100)),a.cachedMessageMap.set(s.seq,{message:s});else if(Math.abs(a.lastSeq-s.seq)>Wd.SEQ_INTERVAL)this.messageMap.set(n,{lastSeq:s.seq,cachedMessageMap:new Map}),this.emitMessage(s);else if(s.seq>a.lastSeq){if(s.seq===a.lastSeq+1)this.emitMessage(s);else if(!a.cachedMessageMap.has(s.seq)){let c=setTimeout(()=>this.emitMessage(s,!0),5e3);a.cachedMessageMap.set(s.seq,{message:s,timeoutId:c})}}else this.log.debug(`drop message ${s.userId}-${s.cmdId}-${s.seq}`)}else this.emit("message",s)}else{this.log.warn(`receive msg from unknown user, wait peer-join tinyId: ${t.srcTinyId}`);let s=n=>{n.tinyId===t.srcTinyId&&(this.room.off("peer-join",s),this.onReceiveMsg(e))};this.room.on("peer-join",s),Ge(2e3).then(()=>this.room.off("peer-join",s))}}emitMessage(e,t=!1){var a;let r=this.messageMap.get(`${e.userId}_${e.cmdId}`),s=e;if(r){if(t){let c=[...r.cachedMessageMap.values()].sort((l,h)=>l.message.seq-h.message.seq);c[0]&&(s=c[0].message)}r.lastSeq!==0&&s.seq-r.lastSeq>1&&this.log.debug(`msg lost userId: ${s.userId} seq: ${r.lastSeq} -> ${s.seq}`),r.lastSeq=s.seq,clearTimeout((a=r.cachedMessageMap.get(s.seq))==null?void 0:a.timeoutId),r.cachedMessageMap.delete(s.seq)}this.log.debug(`receive custom msg: ${JSON.stringify(s)}`),this.emit("message",s);let n=r==null?void 0:r.cachedMessageMap.get(s.seq+1);n&&this.emitMessage(n.message)}};d(Wd,"SEQ_INTERVAL",300);var Gd=Wd;var{isString:Y_,isUndefined:No,getNetworkType:LI,isEmpty:xI}=vt,Ei=class extends Bd{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",ns);d(this,"_changeBigSmallRecords",new Map);d(this,"networkQuality");d(this,"_iceTransportPolicy");d(this,"forceRelay",!1);d(this,"_turnServers",[]);d(this,"_iceServersFromJoin");d(this,"_syncUserListInterval",-1);d(this,"_smallStreamConfig",{bitrate:100,frameRate:15,height:120,width:160});d(this,"enableSEI",!1);d(this,"_enableAudioVolumeEvaluation",!1);d(this,"_audioVolumeIntervalId",0);d(this,"_enableMultiAuxStream",!1);d(this,"_pureAudioPushMode",!1);d(this,"_customMessageManager");d(this,"preferHW",!1);d(this,"healthDetector");d(this,"playoutDelay");d(this,"jitterBufferDelay");d(this,"_updateAudioLevelTaskId",-1);d(this,"switchRoomSubedReq");d(this,"resolveSwitchRoomSubedReq");d(this,"enableVolumeControlInIOS");this._stats=new na(this,this._log),this.userManager=new dd(this.userId,this._log),this._version=$e,this.sdpSemantics=ko,No(e.sdpSemantics)?vi.isUnifiedPlanDefault()&&(this.sdpSemantics=gr):this.sdpSemantics=e.sdpSemantics,this._log.info(`sdpSemantics: ${this.sdpSemantics}, netType: ${LI()}`),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=No(e.enableMultiAuxStream)?!1:e.enableMultiAuxStream,this.enableSEI=e.enableSEI&&ns,!No(e.enableSPC)&&ns&&(this.enableSPC=e.enableSPC),this.preferHW=!!e.preferHW,this.enableVolumeControlInIOS=e.enableVolumeControlInIOS,this._initBusinessInfo(e),this.healthDetector=new F_(this)}get isMainStreamPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.isMainStreamPublished)}get isMainAudioPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.localMainAudioTrack)}get isAuxStreamPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.isAuxStreamPublished)}get hasAuxStream(){return[...this.remotePublishedUserMap.values()].findIndex(e=>e.muteState.hasAuxiliary)>=0}get userMap(){return this.userManager.userMap}get remotePublishedUserMap(){return this.userManager.remotePublishedUserMap}get tinyIdToUserIdMap(){return new Map([...this.userMap.values()].map(e=>[e.tinyId,e.userId]))}get videoCodec(){var e;return((e=this.singlePC)==null?void 0:e.videoCodec)||"h264"}get downlinkVideoCodec(){var e;return((e=this.singlePC)==null?void 0:e.downlinkVideoCodec)||"h264"}join(e,t,r){return f(this,null,function*(){return this.userManager.mySelfId=this.userId,this.userManager.on("1",s=>{this.emit("peer-join",s)}),this.userManager.on("2",s=>{this.closeDownLinkConnection(s,"remote user exitRoom"),this.emit("peer-leave",s)}),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",n=>{var s=la(n,[]);S.emit(C.REMOTE_PUBLISH_STATE_CHANGED,O({room:this},s)),this.emit("remote-publish-state-changed",O({},s))}),this.joinParams=e,new Promise((s,n)=>f(this,null,function*(){var a,c;this._joinReject=n;try{this.checkDestroy();try{yield Promise.all([this.initialize(),this.initSinglePC()])}catch(h){if(h instanceof D&&h.code===I.SPC_INITIALIZED_FAILED)(a=this.signalChannel)==null||a.destroy(),yield this.initialize();else return n(h)}let l=V();yield this.doJoin(e,(c=this.singlePC)==null?void 0:c.clientAbility),v.addSuccessEvent({key:521708,cost:V()-l}),s(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(l){v.addFailedEvent({key:521708,error:l}),n(l)}this._joinReject=null}))})}initSinglePC(){return f(this,null,function*(){if(!(!this.enableSPC||this.singlePC)){this.singlePC=new Xt({signalChannel:this.signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.on("sei-message",e=>this.emit("sei-message",e)),this.singlePC.on("dump",e=>this.emit("dump",e)),this.singlePC.once("error",()=>this.fallbackToMPC());try{return yield this.singlePC.initialize()}catch(e){throw this.fallbackToMPC(),new D({code:I.SPC_INITIALIZED_FAILED,message:e==null?void 0:e.message})}}})}doJoin(e,t){return new Promise((r,s)=>f(this,null,function*(){var c,l,h;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this.signalChannel.once(Ie.SETUP_FAILED,m=>{this.clearJoinTimeout(),S.emit(C.JOIN_SIGNAL_CONNECTION_END,{room:this,error:m}),s(m)}),he((l=(c=this.scheduleResult)==null?void 0:c.config)==null?void 0:l.singlePC)&&ns&&(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:Hl(),netType:qr(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig,receiveMix:!0,isChorus:!!this.enableChorus,enableNtpAudioFrame:!!this.enableChorus&&gn()};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(()=>{s(new D({code:I.JOIN_ROOM_FAILED,message:$({key:B.JOIN_ROOM_TIMEOUT})}))},a),S.emit(C.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?Z.SPC_JOIN_ROOM:Z.JOIN_ROOM,n),this.signalChannel.once(W.JOIN_ROOM_RESULT,m=>f(this,null,function*(){this.clearJoinTimeout();let{code:u,message:_,data:g,tinyId:E}=m.data;S.emit(C.JOIN_RECEIVED_CMD_RES,{room:this,code:u}),u===0?(this._log.info("Join room success, start heartbeat"),E&&(this.tinyId=E),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=g.publishers,this._iceServersFromJoin=g.iceServer?[g.iceServer]:[],this.singlePC&&this.singlePC.setIceServers(this.getIceServers()).then(()=>{var A;(A=this.singlePC)==null||A.connect(L(O({},g.ability),{useVp8:g.ability.useVp8||!!e.useVp8,useH265:g.ability.useH265&&!!e.useH265})).catch(()=>{})}),r()):(this._log.error(`Join room failed result: ${u} error: ${_}`),s(new D({code:I.JOIN_ROOM_FAILED,extraCode:u,message:$({key:B.JOIN_ROOM_FAILED,data:{error:_,code:u}})})))}))}))}reJoin(){return f(this,null,function*(){if(!this.isJoined){this._log.warn("reJoin abort");return}try{this._log.warn(`reJoin pending: ${this.joinParams.roomId}`);let e,t=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,t.push(this.initSinglePC().then(r=>(e=r,r)))),this.signalChannel&&(this.signalChannel.close(),t.push(this.signalChannel.connect())),yield Promise.all(t),yield this.doJoin(L(O({},this.joinParams),{role:this.role==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),e),this._log.warn("reJoin success"),ne.logSuccessEvent({userId:this.userId,eventType:Ke.REJOIN}),this.singlePC){let r=s=>{var n;s.state==="CONNECTED"&&((n=this.singlePC)==null||n.off(xi.CONNECTION_STATE_CHANGED,r),this.uplinkConnection instanceof Tm&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach(a=>{a.installEvents(),a.onSinglePCReconnected()}))};this.singlePC.on(xi.CONNECTION_STATE_CHANGED,r),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof sa&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(e){this._log.warn(`reJoin fail ${e}`),this.reset(),ne.logFailedEvent({userId:this.userId,eventType:Ke.REJOIN,error:e}),this.emit("error",new D({code:I.JOIN_ROOM_FAILED,message:$({key:B.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}})}initialize(){return f(this,null,function*(){let{mainUrl:e,backupUrl:t}=this.getSignalChannelUrl(),r=this.signalChannel||u_(this.userId),s=!!(r&&r.isConnected&&r.keepAlive&&r.userId===this.userId&&r.room===this),n;return Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(n=this.scheduleResult.domains[0]),this._log.info(`${s?"reuse":"setup"} signal channel`),s?(r.url=e,r.backupUrl=t,r.room=this,this.signalChannel=r):(r&&r.close(),this.signalChannel=new Ns({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 Gd(this,this.signalChannel),this._customMessageManager.on("message",a=>{this.emit("custom-message",a)})),this.networkQuality||(this.networkQuality=new ks({signalChannel:this.signalChannel,room:this}),this.networkQuality.on(ks.EVENT_NETWORK_QUALITY,a=>{var c;this.emit("network-quality",a),(c=this.singlePC)==null||c.detectTCPAndUDP(a)})),tt(this,this.signalChannel).add(Ie.CONNECTION_STATE_CHANGED,a=>{S.emit(C.SIGNAL_CONNECTION_STATE_CHANGED,O({room:this},a)),this.emit("signal-connection-state-changed",a)}).add(Ie.RECONNECT_FAILED,a=>{this.reset(),this.emit("error",a)}).add(W.PEER_JOIN,a=>{let{srcTinyId:c,userId:l,role:h}=a.data.data;this.userManager.addUser({userId:l,tinyId:c,role:h})}).add(W.PEER_LEAVE,a=>{let{userId:c,reason:l=0}=a.data.data;this.userManager.deleteUser(c,l)}).add(W.UPDATE_REMOTE_MUTE_STAT,a=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=10*1e3&&this.doHeartbeat(),this.onPublishedUserList(a.data)}).add(W.CLIENT_BANNED,a=>{let c=a.data.data,{reason:l}=c;if(ne.uploadEvent({log:`stat-banned:${l}`,userId:this.userId}),l==="user_time_out"){this._log.warn(`${l} last heart beat time: ${this._lastHeartBeatTime} interval: ${Date.now()-this._lastHeartBeatTime}, visibility: ${document.visibilityState}`),this.reJoin();return}this._log[l==="kick"?"error":"info"](`user was banned because of [${l}]`),this.reset(),this.emit("banned",{reason:l})}).add(W.SEND_SWITCH_ROOM_SUBED_REQ,a=>{if(!this.singlePC)return;let{subList:c}=a.data.data;this._log.info(`auto subscribe ${_t(c,{keysToInclude:["userId"]})}`),c.forEach(l=>{this.singlePC.autoSubscribedUserMap.set(l.userId,l)}),this.resolveSwitchRoomSubedReq()}).add(W.FALLBACK_CODEC,a=>f(this,null,function*(){var l,h,m,u,_;let c=a.data.data;((l=c.videoControlInfo)==null?void 0:l.enableH265Enc)===0&&((h=this.singlePC)==null?void 0:h.videoCodec)==="h265"&&(this._log.warn(`fallback codec enableH265Enc: ${(m=c.videoControlInfo)==null?void 0:m.enableH265Enc}`),v.addCount({key:513e3}),yield(u=this.singlePC)==null?void 0:u.switchVideoEncoder("h264"),yield(_=this.uplinkConnection)==null?void 0:_.sendMediaSettings())})),this.signalChannel.once(Ie.SETUP_SUCCESS,a=>{this.tinyId=a.signalInfo.tinyId,S.emit(C.JOIN_SIGNAL_CONNECTION_END,{room:this})}),S.emit(C.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),s&&S.emit(C.JOIN_SIGNAL_CONNECTION_END,{room:this}),s})}setSignalChannel(e){this.signalChannel=e,e||xe(this)}leave(){return f(this,null,function*(){var e;try{yield this.doHeartbeat()}catch(t){}this._log.info("leave() => leaving room"),S.emit(C.LEAVE_SEND_CMD,{room:this}),(e=this.signalChannel)==null||e.send(Z.LEAVE_ROOM),this.switchRoomSubedReq=void 0})}clearNetworkQuality(){this.networkQuality&&(this.networkQuality.stop(),delete this.networkQuality)}closeConnections(){this.remotePublishedUserMap.forEach(e=>{this.closeDownLinkConnection(e.userId,"you exitRoom")})}clearJoinTimeout(){clearTimeout(this._joinTimeout),this._joinTimeout=-1}startHeartbeat(){this._heartbeat===-1&&(this._heartbeat=oe.run("ric",this.doHeartbeat.bind(this),{delay:2e3}),this.enableChorus&&this.startUpdateNTPTime())}stopHeartbeat(){this._heartbeat!==-1&&(this._log.info("stopHeartbeat"),oe.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return f(this,null,function*(){var n;let e=this.badCaseDetector.getMonitorFreeze(),t=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:e});this.badCaseDetector.resetMonitor();let r=(n=this.signalChannel)!=null&&n.isConnected?yf(this.userId):[],s=L(O({str_sdk_version:Us,uint64_datetime:new Date().getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_event_msg:r,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},t),{msg_device_info:O({uint32_terminal_type:15,str_device_name:ni(),str_os_version:"",uint32_net_type:qr()},t.msg_device_info)});if(this.heartbeatReport=s,this.heartbeatCount++,S.emit(C.HEARTBEAT_REPORT,{room:this,report:s}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(Z.ON_QUALITY_REPORT,s);let a=Date.now();this._lastHeartBeatTime>0&&a-this._lastHeartBeatTime>1e4&&this._log.warn(`heartbeat took ${a-this._lastHeartBeatTime}`),this._lastHeartBeatTime=a,this.signalChannel.isOnline||(this._log.warn("signal channel is not online"),this.signalChannel.startReconnection())}this.emit("heartbeat-report",L(O({},s),{bytes_sent:this._stats.totalBytesSent+this.signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this.signalChannel.bytesReceived}))}!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)})}onPublishedUserList(e){if(!this.isJoined)return;let t=e.data.userList.filter(r=>r.flag!==il).map(({userId:r,srcTinyId:s,flag:n})=>{r===this.userId&&(this.uplinkConnection&&(this.uplinkConnection.flag=n),this.localPublishFlag!==n&&(this.localPublishFlag=n,this.emit("local-publish-flag-changed",n)));let a=this.remotePublishedUserMap.get(r);return a&&this.checkSubscribeBigSmallVideo(a),{userId:r,tinyId:s,flag:n}});e.data.mixRobotList.forEach(({userId:r,srcTinyId:s,flag:n,mixUserList:a})=>{t.unshift({userId:r,tinyId:s,flag:n,isRobot:!0,mixUserList:a})}),e.data.fakeMixUser&&(e.data.fakeMixUser.tinyId=e.data.fakeMixUser.srcTinyId,t.push(e.data.fakeMixUser)),S.emit(C.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:t}),t.find(r=>r.userId===this.userId)||(this.localPublishFlag=0,this.emit("local-publish-flag-changed",0)),this.userManager.setRemotePublishedUserList(t)}closeUplink(e="you unpublished"){this.uplinkConnection&&(this.localTracks.size>0&&this.uplinkConnection.doUnpublish().catch(()=>{}),this.uplinkConnection.close(e),this.uplinkConnection instanceof sa&&(this.uplinkConnection=null)),this.localTracks.forEach(t=>t.unpublish()),this.localTracks.clear()}createDownlinkConnection({userId:e,tinyId:t,flag:r,isRobot:s}){let n=new(this.singlePC?j_:am)({userId:e,tinyId:t,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:r,isRobot:s});this.userManager.addRemotePublishedUser(n),this.installDownlinkEvents(n,e),this.emit("remote-published",n)}closeDownLinkConnection(e,t="remote user unpublished"){let r=this.remotePublishedUserMap.get(e);r&&(r.close(t),this.emit("remote-unpublished",r))}installDownlinkEvents(e,t){e.on("error",r=>{let s=r.getCode();s!==I.ICE_TRANSPORT_ERROR&&(s===I.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",r))}),e.on("connection-state-changed",r=>{this.emit("media-connection-state-changed",L(O({},r),{userId:e.userId}))}),e.on("firewall-restriction",()=>{this.emit("firewall-restriction")})}startSyncUserListInterval(){this._syncUserListInterval===-1&&(this._syncUserListInterval=oe.run("ric",this.syncUserList.bind(this)))}stopSyncUserListInterval(){oe.clearTask(this._syncUserListInterval),this._syncUserListInterval=-1}syncUserList(){return this.getUserList().then(e=>{this.userManager.setUserList(e)}).catch(e=>{this._log.debug(`sync user list failed: ${e}`)})}getUserList(){var e;return(e=this.signalChannel)!=null&&e.isConnected?this.signalChannel.sendWaitForResponse({command:Z.GET_USER_LIST,responseCommand:W.USER_LIST_RES,enableLog:!1,timeout:2e3}).then(({data:t})=>{let{code:r,message:s}=t;if(r===0)return(t.data&&t.data.userList||[]).map(({userId:a,srcTinyId:c,role:l})=>({userId:a,tinyId:c,role:l}));throw $({key:B.SIGNAL_RESPONSE_FAILED,data:{signalResponse:W.USER_LIST_RES,code:r,message:s}})}):Promise.reject("not connected")}getAllConnections(){let e=[...this.remotePublishedUserMap.values()];return this.uplinkConnection&&e.push(this.uplinkConnection),e}isRelayMaybeFailed(){if(this.signalChannel&&!this.signalChannel.isOnline||!tm)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)===ye.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach(r=>{if(r instanceof pt&&!r.getIsReconnecting()){let s=r.getPeerConnection();s&&s.connectionState===ye.CLOSED&&(this._log.warn(`[${r.getUserId()}] pc is closed but not reconnect`),r.startReconnection())}})}fallbackToMPC(){return f(this,null,function*(){var e;if(this._log.warn("fallback to multi pc"),ne.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 sa({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 am({userId:t.userId,tinyId:t.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:t.flag,remoteAudioTrack:t.remoteAudioTrack,remoteVideoTrack:t.remoteVideoTrack,remoteAuxiliaryTrack:t.remoteAuxiliaryTrack});this.installDownlinkEvents(r,t.userId),this.remotePublishedUserMap.set(t.userId,r),t.isMainStreamSubscribed&&(yield r.subscribe(t.subscribeState,"main")),t.isAuxStreamSubscribed&&(yield r.subscribe(t.subscribeState,"auxiliary"))}})}destroy(){this.isDestroyed||(this.signalChannel&&(this._log.info("destroying SignalChannel"),this.signalChannel.close(),this.signalChannel=null),super.destroy(),this._joinReject&&(this._joinReject(new D({code:I.INVALID_OPERATION,message:$({key:B.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners(),this.healthDetector.destroy(),oe.clearTask(this._audioVolumeIntervalId))}switchRole(e){return f(this,null,function*(){this.role!==e&&(e==="audience"&&this.uplinkConnection&&this.closeUplink("you switch role to audience"),yield this.doSwitchRole(e))})}doSwitchRole(e){let t={command:Z.SWITCH_ROLE,data:{role:e==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:W.SWITCH_ROLE_RES,retries:1};return this._log.info(`switchRole signal data: ${JSON.stringify(t.data)}`),this.signalChannel.sendWaitForResponseWithRetry(t).then(r=>{let{code:s,message:n}=r.data;if(s!==0)throw new D({code:I.SWITCH_ROLE_FAILED,message:$({key:B.SWITCH_ROLE_FAILED,data:{message:n,code:s}})});this.role=e}).catch(r=>{throw r instanceof D&&r.getCode()===I.API_CALL_TIMEOUT&&(r=new D({code:I.SWITCH_ROLE_FAILED,message:$({key:B.SWITCH_ROLE_TIMEOUT})})),this._log.error(r),r})}_initUplinkConnection(){this.uplinkConnection=this.singlePC?new Tm({userId:this.userId,tinyId:this.tinyId,room:this}):new sa({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),this.uplinkConnection.on("connection-state-changed",e=>{this.emit("media-connection-state-changed",L(O({},e),{userId:this.userId}))}),this.uplinkConnection.on("firewall-restriction",()=>{this.emit("firewall-restriction")}),this.uplinkConnection.on("error",e=>{let t=e.getCode();t!==I.ICE_TRANSPORT_ERROR&&(t===I.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",e))})}publish(e){return f(this,null,function*(){var r;this.uplinkConnection||this._initUplinkConnection();let t=`${e.streamType} ${e.isAudio&&e.isScreen?"screen":""}${e.kind}`;this._log.info(`publish() => ${t}`),yield(r=this.singlePC)==null?void 0:r.waitForPeerConnectionConnected(),yield this.uplinkConnection.publish({localAudioTrack:e instanceof kt?e:null,localVideoTrack:e instanceof ze?e:null,isAuxiliary:e.streamType==="auxiliary"||e.isScreen})})}unpublish(e){return f(this,null,function*(){if(!(this.scene==="live"&&this.role!=="anchor"||!this.isMainStreamPublished&&!this.isAuxStreamPublished||!this.uplinkConnection)){try{let t=`${e.streamType} ${e.isAudio&&e.isScreen?"screen":""}${e.kind}`;this._log.info(`unpublish() => ${t}`),yield this.uplinkConnection.unpublish({localAudioTrack:e instanceof kt?e:null,localVideoTrack:e instanceof ze?e:null})}catch(t){}this.localTracks.size===0&&this.closeUplink("you unpublished")}})}addTrack(e){if(!this.uplinkConnection||!e.mediaTrack)return Promise.resolve();let t=this.uplinkConnection.addTrack(e);return e.publish(this,t),t}removeTrack(e){return!this.uplinkConnection||!e.mediaTrack?Promise.resolve():(e.unpublish(),this.uplinkConnection.removeTrack(e))}replaceTrack(e){return!this.uplinkConnection||!e.mediaTrack||!hu()?Promise.resolve():this.uplinkConnection.replaceTrack(e).then(t=>{t&&S.emit(C.LOCAL_TRACK_REPLACED,{track:e})})}setBandWidth(e){return f(this,null,function*(){this.uplinkConnection&&(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())})}enableSmall(e){return f(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:p.VIDEO,videoType:p.SMALL,bandwidth:this.uplinkConnection.localMainVideoTrack.small.bitrate})),yield this.uplinkConnection.enableSmall(e)})}subscribe(...e){return f(this,null,function*(){if(e=e.filter(n=>!n.isSubscribed),e.length===0)return;let{userId:t}=e[0],r=this.remotePublishedUserMap.get(t);if(!r)return;let s=e.find(n=>n.mediaType===2)?"auxiliary":"main";try{let n=O({},r.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:n.audio=!0;break;case 4:n.video=!0;break;case 8:n.smallVideo=!0;break;case 2:n.auxiliary=!0;break}});let a=this._changeBigSmallRecords.get(t);a&&a.options.smallVideo&&r.muteState.hasSmall&&n.video&&(n.video=!1,n.smallVideo=!0),S.emit(C.SUBSCRIBE_START,{room:this,streamType:s,remotePublishedUser:r,subscribeState:n}),this._log.info(`subscribe() => ${t} ${s} [${Pd(n)}] prev: [${Pd(r.subscribeState)}]`),yield r.subscribe(n,s),this._log.info(`subscribe ${t} ${s} done`);for(let c of e)c.mediaTrack||(yield c.waitHasMediaTrack());S.emit(C.SUBSCRIBE_SUCCESS,{room:this,streamType:s,remotePublishedUser:r})}catch(n){let a=n instanceof D?n.getCode():I.UNKNOWN,c=n;throw n instanceof D?a===I.REMOTE_STREAM_NOT_EXIST&&(c=new D({code:I.API_CALL_ABORTED,message:$({key:B.API_CALL_ABORTED,data:{message:n.message,userId:t,streamType:s}})}),this._log.warn(c)):(c=new D({code:a,message:$({key:B.SUBSCRIBE_FAILED,data:{message:n.message,userId:t,streamType:s}})}),this._log.error(c)),c}})}unsubscribe(...e){return f(this,null,function*(){let{userId:t}=e[0],r=this.remotePublishedUserMap.get(t);if(!r)return;let s=e.find(n=>n.mediaType===2)?"auxiliary":"main";this._log.info(`unsubscribe() => ${t} ${s}`);try{yield r.unsubscribe({remoteTracks:e,streamType:s})}catch(n){this._log.warn(`unsubscribe() => failed ${n}`)}e.forEach(n=>{n.unsubscribe(),n.mediaType===8&&n.setMediaType(4)}),S.emit(C.UNSUBSCRIBE_SUCCESS,{room:this,streamType:s,remotePublishedUser:r})})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAudioVolumeEvaluation(e=2e3,t){if(e<=0){this._enableAudioVolumeEvaluation=!1,oe.clearTask(this._audioVolumeIntervalId);return}e=Math.floor(Math.max(e,100)),S.emit(C.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&oe.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=oe.run("intervalInWorker",()=>{var s;so.isRunning?this.stopUpdateAudioLevelFromSenderStat():this.updateAudioLevelFromSenderStat(e,t);let r=[];(s=this.remotePublishedUserMap)==null||s.forEach(n=>{if(n.muteState.hasAudio){!so.isRunning&&n.muteState.audioAvailable&&n.remoteAudioTrack.isSubscribed?this.updateDownlinkAudioLevelFromReceiver(n):n.remoteAudioTrack.volume=0;let a=Math.floor(n.remoteAudioTrack.getAudioLevel()*100);r.push({userId:n.userId,volume:a,floatVolume:n.remoteAudioTrack.getInternalAudioLevel()})}}),this.emit("audio-volume",r)},{delay:e,backgroundTask:t})}updateAudioLevelFromSenderStat(e,t){return f(this,null,function*(){var n;if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack||this._updateAudioLevelTaskId!==-1)return;let r=(n=this.uplinkConnection.getPeerConnection())==null?void 0:n.getSenders()[0];if(!r)return;let s=Math.max(e,500);this._log.warn(`updateAudioLevelFromSenderStat ${s}`),this._updateAudioLevelTaskId=oe.run("intervalInWorker",()=>f(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack){this.stopUpdateAudioLevelFromSenderStat();return}let a=yield r.getStats();if(this._updateAudioLevelTaskId<0)return;let{localMainAudioTrack:c}=this.uplinkConnection;a.forEach(l=>{l.type==="media-source"&&l.audioLevel&&(c.volume=l.audioLevel)})}),{delay:s,backgroundTask:t})})}stopUpdateAudioLevelFromSenderStat(){var e;this._updateAudioLevelTaskId!==-1&&(this._log.warn("stopUpdateAudioLevelFromSenderStat"),oe.clearTask(this._updateAudioLevelTaskId),this._updateAudioLevelTaskId=-1,(e=this.uplinkConnection)!=null&&e.localMainAudioTrack&&(this.uplinkConnection.localMainAudioTrack.volume=0))}updateDownlinkAudioLevelFromReceiver(e){var s;let{audioReceiver:t}=e;if(!mu||!t)return;let r=(s=t.getSynchronizationSources()[0])==null?void 0:s.audioLevel;Q(r)?e.remoteAudioTrack.volume=Math.min(r*2,1):t.getStats().then(n=>{n.forEach(a=>{a.type==="inbound-rtp"&&Q(a.audioLevel)&&(e.remoteAudioTrack.volume=a.audioLevel)})})}getLocalAudioStats(){return f(this,null,function*(){var t;let e={};return e[this.userId]={bytesSent:0,packetsSent:0,audioLevel:0},(t=this.uplinkConnection)!=null&&t.localMainAudioTrack&&(e[this.userId]=this.uplinkConnection.localMainAudioTrack.stat),e})}getLocalVideoStats(){return f(this,null,function*(){var t,r;let e={};return e[this.userId]=((r=(t=this.uplinkConnection)==null?void 0:t.localMainVideoTrack)==null?void 0:r.stat)||{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0},e})}getTransportStats(){return f(this,null,function*(){let e={rtt:0,downlinksRTT:{}};if(this.uplinkConnection){let t=yield this._stats.getSenderStats(this.uplinkConnection);e.rtt=t.rtt}for(let[,t]of this.remotePublishedUserMap){let r=yield this._stats.getReceiverStats(t);e.downlinksRTT[r.userId]=r.rtt}return e})}getRemoteVideoStats(e){return f(this,null,function*(){let t={};for(let[r,s]of this.remotePublishedUserMap)e==="main"&&s.muteState.hasVideo&&(t[r]=s.remoteVideoTrack.stat),e==="auxiliary"&&s.muteState.hasAuxiliary&&(t[r]=s.remoteAuxiliaryTrack.stat);return t})}getRemoteAudioStats(){return f(this,null,function*(){let e={};for(let[t,r]of this.remotePublishedUserMap)r.muteState.hasAudio&&(e[t]=r.remoteAudioTrack.stat);return e})}setTurnServer(e,t){this._log.info(`set turn server: ${JSON.stringify(e)} ${t||""}`);let r=[];Array.isArray(e)?e.forEach(s=>r.push(vt.getTurnServer(s))):vt.isPlainObject(e)&&r.push(vt.getTurnServer(e)),this._turnServers=r,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:Z.START_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:W.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"}).catch(t=>{if(t.code!==I.API_CALL_ABORTED)throw t})}sendStopMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:Z.STOP_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:W.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"}).catch(t=>{if(t.code!==I.API_CALL_ABORTED)throw t})}sendStartPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?Z.START_PUBLISH_TENCENT_CDN:Z.START_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?W.START_PUBLISH_TENCENT_CDN_RES:W.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"}).catch(r=>{if(r.code!==I.API_CALL_ABORTED)throw r})}sendStopPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?Z.STOP_PUBLISH_TENCENT_CDN:Z.STOP_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?W.STOP_PUBLISH_TENCENT_CDN_RES:W.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"}).catch(r=>{if(r.code!==I.API_CALL_ABORTED)throw r})}sendStartPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Z.START_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:W.START_PUBLISH_CDN_STREAM_RES,commandDesc:"startPublishCDNStream"}).catch(t=>{if(t.code!==I.API_CALL_ABORTED)throw t})}sendUpdatePushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Z.UPDATE_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:W.UPDATE_PUBLISH_CDN_STREAM_RES,commandDesc:"updatePublishCDNStream"}).catch(t=>{if(t.code!==I.API_CALL_ABORTED)throw t})}sendStopPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Z.STOP_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:W.STOP_PUBLISH_CDN_STREAM_RES,commandDesc:"stopPublishCDNStream"}).catch(t=>{if(t.code!==I.API_CALL_ABORTED)throw t})}sendAbilityStatus(e){var t;(t=this.signalChannel)==null||t.sendWaitForResponse({command:Z.ABILITY_STATUS_REPORT,data:e,timeout:5e3,responseCommand:W.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch(r=>{})}getIceServers(e){var t,r;return this._turnServers.length>0?this._turnServers:(t=this.scheduleResult.iceServers)!=null&&t.length?this.scheduleResult.iceServers:e!=null&&e.length?e:(r=this._iceServersFromJoin)!=null&&r.length?this._iceServersFromJoin:[]}getIceTransportPolicy(){return this.forceRelay?"relay":this._iceTransportPolicy||this.scheduleResult.iceTransportPolicy||"all"}getLogger(){return this._log}enableAIVoice(){throw new Error("Method not implemented.")}getSignalChannelUrl(){let e={mainUrl:"",backupUrl:""},t=vt.getEnv();return t?(e.mainUrl=`wss://${t}.rtc.qq.com`,e.backupUrl=e.mainUrl):this.proxy_ws?(e.mainUrl=this.proxy_ws,e.backupUrl=e.mainUrl):this.proxy_unified?(e.mainUrl=`wss://${this.proxy_unified}`,e.backupUrl=e.mainUrl):Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(e.mainUrl=`wss://${this.scheduleResult.domains[0]}`,e.backupUrl=e.mainUrl,this.scheduleResult.domains[1]&&(e.backupUrl=`wss://${this.scheduleResult.domains[1]}`)),e}getSignalInfo(){var e;return((e=this.signalChannel)==null?void 0:e.getSignalInfo())||{clientIp:"",relayIp:""}}reset(e=!1){this.stopSyncUserListInterval(),this.stopHeartbeat(),this.closeConnections(),this.clearNetworkQuality(),this.closeUplink("you exitRoom"),this.signalChannel&&(e&&this.signalChannel.keepAlive&&this.signalChannel.isConnected?this.signalChannel.stopKeepAliveIn(3600):(this.signalChannel.close(),this.setSignalChannel(null))),this.localPublishFlag=0,this.heartbeatCount=0,this._stats.reset(),this.userManager.clear(),this.userManager.removeAllListeners(),this.singlePC&&(this.singlePC.close(),this.singlePC=null),this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}}checkSubscribeBigSmallVideo(e){return f(this,null,function*(){let{subscribeState:t,userId:r,muteState:{hasSmall:s,hasVideo:n}}=e;if(!s&&!n||!t.video&&!t.smallVideo)return;let a=this._changeBigSmallRecords.get(r);if(!a||a.isSubscribing||a.reSubscribeCount<=0)return;let{options:c,reSubscribeCount:l}=a;if(c.video&&t.video||c.smallVideo&&t.smallVideo&&s)return;let h={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:c.video,smallVideo:c.smallVideo};try{if(!s&&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 ${Po-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount=Po}catch(m){this._log.info(`change [${r}] to ${h.smallVideo?"small":"big"} video failed. count ${Po-a.reSubscribeCount}. reason: ${m}`),a.isSubscribing=!1,a.reSubscribeCount===0&&this._changeBigSmallRecords.delete(r)}})}changeType(e,t){let s={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:Po};this._changeBigSmallRecords.set(t.userId,s),this._log.info(`set [${t.userId}] video prefer type: ${e?"small":"big"}`),this.emit("subscribe-small-video-changed",{userId:t.userId,isSmall:e});let n=this.remotePublishedUserMap.get(t.userId);n&&this.checkSubscribeBigSmallVideo(n)}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(e){this._businessInfo=e.businessInfo;let t={};if(Y_(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!No(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new D({code:I.INVALID_PARAMETER,message:$({key:B.INVALID_PURE_AUDIO})});this._pureAudioPushMode=e.pureAudioPushMode,t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.pure_audio_push_mod=this._pureAudioPushMode}if(!No(e.userDefineRecordId)){let r=/^[A-Za-z0-9_-]{1,64}$/gi;if(e.userDefineRecordId.match(r)===null)throw new D({code:I.INVALID_PARAMETER,message:$({key:B.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!No(e.userDefinePushArgs))if(Y_(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256)t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_push_args=e.userDefinePushArgs;else throw new D({code:I.INVALID_PARAMETER,message:$({key:B.INVALID_USER_DEFINE_PUSH_ARGS})});xI(t)||(this._businessInfo=JSON.stringify(t))}sendCustomMessage(e){var t;(t=this._customMessageManager)==null||t.send(e)}enableInsertableStreams(){return f(this,null,function*(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&mi)return this.singlePC.enableInsertableStreams=!0,yield this.singlePC.waitForPeerConnectionConnected(),yield this.singlePC.startReconnection()})}sendSignalMessage(e){var t;return this.signalChannel?(t=this.signalChannel)==null?void 0:t.sendWaitForResponseWithRetry(e):Promise.reject(new D({code:I.INVALID_OPERATION,message:"not join"}))}get enableCodecPipeline(){return this.videoManager.encodePipeline.length>0||this.videoManager.decodePipeline.length>0||this.audioManager.encodePipeline.length>0||this.audioManager.decodePipeline.length>0}get scriptTransformWorker(){var e;return(e=this.singlePC)==null?void 0:e.scriptTransformWorker}switchRoom(e){return f(this,null,function*(){var _;if(!this.signalChannel||!this.singlePC)return;let{roomId:t,strRoomId:r,userSig:s,privateMapKey:n}=e,a=((_=this.scheduleResult.config)==null?void 0:_.autoSubscribeCount)||(e==null?void 0:e.autoSubscribeCount)||1,c=String(this.useStringRoomId?r:t),l=[];for(let g=0;g<a;g++)l.push({audioSsrc:xt(),bigVideoSsrc:xt(),bigVideoRtxSsrc:xt(),auxVideoSsrc:xt(),auxVideoRtxSsrc:xt()});let h={currRoomId:this.roomId,targetRoomId:c,useStringRoomId:this.useStringRoomId,ability:this.singlePC.clientAbility,userSig:s,privateMapKey:n!=null?n:this.privateMapKey,subscribe:l};this.singlePC.autoSubscribedUserMap.clear(),this.singlePC.autoSubscribedSsrcGroups.clear(),this.singlePC.autoSubscribedSsrcGroups.set(c,l);let m=this.roomId;this.roomId=this.useStringRoomId?r:String(t),this.switchRoomSubedReq=new Promise(g=>{this.resolveSwitchRoomSubedReq=g,Ge(5e3).then(g)}),S.emit(C.SWITCH_ROOM_START,{room:this}),yield this.singlePC.waitForPeerConnectionConnected();let u;try{this.userManager.clear(),u=yield this.signalChannel.sendWaitForResponse({command:Z.SWITCH_ROOM,responseCommand:W.SEND_SWITCH_ROOM_RES,data:h});let{code:g,message:E}=u.data;if(g===0)this.userSig=s,No(n)||(this.privateMapKey=n),S.emit(C.SWITCH_ROOM_SUCCESS,{room:this,currentRoomId:m,targetRoomId:c});else{this._log.error(`switch room failed. result: ${g} error: ${E}`);let A=new D({code:I.SWITCH_ROOM_FAILED,extraCode:g,message:E});throw S.emit(C.SWITCH_ROOM_FAILED,{room:this,error:A}),A}}catch(g){throw this.singlePC.autoSubscribedSsrcGroups.clear(),this.roomId=m,this.resolveSwitchRoomSubedReq(),g}})}isSwitchRoomSupported(){var t;let e="unable to use switchRoom API, fallback to exitRoom and enterRoom.";return((t=this.scheduleResult.config)==null?void 0:t.switchRoom)!==!0?(this._log.warn(`${e} Reason: this sdkAppId is not supported, please contact us [https://trtc.io/contact] to enable it.`),!1):this.scene!=="live"?(this._log.warn(`${e} Reason: the scene is not 'live'.`),!1):this.role!=="audience"?(this._log.warn(`${e} Reason: the role is not 'audience'.`),!1):this.singlePC?!0:(this._log.warn(`${e} Reason: is not using single peerConnection.`),!1)}requestRemoteFallbackToH264(){var e;(e=this.singlePC)==null||e.requestRemoteFallbackToH264()}startUpdateNTPTime(){if(!this.signalChannel)return;let e=[];for(let t=0;t<5;t++)e.push(this.updateNTPTime());return Promise.all(e).then(t=>{var c;let r=t[0].offset,s=t[0].offset;t.forEach(l=>{r=Math.min(l.offset,r),s=Math.max(l.offset,s)});let n=Math.floor(t.reduce((l,h)=>l+h.rtt,0)/t.length),a=Math.floor(t.reduce((l,h)=>l+h.offset,0)/t.length);(s-r>30||n>50)&&setTimeout(()=>this.startUpdateNTPTime(),5e3),ha(a),(c=this.scriptTransformWorker)==null||c.postMessage({type:"ntp-offset",data:a}),this._log.debug(`ntp updated offset: ${a}`),this.emit("ntp-time-updated")}).catch(t=>{this._log.warn(`ntp updated failed: ${t}`)})}updateNTPTime(){let e=Date.now();return this.signalChannel.sendWaitForResponse({command:Z.UPDATE_NETWORK_TIME,responseCommand:W.UPDATE_NETWORK_TIME_RESULT,addReceiveTime:!0,data:{clientSendTime:String(e)},enableLog:!1}).then(t=>{let r=Number(t.data.data.serverSendTime),s=Number(t.data.data.serverRecvTime),n=t.data.receiveTime||Date.now(),a=(s-e+(r-n))/2;return{rtt:n-e-(s-r),offset:a}})}};M([be(["left",j.INIT],"joined"),Mt({settings:{retries:1,timeout:0},onRetrying(e){this._log.warn(`join retry ${e}`)},onRetryFailed(e){this._log.error("join failed",e)},onError(e,t){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),Lt(!0),this.reset(),t()):this.signalChannel&&this.signalChannel.isConnected&&this.signalChannel.keepAlive?(this._log.warn("is using keepAlive ws, retry join"),this.signalChannel.close(),this.reset(),t()):(this.reset(),t())}}),n_()],Ei.prototype,"join",1),M([be("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),a_(),Bc("leave room"),Nn({fnName:"publish",validateArgs:!1}),Nn({fnName:"unsubscribe",validateArgs:!1})],Ei.prototype,"leave",1),M([gi(e=>e.mediaType),X_(),Mt({settings:{retries:Hi,timeout:e=>Kt(e)},onError(e,t,r,[s]){var n;(n=e.message)!=null&&n.includes("timeout")?(this._log.warn(`publish ${s.strMediaType} timeout`,e),t()):(this._log.error(`publish ${s.strMediaType} failed: ${e}`),r(e),S.emit(C.PUBLISH_FAILED,{room:this}))}})],Ei.prototype,"publish",1),M([Nn({fnName:"publish"}),gi(e=>e.mediaType),z_(),Ct(function(){var e,t;this.localTracks.size===0&&yr()&&((t=(e=this.singlePC)==null?void 0:e.getPeerConnection())==null||t.getSenders().forEach(r=>r.track&&r.replaceTrack(null)))})],Ei.prototype,"unpublish",1),M([xc(e=>{if(e.code!==I.API_CALL_ABORTED)throw e}),gi(e=>e.userId)],Ei.prototype,"replaceTrack",1),M([gi((...e)=>e[0].userId),Eo(),c_(),Mt({settings:{retries:Hi,timeout:e=>Kt(e)},onError(e,t,r,s){if(e.message.includes("timeout"))this._log.warn("subscribe timeout"),t();else{let n=(e==null?void 0:e.code)===I.API_CALL_ABORTED;this._log[n?"warn":"error"](`subscribe failed: ${e}`),r(e),S.emit(C.SUBSCRIBE_FAILED,{room:this,remoteTracks:s})}}})],Ei.prototype,"subscribe",1),M([Nn({fnName:"subscribe",callback(...e){this.singlePC||e.forEach(t=>{let r=this.remotePublishedUserMap.get(t.userId);r&&!r.isMainStreamSubscribed&&!r.isAuxStreamSubscribed&&r.close("you unsubscribed")})}}),gi((...e)=>e[0].userId)],Ei.prototype,"unsubscribe",1);ra.create=ra._create.bind(ra,Ei);Tu(30);var d5=ra;export{d5 as default};