trtc-sdk-v5 5.14.2-wasm.2 → 5.15.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/debug-dialog.js +1 -1
- package/index.d.ts +1 -0
- package/package.json +6 -4
- package/plugins/cdn-streaming/package.json +1 -1
- package/plugins/chorus/package.json +1 -1
- package/plugins/cross-room/package.json +1 -1
- package/plugins/custom-encryption/package.json +1 -1
- package/plugins/device-detector/package.json +1 -1
- package/plugins/small-stream-auto-switcher/package.json +1 -1
- package/plugins/video-decoder/package.json +1 -1
- package/plugins/video-effect/basic-beauty/package.json +1 -1
- package/plugins/video-effect/beauty/package.json +1 -1
- package/plugins/video-effect/video-mixer/package.json +1 -1
- package/plugins/video-effect/virtual-background/package.json +1 -1
- package/plugins/video-effect/watermark/package.json +1 -1
- package/plugins/voice-changer/package.json +1 -1
- package/trtc.esm.js +44 -103
- package/trtc.js +1 -17
- package/assets/av_processing.wasm +0 -0
- package/assets/worker.js +0 -17
package/trtc.esm.js
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
|
-
var eS=Object.create;var Da=Object.defineProperty,tS=Object.defineProperties,bg=Object.getOwnPropertyDescriptor,rS=Object.getOwnPropertyDescriptors,iS=Object.getOwnPropertyNames,xd=Object.getOwnPropertySymbols,Ag=Object.getPrototypeOf,Lh=Object.prototype.hasOwnProperty,vg=Object.prototype.propertyIsEnumerable,oS=Reflect.get;var ki=Math.pow,kh=(i,t,e)=>t in i?Da(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e,be=(i,t)=>{for(var e in t||(t={}))Lh.call(t,e)&&kh(i,e,t[e]);if(xd)for(var e of xd(t))vg.call(t,e)&&kh(i,e,t[e]);return i},qe=(i,t)=>tS(i,rS(t));var Oa=(i=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(i,{get:(t,e)=>(typeof require!="undefined"?require:t)[e]}):i)(function(i){if(typeof require!="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+i+'" is not supported')});var Rg=(i,t)=>{var e={};for(var r in i)Lh.call(i,r)&&t.indexOf(r)<0&&(e[r]=i[r]);if(i!=null&&xd)for(var r of xd(i))t.indexOf(r)<0&&vg.call(i,r)&&(e[r]=i[r]);return e};var vn=(i,t)=>()=>(t||i((t={exports:{}}).exports,t),t.exports),eo=(i,t)=>{for(var e in t)Da(i,e,{get:t[e],enumerable:!0})},sS=(i,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of iS(t))!Lh.call(i,o)&&o!==e&&Da(i,o,{get:()=>t[o],enumerable:!(r=bg(t,o))||r.enumerable});return i};var Li=(i,t,e)=>(e=i!=null?eS(Ag(i)):{},sS(t||!i||!i.__esModule?Da(e,"default",{value:i,enumerable:!0}):e,i));var Ie=(i,t,e,r)=>{for(var o=r>1?void 0:r?bg(t,e):t,s=i.length-1,n;s>=0;s--)(n=i[s])&&(o=(r?n(t,e,o):n(o))||o);return r&&o&&Da(t,e,o),o};var p=(i,t,e)=>kh(i,typeof t!="symbol"?t+"":t,e);var Er=(i,t,e)=>oS(Ag(i),e,t);var D=(i,t,e)=>new Promise((r,o)=>{var s=c=>{try{a(e.next(c))}catch(d){o(d)}},n=c=>{try{a(e.throw(c))}catch(d){o(d)}},a=c=>c.done?r(c.value):Promise.resolve(c.value).then(s,n);a((e=e.apply(i,t)).next())});var mo=vn((yC,Am)=>{"use strict";var yI=Object.prototype.hasOwnProperty,Lr="~";function ic(){}Object.create&&(ic.prototype=Object.create(null),new ic().__proto__||(Lr=!1));function SI(i,t,e){this.fn=i,this.context=t,this.once=e||!1}function p_(i,t,e,r,o){if(typeof e!="function")throw new TypeError("The listener must be a function");var s=new SI(e,r||i,o),n=Lr?Lr+t:t;return i._events[n]?i._events[n].fn?i._events[n]=[i._events[n],s]:i._events[n].push(s):(i._events[n]=s,i._eventsCount++),i}function bu(i,t){--i._eventsCount===0?i._events=new ic:delete i._events[t]}function Dr(){this._events=new ic,this._eventsCount=0}Dr.prototype.eventNames=function(){var t=[],e,r;if(this._eventsCount===0)return t;for(r in e=this._events)yI.call(e,r)&&t.push(Lr?r.slice(1):r);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(e)):t};Dr.prototype.listeners=function(t){var e=Lr?Lr+t:t,r=this._events[e];if(!r)return[];if(r.fn)return[r.fn];for(var o=0,s=r.length,n=new Array(s);o<s;o++)n[o]=r[o].fn;return n};Dr.prototype.listenerCount=function(t){var e=Lr?Lr+t:t,r=this._events[e];return r?r.fn?1:r.length:0};Dr.prototype.emit=function(t,e,r,o,s,n){var a=Lr?Lr+t:t;if(!this._events[a])return!1;var c=this._events[a],d=arguments.length,m,l;if(c.fn){switch(c.once&&this.removeListener(t,c.fn,void 0,!0),d){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,e),!0;case 3:return c.fn.call(c.context,e,r),!0;case 4:return c.fn.call(c.context,e,r,o),!0;case 5:return c.fn.call(c.context,e,r,o,s),!0;case 6:return c.fn.call(c.context,e,r,o,s,n),!0}for(l=1,m=new Array(d-1);l<d;l++)m[l-1]=arguments[l];c.fn.apply(c.context,m)}else{var f=c.length,g;for(l=0;l<f;l++)switch(c[l].once&&this.removeListener(t,c[l].fn,void 0,!0),d){case 1:c[l].fn.call(c[l].context);break;case 2:c[l].fn.call(c[l].context,e);break;case 3:c[l].fn.call(c[l].context,e,r);break;case 4:c[l].fn.call(c[l].context,e,r,o);break;default:if(!m)for(g=1,m=new Array(d-1);g<d;g++)m[g-1]=arguments[g];c[l].fn.apply(c[l].context,m)}}return!0};Dr.prototype.on=function(t,e,r){return p_(this,t,e,r,!1)};Dr.prototype.once=function(t,e,r){return p_(this,t,e,r,!0)};Dr.prototype.removeListener=function(t,e,r,o){var s=Lr?Lr+t:t;if(!this._events[s])return this;if(!e)return bu(this,s),this;var n=this._events[s];if(n.fn)n.fn===e&&(!o||n.once)&&(!r||n.context===r)&&bu(this,s);else{for(var a=0,c=[],d=n.length;a<d;a++)(n[a].fn!==e||o&&!n[a].once||r&&n[a].context!==r)&&c.push(n[a]);c.length?this._events[s]=c.length===1?c[0]:c:bu(this,s)}return this};Dr.prototype.removeAllListeners=function(t){var e;return t?(e=Lr?Lr+t:t,this._events[e]&&bu(this,e)):(this._events=new ic,this._eventsCount=0),this};Dr.prototype.off=Dr.prototype.removeListener;Dr.prototype.addListener=Dr.prototype.on;Dr.prefixed=Lr;Dr.EventEmitter=Dr;typeof Am!="undefined"&&(Am.exports=Dr)});var Ou=vn((iw,C_)=>{"use strict";var R_=C_.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(i){return i.encoding?"rtpmap:%d %s/%s/%s":i.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(i){return i.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(i){return i.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(i){return"extmap:%d"+(i.direction?"/%s":"%v")+(i["encrypt-uri"]?" %s":"%v")+" %s"+(i.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(i){return i.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(i){var t="candidate:%s %d %s %d %s %d typ %s";return t+=i.raddr!=null?" raddr %s rport %d":"%v%v",t+=i.tcptype!=null?" tcptype %s":"%v",i.generation!=null&&(t+=" generation %d"),t+=i["network-id"]!=null?" network-id %d":"%v",t+=i["network-cost"]!=null?" network-cost %d":"%v",t}},{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(i){var t="ssrc:%d";return i.attribute!=null&&(t+=" %s",i.value!=null&&(t+=":%s")),t}},{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(i){return i.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(i){return i.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(i){return"imageattr:%s %s %s"+(i.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(i){return"simulcast:%s %s"+(i.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(i){return"ts-refclk:%s"+(i.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(i){var t="mediaclk:";return t+=i.id!=null?"id=%s %s":"%v%s",t+=i.mediaClockValue!=null?"=%s":"",t+=i.rateNumerator!=null?" rate=%s":"",t+=i.rateDenominator!=null?"/%s":"",t}},{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(R_).forEach(function(i){var t=R_[i];t.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var D_=vn(_o=>{"use strict";var Zn=function(i){return String(Number(i))===i?Number(i):i},NI=function(i,t,e,r){if(r&&!e)t[r]=Zn(i[1]);else for(var o=0;o<e.length;o+=1)i[o+1]!=null&&(t[e[o]]=Zn(i[o+1]))},DI=function(i,t,e){var r=i.name&&i.names;i.push&&!t[i.push]?t[i.push]=[]:r&&!t[i.name]&&(t[i.name]={});var o=i.push?{}:r?t[i.name]:t;NI(e.match(i.reg),o,i.names,i.name),i.push&&t[i.push].push(o)},w_=Ou(),OI=RegExp.prototype.test.bind(/^([a-z])=(.*)/);_o.parse=function(i){var t={},e=[],r=t;return i.split(/(\r\n|\r|\n)/).filter(OI).forEach(function(o){var s=o[0],n=o.slice(2);s==="m"&&(e.push({rtp:[],fmtp:[]}),r=e[e.length-1]);for(var a=0;a<(w_[s]||[]).length;a+=1){var c=w_[s][a];if(c.reg.test(n))return DI(c,r,n)}}),t.media=e,t};var N_=function(i,t){var e=t.split(/=(.+)/,2);return e.length===2?i[e[0]]=Zn(e[1]):e.length===1&&t.length>1&&(i[e[0]]=void 0),i};_o.parseParams=function(i){return i.split(/;\s?/).reduce(N_,{})};_o.parseFmtpConfig=_o.parseParams;_o.parsePayloads=function(i){return i.toString().split(" ").map(Number)};_o.parseRemoteCandidates=function(i){for(var t=[],e=i.split(" ").map(Zn),r=0;r<e.length;r+=3)t.push({component:e[r],ip:e[r+1],port:e[r+2]});return t};_o.parseImageAttributes=function(i){return i.split(" ").map(function(t){return t.substring(1,t.length-1).split(",").reduce(N_,{})})};_o.parseSimulcastStreamList=function(i){return i.split(";").map(function(t){return t.split(",").map(function(e){var r,o=!1;return e[0]!=="~"?r=Zn(e):(r=Zn(e.substring(1,e.length)),o=!0),{scid:r,paused:o}})})}});var M_=vn((sw,O_)=>{"use strict";var Fm=Ou(),MI=/%[sdv%]/g,xI=function(i){var t=1,e=arguments,r=e.length;return i.replace(MI,function(o){if(t>=r)return o;var s=e[t];switch(t+=1,o){case"%%":return"%";case"%s":return String(s);case"%d":return Number(s);case"%v":return""}})},hc=function(i,t,e){var r=t.format instanceof Function?t.format(t.push?e:e[t.name]):t.format,o=[i+"="+r];if(t.names)for(var s=0;s<t.names.length;s+=1){var n=t.names[s];t.name?o.push(e[t.name][n]):o.push(e[t.names[s]])}else o.push(e[t.name]);return xI.apply(null,o)},kI=["v","o","s","i","u","e","p","c","b","t","r","z","a"],LI=["i","c","b","a"];O_.exports=function(i,t){t=t||{},i.version==null&&(i.version=0),i.name==null&&(i.name=" "),i.media.forEach(function(s){s.payloads==null&&(s.payloads="")});var e=t.outerOrder||kI,r=t.innerOrder||LI,o=[];return e.forEach(function(s){Fm[s].forEach(function(n){n.name in i&&i[n.name]!=null?o.push(hc(s,n,i)):n.push in i&&i[n.push]!=null&&i[n.push].forEach(function(a){o.push(hc(s,n,a))})})}),i.media.forEach(function(s){o.push(hc("m",Fm.m[0],s)),r.forEach(function(n){Fm[n].forEach(function(a){a.name in s&&s[a.name]!=null?o.push(hc(n,a,s)):a.push in s&&s[a.push]!=null&&s[a.push].forEach(function(c){o.push(hc(n,a,c))})})})}),o.join(`\r
|
|
1
|
+
var Y_=Object.create;var ks=Object.defineProperty,Z_=Object.defineProperties,mm=Object.getOwnPropertyDescriptor,K_=Object.getOwnPropertyDescriptors,eg=Object.getOwnPropertyNames,na=Object.getOwnPropertySymbols,pm=Object.getPrototypeOf,$d=Object.prototype.hasOwnProperty,fm=Object.prototype.propertyIsEnumerable,tg=Reflect.get;var hr=Math.pow,Hd=(o,i,e)=>i in o?ks(o,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[i]=e,M=(o,i)=>{for(var e in i||(i={}))$d.call(i,e)&&Hd(o,e,i[e]);if(na)for(var e of na(i))fm.call(i,e)&&Hd(o,e,i[e]);return o},L=(o,i)=>Z_(o,K_(i));var aa=(o,i)=>{var e={};for(var t in o)$d.call(o,t)&&i.indexOf(t)<0&&(e[t]=o[t]);if(o!=null&&na)for(var t of na(o))i.indexOf(t)<0&&fm.call(o,t)&&(e[t]=o[t]);return e};var Ui=(o,i)=>()=>(i||o((i={exports:{}}).exports,i),i.exports),Vi=(o,i)=>{for(var e in i)ks(o,e,{get:i[e],enumerable:!0})},ig=(o,i,e,t)=>{if(i&&typeof i=="object"||typeof i=="function")for(let r of eg(i))!$d.call(o,r)&&r!==e&&ks(o,r,{get:()=>i[r],enumerable:!(t=mm(i,r))||t.enumerable});return o};var Je=(o,i,e)=>(e=o!=null?Y_(pm(o)):{},ig(i||!o||!o.__esModule?ks(e,"default",{value:o,enumerable:!0}):e,o));var O=(o,i,e,t)=>{for(var r=t>1?void 0:t?mm(i,e):i,s=o.length-1,n;s>=0;s--)(n=o[s])&&(r=(t?n(i,e,r):n(r))||r);return t&&r&&ks(i,e,r),r};var d=(o,i,e)=>Hd(o,typeof i!="symbol"?i+"":i,e);var He=(o,i,e)=>tg(pm(o),e,i);var f=(o,i,e)=>new Promise((t,r)=>{var s=c=>{try{a(e.next(c))}catch(l){r(l)}},n=c=>{try{a(e.throw(c))}catch(l){r(l)}},a=c=>c.done?t(c.value):Promise.resolve(c.value).then(s,n);a((e=e.apply(o,i)).next())});var at=Ui((kI,Wd)=>{"use strict";var rg=Object.prototype.hasOwnProperty,ht="~";function Ps(){}Object.create&&(Ps.prototype=Object.create(null),new Ps().__proto__||(ht=!1));function og(o,i,e){this.fn=o,this.context=i,this.once=e||!1}function _m(o,i,e,t,r){if(typeof e!="function")throw new TypeError("The listener must be a function");var s=new og(e,t||o,r),n=ht?ht+i:i;return o._events[n]?o._events[n].fn?o._events[n]=[o._events[n],s]:o._events[n].push(s):(o._events[n]=s,o._eventsCount++),o}function ca(o,i){--o._eventsCount===0?o._events=new Ps:delete o._events[i]}function nt(){this._events=new Ps,this._eventsCount=0}nt.prototype.eventNames=function(){var i=[],e,t;if(this._eventsCount===0)return i;for(t in e=this._events)rg.call(e,t)&&i.push(ht?t.slice(1):t);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i};nt.prototype.listeners=function(i){var e=ht?ht+i:i,t=this._events[e];if(!t)return[];if(t.fn)return[t.fn];for(var r=0,s=t.length,n=new Array(s);r<s;r++)n[r]=t[r].fn;return n};nt.prototype.listenerCount=function(i){var e=ht?ht+i:i,t=this._events[e];return t?t.fn?1:t.length:0};nt.prototype.emit=function(i,e,t,r,s,n){var a=ht?ht+i:i;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,u,h;if(c.fn){switch(c.once&&this.removeListener(i,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,e),!0;case 3:return c.fn.call(c.context,e,t),!0;case 4:return c.fn.call(c.context,e,t,r),!0;case 5:return c.fn.call(c.context,e,t,r,s),!0;case 6:return c.fn.call(c.context,e,t,r,s,n),!0}for(h=1,u=new Array(l-1);h<l;h++)u[h-1]=arguments[h];c.fn.apply(c.context,u)}else{var m=c.length,_;for(h=0;h<m;h++)switch(c[h].once&&this.removeListener(i,c[h].fn,void 0,!0),l){case 1:c[h].fn.call(c[h].context);break;case 2:c[h].fn.call(c[h].context,e);break;case 3:c[h].fn.call(c[h].context,e,t);break;case 4:c[h].fn.call(c[h].context,e,t,r);break;default:if(!u)for(_=1,u=new Array(l-1);_<l;_++)u[_-1]=arguments[_];c[h].fn.apply(c[h].context,u)}}return!0};nt.prototype.on=function(i,e,t){return _m(this,i,e,t,!1)};nt.prototype.once=function(i,e,t){return _m(this,i,e,t,!0)};nt.prototype.removeListener=function(i,e,t,r){var s=ht?ht+i:i;if(!this._events[s])return this;if(!e)return ca(this,s),this;var n=this._events[s];if(n.fn)n.fn===e&&(!r||n.once)&&(!t||n.context===t)&&ca(this,s);else{for(var a=0,c=[],l=n.length;a<l;a++)(n[a].fn!==e||r&&!n[a].once||t&&n[a].context!==t)&&c.push(n[a]);c.length?this._events[s]=c.length===1?c[0]:c:ca(this,s)}return this};nt.prototype.removeAllListeners=function(i){var e;return i?(e=ht?ht+i:i,this._events[e]&&ca(this,e)):(this._events=new Ps,this._eventsCount=0),this};nt.prototype.off=nt.prototype.removeListener;nt.prototype.addListener=nt.prototype.on;nt.prefixed=ht;nt.EventEmitter=nt;typeof Wd!="undefined"&&(Wd.exports=nt)});var dc=Ui((oC,lp)=>{"use strict";var dp=lp.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(o){return o.encoding?"rtpmap:%d %s/%s/%s":o.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(o){return o.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(o){return o.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(o){return"extmap:%d"+(o.direction?"/%s":"%v")+(o["encrypt-uri"]?" %s":"%v")+" %s"+(o.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(o){return o.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(o){var i="candidate:%s %d %s %d %s %d typ %s";return i+=o.raddr!=null?" raddr %s rport %d":"%v%v",i+=o.tcptype!=null?" tcptype %s":"%v",o.generation!=null&&(i+=" generation %d"),i+=o["network-id"]!=null?" network-id %d":"%v",i+=o["network-cost"]!=null?" network-cost %d":"%v",i}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(o){var i="ssrc:%d";return o.attribute!=null&&(i+=" %s",o.value!=null&&(i+=":%s")),i}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(o){return o.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(o){return o.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(o){return"imageattr:%s %s %s"+(o.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(o){return"simulcast:%s %s"+(o.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(o){return"ts-refclk:%s"+(o.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(o){var i="mediaclk:";return i+=o.id!=null?"id=%s %s":"%v%s",i+=o.mediaClockValue!=null?"=%s":"",i+=o.rateNumerator!=null?" rate=%s":"",i+=o.rateDenominator!=null?"/%s":"",i}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(dp).forEach(function(o){var i=dp[o];i.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var mp=Ui(Yi=>{"use strict";var rs=function(o){return String(Number(o))===o?Number(o):o},hT=function(o,i,e,t){if(t&&!e)i[t]=rs(o[1]);else for(var r=0;r<e.length;r+=1)o[r+1]!=null&&(i[e[r]]=rs(o[r+1]))},mT=function(o,i,e){var t=o.name&&o.names;o.push&&!i[o.push]?i[o.push]=[]:t&&!i[o.name]&&(i[o.name]={});var r=o.push?{}:t?i[o.name]:i;hT(e.match(o.reg),r,o.names,o.name),o.push&&i[o.push].push(r)},up=dc(),pT=RegExp.prototype.test.bind(/^([a-z])=(.*)/);Yi.parse=function(o){var i={},e=[],t=i;return o.split(/(\r\n|\r|\n)/).filter(pT).forEach(function(r){var s=r[0],n=r.slice(2);s==="m"&&(e.push({rtp:[],fmtp:[]}),t=e[e.length-1]);for(var a=0;a<(up[s]||[]).length;a+=1){var c=up[s][a];if(c.reg.test(n))return mT(c,t,n)}}),i.media=e,i};var hp=function(o,i){var e=i.split(/=(.+)/,2);return e.length===2?o[e[0]]=rs(e[1]):e.length===1&&i.length>1&&(o[e[0]]=void 0),o};Yi.parseParams=function(o){return o.split(/;\s?/).reduce(hp,{})};Yi.parseFmtpConfig=Yi.parseParams;Yi.parsePayloads=function(o){return o.toString().split(" ").map(Number)};Yi.parseRemoteCandidates=function(o){for(var i=[],e=o.split(" ").map(rs),t=0;t<e.length;t+=3)i.push({component:e[t],ip:e[t+1],port:e[t+2]});return i};Yi.parseImageAttributes=function(o){return o.split(" ").map(function(i){return i.substring(1,i.length-1).split(",").reduce(hp,{})})};Yi.parseSimulcastStreamList=function(o){return o.split(";").map(function(i){return i.split(",").map(function(e){var t,r=!1;return e[0]!=="~"?t=rs(e):(t=rs(e.substring(1,e.length)),r=!0),{scid:t,paused:r}})})}});var fp=Ui((nC,pp)=>{"use strict";var Zl=dc(),fT=/%[sdv%]/g,_T=function(o){var i=1,e=arguments,t=e.length;return o.replace(fT,function(r){if(i>=t)return r;var s=e[i];switch(i+=1,r){case"%%":return"%";case"%s":return String(s);case"%d":return Number(s);case"%v":return""}})},mn=function(o,i,e){var t=i.format instanceof Function?i.format(i.push?e:e[i.name]):i.format,r=[o+"="+t];if(i.names)for(var s=0;s<i.names.length;s+=1){var n=i.names[s];i.name?r.push(e[i.name][n]):r.push(e[i.names[s]])}else r.push(e[i.name]);return _T.apply(null,r)},gT=["v","o","s","i","u","e","p","c","b","t","r","z","a"],TT=["i","c","b","a"];pp.exports=function(o,i){i=i||{},o.version==null&&(o.version=0),o.name==null&&(o.name=" "),o.media.forEach(function(s){s.payloads==null&&(s.payloads="")});var e=i.outerOrder||gT,t=i.innerOrder||TT,r=[];return e.forEach(function(s){Zl[s].forEach(function(n){n.name in o&&o[n.name]!=null?r.push(mn(s,n,o)):n.push in o&&o[n.push]!=null&&o[n.push].forEach(function(a){r.push(mn(s,n,a))})})}),o.media.forEach(function(s){r.push(mn("m",Zl.m[0],s)),t.forEach(function(n){Zl[n].forEach(function(a){a.name in s&&s[a.name]!=null?r.push(mn(n,a,s)):a.push in s&&s[a.push]!=null&&s[a.push].forEach(function(c){r.push(mn(n,a,c))})})})}),r.join(`\r
|
|
2
2
|
`)+`\r
|
|
3
|
-
`}});var x_=vn(Fi=>{"use strict";var Ws=D_(),PI=M_(),UI=Ou();Fi.grammar=UI;Fi.write=PI;Fi.parse=Ws.parse;Fi.parseParams=Ws.parseParams;Fi.parseFmtpConfig=Ws.parseFmtpConfig;Fi.parsePayloads=Ws.parsePayloads;Fi.parseRemoteCandidates=Ws.parseRemoteCandidates;Fi.parseImageAttributes=Ws.parseImageAttributes;Fi.parseSimulcastStreamList=Ws.parseSimulcastStreamList});var hy=vn((ly,Zf)=>{"use strict";(function(i){typeof ly=="object"&&typeof Zf!="undefined"?Zf.exports=i():typeof define=="function"&&define.amd?define([],i):(typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:this).JSZip=i()})(function(){return function i(t,e,r){function o(a,c){if(!e[a]){if(!t[a]){var d=typeof Oa=="function"&&Oa;if(!c&&d)return d(a,!0);if(s)return s(a,!0);var m=new Error("Cannot find module '"+a+"'");throw m.code="MODULE_NOT_FOUND",m}var l=e[a]={exports:{}};t[a][0].call(l.exports,function(f){var g=t[a][1][f];return o(g||f)},l,l.exports,i,t,e,r)}return e[a].exports}for(var s=typeof Oa=="function"&&Oa,n=0;n<r.length;n++)o(r[n]);return o}({1:[function(i,t,e){"use strict";var r=i("./utils"),o=i("./support"),s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";e.encode=function(n){for(var a,c,d,m,l,f,g,T=[],E=0,y=n.length,v=y,M=r.getTypeOf(n)!=="string";E<n.length;)v=y-E,d=M?(a=n[E++],c=E<y?n[E++]:0,E<y?n[E++]:0):(a=n.charCodeAt(E++),c=E<y?n.charCodeAt(E++):0,E<y?n.charCodeAt(E++):0),m=a>>2,l=(3&a)<<4|c>>4,f=1<v?(15&c)<<2|d>>6:64,g=2<v?63&d:64,T.push(s.charAt(m)+s.charAt(l)+s.charAt(f)+s.charAt(g));return T.join("")},e.decode=function(n){var a,c,d,m,l,f,g=0,T=0,E="data:";if(n.substr(0,E.length)===E)throw new Error("Invalid base64 input, it looks like a data url.");var y,v=3*(n=n.replace(/[^A-Za-z0-9+/=]/g,"")).length/4;if(n.charAt(n.length-1)===s.charAt(64)&&v--,n.charAt(n.length-2)===s.charAt(64)&&v--,v%1!=0)throw new Error("Invalid base64 input, bad content length.");for(y=o.uint8array?new Uint8Array(0|v):new Array(0|v);g<n.length;)a=s.indexOf(n.charAt(g++))<<2|(m=s.indexOf(n.charAt(g++)))>>4,c=(15&m)<<4|(l=s.indexOf(n.charAt(g++)))>>2,d=(3&l)<<6|(f=s.indexOf(n.charAt(g++))),y[T++]=a,l!==64&&(y[T++]=c),f!==64&&(y[T++]=d);return y}},{"./support":30,"./utils":32}],2:[function(i,t,e){"use strict";var r=i("./external"),o=i("./stream/DataWorker"),s=i("./stream/Crc32Probe"),n=i("./stream/DataLengthProbe");function a(c,d,m,l,f){this.compressedSize=c,this.uncompressedSize=d,this.crc32=m,this.compression=l,this.compressedContent=f}a.prototype={getContentWorker:function(){var c=new o(r.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new n("data_length")),d=this;return c.on("end",function(){if(this.streamInfo.data_length!==d.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),c},getCompressedWorker:function(){return new o(r.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},a.createWorkerFrom=function(c,d,m){return c.pipe(new s).pipe(new n("uncompressedSize")).pipe(d.compressWorker(m)).pipe(new n("compressedSize")).withStreamInfo("compression",d)},t.exports=a},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(i,t,e){"use strict";var r=i("./stream/GenericWorker");e.STORE={magic:"\0\0",compressWorker:function(){return new r("STORE compression")},uncompressWorker:function(){return new r("STORE decompression")}},e.DEFLATE=i("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(i,t,e){"use strict";var r=i("./utils"),o=function(){for(var s,n=[],a=0;a<256;a++){s=a;for(var c=0;c<8;c++)s=1&s?3988292384^s>>>1:s>>>1;n[a]=s}return n}();t.exports=function(s,n){return s!==void 0&&s.length?r.getTypeOf(s)!=="string"?function(a,c,d,m){var l=o,f=m+d;a^=-1;for(var g=m;g<f;g++)a=a>>>8^l[255&(a^c[g])];return-1^a}(0|n,s,s.length,0):function(a,c,d,m){var l=o,f=m+d;a^=-1;for(var g=m;g<f;g++)a=a>>>8^l[255&(a^c.charCodeAt(g))];return-1^a}(0|n,s,s.length,0):0}},{"./utils":32}],5:[function(i,t,e){"use strict";e.base64=!1,e.binary=!1,e.dir=!1,e.createFolders=!0,e.date=null,e.compression=null,e.compressionOptions=null,e.comment=null,e.unixPermissions=null,e.dosPermissions=null},{}],6:[function(i,t,e){"use strict";var r=null;r=typeof Promise!="undefined"?Promise:i("lie"),t.exports={Promise:r}},{lie:37}],7:[function(i,t,e){"use strict";var r=typeof Uint8Array!="undefined"&&typeof Uint16Array!="undefined"&&typeof Uint32Array!="undefined",o=i("pako"),s=i("./utils"),n=i("./stream/GenericWorker"),a=r?"uint8array":"array";function c(d,m){n.call(this,"FlateWorker/"+d),this._pako=null,this._pakoAction=d,this._pakoOptions=m,this.meta={}}e.magic="\b\0",s.inherits(c,n),c.prototype.processChunk=function(d){this.meta=d.meta,this._pako===null&&this._createPako(),this._pako.push(s.transformTo(a,d.data),!1)},c.prototype.flush=function(){n.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},c.prototype.cleanUp=function(){n.prototype.cleanUp.call(this),this._pako=null},c.prototype._createPako=function(){this._pako=new o[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var d=this;this._pako.onData=function(m){d.push({data:m,meta:d.meta})}},e.compressWorker=function(d){return new c("Deflate",d)},e.uncompressWorker=function(){return new c("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(i,t,e){"use strict";function r(l,f){var g,T="";for(g=0;g<f;g++)T+=String.fromCharCode(255&l),l>>>=8;return T}function o(l,f,g,T,E,y){var v,M,w=l.file,H=l.compression,B=y!==a.utf8encode,P=s.transformTo("string",y(w.name)),$=s.transformTo("string",a.utf8encode(w.name)),de=w.comment,Ae=s.transformTo("string",y(de)),L=s.transformTo("string",a.utf8encode(de)),te=$.length!==w.name.length,A=L.length!==de.length,le="",He="",ge="",ze=w.dir,me=w.date,re={crc32:0,compressedSize:0,uncompressedSize:0};f&&!g||(re.crc32=l.crc32,re.compressedSize=l.compressedSize,re.uncompressedSize=l.uncompressedSize);var Q=0;f&&(Q|=8),B||!te&&!A||(Q|=2048);var q=0,Be=0;ze&&(q|=16),E==="UNIX"?(Be=798,q|=function(ne,Ze){var yt=ne;return ne||(yt=Ze?16893:33204),(65535&yt)<<16}(w.unixPermissions,ze)):(Be=20,q|=function(ne){return 63&(ne||0)}(w.dosPermissions)),v=me.getUTCHours(),v<<=6,v|=me.getUTCMinutes(),v<<=5,v|=me.getUTCSeconds()/2,M=me.getUTCFullYear()-1980,M<<=4,M|=me.getUTCMonth()+1,M<<=5,M|=me.getUTCDate(),te&&(He=r(1,1)+r(c(P),4)+$,le+="up"+r(He.length,2)+He),A&&(ge=r(1,1)+r(c(Ae),4)+L,le+="uc"+r(ge.length,2)+ge);var De="";return De+=`
|
|
4
|
-
\0`,De+=r(Q,2),De+=H.magic,De+=r(v,2),De+=r(M,2),De+=r(re.crc32,4),De+=r(re.compressedSize,4),De+=r(re.uncompressedSize,4),De+=r(P.length,2),De+=r(le.length,2),{fileRecord:d.LOCAL_FILE_HEADER+De+P+le,dirRecord:d.CENTRAL_FILE_HEADER+r(Be,2)+De+r(Ae.length,2)+"\0\0\0\0"+r(q,4)+r(T,4)+P+le+Ae}}var s=i("../utils"),n=i("../stream/GenericWorker"),a=i("../utf8"),c=i("../crc32"),d=i("../signature");function m(l,f,g,T){n.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=f,this.zipPlatform=g,this.encodeFileName=T,this.streamFiles=l,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}s.inherits(m,n),m.prototype.push=function(l){var f=l.meta.percent||0,g=this.entriesCount,T=this._sources.length;this.accumulate?this.contentBuffer.push(l):(this.bytesWritten+=l.data.length,n.prototype.push.call(this,{data:l.data,meta:{currentFile:this.currentFile,percent:g?(f+100*(g-T-1))/g:100}}))},m.prototype.openedSource=function(l){this.currentSourceOffset=this.bytesWritten,this.currentFile=l.file.name;var f=this.streamFiles&&!l.file.dir;if(f){var g=o(l,f,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:g.fileRecord,meta:{percent:0}})}else this.accumulate=!0},m.prototype.closedSource=function(l){this.accumulate=!1;var f=this.streamFiles&&!l.file.dir,g=o(l,f,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(g.dirRecord),f)this.push({data:function(T){return d.DATA_DESCRIPTOR+r(T.crc32,4)+r(T.compressedSize,4)+r(T.uncompressedSize,4)}(l),meta:{percent:100}});else for(this.push({data:g.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},m.prototype.flush=function(){for(var l=this.bytesWritten,f=0;f<this.dirRecords.length;f++)this.push({data:this.dirRecords[f],meta:{percent:100}});var g=this.bytesWritten-l,T=function(E,y,v,M,w){var H=s.transformTo("string",w(M));return d.CENTRAL_DIRECTORY_END+"\0\0\0\0"+r(E,2)+r(E,2)+r(y,4)+r(v,4)+r(H.length,2)+H}(this.dirRecords.length,g,l,this.zipComment,this.encodeFileName);this.push({data:T,meta:{percent:100}})},m.prototype.prepareNextSource=function(){this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused?this.previous.pause():this.previous.resume()},m.prototype.registerPrevious=function(l){this._sources.push(l);var f=this;return l.on("data",function(g){f.processChunk(g)}),l.on("end",function(){f.closedSource(f.previous.streamInfo),f._sources.length?f.prepareNextSource():f.end()}),l.on("error",function(g){f.error(g)}),this},m.prototype.resume=function(){return!!n.prototype.resume.call(this)&&(!this.previous&&this._sources.length?(this.prepareNextSource(),!0):this.previous||this._sources.length||this.generatedError?void 0:(this.end(),!0))},m.prototype.error=function(l){var f=this._sources;if(!n.prototype.error.call(this,l))return!1;for(var g=0;g<f.length;g++)try{f[g].error(l)}catch(T){}return!0},m.prototype.lock=function(){n.prototype.lock.call(this);for(var l=this._sources,f=0;f<l.length;f++)l[f].lock()},t.exports=m},{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(i,t,e){"use strict";var r=i("../compressions"),o=i("./ZipFileWorker");e.generateWorker=function(s,n,a){var c=new o(n.streamFiles,a,n.platform,n.encodeFileName),d=0;try{s.forEach(function(m,l){d++;var f=function(y,v){var M=y||v,w=r[M];if(!w)throw new Error(M+" is not a valid compression method !");return w}(l.options.compression,n.compression),g=l.options.compressionOptions||n.compressionOptions||{},T=l.dir,E=l.date;l._compressWorker(f,g).withStreamInfo("file",{name:m,dir:T,date:E,comment:l.comment||"",unixPermissions:l.unixPermissions,dosPermissions:l.dosPermissions}).pipe(c)}),c.entriesCount=d}catch(m){c.error(m)}return c}},{"../compressions":3,"./ZipFileWorker":8}],10:[function(i,t,e){"use strict";function r(){if(!(this instanceof r))return new r;if(arguments.length)throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");this.files=Object.create(null),this.comment=null,this.root="",this.clone=function(){var o=new r;for(var s in this)typeof this[s]!="function"&&(o[s]=this[s]);return o}}(r.prototype=i("./object")).loadAsync=i("./load"),r.support=i("./support"),r.defaults=i("./defaults"),r.version="3.10.1",r.loadAsync=function(o,s){return new r().loadAsync(o,s)},r.external=i("./external"),t.exports=r},{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(i,t,e){"use strict";var r=i("./utils"),o=i("./external"),s=i("./utf8"),n=i("./zipEntries"),a=i("./stream/Crc32Probe"),c=i("./nodejsUtils");function d(m){return new o.Promise(function(l,f){var g=m.decompressed.getContentWorker().pipe(new a);g.on("error",function(T){f(T)}).on("end",function(){g.streamInfo.crc32!==m.decompressed.crc32?f(new Error("Corrupted zip : CRC32 mismatch")):l()}).resume()})}t.exports=function(m,l){var f=this;return l=r.extend(l||{},{base64:!1,checkCRC32:!1,optimizedBinaryString:!1,createFolders:!1,decodeFileName:s.utf8decode}),c.isNode&&c.isStream(m)?o.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")):r.prepareContent("the loaded zip file",m,!0,l.optimizedBinaryString,l.base64).then(function(g){var T=new n(l);return T.load(g),T}).then(function(g){var T=[o.Promise.resolve(g)],E=g.files;if(l.checkCRC32)for(var y=0;y<E.length;y++)T.push(d(E[y]));return o.Promise.all(T)}).then(function(g){for(var T=g.shift(),E=T.files,y=0;y<E.length;y++){var v=E[y],M=v.fileNameStr,w=r.resolve(v.fileNameStr);f.file(w,v.decompressed,{binary:!0,optimizedBinaryString:!0,date:v.date,dir:v.dir,comment:v.fileCommentStr.length?v.fileCommentStr:null,unixPermissions:v.unixPermissions,dosPermissions:v.dosPermissions,createFolders:l.createFolders}),v.dir||(f.file(w).unsafeOriginalName=M)}return T.zipComment.length&&(f.comment=T.zipComment),f})}},{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(i,t,e){"use strict";var r=i("../utils"),o=i("../stream/GenericWorker");function s(n,a){o.call(this,"Nodejs stream input adapter for "+n),this._upstreamEnded=!1,this._bindStream(a)}r.inherits(s,o),s.prototype._bindStream=function(n){var a=this;(this._stream=n).pause(),n.on("data",function(c){a.push({data:c,meta:{percent:0}})}).on("error",function(c){a.isPaused?this.generatedError=c:a.error(c)}).on("end",function(){a.isPaused?a._upstreamEnded=!0:a.end()})},s.prototype.pause=function(){return!!o.prototype.pause.call(this)&&(this._stream.pause(),!0)},s.prototype.resume=function(){return!!o.prototype.resume.call(this)&&(this._upstreamEnded?this.end():this._stream.resume(),!0)},t.exports=s},{"../stream/GenericWorker":28,"../utils":32}],13:[function(i,t,e){"use strict";var r=i("readable-stream").Readable;function o(s,n,a){r.call(this,n),this._helper=s;var c=this;s.on("data",function(d,m){c.push(d)||c._helper.pause(),a&&a(m)}).on("error",function(d){c.emit("error",d)}).on("end",function(){c.push(null)})}i("../utils").inherits(o,r),o.prototype._read=function(){this._helper.resume()},t.exports=o},{"../utils":32,"readable-stream":16}],14:[function(i,t,e){"use strict";t.exports={isNode:typeof Buffer!="undefined",newBufferFrom:function(r,o){if(Buffer.from&&Buffer.from!==Uint8Array.from)return Buffer.from(r,o);if(typeof r=="number")throw new Error('The "data" argument must not be a number');return new Buffer(r,o)},allocBuffer:function(r){if(Buffer.alloc)return Buffer.alloc(r);var o=new Buffer(r);return o.fill(0),o},isBuffer:function(r){return Buffer.isBuffer(r)},isStream:function(r){return r&&typeof r.on=="function"&&typeof r.pause=="function"&&typeof r.resume=="function"}}},{}],15:[function(i,t,e){"use strict";function r(w,H,B){var P,$=s.getTypeOf(H),de=s.extend(B||{},c);de.date=de.date||new Date,de.compression!==null&&(de.compression=de.compression.toUpperCase()),typeof de.unixPermissions=="string"&&(de.unixPermissions=parseInt(de.unixPermissions,8)),de.unixPermissions&&16384&de.unixPermissions&&(de.dir=!0),de.dosPermissions&&16&de.dosPermissions&&(de.dir=!0),de.dir&&(w=E(w)),de.createFolders&&(P=T(w))&&y.call(this,P,!0);var Ae=$==="string"&&de.binary===!1&&de.base64===!1;B&&B.binary!==void 0||(de.binary=!Ae),(H instanceof d&&H.uncompressedSize===0||de.dir||!H||H.length===0)&&(de.base64=!1,de.binary=!0,H="",de.compression="STORE",$="string");var L=null;L=H instanceof d||H instanceof n?H:f.isNode&&f.isStream(H)?new g(w,H):s.prepareContent(w,H,de.binary,de.optimizedBinaryString,de.base64);var te=new m(w,L,de);this.files[w]=te}var o=i("./utf8"),s=i("./utils"),n=i("./stream/GenericWorker"),a=i("./stream/StreamHelper"),c=i("./defaults"),d=i("./compressedObject"),m=i("./zipObject"),l=i("./generate"),f=i("./nodejsUtils"),g=i("./nodejs/NodejsStreamInputAdapter"),T=function(w){w.slice(-1)==="/"&&(w=w.substring(0,w.length-1));var H=w.lastIndexOf("/");return 0<H?w.substring(0,H):""},E=function(w){return w.slice(-1)!=="/"&&(w+="/"),w},y=function(w,H){return H=H!==void 0?H:c.createFolders,w=E(w),this.files[w]||r.call(this,w,null,{dir:!0,createFolders:H}),this.files[w]};function v(w){return Object.prototype.toString.call(w)==="[object RegExp]"}var M={load:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},forEach:function(w){var H,B,P;for(H in this.files)P=this.files[H],(B=H.slice(this.root.length,H.length))&&H.slice(0,this.root.length)===this.root&&w(B,P)},filter:function(w){var H=[];return this.forEach(function(B,P){w(B,P)&&H.push(P)}),H},file:function(w,H,B){if(arguments.length!==1)return w=this.root+w,r.call(this,w,H,B),this;if(v(w)){var P=w;return this.filter(function(de,Ae){return!Ae.dir&&P.test(de)})}var $=this.files[this.root+w];return $&&!$.dir?$:null},folder:function(w){if(!w)return this;if(v(w))return this.filter(function($,de){return de.dir&&w.test($)});var H=this.root+w,B=y.call(this,H),P=this.clone();return P.root=B.name,P},remove:function(w){w=this.root+w;var H=this.files[w];if(H||(w.slice(-1)!=="/"&&(w+="/"),H=this.files[w]),H&&!H.dir)delete this.files[w];else for(var B=this.filter(function($,de){return de.name.slice(0,w.length)===w}),P=0;P<B.length;P++)delete this.files[B[P].name];return this},generate:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},generateInternalStream:function(w){var H,B={};try{if((B=s.extend(w||{},{streamFiles:!1,compression:"STORE",compressionOptions:null,type:"",platform:"DOS",comment:null,mimeType:"application/zip",encodeFileName:o.utf8encode})).type=B.type.toLowerCase(),B.compression=B.compression.toUpperCase(),B.type==="binarystring"&&(B.type="string"),!B.type)throw new Error("No output type specified.");s.checkSupport(B.type),B.platform!=="darwin"&&B.platform!=="freebsd"&&B.platform!=="linux"&&B.platform!=="sunos"||(B.platform="UNIX"),B.platform==="win32"&&(B.platform="DOS");var P=B.comment||this.comment||"";H=l.generateWorker(this,B,P)}catch($){(H=new n("error")).error($)}return new a(H,B.type||"string",B.mimeType)},generateAsync:function(w,H){return this.generateInternalStream(w).accumulate(H)},generateNodeStream:function(w,H){return(w=w||{}).type||(w.type="nodebuffer"),this.generateInternalStream(w).toNodejsStream(H)}};t.exports=M},{"./compressedObject":2,"./defaults":5,"./generate":9,"./nodejs/NodejsStreamInputAdapter":12,"./nodejsUtils":14,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31,"./utils":32,"./zipObject":35}],16:[function(i,t,e){"use strict";t.exports=i("stream")},{stream:void 0}],17:[function(i,t,e){"use strict";var r=i("./DataReader");function o(s){r.call(this,s);for(var n=0;n<this.data.length;n++)s[n]=255&s[n]}i("../utils").inherits(o,r),o.prototype.byteAt=function(s){return this.data[this.zero+s]},o.prototype.lastIndexOfSignature=function(s){for(var n=s.charCodeAt(0),a=s.charCodeAt(1),c=s.charCodeAt(2),d=s.charCodeAt(3),m=this.length-4;0<=m;--m)if(this.data[m]===n&&this.data[m+1]===a&&this.data[m+2]===c&&this.data[m+3]===d)return m-this.zero;return-1},o.prototype.readAndCheckSignature=function(s){var n=s.charCodeAt(0),a=s.charCodeAt(1),c=s.charCodeAt(2),d=s.charCodeAt(3),m=this.readData(4);return n===m[0]&&a===m[1]&&c===m[2]&&d===m[3]},o.prototype.readData=function(s){if(this.checkOffset(s),s===0)return[];var n=this.data.slice(this.zero+this.index,this.zero+this.index+s);return this.index+=s,n},t.exports=o},{"../utils":32,"./DataReader":18}],18:[function(i,t,e){"use strict";var r=i("../utils");function o(s){this.data=s,this.length=s.length,this.index=0,this.zero=0}o.prototype={checkOffset:function(s){this.checkIndex(this.index+s)},checkIndex:function(s){if(this.length<this.zero+s||s<0)throw new Error("End of data reached (data length = "+this.length+", asked index = "+s+"). Corrupted zip ?")},setIndex:function(s){this.checkIndex(s),this.index=s},skip:function(s){this.setIndex(this.index+s)},byteAt:function(){},readInt:function(s){var n,a=0;for(this.checkOffset(s),n=this.index+s-1;n>=this.index;n--)a=(a<<8)+this.byteAt(n);return this.index+=s,a},readString:function(s){return r.transformTo("string",this.readData(s))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var s=this.readInt(4);return new Date(Date.UTC(1980+(s>>25&127),(s>>21&15)-1,s>>16&31,s>>11&31,s>>5&63,(31&s)<<1))}},t.exports=o},{"../utils":32}],19:[function(i,t,e){"use strict";var r=i("./Uint8ArrayReader");function o(s){r.call(this,s)}i("../utils").inherits(o,r),o.prototype.readData=function(s){this.checkOffset(s);var n=this.data.slice(this.zero+this.index,this.zero+this.index+s);return this.index+=s,n},t.exports=o},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(i,t,e){"use strict";var r=i("./DataReader");function o(s){r.call(this,s)}i("../utils").inherits(o,r),o.prototype.byteAt=function(s){return this.data.charCodeAt(this.zero+s)},o.prototype.lastIndexOfSignature=function(s){return this.data.lastIndexOf(s)-this.zero},o.prototype.readAndCheckSignature=function(s){return s===this.readData(4)},o.prototype.readData=function(s){this.checkOffset(s);var n=this.data.slice(this.zero+this.index,this.zero+this.index+s);return this.index+=s,n},t.exports=o},{"../utils":32,"./DataReader":18}],21:[function(i,t,e){"use strict";var r=i("./ArrayReader");function o(s){r.call(this,s)}i("../utils").inherits(o,r),o.prototype.readData=function(s){if(this.checkOffset(s),s===0)return new Uint8Array(0);var n=this.data.subarray(this.zero+this.index,this.zero+this.index+s);return this.index+=s,n},t.exports=o},{"../utils":32,"./ArrayReader":17}],22:[function(i,t,e){"use strict";var r=i("../utils"),o=i("../support"),s=i("./ArrayReader"),n=i("./StringReader"),a=i("./NodeBufferReader"),c=i("./Uint8ArrayReader");t.exports=function(d){var m=r.getTypeOf(d);return r.checkSupport(m),m!=="string"||o.uint8array?m==="nodebuffer"?new a(d):o.uint8array?new c(r.transformTo("uint8array",d)):new s(r.transformTo("array",d)):new n(d)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(i,t,e){"use strict";e.LOCAL_FILE_HEADER="PK",e.CENTRAL_FILE_HEADER="PK",e.CENTRAL_DIRECTORY_END="PK",e.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07",e.ZIP64_CENTRAL_DIRECTORY_END="PK",e.DATA_DESCRIPTOR="PK\x07\b"},{}],24:[function(i,t,e){"use strict";var r=i("./GenericWorker"),o=i("../utils");function s(n){r.call(this,"ConvertWorker to "+n),this.destType=n}o.inherits(s,r),s.prototype.processChunk=function(n){this.push({data:o.transformTo(this.destType,n.data),meta:n.meta})},t.exports=s},{"../utils":32,"./GenericWorker":28}],25:[function(i,t,e){"use strict";var r=i("./GenericWorker"),o=i("../crc32");function s(){r.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}i("../utils").inherits(s,r),s.prototype.processChunk=function(n){this.streamInfo.crc32=o(n.data,this.streamInfo.crc32||0),this.push(n)},t.exports=s},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(i,t,e){"use strict";var r=i("../utils"),o=i("./GenericWorker");function s(n){o.call(this,"DataLengthProbe for "+n),this.propName=n,this.withStreamInfo(n,0)}r.inherits(s,o),s.prototype.processChunk=function(n){if(n){var a=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=a+n.data.length}o.prototype.processChunk.call(this,n)},t.exports=s},{"../utils":32,"./GenericWorker":28}],27:[function(i,t,e){"use strict";var r=i("../utils"),o=i("./GenericWorker");function s(n){o.call(this,"DataWorker");var a=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,n.then(function(c){a.dataIsReady=!0,a.data=c,a.max=c&&c.length||0,a.type=r.getTypeOf(c),a.isPaused||a._tickAndRepeat()},function(c){a.error(c)})}r.inherits(s,o),s.prototype.cleanUp=function(){o.prototype.cleanUp.call(this),this.data=null},s.prototype.resume=function(){return!!o.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,r.delay(this._tickAndRepeat,[],this)),!0)},s.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(r.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},s.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var n=null,a=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":n=this.data.substring(this.index,a);break;case"uint8array":n=this.data.subarray(this.index,a);break;case"array":case"nodebuffer":n=this.data.slice(this.index,a)}return this.index=a,this.push({data:n,meta:{percent:this.max?this.index/this.max*100:0}})},t.exports=s},{"../utils":32,"./GenericWorker":28}],28:[function(i,t,e){"use strict";function r(o){this.name=o||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}r.prototype={push:function(o){this.emit("data",o)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(o){this.emit("error",o)}return!0},error:function(o){return!this.isFinished&&(this.isPaused?this.generatedError=o:(this.isFinished=!0,this.emit("error",o),this.previous&&this.previous.error(o),this.cleanUp()),!0)},on:function(o,s){return this._listeners[o].push(s),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(o,s){if(this._listeners[o])for(var n=0;n<this._listeners[o].length;n++)this._listeners[o][n].call(this,s)},pipe:function(o){return o.registerPrevious(this)},registerPrevious:function(o){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.streamInfo=o.streamInfo,this.mergeStreamInfo(),this.previous=o;var s=this;return o.on("data",function(n){s.processChunk(n)}),o.on("end",function(){s.end()}),o.on("error",function(n){s.error(n)}),this},pause:function(){return!this.isPaused&&!this.isFinished&&(this.isPaused=!0,this.previous&&this.previous.pause(),!0)},resume:function(){if(!this.isPaused||this.isFinished)return!1;var o=this.isPaused=!1;return this.generatedError&&(this.error(this.generatedError),o=!0),this.previous&&this.previous.resume(),!o},flush:function(){},processChunk:function(o){this.push(o)},withStreamInfo:function(o,s){return this.extraStreamInfo[o]=s,this.mergeStreamInfo(),this},mergeStreamInfo:function(){for(var o in this.extraStreamInfo)Object.prototype.hasOwnProperty.call(this.extraStreamInfo,o)&&(this.streamInfo[o]=this.extraStreamInfo[o])},lock:function(){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.isLocked=!0,this.previous&&this.previous.lock()},toString:function(){var o="Worker "+this.name;return this.previous?this.previous+" -> "+o:o}},t.exports=r},{}],29:[function(i,t,e){"use strict";var r=i("../utils"),o=i("./ConvertWorker"),s=i("./GenericWorker"),n=i("../base64"),a=i("../support"),c=i("../external"),d=null;if(a.nodestream)try{d=i("../nodejs/NodejsStreamOutputAdapter")}catch(f){}function m(f,g){return new c.Promise(function(T,E){var y=[],v=f._internalType,M=f._outputType,w=f._mimeType;f.on("data",function(H,B){y.push(H),g&&g(B)}).on("error",function(H){y=[],E(H)}).on("end",function(){try{var H=function(B,P,$){switch(B){case"blob":return r.newBlob(r.transformTo("arraybuffer",P),$);case"base64":return n.encode(P);default:return r.transformTo(B,P)}}(M,function(B,P){var $,de=0,Ae=null,L=0;for($=0;$<P.length;$++)L+=P[$].length;switch(B){case"string":return P.join("");case"array":return Array.prototype.concat.apply([],P);case"uint8array":for(Ae=new Uint8Array(L),$=0;$<P.length;$++)Ae.set(P[$],de),de+=P[$].length;return Ae;case"nodebuffer":return Buffer.concat(P);default:throw new Error("concat : unsupported type '"+B+"'")}}(v,y),w);T(H)}catch(B){E(B)}y=[]}).resume()})}function l(f,g,T){var E=g;switch(g){case"blob":case"arraybuffer":E="uint8array";break;case"base64":E="string"}try{this._internalType=E,this._outputType=g,this._mimeType=T,r.checkSupport(E),this._worker=f.pipe(new o(E)),f.lock()}catch(y){this._worker=new s("error"),this._worker.error(y)}}l.prototype={accumulate:function(f){return m(this,f)},on:function(f,g){var T=this;return f==="data"?this._worker.on(f,function(E){g.call(T,E.data,E.meta)}):this._worker.on(f,function(){r.delay(g,arguments,T)}),this},resume:function(){return r.delay(this._worker.resume,[],this._worker),this},pause:function(){return this._worker.pause(),this},toNodejsStream:function(f){if(r.checkSupport("nodestream"),this._outputType!=="nodebuffer")throw new Error(this._outputType+" is not supported by this method");return new d(this,{objectMode:this._outputType!=="nodebuffer"},f)}},t.exports=l},{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(i,t,e){"use strict";if(e.base64=!0,e.array=!0,e.string=!0,e.arraybuffer=typeof ArrayBuffer!="undefined"&&typeof Uint8Array!="undefined",e.nodebuffer=typeof Buffer!="undefined",e.uint8array=typeof Uint8Array!="undefined",typeof ArrayBuffer=="undefined")e.blob=!1;else{var r=new ArrayBuffer(0);try{e.blob=new Blob([r],{type:"application/zip"}).size===0}catch(s){try{var o=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);o.append(r),e.blob=o.getBlob("application/zip").size===0}catch(n){e.blob=!1}}}try{e.nodestream=!!i("readable-stream").Readable}catch(s){e.nodestream=!1}},{"readable-stream":16}],31:[function(i,t,e){"use strict";for(var r=i("./utils"),o=i("./support"),s=i("./nodejsUtils"),n=i("./stream/GenericWorker"),a=new Array(256),c=0;c<256;c++)a[c]=252<=c?6:248<=c?5:240<=c?4:224<=c?3:192<=c?2:1;a[254]=a[254]=1;function d(){n.call(this,"utf-8 decode"),this.leftOver=null}function m(){n.call(this,"utf-8 encode")}e.utf8encode=function(l){return o.nodebuffer?s.newBufferFrom(l,"utf-8"):function(f){var g,T,E,y,v,M=f.length,w=0;for(y=0;y<M;y++)(64512&(T=f.charCodeAt(y)))==55296&&y+1<M&&(64512&(E=f.charCodeAt(y+1)))==56320&&(T=65536+(T-55296<<10)+(E-56320),y++),w+=T<128?1:T<2048?2:T<65536?3:4;for(g=o.uint8array?new Uint8Array(w):new Array(w),y=v=0;v<w;y++)(64512&(T=f.charCodeAt(y)))==55296&&y+1<M&&(64512&(E=f.charCodeAt(y+1)))==56320&&(T=65536+(T-55296<<10)+(E-56320),y++),T<128?g[v++]=T:(T<2048?g[v++]=192|T>>>6:(T<65536?g[v++]=224|T>>>12:(g[v++]=240|T>>>18,g[v++]=128|T>>>12&63),g[v++]=128|T>>>6&63),g[v++]=128|63&T);return g}(l)},e.utf8decode=function(l){return o.nodebuffer?r.transformTo("nodebuffer",l).toString("utf-8"):function(f){var g,T,E,y,v=f.length,M=new Array(2*v);for(g=T=0;g<v;)if((E=f[g++])<128)M[T++]=E;else if(4<(y=a[E]))M[T++]=65533,g+=y-1;else{for(E&=y===2?31:y===3?15:7;1<y&&g<v;)E=E<<6|63&f[g++],y--;1<y?M[T++]=65533:E<65536?M[T++]=E:(E-=65536,M[T++]=55296|E>>10&1023,M[T++]=56320|1023&E)}return M.length!==T&&(M.subarray?M=M.subarray(0,T):M.length=T),r.applyFromCharCode(M)}(l=r.transformTo(o.uint8array?"uint8array":"array",l))},r.inherits(d,n),d.prototype.processChunk=function(l){var f=r.transformTo(o.uint8array?"uint8array":"array",l.data);if(this.leftOver&&this.leftOver.length){if(o.uint8array){var g=f;(f=new Uint8Array(g.length+this.leftOver.length)).set(this.leftOver,0),f.set(g,this.leftOver.length)}else f=this.leftOver.concat(f);this.leftOver=null}var T=function(y,v){var M;for((v=v||y.length)>y.length&&(v=y.length),M=v-1;0<=M&&(192&y[M])==128;)M--;return M<0||M===0?v:M+a[y[M]]>v?M:v}(f),E=f;T!==f.length&&(o.uint8array?(E=f.subarray(0,T),this.leftOver=f.subarray(T,f.length)):(E=f.slice(0,T),this.leftOver=f.slice(T,f.length))),this.push({data:e.utf8decode(E),meta:l.meta})},d.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:e.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},e.Utf8DecodeWorker=d,r.inherits(m,n),m.prototype.processChunk=function(l){this.push({data:e.utf8encode(l.data),meta:l.meta})},e.Utf8EncodeWorker=m},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(i,t,e){"use strict";var r=i("./support"),o=i("./base64"),s=i("./nodejsUtils"),n=i("./external");function a(g){return g}function c(g,T){for(var E=0;E<g.length;++E)T[E]=255&g.charCodeAt(E);return T}i("setimmediate"),e.newBlob=function(g,T){e.checkSupport("blob");try{return new Blob([g],{type:T})}catch(y){try{var E=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);return E.append(g),E.getBlob(T)}catch(v){throw new Error("Bug : can't construct the Blob.")}}};var d={stringifyByChunk:function(g,T,E){var y=[],v=0,M=g.length;if(M<=E)return String.fromCharCode.apply(null,g);for(;v<M;)T==="array"||T==="nodebuffer"?y.push(String.fromCharCode.apply(null,g.slice(v,Math.min(v+E,M)))):y.push(String.fromCharCode.apply(null,g.subarray(v,Math.min(v+E,M)))),v+=E;return y.join("")},stringifyByChar:function(g){for(var T="",E=0;E<g.length;E++)T+=String.fromCharCode(g[E]);return T},applyCanBeUsed:{uint8array:function(){try{return r.uint8array&&String.fromCharCode.apply(null,new Uint8Array(1)).length===1}catch(g){return!1}}(),nodebuffer:function(){try{return r.nodebuffer&&String.fromCharCode.apply(null,s.allocBuffer(1)).length===1}catch(g){return!1}}()}};function m(g){var T=65536,E=e.getTypeOf(g),y=!0;if(E==="uint8array"?y=d.applyCanBeUsed.uint8array:E==="nodebuffer"&&(y=d.applyCanBeUsed.nodebuffer),y)for(;1<T;)try{return d.stringifyByChunk(g,E,T)}catch(v){T=Math.floor(T/2)}return d.stringifyByChar(g)}function l(g,T){for(var E=0;E<g.length;E++)T[E]=g[E];return T}e.applyFromCharCode=m;var f={};f.string={string:a,array:function(g){return c(g,new Array(g.length))},arraybuffer:function(g){return f.string.uint8array(g).buffer},uint8array:function(g){return c(g,new Uint8Array(g.length))},nodebuffer:function(g){return c(g,s.allocBuffer(g.length))}},f.array={string:m,array:a,arraybuffer:function(g){return new Uint8Array(g).buffer},uint8array:function(g){return new Uint8Array(g)},nodebuffer:function(g){return s.newBufferFrom(g)}},f.arraybuffer={string:function(g){return m(new Uint8Array(g))},array:function(g){return l(new Uint8Array(g),new Array(g.byteLength))},arraybuffer:a,uint8array:function(g){return new Uint8Array(g)},nodebuffer:function(g){return s.newBufferFrom(new Uint8Array(g))}},f.uint8array={string:m,array:function(g){return l(g,new Array(g.length))},arraybuffer:function(g){return g.buffer},uint8array:a,nodebuffer:function(g){return s.newBufferFrom(g)}},f.nodebuffer={string:m,array:function(g){return l(g,new Array(g.length))},arraybuffer:function(g){return f.nodebuffer.uint8array(g).buffer},uint8array:function(g){return l(g,new Uint8Array(g.length))},nodebuffer:a},e.transformTo=function(g,T){if(T=T||"",!g)return T;e.checkSupport(g);var E=e.getTypeOf(T);return f[E][g](T)},e.resolve=function(g){for(var T=g.split("/"),E=[],y=0;y<T.length;y++){var v=T[y];v==="."||v===""&&y!==0&&y!==T.length-1||(v===".."?E.pop():E.push(v))}return E.join("/")},e.getTypeOf=function(g){return typeof g=="string"?"string":Object.prototype.toString.call(g)==="[object Array]"?"array":r.nodebuffer&&s.isBuffer(g)?"nodebuffer":r.uint8array&&g instanceof Uint8Array?"uint8array":r.arraybuffer&&g instanceof ArrayBuffer?"arraybuffer":void 0},e.checkSupport=function(g){if(!r[g.toLowerCase()])throw new Error(g+" is not supported by this platform")},e.MAX_VALUE_16BITS=65535,e.MAX_VALUE_32BITS=-1,e.pretty=function(g){var T,E,y="";for(E=0;E<(g||"").length;E++)y+="\\x"+((T=g.charCodeAt(E))<16?"0":"")+T.toString(16).toUpperCase();return y},e.delay=function(g,T,E){setImmediate(function(){g.apply(E||null,T||[])})},e.inherits=function(g,T){function E(){}E.prototype=T.prototype,g.prototype=new E},e.extend=function(){var g,T,E={};for(g=0;g<arguments.length;g++)for(T in arguments[g])Object.prototype.hasOwnProperty.call(arguments[g],T)&&E[T]===void 0&&(E[T]=arguments[g][T]);return E},e.prepareContent=function(g,T,E,y,v){return n.Promise.resolve(T).then(function(M){return r.blob&&(M instanceof Blob||["[object File]","[object Blob]"].indexOf(Object.prototype.toString.call(M))!==-1)&&typeof FileReader!="undefined"?new n.Promise(function(w,H){var B=new FileReader;B.onload=function(P){w(P.target.result)},B.onerror=function(P){H(P.target.error)},B.readAsArrayBuffer(M)}):M}).then(function(M){var w=e.getTypeOf(M);return w?(w==="arraybuffer"?M=e.transformTo("uint8array",M):w==="string"&&(v?M=o.decode(M):E&&y!==!0&&(M=function(H){return c(H,r.uint8array?new Uint8Array(H.length):new Array(H.length))}(M))),M):n.Promise.reject(new Error("Can't read the data of '"+g+"'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?"))})}},{"./base64":1,"./external":6,"./nodejsUtils":14,"./support":30,setimmediate:54}],33:[function(i,t,e){"use strict";var r=i("./reader/readerFor"),o=i("./utils"),s=i("./signature"),n=i("./zipEntry"),a=i("./support");function c(d){this.files=[],this.loadOptions=d}c.prototype={checkSignature:function(d){if(!this.reader.readAndCheckSignature(d)){this.reader.index-=4;var m=this.reader.readString(4);throw new Error("Corrupted zip or bug: unexpected signature ("+o.pretty(m)+", expected "+o.pretty(d)+")")}},isSignature:function(d,m){var l=this.reader.index;this.reader.setIndex(d);var f=this.reader.readString(4)===m;return this.reader.setIndex(l),f},readBlockEndOfCentral:function(){this.diskNumber=this.reader.readInt(2),this.diskWithCentralDirStart=this.reader.readInt(2),this.centralDirRecordsOnThisDisk=this.reader.readInt(2),this.centralDirRecords=this.reader.readInt(2),this.centralDirSize=this.reader.readInt(4),this.centralDirOffset=this.reader.readInt(4),this.zipCommentLength=this.reader.readInt(2);var d=this.reader.readData(this.zipCommentLength),m=a.uint8array?"uint8array":"array",l=o.transformTo(m,d);this.zipComment=this.loadOptions.decodeFileName(l)},readBlockZip64EndOfCentral:function(){this.zip64EndOfCentralSize=this.reader.readInt(8),this.reader.skip(4),this.diskNumber=this.reader.readInt(4),this.diskWithCentralDirStart=this.reader.readInt(4),this.centralDirRecordsOnThisDisk=this.reader.readInt(8),this.centralDirRecords=this.reader.readInt(8),this.centralDirSize=this.reader.readInt(8),this.centralDirOffset=this.reader.readInt(8),this.zip64ExtensibleData={};for(var d,m,l,f=this.zip64EndOfCentralSize-44;0<f;)d=this.reader.readInt(2),m=this.reader.readInt(4),l=this.reader.readData(m),this.zip64ExtensibleData[d]={id:d,length:m,value:l}},readBlockZip64EndOfCentralLocator:function(){if(this.diskWithZip64CentralDirStart=this.reader.readInt(4),this.relativeOffsetEndOfZip64CentralDir=this.reader.readInt(8),this.disksCount=this.reader.readInt(4),1<this.disksCount)throw new Error("Multi-volumes zip are not supported")},readLocalFiles:function(){var d,m;for(d=0;d<this.files.length;d++)m=this.files[d],this.reader.setIndex(m.localHeaderOffset),this.checkSignature(s.LOCAL_FILE_HEADER),m.readLocalPart(this.reader),m.handleUTF8(),m.processAttributes()},readCentralDir:function(){var d;for(this.reader.setIndex(this.centralDirOffset);this.reader.readAndCheckSignature(s.CENTRAL_FILE_HEADER);)(d=new n({zip64:this.zip64},this.loadOptions)).readCentralPart(this.reader),this.files.push(d);if(this.centralDirRecords!==this.files.length&&this.centralDirRecords!==0&&this.files.length===0)throw new Error("Corrupted zip or bug: expected "+this.centralDirRecords+" records in central dir, got "+this.files.length)},readEndOfCentral:function(){var d=this.reader.lastIndexOfSignature(s.CENTRAL_DIRECTORY_END);if(d<0)throw this.isSignature(0,s.LOCAL_FILE_HEADER)?new Error("Corrupted zip: can't find end of central directory"):new Error("Can't find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html");this.reader.setIndex(d);var m=d;if(this.checkSignature(s.CENTRAL_DIRECTORY_END),this.readBlockEndOfCentral(),this.diskNumber===o.MAX_VALUE_16BITS||this.diskWithCentralDirStart===o.MAX_VALUE_16BITS||this.centralDirRecordsOnThisDisk===o.MAX_VALUE_16BITS||this.centralDirRecords===o.MAX_VALUE_16BITS||this.centralDirSize===o.MAX_VALUE_32BITS||this.centralDirOffset===o.MAX_VALUE_32BITS){if(this.zip64=!0,(d=this.reader.lastIndexOfSignature(s.ZIP64_CENTRAL_DIRECTORY_LOCATOR))<0)throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");if(this.reader.setIndex(d),this.checkSignature(s.ZIP64_CENTRAL_DIRECTORY_LOCATOR),this.readBlockZip64EndOfCentralLocator(),!this.isSignature(this.relativeOffsetEndOfZip64CentralDir,s.ZIP64_CENTRAL_DIRECTORY_END)&&(this.relativeOffsetEndOfZip64CentralDir=this.reader.lastIndexOfSignature(s.ZIP64_CENTRAL_DIRECTORY_END),this.relativeOffsetEndOfZip64CentralDir<0))throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir),this.checkSignature(s.ZIP64_CENTRAL_DIRECTORY_END),this.readBlockZip64EndOfCentral()}var l=this.centralDirOffset+this.centralDirSize;this.zip64&&(l+=20,l+=12+this.zip64EndOfCentralSize);var f=m-l;if(0<f)this.isSignature(m,s.CENTRAL_FILE_HEADER)||(this.reader.zero=f);else if(f<0)throw new Error("Corrupted zip: missing "+Math.abs(f)+" bytes.")},prepareReader:function(d){this.reader=r(d)},load:function(d){this.prepareReader(d),this.readEndOfCentral(),this.readCentralDir(),this.readLocalFiles()}},t.exports=c},{"./reader/readerFor":22,"./signature":23,"./support":30,"./utils":32,"./zipEntry":34}],34:[function(i,t,e){"use strict";var r=i("./reader/readerFor"),o=i("./utils"),s=i("./compressedObject"),n=i("./crc32"),a=i("./utf8"),c=i("./compressions"),d=i("./support");function m(l,f){this.options=l,this.loadOptions=f}m.prototype={isEncrypted:function(){return(1&this.bitFlag)==1},useUTF8:function(){return(2048&this.bitFlag)==2048},readLocalPart:function(l){var f,g;if(l.skip(22),this.fileNameLength=l.readInt(2),g=l.readInt(2),this.fileName=l.readData(this.fileNameLength),l.skip(g),this.compressedSize===-1||this.uncompressedSize===-1)throw new Error("Bug or corrupted zip : didn't get enough information from the central directory (compressedSize === -1 || uncompressedSize === -1)");if((f=function(T){for(var E in c)if(Object.prototype.hasOwnProperty.call(c,E)&&c[E].magic===T)return c[E];return null}(this.compressionMethod))===null)throw new Error("Corrupted zip : compression "+o.pretty(this.compressionMethod)+" unknown (inner file : "+o.transformTo("string",this.fileName)+")");this.decompressed=new s(this.compressedSize,this.uncompressedSize,this.crc32,f,l.readData(this.compressedSize))},readCentralPart:function(l){this.versionMadeBy=l.readInt(2),l.skip(2),this.bitFlag=l.readInt(2),this.compressionMethod=l.readString(2),this.date=l.readDate(),this.crc32=l.readInt(4),this.compressedSize=l.readInt(4),this.uncompressedSize=l.readInt(4);var f=l.readInt(2);if(this.extraFieldsLength=l.readInt(2),this.fileCommentLength=l.readInt(2),this.diskNumberStart=l.readInt(2),this.internalFileAttributes=l.readInt(2),this.externalFileAttributes=l.readInt(4),this.localHeaderOffset=l.readInt(4),this.isEncrypted())throw new Error("Encrypted zip are not supported");l.skip(f),this.readExtraFields(l),this.parseZIP64ExtraField(l),this.fileComment=l.readData(this.fileCommentLength)},processAttributes:function(){this.unixPermissions=null,this.dosPermissions=null;var l=this.versionMadeBy>>8;this.dir=!!(16&this.externalFileAttributes),l==0&&(this.dosPermissions=63&this.externalFileAttributes),l==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var l=r(this.extraFields[1].value);this.uncompressedSize===o.MAX_VALUE_32BITS&&(this.uncompressedSize=l.readInt(8)),this.compressedSize===o.MAX_VALUE_32BITS&&(this.compressedSize=l.readInt(8)),this.localHeaderOffset===o.MAX_VALUE_32BITS&&(this.localHeaderOffset=l.readInt(8)),this.diskNumberStart===o.MAX_VALUE_32BITS&&(this.diskNumberStart=l.readInt(4))}},readExtraFields:function(l){var f,g,T,E=l.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});l.index+4<E;)f=l.readInt(2),g=l.readInt(2),T=l.readData(g),this.extraFields[f]={id:f,length:g,value:T};l.setIndex(E)},handleUTF8:function(){var l=d.uint8array?"uint8array":"array";if(this.useUTF8())this.fileNameStr=a.utf8decode(this.fileName),this.fileCommentStr=a.utf8decode(this.fileComment);else{var f=this.findExtraFieldUnicodePath();if(f!==null)this.fileNameStr=f;else{var g=o.transformTo(l,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(g)}var T=this.findExtraFieldUnicodeComment();if(T!==null)this.fileCommentStr=T;else{var E=o.transformTo(l,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(E)}}},findExtraFieldUnicodePath:function(){var l=this.extraFields[28789];if(l){var f=r(l.value);return f.readInt(1)!==1||n(this.fileName)!==f.readInt(4)?null:a.utf8decode(f.readData(l.length-5))}return null},findExtraFieldUnicodeComment:function(){var l=this.extraFields[25461];if(l){var f=r(l.value);return f.readInt(1)!==1||n(this.fileComment)!==f.readInt(4)?null:a.utf8decode(f.readData(l.length-5))}return null}},t.exports=m},{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(i,t,e){"use strict";function r(f,g,T){this.name=f,this.dir=T.dir,this.date=T.date,this.comment=T.comment,this.unixPermissions=T.unixPermissions,this.dosPermissions=T.dosPermissions,this._data=g,this._dataBinary=T.binary,this.options={compression:T.compression,compressionOptions:T.compressionOptions}}var o=i("./stream/StreamHelper"),s=i("./stream/DataWorker"),n=i("./utf8"),a=i("./compressedObject"),c=i("./stream/GenericWorker");r.prototype={internalStream:function(f){var g=null,T="string";try{if(!f)throw new Error("No output type specified.");var E=(T=f.toLowerCase())==="string"||T==="text";T!=="binarystring"&&T!=="text"||(T="string"),g=this._decompressWorker();var y=!this._dataBinary;y&&!E&&(g=g.pipe(new n.Utf8EncodeWorker)),!y&&E&&(g=g.pipe(new n.Utf8DecodeWorker))}catch(v){(g=new c("error")).error(v)}return new o(g,T,"")},async:function(f,g){return this.internalStream(f).accumulate(g)},nodeStream:function(f,g){return this.internalStream(f||"nodebuffer").toNodejsStream(g)},_compressWorker:function(f,g){if(this._data instanceof a&&this._data.compression.magic===f.magic)return this._data.getCompressedWorker();var T=this._decompressWorker();return this._dataBinary||(T=T.pipe(new n.Utf8EncodeWorker)),a.createWorkerFrom(T,f,g)},_decompressWorker:function(){return this._data instanceof a?this._data.getContentWorker():this._data instanceof c?this._data:new s(this._data)}};for(var d=["asText","asBinary","asNodeBuffer","asUint8Array","asArrayBuffer"],m=function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},l=0;l<d.length;l++)r.prototype[d[l]]=m;t.exports=r},{"./compressedObject":2,"./stream/DataWorker":27,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31}],36:[function(i,t,e){(function(r){"use strict";var o,s,n=r.MutationObserver||r.WebKitMutationObserver;if(n){var a=0,c=new n(f),d=r.document.createTextNode("");c.observe(d,{characterData:!0}),o=function(){d.data=a=++a%2}}else if(r.setImmediate||r.MessageChannel===void 0)o="document"in r&&"onreadystatechange"in r.document.createElement("script")?function(){var g=r.document.createElement("script");g.onreadystatechange=function(){f(),g.onreadystatechange=null,g.parentNode.removeChild(g),g=null},r.document.documentElement.appendChild(g)}:function(){setTimeout(f,0)};else{var m=new r.MessageChannel;m.port1.onmessage=f,o=function(){m.port2.postMessage(0)}}var l=[];function f(){var g,T;s=!0;for(var E=l.length;E;){for(T=l,l=[],g=-1;++g<E;)T[g]();E=l.length}s=!1}t.exports=function(g){l.push(g)!==1||s||o()}}).call(this,typeof global!="undefined"?global:typeof self!="undefined"?self:typeof window!="undefined"?window:{})},{}],37:[function(i,t,e){"use strict";var r=i("immediate");function o(){}var s={},n=["REJECTED"],a=["FULFILLED"],c=["PENDING"];function d(E){if(typeof E!="function")throw new TypeError("resolver must be a function");this.state=c,this.queue=[],this.outcome=void 0,E!==o&&g(this,E)}function m(E,y,v){this.promise=E,typeof y=="function"&&(this.onFulfilled=y,this.callFulfilled=this.otherCallFulfilled),typeof v=="function"&&(this.onRejected=v,this.callRejected=this.otherCallRejected)}function l(E,y,v){r(function(){var M;try{M=y(v)}catch(w){return s.reject(E,w)}M===E?s.reject(E,new TypeError("Cannot resolve promise with itself")):s.resolve(E,M)})}function f(E){var y=E&&E.then;if(E&&(typeof E=="object"||typeof E=="function")&&typeof y=="function")return function(){y.apply(E,arguments)}}function g(E,y){var v=!1;function M(B){v||(v=!0,s.reject(E,B))}function w(B){v||(v=!0,s.resolve(E,B))}var H=T(function(){y(w,M)});H.status==="error"&&M(H.value)}function T(E,y){var v={};try{v.value=E(y),v.status="success"}catch(M){v.status="error",v.value=M}return v}(t.exports=d).prototype.finally=function(E){if(typeof E!="function")return this;var y=this.constructor;return this.then(function(v){return y.resolve(E()).then(function(){return v})},function(v){return y.resolve(E()).then(function(){throw v})})},d.prototype.catch=function(E){return this.then(null,E)},d.prototype.then=function(E,y){if(typeof E!="function"&&this.state===a||typeof y!="function"&&this.state===n)return this;var v=new this.constructor(o);return this.state!==c?l(v,this.state===a?E:y,this.outcome):this.queue.push(new m(v,E,y)),v},m.prototype.callFulfilled=function(E){s.resolve(this.promise,E)},m.prototype.otherCallFulfilled=function(E){l(this.promise,this.onFulfilled,E)},m.prototype.callRejected=function(E){s.reject(this.promise,E)},m.prototype.otherCallRejected=function(E){l(this.promise,this.onRejected,E)},s.resolve=function(E,y){var v=T(f,y);if(v.status==="error")return s.reject(E,v.value);var M=v.value;if(M)g(E,M);else{E.state=a,E.outcome=y;for(var w=-1,H=E.queue.length;++w<H;)E.queue[w].callFulfilled(y)}return E},s.reject=function(E,y){E.state=n,E.outcome=y;for(var v=-1,M=E.queue.length;++v<M;)E.queue[v].callRejected(y);return E},d.resolve=function(E){return E instanceof this?E:s.resolve(new this(o),E)},d.reject=function(E){var y=new this(o);return s.reject(y,E)},d.all=function(E){var y=this;if(Object.prototype.toString.call(E)!=="[object Array]")return this.reject(new TypeError("must be an array"));var v=E.length,M=!1;if(!v)return this.resolve([]);for(var w=new Array(v),H=0,B=-1,P=new this(o);++B<v;)$(E[B],B);return P;function $(de,Ae){y.resolve(de).then(function(L){w[Ae]=L,++H!==v||M||(M=!0,s.resolve(P,w))},function(L){M||(M=!0,s.reject(P,L))})}},d.race=function(E){var y=this;if(Object.prototype.toString.call(E)!=="[object Array]")return this.reject(new TypeError("must be an array"));var v=E.length,M=!1;if(!v)return this.resolve([]);for(var w=-1,H=new this(o);++w<v;)B=E[w],y.resolve(B).then(function(P){M||(M=!0,s.resolve(H,P))},function(P){M||(M=!0,s.reject(H,P))});var B;return H}},{immediate:36}],38:[function(i,t,e){"use strict";var r={};(0,i("./lib/utils/common").assign)(r,i("./lib/deflate"),i("./lib/inflate"),i("./lib/zlib/constants")),t.exports=r},{"./lib/deflate":39,"./lib/inflate":40,"./lib/utils/common":41,"./lib/zlib/constants":44}],39:[function(i,t,e){"use strict";var r=i("./zlib/deflate"),o=i("./utils/common"),s=i("./utils/strings"),n=i("./zlib/messages"),a=i("./zlib/zstream"),c=Object.prototype.toString,d=0,m=-1,l=0,f=8;function g(E){if(!(this instanceof g))return new g(E);this.options=o.assign({level:m,method:f,chunkSize:16384,windowBits:15,memLevel:8,strategy:l,to:""},E||{});var y=this.options;y.raw&&0<y.windowBits?y.windowBits=-y.windowBits:y.gzip&&0<y.windowBits&&y.windowBits<16&&(y.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new a,this.strm.avail_out=0;var v=r.deflateInit2(this.strm,y.level,y.method,y.windowBits,y.memLevel,y.strategy);if(v!==d)throw new Error(n[v]);if(y.header&&r.deflateSetHeader(this.strm,y.header),y.dictionary){var M;if(M=typeof y.dictionary=="string"?s.string2buf(y.dictionary):c.call(y.dictionary)==="[object ArrayBuffer]"?new Uint8Array(y.dictionary):y.dictionary,(v=r.deflateSetDictionary(this.strm,M))!==d)throw new Error(n[v]);this._dict_set=!0}}function T(E,y){var v=new g(y);if(v.push(E,!0),v.err)throw v.msg||n[v.err];return v.result}g.prototype.push=function(E,y){var v,M,w=this.strm,H=this.options.chunkSize;if(this.ended)return!1;M=y===~~y?y:y===!0?4:0,typeof E=="string"?w.input=s.string2buf(E):c.call(E)==="[object ArrayBuffer]"?w.input=new Uint8Array(E):w.input=E,w.next_in=0,w.avail_in=w.input.length;do{if(w.avail_out===0&&(w.output=new o.Buf8(H),w.next_out=0,w.avail_out=H),(v=r.deflate(w,M))!==1&&v!==d)return this.onEnd(v),!(this.ended=!0);w.avail_out!==0&&(w.avail_in!==0||M!==4&&M!==2)||(this.options.to==="string"?this.onData(s.buf2binstring(o.shrinkBuf(w.output,w.next_out))):this.onData(o.shrinkBuf(w.output,w.next_out)))}while((0<w.avail_in||w.avail_out===0)&&v!==1);return M===4?(v=r.deflateEnd(this.strm),this.onEnd(v),this.ended=!0,v===d):M!==2||(this.onEnd(d),!(w.avail_out=0))},g.prototype.onData=function(E){this.chunks.push(E)},g.prototype.onEnd=function(E){E===d&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=o.flattenChunks(this.chunks)),this.chunks=[],this.err=E,this.msg=this.strm.msg},e.Deflate=g,e.deflate=T,e.deflateRaw=function(E,y){return(y=y||{}).raw=!0,T(E,y)},e.gzip=function(E,y){return(y=y||{}).gzip=!0,T(E,y)}},{"./utils/common":41,"./utils/strings":42,"./zlib/deflate":46,"./zlib/messages":51,"./zlib/zstream":53}],40:[function(i,t,e){"use strict";var r=i("./zlib/inflate"),o=i("./utils/common"),s=i("./utils/strings"),n=i("./zlib/constants"),a=i("./zlib/messages"),c=i("./zlib/zstream"),d=i("./zlib/gzheader"),m=Object.prototype.toString;function l(g){if(!(this instanceof l))return new l(g);this.options=o.assign({chunkSize:16384,windowBits:0,to:""},g||{});var T=this.options;T.raw&&0<=T.windowBits&&T.windowBits<16&&(T.windowBits=-T.windowBits,T.windowBits===0&&(T.windowBits=-15)),!(0<=T.windowBits&&T.windowBits<16)||g&&g.windowBits||(T.windowBits+=32),15<T.windowBits&&T.windowBits<48&&(15&T.windowBits)==0&&(T.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new c,this.strm.avail_out=0;var E=r.inflateInit2(this.strm,T.windowBits);if(E!==n.Z_OK)throw new Error(a[E]);this.header=new d,r.inflateGetHeader(this.strm,this.header)}function f(g,T){var E=new l(T);if(E.push(g,!0),E.err)throw E.msg||a[E.err];return E.result}l.prototype.push=function(g,T){var E,y,v,M,w,H,B=this.strm,P=this.options.chunkSize,$=this.options.dictionary,de=!1;if(this.ended)return!1;y=T===~~T?T:T===!0?n.Z_FINISH:n.Z_NO_FLUSH,typeof g=="string"?B.input=s.binstring2buf(g):m.call(g)==="[object ArrayBuffer]"?B.input=new Uint8Array(g):B.input=g,B.next_in=0,B.avail_in=B.input.length;do{if(B.avail_out===0&&(B.output=new o.Buf8(P),B.next_out=0,B.avail_out=P),(E=r.inflate(B,n.Z_NO_FLUSH))===n.Z_NEED_DICT&&$&&(H=typeof $=="string"?s.string2buf($):m.call($)==="[object ArrayBuffer]"?new Uint8Array($):$,E=r.inflateSetDictionary(this.strm,H)),E===n.Z_BUF_ERROR&&de===!0&&(E=n.Z_OK,de=!1),E!==n.Z_STREAM_END&&E!==n.Z_OK)return this.onEnd(E),!(this.ended=!0);B.next_out&&(B.avail_out!==0&&E!==n.Z_STREAM_END&&(B.avail_in!==0||y!==n.Z_FINISH&&y!==n.Z_SYNC_FLUSH)||(this.options.to==="string"?(v=s.utf8border(B.output,B.next_out),M=B.next_out-v,w=s.buf2string(B.output,v),B.next_out=M,B.avail_out=P-M,M&&o.arraySet(B.output,B.output,v,M,0),this.onData(w)):this.onData(o.shrinkBuf(B.output,B.next_out)))),B.avail_in===0&&B.avail_out===0&&(de=!0)}while((0<B.avail_in||B.avail_out===0)&&E!==n.Z_STREAM_END);return E===n.Z_STREAM_END&&(y=n.Z_FINISH),y===n.Z_FINISH?(E=r.inflateEnd(this.strm),this.onEnd(E),this.ended=!0,E===n.Z_OK):y!==n.Z_SYNC_FLUSH||(this.onEnd(n.Z_OK),!(B.avail_out=0))},l.prototype.onData=function(g){this.chunks.push(g)},l.prototype.onEnd=function(g){g===n.Z_OK&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=o.flattenChunks(this.chunks)),this.chunks=[],this.err=g,this.msg=this.strm.msg},e.Inflate=l,e.inflate=f,e.inflateRaw=function(g,T){return(T=T||{}).raw=!0,f(g,T)},e.ungzip=f},{"./utils/common":41,"./utils/strings":42,"./zlib/constants":44,"./zlib/gzheader":47,"./zlib/inflate":49,"./zlib/messages":51,"./zlib/zstream":53}],41:[function(i,t,e){"use strict";var r=typeof Uint8Array!="undefined"&&typeof Uint16Array!="undefined"&&typeof Int32Array!="undefined";e.assign=function(n){for(var a=Array.prototype.slice.call(arguments,1);a.length;){var c=a.shift();if(c){if(typeof c!="object")throw new TypeError(c+"must be non-object");for(var d in c)c.hasOwnProperty(d)&&(n[d]=c[d])}}return n},e.shrinkBuf=function(n,a){return n.length===a?n:n.subarray?n.subarray(0,a):(n.length=a,n)};var o={arraySet:function(n,a,c,d,m){if(a.subarray&&n.subarray)n.set(a.subarray(c,c+d),m);else for(var l=0;l<d;l++)n[m+l]=a[c+l]},flattenChunks:function(n){var a,c,d,m,l,f;for(a=d=0,c=n.length;a<c;a++)d+=n[a].length;for(f=new Uint8Array(d),a=m=0,c=n.length;a<c;a++)l=n[a],f.set(l,m),m+=l.length;return f}},s={arraySet:function(n,a,c,d,m){for(var l=0;l<d;l++)n[m+l]=a[c+l]},flattenChunks:function(n){return[].concat.apply([],n)}};e.setTyped=function(n){n?(e.Buf8=Uint8Array,e.Buf16=Uint16Array,e.Buf32=Int32Array,e.assign(e,o)):(e.Buf8=Array,e.Buf16=Array,e.Buf32=Array,e.assign(e,s))},e.setTyped(r)},{}],42:[function(i,t,e){"use strict";var r=i("./common"),o=!0,s=!0;try{String.fromCharCode.apply(null,[0])}catch(d){o=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(d){s=!1}for(var n=new r.Buf8(256),a=0;a<256;a++)n[a]=252<=a?6:248<=a?5:240<=a?4:224<=a?3:192<=a?2:1;function c(d,m){if(m<65537&&(d.subarray&&s||!d.subarray&&o))return String.fromCharCode.apply(null,r.shrinkBuf(d,m));for(var l="",f=0;f<m;f++)l+=String.fromCharCode(d[f]);return l}n[254]=n[254]=1,e.string2buf=function(d){var m,l,f,g,T,E=d.length,y=0;for(g=0;g<E;g++)(64512&(l=d.charCodeAt(g)))==55296&&g+1<E&&(64512&(f=d.charCodeAt(g+1)))==56320&&(l=65536+(l-55296<<10)+(f-56320),g++),y+=l<128?1:l<2048?2:l<65536?3:4;for(m=new r.Buf8(y),g=T=0;T<y;g++)(64512&(l=d.charCodeAt(g)))==55296&&g+1<E&&(64512&(f=d.charCodeAt(g+1)))==56320&&(l=65536+(l-55296<<10)+(f-56320),g++),l<128?m[T++]=l:(l<2048?m[T++]=192|l>>>6:(l<65536?m[T++]=224|l>>>12:(m[T++]=240|l>>>18,m[T++]=128|l>>>12&63),m[T++]=128|l>>>6&63),m[T++]=128|63&l);return m},e.buf2binstring=function(d){return c(d,d.length)},e.binstring2buf=function(d){for(var m=new r.Buf8(d.length),l=0,f=m.length;l<f;l++)m[l]=d.charCodeAt(l);return m},e.buf2string=function(d,m){var l,f,g,T,E=m||d.length,y=new Array(2*E);for(l=f=0;l<E;)if((g=d[l++])<128)y[f++]=g;else if(4<(T=n[g]))y[f++]=65533,l+=T-1;else{for(g&=T===2?31:T===3?15:7;1<T&&l<E;)g=g<<6|63&d[l++],T--;1<T?y[f++]=65533:g<65536?y[f++]=g:(g-=65536,y[f++]=55296|g>>10&1023,y[f++]=56320|1023&g)}return c(y,f)},e.utf8border=function(d,m){var l;for((m=m||d.length)>d.length&&(m=d.length),l=m-1;0<=l&&(192&d[l])==128;)l--;return l<0||l===0?m:l+n[d[l]]>m?l:m}},{"./common":41}],43:[function(i,t,e){"use strict";t.exports=function(r,o,s,n){for(var a=65535&r|0,c=r>>>16&65535|0,d=0;s!==0;){for(s-=d=2e3<s?2e3:s;c=c+(a=a+o[n++]|0)|0,--d;);a%=65521,c%=65521}return a|c<<16|0}},{}],44:[function(i,t,e){"use strict";t.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],45:[function(i,t,e){"use strict";var r=function(){for(var o,s=[],n=0;n<256;n++){o=n;for(var a=0;a<8;a++)o=1&o?3988292384^o>>>1:o>>>1;s[n]=o}return s}();t.exports=function(o,s,n,a){var c=r,d=a+n;o^=-1;for(var m=a;m<d;m++)o=o>>>8^c[255&(o^s[m])];return-1^o}},{}],46:[function(i,t,e){"use strict";var r,o=i("../utils/common"),s=i("./trees"),n=i("./adler32"),a=i("./crc32"),c=i("./messages"),d=0,m=4,l=0,f=-2,g=-1,T=4,E=2,y=8,v=9,M=286,w=30,H=19,B=2*M+1,P=15,$=3,de=258,Ae=de+$+1,L=42,te=113,A=1,le=2,He=3,ge=4;function ze(S,ue){return S.msg=c[ue],ue}function me(S){return(S<<1)-(4<S?9:0)}function re(S){for(var ue=S.length;0<=--ue;)S[ue]=0}function Q(S){var ue=S.state,Y=ue.pending;Y>S.avail_out&&(Y=S.avail_out),Y!==0&&(o.arraySet(S.output,ue.pending_buf,ue.pending_out,Y,S.next_out),S.next_out+=Y,ue.pending_out+=Y,S.total_out+=Y,S.avail_out-=Y,ue.pending-=Y,ue.pending===0&&(ue.pending_out=0))}function q(S,ue){s._tr_flush_block(S,0<=S.block_start?S.block_start:-1,S.strstart-S.block_start,ue),S.block_start=S.strstart,Q(S.strm)}function Be(S,ue){S.pending_buf[S.pending++]=ue}function De(S,ue){S.pending_buf[S.pending++]=ue>>>8&255,S.pending_buf[S.pending++]=255&ue}function ne(S,ue){var Y,x,O=S.max_chain_length,F=S.strstart,pe=S.prev_length,fe=S.nice_match,X=S.strstart>S.w_size-Ae?S.strstart-(S.w_size-Ae):0,oe=S.window,xe=S.w_mask,Z=S.prev,$e=S.strstart+de,b=oe[F+pe-1],it=oe[F+pe];S.prev_length>=S.good_match&&(O>>=2),fe>S.lookahead&&(fe=S.lookahead);do if(oe[(Y=ue)+pe]===it&&oe[Y+pe-1]===b&&oe[Y]===oe[F]&&oe[++Y]===oe[F+1]){F+=2,Y++;do;while(oe[++F]===oe[++Y]&&oe[++F]===oe[++Y]&&oe[++F]===oe[++Y]&&oe[++F]===oe[++Y]&&oe[++F]===oe[++Y]&&oe[++F]===oe[++Y]&&oe[++F]===oe[++Y]&&oe[++F]===oe[++Y]&&F<$e);if(x=de-($e-F),F=$e-de,pe<x){if(S.match_start=ue,fe<=(pe=x))break;b=oe[F+pe-1],it=oe[F+pe]}}while((ue=Z[ue&xe])>X&&--O!=0);return pe<=S.lookahead?pe:S.lookahead}function Ze(S){var ue,Y,x,O,F,pe,fe,X,oe,xe,Z=S.w_size;do{if(O=S.window_size-S.lookahead-S.strstart,S.strstart>=Z+(Z-Ae)){for(o.arraySet(S.window,S.window,Z,Z,0),S.match_start-=Z,S.strstart-=Z,S.block_start-=Z,ue=Y=S.hash_size;x=S.head[--ue],S.head[ue]=Z<=x?x-Z:0,--Y;);for(ue=Y=Z;x=S.prev[--ue],S.prev[ue]=Z<=x?x-Z:0,--Y;);O+=Z}if(S.strm.avail_in===0)break;if(pe=S.strm,fe=S.window,X=S.strstart+S.lookahead,oe=O,xe=void 0,xe=pe.avail_in,oe<xe&&(xe=oe),Y=xe===0?0:(pe.avail_in-=xe,o.arraySet(fe,pe.input,pe.next_in,xe,X),pe.state.wrap===1?pe.adler=n(pe.adler,fe,xe,X):pe.state.wrap===2&&(pe.adler=a(pe.adler,fe,xe,X)),pe.next_in+=xe,pe.total_in+=xe,xe),S.lookahead+=Y,S.lookahead+S.insert>=$)for(F=S.strstart-S.insert,S.ins_h=S.window[F],S.ins_h=(S.ins_h<<S.hash_shift^S.window[F+1])&S.hash_mask;S.insert&&(S.ins_h=(S.ins_h<<S.hash_shift^S.window[F+$-1])&S.hash_mask,S.prev[F&S.w_mask]=S.head[S.ins_h],S.head[S.ins_h]=F,F++,S.insert--,!(S.lookahead+S.insert<$)););}while(S.lookahead<Ae&&S.strm.avail_in!==0)}function yt(S,ue){for(var Y,x;;){if(S.lookahead<Ae){if(Ze(S),S.lookahead<Ae&&ue===d)return A;if(S.lookahead===0)break}if(Y=0,S.lookahead>=$&&(S.ins_h=(S.ins_h<<S.hash_shift^S.window[S.strstart+$-1])&S.hash_mask,Y=S.prev[S.strstart&S.w_mask]=S.head[S.ins_h],S.head[S.ins_h]=S.strstart),Y!==0&&S.strstart-Y<=S.w_size-Ae&&(S.match_length=ne(S,Y)),S.match_length>=$)if(x=s._tr_tally(S,S.strstart-S.match_start,S.match_length-$),S.lookahead-=S.match_length,S.match_length<=S.max_lazy_match&&S.lookahead>=$){for(S.match_length--;S.strstart++,S.ins_h=(S.ins_h<<S.hash_shift^S.window[S.strstart+$-1])&S.hash_mask,Y=S.prev[S.strstart&S.w_mask]=S.head[S.ins_h],S.head[S.ins_h]=S.strstart,--S.match_length!=0;);S.strstart++}else S.strstart+=S.match_length,S.match_length=0,S.ins_h=S.window[S.strstart],S.ins_h=(S.ins_h<<S.hash_shift^S.window[S.strstart+1])&S.hash_mask;else x=s._tr_tally(S,0,S.window[S.strstart]),S.lookahead--,S.strstart++;if(x&&(q(S,!1),S.strm.avail_out===0))return A}return S.insert=S.strstart<$-1?S.strstart:$-1,ue===m?(q(S,!0),S.strm.avail_out===0?He:ge):S.last_lit&&(q(S,!1),S.strm.avail_out===0)?A:le}function ae(S,ue){for(var Y,x,O;;){if(S.lookahead<Ae){if(Ze(S),S.lookahead<Ae&&ue===d)return A;if(S.lookahead===0)break}if(Y=0,S.lookahead>=$&&(S.ins_h=(S.ins_h<<S.hash_shift^S.window[S.strstart+$-1])&S.hash_mask,Y=S.prev[S.strstart&S.w_mask]=S.head[S.ins_h],S.head[S.ins_h]=S.strstart),S.prev_length=S.match_length,S.prev_match=S.match_start,S.match_length=$-1,Y!==0&&S.prev_length<S.max_lazy_match&&S.strstart-Y<=S.w_size-Ae&&(S.match_length=ne(S,Y),S.match_length<=5&&(S.strategy===1||S.match_length===$&&4096<S.strstart-S.match_start)&&(S.match_length=$-1)),S.prev_length>=$&&S.match_length<=S.prev_length){for(O=S.strstart+S.lookahead-$,x=s._tr_tally(S,S.strstart-1-S.prev_match,S.prev_length-$),S.lookahead-=S.prev_length-1,S.prev_length-=2;++S.strstart<=O&&(S.ins_h=(S.ins_h<<S.hash_shift^S.window[S.strstart+$-1])&S.hash_mask,Y=S.prev[S.strstart&S.w_mask]=S.head[S.ins_h],S.head[S.ins_h]=S.strstart),--S.prev_length!=0;);if(S.match_available=0,S.match_length=$-1,S.strstart++,x&&(q(S,!1),S.strm.avail_out===0))return A}else if(S.match_available){if((x=s._tr_tally(S,0,S.window[S.strstart-1]))&&q(S,!1),S.strstart++,S.lookahead--,S.strm.avail_out===0)return A}else S.match_available=1,S.strstart++,S.lookahead--}return S.match_available&&(x=s._tr_tally(S,0,S.window[S.strstart-1]),S.match_available=0),S.insert=S.strstart<$-1?S.strstart:$-1,ue===m?(q(S,!0),S.strm.avail_out===0?He:ge):S.last_lit&&(q(S,!1),S.strm.avail_out===0)?A:le}function at(S,ue,Y,x,O){this.good_length=S,this.max_lazy=ue,this.nice_length=Y,this.max_chain=x,this.func=O}function Lt(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=y,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new o.Buf16(2*B),this.dyn_dtree=new o.Buf16(2*(2*w+1)),this.bl_tree=new o.Buf16(2*(2*H+1)),re(this.dyn_ltree),re(this.dyn_dtree),re(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new o.Buf16(P+1),this.heap=new o.Buf16(2*M+1),re(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new o.Buf16(2*M+1),re(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function wt(S){var ue;return S&&S.state?(S.total_in=S.total_out=0,S.data_type=E,(ue=S.state).pending=0,ue.pending_out=0,ue.wrap<0&&(ue.wrap=-ue.wrap),ue.status=ue.wrap?L:te,S.adler=ue.wrap===2?0:1,ue.last_flush=d,s._tr_init(ue),l):ze(S,f)}function we(S){var ue=wt(S);return ue===l&&function(Y){Y.window_size=2*Y.w_size,re(Y.head),Y.max_lazy_match=r[Y.level].max_lazy,Y.good_match=r[Y.level].good_length,Y.nice_match=r[Y.level].nice_length,Y.max_chain_length=r[Y.level].max_chain,Y.strstart=0,Y.block_start=0,Y.lookahead=0,Y.insert=0,Y.match_length=Y.prev_length=$-1,Y.match_available=0,Y.ins_h=0}(S.state),ue}function fr(S,ue,Y,x,O,F){if(!S)return f;var pe=1;if(ue===g&&(ue=6),x<0?(pe=0,x=-x):15<x&&(pe=2,x-=16),O<1||v<O||Y!==y||x<8||15<x||ue<0||9<ue||F<0||T<F)return ze(S,f);x===8&&(x=9);var fe=new Lt;return(S.state=fe).strm=S,fe.wrap=pe,fe.gzhead=null,fe.w_bits=x,fe.w_size=1<<fe.w_bits,fe.w_mask=fe.w_size-1,fe.hash_bits=O+7,fe.hash_size=1<<fe.hash_bits,fe.hash_mask=fe.hash_size-1,fe.hash_shift=~~((fe.hash_bits+$-1)/$),fe.window=new o.Buf8(2*fe.w_size),fe.head=new o.Buf16(fe.hash_size),fe.prev=new o.Buf16(fe.w_size),fe.lit_bufsize=1<<O+6,fe.pending_buf_size=4*fe.lit_bufsize,fe.pending_buf=new o.Buf8(fe.pending_buf_size),fe.d_buf=1*fe.lit_bufsize,fe.l_buf=3*fe.lit_bufsize,fe.level=ue,fe.strategy=F,fe.method=Y,we(S)}r=[new at(0,0,0,0,function(S,ue){var Y=65535;for(Y>S.pending_buf_size-5&&(Y=S.pending_buf_size-5);;){if(S.lookahead<=1){if(Ze(S),S.lookahead===0&&ue===d)return A;if(S.lookahead===0)break}S.strstart+=S.lookahead,S.lookahead=0;var x=S.block_start+Y;if((S.strstart===0||S.strstart>=x)&&(S.lookahead=S.strstart-x,S.strstart=x,q(S,!1),S.strm.avail_out===0)||S.strstart-S.block_start>=S.w_size-Ae&&(q(S,!1),S.strm.avail_out===0))return A}return S.insert=0,ue===m?(q(S,!0),S.strm.avail_out===0?He:ge):(S.strstart>S.block_start&&(q(S,!1),S.strm.avail_out),A)}),new at(4,4,8,4,yt),new at(4,5,16,8,yt),new at(4,6,32,32,yt),new at(4,4,16,16,ae),new at(8,16,32,32,ae),new at(8,16,128,128,ae),new at(8,32,128,256,ae),new at(32,128,258,1024,ae),new at(32,258,258,4096,ae)],e.deflateInit=function(S,ue){return fr(S,ue,y,15,8,0)},e.deflateInit2=fr,e.deflateReset=we,e.deflateResetKeep=wt,e.deflateSetHeader=function(S,ue){return S&&S.state?S.state.wrap!==2?f:(S.state.gzhead=ue,l):f},e.deflate=function(S,ue){var Y,x,O,F;if(!S||!S.state||5<ue||ue<0)return S?ze(S,f):f;if(x=S.state,!S.output||!S.input&&S.avail_in!==0||x.status===666&&ue!==m)return ze(S,S.avail_out===0?-5:f);if(x.strm=S,Y=x.last_flush,x.last_flush=ue,x.status===L)if(x.wrap===2)S.adler=0,Be(x,31),Be(x,139),Be(x,8),x.gzhead?(Be(x,(x.gzhead.text?1:0)+(x.gzhead.hcrc?2:0)+(x.gzhead.extra?4:0)+(x.gzhead.name?8:0)+(x.gzhead.comment?16:0)),Be(x,255&x.gzhead.time),Be(x,x.gzhead.time>>8&255),Be(x,x.gzhead.time>>16&255),Be(x,x.gzhead.time>>24&255),Be(x,x.level===9?2:2<=x.strategy||x.level<2?4:0),Be(x,255&x.gzhead.os),x.gzhead.extra&&x.gzhead.extra.length&&(Be(x,255&x.gzhead.extra.length),Be(x,x.gzhead.extra.length>>8&255)),x.gzhead.hcrc&&(S.adler=a(S.adler,x.pending_buf,x.pending,0)),x.gzindex=0,x.status=69):(Be(x,0),Be(x,0),Be(x,0),Be(x,0),Be(x,0),Be(x,x.level===9?2:2<=x.strategy||x.level<2?4:0),Be(x,3),x.status=te);else{var pe=y+(x.w_bits-8<<4)<<8;pe|=(2<=x.strategy||x.level<2?0:x.level<6?1:x.level===6?2:3)<<6,x.strstart!==0&&(pe|=32),pe+=31-pe%31,x.status=te,De(x,pe),x.strstart!==0&&(De(x,S.adler>>>16),De(x,65535&S.adler)),S.adler=1}if(x.status===69)if(x.gzhead.extra){for(O=x.pending;x.gzindex<(65535&x.gzhead.extra.length)&&(x.pending!==x.pending_buf_size||(x.gzhead.hcrc&&x.pending>O&&(S.adler=a(S.adler,x.pending_buf,x.pending-O,O)),Q(S),O=x.pending,x.pending!==x.pending_buf_size));)Be(x,255&x.gzhead.extra[x.gzindex]),x.gzindex++;x.gzhead.hcrc&&x.pending>O&&(S.adler=a(S.adler,x.pending_buf,x.pending-O,O)),x.gzindex===x.gzhead.extra.length&&(x.gzindex=0,x.status=73)}else x.status=73;if(x.status===73)if(x.gzhead.name){O=x.pending;do{if(x.pending===x.pending_buf_size&&(x.gzhead.hcrc&&x.pending>O&&(S.adler=a(S.adler,x.pending_buf,x.pending-O,O)),Q(S),O=x.pending,x.pending===x.pending_buf_size)){F=1;break}F=x.gzindex<x.gzhead.name.length?255&x.gzhead.name.charCodeAt(x.gzindex++):0,Be(x,F)}while(F!==0);x.gzhead.hcrc&&x.pending>O&&(S.adler=a(S.adler,x.pending_buf,x.pending-O,O)),F===0&&(x.gzindex=0,x.status=91)}else x.status=91;if(x.status===91)if(x.gzhead.comment){O=x.pending;do{if(x.pending===x.pending_buf_size&&(x.gzhead.hcrc&&x.pending>O&&(S.adler=a(S.adler,x.pending_buf,x.pending-O,O)),Q(S),O=x.pending,x.pending===x.pending_buf_size)){F=1;break}F=x.gzindex<x.gzhead.comment.length?255&x.gzhead.comment.charCodeAt(x.gzindex++):0,Be(x,F)}while(F!==0);x.gzhead.hcrc&&x.pending>O&&(S.adler=a(S.adler,x.pending_buf,x.pending-O,O)),F===0&&(x.status=103)}else x.status=103;if(x.status===103&&(x.gzhead.hcrc?(x.pending+2>x.pending_buf_size&&Q(S),x.pending+2<=x.pending_buf_size&&(Be(x,255&S.adler),Be(x,S.adler>>8&255),S.adler=0,x.status=te)):x.status=te),x.pending!==0){if(Q(S),S.avail_out===0)return x.last_flush=-1,l}else if(S.avail_in===0&&me(ue)<=me(Y)&&ue!==m)return ze(S,-5);if(x.status===666&&S.avail_in!==0)return ze(S,-5);if(S.avail_in!==0||x.lookahead!==0||ue!==d&&x.status!==666){var fe=x.strategy===2?function(X,oe){for(var xe;;){if(X.lookahead===0&&(Ze(X),X.lookahead===0)){if(oe===d)return A;break}if(X.match_length=0,xe=s._tr_tally(X,0,X.window[X.strstart]),X.lookahead--,X.strstart++,xe&&(q(X,!1),X.strm.avail_out===0))return A}return X.insert=0,oe===m?(q(X,!0),X.strm.avail_out===0?He:ge):X.last_lit&&(q(X,!1),X.strm.avail_out===0)?A:le}(x,ue):x.strategy===3?function(X,oe){for(var xe,Z,$e,b,it=X.window;;){if(X.lookahead<=de){if(Ze(X),X.lookahead<=de&&oe===d)return A;if(X.lookahead===0)break}if(X.match_length=0,X.lookahead>=$&&0<X.strstart&&(Z=it[$e=X.strstart-1])===it[++$e]&&Z===it[++$e]&&Z===it[++$e]){b=X.strstart+de;do;while(Z===it[++$e]&&Z===it[++$e]&&Z===it[++$e]&&Z===it[++$e]&&Z===it[++$e]&&Z===it[++$e]&&Z===it[++$e]&&Z===it[++$e]&&$e<b);X.match_length=de-(b-$e),X.match_length>X.lookahead&&(X.match_length=X.lookahead)}if(X.match_length>=$?(xe=s._tr_tally(X,1,X.match_length-$),X.lookahead-=X.match_length,X.strstart+=X.match_length,X.match_length=0):(xe=s._tr_tally(X,0,X.window[X.strstart]),X.lookahead--,X.strstart++),xe&&(q(X,!1),X.strm.avail_out===0))return A}return X.insert=0,oe===m?(q(X,!0),X.strm.avail_out===0?He:ge):X.last_lit&&(q(X,!1),X.strm.avail_out===0)?A:le}(x,ue):r[x.level].func(x,ue);if(fe!==He&&fe!==ge||(x.status=666),fe===A||fe===He)return S.avail_out===0&&(x.last_flush=-1),l;if(fe===le&&(ue===1?s._tr_align(x):ue!==5&&(s._tr_stored_block(x,0,0,!1),ue===3&&(re(x.head),x.lookahead===0&&(x.strstart=0,x.block_start=0,x.insert=0))),Q(S),S.avail_out===0))return x.last_flush=-1,l}return ue!==m?l:x.wrap<=0?1:(x.wrap===2?(Be(x,255&S.adler),Be(x,S.adler>>8&255),Be(x,S.adler>>16&255),Be(x,S.adler>>24&255),Be(x,255&S.total_in),Be(x,S.total_in>>8&255),Be(x,S.total_in>>16&255),Be(x,S.total_in>>24&255)):(De(x,S.adler>>>16),De(x,65535&S.adler)),Q(S),0<x.wrap&&(x.wrap=-x.wrap),x.pending!==0?l:1)},e.deflateEnd=function(S){var ue;return S&&S.state?(ue=S.state.status)!==L&&ue!==69&&ue!==73&&ue!==91&&ue!==103&&ue!==te&&ue!==666?ze(S,f):(S.state=null,ue===te?ze(S,-3):l):f},e.deflateSetDictionary=function(S,ue){var Y,x,O,F,pe,fe,X,oe,xe=ue.length;if(!S||!S.state||(F=(Y=S.state).wrap)===2||F===1&&Y.status!==L||Y.lookahead)return f;for(F===1&&(S.adler=n(S.adler,ue,xe,0)),Y.wrap=0,xe>=Y.w_size&&(F===0&&(re(Y.head),Y.strstart=0,Y.block_start=0,Y.insert=0),oe=new o.Buf8(Y.w_size),o.arraySet(oe,ue,xe-Y.w_size,Y.w_size,0),ue=oe,xe=Y.w_size),pe=S.avail_in,fe=S.next_in,X=S.input,S.avail_in=xe,S.next_in=0,S.input=ue,Ze(Y);Y.lookahead>=$;){for(x=Y.strstart,O=Y.lookahead-($-1);Y.ins_h=(Y.ins_h<<Y.hash_shift^Y.window[x+$-1])&Y.hash_mask,Y.prev[x&Y.w_mask]=Y.head[Y.ins_h],Y.head[Y.ins_h]=x,x++,--O;);Y.strstart=x,Y.lookahead=$-1,Ze(Y)}return Y.strstart+=Y.lookahead,Y.block_start=Y.strstart,Y.insert=Y.lookahead,Y.lookahead=0,Y.match_length=Y.prev_length=$-1,Y.match_available=0,S.next_in=fe,S.input=X,S.avail_in=pe,Y.wrap=F,l},e.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./messages":51,"./trees":52}],47:[function(i,t,e){"use strict";t.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],48:[function(i,t,e){"use strict";t.exports=function(r,o){var s,n,a,c,d,m,l,f,g,T,E,y,v,M,w,H,B,P,$,de,Ae,L,te,A,le;s=r.state,n=r.next_in,A=r.input,a=n+(r.avail_in-5),c=r.next_out,le=r.output,d=c-(o-r.avail_out),m=c+(r.avail_out-257),l=s.dmax,f=s.wsize,g=s.whave,T=s.wnext,E=s.window,y=s.hold,v=s.bits,M=s.lencode,w=s.distcode,H=(1<<s.lenbits)-1,B=(1<<s.distbits)-1;e:do{v<15&&(y+=A[n++]<<v,v+=8,y+=A[n++]<<v,v+=8),P=M[y&H];t:for(;;){if(y>>>=$=P>>>24,v-=$,($=P>>>16&255)===0)le[c++]=65535&P;else{if(!(16&$)){if((64&$)==0){P=M[(65535&P)+(y&(1<<$)-1)];continue t}if(32&$){s.mode=12;break e}r.msg="invalid literal/length code",s.mode=30;break e}de=65535&P,($&=15)&&(v<$&&(y+=A[n++]<<v,v+=8),de+=y&(1<<$)-1,y>>>=$,v-=$),v<15&&(y+=A[n++]<<v,v+=8,y+=A[n++]<<v,v+=8),P=w[y&B];r:for(;;){if(y>>>=$=P>>>24,v-=$,!(16&($=P>>>16&255))){if((64&$)==0){P=w[(65535&P)+(y&(1<<$)-1)];continue r}r.msg="invalid distance code",s.mode=30;break e}if(Ae=65535&P,v<($&=15)&&(y+=A[n++]<<v,(v+=8)<$&&(y+=A[n++]<<v,v+=8)),l<(Ae+=y&(1<<$)-1)){r.msg="invalid distance too far back",s.mode=30;break e}if(y>>>=$,v-=$,($=c-d)<Ae){if(g<($=Ae-$)&&s.sane){r.msg="invalid distance too far back",s.mode=30;break e}if(te=E,(L=0)===T){if(L+=f-$,$<de){for(de-=$;le[c++]=E[L++],--$;);L=c-Ae,te=le}}else if(T<$){if(L+=f+T-$,($-=T)<de){for(de-=$;le[c++]=E[L++],--$;);if(L=0,T<de){for(de-=$=T;le[c++]=E[L++],--$;);L=c-Ae,te=le}}}else if(L+=T-$,$<de){for(de-=$;le[c++]=E[L++],--$;);L=c-Ae,te=le}for(;2<de;)le[c++]=te[L++],le[c++]=te[L++],le[c++]=te[L++],de-=3;de&&(le[c++]=te[L++],1<de&&(le[c++]=te[L++]))}else{for(L=c-Ae;le[c++]=le[L++],le[c++]=le[L++],le[c++]=le[L++],2<(de-=3););de&&(le[c++]=le[L++],1<de&&(le[c++]=le[L++]))}break}}break}}while(n<a&&c<m);n-=de=v>>3,y&=(1<<(v-=de<<3))-1,r.next_in=n,r.next_out=c,r.avail_in=n<a?a-n+5:5-(n-a),r.avail_out=c<m?m-c+257:257-(c-m),s.hold=y,s.bits=v}},{}],49:[function(i,t,e){"use strict";var r=i("../utils/common"),o=i("./adler32"),s=i("./crc32"),n=i("./inffast"),a=i("./inftrees"),c=1,d=2,m=0,l=-2,f=1,g=852,T=592;function E(L){return(L>>>24&255)+(L>>>8&65280)+((65280&L)<<8)+((255&L)<<24)}function y(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new r.Buf16(320),this.work=new r.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function v(L){var te;return L&&L.state?(te=L.state,L.total_in=L.total_out=te.total=0,L.msg="",te.wrap&&(L.adler=1&te.wrap),te.mode=f,te.last=0,te.havedict=0,te.dmax=32768,te.head=null,te.hold=0,te.bits=0,te.lencode=te.lendyn=new r.Buf32(g),te.distcode=te.distdyn=new r.Buf32(T),te.sane=1,te.back=-1,m):l}function M(L){var te;return L&&L.state?((te=L.state).wsize=0,te.whave=0,te.wnext=0,v(L)):l}function w(L,te){var A,le;return L&&L.state?(le=L.state,te<0?(A=0,te=-te):(A=1+(te>>4),te<48&&(te&=15)),te&&(te<8||15<te)?l:(le.window!==null&&le.wbits!==te&&(le.window=null),le.wrap=A,le.wbits=te,M(L))):l}function H(L,te){var A,le;return L?(le=new y,(L.state=le).window=null,(A=w(L,te))!==m&&(L.state=null),A):l}var B,P,$=!0;function de(L){if($){var te;for(B=new r.Buf32(512),P=new r.Buf32(32),te=0;te<144;)L.lens[te++]=8;for(;te<256;)L.lens[te++]=9;for(;te<280;)L.lens[te++]=7;for(;te<288;)L.lens[te++]=8;for(a(c,L.lens,0,288,B,0,L.work,{bits:9}),te=0;te<32;)L.lens[te++]=5;a(d,L.lens,0,32,P,0,L.work,{bits:5}),$=!1}L.lencode=B,L.lenbits=9,L.distcode=P,L.distbits=5}function Ae(L,te,A,le){var He,ge=L.state;return ge.window===null&&(ge.wsize=1<<ge.wbits,ge.wnext=0,ge.whave=0,ge.window=new r.Buf8(ge.wsize)),le>=ge.wsize?(r.arraySet(ge.window,te,A-ge.wsize,ge.wsize,0),ge.wnext=0,ge.whave=ge.wsize):(le<(He=ge.wsize-ge.wnext)&&(He=le),r.arraySet(ge.window,te,A-le,He,ge.wnext),(le-=He)?(r.arraySet(ge.window,te,A-le,le,0),ge.wnext=le,ge.whave=ge.wsize):(ge.wnext+=He,ge.wnext===ge.wsize&&(ge.wnext=0),ge.whave<ge.wsize&&(ge.whave+=He))),0}e.inflateReset=M,e.inflateReset2=w,e.inflateResetKeep=v,e.inflateInit=function(L){return H(L,15)},e.inflateInit2=H,e.inflate=function(L,te){var A,le,He,ge,ze,me,re,Q,q,Be,De,ne,Ze,yt,ae,at,Lt,wt,we,fr,S,ue,Y,x,O=0,F=new r.Buf8(4),pe=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!L||!L.state||!L.output||!L.input&&L.avail_in!==0)return l;(A=L.state).mode===12&&(A.mode=13),ze=L.next_out,He=L.output,re=L.avail_out,ge=L.next_in,le=L.input,me=L.avail_in,Q=A.hold,q=A.bits,Be=me,De=re,ue=m;e:for(;;)switch(A.mode){case f:if(A.wrap===0){A.mode=13;break}for(;q<16;){if(me===0)break e;me--,Q+=le[ge++]<<q,q+=8}if(2&A.wrap&&Q===35615){F[A.check=0]=255&Q,F[1]=Q>>>8&255,A.check=s(A.check,F,2,0),q=Q=0,A.mode=2;break}if(A.flags=0,A.head&&(A.head.done=!1),!(1&A.wrap)||(((255&Q)<<8)+(Q>>8))%31){L.msg="incorrect header check",A.mode=30;break}if((15&Q)!=8){L.msg="unknown compression method",A.mode=30;break}if(q-=4,S=8+(15&(Q>>>=4)),A.wbits===0)A.wbits=S;else if(S>A.wbits){L.msg="invalid window size",A.mode=30;break}A.dmax=1<<S,L.adler=A.check=1,A.mode=512&Q?10:12,q=Q=0;break;case 2:for(;q<16;){if(me===0)break e;me--,Q+=le[ge++]<<q,q+=8}if(A.flags=Q,(255&A.flags)!=8){L.msg="unknown compression method",A.mode=30;break}if(57344&A.flags){L.msg="unknown header flags set",A.mode=30;break}A.head&&(A.head.text=Q>>8&1),512&A.flags&&(F[0]=255&Q,F[1]=Q>>>8&255,A.check=s(A.check,F,2,0)),q=Q=0,A.mode=3;case 3:for(;q<32;){if(me===0)break e;me--,Q+=le[ge++]<<q,q+=8}A.head&&(A.head.time=Q),512&A.flags&&(F[0]=255&Q,F[1]=Q>>>8&255,F[2]=Q>>>16&255,F[3]=Q>>>24&255,A.check=s(A.check,F,4,0)),q=Q=0,A.mode=4;case 4:for(;q<16;){if(me===0)break e;me--,Q+=le[ge++]<<q,q+=8}A.head&&(A.head.xflags=255&Q,A.head.os=Q>>8),512&A.flags&&(F[0]=255&Q,F[1]=Q>>>8&255,A.check=s(A.check,F,2,0)),q=Q=0,A.mode=5;case 5:if(1024&A.flags){for(;q<16;){if(me===0)break e;me--,Q+=le[ge++]<<q,q+=8}A.length=Q,A.head&&(A.head.extra_len=Q),512&A.flags&&(F[0]=255&Q,F[1]=Q>>>8&255,A.check=s(A.check,F,2,0)),q=Q=0}else A.head&&(A.head.extra=null);A.mode=6;case 6:if(1024&A.flags&&(me<(ne=A.length)&&(ne=me),ne&&(A.head&&(S=A.head.extra_len-A.length,A.head.extra||(A.head.extra=new Array(A.head.extra_len)),r.arraySet(A.head.extra,le,ge,ne,S)),512&A.flags&&(A.check=s(A.check,le,ne,ge)),me-=ne,ge+=ne,A.length-=ne),A.length))break e;A.length=0,A.mode=7;case 7:if(2048&A.flags){if(me===0)break e;for(ne=0;S=le[ge+ne++],A.head&&S&&A.length<65536&&(A.head.name+=String.fromCharCode(S)),S&&ne<me;);if(512&A.flags&&(A.check=s(A.check,le,ne,ge)),me-=ne,ge+=ne,S)break e}else A.head&&(A.head.name=null);A.length=0,A.mode=8;case 8:if(4096&A.flags){if(me===0)break e;for(ne=0;S=le[ge+ne++],A.head&&S&&A.length<65536&&(A.head.comment+=String.fromCharCode(S)),S&&ne<me;);if(512&A.flags&&(A.check=s(A.check,le,ne,ge)),me-=ne,ge+=ne,S)break e}else A.head&&(A.head.comment=null);A.mode=9;case 9:if(512&A.flags){for(;q<16;){if(me===0)break e;me--,Q+=le[ge++]<<q,q+=8}if(Q!==(65535&A.check)){L.msg="header crc mismatch",A.mode=30;break}q=Q=0}A.head&&(A.head.hcrc=A.flags>>9&1,A.head.done=!0),L.adler=A.check=0,A.mode=12;break;case 10:for(;q<32;){if(me===0)break e;me--,Q+=le[ge++]<<q,q+=8}L.adler=A.check=E(Q),q=Q=0,A.mode=11;case 11:if(A.havedict===0)return L.next_out=ze,L.avail_out=re,L.next_in=ge,L.avail_in=me,A.hold=Q,A.bits=q,2;L.adler=A.check=1,A.mode=12;case 12:if(te===5||te===6)break e;case 13:if(A.last){Q>>>=7&q,q-=7&q,A.mode=27;break}for(;q<3;){if(me===0)break e;me--,Q+=le[ge++]<<q,q+=8}switch(A.last=1&Q,q-=1,3&(Q>>>=1)){case 0:A.mode=14;break;case 1:if(de(A),A.mode=20,te!==6)break;Q>>>=2,q-=2;break e;case 2:A.mode=17;break;case 3:L.msg="invalid block type",A.mode=30}Q>>>=2,q-=2;break;case 14:for(Q>>>=7&q,q-=7&q;q<32;){if(me===0)break e;me--,Q+=le[ge++]<<q,q+=8}if((65535&Q)!=(Q>>>16^65535)){L.msg="invalid stored block lengths",A.mode=30;break}if(A.length=65535&Q,q=Q=0,A.mode=15,te===6)break e;case 15:A.mode=16;case 16:if(ne=A.length){if(me<ne&&(ne=me),re<ne&&(ne=re),ne===0)break e;r.arraySet(He,le,ge,ne,ze),me-=ne,ge+=ne,re-=ne,ze+=ne,A.length-=ne;break}A.mode=12;break;case 17:for(;q<14;){if(me===0)break e;me--,Q+=le[ge++]<<q,q+=8}if(A.nlen=257+(31&Q),Q>>>=5,q-=5,A.ndist=1+(31&Q),Q>>>=5,q-=5,A.ncode=4+(15&Q),Q>>>=4,q-=4,286<A.nlen||30<A.ndist){L.msg="too many length or distance symbols",A.mode=30;break}A.have=0,A.mode=18;case 18:for(;A.have<A.ncode;){for(;q<3;){if(me===0)break e;me--,Q+=le[ge++]<<q,q+=8}A.lens[pe[A.have++]]=7&Q,Q>>>=3,q-=3}for(;A.have<19;)A.lens[pe[A.have++]]=0;if(A.lencode=A.lendyn,A.lenbits=7,Y={bits:A.lenbits},ue=a(0,A.lens,0,19,A.lencode,0,A.work,Y),A.lenbits=Y.bits,ue){L.msg="invalid code lengths set",A.mode=30;break}A.have=0,A.mode=19;case 19:for(;A.have<A.nlen+A.ndist;){for(;at=(O=A.lencode[Q&(1<<A.lenbits)-1])>>>16&255,Lt=65535&O,!((ae=O>>>24)<=q);){if(me===0)break e;me--,Q+=le[ge++]<<q,q+=8}if(Lt<16)Q>>>=ae,q-=ae,A.lens[A.have++]=Lt;else{if(Lt===16){for(x=ae+2;q<x;){if(me===0)break e;me--,Q+=le[ge++]<<q,q+=8}if(Q>>>=ae,q-=ae,A.have===0){L.msg="invalid bit length repeat",A.mode=30;break}S=A.lens[A.have-1],ne=3+(3&Q),Q>>>=2,q-=2}else if(Lt===17){for(x=ae+3;q<x;){if(me===0)break e;me--,Q+=le[ge++]<<q,q+=8}q-=ae,S=0,ne=3+(7&(Q>>>=ae)),Q>>>=3,q-=3}else{for(x=ae+7;q<x;){if(me===0)break e;me--,Q+=le[ge++]<<q,q+=8}q-=ae,S=0,ne=11+(127&(Q>>>=ae)),Q>>>=7,q-=7}if(A.have+ne>A.nlen+A.ndist){L.msg="invalid bit length repeat",A.mode=30;break}for(;ne--;)A.lens[A.have++]=S}}if(A.mode===30)break;if(A.lens[256]===0){L.msg="invalid code -- missing end-of-block",A.mode=30;break}if(A.lenbits=9,Y={bits:A.lenbits},ue=a(c,A.lens,0,A.nlen,A.lencode,0,A.work,Y),A.lenbits=Y.bits,ue){L.msg="invalid literal/lengths set",A.mode=30;break}if(A.distbits=6,A.distcode=A.distdyn,Y={bits:A.distbits},ue=a(d,A.lens,A.nlen,A.ndist,A.distcode,0,A.work,Y),A.distbits=Y.bits,ue){L.msg="invalid distances set",A.mode=30;break}if(A.mode=20,te===6)break e;case 20:A.mode=21;case 21:if(6<=me&&258<=re){L.next_out=ze,L.avail_out=re,L.next_in=ge,L.avail_in=me,A.hold=Q,A.bits=q,n(L,De),ze=L.next_out,He=L.output,re=L.avail_out,ge=L.next_in,le=L.input,me=L.avail_in,Q=A.hold,q=A.bits,A.mode===12&&(A.back=-1);break}for(A.back=0;at=(O=A.lencode[Q&(1<<A.lenbits)-1])>>>16&255,Lt=65535&O,!((ae=O>>>24)<=q);){if(me===0)break e;me--,Q+=le[ge++]<<q,q+=8}if(at&&(240&at)==0){for(wt=ae,we=at,fr=Lt;at=(O=A.lencode[fr+((Q&(1<<wt+we)-1)>>wt)])>>>16&255,Lt=65535&O,!(wt+(ae=O>>>24)<=q);){if(me===0)break e;me--,Q+=le[ge++]<<q,q+=8}Q>>>=wt,q-=wt,A.back+=wt}if(Q>>>=ae,q-=ae,A.back+=ae,A.length=Lt,at===0){A.mode=26;break}if(32&at){A.back=-1,A.mode=12;break}if(64&at){L.msg="invalid literal/length code",A.mode=30;break}A.extra=15&at,A.mode=22;case 22:if(A.extra){for(x=A.extra;q<x;){if(me===0)break e;me--,Q+=le[ge++]<<q,q+=8}A.length+=Q&(1<<A.extra)-1,Q>>>=A.extra,q-=A.extra,A.back+=A.extra}A.was=A.length,A.mode=23;case 23:for(;at=(O=A.distcode[Q&(1<<A.distbits)-1])>>>16&255,Lt=65535&O,!((ae=O>>>24)<=q);){if(me===0)break e;me--,Q+=le[ge++]<<q,q+=8}if((240&at)==0){for(wt=ae,we=at,fr=Lt;at=(O=A.distcode[fr+((Q&(1<<wt+we)-1)>>wt)])>>>16&255,Lt=65535&O,!(wt+(ae=O>>>24)<=q);){if(me===0)break e;me--,Q+=le[ge++]<<q,q+=8}Q>>>=wt,q-=wt,A.back+=wt}if(Q>>>=ae,q-=ae,A.back+=ae,64&at){L.msg="invalid distance code",A.mode=30;break}A.offset=Lt,A.extra=15&at,A.mode=24;case 24:if(A.extra){for(x=A.extra;q<x;){if(me===0)break e;me--,Q+=le[ge++]<<q,q+=8}A.offset+=Q&(1<<A.extra)-1,Q>>>=A.extra,q-=A.extra,A.back+=A.extra}if(A.offset>A.dmax){L.msg="invalid distance too far back",A.mode=30;break}A.mode=25;case 25:if(re===0)break e;if(ne=De-re,A.offset>ne){if((ne=A.offset-ne)>A.whave&&A.sane){L.msg="invalid distance too far back",A.mode=30;break}Ze=ne>A.wnext?(ne-=A.wnext,A.wsize-ne):A.wnext-ne,ne>A.length&&(ne=A.length),yt=A.window}else yt=He,Ze=ze-A.offset,ne=A.length;for(re<ne&&(ne=re),re-=ne,A.length-=ne;He[ze++]=yt[Ze++],--ne;);A.length===0&&(A.mode=21);break;case 26:if(re===0)break e;He[ze++]=A.length,re--,A.mode=21;break;case 27:if(A.wrap){for(;q<32;){if(me===0)break e;me--,Q|=le[ge++]<<q,q+=8}if(De-=re,L.total_out+=De,A.total+=De,De&&(L.adler=A.check=A.flags?s(A.check,He,De,ze-De):o(A.check,He,De,ze-De)),De=re,(A.flags?Q:E(Q))!==A.check){L.msg="incorrect data check",A.mode=30;break}q=Q=0}A.mode=28;case 28:if(A.wrap&&A.flags){for(;q<32;){if(me===0)break e;me--,Q+=le[ge++]<<q,q+=8}if(Q!==(4294967295&A.total)){L.msg="incorrect length check",A.mode=30;break}q=Q=0}A.mode=29;case 29:ue=1;break e;case 30:ue=-3;break e;case 31:return-4;case 32:default:return l}return L.next_out=ze,L.avail_out=re,L.next_in=ge,L.avail_in=me,A.hold=Q,A.bits=q,(A.wsize||De!==L.avail_out&&A.mode<30&&(A.mode<27||te!==4))&&Ae(L,L.output,L.next_out,De-L.avail_out)?(A.mode=31,-4):(Be-=L.avail_in,De-=L.avail_out,L.total_in+=Be,L.total_out+=De,A.total+=De,A.wrap&&De&&(L.adler=A.check=A.flags?s(A.check,He,De,L.next_out-De):o(A.check,He,De,L.next_out-De)),L.data_type=A.bits+(A.last?64:0)+(A.mode===12?128:0)+(A.mode===20||A.mode===15?256:0),(Be==0&&De===0||te===4)&&ue===m&&(ue=-5),ue)},e.inflateEnd=function(L){if(!L||!L.state)return l;var te=L.state;return te.window&&(te.window=null),L.state=null,m},e.inflateGetHeader=function(L,te){var A;return L&&L.state?(2&(A=L.state).wrap)==0?l:((A.head=te).done=!1,m):l},e.inflateSetDictionary=function(L,te){var A,le=te.length;return L&&L.state?(A=L.state).wrap!==0&&A.mode!==11?l:A.mode===11&&o(1,te,le,0)!==A.check?-3:Ae(L,te,le,le)?(A.mode=31,-4):(A.havedict=1,m):l},e.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./inffast":48,"./inftrees":50}],50:[function(i,t,e){"use strict";var r=i("../utils/common"),o=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],s=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],n=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],a=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];t.exports=function(c,d,m,l,f,g,T,E){var y,v,M,w,H,B,P,$,de,Ae=E.bits,L=0,te=0,A=0,le=0,He=0,ge=0,ze=0,me=0,re=0,Q=0,q=null,Be=0,De=new r.Buf16(16),ne=new r.Buf16(16),Ze=null,yt=0;for(L=0;L<=15;L++)De[L]=0;for(te=0;te<l;te++)De[d[m+te]]++;for(He=Ae,le=15;1<=le&&De[le]===0;le--);if(le<He&&(He=le),le===0)return f[g++]=20971520,f[g++]=20971520,E.bits=1,0;for(A=1;A<le&&De[A]===0;A++);for(He<A&&(He=A),L=me=1;L<=15;L++)if(me<<=1,(me-=De[L])<0)return-1;if(0<me&&(c===0||le!==1))return-1;for(ne[1]=0,L=1;L<15;L++)ne[L+1]=ne[L]+De[L];for(te=0;te<l;te++)d[m+te]!==0&&(T[ne[d[m+te]]++]=te);if(B=c===0?(q=Ze=T,19):c===1?(q=o,Be-=257,Ze=s,yt-=257,256):(q=n,Ze=a,-1),L=A,H=g,ze=te=Q=0,M=-1,w=(re=1<<(ge=He))-1,c===1&&852<re||c===2&&592<re)return 1;for(;;){for(P=L-ze,de=T[te]<B?($=0,T[te]):T[te]>B?($=Ze[yt+T[te]],q[Be+T[te]]):($=96,0),y=1<<L-ze,A=v=1<<ge;f[H+(Q>>ze)+(v-=y)]=P<<24|$<<16|de|0,v!==0;);for(y=1<<L-1;Q&y;)y>>=1;if(y!==0?(Q&=y-1,Q+=y):Q=0,te++,--De[L]==0){if(L===le)break;L=d[m+T[te]]}if(He<L&&(Q&w)!==M){for(ze===0&&(ze=He),H+=A,me=1<<(ge=L-ze);ge+ze<le&&!((me-=De[ge+ze])<=0);)ge++,me<<=1;if(re+=1<<ge,c===1&&852<re||c===2&&592<re)return 1;f[M=Q&w]=He<<24|ge<<16|H-g|0}}return Q!==0&&(f[H+Q]=L-ze<<24|64<<16|0),E.bits=He,0}},{"../utils/common":41}],51:[function(i,t,e){"use strict";t.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],52:[function(i,t,e){"use strict";var r=i("../utils/common"),o=0,s=1;function n(O){for(var F=O.length;0<=--F;)O[F]=0}var a=0,c=29,d=256,m=d+1+c,l=30,f=19,g=2*m+1,T=15,E=16,y=7,v=256,M=16,w=17,H=18,B=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],P=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],$=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],de=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],Ae=new Array(2*(m+2));n(Ae);var L=new Array(2*l);n(L);var te=new Array(512);n(te);var A=new Array(256);n(A);var le=new Array(c);n(le);var He,ge,ze,me=new Array(l);function re(O,F,pe,fe,X){this.static_tree=O,this.extra_bits=F,this.extra_base=pe,this.elems=fe,this.max_length=X,this.has_stree=O&&O.length}function Q(O,F){this.dyn_tree=O,this.max_code=0,this.stat_desc=F}function q(O){return O<256?te[O]:te[256+(O>>>7)]}function Be(O,F){O.pending_buf[O.pending++]=255&F,O.pending_buf[O.pending++]=F>>>8&255}function De(O,F,pe){O.bi_valid>E-pe?(O.bi_buf|=F<<O.bi_valid&65535,Be(O,O.bi_buf),O.bi_buf=F>>E-O.bi_valid,O.bi_valid+=pe-E):(O.bi_buf|=F<<O.bi_valid&65535,O.bi_valid+=pe)}function ne(O,F,pe){De(O,pe[2*F],pe[2*F+1])}function Ze(O,F){for(var pe=0;pe|=1&O,O>>>=1,pe<<=1,0<--F;);return pe>>>1}function yt(O,F,pe){var fe,X,oe=new Array(T+1),xe=0;for(fe=1;fe<=T;fe++)oe[fe]=xe=xe+pe[fe-1]<<1;for(X=0;X<=F;X++){var Z=O[2*X+1];Z!==0&&(O[2*X]=Ze(oe[Z]++,Z))}}function ae(O){var F;for(F=0;F<m;F++)O.dyn_ltree[2*F]=0;for(F=0;F<l;F++)O.dyn_dtree[2*F]=0;for(F=0;F<f;F++)O.bl_tree[2*F]=0;O.dyn_ltree[2*v]=1,O.opt_len=O.static_len=0,O.last_lit=O.matches=0}function at(O){8<O.bi_valid?Be(O,O.bi_buf):0<O.bi_valid&&(O.pending_buf[O.pending++]=O.bi_buf),O.bi_buf=0,O.bi_valid=0}function Lt(O,F,pe,fe){var X=2*F,oe=2*pe;return O[X]<O[oe]||O[X]===O[oe]&&fe[F]<=fe[pe]}function wt(O,F,pe){for(var fe=O.heap[pe],X=pe<<1;X<=O.heap_len&&(X<O.heap_len&&Lt(F,O.heap[X+1],O.heap[X],O.depth)&&X++,!Lt(F,fe,O.heap[X],O.depth));)O.heap[pe]=O.heap[X],pe=X,X<<=1;O.heap[pe]=fe}function we(O,F,pe){var fe,X,oe,xe,Z=0;if(O.last_lit!==0)for(;fe=O.pending_buf[O.d_buf+2*Z]<<8|O.pending_buf[O.d_buf+2*Z+1],X=O.pending_buf[O.l_buf+Z],Z++,fe===0?ne(O,X,F):(ne(O,(oe=A[X])+d+1,F),(xe=B[oe])!==0&&De(O,X-=le[oe],xe),ne(O,oe=q(--fe),pe),(xe=P[oe])!==0&&De(O,fe-=me[oe],xe)),Z<O.last_lit;);ne(O,v,F)}function fr(O,F){var pe,fe,X,oe=F.dyn_tree,xe=F.stat_desc.static_tree,Z=F.stat_desc.has_stree,$e=F.stat_desc.elems,b=-1;for(O.heap_len=0,O.heap_max=g,pe=0;pe<$e;pe++)oe[2*pe]!==0?(O.heap[++O.heap_len]=b=pe,O.depth[pe]=0):oe[2*pe+1]=0;for(;O.heap_len<2;)oe[2*(X=O.heap[++O.heap_len]=b<2?++b:0)]=1,O.depth[X]=0,O.opt_len--,Z&&(O.static_len-=xe[2*X+1]);for(F.max_code=b,pe=O.heap_len>>1;1<=pe;pe--)wt(O,oe,pe);for(X=$e;pe=O.heap[1],O.heap[1]=O.heap[O.heap_len--],wt(O,oe,1),fe=O.heap[1],O.heap[--O.heap_max]=pe,O.heap[--O.heap_max]=fe,oe[2*X]=oe[2*pe]+oe[2*fe],O.depth[X]=(O.depth[pe]>=O.depth[fe]?O.depth[pe]:O.depth[fe])+1,oe[2*pe+1]=oe[2*fe+1]=X,O.heap[1]=X++,wt(O,oe,1),2<=O.heap_len;);O.heap[--O.heap_max]=O.heap[1],function(it,vt){var Mr,xr,Ft,G,gr,Di,lr=vt.dyn_tree,pt=vt.max_code,_n=vt.stat_desc.static_tree,kr=vt.stat_desc.has_stree,ei=vt.stat_desc.extra_bits,vr=vt.stat_desc.extra_base,Oi=vt.stat_desc.max_length,Mi=0;for(G=0;G<=T;G++)it.bl_count[G]=0;for(lr[2*it.heap[it.heap_max]+1]=0,Mr=it.heap_max+1;Mr<g;Mr++)Oi<(G=lr[2*lr[2*(xr=it.heap[Mr])+1]+1]+1)&&(G=Oi,Mi++),lr[2*xr+1]=G,pt<xr||(it.bl_count[G]++,gr=0,vr<=xr&&(gr=ei[xr-vr]),Di=lr[2*xr],it.opt_len+=Di*(G+gr),kr&&(it.static_len+=Di*(_n[2*xr+1]+gr)));if(Mi!==0){do{for(G=Oi-1;it.bl_count[G]===0;)G--;it.bl_count[G]--,it.bl_count[G+1]+=2,it.bl_count[Oi]--,Mi-=2}while(0<Mi);for(G=Oi;G!==0;G--)for(xr=it.bl_count[G];xr!==0;)pt<(Ft=it.heap[--Mr])||(lr[2*Ft+1]!==G&&(it.opt_len+=(G-lr[2*Ft+1])*lr[2*Ft],lr[2*Ft+1]=G),xr--)}}(O,F),yt(oe,b,O.bl_count)}function S(O,F,pe){var fe,X,oe=-1,xe=F[1],Z=0,$e=7,b=4;for(xe===0&&($e=138,b=3),F[2*(pe+1)+1]=65535,fe=0;fe<=pe;fe++)X=xe,xe=F[2*(fe+1)+1],++Z<$e&&X===xe||(Z<b?O.bl_tree[2*X]+=Z:X!==0?(X!==oe&&O.bl_tree[2*X]++,O.bl_tree[2*M]++):Z<=10?O.bl_tree[2*w]++:O.bl_tree[2*H]++,oe=X,b=(Z=0)===xe?($e=138,3):X===xe?($e=6,3):($e=7,4))}function ue(O,F,pe){var fe,X,oe=-1,xe=F[1],Z=0,$e=7,b=4;for(xe===0&&($e=138,b=3),fe=0;fe<=pe;fe++)if(X=xe,xe=F[2*(fe+1)+1],!(++Z<$e&&X===xe)){if(Z<b)for(;ne(O,X,O.bl_tree),--Z!=0;);else X!==0?(X!==oe&&(ne(O,X,O.bl_tree),Z--),ne(O,M,O.bl_tree),De(O,Z-3,2)):Z<=10?(ne(O,w,O.bl_tree),De(O,Z-3,3)):(ne(O,H,O.bl_tree),De(O,Z-11,7));oe=X,b=(Z=0)===xe?($e=138,3):X===xe?($e=6,3):($e=7,4)}}n(me);var Y=!1;function x(O,F,pe,fe){De(O,(a<<1)+(fe?1:0),3),function(X,oe,xe,Z){at(X),Z&&(Be(X,xe),Be(X,~xe)),r.arraySet(X.pending_buf,X.window,oe,xe,X.pending),X.pending+=xe}(O,F,pe,!0)}e._tr_init=function(O){Y||(function(){var F,pe,fe,X,oe,xe=new Array(T+1);for(X=fe=0;X<c-1;X++)for(le[X]=fe,F=0;F<1<<B[X];F++)A[fe++]=X;for(A[fe-1]=X,X=oe=0;X<16;X++)for(me[X]=oe,F=0;F<1<<P[X];F++)te[oe++]=X;for(oe>>=7;X<l;X++)for(me[X]=oe<<7,F=0;F<1<<P[X]-7;F++)te[256+oe++]=X;for(pe=0;pe<=T;pe++)xe[pe]=0;for(F=0;F<=143;)Ae[2*F+1]=8,F++,xe[8]++;for(;F<=255;)Ae[2*F+1]=9,F++,xe[9]++;for(;F<=279;)Ae[2*F+1]=7,F++,xe[7]++;for(;F<=287;)Ae[2*F+1]=8,F++,xe[8]++;for(yt(Ae,m+1,xe),F=0;F<l;F++)L[2*F+1]=5,L[2*F]=Ze(F,5);He=new re(Ae,B,d+1,m,T),ge=new re(L,P,0,l,T),ze=new re(new Array(0),$,0,f,y)}(),Y=!0),O.l_desc=new Q(O.dyn_ltree,He),O.d_desc=new Q(O.dyn_dtree,ge),O.bl_desc=new Q(O.bl_tree,ze),O.bi_buf=0,O.bi_valid=0,ae(O)},e._tr_stored_block=x,e._tr_flush_block=function(O,F,pe,fe){var X,oe,xe=0;0<O.level?(O.strm.data_type===2&&(O.strm.data_type=function(Z){var $e,b=4093624447;for($e=0;$e<=31;$e++,b>>>=1)if(1&b&&Z.dyn_ltree[2*$e]!==0)return o;if(Z.dyn_ltree[18]!==0||Z.dyn_ltree[20]!==0||Z.dyn_ltree[26]!==0)return s;for($e=32;$e<d;$e++)if(Z.dyn_ltree[2*$e]!==0)return s;return o}(O)),fr(O,O.l_desc),fr(O,O.d_desc),xe=function(Z){var $e;for(S(Z,Z.dyn_ltree,Z.l_desc.max_code),S(Z,Z.dyn_dtree,Z.d_desc.max_code),fr(Z,Z.bl_desc),$e=f-1;3<=$e&&Z.bl_tree[2*de[$e]+1]===0;$e--);return Z.opt_len+=3*($e+1)+5+5+4,$e}(O),X=O.opt_len+3+7>>>3,(oe=O.static_len+3+7>>>3)<=X&&(X=oe)):X=oe=pe+5,pe+4<=X&&F!==-1?x(O,F,pe,fe):O.strategy===4||oe===X?(De(O,2+(fe?1:0),3),we(O,Ae,L)):(De(O,4+(fe?1:0),3),function(Z,$e,b,it){var vt;for(De(Z,$e-257,5),De(Z,b-1,5),De(Z,it-4,4),vt=0;vt<it;vt++)De(Z,Z.bl_tree[2*de[vt]+1],3);ue(Z,Z.dyn_ltree,$e-1),ue(Z,Z.dyn_dtree,b-1)}(O,O.l_desc.max_code+1,O.d_desc.max_code+1,xe+1),we(O,O.dyn_ltree,O.dyn_dtree)),ae(O),fe&&at(O)},e._tr_tally=function(O,F,pe){return O.pending_buf[O.d_buf+2*O.last_lit]=F>>>8&255,O.pending_buf[O.d_buf+2*O.last_lit+1]=255&F,O.pending_buf[O.l_buf+O.last_lit]=255&pe,O.last_lit++,F===0?O.dyn_ltree[2*pe]++:(O.matches++,F--,O.dyn_ltree[2*(A[pe]+d+1)]++,O.dyn_dtree[2*q(F)]++),O.last_lit===O.lit_bufsize-1},e._tr_align=function(O){De(O,2,3),ne(O,v,Ae),function(F){F.bi_valid===16?(Be(F,F.bi_buf),F.bi_buf=0,F.bi_valid=0):8<=F.bi_valid&&(F.pending_buf[F.pending++]=255&F.bi_buf,F.bi_buf>>=8,F.bi_valid-=8)}(O)}},{"../utils/common":41}],53:[function(i,t,e){"use strict";t.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(i,t,e){(function(r){(function(o,s){"use strict";if(!o.setImmediate){var n,a,c,d,m=1,l={},f=!1,g=o.document,T=Object.getPrototypeOf&&Object.getPrototypeOf(o);T=T&&T.setTimeout?T:o,n={}.toString.call(o.process)==="[object process]"?function(M){process.nextTick(function(){y(M)})}:function(){if(o.postMessage&&!o.importScripts){var M=!0,w=o.onmessage;return o.onmessage=function(){M=!1},o.postMessage("","*"),o.onmessage=w,M}}()?(d="setImmediate$"+Math.random()+"$",o.addEventListener?o.addEventListener("message",v,!1):o.attachEvent("onmessage",v),function(M){o.postMessage(d+M,"*")}):o.MessageChannel?((c=new MessageChannel).port1.onmessage=function(M){y(M.data)},function(M){c.port2.postMessage(M)}):g&&"onreadystatechange"in g.createElement("script")?(a=g.documentElement,function(M){var w=g.createElement("script");w.onreadystatechange=function(){y(M),w.onreadystatechange=null,a.removeChild(w),w=null},a.appendChild(w)}):function(M){setTimeout(y,0,M)},T.setImmediate=function(M){typeof M!="function"&&(M=new Function(""+M));for(var w=new Array(arguments.length-1),H=0;H<w.length;H++)w[H]=arguments[H+1];var B={callback:M,args:w};return l[m]=B,n(m),m++},T.clearImmediate=E}function E(M){delete l[M]}function y(M){if(f)setTimeout(y,0,M);else{var w=l[M];if(w){f=!0;try{(function(H){var B=H.callback,P=H.args;switch(P.length){case 0:B();break;case 1:B(P[0]);break;case 2:B(P[0],P[1]);break;case 3:B(P[0],P[1],P[2]);break;default:B.apply(s,P)}})(w)}finally{E(M),f=!1}}}}function v(M){M.source===o&&typeof M.data=="string"&&M.data.indexOf(d)===0&&y(+M.data.slice(d.length))}})(typeof self=="undefined"?r===void 0?this:r:self)}).call(this,typeof global!="undefined"?global:typeof self!="undefined"?self:typeof window!="undefined"?window:{})},{}]},{},[10])(10)})});var Cg=(re=>(re[re.INVALID_PARAMETER=4096]="INVALID_PARAMETER",re[re.INVALID_OPERATION=4097]="INVALID_OPERATION",re[re.NOT_SUPPORTED=4098]="NOT_SUPPORTED",re[re.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",re[re.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",re[re.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",re[re.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",re[re.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",re[re.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",re[re.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",re[re.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",re[re.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",re[re.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",re[re.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",re[re.CLIENT_BANNED=16448]="CLIENT_BANNED",re[re.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",re[re.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",re[re.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",re[re.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",re[re.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",re[re.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",re[re.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",re[re.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",re[re.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",re[re.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",re[re.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",re[re.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",re[re.API_CALL_ABORTED=16461]="API_CALL_ABORTED",re[re.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",re[re.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",re[re.SWITCH_ROOM_FAILED=16464]="SWITCH_ROOM_FAILED",re[re.VIDEO_ENCODE_FAILED=16465]="VIDEO_ENCODE_FAILED",re[re.AUDIO_ENCODE_FAILED=16466]="AUDIO_ENCODE_FAILED",re[re.UNKNOWN=65535]="UNKNOWN",re))(Cg||{}),Te=Cg;var nS=function(i){for(let t in Te)if(Te[t]===i)return t;return"UNKNOWN"},Ma=class extends Error{constructor({name:e="RtcError",message:r,code:o=Te.UNKNOWN,extraCode:s=0,constraint:n}){let a=`<${nS(o)} 0x${o.toString(16)}>`,c=`${r}${n?` constraint: ${n}`:""}${r!=null&&r.includes(a)?"":` ${a}`}`;super(c);p(this,"code");p(this,"extraCode");p(this,"message");p(this,"originMessage");p(this,"name");p(this,"constraint");this.code=o,this.extraCode=s,this.name=e,this.message=c,this.constraint=n,this.originMessage=r}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},Me=Ma;var wg=0;var Ng=function(){return wg},to=function(){return Date.now()+wg},kd=function(){let i=new Date;return i.setTime(to()),i.toLocaleString()},Rn=function(i){let t=String(i.getMilliseconds());return"padStart"in String.prototype&&(t=t.toString().padStart(3,"0")),`${i.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")}:${t}`};var Vi={};eo(Vi,{REPORT_TYPE:()=>$n,buildSSOPackage:()=>so,bytes2ms:()=>Hg,calculateScaleResolutionDownNumber:()=>eu,concatArrayBuffers:()=>e_,convertObjectNumberToInt:()=>Wa,copyProperties:()=>Fg,deepClone:()=>Ns,deepCloneBasic:()=>Xd,deepMerge:()=>Ei,delay:()=>Ti,fibonacci:()=>Ds,formatedTime:()=>Qd,getConstructorName:()=>Ln,getContainerFromElement:()=>Yg,getEnv:()=>Ug,getFirst16Bits:()=>r_,getInternalVersion:()=>Jg,getLast16Bits:()=>t_,getLoggerUrl:()=>oo,getMediaStreamTrackInfo:()=>Kd,getMuteStateFromFlag:()=>Ms,getNetworkType:()=>kn,getNumNetworkType:()=>Jd,getReconnectionTimeout:()=>Gg,getStringByteLength:()=>Zg,getTurnServer:()=>Qg,getUint32Version:()=>Yd,getValueType:()=>Xt,getViewListFromView:()=>Vn,glog:()=>$a,ipv4ToUint32:()=>Un,isArray:()=>Gt,isAudioWorkletSupported:()=>qg,isBoolean:()=>Nt,isConstructor:()=>Os,isEmpty:()=>Pn,isFunction:()=>Rt,isLangChinese:()=>_i,isMediaStreamTrack:()=>zg,isNumber:()=>ft,isObject:()=>Xr,isOverseaSdkAppId:()=>si,isPlainObject:()=>Nr,isPortrait:()=>im,isPromise:()=>$o,isRemoteTrack:()=>jg,isRotate90Or270:()=>Jr,isSetSinkIdSupported:()=>Xg,isString:()=>nt,isUndefined:()=>z,loadImage:()=>Bn,loadVideo:()=>Kg,ms2bytes:()=>Wg,ms2samples:()=>rm,normalizeUrl:()=>xs,performanceNow:()=>Xe,promiseAny:()=>Fa,samples2ms:()=>tm,setNetworkTypeFromWebRTC:()=>$g,stringify:()=>oi,stringifyIncludeValue:()=>Ha,throttlePromise:()=>Zd});var zh={};eo(zh,{AUDIO_MUTE_BIT:()=>Fd,AUDIO_STAT_BIT:()=>Nn,AUX_STAT_BIT:()=>Pa,AUX_STREAM_MSID:()=>ES,BACKEND_ENV:()=>$d,BASE_DOC_URL:()=>Br,BASE_HOST:()=>Dg,CAPABILITIES_KEYS:()=>Gd,CLASS_NAME:()=>HS,CLOUD_CONSOLE_URL:()=>uS,CROSS_ROOM_BIT:()=>gS,DATA_FREEZE_TIMING:()=>Wd,DOC_BILLING_CN:()=>Ld,DOC_BILLING_OVERSEA:()=>Pd,DOC_URL:()=>lS,DTLS_STATE_UNKNOWN:()=>wS,ENV_NAME:()=>ro,EXCHANGE_SDP_TIMEOUT:()=>kS,IS_WORKER:()=>Cn,IS_WORKLET:()=>xa,KIBANA_EVENT:()=>ii,LOCAL_STREAM_PUBLISH_STATE:()=>Mg,LOGGER_CMD_TYPE:()=>Bo,LOGGER_DOMAIN:()=>Vh,LOGGER_DOMAIN_OVERSEA:()=>Bh,LOG_LEVEL:()=>ri,LOG_LEVEL_NAME:()=>GS,MAIN_STREAM_MSID:()=>_S,MAX_RTT:()=>Va,MICROPHONE_COMMUNICATIONS:()=>WS,MICROPHONE_DEFAULT:()=>ws,MUTE_ALL_BIT:()=>fS,NAME:()=>j,NETWORK_TYPE:()=>Rs,NOT_SUPPORTED_H264:()=>PS,PAUSED_RETRY_COUNT:()=>Cs,PEERCONNECTION_CONNECTING_TIMEOUT:()=>$S,PEER_CONNECTION_STATE:()=>NS,PEER_LEAVE_REASON:()=>xg,RECOVER_CAPTURE_INTERVAL:()=>Dn,REMOTE_STREAM_TYPE_AUX:()=>yS,REMOTE_STREAM_TYPE_MAIN:()=>TS,RENDER_FREEZE_TIMING:()=>US,SCHEDULE_DOMAIN:()=>io,SCHEDULE_TIMEOUT:()=>FS,SDP_SEMANTICS_PLAN_B:()=>LS,SDP_SEMANTICS_UNIFIED_PLAN:()=>Gh,SECOND_HOST:()=>cS,SIGNAL_PING_PONG_INTERVAL:()=>mS,SIGNAL_PING_TIMEOUT:()=>hS,SIGNAL_RECONNECTION_COUNT:()=>OS,SMALL_STAT_BIT:()=>Hh,SPEAKER_DEFAULT:()=>Ua,STORAGE_EXPIRES_TIME:()=>Ud,STREAM_TYPE_BIG:()=>VS,STREAM_TYPE_SMALL:()=>BS,SUBSCRIBE_SMALL_RETRY_COUNT:()=>zS,SYNC_USER_LIST_INTERVAL:()=>MS,Scene:()=>Pi,THIRD_HOST:()=>dS,TRANSPORT_DIRECTION:()=>pS,TRTC_ERROR_ASSISTANCE:()=>$h,TRTC_QUALITY_BAD:()=>vS,TRTC_QUALITY_DISCONNECTED:()=>CS,TRTC_QUALITY_EXCELLENT:()=>IS,TRTC_QUALITY_GOOD:()=>bS,TRTC_QUALITY_POOR:()=>AS,TRTC_QUALITY_UNKNOWN:()=>SS,TRTC_QUALITY_VERY_BAD:()=>RS,UPDATE_OFFER_TIMEOUT:()=>xS,VIDEO_MUTE_BIT:()=>Hd,VIDEO_STAT_BIT:()=>wn,audioProfileMap:()=>Vd,defaultBigVideoProfile:()=>La,defaultSmallVideoProfile:()=>Fh,getRetryCount:()=>DS,getScriptDir:()=>aS,innerVersion:()=>Ph,loggerProxy:()=>ka,screenProfileMap:()=>Bd,setLoggerProxy:()=>vs,setRetryCount:()=>Wh,setVersion:()=>Uh,version:()=>qt,videoProfileMap:()=>gi});var Ph="4.15.00.1600",qt="5.0.0";function Uh(i){qt=i;let[t,e,r]=i.split(".").map(o=>parseInt(o,10));Ph=`${t}.${Math.min(15,e)}.${Math.min(15,r)}.${e.toString().padStart(2,"0")}${r.toString().padStart(2,"0")}`}var Cn=typeof importScripts!="undefined",xa=typeof registerProcessor!="undefined",aS=()=>{let i=Cn?self.location.href:document.currentScript.src;return i.substring(0,i.lastIndexOf("/")+1)},ka="",vs=i=>ka=i,Dg="web.sdk.qcloud.com",cS="web.sdk.tencent.cn",dS="web.sdk.cloud.tencent.cn",uS="https://console.cloud.tencent.com/trtc",Br=`https://${Dg}/trtc/webrtc/doc`,lS=`${Br}/zh-cn/`,Ld="https://cloud.tencent.com/document/product/647/85386",Pd="https://trtc.io/document/56025",Vh="https://yun.tim.qq.com",Bh="https://apisgp.my-imcloud.com",$h="trtc_error_assistance",Bo={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},ro={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},ri=(n=>(n[n.TRACE=0]="TRACE",n[n.DEBUG=1]="DEBUG",n[n.INFO=2]="INFO",n[n.WARN=3]="WARN",n[n.ERROR=4]="ERROR",n[n.NONE=5]="NONE",n))(ri||{}),hS=18e3,mS=2e3,Rs={unknown:0,wifi:1,"4g":2,"3g":3,"2g":4,wired:5,"5g":6},Ud=7*24*3600*1e3,Vd={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}},gi={"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}},La=gi["480p_2"],Fh=gi["120p_2"],Bd={"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}},j={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"},pS={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},$d={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},Pi=(e=>(e.LIVE="live",e.RTC="rtc",e))(Pi||{}),wn=1,Hh=2,Pa=4,Nn=8,Fd=64,Hd=16,fS=112,gS=128,_S="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",ES="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",TS=j.MAIN,yS=j.AUXILIARY,SS=0,IS=1,bS=2,AS=3,vS=4,RS=5,CS=6,wS="unknown",NS={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},Og=1/0;function Wh(i){Og=i}function DS(){return Og}var OS=30,ii={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"},MS=1e4,xS=1e4,kS=1e4,Gh="unified-plan",LS="plan-b",PS=1028,Mg=(r=>(r[r.UNPUBLISH=-1]="UNPUBLISH",r[r.PUBLISHING=0]="PUBLISHING",r[r.PUBLISHED=1]="PUBLISHED",r))(Mg||{}),Wd=500,US=1e3,VS=j.BIG,BS=j.SMALL,$S=10*1e3,io={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"},FS=2e3,HS={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},Cs=5,ws="default",Ua=ws,WS="communications",GS=Object.keys(ri),xg=["normal leave","timeout leave","kick","role change"],zS=10,Dn=2e3,Gd=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],Va=10*1e3;var jS=function(i,t,e,r){function o(s){return s instanceof e?s:new e(function(n){n(s)})}return new(e||(e=Promise))(function(s,n){function a(m){try{d(r.next(m))}catch(l){n(l)}}function c(m){try{d(r.throw(m))}catch(l){n(l)}}function d(m){m.done?s(m.value):o(m.value).then(a,c)}d((r=r.apply(i,t||[])).next())})},jh=Symbol(32),qh=Symbol(16),Xh=Symbol(8),Ui=class{constructor(t){this.g=t,this.consumed=0,t&&(this.need=t.next().value)}setG(t){this.g=t,this.demand(t.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(t,e){return e&&this.consume(),this.need=t,this.flush()}read(t){return jS(this,void 0,void 0,function*(){return this.lastReadPromise&&(yield this.lastReadPromise),this.lastReadPromise=new Promise((e,r)=>{var o;this.reject=r,this.resolve=n=>{delete this.lastReadPromise,delete this.resolve,delete this.need,e(n)},this.demand(t,!0)||(o=this.pull)===null||o===void 0||o.call(this,t)})})}readU32(){return this.read(jh)}readU16(){return this.read(qh)}readU8(){return this.read(Xh)}close(){var t;this.g&&this.g.return(),this.buffer&&this.buffer.subarray(0,0),(t=this.reject)===null||t===void 0||t.call(this,new Error("EOF")),delete this.lastReadPromise}flush(){if(!this.buffer||!this.need)return;let t=null,e=this.buffer.subarray(this.consumed),r=0,o=s=>e.length<(r=s);if(typeof this.need=="number"){if(o(this.need))return;t=e.subarray(0,r)}else if(this.need===jh){if(o(4))return;t=e[0]<<24|e[1]<<16|e[2]<<8|e[3]}else if(this.need===qh){if(o(2))return;t=e[0]<<8|e[1]}else if(this.need===Xh){if(o(1))return;t=e[0]}else if("buffer"in this.need){if("byteOffset"in this.need){if(o(this.need.byteLength-this.need.byteOffset))return;new Uint8Array(this.need.buffer,this.need.byteOffset).set(e.subarray(0,r)),t=this.need}else if(this.g){this.g.throw(new Error("Unsupported type"));return}}else{if(o(this.need.byteLength))return;new Uint8Array(this.need).set(e.subarray(0,r)),t=this.need}return this.consumed+=r,this.g?this.demand(this.g.next(t).value,!0):this.resolve&&this.resolve(t),t}write(t){if(t instanceof Uint8Array?this.malloc(t.length).set(t):"buffer"in t?this.malloc(t.byteLength).set(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)):this.malloc(t.byteLength).set(new Uint8Array(t)),this.g||this.resolve)this.flush();else return new Promise(e=>this.pull=e)}writeU32(t){this.malloc(4).set([t>>24&255,t>>16&255,t>>8&255,t&255]),this.flush()}writeU16(t){this.malloc(2).set([t>>8&255,t&255]),this.flush()}writeU8(t){this.malloc(1)[0]=t,this.flush()}malloc(t){if(this.buffer){let e=this.buffer.length,r=e+t;if(r<=this.buffer.buffer.byteLength-this.buffer.byteOffset)this.buffer=new Uint8Array(this.buffer.buffer,this.buffer.byteOffset,r);else{let o=new Uint8Array(r);o.set(this.buffer),this.buffer=o}return this.buffer.subarray(e,r)}else return this.buffer=new Uint8Array(t),this.buffer}};Ui.U32=jh;Ui.U16=qh;Ui.U8=Xh;var qS=128,XS=127,B0=~XS,$0=Math.pow(2,31);function Jh(i){let t=new Ui;for(;i>=128;)t.malloc(1)[0]=i&255|qS,i>>>=7;return t.malloc(1)[0]=i&255,t.buffer||new Uint8Array(0)}function zd(i,t=0){let e=new Ui,r=t<<3;switch(typeof i){case"boolean":let o=e.malloc(2);o[0]=r,o[1]=i?1:0;break;case"number":e.malloc(1)[0]=r,e.write(Jh(i));break;case"string":e.malloc(1)[0]=r|2;let s=new TextEncoder().encode(i);e.write(Jh(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 Ui;if(Array.isArray(i))for(let c=0;c<i.length;c++){let d=zd(i[c],c+1);d&&a.write(d)}else{let c=1;for(let d in i){let m=zd(i[d],c++);m&&a.write(m)}}t===0?a.buffer&&e.write(a.buffer):(e.malloc(1)[0]=r|2,a.buffer&&(e.write(Jh(a.buffer.length)),e.write(a.buffer)))}return e.buffer||new Uint8Array(0)}var Ba=class{constructor(){p(this,"buffer");this.buffer=[]}get data(){return this.buffer}get length(){return this.buffer.length}writeInt32(t){this.buffer.push(t>>>24&255),this.buffer.push(t>>>16&255),this.buffer.push(t>>>8&255),this.buffer.push(t&255)}writeInt16(t){this.buffer.push(t>>>8&255),this.buffer.push(t&255)}writeByte(t){this.buffer.push(t&255)}writeBytes(t){for(let e=0;e<t.length;e++)this.buffer.push(t[e])}};function Qh(i,t,e){i[e]=t>>>24&255,i[e+1]=t>>>16&255,i[e+2]=t>>>8&255,i[e+3]=t&255}function wr(i,t){return i[t]<<24|i[t+1]<<16|i[t+2]<<8|i[t+3]}function Yh(i,t){return i[t]}function On(i,t,e){return new TextDecoder().decode(JS(i,t,e))}function JS(i,t,e){return i.slice(t,t+e)}var Zh=0,jd=2654435769,qd=16,em=4,Mn=2,xn=7;function QS(i,t,e,r="AVQualityReportSvc.C2S",o=2e3,s=2,n=30){return{version:o,encryption:s,d2:"",d2Len:0,uinType:n,uin:"",uinLen:0,reqHead:{seqNumber:e,appId:i,appidAtThird:new Uint8Array(0),a2:"",a2Len:0,serviceCmd:r,serviceCmdLen:0,cookie:"",cookieLen:0,imei:"",imeiLen:0,ksid:"",ksidLen:0,clientVersionInfo:"",clientVersionInfoLen:0},busiBuff:t}}function kg(i,t){let e=new Ba,r=QS(t,i,Zh);Zh=Zh+1&2147483647,e.writeInt32(0),e.writeInt32(r.version),e.writeByte(r.encryption);let o=new TextEncoder().encode(r.d2);e.writeInt32(o.length+4),o&&e.writeBytes(o),e.writeByte(r.uinType);let s=new TextEncoder().encode(r.uin);e.writeInt32(s.length+4),s.length&&e.writeBytes(s);let n=new Ba;n.writeInt32(0),n.writeInt32(r.reqHead.seqNumber),n.writeInt32(r.reqHead.appId),n.writeByte(r.reqHead.appId>>>24&255),n.writeByte(r.reqHead.appId>>>16&255),n.writeByte(r.reqHead.appId>>>8&255),n.writeByte(r.reqHead.appId&255);for(let M=4;M<16;M++)n.writeByte(0);let a=new TextEncoder().encode(r.reqHead.a2);n.writeInt32(a.length+4),a.length&&n.writeBytes(a);let c=new TextEncoder().encode(r.reqHead.serviceCmd);n.writeInt32(c.length+4),c.length&&n.writeBytes(c);let d=new TextEncoder().encode(r.reqHead.cookie);n.writeInt32(d.length+4),d.length&&n.writeBytes(d);let m=new TextEncoder().encode(r.reqHead.imei);n.writeInt32(m.length+4),m.length&&n.writeBytes(m);let l=new TextEncoder().encode(r.reqHead.ksid);n.writeInt32(l.length+4),l.length&&n.writeBytes(l);let f=new TextEncoder().encode(r.reqHead.clientVersionInfo);n.writeInt16(f.length+2),f.length&&n.writeBytes(f);let g=n.length;n.data[0]=g>>>24&255,n.data[1]=g>>>16&255,n.data[2]=g>>>8&255,n.data[3]=g&255,nt(i)&&(i=new TextEncoder().encode(i)),n.writeInt32(i.length+4),i.length&&n.writeBytes(i);let T=new Uint8Array(n.data),E=null;r.encryption===1?E=new TextEncoder().encode(r.uin):r.encryption===2&&(E=new Uint8Array(16)),E&&(T=YS(T,E)),e.writeBytes(T);let y=new Uint8Array(e.data),v=y.length;return y[0]=v>>>24&255,y[1]=v>>>16&255,y[2]=v>>>8&255,y[3]=v&255,y}function YS(i,t){let e=i.length,o=(e+1+Mn+xn)%8;o&&(o=8-o);let s=e+1+Mn+xn+o,n=new Uint8Array(s),a=0,c=new Uint8Array(8),d=new Uint8Array(8),m=new Uint8Array(8),l=0;c[0]=Math.floor(Math.random()*256)&248|o,l=1;for(let g=0;g<o;g++)c[l]=Math.floor(Math.random()*256)&255,l+=1;for(let g=0;g<Mn;)if(l<8&&(c[l]=Math.floor(Math.random()*256)&255,l+=1,g+=1),l===8){Kh(c,t,d,m,n,a),a+=8,l=0;for(let T=0;T<8;T++)m[T]=n[a-8+T]}let f=0;for(;f<e;)if(l<8&&(c[l]=i[f],l+=1,f+=1),l===8){Kh(c,t,d,m,n,a),a+=8,l=0;for(let g=0;g<8;g++)m[g]=n[a-8+g]}for(let g=0;g<xn;)if(l<8&&(c[l]=0,l+=1,g+=1),l===8){Kh(c,t,d,m,n,a),a+=8,l=0;for(let T=0;T<8;T++)m[T]=n[a-8+T]}return n}function Kh(i,t,e,r,o,s){for(let n=0;n<8;n++)i[n]^=r[n];ZS(i,t,o,s);for(let n=0;n<8;n++)o[s+n]^=e[n];for(let n=0;n<8;n++)e[n]=i[n]}function ZS(i,t,e,r){let o=wr(i,0),s=wr(i,4),n=[];for(let c=0;c<4;c++)n[c]=wr(t,c*4);let a=0;for(let c=0;c<qd;c++)a+=jd,a=a>>>0,o+=(s<<4)+n[0]^s+a^(s>>>5)+n[1],o=o>>>0,s+=(o<<4)+n[2]^o+a^(o>>>5)+n[3],s=s>>>0;Qh(e,o,r),Qh(e,s,r+4)}var Ug=function(){return new URLSearchParams(location.search).get("trtc_env")||""},si=i=>Number(i)<14e8,oo=function(i,t){let e;ka?e=ka:e=si(i)?Bh:Vh;let r=Math.floor(Math.random()*ki(2,31));return`${e}/v5/AVQualityReportSvc/C2S?random=${r}&sdkappid=${i}&cmdtype=${t}`},Vg="unknown";function kn(){eI();let{userAgent:i,connection:t}=navigator,e=(i.match(/NetType\/\S+/)||[])[0]||"";e=e.toLowerCase().replace("nettype/",""),e==="3gnet"&&(e="3g");let r=t&&t.type&&t.type.toLowerCase(),o=t&&t.effectiveType&&t.effectiveType.toLowerCase();return o==="slow-2"&&(o="2g"),r?Bg(r,o):Vg}function KS(){se.warn("netType changed",kn())}var Lg=!1;function eI(){var i;Lg||(Lg=!0,(i=navigator.connection)==null||i.addEventListener("typechange",KS))}function Bg(i,t){if(Rs[i])return i;switch(i){case"cellular":case"wimax":return t||"unknown";case"ethernet":return"wired";case"none":case"other":default:return"unknown"}}function $g(i){Vg=Bg(i)}function Jd(){return Rs[kn()]}function Fg(i,t){for(let e of Reflect.ownKeys(t))if(e!=="constructor"&&e!=="prototype"&&e!=="name"){let r=Object.getOwnPropertyDescriptor(t,e)||"";Object.defineProperty(i,e,r)}return i}function Hg(i,t=48e3){return tm(i/4,t)}function tm(i,t=48e3){return i*1e3/t}function Wg(i,t=48e3){return rm(i,t)*4}function rm(i,t=48e3){return i*t/1e3}var $a=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},_i=()=>{let i=navigator.language;return i=i.substring(0,2),i==="zh"},Nr=function(i){if(!i||typeof i!="object"||Object.prototype.toString.call(i)!="[object Object]")return!1;let t=Object.getPrototypeOf(i);if(t===null)return!0;let e=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return typeof e=="function"&&e instanceof e&&Function.prototype.toString.call(e)===Function.prototype.toString.call(Object)};function Ds(i,t=1,e=1){return i<=1?e:Ds(i-1,e,t+e)}function Gg(i){return i>8?30*1e3:Ds(i)*1e3}function Xt(i){return Reflect.apply(Object.prototype.toString,i,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var Rt=i=>typeof i=="function",z=i=>typeof i=="undefined",nt=i=>typeof i=="string",ft=i=>typeof i=="number",Nt=i=>typeof i=="boolean",Xr=i=>Xt(i)==="object",Gt=i=>Xt(i)==="array",zg=i=>Xt(i)==="MediaStreamTrack".toLowerCase(),jg=i=>i.isRemote,$o=i=>Xt(i)==="promise",Os=i=>Rt(i)&&i.prototype.constructor===i,Ln=i=>Os(i)?i.prototype.constructor.name:"",qg=typeof AudioWorkletNode!="undefined",Xg=typeof HTMLMediaElement!="undefined"&&"setSinkId"in HTMLMediaElement.prototype;function Fa(i){return new Promise((t,e)=>{let r=[];i.forEach(o=>{o.then(t).catch(s=>{r.push(s),r.length===i.length&&e(r)})})})}function Xe(){return!performance||!performance.now?Date.now():Math.floor(performance.now())}var Pg=i=>+i<10?`0${i}`:i,Jg=i=>{let t=i.match(/^\d+\.\d+\.\d+/)[0];if(!t)return i;let e=t.split("."),r=Pg(e[1])+Pg(e[2]);return e[1]-15>0&&(e[1]="15"),e[2]-15>0&&(e[2]="15"),`${e.join(".")}.${r}`},tI=Object.prototype.hasOwnProperty,{toString:K0}=Object.prototype;function Pn(i){if(i==null)return!0;if(typeof i=="boolean")return!1;if(typeof i=="number")return i===0;if(typeof i=="string"||typeof i=="function"||Array.isArray(i))return i.length===0;if(i instanceof Error)return i.message==="";if(Nr(i))switch(Object.prototype.toString.call(i)){case"[object File]":case"[object Map]":case"[object Set]":return i.size===0;case"[object Object]":{for(let t in i)if(tI.call(i,t))return!1;return!0}}return!1}function Ms(i,t){return{userId:t,hasAudio:!!(i&Nn),hasVideo:!!(i&wn),hasAuxiliary:!!(i&Pa),hasSmall:!!(i&Hh),audioMuted:!!(i&Fd),videoMuted:!!(i&Hd),audioAvailable:!!(i&Nn)&&!(i&Fd),videoAvailable:!!(i&wn)&&!(i&Hd)}}function Qg(i){let t={urls:i.url.startsWith("turn:")||i.url.startsWith("turns:")?i.url:`turn:${i.url}`};return!z(i.username)&&!z(i.credential)&&(t.username=i.username,t.credential=i.credential,t.credentialType="password",z(i.credentialType)||(t.credentialType=i.credentialType)),t}function Un(i,t=!0){if(!nt(i))return 0;let e=i.split(".");return t?(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(i,t,e,r){if(!(Xr(i)&&Xr(t)))return 0;let o=0,s=Object.keys(t),n;for(let a=0,c=s.length;a<c;a++)if(n=s[a],!(z(t[n])||e&&e.includes(n)))if(Xr(i[n])&&Xr(t[n]))o+=Ei(i[n],t[n],e,r);else{if(r&&r.includes(t[n]))continue;i[n]!==t[n]&&(i[n]=Ns(t[n]),o+=1)}return o};function Ns(i){if(Gt(i)){let t=[];return i.forEach((e,r)=>{t[r]=Ns(e)}),t}if(Xr(i)){let t={};return Object.keys(i).forEach(e=>{t[e]=Ns(i[e])}),t}return i}var Vn=i=>{let t=[];if(Gt(i))t=[...i];else if(nt(i)){let e=document.getElementById(i);e&&t.push(e)}else i&&t.push(i);return t},Yg=i=>nt(i)?document.getElementById(i):i,rI=i=>{let t=c=>c<10?`0${c}`:`${c}`,e=i.getFullYear(),r=i.getMonth()+1,o=i.getDate(),s=t(i.getHours()),n=t(i.getMinutes()),a=t(i.getSeconds());return`${e}/${r}/${o} ${s}:${n}:${a}`},Qd=()=>rI(new Date);function oi(i,{keysToInclude:t,keysToExclude:e}){try{if(Gt(i))return`[${i.map(n=>oi(n,{keysToInclude:t,keysToExclude:e})).join(",")}]`;if(!Nr(i)||!Gt(t)&&!Gt(e))return JSON.stringify(i);let r={},o=new Set(t),s=new Set(e);return Object.keys(i).forEach(n=>{(s.size===0&&o.has(n)||o.size===0&&!s.has(n))&&(r[n]=Nr(i[n])||Gt(i[n])?JSON.parse(oi(i[n],{keysToExclude:e,keysToInclude:t})):i[n])}),JSON.stringify(r)}catch(r){return"{}"}}function Ha(i,t=!1){let e=[];return Object.keys(i).forEach(r=>{t===i[r]&&e.push(r)}),oi(i,{keysToInclude:e})}function Zg(i){return i.replace(/[\u4e00-\u9fa5]/g,"aa").length}var im=()=>{var i,t,e,r;return(i=window.screen)!=null&&i.orientation?!!((r=(e=(t=window.screen)==null?void 0:t.orientation)==null?void 0:e.type)!=null&&r.includes("portrait")):window.orientation===0||window.orientation===180},Bn=i=>D(void 0,null,function*(){return new Promise((t,e)=>{let r;if(nt(i))r=new Image,r.crossOrigin="anonymous",r.src=i;else if(r=i,r.complete){t(r);return}r.onload=()=>t(r),r.onerror=()=>{e(new Me({code:Te.INVALID_PARAMETER,message:`load image failed, url: ${i}`}))}})}),Yd=i=>{let t=i.split(".");return+t[0]<<24|+t[1]<<16|+t[2]<<8|+t[3]<<0},Wa=i=>(Object.keys(i).forEach(t=>{ft(i[t])&&(t.startsWith("uint")||t.startsWith("int"))?i[t]=Math.floor(i[t]):(Nr(i[t])||Gt(i[t]))&&Wa(i[t])}),i);function Ti(i,t){return new Promise(e=>{let r=setTimeout(e,i);t&&t(r)})}function Zd(i,t){let e=null;return function(...r){return e||(e=i.apply(t||this,r),e.finally(()=>e=null),e)}}function xs(i){return i.replace(/(^|[^:])\/{2,}/g,"$1/")}function Kd(i){var t;try{let{width:e,height:r,frameRate:o,sampleRate:s,sampleSize:n,channelCount:a}=(t=i.getSettings)==null?void 0:t.call(i),c=i.kind===j.AUDIO?`${s}x${n}@${a}`:`${e}x${r}@${o}`,d=i.stats?` stats: ${JSON.stringify(i.stats).replaceAll('"',"")}`:"";return`${i.id} ${i.readyState} muted:${i.muted} ${i.kind} ${i.label} ${c}${d}`}catch(e){return""}}function eu(i,t){return i.width*i.height===t.width*t.height?1:im()&&t.width>t.height&&i.height>t.width?Math.max(i.width/t.height,i.height/t.width,1):Math.max(i.width/t.width,i.height/t.height,1)}function Jr(i){return i===90||i===270}function Kg(i){return D(this,null,function*(){return new Promise((t,e)=>{let r=document.createElement("video");r.crossOrigin="anonymous",r.src=i,r.muted=!0,r.loop=!0,r.playsInline=!0,r.play().then(()=>t(r)),r.onerror=()=>{e(r.error)}})})}function Xd(i,t=new WeakMap){if(typeof i!="object"||i===null)return i;if(t.has(i))return t.get(i);if(Array.isArray(i)){let e=[];return t.set(i,e),i.forEach((r,o)=>{e[o]=Xd(r,t)}),e}if(Object.prototype.toString.call(i)==="[object Object]"){let e={};return t.set(i,e),Reflect.ownKeys(i).forEach(r=>{e[r]=Xd(i[r],t)}),e}return i}var $n=(r=>(r[r.END_REPORT=2001]="END_REPORT",r[r.LOG=2002]="LOG",r[r.KEY_METRIC_REPORT=2003]="KEY_METRIC_REPORT",r))($n||{});function iI(i,t,e,r){let o={data:i,random:Math.floor(Math.random()*2147483648),sdkAppId:e};return z(r)||(o=qe(be({},o),{gzip:+r})),{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:t,bytes_report_data:JSON.stringify(o)}}}function so(i,t,e,r){try{let o=iI(i,t,e,r),s=zd(o);return kg(s,e)}catch(o){return JSON.stringify(i)}}function e_(i,t){let e=new Uint8Array(i.byteLength+t.byteLength);return e.set(new Uint8Array(i),0),e.set(new Uint8Array(t),i.byteLength),e.buffer}function t_(i){return(i&65535)>>>0}function r_(i){return(i&4294901760)>>>0}function i_(i){let t=oI(i);return t==null?void 0:t.busiBuff}function oI(i){try{let t={},e=0;t.totalLength=wr(i,e),e+=4,t.version=wr(i,e),e+=4,t.encryption=Yh(i,e),e+=1,t.uinType=Yh(i,e),e+=1,t.uinLength=wr(i,e),e+=4,t.uin=t.uinLength>4?On(i,e,t.uinLength-4):"",e+=t.uinLength-4;let r=i.slice(e);if(t.encryption===2){let o=new Uint8Array(16).fill(0);i=sI(r,o),t.decrypted=!0,e=0}else i=r,e=0;return t.rspHeadLength=wr(i,e),e+=4,t.seqNo=wr(i,e),e+=4,t.retCode=wr(i,e),e+=4,t.retStrLength=wr(i,e),e+=4,t.retStr=t.retStrLength?On(i,e,t.retStrLength-4):"",e+=t.retStrLength-4,t.serviceCmdLength=wr(i,e),e+=4,t.serviceCmd=t.serviceCmdLength?On(i,e,t.serviceCmdLength-4):"",e+=t.serviceCmdLength-4,t.cookieLength=wr(i,e),e+=4,t.cookie=t.cookieLength?On(i,e,t.cookieLength-4):"",e+=t.cookieLength-4,t.flag=wr(i,e),e+=4,t.busiBuffLength=wr(i,e),e+=4,t.busiBuff=t.busiBuffLength?On(i,e,t.busiBuffLength-4):"",e+=t.busiBuffLength-4,t}catch(t){}}function o_(i,t){let e=i[0]<<24|i[1]<<16|i[2]<<8|i[3],r=i[4]<<24|i[5]<<16|i[6]<<8|i[7];e=e>>>0,r=r>>>0;let o=jd*qd>>>0;for(let s=0;s<qd;s++)r-=(e<<em)+t[2]^e+o^(e>>>5)+t[3],r=r>>>0,e-=(r<<em)+t[0]^r+o^(r>>>5)+t[1],e=e>>>0,o-=jd,o=o>>>0;return new Uint8Array([e>>>24&255,e>>>16&255,e>>>8&255,e&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255])}function sI(i,t){let e=0,r=new Uint8Array(8).fill(0),o=new Uint8Array(i.slice(0,8)),s=o_(o,t),n=s[0]&7,a=i.length-1-n-Mn-xn,c=new Uint8Array(a),d=0,m=r,l=i.slice(0,8);e=8;let f=1;f+=n;for(let T=1;T<=Mn;)if(f<8)f++,T++;else if(f===8){let E=om(i,e,m,l,s,t);m=E.ivPreCrypt,l=E.ivCurCrypt,s=E.debiBuf,e=E.bufPos,f=0}let g=a;for(;g>0;)if(f<8)c[d++]=s[f]^m[f],f++,g--;else if(f===8){let T=om(i,e,m,l,s,t);m=T.ivPreCrypt,l=T.ivCurCrypt,s=T.debiBuf,e=T.bufPos,f=0}for(let T=1;T<=xn;)if(f<8)s[f]^m[f],f++,T++;else if(f===8){if(e>=i.length)break;let E=om(i,e,m,l,s,t);if(!E.success)break;m=E.ivPreCrypt,l=E.ivCurCrypt,s=E.debiBuf,e=E.bufPos,f=0}return c}function om(i,t,e,r,o,s){if(t+8>i.length)return{success:!1};let n=new Uint8Array(r),a=i.slice(t,t+8),c=new Uint8Array(8);for(let m=0;m<8;m++)c[m]=o[m]^a[m];let d=o_(c,s);return{success:!0,ivPreCrypt:n,ivCurCrypt:a,debiBuf:d,bufPos:t+8}}var s_=typeof TextDecoder!="undefined"?new TextDecoder:void 0;function no({url:i,body:t,method:e="POST",timeout:r,priority:o}){return new Promise((s,n)=>{if("fetch"in window)return fetch(i,{method:e,body:t,priority:o}).then(c=>c.clone().json().then(d=>({data:d}),()=>c.arrayBuffer().then(d=>({data:i_(new Uint8Array(d))||(s_?s_.decode(d):d)})))).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=r||5e3,a.open(e,i,!0),a.send(t)})}function sm(i){return D(this,null,function*(){let t=Xe(),e=JSON.stringify(i);try{if(!CompressionStream||e.length<=2800)return e;let o=new Blob([e],{type:"application/json"}).stream().pipeThrough(new CompressionStream("gzip")),a=yield(yield(yield new Response(o)).blob()).arrayBuffer();return se.debug(`compressJSON ${e.length} -> ${a.byteLength} ${Xe()-t}ms`),a}catch(r){return e}})}var nI=Object.prototype.hasOwnProperty;var Fo=i=>typeof i=="function",ks=i=>typeof i=="undefined";var n_=i=>typeof i=="boolean";var nm=i=>i.isRemote;var am=function(i){if(!i||typeof i!="object"||Object.prototype.toString.call(i)!="[object Object]")return!1;let t=Object.getPrototypeOf(i);if(t===null)return!0;let e=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return typeof e=="function"&&e instanceof e&&Function.prototype.toString.call(e)===Function.prototype.toString.call(Object)};function a_(i){if(i==null)return!0;if(typeof i=="boolean")return!1;if(typeof i=="number")return i===0;if(typeof i=="string"||typeof i=="function"||Array.isArray(i))return i.length===0;if(i instanceof Error)return i.message==="";if(am(i))switch(Object.prototype.toString.call(i)){case"[object File]":case"[object Map]":case"[object Set]":return i.size===0;case"[object Object]":{for(let t in i)if(nI.call(i,t))return!1;return!0}}return!1}var aI=0,cI=1,c_=2;function dI({retryFunction:i,settings:t,onError:e,onRetrying:r,onRetryFailed:o,onRetrySuccess:s,context:n}){return function(...a){let{retries:c=5,timeout:d=1e3}=t,m=0,l=-1,f=aI,g=(T,E)=>D(this,null,function*(){let y=n||this;try{let v=yield i.apply(y,a);m>0&&s&&s.call(this,m),m=0,T(v)}catch(v){let M=()=>{clearTimeout(l),m=0,f=c_,E(v)},w=()=>{f!==c_&&m<(Fo(c)?c():c)?(m++,f=cI,Fo(r)&&r.call(this,m,M),l=window.setTimeout(()=>{l=-1,g(T,E)},Fo(d)?d(m):d)):(M(),Fo(o)&&o.call(this,v))};Fo(e)?e.call(this,{error:v,retry:w,reject:E,retryFuncArgs:a,retriedCount:m}):w()}});return new Promise(g)}}var Ho=dI;var Wo=class i{constructor(t){p(this,"_parentPath");p(this,"userId");p(this,"remoteUserId");p(this,"id");p(this,"sdkAppId");p(this,"type");p(this,"isLocal");this.id=t.id,this.userId=t.userId,this.sdkAppId=t.sdkAppId,this.remoteUserId=t.remoteUserId,this.isLocal=n_(t.isLocal)?t.isLocal:!0,this.type=this.isLocal?"":t.type}getFullId(){return this._parentPath&&this.id?`${this._parentPath}-${this.id}`:this._parentPath?this._parentPath:this.id}createChild(t){let e=new i({id:t.id,userId:ks(t.userId)?this.userId:t.userId,sdkAppId:ks(t.sdkAppId)?this.sdkAppId:t.sdkAppId,type:ks(t.type)?this.type:t.type,isLocal:ks(t.isLocal)?this.isLocal:t.isLocal,remoteUserId:ks(t.remoteUserId)?this.remoteUserId:t.remoteUserId});return e.bindParent(this),e}bindParent(t){let e=t.getFullId();this._parentPath!==e&&(this.debug(`bind logger parent: ${t.id}`),this._parentPath=e,this.userId=t.userId||this.userId,this.sdkAppId=t.sdkAppId||this.sdkAppId)}setUserId(t){this.userId=t}setSdkAppId(t){this.sdkAppId=t}log(t,e){let r=this.isLocal?this.userId:this.remoteUserId,o=this.getFullId();e.unshift(`[${this.isLocal?"\u2191":"\u2193"}${this.type&&this.type!=="main"?"*":""}${o}${r?`|${r}`:""}]`),se.log(t,e,ks(this.userId)||a_(this.userId),this.userId,this.sdkAppId)}info(...t){this.log(2,t)}debug(...t){this.log(1,t)}warn(...t){this.log(3,t)}error(...t){this.log(4,t)}};var Qn={};eo(Qn,{ANDROID_VERSION:()=>ru,CHROME_MAJOR_VERSION:()=>Fr,CHROME_VERSION:()=>Su,EDGE_VERSION:()=>su,EDG_MAJOR_VERSION:()=>dm,EDG_VERSION:()=>nu,ELECTRON_MAJOR_VERSION:()=>pm,FIREFOX_MAJOR_VERSION:()=>ou,FIREFOX_VERSION:()=>iu,HUAWEI_VERSION:()=>gu,IE_VERSION:()=>pI,IOS_MAIN_VERSION:()=>Tr,IOS_VERSION:()=>ai,IPADQQB_VERSION:()=>pu,IS_ANDROID:()=>Bt,IS_ANDROID_WEBVIEW:()=>EI,IS_ANY_SAFARI:()=>ni,IS_CHROME:()=>Xn,IS_CHROME_OS:()=>um,IS_CHROMIUM_BASE:()=>Qr,IS_DESKTOP_IOS_CHROME:()=>Tm,IS_EDG:()=>Wn,IS_EDGE:()=>Ls,IS_ELECTRON:()=>gI,IS_FIREFOX:()=>zt,IS_HEADLESS_CHROME:()=>mm,IS_HONOR:()=>hm,IS_HUAWEI:()=>Ka,IS_HUAWEIBROWSER:()=>Za,IS_IE:()=>h_,IS_IE8:()=>mI,IS_IOS:()=>Ut,IS_IOS_13_OR_14:()=>Em,IS_IOS_15_1:()=>_m,IS_IOS_CHROME:()=>Ga,IS_IPAD:()=>Hn,IS_IPADQQB:()=>Ja,IS_IPAD_PRO:()=>cm,IS_IPHONE:()=>Go,IS_IPOD:()=>l_,IS_LINUX:()=>Qa,IS_LOCAL:()=>bi,IS_MAC:()=>Ii,IS_MACQQB:()=>Xa,IS_MIBROWSER:()=>Ya,IS_MQQB:()=>zn,IS_NATIVE_ANDROID:()=>hI,IS_OLD_ANDROID:()=>lI,IS_OPENHARMONY:()=>qn,IS_OPPOBROWSER:()=>jn,IS_SAFARI:()=>Zt,IS_SAFARI_15_1:()=>TI,IS_SAMSUNGBROWSER:()=>ec,IS_SOGOU:()=>ja,IS_SOGOUM:()=>za,IS_TBS:()=>Si,IS_UCBROWSER:()=>lm,IS_VIVOBROWSER:()=>tc,IS_WECHAT:()=>co,IS_WIN:()=>Ps,IS_WQQB:()=>qa,IS_WX:()=>fI,IS_X5MQQB:()=>Gn,IS_XWEB:()=>ao,MACQQB_VERSION:()=>mu,MI_VERSION:()=>fu,MQQB_VERSION:()=>Fn,OPENHARMONY_VERSION:()=>_I,OPPO_VERSION:()=>Eu,SAFARI_VERSION:()=>uo,SAMSUNG_VERSION:()=>_u,SOGOUM_VERSION:()=>au,SOGOU_VERSION:()=>cu,TBS_VERSION:()=>du,UA_DATA_STRING:()=>yi,USER_AGENT:()=>$r,VIVO_VERSION:()=>Tu,WECHAT_VERSION:()=>lu,WQQB_VERSION:()=>hu,XWEB_VERSION:()=>uu,browserInfo:()=>Bi,getBrowserCoreNumber:()=>Sm,getBrowserInfo:()=>m_,getChromeMajorVersion:()=>yu,getDeviceModel:()=>Vs,getDeviceModelFromUA:()=>Iu,getGPUInfo:()=>ym,getOSName:()=>Jn,getOSNumber:()=>Bs,getOSString:()=>ho,getOSType:()=>bm,getTerminalType:()=>Im,getUserAgentData:()=>Us,isLocalStorageEnabled:()=>lo,isMobile:()=>rc,isVersionLargerThan:()=>gm,isVersionSmallerThan:()=>fm});var $r=typeof navigator=="undefined"?"":navigator.userAgent,et=i=>new RegExp(i,"i").test($r),er=i=>{if(et(i)){let t=new RegExp(`${i}\\/([\\d.]+)`),e=$r.match(t);if(e&&e[1])return e[1]}return""},tu=i=>{if(et(i)){let t=new RegExp(`${i}\\/(\\d+)`),e=$r.match(t);if(e&&e[1])return parseFloat(e[1])}return NaN},d_=/AppleWebKit\/([\d.]+)/i.exec($r),uI=d_?parseFloat(d_[1]):NaN,Hn=et("iPad"),cm=typeof navigator!="undefined"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&et("Macintosh"),Go=et("iPhone")&&!Hn,l_=et("iPod"),Ut=Go||Hn||l_||cm,Bt=et("Android"),ru=function(){if(Bt){let i=$r.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(i){let t=i[1]&&parseFloat(i[1]),e=i[2]&&parseFloat(i[2]);if(t&&e)return parseFloat(`${i[1]}.${i[2]}`);if(t)return t}}return NaN}(),lI=Bt&&et("webkit")&&ru<2.3,hI=Bt&&ru<5&&uI<537,zt=et("Firefox"),iu=er("Firefox"),ou=tu("Firefox"),Ls=et("Edge"),su=er("Edge"),Wn=et("Edg"),nu=er("Edg"),dm=tu("Edg"),za=et("SogouMobileBrowser"),au=er("SogouMobileBrowser"),ja=et("MetaSr\\s"),cu=er("MetaSr\\s"),Si=et("TBS"),du=er("TBS"),ao=et("XWEB"),uu=er("XWEB"),mI=et("MSIE\\s8\\.0"),h_=et("MSIE\\/\\d+"),pI=function(){if(h_){let i=/MSIE\s(\d+)\.\d/.exec($r),t=i&&parseFloat(i[1]);return!t&&/Trident\/7.0/i.test($r)&&/rv:11.0/.test($r)&&(t=11),t}return NaN}(),co=et("(micromessenger|webbrowser)"),lu=er("MicroMessenger"),Gn=!Si&&et("MQQBrowser")&&et("COVC"),zn=!Si&&et("MQQBrowser")&&!et("COVC"),Fn=zn||Gn?er("MQQBrowser"):"",qa=!Si&&et(" QQBrowser"),hu=er(" QQBrowser"),Xa=!Si&&et("QQBrowserLite"),mu=er("QQBrowserLite"),Ja=!Si&&et("MQBHD"),pu=er("MQBHD"),Ps=et("Windows"),Ii=!Ut&&et("MAC OS X"),Qa=!Bt&&et("Linux"),um=et("CrOS"),fI=et("MicroMessenger"),lm=et("UCBrowser"),gI=et("Electron"),Ya=et("MiuiBrowser"),fu=er("MiuiBrowser"),Za=et("HuaweiBrowser"),Ka=et("Huawei")||et("HUAWEI"),hm=et("Honor")||et("HONOR"),gu=er("HuaweiBrowser"),ec=et("SamsungBrowser"),_u=er("SamsungBrowser"),jn=et("HeyTapBrowser"),Eu=er("HeyTapBrowser"),tc=et("VivoBrowser"),Tu=er("VivoBrowser"),qn=et("OpenHarmony"),_I=er("OpenHarmony"),yu=()=>tu("Chrome"),Ga=et("CriOS"),Qr=et("Chrome"),Xn=!Ls&&!ja&&!za&&!Si&&!ao&&!Wn&&!qa&&!Ya&&!Za&&!ec&&!jn&&!tc&&Qr,mm=et("HeadlessChrome"),Fr=yu(),Su=er("Chrome"),pm=tu("Electron"),Zt=!Qr&&!zn&&!Gn&&!Xa&&!Ja&&et("Safari"),ni=Zt||Ut,uo=er("Version"),EI=/Android.*(wv|.0.0.0)/.test($r),ai=(()=>{if(cm)return uo;if(Ut){let i=$r.match(/OS (\d+)_(\d+)/i);if(i&&i[1]){let t=i[1];return i[2]&&(t+=`.${i[2]}`),t}}return""})();function fm(i,t){let e=i.split(".").map(o=>Number(o)),r=t.split(".").map(o=>Number(o));for(let o=0;o<Math.max(e.length,r.length);o++){let s=e[o]||0,n=r[o]||0;if(s<n)return!0;if(s>n)return!1}return!1}function gm(i,t,e=!1){let r=i.split(".").map(s=>Number(s)),o=t.split(".").map(s=>Number(s));for(let s=0;s<Math.max(r.length,o.length);s++){let n=r[s]||0,a=o[s]||0;if(n>a)return!0;if(n<a)return!1}return e}var Tr=Number(ai.split(".")[0]),TI=uo==="15.1",_m=ai==="15.1",Em=(()=>{let i=Number(ai.split(".")[0]);return i===14||i===13})(),Tm=Ga&&uo==="11.1.1",bi=typeof location=="undefined"?!1:location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1",lo=(()=>{let i;return()=>{if(typeof i=="undefined")try{i=!!window.localStorage}catch(t){i=!1}return i}})(),Bi=m_();function m_(){let i=new Map([[zt,["Firefox",iu]],[Wn,["Edg",nu]],[Xn,["Chrome",Su]],[Ga,["ChiOS",er("CriOS")]],[Zt&&!Ga,["Safari",uo]],[Si,["TBS",du]],[ao,["XWEB",uu]],[co&&Go,["WeChat",lu]],[qa,["QQ(Win)",hu]],[zn,["QQ(Mobile)",Fn]],[Gn,["QQ(Mobile X5)",Fn]],[Xa,["QQ(Mac)",mu]],[Ja,["QQ(iPad)",pu]],[Ya,["MI",fu]],[Za,["HW",gu]],[ec,["Samsung",_u]],[jn,["OPPO",Eu]],[tc,["VIVO",Tu]],[Ls,["EDGE",su]],[za,["SogouMobile",au]],[ja,["Sogou",cu]]]),t="unknown",e="unknown";return i.has(!0)&&([t,e]=i.get(!0)),{name:t,version:e}}var Ct=null;function rc(){return Ct&&typeof Ct.mobile=="boolean"?Ct.mobile:Bt||Ut||Go||Hn||qn}var yi="";function Us(){return D(this,null,function*(){if(Ct)return Ct;if(!navigator.userAgentData||typeof navigator.userAgentData.getHighEntropyValues!="function")return null;try{return Ct=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]),Ct&&!yi&&(yi=`UAData: ${Ct.platform}/${Ct.platformVersion}`,Ct.architecture&&Ct.bitness&&(yi+=` ${Ct.architecture}/${Ct.bitness}`),Ct.mobile&&(yi+=" mobile"),Ct.model&&(yi+=` model: ${Ct.model.replace(/\s+/g,"/")}`),Ct.fullVersionList&&(yi+=` ${Ct.fullVersionList.filter(i=>i.brand!=="Not/A)Brand").map(i=>`${i.brand}/${i.version}`).join(",")}`)),Ct}catch(i){return null}})}function ym(){try{let i=document.createElement("canvas"),t=i.getContext("webgl")||i.getContext("experimental-webgl");if(!t)return"";let e=t.getExtension("WEBGL_debug_renderer_info");if(e){let r=t.getParameter(e.UNMASKED_VENDOR_WEBGL),o=t.getParameter(e.UNMASKED_RENDERER_WEBGL);return`${r} ${o}`}return""}catch(i){return""}}function Vs(){return(Ct==null?void 0:Ct.model)||Iu()||""}function Iu(){let i=/;\s*([^;)]+)\s+Build\//,t=$r.match(i);return t!=null&&t[1]?t[1].trim():null}var u_=new Map([[Bt,"Android"],[Ut,"iOS"],[Ps,"Windows"],[Ii,"MacOS"],[Qa,"Linux"],[um,"ChromeOS"]]),Jn=function(){return u_.get(!0)?u_.get(!0):Ct?Ct.platform:"unknown"};function Bs(){return Ps?1:Bt?2:Ii?3:Ut?4:Qa?5:um?6:qn?7:0}function Sm(){return co||ao?4:Qr?1:Zt?2:zt?3:0}var ho=()=>{let i=Jn();return Ct!=null&&Ct.platformVersion?i+=`/${Ct.platformVersion}`:Ut?i+=`/${ai}`:Bt&&(i+=`/${ru}`),i+=`/${Bi.name}/${Zt&&!Ga?Bi.version:Bi.version.split(".")[0]}`,Ct!=null&&Ct.architecture&&(i+=`/${Ct.architecture}`),i};function Im(){return Bt?4:Go?2:Hn?3:Ii?12:Ps?5:Qa?13:qn?22:1}function bm(){return Bt?"Android":Go?"iPhone":Hn?"iPad":Ii?"Mac":Ps?"Windows":Qa?"Linux":"unknown"}var f_=Li(mo(),1),II=new f_.default,ee=II;var Hr=(Z=>(Z.ROOM_DESTROY="1",Z.JOIN_START="21",Z.JOIN_SCHEDULE_SUCCESS="22",Z.JOIN_SIGNAL_CONNECTION_START="23",Z.JOIN_SIGNAL_CONNECTION_END="24",Z.JOIN_SEND_CMD="25",Z.JOIN_RECEIVED_CMD_RES="26",Z.JOIN_SUCCESS="27",Z.JOIN_FAILED="28",Z.LEAVE_START="51",Z.LEAVE_SEND_CMD="52",Z.LEAVE_SUCCESS="53",Z.PUBLISH_START="61",Z.SEND_FIRST_VIDEO_FRAME="62",Z.PUBLISH_FAILED="63",Z.SUBSCRIBE_START="81",Z.SUBSCRIBE_SUCCESS="82",Z.SUBSCRIBE_FAILED="84",Z.UNSUBSCRIBE_SUCCESS="83",Z.LOCAL_TRACK_CAPTURE_START="101",Z.LOCAL_TRACK_CAPTURE_SUCCESS="102",Z.LOCAL_TRACK_CAPTURE_FAILED="103",Z.LOCAL_TRACK_PUBLISHED="104",Z.LOCAL_TRACK_UNPUBLISHED="105",Z.LOCAL_TRACK_REPLACED="106",Z.SWITCH_DEVICE_SUCCESS="107",Z.TRACK_MUTED="108",Z.TRACK_UNMUTED="109",Z.REMOTE_TRACK_SUBSCRIBED="110",Z.REMOTE_TRACK_UNSUBSCRIBED="111",Z.LOCAL_TRACK_RECAPTURE="112",Z.LOCAL_AUDIO_STARTED="113",Z.LOCAL_AUDIO_STOPPED="114",Z.REMOTE_AUDIO_STARTED="115",Z.REMOTE_AUDIO_STOPPED="116",Z.PLAY_TRACK_START="151",Z.PLAYER_STATE_CHANGED="152",Z.VIDEO_LOADED_DATA="153",Z.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",Z.AUDIO_CONTEXT_LONG_SUSPENDED="155",Z.REMOTE_VIDEO_PLAY_START="156",Z.REMOTE_VIDEO_PLAY_FINISH="157",Z.SIGNAL_CONNECTION_STATE_CHANGED="201",Z.PEER_CONNECTION_STATE_CHANGED="202",Z.SINGLE_CONNECTION_STAT="203",Z.SPC_RECONNECTED="204",Z.HEARTBEAT_REPORT="251",Z.RECEIVED_PUBLISHED_USER_LIST="252",Z.REMOTE_PUBLISH_STATE_CHANGED="253",Z.AUDIO_LEVEL_INTERVAL="260",Z.NETWORK_QUALITY="261",Z.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",Z.QUALITY_LIMITATION_CHANGED="263",Z.LOG="264",Z.AUDIO_PROCESSOR_DEBUG="265",Z.SSO_SWITCH="266",Z.SWITCH_ROOM_START="401",Z.SWITCH_ROOM_SUCCESS="407",Z.SWITCH_ROOM_FAILED="408",Z))(Hr||{});var ce=Hr;var vm=class{constructor(){p(this,"enable",!1);p(this,"ssoFailCount",0);ee.on("22",({schedule:t})=>{var e;(e=t==null?void 0:t.config)!=null&&e.sso&&ee.emit("266",{enable:!0})}),ee.on("266",({enable:t})=>{this.enable=t})}handleUploadFailed(){this.ssoFailCount++,this.ssoFailCount>3&&ee.emit("266",{enable:!1})}},zo=new vm;var bI="%cTRTC%c%s",AI="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",vI="display: inline",Au=class Au{constructor(){p(this,"_isEnableUploadLog",!0);p(this,"_localJoinedUser",new Map);p(this,"_queue",[]);p(this,"_timeoutId",-1);p(this,"_logLevel",1);p(this,"_logLevelToUpload",2);!Cn&&!xa&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){ee.on(ce.JOIN_SCHEDULE_SUCCESS,({schedule:t})=>{var e;(e=t==null?void 0:t.config)!=null&&e.logLevelToUpload&&ri[t.config.logLevelToUpload]&&(this._logLevelToUpload=t.config.logLevelToUpload)}),ee.on(ce.JOIN_START,({params:t})=>{this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload()}),ee.on(ce.LEAVE_SUCCESS,({room:t})=>{this.deleteJoinedUser(t.userId)})}startUpload(){this._timeoutId===-1&&this.uploadInterval()}addJoinedUser(t){this._localJoinedUser.set(t.userId,t),this.startUpload()}deleteJoinedUser(t){this._localJoinedUser.delete(t)}uploadInterval(){this.upload().catch(()=>{}),this._timeoutId=window.setTimeout(()=>this.uploadInterval(),5e3)}getLogsToUpload(){let t={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&this._localJoinedUser.size===0)return t;let e=0;for(;e<this._queue.length&&e!==50;e++){let r=this._queue[e];if(r.forAllJoinedClients)this._localJoinedUser.forEach(({userId:o,sdkAppId:s})=>{t.map.has(o)?t.map.get(o).logs.push(r):t.map.set(o,{userId:o,sdkAppId:s,logs:[r]})});else if(nt(r.userId)&&ft(r.sdkAppId)){let{userId:o,sdkAppId:s}=r;t.map.has(o)?t.map.get(o).logs.push(r):t.map.set(o,{userId:o,sdkAppId:s,logs:[r]})}}return t.map.size>0&&(t.splicedQueue=this._queue.splice(0,e)),t}upload(){return D(this,null,function*(){if(this._queue.length===0||!this._isEnableUploadLog)return;let{map:t,splicedQueue:e}=this.getLogsToUpload();if(t.size===0)return;try{let o=[...t.values()];for(let s=0;s<o.length;s++){let{userId:n,sdkAppId:a,logs:c}=o[s],d={timestamp:kd(),sdkAppId:String(a),userId:n,version:qt,log:c.map(f=>f.log).join(`
|
|
5
|
-
`)},m=JSON.stringify(d),l=zo.enable?so(d,2002,a):m;yield this.uploadLogWithRetry(l,a,l instanceof Uint8Array,m),c.forEach(f=>f.uploaded=!0)}}catch(o){}let r=e.filter(o=>!o.uploaded);r.length>0&&(this._queue=r.concat(this._queue))})}uploadLogWithRetry(t,e,r,o){return Ho({retryFunction:()=>no({url:oo(e,Bo.LOG),body:t,timeout:5e3,priority:"low"}).then(s=>{r&&s.data!=="ok"&&(zo.handleUploadFailed(),this.uploadLogWithRetry(o,e,!1,o))}),settings:{retries:3,timeout:2e3},onError:({retry:s})=>{s()}})()}getPrefix(t){let e=new Date;return e.setTime(to()),`[${Rn(e)}] <${ri[t]}>`}getLogLevel(){return this._logLevel}setLogLevel(t){z(ri[t])||(this._logLevel!==t&&this.info("setLogLevel",t),this._logLevel=t)}enableUploadLog(){this._isEnableUploadLog=!0}disableUploadLog(){this.warn("disableUploadLog"),this._isEnableUploadLog=!1}logChunkToString(t){if(nt(t))return t;try{return t instanceof Error?t.toString():JSON.stringify(t)}catch(e){return""}}addLogToQueue(t,e,r=!0,o,s){let n={log:e.reduce((a,c)=>`${a} ${this.logChunkToString(c)}`.trim(),""),level:t,userId:o,sdkAppId:s,forAllJoinedClients:r};ee.emit(ce.LOG,{log:n}),this._isEnableUploadLog&&t>=this._logLevelToUpload&&this._queue.push(n)}log(t,e,r=!0,o,s){var a;if(e.unshift(this.getPrefix(t)),this.addLogToQueue(t,e,r,o,s),t<this._logLevel)return;let n=((a=ri[t])==null?void 0:a.toLowerCase())||"info";Au.PRINT_LOG_TAG?console[n](bI,AI,vI,...e):console[n](...e)}debug(...t){this.log(1,t)}info(...t){this.log(2,t)}warn(...t){this.log(3,t)}error(...t){this.log(4,t)}createLogger(t){if(t.parent instanceof Wo){let e=t,{parent:r}=e,o=Rg(e,["parent"]),s=new Wo(o);return s.bindParent(r),s}return new Wo(t)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),r=e?Number(e):-1;ri[r]&&(this._logLevelToUpload=r)}getQueue(){return this._queue}};p(Au,"PRINT_LOG_TAG",!(Ut||Bt||mm));var Rm=Au,se=new Rm;var RI=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{let t=Math.random()*16|0;return(i=="x"?t:t&3|8).toString(16)})},oc=RI;var Cm=class{constructor(){p(this,"_prefix","TRTC");p(this,"_queue",new Map)}getRealKey(t){return`${this._prefix}_${t}`}checkStorage(){if(!lo())return;setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter(r=>{if(r.startsWith(this._prefix))try{let o=localStorage.getItem(r);if(!o)return!1;let s=JSON.parse(o);if(s&&s.expiresIn<Date.now())return!0}catch(o){return!1}return!1}).forEach(r=>localStorage.removeItem(r))}doFlush(){if(lo())try{for(let[t,e]of this._queue)localStorage.setItem(t,JSON.stringify(e))}catch(t){se.warn(t)}}getItem(t){if(!lo())return null;try{let e=localStorage.getItem(this.getRealKey(t));if(!e)return null;let r=JSON.parse(e);return r&&r.expiresIn>=Date.now()?r.value:null}catch(e){se.warn(e)}}setItem(t,e){if(lo())try{let r={expiresIn:Date.now()+Ud,value:e};this._queue.set(this.getRealKey(t),r)}catch(r){se.warn(r)}}deleteItem(t){if(!lo())return!1;try{return t=this.getRealKey(t),this._queue.delete(t),localStorage.removeItem(t),!0}catch(e){return se.warn(e),!1}}clear(){if(lo())try{localStorage.clear()}catch(t){se.warn(t)}}},Yn=new Cm;var Jo={};eo(Jo,{HTTPS_API:()=>XI,IS_GET_CAPABILITIES_FROM_INPUTDEVICE_SUPPORTED:()=>Ym,IS_GET_CAPABILITIES_SUPPORTED:()=>Qm,IS_GET_SETTINGS_SUPPORTED:()=>ea,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>ib,IS_INSERTABLE_STREAM_SUPPORTED:()=>zs,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>nb,IS_RTC_RTP_SENDER_SUPPORTED:()=>pc,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>q_,IS_SEI_SUPPORTED:()=>fc,IS_SPC_SUPPORTED:()=>KI,basis:()=>ob,capabilityCheck:()=>ep,checkSystemRequirementsInternal:()=>Vu,decodeSupportStatus:()=>B_,detectVideoCodecCapabilities:()=>tp,detectVideoDecoderCapabilities:()=>Z_,detectVideoEncoderCapabilities:()=>Y_,encodeSupportStatus:()=>Jm,getBrowserInfo:()=>Pu,getDisplayResolution:()=>$_,getH264ProfileLevelIds:()=>K_,isAddTransceiverSupported:()=>$u,isBrowserSupported:()=>jm,isCanvasCaptureStreamAPISupported:()=>W_,isCanvasSmallStreamSupported:()=>G_,isGetReceiversSupported:()=>YI,isGetSendersSupported:()=>j_,isGetTransceiversSupported:()=>ZI,isGetUserMediaSupported:()=>F_,isMediaDevicesSupported:()=>Uu,isMediaSessionSupported:()=>X_,isMediaStreamTrackGeneratorSupported:()=>HI,isMediaStreamTrackProcessorSupported:()=>Xm,isReplaceTrackSupported:()=>tb,isRequestVideoFrameCallbackSupported:()=>Ri,isSIMDSupported:()=>Km,isScaleResolutionDownBySupported:()=>z_,isScreenCaptureApiAvailable:()=>mc,isSelectedCandidatePair:()=>JI,isSetParametersSupported:()=>rb,isSetSinkIdSupported:()=>zI,isSmallStreamSupported:()=>Bu,isStopTransceiverSupported:()=>eb,isTRTCSupported:()=>GI,isUnifiedPlanDefault:()=>QI,isUsedInHttpProtocol:()=>Eo,isWebAudioSupported:()=>H_,isWebCodecSupported:()=>Fu,isWebCodecsSupported:()=>qm,isWebRTCSupported:()=>Zm,isWebTransportSupported:()=>J_});var $m={};eo($m,{AUDIO_LEVEL_SCALE:()=>fo,AlphaStitchingType:()=>lc,AudioCodecPipelineType:()=>Hs,AudioDecoderDowngradeState:()=>Dm,AudioPlayerMode:()=>km,AudioType:()=>Mm,BASIC_TYPE:()=>go,BannedReason:()=>Lm,CONNECTION_CLOSED_REASON:()=>__,CheckPermissionType:()=>Bm,ClientEvent:()=>wm,CodecType:()=>A_,ConnectionEvent:()=>g_,ConnectionState:()=>Ru,DECODE_FAILED_ERROR_CODE:()=>Vm,DenoiserMode:()=>Um,DeviceType:()=>Du,FacingMode:()=>Cu,FrameWorkType:()=>vu,LeaveReason:()=>Pm,LocalTrackEvent:()=>jo,MULTI_VIDEO_DATA_TYPE:()=>po,MediaType:()=>dr,MediaTypeLabel:()=>CI,MonitorEventId:()=>ac,MutedFlag:()=>T_,NetworkQualityValue:()=>I_,PlayerState:()=>qo,ReceiveMode:()=>b_,RemoteStreamType:()=>vi,RemoteTrackEvent:()=>$s,RoomEvent:()=>$i,SMALL_MODE:()=>Nu,SceneNumber:()=>Nm,StreamEvent:()=>E_,StreamType:()=>S_,SubscribeMediaType:()=>sc,TIMER_TYPE:()=>Xo,TRACK_ACTION:()=>y_,TRACK_KIND:()=>Om,TrackEvent:()=>Ai,UserRole:()=>Pr,UserRoleNumber:()=>Fs,VideoCodec:()=>wu,VideoCodecPipelineType:()=>dc,VideoContentHint:()=>uc,VideoDecoderDowngradeState:()=>nc,VideoPlayerMode:()=>cc,VideoType:()=>xm});var vu=(e=>(e[e.WEBRTC=30]="WEBRTC",e[e.WASM=37]="WASM",e))(vu||{}),g_=(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))(g_||{}),__=(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))(__||{}),wm=(y=>(y.STREAM_ADDED="stream-added",y.STREAM_REMOVED="stream-removed",y.STREAM_UPDATED="stream-updated",y.STREAM_SUBSCRIBED="stream-subscribed",y.CONNECTION_STATE_CHANGED="connection-state-changed",y.PEER_JOIN="peer-join",y.PEER_LEAVE="peer-leave",y.MUTE_AUDIO="mute-audio",y.MUTE_VIDEO="mute-video",y.UNMUTE_AUDIO="unmute-audio",y.UNMUTE_VIDEO="unmute-video",y.CLIENT_BANNED="client-banned",y.NETWORK_QUALITY="network-quality",y.AUDIO_VOLUME="audio-volume",y.SEI_MESSAGE="sei-message",y.ERROR="error",y))(wm||{}),E_=(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))(E_||{}),jo=(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))(jo||{}),qo=(r=>(r.PAUSED="PAUSED",r.PLAYING="PLAYING",r.STOPPED="STOPPED",r))(qo||{}),$i=(P=>(P.PEER_JOIN="peer-join",P.PEER_LEAVE="peer-leave",P.SIGNAL_CONNECTION_STATE_CHANGED="signal-connection-state-changed",P.MEDIA_CONNECTION_STATE_CHANGED="media-connection-state-changed",P.BANNED="banned",P.NETWORK_QUALITY="network-quality",P.AUDIO_VOLUME="audio-volume",P.SEI_MESSAGE="sei-message",P.ERROR="error",P.REMOTE_PUBLISH_STATE_CHANGED="remote-publish-state-changed",P.REMOTE_PUBLISHED="remote-published",P.REMOTE_UNPUBLISHED="remote-unpublished",P.FIREWALL_RESTRICTION="firewall-restriction",P.HEARTBEAT_REPORT="heartbeat-report",P.CUSTOM_MESSAGE="custom-message",P.LAYER_DATA="layerData",P.FIRST_VIDEO_FRAME="first-video-frame",P.DUMP="dump",P.AUDIO_FRAME="audio-frame",P.SUBSCRIBE_SMALL_VIDEO_CHANGED="subscribe-small-video-changed",P.LOCAL_PUBLISH_FLAG_CHANGED="local-publish-flag-changed",P.NTP_TIME_UPDATED="ntp-time-updated",P))($i||{}),Ai=(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))(Ai||{}),$s=(o=>(o.DECODE_FAILED="decode-failed",o.DECODE_DOWNGRADE_STATE_CHANGED="decode-downgrade-state-changed",o.REMOTE_PUBLISH_CHANGED="remote-publish-changed",o.AUDIO_FRAME_WITH_NTP="audio-frame-with-ntp",o))($s||{}),T_=(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))(T_||{}),Nm=(e=>(e[e.RTC=1]="RTC",e[e.LIVE=2]="LIVE",e))(Nm||{}),Fs=(e=>(e[e.ANCHOR=20]="ANCHOR",e[e.AUDIENCE=21]="AUDIENCE",e))(Fs||{}),Pr=(e=>(e.ANCHOR="anchor",e.AUDIENCE="audience",e))(Pr||{}),Ru=(s=>(s.CONNECTED="CONNECTED",s.DISCONNECTED="DISCONNECTED",s.CONNECTING="CONNECTING",s.RECONNECTED="RECONNECTED",s.RECONNECTING="RECONNECTING",s))(Ru||{}),Dm=(o=>(o.INITIALIZED="INITIALIZED",o.STARTING="STARTING",o.STARTED="STARTED",o.FAILED="FAILED",o))(Dm||{}),nc=(o=>(o.INITIALIZED="INITIALIZED",o.STARTING="STARTING",o.STARTED="STARTED",o.FAILED="FAILED",o))(nc||{}),Om=(r=>(r.AUDIO="audio",r.VIDEO="video",r.AUXILIARY="auxVideo",r))(Om||{}),y_=(e=>(e.ADD="add",e.REMOVE="remove",e))(y_||{}),dr=(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))(dr||{}),CI={1:"audio",2:"auxVideo",4:"video"},Mm=(t=>(t[t.opus=111]="opus",t))(Mm||{}),xm=(e=>(e[e.h264=100]="h264",e[e.vp8=101]="vp8",e))(xm||{}),S_=(e=>(e.Big="big",e.Small="small",e))(S_||{}),vi=(e=>(e.Main="main",e.Aux="auxiliary",e))(vi||{}),po=(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))(po||{}),ac=(ae=>(ae[ae.PUBLISH_VIDEO=32768]="PUBLISH_VIDEO",ae[ae.PUBLISH_AUDIO=32769]="PUBLISH_AUDIO",ae[ae.UNPUBLISH_VIDEO=32770]="UNPUBLISH_VIDEO",ae[ae.UNPUBLISH_AUDIO=32771]="UNPUBLISH_AUDIO",ae[ae.MUTE_AUDIO=32772]="MUTE_AUDIO",ae[ae.MUTE_VIDEO=32773]="MUTE_VIDEO",ae[ae.UNMUTE_AUDIO=32774]="UNMUTE_AUDIO",ae[ae.UNMUTE_VIDEO=32775]="UNMUTE_VIDEO",ae[ae.SUBSCRIBE_VIDEO=32776]="SUBSCRIBE_VIDEO",ae[ae.SUBSCRIBE_AUDIO=32777]="SUBSCRIBE_AUDIO",ae[ae.UNSUBSCRIBE_VIDEO=32778]="UNSUBSCRIBE_VIDEO",ae[ae.UNSUBSCRIBE_AUDIO=32779]="UNSUBSCRIBE_AUDIO",ae[ae.SWITCH_CAMERA=32780]="SWITCH_CAMERA",ae[ae.SWITCH_MICROPHONE=32781]="SWITCH_MICROPHONE",ae[ae.REPLACE_VIDEO=32782]="REPLACE_VIDEO",ae[ae.REPLACE_AUDIO=32783]="REPLACE_AUDIO",ae[ae.MUTE_REMOTE_VIDEO=32784]="MUTE_REMOTE_VIDEO",ae[ae.MUTE_REMOTE_AUDIO=32785]="MUTE_REMOTE_AUDIO",ae[ae.UNMUTE_REMOTE_VIDEO=32786]="UNMUTE_REMOTE_VIDEO",ae[ae.UNMUTE_REMOTE_AUDIO=32787]="UNMUTE_REMOTE_AUDIO",ae[ae.JOIN=32788]="JOIN",ae[ae.LEAVE=32789]="LEAVE",ae[ae.SIGNAL_DISCONNECTED=32790]="SIGNAL_DISCONNECTED",ae[ae.SIGNAL_CONNECTED=32791]="SIGNAL_CONNECTED",ae[ae.TRANSPORT_UPLINK_CONNECTED=32792]="TRANSPORT_UPLINK_CONNECTED",ae[ae.TRANSPORT_DOWNLINK_CONNECTED=32793]="TRANSPORT_DOWNLINK_CONNECTED",ae[ae.SIGNAl_RECONNECTING=32794]="SIGNAl_RECONNECTING",ae[ae.SIGNAL_RECONNECT_SUCCESS=32795]="SIGNAL_RECONNECT_SUCCESS",ae[ae.SIGNAL_RECONNECT_FAIL=32796]="SIGNAL_RECONNECT_FAIL",ae[ae.TRANSPORT_UPLINK_RECONNECTING=32797]="TRANSPORT_UPLINK_RECONNECTING",ae[ae.TRANSPORT_UPLINK_RECONNECT_SUCCESS=32798]="TRANSPORT_UPLINK_RECONNECT_SUCCESS",ae[ae.TRANSPORT_UPLINK_RECONNECT_FAIL=32799]="TRANSPORT_UPLINK_RECONNECT_FAIL",ae[ae.TRANSPORT_DOWNLINK_RECONNECTING=32800]="TRANSPORT_DOWNLINK_RECONNECTING",ae[ae.TRANSPORT_DOWNLINK_RECONNECT_SUCCESS=32801]="TRANSPORT_DOWNLINK_RECONNECT_SUCCESS",ae[ae.TRANSPORT_DOWNLINK_RECONNECT_FAIL=32802]="TRANSPORT_DOWNLINK_RECONNECT_FAIL",ae[ae.SUBSCRIBE_SMALL_VIDEO=32803]="SUBSCRIBE_SMALL_VIDEO",ae[ae.UNSUBSCRIBE_SMALL_VIDEO=32804]="UNSUBSCRIBE_SMALL_VIDEO",ae[ae.PUBLISH_AUX=32805]="PUBLISH_AUX",ae[ae.UNPUBLISH_AUX=32806]="UNPUBLISH_AUX",ae[ae.DEVICE_CAPTURE=2003]="DEVICE_CAPTURE",ae[ae.VIDEO_ENCODER=4004]="VIDEO_ENCODER",ae[ae.VIDEO_DECODER=4005]="VIDEO_DECODER",ae))(ac||{}),I_=(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))(I_||{}),b_=(o=>(o[o.MANUAL=0]="MANUAL",o[o.AUTO_AUDIO=1]="AUTO_AUDIO",o[o.AUTO_VIDEO=2]="AUTO_VIDEO",o[o.AUTO_ALL=3]="AUTO_ALL",o))(b_||{}),Cu=(e=>(e.user="user",e.environment="environment",e))(Cu||{}),cc=(r=>(r[r.ELEMENT=0]="ELEMENT",r[r.CANVAS_FROM_ELEMENT=1]="CANVAS_FROM_ELEMENT",r[r.CANVAS_WITHOUT_ELEMENT=2]="CANVAS_WITHOUT_ELEMENT",r))(cc||{}),km=(e=>(e[e.ELEMENT=0]="ELEMENT",e[e.CONTEXT=1]="CONTEXT",e))(km||{}),Lm=(o=>(o.BANNED="banned",o.KICK="kick",o.USER_TIME_OUT="user_time_out",o.ROOM_DISBAND="room_disband",o))(Lm||{}),Pm=(d=>(d[d.USER_EXIT_REASON_TC_USER_EXIT_NORMAL=0]="USER_EXIT_REASON_TC_USER_EXIT_NORMAL",d[d.USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT=1]="USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT",d[d.USER_EXIT_REASON_TC_USER_EXIT_KICKED=2]="USER_EXIT_REASON_TC_USER_EXIT_KICKED",d[d.USER_EXIT_REASON_TC_USER_EXIT_CHANGED=3]="USER_EXIT_REASON_TC_USER_EXIT_CHANGED",d[d.USER_KICK_OUT_CODE_BUSINESS_USER=4]="USER_KICK_OUT_CODE_BUSINESS_USER",d[d.USER_KICK_OUT_CODE_BUSINESS_ROOM=5]="USER_KICK_OUT_CODE_BUSINESS_ROOM",d[d.USER_KICK_OUT_CODE_SERVER_USER=6]="USER_KICK_OUT_CODE_SERVER_USER",d[d.USER_KICK_OUT_CODE_SERVER_ROOM=7]="USER_KICK_OUT_CODE_SERVER_ROOM",d[d.USER_KICK_SESS_EXSIT=8]="USER_KICK_SESS_EXSIT",d))(Pm||{}),fo=1e8,Um=(e=>(e[e.NORMAL=0]="NORMAL",e[e.FAR_FIELD_REDUCTION=1]="FAR_FIELD_REDUCTION",e))(Um||{}),sc=class{constructor(){p(this,"mediaType",0)}set audio(t){t?this.mediaType|=1:this.mediaType&=-2}get audio(){return!!(this.mediaType&1)}set video(t){t?this.mediaType|=4:this.mediaType&=-5}get video(){return!!(this.mediaType&4)}set auxiliary(t){t?this.mediaType|=2:this.mediaType&=-3}get auxiliary(){return!!(this.mediaType&2)}set smallVideo(t){t?this.mediaType|=8:this.mediaType&=-9}get smallVideo(){return!!(this.mediaType&8)}},go=(s=>(s.String="string",s.Number="number",s.Boolean="boolean",s.Array="array",s.Object="object",s))(go||{}),wu=(s=>(s.H264="h264",s.H265="h265",s.VP8="vp8",s.VP9="vp9",s.AV1="av1",s))(wu||{}),dc=(o=>(o[o.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",o[o.DUMP=1]="DUMP",o[o.SEI=2]="SEI",o[o.ENCODE_AND_DECODE=3]="ENCODE_AND_DECODE",o))(dc||{}),Hs=(o=>(o[o.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",o[o.NTP_TO_AUDIO_FRAME=1]="NTP_TO_AUDIO_FRAME",o[o.DUMP=2]="DUMP",o[o.ENCODE_AND_DECODE=3]="ENCODE_AND_DECODE",o))(Hs||{}),A_=(r=>(r.WebRTC="webrtc",r.WebCodecs="webcodecs",r.WebAssembly="webassembly",r))(A_||{}),Vm=(f=>(f[f.SUCCESS=0]="SUCCESS",f[f.FAILED=1]="FAILED",f[f.WEBCODEC_INIT=2]="WEBCODEC_INIT",f[f.WEBCODEC_CONFIG_NOT_SUPPORT=3]="WEBCODEC_CONFIG_NOT_SUPPORT",f[f.WEBCODEC_DECODER_ERROR=4]="WEBCODEC_DECODER_ERROR",f[f.WEBCODEC_TRACK_MUTE=5]="WEBCODEC_TRACK_MUTE",f[f.WASM_INIT=6]="WASM_INIT",f[f.WASM_WEBGL_UNAVALIABLE=7]="WASM_WEBGL_UNAVALIABLE",f[f.WASM_DECODER_ERROR=8]="WASM_DECODER_ERROR",f[f.WASM_TRACK_MUTE=9]="WASM_TRACK_MUTE",f[f.TEST=10]="TEST",f[f.RENDER_2D_ERROR=11]="RENDER_2D_ERROR",f))(Vm||{}),uc=(o=>(o.NONE="",o.DETAIL="detail",o.MOTION="motion",o.TEXT="text",o))(uc||{}),Xo=(s=>(s.INTERVAL="interval",s.TIMEOUT="timeout",s.RAF="raf",s.RIC="ric",s.INTERVAL_IN_WORKER="intervalInWorker",s))(Xo||{}),Nu=(e=>(e.CANVAS="canvas",e.API="api",e))(Nu||{}),Bm=(o=>(o[o.NONE=0]="NONE",o[o.MICROPHONE=1]="MICROPHONE",o[o.CAMERA=2]="CAMERA",o[o.BOTH=3]="BOTH",o))(Bm||{}),Du=(e=>(e.CAMERA="camera",e.MICROPHONE="microphone",e))(Du||{}),lc=(r=>(r[r.none=0]="none",r[r.horizontal=1]="horizontal",r[r.vertical=2]="vertical",r))(lc||{});var _t={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"},Wr={AVOID_REPEATED_CALL(i){return`previous ${i.name}() is ongoing, please avoid repeated calls.`},INVALID_PARAMETER_REQUIRED({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' is a required param when calling ${e}(), received: ${r}.`},INVALID_PARAMETER_TYPE({key:i,rule:t,fnName:e,value:r}){let o=`${i||t.name}`,s="";return Array.isArray(t.type)?s=t.type.join("|"):s=t.type,`'${o}' must be type of ${s} when calling ${e}(), received type: ${Xt(r)}.`},INVALID_PARAMETER_EMPTY({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' cannot be '${r}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:i,rule:t,fnName:e,value:r}){let o=`${i||t.name}`,s=`${t.instanceOf.name||t.instanceOf}`;return`'${o}' must be instanceof ${s} when calling ${e}(), received type: ${Xt(r)}.`},INVALID_PARAMETER_RANGE({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' must be one of ${t.values.join("|")} when calling ${e}(), received: ${r}.`},INVALID_PARAMETER_MIN({key:i,rule:t,fnName:e,value:r}){return`the min value of ${i||t.name} is ${t.min}, received: ${r}.`},INVALID_PARAMETER_MAX({key:i,rule:t,fnName:e,value:r}){return`the max value of ${i||t.name} is ${t.max}, received: ${r}.`},API_CALL_TIMEOUT(i){return`${i.commandDesc||i.command} timeout observed.`},SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED(i){return`SignalChannel setup failure: (errorCode: ${i.errorCode}, errorMsg: ${i.errorMsg} }).`},ERROR_MESSAGE(i){let t=`${i.type} failed`;return i.message&&(t=`${t}: ${i.message}.`),t},EXCHANGE_SDP_TIMEOUT:"exchange sdp timeout.",DOWNLINK_RECONNECTION_FAILED:"downlink reconnection failed, please check your network and re-join room.",EXCHANGE_SDP_FAILED(i){return`exchange sdp failed ${i.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(i){return`'${i}' must be validate string when useStringRoomId is true.`},INVALID_ROOMID_INTEGER(i){return`'${i}' 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:i,code:t}){return`Failed to join room - ${i} code: ${t}`},REJOIN_ROOM_FAILED(i){return`reJoin room: ${i.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(i){return`duplicate ${i} stream publishing, please unpublish your prev ${i} 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:i,userId:t,streamType:e}){return`failed to subscribe ${t} ${e} stream, reason: ${i}.`},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(i){return`switchRole failed, errCode: ${i.code} errMsg: ${i.message}.`},CLIENT_BANNED(i){return`client was banned because of ${i.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(i){return`startPublishCDNStream failed, errMsg: ${i.message}.`},STOP_PUBLISH_CDN_FAILED(i){return`stopPublishCDNStream failed, errMsg: ${i.message}.`},INVALID_STREAM_ID(i){return`'${i}' 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(i){return`cannot replace ${i.kind} track because stream has not ${i.kind} track`},NOT_BUG_PACKAGE:"You need to buy packages, refer to tencent console.",START_MIX_TRANSCODE_FAILED(i){return`startMixTranscode failed, errMsg: ${i.message}.`},STOP_MIX_TRANSCODE_FAILED(i){return`stopMixTranscode failed, errMsg: ${i.message}.`},MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO({key:i,rule:t,fnName:e,value:r}){return`'${i||t.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(i){return`'${i}' 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:i,fnName:t})=>`'${i}' is not found in the document object when calling ${t}().`,INVALID_ELEMENT_ID_TYPE:({key:i,fnName:t,type:e})=>`the element corresponding to '${i}' must be instanceof HTMLElement when calling ${t}(), received: ${e}.`,PLAY_FAILED:i=>`${i.media} play failed, browser exception: ${i.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(i){return`${i}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(i){return`${i.signalResponse} failed, response code is ${i.code} , errMsg: ${i.message}.`},CATCH_HANDLER_ERROR({name:i,event:t}){return`an error was caught in ${i}.on('${t}', handler), please check your code in 'handler'.`},API_NOT_EXIST({name:i}){return`experimental api ${i} does not exist.`},REPEAT_JOIN:i=>"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:i}){return`failed to call ${i}() because client was destroyed.`},SEI_NOT_SUPPORT:i=>`not support to sendSEIMessage${i===!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:i,name:t,timesInSecond:e,maxSizeInSecond:r})=>`api ${t} call ${i?"size":"times"} is over ${i?`${r} bytes`:e} in a second.`,CONNECTION_ABORTED(i){return`connection aborted due to: ${i}`},API_CALL_ABORTED(i){let t;return i.message.includes("REMOTE_STREAM_NOT_EXIST")?t=`Subscribe ${i.userId} ${i.streamType} stream aborted, reason: remote user ${i.userId} unpublished stream.`:t=`API aborted, reason: ${i.message}`,t},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:i=>`'streamType' is required when 'userId' is not '*', calling ${i}()`};var v_=(i,t)=>t?`${Br}/${i}/${t}`:`${Br}/${i}/index.html`;var wI=()=>{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 i=localStorage==null?void 0:localStorage.getItem($h);if(i){i=JSON.parse(i);let t=document.createElement("script");t.type="text/javascript",t.text=i.message,document.body.appendChild(t);let e=window.TRTC_ERROR_INFO,r=window.TRTC_ERROR_LINK;return document.body.removeChild(t),{TRTC_ERROR_INFO:e,TRTC_ERROR_LINK:r}}return{}};function Et(i){let{key:t,data:e,link:r,addDocLink:o=!0}=i,s="",n="",a="";Rt(Wr[t])?s=Wr[t](e):nt(Wr[t])&&(s=Wr[t]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:d}=wI();r?a=`${r.className}.html#${r.fnName}`:d&&d[t]&&(Rt(d[t])?a=d[t](e):nt(d[t])&&(a=d[t]));let m=s;return _i()&&(c&&c[t]&&(Rt(c[t])?n=c[t](e):nt(c[t])&&(n=c[t])),n&&(o?m=`${n}
|
|
6
|
-
\u8BF7\u67E5\u770B\u6587\u6863: ${v_("zh-cn",a)}
|
|
3
|
+
`}});var _p=Ui(yi=>{"use strict";var io=mp(),ET=fp(),ST=dc();yi.grammar=ST;yi.write=ET;yi.parse=io.parse;yi.parseParams=io.parseParams;yi.parseFmtpConfig=io.parseFmtpConfig;yi.parsePayloads=io.parsePayloads;yi.parseRemoteCandidates=io.parseRemoteCandidates;yi.parseImageAttributes=io.parseImageAttributes;yi.parseSimulcastStreamList=io.parseSimulcastStreamList});var Qh=Ui((_B,n_)=>{"use strict";var s_=n_.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(o){return o.encoding?"rtpmap:%d %s/%s/%s":o.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(o){return o.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(o){return o.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(o){return"extmap:%d"+(o.direction?"/%s":"%v")+(o["encrypt-uri"]?" %s":"%v")+" %s"+(o.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(o){return o.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(o){var i="candidate:%s %d %s %d %s %d typ %s";return i+=o.raddr!=null?" raddr %s rport %d":"%v%v",i+=o.tcptype!=null?" tcptype %s":"%v",o.generation!=null&&(i+=" generation %d"),i+=o["network-id"]!=null?" network-id %d":"%v",i+=o["network-cost"]!=null?" network-cost %d":"%v",i}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(o){var i="ssrc:%d";return o.attribute!=null&&(i+=" %s",o.value!=null&&(i+=":%s")),i}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(o){return o.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(o){return o.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(o){return"imageattr:%s %s %s"+(o.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(o){return"simulcast:%s %s"+(o.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(o){return"ts-refclk:%s"+(o.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(o){var i="mediaclk:";return i+=o.id!=null?"id=%s %s":"%v%s",i+=o.mediaClockValue!=null?"=%s":"",i+=o.rateNumerator!=null?" rate=%s":"",i+=o.rateDenominator!=null?"/%s":"",i}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(s_).forEach(function(o){var i=s_[o];i.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var d_=Ui(dr=>{"use strict";var vs=function(o){return String(Number(o))===o?Number(o):o},iI=function(o,i,e,t){if(t&&!e)i[t]=vs(o[1]);else for(var r=0;r<e.length;r+=1)o[r+1]!=null&&(i[e[r]]=vs(o[r+1]))},rI=function(o,i,e){var t=o.name&&o.names;o.push&&!i[o.push]?i[o.push]=[]:t&&!i[o.name]&&(i[o.name]={});var r=o.push?{}:t?i[o.name]:i;iI(e.match(o.reg),r,o.names,o.name),o.push&&i[o.push].push(r)},a_=Qh(),oI=RegExp.prototype.test.bind(/^([a-z])=(.*)/);dr.parse=function(o){var i={},e=[],t=i;return o.split(/(\r\n|\r|\n)/).filter(oI).forEach(function(r){var s=r[0],n=r.slice(2);s==="m"&&(e.push({rtp:[],fmtp:[]}),t=e[e.length-1]);for(var a=0;a<(a_[s]||[]).length;a+=1){var c=a_[s][a];if(c.reg.test(n))return rI(c,t,n)}}),i.media=e,i};var c_=function(o,i){var e=i.split(/=(.+)/,2);return e.length===2?o[e[0]]=vs(e[1]):e.length===1&&i.length>1&&(o[e[0]]=void 0),o};dr.parseParams=function(o){return o.split(/;\s?/).reduce(c_,{})};dr.parseFmtpConfig=dr.parseParams;dr.parsePayloads=function(o){return o.toString().split(" ").map(Number)};dr.parseRemoteCandidates=function(o){for(var i=[],e=o.split(" ").map(vs),t=0;t<e.length;t+=3)i.push({component:e[t],ip:e[t+1],port:e[t+2]});return i};dr.parseImageAttributes=function(o){return o.split(" ").map(function(i){return i.substring(1,i.length-1).split(",").reduce(c_,{})})};dr.parseSimulcastStreamList=function(o){return o.split(";").map(function(i){return i.split(",").map(function(e){var t,r=!1;return e[0]!=="~"?t=vs(e):(t=vs(e.substring(1,e.length)),r=!0),{scid:t,paused:r}})})}});var u_=Ui((TB,l_)=>{"use strict";var Yh=Qh(),sI=/%[sdv%]/g,nI=function(o){var i=1,e=arguments,t=e.length;return o.replace(sI,function(r){if(i>=t)return r;var s=e[i];switch(i+=1,r){case"%%":return"%";case"%s":return String(s);case"%d":return Number(s);case"%v":return""}})},ta=function(o,i,e){var t=i.format instanceof Function?i.format(i.push?e:e[i.name]):i.format,r=[o+"="+t];if(i.names)for(var s=0;s<i.names.length;s+=1){var n=i.names[s];i.name?r.push(e[i.name][n]):r.push(e[i.names[s]])}else r.push(e[i.name]);return nI.apply(null,r)},aI=["v","o","s","i","u","e","p","c","b","t","r","z","a"],cI=["i","c","b","a"];l_.exports=function(o,i){i=i||{},o.version==null&&(o.version=0),o.name==null&&(o.name=" "),o.media.forEach(function(s){s.payloads==null&&(s.payloads="")});var e=i.outerOrder||aI,t=i.innerOrder||cI,r=[];return e.forEach(function(s){Yh[s].forEach(function(n){n.name in o&&o[n.name]!=null?r.push(ta(s,n,o)):n.push in o&&o[n.push]!=null&&o[n.push].forEach(function(a){r.push(ta(s,n,a))})})}),o.media.forEach(function(s){r.push(ta("m",Yh.m[0],s)),t.forEach(function(n){Yh[n].forEach(function(a){a.name in s&&s[a.name]!=null?r.push(ta(n,a,s)):a.push in s&&s[a.push]!=null&&s[a.push].forEach(function(c){r.push(ta(n,a,c))})})})}),r.join(`\r
|
|
4
|
+
`)+`\r
|
|
5
|
+
`}});var Zh=Ui(lr=>{"use strict";var Co=d_(),dI=u_();lr.write=dI;lr.parse=Co.parse;lr.parseParams=Co.parseParams;lr.parseFmtpConfig=Co.parseFmtpConfig;lr.parsePayloads=Co.parsePayloads;lr.parseRemoteCandidates=Co.parseRemoteCandidates;lr.parseImageAttributes=Co.parseImageAttributes;lr.parseSimulcastStreamList=Co.parseSimulcastStreamList});import D4 from"webrtc-adapter";var Yf=Je(at());var gm=(F=>(F[F.INVALID_PARAMETER=4096]="INVALID_PARAMETER",F[F.INVALID_OPERATION=4097]="INVALID_OPERATION",F[F.NOT_SUPPORTED=4098]="NOT_SUPPORTED",F[F.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",F[F.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",F[F.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",F[F.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",F[F.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",F[F.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",F[F.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",F[F.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",F[F.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",F[F.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",F[F.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",F[F.CLIENT_BANNED=16448]="CLIENT_BANNED",F[F.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",F[F.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",F[F.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",F[F.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",F[F.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",F[F.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",F[F.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",F[F.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",F[F.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",F[F.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",F[F.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",F[F.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",F[F.API_CALL_ABORTED=16461]="API_CALL_ABORTED",F[F.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",F[F.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",F[F.SWITCH_ROOM_FAILED=16464]="SWITCH_ROOM_FAILED",F[F.VIDEO_ENCODE_FAILED=16465]="VIDEO_ENCODE_FAILED",F[F.AUDIO_ENCODE_FAILED=16466]="AUDIO_ENCODE_FAILED",F[F.UNKNOWN=65535]="UNKNOWN",F))(gm||{}),I=gm;var sg=function(o){for(let i in I)if(I[i]===o)return i;return"UNKNOWN"},ws=class extends Error{constructor({name:e="RtcError",message:t,code:r=I.UNKNOWN,extraCode:s=0,constraint:n}){let a=`<${sg(r)} 0x${r.toString(16)}>`,c=`${t}${n?` constraint: ${n}`:""}${t!=null&&t.includes(a)?"":` ${a}`}`;super(c);d(this,"code");d(this,"extraCode");d(this,"message");d(this,"originMessage");d(this,"name");d(this,"constraint");this.code=r,this.extraCode=s,this.name=e,this.message=c,this.constraint=n,this.originMessage=t}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},D=ws;var Gd=0,Tm=!0,da=function(o){Gd=o;let i=new Date;i.setTime(i.getTime()+o),R[Tm?"info":"debug"](`baseTime from server: ${i} offset: ${o}`),Tm=!1},Em=function(){return Gd},Bi=function(){return Date.now()+Gd},la=function(){let o=new Date;return o.setTime(Bi()),o.toLocaleString()},Do=function(o){let i=String(o.getMilliseconds());return"padStart"in String.prototype&&(i=i.toString().padStart(3,"0")),`${o.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")}:${i}`};var vt={};Vi(vt,{REPORT_TYPE:()=>Wo,buildSSOPackage:()=>Gi,bytes2ms:()=>Om,calculateScaleResolutionDownNumber:()=>$o,concatArrayBuffers:()=>ka,convertObjectNumberToInt:()=>qs,copyProperties:()=>Dm,deepClone:()=>Gr,deepCloneBasic:()=>ya,deepMerge:()=>ti,delay:()=>Ke,fibonacci:()=>qr,formatedTime:()=>Bm,getConstructorName:()=>Uo,getContainerFromElement:()=>Vm,getEnv:()=>bm,getFirst16Bits:()=>Hm,getInternalVersion:()=>xm,getLast16Bits:()=>Pa,getLoggerUrl:()=>Wi,getMediaStreamTrackInfo:()=>Ma,getMuteStateFromFlag:()=>ei,getNetworkType:()=>ba,getNumNetworkType:()=>Jr,getReconnectionTimeout:()=>Kt,getStringByteLength:()=>Js,getTurnServer:()=>Um,getUint32Version:()=>Na,getValueType:()=>Oe,getViewListFromView:()=>Fo,glog:()=>_l,ipv4ToUint32:()=>Bo,isArray:()=>Ae,isAudioWorkletSupported:()=>wm,isBoolean:()=>me,isConstructor:()=>jr,isEmpty:()=>Vo,isFunction:()=>ue,isLangChinese:()=>Zt,isMediaStreamTrack:()=>km,isNumber:()=>Q,isObject:()=>yt,isOverseaSdkAppId:()=>Vt,isPlainObject:()=>dt,isPortrait:()=>gl,isPromise:()=>Tr,isRemoteTrack:()=>Pm,isRotate90Or270:()=>bt,isSetSinkIdSupported:()=>Lm,isString:()=>ie,isUndefined:()=>T,loadImage:()=>Ho,loadVideo:()=>Fm,ms2bytes:()=>Mm,ms2samples:()=>fl,normalizeUrl:()=>Oa,performanceNow:()=>U,promiseAny:()=>Xr,samples2ms:()=>pl,setNetworkTypeFromWebRTC:()=>va,stringify:()=>_t,stringifyIncludeValue:()=>Gs,throttlePromise:()=>Da});var ol={};Vi(ol,{AUDIO_MUTE_BIT:()=>Ta,AUDIO_STAT_BIT:()=>_r,AUX_STAT_BIT:()=>Fr,AUX_STREAM_MSID:()=>Yd,BACKEND_ENV:()=>ga,BASE_DOC_URL:()=>ft,BASE_HOST:()=>Sm,CAPABILITIES_KEYS:()=>Ia,CLASS_NAME:()=>vg,CLOUD_CONSOLE_URL:()=>dg,CROSS_ROOM_BIT:()=>Qd,DATA_FREEZE_TIMING:()=>Sa,DOC_BILLING_CN:()=>ua,DOC_BILLING_OVERSEA:()=>ha,DOC_URL:()=>lg,DTLS_STATE_UNKNOWN:()=>Yt,ENV_NAME:()=>Fi,EXCHANGE_SDP_TIMEOUT:()=>il,IS_WORKER:()=>Oo,IS_WORKLET:()=>xs,KIBANA_EVENT:()=>Ze,LOCAL_STREAM_PUBLISH_STATE:()=>Am,LOGGER_CMD_TYPE:()=>mr,LOGGER_DOMAIN:()=>qd,LOGGER_DOMAIN_OVERSEA:()=>jd,LOG_LEVEL:()=>zt,LOG_LEVEL_NAME:()=>Dg,MAIN_STREAM_MSID:()=>Bs,MAX_RTT:()=>$s,MICROPHONE_COMMUNICATIONS:()=>Ng,MICROPHONE_DEFAULT:()=>Wr,MUTE_ALL_BIT:()=>mg,NAME:()=>p,NETWORK_TYPE:()=>ma,NOT_SUPPORTED_H264:()=>Hr,PAUSED_RETRY_COUNT:()=>$r,PEERCONNECTION_CONNECTING_TIMEOUT:()=>Fs,PEER_CONNECTION_STATE:()=>Re,PEER_LEAVE_REASON:()=>rl,RECOVER_CAPTURE_INTERVAL:()=>Po,REMOTE_STREAM_TYPE_AUX:()=>Kd,REMOTE_STREAM_TYPE_MAIN:()=>Zd,RENDER_FREEZE_TIMING:()=>Cg,SCHEDULE_DOMAIN:()=>$i,SCHEDULE_TIMEOUT:()=>bg,SDP_SEMANTICS_PLAN_B:()=>Mo,SDP_SEMANTICS_UNIFIED_PLAN:()=>gr,SECOND_HOST:()=>ag,SIGNAL_PING_PONG_INTERVAL:()=>hg,SIGNAL_PING_TIMEOUT:()=>ug,SIGNAL_RECONNECTION_COUNT:()=>Ig,SMALL_STAT_BIT:()=>Vs,SPEAKER_DEFAULT:()=>Hs,STORAGE_EXPIRES_TIME:()=>pa,STREAM_TYPE_BIG:()=>Rg,STREAM_TYPE_SMALL:()=>yg,SUBSCRIBE_SMALL_RETRY_COUNT:()=>ko,SYNC_USER_LIST_INTERVAL:()=>Ag,Scene:()=>Si,THIRD_HOST:()=>cg,TRANSPORT_DIRECTION:()=>se,TRTC_ERROR_ASSISTANCE:()=>Xd,TRTC_QUALITY_BAD:()=>Tg,TRTC_QUALITY_DISCONNECTED:()=>Sg,TRTC_QUALITY_EXCELLENT:()=>fg,TRTC_QUALITY_GOOD:()=>_g,TRTC_QUALITY_POOR:()=>gg,TRTC_QUALITY_UNKNOWN:()=>pg,TRTC_QUALITY_VERY_BAD:()=>Eg,UPDATE_OFFER_TIMEOUT:()=>tl,VIDEO_MUTE_BIT:()=>Ea,VIDEO_STAT_BIT:()=>fr,audioProfileMap:()=>fa,defaultBigVideoProfile:()=>pr,defaultSmallVideoProfile:()=>zd,getRetryCount:()=>Hi,getScriptDir:()=>ng,innerVersion:()=>Ls,loggerProxy:()=>Us,screenProfileMap:()=>_a,setLoggerProxy:()=>Br,setRetryCount:()=>el,setVersion:()=>Jd,version:()=>$e,videoProfileMap:()=>Qt});var Ls="4.15.00.1600",$e="5.0.0";function Jd(o){$e=o;let[i,e,t]=o.split(".").map(r=>parseInt(r,10));Ls=`${i}.${Math.min(15,e)}.${Math.min(15,t)}.${e.toString().padStart(2,"0")}${t.toString().padStart(2,"0")}`}var Oo=typeof importScripts!="undefined",xs=typeof registerProcessor!="undefined",ng=()=>{let o=Oo?self.location.href:document.currentScript.src;return o.substring(0,o.lastIndexOf("/")+1)},Us="",Br=o=>Us=o,Sm="web.sdk.qcloud.com",ag="web.sdk.tencent.cn",cg="web.sdk.cloud.tencent.cn",dg="https://console.cloud.tencent.com/trtc",ft=`https://${Sm}/trtc/webrtc/doc`,lg=`${ft}/zh-cn/`,ua="https://cloud.tencent.com/document/product/647/85386",ha="https://trtc.io/document/56025",qd="https://yun.tim.qq.com",jd="https://apisgp.my-imcloud.com",Xd="trtc_error_assistance",mr={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},Fi={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},zt=(n=>(n[n.TRACE=0]="TRACE",n[n.DEBUG=1]="DEBUG",n[n.INFO=2]="INFO",n[n.WARN=3]="WARN",n[n.ERROR=4]="ERROR",n[n.NONE=5]="NONE",n))(zt||{}),ug=18e3,hg=2e3,ma={unknown:0,wifi:1,"4g":2,"3g":3,"2g":4,wired:5,"5g":6},pa=7*24*3600*1e3,fa={standard:{sampleRate:48e3,channelCount:1,bitrate:40},"standard-stereo":{sampleRate:48e3,channelCount:2,bitrate:64},high:{sampleRate:48e3,channelCount:1,bitrate:128},"high-stereo":{sampleRate:48e3,channelCount:2,bitrate:192}},Qt={"120p":{width:160,height:120,frameRate:15,bitrate:200},"120p_2":{width:160,height:120,frameRate:15,bitrate:100},"180p":{width:320,height:180,frameRate:15,bitrate:350},"180p_2":{width:320,height:180,frameRate:15,bitrate:150},"240p":{width:320,height:240,frameRate:15,bitrate:400},"240p_2":{width:320,height:240,frameRate:15,bitrate:200},"360p":{width:640,height:360,frameRate:15,bitrate:800},"360p_2":{width:640,height:360,frameRate:15,bitrate:400},"480p":{width:640,height:480,frameRate:15,bitrate:900},"480p_2":{width:640,height:480,frameRate:15,bitrate:500},"720p":{width:1280,height:720,frameRate:15,bitrate:1500},"1080p":{width:1920,height:1080,frameRate:15,bitrate:2e3},"1440p":{width:2560,height:1440,frameRate:30,bitrate:4860},"4K":{width:3840,height:2160,frameRate:30,bitrate:9e3}},pr=Qt["480p_2"],zd=Qt["120p_2"],_a={"480p":{width:640,height:480,frameRate:5,bitrate:900},"480p_2":{width:640,height:480,frameRate:30,bitrate:1e3},"720p":{width:1280,height:720,frameRate:5,bitrate:1200},"720p_2":{width:1280,height:720,frameRate:30,bitrate:3e3},"1080p":{width:1920,height:1080,frameRate:5,bitrate:1600},"1080p_2":{width:1920,height:1080,frameRate:30,bitrate:4e3}},p={CANVAS:"canvas",AUDIO:"audio",VIDEO:"video",SCREEN:"screen",SMALL:"small",BIG:"big",AUXILIARY:"auxiliary",SMALL_VIDEO:"smallVideo",FACING_MODE_USER:"user",FACING_MODE_ENVIRONMENT:"environment",MUTE:"mute",UNMUTE:"unmute",ENDED:"ended",PLAYING:"playing",PAUSE:"pause",ERROR:"error",LOADEDDATA:"loadeddata",LOADEDMETADATA:"loadedmetadata",AUDIO_INPUT:"audioinput",VIDEO_INPUT:"videoinput",DETAIL:"detail",TEXT:"text",MAIN:"main",BACKUP:"backup",BANNED:"banned",KICK:"kick",USER_TIME_OUT:"user_time_out",ROOM_DISBAND:"room_disband",SEI_MESSAGE:"sei-message",ADD:"add",REMOVE:"remove",REPLACE:"replace",TRACK:"track",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",TRANSCEIVER_DIRECTION_SENDONLY:"sendonly",TRANSCEIVER_DIRECTION_RECVONLY:"recvonly",ENTER_PICTURE_IN_PICTURE:"enterpictureinpicture",LEAVE_PICTURE_IN_PICTURE:"leavepictureinpicture",RESIZE:"resize",TIME_UPDATE:"timeupdate"},se={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},ga={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},Si=(e=>(e.LIVE="live",e.RTC="rtc",e))(Si||{}),fr=1,Vs=2,Fr=4,_r=8,Ta=64,Ea=16,mg=112,Qd=128,Bs="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",Yd="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",Zd=p.MAIN,Kd=p.AUXILIARY,pg=0,fg=1,_g=2,gg=3,Tg=4,Eg=5,Sg=6,Yt="unknown",Re={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},Im=1/0;function el(o){Im=o}function Hi(){return Im}var Ig=30,Ze={JOIN:"join",DELTA_JOIN:"delta-join",REJOIN:"rejoin",LEAVE:"leave",DELTA_LEAVE:"delta-leave",PUBLISH:"publish",DELTA_PUBLISH:"delta-publish",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",UPLINK_CONNECTION:"uplink-connection",UPLINK_RECONNECTION:"uplink-reconnection",DOWNLINK_CONNECTION:"downlink-connection",DOWNLINK_RECONNECTION:"downlink-reconnection",ON_TRACK:"ontrack",ICE_CONNECTION_STATE:"iceConnectionState",LOCAL_STREAM_INITIALIZE:"stream-initialize",SIGNAL_CONNECTION:"websocketConnectionState",SIGNAL_RECONNECTION:"websocketReconnectionState",UPDATE_STREAM:"update-stream",RECOVER_LOCAL_AUDIO_TRACK:"recover-local-audio-track",RECOVER_LOCAL_VIDEO_TRACK:"recover-local-video-track",RECOVER_SUBSCRIPTION:"recover-subscription",START_MIX_TRANSCODE:"start-mix-transcode",STOP_MIX_TRANSCODE:"stop-mix-transcode",PLAYER_ERROR:"player-error",SCHEDULE:"schedule",LOAD_WORKLET:"load-worklet",VIDEO_FROZEN_COUNT:"videoFrozenCount",GET_USER_MEDIA_RETRY:"getUserMedia-retry",VIDEO_ENCODE_FAILED_DURING_CALL:"video-encode-failed-during-call",AUDIO_ENCODE_FAILED_DURING_CALL:"audio-encode-failed-during-call"},Ag=1e4,tl=1e4,il=1e4,gr="unified-plan",Mo="plan-b",Hr=1028,Am=(t=>(t[t.UNPUBLISH=-1]="UNPUBLISH",t[t.PUBLISHING=0]="PUBLISHING",t[t.PUBLISHED=1]="PUBLISHED",t))(Am||{}),Sa=500,Cg=1e3,Rg=p.BIG,yg=p.SMALL,Fs=10*1e3,$i={MAIN:"schedule.cloud-rtc.com",BACKUP:"schedule.cloud-rtc.net",MAIN_OVERSEA:"schedule.rtc-web.com",BACKUP_OVERSEA:"schedule.rtc-web.io",MAIN_OVERSEA_BACKUP:"intl-schedule.cloud-rtc.com"},bg=2e3,vg={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},$r=5,Wr="default",Hs=Wr,Ng="communications",Dg=Object.keys(zt),rl=["normal leave","timeout leave","kick","role change"],ko=10,Po=2e3,Ia=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],$s=10*1e3;var Og=function(o,i,e,t){function r(s){return s instanceof e?s:new e(function(n){n(s)})}return new(e||(e=Promise))(function(s,n){function a(u){try{l(t.next(u))}catch(h){n(h)}}function c(u){try{l(t.throw(u))}catch(h){n(h)}}function l(u){u.done?s(u.value):r(u.value).then(a,c)}l((t=t.apply(o,i||[])).next())})},sl=Symbol(32),nl=Symbol(16),al=Symbol(8),Ii=class{constructor(i){this.g=i,this.consumed=0,i&&(this.need=i.next().value)}setG(i){this.g=i,this.demand(i.next().value,!0)}consume(){this.buffer&&this.consumed&&(this.buffer.copyWithin(0,this.consumed),this.buffer=this.buffer.subarray(0,this.buffer.length-this.consumed),this.consumed=0)}demand(i,e){return e&&this.consume(),this.need=i,this.flush()}read(i){return Og(this,void 0,void 0,function*(){return this.lastReadPromise&&(yield this.lastReadPromise),this.lastReadPromise=new Promise((e,t)=>{var r;this.reject=t,this.resolve=n=>{delete this.lastReadPromise,delete this.resolve,delete this.need,e(n)},this.demand(i,!0)||(r=this.pull)===null||r===void 0||r.call(this,i)})})}readU32(){return this.read(sl)}readU16(){return this.read(nl)}readU8(){return this.read(al)}close(){var i;this.g&&this.g.return(),this.buffer&&this.buffer.subarray(0,0),(i=this.reject)===null||i===void 0||i.call(this,new Error("EOF")),delete this.lastReadPromise}flush(){if(!this.buffer||!this.need)return;let i=null,e=this.buffer.subarray(this.consumed),t=0,r=s=>e.length<(t=s);if(typeof this.need=="number"){if(r(this.need))return;i=e.subarray(0,t)}else if(this.need===sl){if(r(4))return;i=e[0]<<24|e[1]<<16|e[2]<<8|e[3]}else if(this.need===nl){if(r(2))return;i=e[0]<<8|e[1]}else if(this.need===al){if(r(1))return;i=e[0]}else if("buffer"in this.need){if("byteOffset"in this.need){if(r(this.need.byteLength-this.need.byteOffset))return;new Uint8Array(this.need.buffer,this.need.byteOffset).set(e.subarray(0,t)),i=this.need}else if(this.g){this.g.throw(new Error("Unsupported type"));return}}else{if(r(this.need.byteLength))return;new Uint8Array(this.need).set(e.subarray(0,t)),i=this.need}return this.consumed+=t,this.g?this.demand(this.g.next(i).value,!0):this.resolve&&this.resolve(i),i}write(i){if(i instanceof Uint8Array?this.malloc(i.length).set(i):"buffer"in i?this.malloc(i.byteLength).set(new Uint8Array(i.buffer,i.byteOffset,i.byteLength)):this.malloc(i.byteLength).set(new Uint8Array(i)),this.g||this.resolve)this.flush();else return new Promise(e=>this.pull=e)}writeU32(i){this.malloc(4).set([i>>24&255,i>>16&255,i>>8&255,i&255]),this.flush()}writeU16(i){this.malloc(2).set([i>>8&255,i&255]),this.flush()}writeU8(i){this.malloc(1)[0]=i,this.flush()}malloc(i){if(this.buffer){let e=this.buffer.length,t=e+i;if(t<=this.buffer.buffer.byteLength-this.buffer.byteOffset)this.buffer=new Uint8Array(this.buffer.buffer,this.buffer.byteOffset,t);else{let r=new Uint8Array(t);r.set(this.buffer),this.buffer=r}return this.buffer.subarray(e,t)}else return this.buffer=new Uint8Array(i),this.buffer}};Ii.U32=sl;Ii.U16=nl;Ii.U8=al;var Mg=128,kg=127,HI=~kg,$I=Math.pow(2,31);function cl(o){let i=new Ii;for(;o>=128;)i.malloc(1)[0]=o&255|Mg,o>>>=7;return i.malloc(1)[0]=o&255,i.buffer||new Uint8Array(0)}function Aa(o,i=0){let e=new Ii,t=i<<3;switch(typeof o){case"boolean":let r=e.malloc(2);r[0]=t,r[1]=o?1:0;break;case"number":e.malloc(1)[0]=t,e.write(cl(o));break;case"string":e.malloc(1)[0]=t|2;let s=new TextEncoder().encode(o);e.write(cl(s.length));let n=e.malloc(s.length);for(let c=0;c<s.length;c++)n[c]=s[c];break;case"object":let a=new Ii;if(Array.isArray(o))for(let c=0;c<o.length;c++){let l=Aa(o[c],c+1);l&&a.write(l)}else{let c=1;for(let l in o){let u=Aa(o[l],c++);u&&a.write(u)}}i===0?a.buffer&&e.write(a.buffer):(e.malloc(1)[0]=t|2,a.buffer&&(e.write(cl(a.buffer.length)),e.write(a.buffer)))}return e.buffer||new Uint8Array(0)}var Ws=class{constructor(){d(this,"buffer");this.buffer=[]}get data(){return this.buffer}get length(){return this.buffer.length}writeInt32(i){this.buffer.push(i>>>24&255),this.buffer.push(i>>>16&255),this.buffer.push(i>>>8&255),this.buffer.push(i&255)}writeInt16(i){this.buffer.push(i>>>8&255),this.buffer.push(i&255)}writeByte(i){this.buffer.push(i&255)}writeBytes(i){for(let e=0;e<i.length;e++)this.buffer.push(i[e])}};function dl(o,i,e){o[e]=i>>>24&255,o[e+1]=i>>>16&255,o[e+2]=i>>>8&255,o[e+3]=i&255}function ct(o,i){return o[i]<<24|o[i+1]<<16|o[i+2]<<8|o[i+3]}function ll(o,i){return o[i]}function wo(o,i,e){return new TextDecoder().decode(Pg(o,i,e))}function Pg(o,i,e){return o.slice(i,i+e)}var ul=0,Ca=2654435769,Ra=16,ml=4,Lo=2,xo=7;function wg(o,i,e,t="AVQualityReportSvc.C2S",r=2e3,s=2,n=30){return{version:r,encryption:s,d2:"",d2Len:0,uinType:n,uin:"",uinLen:0,reqHead:{seqNumber:e,appId:o,appidAtThird:new Uint8Array(0),a2:"",a2Len:0,serviceCmd:t,serviceCmdLen:0,cookie:"",cookieLen:0,imei:"",imeiLen:0,ksid:"",ksidLen:0,clientVersionInfo:"",clientVersionInfoLen:0},busiBuff:i}}function Cm(o,i){let e=new Ws,t=wg(i,o,ul);ul=ul+1&2147483647,e.writeInt32(0),e.writeInt32(t.version),e.writeByte(t.encryption);let r=new TextEncoder().encode(t.d2);e.writeInt32(r.length+4),r&&e.writeBytes(r),e.writeByte(t.uinType);let s=new TextEncoder().encode(t.uin);e.writeInt32(s.length+4),s.length&&e.writeBytes(s);let n=new Ws;n.writeInt32(0),n.writeInt32(t.reqHead.seqNumber),n.writeInt32(t.reqHead.appId),n.writeByte(t.reqHead.appId>>>24&255),n.writeByte(t.reqHead.appId>>>16&255),n.writeByte(t.reqHead.appId>>>8&255),n.writeByte(t.reqHead.appId&255);for(let ae=4;ae<16;ae++)n.writeByte(0);let a=new TextEncoder().encode(t.reqHead.a2);n.writeInt32(a.length+4),a.length&&n.writeBytes(a);let c=new TextEncoder().encode(t.reqHead.serviceCmd);n.writeInt32(c.length+4),c.length&&n.writeBytes(c);let l=new TextEncoder().encode(t.reqHead.cookie);n.writeInt32(l.length+4),l.length&&n.writeBytes(l);let u=new TextEncoder().encode(t.reqHead.imei);n.writeInt32(u.length+4),u.length&&n.writeBytes(u);let h=new TextEncoder().encode(t.reqHead.ksid);n.writeInt32(h.length+4),h.length&&n.writeBytes(h);let m=new TextEncoder().encode(t.reqHead.clientVersionInfo);n.writeInt16(m.length+2),m.length&&n.writeBytes(m);let _=n.length;n.data[0]=_>>>24&255,n.data[1]=_>>>16&255,n.data[2]=_>>>8&255,n.data[3]=_&255,ie(o)&&(o=new TextEncoder().encode(o)),n.writeInt32(o.length+4),o.length&&n.writeBytes(o);let g=new Uint8Array(n.data),E=null;t.encryption===1?E=new TextEncoder().encode(t.uin):t.encryption===2&&(E=new Uint8Array(16)),E&&(g=Lg(g,E)),e.writeBytes(g);let C=new Uint8Array(e.data),k=C.length;return C[0]=k>>>24&255,C[1]=k>>>16&255,C[2]=k>>>8&255,C[3]=k&255,C}function Lg(o,i){let e=o.length,r=(e+1+Lo+xo)%8;r&&(r=8-r);let s=e+1+Lo+xo+r,n=new Uint8Array(s),a=0,c=new Uint8Array(8),l=new Uint8Array(8),u=new Uint8Array(8),h=0;c[0]=Math.floor(Math.random()*256)&248|r,h=1;for(let _=0;_<r;_++)c[h]=Math.floor(Math.random()*256)&255,h+=1;for(let _=0;_<Lo;)if(h<8&&(c[h]=Math.floor(Math.random()*256)&255,h+=1,_+=1),h===8){hl(c,i,l,u,n,a),a+=8,h=0;for(let g=0;g<8;g++)u[g]=n[a-8+g]}let m=0;for(;m<e;)if(h<8&&(c[h]=o[m],h+=1,m+=1),h===8){hl(c,i,l,u,n,a),a+=8,h=0;for(let _=0;_<8;_++)u[_]=n[a-8+_]}for(let _=0;_<xo;)if(h<8&&(c[h]=0,h+=1,_+=1),h===8){hl(c,i,l,u,n,a),a+=8,h=0;for(let g=0;g<8;g++)u[g]=n[a-8+g]}return n}function hl(o,i,e,t,r,s){for(let n=0;n<8;n++)o[n]^=t[n];xg(o,i,r,s);for(let n=0;n<8;n++)r[s+n]^=e[n];for(let n=0;n<8;n++)e[n]=o[n]}function xg(o,i,e,t){let r=ct(o,0),s=ct(o,4),n=[];for(let c=0;c<4;c++)n[c]=ct(i,c*4);let a=0;for(let c=0;c<Ra;c++)a+=Ca,a=a>>>0,r+=(s<<4)+n[0]^s+a^(s>>>5)+n[1],r=r>>>0,s+=(r<<4)+n[2]^r+a^(r>>>5)+n[3],s=s>>>0;dl(e,r,t),dl(e,s,t+4)}var bm=function(){return new URLSearchParams(location.search).get("trtc_env")||""},Vt=o=>Number(o)<14e8,Wi=function(o,i){let e;Us?e=Us:e=Vt(o)?jd:qd;let t=Math.floor(Math.random()*hr(2,31));return`${e}/v5/AVQualityReportSvc/C2S?random=${t}&sdkappid=${o}&cmdtype=${i}`},vm="unknown";function ba(){Vg();let{userAgent:o,connection:i}=navigator,e=(o.match(/NetType\/\S+/)||[])[0]||"";e=e.toLowerCase().replace("nettype/",""),e==="3gnet"&&(e="3g");let t=i&&i.type&&i.type.toLowerCase(),r=i&&i.effectiveType&&i.effectiveType.toLowerCase();return r==="slow-2"&&(r="2g"),t?Nm(t,r):vm}function Ug(){R.warn("netType changed",ba())}var Rm=!1;function Vg(){var o;Rm||(Rm=!0,(o=navigator.connection)==null||o.addEventListener("typechange",Ug))}function Nm(o,i){if(ma[o])return o;switch(o){case"cellular":case"wimax":return i||"unknown";case"ethernet":return"wired";case"none":case"other":default:return"unknown"}}function va(o){vm=Nm(o)}function Jr(){return ma[ba()]}function Dm(o,i){for(let e of Reflect.ownKeys(i))if(e!=="constructor"&&e!=="prototype"&&e!=="name"){let t=Object.getOwnPropertyDescriptor(i,e)||"";Object.defineProperty(o,e,t)}return o}function Om(o,i=48e3){return pl(o/4,i)}function pl(o,i=48e3){return o*1e3/i}function Mm(o,i=48e3){return fl(o,i)*4}function fl(o,i=48e3){return o*i/1e3}var _l=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},Zt=()=>{let o=navigator.language;return o=o.substring(0,2),o==="zh"},dt=function(o){if(!o||typeof o!="object"||Object.prototype.toString.call(o)!="[object Object]")return!1;let i=Object.getPrototypeOf(o);if(i===null)return!0;let e=Object.prototype.hasOwnProperty.call(i,"constructor")&&i.constructor;return typeof e=="function"&&e instanceof e&&Function.prototype.toString.call(e)===Function.prototype.toString.call(Object)};function qr(o,i=1,e=1){return o<=1?e:qr(o-1,e,i+e)}function Kt(o){return o>8?30*1e3:qr(o)*1e3}function Oe(o){return Reflect.apply(Object.prototype.toString,o,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var ue=o=>typeof o=="function",T=o=>typeof o=="undefined",ie=o=>typeof o=="string",Q=o=>typeof o=="number",me=o=>typeof o=="boolean",yt=o=>Oe(o)==="object",Ae=o=>Oe(o)==="array",km=o=>Oe(o)==="MediaStreamTrack".toLowerCase(),Pm=o=>o.isRemote,Tr=o=>Oe(o)==="promise",jr=o=>ue(o)&&o.prototype.constructor===o,Uo=o=>jr(o)?o.prototype.constructor.name:"",wm=typeof AudioWorkletNode!="undefined",Lm=typeof HTMLMediaElement!="undefined"&&"setSinkId"in HTMLMediaElement.prototype;function Xr(o){return new Promise((i,e)=>{let t=[];o.forEach(r=>{r.then(i).catch(s=>{t.push(s),t.length===o.length&&e(t)})})})}function U(){return!performance||!performance.now?Date.now():Math.floor(performance.now())}var ym=o=>+o<10?`0${o}`:o,xm=o=>{let i=o.match(/^\d+\.\d+\.\d+/)[0];if(!i)return o;let e=i.split("."),t=ym(e[1])+ym(e[2]);return e[1]-15>0&&(e[1]="15"),e[2]-15>0&&(e[2]="15"),`${e.join(".")}.${t}`},Bg=Object.prototype.hasOwnProperty,{toString:tA}=Object.prototype;function Vo(o){if(o==null)return!0;if(typeof o=="boolean")return!1;if(typeof o=="number")return o===0;if(typeof o=="string"||typeof o=="function"||Array.isArray(o))return o.length===0;if(o instanceof Error)return o.message==="";if(dt(o))switch(Object.prototype.toString.call(o)){case"[object File]":case"[object Map]":case"[object Set]":return o.size===0;case"[object Object]":{for(let i in o)if(Bg.call(o,i))return!1;return!0}}return!1}function ei(o,i){return{userId:i,hasAudio:!!(o&_r),hasVideo:!!(o&fr),hasAuxiliary:!!(o&Fr),hasSmall:!!(o&Vs),audioMuted:!!(o&Ta),videoMuted:!!(o&Ea),audioAvailable:!!(o&_r)&&!(o&Ta),videoAvailable:!!(o&fr)&&!(o&Ea)}}function Um(o){let i={urls:o.url.startsWith("turn:")||o.url.startsWith("turns:")?o.url:`turn:${o.url}`};return!T(o.username)&&!T(o.credential)&&(i.username=o.username,i.credential=o.credential,i.credentialType="password",T(o.credentialType)||(i.credentialType=o.credentialType)),i}function Bo(o,i=!0){if(!ie(o))return 0;let e=o.split(".");return i?(Number(e[0])<<24|Number(e[1])<<16|Number(e[2])<<8|Number(e[3]))>>>0:(Number(e[3])<<24|Number(e[2])<<16|Number(e[1])<<8|Number(e[0]))>>>0}var ti=function(o,i,e,t){if(!(yt(o)&&yt(i)))return 0;let r=0,s=Object.keys(i),n;for(let a=0,c=s.length;a<c;a++)if(n=s[a],!(T(i[n])||e&&e.includes(n)))if(yt(o[n])&&yt(i[n]))r+=ti(o[n],i[n],e,t);else{if(t&&t.includes(i[n]))continue;o[n]!==i[n]&&(o[n]=Gr(i[n]),r+=1)}return r};function Gr(o){if(Ae(o)){let i=[];return o.forEach((e,t)=>{i[t]=Gr(e)}),i}if(yt(o)){let i={};return Object.keys(o).forEach(e=>{i[e]=Gr(o[e])}),i}return o}var Fo=o=>{let i=[];if(Ae(o))i=[...o];else if(ie(o)){let e=document.getElementById(o);e&&i.push(e)}else o&&i.push(o);return i},Vm=o=>ie(o)?document.getElementById(o):o,Fg=o=>{let i=c=>c<10?`0${c}`:`${c}`,e=o.getFullYear(),t=o.getMonth()+1,r=o.getDate(),s=i(o.getHours()),n=i(o.getMinutes()),a=i(o.getSeconds());return`${e}/${t}/${r} ${s}:${n}:${a}`},Bm=()=>Fg(new Date);function _t(o,{keysToInclude:i,keysToExclude:e}){try{if(Ae(o))return`[${o.map(n=>_t(n,{keysToInclude:i,keysToExclude:e})).join(",")}]`;if(!dt(o)||!Ae(i)&&!Ae(e))return JSON.stringify(o);let t={},r=new Set(i),s=new Set(e);return Object.keys(o).forEach(n=>{(s.size===0&&r.has(n)||r.size===0&&!s.has(n))&&(t[n]=dt(o[n])||Ae(o[n])?JSON.parse(_t(o[n],{keysToExclude:e,keysToInclude:i})):o[n])}),JSON.stringify(t)}catch(t){return"{}"}}function Gs(o,i=!1){let e=[];return Object.keys(o).forEach(t=>{i===o[t]&&e.push(t)}),_t(o,{keysToInclude:e})}function Js(o){return o.replace(/[\u4e00-\u9fa5]/g,"aa").length}var gl=()=>{var o,i,e,t;return(o=window.screen)!=null&&o.orientation?!!((t=(e=(i=window.screen)==null?void 0:i.orientation)==null?void 0:e.type)!=null&&t.includes("portrait")):window.orientation===0||window.orientation===180},Ho=o=>f(void 0,null,function*(){return new Promise((i,e)=>{let t;if(ie(o))t=new Image,t.crossOrigin="anonymous",t.src=o;else if(t=o,t.complete){i(t);return}t.onload=()=>i(t),t.onerror=()=>{e(new D({code:I.INVALID_PARAMETER,message:`load image failed, url: ${o}`}))}})}),Na=o=>{let i=o.split(".");return+i[0]<<24|+i[1]<<16|+i[2]<<8|+i[3]<<0},qs=o=>(Object.keys(o).forEach(i=>{Q(o[i])&&(i.startsWith("uint")||i.startsWith("int"))?o[i]=Math.floor(o[i]):(dt(o[i])||Ae(o[i]))&&qs(o[i])}),o);function Ke(o,i){return new Promise(e=>{let t=setTimeout(e,o);i&&i(t)})}function Da(o,i){let e=null;return function(...t){return e||(e=o.apply(i||this,t),e.finally(()=>e=null),e)}}function Oa(o){return o.replace(/(^|[^:])\/{2,}/g,"$1/")}function Ma(o){var i;try{let{width:e,height:t,frameRate:r,sampleRate:s,sampleSize:n,channelCount:a}=(i=o.getSettings)==null?void 0:i.call(o),c=o.kind===p.AUDIO?`${s}x${n}@${a}`:`${e}x${t}@${r}`,l=o.stats?` stats: ${JSON.stringify(o.stats).replaceAll('"',"")}`:"";return`${o.id} ${o.readyState} muted:${o.muted} ${o.kind} ${o.label} ${c}${l}`}catch(e){return""}}function $o(o,i){return o.width*o.height===i.width*i.height?1:gl()&&i.width>i.height&&o.height>i.width?Math.max(o.width/i.height,o.height/i.width,1):Math.max(o.width/i.width,o.height/i.height,1)}function bt(o){return o===90||o===270}function Fm(o){return f(this,null,function*(){return new Promise((i,e)=>{let t=document.createElement("video");t.crossOrigin="anonymous",t.src=o,t.muted=!0,t.loop=!0,t.playsInline=!0,t.play().then(()=>i(t)),t.onerror=()=>{e(t.error)}})})}function ya(o,i=new WeakMap){if(typeof o!="object"||o===null)return o;if(i.has(o))return i.get(o);if(Array.isArray(o)){let e=[];return i.set(o,e),o.forEach((t,r)=>{e[r]=ya(t,i)}),e}if(Object.prototype.toString.call(o)==="[object Object]"){let e={};return i.set(o,e),Reflect.ownKeys(o).forEach(t=>{e[t]=ya(o[t],i)}),e}return o}var Wo=(t=>(t[t.END_REPORT=2001]="END_REPORT",t[t.LOG=2002]="LOG",t[t.KEY_METRIC_REPORT=2003]="KEY_METRIC_REPORT",t))(Wo||{});function Hg(o,i,e,t){let r={data:o,random:Math.floor(Math.random()*2147483648),sdkAppId:e};return T(t)||(r=L(M({},r),{gzip:+t})),{uint32_sdkappid:0,uint64_from_uin:0,uint32_timestamp:0,uint32_seq:0,msg_common_info:{msg_device_info:{enum_device_type:0,str_device_brand:"",str_device_model:"",str_device_board:"",str_device_cpu_abi:""},msg_system_info:{enum_os_type:0,str_os_version:"",msg_network_info:0},msg_network_info:{enum_network_type:0}},msg_report_content:{uint32_type:i,bytes_report_data:JSON.stringify(r)}}}function Gi(o,i,e,t){try{let r=Hg(o,i,e,t),s=Aa(r);return Cm(s,e)}catch(r){return JSON.stringify(o)}}function ka(o,i){let e=new Uint8Array(o.byteLength+i.byteLength);return e.set(new Uint8Array(o),0),e.set(new Uint8Array(i),o.byteLength),e.buffer}function Pa(o){return(o&65535)>>>0}function Hm(o){return(o&4294901760)>>>0}function $m(o){let i=$g(o);return i==null?void 0:i.busiBuff}function $g(o){try{let i={},e=0;i.totalLength=ct(o,e),e+=4,i.version=ct(o,e),e+=4,i.encryption=ll(o,e),e+=1,i.uinType=ll(o,e),e+=1,i.uinLength=ct(o,e),e+=4,i.uin=i.uinLength>4?wo(o,e,i.uinLength-4):"",e+=i.uinLength-4;let t=o.slice(e);if(i.encryption===2){let r=new Uint8Array(16).fill(0);o=Wg(t,r),i.decrypted=!0,e=0}else o=t,e=0;return i.rspHeadLength=ct(o,e),e+=4,i.seqNo=ct(o,e),e+=4,i.retCode=ct(o,e),e+=4,i.retStrLength=ct(o,e),e+=4,i.retStr=i.retStrLength?wo(o,e,i.retStrLength-4):"",e+=i.retStrLength-4,i.serviceCmdLength=ct(o,e),e+=4,i.serviceCmd=i.serviceCmdLength?wo(o,e,i.serviceCmdLength-4):"",e+=i.serviceCmdLength-4,i.cookieLength=ct(o,e),e+=4,i.cookie=i.cookieLength?wo(o,e,i.cookieLength-4):"",e+=i.cookieLength-4,i.flag=ct(o,e),e+=4,i.busiBuffLength=ct(o,e),e+=4,i.busiBuff=i.busiBuffLength?wo(o,e,i.busiBuffLength-4):"",e+=i.busiBuffLength-4,i}catch(i){}}function Wm(o,i){let e=o[0]<<24|o[1]<<16|o[2]<<8|o[3],t=o[4]<<24|o[5]<<16|o[6]<<8|o[7];e=e>>>0,t=t>>>0;let r=Ca*Ra>>>0;for(let s=0;s<Ra;s++)t-=(e<<ml)+i[2]^e+r^(e>>>5)+i[3],t=t>>>0,e-=(t<<ml)+i[0]^t+r^(t>>>5)+i[1],e=e>>>0,r-=Ca,r=r>>>0;return new Uint8Array([e>>>24&255,e>>>16&255,e>>>8&255,e&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255])}function Wg(o,i){let e=0,t=new Uint8Array(8).fill(0),r=new Uint8Array(o.slice(0,8)),s=Wm(r,i),n=s[0]&7,a=o.length-1-n-Lo-xo,c=new Uint8Array(a),l=0,u=t,h=o.slice(0,8);e=8;let m=1;m+=n;for(let g=1;g<=Lo;)if(m<8)m++,g++;else if(m===8){let E=Tl(o,e,u,h,s,i);u=E.ivPreCrypt,h=E.ivCurCrypt,s=E.debiBuf,e=E.bufPos,m=0}let _=a;for(;_>0;)if(m<8)c[l++]=s[m]^u[m],m++,_--;else if(m===8){let g=Tl(o,e,u,h,s,i);u=g.ivPreCrypt,h=g.ivCurCrypt,s=g.debiBuf,e=g.bufPos,m=0}for(let g=1;g<=xo;)if(m<8)s[m]^u[m],m++,g++;else if(m===8){if(e>=o.length)break;let E=Tl(o,e,u,h,s,i);if(!E.success)break;u=E.ivPreCrypt,h=E.ivCurCrypt,s=E.debiBuf,e=E.bufPos,m=0}return c}function Tl(o,i,e,t,r,s){if(i+8>o.length)return{success:!1};let n=new Uint8Array(t),a=o.slice(i,i+8),c=new Uint8Array(8);for(let u=0;u<8;u++)c[u]=r[u]^a[u];let l=Wm(c,s);return{success:!0,ivPreCrypt:n,ivCurCrypt:a,debiBuf:l,bufPos:i+8}}var Gm=typeof TextDecoder!="undefined"?new TextDecoder:void 0;function Ji({url:o,body:i,method:e="POST",timeout:t,priority:r}){return new Promise((s,n)=>{if("fetch"in window)return fetch(o,{method:e,body:i,priority:r}).then(c=>c.clone().json().then(l=>({data:l}),()=>c.arrayBuffer().then(l=>({data:$m(new Uint8Array(l))||(Gm?Gm.decode(l):l)})))).then(s,n);let a=new XMLHttpRequest;a.onreadystatechange=()=>{if(a.readyState===4)if(a.status>=200&&a.status<300)try{let c=JSON.parse(a.response);s({data:c})}catch(c){s({data:a.response})}else n({status:a.status,statusText:a.statusText||"request failed!"})},a.timeout=t||5e3,a.open(e,o,!0),a.send(i)})}function El(o){return f(this,null,function*(){let i=U(),e=JSON.stringify(o);try{if(!CompressionStream||e.length<=2800)return e;let r=new Blob([e],{type:"application/json"}).stream().pipeThrough(new CompressionStream("gzip")),a=yield(yield(yield new Response(r)).blob()).arrayBuffer();return R.debug(`compressJSON ${e.length} -> ${a.byteLength} ${U()-i}ms`),a}catch(t){return e}})}var Gg=Object.prototype.hasOwnProperty;var Ai=o=>typeof o=="function",gt=o=>typeof o=="undefined";var wa=o=>typeof o=="boolean";var Sl=o=>o.isRemote;var Il=function(o){if(!o||typeof o!="object"||Object.prototype.toString.call(o)!="[object Object]")return!1;let i=Object.getPrototypeOf(o);if(i===null)return!0;let e=Object.prototype.hasOwnProperty.call(i,"constructor")&&i.constructor;return typeof e=="function"&&e instanceof e&&Function.prototype.toString.call(e)===Function.prototype.toString.call(Object)};function Jm(o){if(o==null)return!0;if(typeof o=="boolean")return!1;if(typeof o=="number")return o===0;if(typeof o=="string"||typeof o=="function"||Array.isArray(o))return o.length===0;if(o instanceof Error)return o.message==="";if(Il(o))switch(Object.prototype.toString.call(o)){case"[object File]":case"[object Map]":case"[object Set]":return o.size===0;case"[object Object]":{for(let i in o)if(Gg.call(o,i))return!1;return!0}}return!1}var Jg=0,qg=1,qm=2;function jg({retryFunction:o,settings:i,onError:e,onRetrying:t,onRetryFailed:r,onRetrySuccess:s,context:n}){return function(...a){let{retries:c=5,timeout:l=1e3}=i,u=0,h=-1,m=Jg,_=(g,E)=>f(this,null,function*(){let C=n||this;try{let k=yield o.apply(C,a);u>0&&s&&s.call(this,u),u=0,g(k)}catch(k){let ae=()=>{clearTimeout(h),u=0,m=qm,E(k)},w=()=>{m!==qm&&u<(Ai(c)?c():c)?(u++,m=qg,Ai(t)&&t.call(this,u,ae),h=window.setTimeout(()=>{h=-1,_(g,E)},Ai(l)?l(u):l)):(ae(),Ai(r)&&r.call(this,k))};Ai(e)?e.call(this,{error:k,retry:w,reject:E,retryFuncArgs:a,retriedCount:u}):w()}});return new Promise(_)}}var Ci=jg;var Er=class o{constructor(i){d(this,"_parentPath");d(this,"userId");d(this,"remoteUserId");d(this,"id");d(this,"sdkAppId");d(this,"type");d(this,"isLocal");this.id=i.id,this.userId=i.userId,this.sdkAppId=i.sdkAppId,this.remoteUserId=i.remoteUserId,this.isLocal=wa(i.isLocal)?i.isLocal:!0,this.type=this.isLocal?"":i.type}getFullId(){return this._parentPath&&this.id?`${this._parentPath}-${this.id}`:this._parentPath?this._parentPath:this.id}createChild(i){let e=new o({id:i.id,userId:gt(i.userId)?this.userId:i.userId,sdkAppId:gt(i.sdkAppId)?this.sdkAppId:i.sdkAppId,type:gt(i.type)?this.type:i.type,isLocal:gt(i.isLocal)?this.isLocal:i.isLocal,remoteUserId:gt(i.remoteUserId)?this.remoteUserId:i.remoteUserId});return e.bindParent(this),e}bindParent(i){let e=i.getFullId();this._parentPath!==e&&(this.debug(`bind logger parent: ${i.id}`),this._parentPath=e,this.userId=i.userId||this.userId,this.sdkAppId=i.sdkAppId||this.sdkAppId)}setUserId(i){this.userId=i}setSdkAppId(i){this.sdkAppId=i}log(i,e){let t=this.isLocal?this.userId:this.remoteUserId,r=this.getFullId();e.unshift(`[${this.isLocal?"\u2191":"\u2193"}${this.type&&this.type!=="main"?"*":""}${r}${t?`|${t}`:""}]`),R.log(i,e,gt(this.userId)||Jm(this.userId),this.userId,this.sdkAppId)}info(...i){this.log(2,i)}debug(...i){this.log(1,i)}warn(...i){this.log(3,i)}error(...i){this.log(4,i)}};var es={};Vi(es,{ANDROID_VERSION:()=>xa,CHROME_MAJOR_VERSION:()=>qe,CHROME_VERSION:()=>Ka,EDGE_VERSION:()=>Va,EDG_MAJOR_VERSION:()=>Cl,EDG_VERSION:()=>Ba,ELECTRON_MAJOR_VERSION:()=>Nl,FIREFOX_MAJOR_VERSION:()=>qo,FIREFOX_VERSION:()=>Ua,HUAWEI_VERSION:()=>za,IE_VERSION:()=>Zg,IOS_MAIN_VERSION:()=>et,IOS_VERSION:()=>Tt,IPADQQB_VERSION:()=>ja,IS_ANDROID:()=>_e,IS_ANDROID_WEBVIEW:()=>iT,IS_ANY_SAFARI:()=>Ft,IS_CHROME:()=>Ko,IS_CHROME_OS:()=>Rl,IS_CHROMIUM_BASE:()=>We,IS_DESKTOP_IOS_CHROME:()=>kl,IS_EDG:()=>jo,IS_EDGE:()=>zr,IS_ELECTRON:()=>eT,IS_FIREFOX:()=>te,IS_HEADLESS_CHROME:()=>vl,IS_HONOR:()=>bl,IS_HUAWEI:()=>rn,IS_HUAWEIBROWSER:()=>tn,IS_IE:()=>Qm,IS_IE8:()=>Yg,IS_IOS:()=>Te,IS_IOS_13_OR_14:()=>Ml,IS_IOS_15_1:()=>Ol,IS_IOS_CHROME:()=>js,IS_IPAD:()=>Jo,IS_IPADQQB:()=>Zs,IS_IPAD_PRO:()=>Al,IS_IPHONE:()=>Sr,IS_IPOD:()=>zm,IS_LINUX:()=>Ks,IS_LOCAL:()=>si,IS_MAC:()=>oi,IS_MACQQB:()=>Ys,IS_MIBROWSER:()=>en,IS_MQQB:()=>zo,IS_NATIVE_ANDROID:()=>Qg,IS_OLD_ANDROID:()=>zg,IS_OPENHARMONY:()=>Yo,IS_OPPOBROWSER:()=>Qo,IS_SAFARI:()=>Pe,IS_SAFARI_15_1:()=>rT,IS_SAMSUNGBROWSER:()=>on,IS_SOGOU:()=>zs,IS_SOGOUM:()=>Xs,IS_TBS:()=>ri,IS_UCBROWSER:()=>yl,IS_VIVOBROWSER:()=>sn,IS_WECHAT:()=>ji,IS_WIN:()=>Qr,IS_WQQB:()=>Qs,IS_WX:()=>Kg,IS_X5MQQB:()=>Xo,IS_XWEB:()=>qi,MACQQB_VERSION:()=>qa,MI_VERSION:()=>Xa,MQQB_VERSION:()=>Go,OPENHARMONY_VERSION:()=>tT,OPPO_VERSION:()=>Ya,SAFARI_VERSION:()=>Xi,SAMSUNG_VERSION:()=>Qa,SOGOUM_VERSION:()=>Fa,SOGOU_VERSION:()=>Ha,TBS_VERSION:()=>$a,UA_DATA_STRING:()=>ii,USER_AGENT:()=>Bt,VIVO_VERSION:()=>Za,WECHAT_VERSION:()=>Ga,WQQB_VERSION:()=>Ja,XWEB_VERSION:()=>Wa,browserInfo:()=>Ri,getBrowserCoreNumber:()=>wl,getBrowserInfo:()=>Ym,getChromeMajorVersion:()=>Zo,getDeviceModel:()=>ni,getDeviceModelFromUA:()=>ec,getGPUInfo:()=>Pl,getOSName:()=>tc,getOSNumber:()=>Zr,getOSString:()=>ai,getOSType:()=>oT,getTerminalType:()=>Ll,getUserAgentData:()=>Yr,isLocalStorageEnabled:()=>zi,isMobile:()=>an,isVersionLargerThan:()=>Dl,isVersionSmallerThan:()=>nn});var Bt=typeof navigator=="undefined"?"":navigator.userAgent,K=o=>new RegExp(o,"i").test(Bt),we=o=>{if(K(o)){let i=new RegExp(`${o}\\/([\\d.]+)`),e=Bt.match(i);if(e&&e[1])return e[1]}return""},La=o=>{if(K(o)){let i=new RegExp(`${o}\\/(\\d+)`),e=Bt.match(i);if(e&&e[1])return parseFloat(e[1])}return NaN},jm=/AppleWebKit\/([\d.]+)/i.exec(Bt),Xg=jm?parseFloat(jm[1]):NaN,Jo=K("iPad"),Al=typeof navigator!="undefined"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&K("Macintosh"),Sr=K("iPhone")&&!Jo,zm=K("iPod"),Te=Sr||Jo||zm||Al,_e=K("Android"),xa=function(){if(_e){let o=Bt.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(o){let i=o[1]&&parseFloat(o[1]),e=o[2]&&parseFloat(o[2]);if(i&&e)return parseFloat(`${o[1]}.${o[2]}`);if(i)return i}}return NaN}(),zg=_e&&K("webkit")&&xa<2.3,Qg=_e&&xa<5&&Xg<537,te=K("Firefox"),Ua=we("Firefox"),qo=La("Firefox"),zr=K("Edge"),Va=we("Edge"),jo=K("Edg"),Ba=we("Edg"),Cl=La("Edg"),Xs=K("SogouMobileBrowser"),Fa=we("SogouMobileBrowser"),zs=K("MetaSr\\s"),Ha=we("MetaSr\\s"),ri=K("TBS"),$a=we("TBS"),qi=K("XWEB"),Wa=we("XWEB"),Yg=K("MSIE\\s8\\.0"),Qm=K("MSIE\\/\\d+"),Zg=function(){if(Qm){let o=/MSIE\s(\d+)\.\d/.exec(Bt),i=o&&parseFloat(o[1]);return!i&&/Trident\/7.0/i.test(Bt)&&/rv:11.0/.test(Bt)&&(i=11),i}return NaN}(),ji=K("(micromessenger|webbrowser)"),Ga=we("MicroMessenger"),Xo=!ri&&K("MQQBrowser")&&K("COVC"),zo=!ri&&K("MQQBrowser")&&!K("COVC"),Go=zo||Xo?we("MQQBrowser"):"",Qs=!ri&&K(" QQBrowser"),Ja=we(" QQBrowser"),Ys=!ri&&K("QQBrowserLite"),qa=we("QQBrowserLite"),Zs=!ri&&K("MQBHD"),ja=we("MQBHD"),Qr=K("Windows"),oi=!Te&&K("MAC OS X"),Ks=!_e&&K("Linux"),Rl=K("CrOS"),Kg=K("MicroMessenger"),yl=K("UCBrowser"),eT=K("Electron"),en=K("MiuiBrowser"),Xa=we("MiuiBrowser"),tn=K("HuaweiBrowser"),rn=K("Huawei")||K("HUAWEI"),bl=K("Honor")||K("HONOR"),za=we("HuaweiBrowser"),on=K("SamsungBrowser"),Qa=we("SamsungBrowser"),Qo=K("HeyTapBrowser"),Ya=we("HeyTapBrowser"),sn=K("VivoBrowser"),Za=we("VivoBrowser"),Yo=K("OpenHarmony"),tT=we("OpenHarmony"),Zo=()=>La("Chrome"),js=K("CriOS"),We=K("Chrome"),Ko=!zr&&!zs&&!Xs&&!ri&&!qi&&!jo&&!Qs&&!en&&!tn&&!on&&!Qo&&!sn&&We,vl=K("HeadlessChrome"),qe=Zo(),Ka=we("Chrome"),Nl=La("Electron"),Pe=!We&&!zo&&!Xo&&!Ys&&!Zs&&K("Safari"),Ft=Pe||Te,Xi=we("Version"),iT=/Android.*(wv|.0.0.0)/.test(Bt),Tt=(()=>{if(Al)return Xi;if(Te){let o=Bt.match(/OS (\d+)_(\d+)/i);if(o&&o[1]){let i=o[1];return o[2]&&(i+=`.${o[2]}`),i}}return""})();function nn(o,i){let e=o.split(".").map(r=>Number(r)),t=i.split(".").map(r=>Number(r));for(let r=0;r<Math.max(e.length,t.length);r++){let s=e[r]||0,n=t[r]||0;if(s<n)return!0;if(s>n)return!1}return!1}function Dl(o,i,e=!1){let t=o.split(".").map(s=>Number(s)),r=i.split(".").map(s=>Number(s));for(let s=0;s<Math.max(t.length,r.length);s++){let n=t[s]||0,a=r[s]||0;if(n>a)return!0;if(n<a)return!1}return e}var et=Number(Tt.split(".")[0]),rT=Xi==="15.1",Ol=Tt==="15.1",Ml=(()=>{let o=Number(Tt.split(".")[0]);return o===14||o===13})(),kl=js&&Xi==="11.1.1",si=typeof location=="undefined"?!1:location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1",zi=(()=>{let o;return()=>{if(typeof o=="undefined")try{o=!!window.localStorage}catch(i){o=!1}return o}})(),Ri=Ym();function Ym(){let o=new Map([[te,["Firefox",Ua]],[jo,["Edg",Ba]],[Ko,["Chrome",Ka]],[js,["ChiOS",we("CriOS")]],[Pe&&!js,["Safari",Xi]],[ri,["TBS",$a]],[qi,["XWEB",Wa]],[ji&&Sr,["WeChat",Ga]],[Qs,["QQ(Win)",Ja]],[zo,["QQ(Mobile)",Go]],[Xo,["QQ(Mobile X5)",Go]],[Ys,["QQ(Mac)",qa]],[Zs,["QQ(iPad)",ja]],[en,["MI",Xa]],[tn,["HW",za]],[on,["Samsung",Qa]],[Qo,["OPPO",Ya]],[sn,["VIVO",Za]],[zr,["EDGE",Va]],[Xs,["SogouMobile",Fa]],[zs,["Sogou",Ha]]]),i="unknown",e="unknown";return o.has(!0)&&([i,e]=o.get(!0)),{name:i,version:e}}var pe=null;function an(){return pe&&typeof pe.mobile=="boolean"?pe.mobile:_e||Te||Sr||Jo||Yo}var ii="";function Yr(){return f(this,null,function*(){if(pe)return pe;if(!navigator.userAgentData||typeof navigator.userAgentData.getHighEntropyValues!="function")return null;try{return pe=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]),pe&&!ii&&(ii=`UAData: ${pe.platform}/${pe.platformVersion}`,pe.architecture&&pe.bitness&&(ii+=` ${pe.architecture}/${pe.bitness}`),pe.mobile&&(ii+=" mobile"),pe.model&&(ii+=` model: ${pe.model.replace(/\s+/g,"/")}`),pe.fullVersionList&&(ii+=` ${pe.fullVersionList.filter(o=>o.brand!=="Not/A)Brand").map(o=>`${o.brand}/${o.version}`).join(",")}`)),pe}catch(o){return null}})}function Pl(){try{let o=document.createElement("canvas"),i=o.getContext("webgl")||o.getContext("experimental-webgl");if(!i)return"";let e=i.getExtension("WEBGL_debug_renderer_info");if(e){let t=i.getParameter(e.UNMASKED_VENDOR_WEBGL),r=i.getParameter(e.UNMASKED_RENDERER_WEBGL);return`${t} ${r}`}return""}catch(o){return""}}function ni(){return(pe==null?void 0:pe.model)||ec()||""}function ec(){let o=/;\s*([^;)]+)\s+Build\//,i=Bt.match(o);return i!=null&&i[1]?i[1].trim():null}var Xm=new Map([[_e,"Android"],[Te,"iOS"],[Qr,"Windows"],[oi,"MacOS"],[Ks,"Linux"],[Rl,"ChromeOS"]]),tc=function(){return Xm.get(!0)?Xm.get(!0):pe?pe.platform:"unknown"};function Zr(){return Qr?1:_e?2:oi?3:Te?4:Ks?5:Rl?6:Yo?7:0}function wl(){return ji||qi?4:We?1:Pe?2:te?3:0}var ai=()=>{let o=tc();return pe!=null&&pe.platformVersion?o+=`/${pe.platformVersion}`:Te?o+=`/${Tt}`:_e&&(o+=`/${xa}`),o+=`/${Ri.name}/${Pe&&!js?Ri.version:Ri.version.split(".")[0]}`,pe!=null&&pe.architecture&&(o+=`/${pe.architecture}`),o};function Ll(){return _e?4:Sr?2:Jo?3:oi?12:Qr?5:Ks?13:Yo?22:1}function oT(){return _e?"Android":Sr?"iPhone":Jo?"iPad":oi?"Mac":Qr?"Windows":Ks?"Linux":"unknown"}var Zm=Je(at(),1),sT=new Zm.default,S=sT;var mt=(W=>(W.ROOM_DESTROY="1",W.JOIN_START="21",W.JOIN_SCHEDULE_SUCCESS="22",W.JOIN_SIGNAL_CONNECTION_START="23",W.JOIN_SIGNAL_CONNECTION_END="24",W.JOIN_SEND_CMD="25",W.JOIN_RECEIVED_CMD_RES="26",W.JOIN_SUCCESS="27",W.JOIN_FAILED="28",W.LEAVE_START="51",W.LEAVE_SEND_CMD="52",W.LEAVE_SUCCESS="53",W.PUBLISH_START="61",W.SEND_FIRST_VIDEO_FRAME="62",W.PUBLISH_FAILED="63",W.SUBSCRIBE_START="81",W.SUBSCRIBE_SUCCESS="82",W.SUBSCRIBE_FAILED="84",W.UNSUBSCRIBE_SUCCESS="83",W.LOCAL_TRACK_CAPTURE_START="101",W.LOCAL_TRACK_CAPTURE_SUCCESS="102",W.LOCAL_TRACK_CAPTURE_FAILED="103",W.LOCAL_TRACK_PUBLISHED="104",W.LOCAL_TRACK_UNPUBLISHED="105",W.LOCAL_TRACK_REPLACED="106",W.SWITCH_DEVICE_SUCCESS="107",W.TRACK_MUTED="108",W.TRACK_UNMUTED="109",W.REMOTE_TRACK_SUBSCRIBED="110",W.REMOTE_TRACK_UNSUBSCRIBED="111",W.LOCAL_TRACK_RECAPTURE="112",W.LOCAL_AUDIO_STARTED="113",W.LOCAL_AUDIO_STOPPED="114",W.REMOTE_AUDIO_STARTED="115",W.REMOTE_AUDIO_STOPPED="116",W.PLAY_TRACK_START="151",W.PLAYER_STATE_CHANGED="152",W.VIDEO_LOADED_DATA="153",W.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",W.AUDIO_CONTEXT_LONG_SUSPENDED="155",W.REMOTE_VIDEO_PLAY_START="156",W.REMOTE_VIDEO_PLAY_FINISH="157",W.SIGNAL_CONNECTION_STATE_CHANGED="201",W.PEER_CONNECTION_STATE_CHANGED="202",W.SINGLE_CONNECTION_STAT="203",W.SPC_RECONNECTED="204",W.HEARTBEAT_REPORT="251",W.RECEIVED_PUBLISHED_USER_LIST="252",W.REMOTE_PUBLISH_STATE_CHANGED="253",W.AUDIO_LEVEL_INTERVAL="260",W.NETWORK_QUALITY="261",W.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",W.QUALITY_LIMITATION_CHANGED="263",W.LOG="264",W.AUDIO_PROCESSOR_DEBUG="265",W.SSO_SWITCH="266",W.SWITCH_ROOM_START="401",W.SWITCH_ROOM_SUCCESS="407",W.SWITCH_ROOM_FAILED="408",W))(mt||{});var A=mt;var xl=class{constructor(){d(this,"enable",!1);d(this,"ssoFailCount",0);S.on("22",({schedule:i})=>{var e;(e=i==null?void 0:i.config)!=null&&e.sso&&S.emit("266",{enable:!0})}),S.on("266",({enable:i})=>{this.enable=i})}handleUploadFailed(){this.ssoFailCount++,this.ssoFailCount>3&&S.emit("266",{enable:!1})}},Ir=new xl;var nT="%cTRTC%c%s",aT="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",cT="display: inline",ic=class ic{constructor(){d(this,"_isEnableUploadLog",!0);d(this,"_localJoinedUser",new Map);d(this,"_queue",[]);d(this,"_timeoutId",-1);d(this,"_logLevel",1);d(this,"_logLevelToUpload",2);!Oo&&!xs&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){S.on(A.JOIN_SCHEDULE_SUCCESS,({schedule:i})=>{var e;(e=i==null?void 0:i.config)!=null&&e.logLevelToUpload&&zt[i.config.logLevelToUpload]&&(this._logLevelToUpload=i.config.logLevelToUpload)}),S.on(A.JOIN_START,({params:i})=>{this.addJoinedUser({userId:i.userId,sdkAppId:i.sdkAppId}),this.startUpload()}),S.on(A.LEAVE_SUCCESS,({room:i})=>{this.deleteJoinedUser(i.userId)})}startUpload(){this._timeoutId===-1&&this.uploadInterval()}addJoinedUser(i){this._localJoinedUser.set(i.userId,i),this.startUpload()}deleteJoinedUser(i){this._localJoinedUser.delete(i)}uploadInterval(){this.upload().catch(()=>{}),this._timeoutId=window.setTimeout(()=>this.uploadInterval(),5e3)}getLogsToUpload(){let i={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&this._localJoinedUser.size===0)return i;let e=0;for(;e<this._queue.length&&e!==50;e++){let t=this._queue[e];if(t.forAllJoinedClients)this._localJoinedUser.forEach(({userId:r,sdkAppId:s})=>{i.map.has(r)?i.map.get(r).logs.push(t):i.map.set(r,{userId:r,sdkAppId:s,logs:[t]})});else if(ie(t.userId)&&Q(t.sdkAppId)){let{userId:r,sdkAppId:s}=t;i.map.has(r)?i.map.get(r).logs.push(t):i.map.set(r,{userId:r,sdkAppId:s,logs:[t]})}}return i.map.size>0&&(i.splicedQueue=this._queue.splice(0,e)),i}upload(){return f(this,null,function*(){if(this._queue.length===0||!this._isEnableUploadLog)return;let{map:i,splicedQueue:e}=this.getLogsToUpload();if(i.size===0)return;try{let r=[...i.values()];for(let s=0;s<r.length;s++){let{userId:n,sdkAppId:a,logs:c}=r[s],l={timestamp:la(),sdkAppId:String(a),userId:n,version:$e,log:c.map(m=>m.log).join(`
|
|
6
|
+
`)},u=JSON.stringify(l),h=Ir.enable?Gi(l,2002,a):u;yield this.uploadLogWithRetry(h,a,h instanceof Uint8Array,u),c.forEach(m=>m.uploaded=!0)}}catch(r){}let t=e.filter(r=>!r.uploaded);t.length>0&&(this._queue=t.concat(this._queue))})}uploadLogWithRetry(i,e,t,r){return Ci({retryFunction:()=>Ji({url:Wi(e,mr.LOG),body:i,timeout:5e3,priority:"low"}).then(s=>{t&&s.data!=="ok"&&(Ir.handleUploadFailed(),this.uploadLogWithRetry(r,e,!1,r))}),settings:{retries:3,timeout:2e3},onError:({retry:s})=>{s()}})()}getPrefix(i){let e=new Date;return e.setTime(Bi()),`[${Do(e)}] <${zt[i]}>`}getLogLevel(){return this._logLevel}setLogLevel(i){T(zt[i])||(this._logLevel!==i&&this.info("setLogLevel",i),this._logLevel=i)}enableUploadLog(){this._isEnableUploadLog=!0}disableUploadLog(){this.warn("disableUploadLog"),this._isEnableUploadLog=!1}logChunkToString(i){if(ie(i))return i;try{return i instanceof Error?i.toString():JSON.stringify(i)}catch(e){return""}}addLogToQueue(i,e,t=!0,r,s){let n={log:e.reduce((a,c)=>`${a} ${this.logChunkToString(c)}`.trim(),""),level:i,userId:r,sdkAppId:s,forAllJoinedClients:t};S.emit(A.LOG,{log:n}),this._isEnableUploadLog&&i>=this._logLevelToUpload&&this._queue.push(n)}log(i,e,t=!0,r,s){var a;if(e.unshift(this.getPrefix(i)),this.addLogToQueue(i,e,t,r,s),i<this._logLevel)return;let n=((a=zt[i])==null?void 0:a.toLowerCase())||"info";ic.PRINT_LOG_TAG?console[n](nT,aT,cT,...e):console[n](...e)}debug(...i){this.log(1,i)}info(...i){this.log(2,i)}warn(...i){this.log(3,i)}error(...i){this.log(4,i)}createLogger(i){if(i.parent instanceof Er){let e=i,{parent:t}=e,r=aa(e,["parent"]),s=new Er(r);return s.bindParent(t),s}return new Er(i)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;zt[t]&&(this._logLevelToUpload=t)}getQueue(){return this._queue}};d(ic,"PRINT_LOG_TAG",!(Te||_e||vl));var Ul=ic,R=new Ul;var dT=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,o=>{let i=Math.random()*16|0;return(o=="x"?i:i&3|8).toString(16)})},cn=dT;var Vl=class{constructor(){d(this,"_prefix","TRTC");d(this,"_queue",new Map)}getRealKey(i){return`${this._prefix}_${i}`}checkStorage(){if(!zi())return;setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter(t=>{if(t.startsWith(this._prefix))try{let r=localStorage.getItem(t);if(!r)return!1;let s=JSON.parse(r);if(s&&s.expiresIn<Date.now())return!0}catch(r){return!1}return!1}).forEach(t=>localStorage.removeItem(t))}doFlush(){if(zi())try{for(let[i,e]of this._queue)localStorage.setItem(i,JSON.stringify(e))}catch(i){R.warn(i)}}getItem(i){if(!zi())return null;try{let e=localStorage.getItem(this.getRealKey(i));if(!e)return null;let t=JSON.parse(e);return t&&t.expiresIn>=Date.now()?t.value:null}catch(e){R.warn(e)}}setItem(i,e){if(zi())try{let t={expiresIn:Date.now()+pa,value:e};this._queue.set(this.getRealKey(i),t)}catch(t){R.warn(t)}}deleteItem(i){if(!zi())return!1;try{return i=this.getRealKey(i),this._queue.delete(i),localStorage.removeItem(i),!0}catch(e){return R.warn(e),!1}}clear(){if(zi())try{localStorage.clear()}catch(i){R.warn(i)}}},ts=new Vl;var vi={};Vi(vi,{HTTPS_API:()=>kT,IS_GET_CAPABILITIES_FROM_INPUTDEVICE_SUPPORTED:()=>du,IS_GET_CAPABILITIES_SUPPORTED:()=>cu,IS_GET_SETTINGS_SUPPORTED:()=>bi,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>au,IS_INSERTABLE_STREAM_SUPPORTED:()=>mi,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>Sc,IS_RTC_RTP_SENDER_SUPPORTED:()=>gn,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>ns,IS_SEI_SUPPORTED:()=>En,IS_SPC_SUPPORTED:()=>ss,basis:()=>LT,capabilityCheck:()=>hu,checkSystemRequirementsInternal:()=>_c,decodeSupportStatus:()=>fc,detectVideoCodecCapabilities:()=>mu,detectVideoDecoderCapabilities:()=>Op,detectVideoEncoderCapabilities:()=>Dp,encodeSupportStatus:()=>su,getBrowserInfo:()=>yT,getDisplayResolution:()=>Ip,getH264ProfileLevelIds:()=>Mp,isAddTransceiverSupported:()=>St,isBrowserSupported:()=>ou,isCanvasCaptureStreamAPISupported:()=>Rp,isCanvasSmallStreamSupported:()=>gc,isGetReceiversSupported:()=>oo,isGetSendersSupported:()=>Rr,isGetTransceiversSupported:()=>yr,isGetUserMediaSupported:()=>Ap,isMediaDevicesSupported:()=>pc,isMediaSessionSupported:()=>bp,isMediaStreamTrackGeneratorSupported:()=>bT,isMediaStreamTrackProcessorSupported:()=>fn,isReplaceTrackSupported:()=>nu,isRequestVideoFrameCallbackSupported:()=>Ki,isSIMDSupported:()=>uu,isScaleResolutionDownBySupported:()=>yp,isScreenCaptureApiAvailable:()=>_n,isSelectedCandidatePair:()=>Cr,isSetParametersSupported:()=>Tn,isSetSinkIdSupported:()=>DT,isSmallStreamSupported:()=>Tc,isStopTransceiverSupported:()=>wT,isTRTCSupported:()=>NT,isUnifiedPlanDefault:()=>PT,isUsedInHttpProtocol:()=>Zi,isWebAudioSupported:()=>Cp,isWebCodecSupported:()=>Ec,isWebCodecsSupported:()=>pn,isWebRTCSupported:()=>lu,isWebTransportSupported:()=>vp});var Yl={};Vi(Yl,{AUDIO_LEVEL_SCALE:()=>Dt,AlphaStitchingType:()=>hn,AudioCodecPipelineType:()=>ln,AudioDecoderDowngradeState:()=>$l,AudioPlayerMode:()=>ql,AudioType:()=>ip,BASIC_TYPE:()=>Qi,BannedReason:()=>jl,CONNECTION_CLOSED_REASON:()=>Fl,CheckPermissionType:()=>Ql,ClientEvent:()=>Km,CodecType:()=>ap,ConnectionEvent:()=>ci,ConnectionState:()=>Nt,DECODE_FAILED_ERROR_CODE:()=>zl,DenoiserMode:()=>Xl,DeviceType:()=>cc,FacingMode:()=>sc,FrameWorkType:()=>rc,LeaveReason:()=>np,LocalTrackEvent:()=>Kr,MULTI_VIDEO_DATA_TYPE:()=>ui,MediaType:()=>Ve,MediaTypeLabel:()=>lT,MonitorEventId:()=>dn,MutedFlag:()=>tp,NetworkQualityValue:()=>Jl,PlayerState:()=>Ar,ReceiveMode:()=>sp,RemoteStreamType:()=>Et,RemoteTrackEvent:()=>eo,RoomEvent:()=>di,SMALL_MODE:()=>un,SceneNumber:()=>Hl,StreamEvent:()=>ep,StreamType:()=>op,SubscribeMediaType:()=>Bl,TIMER_TYPE:()=>hi,TRACK_ACTION:()=>Gl,TRACK_KIND:()=>Wl,TrackEvent:()=>li,UserRole:()=>lt,UserRoleNumber:()=>to,VideoCodec:()=>Ht,VideoCodecPipelineType:()=>ac,VideoContentHint:()=>is,VideoDecoderDowngradeState:()=>oc,VideoPlayerMode:()=>nc,VideoType:()=>rp});var rc=(e=>(e[e.WEBRTC=30]="WEBRTC",e[e.WASM=37]="WASM",e))(rc||{}),ci=(E=>(E.TRACK_ADDED="track-added",E.TRACK_UPDATED="track-updated",E.TRACK_SUBSCRIBED="track-subscribed",E.STREAM_ADDED="stream-added",E.STREAM_REMOVED="stream-removed",E.STREAM_UPDATED="stream-updated",E.STREAM_PUBLISHED="stream-published",E.STREAM_SUBSCRIBED="stream-subscribed",E.STREAM_UNSUBSCRIBED="stream-unsubscribed",E.STATE_CHANGED="state-changed",E.ERROR="error",E.CONNECTION_STATE_CHANGED="connection-state-changed",E.FIREWALL_RESTRICTION="firewall-restriction",E.SEI_MESSAGE="sei-message",E.CLOSED="closed",E))(ci||{}),Fl=(n=>(n.REMOTE_LEAVE="remote user exitRoom",n.REMOTE_UNPUBLISH="remote user unpublished",n.LOCAL_LEAVE="you exitRoom",n.LOCAL_UNPUBLISH="you unpublished",n.LOCAL_UNSUBSCRIBE="you unsubscribed",n.SWITCH_ROLE="you switch role to audience",n))(Fl||{}),Km=(C=>(C.STREAM_ADDED="stream-added",C.STREAM_REMOVED="stream-removed",C.STREAM_UPDATED="stream-updated",C.STREAM_SUBSCRIBED="stream-subscribed",C.CONNECTION_STATE_CHANGED="connection-state-changed",C.PEER_JOIN="peer-join",C.PEER_LEAVE="peer-leave",C.MUTE_AUDIO="mute-audio",C.MUTE_VIDEO="mute-video",C.UNMUTE_AUDIO="unmute-audio",C.UNMUTE_VIDEO="unmute-video",C.CLIENT_BANNED="client-banned",C.NETWORK_QUALITY="network-quality",C.AUDIO_VOLUME="audio-volume",C.SEI_MESSAGE="sei-message",C.ERROR="error",C))(Km||{}),ep=(s=>(s.PLAYER_STATE_CHANGED="player-state-changed",s.SCREEN_SHARING_STOPPED="screen-sharing-stopped",s.CONNECTION_STATE_CHANGED="connection-state-changed",s.DEVICE_AUTO_RECOVERED="device-auto-recovered",s.ERROR="error",s))(ep||{}),Kr=(c=>(c.DEVICE_AUTO_RECOVERED="1",c.DEVICE_RECOVER_FAILED="5",c.DEVICE_CHANGED="2",c.ERROR="3",c.PUBLISH_STATE_CHANGED="4",c.ENCODE_FAILED="6",c.TRACK_ENDED="7",c.RENDER="render",c))(Kr||{}),Ar=(t=>(t.PAUSED="PAUSED",t.PLAYING="PLAYING",t.STOPPED="STOPPED",t))(Ar||{}),di=(y=>(y.PEER_JOIN="peer-join",y.PEER_LEAVE="peer-leave",y.SIGNAL_CONNECTION_STATE_CHANGED="signal-connection-state-changed",y.MEDIA_CONNECTION_STATE_CHANGED="media-connection-state-changed",y.BANNED="banned",y.NETWORK_QUALITY="network-quality",y.AUDIO_VOLUME="audio-volume",y.SEI_MESSAGE="sei-message",y.ERROR="error",y.REMOTE_PUBLISH_STATE_CHANGED="remote-publish-state-changed",y.REMOTE_PUBLISHED="remote-published",y.REMOTE_UNPUBLISHED="remote-unpublished",y.FIREWALL_RESTRICTION="firewall-restriction",y.HEARTBEAT_REPORT="heartbeat-report",y.CUSTOM_MESSAGE="custom-message",y.LAYER_DATA="layerData",y.FIRST_VIDEO_FRAME="first-video-frame",y.DUMP="dump",y.AUDIO_FRAME="audio-frame",y.SUBSCRIBE_SMALL_VIDEO_CHANGED="subscribe-small-video-changed",y.LOCAL_PUBLISH_FLAG_CHANGED="local-publish-flag-changed",y.NTP_TIME_UPDATED="ntp-time-updated",y))(di||{}),li=(c=>(c.PLAYER_STATE_CHANGED="player-state-changed",c.MUTE="mute",c.UNMUTE="unmute",c.ERROR="error",c.INPUT_MEDIA_TRACK_CHANGED="input-media-track-changed",c.OUTPUT_MEDIA_TRACK_CHANGED="output-media-track-changed",c.FIRST_VIDEO_FRAME="first-video-frame",c.VIDEO_SIZE_CHANGED="video-size-changed",c))(li||{}),eo=(r=>(r.DECODE_FAILED="decode-failed",r.DECODE_DOWNGRADE_STATE_CHANGED="decode-downgrade-state-changed",r.REMOTE_PUBLISH_CHANGED="remote-publish-changed",r.AUDIO_FRAME_WITH_NTP="audio-frame-with-ntp",r))(eo||{}),tp=(a=>(a[a.VIDEO=1]="VIDEO",a[a.SMALL=2]="SMALL",a[a.AUX=4]="AUX",a[a.AUDIO=8]="AUDIO",a[a.VIDEO_MUTE=16]="VIDEO_MUTE",a[a.AUX_MUTE=32]="AUX_MUTE",a[a.AUDIO_MUTE=64]="AUDIO_MUTE",a))(tp||{}),Hl=(e=>(e[e.RTC=1]="RTC",e[e.LIVE=2]="LIVE",e))(Hl||{}),to=(e=>(e[e.ANCHOR=20]="ANCHOR",e[e.AUDIENCE=21]="AUDIENCE",e))(to||{}),lt=(e=>(e.ANCHOR="anchor",e.AUDIENCE="audience",e))(lt||{}),Nt=(s=>(s.CONNECTED="CONNECTED",s.DISCONNECTED="DISCONNECTED",s.CONNECTING="CONNECTING",s.RECONNECTED="RECONNECTED",s.RECONNECTING="RECONNECTING",s))(Nt||{}),$l=(r=>(r.INITIALIZED="INITIALIZED",r.STARTING="STARTING",r.STARTED="STARTED",r.FAILED="FAILED",r))($l||{}),oc=(r=>(r.INITIALIZED="INITIALIZED",r.STARTING="STARTING",r.STARTED="STARTED",r.FAILED="FAILED",r))(oc||{}),Wl=(t=>(t.AUDIO="audio",t.VIDEO="video",t.AUXILIARY="auxVideo",t))(Wl||{}),Gl=(e=>(e.ADD="add",e.REMOVE="remove",e))(Gl||{}),Ve=(s=>(s[s.NULL=0]="NULL",s[s.AUDIO=1]="AUDIO",s[s.AUX_VIDEO=2]="AUX_VIDEO",s[s.BIG_VIDEO=4]="BIG_VIDEO",s[s.SMALL_VIDEO=8]="SMALL_VIDEO",s))(Ve||{}),lT={1:"audio",2:"auxVideo",4:"video"},ip=(i=>(i[i.opus=111]="opus",i))(ip||{}),rp=(e=>(e[e.h264=100]="h264",e[e.vp8=101]="vp8",e))(rp||{}),op=(e=>(e.Big="big",e.Small="small",e))(op||{}),Et=(e=>(e.Main="main",e.Aux="auxiliary",e))(Et||{}),ui=(s=>(s[s.MULTI_DATA_AUDIO=1]="MULTI_DATA_AUDIO",s[s.MULTI_DATA_BIG_IMG=2]="MULTI_DATA_BIG_IMG",s[s.MULTI_DATA_SMALL_IMG=3]="MULTI_DATA_SMALL_IMG",s[s.MULTI_DATA_AUX_IMG=7]="MULTI_DATA_AUX_IMG",s[s.MULTI_DATA_TYPE_BUTT=12]="MULTI_DATA_TYPE_BUTT",s))(ui||{}),dn=(P=>(P[P.PUBLISH_VIDEO=32768]="PUBLISH_VIDEO",P[P.PUBLISH_AUDIO=32769]="PUBLISH_AUDIO",P[P.UNPUBLISH_VIDEO=32770]="UNPUBLISH_VIDEO",P[P.UNPUBLISH_AUDIO=32771]="UNPUBLISH_AUDIO",P[P.MUTE_AUDIO=32772]="MUTE_AUDIO",P[P.MUTE_VIDEO=32773]="MUTE_VIDEO",P[P.UNMUTE_AUDIO=32774]="UNMUTE_AUDIO",P[P.UNMUTE_VIDEO=32775]="UNMUTE_VIDEO",P[P.SUBSCRIBE_VIDEO=32776]="SUBSCRIBE_VIDEO",P[P.SUBSCRIBE_AUDIO=32777]="SUBSCRIBE_AUDIO",P[P.UNSUBSCRIBE_VIDEO=32778]="UNSUBSCRIBE_VIDEO",P[P.UNSUBSCRIBE_AUDIO=32779]="UNSUBSCRIBE_AUDIO",P[P.SWITCH_CAMERA=32780]="SWITCH_CAMERA",P[P.SWITCH_MICROPHONE=32781]="SWITCH_MICROPHONE",P[P.REPLACE_VIDEO=32782]="REPLACE_VIDEO",P[P.REPLACE_AUDIO=32783]="REPLACE_AUDIO",P[P.MUTE_REMOTE_VIDEO=32784]="MUTE_REMOTE_VIDEO",P[P.MUTE_REMOTE_AUDIO=32785]="MUTE_REMOTE_AUDIO",P[P.UNMUTE_REMOTE_VIDEO=32786]="UNMUTE_REMOTE_VIDEO",P[P.UNMUTE_REMOTE_AUDIO=32787]="UNMUTE_REMOTE_AUDIO",P[P.JOIN=32788]="JOIN",P[P.LEAVE=32789]="LEAVE",P[P.SIGNAL_DISCONNECTED=32790]="SIGNAL_DISCONNECTED",P[P.SIGNAL_CONNECTED=32791]="SIGNAL_CONNECTED",P[P.TRANSPORT_UPLINK_CONNECTED=32792]="TRANSPORT_UPLINK_CONNECTED",P[P.TRANSPORT_DOWNLINK_CONNECTED=32793]="TRANSPORT_DOWNLINK_CONNECTED",P[P.SIGNAl_RECONNECTING=32794]="SIGNAl_RECONNECTING",P[P.SIGNAL_RECONNECT_SUCCESS=32795]="SIGNAL_RECONNECT_SUCCESS",P[P.SIGNAL_RECONNECT_FAIL=32796]="SIGNAL_RECONNECT_FAIL",P[P.TRANSPORT_UPLINK_RECONNECTING=32797]="TRANSPORT_UPLINK_RECONNECTING",P[P.TRANSPORT_UPLINK_RECONNECT_SUCCESS=32798]="TRANSPORT_UPLINK_RECONNECT_SUCCESS",P[P.TRANSPORT_UPLINK_RECONNECT_FAIL=32799]="TRANSPORT_UPLINK_RECONNECT_FAIL",P[P.TRANSPORT_DOWNLINK_RECONNECTING=32800]="TRANSPORT_DOWNLINK_RECONNECTING",P[P.TRANSPORT_DOWNLINK_RECONNECT_SUCCESS=32801]="TRANSPORT_DOWNLINK_RECONNECT_SUCCESS",P[P.TRANSPORT_DOWNLINK_RECONNECT_FAIL=32802]="TRANSPORT_DOWNLINK_RECONNECT_FAIL",P[P.SUBSCRIBE_SMALL_VIDEO=32803]="SUBSCRIBE_SMALL_VIDEO",P[P.UNSUBSCRIBE_SMALL_VIDEO=32804]="UNSUBSCRIBE_SMALL_VIDEO",P[P.PUBLISH_AUX=32805]="PUBLISH_AUX",P[P.UNPUBLISH_AUX=32806]="UNPUBLISH_AUX",P[P.DEVICE_CAPTURE=2003]="DEVICE_CAPTURE",P[P.VIDEO_ENCODER=4004]="VIDEO_ENCODER",P[P.VIDEO_DECODER=4005]="VIDEO_DECODER",P))(dn||{}),Jl=(a=>(a[a.UNKNOWN=0]="UNKNOWN",a[a.EXCELLENT=1]="EXCELLENT",a[a.GOOD=2]="GOOD",a[a.POOR=3]="POOR",a[a.BAD=4]="BAD",a[a.VERY_BAD=5]="VERY_BAD",a[a.DISCONNECTED=6]="DISCONNECTED",a))(Jl||{}),sp=(r=>(r[r.MANUAL=0]="MANUAL",r[r.AUTO_AUDIO=1]="AUTO_AUDIO",r[r.AUTO_VIDEO=2]="AUTO_VIDEO",r[r.AUTO_ALL=3]="AUTO_ALL",r))(sp||{}),sc=(e=>(e.user="user",e.environment="environment",e))(sc||{}),nc=(t=>(t[t.ELEMENT=0]="ELEMENT",t[t.CANVAS_FROM_ELEMENT=1]="CANVAS_FROM_ELEMENT",t[t.CANVAS_WITHOUT_ELEMENT=2]="CANVAS_WITHOUT_ELEMENT",t))(nc||{}),ql=(e=>(e[e.ELEMENT=0]="ELEMENT",e[e.CONTEXT=1]="CONTEXT",e))(ql||{}),jl=(r=>(r.BANNED="banned",r.KICK="kick",r.USER_TIME_OUT="user_time_out",r.ROOM_DISBAND="room_disband",r))(jl||{}),np=(l=>(l[l.USER_EXIT_REASON_TC_USER_EXIT_NORMAL=0]="USER_EXIT_REASON_TC_USER_EXIT_NORMAL",l[l.USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT=1]="USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT",l[l.USER_EXIT_REASON_TC_USER_EXIT_KICKED=2]="USER_EXIT_REASON_TC_USER_EXIT_KICKED",l[l.USER_EXIT_REASON_TC_USER_EXIT_CHANGED=3]="USER_EXIT_REASON_TC_USER_EXIT_CHANGED",l[l.USER_KICK_OUT_CODE_BUSINESS_USER=4]="USER_KICK_OUT_CODE_BUSINESS_USER",l[l.USER_KICK_OUT_CODE_BUSINESS_ROOM=5]="USER_KICK_OUT_CODE_BUSINESS_ROOM",l[l.USER_KICK_OUT_CODE_SERVER_USER=6]="USER_KICK_OUT_CODE_SERVER_USER",l[l.USER_KICK_OUT_CODE_SERVER_ROOM=7]="USER_KICK_OUT_CODE_SERVER_ROOM",l[l.USER_KICK_SESS_EXSIT=8]="USER_KICK_SESS_EXSIT",l))(np||{}),Dt=1e8,Xl=(e=>(e[e.NORMAL=0]="NORMAL",e[e.FAR_FIELD_REDUCTION=1]="FAR_FIELD_REDUCTION",e))(Xl||{}),Bl=class{constructor(){d(this,"mediaType",0)}set audio(i){i?this.mediaType|=1:this.mediaType&=-2}get audio(){return!!(this.mediaType&1)}set video(i){i?this.mediaType|=4:this.mediaType&=-5}get video(){return!!(this.mediaType&4)}set auxiliary(i){i?this.mediaType|=2:this.mediaType&=-3}get auxiliary(){return!!(this.mediaType&2)}set smallVideo(i){i?this.mediaType|=8:this.mediaType&=-9}get smallVideo(){return!!(this.mediaType&8)}},Qi=(s=>(s.String="string",s.Number="number",s.Boolean="boolean",s.Array="array",s.Object="object",s))(Qi||{}),Ht=(s=>(s.H264="h264",s.H265="h265",s.VP8="vp8",s.VP9="vp9",s.AV1="av1",s))(Ht||{}),ac=(r=>(r[r.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",r[r.DUMP=1]="DUMP",r[r.SEI=2]="SEI",r[r.ENCODE_AND_DECODE=3]="ENCODE_AND_DECODE",r))(ac||{}),ln=(r=>(r[r.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",r[r.NTP_TO_AUDIO_FRAME=1]="NTP_TO_AUDIO_FRAME",r[r.DUMP=2]="DUMP",r[r.ENCODE_AND_DECODE=3]="ENCODE_AND_DECODE",r))(ln||{}),ap=(t=>(t.WebRTC="webrtc",t.WebCodecs="webcodecs",t.WebAssembly="webassembly",t))(ap||{}),zl=(m=>(m[m.SUCCESS=0]="SUCCESS",m[m.FAILED=1]="FAILED",m[m.WEBCODEC_INIT=2]="WEBCODEC_INIT",m[m.WEBCODEC_CONFIG_NOT_SUPPORT=3]="WEBCODEC_CONFIG_NOT_SUPPORT",m[m.WEBCODEC_DECODER_ERROR=4]="WEBCODEC_DECODER_ERROR",m[m.WEBCODEC_TRACK_MUTE=5]="WEBCODEC_TRACK_MUTE",m[m.WASM_INIT=6]="WASM_INIT",m[m.WASM_WEBGL_UNAVALIABLE=7]="WASM_WEBGL_UNAVALIABLE",m[m.WASM_DECODER_ERROR=8]="WASM_DECODER_ERROR",m[m.WASM_TRACK_MUTE=9]="WASM_TRACK_MUTE",m[m.TEST=10]="TEST",m[m.RENDER_2D_ERROR=11]="RENDER_2D_ERROR",m))(zl||{}),is=(r=>(r.NONE="",r.DETAIL="detail",r.MOTION="motion",r.TEXT="text",r))(is||{}),hi=(s=>(s.INTERVAL="interval",s.TIMEOUT="timeout",s.RAF="raf",s.RIC="ric",s.INTERVAL_IN_WORKER="intervalInWorker",s))(hi||{}),un=(e=>(e.CANVAS="canvas",e.API="api",e))(un||{}),Ql=(r=>(r[r.NONE=0]="NONE",r[r.MICROPHONE=1]="MICROPHONE",r[r.CAMERA=2]="CAMERA",r[r.BOTH=3]="BOTH",r))(Ql||{}),cc=(e=>(e.CAMERA="camera",e.MICROPHONE="microphone",e))(cc||{}),hn=(t=>(t[t.none=0]="none",t[t.horizontal=1]="horizontal",t[t.vertical=2]="vertical",t))(hn||{});var B={AVOID_REPEATED_CALL:"AVOID_REPEATED_CALL",INVALID_PARAMETER_REQUIRED:"INVALID_PARAMETER_REQUIRED",INVALID_PARAMETER_TYPE:"INVALID_PARAMETER_TYPE",INVALID_PARAMETER_EMPTY:"INVALID_PARAMETER_EMPTY",INVALID_PARAMETER_INSTANCE:"INVALID_PARAMETER_INSTANCE",INVALID_PARAMETER_RANGE:"INVALID_PARAMETER_RANGE",INVALID_PARAMETER_MIN:"INVALID_PARAMETER_MIN",INVALID_PARAMETER_MAX:"INVALID_PARAMETER_MAX",INVALID_PARAMETER_STREAMTYPE:"INVALID_PARAMETER_STREAMTYPE",API_CALL_TIMEOUT:"API_CALL_TIMEOUT",SIGNAL_CHANNEL_RECONNECTION_FAILED:"SIGNAL_CHANNEL_RECONNECTION_FAILED",SIGNAL_CHANNEL_SETUP_FAILED:"SIGNAL_CHANNEL_SETUP_FAILED",ERROR_MESSAGE:"ERROR_MESSAGE",EXCHANGE_SDP_TIMEOUT:"EXCHANGE_SDP_TIMEOUT",DOWNLINK_RECONNECTION_FAILED:"DOWNLINK_RECONNECTION_FAILED",EXCHANGE_SDP_FAILED:"EXCHANGE_SDP_FAILED",UPDATE_OFFER_TIMEOUT:"UPDATE_OFFER_TIMEOUT",UPLINK_RECONNECTION_FAILED:"UPLINK_RECONNECTION_FAILED",INVALID_RECORDID:"INVALID_RECORDID",INVALID_PURE_AUDIO:"INVALID_PURE_AUDIO",INVALID_STREAMID:"INVALID_STREAMID",INVALID_USER_DEFINE_RECORDID:"INVALID_USER_DEFINE_RECORDID",INVALID_USER_DEFINE_PUSH_ARGS:"INVALID_USER_DEFINE_PUSH_ARGS",INVALID_PROXY:"INVALID_PROXY",INVALID_JOIN:"INVALID_JOIN",INVALID_ROOMID_STRING:"INVALID_ROOMID_STRING",INVALID_ROOMID_INTEGER:"INVALID_ROOMID_INTEGER",INVALID_SIGNAL_CHANNEL:"INVALID_SIGNAL_CHANNEL",JOIN_ROOM_TIMEOUT:"JOIN_ROOM_TIMEOUT",JOIN_ROOM_FAILED:"JOIN_ROOM_FAILED",REJOIN_ROOM_FAILED:"REJOIN_ROOM_FAILED",INVALID_DESTROY:"INVALID_DESTROY",INVALID_PUBLISH:"INVALID_PUBLISH",INVALID_UNPUBLISH:"INVALID_UNPUBLISH",INVALID_AUDIENCE:"INVALID_AUDIENCE",INVALID_INITIALIZE:"INVALID_INITIALIZE",INVALID_DUPLICATE_PUBLISHING:"INVALID_DUPLICATE_PUBLISHING",INVALID_SUBSCRIBE_UNDEFINED:"INVALID_SUBSCRIBE_UNDEFINED",INVALID_SUBSCRIBE_LOCAL:"INVALID_SUBSCRIBE_LOCAL",INVALID_REMOTE_STREAM:"INVALID_REMOTE_STREAM",SUBSCRIBE_FAILED:"SUBSCRIBE_FAILED",INVALID_ROLE:"INVALID_ROLE",INVALID_PARAMETER_SWITCH_ROLE:"INVALID_PARAMETER_SWITCH_ROLE",INVALID_OPERATION_SWITCH_ROLE:"INVALID_OPERATION_SWITCH_ROLE",SWITCH_ROLE_TIMEOUT:"SWITCH_ROLE_TIMEOUT",SWITCH_ROLE_FAILED:"SWITCH_ROLE_FAILED",CLIENT_BANNED:"CLIENT_BANNED",INVALID_OPERATION_START_PUBLISH_CDN:"INVALID_OPERATION_START_PUBLISH_CDN",INVALID_OPERATION_STOP_PUBLISH_CDN:"INVALID_OPERATION_STOP_PUBLISH_CDN",INVALID_STREAM_ID:"INVALID_STREAM_ID",START_PUBLISH_CDN_FAILED:"START_PUBLISH_CDN_FAILED",STOP_PUBLISH_CDN_FAILED:"STOP_PUBLISH_CDN_FAILED",START_MIX_TRANSCODE:"START_MIX_TRANSCODE",STOP_MIX_TRANSCODE:"STOP_MIX_TRANSCODE",INVALID_AUDIO_VOLUME:"INVALID_AUDIO_VOLUME",ENABLE_SMALL_STREAM_PUBLISHED:"ENABLE_SMALL_STREAM_PUBLISHED",DISABLE_SMALL_STREAM_PUBLISHED:"DISABLE_SMALL_STREAM_PUBLISHED",NOT_SUPPORTED_SMALL_STREAM:"NOT_SUPPORTED_SMALL_STREAM",INVALID_SMALL_STREAM_PROFILE:"INVALID_SMALL_STREAM_PROFILE",INVALID_PARAMETER_REMOTE_STREAM:"INVALID_PARAMETER_REMOTE_STREAM",INVALID_OPERATION_CHANGE_SMALL:"INVALID_OPERATION_CHANGE_SMALL",REMOTE_NOT_PUBLISH_SMALL_STREAM:"REMOTE_NOT_PUBLISH_SMALL_STREAM",INVALID_SWITCH_DEVICE:"INVALID_SWITCH_DEVICE",INVALID_SWITCH_DEVICE_PUBLISHING:"INVALID_SWITCH_DEVICE_PUBLISHING",INVALID_REPLACE_TRACK:"INVALID_REPLACE_TRACK",INVALID_INITIALIZE_LOCAL_STREAM:"INVALID_INITIALIZE_LOCAL_STREAM",INVALID_ADD_TRACK_REPETITIVE:"INVALID_ADD_TRACK_REPETITIVE",INVALID_ADD_TRACK_REMOVING:"INVALID_ADD_TRACK_REMOVING",INVALID_ADD_TRACK_PUBLISHING:"INVALID_ADD_TRACK_PUBLISHING",INVALID_STREAM_INITIALIZED:"INVALID_STREAM_INITIALIZED",INVALID_ADD_TRACK_NUMBER:"INVALID_ADD_TRACK_NUMBER",INVALID_REMOVE_AUDIO_TRACK:"INVALID_REMOVE_AUDIO_TRACK",INVALID_REMOVE_AUDIO_ADDING:"INVALID_REMOVE_AUDIO_ADDING",INVALID_REMOVE_AUDIO_ON:"INVALID_REMOVE_AUDIO_ON",INVALID_REMOVE_TRACK_PUBLISHING:"INVALID_REMOVE_TRACK_PUBLISHING",INVALID_REMOVE_TRACK_NOT_TRACK:"INVALID_REMOVE_TRACK_NOT_TRACK",INVALID_REMOVE_TRACK_NUMBER:"INVALID_REMOVE_TRACK_NUMBER",INVALID_REPLACE_TRACK_NO_TRACK:"INVALID_REPLACE_TRACK_NO_TRACK",REPEAT_JOIN:"REPEAT_JOIN",CLIENT_DESTROYED:"CLIENT_DESTROYED",NOT_BUG_PACKAGE:"NOT_BUG_PACKAGE",START_MIX_TRANSCODE_FAILED:"START_MIX_TRANSCODE_FAILED",STOP_MIX_TRANSCODE_FAILED:"STOP_MIX_TRANSCODE_FAILED",MIX_TRANSCODE_NOT_STARTED:"MIX_TRANSCODE_NOT_STARTED",CANNOT_LESS_THAN_ZERO:"CANNOT_LESS_THAN_ZERO",MIX_PARAMS_VIDEO_FRAMERATE:"MIX_PARAMS_VIDEO_FRAMERATE",MIX_PARAMS_VIDEO_GOP:"MIX_PARAMS_VIDEO_GOP",MIX_PARAMS_AUDIO_BITRATE:"MIX_PARAMS_AUDIO_BITRATE",MIX_PARAMS_USER_Z_ORDER:"MIX_PARAMS_USER_Z_ORDER",MIX_PARAMS_NOT_SELF:"MIX_PARAMS_NOT_SELF",MIX_PARAMS_USER_STREAM:"MIX_PARAMS_USER_STREAM",INVALID_PLAY:"INVALID_PLAY",INVALID_ELEMENT_ID:"INVALID_ELEMENT_ID",INVALID_ELEMENT_ID_TYPE:"INVALID_ELEMENT_ID_TYPE",PLAY_FAILED:"PLAY_FAILED",INVALID_USERID:"INVALID_USERID",INVALID_CREATE_STREAM_SOURCE:"INVALID_CREATE_STREAM_SOURCE",INVALID_CREATE_STREAM_SCREEN:"INVALID_CREATE_STREAM_SCREEN",INVALID_CREATE_STREAM_AUDIO:"INVALID_CREATE_STREAM_AUDIO",INVALID_CREATE_STREAM_SCREEN_AUDIO:"INVALID_CREATE_STREAM_SCREEN_AUDIO",NOT_SUPPORTED_HTTP:"NOT_SUPPORTED_HTTP",NOT_SUPPORTED_WEBRTC:"NOT_SUPPORTED_WEBRTC",NOT_SUPPORTED_PROFILE:"NOT_SUPPORTED_PROFILE",NOT_SUPPORTED_MEDIA:"NOT_SUPPORTED_MEDIA",NOT_SUPPORTED_H264ENCODE:"NOT_SUPPORTED_H264ENCODE",NOT_SUPPORTED_H264DECODE:"NOT_SUPPORTED_H264DECODE",NOT_SUPPORTED_TRACK:"NOT_SUPPORTED_TRACK",NOT_SUPPORTED_SWITCH_DEVICE:"NOT_SUPPORTED_SWITCH_DEVICE",NOT_SUPPORTED_CAPTURE:"NOT_SUPPORTED_CAPTURE",NOT_SUPPORTED_AUX:"NOT_SUPPORTED_AUX",MICROPHONE_NOT_FOUND:"MICROPHONE_NOT_FOUND",CAMERA_NOT_FOUND:"CAMERA_NOT_FOUND",SIGNAL_RESPONSE_FAILED:"SIGNAL_RESPONSE_FAILED",CATCH_HANDLER_ERROR:"CATCH_HANDLER_ERROR",API_NOT_EXIST:"API_NOT_EXIST",CONNECTION_CLOSED:"CONNECTION_CLOSED",SUBSCRIBE_ALL_FALSE:"SUBSCRIBE_ALL_FALSE",SEI_NOT_SUPPORT:"SEI_NOT_SUPPORT",SEI_DISABLED:"SEI_DISABLED",SEI_BEFORE_PUBLISH:"SEI_BEFORE_PUBLISH",SEI_NOT_VIDEO:"SEI_NOT_VIDEO",CALL_FREQUENCY_LIMIT:"CALL_FREQUENCY_LIMIT",CONNECTION_ABORTED:"CONNECTION_ABORTED",API_CALL_ABORTED:"API_CALL_ABORTED",DUPLICATE_AUX:"DUPLICATE_AUX"},je={AVOID_REPEATED_CALL(o){return`previous ${o.name}() is ongoing, please avoid repeated calls.`},INVALID_PARAMETER_REQUIRED({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' is a required param when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_TYPE({key:o,rule:i,fnName:e,value:t}){let r=`${o||i.name}`,s="";return Array.isArray(i.type)?s=i.type.join("|"):s=i.type,`'${r}' must be type of ${s} when calling ${e}(), received type: ${Oe(t)}.`},INVALID_PARAMETER_EMPTY({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' cannot be '${t}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:o,rule:i,fnName:e,value:t}){let r=`${o||i.name}`,s=`${i.instanceOf.name||i.instanceOf}`;return`'${r}' must be instanceof ${s} when calling ${e}(), received type: ${Oe(t)}.`},INVALID_PARAMETER_RANGE({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' must be one of ${i.values.join("|")} when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_MIN({key:o,rule:i,fnName:e,value:t}){return`the min value of ${o||i.name} is ${i.min}, received: ${t}.`},INVALID_PARAMETER_MAX({key:o,rule:i,fnName:e,value:t}){return`the max value of ${o||i.name} is ${i.max}, received: ${t}.`},API_CALL_TIMEOUT(o){return`${o.commandDesc||o.command} timeout observed.`},SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED(o){return`SignalChannel setup failure: (errorCode: ${o.errorCode}, errorMsg: ${o.errorMsg} }).`},ERROR_MESSAGE(o){let i=`${o.type} failed`;return o.message&&(i=`${i}: ${o.message}.`),i},EXCHANGE_SDP_TIMEOUT:"exchange sdp timeout.",DOWNLINK_RECONNECTION_FAILED:"downlink reconnection failed, please check your network and re-join room.",EXCHANGE_SDP_FAILED(o){return`exchange sdp failed ${o.errMsg}.`},UPDATE_OFFER_TIMEOUT:"update offer timeout observed.",UPLINK_RECONNECTION_FAILED:"uplink reconnection failed, please check your network and publish again.",INVALID_RECORDID:"recordId must be an integer number.",INVALID_PURE_AUDIO:"pureAudioPushMode must be 1 or 2.",INVALID_STREAMID:"streamId must be a sting literal within 64 bytes, and not be empty.",INVALID_USER_DEFINE_RECORDID:"userDefineRecordId must be a sting literal contains (a-zA-Z),(0-9), underline and hyphen, within 64 bytes, and not be empty.",INVALID_USER_DEFINE_PUSH_ARGS:"userDefinePushArgs must be a sting literal within 256 bytes, and not be empty.",INVALID_PROXY:'proxy server url must start with "wss://".',INVALID_JOIN:"duplicate join() called.",INVALID_ROOMID_STRING(o){return`'${o}' must be validate string when useStringRoomId is true.`},INVALID_ROOMID_INTEGER(o){return`'${o}' must be an integer between [1, 4294967294] when useStringRoomId is false.`},INVALID_SIGNAL_CHANNEL:"SignalChannel is not ready yet.",JOIN_ROOM_TIMEOUT:"join room timeout.",JOIN_ROOM_FAILED({error:o,code:i}){return`Failed to join room - ${o} code: ${i}`},REJOIN_ROOM_FAILED(o){return`reJoin room: ${o.roomId} failed, please check your network.`},INVALID_DESTROY:"please call leave() before destroy().",INVALID_PUBLISH:"please call join() before publish().",INVALID_UNPUBLISH:"stream has not been published yet.",INVALID_AUDIENCE:'no permission to publish() under live/audience, please call switchRole("anchor") firstly before publish().',INVALID_INITIALIZE:"cannot publish stream because stream is not initialized, is switching device, or has been closed.",INVALID_DUPLICATE_PUBLISHING(o){return`duplicate ${o} stream publishing, please unpublish your prev ${o} stream and then re-publish.`},INVALID_SUBSCRIBE_UNDEFINED:"stream is undefined or null.",INVALID_SUBSCRIBE_LOCAL:"stream cannot be LocalStream.",INVALID_REMOTE_STREAM:"remoteStream does not exist because it has been unpublished by remote peer.",SUBSCRIBE_FAILED({message:o,userId:i,streamType:e}){return`failed to subscribe ${i} ${e} stream, reason: ${o}.`},INVALID_ROLE:"switchRole can only be called in live mode.",INVALID_PARAMETER_SWITCH_ROLE:"role could only be set to a value as anchor or audience.",INVALID_OPERATION_SWITCH_ROLE:"please call join() before switchRole().",SWITCH_ROLE_TIMEOUT:"switchRole timeout.",SWITCH_ROLE_FAILED(o){return`switchRole failed, errCode: ${o.code} errMsg: ${o.message}.`},CLIENT_BANNED(o){return`client was banned because of ${o.message}.`},INVALID_OPERATION_START_PUBLISH_CDN:"please call startPublishCDNStream() after join room and publish the local stream.",INVALID_OPERATION_STOP_PUBLISH_CDN:"please call startPublishCDNStream() before stopPublishCDNStream().",START_PUBLISH_CDN_FAILED(o){return`startPublishCDNStream failed, errMsg: ${o.message}.`},STOP_PUBLISH_CDN_FAILED(o){return`stopPublishCDNStream failed, errMsg: ${o.message}.`},INVALID_STREAM_ID(o){return`'${o}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},START_MIX_TRANSCODE:"please call startMixTranscode() after join().",STOP_MIX_TRANSCODE:"please call stopMixTranscode() after startMixTranscode().",INVALID_AUDIO_VOLUME:"interval must be a number.",ENABLE_SMALL_STREAM_PUBLISHED:"Cannot enable small stream after localStream published.",DISABLE_SMALL_STREAM_PUBLISHED:"Cannot disable small stream after localStream published.",NOT_SUPPORTED_SMALL_STREAM:"your browser does not support opening small stream.",INVALID_SMALL_STREAM_PROFILE:"small stream profile is invalid.",INVALID_PARAMETER_REMOTE_STREAM:"remoteStream is invalid.",INVALID_OPERATION_CHANGE_SMALL:"cannot switch to the small stream without subscribing to the video of remoteStream.",REMOTE_NOT_PUBLISH_SMALL_STREAM:"remote peer does not publish small stream.",INVALID_SWITCH_DEVICE:"cannot switch device on current stream.",INVALID_SWITCH_DEVICE_PUBLISHING:"cannot switch device when publishing localStream.",INVALID_REPLACE_TRACK:"cannot replace track when publishing localStream.",INVALID_INITIALIZE_LOCAL_STREAM:"local stream has not initialized yet.",INVALID_ADD_TRACK_REPETITIVE:"previous addTrack is ongoing, please avoid repetitive execution.",INVALID_ADD_TRACK_REMOVING:"cannot add track when a track is removing.",INVALID_ADD_TRACK_PUBLISHING:"cannot add track when publishing localStream.",INVALID_STREAM_INITIALIZED:"your local stream haven't been initialized yet.",INVALID_ADD_TRACK_NUMBER:"a Stream has at most one audio track and one video track.",INVALID_REMOVE_AUDIO_TRACK:"remove audio track is not supported on your browser.",INVALID_REMOVE_AUDIO_ADDING:"cannot remove track when a track is adding.",INVALID_REMOVE_AUDIO_ON:"previous removeTrack is ongoing, please avoid repetitive execution.",INVALID_REMOVE_TRACK_PUBLISHING:"cannot remove track when publishing localStream.",INVALID_REMOVE_TRACK_NOT_TRACK:"localStream has not this track.",INVALID_REMOVE_TRACK_NUMBER:"remove the only video track is not supported, please use replaceTrack or muteVideo.",INVALID_REPLACE_TRACK_NO_TRACK(o){return`cannot replace ${o.kind} track because stream has not ${o.kind} track`},NOT_BUG_PACKAGE:"You need to buy packages, refer to tencent console.",START_MIX_TRANSCODE_FAILED(o){return`startMixTranscode failed, errMsg: ${o.message}.`},STOP_MIX_TRANSCODE_FAILED(o){return`stopMixTranscode failed, errMsg: ${o.message}.`},MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' cannot be less than 0 when calling ${e}().`},MIX_PARAMS_VIDEO_FRAMERATE:"'config.videoFramerate' should be an integer between 0 and 30, excluding 0.",MIX_PARAMS_VIDEO_GOP:"'config.videoGOP' should be an integer between 1 and 8.",MIX_PARAMS_AUDIO_BITRATE:"'config.audioBitrate' should be an integer between 32 and 192.",MIX_PARAMS_USER_Z_ORDER(o){return`'${o}' is required and must be between 1 and 15.`},MIX_PARAMS_NOT_SELF:"'config.mixUsers' must contain self.",MIX_PARAMS_USER_STREAM:"'config.videoWidth' and 'config.videoHeight' of output stream should be contain all mix stream.",INVALID_PLAY:"duplicate play() call observed, please stop() firstly.",INVALID_ELEMENT_ID:({key:o,fnName:i})=>`'${o}' is not found in the document object when calling ${i}().`,INVALID_ELEMENT_ID_TYPE:({key:o,fnName:i,type:e})=>`the element corresponding to '${o}' must be instanceof HTMLElement when calling ${i}(), received: ${e}.`,PLAY_FAILED:o=>`${o.media} play failed, browser exception: ${o.error.toString()}`,INVALID_USERID:"userId cannot be all spaces.",INVALID_CREATE_STREAM_SOURCE:"LocalStream must be created by createStream() with either audio/video or audioSource/videoSource, but can not be mixed with audio/video and audioSource/videoSource.",INVALID_CREATE_STREAM_SCREEN:"screen/video cannot be both true.",INVALID_CREATE_STREAM_AUDIO:"audio/screenAudio cannot be both true.",INVALID_CREATE_STREAM_SCREEN_AUDIO:"when screen is true, screenAudio can be configured.",NOT_SUPPORTED_HTTP:"http protocol does not support the ability to capture microphone, camera and screen. please use https to deploy your page.",NOT_SUPPORTED_WEBRTC:"your browser or environment does not support full WebRTC capabilities.",NOT_SUPPORTED_PROFILE:"your browser does not support setVideoProfile.",NOT_SUPPORTED_MEDIA:"your browser or environment does not support navigator.mediaDevices.",NOT_SUPPORTED_H264ENCODE:"your device does not support H.264 encoding.",NOT_SUPPORTED_H264DECODE:"your device does not support H.264 decoding.",NOT_SUPPORTED_TRACK(o){return`${o}Track is not supported on your browser.`},NOT_SUPPORTED_SWITCH_DEVICE:"switchDevice is not supported on your browser.",NOT_SUPPORTED_CAPTURE:"Your browser or environment does not support screen sharing, please check whether the browser version.",MICROPHONE_NOT_FOUND:"no microphone detected, please check your microphone.",CAMERA_NOT_FOUND:"no camera detected, please check your camera.",SIGNAL_RESPONSE_FAILED(o){return`${o.signalResponse} failed, response code is ${o.code} , errMsg: ${o.message}.`},CATCH_HANDLER_ERROR({name:o,event:i}){return`an error was caught in ${o}.on('${i}', handler), please check your code in 'handler'.`},API_NOT_EXIST({name:o}){return`experimental api ${o} does not exist.`},REPEAT_JOIN:o=>"please avoid repeated join.",CONNECTION_CLOSED:"remoteStream has been unsubscribed or unpublished by remote user.",SUBSCRIBE_ALL_FALSE:"cannot subscribe when both audio & video are false, use client.unsubscribe() instead",CLIENT_DESTROYED({funName:o}){return`failed to call ${o}() because client was destroyed.`},SEI_NOT_SUPPORT:o=>`not support to sendSEIMessage${o===!1?" without using h264 codec":""}`,SEI_DISABLED:"SEI is disabled",SEI_BEFORE_PUBLISH:"please call sendSEIMessage() after publish() success",SEI_NOT_VIDEO:"cannot send sei when localStream has not video.",CALL_FREQUENCY_LIMIT:({isSize:o,name:i,timesInSecond:e,maxSizeInSecond:t})=>`api ${i} call ${o?"size":"times"} is over ${o?`${t} bytes`:e} in a second.`,CONNECTION_ABORTED(o){return`connection aborted due to: ${o}`},API_CALL_ABORTED(o){let i;return o.message.includes("REMOTE_STREAM_NOT_EXIST")?i=`Subscribe ${o.userId} ${o.streamType} stream aborted, reason: remote user ${o.userId} unpublished stream.`:i=`API aborted, reason: ${o.message}`,i},DUPLICATE_AUX:"only one auxiliary stream can be published in a room.",NOT_SUPPORTED_AUX:"publish auxiliary stream is not supported on your browser.",INVALID_PARAMETER_STREAMTYPE:o=>`'streamType' is required when 'userId' is not '*', calling ${o}()`};var cp=(o,i)=>i?`${ft}/${o}/${i}`:`${ft}/${o}/index.html`;var uT=()=>{if(window.TRTC_ERROR_INFO&&window.TRTC_ERROR_LINK)return{TRTC_ERROR_INFO:window.TRTC_ERROR_INFO,TRTC_ERROR_LINK:window.TRTC_ERROR_LINK};let o=localStorage==null?void 0:localStorage.getItem(Xd);if(o){o=JSON.parse(o);let i=document.createElement("script");i.type="text/javascript",i.text=o.message,document.body.appendChild(i);let e=window.TRTC_ERROR_INFO,t=window.TRTC_ERROR_LINK;return document.body.removeChild(i),{TRTC_ERROR_INFO:e,TRTC_ERROR_LINK:t}}return{}};function H(o){let{key:i,data:e,link:t,addDocLink:r=!0}=o,s="",n="",a="";ue(je[i])?s=je[i](e):ie(je[i])&&(s=je[i]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:l}=uT();t?a=`${t.className}.html#${t.fnName}`:l&&l[i]&&(ue(l[i])?a=l[i](e):ie(l[i])&&(a=l[i]));let u=s;return Zt()&&(c&&c[i]&&(ue(c[i])?n=c[i](e):ie(c[i])&&(n=c[i])),n&&(r?u=`${n}
|
|
7
|
+
\u8BF7\u67E5\u770B\u6587\u6863: ${cp("zh-cn",a)}
|
|
7
8
|
|
|
8
|
-
`:
|
|
9
|
+
`:u=`${n}
|
|
9
10
|
|
|
10
|
-
`,
|
|
11
|
-
Refer to: ${
|
|
12
|
-
`),m}var zm=Li(x_(),1);var VI=1,BI=0,Mu=class{constructor(t=!0){p(this,"countMap",new Map);p(this,"distributionMap",new Map);p(this,"version");p(this,"log",se.createLogger({id:"kv"}));t&&(ee.on("102",({track:e,cost:r})=>{this.addSuccessEvent({key:e.kind===j.AUDIO?501700:511700,cost:r})}),ee.on("103",({track:e,error:r})=>{this.addFailedEvent({key:e.kind===j.AUDIO?501700:511700,error:r})}),ee.on("266",({enable:e})=>{this.log.info(`${e?"enable":"disable"} sso`),e?this.addSuccessEvent({key:525701}):this.addFailedEvent({key:525701})}))}getReportData(t,e){let r={msg_sdk_basic_info:{uint32_sdk_version:Yd(this.version||qt),uint32_terminal_type:15,bytes_device_name:"",bytes_os_version:"",uint32_framework:30,uint32_network_type:0},stats_count:[...this.countMap.entries()].map(([o,s])=>({uint32_key:o,uint32_count:s})),stats_distribution:[...this.distributionMap.entries()].map(([o,s])=>({uint32_key:o,distribution_items:[...s.entries()].map(([n,a])=>({uint32_item_key:n,uint32_item_value:a}))})),str_user_sig:t,bytes_report_token:e};return this.countMap.clear(),this.distributionMap.clear(),r}clear(){this.countMap.clear(),this.distributionMap.clear()}isEnumKey(t){let e=+String(t).slice(-3);return e>=700&&e<799}isErrorCodeKey(t){let e=+String(t).slice(-3);return e>=600&&e<699}isCountKey(t){let e=+String(t).slice(-3);return e>=0&&e<599}isNumberKey(t){let e=+String(t).slice(-3);return e>=800&&e<899}addCount({key:t,useUV:e=!1}){if(!this.isCountKey(t)){this.log.debug(`${t} is not count key, last 3 number should be 0~599`);return}e&&this.countMap.has(t)||this.countMap.set(t,(this.countMap.get(t)||0)+1)}addEnum({key:t,value:e,useUV:r=!0}){var s;if(!this.isEnumKey(t))return this.log.debug(`${t} is not enum key, last 3 number should be 700~799`);if(r&&this.countMap.has(t))return;this.countMap.set(t,(this.countMap.get(t)||0)+1);let o=((s=this.distributionMap)==null?void 0:s.get(t))||new Map;o.set(e,(o.get(e)||0)+1),this.distributionMap.set(t,o)}addNumber({key:t,value:e,split:r=100,useUV:o=!1,max:s=5e3}){var c;if(!this.isNumberKey(t))return this.log.debug(`${t} is not number key, last 3 number should be 800~899`);if(o&&this.countMap.has(t))return;e>s&&(e=s),this.countMap.set(t,(this.countMap.get(t)||0)+1);let n=((c=this.distributionMap)==null?void 0:c.get(t))||new Map,a=0;if(ft(r))a=Math.floor(e/r);else for(let d=r.length-1;d>0;d--)if(e>r[d]){a=d;break}n.set(a,(n.get(a)||0)+1),this.distributionMap.set(t,n)}addSuccessEvent({key:t,cost:e,timeKey:r,split:o}){if(t&&(this.addEnum({key:t,value:VI,useUV:!1}),e)){let s=+String(t).slice(-3);s<800&&s>=700?this.addNumber({key:r||t+100,value:e,split:o}):r||this.log.debug(`time stat ignored, ${t}`)}}addFailedEvent({key:t,error:e}){if(!t)return;let r=Te.UNKNOWN;e&&(ft(e)?r=e:(!z(e.extraCode)||!z(e.code))&&(r=e.extraCode||e.code)),this.addEnum({key:t,value:BI,useUV:!1}),this.addEnum({key:t,value:Math.abs(r),useUV:!1})}},xu=(P=>(P[P.enterRoom=500700]="enterRoom",P[P.exitRoom=500701]="exitRoom",P[P.switchRole=500702]="switchRole",P[P.destroy=500703]="destroy",P[P.startLocalAudio=500704]="startLocalAudio",P[P.updateLocalAudio=500705]="updateLocalAudio",P[P.stopLocalAudio=500706]="stopLocalAudio",P[P.startLocalVideo=500707]="startLocalVideo",P[P.updateLocalVideo=500708]="updateLocalVideo",P[P.stopLocalVideo=500709]="stopLocalVideo",P[P.startScreenShare=500710]="startScreenShare",P[P.updateScreenShare=500711]="updateScreenShare",P[P.stopScreenShare=500712]="stopScreenShare",P[P.startRemoteVideo=500713]="startRemoteVideo",P[P.updateRemoteVideo=500714]="updateRemoteVideo",P[P.stopRemoteVideo=500715]="stopRemoteVideo",P[P.muteRemoteAudio=500716]="muteRemoteAudio",P[P.setRemoteAudioVolume=500717]="setRemoteAudioVolume",P[P.use=500718]="use",P[P.switchRoom=500719]="switchRoom",P[P.sendSEIMessage=5e5]="sendSEIMessage",P[P.sendCustomMessage=500001]="sendCustomMessage",P))(xu||{}),Hm=(f=>(f[f.AudioMixer=550700]="AudioMixer",f[f.AIDenoiser=551700]="AIDenoiser",f[f.VirtualBackground=570700]="VirtualBackground",f[f.Beauty=571700]="Beauty",f[f.Watermark=572700]="Watermark",f[f.BasicBeauty=574700]="BasicBeauty",f[f.CDNStreaming=590700]="CDNStreaming",f[f.DeviceDetector=591700]="DeviceDetector",f[f.Debug=592700]="Debug",f[f.SmallStreamAutoSwitcher=593700]="SmallStreamAutoSwitcher",f[f.VideoMixer=594700]="VideoMixer",f[f.AudioProcessor=595700]="AudioProcessor",f))(Hm||{}),Wm=(f=>(f[f.AudioMixer=550701]="AudioMixer",f[f.AIDenoiser=551701]="AIDenoiser",f[f.VirtualBackground=570701]="VirtualBackground",f[f.Beauty=571701]="Beauty",f[f.Watermark=572701]="Watermark",f[f.BasicBeauty=574701]="BasicBeauty",f[f.CDNStreaming=590701]="CDNStreaming",f[f.DeviceDetector=591701]="DeviceDetector",f[f.Debug=592701]="Debug",f[f.SmallStreamAutoSwitcher=593701]="SmallStreamAutoSwitcher",f[f.VideoMixer=594701]="VideoMixer",f[f.AudioProcessor=595701]="AudioProcessor",f))(Wm||{}),Gm=(f=>(f[f.AudioMixer=550702]="AudioMixer",f[f.AIDenoiser=551702]="AIDenoiser",f[f.VirtualBackground=570702]="VirtualBackground",f[f.Beauty=571702]="Beauty",f[f.Watermark=572702]="Watermark",f[f.BasicBeauty=574702]="BasicBeauty",f[f.CDNStreaming=590702]="CDNStreaming",f[f.DeviceDetector=591702]="DeviceDetector",f[f.Debug=592702]="Debug",f[f.SmallStreamAutoSwitcher=593702]="SmallStreamAutoSwitcher",f[f.VideoMixer=594702]="VideoMixer",f[f.AudioProcessor=595702]="AudioProcessor",f))(Gm||{});var Kn=(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))(Kn||{});var $I=new Mu(!0),Gs=new Mu(!1);var Se=$I;var rt={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}},FI=new Map([[zt,["Firefox",iu]],[Wn,["Edg",nu]],[Xn,["Chrome",Su]],[Zt,["Safari",uo]],[Si,["TBS",du]],[ao,["XWEB",uu]],[co&&Go,["WeChat",lu]],[qa,["QQ(Win)",hu]],[zn,["QQ(Mobile)",Fn]],[Gn,["QQ(Mobile X5)",Fn]],[Xa,["QQ(Mac)",mu]],[Ja,["QQ(iPad)",pu]],[Ya,["MI",fu]],[Za,["HW",gu]],[ec,["Samsung",_u]],[jn,["OPPO",Eu]],[tc,["VIVO",Tu]],[Ls,["EDGE",su]],[za,["SogouMobile",au]],[ja,["Sogou",cu]]]);function Pu(){let i=FI.get(!0),t=i?i[0]:"unknown",e=i?i[1]:"unknown";return{browserName:t,browserVersion:e}}var jm=function(){return!(lm||Ls||Wn&&dm<80||zt&&ou<56)},qm=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder"].every(t=>t in window)},Uu=function(){if(!navigator.mediaDevices)return Eo()||se.error(Wr.NOT_SUPPORTED_MEDIA),!1;let i=["getUserMedia","enumerateDevices"];return i.filter(t=>t in navigator.mediaDevices).length===i.length},k_=!1;function Eo(){return location.protocol==="http:"&&!bi?(k_||se.error(Et({key:_t.NOT_SUPPORTED_HTTP})),k_=!0,!0):!1}var Xm=function(){return(window==null?void 0:window.OffscreenCanvas)&&(window==null?void 0:window.MediaStreamTrackProcessor)&&(window==null?void 0:window.MediaStreamTrackGenerator)},HI=function(){return!!(window!=null&&window.MediaStreamTrackGenerator)},Jm=function(){return D(this,null,function*(){var o,s,n;if(rt.detail.isH264EncodeSupported&&rt.detail.isVp8EncodeSupported)return{isH264EncodeSupported:rt.detail.isH264EncodeSupported,isVp8EncodeSupported:rt.detail.isVp8EncodeSupported,isH265EncodeSupported:rt.detail.isH265EncodeSupported};let i,t=!1,e=!1,r=!1;try{let a=new RTCPeerConnection,c=document.createElement(j.CANVAS);c.getContext("2d");let d=c.captureStream(0);return a.addTrack(d.getVideoTracks()[0],d),i=yield a.createOffer(),t=((o=i.sdp)==null?void 0:o.toLowerCase().indexOf("h264"))!==-1,e=((s=i.sdp)==null?void 0:s.toLowerCase().indexOf("vp8"))!==-1,r=((n=i.sdp)==null?void 0:n.toLowerCase().indexOf("h265"))!==-1,a.close(),{isH264EncodeSupported:t,isVp8EncodeSupported:e,isH265EncodeSupported:r}}catch(a){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1}}})},B_=function(){return D(this,null,function*(){var r;if(rt.detail.isH264DecodeSupported&&rt.detail.isVp8DecodeSupported)return{isH264DecodeSupported:rt.detail.isH264DecodeSupported,isVp8DecodeSupported:rt.detail.isVp8DecodeSupported,isH265DecodeSupported:rt.detail.isH265DecodeSupported};let i,t=!1,e=!1;try{let o=new RTCPeerConnection;$u()?(o.addTransceiver(j.VIDEO,{direction:"recvonly"}),i=yield o.createOffer()):i=yield o.createOffer({offerToReceiveVideo:!0}),i.sdp.toLowerCase().indexOf("h264")!==-1&&(t=!0),i.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0);let s=((r=i.sdp)==null?void 0:r.toLowerCase().indexOf("h265"))!==-1;return o.close(),{isH264DecodeSupported:t,isVp8DecodeSupported:e,isH265DecodeSupported:s}}catch(o){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}}})};function WI(){return D(this,null,function*(){let[i,t]=yield Promise.all([Jm(),B_()]);return{encode:{h264:i.isH264EncodeSupported,vp8:i.isVp8EncodeSupported,h265:i.isH265EncodeSupported},decode:{h264:t.isH264DecodeSupported,vp8:t.isVp8DecodeSupported,h265:t.isH265DecodeSupported}}})}var Vu=Zd(i=>D(void 0,null,function*(){let t=Date.now(),e=Zm(),r=Uu(),o=qm();if(rt.detail.isWebRTCSupported=e,rt.detail.isMediaDevicesSupported=r,rt.detail.isWebCodecsSupported=o,rt.detail.isScreenShareSupported=mc(),rt.detail.isSmallStreamSupported=Bu(),i===37)return Object.assign(rt.detail,yield qI()),rt.detail.isBrowserSupported=o,rt.result=r&&o,rt.result||se.error(`${navigator.userAgent} ${Ha(rt.detail,!1)}`),L_(i),Se.addNumber({key:523800,value:Date.now()-t}),rt;if(rt.result&&rt.detail.isH264EncodeSupported&&rt.detail.isVp8EncodeSupported&&rt.detail.isH265EncodeSupported&&rt.detail.isH264DecodeSupported&&rt.detail.isVp8DecodeSupported&&rt.detail.isH265DecodeSupported)return rt;let s=jm(),{encode:n,decode:a}=yield WI(),{h264:c,vp8:d}=n,{h264:m}=a,{h265:l}=n,{vp8:f,h265:g}=a;if(!c||!d){let T=yield Jm();se.warn(`detect encode again h264:${c} vp8:${d} result: ${JSON.stringify(T)}`),c=T.isH264EncodeSupported,d=T.isVp8EncodeSupported}if(c&&m&&Bt&&Qr&&!ao&&!Si&&!(jn&&Fr===115)){let{encode:T,decode:E}=yield jI();c=T,m=E}return rt.result=s&&e&&r&&(c||d)&&(m||f),rt.detail.isBrowserSupported=s,rt.detail.isWebRTCSupported=e,rt.detail.isH264EncodeSupported=c,rt.detail.isVp8EncodeSupported=d,rt.detail.isH265EncodeSupported=l,rt.detail.isH264DecodeSupported=m,rt.detail.isVp8DecodeSupported=f,rt.detail.isH265DecodeSupported=g,rt.result||se.error(`${navigator.userAgent} ${Ha(rt.detail,!1)}`),L_(),Se.addNumber({key:523800,value:Date.now()-t}),rt})),GI=function(){return rt.result},mc=function(){return!!(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)},zI=typeof HTMLMediaElement!="undefined"&&"setSinkId"in HTMLMediaElement.prototype,ku=null;function jI(){return D(this,null,function*(){return ku||(ku=new Promise(i=>D(this,null,function*(){let t={encode:!1,decode:!1},e=()=>{};try{let r=document.createElement("canvas"),o=r.getContext("2d");r.width=640,r.height=480;let s=setInterval(()=>{o.fillText("test",Math.floor(Math.random()*640),Math.floor(Math.random()*480))},66),n=-1,a=-1;e=()=>{clearInterval(n),clearInterval(s),clearTimeout(a),d.close(),m.close(),c.getTracks().forEach(E=>E.stop())},a=setTimeout(()=>{e(),i(t)},2*1e3);let c=r.captureStream(),d=new RTCPeerConnection({}),m=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});d.addEventListener("icecandidate",E=>m.addIceCandidate(E.candidate)),m.addEventListener("icecandidate",E=>d.addIceCandidate(E.candidate)),d.addTrack(c.getVideoTracks()[0],c);let l=yield d.createOffer();yield d.setLocalDescription(l),yield m.setRemoteDescription(l);let f=yield m.createAnswer(),g=zm.default.parse(f.sdp),T=g.media[0].rtp.findIndex(E=>E.codec==="H264");g.media[0].rtp=[g.media[0].rtp[T]],g.media[0].fmtp=g.media[0].fmtp.filter(E=>E.payload===g.media[0].rtp[0].payload),g.media[0].rtcpFb&&(g.media[0].rtcpFb=g.media[0].rtcpFb.filter(E=>E.payload===g.media[0].rtp[0].payload)),f.sdp=zm.default.write(g),yield m.setLocalDescription(f),yield d.setRemoteDescription(f),n=setInterval(()=>D(this,null,function*(){t.encode&&t.decode&&(e(),i(t));let[E,y]=yield Promise.all([d.getSenders()[0].getStats(),m.getReceivers()[0].getStats()]);t.encode||E.forEach(v=>{v.type==="outbound-rtp"&&v.mediaType===j.VIDEO&&v.bytesSent>0&&(t.encode=!0)}),t.decode||y.forEach(v=>{v.type==="inbound-rtp"&&v.mediaType===j.VIDEO&&v.bytesReceived>0&&(t.decode=!0)})}),100)}catch(r){e(),se.warn("detectH264Supported failed",r),i({encode:!0,decode:!0})}})).then(i=>(i.encode||(i.decode=!0),(!i.encode||!i.decode)&&se.warn(`detectH264Supported encode: ${i.encode} decode: ${i.decode} ${yi}`),i)),ku)})}var Lu=null;function qI(){return D(this,null,function*(){return Lu||(Lu=new Promise(i=>D(this,null,function*(){let t={isH264EncodeSupported:!1,isH264DecodeSupported:!1,isVp8EncodeSupported:!1,isVp8DecodeSupported:!1};if(!qm()){i(t);return}let e=null,r=null,o=null,s=()=>{o&&clearTimeout(o),e=null,r=null};try{e=document.createElement("canvas"),r=e.getContext("2d"),e.width=320,e.height=240;let n=0,a=()=>{!r||!e||(r.fillStyle=`hsl(${n%360}, 50%, 50%)`,r.fillRect(0,0,e.width,e.height),r.fillStyle="white",r.font="20px Arial",r.fillText(`Frame ${n}`,10,30),n++)};o=setTimeout(()=>{s(),i(t)},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(m=>D(this,null,function*(){let l={type:m.type,encodeSupported:!1,decodeSupported:!1},f;try{f=yield new Promise((g,T)=>D(this,null,function*(){try{let E=new VideoEncoder({output:v=>{g(v),l.encodeSupported=!0},error:T});E.configure(m.encodeConfig),a();let y=new VideoFrame(e,{timestamp:0});E.encode(y,{keyFrame:!0}),y.close(),yield E.flush(),E.close()}catch(E){T(E)}}))}catch(g){return se.warn(`${m.type} encoder error:`,g),l}try{yield new Promise((g,T)=>D(this,null,function*(){try{let E=new VideoDecoder({output:y=>{l.decodeSupported=!0,g(0),y.close()},error:T});E.configure(m.decodeConfig),E.decode(f),yield E.flush(),E.close()}catch(E){T(E)}}))}catch(g){se.warn(`${m.type} decoder error:`,g)}return l})))).forEach(m=>{m.type==="h264"?(t.isH264EncodeSupported=m.encodeSupported,t.isH264DecodeSupported=m.decodeSupported):m.type==="vp8"&&(t.isVp8EncodeSupported=m.encodeSupported,t.isVp8DecodeSupported=m.decodeSupported)}),s(),i(t)}catch(n){s(),se.warn("detectWebCodecsSupported failed:",n),i(t)}})),Lu)})}var XI=(i,t,e)=>{location.protocol==="http:"&&!bi&&(i[t]=()=>{throw new Me({code:Te.INVALID_OPERATION,message:Wr.NOT_SUPPORTED_HTTP})})},JI=function(i){return i.type==="candidate-pair"&&i.nominated&&(i.state==="in-progress"||i.state==="succeeded")?!(Nt(i.selected)&&!i.selected):!1};function $_(){let i="";if(screen.width){let t=screen.width?screen.width*window.devicePixelRatio:"",e=screen.height?screen.height*window.devicePixelRatio:"";i+=`${t} * ${e}`}return i}function F_(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function H_(){let i={isSupported:!1},t=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"];for(let e=0;e<t.length;e++)if(t[e]in window){i.isSupported=!0;break}return i.isSupported}function W_(){return"captureStream"in HTMLCanvasElement.prototype}function G_(){return co||Ut||Fr&&Fr<63?!1:!!(jm()&&W_())}function z_(){return!(Fr<74||Ls||Tr<11||ou<46)}function Bu(){return G_()||z_()}var QI=function(){if(z(window.RTCRtpTransceiver)||!$u()||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let i=null,t=!1;try{i=new RTCPeerConnection({sdpSemantics:Gh}),i.addTransceiver(j.AUDIO),t=!0}catch(e){}return i==null||i.close(),t};function YI(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function j_(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function ZI(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function $u(){return Tr===11&&!Tm?!1:"RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype}var KI=!(!$u()||Qr&&Fr<86);function eb(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}var pc="RTCRtpSender"in window;function tb(){return pc&&"replaceTrack"in window.RTCRtpSender.prototype}function rb(){return pc&&"setParameters"in window.RTCRtpSender.prototype&&j_()}var ib="RTCRtpReceiver"in window&&"getSynchronizationSources"in window.RTCRtpReceiver.prototype,ea=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,Qm=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,Ym=typeof InputDeviceInfo!="undefined"&&"getCapabilities"in InputDeviceInfo.prototype,zs=pc&&"createEncodedStreams"in window.RTCRtpSender.prototype&&yu()>=86,q_="RTCRtpScriptTransform"in window,fc=pc&&(zs||q_),Zm=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(t=>t in window).length>0};function Fu(){let i={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return z(window.AudioDecoder)||(i.AudioDecoder=!0),z(window.AudioEncoder)||(i.AudioEncoder=!0),z(window.VideoDecoder)||(i.VideoDecoder=!0),z(window.VideoEncoder)||(i.VideoEncoder=!0),z(window.ImageDecoder)||(i.ImageDecoder=!0),i}function X_(){return"mediaSession"in navigator&&!z(navigator.mediaSession.setActionHandler)}function J_(){return!z(window.WebTransport)}function Km(){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 ob(){let i={browser:`${Bi.name}/${Bi.version}`,os:Jn(),displayResolution:$_(),isScreenShareSupported:mc(),isWebRTCSupported:Zm(),isGetUserMediaSupported:F_(),isWebAudioSupported:H_(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:Fu(),isMediaSessionSupported:X_(),isWebTransportSupported:J_()};return navigator.userAgent.includes("miniProgram")&&(i.browser=`mini/${i.browser}`),i}var Q_="checkResult";function L_(i=30){Yn.setItem(Q_+i,{ua:navigator.userAgent,checkResult:rt})}function ep(i){Eo();let t=Yn.getItem(Q_+i);t&&t.ua===navigator.userAgent&&t.checkResult&&sb(t.checkResult.detail,rt.detail)&&(rt=t.checkResult),Vu(i)}function sb(i,t){return Xr(i)?Object.keys(t).every(e=>e in i):!1}function Ri(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var nb="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype;function P_(i){return{h264:1,h265:2,vp8:3,vp9:4,av1:5}[i]}var U_=!1;function tp(){return D(this,null,function*(){var i;try{if(U_||!((i=navigator==null?void 0:navigator.mediaCapabilities)!=null&&i.encodingInfo))return;let t=Bs(),e=Sm();if(t===0||e===0)return;U_=!0;let r=["H264","VP8","VP9","AV1","H265"],[o,s]=yield Promise.all([Y_(r),Z_(r)]);o&&Object.keys(o).forEach(c=>{let d=P_(c.toLowerCase());Se.addEnum({key:513707,value:+`${d}${+o[c].supported}${+o[c].powerEfficient}${t}${e}`,useUV:!1})}),s&&Object.keys(s).forEach(c=>{let d=P_(c.toLowerCase());Se.addEnum({key:514713,value:+`${d}${+s[c].supported}${+s[c].powerEfficient}${t}${e}`,useUV:!1})});let{sender:n,receiver:a}=K_();Se.addEnum({key:513708,value:+`${t}${e}${+n.high}`,useUV:!1}),Se.addEnum({key:513709,value:+`${t}${e}${+n.main}`,useUV:!1}),Se.addEnum({key:514714,value:+`${t}${e}${+a.high}`,useUV:!1}),Se.addEnum({key:514715,value:+`${t}${e}${+a.main}`,useUV:!1})}catch(t){se.info("detectVideoCodecCapabilities failed",t)}})}function Y_(i,t=1920,e=1080,r=30,o=3e3){return D(this,null,function*(){let s={};try{for(let n of i){let a=yield navigator.mediaCapabilities.encodingInfo({type:"webrtc",video:{contentType:`video/${n}`,width:t,height:e,bitrate:o,framerate:r}});s[n]=a}}catch(n){}return s})}function Z_(i,t=1920,e=1080,r=30,o=3e3){return D(this,null,function*(){let s={};try{for(let n of i){let a=yield navigator.mediaCapabilities.decodingInfo({type:"webrtc",video:{contentType:`video/${n}`,width:t,height:e,bitrate:o,framerate:r}});s[n]=a}}catch(n){}return s})}function K_(){let i={sender:{base:!1,main:!1,high:!1},receiver:{base:!1,main:!1,high:!1}};try{if(RTCRtpSender&&typeof RTCRtpSender.getCapabilities=="function"){let t=RTCRtpSender.getCapabilities("video");t&&t.codecs&&t.codecs.filter(r=>r.mimeType.toLowerCase()==="video/h264").forEach(r=>{if(r.sdpFmtpLine){let o=r.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(o&&o[1])switch(o[1].slice(0,2)){case"42":i.sender.base=!0;break;case"4d":i.sender.main=!0;break;case"64":i.sender.high=!0;break}}})}if(RTCRtpReceiver&&typeof RTCRtpReceiver.getCapabilities=="function"){let t=RTCRtpReceiver.getCapabilities("video");t&&t.codecs&&t.codecs.filter(r=>r.mimeType.toLowerCase()==="video/h264").forEach(r=>{if(r.sdpFmtpLine){let o=r.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(o&&o[1])switch(o[1].slice(0,2)){case"42":i.receiver.base=!0;break;case"4d":i.receiver.main=!0;break;case"64":i.receiver.high=!0;break}}})}}catch(t){se.warn("get H264 profile levelId failed",t)}return i}var tE=Li(mo(),1);var eE=Symbol("instance"),Nw=Symbol("abortCtrl"),Hu=Symbol("cacheResult"),gc=class{constructor(t,e,r){this.oldState=t,this.newState=e,this.action=r,this.aborted=!1}abort(t){this.aborted=!0,Tc.call(t,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},_c=class extends Error{constructor(t,e,r){super(e),this.state=t,this.message=e,this.cause=r}};function ab(i){return typeof i=="object"&&i&&"then"in i}var Ec=new Map;function Mt(i,t,e={}){return(r,o,s)=>{let n=e.action||o;if(!e.context){let c=Ec.get(r)||[];Ec.has(r)||Ec.set(r,c),c.push({from:i,to:t,action:n})}let a=s.value;s.value=function(...c){let d=this;if(e.context&&(d=Ve.get(typeof e.context=="function"?e.context.call(this,...c):e.context)),d.state===t)return e.sync?d[Hu]:Promise.resolve(d[Hu]);d.state instanceof gc&&d.state.action==e.abortAction&&d.state.abort(d);let m=null;Array.isArray(i)?i.length==0?d.state instanceof gc&&d.state.abort(d):(typeof d.state!="string"||!i.includes(d.state))&&(m=new _c(d._state,`${d.name} ${n} to ${t} failed: current state ${d._state} not from ${i.join("|")}`)):i!==d.state&&(m=new _c(d._state,`${d.name} ${n} to ${t} failed: current state ${d._state} not from ${i}`));let l=y=>{if(e.fail&&e.fail.call(this,y),e.sync){if(e.ignoreError)return y;throw y}else return e.ignoreError?Promise.resolve(y):Promise.reject(y)};if(m)return l(m);let f=d.state,g=new gc(f,t,n);Tc.call(d,g);let T=y=>{var v;return d[Hu]=y,g.aborted||(Tc.call(d,t),(v=e.success)===null||v===void 0||v.call(this,d[Hu])),y},E=y=>(Tc.call(d,f,y),l(y));try{let y=a.apply(this,c);return ab(y)?y.then(T).catch(E):e.sync?T(y):Promise.resolve(T(y))}catch(y){return E(new _c(d._state,`${d.name} ${n} from ${i} to ${t} failed: ${y}`,y instanceof Error?y:new Error(String(y))))}}}}var cb=typeof window!="undefined"&&window.__AFSM__?(e,r)=>{window.dispatchEvent(new CustomEvent(e,{detail:r}))}:typeof importScripts!="undefined"?(e,r)=>{postMessage({type:e,payload:r})}:()=>{};function Tc(i,t){let e=this._state;this._state=i;let r=i.toString();i&&this.emit(r,e),this.emit(Ve.STATECHANGED,i,e,t),this.updateDevTools({value:i,old:e,err:t instanceof Error?t.message:String(t)})}var Ve=class i extends tE.default{constructor(t,e,r){super(),this.name=t,this.groupName=e,this._state=i.INIT,t||(t=Date.now().toString(36)),r?Object.setPrototypeOf(this,r):r=Object.getPrototypeOf(this),e||(this.groupName=this.constructor.name);let o=r[eE];o?this.name=o.name+"-"+o.count++:r[eE]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let t=Object.getPrototypeOf(this),e=Ec.get(t)||[],r=new Set,o=[],s=[],n=new Set,a=Object.getPrototypeOf(t);Ec.has(a)&&(a.stateDiagram.forEach(d=>r.add(d)),a.allStates.forEach(d=>n.add(d))),e.forEach(({from:d,to:m,action:l})=>{typeof d=="string"?o.push({from:d,to:m,action:l}):d.length?d.forEach(f=>{o.push({from:f,to:m,action:l})}):s.push({to:m,action:l})}),o.forEach(({from:d,to:m,action:l})=>{n.add(d),n.add(m),n.add(l+"ing"),r.add(`${d} --> ${l}ing : ${l}`),r.add(`${l}ing --> ${m} : ${l} \u{1F7E2}`),r.add(`${l}ing --> ${d} : ${l} \u{1F534}`)}),s.forEach(({to:d,action:m})=>{r.add(`${m}ing --> ${d} : ${m} \u{1F7E2}`),n.forEach(l=>{l!==d&&r.add(`${l} --> ${m}ing : ${m}`)})});let c=[...r];return Object.defineProperties(t,{stateDiagram:{value:c},allStates:{value:n}}),c}static get(t){let e;return typeof t=="string"?(e=i.instances.get(t),e||i.instances.set(t,e=new i(t,void 0,Object.create(i.prototype)))):(e=i.instances2.get(t),e||i.instances2.set(t,e=new i(t.constructor.name,void 0,Object.create(i.prototype)))),e}static getState(t){var e;return(e=i.get(t))===null||e===void 0?void 0:e.state}updateDevTools(t={}){cb(i.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},t))}get state(){return this._state}set state(t){Tc.call(this,t)}};Ve.STATECHANGED="stateChanged";Ve.UPDATEAFSM="updateAFSM";Ve.INIT="[*]";Ve.ON="on";Ve.OFF="off";Ve.instances=new Map;Ve.instances2=new WeakMap;var ip=typeof window!="undefined",rE=ip&&window.requestIdleCallback||function(i){let t=Date.now();return setTimeout(()=>{i({didTimeout:!1,timeRemaining(){return Math.max(0,50-(Date.now()-t))}})},1e3)},db=ip&&window.cancelIdleCallback||function(i){clearTimeout(i)},iE=ip&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),ar=class ar{static generateTaskID(){return this.currentTaskID++}static run(t,e,r){r!=null&&r.fps&&(r.delay=r.delay||Number((1e3/r.fps).toFixed(2))),t==="interval"?r=be({delay:2e3,count:0,backgroundTask:!0},r):t==="ric"?r=be({delay:1e4,count:0},r):t==="raf"?r=be({fps:60,delay:16.6,count:0,backgroundTask:!0},r):r=be({delay:2e3,count:0,backgroundTask:!0},r);let o=qe(be({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:t,callback:e},r),{delay:r.delay});return this.taskMap.set(o.taskID,o),this[t](o),o.taskID}static interval(t){let e=()=>{t.callback(),t.loopCount+=1,ar.isBreakLoop(t)};return t.intervalID=setInterval(e,t.delay)}static intervalInWorker(t){ar.sharedWorker||(ar.sharedWorker=new Worker(URL.createObjectURL(new Blob([`
|
|
11
|
+
`,u+=s)),r&&(u+=`
|
|
12
|
+
Refer to: ${cp("en",a)}
|
|
13
|
+
`),u}var iu=Je(_p(),1);var IT=1,AT=0,lc=class{constructor(i=!0){d(this,"countMap",new Map);d(this,"distributionMap",new Map);d(this,"version");d(this,"log",R.createLogger({id:"kv"}));i&&(S.on("102",({track:e,cost:t})=>{this.addSuccessEvent({key:e.kind===p.AUDIO?501700:511700,cost:t})}),S.on("103",({track:e,error:t})=>{this.addFailedEvent({key:e.kind===p.AUDIO?501700:511700,error:t})}),S.on("266",({enable:e})=>{this.log.info(`${e?"enable":"disable"} sso`),e?this.addSuccessEvent({key:525701}):this.addFailedEvent({key:525701})}))}getReportData(i,e){let t={msg_sdk_basic_info:{uint32_sdk_version:Na(this.version||$e),uint32_terminal_type:15,bytes_device_name:"",bytes_os_version:"",uint32_framework:30,uint32_network_type:0},stats_count:[...this.countMap.entries()].map(([r,s])=>({uint32_key:r,uint32_count:s})),stats_distribution:[...this.distributionMap.entries()].map(([r,s])=>({uint32_key:r,distribution_items:[...s.entries()].map(([n,a])=>({uint32_item_key:n,uint32_item_value:a}))})),str_user_sig:i,bytes_report_token:e};return this.countMap.clear(),this.distributionMap.clear(),t}clear(){this.countMap.clear(),this.distributionMap.clear()}isEnumKey(i){let e=+String(i).slice(-3);return e>=700&&e<799}isErrorCodeKey(i){let e=+String(i).slice(-3);return e>=600&&e<699}isCountKey(i){let e=+String(i).slice(-3);return e>=0&&e<599}isNumberKey(i){let e=+String(i).slice(-3);return e>=800&&e<899}addCount({key:i,useUV:e=!1}){if(!this.isCountKey(i)){this.log.debug(`${i} is not count key, last 3 number should be 0~599`);return}e&&this.countMap.has(i)||this.countMap.set(i,(this.countMap.get(i)||0)+1)}addEnum({key:i,value:e,useUV:t=!0}){var s;if(!this.isEnumKey(i))return this.log.debug(`${i} is not enum key, last 3 number should be 700~799`);if(t&&this.countMap.has(i))return;this.countMap.set(i,(this.countMap.get(i)||0)+1);let r=((s=this.distributionMap)==null?void 0:s.get(i))||new Map;r.set(e,(r.get(e)||0)+1),this.distributionMap.set(i,r)}addNumber({key:i,value:e,split:t=100,useUV:r=!1,max:s=5e3}){var c;if(!this.isNumberKey(i))return this.log.debug(`${i} is not number key, last 3 number should be 800~899`);if(r&&this.countMap.has(i))return;e>s&&(e=s),this.countMap.set(i,(this.countMap.get(i)||0)+1);let n=((c=this.distributionMap)==null?void 0:c.get(i))||new Map,a=0;if(Q(t))a=Math.floor(e/t);else for(let l=t.length-1;l>0;l--)if(e>t[l]){a=l;break}n.set(a,(n.get(a)||0)+1),this.distributionMap.set(i,n)}addSuccessEvent({key:i,cost:e,timeKey:t,split:r}){if(i&&(this.addEnum({key:i,value:IT,useUV:!1}),e)){let s=+String(i).slice(-3);s<800&&s>=700?this.addNumber({key:t||i+100,value:e,split:r}):t||this.log.debug(`time stat ignored, ${i}`)}}addFailedEvent({key:i,error:e}){if(!i)return;let t=I.UNKNOWN;e&&(Q(e)?t=e:(!T(e.extraCode)||!T(e.code))&&(t=e.extraCode||e.code)),this.addEnum({key:i,value:AT,useUV:!1}),this.addEnum({key:i,value:Math.abs(t),useUV:!1})}},uc=(y=>(y[y.enterRoom=500700]="enterRoom",y[y.exitRoom=500701]="exitRoom",y[y.switchRole=500702]="switchRole",y[y.destroy=500703]="destroy",y[y.startLocalAudio=500704]="startLocalAudio",y[y.updateLocalAudio=500705]="updateLocalAudio",y[y.stopLocalAudio=500706]="stopLocalAudio",y[y.startLocalVideo=500707]="startLocalVideo",y[y.updateLocalVideo=500708]="updateLocalVideo",y[y.stopLocalVideo=500709]="stopLocalVideo",y[y.startScreenShare=500710]="startScreenShare",y[y.updateScreenShare=500711]="updateScreenShare",y[y.stopScreenShare=500712]="stopScreenShare",y[y.startRemoteVideo=500713]="startRemoteVideo",y[y.updateRemoteVideo=500714]="updateRemoteVideo",y[y.stopRemoteVideo=500715]="stopRemoteVideo",y[y.muteRemoteAudio=500716]="muteRemoteAudio",y[y.setRemoteAudioVolume=500717]="setRemoteAudioVolume",y[y.use=500718]="use",y[y.switchRoom=500719]="switchRoom",y[y.sendSEIMessage=5e5]="sendSEIMessage",y[y.sendCustomMessage=500001]="sendCustomMessage",y))(uc||{}),Kl=(m=>(m[m.AudioMixer=550700]="AudioMixer",m[m.AIDenoiser=551700]="AIDenoiser",m[m.VirtualBackground=570700]="VirtualBackground",m[m.Beauty=571700]="Beauty",m[m.Watermark=572700]="Watermark",m[m.BasicBeauty=574700]="BasicBeauty",m[m.CDNStreaming=590700]="CDNStreaming",m[m.DeviceDetector=591700]="DeviceDetector",m[m.Debug=592700]="Debug",m[m.SmallStreamAutoSwitcher=593700]="SmallStreamAutoSwitcher",m[m.VideoMixer=594700]="VideoMixer",m[m.AudioProcessor=595700]="AudioProcessor",m))(Kl||{}),eu=(m=>(m[m.AudioMixer=550701]="AudioMixer",m[m.AIDenoiser=551701]="AIDenoiser",m[m.VirtualBackground=570701]="VirtualBackground",m[m.Beauty=571701]="Beauty",m[m.Watermark=572701]="Watermark",m[m.BasicBeauty=574701]="BasicBeauty",m[m.CDNStreaming=590701]="CDNStreaming",m[m.DeviceDetector=591701]="DeviceDetector",m[m.Debug=592701]="Debug",m[m.SmallStreamAutoSwitcher=593701]="SmallStreamAutoSwitcher",m[m.VideoMixer=594701]="VideoMixer",m[m.AudioProcessor=595701]="AudioProcessor",m))(eu||{}),tu=(m=>(m[m.AudioMixer=550702]="AudioMixer",m[m.AIDenoiser=551702]="AIDenoiser",m[m.VirtualBackground=570702]="VirtualBackground",m[m.Beauty=571702]="Beauty",m[m.Watermark=572702]="Watermark",m[m.BasicBeauty=574702]="BasicBeauty",m[m.CDNStreaming=590702]="CDNStreaming",m[m.DeviceDetector=591702]="DeviceDetector",m[m.Debug=592702]="Debug",m[m.SmallStreamAutoSwitcher=593702]="SmallStreamAutoSwitcher",m[m.VideoMixer=594702]="VideoMixer",m[m.AudioProcessor=595702]="AudioProcessor",m))(tu||{});var os=(w=>(w[w.DECODER_TYPE=514700]="DECODER_TYPE",w[w.DECODER_HW_SW=514701]="DECODER_HW_SW",w[w.DECODE_RESULT=514702]="DECODE_RESULT",w[w.DECODE_FAILED_OS=514703]="DECODE_FAILED_OS",w[w.DOWNGRADE_RESULT=514704]="DOWNGRADE_RESULT",w[w.DOWNGRADE_WEBCODECS_VIDEO=514705]="DOWNGRADE_WEBCODECS_VIDEO",w[w.DOWNGRADE_WEBCODECS_2D=514706]="DOWNGRADE_WEBCODECS_2D",w[w.DOWNGRADE_WASM_WEGBL=514707]="DOWNGRADE_WASM_WEGBL",w[w.DOWNGRADE_WASM_VIDEO=514708]="DOWNGRADE_WASM_VIDEO",w[w.DOWNGRADE_WASM_2D=514709]="DOWNGRADE_WASM_2D",w[w.DECODE_H264_RESULT=514710]="DECODE_H264_RESULT",w[w.DECODE_H265_RESULT=514711]="DECODE_H265_RESULT",w[w.DECODE_VP8_RESULT=514712]="DECODE_VP8_RESULT",w[w.DECODE_CAPABILITIES=514713]="DECODE_CAPABILITIES",w[w.H264_PROFILE_LEVEL_ID_HIGH=514714]="H264_PROFILE_LEVEL_ID_HIGH",w[w.H264_PROFILE_LEVEL_ID_MAIN=514715]="H264_PROFILE_LEVEL_ID_MAIN",w[w.RENDER_FREEZE_RATE=514850]="RENDER_FREEZE_RATE",w[w.DATA_FREEZE_RATE=514851]="DATA_FREEZE_RATE",w[w.VIDEO_CONSUME_RENDER_RATE=514852]="VIDEO_CONSUME_RENDER_RATE",w))(os||{});var CT=new lc(!0),ro=new lc(!1);var v=CT;var ee={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}},RT=new Map([[te,["Firefox",Ua]],[jo,["Edg",Ba]],[Ko,["Chrome",Ka]],[Pe,["Safari",Xi]],[ri,["TBS",$a]],[qi,["XWEB",Wa]],[ji&&Sr,["WeChat",Ga]],[Qs,["QQ(Win)",Ja]],[zo,["QQ(Mobile)",Go]],[Xo,["QQ(Mobile X5)",Go]],[Ys,["QQ(Mac)",qa]],[Zs,["QQ(iPad)",ja]],[en,["MI",Xa]],[tn,["HW",za]],[on,["Samsung",Qa]],[Qo,["OPPO",Ya]],[sn,["VIVO",Za]],[zr,["EDGE",Va]],[Xs,["SogouMobile",Fa]],[zs,["Sogou",Ha]]]);function yT(){let o=RT.get(!0),i=o?o[0]:"unknown",e=o?o[1]:"unknown";return{browserName:i,browserVersion:e}}var ou=function(){return!(yl||zr||jo&&Cl<80||te&&qo<56)},pn=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder"].every(i=>i in window)},pc=function(){if(!navigator.mediaDevices)return Zi()||R.error(je.NOT_SUPPORTED_MEDIA),!1;let o=["getUserMedia","enumerateDevices"];return o.filter(i=>i in navigator.mediaDevices).length===o.length},gp=!1;function Zi(){return location.protocol==="http:"&&!si?(gp||R.error(H({key:B.NOT_SUPPORTED_HTTP})),gp=!0,!0):!1}var fn=function(){return(window==null?void 0:window.OffscreenCanvas)&&(window==null?void 0:window.MediaStreamTrackProcessor)&&(window==null?void 0:window.MediaStreamTrackGenerator)},bT=function(){return!!(window!=null&&window.MediaStreamTrackGenerator)},su=function(){return f(this,null,function*(){var r,s,n;if(ee.detail.isH264EncodeSupported&&ee.detail.isVp8EncodeSupported)return{isH264EncodeSupported:ee.detail.isH264EncodeSupported,isVp8EncodeSupported:ee.detail.isVp8EncodeSupported,isH265EncodeSupported:ee.detail.isH265EncodeSupported};let o,i=!1,e=!1,t=!1;try{let a=new RTCPeerConnection,c=document.createElement(p.CANVAS);c.getContext("2d");let l=c.captureStream(0);return a.addTrack(l.getVideoTracks()[0],l),o=yield a.createOffer(),i=((r=o.sdp)==null?void 0:r.toLowerCase().indexOf("h264"))!==-1,e=((s=o.sdp)==null?void 0:s.toLowerCase().indexOf("vp8"))!==-1,t=((n=o.sdp)==null?void 0:n.toLowerCase().indexOf("h265"))!==-1,a.close(),{isH264EncodeSupported:i,isVp8EncodeSupported:e,isH265EncodeSupported:t}}catch(a){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1}}})},fc=function(){return f(this,null,function*(){var t;if(ee.detail.isH264DecodeSupported&&ee.detail.isVp8DecodeSupported)return{isH264DecodeSupported:ee.detail.isH264DecodeSupported,isVp8DecodeSupported:ee.detail.isVp8DecodeSupported,isH265DecodeSupported:ee.detail.isH265DecodeSupported};let o,i=!1,e=!1;try{let r=new RTCPeerConnection;St()?(r.addTransceiver(p.VIDEO,{direction:"recvonly"}),o=yield r.createOffer()):o=yield r.createOffer({offerToReceiveVideo:!0}),o.sdp.toLowerCase().indexOf("h264")!==-1&&(i=!0),o.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0);let s=((t=o.sdp)==null?void 0:t.toLowerCase().indexOf("h265"))!==-1;return r.close(),{isH264DecodeSupported:i,isVp8DecodeSupported:e,isH265DecodeSupported:s}}catch(r){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}}})};function vT(){return f(this,null,function*(){let[o,i]=yield Promise.all([su(),fc()]);return{encode:{h264:o.isH264EncodeSupported,vp8:o.isVp8EncodeSupported,h265:o.isH265EncodeSupported},decode:{h264:i.isH264DecodeSupported,vp8:i.isVp8DecodeSupported,h265:i.isH265DecodeSupported}}})}var _c=Da(o=>f(void 0,null,function*(){let i=Date.now(),e=lu(),t=pc(),r=pn();if(ee.detail.isWebRTCSupported=e,ee.detail.isMediaDevicesSupported=t,ee.detail.isWebCodecsSupported=r,ee.detail.isScreenShareSupported=_n(),ee.detail.isSmallStreamSupported=Tc(),o===37)return Object.assign(ee.detail,yield MT()),ee.detail.isBrowserSupported=r,ee.result=t&&r,ee.result||R.error(`${navigator.userAgent} ${Gs(ee.detail,!1)}`),Tp(o),v.addNumber({key:523800,value:Date.now()-i}),ee;if(ee.result&&ee.detail.isH264EncodeSupported&&ee.detail.isVp8EncodeSupported&&ee.detail.isH265EncodeSupported&&ee.detail.isH264DecodeSupported&&ee.detail.isVp8DecodeSupported&&ee.detail.isH265DecodeSupported)return ee;let s=ou(),{encode:n,decode:a}=yield vT(),{h264:c,vp8:l}=n,{h264:u}=a,{h265:h}=n,{vp8:m,h265:_}=a;if(!c||!l){let g=yield su();R.warn(`detect encode again h264:${c} vp8:${l} result: ${JSON.stringify(g)}`),c=g.isH264EncodeSupported,l=g.isVp8EncodeSupported}if(c&&u&&_e&&We&&!qi&&!ri&&!(Qo&&qe===115)){let{encode:g,decode:E}=yield OT();c=g,u=E}return ee.result=s&&e&&t&&(c||l)&&(u||m),ee.detail.isBrowserSupported=s,ee.detail.isWebRTCSupported=e,ee.detail.isH264EncodeSupported=c,ee.detail.isVp8EncodeSupported=l,ee.detail.isH265EncodeSupported=h,ee.detail.isH264DecodeSupported=u,ee.detail.isVp8DecodeSupported=m,ee.detail.isH265DecodeSupported=_,ee.result||R.error(`${navigator.userAgent} ${Gs(ee.detail,!1)}`),Tp(),v.addNumber({key:523800,value:Date.now()-i}),ee})),NT=function(){return ee.result},_n=function(){return!!(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)},DT=typeof HTMLMediaElement!="undefined"&&"setSinkId"in HTMLMediaElement.prototype,hc=null;function OT(){return f(this,null,function*(){return hc||(hc=new Promise(o=>f(this,null,function*(){let i={encode:!1,decode:!1},e=()=>{};try{let t=document.createElement("canvas"),r=t.getContext("2d");t.width=640,t.height=480;let s=setInterval(()=>{r.fillText("test",Math.floor(Math.random()*640),Math.floor(Math.random()*480))},66),n=-1,a=-1;e=()=>{clearInterval(n),clearInterval(s),clearTimeout(a),l.close(),u.close(),c.getTracks().forEach(E=>E.stop())},a=setTimeout(()=>{e(),o(i)},2*1e3);let c=t.captureStream(),l=new RTCPeerConnection({}),u=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});l.addEventListener("icecandidate",E=>u.addIceCandidate(E.candidate)),u.addEventListener("icecandidate",E=>l.addIceCandidate(E.candidate)),l.addTrack(c.getVideoTracks()[0],c);let h=yield l.createOffer();yield l.setLocalDescription(h),yield u.setRemoteDescription(h);let m=yield u.createAnswer(),_=iu.default.parse(m.sdp),g=_.media[0].rtp.findIndex(E=>E.codec==="H264");_.media[0].rtp=[_.media[0].rtp[g]],_.media[0].fmtp=_.media[0].fmtp.filter(E=>E.payload===_.media[0].rtp[0].payload),_.media[0].rtcpFb&&(_.media[0].rtcpFb=_.media[0].rtcpFb.filter(E=>E.payload===_.media[0].rtp[0].payload)),m.sdp=iu.default.write(_),yield u.setLocalDescription(m),yield l.setRemoteDescription(m),n=setInterval(()=>f(this,null,function*(){i.encode&&i.decode&&(e(),o(i));let[E,C]=yield Promise.all([l.getSenders()[0].getStats(),u.getReceivers()[0].getStats()]);i.encode||E.forEach(k=>{k.type==="outbound-rtp"&&k.mediaType===p.VIDEO&&k.bytesSent>0&&(i.encode=!0)}),i.decode||C.forEach(k=>{k.type==="inbound-rtp"&&k.mediaType===p.VIDEO&&k.bytesReceived>0&&(i.decode=!0)})}),100)}catch(t){e(),R.warn("detectH264Supported failed",t),o({encode:!0,decode:!0})}})).then(o=>(o.encode||(o.decode=!0),(!o.encode||!o.decode)&&R.warn(`detectH264Supported encode: ${o.encode} decode: ${o.decode} ${ii}`),o)),hc)})}var mc=null;function MT(){return f(this,null,function*(){return mc||(mc=new Promise(o=>f(this,null,function*(){let i={isH264EncodeSupported:!1,isH264DecodeSupported:!1,isVp8EncodeSupported:!1,isVp8DecodeSupported:!1};if(!pn()){o(i);return}let e=null,t=null,r=null,s=()=>{r&&clearTimeout(r),e=null,t=null};try{e=document.createElement("canvas"),t=e.getContext("2d"),e.width=320,e.height=240;let n=0,a=()=>{!t||!e||(t.fillStyle=`hsl(${n%360}, 50%, 50%)`,t.fillRect(0,0,e.width,e.height),t.fillStyle="white",t.font="20px Arial",t.fillText(`Frame ${n}`,10,30),n++)};r=setTimeout(()=>{s(),o(i)},5e3);let c=[{type:"h264",encodeConfig:{codec:"avc1.42E01E",avc:{format:"annexb"},width:320,height:240,bitrate:1e6},decodeConfig:{codec:"avc1.42E01E",avc:{format:"annexb"}}},{type:"vp8",encodeConfig:{codec:"vp8",width:320,height:240,bitrate:1e6},decodeConfig:{codec:"vp8"}}];(yield Promise.all(c.map(u=>f(this,null,function*(){let h={type:u.type,encodeSupported:!1,decodeSupported:!1},m;try{m=yield new Promise((_,g)=>f(this,null,function*(){try{let E=new VideoEncoder({output:k=>{_(k),h.encodeSupported=!0},error:g});E.configure(u.encodeConfig),a();let C=new VideoFrame(e,{timestamp:0});E.encode(C,{keyFrame:!0}),C.close(),yield E.flush(),E.close()}catch(E){g(E)}}))}catch(_){return R.warn(`${u.type} encoder error:`,_),h}try{yield new Promise((_,g)=>f(this,null,function*(){try{let E=new VideoDecoder({output:C=>{h.decodeSupported=!0,_(0),C.close()},error:g});E.configure(u.decodeConfig),E.decode(m),yield E.flush(),E.close()}catch(E){g(E)}}))}catch(_){R.warn(`${u.type} decoder error:`,_)}return h})))).forEach(u=>{u.type==="h264"?(i.isH264EncodeSupported=u.encodeSupported,i.isH264DecodeSupported=u.decodeSupported):u.type==="vp8"&&(i.isVp8EncodeSupported=u.encodeSupported,i.isVp8DecodeSupported=u.decodeSupported)}),s(),o(i)}catch(n){s(),R.warn("detectWebCodecsSupported failed:",n),o(i)}})),mc)})}var kT=(o,i,e)=>{location.protocol==="http:"&&!si&&(o[i]=()=>{throw new D({code:I.INVALID_OPERATION,message:je.NOT_SUPPORTED_HTTP})})},Cr=function(o){return o.type==="candidate-pair"&&o.nominated&&(o.state==="in-progress"||o.state==="succeeded")?!(me(o.selected)&&!o.selected):!1};function Ip(){let o="";if(screen.width){let i=screen.width?screen.width*window.devicePixelRatio:"",e=screen.height?screen.height*window.devicePixelRatio:"";o+=`${i} * ${e}`}return o}function Ap(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function Cp(){let o={isSupported:!1},i=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"];for(let e=0;e<i.length;e++)if(i[e]in window){o.isSupported=!0;break}return o.isSupported}function Rp(){return"captureStream"in HTMLCanvasElement.prototype}function gc(){return ji||Te||qe&&qe<63?!1:!!(ou()&&Rp())}function yp(){return!(qe<74||zr||et<11||qo<46)}function Tc(){return gc()||yp()}var PT=function(){if(T(window.RTCRtpTransceiver)||!St()||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let o=null,i=!1;try{o=new RTCPeerConnection({sdpSemantics:gr}),o.addTransceiver(p.AUDIO),i=!0}catch(e){}return o==null||o.close(),i};function oo(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function Rr(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function yr(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function St(){return et===11&&!kl?!1:"RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype}var ss=!(!St()||We&&qe<86);function wT(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}var gn="RTCRtpSender"in window;function nu(){return gn&&"replaceTrack"in window.RTCRtpSender.prototype}function Tn(){return gn&&"setParameters"in window.RTCRtpSender.prototype&&Rr()}var au="RTCRtpReceiver"in window&&"getSynchronizationSources"in window.RTCRtpReceiver.prototype,bi=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,cu=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,du=typeof InputDeviceInfo!="undefined"&&"getCapabilities"in InputDeviceInfo.prototype,mi=gn&&"createEncodedStreams"in window.RTCRtpSender.prototype&&Zo()>=86,ns="RTCRtpScriptTransform"in window,En=gn&&(mi||ns),lu=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(i=>i in window).length>0};function Ec(){let o={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return T(window.AudioDecoder)||(o.AudioDecoder=!0),T(window.AudioEncoder)||(o.AudioEncoder=!0),T(window.VideoDecoder)||(o.VideoDecoder=!0),T(window.VideoEncoder)||(o.VideoEncoder=!0),T(window.ImageDecoder)||(o.ImageDecoder=!0),o}function bp(){return"mediaSession"in navigator&&!T(navigator.mediaSession.setActionHandler)}function vp(){return!T(window.WebTransport)}function uu(){return typeof WebAssembly=="undefined"?!1:WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]))}function LT(){let o={browser:`${Ri.name}/${Ri.version}`,os:tc(),displayResolution:Ip(),isScreenShareSupported:_n(),isWebRTCSupported:lu(),isGetUserMediaSupported:Ap(),isWebAudioSupported:Cp(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:Ec(),isMediaSessionSupported:bp(),isWebTransportSupported:vp()};return navigator.userAgent.includes("miniProgram")&&(o.browser=`mini/${o.browser}`),o}var Np="checkResult";function Tp(o=30){ts.setItem(Np+o,{ua:navigator.userAgent,checkResult:ee})}function hu(o){Zi();let i=ts.getItem(Np+o);i&&i.ua===navigator.userAgent&&i.checkResult&&xT(i.checkResult.detail,ee.detail)&&(ee=i.checkResult),_c(o)}function xT(o,i){return yt(o)?Object.keys(i).every(e=>e in o):!1}function Ki(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var Sc="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype;function Ep(o){return{h264:1,h265:2,vp8:3,vp9:4,av1:5}[o]}var Sp=!1;function mu(){return f(this,null,function*(){var o;try{if(Sp||!((o=navigator==null?void 0:navigator.mediaCapabilities)!=null&&o.encodingInfo))return;let i=Zr(),e=wl();if(i===0||e===0)return;Sp=!0;let t=["H264","VP8","VP9","AV1","H265"],[r,s]=yield Promise.all([Dp(t),Op(t)]);r&&Object.keys(r).forEach(c=>{let l=Ep(c.toLowerCase());v.addEnum({key:513707,value:+`${l}${+r[c].supported}${+r[c].powerEfficient}${i}${e}`,useUV:!1})}),s&&Object.keys(s).forEach(c=>{let l=Ep(c.toLowerCase());v.addEnum({key:514713,value:+`${l}${+s[c].supported}${+s[c].powerEfficient}${i}${e}`,useUV:!1})});let{sender:n,receiver:a}=Mp();v.addEnum({key:513708,value:+`${i}${e}${+n.high}`,useUV:!1}),v.addEnum({key:513709,value:+`${i}${e}${+n.main}`,useUV:!1}),v.addEnum({key:514714,value:+`${i}${e}${+a.high}`,useUV:!1}),v.addEnum({key:514715,value:+`${i}${e}${+a.main}`,useUV:!1})}catch(i){R.info("detectVideoCodecCapabilities failed",i)}})}function Dp(o,i=1920,e=1080,t=30,r=3e3){return f(this,null,function*(){let s={};try{for(let n of o){let a=yield navigator.mediaCapabilities.encodingInfo({type:"webrtc",video:{contentType:`video/${n}`,width:i,height:e,bitrate:r,framerate:t}});s[n]=a}}catch(n){}return s})}function Op(o,i=1920,e=1080,t=30,r=3e3){return f(this,null,function*(){let s={};try{for(let n of o){let a=yield navigator.mediaCapabilities.decodingInfo({type:"webrtc",video:{contentType:`video/${n}`,width:i,height:e,bitrate:r,framerate:t}});s[n]=a}}catch(n){}return s})}function Mp(){let o={sender:{base:!1,main:!1,high:!1},receiver:{base:!1,main:!1,high:!1}};try{if(RTCRtpSender&&typeof RTCRtpSender.getCapabilities=="function"){let i=RTCRtpSender.getCapabilities("video");i&&i.codecs&&i.codecs.filter(t=>t.mimeType.toLowerCase()==="video/h264").forEach(t=>{if(t.sdpFmtpLine){let r=t.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(r&&r[1])switch(r[1].slice(0,2)){case"42":o.sender.base=!0;break;case"4d":o.sender.main=!0;break;case"64":o.sender.high=!0;break}}})}if(RTCRtpReceiver&&typeof RTCRtpReceiver.getCapabilities=="function"){let i=RTCRtpReceiver.getCapabilities("video");i&&i.codecs&&i.codecs.filter(t=>t.mimeType.toLowerCase()==="video/h264").forEach(t=>{if(t.sdpFmtpLine){let r=t.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(r&&r[1])switch(r[1].slice(0,2)){case"42":o.receiver.base=!0;break;case"4d":o.receiver.main=!0;break;case"64":o.receiver.high=!0;break}}})}}catch(i){R.warn("get H264 profile levelId failed",i)}return o}var Pp=Je(at(),1);var kp=Symbol("instance"),OC=Symbol("abortCtrl"),Ic=Symbol("cacheResult"),Sn=class{constructor(i,e,t){this.oldState=i,this.newState=e,this.action=t,this.aborted=!1}abort(i){this.aborted=!0,Cn.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},In=class extends Error{constructor(i,e,t){super(e),this.state=i,this.message=e,this.cause=t}};function UT(o){return typeof o=="object"&&o&&"then"in o}var An=new Map;function ye(o,i,e={}){return(t,r,s)=>{let n=e.action||r;if(!e.context){let c=An.get(t)||[];An.has(t)||An.set(t,c),c.push({from:o,to:i,action:n})}let a=s.value;s.value=function(...c){let l=this;if(e.context&&(l=q.get(typeof e.context=="function"?e.context.call(this,...c):e.context)),l.state===i)return e.sync?l[Ic]:Promise.resolve(l[Ic]);l.state instanceof Sn&&l.state.action==e.abortAction&&l.state.abort(l);let u=null;Array.isArray(o)?o.length==0?l.state instanceof Sn&&l.state.abort(l):(typeof l.state!="string"||!o.includes(l.state))&&(u=new In(l._state,`${l.name} ${n} to ${i} failed: current state ${l._state} not from ${o.join("|")}`)):o!==l.state&&(u=new In(l._state,`${l.name} ${n} to ${i} failed: current state ${l._state} not from ${o}`));let h=C=>{if(e.fail&&e.fail.call(this,C),e.sync){if(e.ignoreError)return C;throw C}else return e.ignoreError?Promise.resolve(C):Promise.reject(C)};if(u)return h(u);let m=l.state,_=new Sn(m,i,n);Cn.call(l,_);let g=C=>{var k;return l[Ic]=C,_.aborted||(Cn.call(l,i),(k=e.success)===null||k===void 0||k.call(this,l[Ic])),C},E=C=>(Cn.call(l,m,C),h(C));try{let C=a.apply(this,c);return UT(C)?C.then(g).catch(E):e.sync?g(C):Promise.resolve(g(C))}catch(C){return E(new In(l._state,`${l.name} ${n} from ${o} to ${i} failed: ${C}`,C instanceof Error?C:new Error(String(C))))}}}}var VT=typeof window!="undefined"&&window.__AFSM__?(e,t)=>{window.dispatchEvent(new CustomEvent(e,{detail:t}))}:typeof importScripts!="undefined"?(e,t)=>{postMessage({type:e,payload:t})}:()=>{};function Cn(o,i){let e=this._state;this._state=o;let t=o.toString();o&&this.emit(t,e),this.emit(q.STATECHANGED,o,e,i),this.updateDevTools({value:o,old:e,err:i instanceof Error?i.message:String(i)})}var q=class o extends Pp.default{constructor(i,e,t){super(),this.name=i,this.groupName=e,this._state=o.INIT,i||(i=Date.now().toString(36)),t?Object.setPrototypeOf(this,t):t=Object.getPrototypeOf(this),e||(this.groupName=this.constructor.name);let r=t[kp];r?this.name=r.name+"-"+r.count++:t[kp]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let i=Object.getPrototypeOf(this),e=An.get(i)||[],t=new Set,r=[],s=[],n=new Set,a=Object.getPrototypeOf(i);An.has(a)&&(a.stateDiagram.forEach(l=>t.add(l)),a.allStates.forEach(l=>n.add(l))),e.forEach(({from:l,to:u,action:h})=>{typeof l=="string"?r.push({from:l,to:u,action:h}):l.length?l.forEach(m=>{r.push({from:m,to:u,action:h})}):s.push({to:u,action:h})}),r.forEach(({from:l,to:u,action:h})=>{n.add(l),n.add(u),n.add(h+"ing"),t.add(`${l} --> ${h}ing : ${h}`),t.add(`${h}ing --> ${u} : ${h} \u{1F7E2}`),t.add(`${h}ing --> ${l} : ${h} \u{1F534}`)}),s.forEach(({to:l,action:u})=>{t.add(`${u}ing --> ${l} : ${u} \u{1F7E2}`),n.forEach(h=>{h!==l&&t.add(`${h} --> ${u}ing : ${u}`)})});let c=[...t];return Object.defineProperties(i,{stateDiagram:{value:c},allStates:{value:n}}),c}static get(i){let e;return typeof i=="string"?(e=o.instances.get(i),e||o.instances.set(i,e=new o(i,void 0,Object.create(o.prototype)))):(e=o.instances2.get(i),e||o.instances2.set(i,e=new o(i.constructor.name,void 0,Object.create(o.prototype)))),e}static getState(i){var e;return(e=o.get(i))===null||e===void 0?void 0:e.state}updateDevTools(i={}){VT(o.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){Cn.call(this,i)}};q.STATECHANGED="stateChanged";q.UPDATEAFSM="updateAFSM";q.INIT="[*]";q.ON="on";q.OFF="off";q.instances=new Map;q.instances2=new WeakMap;var fu=typeof window!="undefined",wp=fu&&window.requestIdleCallback||function(o){let i=Date.now();return setTimeout(()=>{o({didTimeout:!1,timeRemaining(){return Math.max(0,50-(Date.now()-i))}})},1e3)},BT=fu&&window.cancelIdleCallback||function(o){clearTimeout(o)},Lp=fu&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),Be=class Be{static generateTaskID(){return this.currentTaskID++}static run(i,e,t){t!=null&&t.fps&&(t.delay=t.delay||Number((1e3/t.fps).toFixed(2))),i==="interval"?t=M({delay:2e3,count:0,backgroundTask:!0},t):i==="ric"?t=M({delay:1e4,count:0},t):i==="raf"?t=M({fps:60,delay:16.6,count:0,backgroundTask:!0},t):t=M({delay:2e3,count:0,backgroundTask:!0},t);let r=L(M({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:i,callback:e},t),{delay:t.delay});return this.taskMap.set(r.taskID,r),this[i](r),r.taskID}static interval(i){let e=()=>{i.callback(),i.loopCount+=1,Be.isBreakLoop(i)};return i.intervalID=setInterval(e,i.delay)}static intervalInWorker(i){Be.sharedWorker||(Be.sharedWorker=new Worker(URL.createObjectURL(new Blob([`
|
|
13
14
|
const timers = new Map();
|
|
14
15
|
self.onmessage = function(e) {
|
|
15
16
|
const { taskId, delay, type } = e.data;
|
|
@@ -22,15 +23,15 @@ Refer to: ${v_("en",a)}
|
|
|
22
23
|
timers.delete(taskId);
|
|
23
24
|
}
|
|
24
25
|
};
|
|
25
|
-
`],{type:"application/javascript"}))),
|
|
26
|
-
${r.stack}`));let s=zo.enable?so(o,2002,Number(this._configs.sdkAppId)):JSON.stringify(o);this.sendRequest(oo(this._configs.sdkAppId,Bo.LOG),s)}sendRequest(t,e){setTimeout(()=>no({url:t,body:e,priority:"low"}).catch(()=>{}),2e3)}},It=new op;var js=new WeakMap;function qs({settings:i={retries:5,timeout:2e3},onError:t,onRetrying:e,onRetryFailed:r}){return function(o,s,n){let a=Ho({retryFunction:n.value,settings:i,onError({error:c,retry:d,reject:m,retryFuncArgs:l}){var f;t?t.call(this,c,()=>{var g;(g=js.get(o))!=null&&g.has(s)?d():m(c)},m,l):(f=js.get(o))!=null&&f.has(s)?d():m(c)},onRetrying(c,d){var m;Fo(e)&&e.call(this,c,d),(m=js.get(o))!=null&&m.has(s)&&(js.get(o).get(s).stopRetry=d)},onRetryFailed:r});return n.value=function(...c){let d=js.get(o);return d?d.set(s,{args:c}):js.set(o,new Map([[s,{args:c}]])),a.apply(this,c).finally(()=>{var m;return(m=js.get(o))==null?void 0:m.delete(s)})},n}}var Ci=class extends Ve{constructor(e,r){super(e.id,`${r}-player`);this.options=e;this.kind=r;p(this,"id");p(this,"element",null);p(this,"track");p(this,"url");p(this,"attr");p(this,"mode");p(this,"muted");p(this,"_log");p(this,"_isPausedByUserCall",!1);p(this,"_pausedRetryCount");p(this,"_isElementPlayingFired",!1);p(this,"_interval");p(this,"_delayDestroyTimeoutId",0);p(this,"_playSuccessResolve");p(this,"_isReplayByRecreateMediaStreamCalled",!1);p(this,"isInAutoPlayFailedState",!1);this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=Cs,this._state="STOPPED",this.bindTrackEvents(),this._log.info(`create ${r}-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 D(this,null,function*(){if(!this.isPlaying)try{this._delayDestroyTimeoutId&&(clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0,this.bindTrackEvents(),this.bindElementEvents()),this.bindAutoPlayEvent(),yield new Promise((e,r)=>{this._playSuccessResolve=e,this.element.play().then(e,r)})}catch(e){let r=Et({key:_t.PLAY_FAILED,data:{media:this.kind,error:e}});if(this._log.warn(e),r.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new Me({code:Te.PLAY_NOT_ALLOWED,message:r})}})}stop(e=0){var r;this._isElementPlayingFired=!1,this.unbindEvents(),e>0&&!ni?this._delayDestroyTimeoutId||((r=this.element)==null||r.remove(),this._log.info(`destroy element after 3 * ${e}`),this._delayDestroyTimeoutId=setTimeout(()=>this.destroyElement(),3*e)):this.destroyElement(),this.handleStopped(j.ENDED),this._interval>0&&Jt.clearTask(this._interval)}destroyElement(){this.element&&(this._log.debug("destroy element"),this.element.remove(),this.element.src="",this.element.srcObject=null,this.element=null),clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0}pause(){var e;this._log.info("pause"),(e=this.element)==null||e.pause(),this._isPausedByUserCall=!0,this instanceof Sr&&Qr&&Fr>=128&&this.setPoster(this.getVideoFrame())}resume(){return this._isPausedByUserCall=!1,this.doResume()}doResume(){return this._log.info("resume"),this._isPausedByUserCall||this.isPlaying?Promise.resolve():_m?this.replay():(this.element&&this.track&&Qr&&Fr>=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 yr(this.element,this.element).add(j.PLAYING,e).add(j.ENDED,e).add(j.PAUSE,e).add(j.ERROR,e).add(j.LOADEDDATA,e).add(j.LOADEDMETADATA,e)}}bindTrackEvents(e=this.track){if(e){let r=this.handleTrackEvent.bind(this);Hi==null||Hi.create(e,e).add(j.ENDED,r).add(j.MUTE,r).add(j.UNMUTE,r),e.readyState===j.ENDED&&this.handleTrackEvent({type:j.ENDED}),e.muted&&this.handleTrackEvent({type:j.MUTE})}}bindAutoPlayEvent(){ee.on(ce.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(e=this.track){e&&tr(e)}unbindEvents(){this.element&&tr(this.element),this.unbindTrackEvents(),ee.off(ce.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case j.PLAYING:Qo()||(this.isInAutoPlayFailedState=!1),this._isElementPlayingFired=!0,this._log.info(`${this.kind} player is playing`),this.handlePlaying(j.PLAYING),this._interval&&(Jt.clearTask(this._interval),this._interval=-1);break;case j.ENDED:this._log.info(`${this.kind} player is ended`),this.handleStopped(j.ENDED);break;case j.PAUSE:this._log.info(`${this.kind} player is paused`),this.handlePaused(j.PAUSE),Ut&&(this._interval=Jt.run("timeout",()=>{this.element&&this._state==="PAUSED"&&this.doResume()},{delay:3e3}));break;case j.ERROR:if(this.element&&this.element.error){this.handlePaused(j.ERROR);let{code:o,message:s}=this.element.error;this._log.error(`${this.kind} ${this._log.isLocal?"local":"remote"} MediaError code: ${o} message: ${s} userAgent: ${navigator.userAgent}`),It.uploadEvent({log:`stat-${this.kind}-${ii.PLAYER_ERROR}-${o}-${navigator.userAgent}`,error:this.element.error}),hm||Ka?this.emit(St.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case j.LOADEDDATA:this.kind===j.VIDEO&&this.emit(St.LOADED_DATA);break;case j.LOADEDMETADATA:this.kind===j.VIDEO&&this.emit(St.LOADED_META_DATA);break}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then(()=>{this._log.warn("replayByRecreateMediaStream success"),It.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),Se.addSuccessEvent({key:this.kind===j.AUDIO?506700:516700})}).catch(()=>{var r;this._log.error("replayByRecreateMediaStream failed"),It.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),Se.addFailedEvent({key:this.kind===j.AUDIO?506700:516700,error:(r=this.element)==null?void 0:r.error}),this.emit(St.ERROR,e)})}doReplayByRecreateMediaStream(e){return this._log.warn(`delay ${e}ms to recreate mediaStream`),new Promise((r,o)=>{Ti(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`),o((a=this.element)==null?void 0:a.error)}),Ti(5e3).then(()=>{var s,n;(!this.isPlaying||(s=this.element)!=null&&s.error)&&o((n=this.element)==null?void 0:n.error),r()})})}).finally(()=>{this.element&&(this.element.onerror=null)})}handleTrackEvent(e){return D(this,null,function*(){switch(e.type){case j.ENDED:this.handleStopped(j.ENDED);break;case j.MUTE:this.handlePaused(j.MUTE);break;case j.UNMUTE:this.mode>0?this.handlePlaying(this.mode.toString()):this.element&&(this.element.paused&&(this._log.warn("track unmuted and element is paused, resume"),yield this.doResume()),!this.element.paused&&this._isElementPlayingFired&&this.handlePlaying(j.UNMUTE));break}})}handlePlaying(e){var r;return this._log.debug("handlePlaying",e),(r=this._playSuccessResolve)==null||r.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}};p(Ci,"PlayerEvent",St),Ie([qs({settings:{retries:2,timeout:0},onError(e,r,o,s){s[0]=(s[0]||1e3)+1e3,r()}})],Ci.prototype,"doReplayByRecreateMediaStream",1),Ie([Mt([],"PLAYING",{sync:!0,success(e){this.emit(St.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}})],Ci.prototype,"handlePlaying",1),Ie([Mt("PLAYING","PAUSED",{ignoreError:!0,sync:!0,success(e){this.emit(St.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}})],Ci.prototype,"handlePaused",1),Ie([Mt([],"STOPPED",{sync:!0,success(e){this.emit(St.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}})],Ci.prototype,"handleStopped",1);var To="trtc_autoplay",sp=`${To}_mask`,Sc=`${To}_wrapper`,oE=`${To}_header`,np=`${To}_content`,Wu=`${To}_action_wrapper`,ap=`${To}_question`,cp=`${To}_collapse`,Gu=`${To}_action_confirm`,sE=`${To}_detail`,nE="#2473E8",lp="dialog",lb=`${lp}-show`,hb=`${lp}-1`,mb=`${lp}-2`,aE=!1,dp=!1,Qo=()=>dp,dE=`${Br}/${_i()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,cE=`<br><a href='${dE}' target='_blank'>${_i()?"\u5176\u4ED6\u65B9\u6848\uFF1F":"Any other solution?"}</a>`,pb=`${_i()?`\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${cE}`:`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. ${cE}`}`,up=class{constructor(){p(this,"content","\u97F3\u89C6\u9891\u64AD\u653E\u88AB\u6D4F\u89C8\u5668\u62E6\u622A\uFF0C\u8BF7\u70B9\u51FB\u201C\u6062\u590D\u64AD\u653E\u201D\u3002");p(this,"_dialogNode",null);p(this,"_bodyPosition","");p(this,"_showDetail",!1);p(this,"_isCollapseClicked",!1);p(this,"_isQuestionClicked",!1);if(_i()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!aE){let t=document.createElement("style");t.innerHTML=`.${sp}{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;}.${sp} div:not(.${Wu}){display:block !important;}.${Sc}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${Sc} a{color:${nE};}.${oE}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${np}{margin:8px 0;}.${Wu}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${cp}{margin-right:auto;cursor:pointer}.${ap}{height:100%;line-height:16px;cursor:pointer;}.${Gu}{margin-left:8px;color:#fff;background:${nE};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${Gu}:hover{opacity:0.9;}.${cp},.${Gu},.${np},.${ap}{font-size:14px;}@media screen and (max-width:750px){.${Sc}{width:80vw;}}`,document.head.appendChild(t),aE=!0}this.addDiaLog()}createDiaLog(){let t=document.createElement("template");t.innerHTML=`<div class="${sp}"><div class='${Sc}'><div class='${oE}'>${location.host}</div><div class='${np}'>${this.content}</div><div class='${sE}' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">${pb}</div><div class='${Wu}'></div></div></div>`.trim();let e=document.createElement("button");e.className=Gu,e.innerText=_i()?"\u6062\u590D\u64AD\u653E":"Resume",e.onclick=this.onConfirm.bind(this);let r=document.createElement("div");r.className=ap,r.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=U(),t,r=()=>{if(t=U()-e,t>=i.delay&&(e=U()-Math.floor(t%i.delay),i.callback(),i.loopCount+=1),!Be.isBreakLoop(i))return i.ricID=wp(r,{timeout:i.delay})};return i.ricID=wp(r,{timeout:i.delay})}static raf(i){let e=U(),t,r=()=>{if(document.hidden&&i.backgroundTask)return t=U()-e,e=U(),i.callback(),i.loopCount+=1,Be.isBreakLoop(i)?void 0:i.timeoutID=setTimeout(r,i.delay-Math.floor(t%i.delay));if(t=U()-e,t>=i.delay&&(e=U()-Math.floor(t%i.delay),i.callback(),i.loopCount+=1),!Be.isBreakLoop(i))return i.rafID=requestAnimationFrame(r)};if(i.rafID=requestAnimationFrame(r),i.backgroundTask){let s=()=>{if(document.hidden){let n=U()-e;n>=i.delay?r():i.timeoutID=setTimeout(r,i.delay-n)}};document.addEventListener("visibilitychange",s),i.onVisibilitychange=s,document.hidden&&s()}return i.taskID}static hasTask(i){return this.taskMap.has(i)}static clearTask(i){if(!this.taskMap.has(i))return!0;let{intervalID:e,timeoutID:t,rafID:r,ricID:s,onVisibilitychange:n}=this.taskMap.get(i);return e&&clearInterval(e),t&&clearTimeout(t),r&&Lp&&Lp(r),s&&BT(s),n&&document.removeEventListener("visibilitychange",n),this.taskMap.delete(i),!0}static isBreakLoop(i){return this.hasTask(i.taskID)?i.count!==0&&i.loopCount>=i.count?(this.clearTask(i.taskID),!0):!1:!0}};d(Be,"taskMap",new Map),d(Be,"currentTaskID",1),d(Be,"sharedWorker",null),d(Be,"workerTasks",new Map);var pu=Be,re=pu;var FC={STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",STREAM_UPDATED:"stream-updated",STREAM_SUBSCRIBED:"stream-subscribed",CONNECTION_STATE_CHANGED:"connection-state-changed",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",MUTE_AUDIO:"mute-audio",MUTE_VIDEO:"mute-video",UNMUTE_AUDIO:"unmute-audio",UNMUTE_VIDEO:"unmute-video",CLIENT_BANNED:"client-banned",NETWORK_QUALITY:"network-quality",AUDIO_VOLUME:"audio-volume",SEI_MESSAGE:p.SEI_MESSAGE,ERROR:"error"};var he={LOADED_DATA:p.LOADEDDATA,LOADED_META_DATA:p.LOADEDMETADATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error",RESIZE:p.RESIZE,TIME_UPDATE:"time-update"};var Ni={};Vi(Ni,{create:()=>tt,remove:()=>Le});var Rn=new WeakMap;function tt(o,i){Rn.has(o)||Rn.set(o,[]);let e=Rn.get(o),r={add:(s,n)=>("addEventListener"in i?(e.push(i.removeEventListener.bind(i,s,n)),i.addEventListener(s,n)):(e.push(i.off.bind(i,s,n)),i.on(s,n)),r)};return r}function Le(o){let i=Rn.get(o);i&&(i.forEach(e=>e()),Rn.delete(o))}var _u=class{constructor(){d(this,"_roomIdMap",new Map);d(this,"_configs");typeof registerProcessor=="undefined"&&(this._configs={sdkAppId:"",userId:"",version:$e,env:Fi.QCLOUD,browserVersion:Ri.name+Ri.version,ua:navigator.userAgent})}setConfig({sdkAppId:i,env:e,userId:t,roomId:r}){i!==this._configs.sdkAppId&&(this._configs.sdkAppId=String(i)),this._configs.env=e,this._configs.userId=t,this._roomIdMap.set(t,String(r))}logSuccessEvent(i){si||!R.isAbleToUpload||this._configs.env===Fi.QCLOUD&&this.uploadEventToKibana(L(M({},i),{result:"success"}))}logFailedEvent(i){if(si||!R.isAbleToUpload)return;let{eventType:e,code:t,error:r,userId:s}=i,n={roomId:this._roomIdMap.get(s||this._configs.userId),userId:s,eventType:e,result:"failed",code:t||(r==null?void 0:r.extraCode)||(r==null?void 0:r.code)||I.UNKNOWN};this._configs.env===Fi.QCLOUD&&this.uploadEventToKibana(L(M({},n),{error:r}))}uploadEventToKibana(i){let e=`stat-${i.eventType}-${i.result}`;(i.eventType==="delta-join"||i.eventType==="delta-leave"||i.eventType==="delta-publish")&&(e=`${i.eventType}:${i.delta}`),this.uploadEvent({log:e,userId:i.userId}),i.result==="failed"&&(e=`stat-${i.eventType}-${i.result}-${i.code}`,this.uploadEvent({log:e,userId:i.userId,error:i.error}))}uploadEvent({log:i,userId:e,error:t}){let r={timestamp:la(),sdkAppId:this._configs.sdkAppId,userId:e||this._configs.userId,version:$e,log:i};t&&(r.errorInfo=t.message,t.stack&&(r.errorInfo+=`
|
|
27
|
+
${t.stack}`));let s=Ir.enable?Gi(r,2002,Number(this._configs.sdkAppId)):JSON.stringify(r);this.sendRequest(Wi(this._configs.sdkAppId,mr.LOG),s)}sendRequest(i,e){setTimeout(()=>Ji({url:i,body:e,priority:"low"}).catch(()=>{}),2e3)}},oe=new _u;var Di=new WeakMap;function Ot({settings:o={retries:5,timeout:2e3},onError:i,onRetrying:e,onRetryFailed:t}){return function(r,s,n){let a=Ci({retryFunction:n.value,settings:o,onError({error:c,retry:l,reject:u,retryFuncArgs:h}){var m;i?i.call(this,c,()=>{var _;(_=Di.get(r))!=null&&_.has(s)?l():u(c)},u,h):(m=Di.get(r))!=null&&m.has(s)?l():u(c)},onRetrying(c,l){var u;Ai(e)&&e.call(this,c,l),(u=Di.get(r))!=null&&u.has(s)&&(Di.get(r).get(s).stopRetry=l)},onRetryFailed:t});return n.value=function(...c){let l=Di.get(r);return l?l.set(s,{args:c}):Di.set(r,new Map([[s,{args:c}]])),a.apply(this,c).finally(()=>{var u;return(u=Di.get(r))==null?void 0:u.delete(s)})},n}}function yn({fnName:o,callback:i,validateArgs:e=!0}){return function(t,r,s){let n=s.value;return s.value=function(...a){var c,l;if((c=Di.get(t))!=null&&c.has(o)){let{stopRetry:u,args:h}=Di.get(t).get(o),m=!0;if(e){for(let _ of h)if(!a.find(g=>g===_)){m=!1;break}}m&&(i&&i.apply(this,a),u&&u(),(l=Di.get(t))==null||l.delete(o))}return n.apply(this,a)},s}}var pi=class extends q{constructor(e,t){super(e.id,`${t}-player`);this.options=e;this.kind=t;d(this,"id");d(this,"element",null);d(this,"track");d(this,"url");d(this,"attr");d(this,"mode");d(this,"muted");d(this,"_log");d(this,"_isPausedByUserCall",!1);d(this,"_pausedRetryCount");d(this,"_isElementPlayingFired",!1);d(this,"_interval");d(this,"_delayDestroyTimeoutId",0);d(this,"_playSuccessResolve");d(this,"_isReplayByRecreateMediaStreamCalled",!1);d(this,"isInAutoPlayFailedState",!1);this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=$r,this._state="STOPPED",this.bindTrackEvents(),this._log.info(`create ${t}-player ${this.id}`)}get isPlaying(){var e;return this._state==="PLAYING"&&((e=this.element)==null?void 0:e.paused)===!1}get isPaused(){var e;return this._state==="PAUSED"||((e=this.element)==null?void 0:e.paused)===!0}get isStopped(){return this._state==="STOPPED"}setAttr(e){this.attr=e}setUrl(e){this.track&&(this.unbindTrackEvents(),this.element&&(this.element.srcObject=null),this.track=null),e!==this.url&&(this.url=e,e!==null&&this.element&&(this.element.crossOrigin="anonymous",this.element.src=e))}play(){return f(this,null,function*(){if(!this.isPlaying)try{this._delayDestroyTimeoutId&&(clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0,this.bindTrackEvents(),this.bindElementEvents()),this.bindAutoPlayEvent(),yield new Promise((e,t)=>{this._playSuccessResolve=e,this.element.play().then(e,t)})}catch(e){let t=H({key:B.PLAY_FAILED,data:{media:this.kind,error:e}});if(this._log.warn(e),t.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new D({code:I.PLAY_NOT_ALLOWED,message:t})}})}stop(e=0){var t;this._isElementPlayingFired=!1,this.unbindEvents(),e>0&&!Ft?this._delayDestroyTimeoutId||((t=this.element)==null||t.remove(),this._log.info(`destroy element after 3 * ${e}`),this._delayDestroyTimeoutId=setTimeout(()=>this.destroyElement(),3*e)):this.destroyElement(),this.handleStopped(p.ENDED),this._interval>0&&re.clearTask(this._interval)}destroyElement(){this.element&&(this._log.debug("destroy element"),this.element.remove(),this.element.src="",this.element.srcObject=null,this.element=null),clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0}pause(){var e;this._log.info("pause"),(e=this.element)==null||e.pause(),this._isPausedByUserCall=!0,this instanceof it&&We&&qe>=128&&this.setPoster(this.getVideoFrame())}resume(){return this._isPausedByUserCall=!1,this.doResume()}doResume(){return this._log.info("resume"),this._isPausedByUserCall||this.isPlaying?Promise.resolve():Ol?this.replay():(this.element&&this.track&&We&&qe>=128&&(this.element.srcObject=new MediaStream([this.track])),this.play().catch(()=>{}))}setMuted(e){this.element&&(this.element.muted=e),this.muted=e}replay(){return this.stop(),this.play().catch(()=>{})}bindElementEvents(){if(this.element){let e=this.handleElementEvent.bind(this);return tt(this.element,this.element).add(p.PLAYING,e).add(p.ENDED,e).add(p.PAUSE,e).add(p.ERROR,e).add(p.LOADEDDATA,e).add(p.LOADEDMETADATA,e)}}bindTrackEvents(e=this.track){if(e){let t=this.handleTrackEvent.bind(this);Ni==null||Ni.create(e,e).add(p.ENDED,t).add(p.MUTE,t).add(p.UNMUTE,t),e.readyState===p.ENDED&&this.handleTrackEvent({type:p.ENDED}),e.muted&&this.handleTrackEvent({type:p.MUTE})}}bindAutoPlayEvent(){S.on(A.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(e=this.track){e&&Le(e)}unbindEvents(){this.element&&Le(this.element),this.unbindTrackEvents(),S.off(A.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case p.PLAYING:br()||(this.isInAutoPlayFailedState=!1),this._isElementPlayingFired=!0,this._log.info(`${this.kind} player is playing`),this.handlePlaying(p.PLAYING),this._interval&&(re.clearTask(this._interval),this._interval=-1);break;case p.ENDED:this._log.info(`${this.kind} player is ended`),this.handleStopped(p.ENDED);break;case p.PAUSE:this._log.info(`${this.kind} player is paused`),this.handlePaused(p.PAUSE),Te&&(this._interval=re.run("timeout",()=>{this.element&&this._state==="PAUSED"&&this.doResume()},{delay:3e3}));break;case p.ERROR:if(this.element&&this.element.error){this.handlePaused(p.ERROR);let{code:r,message:s}=this.element.error;this._log.error(`${this.kind} ${this._log.isLocal?"local":"remote"} MediaError code: ${r} message: ${s} userAgent: ${navigator.userAgent}`),oe.uploadEvent({log:`stat-${this.kind}-${Ze.PLAYER_ERROR}-${r}-${navigator.userAgent}`,error:this.element.error}),bl||rn?this.emit(he.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case p.LOADEDDATA:this.kind===p.VIDEO&&this.emit(he.LOADED_DATA);break;case p.LOADEDMETADATA:this.kind===p.VIDEO&&this.emit(he.LOADED_META_DATA);break}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then(()=>{this._log.warn("replayByRecreateMediaStream success"),oe.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),v.addSuccessEvent({key:this.kind===p.AUDIO?506700:516700})}).catch(()=>{var t;this._log.error("replayByRecreateMediaStream failed"),oe.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),v.addFailedEvent({key:this.kind===p.AUDIO?506700:516700,error:(t=this.element)==null?void 0:t.error}),this.emit(he.ERROR,e)})}doReplayByRecreateMediaStream(e){return this._log.warn(`delay ${e}ms to recreate mediaStream`),new Promise((t,r)=>{Ke(e).then(()=>{this.element&&(this.element.srcObject=null,this.element.srcObject=new MediaStream([this.track]),this._log.warn("recreated mediaStream"),this.element.onerror=()=>{var s,n,a;this._log.warn(`element onerror ${(n=(s=this.element)==null?void 0:s.error)==null?void 0:n.code} fired after recreated mediaStream`),r((a=this.element)==null?void 0:a.error)}),Ke(5e3).then(()=>{var s,n;(!this.isPlaying||(s=this.element)!=null&&s.error)&&r((n=this.element)==null?void 0:n.error),t()})})}).finally(()=>{this.element&&(this.element.onerror=null)})}handleTrackEvent(e){return f(this,null,function*(){switch(e.type){case p.ENDED:this.handleStopped(p.ENDED);break;case p.MUTE:this.handlePaused(p.MUTE);break;case p.UNMUTE:this.mode>0?this.handlePlaying(this.mode.toString()):this.element&&(this.element.paused&&(this._log.warn("track unmuted and element is paused, resume"),yield this.doResume()),!this.element.paused&&this._isElementPlayingFired&&this.handlePlaying(p.UNMUTE));break}})}handlePlaying(e){var t;return this._log.debug("handlePlaying",e),(t=this._playSuccessResolve)==null||t.call(this,e),e}handlePaused(e){return this._log.debug("handlePaused",e),e}handleStopped(e){return this._log.debug("handleStopped",e),e}getElement(){return this.element}};d(pi,"PlayerEvent",he),O([Ot({settings:{retries:2,timeout:0},onError(e,t,r,s){s[0]=(s[0]||1e3)+1e3,t()}})],pi.prototype,"doReplayByRecreateMediaStream",1),O([ye([],"PLAYING",{sync:!0,success(e){this.emit(he.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}})],pi.prototype,"handlePlaying",1),O([ye("PLAYING","PAUSED",{ignoreError:!0,sync:!0,success(e){this.emit(he.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}})],pi.prototype,"handlePaused",1),O([ye([],"STOPPED",{sync:!0,success(e){this.emit(he.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}})],pi.prototype,"handleStopped",1);var er="trtc_autoplay",gu=`${er}_mask`,bn=`${er}_wrapper`,xp=`${er}_header`,Tu=`${er}_content`,Ac=`${er}_action_wrapper`,Eu=`${er}_question`,Su=`${er}_collapse`,Cc=`${er}_action_confirm`,Up=`${er}_detail`,Vp="#2473E8",Cu="dialog",HT=`${Cu}-show`,$T=`${Cu}-1`,WT=`${Cu}-2`,Bp=!1,Iu=!1,br=()=>Iu,Hp=`${ft}/${Zt()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,Fp=`<br><a href='${Hp}' target='_blank'>${Zt()?"\u5176\u4ED6\u65B9\u6848\uFF1F":"Any other solution?"}</a>`,GT=`${Zt()?`\u6D4F\u89C8\u5668\u81EA\u52A8\u64AD\u653E\u7B56\u7565\uFF1A\u5728\u7528\u6237\u4E0E\u9875\u9762\u4EA7\u751F\u4EA4\u4E92\uFF08\u70B9\u51FB\u3001\u89E6\u6478\uFF09\u4E4B\u524D\uFF0C\u6D4F\u89C8\u5668\u7981\u6B62\u64AD\u653E\u6709\u58F0\u5A92\u4F53\u3002\u8BE5\u5F39\u7A97\u7528\u4E8E\u5E2E\u52A9\u7528\u6237\u6062\u590D\u97F3\u89C6\u9891\u64AD\u653E\u3002${Fp}`:`Autoplay Policy: Before user interacts with the web page (clicking, touching), page will not be allowed to play media with sound. This Dialog is used to help users resume playback. ${Fp}`}`,Au=class{constructor(){d(this,"content","\u97F3\u89C6\u9891\u64AD\u653E\u88AB\u6D4F\u89C8\u5668\u62E6\u622A\uFF0C\u8BF7\u70B9\u51FB\u201C\u6062\u590D\u64AD\u653E\u201D\u3002");d(this,"_dialogNode",null);d(this,"_bodyPosition","");d(this,"_showDetail",!1);d(this,"_isCollapseClicked",!1);d(this,"_isQuestionClicked",!1);if(Zt()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!Bp){let i=document.createElement("style");i.innerHTML=`.${gu}{position:fixed;top:0;left:0;right:0;bottom:0;width:100vw;height:100vh;display:flex;justify-content:center;align-items:center;background:rgba(0,0,0,0.5);z-index:1500;}.${gu} div:not(.${Ac}){display:block !important;}.${bn}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${bn} a{color:${Vp};}.${xp}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${Tu}{margin:8px 0;}.${Ac}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${Su}{margin-right:auto;cursor:pointer}.${Eu}{height:100%;line-height:16px;cursor:pointer;}.${Cc}{margin-left:8px;color:#fff;background:${Vp};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${Cc}:hover{opacity:0.9;}.${Su},.${Cc},.${Tu},.${Eu}{font-size:14px;}@media screen and (max-width:750px){.${bn}{width:80vw;}}`,document.head.appendChild(i),Bp=!0}this.addDiaLog()}createDiaLog(){let i=document.createElement("template");i.innerHTML=`<div class="${gu}"><div class='${bn}'><div class='${xp}'>${location.host}</div><div class='${Tu}'>${this.content}</div><div class='${Up}' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">${GT}</div><div class='${Ac}'></div></div></div>`.trim();let e=document.createElement("button");e.className=Cc,e.innerText=Zt()?"\u6062\u590D\u64AD\u653E":"Resume",e.onclick=this.onConfirm.bind(this);let t=document.createElement("div");t.className=Eu,t.innerHTML=`<?xml version="1.0" encoding="UTF-8"?>
|
|
27
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">
|
|
28
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"/>
|
|
29
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"/>
|
|
30
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"/>
|
|
31
32
|
</svg>
|
|
32
|
-
`,r.onclick=this.onQuestionClick.bind(this);let o=document.createElement("div");o.className=cp,o.innerText=`${_i()?"\u8BE6\u60C5 >":"Detail >"}`,o.onclick=this.onCollapseClick.bind(this);let s=t.content.firstChild,n=s.querySelector(`.${Wu}`);return n.appendChild(o),n.appendChild(r),n.appendChild(e),s}addDiaLog(){Qo()||(dp=!0,this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${Sc}`).onclick=t=>t.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",se.info("show autoplay dialog"),It.uploadEvent({log:lb}))}deleteDialog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null,dp=!1)}onConfirm(){se.warn("confirm clicked, try resume stream"),ee.emit(ce.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDialog()}onCollapseClick(){let t=this._dialogNode.querySelector(`.${sE}`);t.style.visibility=`${this._showDetail?"hidden":"visible"}`,t.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||It.uploadEvent({log:hb}),this._isCollapseClicked=!0}onQuestionClick(){window.open(dE,"_blank"),this._isQuestionClicked||It.uploadEvent({log:mb}),this._isQuestionClicked=!0}},Ic=null;function ta(){Ic||(Ic=new up)}function uE(){Ic&&(Ic.deleteDialog(),Ic=null)}var Sr=class extends Ci{constructor(e){super(e,j.VIDEO);p(this,"stat",{});p(this,"_calculateTimeout",-1);p(this,"viewMirror",!1);p(this,"objectFit");p(this,"container");p(this,"canvas");p(this,"shouldRenderAlpha",!1);p(this,"_preSize",{width:0,height:0});this.mode=e.canvas?1:0,this.container=e.container,this.canvas=e.canvas,z(e.viewMirror)||(this.viewMirror=e.viewMirror),z(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 r;let e=document.createElement(j.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,Bt&&(e.poster="noposter"),(r=this.container)==null||r.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 r;this.container=e,this.track&&this.elementToRender&&((r=this.container)==null||r.appendChild(this.elementToRender))}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),e&&e.add(j.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(j.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent).add(j.RESIZE,this.handleElementEvent)}handleTrackEvent(e){var r;return e.type===j.MUTE&&((r=this.stat)!=null&&r.fps)&&(this.stat.fps=0),super.handleTrackEvent(e)}handleElementEvent(e){var o,s,n,a,c,d;if(this.mode===2)return;super.handleElementEvent(e);let r=e.type;if(r===j.PAUSE&&(this.container&&!this.container.isConnected&&(this._log.warn(`${this.kind} player has been remove, element ID: ${this.container.id}`),Ti(500).then(()=>{var m;(m=this.container)!=null&&m.isConnected&&(this._pausedRetryCount=Cs,this._log.info(`view container ${this.container.id} is in dom, reset pausedRetryCount`))})),this._pausedRetryCount>0&&!Qo()&&!this._isPausedByUserCall&&(this._log.info(`[${Cs-this._pausedRetryCount+1}/${Cs}] ${this.kind} player auto resume when paused`),this.doResume(),this._pausedRetryCount--),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){let m=this.element.style.transform;r===j.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=m.replace("scaleX(-1)",""):r===j.LEAVE_PICTURE_IN_PICTURE&&!m.includes("scaleX")&&(this.element.style.transform=`${m} scaleX(-1)`)}r===j.RESIZE&&(this._preSize.height!==((o=this.element)==null?void 0:o.videoHeight)||this._preSize.width!==((s=this.element)==null?void 0:s.videoWidth))&&(this._log.info(`video size changed to ${(n=this.element)==null?void 0:n.videoWidth}x${(a=this.element)==null?void 0:a.videoHeight}`),this._preSize.height=((c=this.element)==null?void 0:c.videoHeight)||0,this._preSize.width=((d=this.element)==null?void 0:d.videoWidth)||0,this.emit(St.RESIZE,{newWidth:this._preSize.width,newHeight:this._preSize.height}))}setCanvas(e,r=1){var o,s,n,a;this.canvas!==e&&((o=this.canvas)==null||o.remove(),e==null||e.setAttribute("style",this.styleAttribute),this.canvas=e,this.mode=e?r: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 r=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},e);r.style=Object.assign({width:"100%",height:"100%"},r.style),super.setAttr(r)}get mirror(){return this.viewMirror}setRect(e,r){this.elementToRender&&(this.elementToRender.style.width=`${e}px`,this.elementToRender.style.height=`${r}px`)}setViewMirror(e){this.elementToRender&&(this.elementToRender.style.transform=e?"scaleX(-1)":""),this.viewMirror=e}setObjectFit(e){this.elementToRender&&(this.elementToRender.style.objectFit=`${e}`),this.objectFit=e}setPoster(e){this.element&&(this.element.poster=e)}stop(e=0){var r;super.stop(e),(r=this.canvas)==null||r.remove()}play(){return this.element?this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender):this.initializeElement(),this.mode===2?Promise.resolve():super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(St.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(Ri()&&this.element&&this._calculateTimeout<0){let e=0,r=null,o=(s,n)=>{this.stat.width=n.width,this.stat.height=n.height,r&&(this.stat.fps=Math.round((n.presentedFrames-r.presentedFrames)/(s-e)*1e3)),e=s,r=n,this._calculateTimeout=-1,this.element&&(this._calculateTimeout=setTimeout(()=>{var a;return(a=this.element)==null?void 0:a.requestVideoFrameCallback(o)},2e3))};this.element.requestVideoFrameCallback(o)}}catch(e){this._log.warn("init stat failed",e)}}};function yo(i,t){return D(this,null,function*(){if(!i.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield i.audioWorklet.addModule(t),se.info("worklet addModule success")}catch(e){throw se.info(`worklet addModule catch error. ${e.message}`),e}})}var bc;typeof AudioContext!="undefined"?bc=AudioContext:typeof webkitAudioContext!="undefined"?bc=webkitAudioContext:typeof mozAudioContext!="undefined"&&(bc=mozAudioContext);var fp=1500,Ir,lE=-1,zu=0,Ac=-1,pp=!1,hE=0,mE=-1,pE=-1;fE();function fE(){try{if(Ir)return;Ir=new bc({sampleRate:48e3}),Ir.onstatechange=()=>{se.info(`context state: ${Ir.state}${Ir.state!=="running"?` visibilityState: ${document.visibilityState}`:""}`),ra()},clearTimeout(lE)}catch(i){se.error(`initAudioContext failed: ${i} typeof AudioContextClass: ${typeof bc}`),lE=setTimeout(fE,1e3)}}var ra=()=>{Ir.state==="suspended"?(zu=Xe(),fb(),Yo(),document.addEventListener("click",ra)):Ir.state==="interrupted"?Yo():(zu&&(Se.addNumber({key:507800,value:Xe()-zu,split:[0,500,1e3,1500,2e3,3e3,4e3,5e3,1e4,3e4],max:6e4}),zu=0),gb(),document.removeEventListener("visibilitychange",ra),document.removeEventListener("click",ra))},hp=0,mp=-1;function Yo(){return new Promise((i,t)=>{if(Ir.state==="running")return i();Date.now()-hp<1e3?(clearTimeout(mp),mp=setTimeout(()=>{hp=Date.now(),Ir.resume().then(i,t)},1e3)):(clearTimeout(mp),hp=Date.now(),Ir.resume().then(i,t))}).catch(i=>{se.warn(`context resume failed: ${i}`),document.addEventListener("visibilitychange",ra)})}document.addEventListener("click",ra);function fb(){Ac===-1&&(Ac=setTimeout(()=>{Ir.state==="suspended"&&(pp=!0,ee.emit("155",{isSuspended:!0}))},fp))}function gb(){Ac!==-1&&(clearTimeout(Ac),Ac=-1,pp&&(pp=!1,ee.emit("155",{isSuspended:!1})))}function gE(){if(!Ut||pE!==-1)return;let i=()=>{Xe()-hE<500||(Ir&&Ir.state==="running"&&Ir.currentTime===mE&&(se.warn("context is fake running, auto resume"),Ir.suspend().catch(t=>{se.warn(`context suspend failed: ${t}`)})),mE=Ir.currentTime,hE=Xe())};pE=setInterval(()=>{i()},2e3),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&i()})}var bt=i=>Ir;var rr=class{constructor(t){this.name=t;p(this,"node");p(this,"node2");p(this,"pre",new Set);p(this,"next",new Set);p(this,"context");p(this,"connectedNodes",new Set);p(this,"nextInputChannelMap",new Map);p(this,"_channelCount",1)}get channelCount(){return this._channelCount}set channelCount(t){this._channelCount=t,this.setChannelCount(this.node,t),this.setChannelCount(this.node2,t),this.next.forEach(e=>e.channelCount=t)}setChannelCount(t,e){!t||t instanceof ScriptProcessorNode||(t.channelCountMode="explicit",t.channelCount=e||this.channelCount||1)}setContext(t){this.context=t,this.node&&t.addMixWeight()}removeContext(){var t;this.node&&((t=this.context)==null||t.reduceMixWeight()),delete this.context}replaceNode(t){var e;if(t!==this.node)try{this.node?this._disconnect():(e=this.context)==null||e.addMixWeight(),this.node=t,this.setChannelCount(this.node),this.preNodeReconnect(),this.reconnect()}catch(r){se.error(r)}}setNode(t,e){var r;if(!this.node)try{(r=this.context)==null||r.addMixWeight(),this.node=t,this.setChannelCount(this.node),e&&(this.node2=e,this.setChannelCount(this.node2)),this.preNodeReconnect(),this.reconnect(),Se.addSuccessEvent({key:502701})}catch(o){se.error(o),Se.addFailedEvent({key:502701,error:o})}}deleteNode(){var t;if(this.node)try{this._disconnect(),delete this.node,delete this.node2,(t=this.context)==null||t.reduceMixWeight(),this.preNodeReconnect(),Se.addSuccessEvent({key:502702})}catch(e){se.error(e),Se.addFailedEvent({key:502702,error:e})}}preNodeReconnect(){this.pre.forEach(t=>{t.node?t.reconnect():t.preNodeReconnect()})}connectNext(t){this.next.forEach(e=>{let r=this.nextInputChannelMap.get(e);t._connect(e.node,r)||e.connectNext(t)})}_connect(t,e=0){return!this.node||!t?!1:((this.node2||this.node).connect(t,0,e),this.connectedNodes.add(t),!0)}_disconnect(){this.connectedNodes.forEach(t=>{var e;return(e=this.node2||this.node)==null?void 0:e.disconnect(t)}),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(t,e=0){return this.next.add(t),t.pre.add(this),this.nextInputChannelMap.set(t,e),t}},ju=class extends rr{constructor(e=256){super();this.fftSize=e;p(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(),r=1,o=0,s=0,n=`M${o},${s}`;for(let a=0;a<e.length;a++)s=e[a]/128*100/2,n+=`L${o},${s}`,o+=r;return n}},vc=class{constructor(){p(this,"source",new rr);p(this,"gain",new rr);p(this,"destination",new rr)}get volume(){var t;return((t=this.gain.node)==null?void 0:t.gain.value)||1}setVolume(t){if(t===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(bt().createGain()),this.gain.node.gain.value=t}replaceSource(t){let e=Rc(t);e&&this.source.replaceNode(e)}get track(){var t;return(t=this.stream)==null?void 0:t.getAudioTracks()[0]}get stream(){var t;return(t=this.destination.node)==null?void 0:t.stream}},ia=class extends vc{constructor(e){super();this.context=e;p(this,"aec",new rr("aec"));p(this,"mixNode",new rr("mixNode"));p(this,"silentNode",new rr("silentNode"));p(this,"denoiser",new rr("denoiser"));p(this,"voiceChanger",new rr("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}},qu=class{constructor(){p(this,"audioContext",bt("audio-mixer"));p(this,"destination",this.audioContext.createMediaStreamDestination());p(this,"inputs",new Set);p(this,"mixWeight",0);this.destination.channelCount=1}addMixWeight(t=1){this.mixWeight+=t,this.mixWeight-1===t+1>>1&&this.mixOnChange()}reduceMixWeight(t=1){this.addMixWeight(-t)}close(){this.inputs.forEach(t=>t.remove())}get mixTrack(){return this.destination.stream.getAudioTracks()[0]}},_E=new WeakMap;function Rc(i){try{let t=_E.get(i);if(t)return t;let e=bt();if(i instanceof HTMLAudioElement)t=e.createMediaElementSource(i);else if(i instanceof MediaStreamTrack)t=e.createMediaStreamSource(new MediaStream([i]));else return i;return _E.set(i,t),t}catch(t){if(zt&&t instanceof Error&&t.name==="NotSupportedError")se.warn(t);else throw t}}var Yr=class Yr{constructor(t){p(this,"_volume",0);p(this,"_volumeDb",0);p(this,"_log");p(this,"_scriptProcessorNode",null);p(this,"_audioWorkletNode",null);p(this,"_interval",200);p(this,"ready",this.preload());let{log:e}=t;this._log=e,ee.on(ce.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-Yr.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!Yr.workletReady){let t='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);';Yr.workletReady=yo(Yr.audioContext,URL.createObjectURL(new Blob([t],{type:"application/javascript"})))}return Yr.workletReady.then(()=>this.initAudioWorklet()).catch(t=>(this._log.error(`volumeMeter preload error: ${t}`),this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(Yr.audioContext,"volume-meter");let t=!1;this._audioWorkletNode.port.onmessage=e=>{Yr.lastMessageTime=Date.now(),this._volume=e.data.volume||0,this._volumeDb=e.data.volumeDb||0,!t&&e.data.cacheLen&&e.data.outputLen&&(this._log.warn("worklet play success"),t=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(t){this._log.error(`volumeMeter init audio worklet error: ${t}`),It.logFailedEvent({userId:this._log.userId,eventType:ii.LOAD_WORKLET,error:t}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=bt("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=t=>{Yr.lastMessageTime=Date.now();let e=t.inputBuffer.getChannelData(0),r=0;for(let o=0;o<e.length;++o)r+=e[o]*e[o];this._volume=Math.sqrt(r/e.length)||0}}catch(t){this._log.error(`volumeMeter init script processor error: ${t}`)}}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,ee.off(ce.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(t){var r;let{interval:e}=t;this._interval=e,(r=this._audioWorkletNode)==null||r.port.postMessage({name:"setIntervalTime",intervalTime:e})}};p(Yr,"lastMessageTime",0),p(Yr,"audioContext",bt("volume-meter")),p(Yr,"workletReady");var Xu=Yr,Cc=class extends rr{constructor(e){super();p(this,"_volumeMeter");this._volumeMeter=new Xu(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return D(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 r=e.allocationSize({planeIndex:0}),o=new Float32Array(r>>2);e.copyTo(o,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:o},[o.buffer]),e.close()}}},Ju=Xu;var SE=Li(mo(),1);var TE=i=>t=>t.deviceId===i;var wc=class{constructor(t,e){p(this,"kind");p(this,"type");p(this,"devices",[]);this.kind=t,this.type=e}update(t,e){let r=t.filter(o=>o.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);if(this.devices.length===1&&sa(this.devices[0])){this.devices=r;return}e&&(r.forEach(o=>{if(o.deviceId&&!this.devices.find(TE(o.deviceId))){let s=`${this.kind}${this.type}Added`;se.warn(`${s}: ${JSON.stringify(o)}`),e.emit(s,o)}}),this.devices.forEach(o=>{if(o.deviceId&&!r.find(TE(o.deviceId))){let s=`${this.kind}${this.type}Removed`;se.warn(`${s}: ${JSON.stringify(o)}`),e.emit(s,o)}})),this.devices=r}hasDevice(t){return!!this.devices.find(e=>e.deviceId===t)}},gp=class extends SE.EventEmitter{constructor(){super();p(this,"audioInputs",new wc(j.AUDIO,"Input"));p(this,"videoInputs",new wc(j.VIDEO,"Input"));p(this,"audioOutputs",new wc(j.AUDIO,"Output"));this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||Jt.run("interval",()=>{this.update()},{delay:1e4}))}init(){oa().then(e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)})}update(){return D(this,arguments,function*(e=0){let r=yield oa(e);return this.audioInputs.update(r,this),this.videoInputs.update(r,this),this.audioOutputs.update(r,this),this})}hasBlueTooth(){var r;if(((r=bt())==null?void 0:r.outputLatency)*1e3>150)return!0;let e=["bluetooth","air","wireless","bt","tws","buds","headset","headphone"];return this.audioOutputs.devices.some(o=>e.some(s=>o.label.toLowerCase().includes(s)))||this.audioInputs.devices.some(o=>e.some(s=>o.label.toLowerCase().includes(s)))}},$t=xa||Cn?null:new gp;function sa(i){return i.deviceId===i.groupId&&i.groupId===""}function oa(){return D(this,arguments,function*(i=0){if(Eo()||!Uu())return[];let t=yield navigator.mediaDevices.enumerateDevices();if(i!==0){let e={audio:!1,video:!1};if(t.forEach(r=>{sa(r)&&(r.kind===j.AUDIO_INPUT?e.audio=!0:r.kind===j.VIDEO_INPUT&&(e.video=!0))}),i===2&&(e.audio=!1),i===1&&(e.video=!1),e.audio||e.video){let r;try{r=yield navigator.mediaDevices.getUserMedia(e),e.audio&&Yo()}catch(o){se.debug("capture before getDevices failed: ",o)}t=yield navigator.mediaDevices.enumerateDevices(),r==null||r.getTracks().forEach(o=>o.stop())}}return t.map((e,r)=>{let o={kind:e.kind,deviceId:e.deviceId,groupId:e.groupId,label:e.label||`${e.kind}_${r}`};return e.deviceId.length>0&&_p.add(`${e.deviceId}_${e.kind}`),e.getCapabilities&&(o.getCapabilities=()=>e.getCapabilities()),o})})}function Gr(i=!1){return $t.update(i?1:0).then(t=>t.audioInputs.devices)}function zr(i=!1){return $t.update(i?2:0).then(t=>t.videoInputs.devices)}var yE=!1;function IE(){return D(this,null,function*(){try{yE||(yE=!0,se.info(`speakers:${(yield Zo()).map(i=>` ${i.deviceId.slice(0,8)}: ${i.label}`)}`))}catch(i){}})}function Zo(i=!1){return D(this,null,function*(){return(Ut||Zt)&&(i=!1),$t.update(i?1:0).then(t=>t.audioOutputs.devices)})}var _p=new Set;function bE(i){if(i instanceof CanvasCaptureMediaStreamTrack||!(i instanceof MediaStreamTrack))return!1;let t=i.label.toLocaleLowerCase();if(t.includes("camera")||t.includes("webcam"))return!0;let r=`${((i==null?void 0:i.getSettings())||{}).deviceId}_${j.VIDEO_INPUT}`;return!!_p.has(r)}function AE(i){if(i instanceof CanvasCaptureMediaStreamTrack||!(i instanceof MediaStreamTrack))return!1;let t=i.label.toLocaleLowerCase();if(t.includes("mic")||t.includes("\u9EA6\u514B\u98CE"))return!0;let r=`${((i==null?void 0:i.getSettings())||{}).deviceId}_${j.AUDIO_INPUT}`;return!!_p.has(r)}function Ep(i,t){return D(this,null,function*(){let r=(yield Gr()).find(o=>o.deviceId===ws);return!t&&(r==null?void 0:r.groupId)===i||(r==null?void 0:r.groupId)===i&&r.label===t})}function vE(s){return D(this,arguments,function*({newDeviceId:i,oldDeviceId:t,oldGroupId:e,oldLabel:r,kind:o}){return i!==t?!1:o===j.AUDIO&&i===ws?yield Ep(e,r):!0})}var Qu,Tp=class extends vc{constructor(e){super();this.log=e;p(this,"volumeMeter");p(this,"volumeMeterAfter3A");p(this,"volumeDestination");p(this,"analyser",new ju);this.volumeMeter=new Cc({log:this.log}),this.volumeMeterAfter3A=new Cc({log:this.log}),this.volumeDestination=new rr,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},na=class i extends Ci{constructor(e){super(e,j.AUDIO);p(this,"_outputDeviceId");p(this,"_volume",1);p(this,"_destination",bt("player").createMediaStreamDestination());p(this,"pipeline");p(this,"volumeMeterMode","worklet");p(this,"enableVolumeControlInIOS");this.enableVolumeControlInIOS=e.enableVolumeControlInIOS,this.mode=0,e.url&&(this.url=e.url),this.pipeline=new Tp(this._log)}get duration(){var e;return Math.floor((((e=this.element)==null?void 0:e.duration)||0)*1e3)}get currentTime(){var e;return Math.floor((((e=this.element)==null?void 0:e.currentTime)||0)*1e3)}set currentTime(e){this.element&&(this.element.currentTime=e/1e3)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(e){if((ai==="15.2"||ai==="15.3"||ai==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}let o=Qu||new Audio;o.setAttribute("autoplay","autoplay"),o.srcObject=this.getMediaStream(),o.muted=this.muted,this.url&&(o.crossOrigin="anonymous",o.src=this.url),this.element=o,ft(e)&&(this.element.volume=Math.min(Math.max(e,0),1)),o===Qu&&(Qu=void 0),this.options.enableTimeupdateEvent&&(this.element.ontimeupdate=()=>this.emit(St.TIME_UPDATE,this.currentTime)),this.bindElementEvents()}play(e){return D(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(bt("player").createAnalyser()),IE(),Er(i.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 D(this,null,function*(){var r,o;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield(o=(r=this.element).setSinkId)==null?void 0:o.call(r,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()}},Yu=class extends na{setTrack(t){this.track!==t&&(this.unbindTrackEvents(),this.track=t,this.emit(St.MEDIA_TRACK_CHANGED,t),t&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([t]))))}},Zu=class extends na{constructor(e){super(e);p(this,"_sourceElement");p(this,"_output",new rr);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(bt("player").destination)}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var r,o,s;((o=(r=this.element)==null?void 0:r.error)==null?void 0:o.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(St.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&&!Ut)this.element?(this._log.info(`set element volume: ${e}`),this.element.volume=e):this._log.info("set element volume: no element");else{if(Ut)if(this.enableVolumeControlInIOS)gE();else return;if(zt&&!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),tr(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play())}}stop(e=0){this.pipeline.destroy();let r=this._sourceElement||this.element;r&&ni&&(Qu=r),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}};var Xs=class extends Ve{constructor({userId:e,sdkAppId:r,mediaType:o,room:s,PlayerClass:n=o===1?Zu:Sr}){var a;super();p(this,"id",oc());p(this,"userId","");p(this,"isRemote");p(this,"mediaType");p(this,"room");p(this,"user");p(this,"_log");p(this,"_inputTrack");p(this,"_outputTrack");p(this,"isPlayCalled");p(this,"container",null);p(this,"player");p(this,"subVideoPlayerMap");p(this,"muted",!1);p(this,"abortCtrl");p(this,"objectFit","cover");p(this,"mirror");p(this,"rotation");p(this,"isScreen",!1);p(this,"manager");p(this,"trackSettings");p(this,"isFirstVideoFrameEmitted",!1);this.userId=e||"",this.mediaType=o,this._log=se.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 wi?void 0:this.userId,sdkAppId:r,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof wi}),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(St.PLAYER_STATE_CHANGED,c=>{if(ee.emit(ce.PLAYER_STATE_CHANGED,be({track:this},c)),this.emit("player-state-changed",c),c.state==="PLAYING"&&this.room){let d=!0;for(let{remoteAudioTrack:m,remoteVideoTrack:l,remoteAuxiliaryTrack:f}of[...this.room.remotePublishedUserMap.values()])if(m.isAvailable&&!m.player.isPlaying||l.isAvailable&&!l.player.isPlaying||f.isAvailable&&!f.player.isPlaying){d=!1;break}d&&Qo()&&uE()}}),this.kind===j.VIDEO&&(this.player.on(St.LOADED_DATA,()=>{this.emitFirstVideoFrameEvent(St.LOADED_DATA),ee.emit(ce.VIDEO_LOADED_DATA,{track:this})}),this.player.on(St.LOADED_META_DATA,()=>{this.emitFirstVideoFrameEvent(St.LOADED_META_DATA)}),this.player.on(St.MEDIA_TRACK_CHANGED,c=>{var d;(d=this.subVideoPlayerMap)==null||d.forEach(m=>m.setTrack(c))}),this.player.on(St.RESIZE,c=>{this.emitFirstVideoFrameEvent(St.RESIZE),this.emit("video-size-changed",be({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(St.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||se}get kind(){return this.mediaType===1?j.AUDIO:j.VIDEO}get isAudio(){return this.kind===j.AUDIO}get strMediaType(){return this.mediaType===4?j.VIDEO:this.mediaType===2?j.SCREEN:j.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,r){return D(this,null,function*(){let o=Gt(e)?e[0]:e;if(this.isPlayCalled){this.log.info(`play update options: ${JSON.stringify(r)}`),r&&!z(r.muted)&&this.setPlayerMute(r.muted),r&&!z(r.objectFit)&&(this.objectFit=r.objectFit),this.player instanceof Sr&&(this.player.setObjectFit(this.objectFit),this.container!==o&&o&&(this.container=o,this.player.setContainer(o)),Gt(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),r)));return}if(r&&!z(r.muted)?this.setPlayerMute(r.muted):(!this.isRemote||this.kind===j.VIDEO)&&this.setPlayerMute(!0),r&&!z(r.objectFit)&&(this.objectFit=r.objectFit),this.player instanceof Sr&&(this.player.setObjectFit(this.objectFit),r&&!z(r.poster)&&this.player.setPoster(r.poster)),this.isPlayCalled=!0,o&&(this.container=o,this.player instanceof Sr&&this.player.setContainer(o)),ee.emit(ce.PLAY_TRACK_START,{track:this}),!this._outputTrack){this.log.info("play has not mediaTrack, abort");return}this._log.info(`play with options: ${JSON.stringify(r)}`);try{this.player.setTrack(this.playerMediaTrack),yield this.player.play(r),Gt(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),r))}catch(s){throw this.handleAutoPlayFailed(s),s}})}setMirror(e,r){if(this.isScreen||this.kind!==j.VIDEO||z(e)||e===this.mirror)return;this.mirror=e;let o=this.player;r&&(o=r);let s=this.manager;if(Nt(this.mirror)){o.setViewMirror(this.mirror),!this.isRemote&&s&&(s.mirror=!1);return}switch(this.mirror){case"view":{s&&(s.mirror=!1),o.setViewMirror(!0);break}case"publish":{s&&(s.mirror=!0),o.setViewMirror(!0);break}case"both":s&&(s.mirror=!0),o.setViewMirror(!1)}}playSubContainer(e,r){return D(this,null,function*(){if(!this._outputTrack||this.kind===j.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?r&&(z(r.objectFit)||a.setObjectFit(r.objectFit)):this.subVideoPlayerMap.set(n,new Sr({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 o=[...this.subVideoPlayerMap.values()];for(let s of o)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.player&&(this.log.info(`stop ${this.kind} player`),this.player.stop(nm(this)&&!e?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(r=>{r.stop()}),this.container=null)}resume(){return D(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),ee.emit(e?ce.TRACK_MUTED:ce.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){yr(e,e).add(j.MUTE,this.onTrackMuted).add(j.UNMUTE,this.onTrackUnmuted).add(j.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===j.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){tr(e)}setInputMediaStreamTrack(e){var o;let r=this._inputTrack;if(e!==r)return this._inputTrack=e,this.trackSettings=(o=e.getSettings)==null?void 0:o.call(e),e.enabled=!this.muted,r&&this.uninstallTrackEvent(r),this.installTrackEvent(e),this.emit("input-media-track-changed",e||null,r||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var o;let r=this._outputTrack;e!==r&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",(o=e.getSettings)==null?void 0:o.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(r=>this.handleAutoPlayFailed(r)),this.log.info(`playing state updated, play ${this.kind}`);return}}else if(!this.player.isStopped){this.player.stop(nm(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 D(this,null,function*(){var o;this.log.warn("handleAutoPlayFailed",e);let r=()=>{this.resume().then(()=>{document.removeEventListener("click",r,!0)})};if(this.room&&this.room.enableAutoPlayDialog){if((ao||co)&&(yield Ti(100),(o=this.player)!=null&&o.isPlaying))return;ta()}else document.addEventListener("click",r,!0);ee.once(ce.LOCAL_TRACK_CAPTURE_SUCCESS,({track:s})=>{s.kind==="audio"&&Qo()&&!this.player.isPlaying&&this.isRemote&&this.isAvailable&&r()}),this.emit("error",e)})}getVideoFrame(){return this.player instanceof Sr?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(e){var n,a,c;if(this.isFirstVideoFrameEmitted)return;let r=(n=this.mediaTrack)==null?void 0:n.getSettings(),o=(r==null?void 0:r.width)||((a=this.player.element)==null?void 0:a.videoWidth)||0,s=(r==null?void 0:r.height)||((c=this.player.element)==null?void 0:c.videoHeight)||0;e===St.RESIZE&&!o&&!s||e===St.LOADED_META_DATA&&!o&&!s||(e===St.LOADED_DATA&&!o&&!s&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,Jr(this.rotation)&&([o,s]=[s,o]),this.emit("first-video-frame",{width:o,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`)}};Ie([Mt([],Ve.INIT,{sync:!0})],Xs.prototype,"close",1);var _b=Object.prototype.hasOwnProperty,{toString:IO}=Object.prototype;function Eb(i){if(i==null)return!0;if(typeof i=="boolean")return!1;if(typeof i=="number")return i===0;if(typeof i=="string"||typeof i=="function"||Array.isArray(i))return i.length===0;if(i instanceof Error)return i.message==="";if(Nr(i))switch(Object.prototype.toString.call(i)){case"[object File]":case"[object Map]":case"[object Set]":return i.size===0;case"[object Object]":{for(let t in i)if(_b.call(i,t))return!1;return!0}}return!1}var Nc=Eb;var Tb=function(i){return D(this,null,function*(){let t=Sb(i);se.info(`getUserMedia with constraints: ${JSON.stringify(t)}`);let e=[],r=[],o=["label","deviceId","groupId"];if(t.audio&&(e=yield Gr(),se.info(`microphones: ${oi(e.map(s=>qe(be({},s),{groupId:s.groupId.substring(0,8)})),{keysToInclude:o})}`)),t.video&&(r=yield zr(),se.info(`cameras: ${oi(r,{keysToInclude:o})}`),!Nt(t.video)&&t.video.facingMode==="user"&&!t.video.deviceId)){let n=r.filter(a=>!a.label.includes("infrared")).find(a=>a.label.includes("facing front"));n&&(t.video.deviceId=n.deviceId,se.info(`exclude infrared camera: ${JSON.stringify(t)}`))}try{let s=yield navigator.mediaDevices.getUserMedia(t);return Qm&&s.getTracks().forEach(n=>{var c;let a=n.getCapabilities();se.info(`${n.kind} capabilities: ${oi(a,{keysToInclude:Gd})}`),!z(i.echoCancellation)&&((c=a.echoCancellation)==null?void 0:c.indexOf(i.echoCancellation))===-1&&se.warn(`Invalid argument for 'echoCancellation'. Expected one of [${JSON.stringify(a.echoCancellation)}], but received '${i.echoCancellation}'`)}),t.audio&&Yo(),s}catch(s){let{message:n}=s;throw s.name==="NotFoundError"&&(i.video&&r&&r.length===0&&(n=Et({key:_t.CAMERA_NOT_FOUND})),i.audio&&e&&e.length===0&&(n=Et({key:_t.MICROPHONE_NOT_FOUND}))),new Me({code:Te.INITIALIZE_FAILED,name:s.name,message:n,constraint:s.constraint})}})},yb=Ho({retryFunction:Tb,settings:{retries:3,timeout:500},onError:({error:i,retry:t,reject:e,retryFuncArgs:r,retriedCount:o})=>{let s=o+1;i.name==="NotReadableError"||i.name==="OverconstrainedError"||i.name==="AbortError"?(s===1?(r[0].video&&(r[0].maxResolution=!1,(!Zt||r[0].width*r[0].height<=1920*1080)&&r[0].frameRate&&(r[0].frameRate=r[0].frameRate>10?10:5)),r[0].retryWhenExactFailed&&r[0].useExactDeviceId&&(r[0].useExactDeviceId=!1)):s===2?r[0].useDeviceIdOnly=!0:s===3&&!r[0].useExactDeviceId&&(r[0].useTrueAsConstraint=!0),t()):e(i),r[0].microphoneId&&RE(r[0].microphoneId,!1),r[0].cameraId&&RE(r[0].cameraId,!0)},onRetrying:i=>{se.warn(`getUserMedia NotReadableError observed, retrying [${i}/3]`)},onRetryFailed:i=>{It.logFailedEvent({eventType:ii.GET_USER_MEDIA_RETRY,error:i})},onRetrySuccess:i=>{It.logSuccessEvent({eventType:ii.GET_USER_MEDIA_RETRY}),It.uploadEvent({log:`stat-${ii.GET_USER_MEDIA_RETRY}-success-${i}`})}});function RE(i,t){return D(this,null,function*(){let r=(t?yield zr():yield Gr()).find(o=>o.deviceId===i);r&&Rt(r.getCapabilities)&&se.warn(oi(r.getCapabilities(),{keysToInclude:Gd}))})}function Sb(i){return{audio:Ib(i),video:bb(i)}}function Ib(i){if(!i.audio)return!1;if(i.useTrueAsConstraint)return!0;let t={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:i.sampleRate};return!Nc(i.microphoneId)&&(t.deviceId=i.useExactDeviceId?{exact:i.microphoneId}:i.microphoneId,i.useDeviceIdOnly)?t:(ft(i.channelCount)&&(t.channelCount=i.channelCount),(Nt(i.echoCancellation)||i.echoCancellation==="remote-only"||i.echoCancellation==="all")&&(t.echoCancellation=i.echoCancellation),Nt(i.noiseSuppression)&&!i.noiseSuppression&&(t.noiseSuppression=!1),Nt(i.autoGainControl)&&!i.autoGainControl&&(t.autoGainControl=!1),Nc(t)?!0:t)}function bb(i){if(!i.video)return!1;if(i.useTrueAsConstraint)return!0;let{maxResolution:t=!0}=i,e={};return i.cameraId?e.deviceId=i.useExactDeviceId?{exact:i.cameraId}:i.cameraId:i.facingMode&&(e.facingMode=i.facingMode),i.useDeviceIdOnly&&!Nc(e)?e:(i.width&&(e.width={ideal:i.width},t&&!zt&&(e.width.max=i.width)),i.height&&(e.height={ideal:i.height},t&&!zt&&(e.height.max=i.height)),zt&&Ii&&i.width&&i.height&&i.width*i.height<352*288&&(e.width=i.width,e.height=i.height),i.frameRate&&(e.frameRate=i.frameRate),Nc(e)?!0:e)}var CE=yb;function Ko(i){return ut((t,e)=>function(...r){return D(this,null,function*(){let o=yield t.apply(this,r);return yield i.call(this,...r),o})})}function wE(i){return ut((t,e)=>function(...r){return D(this,null,function*(){try{return yield t.apply(this,r)}catch(o){i.call(this,o)}})})}function ut(i){return function(t,e,r){return r.value=i(r.value,e),r}}var NE=(()=>{let i=!1,t=document.visibilityState;return()=>{document.visibilityState!==t&&se.info(`visibility change: ${document.visibilityState}`),!i&&(document.addEventListener("visibilitychange",()=>{se.info(`visibility change: ${document.visibilityState}`),t=document.visibilityState}),i=!0)}})();var Ab=0,Ku=class{constructor(){p(this,"log",se.createLogger({id:`fq${++Ab}`}));p(this,"isRunning",!1);p(this,"queue",[])}get length(){return this.queue.length}get lastQueueItem(){return this.length===0?null:this.queue[this.length-1]}push(t,e=!1){var s,n;let r=be({},t),o=new Promise((a,c)=>{r.resolve=a,r.reject=c});return r.promise=o,e?this.length<=1?this.queue.push(r):(n=(s=this.lastQueueItem)==null?void 0:s.promise)==null||n.then(r.resolve,r.reject):this.queue.push(r),this.log.debug(`push ${this.length}`),this.isRunning||this.callNext(),o}shift(){let t=this.queue.shift();return this.log.debug(`shift ${this.length}`),t}callNext(){if(this.isRunning||this.length===0)return;this.log.debug("callNext ",this.length);let{fn:t,args:e,context:r,resolve:o,reject:s}=this.queue[0];this.isRunning=!0,t.apply(r,e).then(o,s).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},DE=new WeakMap,OE=new WeakMap;function el(i=!1){return function(t,e,r){let o=r.value;return r.value=function(...s){let n=DE.get(this)||new Ku;return DE.set(this,n),n.push({fn:o,args:s,context:this},i)},r}}function tl(i){return function(t,e,r){let o=r.value,s=n=>i(...n);return r.value=function(...n){let a=OE.get(this)||new Map,c=a.get(s(n))||new Ku;return a.set(s(n),c),OE.set(this,a),c.push({fn:o,args:n,context:this})},r}}function rl(i,t){return ut((e,r)=>function(...o){let s=i;try{let n=e.apply(this,o),a=Xe();return $o(n)?n.then(c=>(t?Se.addSuccessEvent({key:s,cost:Xe()-a}):Se.addSuccessEvent({key:s}),c)).catch(c=>{throw Se.addFailedEvent({key:s,error:c}),c}):(Se.addSuccessEvent({key:s}),n)}catch(n){throw Se.addFailedEvent({key:s,error:n}),n}})}var af={};eo(af,{Events:()=>Qt,Inspect:()=>ci,LastSink:()=>Js,Sink:()=>Ge,Subscribe:()=>Qs,TimeoutError:()=>Dc,audit:()=>aA,bindCallback:()=>jb,bindNodeCallback:()=>qb,buffer:()=>xb,bufferCount:()=>Mb,bufferTime:()=>RA,call:()=>ME,catchError:()=>rf,combineLatest:()=>kE,concat:()=>Cb,concatMap:()=>EA,concatMapTo:()=>TA,count:()=>Qb,create:()=>mt,debounce:()=>cA,debounceTime:()=>dA,defer:()=>LE,delay:()=>CA,deliver:()=>Je,dispose:()=>il,elementAt:()=>uA,empty:()=>kc,every:()=>fA,exhaustMap:()=>IA,exhaustMapTo:()=>bA,expand:()=>wA,filter:()=>Ur,find:()=>lA,findIndex:()=>hA,first:()=>mA,fromAnimationFrame:()=>Gb,fromArray:()=>Vb,fromEvent:()=>Qe,fromEventPattern:()=>Bb,fromFetch:()=>$b,fromIterable:()=>Fb,fromPromise:()=>VE,fromReadableStream:()=>Wb,fromReader:()=>Hb,groupBy:()=>AA,identity:()=>vb,ignoreElements:()=>eA,iif:()=>Nb,inspect:()=>xE,interval:()=>Rp,last:()=>pA,map:()=>ts,mapTo:()=>_A,max:()=>Yb,merge:()=>Oc,mergeMap:()=>yA,mergeMapTo:()=>SA,min:()=>Zb,never:()=>Xb,nothing:()=>Tt,of:()=>Ub,pairwise:()=>gA,pipe:()=>Ye,race:()=>Ap,range:()=>zb,reduce:()=>Cp,retry:()=>OA,scan:()=>tf,setAsapScheduler:()=>Pb,share:()=>So,shareReplay:()=>wb,skip:()=>rA,skipUntil:()=>iA,skipWhile:()=>cl,startWith:()=>Mc,subject:()=>ir,subscribe:()=>lt,sum:()=>Kb,switchMap:()=>Wi,switchMapTo:()=>Io,take:()=>Ni,takeLast:()=>tA,takeUntil:()=>At,takeWhile:()=>BE,tap:()=>en,throttle:()=>sA,throwError:()=>Jb,timeInterval:()=>vA,timeout:()=>nf,timer:()=>xc,toPromise:()=>NA,toReadableStream:()=>DA,withLatestFrom:()=>Ob,zip:()=>Db});function Tt(...i){}var ME=i=>i(),vb=i=>i;function il(){this.dispose()}var xE=()=>typeof __FASTRX_DEVTOOLS__!="undefined",Rb=1,ci=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(t){let e=new yp(t,this,this.streamId++);return Qt.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},Js=class{constructor(){this.defers=new Set,this.disposed=!1}next(t){}complete(){this.dispose()}error(t){this.dispose()}get bindDispose(){return()=>this.dispose()}dispose(){this.disposed=!0,this.complete=Tt,this.error=Tt,this.next=Tt,this.dispose=Tt,this.subscribe=Tt,this.doDefer()}subscribe(t){return t instanceof ci?t.subscribe(this):t(this),this}get bindSubscribe(){return t=>this.subscribe(t)}doDefer(){this.defers.forEach(ME),this.defers.clear()}defer(t){this.defers.add(t)}removeDefer(t){this.defers.delete(t)}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}},Ge=class extends Js{constructor(t){super(),this.sink=t,t.defer(this.bindDispose)}next(t){this.sink.next(t)}complete(){this.sink.complete()}error(t){this.sink.error(t)}},Qs=class extends Js{constructor(t,e=Tt,r=Tt,o=Tt){if(super(),this._next=e,this._error=r,this._complete=o,this.then=Tt,t instanceof ci){let s={toString:()=>"subscribe",id:0,source:t};this.defer(()=>{Qt.defer(s,0)}),Qt.create(s),Qt.pipe(s),this.sourceId=s.id,this.subscribe(t),Qt.subscribe({id:s.id,end:!0}),e==Tt?this._next=n=>Qt.next(s,0,n):this.next=n=>{Qt.next(s,0,n),e(n)},o==Tt?this._complete=()=>Qt.complete(s,0):this.complete=()=>{this.dispose(),Qt.complete(s,0),o()},r==Tt?this._error=n=>Qt.complete(s,0,n):this.error=n=>{this.dispose(),Qt.complete(s,0,n),r(n)}}else this.subscribe(t)}next(t){this._next(t)}complete(){this.dispose(),this._complete()}error(t){this.dispose(),this._error(t)}};function Ye(i,...t){return t.reduce((e,r)=>r(e),i)}function mt(i,t,e){if(xE()){let r=Object.defineProperties(Object.setPrototypeOf(i,ci.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:t,writable:!0,configurable:!0},args:{value:e,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});Qt.create(r);for(let o=0;o<e.length;o++){let s=e[o];typeof s=="function"&&s instanceof ci&&Qt.addSource(r,s)}return r}return i}function Je(i,t){return function(...e){return r=>{if(r instanceof ci){let o=mt(s=>{let n=new i(s,...e);n.sourceId=o.id,n.subscribe(r)},t,arguments);return o.source=r,Qt.pipe(o),o}else return o=>r(new i(o,...e))}}}function es(i,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:i,payload:t}})}var yp=class extends Ge{constructor(t,e,r){super(t),this.source=e,this.id=r,this.sourceId=t.sourceId,this.defer(()=>{Qt.defer(this.source,this.id)})}next(t){Qt.next(this.source,this.id,t),this.sink.next(t)}complete(){Qt.complete(this.source,this.id),this.sink.complete()}error(t){Qt.complete(this.source,this.id,t),this.sink.error(t)}},Qt={addSource(i,t){es("addSource",{id:i.id,name:i.toString(),source:{id:t.id,name:t.toString()}})},next(i,t,e){es("next",{id:i.id,streamId:t,data:e&&e.toString()})},subscribe({id:i,end:t},e){es("subscribe",{id:i,end:t,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(i,t,e){es("complete",{id:i.id,streamId:t,err:e?e.toString():null})},defer(i,t){es("defer",{id:i.id,streamId:t})},pipe(i){es("pipe",{name:i.toString(),id:i.id,source:{id:i.source.id,name:i.source.toString()}})},update(i){es("update",{id:i.id,name:i.toString()})},create(i){i.id||(i.id=Rb++),es("create",{name:i.toString(),id:i.id})}},Dc=class extends Error{constructor(t){super(`timeout after ${t}ms`),this.timeout=t}};var ol=class extends Js{constructor(t){super(),this.source=t,this.sinks=new Set}add(t){t.defer(()=>this.remove(t)),this.sinks.add(t).size===1&&(this.reset(),this.subscribe(this.source))}remove(t){this.sinks.delete(t),this.sinks.size===0&&this.dispose()}next(t){this.sinks.forEach(e=>e.next(t))}complete(){this.sinks.forEach(t=>t.complete()),this.sinks.clear()}error(t){this.sinks.forEach(e=>e.error(t)),this.sinks.clear()}};function So(){return i=>{let t=new ol(i);if(i instanceof ci){let e=mt(r=>{t.add(r)},"share",arguments);return t.sourceId=e.id,e.source=i,Qt.pipe(e),e}return mt(t.add.bind(t),"share",arguments)}}function Oc(...i){return mt(t=>{let e=new Ge(t),r=i.length;e.complete=()=>{--r===0&&t.complete()},i.forEach(e.bindSubscribe)},"merge",arguments)}function Ap(...i){return mt(t=>{let e=new Map;i.forEach(r=>{let o=new Ge(t);e.set(r,o),o.complete=()=>{e.delete(r),e.size===0?t.complete():o.dispose()},o.next=s=>{e.delete(r),e.forEach(n=>n.dispose()),o.resetNext(),o.resetComplete(),o.next(s)}}),i.forEach(r=>e.get(r).subscribe(r))},"race",arguments)}function Cb(...i){return mt(t=>{let e=0,r=i.length,o=new Ge(t);o.complete=()=>{e<r&&!o.disposed?(o.doDefer(),o.subscribe(i[e++])):t.complete()},o.complete()},"concat",arguments)}function wb(i){return t=>{let e=new ol(t),r=[];return e.next=function(o){r.push(o),r.length>i&&r.shift(),this.sinks.forEach(s=>s.next(o))},mt(o=>{o.defer(()=>e.remove(o)),r.forEach(s=>o.next(s)),e.add(o)},"shareReplay",arguments)}}function Nb(i,t,e){return mt(r=>i()?t(r):e(r),"iif",arguments)}function kE(...i){return mt(t=>{let e=i.length,r=e,o=e,s=new Array(e),n=()=>{--o===0&&t.complete()},a=(c,d)=>{let m=new Ge(t);m.next=l=>{r--,m.next=f=>{s[d]=f,r===0&&t.next(s)},m.next(l)},m.complete=n,m.subscribe(c)};i.forEach(a)},"combineLatest",arguments)}function Db(...i){return mt(t=>{let e=i.length,r=e,o=new Array(e),s=()=>{--r===0&&t.complete()},n=(a,c)=>{let d=new Ge(t),m=[];o[c]=m,d.next=l=>{m.push(l),o.every(f=>f.length)&&t.next(o.map(f=>f.shift()))},d.complete=s,d.subscribe(a)};i.forEach(n)},"zip",arguments)}function Mc(...i){return t=>mt((e,r=0,o=i.length)=>{for(;r<o&&!e.disposed;)e.next(i[r++]);e.disposed||e.subscribe(t)},"startWith",arguments)}var Sp=class extends Ge{constructor(t,...e){super(t);let r=new Ge(this.sink);r.next=o=>this.buffer=o,r.complete=Tt,r.subscribe(kE(...e))}next(t){this.buffer&&this.sink.next([t,...this.buffer])}},Ob=Je(Sp,"withLatestFrom"),Ip=class extends Ge{constructor(t,e,r){super(t),this.bufferSize=e,this.startBufferEvery=r,this.buffer=[],this.count=0,this.startBufferEvery&&(this.buffers=[[]])}next(t){this.startBufferEvery?(this.count++===this.startBufferEvery&&(this.buffers.push([]),this.count=1),this.buffers.forEach(e=>{e.push(t)}),this.buffers[0].length===this.bufferSize&&this.sink.next(this.buffers.shift())):(this.buffer.push(t),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(t=>this.sink.next(t)),super.complete()}},Mb=Je(Ip,"bufferCount"),bp=class extends Ge{constructor(t,e){super(t),this.buffer=[];let r=new Ge(t);r.next=o=>{t.next(this.buffer),this.buffer=[]},r.complete=Tt,r.subscribe(e)}next(t){this.buffer.push(t)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},xb=Je(bp,"buffer");var kb=function(i,t,e,r){function o(s){return s instanceof e?s:new e(function(n){n(s)})}return new(e||(e=Promise))(function(s,n){function a(m){try{d(r.next(m))}catch(l){n(l)}}function c(m){try{d(r.throw(m))}catch(l){n(l)}}function d(m){m.done?s(m.value):o(m.value).then(a,c)}d((r=r.apply(i,t||[])).next())})};function ir(i){let t=arguments,e=So()(mt(r=>{e.next=o=>r.next(o),e.complete=()=>r.complete(),e.error=o=>r.error(o),i&&r.subscribe(i)},"subject",t));return e.next=Tt,e.complete=Tt,e.error=Tt,e}function LE(i){return mt(t=>t.subscribe(i()),"defer",arguments)}var aa={promise:i=>{Promise.resolve().then(i)},setImmediate:typeof setImmediate!="undefined"?i=>setImmediate(i):null,setTimeout:i=>setTimeout(i,0)},Lb=()=>typeof Promise!="undefined"?aa.promise:aa.setImmediate?aa.setImmediate:aa.setTimeout,vp=Lb(),PE=i=>t=>{vp(()=>i(t))},Pb=i=>{typeof i=="function"?vp=i:aa[i]&&(vp=aa[i])};var UE=i=>PE(t=>{for(let e=0;!t.disposed&&e<i.length;e++)t.next(i[e]);t.complete()});function Ub(...i){return mt(UE(i),"of",arguments)}function Vb(i){return mt(UE(i),"fromArray",arguments)}function Rp(i){return mt(t=>{let e=0,r=setInterval(()=>t.next(e++),i);return t.defer(()=>{clearInterval(r)}),"interval"},"interval",arguments)}function xc(i,t){return mt(e=>{let r=0,o=setTimeout(()=>{if(e.removeDefer(s),e.next(r++),t){let n=setInterval(()=>e.next(r++),t);e.defer(()=>{clearInterval(n)})}else e.complete()},i),s=()=>clearTimeout(o);e.defer(s)},"timer",arguments)}function sl(i,t){return e=>{let r=o=>e.next(o);e.defer(()=>t(r)),i(r)}}function Bb(i,t){return mt(sl(i,t),"fromEventPattern",arguments)}function Qe(i,t){if("on"in i&&"off"in i)return mt(sl(e=>i.on(t,e),e=>i.off(t,e)),"fromEvent",arguments);if("addListener"in i&&"removeListener"in i)return mt(sl(e=>i.addListener(t,e),e=>i.removeListener(t,e)),"fromEvent",arguments);if("addEventListener"in i)return mt(sl(e=>i.addEventListener(t,e),e=>i.removeEventListener(t,e)),"fromEvent",arguments);throw"target is not a EventDispachter"}function VE(i){return mt(t=>{i.then(t.next.bind(t),t.error.bind(t))},"fromPromise",arguments)}function $b(i,t){return mt(LE(()=>VE(fetch(i,t))),"fromFetch",arguments)}function Fb(i){return mt(PE(t=>{try{for(let e of i){if(t.disposed)return;t.next(e)}t.complete()}catch(e){t.error(e)}}),"fromIterable",arguments)}function Hb(i){let t=e=>kb(this,void 0,void 0,function*(){if(e.disposed)return;let{done:r,value:o}=yield i.read();if(r){e.complete();return}else e.next(o),t(e)});return mt(e=>{t(e)},"fromReader",arguments)}function Wb(i){return mt(t=>{let e=new AbortController,r=e.signal;t.defer(()=>e.abort("cancelled")),i.pipeTo(new WritableStream({write(o){t.next(o)},close(){t.complete()},abort(o){t.error(o)}}),{signal:r}).then(()=>t.complete(),o=>t.error(o))},"fromReadableStream",arguments)}function Gb(){return mt(i=>{let t=requestAnimationFrame(function e(r){i.disposed||(i.next(r),t=requestAnimationFrame(e))});i.defer(()=>cancelAnimationFrame(t))},"fromAnimationFrame",arguments)}function zb(i,t){return mt((e,r=i,o=t+i)=>{for(;r<o&&!e.disposed;)e.next(r++);return e.complete(),"range"},"range",arguments)}function jb(i,t,...e){return mt(r=>{let o=e.concat(s=>(r.next(s),r.complete()));i.apply(t,o)},"bindCallback",arguments)}function qb(i,t,...e){return mt(r=>{let o=e.concat((s,n)=>s?r.error(s):(r.next(n),r.complete()));i.apply(t,o)},"bindNodeCallback",arguments)}function Xb(){return mt(()=>{},"never",arguments)}function Jb(i){return mt(t=>t.error(i),"throwError",arguments)}function kc(){return mt(i=>i.complete(),"empty",arguments)}var Ys=class extends Ge{constructor(t,e,r){super(t),this.f=e;let o=()=>{this.sink.next(this.acc),this.sink.complete()};typeof r=="undefined"?this.next=s=>{this.acc=s,this.complete=o,this.resetNext()}:(this.acc=r,this.complete=o)}next(t){this.acc=this.f(this.acc,t)}},Cp=Je(Ys,"reduce"),Qb=i=>Je(Ys,"count")((t,e)=>i(e)?t+1:t,0),Yb=()=>Je(Ys,"max")(Math.max),Zb=()=>Je(Ys,"min")(Math.min),Kb=()=>Je(Ys,"sum")((i,t)=>i+t,0);var wp=class extends Ge{constructor(t,e,r){super(t),this.filter=e,this.thisArg=r}next(t){this.filter.call(this.thisArg,t)&&this.sink.next(t)}},Ur=Je(wp,"filter"),Np=class extends Ge{next(t){}},eA=Je(Np,"ignoreElements"),Dp=class extends Ge{constructor(t,e){super(t),this.count=e}next(t){this.sink.next(t),--this.count===0&&(this.doDefer(),this.complete())}},Ni=Je(Dp,"take"),Op=class extends Ge{constructor(t,e){super(t);let r=new Ge(t);r.next=()=>{r.doDefer(),t.complete()},r.complete=il,r.subscribe(e)}},At=Je(Op,"takeUntil"),Mp=class extends Ge{constructor(t,e){super(t),this.f=e}next(t){this.f(t)?this.sink.next(t):(this.doDefer(),this.complete())}},BE=Je(Mp,"takeWhile"),tA=i=>Cp((t,e)=>(t.push(e),t.length>i&&t.shift(),t),[]),xp=class extends Ge{constructor(t,e){super(t),this.count=e}next(t){--this.count===0&&(this.next=super.next)}},rA=Je(xp,"skip"),kp=class extends Ge{constructor(t,e){super(t),t.next=Tt;let r=new Ge(t);r.next=()=>{r.doDefer(),t.resetNext()},r.complete=il,r.subscribe(e)}},iA=Je(kp,"skipUntil"),Lp=class extends Ge{constructor(t,e){super(t),this.f=e}next(t){this.f(t)||(this.next=super.next,this.next(t))}},cl=Je(Lp,"skipWhile"),oA={leading:!0,trailing:!1},Pp=class extends Ge{constructor(t,e,r){super(t),this.durationSelector=e,this.trailing=r}cacheValue(t){this.last=t,this.disposed&&this.throttle(t)}send(t){this.sink.next(t),this.throttle(t)}throttle(t){this.reset(),this.subscribe(this.durationSelector(t))}next(){this.complete()}complete(){this.dispose(),this.trailing&&this.send(this.last)}},nl=class extends Ge{constructor(t,e,r=oA){super(t),this.durationSelector=e,this.config=r,this._throttle=new Pp(this.sink,this.durationSelector,this.config.trailing),this._throttle.dispose()}next(t){this._throttle.disposed&&this.config.leading?this._throttle.send(t):this._throttle.cacheValue(t)}complete(){this._throttle.throttle=Tt,this._throttle.complete(),super.complete()}},sA=Je(nl,"throttle"),nA={leading:!1,trailing:!0},aA=i=>Je(nl,"audit")(i,nA),Up=class extends Ge{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},al=class extends Ge{constructor(t,e){super(t),this.durationSelector=e,this._debounce=new Up(this.sink),this._debounce.dispose()}next(t){this._debounce.dispose(),this._debounce.reset(),this._debounce.last=t,this._debounce.subscribe(this.durationSelector(t))}complete(){this._debounce.complete(),super.complete()}},cA=Je(al,"debounce"),dA=i=>Je(al,"debounceTime")(t=>xc(i)),Vp=class extends Ge{constructor(t,e,r){super(t),this.count=e,this.defaultValue=r}next(t){this.count--===0&&(this.defaultValue=t,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()}},uA=Je(Vp,"elementAt"),lA=i=>t=>Ni(1)(cl(e=>!i(e))(t)),Bp=class extends Ge{constructor(t,e){super(t),this.f=e,this.i=0}next(t){this.f(t)?(this.sink.next(this.i++),this.doDefer(),this.complete()):++this.i}},hA=Je(Bp,"findIndex"),$p=class extends Ge{constructor(t,e,r){super(t),this.f=e,this.defaultValue=r,this.index=0}next(t){(!this.f||this.f(t,this.index++))&&(this.defaultValue=t,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()}},mA=Je($p,"first"),Fp=class extends Ge{constructor(t,e,r){super(t),this.f=e,this.defaultValue=r,this.index=0}next(t){(!this.f||this.f(t,this.index++))&&(this.defaultValue=t)}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},pA=Je(Fp,"last"),Hp=class extends Ge{constructor(t,e){super(t),this.predicate=e,this.index=0}next(t){this.predicate(t,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()}},fA=Je(Hp,"every");var Wp=class extends Ge{constructor(t,e,r){super(t),this.f=e,typeof r=="undefined"?this.next=o=>{this.acc=o,this.resetNext(),this.sink.next(this.acc)}:this.acc=r}next(t){this.sink.next(this.acc=this.f(this.acc,t))}},tf=Je(Wp,"scan"),Gp=class extends Ge{constructor(){super(...arguments),this.hasLast=!1}next(t){this.hasLast?this.sink.next([this.last,t]):this.hasLast=!0,this.last=t}},gA=Je(Gp,"pairwise"),dl=class extends Ge{constructor(t,e,r){super(t),this.mapper=e,this.thisArg=r}next(t){super.next(this.mapper.call(this.thisArg,t))}},ts=Je(dl,"map"),_A=i=>Je(dl,"mapTo")(t=>i),Zs=class extends Ge{constructor(t,e,r){super(t),this.data=e,this.context=r}next(t){let e=this.context.combineResults;e?this.sink.next(e(this.data,t)):this.sink.next(t)}tryComplete(){this.context.resetComplete(),this.dispose()}},Ks=class i extends Ge{constructor(t,e,r){super(t),this.makeSource=e,this.combineResults=r,this.index=0}subInner(t,e){let r=this.currentSink=new e(this.sink,t,this);this.complete===i.prototype.complete&&(this.complete=this.tryComplete),r.complete=r.tryComplete,r.subscribe(this.makeSource(t,this.index++))}complete(){this.sink.complete()}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},ul=class extends Zs{},ll=class extends Ks{next(t){this.subInner(t,ul),this.next=e=>{this.currentSink.dispose(),this.subInner(e,ul)}}},Wi=Je(ll,"switchMap");function fl(i){return(t,e)=>i(()=>t,e)}var Io=fl(Je(ll,"switchMapTo")),zp=class extends Zs{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},hl=class extends Ks{constructor(){super(...arguments),this.sources=[],this.next2=this.sources.push.bind(this.sources)}next(t){this.next2(t),this.subNext()}subNext(){this.next=this.next2,this.subInner(this.sources.shift(),zp),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},EA=Je(hl,"concatMap"),TA=fl(Je(hl,"concatMapTo")),jp=class extends Zs{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},ml=class extends Ks{constructor(){super(...arguments),this.inners=new Set}next(t){this.subInner(t,jp),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(t=>t.resetComplete()):this.dispose()}},yA=Je(ml,"mergeMap"),SA=fl(Je(ml,"mergeMapTo")),qp=class extends Zs{dispose(){this.context.resetNext(),super.dispose()}},pl=class extends Ks{next(t){this.next=Tt,this.subInner(t,qp)}},IA=Je(pl,"exhaustMap"),bA=fl(Je(pl,"exhaustMapTo")),Xp=class extends Ge{constructor(t,e){super(t),this.f=e,this.groups=new Map}next(t){let e=this.f(t),r=this.groups.get(e);typeof r=="undefined"&&(r=ir(),r.key=e,this.groups.set(e,r),super.next(r)),r.next(t)}complete(){this.groups.forEach(t=>t.complete()),super.complete()}error(t){this.groups.forEach(e=>e.error(t)),super.error(t)}},AA=Je(Xp,"groupBy"),Jp=class extends Ge{constructor(){super(...arguments),this.start=new Date}next(t){this.sink.next({value:t,interval:Number(new Date)-Number(this.start)}),this.start=new Date}},vA=Je(Jp,"timeInterval"),Qp=class extends Ge{constructor(t,e){super(t),this.miniseconds=e,this.buffer=[],this.id=setInterval(()=>{this.sink.next(this.buffer.concat()),this.buffer.length=0},this.miniseconds)}next(t){this.buffer.push(t)}complete(){this.sink.next(this.buffer),super.complete()}dispose(){clearInterval(this.id),super.dispose()}},RA=Je(Qp,"bufferTime"),Yp=class extends Ge{constructor(t,e){super(t),this.buffer=[],this.delayTime=e}dispose(){clearTimeout(this.timeoutId),super.dispose()}delay(t){this.timeoutId=setTimeout(()=>{let e=this.buffer.shift();if(e){let{time:r,data:o}=e;super.next(o),this.buffer.length&&this.delay(Number(this.buffer[0].time)-Number(r))}},t)}next(t){this.buffer.length||this.delay(this.delayTime),this.buffer.push({time:new Date,data:t})}complete(){this.timeoutId=setTimeout(()=>super.complete(),this.delayTime)}},CA=Je(Yp,"delay"),Zp=class extends Ge{constructor(t,e){super(t),this.selector=e}error(t){this.dispose(),this.selector(t)(this.sink)}},rf=Je(Zp,"catchError"),Kp=class extends Zs{tryComplete(){let t=this.context.inners.delete(this);super.dispose(),t&&this.context.checkComplete()}next(t){this.sink.next(t),this.context.expandValue(t)}},ef=class extends Ks{constructor(t,e){super(t,e),this.project=e,this.inners=new Set,this.sourceCompleted=!1}next(t){this.sink.next(t),this.expandValue(t)}expandValue(t){let e=new Kp(this.sink,t,this);this.currentSink=e,this.complete=this.tryComplete,e.complete=e.tryComplete,this.inners.add(e),e.subscribe(this.makeSource(t,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()}},wA=Je(ef,"expand");var NA=()=>i=>new Promise((t,e)=>{let r;new Qs(i,o=>r=o,e,()=>t(r))}),DA=()=>i=>{let t;return new ReadableStream({start(e){t=new Qs(i,e.enqueue.bind(e),e.error.bind(e),e.close.bind(e))},cancel(){t.dispose()}})},lt=(i=Tt,t=Tt,e=Tt)=>r=>new Qs(r,i,t,e),of=class extends Ge{constructor(t,e){super(t),e instanceof Function?this.next=r=>{e(r),t.next(r)}:(e.next&&(this.next=r=>{e.next(r),t.next(r)}),e.complete&&(this.complete=()=>{e.complete(),t.complete()}),e.error&&(this.error=r=>{e.error(r),t.error(r)}))}},en=Je(of,"tap"),sf=class extends Ge{constructor(t,e){super(t),this.timeout=e,this.id=setTimeout(()=>this.error(new Dc(this.timeout)),this.timeout)}next(t){super.next(t),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},nf=Je(sf,"timeout"),OA=(i=1/0)=>t=>{if(t instanceof ci){let e=mt(r=>{let o=i,s=new Ge(r);s.error=n=>{o-- >0?s.subscribe(t):r.error(n)},s.sourceId=e.id,s.subscribe(t)},"retry",[i]);return e.source=t,Qt.pipe(e),e}else return e=>{let r=i,o=new Ge(e);o.error=s=>{r-- >0?t(o):e.error(s)},t(o)}};var ca=(e=>(e[e.AUTO_SWITCH_NEW_DEVICE=0]="AUTO_SWITCH_NEW_DEVICE",e[e.WAIT_CURRENT_DEVICE=1]="WAIT_CURRENT_DEVICE",e))(ca||{}),tn=class tn extends Xs{constructor(e,r){super({mediaType:e,PlayerClass:r});p(this,"isRemote",!1);p(this,"deviceId");p(this,"groupId","");p(this,"label","");p(this,"sourceTrack");p(this,"enableAutoSwitchWhenRecapturing",!0);p(this,"_isRecapturing",!1);p(this,"_lastRecaptureTime",0);p(this,"_onMuteTimeoutId",-1);p(this,"_encodeCheckTimeoutId",-1);p(this,"recaptureMode",0);p(this,"profile");p(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,r){throw new Error("Method not implemented.")}installTrackEvent(e){e.addEventListener(j.MUTE,this.onTrackMuted),e.addEventListener(j.UNMUTE,this.onTrackUnmuted),e.addEventListener(j.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===j.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){e.removeEventListener(j.MUTE,this.onTrackMuted),e.removeEventListener(j.UNMUTE,this.onTrackUnmuted),e.removeEventListener(j.ENDED,this.onTrackEnded)}setStateToReady(){}capture(e,r=!1){return D(this,null,function*(){var s;let o=this.sourceTrack;try{let n=Xe();ee.emit(ce.LOCAL_TRACK_CAPTURE_START,{track:this});let a;e.customSource?(a=new MediaStream,a.addTrack(e.customSource)):(r||(s=this.sourceTrack)==null||s.stop(),a=yield CE(e));let c=a.getTracks()[0];return yield this.setInputMediaStreamTrack(c),e.customSource||(this.sourceTrack=c,this.updateDeviceIdInUse(),this.listenDeviceChange()),ee.emit(ce.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:Xe()-n}),a}catch(n){throw ee.emit(ce.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:n}),this.log.error(`getUserMedia error observed ${n}`),n}finally{r&&(o==null||o.stop())}})}setOutputMediaStreamTrack(e){var r;if(super.setOutputMediaStreamTrack(e),this.setStateToReady(),this.isPublishing||this.isPublished)return(r=this.room)==null?void 0:r.replaceTrack(this)}get hasFlag(){var r,o;let e=Ms(((r=this.room)==null?void 0:r.localPublishFlag)||0,((o=this.room)==null?void 0:o.userId)||"");return this.mediaType===4&&e.hasVideo||this.mediaType===1&&e.hasAudio||this.mediaType===2&&e.hasAuxiliary}publish(e,r){return D(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 r,this._checkPublishFlag(e)})}_checkPublishFlag(e){return new Promise((r,o)=>D(this,null,function*(){var d,m,l,f;let s=()=>o(new Me({code:Te.API_CALL_ABORTED,message:"publish aborted"}));if(this.hasFlag||this.muted?r():((this.state===Ve.INIT||this.state==="ready")&&s(),Ye(Qe(e,"local-publish-flag-changed"),Ur(()=>this.hasFlag),At(Oc(Qe(this,Ve.INIT),Qe(this,"ready"))),lt(r,o,s))),(((m=(d=this.room)==null?void 0:d.networkQuality)==null?void 0:m.uplinkNetworkQuality)||0)>3)return r();let a=e.heartbeatCount,c=((f=(l=this.mediaTrack)==null?void 0:l.stats)==null?void 0:f.totalFrames)||0;this._encodeCheckTimeoutId=setTimeout(()=>D(this,null,function*(){var T,E,y,v,M,w,H;if((((E=(T=this.room)==null?void 0:T.networkQuality)==null?void 0:E.uplinkNetworkQuality)||0)>3||e.heartbeatCount-a<3)return r();if((this.isPublished||this.isPublishing)&&this.isMediaTrackActive){if((y=this.mediaTrack)!=null&&y.stats){let $=this.mediaTrack.stats.totalFrames||0;$-c===0&&this.log.warn("capture totalFrames is 0 during encode check, totalFrames",$)}let B=this.kind===j.AUDIO,P=this.stat.bytesSent>0;if(Se[P?"addSuccessEvent":"addFailedEvent"]({key:B?503700:513702}),!B){let $=((M=(v=this.room)==null?void 0:v.videoCodec)==null?void 0:M.toUpperCase())||"H264",de={H264:513704,H265:513705,VP8:513706}[$];de&&Se[P?"addSuccessEvent":"addFailedEvent"]({key:de})}if(!P){if(Se.addEnum({key:B?503701:513703,value:Bs()}),It.uploadEvent({log:`stat-encode-failed-${this.kind}-${Vs()||ho()}`,userId:this.userId}),this.log.warn(B?"encode failed":`${(H=(w=this.room)==null?void 0:w.videoCodec)==null?void 0:H.toUpperCase()} encode failed`),this.retryEncodeFailed&&(this.log.warn("retry encode"),yield this.retryEncodeFailed(this),this.stat.bytesSent>0||this.hasFlag||(yield Ti(5e3),this.stat.bytesSent>0||this.hasFlag)))return r();this.emit("6",this),o(new Me({message:`${this.strMediaType} encode failed`,code:B?Te.AUDIO_ENCODE_FAILED:Te.VIDEO_ENCODE_FAILED}))}}}),1e4)}))}unpublish(){this.room&&this.room.localTracks.delete(this),this.log.info("unpublish"),ee.emit(ce.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return D(this,null,function*(){if(this.sourceTrack&&ea){let{deviceId:e,groupId:r}=this.sourceTrack.getSettings(),{label:o}=this.sourceTrack;(yield vE({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=o,r&&(this.groupId=r),oa().then(n=>{let a=n.find(c=>{let d=c.deviceId===e;return r&&(d=d&&c.groupId===r),d});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===j.AUDIO&&!AE(this.sourceTrack)||this.kind===j.VIDEO&&!bE(this.sourceTrack)||this._isRecapturing||e&&Ii&&Zt)}onTrackMuted(){if(super.onTrackMuted(),NE(),!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<Dn){setTimeout(()=>this.onTrackMuted(),Dn);return}this._onMuteTimeoutId=setTimeout(()=>D(this,null,function*(){var e;if((e=this.sourceTrack)!=null&&e.muted){if((Ut||Bt)&&document.visibilityState!=="visible")return;this.recapture(yield this.getRecoverCaptureDeviceId())}}),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return D(this,null,function*(){if(Er(tn.prototype,this,"onTrackEnded").call(this),!!this.isNeedToRecapture()&&this.recaptureMode===0){if(Date.now()-this._lastRecaptureTime<Dn){setTimeout(()=>this.onTrackEnded(),Dn);return}this.emit("7"),this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e,r=!1){return D(this,null,function*(){var n;if(this._isRecapturing||!this.sourceTrack)return;this.log.warn("recapture trying");let o=this.sourceTrack;r||(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 Gr():yield zr()).find(d=>d.deviceId===e)&&(a=e),s.deviceId=a}return this.capture(s,r).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),ee.emit(ce.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(a=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${a.message}`),this.emit("5",a),ee.emit(ce.LOCAL_TRACK_RECAPTURE,{track:this,error:a})}).finally(()=>{r&&(o==null||o.stop())})})}getRecoverCaptureDeviceId(){return D(this,null,function*(){let e=this instanceof Zr;if(e&&this.facingMode)return this.facingMode;let{deviceId:r}=this;if(r){let o=(Lc.get(r)||0)+1;if(Lc.set(r,o),o>=3&&this.enableAutoSwitchWhenRecapturing){let s=e?(yield zr()).find(n=>!Lc.has(n.deviceId)):(yield Gr()).find(n=>!Lc.has(n.deviceId));s&&(this.log.warn(`${r} capture fail ${o} times, change new ${s.deviceId}`),r=s.deviceId)}}return r})}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()}};Ie([Mt(Ve.INIT,"ready",{ignoreError:!0,sync:!0})],tn.prototype,"setStateToReady",1),Ie([el()],tn.prototype,"capture",1),Ie([Mt("ready","publish",{ignoreError:!0,success(){ee.emit(ce.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 r="error",o=e instanceof Me?e:e.cause instanceof Me?e.cause:e,s=!1;o instanceof Me&&(o.message.includes("timeout")?r="timeout":o.code===Te.API_CALL_ABORTED&&(s=!0,r="api-call")),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:r,error:o}),this.log[s?"info":"error"]("publish failed",o)}}),rl(521714,!1)],tn.prototype,"publish",1),Ie([ut(e=>function(){return D(this,null,function*(){let r=this.state==="publish"?"started":"starting";e.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:r,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)})}),Mt([],"ready",{sync:!0})],tn.prototype,"unpublish",1);var wi=tn,Lc=new Map;ee.on(ce.SWITCH_DEVICE_SUCCESS,i=>{i.track.deviceId&&Lc.delete(i.track.deviceId)});var Gi=class i extends wi{constructor(e){super(1,Yu);p(this,"mediaType",1);p(this,"volume",0);p(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40});p(this,"playerMuted",!0);p(this,"pipeline");p(this,"earMonitorGainNode",new rr);p(this,"_output",new rr);p(this,"codecPipeline",[]);p(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0});p(this,"mixedAudioReferenceMap",new Map);p(this,"isAudioContextLongSuspended",!1);p(this,"after3aSilenceStartTime",0);this.manager=e,this.pipeline=new ia(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),ee.on(ce.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this)}get dbVolume(){return Ju.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){z(e)||(e===0&&!this.after3aSilenceStartTime?this.after3aSilenceStartTime=Xe():e>0&&(this.after3aSilenceStartTime=0))}setInputMediaStreamTrack(e){return D(this,null,function*(){let r=this.trackSettings||{};Se.addEnum({key:501701,value:r.channelCount||0,useUV:!1}),Se.addEnum({key:501702,value:r.sampleRate||0,useUV:!1}),Se.addEnum({key:502700,value:0});let{sampleRate:o,channelCount:s}=r;this._log.info(`local audio track input ${JSON.stringify({sampleRate:o,channelCount:s})}`),this.pipeline.source.channelCount=s||1,this.pipeline.replaceSource(e),yield Er(i.prototype,this,"setInputMediaStreamTrack").call(this,e),this.updatePlayingState(!!e)})}capture(a){return D(this,arguments,function*({deviceId:e,customSource:r,useExactDeviceId:o=!0,retryWhenExactFailed:s},n=!1){let c=yield Er(i.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:o,retryWhenExactFailed:s,customSource:r},n);return Yo(),c})}switchDevice(e){return D(this,null,function*(){if(this.mediaTrack){if(this.deviceId===e&&!this.isUseCustomSource)if(e===ws){if(yield Ep(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}),ee.emit(ce.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(r){throw this.log.error(`switch microphone failed ${r}`),this.deviceId&&this.recapture(this.deviceId),r}}})}listenDeviceChange(){$t&&!$t.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&$t.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return D(this,null,function*(){if(e.deviceId===this.deviceId){let r=this.recaptureMode===1;if(this.log.warn(`RecaptureMode: ${ca[this.recaptureMode]}. Current microphone is lost: ${JSON.stringify(e)}`),this.recaptureMode===0){jt(this.userId,{eventId:2003,param1:6,streamType:1});let o=yield Gr();o[0]?this.recapture(o[0].deviceId):r=!0}r&&$t.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.recaptureMode===1&&e.deviceId!==this.deviceId||($t.off("audioInputAdded",this.handleMicrophoneAdded,this),this.log.warn(`microphone added: ${JSON.stringify(e)}`),this.recapture(e.deviceId))}update3A(s){return D(this,arguments,function*({echoCancellation:e,noiseSuppression:r,autoGainControl:o}){let n=this.sourceTrack||this.mediaTrack;if(!n)return;let a=n.getConstraints(),c=!1;!z(e)&&e!==this.profile.echoCancellation&&(this.profile.echoCancellation=e,a.echoCancellation=e,c=!0),!z(r)&&r!==this.profile.noiseSuppression&&(this.profile.noiseSuppression=r,a.noiseSuppression=r,c=!0),!z(o)&&o!==this.profile.autoGainControl&&(this.profile.autoGainControl=o,a.autoGainControl=o,c=!0),c&&(zt||Zt?yield n.applyConstraints(a).catch(d=>this._log.warn("update3A failed: ",d)):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&&Se.addEnum({key:502700,value:2})}setAudioVolume(e){super.setAudioVolume(0),Ut&&this.player.setMuted(!0),this.earMonitorGainNode.node||(this.earMonitorGainNode.setNode(bt().createGain()),this._output.setNode(bt().destination)),this.earMonitorGainNode.node.gain.value=e}enableTrackANS(e){return this.update3A({noiseSuppression:e})}enableTrackAEC(e){if(this.sourceTrack&&!(Zt||Ut))return this.update3A({echoCancellation:e})}addDenoiser(e){var r;if(Fr<=92&&((r=this.trackSettings)==null?void 0:r.sampleRate)!==48e3){this._log.warn("denoiser only support sampleRate 48000 before chrome 93");return}Se.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.enableTrackANS(!1)}mixAudioReference(e,r){if(this.mixedAudioReferenceMap.has(r))return;this.log.info(`mixAudioReference() => ${r}`);let o=Rc(e);if(!o)return;let s=new rr,n=bt().createGain();n.gain.value=1;let a=new rr;s.pipeTo(a).pipeTo(this.pipeline.mixNode),s.setNode(o),a.setNode(n),this.mixedAudioReferenceMap.set(r,[s,a])}unMixAudioReference(e){let[r,o]=this.mixedAudioReferenceMap.get(e)||[];r&&(this.log.info(`unMixAudioReference() => ${e}`),r.deleteNode(),o==null||o.deleteNode(),this.mixedAudioReferenceMap.delete(e))}setAudioReferenceVolume(e,r){let[o,s]=this.mixedAudioReferenceMap.get(e)||[];s!=null&&s.node&&(s.node.gain.value=r/100,this.log.info(`setAudioReferenceVolume() => ${e} ${s.node.gain.value}`))}addAudioProcessor(e,r,o){this.pipeline.silentNode.setNode(o),this.pipeline.mixNode.setNode(r),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,r])=>{e.deleteNode(),r.deleteNode()}),this.mixedAudioReferenceMap.clear(),this.pipeline.remove(),this.earMonitorGainNode.deleteNode(),this._output.deleteNode(),$t.off("audioInputAdded",this.handleMicrophoneAdded,this),$t.off("audioInputRemoved",this.handleMicrophoneRemoved,this),ee.off(ce.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this),super.close()}recapture(e,r=!1){return D(this,null,function*(){try{yield Er(i.prototype,this,"recapture").call(this,e,r)}catch(o){let s=(yield Gr()).find(n=>n.deviceId!==e);if(s)yield Er(i.prototype,this,"recapture").call(this,s.deviceId);else throw o}})}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduceRight((r,o)=>o?o({frame:r,ntp:to()}):r,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 ${fp/1e3} seconds, change to source audio${ni?"":", non-Safari"}`);let r=this.sourceTrack||this.mediaTrack;r&&this.setOutputMediaStreamTrack(r)}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 r=this.sourceTrack||this.mediaTrack;r&&(e=r)}super.setOutputMediaStreamTrack(e)}};var rn=class{constructor(t,e=!1){this.dataView=t;this.isSEI&&(e?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let t=this.seiPayloadStartIndex,e=this.dataView.byteLength-2,r=[],o=0;for(let n=t;n<=e;n++){let a=this.dataView.getInt8(n);switch(a){case 0:case 1:case 2:case 3:o===2&&(r.push(3),o=0),a==0?o++:o=0,r.push(a);break;default:o=0,r.push(a);break}}r.push(this.dataView.getInt8(this.dataView.byteLength-1));let s=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,t),...r]).buffer);this.dataView=s}removePreventionByte(){let t=this.seiPayloadStartIndex,e=this.dataView.byteLength-1,r=[],o=0;for(let n=t;n<=e;n++)switch(this.dataView.getInt8(n)){case 0:o++,r.push(this.dataView.getInt8(n));break;case 3:o!==2&&r.push(this.dataView.getInt8(n)),o=0;break;default:r.push(this.dataView.getInt8(n)),o=0;break}let s=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,t),...r]).buffer);this.dataView=s}get isSEI(){return this.dataView.getUint8(4)===6}get seiPayloadStartIndex(){let t=6;for(let e=6;e<this.dataView.buffer.byteLength&&(t++,this.dataView.getUint8(e)===255);e++);return t}get seiPayloadType(){return this.isSEI?this.dataView.getUint8(5):null}get seiPayload(){if(!this.isSEI)return null;let t=0,e=6;for(let s=6;s<this.dataView.buffer.byteLength;s++){let n=this.dataView.getUint8(s);if(e++,n===255)t+=255;else{t+=n;break}}let r=new ArrayBuffer(t),o=new DataView(r);for(let s=0;s<r.byteLength;s++,e++)o.setInt8(s,this.dataView.getInt8(e));return o}};var gl=class{constructor(){p(this,"_seiMessageList",[]);p(this,"_smallSeiMessageList",[]);p(this,"_seiPayloadType",243)}encodeSEINalu(t){let e=t.byteLength,r=parseInt(String(e/255),10),o=e%255,s=[];s.push(0,0,0,1,6,this._seiPayloadType);for(let a=0;a<r;a++)s.push(255);s.push(o);let n=new DataView(t);return s.push(...new Uint8Array(n.buffer)),s.push(128),new rn(new DataView(new Uint8Array(s).buffer),!0)}sendSEI(t,e){e!=null&&e.seiPayloadType&&(this._seiPayloadType=e.seiPayloadType),this._seiMessageList.push(t),e!=null&&e.small&&this._smallSeiMessageList.push(t)}isEmpty(){return!this._seiMessageList.length}getNaluCount(t){let e=0,r=0,o=new DataView(t);for(let s=0;s<t.byteLength;s++)switch(o.getUint8(s)){case 0:e++;break;case 1:(e===2||e===3)&&r++,e=0;break;default:e=0;break}return r}encode(t,e){let r=e?this._smallSeiMessageList:this._seiMessageList;if(r.length>0&&t.data.byteLength>0){let s=9-this.getNaluCount(t.data);if(s<=0)return 0;let n=r.splice(0,s).reverse().map(this.encodeSEINalu.bind(this)),a=n.reduce((f,g)=>f+g.dataView.byteLength,0),c=new ArrayBuffer(a+t.data.byteLength),d=new DataView(c),m=new DataView(t.data),l=0;for(let f=0;f<n.length;f++)for(let g=0;g<n[f].dataView.byteLength;g++)d.setInt8(l++,n[f].dataView.getInt8(g));for(let f=0;f<t.data.byteLength;f++)d.setInt8(l++,m.getInt8(f));return t.data=c,n.length}return 0}};var rs=class rs extends wi{constructor(e,r=4){super(r,Sr);p(this,"profile",be({},La));p(this,"avoidCropping",!1);p(this,"_scaleResolutionDownBy");p(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0,framesCaptured:0});p(this,"small");p(this,"isNeedToSetBandwidth");p(this,"muteImage");p(this,"manager");p(this,"_seiCodec",new gl);this.manager=e;let o=()=>{var s;if(this.isAllowed2k4k(this.profile))this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1});else{let n=si(((s=this.room)==null?void 0:s.sdkAppId)||0)?Pd:Ld;this.log.warn(`Resolution is reset to 1080p, need to upgrade ability here ${n}`),this.setProfile(qe(be({},this.profile),{width:1920,height:1080})),this.applyProfile()}};this.on("input-media-track-changed",o),this.on("publish",o),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(!(!ea||!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 D(this,null,function*(){var r,o,s;if(nt(e)){if(this.muteImage===e)return;yield(r=this.manager)==null?void 0:r.deleteWatermark("mute"),yield(o=this.manager)==null?void 0:o.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:e,fillVideo:!0}),this.muteImage=e,Er(rs.prototype,this,"setMute").call(this,!1)}else this.muteImage&&(yield(s=this.manager)==null?void 0:s.deleteWatermark("mute"),this.muteImage=void 0),Er(rs.prototype,this,"setMute").call(this,e)})}capture(a){return D(this,arguments,function*({deviceId:e,facingMode:r,useExactDeviceId:o=!0,customSource:s,retryWhenExactFailed:n=!0}){let c={audio:!1,video:!0,facingMode:r||this.facingMode,cameraId:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:o,retryWhenExactFailed:n,customSource:s};if(c.facingMode==="environment"){let d=yield this.getDeviceIdWhenUsingBackCamera();d&&(c.cameraId=d)}return Er(rs.prototype,this,"capture").call(this,c)})}setProfile(e){var o;let r=this.fallbackProfile(e);if(r.bitrate&&(this.isNeedToSetBandwidth=r.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile))super.setProfile(r);else{let s=si(((o=this.room)==null?void 0:o.sdkAppId)||0)?Pd:Ld;this.log.warn(`Resolution is reset to 1080p, need to upgrade ability here ${s}`),super.setProfile(qe(be({},this.profile),{width:1920,height:1080}))}}applyProfile(){return D(this,null,function*(){var a;if(!this.mediaTrack)return;let{width:e=0,height:r=0}=(this.sourceTrack||this.mediaTrack).getSettings(),o=e*r,s=this.settings,n=s.height!==this.profile.height||s.width!==this.profile.width||s.frameRate!==this.profile.frameRate;if(n&&(Tr===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:d=0}=(this.sourceTrack||this.mediaTrack).getSettings(),m=c*d;if(n&&m&&o&&m===o){this.log.warn("set bandwidth failed: resolution is not changed");return}return this.room.setBandWidth({bandwidth:this.profile.bitrate,type:j.VIDEO,videoType:j.BIG})}})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},r=this.sourceTrack||this.mediaTrack;return ea&&r&&Object.assign(e,r.getSettings()),e}get scaleResolutionDownBy(){return this._scaleResolutionDownBy?this._scaleResolutionDownBy:eu(this.settings,this.profile)}isAllowed2k4k(e){var r;return!this.room||!this.room.scheduleResult||this.isScreen||e.height*e.width<2560*1440?!0:((r=this.room.scheduleResult.trtcAutoConf)==null?void 0:r["2k4k"])===1}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}switchDevice(e){return D(this,null,function*(){try{if(!this.isNeedToSwitchDevice(e)&&!this.isUseCustomSource)return;let r={useExactDeviceId:!0,retryWhenExactFailed:!1};e==="user"||e==="environment"?r.facingMode=e:r.deviceId=e,this.sourceTrack&&this.sourceTrack.stop(),yield this.capture(r),ee.emit(ce.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(r){throw this.log.error(`switch camera failed ${r}`),this.deviceId&&this.recapture(this.deviceId),r}})}getDeviceIdWhenUsingBackCamera(){return D(this,null,function*(){let e;try{if(Ka&&!qn&&Ym){let o=(yield zr(!0)).map(n=>{var a;return qe(be({},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=o[0];o.forEach(n=>{var m,l,f,g;let{capabilities:a}=n,c=(m=a.width)!=null&&m.max&&((l=a.height)!=null&&l.max)?a.width.max*a.height.max:0,d=(f=s.capabilities.width)!=null&&f.max&&((g=s.capabilities.height)!=null&&g.max)?s.capabilities.width.max*s.capabilities.height.max:0;c>d&&(s=n)}),s!=null&&s.capabilities&&(this._log.info("use max resolution back camera",s),e=s.deviceId)}}catch(r){this._log.warn("get max res camera failed",r)}return e})}updateSmallConfig(e){var o,s;this._log.info(`update small stream config: ${JSON.stringify(e)}`);let r=!this.small;this.small=this.fallbackProfile(e,!0),(o=this.manager)==null||o.update(),r&&((s=this.room)==null||s.enableSmall(!0)),this.log.info("update small stream config success")}fallbackProfile(e,r=!1){let o=e.width>e.height,s=be({},e);return e.width*e.height<=160*120&&Bt&&Qr&&(this.log.warn(`${r?"small ":""}resolution is ${e.width}*${e.height}, fallback to 240*180 for android chrome`),s.width=o?240:180,s.height=o?180:240,s.bitrate=Math.max(e.bitrate,150)),e.width*e.height>1280*720&&Em&&(s.width=o?1280:720,s.height=o?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),fm(ai,"14.3")&&gm(ai,"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"))}),!r&&this.avoidCropping&&(Qr||zt)&&!rc()&&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,r;this.small&&(delete this.small,(e=this.manager)==null||e.update(),(r=this.room)==null||r.enableSmall(!1))}listenDeviceChange(){$t&&!$t.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&$t.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return D(this,null,function*(){if(e.deviceId===this.deviceId){let r=this.recaptureMode===1;if(this.log.warn(`RecaptureMode: ${ca[this.recaptureMode]}. Current camera is lost: ${JSON.stringify(e)}`),this.recaptureMode===0){jt(this.userId,{eventId:2003,param1:7,streamType:2});let o=yield zr();o[0]?this.recapture(o[0].deviceId):r=!0}r&&$t.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return D(this,null,function*(){this.recaptureMode===1&&e.deviceId!==this.deviceId||($t.off("videoInputAdded",this.handleCameraAdded,this),this.log.warn(`camera added: ${JSON.stringify(e)}`),this.recapture(e.deviceId))})}encodeFrame(e,r){if(!this.manager)return e;let o=r?8:this.mediaType;return this.manager.encodePipeline.reduceRight((s,n)=>n?n({frame:s,mediaType:o}):s,e)}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}play(e,r){return z(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,r)}close(){$t.off("videoInputAdded",this.handleCameraAdded,this),$t.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return D(this,null,function*(){try{yield Er(rs.prototype,this,"recapture").call(this,e)}catch(r){let o=(yield zr()).find(s=>s.deviceId!==e);if(o)yield Er(rs.prototype,this,"recapture").call(this,o.deviceId);else throw r}})}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||z(e)||e!==this.rotation&&(this.rotation=e,this.manager.rotation=e))}};Ie([Ko(function(e){this.setContentHint(e.contentHint||"motion")})],rs.prototype,"capture",1);var Zr=rs;var uf={};eo(uf,{REPORT_TYPE:()=>$n,buildSSOPackage:()=>so,bytes2ms:()=>Hg,calculateScaleResolutionDownNumber:()=>eu,concatArrayBuffers:()=>e_,convertObjectNumberToInt:()=>Wa,copyProperties:()=>Fg,deepClone:()=>Ns,deepCloneBasic:()=>Xd,deepMerge:()=>Ei,delay:()=>Ti,fibonacci:()=>Ds,formatedTime:()=>Qd,getConstructorName:()=>Ln,getContainerFromElement:()=>Yg,getEnv:()=>Ug,getFirst16Bits:()=>r_,getInternalVersion:()=>Jg,getLast16Bits:()=>t_,getLoggerUrl:()=>oo,getMediaStreamTrackInfo:()=>Kd,getMuteStateFromFlag:()=>Ms,getNetworkType:()=>kn,getNumNetworkType:()=>Jd,getReconnectionTimeout:()=>Gg,getStringByteLength:()=>Zg,getTurnServer:()=>Qg,getUint32Version:()=>Yd,getValueType:()=>Xt,getViewListFromView:()=>Vn,glog:()=>$a,ipv4ToUint32:()=>Un,isArray:()=>Gt,isAudioWorkletSupported:()=>qg,isBoolean:()=>Nt,isConstructor:()=>Os,isEmpty:()=>Pn,isFunction:()=>Rt,isLangChinese:()=>_i,isMediaStreamTrack:()=>zg,isNumber:()=>ft,isObject:()=>Xr,isOverseaSdkAppId:()=>si,isPlainObject:()=>Nr,isPortrait:()=>im,isPromise:()=>$o,isRemoteTrack:()=>jg,isRotate90Or270:()=>Jr,isSetSinkIdSupported:()=>Xg,isString:()=>nt,isUndefined:()=>z,loadImage:()=>Bn,loadVideo:()=>Kg,ms2bytes:()=>Wg,ms2samples:()=>rm,normalizeUrl:()=>xs,performanceNow:()=>Xe,promiseAny:()=>Fa,samples2ms:()=>tm,setNetworkTypeFromWebRTC:()=>$g,stringify:()=>oi,stringifyIncludeValue:()=>Ha,throttlePromise:()=>Zd});var xA=[-1,-1,1,-1,-1,1,1,1],kA=[0,0,1,0,0,1,1,1];var is=class is extends Ve{constructor(e,r){super();this.context=e;p(this,"name");p(this,"input");p(this,"output");p(this,"texture");p(this,"ctx2d",null);p(this,"fbo");p(this,"width",0);p(this,"height",0);p(this,"x",0);p(this,"y",0);p(this,"program");p(this,"vertexShader");p(this,"fragmentShader");p(this,"totalFrames",0);p(this,"dropFrames",0);p(this,"matchInputSize",!0);p(this,"texCoordBuffer");p(this,"positionBuffer");p(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0});p(this,"cost",0);p(this,"_canvas",null);p(this,"_image");p(this,"log");if(this.context.on("disconnect",this.close,this),this.name=r.name,this.log=r.logger,this.matchInputSize=r.matchInputSize!==!1,this.width=r.width||e.width,this.height=r.height||e.height,this._image=r.image,e instanceof mr){e.ctx&&r.create2d&&(typeof OffscreenCanvas=="function"&&Tr!==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 o=e.ctx;this.texCoordBuffer=this.createBuffer(kA),this.positionBuffer=this.createBuffer(xA),r.createTexture!==!1&&(this.texture=o.createTexture(),this.useTexture(),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),o.pixelStorei(o.UNPACK_ALIGNMENT,1)),r.useFbo&&(this.fbo=o.createFramebuffer(),this.useBufferFrame(),this.useTexture(),o.texImage2D(o.TEXTURE_2D,0,o.RGBA,this.width,this.height,0,o.RGBA,o.UNSIGNED_BYTE,null),o.framebufferTexture2D(o.FRAMEBUFFER,o.COLOR_ATTACHMENT0,o.TEXTURE_2D,this.texture,0)),r.useDefaultProgram?this.program=e.defaultProgam:(r.vertexShaderSource||r.fragmentShaderSource)&&(this.vertexShader=r.vertexShaderSource?e.createShader(o.VERTEX_SHADER,r.vertexShaderSource):e.defaultVShader,this.fragmentShader=r.fragmentShaderSource?e.createShader(o.FRAGMENT_SHADER,r.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(o){this.context.destroy(new Me({code:Te.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${o.message||o}`}))}}get image(){return this._image}set image(e){this._image=e}createFramebuffer(e){let r=this.context.ctx,o=r.createFramebuffer();return r.bindFramebuffer(r.FRAMEBUFFER,o),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,e,0),o}connect(e,...r){return e.addInput(this,...r),this.output=e,e}addInput(e,...r){this.input=e,this.matchInputSize&&e.width&&e.height&&this.resize(e.width,e.height)}requestFrame(e){let r=Date.now();if(this.context instanceof cr&&this.render(e)||this.context instanceof mr&&this.render2d(e))this.totalFrames++;else return!1;return this.cost=Date.now()-r,!0}render2d(e){var r;return(r=this.input)!=null&&r.requestFrame(e)?this.draw2d(this.input.image,0,0,this.width,this.height):!1}update(e=0){var r;(r=this.output)==null||r.update(e)}disconnect(...e){var r;(r=this.output)==null||r.removeInput(this,...e),delete this.output}removeInput(e,...r){delete this.input}close(){var e,r;if(this.context.off("disconnect",this.close,this),(e=this.output)==null||e.removeInput(this),delete this.output,(r=this.input)==null||r.disconnect(),this.context instanceof cr){let o=this.context.ctx;o.deleteBuffer(this.texCoordBuffer),o.deleteBuffer(this.positionBuffer),this.fbo&&o.deleteFramebuffer(this.fbo),this.texture&&o.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&o.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&o.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&o.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 r=this.context.ctx;e.forEach((o,s)=>{o&&(r.activeTexture(r.TEXTURE0+s),r.bindTexture(r.TEXTURE_2D,o))})}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}createBuffer(e){let r=this.context.ctx,o=r.createBuffer();return r.bindBuffer(r.ARRAY_BUFFER,o),r.bufferData(r.ARRAY_BUFFER,new Float32Array(e),r.STATIC_DRAW),o}setTexBuffer(e){let r=this.context.ctx;r.bindBuffer(r.ARRAY_BUFFER,this.texCoordBuffer),r.bufferData(r.ARRAY_BUFFER,new Float32Array(e),r.STATIC_DRAW)}setPosBuffer(e){let r=this.context.ctx;r.bindBuffer(r.ARRAY_BUFFER,this.positionBuffer),r.bufferData(r.ARRAY_BUFFER,new Float32Array(e),r.STATIC_DRAW)}changeBufferData(e,r){let o=this.context.ctx;o.bindBuffer(o.ARRAY_BUFFER,e),o.bufferData(o.ARRAY_BUFFER,new Float32Array(r),o.STATIC_DRAW)}setAttributes(...e){let r=this.context.ctx;e.forEach((o,s)=>{r.enableVertexAttribArray(s),r.bindBuffer(r.ARRAY_BUFFER,o),r.vertexAttribPointer(s,2,r.FLOAT,!1,0,0)})}getVertexPoint(e,r){return[e/this.width*2-1,r/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,r){if(!(this.width===e&&this.height===r)){if(this.width=e,this.height=r,this._canvas&&(this._canvas.width=e,this._canvas.height=r),this.texture&&this.fbo){this.useTexture();let o=this.context.ctx;o.texImage2D(o.TEXTURE_2D,0,o.RGBA,e,r,0,o.RGBA,o.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(e,r)}}draw(e,r){this.setAttributes(e||this.positionBuffer,r||this.texCoordBuffer);let o=this.context.ctx;o.drawArrays(o.TRIANGLE_STRIP,0,4)}draw2d(e,r,o,s,n,a,c,d,m){let l=!z(a)&&!z(c)&&!z(d)&&!z(m);return this.ctx2d&&e?(e instanceof ImageData?(l?this.ctx2d.putImageData(e,r,o,a,c,d,m):this.ctx2d.putImageData(e,r,o),this.emit(is.RENDER,this.ctx2d.canvas)):(l?this.ctx2d.drawImage(e,a,c,d,m,r,o,s,n):this.ctx2d.drawImage(e,r,o,s,n),this.emit(is.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 l;let{totalFrames:e,x:r,y:o,width:s,height:n,name:a,cost:c}=this,d=Date.now(),m=(e-this.lastInfo.totalFrames)/((d-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:r,y:o,width:s,height:n,timestamp:d,fps:m,name:a,cost:c},be({parent:(l=this.input)==null?void 0:l.getInfo()},this.lastInfo)}createTexture(e){let r=this.context.ctx,o=r.createTexture();return this.useTextures(o),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),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,r.RGBA,r.UNSIGNED_BYTE,e),o}};p(is,"RENDER","render"),Ie([Mt(Ve.INIT,"connected",{sync:!0})],is.prototype,"connect",1),Ie([Mt("connected",Ve.INIT,{ignoreError:!0,sync:!0})],is.prototype,"disconnect",1),Ie([Mt([],"closed",{sync:!0})],is.prototype,"close",1);var or=is;var FE=Ye(Rp(250),ts(()=>performance.now()),So()),HE=i=>t=>{let e=0,r=performance.now();Ye(FE,ts(o=>(o-r)/i>>0),Ur(o=>o!=e?(e=o,!0):!1))(t)},_l=i=>t=>{let e=performance.now();Ye(FE,cl(r=>r-e<i),Ni(1))(t)};var PA=[0,1,1,1,0,0,1,0],on=class extends or{constructor(e,r){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},r));p(this,"_intervalId",0);p(this,"_sequence",0);p(this,"checkGLError",!1);p(this,"checkVisibilityChange");e instanceof mr?this.ctx2d=e.ctx||null:e.available&&(r!=null&&r.mirrorUpAndDown)&&this.setTexBuffer(PA)}start(e){this.log.info(`${this.name} start render ${e} fps`),Jt.clearTask(this._intervalId),this._intervalId=Jt.run("intervalInWorker",()=>{if(e!==this.context.frameRate&&(Jt.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof cr){let o=this.context.ctx.getError();o&&this.context.destroy(new Me({code:Te.VIDEO_MANAGER_ERROR,extraCode:5,message:`${this.name} req ${this._sequence} render ${this.totalFrames} faild ${o}`}))}},{fps:this.context.frameRate})}render(e){var r;return(r=this.input)!=null&&r.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),this.emit(or.RENDER,this.context._canvas),!0):!1}addInput(e,...r){super.addInput(e,...r),this.start(this.context.frameRate)}update(e=0){this.state!=="closed"&&(this._intervalId&&(Jt.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),Jt.clearTask(this._intervalId)}resize(e,r){super.resize(e,r),this.context.setSize(e,r)}close(){super.close(),Jt.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},da=class extends on{constructor(e,r){super(e,r);p(this,"_videoTrack");p(this,"_muteOb");p(this,"_closedOb",Qe(this,"closed"));p(this,"_subscription");p(this,"_canvasContainer");Number(uo)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e.canvas.captureStream().getVideoTracks(),this._muteOb=Qe(this._videoTrack,"mute"),Ye(Qe(this._videoTrack,"ended"),At(this._closedOb),lt(()=>{this.context.destroy(new Me({code:Te.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){this._subscription=Ye(this._muteOb,At(this._closedOb),Io(_l(5e3)),Ur(()=>{var e;return!!((e=this._videoTrack)!=null&&e.muted)&&!document.hidden}),lt(()=>{this.context.destroy(new Me({code:Te.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,r;super.close(),(e=this._videoTrack)==null||e.stop(),delete this._videoTrack,(r=this._canvasContainer)==null||r.remove()}},El=class extends da{render(t){var r;let e=!!((r=this.input)!=null&&r.requestFrame(t));if(this.context._canvas2d){let o=this.context._canvas2d.getContext("2d");o.clearRect(0,0,this.context._canvas2d.width,this.context._canvas2d.height),o.drawImage(this.context._canvas,0,0,this.context._canvas2d.width,this.context._canvas2d.height)}return e}};var Tl=class extends da{constructor(e,r,o){super(e,{name:"smallDestination",logger:o});this.resolution=r}resize(e,r){let o,s=e*r,n=this.resolution.width*this.resolution.height;this.log.info(`big res: ${e}*${r} small res: ${this.resolution.width}*${this.resolution.height} `),s>n?o=s/n:(this.log.warn(`Small stream resolution is not smaller than big stream, which is invalid. big: ${e} * ${r} small: ${this.resolution.width} * ${this.resolution.height}`),o=s/(160*120)),super.resize(e/Math.sqrt(o),r/Math.sqrt(o))}};var Pc=class extends or{constructor(e,r){super(e,be({name:"imageSource"},r));p(this,"_lastImage");p(this,"_totalFrames",0);p(this,"_autoResize",!1);p(this,"_canvasRendered");p(this,"videoCallbackId",0);p(this,"waitingFirstFrame",!0);p(this,"shouldUpdate",!0);this._autoResize=(r==null?void 0:r.autoResize)!==!1,Tr===16&&(this._canvasRendered=ir(),Ye(this._canvasRendered,Mc(this._image),Wi(o=>o instanceof HTMLCanvasElement?Qe(o,"rendered"):kc()),At(Qe(this,"closed")),lt(()=>{this.update()})))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){if(!this.shouldUpdate)return;let e=this.image;this.videoCallbackId&&e.cancelVideoFrameCallback(this.videoCallbackId),Ri()&&!document.hidden&&(this.videoCallbackId=e.requestVideoFrameCallback((r,o)=>{this.waitingFirstFrame&&this.onFirstFrame(),document.hidden||(this._totalFrames=o.presentedFrames,this.update(1))}))}_render(e,r){var a;let{width:o,height:s}=this,{image:n}=this;if(n instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(),{videoWidth:o,videoHeight:s}=n,!o||!s)return!1;n.width=o,n.height=s}else if(n instanceof HTMLImageElement||n instanceof ImageData||n instanceof ImageBitmap){if({width:o,height:s}=n,n!==this._lastImage)this._lastImage=n;else if(o===this.width&&s===this.height)return!0}else n instanceof HTMLCanvasElement||n instanceof OffscreenCanvas?({width:o,height:s}=n,this._lastImage=n):typeof VideoFrame!="undefined"&&n instanceof VideoFrame&&({displayWidth:o,displayHeight:s}=n,(a=this._lastImage)==null||a.close(),this._lastImage=n);if(!this._autoResize)return!0;if(this.width===o&&this.height===s&&this.totalFrames){if(r){this.useTexture();let c=this.context.ctx;c.texSubImage2D(c.TEXTURE_2D,0,0,0,c.RGBA,c.UNSIGNED_BYTE,n)}}else{if(r){this.useTexture();let c=this.context.ctx;c.texImage2D(c.TEXTURE_2D,0,c.RGBA,c.RGBA,c.UNSIGNED_BYTE,n)}this.resize(o,s)}return!0}get image(){return this._image}set image(e){var r;(r=this._canvasRendered)==null||r.next(e),this._image=e}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},Uc=class extends Pc{constructor(e,r,o){super(e,o);this._player=r;this.name="videoPlayerSource",Ye(Qe(this._player,St.PLAYER_STATE_CHANGED),At(Qe(this,"closed")),Ur(({state:s})=>s==="PLAYING"),lt(()=>{this.tryVideoFrameCallback()}))}get image(){return this._player.element}},di=class extends Uc{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(t,e,r){super(t,new Sr({id:r.name,track:e,muted:!0,container:null,objectFit:"contain",log:r.logger}),r),this.name="videoTrackSource",this._player.play()}replaceTrack(t){this.waitingFirstFrame=!0,this._player.setTrack(t),this._player.play()}close(){super.close(),this._player.stop()}},yl=class extends or{constructor(e,r,o){super(e,qe(be({name:"textSource"},o),{create2d:!0}));p(this,"hasChange",!0);p(this,"content","");this.ctx2d.textBaseline="top",this.content=r.content||"",r.font&&(this.font=r.font),r.color&&(this.color=r.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,r){if(!this.ctx2d)return;let{color:o,font:s}=this;super.resize(e,r),this.color=o,this.font=s}drawMultilineText(e=0,r=0,o=1.2){if(!this.ctx2d)return;let s=this.ctx2d.measureText(this.content);r+=s.fontBoundingBoxAscent||s.actualBoundingBoxAscent||0;let n=this.font.match(/(\d+)px/),c=(n?parseInt(n[1],10):16)*o,d=this.content.split(`
|
|
33
|
-
`);for(let
|
|
33
|
+
`,t.onclick=this.onQuestionClick.bind(this);let r=document.createElement("div");r.className=Su,r.innerText=`${Zt()?"\u8BE6\u60C5 >":"Detail >"}`,r.onclick=this.onCollapseClick.bind(this);let s=i.content.firstChild,n=s.querySelector(`.${Ac}`);return n.appendChild(r),n.appendChild(t),n.appendChild(e),s}addDiaLog(){br()||(Iu=!0,this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${bn}`).onclick=i=>i.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",R.info("show autoplay dialog"),oe.uploadEvent({log:HT}))}deleteDialog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null,Iu=!1)}onConfirm(){R.warn("confirm clicked, try resume stream"),S.emit(A.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDialog()}onCollapseClick(){let i=this._dialogNode.querySelector(`.${Up}`);i.style.visibility=`${this._showDetail?"hidden":"visible"}`,i.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||oe.uploadEvent({log:$T}),this._isCollapseClicked=!0}onQuestionClick(){window.open(Hp,"_blank"),this._isQuestionClicked||oe.uploadEvent({log:WT}),this._isQuestionClicked=!0}},vn=null;function as(){vn||(vn=new Au)}function $p(){vn&&(vn.deleteDialog(),vn=null)}var it=class extends pi{constructor(e){super(e,p.VIDEO);d(this,"stat",{});d(this,"_calculateTimeout",-1);d(this,"viewMirror",!1);d(this,"objectFit");d(this,"container");d(this,"canvas");d(this,"shouldRenderAlpha",!1);d(this,"_preSize",{width:0,height:0});this.mode=e.canvas?1:0,this.container=e.container,this.canvas=e.canvas,T(e.viewMirror)||(this.viewMirror=e.viewMirror),T(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}get isPlaying(){var e;return this._state!=="PLAYING"||this.element&&this.element.paused?!1:((e=this.track)==null?void 0:e.readyState)==="live"&&!this.track.muted}initializeElement(){var t;let e=document.createElement(p.VIDEO);this.track&&this.mode!==2&&(e.srcObject=new MediaStream([this.track])),e.muted=!0,e.setAttribute("id",`video_${this.id}`),e.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),e.setAttribute("autoplay","autoplay"),e.setAttribute("playsinline","playsinline"),this.element=e,_e&&(e.poster="noposter"),(t=this.container)==null||t.appendChild(this.elementToRender),this.bindElementEvents(),this.calculateStat()}get styleAttribute(){let e=`width: 100%; height: 100%; object-fit: ${this.objectFit};${this.shouldRenderAlpha?"":"background-color: black"};`;return this.viewMirror&&(e+="transform: scaleX(-1);"),e}setContainer(e){var t;this.container=e,this.track&&this.elementToRender&&((t=this.container)==null||t.appendChild(this.elementToRender))}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),e&&e.add(p.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(p.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent).add(p.RESIZE,this.handleElementEvent)}handleTrackEvent(e){var t;return e.type===p.MUTE&&((t=this.stat)!=null&&t.fps)&&(this.stat.fps=0),super.handleTrackEvent(e)}handleElementEvent(e){var r,s,n,a,c,l;if(this.mode===2)return;super.handleElementEvent(e);let t=e.type;if(t===p.PAUSE&&(this.container&&!this.container.isConnected&&(this._log.warn(`${this.kind} player has been remove, element ID: ${this.container.id}`),Ke(500).then(()=>{var u;(u=this.container)!=null&&u.isConnected&&(this._pausedRetryCount=$r,this._log.info(`view container ${this.container.id} is in dom, reset pausedRetryCount`))})),this._pausedRetryCount>0&&!br()&&!this._isPausedByUserCall&&(this._log.info(`[${$r-this._pausedRetryCount+1}/${$r}] ${this.kind} player auto resume when paused`),this.doResume(),this._pausedRetryCount--),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){let u=this.element.style.transform;t===p.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=u.replace("scaleX(-1)",""):t===p.LEAVE_PICTURE_IN_PICTURE&&!u.includes("scaleX")&&(this.element.style.transform=`${u} scaleX(-1)`)}t===p.RESIZE&&(this._preSize.height!==((r=this.element)==null?void 0:r.videoHeight)||this._preSize.width!==((s=this.element)==null?void 0:s.videoWidth))&&(this._log.info(`video size changed to ${(n=this.element)==null?void 0:n.videoWidth}x${(a=this.element)==null?void 0:a.videoHeight}`),this._preSize.height=((c=this.element)==null?void 0:c.videoHeight)||0,this._preSize.width=((l=this.element)==null?void 0:l.videoWidth)||0,this.emit(he.RESIZE,{newWidth:this._preSize.width,newHeight:this._preSize.height}))}setCanvas(e,t=1){var r,s,n,a;this.canvas!==e&&((r=this.canvas)==null||r.remove(),e==null||e.setAttribute("style",this.styleAttribute),this.canvas=e,this.mode=e?t:0,this.mode===2&&this.setTrack(e.captureStream().getVideoTracks()[0]),e?((s=this.element)==null||s.remove(),(n=this.container)==null||n.appendChild(e)):this.element&&((a=this.container)==null||a.appendChild(this.element)))}setAttr(e){let t=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},e);t.style=Object.assign({width:"100%",height:"100%"},t.style),super.setAttr(t)}get mirror(){return this.viewMirror}setRect(e,t){this.elementToRender&&(this.elementToRender.style.width=`${e}px`,this.elementToRender.style.height=`${t}px`)}setViewMirror(e){this.elementToRender&&(this.elementToRender.style.transform=e?"scaleX(-1)":""),this.viewMirror=e}setObjectFit(e){this.elementToRender&&(this.elementToRender.style.objectFit=`${e}`),this.objectFit=e}setPoster(e){this.element&&(this.element.poster=e)}stop(e=0){var t;super.stop(e),(t=this.canvas)==null||t.remove()}play(){return this.element?this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender):this.initializeElement(),this.mode===2?Promise.resolve():super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(he.MEDIA_TRACK_CHANGED,e),e!==null&&(this.bindTrackEvents(),this.element&&this.mode!==2&&(this.element.srcObject=new MediaStream([e]),this.element.remove()),this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender)))}getVideoFrame(){if(this.canvas)return this.canvas.toDataURL("image/png");if(!this.element)return"";let e=document.createElement("canvas");return e.width=this.element.videoWidth,e.height=this.element.videoHeight,e.getContext("2d").drawImage(this.element,0,0),e.toDataURL("image/png")}getElement(){return this.element}calculateStat(){try{if(Ki()&&this.element&&this._calculateTimeout<0){let e=0,t=null,r=(s,n)=>{this.stat.width=n.width,this.stat.height=n.height,t&&(this.stat.fps=Math.round((n.presentedFrames-t.presentedFrames)/(s-e)*1e3)),e=s,t=n,this._calculateTimeout=-1,this.element&&(this._calculateTimeout=setTimeout(()=>{var a;return(a=this.element)==null?void 0:a.requestVideoFrameCallback(r)},2e3))};this.element.requestVideoFrameCallback(r)}}catch(e){this._log.warn("init stat failed",e)}}};function tr(o,i){return f(this,null,function*(){if(!o.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield o.audioWorklet.addModule(i),R.info("worklet addModule success")}catch(e){throw R.info(`worklet addModule catch error. ${e.message}`),e}})}var Nn;typeof AudioContext!="undefined"?Nn=AudioContext:typeof webkitAudioContext!="undefined"?Nn=webkitAudioContext:typeof mozAudioContext!="undefined"&&(Nn=mozAudioContext);var vu=1500,rt,Wp=-1,Rc=0,Dn=-1,bu=!1,Gp=0,Jp=-1,qp=-1;jp();function jp(){try{if(rt)return;rt=new Nn({sampleRate:48e3}),rt.onstatechange=()=>{R.info(`context state: ${rt.state}${rt.state!=="running"?` visibilityState: ${document.visibilityState}`:""}`),cs()},clearTimeout(Wp)}catch(o){R.error(`initAudioContext failed: ${o} typeof AudioContextClass: ${typeof Nn}`),Wp=setTimeout(jp,1e3)}}var cs=()=>{rt.state==="suspended"?(Rc=U(),JT(),vr(),document.addEventListener("click",cs)):rt.state==="interrupted"?vr():(Rc&&(v.addNumber({key:507800,value:U()-Rc,split:[0,500,1e3,1500,2e3,3e3,4e3,5e3,1e4,3e4],max:6e4}),Rc=0),qT(),document.removeEventListener("visibilitychange",cs),document.removeEventListener("click",cs))},Ru=0,yu=-1;function vr(){return new Promise((o,i)=>{if(rt.state==="running")return o();Date.now()-Ru<1e3?(clearTimeout(yu),yu=setTimeout(()=>{Ru=Date.now(),rt.resume().then(o,i)},1e3)):(clearTimeout(yu),Ru=Date.now(),rt.resume().then(o,i))}).catch(o=>{R.warn(`context resume failed: ${o}`),document.addEventListener("visibilitychange",cs)})}document.addEventListener("click",cs);function JT(){Dn===-1&&(Dn=setTimeout(()=>{rt.state==="suspended"&&(bu=!0,S.emit("155",{isSuspended:!0}))},vu))}function qT(){Dn!==-1&&(clearTimeout(Dn),Dn=-1,bu&&(bu=!1,S.emit("155",{isSuspended:!1})))}function Xp(){if(!Te||qp!==-1)return;let o=()=>{U()-Gp<500||(rt&&rt.state==="running"&&rt.currentTime===Jp&&(R.warn("context is fake running, auto resume"),rt.suspend().catch(i=>{R.warn(`context suspend failed: ${i}`)})),Jp=rt.currentTime,Gp=U())};qp=setInterval(()=>{o()},2e3),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&o()})}var Se=o=>rt;var xe=class{constructor(i){this.name=i;d(this,"node");d(this,"node2");d(this,"pre",new Set);d(this,"next",new Set);d(this,"context");d(this,"connectedNodes",new Set);d(this,"nextInputChannelMap",new Map);d(this,"_channelCount",1)}get channelCount(){return this._channelCount}set channelCount(i){this._channelCount=i,this.setChannelCount(this.node,i),this.setChannelCount(this.node2,i),this.next.forEach(e=>e.channelCount=i)}setChannelCount(i,e){!i||i instanceof ScriptProcessorNode||(i.channelCountMode="explicit",i.channelCount=e||this.channelCount||1)}setContext(i){this.context=i,this.node&&i.addMixWeight()}removeContext(){var i;this.node&&((i=this.context)==null||i.reduceMixWeight()),delete this.context}replaceNode(i){var e;if(i!==this.node)try{this.node?this._disconnect():(e=this.context)==null||e.addMixWeight(),this.node=i,this.setChannelCount(this.node),this.preNodeReconnect(),this.reconnect()}catch(t){R.error(t)}}setNode(i,e){var t;if(!this.node)try{(t=this.context)==null||t.addMixWeight(),this.node=i,this.setChannelCount(this.node),e&&(this.node2=e,this.setChannelCount(this.node2)),this.preNodeReconnect(),this.reconnect(),v.addSuccessEvent({key:502701})}catch(r){R.error(r),v.addFailedEvent({key:502701,error:r})}}deleteNode(){var i;if(this.node)try{this._disconnect(),delete this.node,delete this.node2,(i=this.context)==null||i.reduceMixWeight(),this.preNodeReconnect(),v.addSuccessEvent({key:502702})}catch(e){R.error(e),v.addFailedEvent({key:502702,error:e})}}preNodeReconnect(){this.pre.forEach(i=>{i.node?i.reconnect():i.preNodeReconnect()})}connectNext(i){this.next.forEach(e=>{let t=this.nextInputChannelMap.get(e);i._connect(e.node,t)||e.connectNext(i)})}_connect(i,e=0){return!this.node||!i?!1:((this.node2||this.node).connect(i,0,e),this.connectedNodes.add(i),!0)}_disconnect(){this.connectedNodes.forEach(i=>{var e;return(e=this.node2||this.node)==null?void 0:e.disconnect(i)}),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(i,e=0){return this.next.add(i),i.pre.add(this),this.nextInputChannelMap.set(i,e),i}},yc=class extends xe{constructor(e=256){super();this.fftSize=e;d(this,"dataArray",new Uint8Array(0))}setNode(e){e.fftSize=this.fftSize,this.dataArray=new Uint8Array(e.frequencyBinCount),super.setNode(e)}getByteTimeDomainData(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),this.dataArray}get level(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),Math.max(...this.dataArray)/128-1}get timeDomainPathData(){let e=this.getByteTimeDomainData(),t=1,r=0,s=0,n=`M${r},${s}`;for(let a=0;a<e.length;a++)s=e[a]/128*100/2,n+=`L${r},${s}`,r+=t;return n}},On=class{constructor(){d(this,"source",new xe);d(this,"gain",new xe);d(this,"destination",new xe)}get volume(){var i;return((i=this.gain.node)==null?void 0:i.gain.value)||1}setVolume(i){if(i===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(Se().createGain()),this.gain.node.gain.value=i}replaceSource(i){let e=Mn(i);e&&this.source.replaceNode(e)}get track(){var i;return(i=this.stream)==null?void 0:i.getAudioTracks()[0]}get stream(){var i;return(i=this.destination.node)==null?void 0:i.stream}},ds=class extends On{constructor(e){super();this.context=e;d(this,"aec",new xe("aec"));d(this,"mixNode",new xe("mixNode"));d(this,"silentNode",new xe("silentNode"));d(this,"denoiser",new xe("denoiser"));d(this,"voiceChanger",new xe("voiceChanger"));this.source.pipeTo(this.aec).pipeTo(this.denoiser).pipeTo(this.voiceChanger).pipeTo(this.gain).pipeTo(this.destination),this.silentNode.pipeTo(this.mixNode).pipeTo(this.aec,1)}get isProcessEnabled(){return this.aec.node||this.denoiser.node||this.voiceChanger.node||this.gain.node}connect(){this.context.inputs.has(this)||(this.destination.setNode(this.context.destination),this.source.setContext(this.context),this.aec.setContext(this.context),this.silentNode.setContext(this.context),this.mixNode.setContext(this.context),this.denoiser.setContext(this.context),this.voiceChanger.setContext(this.context),this.gain.setContext(this.context),this.context.inputs.add(this))}disconnect(){this.context.inputs.has(this)&&(this.destination.deleteNode(),this.source.removeContext(),this.aec.removeContext(),this.silentNode.removeContext(),this.mixNode.removeContext(),this.denoiser.removeContext(),this.voiceChanger.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.aec.deleteNode(),this.silentNode.deleteNode(),this.mixNode.deleteNode(),this.denoiser.deleteNode(),this.voiceChanger.deleteNode(),this.source.deleteNode(),this.disconnect()}setVolume(e){if(e===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(this.context.audioContext.createGain()),this.gain.node.gain.value=e}},bc=class{constructor(){d(this,"audioContext",Se("audio-mixer"));d(this,"destination",this.audioContext.createMediaStreamDestination());d(this,"inputs",new Set);d(this,"mixWeight",0);this.destination.channelCount=1}addMixWeight(i=1){this.mixWeight+=i,this.mixWeight-1===i+1>>1&&this.mixOnChange()}reduceMixWeight(i=1){this.addMixWeight(-i)}close(){this.inputs.forEach(i=>i.remove())}get mixTrack(){return this.destination.stream.getAudioTracks()[0]}},zp=new WeakMap;function Mn(o){try{let i=zp.get(o);if(i)return i;let e=Se();if(o instanceof HTMLAudioElement)i=e.createMediaElementSource(o);else if(o instanceof MediaStreamTrack)i=e.createMediaStreamSource(new MediaStream([o]));else return o;return zp.set(o,i),i}catch(i){if(te&&i instanceof Error&&i.name==="NotSupportedError")R.warn(i);else throw i}}var Mt=class Mt{constructor(i){d(this,"_volume",0);d(this,"_volumeDb",0);d(this,"_log");d(this,"_scriptProcessorNode",null);d(this,"_audioWorkletNode",null);d(this,"_interval",200);d(this,"ready",this.preload());let{log:e}=i;this._log=e,S.on(A.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-Mt.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!Mt.workletReady){let i='class VolumeMeterWorklet extends AudioWorkletProcessor{constructor(){super(),this.volume=0,this.intervalTime=200,this.tick=200,this.isStop=!1,this.cache=[],this.sentFirstInfo1=!1,this.unmute=!1,this.port.onmessage=t=>{var e=t.data;switch(e.name){case"chunk":this.cache.push(...e.data),this.sentFirstInfo1||(this.port.postMessage({cl:e.data.length}),this.sentFirstInfo1=!0);break;case"setIntervalTime":this.intervalTime=e.intervalTime;break;case"unmute":this.unmute=!0;break;case"stop":this.isStop=!0}}}process(t,s){t=t[0],s=s[0];if(t||s){if(this.isStop)return!1;var i=s&&s[0]?s[0].length:0,h=this.cache.length,a=(i<h?(s[0].set(this.cache.slice(0,i)),this.cache=this.cache.slice(i)):this.unmute&&s[0].set(t[0]),(i<h?s:t)[0]);if(a){let e=0;for(let t=0;t<a.length;++t)e=Math.max(Math.abs(a[t]),e);s=a.reduce((t,e)=>t+e*e,0)/a.length;this.volume=e,this.tick-=a.length,this.tick<0&&(this.tick+=this.intervalTime/1e3*sampleRate,this.port.postMessage({volume:this.volume,volumeDb:Math.max(10*Math.log10(s)+100,0)/100,cacheLen:h,outputLen:i}))}}return!0}}registerProcessor("volume-meter",VolumeMeterWorklet);';Mt.workletReady=tr(Mt.audioContext,URL.createObjectURL(new Blob([i],{type:"application/javascript"})))}return Mt.workletReady.then(()=>this.initAudioWorklet()).catch(i=>(this._log.error(`volumeMeter preload error: ${i}`),this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(Mt.audioContext,"volume-meter");let i=!1;this._audioWorkletNode.port.onmessage=e=>{Mt.lastMessageTime=Date.now(),this._volume=e.data.volume||0,this._volumeDb=e.data.volumeDb||0,!i&&e.data.cacheLen&&e.data.outputLen&&(this._log.warn("worklet play success"),i=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(i){this._log.error(`volumeMeter init audio worklet error: ${i}`),oe.logFailedEvent({userId:this._log.userId,eventType:Ze.LOAD_WORKLET,error:i}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=Se("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=i=>{Mt.lastMessageTime=Date.now();let e=i.inputBuffer.getChannelData(0),t=0;for(let r=0;r<e.length;++r)t+=e[r]*e[r];this._volume=Math.sqrt(t/e.length)||0}}catch(i){this._log.error(`volumeMeter init script processor error: ${i}`)}}destroy(){this._scriptProcessorNode&&(this._scriptProcessorNode.onaudioprocess=null),this._audioWorkletNode&&(this._audioWorkletNode.port.postMessage({name:"stop"}),this._audioWorkletNode.port.onmessage=null),this._audioWorkletNode=null,this._scriptProcessorNode=null,S.off(A.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}getVolumeDb(){return Math.floor(this._volumeDb*100)}handleAudioLevelInterval(i){var t;let{interval:e}=i;this._interval=e,(t=this._audioWorkletNode)==null||t.port.postMessage({name:"setIntervalTime",intervalTime:e})}};d(Mt,"lastMessageTime",0),d(Mt,"audioContext",Se("volume-meter")),d(Mt,"workletReady");var vc=Mt,kn=class extends xe{constructor(e){super();d(this,"_volumeMeter");this._volumeMeter=new vc(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return f(this,null,function*(){yield this._volumeMeter.preload(),this.setNode(this._volumeMeter.node)})}getCalculatedVolume(){return this._volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this._volumeMeter.getInternalAudioLevel()}getVolumeDb(){return this._volumeMeter.getVolumeDb()}write(e){if(this.node){let t=e.allocationSize({planeIndex:0}),r=new Float32Array(t>>2);e.copyTo(r,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:r},[r.buffer]),e.close()}}},so=vc;var Kp=Je(at(),1);var Yp=o=>i=>i.deviceId===o;var Pn=class{constructor(i,e){d(this,"kind");d(this,"type");d(this,"devices",[]);this.kind=i,this.type=e}update(i,e){let t=i.filter(r=>r.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);if(this.devices.length===1&&us(this.devices[0])){this.devices=t;return}e&&(t.forEach(r=>{if(r.deviceId&&!this.devices.find(Yp(r.deviceId))){let s=`${this.kind}${this.type}Added`;R.warn(`${s}: ${JSON.stringify(r)}`),e.emit(s,r)}}),this.devices.forEach(r=>{if(r.deviceId&&!t.find(Yp(r.deviceId))){let s=`${this.kind}${this.type}Removed`;R.warn(`${s}: ${JSON.stringify(r)}`),e.emit(s,r)}})),this.devices=t}hasDevice(i){return!!this.devices.find(e=>e.deviceId===i)}},Nu=class extends Kp.EventEmitter{constructor(){super();d(this,"audioInputs",new Pn(p.AUDIO,"Input"));d(this,"videoInputs",new Pn(p.VIDEO,"Input"));d(this,"audioOutputs",new Pn(p.AUDIO,"Output"));this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||re.run("interval",()=>{this.update()},{delay:1e4}))}init(){ls().then(e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)})}update(){return f(this,arguments,function*(e=0){let t=yield ls(e);return this.audioInputs.update(t,this),this.videoInputs.update(t,this),this.audioOutputs.update(t,this),this})}hasBlueTooth(){var t;if(((t=Se())==null?void 0:t.outputLatency)*1e3>150)return!0;let e=["bluetooth","air","wireless","bt","tws","buds","headset","headphone"];return this.audioOutputs.devices.some(r=>e.some(s=>r.label.toLowerCase().includes(s)))||this.audioInputs.devices.some(r=>e.some(s=>r.label.toLowerCase().includes(s)))}},be=xs||Oo?null:new Nu;function us(o){return o.deviceId===o.groupId&&o.groupId===""}function ls(){return f(this,arguments,function*(o=0){if(Zi()||!pc())return[];let i=yield navigator.mediaDevices.enumerateDevices();if(o!==0){let e={audio:!1,video:!1};if(i.forEach(t=>{us(t)&&(t.kind===p.AUDIO_INPUT?e.audio=!0:t.kind===p.VIDEO_INPUT&&(e.video=!0))}),o===2&&(e.audio=!1),o===1&&(e.video=!1),e.audio||e.video){let t;try{t=yield navigator.mediaDevices.getUserMedia(e),e.audio&&vr()}catch(r){R.debug("capture before getDevices failed: ",r)}i=yield navigator.mediaDevices.enumerateDevices(),t==null||t.getTracks().forEach(r=>r.stop())}}return i.map((e,t)=>{let r={kind:e.kind,deviceId:e.deviceId,groupId:e.groupId,label:e.label||`${e.kind}_${t}`};return e.deviceId.length>0&&Du.add(`${e.deviceId}_${e.kind}`),e.getCapabilities&&(r.getCapabilities=()=>e.getCapabilities()),r})})}function It(o=!1){return be.update(o?1:0).then(i=>i.audioInputs.devices)}function At(o=!1){return be.update(o?2:0).then(i=>i.videoInputs.devices)}var Zp=!1;function ef(){return f(this,null,function*(){try{Zp||(Zp=!0,R.info(`speakers:${(yield Nr()).map(o=>` ${o.deviceId.slice(0,8)}: ${o.label}`)}`))}catch(o){}})}function Nr(o=!1){return f(this,null,function*(){return(Te||Pe)&&(o=!1),be.update(o?1:0).then(i=>i.audioOutputs.devices)})}var Du=new Set;function tf(o){if(o instanceof CanvasCaptureMediaStreamTrack||!(o instanceof MediaStreamTrack))return!1;let i=o.label.toLocaleLowerCase();if(i.includes("camera")||i.includes("webcam"))return!0;let t=`${((o==null?void 0:o.getSettings())||{}).deviceId}_${p.VIDEO_INPUT}`;return!!Du.has(t)}function rf(o){if(o instanceof CanvasCaptureMediaStreamTrack||!(o instanceof MediaStreamTrack))return!1;let i=o.label.toLocaleLowerCase();if(i.includes("mic")||i.includes("\u9EA6\u514B\u98CE"))return!0;let t=`${((o==null?void 0:o.getSettings())||{}).deviceId}_${p.AUDIO_INPUT}`;return!!Du.has(t)}function Ou(o,i){return f(this,null,function*(){let t=(yield It()).find(r=>r.deviceId===Wr);return!i&&(t==null?void 0:t.groupId)===o||(t==null?void 0:t.groupId)===o&&t.label===i})}function of(s){return f(this,arguments,function*({newDeviceId:o,oldDeviceId:i,oldGroupId:e,oldLabel:t,kind:r}){return o!==i?!1:r===p.AUDIO&&o===Wr?yield Ou(e,t):!0})}var Nc,Mu=class extends On{constructor(e){super();this.log=e;d(this,"volumeMeter");d(this,"volumeMeterAfter3A");d(this,"volumeDestination");d(this,"analyser",new yc);this.volumeMeter=new kn({log:this.log}),this.volumeMeterAfter3A=new kn({log:this.log}),this.volumeDestination=new xe,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},hs=class o extends pi{constructor(e){super(e,p.AUDIO);d(this,"_outputDeviceId");d(this,"_volume",1);d(this,"_destination",Se("player").createMediaStreamDestination());d(this,"pipeline");d(this,"volumeMeterMode","worklet");d(this,"enableVolumeControlInIOS");this.enableVolumeControlInIOS=e.enableVolumeControlInIOS,this.mode=0,e.url&&(this.url=e.url),this.pipeline=new Mu(this._log)}get duration(){var e;return Math.floor((((e=this.element)==null?void 0:e.duration)||0)*1e3)}get currentTime(){var e;return Math.floor((((e=this.element)==null?void 0:e.currentTime)||0)*1e3)}set currentTime(e){this.element&&(this.element.currentTime=e/1e3)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(e){if((Tt==="15.2"||Tt==="15.3"||Tt==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}let r=Nc||new Audio;r.setAttribute("autoplay","autoplay"),r.srcObject=this.getMediaStream(),r.muted=this.muted,this.url&&(r.crossOrigin="anonymous",r.src=this.url),this.element=r,Q(e)&&(this.element.volume=Math.min(Math.max(e,0),1)),r===Nc&&(Nc=void 0),this.options.enableTimeupdateEvent&&(this.element.ontimeupdate=()=>this.emit(he.TIME_UPDATE,this.currentTime)),this.bindElementEvents()}play(e){return f(this,null,function*(){if(!(!this.track&&!this.url))return!this.pipeline.source.node&&this.track&&this.pipeline.replaceSource(this.track),this.element||this.initializeElement(e==null?void 0:e.volume),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),this.volumeMeterMode==="worklet"?(this.pipeline.volumeMeter.init(),this.pipeline.volumeMeterAfter3A.init()):this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(Se("player").createAnalyser()),ef(),He(o.prototype,this,"play").call(this)})}stop(e=0){this.pipeline.destroy(),super.stop(e)}setVolume(e){this._volume=e,this.element&&(this.element.volume=e)}setSinkId(e){return f(this,null,function*(){var t,r;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield(r=(t=this.element).setSinkId)==null?void 0:r.call(t,e))})}get useDestination(){return!!this.pipeline.stream}setLoop(e){this.element&&(this.element.loop=e)}getAudioLevel(){return this.pipeline.volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this.pipeline.volumeMeter.getInternalAudioLevel()}getInternalAudioLevelAfter3A(){return this.pipeline.volumeMeterAfter3A.getInternalAudioLevel()}},Dc=class extends hs{setTrack(i){this.track!==i&&(this.unbindTrackEvents(),this.track=i,this.emit(he.MEDIA_TRACK_CHANGED,i),i&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([i]))))}},Oc=class extends hs{constructor(e){super(e);d(this,"_sourceElement");d(this,"_output",new xe);this.pipeline.source.pipeTo(this.pipeline.gain),this.pipeline.gain.pipeTo(this.pipeline.volumeMeter).pipeTo(this._output),this.pipeline.gain.pipeTo(this.pipeline.destination)}setOutput(){this.mode=1,this._output.setNode(Se("player").destination)}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var t,r,s;((r=(t=this.element)==null?void 0:t.error)==null?void 0:r.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(he.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([e]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e])),this.pipeline.source.channelCount=((s=e.getSettings())==null?void 0:s.channelCount)||1,this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){if(this._volume=e,this.useDestination)this.pipeline.setVolume(e),this._log.info(`set pipeline volume: ${e}`);else if(e<=1&&!Te)this.element?(this._log.info(`set element volume: ${e}`),this.element.volume=e):this._log.info("set element volume: no element");else{if(Te)if(this.enableVolumeControlInIOS)Xp();else return;if(te&&!this.pipeline.source.node){this._log.warn("set pipeline volume failed: no source node");return}this._log.info(`start set pipeline volume: ${e}`),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),Le(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play())}}stop(e=0){this.pipeline.destroy();let t=this._sourceElement||this.element;t&&Ft&&(Nc=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}};var no=class extends q{constructor({userId:e,sdkAppId:t,mediaType:r,room:s,PlayerClass:n=r===1?Oc:it}){var a;super();d(this,"id",cn());d(this,"userId","");d(this,"isRemote");d(this,"mediaType");d(this,"room");d(this,"user");d(this,"_log");d(this,"_inputTrack");d(this,"_outputTrack");d(this,"isPlayCalled");d(this,"container",null);d(this,"player");d(this,"subVideoPlayerMap");d(this,"muted",!1);d(this,"abortCtrl");d(this,"objectFit","cover");d(this,"mirror");d(this,"rotation");d(this,"isScreen",!1);d(this,"manager");d(this,"trackSettings");d(this,"isFirstVideoFrameEmitted",!1);this.userId=e||"",this.mediaType=r,this._log=R.createLogger({parent:s==null?void 0:s.getLogger(),id:`${this.kind[0]}t`,userId:(a=s||this.room)==null?void 0:a.userId,remoteUserId:this instanceof fi?void 0:this.userId,sdkAppId:t,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof fi}),this.player=new n({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log,enableVolumeControlInIOS:s==null?void 0:s.enableVolumeControlInIOS}),this.player.on(he.PLAYER_STATE_CHANGED,c=>{if(S.emit(A.PLAYER_STATE_CHANGED,M({track:this},c)),this.emit("player-state-changed",c),c.state==="PLAYING"&&this.room){let l=!0;for(let{remoteAudioTrack:u,remoteVideoTrack:h,remoteAuxiliaryTrack:m}of[...this.room.remotePublishedUserMap.values()])if(u.isAvailable&&!u.player.isPlaying||h.isAvailable&&!h.player.isPlaying||m.isAvailable&&!m.player.isPlaying){l=!1;break}l&&br()&&$p()}}),this.kind===p.VIDEO&&(this.player.on(he.LOADED_DATA,()=>{this.emitFirstVideoFrameEvent(he.LOADED_DATA),S.emit(A.VIDEO_LOADED_DATA,{track:this})}),this.player.on(he.LOADED_META_DATA,()=>{this.emitFirstVideoFrameEvent(he.LOADED_META_DATA)}),this.player.on(he.MEDIA_TRACK_CHANGED,c=>{var l;(l=this.subVideoPlayerMap)==null||l.forEach(u=>u.setTrack(c))}),this.player.on(he.RESIZE,c=>{this.emitFirstVideoFrameEvent(he.RESIZE),this.emit("video-size-changed",M({userId:this.userId,streamType:this.mediaType===2?"auxiliary":"main"},c))})),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(he.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||R}get kind(){return this.mediaType===1?p.AUDIO:p.VIDEO}get isAudio(){return this.kind===p.AUDIO}get strMediaType(){return this.mediaType===4?p.VIDEO:this.mediaType===2?p.SCREEN:p.AUDIO}get streamType(){return(this.mediaType&2)===0?"main":"auxiliary"}get isMediaTrackActive(){return this.mediaTrack?!this.mediaTrack.muted&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled:!1}play(e,t){return f(this,null,function*(){let r=Ae(e)?e[0]:e;if(this.isPlayCalled){this.log.info(`play update options: ${JSON.stringify(t)}`),t&&!T(t.muted)&&this.setPlayerMute(t.muted),t&&!T(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof it&&(this.player.setObjectFit(this.objectFit),this.container!==r&&r&&(this.container=r,this.player.setContainer(r)),Ae(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t)));return}if(t&&!T(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===p.VIDEO)&&this.setPlayerMute(!0),t&&!T(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof it&&(this.player.setObjectFit(this.objectFit),t&&!T(t.poster)&&this.player.setPoster(t.poster)),this.isPlayCalled=!0,r&&(this.container=r,this.player instanceof it&&this.player.setContainer(r)),S.emit(A.PLAY_TRACK_START,{track:this}),!this._outputTrack){this.log.info("play has not mediaTrack, abort");return}this._log.info(`play with options: ${JSON.stringify(t)}`);try{this.player.setTrack(this.playerMediaTrack),yield this.player.play(t),Ae(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(s){throw this.handleAutoPlayFailed(s),s}})}setMirror(e,t){if(this.isScreen||this.kind!==p.VIDEO||T(e)||e===this.mirror)return;this.mirror=e;let r=this.player;t&&(r=t);let s=this.manager;if(me(this.mirror)){r.setViewMirror(this.mirror),!this.isRemote&&s&&(s.mirror=!1);return}switch(this.mirror){case"view":{s&&(s.mirror=!1),r.setViewMirror(!0);break}case"publish":{s&&(s.mirror=!0),r.setViewMirror(!0);break}case"both":s&&(s.mirror=!0),r.setViewMirror(!1)}}playSubContainer(e,t){return f(this,null,function*(){if(!this._outputTrack||this.kind===p.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((s,n)=>{var a;e.find(c=>n===c)||(s.stop(),(a=this.subVideoPlayerMap)==null||a.delete(n))});for(let[s,n]of e.entries()){let a=this.subVideoPlayerMap.get(n);a?t&&(T(t.objectFit)||a.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new it({id:this.userId||this.id,track:this.playerMediaTrack,container:n,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:`vp-sub${s+1}`})}))}let r=[...this.subVideoPlayerMap.values()];for(let s of r)s.setViewMirror(this.player.mirror),yield s.play()})}setAudioOutput(e){return this.player.setSinkId(e)}setAudioVolume(e){this.player.setVolume(e)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var e;return((e=this.player)==null?void 0:e.getInternalAudioLevel())||0}stop(e=!1){this.isPlayCalled&&(this.isPlayCalled=!1,this.isFirstVideoFrameEmitted=!1,this.player&&(this.log.info(`stop ${this.kind} player`),this.player.stop(Sl(this)&&!e?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(t=>{t.stop()}),this.container=null)}resume(){return f(this,null,function*(){var e;this.isPlayCalled&&(yield(e=this.player)==null?void 0:e.resume())})}close(){this.log.info("close"),this.isPlayCalled&&this.stop(!0)}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),S.emit(e?A.TRACK_MUTED:A.TRACK_UNMUTED,{track:this})}setPlayerMute(e){this.player.setMuted(e)}get mediaTrack(){return this._inputTrack||null}get outMediaTrack(){return this._outputTrack||null}get playerMediaTrack(){return this.outMediaTrack}installTrackEvent(e){tt(e,e).add(p.MUTE,this.onTrackMuted).add(p.UNMUTE,this.onTrackUnmuted).add(p.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===p.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){Le(e)}setInputMediaStreamTrack(e){var r;let t=this._inputTrack;if(e!==t)return this._inputTrack=e,this.trackSettings=(r=e.getSettings)==null?void 0:r.call(e),e.enabled=!this.muted,t&&this.uninstallTrackEvent(t),this.installTrackEvent(e),this.emit("input-media-track-changed",e||null,t||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var r;let t=this._outputTrack;e!==t&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",(r=e.getSettings)==null?void 0:r.call(e).deviceId,e.label),this._outputTrack=e,this._inputTrack&&(this._outputTrack.contentHint=this._inputTrack.contentHint,this._outputTrack.enabled=this._inputTrack.enabled),this.updatePlayingState(!!e),this.emit("output-media-track-changed",e))}setMediaType(e){this.mediaType=e}updatePlayingState(e){if(this.isPlayCalled){if(e){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped){this.player.play().catch(t=>this.handleAutoPlayFailed(t)),this.log.info(`playing state updated, play ${this.kind}`);return}}else if(!this.player.isStopped){this.player.stop(Sl(this)?this.jitterBufferDelay:0),this.log.info(`playing state updated, stop ${this.kind}`);return}}this.log.debug(`updatePlayingState abort ${this.isPlayCalled} ${e} ${this.player.isStopped}`)}handleAutoPlayFailed(e){return f(this,null,function*(){var r;this.log.warn("handleAutoPlayFailed",e);let t=()=>{this.resume().then(()=>{document.removeEventListener("click",t,!0)})};if(this.room&&this.room.enableAutoPlayDialog){if((qi||ji)&&(yield Ke(100),(r=this.player)!=null&&r.isPlaying))return;as()}else document.addEventListener("click",t,!0);S.once(A.LOCAL_TRACK_CAPTURE_SUCCESS,({track:s})=>{s.kind==="audio"&&br()&&!this.player.isPlaying&&this.isRemote&&this.isAvailable&&t()}),this.emit("error",e)})}getVideoFrame(){return this.player instanceof it?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(e){var n,a,c;if(this.isFirstVideoFrameEmitted)return;let t=(n=this.mediaTrack)==null?void 0:n.getSettings(),r=(t==null?void 0:t.width)||((a=this.player.element)==null?void 0:a.videoWidth)||0,s=(t==null?void 0:t.height)||((c=this.player.element)==null?void 0:c.videoHeight)||0;e===he.RESIZE&&!r&&!s||e===he.LOADED_META_DATA&&!r&&!s||(e===he.LOADED_DATA&&!r&&!s&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,bt(this.rotation)&&([r,s]=[s,r]),this.emit("first-video-frame",{width:r,height:s,streamType:this.streamType,userId:this.isRemote?this.userId:""}))}onTrackMuted(){this._log.warn(`${this.kind} track is unable to provide media output`)}onTrackUnmuted(){this._log.info(`${this.kind} track is able to provide media output`)}onTrackEnded(){this._log.warn(`${this.kind} track ended`)}};O([ye([],q.INIT,{sync:!0})],no.prototype,"close",1);var jT=Object.prototype.hasOwnProperty,{toString:Cb}=Object.prototype;function XT(o){if(o==null)return!0;if(typeof o=="boolean")return!1;if(typeof o=="number")return o===0;if(typeof o=="string"||typeof o=="function"||Array.isArray(o))return o.length===0;if(o instanceof Error)return o.message==="";if(dt(o))switch(Object.prototype.toString.call(o)){case"[object File]":case"[object Map]":case"[object Set]":return o.size===0;case"[object Object]":{for(let i in o)if(jT.call(o,i))return!1;return!0}}return!1}var _i=XT;var zT=function(o){return f(this,null,function*(){let i=YT(o);R.info(`getUserMedia with constraints: ${JSON.stringify(i)}`);let e=[],t=[],r=["label","deviceId","groupId"];if(i.audio&&(e=yield It(),R.info(`microphones: ${_t(e.map(s=>L(M({},s),{groupId:s.groupId.substring(0,8)})),{keysToInclude:r})}`)),i.video&&(t=yield At(),R.info(`cameras: ${_t(t,{keysToInclude:r})}`),!me(i.video)&&i.video.facingMode==="user"&&!i.video.deviceId)){let n=t.filter(a=>!a.label.includes("infrared")).find(a=>a.label.includes("facing front"));n&&(i.video.deviceId=n.deviceId,R.info(`exclude infrared camera: ${JSON.stringify(i)}`))}try{let s=yield navigator.mediaDevices.getUserMedia(i);return cu&&s.getTracks().forEach(n=>{var c;let a=n.getCapabilities();R.info(`${n.kind} capabilities: ${_t(a,{keysToInclude:Ia})}`),!T(o.echoCancellation)&&((c=a.echoCancellation)==null?void 0:c.indexOf(o.echoCancellation))===-1&&R.warn(`Invalid argument for 'echoCancellation'. Expected one of [${JSON.stringify(a.echoCancellation)}], but received '${o.echoCancellation}'`)}),i.audio&&vr(),s}catch(s){let{message:n}=s;throw s.name==="NotFoundError"&&(o.video&&t&&t.length===0&&(n=H({key:B.CAMERA_NOT_FOUND})),o.audio&&e&&e.length===0&&(n=H({key:B.MICROPHONE_NOT_FOUND}))),new D({code:I.INITIALIZE_FAILED,name:s.name,message:n,constraint:s.constraint})}})},QT=Ci({retryFunction:zT,settings:{retries:3,timeout:500},onError:({error:o,retry:i,reject:e,retryFuncArgs:t,retriedCount:r})=>{let s=r+1;o.name==="NotReadableError"||o.name==="OverconstrainedError"||o.name==="AbortError"?(s===1?(t[0].video&&(t[0].maxResolution=!1,(!Pe||t[0].width*t[0].height<=1920*1080)&&t[0].frameRate&&(t[0].frameRate=t[0].frameRate>10?10:5)),t[0].retryWhenExactFailed&&t[0].useExactDeviceId&&(t[0].useExactDeviceId=!1)):s===2?t[0].useDeviceIdOnly=!0:s===3&&!t[0].useExactDeviceId&&(t[0].useTrueAsConstraint=!0),i()):e(o),t[0].microphoneId&&sf(t[0].microphoneId,!1),t[0].cameraId&&sf(t[0].cameraId,!0)},onRetrying:o=>{R.warn(`getUserMedia NotReadableError observed, retrying [${o}/3]`)},onRetryFailed:o=>{oe.logFailedEvent({eventType:Ze.GET_USER_MEDIA_RETRY,error:o})},onRetrySuccess:o=>{oe.logSuccessEvent({eventType:Ze.GET_USER_MEDIA_RETRY}),oe.uploadEvent({log:`stat-${Ze.GET_USER_MEDIA_RETRY}-success-${o}`})}});function sf(o,i){return f(this,null,function*(){let t=(i?yield At():yield It()).find(r=>r.deviceId===o);t&&ue(t.getCapabilities)&&R.warn(_t(t.getCapabilities(),{keysToInclude:Ia}))})}function YT(o){return{audio:ZT(o),video:KT(o)}}function ZT(o){if(!o.audio)return!1;if(o.useTrueAsConstraint)return!0;let i={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:o.sampleRate};return!_i(o.microphoneId)&&(i.deviceId=o.useExactDeviceId?{exact:o.microphoneId}:o.microphoneId,o.useDeviceIdOnly)?i:(Q(o.channelCount)&&(i.channelCount=o.channelCount),(me(o.echoCancellation)||o.echoCancellation==="remote-only"||o.echoCancellation==="all")&&(i.echoCancellation=o.echoCancellation),me(o.noiseSuppression)&&!o.noiseSuppression&&(i.noiseSuppression=!1),me(o.autoGainControl)&&!o.autoGainControl&&(i.autoGainControl=!1),_i(i)?!0:i)}function KT(o){if(!o.video)return!1;if(o.useTrueAsConstraint)return!0;let{maxResolution:i=!0}=o,e={};return o.cameraId?e.deviceId=o.useExactDeviceId?{exact:o.cameraId}:o.cameraId:o.facingMode&&(e.facingMode=o.facingMode),o.useDeviceIdOnly&&!_i(e)?e:(o.width&&(e.width={ideal:o.width},i&&!te&&(e.width.max=o.width)),o.height&&(e.height={ideal:o.height},i&&!te&&(e.height.max=o.height)),te&&oi&&o.width&&o.height&&o.width*o.height<352*288&&(e.width=o.width,e.height=o.height),o.frameRate&&(e.frameRate=o.frameRate),_i(e)?!0:e)}var nf=QT;function Mc(o){return Y((i,e)=>function(...t){return f(this,null,function*(){return yield o.apply(this,t),i.apply(this,t)})})}function Ct(o){return Y((i,e)=>function(...t){return f(this,null,function*(){let r=yield i.apply(this,t);return yield o.call(this,...t),r})})}function kc(o){return Y((i,e)=>function(...t){return f(this,null,function*(){try{return yield i.apply(this,t)}catch(r){o.call(this,r)}})})}function Y(o){return function(i,e,t){return t.value=o(t.value,e),t}}var af=(()=>{let o=!1,i=document.visibilityState;return()=>{document.visibilityState!==i&&R.info(`visibility change: ${document.visibilityState}`),!o&&(document.addEventListener("visibilitychange",()=>{R.info(`visibility change: ${document.visibilityState}`),i=document.visibilityState}),o=!0)}})();var eE=0,Pc=class{constructor(){d(this,"log",R.createLogger({id:`fq${++eE}`}));d(this,"isRunning",!1);d(this,"queue",[])}get length(){return this.queue.length}get lastQueueItem(){return this.length===0?null:this.queue[this.length-1]}push(i,e=!1){var s,n;let t=M({},i),r=new Promise((a,c)=>{t.resolve=a,t.reject=c});return t.promise=r,e?this.length<=1?this.queue.push(t):(n=(s=this.lastQueueItem)==null?void 0:s.promise)==null||n.then(t.resolve,t.reject):this.queue.push(t),this.log.debug(`push ${this.length}`),this.isRunning||this.callNext(),r}shift(){let i=this.queue.shift();return this.log.debug(`shift ${this.length}`),i}callNext(){if(this.isRunning||this.length===0)return;this.log.debug("callNext ",this.length);let{fn:i,args:e,context:t,resolve:r,reject:s}=this.queue[0];this.isRunning=!0,i.apply(t,e).then(r,s).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},wc=new WeakMap,Lc=new WeakMap;function ir(o=!1){return function(i,e,t){let r=t.value;return t.value=function(...s){let n=wc.get(this)||new Pc;return wc.set(this,n),n.push({fn:r,args:s,context:this},o)},t}}function xc(o){return function(i,e,t){let r=t.value;return t.value=function(...s){var a,c,l;let n=[];return(c=(a=wc.get(this))==null?void 0:a.queue)==null||c.forEach(u=>n.push(u)),(l=Lc.get(this))==null||l.forEach(u=>u==null?void 0:u.queue.forEach(h=>n.push(h))),n.forEach(u=>{u.reject(new D({code:I.API_CALL_ABORTED,message:o}))}),wc.delete(this),Lc.delete(this),r.apply(this,s)},t}}function gi(o){return function(i,e,t){let r=t.value,s=n=>o(...n);return t.value=function(...n){let a=Lc.get(this)||new Map,c=a.get(s(n))||new Pc;return a.set(s(n),c),Lc.set(this,a),c.push({fn:r,args:n,context:this})},t}}function Rt(o,i){return Y((e,t)=>function(...r){let s=o;try{let n=e.apply(this,r),a=U();return Tr(n)?n.then(c=>(i?v.addSuccessEvent({key:s,cost:U()-a}):v.addSuccessEvent({key:s}),c)).catch(c=>{throw v.addFailedEvent({key:s,error:c}),c}):(v.addSuccessEvent({key:s}),n)}catch(n){throw v.addFailedEvent({key:s,error:n}),n}})}var gh={};Vi(gh,{Events:()=>Me,Inspect:()=>$t,LastSink:()=>ao,Sink:()=>X,Subscribe:()=>co,TimeoutError:()=>wn,audit:()=>UE,bindCallback:()=>AE,bindNodeCallback:()=>CE,buffer:()=>dE,bufferCount:()=>cE,bufferTime:()=>iS,call:()=>cf,catchError:()=>ph,combineLatest:()=>lf,concat:()=>rE,concatMap:()=>XE,concatMapTo:()=>zE,count:()=>bE,create:()=>ne,debounce:()=>VE,debounceTime:()=>BE,defer:()=>uf,delay:()=>rS,deliver:()=>z,dispose:()=>Uc,elementAt:()=>FE,empty:()=>Vn,every:()=>JE,exhaustMap:()=>ZE,exhaustMapTo:()=>KE,expand:()=>oS,filter:()=>Wt,find:()=>HE,findIndex:()=>$E,first:()=>WE,fromAnimationFrame:()=>SE,fromArray:()=>pE,fromEvent:()=>de,fromEventPattern:()=>fE,fromFetch:()=>_E,fromIterable:()=>gE,fromPromise:()=>pf,fromReadableStream:()=>EE,fromReader:()=>TE,groupBy:()=>eS,identity:()=>tE,ignoreElements:()=>OE,iif:()=>sE,inspect:()=>df,interval:()=>Vu,last:()=>GE,map:()=>Bn,mapTo:()=>jE,max:()=>vE,merge:()=>Ln,mergeMap:()=>QE,mergeMapTo:()=>YE,min:()=>NE,never:()=>RE,nothing:()=>fe,of:()=>mE,pairwise:()=>qE,pipe:()=>le,race:()=>xu,range:()=>IE,reduce:()=>Bu,retry:()=>cS,scan:()=>mh,setAsapScheduler:()=>hE,share:()=>rr,shareReplay:()=>oE,skip:()=>kE,skipUntil:()=>PE,skipWhile:()=>$c,startWith:()=>xn,subject:()=>ot,subscribe:()=>Ee,sum:()=>DE,switchMap:()=>Or,switchMapTo:()=>mo,take:()=>or,takeLast:()=>ME,takeUntil:()=>ke,takeWhile:()=>ff,tap:()=>Fn,throttle:()=>LE,throwError:()=>yE,timeInterval:()=>tS,timeout:()=>aS,timer:()=>Un,toPromise:()=>sS,toReadableStream:()=>nS,withLatestFrom:()=>aE,zip:()=>nE});function fe(...o){}var cf=o=>o(),tE=o=>o;function Uc(){this.dispose()}var df=()=>typeof __FASTRX_DEVTOOLS__!="undefined",iE=1,$t=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(i){let e=new ku(i,this,this.streamId++);return Me.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},ao=class{constructor(){this.defers=new Set,this.disposed=!1}next(i){}complete(){this.dispose()}error(i){this.dispose()}get bindDispose(){return()=>this.dispose()}dispose(){this.disposed=!0,this.complete=fe,this.error=fe,this.next=fe,this.dispose=fe,this.subscribe=fe,this.doDefer()}subscribe(i){return i instanceof $t?i.subscribe(this):i(this),this}get bindSubscribe(){return i=>this.subscribe(i)}doDefer(){this.defers.forEach(cf),this.defers.clear()}defer(i){this.defers.add(i)}removeDefer(i){this.defers.delete(i)}reset(){this.disposed=!1,delete this.complete,delete this.next,delete this.dispose,delete this.next,delete this.subscribe}resetNext(){delete this.next}resetComplete(){delete this.complete}resetError(){delete this.error}},X=class extends ao{constructor(i){super(),this.sink=i,i.defer(this.bindDispose)}next(i){this.sink.next(i)}complete(){this.sink.complete()}error(i){this.sink.error(i)}},co=class extends ao{constructor(i,e=fe,t=fe,r=fe){if(super(),this._next=e,this._error=t,this._complete=r,this.then=fe,i instanceof $t){let s={toString:()=>"subscribe",id:0,source:i};this.defer(()=>{Me.defer(s,0)}),Me.create(s),Me.pipe(s),this.sourceId=s.id,this.subscribe(i),Me.subscribe({id:s.id,end:!0}),e==fe?this._next=n=>Me.next(s,0,n):this.next=n=>{Me.next(s,0,n),e(n)},r==fe?this._complete=()=>Me.complete(s,0):this.complete=()=>{this.dispose(),Me.complete(s,0),r()},t==fe?this._error=n=>Me.complete(s,0,n):this.error=n=>{this.dispose(),Me.complete(s,0,n),t(n)}}else this.subscribe(i)}next(i){this._next(i)}complete(){this.dispose(),this._complete()}error(i){this.dispose(),this._error(i)}};function le(o,...i){return i.reduce((e,t)=>t(e),o)}function ne(o,i,e){if(df()){let t=Object.defineProperties(Object.setPrototypeOf(o,$t.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:i,writable:!0,configurable:!0},args:{value:e,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});Me.create(t);for(let r=0;r<e.length;r++){let s=e[r];typeof s=="function"&&s instanceof $t&&Me.addSource(t,s)}return t}return o}function z(o,i){return function(...e){return t=>{if(t instanceof $t){let r=ne(s=>{let n=new o(s,...e);n.sourceId=r.id,n.subscribe(t)},i,arguments);return r.source=t,Me.pipe(r),r}else return r=>t(new o(r,...e))}}}function Dr(o,i){window.postMessage({source:"fastrx-devtools-backend",payload:{event:o,payload:i}})}var ku=class extends X{constructor(i,e,t){super(i),this.source=e,this.id=t,this.sourceId=i.sourceId,this.defer(()=>{Me.defer(this.source,this.id)})}next(i){Me.next(this.source,this.id,i),this.sink.next(i)}complete(){Me.complete(this.source,this.id),this.sink.complete()}error(i){Me.complete(this.source,this.id,i),this.sink.error(i)}},Me={addSource(o,i){Dr("addSource",{id:o.id,name:o.toString(),source:{id:i.id,name:i.toString()}})},next(o,i,e){Dr("next",{id:o.id,streamId:i,data:e&&e.toString()})},subscribe({id:o,end:i},e){Dr("subscribe",{id:o,end:i,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(o,i,e){Dr("complete",{id:o.id,streamId:i,err:e?e.toString():null})},defer(o,i){Dr("defer",{id:o.id,streamId:i})},pipe(o){Dr("pipe",{name:o.toString(),id:o.id,source:{id:o.source.id,name:o.source.toString()}})},update(o){Dr("update",{id:o.id,name:o.toString()})},create(o){o.id||(o.id=iE++),Dr("create",{name:o.toString(),id:o.id})}},wn=class extends Error{constructor(i){super(`timeout after ${i}ms`),this.timeout=i}};var Vc=class extends ao{constructor(i){super(),this.source=i,this.sinks=new Set}add(i){i.defer(()=>this.remove(i)),this.sinks.add(i).size===1&&(this.reset(),this.subscribe(this.source))}remove(i){this.sinks.delete(i),this.sinks.size===0&&this.dispose()}next(i){this.sinks.forEach(e=>e.next(i))}complete(){this.sinks.forEach(i=>i.complete()),this.sinks.clear()}error(i){this.sinks.forEach(e=>e.error(i)),this.sinks.clear()}};function rr(){return o=>{let i=new Vc(o);if(o instanceof $t){let e=ne(t=>{i.add(t)},"share",arguments);return i.sourceId=e.id,e.source=o,Me.pipe(e),e}return ne(i.add.bind(i),"share",arguments)}}function Ln(...o){return ne(i=>{let e=new X(i),t=o.length;e.complete=()=>{--t===0&&i.complete()},o.forEach(e.bindSubscribe)},"merge",arguments)}function xu(...o){return ne(i=>{let e=new Map;o.forEach(t=>{let r=new X(i);e.set(t,r),r.complete=()=>{e.delete(t),e.size===0?i.complete():r.dispose()},r.next=s=>{e.delete(t),e.forEach(n=>n.dispose()),r.resetNext(),r.resetComplete(),r.next(s)}}),o.forEach(t=>e.get(t).subscribe(t))},"race",arguments)}function rE(...o){return ne(i=>{let e=0,t=o.length,r=new X(i);r.complete=()=>{e<t&&!r.disposed?(r.doDefer(),r.subscribe(o[e++])):i.complete()},r.complete()},"concat",arguments)}function oE(o){return i=>{let e=new Vc(i),t=[];return e.next=function(r){t.push(r),t.length>o&&t.shift(),this.sinks.forEach(s=>s.next(r))},ne(r=>{r.defer(()=>e.remove(r)),t.forEach(s=>r.next(s)),e.add(r)},"shareReplay",arguments)}}function sE(o,i,e){return ne(t=>o()?i(t):e(t),"iif",arguments)}function lf(...o){return ne(i=>{let e=o.length,t=e,r=e,s=new Array(e),n=()=>{--r===0&&i.complete()},a=(c,l)=>{let u=new X(i);u.next=h=>{t--,u.next=m=>{s[l]=m,t===0&&i.next(s)},u.next(h)},u.complete=n,u.subscribe(c)};o.forEach(a)},"combineLatest",arguments)}function nE(...o){return ne(i=>{let e=o.length,t=e,r=new Array(e),s=()=>{--t===0&&i.complete()},n=(a,c)=>{let l=new X(i),u=[];r[c]=u,l.next=h=>{u.push(h),r.every(m=>m.length)&&i.next(r.map(m=>m.shift()))},l.complete=s,l.subscribe(a)};o.forEach(n)},"zip",arguments)}function xn(...o){return i=>ne((e,t=0,r=o.length)=>{for(;t<r&&!e.disposed;)e.next(o[t++]);e.disposed||e.subscribe(i)},"startWith",arguments)}var Pu=class extends X{constructor(i,...e){super(i);let t=new X(this.sink);t.next=r=>this.buffer=r,t.complete=fe,t.subscribe(lf(...e))}next(i){this.buffer&&this.sink.next([i,...this.buffer])}},aE=z(Pu,"withLatestFrom"),wu=class extends X{constructor(i,e,t){super(i),this.bufferSize=e,this.startBufferEvery=t,this.buffer=[],this.count=0,this.startBufferEvery&&(this.buffers=[[]])}next(i){this.startBufferEvery?(this.count++===this.startBufferEvery&&(this.buffers.push([]),this.count=1),this.buffers.forEach(e=>{e.push(i)}),this.buffers[0].length===this.bufferSize&&this.sink.next(this.buffers.shift())):(this.buffer.push(i),this.buffer.length===this.bufferSize&&(this.sink.next(this.buffer),this.buffer=[]))}complete(){this.buffer.length?this.sink.next(this.buffer):this.buffers.length&&this.buffers.forEach(i=>this.sink.next(i)),super.complete()}},cE=z(wu,"bufferCount"),Lu=class extends X{constructor(i,e){super(i),this.buffer=[];let t=new X(i);t.next=r=>{i.next(this.buffer),this.buffer=[]},t.complete=fe,t.subscribe(e)}next(i){this.buffer.push(i)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},dE=z(Lu,"buffer");var lE=function(o,i,e,t){function r(s){return s instanceof e?s:new e(function(n){n(s)})}return new(e||(e=Promise))(function(s,n){function a(u){try{l(t.next(u))}catch(h){n(h)}}function c(u){try{l(t.throw(u))}catch(h){n(h)}}function l(u){u.done?s(u.value):r(u.value).then(a,c)}l((t=t.apply(o,i||[])).next())})};function ot(o){let i=arguments,e=rr()(ne(t=>{e.next=r=>t.next(r),e.complete=()=>t.complete(),e.error=r=>t.error(r),o&&t.subscribe(o)},"subject",i));return e.next=fe,e.complete=fe,e.error=fe,e}function uf(o){return ne(i=>i.subscribe(o()),"defer",arguments)}var ms={promise:o=>{Promise.resolve().then(o)},setImmediate:typeof setImmediate!="undefined"?o=>setImmediate(o):null,setTimeout:o=>setTimeout(o,0)},uE=()=>typeof Promise!="undefined"?ms.promise:ms.setImmediate?ms.setImmediate:ms.setTimeout,Uu=uE(),hf=o=>i=>{Uu(()=>o(i))},hE=o=>{typeof o=="function"?Uu=o:ms[o]&&(Uu=ms[o])};var mf=o=>hf(i=>{for(let e=0;!i.disposed&&e<o.length;e++)i.next(o[e]);i.complete()});function mE(...o){return ne(mf(o),"of",arguments)}function pE(o){return ne(mf(o),"fromArray",arguments)}function Vu(o){return ne(i=>{let e=0,t=setInterval(()=>i.next(e++),o);return i.defer(()=>{clearInterval(t)}),"interval"},"interval",arguments)}function Un(o,i){return ne(e=>{let t=0,r=setTimeout(()=>{if(e.removeDefer(s),e.next(t++),i){let n=setInterval(()=>e.next(t++),i);e.defer(()=>{clearInterval(n)})}else e.complete()},o),s=()=>clearTimeout(r);e.defer(s)},"timer",arguments)}function Bc(o,i){return e=>{let t=r=>e.next(r);e.defer(()=>i(t)),o(t)}}function fE(o,i){return ne(Bc(o,i),"fromEventPattern",arguments)}function de(o,i){if("on"in o&&"off"in o)return ne(Bc(e=>o.on(i,e),e=>o.off(i,e)),"fromEvent",arguments);if("addListener"in o&&"removeListener"in o)return ne(Bc(e=>o.addListener(i,e),e=>o.removeListener(i,e)),"fromEvent",arguments);if("addEventListener"in o)return ne(Bc(e=>o.addEventListener(i,e),e=>o.removeEventListener(i,e)),"fromEvent",arguments);throw"target is not a EventDispachter"}function pf(o){return ne(i=>{o.then(i.next.bind(i),i.error.bind(i))},"fromPromise",arguments)}function _E(o,i){return ne(uf(()=>pf(fetch(o,i))),"fromFetch",arguments)}function gE(o){return ne(hf(i=>{try{for(let e of o){if(i.disposed)return;i.next(e)}i.complete()}catch(e){i.error(e)}}),"fromIterable",arguments)}function TE(o){let i=e=>lE(this,void 0,void 0,function*(){if(e.disposed)return;let{done:t,value:r}=yield o.read();if(t){e.complete();return}else e.next(r),i(e)});return ne(e=>{i(e)},"fromReader",arguments)}function EE(o){return ne(i=>{let e=new AbortController,t=e.signal;i.defer(()=>e.abort("cancelled")),o.pipeTo(new WritableStream({write(r){i.next(r)},close(){i.complete()},abort(r){i.error(r)}}),{signal:t}).then(()=>i.complete(),r=>i.error(r))},"fromReadableStream",arguments)}function SE(){return ne(o=>{let i=requestAnimationFrame(function e(t){o.disposed||(o.next(t),i=requestAnimationFrame(e))});o.defer(()=>cancelAnimationFrame(i))},"fromAnimationFrame",arguments)}function IE(o,i){return ne((e,t=o,r=i+o)=>{for(;t<r&&!e.disposed;)e.next(t++);return e.complete(),"range"},"range",arguments)}function AE(o,i,...e){return ne(t=>{let r=e.concat(s=>(t.next(s),t.complete()));o.apply(i,r)},"bindCallback",arguments)}function CE(o,i,...e){return ne(t=>{let r=e.concat((s,n)=>s?t.error(s):(t.next(n),t.complete()));o.apply(i,r)},"bindNodeCallback",arguments)}function RE(){return ne(()=>{},"never",arguments)}function yE(o){return ne(i=>i.error(o),"throwError",arguments)}function Vn(){return ne(o=>o.complete(),"empty",arguments)}var lo=class extends X{constructor(i,e,t){super(i),this.f=e;let r=()=>{this.sink.next(this.acc),this.sink.complete()};typeof t=="undefined"?this.next=s=>{this.acc=s,this.complete=r,this.resetNext()}:(this.acc=t,this.complete=r)}next(i){this.acc=this.f(this.acc,i)}},Bu=z(lo,"reduce"),bE=o=>z(lo,"count")((i,e)=>o(e)?i+1:i,0),vE=()=>z(lo,"max")(Math.max),NE=()=>z(lo,"min")(Math.min),DE=()=>z(lo,"sum")((o,i)=>o+i,0);var Fu=class extends X{constructor(i,e,t){super(i),this.filter=e,this.thisArg=t}next(i){this.filter.call(this.thisArg,i)&&this.sink.next(i)}},Wt=z(Fu,"filter"),Hu=class extends X{next(i){}},OE=z(Hu,"ignoreElements"),$u=class extends X{constructor(i,e){super(i),this.count=e}next(i){this.sink.next(i),--this.count===0&&(this.doDefer(),this.complete())}},or=z($u,"take"),Wu=class extends X{constructor(i,e){super(i);let t=new X(i);t.next=()=>{t.doDefer(),i.complete()},t.complete=Uc,t.subscribe(e)}},ke=z(Wu,"takeUntil"),Gu=class extends X{constructor(i,e){super(i),this.f=e}next(i){this.f(i)?this.sink.next(i):(this.doDefer(),this.complete())}},ff=z(Gu,"takeWhile"),ME=o=>Bu((i,e)=>(i.push(e),i.length>o&&i.shift(),i),[]),Ju=class extends X{constructor(i,e){super(i),this.count=e}next(i){--this.count===0&&(this.next=super.next)}},kE=z(Ju,"skip"),qu=class extends X{constructor(i,e){super(i),i.next=fe;let t=new X(i);t.next=()=>{t.doDefer(),i.resetNext()},t.complete=Uc,t.subscribe(e)}},PE=z(qu,"skipUntil"),ju=class extends X{constructor(i,e){super(i),this.f=e}next(i){this.f(i)||(this.next=super.next,this.next(i))}},$c=z(ju,"skipWhile"),wE={leading:!0,trailing:!1},Xu=class extends X{constructor(i,e,t){super(i),this.durationSelector=e,this.trailing=t}cacheValue(i){this.last=i,this.disposed&&this.throttle(i)}send(i){this.sink.next(i),this.throttle(i)}throttle(i){this.reset(),this.subscribe(this.durationSelector(i))}next(){this.complete()}complete(){this.dispose(),this.trailing&&this.send(this.last)}},Fc=class extends X{constructor(i,e,t=wE){super(i),this.durationSelector=e,this.config=t,this._throttle=new Xu(this.sink,this.durationSelector,this.config.trailing),this._throttle.dispose()}next(i){this._throttle.disposed&&this.config.leading?this._throttle.send(i):this._throttle.cacheValue(i)}complete(){this._throttle.throttle=fe,this._throttle.complete(),super.complete()}},LE=z(Fc,"throttle"),xE={leading:!1,trailing:!0},UE=o=>z(Fc,"audit")(o,xE),zu=class extends X{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},Hc=class extends X{constructor(i,e){super(i),this.durationSelector=e,this._debounce=new zu(this.sink),this._debounce.dispose()}next(i){this._debounce.dispose(),this._debounce.reset(),this._debounce.last=i,this._debounce.subscribe(this.durationSelector(i))}complete(){this._debounce.complete(),super.complete()}},VE=z(Hc,"debounce"),BE=o=>z(Hc,"debounceTime")(i=>Un(o)),Qu=class extends X{constructor(i,e,t){super(i),this.count=e,this.defaultValue=t}next(i){this.count--===0&&(this.defaultValue=i,this.doDefer(),this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("not enough elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},FE=z(Qu,"elementAt"),HE=o=>i=>or(1)($c(e=>!o(e))(i)),Yu=class extends X{constructor(i,e){super(i),this.f=e,this.i=0}next(i){this.f(i)?(this.sink.next(this.i++),this.doDefer(),this.complete()):++this.i}},$E=z(Yu,"findIndex"),Zu=class extends X{constructor(i,e,t){super(i),this.f=e,this.defaultValue=t,this.index=0}next(i){(!this.f||this.f(i,this.index++))&&(this.defaultValue=i,this.doDefer(),this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},WE=z(Zu,"first"),Ku=class extends X{constructor(i,e,t){super(i),this.f=e,this.defaultValue=t,this.index=0}next(i){(!this.f||this.f(i,this.index++))&&(this.defaultValue=i)}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},GE=z(Ku,"last"),eh=class extends X{constructor(i,e){super(i),this.predicate=e,this.index=0}next(i){this.predicate(i,this.index++)?this.result=!0:(this.result=!1,this.doDefer(),this.complete())}complete(){if(this.result===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.result);super.complete()}},JE=z(eh,"every");var th=class extends X{constructor(i,e,t){super(i),this.f=e,typeof t=="undefined"?this.next=r=>{this.acc=r,this.resetNext(),this.sink.next(this.acc)}:this.acc=t}next(i){this.sink.next(this.acc=this.f(this.acc,i))}},mh=z(th,"scan"),ih=class extends X{constructor(){super(...arguments),this.hasLast=!1}next(i){this.hasLast?this.sink.next([this.last,i]):this.hasLast=!0,this.last=i}},qE=z(ih,"pairwise"),Wc=class extends X{constructor(i,e,t){super(i),this.mapper=e,this.thisArg=t}next(i){super.next(this.mapper.call(this.thisArg,i))}},Bn=z(Wc,"map"),jE=o=>z(Wc,"mapTo")(i=>o),uo=class extends X{constructor(i,e,t){super(i),this.data=e,this.context=t}next(i){let e=this.context.combineResults;e?this.sink.next(e(this.data,i)):this.sink.next(i)}tryComplete(){this.context.resetComplete(),this.dispose()}},ho=class o extends X{constructor(i,e,t){super(i),this.makeSource=e,this.combineResults=t,this.index=0}subInner(i,e){let t=this.currentSink=new e(this.sink,i,this);this.complete===o.prototype.complete&&(this.complete=this.tryComplete),t.complete=t.tryComplete,t.subscribe(this.makeSource(i,this.index++))}complete(){this.sink.complete()}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},Gc=class extends uo{},Jc=class extends ho{next(i){this.subInner(i,Gc),this.next=e=>{this.currentSink.dispose(),this.subInner(e,Gc)}}},Or=z(Jc,"switchMap");function zc(o){return(i,e)=>o(()=>i,e)}var mo=zc(z(Jc,"switchMapTo")),rh=class extends uo{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},qc=class extends ho{constructor(){super(...arguments),this.sources=[],this.next2=this.sources.push.bind(this.sources)}next(i){this.next2(i),this.subNext()}subNext(){this.next=this.next2,this.subInner(this.sources.shift(),rh),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},XE=z(qc,"concatMap"),zE=zc(z(qc,"concatMapTo")),oh=class extends uo{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},jc=class extends ho{constructor(){super(...arguments),this.inners=new Set}next(i){this.subInner(i,oh),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(i=>i.resetComplete()):this.dispose()}},QE=z(jc,"mergeMap"),YE=zc(z(jc,"mergeMapTo")),sh=class extends uo{dispose(){this.context.resetNext(),super.dispose()}},Xc=class extends ho{next(i){this.next=fe,this.subInner(i,sh)}},ZE=z(Xc,"exhaustMap"),KE=zc(z(Xc,"exhaustMapTo")),nh=class extends X{constructor(i,e){super(i),this.f=e,this.groups=new Map}next(i){let e=this.f(i),t=this.groups.get(e);typeof t=="undefined"&&(t=ot(),t.key=e,this.groups.set(e,t),super.next(t)),t.next(i)}complete(){this.groups.forEach(i=>i.complete()),super.complete()}error(i){this.groups.forEach(e=>e.error(i)),super.error(i)}},eS=z(nh,"groupBy"),ah=class extends X{constructor(){super(...arguments),this.start=new Date}next(i){this.sink.next({value:i,interval:Number(new Date)-Number(this.start)}),this.start=new Date}},tS=z(ah,"timeInterval"),ch=class extends X{constructor(i,e){super(i),this.miniseconds=e,this.buffer=[],this.id=setInterval(()=>{this.sink.next(this.buffer.concat()),this.buffer.length=0},this.miniseconds)}next(i){this.buffer.push(i)}complete(){this.sink.next(this.buffer),super.complete()}dispose(){clearInterval(this.id),super.dispose()}},iS=z(ch,"bufferTime"),dh=class extends X{constructor(i,e){super(i),this.buffer=[],this.delayTime=e}dispose(){clearTimeout(this.timeoutId),super.dispose()}delay(i){this.timeoutId=setTimeout(()=>{let e=this.buffer.shift();if(e){let{time:t,data:r}=e;super.next(r),this.buffer.length&&this.delay(Number(this.buffer[0].time)-Number(t))}},i)}next(i){this.buffer.length||this.delay(this.delayTime),this.buffer.push({time:new Date,data:i})}complete(){this.timeoutId=setTimeout(()=>super.complete(),this.delayTime)}},rS=z(dh,"delay"),lh=class extends X{constructor(i,e){super(i),this.selector=e}error(i){this.dispose(),this.selector(i)(this.sink)}},ph=z(lh,"catchError"),uh=class extends uo{tryComplete(){let i=this.context.inners.delete(this);super.dispose(),i&&this.context.checkComplete()}next(i){this.sink.next(i),this.context.expandValue(i)}},hh=class extends ho{constructor(i,e){super(i,e),this.project=e,this.inners=new Set,this.sourceCompleted=!1}next(i){this.sink.next(i),this.expandValue(i)}expandValue(i){let e=new uh(this.sink,i,this);this.currentSink=e,this.complete=this.tryComplete,e.complete=e.tryComplete,this.inners.add(e),e.subscribe(this.makeSource(i,this.index++))}complete(){this.sourceCompleted=!0,this.checkComplete()}checkComplete(){this.sourceCompleted&&this.inners.size===0&&(this.resetComplete(),super.complete())}tryComplete(){this.sourceCompleted=!0,this.checkComplete()}},oS=z(hh,"expand");var sS=()=>o=>new Promise((i,e)=>{let t;new co(o,r=>t=r,e,()=>i(t))}),nS=()=>o=>{let i;return new ReadableStream({start(e){i=new co(o,e.enqueue.bind(e),e.error.bind(e),e.close.bind(e))},cancel(){i.dispose()}})},Ee=(o=fe,i=fe,e=fe)=>t=>new co(t,o,i,e),fh=class extends X{constructor(i,e){super(i),e instanceof Function?this.next=t=>{e(t),i.next(t)}:(e.next&&(this.next=t=>{e.next(t),i.next(t)}),e.complete&&(this.complete=()=>{e.complete(),i.complete()}),e.error&&(this.error=t=>{e.error(t),i.error(t)}))}},Fn=z(fh,"tap"),_h=class extends X{constructor(i,e){super(i),this.timeout=e,this.id=setTimeout(()=>this.error(new wn(this.timeout)),this.timeout)}next(i){super.next(i),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},aS=z(_h,"timeout"),cS=(o=1/0)=>i=>{if(i instanceof $t){let e=ne(t=>{let r=o,s=new X(t);s.error=n=>{r-- >0?s.subscribe(i):t.error(n)},s.sourceId=e.id,s.subscribe(i)},"retry",[o]);return e.source=i,Me.pipe(e),e}else return e=>{let t=o,r=new X(e);r.error=s=>{t-- >0?i(r):e.error(s)},i(r)}};var ps=(e=>(e[e.AUTO_SWITCH_NEW_DEVICE=0]="AUTO_SWITCH_NEW_DEVICE",e[e.WAIT_CURRENT_DEVICE=1]="WAIT_CURRENT_DEVICE",e))(ps||{}),po=class po extends no{constructor(e,t){super({mediaType:e,PlayerClass:t});d(this,"isRemote",!1);d(this,"deviceId");d(this,"groupId","");d(this,"label","");d(this,"sourceTrack");d(this,"enableAutoSwitchWhenRecapturing",!0);d(this,"_isRecapturing",!1);d(this,"_lastRecaptureTime",0);d(this,"_onMuteTimeoutId",-1);d(this,"_encodeCheckTimeoutId",-1);d(this,"recaptureMode",0);d(this,"profile");d(this,"retryEncodeFailed")}get enableEncodeFrame(){return!1}get isPublishing(){return this.state.toString()==="publishing"}get isPublished(){return this.state==="publish"}get isUseCustomSource(){return this.sourceTrack&&this.mediaTrack&&this.sourceTrack!==this.mediaTrack}encodeFrame(e,t){throw new Error("Method not implemented.")}installTrackEvent(e){e.addEventListener(p.MUTE,this.onTrackMuted),e.addEventListener(p.UNMUTE,this.onTrackUnmuted),e.addEventListener(p.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===p.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){e.removeEventListener(p.MUTE,this.onTrackMuted),e.removeEventListener(p.UNMUTE,this.onTrackUnmuted),e.removeEventListener(p.ENDED,this.onTrackEnded)}setStateToReady(){}capture(e,t=!1){return f(this,null,function*(){var s;let r=this.sourceTrack;try{let n=U();S.emit(A.LOCAL_TRACK_CAPTURE_START,{track:this});let a;e.customSource?(a=new MediaStream,a.addTrack(e.customSource)):(t||(s=this.sourceTrack)==null||s.stop(),a=yield nf(e));let c=a.getTracks()[0];return yield this.setInputMediaStreamTrack(c),e.customSource||(this.sourceTrack=c,this.updateDeviceIdInUse(),this.listenDeviceChange()),S.emit(A.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:U()-n}),a}catch(n){throw S.emit(A.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:n}),this.log.error(`getUserMedia error observed ${n}`),n}finally{t&&(r==null||r.stop())}})}setOutputMediaStreamTrack(e){var t;if(super.setOutputMediaStreamTrack(e),this.setStateToReady(),this.isPublishing||this.isPublished)return(t=this.room)==null?void 0:t.replaceTrack(this)}get hasFlag(){var t,r;let e=ei(((t=this.room)==null?void 0:t.localPublishFlag)||0,((r=this.room)==null?void 0:r.userId)||"");return this.mediaType===4&&e.hasVideo||this.mediaType===1&&e.hasAudio||this.mediaType===2&&e.hasAuxiliary}publish(e,t){return f(this,null,function*(){return this.room=e,this.room.localTracks.add(this),this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.bindParent(e.getLogger()),yield t,this._checkPublishFlag(e)})}_checkPublishFlag(e){return new Promise((t,r)=>f(this,null,function*(){var l,u,h,m;let s=()=>r(new D({code:I.API_CALL_ABORTED,message:"publish aborted"}));if(this.hasFlag||this.muted?t():((this.state===q.INIT||this.state==="ready")&&s(),le(de(e,"local-publish-flag-changed"),Wt(()=>this.hasFlag),ke(Ln(de(this,q.INIT),de(this,"ready"))),Ee(t,r,s))),(((u=(l=this.room)==null?void 0:l.networkQuality)==null?void 0:u.uplinkNetworkQuality)||0)>3)return t();let a=e.heartbeatCount,c=((m=(h=this.mediaTrack)==null?void 0:h.stats)==null?void 0:m.totalFrames)||0;this._encodeCheckTimeoutId=setTimeout(()=>f(this,null,function*(){var g,E,C,k,ae,w,Ye;if((((E=(g=this.room)==null?void 0:g.networkQuality)==null?void 0:E.uplinkNetworkQuality)||0)>3||e.heartbeatCount-a<3)return t();if((this.isPublished||this.isPublishing)&&this.isMediaTrackActive){if((C=this.mediaTrack)!=null&&C.stats){let j=this.mediaTrack.stats.totalFrames||0;j-c===0&&this.log.warn("capture totalFrames is 0 during encode check, totalFrames",j)}let N=this.kind===p.AUDIO,y=this.stat.bytesSent>0;if(v[y?"addSuccessEvent":"addFailedEvent"]({key:N?503700:513702}),!N){let j=((ae=(k=this.room)==null?void 0:k.videoCodec)==null?void 0:ae.toUpperCase())||"H264",ge={H264:513704,H265:513705,VP8:513706}[j];ge&&v[y?"addSuccessEvent":"addFailedEvent"]({key:ge})}if(!y){if(v.addEnum({key:N?503701:513703,value:Zr()}),oe.uploadEvent({log:`stat-encode-failed-${this.kind}-${ni()||ai()}`,userId:this.userId}),this.log.warn(N?"encode failed":`${(Ye=(w=this.room)==null?void 0:w.videoCodec)==null?void 0:Ye.toUpperCase()} encode failed`),this.retryEncodeFailed&&(this.log.warn("retry encode"),yield this.retryEncodeFailed(this),this.stat.bytesSent>0||this.hasFlag||(yield Ke(5e3),this.stat.bytesSent>0||this.hasFlag)))return t();this.emit("6",this),r(new D({message:`${this.strMediaType} encode failed`,code:N?I.AUDIO_ENCODE_FAILED:I.VIDEO_ENCODE_FAILED}))}}}),1e4)}))}unpublish(){this.room&&this.room.localTracks.delete(this),this.log.info("unpublish"),S.emit(A.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return f(this,null,function*(){if(this.sourceTrack&&bi){let{deviceId:e,groupId:t}=this.sourceTrack.getSettings(),{label:r}=this.sourceTrack;(yield of({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=r,t&&(this.groupId=t),ls().then(n=>{let a=n.find(c=>{let l=c.deviceId===e;return t&&(l=l&&c.groupId===t),l});a&&this.emit("2",a)}))}})}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(e=!1){return!(!this.deviceId||!this.sourceTrack||this.kind===p.AUDIO&&!rf(this.sourceTrack)||this.kind===p.VIDEO&&!tf(this.sourceTrack)||this._isRecapturing||e&&oi&&Pe)}onTrackMuted(){if(super.onTrackMuted(),af(),!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<Po){setTimeout(()=>this.onTrackMuted(),Po);return}this._onMuteTimeoutId=setTimeout(()=>f(this,null,function*(){var e;if((e=this.sourceTrack)!=null&&e.muted){if((Te||_e)&&document.visibilityState!=="visible")return;this.recapture(yield this.getRecoverCaptureDeviceId())}}),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return f(this,null,function*(){if(He(po.prototype,this,"onTrackEnded").call(this),!!this.isNeedToRecapture()&&this.recaptureMode===0){if(Date.now()-this._lastRecaptureTime<Po){setTimeout(()=>this.onTrackEnded(),Po);return}this.emit("7"),this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e,t=!1){return f(this,null,function*(){var n;if(this._isRecapturing||!this.sourceTrack)return;this.log.warn("recapture trying");let r=this.sourceTrack;t||(n=this.sourceTrack)==null||n.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let s={useExactDeviceId:!0};if(e==="user"||e==="environment")s.facingMode=e;else{let a;(this.kind==="audio"?yield It():yield At()).find(l=>l.deviceId===e)&&(a=e),s.deviceId=a}return this.capture(s,t).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),S.emit(A.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(a=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${a.message}`),this.emit("5",a),S.emit(A.LOCAL_TRACK_RECAPTURE,{track:this,error:a})}).finally(()=>{t&&(r==null||r.stop())})})}getRecoverCaptureDeviceId(){return f(this,null,function*(){let e=this instanceof Xe;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let r=(Hn.get(t)||0)+1;if(Hn.set(t,r),r>=3&&this.enableAutoSwitchWhenRecapturing){let s=e?(yield At()).find(n=>!Hn.has(n.deviceId)):(yield It()).find(n=>!Hn.has(n.deviceId));s&&(this.log.warn(`${t} capture fail ${r} times, change new ${s.deviceId}`),t=s.deviceId)}}return t})}stopCapture(){var e;this.sourceTrack&&(this.sourceTrack.stop(),this.uninstallTrackEvent(this.sourceTrack)),this._inputTrack&&this.uninstallTrackEvent(this._inputTrack),(e=this.manager)==null||e.removeInput(this)}close(){super.close(),this.stopCapture()}};O([ye(q.INIT,"ready",{ignoreError:!0,sync:!0})],po.prototype,"setStateToReady",1),O([ir()],po.prototype,"capture",1),O([ye("ready","publish",{ignoreError:!0,success(){S.emit(A.LOCAL_TRACK_PUBLISHED,{track:this,room:this.room}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),this.log.info("published")},fail(e){var n;(n=this.room)==null||n.localTracks.delete(this);let t="error",r=e instanceof D?e:e.cause instanceof D?e.cause:e,s=!1;r instanceof D&&(r.message.includes("timeout")?t="timeout":r.code===I.API_CALL_ABORTED&&(s=!0,t="api-call")),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:t,error:r}),this.log[s?"info":"error"]("publish failed",r)}}),Rt(521714,!1)],po.prototype,"publish",1),O([Y(e=>function(){return f(this,null,function*(){let t=this.state==="publish"?"started":"starting";e.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:t,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)})}),ye([],"ready",{sync:!0})],po.prototype,"unpublish",1);var fi=po,Hn=new Map;S.on(A.SWITCH_DEVICE_SUCCESS,o=>{o.track.deviceId&&Hn.delete(o.track.deviceId)});var kt=class o extends fi{constructor(e){super(1,Dc);d(this,"mediaType",1);d(this,"volume",0);d(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40});d(this,"playerMuted",!0);d(this,"pipeline");d(this,"earMonitorGainNode",new xe);d(this,"_output",new xe);d(this,"codecPipeline",[]);d(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0});d(this,"mixedAudioReferenceMap",new Map);d(this,"isAudioContextLongSuspended",!1);d(this,"after3aSilenceStartTime",0);this.manager=e,this.pipeline=new ds(e),this.pipeline.source.pipeTo(this.player.pipeline.volumeMeter),this.pipeline.gain.pipeTo(this.earMonitorGainNode).pipeTo(this._output),this.pipeline.gain.pipeTo(this.player.pipeline.volumeMeterAfter3A),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this),S.on(A.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this)}get dbVolume(){return so.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}getInternalAudioLevelAfter3A(){if(this.pipeline.isProcessEnabled)return this.player.getInternalAudioLevelAfter3A()}updateAfter3aSilenceStartTime(e){T(e)||(e===0&&!this.after3aSilenceStartTime?this.after3aSilenceStartTime=U():e>0&&(this.after3aSilenceStartTime=0))}setInputMediaStreamTrack(e){return f(this,null,function*(){let t=this.trackSettings||{};v.addEnum({key:501701,value:t.channelCount||0,useUV:!1}),v.addEnum({key:501702,value:t.sampleRate||0,useUV:!1}),v.addEnum({key:502700,value:0});let{sampleRate:r,channelCount:s}=t;this._log.info(`local audio track input ${JSON.stringify({sampleRate:r,channelCount:s})}`),this.pipeline.source.channelCount=s||1,this.pipeline.replaceSource(e),yield He(o.prototype,this,"setInputMediaStreamTrack").call(this,e),this.updatePlayingState(!!e)})}capture(a){return f(this,arguments,function*({deviceId:e,customSource:t,useExactDeviceId:r=!0,retryWhenExactFailed:s},n=!1){let c=yield He(o.prototype,this,"capture").call(this,{video:!1,audio:!0,microphoneId:e,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:r,retryWhenExactFailed:s,customSource:t},n);return vr(),c})}switchDevice(e){return f(this,null,function*(){if(this.mediaTrack){if(this.deviceId===e&&!this.isUseCustomSource)if(e===Wr){if(yield Ou(this.groupId,this.label))return}else return;try{this.log.info(`switchDevice audio to: ${e}`),this.sourceTrack&&this.sourceTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0,retryWhenExactFailed:!1}),S.emit(A.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(t){throw this.log.error(`switch microphone failed ${t}`),this.deviceId&&this.recapture(this.deviceId),t}}})}listenDeviceChange(){be&&!be.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&be.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return f(this,null,function*(){if(e.deviceId===this.deviceId){let t=this.recaptureMode===1;if(this.log.warn(`RecaptureMode: ${ps[this.recaptureMode]}. Current microphone is lost: ${JSON.stringify(e)}`),this.recaptureMode===0){ve(this.userId,{eventId:2003,param1:6,streamType:1});let r=yield It();r[0]?this.recapture(r[0].deviceId):t=!0}t&&be.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.recaptureMode===1&&e.deviceId!==this.deviceId||(be.off("audioInputAdded",this.handleMicrophoneAdded,this),this.log.warn(`microphone added: ${JSON.stringify(e)}`),this.recapture(e.deviceId))}update3A(s){return f(this,arguments,function*({echoCancellation:e,noiseSuppression:t,autoGainControl:r}){let n=this.sourceTrack||this.mediaTrack;if(!n)return;let a=n.getConstraints(),c=!1;!T(e)&&e!==this.profile.echoCancellation&&(this.profile.echoCancellation=e,a.echoCancellation=e,c=!0),!T(t)&&t!==this.profile.noiseSuppression&&(this.profile.noiseSuppression=t,a.noiseSuppression=t,c=!0),!T(r)&&r!==this.profile.autoGainControl&&(this.profile.autoGainControl=r,a.autoGainControl=r,c=!0),c&&(te||Pe?yield n.applyConstraints(a).catch(l=>this._log.warn("update3A failed: ",l)):this.deviceId&&(yield this.recapture(this.deviceId,!0)))})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&v.addEnum({key:502700,value:2})}setAudioVolume(e){super.setAudioVolume(0),Te&&this.player.setMuted(!0),this.earMonitorGainNode.node||(this.earMonitorGainNode.setNode(Se().createGain()),this._output.setNode(Se().destination)),this.earMonitorGainNode.node.gain.value=e}enableTrackANS(e){return this.update3A({noiseSuppression:e})}enableTrackAEC(e){if(this.sourceTrack&&!(Pe||Te))return this.update3A({echoCancellation:e})}addDenoiser(e){var t;if(qe<=92&&((t=this.trackSettings)==null?void 0:t.sampleRate)!==48e3){this._log.warn("denoiser only support sampleRate 48000 before chrome 93");return}v.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.enableTrackANS(!1)}mixAudioReference(e,t){if(this.mixedAudioReferenceMap.has(t))return;this.log.info(`mixAudioReference() => ${t}`);let r=Mn(e);if(!r)return;let s=new xe,n=Se().createGain();n.gain.value=1;let a=new xe;s.pipeTo(a).pipeTo(this.pipeline.mixNode),s.setNode(r),a.setNode(n),this.mixedAudioReferenceMap.set(t,[s,a])}unMixAudioReference(e){let[t,r]=this.mixedAudioReferenceMap.get(e)||[];t&&(this.log.info(`unMixAudioReference() => ${e}`),t.deleteNode(),r==null||r.deleteNode(),this.mixedAudioReferenceMap.delete(e))}setAudioReferenceVolume(e,t){let[r,s]=this.mixedAudioReferenceMap.get(e)||[];s!=null&&s.node&&(s.node.gain.value=t/100,this.log.info(`setAudioReferenceVolume() => ${e} ${s.node.gain.value}`))}addAudioProcessor(e,t,r){this.pipeline.silentNode.setNode(r),this.pipeline.mixNode.setNode(t),this.pipeline.aec.setNode(e)}removeDenoiser(e){if(this.pipeline.denoiser.node===e)return this.pipeline.denoiser.deleteNode(),this.enableTrackANS(!0)}removeAudioProcessor(e){this.pipeline.aec.node===e&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode())}close(){this.mixedAudioReferenceMap.forEach(([e,t])=>{e.deleteNode(),t.deleteNode()}),this.mixedAudioReferenceMap.clear(),this.pipeline.remove(),this.earMonitorGainNode.deleteNode(),this._output.deleteNode(),be.off("audioInputAdded",this.handleMicrophoneAdded,this),be.off("audioInputRemoved",this.handleMicrophoneRemoved,this),S.off(A.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this),super.close()}recapture(e,t=!1){return f(this,null,function*(){try{yield He(o.prototype,this,"recapture").call(this,e,t)}catch(r){let s=(yield It()).find(n=>n.deviceId!==e);if(s)yield He(o.prototype,this,"recapture").call(this,s.deviceId);else throw r}})}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduceRight((t,r)=>r?r({frame:t,ntp:Bi()}):t,e):e}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}get enableEncryptFrame(){return this.manager&&!!this.manager.encodePipeline[0]}handleAudioContextLongSuspended({isSuspended:e}){if(this.pipeline.isProcessEnabled)if(e){this.isAudioContextLongSuspended=!0,this.log.warn(`context has suspended for ${vu/1e3} seconds, change to source audio${Ft?"":", non-Safari"}`);let t=this.sourceTrack||this.mediaTrack;t&&this.setOutputMediaStreamTrack(t)}else this.isAudioContextLongSuspended=!1,this.log.warn("context has resumed, change to processed audio"),this.pipeline.track&&this.setOutputMediaStreamTrack(this.pipeline.track)}setOutputMediaStreamTrack(e){if(this.isAudioContextLongSuspended){let t=this.sourceTrack||this.mediaTrack;t&&(e=t)}super.setOutputMediaStreamTrack(e)}};var sr=class{constructor(i,e=!1){this.dataView=i;this.isSEI&&(e?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let i=this.seiPayloadStartIndex,e=this.dataView.byteLength-2,t=[],r=0;for(let n=i;n<=e;n++){let a=this.dataView.getInt8(n);switch(a){case 0:case 1:case 2:case 3:r===2&&(t.push(3),r=0),a==0?r++:r=0,t.push(a);break;default:r=0,t.push(a);break}}t.push(this.dataView.getInt8(this.dataView.byteLength-1));let s=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=s}removePreventionByte(){let i=this.seiPayloadStartIndex,e=this.dataView.byteLength-1,t=[],r=0;for(let n=i;n<=e;n++)switch(this.dataView.getInt8(n)){case 0:r++,t.push(this.dataView.getInt8(n));break;case 3:r!==2&&t.push(this.dataView.getInt8(n)),r=0;break;default:t.push(this.dataView.getInt8(n)),r=0;break}let s=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=s}get isSEI(){return this.dataView.getUint8(4)===6}get seiPayloadStartIndex(){let i=6;for(let e=6;e<this.dataView.buffer.byteLength&&(i++,this.dataView.getUint8(e)===255);e++);return i}get seiPayloadType(){return this.isSEI?this.dataView.getUint8(5):null}get seiPayload(){if(!this.isSEI)return null;let i=0,e=6;for(let s=6;s<this.dataView.buffer.byteLength;s++){let n=this.dataView.getUint8(s);if(e++,n===255)i+=255;else{i+=n;break}}let t=new ArrayBuffer(i),r=new DataView(t);for(let s=0;s<t.byteLength;s++,e++)r.setInt8(s,this.dataView.getInt8(e));return r}};var Qc=class{constructor(){d(this,"_seiMessageList",[]);d(this,"_smallSeiMessageList",[]);d(this,"_seiPayloadType",243)}encodeSEINalu(i){let e=i.byteLength,t=parseInt(String(e/255),10),r=e%255,s=[];s.push(0,0,0,1,6,this._seiPayloadType);for(let a=0;a<t;a++)s.push(255);s.push(r);let n=new DataView(i);return s.push(...new Uint8Array(n.buffer)),s.push(128),new sr(new DataView(new Uint8Array(s).buffer),!0)}sendSEI(i,e){e!=null&&e.seiPayloadType&&(this._seiPayloadType=e.seiPayloadType),this._seiMessageList.push(i),e!=null&&e.small&&this._smallSeiMessageList.push(i)}isEmpty(){return!this._seiMessageList.length}getNaluCount(i){let e=0,t=0,r=new DataView(i);for(let s=0;s<i.byteLength;s++)switch(r.getUint8(s)){case 0:e++;break;case 1:(e===2||e===3)&&t++,e=0;break;default:e=0;break}return t}encode(i,e){let t=e?this._smallSeiMessageList:this._seiMessageList;if(t.length>0&&i.data.byteLength>0){let s=9-this.getNaluCount(i.data);if(s<=0)return 0;let n=t.splice(0,s).reverse().map(this.encodeSEINalu.bind(this)),a=n.reduce((m,_)=>m+_.dataView.byteLength,0),c=new ArrayBuffer(a+i.data.byteLength),l=new DataView(c),u=new DataView(i.data),h=0;for(let m=0;m<n.length;m++)for(let _=0;_<n[m].dataView.byteLength;_++)l.setInt8(h++,n[m].dataView.getInt8(_));for(let m=0;m<i.data.byteLength;m++)l.setInt8(h++,u.getInt8(m));return i.data=c,n.length}return 0}};var Mr=class Mr extends fi{constructor(e,t=4){super(t,it);d(this,"profile",M({},pr));d(this,"avoidCropping",!1);d(this,"_scaleResolutionDownBy");d(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0,framesCaptured:0});d(this,"small");d(this,"isNeedToSetBandwidth");d(this,"muteImage");d(this,"manager");d(this,"_seiCodec",new Qc);this.manager=e;let r=()=>{var s;if(this.isAllowed2k4k(this.profile))this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1});else{let n=Vt(((s=this.room)==null?void 0:s.sdkAppId)||0)?ha:ua;this.log.warn(`Resolution is reset to 1080p, need to upgrade ability here ${n}`),this.setProfile(L(M({},this.profile),{width:1920,height:1080})),this.applyProfile()}};this.on("input-media-track-changed",r),this.on("publish",r),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(!(!bi||!this.mediaTrack))return this.mediaTrack.getSettings().facingMode}get contentHint(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)||""}get isQosClearFirst(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)==="detail"}get hasSmall(){var e;return!!((e=this.manager)!=null&&e.hasSmall)}setMute(e){return f(this,null,function*(){var t,r,s;if(ie(e)){if(this.muteImage===e)return;yield(t=this.manager)==null?void 0:t.deleteWatermark("mute"),yield(r=this.manager)==null?void 0:r.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:e,fillVideo:!0}),this.muteImage=e,He(Mr.prototype,this,"setMute").call(this,!1)}else this.muteImage&&(yield(s=this.manager)==null?void 0:s.deleteWatermark("mute"),this.muteImage=void 0),He(Mr.prototype,this,"setMute").call(this,e)})}capture(a){return f(this,arguments,function*({deviceId:e,facingMode:t,useExactDeviceId:r=!0,customSource:s,retryWhenExactFailed:n=!0}){let c={audio:!1,video:!0,facingMode:t||this.facingMode,cameraId:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:r,retryWhenExactFailed:n,customSource:s};if(c.facingMode==="environment"){let l=yield this.getDeviceIdWhenUsingBackCamera();l&&(c.cameraId=l)}return He(Mr.prototype,this,"capture").call(this,c)})}setProfile(e){var r;let t=this.fallbackProfile(e);if(t.bitrate&&(this.isNeedToSetBandwidth=t.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile))super.setProfile(t);else{let s=Vt(((r=this.room)==null?void 0:r.sdkAppId)||0)?ha:ua;this.log.warn(`Resolution is reset to 1080p, need to upgrade ability here ${s}`),super.setProfile(L(M({},this.profile),{width:1920,height:1080}))}}applyProfile(){return f(this,null,function*(){var a;if(!this.mediaTrack)return;let{width:e=0,height:t=0}=(this.sourceTrack||this.mediaTrack).getSettings(),r=e*t,s=this.settings,n=s.height!==this.profile.height||s.width!==this.profile.width||s.frameRate!==this.profile.frameRate;if(n&&(et===16&&this.deviceId?yield this.recapture(this.deviceId):(yield(a=this.sourceTrack||this.mediaTrack)==null?void 0:a.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}),this.manager&&this.manager.changeInput(this)),this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1})),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth){this.isNeedToSetBandwidth=!1;let{width:c=0,height:l=0}=(this.sourceTrack||this.mediaTrack).getSettings(),u=c*l;if(n&&u&&r&&u===r){this.log.warn("set bandwidth failed: resolution is not changed");return}return this.room.setBandWidth({bandwidth:this.profile.bitrate,type:p.VIDEO,videoType:p.BIG})}})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},t=this.sourceTrack||this.mediaTrack;return bi&&t&&Object.assign(e,t.getSettings()),e}get scaleResolutionDownBy(){return this._scaleResolutionDownBy?this._scaleResolutionDownBy:$o(this.settings,this.profile)}isAllowed2k4k(e){var t;return!this.room||!this.room.scheduleResult||this.isScreen||e.height*e.width<2560*1440?!0:((t=this.room.scheduleResult.trtcAutoConf)==null?void 0:t["2k4k"])===1}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}switchDevice(e){return f(this,null,function*(){try{if(!this.isNeedToSwitchDevice(e)&&!this.isUseCustomSource)return;let t={useExactDeviceId:!0,retryWhenExactFailed:!1};e==="user"||e==="environment"?t.facingMode=e:t.deviceId=e,this.sourceTrack&&this.sourceTrack.stop(),yield this.capture(t),S.emit(A.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(t){throw this.log.error(`switch camera failed ${t}`),this.deviceId&&this.recapture(this.deviceId),t}})}getDeviceIdWhenUsingBackCamera(){return f(this,null,function*(){let e;try{if(rn&&!Yo&&du){let r=(yield At(!0)).map(n=>{var a;return L(M({},n),{capabilities:(a=n.getCapabilities)==null?void 0:a.call(n)})}).filter(n=>{var a,c;return(c=(a=n.capabilities)==null?void 0:a.facingMode)==null?void 0:c.includes("environment")}),s=r[0];r.forEach(n=>{var u,h,m,_;let{capabilities:a}=n,c=(u=a.width)!=null&&u.max&&((h=a.height)!=null&&h.max)?a.width.max*a.height.max:0,l=(m=s.capabilities.width)!=null&&m.max&&((_=s.capabilities.height)!=null&&_.max)?s.capabilities.width.max*s.capabilities.height.max:0;c>l&&(s=n)}),s!=null&&s.capabilities&&(this._log.info("use max resolution back camera",s),e=s.deviceId)}}catch(t){this._log.warn("get max res camera failed",t)}return e})}updateSmallConfig(e){var r,s;this._log.info(`update small stream config: ${JSON.stringify(e)}`);let t=!this.small;this.small=this.fallbackProfile(e,!0),(r=this.manager)==null||r.update(),t&&((s=this.room)==null||s.enableSmall(!0)),this.log.info("update small stream config success")}fallbackProfile(e,t=!1){let r=e.width>e.height,s=M({},e);return e.width*e.height<=160*120&&_e&&We&&(this.log.warn(`${t?"small ":""}resolution is ${e.width}*${e.height}, fallback to 240*180 for android chrome`),s.width=r?240:180,s.height=r?180:240,s.bitrate=Math.max(e.bitrate,150)),e.width*e.height>1280*720&&Ml&&(s.width=r?1280:720,s.height=r?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),nn(Tt,"14.3")&&Dl(Tt,"14.0",!0)&&this.on("7",()=>{let n=this.profile.width>this.profile.height;this.profile.width*this.profile.height>640*480?(this.profile.width=n?640:480,this.profile.height=n?480:640,this.log.warn("reduce the resolution to 480p on iOS 14.0 ~ 14.2")):this.profile.width*this.profile.height>640*360&&(this.profile.width=n?640:360,this.profile.height=n?360:640,this.log.warn("reduce the resolution to 360p on iOS 14.0 ~ 14.2"))}),!t&&this.avoidCropping&&(We||te)&&!an()&&e.width*e.height<=640*360&&e.width/e.height===16/9&&(this._scaleResolutionDownBy=1280/e.width,e.width=1280,e.height=720,this.log.warn(`capture 720p, scale: ${this._scaleResolutionDownBy}`)),s}stopSmall(){var e,t;this.small&&(delete this.small,(e=this.manager)==null||e.update(),(t=this.room)==null||t.enableSmall(!1))}listenDeviceChange(){be&&!be.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&be.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return f(this,null,function*(){if(e.deviceId===this.deviceId){let t=this.recaptureMode===1;if(this.log.warn(`RecaptureMode: ${ps[this.recaptureMode]}. Current camera is lost: ${JSON.stringify(e)}`),this.recaptureMode===0){ve(this.userId,{eventId:2003,param1:7,streamType:2});let r=yield At();r[0]?this.recapture(r[0].deviceId):t=!0}t&&be.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return f(this,null,function*(){this.recaptureMode===1&&e.deviceId!==this.deviceId||(be.off("videoInputAdded",this.handleCameraAdded,this),this.log.warn(`camera added: ${JSON.stringify(e)}`),this.recapture(e.deviceId))})}encodeFrame(e,t){if(!this.manager)return e;let r=t?8:this.mediaType;return this.manager.encodePipeline.reduceRight((s,n)=>n?n({frame:s,mediaType:r}):s,e)}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}play(e,t){return T(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,t)}close(){be.off("videoInputAdded",this.handleCameraAdded,this),be.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return f(this,null,function*(){try{yield He(Mr.prototype,this,"recapture").call(this,e)}catch(t){let r=(yield At()).find(s=>s.deviceId!==e);if(r)yield He(Mr.prototype,this,"recapture").call(this,r.deviceId);else throw t}})}setContentHint(e){this.mediaTrack&&"contentHint"in this.mediaTrack&&(this.mediaTrack.contentHint!==e&&(this.log.info(`setContentHint ${e}`),this.mediaTrack.contentHint=e),this.outMediaTrack&&this.outMediaTrack.contentHint!==e&&(this.outMediaTrack.contentHint=e))}setRotation(e){this.manager&&(this.isScreen||T(e)||e!==this.rotation&&(this.rotation=e,this.manager.rotation=e))}};O([Ct(function(e){this.setContentHint(e.contentHint||"motion")})],Mr.prototype,"capture",1);var Xe=Mr;var Eh={};Vi(Eh,{REPORT_TYPE:()=>Wo,buildSSOPackage:()=>Gi,bytes2ms:()=>Om,calculateScaleResolutionDownNumber:()=>$o,concatArrayBuffers:()=>ka,convertObjectNumberToInt:()=>qs,copyProperties:()=>Dm,deepClone:()=>Gr,deepCloneBasic:()=>ya,deepMerge:()=>ti,delay:()=>Ke,fibonacci:()=>qr,formatedTime:()=>Bm,getConstructorName:()=>Uo,getContainerFromElement:()=>Vm,getEnv:()=>bm,getFirst16Bits:()=>Hm,getInternalVersion:()=>xm,getLast16Bits:()=>Pa,getLoggerUrl:()=>Wi,getMediaStreamTrackInfo:()=>Ma,getMuteStateFromFlag:()=>ei,getNetworkType:()=>ba,getNumNetworkType:()=>Jr,getReconnectionTimeout:()=>Kt,getStringByteLength:()=>Js,getTurnServer:()=>Um,getUint32Version:()=>Na,getValueType:()=>Oe,getViewListFromView:()=>Fo,glog:()=>_l,ipv4ToUint32:()=>Bo,isArray:()=>Ae,isAudioWorkletSupported:()=>wm,isBoolean:()=>me,isConstructor:()=>jr,isEmpty:()=>Vo,isFunction:()=>ue,isLangChinese:()=>Zt,isMediaStreamTrack:()=>km,isNumber:()=>Q,isObject:()=>yt,isOverseaSdkAppId:()=>Vt,isPlainObject:()=>dt,isPortrait:()=>gl,isPromise:()=>Tr,isRemoteTrack:()=>Pm,isRotate90Or270:()=>bt,isSetSinkIdSupported:()=>Lm,isString:()=>ie,isUndefined:()=>T,loadImage:()=>Ho,loadVideo:()=>Fm,ms2bytes:()=>Mm,ms2samples:()=>fl,normalizeUrl:()=>Oa,performanceNow:()=>U,promiseAny:()=>Xr,samples2ms:()=>pl,setNetworkTypeFromWebRTC:()=>va,stringify:()=>_t,stringifyIncludeValue:()=>Gs,throttlePromise:()=>Da});var uS=[-1,-1,1,-1,-1,1,1,1],hS=[0,0,1,0,0,1,1,1];var kr=class kr extends q{constructor(e,t){super();this.context=e;d(this,"name");d(this,"input");d(this,"output");d(this,"texture");d(this,"ctx2d",null);d(this,"fbo");d(this,"width",0);d(this,"height",0);d(this,"x",0);d(this,"y",0);d(this,"program");d(this,"vertexShader");d(this,"fragmentShader");d(this,"totalFrames",0);d(this,"dropFrames",0);d(this,"matchInputSize",!0);d(this,"texCoordBuffer");d(this,"positionBuffer");d(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0});d(this,"cost",0);d(this,"_canvas",null);d(this,"_image");d(this,"log");if(this.context.on("disconnect",this.close,this),this.name=t.name,this.log=t.logger,this.matchInputSize=t.matchInputSize!==!1,this.width=t.width||e.width,this.height=t.height||e.height,this._image=t.image,e instanceof ze){e.ctx&&t.create2d&&(typeof OffscreenCanvas=="function"&&et!==16?this._canvas=new OffscreenCanvas(this.width,this.height):(this._canvas=document.createElement("canvas"),this._canvas.width=this.width,this._canvas.height=this.height),this.ctx2d=this._canvas.getContext("2d"),this._image=this._canvas);return}try{let r=e.ctx;this.texCoordBuffer=this.createBuffer(hS),this.positionBuffer=this.createBuffer(uS),t.createTexture!==!1&&(this.texture=r.createTexture(),this.useTexture(),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.pixelStorei(r.UNPACK_ALIGNMENT,1)),t.useFbo&&(this.fbo=r.createFramebuffer(),this.useBufferFrame(),this.useTexture(),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,this.width,this.height,0,r.RGBA,r.UNSIGNED_BYTE,null),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,this.texture,0)),t.useDefaultProgram?this.program=e.defaultProgam:(t.vertexShaderSource||t.fragmentShaderSource)&&(this.vertexShader=t.vertexShaderSource?e.createShader(r.VERTEX_SHADER,t.vertexShaderSource):e.defaultVShader,this.fragmentShader=t.fragmentShaderSource?e.createShader(r.FRAGMENT_SHADER,t.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(r){this.context.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${r.message||r}`}))}}get image(){return this._image}set image(e){this._image=e}createFramebuffer(e){let t=this.context.ctx,r=t.createFramebuffer();return t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0),r}connect(e,...t){return e.addInput(this,...t),this.output=e,e}addInput(e,...t){this.input=e,this.matchInputSize&&e.width&&e.height&&this.resize(e.width,e.height)}requestFrame(e){let t=Date.now();if(this.context instanceof Fe&&this.render(e)||this.context instanceof ze&&this.render2d(e))this.totalFrames++;else return!1;return this.cost=Date.now()-t,!0}render2d(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?this.draw2d(this.input.image,0,0,this.width,this.height):!1}update(e=0){var t;(t=this.output)==null||t.update(e)}disconnect(...e){var t;(t=this.output)==null||t.removeInput(this,...e),delete this.output}removeInput(e,...t){delete this.input}close(){var e,t;if(this.context.off("disconnect",this.close,this),(e=this.output)==null||e.removeInput(this),delete this.output,(t=this.input)==null||t.disconnect(),this.context instanceof Fe){let r=this.context.ctx;r.deleteBuffer(this.texCoordBuffer),r.deleteBuffer(this.positionBuffer),this.fbo&&r.deleteFramebuffer(this.fbo),this.texture&&r.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&r.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&r.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&r.deleteProgram(this.program)}this._canvas&&(this._canvas.width=0,this._canvas.height=0,this.ctx2d=null),this.removeAllListeners()}useTexture(){this.useTextures(this.texture)}useInputTexture(){var e;this.useTextures((e=this.input)==null?void 0:e.texture)}useTextures(...e){let t=this.context.ctx;e.forEach((r,s)=>{r&&(t.activeTexture(t.TEXTURE0+s),t.bindTexture(t.TEXTURE_2D,r))})}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}createBuffer(e){let t=this.context.ctx,r=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,r),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW),r}setTexBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}setPosBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}changeBufferData(e,t){let r=this.context.ctx;r.bindBuffer(r.ARRAY_BUFFER,e),r.bufferData(r.ARRAY_BUFFER,new Float32Array(t),r.STATIC_DRAW)}setAttributes(...e){let t=this.context.ctx;e.forEach((r,s)=>{t.enableVertexAttribArray(s),t.bindBuffer(t.ARRAY_BUFFER,r),t.vertexAttribPointer(s,2,t.FLOAT,!1,0,0)})}getVertexPoint(e,t){return[e/this.width*2-1,t/this.height*2-1]}layout2texCoords(e){return[...this.getVertexPoint(e.x,e.y),...this.getVertexPoint(e.x+e.width,e.y),...this.getVertexPoint(e.x,e.y+e.height),...this.getVertexPoint(e.x+e.width,e.y+e.height)]}resize(e,t){if(!(this.width===e&&this.height===t)){if(this.width=e,this.height=t,this._canvas&&(this._canvas.width=e,this._canvas.height=t),this.texture&&this.fbo){this.useTexture();let r=this.context.ctx;r.texImage2D(r.TEXTURE_2D,0,r.RGBA,e,t,0,r.RGBA,r.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(e,t)}}draw(e,t){this.setAttributes(e||this.positionBuffer,t||this.texCoordBuffer);let r=this.context.ctx;r.drawArrays(r.TRIANGLE_STRIP,0,4)}draw2d(e,t,r,s,n,a,c,l,u){let h=!T(a)&&!T(c)&&!T(l)&&!T(u);return this.ctx2d&&e?(e instanceof ImageData?(h?this.ctx2d.putImageData(e,t,r,a,c,l,u):this.ctx2d.putImageData(e,t,r),this.emit(kr.RENDER,this.ctx2d.canvas)):(h?this.ctx2d.drawImage(e,a,c,l,u,t,r,s,n):this.ctx2d.drawImage(e,t,r,s,n),this.emit(kr.RENDER,e)),typeof VideoFrame!="undefined"&&e instanceof VideoFrame&&e.close(),!0):!1}drawBackGround2d(e){this.ctx2d&&(this.ctx2d.save(),this.ctx2d.fillStyle=e,this.ctx2d.fillRect(0,0,this.width,this.height),this.ctx2d.restore())}getInfo(){var h;let{totalFrames:e,x:t,y:r,width:s,height:n,name:a,cost:c}=this,l=Date.now(),u=(e-this.lastInfo.totalFrames)/((l-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:r,width:s,height:n,timestamp:l,fps:u,name:a,cost:c},M({parent:(h=this.input)==null?void 0:h.getInfo()},this.lastInfo)}createTexture(e){let t=this.context.ctx,r=t.createTexture();return this.useTextures(r),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.pixelStorei(t.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),r}};d(kr,"RENDER","render"),O([ye(q.INIT,"connected",{sync:!0})],kr.prototype,"connect",1),O([ye("connected",q.INIT,{ignoreError:!0,sync:!0})],kr.prototype,"disconnect",1),O([ye([],"closed",{sync:!0})],kr.prototype,"close",1);var Ue=kr;var mS=le(Vu(250),Bn(()=>performance.now()),rr());var _f=o=>i=>{let e=performance.now();le(mS,$c(t=>t-e<o),or(1))(i)};var fS=[0,1,1,1,0,0,1,0],fo=class extends Ue{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t));d(this,"_intervalId",0);d(this,"_sequence",0);d(this,"checkGLError",!1);d(this,"checkVisibilityChange");e instanceof ze?this.ctx2d=e.ctx||null:e.available&&(t!=null&&t.mirrorUpAndDown)&&this.setTexBuffer(fS)}start(e){this.log.info(`${this.name} start render ${e} fps`),re.clearTask(this._intervalId),this._intervalId=re.run("intervalInWorker",()=>{if(e!==this.context.frameRate&&(re.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof Fe){let r=this.context.ctx.getError();r&&this.context.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:5,message:`${this.name} req ${this._sequence} render ${this.totalFrames} faild ${r}`}))}},{fps:this.context.frameRate})}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),this.emit(Ue.RENDER,this.context._canvas),!0):!1}addInput(e,...t){super.addInput(e,...t),this.start(this.context.frameRate)}update(e=0){this.state!=="closed"&&(this._intervalId&&(re.clearTask(this._intervalId),this._intervalId=0,e===1&&(this.log.info(`${this.name} use requestVideoFrameCallback`),this.checkVisibilityChange=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info(`${this.name} use timer`),document.removeEventListener("visibilitychange",this.checkVisibilityChange))},document.addEventListener("visibilitychange",this.checkVisibilityChange))),this.requestFrame(this._sequence++))}removeInput(e){super.removeInput(e),re.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}close(){super.close(),re.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},fs=class extends fo{constructor(e,t){super(e,t);d(this,"_videoTrack");d(this,"_muteOb");d(this,"_closedOb",de(this,"closed"));d(this,"_subscription");d(this,"_canvasContainer");Number(Xi)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e.canvas.captureStream().getVideoTracks(),this._muteOb=de(this._videoTrack,"mute"),le(de(this._videoTrack,"ended"),ke(this._closedOb),Ee(()=>{this.context.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){this._subscription=le(this._muteOb,ke(this._closedOb),mo(_f(5e3)),Wt(()=>{var e;return!!((e=this._videoTrack)!=null&&e.muted)&&!document.hidden}),Ee(()=>{this.context.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:7,message:"video track muted"}))}))}disableCheckMute(){var e;(e=this._subscription)==null||e.dispose()}get videoTrack(){return this._videoTrack}putCanvasIntoDom(){!this.context._canvas||!this._canvasContainer||document.getElementById(this.context._canvas.id)||(this.log.info(`${this.name} put canvas to body`),document.body.appendChild(this._canvasContainer),this._canvasContainer.appendChild(this.context._canvas))}render(e){return this.putCanvasIntoDom(),super.render(e)}render2d(e){return this.putCanvasIntoDom(),super.render2d(e)}close(){var e,t;super.close(),(e=this._videoTrack)==null||e.stop(),delete this._videoTrack,(t=this._canvasContainer)==null||t.remove()}},Yc=class extends fs{render(i){var t;let e=!!((t=this.input)!=null&&t.requestFrame(i));if(this.context._canvas2d){let r=this.context._canvas2d.getContext("2d");r.clearRect(0,0,this.context._canvas2d.width,this.context._canvas2d.height),r.drawImage(this.context._canvas,0,0,this.context._canvas2d.width,this.context._canvas2d.height)}return e}};var Zc=class extends fs{constructor(e,t,r){super(e,{name:"smallDestination",logger:r});this.resolution=t}resize(e,t){let r,s=e*t,n=this.resolution.width*this.resolution.height;this.log.info(`big res: ${e}*${t} small res: ${this.resolution.width}*${this.resolution.height} `),s>n?r=s/n:(this.log.warn(`Small stream resolution is not smaller than big stream, which is invalid. big: ${e} * ${t} small: ${this.resolution.width} * ${this.resolution.height}`),r=s/(160*120)),super.resize(e/Math.sqrt(r),t/Math.sqrt(r))}};var $n=class extends Ue{constructor(e,t){super(e,M({name:"imageSource"},t));d(this,"_lastImage");d(this,"_totalFrames",0);d(this,"_autoResize",!1);d(this,"_canvasRendered");d(this,"videoCallbackId",0);d(this,"waitingFirstFrame",!0);d(this,"shouldUpdate",!0);this._autoResize=(t==null?void 0:t.autoResize)!==!1,et===16&&(this._canvasRendered=ot(),le(this._canvasRendered,xn(this._image),Or(r=>r instanceof HTMLCanvasElement?de(r,"rendered"):Vn()),ke(de(this,"closed")),Ee(()=>{this.update()})))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){if(!this.shouldUpdate)return;let e=this.image;this.videoCallbackId&&e.cancelVideoFrameCallback(this.videoCallbackId),Ki()&&!document.hidden&&(this.videoCallbackId=e.requestVideoFrameCallback((t,r)=>{this.waitingFirstFrame&&this.onFirstFrame(),document.hidden||(this._totalFrames=r.presentedFrames,this.update(1))}))}_render(e,t){var a;let{width:r,height:s}=this,{image:n}=this;if(n instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(),{videoWidth:r,videoHeight:s}=n,!r||!s)return!1;n.width=r,n.height=s}else if(n instanceof HTMLImageElement||n instanceof ImageData||n instanceof ImageBitmap){if({width:r,height:s}=n,n!==this._lastImage)this._lastImage=n;else if(r===this.width&&s===this.height)return!0}else n instanceof HTMLCanvasElement||n instanceof OffscreenCanvas?({width:r,height:s}=n,this._lastImage=n):typeof VideoFrame!="undefined"&&n instanceof VideoFrame&&({displayWidth:r,displayHeight:s}=n,(a=this._lastImage)==null||a.close(),this._lastImage=n);if(!this._autoResize)return!0;if(this.width===r&&this.height===s&&this.totalFrames){if(t){this.useTexture();let c=this.context.ctx;c.texSubImage2D(c.TEXTURE_2D,0,0,0,c.RGBA,c.UNSIGNED_BYTE,n)}}else{if(t){this.useTexture();let c=this.context.ctx;c.texImage2D(c.TEXTURE_2D,0,c.RGBA,c.RGBA,c.UNSIGNED_BYTE,n)}this.resize(r,s)}return!0}get image(){return this._image}set image(e){var t;(t=this._canvasRendered)==null||t.next(e),this._image=e}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},Wn=class extends $n{constructor(e,t,r){super(e,r);this._player=t;this.name="videoPlayerSource",le(de(this._player,he.PLAYER_STATE_CHANGED),ke(de(this,"closed")),Wt(({state:s})=>s==="PLAYING"),Ee(()=>{this.tryVideoFrameCallback()}))}get image(){return this._player.element}},Gt=class extends Wn{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(i,e,t){super(i,new it({id:t.name,track:e,muted:!0,container:null,objectFit:"contain",log:t.logger}),t),this.name="videoTrackSource",this._player.play()}replaceTrack(i){this.waitingFirstFrame=!0,this._player.setTrack(i),this._player.play()}close(){super.close(),this._player.stop()}},Kc=class extends Ue{constructor(e,t,r){super(e,L(M({name:"textSource"},r),{create2d:!0}));d(this,"hasChange",!0);d(this,"content","");this.ctx2d.textBaseline="top",this.content=t.content||"",t.font&&(this.font=t.font),t.color&&(this.color=t.color)}set font(e){this.ctx2d&&(this.ctx2d.font=e,this.hasChange=!0)}get font(){var e;return((e=this.ctx2d)==null?void 0:e.font)||""}set color(e){this.ctx2d&&(this.ctx2d.fillStyle=e,this.hasChange=!0)}get color(){var e;return((e=this.ctx2d)==null?void 0:e.fillStyle)||""}render2d(e){return this.ctx2d&&this.hasChange?(this.ctx2d.clearRect(0,0,this.width,this.height),this.drawMultilineText(0,0),this.hasChange=!1,!0):!1}render(e){return!1}resize(e,t){if(!this.ctx2d)return;let{color:r,font:s}=this;super.resize(e,t),this.color=r,this.font=s}drawMultilineText(e=0,t=0,r=1.2){if(!this.ctx2d)return;let s=this.ctx2d.measureText(this.content);t+=s.fontBoundingBoxAscent||s.actualBoundingBoxAscent||0;let n=this.font.match(/(\d+)px/),c=(n?parseInt(n[1],10):16)*r,l=this.content.split(`
|
|
34
|
+
`);for(let u=0;u<l.length;u++)this.ctx2d.fillText(l[u],e,t+u*c)}};var gS=`
|
|
34
35
|
// \u9876\u70B9\u7740\u8272\u5668
|
|
35
36
|
attribute vec4 a_position;
|
|
36
37
|
attribute vec2 a_texCoord;
|
|
@@ -40,7 +41,7 @@ void main() {
|
|
|
40
41
|
gl_Position = a_position;
|
|
41
42
|
v_texCoord = a_texCoord;
|
|
42
43
|
}
|
|
43
|
-
`,
|
|
44
|
+
`,TS=`
|
|
44
45
|
// \u7247\u5143\u7740\u8272\u5668
|
|
45
46
|
precision mediump float;
|
|
46
47
|
varying vec2 v_texCoord;
|
|
@@ -48,88 +49,32 @@ uniform sampler2D u_texture;
|
|
|
48
49
|
|
|
49
50
|
void main() {
|
|
50
51
|
gl_FragColor = texture2D(u_texture, v_texCoord);
|
|
51
|
-
} `;var sn=class extends Ve{constructor(e){super();p(this,"frameRate");p(this,"_canvas");p(this,"log");p(this,"hasAlpha",!1);p(this,"name");p(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,r){this._canvas&&(this._canvas.width=e,this._canvas.height=r)}createVideoTrackSource(e,r){return new di(this,e,{logger:this.log,name:r})}createVideoTrackDestination(e){return new da(this,e)}createVideoImageSource(e,r){return new Pc(this,r?Object.assign(r,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,r){return new Uc(this,e,r?Object.assign(r,{logger:this.log}):{logger:this.log})}createTextSource(e,r){return new yl(this,e,r?Object.assign(r,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}};p(sn,"_ids",0);var $A={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},ua=class ua extends sn{constructor(){super(...arguments);p(this,"defaultProgam");p(this,"defaultVShader");p(this,"defaultFShader");p(this,"ctx");p(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}_${sn._ids++}`),e&&(this._canvas2d=document.createElement("canvas")),this.ctx=this._canvas.getContext("webgl2",$A),!this.ctx)throw new Me({code:Te.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,VA),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,BA),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new Me({code:Te.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})}destroy(e){let r="";return e&&(r=e.message,this.error=e,Se.addFailedEvent({key:512702,error:e})),this.disconnect(),this.log.info(`video context destroy${r}`?`: ${r}`:""),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 r;(r=this.ctx)==null||r.viewport(0,0,e,this.height),super.width=e,this._canvas2d&&(this._canvas2d.width=e)}set height(e){var r;(r=this.ctx)==null||r.viewport(0,0,this.width,e),super.height=e,this._canvas2d&&(this._canvas2d.height=e)}setSize(e,r){var o;(o=this.ctx)==null||o.viewport(0,0,e,r),super.setSize(e,r),this._canvas2d&&(this._canvas2d.width=e,this._canvas2d.height=r)}createShader(e,r){let o=this.ctx,s=o.createShader(e);return o.shaderSource(s,r),o.compileShader(s),s}createProgram(e,r){let o=this.ctx,s=o.createProgram();return o.attachShader(s,e),o.attachShader(s,r),o.linkProgram(s),o.getProgramParameter(s,o.LINK_STATUS)||this.log.error(o.getProgramInfoLog(s)),s}};p(ua,"UNAVAILABLE","unavailable"),Ie([Mt(Ve.INIT,"created",{sync:!0,fail(e){this.log.error("video gl context create failed",e.cause),Se.addFailedEvent({key:512700,error:e.cause||e})},success(){this.log.info("video context created use webgl"),Se.addSuccessEvent({key:512700})}})],ua.prototype,"create",1),Ie([Mt("created",Ve.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(ua.UNAVAILABLE,e),this.removeAllListeners()}})],ua.prototype,"destroy",1);var cr=ua,mr=class extends sn{constructor(){super(...arguments);p(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${sn._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:e.alpha,willReadFrequently:e.willReadFrequently}),!this.ctx)throw new Me({code:Te.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 r="";e&&(r=e.message,this.error=e,Se.addFailedEvent({key:512703,error:e})),this.disconnect(),this.log.info(`video context destroy ${r?`: ${r}`:""}`),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners(),Se.addSuccessEvent({key:512703})}};Ie([Mt(Ve.INIT,"created",{sync:!0,fail(e){this.log.error("video 2d context create failed",e.cause),Se.addFailedEvent({key:512701,error:e.cause||e})},success(){this.log.info("video context created use 2d"),Se.addSuccessEvent({key:512701})}})],mr.prototype,"create",1),Ie([Mt("created",Ve.INIT,{ignoreError:!0,sync:!0})],mr.prototype,"destroy",1);function FA(i,t,e,r,o,s=!1){s&&([e,r]=[r,e]);let n={sWidth:i,sHeight:t,dWidth:e,dHeight:r,sx:0,sy:0,dx:0,dy:0};if(i===0||t===0)return n;switch(o){case void 0:case"fill":break;case"contain":{let a=Math.min(e/i,r/t);n.dWidth=i*a,n.dHeight=t*a,n.dx=(e-n.dWidth)/2,n.dy=(r-n.dHeight)/2;break}case"cover":{let a=Math.max(e/i,r/t),c=e/a,d=r/a;n.sx=(i-c)/2,n.sy=(t-d)/2,n.sWidth=c,n.sHeight=d;break}}return n}var hf=class{constructor(t,e){this.node=t;this.layout=e;p(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}},la=class extends or{constructor(e,r){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:r});p(this,"inputs",[]);p(this,"backgroundColor","black")}addInput(e,r){let o=0,s=this.inputs.length;for(;o<s;){let a=Math.floor((o+s)/2);if(this.inputs[a].layout.zIndex<r.zIndex)o=a+1;else if(this.inputs[a].layout.zIndex>r.zIndex)s=a;else throw new Error(`input already exists at zIndex ${r.zIndex}`)}let n=new hf(e,r);this.inputs.splice(o,0,n)}changeInputLayout(e,r){let o=this.inputs.findIndex(T=>T.node===e);if(o<0)return;let{x:s,y:n,width:a,height:c,zIndex:d,fillMode:m,rotation:l,hidden:f}=r;if(!z(d)&&this.inputs.some(T=>T.layout.zIndex===d&&T.node!==e))throw new Error(`input already exists at zIndex ${r.zIndex}`);let g=this.inputs[o];z(s)||(g.layout.x=s),z(n)||(g.layout.y=n),z(a)||(g.layout.width=a),z(c)||(g.layout.height=c),z(l)||(g.layout.rotation=l),z(f)||(g.layout.hidden=f),m&&(g.layout.fillMode=m),!z(d)&&d!==g.layout.zIndex&&(g.layout.zIndex=d,this.inputs.sort((T,E)=>T.layout.zIndex-E.layout.zIndex))}hasInput(e){return this.inputs.some(r=>r.node===e)}hasNoInput(){return this.inputs.length===0}resize(e,r){if(!this.matchInputSize){super.resize(e,r);return}let o=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(o.width,o.height),this.context instanceof cr&&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,...r){return super.connect(e,...r),this.drawBackGround2d(this.backgroundColor),this.matchInputSize&&this.resize(0,0),e}removeInput(e){this.inputs=this.inputs.filter(r=>r.node!==e),this.inputs.length===0&&this.drawBackGround2d(this.backgroundColor)}render(e){let r=this.context.ctx;if(r.clearColor(0,0,0,0),this.inputs.reduce((s,n)=>n.node.requestFrame(e)||s,!1)&&r){this.useProgram(),r.enable(r.BLEND),r.blendFunc(r.SRC_ALPHA,r.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(r=>r.node.requestFrame(e)),this.ctx2d){this.drawBackGround2d(this.backgroundColor);for(let r=0;r<this.inputs.length;r++){let o=this.inputs[r];if(o.hidden)continue;let s=FA(o.node.width,o.node.height,o.width,o.height,o.fillMode,Jr(o.rotation));this.draw2d(o.node.image,o.x+s.dx,o.y+s.dy,s.dWidth,s.dHeight,s.sx,s.sy,s.sWidth,s.sHeight)}return!0}return!1}debugLayout(e,r,o,s,n=!1){this.ctx2d&&(n&&([o,s]=[s,o]),this.ctx2d.save(),this.ctx2d.strokeStyle="red",this.ctx2d.lineWidth=2,this.ctx2d.strokeRect(e,r,o,s),this.ctx2d.restore())}getInfo(){let{totalFrames:e,x:r,y:o,width:s,height:n,name:a}=this,c=Date.now(),d=(e-this.lastInfo.totalFrames)/((c-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:r,y:o,width:s,height:n,timestamp:c,fps:d,name:a},be({parent:this.inputs.filter(m=>m).map(m=>m.node.getInfo())},this.lastInfo)}removeAllInputs(){this.inputs.forEach(e=>{var r;if(e.node.disconnect(),e.positionBuffer&&this.context instanceof cr)try{(r=this.context.ctx)==null||r.deleteBuffer(e.positionBuffer)}catch(o){}})}close(){super.close(),this.removeAllInputs()}};var HA=[1,0,0,0,1,1,0,1],ui=class extends or{constructor(e,r,o,s){super(e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"transform",logger:r});p(this,"mirror",!1);p(this,"rotation",0);if(o&&(this.mirror=o),s&&(this.rotation=s),e instanceof cr)try{this.setTexBuffer(HA)}catch(n){e.destroy(new Me({code:Te.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${n.message||n}`}))}}draw2d(e,r,o,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,r,o,s,n);return this.ctx2d.restore(),a}return!1}render(e){var r;return(r=this.input)!=null&&r.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}resize(e,r){Jr(this.rotation)&&([e,r]=[r,e]),super.resize(e,r)}};var nn=class extends wi{constructor(e,r=4){super(r,Sr);p(this,"inputLocalVideoTracks",new Map);p(this,"inputLocalScreenTracks",new Map);p(this,"cameraNodeMap",new Map);p(this,"screenNodeMap",new Map);p(this,"textNodeMap",new Map);p(this,"imageNodeMap",new Map);p(this,"videoNodeMap",new Map);p(this,"endedIds",new Set);p(this,"videoContext");p(this,"mixNode");p(this,"destination");p(this,"manager");p(this,"stat");p(this,"_checkId",0);p(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(or.RENDER,o=>{this.emit("render",o)}),this.mixNode=new la(this.videoContext,this.log),this.mixNode.matchInputSize=!1}listenDeviceChange(){throw new Error("Method not implemented.")}enablePrintDetail(e=2e3){this._checkId=Jt.run("interval",()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:e})}create2dVideoContext(){this.videoContext?this.videoContext.destroy():this.videoContext=new mr({frameRate:15,logger:this.log,name:"mix-ctx"}),this.videoContext.create({alpha:!1})}setFps(e){this.autoSetFps=!1,this.videoContext.frameRate=e;for(let r of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])r.shouldUpdate=!1;setTimeout(()=>{var r;return(r=this.destination)==null?void 0:r.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,r=0,o=!0;for(let[n,a]of this.inputLocalVideoTracks)if(a.profile.frameRate>r){if(this.endedIds.has(n)){let c=this.cameraNodeMap.get(n);c&&c.image.cancelVideoFrameCallback(c.videoCallbackId);continue}r=a.profile.frameRate,e=n}for(let[n,a]of this.inputLocalScreenTracks)if(a.profile.frameRate>r){if(this.endedIds.has(n)){let c=this.screenNodeMap.get(n);c&&c.image.cancelVideoFrameCallback(c.videoCallbackId);continue}r=a.profile.frameRate,e=n,o=!1}if(e!==null){let n=o?this.cameraNodeMap.get(e):this.screenNodeMap.get(e);n&&(n.shouldUpdate=!0,n.tryVideoFrameCallback()),this.log.info("set mix fps: ",r)}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,r){var o;(o=this.mixNode)==null||o.resize(e,r)}startMix(){return D(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),ni&&this.player.setCanvas(this.videoContext._canvas),this.setOutputMediaStreamTrack(this.destination.videoTrack),(e=this.manager)==null||e.changeInput(this)})}addCameraSource(e,r,o){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}=r;if(!s)throw new Error("no mediaTrack, add cameraSource failed");r.recaptureMode=1,yr(this,$t).add("videoInputRemoved",a=>{a.deviceId===r.deviceId&&(this.endedIds.add(e),this.setFpsAuto())}),r.on("output-media-track-changed",()=>{this.endedIds.delete(e),this.updateCameraSource(e,o,r.mediaTrack)});let n;Tr===16&&s instanceof CanvasCaptureMediaStreamTrack?n=this.videoContext.createVideoImageSource(s.canvas,{name:"cameraCanvasSource",logger:this.log}):n=this.videoContext.createVideoTrackSource(s,"cameraNodeSource"),n.resize(r.settings.width,r.settings.height),n.shouldUpdate=!1,this._connectMix(n,o,"cover"),this.inputLocalVideoTracks.set(e,r),this.cameraNodeMap.set(e,n),this.setFpsAuto()}addScreenSource(e,r,o){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}=r;if(!s)throw new Error("no mediaTrack, add cameraSource failed");let n=this.videoContext.createVideoTrackSource(s,"screenNodeSource");n.resize(r.settings.width,r.settings.height),n.shouldUpdate=!1,this._connectMix(n,o),this.inputLocalScreenTracks.set(e,r),this.screenNodeMap.set(e,n),this.setFpsAuto()}addTextSource(e){let{id:r,content:o="",font:s,color:n,layout:a}=e;if(this.textNodeMap.has(r))throw new Error(`There is already a textSource with the same ID: ${r}`);let c=this.videoContext.createTextSource({content:o,font:s,color:n});c.resize(a.width,a.height),this._connectMix(c,a),this.textNodeMap.set(r,c)}addImageSource(e,r,o){if(this.imageNodeMap.has(e))throw new Error(`There is already a imageSource with the same ID: ${e}`);let s=this.videoContext.createVideoImageSource(r,{autoResize:!1,logger:this.log});s.resize(r.width,r.height),this._connectMix(s,o),this.imageNodeMap.set(e,s)}addVideoSource(e,r,o){if(this.videoNodeMap.has(e))throw new Error(`There is already a videoSource with the same ID: ${e}`);let s=this.videoContext.createVideoImageSource(r,{autoResize:!1,logger:this.log});s.resize(r.videoWidth,r.videoHeight),s.shouldUpdate=!1,this._connectMix(s,o),this.videoNodeMap.set(e,s)}updateCameraSource(e,r,o=null,s){let n=this.cameraNodeMap.get(e);if(n){if(o){if(Tr===16&&o instanceof CanvasCaptureMediaStreamTrack)if(n instanceof di){let d=n.output;n.close(),n=this.videoContext.createVideoImageSource(o.canvas,{name:"cameraCanvasSource",logger:this.log}),n.connect(d),this.cameraNodeMap.set(e,n)}else n.image=o.canvas;else if(n instanceof di)n.replaceTrack(o);else{let d=n.output;n.close(),n=this.videoContext.createVideoTrackSource(o,"cameraNodeSource"),n.connect(d),this.cameraNodeMap.set(e,n)}let{width:a,height:c}=o.getSettings();a&&c&&n.resize(a,c)}s&&n.resize(s.width,s.height),(s||o)&&this.setFpsAuto(),this._changeMixLayout(n,r)}}updateScreenSource(e,r){let o=this.screenNodeMap.get(e);o&&this._changeMixLayout(o,r)}updateTextSource(e){let{id:r,content:o,font:s,color:n,layout:a}=e,c=this.textNodeMap.get(r);c&&(z(o)||(c.content=o),z(s)||(c.font=s),z(n)||(c.color=n),c.resize(a.width,a.height),this._changeMixLayout(c,a))}updateImageSource(e,r,o){let s=this.imageNodeMap.get(e);s&&(o&&(s.image=o,s.resize(o.width,o.height)),this._changeMixLayout(s,r))}updateVideoSource(e,r,o){let s=this.videoNodeMap.get(e);if(s){if(o){let n=s.image;n instanceof HTMLVideoElement&&this.stopVideoElement(n),s.image=o,s.resize(o.videoWidth,o.videoHeight)}this._changeMixLayout(s,r)}}_connectMix(e,r,o="contain"){if(!this.mixNode)return;let{mirror:s,rotation:n}=r;e.disconnect();let a=new ui(this.videoContext,this.log,s,n);a=e.connect(a),r.fillMode||(r.fillMode=o),a.connect(this.mixNode,r)}_changeMixLayout(e,r){if(!this.mixNode)return;let{mirror:o,rotation:s}=r,n=e.output||e;n instanceof ui&&(z(o)||(n.mirror=o),z(s)||(n.rotation=s),n.resize(e.width,e.height)),this.mixNode.changeInputLayout(n,r)}removeCameraSource(e){let r=this.inputLocalVideoTracks.get(e);if(!r)return;r.close(),this.inputLocalVideoTracks.delete(e);let o=this.cameraNodeMap.get(e);o&&(o.output instanceof ui&&o.output.close(),o.close(),this.cameraNodeMap.delete(e)),this.checkAfterRemove(!0)}removeScreenSource(e){let r=this.inputLocalScreenTracks.get(e);if(!r)return;r.close(),this.inputLocalScreenTracks.delete(e);let o=this.screenNodeMap.get(e);o&&(o.output instanceof ui&&o.output.close(),o.close(),this.screenNodeMap.delete(e)),this.checkAfterRemove(!0)}removeTextSource(e){let r=this.textNodeMap.get(e);r&&(r.output instanceof ui&&r.output.close(),r.close(),this.textNodeMap.delete(e)),this.checkAfterRemove()}removeImageSource(e){let r=this.imageNodeMap.get(e);r&&(r.output instanceof ui&&r.output.close(),r.close(),this.imageNodeMap.delete(e)),this.checkAfterRemove()}removeVideoSource(e){let r=this.videoNodeMap.get(e);r&&(r.output instanceof ui&&r.output.close(),r.image instanceof HTMLVideoElement&&this.stopVideoElement(r.image),r.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(),Jt.clearTask(this._checkId),(e=this.videoContext)==null||e.destroy(),delete this.mixNode,delete this.destination;for(let r of[...this.inputLocalVideoTracks.values(),...this.inputLocalScreenTracks.values()])r.close();this.inputLocalVideoTracks.clear(),this.inputLocalScreenTracks.clear(),this.cameraNodeMap.clear(),this.screenNodeMap.clear(),this.textNodeMap.clear(),this.imageNodeMap.clear(),tr(this);for(let r of this.videoNodeMap.values())r.image instanceof HTMLVideoElement&&this.stopVideoElement(r.image);this.videoNodeMap.clear(),this.log.info("localMixVideoTrack close, stop mix")}};var Sl=oc();if(typeof navigator!="undefined"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:Sl,exposeOrigin:!0,permittedOrigins:["*"]})}catch(i){}var WA=function(i){return D(this,null,function*(){let t=null,e=jA(i);se.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let r=yield navigator.mediaDevices.getDisplayMedia(e);i.systemAudio&&r.getAudioTracks().length===0&&(Xn&&Fr<74||Zt||zt)&&se.warn("Your browser not support capture system audio");let o=r.getVideoTracks()[0];if(o){if(i.frameRate)try{yield o.applyConstraints({frameRate:{min:i.frameRate,ideal:i.frameRate},width:i.width,height:i.height})}catch(s){se.warn(`screen applyConstraints failed: ${s}`)}i.captureElement&&(yield GA(o,i.captureElement))}if(i.audio){let s=zA(i);se.info(`getUserMedia with constraints: ${JSON.stringify(s)}`),t=yield navigator.mediaDevices.getUserMedia(s),r.addTrack(t.getAudioTracks()[0])}return r})};function GA(i,t){return D(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&Rt(i.cropTo))try{if(!(((e=i.getCaptureHandle())==null?void 0:e.handle)===Sl))return;let o=yield CropTarget.fromElement(t);yield i.cropTo(o)}catch(r){se.warn(`cropTo target failed ${r}`)}})}function zA(i){let t={echoCancellation:i.echoCancellation,autoGainControl:i.autoGainControl,noiseSuppression:i.noiseSuppression,sampleRate:i.sampleRate,channelCount:i.channelCount};return z(i.microphoneId)||(t.deviceId=i.microphoneId),{audio:t,video:!1}}function jA(i){let t={preferCurrentTab:i.preferDisplaySurface==="current-tab"||!!i.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:Zt?{max:i.width}:{ideal:i.width,max:i.width},height:Zt?{max:i.height}:{ideal:i.height,max:i.height},frameRate:i.frameRate,displaySurface:i.preferDisplaySurface||"monitor"};if(t.video=e,i.systemAudio){let{echoCancellation:r=!0,noiseSuppression:o=!1,autoGainControl:s=!1}=i;t.audio={echoCancellation:r,noiseSuppression:o,autoGainControl:s,sampleRate:48e3}}return t}var WE=WA;var zi=class extends Zr{constructor(e){super(e,2);p(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600});p(this,"objectFit","contain");p(this,"isScreen",!0);this._log.id=`s-${this._log.id}`}get isShareCurrentTab(){var e,r;try{return Sl===((r=(e=this.mediaTrack)==null?void 0:e.getCaptureHandle())==null?void 0:r.handle)}catch(o){return}}capture(m){return D(this,arguments,function*({systemAudio:e=!1,autoGainControl:r,echoCancellation:o,noiseSuppression:s,audioTrack:n,videoTrack:a,captureElement:c,preferDisplaySurface:d}){try{let l;return a||n?(l=new MediaStream,a&&l.addTrack(a),n&&l.addTrack(n)):(l=yield WE({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:r,echoCancellation:o,noiseSuppression:s,captureElement:c,preferDisplaySurface:d}),this.sourceTrack=l.getVideoTracks()[0]),yield this.setInputMediaStreamTrack(l.getVideoTracks()[0]),l}catch(l){throw this.log.error(`getDisplayMedia error observed ${l}`),l instanceof Me?l:new Me({code:Te.INITIALIZE_FAILED,name:l.name,message:l.message})}})}switchDevice(e){return D(this,null,function*(){throw new Error("Method not implemented.")})}};Ie([Ko(function(e){this.setContentHint(e.contentHint||"detail")})],zi.prototype,"capture",1);var an=class extends Gi{constructor(t){super(t),this._log.id=`s-${this._log.id}`,this.isScreen=!0}addAudioProcessor(t,e,r){this.pipeline.silentNode.setNode(r),this.pipeline.mixNode.setNode(e),this.pipeline.aec.setNode(t),this.enableTrackAEC(!1)}removeAudioProcessor(t){this.pipeline.aec.node===t&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode(),this.enableTrackAEC(!0))}};var qA='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}});',mf;function Vc(i,t=48e3,e=1,r){return D(this,null,function*(){let o=bt("dump");mf||(mf=yo(o,URL.createObjectURL(new Blob([qA],{type:"application/javascript"})))),yield mf;let s=o.sampleRate,n=new AudioWorkletNode(o,"dumper",{numberOfInputs:i.length,numberOfOutputs:0,processorOptions:{sourceSampleRate:s,targetSampleRate:t}});return n.channelCountMode="explicit",n.channelCount=e,r&&n.port.postMessage({port:r},[r]),i.forEach((a,c)=>a.connect(n,0,c)),new ReadableStream({start(a){n.port.onmessage=c=>{a.enqueue(c.data)}},cancel(){i.forEach(a=>a.disconnect(n)),n.port.close()}})})}var Il=class extends qu{constructor(e){super();this.room=e;p(this,"_localAudioTrack");p(this,"_localScreenAudioTrack");p(this,"log");p(this,"denoiser");p(this,"voiceChanger");p(this,"mixChangedDebounce");p(this,"audioProcessor");p(this,"encodePipeline",[]);p(this,"decodePipeline",[]);p(this,"getPCMAbortCtrlMap",new Map);p(this,"audioFrameEventConfigMap",new Map);p(this,"audioReferenceMap",new Map);p(this,"isLocalAudioNeedAudioProcess",!1);p(this,"isScreenAudioNeedAudioProcess",!1);this.log=se.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 m,l;if(!this._localAudioTrack)return;let r=[],o=[];(m=this._localAudioPipline)!=null&&m.source.node&&(r.push(this._localAudioPipline.source.node),o.push("mic")),(l=this._localAudioPipline)!=null&&l.denoiser.node&&(r.push(this._localAudioPipline.denoiser.node),o.push("mic-processed")),this.mixWeight>1&&(r.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),o.push("mix")),this.log.info(`dump audio track ${o}, 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 f=0;f<o.length;f++){let g=URL.createObjectURL(new Blob(n[f])),T=document.createElement("a");T.href=g,T.download=`${o[f]}.pcm`,T.style.display="none",document.body.appendChild(T),T.click(),URL.revokeObjectURL(g),T.remove()}clearTimeout(a),s.abort("download")},d=Vc(r).then(f=>f.pipeTo(new WritableStream({write(g){g.forEach((T,E)=>n[E]=n[E]?n[E].concat(T[0]):[T[0]])}}),s).catch(g=>c));return{then:d.then.bind(d),download:c}}getPCM(e,r){var v,M,w;if(typeof WritableStream=="undefined"){this.log.warn("getPCM failed: browser not support WritableStream");return}let{enable:o,sampleRate:s=48e3,channelCount:n=1,port:a}=(r===""?this.audioFrameEventConfigMap.get(""):this.audioFrameEventConfigMap.get(r)||this.audioFrameEventConfigMap.get("*"))||{};if(!o)return;this.log.info(`getPCM ${r||"local"}`);let c=Math.floor(s*.04),d=new Float32Array(c),m=new Float32Array(c),l,f,g=0,T=new AbortController,E=r===""?(v=this._localAudioTrack)==null?void 0:v.mediaTrack:(w=(M=this.room)==null?void 0:M.remotePublishedUserMap.get(r))==null?void 0:w.remoteAudioTrack.mediaTrack;if(!E){this.log.info(`getPCM failed: ${r||"local"} has no audio track`);return}let y=bt().createMediaStreamSource(new MediaStream([E]));return Vc([y],s,n,a).then(H=>H.pipeTo(new WritableStream({write(B){B[0][0]&&(g+B[0][0].length>c?(d.set(B[0][0].subarray(0,c-g),g),l=B[0][0].subarray(c-g),B[0][1]&&(m.set(B[0][1].subarray(0,c-g),g),f=B[0][1].subarray(c-g)),g+=c-g):(l&&(d.set(l,g),g+=l.length,l=void 0),f&&(m.set(f,g),f=void 0),d.set(B[0][0],g),B[0][1]&&m.set(B[0][1],g),g+=B[0][0].length),g>=c&&(g=0,e({userId:r,sampleRate:s,channelCount:n,data:n===1?d:[d,m]}),d=new Float32Array(c),m=new Float32Array(c)))}}),T).catch(B=>this.log.warn(`stop getPCM reason:${B}`))),T}get hasScreenAudioTrack(){return!z(this._localScreenAudioTrack)}get hasAudioTrack(){return!z(this._localAudioTrack)}changeInput(e){var r,o;if(e instanceof an)return this._localScreenAudioTrack=e,this.isScreenAudioNeedAudioProcess&&((r=this.audioProcessor)!=null&&r.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 Gi)return this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),this.isLocalAudioNeedAudioProcess&&((o=this.audioProcessor)!=null&&o.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 bo)return e.setOutputMediaStreamTrack(e.mediaTrack)}mixAudioReference(e,r){var o;(o=this._localAudioTrack)==null||o.mixAudioReference(e,r)}unMixAudioReference(e){var r;(r=this._localAudioTrack)==null||r.unMixAudioReference(e)}setAudioReferenceVolume(e,r){var o;(o=this._localAudioTrack)==null||o.setAudioReferenceVolume(e,r)}mixOnChange(){return this.mixChangedDebounce||(this.mixChangedDebounce=Promise.resolve().then(()=>{var e,r;return delete this.mixChangedDebounce,Promise.all([(e=this._localAudioTrack)==null?void 0:e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),(r=this._localScreenAudioTrack)==null?void 0:r.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)])})),this.mixChangedDebounce}removeInput(e){e instanceof an?delete this._localScreenAudioTrack:e instanceof Gi?delete this._localAudioTrack:e instanceof bo}addDenoiser(e){var r;this.denoiser=e,(r=this._localAudioTrack)==null||r.addDenoiser(e)}addAudioProcessor(e,r,o,s){var n;this.audioProcessor={localAudioWorkletNode:o,mixNode:e,silentNode:r,screenAudioWorkletNode:s},this.isLocalAudioNeedAudioProcess&&this._localAudioTrack&&o&&(this._localAudioTrack.addAudioProcessor(o,e,r),this.audioReferenceMap.forEach((a,c)=>{var d;(d=this._localAudioTrack)==null||d.mixAudioReference(a,c)})),this.isScreenAudioNeedAudioProcess&&this._localScreenAudioTrack&&s&&((n=this._localScreenAudioTrack)==null||n.addAudioProcessor(s,e,r),this.audioReferenceMap.forEach((a,c)=>{var d;(d=this._localScreenAudioTrack)==null||d.mixAudioReference(a,c)}))}removeDenoiser(e){var r;return delete this.denoiser,(r=this._localAudioTrack)==null?void 0:r.removeDenoiser(e)}addVoiceChanger(e,r){var o;this.voiceChanger=[e,r],(o=this._localAudioTrack)==null||o.pipeline.voiceChanger.setNode(e,r)}removeVoiceChanger(){var e;delete this.voiceChanger,(e=this._localAudioTrack)==null||e.pipeline.voiceChanger.deleteNode()}removeAudioProcessor(e,r){var o,s;delete this.audioProcessor,(o=this._localAudioTrack)==null||o.removeAudioProcessor(e),(s=this._localScreenAudioTrack)==null||s.removeAudioProcessor(r)}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:r}){var o;this.encodePipeline.includes(e)||(this.encodePipeline[r]=e,(o=this.room)==null||o.enableInsertableStreams())}addDecodeProcessor({processor:e,type:r}){var o;this.decodePipeline.includes(e)||(this.decodePipeline[r]=e,(o=this.room)==null||o.enableInsertableStreams())}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}handleLocalTrackStarted({room:e,userId:r}){var s;if(e!==this.room||this.getPCMAbortCtrlMap.get(r))return;let o=this.getPCM(n=>{var a;(a=this.room)==null||a.emit("audio-frame",n)},"");this.getPCMAbortCtrlMap.set(r,o),this.getPCMAbortCtrlMap.get(r)&&((s=this._localAudioTrack)==null||s.on("input-media-track-changed",()=>{let n=this.getPCMAbortCtrlMap.get(r);n&&(n.abort("inputMediaTrackChanged"),n=this.getPCM(a=>{var c;(c=this.room)==null||c.emit("audio-frame",a)},""),this.getPCMAbortCtrlMap.set(r,n))}))}handleLocalTrackStopped({room:e,userId:r}){if(e!==this.room)return;let o=this.getPCMAbortCtrlMap.get(r);o&&(o.abort("stopLocalAudio"),this.getPCMAbortCtrlMap.delete(r))}handleRemoteTrackStarted({room:e,userId:r}){if(e===this.room&&!this.getPCMAbortCtrlMap.get(r)){let o=this.room.audioManager.getPCM(s=>{var n;(n=this.room)==null||n.emit("audio-frame",s)},r);this.getPCMAbortCtrlMap.set(r,o)}}handleRemoteTrackStopped({room:e,userId:r}){if(e!==this.room)return;let o=this.getPCMAbortCtrlMap.get(r);o&&(o.abort("stopRemoteAudio"),this.getPCMAbortCtrlMap.delete(r))}installEvent(){ee.on("113",this.handleLocalTrackStarted,this),ee.on("114",this.handleLocalTrackStopped,this),ee.on("115",this.handleRemoteTrackStarted,this),ee.on("116",this.handleRemoteTrackStopped,this)}uninstallEvent(){ee.off("113",this.handleLocalTrackStarted),ee.off("114",this.handleLocalTrackStopped),ee.off("115",this.handleRemoteTrackStarted),ee.off("116",this.handleRemoteTrackStopped)}updateAudioReference({type:e,audioReference:r,refId:o,volume:s}){if(e==="add"){if(this.audioReferenceMap.get(o)||!r||(this.audioReferenceMap.set(o,r),!this.audioProcessor))return;this.mixAudioReference(r,o)}else if(e==="remove")this.audioReferenceMap.get(o)&&(this.audioReferenceMap.delete(o),this.unMixAudioReference(o));else if(e==="updateVolume"){if(!this.audioProcessor||z(s))return;this.setAudioReferenceVolume(o,s)}}};function GE(i=30,t=2){return ut((e,r)=>function(...o){return new Promise((s,n)=>{let a=setTimeout(()=>{let c=new Me({code:Te.API_CALL_TIMEOUT,message:`checkPendingPromise ${r}() timeout ${i}s`});(this.log||this._log||se).warn(c),t===2?n(c):t===1&&s()},i*1e3);this._checkPendingPromiseSet||(this._checkPendingPromiseSet=new Set),this._checkPendingPromiseSet.add(a),e.apply(this,o).then(s,n).finally(()=>{clearTimeout(a),this._checkPendingPromiseSet&&a&&this._checkPendingPromiseSet.delete(a)})})})}var ji=class ji extends Xs{constructor(e,r,o){super({userId:r.userId,sdkAppId:e.sdkAppId,mediaType:o,room:e});this.room=e;this.user=r;p(this,"tinyId");p(this,"isRemote",!0);p(this,"jitterBufferDelay",0);p(this,"availableState");p(this,"remotePublishState");p(this,"_triggerCheckDecodeSubject",ir(Qe(this,ji.STATE_SUBSCRIBE)));this.tinyId=r.tinyId,this.availableState=new Ve(`${r.userId}-${this.mediaType}-available`,"remote-track-available"),this.remotePublishState=new Ve(`${r.userId}-${this.mediaType}-remote-publish`,"remote-track-publish"),Ye(Oc(Qe(this,Ve.STATECHANGED),Qe(this.remotePublishState,Ve.STATECHANGED)),ts(()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing)),lt(c=>{this.availableState.state!==(c?Ve.ON:Ve.OFF)&&(this.availableState.state=c?Ve.ON:Ve.OFF),this.updatePlayingState(c)}));let s=Ye(Qe(this.player,St.ERROR),Ur(c=>c.code===MediaError.MEDIA_ERR_DECODE)),n=Ye(xc(5e3),Ur(()=>this.ignoreDecodeError||!this.isSubscribed||!this.isPlayCalled||!this.stat.bytesReceived?!1:this.player.isPlaying||(this.kind===j.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)?(this.reportDecodeResult(!0),!1):!0)),a=Ye(Ap(s,n),At(Qe(this,Ve.INIT)));Ye(this._triggerCheckDecodeSubject,Ur(()=>!this.ignoreDecodeError),Io(a),lt(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 r,o;return(((o=(r=this.room)==null?void 0:r.networkQuality)==null?void 0:o.downlinkNetworkQuality)||0)>3||this.player.isInAutoPlayFailedState}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===ji.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===Ve.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,r){var s,n;let o=this.kind===j.AUDIO;if(Se[e?"addSuccessEvent":"addFailedEvent"]({key:o?504700:514702}),!o){let a=((s=this.room)==null?void 0:s.downlinkVideoCodec.toUpperCase())||"H264";Se[e?"addSuccessEvent":"addFailedEvent"]({key:Kn[`DECODE_${a}_RESULT`]}),e||this.log.warn(`${(n=this.room)==null?void 0:n.downlinkVideoCodec} decode failed`)}e||(Se.addEnum({key:o?504701:514703,value:Bs()}),It.uploadEvent({log:`stat-decode-failed-${this.kind}-${Vs()||ho()}`,userId:this.room.userId}),this._log.warn(`decode failed: isPlaying: ${this.player.isPlaying} ${this.kind===j.AUDIO?`audioLevel: ${this.getAudioLevel()}`:`framesDecoded: ${this.stat.framesDecoded>0}`}`),this.emit("decode-failed",{error:r}))}updatePlayingState(e){if(this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.isRemotePublished||!this.outMediaTrack)){this.log.info(`abort play, isSubscribed: ${this.isSubscribed} isAvailable: ${this.isRemotePublished} hasTrack: ${!!this.outMediaTrack} `);return}super.updatePlayingState(e)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.remotePublishState.state=this.isRemotePublished?Ve.ON:Ve.OFF,this.emit("remote-publish-changed",this.isRemotePublished)}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};p(ji,"STATE_SUBSCRIBE","subscribe"),Ie([GE(5,1)],ji.prototype,"waitHasMediaTrack",1),Ie([Mt(Ve.INIT,ji.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),ee.emit(ce.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),rl(521716,!1)],ji.prototype,"subscribe",1),Ie([Mt(ji.STATE_SUBSCRIBE,Ve.INIT,{sync:!0,success(){this.log.info("unsubscribed"),ee.emit(ce.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],ji.prototype,"unsubscribe",1);var ha=ji;var bo=class extends ha{constructor(e,r){super(e,r,1);p(this,"volume",0);p(this,"mediaType",1);p(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.audioManager}get dbVolume(){return Ju.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,r;return this.manager?this.manager.decodePipeline.some(o=>o)||((r=(e=this.player.element)==null?void 0:e.error)==null?void 0:r.code)===MediaError.MEDIA_ERR_DECODE&&Fu().AudioDecoder&&zs:!1}get enableDecryptFrame(){return this.manager&&!!this.manager.decodePipeline[0]}decodeFrame(e){if(!this.manager)return e;let r=e;for(let[o,s]of this.manager.decodePipeline.entries()){if(!s)continue;let n={frame:e,track:this};if(o===1&&this.isAvailable&&this.room.role==="audience"&&(n.onAudioFrameNTPTime=({ntp:a,frame:c,hasLeavingTag:d})=>{this.emit("audio-frame-with-ntp",{ntp:a,frame:c,hasLeavingTag:d})}),r=s(n),!r)return}return r}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get isRemotePublished(){return this.user.muteState.audioAvailable}};var bl=class extends or{constructor(e,r,o,s,n){super(e,{useDefaultProgram:!0,useFbo:!0,name:"alpha",create2d:!0,logger:r});this.setContainer=s;p(this,"initStat",{alphaStitchingType:1});p(this,"end",ir());p(this,"minSize",320);p(this,"maxSize",1280);p(this,"draggable",!1);p(this,"startDragX",0);p(this,"startDragY",0);p(this,"left",0);p(this,"top",0);p(this,"baseWidth",320);p(this,"baseRatio");p(this,"container");this.initStat=n,this.draggable=o,this.bindDragEvents()}bindDragEvents(){let e=this.context._canvas;if(e)if(this.draggable){let r=At(this.end);Ye(Qe(e,"mousedown"),en(this.startDrag.bind(this)),Wi(()=>Ye(Qe(window,"mousemove"),At(Qe(window,"mouseup")))),r,lt(this.doDrag.bind(this))),Ye(Qe(e,"dblclick"),r,lt(this.resetPosition.bind(this))),Ye(Qe(e,"wheel"),r,lt(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 r;return(r=this.input)!=null&&r.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 r=.1,o=e.deltaY,s=this.context._canvas;s&&(this.baseWidth||(this.baseWidth=s.offsetWidth),o<0?this.baseWidth=Math.min(this.baseWidth*(1+r),this.maxSize):this.baseWidth=Math.max(this.baseWidth*(1-r),this.minSize),this.renderCanvas())}resetPosition(){this.left=0,this.top=0,this.renderCanvas()}onRatioReset(){this.renderCanvas()}draw2d(e,r,o,s,n){var g;let{ctx2d:a}=this,c=this.context._canvas;if(!a||!c)return!1;let d=super.draw2d(e,r,o,s,n),m=a.getImageData(0,0,s,n),{data:l}=m,f=!1;if(this.initStat.alphaStitchingType===1){let T=Math.floor(s/2);for(let E=0;E<n;E++)for(let y=0;y<T;y++){let v=(E*s+y)*4,M=y+T,w=(E*s+M)*4,H=l[w];l[w+3]=0;let B=H>=100;l[v+3]=B?255:0}f=super.draw2d(m,0,0,0,0,T,n),c.width=T}else if(this.initStat.alphaStitchingType===2){let T=Math.floor(n/2);for(let E=0;E<T;E++)for(let y=0;y<s;y++){let v=(E*s+y)*4,w=((E+T)*s+y)*4,H=l[w];l[w+3]=0;let B=H>=100;l[v+3]=B?255:0}f=super.draw2d(m,0,0,0,0,s,T),c.height=T}return(g=this.context.ctx)==null||g.clearRect(0,0,s,n),d&&f}close(){this.baseRatio=void 0,this.end.next(),this.end.complete()}};function JA(i){return[15,30,45,60].reduce((e,r)=>Math.abs(r-i)<Math.abs(e-i)?r:e)}var qi=class extends ha{constructor(e,r,o=4){super(e,r,o);p(this,"mediaType",4);p(this,"source");p(this,"shouldRenderAlpha",!1);p(this,"alphaNode");p(this,"shouldBeDraggable",!0);p(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.videoManager,this.once("first-video-frame",s=>{this.room.emit("first-video-frame",s)})}isAlphaSei(e){if(this.userId!==e.userId||e.seiPayloadType!==50)return!1;let r=new Uint8Array(e.data);return r.length%3!==0||r[0]!==0||r[1]!==1?!1:r}play(e,r){return(Nt(r==null?void 0:r.canvasRender)?r.canvasRender:Tr===17)&&!this.source&&this.useCanvasPlayer(),super.play(e,r).then(()=>{this.player.calculateStat(),ee.emit("156",{track:this,player:this.player})})}updateAlphaRenderInfo(e){let r=this.isAlphaSei(e);if(r)if(!this.alphaNode)this.shouldRenderAlpha=!0,this.player.shouldRenderAlpha=!0,this.useCanvasPlayer(r[2]);else{let o=r[2];if(this.alphaNode.baseRatio&&this.alphaNode.initStat.alphaStitchingType===o)return;this.alphaNode.initStat={alphaStitchingType:o};let s=this.player.getElement();if(s){let n=s.videoWidth/s.videoHeight;n&&(this.alphaNode.baseRatio=n*(o===1?.5:2),this.alphaNode.onRatioReset())}this.player.canvas&&(this.player.canvas.id=this.generateAlphaCanvasName(o))}}generateAlphaCanvasName(e){let r="alpha",o=lc[e];return`${r}_${o}_${this.userId}`}useCanvasPlayer(e){if(this.log.info(`useCanvasPlayer(), has element:${!!this.player.element}`),!this.player.element)return;let r=new mr({frameRate:15,logger:this.log,name:this.shouldRenderAlpha&&e?this.generateAlphaCanvasName(e):this.userId});r.create({alpha:this.shouldRenderAlpha,willReadFrequently:this.shouldRenderAlpha});let o=new on(r,{name:"remotePlayer",logger:this.log});if(this.source=r.createVideoPlayerSource(this.player),this.player.setCanvas(r._canvas),this.shouldRenderAlpha&&e){let s=()=>{!this.player.container||!this.alphaNode||(this.alphaNode.container=this.player.container,this.alphaNode.renderCanvas())},n=new bl(r,this.log,this.shouldBeDraggable,s,{alphaStitchingType:e});this.source.connect(n),n.connect(o),this.alphaNode=n}else this.source.connect(o);Ri()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,r),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let r=this.decodeFPS,o=JA(r);if(!ft(r)||r<=0){this.log.debug(`updateCanvasPlayerFPS() ignore decoder: ${r} `);return}if(o===e.frameRate){this.log.debug(`updateCanvasPlayerFPS() ignore ClosestFPS ${o} == ${e.frameRate}`);return}this.log.info(`updateCanvasPlayerFPS() decoder: ${r}, closest: ${o}, current: ${e.frameRate}`),e.frameRate=o}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))||{},r=this.mediaType===2?7:this.isSmall?3:2;if(!e||e.length===0)return 0;let o=e.find(a=>a.uint32_video_stream_type===r);return(o==null?void 0:o.uint32_video_dec_fps)||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),ee.emit("157",{track:this,player:this.player}),this.alphaNode&&this.alphaNode.close(),super.stop()}decodeFrame(e){if(!this.manager)return e;for(let r of this.manager.decodePipeline)if(r&&(e=r({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)}},Al=class extends qi{constructor(e,r){super(e,r,2);p(this,"mediaType",2);p(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}};var ma=new Map;ee.on(ce.JOIN_SUCCESS,({room:i})=>{jt(i.userId,{eventId:32788})});ee.on(ce.LEAVE_START,({room:i})=>{jt(i.userId,{eventId:32789})});ee.on(ce.LOCAL_TRACK_PUBLISHED,({track:i})=>{if(i.room){let t=32769;i.mediaType===4?t=32768:i.mediaType===2&&(t=32805),jt(i.room.userId,{eventId:t})}});ee.on(ce.LOCAL_TRACK_UNPUBLISHED,({track:i})=>{if(i.room){let t=32771;i.mediaType===4?t=32770:i.mediaType===2&&(t=32806),jt(i.room.userId,{eventId:t})}});ee.on(ce.TRACK_MUTED,({track:i})=>{i.room&&(i.kind===j.AUDIO?jt(i.room.userId,{eventId:i.isRemote?32785:32772,remoteUserId:i.isRemote?i.userId:void 0}):jt(i.room.userId,{eventId:i.isRemote?32784:32773,remoteUserId:i.isRemote?i.userId:void 0}))});ee.on(ce.TRACK_UNMUTED,({track:i})=>{i.room&&(i.kind===j.AUDIO?jt(i.room.userId,{eventId:i.isRemote?32787:32774,remoteUserId:i.isRemote?i.userId:void 0}):jt(i.room.userId,{eventId:i.isRemote?32786:32775,remoteUserId:i.isRemote?i.userId:void 0}))});ee.on(ce.REMOTE_TRACK_SUBSCRIBED,({track:i})=>{i.room&&(i.mediaType===1&&jt(i.room.userId,{eventId:32777,remoteUserId:i.userId}),i.mediaType===4&&jt(i.room.userId,{eventId:32776,remoteUserId:i.userId}),i.mediaType===8&&jt(i.room.userId,{eventId:32803,remoteUserId:i.userId}))});ee.on(ce.REMOTE_TRACK_UNSUBSCRIBED,({track:i})=>{i.room&&(i.mediaType===1&&jt(i.room.userId,{eventId:32779,remoteUserId:i.userId}),i.mediaType===4&&jt(i.room.userId,{eventId:32778,remoteUserId:i.userId}),i.mediaType===8&&jt(i.room.userId,{eventId:32804,remoteUserId:i.userId}))});ee.on(ce.SWITCH_DEVICE_SUCCESS,({track:i})=>{i.room&&jt(i.room.userId,{eventId:i.kind===j.VIDEO?32780:32781})});ee.on(ce.LOCAL_TRACK_REPLACED,({track:i})=>{i.room&&jt(i.room.userId,{eventId:i.kind===j.VIDEO?32782:32783})});ee.on(ce.SIGNAL_CONNECTION_STATE_CHANGED,({room:i,prevState:t,state:e})=>{let r;switch(e){case"CONNECTED":t==="RECONNECTING"?r=32795:r=32791;break;case"DISCONNECTED":t==="RECONNECTING"?r=32796:r=32790;break;case"RECONNECTING":r=32794;break}r&&jt(i.userId,{eventId:r})});ee.on(ce.PEER_CONNECTION_STATE_CHANGED,({room:i,prevState:t,state:e,remoteUserId:r})=>{let o=!!r,s;switch(e){case"CONNECTED":t==="RECONNECTING"?s=o?32801:32798:s=o?32793:32792;break;case"DISCONNECTED":t==="RECONNECTING"&&(s=o?32802:32799);break;case"RECONNECTING":s=o?32800:32797;break}s&&jt(i.userId,{eventId:s,remoteUserId:r})});ee.on(ce.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({implementation:i,userId:t,remoteUserId:e,codec:r,isHWCodec:o,prevImplementation:s,streamType:n})=>{let a=o?1:0;s||(a=o?3:2);let c={H264:0,H265:1,VP8:2}[r.toUpperCase()],d={eventId:4004,param1:a,param2:c,streamType:n||2};e&&(d.remoteUserId=e,d.eventId=4005),jt(t,d),Se.addEnum({key:e?514701:513701,value:a}),Se.addEnum({key:e?514700:513700,value:c})});ee.on(ce.LOCAL_TRACK_RECAPTURE,({track:i,error:t})=>{if(i.userId){let e={eventId:2003,param1:0};i.kind===j.AUDIO?(e.streamType=1,t&&(e.param1=2)):(e.streamType=i.streamType==="auxiliary"?7:2,t&&(e.param1=8)),jt(i.userId,e)}});function jt(i,t){let e=qe(be({},t),{timestamp:to()});ma.has(i)?ma.get(i).push(e):ma.set(i,[e])}function zE(i){if(ma.has(i)){let t=ma.get(i).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 ma.delete(i),t}return[]}function jE(...i){return ut((t,e)=>function(...r){return QA.call(this,i,r,e,this._name),t.apply(this,r)})}function QA(i,t,e,r){try{if(Gt(i))for(let o=0;o<i.length;o++)vl.call(this,{rule:i[o],value:t[o],key:i[o].name,fnName:e,className:r});else vl.call(this,{rule:i,value:t[0],key:i.name,fnName:e,className:r})}catch(o){throw se.error(o),o}}function vl({rule:i,value:t,key:e,fnName:r,className:o}){if(z(t)){if(i.required)throw new Me({code:Te.INVALID_PARAMETER,message:Et({key:_t.INVALID_PARAMETER_REQUIRED,data:{key:e,rule:i,fnName:r,value:t},link:{className:o,fnName:r}})});if(z(i.defaultValue))return;t=i.defaultValue}if(Array.isArray(i.type)){let a=!1;for(let c=0;c<i.type.length;c++)i.type[c]===null&&t===null&&(a=!0),Rt(i.type[c])&&t instanceof i.type[c]&&(a=!0),nt(i.type[c])&&Xt(t)===i.type[c].toLowerCase()&&(a=!0);if(!a)throw new Me({code:Te.INVALID_PARAMETER,message:Et({key:_t.INVALID_PARAMETER_TYPE,data:{key:e,rule:{type:i.type.map(c=>Os(c)?Ln(c):nt(c)?c:Xt(c))},fnName:r,value:t},link:{className:o,fnName:r}})})}else if(!z(i.type)&&Xt(t)!==i.type)throw new Me({code:Te.INVALID_PARAMETER,message:Et({key:_t.INVALID_PARAMETER_TYPE,data:{key:e,rule:i,fnName:r,value:t},link:{className:o,fnName:r}})});if(i.allowEmpty===!1){let a=ft(t)&&(t===0||Number.isNaN(t)),c=nt(t)&&t.trim()==="";if(a||c)throw new Me({code:Te.INVALID_PARAMETER,message:Et({key:_t.INVALID_PARAMETER_EMPTY,data:{key:e,rule:i,fnName:r,value:t},link:{className:o,fnName:r}})})}if(i.notLessThanZero&&ft(t)&&t<0)throw new Me({code:Te.INVALID_PARAMETER,message:Et({key:_t.CANNOT_LESS_THAN_ZERO,data:{key:e,rule:i,fnName:r,value:t},link:{className:o,fnName:r}})});if(!z(i.min)&&ft(t)&&t<i.min)throw new Me({code:Te.INVALID_PARAMETER,message:Et({key:_t.INVALID_PARAMETER_MIN,data:{key:e,rule:i,fnName:r,value:t},link:{className:o,fnName:r}})});if(!z(i.max)&&ft(t)&&t>i.max)throw new Me({code:Te.INVALID_PARAMETER,message:Et({key:_t.INVALID_PARAMETER_MAX,data:{key:e,rule:i,fnName:r,value:t},link:{className:o,fnName:r}})});if(nt(i.instanceOf)){if(!t||t._name!==i.instanceOf)throw new Me({code:Te.INVALID_PARAMETER,message:Et({key:_t.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:i,fnName:r,value:t},link:{className:o,fnName:r}})})}else if(Rt(i.instanceOf)&&!(t instanceof i.instanceOf))throw new Me({code:Te.INVALID_PARAMETER,message:Et({key:_t.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:i,fnName:r,value:t},link:{className:o,fnName:r}})});if(i.values&&!i.values.includes(t))throw new Me({code:Te.INVALID_PARAMETER,message:Et({key:_t.INVALID_PARAMETER_RANGE,data:{key:e,rule:i,fnName:r,value:t},link:{className:o,fnName:r}})});let{properties:s}=i;Nr(s)&&Xr(t)&&Object.keys(s).forEach(a=>{vl.call(this,{rule:s[a],value:t&&t[a],key:`${e}.${a}`,fnName:r,className:o})});let{arrayItem:n}=i;Nr(n)&&Gt(t)&&t.forEach((a,c)=>{vl.call(this,{rule:n,value:a,key:`${e}[${c}]`,fnName:r,className:o})}),Rt(i.validate)&&i.validate.call(this,t,e,r,o,this)}var YA=Li(mo(),1);var ZA=Object.create,Dl=Object.defineProperty,KA=Object.defineProperties,oT=Object.getOwnPropertyDescriptor,ev=Object.getOwnPropertyDescriptors,sT=Object.getOwnPropertyNames,Nl=Object.getOwnPropertySymbols,tv=Object.getPrototypeOf,wf=Object.prototype.hasOwnProperty,nT=Object.prototype.propertyIsEnumerable,yf=(i,t,e)=>t in i?Dl(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e,Hc=(i,t)=>{for(var e in t||(t={}))wf.call(t,e)&&yf(i,e,t[e]);if(Nl)for(var e of Nl(t))nT.call(t,e)&&yf(i,e,t[e]);return i},Wc=(i,t)=>KA(i,ev(t)),rv=(i,t)=>{var e={};for(var r in i)wf.call(i,r)&&t.indexOf(r)<0&&(e[r]=i[r]);if(i!=null&&Nl)for(var r of Nl(i))t.indexOf(r)<0&&nT.call(i,r)&&(e[r]=i[r]);return e},iv=(i,t)=>function(){return t||(0,i[sT(i)[0]])((t={exports:{}}).exports,t),t.exports},ov=(i,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of sT(t))wf.call(i,o)||o===e||Dl(i,o,{get:()=>t[o],enumerable:!(r=oT(t,o))||r.enumerable});return i},aT=(i,t,e)=>(e=i!=null?ZA(tv(i)):{},ov(!t&&i&&i.__esModule?e:Dl(e,"default",{value:i,enumerable:!0}),i)),Ao=(i,t,e,r)=>{for(var o,s=r>1?void 0:r?oT(t,e):t,n=i.length-1;n>=0;n--)(o=i[n])&&(s=(r?o(t,e,s):o(s))||s);return r&&s&&Dl(t,e,s),s},xt=(i,t,e)=>yf(i,typeof t!="symbol"?t+"":t,e),cT=iv({"../node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js"(i,t){"use strict";var e=Object.prototype.hasOwnProperty,r="~";function o(){}function s(d,m,l){this.fn=d,this.context=m,this.once=l||!1}function n(d,m,l,f,g){if(typeof l!="function")throw new TypeError("The listener must be a function");var T=new s(l,f||d,g),E=r?r+m:m;return d._events[E]?d._events[E].fn?d._events[E]=[d._events[E],T]:d._events[E].push(T):(d._events[E]=T,d._eventsCount++),d}function a(d,m){--d._eventsCount==0?d._events=new o:delete d._events[m]}function c(){this._events=new o,this._eventsCount=0}Object.create&&(o.prototype=Object.create(null),new o().__proto__||(r=!1)),c.prototype.eventNames=function(){var d,m,l=[];if(this._eventsCount===0)return l;for(m in d=this._events)e.call(d,m)&&l.push(r?m.slice(1):m);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(d)):l},c.prototype.listeners=function(d){var m=r?r+d:d,l=this._events[m];if(!l)return[];if(l.fn)return[l.fn];for(var f=0,g=l.length,T=new Array(g);f<g;f++)T[f]=l[f].fn;return T},c.prototype.listenerCount=function(d){var m=r?r+d:d,l=this._events[m];return l?l.fn?1:l.length:0},c.prototype.emit=function(d,m,l,f,g,T){var E=r?r+d:d;if(!this._events[E])return!1;var y,v,M=this._events[E],w=arguments.length;if(M.fn){switch(M.once&&this.removeListener(d,M.fn,void 0,!0),w){case 1:return M.fn.call(M.context),!0;case 2:return M.fn.call(M.context,m),!0;case 3:return M.fn.call(M.context,m,l),!0;case 4:return M.fn.call(M.context,m,l,f),!0;case 5:return M.fn.call(M.context,m,l,f,g),!0;case 6:return M.fn.call(M.context,m,l,f,g,T),!0}for(v=1,y=new Array(w-1);v<w;v++)y[v-1]=arguments[v];M.fn.apply(M.context,y)}else{var H,B=M.length;for(v=0;v<B;v++)switch(M[v].once&&this.removeListener(d,M[v].fn,void 0,!0),w){case 1:M[v].fn.call(M[v].context);break;case 2:M[v].fn.call(M[v].context,m);break;case 3:M[v].fn.call(M[v].context,m,l);break;case 4:M[v].fn.call(M[v].context,m,l,f);break;default:if(!y)for(H=1,y=new Array(w-1);H<w;H++)y[H-1]=arguments[H];M[v].fn.apply(M[v].context,y)}}return!0},c.prototype.on=function(d,m,l){return n(this,d,m,l,!1)},c.prototype.once=function(d,m,l){return n(this,d,m,l,!0)},c.prototype.removeListener=function(d,m,l,f){var g=r?r+d:d;if(!this._events[g])return this;if(!m)return a(this,g),this;var T=this._events[g];if(T.fn)T.fn!==m||f&&!T.once||l&&T.context!==l||a(this,g);else{for(var E=0,y=[],v=T.length;E<v;E++)(T[E].fn!==m||f&&!T[E].once||l&&T[E].context!==l)&&y.push(T[E]);y.length?this._events[g]=y.length===1?y[0]:y:a(this,g)}return this},c.prototype.removeAllListeners=function(d){var m;return d?(m=r?r+d:d,this._events[m]&&a(this,m)):(this._events=new o,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=r,c.EventEmitter=c,t!==void 0&&(t.exports=c)}}),sv=aT(cT(),1),qE=Symbol("instance"),A2=Symbol("abortCtrl"),Rl=Symbol("cacheResult"),pf=class{constructor(i,t,e){this.oldState=i,this.newState=t,this.action=e,this.aborted=!1}abort(i){this.aborted=!0,zc.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},wl=class extends Error{constructor(i,t,e){super(t),this.state=i,this.message=t,this.cause=e}};function nv(i){return typeof i=="object"&&i&&"then"in i}var Gc=new Map;function os(i,t,e={}){return(r,o,s)=>{let n=e.action||o;if(!e.context){let c=Gc.get(r)||[];Gc.has(r)||Gc.set(r,c),c.push({from:i,to:t,action:n})}let a=s.value;s.value=function(...c){let d=this;if(e.context&&(d=Vr.get(typeof e.context=="function"?e.context.call(this,...c):e.context)),d.state===t)return e.sync?d[Rl]:Promise.resolve(d[Rl]);d.state instanceof pf&&d.state.action==e.abortAction&&d.state.abort(d);let m=null;Array.isArray(i)?i.length==0?d.state instanceof pf&&d.state.abort(d):typeof d.state=="string"&&i.includes(d.state)||(m=new wl(d._state,`${d.name} ${n} to ${t} failed: current state ${d._state} not from ${i.join("|")}`)):i!==d.state&&(m=new wl(d._state,`${d.name} ${n} to ${t} failed: current state ${d._state} not from ${i}`));let l=y=>{if(e.fail&&e.fail.call(this,y),e.sync){if(e.ignoreError)return y;throw y}return e.ignoreError?Promise.resolve(y):Promise.reject(y)};if(m)return l(m);let f=d.state,g=new pf(f,t,n);zc.call(d,g);let T=y=>{var v;return d[Rl]=y,g.aborted||(zc.call(d,t),(v=e.success)===null||v===void 0||v.call(this,d[Rl])),y},E=y=>(zc.call(d,f,y),l(y));try{let y=a.apply(this,c);return nv(y)?y.then(T).catch(E):e.sync?T(y):Promise.resolve(T(y))}catch(y){return E(new wl(d._state,`${d.name} ${n} from ${i} to ${t} failed: ${y}`,y instanceof Error?y:new Error(String(y))))}}}}function av(...i){return(t,e,r)=>{let o=r.value,s=e;r.value=function(...n){if(!i.includes(this.state.toString()))throw new wl(this.state,`${this.name} ${s} failed: current state ${this.state} not in ${i}`);return o.apply(this,n)}}}var cv=typeof window!="undefined"&&window.__AFSM__?(e,r)=>{window.dispatchEvent(new CustomEvent(e,{detail:r}))}:typeof importScripts!="undefined"?(e,r)=>{postMessage({type:e,payload:r})}:()=>{};function zc(i,t){let e=this._state;this._state=i;let r=i.toString();i&&this.emit(r,e),this.emit(Vr.STATECHANGED,i,e,t),this.updateDevTools({value:i,old:e,err:t instanceof Error?t.message:String(t)})}var Vr=class li extends sv.default{constructor(t,e,r){super(),this.name=t,this.groupName=e,this._state=li.INIT,t||(t=Date.now().toString(36)),r?Object.setPrototypeOf(this,r):r=Object.getPrototypeOf(this),e||(this.groupName=this.constructor.name);let o=r[qE];o?this.name=o.name+"-"+o.count++:r[qE]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let t=Object.getPrototypeOf(this),e=Gc.get(t)||[],r=new Set,o=[],s=[],n=new Set,a=Object.getPrototypeOf(t);Gc.has(a)&&(a.stateDiagram.forEach(d=>r.add(d)),a.allStates.forEach(d=>n.add(d))),e.forEach(({from:d,to:m,action:l})=>{typeof d=="string"?o.push({from:d,to:m,action:l}):d.length?d.forEach(f=>{o.push({from:f,to:m,action:l})}):s.push({to:m,action:l})}),o.forEach(({from:d,to:m,action:l})=>{n.add(d),n.add(m),n.add(l+"ing"),r.add(`${d} --> ${l}ing : ${l}`),r.add(`${l}ing --> ${m} : ${l} \u{1F7E2}`),r.add(`${l}ing --> ${d} : ${l} \u{1F534}`)}),s.forEach(({to:d,action:m})=>{r.add(`${m}ing --> ${d} : ${m} \u{1F7E2}`),n.forEach(l=>{l!==d&&r.add(`${l} --> ${m}ing : ${m}`)})});let c=[...r];return Object.defineProperties(t,{stateDiagram:{value:c},allStates:{value:n}}),c}static get(t){let e;return typeof t=="string"?(e=li.instances.get(t),e||li.instances.set(t,e=new li(t,void 0,Object.create(li.prototype)))):(e=li.instances2.get(t),e||li.instances2.set(t,e=new li(t.constructor.name,void 0,Object.create(li.prototype)))),e}static getState(t){var e;return(e=li.get(t))===null||e===void 0?void 0:e.state}updateDevTools(t={}){cv(li.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},t))}get state(){return this._state}set state(t){zc.call(this,t)}};Vr.STATECHANGED="stateChanged",Vr.UPDATEAFSM="updateAFSM",Vr.INIT="[*]",Vr.ON="on",Vr.OFF="off",Vr.instances=new Map,Vr.instances2=new WeakMap;var fa=class extends Vr{constructor(){super(...arguments),xt(this,"decoder"),xt(this,"config")}initialize(){return D(this,null,function*(){this.decoder=new VideoDecoder({output:i=>{this.emit("videoFrame",i)},error:i=>{this.close(),this.emit("error",i)}})})}configure(i){this.config=i,this.decoder.configure(Wc(Hc({},i),{codec:this.getCodec(i)}))}getCodec(i){switch(i.codec){case"hevc":return"hvc1.1.6.L0.12.34.56.78.9A.BC";case"av1":return"av01.0.05M.08";case"avc":return"avc1.420028";default:return i.codec}}decode(i){this.decoder.state==="configured"&&this.decoder.decode(new EncodedVideoChunk(i))}flush(){this.decoder.flush()}reset(){this.decoder.reset()}close(){this.decoder.state!=="closed"&&this.decoder.close()}};function dv(){var i;self.onmessage=t=>{if(t.data.type==="init"){let{canvas:e,wasmScript:r,wasmBinary:o}=t.data,s=e==null?void 0:e.getContext("2d"),n=0,a=0,c={wasmBinary:o,postRun:()=>{i=new c.VideoDecoder({videoInfo(d,m){n=d,a=m,console.log("video info",d,m)},yuvData(d,m){let l=n*a,f=l>>2,g=c.HEAPU32[d>>2],T=c.HEAPU32[1+(d>>2)],E=c.HEAPU32[2+(d>>2)],y=c.HEAPU8.subarray(g,g+l),v=c.HEAPU8.subarray(T,T+f),M=c.HEAPU8.subarray(E,E+f),w=new Uint8Array(l+f+f);w.set(y),w.set(v,l),w.set(M,l+f);let H=new VideoFrame(w,{codedWidth:n,codedHeight:a,format:"I420",timestamp:m});e?(s==null||s.drawImage(H,0,0,e.width,e.height),s==null||s.commit()):self.postMessage({type:"yuvData",videoFrame:H},[H])}}),self.postMessage({type:"ready"})}};Function("var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined;return "+r)()(c)}else if(t.data.type==="decode"){let{packet:e}=t.data;i==null||i.decode(e.data,e.type=="key",e.timestamp)}else if(t.data.type==="setCodec"){let{codec:e,format:r,description:o}=t.data;i==null||i.setCodec(e,r,o!=null?o:"")}}}Ao([os([Vr.INIT,"closed"],"initialized")],fa.prototype,"initialize",1),Ao([os("initialized","configured",{sync:!0})],fa.prototype,"configure",1),Ao([av("configured")],fa.prototype,"decode",1),Ao([os([],Vr.INIT,{sync:!0})],fa.prototype,"reset",1),Ao([os([],"closed",{ignoreError:!0,sync:!0})],fa.prototype,"close",1);var Fc=class extends Vr{constructor(i,t,e=!1,r,o=!1){super(),this.createModule=i,this.wasmBinary=t,this.workerMode=e,this.canvas=r,this.yuvMode=o,xt(this,"worker"),xt(this,"decoder"),xt(this,"config"),xt(this,"module",{}),xt(this,"width",0),xt(this,"height",0)}initialize(i){return D(this,null,function*(){var t;if(this.workerMode){let r=new RegExp("\\{(.+)\\}","s").exec(dv.toString())[1];this.worker=new Worker(URL.createObjectURL(new Blob([r],{type:"text/javascript"})));let o=(t=this.canvas)==null?void 0:t.transferControlToOffscreen(),s=yield this.wasmBinary;return console.warn("worker mode",s),this.worker.postMessage({type:"init",canvas:o,wasmScript:this.createModule.toString(),wasmBinary:s},o?[o,s]:[s]),new Promise(n=>{this.worker.onmessage=a=>{if(a.data.type==="ready")delete this.wasmBinary,n(),console.warn("worker mode initialize success");else if(a.data.type==="yuvData"){let{videoFrame:c}=a.data;this.emit("videoFrame",c)}}})}let e=this.module;return this.wasmBinary&&(e.wasmBinary=yield this.wasmBinary),e.print=r=>console.log(r),e.printErr=r=>console.log(`[JS] ERROR: ${r}`),e.onAbort=()=>console.log("[JS] FATAL: WASM ABORTED"),new Promise(r=>{e.postRun=o=>{this.decoder=new this.module.VideoDecoder(this),console.log("video soft decoder initialize success"),r()},i&&Object.assign(e,i),this.createModule(e)})})}configure(i){var t,e,r;this.config=i;let o=this.config.codec.startsWith("avc")?"avc":"hevc",s=this.config.description?o=="avc"?"avcc":"hvcc":"annexb";(e=this.decoder)==null||e.setCodec(o,s,(t=this.config.description)!=null?t:""),(r=this.worker)==null||r.postMessage({type:"setCodec",codec:o,format:s,description:this.config.description})}decode(i){var t,e;(t=this.decoder)==null||t.decode(i.data,i.type=="key",i.timestamp),this.state==="configured"&&((e=this.worker)==null||e.postMessage({type:"decode",packet:i}))}flush(){}reset(){this.config=void 0,this.decoder&&this.decoder.clear()}close(){this.removeAllListeners(),this.decoder&&(this.decoder.clear(),this.decoder.delete())}videoInfo(i,t){this.width=i,this.height=t;let e={width:i,height:t};this.emit("videoCodecInfo",e)}yuvData(i,t){if(!this.module)return;let e=this.width*this.height,r=e>>2,o=this.module.HEAPU32[i>>2],s=this.module.HEAPU32[1+(i>>2)],n=this.module.HEAPU32[2+(i>>2)],a=this.module.HEAPU8.subarray(o,o+e),c=this.module.HEAPU8.subarray(s,s+r),d=this.module.HEAPU8.subarray(n,n+r);if(this.yuvMode)return void this.emit("videoFrame",{y:a,u:c,v:d,timestamp:t});let m=new Uint8Array(e+r+r);m.set(a),m.set(c,e),m.set(d,e+r),this.emit("videoFrame",new VideoFrame(m,{codedWidth:this.width,codedHeight:this.height,format:"I420",timestamp:t}))}errorInfo(i){let t={errMsg:i};this.emit("error",t)}};Ao([os([Vr.INIT,"closed"],"initialized")],Fc.prototype,"initialize",1),Ao([os("initialized","configured",{sync:!0})],Fc.prototype,"configure",1),Ao([os([],Vr.INIT,{sync:!0})],Fc.prototype,"reset",1),Ao([os([],"closed",{sync:!0})],Fc.prototype,"close",1);var uv=(()=>{var i=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return function(t={}){var e,r,o=t;o.ready=new Promise((u,h)=>{e=u,r=h});var s,n,a,c=Object.assign({},o),d="./this.program",m=typeof window=="object",l=typeof importScripts=="function",f=(typeof process=="object"&&typeof process.versions=="object"&&process.versions.node,"");(m||l)&&(l?f=self.location.href:typeof document!="undefined"&&document.currentScript&&(f=document.currentScript.src),i&&(f=i),f=f.indexOf("blob:")!==0?f.substr(0,f.replace(/[?#].*/,"").lastIndexOf("/")+1):"",s=u=>{var h=new XMLHttpRequest;return h.open("GET",u,!1),h.send(null),h.responseText},l&&(a=u=>{var h=new XMLHttpRequest;return h.open("GET",u,!1),h.responseType="arraybuffer",h.send(null),new Uint8Array(h.response)}),n=(u,h,_)=>{var I=new XMLHttpRequest;I.open("GET",u,!0),I.responseType="arraybuffer",I.onload=()=>{I.status==200||I.status==0&&I.response?h(I.response):_()},I.onerror=_,I.send(null)});var g,T=o.print||console.log.bind(console),E=o.printErr||console.error.bind(console);Object.assign(o,c),c=null,o.arguments&&o.arguments,o.thisProgram&&(d=o.thisProgram),o.quit&&o.quit,o.wasmBinary&&(g=o.wasmBinary);var y,v;o.noExitRuntime,typeof WebAssembly!="object"&&q("no native wasm support detected");var M,w,H,B,P,$,de,Ae,L,te=!1,A=[],le=[],He=[],ge=0,ze=null,me=null;function re(u){ge++,o.monitorRunDependencies&&o.monitorRunDependencies(ge)}function Q(u){if(ge--,o.monitorRunDependencies&&o.monitorRunDependencies(ge),ge==0&&(ze!==null&&(clearInterval(ze),ze=null),me)){var h=me;me=null,h()}}function q(u){o.onAbort&&o.onAbort(u),E(u="Aborted("+u+")"),te=!0,u+=". Build with -sASSERTIONS for more info.";var h=new WebAssembly.RuntimeError(u);throw r(h),h}var Be,De,ne,Ze;function yt(u){return u.startsWith("data:application/octet-stream;base64,")}function ae(u){if(u==Be&&g)return new Uint8Array(g);if(a)return a(u);throw"both async and sync fetching of the wasm failed"}function at(u,h,_){return function(I){return g||!m&&!l||typeof fetch!="function"?Promise.resolve().then(()=>ae(I)):fetch(I,{credentials:"same-origin"}).then(C=>{if(!C.ok)throw"failed to load wasm binary file at '"+I+"'";return C.arrayBuffer()}).catch(()=>ae(I))}(u).then(I=>WebAssembly.instantiate(I,h)).then(I=>I).then(_,I=>{E("failed to asynchronously prepare wasm: "+I),q(I)})}yt(Be="videodec.wasm")||(De=Be,Be=o.locateFile?o.locateFile(De,f):f+De);var Lt=u=>{for(;u.length>0;)u.shift()(o)};function wt(u){this.excPtr=u,this.ptr=u-24,this.set_type=function(h){$[this.ptr+4>>2]=h},this.get_type=function(){return $[this.ptr+4>>2]},this.set_destructor=function(h){$[this.ptr+8>>2]=h},this.get_destructor=function(){return $[this.ptr+8>>2]},this.set_caught=function(h){h=h?1:0,M[this.ptr+12|0]=h},this.get_caught=function(){return M[this.ptr+12|0]!=0},this.set_rethrown=function(h){h=h?1:0,M[this.ptr+13|0]=h},this.get_rethrown=function(){return M[this.ptr+13|0]!=0},this.init=function(h,_){this.set_adjusted_ptr(0),this.set_type(h),this.set_destructor(_)},this.set_adjusted_ptr=function(h){$[this.ptr+16>>2]=h},this.get_adjusted_ptr=function(){return $[this.ptr+16>>2]},this.get_exception_ptr=function(){if(Na(this.get_type()))return $[this.excPtr>>2];var h=this.get_adjusted_ptr();return h!==0?h:this.excPtr}}var we={isAbs:u=>u.charAt(0)==="/",splitPath:u=>/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(u).slice(1),normalizeArray:(u,h)=>{for(var _=0,I=u.length-1;I>=0;I--){var C=u[I];C==="."?u.splice(I,1):C===".."?(u.splice(I,1),_++):_&&(u.splice(I,1),_--)}if(h)for(;_;_--)u.unshift("..");return u},normalize:u=>{var h=we.isAbs(u),_=u.substr(-1)==="/";return(u=we.normalizeArray(u.split("/").filter(I=>!!I),!h).join("/"))||h||(u="."),u&&_&&(u+="/"),(h?"/":"")+u},dirname:u=>{var h=we.splitPath(u),_=h[0],I=h[1];return _||I?(I&&(I=I.substr(0,I.length-1)),_+I):"."},basename:u=>{if(u==="/")return"/";var h=(u=(u=we.normalize(u)).replace(/\/$/,"")).lastIndexOf("/");return h===-1?u:u.substr(h+1)},join:function(){var u=Array.prototype.slice.call(arguments);return we.normalize(u.join("/"))},join2:(u,h)=>we.normalize(u+"/"+h)},fr=u=>(fr=(()=>{if(typeof crypto=="object"&&typeof crypto.getRandomValues=="function")return h=>crypto.getRandomValues(h);q("initRandomDevice")})())(u),S={resolve:function(){for(var u="",h=!1,_=arguments.length-1;_>=-1&&!h;_--){var I=_>=0?arguments[_]:b.cwd();if(typeof I!="string")throw new TypeError("Arguments to path.resolve must be strings");if(!I)return"";u=I+"/"+u,h=we.isAbs(I)}return(h?"/":"")+(u=we.normalizeArray(u.split("/").filter(C=>!!C),!h).join("/"))||"."},relative:(u,h)=>{function _(K){for(var Re=0;Re<K.length&&K[Re]==="";Re++);for(var Pe=K.length-1;Pe>=0&&K[Pe]==="";Pe--);return Re>Pe?[]:K.slice(Re,Pe-Re+1)}u=S.resolve(u).substr(1),h=S.resolve(h).substr(1);for(var I=_(u.split("/")),C=_(h.split("/")),k=Math.min(I.length,C.length),U=k,V=0;V<k;V++)if(I[V]!==C[V]){U=V;break}var ie=[];for(V=U;V<I.length;V++)ie.push("..");return(ie=ie.concat(C.slice(U))).join("/")}},ue=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):void 0,Y=(u,h,_)=>{for(var I=h+_,C=h;u[C]&&!(C>=I);)++C;if(C-h>16&&u.buffer&&ue)return ue.decode(u.subarray(h,C));for(var k="";h<C;){var U=u[h++];if(128&U){var V=63&u[h++];if((224&U)!=192){var ie=63&u[h++];if((U=(240&U)==224?(15&U)<<12|V<<6|ie:(7&U)<<18|V<<12|ie<<6|63&u[h++])<65536)k+=String.fromCharCode(U);else{var K=U-65536;k+=String.fromCharCode(55296|K>>10,56320|1023&K)}}else k+=String.fromCharCode((31&U)<<6|V)}else k+=String.fromCharCode(U)}return k},x=[],O=u=>{for(var h=0,_=0;_<u.length;++_){var I=u.charCodeAt(_);I<=127?h++:I<=2047?h+=2:I>=55296&&I<=57343?(h+=4,++_):h+=3}return h},F=(u,h,_,I)=>{if(!(I>0))return 0;for(var C=_,k=_+I-1,U=0;U<u.length;++U){var V=u.charCodeAt(U);if(V>=55296&&V<=57343&&(V=65536+((1023&V)<<10)|1023&u.charCodeAt(++U)),V<=127){if(_>=k)break;h[_++]=V}else if(V<=2047){if(_+1>=k)break;h[_++]=192|V>>6,h[_++]=128|63&V}else if(V<=65535){if(_+2>=k)break;h[_++]=224|V>>12,h[_++]=128|V>>6&63,h[_++]=128|63&V}else{if(_+3>=k)break;h[_++]=240|V>>18,h[_++]=128|V>>12&63,h[_++]=128|V>>6&63,h[_++]=128|63&V}}return h[_]=0,_-C};function pe(u,h,_){var I=_>0?_:O(u)+1,C=new Array(I),k=F(u,C,0,C.length);return h&&(C.length=k),C}var fe={ttys:[],init:function(){},shutdown:function(){},register:function(u,h){fe.ttys[u]={input:[],output:[],ops:h},b.registerDevice(u,fe.stream_ops)},stream_ops:{open:function(u){var h=fe.ttys[u.node.rdev];if(!h)throw new b.ErrnoError(43);u.tty=h,u.seekable=!1},close:function(u){u.tty.ops.fsync(u.tty)},fsync:function(u){u.tty.ops.fsync(u.tty)},read:function(u,h,_,I,C){if(!u.tty||!u.tty.ops.get_char)throw new b.ErrnoError(60);for(var k=0,U=0;U<I;U++){var V;try{V=u.tty.ops.get_char(u.tty)}catch(ie){throw new b.ErrnoError(29)}if(V===void 0&&k===0)throw new b.ErrnoError(6);if(V==null)break;k++,h[_+U]=V}return k&&(u.node.timestamp=Date.now()),k},write:function(u,h,_,I,C){if(!u.tty||!u.tty.ops.put_char)throw new b.ErrnoError(60);try{for(var k=0;k<I;k++)u.tty.ops.put_char(u.tty,h[_+k])}catch(U){throw new b.ErrnoError(29)}return I&&(u.node.timestamp=Date.now()),k}},default_tty_ops:{get_char:function(u){return(()=>{if(!x.length){var h=null;if(typeof window!="undefined"&&typeof window.prompt=="function"?(h=window.prompt("Input: "))!==null&&(h+=`
|
|
52
|
-
`):typeof readline=="function"&&(h=readline())!==null&&(h+=`
|
|
53
|
-
`),!h)return null;x=pe(h,!0)}return x.shift()})()},put_char:function(u,h){h===null||h===10?(T(Y(u.output,0)),u.output=[]):h!=0&&u.output.push(h)},fsync:function(u){u.output&&u.output.length>0&&(T(Y(u.output,0)),u.output=[])},ioctl_tcgets:function(u){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets:function(u,h,_){return 0},ioctl_tiocgwinsz:function(u){return[24,80]}},default_tty1_ops:{put_char:function(u,h){h===null||h===10?(E(Y(u.output,0)),u.output=[]):h!=0&&u.output.push(h)},fsync:function(u){u.output&&u.output.length>0&&(E(Y(u.output,0)),u.output=[])}}},X=u=>{q()},oe={ops_table:null,mount:u=>oe.createNode(null,"/",16895,0),createNode(u,h,_,I){if(b.isBlkdev(_)||b.isFIFO(_))throw new b.ErrnoError(63);oe.ops_table||(oe.ops_table={dir:{node:{getattr:oe.node_ops.getattr,setattr:oe.node_ops.setattr,lookup:oe.node_ops.lookup,mknod:oe.node_ops.mknod,rename:oe.node_ops.rename,unlink:oe.node_ops.unlink,rmdir:oe.node_ops.rmdir,readdir:oe.node_ops.readdir,symlink:oe.node_ops.symlink},stream:{llseek:oe.stream_ops.llseek}},file:{node:{getattr:oe.node_ops.getattr,setattr:oe.node_ops.setattr},stream:{llseek:oe.stream_ops.llseek,read:oe.stream_ops.read,write:oe.stream_ops.write,allocate:oe.stream_ops.allocate,mmap:oe.stream_ops.mmap,msync:oe.stream_ops.msync}},link:{node:{getattr:oe.node_ops.getattr,setattr:oe.node_ops.setattr,readlink:oe.node_ops.readlink},stream:{}},chrdev:{node:{getattr:oe.node_ops.getattr,setattr:oe.node_ops.setattr},stream:b.chrdev_stream_ops}});var C=b.createNode(u,h,_,I);return b.isDir(C.mode)?(C.node_ops=oe.ops_table.dir.node,C.stream_ops=oe.ops_table.dir.stream,C.contents={}):b.isFile(C.mode)?(C.node_ops=oe.ops_table.file.node,C.stream_ops=oe.ops_table.file.stream,C.usedBytes=0,C.contents=null):b.isLink(C.mode)?(C.node_ops=oe.ops_table.link.node,C.stream_ops=oe.ops_table.link.stream):b.isChrdev(C.mode)&&(C.node_ops=oe.ops_table.chrdev.node,C.stream_ops=oe.ops_table.chrdev.stream),C.timestamp=Date.now(),u&&(u.contents[h]=C,u.timestamp=C.timestamp),C},getFileDataAsTypedArray:u=>u.contents?u.contents.subarray?u.contents.subarray(0,u.usedBytes):new Uint8Array(u.contents):new Uint8Array(0),expandFileStorage(u,h){var _=u.contents?u.contents.length:0;if(!(_>=h)){h=Math.max(h,_*(_<1048576?2:1.125)>>>0),_!=0&&(h=Math.max(h,256));var I=u.contents;u.contents=new Uint8Array(h),u.usedBytes>0&&u.contents.set(I.subarray(0,u.usedBytes),0)}},resizeFileStorage(u,h){if(u.usedBytes!=h)if(h==0)u.contents=null,u.usedBytes=0;else{var _=u.contents;u.contents=new Uint8Array(h),_&&u.contents.set(_.subarray(0,Math.min(h,u.usedBytes))),u.usedBytes=h}},node_ops:{getattr(u){var h={};return h.dev=b.isChrdev(u.mode)?u.id:1,h.ino=u.id,h.mode=u.mode,h.nlink=1,h.uid=0,h.gid=0,h.rdev=u.rdev,b.isDir(u.mode)?h.size=4096:b.isFile(u.mode)?h.size=u.usedBytes:b.isLink(u.mode)?h.size=u.link.length:h.size=0,h.atime=new Date(u.timestamp),h.mtime=new Date(u.timestamp),h.ctime=new Date(u.timestamp),h.blksize=4096,h.blocks=Math.ceil(h.size/h.blksize),h},setattr(u,h){h.mode!==void 0&&(u.mode=h.mode),h.timestamp!==void 0&&(u.timestamp=h.timestamp),h.size!==void 0&&oe.resizeFileStorage(u,h.size)},lookup(u,h){throw b.genericErrors[44]},mknod:(u,h,_,I)=>oe.createNode(u,h,_,I),rename(u,h,_){if(b.isDir(u.mode)){var I;try{I=b.lookupNode(h,_)}catch(k){}if(I)for(var C in I.contents)throw new b.ErrnoError(55)}delete u.parent.contents[u.name],u.parent.timestamp=Date.now(),u.name=_,h.contents[_]=u,h.timestamp=u.parent.timestamp,u.parent=h},unlink(u,h){delete u.contents[h],u.timestamp=Date.now()},rmdir(u,h){var _=b.lookupNode(u,h);for(var I in _.contents)throw new b.ErrnoError(55);delete u.contents[h],u.timestamp=Date.now()},readdir(u){var h=[".",".."];for(var _ in u.contents)u.contents.hasOwnProperty(_)&&h.push(_);return h},symlink(u,h,_){var I=oe.createNode(u,h,41471,0);return I.link=_,I},readlink(u){if(!b.isLink(u.mode))throw new b.ErrnoError(28);return u.link}},stream_ops:{read(u,h,_,I,C){var k=u.node.contents;if(C>=u.node.usedBytes)return 0;var U=Math.min(u.node.usedBytes-C,I);if(U>8&&k.subarray)h.set(k.subarray(C,C+U),_);else for(var V=0;V<U;V++)h[_+V]=k[C+V];return U},write(u,h,_,I,C,k){if(!I)return 0;var U=u.node;if(U.timestamp=Date.now(),h.subarray&&(!U.contents||U.contents.subarray)){if(k)return U.contents=h.subarray(_,_+I),U.usedBytes=I,I;if(U.usedBytes===0&&C===0)return U.contents=h.slice(_,_+I),U.usedBytes=I,I;if(C+I<=U.usedBytes)return U.contents.set(h.subarray(_,_+I),C),I}if(oe.expandFileStorage(U,C+I),U.contents.subarray&&h.subarray)U.contents.set(h.subarray(_,_+I),C);else for(var V=0;V<I;V++)U.contents[C+V]=h[_+V];return U.usedBytes=Math.max(U.usedBytes,C+I),I},llseek(u,h,_){var I=h;if(_===1?I+=u.position:_===2&&b.isFile(u.node.mode)&&(I+=u.node.usedBytes),I<0)throw new b.ErrnoError(28);return I},allocate(u,h,_){oe.expandFileStorage(u.node,h+_),u.node.usedBytes=Math.max(u.node.usedBytes,h+_)},mmap(u,h,_,I,C){if(!b.isFile(u.node.mode))throw new b.ErrnoError(43);var k,U,V=u.node.contents;if(2&C||V.buffer!==M.buffer){if((_>0||_+h<V.length)&&(V=V.subarray?V.subarray(_,_+h):Array.prototype.slice.call(V,_,_+h)),U=!0,!(k=X()))throw new b.ErrnoError(48);M.set(V,k)}else U=!1,k=V.byteOffset;return{ptr:k,allocated:U}},msync:(u,h,_,I,C)=>(oe.stream_ops.write(u,h,0,I,_,!1),0)}},xe=(u,h,_,I)=>{var C=I?"":`al ${u}`;n(u,k=>{var U;U=`Loading data file "${u}" failed (no arrayBuffer).`,k||q(U),h(new Uint8Array(k)),C&&Q()},k=>{if(!_)throw`Loading data file "${u}" failed.`;_()}),C&&re()},Z=o.preloadPlugins||[];function $e(u,h){var _=0;return u&&(_|=365),h&&(_|=146),_}var b={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:!1,ignorePermissions:!0,ErrnoError:null,genericErrors:{},filesystems:null,syncFSRequests:0,lookupPath:(u,h={})=>{if(!(u=S.resolve(u)))return{path:"",node:null};if((h=Object.assign({follow_mount:!0,recurse_count:0},h)).recurse_count>8)throw new b.ErrnoError(32);for(var _=u.split("/").filter(K=>!!K),I=b.root,C="/",k=0;k<_.length;k++){var U=k===_.length-1;if(U&&h.parent)break;if(I=b.lookupNode(I,_[k]),C=we.join2(C,_[k]),b.isMountpoint(I)&&(!U||U&&h.follow_mount)&&(I=I.mounted.root),!U||h.follow)for(var V=0;b.isLink(I.mode);){var ie=b.readlink(C);if(C=S.resolve(we.dirname(C),ie),I=b.lookupPath(C,{recurse_count:h.recurse_count+1}).node,V++>40)throw new b.ErrnoError(32)}}return{path:C,node:I}},getPath:u=>{for(var h;;){if(b.isRoot(u)){var _=u.mount.mountpoint;return h?_[_.length-1]!=="/"?`${_}/${h}`:_+h:_}h=h?`${u.name}/${h}`:u.name,u=u.parent}},hashName:(u,h)=>{for(var _=0,I=0;I<h.length;I++)_=(_<<5)-_+h.charCodeAt(I)|0;return(u+_>>>0)%b.nameTable.length},hashAddNode:u=>{var h=b.hashName(u.parent.id,u.name);u.name_next=b.nameTable[h],b.nameTable[h]=u},hashRemoveNode:u=>{var h=b.hashName(u.parent.id,u.name);if(b.nameTable[h]===u)b.nameTable[h]=u.name_next;else for(var _=b.nameTable[h];_;){if(_.name_next===u){_.name_next=u.name_next;break}_=_.name_next}},lookupNode:(u,h)=>{var _=b.mayLookup(u);if(_)throw new b.ErrnoError(_,u);for(var I=b.hashName(u.id,h),C=b.nameTable[I];C;C=C.name_next){var k=C.name;if(C.parent.id===u.id&&k===h)return C}return b.lookup(u,h)},createNode:(u,h,_,I)=>{var C=new b.FSNode(u,h,_,I);return b.hashAddNode(C),C},destroyNode:u=>{b.hashRemoveNode(u)},isRoot:u=>u===u.parent,isMountpoint:u=>!!u.mounted,isFile:u=>(61440&u)==32768,isDir:u=>(61440&u)==16384,isLink:u=>(61440&u)==40960,isChrdev:u=>(61440&u)==8192,isBlkdev:u=>(61440&u)==24576,isFIFO:u=>(61440&u)==4096,isSocket:u=>!(49152&~u),flagsToPermissionString:u=>{var h=["r","w","rw"][3&u];return 512&u&&(h+="w"),h},nodePermissions:(u,h)=>b.ignorePermissions||(!h.includes("r")||292&u.mode)&&(!h.includes("w")||146&u.mode)&&(!h.includes("x")||73&u.mode)?0:2,mayLookup:u=>{var h=b.nodePermissions(u,"x");return h||(u.node_ops.lookup?0:2)},mayCreate:(u,h)=>{try{return b.lookupNode(u,h),20}catch(_){}return b.nodePermissions(u,"wx")},mayDelete:(u,h,_)=>{var I;try{I=b.lookupNode(u,h)}catch(k){return k.errno}var C=b.nodePermissions(u,"wx");if(C)return C;if(_){if(!b.isDir(I.mode))return 54;if(b.isRoot(I)||b.getPath(I)===b.cwd())return 10}else if(b.isDir(I.mode))return 31;return 0},mayOpen:(u,h)=>u?b.isLink(u.mode)?32:b.isDir(u.mode)&&(b.flagsToPermissionString(h)!=="r"||512&h)?31:b.nodePermissions(u,b.flagsToPermissionString(h)):44,MAX_OPEN_FDS:4096,nextfd:()=>{for(var u=0;u<=b.MAX_OPEN_FDS;u++)if(!b.streams[u])return u;throw new b.ErrnoError(33)},getStreamChecked:u=>{var h=b.getStream(u);if(!h)throw new b.ErrnoError(8);return h},getStream:u=>b.streams[u],createStream:(u,h=-1)=>(b.FSStream||(b.FSStream=function(){this.shared={}},b.FSStream.prototype={},Object.defineProperties(b.FSStream.prototype,{object:{get(){return this.node},set(_){this.node=_}},isRead:{get(){return(2097155&this.flags)!=1}},isWrite:{get(){return!!(2097155&this.flags)}},isAppend:{get(){return 1024&this.flags}},flags:{get(){return this.shared.flags},set(_){this.shared.flags=_}},position:{get(){return this.shared.position},set(_){this.shared.position=_}}})),u=Object.assign(new b.FSStream,u),h==-1&&(h=b.nextfd()),u.fd=h,b.streams[h]=u,u),closeStream:u=>{b.streams[u]=null},chrdev_stream_ops:{open:u=>{var h=b.getDevice(u.node.rdev);u.stream_ops=h.stream_ops,u.stream_ops.open&&u.stream_ops.open(u)},llseek:()=>{throw new b.ErrnoError(70)}},major:u=>u>>8,minor:u=>255&u,makedev:(u,h)=>u<<8|h,registerDevice:(u,h)=>{b.devices[u]={stream_ops:h}},getDevice:u=>b.devices[u],getMounts:u=>{for(var h=[],_=[u];_.length;){var I=_.pop();h.push(I),_.push.apply(_,I.mounts)}return h},syncfs:(u,h)=>{typeof u=="function"&&(h=u,u=!1),b.syncFSRequests++,b.syncFSRequests>1&&E(`warning: ${b.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`);var _=b.getMounts(b.root.mount),I=0;function C(U){return b.syncFSRequests--,h(U)}function k(U){if(U)return k.errored?void 0:(k.errored=!0,C(U));++I>=_.length&&C(null)}_.forEach(U=>{if(!U.type.syncfs)return k(null);U.type.syncfs(U,u,k)})},mount:(u,h,_)=>{var I,C=_==="/",k=!_;if(C&&b.root)throw new b.ErrnoError(10);if(!C&&!k){var U=b.lookupPath(_,{follow_mount:!1});if(_=U.path,I=U.node,b.isMountpoint(I))throw new b.ErrnoError(10);if(!b.isDir(I.mode))throw new b.ErrnoError(54)}var V={type:u,opts:h,mountpoint:_,mounts:[]},ie=u.mount(V);return ie.mount=V,V.root=ie,C?b.root=ie:I&&(I.mounted=V,I.mount&&I.mount.mounts.push(V)),ie},unmount:u=>{var h=b.lookupPath(u,{follow_mount:!1});if(!b.isMountpoint(h.node))throw new b.ErrnoError(28);var _=h.node,I=_.mounted,C=b.getMounts(I);Object.keys(b.nameTable).forEach(U=>{for(var V=b.nameTable[U];V;){var ie=V.name_next;C.includes(V.mount)&&b.destroyNode(V),V=ie}}),_.mounted=null;var k=_.mount.mounts.indexOf(I);_.mount.mounts.splice(k,1)},lookup:(u,h)=>u.node_ops.lookup(u,h),mknod:(u,h,_)=>{var I=b.lookupPath(u,{parent:!0}).node,C=we.basename(u);if(!C||C==="."||C==="..")throw new b.ErrnoError(28);var k=b.mayCreate(I,C);if(k)throw new b.ErrnoError(k);if(!I.node_ops.mknod)throw new b.ErrnoError(63);return I.node_ops.mknod(I,C,h,_)},create:(u,h)=>(h=h!==void 0?h:438,h&=4095,h|=32768,b.mknod(u,h,0)),mkdir:(u,h)=>(h=h!==void 0?h:511,h&=1023,h|=16384,b.mknod(u,h,0)),mkdirTree:(u,h)=>{for(var _=u.split("/"),I="",C=0;C<_.length;++C)if(_[C]){I+="/"+_[C];try{b.mkdir(I,h)}catch(k){if(k.errno!=20)throw k}}},mkdev:(u,h,_)=>(_===void 0&&(_=h,h=438),h|=8192,b.mknod(u,h,_)),symlink:(u,h)=>{if(!S.resolve(u))throw new b.ErrnoError(44);var _=b.lookupPath(h,{parent:!0}).node;if(!_)throw new b.ErrnoError(44);var I=we.basename(h),C=b.mayCreate(_,I);if(C)throw new b.ErrnoError(C);if(!_.node_ops.symlink)throw new b.ErrnoError(63);return _.node_ops.symlink(_,I,u)},rename:(u,h)=>{var _,I,C=we.dirname(u),k=we.dirname(h),U=we.basename(u),V=we.basename(h);if(_=b.lookupPath(u,{parent:!0}).node,I=b.lookupPath(h,{parent:!0}).node,!_||!I)throw new b.ErrnoError(44);if(_.mount!==I.mount)throw new b.ErrnoError(75);var ie,K=b.lookupNode(_,U),Re=S.relative(u,k);if(Re.charAt(0)!==".")throw new b.ErrnoError(28);if((Re=S.relative(h,C)).charAt(0)!==".")throw new b.ErrnoError(55);try{ie=b.lookupNode(I,V)}catch(Le){}if(K!==ie){var Pe=b.isDir(K.mode),Ue=b.mayDelete(_,U,Pe);if(Ue)throw new b.ErrnoError(Ue);if(Ue=ie?b.mayDelete(I,V,Pe):b.mayCreate(I,V))throw new b.ErrnoError(Ue);if(!_.node_ops.rename)throw new b.ErrnoError(63);if(b.isMountpoint(K)||ie&&b.isMountpoint(ie))throw new b.ErrnoError(10);if(I!==_&&(Ue=b.nodePermissions(_,"w")))throw new b.ErrnoError(Ue);b.hashRemoveNode(K);try{_.node_ops.rename(K,I,V)}catch(Le){throw Le}finally{b.hashAddNode(K)}}},rmdir:u=>{var h=b.lookupPath(u,{parent:!0}).node,_=we.basename(u),I=b.lookupNode(h,_),C=b.mayDelete(h,_,!0);if(C)throw new b.ErrnoError(C);if(!h.node_ops.rmdir)throw new b.ErrnoError(63);if(b.isMountpoint(I))throw new b.ErrnoError(10);h.node_ops.rmdir(h,_),b.destroyNode(I)},readdir:u=>{var h=b.lookupPath(u,{follow:!0}).node;if(!h.node_ops.readdir)throw new b.ErrnoError(54);return h.node_ops.readdir(h)},unlink:u=>{var h=b.lookupPath(u,{parent:!0}).node;if(!h)throw new b.ErrnoError(44);var _=we.basename(u),I=b.lookupNode(h,_),C=b.mayDelete(h,_,!1);if(C)throw new b.ErrnoError(C);if(!h.node_ops.unlink)throw new b.ErrnoError(63);if(b.isMountpoint(I))throw new b.ErrnoError(10);h.node_ops.unlink(h,_),b.destroyNode(I)},readlink:u=>{var h=b.lookupPath(u).node;if(!h)throw new b.ErrnoError(44);if(!h.node_ops.readlink)throw new b.ErrnoError(28);return S.resolve(b.getPath(h.parent),h.node_ops.readlink(h))},stat:(u,h)=>{var _=b.lookupPath(u,{follow:!h}).node;if(!_)throw new b.ErrnoError(44);if(!_.node_ops.getattr)throw new b.ErrnoError(63);return _.node_ops.getattr(_)},lstat:u=>b.stat(u,!0),chmod:(u,h,_)=>{var I;if(typeof u=="string"?I=b.lookupPath(u,{follow:!_}).node:I=u,!I.node_ops.setattr)throw new b.ErrnoError(63);I.node_ops.setattr(I,{mode:4095&h|-4096&I.mode,timestamp:Date.now()})},lchmod:(u,h)=>{b.chmod(u,h,!0)},fchmod:(u,h)=>{var _=b.getStreamChecked(u);b.chmod(_.node,h)},chown:(u,h,_,I)=>{var C;if(typeof u=="string"?C=b.lookupPath(u,{follow:!I}).node:C=u,!C.node_ops.setattr)throw new b.ErrnoError(63);C.node_ops.setattr(C,{timestamp:Date.now()})},lchown:(u,h,_)=>{b.chown(u,h,_,!0)},fchown:(u,h,_)=>{var I=b.getStreamChecked(u);b.chown(I.node,h,_)},truncate:(u,h)=>{if(h<0)throw new b.ErrnoError(28);var _;if(typeof u=="string"?_=b.lookupPath(u,{follow:!0}).node:_=u,!_.node_ops.setattr)throw new b.ErrnoError(63);if(b.isDir(_.mode))throw new b.ErrnoError(31);if(!b.isFile(_.mode))throw new b.ErrnoError(28);var I=b.nodePermissions(_,"w");if(I)throw new b.ErrnoError(I);_.node_ops.setattr(_,{size:h,timestamp:Date.now()})},ftruncate:(u,h)=>{var _=b.getStreamChecked(u);if(!(2097155&_.flags))throw new b.ErrnoError(28);b.truncate(_.node,h)},utime:(u,h,_)=>{var I=b.lookupPath(u,{follow:!0}).node;I.node_ops.setattr(I,{timestamp:Math.max(h,_)})},open:(u,h,_)=>{if(u==="")throw new b.ErrnoError(44);var I;if(_=_===void 0?438:_,_=64&(h=typeof h=="string"?function(V){var ie={r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090}[V];if(ie===void 0)throw new Error(`Unknown file open mode: ${V}`);return ie}(h):h)?4095&_|32768:0,typeof u=="object")I=u;else{u=we.normalize(u);try{I=b.lookupPath(u,{follow:!(131072&h)}).node}catch(V){}}var C=!1;if(64&h)if(I){if(128&h)throw new b.ErrnoError(20)}else I=b.mknod(u,_,0),C=!0;if(!I)throw new b.ErrnoError(44);if(b.isChrdev(I.mode)&&(h&=-513),65536&h&&!b.isDir(I.mode))throw new b.ErrnoError(54);if(!C){var k=b.mayOpen(I,h);if(k)throw new b.ErrnoError(k)}512&h&&!C&&b.truncate(I,0),h&=-131713;var U=b.createStream({node:I,path:b.getPath(I),flags:h,seekable:!0,position:0,stream_ops:I.stream_ops,ungotten:[],error:!1});return U.stream_ops.open&&U.stream_ops.open(U),!o.logReadFiles||1&h||(b.readFiles||(b.readFiles={}),u in b.readFiles||(b.readFiles[u]=1)),U},close:u=>{if(b.isClosed(u))throw new b.ErrnoError(8);u.getdents&&(u.getdents=null);try{u.stream_ops.close&&u.stream_ops.close(u)}catch(h){throw h}finally{b.closeStream(u.fd)}u.fd=null},isClosed:u=>u.fd===null,llseek:(u,h,_)=>{if(b.isClosed(u))throw new b.ErrnoError(8);if(!u.seekable||!u.stream_ops.llseek)throw new b.ErrnoError(70);if(_!=0&&_!=1&&_!=2)throw new b.ErrnoError(28);return u.position=u.stream_ops.llseek(u,h,_),u.ungotten=[],u.position},read:(u,h,_,I,C)=>{if(I<0||C<0)throw new b.ErrnoError(28);if(b.isClosed(u))throw new b.ErrnoError(8);if((2097155&u.flags)==1)throw new b.ErrnoError(8);if(b.isDir(u.node.mode))throw new b.ErrnoError(31);if(!u.stream_ops.read)throw new b.ErrnoError(28);var k=C!==void 0;if(k){if(!u.seekable)throw new b.ErrnoError(70)}else C=u.position;var U=u.stream_ops.read(u,h,_,I,C);return k||(u.position+=U),U},write:(u,h,_,I,C,k)=>{if(I<0||C<0)throw new b.ErrnoError(28);if(b.isClosed(u))throw new b.ErrnoError(8);if(!(2097155&u.flags))throw new b.ErrnoError(8);if(b.isDir(u.node.mode))throw new b.ErrnoError(31);if(!u.stream_ops.write)throw new b.ErrnoError(28);u.seekable&&1024&u.flags&&b.llseek(u,0,2);var U=C!==void 0;if(U){if(!u.seekable)throw new b.ErrnoError(70)}else C=u.position;var V=u.stream_ops.write(u,h,_,I,C,k);return U||(u.position+=V),V},allocate:(u,h,_)=>{if(b.isClosed(u))throw new b.ErrnoError(8);if(h<0||_<=0)throw new b.ErrnoError(28);if(!(2097155&u.flags))throw new b.ErrnoError(8);if(!b.isFile(u.node.mode)&&!b.isDir(u.node.mode))throw new b.ErrnoError(43);if(!u.stream_ops.allocate)throw new b.ErrnoError(138);u.stream_ops.allocate(u,h,_)},mmap:(u,h,_,I,C)=>{if(2&I&&!(2&C)&&(2097155&u.flags)!=2)throw new b.ErrnoError(2);if((2097155&u.flags)==1)throw new b.ErrnoError(2);if(!u.stream_ops.mmap)throw new b.ErrnoError(43);return u.stream_ops.mmap(u,h,_,I,C)},msync:(u,h,_,I,C)=>u.stream_ops.msync?u.stream_ops.msync(u,h,_,I,C):0,munmap:u=>0,ioctl:(u,h,_)=>{if(!u.stream_ops.ioctl)throw new b.ErrnoError(59);return u.stream_ops.ioctl(u,h,_)},readFile:(u,h={})=>{if(h.flags=h.flags||0,h.encoding=h.encoding||"binary",h.encoding!=="utf8"&&h.encoding!=="binary")throw new Error(`Invalid encoding type "${h.encoding}"`);var _,I=b.open(u,h.flags),C=b.stat(u).size,k=new Uint8Array(C);return b.read(I,k,0,C,0),h.encoding==="utf8"?_=Y(k,0):h.encoding==="binary"&&(_=k),b.close(I),_},writeFile:(u,h,_={})=>{_.flags=_.flags||577;var I=b.open(u,_.flags,_.mode);if(typeof h=="string"){var C=new Uint8Array(O(h)+1),k=F(h,C,0,C.length);b.write(I,C,0,k,void 0,_.canOwn)}else{if(!ArrayBuffer.isView(h))throw new Error("Unsupported data type");b.write(I,h,0,h.byteLength,void 0,_.canOwn)}b.close(I)},cwd:()=>b.currentPath,chdir:u=>{var h=b.lookupPath(u,{follow:!0});if(h.node===null)throw new b.ErrnoError(44);if(!b.isDir(h.node.mode))throw new b.ErrnoError(54);var _=b.nodePermissions(h.node,"x");if(_)throw new b.ErrnoError(_);b.currentPath=h.path},createDefaultDirectories:()=>{b.mkdir("/tmp"),b.mkdir("/home"),b.mkdir("/home/web_user")},createDefaultDevices:()=>{b.mkdir("/dev"),b.registerDevice(b.makedev(1,3),{read:()=>0,write:(I,C,k,U,V)=>U}),b.mkdev("/dev/null",b.makedev(1,3)),fe.register(b.makedev(5,0),fe.default_tty_ops),fe.register(b.makedev(6,0),fe.default_tty1_ops),b.mkdev("/dev/tty",b.makedev(5,0)),b.mkdev("/dev/tty1",b.makedev(6,0));var u=new Uint8Array(1024),h=0,_=()=>(h===0&&(h=fr(u).byteLength),u[--h]);b.createDevice("/dev","random",_),b.createDevice("/dev","urandom",_),b.mkdir("/dev/shm"),b.mkdir("/dev/shm/tmp")},createSpecialDirectories:()=>{b.mkdir("/proc");var u=b.mkdir("/proc/self");b.mkdir("/proc/self/fd"),b.mount({mount:()=>{var h=b.createNode(u,"fd",16895,73);return h.node_ops={lookup:(_,I)=>{var C=+I,k=b.getStreamChecked(C),U={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>k.path}};return U.parent=U,U}},h}},{},"/proc/self/fd")},createStandardStreams:()=>{o.stdin?b.createDevice("/dev","stdin",o.stdin):b.symlink("/dev/tty","/dev/stdin"),o.stdout?b.createDevice("/dev","stdout",null,o.stdout):b.symlink("/dev/tty","/dev/stdout"),o.stderr?b.createDevice("/dev","stderr",null,o.stderr):b.symlink("/dev/tty1","/dev/stderr"),b.open("/dev/stdin",0),b.open("/dev/stdout",1),b.open("/dev/stderr",1)},ensureErrnoError:()=>{b.ErrnoError||(b.ErrnoError=function(u,h){this.name="ErrnoError",this.node=h,this.setErrno=function(_){this.errno=_},this.setErrno(u),this.message="FS error"},b.ErrnoError.prototype=new Error,b.ErrnoError.prototype.constructor=b.ErrnoError,[44].forEach(u=>{b.genericErrors[u]=new b.ErrnoError(u),b.genericErrors[u].stack="<generic error, no stack>"}))},staticInit:()=>{b.ensureErrnoError(),b.nameTable=new Array(4096),b.mount(oe,{},"/"),b.createDefaultDirectories(),b.createDefaultDevices(),b.createSpecialDirectories(),b.filesystems={MEMFS:oe}},init:(u,h,_)=>{b.init.initialized=!0,b.ensureErrnoError(),o.stdin=u||o.stdin,o.stdout=h||o.stdout,o.stderr=_||o.stderr,b.createStandardStreams()},quit:()=>{b.init.initialized=!1;for(var u=0;u<b.streams.length;u++){var h=b.streams[u];h&&b.close(h)}},findObject:(u,h)=>{var _=b.analyzePath(u,h);return _.exists?_.object:null},analyzePath:(u,h)=>{try{u=(I=b.lookupPath(u,{follow:!h})).path}catch(C){}var _={isRoot:!1,exists:!1,error:0,name:null,path:null,object:null,parentExists:!1,parentPath:null,parentObject:null};try{var I=b.lookupPath(u,{parent:!0});_.parentExists=!0,_.parentPath=I.path,_.parentObject=I.node,_.name=we.basename(u),I=b.lookupPath(u,{follow:!h}),_.exists=!0,_.path=I.path,_.object=I.node,_.name=I.node.name,_.isRoot=I.path==="/"}catch(C){_.error=C.errno}return _},createPath:(u,h,_,I)=>{u=typeof u=="string"?u:b.getPath(u);for(var C=h.split("/").reverse();C.length;){var k=C.pop();if(k){var U=we.join2(u,k);try{b.mkdir(U)}catch(V){}u=U}}return U},createFile:(u,h,_,I,C)=>{var k=we.join2(typeof u=="string"?u:b.getPath(u),h),U=$e(I,C);return b.create(k,U)},createDataFile:(u,h,_,I,C,k)=>{var U=h;u&&(u=typeof u=="string"?u:b.getPath(u),U=h?we.join2(u,h):u);var V=$e(I,C),ie=b.create(U,V);if(_){if(typeof _=="string"){for(var K=new Array(_.length),Re=0,Pe=_.length;Re<Pe;++Re)K[Re]=_.charCodeAt(Re);_=K}b.chmod(ie,146|V);var Ue=b.open(ie,577);b.write(Ue,_,0,_.length,0,k),b.close(Ue),b.chmod(ie,V)}return ie},createDevice:(u,h,_,I)=>{var C=we.join2(typeof u=="string"?u:b.getPath(u),h),k=$e(!!_,!!I);b.createDevice.major||(b.createDevice.major=64);var U=b.makedev(b.createDevice.major++,0);return b.registerDevice(U,{open:V=>{V.seekable=!1},close:V=>{I&&I.buffer&&I.buffer.length&&I(10)},read:(V,ie,K,Re,Pe)=>{for(var Ue=0,Le=0;Le<Re;Le++){var st;try{st=_()}catch(gt){throw new b.ErrnoError(29)}if(st===void 0&&Ue===0)throw new b.ErrnoError(6);if(st==null)break;Ue++,ie[K+Le]=st}return Ue&&(V.node.timestamp=Date.now()),Ue},write:(V,ie,K,Re,Pe)=>{for(var Ue=0;Ue<Re;Ue++)try{I(ie[K+Ue])}catch(Le){throw new b.ErrnoError(29)}return Re&&(V.node.timestamp=Date.now()),Ue}}),b.mkdev(C,k,U)},forceLoadFile:u=>{if(u.isDevice||u.isFolder||u.link||u.contents)return!0;if(typeof XMLHttpRequest!="undefined")throw new Error("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.");if(!s)throw new Error("Cannot load without read() or XMLHttpRequest.");try{u.contents=pe(s(u.url),!0),u.usedBytes=u.contents.length}catch(h){throw new b.ErrnoError(29)}},createLazyFile:(u,h,_,I,C)=>{function k(){this.lengthKnown=!1,this.chunks=[]}if(k.prototype.get=function(Pe){if(!(Pe>this.length-1||Pe<0)){var Ue=Pe%this.chunkSize,Le=Pe/this.chunkSize|0;return this.getter(Le)[Ue]}},k.prototype.setDataGetter=function(Pe){this.getter=Pe},k.prototype.cacheLength=function(){var Pe=new XMLHttpRequest;if(Pe.open("HEAD",_,!1),Pe.send(null),!(Pe.status>=200&&Pe.status<300||Pe.status===304))throw new Error("Couldn't load "+_+". Status: "+Pe.status);var Ue,Le=Number(Pe.getResponseHeader("Content-length")),st=(Ue=Pe.getResponseHeader("Accept-Ranges"))&&Ue==="bytes",gt=(Ue=Pe.getResponseHeader("Content-Encoding"))&&Ue==="gzip",ht=1048576;st||(ht=Le);var Wt=this;Wt.setDataGetter(Pt=>{var nr=Pt*ht,Vo=(Pt+1)*ht-1;if(Vo=Math.min(Vo,Le-1),Wt.chunks[Pt]===void 0&&(Wt.chunks[Pt]=((ti,As)=>{if(ti>As)throw new Error("invalid range ("+ti+", "+As+") or no bytes requested!");if(As>Le-1)throw new Error("only "+Le+" bytes available! programmer error!");var Yt=new XMLHttpRequest;if(Yt.open("GET",_,!1),Le!==ht&&Yt.setRequestHeader("Range","bytes="+ti+"-"+As),Yt.responseType="arraybuffer",Yt.overrideMimeType&&Yt.overrideMimeType("text/plain; charset=x-user-defined"),Yt.send(null),!(Yt.status>=200&&Yt.status<300||Yt.status===304))throw new Error("Couldn't load "+_+". Status: "+Yt.status);return Yt.response!==void 0?new Uint8Array(Yt.response||[]):pe(Yt.responseText||"",!0)})(nr,Vo)),Wt.chunks[Pt]===void 0)throw new Error("doXHR failed!");return Wt.chunks[Pt]}),!gt&&Le||(ht=Le=1,Le=this.getter(0).length,ht=Le,T("LazyFiles on gzip forces download of the whole file when length is accessed")),this._length=Le,this._chunkSize=ht,this.lengthKnown=!0},typeof XMLHttpRequest!="undefined"){if(!l)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var U=new k;Object.defineProperties(U,{length:{get:function(){return this.lengthKnown||this.cacheLength(),this._length}},chunkSize:{get:function(){return this.lengthKnown||this.cacheLength(),this._chunkSize}}});var V={isDevice:!1,contents:U}}else V={isDevice:!1,url:_};var ie=b.createFile(u,h,V,I,C);V.contents?ie.contents=V.contents:V.url&&(ie.contents=null,ie.url=V.url),Object.defineProperties(ie,{usedBytes:{get:function(){return this.contents.length}}});var K={};function Re(Pe,Ue,Le,st,gt){var ht=Pe.node.contents;if(gt>=ht.length)return 0;var Wt=Math.min(ht.length-gt,st);if(ht.slice)for(var Pt=0;Pt<Wt;Pt++)Ue[Le+Pt]=ht[gt+Pt];else for(Pt=0;Pt<Wt;Pt++)Ue[Le+Pt]=ht.get(gt+Pt);return Wt}return Object.keys(ie.stream_ops).forEach(Pe=>{var Ue=ie.stream_ops[Pe];K[Pe]=function(){return b.forceLoadFile(ie),Ue.apply(null,arguments)}}),K.read=(Pe,Ue,Le,st,gt)=>(b.forceLoadFile(ie),Re(Pe,Ue,Le,st,gt)),K.mmap=(Pe,Ue,Le,st,gt)=>{b.forceLoadFile(ie);var ht=X();if(!ht)throw new b.ErrnoError(48);return Re(Pe,M,ht,Ue,Le),{ptr:ht,allocated:!0}},ie.stream_ops=K,ie}},it=(u,h)=>u?Y(w,u,h):"",vt={DEFAULT_POLLMASK:5,calculateAt:function(u,h,_){if(we.isAbs(h))return h;var I;if(u===-100?I=b.cwd():I=vt.getStreamFromFD(u).path,h.length==0){if(!_)throw new b.ErrnoError(44);return I}return we.join2(I,h)},doStat:function(u,h,_){try{var I=u(h)}catch(V){if(V&&V.node&&we.normalize(h)!==we.normalize(b.getPath(V.node)))return-54;throw V}P[_>>2]=I.dev,P[_+4>>2]=I.mode,$[_+8>>2]=I.nlink,P[_+12>>2]=I.uid,P[_+16>>2]=I.gid,P[_+20>>2]=I.rdev,Ze=[I.size>>>0,(ne=I.size,+Math.abs(ne)>=1?ne>0?+Math.floor(ne/4294967296)>>>0:~~+Math.ceil((ne-+(~~ne>>>0))/4294967296)>>>0:0)],P[_+24>>2]=Ze[0],P[_+28>>2]=Ze[1],P[_+32>>2]=4096,P[_+36>>2]=I.blocks;var C=I.atime.getTime(),k=I.mtime.getTime(),U=I.ctime.getTime();return Ze=[Math.floor(C/1e3)>>>0,(ne=Math.floor(C/1e3),+Math.abs(ne)>=1?ne>0?+Math.floor(ne/4294967296)>>>0:~~+Math.ceil((ne-+(~~ne>>>0))/4294967296)>>>0:0)],P[_+40>>2]=Ze[0],P[_+44>>2]=Ze[1],$[_+48>>2]=C%1e3*1e3,Ze=[Math.floor(k/1e3)>>>0,(ne=Math.floor(k/1e3),+Math.abs(ne)>=1?ne>0?+Math.floor(ne/4294967296)>>>0:~~+Math.ceil((ne-+(~~ne>>>0))/4294967296)>>>0:0)],P[_+56>>2]=Ze[0],P[_+60>>2]=Ze[1],$[_+64>>2]=k%1e3*1e3,Ze=[Math.floor(U/1e3)>>>0,(ne=Math.floor(U/1e3),+Math.abs(ne)>=1?ne>0?+Math.floor(ne/4294967296)>>>0:~~+Math.ceil((ne-+(~~ne>>>0))/4294967296)>>>0:0)],P[_+72>>2]=Ze[0],P[_+76>>2]=Ze[1],$[_+80>>2]=U%1e3*1e3,Ze=[I.ino>>>0,(ne=I.ino,+Math.abs(ne)>=1?ne>0?+Math.floor(ne/4294967296)>>>0:~~+Math.ceil((ne-+(~~ne>>>0))/4294967296)>>>0:0)],P[_+88>>2]=Ze[0],P[_+92>>2]=Ze[1],0},doMsync:function(u,h,_,I,C){if(!b.isFile(h.node.mode))throw new b.ErrnoError(43);if(2&I)return 0;var k=w.slice(u,u+_);b.msync(h,k,C,_,I)},varargs:void 0,get:()=>(vt.varargs+=4,P[vt.varargs-4>>2]),getStr:u=>it(u),getStreamFromFD:function(u){return b.getStreamChecked(u)}};function Mr(u){switch(u){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError(`Unknown type size: ${u}`)}}var xr=void 0;function Ft(u){for(var h="",_=u;w[_];)h+=xr[w[_++]];return h}var G={},gr={},Di={},lr=void 0;function pt(u){throw new lr(u)}var _n=void 0;function kr(u){throw new _n(u)}function ei(u,h,_){function I(V){var ie=_(V);ie.length!==u.length&&kr("Mismatched type converter count");for(var K=0;K<u.length;++K)vr(u[K],ie[K])}u.forEach(function(V){Di[V]=h});var C=new Array(h.length),k=[],U=0;h.forEach((V,ie)=>{gr.hasOwnProperty(V)?C[ie]=gr[V]:(k.push(V),G.hasOwnProperty(V)||(G[V]=[]),G[V].push(()=>{C[ie]=gr[V],++U===k.length&&I(C)}))}),k.length===0&&I(C)}function vr(u,h,_={}){if(!("argPackAdvance"in h))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(I,C,k={}){var U=C.name;if(I||pt(`type "${U}" must have a positive integer typeid pointer`),gr.hasOwnProperty(I)){if(k.ignoreDuplicateRegistrations)return;pt(`Cannot register type '${U}' twice`)}if(gr[I]=C,delete Di[I],G.hasOwnProperty(I)){var V=G[I];delete G[I],V.forEach(ie=>ie())}}(u,h,_)}function Oi(u){if(!(this instanceof hi)||!(u instanceof hi))return!1;for(var h=this.$$.ptrType.registeredClass,_=this.$$.ptr,I=u.$$.ptrType.registeredClass,C=u.$$.ptr;h.baseClass;)_=h.upcast(_),h=h.baseClass;for(;I.baseClass;)C=I.upcast(C),I=I.baseClass;return h===I&&_===C}function Mi(u){pt(u.$$.ptrType.registeredClass.name+" instance already deleted")}var _s=!1;function fd(u){}function gd(u){u.count.value-=1,u.count.value===0&&function(h){h.smartPtr?h.smartPtrType.rawDestructor(h.smartPtr):h.ptrType.registeredClass.rawDestructor(h.ptr)}(u)}function _d(u,h,_){if(h===_)return u;if(_.baseClass===void 0)return null;var I=_d(u,h,_.baseClass);return I===null?null:_.downcast(I)}var Es={};function vh(){return Object.keys(ys).length}function Rh(){var u=[];for(var h in ys)ys.hasOwnProperty(h)&&u.push(ys[h]);return u}var Ts=[];function qr(){for(;Ts.length;){var u=Ts.pop();u.$$.deleteScheduled=!1,u.delete()}}var xi=void 0;function Ed(u){xi=u,Ts.length&&xi&&xi(qr)}var ys={};function Mo(u,h){return h=function(_,I){for(I===void 0&&pt("ptr should not be undefined");_.baseClass;)I=_.upcast(I),_=_.baseClass;return I}(u,h),ys[h]}function Ss(u,h){return h.ptrType&&h.ptr||kr("makeClassHandle requires ptr and ptrType"),!!h.smartPtrType!=!!h.smartPtr&&kr("Both smartPtrType and smartPtr must be specified"),h.count={value:1},xo(Object.create(u,{$$:{value:h}}))}function Td(u){var h=this.getPointee(u);if(!h)return this.destructor(u),null;var _=Mo(this.registeredClass,h);if(_!==void 0){if(_.$$.count.value===0)return _.$$.ptr=h,_.$$.smartPtr=u,_.clone();var I=_.clone();return this.destructor(u),I}function C(){return this.isSmartPointer?Ss(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:h,smartPtrType:this,smartPtr:u}):Ss(this.registeredClass.instancePrototype,{ptrType:this,ptr:u})}var k,U=this.registeredClass.getActualType(h),V=Es[U];if(!V)return C.call(this);k=this.isConst?V.constPointerType:V.pointerType;var ie=_d(h,this.registeredClass,k.registeredClass);return ie===null?C.call(this):this.isSmartPointer?Ss(k.registeredClass.instancePrototype,{ptrType:k,ptr:ie,smartPtrType:this,smartPtr:u}):Ss(k.registeredClass.instancePrototype,{ptrType:k,ptr:ie})}var xo=function(u){return typeof FinalizationRegistry=="undefined"?(xo=h=>h,u):(_s=new FinalizationRegistry(h=>{gd(h.$$)}),fd=h=>_s.unregister(h),(xo=h=>{var _=h.$$;if(_.smartPtr){var I={$$:_};_s.register(h,I,h)}return h})(u))};function yd(){if(this.$$.ptr||Mi(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var u,h=xo(Object.create(Object.getPrototypeOf(this),{$$:{value:(u=this.$$,{count:u.count,deleteScheduled:u.deleteScheduled,preservePointerOnDelete:u.preservePointerOnDelete,ptr:u.ptr,ptrType:u.ptrType,smartPtr:u.smartPtr,smartPtrType:u.smartPtrType})}}));return h.$$.count.value+=1,h.$$.deleteScheduled=!1,h}function Ch(){this.$$.ptr||Mi(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&pt("Object already scheduled for deletion"),fd(this),gd(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)}function Sd(){return!this.$$.ptr}function Id(){return this.$$.ptr||Mi(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&pt("Object already scheduled for deletion"),Ts.push(this),Ts.length===1&&xi&&xi(qr),this.$$.deleteScheduled=!0,this}function hi(){}function Rr(u){if(u===void 0)return"_unknown";var h=(u=u.replace(/[^a-zA-Z0-9_]/g,"$")).charCodeAt(0);return h>=48&&h<=57?`_${u}`:u}function En(u,h){return u=Rr(u),{[u]:function(){return h.apply(this,arguments)}}[u]}function bd(u,h,_){if(u[h].overloadTable===void 0){var I=u[h];u[h]=function(){return u[h].overloadTable.hasOwnProperty(arguments.length)||pt(`Function '${_}' called with an invalid number of arguments (${arguments.length}) - expects one of (${u[h].overloadTable})!`),u[h].overloadTable[arguments.length].apply(this,arguments)},u[h].overloadTable=[],u[h].overloadTable[I.argCount]=I}}function Tn(u,h,_,I,C,k,U,V){this.name=u,this.constructor=h,this.instancePrototype=_,this.rawDestructor=I,this.baseClass=C,this.getActualType=k,this.upcast=U,this.downcast=V,this.pureVirtualFunctions=[]}function Is(u,h,_){for(;h!==_;)h.upcast||pt(`Expected null or instance of ${_.name}, got an instance of ${h.name}`),u=h.upcast(u),h=h.baseClass;return u}function wh(u,h){if(h===null)return this.isReference&&pt(`null is not a valid ${this.name}`),0;h.$$||pt(`Cannot pass "${bn(h)}" as a ${this.name}`),h.$$.ptr||pt(`Cannot pass deleted object as a pointer of type ${this.name}`);var _=h.$$.ptrType.registeredClass;return Is(h.$$.ptr,_,this.registeredClass)}function Nh(u,h){var _;if(h===null)return this.isReference&&pt(`null is not a valid ${this.name}`),this.isSmartPointer?(_=this.rawConstructor(),u!==null&&u.push(this.rawDestructor,_),_):0;h.$$||pt(`Cannot pass "${bn(h)}" as a ${this.name}`),h.$$.ptr||pt(`Cannot pass deleted object as a pointer of type ${this.name}`),!this.isConst&&h.$$.ptrType.isConst&&pt(`Cannot convert argument of type ${h.$$.smartPtrType?h.$$.smartPtrType.name:h.$$.ptrType.name} to parameter type ${this.name}`);var I=h.$$.ptrType.registeredClass;if(_=Is(h.$$.ptr,I,this.registeredClass),this.isSmartPointer)switch(h.$$.smartPtr===void 0&&pt("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:h.$$.smartPtrType===this?_=h.$$.smartPtr:pt(`Cannot convert argument of type ${h.$$.smartPtrType?h.$$.smartPtrType.name:h.$$.ptrType.name} to parameter type ${this.name}`);break;case 1:_=h.$$.smartPtr;break;case 2:if(h.$$.smartPtrType===this)_=h.$$.smartPtr;else{var C=h.clone();_=this.rawShare(_,Po.toHandle(function(){C.delete()})),u!==null&&u.push(this.rawDestructor,_)}break;default:pt("Unsupporting sharing policy")}return _}function Ad(u,h){if(h===null)return this.isReference&&pt(`null is not a valid ${this.name}`),0;h.$$||pt(`Cannot pass "${bn(h)}" as a ${this.name}`),h.$$.ptr||pt(`Cannot pass deleted object as a pointer of type ${this.name}`),h.$$.ptrType.isConst&&pt(`Cannot convert argument of type ${h.$$.ptrType.name} to parameter type ${this.name}`);var _=h.$$.ptrType.registeredClass;return Is(h.$$.ptr,_,this.registeredClass)}function bs(u){return this.fromWireType(P[u>>2])}function Dh(u){return this.rawGetPointee&&(u=this.rawGetPointee(u)),u}function vd(u){this.rawDestructor&&this.rawDestructor(u)}function Oh(u){u!==null&&u.delete()}function mi(u,h,_,I,C,k,U,V,ie,K,Re){this.name=u,this.registeredClass=h,this.isReference=_,this.isConst=I,this.isSmartPointer=C,this.pointeeType=k,this.sharingPolicy=U,this.rawGetPointee=V,this.rawConstructor=ie,this.rawShare=K,this.rawDestructor=Re,C||h.baseClass!==void 0?this.toWireType=Nh:I?(this.toWireType=wh,this.destructorFunction=null):(this.toWireType=Ad,this.destructorFunction=null)}var yn=[],Rd=u=>{var h=yn[u];return h||(u>=yn.length&&(yn.length=u+1),yn[u]=h=L.get(u)),h},Mh=(u,h,_)=>u.includes("j")?((I,C,k)=>{var U=o["dynCall_"+I];return k&&k.length?U.apply(null,[C].concat(k)):U.call(null,C)})(u,h,_):Rd(h).apply(null,_);function ko(u,h){var _,I,C,k=(u=Ft(u)).includes("j")?(_=u,I=h,C=[],function(){return C.length=0,Object.assign(C,arguments),Mh(_,I,C)}):Rd(h);return typeof k!="function"&&pt(`unknown function pointer with signature ${u}: ${h}`),k}var Cd=void 0;function Sn(u){var h=fi(u),_=Ft(h);return hr(h),_}function In(u,h){var _=[],I={};throw h.forEach(function C(k){I[k]||gr[k]||(Di[k]?Di[k].forEach(C):(_.push(k),I[k]=!0))}),new Cd(`${u}: `+_.map(Sn).join([", "]))}function Ra(u,h){for(var _=[],I=0;I<u;I++)_.push($[h+4*I>>2]);return _}function wd(u){for(;u.length;){var h=u.pop();u.pop()(h)}}function Ca(u,h){if(!(u instanceof Function))throw new TypeError(`new_ called with constructor type ${typeof u} which is not a function`);var _=En(u.name||"unknownFunctionName",function(){});_.prototype=u.prototype;var I=new _,C=u.apply(I,h);return C instanceof Object?C:I}function Lo(u,h,_,I,C,k){var U=h.length;U<2&&pt("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var V=h[1]!==null&&_!==null,ie=!1,K=1;K<h.length;++K)if(h[K]!==null&&h[K].destructorFunction===void 0){ie=!0;break}var Re=h[0].name!=="void",Pe="",Ue="";for(K=0;K<U-2;++K)Pe+=(K!==0?", ":"")+"arg"+K,Ue+=(K!==0?", ":"")+"arg"+K+"Wired";var Le=`
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
throwBindingError('function ${u} called with ${arguments.length} arguments, expected ${U-2} args!');
|
|
57
|
-
}`;ie&&(Le+=`var destructors = [];
|
|
58
|
-
`);var st=ie?"destructors":"null",gt=["throwBindingError","invoker","fn","runDestructors","retType","classParam"],ht=[pt,I,C,wd,h[0],h[1]];for(V&&(Le+="var thisWired = classParam.toWireType("+st+`, this);
|
|
59
|
-
`),K=0;K<U-2;++K)Le+="var arg"+K+"Wired = argType"+K+".toWireType("+st+", arg"+K+"); // "+h[K+2].name+`
|
|
60
|
-
`,gt.push("argType"+K),ht.push(h[K+2]);if(V&&(Ue="thisWired"+(Ue.length>0?", ":"")+Ue),Le+=(Re||k?"var rv = ":"")+"invoker(fn"+(Ue.length>0?", ":"")+Ue+`);
|
|
61
|
-
`,ie)Le+=`runDestructors(destructors);
|
|
62
|
-
`;else for(K=V?1:2;K<h.length;++K){var Wt=K===1?"thisWired":"arg"+(K-2)+"Wired";h[K].destructorFunction!==null&&(Le+=Wt+"_dtor("+Wt+"); // "+h[K].name+`
|
|
63
|
-
`,gt.push(Wt+"_dtor"),ht.push(h[K].destructorFunction))}return Re&&(Le+=`var ret = retType.fromWireType(rv);
|
|
64
|
-
return ret;
|
|
65
|
-
`),Le+=`}
|
|
66
|
-
`,gt.push(Le),Ca(Function,gt).apply(null,ht)}function Nd(){this.allocated=[void 0],this.freelist=[]}var Cr=new Nd;function Dd(u){u>=Cr.reserved&&--Cr.get(u).refcount==0&&Cr.free(u)}function pi(){for(var u=0,h=Cr.reserved;h<Cr.allocated.length;++h)Cr.allocated[h]!==void 0&&++u;return u}var Po={toValue:u=>(u||pt("Cannot use deleted val. handle = "+u),Cr.get(u).value),toHandle:u=>{switch(u){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:return Cr.allocate({refcount:1,value:u})}}};function bn(u){if(u===null)return"null";var h=typeof u;return h==="object"||h==="array"||h==="function"?u.toString():""+u}function Od(u,h){switch(h){case 2:return function(_){return this.fromWireType(de[_>>2])};case 3:return function(_){return this.fromWireType(Ae[_>>3])};default:throw new TypeError("Unknown float type: "+u)}}function Md(u,h,_){switch(h){case 0:return _?function(I){return M[I]}:function(I){return w[I]};case 1:return _?function(I){return H[I>>1]}:function(I){return B[I>>1]};case 2:return _?function(I){return P[I>>2]}:function(I){return $[I>>2]};default:throw new TypeError("Unknown integer type: "+u)}}var N=typeof TextDecoder!="undefined"?new TextDecoder("utf-16le"):void 0,R=(u,h)=>{for(var _=u,I=_>>1,C=I+h/2;!(I>=C)&&B[I];)++I;if((_=I<<1)-u>32&&N)return N.decode(w.subarray(u,_));for(var k="",U=0;!(U>=h/2);++U){var V=H[u+2*U>>1];if(V==0)break;k+=String.fromCharCode(V)}return k},W=(u,h,_)=>{if(_===void 0&&(_=2147483647),_<2)return 0;for(var I=h,C=(_-=2)<2*u.length?_/2:u.length,k=0;k<C;++k){var U=u.charCodeAt(k);H[h>>1]=U,h+=2}return H[h>>1]=0,h-I},J=u=>2*u.length,he=(u,h)=>{for(var _=0,I="";!(_>=h/4);){var C=P[u+4*_>>2];if(C==0)break;if(++_,C>=65536){var k=C-65536;I+=String.fromCharCode(55296|k>>10,56320|1023&k)}else I+=String.fromCharCode(C)}return I},_e=(u,h,_)=>{if(_===void 0&&(_=2147483647),_<4)return 0;for(var I=h,C=I+_-4,k=0;k<u.length;++k){var U=u.charCodeAt(k);if(U>=55296&&U<=57343&&(U=65536+((1023&U)<<10)|1023&u.charCodeAt(++k)),P[h>>2]=U,(h+=4)+4>C)break}return P[h>>2]=0,h-I},ye=u=>{for(var h=0,_=0;_<u.length;++_){var I=u.charCodeAt(_);I>=55296&&I<=57343&&++_,h+=4}return h},ve={},Ce=[],Ee=[],Fe={},ct=()=>{if(!ct.strings){var u={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:d||"./this.program"};for(var h in Fe)Fe[h]===void 0?delete u[h]:u[h]=Fe[h];var _=[];for(var h in u)_.push(`${h}=${u[h]}`);ct.strings=_}return ct.strings},ot,je,dt,Ht=function(u,h,_,I){u||(u=this),this.parent=u,this.mount=u.mount,this.mounted=null,this.id=b.nextInode++,this.name=h,this.mode=_,this.node_ops={},this.stream_ops={},this.rdev=I},Dt=365,Kt=146;Object.defineProperties(Ht.prototype,{read:{get:function(){return(this.mode&Dt)===Dt},set:function(u){u?this.mode|=Dt:this.mode&=-366}},write:{get:function(){return(this.mode&Kt)===Kt},set:function(u){u?this.mode|=Kt:this.mode&=-147}},isFolder:{get:function(){return b.isDir(this.mode)}},isDevice:{get:function(){return b.isChrdev(this.mode)}}}),b.FSNode=Ht,b.createPreloadedFile=function(u,h,_,I,C,k,U,V,ie,K){var Re=h?S.resolve(we.join2(u,h)):u;function Pe(Ue){function Le(st){K&&K(),V||b.createDataFile(u,h,st,I,C,ie),k&&k(),Q()}(function(st,gt,ht,Wt){typeof Browser!="undefined"&&Browser.init();var Pt=!1;return Z.forEach(function(nr){Pt||nr.canHandle(gt)&&(nr.handle(st,gt,ht,Wt),Pt=!0)}),Pt})(Ue,Re,Le,()=>{U&&U(),Q()})||Le(Ue)}re(),typeof _=="string"?xe(_,Ue=>Pe(Ue),U):Pe(_)},b.staticInit(),function(){for(var u=new Array(256),h=0;h<256;++h)u[h]=String.fromCharCode(h);xr=u}(),lr=o.BindingError=class extends Error{constructor(u){super(u),this.name="BindingError"}},_n=o.InternalError=class extends Error{constructor(u){super(u),this.name="InternalError"}},hi.prototype.isAliasOf=Oi,hi.prototype.clone=yd,hi.prototype.delete=Ch,hi.prototype.isDeleted=Sd,hi.prototype.deleteLater=Id,o.getInheritedInstanceCount=vh,o.getLiveInheritedInstances=Rh,o.flushPendingDeletes=qr,o.setDelayFunction=Ed,mi.prototype.getPointee=Dh,mi.prototype.destructor=vd,mi.prototype.argPackAdvance=8,mi.prototype.readValueFromPointer=bs,mi.prototype.deleteObject=Oh,mi.prototype.fromWireType=Td,Cd=o.UnboundTypeError=(ot=Error,(dt=En(je="UnboundTypeError",function(u){this.name=je,this.message=u;var h=new Error(u).stack;h!==void 0&&(this.stack=this.toString()+`
|
|
67
|
-
`+h.replace(/^Error(:[^\n]*)?\n/,""))})).prototype=Object.create(ot.prototype),dt.prototype.constructor=dt,dt.prototype.toString=function(){return this.message===void 0?this.name:`${this.name}: ${this.message}`},dt),Object.assign(Nd.prototype,{get(u){return this.allocated[u]},has(u){return this.allocated[u]!==void 0},allocate(u){var h=this.freelist.pop()||this.allocated.length;return this.allocated[h]=u,h},free(u){this.allocated[u]=void 0,this.freelist.push(u)}}),Cr.allocated.push({value:void 0},{value:null},{value:!0},{value:!1}),Cr.reserved=Cr.allocated.length,o.count_emval_handles=pi;var Ot,_r={p:function(u,h,_){throw new wt(u).init(h,_),u},C:function(u,h,_){vt.varargs=_;try{var I=vt.getStreamFromFD(u);switch(h){case 0:return(C=vt.get())<0?-28:b.createStream(I,C).fd;case 1:case 2:case 6:case 7:return 0;case 3:return I.flags;case 4:var C=vt.get();return I.flags|=C,0;case 5:return C=vt.get(),H[C+0>>1]=2,0;case 16:case 8:default:return-28;case 9:return k=28,P[wa()>>2]=k,-1}}catch(U){if(b===void 0||U.name!=="ErrnoError")throw U;return-U.errno}var k},w:function(u,h,_,I){vt.varargs=I;try{h=vt.getStr(h),h=vt.calculateAt(u,h);var C=I?vt.get():0;return b.open(h,_,C).fd}catch(k){if(b===void 0||k.name!=="ErrnoError")throw k;return-k.errno}},t:function(u,h,_,I,C){},n:function(u,h,_,I,C){var k=Mr(_);vr(u,{name:h=Ft(h),fromWireType:function(U){return!!U},toWireType:function(U,V){return V?I:C},argPackAdvance:8,readValueFromPointer:function(U){var V;if(_===1)V=M;else if(_===2)V=H;else{if(_!==4)throw new TypeError("Unknown boolean type size: "+h);V=P}return this.fromWireType(V[U>>k])},destructorFunction:null})},r:function(u,h,_,I,C,k,U,V,ie,K,Re,Pe,Ue){Re=Ft(Re),k=ko(C,k),V&&(V=ko(U,V)),K&&(K=ko(ie,K)),Ue=ko(Pe,Ue);var Le=Rr(Re);(function(st,gt,ht){o.hasOwnProperty(st)?((ht===void 0||o[st].overloadTable!==void 0&&o[st].overloadTable[ht]!==void 0)&&pt(`Cannot register public name '${st}' twice`),bd(o,st,st),o.hasOwnProperty(ht)&&pt(`Cannot register multiple overloads of a function with the same number of arguments (${ht})!`),o[st].overloadTable[ht]=gt):(o[st]=gt,ht!==void 0&&(o[st].numArguments=ht))})(Le,function(){In(`Cannot construct ${Re} due to unbound types`,[I])}),ei([u,h,_],I?[I]:[],function(st){var gt,ht;st=st[0],ht=I?(gt=st.registeredClass).instancePrototype:hi.prototype;var Wt=En(Le,function(){if(Object.getPrototypeOf(this)!==Pt)throw new lr("Use 'new' to construct "+Re);if(nr.constructor_body===void 0)throw new lr(Re+" has no accessible constructor");var Yt=nr.constructor_body[arguments.length];if(Yt===void 0)throw new lr(`Tried to invoke ctor of ${Re} with invalid number of parameters (${arguments.length}) - expected (${Object.keys(nr.constructor_body).toString()}) parameters instead!`);return Yt.apply(this,arguments)}),Pt=Object.create(ht,{constructor:{value:Wt}});Wt.prototype=Pt;var nr=new Tn(Re,Wt,Pt,Ue,gt,k,V,K);nr.baseClass&&(nr.baseClass.__derivedClasses===void 0&&(nr.baseClass.__derivedClasses=[]),nr.baseClass.__derivedClasses.push(nr));var Vo=new mi(Re,nr,!0,!1,!1),ti=new mi(Re+"*",nr,!1,!1,!1),As=new mi(Re+" const*",nr,!1,!0,!1);return Es[u]={pointerType:ti,constPointerType:As},function(Yt,Ig,xh){o.hasOwnProperty(Yt)||kr("Replacing nonexistant public symbol"),o[Yt].overloadTable!==void 0&&xh!==void 0?o[Yt].overloadTable[xh]=Ig:(o[Yt]=Ig,o[Yt].argCount=xh)}(Le,Wt),[Vo,ti,As]})},q:function(u,h,_,I,C,k){var U=Ra(h,_);C=ko(I,C),ei([],[u],function(V){var ie=`constructor ${(V=V[0]).name}`;if(V.registeredClass.constructor_body===void 0&&(V.registeredClass.constructor_body=[]),V.registeredClass.constructor_body[h-1]!==void 0)throw new lr(`Cannot register multiple constructors with identical number of parameters (${h-1}) for class '${V.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`);return V.registeredClass.constructor_body[h-1]=()=>{In(`Cannot construct ${V.name} due to unbound types`,U)},ei([],U,function(K){return K.splice(1,0,null),V.registeredClass.constructor_body[h-1]=Lo(ie,K,null,C,k),[]}),[]})},d:function(u,h,_,I,C,k,U,V,ie){var K=Ra(_,I);h=Ft(h),k=ko(C,k),ei([],[u],function(Re){var Pe=`${(Re=Re[0]).name}.${h}`;function Ue(){In(`Cannot call ${Pe} due to unbound types`,K)}h.startsWith("@@")&&(h=Symbol[h.substring(2)]),V&&Re.registeredClass.pureVirtualFunctions.push(h);var Le=Re.registeredClass.instancePrototype,st=Le[h];return st===void 0||st.overloadTable===void 0&&st.className!==Re.name&&st.argCount===_-2?(Ue.argCount=_-2,Ue.className=Re.name,Le[h]=Ue):(bd(Le,h,Pe),Le[h].overloadTable[_-2]=Ue),ei([],K,function(gt){var ht=Lo(Pe,gt,Re,k,U,ie);return Le[h].overloadTable===void 0?(ht.argCount=_-2,Le[h]=ht):Le[h].overloadTable[_-2]=ht,[]}),[]})},D:function(u,h){vr(u,{name:h=Ft(h),fromWireType:function(_){var I=Po.toValue(_);return Dd(_),I},toWireType:function(_,I){return Po.toHandle(I)},argPackAdvance:8,readValueFromPointer:bs,destructorFunction:null})},k:function(u,h,_){var I=Mr(_);vr(u,{name:h=Ft(h),fromWireType:function(C){return C},toWireType:function(C,k){return k},argPackAdvance:8,readValueFromPointer:Od(h,I),destructorFunction:null})},c:function(u,h,_,I,C){h=Ft(h),C===-1&&(C=4294967295);var k=Mr(_),U=K=>K;if(I===0){var V=32-8*_;U=K=>K<<V>>>V}var ie=h.includes("unsigned");vr(u,{name:h,fromWireType:U,toWireType:ie?function(K,Re){return this.name,Re>>>0}:function(K,Re){return this.name,Re},argPackAdvance:8,readValueFromPointer:Md(h,k,I!==0),destructorFunction:null})},b:function(u,h,_){var I=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][h];function C(k){var U=$,V=U[k>>=2],ie=U[k+1];return new I(U.buffer,ie,V)}vr(u,{name:_=Ft(_),fromWireType:C,argPackAdvance:8,readValueFromPointer:C},{ignoreDuplicateRegistrations:!0})},j:function(u,h){var _=(h=Ft(h))==="std::string";vr(u,{name:h,fromWireType:function(I){var C,k=$[I>>2],U=I+4;if(_)for(var V=U,ie=0;ie<=k;++ie){var K=U+ie;if(ie==k||w[K]==0){var Re=it(V,K-V);C===void 0?C=Re:(C+="\0",C+=Re),V=K+1}}else{var Pe=new Array(k);for(ie=0;ie<k;++ie)Pe[ie]=String.fromCharCode(w[U+ie]);C=Pe.join("")}return hr(I),C},toWireType:function(I,C){var k;C instanceof ArrayBuffer&&(C=new Uint8Array(C));var U=typeof C=="string";U||C instanceof Uint8Array||C instanceof Uint8ClampedArray||C instanceof Int8Array||pt("Cannot pass non-string to std::string"),k=_&&U?O(C):C.length;var V=Uo(4+k+1),ie=V+4;if($[V>>2]=k,_&&U)F(C,w,ie,k+1);else if(U)for(var K=0;K<k;++K){var Re=C.charCodeAt(K);Re>255&&(hr(ie),pt("String has UTF-16 code units that do not fit in 8 bits")),w[ie+K]=Re}else for(K=0;K<k;++K)w[ie+K]=C[K];return I!==null&&I.push(hr,V),V},argPackAdvance:8,readValueFromPointer:bs,destructorFunction:function(I){hr(I)}})},f:function(u,h,_){var I,C,k,U,V;_=Ft(_),h===2?(I=R,C=W,U=J,k=()=>B,V=1):h===4&&(I=he,C=_e,U=ye,k=()=>$,V=2),vr(u,{name:_,fromWireType:function(ie){for(var K,Re=$[ie>>2],Pe=k(),Ue=ie+4,Le=0;Le<=Re;++Le){var st=ie+4+Le*h;if(Le==Re||Pe[st>>V]==0){var gt=I(Ue,st-Ue);K===void 0?K=gt:(K+="\0",K+=gt),Ue=st+h}}return hr(ie),K},toWireType:function(ie,K){typeof K!="string"&&pt(`Cannot pass non-string to C++ string type ${_}`);var Re=U(K),Pe=Uo(4+Re+h);return $[Pe>>2]=Re>>V,C(K,Pe+4,Re+h),ie!==null&&ie.push(hr,Pe),Pe},argPackAdvance:8,readValueFromPointer:bs,destructorFunction:function(ie){hr(ie)}})},o:function(u,h){vr(u,{isVoid:!0,name:h=Ft(h),argPackAdvance:0,fromWireType:function(){},toWireType:function(_,I){}})},g:function(u,h,_,I){var C,k;(u=Ce[u])(h=Po.toValue(h),_=(k=ve[C=_])===void 0?Ft(C):k,null,I)},m:Dd,l:function(u,h){var _=function(gt,ht){for(var Wt,Pt,nr,Vo=new Array(gt),ti=0;ti<gt;++ti)Vo[ti]=(Wt=$[ht+4*ti>>2],Pt="parameter "+ti,nr=void 0,(nr=gr[Wt])===void 0&&pt(Pt+" has unknown type "+Sn(Wt)),nr);return Vo}(u,h),I=_[0],C=I.name+"_$"+_.slice(1).map(function(gt){return gt.name}).join("_")+"$",k=Ee[C];if(k!==void 0)return k;for(var U=["retType"],V=[I],ie="",K=0;K<u-1;++K)ie+=(K!==0?", ":"")+"arg"+K,U.push("argType"+K),V.push(_[1+K]);var Re="return function "+Rr("methodCaller_"+C)+`(handle, name, destructors, args) {
|
|
68
|
-
`,Pe=0;for(K=0;K<u-1;++K)Re+=" var arg"+K+" = argType"+K+".readValueFromPointer(args"+(Pe?"+"+Pe:"")+`);
|
|
69
|
-
`,Pe+=_[K+1].argPackAdvance;for(Re+=" var rv = handle[name]("+ie+`);
|
|
70
|
-
`,K=0;K<u-1;++K)_[K+1].deleteObject&&(Re+=" argType"+K+".deleteObject(arg"+K+`);
|
|
71
|
-
`);I.isVoid||(Re+=` return retType.toWireType(destructors, rv);
|
|
72
|
-
`),Re+=`};
|
|
73
|
-
`,U.push(Re);var Ue,Le,st=Ca(Function,U).apply(null,V);return Ue=st,Le=Ce.length,Ce.push(Ue),k=Le,Ee[C]=k,k},a:()=>{q("")},e:function(){return Date.now()},v:()=>w.length,A:(u,h,_)=>w.copyWithin(u,h,h+_),u:u=>{w.length,q("OOM")},y:(u,h)=>{var _=0;return ct().forEach(function(I,C){var k=h+_;$[u+4*C>>2]=k,((U,V)=>{for(var ie=0;ie<U.length;++ie)M[0|V++]=U.charCodeAt(ie);M[0|V]=0})(I,k),_+=I.length+1}),0},z:(u,h)=>{var _=ct();$[u>>2]=_.length;var I=0;return _.forEach(function(C){I+=C.length+1}),$[h>>2]=I,0},i:function(u){try{var h=vt.getStreamFromFD(u);return b.close(h),0}catch(_){if(b===void 0||_.name!=="ErrnoError")throw _;return _.errno}},x:function(u,h){try{var _=vt.getStreamFromFD(u),I=_.tty?2:b.isDir(_.mode)?3:b.isLink(_.mode)?7:4;return M[h|0]=I,H[h+2>>1]=0,Ze=[0,(ne=0,+Math.abs(ne)>=1?ne>0?+Math.floor(ne/4294967296)>>>0:~~+Math.ceil((ne-+(~~ne>>>0))/4294967296)>>>0:0)],P[h+8>>2]=Ze[0],P[h+12>>2]=Ze[1],Ze=[0,(ne=0,+Math.abs(ne)>=1?ne>0?+Math.floor(ne/4294967296)>>>0:~~+Math.ceil((ne-+(~~ne>>>0))/4294967296)>>>0:0)],P[h+16>>2]=Ze[0],P[h+20>>2]=Ze[1],0}catch(C){if(b===void 0||C.name!=="ErrnoError")throw C;return C.errno}},B:function(u,h,_,I){try{var C=((k,U,V,ie)=>{for(var K=0,Re=0;Re<V;Re++){var Pe=$[U>>2],Ue=$[U+4>>2];U+=8;var Le=b.read(k,M,Pe,Ue,ie);if(Le<0)return-1;if(K+=Le,Le<Ue)break;ie!==void 0&&(ie+=Le)}return K})(vt.getStreamFromFD(u),h,_);return $[I>>2]=C,0}catch(k){if(b===void 0||k.name!=="ErrnoError")throw k;return k.errno}},s:function(u,h,_,I,C){var k,U,V=(U=_)+2097152>>>0<4194305-!!(k=h)?(k>>>0)+4294967296*U:NaN;try{if(isNaN(V))return 61;var ie=vt.getStreamFromFD(u);return b.llseek(ie,V,I),Ze=[ie.position>>>0,(ne=ie.position,+Math.abs(ne)>=1?ne>0?+Math.floor(ne/4294967296)>>>0:~~+Math.ceil((ne-+(~~ne>>>0))/4294967296)>>>0:0)],P[C>>2]=Ze[0],P[C+4>>2]=Ze[1],ie.getdents&&V===0&&I===0&&(ie.getdents=null),0}catch(K){if(b===void 0||K.name!=="ErrnoError")throw K;return K.errno}},h:function(u,h,_,I){try{var C=((k,U,V,ie)=>{for(var K=0,Re=0;Re<V;Re++){var Pe=$[U>>2],Ue=$[U+4>>2];U+=8;var Le=b.write(k,M,Pe,Ue,ie);if(Le<0)return-1;K+=Le,ie!==void 0&&(ie+=Le)}return K})(vt.getStreamFromFD(u),h,_);return $[I>>2]=C,0}catch(k){if(b===void 0||k.name!=="ErrnoError")throw k;return k.errno}}},Uo=(function(){var u,h,_,I,C={a:_r};function k(U,V){var ie,K,Re=U.exports;return y=(v=Re).E,ie=y.buffer,o.HEAP8=M=new Int8Array(ie),o.HEAP16=H=new Int16Array(ie),o.HEAP32=P=new Int32Array(ie),o.HEAPU8=w=new Uint8Array(ie),o.HEAPU16=B=new Uint16Array(ie),o.HEAPU32=$=new Uint32Array(ie),o.HEAPF32=de=new Float32Array(ie),o.HEAPF64=Ae=new Float64Array(ie),L=v.H,K=v.F,le.unshift(K),Q(),Re}if(re(),o.instantiateWasm)try{return o.instantiateWasm(C,k)}catch(U){E("Module.instantiateWasm callback failed with error: "+U),r(U)}(u=g,h=Be,_=C,I=function(U){k(U.instance)},u||typeof WebAssembly.instantiateStreaming!="function"||yt(h)||typeof fetch!="function"?at(h,_,I):fetch(h,{credentials:"same-origin"}).then(U=>WebAssembly.instantiateStreaming(U,_).then(I,function(V){return E("wasm streaming compile failed: "+V),E("falling back to ArrayBuffer instantiation"),at(h,_,I)}))).catch(r)}(),u=>(Uo=v.G)(u)),hr=u=>(hr=v.I)(u),wa=()=>(wa=v.J)(),fi=u=>(fi=v.K)(u),Na=(o.__embind_initialize_bindings=()=>(o.__embind_initialize_bindings=v.L)(),u=>(Na=v.M)(u));o.dynCall_jiji=(u,h,_,I,C)=>(o.dynCall_jiji=v.N)(u,h,_,I,C),o._ff_h264_cabac_tables=67061;function An(){function u(){Ot||(Ot=!0,o.calledRun=!0,te||(o.noFSInit||b.init.initialized||b.init(),b.ignorePermissions=!1,fe.init(),Lt(le),e(o),o.onRuntimeInitialized&&o.onRuntimeInitialized(),function(){if(o.postRun)for(typeof o.postRun=="function"&&(o.postRun=[o.postRun]);o.postRun.length;)h=o.postRun.shift(),He.unshift(h);var h;Lt(He)}()))}ge>0||(function(){if(o.preRun)for(typeof o.preRun=="function"&&(o.preRun=[o.preRun]);o.preRun.length;)h=o.preRun.shift(),A.unshift(h);var h;Lt(A)}(),ge>0||(o.setStatus?(o.setStatus("Running..."),setTimeout(function(){setTimeout(function(){o.setStatus("")},1),u()},1)):u()))}if(me=function u(){Ot||An(),Ot||(me=u)},o.preInit)for(typeof o.preInit=="function"&&(o.preInit=[o.preInit]);o.preInit.length>0;)o.preInit.pop()();return An(),t.ready}})(),lv=uv,hv=class extends Fc{constructor(i){super(lv,i!=null&&i.wasmPath?fetch(i==null?void 0:i.wasmPath).then(t=>t.arrayBuffer()):void 0,i==null?void 0:i.workerMode,i==null?void 0:i.canvas,i==null?void 0:i.yuvMode)}},v2=(()=>{var i=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return function(t={}){var e,r,o=t;o.ready=new Promise((N,R)=>{e=N,r=R});var s,n=Object.assign({},o),a=typeof window=="object",c=typeof importScripts=="function",d=(typeof process=="object"&&typeof process.versions=="object"&&process.versions.node,"");(a||c)&&(c?d=self.location.href:typeof document!="undefined"&&document.currentScript&&(d=document.currentScript.src),i&&(d=i),d=d.indexOf("blob:")!==0?d.substr(0,d.replace(/[?#].*/,"").lastIndexOf("/")+1):"",c&&(s=N=>{var R=new XMLHttpRequest;return R.open("GET",N,!1),R.responseType="arraybuffer",R.send(null),new Uint8Array(R.response)}));var m,l=o.print||console.log.bind(console),f=o.printErr||console.error.bind(console);Object.assign(o,n),n=null,o.arguments&&o.arguments,o.thisProgram&&o.thisProgram,o.quit&&o.quit,o.wasmBinary&&(m=o.wasmBinary);var g,T;o.noExitRuntime,typeof WebAssembly!="object"&&ge("no native wasm support detected");var E,y,v,M,w,H,B,P,$,de=!1,Ae=[],L=[],te=[],A=0,le=null,He=null;function ge(N){o.onAbort&&o.onAbort(N),f(N="Aborted("+N+")"),de=!0,N+=". Build with -sASSERTIONS for more info.";var R=new WebAssembly.RuntimeError(N);throw r(R),R}var ze,me;function re(N){return N.startsWith("data:application/octet-stream;base64,")}function Q(N){if(N==ze&&m)return new Uint8Array(m);if(s)return s(N);throw"both async and sync fetching of the wasm failed"}function q(N,R,W){return function(J){return m||!a&&!c||typeof fetch!="function"?Promise.resolve().then(()=>Q(J)):fetch(J,{credentials:"same-origin"}).then(he=>{if(!he.ok)throw"failed to load wasm binary file at '"+J+"'";return he.arrayBuffer()}).catch(()=>Q(J))}(N).then(J=>WebAssembly.instantiate(J,R)).then(J=>J).then(W,J=>{f("failed to asynchronously prepare wasm: "+J),ge(J)})}re(ze="videodec_simd.wasm")||(me=ze,ze=o.locateFile?o.locateFile(me,d):d+me);var Be=N=>{for(;N.length>0;)N.shift()(o)};function De(N){this.excPtr=N,this.ptr=N-24,this.set_type=function(R){H[this.ptr+4>>2]=R},this.get_type=function(){return H[this.ptr+4>>2]},this.set_destructor=function(R){H[this.ptr+8>>2]=R},this.get_destructor=function(){return H[this.ptr+8>>2]},this.set_caught=function(R){R=R?1:0,E[this.ptr+12|0]=R},this.get_caught=function(){return E[this.ptr+12|0]!=0},this.set_rethrown=function(R){R=R?1:0,E[this.ptr+13|0]=R},this.get_rethrown=function(){return E[this.ptr+13|0]!=0},this.init=function(R,W){this.set_adjusted_ptr(0),this.set_type(R),this.set_destructor(W)},this.set_adjusted_ptr=function(R){H[this.ptr+16>>2]=R},this.get_adjusted_ptr=function(){return H[this.ptr+16>>2]},this.get_exception_ptr=function(){if(Od(this.get_type()))return H[this.excPtr>>2];var R=this.get_adjusted_ptr();return R!==0?R:this.excPtr}}function ne(N){switch(N){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError(`Unknown type size: ${N}`)}}var Ze=void 0;function yt(N){for(var R="",W=N;y[W];)R+=Ze[y[W++]];return R}var ae={},at={},Lt={},wt=void 0;function we(N){throw new wt(N)}var fr=void 0;function S(N){throw new fr(N)}function ue(N,R,W){function J(ve){var Ce=W(ve);Ce.length!==N.length&&S("Mismatched type converter count");for(var Ee=0;Ee<N.length;++Ee)Y(N[Ee],Ce[Ee])}N.forEach(function(ve){Lt[ve]=R});var he=new Array(R.length),_e=[],ye=0;R.forEach((ve,Ce)=>{at.hasOwnProperty(ve)?he[Ce]=at[ve]:(_e.push(ve),ae.hasOwnProperty(ve)||(ae[ve]=[]),ae[ve].push(()=>{he[Ce]=at[ve],++ye===_e.length&&J(he)}))}),_e.length===0&&J(he)}function Y(N,R,W={}){if(!("argPackAdvance"in R))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(J,he,_e={}){var ye=he.name;if(J||we(`type "${ye}" must have a positive integer typeid pointer`),at.hasOwnProperty(J)){if(_e.ignoreDuplicateRegistrations)return;we(`Cannot register type '${ye}' twice`)}if(at[J]=he,delete Lt[J],ae.hasOwnProperty(J)){var ve=ae[J];delete ae[J],ve.forEach(Ce=>Ce())}}(N,R,W)}function x(N){if(!(this instanceof kr)||!(N instanceof kr))return!1;for(var R=this.$$.ptrType.registeredClass,W=this.$$.ptr,J=N.$$.ptrType.registeredClass,he=N.$$.ptr;R.baseClass;)W=R.upcast(W),R=R.baseClass;for(;J.baseClass;)he=J.upcast(he),J=J.baseClass;return R===J&&W===he}function O(N){we(N.$$.ptrType.registeredClass.name+" instance already deleted")}var F=!1;function pe(N){}function fe(N){N.count.value-=1,N.count.value===0&&function(R){R.smartPtr?R.smartPtrType.rawDestructor(R.smartPtr):R.ptrType.registeredClass.rawDestructor(R.ptr)}(N)}function X(N,R,W){if(R===W)return N;if(W.baseClass===void 0)return null;var J=X(N,R,W.baseClass);return J===null?null:W.downcast(J)}var oe={};function xe(){return Object.keys(Mr).length}function Z(){var N=[];for(var R in Mr)Mr.hasOwnProperty(R)&&N.push(Mr[R]);return N}var $e=[];function b(){for(;$e.length;){var N=$e.pop();N.$$.deleteScheduled=!1,N.delete()}}var it=void 0;function vt(N){it=N,$e.length&&it&&it(b)}var Mr={};function xr(N,R){return R=function(W,J){for(J===void 0&&we("ptr should not be undefined");W.baseClass;)J=W.upcast(J),W=W.baseClass;return J}(N,R),Mr[R]}function Ft(N,R){return R.ptrType&&R.ptr||S("makeClassHandle requires ptr and ptrType"),!!R.smartPtrType!=!!R.smartPtr&&S("Both smartPtrType and smartPtr must be specified"),R.count={value:1},gr(Object.create(N,{$$:{value:R}}))}function G(N){var R=this.getPointee(N);if(!R)return this.destructor(N),null;var W=xr(this.registeredClass,R);if(W!==void 0){if(W.$$.count.value===0)return W.$$.ptr=R,W.$$.smartPtr=N,W.clone();var J=W.clone();return this.destructor(N),J}function he(){return this.isSmartPointer?Ft(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:R,smartPtrType:this,smartPtr:N}):Ft(this.registeredClass.instancePrototype,{ptrType:this,ptr:N})}var _e,ye=this.registeredClass.getActualType(R),ve=oe[ye];if(!ve)return he.call(this);_e=this.isConst?ve.constPointerType:ve.pointerType;var Ce=X(R,this.registeredClass,_e.registeredClass);return Ce===null?he.call(this):this.isSmartPointer?Ft(_e.registeredClass.instancePrototype,{ptrType:_e,ptr:Ce,smartPtrType:this,smartPtr:N}):Ft(_e.registeredClass.instancePrototype,{ptrType:_e,ptr:Ce})}var gr=function(N){return typeof FinalizationRegistry=="undefined"?(gr=R=>R,N):(F=new FinalizationRegistry(R=>{fe(R.$$)}),pe=R=>F.unregister(R),(gr=R=>{var W=R.$$;if(W.smartPtr){var J={$$:W};F.register(R,J,R)}return R})(N))};function Di(){if(this.$$.ptr||O(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var N,R=gr(Object.create(Object.getPrototypeOf(this),{$$:{value:(N=this.$$,{count:N.count,deleteScheduled:N.deleteScheduled,preservePointerOnDelete:N.preservePointerOnDelete,ptr:N.ptr,ptrType:N.ptrType,smartPtr:N.smartPtr,smartPtrType:N.smartPtrType})}}));return R.$$.count.value+=1,R.$$.deleteScheduled=!1,R}function lr(){this.$$.ptr||O(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&we("Object already scheduled for deletion"),pe(this),fe(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)}function pt(){return!this.$$.ptr}function _n(){return this.$$.ptr||O(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&we("Object already scheduled for deletion"),$e.push(this),$e.length===1&&it&&it(b),this.$$.deleteScheduled=!0,this}function kr(){}function ei(N){if(N===void 0)return"_unknown";var R=(N=N.replace(/[^a-zA-Z0-9_]/g,"$")).charCodeAt(0);return R>=48&&R<=57?`_${N}`:N}function vr(N,R){return N=ei(N),{[N]:function(){return R.apply(this,arguments)}}[N]}function Oi(N,R,W){if(N[R].overloadTable===void 0){var J=N[R];N[R]=function(){return N[R].overloadTable.hasOwnProperty(arguments.length)||we(`Function '${W}' called with an invalid number of arguments (${arguments.length}) - expects one of (${N[R].overloadTable})!`),N[R].overloadTable[arguments.length].apply(this,arguments)},N[R].overloadTable=[],N[R].overloadTable[J.argCount]=J}}function Mi(N,R,W,J,he,_e,ye,ve){this.name=N,this.constructor=R,this.instancePrototype=W,this.rawDestructor=J,this.baseClass=he,this.getActualType=_e,this.upcast=ye,this.downcast=ve,this.pureVirtualFunctions=[]}function _s(N,R,W){for(;R!==W;)R.upcast||we(`Expected null or instance of ${W.name}, got an instance of ${R.name}`),N=R.upcast(N),R=R.baseClass;return N}function fd(N,R){if(R===null)return this.isReference&&we(`null is not a valid ${this.name}`),0;R.$$||we(`Cannot pass "${Is(R)}" as a ${this.name}`),R.$$.ptr||we(`Cannot pass deleted object as a pointer of type ${this.name}`);var W=R.$$.ptrType.registeredClass;return _s(R.$$.ptr,W,this.registeredClass)}function gd(N,R){var W;if(R===null)return this.isReference&&we(`null is not a valid ${this.name}`),this.isSmartPointer?(W=this.rawConstructor(),N!==null&&N.push(this.rawDestructor,W),W):0;R.$$||we(`Cannot pass "${Is(R)}" as a ${this.name}`),R.$$.ptr||we(`Cannot pass deleted object as a pointer of type ${this.name}`),!this.isConst&&R.$$.ptrType.isConst&&we(`Cannot convert argument of type ${R.$$.smartPtrType?R.$$.smartPtrType.name:R.$$.ptrType.name} to parameter type ${this.name}`);var J=R.$$.ptrType.registeredClass;if(W=_s(R.$$.ptr,J,this.registeredClass),this.isSmartPointer)switch(R.$$.smartPtr===void 0&&we("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:R.$$.smartPtrType===this?W=R.$$.smartPtr:we(`Cannot convert argument of type ${R.$$.smartPtrType?R.$$.smartPtrType.name:R.$$.ptrType.name} to parameter type ${this.name}`);break;case 1:W=R.$$.smartPtr;break;case 2:if(R.$$.smartPtrType===this)W=R.$$.smartPtr;else{var he=R.clone();W=this.rawShare(W,Tn.toHandle(function(){he.delete()})),N!==null&&N.push(this.rawDestructor,W)}break;default:we("Unsupporting sharing policy")}return W}function _d(N,R){if(R===null)return this.isReference&&we(`null is not a valid ${this.name}`),0;R.$$||we(`Cannot pass "${Is(R)}" as a ${this.name}`),R.$$.ptr||we(`Cannot pass deleted object as a pointer of type ${this.name}`),R.$$.ptrType.isConst&&we(`Cannot convert argument of type ${R.$$.ptrType.name} to parameter type ${this.name}`);var W=R.$$.ptrType.registeredClass;return _s(R.$$.ptr,W,this.registeredClass)}function Es(N){return this.fromWireType(w[N>>2])}function vh(N){return this.rawGetPointee&&(N=this.rawGetPointee(N)),N}function Rh(N){this.rawDestructor&&this.rawDestructor(N)}function Ts(N){N!==null&&N.delete()}function qr(N,R,W,J,he,_e,ye,ve,Ce,Ee,Fe){this.name=N,this.registeredClass=R,this.isReference=W,this.isConst=J,this.isSmartPointer=he,this.pointeeType=_e,this.sharingPolicy=ye,this.rawGetPointee=ve,this.rawConstructor=Ce,this.rawShare=Ee,this.rawDestructor=Fe,he||R.baseClass!==void 0?this.toWireType=gd:J?(this.toWireType=fd,this.destructorFunction=null):(this.toWireType=_d,this.destructorFunction=null)}var xi=[],Ed=N=>{var R=xi[N];return R||(N>=xi.length&&(xi.length=N+1),xi[N]=R=$.get(N)),R},ys=(N,R,W)=>N.includes("j")?((J,he,_e)=>{var ye=o["dynCall_"+J];return _e&&_e.length?ye.apply(null,[he].concat(_e)):ye.call(null,he)})(N,R,W):Ed(R).apply(null,W);function Mo(N,R){var W,J,he,_e=(N=yt(N)).includes("j")?(W=N,J=R,he=[],function(){return he.length=0,Object.assign(he,arguments),ys(W,J,he)}):Ed(R);return typeof _e!="function"&&we(`unknown function pointer with signature ${N}: ${R}`),_e}var Ss=void 0;function Td(N){var R=bn(N),W=yt(R);return pi(R),W}function xo(N,R){var W=[],J={};throw R.forEach(function he(_e){J[_e]||at[_e]||(Lt[_e]?Lt[_e].forEach(he):(W.push(_e),J[_e]=!0))}),new Ss(`${N}: `+W.map(Td).join([", "]))}function yd(N,R){for(var W=[],J=0;J<N;J++)W.push(H[R+4*J>>2]);return W}function Ch(N){for(;N.length;){var R=N.pop();N.pop()(R)}}function Sd(N,R){if(!(N instanceof Function))throw new TypeError(`new_ called with constructor type ${typeof N} which is not a function`);var W=vr(N.name||"unknownFunctionName",function(){});W.prototype=N.prototype;var J=new W,he=N.apply(J,R);return he instanceof Object?he:J}function Id(N,R,W,J,he,_e){var ye=R.length;ye<2&&we("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var ve=R[1]!==null&&W!==null,Ce=!1,Ee=1;Ee<R.length;++Ee)if(R[Ee]!==null&&R[Ee].destructorFunction===void 0){Ce=!0;break}var Fe=R[0].name!=="void",ct="",ot="";for(Ee=0;Ee<ye-2;++Ee)ct+=(Ee!==0?", ":"")+"arg"+Ee,ot+=(Ee!==0?", ":"")+"arg"+Ee+"Wired";var je=`
|
|
74
|
-
return function ${ei(N)}(${ct}) {
|
|
75
|
-
if (arguments.length !== ${ye-2}) {
|
|
76
|
-
throwBindingError('function ${N} called with ${arguments.length} arguments, expected ${ye-2} args!');
|
|
77
|
-
}`;Ce&&(je+=`var destructors = [];
|
|
78
|
-
`);var dt=Ce?"destructors":"null",Ht=["throwBindingError","invoker","fn","runDestructors","retType","classParam"],Dt=[we,J,he,Ch,R[0],R[1]];for(ve&&(je+="var thisWired = classParam.toWireType("+dt+`, this);
|
|
79
|
-
`),Ee=0;Ee<ye-2;++Ee)je+="var arg"+Ee+"Wired = argType"+Ee+".toWireType("+dt+", arg"+Ee+"); // "+R[Ee+2].name+`
|
|
80
|
-
`,Ht.push("argType"+Ee),Dt.push(R[Ee+2]);if(ve&&(ot="thisWired"+(ot.length>0?", ":"")+ot),je+=(Fe||_e?"var rv = ":"")+"invoker(fn"+(ot.length>0?", ":"")+ot+`);
|
|
81
|
-
`,Ce)je+=`runDestructors(destructors);
|
|
82
|
-
`;else for(Ee=ve?1:2;Ee<R.length;++Ee){var Kt=Ee===1?"thisWired":"arg"+(Ee-2)+"Wired";R[Ee].destructorFunction!==null&&(je+=Kt+"_dtor("+Kt+"); // "+R[Ee].name+`
|
|
83
|
-
`,Ht.push(Kt+"_dtor"),Dt.push(R[Ee].destructorFunction))}return Fe&&(je+=`var ret = retType.fromWireType(rv);
|
|
84
|
-
return ret;
|
|
85
|
-
`),je+=`}
|
|
86
|
-
`,Ht.push(je),Sd(Function,Ht).apply(null,Dt)}function hi(){this.allocated=[void 0],this.freelist=[]}var Rr=new hi;function En(N){N>=Rr.reserved&&--Rr.get(N).refcount==0&&Rr.free(N)}function bd(){for(var N=0,R=Rr.reserved;R<Rr.allocated.length;++R)Rr.allocated[R]!==void 0&&++N;return N}var Tn={toValue:N=>(N||we("Cannot use deleted val. handle = "+N),Rr.get(N).value),toHandle:N=>{switch(N){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:return Rr.allocate({refcount:1,value:N})}}};function Is(N){if(N===null)return"null";var R=typeof N;return R==="object"||R==="array"||R==="function"?N.toString():""+N}function wh(N,R){switch(R){case 2:return function(W){return this.fromWireType(B[W>>2])};case 3:return function(W){return this.fromWireType(P[W>>3])};default:throw new TypeError("Unknown float type: "+N)}}function Nh(N,R,W){switch(R){case 0:return W?function(J){return E[J]}:function(J){return y[J]};case 1:return W?function(J){return v[J>>1]}:function(J){return M[J>>1]};case 2:return W?function(J){return w[J>>2]}:function(J){return H[J>>2]};default:throw new TypeError("Unknown integer type: "+N)}}var Ad=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):void 0,bs=(N,R,W)=>{for(var J=R+W,he=R;N[he]&&!(he>=J);)++he;if(he-R>16&&N.buffer&&Ad)return Ad.decode(N.subarray(R,he));for(var _e="";R<he;){var ye=N[R++];if(128&ye){var ve=63&N[R++];if((224&ye)!=192){var Ce=63&N[R++];if((ye=(240&ye)==224?(15&ye)<<12|ve<<6|Ce:(7&ye)<<18|ve<<12|Ce<<6|63&N[R++])<65536)_e+=String.fromCharCode(ye);else{var Ee=ye-65536;_e+=String.fromCharCode(55296|Ee>>10,56320|1023&Ee)}}else _e+=String.fromCharCode((31&ye)<<6|ve)}else _e+=String.fromCharCode(ye)}return _e},Dh=(N,R)=>N?bs(y,N,R):"",vd=typeof TextDecoder!="undefined"?new TextDecoder("utf-16le"):void 0,Oh=(N,R)=>{for(var W=N,J=W>>1,he=J+R/2;!(J>=he)&&M[J];)++J;if((W=J<<1)-N>32&&vd)return vd.decode(y.subarray(N,W));for(var _e="",ye=0;!(ye>=R/2);++ye){var ve=v[N+2*ye>>1];if(ve==0)break;_e+=String.fromCharCode(ve)}return _e},mi=(N,R,W)=>{if(W===void 0&&(W=2147483647),W<2)return 0;for(var J=R,he=(W-=2)<2*N.length?W/2:N.length,_e=0;_e<he;++_e){var ye=N.charCodeAt(_e);v[R>>1]=ye,R+=2}return v[R>>1]=0,R-J},yn=N=>2*N.length,Rd=(N,R)=>{for(var W=0,J="";!(W>=R/4);){var he=w[N+4*W>>2];if(he==0)break;if(++W,he>=65536){var _e=he-65536;J+=String.fromCharCode(55296|_e>>10,56320|1023&_e)}else J+=String.fromCharCode(he)}return J},Mh=(N,R,W)=>{if(W===void 0&&(W=2147483647),W<4)return 0;for(var J=R,he=J+W-4,_e=0;_e<N.length;++_e){var ye=N.charCodeAt(_e);if(ye>=55296&&ye<=57343&&(ye=65536+((1023&ye)<<10)|1023&N.charCodeAt(++_e)),w[R>>2]=ye,(R+=4)+4>he)break}return w[R>>2]=0,R-J},ko=N=>{for(var R=0,W=0;W<N.length;++W){var J=N.charCodeAt(W);J>=55296&&J<=57343&&++W,R+=4}return R},Cd={},Sn=[],In=[],Ra;Ra=()=>performance.now();var wd,Ca,Lo,Nd=[null,[],[]];(function(){for(var N=new Array(256),R=0;R<256;++R)N[R]=String.fromCharCode(R);Ze=N})(),wt=o.BindingError=class extends Error{constructor(N){super(N),this.name="BindingError"}},fr=o.InternalError=class extends Error{constructor(N){super(N),this.name="InternalError"}},kr.prototype.isAliasOf=x,kr.prototype.clone=Di,kr.prototype.delete=lr,kr.prototype.isDeleted=pt,kr.prototype.deleteLater=_n,o.getInheritedInstanceCount=xe,o.getLiveInheritedInstances=Z,o.flushPendingDeletes=b,o.setDelayFunction=vt,qr.prototype.getPointee=vh,qr.prototype.destructor=Rh,qr.prototype.argPackAdvance=8,qr.prototype.readValueFromPointer=Es,qr.prototype.deleteObject=Ts,qr.prototype.fromWireType=G,Ss=o.UnboundTypeError=(wd=Error,(Lo=vr(Ca="UnboundTypeError",function(N){this.name=Ca,this.message=N;var R=new Error(N).stack;R!==void 0&&(this.stack=this.toString()+`
|
|
87
|
-
`+R.replace(/^Error(:[^\n]*)?\n/,""))})).prototype=Object.create(wd.prototype),Lo.prototype.constructor=Lo,Lo.prototype.toString=function(){return this.message===void 0?this.name:`${this.name}: ${this.message}`},Lo),Object.assign(hi.prototype,{get(N){return this.allocated[N]},has(N){return this.allocated[N]!==void 0},allocate(N){var R=this.freelist.pop()||this.allocated.length;return this.allocated[R]=N,R},free(N){this.allocated[N]=void 0,this.freelist.push(N)}}),Rr.allocated.push({value:void 0},{value:null},{value:!0},{value:!1}),Rr.reserved=Rr.allocated.length,o.count_emval_handles=bd;var Cr,Dd={o:function(N,R,W){throw new De(N).init(R,W),N},r:function(N,R,W,J,he){},m:function(N,R,W,J,he){var _e=ne(W);Y(N,{name:R=yt(R),fromWireType:function(ye){return!!ye},toWireType:function(ye,ve){return ve?J:he},argPackAdvance:8,readValueFromPointer:function(ye){var ve;if(W===1)ve=E;else if(W===2)ve=v;else{if(W!==4)throw new TypeError("Unknown boolean type size: "+R);ve=w}return this.fromWireType(ve[ye>>_e])},destructorFunction:null})},q:function(N,R,W,J,he,_e,ye,ve,Ce,Ee,Fe,ct,ot){Fe=yt(Fe),_e=Mo(he,_e),ve&&(ve=Mo(ye,ve)),Ee&&(Ee=Mo(Ce,Ee)),ot=Mo(ct,ot);var je=ei(Fe);(function(dt,Ht,Dt){o.hasOwnProperty(dt)?((Dt===void 0||o[dt].overloadTable!==void 0&&o[dt].overloadTable[Dt]!==void 0)&&we(`Cannot register public name '${dt}' twice`),Oi(o,dt,dt),o.hasOwnProperty(Dt)&&we(`Cannot register multiple overloads of a function with the same number of arguments (${Dt})!`),o[dt].overloadTable[Dt]=Ht):(o[dt]=Ht,Dt!==void 0&&(o[dt].numArguments=Dt))})(je,function(){xo(`Cannot construct ${Fe} due to unbound types`,[J])}),ue([N,R,W],J?[J]:[],function(dt){var Ht,Dt;dt=dt[0],Dt=J?(Ht=dt.registeredClass).instancePrototype:kr.prototype;var Kt=vr(je,function(){if(Object.getPrototypeOf(this)!==Ot)throw new wt("Use 'new' to construct "+Fe);if(_r.constructor_body===void 0)throw new wt(Fe+" has no accessible constructor");var fi=_r.constructor_body[arguments.length];if(fi===void 0)throw new wt(`Tried to invoke ctor of ${Fe} with invalid number of parameters (${arguments.length}) - expected (${Object.keys(_r.constructor_body).toString()}) parameters instead!`);return fi.apply(this,arguments)}),Ot=Object.create(Dt,{constructor:{value:Kt}});Kt.prototype=Ot;var _r=new Mi(Fe,Kt,Ot,ot,Ht,_e,ve,Ee);_r.baseClass&&(_r.baseClass.__derivedClasses===void 0&&(_r.baseClass.__derivedClasses=[]),_r.baseClass.__derivedClasses.push(_r));var Uo=new qr(Fe,_r,!0,!1,!1),hr=new qr(Fe+"*",_r,!1,!1,!1),wa=new qr(Fe+" const*",_r,!1,!0,!1);return oe[N]={pointerType:hr,constPointerType:wa},function(fi,Na,An){o.hasOwnProperty(fi)||S("Replacing nonexistant public symbol"),o[fi].overloadTable!==void 0&&An!==void 0?o[fi].overloadTable[An]=Na:(o[fi]=Na,o[fi].argCount=An)}(je,Kt),[Uo,hr,wa]})},p:function(N,R,W,J,he,_e){var ye=yd(R,W);he=Mo(J,he),ue([],[N],function(ve){var Ce=`constructor ${(ve=ve[0]).name}`;if(ve.registeredClass.constructor_body===void 0&&(ve.registeredClass.constructor_body=[]),ve.registeredClass.constructor_body[R-1]!==void 0)throw new wt(`Cannot register multiple constructors with identical number of parameters (${R-1}) for class '${ve.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`);return ve.registeredClass.constructor_body[R-1]=()=>{xo(`Cannot construct ${ve.name} due to unbound types`,ye)},ue([],ye,function(Ee){return Ee.splice(1,0,null),ve.registeredClass.constructor_body[R-1]=Id(Ce,Ee,null,he,_e),[]}),[]})},d:function(N,R,W,J,he,_e,ye,ve,Ce){var Ee=yd(W,J);R=yt(R),_e=Mo(he,_e),ue([],[N],function(Fe){var ct=`${(Fe=Fe[0]).name}.${R}`;function ot(){xo(`Cannot call ${ct} due to unbound types`,Ee)}R.startsWith("@@")&&(R=Symbol[R.substring(2)]),ve&&Fe.registeredClass.pureVirtualFunctions.push(R);var je=Fe.registeredClass.instancePrototype,dt=je[R];return dt===void 0||dt.overloadTable===void 0&&dt.className!==Fe.name&&dt.argCount===W-2?(ot.argCount=W-2,ot.className=Fe.name,je[R]=ot):(Oi(je,R,ct),je[R].overloadTable[W-2]=ot),ue([],Ee,function(Ht){var Dt=Id(ct,Ht,Fe,_e,ye,Ce);return je[R].overloadTable===void 0?(Dt.argCount=W-2,je[R]=Dt):je[R].overloadTable[W-2]=Dt,[]}),[]})},u:function(N,R){Y(N,{name:R=yt(R),fromWireType:function(W){var J=Tn.toValue(W);return En(W),J},toWireType:function(W,J){return Tn.toHandle(J)},argPackAdvance:8,readValueFromPointer:Es,destructorFunction:null})},k:function(N,R,W){var J=ne(W);Y(N,{name:R=yt(R),fromWireType:function(he){return he},toWireType:function(he,_e){return _e},argPackAdvance:8,readValueFromPointer:wh(R,J),destructorFunction:null})},b:function(N,R,W,J,he){R=yt(R),he===-1&&(he=4294967295);var _e=ne(W),ye=Ee=>Ee;if(J===0){var ve=32-8*W;ye=Ee=>Ee<<ve>>>ve}var Ce=R.includes("unsigned");Y(N,{name:R,fromWireType:ye,toWireType:Ce?function(Ee,Fe){return this.name,Fe>>>0}:function(Ee,Fe){return this.name,Fe},argPackAdvance:8,readValueFromPointer:Nh(R,_e,J!==0),destructorFunction:null})},a:function(N,R,W){var J=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][R];function he(_e){var ye=H,ve=ye[_e>>=2],Ce=ye[_e+1];return new J(ye.buffer,Ce,ve)}Y(N,{name:W=yt(W),fromWireType:he,argPackAdvance:8,readValueFromPointer:he},{ignoreDuplicateRegistrations:!0})},j:function(N,R){var W=(R=yt(R))==="std::string";Y(N,{name:R,fromWireType:function(J){var he,_e=H[J>>2],ye=J+4;if(W)for(var ve=ye,Ce=0;Ce<=_e;++Ce){var Ee=ye+Ce;if(Ce==_e||y[Ee]==0){var Fe=Dh(ve,Ee-ve);he===void 0?he=Fe:(he+="\0",he+=Fe),ve=Ee+1}}else{var ct=new Array(_e);for(Ce=0;Ce<_e;++Ce)ct[Ce]=String.fromCharCode(y[ye+Ce]);he=ct.join("")}return pi(J),he},toWireType:function(J,he){var _e;he instanceof ArrayBuffer&&(he=new Uint8Array(he));var ye=typeof he=="string";ye||he instanceof Uint8Array||he instanceof Uint8ClampedArray||he instanceof Int8Array||we("Cannot pass non-string to std::string"),_e=W&&ye?(ct=>{for(var ot=0,je=0;je<ct.length;++je){var dt=ct.charCodeAt(je);dt<=127?ot++:dt<=2047?ot+=2:dt>=55296&&dt<=57343?(ot+=4,++je):ot+=3}return ot})(he):he.length;var ve=Po(4+_e+1),Ce=ve+4;if(H[ve>>2]=_e,W&&ye)((ct,ot,je,dt)=>{if(!(dt>0))return 0;for(var Ht=je,Dt=je+dt-1,Kt=0;Kt<ct.length;++Kt){var Ot=ct.charCodeAt(Kt);if(Ot>=55296&&Ot<=57343&&(Ot=65536+((1023&Ot)<<10)|1023&ct.charCodeAt(++Kt)),Ot<=127){if(je>=Dt)break;ot[je++]=Ot}else if(Ot<=2047){if(je+1>=Dt)break;ot[je++]=192|Ot>>6,ot[je++]=128|63&Ot}else if(Ot<=65535){if(je+2>=Dt)break;ot[je++]=224|Ot>>12,ot[je++]=128|Ot>>6&63,ot[je++]=128|63&Ot}else{if(je+3>=Dt)break;ot[je++]=240|Ot>>18,ot[je++]=128|Ot>>12&63,ot[je++]=128|Ot>>6&63,ot[je++]=128|63&Ot}}ot[je]=0})(he,y,Ce,_e+1);else if(ye)for(var Ee=0;Ee<_e;++Ee){var Fe=he.charCodeAt(Ee);Fe>255&&(pi(Ce),we("String has UTF-16 code units that do not fit in 8 bits")),y[Ce+Ee]=Fe}else for(Ee=0;Ee<_e;++Ee)y[Ce+Ee]=he[Ee];return J!==null&&J.push(pi,ve),ve},argPackAdvance:8,readValueFromPointer:Es,destructorFunction:function(J){pi(J)}})},g:function(N,R,W){var J,he,_e,ye,ve;W=yt(W),R===2?(J=Oh,he=mi,ye=yn,_e=()=>M,ve=1):R===4&&(J=Rd,he=Mh,ye=ko,_e=()=>H,ve=2),Y(N,{name:W,fromWireType:function(Ce){for(var Ee,Fe=H[Ce>>2],ct=_e(),ot=Ce+4,je=0;je<=Fe;++je){var dt=Ce+4+je*R;if(je==Fe||ct[dt>>ve]==0){var Ht=J(ot,dt-ot);Ee===void 0?Ee=Ht:(Ee+="\0",Ee+=Ht),ot=dt+R}}return pi(Ce),Ee},toWireType:function(Ce,Ee){typeof Ee!="string"&&we(`Cannot pass non-string to C++ string type ${W}`);var Fe=ye(Ee),ct=Po(4+Fe+R);return H[ct>>2]=Fe>>ve,he(Ee,ct+4,Fe+R),Ce!==null&&Ce.push(pi,ct),ct},argPackAdvance:8,readValueFromPointer:Es,destructorFunction:function(Ce){pi(Ce)}})},n:function(N,R){Y(N,{isVoid:!0,name:R=yt(R),argPackAdvance:0,fromWireType:function(){},toWireType:function(W,J){}})},e:function(N,R,W,J){var he,_e;(N=Sn[N])(R=Tn.toValue(R),W=(_e=Cd[he=W])===void 0?yt(he):_e,null,J)},l:En,h:function(N,R){var W=function(Ht,Dt){for(var Kt,Ot,_r,Uo=new Array(Ht),hr=0;hr<Ht;++hr)Uo[hr]=(Kt=H[Dt+4*hr>>2],Ot="parameter "+hr,_r=void 0,(_r=at[Kt])===void 0&&we(Ot+" has unknown type "+Td(Kt)),_r);return Uo}(N,R),J=W[0],he=J.name+"_$"+W.slice(1).map(function(Ht){return Ht.name}).join("_")+"$",_e=In[he];if(_e!==void 0)return _e;for(var ye=["retType"],ve=[J],Ce="",Ee=0;Ee<N-1;++Ee)Ce+=(Ee!==0?", ":"")+"arg"+Ee,ye.push("argType"+Ee),ve.push(W[1+Ee]);var Fe="return function "+ei("methodCaller_"+he)+`(handle, name, destructors, args) {
|
|
88
|
-
`,ct=0;for(Ee=0;Ee<N-1;++Ee)Fe+=" var arg"+Ee+" = argType"+Ee+".readValueFromPointer(args"+(ct?"+"+ct:"")+`);
|
|
89
|
-
`,ct+=W[Ee+1].argPackAdvance;for(Fe+=" var rv = handle[name]("+Ce+`);
|
|
90
|
-
`,Ee=0;Ee<N-1;++Ee)W[Ee+1].deleteObject&&(Fe+=" argType"+Ee+".deleteObject(arg"+Ee+`);
|
|
91
|
-
`);J.isVoid||(Fe+=` return retType.toWireType(destructors, rv);
|
|
92
|
-
`),Fe+=`};
|
|
93
|
-
`,ye.push(Fe);var ot,je,dt=Sd(Function,ye).apply(null,ve);return ot=dt,je=Sn.length,Sn.push(ot),_e=je,In[he]=_e,_e},f:()=>{ge("")},c:Ra,t:(N,R,W)=>y.copyWithin(N,R,R+W),s:N=>{y.length,ge("OOM")},i:(N,R,W,J)=>{for(var he,_e,ye,ve=0,Ce=0;Ce<W;Ce++){var Ee=H[R>>2],Fe=H[R+4>>2];R+=8;for(var ct=0;ct<Fe;ct++)he=N,_e=y[Ee+ct],ye=void 0,ye=Nd[he],_e===0||_e===10?((he===1?l:f)(bs(ye,0)),ye.length=0):ye.push(_e);ve+=Fe}return H[J>>2]=ve,0}},pi=(function(){var N,R,W,J,he={a:Dd};function _e(ye,ve){var Ce,Ee,Fe=ye.exports;return g=(T=Fe).v,Ce=g.buffer,o.HEAP8=E=new Int8Array(Ce),o.HEAP16=v=new Int16Array(Ce),o.HEAP32=w=new Int32Array(Ce),o.HEAPU8=y=new Uint8Array(Ce),o.HEAPU16=M=new Uint16Array(Ce),o.HEAPU32=H=new Uint32Array(Ce),o.HEAPF32=B=new Float32Array(Ce),o.HEAPF64=P=new Float64Array(Ce),$=T.z,Ee=T.w,L.unshift(Ee),function(){if(A--,o.monitorRunDependencies&&o.monitorRunDependencies(A),A==0&&(le!==null&&(clearInterval(le),le=null),He)){var ct=He;He=null,ct()}}(),Fe}if(A++,o.monitorRunDependencies&&o.monitorRunDependencies(A),o.instantiateWasm)try{return o.instantiateWasm(he,_e)}catch(ye){f("Module.instantiateWasm callback failed with error: "+ye),r(ye)}(N=m,R=ze,W=he,J=function(ye){_e(ye.instance)},N||typeof WebAssembly.instantiateStreaming!="function"||re(R)||typeof fetch!="function"?q(R,W,J):fetch(R,{credentials:"same-origin"}).then(ye=>WebAssembly.instantiateStreaming(ye,W).then(J,function(ve){return f("wasm streaming compile failed: "+ve),f("falling back to ArrayBuffer instantiation"),q(R,W,J)}))).catch(r)}(),N=>(pi=T.x)(N)),Po=N=>(Po=T.y)(N),bn=N=>(bn=T.A)(N),Od=(o.__embind_initialize_bindings=()=>(o.__embind_initialize_bindings=T.B)(),N=>(Od=T.C)(N));o.dynCall_jiji=(N,R,W,J,he)=>(o.dynCall_jiji=T.D)(N,R,W,J,he);function Md(){function N(){Cr||(Cr=!0,o.calledRun=!0,de||(Be(L),e(o),o.onRuntimeInitialized&&o.onRuntimeInitialized(),function(){if(o.postRun)for(typeof o.postRun=="function"&&(o.postRun=[o.postRun]);o.postRun.length;)R=o.postRun.shift(),te.unshift(R);var R;Be(te)}()))}A>0||(function(){if(o.preRun)for(typeof o.preRun=="function"&&(o.preRun=[o.preRun]);o.preRun.length;)R=o.preRun.shift(),Ae.unshift(R);var R;Be(Ae)}(),A>0||(o.setStatus?(o.setStatus("Running..."),setTimeout(function(){setTimeout(function(){o.setStatus("")},1),N()},1)):N()))}if(He=function N(){Cr||Md(),Cr||(He=N)},o.preInit)for(typeof o.preInit=="function"&&(o.preInit=[o.preInit]);o.preInit.length>0;)o.preInit.pop()();return Md(),t.ready}})();var dT=(i=>(i.ROOM_DESTROY="1",i.JOIN_START="21",i.JOIN_SCHEDULE_SUCCESS="22",i.JOIN_SIGNAL_CONNECTION_START="23",i.JOIN_SIGNAL_CONNECTION_END="24",i.JOIN_SEND_CMD="25",i.JOIN_RECEIVED_CMD_RES="26",i.JOIN_SUCCESS="27",i.JOIN_FAILED="28",i.LEAVE_START="51",i.LEAVE_SEND_CMD="52",i.LEAVE_SUCCESS="53",i.PUBLISH_START="61",i.SEND_FIRST_VIDEO_FRAME="62",i.PUBLISH_FAILED="63",i.SUBSCRIBE_START="81",i.SUBSCRIBE_SUCCESS="82",i.SUBSCRIBE_FAILED="84",i.UNSUBSCRIBE_SUCCESS="83",i.LOCAL_TRACK_CAPTURE_START="101",i.LOCAL_TRACK_CAPTURE_SUCCESS="102",i.LOCAL_TRACK_CAPTURE_FAILED="103",i.LOCAL_TRACK_PUBLISHED="104",i.LOCAL_TRACK_UNPUBLISHED="105",i.LOCAL_TRACK_REPLACED="106",i.SWITCH_DEVICE_SUCCESS="107",i.TRACK_MUTED="108",i.TRACK_UNMUTED="109",i.REMOTE_TRACK_SUBSCRIBED="110",i.REMOTE_TRACK_UNSUBSCRIBED="111",i.LOCAL_TRACK_RECAPTURE="112",i.LOCAL_AUDIO_STARTED="113",i.LOCAL_AUDIO_STOPPED="114",i.REMOTE_AUDIO_STARTED="115",i.REMOTE_AUDIO_STOPPED="116",i.PLAY_TRACK_START="151",i.PLAYER_STATE_CHANGED="152",i.VIDEO_LOADED_DATA="153",i.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",i.AUDIO_CONTEXT_LONG_SUSPENDED="155",i.REMOTE_VIDEO_PLAY_START="156",i.REMOTE_VIDEO_PLAY_FINISH="157",i.SIGNAL_CONNECTION_STATE_CHANGED="201",i.PEER_CONNECTION_STATE_CHANGED="202",i.SINGLE_CONNECTION_STAT="203",i.SPC_RECONNECTED="204",i.HEARTBEAT_REPORT="251",i.RECEIVED_PUBLISHED_USER_LIST="252",i.REMOTE_PUBLISH_STATE_CHANGED="253",i.AUDIO_LEVEL_INTERVAL="260",i.NETWORK_QUALITY="261",i.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",i.QUALITY_LIMITATION_CHANGED="263",i.LOG="264",i.AUDIO_PROCESSOR_DEBUG="265",i.SSO_SWITCH="266",i.SWITCH_ROOM_START="401",i.SWITCH_ROOM_SUCCESS="407",i.SWITCH_ROOM_FAILED="408",i))(dT||{}),mv="5.0.0",pv=typeof importScripts!="undefined",fv=typeof registerProcessor!="undefined",gv="",_v="web.sdk.qcloud.com",Ev=`https://${_v}/trtc/webrtc/doc`,R2=`${Ev}/zh-cn/`,Tv="https://yun.tim.qq.com",yv="https://apisgp.my-imcloud.com",Sv={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},cn=(i=>(i[i.TRACE=0]="TRACE",i[i.DEBUG=1]="DEBUG",i[i.INFO=2]="INFO",i[i.WARN=3]="WARN",i[i.ERROR=4]="ERROR",i[i.NONE=5]="NONE",i))(cn||{});var uT={"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}},C2=uT["480p_2"],w2=uT["120p_2"],Ol={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"},N2=Ol.MAIN,D2=Ol.AUXILIARY,O2=Ol.BIG,M2=Ol.SMALL;var x2=Object.keys(cn);var Iv=function(i,t,e,r){return new(e||(e=Promise))(function(o,s){function n(d){try{c(r.next(d))}catch(m){s(m)}}function a(d){try{c(r.throw(d))}catch(m){s(m)}}function c(d){var m;d.done?o(d.value):(m=d.value,m instanceof e?m:new e(function(l){l(m)})).then(n,a)}c((r=r.apply(i,t||[])).next())})},Sf=Symbol(32),If=Symbol(16),bf=Symbol(8),ga=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,t){return t&&this.consume(),this.need=i,this.flush()}read(i){return Iv(this,void 0,void 0,function*(){return this.lastReadPromise&&(yield this.lastReadPromise),this.lastReadPromise=new Promise((t,e)=>{var r;this.reject=e,this.resolve=o=>{delete this.lastReadPromise,delete this.resolve,delete this.need,t(o)},this.demand(i,!0)||(r=this.pull)===null||r===void 0||r.call(this,i)})})}readU32(){return this.read(Sf)}readU16(){return this.read(If)}readU8(){return this.read(bf)}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,t=this.buffer.subarray(this.consumed),e=0,r=o=>t.length<(e=o);if(typeof this.need=="number"){if(r(this.need))return;i=t.subarray(0,e)}else if(this.need===Sf){if(r(4))return;i=t[0]<<24|t[1]<<16|t[2]<<8|t[3]}else if(this.need===If){if(r(2))return;i=t[0]<<8|t[1]}else if(this.need===bf){if(r(1))return;i=t[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(t.subarray(0,e)),i=this.need}else if(this.g)return void this.g.throw(new Error("Unsupported type"))}else{if(r(this.need.byteLength))return;new Uint8Array(this.need).set(t.subarray(0,e)),i=this.need}return this.consumed+=e,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)return new Promise(t=>this.pull=t);this.flush()}writeU32(i){this.malloc(4).set([i>>24&255,i>>16&255,i>>8&255,255&i]),this.flush()}writeU16(i){this.malloc(2).set([i>>8&255,255&i]),this.flush()}writeU8(i){this.malloc(1)[0]=i,this.flush()}malloc(i){if(this.buffer){let t=this.buffer.length,e=t+i;if(e<=this.buffer.buffer.byteLength-this.buffer.byteOffset)this.buffer=new Uint8Array(this.buffer.buffer,this.buffer.byteOffset,e);else{let r=new Uint8Array(e);r.set(this.buffer),this.buffer=r}return this.buffer.subarray(t,e)}return this.buffer=new Uint8Array(i),this.buffer}};ga.U32=Sf,ga.U16=If,ga.U8=bf;var bv=128,Av=127,k2=~Av,L2=Math.pow(2,31);function ff(i){let t=new ga;for(;i>=128;)t.malloc(1)[0]=255&i|bv,i>>>=7;return t.malloc(1)[0]=255&i,t.buffer||new Uint8Array(0)}function Af(i,t=0){let e=new ga,r=t<<3;switch(typeof i){case"boolean":let o=e.malloc(2);o[0]=r,o[1]=i?1:0;break;case"number":e.malloc(1)[0]=r,e.write(ff(i));break;case"string":e.malloc(1)[0]=2|r;let s=new TextEncoder().encode(i);e.write(ff(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 ga;if(Array.isArray(i))for(let c=0;c<i.length;c++){let d=Af(i[c],c+1);d&&a.write(d)}else{let c=1;for(let d in i){let m=Af(i[d],c++);m&&a.write(m)}}t===0?a.buffer&&e.write(a.buffer):(e.malloc(1)[0]=2|r,a.buffer&&(e.write(ff(a.buffer.length)),e.write(a.buffer)))}return e.buffer||new Uint8Array(0)}var XE=class{constructor(){xt(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(255&i)}writeInt16(i){this.buffer.push(i>>>8&255),this.buffer.push(255&i)}writeByte(i){this.buffer.push(255&i)}writeBytes(i){for(let t=0;t<i.length;t++)this.buffer.push(i[t])}};function JE(i,t,e){i[e]=t>>>24&255,i[e+1]=t>>>16&255,i[e+2]=t>>>8&255,i[e+3]=255&t}function jr(i,t){return i[t]<<24|i[t+1]<<16|i[t+2]<<8|i[t+3]}function QE(i,t){return i[t]}function Bc(i,t,e){return new TextDecoder().decode(vv(i,t,e))}function vv(i,t,e){return i.slice(t,t+e)}var gf=0,vf=2654435769,Rf=16,YE=4,jc=2,qc=7;function Rv(i,t,e,r="AVQualityReportSvc.C2S",o=2e3,s=2,n=30){return{version:o,encryption:s,d2:"",d2Len:0,uinType:n,uin:"",uinLen:0,reqHead:{seqNumber:e,appId:i,appidAtThird:new Uint8Array(0),a2:"",a2Len:0,serviceCmd:r,serviceCmdLen:0,cookie:"",cookieLen:0,imei:"",imeiLen:0,ksid:"",ksidLen:0,clientVersionInfo:"",clientVersionInfoLen:0},busiBuff:t}}function Cv(i,t){let e=new XE,r=Rv(t,i,gf);gf=gf+1&2147483647,e.writeInt32(0),e.writeInt32(r.version),e.writeByte(r.encryption);let o=new TextEncoder().encode(r.d2);e.writeInt32(o.length+4),o&&e.writeBytes(o),e.writeByte(r.uinType);let s=new TextEncoder().encode(r.uin);e.writeInt32(s.length+4),s.length&&e.writeBytes(s);let n=new XE;n.writeInt32(0),n.writeInt32(r.reqHead.seqNumber),n.writeInt32(r.reqHead.appId),n.writeByte(r.reqHead.appId>>>24&255),n.writeByte(r.reqHead.appId>>>16&255),n.writeByte(r.reqHead.appId>>>8&255),n.writeByte(255&r.reqHead.appId);for(let M=4;M<16;M++)n.writeByte(0);let a=new TextEncoder().encode(r.reqHead.a2);n.writeInt32(a.length+4),a.length&&n.writeBytes(a);let c=new TextEncoder().encode(r.reqHead.serviceCmd);n.writeInt32(c.length+4),c.length&&n.writeBytes(c);let d=new TextEncoder().encode(r.reqHead.cookie);n.writeInt32(d.length+4),d.length&&n.writeBytes(d);let m=new TextEncoder().encode(r.reqHead.imei);n.writeInt32(m.length+4),m.length&&n.writeBytes(m);let l=new TextEncoder().encode(r.reqHead.ksid);n.writeInt32(l.length+4),l.length&&n.writeBytes(l);let f=new TextEncoder().encode(r.reqHead.clientVersionInfo);n.writeInt16(f.length+2),f.length&&n.writeBytes(f);let g=n.length;n.data[0]=g>>>24&255,n.data[1]=g>>>16&255,n.data[2]=g>>>8&255,n.data[3]=255&g,Cf(i)&&(i=new TextEncoder().encode(i)),n.writeInt32(i.length+4),i.length&&n.writeBytes(i);let T=new Uint8Array(n.data),E=null;r.encryption===1?E=new TextEncoder().encode(r.uin):r.encryption===2&&(E=new Uint8Array(16)),E&&(T=wv(T,E)),e.writeBytes(T);let y=new Uint8Array(e.data),v=y.length;return y[0]=v>>>24&255,y[1]=v>>>16&255,y[2]=v>>>8&255,y[3]=255&v,y}function wv(i,t){let e=i.length,r=(e+1+jc+qc)%8;r&&(r=8-r);let o=new Uint8Array(e+1+jc+qc+r),s=0,n=new Uint8Array(8),a=new Uint8Array(8),c=new Uint8Array(8),d=0;n[0]=248&Math.floor(256*Math.random())|r,d=1;for(let l=0;l<r;l++)n[d]=255&Math.floor(256*Math.random()),d+=1;for(let l=0;l<jc;)if(d<8&&(n[d]=255&Math.floor(256*Math.random()),d+=1,l+=1),d===8){_f(n,t,a,c,o,s),s+=8,d=0;for(let f=0;f<8;f++)c[f]=o[s-8+f]}let m=0;for(;m<e;)if(d<8&&(n[d]=i[m],d+=1,m+=1),d===8){_f(n,t,a,c,o,s),s+=8,d=0;for(let l=0;l<8;l++)c[l]=o[s-8+l]}for(let l=0;l<qc;)if(d<8&&(n[d]=0,d+=1,l+=1),d===8){_f(n,t,a,c,o,s),s+=8,d=0;for(let f=0;f<8;f++)c[f]=o[s-8+f]}return o}function _f(i,t,e,r,o,s){for(let n=0;n<8;n++)i[n]^=r[n];Nv(i,t,o,s);for(let n=0;n<8;n++)o[s+n]^=e[n];for(let n=0;n<8;n++)e[n]=i[n]}function Nv(i,t,e,r){let o=jr(i,0),s=jr(i,4),n=[];for(let c=0;c<4;c++)n[c]=jr(t,4*c);let a=0;for(let c=0;c<Rf;c++)a+=vf,a>>>=0,o+=(s<<4)+n[0]^s+a^(s>>>5)+n[1],o>>>=0,s+=(o<<4)+n[2]^o+a^(o>>>5)+n[3],s>>>=0;JE(e,o,r),JE(e,s,r+4)}var Dv=0,lT=function(){return Date.now()+Dv},Ov=function(){let i=new Date;return i.setTime(lT()),i.toLocaleString()},Mv=function(i){let t=String(i.getMilliseconds());return"padStart"in String.prototype&&(t=t.toString().padStart(3,"0")),`${i.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")}:${t}`};function xv(i){let t=kv(i);return t==null?void 0:t.busiBuff}function kv(i){try{let t={},e=0;t.totalLength=jr(i,e),e+=4,t.version=jr(i,e),e+=4,t.encryption=QE(i,e),e+=1,t.uinType=QE(i,e),e+=1,t.uinLength=jr(i,e),e+=4,t.uin=t.uinLength>4?Bc(i,e,t.uinLength-4):"",e+=t.uinLength-4;let r=i.slice(e);if(t.encryption===2){let o=new Uint8Array(16).fill(0);i=Lv(r,o),t.decrypted=!0,e=0}else i=r,e=0;return t.rspHeadLength=jr(i,e),e+=4,t.seqNo=jr(i,e),e+=4,t.retCode=jr(i,e),e+=4,t.retStrLength=jr(i,e),e+=4,t.retStr=t.retStrLength?Bc(i,e,t.retStrLength-4):"",e+=t.retStrLength-4,t.serviceCmdLength=jr(i,e),e+=4,t.serviceCmd=t.serviceCmdLength?Bc(i,e,t.serviceCmdLength-4):"",e+=t.serviceCmdLength-4,t.cookieLength=jr(i,e),e+=4,t.cookie=t.cookieLength?Bc(i,e,t.cookieLength-4):"",e+=t.cookieLength-4,t.flag=jr(i,e),e+=4,t.busiBuffLength=jr(i,e),e+=4,t.busiBuff=t.busiBuffLength?Bc(i,e,t.busiBuffLength-4):"",e+=t.busiBuffLength-4,t}catch(t){}}function hT(i,t){let e=i[0]<<24|i[1]<<16|i[2]<<8|i[3],r=i[4]<<24|i[5]<<16|i[6]<<8|i[7];e>>>=0,r>>>=0;let o=vf*Rf>>>0;for(let s=0;s<Rf;s++)r-=(e<<YE)+t[2]^e+o^(e>>>5)+t[3],r>>>=0,e-=(r<<YE)+t[0]^r+o^(r>>>5)+t[1],e>>>=0,o-=vf,o>>>=0;return new Uint8Array([e>>>24&255,e>>>16&255,e>>>8&255,255&e,r>>>24&255,r>>>16&255,r>>>8&255,255&r])}function Lv(i,t){let e=0,r=new Uint8Array(8).fill(0),o=hT(new Uint8Array(i.slice(0,8)),t),s=7&o[0],n=i.length-1-s-jc-qc,a=new Uint8Array(n),c=0,d=r,m=i.slice(0,8);e=8;let l=1;l+=s;for(let g=1;g<=jc;)if(l<8)l++,g++;else if(l===8){let T=Ef(i,e,d,m,o,t);d=T.ivPreCrypt,m=T.ivCurCrypt,o=T.debiBuf,e=T.bufPos,l=0}let f=n;for(;f>0;)if(l<8)a[c++]=o[l]^d[l],l++,f--;else if(l===8){let g=Ef(i,e,d,m,o,t);d=g.ivPreCrypt,m=g.ivCurCrypt,o=g.debiBuf,e=g.bufPos,l=0}for(let g=1;g<=qc;)if(l<8)o[l],d[l],l++,g++;else if(l===8){if(e>=i.length)break;let T=Ef(i,e,d,m,o,t);if(!T.success)break;d=T.ivPreCrypt,m=T.ivCurCrypt,o=T.debiBuf,e=T.bufPos,l=0}return a}function Ef(i,t,e,r,o,s){if(t+8>i.length)return{success:!1};let n=new Uint8Array(r),a=i.slice(t,t+8),c=new Uint8Array(8);for(let d=0;d<8;d++)c[d]=o[d]^a[d];return{success:!0,ivPreCrypt:n,ivCurCrypt:a,debiBuf:hT(c,s),bufPos:t+8}}var ZE=typeof TextDecoder!="undefined"?new TextDecoder:void 0;function Pv({url:i,body:t,method:e="POST",timeout:r,priority:o}){return new Promise((s,n)=>{if("fetch"in window)return fetch(i,{method:e,body:t,priority:o}).then(c=>c.clone().json().then(d=>({data:d}),()=>c.arrayBuffer().then(d=>({data:xv(new Uint8Array(d))||(ZE?ZE.decode(d):d)})))).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=r||5e3,a.open(e,i,!0),a.send(t)})}var Uv=Object.prototype.hasOwnProperty,$c=i=>typeof i=="function",pa=i=>i===void 0,Vv=i=>typeof i=="boolean",Bv=function(i){if(!i||typeof i!="object"||Object.prototype.toString.call(i)!="[object Object]")return!1;let t=Object.getPrototypeOf(i);if(t===null)return!0;let e=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return typeof e=="function"&&e instanceof e&&Function.prototype.toString.call(e)===Function.prototype.toString.call(Object)};function $v(i){if(i==null)return!0;if(typeof i=="boolean")return!1;if(typeof i=="number")return i===0;if(typeof i=="string"||typeof i=="function"||Array.isArray(i))return i.length===0;if(i instanceof Error)return i.message==="";if(Bv(i))switch(Object.prototype.toString.call(i)){case"[object File]":case"[object Map]":case"[object Set]":return i.size===0;case"[object Object]":for(let t in i)if(Uv.call(i,t))return!1;return!0}return!1}var Fv=0,Hv=1,KE=2;function Wv({retryFunction:i,settings:t,onError:e,onRetrying:r,onRetryFailed:o,onRetrySuccess:s,context:n}){return function(...a){let{retries:c=5,timeout:d=1e3}=t,m=0,l=-1,f=Fv,g=(T,E)=>D(this,null,function*(){let y=n||this;try{let v=yield i.apply(y,a);m>0&&s&&s.call(this,m),m=0,T(v)}catch(v){let M=()=>{clearTimeout(l),m=0,f=KE,E(v)},w=()=>{f!==KE&&m<($c(c)?c():c)?(m++,f=Hv,$c(r)&&r.call(this,m,M),l=window.setTimeout(()=>{l=-1,g(T,E)},$c(d)?d(m):d)):(M(),$c(o)&&o.call(this,v))};$c(e)?e.call(this,{error:v,retry:w,reject:E,retryFuncArgs:a,retriedCount:m}):w()}});return new Promise(g)}}var Gv=Wv,Tf=class mT{constructor(t){xt(this,"_parentPath"),xt(this,"userId"),xt(this,"remoteUserId"),xt(this,"id"),xt(this,"sdkAppId"),xt(this,"type"),xt(this,"isLocal"),this.id=t.id,this.userId=t.userId,this.sdkAppId=t.sdkAppId,this.remoteUserId=t.remoteUserId,this.isLocal=!Vv(t.isLocal)||t.isLocal,this.type=this.isLocal?"":t.type}getFullId(){return this._parentPath&&this.id?`${this._parentPath}-${this.id}`:this._parentPath?this._parentPath:this.id}createChild(t){let e=new mT({id:t.id,userId:pa(t.userId)?this.userId:t.userId,sdkAppId:pa(t.sdkAppId)?this.sdkAppId:t.sdkAppId,type:pa(t.type)?this.type:t.type,isLocal:pa(t.isLocal)?this.isLocal:t.isLocal,remoteUserId:pa(t.remoteUserId)?this.remoteUserId:t.remoteUserId});return e.bindParent(this),e}bindParent(t){let e=t.getFullId();this._parentPath!==e&&(this.debug(`bind logger parent: ${t.id}`),this._parentPath=e,this.userId=t.userId||this.userId,this.sdkAppId=t.sdkAppId||this.sdkAppId)}setUserId(t){this.userId=t}setSdkAppId(t){this.sdkAppId=t}log(t,e){let r=this.isLocal?this.userId:this.remoteUserId,o=this.getFullId();e.unshift(`[${this.isLocal?"\u2191":"\u2193"}${this.type&&this.type!=="main"?"*":""}${o}${r?`|${r}`:""}]`),vR.log(t,e,pa(this.userId)||$v(this.userId),this.userId,this.sdkAppId)}info(...t){this.log(2,t)}debug(...t){this.log(1,t)}warn(...t){this.log(3,t)}error(...t){this.log(4,t)}},Xi=typeof navigator=="undefined"?"":navigator.userAgent,tt=i=>new RegExp(i,"i").test(Xi),sr=i=>{if(tt(i)){let t=new RegExp(`${i}\\/([\\d.]+)`),e=Xi.match(t);if(e&&e[1])return e[1]}return""},Ml=i=>{if(tt(i)){let t=new RegExp(`${i}\\/(\\d+)`),e=Xi.match(t);if(e&&e[1])return parseFloat(e[1])}return NaN},eT=/AppleWebKit\/([\d.]+)/i.exec(Xi),zv=eT?parseFloat(eT[1]):NaN,pT=tt("iPad"),fT=typeof navigator!="undefined"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&tt("Macintosh"),gT=tt("iPhone")&&!pT,jv=tt("iPod"),Nf=gT||pT||jv||fT,Xc=tt("Android"),_T=function(){if(Xc){let i=Xi.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(i){let t=i[1]&&parseFloat(i[1]),e=i[2]&&parseFloat(i[2]);if(t&&e)return parseFloat(`${i[1]}.${i[2]}`);if(t)return t}}return NaN}(),P2=Xc&&tt("webkit")&&_T<2.3,U2=Xc&&_T<5&&zv<537,qv=tt("Firefox"),Xv=sr("Firefox"),V2=Ml("Firefox"),ET=tt("Edge"),Jv=sr("Edge"),TT=tt("Edg"),Qv=sr("Edg"),B2=Ml("Edg"),yT=tt("SogouMobileBrowser"),Yv=sr("SogouMobileBrowser"),ST=tt("MetaSr\\s"),Zv=sr("MetaSr\\s"),dn=tt("TBS"),Kv=sr("TBS"),IT=tt("XWEB"),eR=sr("XWEB"),$2=tt("MSIE\\s8\\.0"),tR=tt("MSIE\\/\\d+"),F2=function(){if(tR){let i=/MSIE\s(\d+)\.\d/.exec(Xi),t=i&&parseFloat(i[1]);return!t&&/Trident\/7.0/i.test(Xi)&&/rv:11.0/.test(Xi)&&(t=11),t}return NaN}(),rR=tt("(micromessenger|webbrowser)"),iR=sr("MicroMessenger"),Df=!dn&&tt("MQQBrowser")&&tt("COVC"),Of=!dn&&tt("MQQBrowser")&&!tt("COVC"),tT=Of||Df?sr("MQQBrowser"):"",bT=!dn&&tt(" QQBrowser"),oR=sr(" QQBrowser"),AT=!dn&&tt("QQBrowserLite"),sR=sr("QQBrowserLite"),vT=!dn&&tt("MQBHD"),nR=sr("MQBHD"),H2=tt("Windows"),W2=!Nf&&tt("MAC OS X"),G2=!Xc&&tt("Linux"),z2=tt("CrOS"),j2=tt("MicroMessenger"),q2=tt("UCBrowser"),X2=tt("Electron"),RT=tt("MiuiBrowser"),aR=sr("MiuiBrowser"),CT=tt("HuaweiBrowser"),J2=tt("Huawei")||tt("HUAWEI"),Q2=tt("Honor")||tt("HONOR"),cR=sr("HuaweiBrowser"),wT=tt("SamsungBrowser"),dR=sr("SamsungBrowser"),NT=tt("HeyTapBrowser"),uR=sr("HeyTapBrowser"),DT=tt("VivoBrowser"),lR=sr("VivoBrowser"),Y2=tt("OpenHarmony"),Z2=sr("OpenHarmony"),hR=()=>Ml("Chrome"),rT=tt("CriOS"),OT=tt("Chrome"),mR=!ET&&!ST&&!yT&&!dn&&!IT&&!TT&&!bT&&!RT&&!CT&&!wT&&!NT&&!DT&&OT,pR=tt("HeadlessChrome"),K2=hR(),fR=sr("Chrome"),e1=Ml("Electron"),gR=!OT&&!Of&&!Df&&!AT&&!vT&&tt("Safari"),MT=sr("Version"),t1=/Android.*(wv|.0.0.0)/.test(Xi),xT=(()=>{if(fT)return MT;if(Nf){let i=Xi.match(/OS (\d+)_(\d+)/i);if(i&&i[1]){let t=i[1];return i[2]&&(t+=`.${i[2]}`),t}}return""})(),r1=Number(xT.split(".")[0]),i1=(()=>{let i=Number(xT.split(".")[0]);return i===14||i===13})(),o1=typeof location!="undefined"&&(location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1"),s1=_R();function _R(){let i=new Map([[qv,["Firefox",Xv]],[TT,["Edg",Qv]],[mR,["Chrome",fR]],[rT,["ChiOS",sr("CriOS")]],[gR&&!rT,["Safari",MT]],[dn,["TBS",Kv]],[IT,["XWEB",eR]],[rR&&gT,["WeChat",iR]],[bT,["QQ(Win)",oR]],[Of,["QQ(Mobile)",tT]],[Df,["QQ(Mobile X5)",tT]],[AT,["QQ(Mac)",sR]],[vT,["QQ(iPad)",nR]],[RT,["MI",aR]],[CT,["HW",cR]],[wT,["Samsung",dR]],[NT,["OPPO",uR]],[DT,["VIVO",lR]],[ET,["EDGE",Jv]],[yT,["SogouMobile",Yv]],[ST,["Sogou",Zv]]]),t="unknown",e="unknown";return i.has(!0)&&([t,e]=i.get(!0)),{name:t,version:e}}var ER=aT(cT(),1),TR=new ER.default,ss=TR,Cl=dT,yR=class{constructor(){xt(this,"enable",!1),xt(this,"ssoFailCount",0),ss.on("22",({schedule:i})=>{var t;(t=i==null?void 0:i.config)!=null&&t.sso&&ss.emit("266",{enable:!0})}),ss.on("266",({enable:i})=>{this.enable=i})}handleUploadFailed(){this.ssoFailCount++,this.ssoFailCount>3&&ss.emit("266",{enable:!1})}},iT=new yR,SR="%cTRTC%c%s",IR="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",bR="display: inline",kT=class LT{constructor(){xt(this,"_isEnableUploadLog",!0),xt(this,"_localJoinedUser",new Map),xt(this,"_queue",[]),xt(this,"_timeoutId",-1),xt(this,"_logLevel",1),xt(this,"_logLevelToUpload",2),pv||fv||(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){ss.on(Cl.JOIN_SCHEDULE_SUCCESS,({schedule:t})=>{var e;(e=t==null?void 0:t.config)!=null&&e.logLevelToUpload&&cn[t.config.logLevelToUpload]&&(this._logLevelToUpload=t.config.logLevelToUpload)}),ss.on(Cl.JOIN_START,({params:t})=>{this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload()}),ss.on(Cl.LEAVE_SUCCESS,({room:t})=>{this.deleteJoinedUser(t.userId)})}startUpload(){this._timeoutId===-1&&this.uploadInterval()}addJoinedUser(t){this._localJoinedUser.set(t.userId,t),this.startUpload()}deleteJoinedUser(t){this._localJoinedUser.delete(t)}uploadInterval(){this.upload().catch(()=>{}),this._timeoutId=window.setTimeout(()=>this.uploadInterval(),5e3)}getLogsToUpload(){let t={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&this._localJoinedUser.size===0)return t;let e=0;for(;e<this._queue.length&&e!==50;e++){let r=this._queue[e];if(r.forAllJoinedClients)this._localJoinedUser.forEach(({userId:o,sdkAppId:s})=>{t.map.has(o)?t.map.get(o).logs.push(r):t.map.set(o,{userId:o,sdkAppId:s,logs:[r]})});else if(Cf(r.userId)&&wR(r.sdkAppId)){let{userId:o,sdkAppId:s}=r;t.map.has(o)?t.map.get(o).logs.push(r):t.map.set(o,{userId:o,sdkAppId:s,logs:[r]})}}return t.map.size>0&&(t.splicedQueue=this._queue.splice(0,e)),t}upload(){return D(this,null,function*(){if(this._queue.length===0||!this._isEnableUploadLog)return;let{map:t,splicedQueue:e}=this.getLogsToUpload();if(t.size===0)return;try{let o=[...t.values()];for(let s=0;s<o.length;s++){let{userId:n,sdkAppId:a,logs:c}=o[s],d={timestamp:Ov(),sdkAppId:String(a),userId:n,version:mv,log:c.map(f=>f.log).join(`
|
|
94
|
-
`)},m=JSON.stringify(d),l=iT.enable?OR(d,2002,a):m;yield this.uploadLogWithRetry(l,a,l instanceof Uint8Array,m),c.forEach(f=>f.uploaded=!0)}}catch(o){}let r=e.filter(o=>!o.uploaded);r.length>0&&(this._queue=r.concat(this._queue))})}uploadLogWithRetry(t,e,r,o){return Gv({retryFunction:()=>Pv({url:CR(e,Sv.LOG),body:t,timeout:5e3,priority:"low"}).then(s=>{r&&s.data!=="ok"&&(iT.handleUploadFailed(),this.uploadLogWithRetry(o,e,!1,o))}),settings:{retries:3,timeout:2e3},onError:({retry:s})=>{s()}})()}getPrefix(t){let e=new Date;return e.setTime(lT()),`[${Mv(e)}] <${cn[t]}>`}getLogLevel(){return this._logLevel}setLogLevel(t){PT(cn[t])||(this._logLevel!==t&&this.info("setLogLevel",t),this._logLevel=t)}enableUploadLog(){this._isEnableUploadLog=!0}disableUploadLog(){this.warn("disableUploadLog"),this._isEnableUploadLog=!1}logChunkToString(t){if(Cf(t))return t;try{return t instanceof Error?t.toString():JSON.stringify(t)}catch(e){return""}}addLogToQueue(t,e,r=!0,o,s){let n={log:e.reduce((a,c)=>`${a} ${this.logChunkToString(c)}`.trim(),""),level:t,userId:o,sdkAppId:s,forAllJoinedClients:r};ss.emit(Cl.LOG,{log:n}),this._isEnableUploadLog&&t>=this._logLevelToUpload&&this._queue.push(n)}log(t,e,r=!0,o,s){var n;if(e.unshift(this.getPrefix(t)),this.addLogToQueue(t,e,r,o,s),t<this._logLevel)return;let a=((n=cn[t])==null?void 0:n.toLowerCase())||"info";LT.PRINT_LOG_TAG?console[a](SR,IR,bR,...e):console[a](...e)}debug(...t){this.log(1,t)}info(...t){this.log(2,t)}warn(...t){this.log(3,t)}error(...t){this.log(4,t)}createLogger(t){if(t.parent instanceof Tf){let e=t,{parent:r}=e,o=rv(e,["parent"]),s=new Tf(o);return s.bindParent(r),s}return new Tf(t)}checkURLParam(){let t=new URLSearchParams(location.search).get("logLevelToUpload"),e=t?Number(t):-1;cn[e]&&(this._logLevelToUpload=e)}getQueue(){return this._queue}};xt(kT,"PRINT_LOG_TAG",!(Nf||Xc||pR));var AR=kT,vR=new AR,RR=i=>Number(i)<14e8,CR=function(i,t){let e;return e=gv||(RR(i)?yv:Tv),`${e}/v5/AVQualityReportSvc/C2S?random=${Math.floor(Math.random()*ki(2,31))}&sdkappid=${i}&cmdtype=${t}`},n1=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},PT=i=>i===void 0,Cf=i=>typeof i=="string",wR=i=>typeof i=="number",a1=typeof HTMLMediaElement!="undefined"&&"setSinkId"in HTMLMediaElement.prototype;function NR(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var{toString:c1}=Object.prototype;function DR(i,t,e,r){let o={data:i,random:Math.floor(Math.random()*2147483648),sdkAppId:e};return PT(r)||(o=Wc(Hc({},o),{gzip:+r})),{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:t,bytes_report_data:JSON.stringify(o)}}}function OR(i,t,e,r){try{let o=DR(i,t,e,r);return Cv(Af(o),e)}catch(o){return JSON.stringify(i)}}var UT=class VT{constructor(t){this.core=t,xt(this,"contextMap",new Map),xt(this,"decodeProcessorMap",new WeakMap),this.addKVReportBeforeExitRoom=this.addKVReportBeforeExitRoom.bind(this),this.createDecoder=this.createDecoder.bind(this),this.core.innerEmitter.on("51",this.addKVReportBeforeExitRoom)}getAlias(){return"videoDecoder"}getGroup(t){return t!=null&&t.track?`${t.track.userId}${t.track.streamType}`:"*"}getName(){return VT.Name}getValidateRule(t){return{type:this.core.enums.BASIC_TYPE.Object}}createDecoder(t,e){var r;switch(t){case"wasm":let s=((r=this.core.assetsPath)==null?void 0:r.replace(/\/+$/,""))||".";return new hv(Wc(Hc({},e),{wasmPath:`${s}/videodec.wasm`}));case"webCodecs":return new fa;case"mse":throw new Error("mse decoder not supported yet");default:throw new Error("Unsupported decoder type")}}start(t){this.decodeProcessorMap.set(t.track,this.decode(t)),this.core.room.videoManager.addDecodeProcessor({processor:({frame:e,track:r})=>{var o;return((o=this.decodeProcessorMap.get(r))==null?void 0:o({frame:e,track:r}))||e},type:3})}decode(t){let{pipe:e,take:r,subscribe:o}=this.core.rx;return({frame:s,track:n})=>{if(n!==t.track||s.type==="empty")return s;if(this.contextMap.has(n))return this.contextMap.get(n).decode(s);let a=this.core.room.videoManager.createDecodeContext(Wc(Hc({},t),{createDecoder:this.createDecoder}));return e(a.trackDoneOB,r(1),o(()=>{this.core.clearStarted(this,this.getGroup(t)),this.stop({track:n})})),this.contextMap.set(n,a),a.decode(s)}}stop(t){if(t!=null&&t.track){let e=this.contextMap.get(t.track);e&&(e.close("stop"),this.report(e,t.track),this.contextMap.delete(t.track))}else this.contextMap.forEach((e,r)=>{e.close("stop"),this.contextMap.delete(r)});this.contextMap.size===0&&this.core.room.videoManager.removeDecodeProcessor({type:3})}report(t,e){if(t.isReported)return;t.isReported=!0;let r=NR()-t.startPerformanceTime,{renderFreezeTotal:o,dataFreezeTotal:s}=this.getRemoteTrackFreezeDuration(e,t),n=`report health data: ${t.track.userId} ${t.track.streamType} ${t.type}+${t.renderer} goodType\uFF1A${t.goodType} ${t.failedReason?`failedReason: ${t.failedReason}`:""}`;r&&(this.core.kvStatManager.addNumber({key:514850,value:Math.floor(o/r*100),split:1,max:100}),n+=` RENDER_FREEZE_RATE: ${Math.floor(o/r*100)}%`),r&&(this.core.kvStatManager.addNumber({key:514851,value:Math.floor(s/r*100),split:1,max:100}),n+=` DATA_FREEZE_RATE: ${Math.floor(s/r*100)}%`),t.inputFrameCount&&(this.core.kvStatManager.addNumber({key:514852,value:Math.floor(t.decodedFrameCount/t.inputFrameCount*100),split:1,max:100}),n+=` VIDEO_CONSUME_RENDER_RATE: ${Math.floor(t.decodedFrameCount/t.inputFrameCount*100)}%`),this.core.log.info(n)}addKVReportBeforeExitRoom({room:t}){t===this.core.room&&this.contextMap.forEach((e,r)=>{this.report(e,r)})}update(t){let e=this.contextMap.get(t.track);e&&(t.type!=="mock"?(e.close("update"),this.contextMap.set(t.track,this.core.room.videoManager.createDecodeContext(Wc(Hc({},t),{createDecoder:this.createDecoder})))):e.mock(this.core.enums.DECODE_FAILED_ERROR_CODE.TEST))}getRemoteTrackFreezeDuration(t,e){let r=this.core.room.badCaseDetector.getDataFreezeMap().get(`${t.userId}_${t.streamType}`),o=this.core.room.badCaseDetector.getRenderFreezeDuration(`${t.userId}_${t.streamType}`),s=0;return r&&r.durationItemList.forEach(n=>{n.startTime>e.startPerformanceTime&&(s+=n.getDuration())}),{renderFreezeTotal:o,dataFreezeTotal:s}}destroy(){this.core.innerEmitter.off("51",this.addKVReportBeforeExitRoom)}};xt(UT,"Name","TRTCVideoDecoder");var Mf=UT;var Dy=Li(mo());function xf({timesInSecond:i,maxSizeInSecond:t,getSize:e}){return ut((r,o)=>{let s=new WeakMap;return ee.on(ce.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>=i||a.totalSizeInSecond>t))throw new Me({code:Te.INVALID_OPERATION,message:Et({key:_t.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=i,isSize:a.totalSizeInSecond>t,name:o,timesInSecond:i,maxSizeInSecond:t}})});a.callCountInSecond++,r.call(this,...n)}})}var MR="2025-12-04 16:34:28",BT=!0,$T=function(){var i;if(BT){BT=!1,se.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${Br}/en/index.html`),console.info(`* Changelog: ${Br}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),se.info("TRTC Web SDK Version:",qt),bi||se.debug("Build Time:",MR);let t=`UA: ${navigator.userAgent}
|
|
95
|
-
CPU core: ${navigator.hardwareConcurrency}, GPU: ${ym()}`,e=navigator.deviceMemory;e&&(t+=`, minRAM: ${e}GB`),se.info(t),se.info(`URL: ${location.href}${((i=self.frameElement)==null?void 0:i.tagName)==="IFRAME"?" in iframe":""}`),Us().then(r=>{r&&se.info(yi)})}};var un={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 ke={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},Kr=(G=>(G[G.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",G[G.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",G[G.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",G[G.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",G[G.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",G[G.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",G[G.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",G[G.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",G[G.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",G[G.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",G[G.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",G[G.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",G[G.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",G[G.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",G[G.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",G[G.INVALID_ROOM_ID_REQUIRED=5015]="INVALID_ROOM_ID_REQUIRED",G[G.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",G[G.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",G[G.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",G[G.INVALID_ROOM_ID_TYPE_MISMATCH=5019]="INVALID_ROOM_ID_TYPE_MISMATCH",G[G.INVALID_ROOM_ID_DUPLICATE=5020]="INVALID_ROOM_ID_DUPLICATE",G[G.INVALID_OPERATION=5100]="INVALID_OPERATION",G[G.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",G[G.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",G[G.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",G[G.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",G[G.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",G[G.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",G[G.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",G[G.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",G[G.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",G[G.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",G[G.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",G[G.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",G[G.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",G[G.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",G[G.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",G[G.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",G[G.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",G[G.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",G[G.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",G[G.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",G[G.DEVICE_ERROR=5300]="DEVICE_ERROR",G[G.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",G[G.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",G[G.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",G[G.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",G[G.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",G[G.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",G[G.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",G[G.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",G[G.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",G[G.NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX=5310]="NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX",G[G.SERVER_ERROR=5400]="SERVER_ERROR",G[G.NEED_TO_BUY=5401]="NEED_TO_BUY",G[G.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",G[G.OPERATION_FAILED=5500]="OPERATION_FAILED",G[G.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",G[G.REJOIN_FAILED=5502]="REJOIN_FAILED",G[G.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",G[G.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",G[G.VIDEO_ENCODE_FAILED=5505]="VIDEO_ENCODE_FAILED",G[G.AUDIO_ENCODE_FAILED=5506]="AUDIO_ENCODE_FAILED",G[G.VIDEO_DECODE_FAILED=5507]="VIDEO_DECODE_FAILED",G[G.AUDIO_DECODE_FAILED=5508]="AUDIO_DECODE_FAILED",G[G.OPERATION_ABORT=5998]="OPERATION_ABORT",G[G.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",G))(Kr||{});function HT({code:i,params:t,enableDocLink:e=!1}){let r="",o,s=Kr[i];try{o=FT[s]}catch(n){o=FT.UNKNOWN_ERROR}return Rt(o)?r=o(t):nt(o)&&(r=o),t.fnName&&!r.includes(t.fnName)&&(r[r.length-1]!=="."&&(r+="."),r+=` thrown from ${t.fnName}()`),e&&(r+=" doc:"),r}var FT=qe(be({},Wr),{INVALID_PARAMETER({fnName:i}){return`the parameters of the '${i}' you called does not meet the requirements, please check the API documentation.`},INVALID_PARAMETER_REQUIRED({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' is a required param when calling ${e}(), received: ${r}.`},INVALID_PARAMETER_TYPE({key:i,rule:t,fnName:e,value:r}){let o=`${i||t.name}`,s="";return Array.isArray(t.type)?s=t.type.join("|"):s=t.type,`'${o}' must be type of ${s} when calling ${e}(), received type: ${Xt(r)}.`},INVALID_PARAMETER_EMPTY({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' cannot be '${r}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:i,rule:t,fnName:e,value:r}){let o=`${i||t.name}`,s=`${t.instanceOf.name||t.instanceOf}`;return`'${o}' must be instanceof ${s} when calling ${e}(), received type: ${Xt(r)}.`},INVALID_PARAMETER_RANGE({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' must be one of ${t.values.join("|")} when calling ${e}(), received: ${r}.`},INVALID_PARAMETER_LESS_THAN_ZERO({key:i,rule:t,fnName:e}){return`'${i||t.name}' cannot be less than 0 when calling ${e}().`},INVALID_PARAMETER_MIN({key:i,rule:t,value:e}){return`the min value of ${i||t.name} is ${t.min}, received: ${e}.`},INVALID_PARAMETER_MAX({key:i,rule:t,value:e}){return`the max value of ${i||t.name} is ${t.max}, received: ${e}.`},INVALID_ELEMENT_ID({key:i,fnName:t}){return`'${i}' is not found in the document object when calling ${t}().`},INVALID_ELEMENT_ID_TYPE({key:i,fnName:t,type:e}){return`the element corresponding to '${i}' must be instanceof HTMLElement when calling ${t}(), received: ${e}.`},INVALID_STREAM_ID({key:i}){return`'${i}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},INVALID_ROOM_ID_STRING({key:i}){return`'${i}' must be a valid string.`},INVALID_ROOM_ID_INTEGER({key:i}){return`'${i}' must be an integer between [1, 4294967294].`},INVALID_ROOM_ID_INTEGER_STRING({key:i}){return`'${i}' 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:i}){return`The type of target roomId must match the current roomId. Current room is using '${i}', but received '${i==="strRoomId"?"roomId":"strRoomId"}'.`},INVALID_ROOM_ID_DUPLICATE({key:i}){return`the target '${i}' must not be the same as the current '${i}'.`},INVALID_STREAM_TYPE:({fnName:i})=>`'streamType' is required when 'userId' is not '*', calling ${i}()`,INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION({fnName:i}){return`the API '${i}' you called does not meet the requirements, please check the API documentation.`},INVALID_OPERATION_NOT_JOINED({fnName:i}){return`cannot ${i} because you are not enter room yet.`},INVALID_OPERATION_REMOTE_USER_NOT_EXIST({fnName:i,value:t}){return`cannot ${i} because remote user(userId: ${t.userId}) does not publishing stream.`},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST({fnName:i,value:t}){return`cannot ${i} because remote user(userId: ${t.userId}) does not publishing ${t.streamType} video.`},INVALID_OPERATION_REPEAT_CALL({fnName:i}){return`you are already ${i}(), cannot repeated call '${i}'.`},INVALID_OPERATION_NEED_VIDEO({fnName:i}){return`cannot call '${i}' because the camera is not turned on.`},INVALID_OPERATION_NEED_AUDIO({fnName:i}){return`cannot call '${i}' because the microphone or screen share is not turned on.`},INVALID_BUFFER_EMPTY:({key:i})=>`the buffer size of paramerter '${i}' 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:i})=>`you need to call ${i}() after publish stream.`,ENV_NOT_SUPPORTED({fnName:i}){return`the current browser does not support the capability of the function '${i}' 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:i}){return`cannot call ${i} because the browser version is too low, please upgrade to the latest version`},DEVICE_ERROR({fnName:i,error:t}){return`'${i}' got device exception${t?`, error: ${t.toString()}.`:"."}`},DEVICE_NOT_FOUND_ERROR({fnName:i,deviceType:t=ln(i),error:e}){return`NotFoundError, no ${t} detected, please check your device and the configuration on '${i}'${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_ALLOWED_ERROR({fnName:i,deviceType:t=ln(i),error:e}){return`NotAllowedError, you have disabled ${t} access, please allow the current application to use the ${t}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_READABLE_ERROR({fnName:i,deviceType:t=ln(i),error:e}){return`NotReadableError, the ${t} maybe in use by another APP, please check if the device is pre-occupied by another APP.`},DEVICE_OVERCONSTRAINED_ERROR({fnName:i,deviceType:t=ln(i),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:i,deviceType:t=ln(i),error:e}){return`InvalidStateError, after the user clicks and interacts with the page, turn on the ${t}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_SECURITY_ERROR({fnName:i,deviceType:t=ln(i),error:e}){return`SecurityError, check whether the system security policy restricts the use of the ${t}, and it is recommended to turn on the ${t} after the user interacts with the page${e?`, error: ${e.toString()}.`:"."}`},DEVICE_ABORT_ERROR({fnName:i,deviceType:t=ln(i),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:i}){return`camera recover capture failed ${(i==null?void 0:i.name)||""}: ${(i==null?void 0:i.originMessage)||(i==null?void 0:i.message)}`},MICROPHONE_RECOVER_FAILED({error:i}){return`microphone recover capture failed ${(i==null?void 0:i.name)||""}: ${(i==null?void 0:i.originMessage)||(i==null?void 0:i.message)}`},OPERATION_FAILED({fnName:i,error:t}){return`'${i}' failed, reason: ${t==null?void 0:t.toString()}`},FIREWALL_RESTRICTION(){return"media connection failure due to firewall restrictions, please try to change your network."},EVENT_HANDLER_ERROR({eventName:i}){return`an error was caught on trtc.on('${i}', handler), please check your code on 'handler'.`},VIDEO_CONTEXT_ERROR({reason:i,error:t}){return`video context error ${i} ${(t==null?void 0:t.name)||""} ${(t==null?void 0:t.message)||""}`},SERVER_ERROR({fnName:i,error:t}){return`'${i}' got server error: ${t==null?void 0:t.toString()}, please check the SDK documentation.`},NEED_TO_BUY({value:i,url:t}){return`You need to buy packages for ${i}. Refer to: ${t}`},ACCOUNT_NO_MONEY:({fnParams:i})=>`your TRTC account run out of credit, please recharge.${i.sdkAppId?` SDKAppId: ${i.sdkAppId}`:""}`,OPERATION_ABORT({fnName:i}){return`'${i}' abort`},UNKNOWN_ERROR({fnName:i,error:t}){return`'${i}' throw unknown exception${t?`, error: ${t.toString()}.`:"."}`}});function ln(i){if(!i)return"camera";let t=i.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var kf=class i extends Error{constructor({code:e,extraCode:r,message:o="",messageParams:s,fnName:n="",originError:a,data:c}){var m;let d;o?d=o:d=HT({code:e===ke.SERVER_ERROR?e:r||e,params:be({fnName:n,error:a},s)});super(d);p(this,"name","RtcError");p(this,"code");p(this,"extraCode");p(this,"functionName");p(this,"message");p(this,"data");p(this,"handler");p(this,"originError");this.name=Kr[e],this.code=e,this.extraCode=r,this.functionName=n,this.originError=a,this.message=d,this.data=c,this.extraCode===5302&&((m=this.originError)!=null&&m.message.includes("system"))&&(this.handler=()=>{let l={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},f={startLocalVideo:"webcam",startLocalAudio:"microphone"},g=document.createElement("a");Ps?g.href=`ms-settings:privacy-${f[this.functionName]}`:Ii&&(g.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${l[this.functionName]}`),g.href.length>0&&g.click()})}static convertFrom(e,r,o){let s=e;if(e instanceof Me){let{stack:n}=e,a={code:ke.UNKNOWN_ERROR,fnName:r,originError:e};switch(e.getCode()){case Te.INVALID_PARAMETER:a.code=ke.INVALID_PARAMETER,a.message=e.message;break;case Te.INVALID_OPERATION:a.code=ke.INVALID_OPERATION;break;case Te.NOT_SUPPORTED:case Te.NOT_SUPPORTED_H264:a.code=ke.ENV_NOT_SUPPORTED,e.getCode()===Te.NOT_SUPPORTED_H264&&(a.extraCode=e.message.includes(Wr.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case Te.JOIN_ROOM_FAILED:a.messageParams={fnParams:o};case Te.SERVER_TIMEOUT:case Te.SWITCH_ROLE_FAILED:case Te.SWITCH_ROOM_FAILED:a.code=ke.SERVER_ERROR,a.extraCode=e.getExtraCode();break;case Te.API_CALL_ABORTED:a.code=ke.OPERATION_ABORT;break;case Te.DEVICE_NOT_FOUND:case Te.DEVICE_AUTO_RECOVER_FAILED:case Te.INITIALIZE_FAILED:a.code=5300,e.name&&(a.extraCode=xR(e.name));break;case Te.VIDEO_ENCODE_FAILED:a.extraCode=5505;case Te.AUDIO_ENCODE_FAILED:a.extraCode=5506,a.code=ke.OPERATION_FAILED;break;case Te.UNKNOWN:break;default:a.code=ke.OPERATION_FAILED}s=new i(a),n&&(s.stack+=n.substr(n.indexOf(`
|
|
96
|
-
`)))}else{if(e instanceof i)return e;s=new i({code:ke.UNKNOWN_ERROR,fnName:r,originError:e})}return s}};function xR(i){let t;switch(i){case"NotFoundError":t=5301;break;case"NotAllowedError":t=5302;break;case"NotReadableError":t=5303;break;case"OverconstrainedError":t=5304;break;case"InvalidStateError":t=5305;break;case"SecurityError":t=5306;break;case"AbortError":t=5307;break;default:t=5300}return t}var Oe=kf;function Ji(i){return i==="sub"?"auxiliary":i==="auxiliary"?"sub":"main"}function Jc(i){return i===un.QOS_PREFERENCE_CLEAR?"detail":i===un.QOS_PREFERENCE_SMOOTH?"motion":""}function _a(i,t){let e=t?Fh:La;return am(i)?be(be({},e),i):gi[i]?gi[i]:e}var WT={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}}},GT={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}}},Ea={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(i,t,e){if(nt(i)&&!document.getElementById(i))throw new Oe({code:ke.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:t}})}},zT={name:"userId",required:!0,type:"string"},jT={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 Ta(i,t){if(!i)throw new Oe({code:ke.INVALID_OPERATION,extraCode:5101,fnName:t})}function qT(i,t,e){if(!i)throw new Oe({code:ke.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:e}})}function XT(i,t,e){if(!(/^[1-9]\d*$/.test(String(i))&&i<4294967295))throw new Oe({code:ke.INVALID_PARAMETER,extraCode:5013,fnName:t,messageParams:{key:e}})}function JT(i,t,e){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(i))throw new Oe({code:ke.INVALID_PARAMETER,extraCode:5012,fnName:t,messageParams:{key:e}})}var kV={type:"number",notLessThanZero:!0},kR=(i,t)=>i.width*i.height>=t.width*t.height&&i.frameRate>=t.frameRate&&i.bitrate>=t.bitrate;function QT(i){var r;if(!((r=i==null?void 0:i.option)!=null&&r.small))return;if(!Bu()){se.warn("small stream is not supported"),delete i.option.small;return}let t=_a(i.option.profile),e=_a(i.option.small,!0);if(!kR(t,e)){se.warn(`small stream profile must be less than big stream profile. Big: ${JSON.stringify(t)}, Small: ${JSON.stringify(e)}`),delete i.option.small;return}}var LR={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(i,t,e){if(this._room.isJoined)throw new Oe({code:ke.INVALID_OPERATION,extraCode:5104,fnName:e});if(i.roomId){if(nt(i.roomId))throw new Oe({code:ke.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:t}});XT(i.roomId,e,t)}else if(i.strRoomId)JT(i.strRoomId,e,t);else throw new Oe({code:ke.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:Ea,mute:{type:["boolean","string"]},publish:{type:"boolean"},capture:{required:!1,type:"boolean"},option:WT},validate(i){var t,e;if(!((t=i==null?void 0:i.option)!=null&&t.videoTrack)&&Eo())throw new Oe({code:ke.ENV_NOT_SUPPORTED,extraCode:5201});(e=i==null?void 0:i.option)!=null&&e.small&&QT(i)}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:qe(be({},Ea),{required:!1}),publish:{type:"boolean"},capture:{required:!1,type:"boolean"},mute:{type:["boolean","string"]},option:WT},validate(i){var t;(t=i==null?void 0:i.option)!=null&&t.small&&QT(i)}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:jT},validate(i){var t;if(!((t=i==null?void 0:i.option)!=null&&t.audioTrack)&&Eo())throw new Oe({code:ke.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:jT}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:Ea,publish:{type:"boolean"},option:GT},validate(i,t,e,r,o){var s;if(!((s=i==null?void 0:i.option)!=null&&s.videoTrack)){if(Eo())throw new Oe({code:ke.ENV_NOT_SUPPORTED,extraCode:5201});if(!mc())throw new Oe({code:ke.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:Ea,publish:{type:"boolean"},option:GT}},muteRemoteAudio:[zT,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[zT,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:Ea,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(i,t,e){Ta(this._room.isJoined,e);let r=this._room.remotePublishedUserMap.get(i.userId);if(qT(!!r,e,i),r&&(i.streamType==="main"&&!r.muteState.videoAvailable||i.streamType==="sub"&&!r.muteState.hasAuxiliary))throw new Oe({code:ke.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:i}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:qe(be({},Ea),{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(i,t,e){Ta(this._room.isJoined,e);let r=this._room.remotePublishedUserMap.get(i.userId);if(qT(!!r,e,i),r&&(i.streamType==="main"&&!r.muteState.videoAvailable||i.streamType==="sub"&&!r.muteState.hasAuxiliary))throw new Oe({code:ke.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:i}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(i,t,e){if(i.userId!=="*"&&z(i.streamType))throw new Oe({code:ke.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(i,t,e){Ta(this._room.isJoining||this._room.isJoined,e)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(i,t,e,r){if(!fc)throw new Oe({code:ke.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new Oe({code:ke.INVALID_OPERATION,fnName:e,extraCode:5108});if(i.byteLength>1e3)throw new Oe({code:ke.INVALID_PARAMETER,extraCode:5018,fnName:e});if(i.byteLength===0)throw new Oe({code:ke.INVALID_PARAMETER,extraCode:5017,messageParams:{key:t},fnName:e});Ta(this._room.isJoined,e)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(i,t,e){if(!i&&!this._room.isMainStreamPublished||i&&!this._room.isAuxStreamPublished)throw new Oe({code:ke.INVALID_OPERATION,extraCode:5109,messageParams:{key:t},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(i,t,e,r){if(i.byteLength>1e3)throw new Oe({code:ke.INVALID_PARAMETER,extraCode:5018,fnName:e});if(i.byteLength===0)throw new Oe({code:ke.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:t}})}}},validate(i,t,e){if(Ta(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new Oe({code:ke.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:t}})}},switchRoom:{name:"switchRoomConfig",type:"object",required:!0,validate(i,t,e){if(Ta(this._room.isJoined,e),this._room.useStringRoomId&&i.strRoomId===this._room.roomId||!this._room.useStringRoomId&&i.roomId===Number(this._room.roomId))throw new Oe({code:ke.INVALID_PARAMETER,extraCode:5020,fnName:e,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(i.roomId&&this._room.useStringRoomId||!i.roomId&&i.strRoomId&&!this._room.useStringRoomId)throw new Oe({code:ke.INVALID_PARAMETER,extraCode:5019,fnName:e,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(i.roomId)XT(i.roomId,e,t);else if(i.strRoomId)JT(i.strRoomId,e,t);else throw new Oe({code:ke.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}}}},ur={TRTC:LR};var Or=class extends Error{};function PR(i,t){let e=Ns(i);for(let r=0;r<t.length;r++)Ei(e[r],t[r]);return e}function UR(i){this._resolve=Promise.resolve(i)}function VR(i){this._reject=Promise.reject(i)}var ns=class ns{constructor(t,e){this.instance=t;this.group=e;p(this,"started",!1);p(this,"ops",[]);p(this,"startSame",()=>!0);p(this,"mergeUpdate",PR);let r=ns.instances.get(t);r?r.set(e,this):ns.instances.set(t,new Map([[e,this]]))}static get(t,e){if(!e)return;let r=ns.instances.get(t);return r&&r.get(e)||new ns(t,e)}static gets(t,e){let r=ns.instances.get(t),o=[];return r&&r.forEach((s,n)=>{e.test(n)&&o.push(s)}),o}action(t,e,r){let o=a=>{var c;return t===0?this.started=!0:t===3&&(this.started=!1),this.ops.shift(),(c=this.currentOp)==null||c.action(),a},s=a=>{var c,d;throw this.ops.shift(),t===0&&((c=this.currentOp)==null?void 0:c.type)===2&&this.ops.shift().reject(new Or("start failed")),(d=this.currentOp)==null||d.action(),a},n={type:t,action:()=>e(...n.args).then(o,s),args:r,resolve:UR,reject:VR};try{switch(this.state){case 1:if(t===0)throw new Or("already started");break;case 4:if(t===2)throw new Or("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(o,s)}cacheOp(t){if(this.ops.length===1)switch(this.state){case 0:case 2:if(t.type===0)throw new Or("already start");break;case 3:switch(t.type){case 2:throw new Or("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new Or("unknown state")}else switch(t.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let r=new Or("keep stop");if(this.ops.slice(1).forEach(o=>o.reject(r)),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,t.args),this.lastOp.promise;case 3:throw new Or("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new Or("start not allowed after update");case 0:throw new Or("duplicate start");case 3:if(this.startSame(this.currentOp.args,t.args))throw this.ops.pop().reject(new Or("keep start")),new Or("already start")}}t.promise=new Promise((r,o)=>{t._resolve?t._resolve.then(r):t.resolve=r,t._reject?t._reject.catch(o):t.reject=o});let{action:e}=t;return t.action=()=>e().then(t.resolve,t.reject),this.ops.push(t),t.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}};p(ns,"instances",new WeakMap);var vo=ns;var kl=new WeakMap,Ll=(i,t)=>{if(t instanceof Or){let{stack:e}=t;t=new Oe({code:ke.OPERATION_ABORT,message:`${i} abort: ${t.message}`,fnName:i}),e&&(t.stack+=e.substr(e.indexOf(`
|
|
97
|
-
`)))}throw t};function as(i,t){return ut((e,r)=>function(...o){let s=vo.get(this,typeof i=="string"?i:i.call(this,...o));return s?(t&&(s.startSame=t.bind(this)),s.action(0,e.bind(this),o).catch(Ll.bind(null,r))):e.apply(this,o)})}function hn(i,t){let{merge:e,debounce:r}=t||{};return ut((o,s)=>function(...n){let a=vo.get(this,typeof i=="string"?i:i.call(this,...n));if(!a)return o.apply(this,n);if(e&&(a.mergeUpdate=e.bind(this)),r&&r.isNeedToDebounce.apply(this,n)){let{delay:c,getKey:d}=r;return new Promise((m,l)=>{var T,E;let f=(T=kl.get(this))==null?void 0:T.get(d(...n));if(f){let{timeoutId:y,resolve:v}=f;clearTimeout(y),v()}let g=setTimeout(()=>{if(a.state===3||a.state===4)return m();a.action(2,o.bind(this),n).catch(Ll.bind(null,s)).then(m,l)},c);kl.has(this)?(E=kl.get(this))==null||E.set(d(...n),{timeoutId:g,resolve:m}):kl.set(this,new Map([[d(...n),{timeoutId:g,resolve:m}]]))})}return a.action(2,o.bind(this),n).catch(Ll.bind(null,s))})}function cs(i){return ut((t,e)=>function(...r){let o=typeof i=="function"?i.call(this,...r):i;if(o instanceof RegExp)return Promise.all(vo.gets(this,o).map(n=>n.action(3,()=>Promise.resolve(),r))).then(()=>t.call(this,...r));let s=vo.get(this,o);return s?s.action(3,t.bind(this),r).catch(Ll.bind(null,e)):t.apply(this,r)})}function ds(){return function(i,t,e){return i.prototype[t]=function(){let r=this._log||console,o=`"${t}" is a static method. Use TRTC.${t}() instead. See: ${Br}/en/TRTC.html#.${t}`;r.warn(o)},e}}var Ne={ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",KICKED_OUT:"kicked-out",REMOTE_USER_ENTER:"remote-user-enter",REMOTE_USER_EXIT:"remote-user-exit",REMOTE_AUDIO_AVAILABLE:"remote-audio-available",REMOTE_AUDIO_UNAVAILABLE:"remote-audio-unavailable",REMOTE_VIDEO_AVAILABLE:"remote-video-available",REMOTE_VIDEO_UNAVAILABLE:"remote-video-unavailable",AUDIO_VOLUME:"audio-volume",AUDIO_FRAME:"audio-frame",NETWORK_QUALITY:"network-quality",CONNECTION_STATE_CHANGED:"connection-state-changed",AUDIO_PLAY_STATE_CHANGED:"audio-play-state-changed",VIDEO_PLAY_STATE_CHANGED:"video-play-state-changed",SCREEN_SHARE_STOPPED:"screen-share-stopped",DEVICE_CHANGED:"device-changed",PUBLISH_STATE_CHANGED:"publish-state-changed",TRACK:"track",STATISTICS:"statistics",SEI_MESSAGE:"sei-message",CUSTOM_MESSAGE:"custom-message",VIDEO_DECODE_DOWNGRADE_STATE_CHANGED:"video-decode-downgrade-state-changed",LAYER_DATA:"layerData",FIRST_VIDEO_FRAME:"first-video-frame",PERMISSION_STATE_CHANGE:"permission-state-change",VIDEO_SIZE_CHANGED:"video-size-changed"},YT=new Set([Ne.AUDIO_VOLUME,Ne.AUDIO_FRAME,Ne.NETWORK_QUALITY,Ne.STATISTICS,Ne.SEI_MESSAGE,Ne.CUSTOM_MESSAGE,Ne.LAYER_DATA]);var Uf={};eo(Uf,{ScheduleRequestType:()=>ey,getAbilityConfig:()=>FR,getScheduleDomain:()=>Vl,isNeedToSchedule:()=>Pl,scheduleProxy:()=>Qi,sendScheduleRequest:()=>Pf,setIsNeedToSchedule:()=>Ro,setScheduleProxy:()=>Ul});var Lf=null,KT=0,BR=48*3600*1e3,Pl=!0;typeof document!="undefined"&&document.head.insertAdjacentHTML("beforeend",Object.values(io).map(i=>`<link rel="dns-prefetch" href="https://${i}">`).join(`\r
|
|
98
|
-
`));function Ro(i){Nt(i)&&i!==Pl&&(Pl=i,se.info(`setIsNeedToSchedule ${i}`),i||(KT=Date.now()+BR))}ee.on("28",()=>Ro(!0));ee.on("63",()=>Ro(!0));ee.on("84",()=>Ro(!0));ee.on("201",i=>{i.state==="RECONNECTING"&&Ro(!0)});ee.on("202",i=>{i.state==="RECONNECTING"&&Ro(!0)});function $R(i,t,e){let r={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let o=performance.getEntriesByType("resource"),s=us(i,"config",j.MAIN),n=us(i,"config",j.BACKUP);for(let a of o)if(a.startTime>=e&&(a.name===s||a.name===n)&&a.transferSize>0){let c=a.name===s?j.MAIN:j.BACKUP,d=Math.round(a.duration),m=Math.round(a.domainLookupStart-a.startTime),l=a.redirectStart>0?Math.round(a.redirectEnd-a.redirectStart):0,f=a.fetchStart>0?Math.round(a.domainLookupStart-a.fetchStart):0,g=Math.round(a.domainLookupEnd-a.domainLookupStart),T=Math.round(a.requestStart-a.secureConnectionStart),E=Math.round(a.secureConnectionStart-a.connectStart),y=Math.round(a.responseStart-a.requestStart),v=Math.round(a.responseEnd-a.responseStart),M=[g,T,E,y,v];It.uploadEvent({log:`stat-schedule-net:${d}(${m}(${l}->${f})->${M.join("->")}) ${c}`,userId:t}),r=qe(be({},r),{totalCost:d,local:m,dns:g,tcp:E,tls:T,request:y,response:v});break}}catch(o){se.error("getScheduleDetailCost error",o)}return r}function Pf(d){return D(this,arguments,function*({userId:i,sdkAppId:t,useStringRoomId:e,roomId:r,userSig:o,version:s,frameWorkType:n,role:a,latencyLevel:c}){var l;if(!Pl&&Lf&&KT>Date.now())return{isCached:!0,result:Lf};let m={delta:0,count:[1,1],msg:[],detail:[]};try{let f=new FormData;f.append("userId",String(i)),f.append("sdkAppId",String(t)),f.append("isStrGroupId",String(e)),f.append("groupId",String(r)),f.append("sdkVersion",s),f.append("userSig",String(o));let g=((l=yield Us())==null?void 0:l.model)||Iu();g&&f.append("model",g);let T=ho();T&&f.append("osString",T),a&&f.append("role",String(a)),c&&f.append("latencyLevel",String(c)),n&&f.append("frameWorkType",String(n));let E=Xe(),y=yield WR(f,m,t);y.config&&(y.config.loggerDomain&&vs(y.config.loggerDomain),Nt(y.config.scheduleCache)&&Ro(!y.config.scheduleCache)),m.delta=Xe()-E;let v=$R(Number(t),i,E);return Lf=y,{isCached:!1,result:y,detailCost:v}}catch(f){let g=Gt(f)?f[0]:f,T=ft(g.code)?g.code:0,E=`schedule failed${g.message?`: ${g.message}`:""}`,y=new Me({code:Te.SCHEDULE_FAILED,extraCode:T,message:Et({key:_t.JOIN_ROOM_FAILED,data:{error:E,code:T}})});throw se.error(E,T),y}})}var Qi={main:"",backup:""};function Ul(i){Gt(i)?(Qi.main=i[0],Qi.backup=i[1]):Qi.main=i}var ey=(r=>(r.CONFIG="config",r.TRTC_AUTO_CONF="trtcAutoConf",r.AUDIO_AI_AUTH="audioAiAuth",r))(ey||{});function us(i,t,e=j.MAIN,r=!1){return`https://${Qi[e]||Vl(i,e,r)}/api/v1/${t}`}function FR(i,t,e){let r=us(i,t),o=us(i,t,j.BACKUP),s=new URLSearchParams(e).toString(),n=fetch(`${r}?${s}`).then(c=>c.json()),a=fetch(`${o}?${s}`).then(c=>c.json());return Fa([n,a])}function Vl(i,t=j.MAIN,e=!1){let r;return si(i)?e?r=t===j.MAIN?io.MAIN_OVERSEA_BACKUP:io.BACKUP_OVERSEA:r=t===j.MAIN?io.MAIN_OVERSEA:io.BACKUP_OVERSEA:r=t===j.MAIN?io.MAIN:io.BACKUP,r}function HR(i,t,e){return new Promise((r,o)=>{no({url:i,body:t,timeout:e.timeout,priority:"high"}).then(s=>{s.data.code===0?r(s.data.data):o({code:s.data.code,message:s.data.msg})}).catch(o)})}var ZT=(i,t)=>Ho({retryFunction:HR,settings:{retries:3,timeout:0},onError:t,onRetrying:i});function WR(i,t,e){return new Promise((r,o)=>{let s=null;Fa([ZT(n=>t.count[0]=n+1,({error:n,retry:a,retriedCount:c,retryFuncArgs:d})=>{t.msg[0]=n.message,s||(c>=1&&(d[0]=us(e,"config",j.MAIN,!0)),a())})(us(e,"config",j.MAIN),i,{get timeout(){return Ds(2+t.count[0])*1e3}}),ZT(n=>t.count[1]=n+1,({error:n,retry:a,retriedCount:c,retryFuncArgs:d})=>{t.msg[1]=n.message,s||(c>=2&&(d[0]=us(e,"config",j.BACKUP,!0)),a())})(us(e,"config",j.BACKUP),i,{get timeout(){return Ds(2+t.count[1])*1e3}})]).then(n=>{s=n,r(s)}).catch(o)})}var GR=i=>i.startsWith("data:application/octet-stream;base64,"),zR=i=>i.startsWith("file://"),Qc=class{constructor(){p(this,"_log");this._log=se.createLogger({id:"fd"})}download(t,e){return D(this,null,function*(){let{type:r="blob"}=e||{};t=xs(t);try{let o=Xe(),s;if(Rt(fetch)?s=yield this.downloadWithFetch(t,r):s=yield this.downloadWithXHR(t,r),!s||!s.data)throw new Error("data is empty");let n=Xe()-o;return this._log.info(`downloaded: ${t}, return type: ${r}, cost: ${n}ms`),Se.addSuccessEvent({key:522700,cost:Xe()-o}),s.data}catch(o){throw this._log.error(`failed to download: ${t}, error: ${o}`),Se.addFailedEvent({key:522700,error:o}),o}})}downloadWithFetch(t,e){return D(this,null,function*(){this._log.info(`download with fetch: ${t}, return type: ${e}`);try{let r=yield fetch(t);if(!r.ok){let s=new Error(`network response was not ok: ${r.status}`);throw s.status=r.status,s}let o;return e==="arraybuffer"?o=yield r.arrayBuffer():o=yield r.blob(),{data:o}}catch(r){throw r}})}downloadWithXHR(t,e){return this._log.info(`download with xhr: ${t}, return type: ${e}`),new Promise((r,o)=>{let s=new XMLHttpRequest;s.open("GET",t,!0),s.responseType=e,s.onload=()=>{if(s.status===200||s.status===0&&s.response)r({data:s.response});else{let n=new Error(`XHR failed, status: ${s.status}`);n.status=s.status,o(n)}},s.onerror=o,s.send(null)})}loadWasm(t,e){return D(this,null,function*(){this._log.info(`loadWasm ${t}, importObject: ${JSON.stringify(e)}`);let r=Xe(),o=null,s=null;if(Rt(WebAssembly.instantiateStreaming)&&!GR(t)&&!zR(t)&&Rt(fetch))try{let n=fetch(t);o=(yield WebAssembly.instantiateStreaming(n,e)).instance}catch(n){s=n}if(!o)try{let n=yield this.download(t,{type:"arraybuffer"});o=(yield WebAssembly.instantiate(n,e)).instance}catch(n){s=n}if(o){let n=Xe()-r;return this._log.info(`loadedWasm ${t}, cost: ${n}ms`),Se.addSuccessEvent({key:522701,cost:n}),o}throw this._log.error(`failed to loadWasm ${t}, error: ${s}`),Se.addFailedEvent({key:522701,error:s}),s})}loadScript(t){this._log.info(`loadScript ${t}`);let e=Xe();return new Promise((r,o)=>{let s=document.createElement("script");s.type="text/javascript",s.onload=()=>{this._log.info(`loadedScript ${t}, cost: ${Xe()-e}ms`),Se.addSuccessEvent({key:522702,cost:Xe()-e,split:1e3}),r(s)},s.onerror=n=>{this._log.error(`failed to loadScript ${t}, error: ${(n==null?void 0:n.message)||JSON.stringify(n)}`),Se.addFailedEvent({key:522702}),o(n)},s.crossOrigin="anonymous",s.src=t,document.head.append?document.head.append(s):document.getElementsByTagName("head")[0].appendChild(s)})}};Ie([qs({settings:{timeout:0,retries:3},onError(t,e,r){var o;(t==null?void 0:t.status)===404||(o=t==null?void 0:t.message)!=null&&o.includes("404")?(this._log.warn("download 404, stop retry"),r(t)):e()},onRetrying(t){this._log.warn(`download retrying: ${t}`)}})],Qc.prototype,"download",1),Ie([qs({settings:{timeout:3e3,retries:3},onRetrying(t){this._log.warn(`loadScript retrying: ${t}`)}})],Qc.prototype,"loadScript",1);var Yc=new Qc;function ty({TRTC:i,room:t,errorModule:e,assetsPath:r}){return{TRTC:i,LocalMixVideoTrack:nn,LocalVideoTrack:Zr,LocalScreenTrack:zi,room:t,assetsPath:r,fileDownloader:Yc,innerEmitter:ee,INNER_EVENT:ce,constants:zh,environment:Qn,utils:uf,eventLogger:It,log:this.room.getLogger(),loggerManager:se,errorModule:e,kvStatManager:Se,rtcDectection:Jo,trtc:this,rx:af,enums:$m,schedule:Uf,getDevices:oa,initVisionTaskRegistry:(o,s="/mediapipe/vision.js")=>D(this,null,function*(){window.VisionTaskRegistry||(yield Yc.loadScript(`${o}/${s}`.replace(/([^:]\/)\/+/g,"$1"))),yield(yield window.VisionTaskRegistry.getInstance(o)).preloadModels([window.VisionTaskType.ImageSegmenter])}),audioContext:bt(),deviceDetector:$t,AudioPlayer:na,showAutoPlayDialog:ta,Timer:Jt,clearStarted:(o,s)=>{let n=o.getAlias(),a=vo.instances.get(this);if(a)if(s){let c=a.get(n+s);if(!c)return;c.started=!1}else a.forEach((c,d)=>{d.startsWith(n)&&(c.started=!1)})},startGetPCM:Vc,createAudioNode:Rc,getNetworkTimeOffset:Ng,validateSourceNode:()=>{var o;if(zt&&!((o=this.room.audioManager._localAudioPipline)!=null&&o.source.node))throw new Oe({code:ke.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 ry=(i,t)=>{let{emit:e}=i;return i.emit=(...r)=>{try{return e.apply(i,r)}catch(o){let s=Et({key:_t.CATCH_HANDLER_ERROR,data:{name:t,event:r[0]},addDocLink:!1});return se.warn(`${s}
|
|
52
|
+
} `;var _o=class extends q{constructor(e){super();d(this,"frameRate");d(this,"_canvas");d(this,"log");d(this,"hasAlpha",!1);d(this,"name");d(this,"error");this.name=e.name,this.log=e.logger.createChild({id:`vc-${this.name}`}),this.frameRate=e.frameRate}get canvas(){return this._canvas}set width(e){this._canvas&&(this._canvas.width=e)}get width(){var e;return((e=this._canvas)==null?void 0:e.width)||0}set height(e){this._canvas&&(this._canvas.height=e)}get height(){var e;return((e=this._canvas)==null?void 0:e.height)||0}setSize(e,t){this._canvas&&(this._canvas.width=e,this._canvas.height=t)}createVideoTrackSource(e,t){return new Gt(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new fs(this,e)}createVideoImageSource(e,t){return new $n(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new Wn(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}createTextSource(e,t){return new Kc(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}};d(_o,"_ids",0);var ES={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},_s=class _s extends _o{constructor(){super(...arguments);d(this,"defaultProgam");d(this,"defaultVShader");d(this,"defaultFShader");d(this,"ctx");d(this,"_canvas2d")}get canvas(){return this._canvas2d||this._canvas}create(e=!1){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${_o._ids++}`),e&&(this._canvas2d=document.createElement("canvas")),this.ctx=this._canvas.getContext("webgl2",ES),!this.ctx)throw new D({code:I.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,gS),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,TS),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})}destroy(e){let t="";return e&&(t=e.message,this.error=e,v.addFailedEvent({key:512702,error:e})),this.disconnect(),this.log.info(`video context destroy${t}`?`: ${t}`:""),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),e}set width(e){var t;(t=this.ctx)==null||t.viewport(0,0,e,this.height),super.width=e,this._canvas2d&&(this._canvas2d.width=e)}set height(e){var t;(t=this.ctx)==null||t.viewport(0,0,this.width,e),super.height=e,this._canvas2d&&(this._canvas2d.height=e)}setSize(e,t){var r;(r=this.ctx)==null||r.viewport(0,0,e,t),super.setSize(e,t),this._canvas2d&&(this._canvas2d.width=e,this._canvas2d.height=t)}createShader(e,t){let r=this.ctx,s=r.createShader(e);return r.shaderSource(s,t),r.compileShader(s),s}createProgram(e,t){let r=this.ctx,s=r.createProgram();return r.attachShader(s,e),r.attachShader(s,t),r.linkProgram(s),r.getProgramParameter(s,r.LINK_STATUS)||this.log.error(r.getProgramInfoLog(s)),s}};d(_s,"UNAVAILABLE","unavailable"),O([ye(q.INIT,"created",{sync:!0,fail(e){this.log.error("video gl context create failed",e.cause),v.addFailedEvent({key:512700,error:e.cause||e})},success(){this.log.info("video context created use webgl"),v.addSuccessEvent({key:512700})}})],_s.prototype,"create",1),O([ye("created",q.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(_s.UNAVAILABLE,e),this.removeAllListeners()}})],_s.prototype,"destroy",1);var Fe=_s,ze=class extends _o{constructor(){super(...arguments);d(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${_o._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:e.alpha,willReadFrequently:e.willReadFrequently}),!this.ctx)throw new D({code:I.VIDEO_MANAGER_ERROR,extraCode:2,message:"2d context not supported"});this._canvas.addEventListener("contextlost",()=>{this.log.error("2d context lost")}),this._canvas.addEventListener("contextrestored",()=>{this.log.warn("2d context restored")})}destroy(e){let t="";e&&(t=e.message,this.error=e,v.addFailedEvent({key:512703,error:e})),this.disconnect(),this.log.info(`video context destroy ${t?`: ${t}`:""}`),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners(),v.addSuccessEvent({key:512703})}};O([ye(q.INIT,"created",{sync:!0,fail(e){this.log.error("video 2d context create failed",e.cause),v.addFailedEvent({key:512701,error:e.cause||e})},success(){this.log.info("video context created use 2d"),v.addSuccessEvent({key:512701})}})],ze.prototype,"create",1),O([ye("created",q.INIT,{ignoreError:!0,sync:!0})],ze.prototype,"destroy",1);function SS(o,i,e,t,r,s=!1){s&&([e,t]=[t,e]);let n={sWidth:o,sHeight:i,dWidth:e,dHeight:t,sx:0,sy:0,dx:0,dy:0};if(o===0||i===0)return n;switch(r){case void 0:case"fill":break;case"contain":{let a=Math.min(e/o,t/i);n.dWidth=o*a,n.dHeight=i*a,n.dx=(e-n.dWidth)/2,n.dy=(t-n.dHeight)/2;break}case"cover":{let a=Math.max(e/o,t/i),c=e/a,l=t/a;n.sx=(o-c)/2,n.sy=(i-l)/2,n.sWidth=c,n.sHeight=l;break}}return n}var Ih=class{constructor(i,e){this.node=i;this.layout=e;d(this,"positionBuffer")}get x(){return this.layout.x||this.node.x}get y(){return this.layout.y||this.node.y}get width(){return this.layout.width||this.node.width}get height(){return this.layout.height||this.node.height}get right(){return this.x+this.width}get bottom(){return this.y+this.height}get fillMode(){return this.layout.fillMode}get rotation(){return this.layout.rotation}get hidden(){return!!this.layout.hidden}},gs=class extends Ue{constructor(e,t){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:t});d(this,"inputs",[]);d(this,"backgroundColor","black")}addInput(e,t){let r=0,s=this.inputs.length;for(;r<s;){let a=Math.floor((r+s)/2);if(this.inputs[a].layout.zIndex<t.zIndex)r=a+1;else if(this.inputs[a].layout.zIndex>t.zIndex)s=a;else throw new Error(`input already exists at zIndex ${t.zIndex}`)}let n=new Ih(e,t);this.inputs.splice(r,0,n)}changeInputLayout(e,t){let r=this.inputs.findIndex(g=>g.node===e);if(r<0)return;let{x:s,y:n,width:a,height:c,zIndex:l,fillMode:u,rotation:h,hidden:m}=t;if(!T(l)&&this.inputs.some(g=>g.layout.zIndex===l&&g.node!==e))throw new Error(`input already exists at zIndex ${t.zIndex}`);let _=this.inputs[r];T(s)||(_.layout.x=s),T(n)||(_.layout.y=n),T(a)||(_.layout.width=a),T(c)||(_.layout.height=c),T(h)||(_.layout.rotation=h),T(m)||(_.layout.hidden=m),u&&(_.layout.fillMode=u),!T(l)&&l!==_.layout.zIndex&&(_.layout.zIndex=l,this.inputs.sort((g,E)=>g.layout.zIndex-E.layout.zIndex))}hasInput(e){return this.inputs.some(t=>t.node===e)}hasNoInput(){return this.inputs.length===0}resize(e,t){if(!this.matchInputSize){super.resize(e,t);return}let r=this.inputs.reduce((s,n)=>n?Object.assign(s,{width:Math.max(s.width,n.right),height:Math.max(s.height,n.bottom)}):s,{width:0,height:0});super.resize(r.width,r.height),this.context instanceof Fe&&this.inputs.forEach(s=>{if(s){let n=this.layout2texCoords(s);s.positionBuffer?this.changeBufferData(s.positionBuffer,n):s.positionBuffer=this.createBuffer(n)}})}connect(e,...t){return super.connect(e,...t),this.drawBackGround2d(this.backgroundColor),this.matchInputSize&&this.resize(0,0),e}removeInput(e){this.inputs=this.inputs.filter(t=>t.node!==e),this.inputs.length===0&&this.drawBackGround2d(this.backgroundColor)}render(e){let t=this.context.ctx;if(t.clearColor(0,0,0,0),this.inputs.reduce((s,n)=>n.node.requestFrame(e)||s,!1)&&t){this.useProgram(),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let s=0;s<this.inputs.length;s++){let n=this.inputs[s];n&&(n.node.useTexture(),this.draw(n.positionBuffer))}return!0}return!1}render2d(e){if(this.inputs.forEach(t=>t.node.requestFrame(e)),this.ctx2d){this.drawBackGround2d(this.backgroundColor);for(let t=0;t<this.inputs.length;t++){let r=this.inputs[t];if(r.hidden)continue;let s=SS(r.node.width,r.node.height,r.width,r.height,r.fillMode,bt(r.rotation));this.draw2d(r.node.image,r.x+s.dx,r.y+s.dy,s.dWidth,s.dHeight,s.sx,s.sy,s.sWidth,s.sHeight)}return!0}return!1}debugLayout(e,t,r,s,n=!1){this.ctx2d&&(n&&([r,s]=[s,r]),this.ctx2d.save(),this.ctx2d.strokeStyle="red",this.ctx2d.lineWidth=2,this.ctx2d.strokeRect(e,t,r,s),this.ctx2d.restore())}getInfo(){let{totalFrames:e,x:t,y:r,width:s,height:n,name:a}=this,c=Date.now(),l=(e-this.lastInfo.totalFrames)/((c-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:r,width:s,height:n,timestamp:c,fps:l,name:a},M({parent:this.inputs.filter(u=>u).map(u=>u.node.getInfo())},this.lastInfo)}removeAllInputs(){this.inputs.forEach(e=>{var t;if(e.node.disconnect(),e.positionBuffer&&this.context instanceof Fe)try{(t=this.context.ctx)==null||t.deleteBuffer(e.positionBuffer)}catch(r){}})}close(){super.close(),this.removeAllInputs()}};var IS=[1,0,0,0,1,1,0,1],Jt=class extends Ue{constructor(e,t,r,s){super(e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"transform",logger:t});d(this,"mirror",!1);d(this,"rotation",0);if(r&&(this.mirror=r),s&&(this.rotation=s),e instanceof Fe)try{this.setTexBuffer(IS)}catch(n){e.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${n.message||n}`}))}}draw2d(e,t,r,s,n){if(this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height),this.ctx2d.save(),this.mirror&&(this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0)),this.rotation===90?(this.ctx2d.translate(s,0),this.ctx2d.rotate(Math.PI/2),this.ctx2d.scale(n/s,s/n)):this.rotation===180?(this.ctx2d.translate(this.width,this.height),this.ctx2d.rotate(Math.PI)):this.rotation===270&&(this.ctx2d.translate(0,n),this.ctx2d.rotate(3*Math.PI/2),this.ctx2d.scale(n/s,s/n));let a=super.draw2d(e,t,r,s,n);return this.ctx2d.restore(),a}return!1}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}resize(e,t){bt(this.rotation)&&([e,t]=[t,e]),super.resize(e,t)}};var go=class extends fi{constructor(e,t=4){super(t,it);d(this,"inputLocalVideoTracks",new Map);d(this,"inputLocalScreenTracks",new Map);d(this,"cameraNodeMap",new Map);d(this,"screenNodeMap",new Map);d(this,"textNodeMap",new Map);d(this,"imageNodeMap",new Map);d(this,"videoNodeMap",new Map);d(this,"endedIds",new Set);d(this,"videoContext");d(this,"mixNode");d(this,"destination");d(this,"manager");d(this,"stat");d(this,"_checkId",0);d(this,"autoSetFps",!0);this.manager=e,this.log.id+="mix",this.create2dVideoContext(),this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log}),this.destination.on(Ue.RENDER,r=>{this.emit("render",r)}),this.mixNode=new gs(this.videoContext,this.log),this.mixNode.matchInputSize=!1}listenDeviceChange(){throw new Error("Method not implemented.")}enablePrintDetail(e=2e3){this._checkId=re.run("interval",()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:e})}create2dVideoContext(){this.videoContext?this.videoContext.destroy():this.videoContext=new ze({frameRate:15,logger:this.log,name:"mix-ctx"}),this.videoContext.create({alpha:!1})}setFps(e){this.autoSetFps=!1,this.videoContext.frameRate=e;for(let t of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])t.shouldUpdate=!1;setTimeout(()=>{var t;return(t=this.destination)==null?void 0:t.start(this.videoContext.frameRate)},500)}setFpsAuto(){var s;if(!this.autoSetFps)return;for(let n of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])n.shouldUpdate=!1;let e=null,t=0,r=!0;for(let[n,a]of this.inputLocalVideoTracks)if(a.profile.frameRate>t){if(this.endedIds.has(n)){let c=this.cameraNodeMap.get(n);c&&c.image.cancelVideoFrameCallback(c.videoCallbackId);continue}t=a.profile.frameRate,e=n}for(let[n,a]of this.inputLocalScreenTracks)if(a.profile.frameRate>t){if(this.endedIds.has(n)){let c=this.screenNodeMap.get(n);c&&c.image.cancelVideoFrameCallback(c.videoCallbackId);continue}t=a.profile.frameRate,e=n,r=!1}if(e!==null){let n=r?this.cameraNodeMap.get(e):this.screenNodeMap.get(e);n&&(n.shouldUpdate=!0,n.tryVideoFrameCallback()),this.log.info("set mix fps: ",t)}else(s=this.destination)==null||s.start(this.videoContext.frameRate),this.log.info("fallback to timer, fps: ",this.videoContext.frameRate)}setMixBackground(e){this.mixNode&&(this.mixNode.backgroundColor=e)}resizeMixCanvas(e,t){var r;(r=this.mixNode)==null||r.resize(e,t)}startMix(){return f(this,null,function*(){var e;if(!this.mixNode||!this.destination)throw new Error("can't mix without necessary conditions");this.mixNode.disconnect(),this.mixNode.connect(this.destination),Ft&&this.player.setCanvas(this.videoContext._canvas),this.setOutputMediaStreamTrack(this.destination.videoTrack),(e=this.manager)==null||e.changeInput(this)})}addCameraSource(e,t,r){if(this.inputLocalVideoTracks.has(e)||this.cameraNodeMap.has(e))throw new Error(`There is already a cameraSource with the same ID: ${e}`);let{mediaTrack:s}=t;if(!s)throw new Error("no mediaTrack, add cameraSource failed");t.recaptureMode=1,tt(this,be).add("videoInputRemoved",a=>{a.deviceId===t.deviceId&&(this.endedIds.add(e),this.setFpsAuto())}),t.on("output-media-track-changed",()=>{this.endedIds.delete(e),this.updateCameraSource(e,r,t.mediaTrack)});let n;et===16&&s instanceof CanvasCaptureMediaStreamTrack?n=this.videoContext.createVideoImageSource(s.canvas,{name:"cameraCanvasSource",logger:this.log}):n=this.videoContext.createVideoTrackSource(s,"cameraNodeSource"),n.resize(t.settings.width,t.settings.height),n.shouldUpdate=!1,this._connectMix(n,r,"cover"),this.inputLocalVideoTracks.set(e,t),this.cameraNodeMap.set(e,n),this.setFpsAuto()}addScreenSource(e,t,r){if(this.inputLocalScreenTracks.has(e)||this.screenNodeMap.has(e))throw new Error(`There is already a screenSource with the same ID: ${e}`);let{mediaTrack:s}=t;if(!s)throw new Error("no mediaTrack, add cameraSource failed");let n=this.videoContext.createVideoTrackSource(s,"screenNodeSource");n.resize(t.settings.width,t.settings.height),n.shouldUpdate=!1,this._connectMix(n,r),this.inputLocalScreenTracks.set(e,t),this.screenNodeMap.set(e,n),this.setFpsAuto()}addTextSource(e){let{id:t,content:r="",font:s,color:n,layout:a}=e;if(this.textNodeMap.has(t))throw new Error(`There is already a textSource with the same ID: ${t}`);let c=this.videoContext.createTextSource({content:r,font:s,color:n});c.resize(a.width,a.height),this._connectMix(c,a),this.textNodeMap.set(t,c)}addImageSource(e,t,r){if(this.imageNodeMap.has(e))throw new Error(`There is already a imageSource with the same ID: ${e}`);let s=this.videoContext.createVideoImageSource(t,{autoResize:!1,logger:this.log});s.resize(t.width,t.height),this._connectMix(s,r),this.imageNodeMap.set(e,s)}addVideoSource(e,t,r){if(this.videoNodeMap.has(e))throw new Error(`There is already a videoSource with the same ID: ${e}`);let s=this.videoContext.createVideoImageSource(t,{autoResize:!1,logger:this.log});s.resize(t.videoWidth,t.videoHeight),s.shouldUpdate=!1,this._connectMix(s,r),this.videoNodeMap.set(e,s)}updateCameraSource(e,t,r=null,s){let n=this.cameraNodeMap.get(e);if(n){if(r){if(et===16&&r instanceof CanvasCaptureMediaStreamTrack)if(n instanceof Gt){let l=n.output;n.close(),n=this.videoContext.createVideoImageSource(r.canvas,{name:"cameraCanvasSource",logger:this.log}),n.connect(l),this.cameraNodeMap.set(e,n)}else n.image=r.canvas;else if(n instanceof Gt)n.replaceTrack(r);else{let l=n.output;n.close(),n=this.videoContext.createVideoTrackSource(r,"cameraNodeSource"),n.connect(l),this.cameraNodeMap.set(e,n)}let{width:a,height:c}=r.getSettings();a&&c&&n.resize(a,c)}s&&n.resize(s.width,s.height),(s||r)&&this.setFpsAuto(),this._changeMixLayout(n,t)}}updateScreenSource(e,t){let r=this.screenNodeMap.get(e);r&&this._changeMixLayout(r,t)}updateTextSource(e){let{id:t,content:r,font:s,color:n,layout:a}=e,c=this.textNodeMap.get(t);c&&(T(r)||(c.content=r),T(s)||(c.font=s),T(n)||(c.color=n),c.resize(a.width,a.height),this._changeMixLayout(c,a))}updateImageSource(e,t,r){let s=this.imageNodeMap.get(e);s&&(r&&(s.image=r,s.resize(r.width,r.height)),this._changeMixLayout(s,t))}updateVideoSource(e,t,r){let s=this.videoNodeMap.get(e);if(s){if(r){let n=s.image;n instanceof HTMLVideoElement&&this.stopVideoElement(n),s.image=r,s.resize(r.videoWidth,r.videoHeight)}this._changeMixLayout(s,t)}}_connectMix(e,t,r="contain"){if(!this.mixNode)return;let{mirror:s,rotation:n}=t;e.disconnect();let a=new Jt(this.videoContext,this.log,s,n);a=e.connect(a),t.fillMode||(t.fillMode=r),a.connect(this.mixNode,t)}_changeMixLayout(e,t){if(!this.mixNode)return;let{mirror:r,rotation:s}=t,n=e.output||e;n instanceof Jt&&(T(r)||(n.mirror=r),T(s)||(n.rotation=s),n.resize(e.width,e.height)),this.mixNode.changeInputLayout(n,t)}removeCameraSource(e){let t=this.inputLocalVideoTracks.get(e);if(!t)return;t.close(),this.inputLocalVideoTracks.delete(e);let r=this.cameraNodeMap.get(e);r&&(r.output instanceof Jt&&r.output.close(),r.close(),this.cameraNodeMap.delete(e)),this.checkAfterRemove(!0)}removeScreenSource(e){let t=this.inputLocalScreenTracks.get(e);if(!t)return;t.close(),this.inputLocalScreenTracks.delete(e);let r=this.screenNodeMap.get(e);r&&(r.output instanceof Jt&&r.output.close(),r.close(),this.screenNodeMap.delete(e)),this.checkAfterRemove(!0)}removeTextSource(e){let t=this.textNodeMap.get(e);t&&(t.output instanceof Jt&&t.output.close(),t.close(),this.textNodeMap.delete(e)),this.checkAfterRemove()}removeImageSource(e){let t=this.imageNodeMap.get(e);t&&(t.output instanceof Jt&&t.output.close(),t.close(),this.imageNodeMap.delete(e)),this.checkAfterRemove()}removeVideoSource(e){let t=this.videoNodeMap.get(e);t&&(t.output instanceof Jt&&t.output.close(),t.image instanceof HTMLVideoElement&&this.stopVideoElement(t.image),t.close(),this.videoNodeMap.delete(e)),this.checkAfterRemove()}checkAfterRemove(e=!1){e&&this.setFpsAuto()}stopVideoElement(e){e.pause(),e.src="",e.srcObject=null,e.remove()}close(){var e;super.close(),re.clearTask(this._checkId),(e=this.videoContext)==null||e.destroy(),delete this.mixNode,delete this.destination;for(let t of[...this.inputLocalVideoTracks.values(),...this.inputLocalScreenTracks.values()])t.close();this.inputLocalVideoTracks.clear(),this.inputLocalScreenTracks.clear(),this.cameraNodeMap.clear(),this.screenNodeMap.clear(),this.textNodeMap.clear(),this.imageNodeMap.clear(),Le(this);for(let t of this.videoNodeMap.values())t.image instanceof HTMLVideoElement&&this.stopVideoElement(t.image);this.videoNodeMap.clear(),this.log.info("localMixVideoTrack close, stop mix")}};var ed=cn();if(typeof navigator!="undefined"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:ed,exposeOrigin:!0,permittedOrigins:["*"]})}catch(o){}var AS=function(o){return f(this,null,function*(){let i=null,e=yS(o);R.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let t=yield navigator.mediaDevices.getDisplayMedia(e);o.systemAudio&&t.getAudioTracks().length===0&&(Ko&&qe<74||Pe||te)&&R.warn("Your browser not support capture system audio");let r=t.getVideoTracks()[0];if(r){if(o.frameRate)try{yield r.applyConstraints({frameRate:{min:o.frameRate,ideal:o.frameRate},width:o.width,height:o.height})}catch(s){R.warn(`screen applyConstraints failed: ${s}`)}o.captureElement&&(yield CS(r,o.captureElement))}if(o.audio){let s=RS(o);R.info(`getUserMedia with constraints: ${JSON.stringify(s)}`),i=yield navigator.mediaDevices.getUserMedia(s),t.addTrack(i.getAudioTracks()[0])}return t})};function CS(o,i){return f(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&ue(o.cropTo))try{if(!(((e=o.getCaptureHandle())==null?void 0:e.handle)===ed))return;let r=yield CropTarget.fromElement(i);yield o.cropTo(r)}catch(t){R.warn(`cropTo target failed ${t}`)}})}function RS(o){let i={echoCancellation:o.echoCancellation,autoGainControl:o.autoGainControl,noiseSuppression:o.noiseSuppression,sampleRate:o.sampleRate,channelCount:o.channelCount};return T(o.microphoneId)||(i.deviceId=o.microphoneId),{audio:i,video:!1}}function yS(o){let i={preferCurrentTab:o.preferDisplaySurface==="current-tab"||!!o.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:Pe?{max:o.width}:{ideal:o.width,max:o.width},height:Pe?{max:o.height}:{ideal:o.height,max:o.height},frameRate:o.frameRate,displaySurface:o.preferDisplaySurface||"monitor"};if(i.video=e,o.systemAudio){let{echoCancellation:t=!0,noiseSuppression:r=!1,autoGainControl:s=!1}=o;i.audio={echoCancellation:t,noiseSuppression:r,autoGainControl:s,sampleRate:48e3}}return i}var gf=AS;var Pt=class extends Xe{constructor(e){super(e,2);d(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600});d(this,"objectFit","contain");d(this,"isScreen",!0);this._log.id=`s-${this._log.id}`}get isShareCurrentTab(){var e,t;try{return ed===((t=(e=this.mediaTrack)==null?void 0:e.getCaptureHandle())==null?void 0:t.handle)}catch(r){return}}capture(u){return f(this,arguments,function*({systemAudio:e=!1,autoGainControl:t,echoCancellation:r,noiseSuppression:s,audioTrack:n,videoTrack:a,captureElement:c,preferDisplaySurface:l}){try{let h;return a||n?(h=new MediaStream,a&&h.addTrack(a),n&&h.addTrack(n)):(h=yield gf({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:t,echoCancellation:r,noiseSuppression:s,captureElement:c,preferDisplaySurface:l}),this.sourceTrack=h.getVideoTracks()[0]),yield this.setInputMediaStreamTrack(h.getVideoTracks()[0]),h}catch(h){throw this.log.error(`getDisplayMedia error observed ${h}`),h instanceof D?h:new D({code:I.INITIALIZE_FAILED,name:h.name,message:h.message})}})}switchDevice(e){return f(this,null,function*(){throw new Error("Method not implemented.")})}};O([Ct(function(e){this.setContentHint(e.contentHint||"detail")})],Pt.prototype,"capture",1);var To=class extends kt{constructor(i){super(i),this._log.id=`s-${this._log.id}`,this.isScreen=!0}addAudioProcessor(i,e,t){this.pipeline.silentNode.setNode(t),this.pipeline.mixNode.setNode(e),this.pipeline.aec.setNode(i),this.enableTrackAEC(!1)}removeAudioProcessor(i){this.pipeline.aec.node===i&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode(),this.enableTrackAEC(!0))}};var bS='registerProcessor("dumper",class extends AudioWorkletProcessor{constructor(e){super(),this.sourceSampleRate=e.processorOptions.sourceSampleRate||48e3,this.targetSampleRate=e.processorOptions.targetSampleRate||48e3,this.port.onmessage=e=>{this.port2=e.data.port}}process(e){return(this.port2||this.port).postMessage(this.resampleAll(e,this.sourceSampleRate,this.targetSampleRate)),!0}resampleAll(r,s,a){if(s===a)return r;var o=[];for(let t=0;t<r.length;t++){o[t]=[];for(let e=0;e<r[t].length;e++)o[t][e]=this.resample(r[t][e],s,a)}return o}resample(t,e,r){if(e===r)return t;var s=Math.round(t.length*(this.targetSampleRate/this.sourceSampleRate)),a=new Float32Array(s),o=(t.length-1)/(s-1);a[0]=t[0];for(let e=1;e<s-1;e++){var l=e*o,p=Math.floor(l),h=Math.ceil(l);a[e]=t[p]+(t[h]-t[p])*(l-p)}return a[s-1]=t[t.length-1],a}});',Ah;function Gn(o,i=48e3,e=1,t){return f(this,null,function*(){let r=Se("dump");Ah||(Ah=tr(r,URL.createObjectURL(new Blob([bS],{type:"application/javascript"})))),yield Ah;let s=r.sampleRate,n=new AudioWorkletNode(r,"dumper",{numberOfInputs:o.length,numberOfOutputs:0,processorOptions:{sourceSampleRate:s,targetSampleRate:i}});return n.channelCountMode="explicit",n.channelCount=e,t&&n.port.postMessage({port:t},[t]),o.forEach((a,c)=>a.connect(n,0,c)),new ReadableStream({start(a){n.port.onmessage=c=>{a.enqueue(c.data)}},cancel(){o.forEach(a=>a.disconnect(n)),n.port.close()}})})}var td=class extends bc{constructor(e){super();this.room=e;d(this,"_localAudioTrack");d(this,"_localScreenAudioTrack");d(this,"log");d(this,"denoiser");d(this,"voiceChanger");d(this,"mixChangedDebounce");d(this,"audioProcessor");d(this,"encodePipeline",[]);d(this,"decodePipeline",[]);d(this,"getPCMAbortCtrlMap",new Map);d(this,"audioFrameEventConfigMap",new Map);d(this,"audioReferenceMap",new Map);d(this,"isLocalAudioNeedAudioProcess",!1);d(this,"isScreenAudioNeedAudioProcess",!1);this.log=R.createLogger({parent:e==null?void 0:e.getLogger(),id:"am",userId:e==null?void 0:e.userId,sdkAppId:e==null?void 0:e.sdkAppId}),this.installEvent()}get localAudioTrack(){return this._localAudioTrack}get _localAudioPipline(){var e;return(e=this._localAudioTrack)==null?void 0:e.pipeline}get _localScreenAudioPipeline(){var e;return(e=this._localScreenAudioTrack)==null?void 0:e.pipeline}dump(e){var u,h;if(!this._localAudioTrack)return;let t=[],r=[];(u=this._localAudioPipline)!=null&&u.source.node&&(t.push(this._localAudioPipline.source.node),r.push("mic")),(h=this._localAudioPipline)!=null&&h.denoiser.node&&(t.push(this._localAudioPipline.denoiser.node),r.push("mic-processed")),this.mixWeight>1&&(t.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),r.push("mix")),this.log.info(`dump audio track ${r}, duration: ${e}`);let s=new AbortController,n=[],a=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),s.abort("timeout")},e*1e3),c=()=>{for(let m=0;m<r.length;m++){let _=URL.createObjectURL(new Blob(n[m])),g=document.createElement("a");g.href=_,g.download=`${r[m]}.pcm`,g.style.display="none",document.body.appendChild(g),g.click(),URL.revokeObjectURL(_),g.remove()}clearTimeout(a),s.abort("download")},l=Gn(t).then(m=>m.pipeTo(new WritableStream({write(_){_.forEach((g,E)=>n[E]=n[E]?n[E].concat(g[0]):[g[0]])}}),s).catch(_=>c));return{then:l.then.bind(l),download:c}}getPCM(e,t){var k,ae,w;if(typeof WritableStream=="undefined"){this.log.warn("getPCM failed: browser not support WritableStream");return}let{enable:r,sampleRate:s=48e3,channelCount:n=1,port:a}=(t===""?this.audioFrameEventConfigMap.get(""):this.audioFrameEventConfigMap.get(t)||this.audioFrameEventConfigMap.get("*"))||{};if(!r)return;this.log.info(`getPCM ${t||"local"}`);let c=Math.floor(s*.04),l=new Float32Array(c),u=new Float32Array(c),h,m,_=0,g=new AbortController,E=t===""?(k=this._localAudioTrack)==null?void 0:k.mediaTrack:(w=(ae=this.room)==null?void 0:ae.remotePublishedUserMap.get(t))==null?void 0:w.remoteAudioTrack.mediaTrack;if(!E){this.log.info(`getPCM failed: ${t||"local"} has no audio track`);return}let C=Se().createMediaStreamSource(new MediaStream([E]));return Gn([C],s,n,a).then(Ye=>Ye.pipeTo(new WritableStream({write(N){N[0][0]&&(_+N[0][0].length>c?(l.set(N[0][0].subarray(0,c-_),_),h=N[0][0].subarray(c-_),N[0][1]&&(u.set(N[0][1].subarray(0,c-_),_),m=N[0][1].subarray(c-_)),_+=c-_):(h&&(l.set(h,_),_+=h.length,h=void 0),m&&(u.set(m,_),m=void 0),l.set(N[0][0],_),N[0][1]&&u.set(N[0][1],_),_+=N[0][0].length),_>=c&&(_=0,e({userId:t,sampleRate:s,channelCount:n,data:n===1?l:[l,u]}),l=new Float32Array(c),u=new Float32Array(c)))}}),g).catch(N=>this.log.warn(`stop getPCM reason:${N}`))),g}get hasScreenAudioTrack(){return!T(this._localScreenAudioTrack)}get hasAudioTrack(){return!T(this._localAudioTrack)}changeInput(e){var t,r;if(e instanceof To)return this._localScreenAudioTrack=e,this.isScreenAudioNeedAudioProcess&&((t=this.audioProcessor)!=null&&t.screenAudioWorkletNode)&&(e.addAudioProcessor(this.audioProcessor.screenAudioWorkletNode,this.audioProcessor.mixNode,this.audioProcessor.silentNode),this.audioReferenceMap.forEach((s,n)=>{e.mixAudioReference(s,n)})),e.pipeline.connect(),this.mixOnChange();if(e instanceof kt)return this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),this.isLocalAudioNeedAudioProcess&&((r=this.audioProcessor)!=null&&r.localAudioWorkletNode)&&(e.addAudioProcessor(this.audioProcessor.localAudioWorkletNode,this.audioProcessor.mixNode,this.audioProcessor.silentNode),this.audioReferenceMap.forEach((s,n)=>{e.mixAudioReference(s,n)})),e.pipeline.connect(),this.mixOnChange();if(e instanceof Ti)return e.setOutputMediaStreamTrack(e.mediaTrack)}mixAudioReference(e,t){var r;(r=this._localAudioTrack)==null||r.mixAudioReference(e,t)}unMixAudioReference(e){var t;(t=this._localAudioTrack)==null||t.unMixAudioReference(e)}setAudioReferenceVolume(e,t){var r;(r=this._localAudioTrack)==null||r.setAudioReferenceVolume(e,t)}mixOnChange(){return this.mixChangedDebounce||(this.mixChangedDebounce=Promise.resolve().then(()=>{var e,t;return delete this.mixChangedDebounce,Promise.all([(e=this._localAudioTrack)==null?void 0:e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),(t=this._localScreenAudioTrack)==null?void 0:t.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)])})),this.mixChangedDebounce}removeInput(e){e instanceof To?delete this._localScreenAudioTrack:e instanceof kt?delete this._localAudioTrack:e instanceof Ti}addDenoiser(e){var t;this.denoiser=e,(t=this._localAudioTrack)==null||t.addDenoiser(e)}addAudioProcessor(e,t,r,s){var n;this.audioProcessor={localAudioWorkletNode:r,mixNode:e,silentNode:t,screenAudioWorkletNode:s},this.isLocalAudioNeedAudioProcess&&this._localAudioTrack&&r&&(this._localAudioTrack.addAudioProcessor(r,e,t),this.audioReferenceMap.forEach((a,c)=>{var l;(l=this._localAudioTrack)==null||l.mixAudioReference(a,c)})),this.isScreenAudioNeedAudioProcess&&this._localScreenAudioTrack&&s&&((n=this._localScreenAudioTrack)==null||n.addAudioProcessor(s,e,t),this.audioReferenceMap.forEach((a,c)=>{var l;(l=this._localScreenAudioTrack)==null||l.mixAudioReference(a,c)}))}removeDenoiser(e){var t;return delete this.denoiser,(t=this._localAudioTrack)==null?void 0:t.removeDenoiser(e)}addVoiceChanger(e,t){var r;this.voiceChanger=[e,t],(r=this._localAudioTrack)==null||r.pipeline.voiceChanger.setNode(e,t)}removeVoiceChanger(){var e;delete this.voiceChanger,(e=this._localAudioTrack)==null||e.pipeline.voiceChanger.deleteNode()}removeAudioProcessor(e,t){var r,s;delete this.audioProcessor,(r=this._localAudioTrack)==null||r.removeAudioProcessor(e),(s=this._localScreenAudioTrack)==null||s.removeAudioProcessor(t)}destroy(){this.close(),this.audioReferenceMap.clear(),this.getPCMAbortCtrlMap.forEach(e=>e==null?void 0:e.abort("destroy")),this.getPCMAbortCtrlMap.clear(),this.audioFrameEventConfigMap.clear(),this.uninstallEvent()}addEncodeProcessor({processor:e,type:t}){var r;this.encodePipeline.includes(e)||(this.encodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}addDecodeProcessor({processor:e,type:t}){var r;this.decodePipeline.includes(e)||(this.decodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}handleLocalTrackStarted({room:e,userId:t}){var s;if(e!==this.room||this.getPCMAbortCtrlMap.get(t))return;let r=this.getPCM(n=>{var a;(a=this.room)==null||a.emit("audio-frame",n)},"");this.getPCMAbortCtrlMap.set(t,r),this.getPCMAbortCtrlMap.get(t)&&((s=this._localAudioTrack)==null||s.on("input-media-track-changed",()=>{let n=this.getPCMAbortCtrlMap.get(t);n&&(n.abort("inputMediaTrackChanged"),n=this.getPCM(a=>{var c;(c=this.room)==null||c.emit("audio-frame",a)},""),this.getPCMAbortCtrlMap.set(t,n))}))}handleLocalTrackStopped({room:e,userId:t}){if(e!==this.room)return;let r=this.getPCMAbortCtrlMap.get(t);r&&(r.abort("stopLocalAudio"),this.getPCMAbortCtrlMap.delete(t))}handleRemoteTrackStarted({room:e,userId:t}){if(e===this.room&&!this.getPCMAbortCtrlMap.get(t)){let r=this.room.audioManager.getPCM(s=>{var n;(n=this.room)==null||n.emit("audio-frame",s)},t);this.getPCMAbortCtrlMap.set(t,r)}}handleRemoteTrackStopped({room:e,userId:t}){if(e!==this.room)return;let r=this.getPCMAbortCtrlMap.get(t);r&&(r.abort("stopRemoteAudio"),this.getPCMAbortCtrlMap.delete(t))}installEvent(){S.on("113",this.handleLocalTrackStarted,this),S.on("114",this.handleLocalTrackStopped,this),S.on("115",this.handleRemoteTrackStarted,this),S.on("116",this.handleRemoteTrackStopped,this)}uninstallEvent(){S.off("113",this.handleLocalTrackStarted),S.off("114",this.handleLocalTrackStopped),S.off("115",this.handleRemoteTrackStarted),S.off("116",this.handleRemoteTrackStopped)}updateAudioReference({type:e,audioReference:t,refId:r,volume:s}){if(e==="add"){if(this.audioReferenceMap.get(r)||!t||(this.audioReferenceMap.set(r,t),!this.audioProcessor))return;this.mixAudioReference(t,r)}else if(e==="remove")this.audioReferenceMap.get(r)&&(this.audioReferenceMap.delete(r),this.unMixAudioReference(r));else if(e==="updateVolume"){if(!this.audioProcessor||T(s))return;this.setAudioReferenceVolume(r,s)}}};function Eo(o=30,i=2){return Y((e,t)=>function(...r){return new Promise((s,n)=>{let a=setTimeout(()=>{let c=new D({code:I.API_CALL_TIMEOUT,message:`checkPendingPromise ${t}() timeout ${o}s`});(this.log||this._log||R).warn(c),i===2?n(c):i===1&&s()},o*1e3);this._checkPendingPromiseSet||(this._checkPendingPromiseSet=new Set),this._checkPendingPromiseSet.add(a),e.apply(this,r).then(s,n).finally(()=>{clearTimeout(a),this._checkPendingPromiseSet&&a&&this._checkPendingPromiseSet.delete(a)})})})}function Tf(){return Y((o,i)=>function(...e){return this._checkPendingPromiseSet&&(this._checkPendingPromiseSet.forEach(t=>clearTimeout(t)),this._checkPendingPromiseSet.clear()),o.apply(this,e)})}var Mi=class Mi extends no{constructor(e,t,r){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:r,room:e});this.room=e;this.user=t;d(this,"tinyId");d(this,"isRemote",!0);d(this,"jitterBufferDelay",0);d(this,"availableState");d(this,"remotePublishState");d(this,"_triggerCheckDecodeSubject",ot(de(this,Mi.STATE_SUBSCRIBE)));this.tinyId=t.tinyId,this.availableState=new q(`${t.userId}-${this.mediaType}-available`,"remote-track-available"),this.remotePublishState=new q(`${t.userId}-${this.mediaType}-remote-publish`,"remote-track-publish"),le(Ln(de(this,q.STATECHANGED),de(this.remotePublishState,q.STATECHANGED)),Bn(()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing)),Ee(c=>{this.availableState.state!==(c?q.ON:q.OFF)&&(this.availableState.state=c?q.ON:q.OFF),this.updatePlayingState(c)}));let s=le(de(this.player,he.ERROR),Wt(c=>c.code===MediaError.MEDIA_ERR_DECODE)),n=le(Un(5e3),Wt(()=>this.ignoreDecodeError||!this.isSubscribed||!this.isPlayCalled||!this.stat.bytesReceived?!1:this.player.isPlaying||(this.kind===p.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)?(this.reportDecodeResult(!0),!1):!0)),a=le(xu(s,n),ke(de(this,q.INIT)));le(this._triggerCheckDecodeSubject,Wt(()=>!this.ignoreDecodeError),mo(a),Ee(c=>{this.reportDecodeResult(!1,c)}))}setMute(e){this.isRemotePublished&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.isRemotePublished&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}checkDecodeResult(){this._triggerCheckDecodeSubject.next(!0)}waitHasMediaTrack(){return new Promise(e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)})}get ignoreDecodeError(){var t,r;return(((r=(t=this.room)==null?void 0:t.networkQuality)==null?void 0:r.downlinkNetworkQuality)||0)>3||this.player.isInAutoPlayFailedState}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===Mi.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===q.ON}get isNeedPlay(){return this.isAvailable&&this.isPlayCalled}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}reportDecodeResult(e,t){var s,n;let r=this.kind===p.AUDIO;if(v[e?"addSuccessEvent":"addFailedEvent"]({key:r?504700:514702}),!r){let a=((s=this.room)==null?void 0:s.downlinkVideoCodec.toUpperCase())||"H264";v[e?"addSuccessEvent":"addFailedEvent"]({key:os[`DECODE_${a}_RESULT`]}),e||this.log.warn(`${(n=this.room)==null?void 0:n.downlinkVideoCodec} decode failed`)}e||(v.addEnum({key:r?504701:514703,value:Zr()}),oe.uploadEvent({log:`stat-decode-failed-${this.kind}-${ni()||ai()}`,userId:this.room.userId}),this._log.warn(`decode failed: isPlaying: ${this.player.isPlaying} ${this.kind===p.AUDIO?`audioLevel: ${this.getAudioLevel()}`:`framesDecoded: ${this.stat.framesDecoded>0}`}`),this.emit("decode-failed",{error:t}))}updatePlayingState(e){if(this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.isRemotePublished||!this.outMediaTrack)){this.log.info(`abort play, isSubscribed: ${this.isSubscribed} isAvailable: ${this.isRemotePublished} hasTrack: ${!!this.outMediaTrack} `);return}super.updatePlayingState(e)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.remotePublishState.state=this.isRemotePublished?q.ON:q.OFF,this.emit("remote-publish-changed",this.isRemotePublished)}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};d(Mi,"STATE_SUBSCRIBE","subscribe"),O([Eo(5,1)],Mi.prototype,"waitHasMediaTrack",1),O([ye(q.INIT,Mi.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),S.emit(A.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),Rt(521716,!1)],Mi.prototype,"subscribe",1),O([ye(Mi.STATE_SUBSCRIBE,q.INIT,{sync:!0,success(){this.log.info("unsubscribed"),S.emit(A.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],Mi.prototype,"unsubscribe",1);var Ts=Mi;var Ti=class extends Ts{constructor(e,t){super(e,t,1);d(this,"volume",0);d(this,"mediaType",1);d(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.audioManager}get dbVolume(){return so.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}onPlayerError(e){this.enableDecodeFrame&&(this._log.warn("use audio decoder"),this.room.enableInsertableStreams())}get enableDecodeFrame(){var e,t;return this.manager?this.manager.decodePipeline.some(r=>r)||((t=(e=this.player.element)==null?void 0:e.error)==null?void 0:t.code)===MediaError.MEDIA_ERR_DECODE&&Ec().AudioDecoder&&mi:!1}get enableDecryptFrame(){return this.manager&&!!this.manager.decodePipeline[0]}decodeFrame(e){if(!this.manager)return e;let t=e;for(let[r,s]of this.manager.decodePipeline.entries()){if(!s)continue;let n={frame:e,track:this};if(r===1&&this.isAvailable&&this.room.role==="audience"&&(n.onAudioFrameNTPTime=({ntp:a,frame:c,hasLeavingTag:l})=>{this.emit("audio-frame-with-ntp",{ntp:a,frame:c,hasLeavingTag:l})}),t=s(n),!t)return}return t}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get isRemotePublished(){return this.user.muteState.audioAvailable}};var id=class extends Ue{constructor(e,t,r,s,n){super(e,{useDefaultProgram:!0,useFbo:!0,name:"alpha",create2d:!0,logger:t});this.setContainer=s;d(this,"initStat",{alphaStitchingType:1});d(this,"end",ot());d(this,"minSize",320);d(this,"maxSize",1280);d(this,"draggable",!1);d(this,"startDragX",0);d(this,"startDragY",0);d(this,"left",0);d(this,"top",0);d(this,"baseWidth",320);d(this,"baseRatio");d(this,"container");this.initStat=n,this.draggable=r,this.bindDragEvents()}bindDragEvents(){let e=this.context._canvas;if(e)if(this.draggable){let t=ke(this.end);le(de(e,"mousedown"),Fn(this.startDrag.bind(this)),Or(()=>le(de(window,"mousemove"),ke(de(window,"mouseup")))),t,Ee(this.doDrag.bind(this))),le(de(e,"dblclick"),t,Ee(this.resetPosition.bind(this))),le(de(e,"wheel"),t,Ee(this.handleZoom.bind(this))),this.renderCanvas()}else{if(!this.container)return;this.container.style.removeProperty("left"),this.container.style.removeProperty("top"),this.end.next()}}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}startDrag(e){e.preventDefault(),e.button===0&&(this.startDragX=e.clientX-this.left,this.startDragY=e.clientY-this.top)}renderCanvas(){let{container:e}=this;e||this.setContainer(),!(!e||!this.baseRatio||!this.draggable)&&(e.style.setProperty("width",`${this.baseWidth}px`),e.style.setProperty("height",`${this.baseWidth/this.baseRatio}px`),e.style.setProperty("position","fixed"),e.style.setProperty("left",`${this.left}px`),e.style.setProperty("top",`${this.top}px`))}doDrag(e){e.preventDefault(),this.left=e.clientX-this.startDragX,this.top=e.clientY-this.startDragY,this.renderCanvas()}handleZoom(e){e.preventDefault();let t=.1,r=e.deltaY,s=this.context._canvas;s&&(this.baseWidth||(this.baseWidth=s.offsetWidth),r<0?this.baseWidth=Math.min(this.baseWidth*(1+t),this.maxSize):this.baseWidth=Math.max(this.baseWidth*(1-t),this.minSize),this.renderCanvas())}resetPosition(){this.left=0,this.top=0,this.renderCanvas()}onRatioReset(){this.renderCanvas()}draw2d(e,t,r,s,n){var _;let{ctx2d:a}=this,c=this.context._canvas;if(!a||!c)return!1;let l=super.draw2d(e,t,r,s,n),u=a.getImageData(0,0,s,n),{data:h}=u,m=!1;if(this.initStat.alphaStitchingType===1){let g=Math.floor(s/2);for(let E=0;E<n;E++)for(let C=0;C<g;C++){let k=(E*s+C)*4,ae=C+g,w=(E*s+ae)*4,Ye=h[w];h[w+3]=0;let N=Ye>=100;h[k+3]=N?255:0}m=super.draw2d(u,0,0,0,0,g,n),c.width=g}else if(this.initStat.alphaStitchingType===2){let g=Math.floor(n/2);for(let E=0;E<g;E++)for(let C=0;C<s;C++){let k=(E*s+C)*4,w=((E+g)*s+C)*4,Ye=h[w];h[w+3]=0;let N=Ye>=100;h[k+3]=N?255:0}m=super.draw2d(u,0,0,0,0,s,g),c.height=g}return(_=this.context.ctx)==null||_.clearRect(0,0,s,n),l&&m}close(){this.baseRatio=void 0,this.end.next(),this.end.complete()}};function DS(o){return[15,30,45,60].reduce((e,t)=>Math.abs(t-o)<Math.abs(e-o)?t:e)}var ki=class extends Ts{constructor(e,t,r=4){super(e,t,r);d(this,"mediaType",4);d(this,"source");d(this,"shouldRenderAlpha",!1);d(this,"alphaNode");d(this,"shouldBeDraggable",!0);d(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.videoManager,this.on("first-video-frame",s=>{this.room.emit("first-video-frame",s)})}isAlphaSei(e){if(this.userId!==e.userId||e.seiPayloadType!==50)return!1;let t=new Uint8Array(e.data);return t.length%3!==0||t[0]!==0||t[1]!==1?!1:t}play(e,t){return(me(t==null?void 0:t.canvasRender)?t.canvasRender:et===17)&&!this.source&&this.useCanvasPlayer(),super.play(e,t).then(()=>{this.player.calculateStat(),S.emit("156",{track:this,player:this.player})})}updateAlphaRenderInfo(e){let t=this.isAlphaSei(e);if(t)if(!this.alphaNode)this.shouldRenderAlpha=!0,this.player.shouldRenderAlpha=!0,this.useCanvasPlayer(t[2]);else{let r=t[2];if(this.alphaNode.baseRatio&&this.alphaNode.initStat.alphaStitchingType===r)return;this.alphaNode.initStat={alphaStitchingType:r};let s=this.player.getElement();if(s){let n=s.videoWidth/s.videoHeight;n&&(this.alphaNode.baseRatio=n*(r===1?.5:2),this.alphaNode.onRatioReset())}this.player.canvas&&(this.player.canvas.id=this.generateAlphaCanvasName(r))}}generateAlphaCanvasName(e){let t="alpha",r=hn[e];return`${t}_${r}_${this.userId}`}useCanvasPlayer(e){if(this.log.info(`useCanvasPlayer(), has element:${!!this.player.element}`),!this.player.element)return;let t=new ze({frameRate:15,logger:this.log,name:this.shouldRenderAlpha&&e?this.generateAlphaCanvasName(e):this.userId});t.create({alpha:this.shouldRenderAlpha,willReadFrequently:this.shouldRenderAlpha});let r=new fo(t,{name:"remotePlayer",logger:this.log});if(this.source=t.createVideoPlayerSource(this.player),this.player.setCanvas(t._canvas),this.shouldRenderAlpha&&e){let s=()=>{!this.player.container||!this.alphaNode||(this.alphaNode.container=this.player.container,this.alphaNode.renderCanvas())},n=new id(t,this.log,this.shouldBeDraggable,s,{alphaStitchingType:e});this.source.connect(n),n.connect(r),this.alphaNode=n}else this.source.connect(r);Ki()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,t),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let t=this.decodeFPS,r=DS(t);if(!Q(t)||t<=0){this.log.debug(`updateCanvasPlayerFPS() ignore decoder: ${t} `);return}if(r===e.frameRate){this.log.debug(`updateCanvasPlayerFPS() ignore ClosestFPS ${r} == ${e.frameRate}`);return}this.log.info(`updateCanvasPlayerFPS() decoder: ${t}, closest: ${r}, current: ${e.frameRate}`),e.frameRate=r}get decodeFPS(){var n;let{msg_video_status:e}=((n=this.room.heartbeatReport)==null?void 0:n.msg_down_stream_info.find(a=>a.msg_user_info.str_identifier===this.userId))||{},t=this.mediaType===2?7:this.isSmall?3:2;if(!e||e.length===0)return 0;let r=e.find(a=>a.uint32_video_stream_type===t);return(r==null?void 0:r.uint32_video_dec_fps)||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),S.emit("157",{track:this,player:this.player}),this.alphaNode&&this.alphaNode.close(),super.stop()}decodeFrame(e){if(!this.manager)return e;for(let t of this.manager.decodePipeline)if(t&&(e=t({frame:e,track:this}),!e))return;return e}get isBig(){return this.mediaType===4}get isSmall(){return this.mediaType===8}changeType(e){this.room.changeType(e,this.user)}get isRemotePublished(){return this.user.muteState.videoAvailable}setMirror(e){e==="publish"||e==="both"||super.setMirror(e)}setDraggable(e){this.shouldBeDraggable=e,this.alphaNode&&(this.alphaNode.draggable=e,this.alphaNode.bindDragEvents())}onDecodeDowngradeStateChanged(e){this.emit("decode-downgrade-state-changed",e)}},Es=class extends ki{constructor(e,t){super(e,t,2);d(this,"mediaType",2);d(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}};var Ss=new Map;S.on(A.JOIN_SUCCESS,({room:o})=>{ve(o.userId,{eventId:32788})});S.on(A.LEAVE_START,({room:o})=>{ve(o.userId,{eventId:32789})});S.on(A.LOCAL_TRACK_PUBLISHED,({track:o})=>{if(o.room){let i=32769;o.mediaType===4?i=32768:o.mediaType===2&&(i=32805),ve(o.room.userId,{eventId:i})}});S.on(A.LOCAL_TRACK_UNPUBLISHED,({track:o})=>{if(o.room){let i=32771;o.mediaType===4?i=32770:o.mediaType===2&&(i=32806),ve(o.room.userId,{eventId:i})}});S.on(A.TRACK_MUTED,({track:o})=>{o.room&&(o.kind===p.AUDIO?ve(o.room.userId,{eventId:o.isRemote?32785:32772,remoteUserId:o.isRemote?o.userId:void 0}):ve(o.room.userId,{eventId:o.isRemote?32784:32773,remoteUserId:o.isRemote?o.userId:void 0}))});S.on(A.TRACK_UNMUTED,({track:o})=>{o.room&&(o.kind===p.AUDIO?ve(o.room.userId,{eventId:o.isRemote?32787:32774,remoteUserId:o.isRemote?o.userId:void 0}):ve(o.room.userId,{eventId:o.isRemote?32786:32775,remoteUserId:o.isRemote?o.userId:void 0}))});S.on(A.REMOTE_TRACK_SUBSCRIBED,({track:o})=>{o.room&&(o.mediaType===1&&ve(o.room.userId,{eventId:32777,remoteUserId:o.userId}),o.mediaType===4&&ve(o.room.userId,{eventId:32776,remoteUserId:o.userId}),o.mediaType===8&&ve(o.room.userId,{eventId:32803,remoteUserId:o.userId}))});S.on(A.REMOTE_TRACK_UNSUBSCRIBED,({track:o})=>{o.room&&(o.mediaType===1&&ve(o.room.userId,{eventId:32779,remoteUserId:o.userId}),o.mediaType===4&&ve(o.room.userId,{eventId:32778,remoteUserId:o.userId}),o.mediaType===8&&ve(o.room.userId,{eventId:32804,remoteUserId:o.userId}))});S.on(A.SWITCH_DEVICE_SUCCESS,({track:o})=>{o.room&&ve(o.room.userId,{eventId:o.kind===p.VIDEO?32780:32781})});S.on(A.LOCAL_TRACK_REPLACED,({track:o})=>{o.room&&ve(o.room.userId,{eventId:o.kind===p.VIDEO?32782:32783})});S.on(A.SIGNAL_CONNECTION_STATE_CHANGED,({room:o,prevState:i,state:e})=>{let t;switch(e){case"CONNECTED":i==="RECONNECTING"?t=32795:t=32791;break;case"DISCONNECTED":i==="RECONNECTING"?t=32796:t=32790;break;case"RECONNECTING":t=32794;break}t&&ve(o.userId,{eventId:t})});S.on(A.PEER_CONNECTION_STATE_CHANGED,({room:o,prevState:i,state:e,remoteUserId:t})=>{let r=!!t,s;switch(e){case"CONNECTED":i==="RECONNECTING"?s=r?32801:32798:s=r?32793:32792;break;case"DISCONNECTED":i==="RECONNECTING"&&(s=r?32802:32799);break;case"RECONNECTING":s=r?32800:32797;break}s&&ve(o.userId,{eventId:s,remoteUserId:t})});S.on(A.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({implementation:o,userId:i,remoteUserId:e,codec:t,isHWCodec:r,prevImplementation:s,streamType:n})=>{let a=r?1:0;s||(a=r?3:2);let c={H264:0,H265:1,VP8:2}[t.toUpperCase()],l={eventId:4004,param1:a,param2:c,streamType:n||2};e&&(l.remoteUserId=e,l.eventId=4005),ve(i,l),v.addEnum({key:e?514701:513701,value:a}),v.addEnum({key:e?514700:513700,value:c})});S.on(A.LOCAL_TRACK_RECAPTURE,({track:o,error:i})=>{if(o.userId){let e={eventId:2003,param1:0};o.kind===p.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType=o.streamType==="auxiliary"?7:2,i&&(e.param1=8)),ve(o.userId,e)}});function ve(o,i){let e=L(M({},i),{timestamp:Bi()});Ss.has(o)?Ss.get(o).push(e):Ss.set(o,[e])}function Ef(o){if(Ss.has(o)){let i=Ss.get(o).map(e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,uint32_param1:e.param1,uint32_param2:e.param2,uint32_video_stream_type:e.streamType}));return Ss.delete(o),i}return[]}function Sf(...o){return Y((i,e)=>function(...t){return OS.call(this,o,t,e,this._name),i.apply(this,t)})}function OS(o,i,e,t){try{if(Ae(o))for(let r=0;r<o.length;r++)rd.call(this,{rule:o[r],value:i[r],key:o[r].name,fnName:e,className:t});else rd.call(this,{rule:o,value:i[0],key:o.name,fnName:e,className:t})}catch(r){throw R.error(r),r}}function rd({rule:o,value:i,key:e,fnName:t,className:r}){if(T(i)){if(o.required)throw new D({code:I.INVALID_PARAMETER,message:H({key:B.INVALID_PARAMETER_REQUIRED,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(T(o.defaultValue))return;i=o.defaultValue}if(Array.isArray(o.type)){let a=!1;for(let c=0;c<o.type.length;c++)o.type[c]===null&&i===null&&(a=!0),ue(o.type[c])&&i instanceof o.type[c]&&(a=!0),ie(o.type[c])&&Oe(i)===o.type[c].toLowerCase()&&(a=!0);if(!a)throw new D({code:I.INVALID_PARAMETER,message:H({key:B.INVALID_PARAMETER_TYPE,data:{key:e,rule:{type:o.type.map(c=>jr(c)?Uo(c):ie(c)?c:Oe(c))},fnName:t,value:i},link:{className:r,fnName:t}})})}else if(!T(o.type)&&Oe(i)!==o.type)throw new D({code:I.INVALID_PARAMETER,message:H({key:B.INVALID_PARAMETER_TYPE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(o.allowEmpty===!1){let a=Q(i)&&(i===0||Number.isNaN(i)),c=ie(i)&&i.trim()==="";if(a||c)throw new D({code:I.INVALID_PARAMETER,message:H({key:B.INVALID_PARAMETER_EMPTY,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})})}if(o.notLessThanZero&&Q(i)&&i<0)throw new D({code:I.INVALID_PARAMETER,message:H({key:B.CANNOT_LESS_THAN_ZERO,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(!T(o.min)&&Q(i)&&i<o.min)throw new D({code:I.INVALID_PARAMETER,message:H({key:B.INVALID_PARAMETER_MIN,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(!T(o.max)&&Q(i)&&i>o.max)throw new D({code:I.INVALID_PARAMETER,message:H({key:B.INVALID_PARAMETER_MAX,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(ie(o.instanceOf)){if(!i||i._name!==o.instanceOf)throw new D({code:I.INVALID_PARAMETER,message:H({key:B.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})})}else if(ue(o.instanceOf)&&!(i instanceof o.instanceOf))throw new D({code:I.INVALID_PARAMETER,message:H({key:B.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(o.values&&!o.values.includes(i))throw new D({code:I.INVALID_PARAMETER,message:H({key:B.INVALID_PARAMETER_RANGE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});let{properties:s}=o;dt(s)&&yt(i)&&Object.keys(s).forEach(a=>{rd.call(this,{rule:s[a],value:i&&i[a],key:`${e}.${a}`,fnName:t,className:r})});let{arrayItem:n}=o;dt(n)&&Ae(i)&&i.forEach((a,c)=>{rd.call(this,{rule:n,value:a,key:`${e}[${c}]`,fnName:t,className:r})}),ue(o.validate)&&o.validate.call(this,i,e,t,r,this)}var If=Je(at(),1);var od=class extends If.EventEmitter{constructor(e,t,r="userId"){super();this.mySelfId=e;this._log=t;this.key=r;d(this,"userMap",new Map);d(this,"remotePublishedUserMap",new Map)}get hasRobotUser(){return!![...this.remotePublishedUserMap.values()].find(e=>e.isRobot)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:r,tinyId:s,role:n}=e;if(this.userMap.has(t))return;let a={userId:r,tinyId:s,role:n===20?"anchor":"audience"};this.userMap.set(t,a),this.emit("1",a)}deleteUser(e,t){let r=this.userMap.get(e);if(!r)return;let s=`peer leave [${e}]`;T(t)||(s+=`:${rl[t]}`),this._log.info(s);let n=this.remotePublishedUserMap.get(e);if(n){let a=n.muteState;n.flag=0,this.emit("5",n.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:a,muteState:n.muteState,flag:0})}this.userMap.delete(e),this.emit("2",r.userId)}setUserList(e){this.userMap.forEach(t=>{e.findIndex(r=>r[this.key]===t[this.key])<0&&this.deleteUser(t[this.key],0)}),e.forEach(t=>{!this.userMap.has(t[this.key])&&t[this.key]!==this.mySelfId&&this.addUser(t)})}addRemotePublishedUser(e){this.remotePublishedUserMap.has(e[this.key])||this.remotePublishedUserMap.set(e[this.key],e)}deleteRemotePublishedUser(e){this.remotePublishedUserMap.has(e)&&this.remotePublishedUserMap.delete(e)}setRemotePublishedUserList(e){this.remotePublishedUserMap.forEach(t=>{let r=t[this.key];if(e.findIndex(s=>s[this.key]===t[this.key])<0){this._log.info(`remote [${r}] unpublish`);let s=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(r),this.emit("6",{prevMuteState:s,muteState:t.muteState,flag:0})}}),e.forEach(t=>{var u;let r=t[this.key];if(r===this.mySelfId){this.emit("7",t);return}let{flag:s,userId:n,tinyId:a}=t,c=ei(s,n),l=(u=this.remotePublishedUserMap.get(r))==null?void 0:u.muteState;if(l){let h=this.remotePublishedUserMap.get(r);h&&h.flag!==s&&(h.flag=s,this._log.info(`remote publish updated: ${JSON.stringify(h.muteState)}`),this.emit("6",{prevMuteState:l,muteState:c,flag:s}))}else this._log.info(`remote publish. state: ${JSON.stringify(c)}`),this.addUser({userId:n,tinyId:a,role:20}),this.emit("3",t),this.emit("6",{prevMuteState:ei(0,n),muteState:c,flag:s})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function Ch({timesInSecond:o,maxSizeInSecond:i,getSize:e}){return Y((t,r)=>{let s=new WeakMap;return S.on(A.ROOM_DESTROY,({room:n})=>s.delete(n)),function(...n){let a=s.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},s.set(this,a)),a.timestamp===0?a.timestamp=Date.now():Date.now()-a.timestamp>1e3&&(a.timestamp=Date.now(),a.callCountInSecond=0,a.totalSizeInSecond=0),e&&(a.totalSizeInSecond+=e(...n)),a.timestamp!==0&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=o||a.totalSizeInSecond>i))throw new D({code:I.INVALID_OPERATION,message:H({key:B.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=o,isSize:a.totalSizeInSecond>i,name:r,timesInSecond:o,maxSizeInSecond:i}})});a.callCountInSecond++,t.call(this,...n)}})}var MS="2025-12-06 23:07:01",Af=!0,Cf=function(){var o;if(Af){Af=!1,R.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${ft}/en/index.html`),console.info(`* Changelog: ${ft}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),R.info("TRTC Web SDK Version:",$e),si||R.debug("Build Time:",MS);let i=`UA: ${navigator.userAgent}
|
|
53
|
+
CPU core: ${navigator.hardwareConcurrency}, GPU: ${Pl()}`,e=navigator.deviceMemory;e&&(i+=`, minRAM: ${e}GB`),R.info(i),R.info(`URL: ${location.href}${((o=self.frameElement)==null?void 0:o.tagName)==="IFRAME"?" in iframe":""}`),Yr().then(t=>{t&&R.info(ii)})}};var So={SCENE_LIVE:"live",SCENE_RTC:"rtc",ROLE_ANCHOR:"anchor",ROLE_AUDIENCE:"audience",STREAM_TYPE_MAIN:"main",STREAM_TYPE_SUB:"sub",AUDIO_PROFILE_STANDARD:"standard",AUDIO_PROFILE_STANDARD_STEREO:"standard-stereo",AUDIO_PROFILE_HIGH:"high",AUDIO_PROFILE_HIGH_STEREO:"high-stereo",QOS_PREFERENCE_SMOOTH:"smooth",QOS_PREFERENCE_CLEAR:"clear",SPEAKER:"Speakerphone",HEADSET:"Headset earpiece"};var $={INVALID_PARAMETER:5e3,INVALID_OPERATION:5100,ENV_NOT_SUPPORTED:5200,DEVICE_ERROR:5300,SERVER_ERROR:5400,OPERATION_FAILED:5500,OPERATION_ABORT:5998,UNKNOWN_ERROR:5999},wt=(b=>(b[b.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",b[b.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",b[b.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",b[b.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",b[b.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",b[b.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",b[b.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",b[b.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",b[b.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",b[b.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",b[b.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",b[b.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",b[b.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",b[b.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",b[b.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",b[b.INVALID_ROOM_ID_REQUIRED=5015]="INVALID_ROOM_ID_REQUIRED",b[b.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",b[b.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",b[b.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",b[b.INVALID_ROOM_ID_TYPE_MISMATCH=5019]="INVALID_ROOM_ID_TYPE_MISMATCH",b[b.INVALID_ROOM_ID_DUPLICATE=5020]="INVALID_ROOM_ID_DUPLICATE",b[b.INVALID_OPERATION=5100]="INVALID_OPERATION",b[b.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",b[b.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",b[b.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",b[b.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",b[b.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",b[b.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",b[b.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",b[b.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",b[b.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",b[b.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",b[b.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",b[b.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",b[b.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",b[b.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",b[b.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",b[b.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",b[b.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",b[b.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",b[b.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",b[b.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",b[b.DEVICE_ERROR=5300]="DEVICE_ERROR",b[b.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",b[b.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",b[b.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",b[b.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",b[b.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",b[b.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",b[b.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",b[b.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",b[b.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",b[b.NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX=5310]="NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX",b[b.SERVER_ERROR=5400]="SERVER_ERROR",b[b.NEED_TO_BUY=5401]="NEED_TO_BUY",b[b.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",b[b.OPERATION_FAILED=5500]="OPERATION_FAILED",b[b.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",b[b.REJOIN_FAILED=5502]="REJOIN_FAILED",b[b.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",b[b.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",b[b.VIDEO_ENCODE_FAILED=5505]="VIDEO_ENCODE_FAILED",b[b.AUDIO_ENCODE_FAILED=5506]="AUDIO_ENCODE_FAILED",b[b.VIDEO_DECODE_FAILED=5507]="VIDEO_DECODE_FAILED",b[b.AUDIO_DECODE_FAILED=5508]="AUDIO_DECODE_FAILED",b[b.OPERATION_ABORT=5998]="OPERATION_ABORT",b[b.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",b))(wt||{});function yf({code:o,params:i,enableDocLink:e=!1}){let t="",r,s=wt[o];try{r=Rf[s]}catch(n){r=Rf.UNKNOWN_ERROR}return ue(r)?t=r(i):ie(r)&&(t=r),i.fnName&&!t.includes(i.fnName)&&(t[t.length-1]!=="."&&(t+="."),t+=` thrown from ${i.fnName}()`),e&&(t+=" doc:"),t}var Rf=L(M({},je),{INVALID_PARAMETER({fnName:o}){return`the parameters of the '${o}' you called does not meet the requirements, please check the API documentation.`},INVALID_PARAMETER_REQUIRED({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' is a required param when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_TYPE({key:o,rule:i,fnName:e,value:t}){let r=`${o||i.name}`,s="";return Array.isArray(i.type)?s=i.type.join("|"):s=i.type,`'${r}' must be type of ${s} when calling ${e}(), received type: ${Oe(t)}.`},INVALID_PARAMETER_EMPTY({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' cannot be '${t}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:o,rule:i,fnName:e,value:t}){let r=`${o||i.name}`,s=`${i.instanceOf.name||i.instanceOf}`;return`'${r}' must be instanceof ${s} when calling ${e}(), received type: ${Oe(t)}.`},INVALID_PARAMETER_RANGE({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' must be one of ${i.values.join("|")} when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_LESS_THAN_ZERO({key:o,rule:i,fnName:e}){return`'${o||i.name}' cannot be less than 0 when calling ${e}().`},INVALID_PARAMETER_MIN({key:o,rule:i,value:e}){return`the min value of ${o||i.name} is ${i.min}, received: ${e}.`},INVALID_PARAMETER_MAX({key:o,rule:i,value:e}){return`the max value of ${o||i.name} is ${i.max}, received: ${e}.`},INVALID_ELEMENT_ID({key:o,fnName:i}){return`'${o}' is not found in the document object when calling ${i}().`},INVALID_ELEMENT_ID_TYPE({key:o,fnName:i,type:e}){return`the element corresponding to '${o}' must be instanceof HTMLElement when calling ${i}(), received: ${e}.`},INVALID_STREAM_ID({key:o}){return`'${o}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},INVALID_ROOM_ID_STRING({key:o}){return`'${o}' must be a valid string.`},INVALID_ROOM_ID_INTEGER({key:o}){return`'${o}' must be an integer between [1, 4294967294].`},INVALID_ROOM_ID_INTEGER_STRING({key:o}){return`'${o}' must be an integer but go a string, use 'parseInt' to convert it or use 'strRoomId' instead.`},INVALID_ROOM_ID_REQUIRED(){return"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required."},INVALID_ROOM_ID_TYPE_MISMATCH({key:o}){return`The type of target roomId must match the current roomId. Current room is using '${o}', but received '${o==="strRoomId"?"roomId":"strRoomId"}'.`},INVALID_ROOM_ID_DUPLICATE({key:o}){return`the target '${o}' must not be the same as the current '${o}'.`},INVALID_STREAM_TYPE:({fnName:o})=>`'streamType' is required when 'userId' is not '*', calling ${o}()`,INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION({fnName:o}){return`the API '${o}' you called does not meet the requirements, please check the API documentation.`},INVALID_OPERATION_NOT_JOINED({fnName:o}){return`cannot ${o} because you are not enter room yet.`},INVALID_OPERATION_REMOTE_USER_NOT_EXIST({fnName:o,value:i}){return`cannot ${o} because remote user(userId: ${i.userId}) does not publishing stream.`},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST({fnName:o,value:i}){return`cannot ${o} because remote user(userId: ${i.userId}) does not publishing ${i.streamType} video.`},INVALID_OPERATION_REPEAT_CALL({fnName:o}){return`you are already ${o}(), cannot repeated call '${o}'.`},INVALID_OPERATION_NEED_VIDEO({fnName:o}){return`cannot call '${o}' because the camera is not turned on.`},INVALID_OPERATION_NEED_AUDIO({fnName:o}){return`cannot call '${o}' because the microphone or screen share is not turned on.`},INVALID_BUFFER_EMPTY:({key:o})=>`the buffer size of paramerter '${o}' cannot be empty`,INVALID_BUFFER_OVERSIZE:()=>"buffer size is over 1000 Bytes",INVALID_ROLE_AUDIENCE:()=>"role: 'audience' cannot call this api.",INVALID_NOT_ENABLE_SEI:()=>"you need to enable SEI in TRTC.create({ enableSEI: true })",INVALID_NEED_CALL_PUBLISHED:({fnName:o})=>`you need to call ${o}() after publish stream.`,ENV_NOT_SUPPORTED({fnName:o}){return`the current browser does not support the capability of the function '${o}' you are calling, please check the API documentation.`},NOT_SUPPORTED_WEBRTC:"the current browser does not support WebRTC capability, please check the SDK documentation.",NOT_SUPPORTED_H264_ENCODE:"this browser does not support H264 encode.",NOT_SUPPORTED_H264_DECODE:"this browser does not support H264 decode.",NOT_SUPPORTED_SCREEN_SHARE:"this browser does not support screen share, please check the browser version.",NOT_SUPPORTED_SMALL_VIDEO:"this browser does not support small video, please check the browser version.",NOT_SUPPORTED_SEI:"this browser does not support SEI, please check the browser version.",NOT_SUPPORTED_WEBGL:"this browser does not support WebGL, please check the browser version.",NOT_SUPPORTED_CHROME_VERSION({fnName:o}){return`cannot call ${o} because the browser version is too low, please upgrade to the latest version`},DEVICE_ERROR({fnName:o,error:i}){return`'${o}' got device exception${i?`, error: ${i.toString()}.`:"."}`},DEVICE_NOT_FOUND_ERROR({fnName:o,deviceType:i=Io(o),error:e}){return`NotFoundError, no ${i} detected, please check your device and the configuration on '${o}'${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_ALLOWED_ERROR({fnName:o,deviceType:i=Io(o),error:e}){return`NotAllowedError, you have disabled ${i} access, please allow the current application to use the ${i}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_READABLE_ERROR({fnName:o,deviceType:i=Io(o),error:e}){return`NotReadableError, the ${i} maybe in use by another APP, please check if the device is pre-occupied by another APP.`},DEVICE_OVERCONSTRAINED_ERROR({fnName:o,deviceType:i=Io(o),error:e}){return`OverconstrainedError, the device ID is incorrect, please check whether the device ID passed in is correct${e?`, error: ${e.toString()}.`:"."}`},DEVICE_INVALID_STATE_ERROR({fnName:o,deviceType:i=Io(o),error:e}){return`InvalidStateError, after the user clicks and interacts with the page, turn on the ${i}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_SECURITY_ERROR({fnName:o,deviceType:i=Io(o),error:e}){return`SecurityError, check whether the system security policy restricts the use of the ${i}, and it is recommended to turn on the ${i} after the user interacts with the page${e?`, error: ${e.toString()}.`:"."}`},DEVICE_ABORT_ERROR({fnName:o,deviceType:i=Io(o),error:e}){return`AbortError, an unknown exception in the system makes the device unusable, recommended to change the device or browser and re-check whether the device is normal${e?` error: ${e.toString()}.`:"."}`},CAMERA_RECOVER_FAILED({error:o}){return`camera recover capture failed ${(o==null?void 0:o.name)||""}: ${(o==null?void 0:o.originMessage)||(o==null?void 0:o.message)}`},MICROPHONE_RECOVER_FAILED({error:o}){return`microphone recover capture failed ${(o==null?void 0:o.name)||""}: ${(o==null?void 0:o.originMessage)||(o==null?void 0:o.message)}`},OPERATION_FAILED({fnName:o,error:i}){return`'${o}' failed, reason: ${i==null?void 0:i.toString()}`},FIREWALL_RESTRICTION(){return"media connection failure due to firewall restrictions, please try to change your network."},EVENT_HANDLER_ERROR({eventName:o}){return`an error was caught on trtc.on('${o}', handler), please check your code on 'handler'.`},VIDEO_CONTEXT_ERROR({reason:o,error:i}){return`video context error ${o} ${(i==null?void 0:i.name)||""} ${(i==null?void 0:i.message)||""}`},SERVER_ERROR({fnName:o,error:i}){return`'${o}' got server error: ${i==null?void 0:i.toString()}, please check the SDK documentation.`},NEED_TO_BUY({value:o,url:i}){return`You need to buy packages for ${o}. Refer to: ${i}`},ACCOUNT_NO_MONEY:({fnParams:o})=>`your TRTC account run out of credit, please recharge.${o.sdkAppId?` SDKAppId: ${o.sdkAppId}`:""}`,OPERATION_ABORT({fnName:o}){return`'${o}' abort`},UNKNOWN_ERROR({fnName:o,error:i}){return`'${o}' throw unknown exception${i?`, error: ${i.toString()}.`:"."}`}});function Io(o){if(!o)return"camera";let i=o.toLowerCase();return i.includes("screen")?"screen share":i.includes("audio")?"microphone":"camera"}var Rh=class o extends Error{constructor({code:e,extraCode:t,message:r="",messageParams:s,fnName:n="",originError:a,data:c}){var u;let l;r?l=r:l=yf({code:e===$.SERVER_ERROR?e:t||e,params:M({fnName:n,error:a},s)});super(l);d(this,"name","RtcError");d(this,"code");d(this,"extraCode");d(this,"functionName");d(this,"message");d(this,"data");d(this,"handler");d(this,"originError");this.name=wt[e],this.code=e,this.extraCode=t,this.functionName=n,this.originError=a,this.message=l,this.data=c,this.extraCode===5302&&((u=this.originError)!=null&&u.message.includes("system"))&&(this.handler=()=>{let h={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},m={startLocalVideo:"webcam",startLocalAudio:"microphone"},_=document.createElement("a");Qr?_.href=`ms-settings:privacy-${m[this.functionName]}`:oi&&(_.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${h[this.functionName]}`),_.href.length>0&&_.click()})}static convertFrom(e,t,r){let s=e;if(e instanceof D){let{stack:n}=e,a={code:$.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case I.INVALID_PARAMETER:a.code=$.INVALID_PARAMETER,a.message=e.message;break;case I.INVALID_OPERATION:a.code=$.INVALID_OPERATION;break;case I.NOT_SUPPORTED:case I.NOT_SUPPORTED_H264:a.code=$.ENV_NOT_SUPPORTED,e.getCode()===I.NOT_SUPPORTED_H264&&(a.extraCode=e.message.includes(je.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case I.JOIN_ROOM_FAILED:a.messageParams={fnParams:r};case I.SERVER_TIMEOUT:case I.SWITCH_ROLE_FAILED:case I.SWITCH_ROOM_FAILED:a.code=$.SERVER_ERROR,a.extraCode=e.getExtraCode();break;case I.API_CALL_ABORTED:a.code=$.OPERATION_ABORT;break;case I.DEVICE_NOT_FOUND:case I.DEVICE_AUTO_RECOVER_FAILED:case I.INITIALIZE_FAILED:a.code=5300,e.name&&(a.extraCode=kS(e.name));break;case I.VIDEO_ENCODE_FAILED:a.extraCode=5505;case I.AUDIO_ENCODE_FAILED:a.extraCode=5506,a.code=$.OPERATION_FAILED;break;case I.UNKNOWN:break;default:a.code=$.OPERATION_FAILED}s=new o(a),n&&(s.stack+=n.substr(n.indexOf(`
|
|
54
|
+
`)))}else{if(e instanceof o)return e;s=new o({code:$.UNKNOWN_ERROR,fnName:t,originError:e})}return s}};function kS(o){let i;switch(o){case"NotFoundError":i=5301;break;case"NotAllowedError":i=5302;break;case"NotReadableError":i=5303;break;case"OverconstrainedError":i=5304;break;case"InvalidStateError":i=5305;break;case"SecurityError":i=5306;break;case"AbortError":i=5307;break;default:i=5300}return i}var V=Rh;function Pi(o){return o==="sub"?"auxiliary":o==="auxiliary"?"sub":"main"}function Jn(o){return o===So.QOS_PREFERENCE_CLEAR?"detail":o===So.QOS_PREFERENCE_SMOOTH?"motion":""}function Is(o,i){let e=i?zd:pr;return Il(o)?M(M({},e),o):Qt[o]?Qt[o]:e}var bf={type:"object",properties:{cameraId:{type:"string"},useFrontCamera:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:["string","boolean"],values:[!0,!1,"view","publish","both"]},small:{type:["string","object","boolean"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack}}},vf={type:"object",properties:{systemAudio:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},profile:{type:["string","object"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack},audioTrack:{instanceOf:MediaStreamTrack}}},As={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(o,i,e){if(ie(o)&&!document.getElementById(o))throw new V({code:$.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:i}})}},Nf={name:"userId",required:!0,type:"string"},Df={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{type:["string","object"],properties:{bitrate:{type:"number"},channelCount:{type:"number"}}},echoCancellation:{values:[!0,!1,"remote-only","all"]},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function Cs(o,i){if(!o)throw new V({code:$.INVALID_OPERATION,extraCode:5101,fnName:i})}function Of(o,i,e){if(!o)throw new V({code:$.INVALID_OPERATION,extraCode:5102,fnName:i,messageParams:{value:e}})}function Mf(o,i,e){if(!(/^[1-9]\d*$/.test(String(o))&&o<4294967295))throw new V({code:$.INVALID_PARAMETER,extraCode:5013,fnName:i,messageParams:{key:e}})}function kf(o,i,e){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(o))throw new V({code:$.INVALID_PARAMETER,extraCode:5012,fnName:i,messageParams:{key:e}})}var Lw={type:"number",notLessThanZero:!0},PS=(o,i)=>o.width*o.height>=i.width*i.height&&o.frameRate>=i.frameRate&&o.bitrate>=i.bitrate;function Pf(o){var t;if(!((t=o==null?void 0:o.option)!=null&&t.small))return;if(!Tc()){R.warn("small stream is not supported"),delete o.option.small;return}let i=Is(o.option.profile),e=Is(o.option.small,!0);if(!PS(i,e)){R.warn(`small stream profile must be less than big stream profile. Big: ${JSON.stringify(i)}, Small: ${JSON.stringify(e)}`),delete o.option.small;return}}var wS={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(o,i,e){if(this._room.isJoined)throw new V({code:$.INVALID_OPERATION,extraCode:5104,fnName:e});if(o.roomId){if(ie(o.roomId))throw new V({code:$.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:i}});Mf(o.roomId,e,i)}else if(o.strRoomId)kf(o.strRoomId,e,i);else throw new V({code:$.INVALID_PARAMETER,extraCode:5015,fnName:e})},properties:{sdkAppId:{required:!0,type:"number",allowEmpty:!1},userId:{required:!0,type:"string",allowEmpty:!1},userSig:{required:!0,type:"string",allowEmpty:!1},scene:{type:"string",values:["live","rtc"]},role:{type:"string",values:["audience","anchor"]},roomId:{type:["string","number"]},strRoomId:{type:"string"},proxy:{type:["object","string"],properties:{websocketProxy:{type:"string"},turnServer:{type:["object","array"],properties:{url:{required:!0,type:"string"},username:{type:"string"},credential:{type:"string"},credentialType:{type:"string",values:["password"]}}},loggerProxy:{type:"string"},webtransportProxy:{type:"string"}}},enableAutoPlayDialog:{type:"boolean"},userDefineRecordId:{type:"string"},latencyLevel:{type:"number"},playoutDelay:{type:"object",properties:{min:{type:"number",min:0,max:1e3},max:{type:"number",min:0,max:1e4}}}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:As,mute:{type:["boolean","string"]},publish:{type:"boolean"},capture:{required:!1,type:"boolean"},option:bf},validate(o){var i,e;if(!((i=o==null?void 0:o.option)!=null&&i.videoTrack)&&Zi())throw new V({code:$.ENV_NOT_SUPPORTED,extraCode:5201});(e=o==null?void 0:o.option)!=null&&e.small&&Pf(o)}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:L(M({},As),{required:!1}),publish:{type:"boolean"},capture:{required:!1,type:"boolean"},mute:{type:["boolean","string"]},option:bf},validate(o){var i;(i=o==null?void 0:o.option)!=null&&i.small&&Pf(o)}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:Df},validate(o){var i;if(!((i=o==null?void 0:o.option)!=null&&i.audioTrack)&&Zi())throw new V({code:$.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:Df}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:As,publish:{type:"boolean"},option:vf},validate(o,i,e,t,r){var s;if(!((s=o==null?void 0:o.option)!=null&&s.videoTrack)){if(Zi())throw new V({code:$.ENV_NOT_SUPPORTED,extraCode:5201});if(!_n())throw new V({code:$.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:As,publish:{type:"boolean"},option:vf}},muteRemoteAudio:[Nf,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[Nf,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:As,userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(o,i,e){Cs(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(o.userId);if(Of(!!t,e,o),t&&(o.streamType==="main"&&!t.muteState.videoAvailable||o.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new V({code:$.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:o}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:L(M({},As),{required:!1}),userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(o,i,e){Cs(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(o.userId);if(Of(!!t,e,o),t&&(o.streamType==="main"&&!t.muteState.videoAvailable||o.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new V({code:$.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:o}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(o,i,e){if(o.userId!=="*"&&T(o.streamType))throw new V({code:$.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(o,i,e){Cs(this._room.isJoining||this._room.isJoined,e)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(o,i,e,t){if(!En)throw new V({code:$.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new V({code:$.INVALID_OPERATION,fnName:e,extraCode:5108});if(o.byteLength>1e3)throw new V({code:$.INVALID_PARAMETER,extraCode:5018,fnName:e});if(o.byteLength===0)throw new V({code:$.INVALID_PARAMETER,extraCode:5017,messageParams:{key:i},fnName:e});Cs(this._room.isJoined,e)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(o,i,e){if(!o&&!this._room.isMainStreamPublished||o&&!this._room.isAuxStreamPublished)throw new V({code:$.INVALID_OPERATION,extraCode:5109,messageParams:{key:i},fnName:e})}}}}],sendCustomMessage:{name:"message",required:!0,type:"object",properties:{cmdId:{type:"number",required:!0,min:1,max:10},data:{instanceOf:ArrayBuffer,required:!0,validate(o,i,e,t){if(o.byteLength>1e3)throw new V({code:$.INVALID_PARAMETER,extraCode:5018,fnName:e});if(o.byteLength===0)throw new V({code:$.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:i}})}}},validate(o,i,e){if(Cs(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new V({code:$.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:i}})}},switchRoom:{name:"switchRoomConfig",type:"object",required:!0,validate(o,i,e){if(Cs(this._room.isJoined,e),this._room.useStringRoomId&&o.strRoomId===this._room.roomId||!this._room.useStringRoomId&&o.roomId===Number(this._room.roomId))throw new V({code:$.INVALID_PARAMETER,extraCode:5020,fnName:e,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(o.roomId&&this._room.useStringRoomId||!o.roomId&&o.strRoomId&&!this._room.useStringRoomId)throw new V({code:$.INVALID_PARAMETER,extraCode:5019,fnName:e,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(o.roomId)Mf(o.roomId,e,i);else if(o.strRoomId)kf(o.strRoomId,e,i);else throw new V({code:$.INVALID_PARAMETER,extraCode:5015,fnName:e})},properties:{roomId:{type:"number"},strRoomId:{type:"string"},privateMapKey:{type:"string"},userSig:{type:"string",required:!0},autoSubscribeCount:{type:"number",min:0,max:50}}}},Ge={TRTC:wS};var ut=class extends Error{};function LS(o,i){let e=Gr(o);for(let t=0;t<i.length;t++)ti(e[t],i[t]);return e}function xS(o){this._resolve=Promise.resolve(o)}function US(o){this._reject=Promise.reject(o)}var Pr=class Pr{constructor(i,e){this.instance=i;this.group=e;d(this,"started",!1);d(this,"ops",[]);d(this,"startSame",()=>!0);d(this,"mergeUpdate",LS);let t=Pr.instances.get(i);t?t.set(e,this):Pr.instances.set(i,new Map([[e,this]]))}static get(i,e){if(!e)return;let t=Pr.instances.get(i);return t&&t.get(e)||new Pr(i,e)}static gets(i,e){let t=Pr.instances.get(i),r=[];return t&&t.forEach((s,n)=>{e.test(n)&&r.push(s)}),r}action(i,e,t){let r=a=>{var c;return i===0?this.started=!0:i===3&&(this.started=!1),this.ops.shift(),(c=this.currentOp)==null||c.action(),a},s=a=>{var c,l;throw this.ops.shift(),i===0&&((c=this.currentOp)==null?void 0:c.type)===2&&this.ops.shift().reject(new ut("start failed")),(l=this.currentOp)==null||l.action(),a},n={type:i,action:()=>e(...n.args).then(r,s),args:t,resolve:xS,reject:US};try{switch(this.state){case 1:if(i===0)throw new ut("already started");break;case 4:if(i===2)throw new ut("not started");break;default:return this.cacheOp(n)}}catch(a){return Promise.reject(a)}return this.ops.push(n),n.promise=e(...n.args).then(r,s)}cacheOp(i){if(this.ops.length===1)switch(this.state){case 0:case 2:if(i.type===0)throw new ut("already start");break;case 3:switch(i.type){case 2:throw new ut("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new ut("unknown state")}else switch(i.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let t=new ut("keep stop");if(this.ops.slice(1).forEach(r=>r.reject(t)),this.ops=this.ops.slice(0,1),this.state===3)return this.currentOp.promise}break;case 2:switch(this.lastOpType){case 2:return this.lastOp.args=this.mergeUpdate(this.lastOp.args,i.args),this.lastOp.promise;case 3:throw new ut("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new ut("start not allowed after update");case 0:throw new ut("duplicate start");case 3:if(this.startSame(this.currentOp.args,i.args))throw this.ops.pop().reject(new ut("keep start")),new ut("already start")}}i.promise=new Promise((t,r)=>{i._resolve?i._resolve.then(t):i.resolve=t,i._reject?i._reject.catch(r):i.reject=r});let{action:e}=i;return i.action=()=>e().then(i.resolve,i.reject),this.ops.push(i),i.promise}get lastOp(){return this.ops[this.ops.length-1]}get lastOpType(){return this.lastOp.type}get currentOp(){return this.ops[0]}get state(){return this.currentOp?this.currentOp.type:this.started?1:4}};d(Pr,"instances",new WeakMap);var nr=Pr;var nd=new WeakMap,ad=(o,i)=>{if(i instanceof ut){let{stack:e}=i;i=new V({code:$.OPERATION_ABORT,message:`${o} abort: ${i.message}`,fnName:o}),e&&(i.stack+=e.substr(e.indexOf(`
|
|
55
|
+
`)))}throw i};function wr(o,i){return Y((e,t)=>function(...r){let s=nr.get(this,typeof o=="string"?o:o.call(this,...r));return s?(i&&(s.startSame=i.bind(this)),s.action(0,e.bind(this),r).catch(ad.bind(null,t))):e.apply(this,r)})}function Ao(o,i){let{merge:e,debounce:t}=i||{};return Y((r,s)=>function(...n){let a=nr.get(this,typeof o=="string"?o:o.call(this,...n));if(!a)return r.apply(this,n);if(e&&(a.mergeUpdate=e.bind(this)),t&&t.isNeedToDebounce.apply(this,n)){let{delay:c,getKey:l}=t;return new Promise((u,h)=>{var g,E;let m=(g=nd.get(this))==null?void 0:g.get(l(...n));if(m){let{timeoutId:C,resolve:k}=m;clearTimeout(C),k()}let _=setTimeout(()=>{if(a.state===3||a.state===4)return u();a.action(2,r.bind(this),n).catch(ad.bind(null,s)).then(u,h)},c);nd.has(this)?(E=nd.get(this))==null||E.set(l(...n),{timeoutId:_,resolve:u}):nd.set(this,new Map([[l(...n),{timeoutId:_,resolve:u}]]))})}return a.action(2,r.bind(this),n).catch(ad.bind(null,s))})}function Lr(o){return Y((i,e)=>function(...t){let r=typeof o=="function"?o.call(this,...t):o;if(r instanceof RegExp)return Promise.all(nr.gets(this,r).map(n=>n.action(3,()=>Promise.resolve(),t))).then(()=>i.call(this,...t));let s=nr.get(this,r);return s?s.action(3,i.bind(this),t).catch(ad.bind(null,e)):i.apply(this,t)})}function xr(){return function(o,i,e){return o.prototype[i]=function(){let t=this._log||console,r=`"${i}" is a static method. Use TRTC.${i}() instead. See: ${ft}/en/TRTC.html#.${i}`;t.warn(r)},e}}var x={ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",KICKED_OUT:"kicked-out",REMOTE_USER_ENTER:"remote-user-enter",REMOTE_USER_EXIT:"remote-user-exit",REMOTE_AUDIO_AVAILABLE:"remote-audio-available",REMOTE_AUDIO_UNAVAILABLE:"remote-audio-unavailable",REMOTE_VIDEO_AVAILABLE:"remote-video-available",REMOTE_VIDEO_UNAVAILABLE:"remote-video-unavailable",AUDIO_VOLUME:"audio-volume",AUDIO_FRAME:"audio-frame",NETWORK_QUALITY:"network-quality",CONNECTION_STATE_CHANGED:"connection-state-changed",AUDIO_PLAY_STATE_CHANGED:"audio-play-state-changed",VIDEO_PLAY_STATE_CHANGED:"video-play-state-changed",SCREEN_SHARE_STOPPED:"screen-share-stopped",DEVICE_CHANGED:"device-changed",PUBLISH_STATE_CHANGED:"publish-state-changed",TRACK:"track",STATISTICS:"statistics",SEI_MESSAGE:"sei-message",CUSTOM_MESSAGE:"custom-message",VIDEO_DECODE_DOWNGRADE_STATE_CHANGED:"video-decode-downgrade-state-changed",LAYER_DATA:"layerData",FIRST_VIDEO_FRAME:"first-video-frame",PERMISSION_STATE_CHANGE:"permission-state-change",VIDEO_SIZE_CHANGED:"video-size-changed"},wf=new Set([x.AUDIO_VOLUME,x.AUDIO_FRAME,x.NETWORK_QUALITY,x.STATISTICS,x.SEI_MESSAGE,x.CUSTOM_MESSAGE,x.LAYER_DATA]);var vh={};Vi(vh,{ScheduleRequestType:()=>Uf,getAbilityConfig:()=>FS,getScheduleDomain:()=>ld,isNeedToSchedule:()=>cd,scheduleProxy:()=>wi,sendScheduleRequest:()=>bh,setIsNeedToSchedule:()=>Lt,setScheduleProxy:()=>dd});var yh=null,xf=0,VS=48*3600*1e3,cd=!0;typeof document!="undefined"&&document.head.insertAdjacentHTML("beforeend",Object.values($i).map(o=>`<link rel="dns-prefetch" href="https://${o}">`).join(`\r
|
|
56
|
+
`));function Lt(o){me(o)&&o!==cd&&(cd=o,R.info(`setIsNeedToSchedule ${o}`),o||(xf=Date.now()+VS))}S.on("28",()=>Lt(!0));S.on("63",()=>Lt(!0));S.on("84",()=>Lt(!0));S.on("201",o=>{o.state==="RECONNECTING"&&Lt(!0)});S.on("202",o=>{o.state==="RECONNECTING"&&Lt(!0)});function BS(o,i,e){let t={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let r=performance.getEntriesByType("resource"),s=Ur(o,"config",p.MAIN),n=Ur(o,"config",p.BACKUP);for(let a of r)if(a.startTime>=e&&(a.name===s||a.name===n)&&a.transferSize>0){let c=a.name===s?p.MAIN:p.BACKUP,l=Math.round(a.duration),u=Math.round(a.domainLookupStart-a.startTime),h=a.redirectStart>0?Math.round(a.redirectEnd-a.redirectStart):0,m=a.fetchStart>0?Math.round(a.domainLookupStart-a.fetchStart):0,_=Math.round(a.domainLookupEnd-a.domainLookupStart),g=Math.round(a.requestStart-a.secureConnectionStart),E=Math.round(a.secureConnectionStart-a.connectStart),C=Math.round(a.responseStart-a.requestStart),k=Math.round(a.responseEnd-a.responseStart),ae=[_,g,E,C,k];oe.uploadEvent({log:`stat-schedule-net:${l}(${u}(${h}->${m})->${ae.join("->")}) ${c}`,userId:i}),t=L(M({},t),{totalCost:l,local:u,dns:_,tcp:E,tls:g,request:C,response:k});break}}catch(r){R.error("getScheduleDetailCost error",r)}return t}function bh(l){return f(this,arguments,function*({userId:o,sdkAppId:i,useStringRoomId:e,roomId:t,userSig:r,version:s,frameWorkType:n,role:a,latencyLevel:c}){var h;if(!cd&&yh&&xf>Date.now())return{isCached:!0,result:yh};let u={delta:0,count:[1,1],msg:[],detail:[]};try{let m=new FormData;m.append("userId",String(o)),m.append("sdkAppId",String(i)),m.append("isStrGroupId",String(e)),m.append("groupId",String(t)),m.append("sdkVersion",s),m.append("userSig",String(r));let _=((h=yield Yr())==null?void 0:h.model)||ec();_&&m.append("model",_);let g=ai();g&&m.append("osString",g),a&&m.append("role",String(a)),c&&m.append("latencyLevel",String(c)),n&&m.append("frameWorkType",String(n));let E=U(),C=yield $S(m,u,i);C.config&&(C.config.loggerDomain&&Br(C.config.loggerDomain),me(C.config.scheduleCache)&&Lt(!C.config.scheduleCache)),u.delta=U()-E;let k=BS(Number(i),o,E);return yh=C,{isCached:!1,result:C,detailCost:k}}catch(m){let _=Ae(m)?m[0]:m,g=Q(_.code)?_.code:0,E=`schedule failed${_.message?`: ${_.message}`:""}`,C=new D({code:I.SCHEDULE_FAILED,extraCode:g,message:H({key:B.JOIN_ROOM_FAILED,data:{error:E,code:g}})});throw R.error(E,g),C}})}var wi={main:"",backup:""};function dd(o){Ae(o)?(wi.main=o[0],wi.backup=o[1]):wi.main=o}var Uf=(t=>(t.CONFIG="config",t.TRTC_AUTO_CONF="trtcAutoConf",t.AUDIO_AI_AUTH="audioAiAuth",t))(Uf||{});function Ur(o,i,e=p.MAIN,t=!1){return`https://${wi[e]||ld(o,e,t)}/api/v1/${i}`}function FS(o,i,e){let t=Ur(o,i),r=Ur(o,i,p.BACKUP),s=new URLSearchParams(e).toString(),n=fetch(`${t}?${s}`).then(c=>c.json()),a=fetch(`${r}?${s}`).then(c=>c.json());return Xr([n,a])}function ld(o,i=p.MAIN,e=!1){let t;return Vt(o)?e?t=i===p.MAIN?$i.MAIN_OVERSEA_BACKUP:$i.BACKUP_OVERSEA:t=i===p.MAIN?$i.MAIN_OVERSEA:$i.BACKUP_OVERSEA:t=i===p.MAIN?$i.MAIN:$i.BACKUP,t}function HS(o,i,e){return new Promise((t,r)=>{Ji({url:o,body:i,timeout:e.timeout,priority:"high"}).then(s=>{s.data.code===0?t(s.data.data):r({code:s.data.code,message:s.data.msg})}).catch(r)})}var Lf=(o,i)=>Ci({retryFunction:HS,settings:{retries:3,timeout:0},onError:i,onRetrying:o});function $S(o,i,e){return new Promise((t,r)=>{let s=null;Xr([Lf(n=>i.count[0]=n+1,({error:n,retry:a,retriedCount:c,retryFuncArgs:l})=>{i.msg[0]=n.message,s||(c>=1&&(l[0]=Ur(e,"config",p.MAIN,!0)),a())})(Ur(e,"config",p.MAIN),o,{get timeout(){return qr(2+i.count[0])*1e3}}),Lf(n=>i.count[1]=n+1,({error:n,retry:a,retriedCount:c,retryFuncArgs:l})=>{i.msg[1]=n.message,s||(c>=2&&(l[0]=Ur(e,"config",p.BACKUP,!0)),a())})(Ur(e,"config",p.BACKUP),o,{get timeout(){return qr(2+i.count[1])*1e3}})]).then(n=>{s=n,t(s)}).catch(r)})}var WS=o=>o.startsWith("data:application/octet-stream;base64,"),GS=o=>o.startsWith("file://"),qn=class{constructor(){d(this,"_log");this._log=R.createLogger({id:"fd"})}download(i,e){return f(this,null,function*(){let{type:t="blob"}=e||{};i=Oa(i);try{let r=U(),s;if(ue(fetch)?s=yield this.downloadWithFetch(i,t):s=yield this.downloadWithXHR(i,t),!s||!s.data)throw new Error("data is empty");let n=U()-r;return this._log.info(`downloaded: ${i}, return type: ${t}, cost: ${n}ms`),v.addSuccessEvent({key:522700,cost:U()-r}),s.data}catch(r){throw this._log.error(`failed to download: ${i}, error: ${r}`),v.addFailedEvent({key:522700,error:r}),r}})}downloadWithFetch(i,e){return f(this,null,function*(){this._log.info(`download with fetch: ${i}, return type: ${e}`);try{let t=yield fetch(i);if(!t.ok){let s=new Error(`network response was not ok: ${t.status}`);throw s.status=t.status,s}let r;return e==="arraybuffer"?r=yield t.arrayBuffer():r=yield t.blob(),{data:r}}catch(t){throw t}})}downloadWithXHR(i,e){return this._log.info(`download with xhr: ${i}, return type: ${e}`),new Promise((t,r)=>{let s=new XMLHttpRequest;s.open("GET",i,!0),s.responseType=e,s.onload=()=>{if(s.status===200||s.status===0&&s.response)t({data:s.response});else{let n=new Error(`XHR failed, status: ${s.status}`);n.status=s.status,r(n)}},s.onerror=r,s.send(null)})}loadWasm(i,e){return f(this,null,function*(){this._log.info(`loadWasm ${i}, importObject: ${JSON.stringify(e)}`);let t=U(),r=null,s=null;if(ue(WebAssembly.instantiateStreaming)&&!WS(i)&&!GS(i)&&ue(fetch))try{let n=fetch(i);r=(yield WebAssembly.instantiateStreaming(n,e)).instance}catch(n){s=n}if(!r)try{let n=yield this.download(i,{type:"arraybuffer"});r=(yield WebAssembly.instantiate(n,e)).instance}catch(n){s=n}if(r){let n=U()-t;return this._log.info(`loadedWasm ${i}, cost: ${n}ms`),v.addSuccessEvent({key:522701,cost:n}),r}throw this._log.error(`failed to loadWasm ${i}, error: ${s}`),v.addFailedEvent({key:522701,error:s}),s})}loadScript(i){this._log.info(`loadScript ${i}`);let e=U();return new Promise((t,r)=>{let s=document.createElement("script");s.type="text/javascript",s.onload=()=>{this._log.info(`loadedScript ${i}, cost: ${U()-e}ms`),v.addSuccessEvent({key:522702,cost:U()-e,split:1e3}),t(s)},s.onerror=n=>{this._log.error(`failed to loadScript ${i}, error: ${(n==null?void 0:n.message)||JSON.stringify(n)}`),v.addFailedEvent({key:522702}),r(n)},s.crossOrigin="anonymous",s.src=i,document.head.append?document.head.append(s):document.getElementsByTagName("head")[0].appendChild(s)})}};O([Ot({settings:{timeout:0,retries:3},onError(i,e,t){var r;(i==null?void 0:i.status)===404||(r=i==null?void 0:i.message)!=null&&r.includes("404")?(this._log.warn("download 404, stop retry"),t(i)):e()},onRetrying(i){this._log.warn(`download retrying: ${i}`)}})],qn.prototype,"download",1),O([Ot({settings:{timeout:3e3,retries:3},onRetrying(i){this._log.warn(`loadScript retrying: ${i}`)}})],qn.prototype,"loadScript",1);var jn=new qn;function Vf({TRTC:o,room:i,errorModule:e,assetsPath:t}){return{TRTC:o,LocalMixVideoTrack:go,LocalVideoTrack:Xe,LocalScreenTrack:Pt,room:i,assetsPath:t,fileDownloader:jn,innerEmitter:S,INNER_EVENT:A,constants:ol,environment:es,utils:Eh,eventLogger:oe,log:this.room.getLogger(),loggerManager:R,errorModule:e,kvStatManager:v,rtcDectection:vi,trtc:this,rx:gh,enums:Yl,schedule:vh,getDevices:ls,initVisionTaskRegistry:(r,s="/mediapipe/vision.js")=>f(this,null,function*(){window.VisionTaskRegistry||(yield jn.loadScript(`${r}/${s}`.replace(/([^:]\/)\/+/g,"$1"))),yield(yield window.VisionTaskRegistry.getInstance(r)).preloadModels([window.VisionTaskType.ImageSegmenter])}),audioContext:Se(),deviceDetector:be,AudioPlayer:hs,showAutoPlayDialog:as,Timer:re,clearStarted:(r,s)=>{let n=r.getAlias(),a=nr.instances.get(this);if(a)if(s){let c=a.get(n+s);if(!c)return;c.started=!1}else a.forEach((c,l)=>{l.startsWith(n)&&(c.started=!1)})},startGetPCM:Gn,createAudioNode:Mn,getNetworkTimeOffset:Em,validateSourceNode:()=>{var r;if(te&&!((r=this.room.audioManager._localAudioPipline)!=null&&r.source.node))throw new V({code:$.DEVICE_ERROR,extraCode:5310,message:"The audio processing plugin cannot be used due to the microphone's sampling rate is not 48KHz in Firefox. Please switch to another browser such as Chrome."})}}}var Bf=(o,i)=>{let{emit:e}=o;return o.emit=(...t)=>{try{return e.apply(o,t)}catch(r){let s=H({key:B.CATCH_HANDLER_ERROR,data:{name:i,event:t[0]},addDocLink:!1});return R.warn(`${s}
|
|
99
57
|
|
|
100
|
-
${o.stack}`),!1}},i};var ya=new WeakMap;function iy(i){let t=ya.get(i);t&&(t.forEach(e=>clearTimeout(e)),ya.delete(i))}function Zc(i,t){return ut((e,r)=>function(...o){let s=ya.get(this);s||(s=new Map,ya.set(this,s));let n=t(...o),a=s.get(n);if(!a||a<=0){e.apply(this,o);let c=setTimeout(()=>{var d;(d=ya.get(this))==null||d.delete(n)},i);s.set(n,c)}else{clearTimeout(a);let c=window.setTimeout(()=>{var d;e.apply(this,o),(d=ya.get(this))==null||d.delete(n)},i);s.set(n,c)}})}var sy="trtc-sdk-v5",Vf="5.14.2-wasm.2";function br(...i){return ut((t,e)=>function(...r){try{$l.call(this,i,r,e,this._name)}catch(o){return Promise.reject(o)}return t.apply(this,r)})}function Bf(...i){return ut((t,e)=>function(...r){try{$l.call(this,i,r,e,this._name)}catch(o){throw o}return t.apply(this,r)})}function $l(i,t,e,r){if(Gt(i))for(let o=0;o<i.length;o++)Bl.call(this,{rule:i[o],value:t[o],key:i[o].name,fnName:e,className:r});else Bl.call(this,{rule:i,value:t[0],key:i.name,fnName:e,className:r})}function Bl({rule:i,value:t,key:e,fnName:r,className:o}){function s(c){return{code:ke.INVALID_PARAMETER,extraCode:c,fnName:r,messageParams:{key:e,rule:i,value:t}}}if(z(t)){if(i.required)throw new Oe(s(5001));if(z(i.defaultValue)){Rt(i.validate)&&i.validate.call(this,t,e,r,o,this);return}t=i.defaultValue}if(Array.isArray(i.type)){let c=!1;for(let d=0;d<i.type.length;d++)i.type[d]===null&&t===null&&(c=!0),Rt(i.type[d])&&t instanceof i.type[d]&&(c=!0),nt(i.type[d])&&Xt(t)===i.type[d].toLowerCase()&&(c=!0);if(!c)throw new Oe({code:ke.INVALID_PARAMETER,extraCode:5002,fnName:r,messageParams:{key:e,rule:{type:i.type.map(d=>Os(d)?Ln(d):nt(d)?d:Xt(d))},value:t}})}else if(!z(i.type)&&Xt(t)!==i.type)throw new Oe(s(5002));if(i.allowEmpty===!1){let c=ft(t)&&(t===0||Number.isNaN(t)),d=nt(t)&&t.trim()==="";if(c||d)throw new Oe(s(5003))}if(i.notLessThanZero&&ft(t)&&t<0)throw new Oe(s(5006));if(!z(i.min)&&ft(t)&&t<i.min)throw new Oe(s(5007));if(!z(i.max)&&ft(t)&&t>i.max)throw new Oe(s(5008));if(nt(i.instanceOf)){if(!t||t._name!==i.instanceOf)throw new Oe(s(5004))}else if(Rt(i.instanceOf)&&!(t instanceof i.instanceOf))throw new Oe(s(5004));if(Array.isArray(i.values)&&!i.values.includes(t))throw new Oe(s(5005));let{properties:n}=i;Nr(n)&&Xr(t)&&Object.keys(n).forEach(c=>{Bl.call(this,{rule:n[c],value:t&&t[c],key:`${c}`,fnName:r,className:o})});let{arrayItem:a}=i;Nr(a)&&Gt(t)&&t.forEach((c,d)=>{Bl.call(this,{rule:a,value:c,key:`${e}[${d}]`,fnName:r,className:o})}),Rt(i.validate)&&i.validate.call(this,t,e,r,o,this)}function Vt(i={}){let{getRemoteId:t=()=>"",replaceArg:e,getKVReportKey:r,ignoreLog:o,ignoreErrorLog:s}=i;return ut((n,a)=>function(...c){var g,T,E;function d(y,v,M){if(M&&M.includes(y))return"hided";if(e){let w=e(...c);if(c[w.argIndex]===v)return w.value}if(v===c||y in c)return v;try{return v instanceof HTMLElement?`id: ${v.id} type:${Xt(v)}`:v instanceof MediaStreamTrack?Kd(v):(JSON.stringify(v),v)}catch(w){return`type:${Xt(v)}`}}let m=this._log||se;if(o!=null&&o(...c))return n.apply(this,c);c.length>0?m.info(`${a}() ${JSON.stringify(c,(y,v)=>d(y,v,["userSig","privateMapKey"]))}`):m.info(`${a}()`);let l=r?r(...c):xu[a],f=(s==null?void 0:s(...c))||!1;try{let y=n.apply(this,c),v=Xe();if($o(y)){let M=`${a.includes("Plugin")?`${((T=(g=c[0]).getName)==null?void 0:T.call(g))||""} `:" "}`;return y.then(w=>(m.info(`${a}() success ${M}${t.call(this,...c)}`),Se.addSuccessEvent({key:l,cost:Xe()-v}),w)).catch(w=>{var P;w=Oe.convertFrom.call(this,w,a,c.length===1?c[0]:c);let H=w.extraCode||w.code,B=(P=w.message)!=null&&P.includes(H)?"":` code:${H}`;throw f||m.error(`${a}() failed ${M}${t.call(this,...c)} ${w}${B} params: ${JSON.stringify(c,d)}`),Se.addFailedEvent({key:l,error:w}),w})}return Se.addSuccessEvent({key:l}),y}catch(y){y=Oe.convertFrom.call(this,y,a);let v=y.extraCode||y.code,M=(E=y.message)!=null&&E.includes(v)?"":` code:${v}`;throw f||m.error(`${a}() failed ${y}${M} params: ${JSON.stringify(c,d)}`),Se.addFailedEvent({key:l,error:y}),y}})}var Fl=i=>ut((t,e)=>function(r,o){return D(this,null,function*(){let s=this._plugins.get(r);if(!s)throw this._log.error(`plugin ${String(r)} is not found`),new Oe({code:ke.OPERATION_ABORT,message:`plugin ${String(r)} is not found`,fnName:e});if(Rt(s.constructor.isSupported)&&!s.constructor.isSupported())throw this._log.error(`plugin ${String(r)} is not supported`),new Oe({code:ke.ENV_NOT_SUPPORTED,message:`plugin ${String(r)} is not supported`,extraCode:5210,fnName:e});return $l.call(this,s.getValidateRule(i),[o],e,"TRTC"),t.call(this,s,o)})});var Hl=0,$f,Co=class Co{constructor(t){this.core=t;p(this,"log");p(this,"customAudioReferenceMap",new Map);p(this,"audioRefId",0);p(this,"audioContext",bt());p(this,"localAudioWorkletNode");p(this,"screenAudioWorkletNode");p(this,"mixNode");p(this,"silentNode");Hl=Hl+1,this.log=t.log.createChild({id:`${this.getAlias()}${Hl}`}),this.log.info(`created id=${this.getAlias()}${Hl}`),this.installEvent()}static getStartValidateRule(t){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,r,o,s){if(!t.room.audioManager.hasAudioTrack&&!t.room.audioManager.hasScreenAudioTrack)throw new Oe({code:ke.INVALID_OPERATION,extraCode:5106,fnName:o})}}}preload(t){return $f||($f=this.doPreload(t)),$f}doPreload(t){return D(this,null,function*(){let e=yield this.core.fileDownloader.download(t,{type:"blob"}),r=URL.createObjectURL(e);try{yield yo(this.audioContext,r)}catch(o){this.log.error(`preload audioProcessor failed. ${o}`)}finally{URL.revokeObjectURL(r)}})}getName(){return Co.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(t){switch(t){case"start":return Co.getStartValidateRule(this.core);case"update":return Co.updateValidateRule;case"stop":return Co.stopValidateRule}}start(t){return D(this,null,function*(){var f,g,T,E;let{room:e}=this.core,{sdkAppId:r,userId:o,userSig:s,assetsPath:n=this.core.assetsPath,audioReference:a,processLevel:c,enableDump:d,isLocalAudioNeedAudioProcess:m=!0,isScreenAudioNeedAudioProcess:l=!1}=t;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=m,this.core.room.audioManager.isScreenAudioNeedAudioProcess=l,!n)throw new Oe({code:ke.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`),m&&!this.localAudioWorkletNode){let{sign:y,status:v,timestamp:M}=yield this.getAuthData(r,o,s);this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",r,o,M,y,v,e)}if(l&&!this.screenAudioWorkletNode){let{sign:y,status:v,timestamp:M}=yield this.getAuthData(r,o,s);this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",r,o,M,y,v,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()),(f=this.localAudioWorkletNode)==null||f.port.postMessage({type:"enable"}),(g=this.screenAudioWorkletNode)==null||g.port.postMessage({type:"enable"}),e.audioManager.addAudioProcessor(this.mixNode,this.silentNode,this.localAudioWorkletNode,this.screenAudioWorkletNode),z(a)||a.forEach(y=>{this.customAudioReferenceMap.set(y,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:y,refId:`o-${this.audioRefId++}`})}),z(c)||(T=this.localAudioWorkletNode)==null||T.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:c}}),z(d)||(E=this.localAudioWorkletNode)==null||E.port.postMessage({type:"dump",data:{enable:d}})})}update(t){return D(this,null,function*(){var s,n,a;let{audioReference:e,enableDump:r,processLevel:o}=t;z(e)||(this.customAudioReferenceMap.forEach((c,d)=>{this.customAudioReferenceMap.delete(d),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++}`})})),z(o)||(s=this.localAudioWorkletNode)==null||s.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:o}}),z(r)||((n=this.localAudioWorkletNode)==null||n.port.postMessage({type:"dump",data:{enable:r}}),(a=this.screenAudioWorkletNode)==null||a.port.postMessage({type:"dump",data:{enable:r}}))})}stop(){return D(this,null,function*(){var e,r;let{room:t}=this.core;(e=this.localAudioWorkletNode)==null||e.port.postMessage({type:"disable"}),(r=this.screenAudioWorkletNode)==null||r.port.postMessage({type:"disable"}),yield t.audioManager.removeAudioProcessor(this.localAudioWorkletNode,this.screenAudioWorkletNode)})}destroy(){this.localAudioWorkletNode&&(this.localAudioWorkletNode.port.onmessage=null),this.screenAudioWorkletNode&&(this.screenAudioWorkletNode.port.onmessage=null),this.uninstallEvent()}getAuthData(t,e,r){return D(this,null,function*(){let o=String(Date.now()).slice(0,-3),{auth:s,sign:n,status:a,message:c}=yield qR({sdkAppId:t,userSig:r,userId:e,timestamp:o});if(!s)throw this.log.info(`audioProcessor: ${e} auth result: ${s}. Message: ${c}`),new Oe({code:ke.INVALID_PARAMETER,message:c});return{sign:n,status:a,timestamp:o}})}initWorkletNode(t,e,r,o,s,n,a,c){t.port.postMessage({type:"init",data:{sdkAppId:String(r),userId:o,timestamp:s,sign:n,status:a}}),t.port.onmessage=d=>{var l;let{data:m}=d;switch(m.type){case"cost":let f=(m==null?void 0:m.value)>10?"info":"debug";this.log[f](`${e==="localAudio"?"":`[${e}] `}avg cost: ${m.value} max: ${m==null?void 0:m.max}(${Rn(new Date(m==null?void 0:m.maxCostTimestamp))}) hist: ${(l=m==null?void 0:m.hist)==null?void 0:l.join(" ")}`);return;case"log":this.log[m.logLevel](`${e==="localAudio"?"":`[${e}] `}${m.value}`);return;case"dump":ee.emit("265",{room:c,data:m.value,type:e==="localAudio"?"dump":"dump-screen-audio"});return}}}handleLocalAudioStarted(t){return D(this,null,function*(){var e;if(!(!this.hitTest(t.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(r){this.log.warn(`audio processor auto start failed, error: ${r}`)}})}handleLocalAudioStopped(t){return D(this,null,function*(){var e;!this.hitTest(t.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(t){return t===this.core.room}};p(Co,"updateValidateRule",{type:"object"}),p(Co,"stopValidateRule",{type:"object"}),p(Co,"Name","AudioProcessor");var Wl=Co;function jR(i,t=j.MAIN){return`https://${Qi[t]||Vl(i,t)}/api/v1/audioAiAuth`}function qR(o){return D(this,arguments,function*({sdkAppId:i,userId:t,userSig:e,timestamp:r}){let n=`${jR(i)}?sdkAppId=${i}&userId=${t}&userSig=${e}×tamp=${r}`,a=yield fetch(n),{data:{errCode:c,errMsg:d,sign:m,status:l}}=yield a.json();if(l==="1")return{auth:!0,sign:m,status:l,message:d};let f=si(i)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",g="Init RTCAudioProcessor failed.",T="";switch(c){case 1:T="Please check your params.";break;case 2:T=`You need to buy packages. Refer to: ${f}`;break;case 3:T="Server is invalid. Please contact our engineer. ";break;case 4:T=`Your packages is not active. Refer to: ${f}`;break;case 5:T=`Your packages is expired. Refer to: ${f}`;break;case 6:T="Your version is not supported.";break}return{auth:!1,status:l,message:d?`${g} Reason: ${d}. ${T}`:`${g}, ${T}`}})}var Gl=0,Ff=class{constructor(t,e){p(this,"audioObjectURL");p(this,"player");p(this,"publisher");p(this,"mixInput");this.mixInput=new ia(e),t.url?(this.player=new Audio(t.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(t.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(t.track),this.mixInput.connect()}updateSettings(t){this.player&&(z(t.volume)||(this.volume=t.volume),z(t.loop)||(this.loop=t.loop),z(t.playbackRate)||(this.playbackRate=t.playbackRate))}updateListener(t){if(this.player){if(t.onDurationChange){let{onDurationChange:e}=t;this.player.ondurationchange=r=>{e(r.target.duration)}}if(t.onTimeUpdate){let e=t.onTimeUpdate,{player:r}=this;r.ontimeupdate=()=>{e(r.currentTime,r.duration)}}t.onEnded&&(this.player.onended=t.onEnded)}}reload(t){return D(this,null,function*(){if(t.url){let e=yield Yc.download(t.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(t),this.updateSettings(t))}else this.mixInput.replaceSource(t.track)})}reset(){this.seek(0),this.mixInput.connect()}seek(t){this.player&&(t<0&&t>this.player.duration||(this.player.currentTime=t,this.publisher.currentTime=t))}play(){var t,e;return Promise.all([(t=this.player)==null?void 0:t.play(),(e=this.publisher)==null?void 0:e.play()])}pause(){var t,e;(t=this.player)==null||t.pause(),(e=this.publisher)==null||e.pause()}stop(){var t;(t=this.player)==null||t.pause(),this.mixInput.disconnect()}setOperation(t){t==="pause"&&this.pause(),t==="resume"&&(this.pause(),this.play()),t==="stop"&&(this.pause(),this.seek(0))}set volume(t){!this.player||!this.publisher||(this.player.volume=t,this.publisher.volume=t)}set loop(t){!this.player||!this.publisher||(this.player.loop=t,this.publisher.loop=t)}set playbackRate(t){!this.player||!this.publisher||(this.player.playbackRate=t,this.publisher.playbackRate=t)}};function Sa(i,t){if(t&&typeof t!="function")throw new Oe({code:ke.INVALID_PARAMETER,message:`start audioMixer plugin: param ${i} should be a function.`})}var Yi=class Yi{constructor(t){this.core=t;p(this,"log");p(this,"mixedMusicMap",new Map);p(this,"cacheMusicMap",new Map);Gl=Gl+1,this.log=t.log.createChild({id:`${this.getAlias()}${Gl}`}),this.log.info(`created id=${this.getAlias()}${Gl}`)}getName(){return Yi.Name}getAlias(){return"ax"}getGroup(t){return t==null?void 0:t.id}getValidateRule(t){switch(t){case"start":return Yi.startValidateRule;case"update":return Yi.updateValidateRule;case"stop":return Yi.stopValidateRule}}start(t){return D(this,null,function*(){let{room:e}=this.core;this.core.validateSourceNode(),this.log.info(`add music source, id: ${t.id} url: ${t.url}, track: ${t.track}`);let{id:r,url:o}=t;if(this.mixedMusicMap.has(r))return;let s=this.cacheMusicMap.get(r);s?t.url?s.reset():(s.mixInput.replaceSource(t.track),s.mixInput.connect()):(s=new Ff(t,e.audioManager),this.cacheMusicMap.set(r,s)),s.updateListener(t),s.updateSettings(t);try{yield s.play()}catch(n){yield this.handleAutoPlayFailed(s,t,n)}this.mixedMusicMap.set(r,s),s.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"add",audioReference:s.mixInput.source.node,refId:`ax-${r}`}),this.log.info(`start mix audio track ${r} success.`),Se.addEnum({key:502700,value:3}),this.kvUpload(t)})}handleAutoPlayFailed(t,e,r){return D(this,null,function*(){if(r.name==="NotSupportedError")this.log.error(`play failed, try to reload source. error: ${r}`),yield t.reload(e),yield t.play();else if(r.name==="NotAllowedError")if(this.core.room.enableAutoPlayDialog){let o=()=>{var s;(s=t.play())==null||s.finally(()=>{ee.off("154",o,this)})};ee.on("154",o,this),ta()}else this.core.trtc.emit(Ne.AUTOPLAY_FAILED,{userId:"",mediaType:"audio",resume:()=>D(this,null,function*(){return t.play()})});else throw r})}update(t){return D(this,null,function*(){let{id:e,operation:r,seekFrom:o,playbackRate:s}=t;this.log.info(`update music source, ${JSON.stringify(t)}`);let n=this.mixedMusicMap.get(e);if(!n){this.log.warn(`update music source failed, music id: ${e} not found.`);return}n.updateSettings(t),n.updateListener(t),z(r)||n.setOperation(r),z(o)||n.seek(o),this.kvUpload(t)})}stop(e){return D(this,arguments,function*({id:t}){if(this.mixedMusicMap.has(t)){this.log.info(`remove music source, music id: ${t}`);let r=this.mixedMusicMap.get(t);r!=null&&r.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:r.mixInput.source.node,refId:`ax-${t}`}),r==null||r.stop(),this.mixedMusicMap.delete(t)}t==="*"&&this.destroyAllMusic()})}kvUpload(t){let{track:e,loop:r,volume:o,playbackRate:s,operation:n,seekFrom:a,onTimeUpdate:c,onDurationChange:d,onEnded:m}=t;e&&Se.addCount({key:502009}),r&&Se.addCount({key:502001}),o&&Se.addCount({key:502002}),s&&Se.addCount({key:502003}),n&&Se.addCount({key:502004}),a&&Se.addCount({key:502005}),typeof c!="function"&&Se.addCount({key:502007}),typeof m!="function"&&Se.addCount({key:502008}),typeof d!="function"&&Se.addCount({key:502006})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((t,e)=>{t!=null&&t.mixInput.track&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:t.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()}};p(Yi,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(t,e,r){if(t.url&&t.url!=="*"){let o=t.url.split("?")[0],s=["mp3","ogg","wav","flac"],n=o.split(".").pop(),a=s.indexOf(n)>=0,c=o.startsWith("blob"),d=o.startsWith("data");if(!(a||c||d))throw new Oe({code:ke.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:r})}if(!t.url&&!t.track)throw new Oe({code:ke.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:r});Sa("onTimeUpdate",t.onTimeUpdate),Sa("onEnded",t.onEnded),Sa("onDurationChange",t.onDurationChange)}}),p(Yi,"updateValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},loop:{type:"boolean"},volume:{type:"number"},seekFrom:{type:"number"},operation:{type:"string",values:["pause","resume","stop"]}},validate(t,e,r){Sa("onTimeUpdate",t.onTimeUpdate),Sa("onEnded",t.onEnded),Sa("onDurationChange",t.onDurationChange)}}),p(Yi,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),p(Yi,"Name","AudioMixer");var zl=Yi;var jl=0,Hf,wo=class wo{constructor(t){this.core=t;p(this,"log");p(this,"audioContext",bt("denoiser"));p(this,"workletNode");p(this,"config",{enableFarFieldReduce:!1,farFieldReduceThreshold:.5});jl=jl+1,this.log=t.log.createChild({id:`${this.getAlias()}${jl}`}),this.log.info(`created id=${this.getAlias()}${jl}`)}static startValidateRule(t){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,r,o,s){if(!t.room.audioManager.hasAudioTrack)throw new Oe({code:ke.INVALID_OPERATION,extraCode:5106,fnName:o})}}}preload(t){return Hf||(Hf=this.doPreload(t)),Hf}doPreload(t){return D(this,null,function*(){let e=yield this.core.fileDownloader.download(t,{type:"blob"}),r=URL.createObjectURL(e);try{yield yo(this.audioContext,r)}catch(o){throw this.log.error("load worklet failed",o),o}finally{URL.revokeObjectURL(r)}})}getName(){return wo.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser"}getValidateRule(t){switch(t){case"start":return wo.startValidateRule(this.core);case"update":return wo.updateValidateRule;case"stop":return wo.stopValidateRule}}start(t){return D(this,null,function*(){let{room:e,schedule:r}=this.core,{assetsPath:o=this.core.assetsPath}=t;if(!o)throw new Oe({code:ke.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(`${o}/denoiser-wasm${Km()?"":"-nosimd"}.js`),!this.workletNode){let s=String(Date.now()).slice(0,-3),{auth:n,sign:a,status:c,message:d}=yield JR(r,qe(be({},t),{timestamp:s}));if(!n)throw this.log.info(`RTCAIDenoiser: ${t.userId} auth result: ${n}. Message: ${d}`),new Oe({code:ke.INVALID_PARAMETER,message:d});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(t.sdkAppId),userId:t.userId,timestamp:s,sign:a,status:c}}),this.workletNode.port.onmessage=m=>{var f;let{data:l}=m;if(l.type==="cost"){let g=(l==null?void 0:l.max)>20?"warn":(l==null?void 0:l.max)>10?"info":"debug";this.log[g](`avg cost: ${l.value} max: ${l==null?void 0:l.max}(${Rn(new Date(l==null?void 0:l.maxCostTimestamp))}) hist: ${(f=l==null?void 0:l.hist)==null?void 0:f.join(" ")}`)}else l.type==="log"&&this.log[l.logLevel](`${l.value}`)}}this.updateConfig(t),this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(t){return D(this,null,function*(){this.updateConfig(t)})}stop(){return D(this,null,function*(){if(!this.workletNode)return;let{room:t}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield t.audioManager.removeDenoiser(this.workletNode)})}updateConfig(t){if(!this.workletNode)return;let e=!1;z(t.mode)||(t.mode===0?this.config.enableFarFieldReduce=!1:t.mode===1&&(this.config.enableFarFieldReduce=!0),e=!0),z(t.farFieldReduceThreshold)||(this.config.farFieldReduceThreshold=t.farFieldReduceThreshold,e=!0),e&&this.workletNode.port.postMessage({type:"setConfig",data:this.config})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};p(wo,"updateValidateRule",{type:"object",properties:{mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}}}),p(wo,"stopValidateRule",{type:"object"}),p(wo,"Name","AIDenoiser");var ql=wo;function JR(s,n){return D(this,arguments,function*(i,{sdkAppId:t,userId:e,userSig:r,timestamp:o}){try{let{data:{errCode:a,errMsg:c,sign:d,status:m}}=yield i.getAbilityConfig(t,i.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:t,userId:e,userSig:r,timestamp:o});if(m==="1")return{auth:!0,sign:d,status:m,message:c};let l=si(t)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",f="Init RTCAIDenoiser failed.",g="";switch(a){case 1:g="Please check your params.";break;case 2:g=`You need to buy packages. Refer to: ${l}`;break;case 3:g="Server is invalid. Please contact our engineer. ";break;case 4:g=`Your packages is not active. Refer to: ${l}`;break;case 5:g=`Your packages is expired. Refer to: ${l}`;break;case 6:g="Your version is not supported.";break}return{auth:!1,status:m,message:c?`${f} Reason: ${c}. ${g}`:`${f}, ${g}`}}catch(a){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${a}`}}})}var ay=Li(mo(),1);var Wf=class extends ay.EventEmitter{constructor(){super();p(this,"observer");p(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 D(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!Bt&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){It.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let r=this.stateNum,o=e[e.length-1];this.state=o.state,(this.stateNum>3||r>3)&&se.info(`${o.source}: ${o.state}`),this.emit("state-changed",{type:o.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(r){It.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:r})}}},QR=new Wf,Gf=QR;function YR([i,t]){let e=t.byteLength,r=parseInt(String(e/255),10),o=e%255,s=[];s.push(0,0,0,1,6,i);for(let a=0;a<r;a++)s.push(255);s.push(o);let n=new DataView(t);return s.push(...new Uint8Array(n.buffer)),s.push(128),new rn(new DataView(new Uint8Array(s).buffer),!0)}function ZR(i){return i.type==="empty"||i.data.byteLength===0}function KR(i){return i.getInt32(0)===1&&i.getInt8(4)===6}function e0(i){let t=0,e=0,r=new DataView(i);for(let o=0;o<i.byteLength;o++)switch(r.getUint8(o)){case 0:t++;break;case 1:(t===2||t===3)&&e++,t=0;break;default:t=0;break}return e}function zf({frame:i,seiMessageList:t}){if(!t||t.length===0||i.data.byteLength===0)return i;let r=9-e0(i.data);if(r<=0)return i;let o=t.splice(0,r).reverse().map(YR),s=o.reduce((m,l)=>m+l.dataView.byteLength,0),n=new ArrayBuffer(s+i.data.byteLength),a=new DataView(n),c=new DataView(i.data),d=0;for(let m=0;m<o.length;m++)for(let l=0;l<o[m].dataView.byteLength;l++)a.setInt8(d++,o[m].dataView.getInt8(l));for(let m=0;m<i.data.byteLength;m++)a.setInt8(d++,c.getInt8(m));return i.data=n,i}function jf({frame:i,onSEI:t}){try{let e=new DataView(i.data);if(ZR(i)||!KR(e))return i;let r=[],o=0,s=-1,n=-1;for(let a=0;a<i.data.byteLength;a++){let c=e.getUint8(a);if(c===0)o++;else if(c===1){if(o===2||o===3){let d=a-o;if(s===-1?s=d:n===-1&&(n=d,r.push(new rn(new DataView(e.buffer.slice(s,n)))),s=d,n=-1),!(e.getUint8(a+1)===6)){i.data=e.buffer.slice(d);break}}o=0}else o=0}t==null||t(r.reverse())}catch(e){}return i}var qf=0,Kc=class Kc{constructor(t){this.core=t;p(this,"log");p(this,"_seiMessageList",[]);p(this,"_smallSeiMessageList",[]);p(this,"_subStreamSeiMessageList",[]);qf++,this.log=t.log.createChild({id:`${this.getAlias()}${qf}`}),this.log.info(`[sei] created id=${this.getAlias()}${qf}`),this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode({frame:t,mediaType:e}){try{let r=e===8?this._smallSeiMessageList:e===2?this._subStreamSeiMessageList:this._seiMessageList;return zf({frame:t,seiMessageList:r})}catch(r){this.log.warn(r)}return t}decode({frame:t,track:e}){return jf({frame:t,onSEI:r=>{r.forEach(o=>{this.core.trtc.emit(Ne.SEI_MESSAGE,{seiPayloadType:o.seiPayloadType,data:o.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"})})}})}destroy(){this.log.debug("destroy"),this.stop(),delete this.core}getValidateRule(t){switch(t){case"start":return{type:"object"};case"update":return{type:"object"};case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:zs?this.encode:zf,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:zs?this.decode:jf,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update({buffer:t,options:e}){var s;let r=[e.seiPayloadType,t],o=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(r):(this._seiMessageList.push(r),o&&this._smallSeiMessageList.push(r)),(s=this.core.room.scriptTransformWorker)==null||s.postMessage({type:"sei",data:r,isMain:!e.toSubStream,small:o})}getName(){return Kc.Name}getAlias(){return"sei"}getGroup(){return"sei"}};p(Kc,"autoStart",!0),p(Kc,"Name","SEI");var Xl=Kc;function Xf({frame:i,onDump:t}){return t==null||t(),i}function Jf({frame:i,onDump:t}){return t==null||t(),i}function Qf({frame:i,onDump:t}){return t==null||t(),i}function Yf({frame:i,onDump:t}){return t==null||t(),i}var cy=()=>{let i=window.navigator&&window.navigator.userAgent||"",t=/iPad/i.test(i)||/iPhone/i.test(i),e=/Android/i.test(i);return t||e},Ke={LOG_BUTTON:"Log",NETWORK_BUTTON:"Network",DUMP_BUTTON:"Dump",DUMPING_BUTTON:"Dumping",END_BUTTON:"End",UPLOAD_BUTTON:"Upload Log",EXPORT_BUTTON:"Export Log",HIDE_BUTTON:"Hide",GO_BOTTOM:"goBottom",BACK_TOP:"backTop",CLEAR_LOG:"Clear Log",UPLINK:"Uplink",DOWNLINK:"Downlink",NO_DATA:"No Data",BASIC:"Basic",DURATION:"Duration",VIDEO:"Video",AUDIO:"Audio",SCREEN:"Screen"},dy=i=>i.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d").replace(">",">").replace(">","<"),ls={"play() error: NotAllowedError:":{tips:i=>i.includes("main <video>")||i.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:i=>i.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:i=>i.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"Microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio track is unable to provide media output":{tips:"The microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"is adding audio track to current published local stream":{tips:"add audio track",color:"orange"},"is removing audio track from current published local stream":{tips:"remove audio track",color:"orange"},"is removing video track from current published local stream":{tips:"remove video track",color:"orange"},"is adding video track to current published local stream":{tips:"add video track",color:"orange"},"is replacing audio track to current published local main stream":{tips:"replace audio track",color:"orange"},"is replacing video track to current published local main stream":{tips:"replace video track",color:"orange"},"downlink network quality change":{tips:"Downstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"uplink network quality change":{tips:"Upstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"localStream mute video":{tips:"mute upstream video stream",color:"orange"},"localStream unmute video":{tips:"unmute upstream video stream",color:"orange"},"localStream mute audio":{tips:"mute upstream audio stream",color:"orange"},"localStream unmute audio":{tips:"unmute upstream audio stream",color:"orange"},"black detected":{tips:"Detect black screen, which means fps = 0. It is usually caused by network, and the network will be recovered after a while. If the network is normal but has not been restored, it is an abnormal situation."},'main stream start to play with options: {"muted":true}':{tips:"Play the remote stream in silent mode. Generally, the remote stream does not need to be played in silent mode. You need to confirm whether the parameters passed in the client stream.play API call are correct.",color:"orange"},"main stream - audio player is starting playing":{tips:"Remote stream audio playback success",color:"#0dd90d",class:"success"},"main stream - video player is starting playing":{tips:"Remote stream video playback success",color:"#0dd90d",class:"success"},"video player is playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"audio player is playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"stream - video player is starting playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"stream - audio player is starting playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"switch camera success":{tips:"Switch camera success",color:"#0dd90d",class:"success"},"switch microphone success":{tips:"Switch microphone success",color:"#0dd90d",class:"success"},gotStream:{tips:"Local stream capture success"},"local stream is published successfully":{tips:"Publish success",color:"#0dd90d",class:"success"},"encoderImplementation change to OpenH264":{tips:"Use software encoding"},"encoderImplementation change to ExternalEncoder":{tips:"Use hardware encoding"},"getUserMedia with constraints":{tips:"Start media (camera/microphone) capture"},"getDisplayMedia with constraints":{tips:"Start screen sharing capture"},"client-banned":{tips:"Kicked out of the room",color:"red",class:"red",textColor:"#fff"},user_timeout:{tips:"The backend is too long without receiving SDK heartbeat, which is usually caused by the JS thread being blocked for a long time. If the reproduction probability is high, the application browser Performance tool analyzes where the JS thread is blocked.",color:"red",class:"red",textColor:"#fff"},"schedule failed":{tips:"Signaling request failed, does not affect the normal room entry process, SDK will connect to the default signaling domain."},"updateStream() video flag is true, but no camera detected, set video to false":{tips:"When trying to resume camera acquisition, the camera acquisition is not resumed because it is detected that there is no camera.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to bandwidth":{tips:"bandwidth estimation is not enough to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to cpu":{tips:"cpu load is too high to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: hidden":{tips:"User page switched to backend, in mobile devices, this will cause the device to pause the capture, and it will be restored when the user switches backend to the frontend.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: visible":{tips:"User page switched to frontend",color:"orange",class:"orange",textColor:"#fff"},"main stream - audio player is paused":{tips:`The remote stream audio playback is paused, which usually has two possibilities:
|
|
58
|
+
${r.stack}`),!1}},o};var Rs=new WeakMap;function Ff(o){let i=Rs.get(o);i&&(i.forEach(e=>clearTimeout(e)),Rs.delete(o))}function Hf(o,i){return Y((e,t)=>function(...r){let s=Rs.get(this);s||(s=new Map,Rs.set(this,s));let n=i(...r),a=s.get(n);if(!a||a<=0){e.apply(this,r);let c=setTimeout(()=>{var l;(l=Rs.get(this))==null||l.delete(n)},o);s.set(n,c)}else{clearTimeout(a);let c=window.setTimeout(()=>{var l;e.apply(this,r),(l=Rs.get(this))==null||l.delete(n)},o);s.set(n,c)}})}var Wf="trtc-sdk-v5",Nh="5.15.0-beta.2";function st(...o){return Y((i,e)=>function(...t){try{hd.call(this,o,t,e,this._name)}catch(r){return Promise.reject(r)}return i.apply(this,t)})}function Dh(...o){return Y((i,e)=>function(...t){try{hd.call(this,o,t,e,this._name)}catch(r){throw r}return i.apply(this,t)})}function hd(o,i,e,t){if(Ae(o))for(let r=0;r<o.length;r++)ud.call(this,{rule:o[r],value:i[r],key:o[r].name,fnName:e,className:t});else ud.call(this,{rule:o,value:i[0],key:o.name,fnName:e,className:t})}function ud({rule:o,value:i,key:e,fnName:t,className:r}){function s(c){return{code:$.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:o,value:i}}}if(T(i)){if(o.required)throw new V(s(5001));if(T(o.defaultValue)){ue(o.validate)&&o.validate.call(this,i,e,t,r,this);return}i=o.defaultValue}if(Array.isArray(o.type)){let c=!1;for(let l=0;l<o.type.length;l++)o.type[l]===null&&i===null&&(c=!0),ue(o.type[l])&&i instanceof o.type[l]&&(c=!0),ie(o.type[l])&&Oe(i)===o.type[l].toLowerCase()&&(c=!0);if(!c)throw new V({code:$.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:o.type.map(l=>jr(l)?Uo(l):ie(l)?l:Oe(l))},value:i}})}else if(!T(o.type)&&Oe(i)!==o.type)throw new V(s(5002));if(o.allowEmpty===!1){let c=Q(i)&&(i===0||Number.isNaN(i)),l=ie(i)&&i.trim()==="";if(c||l)throw new V(s(5003))}if(o.notLessThanZero&&Q(i)&&i<0)throw new V(s(5006));if(!T(o.min)&&Q(i)&&i<o.min)throw new V(s(5007));if(!T(o.max)&&Q(i)&&i>o.max)throw new V(s(5008));if(ie(o.instanceOf)){if(!i||i._name!==o.instanceOf)throw new V(s(5004))}else if(ue(o.instanceOf)&&!(i instanceof o.instanceOf))throw new V(s(5004));if(Array.isArray(o.values)&&!o.values.includes(i))throw new V(s(5005));let{properties:n}=o;dt(n)&&yt(i)&&Object.keys(n).forEach(c=>{ud.call(this,{rule:n[c],value:i&&i[c],key:`${c}`,fnName:t,className:r})});let{arrayItem:a}=o;dt(a)&&Ae(i)&&i.forEach((c,l)=>{ud.call(this,{rule:a,value:c,key:`${e}[${l}]`,fnName:t,className:r})}),ue(o.validate)&&o.validate.call(this,i,e,t,r,this)}function Ce(o={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t,ignoreLog:r,ignoreErrorLog:s}=o;return Y((n,a)=>function(...c){var _,g,E;function l(C,k,ae){if(ae&&ae.includes(C))return"hided";if(e){let w=e(...c);if(c[w.argIndex]===k)return w.value}if(k===c||C in c)return k;try{return k instanceof HTMLElement?`id: ${k.id} type:${Oe(k)}`:k instanceof MediaStreamTrack?Ma(k):(JSON.stringify(k),k)}catch(w){return`type:${Oe(k)}`}}let u=this._log||R;if(r!=null&&r(...c))return n.apply(this,c);c.length>0?u.info(`${a}() ${JSON.stringify(c,(C,k)=>l(C,k,["userSig","privateMapKey"]))}`):u.info(`${a}()`);let h=t?t(...c):uc[a],m=(s==null?void 0:s(...c))||!1;try{let C=n.apply(this,c),k=U();if(Tr(C)){let ae=`${a.includes("Plugin")?`${((g=(_=c[0]).getName)==null?void 0:g.call(_))||""} `:" "}`;return C.then(w=>(u.info(`${a}() success ${ae}${i.call(this,...c)}`),v.addSuccessEvent({key:h,cost:U()-k}),w)).catch(w=>{var y;w=V.convertFrom.call(this,w,a,c.length===1?c[0]:c);let Ye=w.extraCode||w.code,N=(y=w.message)!=null&&y.includes(Ye)?"":` code:${Ye}`;throw m||u.error(`${a}() failed ${ae}${i.call(this,...c)} ${w}${N} params: ${JSON.stringify(c,l)}`),v.addFailedEvent({key:h,error:w}),w})}return v.addSuccessEvent({key:h}),C}catch(C){C=V.convertFrom.call(this,C,a);let k=C.extraCode||C.code,ae=(E=C.message)!=null&&E.includes(k)?"":` code:${k}`;throw m||u.error(`${a}() failed ${C}${ae} params: ${JSON.stringify(c,l)}`),v.addFailedEvent({key:h,error:C}),C}})}var md=o=>Y((i,e)=>function(t,r){return f(this,null,function*(){let s=this._plugins.get(t);if(!s)throw this._log.error(`plugin ${String(t)} is not found`),new V({code:$.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});if(ue(s.constructor.isSupported)&&!s.constructor.isSupported())throw this._log.error(`plugin ${String(t)} is not supported`),new V({code:$.ENV_NOT_SUPPORTED,message:`plugin ${String(t)} is not supported`,extraCode:5210,fnName:e});return hd.call(this,s.getValidateRule(o),[r],e,"TRTC"),i.call(this,s,r)})});var pd=0,Oh,ar=class ar{constructor(i){this.core=i;d(this,"log");d(this,"customAudioReferenceMap",new Map);d(this,"audioRefId",0);d(this,"audioContext",Se());d(this,"localAudioWorkletNode");d(this,"screenAudioWorkletNode");d(this,"mixNode");d(this,"silentNode");pd=pd+1,this.log=i.log.createChild({id:`${this.getAlias()}${pd}`}),this.log.info(`created id=${this.getAlias()}${pd}`),this.installEvent()}static getStartValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,t,r,s){if(!i.room.audioManager.hasAudioTrack&&!i.room.audioManager.hasScreenAudioTrack)throw new V({code:$.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return Oh||(Oh=this.doPreload(i)),Oh}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield tr(this.audioContext,t)}catch(r){this.log.error(`preload audioProcessor failed. ${r}`)}finally{URL.revokeObjectURL(t)}})}getName(){return ar.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(i){switch(i){case"start":return ar.getStartValidateRule(this.core);case"update":return ar.updateValidateRule;case"stop":return ar.stopValidateRule}}start(i){return f(this,null,function*(){var m,_,g,E;let{room:e}=this.core,{sdkAppId:t,userId:r,userSig:s,assetsPath:n=this.core.assetsPath,audioReference:a,processLevel:c,enableDump:l,isLocalAudioNeedAudioProcess:u=!0,isScreenAudioNeedAudioProcess:h=!1}=i;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=u,this.core.room.audioManager.isScreenAudioNeedAudioProcess=h,!n)throw new V({code:$.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload(`${n}/audioProcessor-wasm.js`),u&&!this.localAudioWorkletNode){let{sign:C,status:k,timestamp:ae}=yield this.getAuthData(t,r,s);this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",t,r,ae,C,k,e)}if(h&&!this.screenAudioWorkletNode){let{sign:C,status:k,timestamp:ae}=yield this.getAuthData(t,r,s);this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",t,r,ae,C,k,e)}this.mixNode||(this.mixNode=this.audioContext.createGain(),this.mixNode.gain.value=1),this.silentNode||(this.silentNode=this.audioContext.createConstantSource(),this.silentNode.offset.setValueAtTime(0,this.audioContext.currentTime),this.silentNode.start()),(m=this.localAudioWorkletNode)==null||m.port.postMessage({type:"enable"}),(_=this.screenAudioWorkletNode)==null||_.port.postMessage({type:"enable"}),e.audioManager.addAudioProcessor(this.mixNode,this.silentNode,this.localAudioWorkletNode,this.screenAudioWorkletNode),T(a)||a.forEach(C=>{this.customAudioReferenceMap.set(C,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:C,refId:`o-${this.audioRefId++}`})}),T(c)||(g=this.localAudioWorkletNode)==null||g.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:c}}),T(l)||(E=this.localAudioWorkletNode)==null||E.port.postMessage({type:"dump",data:{enable:l}})})}update(i){return f(this,null,function*(){var s,n,a;let{audioReference:e,enableDump:t,processLevel:r}=i;T(e)||(this.customAudioReferenceMap.forEach((c,l)=>{this.customAudioReferenceMap.delete(l),this.core.room.audioManager.updateAudioReference({type:"remove",refId:c})}),e.forEach(c=>{this.customAudioReferenceMap.set(c,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:c,refId:`o-${this.audioRefId++}`})})),T(r)||(s=this.localAudioWorkletNode)==null||s.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:r}}),T(t)||((n=this.localAudioWorkletNode)==null||n.port.postMessage({type:"dump",data:{enable:t}}),(a=this.screenAudioWorkletNode)==null||a.port.postMessage({type:"dump",data:{enable:t}}))})}stop(){return f(this,null,function*(){var e,t;let{room:i}=this.core;(e=this.localAudioWorkletNode)==null||e.port.postMessage({type:"disable"}),(t=this.screenAudioWorkletNode)==null||t.port.postMessage({type:"disable"}),yield i.audioManager.removeAudioProcessor(this.localAudioWorkletNode,this.screenAudioWorkletNode)})}destroy(){this.localAudioWorkletNode&&(this.localAudioWorkletNode.port.onmessage=null),this.screenAudioWorkletNode&&(this.screenAudioWorkletNode.port.onmessage=null),this.uninstallEvent()}getAuthData(i,e,t){return f(this,null,function*(){let r=String(Date.now()).slice(0,-3),{auth:s,sign:n,status:a,message:c}=yield qS({sdkAppId:i,userSig:t,userId:e,timestamp:r});if(!s)throw this.log.info(`audioProcessor: ${e} auth result: ${s}. Message: ${c}`),new V({code:$.INVALID_PARAMETER,message:c});return{sign:n,status:a,timestamp:r}})}initWorkletNode(i,e,t,r,s,n,a,c){i.port.postMessage({type:"init",data:{sdkAppId:String(t),userId:r,timestamp:s,sign:n,status:a}}),i.port.onmessage=l=>{var h;let{data:u}=l;switch(u.type){case"cost":let m=(u==null?void 0:u.value)>10?"info":"debug";this.log[m](`${e==="localAudio"?"":`[${e}] `}avg cost: ${u.value} max: ${u==null?void 0:u.max}(${Do(new Date(u==null?void 0:u.maxCostTimestamp))}) hist: ${(h=u==null?void 0:u.hist)==null?void 0:h.join(" ")}`);return;case"log":this.log[u.logLevel](`${e==="localAudio"?"":`[${e}] `}${u.value}`);return;case"dump":S.emit("265",{room:c,data:u.value,type:e==="localAudio"?"dump":"dump-screen-audio"});return}}}handleLocalAudioStarted(i){return f(this,null,function*(){var e;if(!(!this.hitTest(i.room)||((e=this.core.room.scheduleResult.config)==null?void 0:e.audioProcessor)!==!0))try{yield this.core.trtc.startPlugin("AudioProcessor",{sdkAppId:this.core.room.sdkAppId,userId:this.core.room.userId,userSig:this.core.room.userSig}),this.log.warn("audio processor auto start success")}catch(t){this.log.warn(`audio processor auto start failed, error: ${t}`)}})}handleLocalAudioStopped(i){return f(this,null,function*(){var e;!this.hitTest(i.room)||((e=this.core.room.scheduleResult.config)==null?void 0:e.audioProcessor)!==!0||(yield this.core.trtc.stopPlugin("AudioProcessor"))})}installEvent(){this.core.innerEmitter.on("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.on("114",this.handleLocalAudioStopped,this)}uninstallEvent(){this.core.innerEmitter.off("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.off("114",this.handleLocalAudioStopped,this)}hitTest(i){return i===this.core.room}};d(ar,"updateValidateRule",{type:"object"}),d(ar,"stopValidateRule",{type:"object"}),d(ar,"Name","AudioProcessor");var fd=ar;function JS(o,i=p.MAIN){return`https://${wi[i]||ld(o,i)}/api/v1/audioAiAuth`}function qS(r){return f(this,arguments,function*({sdkAppId:o,userId:i,userSig:e,timestamp:t}){let n=`${JS(o)}?sdkAppId=${o}&userId=${i}&userSig=${e}×tamp=${t}`,a=yield fetch(n),{data:{errCode:c,errMsg:l,sign:u,status:h}}=yield a.json();if(h==="1")return{auth:!0,sign:u,status:h,message:l};let m=Vt(o)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",_="Init RTCAudioProcessor failed.",g="";switch(c){case 1:g="Please check your params.";break;case 2:g=`You need to buy packages. Refer to: ${m}`;break;case 3:g="Server is invalid. Please contact our engineer. ";break;case 4:g=`Your packages is not active. Refer to: ${m}`;break;case 5:g=`Your packages is expired. Refer to: ${m}`;break;case 6:g="Your version is not supported.";break}return{auth:!1,status:h,message:l?`${_} Reason: ${l}. ${g}`:`${_}, ${g}`}})}var _d=0,Mh=class{constructor(i,e){d(this,"audioObjectURL");d(this,"player");d(this,"publisher");d(this,"mixInput");this.mixInput=new ds(e),i.url?(this.player=new Audio(i.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(i.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(i.track),this.mixInput.connect()}updateSettings(i){this.player&&(T(i.volume)||(this.volume=i.volume),T(i.loop)||(this.loop=i.loop),T(i.playbackRate)||(this.playbackRate=i.playbackRate))}updateListener(i){if(this.player){if(i.onDurationChange){let{onDurationChange:e}=i;this.player.ondurationchange=t=>{e(t.target.duration)}}if(i.onTimeUpdate){let e=i.onTimeUpdate,{player:t}=this;t.ontimeupdate=()=>{e(t.currentTime,t.duration)}}i.onEnded&&(this.player.onended=i.onEnded)}}reload(i){return f(this,null,function*(){if(i.url){let e=yield jn.download(i.url,{retries:3,type:"blob"});this.audioObjectURL&&URL.revokeObjectURL(this.audioObjectURL),this.audioObjectURL=URL.createObjectURL(e),this.player&&this.publisher?(this.player.src=this.audioObjectURL,this.publisher.src=this.audioObjectURL):(this.player=new Audio(this.audioObjectURL),this.player.crossOrigin="anonymous",this.publisher=new Audio(this.audioObjectURL),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher),this.updateListener(i),this.updateSettings(i))}else this.mixInput.replaceSource(i.track)})}reset(){this.seek(0),this.mixInput.connect()}seek(i){this.player&&(i<0&&i>this.player.duration||(this.player.currentTime=i,this.publisher.currentTime=i))}play(){var i,e;return Promise.all([(i=this.player)==null?void 0:i.play(),(e=this.publisher)==null?void 0:e.play()])}pause(){var i,e;(i=this.player)==null||i.pause(),(e=this.publisher)==null||e.pause()}stop(){var i;(i=this.player)==null||i.pause(),this.mixInput.disconnect()}setOperation(i){i==="pause"&&this.pause(),i==="resume"&&(this.pause(),this.play()),i==="stop"&&(this.pause(),this.seek(0))}set volume(i){!this.player||!this.publisher||(this.player.volume=i,this.publisher.volume=i)}set loop(i){!this.player||!this.publisher||(this.player.loop=i,this.publisher.loop=i)}set playbackRate(i){!this.player||!this.publisher||(this.player.playbackRate=i,this.publisher.playbackRate=i)}};function ys(o,i){if(i&&typeof i!="function")throw new V({code:$.INVALID_PARAMETER,message:`start audioMixer plugin: param ${o} should be a function.`})}var Li=class Li{constructor(i){this.core=i;d(this,"log");d(this,"mixedMusicMap",new Map);d(this,"cacheMusicMap",new Map);_d=_d+1,this.log=i.log.createChild({id:`${this.getAlias()}${_d}`}),this.log.info(`created id=${this.getAlias()}${_d}`)}getName(){return Li.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return Li.startValidateRule;case"update":return Li.updateValidateRule;case"stop":return Li.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e}=this.core;this.core.validateSourceNode(),this.log.info(`add music source, id: ${i.id} url: ${i.url}, track: ${i.track}`);let{id:t,url:r}=i;if(this.mixedMusicMap.has(t))return;let s=this.cacheMusicMap.get(t);s?i.url?s.reset():(s.mixInput.replaceSource(i.track),s.mixInput.connect()):(s=new Mh(i,e.audioManager),this.cacheMusicMap.set(t,s)),s.updateListener(i),s.updateSettings(i);try{yield s.play()}catch(n){yield this.handleAutoPlayFailed(s,i,n)}this.mixedMusicMap.set(t,s),s.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"add",audioReference:s.mixInput.source.node,refId:`ax-${t}`}),this.log.info(`start mix audio track ${t} success.`),v.addEnum({key:502700,value:3}),this.kvUpload(i)})}handleAutoPlayFailed(i,e,t){return f(this,null,function*(){if(t.name==="NotSupportedError")this.log.error(`play failed, try to reload source. error: ${t}`),yield i.reload(e),yield i.play();else if(t.name==="NotAllowedError")if(this.core.room.enableAutoPlayDialog){let r=()=>{var s;(s=i.play())==null||s.finally(()=>{S.off("154",r,this)})};S.on("154",r,this),as()}else this.core.trtc.emit(x.AUTOPLAY_FAILED,{userId:"",mediaType:"audio",resume:()=>f(this,null,function*(){return i.play()})});else throw t})}update(i){return f(this,null,function*(){let{id:e,operation:t,seekFrom:r,playbackRate:s}=i;this.log.info(`update music source, ${JSON.stringify(i)}`);let n=this.mixedMusicMap.get(e);if(!n){this.log.warn(`update music source failed, music id: ${e} not found.`);return}n.updateSettings(i),n.updateListener(i),T(t)||n.setOperation(t),T(r)||n.seek(r),this.kvUpload(i)})}stop(e){return f(this,arguments,function*({id:i}){if(this.mixedMusicMap.has(i)){this.log.info(`remove music source, music id: ${i}`);let t=this.mixedMusicMap.get(i);t!=null&&t.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:t.mixInput.source.node,refId:`ax-${i}`}),t==null||t.stop(),this.mixedMusicMap.delete(i)}i==="*"&&this.destroyAllMusic()})}kvUpload(i){let{track:e,loop:t,volume:r,playbackRate:s,operation:n,seekFrom:a,onTimeUpdate:c,onDurationChange:l,onEnded:u}=i;e&&v.addCount({key:502009}),t&&v.addCount({key:502001}),r&&v.addCount({key:502002}),s&&v.addCount({key:502003}),n&&v.addCount({key:502004}),a&&v.addCount({key:502005}),typeof c!="function"&&v.addCount({key:502007}),typeof u!="function"&&v.addCount({key:502008}),typeof l!="function"&&v.addCount({key:502006})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((i,e)=>{i!=null&&i.mixInput.track&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:i.mixInput.track,refId:e}),this.stop({id:e})})}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}};d(Li,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(i,e,t){if(i.url&&i.url!=="*"){let r=i.url.split("?")[0],s=["mp3","ogg","wav","flac"],n=r.split(".").pop(),a=s.indexOf(n)>=0,c=r.startsWith("blob"),l=r.startsWith("data");if(!(a||c||l))throw new V({code:$.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new V({code:$.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});ys("onTimeUpdate",i.onTimeUpdate),ys("onEnded",i.onEnded),ys("onDurationChange",i.onDurationChange)}}),d(Li,"updateValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},loop:{type:"boolean"},volume:{type:"number"},seekFrom:{type:"number"},operation:{type:"string",values:["pause","resume","stop"]}},validate(i,e,t){ys("onTimeUpdate",i.onTimeUpdate),ys("onEnded",i.onEnded),ys("onDurationChange",i.onDurationChange)}}),d(Li,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),d(Li,"Name","AudioMixer");var gd=Li;var Td=0,kh,cr=class cr{constructor(i){this.core=i;d(this,"log");d(this,"audioContext",Se("denoiser"));d(this,"workletNode");d(this,"config",{enableFarFieldReduce:!1,farFieldReduceThreshold:.5});Td=Td+1,this.log=i.log.createChild({id:`${this.getAlias()}${Td}`}),this.log.info(`created id=${this.getAlias()}${Td}`)}static startValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0},mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}},validate(e,t,r,s){if(!i.room.audioManager.hasAudioTrack)throw new V({code:$.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return kh||(kh=this.doPreload(i)),kh}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield tr(this.audioContext,t)}catch(r){throw this.log.error("load worklet failed",r),r}finally{URL.revokeObjectURL(t)}})}getName(){return cr.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser"}getValidateRule(i){switch(i){case"start":return cr.startValidateRule(this.core);case"update":return cr.updateValidateRule;case"stop":return cr.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e,schedule:t}=this.core,{assetsPath:r=this.core.assetsPath}=i;if(!r)throw new V({code:$.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload(`${r}/denoiser-wasm${uu()?"":"-nosimd"}.js`),!this.workletNode){let s=String(Date.now()).slice(0,-3),{auth:n,sign:a,status:c,message:l}=yield XS(t,L(M({},i),{timestamp:s}));if(!n)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${n}. Message: ${l}`),new V({code:$.INVALID_PARAMETER,message:l});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(i.sdkAppId),userId:i.userId,timestamp:s,sign:a,status:c}}),this.workletNode.port.onmessage=u=>{var m;let{data:h}=u;if(h.type==="cost"){let _=(h==null?void 0:h.max)>20?"warn":(h==null?void 0:h.max)>10?"info":"debug";this.log[_](`avg cost: ${h.value} max: ${h==null?void 0:h.max}(${Do(new Date(h==null?void 0:h.maxCostTimestamp))}) hist: ${(m=h==null?void 0:h.hist)==null?void 0:m.join(" ")}`)}else h.type==="log"&&this.log[h.logLevel](`${h.value}`)}}this.updateConfig(i),this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(i){return f(this,null,function*(){this.updateConfig(i)})}stop(){return f(this,null,function*(){if(!this.workletNode)return;let{room:i}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield i.audioManager.removeDenoiser(this.workletNode)})}updateConfig(i){if(!this.workletNode)return;let e=!1;T(i.mode)||(i.mode===0?this.config.enableFarFieldReduce=!1:i.mode===1&&(this.config.enableFarFieldReduce=!0),e=!0),T(i.farFieldReduceThreshold)||(this.config.farFieldReduceThreshold=i.farFieldReduceThreshold,e=!0),e&&this.workletNode.port.postMessage({type:"setConfig",data:this.config})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};d(cr,"updateValidateRule",{type:"object",properties:{mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}}}),d(cr,"stopValidateRule",{type:"object"}),d(cr,"Name","AIDenoiser");var Ed=cr;function XS(s,n){return f(this,arguments,function*(o,{sdkAppId:i,userId:e,userSig:t,timestamp:r}){try{let{data:{errCode:a,errMsg:c,sign:l,status:u}}=yield o.getAbilityConfig(i,o.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:i,userId:e,userSig:t,timestamp:r});if(u==="1")return{auth:!0,sign:l,status:u,message:c};let h=Vt(i)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",m="Init RTCAIDenoiser failed.",_="";switch(a){case 1:_="Please check your params.";break;case 2:_=`You need to buy packages. Refer to: ${h}`;break;case 3:_="Server is invalid. Please contact our engineer. ";break;case 4:_=`Your packages is not active. Refer to: ${h}`;break;case 5:_=`Your packages is expired. Refer to: ${h}`;break;case 6:_="Your version is not supported.";break}return{auth:!1,status:u,message:c?`${m} Reason: ${c}. ${_}`:`${m}, ${_}`}}catch(a){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${a}`}}})}var Jf=Je(at(),1);var Ph=class extends Jf.EventEmitter{constructor(){super();d(this,"observer");d(this,"state","nominal");this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return f(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!_e&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){oe.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let t=this.stateNum,r=e[e.length-1];this.state=r.state,(this.stateNum>3||t>3)&&R.info(`${r.source}: ${r.state}`),this.emit("state-changed",{type:r.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(t){oe.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},zS=new Ph,wh=zS;function Lh([o,i]){let e=i.byteLength,t=parseInt(String(e/255),10),r=e%255,s=[];s.push(0,0,0,1,6,o);for(let a=0;a<t;a++)s.push(255);s.push(r);let n=new DataView(i);return s.push(...new Uint8Array(n.buffer)),s.push(128),new sr(new DataView(new Uint8Array(s).buffer),!0)}function xh(o){return o.type==="empty"||o.data.byteLength===0}function Uh(o){return o.getInt32(0)===1&&o.getInt8(4)===6}function Vh(o){let i=0,e=0,t=new DataView(o);for(let r=0;r<o.byteLength;r++)switch(t.getUint8(r)){case 0:i++;break;case 1:(i===2||i===3)&&e++,i=0;break;default:i=0;break}return e}function Bh({frame:o,seiMessageList:i}){if(!i||i.length===0||o.data.byteLength===0)return o;let t=9-Vh(o.data);if(t<=0)return o;let r=i.splice(0,t).reverse().map(Lh),s=r.reduce((u,h)=>u+h.dataView.byteLength,0),n=new ArrayBuffer(s+o.data.byteLength),a=new DataView(n),c=new DataView(o.data),l=0;for(let u=0;u<r.length;u++)for(let h=0;h<r[u].dataView.byteLength;h++)a.setInt8(l++,r[u].dataView.getInt8(h));for(let u=0;u<o.data.byteLength;u++)a.setInt8(l++,c.getInt8(u));return o.data=n,o}function Fh({frame:o,onSEI:i}){try{let e=new DataView(o.data);if(xh(o)||!Uh(e))return o;let t=[],r=0,s=-1,n=-1;for(let a=0;a<o.data.byteLength;a++){let c=e.getUint8(a);if(c===0)r++;else if(c===1){if(r===2||r===3){let l=a-r;if(s===-1?s=l:n===-1&&(n=l,t.push(new sr(new DataView(e.buffer.slice(s,n)))),s=l,n=-1),!(e.getUint8(a+1)===6)){o.data=e.buffer.slice(l);break}}r=0}else r=0}i==null||i(t.reverse())}catch(e){}return o}var Hh=0,Xn=class Xn{constructor(i){this.core=i;d(this,"log");d(this,"_seiMessageList",[]);d(this,"_smallSeiMessageList",[]);d(this,"_subStreamSeiMessageList",[]);Hh++,this.log=i.log.createChild({id:`${this.getAlias()}${Hh}`}),this.log.info(`[sei] created id=${this.getAlias()}${Hh}`),this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode({frame:i,mediaType:e}){try{let t=e===8?this._smallSeiMessageList:e===2?this._subStreamSeiMessageList:this._seiMessageList;return Bh({frame:i,seiMessageList:t})}catch(t){this.log.warn(t)}return i}decode({frame:i,track:e}){return Fh({frame:i,onSEI:t=>{t.forEach(r=>{this.core.trtc.emit(x.SEI_MESSAGE,{seiPayloadType:r.seiPayloadType,data:r.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"})})}})}destroy(){this.log.debug("destroy"),this.stop(),delete this.core}getValidateRule(i){switch(i){case"start":return{type:"object"};case"update":return{type:"object"};case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:mi?this.encode:Bh,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:mi?this.decode:Fh,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update({buffer:i,options:e}){var s;let t=[e.seiPayloadType,i],r=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(t):(this._seiMessageList.push(t),r&&this._smallSeiMessageList.push(t)),(s=this.core.room.scriptTransformWorker)==null||s.postMessage({type:"sei",data:t,isMain:!e.toSubStream,small:r})}getName(){return Xn.Name}getAlias(){return"sei"}getGroup(){return"sei"}};d(Xn,"autoStart",!0),d(Xn,"Name","SEI");var Sd=Xn;function $h({frame:o,onDump:i}){return i==null||i(),o}function Wh({frame:o,onDump:i}){return i==null||i(),o}var qf={"play() error: NotAllowedError:":{tips:o=>o.includes("main <video>")||o.includes("main <audio>")?"Remote stream auto play is restricted and playback fails":"Local stream playback failure, generally only occurs in Android WeChat devices, no need to handle",color:"red",class:"red"},"updateStream() try to recover local stream":{tips:"Device acquisition exception, automatic recovery is in progress"},"updateStream() recover local stream successfully":{tips:"Device acquisition exception, automatic recovery is successful"},"updateStream() failed to recover local stream":{tips:"Device acquisition exception, automatic recovery failed"},"main stream - video track is muted":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is muted":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is muted":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unable to provide media output":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is unable to provide media output":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is unable to provide media output":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unmuted":{tips:"Received enough playback video data"},"main stream - audio track is unmuted":{tips:"Received enough playback audio data"},"auxiliary stream - video track is unmuted":{tips:"Received enough playback screen sharing data"},"main stream - audio player track is ended":{tips:"Remote audio track stopped"},"main stream - video player track is ended":{tips:"Remote video track stopped"},"auxiliary stream - video player track is ended":{tips:"Received enough playback screen sharing data"},"stream - video track is muted":{tips:"Camera capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"stream - video track is unable to provide media output":{tips:"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked, and the customer needs to re-acquire. SDK v4.11.4+ will automatically resume acquisition without customer intervention",color:"orange"},"video track is unable to provide media output":{tips:o=>o.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"stream - audio track is muted":{tips:"Microphone capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"audio track is unable to provide media output":{tips:o=>o.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"Microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio track is unable to provide media output":{tips:"The microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"is adding audio track to current published local stream":{tips:"add audio track",color:"orange"},"is removing audio track from current published local stream":{tips:"remove audio track",color:"orange"},"is removing video track from current published local stream":{tips:"remove video track",color:"orange"},"is adding video track to current published local stream":{tips:"add video track",color:"orange"},"is replacing audio track to current published local main stream":{tips:"replace audio track",color:"orange"},"is replacing video track to current published local main stream":{tips:"replace video track",color:"orange"},"downlink network quality change":{tips:"Downstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"uplink network quality change":{tips:"Upstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"localStream mute video":{tips:"mute upstream video stream",color:"orange"},"localStream unmute video":{tips:"unmute upstream video stream",color:"orange"},"localStream mute audio":{tips:"mute upstream audio stream",color:"orange"},"localStream unmute audio":{tips:"unmute upstream audio stream",color:"orange"},"black detected":{tips:"Detect black screen, which means fps = 0. It is usually caused by network, and the network will be recovered after a while. If the network is normal but has not been restored, it is an abnormal situation."},'main stream start to play with options: {"muted":true}':{tips:"Play the remote stream in silent mode. Generally, the remote stream does not need to be played in silent mode. You need to confirm whether the parameters passed in the client stream.play API call are correct.",color:"orange"},"main stream - audio player is starting playing":{tips:"Remote stream audio playback success",color:"#0dd90d",class:"success"},"main stream - video player is starting playing":{tips:"Remote stream video playback success",color:"#0dd90d",class:"success"},"video player is playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"audio player is playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"stream - video player is starting playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"stream - audio player is starting playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"switch camera success":{tips:"Switch camera success",color:"#0dd90d",class:"success"},"switch microphone success":{tips:"Switch microphone success",color:"#0dd90d",class:"success"},gotStream:{tips:"Local stream capture success"},"local stream is published successfully":{tips:"Publish success",color:"#0dd90d",class:"success"},"encoderImplementation change to OpenH264":{tips:"Use software encoding"},"encoderImplementation change to ExternalEncoder":{tips:"Use hardware encoding"},"getUserMedia with constraints":{tips:"Start media (camera/microphone) capture"},"getDisplayMedia with constraints":{tips:"Start screen sharing capture"},"client-banned":{tips:"Kicked out of the room",color:"red",class:"red",textColor:"#fff"},user_timeout:{tips:"The backend is too long without receiving SDK heartbeat, which is usually caused by the JS thread being blocked for a long time. If the reproduction probability is high, the application browser Performance tool analyzes where the JS thread is blocked.",color:"red",class:"red",textColor:"#fff"},"schedule failed":{tips:"Signaling request failed, does not affect the normal room entry process, SDK will connect to the default signaling domain."},"updateStream() video flag is true, but no camera detected, set video to false":{tips:"When trying to resume camera acquisition, the camera acquisition is not resumed because it is detected that there is no camera.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to bandwidth":{tips:"bandwidth estimation is not enough to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to cpu":{tips:"cpu load is too high to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: hidden":{tips:"User page switched to backend, in mobile devices, this will cause the device to pause the capture, and it will be restored when the user switches backend to the frontend.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: visible":{tips:"User page switched to frontend",color:"orange",class:"orange",textColor:"#fff"},"main stream - audio player is paused":{tips:`The remote stream audio playback is paused, which usually has two possibilities:
|
|
101
59
|
1. The business side passes in the div tag container for playing audio and video to be removed by the business side from the DOM.
|
|
102
60
|
2. If the user is in Chrome 70 and below, when the div container is moved, the playback will be paused.`,color:"orange",class:"orange",textColor:"#fff"},"main stream - video player is paused":{tips:`The remote stream video playback is paused, which usually has two possibilities:
|
|
103
61
|
1. The business side passes in the div tag container for playing audio and video to be removed by the business side from the DOM.
|
|
104
|
-
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(i=>{ls[`${i}()`]={tips:`Call trtc.${i}`,color:"blue",class:"blue",textColor:"#fff"}});var uy=Object.keys(ls);var _y=Li(hy());var kt="trtc_debug_dialog",ms=`${kt}_activated`,Jl=`${kt}_switch`,eg=`${kt}_mask`,Ql=`${kt}_panel`,tg=`${kt}_tabber`,Ia=`${kt}_tab`,rg=`${kt}_topbar`,mn=`${kt}_toptab`,No=`${kt}_content`,ih=`${kt}_has_topbar`,og=`${No}_log`,pn=`${No}_network`,Oo=`${kt}_dump`,ed=`${pn}_title`,od=`${pn}_basic`,Yl=`${pn}_local`,Zl=`${pn}_remote`,Kf=`${Oo}_title`,ba=`${Oo}_local`,Ki=`${Oo}_remote`,my=`${Ki}_hook`,oh=`${kt}_banner`,Ey=`${oh}_item`,py=`${kt}_toolbar`,td=`${kt}_tool`,Do=`${kt}_item`,Ty=`${Do}_debug`,yy=`${Do}_info`,Sy=`${Do}_warn`,Iy=`${Do}_error`,fy=`${kt}_back_top`,gy=`${kt}_go_bottom`,Kl=`${Oo}_local_audio`,eh=`${Oo}_local_video_main`,th=`${Oo}_local_video_aux`,rd=`${kt}_tooltip`,by=`${od}_network_info`,Ay=`${od}_room_info`,rh=`${og}_controller`,Zi="success",Aa="warning",hs="failed",sh=0,ig=class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}),this.addStyle(),this.addDialog()}addDialog(){var e;let t=document.createElement("template");t.innerHTML=`<div id="${kt}" class="${kt}"><div class="${Jl}">Debug#${++sh}</div><div class="${eg}"></div><div class="${Ql}"><div class="${tg}"><a class="${Ia} ${ms}" data-tab="log">${Ke.LOG_BUTTON}</a><a class="${Ia}" data-tab="network">${Ke.NETWORK_BUTTON}</a><a class="${Ia}" data-tab="dump">${Ke.DUMP_BUTTON}</a></div><div class="${rh}"><div data-type="back_top">${Ke.BACK_TOP}</div><div data-type="go_bottom">${Ke.GO_BOTTOM}</div><div data-type="clear_log">${Ke.CLEAR_LOG}</div></div><div class="${rg}"><a class="${mn} ${ms}" data-type="all">All</a><a class="${mn}" data-type="debug">Debug</a><a class="${mn}" data-type="info">Info</a><a class="${mn}" data-type="warn">Warn</a><a class="${mn}" data-type="error">Error</a></div><div class="${No} ${ih}"><div class="${og}"></div><div class="${pn}"><div class="${ed}">${Ke.BASIC}</div><div class="${od}"><div class="${Ay}"></div><div class="${by}">${Ke.NO_DATA}</div></div><div class="${ed}">${Ke.UPLINK}</div><div class="${Yl}">${Ke.NO_DATA}</div><div class="${ed}">${Ke.DOWNLINK}</div><div class="${Zl}">${Ke.NO_DATA}</div></div><div class="${Oo}"><div class="${Kf}">${Ke.UPLINK}</div><div class="${ba}"><div id="${Kl}"><span>${Ke.AUDIO} - ${Ke.DURATION}(s):</span><input type="number" min=0 value=0></input><button class="dump">${Ke.DUMP_BUTTON}</button><button class="end-dump" disabled>${Ke.END_BUTTON}</button></div><div id="${eh}"><span>${Ke.VIDEO} - ${Ke.DURATION}(s):</span><input type="number" min=0 value=10></input><button class="dump">${Ke.DUMP_BUTTON}</button><button class="end-dump" disabled>${Ke.END_BUTTON}</button></div><div id="${th}"><span>${Ke.SCREEN} - ${Ke.DURATION}(s):</span><input type="number" min=0 value=10></input><button class="dump">${Ke.DUMP_BUTTON}</button><button class="end-dump" disabled>${Ke.END_BUTTON}</button></div></div><div class="${Kf}">${Ke.DOWNLINK}</div><div class="${Ki}"><div class="${my}">userId:<input id="dump-remote-video-hook-userid" value='*' />duration:<input id="dump-remote-video-hook-duration" min='1' value='10' type='number' />mediaType:<select id="dump-remote-video-hook-mediaType" value='main' ><option value='main' checked>Video</option><option value='sub'>Screen</option></select><button id="dump-remote-video-hook-button">dump if video is available</button></div></div></div></div><div class="${oh}"></div><div class="${py}"><a id="trtc_upload" class="${td}">${Ke.UPLOAD_BUTTON}</a><a id="trtc_export" class="${td}">${Ke.EXPORT_BUTTON}</a><a id="trtc_hide" class="${td}">${Ke.HIDE_BUTTON}</a></div></div></div>`,(e=this.shadowRoot)==null||e.appendChild(t.content.firstChild)}addStyle(){var e;let t=document.createElement("style");t.textContent=`#${kt}{font-size:14px;--DD-BG-0:#ededed;--DD-BG-1:#f7f7f7;--DD-BG-2:#fff;--DD-BORDER:rgba(0,0,0,0.1);--DD-ERROR:red;--DD-WARN:#fa9d3b;--DD-INFO:#000;--DD-DEBUG:#10aeff;--DD-WARN-BG:#fff3cc;--DD-ERROR-BG:#ffe6e6;}#${kt} a,.${Jl}{cursor:pointer;}.${kt}{color:black;}.${Jl}{display:block;position:fixed;right:50px;bottom:${150+sh*50}px;border-radius:5px;background-color:#07c160;color:#fff;padding:5px 10px;z-index:10000;}.${eg}{display:none;position:fixed;left:0;top:0;right:0;bottom:0;z-index:10001;background-color:rgb(0,0,0,0.6);}.${Ql}{background-color:#ededed;display:none;position:fixed;min-height:85%;left:60%;right:0;bottom:0;z-index:10002;border:1px solid var(--DD-BG-0);}@media (max-width:768px) {.${Ql}{left:0;}}.${tg}{display:flex;height:2em;border-bottom:1px solid var(--DD-BORDER);}.${Ia}{padding:0 20px;border-right:1px solid rgba(0,0,0,0.1);line-height:2em;color:black;}.${Ia}.${ms}{background-color:var(--DD-BG-2);}.${Ia}.disabled{cursor:not-allowed;background-color:#ededed;color:#999;}.${rg}{height:2em;display:flex;flex-direction:row;}.${mn}{width:20%;text-align:center;line-height:2em;border-right:1px solid var(--DD-BORDER);border-bottom:1px solid var(--DD-BORDER);color:black;}.${mn}.${ms}{border-bottom:1px solid #1485ee;background-color:var(--DD-BG-2);}.${No}{background-color:#fff;position:absolute;left:0;right:0;top:2em;bottom:8em;overflow-y:scroll;overflow-x:hidden;}.${No}.${ih}{top:4em;bottom:10em}.${pn}{display:none;}.${Oo}{display:none;}.${ed},.${Kf}{line-height:2em;text-align:center;background-color:var(--DD-BG-0);border-bottom:1px solid var(--DD-BORDER);}.${od},.${Yl},.${Zl}{text-align:center;border-bottom:1px solid var(--DD-BORDER);}.${ba},.${Ki}{display:flex;flex-direction:column;padding:0.5em 0;justify-content:center;align-items:center;}.${ba} div input{margin:0 10px;height:1.5em;width:4em;}.${ba} div {padding:10px 0;border-radius:5px;}.${ba} div button,.${Ki} div button {cursor:pointer;height:1.8em;border-radius:5px;margin-right:5px;}.${ba} div button[disabled],.${Ki} div button[disabled]{cursor:not-allowed;}.${Ki} select {height:1.8em;margin:0 10px;}.${Ki} div input{margin:0 10px;height:1.5em;width:4em;}.${my} {line-height:3em;padding:0.5em;}.${ed}{text-align:center;background-color:var(--DD-BG-0);border-bottom:1px solid var(--DD-BORDER);}.${od},.${Yl},.${Zl}{text-align:center;border-bottom:1px solid var(--DD-BORDER);}.${Do}{border-bottom:1px solid var(--DD-BG-0);padding:5px 10px;overflow-wrap: break-word;}.${Iy}{color:var(--DD-ERROR);background-color:var(--DD-ERROR-BG);}.${Sy}{color:var(--DD-WARN);background-color:var(--DD-WARN-BG);}div .${yy}{color:var(--DD-INFO);}.${Ty}{color:var(--DD-DEBUG);}.${oh}{position:absolute;left:0;right:0;bottom:2em;height:6em;border-bottom:1px solid var(--DD-BORDER);display:flex;flex-direction:column;overflow-y:scroll;background-color:var(--DD-BG-1);}.${Ey}{border-bottom:1px solid var(--DD-BORDER);padding:5px 10px;overflow-wrap: break-word;}.${py}{position:absolute;line-height:2em;display:flex;flex-direction:row;left:0;right:0;bottom:0;}.${td}{flex:1;color:black;text-align:center;background-color:#ededed;border-right:1px solid var(--DD-BORDER);}#${kt} .${fy},#${kt} .${gy}{position:absolute;height:2em;width:6em;right:2em;border-radius:5px;background-color:rgba(30,136,229,0.8);z-index:10003;cursor:pointer;padding:0 5px;line-height:2em;color:white;text-align:center;}.${gy}{bottom:9em;}.${fy}{bottom:11.5em;}#${kt} .${td}.disable{cursor:not-allowed;background-color:#ededed;color:#999;}.${rd} {position:relative;display:inline-block;}.${rd} .tooltiptext{visibility:hidden;width:180px;background-color:black;color:#fff;text-align:center;padding:5px 0;border-radius:6px;position:absolute;}.${rd} .tooltip-top {bottom:125%;left:50%;margin-left:-90px;}.${rd}:hover .tooltiptext{visibility:visible;}.${rh}{position:absolute;left:0;right:0;bottom:8em;height:2em;display:flex;align-items:center;}.${rh} div{flex:1;cursor:pointer;border-right:1px solid var(--DD-BORDER);text-align: center;}`,(e=this.shadowRoot)==null||e.appendChild(t)}};customElements.define("trtc-basic-debug-dialog",ig);var id=class{constructor(t,e,r,o,s,n){p(this,"_dialogNode",null);p(this,"_switchNode",null);p(this,"_maskNode",null);p(this,"_panelNode",null);p(this,"_logContentNode",null);p(this,"_networkContentNode",null);p(this,"_dumpContentNode",null);p(this,"_tabNodes",[]);p(this,"_toptabNodes",[]);p(this,"_hasMove",!1);p(this,"_showDialog",!1);p(this,"_isMobile",!1);p(this,"_showLogType","all");p(this,"prevBytesSent",0);p(this,"prevBytesReceived",0);p(this,"_core");p(this,"_log");p(this,"_logList",[]);p(this,"isUploading",!1);p(this,"publishMap",new Map);p(this,"dumpLocalVideoMap");p(this,"dumpRemoteVideoMap");p(this,"dumpLocalAudioMap");p(this,"dumpRemoteAudioMap");p(this,"eventMap",new Map);p(this,"switchPos",{x:0,y:0,startX:0,startY:0,endX:0,endY:0,isTouchEnd:!1});p(this,"handleLeaveSuccess",({room:t})=>{var r,o;if(!this.hitTest(t))return;let e=(o=(r=this._dialogNode)==null?void 0:r.shadowRoot)==null?void 0:o.querySelector(`.${Ki}`);for(let s of this.publishMap.values())e==null||e.removeChild(s);this.publishMap.clear()});p(this,"handleJoinSuccess",({room:t})=>{var r,o;if(!this.hitTest(t))return;let e=(o=(r=this._dialogNode)==null?void 0:r.shadowRoot)==null?void 0:o.querySelector(`.${Ay}`);e.innerHTML=`sdkAppId: ${t.sdkAppId}<br/>roomId: ${t.roomId}<br/>userId: ${t.userId}<br/>`});p(this,"handleRemoteVideoAvailable",t=>{let e=t.streamType==="sub"?"auxiliary":"main";this.renderDumpTab(t.userId,"remote",e,"publish")});p(this,"handleRemoteVideoUnavailable",t=>{let e=t.streamType==="sub"?"auxiliary":"main";this.renderDumpTab(t.userId,"remote",e,"unpublish")});p(this,"handleRemoteAudioAvailable",t=>{this.renderDumpTab(t.userId,"remote","audio","publish")});p(this,"handleRemoteAudioUnavailable",t=>{this.renderDumpTab(t.userId,"remote","audio","unpublish")});p(this,"renderDumpTab",(t,e,r,o)=>{var a,c,d;let s={main:"video",auxiliary:"screen",audio:"audio"},n=(m,l)=>{var M,w,H;let f=document.createElement("div");f.innerText=`${m} - ${s[l]} - ${Ke.DURATION}(s):`;let g=document.createElement("input");g.type="number",g.min="0",g.value="10",g.id=`dump_remote_${l}_${m}`;let T=document.createElement("button");T.innerText=Ke.END_BUTTON,T.disabled=!0;let E=document.createElement("button");E.innerText=Ke.DUMP_BUTTON,E.onclick=()=>{let B,P,$=Number(g.value);if(l==="audio")({download:B,onDumpEnd:P}=new URLSearchParams(location.search).get("dump_audio_before_codec")==="true"?this.dumpAudioFromPipeline("remote",$,m):this.dumpAudio("remote",$,m));else{if(!this.isSupportDumpVideo())return;({download:B,onDumpEnd:P}=this.dumpVideo(l,"remote",$,m))}B&&(this.inactiveButton(E,Ke.DUMPING_BUTTON),$>0?setTimeout(()=>{B==null||B(),this.activeButton(E,Ke.DUMP_BUTTON)},$*1e3):(this.activeButton(T),T.onclick=()=>{T.onclick=null,B==null||B(),P==null||P(),this.activeButton(E,Ke.DUMP_BUTTON),this.inactiveButton(T)}))};let y;if(l!=="audio"){y=document.createElement("button"),y.innerText="preview",y.style.whiteSpace="pre";let B=document.createElement("video");document.body.appendChild(B),B.id=`${kt}_preview_remote_${l}_${m}`,B.style.cssText=`
|
|
105
|
-
|
|
106
|
-
height: 240px;
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
transform: translate(-50%, -50%);
|
|
113
|
-
z-index: 10004;
|
|
114
|
-
`,y.onclick=()=>D(this,null,function*(){var P;if(B.style.display=B.style.display==="none"?"":"none",y&&(y.innerText=B.style.display==="none"?"preview":" hide "),!B.srcObject){let $=this._core.room.remotePublishedUserMap.get(m);if($){let de=(P=$[l==="main"?"remoteVideoTrack":"remoteAuxiliaryTrack"])==null?void 0:P.mediaTrack;de?(B.srcObject=new MediaStream([de]),yield B.play()):this.addInfoToBanner(hs,"failed to preview, remote video track is not available")}}})}f.appendChild(g),f.appendChild(E),f.appendChild(T),y&&f.appendChild(y),f.style.cssText="padding:10px;";let v=document.createElement("div");return v.style.cssText="width:100%;display:flex;justify-content:center;border-top: 1px solid var(--DD-BORDER);",v.appendChild(f),(H=(w=(M=this._dialogNode)==null?void 0:M.shadowRoot)==null?void 0:w.querySelector(`.${Ki}`))==null||H.appendChild(v),v};if(e==="remote")if(o==="publish"){let m=n(t,r);this.publishMap.set(`${t}-${e}-${r}`,m)}else{let m=this.publishMap.get(`${t}-${e}-${r}`);if(!m)return;(d=(c=(a=this._dialogNode)==null?void 0:a.shadowRoot)==null?void 0:c.querySelector(`.${Ki}`))==null||d.removeChild(m);let l=document.querySelector(`#${kt}_preview_remote_${r}_${t}`);l&&document.body.removeChild(l),this.publishMap.delete(`${t}-${e}-${r}`)}});p(this,"handleStatistics",t=>{var d,m,l,f,g,T;let e=(t.bytesSent-this.prevBytesSent)/2,r=(t.bytesReceived-this.prevBytesReceived)/2;this.prevBytesSent=t.bytesSent,this.prevBytesReceived=t.bytesReceived;let o=(m=(d=this._dialogNode)==null?void 0:d.shadowRoot)==null?void 0:m.querySelector(`.${by}`);o.innerHTML=`rtt: ${t.rtt} ms upLoss: ${t.upLoss}% downLoss: ${t.downLoss}% <br>
|
|
115
|
-
\u2191 ${e/1e3} KB/s (${8*e/1e3} Kb/s) <br>
|
|
116
|
-
\u2193 ${r/1e3} KB/s (${8*r/1e3} Kb/s) <br>
|
|
117
|
-
`;let s=(f=(l=this._dialogNode)==null?void 0:l.shadowRoot)==null?void 0:f.querySelector(`.${Yl}`),n="";t.localStatistics.audio.bitrate&&(n=`<li>local audio: ${t.localStatistics.audio.bitrate} Kb/s audioLevel: ${t.localStatistics.audio.audioLevel.toFixed(5)}</li>`),t.localStatistics.video.length>0&&(n+=`${t.localStatistics.video.map(E=>`<li>local ${E.videoType} video: ${E.bitrate} Kb/s ${E.width}*${E.height} ${E.frameRate}fps</li>`).join("")}`),s.innerHTML=n===""?`${Ke.NO_DATA}`:n;let a=(T=(g=this._dialogNode)==null?void 0:g.shadowRoot)==null?void 0:T.querySelector(`.${Zl}`),c="";t.remoteStatistics.length>0&&t.remoteStatistics.forEach(E=>{let y=`remote ${E.userId}:`;E.audio.bitrate>0&&(y+=`<li>audio: ${E.audio.bitrate} Kb/s audioLevel: ${E.audio.audioLevel.toFixed(5)}</li>`),E.video.length>0&&E.video.forEach(v=>{y+=`<li>${v.videoType} video: ${v.bitrate} Kb/s ${v.width}*${v.height} ${v.frameRate}fps</li>`}),c+=y}),a.innerHTML=c===""?`${Ke.NO_DATA}`:c});p(this,"pad",t=>t<10?`0${t}`:`${t}`);this._core=t,this._log=e,this.dumpLocalVideoMap=r,this.dumpRemoteVideoMap=o,this.dumpLocalAudioMap=s,this.dumpRemoteAudioMap=n,this.initCustomElements(),this.synchronizeLog(),this.installEvents(),window[`__trtc_instance_${sh}__`]=this._core.trtc}initCustomElements(){this._isMobile=cy();let t=document.createElement("trtc-basic-debug-dialog");document.body.appendChild(t);let e=t.shadowRoot;if(this._dialogNode=t,!e)return;this._switchNode=e.querySelector(`.${Jl}`),this._addEventListener(this._switchNode,"click",this.onSwitchClick.bind(this));let r=getComputedStyle(this._switchNode);this.switchPos.x=parseInt(r.right,10)||50,this.switchPos.y=parseInt(r.bottom,10)||100+sh*50,this._isMobile?(this._switchNode.ontouchstart=this.onTouchStart.bind(this),this._switchNode.ontouchend=this.onTouchEnd.bind(this),this._switchNode.ontouchmove=this.onTouchMove.bind(this)):this._switchNode.onmousedown=this.onMouseDown.bind(this),this._maskNode=e.querySelector(`.${eg}`),this._addEventListener(this._maskNode,"click",this.onMaskClick.bind(this)),this._panelNode=e.querySelector(`.${Ql}`),e.querySelector(`.${rh}`).childNodes.forEach(w=>{switch(w.getAttribute("data-type")){case"go_bottom":this._addEventListener(w,"click",this.onGoBottomClick.bind(this));break;case"back_top":this._addEventListener(w,"click",this.onBackTopClick.bind(this));break;case"clear_log":this._addEventListener(w,"click",this.onClearLogClick.bind(this));break}}),this._logContentNode=e.querySelector(`.${og}`),this._networkContentNode=e.querySelector(`.${pn}`),this._dumpContentNode=e.querySelector(`.${Oo}`),this._tabNodes=Array.from(e.querySelector(`.${tg}`).children),this._tabNodes.forEach(w=>{this._addEventListener(w,"click",this.onTabClick.bind(this))}),this._toptabNodes=Array.from(e.querySelector(`.${rg}`).children),this._toptabNodes.forEach(w=>{this._addEventListener(w,"click",this.onToptabClick.bind(this))});let s=e.querySelector("#trtc_upload");this._addEventListener(s,"click",this.onUploadClick.bind(this));let n=e.querySelector("#trtc_export");this._addEventListener(n,"click",this.onExportClick.bind(this));let a=e.querySelector("#trtc_hide");this._addEventListener(a,"click",this.onHideClick.bind(this));let c=e.querySelector(`#${eh} .dump`),d=e.querySelector(`#${eh} .end-dump`),m=Number(e.querySelector(`#${eh} input`).value);this._addEventListener(c,"click",this.getDumpButtonClickHandler.bind(this,c,d,m,"main","local"));let l=e.querySelector(`#${th} .dump`),f=e.querySelector(`#${th} .end-dump`),g=Number(e.querySelector(`#${th} input`).value);this._addEventListener(l,"click",this.getDumpButtonClickHandler.bind(this,l,f,g,"auxiliary","local"));let T=e.querySelector(`#${Kl} button`);this._addEventListener(T,"click",()=>{let w=Number(e.querySelector(`#${Kl} input`).value),{download:H,onDumpEnd:B}=new URLSearchParams(location.search).get("dump_audio_from_pipeline")==="true"?this.dumpAudioFromPipeline("local",w):this.dumpAudio("local",w);if(!H){this.addInfoToBanner(hs,"Failed to dump, please check if the current user has started the audio");return}if(this.inactiveButton(T,Ke.DUMPING_BUTTON),w>0)setTimeout(()=>{H(),this.activeButton(T,Ke.DUMP_BUTTON)},w*1e3);else{let P=e.querySelector(`#${Kl} .end-dump`);this.activeButton(P),P.onclick=()=>{P.onclick=null,H(),B==null||B(),this.activeButton(T,Ke.DUMP_BUTTON),this.inactiveButton(P)}}});let E=e.querySelector("#dump-remote-video-hook-userid"),y=e.querySelector("#dump-remote-video-hook-duration"),v=e.querySelector("#dump-remote-video-hook-mediaType"),M=e.querySelector("#dump-remote-video-hook-button");M.onclick=()=>{let w=Number(y.value);if(w<1){this.addInfoToBanner(hs,"duration at least 1s");return}let H=E.value;if(!H){this.addInfoToBanner(hs,"please input user id");return}H==="*"&&this.inactiveButton(M);let B=v.value,P=`remote_${H}_${B==="sub"?"auxiliary":B}`,$,de,Ae=L=>{if((L.userId===H||H==="*")&&L.streamType===B){if(this.addInfoToBanner(Zi,`[${L.userId}_${B}] starting to dump video, duration: ${w}s`),{download:$,onDumpEnd:de}=this.dumpVideo(L.streamType==="sub"?"auxiliary":L.streamType,"remote",w,L.userId),!$)return;setTimeout(()=>{$==null||$(),de==null||de(),H!=="*"&&this._core.trtc.off(this._core.TRTC.EVENT.REMOTE_VIDEO_AVAILABLE,Ae)},w*1e3)}};this._core.trtc.on(this._core.TRTC.EVENT.REMOTE_VIDEO_AVAILABLE,Ae),this.addInfoToBanner(Zi,`[${P}] waiting to dump video from ${H==="*"?"all remote users":`user ${H}`}, duration: ${w}s`)}}synchronizeLog(){this._core.loggerManager.getQueue().forEach(e=>{this.updateLog(e)})}isSupportDumpVideo(){return!this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED&&!this._core.rtcDectection.IS_SCRIPT_TRANSFORM_SUPPORTED?(this.addInfoToBanner(hs,"Current browser does not support dumping video"),!1):!0}_addEventListener(t,e,r,o){t&&(t.addEventListener(e,r,o),this.eventMap.set(t,{type:e,listener:r}))}_removeEventListener(){this.eventMap.forEach(({type:t,listener:e},r)=>{r&&r.removeEventListener(t,e)}),this.eventMap.clear(),this._switchNode&&(this._switchNode.onmousedown=null,this._switchNode.ontouchmove=null,this._switchNode.ontouchstart=null,this._switchNode.ontouchend=null)}closeDialog(){this.uninstallEvents(),this._removeEventListener(),this._dialogNode&&(document.body.removeChild(this._dialogNode),this._dialogNode=null)}updateLog(t){var r;this._logList.push(t);let e=document.createElement("div");switch(e.classList.add(Do),t.level){case 4:e.classList.add(Iy);break;case 2:e.classList.add(yy);break;case 3:e.classList.add(Sy);break;case 1:e.classList.add(Ty);break;default:break}e.textContent=t.log,this._showLogType!=="all"&&!e.classList.contains(`${Do}_${this._showLogType}`)&&(e.style.display="none"),(r=this._logContentNode)==null||r.appendChild(e),this.addHelper(e)}getDumpButtonClickHandler(t,e,r,o,s){if(!this.isSupportDumpVideo())return;let{download:n,onDumpEnd:a}=this.dumpVideo(o,s,r);if(n){this.addInfoToBanner(Zi,`[${s}_${o}] starting to dump...`),this.inactiveButton(t,Ke.DUMPING_BUTTON),r>0?setTimeout(()=>{n(),this.activeButton(t,Ke.DUMP_BUTTON)},r*1e3):(this.activeButton(e),e.onclick=()=>{e.onclick=null,a==null||a(),n(),this.activeButton(t,Ke.DUMP_BUTTON),this.inactiveButton(e)});return}this.addInfoToBanner(Zi,`[${s}_${o}] waiting to dump...`);let c=({track:d})=>{if(d.room===this._core.room&&d.streamType===o){this.addInfoToBanner(Zi,`[${s}_${o}] starting to dump`),s==="local"&&this._core.innerEmitter.off("104",c);let{download:m,onDumpEnd:l}=this.dumpVideo(o,s,r);if(!m)return;r>0?setTimeout(()=>{m(),this.activeButton(t,Ke.DUMP_BUTTON)},r*1e3):(this.activeButton(e),e.onclick=()=>{e.onclick=null,l==null||l(),m(),this.activeButton(t,Ke.DUMP_BUTTON),this.inactiveButton(e)})}};c.bind(this),s==="local"&&this._core.innerEmitter.on("104",c),this.inactiveButton(t,Ke.DUMPING_BUTTON)}onSwitchClick(){if(this._hasMove){this._hasMove=!1;return}this._showDialog?this.hideDialog():(this._isMobile&&(this._maskNode.style.display="block"),this._panelNode.style.display="block",this._switchNode.style.display="none",this._showDialog=!0,this.logContentGoBottom())}onTabClick(t){var o,s,n,a,c,d,m;let e=t.target;(o=this._tabNodes)==null||o.forEach(l=>{l.classList.remove(ms)}),e.classList.add(ms);let r=e.getAttribute("data-tab");r==="log"?((a=(n=(s=this._dialogNode)==null?void 0:s.shadowRoot)==null?void 0:n.querySelector(`.${No}`))==null||a.classList.add(ih),this._logContentNode.style.display="block",this._networkContentNode.style.display="none",this._dumpContentNode.style.display="none",this.logContentGoBottom()):((m=(d=(c=this._dialogNode)==null?void 0:c.shadowRoot)==null?void 0:d.querySelector(`.${No}`))==null||m.classList.remove(ih),r==="network"?(this._networkContentNode.style.display="block",this._logContentNode.style.display="none",this._dumpContentNode.style.display="none"):r==="dump"&&(this._dumpContentNode.style.display="block",this._networkContentNode.style.display="none",this._logContentNode.style.display="none"))}onToptabClick(t){var s,n;let e=t.target;(s=this._toptabNodes)==null||s.forEach(a=>{a.classList.remove(ms)}),e.classList.add(ms),this._showLogType=e.getAttribute("data-type");let r=(n=this._logContentNode)==null?void 0:n.querySelectorAll(`.${Do}`),o=`${Do}_${this._showLogType}`;r.forEach(a=>{a.classList.contains(o)||this._showLogType==="all"?a.style.display="block":a.style.display="none"}),this.logContentGoBottom()}onExportClick(){let t=this._logList.reduce((n,a)=>`${n+a.log}
|
|
118
|
-
`,""),e=new Blob([t],{type:"text/plain"}),r=document.createElement("a"),o=URL.createObjectURL(e);r.href=o;let s=`trtc_${this._core.room.sdkAppId===void 0?"EmptySdkAppId":this._core.room.sdkAppId}_${this._core.room.userId===void 0?"EmptyUserId":this._core.room.userId}_${this.formatStartDumpTime(+new Date)}.log`;r.download=s,r.style.display="none",document.body.appendChild(r),r.click(),URL.revokeObjectURL(o),document.body.removeChild(r),this.addInfoToBanner(Zi,`Export success: The log file name is ${s}`),this._core.kvStatManager.addSuccessEvent({key:592703})}addInfoToBanner(t,e){var n,a;let r=(a=(n=this._dialogNode)==null?void 0:n.shadowRoot)==null?void 0:a.querySelector(`.${oh}`),o=document.createElement("div");o.classList.add(Ey);let s=t===Zi?"\u{1F7E9}":t===Aa?"\u{1F7E7}":"\u{1F7E5}";o.innerText=`${s} [${this.getCurrentTime()}] ${e}`,r.appendChild(o),r.scrollTop=r.scrollHeight}onUploadClick(){return D(this,null,function*(){var a,c;if(this.isUploading)return;this.isUploading=!0;let t=(c=(a=this._dialogNode)==null?void 0:a.shadowRoot)==null?void 0:c.querySelector("#trtc_upload");t.innerText="Uploading...",t==null||t.classList.add(".disable");let e=this._logList.reduce((d,m)=>`${d+m.log}
|
|
119
|
-
`,""),r=new Blob([e],{type:"text/plain"}),o=new FormData;o.append("file",r,"trtc.log"),o.append("sdkAppId",`${this._core.room.sdkAppId||"EmptySdkAppId"}`),o.append("userId",`${this._core.room.userId||"EmptyUserId"}`),fetch("https://service.trtc.qcloud.com/api/uploadLogFile",{method:"POST",body:o}).then(d=>d.json()).then(d=>{this.addInfoToBanner(d.type,d.message_en||"Upload Failed: Please use local export"),this.isUploading=!1,this._log.info(d.message_en),this._core.kvStatManager.addSuccessEvent({key:592704})}).catch(()=>{this.addInfoToBanner(hs,"Upload Failed: Please use local export"),this._log.info("Upload Failed: Please use local export"),this._core.kvStatManager.addFailedEvent({key:592704})}).finally(()=>{t.innerText=Ke.UPLOAD_BUTTON,t==null||t.classList.remove(".disable"),this.isUploading=!1})})}onHideClick(){this.hideDialog()}onMaskClick(){this.hideDialog()}hideDialog(){this._isMobile&&(this._maskNode.style.display="none"),this._panelNode.style.display="none",this._switchNode.style.display="block",this._showDialog=!1}onBackTopClick(){var t,e,r;(r=(e=(t=this._dialogNode)==null?void 0:t.shadowRoot)==null?void 0:e.querySelector(`.${No}`))==null||r.scrollTo(0,0)}onGoBottomClick(){this.logContentGoBottom()}onClearLogClick(){this._logList=[],this._logContentNode&&(this._logContentNode.innerHTML="")}logContentGoBottom(){var e,r;let t=(r=(e=this._dialogNode)==null?void 0:e.shadowRoot)==null?void 0:r.querySelector(`.${No}`);t==null||t.scrollTo(0,t==null?void 0:t.scrollHeight)}onMouseDown(t){t.preventDefault(),this.switchPos.startX=t.pageX,this.switchPos.startY=t.pageY,document.onmousemove=this.onMouseMove.bind(this),document.onmouseup=this.onMouseUp.bind(this)}onMouseMove(t){t.cancelable&&t.preventDefault(),this._hasMove=!0;let e=this.switchPos.x-(t.pageX-this.switchPos.startX),r=this.switchPos.y-(t.pageY-this.switchPos.startY);[e,r]=this.getSafeAreaXY(e,r),this._switchNode.style.right=`${e}px`,this._switchNode.style.bottom=`${r}px`,this.switchPos.endX=e,this.switchPos.endY=r}onMouseUp(){this.switchPos.startX=0,this.switchPos.startY=0,this.switchPos.x=this.switchPos.endX,this.switchPos.y=this.switchPos.endY,document.onmousemove=null,document.onmouseup=null}onTouchStart(t){this.switchPos.startX=t.touches[0].pageX,this.switchPos.startY=t.touches[0].pageY,this.switchPos.isTouchEnd=!1}onTouchEnd(){this.switchPos.isTouchEnd&&(this.switchPos.startX=0,this.switchPos.startY=0,this.switchPos.isTouchEnd=!1,this.switchPos.x=this.switchPos.endX,this.switchPos.y=this.switchPos.endY)}onTouchMove(t){if(t.touches.length<=0)return;let e=t.touches[0].pageX-this.switchPos.startX,r=t.touches[0].pageY-this.switchPos.startY,o=Math.floor(this.switchPos.x-e),s=Math.floor(this.switchPos.y-r);[o,s]=this.getSafeAreaXY(o,s),this._switchNode.style.right=`${o}px`,this._switchNode.style.bottom=`${s}px`,this.switchPos.endX=o,this.switchPos.endY=s,this.switchPos.isTouchEnd=!0,t.cancelable&&t.preventDefault()}getSafeAreaXY(t,e){let r=Math.max(document.documentElement.offsetWidth,window.innerWidth),o=Math.max(document.documentElement.offsetHeight,window.innerHeight);return t+this._switchNode.offsetWidth>r&&(t=r-this._switchNode.offsetWidth),e+this._switchNode.offsetHeight>o&&(e=o-this._switchNode.offsetHeight),t<0&&(t=0),e<20&&(e=20),[t,e]}hitTest(t){return t===this._core.room}installEvents(){this._core.innerEmitter.on("264",this.handleLog,this),this._core.innerEmitter.on("53",this.handleLeaveSuccess,this),this._core.innerEmitter.on("27",this.handleJoinSuccess,this),this._core.trtc.on(this._core.TRTC.EVENT.STATISTICS,this.handleStatistics,this),this._core.trtc.on(this._core.TRTC.EVENT.REMOTE_AUDIO_AVAILABLE,this.handleRemoteAudioAvailable),this._core.trtc.on(this._core.TRTC.EVENT.REMOTE_AUDIO_UNAVAILABLE,this.handleRemoteAudioUnavailable),this._core.trtc.on(this._core.TRTC.EVENT.REMOTE_VIDEO_AVAILABLE,this.handleRemoteVideoAvailable),this._core.trtc.on(this._core.TRTC.EVENT.REMOTE_VIDEO_UNAVAILABLE,this.handleRemoteVideoUnavailable),this._core.room.on("dump",this.handleDumpFromScriptTransform,this)}uninstallEvents(){this._core.innerEmitter.off("264",this.handleLog,this),this._core.innerEmitter.off("53",this.handleLeaveSuccess,this),this._core.innerEmitter.off("27",this.handleJoinSuccess,this),this._core.trtc.off(this._core.TRTC.EVENT.STATISTICS,this.handleStatistics,this),this._core.trtc.off(this._core.TRTC.EVENT.REMOTE_AUDIO_AVAILABLE,this.handleRemoteAudioAvailable),this._core.trtc.off(this._core.TRTC.EVENT.REMOTE_AUDIO_UNAVAILABLE,this.handleRemoteAudioUnavailable),this._core.trtc.off(this._core.TRTC.EVENT.REMOTE_VIDEO_AVAILABLE,this.handleRemoteVideoAvailable),this._core.trtc.off(this._core.TRTC.EVENT.REMOTE_VIDEO_UNAVAILABLE,this.handleRemoteVideoUnavailable),this._core.room.off("dump",this.handleDumpFromScriptTransform,this)}handleDumpFromScriptTransform(t){if(!t.isAudio)if(t.userId){let e=this.dumpRemoteVideoMap[`${t.userId}-${t.streamType}`];e&&(e.data.push(t.data),e.duration>0&&Date.now()-e.startTimestamp>e.duration*1e3&&e.onDumpEnd())}else{let e=t.streamType==="main"?"main":"sub",r=this.dumpLocalVideoMap[e];r&&(r.data.push(t.data),r.duration>0&&Date.now()-r.startTimestamp>r.duration*1e3&&r.onDumpEnd())}}inactiveButton(t,e){t.disabled=!0,e&&(t.innerText=e)}activeButton(t,e){t.disabled=!1,e&&(t.innerText=e)}handleLog(t){this.updateLog(t.log)}addHelper(t){let e=/((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}/g,r=uy,o=t.innerText;o=o.split(`
|
|
120
|
-
`).map(s=>{if(s=s.replace(/</g,"<").replace(/>/g,">"),s.includes("failed"))return s.includes("on autoplay-failed")?s:`<span class='red' style="background:red; color:#fff;">${s}</span>`;if(s.includes("clientIp:")){let n=s.match(e);return n==null||n.forEach(a=>{s=s.replace(a,`<a href="javascript:void(0);" target=""><span class='ip' style="background:#e1dfdf">${a}</span></a>`)}),s}return s.includes("URL of current page")&&(s=s.replace(/URL of current page: (.+)/,'URL of current page: <a href="$1">$1</a>')),s}).join(`
|
|
121
|
-
`),r.forEach(s=>{if(t.innerText.includes(s)){let n="";n=typeof ls[s].tips=="function"?ls[s].tips(t.innerText):ls[s].tips,o=o.replace(new RegExp(`${dy(s)}`,"gi"),`<span class="${rd}" style="background:${ls[s].color||"#e1dfdf"}; color: ${ls[s].textColor||"#000"}">${s}
|
|
122
|
-
<span class="tooltiptext tooltip-top">${n}</span>
|
|
123
|
-
</span>`)}}),t.innerHTML=o}getCurrentTime(){let t=new Date,e=this.pad(t.getHours()),r=this.pad(t.getMinutes()),o=this.pad(t.getSeconds());return`${e}:${r}:${o}`}dumpAudioFromPipeline(t,e,r){this.addInfoToBanner(Aa,"dump audio from pipeline");let o=Date.now(),s=this.formatStartDumpTime(o),n=[],a=`${t}_${r}`,c;if(t==="local")c=this._core.trtc._localAudioTrack;else if(r){let l=this._core.room.remotePublishedUserMap.get(r);l&&(c=l.remoteAudioTrack)}let d=()=>{var v,M;if(n.length===0){this.addInfoToBanner(hs,`[${a}] dump failed. Reason: data is empty`);return}let l=(t==="local"?(v=this._core.room.singlePC)==null?void 0:v.audioCodec:(M=this._core.room.userManager)==null?void 0:M.getPublishedUser(r).audioCodec)||"opus",f,g=l;l==="opus"?(this.addInfoToBanner(Aa,`[${a}] package opus to ogg`),f=this.convertOpusToOgg(n),g="ogg"):f=new Blob(n);let T=URL.createObjectURL(f),E=document.createElement("a"),y=t==="local"?`local_${s}.${g}`:`remote-${r}_${s}.${g}`;E.href=T,E.download=y,E.style.display="none",document.body.appendChild(E),E.click(),URL.revokeObjectURL(T),E.remove(),this.addInfoToBanner(Zi,`[${a}] dump success. File name is: ${y}`)},m;if(t==="local"){if(!this.hasLocalTrack("main","audio"))return{};m=()=>{delete this.dumpLocalAudioMap.main},this.dumpLocalAudioMap.main={startTimestamp:o,data:n,duration:e,onDumpEnd:m}}if(t==="remote"&&r){if(m=()=>{delete this.dumpRemoteAudioMap[`${r}`]},this.dumpRemoteAudioMap[`${r}`])return this.addInfoToBanner(Aa,`[${a}] dump already exists.`),{};this.dumpRemoteAudioMap[`${r}`]={startTimestamp:o,data:n,duration:e,onDumpEnd:m}}return{download:d,onDumpEnd:m}}dumpVideo(t,e,r,o){let s=Date.now(),n=this.formatStartDumpTime(s),a=[],c=`${e}_${o}_${t}`,d;if(e==="local")d=t==="main"?this._core.trtc._localVideoTrack:this._core.trtc._localScreenTrack;else if(o){let f=this._core.room.remotePublishedUserMap.get(o);f&&(d=t==="main"?f.remoteVideoTrack:f.remoteAuxiliaryTrack)}let m=()=>{var v,M;if(a.length===0){this.addInfoToBanner(hs,`[${c}] dump failed. Reason: data is empty`);return}let f;t==="main"?f="video":t==="auxiliary"&&(f="screen");let g;this.getVideoCodec(o||"")==="vp8"?(this.addInfoToBanner(Aa,`[${c}] package vp8 into ivf format`),g=this.convertVP8ToIVF(a,d)):g=new Blob(a);let T=URL.createObjectURL(g),E=document.createElement("a"),y=e==="local"?`local_${f}_${n}.${((v=this._core.room.singlePC)==null?void 0:v.videoCodec)||"h264"}`:`remote-${o}_${f}_${n}.${((M=this._core.room.userManager)==null?void 0:M.getPublishedUser(o).videoCodec)||"h264"}`;E.href=T,E.download=y,E.style.display="none",document.body.appendChild(E),E.click(),URL.revokeObjectURL(T),E.remove(),this.addInfoToBanner(Zi,`[${c}] dump success. File name is: ${y}`)},l;if(e==="local"){if(!this.hasLocalTrack(t,"video"))return{};l=()=>{delete this.dumpLocalVideoMap[t==="auxiliary"?"sub":"main"]},this.dumpLocalVideoMap[t==="auxiliary"?"sub":"main"]={startTimestamp:s,data:a,duration:r,onDumpEnd:l}}if(e==="remote"&&o){if(l=()=>{delete this.dumpRemoteVideoMap[`${o}-${t}`]},this.dumpRemoteVideoMap[`${o}-${t}`])return this.addInfoToBanner(Aa,`[${c}] dump already exists.`),{};this.dumpRemoteVideoMap[`${o}-${t}`]={startTimestamp:s,data:a,duration:r,onDumpEnd:l}}return{download:m,onDumpEnd:l}}convertVP8ToIVF(t,e){var m,l,f;function r(g,T,E){for(let y=0;y<E.length;y++)g.setUint8(T+y,E.charCodeAt(y))}let o=t.reduce((g,T)=>g+12+T.byteLength,32),s=new ArrayBuffer(o),n=new DataView(s),a=new Uint8Array(s),c=0;r(n,c,"DKIF"),c+=4,n.setUint16(c,0,!0),c+=2,n.setUint16(c,32,!0),c+=2,r(n,c,"VP80"),c+=4,n.setUint16(c,((m=e==null?void 0:e._inputTrack)==null?void 0:m.getSettings().width)||0,!0),c+=2,n.setUint16(c,((l=e==null?void 0:e._inputTrack)==null?void 0:l.getSettings().height)||0,!0),c+=2;let d=(e instanceof qi?e==null?void 0:e.decodeFPS:(f=e==null?void 0:e.mediaTrack)==null?void 0:f.getSettings().frameRate)||15;return n.setUint32(c,d,!0),c+=4,n.setUint32(c,1,!0),c+=4,n.setUint32(c,t.length,!0),c+=4,n.setUint32(c,0,!0),c+=4,t.forEach((g,T)=>{let E=g.byteLength,y=Math.floor(T*1e6/d);n.setUint32(c,E,!0),c+=4,n.setFloat64(c,y,!0),c+=8,a.set(new Uint8Array(g),c),c+=E}),new Blob([s],{type:"application/octet-stream"})}getVideoCodec(t){var e,r;return t===""?(e=this._core.room.singlePC)==null?void 0:e.videoCodec:(r=this._core.room.remotePublishedUserMap.get(t))==null?void 0:r.videoCodec}hasLocalTrack(t,e){for(let r of this._core.room.localTracks)if(r.streamType===t&&r.kind===e)return!0;return!1}dumpAudio(t,e,r){var B,P,$;let o=null,s=[],n=[],a=[],c=[],d=[],m=[],l=[],f=new AbortController,g=Date.now(),T=this.formatStartDumpTime(g),E=this._core.room.audioManager._localAudioPipline,y=this._core.room.audioManager._localScreenAudioPipeline,v,M,w=({room:de,data:Ae,type:L})=>{if(this.hitTest(de)){if(L==="dump"){if(c[0]=c[0]?c[0].concat(Ae.captureInput):Ae.captureInput,c[1]=c[1]?c[1].concat(Ae.playInput):Ae.playInput,!v)v=Ae.startTime,M=Ae.startTime;else{let A=Ae.startTime-v,le=Ae.endTime-Ae.startTime;if(A>30||le>30){let ze=function(me){if(typeof me!="number"||me<0)return"0\u6BEB\u79D2";let re=[],Q=Math.floor(me/6e4),q=me%6e4;Q>0&&re.push(`${Q}\u5206`);let Be=Math.floor(q/1e3);return q%=1e3,(Be>0||re.length)&&re.push(`${Be}\u79D2`),(q>0||!re.length)&&re.push(`${q}\u6BEB\u79D2`),re.join("")};var te=ze;let He=Ae.startTime-M,ge=v-M;l.push(`${Ae.startTime} ${ze(He)}~${ze(ge)} ${A} ${le}`)}v=Ae.startTime}m.push(Ae.startTime)}L==="dump-screen-audio"&&(d[0]=d[0]?d[0].concat(Ae.captureInput):Ae.captureInput,d[1]=d[1]?d[1].concat(Ae.playInput):Ae.playInput)}};if(t==="local"){let{sampleRate:de}=this._core.room.audioManager.audioContext;if(!this._core.room.audioManager.hasAudioTrack&&!this._core.room.audioManager.hasScreenAudioTrack)return{};if(E!=null&&E.source.node&&(s.push(E.source.node),n.push(`local_audio_raw_capture-${de}-${E.source.node.channelCount}`)),((B=E==null?void 0:E.aec)!=null&&B.node||y!=null&&y.aec.node)&&(this._core.trtc.updatePlugin("AudioProcessor",{enableDump:!0}),this._core.innerEmitter.on("265",w),(P=E==null?void 0:E.aec)!=null&&P.node&&(s.push(E.aec.node),n.push(`local_audio_audioProcessor_processed-${de}-${E.aec.node.channelCount}`)),y!=null&&y.aec.node&&(s.push(y.aec.node),n.push(`screen_audio_audioProcessor_processed-${de}-${y.aec.node.channelCount}`))),E!=null&&E.denoiser.node&&(s.push(E.denoiser.node),n.push(`local_audio_denoiser_processed-${de}-${E.denoiser.node.channelCount}`)),this._core.room.audioManager.mixWeight>1&&(E!=null&&E.stream)){let Ae=this._core.room.audioManager.audioContext.createMediaStreamSource(E.stream);Ae.channelCount=1,s.push(Ae),n.push(`local_audio_destination-${de}-${Ae.channelCount}`)}}else if(t==="remote"&&r!==void 0){let de=($=this._core.room.remotePublishedUserMap.get(r))==null?void 0:$.remoteAudioTrack;if(!(de!=null&&de.mediaTrack))return{};let Ae=this._core.createAudioNode(de.mediaTrack);s.push(Ae),n.push(`remote_${r}`)}let H=()=>D(this,null,function*(){var A,le,He,ge,ze;let de=new _y.default;for(let me=0;me<n.length;me++)de.file(`${n[me]}.pcm`,new Blob(a[me]));if((A=c==null?void 0:c[0])!=null&&A.length&&de.file("audioProcessor_input_capture.pcm",new Blob(c[0])),(le=c==null?void 0:c[1])!=null&&le.length&&de.file("audioProcessor_input_playback.pcm",new Blob(c[1])),(He=d==null?void 0:d[0])!=null&&He.length&&de.file("audioProcessor_screen_audio_input_capture.pcm",new Blob(d[0])),(ge=d==null?void 0:d[1])!=null&&ge.length&&de.file("audioProcessor_screen_audio_input_playback.pcm",new Blob(d[1])),m!=null&&m.length){let me=m.reduce((re,Q)=>`${re}
|
|
124
|
-
${Q}`);de.file("audioProcessor_handle_timestamp.txt",new Blob([me]))}if(l!=null&&l.length){let me=l.reduce((re,Q)=>`${re}
|
|
125
|
-
${Q}`);de.file("audioProcessor_big_gap_data.txt",new Blob([me]))}let Ae=yield de.generateAsync({type:"blob"}),L=URL.createObjectURL(Ae),te=document.createElement("a");te.href=L,te.download=`${t}-audio-${T}.zip`,te.style.display="none",document.body.appendChild(te),te.click(),URL.revokeObjectURL(L),te.remove(),this.addInfoToBanner(Zi,`Dump success, file name is: ${t}-${T}.zip`),this._core.innerEmitter.off("265",w),((ze=E==null?void 0:E.aec)!=null&&ze.node||y!=null&&y.aec.node)&&this._core.trtc.updatePlugin("AudioProcessor",{enableDump:!1}),o&&clearTimeout(o),f.abort("download")});return e>0&&(o=Number(setTimeout(()=>{f.abort("timeout")},e*1e3))),s.length>0&&this._core.startGetPCM(s).then(de=>de.pipeTo(new WritableStream({write(Ae){Ae.forEach((L,te)=>{a[te]=a[te]?a[te].concat(L[0]):[L[0]]})}}),f).catch(()=>H)),{download:H,onDumpEnd:()=>{f.abort("timeout")}}}formatStartDumpTime(t){let e=new Date(t),r=e.getFullYear(),o=this.pad(e.getMonth()+1),s=this.pad(e.getDate()),n=this.pad(e.getHours()),a=this.pad(e.getMinutes()),c=this.pad(e.getSeconds()),d=-e.getTimezoneOffset(),m=Math.floor(Math.abs(d)/60),l=Math.abs(d)%60,f=d>=0?"+":"-";return`${r}-${o}-${s}T${n}-${a}-${c}${f}${this.pad(m)}-${this.pad(l)}`}convertOpusToOgg(t){let o=Math.floor(Math.random()*4294967295),s=0,n=0,a=[],c=this.createOpusHead(48e3,2);a.push(this.createOggPage(2,0,o,s++,[c]));let d=this.createOpusTags();a.push(this.createOggPage(0,0,o,s++,[d]));let m=[],l=0;return t.forEach((f,g)=>{let T=this.getOpusPacketDuration(f);m.push(f),l+=f.byteLength,n+=T;let E=g===t.length-1;if(l>6e4||m.length>=50||E){let y=E?4:0;a.push(this.createOggPage(y,n,o,s++,m)),m=[],l=0}}),new Blob(a,{type:"audio/ogg"})}createOpusHead(t,e){let r=new ArrayBuffer(19),o=new DataView(r);return this.writeString(o,0,"OpusHead"),o.setUint8(8,1),o.setUint8(9,e),o.setUint16(10,0,!0),o.setUint32(12,t,!0),o.setUint16(16,0,!0),o.setUint8(18,0),r}createOpusTags(){let t="TRTC Debugger",e=t.length,r=new ArrayBuffer(12+e+4),o=new DataView(r);return this.writeString(o,0,"OpusTags"),o.setUint32(8,e,!0),this.writeString(o,12,t),o.setUint32(12+e,0,!0),r}createOggPage(t,e,r,o,s){let n=0;s.forEach(y=>{let v=y.byteLength;for(;v>=255;)n++,v-=255;n++});let a=27+n,c=s.reduce((y,v)=>y+v.byteLength,0),d=a+c,m=new ArrayBuffer(d),l=new DataView(m),f=new Uint8Array(m);this.writeString(l,0,"OggS"),l.setUint8(4,0),l.setUint8(5,t),l.setUint32(6,e&4294967295,!0),l.setUint32(10,Math.floor(e/4294967295),!0),l.setUint32(14,r,!0),l.setUint32(18,o,!0),l.setUint32(22,0,!0),l.setUint8(26,n);let g=27;s.forEach(y=>{let v=y.byteLength;for(;v>=255;)f[g++]=255,v-=255;f[g++]=v});let T=a;s.forEach(y=>{f.set(new Uint8Array(y),T),T+=y.byteLength});let E=this.crc32(f);return l.setUint32(22,E,!0),f}writeString(t,e,r){for(let o=0;o<r.length;o++)t.setUint8(e+o,r.charCodeAt(o))}getOpusPacketDuration(t){if(t.byteLength===0)return 0;let e=new Uint8Array(t),r=e[0],o=r>>3&31,s=r&3,n=1;if(s===1||s===2)n=2;else if(s===3){if(t.byteLength<2)return 0;n=e[1]&63}return([480,480,480,480,960,960,960,960,1920,1920,1920,1920,2880,2880,480,480,120,120,120,120,240,240,240,240,480,480,480,480,960,960,960,960][o]||960)*n}crc32(t){let e=new Uint32Array(256),r=79764919;for(let s=0;s<256;s++){let n=s<<24;for(let a=0;a<8;a++)(n&2147483648)!==0?n=n<<1^r:n<<=1;e[s]=n>>>0}let o=0;for(let s=0;s<t.length;s++){let n=(o>>>24^t[s])&255;o=(o<<8^e[n])>>>0}return o}};Ie([Zc(300,()=>"export")],id.prototype,"onExportClick",1),Ie([Zc(300,()=>"upload")],id.prototype,"onUploadClick",1);var vy=id;var t0=0,nh,sd=class sd{constructor(t){this.core=t;p(this,"_core");p(this,"log");p(this,"dumpLocalVideoMap",{});p(this,"dumpRemoteVideoMap",{});p(this,"dumpLocalAudioMap",{});p(this,"dumpRemoteAudioMap",{});p(this,"dialog");this._core=t,this.log=t.log.createChild({id:`${this.getAlias()}${++t0}`}),this.log.info("created")}getName(){return sd.Name}getAlias(){return"dm"}getGroup(){return"dm"}getValidateRule(t){switch(t){case"start":return{name:"StartDebugOptions",required:!1};case"update":return{name:"UpdateDebugOptions",required:!1};case"stop":return{name:"StopDebugOptions",required:!1}}}start(){return D(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(),this.addAudioProcessor())})}update(e){return D(this,arguments,function*({visible:t}){t?(yield this.openDebugDiaLog(),this.addVideoProcessor()):(this.closeDebugDiaLog(),this.removeVideoProcessor())})}stop(){this.closeDebugDiaLog(),this.removeVideoProcessor(),this.removeAudioProcessor()}destroy(){this.stop()}openDebugDiaLog(){return D(this,null,function*(){var t;if(!this.dialog)try{if(nh)yield nh;else{let e=new URLSearchParams(location.search).get("trtcDebugDialogPath")||((t=window.sessionStorage)==null?void 0:t.getItem("TRTC_DEBUG_DIALOG_PATH"))||`https://unpkg.com/${sy}@${qt}/assets/debug-dialog.js`;nh=this._core.fileDownloader.loadScript(e),yield nh}this.dialog=new vy(this._core,this.log,this.dumpLocalVideoMap,this.dumpRemoteVideoMap,this.dumpLocalAudioMap,this.dumpRemoteAudioMap),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):Xf,type:1}),this._core.room.videoManager.addDecodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.decodeVideo.bind(this):Jf,type:1})}removeVideoProcessor(){this._core.room.videoManager.removeEncodeProcessor({type:1}),this._core.room.videoManager.removeDecodeProcessor({type:1})}addAudioProcessor(){this._core.room.audioManager.addEncodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.encodeAudio.bind(this):Qf,type:2}),this._core.room.audioManager.addDecodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.decodeAudio.bind(this):Yf,type:2})}removeAudioProcessor(){this._core.room.audioManager.removeEncodeProcessor({type:2}),this._core.room.audioManager.removeDecodeProcessor({type:2})}encodeVideo({frame:t,mediaType:e}){return Xf({frame:t,onDump:()=>{if(!e)return;let r=e===2?"sub":"main",o=this.dumpLocalVideoMap[r];o&&(o.data.push(t.data.slice(0)),o.duration>0&&Date.now()-o.startTimestamp>o.duration*1e3&&o.onDumpEnd())}})}decodeVideo({frame:t,track:e}){return Jf({frame:t,onDump:()=>{if(!e)return;let r=this.dumpRemoteVideoMap[`${e.userId}-${e.streamType}`];r&&(r.data.push(t.data.slice(0)),r.duration>0&&Date.now()-r.startTimestamp>r.duration*1e3&&r.onDumpEnd())}})}encodeAudio({frame:t}){return Qf({frame:t,onDump:()=>{let e=this.dumpLocalAudioMap.main;e&&(e.data.push(t.data.slice(0)),e.duration>0&&Date.now()-e.startTimestamp>e.duration*1e3&&e.onDumpEnd())}})}decodeAudio({frame:t,track:e}){return Yf({frame:t,onDump:()=>{if(!e)return;let r=this.dumpRemoteAudioMap[e.userId];r&&(r.data.push(t.data.slice(0)),r.duration>0&&Date.now()-r.startTimestamp>r.duration*1e3&&r.onDumpEnd())}})}};p(sd,"Name","Debug"),p(sd,"autoStart",!0);var ah=sd;var Ry=i=>{switch(i){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},ch=class{constructor(t,e,r){p(this,"trackDoneOB");p(this,"startOB");p(this,"stopOB");p(this,"inputFrameCount",0);p(this,"decodedFrameCount",0);p(this,"type","auto");p(this,"config");p(this,"decoder");p(this,"_decodeSink");let{kvStatManager:o,trtc:s}=t;this.config=r.config,this.trackDoneOB=Qe(e,Ve.INIT),this.stopOB=ir(),this.startOB=ir(),r.type==="auto"?this.type="webCodecs":this.type=r.type;let n=ir(),a=c=>{let d=this.pipe(e);return n.next("STARTING"),e.log.info(`decoder type: ${this.type}`),Ye(d,At(this.stopOB),lt(()=>{},m=>{e.log.error(m),o.addFailedEvent({key:Ry(this.type),error:m}),c>4?this.startOB.error(m):this.startOB.next(c+1)})),Ye(d,Ni(1),rf(kc))};Ye(this.startOB,Mc(0),Wi(a),At(this.stopOB),lt(()=>{e.player.setOutput(),n.next("STARTED")},c=>{n.next("FAILED")},()=>{o.addSuccessEvent({key:Ry(this.type)}),o.addSuccessEvent({key:504702})}))}mock(t){this._decodeSink?this._decodeSink.error(t):this.startOB.next(0)}close(t){this.stopOB.next(t)}pipe(t){return So()(e=>D(this,null,function*(){this._decodeSink=e,e.defer(()=>{var o;(o=this.decoder)==null||o.close()});let{type:r}=this;try{switch(r){case"webCodecs":this.decoder=new AudioDecoder({error:o=>{t.log.error(o),e.error(4)},output:o=>{this.decodedFrameCount++,e.next(o),t.player.write(o)}});break;case"wasm":break}this.decoder.configure(this.config)}catch(o){t.log.error(o),e.error(r==="webCodecs"?2:6)}}))}decodeFrame(t){var e;this.inputFrameCount++,((e=this.decoder)==null?void 0:e.state)==="configured"&&this.decoder.decode(new EncodedAudioChunk({data:t.data,timestamp:t.timestamp,type:"key"}))}},r0={type:"object"},nd=class nd{constructor(t){this.core=t;p(this,"log");p(this,"contextMap",new Map);p(this,"decodeProcessorMap",new WeakMap);this.log=t.log.createChild({id:`${this.getAlias()}`})}getAlias(){return nd.Name}getGroup(t){return t.track.userId+t.track.streamType}getName(){return nd.Name}getValidateRule(t){return r0}start(t){let{track:e}=t;this.decodeProcessorMap.set(e,this.decode(t)),this.core.room.audioManager.addDecodeProcessor({processor:({frame:r,track:o})=>this.decodeProcessorMap.has(o)?this.decodeProcessorMap.get(o)({frame:r,track:o}):r,type:3})}decode(t){return({frame:e,track:r})=>{if(r!==t.track)return e;if(this.contextMap.has(r))return this.contextMap.get(r).decodeFrame(e);let o=new ch(this.core,r,t);return Ye(o.trackDoneOB,Ni(1),lt(()=>{this.core.clearStarted(this,this.getGroup(t)),this.stop({track:r})})),this.contextMap.set(r,o),o.decodeFrame(e)}}stop({track:t}){let e=this.contextMap.get(t);e&&(e.close("stop"),this.contextMap.delete(t),this.contextMap.size===0&&this.core.room.audioManager.removeDecodeProcessor({type:3}))}update(t){let e=this.contextMap.get(t.track);if(e){if(t.type==="mock"){e.mock(10);return}e.close("update"),this.contextMap.set(t.track,new ch(this.core,t.track,t))}}};p(nd,"Name","TRTCAudioDecoder");var ad=nd;var dh=class{constructor(){p(this,"log");this.log=se.createLogger({id:"exp"})}call(t,e){return D(this,null,function*(){return Rt(this[t])?this[t](e):Promise.reject(new Me({code:Te.INVALID_PARAMETER,message:Et({key:_t.API_NOT_EXIST,data:{name:t}})}))})}enableAudioFrameEvent(t){return D(this,null,function*(){let{trtcInstance:e,enable:r,userId:o,sampleRate:s=48e3,channelCount:n=1,port:a}=t,{audioManager:c}=e.room,{getPCMAbortCtrlMap:d,audioFrameEventConfigMap:m}=c;if(m.set(o,{enable:r,sampleRate:s,channelCount:n,port:a}),r)if(o==="*")e.room.remotePublishedUserMap.forEach(l=>{if(l.remoteAudioTrack.isAvailable){if(d.get(l.userId))return;let f=c.getPCM(g=>{e.emit(Ne.AUDIO_FRAME,g)},l.userId);d.set(l.userId,f)}});else{if(d.get(o))return;let l=c.getPCM(f=>{e.emit(Ne.AUDIO_FRAME,f)},o);d.set(o,l)}else if(o==="*")e.room.remotePublishedUserMap.forEach(l=>{if(l.remoteAudioTrack.isSubscribed){let{userId:f}=l,g=d.get(f);g==null||g.abort("disable"),d.delete(f)}});else{let l=d.get(o);l==null||l.abort("disable"),d.delete(o)}})}resumeRemotePlayer(t){return D(this,null,function*(){if(t.userId==="*"){let r=[];return t.trtcInstance.room.remotePublishedUserMap.forEach(o=>{let{remoteAudioTrack:s,remoteVideoTrack:n,remoteAuxiliaryTrack:a}=o;t.streamType?t.streamType==="main"?(s.isAvailable&&r.push(s.player.resume()),n.isAvailable&&r.push(n.player.resume())):a.isAvailable&&r.push(a.player.resume()):(s.isAvailable&&r.push(s.player.resume()),n.isAvailable&&r.push(n.player.resume()),a.isAvailable&&r.push(a.player.resume()))}),Promise.all(r)}let e=t.trtcInstance.room.remotePublishedUserMap.get(t.userId);if(e)return t.streamType==="main"?Promise.all([e.remoteAudioTrack.player.resume(),e.remoteVideoTrack.player.resume()]):e.remoteAuxiliaryTrack.player.resume()})}pauseRemotePlayer(t){if(t.userId==="*")t.trtcInstance.room.remotePublishedUserMap.forEach(e=>{let{remoteAudioTrack:r,remoteVideoTrack:o,remoteAuxiliaryTrack:s}=e;t.streamType?t.streamType==="main"?(r.isAvailable&&r.player.pause(),o.isAvailable&&o.player.pause()):s.isAvailable&&s.player.pause():(r.isAvailable&&r.player.pause(),o.isAvailable&&o.player.pause(),s.isAvailable&&s.player.pause())});else{let e=t.trtcInstance.room.remotePublishedUserMap.get(t.userId);e&&(t.streamType==="main"?(e.remoteAudioTrack.player.pause(),e.remoteVideoTrack.player.pause()):e.remoteAuxiliaryTrack.player.pause())}}};Ie([jE({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"}}})],dh.prototype,"enableAudioFrameEvent",1);var Cy=new dh;var wy=Li(mo(),1);var sg=class extends wy.EventEmitter{constructor(){super();p(this,"states",{});p(this,"permissionChangeHandler");p(this,"log");this.log=se.createLogger({id:"pm"}),this.permissionChangeHandler=()=>{var e,r;this.emit("permission-state-change",{camera:(e=this.states.camera)==null?void 0:e.state,microphone:(r=this.states.microphone)==null?void 0:r.state})}}request(e){return D(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(o=>o.stop())})}get(e){return D(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(r){return this.log.error(`get ${e} permission failed, error: ${r instanceof Error?r.message:r}`),null}})}destroy(){Object.values(this.states).forEach(e=>{e==null||e.removeEventListener("change",this.permissionChangeHandler)}),this.states={}}},cd=new sg;var Ny=0,dd=new Set,pr=null;Uh(Vf);Yn.checkStorage();var We=class We extends Dy.EventEmitter{constructor(e,r){super();p(this,"_room");p(this,"_eventListened",new Set);p(this,"_localVideoTrack",null);p(this,"_localAudioTrack",null);p(this,"_localScreenTrack",null);p(this,"_localScreenAudioTrack",null);p(this,"_localVideoConfig",null);p(this,"_localScreenConfig",null);p(this,"_localAudioConfig",null);p(this,"_remoteVideoConfigMap",new Map);p(this,"_remoteAudioConfigMap",new Map);p(this,"_remoteAudioVolumeMap",new Map);p(this,"_remoteAudioMuteMap",new Map);p(this,"_mediaTrackMap",new WeakMap);p(this,"_log",se.createLogger({id:`t${++Ny}`}));p(this,"_plugins",new Map);p(this,"_networkQuality",null);p(this,"_speakerId");p(this,"enterRoomParams");p(this,"_enableAutoSwitchWhenRecapturing",!0);this._room=new e(be({logger:this._log,frameWorkType:We.frameWorkType},r)),this._room.videoDecodeFallbackType=r.videoDecodeFallback,Nt(r.enableAutoSwitchWhenRecapturing)&&(this._enableAutoSwitchWhenRecapturing=r.enableAutoSwitchWhenRecapturing),this._log.info(`create() ${JSON.stringify(r,(o,s)=>o==="plugins"?s.map(n=>n.Name):s)}`),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(o){return this._room.audioManager.dump(o)}}}),r.plugins&&r.plugins.forEach(o=>{this._use(o,r.assetsPath)}),this._use(zl,r.assetsPath),this._use(Wl,r.assetsPath),this._use(ql,r.assetsPath),this._use(ad,r.assetsPath),this._use(ah),r.enableSEI&&fc&&this._use(Xl),this._room.on("audio-volume",o=>{var s,n;!o.find(a=>a.userId==="")&&this._localAudioTrack&&o.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()}),r.volumeType===1&&o.forEach(a=>{var d;let c=a.userId===""?this._localAudioTrack:(d=this.room.remotePublishedUserMap.get(a.userId))==null?void 0:d.remoteAudioTrack;c&&(a.volume=c.dbVolume)}),r.enableDbVolume&&o.forEach(a=>{var d;let c=a.userId===""?this._localAudioTrack:(d=this.room.remotePublishedUserMap.get(a.userId))==null?void 0:d.remoteAudioTrack;c&&(a.volume=c.dbVolume)}),this.emit(Ne.AUDIO_VOLUME,{result:o.sort((a,c)=>c.volume-a.volume)})}),this._room.videoManager.on("error",o=>{this._log.error(new Oe({code:ke.OPERATION_FAILED,extraCode:5504,message:o.message,originError:o}))}),this._listenEvents(),this._initActiveSpeaker(),ry(this,"trtc")}static create(e){}static _create(e,r){$T();let o=new We(e,r||{});return dd.add(o),o.__v_skip=!0,o}get room(){return this._room}_listenEvents(){yr(this,this._room).add("peer-join",e=>{let{userId:r}=e;this.emit(Ne.REMOTE_USER_ENTER,{userId:r})}).add("peer-leave",e=>{this.emit(Ne.REMOTE_USER_EXIT,{userId:e})}).add("banned",e=>{Ro(!0),this._exitRoom().finally(()=>{this.emit(Ne.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().finally(()=>{this.emit(Ne.ERROR,Oe.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(Ne.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let r=qe(be({},e),{uplinkRTT:Math.min(e.uplinkRTT,Va),downlinkRTT:Math.min(e.downlinkRTT,Va)});this.emit(Ne.NETWORK_QUALITY,r)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(o=>{yr(o,o).add("player-state-changed",s=>{let n=qe(be({},s),{userId:e.userId});o.kind===j.VIDEO&&(n.streamType=Ji(o.streamType)),this.emit(o.kind===j.AUDIO?Ne.AUDIO_PLAY_STATE_CHANGED:Ne.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",s=>{s.getCode()===Te.PLAY_NOT_ALLOWED&&this.emit(Ne.AUTOPLAY_FAILED,{userId:o.userId,mediaType:o.strMediaType,resume:()=>o.player.resume()})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(o=>{tr(o)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:r})=>{let{userId:o}=r,s=e.audioAvailable,n=e.videoAvailable,{audioAvailable:a,videoAvailable:c}=r;a||this._remoteAudioConfigMap.delete(o),c||this._removeRemoteVideoConfig(o,"main"),r.hasAuxiliary||this._removeRemoteVideoConfig(o,"sub"),n!==c&&(c?this._onVideoAvailable({userId:o,streamType:"main"}):this._onVideoUnavailable({userId:o,streamType:"main"}),this.emit(c?Ne.REMOTE_VIDEO_AVAILABLE:Ne.REMOTE_VIDEO_UNAVAILABLE,{userId:o,streamType:"main"})),s!==a&&(a?this._onAudioAvailable({userId:o}):this._onAudioUnavailable({userId:o,muteState:r}),this.emit(a?Ne.REMOTE_AUDIO_AVAILABLE:Ne.REMOTE_AUDIO_UNAVAILABLE,{userId:o})),e.hasAuxiliary!==r.hasAuxiliary&&(r.hasAuxiliary?this._onVideoAvailable({userId:o,streamType:"sub"}):this._onVideoUnavailable({userId:o,streamType:"sub"}),this.emit(r.hasAuxiliary?Ne.REMOTE_VIDEO_AVAILABLE:Ne.REMOTE_VIDEO_UNAVAILABLE,{userId:o,streamType:"sub"}))}).add("sei-message",e=>{this.emit(Ne.SEI_MESSAGE,qe(be({},e),{streamType:Ji(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(Ne.ERROR,new Oe({code:ke.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var s,n,a,c,d,m,l;let r={2:"big",3:"small",7:"sub"},o={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,Va),upLoss:((c=this._networkQuality)==null?void 0:c.uplinkLoss)||0,downLoss:((d=this._networkQuality)==null?void 0:d.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((m=e.msg_up_stream_info.msg_audio_status)==null?void 0:m.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((l=e.msg_up_stream_info.msg_audio_status)==null?void 0:l.uint32_audio_level)||0)/fo},video:e.msg_up_stream_info.msg_video_status.filter(f=>r[f.uint32_video_stream_type]).map(f=>({bitrate:(f.uint32_video_codec_bitrate||0)/1e3,width:f.uint32_video_width,height:f.uint32_video_height,frameRate:f.uint32_video_enc_fps,videoType:r[f.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(f=>({userId:f.msg_user_info.str_identifier,audio:{bitrate:(f.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(f.msg_audio_status.uint32_audio_level||0)/fo,point2pointDelay:(f.msg_audio_status.uint32_audio_p2p_delay||0)+(f.msg_audio_status.uint32_audio_cache_ms||0),jitterBufferDelay:f.msg_audio_status.uint32_audio_cache_ms||0},video:f.msg_video_status.map(g=>({bitrate:(g.uint32_video_codec_bitrate||0)/1e3,width:g.uint32_video_width,height:g.uint32_video_height,frameRate:g.uint32_video_dec_fps,videoType:r[g.uint32_video_stream_type],point2pointDelay:(g.uint32_video_p2p_delay||0)+(g.uint32_video_cache_ms||0),jitterBufferDelay:g.uint32_video_cache_ms||0,codec:g.uint32_video_codec}))}))};this.emit(Ne.STATISTICS,o)}).add("custom-message",e=>{this.emit(Ne.CUSTOM_MESSAGE,e)}).add("layerData",e=>this.emit(Ne.LAYER_DATA,e)).add("first-video-frame",e=>{this.emit(Ne.FIRST_VIDEO_FRAME,qe(be({},e),{streamType:Ji(e.streamType)}))}).add("audio-frame",e=>{this.emit(Ne.AUDIO_FRAME,e)}),yr(this,$t).add("audioInputAdded",e=>{this.emit(Ne.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(Ne.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(Ne.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(Ne.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>D(this,null,function*(){if(this.emit(Ne.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),pr&&pr.deviceId===Ua){let r=(yield Zo()).find(o=>o.deviceId===Ua);r&&pr.groupId!==r.groupId&&(pr=r,this.emit(Ne.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}))}})).add("audioOutputRemoved",e=>D(this,null,function*(){this.emit(Ne.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let r=(yield Zo())[0];if(!r||!pr||pr.groupId===r.groupId)return;let o=pr.deviceId===e.deviceId,s=pr.deviceId===Ua&&pr.deviceId===r.deviceId;(o||s)&&(pr=r,this.emit(Ne.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}))})),yr(this,cd).add("permission-state-change",e=>{this.emit(Ne.PERMISSION_STATE_CHANGE,e)}),this.room.enableSEI&&this.on(Ne.SEI_MESSAGE,e=>{var o;let r=(o=this.room.remotePublishedUserMap.get(e.userId))==null?void 0:o.remoteVideoTrack;r&&r.updateAlphaRenderInfo(e)})}getNetworkTime(){return to()}use(e){let r,o;return"plugin"in e?(r=e.plugin,o=e.assetsPath):r=e,r.Name==="Chorus"&&(this.room.enableChorus=!0),this._use(r,o)}_use(e,r){let o=this._plugins.get(e.Name);if(o)return this._log.warn("duplicate install plugin",e.Name),o;let s=new e(ty.call(this,{TRTC:We,room:this._room,assetsPath:r,errorModule:{RtcError:Oe,ErrorCode:ke,CoreErrorCode:Te,ErrorCodeDictionary:Kr}}));return this._plugins.set(e.Name,s),s.__v_skip=!0,e.autoStart&&this.startPlugin(e.Name),s}enterRoom(e){return D(this,null,function*(){var c,d;this.enterRoomParams=e;let{scene:r="rtc",enableAutoPlayDialog:o=!0,autoReceiveAudio:s=!0,autoReceiveVideo:n=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!nt(e.proxy)&&e.proxy.turnServer&&((d=(c=this._room).setTurnServer)==null||d.call(c,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=o,this._room.autoReceiveAudio=s,this._room.autoReceiveVideo=n,Nt(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,keepAlive:e.keepAlive};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(a,r,We.frameWorkType),this._checkTrackToPublish(),Gf.start()})}exitRoom(){return D(this,null,function*(){return yield this._exitRoom()})}switchRoom(e){return D(this,null,function*(){if(this.room.isSwitchRoomSupported())try{this._clearRemoteTracks(),yield this._room.switchRoom(e)}catch(r){if(r instanceof Ma&&(r.code===Te.API_CALL_TIMEOUT||r.code===Te.SWITCH_ROOM_FAILED))this._log.warn(`switchRoom ${r.code===Te.API_CALL_TIMEOUT?"timeout":"failed"}, fallback to exitRoom() and enterRoom()`),yield this._rejoinRoom(e);else throw r}else yield this._rejoinRoom(e)})}_rejoinRoom(e){return D(this,null,function*(){yield this.exitRoom();let r=be(be({},this.enterRoomParams),e);yield this.enterRoom(r)})}_clearRemoteTracks(){new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(e=>{this._stopRemoteAudio({userId:e}).catch(()=>{})}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let r=e.includes("main")?"main":"sub",o=e.split(`_${r}`)[0];o&&this._stopRemoteVideo({userId:o,streamType:r}).catch(()=>{})}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),iy(this),this._room.remotePublishedUserMap.forEach(e=>{tr(e.remoteAudioTrack),tr(e.remoteVideoTrack),tr(e.remoteAuxiliaryTrack)})}switchRole(e,r){return D(this,null,function*(){r!=null&&r.privateMapKey&&(this._room.privateMapKey=r.privateMapKey),r!=null&&r.latencyLevel&&(this._room.latencyLevel=r.latencyLevel),yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){this._plugins.forEach(e=>{var r;return(r=e.destroy)==null?void 0:r.call(e)}),this._plugins.clear(),tr(this),this.removeAllListeners(),this._room.destroy(),dd.delete(this),dd.size===0&&Gf.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),ee.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return D(this,arguments,function*(e={publish:!0}){if(this._localAudioTrack){this._log.warn("local audio is already started");return}let{publish:r=!0,mute:o,option:s}=e,n=new Gi(this._room.audioManager),a={},c={muted:!0};s&&(z(s.microphoneId)?z(s.audioTrack)||(a.customSource=s.audioTrack):a.deviceId=s.microphoneId,s&&ft(s.captureVolume)&&n.setCaptureVolume(s.captureVolume),z(s.profile)||(nt(s.profile)?Vd[s.profile]&&n.setProfile(Vd[s.profile]):n.setProfile(s.profile)),ft(s.earMonitorVolume)&&(c.muted=!(s.earMonitorVolume>0),c.volume=s.earMonitorVolume),z(s.echoCancellation)||(n.profile.echoCancellation=s.echoCancellation),z(s.noiseSuppression)||(n.profile.noiseSuppression=s.noiseSuppression),z(s.autoGainControl)||(n.profile.autoGainControl=s.autoGainControl),Nt(this._enableAutoSwitchWhenRecapturing)&&(n.enableAutoSwitchWhenRecapturing=this._enableAutoSwitchWhenRecapturing)),n.on("5",d=>{this.emit(Ne.ERROR,new Oe({code:ke.DEVICE_ERROR,extraCode:5309,messageParams:{error:d}}))}),n.on("2",d=>{this.emit(Ne.DEVICE_CHANGED,{type:"microphone",action:"active",device:d})}),n.on("4",d=>{let m;d.error&&(m=Oe.convertFrom(d.error)),this.emit(Ne.PUBLISH_STATE_CHANGED,qe(be({},d),{error:m}))}),n.on("6",()=>{}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId),yield n.capture(a),z(o)||n.setMute(o),yr(n,n).add("player-state-changed",d=>{this.emit(Ne.AUDIO_PLAY_STATE_CHANGED,qe(be({},d),{userId:""}))}),r&&this._room.isJoined&&this._room.publish(n).catch(()=>{}),this._localAudioTrack=n,this._localAudioConfig=qe(be({},e),{publish:r}),yield this._updateAudioPlayOption({playOption:c,track:n}),ee.emit("113",{userId:"",room:this.room})})}updateLocalAudio(e){return D(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:r,mute:o,option:s}=e,n={};s&&(s.microphoneId?yield this._localAudioTrack.switchDevice(s.microphoneId):z(s.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(s.audioTrack)),z(s.captureVolume)||this._localAudioTrack.setCaptureVolume(s.captureVolume),z(s.earMonitorVolume)||(n.muted=!(s.earMonitorVolume>0),n.volume=s.earMonitorVolume),yield this._localAudioTrack.update3A(s)),this._room.isJoined&&!z(r)&&(r&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!r&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),z(o)||this._localAudioTrack.setMute(o),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),Ei(this._localAudioConfig,e)})}stopLocalAudio(){return D(this,null,function*(){this._localAudioTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),ee.emit("114",{userId:"",room:this.room}),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),tr(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)})}startLocalVideo(){return D(this,arguments,function*(e={publish:!0,view:null,capture:!0}){var l;if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:r,publish:o=!0,capture:s=!0,mute:n,option:a}=e,c=new Zr(this._room.videoManager),d={},m={};a&&(Nt(a.avoidCropping)&&(c.avoidCropping=a.avoidCropping),a.cameraId?d.deviceId=a.cameraId:z(a.useFrontCamera)?z(a.videoTrack)||(d.customSource=a.videoTrack):d.facingMode=a.useFrontCamera?j.FACING_MODE_USER:j.FACING_MODE_ENVIRONMENT,z(a.retryWhenExactFailed)||(d.retryWhenExactFailed=a.retryWhenExactFailed),a.qosPreference&&(d.contentHint=Jc(a.qosPreference)),z(a.profile)||(nt(a.profile)?gi[a.profile]&&c.setProfile(gi[a.profile]):c.setProfile(a.profile)),z(a.fillMode)||(m.objectFit=a.fillMode),z(a.mirror)||(m.mirror=a.mirror),z(a.small)||(z(a.smallMode)||(this._room.smallMode=a.smallMode),Nt(a.small)&&a.small===!1?c.stopSmall():c.updateSmallConfig(_a(a.small,!0))),z(a.rotation)||c.setRotation(a.rotation),Nt(this._enableAutoSwitchWhenRecapturing)&&(c.enableAutoSwitchWhenRecapturing=this._enableAutoSwitchWhenRecapturing)),c.once("first-video-frame",f=>{this.emit(Ne.FIRST_VIDEO_FRAME,qe(be({},f),{streamType:Ji(f.streamType)}))}),c.on("5",f=>{this.emit(Ne.ERROR,new Oe({code:ke.DEVICE_ERROR,extraCode:5308,messageParams:{error:f}}))}),c.on("2",f=>{this.emit(Ne.DEVICE_CHANGED,{type:"camera",action:"active",device:f})}),c.on("4",f=>{let g;f.error&&(g=Oe.convertFrom(f.error)),this.emit(Ne.PUBLISH_STATE_CHANGED,qe(be({},f),{error:g}))}),c.on("6",()=>{}),this._listenOutputTrackChanged(c),s?yield c.capture(d):(l=c.manager)==null||l.changeInput(c),z(n)||(yield c.setMute(n)),yr(c,c).add("player-state-changed",f=>{this.emit(Ne.VIDEO_PLAY_STATE_CHANGED,qe(be({},f),{userId:"",streamType:"main"}))}).add("video-size-changed",f=>{this.emit(Ne.VIDEO_SIZE_CHANGED,qe(be({},f),{streamType:Ji(f.streamType)}))}),o&&this._room.isJoined&&this._room.publish(c).catch(()=>{}),this._localVideoTrack=c,this._localVideoConfig=qe(be({},e),{view:r,publish:o,capture:s}),yield this._updateVideoPlayOption({view:r,playOption:m,track:c})})}updateLocalVideo(e){return D(this,null,function*(){var d,m,l;if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:r,publish:o,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):z(a==null?void 0:a.useFrontCamera)?z(a==null?void 0:a.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(a==null?void 0:a.videoTrack)):yield this._localVideoTrack.switchDevice(a!=null&&a.useFrontCamera?j.FACING_MODE_USER:j.FACING_MODE_ENVIRONMENT):this._localVideoTrack.stopCapture();else if(n){let f={};f.deviceId=(a==null?void 0:a.cameraId)||((d=this._localVideoConfig.option)==null?void 0:d.cameraId),f.facingMode=a!=null&&a.useFrontCamera||(m=this._localVideoConfig.option)!=null&&m.useFrontCamera?j.FACING_MODE_USER:j.FACING_MODE_ENVIRONMENT,f.customSource=(a==null?void 0:a.videoTrack)||((l=this._localVideoConfig.option)==null?void 0:l.videoTrack),yield this._localVideoTrack.capture(f)}a&&(z(a.profile)||(nt(a.profile)?gi[a.profile]&&this._localVideoTrack.setProfile(gi[a.profile]):this._localVideoTrack.setProfile(a.profile),(!a.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(a.cameraId))&&z(a.useFrontCamera)&&(yield this._localVideoTrack.applyProfile())),z(a.fillMode)||(c.objectFit=a.fillMode),z(a.mirror)||(c.mirror=a.mirror),z(a.rotation)||this._localVideoTrack.setRotation(a.rotation),a.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(Jc(a.qosPreference)),z(a.small)||(Nt(a.small)&&!a.small?this._localVideoTrack.stopSmall():this._localVideoTrack.updateSmallConfig(_a(a.small,!0)))),this._room.isJoined&&z(o)&&this._localVideoConfig.publish&&n&&!this._localVideoConfig.capture&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._room.isJoined&&((o!=null?o:this._localVideoConfig.publish)?this._room.publish(this._localVideoTrack).catch(()=>{}):this._room.unpublish(this._localVideoTrack).catch(()=>{})),z(s)||(yield this._localVideoTrack.setMute(s)),yield this._updateVideoPlayOption({view:r,playOption:c,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),Ei(this._localVideoConfig,e)})}stopLocalVideo(){return D(this,null,function*(){this._localVideoTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),tr(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return D(this,arguments,function*(e={publish:!0,view:null}){var f,g;if(this._localScreenTrack){this._log.warn("screen share is already started");return}let{view:r=null,publish:o=!0,muteSystemAudio:s,option:n}=e,a=new zi(this._room.videoManager);a.on("4",T=>{let E;T.error&&(E=Oe.convertFrom(T.error)),this.emit(Ne.PUBLISH_STATE_CHANGED,qe(be({},T),{error:E}))}),a.once("first-video-frame",T=>{this.emit(Ne.FIRST_VIDEO_FRAME,qe(be({},T),{streamType:Ji(T.streamType)}))}),this._listenOutputTrackChanged(a),e.streamType==="main"&&(a.mediaType=4);let c=null,d={},m={};n&&(z(n.profile)||(nt(n.profile)?Bd[n.profile]&&a.setProfile(Bd[n.profile]):a.setProfile(n.profile)),n.systemAudio&&(d.systemAudio=!0,d.echoCancellation=n.echoCancellation,d.noiseSuppression=n.noiseSuppression,d.autoGainControl=n.autoGainControl),z(n.fillMode)||(m.objectFit=n.fillMode),n.videoTrack&&(d.videoTrack=n.videoTrack),n.audioTrack&&(d.audioTrack=n.audioTrack),n.captureElement&&(d.captureElement=n.captureElement),n.preferDisplaySurface&&(d.preferDisplaySurface=n.preferDisplaySurface),n.qosPreference&&(d.contentHint=Jc(n.qosPreference)));let l=yield a.capture(d);if(a.mediaTrack.addEventListener(j.ENDED,()=>{this._stopScreenShare(),this.emit(Ne.SCREEN_SHARE_STOPPED)}),l.getAudioTracks()[0]){c=new an(this._room.audioManager);let T=l.getAudioTracks()[0];(f=e.option)!=null&&f.systemAudio&&!((g=e.option)!=null&&g.audioTrack)&&(c.sourceTrack=T),yield c.setInputMediaStreamTrack(T),Nt(s)&&c.mediaTrack&&(c.mediaTrack.enabled=!s),this._speakerId&&c.setAudioOutput(this._speakerId)}if(yr(a,a).add("player-state-changed",T=>{this.emit(Ne.VIDEO_PLAY_STATE_CHANGED,qe(be({},T),{userId:"",streamType:"sub"}))}),o&&this._room.isJoined){let T=[a];c&&(T.push(c),this._checkScreenAudioEchoCancellation(a,c)),T.forEach(E=>this._room.publish(E).catch(()=>{}))}this._localScreenTrack=a,this._localScreenAudioTrack=c,this._localScreenConfig=qe(be({},e),{view:r,publish:o}),yield this._updateVideoPlayOption({view:r,playOption:m,track:a})})}updateScreenShare(e){return D(this,null,function*(){var c;if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:r,publish:o,muteSystemAudio:s,option:n}=e,a={};if(n&&(z(n.fillMode)||(a.objectFit=n.fillMode),n.qosPreference)){let d=Jc(n.qosPreference);this._localScreenTrack.setContentHint(d)}if(this._room.isJoined&&!z(o)){if(o&&!this._localScreenConfig.publish){let d=[this._localScreenTrack];this._localScreenAudioTrack&&d.push(this._localScreenAudioTrack),d.forEach(m=>this._room.publish(m).catch(()=>{}))}if(this._localScreenConfig.publish&&!o){let d=[this._localScreenTrack];this._localScreenAudioTrack&&d.push(this._localScreenAudioTrack),d.forEach(m=>this._room.unpublish(m).catch(()=>{}))}}(c=this._localScreenAudioTrack)!=null&&c.mediaTrack&&Nt(s)&&(this._localScreenAudioTrack.mediaTrack.enabled=!s),yield this._updateVideoPlayOption({view:r,playOption:a,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),Ei(this._localScreenConfig,e)})}stopScreenShare(){return D(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return D(this,null,function*(){let{view:r,userId:o,streamType:s,option:n}=e,a=`${o}_${s}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${o}, streamType:${s}`);return}let c=this._room.remotePublishedUserMap.get(o);if(!c)return;let d={},m=s==="main"?c.remoteVideoTrack:c.remoteAuxiliaryTrack;m.on("decode-failed",l=>{this.emit(Ne.ERROR,new Oe({code:ke.OPERATION_FAILED,extraCode:5507,message:"video decode failed"}))}),m.on("video-size-changed",l=>{this.emit(Ne.VIDEO_SIZE_CHANGED,qe(be({},l),{streamType:Ji(l.streamType)}))}),this._listenOutputTrackChanged(m),n&&(z(n.fillMode)||(d.objectFit=n.fillMode),z(n.mirror)||(d.mirror=n.mirror),z(n.poster)||(d.poster=n.poster),d.canvasRender=n.canvasRender,s==="main"&&!z(n.small)&&(!c.remoteVideoTrack.isSubscribing&&!c.remoteVideoTrack.isSubscribed&&c.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,m.user)),z(n.draggable)||m.setDraggable(n.draggable)),yield this._room.subscribe(m),yield this._enableVideoDecodeFallback(m,s),yield this._updateVideoPlayOption({view:r,playOption:d,track:m}),this._emitTrackEvent(m),this._remoteVideoConfigMap.set(a,{config:e}),n&&!z(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:m,view:r,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:n==null?void 0:n.viewRoot})})}updateRemoteVideo(e){return D(this,null,function*(){var y,v;let{view:r,userId:o,streamType:s,option:n}=e,a=`${o}_${s}`,c=this._remoteVideoConfigMap.get(a);if(!c||!this._room.remotePublishedUserMap.has(o))return;let d={};n&&(z(n.fillMode)||(d.objectFit=n.fillMode),z(n.mirror)||(d.mirror=n.mirror));let m=null,l=this._room.remotePublishedUserMap.get(o);if(s==="main"&&(l!=null&&l.muteState.hasVideo)&&(m=l.remoteVideoTrack),s==="sub"&&(l!=null&&l.muteState.hasAuxiliary)&&(m=l.remoteAuxiliaryTrack),!m)return;let{config:f}=c;s==="main"&&n&&!z(n.small)&&this._room.changeType(n.small,m.user),n&&!z(n.draggable)&&m.setDraggable(n.draggable),yield this._updateVideoPlayOption({view:r,playOption:d,track:m,prevConfig:f}),Ei(f,e);let g=z(n==null?void 0:n.receiveWhenViewVisible)?(y=f.option)==null?void 0:y.receiveWhenViewVisible:n.receiveWhenViewVisible,T=z(r)?f.view:r,E=z(n==null?void 0:n.viewRoot)?(v=f.option)==null?void 0:v.viewRoot:n.viewRoot;this._observeView({remoteTrack:m,view:T,receiveWhenViewVisible:g,viewRoot:E})})}stopRemoteVideo(e){return D(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,r=!0){return D(this,null,function*(){let o=[],s=this._room.remotePublishedUserMap.get(e.userId);if(s){let{muteState:n,remoteVideoTrack:a,remoteAuxiliaryTrack:c}=s;e.streamType==="main"&&(a.stop(),n.hasVideo&&o.push(a)),e.streamType==="sub"&&(c.stop(),n.hasAuxiliary&&o.push(c))}for(let n of o)r&&(yield this._room.unsubscribe(n),this._mediaTrackMap.delete(n.outMediaTrack));this._removeRemoteVideoConfig(e.userId,e.streamType)})}_removeRemoteVideoConfig(e,r){let o=`${e}_${r}`,s=this._remoteVideoConfigMap.get(o);s&&s.observer&&s.observer.disconnect(),this._remoteVideoConfigMap.delete(o)}muteRemoteAudio(e,r){return D(this,null,function*(){this._remoteAudioMuteMap.set(e,r);try{if(e==="*")if(r)yield this._stopRemoteAudio({userId:e});else{let o=[...this._room.remotePublishedUserMap.values()];for(let s of o)s.muteState.hasAudio&&!this._remoteAudioConfigMap.has(s.userId)&&(yield this._startRemoteAudio({userId:s.userId}))}else r?yield this._stopRemoteAudio({userId:e}):this._remoteAudioConfigMap.has(e)||(yield this._startRemoteAudio({userId:e}))}catch(o){throw o.code!==ke.OPERATION_ABORT&&this._remoteAudioMuteMap.delete(e),o}})}setRemoteAudioVolume(e,r){if(e==="*"){this._remoteAudioVolumeMap.set("*",r),this._remoteAudioVolumeMap.forEach((s,n)=>this._remoteAudioVolumeMap.set(n,r));let o=[...this._room.remotePublishedUserMap.values()];for(let s of o)this._remoteAudioVolumeMap.set(s.userId,r),s.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:r},track:s.remoteAudioTrack})}else if(e){let o=this._room.remotePublishedUserMap.get(e);this._remoteAudioVolumeMap.set(e,r),o&&o.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:r},track:o.remoteAudioTrack})}}startPlugin(e,r){return D(this,null,function*(){return e.start(r)})}updatePlugin(e,r){return D(this,null,function*(){return e.update(r)})}stopPlugin(e,r){return D(this,null,function*(){return e.stop(r)})}enableAudioVolumeEvaluation(e=2e3,r=!1){this._room.enableAudioVolumeEvaluation(e,r)}on(e,r,o){if(this.listeners(e).includes(r))return this;if(this._log.debug("on",e),super.on(e,r,o),this._eventListened.add(e),this.listeners(Ne.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,...r){try{YT.has(e)||this._log.debug(`emit ${e} ${JSON.stringify(r)}`)}catch(o){}return super.emit(e,...r)}off(e,r,o){if(this._log.debug("off",e),e==="*"?(this._eventListened.clear(),this.removeAllListeners()):super.off(e,r,o),(e===We.EVENT.AUDIO_FRAME||e==="*")&&this.listeners(We.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 r,o=null,s="main",n=!1;if(nt(e)?r=e:(r=e.userId,n=e.processed===!0,e.streamType&&(s=e.streamType)),r){let a=this._room.remotePublishedUserMap.get(r);a&&(o=a.remoteAudioTrack)}else o=s==="sub"?this._localScreenAudioTrack:this._localAudioTrack;return o?n&&o.outMediaTrack&&o.outMediaTrack!==o.mediaTrack?o.outMediaTrack.clone():o.mediaTrack:null}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:r="",streamType:o="main",processed:s=!1}=e,n=null;if(r==="")o==="main"&&this._localVideoTrack&&(n=this._localVideoTrack),o==="sub"&&this._localScreenTrack&&(n=this._localScreenTrack);else{let a=this._room.remotePublishedUserMap.get(r);a&&(n=o==="main"?a.remoteVideoTrack:a.remoteAuxiliaryTrack)}return n?s&&n.outMediaTrack&&n.outMediaTrack!==n.mediaTrack?n.outMediaTrack.clone():n.mediaTrack:null}getVideoSnapshot(e={}){let{userId:r,streamType:o="main"}=e;if(r){let s=this._room.remotePublishedUserMap.get(r);if(o==="main"&&(s!=null&&s.muteState.hasVideo))return s.remoteVideoTrack.getVideoFrame();if(o==="sub"&&(s!=null&&s.muteState.hasAuxiliary))return s.remoteAuxiliaryTrack.getVideoFrame()}else{if(o==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(o==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(e){var r,o;this._speakerId=e,(r=this._localAudioTrack)==null||r.setAudioOutput(e),(o=this._localScreenAudioTrack)==null||o.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(s=>s.remoteAudioTrack.setAudioOutput(e))}setCurrentSpeaker(e){return D(this,null,function*(){(yield Zo()).forEach(o=>{o.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(Ne.DEVICE_CHANGED,{type:"speaker",action:"active",device:o}),pr=o)}),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: ${Br}/en/TRTC.html#.setCurrentSpeaker`)})}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return D(this,null,function*(){var a;let{userId:r}=e;if(this._remoteAudioConfigMap.has(r)){this._log.warn(`remote audio has already started. userId:${r}`);return}let o=this._room.remotePublishedUserMap.get(r);if(!o)return;let s={},n=o.remoteAudioTrack;n.on("decode-failed",c=>{this.emit(Ne.ERROR,new Oe({code:ke.OPERATION_FAILED,extraCode:5508,message:"audio decode failed"}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId);try{let c=(a=this._remoteAudioVolumeMap.get(r))!=null?a:this._remoteAudioVolumeMap.get("*"),d=ft(c)?c:100;s.volume=d,this._remoteAudioConfigMap.set(r,e),yield this._room.subscribe(n),Ye(Qe(n,"decode-failed"),At(Qe(n,Ve.INIT)),lt(()=>{this.startPlugin(ad.Name,{track:n,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:s,track:n}),ee.emit("115",{userId:r,room:this.room}),n.outMediaTrack&&this.room.audioManager.updateAudioReference({type:"add",audioReference:n.outMediaTrack,refId:`ra-${r}`})}catch(c){throw this._remoteAudioConfigMap.delete(r),c}this._emitTrackEvent(n)})}_stopRemoteAudio(e,r=!0){return D(this,null,function*(){let o=this._room.remotePublishedUserMap.get(e.userId);o&&(o.remoteAudioTrack.stop(),o.muteState.hasAudio&&r&&(yield this._room.unsubscribe(o.remoteAudioTrack)),this._mediaTrackMap.delete(o.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete(`${e.userId}`),ee.emit("116",{userId:e.userId,room:this.room}),this.room.audioManager.updateAudioReference({type:"remove",refId:`ra-${e.userId}`})})}_enableVideoDecodeFallback(e,r){let o=this._room.videoDecodeFallbackType;if(!o||!this._plugins.has("TRTCVideoDecoder"))return;e.log.debug("remote video will fall back when decode failed",e.id);let s;Ye(Qe(e,"decode-failed"),At(Qe(e,Ve.INIT)),en(()=>{this._room.downlinkVideoCodec!=="h265"&&this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:o})}),Io(Qe(e,"decode-downgrade-state-changed")),lt(n=>{s=n.state,this.emit(Ne.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,qe(be({},n),{streamType:r,userId:e.userId}))},n=>{e.log.error("fallback",n)},()=>{s==="STARTED"&&e.log.info("fallback complete")}))}_updateVideoPlayOption(n){return D(this,arguments,function*({view:e,playOption:r,track:o,prevConfig:s}){if(o.setMirror(r.mirror),z(e)&&s&&s.view&&!Pn(r)){let a=Vn(s.view);a.length>0&&(yield o.play(a,r))}if(!z(e)){let a=Vn(e);a.length>0?yield o.play(a,r):o.stop()}})}_updateAudioPlayOption(s){return D(this,arguments,function*({playOption:e={},track:r,prevConfig:o}){if(!r.isPlayCalled)try{yield r.play(null,e)}catch(n){}if(z(e.muted)||r.setPlayerMute(e.muted),z(e.volume)||r.setAudioVolume(e.volume/100),r instanceof Gi&&r.mediaTrack){let n=e.muted===!1&&!z(e.volume)&&e.volume>0?"add":"remove";this.room.audioManager.updateAudioReference({type:n,audioReference:r.mediaTrack,refId:"em"})}else if(r instanceof bo){let n=e.muted?0:e.volume;if(z(n))return;this.room.audioManager.updateAudioReference({type:"updateVolume",refId:`ra-${r.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,r=!0){let o=e.isRemote?e.userId:"";e.outMediaTrack&&(r&&this._mediaTrackMap.get(e.outMediaTrack)===o||(this._mediaTrackMap.set(e.outMediaTrack,o),this.emit(Ne.TRACK,{userId:o,streamType:Ji(e.streamType),track:e.outMediaTrack,sourceTrack:e.mediaTrack})))}_checkTrackToPublish(){var r,o,s;let e=[];if((r=this._localAudioConfig)!=null&&r.publish&&this._localAudioTrack&&e.push(this._localAudioTrack),(o=this._localVideoConfig)!=null&&o.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:r,receiveWhenViewVisible:o=!1,viewRoot:s}){if(z(r))return;let n=this._remoteVideoConfigMap.get(`${e.userId}_${Ji(e.streamType)}`);if(!n)return;let a=n.observer||void 0;if(r===null||Gt(r)&&r.length===0||!o){a==null||a.disconnect(),e.isSubscribed||this._room.subscribe(e).catch(()=>{});return}let d=n.visibleViewMap||new Map,m=-1;(!a||a.root!==s)&&(a==null||a.disconnect(),d.clear(),a=new IntersectionObserver(f=>{f.forEach(g=>{d.set(g.target,g.isIntersecting),e.log.info(`view ${g.target.id} is${g.isIntersecting?"":" not"} visible`)}),clearTimeout(m),m=window.setTimeout(()=>{[...d.values()].find(T=>T)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:s}));let l=new Set(Vn(r));d.forEach((f,g)=>{l.has(g)||(a.unobserve(g),d.delete(g))}),l.forEach(f=>{d.set(f,!0),a.observe(f)}),a.takeRecords().forEach(f=>{d.set(f.target,f.isIntersecting)}),n.visibleViewMap=d,n.observer=a}_exitRoom(){return D(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),this._clearRemoteTracks()})}_stopScreenShare(){return D(this,null,function*(){var e;if(this._localScreenTrack){if(this._room.isJoined){let r=[this._localScreenTrack];this._localScreenAudioTrack&&r.push(this._localScreenAudioTrack),yield Promise.all(r.map(o=>this._room.unpublish(o).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),tr(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_checkScreenAudioEchoCancellation(e,r){return D(this,null,function*(){var s,n;if(!e||!r)return;let o=(s=e.trackSettings)==null?void 0:s.displaySurface;if(((n=r.trackSettings)==null?void 0:n.echoCancellation)===!1&&(o==="monitor"||o==="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"&&(!pr||sa(pr))&&(this._initActiveSpeaker(),ee.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return D(this,null,function*(){if(pr&&!sa(pr))this.emit(Ne.DEVICE_CHANGED,{type:"speaker",action:"active",device:pr});else{let e=yield Zo();e[0]&&!sa(e[0])?(pr=e[0],this.emit(Ne.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):ee.on("102",this._onLocalTrackCaptured,this)}})}_onAudioAvailable({userId:e}){let r=this._remoteAudioMuteMap.has(e)?this._remoteAudioMuteMap.get(e):this._remoteAudioMuteMap.get("*");(r===!1||this._room.autoReceiveAudio&&!r)&&this._doStartRemoteAudio({userId:e}).catch(()=>{})}_onVideoAvailable({userId:e,streamType:r}){if(!this._room.autoReceiveVideo)return;let o=this._room.remotePublishedUserMap.get(e);if(o){let s=r==="main"?o.remoteVideoTrack:o.remoteAuxiliaryTrack,n=[s];this._room.autoReceiveAudio&&o.remoteAudioTrack.isAvailable&&n.push(o.remoteAudioTrack),this._room.subscribe(...n).then(()=>{this._emitTrackEvent(s)}).catch(()=>{})}}_onAudioUnavailable({userId:e,muteState:r}){r.hasAudio&&r.audioMuted||this._stopRemoteAudio({userId:e},!1).catch(()=>{})}_onVideoUnavailable({userId:e,streamType:r}){this._stopRemoteVideo({userId:e,streamType:r},!1).catch(()=>{})}sendSEIMessage(e,r){var s;let o=this._plugins.get("SEI");o&&(o.update({buffer:e,options:qe(be({seiPayloadType:243},r),{small:!!((s=this._localVideoTrack)!=null&&s.small)})}),Se.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var r,o;(o=(r=this._room).sendCustomMessage)==null||o.call(r,e),Se.addCount({key:500001,useUV:!0})}callExperimentalAPI(e,r){return D(this,null,function*(){return this._log.info(`callExperimentalAPI(${e}, ${JSON.stringify(r)})`),Cy.call(e,be({trtcInstance:this},r))})}static setLogLevel(e,r){se.setLogLevel(e),z(r)||(r?se.enableUploadLog():se.disableUploadLog())}static isSupported(){return Vu(We.frameWorkType)}static getPermissions(o){return D(this,arguments,function*({request:e=!0,types:r=["camera","microphone"]}){e&&(yield cd.request(r).catch(a=>{var c;return se.error(`getPermissions request failed, error: ${(c=a==null?void 0:a.message)!=null?c:a}`)}));let[s,n]=yield Promise.all([cd.get("camera"),cd.get("microphone")]);return{camera:s,microphone:n}})}static getCameraList(e=!0){return zr(e)}static getMicrophoneList(e=!0){return Gr(e)}static getSpeakerList(e=!0){return Zo(e)}static setCurrentSpeaker(e){return D(this,null,function*(){if(Bt&&(e===un.SPEAKER||e===un.HEADSET)){let o=yield We.getMicrophoneList(),s="";if(o.forEach(n=>{n.label===e&&(s=n.deviceId)}),!s)return;dd.forEach(n=>D(this,null,function*(){n._localAudioTrack&&(yield n.updateLocalAudio({option:{microphoneId:s}}))}));return}(yield Zo()).forEach(o=>{o.deviceId===e&&(dd.forEach(s=>{s._setCurrentSpeaker(e),s.emit(Ne.DEVICE_CHANGED,{type:"speaker",action:"active",device:o})}),pr=o)})})}static _addKVStat({type:e,key:r,value:o,base:s,useUV:n,version:a,max:c}){switch(a&&(Gs.version=a),e){case"count":Gs.addCount({key:r,useUV:n});break;case"enum":Gs.addEnum({key:r,value:o,useUV:n});break;case"number":Gs.addNumber({key:r,value:o,split:s,max:c});break}}};p(We,"VERSION",Vf),p(We,"_loggerManager",se),p(We,"EVENT",Ne),p(We,"ERROR_CODE",ke),p(We,"TYPE",un),p(We,"frameWorkType",30),Ie([Vt({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"}})})],We.prototype,"use",1),Ie([br(ur.TRTC.enterRoom),as("room",([e],[r])=>(e.roomId||e.strRoomId)===(r.roomId||r.strRoomId)&&e.userId===r.userId&&e.sdkAppId===r.sdkAppId),ut(e=>function(r){return this._log.setUserId(r.userId),this._log.setSdkAppId(r.sdkAppId),e.call(this,r)}),Vt()],We.prototype,"enterRoom",1),Ie([Vt()],We.prototype,"exitRoom",1),Ie([br(ur.TRTC.switchRoom),Vt(),el()],We.prototype,"switchRoom",1),Ie([br(ur.TRTC.switchRole),hn("room",{merge:(e,r)=>r}),Vt()],We.prototype,"switchRole",1),Ie([Vt()],We.prototype,"destroy",1),Ie([br(ur.TRTC.startLocalAudio),as("audio",([e],[r])=>{var o,s;return((o=e==null?void 0:e.option)==null?void 0:o.microphoneId)===((s=r==null?void 0:r.option)==null?void 0:s.microphoneId)}),Vt()],We.prototype,"startLocalAudio",1),Ie([br(ur.TRTC.updateLocalAudio),hn("audio",{debounce:{delay:200,getKey:()=>`${Ny}-localAudio`,isNeedToDebounce:e=>{var r;return!z((r=e.option)==null?void 0:r.captureVolume)}}}),Vt()],We.prototype,"updateLocalAudio",1),Ie([cs("audio"),Vt()],We.prototype,"stopLocalAudio",1),Ie([br(ur.TRTC.startLocalVideo),as("video",([e],[r])=>{var o,s;return((o=e==null?void 0:e.option)==null?void 0:o.cameraId)===((s=r==null?void 0:r.option)==null?void 0:s.cameraId)}),Vt()],We.prototype,"startLocalVideo",1),Ie([br(ur.TRTC.updateLocalVideo),hn("video"),Vt()],We.prototype,"updateLocalVideo",1),Ie([cs("video"),Vt()],We.prototype,"stopLocalVideo",1),Ie([br(ur.TRTC.startScreenShare),as("screen",()=>!0),Vt()],We.prototype,"startScreenShare",1),Ie([br(ur.TRTC.updateScreenShare),hn("screen"),Vt()],We.prototype,"updateScreenShare",1),Ie([Vt()],We.prototype,"stopScreenShare",1),Ie([br(ur.TRTC.startRemoteVideo),as(e=>`v${e.userId}${e.streamType}`,()=>!0),Vt({getRemoteId:e=>`${e.userId}_${e.streamType}`})],We.prototype,"startRemoteVideo",1),Ie([br(ur.TRTC.updateRemoteVideo),hn(e=>`v${e.userId}${e.streamType}`),Vt({getRemoteId:e=>`${e.userId}_${e.streamType}`})],We.prototype,"updateRemoteVideo",1),Ie([br(ur.TRTC.stopRemoteVideo),ut(e=>function(r){return D(this,null,function*(){if(r.userId==="*"){let o=[];return this._room.remotePublishedUserMap.forEach(s=>{this._remoteVideoConfigMap.has(`${s.userId}_main`)&&o.push(this.stopRemoteVideo({streamType:"main",userId:s.userId}).catch(()=>{})),this._remoteVideoConfigMap.has(`${s.userId}_sub`)&&o.push(this.stopRemoteVideo({streamType:"sub",userId:s.userId}).catch(()=>{}))}),Promise.all(o)}return e.call(this,r)})}),Vt({getRemoteId:e=>`${e.userId}_${e.streamType}`})],We.prototype,"stopRemoteVideo",1),Ie([cs(e=>`v${e.userId}${e.streamType}`)],We.prototype,"_stopRemoteVideo",1),Ie([br(...ur.TRTC.muteRemoteAudio),Vt({getRemoteId:e=>e})],We.prototype,"muteRemoteAudio",1),Ie([Bf(...ur.TRTC.setRemoteAudioVolume),Zc(200,e=>e),Vt({getRemoteId:e=>e})],We.prototype,"setRemoteAudioVolume",1),Ie([Fl("start"),Ko(e=>{var r;return(r=e.afterStart)==null?void 0:r.call(e)}),as((e,r)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(r)),Vt({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Hm[e.getName()],ignoreLog:e=>e.getName()==="Debug",ignoreErrorLog:e=>e.getName()==="AudioProcessor"})],We.prototype,"startPlugin",1),Ie([Fl("update"),hn((e,r)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(r),{merge:(e,r)=>(Ei(e[1],r[1]),e)}),Vt({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Wm[e.getName()]})],We.prototype,"updatePlugin",1),Ie([Fl("stop"),cs((e,r)=>{if(e.disableRandomCall)return null;let o=e.getGroup(r),s=e.getAlias();return o==="*"?new RegExp(`${s}.*`):s+o}),Vt({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Gm[e.getName()]})],We.prototype,"stopPlugin",1),Ie([Bf(...ur.TRTC.enableAudioVolumeEvaluation)],We.prototype,"enableAudioVolumeEvaluation",1),Ie([Vt()],We.prototype,"getVideoSnapshot",1),Ie([Vt()],We.prototype,"_setCurrentSpeaker",1),Ie([as(e=>`a${e.userId}`,()=>!0)],We.prototype,"_startRemoteAudio",1),Ie([ut(e=>function(r){return D(this,null,function*(){return r.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(o=>this._stopRemoteAudio(qe(be({},r),{userId:o.userId})).catch(()=>{}))):e.call(this,r)})}),cs(e=>`a${e.userId}`)],We.prototype,"_stopRemoteAudio",1),Ie([cs("room")],We.prototype,"_exitRoom",1),Ie([cs("screen")],We.prototype,"_stopScreenShare",1),Ie([br(...ur.TRTC.sendSEIMessage),xf({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...e)=>e[0].byteLength})],We.prototype,"sendSEIMessage",1),Ie([br(ur.TRTC.sendCustomMessage),xf({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],We.prototype,"sendCustomMessage",1),Ie([ds()],We,"create",1),Ie([br(ur.TRTC.create)],We,"_create",1),Ie([ds()],We,"setLogLevel",1),Ie([ds()],We,"isSupported",1),Ie([ds()],We,"getPermissions",1),Ie([ds()],We,"getCameraList",1),Ie([ds()],We,"getMicrophoneList",1),Ie([ds()],We,"getSpeakerList",1);var ng=We,va=ng;var uh=class{constructor(t,e){p(this,"_flag");p(this,"terminalType");p(this,"userId");p(this,"tinyId");p(this,"role");p(this,"remoteAudioTrack");p(this,"remoteVideoTrack");p(this,"remoteAuxiliaryTrack");this.userId=e.userId||"",this.tinyId=e.tinyId||"",this.role=e.role||"audience",this.terminalType=e.terminalType,this.remoteAudioTrack=new bo(t,this),this.remoteVideoTrack=new qi(t,this),this.remoteAuxiliaryTrack=new Al(t,this),this.flag=e.flag||0}get subscribeState(){let t={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(this.remoteVideoTrack.mediaType&8?t.smallVideo=!0:t.video=!0),this.remoteAudioTrack.isSubscribed&&(t.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(t.auxiliary=!0),t}get muteState(){return Ms(this.flag,this.userId)}get flag(){return this._flag}set flag(t){if(t===this._flag)return;let e,r=this.muteState;this._flag=t;let o=this.muteState;for(e in o)r[e]!=o[e]&&console.log(this.userId,e,r[e],"->",o[e]);this.remoteAudioTrack.onFlagChanged(),this.remoteVideoTrack.onFlagChanged(),this.remoteAuxiliaryTrack.onFlagChanged()}};var ag=class{constructor(){p(this,"_set",new Set);ee.on(ce.LEAVE_SUCCESS,this.delete,this),ee.on(ce.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess,this)}add({room:t,roomId:e}){if(t.scene==="rtc")return;let r=this.getKey(t.userId,e||t.roomId,t.sdkAppId,t.useStringRoomId);this._set.add(r)}delete({room:t,roomId:e}){if(t.scene==="rtc")return;let r=this.getKey(t.userId,t.roomId||e,t.sdkAppId,t.useStringRoomId);this._set.delete(r)}getKey(t,e,r,o){return`${r}_${e}_${t}_${o}`}isJoined({userId:t,roomId:e,sdkAppId:r,room:o}){return o.scene==="rtc"?!1:this._set.has(this.getKey(t,e,r,o.useStringRoomId))}handleSwitchRoomSuccess({room:t,currentRoomId:e,targetRoomId:r}){t.scene!=="rtc"&&(this._set.delete(this.getKey(t.userId,e,t.sdkAppId,t.useStringRoomId)),this._set.add(this.getKey(t.userId,r,t.sdkAppId,t.useStringRoomId)))}};function i0(){return D(this,null,function*(){let i,t;try{let g=yield Gr();i=g&&g.length}catch(g){}try{let g=yield zr();t=g&&g.length}catch(g){}let e={microphone:i,camera:t},{isH264EncodeSupported:r,isVp8EncodeSupported:o,isH264DecodeSupported:s,isVp8DecodeSupported:n,isH265EncodeSupported:a,isH265DecodeSupported:c}=this.checkSystemResult.detail,d=Jo.basis(),m={webRTC:d.isWebRTCSupported,getUserMedia:d.isGetUserMediaSupported,webSocket:d.isWebSocketsSupported,screenShare:d.isScreenShareSupported,webAudio:d.isWebAudioSupported,h264Encode:r,h264Decode:s,vp8Encode:o,vp8Decode:n,h265Encode:a,h265Decode:c},l={browser:d.browser,os:d.os,trtc:m,devices:e},f={isWebCodecSupported:d.isWebCodecSupported,isMediaSessionSupported:d.isMediaSessionSupported,isWebTransportSupported:d.isWebTransportSupported};It.uploadEvent({log:`trtcstats-${JSON.stringify(l)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(l)}`),It.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(f)}`,userId:this.userId}),tp()})}function Oy(){return ut(i=>{let t=new ag;return function(e,r,o){return D(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=r,e.privateMapKey=e.privateMapKey||"",this.isJoined)throw new Me({code:Te.INVALID_OPERATION,message:Et({key:_t.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:s,sdkAppId:this.sdkAppId,room:this}))throw new Me({code:Te.INVALID_OPERATION,message:Et({key:_t.REPEAT_JOIN,data:this.userId})});t.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}`),ee.emit(ce.JOIN_START,{room:this,roomId:s,params:e});let n=Vi.getEnv();n||(n=ro.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith($d.OLD_CLOUD_LADDER)?n=ro.OLD_CLOUD_LADDER:this.proxy_ws.startsWith($d.WEBRTC)&&(n=ro.WEBRTC))),It.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:s}),Jo.checkSystemRequirementsInternal(o).then(a=>{this.checkSystemResult=a,i0.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Vi.getEnv()&&(yield this.schedule(e,o));let a=yield i.call(this,e,r,o);return this.roomId=s,this._joinedTimestamp=Vi.performanceNow(),ee.emit(ce.JOIN_SUCCESS,{room:this}),o===30&&!e.component&&It.uploadEvent({log:`stat-conv-${Number(bi)}-${location.hostname}`,userId:this.userId}),a}catch(a){throw t.delete({room:this,roomId:s}),ee.emit(ce.JOIN_FAILED,{room:this,error:a}),a}})}})}var My=()=>ut(i=>function(...t){return D(this,null,function*(){ee.emit(ce.LEAVE_START,{room:this}),yield i.call(this,...t),ee.emit(ce.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function xy(){return ut(i=>function(...t){return D(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(t=t.filter(r=>r.outMediaTrack&&r.state==="ready"),!t.length))return;ee.emit("61",{room:this});let e=i.apply(this,t);return Promise.all(t.map(r=>r.publish(this,e)))})})}function ky(){return ut(i=>function(...t){let e=i.apply(this,t);return t.forEach(r=>r.unpublish()),e})}function Ly(){return ut(i=>function(...t){let e=i.apply(this,t);return t.forEach(r=>!r.isSubscribed&&r.subscribe(e)),e})}function o0({fn:i,context:t}){return function(...e){try{let r=i.apply(t,e);return $o(r)?r.catch(o=>se.error(`${i.name}() error observed ${o}`)):r}catch(r){se.error(`${i.name}() error observed ${r}`)}}}var lh=class{constructor(t){p(this,"_frameWorkType");p(this,"_component");p(this,"_language");p(this,"connectionType");p(this,"_room");p(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,reportToken:void 0});p(this,"_keyPrefix");p(this,"_log");p(this,"_intervalId");p(this,"_firstPublishedUserList");p(this,"_networkQuality");p(this,"_basicInfo");p(this,"_pathJoinRoom");p(this,"_pathLeaveRoom");p(this,"_pathMainVideoMap");p(this,"_pathMainAudioMap");p(this,"_pathAuxiliaryMap");p(this,"_remoteStreamStatMap");p(this,"_localStreamStat");p(this,"_eventMap",new Map);p(this,"_captureCostSum",0);p(this,"_captureCostCount",0);p(this,"isDestroyed",!1);this._frameWorkType=t.frameWorkType||30,this._component=t.component||0,this.connectionType=t.connectionType||1,this._language=t.language||0,this._room=t.room,this._keyPrefix="key_point",this._log=se.createLogger({parent:this._room.getLogger(),id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(e=>{e.startsWith("handle")&&Rt(this[e])&&(this[e]=o0({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:qt,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,Us().then(()=>{this._basicInfo.string_os_version=ho(),this._basicInfo.string_device_name=Vs()||this._basicInfo.string_os_version})}addEvent(t,e){return this._eventMap.set(t,e),ee.on(t,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(ce.JOIN_START,this.handleJoinStart).addEvent(ce.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(ce.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(ce.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(ce.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(ce.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(ce.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(ce.JOIN_FAILED,this.handleJoinFailed).addEvent(ce.LEAVE_START,this.handleLeaveStart).addEvent(ce.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(ce.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(ce.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(ce.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(ce.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(ce.PUBLISH_START,this.handlePublishStart).addEvent(ce.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(ce.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(ce.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(ce.PLAY_TRACK_START,this.handlePlayStart).addEvent(ce.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(ce.PLAYER_STATE_CHANGED,({track:t,state:e,type:r})=>{!t.isRemote||!this.hitTest(t.room)||e==="PLAYING"&&(r===j.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))}).addEvent(ce.SWITCH_ROOM_START,this.handleSwitchRoomStart).addEvent(ce.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess).addEvent(ce.SWITCH_ROOM_FAILED,this.handleSwitchRoomFailed).addEvent(ce.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(ce.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(ce.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(ce.REMOTE_PUBLISH_STATE_CHANGED,({room:t,prevMuteState:e,muteState:r})=>{if(!this.hitTest(t))return;let o=e.hasAudio||e.hasVideo||e.hasSmall,s=e.hasAuxiliary,n=r.hasAudio||r.hasVideo||r.hasSmall,a=r.hasAuxiliary;!o&&n&&this.handleRemoteStreamAdded(r.userId,"main"),!s&&a&&this.handleRemoteStreamAdded(r.userId,"auxiliary")}).addEvent(ce.SINGLE_CONNECTION_STAT,({room:t,stat:e})=>{this.hitTest(t)&&(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((t,e)=>ee.off(e,t)),this._eventMap.clear()}destroy(){this.uninstallEvents(),Jt.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(t){this.hitTest(t.room)&&(this._pathJoinRoom.uint64_start_time===0&&(this._pathJoinRoom.uint64_start_time=Date.now()),t.params&&(z(t.params.frameWorkType)||(this._frameWorkType=t.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),z(t.params.component)||(this._component=t.params.component,this._basicInfo.uint32_component=this._component),z(t.params.language)||(this._language=t.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleJoinScheduleSuccess({room:t,detailCost:e}){if(this.hitTest(t)&&e){let{totalCost:r,local:o,dns:s,tcp:n,tls:a,request:c,response:d}=e;this._pathJoinRoom.int32_schedule_cost=r,this._pathJoinRoom.int32_schedule_local=o,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=d}}handleSignalConnectionStart({room:t}){this.hitTest(t)&&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:t,error:e}){this.hitTest(t)&&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 Me?Number(e.getExtraCode()||e.getCode()):Te.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}handleJoinSendCMD(t){this.hitTest(t.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(t){this.hitTest(t.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=t.code,t.code!==0&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}handleJoinSuccess(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_end_time===0&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=t.room.getSignalInfo())}handleJoinFailed({room:t,error:e}){this.hitTest(t)&&(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(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_recv_userlist_time===0&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=t.publishedUserList||[])}handleSendFirstVideoFrame({room:t}){this.hitTest(t)&&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(t){this.hitTest(t.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(t){var e;if(this.hitTest(t.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 r=(e=this._room.audioManager.localAudioTrack)==null?void 0:e.after3aSilenceStartTime;r&&(this._localStreamStat.statsToReport.uint32_after3a_silence_duration=Xe()-r)}else this._log.warn("pathJoinRoom endTime is 0");this.report()}}handleLeaveSendCMD(t){this.hitTest(t.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(t){if(this.hitTest(t.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:t}){if(this.hitTest(t)&&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:t,error:e}){if(this.hitTest(t)){let r=Date.now();this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=r,this._pathJoinRoom.uint64_end_time=r,e&&(this._pathJoinRoom.int32_end_ret=e instanceof Me?Number(e.getExtraCode()||e.getCode()):Te.UNKNOWN)}}handleRemoteStreamAdded(t,e){var o;let r=`${t}_${e}`;if(!this._remoteStreamStatMap.has(r)){let s={userId:t,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:qe(be({},s0),{msg_user_info:new ud({userId:t,tinyId:(o=this._room.remotePublishedUserMap.get(t))==null?void 0:o.tinyId,role:20})})};s.statsToReport.uint32_stream_type=e==="main"?2:7,this._remoteStreamStatMap.set(r,s)}}handleSubscribeStart({room:t,remotePublishedUser:e,streamType:r,subscribeState:o}){if(!this.hitTest(t))return;let{userId:s,tinyId:n,role:a}=e,c=new ud({userId:s,tinyId:n,role:a==="anchor"?20:21}),d=Date.now(),m=`${s}_${r}`,l=this._remoteStreamStatMap.get(m);l&&l.subscribeStartTime===0&&(l.subscribeStartTime=d),r==="main"?(e.muteState.hasVideo&&(o.video||o.smallVideo)&&!this._pathMainVideoMap.has(m)&&this._pathMainVideoMap.set(m,{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:d}),e.muteState.hasAudio&&o.audio&&!this._pathMainAudioMap.has(m)&&this._pathMainAudioMap.set(m,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:s,sendSubscribeCMDTime:d})):e.muteState.hasAuxiliary&&o.auxiliary&&!this._pathAuxiliaryMap.has(m)&&this._pathAuxiliaryMap.set(m,{sendSubscribeCMDTime:d})}handleSubscribed({room:t,remotePublishedUser:e,streamType:r}){if(this.hitTest(t)){let o=`${e.userId}_${r}`,s=this._remoteStreamStatMap.get(o);s&&s.subscribedTime===0&&(s.subscribedTime=Date.now())}}handlePlayStart({track:t}){if(!t.isRemote||!this.hitTest(t.room))return;let e=`${t.userId}_${t.streamType}`,r=this._remoteStreamStatMap.get(e);(r==null?void 0:r.playStreamTime)===0&&(r.playStreamTime=Date.now())}handleVideoLoadedData({track:t}){if(!t.isRemote||!this.hitTest(t.room))return;let e=`${t.userId}_${t.streamType}`,r=this._pathMainVideoMap.get(e);r&&r.statsToReport.uint64_combine_first_frame_time===0&&(r.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(t){let e=`${t.userId}_${t.streamType}`,r=Date.now(),o=this._pathMainVideoMap.get(e),s=this._remoteStreamStatMap.get(e);if(s){let{statsToReport:n}=s;if(!n.uint32_video_render_first&&t.streamType==="main"?this.hasVideoFlag(t.userId):this.hasAuxFlag(t.userId)){let a=r-this._pathJoinRoom.uint64_start_time;n.uint32_video_render_first=a,Se.addNumber({key:516820,value:a})}}(o==null?void 0:o.statsToReport.uint64_render_first_frame_time)===0&&(o.statsToReport.uint64_render_first_frame_time=r)}handleAudioPlaying(t){let e=`${t.userId}_${t.streamType}`,r=this._pathMainAudioMap.get(e);r&&r.statsToReport.uint64_play_first_frame_time===0&&(r.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(t){this.hitTest(t.room)&&(this._networkQuality.totalUplinkLoss+=t.uplink.loss,this._networkQuality.totalUplinkRTT+=t.uplink.rtt,this._networkQuality.count++,t.downlinks.forEach(({rtt:e,loss:r,userId:o,videoDelay:s,audioDelay:n})=>{let a=this._networkQuality.totalDownlinkRTTAndLossMap.get(o);if(a)a.totalRTT+=e,a.totalLoss+=r,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,d,m,l;s&&(d=s,m=1),n&&(c=n,l=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(o,{totalRTT:e,totalLoss:r,count:1,totalAudioDelay:c,totalVideoDelay:d,audioDelayCount:l,videoDelayCount:m})}}))}handleHeartbeatStats(t){var e;if(this.hitTest(t.room)){let{msg_device_info:r,msg_up_stream_info:o,msg_down_stream_info:s}=t.report;if(o.msg_video_status[0]){let{uint32_video_codec_bitrate:n,uint32_video_enc_fps:a,uint32_video_width:c,uint32_video_height:d}=o.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=n,this._localStreamStat.totalVideoFPS+=a,this._localStreamStat.totalVideoWidth+=c,this._localStreamStat.totalVideoHeight+=d,this._localStreamStat.videoCount++}if(o.msg_audio_status){let{uint32_audio_level:n}=o.msg_audio_status;Math.floor(n/fo*100)>0&&(this._localStreamStat.totalAudioLevel+=n/fo,this._localStreamStat.audioLevelCount++)}s.forEach(n=>{let{msg_user_info:a,msg_audio_status:c,msg_video_status:d}=n,m=a.str_identifier,l=this._room.remotePublishedUserMap.get(m);if(d.forEach(f=>{let g=f.uint32_video_stream_type===2,T=f.uint32_video_stream_type===7,E=`${m}_${g?"main":"auxiliary"}`,y=this._remoteStreamStatMap.get(E);if(y&&(g&&(l!=null&&l.remoteVideoTrack.isSubscribed)||T&&(l!=null&&l.remoteAuxiliaryTrack))){y.totalVideoFPS+=f.uint32_video_receive_fps,y.totalVideoBitrate+=f.uint32_video_codec_bitrate,y.videoCount++,y.statsToReport.uint32_video_width===0&&(y.statsToReport.uint32_video_width=f.uint32_video_width),y.statsToReport.uint32_video_height===0&&(y.statsToReport.uint32_video_height=f.uint32_video_height);let v=g?l.remoteVideoTrack:l.remoteAuxiliaryTrack;v.stat.jitterBufferDelay&&(y.videoJitterBufferDelay=v.stat.jitterBufferDelay),v.stat.framesReceived&&(y.statsToReport.uint32_video_consume_render_rate=Math.floor(v.stat.framesDecoded/v.stat.framesReceived*ki(10,6)))}}),!Pn(c)){let f=`${m}_main`,g=this._remoteStreamStatMap.get(f);this._remoteStreamStatMap.has(f)&&g&&l!=null&&l.remoteAudioTrack.isSubscribed&&(g.totalAudioBitrate+=c.uint32_audio_codec_bitrate,g.audioCount++,l.remoteAudioTrack.stat.jitterBufferDelay&&(g.audioJitterBufferDelay=l.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(c.uint32_audio_level/fo*100)>0&&(g.totalAudioLevel+=c.uint32_audio_level/fo,g.audioLevelCount++),c.uint32_audio_block_time&&(g.statsToReport.uint32_audio_block_time+=c.uint32_audio_block_time))}}),r.uint32_audio_capture_cost&&(this._captureCostSum+=r.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)),r.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:t}){this.hitTest(t)&&this._localStreamStat.publishStartTime===0&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart({track:t}){t.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),t.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess({track:t}){t.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()),t.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:t,error:e}){let o={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[e.name]||(e instanceof Me?e.getExtraCode()||e.getCode():Te.UNKNOWN);t.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=o,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),t.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=o,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}hasVideoFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&wn)>=0}hasAudioFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&Nn)>=0}hasAuxFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&Pa)>=0}hitTest(t){return t===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 t=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),e=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=t<<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((t,e)=>{let{userId:r}=t,o=this._networkQuality.totalDownlinkRTTAndLossMap.get(r);if(o){let{totalLoss:m,count:l,audioDelayCount:f,videoDelayCount:g,totalAudioDelay:T,totalVideoDelay:E}=o;t.statsToReport.uint32_avg_down_loss=Math.floor(m/l),f&&T&&(t.statsToReport.uint32_audio_network_p2p_delay=Math.floor(T/f),t.audioJitterBufferDelay&&(t.statsToReport.uint32_p2p_delay=Math.floor(t.statsToReport.uint32_audio_network_p2p_delay+t.audioJitterBufferDelay))),g&&E&&(t.statsToReport.uint32_video_network_p2p_delay=Math.floor(E/g))}t.videoCount>0&&(t.statsToReport.uint32_video_avg_fps=Math.floor(t.totalVideoFPS/t.videoCount),t.statsToReport.uint32_video_avg_bitrate=Math.floor(t.totalVideoBitrate/t.videoCount)),t.audioCount>0&&(t.statsToReport.uint32_audio_recv_bitrate=t.statsToReport.uint32_audio_bitrate=Math.floor(t.totalAudioBitrate/t.audioCount)),t.audioLevelCount>0&&(t.statsToReport.uint32_audio_play_db=Math.floor(t.totalAudioLevel/t.audioLevelCount*100));let{callDurationCalculator:s}=this._room;s&&(t.statsToReport.uint32_audio_play_time=s.getDuration(e,j.AUDIO),t.statsToReport.uint32_video_play_time=s.getDuration(e,j.VIDEO)),t.statsToReport.uint32_video_render_first&&(t.statsToReport.uint32_video_render_first=Math.min(t.statsToReport.uint32_video_render_first,fn));let{badCaseDetector:n}=this._room,{dataFreeze:a,count:c}=n.getDataFreezeDuration(e),{renderFreeze:d}=n.getRenderFreezeDuration(e);t.statsToReport.uint32_video_block_count=c,t.statsToReport.uint32_video_block_time=Math.min(a,t.statsToReport.uint32_video_play_time),t.statsToReport.uint32_video_external_block_time=Math.min(d,t.statsToReport.uint32_video_play_time),t.statsToReport.uint32_audio_block_time=Math.min(t.statsToReport.uint32_audio_block_time,t.statsToReport.uint32_audio_play_time),n.isBlackStream(e)&&t.statsToReport.uint32_video_avg_fps===0?t.statsToReport.uint32_video_black_screen_subjective=1:t.statsToReport.uint32_video_black_screen_subjective=0}),this._pathMainAudioMap.forEach((t,e)=>{if(!this.hasAudioFlag(t.userId)){this._pathMainAudioMap.delete(e);return}t.statsToReport.uint64_play_first_frame_time-t.statsToReport.uint64_start_enter_time>fn&&(t.statsToReport.uint64_play_first_frame_time=t.statsToReport.uint64_start_enter_time+fn)}),this._pathMainVideoMap.forEach((t,e)=>{if(!this.hasVideoFlag(t.userId)){this._pathMainVideoMap.delete(e);return}t.statsToReport.uint64_render_first_frame_time-t.statsToReport.uint64_start_enter_time>fn&&(t.statsToReport.uint64_render_first_frame_time=t.statsToReport.uint64_start_enter_time+fn)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>fn&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+fn)}getReportData(){this._basicInfo.uint32_networkType=Jd();let t={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new ud({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:Un(this._signalInfo.relayIp),uint32_client_ip:Un(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*ki(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:Un(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 Wa(t),t}report(){return D(this,null,function*(){try{this.prepareReport();let t=this.getReportData();yield this.upload(t),this.initData()}catch(t){this._log.warn(t)}finally{this.isDestroyed&&(this._room=null)}})}upload(t){return D(this,null,function*(){if(t.msg_path_enter_room.uint64_start_time===0)return;let e=Number(this._room.sdkAppId),r=zo.enable?so(t,2001,e):yield sm(t),o=r instanceof ArrayBuffer,s=`${oo(e,Bo.KEY_POINT)}&gzip=${+o}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(s,r));let a=[this.uploadKVStat(Se),this.uploadKVStat(Gs)];n||a.push(no({url:s,body:r,priority:"low"})),yield Promise.all(a)})}setConnectionType(t){this.connectionType=t,this._basicInfo.uint32_connection_type=t}uploadKVStat(t){return D(this,null,function*(){let e=t.getReportData(this._room.userSig,this._signalInfo.reportToken);if(e.stats_count.length===0&&e.stats_distribution.length===0)return;e.msg_sdk_basic_info=qe(be({},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 r=zo.enable?so(e,2003,this._room.sdkAppId):yield sm(e),o=r instanceof ArrayBuffer,s=`${oo(+this._room.sdkAppId,Bo.KV_STAT)}&gzip=${+o}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(s,r)),n||no({url:s,body:r})})}};Ie([qs({settings:{timeout:500,retries:3}})],lh.prototype,"upload",1);var fn=5e3,s0={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},ud=class{constructor(t){p(this,"str_identifier");p(this,"str_tinyid");p(this,"uint32_role");this.str_identifier=String(t.userId),this.str_tinyid=String(t.tinyId||0),this.uint32_role=t.role}},Py=lh;var cg=class{constructor(){p(this,"_startTime");p(this,"_endTime");this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=Xe())}stop(){this._endTime===0&&(this._endTime=Xe())}getDuration(){return this._endTime===0?Xe()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},hh=cg;var dg=class{constructor(t){p(this,"_room",null);p(this,"_durationMap");p(this,"_eventMap",new Map);this._room=t.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(ce.REMOTE_TRACK_SUBSCRIBED,this.handleSubscribed).set(ce.REMOTE_TRACK_UNSUBSCRIBED,this.handleUnsubscribed).set(ce.REMOTE_PUBLISH_STATE_CHANGED,({room:t,prevMuteState:e,muteState:r})=>{var n;let{userId:o}=r;if(!this.hitTest(t))return;e.hasAudio&&!r.hasAudio&&this.stopDurationItem(`${o}_main`,j.AUDIO),e.hasVideo&&!r.hasVideo&&this.stopDurationItem(`${o}_main`,j.VIDEO),e.hasAuxiliary&&!r.hasAuxiliary&&this.stopDurationItem(`${o}_auxiliary`,j.VIDEO);let s=(n=this._room)==null?void 0:n.remotePublishedUserMap.get(o);s&&(!e.hasAudio&&r.hasAudio&&s.remoteAudioTrack.isSubscribed&&this.addDuractionItem(o,j.AUDIO,"main"),!e.hasVideo&&r.hasVideo&&s.remoteVideoTrack.isSubscribed&&this.addDuractionItem(o,j.VIDEO,"main"),!e.hasAuxiliary&&r.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(o,j.VIDEO,"auxiliary"))}),this._eventMap.forEach((t,e)=>ee.on(e,t,this))}uninstallEvents(){this._eventMap.forEach((t,e)=>ee.off(e,t,this)),this._eventMap.clear()}handleSubscribed({track:t}){if(!this.hitTest(t.room))return;let{userId:e,streamType:r,kind:o}=t;t.isSubscribed?this.addDuractionItem(e,o,r):this.stopDurationItem(`${e}_${r}`,o)}handleUnsubscribed({track:t}){this.hitTest(t.room)&&this.stopDurationItem(`${t.userId}_${t.streamType}`,t.kind)}isRecording(t){return t.findIndex(e=>e.endTime===0)>=0}addDuractionItem(t,e,r){let o=`${t}_${r}`,s=new hh,n=this._durationMap.get(o);n?this.isRecording(n[e])||n[e].push(s):this._durationMap.set(o,{userId:t,type:r,audio:e===j.AUDIO?[s]:[],video:e===j.AUDIO?[]:[s]})}stopDurationItem(t,e){if(this._durationMap.has(t)){let o=this._durationMap.get(t)[e].find(s=>s.endTime===0);o&&o.stop()}}hitTest(t){return this._room===t}getDuration(t,e){return this._durationMap.has(t)?this._durationMap.get(t)[e].reduce((o,s)=>o+s.getDuration(),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},Uy=dg;var ug=class{constructor(){p(this,"renderFreezeMap",new Map);p(this,"dataFreezeMap",new Map)}get(t,e){let r=this.renderFreezeMap.get(t),o=this.dataFreezeMap.get(t);return e?e==="data"?o:r:(Zt||zt)&&r&&o&&r.duration>o.duration?r:o}set(t,e,r){r==="data"?this.dataFreezeMap.set(t,e):this.renderFreezeMap.set(t,e)}clear(){this.renderFreezeMap.clear(),this.dataFreezeMap.clear()}},lg=class{constructor(t){p(this,"_room");p(this,"_renderFreezeMap",new Map);p(this,"_isVideoPlayingEventFiredMap",new Map);p(this,"_dataFreezeMap",new Map);p(this,"_monitorFreezeData",new ug);p(this,"_eventMap",new Map);p(this,"_videoEncodeFailedCount",0);p(this,"_audioEncodeFailedCount",0);p(this,"_encodeFailedThreshold",3);p(this,"eventListenerMap",new Map);this._room=t.room,this.installEvents()}getRenderFreezeMap(){return this._renderFreezeMap}getDataFreezeMap(){return this._dataFreezeMap}installEvents(){this._eventMap.set(ce.LEAVE_SUCCESS,({room:t})=>{this.hitTest(t)&&this.stop()}).set(ce.PLAY_TRACK_START,this.onPlayTrackStart).set(ce.UNSUBSCRIBE_SUCCESS,({room:t,streamType:e,remotePublishedUser:r})=>{if(!this.hitTest(t))return;let{userId:o}=r,s=`${o}_${e}`;this.stopDataFreeze({key:s,userId:o,type:e})}).set(ce.REMOTE_PUBLISH_STATE_CHANGED,({room:t,prevMuteState:e,muteState:r})=>{if(!this.hitTest(t))return;let{userId:o}=r;if(e.hasVideo&&!r.hasVideo){let s="main",n=`${r.userId}_${s}`;this.stopDataFreeze({key:n,userId:o,type:s})}if(e.hasAuxiliary&&!r.hasAuxiliary){let s="auxiliary",n=`${r.userId}_${s}`;this.stopDataFreeze({key:n,userId:o,type:s})}}).set(ce.PLAYER_STATE_CHANGED,({track:t,state:e,reason:r,type:o})=>{if(!(!t.isRemote||!t.room||!this.hitTest(t.room)||o!==j.VIDEO)){if(e==="PLAYING"){let s=`${t.userId}_${t.streamType}`;this._isVideoPlayingEventFiredMap.set(s,!0)}r===j.MUTE?this.onVideoTrackMuted(t):r===j.UNMUTE&&this.onVideoTrackUnmuted(t)}}).set(ce.HEARTBEAT_REPORT,this.onHearBeatReport).set(ce.REMOTE_VIDEO_PLAY_START,this.onRemoteVideoPlayStart).set(ce.REMOTE_VIDEO_PLAY_FINISH,this.onRemoteVideoPlayEnd),this._eventMap.forEach((t,e)=>ee.on(e,t,this))}uninstallEvents(){this._eventMap.forEach((t,e)=>ee.off(e,t,this)),this._eventMap.clear()}stop(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}onVideoTrackMuted(t){if(!t.isSubscribed)return;let{userId:e,streamType:r}=t,o=`${e}_${r}`,s=this._dataFreezeMap.get(o),n=new hh;s?s.durationItemList.push(n):this._dataFreezeMap.set(o,{userId:e,type:r,durationItemList:[n],isFreezing(){let a=this.durationItemList[this.durationItemList.length-1];return a&&a.endTime===0}})}onVideoTrackUnmuted(t){if(!t.isSubscribed)return;let{userId:e,streamType:r}=t,o=`${e}_${r}`;this.stopDataFreeze({key:o,userId:e,type:r})}onHearBeatReport({room:t,report:e}){if(this.hitTest(t)){if(e.msg_up_stream_info.msg_video_status){let r=e.msg_up_stream_info.msg_video_status,o=Array.from(this._room.localTracks).find(n=>n.kind==="video"&&!n.isScreen),s=(o==null?void 0:o.stat.bytesSent)||0;if((o==null?void 0:o.isMediaTrackActive)===!1||s<=0||o!=null&&o.isUseCustomSource)return;r.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&&(o!=null&&o.isPublished)?(this._videoEncodeFailedCount+=1,this._videoEncodeFailedCount===this._encodeFailedThreshold&&It.uploadEvent({userId:this._room.userId,log:`stat-${ii.VIDEO_ENCODE_FAILED_DURING_CALL}`})):this._videoEncodeFailedCount=0)})}if(e.msg_up_stream_info.msg_audio_status){let r=e.msg_up_stream_info.msg_audio_status,o=Array.from(this._room.localTracks).find(n=>n.kind==="audio"),s=(o==null?void 0:o.stat.bytesSent)||0;if((o==null?void 0:o.isMediaTrackActive)===!1||s<=0)return;r.uint32_audio_codec_bitrate===0&&(o!=null&&o.isPublished)?(this._audioEncodeFailedCount+=1,this._audioEncodeFailedCount===this._encodeFailedThreshold&&It.uploadEvent({userId:this._room.userId,log:`stat-${ii.AUDIO_ENCODE_FAILED_DURING_CALL}`})):this._audioEncodeFailedCount=0}}}stopDataFreeze({key:t,userId:e,type:r}){let o=this._dataFreezeMap.get(t);if(!o||!o.isFreezing())return;let s=o.durationItemList[o.durationItemList.length-1];s.stop();let n=s.getDuration();if(n>Wd){let a=this._monitorFreezeData.get(t,"data");this._monitorFreezeData.set(t,{userId:e,type:r,duration:a?a.duration+n:n},"data")}else o.durationItemList.pop()}getTotalDuration(t){return t.reduce((e,r)=>{let o=r.getDuration();return e+Math.min(o,5e3)},0)}onPlayTrackStart({track:t}){if(!t.isRemote||!this.hitTest(t.room)||t.kind!==j.VIDEO||!t.isRemotePublished)return;let e=`${t.userId}_${t.streamType}`;this._isVideoPlayingEventFiredMap.has(e)||this._isVideoPlayingEventFiredMap.set(e,!1)}getDataFreezeDuration(t){let e={dataFreeze:0,count:0},r=this._dataFreezeMap.get(t);if(r){if(r.isFreezing()){let o=r.durationItemList[r.durationItemList.length-1];o.stop(),o.getDuration()<Wd&&r.durationItemList.pop()}e.dataFreeze=this.getTotalDuration(r.durationItemList),e.count=r.durationItemList.length}return e}getRenderFreezeDuration(t){let e={renderFreeze:0,count:0},r=this._renderFreezeMap.get(t);return r&&(e.renderFreeze=r.totalDuration,e.count=r.count),e}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(t){return this._isVideoPlayingEventFiredMap.has(t)?!this._isVideoPlayingEventFiredMap.get(t):!1}onRemoteVideoPlayStart({track:t,player:e}){var n;if(!Ri())return;let r=0,o=()=>{document.hidden||(r=0)};document.addEventListener("visibilitychange",o);let s=(a,c)=>{var d;if(r){let m=t.decodeFPS,l=m>0&&m<=5?600+1e3/m:600,f=c.presentationTime-r;if(f>l){f=Math.min(f,5e3);let g=`${t.userId}_${t.streamType}`,T=this._monitorFreezeData.get(g,"render");T?T.duration+=f:this._monitorFreezeData.set(g,{userId:t.userId,type:t.streamType,duration:f},"render");let E=this._renderFreezeMap.get(g);E?(E.totalDuration+=f,E.count+=1):this._renderFreezeMap.set(g,{userId:t.userId,type:t.streamType,totalDuration:f,count:1})}}r=c.presentationTime,(d=e.element)==null||d.requestVideoFrameCallback(s)};(n=e.element)==null||n.requestVideoFrameCallback(s),this.eventListenerMap.set(`${t.userId}_${t.streamType}`,{onVisibilityChange:o})}onRemoteVideoPlayEnd({track:t,player:e}){let r=`${t.userId}_${t.streamType}`,o=this.eventListenerMap.get(r);o&&document.removeEventListener("visibilitychange",o.onVisibilityChange)}resetMonitor(){this._monitorFreezeData.clear()}hitTest(t){return t===this._room}destroy(){this.uninstallEvents()}},Vy=lg;var Fy=Li(mo(),1);var mh=class{constructor(t,e,r,o,s,n=4/3){this.vbMode=t;this.faceDetectorHash=r;this.visionTaskRegistry=o;this.logger=s;p(this,"animationState");p(this,"originalAspect");p(this,"totalOffsetX",0);p(this,"totalOffsetY",0);p(this,"defaultScaleRatio",.1);p(this,"isRecovering",!1);p(this,"boundaryY",280);p(this,"lastActionTime",0);p(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(t,e,r){let s=[{key:570704,error:r!=null?r:e?void 0:11},{key:570705,error:r!=null?r:e?void 0:22}][t-1];s&&(e?Se.addSuccessEvent({key:s.key}):Se.addFailedEvent({key:s.key,error:s.error}))}actionCentering(t){let e=Date.now();if(this.animation(),!this.faceDetectorHash||e-this.lastActionTime<this.restTime||this.animationState.animating)return;let{videoWidth:r,videoHeight:o}=t;this.animationState.debounceThreshold=r/30,this.animationState.movementThreshold=r/20,this.boundaryY=o*.6;try{let s=this.visionTaskRegistry.getResult(this.faceDetectorHash);if(s.detections.length<=0){this.vbMode===1&&this.recoverOriginal(r,o);return}let n=s.detections[0].boundingBox,a=n.originX,c=n.originY,d=n.width,m=n.height;this.vbMode===1?this.dualStageCropping(r,o,a,c,d,m):this.vbMode===2&&this.movingPortrait(r,o,a,c,d,m)}catch(s){this.logger.error(s)}this.lastActionTime=e}calculateBoundary(t,e,r,o){let s,n;return t>e/2?(s=e-r-o,n=r-s):(s=r,n=0),{min:s,offset:n}}calculateTargetPosition(t,e,r,o,s,n,a=.4){let c=t+r/2,d=e+o/2,m,l,{min:f,offset:g}=this.calculateBoundary(c,s,t,r),{min:T,offset:E}=this.calculateBoundary(d,n,e,o);return m=2*f+r,l=2*T+o,m/l>this.originalAspect?(m=l*this.originalAspect,g=c-m/2):(l=m/this.originalAspect,E=d-l/2),r/s>a&&(g=0,E=0,m=s,l=n),g=Math.max(0,Math.min(g,s-m)),E=Math.max(0,Math.min(E,n-l)),{sx:g,sy:E,cropWidth:m,cropHeight:l,timestamp:Date.now()}}processFacePositionCrop(t,e,r){if(!this.animationState.current||!this.animationState.target){let a={sx:0,sy:0,cropWidth:e,cropHeight:r,timestamp:Date.now()};this.animationState.current=a,this.animationState.target=a;return}let o=this.positionDistance(this.animationState.target,t),s=this.positionDistance(this.animationState.current,t),n=this.animationState.current.cropWidth/e;o>this.animationState.debounceThreshold*n&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&s>this.animationState.movementThreshold*n&&(this.animationState.target=t,this.animationState.debounceTimer=setTimeout(()=>{this.animationState.startTime=Date.now(),this.animationState.animating=!0},this.animationState.debounceTime))}processFacePositionPortrait(t){if(!this.animationState.current||!this.animationState.target){this.animationState.current=be({},t),this.animationState.target=be({},t);return}let e=this.positionDistance(this.animationState.current,t),r=this.positionDistance(this.animationState.target,t);e>this.animationState.debounceThreshold&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&r>this.animationState.movementThreshold&&(this.animationState.current=t,this.animationState.debounceTimer=setTimeout(()=>{this.animationState.startTime=Date.now(),this.animationState.animating=!0},this.animationState.debounceTime))}animation(){if(!this.animationState.animating)return;let t=Date.now()-this.animationState.startTime,e=Math.min(t/this.animationState.duration,1),r=o=>o<.5?2*o*o:-1+(4-2*o)*o;if(this.animationState.current&&this.animationState.target){let o=(this.animationState.target.sx-this.animationState.current.sx)*r(e);this.animationState.current.sx+=o,this.totalOffsetX+=o;let s=(this.animationState.target.sy-this.animationState.current.sy)*r(e);if(this.animationState.current.sy+=s,this.totalOffsetY+=s,this.animationState.current.cropWidth+=(this.animationState.target.cropWidth-this.animationState.current.cropWidth)*r(e),this.animationState.current.cropHeight+=(this.animationState.target.cropHeight-this.animationState.current.cropHeight)*r(e),this.animationState.current.scaleRatio&&this.animationState.target.scaleRatio&&(this.animationState.current.scaleRatio+=(this.animationState.target.scaleRatio-this.animationState.current.scaleRatio)*r(e)),ft(this.animationState.current.scaleOffsetX)&&ft(this.animationState.target.scaleOffsetX)&&ft(this.animationState.current.scaleOffsetY)&&ft(this.animationState.target.scaleOffsetY)){let n=(this.animationState.target.scaleOffsetX-this.animationState.current.scaleOffsetX)*r(e);this.animationState.current.scaleOffsetX+=n;let a=(this.animationState.target.scaleOffsetY-this.animationState.current.scaleOffsetY)*r(e);this.animationState.current.scaleOffsetY+=a}}e>=1&&(this.animationState.animating=!1,this.animationState.current=this.animationState.target,this.isRecovering=!1)}positionDistance(t,e){return Math.sqrt(ki(t.sx-e.sx,2)+ki(t.sy-e.sy,2))}recoverOriginal(t,e){this.animationState.target={sx:0,sy:0,cropWidth:t,cropHeight:e,timestamp:Date.now()},this.animationState.animating=!0,this.animationState.startTime=Date.now(),this.isRecovering=!0}dualStageCropping(t,e,r,o,s,n,a=.3){if(this.isRecovering)return;let c=this.calculateTargetPosition(r,o,s,n,t,e);this.processFacePositionCrop(c,t,e),s*n/c.cropWidth/c.cropHeight>a&&this.recoverOriginal(t,e)}movingPortrait(t,e,r,o,s,n){var c,d,m,l,f,g,T,E,y,v,M,w;let a={sx:r+s/2+this.totalOffsetX,sy:o+n/2+this.totalOffsetY,cropWidth:t,cropHeight:e,scaleRatio:(d=(c=this.animationState.current)==null?void 0:c.scaleRatio)!=null?d:1,scaleOffsetX:(l=(m=this.animationState.current)==null?void 0:m.scaleOffsetX)!=null?l:0,scaleOffsetY:(g=(f=this.animationState.current)==null?void 0:f.scaleOffsetY)!=null?g:0,timestamp:Date.now()};this.animationState.target={sx:t/2,sy:o+n/2,cropWidth:t,cropHeight:e,scaleRatio:(E=(T=this.animationState.target)==null?void 0:T.scaleRatio)!=null?E:1,scaleOffsetX:(v=(y=this.animationState.target)==null?void 0:y.scaleOffsetX)!=null?v:0,scaleOffsetY:(w=(M=this.animationState.target)==null?void 0:M.scaleOffsetY)!=null?w:0,timestamp:Date.now()},this.animationState.animating||(this.animationState.target.scaleRatio=Math.sqrt(s*n/t/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(t){this.originalAspect=t}get current(){return this.animationState.current}get offset(){return{offsetX:this.totalOffsetX,offsetY:this.totalOffsetY}}get targetCrop(){return this.animationState.target}};var n0=`#version 300 es
|
|
62
|
+
2. If the user is in Chrome 70 and below, when the div container is moved, the playback will be paused.`,color:"orange",class:"orange",textColor:"#fff"},'"displaySurface":"window"':{tips:"Screen sharing captures the application window",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"monitor"':{tips:"Screen sharing captures the entire screen",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"browser"':{tips:"Screen sharing captures a certain tab page",color:"blue",class:"blue",textColor:"#fff"},updateMediaSettings:{tips:"The resolution and frame rate below are the actual resolution and frame rate captured",color:"blue",class:"blue",textColor:"#fff"},"main stream start to play with":{tips:"Call remoteStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"stream start to play with":{tips:"Call localStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"main setAudioVolume to 0":{tips:"Business side calls remoteStream.setAudioVolume(0) interface to set the playback volume to 0, which will cause the playback to be silent",color:"orange",class:"orange",textColor:"#fff"},"screen sharing was stopped because the video track is ended":{tips:"Screen sharing capture stopped, possible reasons: user clicks the stop button, the window/page shared by the user is closed, etc.",color:"orange",class:"orange",textColor:"#fff"},"Join() => joining room":{tips:"Call client.join interface",color:"blue",class:"blue",textColor:"#fff"},"publish() => publishing local stream":{tips:"Call client.publish interface",color:"blue",class:"blue",textColor:"#fff"},"subscribe() => subscribe to":{tips:"Call client.subscribe interface",color:"blue",class:"blue",textColor:"#fff"},"switchRole() => switch role":{tips:"Call client.switchRole interface",color:"blue",class:"blue",textColor:"#fff"}};["enterRoom","exitRoom","switchRole","destroy","startLocalAudio","updateLocalAudio","stopLocalAudio","startLocalVideo","updateLocalVideo","stopLocalVideo","startScreenShare","updateScreenShare","stopScreenShare","startRemoteVideo","updateRemoteVideo","stopRemoteVideo","muteRemoteAudio","setRemoteAudioVolume"].forEach(o=>{qf[`${o}()`]={tips:`Call trtc.${o}`,color:"blue",class:"blue",textColor:"#fff"}});var N0=Object.keys(qf);var QS=0,Id,zn=class zn{constructor(i){this.core=i;d(this,"_core");d(this,"log");d(this,"dumpLocalVideoMap",{});d(this,"dumpRemoteVideoMap",{});d(this,"dialog");this._core=i,this.log=i.log.createChild({id:`${this.getAlias()}${++QS}`}),this.log.info("created")}getName(){return zn.Name}getAlias(){return"dm"}getGroup(){return"dm"}getValidateRule(i){switch(i){case"start":return{name:"StartDebugOptions",required:!1};case"update":return{name:"UpdateDebugOptions",required:!1};case"stop":return{name:"StopDebugOptions",required:!1}}}start(){return f(this,null,function*(){var e;!new URLSearchParams(location.search).has("trtcDebug")&&((e=window.sessionStorage)==null?void 0:e.getItem("TRTC_ENABLE_DEBUG_PLUGIN"))!=="true"||(yield this.openDebugDiaLog(),this.addVideoProcessor())})}update(e){return f(this,arguments,function*({visible:i}){i?(yield this.openDebugDiaLog(),this.addVideoProcessor()):(this.closeDebugDiaLog(),this.removeVideoProcessor())})}stop(){this.closeDebugDiaLog(),this.removeVideoProcessor()}destroy(){this.stop()}openDebugDiaLog(){return f(this,null,function*(){var i;if(!this.dialog)try{if(Id)yield Id;else{let e=new URLSearchParams(location.search).get("trtcDebugDialogPath")||((i=window.sessionStorage)==null?void 0:i.getItem("TRTC_DEBUG_DIALOG_PATH"))||`https://unpkg.com/${Wf}@${$e}/assets/debug-dialog.js`;Id=this._core.fileDownloader.loadScript(e),yield Id}this.dialog=new TRTCDebugDialog(this._core,this.log,this.dumpLocalVideoMap,this.dumpRemoteVideoMap),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(e){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(e))}})}closeDebugDiaLog(){this.dialog&&(this.dialog.closeDialog(),this.dialog=null)}addVideoProcessor(){this._core.room.videoManager.addEncodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.encodeVideo.bind(this):$h,type:1}),this._core.room.videoManager.addDecodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.decodeVideo.bind(this):Wh,type:1})}removeVideoProcessor(){this._core.room.videoManager.removeEncodeProcessor({type:1}),this._core.room.videoManager.removeDecodeProcessor({type:1})}encodeVideo({frame:i,mediaType:e}){return $h({frame:i,onDump:()=>{if(!e)return;let t=e===2?"sub":"main",r=this.dumpLocalVideoMap[t];r&&(r.data.push(i.data.slice(0)),r.duration>0&&Date.now()-r.startTimestamp>r.duration*1e3&&r.onDumpEnd())}})}decodeVideo({frame:i,track:e}){return Wh({frame:i,onDump:()=>{if(!e)return;let t=this.dumpRemoteVideoMap[`${e.userId}-${e.streamType}`];t&&(t.data.push(i.data.slice(0)),t.duration>0&&Date.now()-t.startTimestamp>t.duration*1e3&&t.onDumpEnd())}})}};d(zn,"Name","Debug"),d(zn,"autoStart",!0);var Ad=zn;var jf=o=>{switch(o){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},Cd=class{constructor(i,e,t){d(this,"trackDoneOB");d(this,"startOB");d(this,"stopOB");d(this,"inputFrameCount",0);d(this,"decodedFrameCount",0);d(this,"type","auto");d(this,"config");d(this,"decoder");d(this,"_decodeSink");let{kvStatManager:r,trtc:s}=i;this.config=t.config,this.trackDoneOB=de(e,q.INIT),this.stopOB=ot(),this.startOB=ot(),t.type==="auto"?this.type="webCodecs":this.type=t.type;let n=ot(),a=c=>{let l=this.pipe(e);return n.next("STARTING"),e.log.info(`decoder type: ${this.type}`),le(l,ke(this.stopOB),Ee(()=>{},u=>{e.log.error(u),r.addFailedEvent({key:jf(this.type),error:u}),c>4?this.startOB.error(u):this.startOB.next(c+1)})),le(l,or(1),ph(Vn))};le(this.startOB,xn(0),Or(a),ke(this.stopOB),Ee(()=>{e.player.setOutput(),n.next("STARTED")},c=>{n.next("FAILED")},()=>{r.addSuccessEvent({key:jf(this.type)}),r.addSuccessEvent({key:504702})}))}mock(i){this._decodeSink?this._decodeSink.error(i):this.startOB.next(0)}close(i){this.stopOB.next(i)}pipe(i){return rr()(e=>f(this,null,function*(){this._decodeSink=e,e.defer(()=>{var r;(r=this.decoder)==null||r.close()});let{type:t}=this;try{switch(t){case"webCodecs":this.decoder=new AudioDecoder({error:r=>{i.log.error(r),e.error(4)},output:r=>{this.decodedFrameCount++,e.next(r),i.player.write(r)}});break;case"wasm":break}this.decoder.configure(this.config)}catch(r){i.log.error(r),e.error(t==="webCodecs"?2:6)}}))}decodeFrame(i){var e;this.inputFrameCount++,((e=this.decoder)==null?void 0:e.state)==="configured"&&this.decoder.decode(new EncodedAudioChunk({data:i.data,timestamp:i.timestamp,type:"key"}))}},YS={type:"object"},Qn=class Qn{constructor(i){this.core=i;d(this,"log");d(this,"contextMap",new Map);d(this,"decodeProcessorMap",new WeakMap);this.log=i.log.createChild({id:`${this.getAlias()}`})}getAlias(){return Qn.Name}getGroup(i){return i.track.userId+i.track.streamType}getName(){return Qn.Name}getValidateRule(i){return YS}start(i){let{track:e}=i;this.decodeProcessorMap.set(e,this.decode(i)),this.core.room.audioManager.addDecodeProcessor({processor:({frame:t,track:r})=>this.decodeProcessorMap.has(r)?this.decodeProcessorMap.get(r)({frame:t,track:r}):t,type:3})}decode(i){return({frame:e,track:t})=>{if(t!==i.track)return e;if(this.contextMap.has(t))return this.contextMap.get(t).decodeFrame(e);let r=new Cd(this.core,t,i);return le(r.trackDoneOB,or(1),Ee(()=>{this.core.clearStarted(this,this.getGroup(i)),this.stop({track:t})})),this.contextMap.set(t,r),r.decodeFrame(e)}}stop({track:i}){let e=this.contextMap.get(i);e&&(e.close("stop"),this.contextMap.delete(i),this.contextMap.size===0&&this.core.room.audioManager.removeDecodeProcessor({type:3}))}update(i){let e=this.contextMap.get(i.track);if(e){if(i.type==="mock"){e.mock(10);return}e.close("update"),this.contextMap.set(i.track,new Cd(this.core,i.track,i))}}};d(Qn,"Name","TRTCAudioDecoder");var Yn=Qn;var Rd=class{constructor(){d(this,"log");this.log=R.createLogger({id:"exp"})}call(i,e){return f(this,null,function*(){return ue(this[i])?this[i](e):Promise.reject(new D({code:I.INVALID_PARAMETER,message:H({key:B.API_NOT_EXIST,data:{name:i}})}))})}enableAudioFrameEvent(i){return f(this,null,function*(){let{trtcInstance:e,enable:t,userId:r,sampleRate:s=48e3,channelCount:n=1,port:a}=i,{audioManager:c}=e.room,{getPCMAbortCtrlMap:l,audioFrameEventConfigMap:u}=c;if(u.set(r,{enable:t,sampleRate:s,channelCount:n,port:a}),t)if(r==="*")e.room.remotePublishedUserMap.forEach(h=>{if(h.remoteAudioTrack.isAvailable){if(l.get(h.userId))return;let m=c.getPCM(_=>{e.emit(x.AUDIO_FRAME,_)},h.userId);l.set(h.userId,m)}});else{if(l.get(r))return;let h=c.getPCM(m=>{e.emit(x.AUDIO_FRAME,m)},r);l.set(r,h)}else if(r==="*")e.room.remotePublishedUserMap.forEach(h=>{if(h.remoteAudioTrack.isSubscribed){let{userId:m}=h,_=l.get(m);_==null||_.abort("disable"),l.delete(m)}});else{let h=l.get(r);h==null||h.abort("disable"),l.delete(r)}})}resumeRemotePlayer(i){return f(this,null,function*(){if(i.userId==="*"){let t=[];return i.trtcInstance.room.remotePublishedUserMap.forEach(r=>{let{remoteAudioTrack:s,remoteVideoTrack:n,remoteAuxiliaryTrack:a}=r;i.streamType?i.streamType==="main"?(s.isAvailable&&t.push(s.player.resume()),n.isAvailable&&t.push(n.player.resume())):a.isAvailable&&t.push(a.player.resume()):(s.isAvailable&&t.push(s.player.resume()),n.isAvailable&&t.push(n.player.resume()),a.isAvailable&&t.push(a.player.resume()))}),Promise.all(t)}let e=i.trtcInstance.room.remotePublishedUserMap.get(i.userId);if(e)return i.streamType==="main"?Promise.all([e.remoteAudioTrack.player.resume(),e.remoteVideoTrack.player.resume()]):e.remoteAuxiliaryTrack.player.resume()})}pauseRemotePlayer(i){if(i.userId==="*")i.trtcInstance.room.remotePublishedUserMap.forEach(e=>{let{remoteAudioTrack:t,remoteVideoTrack:r,remoteAuxiliaryTrack:s}=e;i.streamType?i.streamType==="main"?(t.isAvailable&&t.player.pause(),r.isAvailable&&r.player.pause()):s.isAvailable&&s.player.pause():(t.isAvailable&&t.player.pause(),r.isAvailable&&r.player.pause(),s.isAvailable&&s.player.pause())});else{let e=i.trtcInstance.room.remotePublishedUserMap.get(i.userId);e&&(i.streamType==="main"?(e.remoteAudioTrack.player.pause(),e.remoteVideoTrack.player.pause()):e.remoteAuxiliaryTrack.player.pause())}}};O([Sf({name:"options",type:"object",required:!0,properties:{enable:{required:!0,type:"boolean"},userId:{required:!0,type:"string"},sampleRate:{type:"number",values:[8e3,16e3,32e3,44100,48e3]},channelCount:{type:"number",values:[1,2]},port:{type:"messageport"}}})],Rd.prototype,"enableAudioFrameEvent",1);var Xf=new Rd;var zf=Je(at(),1);var Gh=class extends zf.EventEmitter{constructor(){super();d(this,"states",{});d(this,"permissionChangeHandler");d(this,"log");this.log=R.createLogger({id:"pm"}),this.permissionChangeHandler=()=>{var e,t;this.emit("permission-state-change",{camera:(e=this.states.camera)==null?void 0:e.state,microphone:(t=this.states.microphone)==null?void 0:t.state})}}request(e){return f(this,null,function*(){if(this.log.info(`request ${e.join(", ")}`),e.length===0)return Promise.resolve();(yield navigator.mediaDevices.getUserMedia({video:e.includes("camera"),audio:e.includes("microphone")})).getTracks().forEach(r=>r.stop())})}get(e){return f(this,null,function*(){try{return this.states[e]||(this.states[e]=yield navigator.permissions.query({name:e}),this.states[e].addEventListener("change",this.permissionChangeHandler)),this.log.info(`get ${e} permission state: ${this.states[e].state}`),this.states[e].state}catch(t){return this.log.error(`get ${e} permission failed, error: ${t instanceof Error?t.message:t}`),null}})}destroy(){Object.values(this.states).forEach(e=>{e==null||e.removeEventListener("change",this.permissionChangeHandler)}),this.states={}}},Zn=new Gh;var Qf=0,Kn=new Set,Qe=null;Jd(Nh);ts.checkStorage();var J=class J extends Yf.EventEmitter{constructor(e,t){super();d(this,"_room");d(this,"_eventListened",new Set);d(this,"_localVideoTrack",null);d(this,"_localAudioTrack",null);d(this,"_localScreenTrack",null);d(this,"_localScreenAudioTrack",null);d(this,"_localVideoConfig",null);d(this,"_localScreenConfig",null);d(this,"_localAudioConfig",null);d(this,"_remoteVideoConfigMap",new Map);d(this,"_remoteAudioConfigMap",new Map);d(this,"_remoteAudioVolumeMap",new Map);d(this,"_remoteAudioMuteMap",new Map);d(this,"_mediaTrackMap",new WeakMap);d(this,"_log",R.createLogger({id:`t${++Qf}`}));d(this,"_plugins",new Map);d(this,"_networkQuality",null);d(this,"_speakerId");d(this,"enterRoomParams");d(this,"_enableAutoSwitchWhenRecapturing",!0);this._room=new e(M({logger:this._log,frameWorkType:J.frameWorkType},t)),this._room.videoDecodeFallbackType=t.videoDecodeFallback,me(t.enableAutoSwitchWhenRecapturing)&&(this._enableAutoSwitchWhenRecapturing=t.enableAutoSwitchWhenRecapturing),this._log.info(`create() ${JSON.stringify(t,(r,s)=>r==="plugins"?s.map(n=>n.Name):s)}`),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(r){return this._room.audioManager.dump(r)}}}),t.plugins&&t.plugins.forEach(r=>{this._use(r,t.assetsPath)}),this._use(gd,t.assetsPath),this._use(fd,t.assetsPath),this._use(Ed,t.assetsPath),this._use(Yn,t.assetsPath),this._use(Ad),t.enableSEI&&En&&this._use(Sd),this._room.on("audio-volume",r=>{var s,n;!r.find(a=>a.userId==="")&&this._localAudioTrack&&r.push({userId:"",volume:Math.floor(((s=this._localAudioTrack.getInternalAudioLevelAfter3A())!=null?s:this._localAudioTrack.getAudioLevel())*100),floatVolume:(n=this._localAudioTrack.getInternalAudioLevelAfter3A())!=null?n:this._localAudioTrack.getInternalAudioLevel()}),t.volumeType===1&&r.forEach(a=>{var l;let c=a.userId===""?this._localAudioTrack:(l=this.room.remotePublishedUserMap.get(a.userId))==null?void 0:l.remoteAudioTrack;c&&(a.volume=c.dbVolume)}),t.enableDbVolume&&r.forEach(a=>{var l;let c=a.userId===""?this._localAudioTrack:(l=this.room.remotePublishedUserMap.get(a.userId))==null?void 0:l.remoteAudioTrack;c&&(a.volume=c.dbVolume)}),this.emit(x.AUDIO_VOLUME,{result:r.sort((a,c)=>c.volume-a.volume)})}),this._room.videoManager.on("error",r=>{this._log.error(new V({code:$.OPERATION_FAILED,extraCode:5504,message:r.message,originError:r}))}),this._listenEvents(),this._initActiveSpeaker(),Bf(this,"trtc")}static create(e){}static _create(e,t){Cf();let r=new J(e,t||{});return Kn.add(r),r.__v_skip=!0,r}get room(){return this._room}_listenEvents(){tt(this,this._room).add("peer-join",e=>{let{userId:t}=e;this.emit(x.REMOTE_USER_ENTER,{userId:t})}).add("peer-leave",e=>{this.emit(x.REMOTE_USER_EXIT,{userId:e})}).add("banned",e=>{Lt(!0),this._exitRoom().finally(()=>{this.emit(x.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().finally(()=>{this.emit(x.ERROR,V.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(x.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let t=L(M({},e),{uplinkRTT:Math.min(e.uplinkRTT,$s),downlinkRTT:Math.min(e.downlinkRTT,$s)});this.emit(x.NETWORK_QUALITY,t)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(r=>{tt(r,r).add("player-state-changed",s=>{let n=L(M({},s),{userId:e.userId});r.kind===p.VIDEO&&(n.streamType=Pi(r.streamType)),this.emit(r.kind===p.AUDIO?x.AUDIO_PLAY_STATE_CHANGED:x.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",s=>{s.getCode()===I.PLAY_NOT_ALLOWED&&this.emit(x.AUTOPLAY_FAILED,{userId:r.userId,mediaType:r.strMediaType,resume:()=>r.player.resume()})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(r=>{Le(r)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:t})=>{let{userId:r}=t,s=e.audioAvailable,n=e.videoAvailable,{audioAvailable:a,videoAvailable:c}=t;a||this._remoteAudioConfigMap.delete(r),c||this._removeRemoteVideoConfig(r,"main"),t.hasAuxiliary||this._removeRemoteVideoConfig(r,"sub"),n!==c&&(c?this._onVideoAvailable({userId:r,streamType:"main"}):this._onVideoUnavailable({userId:r,streamType:"main"}),this.emit(c?x.REMOTE_VIDEO_AVAILABLE:x.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"main"})),s!==a&&(a?this._onAudioAvailable({userId:r}):this._onAudioUnavailable({userId:r,muteState:t}),this.emit(a?x.REMOTE_AUDIO_AVAILABLE:x.REMOTE_AUDIO_UNAVAILABLE,{userId:r})),e.hasAuxiliary!==t.hasAuxiliary&&(t.hasAuxiliary?this._onVideoAvailable({userId:r,streamType:"sub"}):this._onVideoUnavailable({userId:r,streamType:"sub"}),this.emit(t.hasAuxiliary?x.REMOTE_VIDEO_AVAILABLE:x.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"sub"}))}).add("sei-message",e=>{this.emit(x.SEI_MESSAGE,L(M({},e),{streamType:Pi(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(x.ERROR,new V({code:$.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var s,n,a,c,l,u,h;let t={2:"big",3:"small",7:"sub"},r={rtt:Math.min(e.msg_up_stream_info.msg_network_status.uint32_rtt||((s=e.msg_down_stream_info[0])==null?void 0:s.msg_network_status.uint32_rtt)||((n=this._networkQuality)==null?void 0:n.uplinkRTT)||((a=this._networkQuality)==null?void 0:a.downlinkRTT)||0,$s),upLoss:((c=this._networkQuality)==null?void 0:c.uplinkLoss)||0,downLoss:((l=this._networkQuality)==null?void 0:l.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((u=e.msg_up_stream_info.msg_audio_status)==null?void 0:u.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((h=e.msg_up_stream_info.msg_audio_status)==null?void 0:h.uint32_audio_level)||0)/Dt},video:e.msg_up_stream_info.msg_video_status.filter(m=>t[m.uint32_video_stream_type]).map(m=>({bitrate:(m.uint32_video_codec_bitrate||0)/1e3,width:m.uint32_video_width,height:m.uint32_video_height,frameRate:m.uint32_video_enc_fps,videoType:t[m.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(m=>({userId:m.msg_user_info.str_identifier,audio:{bitrate:(m.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(m.msg_audio_status.uint32_audio_level||0)/Dt,point2pointDelay:(m.msg_audio_status.uint32_audio_p2p_delay||0)+(m.msg_audio_status.uint32_audio_cache_ms||0),jitterBufferDelay:m.msg_audio_status.uint32_audio_cache_ms||0},video:m.msg_video_status.map(_=>({bitrate:(_.uint32_video_codec_bitrate||0)/1e3,width:_.uint32_video_width,height:_.uint32_video_height,frameRate:_.uint32_video_dec_fps,videoType:t[_.uint32_video_stream_type],point2pointDelay:(_.uint32_video_p2p_delay||0)+(_.uint32_video_cache_ms||0),jitterBufferDelay:_.uint32_video_cache_ms||0,codec:_.uint32_video_codec}))}))};this.emit(x.STATISTICS,r)}).add("custom-message",e=>{this.emit(x.CUSTOM_MESSAGE,e)}).add("layerData",e=>this.emit(x.LAYER_DATA,e)).add("first-video-frame",e=>{this.emit(x.FIRST_VIDEO_FRAME,L(M({},e),{streamType:Pi(e.streamType)}))}).add("audio-frame",e=>{this.emit(x.AUDIO_FRAME,e)}),tt(this,be).add("audioInputAdded",e=>{this.emit(x.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(x.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(x.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(x.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>f(this,null,function*(){if(this.emit(x.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Qe&&Qe.deviceId===Hs){let t=(yield Nr()).find(r=>r.deviceId===Hs);t&&Qe.groupId!==t.groupId&&(Qe=t,this.emit(x.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}})).add("audioOutputRemoved",e=>f(this,null,function*(){this.emit(x.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield Nr())[0];if(!t||!Qe||Qe.groupId===t.groupId)return;let r=Qe.deviceId===e.deviceId,s=Qe.deviceId===Hs&&Qe.deviceId===t.deviceId;(r||s)&&(Qe=t,this.emit(x.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))})),tt(this,Zn).add("permission-state-change",e=>{this.emit(x.PERMISSION_STATE_CHANGE,e)}),this.room.enableSEI&&this.on(x.SEI_MESSAGE,e=>{var r;let t=(r=this.room.remotePublishedUserMap.get(e.userId))==null?void 0:r.remoteVideoTrack;t&&t.updateAlphaRenderInfo(e)})}getNetworkTime(){return Bi()}use(e){let t,r;return"plugin"in e?(t=e.plugin,r=e.assetsPath):t=e,t.Name==="Chorus"&&(this.room.enableChorus=!0),this._use(t,r)}_use(e,t){let r=this._plugins.get(e.Name);if(r)return this._log.warn("duplicate install plugin",e.Name),r;let s=new e(Vf.call(this,{TRTC:J,room:this._room,assetsPath:t,errorModule:{RtcError:V,ErrorCode:$,CoreErrorCode:I,ErrorCodeDictionary:wt}}));return this._plugins.set(e.Name,s),s.__v_skip=!0,e.autoStart&&this.startPlugin(e.Name),s}enterRoom(e){return f(this,null,function*(){var c,l;this.enterRoomParams=e;let{scene:t="rtc",enableAutoPlayDialog:r=!0,autoReceiveAudio:s=!0,autoReceiveVideo:n=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!ie(e.proxy)&&e.proxy.turnServer&&((l=(c=this._room).setTurnServer)==null||l.call(c,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=r,this._room.autoReceiveAudio=s,this._room.autoReceiveVideo=n,me(e.preferHW)&&(this._room.preferHW=e.preferHW),e.playoutDelay&&(this._room.playoutDelay=e.playoutDelay),e.jitterBufferDelay&&(this._room.jitterBufferDelay=e.jitterBufferDelay);let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:e.role==="audience"?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language,priority:e.priority,useVp8:e.useVp8,useH265:e.useH265||!1,keepAlive:e.keepAlive,videoProfileLevel:e.videoProfileLevel};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(a,t,J.frameWorkType),this._checkTrackToPublish(),wh.start()})}exitRoom(){return f(this,null,function*(){return yield this._exitRoom()})}switchRoom(e){return f(this,null,function*(){if(this.room.isSwitchRoomSupported())try{this._clearRemoteTracks(),yield this._room.switchRoom(e)}catch(t){if(t instanceof ws&&(t.code===I.API_CALL_TIMEOUT||t.code===I.SWITCH_ROOM_FAILED))this._log.warn(`switchRoom ${t.code===I.API_CALL_TIMEOUT?"timeout":"failed"}, fallback to exitRoom() and enterRoom()`),yield this._rejoinRoom(e);else throw t}else yield this._rejoinRoom(e)})}_rejoinRoom(e){return f(this,null,function*(){yield this.exitRoom();let t=M(M({},this.enterRoomParams),e);yield this.enterRoom(t)})}_clearRemoteTracks(){new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(e=>{this._stopRemoteAudio({userId:e}).catch(()=>{})}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let t=e.includes("main")?"main":"sub",r=e.split(`_${t}`)[0];r&&this._stopRemoteVideo({userId:r,streamType:t}).catch(()=>{})}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),Ff(this),this._room.remotePublishedUserMap.forEach(e=>{Le(e.remoteAudioTrack),Le(e.remoteVideoTrack),Le(e.remoteAuxiliaryTrack)})}switchRole(e,t){return f(this,null,function*(){t!=null&&t.privateMapKey&&(this._room.privateMapKey=t.privateMapKey),t!=null&&t.latencyLevel&&(this._room.latencyLevel=t.latencyLevel),yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){this._plugins.forEach(e=>{var t;return(t=e.destroy)==null?void 0:t.call(e)}),this._plugins.clear(),Le(this),this.removeAllListeners(),this._room.destroy(),Kn.delete(this),Kn.size===0&&wh.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),S.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return f(this,arguments,function*(e={publish:!0}){if(this._localAudioTrack){this._log.warn("local audio is already started");return}let{publish:t=!0,mute:r,option:s}=e,n=new kt(this._room.audioManager),a={},c={muted:!0};s&&(T(s.microphoneId)?T(s.audioTrack)||(a.customSource=s.audioTrack):a.deviceId=s.microphoneId,s&&Q(s.captureVolume)&&n.setCaptureVolume(s.captureVolume),T(s.profile)||(ie(s.profile)?fa[s.profile]&&n.setProfile(fa[s.profile]):n.setProfile(s.profile)),Q(s.earMonitorVolume)&&(c.muted=!(s.earMonitorVolume>0),c.volume=s.earMonitorVolume),T(s.echoCancellation)||(n.profile.echoCancellation=s.echoCancellation),T(s.noiseSuppression)||(n.profile.noiseSuppression=s.noiseSuppression),T(s.autoGainControl)||(n.profile.autoGainControl=s.autoGainControl),me(this._enableAutoSwitchWhenRecapturing)&&(n.enableAutoSwitchWhenRecapturing=this._enableAutoSwitchWhenRecapturing)),n.on("5",l=>{this.emit(x.ERROR,new V({code:$.DEVICE_ERROR,extraCode:5309,messageParams:{error:l}}))}),n.on("2",l=>{this.emit(x.DEVICE_CHANGED,{type:"microphone",action:"active",device:l})}),n.on("4",l=>{let u;l.error&&(u=V.convertFrom(l.error)),this.emit(x.PUBLISH_STATE_CHANGED,L(M({},l),{error:u}))}),n.on("6",()=>{}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId),yield n.capture(a),T(r)||n.setMute(r),tt(n,n).add("player-state-changed",l=>{this.emit(x.AUDIO_PLAY_STATE_CHANGED,L(M({},l),{userId:""}))}),t&&this._room.isJoined&&this._room.publish(n).catch(()=>{}),this._localAudioTrack=n,this._localAudioConfig=L(M({},e),{publish:t}),yield this._updateAudioPlayOption({playOption:c,track:n}),S.emit("113",{userId:"",room:this.room})})}updateLocalAudio(e){return f(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:r,option:s}=e,n={};s&&(s.microphoneId?yield this._localAudioTrack.switchDevice(s.microphoneId):T(s.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(s.audioTrack)),T(s.captureVolume)||this._localAudioTrack.setCaptureVolume(s.captureVolume),T(s.earMonitorVolume)||(n.muted=!(s.earMonitorVolume>0),n.volume=s.earMonitorVolume),yield this._localAudioTrack.update3A(s)),this._room.isJoined&&!T(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),T(r)||this._localAudioTrack.setMute(r),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),ti(this._localAudioConfig,e)})}stopLocalAudio(){return f(this,null,function*(){this._localAudioTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),S.emit("114",{userId:"",room:this.room}),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),Le(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)})}startLocalVideo(){return f(this,arguments,function*(e={publish:!0,view:null,capture:!0}){var h;if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:t,publish:r=!0,capture:s=!0,mute:n,option:a}=e,c=new Xe(this._room.videoManager),l={},u={};a&&(me(a.avoidCropping)&&(c.avoidCropping=a.avoidCropping),a.cameraId?l.deviceId=a.cameraId:T(a.useFrontCamera)?T(a.videoTrack)||(l.customSource=a.videoTrack):l.facingMode=a.useFrontCamera?p.FACING_MODE_USER:p.FACING_MODE_ENVIRONMENT,T(a.retryWhenExactFailed)||(l.retryWhenExactFailed=a.retryWhenExactFailed),a.qosPreference&&(l.contentHint=Jn(a.qosPreference)),T(a.profile)||(ie(a.profile)?Qt[a.profile]&&c.setProfile(Qt[a.profile]):c.setProfile(a.profile)),T(a.fillMode)||(u.objectFit=a.fillMode),T(a.mirror)||(u.mirror=a.mirror),T(a.small)||(T(a.smallMode)||(this._room.smallMode=a.smallMode),me(a.small)&&a.small===!1?c.stopSmall():c.updateSmallConfig(Is(a.small,!0))),T(a.rotation)||c.setRotation(a.rotation),me(this._enableAutoSwitchWhenRecapturing)&&(c.enableAutoSwitchWhenRecapturing=this._enableAutoSwitchWhenRecapturing)),c.once("first-video-frame",m=>{this.emit(x.FIRST_VIDEO_FRAME,L(M({},m),{streamType:Pi(m.streamType)}))}),c.on("5",m=>{this.emit(x.ERROR,new V({code:$.DEVICE_ERROR,extraCode:5308,messageParams:{error:m}}))}),c.on("2",m=>{this.emit(x.DEVICE_CHANGED,{type:"camera",action:"active",device:m})}),c.on("4",m=>{let _;m.error&&(_=V.convertFrom(m.error)),this.emit(x.PUBLISH_STATE_CHANGED,L(M({},m),{error:_}))}),c.on("6",()=>{}),this._listenOutputTrackChanged(c),s?yield c.capture(l):(h=c.manager)==null||h.changeInput(c),T(n)||(yield c.setMute(n)),tt(c,c).add("player-state-changed",m=>{this.emit(x.VIDEO_PLAY_STATE_CHANGED,L(M({},m),{userId:"",streamType:"main"}))}).add("video-size-changed",m=>{this.emit(x.VIDEO_SIZE_CHANGED,L(M({},m),{streamType:Pi(m.streamType)}))}),r&&this._room.isJoined&&this._room.publish(c).catch(()=>{}),this._localVideoTrack=c,this._localVideoConfig=L(M({},e),{view:t,publish:r,capture:s}),yield this._updateVideoPlayOption({view:t,playOption:u,track:c})})}updateLocalVideo(e){return f(this,null,function*(){var l,u,h;if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:r,mute:s,capture:n,option:a}=e,c={};if(this._localVideoConfig.capture)n!==!1?a!=null&&a.cameraId?yield this._localVideoTrack.switchDevice(a==null?void 0:a.cameraId):T(a==null?void 0:a.useFrontCamera)?T(a==null?void 0:a.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(a==null?void 0:a.videoTrack)):yield this._localVideoTrack.switchDevice(a!=null&&a.useFrontCamera?p.FACING_MODE_USER:p.FACING_MODE_ENVIRONMENT):this._localVideoTrack.stopCapture();else if(n){let m={};m.deviceId=(a==null?void 0:a.cameraId)||((l=this._localVideoConfig.option)==null?void 0:l.cameraId),m.facingMode=a!=null&&a.useFrontCamera||(u=this._localVideoConfig.option)!=null&&u.useFrontCamera?p.FACING_MODE_USER:p.FACING_MODE_ENVIRONMENT,m.customSource=(a==null?void 0:a.videoTrack)||((h=this._localVideoConfig.option)==null?void 0:h.videoTrack),yield this._localVideoTrack.capture(m)}a&&(T(a.profile)||(ie(a.profile)?Qt[a.profile]&&this._localVideoTrack.setProfile(Qt[a.profile]):this._localVideoTrack.setProfile(a.profile),(!a.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(a.cameraId))&&T(a.useFrontCamera)&&(yield this._localVideoTrack.applyProfile())),T(a.fillMode)||(c.objectFit=a.fillMode),T(a.mirror)||(c.mirror=a.mirror),T(a.rotation)||this._localVideoTrack.setRotation(a.rotation),a.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(Jn(a.qosPreference)),T(a.small)||(me(a.small)&&!a.small?this._localVideoTrack.stopSmall():this._localVideoTrack.updateSmallConfig(Is(a.small,!0)))),this._room.isJoined&&T(r)&&this._localVideoConfig.publish&&n&&!this._localVideoConfig.capture&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._room.isJoined&&((r!=null?r:this._localVideoConfig.publish)?this._room.publish(this._localVideoTrack).catch(()=>{}):this._room.unpublish(this._localVideoTrack).catch(()=>{})),T(s)||(yield this._localVideoTrack.setMute(s)),yield this._updateVideoPlayOption({view:t,playOption:c,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),ti(this._localVideoConfig,e)})}stopLocalVideo(){return f(this,null,function*(){this._localVideoTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),Le(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return f(this,arguments,function*(e={publish:!0,view:null}){var m,_;if(this._localScreenTrack){this._log.warn("screen share is already started");return}let{view:t=null,publish:r=!0,muteSystemAudio:s,option:n}=e,a=new Pt(this._room.videoManager);a.on("4",g=>{let E;g.error&&(E=V.convertFrom(g.error)),this.emit(x.PUBLISH_STATE_CHANGED,L(M({},g),{error:E}))}),a.once("first-video-frame",g=>{this.emit(x.FIRST_VIDEO_FRAME,L(M({},g),{streamType:Pi(g.streamType)}))}),this._listenOutputTrackChanged(a),e.streamType==="main"&&(a.mediaType=4);let c=null,l={},u={};n&&(T(n.profile)||(ie(n.profile)?_a[n.profile]&&a.setProfile(_a[n.profile]):a.setProfile(n.profile)),n.systemAudio&&(l.systemAudio=!0,l.echoCancellation=n.echoCancellation,l.noiseSuppression=n.noiseSuppression,l.autoGainControl=n.autoGainControl),T(n.fillMode)||(u.objectFit=n.fillMode),n.videoTrack&&(l.videoTrack=n.videoTrack),n.audioTrack&&(l.audioTrack=n.audioTrack),n.captureElement&&(l.captureElement=n.captureElement),n.preferDisplaySurface&&(l.preferDisplaySurface=n.preferDisplaySurface),n.qosPreference&&(l.contentHint=Jn(n.qosPreference)));let h=yield a.capture(l);if(a.mediaTrack.addEventListener(p.ENDED,()=>{this._stopScreenShare(),this.emit(x.SCREEN_SHARE_STOPPED)}),h.getAudioTracks()[0]){c=new To(this._room.audioManager);let g=h.getAudioTracks()[0];(m=e.option)!=null&&m.systemAudio&&!((_=e.option)!=null&&_.audioTrack)&&(c.sourceTrack=g),yield c.setInputMediaStreamTrack(g),me(s)&&c.mediaTrack&&(c.mediaTrack.enabled=!s),this._speakerId&&c.setAudioOutput(this._speakerId)}if(tt(a,a).add("player-state-changed",g=>{this.emit(x.VIDEO_PLAY_STATE_CHANGED,L(M({},g),{userId:"",streamType:"sub"}))}),r&&this._room.isJoined){let g=[a];c&&(g.push(c),this._checkScreenAudioEchoCancellation(a,c)),g.forEach(E=>this._room.publish(E).catch(()=>{}))}this._localScreenTrack=a,this._localScreenAudioTrack=c,this._localScreenConfig=L(M({},e),{view:t,publish:r}),yield this._updateVideoPlayOption({view:t,playOption:u,track:a})})}updateScreenShare(e){return f(this,null,function*(){var c;if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:r,muteSystemAudio:s,option:n}=e,a={};if(n&&(T(n.fillMode)||(a.objectFit=n.fillMode),n.qosPreference)){let l=Jn(n.qosPreference);this._localScreenTrack.setContentHint(l)}if(this._room.isJoined&&!T(r)){if(r&&!this._localScreenConfig.publish){let l=[this._localScreenTrack];this._localScreenAudioTrack&&l.push(this._localScreenAudioTrack),l.forEach(u=>this._room.publish(u).catch(()=>{}))}if(this._localScreenConfig.publish&&!r){let l=[this._localScreenTrack];this._localScreenAudioTrack&&l.push(this._localScreenAudioTrack),l.forEach(u=>this._room.unpublish(u).catch(()=>{}))}}(c=this._localScreenAudioTrack)!=null&&c.mediaTrack&&me(s)&&(this._localScreenAudioTrack.mediaTrack.enabled=!s),yield this._updateVideoPlayOption({view:t,playOption:a,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),ti(this._localScreenConfig,e)})}stopScreenShare(){return f(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return f(this,null,function*(){let{view:t,userId:r,streamType:s,option:n}=e,a=`${r}_${s}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${r}, streamType:${s}`);return}let c=this._room.remotePublishedUserMap.get(r);if(!c)return;let l={},u=s==="main"?c.remoteVideoTrack:c.remoteAuxiliaryTrack;u.on("decode-failed",h=>{this.emit(x.ERROR,new V({code:$.OPERATION_FAILED,extraCode:5507,message:"video decode failed"}))}),u.on("video-size-changed",h=>{this.emit(x.VIDEO_SIZE_CHANGED,L(M({},h),{streamType:Pi(h.streamType)}))}),this._listenOutputTrackChanged(u),n&&(T(n.fillMode)||(l.objectFit=n.fillMode),T(n.mirror)||(l.mirror=n.mirror),T(n.poster)||(l.poster=n.poster),l.canvasRender=n.canvasRender,s==="main"&&!T(n.small)&&(!c.remoteVideoTrack.isSubscribing&&!c.remoteVideoTrack.isSubscribed&&c.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,u.user)),T(n.draggable)||u.setDraggable(n.draggable)),yield this._room.subscribe(u),yield this._enableVideoDecodeFallback(u,s),yield this._updateVideoPlayOption({view:t,playOption:l,track:u}),this._emitTrackEvent(u),this._remoteVideoConfigMap.set(a,{config:e}),n&&!T(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:u,view:t,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:n==null?void 0:n.viewRoot})})}updateRemoteVideo(e){return f(this,null,function*(){var C,k;let{view:t,userId:r,streamType:s,option:n}=e,a=`${r}_${s}`,c=this._remoteVideoConfigMap.get(a);if(!c||!this._room.remotePublishedUserMap.has(r))return;let l={};n&&(T(n.fillMode)||(l.objectFit=n.fillMode),T(n.mirror)||(l.mirror=n.mirror));let u=null,h=this._room.remotePublishedUserMap.get(r);if(s==="main"&&(h!=null&&h.muteState.hasVideo)&&(u=h.remoteVideoTrack),s==="sub"&&(h!=null&&h.muteState.hasAuxiliary)&&(u=h.remoteAuxiliaryTrack),!u)return;let{config:m}=c;s==="main"&&n&&!T(n.small)&&this._room.changeType(n.small,u.user),n&&!T(n.draggable)&&u.setDraggable(n.draggable),yield this._updateVideoPlayOption({view:t,playOption:l,track:u,prevConfig:m}),ti(m,e);let _=T(n==null?void 0:n.receiveWhenViewVisible)?(C=m.option)==null?void 0:C.receiveWhenViewVisible:n.receiveWhenViewVisible,g=T(t)?m.view:t,E=T(n==null?void 0:n.viewRoot)?(k=m.option)==null?void 0:k.viewRoot:n.viewRoot;this._observeView({remoteTrack:u,view:g,receiveWhenViewVisible:_,viewRoot:E})})}stopRemoteVideo(e){return f(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,t=!0){return f(this,null,function*(){let r=[],s=this._room.remotePublishedUserMap.get(e.userId);if(s){let{muteState:n,remoteVideoTrack:a,remoteAuxiliaryTrack:c}=s;e.streamType==="main"&&(a.stop(),n.hasVideo&&r.push(a)),e.streamType==="sub"&&(c.stop(),n.hasAuxiliary&&r.push(c))}for(let n of r)t&&(yield this._room.unsubscribe(n),this._mediaTrackMap.delete(n.outMediaTrack));this._removeRemoteVideoConfig(e.userId,e.streamType)})}_removeRemoteVideoConfig(e,t){let r=`${e}_${t}`,s=this._remoteVideoConfigMap.get(r);s&&s.observer&&s.observer.disconnect(),this._remoteVideoConfigMap.delete(r)}muteRemoteAudio(e,t){return f(this,null,function*(){this._remoteAudioMuteMap.set(e,t);try{if(e==="*")if(t)yield this._stopRemoteAudio({userId:e});else{let r=[...this._room.remotePublishedUserMap.values()];for(let s of r)s.muteState.hasAudio&&!this._remoteAudioConfigMap.has(s.userId)&&(yield this._startRemoteAudio({userId:s.userId}))}else t?yield this._stopRemoteAudio({userId:e}):this._remoteAudioConfigMap.has(e)||(yield this._startRemoteAudio({userId:e}))}catch(r){throw r.code!==$.OPERATION_ABORT&&this._remoteAudioMuteMap.delete(e),r}})}setRemoteAudioVolume(e,t){if(e==="*"){this._remoteAudioVolumeMap.set("*",t),this._remoteAudioVolumeMap.forEach((s,n)=>this._remoteAudioVolumeMap.set(n,t));let r=[...this._room.remotePublishedUserMap.values()];for(let s of r)this._remoteAudioVolumeMap.set(s.userId,t),s.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:s.remoteAudioTrack})}else if(e){let r=this._room.remotePublishedUserMap.get(e);this._remoteAudioVolumeMap.set(e,t),r&&r.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:r.remoteAudioTrack})}}startPlugin(e,t){return f(this,null,function*(){return e.start(t)})}updatePlugin(e,t){return f(this,null,function*(){return e.update(t)})}stopPlugin(e,t){return f(this,null,function*(){return e.stop(t)})}enableAudioVolumeEvaluation(e=2e3,t=!1){this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,r){if(this.listeners(e).includes(t))return this;if(this._log.debug("on",e),super.on(e,t,r),this._eventListened.add(e),this.listeners(x.AUDIO_FRAME).length>0){let{audioFrameEventConfigMap:s}=this.room.audioManager;s.get("")||s.set("",{enable:!0}),this._localAudioTrack&&this.room.audioManager.handleLocalTrackStarted({userId:"",room:this.room})}return this}emit(e,...t){try{wf.has(e)||this._log.debug(`emit ${e} ${JSON.stringify(t)}`)}catch(r){}return super.emit(e,...t)}off(e,t,r){if(this._log.debug("off",e),e==="*"?(this._eventListened.clear(),this.removeAllListeners()):super.off(e,t,r),(e===J.EVENT.AUDIO_FRAME||e==="*")&&this.listeners(J.EVENT.AUDIO_FRAME).length===0){let{getPCMAbortCtrlMap:s}=this.room.audioManager;s.forEach(n=>{n==null||n.abort("off")}),s.clear()}return this}getAudioTrack(e={userId:"",streamType:"main"}){let t,r=null,s="main",n=!1;if(ie(e)?t=e:(t=e.userId,n=e.processed===!0,e.streamType&&(s=e.streamType)),t){let a=this._room.remotePublishedUserMap.get(t);a&&(r=a.remoteAudioTrack)}else r=s==="sub"?this._localScreenAudioTrack:this._localAudioTrack;return r?n&&r.outMediaTrack&&r.outMediaTrack!==r.mediaTrack?r.outMediaTrack.clone():r.mediaTrack:null}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:t="",streamType:r="main",processed:s=!1}=e,n=null;if(t==="")r==="main"&&this._localVideoTrack&&(n=this._localVideoTrack),r==="sub"&&this._localScreenTrack&&(n=this._localScreenTrack);else{let a=this._room.remotePublishedUserMap.get(t);a&&(n=r==="main"?a.remoteVideoTrack:a.remoteAuxiliaryTrack)}return n?s&&n.outMediaTrack&&n.outMediaTrack!==n.mediaTrack?n.outMediaTrack.clone():n.mediaTrack:null}getVideoSnapshot(e={}){let{userId:t,streamType:r="main"}=e;if(t){let s=this._room.remotePublishedUserMap.get(t);if(r==="main"&&(s!=null&&s.muteState.hasVideo))return s.remoteVideoTrack.getVideoFrame();if(r==="sub"&&(s!=null&&s.muteState.hasAuxiliary))return s.remoteAuxiliaryTrack.getVideoFrame()}else{if(r==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(r==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(e){var t,r;this._speakerId=e,(t=this._localAudioTrack)==null||t.setAudioOutput(e),(r=this._localScreenAudioTrack)==null||r.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(s=>s.remoteAudioTrack.setAudioOutput(e))}setCurrentSpeaker(e){return f(this,null,function*(){(yield Nr()).forEach(r=>{r.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(x.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}),Qe=r)}),this._log.warn(`the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: ${ft}/en/TRTC.html#.setCurrentSpeaker`)})}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return f(this,null,function*(){var a;let{userId:t}=e;if(this._remoteAudioConfigMap.has(t)){this._log.warn(`remote audio has already started. userId:${t}`);return}let r=this._room.remotePublishedUserMap.get(t);if(!r)return;let s={},n=r.remoteAudioTrack;n.on("decode-failed",c=>{this.emit(x.ERROR,new V({code:$.OPERATION_FAILED,extraCode:5508,message:"audio decode failed"}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId);try{let c=(a=this._remoteAudioVolumeMap.get(t))!=null?a:this._remoteAudioVolumeMap.get("*"),l=Q(c)?c:100;s.volume=l,this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(n),le(de(n,"decode-failed"),ke(de(n,q.INIT)),Ee(()=>{this.startPlugin(Yn.Name,{track:n,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:s,track:n}),S.emit("115",{userId:t,room:this.room}),n.outMediaTrack&&this.room.audioManager.updateAudioReference({type:"add",audioReference:n.outMediaTrack,refId:`ra-${t}`})}catch(c){throw this._remoteAudioConfigMap.delete(t),c}this._emitTrackEvent(n)})}_stopRemoteAudio(e,t=!0){return f(this,null,function*(){let r=this._room.remotePublishedUserMap.get(e.userId);r&&(r.remoteAudioTrack.stop(),r.muteState.hasAudio&&t&&(yield this._room.unsubscribe(r.remoteAudioTrack)),this._mediaTrackMap.delete(r.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete(`${e.userId}`),S.emit("116",{userId:e.userId,room:this.room}),this.room.audioManager.updateAudioReference({type:"remove",refId:`ra-${e.userId}`})})}_enableVideoDecodeFallback(e,t){let r=this._room.videoDecodeFallbackType;if(!r||!this._plugins.has("TRTCVideoDecoder"))return;e.log.debug("remote video will fall back when decode failed",e.id);let s;le(de(e,"decode-failed"),ke(de(e,q.INIT)),Fn(()=>{this._room.downlinkVideoCodec!=="h265"&&this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:r})}),mo(de(e,"decode-downgrade-state-changed")),Ee(n=>{s=n.state,this.emit(x.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,L(M({},n),{streamType:t,userId:e.userId}))},n=>{e.log.error("fallback",n)},()=>{s==="STARTED"&&e.log.info("fallback complete")}))}_updateVideoPlayOption(n){return f(this,arguments,function*({view:e,playOption:t,track:r,prevConfig:s}){if(r.setMirror(t.mirror),T(e)&&s&&s.view&&!Vo(t)){let a=Fo(s.view);a.length>0&&(yield r.play(a,t))}if(!T(e)){let a=Fo(e);a.length>0?yield r.play(a,t):r.stop()}})}_updateAudioPlayOption(s){return f(this,arguments,function*({playOption:e={},track:t,prevConfig:r}){if(!t.isPlayCalled)try{yield t.play(null,e)}catch(n){}if(T(e.muted)||t.setPlayerMute(e.muted),T(e.volume)||t.setAudioVolume(e.volume/100),t instanceof kt&&t.mediaTrack){let n=e.muted===!1&&!T(e.volume)&&e.volume>0?"add":"remove";this.room.audioManager.updateAudioReference({type:n,audioReference:t.mediaTrack,refId:"em"})}else if(t instanceof Ti){let n=e.muted?0:e.volume;if(T(n))return;this.room.audioManager.updateAudioReference({type:"updateVolume",refId:`ra-${t.userId}`,volume:e.volume})}})}_listenOutputTrackChanged(e){e.listeners("output-media-track-changed").length===0&&e.on("output-media-track-changed",()=>this._emitTrackEvent(e,!1))}_emitTrackEvent(e,t=!0){let r=e.isRemote?e.userId:"";e.outMediaTrack&&(t&&this._mediaTrackMap.get(e.outMediaTrack)===r||(this._mediaTrackMap.set(e.outMediaTrack,r),this.emit(x.TRACK,{userId:r,streamType:Pi(e.streamType),track:e.outMediaTrack,sourceTrack:e.mediaTrack})))}_checkTrackToPublish(){var t,r,s;let e=[];if((t=this._localAudioConfig)!=null&&t.publish&&this._localAudioTrack&&e.push(this._localAudioTrack),(r=this._localVideoConfig)!=null&&r.publish&&this._localVideoTrack&&e.push(this._localVideoTrack),(s=this._localScreenConfig)!=null&&s.publish&&(this._localScreenTrack&&e.push(this._localScreenTrack),this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack),this._checkScreenAudioEchoCancellation(this._localScreenTrack,this._localScreenAudioTrack)),e.length!==0)return Promise.all(e.map(n=>this._room.publish(n).catch(()=>{})))}_observeView({remoteTrack:e,view:t,receiveWhenViewVisible:r=!1,viewRoot:s}){if(T(t))return;let n=this._remoteVideoConfigMap.get(`${e.userId}_${Pi(e.streamType)}`);if(!n)return;let a=n.observer||void 0;if(t===null||Ae(t)&&t.length===0||!r){a==null||a.disconnect(),e.isSubscribed||this._room.subscribe(e).catch(()=>{});return}let l=n.visibleViewMap||new Map,u=-1;(!a||a.root!==s)&&(a==null||a.disconnect(),l.clear(),a=new IntersectionObserver(m=>{m.forEach(_=>{l.set(_.target,_.isIntersecting),e.log.info(`view ${_.target.id} is${_.isIntersecting?"":" not"} visible`)}),clearTimeout(u),u=window.setTimeout(()=>{[...l.values()].find(g=>g)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:s}));let h=new Set(Fo(t));l.forEach((m,_)=>{h.has(_)||(a.unobserve(_),l.delete(_))}),h.forEach(m=>{l.set(m,!0),a.observe(m)}),a.takeRecords().forEach(m=>{l.set(m.target,m.isIntersecting)}),n.visibleViewMap=l,n.observer=a}_exitRoom(){return f(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),this._clearRemoteTracks()})}_stopScreenShare(){return f(this,null,function*(){var e;if(this._localScreenTrack){if(this._room.isJoined){let t=[this._localScreenTrack];this._localScreenAudioTrack&&t.push(this._localScreenAudioTrack),yield Promise.all(t.map(r=>this._room.unpublish(r).catch(()=>{})))}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(((e=this._localScreenAudioTrack.trackSettings)==null?void 0:e.echoCancellation)===!1&&this.stopPlugin("AudioProcessor"),this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),Le(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_checkScreenAudioEchoCancellation(e,t){return f(this,null,function*(){var s,n;if(!e||!t)return;let r=(s=e.trackSettings)==null?void 0:s.displaySurface;if(((n=t.trackSettings)==null?void 0:n.echoCancellation)===!1&&(r==="monitor"||r==="browser"&&e.isShareCurrentTab)){this._log.warn("echoCancellation of screen audio track is disable. Try starting audioProcessor plugin");try{yield this.startPlugin("AudioProcessor",{sdkAppId:Number(this.room.sdkAppId),userId:this._room.userId,userSig:this.room.userSig,isScreenAudioNeedAudioProcess:!0,isLocalAudioNeedAudioProcess:!1})}catch(a){this._log.warn("start audioProcessor plugin failed: ",a)}}})}_onLocalTrackCaptured({track:e}){e.kind==="audio"&&(!Qe||us(Qe))&&(this._initActiveSpeaker(),S.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return f(this,null,function*(){if(Qe&&!us(Qe))this.emit(x.DEVICE_CHANGED,{type:"speaker",action:"active",device:Qe});else{let e=yield Nr();e[0]&&!us(e[0])?(Qe=e[0],this.emit(x.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):S.on("102",this._onLocalTrackCaptured,this)}})}_onAudioAvailable({userId:e}){let t=this._remoteAudioMuteMap.has(e)?this._remoteAudioMuteMap.get(e):this._remoteAudioMuteMap.get("*");(t===!1||this._room.autoReceiveAudio&&!t)&&this._doStartRemoteAudio({userId:e}).catch(()=>{})}_onVideoAvailable({userId:e,streamType:t}){if(!this._room.autoReceiveVideo)return;let r=this._room.remotePublishedUserMap.get(e);if(r){let s=t==="main"?r.remoteVideoTrack:r.remoteAuxiliaryTrack,n=[s];this._room.autoReceiveAudio&&r.remoteAudioTrack.isAvailable&&n.push(r.remoteAudioTrack),this._room.subscribe(...n).then(()=>{this._emitTrackEvent(s)}).catch(()=>{})}}_onAudioUnavailable({userId:e,muteState:t}){t.hasAudio&&t.audioMuted||this._stopRemoteAudio({userId:e},!1).catch(()=>{})}_onVideoUnavailable({userId:e,streamType:t}){this._stopRemoteVideo({userId:e,streamType:t},!1).catch(()=>{})}sendSEIMessage(e,t){var s;let r=this._plugins.get("SEI");r&&(r.update({buffer:e,options:L(M({seiPayloadType:243},t),{small:!!((s=this._localVideoTrack)!=null&&s.small)})}),v.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,r;(r=(t=this._room).sendCustomMessage)==null||r.call(t,e),v.addCount({key:500001,useUV:!0})}callExperimentalAPI(e,t){return f(this,null,function*(){return this._log.info(`callExperimentalAPI(${e}, ${JSON.stringify(t)})`),Xf.call(e,M({trtcInstance:this},t))})}static setLogLevel(e,t){R.setLogLevel(e),T(t)||(t?R.enableUploadLog():R.disableUploadLog())}static isSupported(){return _c(J.frameWorkType)}static getPermissions(r){return f(this,arguments,function*({request:e=!0,types:t=["camera","microphone"]}){e&&(yield Zn.request(t).catch(a=>{var c;return R.error(`getPermissions request failed, error: ${(c=a==null?void 0:a.message)!=null?c:a}`)}));let[s,n]=yield Promise.all([Zn.get("camera"),Zn.get("microphone")]);return{camera:s,microphone:n}})}static getCameraList(e=!0){return At(e)}static getMicrophoneList(e=!0){return It(e)}static getSpeakerList(e=!0){return Nr(e)}static setCurrentSpeaker(e){return f(this,null,function*(){if(_e&&(e===So.SPEAKER||e===So.HEADSET)){let r=yield J.getMicrophoneList(),s="";if(r.forEach(n=>{n.label===e&&(s=n.deviceId)}),!s)return;Kn.forEach(n=>f(this,null,function*(){n._localAudioTrack&&(yield n.updateLocalAudio({option:{microphoneId:s}}))}));return}(yield Nr()).forEach(r=>{r.deviceId===e&&(Kn.forEach(s=>{s._setCurrentSpeaker(e),s.emit(x.DEVICE_CHANGED,{type:"speaker",action:"active",device:r})}),Qe=r)})})}static _addKVStat({type:e,key:t,value:r,base:s,useUV:n,version:a,max:c}){switch(a&&(ro.version=a),e){case"count":ro.addCount({key:t,useUV:n});break;case"enum":ro.addEnum({key:t,value:r,useUV:n});break;case"number":ro.addNumber({key:t,value:r,split:s,max:c});break}}};d(J,"VERSION",Nh),d(J,"_loggerManager",R),d(J,"EVENT",x),d(J,"ERROR_CODE",$),d(J,"TYPE",So),d(J,"frameWorkType",30),O([Ce({replaceArg:e=>({argIndex:0,value:{name:"plugin"in e?e.plugin.Name:e.Name,assetsPath:"assetsPath"in e?e==null?void 0:e.assetsPath:"default"}})})],J.prototype,"use",1),O([st(Ge.TRTC.enterRoom),wr("room",([e],[t])=>(e.roomId||e.strRoomId)===(t.roomId||t.strRoomId)&&e.userId===t.userId&&e.sdkAppId===t.sdkAppId),Y(e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)}),Ce()],J.prototype,"enterRoom",1),O([Ce()],J.prototype,"exitRoom",1),O([st(Ge.TRTC.switchRoom),Ce(),ir()],J.prototype,"switchRoom",1),O([st(Ge.TRTC.switchRole),Ao("room",{merge:(e,t)=>t}),Ce()],J.prototype,"switchRole",1),O([Ce()],J.prototype,"destroy",1),O([st(Ge.TRTC.startLocalAudio),wr("audio",([e],[t])=>{var r,s;return((r=e==null?void 0:e.option)==null?void 0:r.microphoneId)===((s=t==null?void 0:t.option)==null?void 0:s.microphoneId)}),Ce()],J.prototype,"startLocalAudio",1),O([st(Ge.TRTC.updateLocalAudio),Ao("audio",{debounce:{delay:200,getKey:()=>`${Qf}-localAudio`,isNeedToDebounce:e=>{var t;return!T((t=e.option)==null?void 0:t.captureVolume)}}}),Ce()],J.prototype,"updateLocalAudio",1),O([Lr("audio"),Ce()],J.prototype,"stopLocalAudio",1),O([st(Ge.TRTC.startLocalVideo),wr("video",([e],[t])=>{var r,s;return((r=e==null?void 0:e.option)==null?void 0:r.cameraId)===((s=t==null?void 0:t.option)==null?void 0:s.cameraId)}),Ce()],J.prototype,"startLocalVideo",1),O([st(Ge.TRTC.updateLocalVideo),Ao("video"),Ce()],J.prototype,"updateLocalVideo",1),O([Lr("video"),Ce()],J.prototype,"stopLocalVideo",1),O([st(Ge.TRTC.startScreenShare),wr("screen",()=>!0),Ce()],J.prototype,"startScreenShare",1),O([st(Ge.TRTC.updateScreenShare),Ao("screen"),Ce()],J.prototype,"updateScreenShare",1),O([Ce()],J.prototype,"stopScreenShare",1),O([st(Ge.TRTC.startRemoteVideo),wr(e=>`v${e.userId}${e.streamType}`,()=>!0),Ce({getRemoteId:e=>`${e.userId}_${e.streamType}`})],J.prototype,"startRemoteVideo",1),O([st(Ge.TRTC.updateRemoteVideo),Ao(e=>`v${e.userId}${e.streamType}`),Ce({getRemoteId:e=>`${e.userId}_${e.streamType}`})],J.prototype,"updateRemoteVideo",1),O([st(Ge.TRTC.stopRemoteVideo),Y(e=>function(t){return f(this,null,function*(){if(t.userId==="*"){let r=[];return this._room.remotePublishedUserMap.forEach(s=>{this._remoteVideoConfigMap.has(`${s.userId}_main`)&&r.push(this.stopRemoteVideo({streamType:"main",userId:s.userId}).catch(()=>{})),this._remoteVideoConfigMap.has(`${s.userId}_sub`)&&r.push(this.stopRemoteVideo({streamType:"sub",userId:s.userId}).catch(()=>{}))}),Promise.all(r)}return e.call(this,t)})}),Ce({getRemoteId:e=>`${e.userId}_${e.streamType}`})],J.prototype,"stopRemoteVideo",1),O([Lr(e=>`v${e.userId}${e.streamType}`)],J.prototype,"_stopRemoteVideo",1),O([st(...Ge.TRTC.muteRemoteAudio),Ce({getRemoteId:e=>e})],J.prototype,"muteRemoteAudio",1),O([Dh(...Ge.TRTC.setRemoteAudioVolume),Hf(200,e=>e),Ce({getRemoteId:e=>e})],J.prototype,"setRemoteAudioVolume",1),O([md("start"),Ct(e=>{var t;return(t=e.afterStart)==null?void 0:t.call(e)}),wr((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t)),Ce({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Kl[e.getName()],ignoreLog:e=>e.getName()==="Debug",ignoreErrorLog:e=>e.getName()==="AudioProcessor"})],J.prototype,"startPlugin",1),O([md("update"),Ao((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t),{merge:(e,t)=>(ti(e[1],t[1]),e)}),Ce({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>eu[e.getName()]})],J.prototype,"updatePlugin",1),O([md("stop"),Lr((e,t)=>{if(e.disableRandomCall)return null;let r=e.getGroup(t),s=e.getAlias();return r==="*"?new RegExp(`${s}.*`):s+r}),Ce({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>tu[e.getName()]})],J.prototype,"stopPlugin",1),O([Dh(...Ge.TRTC.enableAudioVolumeEvaluation)],J.prototype,"enableAudioVolumeEvaluation",1),O([Ce()],J.prototype,"getVideoSnapshot",1),O([Ce()],J.prototype,"_setCurrentSpeaker",1),O([wr(e=>`a${e.userId}`,()=>!0)],J.prototype,"_startRemoteAudio",1),O([Y(e=>function(t){return f(this,null,function*(){return t.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(r=>this._stopRemoteAudio(L(M({},t),{userId:r.userId})).catch(()=>{}))):e.call(this,t)})}),Lr(e=>`a${e.userId}`)],J.prototype,"_stopRemoteAudio",1),O([Lr("room")],J.prototype,"_exitRoom",1),O([Lr("screen")],J.prototype,"_stopScreenShare",1),O([st(...Ge.TRTC.sendSEIMessage),Ch({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...e)=>e[0].byteLength})],J.prototype,"sendSEIMessage",1),O([st(Ge.TRTC.sendCustomMessage),Ch({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],J.prototype,"sendCustomMessage",1),O([xr()],J,"create",1),O([st(Ge.TRTC.create)],J,"_create",1),O([xr()],J,"setLogLevel",1),O([xr()],J,"isSupported",1),O([xr()],J,"getPermissions",1),O([xr()],J,"getCameraList",1),O([xr()],J,"getMicrophoneList",1),O([xr()],J,"getSpeakerList",1);var Jh=J,ea=Jh;var qh=class{constructor(){d(this,"_set",new Set);S.on(A.LEAVE_SUCCESS,this.delete,this),S.on(A.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess,this)}add({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,e||i.roomId,i.sdkAppId,i.useStringRoomId);this._set.add(t)}delete({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,i.roomId||e,i.sdkAppId,i.useStringRoomId);this._set.delete(t)}getKey(i,e,t,r){return`${t}_${e}_${i}_${r}`}isJoined({userId:i,roomId:e,sdkAppId:t,room:r}){return r.scene==="rtc"?!1:this._set.has(this.getKey(i,e,t,r.useStringRoomId))}handleSwitchRoomSuccess({room:i,currentRoomId:e,targetRoomId:t}){i.scene!=="rtc"&&(this._set.delete(this.getKey(i.userId,e,i.sdkAppId,i.useStringRoomId)),this._set.add(this.getKey(i.userId,t,i.sdkAppId,i.useStringRoomId)))}};function ZS(){return f(this,null,function*(){let o,i;try{let _=yield It();o=_&&_.length}catch(_){}try{let _=yield At();i=_&&_.length}catch(_){}let e={microphone:o,camera:i},{isH264EncodeSupported:t,isVp8EncodeSupported:r,isH264DecodeSupported:s,isVp8DecodeSupported:n,isH265EncodeSupported:a,isH265DecodeSupported:c}=this.checkSystemResult.detail,l=vi.basis(),u={webRTC:l.isWebRTCSupported,getUserMedia:l.isGetUserMediaSupported,webSocket:l.isWebSocketsSupported,screenShare:l.isScreenShareSupported,webAudio:l.isWebAudioSupported,h264Encode:t,h264Decode:s,vp8Encode:r,vp8Decode:n,h265Encode:a,h265Decode:c},h={browser:l.browser,os:l.os,trtc:u,devices:e},m={isWebCodecSupported:l.isWebCodecSupported,isMediaSessionSupported:l.isMediaSessionSupported,isWebTransportSupported:l.isWebTransportSupported};oe.uploadEvent({log:`trtcstats-${JSON.stringify(h)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(h)}`),oe.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(m)}`,userId:this.userId}),mu()})}function Zf(){return Y(o=>{let i=new qh;return function(e,t,r){return f(this,null,function*(){let s=String(e.roomId||e.strRoomId);if(this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.userSig=e.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=t,e.privateMapKey=e.privateMapKey||"",this.isJoined)throw new D({code:I.INVALID_OPERATION,message:H({key:B.INVALID_JOIN})});if(this.checkDestroy(),i.isJoined({userId:this.userId,roomId:s,sdkAppId:this.sdkAppId,room:this}))throw new D({code:I.INVALID_OPERATION,message:H({key:B.REPEAT_JOIN,data:this.userId})});i.add({room:this,roomId:s}),this.role=e.role===21?"audience":"anchor",this._log.info(`Join() => joining room: ${s} useStringRoomId: ${this.useStringRoomId} scene: ${this.scene} role: ${this.role}`),S.emit(A.JOIN_START,{room:this,roomId:s,params:e});let n=vt.getEnv();n||(n=Fi.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(ga.OLD_CLOUD_LADDER)?n=Fi.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(ga.WEBRTC)&&(n=Fi.WEBRTC))),oe.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:s}),vi.checkSystemRequirementsInternal(r).then(a=>{this.checkSystemResult=a,ZS.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!vt.getEnv()&&(yield this.schedule(e,r));let a=yield o.call(this,e,t,r);return this.roomId=s,this._joinedTimestamp=vt.performanceNow(),S.emit(A.JOIN_SUCCESS,{room:this}),r===30&&!e.component&&oe.uploadEvent({log:`stat-conv-${Number(si)}-${location.hostname}`,userId:this.userId}),a}catch(a){throw i.delete({room:this,roomId:s}),S.emit(A.JOIN_FAILED,{room:this,error:a}),a}})}})}var Kf=()=>Y(o=>function(...i){return f(this,null,function*(){S.emit(A.LEAVE_START,{room:this}),yield o.call(this,...i),S.emit(A.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function e_(){return Y(o=>function(...i){let e=o.apply(this,i);return i.forEach(t=>!t.isSubscribed&&t.subscribe(e)),e})}var i_=Je(at());var Ie={SETUP_SUCCESS:"1",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",RECONNECT_FAILED:"4",SETUP_FAILED:"5",DISCONNECTED:"6",CLOSE:"7",ONLINE:"8"};var qt={CLIENT_BANNED:9,CHANNEL_SETUP_RESULT:19,CHANNEL_RECONNECT_RESULT:514,JOIN_ROOM_RESULT:20,PEER_JOIN:4134,PEER_LEAVE:4135,STREAM_ADDED:16,STREAM_REMOVED:18,UPLINK_NETWORK_STATS:22,UPDATE_REMOTE_MUTE_STAT:23,PUBLISH_RESULT:4098,PUBLISH_STATE_CHANGE_RESULT:4112,UNPUBLISH_RESULT:4100,SUBSCRIBE_RESULT:4102,UNSUBSCRIBE_RESULT:4104,SUBSCRIBE_CHANGE_RESULT:4106,MUTE_RESULT:4108,UPDATE_OFFER_RESULT:4128,START_PUBLISH_TENCENT_CDN_RES:1286,STOP_PUBLISH_TENCENT_CDN_RES:1288,START_PUBLISH_GIVEN_CDN_RES:777,STOP_PUBLISH_GIVEN_CDN_RES:779,START_MIX_TRANSCODE_RES:781,STOP_MIX_TRANSCODE_RES:783,START_PUBLISH_CDN_STREAM_RES:8196,UPDATE_PUBLISH_CDN_STREAM_RES:8198,STOP_PUBLISH_CDN_STREAM_RES:8200,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772,REBUILD_PEER_CONNECTION_RES:4150,SPC_PUBLISH_RESULT:4146,SPC_SUBSCRIBE_RESULT:4156,ABILITY_STATUS_REPORT_RESULT:4158,SERVER_FIRST_PACKAGE_RECEIVED:5e3,RECEIVE_CUSTOM_MSG:4140,FALLBACK_CODEC:66,SEND_SWITCH_ROOM_RES:4160,SEND_SWITCH_ROOM_SUBED_REQ:4161,UPDATE_NETWORK_TIME_RESULT:5001,CUSTOM_CMD_RES:8220},t_=[qt.UPDATE_REMOTE_MUTE_STAT,qt.UPLINK_NETWORK_STATS,qt.USER_LIST_RES,qt.MUTE_RESULT,qt.SERVER_FIRST_PACKAGE_RECEIVED,qt.RECEIVE_CUSTOM_MSG,qt.UPDATE_NETWORK_TIME_RESULT],G={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",START_PUBLISH_CDN_STREAM_RES:"start-publish-cdn-stream-res",UPDATE_PUBLISH_CDN_STREAM_RES:"update-publish-cdn-stream-res",STOP_PUBLISH_CDN_STREAM_RES:"stop-publish-cdn-stream-res",USER_LIST_RES:"user-list-res",SWITCH_ROLE_RES:"switch_role_res",MUTE_RESULT:"mute-result",UPDATE_CONSTRAINT_CONFIG_RES:"update-contraint-config-res",REBUILD_PEER_CONNECTION_RES:"rebuild-pc-res",SPC_PUBLISH_RESULT:"spc-publish-result",SPC_SUBSCRIBE_RESULT:"spc-subscribe-result",ABILITY_STATUS_REPORT_RESULT:"ability-status-report",SERVER_FIRST_PACKAGE_RECEIVED:"first-pkg-received",RECEIVE_CUSTOM_MSG:"receive-custom-msg",FALLBACK_CODEC:"fallback-codec",SEND_SWITCH_ROOM_RES:"send-switch-room-res",SEND_SWITCH_ROOM_SUBED_REQ:"send-switch-room-subed-res",UPDATE_NETWORK_TIME_RESULT:"update_network_time_result",CUSTOM_CMD_RES:"custom-cmd-res"},Z={PUBLISH_CHANGE:"publish_change",JOIN_ROOM:"join",LEAVE_ROOM:"leave",ON_QUALITY_REPORT:"quality_report",UPDATE_MUTE_STAT:"mute_uplink",PUBLISH:"publish",PUBLISH_STATE_CHANGE:"publish_state_change",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",RECEIVE_DATA_USER_LIST:"receive_data_userlist",UNSUBSCRIBE:"unsubscribe",SUBSCRIBE_CHANGE:"subscribe_change",START_PUBLISH_TENCENT_CDN:"start_publishing",STOP_PUBLISH_TENCENT_CDN:"stop_publishing",START_PUBLISH_GIVEN_CDN:"start_push_user_cdn",STOP_PUBLISH_GIVEN_CDN:"stop_push_user_cdn",START_MIX_TRANSCODE:"start_mcu_mix",STOP_MIX_TRANSCODE:"stop_mcu_mix",START_PUBLISH_CDN_STREAM:"start_publish_cdn_stream",UPDATE_PUBLISH_CDN_STREAM:"update_publish_cdn_stream",STOP_PUBLISH_CDN_STREAM:"stop_publish_cdn_stream",GET_USER_LIST:"get_user_list",SWITCH_ROLE:"change_role",UPDATE_CONSTRAINT_CONFIG:"update_constraint_config",REBUILD_PEER_CONNECTION:"rebuild_pc",READY_TO_RECEIVE_DATA:"ready_to_receive",SPC_JOIN_ROOM:"join/v2",SPC_PUBLISH:"publish/v2",SPC_SUBSCRIBE:"subscribe/v3",ABILITY_STATUS_REPORT:"ability_status_report",RECONNECT_WS:"reconnect",SEND_CUSTOM_MSG:"channel_msg",SWITCH_ROOM:"switch_room",UPDATE_NETWORK_TIME:"update_network_time",CUSTOM_CMD:"abstract_cmd"};var yd=new Set;function r_(o){let i=[...yd.values()].find(e=>e.room.userId===o&&!e.room.isJoined);return i||null}var eI=["autoTest","relayInnerIp","relayOuterIp","mcd","newRelay","clientIp"],bs=class extends i_.default{constructor(e){var r,s,n;super();d(this,"room");d(this,"sdkAppId");d(this,"userId");d(this,"userSig");d(this,"url");d(this,"backupUrl");d(this,"destroyed",!1);d(this,"_socketInUse");d(this,"_socket");d(this,"_backupSocket");d(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,bakRelayIps:[],reportToken:void 0});d(this,"_currentState","DISCONNECTED");d(this,"_isReconnecting",!1);d(this,"_seq",0);d(this,"_log");d(this,"_lastMessageTime",-1);d(this,"_connectStartTime",-1);d(this,"_stopConnectRetry");d(this,"_isFirstConnect",!0);d(this,"bytesSent",0);d(this,"bytesReceived",0);d(this,"keepAlive",!1);d(this,"signalDomainWhenUnifiedProxy");d(this,"stopKeepAliveTimeout");d(this,"rtt",0);this.room=e.room,this.sdkAppId=e.sdkAppId,this.userId=e.userId,this.userSig=e.userSig,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy;let t=((s=(r=this.room.scheduleResult)==null?void 0:r.config)==null?void 0:s.keepAliveClient)||0;(n=this.room.joinParams)!=null&&n.keepAlive&&!t&&(t=1),t-yd.size>0&&this.room.enableSPC&&(this.keepAlive=!0,yd.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=R.createLogger({parent:this.room.getLogger(),id:"ws",userId:this.userId,sdkAppId:this.sdkAppId}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get race(){return this.room.enableSPC&&!this.room.proxy_ws}get urlParam(){let e=`?sdkAppId=${encodeURIComponent(this.sdkAppId)}&userId=${encodeURIComponent(this.userId)}&userSig=${encodeURIComponent(this.userSig)}&keepAlive=${encodeURIComponent(Number(this.keepAlive))}`;this.signalDomainWhenUnifiedProxy&&(e+=`&signalDomain=${encodeURIComponent(this.signalDomainWhenUnifiedProxy)}`);let t=new URLSearchParams(location.search);return eI.forEach(r=>{let s=t.get(`trtc_${r}`);s&&(e+=`&${r}=${encodeURIComponent(s)}`)}),this.race?`${e}&race=1`:e}get _urlWithParam(){return`${this.url}${this.race?"/v2/ws":""}${this.urlParam}`}get _backupUrlWithParam(){return`${this.backupUrl}${this.race?"/v2/ws":""}${this.urlParam}`}get isConnected(){return this._currentState==="CONNECTED"}get isConnecting(){return this._currentState==="CONNECTING"}get isOnline(){return this._currentState==="CONNECTED"&&Date.now()-this._lastMessageTime<12*1e3}connect(){return f(this,arguments,function*(e=10*1e3){if(this.isConnected)return Promise.resolve();this._log.info(`connect to [${this.url}, ${this.backupUrl}] ${this.race?"race":""}${e?` timeout: ${e}`:""} keepAlive: ${Number(this.keepAlive)}`),this.emitConnectionStateChanged("CONNECTING"),this._connectStartTime=U();let t=[this.connectWS({url:this._urlWithParam,isMain:!0,timeout:e})];this.race&&this._backupUrlWithParam!==this._urlWithParam&&t.push(this.connectWS({url:this._backupUrlWithParam,isMain:!1,timeout:e})),this._socketInUse=yield Xr(t),this.unbindAndCloseSocket(this._socketInUse===this._socket?p.BACKUP:p.MAIN),this._isFirstConnect&&(v.addSuccessEvent({key:521720}),this._isFirstConnect=!1),this.emitConnectionStateChanged("CONNECTED")})}connectWS({url:e,timeout:t,isMain:r}){let s=new WebSocket(e);this.bindSocket(s),r?this._socket=s:this._backupSocket=s;let n=-1;return new Promise((a,c)=>{s.onclose=c,s.onerror=c,s.onopen=()=>a(s),t&&(n=setTimeout(()=>{this.unbindAndCloseSocket(r?p.MAIN:p.BACKUP),c(new D({code:I.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))},t))}).finally(()=>{s.onclose=null,s.onerror=null,s.onopen=null,clearTimeout(n)})}bindSocket(e){e.addEventListener("close",this.onclose),e.addEventListener("error",this.onerror),e.addEventListener("message",this.onmessage)}unbindSocket(e){e.removeEventListener("close",this.onclose),e.removeEventListener("error",this.onerror),e.removeEventListener("message",this.onmessage)}unbindAndCloseSocket(e){if(e===p.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(t){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(t){}this._backupSocket=null}}onclose(e){e.target===this._socketInUse&&(this._log.warn(`${e.target===this._socket?"main":"backup"} is closed code:${e.code} ${e.reason}`),this.emitConnectionStateChanged("DISCONNECTED"),(!e.wasClean||e.code!==1e3)&&this.startReconnection(),this.room.isJoining&&this.emit(Ie.SETUP_FAILED,new D({code:I.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onclose"})))}onerror(e){this._log.error(`${e.target===this._socket?"main":"backup"} error observed`),this.emitConnectionStateChanged("DISCONNECTED"),e.target===this._socketInUse&&(this.unbindAndCloseSocket(p.MAIN),this.unbindAndCloseSocket(p.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(Ie.SETUP_FAILED,new D({code:I.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(e){if(!this.isConnected)return;let{isOnline:t}=this;this._lastMessageTime=Date.now(),t||this.emit(Ie.ONLINE),this.bytesReceived+=Js(e.data);let r=JSON.parse(e.data),{cmd:s,data:n}=r,a=Object.values(qt),l=Object.keys(qt)[a.indexOf(s)],u=G[l]||s;switch(t_.includes(s)||(this._log.debug(`received ${s} msg: ${e.data}`),u&&this._log.info(`Received event: [ ${u} ]`)),s){case qt.CHANNEL_SETUP_RESULT:{if(r.code===0)this._signalInfo.clientIp=n.clientIp,this._signalInfo.signalIp=n.signalInnerIp,n.svrTime&&da(n.svrTime-new Date().getTime()),this._log.info(`ChannelSetup Success ${U()-this._connectStartTime}`),v.addSuccessEvent({key:521701,cost:U()-this._connectStartTime}),this._connectStartTime=-1,this.emit(Ie.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let h=new D({code:I.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:r.code,message:H({key:B.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:r.code,errorMsg:r.message}})});this._log.error(`${r.code}, ${r.message}`),this.close(),v.addFailedEvent({key:521701,error:h}),this.emit(Ie.SETUP_FAILED,h)}break}case qt.JOIN_ROOM_RESULT:{r.code===0&&(this._signalInfo.relayIp=n.relayOuterIp,this._signalInfo.relayInnerIp=n.relayInnerIp,this._signalInfo.bakRelayIps=n.bakRelayIps,this._signalInfo.relayPort=n.relayPort,this._signalInfo.tinyId=r.tinyId,this._signalInfo.endReportExtend=n.endReportExtend,this._signalInfo.reportToken=n.reportToken,this._log.info(`signalIp:${this._signalInfo.signalIp} clientIp:${this._signalInfo.clientIp} relayIp: ${this._signalInfo.relayIp}`)),this.emit(u,{data:r});break}default:this.emit(String(u),{data:r});break}}reGetSignalChannelUrl(){return f(this,null,function*(){try{if(!this.room.joinParams)return;Lt(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(e){}})}startReconnection(){if(!this._socketInUse)return;this._socketInUse.onclose=null,this._socketInUse.close(4011);let e=this._socketInUse===this._socket;this.unbindAndCloseSocket(e?p.MAIN:p.BACKUP),this._socketInUse=null,this.emitConnectionStateChanged("DISCONNECTED"),this.reconnect()}reconnect(){return f(this,null,function*(){if(!this._isReconnecting){if(!this.room.isJoined&&this.keepAlive){this.close();return}this._isReconnecting=!0;try{this._log.warn("reconnect"),yield this.connect();let{roomId:e,useStringRoomId:t}=this.room,{relayIp:r,relayInnerIp:s,relayPort:n}=this._signalInfo,{data:a}=yield this.sendWaitForResponse({command:Z.RECONNECT_WS,data:{roomId:e,useStringRoomId:t,relayInnerIp:s,relayOuterIp:r,relayPort:n},responseCommand:G.CHANNEL_RECONNECT_RESULT});a.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),v.addSuccessEvent({key:521702,cost:U()-this._connectStartTime}),this._connectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(v.addFailedEvent({key:521702,error:a.code}),this._log.warn(`reconnect failed, ${a.code} ${a.message}`),this.room.reJoin())}catch(e){this._log.error(e),this.room.reJoin()}}})}send(e,t={}){if(this.isConnected&&!this.room.isLeft){let r={cmd:e,data:t,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},s=JSON.stringify(r);return this._socketInUse.send(s),this.bytesSent+=Js(s),r.seq}}sendWaitForResponse({command:e,data:t,timeout:r=5e3,responseCommand:s,commandDesc:n,enableLog:a=!0,addReceiveTime:c=!1}){return new Promise((l,u)=>{let h=()=>{clearTimeout(m),u(new D({code:I.API_CALL_ABORTED,message:`${e} aborted due to connection closed`}))};this.once(Ie.CLOSE,h);let m=setTimeout(()=>{this.off(s,_),this.off(Ie.CLOSE,h);let E=new D({code:I.API_CALL_TIMEOUT,message:H({key:B.API_CALL_TIMEOUT,data:{commandDesc:n,command:e}})});a&&this._log.warn(E),u(E)},r),_=E=>{E.data.seq===g&&(clearTimeout(m),this.off(s,_),this.off(Ie.CLOSE,h),c&&(E.data.receiveTime=Date.now()),l(E))};this.on(s,_);let g=this.send(e,t)})}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:r,retries:s=0,retryTimeout:n=0}=e;return Ci({retryFunction:this.sendWaitForResponse,onError:({retry:a,reject:c,error:l})=>{!this.room.isJoined||this.destroyed||l.code===I.API_CALL_ABORTED?c(l):this.isOnline?a():(this._log.warn(`retry ${r} when connected`),this.once(Ie.ONLINE,a))},onRetrying:a=>{this._log.warn(`${t||r} timeout observed, retrying [${a}/${s}]`)},settings:{retries:s,timeout:n},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),clearTimeout(this.stopKeepAliveTimeout),yd.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,bakRelayIps:[],endReportExtend:void 0,reportToken:void 0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(p.MAIN),this.unbindAndCloseSocket(p.BACKUP),this.emitConnectionStateChanged("DISCONNECTED"),this.emit(Ie.CLOSE)}destroy(){this.close(),this.destroyed=!0}getBackupRelayIpPair(){var t;let e=(t=this._signalInfo.bakRelayIps)==null?void 0:t.shift();return e&&(e.relayPort=e.relayPort||this._signalInfo.relayPort),e}clearBakRelayIps(){this._signalInfo.bakRelayIps=[]}stopKeepAliveIn(e=3600){if(this.keepAlive){this._log.info(`stopKeepAlive in ${e}s`),this.stopKeepAliveTimeout=setTimeout(()=>{this.keepAlive=!1,this._log.info(`close due to not used ${e}s`),this.close(),this.off(G.JOIN_ROOM_RESULT,t)},e*1e3);let t=r=>{r.data.code===0&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(G.JOIN_ROOM_RESULT,t))};this.on(G.JOIN_ROOM_RESULT,t)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info(`${this._currentState} -> ${e}`),this.emit(Ie.CONNECTION_STATE_CHANGED,{prevState:this._currentState,state:e}),this._currentState=e,e==="CONNECTED"?this.emit(Ie.CONNECTED):e==="DISCONNECTED"&&this.emit(Ie.DISCONNECTED))}};O([Ot({settings:{retries:1/0,timeout:2e3},onError(e,t){!this.room.isDestroyed&&!this.destroyed&&(this._isFirstConnect&&(v.addFailedEvent({key:521720,error:e}),this._isFirstConnect=!1),t())},onRetrying(e,t){this._log.warn(`retrying to connect ${e}`),e>=3&&e%3===0&&this.reGetSignalChannelUrl(),t&&(this._stopConnectRetry=t,(this.room.isDestroyed||this.destroyed)&&t())}})],bs.prototype,"connect",1);var o_=Je(at());var jh=0,Xh=!1,bd=new Set,tI=o=>jh>2&&!Xh&&bd.size===0&&o,zh=!1,pt=class{constructor(i){d(this,"userId");d(this,"tinyId");d(this,"_sdpSemantics");d(this,"_isUplink");d(this,"_room");d(this,"_log");d(this,"_signalChannel");d(this,"_isErrorObserved",!1);d(this,"_waitForPeerConnectionConnectedPromise");d(this,"_waitForPeerConnectionConnectedPromiseReject",null);d(this,"_peerConnection",null);d(this,"_emitter",new o_.default);d(this,"_currentState","DISCONNECTED");d(this,"_isReconnecting",!1);d(this,"_reconnectionCount",0);d(this,"_reconnectionTimer",-1);d(this,"_isFirstConnection",!0);d(this,"_prevTime",-1);d(this,"_localAddress");d(this,"_remoteAddress");this.userId=i.userId,this.tinyId=i.tinyId,this._room=i.room,this._sdpSemantics=i.room.sdpSemantics,this._isUplink=i.isUplink,this._log=i.room.getLogger().createChild({id:"n-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=i.signalChannel}beforeConnect(){this._prevTime<0&&(this._prevTime=U())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,v.addSuccessEvent({key:521705,cost:Math.min(U()-this._prevTime,30*1e3)})):this._isReconnecting&&v.addSuccessEvent({key:521706,cost:U()-this._prevTime}),this._prevTime=-1}catch(i){throw this._isFirstConnection?(this._isFirstConnection=!1,v.addFailedEvent({key:521705,error:i})):this._isReconnecting&&this._reconnectionCount>=3&&v.addFailedEvent({key:521706,error:i}),i}}initialize(){let i={iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"};this._peerConnection=new RTCPeerConnection(i),this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this)}close(i){this._log.info("close connection"),this._emitter.emit("closed",i),this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),bd.delete(this)}closePeerConnection(i=!1){this._peerConnection&&(this._log.info("close pc"),this._peerConnection.onconnectionstatechange=null,this._peerConnection.close(),this._peerConnection=null,i&&this.emitConnectionStateChangedEvent("DISCONNECTED")),this._waitForPeerConnectionConnectedPromiseReject&&this._waitForPeerConnectionConnectedPromiseReject(new D({code:I.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return Yt;let i=null;if(this._isUplink){if(!Rr()||this._peerConnection.getSenders().length===0)return Yt;i=this._peerConnection.getSenders()[0].transport}else{if(!oo()||this._peerConnection.getReceivers().length===0)return Yt;i=this._peerConnection.getReceivers()[0].transport}return i?i.state:Yt}onConnectionStateChange(i){let e=this._peerConnection.iceConnectionState,t=this.getDTLSTransportState();if(this._log.info(`connectionState: ${i.target.connectionState}, ICE: ${e}, DTLS: ${t}`),i.target.connectionState===Re.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),i.target.connectionState===Re.FAILED||i.target.connectionState===Re.CLOSED){let r=`connection ${i.target.connectionState}. ICE Transport state: ${e}, DTLS Transport state: ${t}`,s=new D({message:r,code:I.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",s)}(i.target.connectionState===Re.CONNECTED||i.target.connectionState===Re.COMPLETED)&&(this.logSelectedCandidate(),oe.logSuccessEvent({userId:this._room.userId,eventType:Ze.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(i){return i===this._currentState?!1:(i==="CONNECTED"?(jh=0,Xh=!1,zh=!0,bd.add(this)):bd.delete(this),S.emit(A.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:i,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:i}),this._currentState=i,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}logSelectedCandidate(){return f(this,null,function*(){if(!this._peerConnection)return;let i=yield this._peerConnection.getStats();for(let[,e]of i)if(Cr(e)){let t=i.get(e.localCandidateId),r=i.get(e.remoteCandidateId);t&&(this._log.info(`local candidate: ${t.candidateType} ${t.protocol}:${t.ip||t.address}:${t.port} ${t.networkType||""} ${t.candidateType==="relay"?`relayProtocol:${t.relayProtocol}`:""}`),this._localAddress=`${t.ip||t.address}:${t.port}`),r&&(this._log.info(`remote candidate: ${r.candidateType} ${r.protocol}:${r.ip||r.address}:${r.port}`),this._remoteAddress=`${r.protocol}:${r.ip||r.address}`);break}})}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise?this._waitForPeerConnectionConnectedPromise:(this._waitForPeerConnectionConnectedPromise=new Promise((i,e)=>{if(this._currentState==="CONNECTED")return i();this._waitForPeerConnectionConnectedPromiseReject=e;let t=a=>{a.state==="CONNECTED"&&(clearTimeout(n),s(),i())},r=({room:a})=>{a===this._room&&(clearTimeout(n),s(),e(new D({code:I.API_CALL_ABORTED,message:H({key:B.CONNECTION_ABORTED,data:"leave room"})})))},s=()=>{S.off(A.LEAVE_SUCCESS,r,this),this._emitter.off("connection-state-changed",t,this)},n=setTimeout(()=>{s();let a=new D({code:I.API_CALL_TIMEOUT,message:"connection timeout"});jh+=1,tI(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),Xh=!0,this._emitter.emit("firewall-restriction")),e(a)},Fs);S.on(A.LEAVE_SUCCESS,r,this),this._emitter.on("connection-state-changed",t,this)}),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally(()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null}),this._waitForPeerConnectionConnectedPromise)}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(Ie.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=Hi()){this._log.warn(`SDK has tried reconnect for ${this._reconnectionCount} times, but all failed, please check your network`),this.stopReconnection();let i=new D({code:this._isUplink?I.UPLINK_RECONNECTION_FAILED:I.DOWNLINK_RECONNECTION_FAILED,message:H({key:this._isUplink?B.UPLINK_RECONNECTION_FAILED:B.DOWNLINK_RECONNECTION_FAILED})});return this.emitConnectionStateChangedEvent("DISCONNECTED"),this._emitter.emit("error",i),-1}return this._signalChannel.isConnected?(this._reconnectionCount+=1,this._log.warn(`reconnect() trying [${this._reconnectionCount}]`),1):(this._log.warn("reconnect() signal channel is not connected, suspend reconnection until signal is connected"),this._signalChannel.once(Ie.CONNECTED,this.reconnect,this),-1)}on(i,e,t){this._emitter.on(i,e,t)}off(i,e,t){this._emitter.off(i,e,t)}getIsReconnecting(){return this._isReconnecting}get isH264(){var i,e;return!!((e=(i=this._peerConnection)==null?void 0:i.remoteDescription)!=null&&e.sdp.includes("H264"))}setOffer(i){var e;return(e=this._peerConnection)==null?void 0:e.setLocalDescription(i)}setAnswer(i){var e;return(e=this._peerConnection)==null?void 0:e.setRemoteDescription(i)}};O([Rt(521712,!1)],pt.prototype,"setOffer",1),O([Rt(521713,!1)],pt.prototype,"setAnswer",1);var Kh=Je(Zh());var Ne=function(o){return Kh.default.parse(o)},jt=function(o){return Kh.default.write(o)},h_=function(o){let i=Ne(o);return i.media.forEach(e=>{e.type===p.AUDIO&&e.fmtp.forEach(t=>{t.config+=";sprop-stereo=1;stereo=1"})}),jt(i)};function m_(o){let i=Ne(o);return i.media.forEach(e=>{var t,r;if(e.type===p.VIDEO){let s=new Set;e.rtp.forEach(({payload:a,codec:c})=>c==="H264"&&s.add(a)),e.fmtp.forEach(({payload:a,config:c})=>{let l=c.match(/apt=(\d+)/);l&&l[1]&&s.has(Number(l[1]))&&s.add(a)});let n=({payload:a})=>!s.has(a);e.rtp=e.rtp.filter(n),e.rtcpFb=(t=e.rtcpFb)==null?void 0:t.filter(n),e.fmtp=e.fmtp.filter(n),e.payloads=(r=e.payloads)==null?void 0:r.split(" ").filter(a=>!s.has(Number(a))).join(" ")}}),jt(i)}function vd(o){return Object.keys(o).filter(i=>o[i])}var Ns=class Ns extends pt{constructor(e){super(L(M({},e),{isUplink:!1}));d(this,"_flag",0);d(this,"isRobot",!1);d(this,"role","anchor");d(this,"remoteAudioTrack");d(this,"remoteVideoTrack");d(this,"remoteAuxiliaryTrack");d(this,"ssrc",{audio:0,video:0,auxiliary:0});d(this,"_isSDPExchanging",!1);d(this,"_videoCodec");this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=e.remoteAudioTrack||new Ti(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new ki(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new Es(this._room,this)}get videoCodec(){var t,r;let e=(r=(t=this._peerConnection)==null?void 0:t.remoteDescription)==null?void 0:r.sdp;return e?e.includes("H264")?"h264":"vp8":this._videoCodec||"h264"}set videoCodec(e){this._videoCodec=e}get subscribeState(){let e={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(this.remoteVideoTrack.mediaType&8?e.smallVideo=!0:e.video=!0),this.remoteAudioTrack.isSubscribed&&(e.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(e.auxiliary=!0),e}get muteState(){return ei(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,r,s;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(r=this.remoteVideoTrack)==null||r.onFlagChanged(),(s=this.remoteAuxiliaryTrack)==null||s.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===p.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var s,n;let t=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&t!==e&&((s=this.remoteVideoTrack)==null||s.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),r}onTrack(e){let t=e.streams[0],{track:r}=e,s=t.id===Bs?p.MAIN:p.AUXILIARY;this._log.debug(`ontrack ${s} ${r.kind}`);let n=p.AUDIO;r.kind===p.VIDEO&&(n=s===p.MAIN?p.VIDEO:p.AUXILIARY);let a=this.remoteAudioTrack;n===p.VIDEO?a=this.remoteVideoTrack:n===p.AUXILIARY&&(a=this.remoteAuxiliaryTrack),a.setInputMediaStreamTrack(r)}addRRTRLine(e){let t=e.split(`\r
|
|
63
|
+
`),r=new Map;t.forEach((n,a)=>{/^a=rtcp-fb:/.test(n)&&t[a+1]&&!/^a=rtcp-fb:/.test(t[a+1])&&r.set(a+1,`${n.match(/^a=rtcp-fb:\d+/)[0]} rrtr`)});let s=[...r];for(let n=0;n<s.length;n++){let[a,c]=s[n];t.splice(a+n,0,c)}return t.join(`\r
|
|
64
|
+
`)}addSPSDescription(e){let t=Ne(e);return t.media.forEach(r=>{r.type===p.VIDEO&&r.fmtp.forEach(s=>{s.config+=";sps-pps-idr-in-keyframe=1"})}),jt(t)}removeSDESDescription(e){let t=["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"],r=Ne(e);return r.media.forEach(s=>{s.ext&&(s.ext=s.ext.filter(n=>!t.includes(n.uri)))}),jt(r)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return f(this,null,function*(){var r,s;try{if((((r=this._peerConnection)==null?void 0:r.connectionState)===Re.NEW||((s=this._peerConnection)==null?void 0:s.connectionState)===Re.CONNECTING)&&(yield this.waitForPeerConnectionConnected()),this.isSubscriptionStateNotChanged(e)){this._peerConnection||(this.initialize(),yield this.connect(e));return}if(this._log.info(`subscribe ${t} ${JSON.stringify(e)}`),this._peerConnection||this._isSDPExchanging){let n="subscribe_change";Object.values(e).find(a=>a===!0)||(n="unsubscribe"),yield this.sendSubscription(n,e)}else this.initialize(),yield this.connect(e)}catch(n){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${n.message} ${JSON.stringify(this.muteState)}`),new D({code:I.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):n}})}unsubscribe(r){return f(this,arguments,function*({remoteTracks:e,streamType:t}){if(this._currentState==="CONNECTED"&&(t==="main"&&!this.isMainStreamSubscribed||t==="auxiliary"&&!this.isAuxStreamSubscribed)){this._log.info(`${t} stream already unsubscribed`);return}let s=M({},this.subscribeState);e.forEach(a=>{switch(a.mediaType){case 1:s.audio=!1;break;case 4:s.video=!1;break;case 8:s.smallVideo=!1;break;case 2:s.auxiliary=!1;break;default:break}});let n="subscribe_change";Object.values(s).find(a=>a===!0)||(n="unsubscribe"),this._log.info(`${n==="unsubscribe"?n:"subscribe"} ${t} [${vd(s)}]`),yield this.sendSubscription(n,s),n==="unsubscribe"&&(this.closePeerConnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"))})}sendSubscription(e,t=this.subscribeState){let r={srcTinyId:this.tinyId,srcUserId:this.userId},s=Z.UNSUBSCRIBE,n=G.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(r={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},s=Z.SUBSCRIBE_CHANGE,n=G.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:s,data:r,responseCommand:n,timeout:1e4}).then(({data:a})=>{if(a.code!==0){let c=new D({code:a.code,message:H({key:B.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(c),c}})}connect(){return f(this,arguments,function*(e=this.subscribeState){try{yield this.exchangeSDP(e),yield this.waitForPeerConnectionConnected()}catch(t){throw this.closePeerConnection(!0),t}})}exchangeSDP(e){return f(this,null,function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info("createOffer success, sending offer");let{type:t,sdp:r}=this._peerConnection.localDescription,s={type:t,sdp:r,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},n=yield this._signalChannel.sendWaitForResponse({command:Z.SUBSCRIBE,commandDesc:"exchange sdp",data:s,responseCommand:G.SUBSCRIBE_RESULT,timeout:il});if(!this._peerConnection){let a=new D({code:I.INVALID_OPERATION,message:H({key:B.CONNECTION_CLOSED})});throw this._log.warn(a),a}yield this.onSubscribeResult(n),this._isSDPExchanging=!1}catch(t){throw this._isSDPExchanging=!1,t}})}createOffer(){return f(this,null,function*(){let e={voiceActivityDetection:!1};St()&&this._sdpSemantics===gr?(this._peerConnection.addTransceiver(p.AUDIO,{direction:se.RECVONLY}),this._peerConnection.addTransceiver(p.VIDEO,{direction:se.RECVONLY}),this._peerConnection.addTransceiver(p.VIDEO,{direction:se.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:r}=yield fc();r||(this._log.warn("remove h264 desc from sdp"),t.sdp=m_(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=h_(t.sdp),this._sdpSemantics===gr&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this.setOffer(t)})}onSubscribeResult(e){return f(this,null,function*(){let{code:t,message:r=""}=e&&e.data||{},{type:s,sdp:n}=e&&e.data&&e.data.data||{};if(t===Hr)throw new D({code:I.NOT_SUPPORTED_H264,message:H({key:B.NOT_SUPPORTED_H264DECODE})});try{if(t!==0)throw new D({code:t,message:H({key:B.EXCHANGE_SDP_FAILED,data:{errMsg:r}})});this._log.debug(`accept remote answer: ${n}`),yield this.setAnswer({type:s,sdp:n}),this.updateSSRC(n)}catch(a){throw this._log.error(a),a}})}updateSSRC(e){try{Ne(e).media.forEach(r=>{if(r.ssrcs)if(r.type===p.AUDIO){let s=r.ssrcs.find(n=>{var a;return(a=n.value)==null?void 0:a.includes(Bs)});s&&(this.ssrc.audio=Number(s.id))}else{let s=r.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(Bs)}),n=r.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(Yd)});s&&(this.ssrc.video=Number(s.id)),n&&(this.ssrc.auxiliary=Number(n.id))}})}catch(t){}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return f(this,null,function*(){if(!(He(Ns.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch(t){let r=Kt(this._reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${r/1e3}s`),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},r)}})}getIsReconnecting(){return this._isReconnecting}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}getCurrentState(){return this._currentState}setDelay({audioDelay:e,videoDelay:t}){this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=t}get audioReceiver(){var e;return((e=this._peerConnection)==null?void 0:e.getReceivers()[0])||null}};O([Y(e=>function(...t){return new Promise((r,s)=>{let n=a=>{this._emitter.off("closed",n),s(new D({code:I.API_CALL_ABORTED,message:H({key:B.CONNECTION_ABORTED,data:a})}))};this._emitter.on("closed",n),e.apply(this,t).then(r,s).finally(()=>{this._emitter.off("closed",n)})})})],Ns.prototype,"subscribe",1),O([Rt(521717,!1)],Ns.prototype,"unsubscribe",1),O([Ct(pt.prototype.afterConnect),Mc(pt.prototype.beforeConnect)],Ns.prototype,"connect",1);var em=Ns,tm=em;var f_={voiceActivityDetection:!1},Ds=class Ds extends pt{constructor(e){super(L(M({},e),{isUplink:!0}));d(this,"localMainAudioTrack",null);d(this,"localMainVideoTrack",null);d(this,"localAuxAudioTrack",null);d(this,"localAuxVideoTrack",null);d(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0});d(this,"_isPublishingAux",!1);d(this,"_publishingLocalAudioTrack");d(this,"_publishingLocalVideoTrack");d(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0});d(this,"flag",0)}get videoCodec(){return this._mediaSettings.videoCodec.toLowerCase()||"h264"}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}initialize(){super.initialize(),this.installEvents()}reset(){this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this.uninstallEvents()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this._emitter.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this._emitter.on("connection-state-changed",this.handleConnectionStateChange,this)}uninstallEvents(){this._emitter.off("connection-state-changed",this.handleConnectionStateChange,this)}emitConnectionStateChangedEvent(e,t){var n,a,c;let r=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&r!==e&&(t?t.emit("connection-state-changed",{prevState:r,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:r,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:r,state:e}),(c=this._publishingLocalVideoTrack)==null||c.emit("connection-state-changed",{prevState:r,state:e}))),s}publish(s){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:r}){this._peerConnection||this.initialize(),e&&(this._publishingLocalAudioTrack=e),t&&(this._publishingLocalVideoTrack=t),this._isPublishingAux=r;let n;t&&!r&&t.small&&(n=this._room.videoManager.smallTrack),this.sendMediaSettings(),St()?yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:n,isAuxiliary:r}):yield this.publishByAddTrack({localAudioTrack:e,localVideoTrack:t,smallTrack:n}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,r?(t&&(this.localAuxVideoTrack=t),e&&(this.localAuxAudioTrack=e)):(t&&(this.localMainVideoTrack=t),e&&(this.localMainAudioTrack=e)),this.installTrackMuteEvents(e,t),this.sendMutedFlag()})}publishByTransceiver(n){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:r,isAuxiliary:s}){this._log.info("publish by transceiver");let a=new MediaStream,c=t==null?void 0:t.outMediaTrack,l=e==null?void 0:e.outMediaTrack;l&&a.addTrack(l),c&&a.addTrack(c);let u=this._peerConnection.getTransceivers();if(u.length===0)this._peerConnection.addTransceiver(l||p.AUDIO,{direction:se.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(s?p.VIDEO:c||p.VIDEO,{direction:se.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(r||p.VIDEO,{direction:se.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(s?c||p.VIDEO:p.VIDEO,{direction:se.SENDONLY,streams:[a]}),yield this.connect();else{let h=[];if(l&&(u[0].sender.track||h.push(0),yield u[0].sender.replaceTrack(l),yield this.setBandwidth({bandwidth:(e==null?void 0:e.profile.bitrate)||40,type:p.AUDIO})),c){let m=s?3:1;yield u[m].sender.replaceTrack(c),yield this.setBandwidth({bandwidth:t.profile.bitrate,type:p.VIDEO,videoType:s?p.AUXILIARY:p.BIG}),h.push(m),r&&(yield u[2].sender.replaceTrack(r),yield this.setBandwidth({bandwidth:t.small.bitrate,type:p.VIDEO,videoType:p.SMALL}),h.push(2))}yield this.setTransceiverDirection(se.SENDONLY,h),yield this.doPublishChange(),t==null||t.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),t==null||t.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"})}})}publishByAddTrack(s){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:r}){this._log.info("publish by addtrack");let n=t==null?void 0:t.outMediaTrack,a=e==null?void 0:e.outMediaTrack;if(this._peerConnection&&this._peerConnection.connectionState!=="new"){e&&a&&(yield this.addTrack(e)),n&&(yield this.addTrack(t));return}let c=new MediaStream;if(a&&c.addTrack(a),n&&c.addTrack(n),a&&this._peerConnection.addTrack(a,c),n&&(this._peerConnection.addTrack(n,c),r)){let l=new MediaStream;l.addTrack(r),this._peerConnection.addTrack(r,l)}yield this.connect()})}enableSmall(e){return f(this,null,function*(){let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.setTransceiverDirection(se.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(se.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()})}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(r){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){if(!yr()){if(e&&e.outMediaTrack&&!t&&this.localMainVideoTrack){yield this.removeTrack(e),this.localMainAudioTrack=null;return}if(t&&t.outMediaTrack&&!e&&this.localMainAudioTrack){yield this.removeTrack(t),this.localMainVideoTrack=null;return}yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),this.emitConnectionStateChangedEvent("DISCONNECTED",t);return}let s=t&&t===this.localAuxVideoTrack,n=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),c=[];e&&(s?this.localAuxAudioTrack=null:this.localMainAudioTrack=null,!this.localAuxAudioTrack&&!this.localMainAudioTrack&&(yield a[0].replaceTrack(null),c.push(0))),n&&(s?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=L(M({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),c.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=L(M({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),c.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.setTransceiverDirection(se.INACTIVE,c),yield this.doPublishChange(!1)):yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),t==null||t.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return f(this,null,function*(){let t={state:this._room.publishState,constraintConfig:this._mediaSettings},r=yield this._signalChannel.sendWaitForResponse({command:Z.PUBLISH_STATE_CHANGE,data:t,responseCommand:G.PUBLISH_STATE_CHANGE_RESULT,enableLog:e});this.checkPublishResultCode(r.data.code,r.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:Z.UNPUBLISH,commandDesc:"unpublish",responseCommand:G.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===I.API_CALL_TIMEOUT)return Promise.resolve();throw t})}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let r=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:s,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:s=this._publishingLocalVideoTrack),bi){if(r&&r.outMediaTrack){let a=r.outMediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=r.profile.bitrate*1e3,this._mediaSettings.audioFs=a.sampleRate||0}if(s&&s.outMediaTrack){let a=s.outMediaTrack.getSettings();this._mediaSettings.videoWidth=a.width||0,this._mediaSettings.videoHeight=a.height||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=s.profile.bitrate*1e3,s.small&&(this._mediaSettings.smallVideoWidth=s.small.width,this._mediaSettings.smallVideoHeight=s.small.height,this._mediaSettings.smallVideoFps=s.small.frameRate,this._mediaSettings.smallVideoBps=s.small.bitrate*1e3)}if(n&&n.outMediaTrack){let a=n.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=a.width||0,this._mediaSettings.auxVideoHeight=a.height||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=n.profile.bitrate*1e3}}else r&&r.outMediaTrack&&(this._mediaSettings.audioChannel=r.profile.channelCount,this._mediaSettings.audioBps=r.profile.bitrate*1e3,this._mediaSettings.audioFs=r.profile.sampleRate),s&&s.outMediaTrack&&(this._mediaSettings.videoWidth=s.profile.width,this._mediaSettings.videoHeight=s.profile.height,this._mediaSettings.videoFps=s.profile.frameRate,this._mediaSettings.videoBps=s.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:Z.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:G.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return f(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is adding ${e.kind} track to current published local ${t?p.AUXILIARY:p.MAIN} stream`),St()?yield this.addTrackByTransceiver(e,t):yield this.addTrackBySender(e)})}addTrackByTransceiver(e,t){return f(this,null,function*(){var s;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===p.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),n===1&&((s=this.localMainVideoTrack)!=null&&s.small)&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===se.INACTIVE&&(yield this.setTransceiverDirection(se.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}addTrackBySender(e){return f(this,null,function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;yr()&&this._peerConnection.getTransceivers().findIndex(s=>s.direction==="stopped")>=0&&(this._log.warn("transceiver is stopping, negotiate sdp first"),yield this.updateOffer("remove",t));let r=this._peerConnection.getSenders().find(s=>s.track&&s.track.kind===t.kind);if(r&&r.track){this._log.warn("sender already exists, remove sender first");let s=r.track;this.removeSender(r),yield this.updateOffer("remove",s)}if(t&&this._peerConnection.addTrack(t,new MediaStream([t])),t.kind===p.VIDEO&&e instanceof Xe&&e.small){let s=new MediaStream,{smallTrack:n}=this._room.videoManager;s.addTrack(n),this._peerConnection.addTrack(n,s)}yield this.updateOffer("add",t)})}isNeedToResetOfferOrder(){if(this._sdpSemantics===Mo||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=Ne(e);for(let r=0;r<t.media.length;r++)if(Number(t.media[r].mid)===0&&t.media[r].type===p.VIDEO)return!0;return!1}removeSender(e){let t=null;yr()&&(t=this._peerConnection.getTransceivers().find(r=>r.sender&&r.sender.track===e.track)),this._peerConnection.removeTrack(e),t&&ue(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return f(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${t?p.AUXILIARY:p.MAIN} stream`),St()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)})}removeTrackByTransceiver(e,t){return f(this,null,function*(){if(!e.outMediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===p.AUDIO)yield r[0].sender.replaceTrack(null);else{let s=t?3:1;yield r[s].sender.replaceTrack(null),s===1&&e.small&&(yield r[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(se.INACTIVE,[s])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,t){return f(this,null,function*(){if(!te)return;let r=!1,s=!1;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let n=this._peerConnection.getTransceivers();if(t.forEach(l=>{n[l].direction!==e&&(n[l].direction=e,r=!0)}),r){this._log.info("updating offer");let l=yield this._peerConnection.createOffer();yield this.setOffer(l)}let a=-1,c=this._peerConnection.remoteDescription.sdp.split(`\r
|
|
65
|
+
`).map(l=>{if(l.match(new RegExp(`a=(${se.INACTIVE}|${se.RECVONLY}|${se.SENDONLY})`))&&a++,t.includes(a)){if(e===se.INACTIVE&&l.includes(`a=${se.RECVONLY}`))return s=!0,`a=${e}`;if(e===se.SENDONLY&&l.includes(`a=${se.INACTIVE}`))return s=!0,`a=${se.RECVONLY}`}return l}).join(`\r
|
|
66
|
+
`);s&&(this._log.info("updating answer"),yield this.setAnswer({type:"answer",sdp:c}))})}removeTrackBySender(e){return f(this,null,function*(){if(!e.outMediaTrack)return;if(e.kind===p.VIDEO&&this.isNeedToResetOfferOrder()&&this.localMainAudioTrack){this.reset(),this.initialize(),yield this.publish({localAudioTrack:this.localMainAudioTrack,isAuxiliary:!1});return}let t=this._peerConnection.getSenders().find(r=>r.track===e.outMediaTrack);t&&(this.removeSender(t),e.kind===p.VIDEO&&e.small&&this._peerConnection.getSenders().forEach(r=>{r.track&&r.track.kind===p.VIDEO&&this.removeSender(r)})),yield this.updateOffer("remove",e.outMediaTrack)})}replaceTrack(e){return f(this,null,function*(){var n;let t=(n=this._peerConnection)==null?void 0:n.getSenders();if(!t||t.length===0||!e.mediaTrack)return!1;let r;if(St()?r=e.kind===p.AUDIO?t[0]:t[1]:r=t.find(a=>a.track&&a.track.kind===e.kind),!r)return!1;let s=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info(`is replacing ${e.kind} track on ${s?p.AUXILIARY:p.MAIN} stream`),e.kind===p.AUDIO?yield r.replaceTrack(e.outMediaTrack):e.kind===p.VIDEO&&(s?t[3]&&(yield t[3].replaceTrack(e.outMediaTrack)):yield r.replaceTrack(e.outMediaTrack)),!0})}updateOffer(e,t){return f(this,null,function*(){try{let r=yield this._peerConnection.createOffer(f_);te&&r.sdp&&(r.sdp=this.setSDPDirection(r.sdp,"sendrecv")),yield this.setOffer(r);let s=this.updateMediaSettings(),n={action:e,trackId:t.id,kind:t.kind===p.VIDEO?"bigVideo":t.kind,type:"offer",sdp:this._peerConnection.localDescription.sdp,constraintConfig:s,state:this._room.publishState};this._log.info("createOffer success, sending updated offer to remote server"),this._log.debug(`updatedOffer: ${n.sdp}`);let a=yield this._signalChannel.sendWaitForResponse({command:Z.PUBLISH_CHANGE,data:n,responseCommand:G.UPDATE_OFFER_RESULT,timeout:tl,commandDesc:"update offer"}),{code:c,message:l}=a.data;c!==0&&this.checkPublishResultCode(c,l),yield this.acceptAnswer(a.data.data),r.sdp&&this.updateSSRC(r.sdp)}catch(r){throw this._log.error(r),r}})}setBandwidth(n){return f(this,arguments,function*({bandwidth:e,type:t,videoType:r,sdp:s}){if(!Tn())return s?t===p.VIDEO?this.updateVideoBandwidthRestriction(s,e,r):this.updateAudioBandwidthRestriction(s,e):void 0;let a,c=this._peerConnection.getSenders();if(St()){let l=0;t===p.VIDEO&&(r===p.SMALL?l=2:r===p.AUXILIARY?l=3:l=1),a=c[l]}else a=c.find(l=>l.track&&l.track.kind===t);if(a){let l=a.getParameters();(!l.encodings||l.encodings.length===0)&&(l.encodings=[{}]),l.encodings[0].maxBitrate=e*1e3;try{return yield a.setParameters(l),this._log.info(`${r||""}${t} bandwidth ${e} kbps`),s}catch(u){if(this._log.info(`failed to set bandwidth by setting maxBitrate: ${u}`),s)return t===p.VIDEO?this.updateVideoBandwidthRestriction(s,e,r):this.updateAudioBandwidthRestriction(s,e)}}return s})}updateVideoBandwidthRestriction(e,t,r){let s="AS";te&&(s="TIAS",t=t*1e3);let n=0,a=-1;return r===p.SMALL?n=1:r===p.AUXILIARY&&(n=2),e=e.replace(/m=video (.*)\r\nc=IN (.*)\r\n/g,c=>(a+=1,a===n?`${c}b=${s}:${t}\r
|
|
67
|
+
`:c)),e}updateAudioBandwidthRestriction(e,t){let r="AS";return te&&(r="TIAS",t=t*1e3),e=e.replace(/m=audio (.*)\r\nc=IN (.*)\r\n/,`m=audio $1\r
|
|
68
|
+
c=IN $2\r
|
|
69
|
+
b=${r}:${t}\r
|
|
70
|
+
`),e}removeBandwidthRestriction(e){return e.replace(/b=AS:.*\r\n/,"").replace(/b=TIAS:.*\r\n/,"")}removeVideoOrientation(e){return e.replace(/urn:3gpp:video-orientation/,"")}connect(){return f(this,null,function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(e){throw this.closePeerConnection(!0),this.uninstallEvents(),e}})}exchangeSDP(){return f(this,null,function*(){try{yield this.createOffer(),this._log.info("createOffer success, sending offer to remote server"),yield this.doExchangeSDP()}catch(e){throw e}})}createOffer(){return f(this,null,function*(){try{let e=yield this._peerConnection.createOffer(f_);yield this.setOffer(e),e.sdp&&this.updateSSRC(e.sdp)}catch(e){throw e}})}doExchangeSDP(){let e={command:Z.PUBLISH,responseCommand:G.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof Pt||this.localAuxVideoTrack instanceof Pt,state:this._room.publishState,constraintConfig:this._mediaSettings},enableLog:!1};return this._log.debug(`sending sdp offer: ${e.data.sdp}`),this._signalChannel.sendWaitForResponse(e).then(t=>{let{code:r,message:s,data:n}=t.data;return r===0?this.acceptAnswer(n):this.checkPublishResultCode(r,s)})}setSDPDirection(e,t,r="all"){let s=Ne(e);return s.media.forEach(n=>{(r==="all"||n.type===r)&&(n.direction=t)}),jt(s)}acceptAnswer(e){return f(this,null,function*(){var t,r,s,n,a;try{let c;if(this._publishingLocalAudioTrack||this._publishingLocalVideoTrack||this.isMainStreamPublished){let h=((t=this._publishingLocalVideoTrack)==null?void 0:t.profile.bitrate)||((r=this.localMainVideoTrack)==null?void 0:r.profile.bitrate),m=((s=this._publishingLocalAudioTrack)==null?void 0:s.profile.bitrate)||((n=this.localMainAudioTrack)==null?void 0:n.profile.bitrate);if(h){let _=this._isPublishingAux?p.AUXILIARY:p.BIG;c=yield this.setBandwidth({bandwidth:h,type:p.VIDEO,sdp:c,videoType:_})}m&&(c=yield this.setBandwidth({bandwidth:m,type:p.AUDIO,sdp:c}))}if(c=this.removeVideoOrientation(e.sdp),(a=this._publishingLocalVideoTrack)!=null&&a.small){let{smallStreamConfig:h}=this._room;c=yield this.setBandwidth({bandwidth:this._publishingLocalVideoTrack.small.bitrate||h.bitrate,type:p.VIDEO,videoType:p.SMALL,sdp:c})}let u={type:e.type,sdp:c};yield this.setAnswer(u),this._log.debug(`accepted answer: ${c}`)}catch(c){throw this._log.error(`failed to accept remote answer ${c}`),c}})}sendMutedFlag(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info(`send muted state: ${JSON.stringify(this._room.muteState)}`),this._signalChannel.send(Z.UPDATE_MUTE_STAT,this._room.muteState))}getIsReconnecting(){return this._isReconnecting}reconnect(){return f(this,null,function*(){if(!(He(Ds.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:Z.UNPUBLISH,responseCommand:G.UNPUBLISH_RESULT,enableLog:!1}),this.closePeerConnection(),this.initialize(),this.isMainStreamPublished&&(yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0})),this._log.warn("reconnect() uplink reconnect successfully"),this.stopReconnection()}catch(t){let r=Kt(this._reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${r/1e3}s`),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},r)}})}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&S.emit(A.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{Ne(e).media.forEach((r,s)=>{if(r.type===p.AUDIO){let n=r.ssrcs&&r.ssrcs[0];n&&(this.ssrc.audio=Number(n.id))}else{if(this._sdpSemantics===Mo&&r.ssrcGroups){r.ssrcGroups.forEach((a,c)=>{let l=Number(a.ssrcs.split(" ")[0]);c===0?this.ssrc.video=l:c===1&&(this.ssrc.small=l)});return}let n=r.ssrcs&&r.ssrcs[0];if(!n)return;switch(s){case 1:this.ssrc.video=Number(n.id);break;case 2:this.ssrc.small=Number(n.id);break;case 3:this.ssrc.auxiliary=Number(n.id);break;default:break}}})}catch(t){}}getVideoTrackId(e=p.VIDEO){if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===p.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===p.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===p.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===p.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===Hr?(this._log.error(je.NOT_SUPPORTED_H264ENCODE),new D({code:I.NOT_SUPPORTED_H264,message:H({key:B.NOT_SUPPORTED_H264ENCODE})})):new D({code:I.UNKNOWN,message:H({key:B.SIGNAL_RESPONSE_FAILED,data:{signalResponse:G.PUBLISH_RESULT,code:e,message:t}})})}};O([Y(e=>function(...t){return new Promise((r,s)=>{let n=a=>{this._emitter.off("closed",n),s(new D({code:I.API_CALL_ABORTED,message:H({key:B.CONNECTION_ABORTED,data:a})}))};this._emitter.on("closed",n),e.apply(this,t).then(r,s).finally(()=>{this._emitter.off("closed",n)})})})],Ds.prototype,"publish",1),O([Rt(521715,!1)],Ds.prototype,"unpublish",1),O([Ct(pt.prototype.afterConnect),Mc(pt.prototype.beforeConnect)],Ds.prototype,"connect",1);var im=Ds,ia=im;var ra=class{constructor(i,e){this.room=i;d(this,"_log");d(this,"_prevReportTime",0);d(this,"_prevReport",{});d(this,"_prevStats",null);d(this,"_prevEncoderImplementation","");d(this,"_prevAuxEncoderImpl","");d(this,"_prevQualityLimitationReason","");d(this,"_prevAuxQualityLimitationReason","");d(this,"_prevDecoderImplementationMap",new Map);d(this,"_decodeMap",new Map);d(this,"_prevQpSum",0);d(this,"_prevAuxQpSum",0);d(this,"totalBytesSent",0);d(this,"totalBytesReceived",0);d(this,"_spcStats",null);this._log=e}get statInterval(){return this._prevReportTime===0?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(i){return f(this,null,function*(){var s;let e={audio:{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0},video:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},small:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},auxiliary:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},rtt:0},t=i.getPeerConnection(),r=i.getSSRC();if(t)try{if((this._spcStats||(yield t.getStats())).forEach(a=>{var u,h,m,_,g,E,C,k,ae,w,Ye,N,y;let c,l;if(a.type==="outbound-rtp")if((a.mediaType||a.kind)===p.VIDEO){if(a.ssrc===r.video?(c=p.VIDEO,l=i.localMainVideoTrack):a.ssrc===r.small?c=p.SMALL:a.ssrc===r.auxiliary&&(l=i.localAuxVideoTrack,c=p.AUXILIARY),!c)return;e[c].bytesSent=a.bytesSent,e[c].packetsSent=a.packetsSent,e[c].framesEncoded=a.framesEncoded,T(a.keyFramesEncoded)||(e[c].keyFramesEncoded=a.keyFramesEncoded),T(a.nackCount)||(e[c].nackCount=a.nackCount),T(a.pliCount)||(e[c].pliCount=a.pliCount),T(a.retransmittedPacketsSent)||(e[c].retransmittedPacketsSent=a.retransmittedPacketsSent),T(a.totalEncodeTime)||(e[c].totalEncodeTime=a.totalEncodeTime),T(a.totalPacketSendDelay)||(e[c].totalPacketSendDelay=a.totalPacketSendDelay);let ge=0;if(!T(a.qpSum)&&!T(a.framesEncoded)&&a.framesEncoded>0){let ce=a.qpSum,De=a.framesEncoded,Ut=c===p.VIDEO?this._prevQpSum:this._prevAuxQpSum,No=c===p.VIDEO?((h=(u=i.localMainVideoTrack)==null?void 0:u.stat)==null?void 0:h.framesEncoded)||0:((_=(m=i.localAuxVideoTrack)==null?void 0:m.stat)==null?void 0:_.framesEncoded)||0;if(De>No&&ce>Ut){let Bd=ce-Ut,Fd=De-No;ge=Math.round(Bd/Fd),ge>35&&this._log.warn(`${c===p.AUXILIARY?"aux ":""}video encoder QP is high: ${ge}, resolution: ${a.frameWidth}x${a.frameHeight}, codec: ${i.videoCodec}, `)}c===p.VIDEO?this._prevQpSum=ce:c===p.AUXILIARY&&(this._prevAuxQpSum=ce)}if(!T(a.encoderImplementation)&&(c===p.VIDEO&&this._prevEncoderImplementation!==a.encoderImplementation||c===p.AUXILIARY&&this._prevAuxEncoderImpl!==a.encoderImplementation)){let ce=2,De=this._prevEncoderImplementation;c===p.AUXILIARY&&(ce=7,De=this._prevAuxEncoderImpl),S.emit("262",{userId:i.userId,streamType:ce,prevImplementation:De,implementation:a.encoderImplementation,codec:i.videoCodec,isHWCodec:a.powerEfficientEncoder}),this[c===p.VIDEO?"_prevEncoderImplementation":"_prevAuxEncoderImpl"]=a.encoderImplementation,this._log.info(`${c===p.AUXILIARY?"aux ":""}encoderImplementation change to ${a.encoderImplementation}(${i.videoCodec}) HWEncoder: ${a.powerEfficientEncoder}`)}a.ssrc===r.video?!T(a.qualityLimitationReason)&&a.bytesSent!==0&&this._prevQualityLimitationReason!==a.qualityLimitationReason&&(this._log.info(`qualityLimitationReason change to ${a.qualityLimitationReason}`),S.emit("263",{userId:i.userId,reason:a.qualityLimitationReason,prevReason:this._prevQualityLimitationReason,streamType:2,isQosClearFirst:(g=i.localMainVideoTrack)==null?void 0:g.isQosClearFirst}),this._prevQualityLimitationReason=a.qualityLimitationReason):a.ssrc===r.auxiliary&&!T(a.qualityLimitationReason)&&a.bytesSent!==0&&this._prevAuxQualityLimitationReason!==a.qualityLimitationReason&&(this._log.info(`aux qualityLimitationReason change to ${a.qualityLimitationReason}`),S.emit("263",{userId:i.userId,reason:a.qualityLimitationReason,prevReason:this._prevAuxQualityLimitationReason,streamType:7,isQosClearFirst:(E=i.localAuxVideoTrack)==null?void 0:E.isQosClearFirst}),this._prevAuxQualityLimitationReason=a.qualityLimitationReason)}else e.audio.bytesSent=a.bytesSent,e.audio.packetsSent=a.packetsSent;else if(a.type==="candidate-pair")Cr(a)&&(this.totalBytesSent=a.bytesSent,Q(a.currentRoundTripTime)&&(e.rtt=Math.floor(a.currentRoundTripTime*1e3)));else if(a.type==="media-source"){if(a.kind===p.AUDIO)e.audio.audioLevel=a.audioLevel||0,e.audio.totalAudioEnergy=a.totalAudioEnergy||0,a.echoReturnLoss,T((ae=(k=(C=i.localMainAudioTrack)==null?void 0:C.sourceTrack)==null?void 0:k.stats)==null?void 0:ae.deliveredFramesDuration)?a.totalSamplesDuration&&(e.audio.totalSamplesDuration=a.totalSamplesDuration):e.audio.totalSamplesDuration=i.localMainAudioTrack.sourceTrack.stats.deliveredFramesDuration/1e3;else if(a.kind===p.VIDEO)if(a.trackIdentifier===i.getVideoTrackId(p.VIDEO))if((N=(Ye=(w=i.localMainVideoTrack)==null?void 0:w.sourceTrack)==null?void 0:Ye.stats)!=null&&N.deliveredFrames){let{deliveredFrames:j}=i.localMainVideoTrack.sourceTrack.stats;e.video.framesCaptured=j,i.localMainVideoTrack.stat.framesCaptured&&i.localMainVideoTrack.stat.framesCaptured>0&&j>=i.localMainVideoTrack.stat.framesCaptured?e.video.fpsCapture=Math.floor((j-i.localMainVideoTrack.stat.framesCaptured)/this.statInterval):e.video.fpsCapture=a.framesPerSecond}else e.video.fpsCapture=a.framesPerSecond;else a.trackIdentifier===i.getVideoTrackId(p.AUXILIARY)?e.auxiliary.fpsCapture=a.framesPerSecond:e.small.fpsCapture=a.framesPerSecond}if(!T(a.audioLevel)&&((y=i.localMainAudioTrack)!=null&&y.mediaTrack)&&a.trackIdentifier===i.localMainAudioTrack.mediaTrack.id&&(e.audio.audioLevel=a.audioLevel||0),!T(a.frameWidth)){let j=p.SMALL;a.trackIdentifier===i.getVideoTrackId(p.VIDEO)||a.ssrc===r.video?j=p.VIDEO:(a.trackIdentifier===i.getVideoTrackId(p.AUXILIARY)||a.ssrc===r.auxiliary)&&(j=p.AUXILIARY),e[j].frameWidth=a.frameWidth,e[j].frameHeight=a.frameHeight,e[j].framesSent=a.framesSent}}),i.localMainAudioTrack){let a=i.localMainAudioTrack.getInternalAudioLevel(),c=i.localMainAudioTrack.getInternalAudioLevelAfter3A();e.audio.audioCaptureEnergyAfter3a=c,e.audio.micAudioLevel=a,e.audio.audioLevel===0&&(e.audio.audioLevel=c!=null?c:a)}this.totalBytesSent||(this.totalBytesSent+=e.audio.bytesSent+e.video.bytesSent+e.auxiliary.bytesSent),Object.keys(e).forEach(a=>{a===p.AUDIO?(i.localMainAudioTrack&&(i.localMainAudioTrack.stat=e[a]),i.localAuxAudioTrack&&(i.localAuxAudioTrack.stat=e[a])):a===p.VIDEO?i.localMainVideoTrack&&(i.localMainVideoTrack.stat=e[a]):a===p.AUXILIARY&&i.localAuxVideoTrack&&(i.localAuxVideoTrack.stat=e[a])})}catch(n){this._log.warn(`failed to getStats on sender connection ${n}`)}return e.rtt===0&&(e.rtt=((s=this.room.networkQuality)==null?void 0:s.uplinkRTT)||0),e})}getReceiverStats(i){return f(this,null,function*(){var r,s,n;let e={tinyId:i.tinyId,userId:i.userId,rtt:0,hasAudio:!1,hasVideo:!1,hasAuxiliary:!1,isSmallSubscribed:!1,audio:{bytesReceived:0,packetsReceived:0,packetsLost:0,p2pDelay:0,totalJitter:0,totalJitterCount:0,audioLevel:0,totalAudioEnergy:0,insertedSamplesForDeceleration:0,removedSamplesForAcceleration:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,freezeCount:0,totalFreezesDuration:0,totalJitter:0,totalJitterCount:0,p2pDelay:0,codec:""},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,totalJitter:0,totalJitterCount:0,p2pDelay:0,codec:""}},t=i.getPeerConnection();if(t)try{let{ssrc:a}=i,{muteState:c,subscribeState:l}=i;(this._spcStats||(yield t.getStats())).forEach(h=>{var m,_;if(h.type==="codec"&&this._decodeMap.set(h.id,h),h.type==="inbound-rtp"){let g=(h.mediaType||h.kind)===p.AUDIO;if(g){if(h.ssrc!==a.audio||!c.hasAudio)return;e.audio.packetsReceived=h.packetsReceived,e.audio.bytesReceived=h.bytesReceived,e.audio.packetsLost=h.packetsLost,h.insertedSamplesForDeceleration&&(e.audio.insertedSamplesForDeceleration=h.insertedSamplesForDeceleration),h.removedSamplesForAcceleration&&(e.audio.removedSamplesForAcceleration=h.removedSamplesForAcceleration),h.totalSamplesDuration&&(e.audio.totalSamplesDuration=h.totalSamplesDuration),h.totalSamplesReceived&&(e.audio.totalSamplesReceived=h.totalSamplesReceived),h.concealedSamples&&(e.audio.concealedSamples=h.concealedSamples),h.silentConcealedSamples&&(e.audio.silentConcealedSamples=h.silentConcealedSamples);let{remoteAudioTrack:E}=i;E.stat.packetsReceived=h.packetsReceived,E.stat.bytesReceived=h.bytesReceived,E.stat.packetsLost=h.packetsLost,e.audio.p2pDelay=E.stat.end2EndDelay,e.hasAudio=!0}else{if(te&&h.bytesReceived===0)return;let E;h.ssrc===a.video&&c.hasVideo&&(e.video.packetsReceived=h.packetsReceived,e.video.bytesReceived=h.bytesReceived,e.video.packetsLost=h.packetsLost,e.video.framesReceived=h.framesReceived,e.video.framesDecoded=h.framesDecoded,e.video.fpsDecoded=h.framesPerSecond,e.hasVideo=!0,i.videoCodec=Ht[(m=this._decodeMap.get(h.codecId))==null?void 0:m.mimeType.split("/")[1]]||"h264",e.video.codec=i.videoCodec,E=i.remoteVideoTrack,c.hasSmall&&l.smallVideo&&(e.isSmallSubscribed=!0),h.decoderImplementation&&(!this._prevDecoderImplementationMap.has(e.userId)||this._prevDecoderImplementationMap.get(e.userId)!==h.decoderImplementation)&&(this._log.info(`${e.userId} decoderImplementation change to ${h.decoderImplementation}(${i.videoCodec}) HWDecoder: ${h.powerEfficientDecoder}`),S.emit("262",{userId:this.room.userId,remoteUserId:e.userId,prevImplementation:this._prevDecoderImplementationMap.get(e.userId),implementation:h.decoderImplementation,codec:i.videoCodec,isHWCodec:h.powerEfficientDecoder}),this._prevDecoderImplementationMap.set(e.userId,h.decoderImplementation))),h.ssrc===a.auxiliary&&c.hasAuxiliary&&(e.auxiliary.packetsReceived=h.packetsReceived,e.auxiliary.bytesReceived=h.bytesReceived,e.auxiliary.packetsLost=h.packetsLost,e.auxiliary.framesReceived=h.framesReceived,e.auxiliary.framesDecoded=h.framesDecoded,e.auxiliary.fpsDecoded=h.framesPerSecond,E=i.remoteAuxiliaryTrack,e.auxiliary.p2pDelay=E.stat.end2EndDelay,e.hasAuxiliary=!0,e.video.codec=((_=this._decodeMap.get(h.codecId))==null?void 0:_.mimeType.split("/")[1].toLowerCase())||"h264"),E&&(E.stat.packetsReceived=h.packetsReceived,E.stat.bytesReceived=h.bytesReceived,E.stat.packetsLost=h.packetsLost,E.stat.framesReceived=h.framesReceived,E.stat.framesDecoded=h.framesDecoded,h.jitterBufferDelay&&(E.stat.jitterBufferDelay=Math.floor(h.jitterBufferDelay/h.jitterBufferEmittedCount*1e3)),e.video.p2pDelay=E.stat.end2EndDelay)}h.jitterBufferDelay&&(g?(e.audio.totalJitter=h.jitterBufferDelay,e.audio.totalJitterCount=h.jitterBufferEmittedCount):h.ssrc===a.video&&c.hasVideo?(e.video.totalJitter=h.jitterBufferDelay,e.video.totalJitterCount=h.jitterBufferEmittedCount):h.ssrc===a.auxiliary&&c.hasAuxiliary&&(e.auxiliary.totalJitter=h.jitterBufferDelay,e.auxiliary.totalJitterCount=h.jitterBufferEmittedCount))}else h.type==="candidate-pair"&&Cr(h)&&(this.totalBytesReceived=h.bytesReceived,Q(h.currentRoundTripTime)&&(e.rtt=Math.floor(h.currentRoundTripTime*1e3)));T(h.frameWidth)||((h.trackIdentifier===i.getMainStreamVideoTrackId()||h.ssrc===a.video)&&(e.video.frameWidth=h.frameWidth,e.video.frameHeight=h.frameHeight,i.remoteVideoTrack.stat.frameWidth=h.frameWidth,i.remoteVideoTrack.stat.frameHeight=h.frameHeight),(h.trackIdentifier===i.getAuxStreamVideoTrackId()||h.ssrc===a.auxiliary)&&(e.auxiliary.frameWidth=h.frameWidth,e.auxiliary.frameHeight=h.frameHeight,i.remoteAuxiliaryTrack.stat.frameWidth=h.frameWidth,i.remoteAuxiliaryTrack.stat.frameHeight=h.frameHeight)),!T(h.audioLevel)&&i.muteState.audioAvailable&&i.remoteAudioTrack.mediaTrack&&h.trackIdentifier===i.remoteAudioTrack.mediaTrack.id&&(e.audio.audioLevel=h.audioLevel||0,e.audio.totalAudioEnergy=h.totalAudioEnergy||0)}),e.audio.audioLevel===0&&i.muteState.audioAvailable&&(e.audio.audioLevel=i.remoteAudioTrack.getInternalAudioLevel()||0),this.totalBytesReceived||(this.totalBytesReceived+=e.audio.bytesReceived+e.video.bytesReceived+e.auxiliary.bytesReceived),T((r=i.remoteVideoTrack.player.stat)==null?void 0:r.fps)||(e.video.fpsRender=i.remoteVideoTrack.player.stat.fps),T((s=i.remoteAuxiliaryTrack.player.stat)==null?void 0:s.fps)||(e.auxiliary.fpsRender=i.remoteAuxiliaryTrack.player.stat.fps)}catch(a){this._log.warn(`failed to getStats on receiver connection ${a}`)}return e.rtt===0&&(e.rtt=((n=this.room.networkQuality)==null?void 0:n.uplinkRTT)||0),e})}getStats(i,e){return f(this,null,function*(){let t={},r,s=[];if(this.room.singlePC){let n=this.room.singlePC.getPeerConnection();if(!n)return{senderStats:t,receiverStats:s};let a=U(),c=yield n.getStats(),l=U();l-a>2e3&&this._log.warn(`getStats cost ${l-a}ms`);let u=[],h=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source","codec","media-playout"]);c.forEach(m=>h.has(m.type)&&u.push(m)),this._spcStats=u}i&&(t=yield this.getSenderStats(i));for(let[n,a]of e){let c=yield this.getReceiverStats(a);s.push(c)}return e.size&&(r=this.getMediaPlayoutStats(this._spcStats)),{senderStats:t,receiverStats:s,mediaPlayoutStats:r}})}getDifferenceValue(i,e){if(_i(i))return e;let t=e-i;return t<0?0:t}prepareReport({stats:i,report:e,freezeMap:t,uplinkConnection:r}){var m,_,g,E,C,k,ae,w,Ye;if(!_i(i.senderStats)){let N={uint32_audio_level:i.senderStats.audio.audioLevel*Dt,uint32_audio_energy:(i.senderStats.audio.totalAudioEnergy||0)*1e6,uint32_audio_codec_bitrate:i.senderStats.audio.bytesSent};i.senderStats.audio.micAudioLevel&&(N.uint32_mic_audio_level=i.senderStats.audio.micAudioLevel*Dt),T(i.senderStats.audio.audioCaptureEnergyAfter3a)||(N.uint32_audio_capture_energy_after3a=i.senderStats.audio.audioCaptureEnergyAfter3a*Dt),i.senderStats.audio.totalSamplesDuration&&(e.msg_device_info.uint32_audio_capture_cost=i.senderStats.audio.totalSamplesDuration);let y=[];if(i.senderStats.video.bytesSent){let ge={uint32_video_stream_type:2,uint32_video_codec_fps:i.senderStats.video.framesSent,uint32_video_capture_fps:i.senderStats.video.fpsCapture,uint32_video_width:i.senderStats.video.frameWidth,uint32_video_height:i.senderStats.video.frameHeight,uint32_video_codec_bitrate:i.senderStats.video.bytesSent,uint32_video_enc_fps:i.senderStats.video.framesEncoded,uint32_key_frame_count:i.senderStats.video.keyFramesEncoded,uint32_nack_count:i.senderStats.video.nackCount,uint32_pli_count:i.senderStats.video.pliCount,uint32_encode_cost:(i.senderStats.video.totalEncodeTime||0)*1e3,uint32_send_packet_cost:(i.senderStats.video.totalPacketSendDelay||0)*1e3,uint32_video_arq_packets:i.senderStats.video.retransmittedPacketsSent};y.push(ge)}if(i.senderStats.small.bytesSent){let ge={uint32_video_stream_type:3,uint32_video_codec_fps:i.senderStats.small.framesSent||0,uint32_video_capture_fps:i.senderStats.small.fpsCapture||0,uint32_video_width:i.senderStats.small.frameWidth||0,uint32_video_height:i.senderStats.small.frameHeight||0,uint32_video_codec_bitrate:i.senderStats.small.bytesSent,uint32_video_enc_fps:i.senderStats.small.framesEncoded||0,uint32_key_frame_count:i.senderStats.small.keyFramesEncoded,uint32_nack_count:i.senderStats.small.nackCount,uint32_pli_count:i.senderStats.small.pliCount,uint32_encode_cost:(i.senderStats.small.totalEncodeTime||0)*1e3,uint32_send_packet_cost:(i.senderStats.small.totalPacketSendDelay||0)*1e3,uint32_video_arq_packets:i.senderStats.small.retransmittedPacketsSent};y.push(ge)}if(i.senderStats.auxiliary.bytesSent){let ge={uint32_video_stream_type:7,uint32_video_codec_fps:i.senderStats.auxiliary.framesSent||0,uint32_video_capture_fps:i.senderStats.auxiliary.fpsCapture||0,uint32_video_width:i.senderStats.auxiliary.frameWidth||0,uint32_video_height:i.senderStats.auxiliary.frameHeight||0,uint32_video_codec_bitrate:i.senderStats.auxiliary.bytesSent,uint32_video_enc_fps:i.senderStats.auxiliary.framesEncoded||0,uint32_key_frame_count:i.senderStats.auxiliary.keyFramesEncoded,uint32_nack_count:i.senderStats.auxiliary.nackCount,uint32_pli_count:i.senderStats.auxiliary.pliCount,uint32_encode_cost:(i.senderStats.auxiliary.totalEncodeTime||0)*1e3,uint32_send_packet_cost:(i.senderStats.auxiliary.totalPacketSendDelay||0)*1e3,uint32_video_arq_packets:i.senderStats.auxiliary.retransmittedPacketsSent};y.push(ge)}let j={uint32_bitrate:0,uint32_lost:0,uint32_rtt:i.senderStats.rtt};e.msg_up_stream_info={msg_audio_status:N,msg_video_status:y,msg_network_status:j}}let{statInterval:s}=this;e.msg_down_stream_info=[],i.receiverStats.forEach(N=>{let y={msg_user_info:{str_identifier:N.userId,uint64_tinyid:N.tinyId},msg_network_status:{uint32_rtt:N.rtt,uint32_bitrate:0,uint32_lost:0},msg_audio_status:{},msg_video_status:[]};if(N.hasAudio){let j={uint32_audio_p2p_delay:N.audio.p2pDelay,uint32_audio_cache_ms:N.audio.totalJitter,uint32_audio_cache_ms_count:N.audio.totalJitterCount,uint32_audio_codec_bitrate:N.audio.bytesReceived,uint32_audio_total_bitrate:N.audio.bytesReceived,uint32_audio_level:N.audio.audioLevel*1e8,uint32_audio_energy:N.audio.totalAudioEnergy*1e6,uint32_audio_receive:N.audio.packetsReceived,uint32_audio_origin_lost:N.audio.packetsLost};y.msg_audio_status=j}if(N.hasVideo){let j=t.get(`${N.userId}_${Zd}`),ge=j?j.duration:0,ce={uint32_video_stream_type:N.isSmallSubscribed?3:2,uint32_video_receive_fps:N.video.framesReceived,uint32_video_width:N.video.frameWidth,uint32_video_height:N.video.frameHeight,uint32_video_codec_bitrate:N.video.bytesReceived,uint32_video_receive:N.video.packetsReceived,uint32_video_origin_lost:N.video.packetsLost,uint32_video_block_time:ge,uint32_video_dec_fps:N.video.framesDecoded,uint32_video_codec_fps:N.video.fpsRender,uint32_video_cache_ms:N.video.totalJitter,uint32_video_cache_ms_count:N.video.totalJitterCount,uint32_video_p2p_delay:N.video.p2pDelay,uint32_video_codec:N.video.codec};y.msg_video_status.push(ce)}if(N.hasAuxiliary){let j=t.get(`${N.userId}_${Kd}`),ge=j?j.duration:0,ce={uint32_video_stream_type:7,uint32_video_receive_fps:N.auxiliary.framesReceived,uint32_video_width:N.auxiliary.frameWidth,uint32_video_height:N.auxiliary.frameHeight,uint32_video_codec_bitrate:N.auxiliary.bytesReceived,uint32_video_receive:N.auxiliary.packetsReceived+N.auxiliary.packetsLost,uint32_video_origin_lost:N.auxiliary.packetsLost,uint32_video_block_time:ge,uint32_video_dec_fps:N.auxiliary.framesDecoded,uint32_video_codec_fps:N.video.fpsRender,uint32_video_cache_ms:N.auxiliary.totalJitter,uint32_video_cache_ms_count:N.auxiliary.totalJitterCount,uint32_video_p2p_delay:N.auxiliary.p2pDelay,uint32_video_codec:N.video.codec};y.msg_video_status.push(ce)}e.msg_down_stream_info.push(y)}),i.mediaPlayoutStats&&!_i(i.mediaPlayoutStats)&&(i.mediaPlayoutStats.synthesizedSamplesDuration*=1e3,i.mediaPlayoutStats.totalSamplesDuration*=1e3);let n=this._prevReport,a=this._prevStats;if(this._prevReport=JSON.parse(JSON.stringify(e)),this._prevStats=JSON.parse(JSON.stringify(i)),e.msg_up_stream_info.msg_audio_status&&n.msg_up_stream_info.msg_audio_status){let N=n.msg_up_stream_info.msg_audio_status,y=e.msg_up_stream_info.msg_audio_status;if(N.uint32_audio_codec_bitrate===0)y.uint32_audio_codec_bitrate=0;else{let j=this.getDifferenceValue(N.uint32_audio_codec_bitrate,y.uint32_audio_codec_bitrate);y.uint32_audio_codec_bitrate=Math.round(j*8/s),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=y.uint32_audio_codec_bitrate}(m=n.msg_device_info)!=null&&m.uint32_audio_capture_cost?(e.msg_device_info.uint32_audio_capture_cost=2*Math.floor(this.getDifferenceValue(n.msg_device_info.uint32_audio_capture_cost,e.msg_device_info.uint32_audio_capture_cost)*1e3/s),e.msg_device_info.uint32_audio_capture_cost>0&&((g=r==null?void 0:r.localMainAudioTrack)==null||g.updateAfter3aSilenceStartTime((_=i.senderStats.audio.audioCaptureEnergyAfter3a)!=null?_:i.senderStats.audio.micAudioLevel))):delete e.msg_device_info.uint32_audio_capture_cost}let c=n.msg_up_stream_info.msg_video_status;e.msg_up_stream_info.msg_video_status.forEach(N=>{let y=c.find(Ut=>Ut.uint32_video_stream_type===N.uint32_video_stream_type);if(!y||y.uint32_video_codec_bitrate===0){N.uint32_video_codec_bitrate=0,N.uint32_video_enc_fps=0,N.uint32_video_codec_fps=0;return}let j=0,ge=0,ce=0;y&&N.uint32_video_codec_bitrate>=y.uint32_video_codec_bitrate&&(j=y.uint32_video_codec_bitrate,ge=y.uint32_video_enc_fps,ce=y.uint32_video_codec_fps);let De=this.getDifferenceValue(j,N.uint32_video_codec_bitrate);N.uint32_video_codec_bitrate=Math.round(De*8/s),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=N.uint32_video_codec_bitrate,N.uint32_video_enc_fps=Math.round(this.getDifferenceValue(ge,N.uint32_video_enc_fps)/s),N.uint32_video_codec_fps=Math.round(this.getDifferenceValue(ce,N.uint32_video_codec_fps)/s),y.uint32_video_width===0&&y.uint32_video_height===0&&y.uint32_video_codec_fps===0&&(N.uint32_video_codec_fps=N.uint32_video_enc_fps),T(y.uint32_key_frame_count)||(N.uint32_key_frame_count=Math.round(this.getDifferenceValue(y.uint32_key_frame_count,N.uint32_key_frame_count))),T(y.uint32_nack_count)||(N.uint32_nack_count=Math.round(this.getDifferenceValue(y.uint32_nack_count,N.uint32_nack_count))),T(y.uint32_pli_count)||(N.uint32_pli_count=Math.round(this.getDifferenceValue(y.uint32_pli_count,N.uint32_pli_count))),T(y.uint32_video_arq_packets)||(N.uint32_video_arq_packets=Math.round(this.getDifferenceValue(y.uint32_video_arq_packets,N.uint32_video_arq_packets))),T(y.uint32_encode_cost)||(N.uint32_encode_cost=Math.round(this.getDifferenceValue(y.uint32_encode_cost,N.uint32_encode_cost)/s)),T(y.uint32_send_packet_cost)||(N.uint32_send_packet_cost=Math.round(this.getDifferenceValue(y.uint32_send_packet_cost,N.uint32_send_packet_cost)/s))});let u=n.msg_down_stream_info;e.msg_down_stream_info=e.msg_down_stream_info.filter(N=>u.find(y=>y.msg_user_info.uint64_tinyid===N.msg_user_info.uint64_tinyid));let h=e.msg_down_stream_info;if(h.forEach(N=>{let y=u.find(j=>j.msg_user_info.uint64_tinyid===N.msg_user_info.uint64_tinyid);if(!_i(N.msg_audio_status)&&!_i(y.msg_audio_status)){let j=N.msg_audio_status,ge=y.msg_audio_status,ce=this.getDifferenceValue(ge.uint32_audio_cache_ms_count,j.uint32_audio_cache_ms_count);delete j.uint32_audio_cache_ms_count,j.uint32_audio_cache_ms=Math.floor(1e3*this.getDifferenceValue(ge.uint32_audio_cache_ms,j.uint32_audio_cache_ms)/ce)||0;let De=this.room.remotePublishedUserMap.get(N.msg_user_info.str_identifier);De&&(De.remoteAudioTrack.stat.jitterBufferDelay=j.uint32_audio_cache_ms),j.uint32_audio_origin_lost=this.getDifferenceValue(ge.uint32_audio_origin_lost,j.uint32_audio_origin_lost),j.uint32_audio_receive=this.getDifferenceValue(ge.uint32_audio_receive,j.uint32_audio_receive),j.uint32_audio_receive+=j.uint32_audio_origin_lost;let Ut=this.getDifferenceValue(ge.uint32_audio_codec_bitrate,j.uint32_audio_codec_bitrate);j.uint32_audio_codec_bitrate=Math.round(Ut*8/s),j.uint32_audio_total_bitrate=Math.round(Ut*8/s)}else N.msg_audio_status={};if(N.msg_video_status&&y.msg_video_status){let j=y.msg_video_status;N.msg_video_status=N.msg_video_status.filter(ce=>j.find(De=>De.uint32_video_stream_type===ce.uint32_video_stream_type)),N.msg_video_status.forEach(ce=>{let De=j.find(Q_=>Q_.uint32_video_stream_type===ce.uint32_video_stream_type),Ut=De.uint32_video_receive,No=De.uint32_video_origin_lost,Bd=De.uint32_video_codec_bitrate,Fd=De.uint32_video_receive_fps,j_=De.uint32_video_dec_fps;ce.uint32_video_origin_lost=this.getDifferenceValue(No,ce.uint32_video_origin_lost),ce.uint32_video_receive=this.getDifferenceValue(Ut,ce.uint32_video_receive)+ce.uint32_video_origin_lost;let X_=this.getDifferenceValue(Bd,ce.uint32_video_codec_bitrate);ce.uint32_video_codec_bitrate=Math.round(X_*8/s);let z_=this.getDifferenceValue(Fd,ce.uint32_video_receive_fps);ce.uint32_video_receive_fps=Math.round(z_/s),ce.uint32_video_dec_fps=Math.round(this.getDifferenceValue(j_,ce.uint32_video_dec_fps)/s);let F=this.getDifferenceValue(De.uint32_video_cache_ms_count,ce.uint32_video_cache_ms_count);delete ce.uint32_video_cache_ms_count,ce.uint32_video_cache_ms=Math.floor(1e3*this.getDifferenceValue(De.uint32_video_cache_ms,ce.uint32_video_cache_ms)/F)||0})}}),!T((E=a==null?void 0:a.mediaPlayoutStats)==null?void 0:E.totalSamplesDuration)&&!T((C=i.mediaPlayoutStats)==null?void 0:C.totalSamplesDuration)){let N=2*Math.floor(this.getDifferenceValue((k=a==null?void 0:a.mediaPlayoutStats)==null?void 0:k.synthesizedSamplesDuration,(ae=i.mediaPlayoutStats)==null?void 0:ae.synthesizedSamplesDuration)/s),y=2*Math.floor(this.getDifferenceValue((w=a==null?void 0:a.mediaPlayoutStats)==null?void 0:w.totalSamplesDuration,(Ye=i.mediaPlayoutStats)==null?void 0:Ye.totalSamplesDuration)/s);e.msg_device_info.uint32_audio_play_cost=y-N}return a&&i.receiverStats.forEach(N=>{if(N.audio.concealedSamples&&N.audio.totalSamplesReceived){let y=a.receiverStats.find(j=>j.userId===N.userId);if(y&&y.audio.concealedSamples&&y.audio.totalSamplesReceived){let j=(N.audio.silentConcealedSamples||0)-(y.audio.silentConcealedSamples||0),ge=N.audio.concealedSamples-y.audio.concealedSamples,ce=N.audio.totalSamplesReceived-y.audio.totalSamplesReceived,De=Math.floor((ge-j)/ce*1e3*s);if(De>s*1e3/5){let Ut=h.find(No=>No.msg_user_info.str_identifier===N.userId);Ut&&(Ut.msg_audio_status.uint32_audio_block_time=De)}}}}),e.msg_down_stream_info.forEach(N=>{N.msg_video_status.forEach(y=>{y.uint32_video_codec_bitrate===0&&y.uint32_video_receive_fps===0&&(y.uint32_video_width=0,y.uint32_video_height=0)})}),e}getStatsReport(r){return f(this,arguments,function*({uplinkConnection:i,downlinkConnections:e,freezeMap:t}){let s={msg_device_info:{},msg_up_stream_info:{msg_audio_status:{uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_capture_energy_after3a:0},msg_video_status:[],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}},msg_down_stream_info:[{msg_user_info:{str_identifier:"",uint64_tinyid:0},msg_audio_status:{uint32_audio_cache_ms:0,uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_total_bitrate:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_final_lost:0},msg_video_status:[{uint32_video_cache_ms:0,uint32_video_stream_type:0,uint32_video_receive_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_codec_bitrate:0,uint32_video_receive:0,uint32_video_origin_lost:0,uint32_video_block_time:0,uint32_video_dec_fps:0}],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}}]},n=yield this.getStats(i,e);return JSON.stringify(this._prevReport)==="{}"&&(this._prevReport=JSON.parse(JSON.stringify(s))),this.prepareReport({stats:n,report:s,freezeMap:t,uplinkConnection:i}),this._prevReportTime=Date.now(),s})}getMediaPlayoutStats(i){let e;if(Ae(i)){for(let t of i)if(t.type==="media-playout"){let{synthesizedSamplesDuration:r,totalSamplesDuration:s}=t;e={synthesizedSamplesDuration:r,totalSamplesDuration:s};break}return e}}reset(){var i;this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map,(i=this.room.localMainVideoTrack)!=null&&i.stat&&(this.room.localMainVideoTrack.stat.framesCaptured=0)}};var T_=Je(at());function __(o){let i={totalCost:0,local:0,redirect:0,httpCache:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let e=performance.getEntriesByType("resource").reverse();for(let t of e)if(t.name===o){let r=Math.round(t.duration),s=Math.max(Math.round(t.domainLookupStart-t.startTime),0),n=t.redirectStart>0?Math.max(Math.round(t.redirectEnd-t.redirectStart),0):0,a=t.fetchStart>0?Math.max(Math.round(t.domainLookupStart-t.fetchStart),0):0,c=Math.round(t.domainLookupEnd-t.domainLookupStart),l=Math.round(t.requestStart-t.secureConnectionStart),u=Math.round(t.secureConnectionStart-t.connectStart),h=Math.round(t.responseStart-t.requestStart),m=Math.round(t.responseEnd-(t.responseStart||t.startTime));i=L(M({},i),{totalCost:r,local:s,redirect:n,httpCache:a,dns:c,tcp:u,tls:l,request:h,response:m});break}}catch(e){}return i}function g_(o){return new Promise(i=>f(this,null,function*(){let e=setTimeout(()=>{i({totalCost:1e4,local:0,dns:0,tcp:0,tls:0,request:0,response:0})},1e4),t=Date.now(),r=`https://${o}/?t=${t}`;try{yield fetch(r)}catch(n){}clearTimeout(e);let s=__(r);s.totalCost===0&&(s.totalCost=Date.now()-t),i(s)}))}var uI=700,Ro=class Ro extends T_.default{constructor({signalChannel:e,room:t}){super();d(this,"_room");d(this,"_signalChannel");d(this,"_log");d(this,"uplinkRTT",0);d(this,"uplinkLoss",0);d(this,"downlinkRTT",0);d(this,"downlinkLoss",0);d(this,"pingResults",{});d(this,"_downlinkPrevStatMap",new Map);d(this,"_downlinkLossAndRTTMap",new Map);d(this,"_interval",-1);d(this,"_uplinkNetworkQuality",0);d(this,"_downlinkNetworkQuality",0);this._room=t,this._signalChannel=e,this._log=R.createLogger({parent:t.getLogger(),id:"q",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this.initialize()}get uplinkNetworkQuality(){return this._uplinkNetworkQuality}set uplinkNetworkQuality(e){e!==this._uplinkNetworkQuality&&this._log.info(`uplink ${this.uplinkNetworkQuality} -> ${e}, rtt: ${this.uplinkRTT}, loss: ${this.uplinkLoss} ws-rtt: ${this._signalChannel.rtt}`),this._uplinkNetworkQuality=e}get downlinkNetworkQuality(){return this._downlinkNetworkQuality}set downlinkNetworkQuality(e){if(e!==this._downlinkNetworkQuality){let{rtt:t,loss:r}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._log.info(`downlink ${this.downlinkNetworkQuality} -> ${e}, rtt: ${t}, loss: ${r} ws-rtt: ${this._signalChannel.rtt}`)}this._downlinkNetworkQuality=e}initialize(){this._signalChannel.on(G.UPLINK_NETWORK_STATS,e=>{this.handleUplinkNetworkQuality(e)}),this._signalChannel.on(Ie.CONNECTION_STATE_CHANGED,this.handleSignalConnectionStateChange.bind(this)),this.start()}handleUplinkNetworkQuality(e){var c,l;if(e.data.code!==0)return;let t=e.data.data;if(t.delay&&this.updateDelay(t.delay),this._room.signalChannel&&t.wsRtt&&(this._room.signalChannel.rtt=t.wsRtt),!this._room.uplinkConnection){this.uplinkNetworkQuality=0,this.uplinkLoss=0,this.uplinkRTT=0;return}let r=(l=(c=this._room)==null?void 0:c.uplinkConnection)==null?void 0:l.getPeerConnection();if(r&&this.isPeerConnectionDisconnected(r)){this.uplinkNetworkQuality=6,this.uplinkLoss=0,this.uplinkRTT=0;return}let s=t.expectAudPkg+t.expectVidPkg,n=t.recvAudPkg+t.recvVidPkg,a=s-n;s===0&&n===0||(a<=0?this.uplinkLoss=0:this.uplinkLoss=Math.round(a/s*100),this.uplinkRTT=t.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this.uplinkLoss,this.uplinkRTT))}handleDownlinkNetworkQuality(){return f(this,null,function*(){if(this._room.remotePublishedUserMap.size===0){this.downlinkNetworkQuality=0;return}let e=[...this._room.remotePublishedUserMap.values()],t=e.filter(a=>{var c;return((c=a.getPeerConnection())==null?void 0:c.connectionState)===Re.CONNECTED});if(e.filter(a=>this.isPeerConnectionDisconnected(a.getPeerConnection())).length===e.length){this.downlinkNetworkQuality=6;return}for(let a=0;a<t.length;a++){let c=t[a].getPeerConnection();if(!c)return;let{rtt:l,totalPacketsLost:u,totalPacketsReceived:h}=yield this.getStat(c);if(!this._downlinkPrevStatMap.has(c)){this._downlinkPrevStatMap.set(c,{totalPacketsLost:u,totalPacketsReceived:h});continue}let m=0,_=this._downlinkPrevStatMap.get(c),g=u-_.totalPacketsLost,E=h-_.totalPacketsReceived;g<=0||E<0?m=0:m=Math.round(g/(g+E)*100),this._downlinkPrevStatMap.set(c,{totalPacketsLost:u,totalPacketsReceived:h}),this._downlinkLossAndRTTMap.set(c,{rtt:l,loss:m,userId:t[a].getUserId(),audioDelay:t[a].remoteAudioTrack.stat.end2EndDelay,videoDelay:t[a].remoteVideoTrack.stat.end2EndDelay})}if([...this._downlinkPrevStatMap.keys()].forEach(a=>{this.isPeerConnectionDisconnected(a)&&(this._downlinkPrevStatMap.delete(a),this._downlinkLossAndRTTMap.delete(a))}),this._downlinkLossAndRTTMap.size===0){this.downlinkRTT=0,this.downlinkLoss=0,this.downlinkNetworkQuality=0;return}let{rtt:s,loss:n}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this.downlinkRTT=s,this.downlinkLoss=n,this.downlinkNetworkQuality=this.getNetworkQuality(n,s)})}getStat(e){return f(this,null,function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!oo())return t;let r=e.getReceivers();try{for(let s=0;s<r.length;s++)(yield r[s].getStats()).forEach(c=>{c.type==="candidate-pair"&&Q(c.currentRoundTripTime)&&(t.rtt=Math.round(c.currentRoundTripTime*1e3)),c.type==="inbound-rtp"&&(c.mediaType===p.AUDIO||c.mediaType===p.VIDEO)&&(t.totalPacketsLost+=c.packetsLost,t.totalPacketsReceived+=c.packetsReceived)});return t.rtt===0&&(t.rtt=this.uplinkRTT),t}catch(s){return t}})}getAverageLossAndRTT(e){let t={rtt:0,loss:0};return Array.isArray(e)&&e.length>0&&(e.forEach(r=>{t.rtt+=r.rtt,t.loss+=r.loss}),Object.keys(t).forEach(r=>{t[r]=Math.round(t[r]/e.length)})),t}getNetworkQuality(e,t){return e>50||t>500?5:e>30||t>350?4:e>20||t>200?3:e>10||t>100?2:e>=0||t>=0?1:0}handleSignalConnectionStateChange(e){e.state==="DISCONNECTED"?(this.uplinkRTT=0,this.uplinkLoss=0,this.uplinkNetworkQuality=6):e.state==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=5)}handleUplinkConnectionStateChange({state:e}){e==="DISCONNECTED"?(this.uplinkLoss=0,this.uplinkRTT=0,this.uplinkNetworkQuality=6):e==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=5)}isPeerConnectionDisconnected(e){return!!(e&&(e.connectionState===Re.DISCONNECTED||e.connectionState===Re.FAILED||e.connectionState===Re.CLOSED))}setUplinkConnection(e){this._room.uplinkConnection=e,this._room.uplinkConnection?this._room.uplinkConnection.on("connection-state-changed",this.handleUplinkConnectionStateChange.bind(this)):(this.uplinkNetworkQuality=0,this.uplinkRTT=0,this.uplinkLoss=0)}start(){if(this._interval!==-1){this._log.info("network quality calculating is already started");return}this._log.debug("start network quality calculating"),this._interval=re.run("ric",()=>{var n;this.handleDownlinkNetworkQuality();let e=[...this._downlinkLossAndRTTMap.values()];S.emit(A.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this.uplinkRTT,loss:this.uplinkLoss},downlinks:e});let t=(n=this._room.scheduleResult.config)==null?void 0:n.pingDomainInfo,r={uplinkNetworkQuality:this.uplinkNetworkQuality,downlinkNetworkQuality:this.downlinkNetworkQuality,uplinkRTT:this.uplinkRTT,uplinkLoss:this.uplinkLoss,downlinkRTT:this.downlinkRTT,downlinkLoss:this.downlinkLoss};t&&(r=L(M({},r),{pingResults:this.uplinkRTT>t.rttThreshold||this.downlinkRTT>t.rttThreshold?this.pingResults:{}})),this.emit(Ro.EVENT_NETWORK_QUALITY,r);let s=Date.now();if(t&&(this.uplinkRTT>t.rttThreshold||this.downlinkRTT>t.rttThreshold)&&s-Ro.lastPingTime>t.interval*1e3){Ro.lastPingTime=Date.now();let a=t.domain.map(c=>g_(c).then(l=>({domain:c,cost:l.totalCost})));Promise.all(a).then(c=>{this.pingResults.isPoorNetwork=c.some(l=>l.cost>uI),this.pingResults.timestamp=s,this.pingResults.data=c,c.forEach(l=>{v.addSuccessEvent({key:521718,cost:l.cost})}),this._log.warn(`All ping results: ${JSON.stringify(c)}`)}).catch(c=>{this._log.warn(`Error during pinging domains: ${c}`)})}},{delay:2e3})}stop(){this._log.debug("stopped"),this._interval!==-1&&(re.clearTask(this._interval),this._interval=-1),this._downlinkLossAndRTTMap.clear(),this._downlinkPrevStatMap.clear()}updateDelay(e){let{tinyIdToUserIdMap:t}=this._room;e.forEach(({srcTinyId:r,videoDelay:s,audioDelay:n})=>{let a=t.get(r);if(a){let c=this._room.remotePublishedUserMap.get(a);c==null||c.setDelay({videoDelay:s,audioDelay:n})}})}};d(Ro,"EVENT_NETWORK_QUALITY","0"),d(Ro,"lastPingTime",0);var Os=Ro;function hI({fn:o,context:i}){return function(...e){try{let t=o.apply(i,e);return Tr(t)?t.catch(r=>R.error(`${o.name}() error observed ${r}`)):t}catch(t){R.error(`${o.name}() error observed ${t}`)}}}var Nd=class{constructor(i){d(this,"_frameWorkType");d(this,"_component");d(this,"_language");d(this,"connectionType");d(this,"_room");d(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,reportToken:void 0});d(this,"_keyPrefix");d(this,"_log");d(this,"_intervalId");d(this,"_firstPublishedUserList");d(this,"_networkQuality");d(this,"_basicInfo");d(this,"_pathJoinRoom");d(this,"_pathLeaveRoom");d(this,"_pathMainVideoMap");d(this,"_pathMainAudioMap");d(this,"_pathAuxiliaryMap");d(this,"_remoteStreamStatMap");d(this,"_localStreamStat");d(this,"_eventMap",new Map);d(this,"_captureCostSum",0);d(this,"_captureCostCount",0);d(this,"isDestroyed",!1);this._frameWorkType=i.frameWorkType||30,this._component=i.component||0,this.connectionType=i.connectionType||1,this._language=i.language||0,this._room=i.room,this._keyPrefix="key_point",this._log=R.createLogger({parent:this._room.getLogger(),id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(e=>{e.startsWith("handle")&&ue(this[e])&&(this[e]=hI({fn:this[e],context:this}))}),this.initData(),this.installEvents()}initData(){this._firstPublishedUserList=[],this._networkQuality={totalUplinkRTT:0,totalUplinkLoss:0,count:0,totalDownlinkRTTAndLossMap:new Map},this._basicInfo={string_sdk_version:$e,uint32_os_type:15,string_device_name:"",string_http_user_agent:navigator.userAgent,string_os_version:"",uint32_avg_rtt:0,uint32_avg_up_loss:0,uint32_scene:this._room.scene==="live"?1:0,uint32_joining_duration:0,uint32_networkType:0,uint32_framework:this._frameWorkType,uint32_component:this._component,uint32_connection_type:this.connectionType,uint32_caller_coding_language:this._language,string_domain:location.hostname},this._pathJoinRoom={uint64_start_time:0,uint64_send_request_acc_ip_cmd_start_time:0,uint64_send_request_acc_ip_cmd_end_time:0,uint64_send_request_enter_room_cmd_start_time:0,uint64_send_request_enter_room_cmd_end_time:0,uint64_send_first_video_frame_time:0,uint64_recv_userlist_time:0,uint64_end_time:0,int32_send_request_acc_ip_cmd_ret:0,int32_send_request_enter_room_cmd_ret:0,int32_end_ret:0},this._pathLeaveRoom={uint64_start_time:0,uint64_send_request_exit_room_cmd_start_time:0,uint64_send_request_exit_room_cmd_end_time:0,uint64_end_time:0,int32_send_request_exit_room_cmd_ret:0,int32_end_ret:0},this._localStreamStat={totalVideoBitrate:0,totalVideoFPS:0,totalVideoHeight:0,totalVideoWidth:0,totalAudioLevel:0,videoCount:0,audioLevelCount:0,publishStartTime:0,statsToReport:{uint32_audio_capture_db:0,uint32_video_big_capture_fps:0,uint32_video_big_bitrate:0,uint32_video_big_resolution:0,uint32_audio_capture_thread_health_zero_cnt:0,uint32_after3a_silence_duration:0}},this._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,Yr().then(()=>{this._basicInfo.string_os_version=ai(),this._basicInfo.string_device_name=ni()||this._basicInfo.string_os_version})}addEvent(i,e){return this._eventMap.set(i,e),S.on(i,e),this}installEvents(){this.handleUnload=this.handleUnload.bind(this),window.addEventListener("pagehide",this.handleUnload),this._room.once("banned",()=>this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})),this.addEvent(A.JOIN_START,this.handleJoinStart).addEvent(A.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(A.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(A.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(A.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(A.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(A.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(A.JOIN_FAILED,this.handleJoinFailed).addEvent(A.LEAVE_START,this.handleLeaveStart).addEvent(A.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(A.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(A.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(A.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(A.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(A.PUBLISH_START,this.handlePublishStart).addEvent(A.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(A.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(A.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(A.PLAY_TRACK_START,this.handlePlayStart).addEvent(A.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(A.PLAYER_STATE_CHANGED,({track:i,state:e,type:t})=>{!i.isRemote||!this.hitTest(i.room)||e==="PLAYING"&&(t===p.AUDIO?this.handleAudioPlaying(i):this.handleVideoPlaying(i))}).addEvent(A.SWITCH_ROOM_START,this.handleSwitchRoomStart).addEvent(A.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess).addEvent(A.SWITCH_ROOM_FAILED,this.handleSwitchRoomFailed).addEvent(A.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(A.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(A.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(A.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{if(!this.hitTest(i))return;let r=e.hasAudio||e.hasVideo||e.hasSmall,s=e.hasAuxiliary,n=t.hasAudio||t.hasVideo||t.hasSmall,a=t.hasAuxiliary;!r&&n&&this.handleRemoteStreamAdded(t.userId,"main"),!s&&a&&this.handleRemoteStreamAdded(t.userId,"auxiliary")}).addEvent(A.SINGLE_CONNECTION_STAT,({room:i,stat:e})=>{this.hitTest(i)&&(this._pathJoinRoom.int32_ice_cost=e.ice,this._pathJoinRoom.int32_dtls_cost=e.dtls,this._pathJoinRoom.int32_peer_connection_cost=e.peerConnection)})}uninstallEvents(){window.removeEventListener("pagehide",this.handleUnload),this._eventMap.forEach((i,e)=>S.off(e,i)),this._eventMap.clear()}destroy(){this.uninstallEvents(),re.clearTask(this._intervalId),this._pathJoinRoom.uint64_start_time===0&&(this._room=null),this.isDestroyed=!0}handleUnload(){this._room.isJoined&&this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})}handleJoinStart(i){this.hitTest(i.room)&&(this._pathJoinRoom.uint64_start_time===0&&(this._pathJoinRoom.uint64_start_time=Date.now()),i.params&&(T(i.params.frameWorkType)||(this._frameWorkType=i.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),T(i.params.component)||(this._component=i.params.component,this._basicInfo.uint32_component=this._component),T(i.params.language)||(this._language=i.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleJoinScheduleSuccess({room:i,detailCost:e}){if(this.hitTest(i)&&e){let{totalCost:t,local:r,dns:s,tcp:n,tls:a,request:c,response:l}=e;this._pathJoinRoom.int32_schedule_cost=t,this._pathJoinRoom.int32_schedule_local=r,this._pathJoinRoom.int32_schedule_dns=s,this._pathJoinRoom.int32_schedule_tcp=n,this._pathJoinRoom.int32_schedule_tls=a,this._pathJoinRoom.int32_schedule_request=c,this._pathJoinRoom.int32_schedule_response=l}}handleSignalConnectionStart({room:i}){this.hitTest(i)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time=Date.now())}handleSignalConnectionEnd({room:i,error:e}){this.hitTest(i)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time=Date.now(),e&&(this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret=e instanceof D?Number(e.getExtraCode()||e.getCode()):I.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}handleJoinSendCMD(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now())}handleJoinReceivedCMDResponce(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=i.code,i.code!==0&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}handleJoinSuccess(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_end_time===0&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=i.room.getSignalInfo())}handleJoinFailed({room:i,error:e}){this.hitTest(i)&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret===0&&(this._pathJoinRoom.int32_end_ret=e.code||this._pathJoinRoom.int32_send_request_enter_room_cmd_ret||this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret),setTimeout(()=>{this.report()}))}handleReceivedPublishUserList(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_recv_userlist_time===0&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=i.publishedUserList||[])}handleSendFirstVideoFrame({room:i}){this.hitTest(i)&&this._pathJoinRoom.uint64_send_first_video_frame_time===0&&this._pathJoinRoom.uint64_start_time!==0&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now())}handleLeaveStart(i){this.hitTest(i.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(i){var e;if(this.hitTest(i.room)&&this._pathLeaveRoom.uint64_end_time===0){if(this._pathLeaveRoom.uint64_end_time=Date.now(),this._pathJoinRoom.uint64_end_time!==0){this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time;let t=(e=this._room.audioManager.localAudioTrack)==null?void 0:e.after3aSilenceStartTime;t&&(this._localStreamStat.statsToReport.uint32_after3a_silence_duration=U()-t)}else this._log.warn("pathJoinRoom endTime is 0");this.report()}}handleLeaveSendCMD(i){this.hitTest(i.room)&&(this._pathLeaveRoom.uint64_send_request_exit_room_cmd_start_time=Date.now(),this._pathLeaveRoom.uint64_send_request_exit_room_cmd_end_time=Date.now())}handleSwitchRoomStart(i){if(this.hitTest(i.room)){let e=Date.now();this.report().then(()=>{this._pathJoinRoom.uint64_start_time=e,this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=e})}}handleSwitchRoomSuccess({room:i}){if(this.hitTest(i)&&this._pathJoinRoom.uint64_end_time===0){let e=Date.now();this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=e,this._pathJoinRoom.uint64_end_time=e,this._pathJoinRoom.int32_end_ret}}handleSwitchRoomFailed({room:i,error:e}){if(this.hitTest(i)){let t=Date.now();this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=t,this._pathJoinRoom.uint64_end_time=t,e&&(this._pathJoinRoom.int32_end_ret=e instanceof D?Number(e.getExtraCode()||e.getCode()):I.UNKNOWN)}}handleRemoteStreamAdded(i,e){var r;let t=`${i}_${e}`;if(!this._remoteStreamStatMap.has(t)){let s={userId:i,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:L(M({},mI),{msg_user_info:new oa({userId:i,tinyId:(r=this._room.remotePublishedUserMap.get(i))==null?void 0:r.tinyId,role:20})})};s.statsToReport.uint32_stream_type=e==="main"?2:7,this._remoteStreamStatMap.set(t,s)}}handleSubscribeStart({room:i,remotePublishedUser:e,streamType:t,subscribeState:r}){if(!this.hitTest(i))return;let{userId:s,tinyId:n,role:a}=e,c=new oa({userId:s,tinyId:n,role:a==="anchor"?20:21}),l=Date.now(),u=`${s}_${t}`,h=this._remoteStreamStatMap.get(u);h&&h.subscribeStartTime===0&&(h.subscribeStartTime=l),t==="main"?(e.muteState.hasVideo&&(r.video||r.smallVideo)&&!this._pathMainVideoMap.has(u)&&this._pathMainVideoMap.set(u,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:s,sendSubscribeCMDTime:l}),e.muteState.hasAudio&&r.audio&&!this._pathMainAudioMap.has(u)&&this._pathMainAudioMap.set(u,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:s,sendSubscribeCMDTime:l})):e.muteState.hasAuxiliary&&r.auxiliary&&!this._pathAuxiliaryMap.has(u)&&this._pathAuxiliaryMap.set(u,{sendSubscribeCMDTime:l})}handleSubscribed({room:i,remotePublishedUser:e,streamType:t}){if(this.hitTest(i)){let r=`${e.userId}_${t}`,s=this._remoteStreamStatMap.get(r);s&&s.subscribedTime===0&&(s.subscribedTime=Date.now())}}handlePlayStart({track:i}){if(!i.isRemote||!this.hitTest(i.room))return;let e=`${i.userId}_${i.streamType}`,t=this._remoteStreamStatMap.get(e);(t==null?void 0:t.playStreamTime)===0&&(t.playStreamTime=Date.now())}handleVideoLoadedData({track:i}){if(!i.isRemote||!this.hitTest(i.room))return;let e=`${i.userId}_${i.streamType}`,t=this._pathMainVideoMap.get(e);t&&t.statsToReport.uint64_combine_first_frame_time===0&&(t.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(i){let e=`${i.userId}_${i.streamType}`,t=Date.now(),r=this._pathMainVideoMap.get(e),s=this._remoteStreamStatMap.get(e);if(s){let{statsToReport:n}=s;if(!n.uint32_video_render_first&&i.streamType==="main"?this.hasVideoFlag(i.userId):this.hasAuxFlag(i.userId)){let a=t-this._pathJoinRoom.uint64_start_time;n.uint32_video_render_first=a,v.addNumber({key:516820,value:a})}}(r==null?void 0:r.statsToReport.uint64_render_first_frame_time)===0&&(r.statsToReport.uint64_render_first_frame_time=t)}handleAudioPlaying(i){let e=`${i.userId}_${i.streamType}`,t=this._pathMainAudioMap.get(e);t&&t.statsToReport.uint64_play_first_frame_time===0&&(t.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(i){this.hitTest(i.room)&&(this._networkQuality.totalUplinkLoss+=i.uplink.loss,this._networkQuality.totalUplinkRTT+=i.uplink.rtt,this._networkQuality.count++,i.downlinks.forEach(({rtt:e,loss:t,userId:r,videoDelay:s,audioDelay:n})=>{let a=this._networkQuality.totalDownlinkRTTAndLossMap.get(r);if(a)a.totalRTT+=e,a.totalLoss+=t,s&&(a.totalVideoDelay=(a.totalVideoDelay||0)+s,a.videoDelayCount=(a.videoDelayCount||0)+1),n&&(a.totalAudioDelay=(a.totalAudioDelay||0)+n,a.audioDelayCount=(a.audioDelayCount||0)+1),a.count++;else{let c,l,u,h;s&&(l=s,u=1),n&&(c=n,h=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(r,{totalRTT:e,totalLoss:t,count:1,totalAudioDelay:c,totalVideoDelay:l,audioDelayCount:h,videoDelayCount:u})}}))}handleHeartbeatStats(i){var e;if(this.hitTest(i.room)){let{msg_device_info:t,msg_up_stream_info:r,msg_down_stream_info:s}=i.report;if(r.msg_video_status[0]){let{uint32_video_codec_bitrate:n,uint32_video_enc_fps:a,uint32_video_width:c,uint32_video_height:l}=r.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=n,this._localStreamStat.totalVideoFPS+=a,this._localStreamStat.totalVideoWidth+=c,this._localStreamStat.totalVideoHeight+=l,this._localStreamStat.videoCount++}if(r.msg_audio_status){let{uint32_audio_level:n}=r.msg_audio_status;Math.floor(n/Dt*100)>0&&(this._localStreamStat.totalAudioLevel+=n/Dt,this._localStreamStat.audioLevelCount++)}s.forEach(n=>{let{msg_user_info:a,msg_audio_status:c,msg_video_status:l}=n,u=a.str_identifier,h=this._room.remotePublishedUserMap.get(u);if(l.forEach(m=>{let _=m.uint32_video_stream_type===2,g=m.uint32_video_stream_type===7,E=`${u}_${_?"main":"auxiliary"}`,C=this._remoteStreamStatMap.get(E);if(C&&(_&&(h!=null&&h.remoteVideoTrack.isSubscribed)||g&&(h!=null&&h.remoteAuxiliaryTrack))){C.totalVideoFPS+=m.uint32_video_receive_fps,C.totalVideoBitrate+=m.uint32_video_codec_bitrate,C.videoCount++,C.statsToReport.uint32_video_width===0&&(C.statsToReport.uint32_video_width=m.uint32_video_width),C.statsToReport.uint32_video_height===0&&(C.statsToReport.uint32_video_height=m.uint32_video_height);let k=_?h.remoteVideoTrack:h.remoteAuxiliaryTrack;k.stat.jitterBufferDelay&&(C.videoJitterBufferDelay=k.stat.jitterBufferDelay),k.stat.framesReceived&&(C.statsToReport.uint32_video_consume_render_rate=Math.floor(k.stat.framesDecoded/k.stat.framesReceived*hr(10,6)))}}),!Vo(c)){let m=`${u}_main`,_=this._remoteStreamStatMap.get(m);this._remoteStreamStatMap.has(m)&&_&&h!=null&&h.remoteAudioTrack.isSubscribed&&(_.totalAudioBitrate+=c.uint32_audio_codec_bitrate,_.audioCount++,h.remoteAudioTrack.stat.jitterBufferDelay&&(_.audioJitterBufferDelay=h.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(c.uint32_audio_level/Dt*100)>0&&(_.totalAudioLevel+=c.uint32_audio_level/Dt,_.audioLevelCount++),c.uint32_audio_block_time&&(_.statsToReport.uint32_audio_block_time+=c.uint32_audio_block_time))}}),t.uint32_audio_capture_cost&&(this._captureCostSum+=t.uint32_audio_capture_cost,this._captureCostCount+=1,this._captureCostCount>=100&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0)),t.uint32_audio_capture_cost===0&&((e=this._room.audioManager.localAudioTrack)==null?void 0:e.muted)===!1&&(this._localStreamStat.statsToReport.uint32_audio_capture_thread_health_zero_cnt+=1)}}handlePublishStart({room:i}){this.hitTest(i)&&this._localStreamStat.publishStartTime===0&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart({track:i}){i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess({track:i}){i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=0,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=0,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed({track:i,error:e}){let r={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[e.name]||(e instanceof D?e.getExtraCode()||e.getCode():I.UNKNOWN);i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=r,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=r,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}hasVideoFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&fr)>=0}hasAudioFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&_r)>=0}hasAuxFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&Fr)>=0}hitTest(i){return i===this._room}prepareReport(){if(this._captureCostCount>0&&!this._basicInfo.uint32_audio_capture_cost&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0),this._networkQuality.count>0&&(this._basicInfo.uint32_avg_rtt=Math.floor(this._networkQuality.totalUplinkRTT/this._networkQuality.count),this._basicInfo.uint32_avg_up_loss=Math.floor(this._networkQuality.totalUplinkLoss/this._networkQuality.count)),this._localStreamStat.videoCount>0){this._localStreamStat.statsToReport.uint32_video_big_capture_fps=Math.floor(this._localStreamStat.totalVideoFPS/this._localStreamStat.videoCount),this._localStreamStat.statsToReport.uint32_video_big_bitrate=Math.floor(this._localStreamStat.totalVideoBitrate/this._localStreamStat.videoCount);let i=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),e=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=i<<16|e}this._localStreamStat.audioLevelCount>0&&(this._localStreamStat.statsToReport.uint32_audio_capture_db=Math.floor(this._localStreamStat.totalAudioLevel/this._localStreamStat.audioLevelCount*100)),this._remoteStreamStatMap.forEach((i,e)=>{let{userId:t}=i,r=this._networkQuality.totalDownlinkRTTAndLossMap.get(t);if(r){let{totalLoss:u,count:h,audioDelayCount:m,videoDelayCount:_,totalAudioDelay:g,totalVideoDelay:E}=r;i.statsToReport.uint32_avg_down_loss=Math.floor(u/h),m&&g&&(i.statsToReport.uint32_audio_network_p2p_delay=Math.floor(g/m),i.audioJitterBufferDelay&&(i.statsToReport.uint32_p2p_delay=Math.floor(i.statsToReport.uint32_audio_network_p2p_delay+i.audioJitterBufferDelay))),_&&E&&(i.statsToReport.uint32_video_network_p2p_delay=Math.floor(E/_))}i.videoCount>0&&(i.statsToReport.uint32_video_avg_fps=Math.floor(i.totalVideoFPS/i.videoCount),i.statsToReport.uint32_video_avg_bitrate=Math.floor(i.totalVideoBitrate/i.videoCount)),i.audioCount>0&&(i.statsToReport.uint32_audio_recv_bitrate=i.statsToReport.uint32_audio_bitrate=Math.floor(i.totalAudioBitrate/i.audioCount)),i.audioLevelCount>0&&(i.statsToReport.uint32_audio_play_db=Math.floor(i.totalAudioLevel/i.audioLevelCount*100));let{callDurationCalculator:s}=this._room;s&&(i.statsToReport.uint32_audio_play_time=s.getDuration(e,p.AUDIO),i.statsToReport.uint32_video_play_time=s.getDuration(e,p.VIDEO)),i.statsToReport.uint32_video_render_first&&(i.statsToReport.uint32_video_render_first=Math.min(i.statsToReport.uint32_video_render_first,yo));let{badCaseDetector:n}=this._room,{dataFreeze:a,count:c}=n.getDataFreezeDuration(e),{renderFreeze:l}=n.getRenderFreezeDuration(e);i.statsToReport.uint32_video_block_count=c,i.statsToReport.uint32_video_block_time=Math.min(a,i.statsToReport.uint32_video_play_time),i.statsToReport.uint32_video_external_block_time=Math.min(l,i.statsToReport.uint32_video_play_time),i.statsToReport.uint32_audio_block_time=Math.min(i.statsToReport.uint32_audio_block_time,i.statsToReport.uint32_audio_play_time),n.isBlackStream(e)&&i.statsToReport.uint32_video_avg_fps===0?i.statsToReport.uint32_video_black_screen_subjective=1:i.statsToReport.uint32_video_black_screen_subjective=0}),this._pathMainAudioMap.forEach((i,e)=>{if(!this.hasAudioFlag(i.userId)){this._pathMainAudioMap.delete(e);return}i.statsToReport.uint64_play_first_frame_time-i.statsToReport.uint64_start_enter_time>yo&&(i.statsToReport.uint64_play_first_frame_time=i.statsToReport.uint64_start_enter_time+yo)}),this._pathMainVideoMap.forEach((i,e)=>{if(!this.hasVideoFlag(i.userId)){this._pathMainVideoMap.delete(e);return}i.statsToReport.uint64_render_first_frame_time-i.statsToReport.uint64_start_enter_time>yo&&(i.statsToReport.uint64_render_first_frame_time=i.statsToReport.uint64_start_enter_time+yo)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>yo&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+yo)}getReportData(){this._basicInfo.uint32_networkType=Jr();let i={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new oa({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:Bo(this._signalInfo.relayIp),uint32_client_ip:Bo(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*hr(2,31)),msg_path_enter_room:this._pathJoinRoom,msg_path_exit_room:this._pathLeaveRoom,msg_path_recv_video:[...this._pathMainVideoMap.values()].map(e=>e.statsToReport),msg_quality_statistics:[...this._remoteStreamStatMap.values()].map(e=>e.statsToReport),str_room_name:String(this._room.roomId||0),msg_path_recv_audio:[...this._pathMainAudioMap.values()].map(e=>e.statsToReport),uint32_info_client_ip:Bo(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,bytes_report_buf_from_0x1:this._signalInfo.endReportExtend,str_user_sig:this._room.userSig,bytes_report_token:this._signalInfo.reportToken};return qs(i),i}report(){return f(this,null,function*(){try{this.prepareReport();let i=this.getReportData();yield this.upload(i),this.initData()}catch(i){this._log.warn(i)}finally{this.isDestroyed&&(this._room=null)}})}upload(i){return f(this,null,function*(){if(i.msg_path_enter_room.uint64_start_time===0)return;let e=Number(this._room.sdkAppId),t=Ir.enable?Gi(i,2001,e):yield El(i),r=t instanceof ArrayBuffer,s=`${Wi(e,mr.KEY_POINT)}&gzip=${+r}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(s,t));let a=[this.uploadKVStat(v),this.uploadKVStat(ro)];n||a.push(Ji({url:s,body:t,priority:"low"})),yield Promise.all(a)})}setConnectionType(i){this.connectionType=i,this._basicInfo.uint32_connection_type=i}uploadKVStat(i){return f(this,null,function*(){let e=i.getReportData(this._room.userSig,this._signalInfo.reportToken);if(e.stats_count.length===0&&e.stats_distribution.length===0)return;e.msg_sdk_basic_info=L(M({},e.msg_sdk_basic_info),{bytes_device_name:this._basicInfo.string_device_name||"",bytes_os_version:this._basicInfo.string_os_version||"",uint32_framework:this._frameWorkType,uint32_network_type:this._basicInfo.uint32_networkType||0}),this._log.debug(e);let t=Ir.enable?Gi(e,2003,this._room.sdkAppId):yield El(e),r=t instanceof ArrayBuffer,s=`${Wi(+this._room.sdkAppId,mr.KV_STAT)}&gzip=${+r}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(s,t)),n||Ji({url:s,body:t})})}};O([Ot({settings:{timeout:500,retries:3}})],Nd.prototype,"upload",1);var yo=5e3,mI={msg_user_info:null,uint32_video_avg_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_avg_bitrate:0,uint32_video_block_time:0,uint32_video_play_time:0,uint32_audio_block_time:0,uint32_audio_play_time:0,uint32_audio_play_db:0,uint32_avg_down_loss:0,uint32_stream_type:0,uint32_video_block_count:0,uint32_audio_block_count:0,uint32_audio_bitrate:0,uint32_video_black_screen_subjective:0,uint32_audio_recv_bitrate:0,uint32_video_external_block_time:0,uint32_video_consume_render_rate:0},oa=class{constructor(i){d(this,"str_identifier");d(this,"str_tinyid");d(this,"uint32_role");this.str_identifier=String(i.userId),this.str_tinyid=String(i.tinyId||0),this.uint32_role=i.role}},E_=Nd;var rm=class{constructor(){d(this,"_startTime");d(this,"_endTime");this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=U())}stop(){this._endTime===0&&(this._endTime=U())}getDuration(){return this._endTime===0?U()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},Dd=rm;var om=class{constructor(i){d(this,"_room",null);d(this,"_durationMap");d(this,"_eventMap",new Map);this._room=i.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(A.REMOTE_TRACK_SUBSCRIBED,this.handleSubscribed).set(A.REMOTE_TRACK_UNSUBSCRIBED,this.handleUnsubscribed).set(A.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{var n;let{userId:r}=t;if(!this.hitTest(i))return;e.hasAudio&&!t.hasAudio&&this.stopDurationItem(`${r}_main`,p.AUDIO),e.hasVideo&&!t.hasVideo&&this.stopDurationItem(`${r}_main`,p.VIDEO),e.hasAuxiliary&&!t.hasAuxiliary&&this.stopDurationItem(`${r}_auxiliary`,p.VIDEO);let s=(n=this._room)==null?void 0:n.remotePublishedUserMap.get(r);s&&(!e.hasAudio&&t.hasAudio&&s.remoteAudioTrack.isSubscribed&&this.addDuractionItem(r,p.AUDIO,"main"),!e.hasVideo&&t.hasVideo&&s.remoteVideoTrack.isSubscribed&&this.addDuractionItem(r,p.VIDEO,"main"),!e.hasAuxiliary&&t.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(r,p.VIDEO,"auxiliary"))}),this._eventMap.forEach((i,e)=>S.on(e,i,this))}uninstallEvents(){this._eventMap.forEach((i,e)=>S.off(e,i,this)),this._eventMap.clear()}handleSubscribed({track:i}){if(!this.hitTest(i.room))return;let{userId:e,streamType:t,kind:r}=i;i.isSubscribed?this.addDuractionItem(e,r,t):this.stopDurationItem(`${e}_${t}`,r)}handleUnsubscribed({track:i}){this.hitTest(i.room)&&this.stopDurationItem(`${i.userId}_${i.streamType}`,i.kind)}isRecording(i){return i.findIndex(e=>e.endTime===0)>=0}addDuractionItem(i,e,t){let r=`${i}_${t}`,s=new Dd,n=this._durationMap.get(r);n?this.isRecording(n[e])||n[e].push(s):this._durationMap.set(r,{userId:i,type:t,audio:e===p.AUDIO?[s]:[],video:e===p.AUDIO?[]:[s]})}stopDurationItem(i,e){if(this._durationMap.has(i)){let r=this._durationMap.get(i)[e].find(s=>s.endTime===0);r&&r.stop()}}hitTest(i){return this._room===i}getDuration(i,e){return this._durationMap.has(i)?this._durationMap.get(i)[e].reduce((r,s)=>r+s.getDuration(),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},S_=om;var sm=class{constructor(){d(this,"renderFreezeMap",new Map);d(this,"dataFreezeMap",new Map)}get(i,e){let t=this.renderFreezeMap.get(i),r=this.dataFreezeMap.get(i);return e?e==="data"?r:t:(Pe||te)&&t&&r&&t.duration>r.duration?t:r}set(i,e,t){t==="data"?this.dataFreezeMap.set(i,e):this.renderFreezeMap.set(i,e)}clear(){this.renderFreezeMap.clear(),this.dataFreezeMap.clear()}},nm=class{constructor(i){d(this,"_room");d(this,"_renderFreezeMap",new Map);d(this,"_isVideoPlayingEventFiredMap",new Map);d(this,"_dataFreezeMap",new Map);d(this,"_monitorFreezeData",new sm);d(this,"_eventMap",new Map);d(this,"_videoEncodeFailedCount",0);d(this,"_audioEncodeFailedCount",0);d(this,"_encodeFailedThreshold",3);d(this,"eventListenerMap",new Map);this._room=i.room,this.installEvents()}getRenderFreezeMap(){return this._renderFreezeMap}getDataFreezeMap(){return this._dataFreezeMap}installEvents(){this._eventMap.set(A.LEAVE_SUCCESS,({room:i})=>{this.hitTest(i)&&this.stop()}).set(A.PLAY_TRACK_START,this.onPlayTrackStart).set(A.UNSUBSCRIBE_SUCCESS,({room:i,streamType:e,remotePublishedUser:t})=>{if(!this.hitTest(i))return;let{userId:r}=t,s=`${r}_${e}`;this.stopDataFreeze({key:s,userId:r,type:e})}).set(A.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{if(!this.hitTest(i))return;let{userId:r}=t;if(e.hasVideo&&!t.hasVideo){let s="main",n=`${t.userId}_${s}`;this.stopDataFreeze({key:n,userId:r,type:s})}if(e.hasAuxiliary&&!t.hasAuxiliary){let s="auxiliary",n=`${t.userId}_${s}`;this.stopDataFreeze({key:n,userId:r,type:s})}}).set(A.PLAYER_STATE_CHANGED,({track:i,state:e,reason:t,type:r})=>{if(!(!i.isRemote||!i.room||!this.hitTest(i.room)||r!==p.VIDEO)){if(e==="PLAYING"){let s=`${i.userId}_${i.streamType}`;this._isVideoPlayingEventFiredMap.set(s,!0)}t===p.MUTE?this.onVideoTrackMuted(i):t===p.UNMUTE&&this.onVideoTrackUnmuted(i)}}).set(A.HEARTBEAT_REPORT,this.onHearBeatReport).set(A.REMOTE_VIDEO_PLAY_START,this.onRemoteVideoPlayStart).set(A.REMOTE_VIDEO_PLAY_FINISH,this.onRemoteVideoPlayEnd),this._eventMap.forEach((i,e)=>S.on(e,i,this))}uninstallEvents(){this._eventMap.forEach((i,e)=>S.off(e,i,this)),this._eventMap.clear()}stop(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}onVideoTrackMuted(i){if(!i.isSubscribed)return;let{userId:e,streamType:t}=i,r=`${e}_${t}`,s=this._dataFreezeMap.get(r),n=new Dd;s?s.durationItemList.push(n):this._dataFreezeMap.set(r,{userId:e,type:t,durationItemList:[n],isFreezing(){let a=this.durationItemList[this.durationItemList.length-1];return a&&a.endTime===0}})}onVideoTrackUnmuted(i){if(!i.isSubscribed)return;let{userId:e,streamType:t}=i,r=`${e}_${t}`;this.stopDataFreeze({key:r,userId:e,type:t})}onHearBeatReport({room:i,report:e}){if(this.hitTest(i)){if(e.msg_up_stream_info.msg_video_status){let t=e.msg_up_stream_info.msg_video_status,r=Array.from(this._room.localTracks).find(n=>n.kind==="video"&&!n.isScreen),s=(r==null?void 0:r.stat.bytesSent)||0;if((r==null?void 0:r.isMediaTrackActive)===!1||s<=0||r!=null&&r.isUseCustomSource)return;t.forEach(n=>{n.uint32_video_stream_type===2&&(n.uint32_video_capture_fps!==0&&n.uint32_video_codec_bitrate===0&&n.uint32_video_enc_fps===0&&(r!=null&&r.isPublished)?(this._videoEncodeFailedCount+=1,this._videoEncodeFailedCount===this._encodeFailedThreshold&&oe.uploadEvent({userId:this._room.userId,log:`stat-${Ze.VIDEO_ENCODE_FAILED_DURING_CALL}`})):this._videoEncodeFailedCount=0)})}if(e.msg_up_stream_info.msg_audio_status){let t=e.msg_up_stream_info.msg_audio_status,r=Array.from(this._room.localTracks).find(n=>n.kind==="audio"),s=(r==null?void 0:r.stat.bytesSent)||0;if((r==null?void 0:r.isMediaTrackActive)===!1||s<=0)return;t.uint32_audio_codec_bitrate===0&&(r!=null&&r.isPublished)?(this._audioEncodeFailedCount+=1,this._audioEncodeFailedCount===this._encodeFailedThreshold&&oe.uploadEvent({userId:this._room.userId,log:`stat-${Ze.AUDIO_ENCODE_FAILED_DURING_CALL}`})):this._audioEncodeFailedCount=0}}}stopDataFreeze({key:i,userId:e,type:t}){let r=this._dataFreezeMap.get(i);if(!r||!r.isFreezing())return;let s=r.durationItemList[r.durationItemList.length-1];s.stop();let n=s.getDuration();if(n>Sa){let a=this._monitorFreezeData.get(i,"data");this._monitorFreezeData.set(i,{userId:e,type:t,duration:a?a.duration+n:n},"data")}else r.durationItemList.pop()}getTotalDuration(i){return i.reduce((e,t)=>{let r=t.getDuration();return e+Math.min(r,5e3)},0)}onPlayTrackStart({track:i}){if(!i.isRemote||!this.hitTest(i.room)||i.kind!==p.VIDEO||!i.isRemotePublished)return;let e=`${i.userId}_${i.streamType}`;this._isVideoPlayingEventFiredMap.has(e)||this._isVideoPlayingEventFiredMap.set(e,!1)}getDataFreezeDuration(i){let e={dataFreeze:0,count:0},t=this._dataFreezeMap.get(i);if(t){if(t.isFreezing()){let r=t.durationItemList[t.durationItemList.length-1];r.stop(),r.getDuration()<Sa&&t.durationItemList.pop()}e.dataFreeze=this.getTotalDuration(t.durationItemList),e.count=t.durationItemList.length}return e}getRenderFreezeDuration(i){let e={renderFreeze:0,count:0},t=this._renderFreezeMap.get(i);return t&&(e.renderFreeze=t.totalDuration,e.count=t.count),e}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(i){return this._isVideoPlayingEventFiredMap.has(i)?!this._isVideoPlayingEventFiredMap.get(i):!1}onRemoteVideoPlayStart({track:i,player:e}){var n;if(!Ki())return;let t=0,r=()=>{document.hidden||(t=0)};document.addEventListener("visibilitychange",r);let s=(a,c)=>{var l;if(t){let u=i.decodeFPS,h=u>0&&u<=5?600+1e3/u:600,m=c.presentationTime-t;if(m>h){m=Math.min(m,5e3);let _=`${i.userId}_${i.streamType}`,g=this._monitorFreezeData.get(_,"render");g?g.duration+=m:this._monitorFreezeData.set(_,{userId:i.userId,type:i.streamType,duration:m},"render");let E=this._renderFreezeMap.get(_);E?(E.totalDuration+=m,E.count+=1):this._renderFreezeMap.set(_,{userId:i.userId,type:i.streamType,totalDuration:m,count:1})}}t=c.presentationTime,(l=e.element)==null||l.requestVideoFrameCallback(s)};(n=e.element)==null||n.requestVideoFrameCallback(s),this.eventListenerMap.set(`${i.userId}_${i.streamType}`,{onVisibilityChange:r})}onRemoteVideoPlayEnd({track:i,player:e}){let t=`${i.userId}_${i.streamType}`,r=this.eventListenerMap.get(t);r&&document.removeEventListener("visibilitychange",r.onVisibilityChange)}resetMonitor(){this._monitorFreezeData.clear()}hitTest(i){return i===this._room}destroy(){this.uninstallEvents()}},I_=nm;var R_=Je(at(),1);var Od=class{constructor(i,e,t,r,s,n=4/3){this.vbMode=i;this.faceDetectorHash=t;this.visionTaskRegistry=r;this.logger=s;d(this,"animationState");d(this,"originalAspect");d(this,"totalOffsetX",0);d(this,"totalOffsetY",0);d(this,"defaultScaleRatio",.1);d(this,"isRecovering",!1);d(this,"boundaryY",280);d(this,"lastActionTime",0);d(this,"restTime",400);this.animationState={current:null,target:null,animating:!1,debounceTimer:null,startTime:0,duration:3e3,debounceTime:150,movementThreshold:30,debounceThreshold:15},this.addEvent(this.vbMode,!!this.faceDetectorHash),this.originalAspect=n||4/3,this.visionTaskRegistry.setVideo(this.faceDetectorHash,e)}addEvent(i,e,t){let s=[{key:570704,error:t!=null?t:e?void 0:11},{key:570705,error:t!=null?t:e?void 0:22}][i-1];s&&(e?v.addSuccessEvent({key:s.key}):v.addFailedEvent({key:s.key,error:s.error}))}actionCentering(i){let e=Date.now();if(this.animation(),!this.faceDetectorHash||e-this.lastActionTime<this.restTime||this.animationState.animating)return;let{videoWidth:t,videoHeight:r}=i;this.animationState.debounceThreshold=t/30,this.animationState.movementThreshold=t/20,this.boundaryY=r*.6;try{let s=this.visionTaskRegistry.getResult(this.faceDetectorHash);if(s.detections.length<=0){this.vbMode===1&&this.recoverOriginal(t,r);return}let n=s.detections[0].boundingBox,a=n.originX,c=n.originY,l=n.width,u=n.height;this.vbMode===1?this.dualStageCropping(t,r,a,c,l,u):this.vbMode===2&&this.movingPortrait(t,r,a,c,l,u)}catch(s){this.logger.error(s)}this.lastActionTime=e}calculateBoundary(i,e,t,r){let s,n;return i>e/2?(s=e-t-r,n=t-s):(s=t,n=0),{min:s,offset:n}}calculateTargetPosition(i,e,t,r,s,n,a=.4){let c=i+t/2,l=e+r/2,u,h,{min:m,offset:_}=this.calculateBoundary(c,s,i,t),{min:g,offset:E}=this.calculateBoundary(l,n,e,r);return u=2*m+t,h=2*g+r,u/h>this.originalAspect?(u=h*this.originalAspect,_=c-u/2):(h=u/this.originalAspect,E=l-h/2),t/s>a&&(_=0,E=0,u=s,h=n),_=Math.max(0,Math.min(_,s-u)),E=Math.max(0,Math.min(E,n-h)),{sx:_,sy:E,cropWidth:u,cropHeight:h,timestamp:Date.now()}}processFacePositionCrop(i,e,t){if(!this.animationState.current||!this.animationState.target){let a={sx:0,sy:0,cropWidth:e,cropHeight:t,timestamp:Date.now()};this.animationState.current=a,this.animationState.target=a;return}let r=this.positionDistance(this.animationState.target,i),s=this.positionDistance(this.animationState.current,i),n=this.animationState.current.cropWidth/e;r>this.animationState.debounceThreshold*n&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&s>this.animationState.movementThreshold*n&&(this.animationState.target=i,this.animationState.debounceTimer=setTimeout(()=>{this.animationState.startTime=Date.now(),this.animationState.animating=!0},this.animationState.debounceTime))}processFacePositionPortrait(i){if(!this.animationState.current||!this.animationState.target){this.animationState.current=M({},i),this.animationState.target=M({},i);return}let e=this.positionDistance(this.animationState.current,i),t=this.positionDistance(this.animationState.target,i);e>this.animationState.debounceThreshold&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&t>this.animationState.movementThreshold&&(this.animationState.current=i,this.animationState.debounceTimer=setTimeout(()=>{this.animationState.startTime=Date.now(),this.animationState.animating=!0},this.animationState.debounceTime))}animation(){if(!this.animationState.animating)return;let i=Date.now()-this.animationState.startTime,e=Math.min(i/this.animationState.duration,1),t=r=>r<.5?2*r*r:-1+(4-2*r)*r;if(this.animationState.current&&this.animationState.target){let r=(this.animationState.target.sx-this.animationState.current.sx)*t(e);this.animationState.current.sx+=r,this.totalOffsetX+=r;let s=(this.animationState.target.sy-this.animationState.current.sy)*t(e);if(this.animationState.current.sy+=s,this.totalOffsetY+=s,this.animationState.current.cropWidth+=(this.animationState.target.cropWidth-this.animationState.current.cropWidth)*t(e),this.animationState.current.cropHeight+=(this.animationState.target.cropHeight-this.animationState.current.cropHeight)*t(e),this.animationState.current.scaleRatio&&this.animationState.target.scaleRatio&&(this.animationState.current.scaleRatio+=(this.animationState.target.scaleRatio-this.animationState.current.scaleRatio)*t(e)),Q(this.animationState.current.scaleOffsetX)&&Q(this.animationState.target.scaleOffsetX)&&Q(this.animationState.current.scaleOffsetY)&&Q(this.animationState.target.scaleOffsetY)){let n=(this.animationState.target.scaleOffsetX-this.animationState.current.scaleOffsetX)*t(e);this.animationState.current.scaleOffsetX+=n;let a=(this.animationState.target.scaleOffsetY-this.animationState.current.scaleOffsetY)*t(e);this.animationState.current.scaleOffsetY+=a}}e>=1&&(this.animationState.animating=!1,this.animationState.current=this.animationState.target,this.isRecovering=!1)}positionDistance(i,e){return Math.sqrt(hr(i.sx-e.sx,2)+hr(i.sy-e.sy,2))}recoverOriginal(i,e){this.animationState.target={sx:0,sy:0,cropWidth:i,cropHeight:e,timestamp:Date.now()},this.animationState.animating=!0,this.animationState.startTime=Date.now(),this.isRecovering=!0}dualStageCropping(i,e,t,r,s,n,a=.3){if(this.isRecovering)return;let c=this.calculateTargetPosition(t,r,s,n,i,e);this.processFacePositionCrop(c,i,e),s*n/c.cropWidth/c.cropHeight>a&&this.recoverOriginal(i,e)}movingPortrait(i,e,t,r,s,n){var c,l,u,h,m,_,g,E,C,k,ae,w;let a={sx:t+s/2+this.totalOffsetX,sy:r+n/2+this.totalOffsetY,cropWidth:i,cropHeight:e,scaleRatio:(l=(c=this.animationState.current)==null?void 0:c.scaleRatio)!=null?l:1,scaleOffsetX:(h=(u=this.animationState.current)==null?void 0:u.scaleOffsetX)!=null?h:0,scaleOffsetY:(_=(m=this.animationState.current)==null?void 0:m.scaleOffsetY)!=null?_:0,timestamp:Date.now()};this.animationState.target={sx:i/2,sy:r+n/2,cropWidth:i,cropHeight:e,scaleRatio:(E=(g=this.animationState.target)==null?void 0:g.scaleRatio)!=null?E:1,scaleOffsetX:(k=(C=this.animationState.target)==null?void 0:C.scaleOffsetX)!=null?k:0,scaleOffsetY:(w=(ae=this.animationState.target)==null?void 0:ae.scaleOffsetY)!=null?w:0,timestamp:Date.now()},this.animationState.animating||(this.animationState.target.scaleRatio=Math.sqrt(s*n/i/e/this.defaultScaleRatio),this.animationState.target.scaleOffsetX=-this.animationState.target.scaleRatio/2+.5,this.animationState.target.scaleOffsetY=-this.animationState.target.scaleRatio+1,(this.animationState.target.sy-this.animationState.target.scaleOffsetY*this.animationState.target.cropHeight)/this.animationState.target.scaleRatio<this.boundaryY&&(this.animationState.target.scaleOffsetY=(this.animationState.target.sy-this.boundaryY*this.animationState.target.scaleRatio)/this.animationState.target.cropHeight)),this.processFacePositionPortrait(a)}set aspectRatio(i){this.originalAspect=i}get current(){return this.animationState.current}get offset(){return{offsetX:this.totalOffsetX,offsetY:this.totalOffsetY}}get targetCrop(){return this.animationState.target}};var pI=`#version 300 es
|
|
126
71
|
in vec2 a_position;
|
|
127
72
|
in vec2 a_texCoord;
|
|
128
73
|
out vec2 v_texCoord;
|
|
129
74
|
void main() {
|
|
130
75
|
gl_Position = vec4(a_position.x, a_position.y, 0, 1);
|
|
131
76
|
v_texCoord = a_texCoord;
|
|
132
|
-
}`,
|
|
77
|
+
}`,fI=`#version 300 es
|
|
133
78
|
precision highp float;
|
|
134
79
|
uniform sampler2D u_texture;
|
|
135
80
|
uniform sampler2D mask;
|
|
@@ -138,7 +83,7 @@ in vec2 v_texCoord;
|
|
|
138
83
|
out vec4 outColor;
|
|
139
84
|
void main() {
|
|
140
85
|
outColor = vec4(texture(u_texture, v_texCoord).rgb, texture(mask, v_texCoord).a);
|
|
141
|
-
}`,
|
|
86
|
+
}`,Md=class extends Gt{constructor(e,t){super(e,t.input,{name:"vb",create2d:!1,useDefaultProgram:!1,useFbo:!1,createTexture:!0,width:t.width,height:t.height,logger:e.log});d(this,"_bgTexture");d(this,"_waterMarkTexture");d(this,"_lastMaskTexture");d(this,"_lastMaskFbo");d(this,"_textureValid",!1);d(this,"_selfieTextureValid",!1);d(this,"_selfieSegmentationHash");d(this,"wasm");d(this,"predictReady");d(this,"_color");d(this,"_prePrograme");d(this,"_segmentationMask");d(this,"_weixin",!1);d(this,"_centerFace");d(this,"_textureMatrixLocation");d(this,"_offsetMatrixLocation");d(this,"_colorLocation");d(this,"_enableFaceCentering",!1);d(this,"_enableEffectOptimization",!1);d(this,"_mat4");d(this,"_postProcessing");d(this,"_onAbort");d(this,"_visionTaskRegistry");d(this,"resolvePreditReady");this.init(t).catch(r=>{e.log.error(r),e.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:6,message:`init vb node error ${r.message||r}`})),this.resolvePreditReady()})}init(e){return f(this,null,function*(){var n,a,c;this.predictReady=new Promise(l=>{this.resolvePreditReady=l});let t=e.Wasm,r=this.context.ctx;if(e.color&&(this._color=e.color),e.mat4&&(this._mat4=e.mat4),e.postProcessing&&(this._postProcessing=e.postProcessing),this._enableFaceCentering=(n=e.enableFaceCentering)!=null?n:!1,this._enableEffectOptimization=(a=e.enableEffectOptimization)!=null?a:!1,this.wasm=new t.AllIn1(r),this.wasm.blurRadius=e.blurRadius||3,this.wasm.mirror=!!e.mirror,this.wasm.rotation=e.rotation||0,this.wasm.vbMode=e.bg==="blur"?1:e.bg instanceof HTMLImageElement?2:e.bg==="color"?3:0,this._onAbort=e.onAbort,e.bg||this.resolvePreditReady(),e.waterMark){let{x:l,y:u,width:h,height:m}=e.waterMark;this.wasm.setWaterMark(l,u,h,m)}if(e.beautyParams){let{beauty:l,brightness:u,ruddy:h}=e.beautyParams;this.wasm.setBeauty(l,u,h,e==null?void 0:e.width,e==null?void 0:e.height)}this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),r.uniform1i(r.getUniformLocation(this.program,"mask"),1),e.bg instanceof HTMLImageElement&&(r.uniform1i(r.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(e.bg)),e.waterMark&&(r.uniform1i(r.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(e.waterMark.image));let s=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);if(this._textureMatrixLocation=r.getUniformLocation(this.program,"u_textureMatrix"),r.uniformMatrix4fv(this._textureMatrixLocation,!1,s),this._offsetMatrixLocation=r.getUniformLocation(this.program,"u_offsetMatrix"),r.uniformMatrix4fv(this._offsetMatrixLocation,!1,s),this._colorLocation=r.getUniformLocation(this.program,"u_color"),r.uniform1i(r.getUniformLocation(this.program,"lastMask"),4),this._weixin){let l=this.context.createShader(r.FRAGMENT_SHADER,fI),u=this.context.createShader(r.VERTEX_SHADER,pI);this._prePrograme=this.context.createProgram(u,l),r.useProgram(this._prePrograme),this.setAttributes(this.positionBuffer,this.texCoordBuffer),r.uniform1i(r.getUniformLocation(this._prePrograme,"mask"),1)}this._enableEffectOptimization&&(this.wasm.vbMode===2||this.wasm.vbMode===3)?an()?(this._postProcessing=void 0,this.log.warn("Virtual background post-processing isn't allowed on mobile.")):(c=this._postProcessing)==null||c.init(r,this.positionBuffer,this.texCoordBuffer,4/3):this._postProcessing=void 0,yield this.initVisionTasks(e)})}initVisionTasks(e){return f(this,null,function*(){if(e.bg){if(this._visionTaskRegistry=yield window.VisionTaskRegistry.getInstance(),!window.VisionTaskRegistry||!this._visionTaskRegistry||!this._visionTaskRegistry.visionWasm)throw new Error("Virtual background assets not found. Please redeploy the assets of the npm package.");if(this._selfieSegmentationHash=yield this._visionTaskRegistry.register(window.VisionTaskType.ImageSegmenter,{canvas:this.context._canvas}),this._visionTaskRegistry.setVideo(this._selfieSegmentationHash,this.image),this._enableFaceCentering)try{this._visionTaskRegistry.models.has(window.VisionTaskType.FaceDetector)||(yield this._visionTaskRegistry.preloadModels([window.VisionTaskType.FaceDetector]));let t=yield this._visionTaskRegistry.register(window.VisionTaskType.FaceDetector);if(!t)return;this._centerFace=new Od(this.wasm.vbMode,this.image,t,this._visionTaskRegistry,this.context.log)}catch(t){this.log.error("Face detector model not found. Please redeploy the assets of the npm package.")}}})}onPredict(e){let t=this.context.ctx;this._weixin&&(this._lastMaskTexture||(this._lastMaskTexture=this.createTexture(this.image),this._lastMaskFbo=this.createFramebuffer(this._lastMaskTexture)));let r=this.getMaskTexture(e);if(!r)return;let s=r;this._postProcessing&&(this._postProcessing.ratio=this.image.videoWidth/this.image.videoHeight,s=this._postProcessing.postProcessing(r)),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),this.useTexture(),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,s||null),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),this.wasm.vbMode===3&&t.uniform3fv(this._colorLocation,this._color),this.useBufferFrame(),this._segmentationMask=e,this.totalFrames++,this.centerFace(),bt(this.wasm.rotation)&&this.resize(this.image.height,this.image.width),t.viewport(0,0,t.canvas.width,t.canvas.height),t.drawArrays(t.TRIANGLE_STRIP,0,4),e.close()}getMaskTexture(e){return e.confidenceMasks?e.confidenceMasks[0].getAsWebGLTexture():void 0}onFirstFrame(){this.waitingFirstFrame=!1;let e=this.context.ctx;this.useTexture(),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,this.image)}render(e){let t=this.context.ctx,{image:r}=this;this.tryVideoFrameCallback();let{videoWidth:s,videoHeight:n}=r;if(bt(this.wasm.rotation)&&!this._visionTaskRegistry&&([s,n]=[n,s]),s===0||n===0||!this.available)return!1;r.width=s,r.height=n;let a=!1;if(this.totalFrames)this.useTexture(),a=this._selfieTextureValid,this._selfieTextureValid=!0;else{if(this.program)this.useTexture();else return!1;a=this._textureValid,this._textureValid=!0}if(this.width!==s||this.height!==n||!a?(this.resize(s,n),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,r)):t.texSubImage2D(t.TEXTURE_2D,0,0,0,t.RGBA,t.UNSIGNED_BYTE,r),this._weixin){if(t.useProgram(this._prePrograme),this.useTexture(),this._segmentationMask){let c=this.getMaskTexture(this._segmentationMask);t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,c||null),t.bindFramebuffer(t.FRAMEBUFFER,this._lastMaskFbo||null)}t.drawArrays(t.TRIANGLE_STRIP,0,4),this.useTexture(),this._segmentationMask?t.copyTexSubImage2D(t.TEXTURE_2D,0,0,0,0,0,s,n):t.copyTexImage2D(t.TEXTURE_2D,0,t.RGBA,0,0,s,n,0)}try{if(this._selfieSegmentationHash&&this._visionTaskRegistry){let c=this._visionTaskRegistry.getResult(this._selfieSegmentationHash);this.totalFrames===1&&this.context._canvas&&this.resolvePreditReady(),this.onPredict(c)}}catch(c){this._onAbort&&this._onAbort(c)}return this.totalFrames||(t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),t.drawArrays(t.TRIANGLE_STRIP,0,4)),this._visionTaskRegistry&&this._visionTaskRegistry.resetHashResults(),!1}centerFace(){if(!this._centerFace||!this._enableFaceCentering)return;let e=this.context.ctx;this._centerFace.aspectRatio=e.canvas.width/e.canvas.height,this._centerFace.actionCentering(this.image);let{current:t,offset:r}=this._centerFace;if(t&&(this.wasm.vbMode===1&&this.drawImage(t.sx,t.sy,t.cropWidth,t.cropHeight),r&&this.wasm.vbMode===2)){if(!this._mat4)return;let s=this._mat4.create(),{scaleRatio:n=1,scaleOffsetX:a=0,scaleOffsetY:c=0}=t;this._mat4.fromTranslation(s,[-r.offsetX/e.canvas.width+a,c,0]),this._mat4.scale(s,s,[n,n,1]),e.uniformMatrix4fv(this._offsetMatrixLocation,!1,s)}}drawImage(e,t,r,s){let n=this.context.ctx;if(!this._mat4)return;let{width:a,height:c}=n.canvas,l=this._mat4.create();this._mat4.fromTranslation(l,[e/a,1-(t+s)/c,0]),this._mat4.scale(l,l,[r/a,s/c,1]),n.uniformMatrix4fv(this._textureMatrixLocation,!1,l)}close(){var t;super.close();let e=this.context.ctx;this._bgTexture&&e.deleteTexture(this._bgTexture),this._waterMarkTexture&&e.deleteTexture(this._waterMarkTexture),this._lastMaskTexture&&e.deleteTexture(this._lastMaskTexture),this._lastMaskFbo&&e.deleteFramebuffer(this._lastMaskFbo),this._prePrograme&&e.deleteProgram(this._prePrograme),this._postProcessing&&this._postProcessing.close(),(t=this.wasm)==null||t.close()}};var kd=class extends Ue{constructor(e){super(e,{name:"yuv-source",useDefaultProgram:!1,create2d:!1,useFbo:!1,createTexture:!1,logger:e.log,fragmentShaderSource:`
|
|
142
87
|
precision highp float;
|
|
143
88
|
uniform sampler2D ySampler;
|
|
144
89
|
uniform sampler2D uSampler;
|
|
@@ -163,19 +108,15 @@ void main() {
|
|
|
163
108
|
void main() {
|
|
164
109
|
gl_Position = vertexPos;
|
|
165
110
|
textureCoord = texturePos;
|
|
166
|
-
}`});p(this,"yTextureRef");p(this,"uTextureRef");p(this,"vTextureRef");p(this,"Y");p(this,"U");p(this,"V");this.useProgram();let r=this.context.ctx;r.pixelStorei(r.PACK_ALIGNMENT,1),r.pixelStorei(r.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,r){let o=this.context.ctx,s=o.createTexture();return o.bindTexture(o.TEXTURE_2D,s),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),o.bindTexture(o.TEXTURE_2D,null),o.uniform1i(o.getUniformLocation(this.program,e),r),s}render(e){let r=this.context.ctx,o=this.width,s=this.height;return this.useProgram(),r.viewport(0,0,o,s),r.activeTexture(r.TEXTURE0),r.bindTexture(r.TEXTURE_2D,this.yTextureRef),r.texSubImage2D(r.TEXTURE_2D,0,0,0,o,s,r.LUMINANCE,r.UNSIGNED_BYTE,this.Y),r.activeTexture(r.TEXTURE1),r.bindTexture(r.TEXTURE_2D,this.uTextureRef),r.texSubImage2D(r.TEXTURE_2D,0,0,0,o/2,s/2,r.LUMINANCE,r.UNSIGNED_BYTE,this.U),r.activeTexture(r.TEXTURE2),r.bindTexture(r.TEXTURE_2D,this.vTextureRef),r.texSubImage2D(r.TEXTURE_2D,0,0,0,o/2,s/2,r.LUMINANCE,r.UNSIGNED_BYTE,this.V),this.draw(),!0}resize(e,r){super.resize(e,r);let o=this.context.ctx;o.activeTexture(o.TEXTURE0),o.bindTexture(o.TEXTURE_2D,this.yTextureRef),o.texImage2D(o.TEXTURE_2D,0,o.LUMINANCE,e,r,0,o.LUMINANCE,o.UNSIGNED_BYTE,null),o.activeTexture(o.TEXTURE1),o.bindTexture(o.TEXTURE_2D,this.uTextureRef),o.texImage2D(o.TEXTURE_2D,0,o.LUMINANCE,e/2,r/2,0,o.LUMINANCE,o.UNSIGNED_BYTE,null),o.activeTexture(o.TEXTURE2),o.bindTexture(o.TEXTURE_2D,this.vTextureRef),o.texImage2D(o.TEXTURE_2D,0,o.LUMINANCE,e/2,r/2,0,o.LUMINANCE,o.UNSIGNED_BYTE,null)}};var By=(i,t)=>{switch(i){case"webCodecs":return t==="videoFrame"?514705:514706;case"wasm":return t==="webgl"?514707:t==="videoFrame"?514708:514709}throw new Error("decoder type not supported")};function c0(i){return i[0]===0&&i[1]===0&&i[2]===0&&i[3]===1}var d0=0,gh=class{constructor(t){p(this,"id",d0++);p(this,"trackDoneOB");p(this,"startOB");p(this,"stopOB");p(this,"decoder");p(this,"videoContext");p(this,"gop",0);p(this,"gop_helper",0);p(this,"waitFirstKeyFrame",!0);p(this,"startTimestamp",0);p(this,"startTime",0);p(this,"startPerformanceTime",0);p(this,"inputFrameCount",0);p(this,"decodedFrameCount",0);p(this,"decodeFrameCount",0);p(this,"downgradeLevel",0);p(this,"lastDowngradeTime",0);p(this,"lastFrameDiff",0);p(this,"lastDecodeFrameTimestamp",0);p(this,"config");p(this,"gop_before_configure",[]);p(this,"videoElement");p(this,"type","wasm");p(this,"goodType");p(this,"renderer","2d");p(this,"wasmOption");p(this,"createDecoder");p(this,"_decodeSink");p(this,"isReported",!1);p(this,"track");p(this,"stateChangeOB");p(this,"failedReason");let{track:e,createDecoder:r}=t;if(this.stateChangeOB=ir(),this.track=e,this.createDecoder=r,this.wasmOption={yuvMode:t.renderer==="webgl",wasmPath:t.wasmPath,workerMode:t.workerMode,canvas:t.canvas},this.config=t.config,this.videoElement=t.videoElement,this.renderer=t.renderer,this.trackDoneOB=Qe(e.availableState,Ve.OFF),this.stopOB=ir(),t.type==="auto"){switch(t.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=t.type;this.changeRenderer(this.renderer),Ye(this.stateChangeOB,tf((o,s)=>(o!==s&&e.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:this.failedReason,prevState:o,state:s}),s),"INITIALIZED"),At(this.stopOB),lt()),this.start()}start(t=0){this.waitFirstKeyFrame=!0,this.stateChangeOB.next("STARTING");let e=Ye(this.pipe(this.track),At(this.stopOB),So());Ye(e,lt(()=>{this.track.stat.framesDecoded++},r=>{if(this.track.log.error(`${this.id} play failed: ${r} retryCount: ${t}`),Se.addFailedEvent({key:By(this.type,this.renderer),error:r}),t>4)this.failedReason=r,this.stateChangeOB.next("FAILED"),Se.addFailedEvent({key:514704});else{if(this.goodType){this.start(t);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(t+1)}},()=>{this.track.log.warn(`${this.id} decoderOB completed`),Se.addSuccessEvent({key:By(this.type,this.renderer)}),Se.addSuccessEvent({key:514704})})),Ye(e,Ni(1),lt(()=>{this.track.player.handlePlaying("canvas"),this.goodType=this.type,this.stateChangeOB.next("STARTED")}))}mock(t){this._decodeSink?this._decodeSink.error(t):this.start()}close(t){this.stopOB.next(t)}changeRenderer(t){this.renderer=t,this.renderer==="videoFrame"&&!Xm()&&(this.renderer="2d"),this.wasmOption.yuvMode=this.renderer==="webgl"}decode(t,e=!1){var a,c;if(this.failedReason)return;this.inputFrameCount++;let r=new Uint8Array(t.data);if(!c0(r)||r.length<5)return this.stateChangeOB.next("FAILED"),this.close(`not h26x frame ${r.subarray(0,5)}`),t;let o=r[4]&31,s=!1;switch(o){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:t.data,timestamp:t.timestamp,type:t.type}),t;this.gop_before_configure.length>0&&!e&&(this.gop_before_configure.forEach(d=>this.decode(d,!0)),this.gop_before_configure=[]);let{timestamp:n}=t;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=Xe();else{this.track.log.debug(`wait first key frame ${this.inputFrameCount} ${r.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=t.getMetadata)==null?void 0:c.call(t).rtpTimestamp}`),this.decodeFrameCount++,this.lastDecodeFrameTimestamp=n,this.decoder.decode({data:t.data,type:t.type,timestamp:this.lastDecodeFrameTimestamp});return}return t}checkDowngradeByFrameDiff(){let t=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!==t&&this.track.log.debug(`downgrade level ${t} to ${this.downgradeLevel} ${this.decodeFrameCount} frameDiff: ${e}, lastFrameDiff: ${this.lastFrameDiff}`),this.lastFrameDiff=e,this.lastDowngradeTime=Date.now()}checkDowngradeByTimestampDiff(t){let e=this.downgradeLevel;this.lastDecodeFrameTimestamp-t>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(t){return e=>D(this,null,function*(){this._decodeSink=e;let r,o=t.mediaTrack;e.defer(()=>{var a;o&&(t.player.setCanvas(),t.setInputMediaStreamTrack(o)),r==null||r.close(),(a=this.videoContext)==null||a.destroy(),delete this._decodeSink});let{renderer:s,type:n}=this;t.log.info(`decoder type: ${this.type} renderer: ${this.renderer}`);try{switch(n){case"wasm":r=this.createDecoder(n,this.wasmOption);break;case"webCodecs":r=this.createDecoder(n);break;default:throw new Error("not supported yet")}let a=0;if(r.on("videoFrame",c=>{this.decodedFrameCount++,a++,(a<=10||a%500===0)&&t.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)}),r.on("error",c=>{t.log.error(c),e.error(n==="webCodecs"?4:8)}),yield r.initialize(this.videoElement),!this._decodeSink)return;if(r.configure(this.config),n==="wasm"&&s==="webgl"){this.videoContext=new cr({frameRate:15,logger:t.log,name:t.userId}),this.videoContext.create(),this.videoContext.on(cr.UNAVAILABLE,d=>{t.log.error(d),e.error(7)});let c=new fh(this.videoContext);r.on("videoCodecInfo",d=>c.resize(d.width,d.height)),r.on("videoFrame",d=>{({y:c.Y,u:c.U,v:c.V}=d),this.downgradeLevel===1?this.decodedFrameCount%2===0&&c.render(this.decodedFrameCount):c.render(this.decodedFrameCount)}),t.source=c,t.player.setCanvas(this.videoContext._canvas,2)}else if(s==="videoFrame"){t.player.setCanvas();let c=new MediaStreamTrackGenerator({kind:"video"}),d=c.writable.getWriter();t.setInputMediaStreamTrack(c),r.on("videoFrame",m=>d.write(m))}else{this.videoContext=new mr({frameRate:15,logger:t.log,name:t.userId}),this.videoContext.create({alpha:!1});let c=this.videoContext.createVideoImageSource();r.on("videoFrame",m=>{try{c.image=m,c.update()}catch(l){delete this.goodType,t.log.error(l),e.error(11)}});let d=new on(this.videoContext,{name:"remotePlayer",logger:t.log});c.connect(d),t.source=c,t.player.setCanvas(this.videoContext._canvas,2)}this.decoder=r}catch(a){t.log.error(a),e.error(n==="webCodecs"?2:6)}})}};var $y=Promise.resolve(),ld=class extends Fy.EventEmitter{constructor(e){super();this.room=e;p(this,"videoContext");p(this,"_glVideoContext");p(this,"_2dVideoContext");p(this,"destination");p(this,"smallVideoContext");p(this,"smallDestination");p(this,"smallTrackSource");p(this,"smallImageSource");p(this,"_isMirror",!1);p(this,"_rotation",0);p(this,"cameraTrack");p(this,"cameraNode");p(this,"transformNode");p(this,"mixNode");p(this,"screenTrack");p(this,"screenNode");p(this,"selfModel",!1);p(this,"blurRadius",3);p(this,"arTrack");p(this,"_enableFaceCentering",!1);p(this,"_enableEffectOptimization",!1);p(this,"onAbort");p(this,"_color");p(this,"Wasm");p(this,"waterMarkNode");p(this,"_waterMarkOption");p(this,"watermarkImageList",[]);p(this,"_beautyParams");p(this,"isUsingArTrack",!1);p(this,"mixTrack");p(this,"_isMixScreen",!1);p(this,"_virtualBackground");p(this,"_virtualBackgroundAbortCallback");p(this,"virtualBackgroundInstance");p(this,"_bgAssetPath");p(this,"log");p(this,"_mat4");p(this,"_postProcessing");p(this,"_checkId",0);p(this,"_use2d",!1);p(this,"_autoSwitchRenderMode",!0);p(this,"encodePipeline",[]);p(this,"decodePipeline",[]);p(this,"updated",$y);p(this,"_updateFlag",!1);this.log=se.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 mr({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 r=e==="2d";this._use2d!==r&&(this._use2d=r,this.clear(),this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.update())}get cameraResolution(){var o;let{width:e,height:r}=((o=this.cameraTrack)==null?void 0:o.settings)||{};return Jr(this._rotation)?{width:r,height:e}:{width:e,height:r}}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new mr({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this._2dVideoContext}getGlVideoContext(){if(!this._glVideoContext)this._glVideoContext=new cr({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(pm<=22),this._glVideoContext.on(cr.UNAVAILABLE,e=>{var r;this.emit("error",e),this.log.warn("video context unavailable",e),(r=this._virtualBackgroundAbortCallback)==null||r.call(this,e),this.update().catch(o=>{this.log.error(o)})})}catch(e){this.emit("error",e)}}initVirtualBackground(e,r,o){this.onAbort=e,this._mat4=r,this._postProcessing=o}enablePrintDetail(e=2e3){this._checkId=Jt.run("interval",()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:e})}destroy(){var e,r;(e=this._2dVideoContext)==null||e.destroy(),(r=this._glVideoContext)==null||r.destroy(),this.smallVideoContext.destroy(),Jt.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(ni||this._isMixScreen||this._isTransform||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}sendCreateResult(e="videoCtxGl",r){let o=e==="videoCtxGl"?512700:512701;r?Se.addFailedEvent({key:o,error:r}):Se.addSuccessEvent({key:o})}checkOrCreateVideoContext(){let e=this._use2d;if(this._autoSwitchRenderMode&&(this._use2d=!this._hasVirtualBg),this.videoContext)if(this.videoContext.available){let r=!this.videoContext.hasAlpha&&this.needAlpha;if(this._autoSwitchRenderMode&&e===this._hasVirtualBg)this.clear();else if(r)if(this._use2d)this.clear();else return!0;else return!0}else{if(this._glVideoContext=new cr({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,r){if(this.smallMode!=="api")if(e){if(!this.smallVideoContext.available){if(this.smallVideoContext.create({alpha:!1}),!this.smallVideoContext.available)return;this.smallDestination=new Tl(this.smallVideoContext,e,this.log),this.smallVideoContext.on(cr.UNAVAILABLE,o=>{this.log.warn("small video context lost",o)})}if(this.smallVideoContext.frameRate=e.frameRate,this.smallDestination.resolution=e,r)this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=r:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(r),this.smallImageSource.resize(r.width,r.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:o,height:s}=this.cameraTrack.settings;this.smallTrackSource.resize(o,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 r;try{let o=this.cameraTrack,{small:s,player:n}=o;ni&&n.setCanvas(e);let a=e&&((r=this.destination)==null?void 0:r.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),o.setOutputMediaStreamTrack(a)}catch(o){this.log.error("set main output failed",o)}}update(e=!1){return D(this,null,function*(){var s;if(!this.cameraTrack||!this.initialTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:r,profile:o}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams)this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log}),this.destination.on(or.RENDER,n=>{var a;(a=this.cameraTrack)==null||a.emit("render",n)})),Tr===16?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof di?(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 di?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(r.width,r.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 El(this.videoContext,{name:"mainDestination",logger:this.log}),this.destination.on(or.RENDER,d=>{var m;(m=this.cameraTrack)==null||m.emit("render",d)}));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 ph(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=o.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 ui(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 la(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:d}=this.cameraResolution;this.waterMarkNode.image=yield this.getWatermarkImage(c,d),c&&d&&this.waterMarkNode.resize(c,d)}(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 r,o,s,n,a;if(e instanceof zi)return this.log.info("change screen input",(r=e.mediaTrack)==null?void 0:r.label),this.setScreenTrack(e);if(e instanceof Zr)return this.log.info("change video input",(o=e.mediaTrack)==null?void 0:o.label),this.setCameraTrack(e);if(e instanceof qi){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 nn)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 r;e instanceof zi?((r=this.screenNode)==null||r.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof Zr?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 qi?e.source&&e.source.context.destroy():e instanceof nn&&(delete this.mixTrack,this.update())}setMixTrack(e){this.mixTrack=e}setCameraTrack(e){return this.cameraTrack=e,this.update(!0)}setScreenTrack(e){return D(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,r){return D(this,null,function*(){let o=document.createElement("canvas");r&&e&&(o.height=r,o.width=e);let s=o.getContext("2d");if(!s)throw new Me({code:Te.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort((n,a)=>n.zIndex-a.zIndex),this.watermarkImageList.forEach(({image:n,x:a,y:c,width:d,height:m,fillVideo:l})=>{let f=l&&e||d,g=l&&r||m,T=l?0:a,E=l?0:c;s.drawImage(n,T,E,f,g)}),Bn(o.toDataURL())})}pushWaterMarkImageList(e){let{type:r}=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)||((r==="mute"||r==="watermark")&&(this.watermarkImageList=this.watermarkImageList.filter(s=>s.type!==r)),this.watermarkImageList.push(e))}setBeautyParams(e){return D(this,null,function*(){this._beautyParams=e,this.update()})}stopBeauty(){return D(this,null,function*(){this._beautyParams=void 0,this.update()})}setWatermark(e){return D(this,null,function*(){let r;try{r=yield Bn((e==null?void 0:e.imageElement)||e.imageUrl)}catch(f){throw new Me({code:Te.INVALID_PARAMETER,message:`load image failed, url: ${e.imageUrl}`})}let{x:o=0,y:s=0,width:n=r.width,height:a=r.height,type:c="watermark",zIndex:d=2,fillVideo:m=!1}=e;this.watermarkImageList.some(f=>f.type===c)?(this.watermarkImageList=this.watermarkImageList.filter(f=>f.type!==c),this.pushWaterMarkImageList({x:o,y:s,width:n,height:a,image:r,zIndex:d,type:c,imageUrl:e.imageUrl,fillVideo:m}),r=yield this.getWatermarkImage(this.cameraResolution.width,this.cameraResolution.height),this._waterMarkOption={x:0,y:0,width:r.width,height:r.height,image:r},this.waterMarkNode?(this.waterMarkNode.x=0,this.waterMarkNode.y=0,this.waterMarkNode.resize(r.width,r.height),this.waterMarkNode.image=r):this.update()):(this.pushWaterMarkImageList({x:o,y:s,width:n,height:a,image:r,zIndex:d,type:c,imageUrl:e.imageUrl,fillVideo:m}),yield this.freshWatermark()),this.log.info("set watermark",JSON.stringify(this.watermarkImageList,(f,g)=>f==="imageUrl"?void 0:g))})}deleteWatermark(e="watermark"){return D(this,null,function*(){this.watermarkImageList=this.watermarkImageList.filter(r=>r.type!==e),this.log.info("delete watermark",e,JSON.stringify(this.watermarkImageList,(r,o)=>r==="imageUrl"?void 0:o)),yield this.freshWatermark()})}freshWatermark(){return D(this,null,function*(){var s;(s=this.waterMarkNode)==null||s.close(),delete this.waterMarkNode,delete this._waterMarkOption;let{width:e,height:r}=this.cameraResolution,o=yield this.getWatermarkImage(e,r);this._waterMarkOption={x:0,y:0,width:o.width,height:o.height,image:o},this.update()})}setVirtualBackground(e){return D(this,null,function*(){var r,o,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 Bn(e.imageUrl):(this.blurRadius=e.blurLevel||this.blurRadius||3,this._virtualBackground=e.type),this._enableFaceCentering=(r=e.enableFaceCentering)!=null?r:this._enableFaceCentering,this._enableEffectOptimization=(o=e.enableEffectOptimization)!=null?o: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 Me({code:Te.INVALID_OPERATION,message:`webgl context create failed, ${this._glVideoContext.error}`})})}get mixScreen(){return this._isMixScreen}set mixScreen(e){var r;this._isMixScreen=e,this._isMixScreen||((r=this.screenNode)==null||r.close(),delete this.screenNode),this.update()}set mirror(e){var r;this._isMirror!==e&&(this._isMirror=e,this._isTransform||((r=this.transformNode)==null||r.close(),delete this.transformNode),this.update())}get mirror(){return this._isMirror}set rotation(e){var r;this._rotation!==e&&(this._rotation=e,this._isTransform||((r=this.transformNode)==null||r.close(),delete this.transformNode),this.update())}get rotation(){return this._rotation}enableAr(e){this.arTrack=e,this.isUsingArTrack=!0,this.update()}updateAr(){return D(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 gh(e)}clear(){var e,r;(e=this.videoContext)==null||e.disconnect(),(r=this.destination)==null||r.removeAllListeners(),delete this.destination,delete this.cameraNode,delete this.transformNode,delete this.screenNode,delete this.waterMarkNode}addEncodeProcessor({processor:e,type:r}){var o;this.encodePipeline.includes(e)||(this.encodePipeline[r]=e,(o=this.room)==null||o.enableInsertableStreams())}addDecodeProcessor({processor:e,type:r}){var o;this.decodePipeline.includes(e)||(this.decodePipeline[r]=e,(o=this.room)==null||o.enableInsertableStreams())}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}};Ie([wE(function(e){this.log.error("update failed",e)}),ut(e=>function(...r){return D(this,null,function*(){this._updateFlag||(this._updateFlag=!0,yield $y,this.updated=new Promise((o,s)=>{e.apply(this,r).then(o,s),setTimeout(s,5e3,new Me({code:Te.API_CALL_TIMEOUT,message:"update timeout"}))}),this._updateFlag=!1,yield this.updated)})})],ld.prototype,"update",1);var u0=0;var _h=class extends Ve{constructor(e){super("room");p(this,"seq",++u0);p(this,"sdkAppId");p(this,"userId");p(this,"userSig");p(this,"privateMapKey");p(this,"latencyLevel");p(this,"tinyId");p(this,"scene");p(this,"roomId");p(this,"useStringRoomId");p(this,"role","anchor");p(this,"joinParams",null);p(this,"localPublishFlag",0);p(this,"localTracks",new Set);p(this,"enableAutoPlayDialog",!0);p(this,"autoReceiveAudio",!0);p(this,"autoReceiveVideo",!0);p(this,"proxy_ws");p(this,"proxy_wt");p(this,"proxy_unified");p(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}});p(this,"keyPointManager");p(this,"audioManager");p(this,"videoManager");p(this,"callDurationCalculator");p(this,"badCaseDetector");p(this,"scheduleResult",{domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null});p(this,"videoDecodeFallbackType");p(this,"smallMode","canvas");p(this,"enableChorus",!1);p(this,"_isUsingCachedSchedule",!1);p(this,"_log");p(this,"_joinedTimestamp",0);p(this,"_sdkType");p(this,"heartbeatReport");p(this,"heartbeatCount",0);p(this,"quality");p(this,"enableSEI");p(this,"isDestroyed",!1);this._log=se.createLogger({parent:e.logger,id:`r${this.seq}`}),this.useStringRoomId=!!e.useStringRoomId,Nt(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),Nt(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),Nt(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new Py({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new Uy({room:this}),this.badCaseDetector=new Vy({room:this}),this.audioManager=new Il(this),this.videoManager=new ld(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(r=>{if(r.isPublished||r.isPublishing)switch(r.mediaType){case 1:e.audio=!0;break;case 4:e.bigVideo=!0,e.smallVideo=r.hasSmall;break;case 2:e.auxVideo=!0;default:break}}),e}get muteState(){var e,r,o;return{audio:!!((e=this.localMainAudioTrack)!=null&&e.muted),bigVideo:!!((r=this.localMainVideoTrack)!=null&&r.muted),auxVideo:!!((o=this.localAuxVideoTrack)!=null&&o.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 D(this,null,function*(){return this.publish(e)})}removeTrack(e){return D(this,null,function*(){return this.unpublish(e)})}replaceTrack(e){return D(this,null,function*(){})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(nt(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(Nr(e)){let{websocketProxy:r,webtransportProxy:o,loggerProxy:s,scheduleProxy:n,unifiedProxy:a}=e;this.proxy_ws=r,this.proxy_wt=o,this.proxy_unified=a,a?(Ul([a,a]),vs(`https://${a}`)):(s&&vs(s),n&&Ul(n))}ee.once(ce.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:Qi.main,sched_back_domain:Qi.backup,signal_domain:this.proxy_ws||this.proxy_wt||""}))}getRemoteAudioStats(){return D(this,null,function*(){let e={};return this.remotePublishedUserMap.forEach(r=>{e[r.userId]=r.remoteAudioTrack.stat}),e})}getTransportStats(){return D(this,null,function*(){var r;let e={rtt:((r=this.quality)==null?void 0:r.uplinkRTT)||0,downlinksRTT:{}};if(this.quality)for(let o of this.quality.downlinkInfo)e.downlinksRTT[o.userId]=o.rtt;return e})}getRemoteVideoStats(){return D(this,arguments,function*(e="main"){let r={};return this.remotePublishedUserMap.forEach(o=>{let s=e==="auxiliary"?o.remoteAuxiliaryTrack:o.remoteVideoTrack;r[o.userId]=s.stat}),r})}checkDestroy(){if(this.isDestroyed)throw new Me({code:Te.INVALID_OPERATION,message:Et({key:_t.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(Wr.INVALID_DESTROY),new Me({code:Te.INVALID_OPERATION,message:Et({key:_t.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,ee.emit(ce.ROOM_DESTROY,{room:this})}schedule(e,r){return D(this,null,function*(){var s,n,a,c;let o=Xe();try{let{isCached:d,result:m,detailCost:l}=yield Pf({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:qt,userSig:this.userSig,role:this.scene==="live"?e.role:void 0,frameWorkType:r,latencyLevel:e.latencyLevel});this._isUsingCachedSchedule=d,this._log.info(`schedule cache:${+d} ${oi(m,{keysToExclude:["username","credential"]})}`),d&&ee.once(ce.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=be(be({},this.scheduleResult),m),ft((s=m.config)==null?void 0:s.retryCount)&&Wh(m.config.retryCount),nt((n=m.config)==null?void 0:n.loggerDomain)&&vs(m.config.loggerDomain),this.videoDecodeFallbackType=((a=m.config)==null?void 0:a.videoDecodeFallback)||this.videoDecodeFallbackType,this.smallMode=((c=m.config)==null?void 0:c.smallMode)||this.smallMode,ee.emit(ce.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:l}),Se.addSuccessEvent({key:521700,cost:Xe()-o})}catch(d){throw Se.addFailedEvent({key:521700,error:d}),d}})}sendAbilityStatus(e){}enableInsertableStreams(){return Promise.resolve()}switchRoom(e){return Promise.reject()}isSwitchRoomSupported(){return!1}};function Hy(i,t=!1){let e=Object.defineProperties(ir(),{postMessage:{value:i.postMessage.bind(i)},port:{get(){return i},set(o){i.onmessage=Tt,i.onmessageerror=Tt,i=o,r()}}});function r(){i.onmessage=o=>{o.data?o.ports.length||t?e.next(o):e.next(o.data):(e.complete(),i.close())},i.onmessageerror=o=>{e.error(o),i.close()}}return r(),e}var hg=class extends Ge{constructor(t,e){super(t);let r=new Ge(t);r.next=Tt,e(r)}},EW=Je(hg,"takeUntilComplete");var Ar={useWt:!0,useAINS:!0,useHardDecoder:"prefer-software",useHardEncoder:"prefer-software",unreliable:!1,debug:!1,assetsPath:"",enableUpload:!0},Wy="__INLINE__WORKER__",Gy="__INLINE__WASM__",{debug:zy}=console;Ar.debug||(console.debug=()=>{});var l0=!Wy.startsWith("__"),h0=!Gy.startsWith("__");function Eh(){let i=xs(`${Ar.assetsPath?`${Ar.assetsPath}/`:""}worker.js`);return l0?URL.createObjectURL(new Blob([atob(Wy)],{type:"application/javascript"})):i.startsWith("http")?fetch(i).then(t=>t.blob().then(e=>URL.createObjectURL(e))):i}var hd;function Th(){return D(this,null,function*(){let i=Ar.assetsPath?`${Ar.assetsPath}/`:"";return hd||(h0?hd=new TextEncoder().encode(atob(Gy)).buffer:hd=yield fetch(xs(`${i}av_processing.wasm`)).then(t=>t.arrayBuffer()),hd)})}var mg=class{constructor(){p(this,"playPort");p(this,"playPortSent",!1);p(this,"worklet");p(this,"workletPromise")}init(){return this.workletPromise||(this.workletPromise=this._init()),this.workletPromise}_init(){return D(this,null,function*(){let t=bt("player"),e=Eh();try{yield t.audioWorklet.addModule(typeof e=="string"?e:yield e),se.info("global audio player worklet addModule success",e)}catch(r){throw se.error("global audio player worklet addModule failed:",r),r}return this.worklet=new AudioWorkletNode(t,"global-audio-player",{processorOptions:{wasm:yield Th(),flag:Ar},numberOfInputs:2}),se.info("global audio player worklet created",t.state),this.worklet.connect(t.destination),this.playPort=this.worklet.port,this.playPort})}playAudio(t){return D(this,null,function*(){var r;yield this.init();let e=new MessageChannel;(r=this.playPort)==null||r.postMessage(null,[e.port1]),t(e.port2)})}},md=new mg;var pg=(()=>{if(typeof self=="undefined")return!1;if(!("top"in self&&self!==top)){if("showOpenFilePicker"in self)return"showOpenFilePicker"}return!1})(),RW=pg?Promise.resolve().then(function(){return g0}):Promise.resolve().then(function(){return I0});var CW=pg?Promise.resolve().then(function(){return E0}):Promise.resolve().then(function(){return A0});var m0=pg?Promise.resolve().then(function(){return y0}):Promise.resolve().then(function(){return R0});function fg(...i){return D(this,null,function*(){return(yield m0).default(...i)})}var p0=i=>D(void 0,null,function*(){let t=yield i.getFile();return t.handle=i,t}),f0=(...t)=>D(void 0,[...t],function*(i=[{}]){Array.isArray(i)||(i=[i]);let e=[];i.forEach((s,n)=>{e[n]={description:s.description||"Files",accept:{}},s.mimeTypes?s.mimeTypes.map(a=>{e[n].accept[a]=s.extensions||[]}):e[n].accept["*/*"]=s.extensions||[]});let r=yield window.showOpenFilePicker({id:i[0].id,startIn:i[0].startIn,types:e,multiple:i[0].multiple||!1,excludeAcceptAllOption:i[0].excludeAcceptAllOption||!1}),o=yield Promise.all(r.map(p0));return i[0].multiple?o:o[0]}),g0={__proto__:null,default:f0};function yh(i){function t(e){if(Object(e)!==e)return Promise.reject(new TypeError(e+" is not an object."));var r=e.done;return Promise.resolve(e.value).then(function(o){return{value:o,done:r}})}return yh=function(e){this.s=e,this.n=e.next},yh.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var r=this.s.return;return r===void 0?Promise.resolve({value:e,done:!0}):t(r.apply(this.s,arguments))},throw:function(e){var r=this.s.return;return r===void 0?Promise.reject(e):t(r.apply(this.s,arguments))}},new yh(i)}var jy=(o,s,...n)=>D(void 0,[o,s,...n],function*(i,t,e=i.name,r){let a=[],c=[];var d,m=!1,l=!1;try{for(var f,g=function(T){var E,y,v,M=2;for(typeof Symbol!="undefined"&&(y=Symbol.asyncIterator,v=Symbol.iterator);M--;){if(y&&(E=T[y])!=null)return E.call(T);if(v&&(E=T[v])!=null)return new yh(E.call(T));y="@@asyncIterator",v="@@iterator"}throw new TypeError("Object is not async iterable")}(i.values());m=!(f=yield g.next()).done;m=!1){let T=f.value,E=`${e}/${T.name}`;T.kind==="file"?c.push(T.getFile().then(y=>(y.directoryHandle=i,y.handle=T,Object.defineProperty(y,"webkitRelativePath",{configurable:!0,enumerable:!0,get:()=>E})))):T.kind!=="directory"||!t||r&&r(T)||a.push(jy(T,t,E,r))}}catch(T){l=!0,d=T}finally{try{m&&g.return!=null&&(yield g.return())}finally{if(l)throw d}}return[...(yield Promise.all(a)).flat(),...yield Promise.all(c)]}),_0=(...t)=>D(void 0,[...t],function*(i={}){i.recursive=i.recursive||!1,i.mode=i.mode||"read";let e=yield window.showDirectoryPicker({id:i.id,startIn:i.startIn,mode:i.mode});return jy(e,i.recursive,void 0,i.skipDirectory)}),E0={__proto__:null,default:_0},T0=(s,...n)=>D(void 0,[s,...n],function*(i,t=[{}],e=null,r=!1,o=null){Array.isArray(t)||(t=[t]),t[0].fileName=t[0].fileName||"Untitled";let a=[],c=null;if(i instanceof Blob&&i.type?c=i.type:i.headers&&i.headers.get("content-type")&&(c=i.headers.get("content-type")),t.forEach((l,f)=>{a[f]={description:l.description||"Files",accept:{}},l.mimeTypes?(f===0&&c&&l.mimeTypes.push(c),l.mimeTypes.map(g=>{a[f].accept[g]=l.extensions||[]})):c?a[f].accept[c]=l.extensions||[]:a[f].accept["*/*"]=l.extensions||[]}),e)try{yield e.getFile()}catch(l){if(e=null,r)throw l}let d=e||(yield window.showSaveFilePicker({suggestedName:t[0].fileName,id:t[0].id,startIn:t[0].startIn,types:a,excludeAcceptAllOption:t[0].excludeAcceptAllOption||!1}));!e&&o&&o(d);let m=yield d.createWritable();return"stream"in i?(yield i.stream().pipeTo(m),d):"body"in i?(yield i.body.pipeTo(m),d):(yield m.write(yield i),yield m.close(),d)}),y0={__proto__:null,default:T0},S0=(...t)=>D(void 0,[...t],function*(i=[{}]){return Array.isArray(i)||(i=[i]),new Promise((e,r)=>{let o=document.createElement("input");o.type="file";let s=[...i.map(d=>d.mimeTypes||[]),...i.map(d=>d.extensions||[])].join();o.multiple=i[0].multiple||!1,o.accept=s||"",o.style.display="none",document.body.append(o);let n=d=>{typeof a=="function"&&a(),e(d)},a=i[0].legacySetup&&i[0].legacySetup(n,()=>a(r),o),c=()=>{window.removeEventListener("focus",c),o.remove()};o.addEventListener("click",()=>{window.addEventListener("focus",c)}),o.addEventListener("change",()=>{window.removeEventListener("focus",c),o.remove(),n(o.multiple?Array.from(o.files):o.files[0])}),"showPicker"in HTMLInputElement.prototype?o.showPicker():o.click()})}),I0={__proto__:null,default:S0},b0=(...t)=>D(void 0,[...t],function*(i=[{}]){return Array.isArray(i)||(i=[i]),i[0].recursive=i[0].recursive||!1,new Promise((e,r)=>{let o=document.createElement("input");o.type="file",o.webkitdirectory=!0;let s=a=>{typeof n=="function"&&n(),e(a)},n=i[0].legacySetup&&i[0].legacySetup(s,()=>n(r),o);o.addEventListener("change",()=>{let a=Array.from(o.files);i[0].recursive?i[0].recursive&&i[0].skipDirectory&&(a=a.filter(c=>c.webkitRelativePath.split("/").every(d=>!i[0].skipDirectory({name:d,kind:"directory"})))):a=a.filter(c=>c.webkitRelativePath.split("/").length===2),s(a)}),"showPicker"in HTMLInputElement.prototype?o.showPicker():o.click()})}),A0={__proto__:null,default:b0},v0=(e,...r)=>D(void 0,[e,...r],function*(i,t={}){Array.isArray(t)&&(t=t[0]);let o=document.createElement("a"),s=i;"body"in i&&(s=yield function(c,d){return D(this,null,function*(){let m=c.getReader(),l=new ReadableStream({start:T=>function E(){return D(this,null,function*(){return m.read().then(({done:y,value:v})=>{if(!y)return T.enqueue(v),E();T.close()})})}()}),f=new Response(l),g=yield f.blob();return m.releaseLock(),new Blob([g],{type:d})})}(i.body,i.headers.get("content-type"))),o.download=t.fileName||"Untitled",o.href=URL.createObjectURL(yield s);let n=()=>{typeof a=="function"&&a()},a=t.legacySetup&&t.legacySetup(n,()=>a(),o);return o.addEventListener("click",()=>{setTimeout(()=>URL.revokeObjectURL(o.href),3e4),n()}),o.click(),null}),R0={__proto__:null,default:v0};var gg=class{constructor(t){this.name=t;p(this,"ready");p(this,"worker");p(this,"ports");p(this,"ids",1);p(this,"transactions",new Map);p(this,"log");p(this,"addTransaction",t=>(this.transactions.set(++this.ids,t),this.ids))}postMessage(t,e){var r;(r=this.worker)==null||r.postMessage(t,e)}create(t){return D(this,null,function*(){if(this.ready)return this.ready;t||(t=this.name),console.time(`createWorker_${t}`);let e=Eh(),r=new Worker(typeof e=="string"?e:yield e,{name:t});return this.worker=r,this.ready=new Promise((o,s)=>D(this,null,function*(){r.onmessage=({data:{id:n,type:a,payload:c}})=>{var d;if(n)(d=this.transactions.get(n))==null||d(c),this.transactions.delete(n);else switch(a){case"error":console.timeEnd(`createWorker_${t}`),console.warn("worker error:",c),s(c);break;case"ready":console.timeEnd(`createWorker_${t}`),o(this);break;case"updateAFSM":if(c.value){let m=typeof c.old=="string"?c.old:`${c.old.action}ing`,l=typeof c.value=="string"?c.value:`${c.value.action}ing`;console.log(Qd(),c.group,c.name,m,"\u{1F449}",l)}break;case"log":console.log(c);break;case"glog":window.dispatchEvent(new CustomEvent(a,{detail:c}));break}},r.postMessage({wasm:yield Th(),flag:Ar},this.ports)}))})}destroy(){var t;console.log("destroy worker",this.name),delete this.ready,(t=this.worker)==null||t.terminate()}},_g=class{constructor(t,e,r){this.worker=t;p(this,"channel",new MessageChannel);p(this,"ready");this.ready=new Promise((o,s)=>{this.worker.postMessage({id:this.worker.addTransaction(o),payload:e},[this.channel.port2])}).then(o=>(o.err===0&&(this.worker.sessionCount++,this.channel.port1.onmessage=r),o))}postMessage(...t){this.channel.port1.postMessage(...t)}destroy(){--this.worker.sessionCount===0&&this.worker.destroy()}},Eg=class i extends gg{constructor(){super("main");p(this,"switchValue",new Map);p(this,"extendChannel");p(this,"sessionCount",0)}setSwitchValue(e,r){var o;this.switchValue.set(e,r),(o=this.extendChannel)==null||o.port1.postMessage([e,r])}create(){return D(this,null,function*(){return this.ready?this.ready:(this.extendChannel=new MessageChannel,this.ports=[this.extendChannel.port2],yield Er(i.prototype,this,"create").call(this),this.switchValue.forEach((e,r)=>{this.extendChannel.port1.postMessage([r,e])}),this)})}},ps=new Eg,gn,C0=-1;function qy(i){return console.log(i),gn.push(i.slice()),gn.length>1e3&&gn.shift(),i}function Xy(i){return D(this,null,function*(){switch(C0){case 0:this.edpl.willDecodeAudio=qy;break;case 2:this.edpl.didEncodeAudio=qy;break}yield ps.create(),ee.emit(ce.JOIN_SEND_CMD,{room:this});let t=new _g(ps,i,o=>{let s=o.data;if(typeof s=="string")this.onWorkerEvent(s);else if(s==null)this.onWorkerEvent("client-banned",0),t.destroy();else{let{cmd:n,payload:a}=s;this.onWorkerEvent(n,a)}}),{err:e,data:r}=yield t.ready;if(typeof e=="number"){if(ee.emit(ce.JOIN_RECEIVED_CMD_RES,{room:this,code:e}),e===0)return Object.assign(this,r,{session:t});throw new Me({code:Te.JOIN_ROOM_FAILED,extraCode:Number(e),message:Et({key:_t.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:e,errorMsg:""}})})}else throw e})}Object.defineProperties(window,{useAINS:{set:Tg},useWt:{set:w0},enableDebug:{set(i){console.debug=i?zy:()=>{},ps.setSwitchValue("enableDebug",i)}},useV2:{set:yg},dump:{value(){if(gn||(console.warn("dump audio will be activated at next time join room"),gn=[]),!gn.length){console.warn("no audio data to dump,try it later");return}let i=[];return gn.forEach(t=>{i.push(new Uint16Array([t.length])),i.push(t)}),fg(new Blob(i),{fileName:"audio dump hex",extensions:[".hex"]})}},dumpAudio:{value(i="audio",t=2e3){let e=[],r=new Promise(o=>{let s=new MessageChannel;ps.extendChannel.port1.postMessage(["dump",i],[s.port1]),s.port2.onmessage=({data:n})=>{console.log(n),e.push(n),e.length>t&&(s.port2.onmessage=null,ps.extendChannel.port1.postMessage(["dump",i]),s.port2.close(),o(new Blob(e)))}});return fg(r,{fileName:i,extensions:[".pcm"]})}},hardDec:{set(i){switch(i){case!0:Ar.useHardDecoder="prefer-hardware";break;case!1:Ar.useHardDecoder="prefer-software";break;default:Ar.useHardDecoder="no-preference"}}}});function Tg(i){return D(this,null,function*(){ps.setSwitchValue("useAINS",i)})}function yg(i){return D(this,null,function*(){ps.setSwitchValue("useV2",i)})}function w0(i){return D(this,null,function*(){ps.setSwitchValue("useWt",i)})}function Jy(i){let t=new MediaStreamTrackGenerator({kind:"audio"});i.setInputMediaStreamTrack(t),i.player.setVolume(0),this.postMessage({cmd:"pullAudio",payload:{tinyId:i.tinyId,writable:t.writable}},[t.writable])}function Qy(i){return D(this,null,function*(){var o;this._log.info("pull video",i);let t=Date.now(),e=0,r=new MessageChannel;this.postMessage({cmd:"pullVideo",payload:{mediaType:i.mediaType,tinyId:i.tinyId}},[r.port1]),(o=i.stat).framesReceived||(o.framesReceived=0),Ye(Hy(r.port2),At(Qe(i,Ve.INIT)),lt(s=>{let{data:n,packetsReceived:a}=s;i.stat.packetsReceived=a,i.stat.framesReceived++,e++;let c=n[4]&31;if(e<=10){let m=Array.from(n.slice(0,10)).map(l=>l.toString(16).padStart(2,"0")).join(" ");this._log.info(`Frame ${e} - Size: ${n.length} bytes, Type: ${c}, Timestamp: ${Date.now()-t}ms First 10 bytes: ${m}`)}let d;switch(c){case 5:case 7:d="key";break;default:d="delta";break}i.isAvailable?i.decodeFrame({data:n.buffer,type:d,timestamp:(Date.now()-t)*1e3}):console.warn("track is not available")},()=>{},()=>{r.port2.postMessage(null),r.port2.close()}))})}var Sh=[];function Zy(i){var c;let t=ir();if(this.state!=="joined")throw new Error("Room is not joined");if(i.state==="publish")return;for(let d=0;d<=Sh.length;d++)if(!Sh[d]){Sh[d]=this,this.index=d;break}let e=i.profile;this._log.info("start push audio",this.index,e);let r=new MessageChannel,o=i.enableEncryptFrame?new MessageChannel:null;(c=this.session)==null||c.postMessage({cmd:"pushAudio",payload:be({index:this.index},e)},o?[r.port2,o.port2]:[r.port2]),r.port1.onmessage=d=>{d.data==null||(typeof d.data=="number"?t.next(d.data):o&&o.port1.postMessage(qe(be({},d.data),{data:new Uint8Array(i.encodeFrame({data:d.data.data.buffer,timestamp:d.data.timestamp}).data)})))};let s=new MediaStream,n,a=d=>{let m=s.getAudioTracks()[0];m&&(n.disconnect(),s.removeTrack(m)),s.addTrack(d),this._log.info("push audio track:",d.readyState,d.getSettings().deviceId),n=bt("player").createMediaStreamSource(s),n.connect(md.worklet,0,this.index)};Ye(Qe(i,"output-media-track-changed"),At(Qe(i,"ready")),lt(a,console.error,()=>{this._log.info("stop push audio",e),i.volume=0,n.disconnect(),Sh[this.index]=null,o&&o.port1.postMessage(null),r.port1.postMessage(null)})),Ye(t,en(d=>i.volume=d),Io(_l(1e3)),lt(()=>{i.volume=0})),a(i.outMediaTrack)}var aG=new Intl.DateTimeFormat("zh-CN",{dateStyle:"short",timeStyle:"medium"});var Sg=class{constructor(t,e,r,o){this.localTrack=t;this.type=e;this.config=r;this.port=o;p(this,"track");p(this,"label");p(this,"insertKeyFrame",!0);p(this,"session");p(this,"tsMap",new Map);t._log.info("create Video Encoder",r)}trans(t,e,r){return D(this,null,function*(){let o=yield this.recreate(r,{recreateCount:0,frameEncoded:0,selectConfigIndex:0});e.signal.addEventListener("abort",()=>{o.encoder.close()});let s=0;return t.pipeThrough(new TransformStream({transform:(n,a)=>{o.encoder.state==="configured"&&(this.tsMap.set(s,Date.now()),this.encode(n),s++,a.enqueue(n))}}),e)})}encode(t){var e,r;(r=(e=this.session)==null?void 0:e.encoder)==null||r.encode(t,{keyFrame:this.insertKeyFrame}),this.insertKeyFrame=!1}start(t,e,r){return D(this,null,function*(){let o=yield this.recreate(r,{recreateCount:0,frameEncoded:0,selectConfigIndex:0});this.session=o;let s=0;t.pipeTo(new WritableStream({write:n=>{o.encoder.state==="configured"&&(s<10&&this.localTrack.log.info(`capture ${this.label} track frame:`,s,Date.now(),n.timestamp,n.displayWidth,n.displayHeight),(n.displayWidth!==this.config.width||n.displayHeight!==this.config.height)&&(this.localTrack.log.info("resize video track frame:",n.displayWidth,n.displayHeight,this.config.width,this.config.height),this.configure({width:n.displayWidth,height:n.displayHeight},o)),this.tsMap.set(s,Date.now()),this.encode(n),s<10&&this.localTrack.log.info(`encode ${this.label} track frame:`,s),s++,n.close())}}),e).catch(n=>{this.localTrack.log.warn(n),o.encoder.close()})})}recreate(t,e){return D(this,null,function*(){let r=0,o=new VideoEncoder({output:s=>{let n=this.tsMap.get(r);if(this.tsMap.delete(s.timestamp),r<10&&(r===0&&e.recreateCount===0&&ee.emit(ce.SEND_FIRST_VIDEO_FRAME,{room:t}),this.localTrack.log.info(`encoded ${this.label} track frame:`,r,Date.now(),s.timestamp)),r++,e.frameEncoded=r,this.track.enabled===!1)return;let a=null;if(this.localTrack.enableEncodeFrame){a=new Uint8Array(s.byteLength),s.copyTo(a);let c=this.localTrack.encodeFrame({data:a.buffer},this.type===3);a=new Uint8Array(c.data)}a?(this.localTrack.stat.bytesSent+=a.length,this.port.postMessage({chunk:{type:s.type,timestamp:s.timestamp,data:a,duration:s.duration},timestamp:n},[a.buffer])):(this.localTrack.stat.bytesSent+=s.byteLength,this.port.postMessage({chunk:s,timestamp:n}))},error:s=>{this.localTrack.log.warn(s,this.config),e.recreateCount++,setTimeout(()=>this.recreate(t,e),100)}});return e.encoder=o,yield this.configure(null,e),e})}configure(t,e){return D(this,null,function*(){var r;t&&Object.assign(this.config,t),(r=e.encoder)==null||r.configure(this.config)})}close(){this.port.postMessage(null),this.port.close()}};function Ih(i,t){return D(this,null,function*(){let e=i.mediaType===2,r=e?"screen":"video",o={codec:"avc1.420028",latencyMode:"realtime",avc:{format:"annexb"},hardwareAcceleration:Ar.useHardEncoder,width:t.profile.width,height:t.profile.height,framerate:t.profile.frameRate,bitrate:t.profile.bitrate*1e3},s=new MessageChannel;this.postMessage({cmd:"pushVideo",payload:t},[s.port1]);let n=new Sg(i,t.type,o,s.port2);return s.port2.onmessage=a=>{if(a.data===260)n.insertKeyFrame=!0;else if(!e){let{bitrate:c}=a.data;$a({configureBr:[a.data.bitrate,c]}),n.session&&n.configure({bitrate:c},n.session)}},this._log.info("start push",r,t),n})}function Ky(i){return D(this,null,function*(){var m;let t=i.mediaType===2,e=t?"screen":"video",r={type:t?7:2,profile:i.profile,trackType:t?"screen":"camera",crypto:!!((m=i.manager)!=null&&m.encodePipeline[0])};!t&&i.outMediaTrack instanceof CanvasCaptureMediaStreamTrack&&(r.trackType="canvas");let{trackType:o}=r,{width:s,height:n}=i.outMediaTrack.getSettings();r.profile.width=s,r.profile.height=n;let a=yield Ih.call(this,i,r);this._log.info("VideoEncoder created",r);let c,d=l=>D(this,null,function*(){if(c==null||c.abort("track changed"),!l)return;c=new AbortController;let{width:f,height:g,displaySurface:T}=l.getSettings();f&&(a.config.width=f),g&&(a.config.height=g);let E=$r.match(/Chrome\/(\d+)/);(E==null?void 0:E[1])==="114"&&T==="browser"&&delete a.config.hardwareAcceleration,this._log.info("push",e,"track:",l.readyState,l.getSettings());let y;if(typeof MediaStreamTrackProcessor!="undefined"&&!(l instanceof CanvasCaptureMediaStreamTrack))y=new MediaStreamTrackProcessor({track:l}).readable;else{let M;y=new ReadableStream({start(w){i.on("render",H=>{if(!(i.player.mode===0&&!document.hidden))try{w.enqueue(new VideoFrame(H,{timestamp:performance.now()*1e3}))}catch(B){console.warn(B)}})},pull(w){return D(this,null,function*(){if(i.player.mode===0&&Ri()&&i.player.element)return new Promise(H=>{i.player.element.requestVideoFrameCallback((B,P)=>{try{let $=new VideoFrame(i.player.element);w.enqueue($)}catch($){console.warn($)}H()})})})}})}let v="small"in i&&i.small;return v?(this.smallEncoder||(this.smallEncoder=yield Ih.call(this,i,{profile:v,type:3,trackType:o})),this.smallEncoder.track=l,this.smallEncoder.label="small",y=yield this.smallEncoder.trans(y,c,this)):this.smallEncoder&&(this.smallEncoder.close(),delete this.smallEncoder),a.track=l,a.label=e,a.start(y,c,this)});return Ye(Qe(i,"output-media-track-changed"),At(Qe(i,"ready")),lt(d,console.error,()=>{var l;this._log.info("stop push",e,r),c.abort("unpublish"),a.close(),(l=this.smallEncoder)==null||l.close()})),d(i.outMediaTrack)})}var fs=class fs extends Ve{constructor(e){var r,o;super((o=(r=e.roomid)==null?void 0:r.toString())!=null?o:e.name,"volumeEvaluation");this.room=e;p(this,"enableInBackground",!1);p(this,"interval",400);e.on("joined",()=>{this.emit(fs.INTERVALCHANGED,this.interval)}),Ye(Qe(this,fs.INTERVALCHANGED),Wi(s=>this.room.state==="joined"?this.room.fromWorker("getAudioEnergy",s):Ye(HE(s),ts(()=>[]))),lt(s=>{s.forEach(n=>{this.room.remotePublishedUserMap.has(n.userId)&&(this.room.remotePublishedUserMap.get(n.userId).remoteAudioTrack.volume=n.volume)}),(!document.hidden||this.enableInBackground)&&this.state==Ve.ON&&this.room.emit("audio-volume",s)}))}start(e,r){this.interval=e,this.enableInBackground=r,this.emit(fs.INTERVALCHANGED,this.interval)}stop(){}};p(fs,"INTERVALCHANGED","intervalChanged"),Ie([Mt([Ve.INIT,Ve.OFF],Ve.ON)],fs.prototype,"start",1),Ie([Mt([],Ve.OFF)],fs.prototype,"stop",1);var bh=fs;var gs=class gs extends _h{constructor(e){super(e);p(this,"index",0);p(this,"session");p(this,"tinyid");p(this,"roomid");p(this,"openid");p(this,"socketid");p(this,"relayip");p(this,"clientip");p(this,"remotePublishedUserMap",new Map);p(this,"bussinessInfo");p(this,"token");p(this,"audioVolumeEvalution",new bh(this));p(this,"enableAIVoice",Tg);p(this,"AbilityOption",{AVLimit:{EncVideoCodec:"H265",EncVideoWidth:0,EncVideoHeight:0,EncVideoBr:"0",EncVideoFps:0,EncAudioCodec:"opus",EncAudioFS:0,EncAudioCh:0,EncAudioBr:"0"},GeneralLimit:{CPULimit:{uint32_CPU_num:navigator.hardwareConcurrency||0,str_CPU_name:navigator.platform,uint32_CPU_maxfreq:0,model:"",uint32_total_memory:0},uint32_terminal_type:Im(),uint32_device_type:0,str_os_verion:bm(),uint32_link_type:1,str_client_version:qt,uint32_net_type:Rs[Vi.getNetworkType()],ua:navigator.userAgent,version:""}});p(this,"joinAbortController",new AbortController);p(this,"smallAbortCtrl");p(this,"smallEncoder");e.tinyId&&(this.tinyId=e.tinyId,yg(!0)),this._log||(this._log=e.logger),this.bussinessInfo=e.bussinessInfo,e.encodedDataProcessingListener&&this.setEncodedDataProcessingListener(e.encodedDataProcessingListener)}replaceTrack(e){return D(this,null,function*(){})}getLogger(){return this._log}postMessage(e,r){this.session&&(e?typeof e=="string"?this.session.postMessage({cmd:e,payload:r}):this.session.postMessage(e,r):this.session.postMessage(null))}sendMessage(e,r){return new Promise((o,s)=>{this.state!="joined"&&s("join room first");let n=new MessageChannel;this.postMessage({cmd:e,payload:r},[n.port1]),n.port2.onmessageerror=s,n.port2.onmessage=a=>{n.port2.close(),o(a.data)}})}fromWorker(e,r){if(this.state!="joined")throw"join room first";return o=>{var n;let s=new MessageChannel;s.port2.onmessage=a=>{a.data?o.next(a.data):o.complete()},s.port2.onmessageerror=a=>o.error(a),o.defer(()=>{s.port2.postMessage(null),s.port2.close()}),(n=this.session)==null||n.postMessage({cmd:e,payload:r},[s.port1])}}switchRole(e){return D(this,null,function*(){if(e!==this.role)return this._log.info(`switchRole() => switch role to: ${e}`),e=="audience"&&this.unpublish(...this.localTracks),this.sendMessage("switchRole",e=="audience"?21:20).then(r=>{this.role=e})})}join(e,r,o){return D(this,null,function*(){var c,d,m;let s=Vi.getEnv(),n=Pu(),a={isH264EncodeSupported:this.checkSystemResult.detail.isH264EncodeSupported,isVp8EncodeSupported:this.checkSystemResult.detail.isVp8EncodeSupported,frameWorkType:o,params:e,proxy_wt:(c=this.proxy_wt)==null?void 0:c.replace("https://",""),proxy_ws:(d=this.proxy_ws)==null?void 0:d.replace("wss://",""),proxy_cloud:(m=this.scheduleResult.iceServers)!=null&&m.length?this.scheduleResult.iceServers[0].urls:[],proxy_unified:this.proxy_unified,domains:this.scheduleResult.domains,env:s,osName:Jn(),browserInfo:Pu(),tinyId:this.tinyId,joinReq:{useStrRoomid:!!this.useStringRoomId,roomid:String(e.roomId||e.strRoomId),sdkAppID:String(e.sdkAppId),userSig:e.userSig,privMapEncrypt:e.privateMapKey||"",privMap:"",pstnBizType:0,role:"user",jsSdkVersion:qt,browserVersion:n.browserName+n.browserVersion,closeLocalMedia:!0,trtcscene:r==="live"?2:1,trtcrole:e.role,bussinessInfo:e.businessInfo||this.bussinessInfo||"",isAuxUser:0,autoSubscribe:this.autoReceiveAudio&&this.autoReceiveVideo,AbilityOption:this.AbilityOption}};yield Xy.call(this,a),console.log(this),md.playAudio(l=>this.postMessage({cmd:"setAudioWorkletPort"},[l])),this.checkDestroy()})}leave(){return D(this,null,function*(){this.remotePublishedUserMap.forEach(e=>{e.remoteAudioTrack.close(),e.remoteAuxiliaryTrack.close(),e.remoteVideoTrack.close()}),this.postMessage(null),this.remotePublishedUserMap.clear(),this.localTracks.forEach((e,r)=>r.unpublish()),this.localTracks.clear()})}getSignalInfo(){return{tinyId:this.tinyid,clientIp:this.clientip,signalIp:"",relayIp:this.relayip,relayInnerIp:"",relayPort:0}}enableAudioVolumeEvaluation(e=2e3,r=!1){e<=0?this.audioVolumeEvalution.stop():this.audioVolumeEvalution.start(e,r)}getLocalAudioStats(){return this.sendMessage("getLocalAudioStats")}getLocalVideoStats(){return this.sendMessage("getLocalVideoStats")}afterJoin(){return D(this,null,function*(){let e=At(Qe(this,"left"));Ye(r=>D(this,null,function*(){let o=new MessageChannel;o.port2.onmessage=s=>{s.data?r.next({data:s.data,port:o.port2}):r.complete()},o.port2.onmessageerror=s=>r.error(s),r.defer(()=>{o.port2.postMessage(null),o.port2.close()}),this.postMessage({cmd:"decodeAudio",payload:!!this.audioManager.decodePipeline[0]},[o.port1])}),e,lt(({data:r,port:o})=>{let s=this.audioManager.decodePipeline[0]({frame:{data:r.data.buffer}});o.postMessage(qe(be({},r),{data:new Uint8Array(s.data)}),[s.data])}))})}onWorkerEvent(e,r){switch(e!=="network-quality"&&console.info(this.userId,"onWorkerEvent",e,JSON.stringify(r)),e){case ce.RECEIVED_PUBLISHED_USER_LIST:ee.emit(e,be({room:this},r));return;case"1":if(r.userId===this.userId)return;this.emit("peer-join",r);return;case"2":this.emit("peer-leave",r);return;case"3":let o=new uh(this,r);this.remotePublishedUserMap.set(r.userId,o),this.emit("remote-published",o);return;case"5":{let l=r,f=this.remotePublishedUserMap.get(l);f&&(f.remoteVideoTrack.close(),f.remoteAuxiliaryTrack.close(),f.remoteAudioTrack.close(),this.remotePublishedUserMap.delete(l),this.emit("remote-unpublished",f))}return;case"banned":switch(r){case 8:this.emit("banned",{reason:"kick",message:""});return;case 2:case 6:case 4:this.emit("banned",{reason:"banned",message:""});return;case 7:case 5:this.emit("banned",{reason:"room_disband",message:""});return}break;case"6":{let{prevMuteState:l,muteState:f,flag:g}=r,T=this.remotePublishedUserMap.get(f.userId);if(!T){this.emit("remote-publish-state-changed",r);return}T.flag=g}ee.emit(ce.REMOTE_PUBLISH_STATE_CHANGED,be({room:this},r)),this.emit("remote-publish-state-changed",r);return;case"7":this.localPublishFlag!==r.flag&&(this.localPublishFlag=r.flag,this.emit("local-publish-flag-changed",r.flag));return;case"network-quality":this.quality=be({},r);let{uplinkLoss:s,uplinkRTT:n,uplinkInfo:a,downlinkInfo:c,msg_down_stream_info:d}=r,m={str_sdk_version:qt,uint64_datetime:Date.now(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyid},msg_device_info:{uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:Rs[kn()]},msg_event_msg:zE(this.userId),str_acc_ip:this.relayip,str_client_ip:this.clientip,msg_up_stream_info:a,msg_down_stream_info:d};ee.emit(ce.HEARTBEAT_REPORT,{room:this,report:m}),this.emit("heartbeat-report",m),ee.emit(ce.NETWORK_QUALITY,{room:this,uplink:{rtt:n,loss:s},downlinks:c}),delete r.downlinkInfo;break;case"signal-connection-state-changed":ee.emit(ce.SIGNAL_CONNECTION_STATE_CHANGED,be({room:this},r));return}this.emit(e,r)}sendStartPublishCDN(e,r){return e.roomid=this.roomId,e.sdkAppID=String(this.sdkAppId),e.socketid=this.socketid,r&&(e.request_time=e.pushRequestTime),this.sendMessage("publishCdn",e)}sendStopPublishCDN(e,r){return e.roomid=this.roomId,e.sdkAppID=String(this.sdkAppId),e.socketid=this.socketid,r&&(e.request_time=e.pushRequestTime),this.sendMessage("stopPublishCdn",e)}sendStartMixTranscode(e){return this.sendMessage("startMcuMix",e)}sendStopMixTranscode(e){return this.sendMessage("stopMcuMix",e)}publish(e){return D(this,null,function*(){switch(yield this.sendMessage("publish",e.mediaType).then(r=>r.err!==0?Promise.reject(r.err):r),yr(e,e).add("mute",()=>{this.postMessage("mute",{mediaType:e.mediaType,userId:this.userId,srctinyid:this.tinyid,remove:!0})}).add("unmute",()=>{this.postMessage("unmute",{mediaType:e.mediaType,userId:this.userId,srctinyid:this.tinyid,add:!0})}),e.mediaType){case 1:yield md.init(),Zy.call(this,e);break;default:yield Ky.call(this,e)}e.muted&&this.postMessage("mute",{mediaType:e.mediaType,srctinyid:this.tinyid,userId:this.openid,remove:!0})})}unpublish(e){return D(this,null,function*(){tr(e)})}subscribe(...e){return D(this,null,function*(){let r=e.reduce((l,f)=>f.mediaType|l,0),{userId:o,tinyId:s,streamType:n}=e[0],a=this.remotePublishedUserMap.get(o),c=be({},a.subscribeState),d=Object.assign(new sc,c);d.mediaType|=r,ee.emit(ce.SUBSCRIBE_START,{room:this,streamType:n,remotePublishedUser:a,subscribeState:d});let m=yield this.sendMessage("subscribe",{mediaType:d.mediaType,userId:o,srctinyid:s,mediaDescription:{audioParam:{mediaType:1,payloadFmtps:[{payloadType:111,fmtp:"minptime=10;useinbandfec=1"}]},videoParam:[4,8,2].filter(l=>d.mediaType&l).map(l=>({mediaType:l,payloadFmtps:[{payloadType:100,fmtp:"packetization-mode=1;profile-level-id=42e01f"}]}))}});console.dir("subscribe",m),yield Promise.all(e.filter(l=>!l.isSubscribed).map(l=>{switch(l.mediaType){case 1:return Jy.call(this,l);default:return Qy.call(this,l)}})),ee.emit(ce.SUBSCRIBE_SUCCESS,{room:this,streamType:n,remotePublishedUser:a})})}unsubscribe(...e){return D(this,null,function*(){let r=0;for(let o of e)r|=o.mediaType;if(e.length){let{userId:o,streamType:s,tinyId:n}=e[0];yield this.sendMessage("unSubscribe",{mediaType:r,srctinyid:n,userId:o});for(let a of e)a.unsubscribe();ee.emit(ce.UNSUBSCRIBE_SUCCESS,{room:this,streamType:s,remotePublishedUser:this.remotePublishedUserMap.get(o)})}})}enableSmall(e){return D(this,null,function*(){var r;if(e){if(this.videoManager.smallTrack){let o=this.videoManager.cameraTrack;this.smallEncoder=yield Ih.call(this,o,{profile:o.small,type:3,trackType:"camera"});let s=new MediaStreamTrackProcessor({track:this.videoManager.smallTrack}).readable;this.smallEncoder.track=this.videoManager.smallTrack,this.smallEncoder.label="small",this.smallAbortCtrl=new AbortController,this.smallEncoder.start(s,this.smallAbortCtrl,this),this._log.info("push small")}}else(r=this.smallAbortCtrl)==null||r.abort("stop"),this.smallEncoder&&(this.smallEncoder.close(),delete this.smallEncoder)})}changeType(e,r){let o=this.remotePublishedUserMap.get(r.userId);if(!o)return;let s=e?8:4;if(o.remoteVideoTrack.mediaType===s)return;let n={srctinyid:o.tinyId,mediaType:s,userId:r.userId,mediaDescription:{audioParam:{mediaType:1,payloadFmtps:[{payloadType:111,fmtp:"minptime=10;useinbandfec=1"}]},videoParam:[4,8].filter(a=>s&a).map(a=>({mediaType:a,payloadFmtps:[{payloadType:100,fmtp:"packetization-mode=1;profile-level-id=42e01f"}]}))}};o.remoteVideoTrack.mediaType=n.mediaType,this.postMessage("changetype",n)}destroy(){this.isDestroyed||(super.destroy(),this.isDestroyed=!0,this.joinAbortController.abort("destroy"))}};Ie([Ko(gs.prototype.afterJoin),Mt(["left",Ve.INIT],"joined"),Oy()],gs.prototype,"join",1),Ie([Mt("joined","left",{ignoreError:!0}),My()],gs.prototype,"leave",1),Ie([tl(e=>e.mediaType),xy()],gs.prototype,"publish",1),Ie([tl(e=>e.mediaType),ky()],gs.prototype,"unpublish",1),Ie([tl((...e)=>e[0].userId),Ly()],gs.prototype,"subscribe",1);var Ah=gs;va.frameWorkType=37;va.create=function(i){let t=va._create.call(this,Ah,i);return t._use(Mf,i==null?void 0:i.assetsPath),i!=null&&i.assetsPath&&(Ar.assetsPath=i==null?void 0:i.assetsPath),console.log("trtc wasm sdk:",qt,"created",Ar),t};Object.assign(va.prototype,{_setCurrentSpeaker(i){let t=bt("player");return t!=null&&t.setSinkId?t.setSinkId(i):Promise.reject("not support")},_enableVideoDecodeFallback(i,t){return D(this,null,function*(){return this.startPlugin(Mf.Name,{type:"webCodecs",renderer:"videoFrame",track:i,config:{codec:"avc1.640028",hardwareAcceleration:"prefer-software",optimizeForLatency:!0},fallback:"wasm"}),new Promise((e,r)=>{Ye(Qe(i,"decode-downgrade-state-changed"),Ur(o=>o.state==="STARTED"),Ni(1),nf(1e4),At(Qe(i,Ve.INIT)),lt(e,r))})})}});ep(37);var xz=va;export{xz as default};
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
<http://stuartk.com/jszip>
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
JSZip uses the library pako released under the MIT license :
|
|
179
|
-
https://github.com/nodeca/pako/blob/main/LICENSE
|
|
180
|
-
*)
|
|
181
|
-
*/
|
|
111
|
+
}`});d(this,"yTextureRef");d(this,"uTextureRef");d(this,"vTextureRef");d(this,"Y");d(this,"U");d(this,"V");this.useProgram();let t=this.context.ctx;t.pixelStorei(t.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),this.setTexBuffer([0,1,1,1,0,0,1,0]),this.yTextureRef=this._initTexture("ySampler",0),this.uTextureRef=this._initTexture("uSampler",1),this.vTextureRef=this._initTexture("vSampler",2),this._canvas=e._canvas}_initTexture(e,t){let r=this.context.ctx,s=r.createTexture();return r.bindTexture(r.TEXTURE_2D,s),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.bindTexture(r.TEXTURE_2D,null),r.uniform1i(r.getUniformLocation(this.program,e),t),s}render(e){let t=this.context.ctx,r=this.width,s=this.height;return this.useProgram(),t.viewport(0,0,r,s),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,this.yTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,r,s,t.LUMINANCE,t.UNSIGNED_BYTE,this.Y),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,this.uTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,r/2,s/2,t.LUMINANCE,t.UNSIGNED_BYTE,this.U),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this.vTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,r/2,s/2,t.LUMINANCE,t.UNSIGNED_BYTE,this.V),this.draw(),!0}resize(e,t){super.resize(e,t);let r=this.context.ctx;r.activeTexture(r.TEXTURE0),r.bindTexture(r.TEXTURE_2D,this.yTextureRef),r.texImage2D(r.TEXTURE_2D,0,r.LUMINANCE,e,t,0,r.LUMINANCE,r.UNSIGNED_BYTE,null),r.activeTexture(r.TEXTURE1),r.bindTexture(r.TEXTURE_2D,this.uTextureRef),r.texImage2D(r.TEXTURE_2D,0,r.LUMINANCE,e/2,t/2,0,r.LUMINANCE,r.UNSIGNED_BYTE,null),r.activeTexture(r.TEXTURE2),r.bindTexture(r.TEXTURE_2D,this.vTextureRef),r.texImage2D(r.TEXTURE_2D,0,r.LUMINANCE,e/2,t/2,0,r.LUMINANCE,r.UNSIGNED_BYTE,null)}};var A_=(o,i)=>{switch(o){case"webCodecs":return i==="videoFrame"?514705:514706;case"wasm":return i==="webgl"?514707:i==="videoFrame"?514708:514709}throw new Error("decoder type not supported")};function _I(o){return o[0]===0&&o[1]===0&&o[2]===0&&o[3]===1}var gI=0,Pd=class{constructor(i){d(this,"id",gI++);d(this,"trackDoneOB");d(this,"startOB");d(this,"stopOB");d(this,"decoder");d(this,"videoContext");d(this,"gop",0);d(this,"gop_helper",0);d(this,"waitFirstKeyFrame",!0);d(this,"startTimestamp",0);d(this,"startTime",0);d(this,"startPerformanceTime",0);d(this,"inputFrameCount",0);d(this,"decodedFrameCount",0);d(this,"decodeFrameCount",0);d(this,"downgradeLevel",0);d(this,"lastDowngradeTime",0);d(this,"lastFrameDiff",0);d(this,"lastDecodeFrameTimestamp",0);d(this,"config");d(this,"gop_before_configure",[]);d(this,"videoElement");d(this,"type","wasm");d(this,"goodType");d(this,"renderer","2d");d(this,"wasmOption");d(this,"createDecoder");d(this,"_decodeSink");d(this,"isReported",!1);d(this,"track");d(this,"stateChangeOB");d(this,"failedReason");let{track:e,createDecoder:t}=i;if(this.stateChangeOB=ot(),this.track=e,this.createDecoder=t,this.wasmOption={yuvMode:i.renderer==="webgl",wasmPath:i.wasmPath,workerMode:i.workerMode,canvas:i.canvas},this.config=i.config,this.videoElement=i.videoElement,this.renderer=i.renderer,this.trackDoneOB=de(e.availableState,q.OFF),this.stopOB=ot(),i.type==="auto"){switch(i.fallback){case"wasm":this.type="wasm",this.renderer="webgl";break;case"wasm_2d":this.type="wasm",this.renderer="2d";break;case"wasm_video":this.type="wasm",this.renderer="videoFrame";break;default:this.type="webCodecs"}this.wasmOption.yuvMode=this.renderer==="webgl"}else this.type=i.type;this.changeRenderer(this.renderer),le(this.stateChangeOB,mh((r,s)=>(r!==s&&e.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:this.failedReason,prevState:r,state:s}),s),"INITIALIZED"),ke(this.stopOB),Ee()),this.start()}start(i=0){this.waitFirstKeyFrame=!0,this.stateChangeOB.next("STARTING");let e=le(this.pipe(this.track),ke(this.stopOB),rr());le(e,Ee(()=>{this.track.stat.framesDecoded++},t=>{if(this.track.log.error(`${this.id} play failed: ${t} retryCount: ${i}`),v.addFailedEvent({key:A_(this.type,this.renderer),error:t}),i>4)this.failedReason=t,this.stateChangeOB.next("FAILED"),v.addFailedEvent({key:514704});else{if(this.goodType){this.start(i);return}switch(this.type){case"webCodecs":this.type="wasm",this.changeRenderer("webgl");break;case"wasm":switch(this.renderer){case"webgl":this.changeRenderer("videoFrame");break}}this.start(i+1)}},()=>{this.track.log.warn(`${this.id} decoderOB completed`),v.addSuccessEvent({key:A_(this.type,this.renderer)}),v.addSuccessEvent({key:514704})})),le(e,or(1),Ee(()=>{this.track.player.handlePlaying("canvas"),this.goodType=this.type,this.stateChangeOB.next("STARTED")}))}mock(i){this._decodeSink?this._decodeSink.error(i):this.start()}close(i){this.stopOB.next(i)}changeRenderer(i){this.renderer=i,this.renderer==="videoFrame"&&!fn()&&(this.renderer="2d"),this.wasmOption.yuvMode=this.renderer==="webgl"}decode(i,e=!1){var a,c;if(this.failedReason)return;this.inputFrameCount++;let t=new Uint8Array(i.data);if(!_I(t)||t.length<5)return this.stateChangeOB.next("FAILED"),this.close(`not h26x frame ${t.subarray(0,5)}`),i;let r=t[4]&31,s=!1;switch(r){case 5:case 7:s=!0;break}if(((a=this.decoder)==null?void 0:a.state)!=="configured")return this.track.log.debug(`not configured ${this.inputFrameCount}`),s&&(this.gop_before_configure=[]),this.gop_before_configure.push({data:i.data,timestamp:i.timestamp,type:i.type}),i;this.gop_before_configure.length>0&&!e&&(this.gop_before_configure.forEach(l=>this.decode(l,!0)),this.gop_before_configure=[]);let{timestamp:n}=i;if(s?(this.gop=this.gop_helper,this.gop_helper=0):this.gop_helper++,this.decoder){if(this.waitFirstKeyFrame)if(s)this.waitFirstKeyFrame=!1,this.startTimestamp=n,this.startTime=Date.now(),this.startPerformanceTime=U();else{this.track.log.debug(`wait first key frame ${this.inputFrameCount} ${t.subarray(0,5).join(" ")}`);return}switch(this.downgradeLevel){case 0:break;case 1:break;case 2:if(this.gop_helper>this.gop>>1)return;break;case 3:if(this.gop_helper>0)return;break;default:return}(this.decodeFrameCount<10||this.decodeFrameCount%500===0)&&this.track.log.debug(`decode ${this.decodeFrameCount} gop: ${this.gop} ${n} ${(c=i.getMetadata)==null?void 0:c.call(i).rtpTimestamp}`),this.decodeFrameCount++,this.lastDecodeFrameTimestamp=n,this.decoder.decode({data:i.data,type:i.type,timestamp:this.lastDecodeFrameTimestamp});return}return i}checkDowngradeByFrameDiff(){let i=this.downgradeLevel,e=this.decodeFrameCount-this.decodedFrameCount;e>this.lastFrameDiff?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):e<=this.lastFrameDiff&&this.downgradeLevel>0&&this.downgradeLevel--,this.downgradeLevel!==i&&this.track.log.debug(`downgrade level ${i} to ${this.downgradeLevel} ${this.decodeFrameCount} frameDiff: ${e}, lastFrameDiff: ${this.lastFrameDiff}`),this.lastFrameDiff=e,this.lastDowngradeTime=Date.now()}checkDowngradeByTimestampDiff(i){let e=this.downgradeLevel;this.lastDecodeFrameTimestamp-i>9e4?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):this.downgradeLevel>0&&this.downgradeLevel--,this.downgradeLevel!==e&&this.track.log.debug(`downgrade level ${e} to ${this.downgradeLevel}`)}pipe(i){return e=>f(this,null,function*(){this._decodeSink=e;let t,r=i.mediaTrack;e.defer(()=>{var a;r&&(i.player.setCanvas(),i.setInputMediaStreamTrack(r)),t==null||t.close(),(a=this.videoContext)==null||a.destroy(),delete this._decodeSink});let{renderer:s,type:n}=this;i.log.info(`decoder type: ${this.type} renderer: ${this.renderer}`);try{switch(n){case"wasm":t=this.createDecoder(n,this.wasmOption);break;case"webCodecs":t=this.createDecoder(n);break;default:throw new Error("not supported yet")}let a=0;if(t.on("videoFrame",c=>{this.decodedFrameCount++,a++,(a<=10||a%500===0)&&i.log.debug(`frame ${a} ${this.decodedFrameCount}/${this.decodeFrameCount} decoded ${c.timestamp}`),Date.now()-this.lastDowngradeTime>5e3&&(this.type==="webCodecs"?this.checkDowngradeByFrameDiff():this.type==="wasm"&&this.checkDowngradeByTimestampDiff(c.timestamp)),e.next(c)}),t.on("error",c=>{i.log.error(c),e.error(n==="webCodecs"?4:8)}),yield t.initialize(this.videoElement),!this._decodeSink)return;if(t.configure(this.config),n==="wasm"&&s==="webgl"){this.videoContext=new Fe({frameRate:15,logger:i.log,name:i.userId}),this.videoContext.create(),this.videoContext.on(Fe.UNAVAILABLE,l=>{i.log.error(l),e.error(7)});let c=new kd(this.videoContext);t.on("videoCodecInfo",l=>c.resize(l.width,l.height)),t.on("videoFrame",l=>{({y:c.Y,u:c.U,v:c.V}=l),this.downgradeLevel===1?this.decodedFrameCount%2===0&&c.render(this.decodedFrameCount):c.render(this.decodedFrameCount)}),i.source=c,i.player.setCanvas(this.videoContext._canvas,2)}else if(s==="videoFrame"){i.player.setCanvas();let c=new MediaStreamTrackGenerator({kind:"video"}),l=c.writable.getWriter();i.setInputMediaStreamTrack(c),t.on("videoFrame",u=>l.write(u))}else{this.videoContext=new ze({frameRate:15,logger:i.log,name:i.userId}),this.videoContext.create({alpha:!1});let c=this.videoContext.createVideoImageSource();t.on("videoFrame",u=>{try{c.image=u,c.update()}catch(h){delete this.goodType,i.log.error(h),e.error(11)}});let l=new fo(this.videoContext,{name:"remotePlayer",logger:i.log});c.connect(l),i.source=c,i.player.setCanvas(this.videoContext._canvas,2)}this.decoder=t}catch(a){i.log.error(a),e.error(n==="webCodecs"?2:6)}})}};var C_=Promise.resolve(),sa=class extends R_.EventEmitter{constructor(e){super();this.room=e;d(this,"videoContext");d(this,"_glVideoContext");d(this,"_2dVideoContext");d(this,"destination");d(this,"smallVideoContext");d(this,"smallDestination");d(this,"smallTrackSource");d(this,"smallImageSource");d(this,"_isMirror",!1);d(this,"_rotation",0);d(this,"cameraTrack");d(this,"cameraNode");d(this,"transformNode");d(this,"mixNode");d(this,"screenTrack");d(this,"screenNode");d(this,"selfModel",!1);d(this,"blurRadius",3);d(this,"arTrack");d(this,"_enableFaceCentering",!1);d(this,"_enableEffectOptimization",!1);d(this,"onAbort");d(this,"_color");d(this,"Wasm");d(this,"waterMarkNode");d(this,"_waterMarkOption");d(this,"watermarkImageList",[]);d(this,"_beautyParams");d(this,"isUsingArTrack",!1);d(this,"mixTrack");d(this,"_isMixScreen",!1);d(this,"_virtualBackground");d(this,"_virtualBackgroundAbortCallback");d(this,"virtualBackgroundInstance");d(this,"_bgAssetPath");d(this,"log");d(this,"_mat4");d(this,"_postProcessing");d(this,"_checkId",0);d(this,"_use2d",!1);d(this,"_autoSwitchRenderMode",!0);d(this,"encodePipeline",[]);d(this,"decodePipeline",[]);d(this,"updated",C_);d(this,"_updateFlag",!1);this.log=R.createLogger({parent:e==null?void 0:e.getLogger(),id:"vm",userId:e==null?void 0:e.userId,sdkAppId:e==null?void 0:e.sdkAppId}),this.smallVideoContext=new ze({frameRate:15,logger:this.log,name:"s"}),this.enablePrintDetail()}get smallMode(){var e;return((e=this.room)==null?void 0:e.smallMode)||"canvas"}get _hasVirtualBg(){return!!this._virtualBackground}get _hasWaterMark(){return this.watermarkImageList.length>0}get _isRotate(){return this._rotation!==0}get _isTransform(){return this._isMirror||this._isRotate}get renderMode(){return this._autoSwitchRenderMode?"auto":this._use2d?"2d":"webgl"}set renderMode(e){if(this._autoSwitchRenderMode=e==="auto",this._autoSwitchRenderMode)return;let t=e==="2d";this._use2d!==t&&(this._use2d=t,this.clear(),this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.update())}get cameraResolution(){var r;let{width:e,height:t}=((r=this.cameraTrack)==null?void 0:r.settings)||{};return bt(this._rotation)?{width:t,height:e}:{width:e,height:t}}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new ze({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this._2dVideoContext}getGlVideoContext(){if(!this._glVideoContext)this._glVideoContext=new Fe({frameRate:15,logger:this.log,name:"m"});else if(this._glVideoContext.available)return this._glVideoContext;return this.initializeGlVideoContext(),this._glVideoContext}initializeGlVideoContext(){try{this._glVideoContext.create(Nl<=22),this._glVideoContext.on(Fe.UNAVAILABLE,e=>{var t;this.emit("error",e),this.log.warn("video context unavailable",e),(t=this._virtualBackgroundAbortCallback)==null||t.call(this,e),this.update().catch(r=>{this.log.error(r)})})}catch(e){this.emit("error",e)}}initVirtualBackground(e,t,r){this.onAbort=e,this._mat4=t,this._postProcessing=r}enablePrintDetail(e=2e3){this._checkId=re.run("interval",()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:e})}destroy(){var e,t;(e=this._2dVideoContext)==null||e.destroy(),(t=this._glVideoContext)==null||t.destroy(),this.smallVideoContext.destroy(),re.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(Ft||this._isMixScreen||this._isTransform||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}sendCreateResult(e="videoCtxGl",t){let r=e==="videoCtxGl"?512700:512701;t?v.addFailedEvent({key:r,error:t}):v.addSuccessEvent({key:r})}checkOrCreateVideoContext(){let e=this._use2d;if(this._autoSwitchRenderMode&&(this._use2d=!this._hasVirtualBg),this.videoContext)if(this.videoContext.available){let t=!this.videoContext.hasAlpha&&this.needAlpha;if(this._autoSwitchRenderMode&&e===this._hasVirtualBg)this.clear();else if(t)if(this._use2d)this.clear();else return!0;else return!0}else{if(this._glVideoContext=new Fe({frameRate:15,logger:this.log,name:"m"}),this.initializeGlVideoContext(),this._glVideoContext.available)return this.videoContext=this._glVideoContext,this.videoContext.available;this.log.warn("webgl is still not available"),this.clear(),this._use2d=!0}return this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.videoContext.available}get smallTrack(){var e;return(e=this.smallDestination)==null?void 0:e.videoTrack}get hasSmall(){return!!this.smallTrack}get initialTrack(){var e;return(e=this.cameraTrack)==null?void 0:e.mediaTrack}setSmallVideo(e,t){if(this.smallMode!=="api")if(e){if(!this.smallVideoContext.available){if(this.smallVideoContext.create({alpha:!1}),!this.smallVideoContext.available)return;this.smallDestination=new Zc(this.smallVideoContext,e,this.log),this.smallVideoContext.on(Fe.UNAVAILABLE,r=>{this.log.warn("small video context lost",r)})}if(this.smallVideoContext.frameRate=e.frameRate,this.smallDestination.resolution=e,t)this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=t:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(t),this.smallImageSource.resize(t.width,t.height),this.smallImageSource.connect(this.smallDestination));else if(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource)this.smallTrackSource.replaceTrack(this.initialTrack);else{this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack,"smallTrackSource");let{width:r,height:s}=this.cameraTrack.settings;this.smallTrackSource.resize(r,s),this.smallTrackSource.connect(this.smallDestination)}}else this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource)}_setMainOutput(e){var t;try{let r=this.cameraTrack,{small:s,player:n}=r;Ft&&n.setCanvas(e);let a=e&&((t=this.destination)==null?void 0:t.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),a=this.arTrack),this.log.info(`set main output ${a?a.label:"no output track"}`),this.setSmallVideo(s,e),r.setOutputMediaStreamTrack(a)}catch(r){this.log.error("set main output failed",r)}}update(e=!1){return f(this,null,function*(){var s;if(!this.cameraTrack||!this.initialTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:t,profile:r}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams)this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log}),this.destination.on(Ue.RENDER,n=>{var a;(a=this.cameraTrack)==null||a.emit("render",n)})),et===16?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof Gt?(this.cameraNode.close(),delete this.cameraNode):this.cameraNode.image=this.initialTrack.canvas),this.cameraNode||(this.cameraNode=this.videoContext.createVideoImageSource(this.initialTrack.canvas,{name:"cameraCanvasSource",logger:this.log}))):(this.cameraNode&&(this.cameraNode instanceof Gt?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode.close(),delete this.cameraNode)),this.cameraNode||(this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraTrackSource"))):this.cameraNode?this.cameraNode.replaceTrack(this.initialTrack):this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraNodeSource"),this.cameraNode.resize(t.width,t.height);else if(e&&this.cameraNode&&this.destination)this.cameraNode.replaceTrack(this.initialTrack);else{this.cameraNode&&this.cameraNode.close(),this.destination?this.destination.disableCheckMute():(this.destination=new Yc(this.videoContext,{name:"mainDestination",logger:this.log}),this.destination.on(Ue.RENDER,l=>{var u;(u=this.cameraTrack)==null||u.emit("render",l)}));let{width:n,height:a}=this.cameraResolution,c=yield this.getWatermarkImage(n,a);this._waterMarkOption={x:0,y:0,width:c.width,height:c.height,image:c},this.cameraNode=new Md(this.videoContext,{input:this.initialTrack,width:n,height:a,mirror:this._isMirror,rotation:this._rotation,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,beautyParams:this._beautyParams,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,Wasm:this.Wasm,enableFaceCentering:this._enableFaceCentering,enableEffectOptimization:this._enableEffectOptimization,onAbort:this.onAbort,mat4:this._mat4,postProcessing:this._postProcessing,color:this._color}),this.cameraNode.connect(this.destination),this.destination.enableCheckMute(),yield this.cameraNode.predictReady}if(this.videoContext.frameRate=r.frameRate,this._use2d){let n=this.cameraNode;if(n.disconnect(),this._isTransform&&(this.transformNode?(this.transformNode.mirror=this._isMirror,this.transformNode.rotation=this._rotation):this.transformNode=new Jt(this.videoContext,this.log,this._isMirror,this._rotation),n=n.connect(this.transformNode),n.disconnect(),this.log.info(`start mirror ${this._isMirror} rotate ${this.rotation}`)),this.mixNode&&this.mixNode.close(),delete this.mixNode,this._isMixScreen||this._hasWaterMark){if(this.mixNode=new gs(this.videoContext,this.log),n.connect(this.mixNode,{zIndex:1}),this._hasWaterMark&&!this.waterMarkNode&&this._waterMarkOption)this.waterMarkNode=this.videoContext.createVideoImageSource(this._waterMarkOption.image,{autoResize:!1,logger:this.log}),this.waterMarkNode.resize(this._waterMarkOption.width,this._waterMarkOption.height),this.waterMarkNode.x=this._waterMarkOption.x,this.waterMarkNode.y=this._waterMarkOption.y;else if(this.waterMarkNode){let{width:c,height:l}=this.cameraResolution;this.waterMarkNode.image=yield this.getWatermarkImage(c,l),c&&l&&this.waterMarkNode.resize(c,l)}(s=this.waterMarkNode)==null||s.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&(this.screenNode||(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource"),this.screenNode.resize(this.screenTrack.settings.width,this.screenTrack.settings.height)),this.screenNode.shouldUpdate=!1,this.screenNode.connect(this.mixNode,{zIndex:0})),n=this.mixNode,this.log.info("start mix",`${this.mixNode.width}x${this.mixNode.height}`)}n.connect(this.destination)}return this.log.info(`update ${this._use2d?"2d":"webgl"}`),this._setMainOutput(this.videoContext.canvas)})}clearLastFrame(){var e;this.destination&&((e=this.destination.ctx2d)==null||e.clearRect(0,0,this.destination.width,this.destination.height))}changeInput(e){var t,r,s,n,a;if(e instanceof Pt)return this.log.info("change screen input",(t=e.mediaTrack)==null?void 0:t.label),this.setScreenTrack(e);if(e instanceof Xe)return this.log.info("change video input",(r=e.mediaTrack)==null?void 0:r.label),this.setCameraTrack(e);if(e instanceof ki){this.log.info("change remote input",(s=e.mediaTrack)==null?void 0:s.label);let c=e.mediaTrack;return e.setOutputMediaStreamTrack(c)}if(e instanceof go)return this.log.info("change mix input",(n=e.outMediaTrack)==null?void 0:n.label),this.setMixTrack(e);this.log.warn("change unknown input",(a=e.mediaTrack)==null?void 0:a.label)}removeInput(e){var t;e instanceof Pt?((t=this.screenNode)==null||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof Xe?this._isMixScreen?(delete this.cameraNode,this.cameraTrack._inputTrack=null,this.update()):(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof ki?e.source&&e.source.context.destroy():e instanceof go&&(delete this.mixTrack,this.update())}setMixTrack(e){this.mixTrack=e}setCameraTrack(e){return this.cameraTrack=e,this.update(!0)}setScreenTrack(e){return f(this,null,function*(){return this.screenTrack=e,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):yield this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)})}getWatermarkImage(e,t){return f(this,null,function*(){let r=document.createElement("canvas");t&&e&&(r.height=t,r.width=e);let s=r.getContext("2d");if(!s)throw new D({code:I.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort((n,a)=>n.zIndex-a.zIndex),this.watermarkImageList.forEach(({image:n,x:a,y:c,width:l,height:u,fillVideo:h})=>{let m=h&&e||l,_=h&&t||u,g=h?0:a,E=h?0:c;s.drawImage(n,g,E,m,_)}),Ho(r.toDataURL())})}pushWaterMarkImageList(e){let{type:t}=e;this.watermarkImageList.some(s=>s.imageUrl===e.imageUrl&&s.height===e.height&&s.width===e.width&&s.x===e.x&&s.y===e.y&&s.type===e.type&&s.zIndex===e.zIndex&&s.fillVideo===e.fillVideo)||((t==="mute"||t==="watermark")&&(this.watermarkImageList=this.watermarkImageList.filter(s=>s.type!==t)),this.watermarkImageList.push(e))}setBeautyParams(e){return f(this,null,function*(){this._beautyParams=e,this.update()})}stopBeauty(){return f(this,null,function*(){this._beautyParams=void 0,this.update()})}setWatermark(e){return f(this,null,function*(){let t;try{t=yield Ho((e==null?void 0:e.imageElement)||e.imageUrl)}catch(m){throw new D({code:I.INVALID_PARAMETER,message:`load image failed, url: ${e.imageUrl}`})}let{x:r=0,y:s=0,width:n=t.width,height:a=t.height,type:c="watermark",zIndex:l=2,fillVideo:u=!1}=e;this.watermarkImageList.some(m=>m.type===c)?(this.watermarkImageList=this.watermarkImageList.filter(m=>m.type!==c),this.pushWaterMarkImageList({x:r,y:s,width:n,height:a,image:t,zIndex:l,type:c,imageUrl:e.imageUrl,fillVideo:u}),t=yield this.getWatermarkImage(this.cameraResolution.width,this.cameraResolution.height),this._waterMarkOption={x:0,y:0,width:t.width,height:t.height,image:t},this.waterMarkNode?(this.waterMarkNode.x=0,this.waterMarkNode.y=0,this.waterMarkNode.resize(t.width,t.height),this.waterMarkNode.image=t):this.update()):(this.pushWaterMarkImageList({x:r,y:s,width:n,height:a,image:t,zIndex:l,type:c,imageUrl:e.imageUrl,fillVideo:u}),yield this.freshWatermark()),this.log.info("set watermark",JSON.stringify(this.watermarkImageList,(m,_)=>m==="imageUrl"?void 0:_))})}deleteWatermark(e="watermark"){return f(this,null,function*(){this.watermarkImageList=this.watermarkImageList.filter(t=>t.type!==e),this.log.info("delete watermark",e,JSON.stringify(this.watermarkImageList,(t,r)=>t==="imageUrl"?void 0:r)),yield this.freshWatermark()})}freshWatermark(){return f(this,null,function*(){var s;(s=this.waterMarkNode)==null||s.close(),delete this.waterMarkNode,delete this._waterMarkOption;let{width:e,height:t}=this.cameraResolution,r=yield this.getWatermarkImage(e,t);this._waterMarkOption={x:0,y:0,width:r.width,height:r.height,image:r},this.update()})}setVirtualBackground(e){return f(this,null,function*(){var t,r,s;if(!e)delete this._virtualBackground,delete this._virtualBackgroundAbortCallback;else{if(e.onAbort&&(this._virtualBackgroundAbortCallback=e.onAbort),this._use2d&&!this._autoSwitchRenderMode)return Promise.reject(new Error("not support virtual background in 2d mode"));this._bgAssetPath=e.assetPath,e.type==="image"?this._virtualBackground=yield Ho(e.imageUrl):(this.blurRadius=e.blurLevel||this.blurRadius||3,this._virtualBackground=e.type),this._enableFaceCentering=(t=e.enableFaceCentering)!=null?t:this._enableFaceCentering,this._enableEffectOptimization=(r=e.enableEffectOptimization)!=null?r:this._enableEffectOptimization,this._color=(s=e.color)!=null?s:[0,1,0]}if(this.log.info(`${this._virtualBackground?"start":"stop"} virtual background, ${(e==null?void 0:e.type)||""}, ${this.blurRadius||""}`),yield this.update(),this._virtualBackground&&!this._glVideoContext.available)throw new D({code:I.INVALID_OPERATION,message:`webgl context create failed, ${this._glVideoContext.error}`})})}get mixScreen(){return this._isMixScreen}set mixScreen(e){var t;this._isMixScreen=e,this._isMixScreen||((t=this.screenNode)==null||t.close(),delete this.screenNode),this.update()}set mirror(e){var t;this._isMirror!==e&&(this._isMirror=e,this._isTransform||((t=this.transformNode)==null||t.close(),delete this.transformNode),this.update())}get mirror(){return this._isMirror}set rotation(e){var t;this._rotation!==e&&(this._rotation=e,this._isTransform||((t=this.transformNode)==null||t.close(),delete this.transformNode),this.update())}get rotation(){return this._rotation}enableAr(e){this.arTrack=e,this.isUsingArTrack=!0,this.update()}updateAr(){return f(this,null,function*(){var e;(e=this.cameraTrack)!=null&&e.mediaTrack&&(yield this.virtualBackgroundInstance.ar.updateInputTrack(this.cameraTrack.mediaTrack.clone()))})}disableAr(){var e;this.isUsingArTrack=!1,(e=this.arTrack)==null||e.stop(),this.arTrack=void 0,this.update()}createDecodeContext(e){return new Pd(e)}clear(){var e,t;(e=this.videoContext)==null||e.disconnect(),(t=this.destination)==null||t.removeAllListeners(),delete this.destination,delete this.cameraNode,delete this.transformNode,delete this.screenNode,delete this.waterMarkNode}addEncodeProcessor({processor:e,type:t}){var r;this.encodePipeline.includes(e)||(this.encodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}addDecodeProcessor({processor:e,type:t}){var r;this.decodePipeline.includes(e)||(this.decodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}};O([kc(function(e){this.log.error("update failed",e)}),Y(e=>function(...t){return f(this,null,function*(){this._updateFlag||(this._updateFlag=!0,yield C_,this.updated=new Promise((r,s)=>{e.apply(this,t).then(r,s),setTimeout(s,5e3,new D({code:I.API_CALL_TIMEOUT,message:"update timeout"}))}),this._updateFlag=!1,yield this.updated)})})],sa.prototype,"update",1);var TI=0;var wd=class extends q{constructor(e){super("room");d(this,"seq",++TI);d(this,"sdkAppId");d(this,"userId");d(this,"userSig");d(this,"privateMapKey");d(this,"latencyLevel");d(this,"tinyId");d(this,"scene");d(this,"roomId");d(this,"useStringRoomId");d(this,"role","anchor");d(this,"joinParams",null);d(this,"localPublishFlag",0);d(this,"localTracks",new Set);d(this,"enableAutoPlayDialog",!0);d(this,"autoReceiveAudio",!0);d(this,"autoReceiveVideo",!0);d(this,"proxy_ws");d(this,"proxy_wt");d(this,"proxy_unified");d(this,"checkSystemResult",{result:!0,detail:{isBrowserSupported:!0,isWebRTCSupported:!0,isWebCodecsSupported:!0,isMediaDevicesSupported:!0,isScreenShareSupported:!0,isSmallStreamSupported:!0,isH264EncodeSupported:!0,isVp8EncodeSupported:!0,isH264DecodeSupported:!0,isVp8DecodeSupported:!0,isH265EncodeSupported:!0,isH265DecodeSupported:!0}});d(this,"keyPointManager");d(this,"audioManager");d(this,"videoManager");d(this,"callDurationCalculator");d(this,"badCaseDetector");d(this,"scheduleResult",{domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null});d(this,"videoDecodeFallbackType");d(this,"smallMode","canvas");d(this,"enableChorus",!1);d(this,"_isUsingCachedSchedule",!1);d(this,"_log");d(this,"_joinedTimestamp",0);d(this,"_sdkType");d(this,"heartbeatReport");d(this,"heartbeatCount",0);d(this,"quality");d(this,"enableSEI");d(this,"isDestroyed",!1);this._log=R.createLogger({parent:e.logger,id:`r${this.seq}`}),this.useStringRoomId=!!e.useStringRoomId,me(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),me(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),me(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new E_({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new S_({room:this}),this.badCaseDetector=new I_({room:this}),this.audioManager=new td(this),this.videoManager=new sa(this)}get videoCodec(){return"h264"}get scriptTransformWorker(){}get isMainStreamPublished(){for(let e of this.localTracks)if(e.mediaType&4)return!0;return!1}get isAuxStreamPublished(){for(let e of this.localTracks)if(e.mediaType&2)return!0;return!1}get hasAuxStream(){for(let e of this.remotePublishedUserMap.values())if(e.muteState.hasAuxiliary)return!0;return this.isAuxStreamPublished}get localMainAudioTrack(){for(let e of this.localTracks)if(e.mediaType&1)return e;return null}get localMainVideoTrack(){for(let e of this.localTracks)if(e.mediaType&4)return e;return null}get localAuxVideoTrack(){for(let e of this.localTracks)if(e.mediaType&2)return e;return null}get publishState(){let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};return this.localTracks.forEach(t=>{if(t.isPublished||t.isPublishing)switch(t.mediaType){case 1:e.audio=!0;break;case 4:e.bigVideo=!0,e.smallVideo=t.hasSmall;break;case 2:e.auxVideo=!0;default:break}}),e}get muteState(){var e,t,r;return{audio:!!((e=this.localMainAudioTrack)!=null&&e.muted),bigVideo:!!((t=this.localMainVideoTrack)!=null&&t.muted),auxVideo:!!((r=this.localAuxVideoTrack)!=null&&r.muted)}}getLogger(){return this._log}get isJoining(){return this.state.toString()==="joining"}get isJoined(){return this.state==="joined"}get isLeft(){return this.state==="left"}addTrack(e){return f(this,null,function*(){return this.publish(e)})}removeTrack(e){return f(this,null,function*(){return this.unpublish(e)})}replaceTrack(e){return f(this,null,function*(){})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(ie(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(dt(e)){let{websocketProxy:t,webtransportProxy:r,loggerProxy:s,scheduleProxy:n,unifiedProxy:a}=e;this.proxy_ws=t,this.proxy_wt=r,this.proxy_unified=a,a?(dd([a,a]),Br(`https://${a}`)):(s&&Br(s),n&&dd(n))}S.once(A.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:wi.main,sched_back_domain:wi.backup,signal_domain:this.proxy_ws||this.proxy_wt||""}))}getRemoteAudioStats(){return f(this,null,function*(){let e={};return this.remotePublishedUserMap.forEach(t=>{e[t.userId]=t.remoteAudioTrack.stat}),e})}getTransportStats(){return f(this,null,function*(){var t;let e={rtt:((t=this.quality)==null?void 0:t.uplinkRTT)||0,downlinksRTT:{}};if(this.quality)for(let r of this.quality.downlinkInfo)e.downlinksRTT[r.userId]=r.rtt;return e})}getRemoteVideoStats(){return f(this,arguments,function*(e="main"){let t={};return this.remotePublishedUserMap.forEach(r=>{let s=e==="auxiliary"?r.remoteAuxiliaryTrack:r.remoteVideoTrack;t[r.userId]=s.stat}),t})}checkDestroy(){if(this.isDestroyed)throw new D({code:I.INVALID_OPERATION,message:H({key:B.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(je.INVALID_DESTROY),new D({code:I.INVALID_OPERATION,message:H({key:B.INVALID_DESTROY})});this._log.info("destroy room"),this.audioManager.destroy(),this.videoManager.destroy(),this.keyPointManager.destroy(),this.callDurationCalculator.destroy(),this.badCaseDetector.destroy(),this.isDestroyed=!0,S.emit(A.ROOM_DESTROY,{room:this})}schedule(e,t){return f(this,null,function*(){var s,n,a,c;let r=U();try{let{isCached:l,result:u,detailCost:h}=yield bh({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:$e,userSig:this.userSig,role:this.scene==="live"?e.role:void 0,frameWorkType:t,latencyLevel:e.latencyLevel});this._isUsingCachedSchedule=l,this._log.info(`schedule cache:${+l} ${_t(u,{keysToExclude:["username","credential"]})}`),l&&S.once(A.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=M(M({},this.scheduleResult),u),Q((s=u.config)==null?void 0:s.retryCount)&&el(u.config.retryCount),ie((n=u.config)==null?void 0:n.loggerDomain)&&Br(u.config.loggerDomain),this.videoDecodeFallbackType=((a=u.config)==null?void 0:a.videoDecodeFallback)||this.videoDecodeFallbackType,this.smallMode=((c=u.config)==null?void 0:c.smallMode)||this.smallMode,S.emit(A.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:h}),v.addSuccessEvent({key:521700,cost:U()-r})}catch(l){throw v.addFailedEvent({key:521700,error:l}),l}})}sendAbilityStatus(e){}enableInsertableStreams(){return Promise.resolve()}switchRoom(e){return Promise.reject()}isSwitchRoomSupported(){return!1}};var x_=Je(at());var am=Je(Zh());var y_=o=>{let i=Ne(o),e={audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0};return i.media.forEach((t,r)=>{var s;if(t.ssrcs&&!T(t.ssrcs[0].id)){let n=Number(t.ssrcs[0].id),a=Number((s=t.ssrcs.filter(c=>c.attribute==="cname")[1])==null?void 0:s.id);switch(r){case 0:e.audioSsrc=n;break;case 1:e.bigVideoSsrc=n,e.bigVideoRtxSsrc=a;break;case 2:e.smallVideoSsrc=n,e.smallVideoRtxSsrc=a;break;case 3:e.auxVideoSsrc=n,e.auxVideoRtxSsrc=a;break}}}),e};function b_(o){var e;let i=[];for(let t=0;t<o.rtp.length;t++){if(["rtx","red","ulpfec"].includes(o.rtp[t].codec))continue;let r=o.fmtp.filter(s=>s.payload===o.rtp[t].payload)[0];i.push({payload:o.rtp[t].payload,codec:o.rtp[t].codec,fmtp:r?r.config:"",rate:o.rtp[t].rate,rtx:((e=o.rtp[t+1])==null?void 0:e.codec)==="rtx"?o.rtp[t+1].payload:0,rtcpfb:((o==null?void 0:o.rtcpFb)||[]).filter(s=>s.payload===o.rtp[t].payload).map(({type:s,subtype:n})=>({id:s,params:n?[n]:[]}))})}return i}function EI(){return f(this,null,function*(){let o=new RTCPeerConnection;o.addTransceiver(p.VIDEO,{direction:p.TRANSCEIVER_DIRECTION_RECVONLY});let i=yield o.createOffer();if(!i.sdp)return[];let e=Ne(i.sdp),t=b_(e.media[0]);return o.close(),t})}var v_=(o,i)=>f(void 0,null,function*(){var a;let e=Ne(o),t={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],decoders:[],extensions:[]},useDataChannel:!1};t.ice.ufrag=String(e.media[0].iceUfrag),t.ice.password=e.media[0].icePwd||"",e.fingerprint&&(t.dtls.hash=e.fingerprint.type,t.dtls.fingerprint=e.fingerprint.hash,t.dtls.setup=e.setup||""),e.media[0].fingerprint&&(t.dtls.hash=e.media[0].fingerprint.type,t.dtls.fingerprint=e.media[0].fingerprint.hash),t.dtls.setup=e.media[0].setup||"";let r=e.media[0],s=e.media[1];r.ext&&(t.audio.extensions=r.ext.map(c=>({id:c.value,uri:c.uri}))),s.ext&&(t.video.extensions=s.ext.map(c=>({id:c.value,uri:c.uri})));for(let c of r.rtp){if(c.codec!=="opus")continue;let l=r.fmtp.find(h=>h.payload===c.payload);if(!l)continue;let u={codec:c.codec,fmtp:l.config,payload:l.payload,rate:c.rate,channels:c.encoding,rtcpfb:[],rtx:0};(a=r.rtcpFb)==null||a.forEach(({payload:h,type:m,subtype:_})=>{if(h===u.payload){let g={id:m,params:[]};_&&g.params.push(_),u.rtcpfb.push(g)}}),t.audio.codecs.push(u);break}let n=["h264","vp8","h265"];return i&&n.shift(),t.video.codecs=[...b_(s)].filter(c=>n.includes(c.codec.toLocaleLowerCase())),t.video.decoders=(yield EI()).filter(c=>["h264","vp8","h265"].includes(c.codec.toLocaleLowerCase())),t}),N_=({serverAbility:o,clientAbility:i,offerSDP:e,enableCustomMessage:t})=>{let r=Ne(e),s={extmapAllowMixed:"extmap-allow-mixed",groups:r.groups,icelite:"ice-lite",media:[],msidSemantic:{semantic:"",token:"WMS"},name:"-",origin:{address:"127.0.0.1",username:"-",sessionId:String(Date.now()),sessionVersion:1,netType:"IN",ipVer:4},timing:{start:0,stop:0},version:0},n={candidates:o.candidates.map(a=>({component:1,foundation:"1",generation:0,ip:a.ip,port:a.port,priority:a.priority,transport:a.foundation,type:a.type})),connection:{version:4,ip:"0.0.0.0"},direction:p.TRANSCEIVER_DIRECTION_RECVONLY,ext:o.audio.extensions.map(a=>({value:a.id,uri:a.uri})),fingerprint:{type:o.dtls.hash,hash:o.dtls.fingerprint},fmtp:[{payload:o.audio.codecs[0].payload,config:o.audio.codecs[0].fmtp}],icePwd:o.ice.password,iceUfrag:o.ice.ufrag,mid:"0",payloads:String(o.audio.codecs[0].payload),port:r.media[0].port,protocol:r.media[0].protocol,type:p.AUDIO,setup:o.dtls.setup,rtcpFb:o.audio.codecs[0].rtcpfb.map(a=>({payload:o.audio.codecs[0].payload,type:a.id,subtype:a.params[0]})),rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[{payload:o.audio.codecs[0].payload,codec:o.audio.codecs[0].codec,rate:o.audio.codecs[0].rate,encoding:o.audio.codecs[0].channels}]};return s.media.push(n),[1,2,3].forEach(a=>{s.media.push(cm({mid:a,serverAbility:o,clientAbility:i,parsedOffer:r}))}),t&&s.media.push(r.media.find(a=>a.mid==="dc")),jt(s)},cm=({mid:o,serverAbility:i,clientAbility:e,parsedOffer:t,isDownlink:r=!1})=>{let s={candidates:i.candidates.map(n=>({component:1,foundation:"1",generation:0,ip:n.ip,port:n.port,priority:n.priority,transport:n.foundation,type:n.type})),connection:{version:4,ip:"0.0.0.0"},direction:p.TRANSCEIVER_DIRECTION_RECVONLY,ext:i.video.extensions.map(n=>({value:n.id,uri:n.uri})),fingerprint:{type:i.dtls.hash,hash:i.dtls.fingerprint},fmtp:[],icePwd:i.ice.password,iceUfrag:i.ice.ufrag,mid:String(o),payloads:"",port:t.media[0].port,protocol:t.media[0].protocol,type:p.VIDEO,setup:i.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(r){let n=i.video.decoders;(!n||n.length===0)&&(n=i.video.codecs),(!n||n.length===0)&&(n=e.video.decoders),n.forEach(a=>{Vr(s,a)})}else{let n;i.useH265?n=i.video.codecs.findIndex(c=>c.codec.toLowerCase()==="h265"):n=i.video.codecs.findIndex(c=>c.codec.toLowerCase()===(i.useVp8?"vp8":"h264"));let a=i.video.codecs[n]||e.video.codecs[0];Vr(s,a)}return s},Vr=(o,i)=>{o.payloads=`${o.payloads} ${i.payload}`.trim(),o.fmtp.push({payload:i.payload,config:i.fmtp}),o.rtcpFb=[...o.rtcpFb||[],...i.rtcpfb.map(e=>({payload:i.payload,type:e.id,subtype:e.params[0]}))],o.rtp.push({payload:i.payload,codec:i.codec.toUpperCase(),rate:i.rate}),i.rtx&&(o.payloads=`${o.payloads} ${i.rtx}`,o.fmtp.push({payload:i.rtx,config:`apt=${i.payload}`}),o.rtp.push({payload:i.rtx,codec:"rtx",rate:i.rate}))};function SI(o){let i=new Set(["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"]);o.ext&&(o.ext=o.ext.filter(e=>!i.has(e.uri)))}function II(o){if(!o.rtcpFb)return;let i=[];o.rtcpFb.forEach((e,t)=>{var r;i.push(e),o.rtcpFb&&((r=o.rtcpFb[t+1])==null?void 0:r.payload)!==e.payload&&e.type!=="rrtr"&&i.push({payload:e.payload,type:"rrtr"})}),o.rtcpFb=i}function AI(o){o.type===p.VIDEO&&o.fmtp&&o.fmtp.forEach(i=>{i.config.includes("apt")||(i.config+=";sps-pps-idr-in-keyframe=1")})}function CI(o){o.type===p.AUDIO&&o.fmtp&&o.fmtp.forEach(i=>{i.config+=";sprop-stereo=1;stereo=1"})}var D_=(o,i,e)=>{let t=am.default.parse(o);return t.media.forEach((r,s)=>{var n;if((r.type===p.AUDIO||r.type===p.VIDEO)&&(II(r),AI(r),CI(r),SI(r),r.type===p.VIDEO)){if(s<4)r.payloads="",r.fmtp=[],r.rtp=[],r.rtcpFb=[],i.video.codecs.forEach(a=>Vr(r,a));else if(e){r.payloads="",r.fmtp=[],r.rtp=[],r.rtcpFb=[];let a=e.video.decoders;(!a||a.length===0)&&(a=e.video.codecs),(!a||a.length===0)&&(a=i.video.decoders),a.forEach(c=>Vr(r,c))}}(n=r.payloads)!=null&&n.includes("datachannel")&&t.groups&&r.mid&&(t.groups[0].mids=t.groups[0].mids.replace(r.mid,"dc"),r.mid="dc")}),am.default.write(t)};var O_=Je(at());var Ld=class extends O_.EventEmitter{constructor(e){super();this.room=e;d(this,"mainFpsHealth",1);d(this,"mainBitrateHealth",1);d(this,"badMainBitrateHealthCount",0);d(this,"lastEmitBadHealthTime",0);d(this,"log");!_e&&We&&S.on("262",this.onVideoCodecChanged,this),this.log=e.getLogger().createChild({id:"h-d"})}onVideoCodecChanged({remoteUserId:e,streamType:t,isHWCodec:r,codec:s}){if(!(e||t===7||s!=="h264")){if(!r){this.room.off("heartbeat-report",this.onHeartbeatReport,this);return}this.room.listeners("heartbeat-report").includes(this.onHeartbeatReport)||this.room.on("heartbeat-report",this.onHeartbeatReport,this)}}onHeartbeatReport(e){Date.now()-this.lastEmitBadHealthTime<30*1e3||(e.msg_up_stream_info.msg_video_status.forEach(t=>{if(t.uint32_video_enc_fps&&t.uint32_video_capture_fps){let r=t.uint32_video_enc_fps/t.uint32_video_capture_fps;t.uint32_video_stream_type===2&&(this.mainFpsHealth=r)}if(t.uint32_video_codec_bitrate&&t.uint32_video_stream_type===2){let{localMainVideoTrack:r}=this.room;r&&(this.mainBitrateHealth=t.uint32_video_codec_bitrate/1e3/r.profile.bitrate)}}),this.log.debug(`mainBitrateHealth: ${this.mainBitrateHealth} mainFpsHealth: ${this.mainFpsHealth}`),this.mainBitrateHealth>.5&&(this.badMainBitrateHealthCount=0),this.mainFpsHealth>.9&&this.mainBitrateHealth<.5&&(this.badMainBitrateHealthCount++,this.badMainBitrateHealthCount>3&&(this.badMainBitrateHealthCount=0,this.lastEmitBadHealthTime=Date.now(),this.log.warn(`bad main bitrate health: ${this.mainBitrateHealth} fps health: ${this.mainFpsHealth}`),this.emit("1",{isAux:!1}))))}destroy(){S.off("262",this.onVideoCodecChanged,this),this.room.off("heartbeat-report",this.onHeartbeatReport,this)}};d(Ld,"EVENT_BAD_HEALTH","bad_health");var M_=Ld;function k_({seiMessageList:o,isAudio:i,getNtpTime:e,isMain:t}){return new TransformStream({transform(r,s){let n=r;i?audioEncodePipeline.forEach(a=>{n=a({frame:n,ntp:e()})}):videoEncodePipeline.forEach(a=>{n=a({frame:n,seiMessageList:o,onDump:()=>{self.postMessage({type:"dump",isAudio:i,data:n.data,userId:"",streamType:t?"main":"auxiliary"})}})}),s.enqueue(n)}})}function P_({userId:o,streamType:i,isAudio:e}){return new TransformStream({transform(t,r){let s=t;e?(audioDecodePipeline.forEach(n=>{s=n({frame:s,onAudioFrameNTPTime:a=>{self.postMessage({type:"audio-ntp",data:a,userId:o,streamType:i})},onDump:()=>{self.postMessage({type:"dump",isAudio:e,data:s.data,userId:o,streamType:i})}})}),r.enqueue(s)):videoDecodePipeline.forEach(n=>{s=n({frame:s,onSEI:a=>{a.forEach(c=>{self.postMessage({type:"sei",seiPayloadType:c.seiPayloadType,data:c.seiPayload.buffer,userId:o,streamType:i})})}})}),r.enqueue(s)}})}function w_(o){let i=[sr],e=[Vh,xh,Uh,Lh,k_,P_,Pa,ka],t=()=>{let l=[],u=[],h=[],m=0;self.onmessage=_=>{switch(_.data.type){case"sei":_.data.isMain?(l.push(_.data.data),_.data.small&&h.push(_.data.data)):u.push(_.data.data);break;case"ntp-offset":m=_.data.data;break}},self.onrtctransform=_=>{let{options:g}=_.transformer,E=g.isReceiver?P_({userId:g.userId,streamType:g.streamType,isAudio:g.isAudio}):k_({getNtpTime:()=>Date.now()+m,isAudio:g.isAudio,isMain:g.isMain,seiMessageList:g.isMain?g.small?h:l:u});_.transformer.readable.pipeThrough(E).pipeTo(_.transformer.writable)}},r=`const videoEncodePipeline=[${o.videoEncodePipeline.toString()}];
|
|
112
|
+
const videoDecodePipeline=[${o.videoDecodePipeline.toString()}];
|
|
113
|
+
const audioEncodePipeline = [${o.audioEncodePipeline.toString()}];
|
|
114
|
+
const audioDecodePipeline = [${o.audioDecodePipeline.toString()}];`,s=`(()=>{${i.map(l=>`const ${l.name}=(()=>${l.toString()})()`).join(`
|
|
115
|
+
`)}
|
|
116
|
+
${e.map(l=>l.toString()).join(`
|
|
117
|
+
`)};(${t})();${r}})()`,n=new Blob([s],{type:"text/javascript"}),a=URL.createObjectURL(n),c=new Worker(a);return URL.revokeObjectURL(a),c}var xi=(l=>(l.TRACK="track",l.DATA_CHANNEL_MESSAGE="data_channel_msg",l[l.CONNECTION_STATE_CHANGED="connection-state-changed"]="CONNECTION_STATE_CHANGED",l[l.FIREWALL_RESTRICTION="firewall-restriction"]="FIREWALL_RESTRICTION",l.RECONNECTED="spc-reconnected",l.RECONNECT_FAILED="spc-reconnect-failed",l.ERROR="error",l.SEI_MESSAGE="sei-message",l.DUMP="dump",l))(xi||{}),U_=0,V_=!1,RI=new Set,yI=o=>U_>2&&!V_&&RI.size===0&&o,bI=1,Xt=class extends x_.default{constructor({signalChannel:e,room:t,enableCustomMessage:r}){super();d(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0});d(this,"isDestroyed",!1);d(this,"currentState","DISCONNECTED");d(this,"_room");d(this,"_signalChannel");d(this,"_peerConnection",null);d(this,"_datachannel",null);d(this,"_enableCustomMessage");d(this,"_log");d(this,"_downlinkMIDMap",new Map);d(this,"_downlinkMIDUserIDMap",new Map);d(this,"_reconnectionTimer",-1);d(this,"reconnectionCount",0);d(this,"clientAbility");d(this,"_serverAbility",null);d(this,"addDownlinkQueue",new Set);d(this,"removeDownlinkQueue",new Set);d(this,"_parsedAnswer",null);d(this,"_updateSDPPromise",null);d(this,"_waitForPCConnectedPromise");d(this,"clearWaitForConnectedPromise");d(this,"clearConnectTimeout");d(this,"_isSDPLogged",!1);d(this,"enableInsertableStreams",!1);d(this,"insertableStreamsAbortMap",new Map);d(this,"receiverRemoteTrackMap",new WeakMap);d(this,"scriptTransformWorker");d(this,"_isRelayTried",!1);d(this,"_rttOverCount",0);d(this,"originOffer",null);d(this,"autoSubscribedSsrcGroups",new Map);d(this,"autoSubscribedUserMap",new Map);d(this,"_h265DecodeFailed",!1);this._room=t,this._enableCustomMessage=r,this._signalChannel=e,this._log=R.createLogger({parent:this._room.getLogger(),id:`spc${bI++}`,userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableCodecPipeline&&(mi?this.enableInsertableStreams=!0:this.initScriptTransformWorker()),this._room.healthDetector.on("1",this.onBadHealth,this)}get isH264EncodeSupported(){let e=this._room.checkSystemResult.detail.isH264EncodeSupported;return this._serverAbility&&(e=e&&!!this._serverAbility.video.codecs.find(t=>t.codec.toLowerCase()==="h264")),e}addAbortController(e,t){var r;(r=this.insertableStreamsAbortMap.get(e))==null||r.abort("destroy"),this.insertableStreamsAbortMap.set(e,t)}get isVP8EncodeSupported(){let e=this._room.checkSystemResult.detail.isVp8EncodeSupported;return this._serverAbility&&(e=e&&this._serverAbility.video.codecs.find(t=>t.codec.toLowerCase()==="vp8")),e}get isH265EncodeSupported(){let e=this._room.checkSystemResult.detail.isH265EncodeSupported;return this._serverAbility&&(e=e&&!!this._serverAbility.video.codecs.find(t=>t.codec.toLowerCase()==="h265")),e}get videoCodec(){var t,r,s;let e=(t=this._parsedAnswer)==null?void 0:t.media[1].rtp.find(n=>["h264","vp8","h265"].includes(n.codec.toLowerCase()));return e?e.codec.toLowerCase():(r=this._serverAbility)!=null&&r.useH265?"h265":(s=this._serverAbility)!=null&&s.useVp8?"vp8":"h264"}get downlinkVideoCodec(){var e,t,r;return(e=this._serverAbility)!=null&&e.useH265&&((t=this._serverAbility)!=null&&t.video.decoders.find(s=>s.codec.toLowerCase()==="h265"))&&!this._h265DecodeFailed?"h265":(r=this._serverAbility)!=null&&r.video.decoders.find(s=>s.codec.toLowerCase()==="h264")?"h264":"vp8"}get isUsingH264(){return this.videoCodec==="h264"}get isUsingH265(){return this.videoCodec==="h265"}get isUsingVP8(){return this.videoCodec==="vp8"}get is42001fSupported(){return this.clientAbility?!!this.clientAbility.video.codecs.find(e=>e.fmtp.includes("42001f")):!1}get uplinkSSRC(){return this._peerConnection&&this._peerConnection.localDescription?y_(this._peerConnection.localDescription.sdp):{audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0}}onBadHealth({isAux:e}){}initScriptTransformWorker(){ns&&(this.scriptTransformWorker=w_({videoEncodePipeline:this._room.videoManager.encodePipeline,videoDecodePipeline:this._room.videoManager.decodePipeline,audioEncodePipeline:this._room.audioManager.encodePipeline,audioDecodePipeline:this._room.audioManager.decodePipeline}),this.scriptTransformWorker.onmessage=e=>{e.data.type==="sei"?this.emit("sei-message",e.data):e.data.type,e.data.type==="dump"&&this.emit("dump",e.data)},this.scriptTransformWorker.onerror=e=>{this._log.error("scriptTransformWorker error: ",e.message)})}get isReconnecting(){return this.currentState==="RECONNECTING"||this._reconnectionTimer>0||this.reconnectionCount>0}get dtlsTransport(){if(!this._peerConnection)return null;let e=this._peerConnection.getSenders();return e.length===0?null:e[0].transport}getPeerConnectionConfig(e){var s;let t={encodedInsertableStreams:this.enableInsertableStreams,offerExtmapAllowMixed:!0,iceServers:e,iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._room.sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"},r=(s=this._peerConnection)==null?void 0:s.getConfiguration().encodedInsertableStreams;return wa(r)&&(t.encodedInsertableStreams=r),this._log.debug("getPeerConnectionConfig",JSON.stringify(t)),t}initialize(e){return f(this,null,function*(){var r;let t;try{return this._peerConnection=new RTCPeerConnection(this.getPeerConnectionConfig(e)),this._peerConnection.oniceconnectionstatechange=()=>{if(!this._peerConnection)return;let s=this._peerConnection.iceConnectionState;this._log.debug(`ice state: ${s}`),s==="checking"&&this.stat.iceStartTime===0?this.stat.iceStartTime=Date.now():s==="connected"&&this.stat.iceEndTime===0?(this.stat.iceEndTime=Date.now(),this._signalChannel.clearBakRelayIps(),v.addSuccessEvent({key:521711,cost:this.stat.iceEndTime-this.stat.iceStartTime})):s==="failed"&&v.addFailedEvent({key:521711})},this._peerConnection.onsignalingstatechange=()=>{var n;let s=((n=this._peerConnection)==null?void 0:n.signalingState)||"";this._log[s==="closed"?"debug":"info"](`signaling state: ${s}`)},this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this._peerConnection.ontrack=s=>this.emit("track",s),this._enableCustomMessage&&(this._datachannel=this._peerConnection.createDataChannel(`${this._room.userId}dc`),this._datachannel.binaryType="arraybuffer",this._datachannel.onopen=()=>{this._log.info("datachannel open")},this._datachannel.onclose=()=>{this._log.warn("datachannel close")},this._datachannel.onmessage=s=>{let n=new lm(s.data);this.emit("data_channel_msg",{data:n})},this._datachannel.onerror=s=>{this._log.warn("datachannel error",s)}),this._peerConnection.addTransceiver(p.AUDIO,{direction:p.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(p.VIDEO,{direction:p.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(p.VIDEO,{direction:p.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(p.VIDEO,{direction:p.TRANSCEIVER_DIRECTION_SENDONLY}),t=yield this._peerConnection.createOffer(),this.clientAbility=yield v_(t.sdp,((r=this._room.scheduleResult.config)==null?void 0:r.remove264FromSDP)||!1),this.originOffer=t,this.dtlsTransport&&(this.dtlsTransport.onstatechange=()=>{let{dtlsTransport:s}=this;s&&(this._log.debug(`dtls state: ${s.state}`),s.state==="connecting"&&this.stat.dtlsStartTime===0?this.stat.dtlsStartTime=Date.now():s.state==="connected"&&this.stat.dtlsEndTime===0&&(this.stat.dtlsEndTime=Date.now()))}),v.addSuccessEvent({key:521707}),this.clientAbility}catch(s){throw v.addFailedEvent({key:521707,error:s}),this._log.error(`initialize failed ${s}
|
|
118
|
+
offer: ${t==null?void 0:t.sdp}`),s}})}setIceServers(e){return f(this,null,function*(){var t;if(!(!this._peerConnection||e.length===0))try{if(this._log.info("setIceServers",JSON.stringify(e,(r,s)=>r==="username"||r==="credential"?"hided":s)),this._peerConnection.setConfiguration(this.getPeerConnectionConfig(e)),(t=this._peerConnection)!=null&&t.localDescription||!this.originOffer){this._log.warn("setIceServers already has localDescription or no origin Offer");return}yield this.setOffer(this.originOffer)}catch(r){this._log.warn("setIceServers error ",r)}})}setPriority(e="high"){if(this._peerConnection)try{this._peerConnection.getSenders().forEach(r=>{let s=r.getParameters();s.encodings[0]&&(s.encodings[0].priority=e,s.encodings[0].networkPriority=e,r.setParameters(s).catch(n=>{this._log.warn("setPriority error ",n)}))})}catch(t){this._log.warn("setPriority error ",t)}}connect(e,t=!1){return f(this,null,function*(){var r,s,n,a;try{if(this.currentState==="CONNECTED")return;!((r=this._peerConnection)!=null&&r.localDescription)&&this.originOffer&&(yield this.setOffer(this.originOffer));let c=U();if(((s=this._room.joinParams)==null?void 0:s.videoProfileLevel)==="high"){let h=this.clientAbility.video.codecs.find(m=>m.fmtp.includes("profile-level-id=64"));if(h){let m=e.video.codecs.findIndex(_=>_.codec.toLowerCase()===h.codec.toLowerCase());e.video.codecs[m]=h,this._log.warn("set new profile level id",h)}}let l={type:"answer",sdp:N_({serverAbility:e,clientAbility:this.clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(l),yield this.waitForPeerConnectionConnected();let u=((n=this._room.scheduleResult.config)==null?void 0:n.priority)||((a=this._room.joinParams)==null?void 0:a.priority)||new URLSearchParams(location.search).get("priority");u&&this.setPriority(u),t||v.addSuccessEvent({key:521703,cost:U()-c})}catch(c){let l=c instanceof D&&c.code===I.API_CALL_ABORTED;throw l||this._log.error(`connect failed: ${c}`,e),this.reset(),!l&&!this.isReconnecting&&!this.isDestroyed&&(v.addFailedEvent({key:521703,error:c}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),c}})}reconnect(){return f(this,null,function*(){if(this._reconnectionTimer!==-1){this._log.warn("reconnect() is reconnecting, ignore current reconnection");return}if(!this._signalChannel.isConnected){this._log.warn("reconnect() wait signal channel is connected"),this._signalChannel.once(Ie.CONNECTED,this.reconnect,this);return}try{this.reconnectionCount+=1,this._log.warn(`reconnect() trying [${this.reconnectionCount}]`),this.reset();let e=this._signalChannel.getBackupRelayIpPair(),t=yield this.initialize(this._room.getIceServers(e!=null&&e.iceServer?[e.iceServer]:[])),r=M({ability:t},e),s=yield this._signalChannel.sendWaitForResponse({command:Z.REBUILD_PEER_CONNECTION,responseCommand:G.REBUILD_PEER_CONNECTION_RES,data:r,enableLog:!1});if(s.data.code!==0)throw new D({code:s.data.code,message:s.data.message});yield this.connect(s.data.data.ability,!0),v.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),S.emit(A.SPC_RECONNECTED,{room:this._room}),this.emit("spc-reconnected")}catch(e){if(!this.isReconnecting||this.isDestroyed)return;if(e!=null&&e.message.includes("timeout")){let t=Kt(this.reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${t/1e3}s`),yield Ke(t,r=>{this._reconnectionTimer=r}),this.clearReconnectionTimer(),yield this.reconnect()}else this._log.error(`reconnect() failed ${e==null?void 0:e.code} ${e}`),v.addFailedEvent({key:521704,error:e}),this.reconnectionCount>=Hi()&&this._log.warn(`SDK has tried reconnect for ${Hi()} times, but all failed, please check your network`),this.stopReconnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.emit("error")}})}getPeerConnection(){return this._peerConnection}startReconnection(){return f(this,null,function*(){this.isReconnecting||(this._log.warn("start reconnect"),this._updateSDPPromise=null,this.emitConnectionStateChangedEvent("RECONNECTING"),yield this.reconnect())})}stopReconnection(){var e;this.isReconnecting&&(this._log.info("stop reconnect"),this.reconnectionCount=0,this.clearReconnectionTimer(),(e=this.clearConnectTimeout)==null||e.call(this),this._signalChannel.off(Ie.CONNECTED,this.reconnect,this),this.currentState==="RECONNECTING"&&this.emitConnectionStateChangedEvent("DISCONNECTED"))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&((e=this._peerConnection)==null?void 0:e.connectionState)===Re.CLOSED&&this.startReconnection()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}onConnectionStateChange(e){var s;let t=((s=this._peerConnection)==null?void 0:s.iceConnectionState)||"closed",r=this.getDTLSTransportState();this._log.info(`connectionState: ${e.target.connectionState} ICE: ${t} DTLS: ${r}`),e.target.connectionState===Re.CONNECTING&&(this.stat.peerConnectionStartTime===0&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(e.target.connectionState===Re.FAILED||e.target.connectionState===Re.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this._room.forceRelay?this.switchRelay(!1):this.startReconnection()),(e.target.connectionState===Re.CONNECTED||e.target.connectionState===Re.COMPLETED)&&(this.stat.peerConnectionEndTime===0&&(this.stat.peerConnectionEndTime=Date.now()),S.emit(A.SINGLE_CONNECTION_STAT,{room:this._room,stat:{ice:this.stat.iceEndTime-this.stat.iceStartTime,dtls:this.stat.dtlsEndTime-this.stat.dtlsStartTime,peerConnection:this.stat.peerConnectionEndTime-this.stat.peerConnectionStartTime}}),this.logSelectedCandidate(),this.emitConnectionStateChangedEvent("CONNECTED"))}getDTLSTransportState(){if(!this._peerConnection)return Yt;let e=null;return!Rr()||this._peerConnection.getSenders().length===0?Yt:(e=this._peerConnection.getSenders()[0].transport,!oo()||this._peerConnection.getReceivers().length===0?Yt:e?e.state:Yt)}emitConnectionStateChangedEvent(e){e!==this.currentState&&(this.currentState==="RECONNECTING"&&e==="CONNECTING"||(this.emit(xi.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:e}),this.currentState=e))}logSelectedCandidate(){return f(this,null,function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[t,r]of e)if(Cr(r)){let s=e.get(r.localCandidateId),n=e.get(r.remoteCandidateId);s&&(this._log.info(`local candidate: ${s.candidateType} ${s.protocol}:${s.ip||s.address}:${s.port} ${s.networkType||""} ${s.relayProtocol?`relayProtocol:${s.relayProtocol} url: ${s.url}`:""}`),s.networkType&&va(s.networkType)),n&&this._log.info(`remote candidate: ${n.candidateType} ${n.protocol}:${n.ip||n.address}:${n.port}`);break}})}waitForPeerConnectionConnected(){return this._waitForPCConnectedPromise?this._waitForPCConnectedPromise:(this._waitForPCConnectedPromise=new Promise((e,t)=>{if(this.currentState==="CONNECTED")return e();let r=c=>{c.state==="CONNECTED"&&(clearTimeout(a),n(),e())},s=({room:c})=>{c===this._room&&(clearTimeout(a),n(),t(new D({code:I.API_CALL_ABORTED,message:H({key:B.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{S.off(A.LEAVE_SUCCESS,s,this),this.off(xi.CONNECTION_STATE_CHANGED,r,this)},a=setTimeout(()=>{n();let c=new D({code:I.API_CALL_TIMEOUT,message:"connection timeout"});U_+=1,yI(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),V_=!0,this.emit(xi.FIREWALL_RESTRICTION)),t(c)},Fs);this.clearConnectTimeout=()=>{n(),clearTimeout(a),delete this.clearConnectTimeout},this.clearWaitForConnectedPromise=()=>{this._waitForPCConnectedPromise=null,t(new D({code:I.API_CALL_TIMEOUT,message:"connection timeout"}))},S.on(A.LEAVE_SUCCESS,s,this),this.on(xi.CONNECTION_STATE_CHANGED,r,this)}),this._waitForPCConnectedPromise=this._waitForPCConnectedPromise.finally(()=>{this._waitForPCConnectedPromise=null,delete this.clearConnectTimeout}),this._waitForPCConnectedPromise)}waitForReconnected(){return this.isReconnecting?new Promise((e,t)=>{this.once("spc-reconnected",e),this.once("error",t)}):Promise.resolve()}addDownlink(e){return f(this,null,function*(){if(this._log.info(`addDownlink(${e.userId}) trying`),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise),this.updateLocalAndRemoteSDPConfig(e),this.addDownlinkQueue.size===0)try{yield this.updateSDP(),this._log.info(`addDownlink(${e.userId}) done`)}catch(t){this._log.error(`addDownlink(${e.userId}) failed ${t}`),yield this.startReconnection()}})}updateLocalAndRemoteSDPConfig({ssrc:e,userId:t,tinyId:r}){if(!this._peerConnection)return;this._log.info(`updateLocalAndRemoteSDPConfig ${t} ${JSON.stringify(e)}`);let s=this._peerConnection.getTransceivers().slice(4).filter(m=>m.direction==="inactive").slice(0,3).map(m=>(m.direction=p.TRANSCEIVER_DIRECTION_RECVONLY,Number(m.mid)));this._parsedAnswer||(this._parsedAnswer=Ne(this._peerConnection.remoteDescription.sdp));let n=this._parsedAnswer.media.filter(m=>{var _;return(_=m.ssrcs)==null?void 0:_.find(g=>{var E;return(E=g.value)==null?void 0:E.includes(r)})}),a,c,l;if(n.length===3)a=n[0],c=n[1],l=n[2];else if(s.length===3)a=this._parsedAnswer.media.find(m=>Number(m.mid)===Number(s[0])),c=this._parsedAnswer.media.find(m=>Number(m.mid)===Number(s[1])),l=this._parsedAnswer.media.find(m=>Number(m.mid)===Number(s[2]));else if(s.length===0){this._peerConnection.addTransceiver(p.AUDIO,{direction:p.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(p.VIDEO,{direction:p.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(p.VIDEO,{direction:p.TRANSCEIVER_DIRECTION_RECVONLY}),a=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let m=cm({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:Ne(this._peerConnection.localDescription.sdp),isDownlink:!0});c=JSON.parse(JSON.stringify(m)),l=JSON.parse(JSON.stringify(m)),a.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(a),c.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(c),l.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(l)}a.direction=p.TRANSCEIVER_DIRECTION_SENDONLY;let u=`${r}-${e.audio}`;a.ssrcs=[{id:e.audio,attribute:"cname",value:`${u}`},{id:e.audio,attribute:"msid",value:`${u}-${p.MAIN} ${u}-audio`}],c.direction=p.TRANSCEIVER_DIRECTION_SENDONLY,c.ssrcs=[{id:e.video,attribute:"cname",value:`${u}`},{id:e.video,attribute:"msid",value:`${u}-${p.MAIN} ${u}-bigvideo`},{id:e.videoRtx,attribute:"cname",value:`${u}`},{id:e.videoRtx,attribute:"msid",value:`${u}-${p.MAIN} ${u}-bigvideo`}],c.ssrcGroups=[{semantics:"FID",ssrcs:`${e.video} ${e.videoRtx}`}],l.direction=p.TRANSCEIVER_DIRECTION_SENDONLY;let h=`${u}-aux`;l.ssrcs=[{id:e.auxiliary,attribute:"cname",value:h},{id:e.auxiliary,attribute:"msid",value:`${h} ${u}-aux${p.VIDEO}`},{id:e.auxiliaryRtx,attribute:"cname",value:`${h} ${u}-aux${p.VIDEO}`},{id:e.auxiliaryRtx,attribute:"msid",value:`${h} ${u}-aux${p.VIDEO}`}],l.ssrcGroups=[{semantics:"FID",ssrcs:`${e.auxiliary} ${e.auxiliaryRtx}`}],this._parsedAnswer.groups&&(this._parsedAnswer.groups[0].mids=this._parsedAnswer.media.map(m=>m.mid).join(" ")),this._downlinkMIDMap.set(t,[a.mid,c.mid,l.mid]),this._downlinkMIDUserIDMap.set(a.mid,t),this._downlinkMIDUserIDMap.set(c.mid,t),this._downlinkMIDUserIDMap.set(l.mid,t)}removeDownlink(e){return f(this,null,function*(){if(!this._downlinkMIDMap.has(e)||!this._peerConnection)return;this._log.info(`removeDownlink(${e}) trying`),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise);let t=this._downlinkMIDMap.get(e),r=!1;this._peerConnection.getTransceivers().forEach(s=>{t!=null&&t.includes(Number(s.mid))&&(r=!0,s.direction="inactive")}),this._parsedAnswer||(this._parsedAnswer=Ne(this._peerConnection.remoteDescription.sdp)),this._parsedAnswer.media.forEach(s=>{t!=null&&t.includes(Number(s.mid))&&(r=!0,s.direction="inactive",s.ssrcs=[],s.ssrcGroups=[])}),this.removeDownlinkQueue.size===0&&r&&(yield this.updateSDP()),this._downlinkMIDMap.delete(e),t==null||t.forEach(s=>this._downlinkMIDUserIDMap.delete(s)),this._log.info(`removeDownlink(${e}) done`)})}setBandwidth(e){return f(this,null,function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:r,smallVideo:s,auxVideo:n}=e;try{if(Tn()){let a=this._peerConnection.getSenders().slice(0,4);for(let l=0;l<a.length;l++){let u=a[l],h;l===0&&t?h=t:l===1&&r?h=r:l===2&&s?h=s:l===3&&n&&(h=n),h&&(yield this.setSenderMaxBitrate(u,h))}let c=!1;r&&a[1].track&&(c=this.setStartBitrate(1,r)),n&&a[3].track&&(c=this.setStartBitrate(3,n)||c),c&&(yield this.updateSDP())}else yield this.setBandwidthBySDP(e);this._log.info(`setBandwidth ${JSON.stringify(e)}`)}catch(a){this._log.error(`failed to set bandwidth: ${a}`)}})}setStartBitrate(e,t){var r,s;return(r=this._peerConnection)!=null&&r.remoteDescription&&(this._parsedAnswer||(this._parsedAnswer=Ne(this._peerConnection.remoteDescription.sdp)),(s=this._parsedAnswer.media[e])!=null&&s.fmtp[0])?(this._parsedAnswer.media[e].fmtp[0].config+=`;x-google-start-bitrate=${t>5e3?5e3:t}`,!0):!1}setSenderMaxBitrate(e,t){let r=e.getParameters();if((!r.encodings||r.encodings.length===0)&&(r.encodings=[{}]),t==="unlimited")delete r.encodings[0].maxBitrate;else{if(r.encodings[0].maxBitrate===t*1e3)return;r.encodings[0].maxBitrate=t*1e3}return e.setParameters(r)}setBandwidthBySDP({audio:e,bigVideo:t,smallVideo:r,auxVideo:s}){if(!this._peerConnection||!this._peerConnection.localDescription)return;let n=Ne(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=Ne(this._peerConnection.remoteDescription.sdp));let a=te?"TIAS":"AS";e&&(n.media[0].bandwidth=[{type:a,limit:te?e*1e3:e}],this._parsedAnswer.media[0].bandwidth=[{type:a,limit:te?e*1e3:e}]),t&&(n.media[1].bandwidth=[{type:a,limit:te?t*1e3:t}],this._parsedAnswer.media[1].bandwidth=[{type:a,limit:te?t*1e3:t}]),r&&(n.media[2].bandwidth=[{type:a,limit:te?r*1e3:r}],this._parsedAnswer.media[2].bandwidth=[{type:a,limit:te?r*1e3:r}]),s&&(n.media[3].bandwidth=[{type:a,limit:te?s*1e3:s}],this._parsedAnswer.media[3].bandwidth=[{type:a,limit:te?s*1e3:s}]);let c={type:"offer",sdp:jt(n)};return this.updateSDP({localDescription:c})}setScaleResolutionDownBy(e,t,r){let s=e.getParameters();(!s.encodings||s.encodings.length===0)&&(s.encodings=[{}]);let n=s.encodings[0].scaleResolutionDownBy;if(T(n)?t===1:t===n)return;let a=`setScaleResolutionDownBy ${r} ${t}`;return n&&(a+=` prevScale: ${n}`),this._log.warn(a),s.encodings[0].scaleResolutionDownBy=t,e.setParameters(s)}setDegradationPreference(e,t,r){if(We&&qe<83||Te&&nn(Tt,"12.1")||te&&qo<138)return;let s=e.getParameters(),n="balanced";if(t==="motion"?n="maintain-framerate":t==="detail"&&(n="maintain-resolution"),s.degradationPreference===n)return;let a=`setDegradationPreference ${r} ${n}`;return this._log.info(a),s.degradationPreference=n,e.setParameters(s).catch(c=>this._log.warn(`${a} failed: ${c}`))}updateSDP({localDescription:e}={}){if(!this._parsedAnswer)return Promise.resolve();let t=jt(this._parsedAnswer);return this._updateSDPPromise=new Promise((r,s)=>f(this,null,function*(){var n,a;try{!e&&this._peerConnection&&(this._log.info("creating offer"),e=yield this._peerConnection.createOffer()),e&&(yield this.setOffer(e)),yield this.setAnswer({type:"answer",sdp:t}),this._updateSDPPromise=null,r()}catch(c){this._log.error(c),!this._isSDPLogged&&this._peerConnection&&(this._log.warn(`current offer: ${this.filterSDPDirection((n=this._peerConnection.localDescription)==null?void 0:n.sdp)}
|
|
119
|
+
next offer: ${this.filterSDPDirection(e==null?void 0:e.sdp)}`),this._log.warn(`current answer: ${this.filterSDPDirection((a=this._peerConnection.remoteDescription)==null?void 0:a.sdp)}
|
|
120
|
+
next answer: ${this.filterSDPDirection(t)}`),this._log.warn(`offer: ${e==null?void 0:e.sdp}`),this._log.warn(`answer: ${t}`),this._log.warn(`transceivers: ${JSON.stringify(this._peerConnection.getTransceivers().map(({mid:l,currentDirection:u,direction:h,stopped:m})=>({mid:l,currentDirection:u,direction:h,stopped:m})))}`),this._log.warn(`parsedAnswer: ${JSON.stringify(this._parsedAnswer)}`),this._isSDPLogged=!0),this._updateSDPPromise=null,s(c)}})),this._updateSDPPromise}setTransceiverDirection(e,t){return f(this,null,function*(){if(!te||!this._peerConnection||!this._parsedAnswer)return;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let r=this._peerConnection.getTransceivers();t.forEach(s=>{r[s].direction!==e&&(r[s].direction=e)});for(let s of t){let n=this._parsedAnswer.media[s].direction;e===se.INACTIVE&&n===se.RECVONLY&&(this._parsedAnswer.media[s].direction=e),e===se.SENDONLY&&n===se.INACTIVE&&(this._parsedAnswer.media[s].direction=se.RECVONLY)}yield this.updateSDP()})}filterSDPDirection(e=""){return Ne(e).media.map(r=>r.direction)}setOffer(e){this._log.info("setting offer");let t=D_(e.sdp,this.clientAbility,this._serverAbility);return this._log.debug(t),this._peerConnection.setLocalDescription({type:"offer",sdp:t})}setAnswer(e){return this._log.info("setting answer"),this._log.debug(e.sdp),this._peerConnection.setRemoteDescription(e)}switchVideoEncoder(e){return f(this,null,function*(){if(e==="h265"&&!this._parsedAnswer&&(this._parsedAnswer=Ne(this._peerConnection.remoteDescription.sdp)),!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let t=!1;this._parsedAnswer.media.forEach(r=>{var s;if(r.type===p.VIDEO){let n=this._serverAbility.video.codecs.find(a=>a.codec.toLowerCase()===e);n&&!((s=r.payloads)!=null&&s.includes(String(n.payload)))&&(r.fmtp=[],r.payloads="",r.rtp=[],r.rtcpFb=[],Vr(r,n),t=!0)}}),t&&(this._log.warn(`switch video encoder to ${e}`),yield this.updateSDP())})}useHWEncoder(e=!0,t){return f(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let r=!1,s=[];T(t)?s=this._parsedAnswer.media.slice(1,4):t===2?s.push(this._parsedAnswer.media[1]):t===3?s.push(this._parsedAnswer.media[2]):t===7&&s.push(this._parsedAnswer.media[3]),s.forEach(n=>{var a;if(n.type===p.VIDEO){let c;e&&this.is42001fSupported?c=this.clientAbility.video.codecs.find(l=>l.fmtp.includes("42001f")):e||(c=this._serverAbility.video.codecs.find(l=>l.codec.toLowerCase()===(this._serverAbility.useVp8?"vp8":"h264"))),c&&!((a=n.payloads)!=null&&a.includes(String(c.payload)))&&(n.fmtp=[],n.payloads="",n.rtp=[],n.rtcpFb=[],Vr(n,c),r=!0)}}),r&&(this._log.warn(`use ${e?"hw":"sw"} encoder`),yield this.updateSDP())})}setProfileLevelId(e="42e01f",t){return f(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let r=!1,s=[];T(t)?s=this._parsedAnswer.media.slice(1,4):t===2?s.push(this._parsedAnswer.media[1]):t===3?s.push(this._parsedAnswer.media[2]):t===7&&s.push(this._parsedAnswer.media[3]),s.forEach(n=>{var a;if(n.type===p.VIDEO){let c;e&&(c=this.clientAbility.video.codecs.find(l=>l.fmtp.includes(e))),c&&!((a=n.payloads)!=null&&a.includes(String(c.payload)))&&(n.fmtp=[],n.payloads="",n.rtp=[],n.rtcpFb=[],Vr(n,c),r=!0)}}),r&&(this._log.warn(`use ${e}`),yield this.updateSDP())})}sendDataChannelMessage(e){var t;(t=this._datachannel)==null||t.send(e)}reset(){var e;this._peerConnection&&(this._peerConnection.close(),this._peerConnection.removeEventListener("track",this._peerConnection._onaddstreampoly,this),this._peerConnection._onaddstreampoly=null,this._peerConnection=null),(e=this.clearWaitForConnectedPromise)==null||e.call(this),this._parsedAnswer=null,this.originOffer=null}close(){this._log.info("close pc"),this.isDestroyed=!0,this.removeRTCListener(),this.insertableStreamsAbortMap.forEach(e=>Ai(e.abort)&&e.abort("destroy")),this.insertableStreamsAbortMap.clear(),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners(),this._room.healthDetector.off("1",this.onBadHealth,this)}getReceiversByUserId(e){if(!this._peerConnection)return[];let t=this._peerConnection.getReceivers();return(this._downlinkMIDMap.get(e)||[]).map(r=>t[r])}get isUsingRelay(){return this._room.getIceTransportPolicy()==="relay"}detectTCPAndUDP({uplinkRTT:e,downlinkRTT:t}){var u;if(this.currentState!=="CONNECTED"||this._isRelayTried&&!this._room.forceRelay||this._room.getIceServers().length===0)return;let r=this._signalChannel.rtt,s=Math.max(e,t),{rttRatioThreshold:n,rttThreshold:a}=((u=this._room.scheduleResult.config)==null?void 0:u.useTurnTcpInfo)||{};if(!n||!a||!r||!s)return;let c=Math.floor(s/r),l=(this._isRelayTried||c>n)&&s>a;if(!l){this._rttOverCount=0;return}++this._rttOverCount<5||(this._log.warn(`detectTCPAndUDP ws-rtt: ${r} upRTT: ${e} downRTT: ${t} ratio: ${c} over-count: ${this._rttOverCount} isOver: ${l} isRelayTried: ${this._isRelayTried} force-relay: ${this._room.forceRelay}`),!this.isUsingRelay&&!this._isRelayTried?(this._isRelayTried=!0,this._rttOverCount=0,this.switchRelay(!0)):this._room.forceRelay&&this.switchRelay(!1))}switchRelay(e,t=!1){return f(this,null,function*(){if(this.isUsingRelay===e)return;let r=e?"relay":"udp",s=e?521709:521710;try{this._room.forceRelay=e,this._log.warn(`switchRelay ${r}`);let n=Date.now();yield this.doSwitchRelay(r),this._log.warn(`switchRelay ${r} success`),v.addSuccessEvent({key:s,cost:Date.now()-n})}catch(n){this._log.warn(`switchRelay ${r} failed`,n),v.addFailedEvent({key:s,error:n}),t?this._room.reJoin():yield this.switchRelay(!e,!0)}})}doSwitchRelay(e){return new Promise((t,r)=>{let s=setTimeout(()=>{this.stopReconnection(),r(new Error(`switch ${e} timeout`))},1e4);this.startReconnection().then(t,r).finally(()=>clearTimeout(s))})}removeRTCListener(){this._peerConnection&&(this._peerConnection.oniceconnectionstatechange=null,this._peerConnection.onconnectionstatechange=null,this._peerConnection.onsignalingstatechange=null,this._peerConnection.ontrack=null),this.dtlsTransport&&(this.dtlsTransport.onstatechange=null)}requestRemoteFallbackToH264(){this._log.warn("H265 decode failed, remote need to fallback h264"),this._h265DecodeFailed=!0,this._signalChannel.sendWaitForResponse({command:Z.UPDATE_CONSTRAINT_CONFIG,data:{videoDecCodec:"h264"},responseCommand:G.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)})}};O([xc("reconnect")],Xt.prototype,"startReconnection",1),O([gi(e=>e.userId)],Xt.prototype,"addDownlink",1),O([gi(e=>e)],Xt.prototype,"removeDownlink",1),O([ir(!0)],Xt.prototype,"updateSDP",1),O([Rt(521712,!1),Eo(10,0)],Xt.prototype,"setOffer",1),O([Rt(521713,!1),Eo(10,0)],Xt.prototype,"setAnswer",1),O([Tf()],Xt.prototype,"close",1);var dm=class{constructor(i){d(this,"tag");d(this,"len");d(this,"data");let e=new DataView(i);this.tag=e.getUint16(),this.len=e.getUint16(2),this.data=new Uint8Array(i).slice(4,4+this.len).buffer}},lm=class{constructor(i){d(this,"tinyId");d(this,"data");let e=new DataView(i),t=0,r=[];for(;t<e.byteLength;){let s=e.getUint16(t+2),n=new dm(new Uint8Array(i).slice(t,t+2+2+s).buffer);r.push(n),t+=4+s}r.forEach(s=>{s.tag===1?this.tinyId=new TextDecoder().decode(s.data):s.tag===2&&(this.data=s.data)})}},L_=new Set;function xt(){let o=Math.floor(Math.random()*4294967296);return L_.has(o)?xt():(L_.add(o),o)}var B_=Je(at());var bo=class extends B_.default{constructor(e){super();d(this,"userId");d(this,"tinyId");d(this,"_sdpSemantics");d(this,"_isUplink");d(this,"_room");d(this,"_log");d(this,"_currentState","DISCONNECTED");d(this,"_prevTime",-1);d(this,"_blackSmallVideoDetectionId");this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=R.createLogger({parent:this._room.getLogger(),id:"n",userId:this._room.userId,remoteUserId:this._isUplink?void 0:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink})}get _peerConnection(){var e;return((e=this.singlePC)==null?void 0:e.getPeerConnection())||null}get singlePC(){return this._room.singlePC}get _signalChannel(){return this._room.signalChannel}close(e){this._log.info("close connection"),this.emit("closed",e)}emitConnectionStateChangedEvent(e){return e===this._currentState?!1:(S.emit(A.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:e,remoteUserId:this._isUplink?void 0:this.userId}),this.emit("connection-state-changed",{prevState:this._currentState,state:e}),this._currentState=e,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}getCurrentState(){return this._currentState}get isH264(){var e,t;return!!((t=(e=this._peerConnection)==null?void 0:e.remoteDescription)!=null&&t.sdp.includes("H264"))}};var um=class{constructor(){d(this,"worker");d(this,"callbacks",new Map);d(this,"_log");d(this,"sleep",{});d(this,"heartbeatListenerCleaner",new Map);d(this,"userIdMap",new Map);this._log=R.createLogger({id:"bvd"})}getWorker(){if(!this.worker){let i=`
|
|
121
|
+
const tracks=new Map;let canvas,ctx;const log=(...t)=>postMessage({type:"log",message:"[worker] "+t.join(" ")});function startDetection(e,t,a){if(!tracks.has(e)){const c={reader:a.getReader(),blackCount:0,timeoutId:null,intervalId:null};tracks.set(e,c),c.timeoutId=setTimeout(()=>stopDetection(e,"timeout"),t),c.intervalId=setInterval(async()=>{try{await isFrameBlack(e)?(c.blackCount++,postMessage({type:"blackCount",trackId:e,count:c.blackCount}),3<=c.blackCount&&(postMessage({type:"black",trackId:e}),stopDetection(e,"black"))):c.blackCount=0}catch(t){log("check black video error:",t.message),stopDetection(e,"error")}},1e3)}}function stopDetection(t,e){var a=tracks.get(t);a&&(a.timeoutId&&clearTimeout(a.timeoutId),a.intervalId&&clearInterval(a.intervalId),a.reader&&a.reader.cancel(),tracks.delete(t),postMessage({type:e,trackId:t}))}async function isFrameBlack(t){t=tracks.get(t);if(!t)return!1;var t=t.reader,{done:t,value:e}=await t.read();if(!e||t)return!1;canvas||(canvas=new OffscreenCanvas(e.codedWidth,e.codedHeight),ctx=canvas.getContext("2d",{willReadFrequently:!0})),canvas.width===e.codedWidth&&canvas.height===e.codedHeight||(canvas.width=e.codedWidth,canvas.height=e.codedHeight,ctx=canvas.getContext("2d",{willReadFrequently:!0})),ctx.drawImage(e,0,0,canvas.width,canvas.height);t=getFrameBlackRatio(ctx.getImageData(0,0,canvas.width,canvas.height));return e.close(),1===t}function getFrameBlackRatio(t){var e=t.data;let a=0;for(let t=0;t<100;t++){var c=4*Math.floor(Math.random()*(e.length/4)),[c,r,n,o]=[e[c],e[1+c],e[2+c],e[3+c]];0<o&&0===c&&0===r&&0===n&&a++}return a/100}self.onmessage=t=>{var{type:t,trackId:e,timeout:a,readable:c}=t.data;"addTrack"===t&&startDetection(e,a,c),"removeTrack"===t&&stopDetection(e)};
|
|
122
|
+
`,e=new Blob([i],{type:"application/javascript"}),t=URL.createObjectURL(e);this.worker=new Worker(t),URL.revokeObjectURL(t),this.worker.onerror=r=>this._log.warn("worker error:",r.message,r.filename||"unknown",r.lineno||"unknown"),this.worker.onmessage=r=>{var l;let{type:s,trackId:n,message:a,count:c}=r.data;if(s==="black")(l=this.callbacks.get(n))==null||l();else if(s==="log")this._log.warn(a);else if(s==="blackCount"){let u=this.userIdMap.get(n);this._log.warn(`${u||n} black count: ${c}`)}}}return this.worker}start({track:i,isUplink:e,room:t,userId:r,onBlack:s}){if(this._log.debug("start detect black video",i.id),!fn()||!s||!i||typeof Worker=="undefined"){this._log.warn("black video detector not supported");return}let n=a=>{var l,u,h,m;let c;if(e)c=(u=(l=a.msg_up_stream_info)==null?void 0:l.msg_video_status)==null?void 0:u.filter(_=>_.uint32_video_stream_type===3)[0];else{let _=(h=a.msg_down_stream_info)==null?void 0:h.filter(g=>{var E;return((E=g.msg_user_info)==null?void 0:E.str_identifier)===r})[0];c=(m=_==null?void 0:_.msg_video_status)==null?void 0:m.filter(g=>g.uint32_video_stream_type===3)[0]}if(c){let _=(c.uint32_video_codec_bitrate||0)/1e3;if(this.sleep[i.id]&&this.sleep[i.id]>0){this.sleep[i.id]-=1;return}_>0&&_<10&&(this.sleep[i.id]=30,this._log.info("track bitrate",_,"start check"),this.checkOnce(i,30*1e3))}};return t.on("heartbeat-report",n),this.heartbeatListenerCleaner.set(i.id,()=>t.off("heartbeat-report",n)),this.callbacks.set(i.id,s),this.userIdMap.set(i.id,r),i.id}checkOnce(i,e){try{let t=this.getWorker();if(!t)throw new Error("Worker not available");let r=new MediaStreamTrackProcessor({track:i});t.postMessage({type:"addTrack",trackId:i.id,timeout:e,readable:r.readable},[r.readable])}catch(t){this._log.warn("check error:",t),this.stop(i.id)}}stop(i){if(i){this.worker&&this.worker.postMessage({type:"removeTrack",trackId:i}),this.callbacks.delete(i),delete this.sleep[i];let e=this.heartbeatListenerCleaner.get(i);e&&e(),this.heartbeatListenerCleaner.delete(i),this.userIdMap.delete(i)}}destroy(){this.callbacks.forEach((i,e)=>this.stop(e)),this.worker&&(this.worker.terminate(),this.worker=null)}},ur=new um;var xd=class extends bo{constructor(e){super(L(M({},e),{isUplink:!0}));d(this,"localMainAudioTrack",null);d(this,"localMainVideoTrack",null);d(this,"localAuxAudioTrack",null);d(this,"localAuxVideoTrack",null);d(this,"_isPublishingAux",!1);d(this,"_publishingLocalAudioTrack");d(this,"_publishingLocalVideoTrack");d(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,videoDecCodec:"",audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0});d(this,"_flag",0);d(this,"_checkPublishStateTimeoutId",-1);this.initialize()}get videoCodec(){var e;return((e=this.singlePC)==null?void 0:e.videoCodec)||"h264"}get ssrc(){if(!this.singlePC)return{audio:0,video:0,videoRtx:0,small:0,smallRtx:0,auxiliary:0,auxiliaryRtx:0};let{audioSsrc:e,bigVideoSsrc:t,bigVideoRtxSsrc:r,smallVideoSsrc:s,smallVideoRtxSsrc:n,auxVideoSsrc:a,auxVideoRtxSsrc:c}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:r||0,small:s||0,smallRtx:n||0,auxiliary:a||0,auxiliaryRtx:c||0}}get flag(){return this._flag}set flag(e){this._flag!==e&&(this._flag=e,this.checkPublishState())}checkPublishState(e=!1){try{if(!e&&this._checkPublishStateTimeoutId>0)return;let{serverPublishState:t}=this,{publishState:r}=this._room,s=Object.keys(r).filter(n=>{if(r[n]!==t[n]&&r[n])switch(n){case"audio":return!(!this.localMainAudioTrack||!this.localMainAudioTrack.isMediaTrackActive);case"bigVideo":case"smallVideo":return!(!this.localMainVideoTrack||!this.localMainVideoTrack.isMediaTrackActive);case"auxVideo":return!(!this.localAuxVideoTrack||!this.localAuxVideoTrack.isMediaTrackActive)}return!1});if(s.length>0){if(e)v.addCount({key:521e3}),s.forEach(n=>{this._log.warn(`${n} publish failed during call ${ai()} ${ni()}`),v.addEnum({key:521719,value:F_[n]})});else{this._checkPublishStateTimeoutId=re.run("timeout",()=>this.checkPublishState(!0),{delay:10*1e3,count:1});return}re.clearTask(this._checkPublishStateTimeoutId),this._checkPublishStateTimeoutId=-1}}catch(t){this._log.warn("checkPublishState failed",t)}}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}get serverPublishState(){return{audio:!!(this.flag&_r),bigVideo:!!(this.flag&fr),smallVideo:!!(this.flag&Vs),auxVideo:!!(this.flag&Fr)}}initialize(){this.installEvents()}close(e){var r;let t=((r=this._peerConnection)==null?void 0:r.getSenders())||[];for(let s of t)s.replaceTrack(null);super.close(e),this.uninstallEvents(),this.uninstallTrackMuteEvents(this.localMainAudioTrack,this.localMainVideoTrack,this.localAuxVideoTrack),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),this.installSPCEvents()}installSPCEvents(){var e,t;(e=this.singlePC)!=null&&e.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||(t=this.singlePC)==null||t.on("spc-reconnected",this.onSinglePCReconnected,this)}uninstallSPCEvents(){var e;(e=this.singlePC)==null||e.off("spc-reconnected",this.onSinglePCReconnected,this)}uninstallEvents(){this.off("connection-state-changed",this.handleConnectionStateChange,this),this.uninstallSPCEvents()}emitConnectionStateChangedEvent(e,t){var n,a,c;let r=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&r!==e&&(t?t.emit("connection-state-changed",{prevState:r,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:r,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:r,state:e}),(c=this._publishingLocalVideoTrack)==null||c.emit("connection-state-changed",{prevState:r,state:e}))),s}onVideoEncodeFailed(e){return f(this,null,function*(){if(!e||!e.isMediaTrackActive)return;let{videoCodec:t,singlePC:r}=this;if(!r)return;let s={h265:{supported:r.isH264EncodeSupported,target:"h264",log:"h265 encoder not working"},h264:{supported:r.isVP8EncodeSupported,target:"vp8",log:"h264 encoder not working"},vp8:{supported:!1,target:"vp8",log:"vp8 encoder not working, no fallback available"}};if(t==="vp9"||t==="av1")return;let n=s[t];this._log.warn(n.log),n!=null&&n.supported&&(yield r.switchVideoEncoder(n.target))})}publish(s){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:r}){var c,l,u,h,m,_,g;if(!this.singlePC)return;if(this.installEvents(),this.installTrackMuteEvents(e,t),t&&(t.retryEncodeFailed=this.onVideoEncodeFailed.bind(this)),yield this.singlePC.waitForPeerConnectionConnected(),e&&(this._publishingLocalAudioTrack=e),t){if(!this.singlePC.isH264EncodeSupported&&!this.singlePC.isVP8EncodeSupported)throw new D({code:I.NOT_SUPPORTED_H264,message:H({key:B.NOT_SUPPORTED_H264ENCODE})});this.singlePC.isUsingH264&&!this.singlePC.isH264EncodeSupported&&this.singlePC.isVP8EncodeSupported&&(this._log.warn("h264 encoder not supported"),yield this.singlePC.switchVideoEncoder("vp8")),_e&&Zo()===115&&t.profile.width*t.profile.height<=640*360&&(this._log.warn(`fallback video to defaultBigVideoProfile: ${JSON.stringify(pr)}`),t.setProfile(pr),yield t.applyProfile()),this._publishingLocalVideoTrack=t}this._isPublishingAux=r;let n;if(t&&!r&&t.small&&(n=this._room.videoManager.smallTrack),yield this._signalChannel.sendWaitForResponseWithRetry({command:Z.SPC_PUBLISH,responseCommand:G.SPC_PUBLISH_RESULT,data:L(M({},this.singlePC.uplinkSSRC),{state:this._room.publishState,muteState:this._room.muteState}),retries:3}),yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:n,isAuxiliary:r}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,t){this[r?"localAuxVideoTrack":"localMainVideoTrack"]=t,yield this.singlePC.setDegradationPreference(this._peerConnection.getSenders()[r?3:1],t.contentHint,t.streamType);let{scaleResolutionDownBy:E}=t;yield this.singlePC.setScaleResolutionDownBy(this._peerConnection.getSenders()[r?3:1],E,t.streamType)}e&&(this[r?"localAuxAudioTrack":"localMainAudioTrack"]=e),yield this.singlePC.setBandwidth({audio:((c=this.localMainAudioTrack)==null?void 0:c.profile.bitrate)||((l=this.localAuxAudioTrack)==null?void 0:l.profile.bitrate),bigVideo:(u=this.localMainVideoTrack)==null?void 0:u.profile.bitrate,smallVideo:(m=(h=this.localMainVideoTrack)==null?void 0:h.small)==null?void 0:m.bitrate,auxVideo:(_=this.localAuxVideoTrack)==null?void 0:_.profile.bitrate}),this.sendMediaSettings(),(this._room.preferHW||(g=this._room.scheduleResult.config)!=null&&g.preferHW)&&t&&t.profile.width*t.profile.height>=1280*720&&this.singlePC.useHWEncoder(!0,r?7:2);let a=new URLSearchParams(location.search).get("profileLevelId");a&&this.singlePC.setProfileLevelId(a)})}publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:r,isAuxiliary:s}){if(!St())return;this._log.info("publish by transceiver");let n=t==null?void 0:t.outMediaTrack,a=e==null?void 0:e.outMediaTrack,c=this._peerConnection.getTransceivers(),l=[],u=[],h=(_,g,E)=>{var k;let C=c[g].sender.replaceTrack(E);u.push(g),(k=this.singlePC)!=null&&k.enableInsertableStreams&&C.then(()=>this.createEncodedStreams(c[g].sender,_)),this.initSenderTransform(c[g].sender,_),l.push(C)};a&&h(e.mediaType,0,a),n&&h(t.mediaType,s?3:1,n),t!=null&&t.small&&l.push(this.publishSmall(this._room.videoManager.smallMode,t));let m=this.singlePC.setTransceiverDirection(se.SENDONLY,u);return l.push(m),Promise.all(l)}getTrackByMediaType(e){switch(e){case 1:return this.localMainAudioTrack||this._room.localMainAudioTrack;case 4:case 8:return this.localMainVideoTrack||this._room.localMainVideoTrack;case 2:return this.localAuxVideoTrack||this._room.localAuxVideoTrack;default:return null}}createEncodedStreams(e,t){var a,c;if(this.singlePC.insertableStreamsAbortMap.has(e))return;let r=e.createEncodedStreams(),s=new AbortController;(a=this.singlePC)==null||a.addAbortController(e,s),((c=this.getTrackByMediaType(t))!=null&&c.enableEncodeFrame?r.readable.pipeThrough(new TransformStream({transform:(l,u)=>{var m,_;let h=this.getTrackByMediaType(t);if(!h||!h.encodeFrame)return u.enqueue(l);h.isAudio?u.enqueue(h.enableEncodeFrame?h.encodeFrame(l):l):u.enqueue((m=this.singlePC)!=null&&m.isUsingH264||(_=this.singlePC)!=null&&_.isUsingH265?h.encodeFrame(l,t===8):l)}}),s):r.readable).pipeTo(r.writable,s).catch(l=>{this._log.debug("encoded stream error",l),l!=="destroy"&&this._log.warn(l)})}initSenderTransform(e,t){if(!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker||!ns)return;let r=t!==2,s=t===8;e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!1,isAudio:t===1,isMain:r,isSmall:s}))}enableSmall(e){return f(this,null,function*(){e?yield this.publishSmall(this._room.videoManager.smallMode):yield this.unpublishSmall()})}publishSmall(r){return f(this,arguments,function*(e,t=this.localMainVideoTrack){var l;if(!this.singlePC)return;if(e==="canvas"&&!gc()){this._log.warn("canvas mode small stream is not supported");return}let s=this._peerConnection.getTransceivers(),{sender:n}=s[2],a=yield this.doPublishSmall(e,t),c=e==="canvas"?524700:524701;if(v.addSuccessEvent({key:c}),!a){v.addFailedEvent({key:c,error:10001});return}(l=this.singlePC)!=null&&l.enableInsertableStreams&&this.createEncodedStreams(n,8),this.initSenderTransform(n,8),yield this.singlePC.setTransceiverDirection(se.SENDONLY,[2]),this.updateMediaSettings(),yield this.doPublishChange(),n.track&&(this._blackSmallVideoDetectionId=ur.start({track:n.track,room:this._room,isUplink:!0,userId:this.userId,onBlack:()=>{this._log.warn("small video is black");let u=e==="canvas"?524700:524701;v.addFailedEvent({key:u,error:10002}),ur.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0}}))})}doPublishSmall(r){return f(this,arguments,function*(e,t=this.localMainVideoTrack){if(!this.singlePC)return null;this._log.info("publish small",e);let s=this._peerConnection.getTransceivers(),{sender:n}=s[2];if(e==="canvas"&&this._room.videoManager.smallTrack)return yield n.replaceTrack(this._room.videoManager.smallTrack),"canvas";if(e==="api"&&(t!=null&&t.outMediaTrack)&&(t!=null&&t.small)){yield n.replaceTrack(t==null?void 0:t.outMediaTrack);let a=n.getParameters(),c=$o(t==null?void 0:t.profile,t==null?void 0:t.small);return this._log.info("small scaleResolutionDownBy",c),a.encodings[0].scaleResolutionDownBy=c,n.setParameters(a),"api"}return this._log.warn(`small track can not be enabled, smallMode: ${this._room.videoManager.smallMode}, smallTrack: ${!!this._room.videoManager.smallTrack}, bigVideoTrack: ${!!(t!=null&&t.outMediaTrack)}`),null})}unpublishSmall(){return f(this,null,function*(){if(!this.singlePC)return;this._log.info("unpublish small"),yield this._peerConnection.getTransceivers()[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(se.INACTIVE,[2]),this.updateMediaSettings(),yield this.doPublishChange(),ur.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0})}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(r){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){var l;yield(l=this.singlePC)==null?void 0:l.waitForPeerConnectionConnected();let s=t&&t===this.localAuxVideoTrack||e&&e===this.localAuxAudioTrack,n=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),c=[];e&&(s?this.localAuxAudioTrack=null:this.localMainAudioTrack=null,!this.localMainAudioTrack&&!this.localAuxAudioTrack&&(yield a[0].replaceTrack(null),c.push(0))),n&&(s?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=L(M({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),c.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=L(M({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),c.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.singlePC.setTransceiverDirection(se.INACTIVE,c),yield this.doPublishChange(!1)):yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),t==null||t.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return f(this,null,function*(){let t={state:this._room.publishState,constraintConfig:this._mediaSettings},r=yield this._signalChannel.sendWaitForResponseWithRetry({command:Z.PUBLISH_STATE_CHANGE,data:t,responseCommand:G.PUBLISH_STATE_CHANGE_RESULT,enableLog:e,retries:3});this.checkPublishResultCode(r.data.code,r.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:Z.UNPUBLISH,commandDesc:"unpublish",responseCommand:G.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===I.API_CALL_TIMEOUT||t.getCode()===I.API_CALL_ABORTED)return Promise.resolve();throw t})}updateMediaSettings(){var s,n;this._mediaSettings.videoCodec=((s=this.singlePC)==null?void 0:s.videoCodec)||"h264",this._mediaSettings.videoDecCodec=((n=this.singlePC)==null?void 0:n.downlinkVideoCodec)||"h264";let e=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:t,localAuxVideoTrack:r}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?r=this._publishingLocalVideoTrack:t=this._publishingLocalVideoTrack),bi){if(e&&e.outMediaTrack){let a=e.outMediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=e.profile.bitrate*1e3,this._mediaSettings.audioFs=a.sampleRate||0}if(t&&t.outMediaTrack){let a=t.outMediaTrack.getSettings(),{scaleResolutionDownBy:c}=t;this._mediaSettings.videoWidth=(a.width||0)/c||0,this._mediaSettings.videoHeight=(a.height||0)/c||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=t.profile.bitrate*1e3,t.small&&(this._mediaSettings.smallVideoWidth=t.small.width,this._mediaSettings.smallVideoHeight=t.small.height,this._mediaSettings.smallVideoFps=t.small.frameRate,this._mediaSettings.smallVideoBps=t.small.bitrate*1e3)}if(r&&r.outMediaTrack){let a=r.outMediaTrack.getSettings(),{scaleResolutionDownBy:c}=r;this._mediaSettings.auxVideoWidth=(a.width||0)/c||0,this._mediaSettings.auxVideoHeight=(a.height||0)/c||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=r.profile.bitrate*1e3}}else e&&e.outMediaTrack&&(this._mediaSettings.audioChannel=e.profile.channelCount,this._mediaSettings.audioBps=e.profile.bitrate*1e3,this._mediaSettings.audioFs=e.profile.sampleRate),t&&t.outMediaTrack&&(this._mediaSettings.videoWidth=t.profile.width,this._mediaSettings.videoHeight=t.profile.height,this._mediaSettings.videoFps=t.profile.frameRate,this._mediaSettings.videoBps=t.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:Z.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:G.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return f(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is adding ${e.kind} track to current published local ${t?p.AUXILIARY:p.MAIN} stream`),yr()&&(yield this.addTrackByTransceiver(e,t))})}addTrackByTransceiver(e,t){return f(this,null,function*(){var s;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===p.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),n===1&&((s=this.localMainVideoTrack)!=null&&s.small)&&this._room.videoManager.smallTrack&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===se.INACTIVE&&(yield this.singlePC.setTransceiverDirection(se.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}removeTrack(e){return f(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${t?p.AUXILIARY:p.MAIN} stream`),yr()&&(yield this.removeTrackByTransceiver(e,t))})}removeTrackByTransceiver(e,t){return f(this,null,function*(){if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===p.AUDIO)yield r[0].sender.replaceTrack(null);else{let s=t?3:1;yield r[s].sender.replaceTrack(null),s===1&&this._room.videoManager.hasSmall&&(yield r[2].sender.replaceTrack(null)),yield this.singlePC.setTransceiverDirection(se.INACTIVE,[s])}this.updateMediaSettings(),yield this.doPublishChange()})}replaceTrack(e){return f(this,null,function*(){var n;let t=(n=this._peerConnection)==null?void 0:n.getSenders(),r=e.outMediaTrack||e.mediaTrack;if(!t||t.length===0||!r||t.find(a=>a.track===r))return!1;let s=e.mediaType===2||e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info(`is replacing ${r.kind} track ${r.id} ${r.label} on ${s?p.AUXILIARY:p.MAIN} stream`),r.kind===p.AUDIO&&t[0]&&(yield t[0].replaceTrack(r)),r.kind===p.VIDEO&&(!s&&t[1]&&(yield t[1].replaceTrack(r)),s&&t[3]&&(yield t[3].replaceTrack(r))),!0})}setBandwidth(s){return f(this,arguments,function*({bandwidth:e,type:t,videoType:r}){if(this.singlePC){let n={};t===p.AUDIO?n.audio=e:r==="big"?n.bigVideo=e:r==="small"?n.smallVideo=e:n.auxVideo=e,yield this.singlePC.setBandwidth(n)}})}sendMutedFlag(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info(`send muted state: ${JSON.stringify(this._room.muteState)}`),this._signalChannel.sendWaitForResponseWithRetry({command:Z.UPDATE_MUTE_STAT,responseCommand:G.MUTE_RESULT,data:this._room.muteState,retries:3}).catch(()=>{}))}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&S.emit(A.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(e=p.VIDEO){if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===p.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===p.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===p.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===p.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===Hr?(this._log.error(je.NOT_SUPPORTED_H264ENCODE),new D({code:I.NOT_SUPPORTED_H264,message:H({key:B.NOT_SUPPORTED_H264ENCODE})})):new D({code:I.UNKNOWN,message:H({key:B.SIGNAL_RESPONSE_FAILED,data:{signalResponse:G.PUBLISH_RESULT,code:e,message:t}})})}onSinglePCReconnected(){return f(this,null,function*(){this.isMainStreamPublished&&(this._log.warn("republish main stream"),yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(this._log.warn("republish aux stream"),yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0}))})}};O([Ct(({localVideoTrack:e})=>{e==null||delete e.retryEncodeFailed})],xd.prototype,"unpublish",1);var F_=(r=>(r[r.audio=1]="audio",r[r.bigVideo=2]="bigVideo",r[r.smallVideo=3]="smallVideo",r[r.auxVideo=4]="auxVideo",r))(F_||{}),hm=xd;function H_(o){return Object.keys(o).filter(i=>o[i])}var Ms=class extends bo{constructor(e){super(L(M({},e),{isUplink:!1}));d(this,"_flag",0);d(this,"isRobot",!1);d(this,"role","anchor");d(this,"remoteAudioTrack");d(this,"remoteVideoTrack");d(this,"remoteAuxiliaryTrack");d(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0});d(this,"jitterBufferTimeoutId",-1);d(this,"_videoCodec");this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=new Ti(this._room,this),this.remoteVideoTrack=new ki(this._room,this),this.remoteAuxiliaryTrack=new Es(this._room,this),this.initialize()}get videoCodec(){var e;return this._videoCodec||((e=this.singlePC)==null?void 0:e.downlinkVideoCodec)||"h264"}set videoCodec(e){this._videoCodec=e}get subscribeState(){return{audio:this.remoteAudioTrack.isSubscribed||this.remoteAudioTrack.isSubscribing,video:this.remoteVideoTrack.isBig&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),smallVideo:this.remoteVideoTrack.isSmall&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),auxiliary:this.remoteAuxiliaryTrack.isSubscribed||this.remoteAuxiliaryTrack.isSubscribing}}get muteState(){return ei(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,r,s;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(r=this.remoteVideoTrack)==null||r.onFlagChanged(),(s=this.remoteAuxiliaryTrack)==null||s.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===p.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){clearTimeout(this.jitterBufferTimeoutId),super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents(),this.removeDownlink()}installEvents(){this.singlePC&&(this.listeners("track").includes(this.onTrack)||this.singlePC.on("track",this.onTrack,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||this.singlePC.on("spc-reconnected",this.onSinglePCReconnected,this),this.remoteVideoTrack.on("decode-failed",this.onDecodeFailed,this))}uninstallEvents(){this.singlePC&&(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this),this.remoteVideoTrack.off("decode-failed",this.onDecodeFailed,this))}emitConnectionStateChangedEvent(e){var s,n;let t=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&t!==e&&((s=this.remoteVideoTrack)==null||s.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),r}onTrack(e){var u,h;let t=e.streams[0],{track:r,receiver:s}=e;if(!t.id.includes(this.tinyId))return;let a=t.id.includes("aux")?"auxiliary":"main";this._log.debug(`ontrack ${a} ${r.kind}`);let c=p.AUDIO;r.kind===p.VIDEO&&(c=a===p.MAIN?p.VIDEO:p.AUXILIARY);let l=this.remoteAudioTrack;c===p.VIDEO?l=this.remoteVideoTrack:c===p.AUXILIARY&&(l=this.remoteAuxiliaryTrack),(u=this.singlePC)==null||u.receiverRemoteTrackMap.set(s,l),(h=this.singlePC)!=null&&h.scriptTransformWorker&&this.initReceiverTransform(s,a,r.kind===p.AUDIO),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(s),l.setInputMediaStreamTrack(r)}createEncodedStreams(e){if(!this.singlePC.insertableStreamsAbortMap.has(e)){let t=e.createEncodedStreams(),r=new AbortController,s={abortController:r,enqueue:n=>{var c,l,u;let a=(c=this.singlePC)==null?void 0:c.receiverRemoteTrackMap.get(e);return!a||a.kind==="video"&&!((l=this.singlePC)!=null&&l.isUsingH264)&&!((u=this.singlePC)!=null&&u.isUsingH265)?n:a.decodeFrame(n)}};t.readable.pipeThrough(new TransformStream({transform:(n,a)=>{let c=s.enqueue(n);c&&a.enqueue(c)}})).pipeTo(t.writable,r).catch(n=>{n!=="destroy"&&this._log.warn(n)}),this.singlePC.addAbortController(e,r)}}initReceiverTransform(e,t,r){!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker||e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!0,isAudio:r,userId:this.userId,streamType:t}))}subscribe(e,t){return f(this,null,function*(){var r,s;try{let n=!0;if(this._log.info(`subscribe ${t} ${H_(e)}`),this.hasSSRC){let l="subscribe_change";Object.values(e).find(u=>u===!0)||(l="unsubscribe"),yield this.sendSubscription(l,e)}else{if(yield this._room.switchRoomSubedReq,(r=this.singlePC)!=null&&r.autoSubscribedUserMap.size){let l=this.singlePC.autoSubscribedUserMap.get(this.userId);if(l){this.singlePC.autoSubscribedUserMap.delete(this.userId);let u=(s=this.singlePC.autoSubscribedSsrcGroups.get(this._room.roomId))==null?void 0:s[l.groupIndex];u&&(this.ssrc={audio:u.audioSsrc,video:u.bigVideoSsrc,videoRtx:u.bigVideoRtxSsrc,auxiliary:u.auxVideoSsrc,auxiliaryRtx:u.auxVideoRtxSsrc},n=!1)}}yield this.doSubscribe(e,n),this.checkTrackEnded(e)}let{user:a,mediaTrack:c}=this.remoteVideoTrack;e.smallVideo&&c?(v.addSuccessEvent({key:524702}),this._blackSmallVideoDetectionId=ur.start({track:c,isUplink:!1,room:this._room,userId:this.userId,onBlack:()=>{this._log.warn("small video is black, auto change to big"),this._room.changeType(!1,a),v.addFailedEvent({key:524702}),ur.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0}})):(ur.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0)}catch(n){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${n.message} ${JSON.stringify(this.muteState)}`),new D({code:I.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):n}})}checkTrackEnded(e){var t,r,s;if((e.audio&&((t=this.remoteAudioTrack.mediaTrack)==null?void 0:t.readyState)==="ended"||e.video&&((r=this.remoteVideoTrack.mediaTrack)==null?void 0:r.readyState)==="ended"||e.auxiliary&&((s=this.remoteAuxiliaryTrack.mediaTrack)==null?void 0:s.readyState)==="ended")&&this.singlePC&&!this.singlePC.isReconnecting){if(this._log.warn("remote track ended start spc reconnect"),We&&qe<92)return;this.singlePC.startReconnection()}}unsubscribe(r){return f(this,arguments,function*({remoteTracks:e,streamType:t}){var a;if(t==="main"&&!this.isMainStreamSubscribed||t==="auxiliary"&&!this.isAuxStreamSubscribed){this._log.info(`${t} stream already unsubscribed`);return}let s=M({},this.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:s.audio=!1;break;case 4:s.video=!1;break;case 8:s.smallVideo=!1;break;case 2:s.auxiliary=!1;break;default:break}});let n="subscribe_change";Object.values(s).find(c=>c===!0)||(n="unsubscribe"),this._log.info(`${n==="unsubscribe"?n:"subscribe"} ${t} [${H_(s)}]`),n==="unsubscribe"&&((a=this.singlePC)==null||a.removeDownlinkQueue.add(this.tinyId)),yield this.sendSubscription(n,s),t==="main"&&(ur.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0),n==="unsubscribe"&&(yield this.removeDownlink())})}sendSubscription(e,t=this.subscribeState){let r={srcTinyId:this.tinyId,srcUserId:this.userId},s=Z.UNSUBSCRIBE,n=G.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(r={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},s=Z.SUBSCRIBE_CHANGE,n=G.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponseWithRetry({command:s,data:r,responseCommand:n,timeout:1e4,retries:3}).then(({data:a})=>{if(a.code!==0){let c=new D({code:a.code,message:H({key:B.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(c),c}})}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}setDelay({audioDelay:e,videoDelay:t}){this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=t}onSinglePCReconnected(){return f(this,null,function*(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary)&&(this._log.warn(`resubscribe ${JSON.stringify(this.subscribeState)}`),yield this.doSubscribe(this.subscribeState),this.remoteAudioTrack.checkDecodeResult(),this.remoteVideoTrack.checkDecodeResult(),this.remoteAuxiliaryTrack.checkDecodeResult())})}get hasSSRC(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}doSubscribe(){return f(this,arguments,function*(e=this.subscribeState,t=!0){if(this.singlePC){this.singlePC.addDownlinkQueue.add(this.tinyId),yield this.singlePC.waitForPeerConnectionConnected();try{if(t||!this.hasSSRC){let r={audioSsrc:xt(),bigVideoSsrc:xt(),bigVideoRtxSsrc:xt(),auxVideoSsrc:xt(),auxVideoRtxSsrc:xt()},{audioSsrc:s,bigVideoSsrc:n,bigVideoRtxSsrc:a,auxVideoSsrc:c,auxVideoRtxSsrc:l}=r;this.ssrc={audio:s,video:n,videoRtx:a,auxiliary:c,auxiliaryRtx:l},this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc});try{let u=yield this._signalChannel.sendWaitForResponseWithRetry({command:Z.SPC_SUBSCRIBE,responseCommand:G.SPC_SUBSCRIBE_RESULT,data:{srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo,customData:!1,ssrc:r},retries:3,retryTimeout:0});if(u.data.code!==0&&u.data.code!==-10036)throw new D({code:u.data.code,message:u.data.message})}catch(u){throw yield this.removeDownlink(),u}return}this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc})}finally{if(!Sc)return;let{main:r,aux:s}=this._room.jitterBufferDelay||{},{jitterDelay:n=r,jitterDelayAux:a=s}=this._room.scheduleResult.config||{};(Q(n)||Q(a))&&this.setJitterBufferDelay({mainDelay:n,auxDelay:a})}}})}removeDownlink(){return f(this,null,function*(){if(!this.singlePC)return;this.ssrc={audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0},this.singlePC.removeDownlinkQueue.delete(this.tinyId);let e=this._room.scheduleResult.config;(e!=null&&e.jitterDelay||e!=null&&e.jitterDelayAux)&&this.setJitterBufferDelay({mainDelay:0,auxDelay:0}),yield this.singlePC.removeDownlink(this.userId)})}setJitterBufferDelay({mainDelay:e,auxDelay:t}){if(!Sc||!this.singlePC||!this._peerConnection||gt(e)&>(t))return Promise.resolve();this._log.info(`set jitterBuffer main: ${e} aux: ${t}`);let r=this.singlePC.getReceiversByUserId(this.userId);return Q(e)&&(this.remoteAudioTrack.jitterBufferDelay=e,this.remoteVideoTrack.jitterBufferDelay=e),Q(t)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=t,gt(e)&&(this.remoteAudioTrack.jitterBufferDelay=t)),new Promise(s=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:s})})}doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:s}){try{if(e===0&&t===0)return r.forEach(a=>a.jitterBufferTarget=0),s();if(r.forEach(a=>{var h;let c=a.track===this.remoteAuxiliaryTrack.outMediaTrack||gt(e)&&a.track===this.remoteAudioTrack.outMediaTrack;if(c&>(t)||!c&>(e))return;let l=c?t||0:e,u=(a.jitterBufferTarget||0)+100;u>l||(a.jitterBufferTarget=u,this._log.debug(`set ${c?"aux ":""}${(h=a==null?void 0:a.track)==null?void 0:h.kind} jitterBuffer delay ${u} -> ${l}`))}),!r.find(a=>{let c=a.track===this.remoteAuxiliaryTrack.outMediaTrack?t||0:e;return a.jitterBufferTarget<c}))return this._log.info(`set jitterBuffer main: ${e} aux: ${t} done`),s();this.jitterBufferTimeoutId=setTimeout(()=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:s})},1e3)}catch(n){this._log.warn(`set jitterBuffer delay error: ${n}`),clearTimeout(this.jitterBufferTimeoutId),s()}}get audioReceiver(){var e;return((e=this.singlePC)==null?void 0:e.getReceiversByUserId(this.userId)[0])||null}onDecodeFailed(){this._room.downlinkVideoCodec==="h265"&&this._room.requestRemoteFallbackToH264()}};O([ir(),Y(e=>function(...t){return new Promise((r,s)=>{let n=a=>{this.off("closed",n),s(new D({code:I.API_CALL_ABORTED,message:H({key:B.CONNECTION_ABORTED,data:a})}))};this.on("closed",n),e.apply(this,t).then(r,s).finally(()=>{this.off("closed",n)})})})],Ms.prototype,"subscribe",1),O([ir()],Ms.prototype,"unsubscribe",1),O([gi(()=>"jitter")],Ms.prototype,"setJitterBufferDelay",1);var $_=Ms;function W_(){return Y(o=>function(...i){return f(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(i=i.filter(t=>t.outMediaTrack&&t.state==="ready"),!i.length))return;S.emit("61",{room:this});let e=o.apply(this,i);return Promise.all(i.map(t=>t.publish(this,e)))})})}function G_(){return Y(o=>function(...i){let e=o.apply(this,i);return i.forEach(t=>t.unpublish()),e})}var J_=Je(at());function NI(){return Math.floor(Math.random()*16383)}var Vd=class Vd extends J_.EventEmitter{constructor(e,t){super();this.room=e;this.signalChannel=t;d(this,"log");d(this,"cmdIdSeqMap",new Map);d(this,"messageMap",new Map);this.log=R.createLogger({parent:e.getLogger(),id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),t.on(G.RECEIVE_CUSTOM_MSG,this.onReceiveMsg),this.room.on("peer-leave",r=>{[...this.messageMap.keys()].forEach(s=>{s.split("_").slice(0,-1).join("_")===r&&this.messageMap.delete(s)})})}send({cmdId:e,data:t}){let r=this.cmdIdSeqMap.get(e)||NI(),s={cmdId:e,msg:btoa(String.fromCharCode(...new Uint8Array(t))),ordered:!0,reliable:!0,streamSeq:r};this.cmdIdSeqMap.set(e,r+1),this.signalChannel.send(Z.SEND_CUSTOM_MSG,s),this.log.debug(`send custom msg: ${JSON.stringify(s)}`)}onReceiveMsg(e){let{data:t}=e.data,r=this.room.tinyIdToUserIdMap.get(t.srcTinyId);if(r){let s={userId:r,cmdId:t.cmdId,seq:t.streamSeq,data:Uint8Array.from(atob(t.msg),n=>n.charCodeAt(0)).buffer};if(t.ordered){let n=`${r}_${s.cmdId}`,a=this.messageMap.get(n);if(!a||a.lastSeq===0)a||(a={lastSeq:0,cachedMessageMap:new Map},this.messageMap.set(n,a),setTimeout(()=>this.emitMessage(s,!0),100)),a.cachedMessageMap.set(s.seq,{message:s});else if(Math.abs(a.lastSeq-s.seq)>Vd.SEQ_INTERVAL)this.messageMap.set(n,{lastSeq:s.seq,cachedMessageMap:new Map}),this.emitMessage(s);else if(s.seq>a.lastSeq){if(s.seq===a.lastSeq+1)this.emitMessage(s);else if(!a.cachedMessageMap.has(s.seq)){let c=setTimeout(()=>this.emitMessage(s,!0),5e3);a.cachedMessageMap.set(s.seq,{message:s,timeoutId:c})}}else this.log.debug(`drop message ${s.userId}-${s.cmdId}-${s.seq}`)}else this.emit("message",s)}else{this.log.warn(`receive msg from unknown user, wait peer-join tinyId: ${t.srcTinyId}`);let s=n=>{n.tinyId===t.srcTinyId&&(this.room.off("peer-join",s),this.onReceiveMsg(e))};this.room.on("peer-join",s),Ke(2e3).then(()=>this.room.off("peer-join",s))}}emitMessage(e,t=!1){var a;let r=this.messageMap.get(`${e.userId}_${e.cmdId}`),s=e;if(r){if(t){let c=[...r.cachedMessageMap.values()].sort((l,u)=>l.message.seq-u.message.seq);c[0]&&(s=c[0].message)}r.lastSeq!==0&&s.seq-r.lastSeq>1&&this.log.debug(`msg lost userId: ${s.userId} seq: ${r.lastSeq} -> ${s.seq}`),r.lastSeq=s.seq,clearTimeout((a=r.cachedMessageMap.get(s.seq))==null?void 0:a.timeoutId),r.cachedMessageMap.delete(s.seq)}this.log.debug(`receive custom msg: ${JSON.stringify(s)}`),this.emit("message",s);let n=r==null?void 0:r.cachedMessageMap.get(s.seq+1);n&&this.emitMessage(n.message)}};d(Vd,"SEQ_INTERVAL",300);var Ud=Vd;var{isString:q_,isUndefined:vo,getNetworkType:DI,isEmpty:OI}=vt,Ei=class extends wd{constructor(e){super(e);d(this,"_businessInfo");d(this,"userManager");d(this,"_version");d(this,"_heartbeat",-1);d(this,"_lastHeartBeatTime",-1);d(this,"_stats");d(this,"_joinTimeout",-1);d(this,"_firstPublishedList",null);d(this,"_joinReject",null);d(this,"_isRelayChanged",!1);d(this,"sdpSemantics");d(this,"signalChannel",null);d(this,"uplinkConnection",null);d(this,"singlePC",null);d(this,"enableSPC",ss);d(this,"_changeBigSmallRecords",new Map);d(this,"networkQuality");d(this,"_iceTransportPolicy");d(this,"forceRelay",!1);d(this,"_turnServers",[]);d(this,"_iceServersFromJoin");d(this,"_syncUserListInterval",-1);d(this,"_smallStreamConfig",{bitrate:100,frameRate:15,height:120,width:160});d(this,"enableSEI",!1);d(this,"_enableAudioVolumeEvaluation",!1);d(this,"_audioVolumeIntervalId",0);d(this,"_enableMultiAuxStream",!1);d(this,"_pureAudioPushMode",!1);d(this,"_customMessageManager");d(this,"preferHW",!1);d(this,"healthDetector");d(this,"playoutDelay");d(this,"jitterBufferDelay");d(this,"_updateAudioLevelTaskId",-1);d(this,"switchRoomSubedReq");d(this,"resolveSwitchRoomSubedReq");d(this,"enableVolumeControlInIOS");this._stats=new ra(this,this._log),this.userManager=new od(this.userId,this._log),this._version=$e,this.sdpSemantics=Mo,vo(e.sdpSemantics)?vi.isUnifiedPlanDefault()&&(this.sdpSemantics=gr):this.sdpSemantics=e.sdpSemantics,this._log.info(`sdpSemantics: ${this.sdpSemantics}, netType: ${DI()}`),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=vo(e.enableMultiAuxStream)?!1:e.enableMultiAuxStream,this.enableSEI=e.enableSEI&&ss,!vo(e.enableSPC)&&ss&&(this.enableSPC=e.enableSPC),this.preferHW=!!e.preferHW,this.enableVolumeControlInIOS=e.enableVolumeControlInIOS,this._initBusinessInfo(e),this.healthDetector=new M_(this)}get isMainStreamPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.isMainStreamPublished)}get isMainAudioPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.localMainAudioTrack)}get isAuxStreamPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.isAuxStreamPublished)}get hasAuxStream(){return[...this.remotePublishedUserMap.values()].findIndex(e=>e.muteState.hasAuxiliary)>=0}get userMap(){return this.userManager.userMap}get remotePublishedUserMap(){return this.userManager.remotePublishedUserMap}get tinyIdToUserIdMap(){return new Map([...this.userMap.values()].map(e=>[e.tinyId,e.userId]))}get videoCodec(){var e;return((e=this.singlePC)==null?void 0:e.videoCodec)||"h264"}get downlinkVideoCodec(){var e;return((e=this.singlePC)==null?void 0:e.downlinkVideoCodec)||"h264"}join(e,t,r){return f(this,null,function*(){return this.userManager.mySelfId=this.userId,this.userManager.on("1",s=>{this.emit("peer-join",s)}),this.userManager.on("2",s=>{this.closeDownLinkConnection(s,"remote user exitRoom"),this.emit("peer-leave",s)}),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",n=>{var s=aa(n,[]);S.emit(A.REMOTE_PUBLISH_STATE_CHANGED,M({room:this},s)),this.emit("remote-publish-state-changed",M({},s))}),this.joinParams=e,new Promise((s,n)=>f(this,null,function*(){var a,c;this._joinReject=n;try{this.checkDestroy();try{yield Promise.all([this.initialize(),this.initSinglePC()])}catch(u){if(u instanceof D&&u.code===I.SPC_INITIALIZED_FAILED)(a=this.signalChannel)==null||a.destroy(),yield this.initialize();else return n(u)}let l=U();yield this.doJoin(e,(c=this.singlePC)==null?void 0:c.clientAbility),v.addSuccessEvent({key:521708,cost:U()-l}),s(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(l){v.addFailedEvent({key:521708,error:l}),n(l)}this._joinReject=null}))})}initSinglePC(){return f(this,null,function*(){if(!(!this.enableSPC||this.singlePC)){this.singlePC=new Xt({signalChannel:this.signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.on("sei-message",e=>this.emit("sei-message",e)),this.singlePC.on("dump",e=>this.emit("dump",e)),this.singlePC.once("error",()=>this.fallbackToMPC());try{return yield this.singlePC.initialize()}catch(e){throw this.fallbackToMPC(),new D({code:I.SPC_INITIALIZED_FAILED,message:e==null?void 0:e.message})}}})}doJoin(e,t){return new Promise((r,s)=>f(this,null,function*(){var c,l,u;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this.signalChannel.once(Ie.SETUP_FAILED,h=>{this.clearJoinTimeout(),S.emit(A.JOIN_SIGNAL_CONNECTION_END,{room:this,error:h}),s(h)}),me((l=(c=this.scheduleResult)==null?void 0:c.config)==null?void 0:l.singlePC)&&ss&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2),t&&this.playoutDelay&&(t.playoutDelay=this.playoutDelay);let n={roomId:String(e.roomId||e.strRoomId),useStringRoomId:this.useStringRoomId,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel,trtcRole:e.role,trtcScene:this.scene==="live"?2:1,sdpSemantics:this.sdpSemantics,version:this._version,ua:navigator&&navigator.userAgent||"",terminalType:Ll(),netType:Jr(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig,receiveMix:!0,isChorus:!!this.enableChorus,enableNtpAudioFrame:!!this.enableChorus&&pn()};this._log.debug(`join room signal data: ${JSON.stringify(n)}`);let a=5e3;(u=this.scheduleResult.config)!=null&&u.enterRoomTimeout&&this.scheduleResult.config.enterRoomTimeout>=1&&(a=this.scheduleResult.config.enterRoomTimeout*1e3),this._joinTimeout=window.setTimeout(()=>{s(new D({code:I.JOIN_ROOM_FAILED,message:H({key:B.JOIN_ROOM_TIMEOUT})}))},a),S.emit(A.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?Z.SPC_JOIN_ROOM:Z.JOIN_ROOM,n),this.signalChannel.once(G.JOIN_ROOM_RESULT,h=>f(this,null,function*(){this.clearJoinTimeout();let{code:m,message:_,data:g,tinyId:E}=h.data;S.emit(A.JOIN_RECEIVED_CMD_RES,{room:this,code:m}),m===0?(this._log.info("Join room success, start heartbeat"),E&&(this.tinyId=E),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=g.publishers,this._iceServersFromJoin=g.iceServer?[g.iceServer]:[],this.singlePC&&this.singlePC.setIceServers(this.getIceServers()).then(()=>{var C;(C=this.singlePC)==null||C.connect(L(M({},g.ability),{useVp8:g.ability.useVp8||!!e.useVp8,useH265:g.ability.useH265&&!!e.useH265})).catch(()=>{})}),r()):(this._log.error(`Join room failed result: ${m} error: ${_}`),s(new D({code:I.JOIN_ROOM_FAILED,extraCode:m,message:H({key:B.JOIN_ROOM_FAILED,data:{error:_,code:m}})})))}))}))}reJoin(){return f(this,null,function*(){if(!this.isJoined){this._log.warn("reJoin abort");return}try{this._log.warn(`reJoin pending: ${this.joinParams.roomId}`);let e,t=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,t.push(this.initSinglePC().then(r=>(e=r,r)))),this.signalChannel&&(this.signalChannel.close(),t.push(this.signalChannel.connect())),yield Promise.all(t),yield this.doJoin(L(M({},this.joinParams),{role:this.role==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),e),this._log.warn("reJoin success"),oe.logSuccessEvent({userId:this.userId,eventType:Ze.REJOIN}),this.singlePC){let r=s=>{var n;s.state==="CONNECTED"&&((n=this.singlePC)==null||n.off(xi.CONNECTION_STATE_CHANGED,r),this.uplinkConnection instanceof hm&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach(a=>{a.installEvents(),a.onSinglePCReconnected()}))};this.singlePC.on(xi.CONNECTION_STATE_CHANGED,r),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof ia&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(e){this._log.warn(`reJoin fail ${e}`),this.reset(),oe.logFailedEvent({userId:this.userId,eventType:Ze.REJOIN,error:e}),this.emit("error",new D({code:I.JOIN_ROOM_FAILED,message:H({key:B.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}})}initialize(){return f(this,null,function*(){let{mainUrl:e,backupUrl:t}=this.getSignalChannelUrl(),r=this.signalChannel||r_(this.userId),s=!!(r&&r.isConnected&&r.keepAlive&&r.userId===this.userId&&r.room===this),n;return Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(n=this.scheduleResult.domains[0]),this._log.info(`${s?"reuse":"setup"} signal channel`),s?(r.url=e,r.backupUrl=t,r.room=this,this.signalChannel=r):(r&&r.close(),this.signalChannel=new bs({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:e,backupUrl:t,room:this,signalDomainWhenUnifiedProxy:this.proxy_unified?n:void 0}),this._customMessageManager=new Ud(this,this.signalChannel),this._customMessageManager.on("message",a=>{this.emit("custom-message",a)})),this.networkQuality||(this.networkQuality=new Os({signalChannel:this.signalChannel,room:this}),this.networkQuality.on(Os.EVENT_NETWORK_QUALITY,a=>{var c;this.emit("network-quality",a),(c=this.singlePC)==null||c.detectTCPAndUDP(a)})),tt(this,this.signalChannel).add(Ie.CONNECTION_STATE_CHANGED,a=>{S.emit(A.SIGNAL_CONNECTION_STATE_CHANGED,M({room:this},a)),this.emit("signal-connection-state-changed",a)}).add(Ie.RECONNECT_FAILED,a=>{this.reset(),this.emit("error",a)}).add(G.PEER_JOIN,a=>{let{srcTinyId:c,userId:l,role:u}=a.data.data;this.userManager.addUser({userId:l,tinyId:c,role:u})}).add(G.PEER_LEAVE,a=>{let{userId:c,reason:l=0}=a.data.data;this.userManager.deleteUser(c,l)}).add(G.UPDATE_REMOTE_MUTE_STAT,a=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=10*1e3&&this.doHeartbeat(),this.onPublishedUserList(a.data)}).add(G.CLIENT_BANNED,a=>{let c=a.data.data,{reason:l}=c;if(oe.uploadEvent({log:`stat-banned:${l}`,userId:this.userId}),l==="user_time_out"){this._log.warn(`${l} last heart beat time: ${this._lastHeartBeatTime} interval: ${Date.now()-this._lastHeartBeatTime}, visibility: ${document.visibilityState}`),this.reJoin();return}this._log[l==="kick"?"error":"info"](`user was banned because of [${l}]`),this.reset(),this.emit("banned",{reason:l})}).add(G.SEND_SWITCH_ROOM_SUBED_REQ,a=>{if(!this.singlePC)return;let{subList:c}=a.data.data;this._log.info(`auto subscribe ${_t(c,{keysToInclude:["userId"]})}`),c.forEach(l=>{this.singlePC.autoSubscribedUserMap.set(l.userId,l)}),this.resolveSwitchRoomSubedReq()}).add(G.FALLBACK_CODEC,a=>f(this,null,function*(){var l,u,h,m,_;let c=a.data.data;((l=c.videoControlInfo)==null?void 0:l.enableH265Enc)===0&&((u=this.singlePC)==null?void 0:u.videoCodec)==="h265"&&(this._log.warn(`fallback codec enableH265Enc: ${(h=c.videoControlInfo)==null?void 0:h.enableH265Enc}`),v.addCount({key:513e3}),yield(m=this.singlePC)==null?void 0:m.switchVideoEncoder("h264"),yield(_=this.uplinkConnection)==null?void 0:_.sendMediaSettings())})),this.signalChannel.once(Ie.SETUP_SUCCESS,a=>{this.tinyId=a.signalInfo.tinyId,S.emit(A.JOIN_SIGNAL_CONNECTION_END,{room:this})}),S.emit(A.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),s&&S.emit(A.JOIN_SIGNAL_CONNECTION_END,{room:this}),s})}setSignalChannel(e){this.signalChannel=e,e||Le(this)}leave(){return f(this,null,function*(){var e;try{yield this.doHeartbeat()}catch(t){}this._log.info("leave() => leaving room"),S.emit(A.LEAVE_SEND_CMD,{room:this}),(e=this.signalChannel)==null||e.send(Z.LEAVE_ROOM),this.switchRoomSubedReq=void 0})}clearNetworkQuality(){this.networkQuality&&(this.networkQuality.stop(),delete this.networkQuality)}closeConnections(){this.remotePublishedUserMap.forEach(e=>{this.closeDownLinkConnection(e.userId,"you exitRoom")})}clearJoinTimeout(){clearTimeout(this._joinTimeout),this._joinTimeout=-1}startHeartbeat(){this._heartbeat===-1&&(this._heartbeat=re.run("ric",this.doHeartbeat.bind(this),{delay:2e3}),this.enableChorus&&this.startUpdateNTPTime())}stopHeartbeat(){this._heartbeat!==-1&&(this._log.info("stopHeartbeat"),re.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return f(this,null,function*(){var n;let e=this.badCaseDetector.getMonitorFreeze(),t=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:e});this.badCaseDetector.resetMonitor();let r=(n=this.signalChannel)!=null&&n.isConnected?Ef(this.userId):[],s=L(M({str_sdk_version:Ls,uint64_datetime:new Date().getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_event_msg:r,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},t),{msg_device_info:M({uint32_terminal_type:15,str_device_name:ni(),str_os_version:"",uint32_net_type:Jr()},t.msg_device_info)});if(this.heartbeatReport=s,this.heartbeatCount++,S.emit(A.HEARTBEAT_REPORT,{room:this,report:s}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(Z.ON_QUALITY_REPORT,s);let a=Date.now();this._lastHeartBeatTime>0&&a-this._lastHeartBeatTime>1e4&&this._log.warn(`heartbeat took ${a-this._lastHeartBeatTime}`),this._lastHeartBeatTime=a,this.signalChannel.isOnline||(this._log.warn("signal channel is not online"),this.signalChannel.startReconnection())}this.emit("heartbeat-report",L(M({},s),{bytes_sent:this._stats.totalBytesSent+this.signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this.signalChannel.bytesReceived}))}!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)})}onPublishedUserList(e){if(!this.isJoined)return;let t=e.data.userList.filter(r=>r.flag!==Qd).map(({userId:r,srcTinyId:s,flag:n})=>{r===this.userId&&(this.uplinkConnection&&(this.uplinkConnection.flag=n),this.localPublishFlag!==n&&(this.localPublishFlag=n,this.emit("local-publish-flag-changed",n)));let a=this.remotePublishedUserMap.get(r);return a&&this.checkSubscribeBigSmallVideo(a),{userId:r,tinyId:s,flag:n}});e.data.mixRobotList.forEach(({userId:r,srcTinyId:s,flag:n,mixUserList:a})=>{t.unshift({userId:r,tinyId:s,flag:n,isRobot:!0,mixUserList:a})}),e.data.fakeMixUser&&(e.data.fakeMixUser.tinyId=e.data.fakeMixUser.srcTinyId,t.push(e.data.fakeMixUser)),S.emit(A.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:t}),t.find(r=>r.userId===this.userId)||(this.localPublishFlag=0,this.emit("local-publish-flag-changed",0)),this.userManager.setRemotePublishedUserList(t)}closeUplink(e="you unpublished"){this.uplinkConnection&&(this.localTracks.size>0&&this.uplinkConnection.doUnpublish().catch(()=>{}),this.uplinkConnection.close(e),this.uplinkConnection instanceof ia&&(this.uplinkConnection=null)),this.localTracks.forEach(t=>t.unpublish()),this.localTracks.clear()}createDownlinkConnection({userId:e,tinyId:t,flag:r,isRobot:s}){let n=new(this.singlePC?$_:tm)({userId:e,tinyId:t,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:r,isRobot:s});this.userManager.addRemotePublishedUser(n),this.installDownlinkEvents(n,e),this.emit("remote-published",n)}closeDownLinkConnection(e,t="remote user unpublished"){let r=this.remotePublishedUserMap.get(e);r&&(r.close(t),this.emit("remote-unpublished",r))}installDownlinkEvents(e,t){e.on("error",r=>{let s=r.getCode();s!==I.ICE_TRANSPORT_ERROR&&(s===I.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",r))}),e.on("connection-state-changed",r=>{this.emit("media-connection-state-changed",L(M({},r),{userId:e.userId}))}),e.on("firewall-restriction",()=>{this.emit("firewall-restriction")})}startSyncUserListInterval(){this._syncUserListInterval===-1&&(this._syncUserListInterval=re.run("ric",this.syncUserList.bind(this)))}stopSyncUserListInterval(){re.clearTask(this._syncUserListInterval),this._syncUserListInterval=-1}syncUserList(){return this.getUserList().then(e=>{this.userManager.setUserList(e)}).catch(e=>{this._log.debug(`sync user list failed: ${e}`)})}getUserList(){var e;return(e=this.signalChannel)!=null&&e.isConnected?this.signalChannel.sendWaitForResponse({command:Z.GET_USER_LIST,responseCommand:G.USER_LIST_RES,enableLog:!1,timeout:2e3}).then(({data:t})=>{let{code:r,message:s}=t;if(r===0)return(t.data&&t.data.userList||[]).map(({userId:a,srcTinyId:c,role:l})=>({userId:a,tinyId:c,role:l}));throw H({key:B.SIGNAL_RESPONSE_FAILED,data:{signalResponse:G.USER_LIST_RES,code:r,message:s}})}):Promise.reject("not connected")}getAllConnections(){let e=[...this.remotePublishedUserMap.values()];return this.uplinkConnection&&e.push(this.uplinkConnection),e}isRelayMaybeFailed(){if(this.signalChannel&&!this.signalChannel.isOnline||!zh)return!1;if(this.singlePC)return this.singlePC.reconnectionCount>6;let e=this.getAllConnections();if(e.length===0)return!1;for(let t=0;t<e.length;t++)if(e[t].getReconnectionCount()<6)return!1;return!0}checkConnectionsToReconnect(){var e;this.singlePC?((e=this.singlePC.getPeerConnection())==null?void 0:e.connectionState)===Re.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach(r=>{if(r instanceof pt&&!r.getIsReconnecting()){let s=r.getPeerConnection();s&&s.connectionState===Re.CLOSED&&(this._log.warn(`[${r.getUserId()}] pc is closed but not reconnect`),r.startReconnection())}})}fallbackToMPC(){return f(this,null,function*(){var e;if(this._log.warn("fallback to multi pc"),oe.uploadEvent({log:"stat-fallback",userId:this.userId}),this.enableSPC=!1,(e=this.singlePC)==null||e.close(),this.singlePC=null,this.isJoined&&(yield this.reJoin()),this.uplinkConnection){let t=this.uplinkConnection;this.uplinkConnection=new ia({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),t.isMainStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:t.localMainAudioTrack,localVideoTrack:t.localMainVideoTrack,isAuxiliary:!1})),t.isAuxStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:t.localAuxAudioTrack,localVideoTrack:t.localAuxVideoTrack,isAuxiliary:!0})),t.close()}for(let t of[...this.remotePublishedUserMap.values()]){let r=new tm({userId:t.userId,tinyId:t.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:t.flag,remoteAudioTrack:t.remoteAudioTrack,remoteVideoTrack:t.remoteVideoTrack,remoteAuxiliaryTrack:t.remoteAuxiliaryTrack});this.installDownlinkEvents(r,t.userId),this.remotePublishedUserMap.set(t.userId,r),t.isMainStreamSubscribed&&(yield r.subscribe(t.subscribeState,"main")),t.isAuxStreamSubscribed&&(yield r.subscribe(t.subscribeState,"auxiliary"))}})}destroy(){this.isDestroyed||(this.signalChannel&&(this._log.info("destroying SignalChannel"),this.signalChannel.close(),this.signalChannel=null),super.destroy(),this._joinReject&&(this._joinReject(new D({code:I.INVALID_OPERATION,message:H({key:B.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners(),this.healthDetector.destroy(),re.clearTask(this._audioVolumeIntervalId))}switchRole(e){return f(this,null,function*(){this.role!==e&&(e==="audience"&&this.uplinkConnection&&this.closeUplink("you switch role to audience"),yield this.doSwitchRole(e))})}doSwitchRole(e){let t={command:Z.SWITCH_ROLE,data:{role:e==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:G.SWITCH_ROLE_RES,retries:1};return this._log.info(`switchRole signal data: ${JSON.stringify(t.data)}`),this.signalChannel.sendWaitForResponseWithRetry(t).then(r=>{let{code:s,message:n}=r.data;if(s!==0)throw new D({code:I.SWITCH_ROLE_FAILED,message:H({key:B.SWITCH_ROLE_FAILED,data:{message:n,code:s}})});this.role=e}).catch(r=>{throw r instanceof D&&r.getCode()===I.API_CALL_TIMEOUT&&(r=new D({code:I.SWITCH_ROLE_FAILED,message:H({key:B.SWITCH_ROLE_TIMEOUT})})),this._log.error(r),r})}_initUplinkConnection(){this.uplinkConnection=this.singlePC?new hm({userId:this.userId,tinyId:this.tinyId,room:this}):new ia({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),this.uplinkConnection.on("connection-state-changed",e=>{this.emit("media-connection-state-changed",L(M({},e),{userId:this.userId}))}),this.uplinkConnection.on("firewall-restriction",()=>{this.emit("firewall-restriction")}),this.uplinkConnection.on("error",e=>{let t=e.getCode();t!==I.ICE_TRANSPORT_ERROR&&(t===I.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",e))})}publish(e){return f(this,null,function*(){var r;this.uplinkConnection||this._initUplinkConnection();let t=`${e.streamType} ${e.isAudio&&e.isScreen?"screen":""}${e.kind}`;this._log.info(`publish() => ${t}`),yield(r=this.singlePC)==null?void 0:r.waitForPeerConnectionConnected(),yield this.uplinkConnection.publish({localAudioTrack:e instanceof kt?e:null,localVideoTrack:e instanceof Xe?e:null,isAuxiliary:e.streamType==="auxiliary"||e.isScreen})})}unpublish(e){return f(this,null,function*(){if(!(this.scene==="live"&&this.role!=="anchor"||!this.isMainStreamPublished&&!this.isAuxStreamPublished||!this.uplinkConnection)){try{let t=`${e.streamType} ${e.isAudio&&e.isScreen?"screen":""}${e.kind}`;this._log.info(`unpublish() => ${t}`),yield this.uplinkConnection.unpublish({localAudioTrack:e instanceof kt?e:null,localVideoTrack:e instanceof Xe?e:null})}catch(t){}this.localTracks.size===0&&this.closeUplink("you unpublished")}})}addTrack(e){if(!this.uplinkConnection||!e.mediaTrack)return Promise.resolve();let t=this.uplinkConnection.addTrack(e);return e.publish(this,t),t}removeTrack(e){return!this.uplinkConnection||!e.mediaTrack?Promise.resolve():(e.unpublish(),this.uplinkConnection.removeTrack(e))}replaceTrack(e){return!this.uplinkConnection||!e.mediaTrack||!nu()?Promise.resolve():this.uplinkConnection.replaceTrack(e).then(t=>{t&&S.emit(A.LOCAL_TRACK_REPLACED,{track:e})})}setBandWidth(e){return f(this,null,function*(){this.uplinkConnection&&(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())})}enableSmall(e){return f(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:p.VIDEO,videoType:p.SMALL,bandwidth:this.uplinkConnection.localMainVideoTrack.small.bitrate})),yield this.uplinkConnection.enableSmall(e)})}subscribe(...e){return f(this,null,function*(){if(e=e.filter(n=>!n.isSubscribed),e.length===0)return;let{userId:t}=e[0],r=this.remotePublishedUserMap.get(t);if(!r)return;let s=e.find(n=>n.mediaType===2)?"auxiliary":"main";try{let n=M({},r.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:n.audio=!0;break;case 4:n.video=!0;break;case 8:n.smallVideo=!0;break;case 2:n.auxiliary=!0;break}});let a=this._changeBigSmallRecords.get(t);a&&a.options.smallVideo&&r.muteState.hasSmall&&n.video&&(n.video=!1,n.smallVideo=!0),S.emit(A.SUBSCRIBE_START,{room:this,streamType:s,remotePublishedUser:r,subscribeState:n}),this._log.info(`subscribe() => ${t} ${s} [${vd(n)}] prev: [${vd(r.subscribeState)}]`),yield r.subscribe(n,s),this._log.info(`subscribe ${t} ${s} done`);for(let c of e)c.mediaTrack||(yield c.waitHasMediaTrack());S.emit(A.SUBSCRIBE_SUCCESS,{room:this,streamType:s,remotePublishedUser:r})}catch(n){let a=n instanceof D?n.getCode():I.UNKNOWN,c=n;throw n instanceof D?a===I.REMOTE_STREAM_NOT_EXIST&&(c=new D({code:I.API_CALL_ABORTED,message:H({key:B.API_CALL_ABORTED,data:{message:n.message,userId:t,streamType:s}})}),this._log.warn(c)):(c=new D({code:a,message:H({key:B.SUBSCRIBE_FAILED,data:{message:n.message,userId:t,streamType:s}})}),this._log.error(c)),c}})}unsubscribe(...e){return f(this,null,function*(){let{userId:t}=e[0],r=this.remotePublishedUserMap.get(t);if(!r)return;let s=e.find(n=>n.mediaType===2)?"auxiliary":"main";this._log.info(`unsubscribe() => ${t} ${s}`);try{yield r.unsubscribe({remoteTracks:e,streamType:s})}catch(n){this._log.warn(`unsubscribe() => failed ${n}`)}e.forEach(n=>{n.unsubscribe(),n.mediaType===8&&n.setMediaType(4)}),S.emit(A.UNSUBSCRIBE_SUCCESS,{room:this,streamType:s,remotePublishedUser:r})})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAudioVolumeEvaluation(e=2e3,t){if(e<=0){this._enableAudioVolumeEvaluation=!1,re.clearTask(this._audioVolumeIntervalId);return}e=Math.floor(Math.max(e,100)),S.emit(A.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&re.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=re.run("intervalInWorker",()=>{var s;so.isRunning?this.stopUpdateAudioLevelFromSenderStat():this.updateAudioLevelFromSenderStat(e,t);let r=[];(s=this.remotePublishedUserMap)==null||s.forEach(n=>{if(n.muteState.hasAudio){!so.isRunning&&n.muteState.audioAvailable&&n.remoteAudioTrack.isSubscribed?this.updateDownlinkAudioLevelFromReceiver(n):n.remoteAudioTrack.volume=0;let a=Math.floor(n.remoteAudioTrack.getAudioLevel()*100);r.push({userId:n.userId,volume:a,floatVolume:n.remoteAudioTrack.getInternalAudioLevel()})}}),this.emit("audio-volume",r)},{delay:e,backgroundTask:t})}updateAudioLevelFromSenderStat(e,t){return f(this,null,function*(){var n;if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack||this._updateAudioLevelTaskId!==-1)return;let r=(n=this.uplinkConnection.getPeerConnection())==null?void 0:n.getSenders()[0];if(!r)return;let s=Math.max(e,500);this._log.warn(`updateAudioLevelFromSenderStat ${s}`),this._updateAudioLevelTaskId=re.run("intervalInWorker",()=>f(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack){this.stopUpdateAudioLevelFromSenderStat();return}let a=yield r.getStats();if(this._updateAudioLevelTaskId<0)return;let{localMainAudioTrack:c}=this.uplinkConnection;a.forEach(l=>{l.type==="media-source"&&l.audioLevel&&(c.volume=l.audioLevel)})}),{delay:s,backgroundTask:t})})}stopUpdateAudioLevelFromSenderStat(){var e;this._updateAudioLevelTaskId!==-1&&(this._log.warn("stopUpdateAudioLevelFromSenderStat"),re.clearTask(this._updateAudioLevelTaskId),this._updateAudioLevelTaskId=-1,(e=this.uplinkConnection)!=null&&e.localMainAudioTrack&&(this.uplinkConnection.localMainAudioTrack.volume=0))}updateDownlinkAudioLevelFromReceiver(e){var s;let{audioReceiver:t}=e;if(!au||!t)return;let r=(s=t.getSynchronizationSources()[0])==null?void 0:s.audioLevel;Q(r)?e.remoteAudioTrack.volume=Math.min(r*2,1):t.getStats().then(n=>{n.forEach(a=>{a.type==="inbound-rtp"&&Q(a.audioLevel)&&(e.remoteAudioTrack.volume=a.audioLevel)})})}getLocalAudioStats(){return f(this,null,function*(){var t;let e={};return e[this.userId]={bytesSent:0,packetsSent:0,audioLevel:0},(t=this.uplinkConnection)!=null&&t.localMainAudioTrack&&(e[this.userId]=this.uplinkConnection.localMainAudioTrack.stat),e})}getLocalVideoStats(){return f(this,null,function*(){var t,r;let e={};return e[this.userId]=((r=(t=this.uplinkConnection)==null?void 0:t.localMainVideoTrack)==null?void 0:r.stat)||{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0},e})}getTransportStats(){return f(this,null,function*(){let e={rtt:0,downlinksRTT:{}};if(this.uplinkConnection){let t=yield this._stats.getSenderStats(this.uplinkConnection);e.rtt=t.rtt}for(let[,t]of this.remotePublishedUserMap){let r=yield this._stats.getReceiverStats(t);e.downlinksRTT[r.userId]=r.rtt}return e})}getRemoteVideoStats(e){return f(this,null,function*(){let t={};for(let[r,s]of this.remotePublishedUserMap)e==="main"&&s.muteState.hasVideo&&(t[r]=s.remoteVideoTrack.stat),e==="auxiliary"&&s.muteState.hasAuxiliary&&(t[r]=s.remoteAuxiliaryTrack.stat);return t})}getRemoteAudioStats(){return f(this,null,function*(){let e={};for(let[t,r]of this.remotePublishedUserMap)r.muteState.hasAudio&&(e[t]=r.remoteAudioTrack.stat);return e})}setTurnServer(e,t){this._log.info(`set turn server: ${JSON.stringify(e)} ${t||""}`);let r=[];Array.isArray(e)?e.forEach(s=>r.push(vt.getTurnServer(s))):vt.isPlainObject(e)&&r.push(vt.getTurnServer(e)),this._turnServers=r,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:Z.START_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:G.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"}).catch(t=>{if(t.code!==I.API_CALL_ABORTED)throw t})}sendStopMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:Z.STOP_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:G.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"}).catch(t=>{if(t.code!==I.API_CALL_ABORTED)throw t})}sendStartPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?Z.START_PUBLISH_TENCENT_CDN:Z.START_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?G.START_PUBLISH_TENCENT_CDN_RES:G.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"}).catch(r=>{if(r.code!==I.API_CALL_ABORTED)throw r})}sendStopPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?Z.STOP_PUBLISH_TENCENT_CDN:Z.STOP_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?G.STOP_PUBLISH_TENCENT_CDN_RES:G.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"}).catch(r=>{if(r.code!==I.API_CALL_ABORTED)throw r})}sendStartPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Z.START_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:G.START_PUBLISH_CDN_STREAM_RES,commandDesc:"startPublishCDNStream"}).catch(t=>{if(t.code!==I.API_CALL_ABORTED)throw t})}sendUpdatePushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Z.UPDATE_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:G.UPDATE_PUBLISH_CDN_STREAM_RES,commandDesc:"updatePublishCDNStream"}).catch(t=>{if(t.code!==I.API_CALL_ABORTED)throw t})}sendStopPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Z.STOP_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:G.STOP_PUBLISH_CDN_STREAM_RES,commandDesc:"stopPublishCDNStream"}).catch(t=>{if(t.code!==I.API_CALL_ABORTED)throw t})}sendAbilityStatus(e){var t;(t=this.signalChannel)==null||t.sendWaitForResponse({command:Z.ABILITY_STATUS_REPORT,data:e,timeout:5e3,responseCommand:G.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch(r=>{})}getIceServers(e){var t,r;return this._turnServers.length>0?this._turnServers:(t=this.scheduleResult.iceServers)!=null&&t.length?this.scheduleResult.iceServers:e!=null&&e.length?e:(r=this._iceServersFromJoin)!=null&&r.length?this._iceServersFromJoin:[]}getIceTransportPolicy(){return this.forceRelay?"relay":this._iceTransportPolicy||this.scheduleResult.iceTransportPolicy||"all"}getLogger(){return this._log}enableAIVoice(){throw new Error("Method not implemented.")}getSignalChannelUrl(){let e={mainUrl:"",backupUrl:""},t=vt.getEnv();return t?(e.mainUrl=`wss://${t}.rtc.qq.com`,e.backupUrl=e.mainUrl):this.proxy_ws?(e.mainUrl=this.proxy_ws,e.backupUrl=e.mainUrl):this.proxy_unified?(e.mainUrl=`wss://${this.proxy_unified}`,e.backupUrl=e.mainUrl):Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(e.mainUrl=`wss://${this.scheduleResult.domains[0]}`,e.backupUrl=e.mainUrl,this.scheduleResult.domains[1]&&(e.backupUrl=`wss://${this.scheduleResult.domains[1]}`)),e}getSignalInfo(){var e;return((e=this.signalChannel)==null?void 0:e.getSignalInfo())||{clientIp:"",relayIp:""}}reset(e=!1){this.stopSyncUserListInterval(),this.stopHeartbeat(),this.closeConnections(),this.clearNetworkQuality(),this.closeUplink("you exitRoom"),this.signalChannel&&(e&&this.signalChannel.keepAlive&&this.signalChannel.isConnected?this.signalChannel.stopKeepAliveIn(3600):(this.signalChannel.close(),this.setSignalChannel(null))),this.localPublishFlag=0,this.heartbeatCount=0,this._stats.reset(),this.userManager.clear(),this.userManager.removeAllListeners(),this.singlePC&&(this.singlePC.close(),this.singlePC=null),this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}}checkSubscribeBigSmallVideo(e){return f(this,null,function*(){let{subscribeState:t,userId:r,muteState:{hasSmall:s,hasVideo:n}}=e;if(!s&&!n||!t.video&&!t.smallVideo)return;let a=this._changeBigSmallRecords.get(r);if(!a||a.isSubscribing||a.reSubscribeCount<=0)return;let{options:c,reSubscribeCount:l}=a;if(c.video&&t.video||c.smallVideo&&t.smallVideo&&s)return;let u={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:c.video,smallVideo:c.smallVideo};try{if(!s&&u.smallVideo&&(u.video=!0,u.smallVideo=!1),u.smallVideo===t.smallVideo&&u.video===t.video)return;a.isSubscribing=!0,a.reSubscribeCount=l-1,yield e.subscribe(u,"main"),e.remoteVideoTrack.setMediaType(u.smallVideo?8:4),this._log.info(`change [${r}] to ${u.smallVideo?"small":"big"} video successfully. count ${ko-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount=ko}catch(h){this._log.info(`change [${r}] to ${u.smallVideo?"small":"big"} video failed. count ${ko-a.reSubscribeCount}. reason: ${h}`),a.isSubscribing=!1,a.reSubscribeCount===0&&this._changeBigSmallRecords.delete(r)}})}changeType(e,t){let s={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:ko};this._changeBigSmallRecords.set(t.userId,s),this._log.info(`set [${t.userId}] video prefer type: ${e?"small":"big"}`),this.emit("subscribe-small-video-changed",{userId:t.userId,isSmall:e});let n=this.remotePublishedUserMap.get(t.userId);n&&this.checkSubscribeBigSmallVideo(n)}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(e){this._businessInfo=e.businessInfo;let t={};if(q_(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!vo(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new D({code:I.INVALID_PARAMETER,message:H({key:B.INVALID_PURE_AUDIO})});this._pureAudioPushMode=e.pureAudioPushMode,t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.pure_audio_push_mod=this._pureAudioPushMode}if(!vo(e.userDefineRecordId)){let r=/^[A-Za-z0-9_-]{1,64}$/gi;if(e.userDefineRecordId.match(r)===null)throw new D({code:I.INVALID_PARAMETER,message:H({key:B.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!vo(e.userDefinePushArgs))if(q_(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256)t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_push_args=e.userDefinePushArgs;else throw new D({code:I.INVALID_PARAMETER,message:H({key:B.INVALID_USER_DEFINE_PUSH_ARGS})});OI(t)||(this._businessInfo=JSON.stringify(t))}sendCustomMessage(e){var t;(t=this._customMessageManager)==null||t.send(e)}enableInsertableStreams(){return f(this,null,function*(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&mi)return this.singlePC.enableInsertableStreams=!0,yield this.singlePC.waitForPeerConnectionConnected(),yield this.singlePC.startReconnection()})}sendSignalMessage(e){var t;return this.signalChannel?(t=this.signalChannel)==null?void 0:t.sendWaitForResponseWithRetry(e):Promise.reject(new D({code:I.INVALID_OPERATION,message:"not join"}))}get enableCodecPipeline(){return this.videoManager.encodePipeline.length>0||this.videoManager.decodePipeline.length>0||this.audioManager.encodePipeline.length>0||this.audioManager.decodePipeline.length>0}get scriptTransformWorker(){var e;return(e=this.singlePC)==null?void 0:e.scriptTransformWorker}switchRoom(e){return f(this,null,function*(){var _;if(!this.signalChannel||!this.singlePC)return;let{roomId:t,strRoomId:r,userSig:s,privateMapKey:n}=e,a=((_=this.scheduleResult.config)==null?void 0:_.autoSubscribeCount)||(e==null?void 0:e.autoSubscribeCount)||1,c=String(this.useStringRoomId?r:t),l=[];for(let g=0;g<a;g++)l.push({audioSsrc:xt(),bigVideoSsrc:xt(),bigVideoRtxSsrc:xt(),auxVideoSsrc:xt(),auxVideoRtxSsrc:xt()});let u={currRoomId:this.roomId,targetRoomId:c,useStringRoomId:this.useStringRoomId,ability:this.singlePC.clientAbility,userSig:s,privateMapKey:n!=null?n:this.privateMapKey,subscribe:l};this.singlePC.autoSubscribedUserMap.clear(),this.singlePC.autoSubscribedSsrcGroups.clear(),this.singlePC.autoSubscribedSsrcGroups.set(c,l);let h=this.roomId;this.roomId=this.useStringRoomId?r:String(t),this.switchRoomSubedReq=new Promise(g=>{this.resolveSwitchRoomSubedReq=g,Ke(5e3).then(g)}),S.emit(A.SWITCH_ROOM_START,{room:this}),yield this.singlePC.waitForPeerConnectionConnected();let m;try{this.userManager.clear(),m=yield this.signalChannel.sendWaitForResponse({command:Z.SWITCH_ROOM,responseCommand:G.SEND_SWITCH_ROOM_RES,data:u});let{code:g,message:E}=m.data;if(g===0)this.userSig=s,vo(n)||(this.privateMapKey=n),S.emit(A.SWITCH_ROOM_SUCCESS,{room:this,currentRoomId:h,targetRoomId:c});else{this._log.error(`switch room failed. result: ${g} error: ${E}`);let C=new D({code:I.SWITCH_ROOM_FAILED,extraCode:g,message:E});throw S.emit(A.SWITCH_ROOM_FAILED,{room:this,error:C}),C}}catch(g){throw this.singlePC.autoSubscribedSsrcGroups.clear(),this.roomId=h,this.resolveSwitchRoomSubedReq(),g}})}isSwitchRoomSupported(){var t;let e="unable to use switchRoom API, fallback to exitRoom and enterRoom.";return((t=this.scheduleResult.config)==null?void 0:t.switchRoom)!==!0?(this._log.warn(`${e} Reason: this sdkAppId is not supported, please contact us [https://trtc.io/contact] to enable it.`),!1):this.scene!=="live"?(this._log.warn(`${e} Reason: the scene is not 'live'.`),!1):this.role!=="audience"?(this._log.warn(`${e} Reason: the role is not 'audience'.`),!1):this.singlePC?!0:(this._log.warn(`${e} Reason: is not using single peerConnection.`),!1)}requestRemoteFallbackToH264(){var e;(e=this.singlePC)==null||e.requestRemoteFallbackToH264()}startUpdateNTPTime(){if(!this.signalChannel)return;let e=[];for(let t=0;t<5;t++)e.push(this.updateNTPTime());return Promise.all(e).then(t=>{var c;let r=t[0].offset,s=t[0].offset;t.forEach(l=>{r=Math.min(l.offset,r),s=Math.max(l.offset,s)});let n=Math.floor(t.reduce((l,u)=>l+u.rtt,0)/t.length),a=Math.floor(t.reduce((l,u)=>l+u.offset,0)/t.length);(s-r>30||n>50)&&setTimeout(()=>this.startUpdateNTPTime(),5e3),da(a),(c=this.scriptTransformWorker)==null||c.postMessage({type:"ntp-offset",data:a}),this._log.debug(`ntp updated offset: ${a}`),this.emit("ntp-time-updated")}).catch(t=>{this._log.warn(`ntp updated failed: ${t}`)})}updateNTPTime(){let e=Date.now();return this.signalChannel.sendWaitForResponse({command:Z.UPDATE_NETWORK_TIME,responseCommand:G.UPDATE_NETWORK_TIME_RESULT,addReceiveTime:!0,data:{clientSendTime:String(e)},enableLog:!1}).then(t=>{let r=Number(t.data.data.serverSendTime),s=Number(t.data.data.serverRecvTime),n=t.data.receiveTime||Date.now(),a=(s-e+(r-n))/2;return{rtt:n-e-(s-r),offset:a}})}};O([ye(["left",q.INIT],"joined"),Ot({settings:{retries:1,timeout:0},onRetrying(e){this._log.warn(`join retry ${e}`)},onRetryFailed(e){this._log.error("join failed",e)},onError(e,t){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),Lt(!0),this.reset(),t()):this.signalChannel&&this.signalChannel.isConnected&&this.signalChannel.keepAlive?(this._log.warn("is using keepAlive ws, retry join"),this.signalChannel.close(),this.reset(),t()):(this.reset(),t())}}),Zf()],Ei.prototype,"join",1),O([ye("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),Kf(),xc("leave room"),yn({fnName:"publish",validateArgs:!1}),yn({fnName:"unsubscribe",validateArgs:!1})],Ei.prototype,"leave",1),O([gi(e=>e.mediaType),W_(),Ot({settings:{retries:Hi,timeout:e=>Kt(e)},onError(e,t,r,[s]){var n;(n=e.message)!=null&&n.includes("timeout")?(this._log.warn(`publish ${s.strMediaType} timeout`,e),t()):(this._log.error(`publish ${s.strMediaType} failed: ${e}`),r(e),S.emit(A.PUBLISH_FAILED,{room:this}))}})],Ei.prototype,"publish",1),O([yn({fnName:"publish"}),gi(e=>e.mediaType),G_(),Ct(function(){var e,t;this.localTracks.size===0&&Rr()&&((t=(e=this.singlePC)==null?void 0:e.getPeerConnection())==null||t.getSenders().forEach(r=>r.track&&r.replaceTrack(null)))})],Ei.prototype,"unpublish",1),O([kc(e=>{if(e.code!==I.API_CALL_ABORTED)throw e}),gi(e=>e.userId)],Ei.prototype,"replaceTrack",1),O([gi((...e)=>e[0].userId),Eo(),e_(),Ot({settings:{retries:Hi,timeout:e=>Kt(e)},onError(e,t,r,s){e.message.includes("timeout")?(this._log.warn("subscribe timeout"),t()):(this._log.error(`subscribe failed: ${e}`),r(e),S.emit(A.SUBSCRIBE_FAILED,{room:this,remoteTracks:s}))}})],Ei.prototype,"subscribe",1),O([yn({fnName:"subscribe",callback(...e){this.singlePC||e.forEach(t=>{let r=this.remotePublishedUserMap.get(t.userId);r&&!r.isMainStreamSubscribed&&!r.isAuxStreamSubscribed&&r.close("you unsubscribed")})}}),gi((...e)=>e[0].userId)],Ei.prototype,"unsubscribe",1);ea.create=ea._create.bind(ea,Ei);hu(30);var w4=ea;export{w4 as default};
|