trtc-sdk-v5 5.10.0-wasm.1 → 5.10.0-wasm.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/denoiser-wasm.js +1 -1
- package/assets/worker.js +8 -8
- package/index.d.ts +32 -7
- package/package.json +1 -1
- package/plugins/cdn-streaming/package.json +1 -1
- package/plugins/cross-room/package.json +1 -1
- package/plugins/custom-encryption/package.json +1 -1
- package/plugins/device-detector/device-detector.esm.js +8 -8
- package/plugins/device-detector/device-detector.umd.js +2 -2
- package/plugins/device-detector/package.json +1 -1
- package/plugins/video-decoder/package.json +1 -1
- package/plugins/video-decoder/video-decoder.esm.d.ts +20 -20
- package/plugins/video-decoder/video-decoder.esm.js +1 -1
- package/plugins/video-decoder/video-decoder.umd.js +1 -1
- package/plugins/video-effect/basic-beauty/package.json +1 -1
- package/plugins/video-effect/beauty/beauty.esm.js +1 -1
- package/plugins/video-effect/beauty/beauty.umd.js +1 -1
- package/plugins/video-effect/beauty/package.json +1 -1
- package/plugins/video-effect/virtual-background/package.json +1 -1
- package/plugins/video-effect/virtual-background/virtual-background.esm.js +1 -1
- package/plugins/video-effect/virtual-background/virtual-background.umd.js +1 -1
- package/plugins/video-effect/watermark/package.json +1 -1
- package/plugins/voice-changer/package.json +1 -1
- package/plugins/voice-changer/voice-changer.esm.js +1 -1
- package/plugins/voice-changer/voice-changer.umd.js +1 -1
- package/trtc.esm.js +44 -44
package/trtc.esm.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
var Mg=Object.create;var En=Object.defineProperty,Og=Object.defineProperties,bp=Object.getOwnPropertyDescriptor,Pg=Object.getOwnPropertyDescriptors,xg=Object.getOwnPropertyNames,Ap=Object.getOwnPropertySymbols,Rp=Object.getPrototypeOf,vp=Object.prototype.hasOwnProperty,kg=Object.prototype.propertyIsEnumerable,Lg=Reflect.get;var _n=Math.pow,Nu=(i,t,e)=>t in i?En(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e,Z=(i,t)=>{for(var e in t||(t={}))vp.call(t,e)&&Nu(i,e,t[e]);if(Ap)for(var e of Ap(t))kg.call(t,e)&&Nu(i,e,t[e]);return i},Ee=(i,t)=>Og(i,Pg(t));var Tn=(i,t)=>()=>(t||i((t={exports:{}}).exports,t),t.exports),qr=(i,t)=>{for(var e in t)En(i,e,{get:t[e],enumerable:!0})},Ug=(i,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of xg(t))!vp.call(i,o)&&o!==e&&En(i,o,{get:()=>t[o],enumerable:!(r=bp(t,o))||r.enumerable});return i};var Di=(i,t,e)=>(e=i!=null?Mg(Rp(i)):{},Ug(t||!i||!i.__esModule?En(e,"default",{value:i,enumerable:!0}):e,i));var X=(i,t,e,r)=>{for(var o=r>1?void 0:r?bp(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&&En(t,e,o),o};var u=(i,t,e)=>Nu(i,typeof t!="symbol"?t+"":t,e);var Bt=(i,t,e)=>Lg(Rp(i),e,t);var y=(i,t,e)=>new Promise((r,o)=>{var s=p=>{try{d(e.next(p))}catch(m){o(m)}},n=p=>{try{d(e.throw(p))}catch(m){o(m)}},d=p=>p.done?r(p.value):Promise.resolve(p.value).then(s,n);d((e=e.apply(i,t)).next())});var Ui=Tn((KS,sl)=>{"use strict";var FE=Object.prototype.hasOwnProperty,$t="~";function Xn(){}Object.create&&(Xn.prototype=Object.create(null),new Xn().__proto__||($t=!1));function HE(i,t,e){this.fn=i,this.context=t,this.once=e||!1}function ih(i,t,e,r,o){if(typeof e!="function")throw new TypeError("The listener must be a function");var s=new HE(e,r||i,o),n=$t?$t+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 Bc(i,t){--i._eventsCount===0?i._events=new Xn:delete i._events[t]}function Ot(){this._events=new Xn,this._eventsCount=0}Ot.prototype.eventNames=function(){var t=[],e,r;if(this._eventsCount===0)return t;for(r in e=this._events)FE.call(e,r)&&t.push($t?r.slice(1):r);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(e)):t};Ot.prototype.listeners=function(t){var e=$t?$t+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};Ot.prototype.listenerCount=function(t){var e=$t?$t+t:t,r=this._events[e];return r?r.fn?1:r.length:0};Ot.prototype.emit=function(t,e,r,o,s,n){var d=$t?$t+t:t;if(!this._events[d])return!1;var p=this._events[d],m=arguments.length,E,_;if(p.fn){switch(p.once&&this.removeListener(t,p.fn,void 0,!0),m){case 1:return p.fn.call(p.context),!0;case 2:return p.fn.call(p.context,e),!0;case 3:return p.fn.call(p.context,e,r),!0;case 4:return p.fn.call(p.context,e,r,o),!0;case 5:return p.fn.call(p.context,e,r,o,s),!0;case 6:return p.fn.call(p.context,e,r,o,s,n),!0}for(_=1,E=new Array(m-1);_<m;_++)E[_-1]=arguments[_];p.fn.apply(p.context,E)}else{var b=p.length,C;for(_=0;_<b;_++)switch(p[_].once&&this.removeListener(t,p[_].fn,void 0,!0),m){case 1:p[_].fn.call(p[_].context);break;case 2:p[_].fn.call(p[_].context,e);break;case 3:p[_].fn.call(p[_].context,e,r);break;case 4:p[_].fn.call(p[_].context,e,r,o);break;default:if(!E)for(C=1,E=new Array(m-1);C<m;C++)E[C-1]=arguments[C];p[_].fn.apply(p[_].context,E)}}return!0};Ot.prototype.on=function(t,e,r){return ih(this,t,e,r,!1)};Ot.prototype.once=function(t,e,r){return ih(this,t,e,r,!0)};Ot.prototype.removeListener=function(t,e,r,o){var s=$t?$t+t:t;if(!this._events[s])return this;if(!e)return Bc(this,s),this;var n=this._events[s];if(n.fn)n.fn===e&&(!o||n.once)&&(!r||n.context===r)&&Bc(this,s);else{for(var d=0,p=[],m=n.length;d<m;d++)(n[d].fn!==e||o&&!n[d].once||r&&n[d].context!==r)&&p.push(n[d]);p.length?this._events[s]=p.length===1?p[0]:p:Bc(this,s)}return this};Ot.prototype.removeAllListeners=function(t){var e;return t?(e=$t?$t+t:t,this._events[e]&&Bc(this,e)):(this._events=new Xn,this._eventsCount=0),this};Ot.prototype.off=Ot.prototype.removeListener;Ot.prototype.addListener=Ot.prototype.on;Ot.prefixed=$t;Ot.EventEmitter=Ot;typeof sl!="undefined"&&(sl.exports=Ot)});var Il=Tn((My,gh)=>{"use strict";var fh=gh.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(fh).forEach(function(i){var t=fh[i];t.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var Th=Tn(ii=>{"use strict";var Ps=function(i){return String(Number(i))===i?Number(i):i},QE=function(i,t,e,r){if(r&&!e)t[r]=Ps(i[1]);else for(var o=0;o<e.length;o+=1)i[o+1]!=null&&(t[e[o]]=Ps(i[o+1]))},YE=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;QE(e.match(i.reg),o,i.names,i.name),i.push&&t[i.push].push(o)},Eh=Il(),ZE=RegExp.prototype.test.bind(/^([a-z])=(.*)/);ii.parse=function(i){var t={},e=[],r=t;return i.split(/(\r\n|\r|\n)/).filter(ZE).forEach(function(o){var s=o[0],n=o.slice(2);s==="m"&&(e.push({rtp:[],fmtp:[]}),r=e[e.length-1]);for(var d=0;d<(Eh[s]||[]).length;d+=1){var p=Eh[s][d];if(p.reg.test(n))return YE(p,r,n)}}),t.media=e,t};var _h=function(i,t){var e=t.split(/=(.+)/,2);return e.length===2?i[e[0]]=Ps(e[1]):e.length===1&&t.length>1&&(i[e[0]]=void 0),i};ii.parseParams=function(i){return i.split(/;\s?/).reduce(_h,{})};ii.parseFmtpConfig=ii.parseParams;ii.parsePayloads=function(i){return i.toString().split(" ").map(Number)};ii.parseRemoteCandidates=function(i){for(var t=[],e=i.split(" ").map(Ps),r=0;r<e.length;r+=3)t.push({component:e[r],ip:e[r+1],port:e[r+2]});return t};ii.parseImageAttributes=function(i){return i.split(" ").map(function(t){return t.substring(1,t.length-1).split(",").reduce(_h,{})})};ii.parseSimulcastStreamList=function(i){return i.split(";").map(function(t){return t.split(",").map(function(e){var r,o=!1;return e[0]!=="~"?r=Ps(e):(r=Ps(e.substring(1,e.length)),o=!0),{scid:r,paused:o}})})}});var Sh=Tn((Py,Ih)=>{"use strict";var Sl=Il(),KE=/%[sdv%]/g,e_=function(i){var t=1,e=arguments,r=e.length;return i.replace(KE,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""}})},ea=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 e_.apply(null,o)},t_=["v","o","s","i","u","e","p","c","b","t","r","z","a"],r_=["i","c","b","a"];Ih.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||t_,r=t.innerOrder||r_,o=[];return e.forEach(function(s){Sl[s].forEach(function(n){n.name in i&&i[n.name]!=null?o.push(ea(s,n,i)):n.push in i&&i[n.push]!=null&&i[n.push].forEach(function(d){o.push(ea(s,n,d))})})}),i.media.forEach(function(s){o.push(ea("m",Sl.m[0],s)),r.forEach(function(n){Sl[n].forEach(function(d){d.name in s&&s[d.name]!=null?o.push(ea(n,d,s)):d.push in s&&s[d.push]!=null&&s[d.push].forEach(function(p){o.push(ea(n,d,p))})})})}),o.join(`\r
|
|
1
|
+
var Lg=Object.create;var gn=Object.defineProperty,Ug=Object.defineProperties,vp=Object.getOwnPropertyDescriptor,Vg=Object.getOwnPropertyDescriptors,Fg=Object.getOwnPropertyNames,Rp=Object.getOwnPropertySymbols,Cp=Object.getPrototypeOf,Dp=Object.prototype.hasOwnProperty,$g=Object.prototype.propertyIsEnumerable,Bg=Reflect.get;var En=Math.pow,Nu=(i,t,e)=>t in i?gn(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e,ee=(i,t)=>{for(var e in t||(t={}))Dp.call(t,e)&&Nu(i,e,t[e]);if(Rp)for(var e of Rp(t))$g.call(t,e)&&Nu(i,e,t[e]);return i},Ee=(i,t)=>Ug(i,Vg(t));var _n=(i,t)=>()=>(t||i((t={exports:{}}).exports,t),t.exports),Jr=(i,t)=>{for(var e in t)gn(i,e,{get:t[e],enumerable:!0})},Hg=(i,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Fg(t))!Dp.call(i,o)&&o!==e&&gn(i,o,{get:()=>t[o],enumerable:!(r=vp(t,o))||r.enumerable});return i};var Mi=(i,t,e)=>(e=i!=null?Lg(Cp(i)):{},Hg(t||!i||!i.__esModule?gn(e,"default",{value:i,enumerable:!0}):e,i));var X=(i,t,e,r)=>{for(var o=r>1?void 0:r?vp(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&&gn(t,e,o),o};var u=(i,t,e)=>Nu(i,typeof t!="symbol"?t+"":t,e);var Ft=(i,t,e)=>Bg(Cp(i),e,t);var y=(i,t,e)=>new Promise((r,o)=>{var s=p=>{try{d(e.next(p))}catch(m){o(m)}},n=p=>{try{d(e.throw(p))}catch(m){o(m)}},d=p=>p.done?r(p.value):Promise.resolve(p.value).then(s,n);d((e=e.apply(i,t)).next())});var $i=_n((ey,al)=>{"use strict";var JE=Object.prototype.hasOwnProperty,$t="~";function zn(){}Object.create&&(zn.prototype=Object.create(null),new zn().__proto__||($t=!1));function zE(i,t,e){this.fn=i,this.context=t,this.once=e||!1}function oh(i,t,e,r,o){if(typeof e!="function")throw new TypeError("The listener must be a function");var s=new zE(e,r||i,o),n=$t?$t+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 Fc(i,t){--i._eventsCount===0?i._events=new zn:delete i._events[t]}function Ot(){this._events=new zn,this._eventsCount=0}Ot.prototype.eventNames=function(){var t=[],e,r;if(this._eventsCount===0)return t;for(r in e=this._events)JE.call(e,r)&&t.push($t?r.slice(1):r);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(e)):t};Ot.prototype.listeners=function(t){var e=$t?$t+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};Ot.prototype.listenerCount=function(t){var e=$t?$t+t:t,r=this._events[e];return r?r.fn?1:r.length:0};Ot.prototype.emit=function(t,e,r,o,s,n){var d=$t?$t+t:t;if(!this._events[d])return!1;var p=this._events[d],m=arguments.length,g,_;if(p.fn){switch(p.once&&this.removeListener(t,p.fn,void 0,!0),m){case 1:return p.fn.call(p.context),!0;case 2:return p.fn.call(p.context,e),!0;case 3:return p.fn.call(p.context,e,r),!0;case 4:return p.fn.call(p.context,e,r,o),!0;case 5:return p.fn.call(p.context,e,r,o,s),!0;case 6:return p.fn.call(p.context,e,r,o,s,n),!0}for(_=1,g=new Array(m-1);_<m;_++)g[_-1]=arguments[_];p.fn.apply(p.context,g)}else{var b=p.length,N;for(_=0;_<b;_++)switch(p[_].once&&this.removeListener(t,p[_].fn,void 0,!0),m){case 1:p[_].fn.call(p[_].context);break;case 2:p[_].fn.call(p[_].context,e);break;case 3:p[_].fn.call(p[_].context,e,r);break;case 4:p[_].fn.call(p[_].context,e,r,o);break;default:if(!g)for(N=1,g=new Array(m-1);N<m;N++)g[N-1]=arguments[N];p[_].fn.apply(p[_].context,g)}}return!0};Ot.prototype.on=function(t,e,r){return oh(this,t,e,r,!1)};Ot.prototype.once=function(t,e,r){return oh(this,t,e,r,!0)};Ot.prototype.removeListener=function(t,e,r,o){var s=$t?$t+t:t;if(!this._events[s])return this;if(!e)return Fc(this,s),this;var n=this._events[s];if(n.fn)n.fn===e&&(!o||n.once)&&(!r||n.context===r)&&Fc(this,s);else{for(var d=0,p=[],m=n.length;d<m;d++)(n[d].fn!==e||o&&!n[d].once||r&&n[d].context!==r)&&p.push(n[d]);p.length?this._events[s]=p.length===1?p[0]:p:Fc(this,s)}return this};Ot.prototype.removeAllListeners=function(t){var e;return t?(e=$t?$t+t:t,this._events[e]&&Fc(this,e)):(this._events=new zn,this._eventsCount=0),this};Ot.prototype.off=Ot.prototype.removeListener;Ot.prototype.addListener=Ot.prototype.on;Ot.prefixed=$t;Ot.EventEmitter=Ot;typeof al!="undefined"&&(al.exports=Ot)});var yl=_n((Oy,Eh)=>{"use strict";var gh=Eh.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(gh).forEach(function(i){var t=gh[i];t.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var Ih=_n(si=>{"use strict";var Ps=function(i){return String(Number(i))===i?Number(i):i},r_=function(i,t,e,r){if(r&&!e)t[r]=Ps(i[1]);else for(var o=0;o<e.length;o+=1)i[o+1]!=null&&(t[e[o]]=Ps(i[o+1]))},i_=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;r_(e.match(i.reg),o,i.names,i.name),i.push&&t[i.push].push(o)},_h=yl(),o_=RegExp.prototype.test.bind(/^([a-z])=(.*)/);si.parse=function(i){var t={},e=[],r=t;return i.split(/(\r\n|\r|\n)/).filter(o_).forEach(function(o){var s=o[0],n=o.slice(2);s==="m"&&(e.push({rtp:[],fmtp:[]}),r=e[e.length-1]);for(var d=0;d<(_h[s]||[]).length;d+=1){var p=_h[s][d];if(p.reg.test(n))return i_(p,r,n)}}),t.media=e,t};var Th=function(i,t){var e=t.split(/=(.+)/,2);return e.length===2?i[e[0]]=Ps(e[1]):e.length===1&&t.length>1&&(i[e[0]]=void 0),i};si.parseParams=function(i){return i.split(/;\s?/).reduce(Th,{})};si.parseFmtpConfig=si.parseParams;si.parsePayloads=function(i){return i.toString().split(" ").map(Number)};si.parseRemoteCandidates=function(i){for(var t=[],e=i.split(" ").map(Ps),r=0;r<e.length;r+=3)t.push({component:e[r],ip:e[r+1],port:e[r+2]});return t};si.parseImageAttributes=function(i){return i.split(" ").map(function(t){return t.substring(1,t.length-1).split(",").reduce(Th,{})})};si.parseSimulcastStreamList=function(i){return i.split(";").map(function(t){return t.split(",").map(function(e){var r,o=!1;return e[0]!=="~"?r=Ps(e):(r=Ps(e.substring(1,e.length)),o=!0),{scid:r,paused:o}})})}});var yh=_n((Py,Sh)=>{"use strict";var Al=yl(),s_=/%[sdv%]/g,n_=function(i){var t=1,e=arguments,r=e.length;return i.replace(s_,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""}})},ea=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 n_.apply(null,o)},a_=["v","o","s","i","u","e","p","c","b","t","r","z","a"],c_=["i","c","b","a"];Sh.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||a_,r=t.innerOrder||c_,o=[];return e.forEach(function(s){Al[s].forEach(function(n){n.name in i&&i[n.name]!=null?o.push(ea(s,n,i)):n.push in i&&i[n.push]!=null&&i[n.push].forEach(function(d){o.push(ea(s,n,d))})})}),i.media.forEach(function(s){o.push(ea("m",Al.m[0],s)),r.forEach(function(n){Al[n].forEach(function(d){d.name in s&&s[d.name]!=null?o.push(ea(n,d,s)):d.push in s&&s[d.push]!=null&&s[d.push].forEach(function(p){o.push(ea(n,d,p))})})})}),o.join(`\r
|
|
2
2
|
`)+`\r
|
|
3
|
-
`}});var yh=Tn(oi=>{"use strict";var Co=Th(),i_=Sh();oi.write=i_;oi.parse=Co.parse;oi.parseParams=Co.parseParams;oi.parseFmtpConfig=Co.parseFmtpConfig;oi.parsePayloads=Co.parsePayloads;oi.parseRemoteCandidates=Co.parseRemoteCandidates;oi.parseImageAttributes=Co.parseImageAttributes;oi.parseSimulcastStreamList=Co.parseSimulcastStreamList});var Cp=(ee=>(ee[ee.INVALID_PARAMETER=4096]="INVALID_PARAMETER",ee[ee.INVALID_OPERATION=4097]="INVALID_OPERATION",ee[ee.NOT_SUPPORTED=4098]="NOT_SUPPORTED",ee[ee.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",ee[ee.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",ee[ee.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",ee[ee.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",ee[ee.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",ee[ee.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",ee[ee.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",ee[ee.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",ee[ee.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",ee[ee.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",ee[ee.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",ee[ee.CLIENT_BANNED=16448]="CLIENT_BANNED",ee[ee.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",ee[ee.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",ee[ee.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",ee[ee.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",ee[ee.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",ee[ee.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",ee[ee.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",ee[ee.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",ee[ee.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",ee[ee.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",ee[ee.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",ee[ee.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",ee[ee.API_CALL_ABORTED=16461]="API_CALL_ABORTED",ee[ee.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",ee[ee.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",ee[ee.UNKNOWN=65535]="UNKNOWN",ee))(Cp||{}),te=Cp;var Vg=function(i){for(let t in te)if(te[t]===i)return t;return"UNKNOWN"},Du=class extends Error{constructor({name:e="RtcError",message:r,code:o=te.UNKNOWN,extraCode:s=0,constraint:n}){let d=`<${Vg(o)} 0x${o.toString(16)}>`,p=`${r}${n?` constraint: ${n}`:""}${r!=null&&r.includes(d)?"":` ${d}`}`;super(p);u(this,"code");u(this,"extraCode");u(this,"message");u(this,"originMessage");u(this,"name");u(this,"constraint");this.code=o,this.extraCode=s,this.name=e,this.message=p,this.constraint=n,this.originMessage=r}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},he=Du;var OS=new Date().getTime(),Bg=0;var In=function(){return new Date().getTime()+Bg},sc=function(){let i=new Date;return i.setTime(In()),i.toLocaleString()};var Lr={};qr(Lr,{bytes2ms:()=>Up,convertObjectNumberToInt:()=>On,copyProperties:()=>Lp,deepClone:()=>go,deepMerge:()=>kr,delay:()=>Pn,fibonacci:()=>Eo,formatedTime:()=>Ec,getConstructorName:()=>wn,getContainerFromElement:()=>jp,getEnv:()=>Pp,getInternalVersion:()=>Wp,getLoggerUrl:()=>Qr,getMuteStateFromFlag:()=>Mn,getNetworkType:()=>Nn,getNumNetworkType:()=>fc,getReconnectionTimeout:()=>Bp,getStringByteLength:()=>qp,getTurnServer:()=>Gp,getUint32Version:()=>Ic,getValueType:()=>mt,getViewListFromView:()=>gs,glog:()=>Dn,ipv4ToUint32:()=>fs,isArray:()=>st,isAudioWorkletSupported:()=>Hp,isBoolean:()=>dt,isConstructor:()=>ps,isEmpty:()=>hs,isFunction:()=>ze,isLangChinese:()=>hr,isMediaStreamTrack:()=>$p,isNumber:()=>je,isObject:()=>xr,isOverseaSdkAppId:()=>Cn,isPlainObject:()=>Gt,isPortrait:()=>Tc,isPromise:()=>Mi,isRemoteTrack:()=>Fp,isString:()=>we,isUndefined:()=>$,loadImage:()=>Es,ms2bytes:()=>Vp,ms2samples:()=>Fu,performanceNow:()=>_e,promiseAny:()=>gc,samples2ms:()=>$u,setNetworkType:()=>kp,stringify:()=>rr,stringifyIncludeValue:()=>_c,throttlePromise:()=>Sc});var Bu={};qr(Bu,{AUDIO_MUTE_BIT:()=>lc,AUDIO_STAT_BIT:()=>ls,AUX_STAT_BIT:()=>An,AUX_STREAM_MSID:()=>Yg,BACKEND_ENV:()=>uc,BASE_DOC_URL:()=>Mr,BASE_HOST:()=>Np,CAPABILITIES_KEYS:()=>hc,CLASS_NAME:()=>SE,CLOUD_CONSOLE_URL:()=>Wg,CROSS_ROOM_BIT:()=>Xg,DATA_FREEZE_TIMING:()=>pc,DEFAULT_ASSETS_URL:()=>nc,DOC_URL:()=>Gg,DTLS_STATE_UNKNOWN:()=>aE,ENV_NAME:()=>Jr,EXCHANGE_SDP_TIMEOUT:()=>pE,IS_WORKER:()=>ds,IS_WORKLET:()=>Sn,KIBANA_EVENT:()=>zr,LOCAL_STREAM_PUBLISH_STATE:()=>wp,LOGGER_CMD_TYPE:()=>wi,LOGGER_DOMAIN:()=>Ou,LOGGER_DOMAIN_OVERSEA:()=>Pu,LOG_LEVEL:()=>pr,LOG_LEVEL_NAME:()=>AE,MAIN_STREAM_MSID:()=>Qg,MAX_RTT:()=>Rn,MICROPHONE_COMMUNICATIONS:()=>yE,MICROPHONE_DEFAULT:()=>fo,MUTE_ALL_BIT:()=>zg,NAME:()=>D,NETWORK_TYPE:()=>ho,NOT_SUPPORTED_H264:()=>fE,PAUSED_RETRY_COUNT:()=>Vu,PEERCONNECTION_CONNECTING_TIMEOUT:()=>TE,PEER_CONNECTION_STATE:()=>cE,PEER_LEAVE_REASON:()=>Mp,RECOVER_CAPTURE_INTERVAL:()=>ms,REMOTE_STREAM_TYPE_AUX:()=>Kg,REMOTE_STREAM_TYPE_MAIN:()=>Zg,RENDER_FREEZE_TIMING:()=>gE,SCHEDULE_DOMAIN:()=>Xr,SCHEDULE_TIMEOUT:()=>IE,SDP_SEMANTICS_PLAN_B:()=>hE,SDP_SEMANTICS_UNIFIED_PLAN:()=>Uu,SECOND_HOST:()=>Fg,SIGNAL_PING_PONG_INTERVAL:()=>qg,SIGNAL_PING_TIMEOUT:()=>jg,SIGNAL_RECONNECTION_COUNT:()=>uE,SMALL_STAT_BIT:()=>ku,SPEAKER_DEFAULT:()=>bn,STORAGE_EXPIRES_TIME:()=>ac,STREAM_TYPE_BIG:()=>EE,STREAM_TYPE_SMALL:()=>_E,SUBSCRIBE_SMALL_RETRY_COUNT:()=>bE,SYNC_USER_LIST_INTERVAL:()=>lE,Scene:()=>Pr,THIRD_HOST:()=>Hg,TRANSPORT_DIRECTION:()=>Jg,TRTC_ERROR_ASSISTANCE:()=>xu,TRTC_QUALITY_BAD:()=>oE,TRTC_QUALITY_DISCONNECTED:()=>nE,TRTC_QUALITY_EXCELLENT:()=>tE,TRTC_QUALITY_GOOD:()=>rE,TRTC_QUALITY_POOR:()=>iE,TRTC_QUALITY_UNKNOWN:()=>eE,TRTC_QUALITY_VERY_BAD:()=>sE,UPDATE_OFFER_TIMEOUT:()=>mE,VIDEO_MUTE_BIT:()=>mc,VIDEO_STAT_BIT:()=>us,audioProfileMap:()=>cc,getRetryCount:()=>dE,getScriptDir:()=>$g,innerVersion:()=>wu,loggerProxy:()=>yn,screenProfileMap:()=>dc,setLoggerProxy:()=>po,setRetryCount:()=>Lu,setVersion:()=>Mu,version:()=>rt,videoProfileMap:()=>Or});var wu="4.15.00.1600",rt="5.0.0";function Mu(i){rt=i;let[t,e,r]=i.split(".").map(o=>parseInt(o,10));wu=`${t}.${Math.min(15,e)}.${Math.min(15,r)}.${e.toString().padStart(2,"0")}${r.toString().padStart(2,"0")}`}var ds=typeof importScripts!="undefined",Sn=typeof registerProcessor!="undefined",$g=()=>{let i=ds?self.location.href:document.currentScript.src;return i.substring(0,i.lastIndexOf("/")+1)},yn="",po=i=>yn=i,Np="web.sdk.qcloud.com",Fg="web.sdk.tencent.cn",Hg="web.sdk.cloud.tencent.cn",Wg="https://console.cloud.tencent.com/trtc",Mr=`https://${Np}/trtc/webrtc/v5/doc`,nc="https://web.sdk.qcloud.com/trtc/webrtc/v5/assets/",Gg=`${Mr}/zh-cn/`,Ou="https://yun.tim.qq.com",Pu="https://apisgp.my-imcloud.com",xu="trtc_error_assistance",wi={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},Jr={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},pr=(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))(pr||{}),jg=18e3,qg=2e3,ho={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5,"5g":6},ac=7*24*3600*1e3,cc={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}},Or={"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}},dc={"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}},D={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"},Jg={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},uc={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},Pr=(e=>(e.LIVE="live",e.RTC="rtc",e))(Pr||{}),us=1,ku=2,An=4,ls=8,lc=64,mc=16,zg=112,Xg=128,Qg="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",Yg="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",Zg=D.MAIN,Kg=D.AUXILIARY,eE=0,tE=1,rE=2,iE=3,oE=4,sE=5,nE=6,aE="unknown",cE={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},Dp=1/0;function Lu(i){Dp=i}function dE(){return Dp}var uE=30,zr={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"},lE=1e4,mE=1e4,pE=1e4,Uu="unified-plan",hE="plan-b",fE=1028,wp=(r=>(r[r.UNPUBLISH=-1]="UNPUBLISH",r[r.PUBLISHING=0]="PUBLISHING",r[r.PUBLISHED=1]="PUBLISHED",r))(wp||{}),pc=500,gE=1e3,EE=D.BIG,_E=D.SMALL,TE=10*1e3,Xr={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"},IE=2e3,SE={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},Vu=5,fo="default",bn=fo,yE="communications",AE=Object.keys(pr),Mp=["normal leave","timeout leave","kick","role change"],bE=10,ms=2e3,hc=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],Rn=10*1e3;var Pp=function(){return new URLSearchParams(location.search).get("trtc_env")||""},Cn=i=>Number(i)<14e8,Qr=function(i,t){let e;yn?e=yn:e=Cn(i)?Pu:Ou;let r=Math.floor(Math.random()*_n(2,31));return`${e}/v5/AVQualityReportSvc/C2S?random=${r}&sdkappid=${i}&cmdtype=${t}`},vn="unknown";function Nn(){if(vn!=="unknown")return vn;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&&(vn=xp(r,o)),vn}function xp(i,t){if(ho[i])return i;switch(i){case"cellular":case"wimax":return t||"unknown";case"ethernet":return"wired";case"none":case"other":default:return"unknown"}}function kp(i){vn=xp(i)}function fc(){return ho[Nn()]}function Lp(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 Up(i,t=48e3){return $u(i/4,t)}function $u(i,t=48e3){return i*1e3/t}function Vp(i,t=48e3){return Fu(i,t)*4}function Fu(i,t=48e3){return i*t/1e3}var Dn=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},hr=()=>{let i=navigator.language;return i=i.substring(0,2),i==="zh"},Gt=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 Eo(i,t=1,e=1){return i<=1?e:Eo(i-1,e,t+e)}function Bp(i){return i>8?30*1e3:Eo(i)*1e3}function mt(i){return Reflect.apply(Object.prototype.toString,i,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var ze=i=>typeof i=="function",$=i=>typeof i=="undefined",we=i=>typeof i=="string",je=i=>typeof i=="number",dt=i=>typeof i=="boolean",xr=i=>mt(i)==="object",st=i=>mt(i)==="array",$p=i=>mt(i)==="MediaStreamTrack".toLowerCase(),Fp=i=>i.isRemote,Mi=i=>mt(i)==="promise",ps=i=>ze(i)&&i.prototype.constructor===i,wn=i=>ps(i)?i.prototype.constructor.name:"",Hp=typeof AudioWorkletNode!="undefined";function gc(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 _e(){return!performance||!performance.now?Date.now():Math.floor(performance.now())}var Op=i=>+i<10?`0${i}`:i,Wp=i=>{let t=i.match(/^\d+\.\d+\.\d+/)[0];if(!t)return i;let e=t.split("."),r=Op(e[1])+Op(e[2]);return e[1]-15>0&&(e[1]="15"),e[2]-15>0&&(e[2]="15"),`${e.join(".")}.${r}`},RE=Object.prototype.hasOwnProperty,{toString:US}=Object.prototype;function hs(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(Gt(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(RE.call(i,t))return!1;return!0}}return!1}function Mn(i,t){return{userId:t,hasAudio:!!(i&ls),hasVideo:!!(i&us),hasAuxiliary:!!(i&An),hasSmall:!!(i&ku),audioMuted:!!(i&lc),videoMuted:!!(i&mc),audioAvailable:!!(i&ls)&&!(i&lc),videoAvailable:!!(i&us)&&!(i&mc)}}function Gp(i){let t={urls:i.url.startsWith("turn:")||i.url.startsWith("turns:")?i.url:`turn:${i.url}`};return!$(i.username)&&!$(i.credential)&&(t.username=i.username,t.credential=i.credential,t.credentialType="password",$(i.credentialType)||(t.credentialType=i.credentialType)),t}function fs(i,t=!0){if(!we(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 kr=function(i,t,e,r){if(!(xr(i)&&xr(t)))return 0;let o=0,s=Object.keys(t),n;for(let d=0,p=s.length;d<p;d++)if(n=s[d],!($(t[n])||e&&e.includes(n)))if(xr(i[n])&&xr(t[n]))o+=kr(i[n],t[n],e,r);else{if(r&&r.includes(t[n]))continue;i[n]!==t[n]&&(i[n]=go(t[n]),o+=1)}return o};function go(i){if(st(i)){let t=[];return i.forEach((e,r)=>{t[r]=go(e)}),t}if(xr(i)){let t={};return Object.keys(i).forEach(e=>{t[e]=go(i[e])}),t}return i}var gs=i=>{let t=[];if(st(i))t=[...i];else if(we(i)){let e=document.getElementById(i);e&&t.push(e)}else i&&t.push(i);return t},jp=i=>we(i)?document.getElementById(i):i,vE=i=>{let t=p=>p<10?`0${p}`:`${p}`,e=i.getFullYear(),r=i.getMonth()+1,o=i.getDate(),s=t(i.getHours()),n=t(i.getMinutes()),d=t(i.getSeconds());return`${e}/${r}/${o} ${s}:${n}:${d}`},Ec=()=>vE(new Date);function rr(i,{keysToInclude:t,keysToExclude:e}){try{if(st(i))return`[${i.map(n=>rr(n,{keysToInclude:t,keysToExclude:e})).join(",")}]`;if(!Gt(i)||!st(t)&&!st(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]=Gt(i[n])||st(i[n])?JSON.parse(rr(i[n],{keysToExclude:e,keysToInclude:t})):i[n])}),JSON.stringify(r)}catch(r){return"{}"}}function _c(i,t=!1){let e=[];return Object.keys(i).forEach(r=>{t===i[r]&&e.push(r)}),rr(i,{keysToInclude:e})}function qp(i){return i.replace(/[\u4e00-\u9fa5]/g,"aa").length}var Tc=()=>{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},Es=i=>y(void 0,null,function*(){return new Promise((t,e)=>{let r;if(we(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 he({code:te.INVALID_PARAMETER,message:`load image failed, url: ${i}`}))}})}),Ic=i=>{let t=i.split(".");return+t[0]<<24|+t[1]<<16|+t[2]<<8|+t[3]<<0},On=i=>(Object.keys(i).forEach(t=>{je(i[t])&&(t.startsWith("uint")||t.startsWith("int"))?i[t]=Math.floor(i[t]):(Gt(i[t])||st(i[t]))&&On(i[t])}),i);function Pn(i,t){return new Promise(e=>{let r=setTimeout(e,i);t&&t(r)})}function Sc(i,t){let e=null;return function(...r){return e||(e=i.apply(t||this,r),e.finally(()=>e=null),e)}}function Yr({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(p=>p.text()).then(p=>{try{s({data:JSON.parse(p)})}catch(m){s({data:p})}},n);let d=new XMLHttpRequest;d.onreadystatechange=()=>{if(d.readyState===4)if(d.status>=200&&d.status<300)try{let p=JSON.parse(d.response);s({data:p})}catch(p){s({data:d.response})}else n({status:d.status,statusText:d.statusText||"request failed!"})},d.timeout=r||5e3,d.open(e,i,!0),d.send(t)})}function Hu(i){return y(this,null,function*(){let t=_e(),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")),d=yield(yield(yield new Response(o)).blob()).arrayBuffer();return B.debug(`compressJSON ${e.length} -> ${d.byteLength} ${_e()-t}ms`),d}catch(r){return e}})}var CE=Object.prototype.hasOwnProperty;var Oi=i=>typeof i=="function",Jp=i=>typeof i=="undefined";var zp=i=>typeof i=="boolean";var Wu=i=>i.isRemote;var NE=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 Xp(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(NE(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(CE.call(i,t))return!1;return!0}}return!1}var DE=0,wE=1,Qp=2;function ME({retryFunction:i,settings:t,onError:e,onRetrying:r,onRetryFailed:o,onRetrySuccess:s,context:n}){return function(...d){let{retries:p=5,timeout:m=1e3}=t,E=0,_=-1,b=DE,C=(k,x)=>y(this,null,function*(){let P=n||this;try{let J=yield i.apply(P,d);E>0&&s&&s.call(this,E),E=0,k(J)}catch(J){let Q=()=>{clearTimeout(_),E=0,b=Qp,x(J)},De=()=>{b!==Qp&&E<(Oi(p)?p():p)?(E++,b=wE,Oi(r)&&r.call(this,E,Q),_=window.setTimeout(()=>{_=-1,C(k,x)},Oi(m)?m(E):m)):(Q(),Oi(o)&&o.call(this,J))};Oi(e)?e.call(this,{error:J,retry:De,reject:x,retryFuncArgs:d,retriedCount:E}):De()}});return new Promise(C)}}var Pi=ME;var _s=class{constructor(t){u(this,"userId");u(this,"remoteUserId");u(this,"id");u(this,"sdkAppId");u(this,"type");u(this,"isLocal");this.id=t.id,this.userId=t.userId,this.sdkAppId=t.sdkAppId,this.remoteUserId=t.remoteUserId,this.isLocal=zp(t.isLocal)?t.isLocal:!0,this.type=this.isLocal?"":t.type}createChild(t){return Object.setPrototypeOf(t,this)}setUserId(t){this.userId=t}setSdkAppId(t){this.sdkAppId=t}log(t,e){let r=this.isLocal?this.userId:this.remoteUserId;e.unshift(`[${this.isLocal?"\u2191":"\u2193"}${this.type&&this.type!=="main"?"*":""}${this.id}${r?`|${r}`:""}]`),B.log(t,e,Jp(this.userId)||Xp(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 Ds={};qr(Ds,{ANDROID_VERSION:()=>qu,CHROME_MAJOR_VERSION:()=>Zr,CHROME_VERSION:()=>Vc,EDGE_VERSION:()=>Ac,EDG_MAJOR_VERSION:()=>zu,EDG_VERSION:()=>bc,FIREFOX_MAJOR_VERSION:()=>Ju,FIREFOX_VERSION:()=>yc,HUAWEI_VERSION:()=>xc,IE_VERSION:()=>LE,IOS_MAIN_VERSION:()=>Qt,IOS_VERSION:()=>Li,IPADQQB_VERSION:()=>Oc,IS_ANDROID:()=>gt,IS_ANDROID_WEBVIEW:()=>el,IS_ANY_SAFARI:()=>xi,IS_CHROME:()=>Cs,IS_CHROME_OS:()=>Xu,IS_CHROMIUM_BASE:()=>Io,IS_EDG:()=>Ss,IS_EDGE:()=>Is,IS_ELECTRON:()=>VE,IS_FIREFOX:()=>gr,IS_HEADLESS_CHROME:()=>Ku,IS_HONOR:()=>Zu,IS_HUAWEI:()=>Yu,IS_HUAWEIBROWSER:()=>Wn,IS_IE:()=>eh,IS_IE8:()=>kE,IS_IOS:()=>It,IS_IOS_13_OR_14:()=>rl,IS_IOS_15_1:()=>tl,IS_IPAD:()=>xn,IS_IPADQQB:()=>$n,IS_IPAD_PRO:()=>ju,IS_IPHONE:()=>_o,IS_IPOD:()=>Kp,IS_LINUX:()=>Fn,IS_LOCAL:()=>Tr,IS_MAC:()=>_r,IS_MACQQB:()=>Bn,IS_MIBROWSER:()=>Hn,IS_MQQB:()=>bs,IS_NATIVE_ANDROID:()=>xE,IS_OLD_ANDROID:()=>PE,IS_OPENHARMONY:()=>th,IS_OPPOBROWSER:()=>Rs,IS_SAFARI:()=>Mt,IS_SAFARI_15_1:()=>$E,IS_SAMSUNGBROWSER:()=>Gn,IS_SOGOU:()=>Ln,IS_SOGOUM:()=>kn,IS_TBS:()=>Er,IS_UCBROWSER:()=>Qu,IS_VIVOBROWSER:()=>vs,IS_WECHAT:()=>ys,IS_WIN:()=>To,IS_WQQB:()=>Vn,IS_WX:()=>UE,IS_X5MQQB:()=>As,IS_XWEB:()=>Un,MACQQB_VERSION:()=>Mc,MI_VERSION:()=>Pc,MQQB_VERSION:()=>Ts,OPENHARMONY_VERSION:()=>BE,OPPO_VERSION:()=>Lc,SAFARI_VERSION:()=>ki,SAMSUNG_VERSION:()=>kc,SOGOUM_VERSION:()=>Rc,SOGOU_VERSION:()=>vc,TBS_VERSION:()=>Cc,UA_DATA_STRING:()=>fr,USER_AGENT:()=>Xt,VIVO_VERSION:()=>Uc,WECHAT_VERSION:()=>Dc,WQQB_VERSION:()=>wc,XWEB_VERSION:()=>Nc,browserInfo:()=>Ur,getBrowserInfo:()=>rh,getChromeMajorVersion:()=>jn,getDeviceModel:()=>Jn,getOSName:()=>Ns,getOSNumber:()=>zn,getOSString:()=>So,getOSType:()=>ol,getTerminalType:()=>il,getUserAgentData:()=>qn,isLocalStorageEnabled:()=>Kr});var Xt=typeof navigator=="undefined"?"":navigator.userAgent,Ie=i=>new RegExp(i,"i").test(Xt),pt=i=>{if(Ie(i)){let t=new RegExp(`${i}\\/([\\d.]+)`),e=Xt.match(t);if(e&&e[1])return e[1]}return""},Gu=i=>{if(Ie(i)){let t=new RegExp(`${i}\\/(\\d+)`),e=Xt.match(t);if(e&&e[1])return parseFloat(e[1])}return NaN},Yp=/AppleWebKit\/([\d.]+)/i.exec(Xt),OE=Yp?parseFloat(Yp[1]):NaN,xn=Ie("iPad"),ju=typeof navigator!="undefined"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&Ie("Macintosh"),_o=Ie("iPhone")&&!xn,Kp=Ie("iPod"),It=_o||xn||Kp||ju,gt=Ie("Android"),qu=function(){if(gt){let i=Xt.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}(),PE=gt&&Ie("webkit")&&qu<2.3,xE=gt&&qu<5&&OE<537,gr=Ie("Firefox"),yc=pt("Firefox"),Ju=Gu("Firefox"),Is=Ie("Edge"),Ac=pt("Edge"),Ss=Ie("Edg"),bc=pt("Edg"),zu=Gu("Edg"),kn=Ie("SogouMobileBrowser"),Rc=pt("SogouMobileBrowser"),Ln=Ie("MetaSr\\s"),vc=pt("MetaSr\\s"),Er=Ie("TBS"),Cc=pt("TBS"),Un=Ie("XWEB"),Nc=pt("XWEB"),kE=Ie("MSIE\\s8\\.0"),eh=Ie("MSIE\\/\\d+"),LE=function(){if(eh){let i=/MSIE\s(\d+)\.\d/.exec(Xt),t=i&&parseFloat(i[1]);return!t&&/Trident\/7.0/i.test(Xt)&&/rv:11.0/.test(Xt)&&(t=11),t}return NaN}(),ys=Ie("(micromessenger|webbrowser)"),Dc=pt("MicroMessenger"),As=!Er&&Ie("MQQBrowser")&&Ie("COVC"),bs=!Er&&Ie("MQQBrowser")&&!Ie("COVC"),Ts=bs||As?pt("MQQBrowser"):"",Vn=!Er&&Ie(" QQBrowser"),wc=pt(" QQBrowser"),Bn=!Er&&Ie("QQBrowserLite"),Mc=pt("QQBrowserLite"),$n=!Er&&Ie("MQBHD"),Oc=pt("MQBHD"),To=Ie("Windows"),_r=!It&&Ie("MAC OS X"),Fn=!gt&&Ie("Linux"),Xu=Ie("CrOS"),UE=Ie("MicroMessenger"),Qu=Ie("UCBrowser"),VE=Ie("Electron"),Hn=Ie("MiuiBrowser"),Pc=pt("MiuiBrowser"),Wn=Ie("HuaweiBrowser"),Yu=Ie("Huawei")||Ie("HUAWEI"),Zu=Ie("Honor")||Ie("HONOR"),xc=pt("HuaweiBrowser"),Gn=Ie("SamsungBrowser"),kc=pt("SamsungBrowser"),Rs=Ie("HeyTapBrowser"),Lc=pt("HeyTapBrowser"),vs=Ie("VivoBrowser"),Uc=pt("VivoBrowser"),th=Ie("OpenHarmony"),BE=pt("OpenHarmony"),jn=()=>Gu("Chrome"),Io=Ie("Chrome"),Cs=!Is&&!Ln&&!kn&&!Er&&!Un&&!Ss&&!Vn&&!Hn&&!Wn&&!Gn&&!Rs&&!vs&&Io,Ku=Ie("HeadlessChrome"),Zr=jn(),Vc=pt("Chrome"),Mt=!Io&&!bs&&!As&&!Bn&&!$n&&Ie("Safari"),xi=Mt||It,ki=pt("Version"),el=/Android.*(wv|.0.0.0)/.test(Xt),Li=(()=>{if(ju)return ki;if(It){let i=Xt.match(/OS (\d+)_(\d+)/i);if(i&&i[1]){let t=i[1];return i[2]&&(t+=`.${i[2]}`),t}}return""})(),Qt=Number(Li.split(".")[0]),$E=ki==="15.1",tl=Li==="15.1",rl=(()=>{let i=Number(Li.split(".")[0]);return i===14||i===13})(),Tr=typeof location=="undefined"?!1:location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1",Kr=(()=>{let i;return()=>{if(typeof i=="undefined")try{i=!!window.localStorage}catch(t){i=!1}return i}})(),Ur=rh();function rh(){let i=new Map([[gr,["Firefox",yc]],[Ss,["Edg",bc]],[Cs,["Chrome",Vc]],[Mt,["Safari",ki]],[Er,["TBS",Cc]],[Un,["XWEB",Nc]],[ys&&_o,["WeChat",Dc]],[Vn,["QQ(Win)",wc]],[bs,["QQ(Mobile)",Ts]],[As,["QQ(Mobile X5)",Ts]],[Bn,["QQ(Mac)",Mc]],[$n,["QQ(iPad)",Oc]],[Hn,["MI",Pc]],[Wn,["HW",xc]],[Gn,["Samsung",kc]],[Rs,["OPPO",Lc]],[vs,["VIVO",Uc]],[Is,["EDGE",Ac]],[kn,["SogouMobile",Rc]],[Ln,["Sogou",vc]]]),t="unknown",e="unknown";return i.has(!0)&&([t,e]=i.get(!0)),{name:t,version:e}}var We=null,fr="";function qn(){return y(this,null,function*(){if(We)return We;if(!navigator.userAgentData||typeof navigator.userAgentData.getHighEntropyValues!="function")return null;try{return We=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]),We&&!fr&&(fr=`UAData: ${We.platform}/${We.platformVersion}`,We.architecture&&We.bitness&&(fr+=` ${We.architecture}/${We.bitness}`),We.mobile&&(fr+=" mobile"),We.model&&(fr+=` model: ${We.model}`),We.fullVersionList&&(fr+=` ${We.fullVersionList.filter(i=>i.brand!=="Not/A)Brand").map(i=>`${i.brand}/${i.version}`).join(",")}`)),We}catch(i){return null}})}function Jn(){return(We==null?void 0:We.model)||""}var Zp=new Map([[gt,"Android"],[It,"iOS"],[To,"Windows"],[_r,"MacOS"],[Fn,"Linux"],[Xu,"ChromeOS"]]),Ns=function(){return Zp.get(!0)?Zp.get(!0):We?We.platform:"unknown"};function zn(){return To?1:gt?2:_r?3:It?4:Fn?5:Xu?6:0}var So=()=>{let i=Ns();return i+=`/${Ur.name}/${Mt?Ur.version:Ur.version.split(".")[0]}`,We!=null&&We.platformVersion&&(i+=`/${We.platformVersion}`),We!=null&&We.architecture&&(i+=`/${We.architecture}`),i};function il(){return gt?4:_o?2:xn?3:_r?12:To?5:Fn?13:th?22:1}function ol(){return gt?"Android":_o?"iPhone":xn?"iPad":_r?"Mac":To?"Windows":Fn?"Linux":"unknown"}var oh=Di(Ui(),1),WE=new oh.default,H=WE;var yo=(V=>(V.ROOM_DESTROY="1",V.JOIN_START="21",V.JOIN_SCHEDULE_SUCCESS="22",V.JOIN_SIGNAL_CONNECTION_START="23",V.JOIN_SIGNAL_CONNECTION_END="24",V.JOIN_SEND_CMD="25",V.JOIN_RECEIVED_CMD_RES="26",V.JOIN_SUCCESS="27",V.JOIN_FAILED="28",V.LEAVE_START="51",V.LEAVE_SEND_CMD="52",V.LEAVE_SUCCESS="53",V.PUBLISH_START="61",V.SEND_FIRST_VIDEO_FRAME="62",V.PUBLISH_FAILED="63",V.SUBSCRIBE_START="81",V.SUBSCRIBE_SUCCESS="82",V.SUBSCRIBE_FAILED="84",V.UNSUBSCRIBE_SUCCESS="83",V.LOCAL_TRACK_CAPTURE_START="101",V.LOCAL_TRACK_CAPTURE_SUCCESS="102",V.LOCAL_TRACK_CAPTURE_FAILED="103",V.LOCAL_TRACK_PUBLISHED="104",V.LOCAL_TRACK_UNPUBLISHED="105",V.LOCAL_TRACK_REPLACED="106",V.SWITCH_DEVICE_SUCCESS="107",V.TRACK_MUTED="108",V.TRACK_UNMUTED="109",V.REMOTE_TRACK_SUBSCRIBED="110",V.REMOTE_TRACK_UNSUBSCRIBED="111",V.LOCAL_TRACK_RECAPTURE="112",V.PLAY_TRACK_START="151",V.PLAYER_STATE_CHANGED="152",V.VIDEO_LOADED_DATA="153",V.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",V.SIGNAL_CONNECTION_STATE_CHANGED="201",V.PEER_CONNECTION_STATE_CHANGED="202",V.SINGLE_CONNECTION_STAT="203",V.SPC_RECONNECTED="204",V.HEARTBEAT_REPORT="251",V.RECEIVED_PUBLISHED_USER_LIST="252",V.REMOTE_PUBLISH_STATE_CHANGED="253",V.AUDIO_LEVEL_INTERVAL="260",V.NETWORK_QUALITY="261",V.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",V.QUALITY_LIMITATION_CHANGED="263",V.LOG="264",V))(yo||{});var L=yo;var GE="%cTRTC%c%s",jE="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",qE="display: inline",$c=class $c{constructor(){u(this,"_isEnableUploadLog",!0);u(this,"_localJoinedUser",new Map);u(this,"_queue",[]);u(this,"_timeoutId",-1);u(this,"_logLevel",1);u(this,"_logLevelToUpload",2);!ds&&!Sn&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){H.on(L.JOIN_SCHEDULE_SUCCESS,({schedule:t})=>{var e;(e=t==null?void 0:t.config)!=null&&e.logLevelToUpload&&pr[t.config.logLevelToUpload]&&(this._logLevelToUpload=t.config.logLevelToUpload)}),H.on(L.JOIN_SUCCESS,({room:t})=>{this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload()}),H.once(L.JOIN_FAILED,()=>{this.startUpload()}),H.on(L.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(we(r.userId)&&je(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 y(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:d,logs:p}=o[s];yield this.uploadLogWithRetry(JSON.stringify({timestamp:sc(),sdkAppId:String(d),userId:n,version:rt,log:p.map(m=>m.log).join(`
|
|
4
|
-
`)}),d),p.forEach(m=>m.uploaded=!0)}}catch(o){}let r=e.filter(o=>!o.uploaded);r.length>0&&(this._queue=r.concat(this._queue))})}uploadLogWithRetry(t,e){return Pi({retryFunction:()=>Yr({url:Qr(e,wi.LOG),body:t,timeout:5e3,priority:"low"}),settings:{retries:3,timeout:2e3},onError:({retry:r})=>{r()}})()}getPrefix(t){let e=new Date;e.setTime(In());let r=String(e.getMilliseconds());return"padStart"in String.prototype&&(r=r.toString().padStart(3,"0")),`[${e.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")}:${r}] <${pr[t]}>`}getLogLevel(){return this._logLevel}setLogLevel(t){$(pr[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(we(t))return t;try{return t instanceof Error?t.toString():JSON.stringify(t)}catch(e){return""}}log(t,e,r=!0,o,s){var p;e.unshift(this.getPrefix(t));let n={log:e.reduce((m,E)=>`${m} ${this.logChunkToString(E)}`.trim(),""),level:t,userId:o,sdkAppId:s,forAllJoinedClients:r};if(H.emit(L.LOG,{log:n}),this._isEnableUploadLog&&t>=this._logLevelToUpload&&this._queue.push(n),t<this._logLevel)return;let d=((p=pr[t])==null?void 0:p.toLowerCase())||"info";$c.PRINT_LOG_TAG?console[d](GE,jE,qE,...e):console[d](...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){return new _s(t)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),r=e?Number(e):-1;pr[r]&&(this._logLevelToUpload=r)}getQueue(){return this._queue}};u($c,"PRINT_LOG_TAG",!(It||gt||Ku));var nl=$c,B=new nl;var JE=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)})},Qn=JE;var al=class{constructor(){u(this,"_prefix","TRTC");u(this,"_queue",new Map)}getRealKey(t){return`${this._prefix}_${t}`}checkStorage(){if(!Kr())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(Kr())try{for(let[t,e]of this._queue)localStorage.setItem(t,JSON.stringify(e))}catch(t){B.warn(t)}}getItem(t){if(!Kr())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){B.warn(e)}}setItem(t,e){if(Kr())try{let r={expiresIn:Date.now()+ac,value:e};this._queue.set(this.getRealKey(t),r)}catch(r){B.warn(r)}}deleteItem(t){if(!Kr())return!1;try{return t=this.getRealKey(t),this._queue.delete(t),localStorage.removeItem(t),!0}catch(e){return B.warn(e),!1}}clear(){if(Kr())try{localStorage.clear()}catch(t){B.warn(t)}}},ws=new al;var Vi={};qr(Vi,{HTTPS_API:()=>u_,IS_GET_CAPABILITIES_SUPPORTED:()=>Dl,IS_GET_SETTINGS_SUPPORTED:()=>xs,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>T_,IS_INSERTABLE_STREAM_SUPPORTED:()=>oa,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>A_,IS_RTC_RTP_SENDER_SUPPORTED:()=>ia,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>Oh,IS_SEI_SUPPORTED:()=>sa,IS_SPC_SUPPORTED:()=>f_,basis:()=>S_,capabilityCheck:()=>Ml,checkSystemRequirementsInternal:()=>Kc,decodeSupportStatus:()=>Rh,encodeSupportStatus:()=>vl,getBrowserInfo:()=>Yc,getDisplayResolution:()=>vh,isAddTransceiverSupported:()=>Mh,isBrowserSupported:()=>Cl,isGetReceiversSupported:()=>p_,isGetSendersSupported:()=>wh,isGetTransceiversSupported:()=>h_,isGetUserMediaSupported:()=>Ch,isMediaDevicesSupported:()=>Zc,isMediaSessionSupported:()=>xh,isMediaStreamTrackProcessorSupported:()=>Nl,isReplaceTrackSupported:()=>E_,isRequestVideoFrameCallbackSupported:()=>Do,isSIMDSupported:()=>I_,isScreenCaptureApiAvailable:()=>ta,isSelectedCandidatePair:()=>l_,isSetParametersSupported:()=>__,isSmallStreamAPISupported:()=>Dh,isSmallStreamSupported:()=>ra,isStopTransceiverSupported:()=>g_,isTRTCSupported:()=>c_,isUnifiedPlanDefault:()=>m_,isUsedInHttpProtocol:()=>si,isWebAudioSupported:()=>Nh,isWebCodecSupported:()=>Ph,isWebCodecsSupported:()=>bh,isWebRTCSupported:()=>wl,isWebTransportSupported:()=>kh});var Tl={};qr(Tl,{AUDIO_LEVEL_SCALE:()=>ri,AudioCodecPipelineType:()=>Jc,AudioDecoderDowngradeState:()=>ul,AudioPlayerMode:()=>hl,AudioType:()=>ml,BASIC_TYPE:()=>Ro,BannedReason:()=>fl,CONNECTION_CLOSED_REASON:()=>nh,ClientEvent:()=>cl,CodecType:()=>ph,ConnectionEvent:()=>sh,ConnectionState:()=>Hc,DECODE_FAILED_ERROR_CODE:()=>_l,FacingMode:()=>Gc,LeaveReason:()=>gl,LocalTrackEvent:()=>Fc,MULTI_VIDEO_DATA_TYPE:()=>ti,MediaType:()=>vt,MediaTypeLabel:()=>zE,MonitorEventId:()=>Zn,MutedFlag:()=>ch,NetworkQualityValue:()=>lh,PlayerState:()=>Ms,ReceiveMode:()=>mh,RemoteStreamType:()=>Vr,RemoteTrackEvent:()=>Os,RoomEvent:()=>Ao,SceneNumber:()=>dl,StreamEvent:()=>ah,StreamType:()=>uh,SubscribeMediaType:()=>Yn,TIMER_TYPE:()=>vo,TRACK_ACTION:()=>dh,TRACK_KIND:()=>ll,TrackEvent:()=>ei,UserRole:()=>jt,UserRoleNumber:()=>bo,VideoCodec:()=>El,VideoCodecPipelineType:()=>qc,VideoContentHint:()=>Kn,VideoDecoderDowngradeState:()=>Wc,VideoPlayerMode:()=>jc,VideoType:()=>pl});var sh=(x=>(x.TRACK_ADDED="track-added",x.TRACK_UPDATED="track-updated",x.TRACK_SUBSCRIBED="track-subscribed",x.STREAM_ADDED="stream-added",x.STREAM_REMOVED="stream-removed",x.STREAM_UPDATED="stream-updated",x.STREAM_PUBLISHED="stream-published",x.STREAM_SUBSCRIBED="stream-subscribed",x.STREAM_UNSUBSCRIBED="stream-unsubscribed",x.STATE_CHANGED="state-changed",x.ERROR="error",x.CONNECTION_STATE_CHANGED="connection-state-changed",x.FIREWALL_RESTRICTION="firewall-restriction",x.SEI_MESSAGE="sei-message",x.CLOSED="closed",x))(sh||{}),nh=(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))(nh||{}),cl=(P=>(P.STREAM_ADDED="stream-added",P.STREAM_REMOVED="stream-removed",P.STREAM_UPDATED="stream-updated",P.STREAM_SUBSCRIBED="stream-subscribed",P.CONNECTION_STATE_CHANGED="connection-state-changed",P.PEER_JOIN="peer-join",P.PEER_LEAVE="peer-leave",P.MUTE_AUDIO="mute-audio",P.MUTE_VIDEO="mute-video",P.UNMUTE_AUDIO="unmute-audio",P.UNMUTE_VIDEO="unmute-video",P.CLIENT_BANNED="client-banned",P.NETWORK_QUALITY="network-quality",P.AUDIO_VOLUME="audio-volume",P.SEI_MESSAGE="sei-message",P.ERROR="error",P))(cl||{}),ah=(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))(ah||{}),Fc=(n=>(n.DEVICE_AUTO_RECOVERED="1",n.DEVICE_RECOVER_FAILED="5",n.DEVICE_CHANGED="2",n.ERROR="3",n.PUBLISH_STATE_CHANGED="4",n.ENCODE_FAILED="6",n))(Fc||{}),Ms=(r=>(r.PAUSED="PAUSED",r.PLAYING="PLAYING",r.STOPPED="STOPPED",r))(Ms||{}),Ao=(Q=>(Q.PEER_JOIN="peer-join",Q.PEER_LEAVE="peer-leave",Q.SIGNAL_CONNECTION_STATE_CHANGED="signal-connection-state-changed",Q.MEDIA_CONNECTION_STATE_CHANGED="media-connection-state-changed",Q.BANNED="banned",Q.NETWORK_QUALITY="network-quality",Q.AUDIO_VOLUME="audio-volume",Q.SEI_MESSAGE="sei-message",Q.ERROR="error",Q.REMOTE_PUBLISH_STATE_CHANGED="remote-publish-state-changed",Q.REMOTE_PUBLISHED="remote-published",Q.REMOTE_UNPUBLISHED="remote-unpublished",Q.FIREWALL_RESTRICTION="firewall-restriction",Q.HEARTBEAT_REPORT="heartbeat-report",Q.CUSTOM_MESSAGE="custom-message",Q.LAYER_DATA="layerData",Q.FIRST_VIDEO_FRAME="first-video-frame",Q.DUMP="dump",Q))(Ao||{}),ei=(d=>(d.PLAYER_STATE_CHANGED="player-state-changed",d.MUTE="mute",d.UNMUTE="unmute",d.ERROR="error",d.INPUT_MEDIA_TRACK_CHANGED="input-media-track-changed",d.OUTPUT_MEDIA_TRACK_CHANGED="output-media-track-changed",d.FIRST_VIDEO_FRAME="first-video-frame",d))(ei||{}),Os=(e=>(e.DECODE_FAILED="decode-failed",e.DECODE_DOWNGRADE_STATE_CHANGED="decode-downgrade-state-changed",e))(Os||{}),ch=(d=>(d[d.VIDEO=1]="VIDEO",d[d.SMALL=2]="SMALL",d[d.AUX=4]="AUX",d[d.AUDIO=8]="AUDIO",d[d.VIDEO_MUTE=16]="VIDEO_MUTE",d[d.AUX_MUTE=32]="AUX_MUTE",d[d.AUDIO_MUTE=64]="AUDIO_MUTE",d))(ch||{}),dl=(e=>(e[e.RTC=1]="RTC",e[e.LIVE=2]="LIVE",e))(dl||{}),bo=(e=>(e[e.ANCHOR=20]="ANCHOR",e[e.AUDIENCE=21]="AUDIENCE",e))(bo||{}),jt=(e=>(e.ANCHOR="anchor",e.AUDIENCE="audience",e))(jt||{}),Hc=(s=>(s.CONNECTED="CONNECTED",s.DISCONNECTED="DISCONNECTED",s.CONNECTING="CONNECTING",s.RECONNECTED="RECONNECTED",s.RECONNECTING="RECONNECTING",s))(Hc||{}),ul=(o=>(o.INITIALIZED="INITIALIZED",o.STARTING="STARTING",o.STARTED="STARTED",o.FAILED="FAILED",o))(ul||{}),Wc=(o=>(o.INITIALIZED="INITIALIZED",o.STARTING="STARTING",o.STARTED="STARTED",o.FAILED="FAILED",o))(Wc||{}),ll=(r=>(r.AUDIO="audio",r.VIDEO="video",r.AUXILIARY="auxVideo",r))(ll||{}),dh=(e=>(e.ADD="add",e.REMOVE="remove",e))(dh||{}),vt=(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))(vt||{}),zE={1:"audio",2:"auxVideo",4:"video"},ml=(t=>(t[t.opus=111]="opus",t))(ml||{}),pl=(e=>(e[e.h264=100]="h264",e[e.vp8=101]="vp8",e))(pl||{}),uh=(e=>(e.Big="big",e.Small="small",e))(uh||{}),Vr=(e=>(e.Main="main",e.Aux="auxiliary",e))(Vr||{}),ti=(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))(ti||{}),Zn=(G=>(G[G.PUBLISH_VIDEO=32768]="PUBLISH_VIDEO",G[G.PUBLISH_AUDIO=32769]="PUBLISH_AUDIO",G[G.UNPUBLISH_VIDEO=32770]="UNPUBLISH_VIDEO",G[G.UNPUBLISH_AUDIO=32771]="UNPUBLISH_AUDIO",G[G.MUTE_AUDIO=32772]="MUTE_AUDIO",G[G.MUTE_VIDEO=32773]="MUTE_VIDEO",G[G.UNMUTE_AUDIO=32774]="UNMUTE_AUDIO",G[G.UNMUTE_VIDEO=32775]="UNMUTE_VIDEO",G[G.SUBSCRIBE_VIDEO=32776]="SUBSCRIBE_VIDEO",G[G.SUBSCRIBE_AUDIO=32777]="SUBSCRIBE_AUDIO",G[G.UNSUBSCRIBE_VIDEO=32778]="UNSUBSCRIBE_VIDEO",G[G.UNSUBSCRIBE_AUDIO=32779]="UNSUBSCRIBE_AUDIO",G[G.SWITCH_CAMERA=32780]="SWITCH_CAMERA",G[G.SWITCH_MICROPHONE=32781]="SWITCH_MICROPHONE",G[G.REPLACE_VIDEO=32782]="REPLACE_VIDEO",G[G.REPLACE_AUDIO=32783]="REPLACE_AUDIO",G[G.MUTE_REMOTE_VIDEO=32784]="MUTE_REMOTE_VIDEO",G[G.MUTE_REMOTE_AUDIO=32785]="MUTE_REMOTE_AUDIO",G[G.UNMUTE_REMOTE_VIDEO=32786]="UNMUTE_REMOTE_VIDEO",G[G.UNMUTE_REMOTE_AUDIO=32787]="UNMUTE_REMOTE_AUDIO",G[G.JOIN=32788]="JOIN",G[G.LEAVE=32789]="LEAVE",G[G.SIGNAL_DISCONNECTED=32790]="SIGNAL_DISCONNECTED",G[G.SIGNAL_CONNECTED=32791]="SIGNAL_CONNECTED",G[G.TRANSPORT_UPLINK_CONNECTED=32792]="TRANSPORT_UPLINK_CONNECTED",G[G.TRANSPORT_DOWNLINK_CONNECTED=32793]="TRANSPORT_DOWNLINK_CONNECTED",G[G.SIGNAl_RECONNECTING=32794]="SIGNAl_RECONNECTING",G[G.SIGNAL_RECONNECT_SUCCESS=32795]="SIGNAL_RECONNECT_SUCCESS",G[G.SIGNAL_RECONNECT_FAIL=32796]="SIGNAL_RECONNECT_FAIL",G[G.TRANSPORT_UPLINK_RECONNECTING=32797]="TRANSPORT_UPLINK_RECONNECTING",G[G.TRANSPORT_UPLINK_RECONNECT_SUCCESS=32798]="TRANSPORT_UPLINK_RECONNECT_SUCCESS",G[G.TRANSPORT_UPLINK_RECONNECT_FAIL=32799]="TRANSPORT_UPLINK_RECONNECT_FAIL",G[G.TRANSPORT_DOWNLINK_RECONNECTING=32800]="TRANSPORT_DOWNLINK_RECONNECTING",G[G.TRANSPORT_DOWNLINK_RECONNECT_SUCCESS=32801]="TRANSPORT_DOWNLINK_RECONNECT_SUCCESS",G[G.TRANSPORT_DOWNLINK_RECONNECT_FAIL=32802]="TRANSPORT_DOWNLINK_RECONNECT_FAIL",G[G.SUBSCRIBE_SMALL_VIDEO=32803]="SUBSCRIBE_SMALL_VIDEO",G[G.UNSUBSCRIBE_SMALL_VIDEO=32804]="UNSUBSCRIBE_SMALL_VIDEO",G[G.PUBLISH_AUX=32805]="PUBLISH_AUX",G[G.UNPUBLISH_AUX=32806]="UNPUBLISH_AUX",G[G.DEVICE_CAPTURE=2003]="DEVICE_CAPTURE",G[G.VIDEO_ENCODER=4004]="VIDEO_ENCODER",G[G.VIDEO_DECODER=4005]="VIDEO_DECODER",G))(Zn||{}),lh=(d=>(d[d.UNKNOWN=0]="UNKNOWN",d[d.EXCELLENT=1]="EXCELLENT",d[d.GOOD=2]="GOOD",d[d.POOR=3]="POOR",d[d.BAD=4]="BAD",d[d.VERY_BAD=5]="VERY_BAD",d[d.DISCONNECTED=6]="DISCONNECTED",d))(lh||{}),mh=(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))(mh||{}),Gc=(e=>(e.user="user",e.environment="environment",e))(Gc||{}),jc=(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))(jc||{}),hl=(e=>(e[e.ELEMENT=0]="ELEMENT",e[e.CONTEXT=1]="CONTEXT",e))(hl||{}),fl=(o=>(o.BANNED="banned",o.KICK="kick",o.USER_TIME_OUT="user_time_out",o.ROOM_DISBAND="room_disband",o))(fl||{}),gl=(m=>(m[m.USER_EXIT_REASON_TC_USER_EXIT_NORMAL=0]="USER_EXIT_REASON_TC_USER_EXIT_NORMAL",m[m.USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT=1]="USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT",m[m.USER_EXIT_REASON_TC_USER_EXIT_KICKED=2]="USER_EXIT_REASON_TC_USER_EXIT_KICKED",m[m.USER_EXIT_REASON_TC_USER_EXIT_CHANGED=3]="USER_EXIT_REASON_TC_USER_EXIT_CHANGED",m[m.USER_KICK_OUT_CODE_BUSINESS_USER=4]="USER_KICK_OUT_CODE_BUSINESS_USER",m[m.USER_KICK_OUT_CODE_BUSINESS_ROOM=5]="USER_KICK_OUT_CODE_BUSINESS_ROOM",m[m.USER_KICK_OUT_CODE_SERVER_USER=6]="USER_KICK_OUT_CODE_SERVER_USER",m[m.USER_KICK_OUT_CODE_SERVER_ROOM=7]="USER_KICK_OUT_CODE_SERVER_ROOM",m[m.USER_KICK_SESS_EXSIT=8]="USER_KICK_SESS_EXSIT",m))(gl||{}),ri=1e8,Yn=class{constructor(){u(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)}},Ro=(s=>(s.String="string",s.Number="number",s.Boolean="boolean",s.Array="array",s.Object="object",s))(Ro||{}),El=(r=>(r.H264="h264",r.H265="h265",r.VP8="vp8",r))(El||{}),qc=(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))(qc||{}),Jc=(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))(Jc||{}),ph=(r=>(r.WebRTC="webrtc",r.WebCodecs="webcodecs",r.WebAssembly="webassembly",r))(ph||{}),_l=(_=>(_[_.SUCCESS=0]="SUCCESS",_[_.FAILED=1]="FAILED",_[_.WEBCODEC_INIT=2]="WEBCODEC_INIT",_[_.WEBCODEC_CONFIG_NOT_SUPPORT=3]="WEBCODEC_CONFIG_NOT_SUPPORT",_[_.WEBCODEC_DECODER_ERROR=4]="WEBCODEC_DECODER_ERROR",_[_.WEBCODEC_TRACK_MUTE=5]="WEBCODEC_TRACK_MUTE",_[_.WASM_INIT=6]="WASM_INIT",_[_.WASM_WEBGL_UNAVALIABLE=7]="WASM_WEBGL_UNAVALIABLE",_[_.WASM_DECODER_ERROR=8]="WASM_DECODER_ERROR",_[_.WASM_TRACK_MUTE=9]="WASM_TRACK_MUTE",_[_.TEST=10]="TEST",_))(_l||{}),Kn=(o=>(o.NONE="",o.DETAIL="detail",o.MOTION="motion",o.TEXT="text",o))(Kn||{}),vo=(s=>(s.INTERVAL="interval",s.TIMEOUT="timeout",s.RAF="raf",s.RIC="ric",s.INTERVAL_IN_WORKER="intervalInWorker",s))(vo||{});var nt={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"},qt={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: ${mt(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: ${mt(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 hh=(i,t)=>t?`${Mr}/${i}/${t}`:`${Mr}/${i}/index.html`;var XE=()=>{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(xu);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 at(i){let{key:t,data:e,link:r,addDocLink:o=!0}=i,s="",n="",d="";ze(qt[t])?s=qt[t](e):we(qt[t])&&(s=qt[t]);let{TRTC_ERROR_INFO:p,TRTC_ERROR_LINK:m}=XE();r?d=`${r.className}.html#${r.fnName}`:m&&m[t]&&(ze(m[t])?d=m[t](e):we(m[t])&&(d=m[t]));let E=s;return hr()&&(p&&p[t]&&(ze(p[t])?n=p[t](e):we(p[t])&&(n=p[t])),n&&(o?E=`${n}
|
|
5
|
-
\u8BF7\u67E5\u770B\u6587\u6863: ${
|
|
3
|
+
`}});var Ah=_n(ni=>{"use strict";var wo=Ih(),d_=yh();ni.write=d_;ni.parse=wo.parse;ni.parseParams=wo.parseParams;ni.parseFmtpConfig=wo.parseFmtpConfig;ni.parsePayloads=wo.parsePayloads;ni.parseRemoteCandidates=wo.parseRemoteCandidates;ni.parseImageAttributes=wo.parseImageAttributes;ni.parseSimulcastStreamList=wo.parseSimulcastStreamList});var Np=(K=>(K[K.INVALID_PARAMETER=4096]="INVALID_PARAMETER",K[K.INVALID_OPERATION=4097]="INVALID_OPERATION",K[K.NOT_SUPPORTED=4098]="NOT_SUPPORTED",K[K.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",K[K.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",K[K.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",K[K.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",K[K.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",K[K.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",K[K.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",K[K.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",K[K.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",K[K.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",K[K.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",K[K.CLIENT_BANNED=16448]="CLIENT_BANNED",K[K.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",K[K.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",K[K.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",K[K.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",K[K.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",K[K.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",K[K.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",K[K.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",K[K.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",K[K.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",K[K.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",K[K.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",K[K.API_CALL_ABORTED=16461]="API_CALL_ABORTED",K[K.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",K[K.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",K[K.UNKNOWN=65535]="UNKNOWN",K))(Np||{}),te=Np;var Wg=function(i){for(let t in te)if(te[t]===i)return t;return"UNKNOWN"},wu=class extends Error{constructor({name:e="RtcError",message:r,code:o=te.UNKNOWN,extraCode:s=0,constraint:n}){let d=`<${Wg(o)} 0x${o.toString(16)}>`,p=`${r}${n?` constraint: ${n}`:""}${r!=null&&r.includes(d)?"":` ${d}`}`;super(p);u(this,"code");u(this,"extraCode");u(this,"message");u(this,"originMessage");u(this,"name");u(this,"constraint");this.code=o,this.extraCode=s,this.name=e,this.message=p,this.constraint=n,this.originMessage=r}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},he=wu;var xS=new Date().getTime(),Gg=0;var Tn=function(){return new Date().getTime()+Gg},oc=function(){let i=new Date;return i.setTime(Tn()),i.toLocaleString()},sc=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 Lr={};Jr(Lr,{bytes2ms:()=>Fp,convertObjectNumberToInt:()=>On,copyProperties:()=>Vp,deepClone:()=>So,deepMerge:()=>kr,delay:()=>xn,fibonacci:()=>yo,formatedTime:()=>gc,getConstructorName:()=>Nn,getContainerFromElement:()=>Jp,getEnv:()=>kp,getInternalVersion:()=>jp,getLoggerUrl:()=>Yr,getMuteStateFromFlag:()=>Mn,getNetworkType:()=>Cn,getNumNetworkType:()=>fc,getReconnectionTimeout:()=>Bp,getStringByteLength:()=>zp,getTurnServer:()=>qp,getUint32Version:()=>Tc,getValueType:()=>ht,getViewListFromView:()=>Es,glog:()=>Dn,ipv4ToUint32:()=>gs,isArray:()=>st,isAudioWorkletSupported:()=>Gp,isBoolean:()=>nt,isConstructor:()=>hs,isEmpty:()=>fs,isFunction:()=>Xe,isLangChinese:()=>fr,isMediaStreamTrack:()=>Hp,isNumber:()=>je,isObject:()=>Pr,isOverseaSdkAppId:()=>vn,isPlainObject:()=>Gt,isPortrait:()=>_c,isPromise:()=>xi,isRemoteTrack:()=>Wp,isString:()=>we,isUndefined:()=>V,loadImage:()=>_s,ms2bytes:()=>$p,ms2samples:()=>Hu,performanceNow:()=>_e,promiseAny:()=>wn,samples2ms:()=>Bu,setNetworkType:()=>Up,stringify:()=>ir,stringifyIncludeValue:()=>Ec,throttlePromise:()=>Ic});var $u={};Jr($u,{AUDIO_MUTE_BIT:()=>lc,AUDIO_STAT_BIT:()=>ms,AUX_STAT_BIT:()=>yn,AUX_STREAM_MSID:()=>rE,BACKEND_ENV:()=>uc,BASE_DOC_URL:()=>Mr,BASE_HOST:()=>wp,CAPABILITIES_KEYS:()=>hc,CLASS_NAME:()=>vE,CLOUD_CONSOLE_URL:()=>zg,CROSS_ROOM_BIT:()=>eE,DATA_FREEZE_TIMING:()=>pc,DEFAULT_ASSETS_URL:()=>nc,DOC_URL:()=>Xg,DTLS_STATE_UNKNOWN:()=>mE,ENV_NAME:()=>zr,EXCHANGE_SDP_TIMEOUT:()=>_E,IS_WORKER:()=>us,IS_WORKLET:()=>In,KIBANA_EVENT:()=>Xr,LOCAL_STREAM_PUBLISH_STATE:()=>Op,LOGGER_CMD_TYPE:()=>Oi,LOGGER_DOMAIN:()=>xu,LOGGER_DOMAIN_OVERSEA:()=>Pu,LOG_LEVEL:()=>hr,LOG_LEVEL_NAME:()=>DE,MAIN_STREAM_MSID:()=>tE,MAX_RTT:()=>bn,MICROPHONE_COMMUNICATIONS:()=>CE,MICROPHONE_DEFAULT:()=>Io,MUTE_ALL_BIT:()=>Kg,NAME:()=>D,NETWORK_TYPE:()=>To,NOT_SUPPORTED_H264:()=>IE,PAUSED_RETRY_COUNT:()=>Fu,PEERCONNECTION_CONNECTING_TIMEOUT:()=>bE,PEER_CONNECTION_STATE:()=>pE,PEER_LEAVE_REASON:()=>xp,RECOVER_CAPTURE_INTERVAL:()=>ps,REMOTE_STREAM_TYPE_AUX:()=>oE,REMOTE_STREAM_TYPE_MAIN:()=>iE,RENDER_FREEZE_TIMING:()=>SE,SCHEDULE_DOMAIN:()=>Qr,SCHEDULE_TIMEOUT:()=>RE,SDP_SEMANTICS_PLAN_B:()=>TE,SDP_SEMANTICS_UNIFIED_PLAN:()=>Vu,SECOND_HOST:()=>qg,SIGNAL_PING_PONG_INTERVAL:()=>Yg,SIGNAL_PING_TIMEOUT:()=>Qg,SIGNAL_RECONNECTION_COUNT:()=>fE,SMALL_STAT_BIT:()=>Lu,SPEAKER_DEFAULT:()=>An,STORAGE_EXPIRES_TIME:()=>ac,STREAM_TYPE_BIG:()=>yE,STREAM_TYPE_SMALL:()=>AE,SUBSCRIBE_SMALL_RETRY_COUNT:()=>NE,SYNC_USER_LIST_INTERVAL:()=>gE,Scene:()=>xr,THIRD_HOST:()=>Jg,TRANSPORT_DIRECTION:()=>Zg,TRTC_ERROR_ASSISTANCE:()=>ku,TRTC_QUALITY_BAD:()=>dE,TRTC_QUALITY_DISCONNECTED:()=>lE,TRTC_QUALITY_EXCELLENT:()=>nE,TRTC_QUALITY_GOOD:()=>aE,TRTC_QUALITY_POOR:()=>cE,TRTC_QUALITY_UNKNOWN:()=>sE,TRTC_QUALITY_VERY_BAD:()=>uE,UPDATE_OFFER_TIMEOUT:()=>EE,VIDEO_MUTE_BIT:()=>mc,VIDEO_STAT_BIT:()=>ls,audioProfileMap:()=>cc,getRetryCount:()=>hE,getScriptDir:()=>jg,innerVersion:()=>Mu,loggerProxy:()=>Sn,screenProfileMap:()=>dc,setLoggerProxy:()=>_o,setRetryCount:()=>Uu,setVersion:()=>Ou,version:()=>rt,videoProfileMap:()=>Or});var Mu="4.15.00.1600",rt="5.0.0";function Ou(i){rt=i;let[t,e,r]=i.split(".").map(o=>parseInt(o,10));Mu=`${t}.${Math.min(15,e)}.${Math.min(15,r)}.${e.toString().padStart(2,"0")}${r.toString().padStart(2,"0")}`}var us=typeof importScripts!="undefined",In=typeof registerProcessor!="undefined",jg=()=>{let i=us?self.location.href:document.currentScript.src;return i.substring(0,i.lastIndexOf("/")+1)},Sn="",_o=i=>Sn=i,wp="web.sdk.qcloud.com",qg="web.sdk.tencent.cn",Jg="web.sdk.cloud.tencent.cn",zg="https://console.cloud.tencent.com/trtc",Mr=`https://${wp}/trtc/webrtc/v5/doc`,nc="https://web.sdk.qcloud.com/trtc/webrtc/v5/assets/",Xg=`${Mr}/zh-cn/`,xu="https://yun.tim.qq.com",Pu="https://apisgp.my-imcloud.com",ku="trtc_error_assistance",Oi={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},zr={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},hr=(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))(hr||{}),Qg=18e3,Yg=2e3,To={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5,"5g":6},ac=7*24*3600*1e3,cc={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}},Or={"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}},dc={"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}},D={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"},Zg={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},uc={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},xr=(e=>(e.LIVE="live",e.RTC="rtc",e))(xr||{}),ls=1,Lu=2,yn=4,ms=8,lc=64,mc=16,Kg=112,eE=128,tE="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",rE="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",iE=D.MAIN,oE=D.AUXILIARY,sE=0,nE=1,aE=2,cE=3,dE=4,uE=5,lE=6,mE="unknown",pE={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},Mp=1/0;function Uu(i){Mp=i}function hE(){return Mp}var fE=30,Xr={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"},gE=1e4,EE=1e4,_E=1e4,Vu="unified-plan",TE="plan-b",IE=1028,Op=(r=>(r[r.UNPUBLISH=-1]="UNPUBLISH",r[r.PUBLISHING=0]="PUBLISHING",r[r.PUBLISHED=1]="PUBLISHED",r))(Op||{}),pc=500,SE=1e3,yE=D.BIG,AE=D.SMALL,bE=10*1e3,Qr={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"},RE=2e3,vE={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},Fu=5,Io="default",An=Io,CE="communications",DE=Object.keys(hr),xp=["normal leave","timeout leave","kick","role change"],NE=10,ps=2e3,hc=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],bn=10*1e3;var kp=function(){return new URLSearchParams(location.search).get("trtc_env")||""},vn=i=>Number(i)<14e8,Yr=function(i,t){let e;Sn?e=Sn:e=vn(i)?Pu:xu;let r=Math.floor(Math.random()*En(2,31));return`${e}/v5/AVQualityReportSvc/C2S?random=${r}&sdkappid=${i}&cmdtype=${t}`},Rn="unknown";function Cn(){if(Rn!=="unknown")return Rn;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&&(Rn=Lp(r,o)),Rn}function Lp(i,t){if(To[i])return i;switch(i){case"cellular":case"wimax":return t||"unknown";case"ethernet":return"wired";case"none":case"other":default:return"unknown"}}function Up(i){Rn=Lp(i)}function fc(){return To[Cn()]}function Vp(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 Fp(i,t=48e3){return Bu(i/4,t)}function Bu(i,t=48e3){return i*1e3/t}function $p(i,t=48e3){return Hu(i,t)*4}function Hu(i,t=48e3){return i*t/1e3}var Dn=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},fr=()=>{let i=navigator.language;return i=i.substring(0,2),i==="zh"},Gt=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 yo(i,t=1,e=1){return i<=1?e:yo(i-1,e,t+e)}function Bp(i){return i>8?30*1e3:yo(i)*1e3}function ht(i){return Reflect.apply(Object.prototype.toString,i,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var Xe=i=>typeof i=="function",V=i=>typeof i=="undefined",we=i=>typeof i=="string",je=i=>typeof i=="number",nt=i=>typeof i=="boolean",Pr=i=>ht(i)==="object",st=i=>ht(i)==="array",Hp=i=>ht(i)==="MediaStreamTrack".toLowerCase(),Wp=i=>i.isRemote,xi=i=>ht(i)==="promise",hs=i=>Xe(i)&&i.prototype.constructor===i,Nn=i=>hs(i)?i.prototype.constructor.name:"",Gp=typeof AudioWorkletNode!="undefined";function wn(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 _e(){return!performance||!performance.now?Date.now():Math.floor(performance.now())}var Pp=i=>+i<10?`0${i}`:i,jp=i=>{let t=i.match(/^\d+\.\d+\.\d+/)[0];if(!t)return i;let e=t.split("."),r=Pp(e[1])+Pp(e[2]);return e[1]-15>0&&(e[1]="15"),e[2]-15>0&&(e[2]="15"),`${e.join(".")}.${r}`},wE=Object.prototype.hasOwnProperty,{toString:VS}=Object.prototype;function fs(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(Gt(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(wE.call(i,t))return!1;return!0}}return!1}function Mn(i,t){return{userId:t,hasAudio:!!(i&ms),hasVideo:!!(i&ls),hasAuxiliary:!!(i&yn),hasSmall:!!(i&Lu),audioMuted:!!(i&lc),videoMuted:!!(i&mc),audioAvailable:!!(i&ms)&&!(i&lc),videoAvailable:!!(i&ls)&&!(i&mc)}}function qp(i){let t={urls:i.url.startsWith("turn:")||i.url.startsWith("turns:")?i.url:`turn:${i.url}`};return!V(i.username)&&!V(i.credential)&&(t.username=i.username,t.credential=i.credential,t.credentialType="password",V(i.credentialType)||(t.credentialType=i.credentialType)),t}function gs(i,t=!0){if(!we(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 kr=function(i,t,e,r){if(!(Pr(i)&&Pr(t)))return 0;let o=0,s=Object.keys(t),n;for(let d=0,p=s.length;d<p;d++)if(n=s[d],!(V(t[n])||e&&e.includes(n)))if(Pr(i[n])&&Pr(t[n]))o+=kr(i[n],t[n],e,r);else{if(r&&r.includes(t[n]))continue;i[n]!==t[n]&&(i[n]=So(t[n]),o+=1)}return o};function So(i){if(st(i)){let t=[];return i.forEach((e,r)=>{t[r]=So(e)}),t}if(Pr(i)){let t={};return Object.keys(i).forEach(e=>{t[e]=So(i[e])}),t}return i}var Es=i=>{let t=[];if(st(i))t=[...i];else if(we(i)){let e=document.getElementById(i);e&&t.push(e)}else i&&t.push(i);return t},Jp=i=>we(i)?document.getElementById(i):i,ME=i=>{let t=p=>p<10?`0${p}`:`${p}`,e=i.getFullYear(),r=i.getMonth()+1,o=i.getDate(),s=t(i.getHours()),n=t(i.getMinutes()),d=t(i.getSeconds());return`${e}/${r}/${o} ${s}:${n}:${d}`},gc=()=>ME(new Date);function ir(i,{keysToInclude:t,keysToExclude:e}){try{if(st(i))return`[${i.map(n=>ir(n,{keysToInclude:t,keysToExclude:e})).join(",")}]`;if(!Gt(i)||!st(t)&&!st(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]=Gt(i[n])||st(i[n])?JSON.parse(ir(i[n],{keysToExclude:e,keysToInclude:t})):i[n])}),JSON.stringify(r)}catch(r){return"{}"}}function Ec(i,t=!1){let e=[];return Object.keys(i).forEach(r=>{t===i[r]&&e.push(r)}),ir(i,{keysToInclude:e})}function zp(i){return i.replace(/[\u4e00-\u9fa5]/g,"aa").length}var _c=()=>{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},_s=i=>y(void 0,null,function*(){return new Promise((t,e)=>{let r;if(we(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 he({code:te.INVALID_PARAMETER,message:`load image failed, url: ${i}`}))}})}),Tc=i=>{let t=i.split(".");return+t[0]<<24|+t[1]<<16|+t[2]<<8|+t[3]<<0},On=i=>(Object.keys(i).forEach(t=>{je(i[t])&&(t.startsWith("uint")||t.startsWith("int"))?i[t]=Math.floor(i[t]):(Gt(i[t])||st(i[t]))&&On(i[t])}),i);function xn(i,t){return new Promise(e=>{let r=setTimeout(e,i);t&&t(r)})}function Ic(i,t){let e=null;return function(...r){return e||(e=i.apply(t||this,r),e.finally(()=>e=null),e)}}function Zr({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(p=>p.text()).then(p=>{try{s({data:JSON.parse(p)})}catch(m){s({data:p})}},n);let d=new XMLHttpRequest;d.onreadystatechange=()=>{if(d.readyState===4)if(d.status>=200&&d.status<300)try{let p=JSON.parse(d.response);s({data:p})}catch(p){s({data:d.response})}else n({status:d.status,statusText:d.statusText||"request failed!"})},d.timeout=r||5e3,d.open(e,i,!0),d.send(t)})}function Wu(i){return y(this,null,function*(){let t=_e(),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")),d=yield(yield(yield new Response(o)).blob()).arrayBuffer();return $.debug(`compressJSON ${e.length} -> ${d.byteLength} ${_e()-t}ms`),d}catch(r){return e}})}var OE=Object.prototype.hasOwnProperty;var Pi=i=>typeof i=="function",Xp=i=>typeof i=="undefined";var Qp=i=>typeof i=="boolean";var Gu=i=>i.isRemote;var xE=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 Yp(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(xE(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(OE.call(i,t))return!1;return!0}}return!1}var PE=0,kE=1,Zp=2;function LE({retryFunction:i,settings:t,onError:e,onRetrying:r,onRetryFailed:o,onRetrySuccess:s,context:n}){return function(...d){let{retries:p=5,timeout:m=1e3}=t,g=0,_=-1,b=PE,N=(k,P)=>y(this,null,function*(){let x=n||this;try{let J=yield i.apply(x,d);g>0&&s&&s.call(this,g),g=0,k(J)}catch(J){let Q=()=>{clearTimeout(_),g=0,b=Zp,P(J)},Ne=()=>{b!==Zp&&g<(Pi(p)?p():p)?(g++,b=kE,Pi(r)&&r.call(this,g,Q),_=window.setTimeout(()=>{_=-1,N(k,P)},Pi(m)?m(g):m)):(Q(),Pi(o)&&o.call(this,J))};Pi(e)?e.call(this,{error:J,retry:Ne,reject:P,retryFuncArgs:d,retriedCount:g}):Ne()}});return new Promise(N)}}var ki=LE;var Ts=class{constructor(t){u(this,"userId");u(this,"remoteUserId");u(this,"id");u(this,"sdkAppId");u(this,"type");u(this,"isLocal");this.id=t.id,this.userId=t.userId,this.sdkAppId=t.sdkAppId,this.remoteUserId=t.remoteUserId,this.isLocal=Qp(t.isLocal)?t.isLocal:!0,this.type=this.isLocal?"":t.type}createChild(t){return Object.setPrototypeOf(t,this)}setUserId(t){this.userId=t}setSdkAppId(t){this.sdkAppId=t}log(t,e){let r=this.isLocal?this.userId:this.remoteUserId;e.unshift(`[${this.isLocal?"\u2191":"\u2193"}${this.type&&this.type!=="main"?"*":""}${this.id}${r?`|${r}`:""}]`),$.log(t,e,Xp(this.userId)||Yp(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 ws={};Jr(ws,{ANDROID_VERSION:()=>Ju,CHROME_MAJOR_VERSION:()=>ei,CHROME_VERSION:()=>Vc,EDGE_VERSION:()=>yc,EDG_MAJOR_VERSION:()=>Xu,EDG_VERSION:()=>Ac,FIREFOX_MAJOR_VERSION:()=>zu,FIREFOX_VERSION:()=>Sc,HUAWEI_VERSION:()=>xc,IE_VERSION:()=>BE,IOS_MAIN_VERSION:()=>Yt,IOS_VERSION:()=>Fi,IPADQQB_VERSION:()=>Mc,IS_ANDROID:()=>at,IS_ANDROID_WEBVIEW:()=>jE,IS_ANY_SAFARI:()=>Ui,IS_CHROME:()=>Ds,IS_CHROME_OS:()=>Qu,IS_CHROMIUM_BASE:()=>Kr,IS_EDG:()=>As,IS_EDGE:()=>ys,IS_ELECTRON:()=>WE,IS_FIREFOX:()=>Qt,IS_HEADLESS_CHROME:()=>tl,IS_HONOR:()=>Ku,IS_HUAWEI:()=>Zu,IS_HUAWEIBROWSER:()=>Bn,IS_IE:()=>rh,IS_IE8:()=>$E,IS_IOS:()=>lt,IS_IOS_13_OR_14:()=>il,IS_IOS_15_1:()=>rl,IS_IPAD:()=>Ss,IS_IPADQQB:()=>Vn,IS_IPAD_PRO:()=>qu,IS_IPHONE:()=>Li,IS_IPOD:()=>th,IS_LINUX:()=>Fn,IS_LOCAL:()=>Tr,IS_MAC:()=>_r,IS_MACQQB:()=>Un,IS_MIBROWSER:()=>$n,IS_MQQB:()=>Cs,IS_NATIVE_ANDROID:()=>FE,IS_OLD_ANDROID:()=>VE,IS_OPENHARMONY:()=>el,IS_OPPOBROWSER:()=>Wn,IS_SAFARI:()=>Mt,IS_SAFARI_15_1:()=>qE,IS_SAMSUNGBROWSER:()=>Hn,IS_SOGOU:()=>kn,IS_SOGOUM:()=>Pn,IS_TBS:()=>Er,IS_UCBROWSER:()=>Yu,IS_VIVOBROWSER:()=>Gn,IS_WECHAT:()=>Rs,IS_WIN:()=>Ao,IS_WQQB:()=>Ln,IS_WX:()=>HE,IS_X5MQQB:()=>vs,IS_XWEB:()=>bs,MACQQB_VERSION:()=>wc,MI_VERSION:()=>Oc,MQQB_VERSION:()=>Is,OPENHARMONY_VERSION:()=>GE,OPPO_VERSION:()=>kc,SAFARI_VERSION:()=>Vi,SAMSUNG_VERSION:()=>Pc,SOGOUM_VERSION:()=>bc,SOGOU_VERSION:()=>Rc,TBS_VERSION:()=>vc,UA_DATA_STRING:()=>gr,USER_AGENT:()=>Xt,VIVO_VERSION:()=>Lc,WECHAT_VERSION:()=>Dc,WQQB_VERSION:()=>Nc,XWEB_VERSION:()=>Cc,browserInfo:()=>Ur,getBrowserInfo:()=>ih,getChromeMajorVersion:()=>Uc,getDeviceModel:()=>qn,getOSName:()=>Ns,getOSNumber:()=>Jn,getOSString:()=>bo,getOSType:()=>nl,getTerminalType:()=>sl,getUserAgentData:()=>jn,isLocalStorageEnabled:()=>ti,isMobile:()=>ol});var Xt=typeof navigator=="undefined"?"":navigator.userAgent,Ie=i=>new RegExp(i,"i").test(Xt),ft=i=>{if(Ie(i)){let t=new RegExp(`${i}\\/([\\d.]+)`),e=Xt.match(t);if(e&&e[1])return e[1]}return""},ju=i=>{if(Ie(i)){let t=new RegExp(`${i}\\/(\\d+)`),e=Xt.match(t);if(e&&e[1])return parseFloat(e[1])}return NaN},Kp=/AppleWebKit\/([\d.]+)/i.exec(Xt),UE=Kp?parseFloat(Kp[1]):NaN,Ss=Ie("iPad"),qu=typeof navigator!="undefined"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&Ie("Macintosh"),Li=Ie("iPhone")&&!Ss,th=Ie("iPod"),lt=Li||Ss||th||qu,at=Ie("Android"),Ju=function(){if(at){let i=Xt.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}(),VE=at&&Ie("webkit")&&Ju<2.3,FE=at&&Ju<5&&UE<537,Qt=Ie("Firefox"),Sc=ft("Firefox"),zu=ju("Firefox"),ys=Ie("Edge"),yc=ft("Edge"),As=Ie("Edg"),Ac=ft("Edg"),Xu=ju("Edg"),Pn=Ie("SogouMobileBrowser"),bc=ft("SogouMobileBrowser"),kn=Ie("MetaSr\\s"),Rc=ft("MetaSr\\s"),Er=Ie("TBS"),vc=ft("TBS"),bs=Ie("XWEB"),Cc=ft("XWEB"),$E=Ie("MSIE\\s8\\.0"),rh=Ie("MSIE\\/\\d+"),BE=function(){if(rh){let i=/MSIE\s(\d+)\.\d/.exec(Xt),t=i&&parseFloat(i[1]);return!t&&/Trident\/7.0/i.test(Xt)&&/rv:11.0/.test(Xt)&&(t=11),t}return NaN}(),Rs=Ie("(micromessenger|webbrowser)"),Dc=ft("MicroMessenger"),vs=!Er&&Ie("MQQBrowser")&&Ie("COVC"),Cs=!Er&&Ie("MQQBrowser")&&!Ie("COVC"),Is=Cs||vs?ft("MQQBrowser"):"",Ln=!Er&&Ie(" QQBrowser"),Nc=ft(" QQBrowser"),Un=!Er&&Ie("QQBrowserLite"),wc=ft("QQBrowserLite"),Vn=!Er&&Ie("MQBHD"),Mc=ft("MQBHD"),Ao=Ie("Windows"),_r=!lt&&Ie("MAC OS X"),Fn=!at&&Ie("Linux"),Qu=Ie("CrOS"),HE=Ie("MicroMessenger"),Yu=Ie("UCBrowser"),WE=Ie("Electron"),$n=Ie("MiuiBrowser"),Oc=ft("MiuiBrowser"),Bn=Ie("HuaweiBrowser"),Zu=Ie("Huawei")||Ie("HUAWEI"),Ku=Ie("Honor")||Ie("HONOR"),xc=ft("HuaweiBrowser"),Hn=Ie("SamsungBrowser"),Pc=ft("SamsungBrowser"),Wn=Ie("HeyTapBrowser"),kc=ft("HeyTapBrowser"),Gn=Ie("VivoBrowser"),Lc=ft("VivoBrowser"),el=Ie("OpenHarmony"),GE=ft("OpenHarmony"),Uc=()=>ju("Chrome"),Kr=Ie("Chrome"),Ds=!ys&&!kn&&!Pn&&!Er&&!bs&&!As&&!Ln&&!$n&&!Bn&&!Hn&&!Wn&&!Gn&&Kr,tl=Ie("HeadlessChrome"),ei=Uc(),Vc=ft("Chrome"),Mt=!Kr&&!Cs&&!vs&&!Un&&!Vn&&Ie("Safari"),Ui=Mt||lt,Vi=ft("Version"),jE=/Android.*(wv|.0.0.0)/.test(Xt),Fi=(()=>{if(qu)return Vi;if(lt){let i=Xt.match(/OS (\d+)_(\d+)/i);if(i&&i[1]){let t=i[1];return i[2]&&(t+=`.${i[2]}`),t}}return""})(),Yt=Number(Fi.split(".")[0]),qE=Vi==="15.1",rl=Fi==="15.1",il=(()=>{let i=Number(Fi.split(".")[0]);return i===14||i===13})(),Tr=typeof location=="undefined"?!1:location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1",ti=(()=>{let i;return()=>{if(typeof i=="undefined")try{i=!!window.localStorage}catch(t){i=!1}return i}})(),Ur=ih();function ih(){let i=new Map([[Qt,["Firefox",Sc]],[As,["Edg",Ac]],[Ds,["Chrome",Vc]],[Mt,["Safari",Vi]],[Er,["TBS",vc]],[bs,["XWEB",Cc]],[Rs&&Li,["WeChat",Dc]],[Ln,["QQ(Win)",Nc]],[Cs,["QQ(Mobile)",Is]],[vs,["QQ(Mobile X5)",Is]],[Un,["QQ(Mac)",wc]],[Vn,["QQ(iPad)",Mc]],[$n,["MI",Oc]],[Bn,["HW",xc]],[Hn,["Samsung",Pc]],[Wn,["OPPO",kc]],[Gn,["VIVO",Lc]],[ys,["EDGE",yc]],[Pn,["SogouMobile",bc]],[kn,["Sogou",Rc]]]),t="unknown",e="unknown";return i.has(!0)&&([t,e]=i.get(!0)),{name:t,version:e}}var $e=null;function ol(){return $e&&typeof $e.mobile=="boolean"?$e.mobile:at||lt||Li||Ss||el}var gr="";function jn(){return y(this,null,function*(){if($e)return $e;if(!navigator.userAgentData||typeof navigator.userAgentData.getHighEntropyValues!="function")return null;try{return $e=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]),$e&&!gr&&(gr=`UAData: ${$e.platform}/${$e.platformVersion}`,$e.architecture&&$e.bitness&&(gr+=` ${$e.architecture}/${$e.bitness}`),$e.mobile&&(gr+=" mobile"),$e.model&&(gr+=` model: ${$e.model}`),$e.fullVersionList&&(gr+=` ${$e.fullVersionList.filter(i=>i.brand!=="Not/A)Brand").map(i=>`${i.brand}/${i.version}`).join(",")}`)),$e}catch(i){return null}})}function qn(){return($e==null?void 0:$e.model)||""}var eh=new Map([[at,"Android"],[lt,"iOS"],[Ao,"Windows"],[_r,"MacOS"],[Fn,"Linux"],[Qu,"ChromeOS"]]),Ns=function(){return eh.get(!0)?eh.get(!0):$e?$e.platform:"unknown"};function Jn(){return Ao?1:at?2:_r?3:lt?4:Fn?5:Qu?6:0}var bo=()=>{let i=Ns();return i+=`/${Ur.name}/${Mt?Ur.version:Ur.version.split(".")[0]}`,$e!=null&&$e.platformVersion&&(i+=`/${$e.platformVersion}`),$e!=null&&$e.architecture&&(i+=`/${$e.architecture}`),i};function sl(){return at?4:Li?2:Ss?3:_r?12:Ao?5:Fn?13:el?22:1}function nl(){return at?"Android":Li?"iPhone":Ss?"iPad":_r?"Mac":Ao?"Windows":Fn?"Linux":"unknown"}var sh=Mi($i(),1),XE=new sh.default,H=XE;var Ro=(F=>(F.ROOM_DESTROY="1",F.JOIN_START="21",F.JOIN_SCHEDULE_SUCCESS="22",F.JOIN_SIGNAL_CONNECTION_START="23",F.JOIN_SIGNAL_CONNECTION_END="24",F.JOIN_SEND_CMD="25",F.JOIN_RECEIVED_CMD_RES="26",F.JOIN_SUCCESS="27",F.JOIN_FAILED="28",F.LEAVE_START="51",F.LEAVE_SEND_CMD="52",F.LEAVE_SUCCESS="53",F.PUBLISH_START="61",F.SEND_FIRST_VIDEO_FRAME="62",F.PUBLISH_FAILED="63",F.SUBSCRIBE_START="81",F.SUBSCRIBE_SUCCESS="82",F.SUBSCRIBE_FAILED="84",F.UNSUBSCRIBE_SUCCESS="83",F.LOCAL_TRACK_CAPTURE_START="101",F.LOCAL_TRACK_CAPTURE_SUCCESS="102",F.LOCAL_TRACK_CAPTURE_FAILED="103",F.LOCAL_TRACK_PUBLISHED="104",F.LOCAL_TRACK_UNPUBLISHED="105",F.LOCAL_TRACK_REPLACED="106",F.SWITCH_DEVICE_SUCCESS="107",F.TRACK_MUTED="108",F.TRACK_UNMUTED="109",F.REMOTE_TRACK_SUBSCRIBED="110",F.REMOTE_TRACK_UNSUBSCRIBED="111",F.LOCAL_TRACK_RECAPTURE="112",F.PLAY_TRACK_START="151",F.PLAYER_STATE_CHANGED="152",F.VIDEO_LOADED_DATA="153",F.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",F.SIGNAL_CONNECTION_STATE_CHANGED="201",F.PEER_CONNECTION_STATE_CHANGED="202",F.SINGLE_CONNECTION_STAT="203",F.SPC_RECONNECTED="204",F.HEARTBEAT_REPORT="251",F.RECEIVED_PUBLISHED_USER_LIST="252",F.REMOTE_PUBLISH_STATE_CHANGED="253",F.AUDIO_LEVEL_INTERVAL="260",F.NETWORK_QUALITY="261",F.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",F.QUALITY_LIMITATION_CHANGED="263",F.LOG="264",F))(Ro||{});var L=Ro;var QE="%cTRTC%c%s",YE="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",ZE="display: inline",$c=class $c{constructor(){u(this,"_isEnableUploadLog",!0);u(this,"_localJoinedUser",new Map);u(this,"_queue",[]);u(this,"_timeoutId",-1);u(this,"_logLevel",1);u(this,"_logLevelToUpload",2);!us&&!In&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){H.on(L.JOIN_SCHEDULE_SUCCESS,({schedule:t})=>{var e;(e=t==null?void 0:t.config)!=null&&e.logLevelToUpload&&hr[t.config.logLevelToUpload]&&(this._logLevelToUpload=t.config.logLevelToUpload)}),H.on(L.JOIN_SUCCESS,({room:t})=>{this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload()}),H.once(L.JOIN_FAILED,()=>{this.startUpload()}),H.on(L.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(we(r.userId)&&je(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 y(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:d,logs:p}=o[s];yield this.uploadLogWithRetry(JSON.stringify({timestamp:oc(),sdkAppId:String(d),userId:n,version:rt,log:p.map(m=>m.log).join(`
|
|
4
|
+
`)}),d),p.forEach(m=>m.uploaded=!0)}}catch(o){}let r=e.filter(o=>!o.uploaded);r.length>0&&(this._queue=r.concat(this._queue))})}uploadLogWithRetry(t,e){return ki({retryFunction:()=>Zr({url:Yr(e,Oi.LOG),body:t,timeout:5e3,priority:"low"}),settings:{retries:3,timeout:2e3},onError:({retry:r})=>{r()}})()}getPrefix(t){let e=new Date;return e.setTime(Tn()),`[${sc(e)}] <${hr[t]}>`}getLogLevel(){return this._logLevel}setLogLevel(t){V(hr[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(we(t))return t;try{return t instanceof Error?t.toString():JSON.stringify(t)}catch(e){return""}}log(t,e,r=!0,o,s){var p;e.unshift(this.getPrefix(t));let n={log:e.reduce((m,g)=>`${m} ${this.logChunkToString(g)}`.trim(),""),level:t,userId:o,sdkAppId:s,forAllJoinedClients:r};if(H.emit(L.LOG,{log:n}),this._isEnableUploadLog&&t>=this._logLevelToUpload&&this._queue.push(n),t<this._logLevel)return;let d=((p=hr[t])==null?void 0:p.toLowerCase())||"info";$c.PRINT_LOG_TAG?console[d](QE,YE,ZE,...e):console[d](...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){return new Ts(t)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),r=e?Number(e):-1;hr[r]&&(this._logLevelToUpload=r)}getQueue(){return this._queue}};u($c,"PRINT_LOG_TAG",!(lt||at||tl));var cl=$c,$=new cl;var KE=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)})},Xn=KE;var dl=class{constructor(){u(this,"_prefix","TRTC");u(this,"_queue",new Map)}getRealKey(t){return`${this._prefix}_${t}`}checkStorage(){if(!ti())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(ti())try{for(let[t,e]of this._queue)localStorage.setItem(t,JSON.stringify(e))}catch(t){$.warn(t)}}getItem(t){if(!ti())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){$.warn(e)}}setItem(t,e){if(ti())try{let r={expiresIn:Date.now()+ac,value:e};this._queue.set(this.getRealKey(t),r)}catch(r){$.warn(r)}}deleteItem(t){if(!ti())return!1;try{return t=this.getRealKey(t),this._queue.delete(t),localStorage.removeItem(t),!0}catch(e){return $.warn(e),!1}}clear(){if(ti())try{localStorage.clear()}catch(t){$.warn(t)}}},Ms=new dl;var Bi={};Jr(Bi,{HTTPS_API:()=>g_,IS_GET_CAPABILITIES_SUPPORTED:()=>Ml,IS_GET_SETTINGS_SUPPORTED:()=>ks,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>R_,IS_INSERTABLE_STREAM_SUPPORTED:()=>oa,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>N_,IS_RTC_RTP_SENDER_SUPPORTED:()=>ia,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>xh,IS_SEI_SUPPORTED:()=>sa,IS_SPC_SUPPORTED:()=>S_,basis:()=>C_,capabilityCheck:()=>xl,checkSystemRequirementsInternal:()=>Zc,decodeSupportStatus:()=>vh,encodeSupportStatus:()=>Dl,getBrowserInfo:()=>Qc,getDisplayResolution:()=>Ch,isAddTransceiverSupported:()=>Oh,isBrowserSupported:()=>Nl,isGetReceiversSupported:()=>T_,isGetSendersSupported:()=>Mh,isGetTransceiversSupported:()=>I_,isGetUserMediaSupported:()=>Dh,isMediaDevicesSupported:()=>Yc,isMediaSessionSupported:()=>kh,isMediaStreamTrackProcessorSupported:()=>wl,isReplaceTrackSupported:()=>A_,isRequestVideoFrameCallbackSupported:()=>Oo,isSIMDSupported:()=>v_,isScreenCaptureApiAvailable:()=>ta,isSelectedCandidatePair:()=>E_,isSetParametersSupported:()=>b_,isSmallStreamAPISupported:()=>wh,isSmallStreamSupported:()=>ra,isStopTransceiverSupported:()=>y_,isTRTCSupported:()=>h_,isUnifiedPlanDefault:()=>__,isUsedInHttpProtocol:()=>ai,isWebAudioSupported:()=>Nh,isWebCodecSupported:()=>Ph,isWebCodecsSupported:()=>Rh,isWebRTCSupported:()=>Ol,isWebTransportSupported:()=>Lh});var Sl={};Jr(Sl,{AUDIO_LEVEL_SCALE:()=>oi,AudioCodecPipelineType:()=>qc,AudioDecoderDowngradeState:()=>ml,AudioPlayerMode:()=>gl,AudioType:()=>hl,BASIC_TYPE:()=>Do,BannedReason:()=>El,CONNECTION_CLOSED_REASON:()=>ah,ClientEvent:()=>ul,CodecType:()=>hh,ConnectionEvent:()=>nh,ConnectionState:()=>Hc,DECODE_FAILED_ERROR_CODE:()=>Il,FacingMode:()=>Wc,LeaveReason:()=>_l,LocalTrackEvent:()=>Bc,MULTI_VIDEO_DATA_TYPE:()=>ii,MediaType:()=>Ct,MediaTypeLabel:()=>e_,MonitorEventId:()=>Zn,MutedFlag:()=>dh,NetworkQualityValue:()=>mh,PlayerState:()=>Os,ReceiveMode:()=>ph,RemoteStreamType:()=>Vr,RemoteTrackEvent:()=>xs,RoomEvent:()=>vo,SceneNumber:()=>ll,StreamEvent:()=>ch,StreamType:()=>lh,SubscribeMediaType:()=>Qn,TIMER_TYPE:()=>No,TRACK_ACTION:()=>uh,TRACK_KIND:()=>pl,TrackEvent:()=>ri,UserRole:()=>jt,UserRoleNumber:()=>Co,VideoCodec:()=>Tl,VideoCodecPipelineType:()=>jc,VideoContentHint:()=>Kn,VideoDecoderDowngradeState:()=>Yn,VideoPlayerMode:()=>Gc,VideoType:()=>fl});var nh=(P=>(P.TRACK_ADDED="track-added",P.TRACK_UPDATED="track-updated",P.TRACK_SUBSCRIBED="track-subscribed",P.STREAM_ADDED="stream-added",P.STREAM_REMOVED="stream-removed",P.STREAM_UPDATED="stream-updated",P.STREAM_PUBLISHED="stream-published",P.STREAM_SUBSCRIBED="stream-subscribed",P.STREAM_UNSUBSCRIBED="stream-unsubscribed",P.STATE_CHANGED="state-changed",P.ERROR="error",P.CONNECTION_STATE_CHANGED="connection-state-changed",P.FIREWALL_RESTRICTION="firewall-restriction",P.SEI_MESSAGE="sei-message",P.CLOSED="closed",P))(nh||{}),ah=(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))(ah||{}),ul=(x=>(x.STREAM_ADDED="stream-added",x.STREAM_REMOVED="stream-removed",x.STREAM_UPDATED="stream-updated",x.STREAM_SUBSCRIBED="stream-subscribed",x.CONNECTION_STATE_CHANGED="connection-state-changed",x.PEER_JOIN="peer-join",x.PEER_LEAVE="peer-leave",x.MUTE_AUDIO="mute-audio",x.MUTE_VIDEO="mute-video",x.UNMUTE_AUDIO="unmute-audio",x.UNMUTE_VIDEO="unmute-video",x.CLIENT_BANNED="client-banned",x.NETWORK_QUALITY="network-quality",x.AUDIO_VOLUME="audio-volume",x.SEI_MESSAGE="sei-message",x.ERROR="error",x))(ul||{}),ch=(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))(ch||{}),Bc=(n=>(n.DEVICE_AUTO_RECOVERED="1",n.DEVICE_RECOVER_FAILED="5",n.DEVICE_CHANGED="2",n.ERROR="3",n.PUBLISH_STATE_CHANGED="4",n.ENCODE_FAILED="6",n))(Bc||{}),Os=(r=>(r.PAUSED="PAUSED",r.PLAYING="PLAYING",r.STOPPED="STOPPED",r))(Os||{}),vo=(Q=>(Q.PEER_JOIN="peer-join",Q.PEER_LEAVE="peer-leave",Q.SIGNAL_CONNECTION_STATE_CHANGED="signal-connection-state-changed",Q.MEDIA_CONNECTION_STATE_CHANGED="media-connection-state-changed",Q.BANNED="banned",Q.NETWORK_QUALITY="network-quality",Q.AUDIO_VOLUME="audio-volume",Q.SEI_MESSAGE="sei-message",Q.ERROR="error",Q.REMOTE_PUBLISH_STATE_CHANGED="remote-publish-state-changed",Q.REMOTE_PUBLISHED="remote-published",Q.REMOTE_UNPUBLISHED="remote-unpublished",Q.FIREWALL_RESTRICTION="firewall-restriction",Q.HEARTBEAT_REPORT="heartbeat-report",Q.CUSTOM_MESSAGE="custom-message",Q.LAYER_DATA="layerData",Q.FIRST_VIDEO_FRAME="first-video-frame",Q.DUMP="dump",Q))(vo||{}),ri=(d=>(d.PLAYER_STATE_CHANGED="player-state-changed",d.MUTE="mute",d.UNMUTE="unmute",d.ERROR="error",d.INPUT_MEDIA_TRACK_CHANGED="input-media-track-changed",d.OUTPUT_MEDIA_TRACK_CHANGED="output-media-track-changed",d.FIRST_VIDEO_FRAME="first-video-frame",d))(ri||{}),xs=(e=>(e.DECODE_FAILED="decode-failed",e.DECODE_DOWNGRADE_STATE_CHANGED="decode-downgrade-state-changed",e))(xs||{}),dh=(d=>(d[d.VIDEO=1]="VIDEO",d[d.SMALL=2]="SMALL",d[d.AUX=4]="AUX",d[d.AUDIO=8]="AUDIO",d[d.VIDEO_MUTE=16]="VIDEO_MUTE",d[d.AUX_MUTE=32]="AUX_MUTE",d[d.AUDIO_MUTE=64]="AUDIO_MUTE",d))(dh||{}),ll=(e=>(e[e.RTC=1]="RTC",e[e.LIVE=2]="LIVE",e))(ll||{}),Co=(e=>(e[e.ANCHOR=20]="ANCHOR",e[e.AUDIENCE=21]="AUDIENCE",e))(Co||{}),jt=(e=>(e.ANCHOR="anchor",e.AUDIENCE="audience",e))(jt||{}),Hc=(s=>(s.CONNECTED="CONNECTED",s.DISCONNECTED="DISCONNECTED",s.CONNECTING="CONNECTING",s.RECONNECTED="RECONNECTED",s.RECONNECTING="RECONNECTING",s))(Hc||{}),ml=(o=>(o.INITIALIZED="INITIALIZED",o.STARTING="STARTING",o.STARTED="STARTED",o.FAILED="FAILED",o))(ml||{}),Yn=(o=>(o.INITIALIZED="INITIALIZED",o.STARTING="STARTING",o.STARTED="STARTED",o.FAILED="FAILED",o))(Yn||{}),pl=(r=>(r.AUDIO="audio",r.VIDEO="video",r.AUXILIARY="auxVideo",r))(pl||{}),uh=(e=>(e.ADD="add",e.REMOVE="remove",e))(uh||{}),Ct=(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))(Ct||{}),e_={1:"audio",2:"auxVideo",4:"video"},hl=(t=>(t[t.opus=111]="opus",t))(hl||{}),fl=(e=>(e[e.h264=100]="h264",e[e.vp8=101]="vp8",e))(fl||{}),lh=(e=>(e.Big="big",e.Small="small",e))(lh||{}),Vr=(e=>(e.Main="main",e.Aux="auxiliary",e))(Vr||{}),ii=(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))(ii||{}),Zn=(G=>(G[G.PUBLISH_VIDEO=32768]="PUBLISH_VIDEO",G[G.PUBLISH_AUDIO=32769]="PUBLISH_AUDIO",G[G.UNPUBLISH_VIDEO=32770]="UNPUBLISH_VIDEO",G[G.UNPUBLISH_AUDIO=32771]="UNPUBLISH_AUDIO",G[G.MUTE_AUDIO=32772]="MUTE_AUDIO",G[G.MUTE_VIDEO=32773]="MUTE_VIDEO",G[G.UNMUTE_AUDIO=32774]="UNMUTE_AUDIO",G[G.UNMUTE_VIDEO=32775]="UNMUTE_VIDEO",G[G.SUBSCRIBE_VIDEO=32776]="SUBSCRIBE_VIDEO",G[G.SUBSCRIBE_AUDIO=32777]="SUBSCRIBE_AUDIO",G[G.UNSUBSCRIBE_VIDEO=32778]="UNSUBSCRIBE_VIDEO",G[G.UNSUBSCRIBE_AUDIO=32779]="UNSUBSCRIBE_AUDIO",G[G.SWITCH_CAMERA=32780]="SWITCH_CAMERA",G[G.SWITCH_MICROPHONE=32781]="SWITCH_MICROPHONE",G[G.REPLACE_VIDEO=32782]="REPLACE_VIDEO",G[G.REPLACE_AUDIO=32783]="REPLACE_AUDIO",G[G.MUTE_REMOTE_VIDEO=32784]="MUTE_REMOTE_VIDEO",G[G.MUTE_REMOTE_AUDIO=32785]="MUTE_REMOTE_AUDIO",G[G.UNMUTE_REMOTE_VIDEO=32786]="UNMUTE_REMOTE_VIDEO",G[G.UNMUTE_REMOTE_AUDIO=32787]="UNMUTE_REMOTE_AUDIO",G[G.JOIN=32788]="JOIN",G[G.LEAVE=32789]="LEAVE",G[G.SIGNAL_DISCONNECTED=32790]="SIGNAL_DISCONNECTED",G[G.SIGNAL_CONNECTED=32791]="SIGNAL_CONNECTED",G[G.TRANSPORT_UPLINK_CONNECTED=32792]="TRANSPORT_UPLINK_CONNECTED",G[G.TRANSPORT_DOWNLINK_CONNECTED=32793]="TRANSPORT_DOWNLINK_CONNECTED",G[G.SIGNAl_RECONNECTING=32794]="SIGNAl_RECONNECTING",G[G.SIGNAL_RECONNECT_SUCCESS=32795]="SIGNAL_RECONNECT_SUCCESS",G[G.SIGNAL_RECONNECT_FAIL=32796]="SIGNAL_RECONNECT_FAIL",G[G.TRANSPORT_UPLINK_RECONNECTING=32797]="TRANSPORT_UPLINK_RECONNECTING",G[G.TRANSPORT_UPLINK_RECONNECT_SUCCESS=32798]="TRANSPORT_UPLINK_RECONNECT_SUCCESS",G[G.TRANSPORT_UPLINK_RECONNECT_FAIL=32799]="TRANSPORT_UPLINK_RECONNECT_FAIL",G[G.TRANSPORT_DOWNLINK_RECONNECTING=32800]="TRANSPORT_DOWNLINK_RECONNECTING",G[G.TRANSPORT_DOWNLINK_RECONNECT_SUCCESS=32801]="TRANSPORT_DOWNLINK_RECONNECT_SUCCESS",G[G.TRANSPORT_DOWNLINK_RECONNECT_FAIL=32802]="TRANSPORT_DOWNLINK_RECONNECT_FAIL",G[G.SUBSCRIBE_SMALL_VIDEO=32803]="SUBSCRIBE_SMALL_VIDEO",G[G.UNSUBSCRIBE_SMALL_VIDEO=32804]="UNSUBSCRIBE_SMALL_VIDEO",G[G.PUBLISH_AUX=32805]="PUBLISH_AUX",G[G.UNPUBLISH_AUX=32806]="UNPUBLISH_AUX",G[G.DEVICE_CAPTURE=2003]="DEVICE_CAPTURE",G[G.VIDEO_ENCODER=4004]="VIDEO_ENCODER",G[G.VIDEO_DECODER=4005]="VIDEO_DECODER",G))(Zn||{}),mh=(d=>(d[d.UNKNOWN=0]="UNKNOWN",d[d.EXCELLENT=1]="EXCELLENT",d[d.GOOD=2]="GOOD",d[d.POOR=3]="POOR",d[d.BAD=4]="BAD",d[d.VERY_BAD=5]="VERY_BAD",d[d.DISCONNECTED=6]="DISCONNECTED",d))(mh||{}),ph=(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))(ph||{}),Wc=(e=>(e.user="user",e.environment="environment",e))(Wc||{}),Gc=(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))(Gc||{}),gl=(e=>(e[e.ELEMENT=0]="ELEMENT",e[e.CONTEXT=1]="CONTEXT",e))(gl||{}),El=(o=>(o.BANNED="banned",o.KICK="kick",o.USER_TIME_OUT="user_time_out",o.ROOM_DISBAND="room_disband",o))(El||{}),_l=(m=>(m[m.USER_EXIT_REASON_TC_USER_EXIT_NORMAL=0]="USER_EXIT_REASON_TC_USER_EXIT_NORMAL",m[m.USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT=1]="USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT",m[m.USER_EXIT_REASON_TC_USER_EXIT_KICKED=2]="USER_EXIT_REASON_TC_USER_EXIT_KICKED",m[m.USER_EXIT_REASON_TC_USER_EXIT_CHANGED=3]="USER_EXIT_REASON_TC_USER_EXIT_CHANGED",m[m.USER_KICK_OUT_CODE_BUSINESS_USER=4]="USER_KICK_OUT_CODE_BUSINESS_USER",m[m.USER_KICK_OUT_CODE_BUSINESS_ROOM=5]="USER_KICK_OUT_CODE_BUSINESS_ROOM",m[m.USER_KICK_OUT_CODE_SERVER_USER=6]="USER_KICK_OUT_CODE_SERVER_USER",m[m.USER_KICK_OUT_CODE_SERVER_ROOM=7]="USER_KICK_OUT_CODE_SERVER_ROOM",m[m.USER_KICK_SESS_EXSIT=8]="USER_KICK_SESS_EXSIT",m))(_l||{}),oi=1e8,Qn=class{constructor(){u(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)}},Do=(s=>(s.String="string",s.Number="number",s.Boolean="boolean",s.Array="array",s.Object="object",s))(Do||{}),Tl=(r=>(r.H264="h264",r.H265="h265",r.VP8="vp8",r))(Tl||{}),jc=(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))(jc||{}),qc=(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))(qc||{}),hh=(r=>(r.WebRTC="webrtc",r.WebCodecs="webcodecs",r.WebAssembly="webassembly",r))(hh||{}),Il=(_=>(_[_.SUCCESS=0]="SUCCESS",_[_.FAILED=1]="FAILED",_[_.WEBCODEC_INIT=2]="WEBCODEC_INIT",_[_.WEBCODEC_CONFIG_NOT_SUPPORT=3]="WEBCODEC_CONFIG_NOT_SUPPORT",_[_.WEBCODEC_DECODER_ERROR=4]="WEBCODEC_DECODER_ERROR",_[_.WEBCODEC_TRACK_MUTE=5]="WEBCODEC_TRACK_MUTE",_[_.WASM_INIT=6]="WASM_INIT",_[_.WASM_WEBGL_UNAVALIABLE=7]="WASM_WEBGL_UNAVALIABLE",_[_.WASM_DECODER_ERROR=8]="WASM_DECODER_ERROR",_[_.WASM_TRACK_MUTE=9]="WASM_TRACK_MUTE",_[_.TEST=10]="TEST",_))(Il||{}),Kn=(o=>(o.NONE="",o.DETAIL="detail",o.MOTION="motion",o.TEXT="text",o))(Kn||{}),No=(s=>(s.INTERVAL="interval",s.TIMEOUT="timeout",s.RAF="raf",s.RIC="ric",s.INTERVAL_IN_WORKER="intervalInWorker",s))(No||{});var ct={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"},qt={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: ${ht(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: ${ht(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 fh=(i,t)=>t?`${Mr}/${i}/${t}`:`${Mr}/${i}/index.html`;var t_=()=>{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(ku);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 dt(i){let{key:t,data:e,link:r,addDocLink:o=!0}=i,s="",n="",d="";Xe(qt[t])?s=qt[t](e):we(qt[t])&&(s=qt[t]);let{TRTC_ERROR_INFO:p,TRTC_ERROR_LINK:m}=t_();r?d=`${r.className}.html#${r.fnName}`:m&&m[t]&&(Xe(m[t])?d=m[t](e):we(m[t])&&(d=m[t]));let g=s;return fr()&&(p&&p[t]&&(Xe(p[t])?n=p[t](e):we(p[t])&&(n=p[t])),n&&(o?g=`${n}
|
|
5
|
+
\u8BF7\u67E5\u770B\u6587\u6863: ${fh("zh-cn",d)}
|
|
6
6
|
|
|
7
|
-
`:
|
|
7
|
+
`:g=`${n}
|
|
8
8
|
|
|
9
|
-
`,
|
|
10
|
-
Refer to: ${
|
|
11
|
-
`),E}var Rl=Di(yh(),1);var o_=1,s_=0,zc=class{constructor(t=!0){u(this,"countMap",new Map);u(this,"distributionMap",new Map);u(this,"version");u(this,"log",B.createLogger({id:"kv"}));t&&(H.on("102",({track:e,cost:r})=>{this.addSuccessEvent({key:e.kind===D.AUDIO?501700:511700,cost:r})}),H.on("103",({track:e,error:r})=>{this.addFailedEvent({key:e.kind===D.AUDIO?501700:511700,error:r})}))}getReportData(){let t={msg_sdk_basic_info:{uint32_sdk_version:Ic(this.version||rt),uint32_terminal_type:15,bytes_device_name:"",bytes_os_version:"",uint32_framework:30,uint32_network_type:0},stats_count:[...this.countMap.entries()].map(([e,r])=>({uint32_key:e,uint32_count:r})),stats_distribution:[...this.distributionMap.entries()].map(([e,r])=>({uint32_key:e,distribution_items:[...r.entries()].map(([o,s])=>({uint32_item_key:o,uint32_item_value:s}))}))};return this.countMap.clear(),this.distributionMap.clear(),t}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}){var d;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;this.countMap.set(t,(this.countMap.get(t)||0)+1);let s=((d=this.distributionMap)==null?void 0:d.get(t))||new Map,n=0;if(je(r))n=Math.floor(e/r);else for(let p=r.length-1;p>0;p--)if(e>r[p]){n=p;break}s.set(n,(s.get(n)||0)+1),this.distributionMap.set(t,s)}addSuccessEvent({key:t,cost:e,timeKey:r,split:o}){if(t&&(this.addEnum({key:t,value:o_,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&&(je(e)?r=e:(!$(e.extraCode)||!$(e.code))&&(r=e.extraCode||e.code)),this.addEnum({key:t,value:s_,useUV:!1}),this.addEnum({key:t,value:r,useUV:!1})}},Xc=(me=>(me[me.enterRoom=500700]="enterRoom",me[me.exitRoom=500701]="exitRoom",me[me.switchRole=500702]="switchRole",me[me.destroy=500703]="destroy",me[me.startLocalAudio=500704]="startLocalAudio",me[me.updateLocalAudio=500705]="updateLocalAudio",me[me.stopLocalAudio=500706]="stopLocalAudio",me[me.startLocalVideo=500707]="startLocalVideo",me[me.updateLocalVideo=500708]="updateLocalVideo",me[me.stopLocalVideo=500709]="stopLocalVideo",me[me.startScreenShare=500710]="startScreenShare",me[me.updateScreenShare=500711]="updateScreenShare",me[me.stopScreenShare=500712]="stopScreenShare",me[me.startRemoteVideo=500713]="startRemoteVideo",me[me.updateRemoteVideo=500714]="updateRemoteVideo",me[me.stopRemoteVideo=500715]="stopRemoteVideo",me[me.muteRemoteAudio=500716]="muteRemoteAudio",me[me.setRemoteAudioVolume=500717]="setRemoteAudioVolume",me[me.use=500718]="use",me[me.sendSEIMessage=5e5]="sendSEIMessage",me[me.sendCustomMessage=500001]="sendCustomMessage",me))(Xc||{}),yl=(m=>(m[m.AudioMixer=550700]="AudioMixer",m[m.AIDenoiser=551700]="AIDenoiser",m[m.VirtualBackground=570700]="VirtualBackground",m[m.Beauty=571700]="Beauty",m[m.Watermark=572700]="Watermark",m[m.BasicBeauty=574700]="BasicBeauty",m[m.CDNStreaming=590700]="CDNStreaming",m[m.DeviceDetector=591700]="DeviceDetector",m[m.Debug=592700]="Debug",m))(yl||{}),Al=(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))(Al||{}),bl=(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))(bl||{});var n_=new zc(!0),No=new zc(!1);var Y=n_;var xe={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},a_=new Map([[gr,["Firefox",yc]],[Ss,["Edg",bc]],[Cs,["Chrome",Vc]],[Mt,["Safari",ki]],[Er,["TBS",Cc]],[Un,["XWEB",Nc]],[ys&&_o,["WeChat",Dc]],[Vn,["QQ(Win)",wc]],[bs,["QQ(Mobile)",Ts]],[As,["QQ(Mobile X5)",Ts]],[Bn,["QQ(Mac)",Mc]],[$n,["QQ(iPad)",Oc]],[Hn,["MI",Pc]],[Wn,["HW",xc]],[Gn,["Samsung",kc]],[Rs,["OPPO",Lc]],[vs,["VIVO",Uc]],[Is,["EDGE",Ac]],[kn,["SogouMobile",Rc]],[Ln,["Sogou",vc]]]);function Yc(){let i=a_.get(!0),t=i?i[0]:"unknown",e=i?i[1]:"unknown";return{browserName:t,browserVersion:e}}var Cl=function(){return!(Qu||Is||Ss&&zu<80||gr&&Ju<56)},bh=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder","MediaStreamTrackGenerator"].every(t=>t in window)},Zc=function(){if(!navigator.mediaDevices)return si()||B.error(qt.NOT_SUPPORTED_MEDIA),!1;let i=["getUserMedia","enumerateDevices"];return i.filter(t=>t in navigator.mediaDevices).length===i.length},Ah=!1;function si(){return location.protocol==="http:"&&!Tr?(Ah||B.error(at({key:nt.NOT_SUPPORTED_HTTP})),Ah=!0,!0):!1}var Nl=function(){return(window==null?void 0:window.OffscreenCanvas)&&(window==null?void 0:window.MediaStreamTrackProcessor)&&(window==null?void 0:window.MediaStreamTrackGenerator)},vl=function(){return y(this,null,function*(){if(xe.detail.isH264EncodeSupported&&xe.detail.isVp8EncodeSupported)return{isH264EncodeSupported:xe.detail.isH264EncodeSupported,isVp8EncodeSupported:xe.detail.isVp8EncodeSupported};let i,t=!1,e=!1;try{let r=new RTCPeerConnection,o=document.createElement(D.CANVAS);o.getContext("2d");let s=o.captureStream(0);return r.addTrack(s.getVideoTracks()[0],s),i=yield r.createOffer(),i.sdp.toLowerCase().indexOf("h264")!==-1&&(t=!0),i.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0),r.close(),xe.detail.isH264EncodeSupported=t,xe.detail.isVp8EncodeSupported=e,{isH264EncodeSupported:xe.detail.isH264EncodeSupported,isVp8EncodeSupported:xe.detail.isVp8EncodeSupported}}catch(r){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1}}})},Rh=function(){return y(this,null,function*(){if(xe.detail.isH264DecodeSupported&&xe.detail.isVp8DecodeSupported)return{isH264DecodeSupported:xe.detail.isH264DecodeSupported,isVp8DecodeSupported:xe.detail.isVp8DecodeSupported};let i,t=!1,e=!1;try{let r=new RTCPeerConnection;return i=yield r.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0}),i.sdp.toLowerCase().indexOf("h264")!==-1&&(t=!0),i.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0),r.close(),{isH264DecodeSupported:t,isVp8DecodeSupported:e}}catch(r){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1}}})},Kc=Sc(()=>y(void 0,null,function*(){if(xe.result&&xe.detail.isH264EncodeSupported&&xe.detail.isVp8EncodeSupported&&xe.detail.isH264DecodeSupported&&xe.detail.isVp8DecodeSupported)return xe;let i=Date.now(),t=Cl(),e=wl(),r=bh(),o=Zc(),{isH264EncodeSupported:s,isVp8EncodeSupported:n}=yield vl(),{isH264DecodeSupported:d,isVp8DecodeSupported:p}=yield Rh();if(!s||!n){let m=yield vl();B.warn(`detect encode again h264:${s} vp8:${n} result: ${JSON.stringify(m)}`),s=m.isH264EncodeSupported,n=m.isVp8EncodeSupported}if(s&&d&&(Rs||vs||el)&&!Er&&jn()<79){let{encode:m,decode:E}=yield d_();s=m,d=E}return xe.result=t&&e&&o&&(s||n)&&(d||p),xe.detail.isBrowserSupported=t,xe.detail.isWebRTCSupported=e,xe.detail.isWebCodecsSupported=r,xe.detail.isMediaDevicesSupported=o,xe.detail.isScreenShareSupported=ta(),xe.detail.isSmallStreamSupported=ra(),xe.detail.isH264EncodeSupported=s,xe.detail.isVp8EncodeSupported=n,xe.detail.isH264DecodeSupported=d,xe.detail.isVp8DecodeSupported=p,xe.result||B.error(`${navigator.userAgent} ${_c(xe.detail,!1)}`),y_(),Y.addNumber({key:523800,value:Date.now()-i}),xe})),c_=function(){return xe.result},ta=function(){return!!(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)},Qc=null;function d_(){return y(this,null,function*(){return Qc||(Qc=new Promise(i=>y(this,null,function*(){let t={encode:!1,decode:!1},e=()=>{};try{B.warn("detectH264Supported start");let r=document.createElement("canvas"),o=r.getContext("2d");r.width=320,r.height=240;let s=setInterval(()=>{o.fillText("test",Math.floor(Math.random()*320),Math.floor(Math.random()*240))},66),n=-1,d=-1;e=()=>{clearInterval(n),clearInterval(s),clearTimeout(d),m.close(),E.close(),p.getTracks().forEach(x=>x.stop())},d=setTimeout(()=>{e(),i(t)},2*1e3);let p=r.captureStream(),m=new RTCPeerConnection({}),E=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});m.addEventListener("icecandidate",x=>E.addIceCandidate(x.candidate)),E.addEventListener("icecandidate",x=>m.addIceCandidate(x.candidate)),m.addTrack(p.getVideoTracks()[0],p);let _=yield m.createOffer();yield m.setLocalDescription(_),yield E.setRemoteDescription(_);let b=yield E.createAnswer(),C=Rl.default.parse(b.sdp),k=C.media[0].rtp.findIndex(x=>x.codec==="H264");C.media[0].rtp=[C.media[0].rtp[k]],C.media[0].fmtp=C.media[0].fmtp.filter(x=>x.payload===C.media[0].rtp[0].payload),C.media[0].rtcpFb&&(C.media[0].rtcpFb=C.media[0].rtcpFb.filter(x=>x.payload===C.media[0].rtp[0].payload)),b.sdp=Rl.default.write(C),yield E.setLocalDescription(b),yield m.setRemoteDescription(b),n=setInterval(()=>y(this,null,function*(){t.encode&&t.decode&&(e(),i(t));let x=yield m.getSenders()[0].getStats(),P=yield E.getReceivers()[0].getStats();t.encode||x.forEach(J=>{J.type==="outbound-rtp"&&J.mediaType===D.VIDEO&&J.bytesSent>0&&(t.encode=!0)}),t.decode||P.forEach(J=>{J.type==="inbound-rtp"&&J.mediaType===D.VIDEO&&J.bytesReceived>0&&(t.decode=!0)})}),100)}catch(r){e(),B.warn(r),i(t)}})).then(i=>((!i.encode||!i.decode)&&B.warn(`detectH264Supported encode: ${i.encode} decode: ${i.decode} ${fr}`),i)),Qc)})}var u_=(i,t,e)=>{location.protocol==="http:"&&!Tr&&(i[t]=()=>{throw new he({code:te.INVALID_OPERATION,message:qt.NOT_SUPPORTED_HTTP})})},l_=function(i){return i.type==="candidate-pair"&&i.nominated&&(i.state==="in-progress"||i.state==="succeeded")?!(dt(i.selected)&&!i.selected):!1};function vh(){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 Ch(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function Nh(){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 Dh(){return"captureStream"in HTMLCanvasElement.prototype}function ra(){return ys||It||Zr&&Zr<63?!1:!!(Cl()&&Dh())}var m_=function(){if($(window.RTCRtpTransceiver)||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let i=null,t=!1;try{i=new RTCPeerConnection({sdpSemantics:Uu}),i.addTransceiver(D.AUDIO),t=!0}catch(e){}return i==null||i.close(),t};function p_(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function wh(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function h_(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function Mh(){return Qt===11?!1:"RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype}var f_=!(!Mh()||Io&&Zr<86);function g_(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}var ia="RTCRtpSender"in window;function E_(){return ia&&"replaceTrack"in window.RTCRtpSender.prototype}function __(){return ia&&"setParameters"in window.RTCRtpSender.prototype&&wh()}var T_="RTCRtpReceiver"in window&&"getSynchronizationSources"in window.RTCRtpReceiver.prototype,xs=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,Dl=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,oa=ia&&"createEncodedStreams"in window.RTCRtpSender.prototype&&jn()>=86,Oh="RTCRtpScriptTransform"in window,sa=ia&&(oa||Oh),wl=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(t=>t in window).length>0};function Ph(){let i={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return $(window.AudioDecoder)||(i.AudioDecoder=!0),$(window.AudioEncoder)||(i.AudioEncoder=!0),$(window.VideoDecoder)||(i.VideoDecoder=!0),$(window.VideoEncoder)||(i.VideoEncoder=!0),$(window.ImageDecoder)||(i.ImageDecoder=!0),i}function xh(){return"mediaSession"in navigator&&!$(navigator.mediaSession.setActionHandler)}function kh(){return!$(window.WebTransport)}function I_(){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 S_(){let i={browser:`${Ur.name}/${Ur.version}`,os:Ns(),displayResolution:vh(),isScreenShareSupported:ta(),isWebRTCSupported:wl(),isGetUserMediaSupported:Ch(),isWebAudioSupported:Nh(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:Ph(),isMediaSessionSupported:xh(),isWebTransportSupported:kh()};return navigator.userAgent.includes("miniProgram")&&(i.browser=`mini/${i.browser}`),i}var Lh="checkResult";function y_(){ws.setItem(Lh,{ua:navigator.userAgent,checkResult:xe})}function Ml(){si();let i=ws.getItem(Lh);i&&i.ua===navigator.userAgent&&(xe=i.checkResult),Kc()}function Do(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var A_="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype;var Vh=Di(Ui(),1);var Uh=Symbol("instance"),tA=Symbol("abortCtrl"),ed=Symbol("cacheResult"),na=class{constructor(t,e,r){this.oldState=t,this.newState=e,this.action=r,this.aborted=!1}abort(t){this.aborted=!0,da.call(t,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},aa=class extends Error{constructor(t,e,r){super(e),this.state=t,this.message=e,this.cause=r}};function b_(i){return typeof i=="object"&&i&&"then"in i}var ca=new Map;function qe(i,t,e={}){return(r,o,s)=>{let n=e.action||o;if(!e.context){let p=ca.get(r)||[];ca.has(r)||ca.set(r,p),p.push({from:i,to:t,action:n})}let d=s.value;s.value=function(...p){let m=this;if(e.context&&(m=ne.get(typeof e.context=="function"?e.context.call(this,...p):e.context)),m.state===t)return e.sync?m[ed]:Promise.resolve(m[ed]);m.state instanceof na&&m.state.action==e.abortAction&&m.state.abort(m);let E=null;Array.isArray(i)?i.length==0?m.state instanceof na&&m.state.abort(m):(typeof m.state!="string"||!i.includes(m.state))&&(E=new aa(m._state,`${m.name} ${n} to ${t} failed: current state ${m._state} not from ${i.join("|")}`)):i!==m.state&&(E=new aa(m._state,`${m.name} ${n} to ${t} failed: current state ${m._state} not from ${i}`));let _=P=>{if(e.fail&&e.fail.call(this,P),e.sync){if(e.ignoreError)return P;throw P}else return e.ignoreError?Promise.resolve(P):Promise.reject(P)};if(E)return _(E);let b=m.state,C=new na(b,t,n);da.call(m,C);let k=P=>{var J;return m[ed]=P,C.aborted||(da.call(m,t),(J=e.success)===null||J===void 0||J.call(this,m[ed])),P},x=P=>(da.call(m,b,P),_(P));try{let P=d.apply(this,p);return b_(P)?P.then(k).catch(x):e.sync?k(P):Promise.resolve(k(P))}catch(P){return x(new aa(m._state,`${m.name} ${n} from ${i} to ${t} failed: ${P}`,P instanceof Error?P:new Error(String(P))))}}}}var R_=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 da(i,t){let e=this._state;this._state=i;let r=i.toString();i&&this.emit(r,e),this.emit(ne.STATECHANGED,i,e,t),this.updateDevTools({value:i,old:e,err:t instanceof Error?t.message:String(t)})}var ne=class i extends Vh.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[Uh];o?this.name=o.name+"-"+o.count++:r[Uh]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let t=Object.getPrototypeOf(this),e=ca.get(t)||[],r=new Set,o=[],s=[],n=new Set,d=Object.getPrototypeOf(t);ca.has(d)&&(d.stateDiagram.forEach(m=>r.add(m)),d.allStates.forEach(m=>n.add(m))),e.forEach(({from:m,to:E,action:_})=>{typeof m=="string"?o.push({from:m,to:E,action:_}):m.length?m.forEach(b=>{o.push({from:b,to:E,action:_})}):s.push({to:E,action:_})}),o.forEach(({from:m,to:E,action:_})=>{n.add(m),n.add(E),n.add(_+"ing"),r.add(`${m} --> ${_}ing : ${_}`),r.add(`${_}ing --> ${E} : ${_} \u{1F7E2}`),r.add(`${_}ing --> ${m} : ${_} \u{1F534}`)}),s.forEach(({to:m,action:E})=>{r.add(`${E}ing --> ${m} : ${E} \u{1F7E2}`),n.forEach(_=>{_!==m&&r.add(`${_} --> ${E}ing : ${E}`)})});let p=[...r];return Object.defineProperties(t,{stateDiagram:{value:p},allStates:{value:n}}),p}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={}){R_(i.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},t))}get state(){return this._state}set state(t){da.call(this,t)}};ne.STATECHANGED="stateChanged";ne.UPDATEAFSM="updateAFSM";ne.INIT="[*]";ne.ON="on";ne.OFF="off";ne.instances=new Map;ne.instances2=new WeakMap;var Pl=typeof window!="undefined",Bh=Pl&&window.requestIdleCallback||function(i){let t=Date.now();return setTimeout(()=>{i({didTimeout:!1,timeRemaining(){return Math.max(0,50-(Date.now()-t))}})},1e3)},v_=Pl&&window.cancelIdleCallback||function(i){clearTimeout(i)},$h=Pl&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),ht=class ht{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=Z({delay:2e3,count:0,backgroundTask:!0},r):t==="ric"?r=Z({delay:1e4,count:0},r):t==="raf"?r=Z({fps:60,delay:16.6,count:0,backgroundTask:!0},r):r=Z({delay:2e3,count:0,backgroundTask:!0},r);let o=Ee(Z({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,ht.isBreakLoop(t)};return t.intervalID=setInterval(e,t.delay)}static intervalInWorker(t){ht.sharedWorker||(ht.sharedWorker=new Worker(URL.createObjectURL(new Blob([`
|
|
9
|
+
`,g+=s)),o&&(g+=`
|
|
10
|
+
Refer to: ${fh("en",d)}
|
|
11
|
+
`),g}var Cl=Mi(Ah(),1);var u_=1,l_=0,Jc=class{constructor(t=!0){u(this,"countMap",new Map);u(this,"distributionMap",new Map);u(this,"version");u(this,"log",$.createLogger({id:"kv"}));t&&(H.on("102",({track:e,cost:r})=>{this.addSuccessEvent({key:e.kind===D.AUDIO?501700:511700,cost:r})}),H.on("103",({track:e,error:r})=>{this.addFailedEvent({key:e.kind===D.AUDIO?501700:511700,error:r})}))}getReportData(){let t={msg_sdk_basic_info:{uint32_sdk_version:Tc(this.version||rt),uint32_terminal_type:15,bytes_device_name:"",bytes_os_version:"",uint32_framework:30,uint32_network_type:0},stats_count:[...this.countMap.entries()].map(([e,r])=>({uint32_key:e,uint32_count:r})),stats_distribution:[...this.distributionMap.entries()].map(([e,r])=>({uint32_key:e,distribution_items:[...r.entries()].map(([o,s])=>({uint32_item_key:o,uint32_item_value:s}))}))};return this.countMap.clear(),this.distributionMap.clear(),t}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}){var d;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;this.countMap.set(t,(this.countMap.get(t)||0)+1);let s=((d=this.distributionMap)==null?void 0:d.get(t))||new Map,n=0;if(je(r))n=Math.floor(e/r);else for(let p=r.length-1;p>0;p--)if(e>r[p]){n=p;break}s.set(n,(s.get(n)||0)+1),this.distributionMap.set(t,s)}addSuccessEvent({key:t,cost:e,timeKey:r,split:o}){if(t&&(this.addEnum({key:t,value:u_,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&&(je(e)?r=e:(!V(e.extraCode)||!V(e.code))&&(r=e.extraCode||e.code)),this.addEnum({key:t,value:l_,useUV:!1}),this.addEnum({key:t,value:Math.abs(r),useUV:!1})}},zc=(me=>(me[me.enterRoom=500700]="enterRoom",me[me.exitRoom=500701]="exitRoom",me[me.switchRole=500702]="switchRole",me[me.destroy=500703]="destroy",me[me.startLocalAudio=500704]="startLocalAudio",me[me.updateLocalAudio=500705]="updateLocalAudio",me[me.stopLocalAudio=500706]="stopLocalAudio",me[me.startLocalVideo=500707]="startLocalVideo",me[me.updateLocalVideo=500708]="updateLocalVideo",me[me.stopLocalVideo=500709]="stopLocalVideo",me[me.startScreenShare=500710]="startScreenShare",me[me.updateScreenShare=500711]="updateScreenShare",me[me.stopScreenShare=500712]="stopScreenShare",me[me.startRemoteVideo=500713]="startRemoteVideo",me[me.updateRemoteVideo=500714]="updateRemoteVideo",me[me.stopRemoteVideo=500715]="stopRemoteVideo",me[me.muteRemoteAudio=500716]="muteRemoteAudio",me[me.setRemoteAudioVolume=500717]="setRemoteAudioVolume",me[me.use=500718]="use",me[me.sendSEIMessage=5e5]="sendSEIMessage",me[me.sendCustomMessage=500001]="sendCustomMessage",me))(zc||{}),bl=(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))(bl||{}),Rl=(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))(Rl||{}),vl=(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))(vl||{});var m_=new Jc(!0),Mo=new Jc(!1);var Y=m_;var Pe={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},p_=new Map([[Qt,["Firefox",Sc]],[As,["Edg",Ac]],[Ds,["Chrome",Vc]],[Mt,["Safari",Vi]],[Er,["TBS",vc]],[bs,["XWEB",Cc]],[Rs&&Li,["WeChat",Dc]],[Ln,["QQ(Win)",Nc]],[Cs,["QQ(Mobile)",Is]],[vs,["QQ(Mobile X5)",Is]],[Un,["QQ(Mac)",wc]],[Vn,["QQ(iPad)",Mc]],[$n,["MI",Oc]],[Bn,["HW",xc]],[Hn,["Samsung",Pc]],[Wn,["OPPO",kc]],[Gn,["VIVO",Lc]],[ys,["EDGE",yc]],[Pn,["SogouMobile",bc]],[kn,["Sogou",Rc]]]);function Qc(){let i=p_.get(!0),t=i?i[0]:"unknown",e=i?i[1]:"unknown";return{browserName:t,browserVersion:e}}var Nl=function(){return!(Yu||ys||As&&Xu<80||Qt&&zu<56)},Rh=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder","MediaStreamTrackGenerator"].every(t=>t in window)},Yc=function(){if(!navigator.mediaDevices)return ai()||$.error(qt.NOT_SUPPORTED_MEDIA),!1;let i=["getUserMedia","enumerateDevices"];return i.filter(t=>t in navigator.mediaDevices).length===i.length},bh=!1;function ai(){return location.protocol==="http:"&&!Tr?(bh||$.error(dt({key:ct.NOT_SUPPORTED_HTTP})),bh=!0,!0):!1}var wl=function(){return(window==null?void 0:window.OffscreenCanvas)&&(window==null?void 0:window.MediaStreamTrackProcessor)&&(window==null?void 0:window.MediaStreamTrackGenerator)},Dl=function(){return y(this,null,function*(){if(Pe.detail.isH264EncodeSupported&&Pe.detail.isVp8EncodeSupported)return{isH264EncodeSupported:Pe.detail.isH264EncodeSupported,isVp8EncodeSupported:Pe.detail.isVp8EncodeSupported};let i,t=!1,e=!1;try{let r=new RTCPeerConnection,o=document.createElement(D.CANVAS);o.getContext("2d");let s=o.captureStream(0);return r.addTrack(s.getVideoTracks()[0],s),i=yield r.createOffer(),i.sdp.toLowerCase().indexOf("h264")!==-1&&(t=!0),i.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0),r.close(),Pe.detail.isH264EncodeSupported=t,Pe.detail.isVp8EncodeSupported=e,{isH264EncodeSupported:Pe.detail.isH264EncodeSupported,isVp8EncodeSupported:Pe.detail.isVp8EncodeSupported}}catch(r){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1}}})},vh=function(){return y(this,null,function*(){if(Pe.detail.isH264DecodeSupported&&Pe.detail.isVp8DecodeSupported)return{isH264DecodeSupported:Pe.detail.isH264DecodeSupported,isVp8DecodeSupported:Pe.detail.isVp8DecodeSupported};let i,t=!1,e=!1;try{let r=new RTCPeerConnection;return i=yield r.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0}),i.sdp.toLowerCase().indexOf("h264")!==-1&&(t=!0),i.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0),r.close(),{isH264DecodeSupported:t,isVp8DecodeSupported:e}}catch(r){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1}}})},Zc=Ic(()=>y(void 0,null,function*(){if(Pe.result&&Pe.detail.isH264EncodeSupported&&Pe.detail.isVp8EncodeSupported&&Pe.detail.isH264DecodeSupported&&Pe.detail.isVp8DecodeSupported)return Pe;let i=Date.now(),t=Nl(),e=Ol(),r=Rh(),o=Yc(),{isH264EncodeSupported:s,isVp8EncodeSupported:n}=yield Dl(),{isH264DecodeSupported:d,isVp8DecodeSupported:p}=yield vh();if(!s||!n){let m=yield Dl();$.warn(`detect encode again h264:${s} vp8:${n} result: ${JSON.stringify(m)}`),s=m.isH264EncodeSupported,n=m.isVp8EncodeSupported}if(s&&d&&at&&Kr&&!bs&&!Er){let{encode:m,decode:g}=yield f_();s=m,d=g}return Pe.result=t&&e&&o&&(s||n)&&(d||p),Pe.detail.isBrowserSupported=t,Pe.detail.isWebRTCSupported=e,Pe.detail.isWebCodecsSupported=r,Pe.detail.isMediaDevicesSupported=o,Pe.detail.isScreenShareSupported=ta(),Pe.detail.isSmallStreamSupported=ra(),Pe.detail.isH264EncodeSupported=s,Pe.detail.isVp8EncodeSupported=n,Pe.detail.isH264DecodeSupported=d,Pe.detail.isVp8DecodeSupported=p,Pe.result||$.error(`${navigator.userAgent} ${Ec(Pe.detail,!1)}`),D_(),Y.addNumber({key:523800,value:Date.now()-i}),Pe})),h_=function(){return Pe.result},ta=function(){return!!(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)},Xc=null;function f_(){return y(this,null,function*(){return Xc||(Xc=new Promise(i=>y(this,null,function*(){let t={encode:!1,decode:!1},e=()=>{};try{let r=document.createElement("canvas"),o=r.getContext("2d");r.width=320,r.height=240;let s=setInterval(()=>{o.fillText("test",Math.floor(Math.random()*320),Math.floor(Math.random()*240))},66),n=-1,d=-1;e=()=>{clearInterval(n),clearInterval(s),clearTimeout(d),m.close(),g.close(),p.getTracks().forEach(P=>P.stop())},d=setTimeout(()=>{e(),i(t)},2*1e3);let p=r.captureStream(),m=new RTCPeerConnection({}),g=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});m.addEventListener("icecandidate",P=>g.addIceCandidate(P.candidate)),g.addEventListener("icecandidate",P=>m.addIceCandidate(P.candidate)),m.addTrack(p.getVideoTracks()[0],p);let _=yield m.createOffer();yield m.setLocalDescription(_),yield g.setRemoteDescription(_);let b=yield g.createAnswer(),N=Cl.default.parse(b.sdp),k=N.media[0].rtp.findIndex(P=>P.codec==="H264");N.media[0].rtp=[N.media[0].rtp[k]],N.media[0].fmtp=N.media[0].fmtp.filter(P=>P.payload===N.media[0].rtp[0].payload),N.media[0].rtcpFb&&(N.media[0].rtcpFb=N.media[0].rtcpFb.filter(P=>P.payload===N.media[0].rtp[0].payload)),b.sdp=Cl.default.write(N),yield g.setLocalDescription(b),yield m.setRemoteDescription(b),n=setInterval(()=>y(this,null,function*(){t.encode&&t.decode&&(e(),i(t));let[P,x]=yield Promise.all([m.getSenders()[0].getStats(),g.getReceivers()[0].getStats()]);t.encode||P.forEach(J=>{J.type==="outbound-rtp"&&J.mediaType===D.VIDEO&&J.bytesSent>0&&(t.encode=!0)}),t.decode||x.forEach(J=>{J.type==="inbound-rtp"&&J.mediaType===D.VIDEO&&J.bytesReceived>0&&(t.decode=!0)})}),100)}catch(r){e(),$.warn("detectH264Supported failed",r),i({encode:!0,decode:!0})}})).then(i=>(i.encode||(i.decode=!0),(!i.encode||!i.decode)&&$.warn(`detectH264Supported encode: ${i.encode} decode: ${i.decode} ${gr}`),i)),Xc)})}var g_=(i,t,e)=>{location.protocol==="http:"&&!Tr&&(i[t]=()=>{throw new he({code:te.INVALID_OPERATION,message:qt.NOT_SUPPORTED_HTTP})})},E_=function(i){return i.type==="candidate-pair"&&i.nominated&&(i.state==="in-progress"||i.state==="succeeded")?!(nt(i.selected)&&!i.selected):!1};function Ch(){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 Dh(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function Nh(){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 wh(){return"captureStream"in HTMLCanvasElement.prototype}function ra(){return Rs||lt||ei&&ei<63?!1:!!(Nl()&&wh())}var __=function(){if(V(window.RTCRtpTransceiver)||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let i=null,t=!1;try{i=new RTCPeerConnection({sdpSemantics:Vu}),i.addTransceiver(D.AUDIO),t=!0}catch(e){}return i==null||i.close(),t};function T_(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function Mh(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function I_(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function Oh(){return Yt===11?!1:"RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype}var S_=!(!Oh()||Kr&&ei<86);function y_(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}var ia="RTCRtpSender"in window;function A_(){return ia&&"replaceTrack"in window.RTCRtpSender.prototype}function b_(){return ia&&"setParameters"in window.RTCRtpSender.prototype&&Mh()}var R_="RTCRtpReceiver"in window&&"getSynchronizationSources"in window.RTCRtpReceiver.prototype,ks=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,Ml=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,oa=ia&&"createEncodedStreams"in window.RTCRtpSender.prototype&&Uc()>=86,xh="RTCRtpScriptTransform"in window,sa=ia&&(oa||xh),Ol=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(t=>t in window).length>0};function Ph(){let i={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return V(window.AudioDecoder)||(i.AudioDecoder=!0),V(window.AudioEncoder)||(i.AudioEncoder=!0),V(window.VideoDecoder)||(i.VideoDecoder=!0),V(window.VideoEncoder)||(i.VideoEncoder=!0),V(window.ImageDecoder)||(i.ImageDecoder=!0),i}function kh(){return"mediaSession"in navigator&&!V(navigator.mediaSession.setActionHandler)}function Lh(){return!V(window.WebTransport)}function v_(){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 C_(){let i={browser:`${Ur.name}/${Ur.version}`,os:Ns(),displayResolution:Ch(),isScreenShareSupported:ta(),isWebRTCSupported:Ol(),isGetUserMediaSupported:Dh(),isWebAudioSupported:Nh(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:Ph(),isMediaSessionSupported:kh(),isWebTransportSupported:Lh()};return navigator.userAgent.includes("miniProgram")&&(i.browser=`mini/${i.browser}`),i}var Uh="checkResult";function D_(){Ms.setItem(Uh,{ua:navigator.userAgent,checkResult:Pe})}function xl(){ai();let i=Ms.getItem(Uh);i&&i.ua===navigator.userAgent&&(Pe=i.checkResult),Zc()}function Oo(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var N_="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype;var Fh=Mi($i(),1);var Vh=Symbol("instance"),rA=Symbol("abortCtrl"),Kc=Symbol("cacheResult"),na=class{constructor(t,e,r){this.oldState=t,this.newState=e,this.action=r,this.aborted=!1}abort(t){this.aborted=!0,da.call(t,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},aa=class extends Error{constructor(t,e,r){super(e),this.state=t,this.message=e,this.cause=r}};function w_(i){return typeof i=="object"&&i&&"then"in i}var ca=new Map;function qe(i,t,e={}){return(r,o,s)=>{let n=e.action||o;if(!e.context){let p=ca.get(r)||[];ca.has(r)||ca.set(r,p),p.push({from:i,to:t,action:n})}let d=s.value;s.value=function(...p){let m=this;if(e.context&&(m=ne.get(typeof e.context=="function"?e.context.call(this,...p):e.context)),m.state===t)return e.sync?m[Kc]:Promise.resolve(m[Kc]);m.state instanceof na&&m.state.action==e.abortAction&&m.state.abort(m);let g=null;Array.isArray(i)?i.length==0?m.state instanceof na&&m.state.abort(m):(typeof m.state!="string"||!i.includes(m.state))&&(g=new aa(m._state,`${m.name} ${n} to ${t} failed: current state ${m._state} not from ${i.join("|")}`)):i!==m.state&&(g=new aa(m._state,`${m.name} ${n} to ${t} failed: current state ${m._state} not from ${i}`));let _=x=>{if(e.fail&&e.fail.call(this,x),e.sync){if(e.ignoreError)return x;throw x}else return e.ignoreError?Promise.resolve(x):Promise.reject(x)};if(g)return _(g);let b=m.state,N=new na(b,t,n);da.call(m,N);let k=x=>{var J;return m[Kc]=x,N.aborted||(da.call(m,t),(J=e.success)===null||J===void 0||J.call(this,m[Kc])),x},P=x=>(da.call(m,b,x),_(x));try{let x=d.apply(this,p);return w_(x)?x.then(k).catch(P):e.sync?k(x):Promise.resolve(k(x))}catch(x){return P(new aa(m._state,`${m.name} ${n} from ${i} to ${t} failed: ${x}`,x instanceof Error?x:new Error(String(x))))}}}}var M_=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 da(i,t){let e=this._state;this._state=i;let r=i.toString();i&&this.emit(r,e),this.emit(ne.STATECHANGED,i,e,t),this.updateDevTools({value:i,old:e,err:t instanceof Error?t.message:String(t)})}var ne=class i extends Fh.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[Vh];o?this.name=o.name+"-"+o.count++:r[Vh]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let t=Object.getPrototypeOf(this),e=ca.get(t)||[],r=new Set,o=[],s=[],n=new Set,d=Object.getPrototypeOf(t);ca.has(d)&&(d.stateDiagram.forEach(m=>r.add(m)),d.allStates.forEach(m=>n.add(m))),e.forEach(({from:m,to:g,action:_})=>{typeof m=="string"?o.push({from:m,to:g,action:_}):m.length?m.forEach(b=>{o.push({from:b,to:g,action:_})}):s.push({to:g,action:_})}),o.forEach(({from:m,to:g,action:_})=>{n.add(m),n.add(g),n.add(_+"ing"),r.add(`${m} --> ${_}ing : ${_}`),r.add(`${_}ing --> ${g} : ${_} \u{1F7E2}`),r.add(`${_}ing --> ${m} : ${_} \u{1F534}`)}),s.forEach(({to:m,action:g})=>{r.add(`${g}ing --> ${m} : ${g} \u{1F7E2}`),n.forEach(_=>{_!==m&&r.add(`${_} --> ${g}ing : ${g}`)})});let p=[...r];return Object.defineProperties(t,{stateDiagram:{value:p},allStates:{value:n}}),p}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={}){M_(i.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},t))}get state(){return this._state}set state(t){da.call(this,t)}};ne.STATECHANGED="stateChanged";ne.UPDATEAFSM="updateAFSM";ne.INIT="[*]";ne.ON="on";ne.OFF="off";ne.instances=new Map;ne.instances2=new WeakMap;var kl=typeof window!="undefined",$h=kl&&window.requestIdleCallback||function(i){let t=Date.now();return setTimeout(()=>{i({didTimeout:!1,timeRemaining(){return Math.max(0,50-(Date.now()-t))}})},1e3)},O_=kl&&window.cancelIdleCallback||function(i){clearTimeout(i)},Bh=kl&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),gt=class gt{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=ee({delay:2e3,count:0,backgroundTask:!0},r):t==="ric"?r=ee({delay:1e4,count:0},r):t==="raf"?r=ee({fps:60,delay:16.6,count:0,backgroundTask:!0},r):r=ee({delay:2e3,count:0,backgroundTask:!0},r);let o=Ee(ee({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,gt.isBreakLoop(t)};return t.intervalID=setInterval(e,t.delay)}static intervalInWorker(t){gt.sharedWorker||(gt.sharedWorker=new Worker(URL.createObjectURL(new Blob([`
|
|
12
12
|
const timers = new Map();
|
|
13
13
|
self.onmessage = function(e) {
|
|
14
14
|
const { taskId, delay, type } = e.data;
|
|
@@ -21,14 +21,14 @@ Refer to: ${hh("en",d)}
|
|
|
21
21
|
timers.delete(taskId);
|
|
22
22
|
}
|
|
23
23
|
};
|
|
24
|
-
`],{type:"application/javascript"}))),
|
|
25
|
-
${r.stack}`)),this.sendRequest(Qr(this._configs.sdkAppId,wi.LOG),o)}sendRequest(t,e){setTimeout(()=>Yr({url:t,body:JSON.stringify(e),priority:"low"}).catch(()=>{}),2e3)}},$e=new xl;var wo=new WeakMap;function Bi({settings:i={retries:5,timeout:2e3},onError:t,onRetrying:e,onRetryFailed:r}){return function(o,s,n){let d=Pi({retryFunction:n.value,settings:i,onError({error:p,retry:m,reject:E,retryFuncArgs:_}){var b;t?t.call(this,p,()=>{var C;(C=wo.get(o))!=null&&C.has(s)?m():E(p)},E,_):(b=wo.get(o))!=null&&b.has(s)?m():E(p)},onRetrying(p,m){var E;Oi(e)&&e.call(this,p,m),(E=wo.get(o))!=null&&E.has(s)&&(wo.get(o).get(s).stopRetry=m)},onRetryFailed:r});return n.value=function(...p){let m=wo.get(o);return m?m.set(s,{args:p}):wo.set(o,new Map([[s,{args:p}]])),d.apply(this,p).finally(()=>{var E;return(E=wo.get(o))==null?void 0:E.delete(s)})},n}}var $r=class extends ne{constructor(e,r){super(e.id,`${r}-player`);this.kind=r;u(this,"id");u(this,"element",null);u(this,"track");u(this,"url");u(this,"attr");u(this,"mode");u(this,"muted");u(this,"_log");u(this,"_pausedRetryCount");u(this,"_isElementPlayingFired",!1);u(this,"_interval");u(this,"_delayDestroyTimeoutId",0);u(this,"_playSuccessResolve");u(this,"_isReplayByRecreateMediaStreamCalled",!1);u(this,"isInAutoPlayFailedState",!1);this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=Vu,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||this.track&&this.track.readyState==="live"&&!this.track.muted)}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 y(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=at({key:nt.PLAY_FAILED,data:{media:this.kind,error:e}});if(this.track&&!this.track.muted&&this._log.warn(e),r.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new he({code:te.PLAY_NOT_ALLOWED,message:r})}})}stop(e=0){this._isElementPlayingFired=!1,this.unbindEvents(),e>0&&!xi?this._delayDestroyTimeoutId||(this._log.info(`destroy element after 3 * ${e}`),this._delayDestroyTimeoutId=setTimeout(()=>this.destroyElement(),3*e)):this.destroyElement(),this.handleStopped(D.ENDED),this._interval>0&&St.clearTask(this._interval)}destroyElement(){this.element&&(this._log.debug("destroy element"),this.element.remove(),this.element.srcObject=null,this.element=null),clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0}pause(){var e;this.isPlaying&&((e=this.element)==null||e.pause())}resume(){return this._log.info("resume"),this.isPlaying?Promise.resolve():tl?this.replay():this.play().catch(()=>{})}setMuted(e){this.element&&(this.element.muted=e),this.muted=e}replay(){return this.stop(),this.play().catch(()=>{})}bindElementEvents(){if(this.element){let e=this.handleElementEvent.bind(this);return Pt(this.element,this.element).add(D.PLAYING,e).add(D.ENDED,e).add(D.PAUSE,e).add(D.ERROR,e).add(D.LOADEDDATA,e).add(D.LOADEDMETADATA,e)}}bindTrackEvents(e=this.track){if(e){let r=this.handleTrackEvent.bind(this);Br==null||Br.create(e,e).add(D.ENDED,r).add(D.MUTE,r).add(D.UNMUTE,r),e.readyState===D.ENDED&&this.handleTrackEvent({type:D.ENDED}),e.muted&&this.handleTrackEvent({type:D.MUTE})}}bindAutoPlayEvent(){H.on(L.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(e=this.track){e&&ut(e)}unbindEvents(){this.element&&ut(this.element),this.unbindTrackEvents(),H.off(L.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case D.PLAYING:this.isInAutoPlayFailedState=!1,this._isElementPlayingFired=!0,this._log.info(`${this.kind} player is playing`),this.handlePlaying(D.PLAYING),this._interval&&(St.clearTask(this._interval),this._interval=-1);break;case D.ENDED:this._log.info(`${this.kind} player is ended`),this.handleStopped(D.ENDED);break;case D.PAUSE:this._log.info(`${this.kind} player is paused`),this.handlePaused(D.PAUSE),It&&(this._interval=St.run("timeout",()=>{this.element&&this._state==="PAUSED"&&this.resume()},{delay:3e3}));break;case D.ERROR:if(this.element&&this.element.error){this.handlePaused(D.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}`),$e.uploadEvent({log:`stat-${this.kind}-${zr.PLAYER_ERROR}-${o}-${navigator.userAgent}`,error:this.element.error}),Zu||Yu?this.emit(Xe.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case D.LOADEDDATA:this.kind===D.VIDEO&&this.emit(Xe.LOADED_DATA);break;case D.LOADEDMETADATA:this.kind===D.VIDEO&&this.emit(Xe.LOADED_META_DATA);break}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then(()=>{this._log.warn("replayByRecreateMediaStream success"),$e.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),Y.addSuccessEvent({key:this.kind===D.AUDIO?506700:516700})}).catch(()=>{var r;this._log.error("replayByRecreateMediaStream failed"),$e.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),Y.addFailedEvent({key:this.kind===D.AUDIO?506700:516700,error:(r=this.element)==null?void 0:r.error}),this.emit(Xe.ERROR,e)})}doReplayByRecreateMediaStream(e){return this._log.warn(`delay ${e}ms to recreate mediaStream`),new Promise((r,o)=>{Pn(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,d;this._log.warn(`element onerror ${(n=(s=this.element)==null?void 0:s.error)==null?void 0:n.code} fired after recreated mediaStream`),o((d=this.element)==null?void 0:d.error)}),Pn(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){switch(e.type){case D.ENDED:this.handleStopped(D.ENDED);break;case D.MUTE:this.handlePaused(D.MUTE);break;case D.UNMUTE:this._isElementPlayingFired?this.handlePlaying(D.UNMUTE):this.mode>0&&this.handlePlaying(this.mode.toString());break}}handlePlaying(e){var r;(r=this._playSuccessResolve)==null||r.call(this,e),this.emit(Xe.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this.emit(Xe.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this.emit(Xe.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};X([Bi({settings:{retries:2,timeout:0},onError(e,r,o,s){s[0]=(s[0]||1e3)+1e3,r()}})],$r.prototype,"doReplayByRecreateMediaStream",1),X([qe([],"PLAYING",{sync:!0})],$r.prototype,"handlePlaying",1),X([qe("PLAYING","PAUSED",{ignoreError:!0,sync:!0})],$r.prototype,"handlePaused",1),X([qe([],"STOPPED",{sync:!0})],$r.prototype,"handleStopped",1);var ni="trtc_autoplay",kl=`${ni}_mask`,ks=`${ni}_wrapper`,Fh=`${ni}_header`,Ll=`${ni}_content`,td=`${ni}_action_wrapper`,Ul=`${ni}_question`,Vl=`${ni}_collapse`,rd=`${ni}_action_confirm`,Hh=`${ni}_detail`,Wh="#2473E8",$l="dialog",N_=`${$l}-show`,D_=`${$l}-1`,w_=`${$l}-2`,Gh=!1,Fl=()=>!!document.querySelector(`.${ks}`),qh=`${Mr}/${hr()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,jh=`<br><a href='${qh}' target='_blank'>${hr()?"\u5176\u4ED6\u65B9\u6848\uFF1F":"Any other solution?"}</a>`,M_=`${hr()?`\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${jh}`:`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. ${jh}`}`,Bl=class{constructor(){u(this,"content","\u97F3\u89C6\u9891\u64AD\u653E\u88AB\u6D4F\u89C8\u5668\u62E6\u622A\uFF0C\u8BF7\u70B9\u51FB\u201C\u6062\u590D\u64AD\u653E\u201D\u3002");u(this,"_dialogNode",null);u(this,"_bodyPosition","");u(this,"_showDetail",!1);u(this,"_isCollapseClicked",!1);u(this,"_isQuestionClicked",!1);if(hr()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!Gh){let t=document.createElement("style");t.innerHTML=`.${kl}{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;}.${kl} div:not(.${td}){display:block !important;}.${ks}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${ks} a{color:${Wh};}.${Fh}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${Ll}{margin:8px 0;}.${td}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${Vl}{margin-right:auto;cursor:pointer}.${Ul}{height:100%;line-height:16px;cursor:pointer;}.${rd}{margin-left:8px;color:#fff;background:${Wh};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${rd}:hover{opacity:0.9;}.${Vl},.${rd},.${Ll},.${Ul}{font-size:14px;}@media screen and (max-width:750px){.${ks}{width:80vw;}}`,document.head.appendChild(t),Gh=!0}this.addDiaLog()}createDiaLog(){let t=document.createElement("template");t.innerHTML=`<div class="${kl}"><div class='${ks}'><div class='${Fh}'>${location.host}</div><div class='${Ll}'>${this.content}</div><div class='${Hh}' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">${M_}</div><div class='${td}'></div></div></div>`.trim();let e=document.createElement("button");e.className=rd,e.innerText=hr()?"\u6062\u590D\u64AD\u653E":"Resume",e.onclick=this.onConfirm.bind(this);let r=document.createElement("div");r.className=Ul,r.innerHTML=`<?xml version="1.0" encoding="UTF-8"?>
|
|
24
|
+
`],{type:"application/javascript"}))),gt.sharedWorker.onmessage=e=>{var r;if(e.data.type==="tick"){let o=gt.workerTasks.get(e.data.taskId);o&&(o.callback(),o.loopCount+=1,gt.isBreakLoop(o)&&((r=gt.sharedWorker)==null||r.postMessage({type:"stop",taskId:o.taskID}),gt.workerTasks.delete(o.taskID)))}}),gt.workerTasks.set(t.taskID,t),gt.sharedWorker.postMessage({taskId:t.taskID,delay:t.delay,type:"start"})}static timeout(t){let e=()=>{if(t.callback(),t.loopCount+=1,!gt.isBreakLoop(t))return t.timeoutID=setTimeout(e,t.delay)};return t.timeoutID=setTimeout(e,t.delay)}static ric(t){let e=_e(),r,o=()=>{if(r=_e()-e,r>=t.delay&&(e=_e()-Math.floor(r%t.delay),t.callback(),t.loopCount+=1),!gt.isBreakLoop(t))return t.ricID=$h(o,{timeout:t.delay})};return t.ricID=$h(o,{timeout:t.delay})}static raf(t){let e=_e(),r,o=()=>{if(document.hidden&&t.backgroundTask)return r=_e()-e,e=_e(),t.callback(),t.loopCount+=1,gt.isBreakLoop(t)?void 0:t.timeoutID=setTimeout(o,t.delay-Math.floor(r%t.delay));if(r=_e()-e,r>=t.delay&&(e=_e()-Math.floor(r%t.delay),t.callback(),t.loopCount+=1),!gt.isBreakLoop(t))return t.rafID=requestAnimationFrame(o)};if(t.rafID=requestAnimationFrame(o),t.backgroundTask){let s=()=>{if(document.hidden){let n=_e()-e;n>=t.delay?o():t.timeoutID=setTimeout(o,t.delay-n)}};document.addEventListener("visibilitychange",s),t.onVisibilitychange=s,document.hidden&&s()}return t.taskID}static hasTask(t){return this.taskMap.has(t)}static clearTask(t){if(!this.taskMap.has(t))return!0;let{intervalID:e,timeoutID:r,rafID:o,ricID:s,onVisibilitychange:n,worker:d}=this.taskMap.get(t);return d&&d.terminate(),e&&clearInterval(e),r&&clearTimeout(r),o&&Bh&&Bh(o),s&&O_(s),n&&document.removeEventListener("visibilitychange",n),this.taskMap.delete(t),!0}static isBreakLoop(t){return this.taskMap.has(t.taskID)?t.count!==0&&t.loopCount>=t.count?(this.clearTask(t.taskID),!0):!1:!0}};u(gt,"taskMap",new Map),u(gt,"currentTaskID",1),u(gt,"sharedWorker",null),u(gt,"workerTasks",new Map);var Pl=gt,At=Pl;var mA={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:D.SEI_MESSAGE,ERROR:"error"};var Qe={LOADED_DATA:D.LOADEDDATA,LOADED_META_DATA:D.LOADEDMETADATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error"};var Fr={};Jr(Fr,{create:()=>xt,remove:()=>mt});var ua=new WeakMap;function xt(i,t){ua.has(i)||ua.set(i,[]);let e=ua.get(i),o={add:(s,n)=>("addEventListener"in t?(e.push(t.removeEventListener.bind(t,s,n)),t.addEventListener(s,n)):(e.push(t.off.bind(t,s,n)),t.on(s,n)),o)};return o}function mt(i){let t=ua.get(i);t&&(t.forEach(e=>e()),ua.delete(i))}var Ll=class{constructor(){u(this,"_roomIdMap",new Map);u(this,"_configs");typeof registerProcessor=="undefined"&&(this._configs={sdkAppId:"",userId:"",version:rt,env:zr.QCLOUD,browserVersion:Ur.name+Ur.version,ua:navigator.userAgent})}setConfig({sdkAppId:t,env:e,userId:r,roomId:o}){t!==this._configs.sdkAppId&&(this._configs.sdkAppId=String(t)),this._configs.env=e,this._configs.userId=r,this._roomIdMap.set(r,String(o))}logSuccessEvent(t){Tr||!$.isAbleToUpload||this._configs.env===zr.QCLOUD&&this.uploadEventToKibana(Ee(ee({},t),{result:"success"}))}logFailedEvent(t){if(Tr||!$.isAbleToUpload)return;let{eventType:e,code:r,error:o,userId:s}=t,n={roomId:this._roomIdMap.get(s||this._configs.userId),userId:s,eventType:e,result:"failed",code:r||(o==null?void 0:o.extraCode)||(o==null?void 0:o.code)||te.UNKNOWN};this._configs.env===zr.QCLOUD&&this.uploadEventToKibana(Ee(ee({},n),{error:o}))}uploadEventToKibana(t){let e=`stat-${t.eventType}-${t.result}`;(t.eventType==="delta-join"||t.eventType==="delta-leave"||t.eventType==="delta-publish")&&(e=`${t.eventType}:${t.delta}`),this.uploadEvent({log:e,userId:t.userId}),t.result==="failed"&&(e=`stat-${t.eventType}-${t.result}-${t.code}`,this.uploadEvent({log:e,userId:t.userId,error:t.error}))}uploadEvent({log:t,userId:e,error:r}){let o={timestamp:oc(),sdkAppId:this._configs.sdkAppId,userId:e||this._configs.userId,version:rt,log:t};r&&(o.errorInfo=r.message,r.stack&&(o.errorInfo+=`
|
|
25
|
+
${r.stack}`)),this.sendRequest(Yr(this._configs.sdkAppId,Oi.LOG),o)}sendRequest(t,e){setTimeout(()=>Zr({url:t,body:JSON.stringify(e),priority:"low"}).catch(()=>{}),2e3)}},Be=new Ll;var xo=new WeakMap;function Hi({settings:i={retries:5,timeout:2e3},onError:t,onRetrying:e,onRetryFailed:r}){return function(o,s,n){let d=ki({retryFunction:n.value,settings:i,onError({error:p,retry:m,reject:g,retryFuncArgs:_}){var b;t?t.call(this,p,()=>{var N;(N=xo.get(o))!=null&&N.has(s)?m():g(p)},g,_):(b=xo.get(o))!=null&&b.has(s)?m():g(p)},onRetrying(p,m){var g;Pi(e)&&e.call(this,p,m),(g=xo.get(o))!=null&&g.has(s)&&(xo.get(o).get(s).stopRetry=m)},onRetryFailed:r});return n.value=function(...p){let m=xo.get(o);return m?m.set(s,{args:p}):xo.set(o,new Map([[s,{args:p}]])),d.apply(this,p).finally(()=>{var g;return(g=xo.get(o))==null?void 0:g.delete(s)})},n}}var $r=class extends ne{constructor(e,r){super(e.id,`${r}-player`);this.kind=r;u(this,"id");u(this,"element",null);u(this,"track");u(this,"url");u(this,"attr");u(this,"mode");u(this,"muted");u(this,"_log");u(this,"_pausedRetryCount");u(this,"_isElementPlayingFired",!1);u(this,"_interval");u(this,"_delayDestroyTimeoutId",0);u(this,"_playSuccessResolve");u(this,"_isReplayByRecreateMediaStreamCalled",!1);u(this,"isInAutoPlayFailedState",!1);this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=Fu,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||this.track&&this.track.readyState==="live"&&!this.track.muted)}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 y(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=dt({key:ct.PLAY_FAILED,data:{media:this.kind,error:e}});if(this.track&&!this.track.muted&&this._log.warn(e),r.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new he({code:te.PLAY_NOT_ALLOWED,message:r})}})}stop(e=0){this._isElementPlayingFired=!1,this.unbindEvents(),e>0&&!Ui?this._delayDestroyTimeoutId||(this._log.info(`destroy element after 3 * ${e}`),this._delayDestroyTimeoutId=setTimeout(()=>this.destroyElement(),3*e)):this.destroyElement(),this.handleStopped(D.ENDED),this._interval>0&&At.clearTask(this._interval)}destroyElement(){this.element&&(this._log.debug("destroy element"),this.element.remove(),this.element.srcObject=null,this.element=null),clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0}pause(){var e;this.isPlaying&&((e=this.element)==null||e.pause())}resume(){return this._log.info("resume"),this.isPlaying?Promise.resolve():rl?this.replay():this.play().catch(()=>{})}setMuted(e){this.element&&(this.element.muted=e),this.muted=e}replay(){return this.stop(),this.play().catch(()=>{})}bindElementEvents(){if(this.element){let e=this.handleElementEvent.bind(this);return xt(this.element,this.element).add(D.PLAYING,e).add(D.ENDED,e).add(D.PAUSE,e).add(D.ERROR,e).add(D.LOADEDDATA,e).add(D.LOADEDMETADATA,e)}}bindTrackEvents(e=this.track){if(e){let r=this.handleTrackEvent.bind(this);Fr==null||Fr.create(e,e).add(D.ENDED,r).add(D.MUTE,r).add(D.UNMUTE,r),e.readyState===D.ENDED&&this.handleTrackEvent({type:D.ENDED}),e.muted&&this.handleTrackEvent({type:D.MUTE})}}bindAutoPlayEvent(){H.on(L.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(e=this.track){e&&mt(e)}unbindEvents(){this.element&&mt(this.element),this.unbindTrackEvents(),H.off(L.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case D.PLAYING:this.isInAutoPlayFailedState=!1,this._isElementPlayingFired=!0,this._log.info(`${this.kind} player is playing`),this.handlePlaying(D.PLAYING),this._interval&&(At.clearTask(this._interval),this._interval=-1);break;case D.ENDED:this._log.info(`${this.kind} player is ended`),this.handleStopped(D.ENDED);break;case D.PAUSE:this._log.info(`${this.kind} player is paused`),this.handlePaused(D.PAUSE),lt&&(this._interval=At.run("timeout",()=>{this.element&&this._state==="PAUSED"&&this.resume()},{delay:3e3}));break;case D.ERROR:if(this.element&&this.element.error){this.handlePaused(D.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}`),Be.uploadEvent({log:`stat-${this.kind}-${Xr.PLAYER_ERROR}-${o}-${navigator.userAgent}`,error:this.element.error}),Ku||Zu?this.emit(Qe.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case D.LOADEDDATA:this.kind===D.VIDEO&&this.emit(Qe.LOADED_DATA);break;case D.LOADEDMETADATA:this.kind===D.VIDEO&&this.emit(Qe.LOADED_META_DATA);break}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then(()=>{this._log.warn("replayByRecreateMediaStream success"),Be.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),Y.addSuccessEvent({key:this.kind===D.AUDIO?506700:516700})}).catch(()=>{var r;this._log.error("replayByRecreateMediaStream failed"),Be.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),Y.addFailedEvent({key:this.kind===D.AUDIO?506700:516700,error:(r=this.element)==null?void 0:r.error}),this.emit(Qe.ERROR,e)})}doReplayByRecreateMediaStream(e){return this._log.warn(`delay ${e}ms to recreate mediaStream`),new Promise((r,o)=>{xn(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,d;this._log.warn(`element onerror ${(n=(s=this.element)==null?void 0:s.error)==null?void 0:n.code} fired after recreated mediaStream`),o((d=this.element)==null?void 0:d.error)}),xn(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){switch(e.type){case D.ENDED:this.handleStopped(D.ENDED);break;case D.MUTE:this.handlePaused(D.MUTE);break;case D.UNMUTE:this._isElementPlayingFired?this.handlePlaying(D.UNMUTE):this.mode>0&&this.handlePlaying(this.mode.toString());break}}handlePlaying(e){var r;(r=this._playSuccessResolve)==null||r.call(this,e),this.emit(Qe.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this.emit(Qe.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this.emit(Qe.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};X([Hi({settings:{retries:2,timeout:0},onError(e,r,o,s){s[0]=(s[0]||1e3)+1e3,r()}})],$r.prototype,"doReplayByRecreateMediaStream",1),X([qe([],"PLAYING",{sync:!0})],$r.prototype,"handlePlaying",1),X([qe("PLAYING","PAUSED",{ignoreError:!0,sync:!0})],$r.prototype,"handlePaused",1),X([qe([],"STOPPED",{sync:!0})],$r.prototype,"handleStopped",1);var ci="trtc_autoplay",Ul=`${ci}_mask`,Ls=`${ci}_wrapper`,Hh=`${ci}_header`,Vl=`${ci}_content`,ed=`${ci}_action_wrapper`,Fl=`${ci}_question`,$l=`${ci}_collapse`,td=`${ci}_action_confirm`,Wh=`${ci}_detail`,Gh="#2473E8",Hl="dialog",P_=`${Hl}-show`,k_=`${Hl}-1`,L_=`${Hl}-2`,jh=!1,Wl=()=>!!document.querySelector(`.${Ls}`),Jh=`${Mr}/${fr()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,qh=`<br><a href='${Jh}' target='_blank'>${fr()?"\u5176\u4ED6\u65B9\u6848\uFF1F":"Any other solution?"}</a>`,U_=`${fr()?`\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${qh}`:`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. ${qh}`}`,Bl=class{constructor(){u(this,"content","\u97F3\u89C6\u9891\u64AD\u653E\u88AB\u6D4F\u89C8\u5668\u62E6\u622A\uFF0C\u8BF7\u70B9\u51FB\u201C\u6062\u590D\u64AD\u653E\u201D\u3002");u(this,"_dialogNode",null);u(this,"_bodyPosition","");u(this,"_showDetail",!1);u(this,"_isCollapseClicked",!1);u(this,"_isQuestionClicked",!1);if(fr()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!jh){let t=document.createElement("style");t.innerHTML=`.${Ul}{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;}.${Ul} div:not(.${ed}){display:block !important;}.${Ls}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${Ls} a{color:${Gh};}.${Hh}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${Vl}{margin:8px 0;}.${ed}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${$l}{margin-right:auto;cursor:pointer}.${Fl}{height:100%;line-height:16px;cursor:pointer;}.${td}{margin-left:8px;color:#fff;background:${Gh};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${td}:hover{opacity:0.9;}.${$l},.${td},.${Vl},.${Fl}{font-size:14px;}@media screen and (max-width:750px){.${Ls}{width:80vw;}}`,document.head.appendChild(t),jh=!0}this.addDiaLog()}createDiaLog(){let t=document.createElement("template");t.innerHTML=`<div class="${Ul}"><div class='${Ls}'><div class='${Hh}'>${location.host}</div><div class='${Vl}'>${this.content}</div><div class='${Wh}' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">${U_}</div><div class='${ed}'></div></div></div>`.trim();let e=document.createElement("button");e.className=td,e.innerText=fr()?"\u6062\u590D\u64AD\u653E":"Resume",e.onclick=this.onConfirm.bind(this);let r=document.createElement("div");r.className=Fl,r.innerHTML=`<?xml version="1.0" encoding="UTF-8"?>
|
|
26
26
|
<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">
|
|
27
27
|
<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"/>
|
|
28
28
|
<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"/>
|
|
29
29
|
<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"/>
|
|
30
30
|
</svg>
|
|
31
|
-
`,r.onclick=this.onQuestionClick.bind(this);let o=document.createElement("div");o.className=Vl,o.innerText=`${hr()?"\u8BE6\u60C5 >":"Detail >"}`,o.onclick=this.onCollapseClick.bind(this);let s=t.content.firstChild,n=s.querySelector(`.${td}`);return n.appendChild(o),n.appendChild(r),n.appendChild(e),s}addDiaLog(){Fl()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${ks}`).onclick=t=>t.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",B.info("show autoplay dialog"),$e.uploadEvent({log:N_}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){B.warn("confirm clicked, try resume stream"),H.emit(L.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let t=this._dialogNode.querySelector(`.${Hh}`);t.style.visibility=`${this._showDetail?"hidden":"visible"}`,t.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||$e.uploadEvent({log:D_}),this._isCollapseClicked=!0}onQuestionClick(){window.open(qh,"_blank"),this._isQuestionClicked||$e.uploadEvent({log:w_}),this._isQuestionClicked=!0}},Jh=Bl;var Yt=class extends $r{constructor(e){super(e,D.VIDEO);u(this,"stat",{});u(this,"_calculateTimeout",-1);u(this,"viewMirror",!1);u(this,"objectFit");u(this,"container");u(this,"canvas");u(this,"canvasTrack");this.mode=e.canvas?1:0,this.container=e.container,this.canvas=e.canvas,$(e.viewMirror)||(this.viewMirror=e.viewMirror),$(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}initializeElement(){var r;let e=document.createElement(D.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,(r=this.container)==null||r.appendChild(this.elementToRender),this.bindElementEvents(),this.calculateStat()}get styleAttribute(){let e=`width: 100%; height: 100%; object-fit: ${this.objectFit};background-color: black;`;return this.viewMirror&&(e+="transform: scaleX(-1);"),e}setContainer(e){var r;this.container=e,(this.track||this.canvasTrack)&&this.elementToRender&&((r=this.container)==null||r.appendChild(this.elementToRender))}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),e&&e.add(D.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(D.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent)}handleTrackEvent(e){var r;super.handleTrackEvent(e),e.type===D.MUTE&&((r=this.stat)!=null&&r.fps)&&(this.stat.fps=0)}handleElementEvent(e){var o;if(this.mode===2)return;super.handleElementEvent(e);let r=e.type;if(r===D.PAUSE&&(this.container&&document.getElementById(this.container.id)||this._log.warn(`${this.kind} player has been remove, element ID: ${(o=this.container)==null?void 0:o.id}`),this._pausedRetryCount>0&&!Fl()&&(this._log.info(`${this.kind} player auto resume when paused`),this.resume(),this._pausedRetryCount--),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){let s=this.element.style.transform;r===D.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=s.replace("scaleX(-1)",""):r===D.LEAVE_PICTURE_IN_PICTURE&&!s.includes("scaleX")&&(this.element.style.transform=`${s} scaleX(-1)`)}}setCanvas(e,r=1){var o,s,n,d;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&&((d=this.container)==null||d.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}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(Xe.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(Do()&&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 d;return(d=this.element)==null?void 0:d.requestVideoFrameCallback(o)},2e3))};this.element.requestVideoFrameCallback(o)}}catch(e){this._log.warn("init stat failed",e)}}};function Mo(i,t){return y(this,null,function*(){if(!i.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield i.audioWorklet.addModule(t),B.info("worklet addModule success")}catch(e){throw B.info(`worklet addModule catch error. ${e.message}`),e}})}var la;typeof AudioContext!="undefined"?la=AudioContext:typeof webkitAudioContext!="undefined"?la=webkitAudioContext:typeof mozAudioContext!="undefined"&&(la=mozAudioContext);var Ir,zh=-1;Xh();function Xh(){try{if(Ir)return;Ir=new la({sampleRate:48e3}),Ir.onstatechange=()=>{B.info(`context state: ${Ir.state}${Ir.state!=="running"?` visibilityState: ${document.visibilityState}`:""}`),Ls()},clearTimeout(zh)}catch(i){B.error(`initAudioContext failed: ${i} typeof AudioContextClass: ${typeof la}`),zh=setTimeout(Xh,1e3)}}var Ls=()=>{Ir.state==="suspended"?(Us(),document.addEventListener("click",Ls)):Ir.state==="interrupted"?Us():(document.removeEventListener("visibilitychange",Ls),document.removeEventListener("click",Ls))},Hl=0,Wl=-1;function Us(){return new Promise((i,t)=>{if(Ir.state==="running")return i();Date.now()-Hl<1e3?(clearTimeout(Wl),Wl=setTimeout(()=>{Hl=Date.now(),Ir.resume().then(i,t)},1e3)):(clearTimeout(Wl),Hl=Date.now(),Ir.resume().then(i,t))}).catch(i=>{B.warn(`context resume failed: ${i}`),document.addEventListener("visibilitychange",Ls)})}document.addEventListener("click",Ls);var et=i=>Ir;var xt=class{constructor(){u(this,"node");u(this,"node2");u(this,"pre",new Set);u(this,"next",new Set);u(this,"context");u(this,"connectedNodes",new Set)}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.preNodeReconnect(),this.reconnect()}catch(r){B.error(r)}}setNode(t,e){var r;if(!this.node)try{(r=this.context)==null||r.addMixWeight(),this.node=t,e&&(this.node2=e),this.preNodeReconnect(),this.reconnect(),Y.addSuccessEvent({key:502701})}catch(o){B.error(o),Y.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(),Y.addSuccessEvent({key:502702})}catch(e){B.error(e),Y.addFailedEvent({key:502702,error:e})}}preNodeReconnect(){this.pre.forEach(t=>{t.node?t.reconnect():t.preNodeReconnect()})}connectNext(t){this.next.forEach(e=>{t._connect(e.node)||e.connectNext(t)})}_connect(t){return!this.node||!t?!1:((this.node2||this.node).connect(t),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){return t.forEach(e=>{this.next.add(e),e.pre.add(this)}),this}},id=class extends xt{constructor(e=256){super();this.fftSize=e;u(this,"dataArray",new Uint8Array(0))}setNode(e){e.fftSize=this.fftSize,this.dataArray=new Uint8Array(e.frequencyBinCount),super.setNode(e)}getByteTimeDomainData(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),this.dataArray}get level(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),Math.max(...this.dataArray)/128-1}get timeDomainPathData(){let e=this.getByteTimeDomainData(),r=1,o=0,s=0,n=`M${o},${s}`;for(let d=0;d<e.length;d++)s=e[d]/128*100/2,n+=`L${o},${s}`,o+=r;return n}},ma=class{constructor(){u(this,"source",new xt);u(this,"gain",new xt);u(this,"destination",new xt)}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(et().createGain()),this.gain.node.gain.value=t}replaceSource(t){this.source.replaceNode(Gl(t))}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}},Vs=class extends ma{constructor(e){super();this.context=e;u(this,"denoiser",new xt);u(this,"voiceChanger",new xt);this.source.pipeTo(this.denoiser.pipeTo(this.voiceChanger.pipeTo(this.gain.pipeTo(this.destination))))}connect(){this.context.inputs.has(this)||(this.destination.setNode(this.context.destination),this.source.setContext(this.context),this.denoiser.setContext(this.context),this.voiceChanger.setContext(this.context),this.gain.setContext(this.context),this.context.inputs.add(this))}disconnect(){this.context.inputs.has(this)&&(this.destination.deleteNode(),this.source.removeContext(),this.denoiser.removeContext(),this.voiceChanger.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.denoiser.deleteNode(),this.voiceChanger.deleteNode(),this.source.deleteNode(),this.disconnect()}setVolume(e){if(e===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(this.context.audioContext.createGain()),this.gain.node.gain.value=e}},od=class{constructor(){u(this,"audioContext",et("audio-mixer"));u(this,"destination",this.audioContext.createMediaStreamDestination());u(this,"inputs",new Set);u(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]}},Qh=new WeakMap;function Gl(i){let t=Qh.get(i);if(t)return t;let e=et();if(i instanceof HTMLAudioElement)t=e.createMediaElementSource(i);else if(i instanceof MediaStreamTrack)t=e.createMediaStreamSource(new MediaStream([i]));else return i;return Qh.set(i,t),t}var Zt=class Zt{constructor(t){u(this,"_volume",0);u(this,"_volumeDb",0);u(this,"_log");u(this,"_scriptProcessorNode",null);u(this,"_audioWorkletNode",null);u(this,"_interval",200);u(this,"ready",this.preload());let{log:e}=t;this._log=e,H.on(L.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-Zt.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!Zt.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);';Zt.workletReady=Mo(Zt.audioContext,URL.createObjectURL(new Blob([t],{type:"application/javascript"})))}return Zt.workletReady.then(()=>this.initAudioWorklet()).catch(t=>(this._log.error(`volumeMeter preload error: ${t}`),this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(Zt.audioContext,"volume-meter");let t=!1;this._audioWorkletNode.port.onmessage=e=>{Zt.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}`),$e.logFailedEvent({userId:this._log.userId,eventType:zr.LOAD_WORKLET,error:t}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=et("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=t=>{Zt.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,H.off(L.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})}};u(Zt,"lastMessageTime",0),u(Zt,"audioContext",et("volume-meter")),u(Zt,"workletReady");var sd=Zt,nd=class extends xt{constructor(e){super();u(this,"_volumeMeter");this._volumeMeter=new sd(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return y(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()}}},ad=sd;var ef=Di(Ui(),1);var Zh=i=>t=>t.deviceId===i;var pa=class{constructor(t,e="Input"){u(this,"kind");u(this,"type");u(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&&Bs(this.devices[0])){this.devices=r;return}e&&(r.forEach(o=>{if(o.deviceId&&!this.devices.find(Zh(o.deviceId))){let s=`${this.kind}${this.type}Added`;B.warn(`${s}: ${JSON.stringify(o)}`),e.emit(s,o)}}),this.devices.forEach(o=>{if(o.deviceId&&!r.find(Zh(o.deviceId))){let s=`${this.kind}${this.type}Removed`;B.warn(`${s}: ${JSON.stringify(o)}`),e.emit(s,o)}})),this.devices=r}hasDevice(t){return!!this.devices.find(e=>e.deviceId===t)}},jl=class extends ef.EventEmitter{constructor(){super();u(this,"audioInputs",new pa(D.AUDIO));u(this,"videoInputs",new pa(D.VIDEO));u(this,"audioOutputs",new pa(D.AUDIO,"Output"));this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||St.run("interval",()=>{this.update()},{delay:1e4}))}init(){cd().then(e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)})}update(){return y(this,arguments,function*(e=0){let r=yield cd(e);return this.audioInputs.update(r,this),this.videoInputs.update(r,this),this.audioOutputs.update(r,this),this})}},Et=Sn||ds?null:new jl;function Bs(i){return i.deviceId===i.groupId&&i.groupId===""}function cd(){return y(this,arguments,function*(i=0){if(si()||!Zc())return[];let t=yield navigator.mediaDevices.enumerateDevices();if(i!==0){let e={audio:!1,video:!1};if(t.forEach(r=>{Bs(r)&&(r.kind===D.AUDIO_INPUT?e.audio=!0:r.kind===D.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&&Us()}catch(o){B.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&&ql.add(`${e.deviceId}_${e.kind}`),e.getCapabilities&&(o.getCapabilities=()=>e.getCapabilities()),o})})}function Jt(i=!1){return Et.update(i?1:0).then(t=>t.audioInputs.devices)}function Kt(i=!1){return Et.update(i?2:0).then(t=>t.videoInputs.devices)}var Kh=!1;function tf(){return y(this,null,function*(){try{Kh||(Kh=!0,B.info(`speakers:${(yield $i()).map(i=>` ${i.deviceId.slice(0,8)}: ${i.label}`)}`))}catch(i){}})}function $i(i=!1){return y(this,null,function*(){return(It||Mt)&&(i=!1),Et.update(i?1:0).then(t=>t.audioOutputs.devices)})}var ql=new Set;function rf(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}_${D.VIDEO_INPUT}`;return!!ql.has(r)}function of(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}_${D.AUDIO_INPUT}`;return!!ql.has(r)}function Jl(i,t){return y(this,null,function*(){let r=(yield Jt()).find(o=>o.deviceId===fo);return!t&&(r==null?void 0:r.groupId)===i||(r==null?void 0:r.groupId)===i&&r.label===t})}function sf(s){return y(this,arguments,function*({newDeviceId:i,oldDeviceId:t,oldGroupId:e,oldLabel:r,kind:o}){return i!==t?!1:o===D.AUDIO&&i===fo?yield Jl(e,r):!0})}var dd,zl=class extends ma{constructor(e){super();this.log=e;u(this,"volumeMeter");u(this,"volumeDestination");u(this,"analyser",new id);this.volumeMeter=new nd({log:this.log}),this.volumeDestination=new xt,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},ud=class i extends $r{constructor(e){super(e,D.AUDIO);u(this,"_outputDeviceId");u(this,"_volume",1);u(this,"_destination",et("player").createMediaStreamDestination());u(this,"pipeline");u(this,"volumeMeterMode","worklet");this.mode=0,this.pipeline=new zl(this._log)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(e){if((Li==="15.2"||Li==="15.3"||Li==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}let o=dd||new Audio;o.setAttribute("autoplay","autoplay"),o.srcObject=this.getMediaStream(),o.muted=this.muted,this.element=o,je(e)&&(this.element.volume=Math.min(Math.max(e,0),1)),o===dd&&(dd=void 0),this.bindElementEvents()}play(e){return y(this,null,function*(){if(this.track)return this.pipeline.source.node||this.pipeline.replaceSource(this.track),this.element||this.initializeElement(e==null?void 0:e.volume),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),this.volumeMeterMode==="worklet"?this.pipeline.volumeMeter.init():this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(et("player").createAnalyser()),tf(),Bt(i.prototype,this,"play").call(this)})}stop(e=0){this.pipeline.destroy(),super.stop(e)}setSinkId(e){return y(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()}},ld=class extends ud{setTrack(t){this.track!==t&&(this.unbindTrackEvents(),this.track=t,this.emit(Xe.MEDIA_TRACK_CHANGED,t),t&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([t]))))}setVolume(t){this._volume=t,this.element&&(this.element.volume=t)}},md=class extends ud{constructor(e){super(e);u(this,"_sourceElement");u(this,"_output",new xt);this.pipeline.source.pipeTo(this.pipeline.gain.pipeTo(this.pipeline.volumeMeter.pipeTo(this._output),this.pipeline.destination))}setOutput(){this.mode=1,this._output.setNode(et("player").destination)}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var r,o;((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(Xe.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.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){this._volume=e,this.useDestination?(this.pipeline.setVolume(e),this._log.info(`set pipeline volume: ${e}`)):e<=1?this.element?(this._log.info(`set element volume: ${e}`),this.element.volume=e):this._log.info("set element volume: no element"):It||(this._log.info(`start set pipeline volume: ${e}`),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),ut(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&&xi&&(dd=r),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}};var Oo=class extends ne{constructor({userId:e,sdkAppId:r,mediaType:o,room:s,PlayerClass:n=o===1?md:Yt}){var d;super();u(this,"id",Qn());u(this,"userId","");u(this,"isRemote");u(this,"mediaType");u(this,"room");u(this,"user");u(this,"_log");u(this,"_inputTrack");u(this,"_outputTrack");u(this,"isPlayCalled");u(this,"container",null);u(this,"player");u(this,"subVideoPlayerMap");u(this,"muted",!1);u(this,"abortCtrl");u(this,"objectFit","cover");u(this,"mirror");u(this,"isScreen",!1);u(this,"manager");u(this,"trackSettings");u(this,"isFirstVideoFrameEmitted",!1);this.userId=e||"",this.mediaType=o,this._log=B.createLogger({id:`${this.kind[0]}t`,userId:(d=s||this.room)==null?void 0:d.userId,remoteUserId:this instanceof ai?void 0:this.userId,sdkAppId:r,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof ai}),this.player=new n({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log}),this.player.on(Xe.PLAYER_STATE_CHANGED,p=>{H.emit(L.PLAYER_STATE_CHANGED,Z({track:this},p)),this.emit("player-state-changed",p)}),this.kind===D.VIDEO&&(this.player.on(Xe.LOADED_DATA,()=>{this.emitFirstVideoFrameEvent(Xe.LOADED_DATA),H.emit(L.VIDEO_LOADED_DATA,{track:this})}),this.player.on(Xe.LOADED_META_DATA,()=>{this.emitFirstVideoFrameEvent(Xe.LOADED_META_DATA)}),this.player.on(Xe.MEDIA_TRACK_CHANGED,p=>{var m;(m=this.subVideoPlayerMap)==null||m.forEach(E=>E.setTrack(p))})),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(Xe.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||B}get kind(){return this.mediaType===1?D.AUDIO:D.VIDEO}get strMediaType(){return this.mediaType===4?D.VIDEO:this.mediaType===2?D.SCREEN:D.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 y(this,null,function*(){let o=st(e)?e[0]:e;if(this.isPlayCalled){this.log.info(`play update options: ${JSON.stringify(r)}`),r&&!$(r.muted)&&this.setPlayerMute(r.muted),r&&!$(r.objectFit)&&(this.objectFit=r.objectFit),this.player instanceof Yt&&(this.player.setObjectFit(this.objectFit),this.container!==o&&o&&(this.container=o,this.player.setContainer(o)),st(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),r)));return}if(r&&!$(r.muted)?this.setPlayerMute(r.muted):(!this.isRemote||this.kind===D.VIDEO)&&this.setPlayerMute(!0),r&&!$(r.objectFit)&&(this.objectFit=r.objectFit),this.player instanceof Yt&&this.player.setObjectFit(this.objectFit),this.isPlayCalled=!0,o&&(this.container=o,this.player instanceof Yt&&this.player.setContainer(o)),H.emit(L.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),st(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!==D.VIDEO||$(e)||e===this.mirror)return;this.mirror=e;let o=this.player;r&&(o=r);let s=this.manager;if(dt(this.mirror)){o.setViewMirror(this.mirror),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 y(this,null,function*(){if(!this._outputTrack||this.kind===D.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((s,n)=>{var d;e.find(p=>n===p)||(s.stop(),(d=this.subVideoPlayerMap)==null||d.delete(n))});for(let[s,n]of e.entries()){let d=this.subVideoPlayerMap.get(n);d?r&&($(r.objectFit)||d.setObjectFit(r.objectFit)):this.subVideoPlayerMap.set(n,new Yt({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(Wu(this)&&!e?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(r=>{r.stop()}),this.container=null)}resume(){return y(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),H.emit(e?L.TRACK_MUTED:L.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){Pt(e,e).add(D.MUTE,this.onTrackMuted).add(D.UNMUTE,this.onTrackUnmuted).add(D.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===D.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){ut(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(Wu(this)?this.jitterBufferDelay:0),this.log.info(`playing state updated, stop ${this.kind}`);return}}this.log.debug(`updatePlayingState abort ${this.isPlayCalled} ${e} ${this.player.isStopped}`)}handleAutoPlayFailed(e){if(this.room&&this.room.enableAutoPlayDialog)new Jh;else{let r=()=>{this.resume().then(()=>{document.removeEventListener("click",r,!0)})};document.addEventListener("click",r,!0)}this.emit("error",e)}getVideoFrame(){return this.player instanceof Yt?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(e){var n,d,p;if(this.isFirstVideoFrameEmitted)return;let r=(n=this.mediaTrack)==null?void 0:n.getSettings(),o=(r==null?void 0:r.width)||((d=this.player.element)==null?void 0:d.videoWidth)||0,s=(r==null?void 0:r.height)||((p=this.player.element)==null?void 0:p.videoHeight)||0;e===Xe.LOADED_META_DATA&&!o&&!s||(e===Xe.LOADED_DATA&&!o&&!s&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,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`)}};X([qe([],ne.INIT,{sync:!0})],Oo.prototype,"close",1);var O_=Object.prototype.hasOwnProperty,{toString:OR}=Object.prototype;function P_(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(Gt(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(O_.call(i,t))return!1;return!0}}return!1}var ha=P_;var x_=function(i){return y(this,null,function*(){let t=L_(i);B.info(`getUserMedia with constraints: ${JSON.stringify(t)}`);let e=[],r=[],o=["label","deviceId","groupId"];t.audio&&(e=yield Jt(),B.info(`microphones: ${rr(e.map(s=>Ee(Z({},s),{groupId:s.groupId.substring(0,8)})),{keysToInclude:o})}`)),t.video&&(r=yield Kt(),B.info(`cameras: ${rr(r,{keysToInclude:o})}`));try{let s=yield navigator.mediaDevices.getUserMedia(t);return Dl&&s.getTracks().forEach(n=>{B.info(`${n.kind} capabilities: ${rr(n.getCapabilities(),{keysToInclude:hc})}`)}),t.audio&&Us(),s}catch(s){let{message:n}=s;throw s.name==="NotFoundError"&&(i.video&&r&&r.length===0&&(n=at({key:nt.CAMERA_NOT_FOUND})),i.audio&&e&&e.length===0&&(n=at({key:nt.MICROPHONE_NOT_FOUND}))),new he({code:te.INITIALIZE_FAILED,name:s.name,message:n,constraint:s.constraint})}})},k_=Pi({retryFunction:x_,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"?(s===1?(r[0].video&&(r[0].maxResolution=!1,(!Mt||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&&nf(r[0].microphoneId,!1),r[0].cameraId&&nf(r[0].cameraId,!0)},onRetrying:i=>{B.warn(`getUserMedia NotReadableError observed, retrying [${i}/3]`)},onRetryFailed:i=>{$e.logFailedEvent({eventType:zr.GET_USER_MEDIA_RETRY,error:i})},onRetrySuccess:i=>{$e.logSuccessEvent({eventType:zr.GET_USER_MEDIA_RETRY}),$e.uploadEvent({log:`stat-${zr.GET_USER_MEDIA_RETRY}-success-${i}`})}});function nf(i,t){return y(this,null,function*(){let r=(t?yield Kt():yield Jt()).find(o=>o.deviceId===i);r&&ze(r.getCapabilities)&&B.warn(rr(r.getCapabilities(),{keysToInclude:hc}))})}function L_(i){return{audio:U_(i),video:V_(i)}}function U_(i){if(!i.audio)return!1;if(i.useTrueAsConstraint)return!0;let t={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:i.sampleRate};return!ha(i.microphoneId)&&(t.deviceId=i.useExactDeviceId?{exact:i.microphoneId}:i.microphoneId,i.useDeviceIdOnly)?t:(je(i.channelCount)&&(t.channelCount=i.channelCount),dt(i.echoCancellation)&&!i.echoCancellation&&(t.echoCancellation=!1),dt(i.noiseSuppression)&&!i.noiseSuppression&&(t.noiseSuppression=!1),dt(i.autoGainControl)&&!i.autoGainControl&&(t.autoGainControl=!1),ha(t)?!0:t)}function V_(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&&!ha(e)?e:(i.width&&(e.width={ideal:i.width},t&&!gr&&(e.width.max=i.width)),i.height&&(e.height={ideal:i.height},t&&!gr&&(e.height.max=i.height)),gr&&_r&&i.width&&i.height&&i.width*i.height<352*288&&(e.width=i.width,e.height=i.height),i.frameRate&&(e.frameRate=i.frameRate),ha(e)?!0:e)}var af=k_;function Fi(i){return Me((t,e)=>function(...r){return y(this,null,function*(){let o=yield t.apply(this,r);return yield i.call(this,...r),o})})}function cf(i){return Me((t,e)=>function(...r){return y(this,null,function*(){try{return yield t.apply(this,r)}catch(o){i.call(this,o)}})})}function Me(i){return function(t,e,r){return r.value=i(r.value,e),r}}var df=(()=>{let i=!1,t=document.visibilityState;return()=>{document.visibilityState!==t&&B.info(`visibility change: ${document.visibilityState}`),!i&&(document.addEventListener("visibilitychange",()=>{B.info(`visibility change: ${document.visibilityState}`),t=document.visibilityState}),i=!0)}})();var B_=0,pd=class{constructor(){u(this,"log",B.createLogger({id:`fq${++B_}`}));u(this,"isRunning",!1);u(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=Z({},t),o=new Promise((d,p)=>{r.resolve=d,r.reject=p});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()})}},uf=new WeakMap,lf=new WeakMap;function mf(i=!1){return function(t,e,r){let o=r.value;return r.value=function(...s){let n=uf.get(this)||new pd;return uf.set(this,n),n.push({fn:o,args:s,context:this},i)},r}}function hd(i){return function(t,e,r){let o=r.value,s=n=>i(...n);return r.value=function(...n){let d=lf.get(this)||new Map,p=d.get(s(n))||new pd;return d.set(s(n),p),lf.set(this,d),p.push({fn:o,args:n,context:this})},r}}function fd(i,t){return Me((e,r)=>function(...o){let s=i;try{let n=e.apply(this,o),d=_e();return Mi(n)?n.then(p=>(t?Y.addSuccessEvent({key:s,cost:_e()-d}):Y.addSuccessEvent({key:s}),p)).catch(p=>{throw Y.addFailedEvent({key:s,error:p}),p}):(Y.addSuccessEvent({key:s}),n)}catch(n){throw Y.addFailedEvent({key:s,error:n}),n}})}var Po=class Po extends Oo{constructor(e,r){super({mediaType:e,PlayerClass:r});u(this,"isRemote",!1);u(this,"deviceId");u(this,"groupId","");u(this,"label","");u(this,"_isRecapturing",!1);u(this,"_lastRecaptureTime",0);u(this,"_onMuteTimeoutId",-1);u(this,"_encodeCheckTimeoutId",-1);u(this,"profile")}get enableEncodeFrame(){return!1}get isPublishing(){return this.state.toString()==="publishing"}get isPublished(){return this.state==="publish"}encodeFrame(e,r){throw new Error("Method not implemented.")}installTrackEvent(e){Pt(e,e).add(D.MUTE,this.onTrackMuted).add(D.UNMUTE,this.onTrackUnmuted).add(D.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===D.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){ut(e)}setStateToCapture(){}capture(e){return y(this,null,function*(){var r;try{let o=_e();H.emit(L.LOCAL_TRACK_CAPTURE_START,{track:this});let s;e.customSource?(s=new MediaStream,s.addTrack(e.customSource)):((r=this.mediaTrack)==null||r.stop(),s=yield af(e));let n=s.getTracks()[0];return yield this.setInputMediaStreamTrack(n),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),H.emit(L.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:_e()-o}),s}catch(o){throw H.emit(L.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:o}),this.log.error(`getUserMedia error observed ${o}`),o}})}setInputMediaStreamTrack(e){return this.state===ne.INIT&&this.setStateToCapture(),super.setInputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var r;if(super.setOutputMediaStreamTrack(e),this.isPublishing||this.isPublished)return(r=this.room)==null?void 0:r.replaceTrack(this)}publish(e,r){return this.room=e,this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),r}unpublish(){this.room&&this.room.localTracks.delete(this),H.emit(L.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return y(this,null,function*(){if(this.mediaTrack&&xs){let{deviceId:e,groupId:r}=this.mediaTrack.getSettings(),{label:o}=this.mediaTrack;(yield sf({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=o,r&&(this.groupId=r),cd().then(n=>{let d=n.find(p=>p.deviceId===e);d&&this.emit("2",d)}))}})}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(e=!1){return!(!this.deviceId||!this.mediaTrack||this.kind===D.AUDIO&&!of(this.mediaTrack)||this.kind===D.VIDEO&&!rf(this.mediaTrack)||this._isRecapturing||e&&_r&&Mt)}onTrackMuted(){if(super.onTrackMuted(),df(),!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<ms){setTimeout(()=>this.onTrackMuted(),ms);return}this._onMuteTimeoutId=setTimeout(()=>y(this,null,function*(){var e;if((e=this.mediaTrack)!=null&&e.muted){if((It||gt)&&document.visibilityState!=="visible")return;this.recapture(yield this.getRecoverCaptureDeviceId())}}),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return y(this,null,function*(){if(Bt(Po.prototype,this,"onTrackEnded").call(this),!!this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<ms){setTimeout(()=>this.onTrackEnded(),ms);return}this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e){return y(this,null,function*(){var o;if(this._isRecapturing||!this._inputTrack)return;this.log.warn("recapture trying"),(o=this._inputTrack)==null||o.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let r={useExactDeviceId:!0};if(e==="user"||e==="environment")r.facingMode=e;else{let s;(this.kind==="audio"?yield Jt():yield Kt()).find(d=>d.deviceId===e)&&(s=e),r.deviceId=s}return this.capture(r).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),H.emit(L.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(s=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${s.message}`),this.emit("5",s),H.emit(L.LOCAL_TRACK_RECAPTURE,{track:this,error:s})})})}getRecoverCaptureDeviceId(){return y(this,null,function*(){let e=this instanceof Sr;if(e&&this.facingMode)return this.facingMode;let{deviceId:r}=this;if(r){let o=(fa.get(r)||0)+1;if(fa.set(r,o),o>=3){let s=e?(yield Kt()).find(n=>!fa.has(n.deviceId)):(yield Jt()).find(n=>!fa.has(n.deviceId));s&&(this.log.warn(`${r} capture fail ${o} times, change new ${s.deviceId}`),r=s.deviceId)}}return r})}close(){var e;super.close(),this._inputTrack&&(this._inputTrack.stop(),this.uninstallTrackEvent(this._inputTrack)),(e=this.manager)==null||e.removeInput(this)}};X([qe(ne.INIT,"capture",{ignoreError:!0,sync:!0})],Po.prototype,"setStateToCapture",1),X([mf()],Po.prototype,"capture",1),X([qe("capture","publish",{ignoreError:!0,success(){var r,o;this.room.localTracks.add(this),H.emit(L.LOCAL_TRACK_PUBLISHED,{track:this}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),!((((o=(r=this.room)==null?void 0:r.networkQuality)==null?void 0:o.uplinkNetworkQuality)||0)>3)&&(this._encodeCheckTimeoutId=setTimeout(()=>{var n,d;if(!((((d=(n=this.room)==null?void 0:n.networkQuality)==null?void 0:d.uplinkNetworkQuality)||0)>3)&&this.isPublished&&this.isMediaTrackActive){let p=this.kind===D.AUDIO,m=this.stat.bytesSent>0;Y[m?"addSuccessEvent":"addFailedEvent"]({key:p?503700:513702}),m||(Y.addEnum({key:p?503701:513703,value:zn()}),$e.uploadEvent({log:`stat-encode-failed-${this.kind}-${Jn()||So()}`,userId:this.userId}),this.log.warn("encode failed"),this.emit("6",this))}},5e3))},fail(e){let r="error";if(e.cause instanceof RTCError){let o=e.cause;o.message.includes("timeout")?r="timeout":o.code===te.API_CALL_ABORTED&&(r="api-call")}this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:r,error:e.cause||e})}}),fd(521714,!1)],Po.prototype,"publish",1),X([Me(e=>function(){return y(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)})}),qe([],"capture",{sync:!0})],Po.prototype,"unpublish",1);var ai=Po,fa=new Map;H.on(L.SWITCH_DEVICE_SUCCESS,i=>{i.track.deviceId&&fa.delete(i.track.deviceId)});var ci=class i extends ai{constructor(e){super(1,ld);u(this,"mediaType",1);u(this,"volume",0);u(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40});u(this,"playerMuted",!0);u(this,"pipeline");u(this,"earMonitorGainNode",new xt);u(this,"_output",new xt);u(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0});this.manager=e,this.pipeline=new Vs(e),this.pipeline.gain.pipeTo(this.earMonitorGainNode.pipeTo(this._output),this.player.pipeline.volumeMeter),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this)}get dbVolume(){return ad.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}get playerMediaTrack(){return this.mediaTrack}setInputMediaStreamTrack(e){return y(this,null,function*(){let r=this.trackSettings||{};Y.addEnum({key:501701,value:r.channelCount||0,useUV:!1}),Y.addEnum({key:501702,value:r.sampleRate||0,useUV:!1}),Y.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.replaceSource(e),yield Bt(i.prototype,this,"setInputMediaStreamTrack").call(this,e),this.updatePlayingState(!!e)})}capture({deviceId:e,customSource:r,useExactDeviceId:o=!0,retryWhenExactFailed:s=!0}){return super.capture({video:!1,audio:!0,microphoneId:e,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:o,retryWhenExactFailed:s,customSource:r})}switchDevice(e){return y(this,null,function*(){if(this.mediaTrack){if(this.deviceId===e)if(e===fo){if(yield Jl(this.groupId,this.label))return}else return;try{this.log.info(`switchDevice audio to: ${e}`),this.mediaTrack&&this.mediaTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0,retryWhenExactFailed:!1}),H.emit(L.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(){Et&&!Et.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&Et.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return y(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current microphone is lost: ${JSON.stringify(e)}`),tt(this.userId,{eventId:2003,param1:6,streamType:1});let r=yield Jt();r[0]?this.recapture(r[0].deviceId):Et.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.log.warn(`microphone added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)}update3A(s){return y(this,arguments,function*({echoCancellation:e,noiseSuppression:r,autoGainControl:o}){let n=!1;!$(e)&&e!==this.profile.echoCancellation&&(this.profile.echoCancellation=e,n=!0),!$(r)&&r!==this.profile.noiseSuppression&&(this.profile.noiseSuppression=r,n=!0),!$(o)&&o!==this.profile.autoGainControl&&(this.profile.autoGainControl=o,n=!0),n&&this.deviceId&&(yield this.recapture(this.deviceId))})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&Y.addEnum({key:502700,value:2})}setAudioVolume(e){super.setAudioVolume(0),this.earMonitorGainNode.node||(this.earMonitorGainNode.setNode(et().createGain()),this._output.setNode(et().destination)),this.earMonitorGainNode.node.gain.value=e}enableTrackANS(e){if(!this._inputTrack)return;let r=this._inputTrack.getConstraints();return r.noiseSuppression=e,this._inputTrack.applyConstraints(r).catch(o=>this._log.warn(`${e?"enable":"disable"} ANS failed `,o))}addDenoiser(e){var r;if(Zr<=92&&((r=this.trackSettings)==null?void 0:r.sampleRate)!==48e3){this._log.warn("denoiser only support sampleRate 48000 before chrome 93");return}Y.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.enableTrackANS(!1)}removeDenoiser(e){this.pipeline.denoiser.node===e&&(this.pipeline.denoiser.deleteNode(),this.enableTrackANS(!0))}close(){this.pipeline.remove(),this.earMonitorGainNode.deleteNode(),this._output.deleteNode(),Et.off("audioInputAdded",this.handleMicrophoneAdded,this),Et.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}recapture(e){return y(this,null,function*(){try{yield Bt(i.prototype,this,"recapture").call(this,e)}catch(r){let o=(yield Jt()).find(s=>s.deviceId!==e);if(o)yield Bt(i.prototype,this,"recapture").call(this,o.deviceId);else throw r}})}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduceRight((r,o)=>o?o({frame:r}):r,e):e}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}};var xo=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 d=this.dataView.getInt8(n);switch(d){case 0:case 1:case 2:case 3:o===2&&(r.push(3),o=0),d==0?o++:o=0,r.push(d);break;default:o=0,r.push(d);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 gd=class{constructor(){u(this,"_seiMessageList",[]);u(this,"_smallSeiMessageList",[]);u(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 d=0;d<r;d++)s.push(255);s.push(o);let n=new DataView(t);return s.push(...new Uint8Array(n.buffer)),s.push(128),new xo(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)),d=n.reduce((b,C)=>b+C.dataView.byteLength,0),p=new ArrayBuffer(d+t.data.byteLength),m=new DataView(p),E=new DataView(t.data),_=0;for(let b=0;b<n.length;b++)for(let C=0;C<n[b].dataView.byteLength;C++)m.setInt8(_++,n[b].dataView.getInt8(C));for(let b=0;b<t.data.byteLength;b++)m.setInt8(_++,E.getInt8(b));return t.data=p,n.length}return 0}};var ko=class ko extends ai{constructor(e,r=4){super(r,Yt);u(this,"profile",{width:640,height:480,frameRate:15,bitrate:500});u(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0});u(this,"small");u(this,"isNeedToSetBandwidth");u(this,"muteImage");u(this,"manager");u(this,"_seiCodec",new gd);this.manager=e;let o=()=>{this.isAllowed2k4k(this.profile)?this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1}):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),this.setProfile(Ee(Z({},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(!(!xs||!this.mediaTrack))return this.mediaTrack.getSettings().facingMode}get isQosClearFirst(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)==="detail"}setMute(e){return y(this,null,function*(){var r,o,s;if(we(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}),this.muteImage=e,Bt(ko.prototype,this,"setMute").call(this,!1)}else yield(s=this.manager)==null?void 0:s.deleteWatermark("mute"),this.muteImage=void 0,Bt(ko.prototype,this,"setMute").call(this,e)})}capture({deviceId:e,facingMode:r,useExactDeviceId:o=!0,customSource:s,retryWhenExactFailed:n=!0}){return super.capture({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})}setProfile(e){let r=Z({},e),o=r.width>r.height;r.width*r.height<=160*120&>&&Io&&(this.log.warn(`resolution is ${r.width}*${r.height}, fallback to 240*180`),r.width=o?240:180,r.height=o?180:240,r.bitrate=Math.max(r.bitrate,150)),r.width*r.height>1280*720&&rl&&(r.width=o?1280:720,r.height=o?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),r.bitrate&&(this.isNeedToSetBandwidth=r.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile)?super.setProfile(r):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),super.setProfile(Ee(Z({},this.profile),{width:1920,height:1080})))}applyProfile(){return y(this,null,function*(){var o;if(!this.mediaTrack)return;let e=this.settings;if(!(!(e.height!==this.profile.height||e.width!==this.profile.width||e.frameRate!==this.profile.frameRate)||!this.deviceId)&&(Qt===16?yield this.recapture(this.deviceId):(yield(o=this.mediaTrack)==null?void 0:o.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))return this.isNeedToSetBandwidth=!1,this.room.setBandWidth({bandwidth:this.profile.bitrate,type:D.VIDEO,videoType:D.BIG})})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate};return xs&&this.mediaTrack&&Object.assign(e,this.mediaTrack.getSettings()),e}get scaleResolutionDownBy(){let{settings:e}=this;return e.width===this.profile.width&&e.height===this.profile.height?1:Tc()&&this.profile.width>this.profile.height&&e.height>e.width?Math.max(e.width/this.profile.height,e.height/this.profile.width,1):Math.max(e.width/this.profile.width,e.height/this.profile.height,1)}isAllowed2k4k(e){var 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 y(this,null,function*(){try{if(!this.isNeedToSwitchDevice(e))return;let r={useExactDeviceId:!0,retryWhenExactFailed:!1};e==="user"||e==="environment"?r.facingMode=e:r.deviceId=e,this.mediaTrack.stop(),yield this.capture(r),H.emit(L.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}})}listenDeviceChange(){Et&&!Et.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&Et.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return y(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current camera is lost: ${JSON.stringify(e)}`),tt(this.userId,{eventId:2003,param1:7,streamType:2});let r=yield Kt();r[0]?this.recapture(r[0].deviceId):Et.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return y(this,null,function*(){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 $(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,r)}close(){Et.off("videoInputAdded",this.handleCameraAdded,this),Et.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return y(this,null,function*(){try{yield Bt(ko.prototype,this,"recapture").call(this,e)}catch(r){let o=(yield Kt()).find(s=>s.deviceId!==e);if(o)yield Bt(ko.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))}};X([Fi(function(e){this.setContentHint(e.contentHint||"motion")})],ko.prototype,"capture",1);var Sr=ko;var ff=Qn();if(typeof navigator!="undefined"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:ff,exposeOrigin:!0,permittedOrigins:["*"]})}catch(i){}var H_=function(i){return y(this,null,function*(){let t=null,e=j_(i);B.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let r=yield navigator.mediaDevices.getDisplayMedia(e);i.systemAudio&&r.getAudioTracks().length===0&&(Cs&&Zr<74||Mt||gr)&&B.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){B.warn(`screen applyConstraints failed: ${s}`)}i.captureElement&&(yield W_(o,i.captureElement))}if(i.audio){let s=G_(i);B.info(`getUserMedia with constraints: ${JSON.stringify(s)}`),t=yield navigator.mediaDevices.getUserMedia(s),r.addTrack(t.getAudioTracks()[0])}return r})};function W_(i,t){return y(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&ze(i.cropTo))try{if(!(((e=i.getCaptureHandle())==null?void 0:e.handle)===ff))return;let o=yield CropTarget.fromElement(t);yield i.cropTo(o)}catch(r){B.warn(`cropTo target failed ${r}`)}})}function G_(i){let t={echoCancellation:i.echoCancellation,autoGainControl:i.autoGainControl,noiseSuppression:i.noiseSuppression,sampleRate:i.sampleRate,channelCount:i.channelCount};return $(i.microphoneId)||(t.deviceId=i.microphoneId),{audio:t,video:!1}}function j_(i){let t={preferCurrentTab:i.preferDisplaySurface==="current-tab"||!!i.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:Mt?{max:i.width}:{ideal:i.width,max:i.width},height:Mt?{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 gf=H_;var Hi=class extends Sr{constructor(e){super(e,2);u(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600});u(this,"objectFit","contain");u(this,"isScreen",!0);this._log.id=`s-${this._log.id}`}capture(E){return y(this,arguments,function*({systemAudio:e=!1,autoGainControl:r,echoCancellation:o,noiseSuppression:s,audioTrack:n,videoTrack:d,captureElement:p,preferDisplaySurface:m}){try{let _;return d||n?(_=new MediaStream,d&&_.addTrack(d),n&&_.addTrack(n)):_=yield gf({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:r,echoCancellation:o,noiseSuppression:s,captureElement:p,preferDisplaySurface:m}),yield this.setInputMediaStreamTrack(_.getVideoTracks()[0]),_}catch(_){throw this.log.error(`getDisplayMedia error observed ${_}`),_ instanceof he?_:new he({code:te.INITIALIZE_FAILED,name:_.name,message:_.message})}})}switchDevice(e){return y(this,null,function*(){throw new Error("Method not implemented.")})}};X([Fi(function(e){this.setContentHint(e.contentHint||"detail")})],Hi.prototype,"capture",1);var Lo=class extends ci{constructor(t){super(t),this._log.id=`s-${this._log.id}`}};var q_="registerProcessor('dumper', class extends AudioWorkletProcessor {process(inputs) {this.port.postMessage(inputs);return true;}});",Ql;function ga(i){return y(this,null,function*(){let t=et("dump");Ql||(Ql=Mo(t,URL.createObjectURL(new Blob([q_],{type:"application/javascript"})))),yield Ql;let e=new AudioWorkletNode(t,"dumper",{numberOfInputs:i.length,numberOfOutputs:0});return i.forEach((r,o)=>r.connect(e,0,o)),new ReadableStream({start(r){e.port.onmessage=o=>{r.enqueue(o.data)}},cancel(){i.forEach(r=>r.disconnect(e)),e.port.close()}})})}var Ed=class extends od{constructor(e){super();this.room=e;u(this,"_localAudioTrack");u(this,"_localScreenAudioTrack");u(this,"log",B.createLogger({id:"am"}));u(this,"denoiser");u(this,"voiceChanger");u(this,"mixChangedDebounce");u(this,"encodePipeline",[]);u(this,"decodePipeline",[]);e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId))}get _localAudioPipline(){var e;return(e=this._localAudioTrack)==null?void 0:e.pipeline}dump(e){var E,_;if(!this._localAudioTrack)return;let r=[],o=[];(E=this._localAudioPipline)!=null&&E.source.node&&(r.push(this._localAudioPipline.source.node),o.push("mic")),(_=this._localAudioPipline)!=null&&_.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=[],d=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),s.abort("timeout")},e*1e3),p=()=>{for(let b=0;b<o.length;b++){let C=URL.createObjectURL(new Blob(n[b])),k=document.createElement("a");k.href=C,k.download=`${o[b]}.pcm`,k.style.display="none",document.body.appendChild(k),k.click(),URL.revokeObjectURL(C),k.remove()}clearTimeout(d),s.abort("download")},m=ga(r).then(b=>b.pipeTo(new WritableStream({write(C){C.forEach((k,x)=>n[x]=n[x]?n[x].concat(k[0]):[k[0]])}}),s).catch(C=>p));return{then:m.then.bind(m),download:p}}getPCM(e){var n;if($(WritableStream)){this.log.warn("getPCM failed: browser not support WritableStream");return}if(!((n=this._localAudioPipline)!=null&&n.source.node)){this.log.warn("getPCM failed: no local audio track");return}this.log.warn("getPCM");let r=new Float32Array(1920),o=0,s=new AbortController;return ga([this._localAudioPipline.source.node]).then(d=>d.pipeTo(new WritableStream({write(p){p[0][0]&&(r.set(p[0][0],o),o+=p[0][0].length,o>=1920&&(o=0,e(r),r=new Float32Array(1920)))}}),s).catch(p=>this.log.warn(`stop getPCM reason:${p}`))),s}get hasScreenAudioTrack(){return this._localScreenAudioTrack!==null}get hasAudioTrack(){return!$(this._localAudioTrack)}changeInput(e){if(e instanceof Lo)return this._localScreenAudioTrack=e,e.pipeline.connect(),this.mixOnChange();if(e instanceof ci)return this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),e.pipeline.connect(),this.mixOnChange();if(e instanceof Uo)return e.setOutputMediaStreamTrack(e.mediaTrack)}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 Lo?delete this._localScreenAudioTrack:e instanceof ci?delete this._localAudioTrack:e instanceof Uo}addDenoiser(e){var r;this.denoiser=e,(r=this._localAudioTrack)==null||r.addDenoiser(e)}removeDenoiser(e){var r;delete this.denoiser,(r=this._localAudioTrack)==null||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()}destroy(){this.close()}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}};function Ef(i=30,t=2){return Me((e,r)=>function(...o){return new Promise((s,n)=>{let d=setTimeout(()=>{let p=new he({code:te.API_CALL_TIMEOUT,message:`checkPendingPromise ${r}() timeout ${i}s`});B.warn(p),t===2?n(p):t===1&&s()},i*1e3);e.apply(this,o).then(s,n).finally(()=>{clearTimeout(d)})})})}var km={};qr(km,{Events:()=>it,Inspect:()=>ir,LastSink:()=>Vo,Sink:()=>de,Subscribe:()=>Bo,TimeoutError:()=>Ea,audit:()=>NT,bindCallback:()=>pT,bindNodeCallback:()=>hT,buffer:()=>rT,bufferCount:()=>tT,bufferTime:()=>JT,call:()=>_f,catchError:()=>Mm,combineLatest:()=>If,concat:()=>Q_,concatMap:()=>BT,concatMapTo:()=>$T,count:()=>ET,create:()=>Oe,debounce:()=>DT,debounceTime:()=>wT,defer:()=>Sf,delay:()=>zT,deliver:()=>pe,dispose:()=>_d,elementAt:()=>MT,empty:()=>Ta,every:()=>LT,exhaustMap:()=>WT,exhaustMapTo:()=>GT,filter:()=>Fo,find:()=>OT,findIndex:()=>PT,first:()=>xT,fromAnimationFrame:()=>lT,fromArray:()=>sT,fromEvent:()=>Ne,fromEventPattern:()=>nT,fromFetch:()=>aT,fromIterable:()=>cT,fromPromise:()=>bf,fromReadableStream:()=>uT,fromReader:()=>dT,groupBy:()=>jT,identity:()=>J_,ignoreElements:()=>ST,iif:()=>Z_,inspect:()=>Tf,interval:()=>rm,last:()=>kT,map:()=>Gi,mapTo:()=>VT,max:()=>_T,merge:()=>tm,mergeMap:()=>FT,mergeMapTo:()=>HT,min:()=>TT,never:()=>fT,nothing:()=>Ue,of:()=>oT,pairwise:()=>UT,pipe:()=>ve,race:()=>X_,range:()=>mT,reduce:()=>om,retry:()=>YT,scan:()=>wm,share:()=>di,shareReplay:()=>Y_,skip:()=>AT,skipUntil:()=>bT,skipWhile:()=>Ad,startWith:()=>_a,subject:()=>Ct,subscribe:()=>Ve,sum:()=>IT,switchMap:()=>ji,switchMapTo:()=>Ho,take:()=>yr,takeLast:()=>yT,takeUntil:()=>Qe,takeWhile:()=>Rf,tap:()=>Ia,throttle:()=>vT,throwError:()=>gT,timeInterval:()=>qT,timeout:()=>xm,timer:()=>im,toPromise:()=>XT,toReadableStream:()=>QT,withLatestFrom:()=>eT,zip:()=>K_});function Ue(...i){}var _f=i=>i(),J_=i=>i;function _d(){this.dispose()}var Tf=()=>typeof __FASTRX_DEVTOOLS__!="undefined",z_=1,ir=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(t){let e=new Yl(t,this,this.streamId++);return it.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},Vo=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=Ue,this.error=Ue,this.next=Ue,this.dispose=Ue,this.subscribe=Ue,this.doDefer()}subscribe(t){return t instanceof ir?t.subscribe(this):t(this),this}get bindSubscribe(){return t=>this.subscribe(t)}doDefer(){this.defers.forEach(_f),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}},de=class extends Vo{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)}},Bo=class extends Vo{constructor(t,e=Ue,r=Ue,o=Ue){if(super(),this._next=e,this._error=r,this._complete=o,this.then=Ue,t instanceof ir){let s={toString:()=>"subscribe",id:0,source:t};this.defer(()=>{it.defer(s,0)}),it.create(s),it.pipe(s),this.sourceId=s.id,this.subscribe(t),it.subscribe({id:s.id,end:!0}),e==Ue?this._next=n=>it.next(s,0,n):this.next=n=>{it.next(s,0,n),e(n)},o==Ue?this._complete=()=>it.complete(s,0):this.complete=()=>{this.dispose(),it.complete(s,0),o()},r==Ue?this._error=n=>it.complete(s,0,n):this.error=n=>{this.dispose(),it.complete(s,0,n),r()}}else this.subscribe(t)}next(t){this._next(t)}complete(){this.dispose(),this._complete()}error(t){this.dispose(),this._error(t)}};function ve(i,...t){return t.reduce((e,r)=>r(e),i)}function Oe(i,t,e){if(Tf()){let r=Object.defineProperties(Object.setPrototypeOf(i,ir.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}});it.create(r);for(let o=0;o<e.length;o++){let s=e[o];typeof s=="function"&&s instanceof ir&&it.addSource(r,s)}return r}return i}function pe(i,t){return function(...e){return r=>{if(r instanceof ir){let o=Oe(s=>{let n=new i(s,...e);n.sourceId=o.id,n.subscribe(r)},t,arguments);return o.source=r,it.pipe(o),o}else return o=>r(new i(o,...e))}}}function Wi(i,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:i,payload:t}})}var Yl=class extends de{constructor(t,e,r){super(t),this.source=e,this.id=r,this.sourceId=t.sourceId,this.defer(()=>{it.defer(this.source,this.id)})}next(t){it.next(this.source,this.id,t),this.sink.next(t)}complete(){it.complete(this.source,this.id),this.sink.complete()}error(t){it.complete(this.source,this.id,t),this.sink.error(t)}},it={addSource(i,t){Wi("addSource",{id:i.id,name:i.toString(),source:{id:t.id,name:t.toString()}})},next(i,t,e){Wi("next",{id:i.id,streamId:t,data:e&&e.toString()})},subscribe({id:i,end:t},e){Wi("subscribe",{id:i,end:t,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(i,t,e){Wi("complete",{id:i.id,streamId:t,err:e?e.toString():null})},defer(i,t){Wi("defer",{id:i.id,streamId:t})},pipe(i){Wi("pipe",{name:i.toString(),id:i.id,source:{id:i.source.id,name:i.source.toString()}})},update(i){Wi("update",{id:i.id,name:i.toString()})},create(i){i.id||(i.id=z_++),Wi("create",{name:i.toString(),id:i.id})}},Ea=class extends Error{constructor(t){super(`timeout after ${t}ms`),this.timeout=t}};var Td=class extends Vo{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 di(){return i=>{let t=new Td(i);if(i instanceof ir){let e=Oe(r=>{t.add(r)},"share",arguments);return t.sourceId=e.id,e.source=i,it.pipe(e),e}return Oe(t.add.bind(t),"share",arguments)}}function tm(...i){return Oe(t=>{let e=new de(t),r=i.length;e.complete=()=>{--r===0&&t.complete()},i.forEach(e.bindSubscribe)},"merge",arguments)}function X_(...i){return Oe(t=>{let e=new Map;i.forEach(r=>{let o=new de(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 Q_(...i){return Oe(t=>{let e=0,r=i.length,o=new de(t);o.complete=()=>{e<r&&!o.disposed?(o.doDefer(),o.subscribe(i[e++])):t.complete()},o.complete()},"concat",arguments)}function Y_(i){return t=>{let e=new Td(t),r=[];return e.next=function(o){r.push(o),r.length>i&&r.shift(),this.sinks.forEach(s=>s.next(o))},Oe(o=>{o.defer(()=>e.remove(o)),r.forEach(s=>o.next(s)),e.add(o)},"shareReplay",arguments)}}function Z_(i,t,e){return Oe(r=>i()?t(r):e(r),"iif",arguments)}function If(...i){return Oe(t=>{let e=i.length,r=e,o=e,s=new Array(e),n=()=>{--o===0&&t.complete()},d=(p,m)=>{let E=new de(t);E.next=_=>{--r===0?(E.next=b=>{s[m]=b,t.next(s)},E.next(_)):s[m]=_},E.complete=n,E.subscribe(p)};i.forEach(d)},"combineLatest",arguments)}function K_(...i){return Oe(t=>{let e=i.length,r=e,o=new Array(e),s=()=>{--r===0&&t.complete()},n=(d,p)=>{let m=new de(t),E=[];o[p]=E,m.next=_=>{E.push(_),o.every(b=>b.length)&&t.next(o.map(b=>b.shift()))},m.complete=s,m.subscribe(d)};i.forEach(n)},"zip",arguments)}function _a(...i){return t=>Oe((e,r=0,o=i.length)=>{for(;r<o&&!e.disposed;)e.next(i[r++]);e.disposed||e.subscribe(t)},"startWith",arguments)}var Zl=class extends de{constructor(t,...e){super(t);let r=new de(this.sink);r.next=o=>this.buffer=o,r.complete=Ue,r.subscribe(If(...e))}next(t){this.buffer&&this.sink.next([t,...this.buffer])}},eT=pe(Zl,"withLatestFrom"),Kl=class extends de{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()}},tT=pe(Kl,"bufferCount"),em=class extends de{constructor(t,e){super(t),this.buffer=[];let r=new de(t);r.next=o=>{t.next(this.buffer),this.buffer=[]},r.complete=Ue,r.subscribe(e)}next(t){this.buffer.push(t)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},rT=pe(em,"buffer");var iT=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 d(E){try{m(r.next(E))}catch(_){n(_)}}function p(E){try{m(r.throw(E))}catch(_){n(_)}}function m(E){E.done?s(E.value):o(E.value).then(d,p)}m((r=r.apply(i,t||[])).next())})};function Ct(i){let t=arguments,e=di()(Oe(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=Ue,e.complete=Ue,e.error=Ue,e}function Sf(i){return Oe(t=>t.subscribe(i()),"defer",arguments)}var yf=i=>t=>{setTimeout(()=>i(t))},Af=i=>yf(t=>{for(let e=0;!t.disposed&&e<i.length;e++)t.next(i[e]);t.complete()});function oT(...i){return Oe(Af(i),"of",arguments)}function sT(i){return Oe(Af(i),"fromArray",arguments)}function rm(i){return Oe(t=>{let e=0,r=setInterval(()=>t.next(e++),i);return t.defer(()=>{clearInterval(r)}),"interval"},"interval",arguments)}function im(i,t){return Oe(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 Id(i,t){return e=>{let r=o=>e.next(o);e.defer(()=>t(r)),i(r)}}function nT(i,t){return Oe(Id(i,t),"fromEventPattern",arguments)}function Ne(i,t){if("on"in i&&"off"in i)return Oe(Id(e=>i.on(t,e),e=>i.off(t,e)),"fromEvent",arguments);if("addListener"in i&&"removeListener"in i)return Oe(Id(e=>i.addListener(t,e),e=>i.removeListener(t,e)),"fromEvent",arguments);if("addEventListener"in i)return Oe(Id(e=>i.addEventListener(t,e),e=>i.removeEventListener(t,e)),"fromEvent",arguments);throw"target is not a EventDispachter"}function bf(i){return Oe(t=>{i.then(t.next.bind(t),t.error.bind(t))},"fromPromise",arguments)}function aT(i,t){return Oe(Sf(()=>bf(fetch(i,t))),"fromFetch",arguments)}function cT(i){return Oe(yf(t=>{try{for(let e of i){if(t.disposed)return;t.next(e)}t.complete()}catch(e){t.error(e)}}),"fromIterable",arguments)}function dT(i){let t=e=>iT(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 Oe(e=>{t(e)},"fromReader",arguments)}function uT(i){return Oe(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 lT(){return Oe(i=>{let t=requestAnimationFrame(function e(r){i.disposed||(i.next(r),t=requestAnimationFrame(e))});i.defer(()=>cancelAnimationFrame(t))},"fromAnimationFrame",arguments)}function mT(i,t){return Oe((e,r=i,o=t+i)=>{for(;r<o&&!e.disposed;)e.next(r++);return e.complete(),"range"},"range",arguments)}function pT(i,t,...e){return Oe(r=>{let o=e.concat(s=>(r.next(s),r.complete()));i.apply(t,o)},"bindCallback",arguments)}function hT(i,t,...e){return Oe(r=>{let o=e.concat((s,n)=>s?r.error(s):(r.next(n),r.complete()));i.apply(t,o)},"bindNodeCallback",arguments)}function fT(){return Oe(()=>{},"never",arguments)}function gT(i){return Oe(t=>t.error(i),"throwError",arguments)}function Ta(){return Oe(i=>i.complete(),"empty",arguments)}var $o=class extends de{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)}},om=pe($o,"reduce"),ET=i=>pe($o,"count")((t,e)=>i(e)?t+1:t,0),_T=()=>pe($o,"max")(Math.max),TT=()=>pe($o,"min")(Math.min),IT=()=>pe($o,"sum")((i,t)=>i+t,0);var sm=class extends de{constructor(t,e,r){super(t),this.filter=e,this.thisArg=r}next(t){this.filter.call(this.thisArg,t)&&this.sink.next(t)}},Fo=pe(sm,"filter"),nm=class extends de{next(t){}},ST=pe(nm,"ignoreElements"),am=class extends de{constructor(t,e){super(t),this.count=e}next(t){this.sink.next(t),--this.count===0&&this.complete()}},yr=pe(am,"take"),cm=class extends de{constructor(t,e){super(t);let r=new de(t);r.next=()=>t.complete(),r.complete=_d,r.subscribe(e)}},Qe=pe(cm,"takeUntil"),dm=class extends de{constructor(t,e){super(t),this.f=e}next(t){this.f(t)?this.sink.next(t):this.complete()}},Rf=pe(dm,"takeWhile"),yT=i=>om((t,e)=>(t.push(e),t.length>i&&t.shift(),t),[]),um=class extends de{constructor(t,e){super(t),this.count=e}next(t){--this.count===0&&(this.next=super.next)}},AT=pe(um,"skip"),lm=class extends de{constructor(t,e){super(t),t.next=Ue;let r=new de(t);r.next=()=>{r.dispose(),t.resetNext()},r.complete=_d,r.subscribe(e)}},bT=pe(lm,"skipUntil"),mm=class extends de{constructor(t,e){super(t),this.f=e}next(t){this.f(t)||(this.next=super.next,this.next(t))}},Ad=pe(mm,"skipWhile"),RT={leading:!0,trailing:!1},pm=class extends de{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)}},Sd=class extends de{constructor(t,e,r=RT){super(t),this.durationSelector=e,this.config=r,this._throttle=new pm(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=Ue,this._throttle.complete(),super.complete()}},vT=pe(Sd,"throttle"),CT={leading:!1,trailing:!0},NT=i=>pe(Sd,"audit")(i,CT),hm=class extends de{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},yd=class extends de{constructor(t,e){super(t),this.durationSelector=e,this._debounce=new hm(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()}},DT=pe(yd,"debounce"),wT=i=>pe(yd,"debounceTime")(t=>im(i)),fm=class extends de{constructor(t,e,r){super(t),this.count=e,this.defaultValue=r}next(t){this.count--===0&&(this.defaultValue=t,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()}},MT=pe(fm,"elementAt"),OT=i=>t=>yr(1)(Ad(e=>!i(e))(t)),gm=class extends de{constructor(t,e){super(t),this.f=e,this.i=0}next(t){this.f(t)?(this.sink.next(this.i++),this.complete()):++this.i}},PT=pe(gm,"findIndex"),Em=class extends de{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.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},xT=pe(Em,"first"),_m=class extends de{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()}},kT=pe(_m,"last"),Tm=class extends de{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.complete())}complete(){if(this.result===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.result);super.complete()}},LT=pe(Tm,"every");var Im=class extends de{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))}},wm=pe(Im,"scan"),Sm=class extends de{constructor(){super(...arguments),this.hasLast=!1}next(t){this.hasLast?this.sink.next([this.last,t]):this.hasLast=!0,this.last=t}},UT=pe(Sm,"pairwise"),bd=class extends de{constructor(t,e,r){super(t),this.mapper=e,this.thisArg=r}next(t){super.next(this.mapper.call(this.thisArg,t))}},Gi=pe(bd,"map"),VT=i=>pe(bd,"mapTo")(t=>i),$s=class extends de{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()}},Fs=class extends de{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=this.tryComplete,r.complete=r.tryComplete,r.subscribe(this.makeSource(t,this.index++))}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},Rd=class extends $s{},vd=class extends Fs{next(t){this.subInner(t,Rd),this.next=e=>{this.currentSink.dispose(),this.subInner(e,Rd)}}},ji=pe(vd,"switchMap");function wd(i){return(t,e)=>i(()=>t,e)}var Ho=wd(pe(vd,"switchMapTo")),ym=class extends $s{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},Cd=class extends Fs{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(),ym),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},BT=pe(Cd,"concatMap"),$T=wd(pe(Cd,"concatMapTo")),Am=class extends $s{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},Nd=class extends Fs{constructor(){super(...arguments),this.inners=new Set}next(t){this.subInner(t,Am),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(t=>t.resetComplete()):this.dispose()}},FT=pe(Nd,"mergeMap"),HT=wd(pe(Nd,"mergeMapTo")),bm=class extends $s{dispose(){this.context.resetNext(),super.dispose()}},Dd=class extends Fs{next(t){this.next=Ue,this.subInner(t,bm)}},WT=pe(Dd,"exhaustMap"),GT=wd(pe(Dd,"exhaustMapTo")),Rm=class extends de{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=Ct(),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)}},jT=pe(Rm,"groupBy"),vm=class extends de{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}},qT=pe(vm,"timeInterval"),Cm=class extends de{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()}},JT=pe(Cm,"bufferTime"),Nm=class extends de{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)}},zT=pe(Nm,"delay"),Dm=class extends de{constructor(t,e){super(t),this.selector=e}error(t){this.dispose(),this.selector(t)(this.sink)}},Mm=pe(Dm,"catchError");var XT=()=>i=>new Promise((t,e)=>{let r;new Bo(i,o=>r=o,e,()=>t(r))}),QT=()=>i=>{let t;return new ReadableStream({start(e){t=new Bo(i,e.enqueue.bind(e),e.error.bind(e),e.close.bind(e))},cancel(){t.dispose()}})},Ve=(i=Ue,t=Ue,e=Ue)=>r=>new Bo(r,i,t,e),Om=class extends de{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)}))}},Ia=pe(Om,"tap"),Pm=class extends de{constructor(t,e){super(t),this.timeout=e,this.id=setTimeout(()=>this.error(new Ea(this.timeout)),this.timeout)}next(t){super.next(t),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},xm=pe(Pm,"timeout"),YT=(i=1/0)=>t=>{if(t instanceof ir){let e=Oe(r=>{let o=i,s=new de(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,it.pipe(e),e}else return e=>{let r=i,o=new de(e);o.error=s=>{r-- >0?t(o):e.error(s)},t(o)}};var ui=class ui extends Oo{constructor(e,r,o){super({userId:r.userId,sdkAppId:e.sdkAppId,mediaType:o,room:e});this.room=e;this.user=r;u(this,"tinyId");u(this,"isRemote",!0);u(this,"jitterBufferDelay",0);u(this,"availableState");u(this,"remotePublishState");u(this,"_decodeCheckTimeoutId",-1);this.tinyId=r.tinyId,this.availableState=new ne(`${r.userId}-${this.mediaType}-available`,"remote-track-available"),this.remotePublishState=new ne(`${r.userId}-${this.mediaType}-remote-publish`,"remote-track-publish"),ve(tm(Ne(this,ne.STATECHANGED),Ne(this.remotePublishState,ne.STATECHANGED)),Gi(()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing)),Ve(s=>{this.availableState.state!==(s?ne.ON:ne.OFF)&&(this.availableState.state=s?ne.ON:ne.OFF),this.updatePlayingState(s)}))}setMute(e){this.isRemotePublished&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.isRemotePublished&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}waitHasMediaTrack(){return new Promise(e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)})}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===ui.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===ne.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){let o=this.kind===D.AUDIO;Y[e?"addSuccessEvent":"addFailedEvent"]({key:o?504700:514702}),e||(Y.addEnum({key:o?504701:514703,value:zn()}),$e.uploadEvent({log:`stat-decode-failed-${this.kind}-${Jn()||So()}`,userId:this.room.userId}),this._log.warn(`decode failed: isPlaying: ${this.player.isPlaying} ${this.kind===D.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?ne.ON:ne.OFF}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};u(ui,"STATE_SUBSCRIBE","subscribe"),X([Ef(5,1)],ui.prototype,"waitHasMediaTrack",1),X([qe(ne.INIT,ui.STATE_SUBSCRIBE,{success(){var r,o;this.log.info("subscribed"),H.emit(L.REMOTE_TRACK_SUBSCRIBED,{track:this}),!((((o=(r=this.room)==null?void 0:r.networkQuality)==null?void 0:o.downlinkNetworkQuality)||0)>3||this.player.isInAutoPlayFailedState)&&(this._decodeCheckTimeoutId=setTimeout(()=>{var n,d;if(!((((d=(n=this.room)==null?void 0:n.networkQuality)==null?void 0:d.downlinkNetworkQuality)||0)>3||this.player.isInAutoPlayFailedState)&&this.isSubscribed&&this.isPlayCalled&&this.stat.bytesReceived>0){let p=this.kind===D.AUDIO,m=this.player.isPlaying||(p?this.getAudioLevel()>0:this.stat.framesDecoded>0);this.reportDecodeResult(m)}},5e3),this.player.once(Xe.ERROR,s=>{s.code===MediaError.MEDIA_ERR_DECODE&&(clearTimeout(this._decodeCheckTimeoutId),this.reportDecodeResult(!1,3))}))},ignoreError:!0}),fd(521716,!1)],ui.prototype,"subscribe",1),X([qe(ui.STATE_SUBSCRIBE,ne.INIT,{sync:!0,success(){this.log.info("unsubscribed"),H.emit(L.REMOTE_TRACK_UNSUBSCRIBED,{track:this}),clearTimeout(this._decodeCheckTimeoutId)}})],ui.prototype,"unsubscribe",1);var Hs=ui;var Uo=class extends Hs{constructor(e,r){super(e,r,1);u(this,"volume",0);u(this,"mediaType",1);u(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.audioManager}get dbVolume(){return ad.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}decodeFrame(e){if(!this.manager)return e;let r=e;for(let o of this.manager.decodePipeline)if(o&&(r=o({frame:r,track:this}),!r))return;return r}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get isRemotePublished(){return this.user.muteState.audioAvailable}};var KT=[-1,-1,1,-1,-1,1,1,1],eI=[0,0,1,0,0,1,1,1];var Ft=class extends ne{constructor(e,r){super();this.context=e;u(this,"name");u(this,"input");u(this,"output");u(this,"texture");u(this,"ctx2d",null);u(this,"fbo");u(this,"width",0);u(this,"height",0);u(this,"x",0);u(this,"y",0);u(this,"program");u(this,"vertexShader");u(this,"fragmentShader");u(this,"totalFrames",0);u(this,"dropFrames",0);u(this,"matchInputSize",!0);u(this,"texCoordBuffer");u(this,"positionBuffer");u(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0});u(this,"cost",0);u(this,"_canvas",null);u(this,"_image");u(this,"log");if(this.context.on("disconnect",this.close,this),this.name=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 kt){e.ctx&&r.create2d&&(typeof OffscreenCanvas=="function"&&Qt!==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(eI),this.positionBuffer=this.createBuffer(KT),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.PACK_ALIGNMENT,1),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 he({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 yt&&this.render(e)||this.context instanceof kt&&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 yt){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){return this.ctx2d&&e?(e instanceof ImageData?this.ctx2d.putImageData(e,r,o):(this.ctx2d.drawImage(e,r,o,s,n),typeof VideoFrame!="undefined"&&e instanceof VideoFrame&&e.close()),!0):!1}getInfo(){var _;let{totalFrames:e,x:r,y:o,width:s,height:n,name:d,cost:p}=this,m=Date.now(),E=(e-this.lastInfo.totalFrames)/((m-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:r,y:o,width:s,height:n,timestamp:m,fps:E,name:d,cost:p},Z({parent:(_=this.input)==null?void 0:_.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.PACK_ALIGNMENT,1),r.pixelStorei(r.UNPACK_ALIGNMENT,1),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,r.RGBA,r.UNSIGNED_BYTE,e),o}};X([qe(ne.INIT,"connected",{sync:!0})],Ft.prototype,"connect",1),X([qe("connected",ne.INIT,{ignoreError:!0,sync:!0})],Ft.prototype,"disconnect",1),X([qe([],"closed",{sync:!0})],Ft.prototype,"close",1);var Cf=ve(rm(250),Gi(()=>performance.now()),di()),Nf=i=>t=>{let e=0,r=performance.now();ve(Cf,Gi(o=>(o-r)/i>>0),Fo(o=>o!=e?(e=o,!0):!1))(t)},Md=i=>t=>{let e=performance.now();ve(Cf,Ad(r=>r-e<i),yr(1))(t)};var rI=[0,1,1,1,0,0,1,0],Wo=class extends Ft{constructor(e,r){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},r));u(this,"_intervalId",0);u(this,"_sequence",0);u(this,"checkGLError",!1);u(this,"checkVisibilityChange");e instanceof kt?this.ctx2d=e.ctx||null:e.available&&(r!=null&&r.mirrorUpAndDown)&&this.setTexBuffer(rI)}start(e){this.log.info(`${this.name} start render ${e} fps`),St.clearTask(this._intervalId),this._intervalId=St.run("intervalInWorker",()=>{if(e!==this.context.frameRate&&(St.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof yt){let o=this.context.ctx.getError();o&&this.context.destroy(new he({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(),!0):!1}addInput(e,...r){super.addInput(e,...r),this.start(this.context.frameRate)}update(e=0){if(this._intervalId&&(St.clearTask(this._intervalId),this._intervalId=0,e===1)){this.log.info(`${this.name} use requestVideoFrameCallback`);let r=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info(`${this.name} use timer`),document.removeEventListener("visibilitychange",r))};document.addEventListener("visibilitychange",r)}this.requestFrame(this._sequence++)}removeInput(e){super.removeInput(e),St.clearTask(this._intervalId)}resize(e,r){super.resize(e,r),this.context.setSize(e,r)}close(){super.close(),St.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},Ws=class extends Wo{constructor(e,r){super(e,r);u(this,"_videoTrack");u(this,"_muteOb");u(this,"_closedOb",Ne(this,"closed"));u(this,"_subscription");u(this,"_canvasContainer");Number(ki)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e._canvas.captureStream().getVideoTracks(),this._muteOb=Ne(this._videoTrack,"mute"),ve(Ne(this._videoTrack,"ended"),Qe(this._closedOb),Ve(()=>{this.context.destroy(new he({code:te.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){this._subscription=ve(this._muteOb,Qe(this._closedOb),Ho(Md(5e3)),Ve(()=>{var e;(e=this._videoTrack)!=null&&e.muted&&this.context.destroy(new he({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()}},Od=class extends Ws{render(t){var e;return!!((e=this.input)!=null&&e.requestFrame(t))}};var Pd=class extends Ws{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 Sa=class extends Ft{constructor(e,r){super(e,Z({name:"imageSource"},r));u(this,"_lastImage");u(this,"_totalFrames",0);u(this,"_autoResize",!1);u(this,"_canvasRendered");u(this,"_videoCallbackId",0);this._autoResize=(r==null?void 0:r.autoResize)!==!1,Qt===16&&(this._canvasRendered=Ct(),ve(this._canvasRendered,_a(this._image),ji(o=>o instanceof HTMLCanvasElement?Ne(o,"rendered"):Ta()),Qe(Ne(this,"closed")),Ve(()=>{this.update()})))}tryVideoFrameCallback(e){this._videoCallbackId&&e.cancelVideoFrameCallback(this._videoCallbackId),Do()&&!document.hidden&&(this._videoCallbackId=e.requestVideoFrameCallback((r,o)=>{document.hidden||(this._totalFrames=o.presentedFrames,this.update(1))}))}_render(e,r){var d;let{width:o,height:s}=this,{image:n}=this;if(n instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(n),{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!1}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,(d=this._lastImage)==null||d.close(),this._lastImage=n);if(!this._autoResize)return!0;if(this.width===o&&this.height===s&&this.totalFrames){if(r){this.useTexture();let p=this.context.ctx;p.texSubImage2D(p.TEXTURE_2D,0,0,0,p.RGBA,p.UNSIGNED_BYTE,n)}}else{if(r){this.useTexture();let p=this.context.ctx;p.texImage2D(p.TEXTURE_2D,0,p.RGBA,p.RGBA,p.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)}},ya=class extends Sa{constructor(e,r,o){super(e,o);this._player=r;this.name="videoPlayerSource",ve(Ne(this._player,Xe.PLAYER_STATE_CHANGED),Qe(Ne(this,"closed")),Fo(({state:s})=>s==="PLAYING"),Ve(()=>{this.tryVideoFrameCallback(this._player.element)}))}get image(){return this._player.element}},li=class extends ya{constructor(t,e,r){super(t,new Yt({id:r.name,track:e,muted:!0,container:null,objectFit:"contain",log:r.logger}),r),this.name="videoTrackSource",this._player.play()}replaceTrack(t){this._player.setTrack(t),this._player.play()}close(){super.close(),this._player.stop()}};var oI=`
|
|
31
|
+
`,r.onclick=this.onQuestionClick.bind(this);let o=document.createElement("div");o.className=$l,o.innerText=`${fr()?"\u8BE6\u60C5 >":"Detail >"}`,o.onclick=this.onCollapseClick.bind(this);let s=t.content.firstChild,n=s.querySelector(`.${ed}`);return n.appendChild(o),n.appendChild(r),n.appendChild(e),s}addDiaLog(){Wl()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${Ls}`).onclick=t=>t.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",$.info("show autoplay dialog"),Be.uploadEvent({log:P_}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){$.warn("confirm clicked, try resume stream"),H.emit(L.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let t=this._dialogNode.querySelector(`.${Wh}`);t.style.visibility=`${this._showDetail?"hidden":"visible"}`,t.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||Be.uploadEvent({log:k_}),this._isCollapseClicked=!0}onQuestionClick(){window.open(Jh,"_blank"),this._isQuestionClicked||Be.uploadEvent({log:L_}),this._isQuestionClicked=!0}},zh=Bl;var Zt=class extends $r{constructor(e){super(e,D.VIDEO);u(this,"stat",{});u(this,"_calculateTimeout",-1);u(this,"viewMirror",!1);u(this,"objectFit");u(this,"container");u(this,"canvas");u(this,"canvasTrack");this.mode=e.canvas?1:0,this.container=e.container,this.canvas=e.canvas,V(e.viewMirror)||(this.viewMirror=e.viewMirror),V(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}initializeElement(){var r;let e=document.createElement(D.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,(r=this.container)==null||r.appendChild(this.elementToRender),this.bindElementEvents(),this.calculateStat()}get styleAttribute(){let e=`width: 100%; height: 100%; object-fit: ${this.objectFit};background-color: black;`;return this.viewMirror&&(e+="transform: scaleX(-1);"),e}setContainer(e){var r;this.container=e,(this.track||this.canvasTrack)&&this.elementToRender&&((r=this.container)==null||r.appendChild(this.elementToRender))}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),e&&e.add(D.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(D.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent)}handleTrackEvent(e){var r;super.handleTrackEvent(e),e.type===D.MUTE&&((r=this.stat)!=null&&r.fps)&&(this.stat.fps=0)}handleElementEvent(e){var o;if(this.mode===2)return;super.handleElementEvent(e);let r=e.type;if(r===D.PAUSE&&(this.container&&document.getElementById(this.container.id)||this._log.warn(`${this.kind} player has been remove, element ID: ${(o=this.container)==null?void 0:o.id}`),this._pausedRetryCount>0&&!Wl()&&(this._log.info(`${this.kind} player auto resume when paused`),this.resume(),this._pausedRetryCount--),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){let s=this.element.style.transform;r===D.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=s.replace("scaleX(-1)",""):r===D.LEAVE_PICTURE_IN_PICTURE&&!s.includes("scaleX")&&(this.element.style.transform=`${s} scaleX(-1)`)}}setCanvas(e,r=1){var o,s,n,d;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&&((d=this.container)==null||d.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(Qe.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(Oo()&&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 d;return(d=this.element)==null?void 0:d.requestVideoFrameCallback(o)},2e3))};this.element.requestVideoFrameCallback(o)}}catch(e){this._log.warn("init stat failed",e)}}};function Po(i,t){return y(this,null,function*(){if(!i.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield i.audioWorklet.addModule(t),$.info("worklet addModule success")}catch(e){throw $.info(`worklet addModule catch error. ${e.message}`),e}})}var la;typeof AudioContext!="undefined"?la=AudioContext:typeof webkitAudioContext!="undefined"?la=webkitAudioContext:typeof mozAudioContext!="undefined"&&(la=mozAudioContext);var Ir,Xh=-1;Qh();function Qh(){try{if(Ir)return;Ir=new la({sampleRate:48e3}),Ir.onstatechange=()=>{$.info(`context state: ${Ir.state}${Ir.state!=="running"?` visibilityState: ${document.visibilityState}`:""}`),Us()},clearTimeout(Xh)}catch(i){$.error(`initAudioContext failed: ${i} typeof AudioContextClass: ${typeof la}`),Xh=setTimeout(Qh,1e3)}}var Us=()=>{Ir.state==="suspended"?(Vs(),document.addEventListener("click",Us)):Ir.state==="interrupted"?Vs():(document.removeEventListener("visibilitychange",Us),document.removeEventListener("click",Us))},Gl=0,jl=-1;function Vs(){return new Promise((i,t)=>{if(Ir.state==="running")return i();Date.now()-Gl<1e3?(clearTimeout(jl),jl=setTimeout(()=>{Gl=Date.now(),Ir.resume().then(i,t)},1e3)):(clearTimeout(jl),Gl=Date.now(),Ir.resume().then(i,t))}).catch(i=>{$.warn(`context resume failed: ${i}`),document.addEventListener("visibilitychange",Us)})}document.addEventListener("click",Us);var et=i=>Ir;var Pt=class{constructor(){u(this,"node");u(this,"node2");u(this,"pre",new Set);u(this,"next",new Set);u(this,"context");u(this,"connectedNodes",new Set)}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.preNodeReconnect(),this.reconnect()}catch(r){$.error(r)}}setNode(t,e){var r;if(!this.node)try{(r=this.context)==null||r.addMixWeight(),this.node=t,e&&(this.node2=e),this.preNodeReconnect(),this.reconnect(),Y.addSuccessEvent({key:502701})}catch(o){$.error(o),Y.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(),Y.addSuccessEvent({key:502702})}catch(e){$.error(e),Y.addFailedEvent({key:502702,error:e})}}preNodeReconnect(){this.pre.forEach(t=>{t.node?t.reconnect():t.preNodeReconnect()})}connectNext(t){this.next.forEach(e=>{t._connect(e.node)||e.connectNext(t)})}_connect(t){return!this.node||!t?!1:((this.node2||this.node).connect(t),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){return t.forEach(e=>{this.next.add(e),e.pre.add(this)}),this}},rd=class extends Pt{constructor(e=256){super();this.fftSize=e;u(this,"dataArray",new Uint8Array(0))}setNode(e){e.fftSize=this.fftSize,this.dataArray=new Uint8Array(e.frequencyBinCount),super.setNode(e)}getByteTimeDomainData(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),this.dataArray}get level(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),Math.max(...this.dataArray)/128-1}get timeDomainPathData(){let e=this.getByteTimeDomainData(),r=1,o=0,s=0,n=`M${o},${s}`;for(let d=0;d<e.length;d++)s=e[d]/128*100/2,n+=`L${o},${s}`,o+=r;return n}},ma=class{constructor(){u(this,"source",new Pt);u(this,"gain",new Pt);u(this,"destination",new Pt)}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(et().createGain()),this.gain.node.gain.value=t}replaceSource(t){this.source.replaceNode(ql(t))}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}},Fs=class extends ma{constructor(e){super();this.context=e;u(this,"denoiser",new Pt);u(this,"voiceChanger",new Pt);this.source.pipeTo(this.denoiser.pipeTo(this.voiceChanger.pipeTo(this.gain.pipeTo(this.destination))))}connect(){this.context.inputs.has(this)||(this.destination.setNode(this.context.destination),this.source.setContext(this.context),this.denoiser.setContext(this.context),this.voiceChanger.setContext(this.context),this.gain.setContext(this.context),this.context.inputs.add(this))}disconnect(){this.context.inputs.has(this)&&(this.destination.deleteNode(),this.source.removeContext(),this.denoiser.removeContext(),this.voiceChanger.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.denoiser.deleteNode(),this.voiceChanger.deleteNode(),this.source.deleteNode(),this.disconnect()}setVolume(e){if(e===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(this.context.audioContext.createGain()),this.gain.node.gain.value=e}},id=class{constructor(){u(this,"audioContext",et("audio-mixer"));u(this,"destination",this.audioContext.createMediaStreamDestination());u(this,"inputs",new Set);u(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]}},Yh=new WeakMap;function ql(i){let t=Yh.get(i);if(t)return t;let e=et();if(i instanceof HTMLAudioElement)t=e.createMediaElementSource(i);else if(i instanceof MediaStreamTrack)t=e.createMediaStreamSource(new MediaStream([i]));else return i;return Yh.set(i,t),t}var Kt=class Kt{constructor(t){u(this,"_volume",0);u(this,"_volumeDb",0);u(this,"_log");u(this,"_scriptProcessorNode",null);u(this,"_audioWorkletNode",null);u(this,"_interval",200);u(this,"ready",this.preload());let{log:e}=t;this._log=e,H.on(L.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-Kt.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!Kt.workletReady){let 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);';Kt.workletReady=Po(Kt.audioContext,URL.createObjectURL(new Blob([t],{type:"application/javascript"})))}return Kt.workletReady.then(()=>this.initAudioWorklet()).catch(t=>(this._log.error(`volumeMeter preload error: ${t}`),this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(Kt.audioContext,"volume-meter");let t=!1;this._audioWorkletNode.port.onmessage=e=>{Kt.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}`),Be.logFailedEvent({userId:this._log.userId,eventType:Xr.LOAD_WORKLET,error:t}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=et("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=t=>{Kt.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,H.off(L.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})}};u(Kt,"lastMessageTime",0),u(Kt,"audioContext",et("volume-meter")),u(Kt,"workletReady");var od=Kt,sd=class extends Pt{constructor(e){super();u(this,"_volumeMeter");this._volumeMeter=new od(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return y(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()}}},nd=od;var tf=Mi($i(),1);var Kh=i=>t=>t.deviceId===i;var pa=class{constructor(t,e="Input"){u(this,"kind");u(this,"type");u(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&&$s(this.devices[0])){this.devices=r;return}e&&(r.forEach(o=>{if(o.deviceId&&!this.devices.find(Kh(o.deviceId))){let s=`${this.kind}${this.type}Added`;$.warn(`${s}: ${JSON.stringify(o)}`),e.emit(s,o)}}),this.devices.forEach(o=>{if(o.deviceId&&!r.find(Kh(o.deviceId))){let s=`${this.kind}${this.type}Removed`;$.warn(`${s}: ${JSON.stringify(o)}`),e.emit(s,o)}})),this.devices=r}hasDevice(t){return!!this.devices.find(e=>e.deviceId===t)}},Jl=class extends tf.EventEmitter{constructor(){super();u(this,"audioInputs",new pa(D.AUDIO));u(this,"videoInputs",new pa(D.VIDEO));u(this,"audioOutputs",new pa(D.AUDIO,"Output"));this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||At.run("interval",()=>{this.update()},{delay:1e4}))}init(){ad().then(e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)})}update(){return y(this,arguments,function*(e=0){let r=yield ad(e);return this.audioInputs.update(r,this),this.videoInputs.update(r,this),this.audioOutputs.update(r,this),this})}},Tt=In||us?null:new Jl;function $s(i){return i.deviceId===i.groupId&&i.groupId===""}function ad(){return y(this,arguments,function*(i=0){if(ai()||!Yc())return[];let t=yield navigator.mediaDevices.enumerateDevices();if(i!==0){let e={audio:!1,video:!1};if(t.forEach(r=>{$s(r)&&(r.kind===D.AUDIO_INPUT?e.audio=!0:r.kind===D.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&&Vs()}catch(o){$.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&&zl.add(`${e.deviceId}_${e.kind}`),e.getCapabilities&&(o.getCapabilities=()=>e.getCapabilities()),o})})}function Jt(i=!1){return Tt.update(i?1:0).then(t=>t.audioInputs.devices)}function er(i=!1){return Tt.update(i?2:0).then(t=>t.videoInputs.devices)}var ef=!1;function rf(){return y(this,null,function*(){try{ef||(ef=!0,$.info(`speakers:${(yield Wi()).map(i=>` ${i.deviceId.slice(0,8)}: ${i.label}`)}`))}catch(i){}})}function Wi(i=!1){return y(this,null,function*(){return(lt||Mt)&&(i=!1),Tt.update(i?1:0).then(t=>t.audioOutputs.devices)})}var zl=new Set;function of(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}_${D.VIDEO_INPUT}`;return!!zl.has(r)}function sf(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}_${D.AUDIO_INPUT}`;return!!zl.has(r)}function Xl(i,t){return y(this,null,function*(){let r=(yield Jt()).find(o=>o.deviceId===Io);return!t&&(r==null?void 0:r.groupId)===i||(r==null?void 0:r.groupId)===i&&r.label===t})}function nf(s){return y(this,arguments,function*({newDeviceId:i,oldDeviceId:t,oldGroupId:e,oldLabel:r,kind:o}){return i!==t?!1:o===D.AUDIO&&i===Io?yield Xl(e,r):!0})}var cd,Ql=class extends ma{constructor(e){super();this.log=e;u(this,"volumeMeter");u(this,"volumeDestination");u(this,"analyser",new rd);this.volumeMeter=new sd({log:this.log}),this.volumeDestination=new Pt,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},dd=class i extends $r{constructor(e){super(e,D.AUDIO);u(this,"_outputDeviceId");u(this,"_volume",1);u(this,"_destination",et("player").createMediaStreamDestination());u(this,"pipeline");u(this,"volumeMeterMode","worklet");this.mode=0,this.pipeline=new Ql(this._log)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(e){if((Fi==="15.2"||Fi==="15.3"||Fi==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}let o=cd||new Audio;o.setAttribute("autoplay","autoplay"),o.srcObject=this.getMediaStream(),o.muted=this.muted,this.element=o,je(e)&&(this.element.volume=Math.min(Math.max(e,0),1)),o===cd&&(cd=void 0),this.bindElementEvents()}play(e){return y(this,null,function*(){if(this.track)return this.pipeline.source.node||this.pipeline.replaceSource(this.track),this.element||this.initializeElement(e==null?void 0:e.volume),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),this.volumeMeterMode==="worklet"?this.pipeline.volumeMeter.init():this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(et("player").createAnalyser()),rf(),Ft(i.prototype,this,"play").call(this)})}stop(e=0){this.pipeline.destroy(),super.stop(e)}setSinkId(e){return y(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()}},ud=class extends dd{setTrack(t){this.track!==t&&(this.unbindTrackEvents(),this.track=t,this.emit(Qe.MEDIA_TRACK_CHANGED,t),t&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([t]))))}setVolume(t){this._volume=t,this.element&&(this.element.volume=t)}},ld=class extends dd{constructor(e){super(e);u(this,"_sourceElement");u(this,"_output",new Pt);this.pipeline.source.pipeTo(this.pipeline.gain.pipeTo(this.pipeline.volumeMeter.pipeTo(this._output),this.pipeline.destination))}setOutput(){this.mode=1,this._output.setNode(et("player").destination)}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var r,o;((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(Qe.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.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){this._volume=e,this.useDestination?(this.pipeline.setVolume(e),this._log.info(`set pipeline volume: ${e}`)):e<=1?this.element?(this._log.info(`set element volume: ${e}`),this.element.volume=e):this._log.info("set element volume: no element"):lt||(this._log.info(`start set pipeline volume: ${e}`),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),mt(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&&Ui&&(cd=r),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}};var ko=class extends ne{constructor({userId:e,sdkAppId:r,mediaType:o,room:s,PlayerClass:n=o===1?ld:Zt}){var d;super();u(this,"id",Xn());u(this,"userId","");u(this,"isRemote");u(this,"mediaType");u(this,"room");u(this,"user");u(this,"_log");u(this,"_inputTrack");u(this,"_outputTrack");u(this,"isPlayCalled");u(this,"container",null);u(this,"player");u(this,"subVideoPlayerMap");u(this,"muted",!1);u(this,"abortCtrl");u(this,"objectFit","cover");u(this,"mirror");u(this,"isScreen",!1);u(this,"manager");u(this,"trackSettings");u(this,"isFirstVideoFrameEmitted",!1);this.userId=e||"",this.mediaType=o,this._log=$.createLogger({id:`${this.kind[0]}t`,userId:(d=s||this.room)==null?void 0:d.userId,remoteUserId:this instanceof di?void 0:this.userId,sdkAppId:r,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof di}),this.player=new n({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log}),this.player.on(Qe.PLAYER_STATE_CHANGED,p=>{H.emit(L.PLAYER_STATE_CHANGED,ee({track:this},p)),this.emit("player-state-changed",p)}),this.kind===D.VIDEO&&(this.player.on(Qe.LOADED_DATA,()=>{this.emitFirstVideoFrameEvent(Qe.LOADED_DATA),H.emit(L.VIDEO_LOADED_DATA,{track:this})}),this.player.on(Qe.LOADED_META_DATA,()=>{this.emitFirstVideoFrameEvent(Qe.LOADED_META_DATA)}),this.player.on(Qe.MEDIA_TRACK_CHANGED,p=>{var m;(m=this.subVideoPlayerMap)==null||m.forEach(g=>g.setTrack(p))})),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(Qe.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||$}get kind(){return this.mediaType===1?D.AUDIO:D.VIDEO}get strMediaType(){return this.mediaType===4?D.VIDEO:this.mediaType===2?D.SCREEN:D.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 y(this,null,function*(){let o=st(e)?e[0]:e;if(this.isPlayCalled){this.log.info(`play update options: ${JSON.stringify(r)}`),r&&!V(r.muted)&&this.setPlayerMute(r.muted),r&&!V(r.objectFit)&&(this.objectFit=r.objectFit),this.player instanceof Zt&&(this.player.setObjectFit(this.objectFit),this.container!==o&&o&&(this.container=o,this.player.setContainer(o)),st(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),r)));return}if(r&&!V(r.muted)?this.setPlayerMute(r.muted):(!this.isRemote||this.kind===D.VIDEO)&&this.setPlayerMute(!0),r&&!V(r.objectFit)&&(this.objectFit=r.objectFit),this.player instanceof Zt&&(this.player.setObjectFit(this.objectFit),r&&!V(r.poster)&&this.player.setPoster(r.poster)),this.isPlayCalled=!0,o&&(this.container=o,this.player instanceof Zt&&this.player.setContainer(o)),H.emit(L.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),st(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!==D.VIDEO||V(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),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 y(this,null,function*(){if(!this._outputTrack||this.kind===D.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((s,n)=>{var d;e.find(p=>n===p)||(s.stop(),(d=this.subVideoPlayerMap)==null||d.delete(n))});for(let[s,n]of e.entries()){let d=this.subVideoPlayerMap.get(n);d?r&&(V(r.objectFit)||d.setObjectFit(r.objectFit)):this.subVideoPlayerMap.set(n,new Zt({id:this.userId||this.id,track:this.playerMediaTrack,container:n,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:`vp-sub${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(Gu(this)&&!e?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(r=>{r.stop()}),this.container=null)}resume(){return y(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),H.emit(e?L.TRACK_MUTED:L.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){xt(e,e).add(D.MUTE,this.onTrackMuted).add(D.UNMUTE,this.onTrackUnmuted).add(D.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===D.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){mt(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(Gu(this)?this.jitterBufferDelay:0),this.log.info(`playing state updated, stop ${this.kind}`);return}}this.log.debug(`updatePlayingState abort ${this.isPlayCalled} ${e} ${this.player.isStopped}`)}handleAutoPlayFailed(e){if(this.room&&this.room.enableAutoPlayDialog)new zh;else{let r=()=>{this.resume().then(()=>{document.removeEventListener("click",r,!0)})};document.addEventListener("click",r,!0)}this.emit("error",e)}getVideoFrame(){return this.player instanceof Zt?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(e){var n,d,p;if(this.isFirstVideoFrameEmitted)return;let r=(n=this.mediaTrack)==null?void 0:n.getSettings(),o=(r==null?void 0:r.width)||((d=this.player.element)==null?void 0:d.videoWidth)||0,s=(r==null?void 0:r.height)||((p=this.player.element)==null?void 0:p.videoHeight)||0;e===Qe.LOADED_META_DATA&&!o&&!s||(e===Qe.LOADED_DATA&&!o&&!s&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,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`)}};X([qe([],ne.INIT,{sync:!0})],ko.prototype,"close",1);var V_=Object.prototype.hasOwnProperty,{toString:xR}=Object.prototype;function F_(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(Gt(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(V_.call(i,t))return!1;return!0}}return!1}var ha=F_;var $_=function(i){return y(this,null,function*(){let t=H_(i);$.info(`getUserMedia with constraints: ${JSON.stringify(t)}`);let e=[],r=[],o=["label","deviceId","groupId"];t.audio&&(e=yield Jt(),$.info(`microphones: ${ir(e.map(s=>Ee(ee({},s),{groupId:s.groupId.substring(0,8)})),{keysToInclude:o})}`)),t.video&&(r=yield er(),$.info(`cameras: ${ir(r,{keysToInclude:o})}`));try{let s=yield navigator.mediaDevices.getUserMedia(t);return Ml&&s.getTracks().forEach(n=>{$.info(`${n.kind} capabilities: ${ir(n.getCapabilities(),{keysToInclude:hc})}`)}),t.audio&&Vs(),s}catch(s){let{message:n}=s;throw s.name==="NotFoundError"&&(i.video&&r&&r.length===0&&(n=dt({key:ct.CAMERA_NOT_FOUND})),i.audio&&e&&e.length===0&&(n=dt({key:ct.MICROPHONE_NOT_FOUND}))),new he({code:te.INITIALIZE_FAILED,name:s.name,message:n,constraint:s.constraint})}})},B_=ki({retryFunction:$_,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"?(s===1?(r[0].video&&(r[0].maxResolution=!1,(!Mt||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&&af(r[0].microphoneId,!1),r[0].cameraId&&af(r[0].cameraId,!0)},onRetrying:i=>{$.warn(`getUserMedia NotReadableError observed, retrying [${i}/3]`)},onRetryFailed:i=>{Be.logFailedEvent({eventType:Xr.GET_USER_MEDIA_RETRY,error:i})},onRetrySuccess:i=>{Be.logSuccessEvent({eventType:Xr.GET_USER_MEDIA_RETRY}),Be.uploadEvent({log:`stat-${Xr.GET_USER_MEDIA_RETRY}-success-${i}`})}});function af(i,t){return y(this,null,function*(){let r=(t?yield er():yield Jt()).find(o=>o.deviceId===i);r&&Xe(r.getCapabilities)&&$.warn(ir(r.getCapabilities(),{keysToInclude:hc}))})}function H_(i){return{audio:W_(i),video:G_(i)}}function W_(i){if(!i.audio)return!1;if(i.useTrueAsConstraint)return!0;let t={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:i.sampleRate};return!ha(i.microphoneId)&&(t.deviceId=i.useExactDeviceId?{exact:i.microphoneId}:i.microphoneId,i.useDeviceIdOnly)?t:(je(i.channelCount)&&(t.channelCount=i.channelCount),nt(i.echoCancellation)&&!i.echoCancellation&&(t.echoCancellation=!1),nt(i.noiseSuppression)&&!i.noiseSuppression&&(t.noiseSuppression=!1),nt(i.autoGainControl)&&!i.autoGainControl&&(t.autoGainControl=!1),ha(t)?!0:t)}function G_(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&&!ha(e)?e:(i.width&&(e.width={ideal:i.width},t&&!Qt&&(e.width.max=i.width)),i.height&&(e.height={ideal:i.height},t&&!Qt&&(e.height.max=i.height)),Qt&&_r&&i.width&&i.height&&i.width*i.height<352*288&&(e.width=i.width,e.height=i.height),i.frameRate&&(e.frameRate=i.frameRate),ha(e)?!0:e)}var cf=B_;function Gi(i){return Me((t,e)=>function(...r){return y(this,null,function*(){let o=yield t.apply(this,r);return yield i.call(this,...r),o})})}function df(i){return Me((t,e)=>function(...r){return y(this,null,function*(){try{return yield t.apply(this,r)}catch(o){i.call(this,o)}})})}function Me(i){return function(t,e,r){return r.value=i(r.value,e),r}}var uf=(()=>{let i=!1,t=document.visibilityState;return()=>{document.visibilityState!==t&&$.info(`visibility change: ${document.visibilityState}`),!i&&(document.addEventListener("visibilitychange",()=>{$.info(`visibility change: ${document.visibilityState}`),t=document.visibilityState}),i=!0)}})();var j_=0,md=class{constructor(){u(this,"log",$.createLogger({id:`fq${++j_}`}));u(this,"isRunning",!1);u(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=ee({},t),o=new Promise((d,p)=>{r.resolve=d,r.reject=p});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()})}},lf=new WeakMap,mf=new WeakMap;function pf(i=!1){return function(t,e,r){let o=r.value;return r.value=function(...s){let n=lf.get(this)||new md;return lf.set(this,n),n.push({fn:o,args:s,context:this},i)},r}}function pd(i){return function(t,e,r){let o=r.value,s=n=>i(...n);return r.value=function(...n){let d=mf.get(this)||new Map,p=d.get(s(n))||new md;return d.set(s(n),p),mf.set(this,d),p.push({fn:o,args:n,context:this})},r}}function hd(i,t){return Me((e,r)=>function(...o){let s=i;try{let n=e.apply(this,o),d=_e();return xi(n)?n.then(p=>(t?Y.addSuccessEvent({key:s,cost:_e()-d}):Y.addSuccessEvent({key:s}),p)).catch(p=>{throw Y.addFailedEvent({key:s,error:p}),p}):(Y.addSuccessEvent({key:s}),n)}catch(n){throw Y.addFailedEvent({key:s,error:n}),n}})}var Lo=class Lo extends ko{constructor(e,r){super({mediaType:e,PlayerClass:r});u(this,"isRemote",!1);u(this,"deviceId");u(this,"groupId","");u(this,"label","");u(this,"_isRecapturing",!1);u(this,"_lastRecaptureTime",0);u(this,"_onMuteTimeoutId",-1);u(this,"_encodeCheckTimeoutId",-1);u(this,"profile")}get enableEncodeFrame(){return!1}get isPublishing(){return this.state.toString()==="publishing"}get isPublished(){return this.state==="publish"}encodeFrame(e,r){throw new Error("Method not implemented.")}installTrackEvent(e){xt(e,e).add(D.MUTE,this.onTrackMuted).add(D.UNMUTE,this.onTrackUnmuted).add(D.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===D.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){mt(e)}setStateToCapture(){}capture(e){return y(this,null,function*(){var r;try{let o=_e();H.emit(L.LOCAL_TRACK_CAPTURE_START,{track:this});let s;e.customSource?(s=new MediaStream,s.addTrack(e.customSource)):((r=this.mediaTrack)==null||r.stop(),s=yield cf(e));let n=s.getTracks()[0];return yield this.setInputMediaStreamTrack(n),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),H.emit(L.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:_e()-o}),s}catch(o){throw H.emit(L.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:o}),this.log.error(`getUserMedia error observed ${o}`),o}})}setInputMediaStreamTrack(e){return this.state===ne.INIT&&this.setStateToCapture(),super.setInputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var r;if(super.setOutputMediaStreamTrack(e),this.isPublishing||this.isPublished)return(r=this.room)==null?void 0:r.replaceTrack(this)}publish(e,r){return this.room=e,this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),r}unpublish(){this.room&&this.room.localTracks.delete(this),H.emit(L.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return y(this,null,function*(){if(this.mediaTrack&&ks){let{deviceId:e,groupId:r}=this.mediaTrack.getSettings(),{label:o}=this.mediaTrack;(yield nf({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=o,r&&(this.groupId=r),ad().then(n=>{let d=n.find(p=>p.deviceId===e);d&&this.emit("2",d)}))}})}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(e=!1){return!(!this.deviceId||!this.mediaTrack||this.kind===D.AUDIO&&!sf(this.mediaTrack)||this.kind===D.VIDEO&&!of(this.mediaTrack)||this._isRecapturing||e&&_r&&Mt)}onTrackMuted(){if(super.onTrackMuted(),uf(),!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<ps){setTimeout(()=>this.onTrackMuted(),ps);return}this._onMuteTimeoutId=setTimeout(()=>y(this,null,function*(){var e;if((e=this.mediaTrack)!=null&&e.muted){if((lt||at)&&document.visibilityState!=="visible")return;this.recapture(yield this.getRecoverCaptureDeviceId())}}),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return y(this,null,function*(){if(Ft(Lo.prototype,this,"onTrackEnded").call(this),!!this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<ps){setTimeout(()=>this.onTrackEnded(),ps);return}this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e){return y(this,null,function*(){var o;if(this._isRecapturing||!this._inputTrack)return;this.log.warn("recapture trying"),(o=this._inputTrack)==null||o.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let r={useExactDeviceId:!0};if(e==="user"||e==="environment")r.facingMode=e;else{let s;(this.kind==="audio"?yield Jt():yield er()).find(d=>d.deviceId===e)&&(s=e),r.deviceId=s}return this.capture(r).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),H.emit(L.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(s=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${s.message}`),this.emit("5",s),H.emit(L.LOCAL_TRACK_RECAPTURE,{track:this,error:s})})})}getRecoverCaptureDeviceId(){return y(this,null,function*(){let e=this instanceof Sr;if(e&&this.facingMode)return this.facingMode;let{deviceId:r}=this;if(r){let o=(fa.get(r)||0)+1;if(fa.set(r,o),o>=3){let s=e?(yield er()).find(n=>!fa.has(n.deviceId)):(yield Jt()).find(n=>!fa.has(n.deviceId));s&&(this.log.warn(`${r} capture fail ${o} times, change new ${s.deviceId}`),r=s.deviceId)}}return r})}close(){var e;super.close(),this._inputTrack&&(this._inputTrack.stop(),this.uninstallTrackEvent(this._inputTrack)),(e=this.manager)==null||e.removeInput(this)}};X([qe(ne.INIT,"capture",{ignoreError:!0,sync:!0})],Lo.prototype,"setStateToCapture",1),X([pf()],Lo.prototype,"capture",1),X([qe("capture","publish",{ignoreError:!0,success(){var r,o;this.room.localTracks.add(this),H.emit(L.LOCAL_TRACK_PUBLISHED,{track:this}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),!((((o=(r=this.room)==null?void 0:r.networkQuality)==null?void 0:o.uplinkNetworkQuality)||0)>3)&&(this._encodeCheckTimeoutId=setTimeout(()=>{var n,d;if(!((((d=(n=this.room)==null?void 0:n.networkQuality)==null?void 0:d.uplinkNetworkQuality)||0)>3)&&this.isPublished&&this.isMediaTrackActive){let p=this.kind===D.AUDIO,m=this.stat.bytesSent>0;Y[m?"addSuccessEvent":"addFailedEvent"]({key:p?503700:513702}),m||(Y.addEnum({key:p?503701:513703,value:Jn()}),Be.uploadEvent({log:`stat-encode-failed-${this.kind}-${qn()||bo()}`,userId:this.userId}),this.log.warn("encode failed"),this.emit("6",this))}},5e3))},fail(e){let r="error";if(e.cause instanceof RTCError){let o=e.cause;o.message.includes("timeout")?r="timeout":o.code===te.API_CALL_ABORTED&&(r="api-call")}this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:r,error:e.cause||e})}}),hd(521714,!1)],Lo.prototype,"publish",1),X([Me(e=>function(){return y(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)})}),qe([],"capture",{sync:!0})],Lo.prototype,"unpublish",1);var di=Lo,fa=new Map;H.on(L.SWITCH_DEVICE_SUCCESS,i=>{i.track.deviceId&&fa.delete(i.track.deviceId)});var ui=class i extends di{constructor(e){super(1,ud);u(this,"mediaType",1);u(this,"volume",0);u(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40});u(this,"playerMuted",!0);u(this,"pipeline");u(this,"earMonitorGainNode",new Pt);u(this,"_output",new Pt);u(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0});this.manager=e,this.pipeline=new Fs(e),this.pipeline.gain.pipeTo(this.earMonitorGainNode.pipeTo(this._output),this.player.pipeline.volumeMeter),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this)}get dbVolume(){return nd.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}setInputMediaStreamTrack(e){return y(this,null,function*(){let r=this.trackSettings||{};Y.addEnum({key:501701,value:r.channelCount||0,useUV:!1}),Y.addEnum({key:501702,value:r.sampleRate||0,useUV:!1}),Y.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.replaceSource(e),yield Ft(i.prototype,this,"setInputMediaStreamTrack").call(this,e),this.updatePlayingState(!!e)})}capture({deviceId:e,customSource:r,useExactDeviceId:o=!0,retryWhenExactFailed:s=!0}){return super.capture({video:!1,audio:!0,microphoneId:e,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:o,retryWhenExactFailed:s,customSource:r})}switchDevice(e){return y(this,null,function*(){if(this.mediaTrack){if(this.deviceId===e)if(e===Io){if(yield Xl(this.groupId,this.label))return}else return;try{this.log.info(`switchDevice audio to: ${e}`),this.mediaTrack&&this.mediaTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0,retryWhenExactFailed:!1}),H.emit(L.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(){Tt&&!Tt.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&Tt.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return y(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current microphone is lost: ${JSON.stringify(e)}`),tt(this.userId,{eventId:2003,param1:6,streamType:1});let r=yield Jt();r[0]?this.recapture(r[0].deviceId):Tt.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.log.warn(`microphone added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)}update3A(s){return y(this,arguments,function*({echoCancellation:e,noiseSuppression:r,autoGainControl:o}){let n=!1;!V(e)&&e!==this.profile.echoCancellation&&(this.profile.echoCancellation=e,n=!0),!V(r)&&r!==this.profile.noiseSuppression&&(this.profile.noiseSuppression=r,n=!0),!V(o)&&o!==this.profile.autoGainControl&&(this.profile.autoGainControl=o,n=!0),n&&this.deviceId&&(yield this.recapture(this.deviceId))})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&Y.addEnum({key:502700,value:2})}setAudioVolume(e){super.setAudioVolume(0),lt&&this.player.setMuted(!0),this.earMonitorGainNode.node||(this.earMonitorGainNode.setNode(et().createGain()),this._output.setNode(et().destination)),this.earMonitorGainNode.node.gain.value=e}enableTrackANS(e){if(!this._inputTrack)return;let r=this._inputTrack.getConstraints();return r.noiseSuppression=e,this._inputTrack.applyConstraints(r).catch(o=>this._log.warn(`${e?"enable":"disable"} ANS failed `,o))}addDenoiser(e){var r;if(ei<=92&&((r=this.trackSettings)==null?void 0:r.sampleRate)!==48e3){this._log.warn("denoiser only support sampleRate 48000 before chrome 93");return}Y.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.enableTrackANS(!1)}removeDenoiser(e){this.pipeline.denoiser.node===e&&(this.pipeline.denoiser.deleteNode(),this.enableTrackANS(!0))}close(){this.pipeline.remove(),this.earMonitorGainNode.deleteNode(),this._output.deleteNode(),Tt.off("audioInputAdded",this.handleMicrophoneAdded,this),Tt.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}recapture(e){return y(this,null,function*(){try{yield Ft(i.prototype,this,"recapture").call(this,e)}catch(r){let o=(yield Jt()).find(s=>s.deviceId!==e);if(o)yield Ft(i.prototype,this,"recapture").call(this,o.deviceId);else throw r}})}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduceRight((r,o)=>o?o({frame:r}):r,e):e}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}};var Uo=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 d=this.dataView.getInt8(n);switch(d){case 0:case 1:case 2:case 3:o===2&&(r.push(3),o=0),d==0?o++:o=0,r.push(d);break;default:o=0,r.push(d);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 fd=class{constructor(){u(this,"_seiMessageList",[]);u(this,"_smallSeiMessageList",[]);u(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 d=0;d<r;d++)s.push(255);s.push(o);let n=new DataView(t);return s.push(...new Uint8Array(n.buffer)),s.push(128),new Uo(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)),d=n.reduce((b,N)=>b+N.dataView.byteLength,0),p=new ArrayBuffer(d+t.data.byteLength),m=new DataView(p),g=new DataView(t.data),_=0;for(let b=0;b<n.length;b++)for(let N=0;N<n[b].dataView.byteLength;N++)m.setInt8(_++,n[b].dataView.getInt8(N));for(let b=0;b<t.data.byteLength;b++)m.setInt8(_++,g.getInt8(b));return t.data=p,n.length}return 0}};var Vo=class Vo extends di{constructor(e,r=4){super(r,Zt);u(this,"profile",{width:640,height:480,frameRate:15,bitrate:500});u(this,"avoidCrop",!1);u(this,"_scaleResolutionDownBy");u(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0});u(this,"small");u(this,"isNeedToSetBandwidth");u(this,"muteImage");u(this,"manager");u(this,"_seiCodec",new fd);this.manager=e;let o=()=>{this.isAllowed2k4k(this.profile)?this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1}):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),this.setProfile(Ee(ee({},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(!(!ks||!this.mediaTrack))return this.mediaTrack.getSettings().facingMode}get isQosClearFirst(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)==="detail"}setMute(e){return y(this,null,function*(){var r,o,s;if(we(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}),this.muteImage=e,Ft(Vo.prototype,this,"setMute").call(this,!1)}else yield(s=this.manager)==null?void 0:s.deleteWatermark("mute"),this.muteImage=void 0,Ft(Vo.prototype,this,"setMute").call(this,e)})}capture({deviceId:e,facingMode:r,useExactDeviceId:o=!0,customSource:s,retryWhenExactFailed:n=!0}){return super.capture({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})}setProfile(e){let r=ee({},e),o=r.width>r.height;r.width*r.height<=160*120&&at&&Kr&&(this.log.warn(`resolution is ${r.width}*${r.height}, fallback to 240*180`),r.width=o?240:180,r.height=o?180:240,r.bitrate=Math.max(r.bitrate,150)),r.width*r.height>1280*720&&il&&(r.width=o?1280:720,r.height=o?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),this.avoidCrop&&(Kr||Qt)&&!ol()&&r.width*r.height<=640*360&&r.width/r.height===16/9&&(this._scaleResolutionDownBy=1280/r.width,r.width=1280,r.height=720,this.log.warn(`capture 720p, scale: ${this._scaleResolutionDownBy}`)),r.bitrate&&(this.isNeedToSetBandwidth=r.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile)?super.setProfile(r):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),super.setProfile(Ee(ee({},this.profile),{width:1920,height:1080})))}applyProfile(){return y(this,null,function*(){var o;if(!this.mediaTrack)return;let e=this.settings;if(!(!(e.height!==this.profile.height||e.width!==this.profile.width||e.frameRate!==this.profile.frameRate)||!this.deviceId)&&(Yt===16?yield this.recapture(this.deviceId):(yield(o=this.mediaTrack)==null?void 0:o.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))return this.isNeedToSetBandwidth=!1,this.room.setBandWidth({bandwidth:this.profile.bitrate,type:D.VIDEO,videoType:D.BIG})})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate};return ks&&this.mediaTrack&&Object.assign(e,this.mediaTrack.getSettings()),e}get scaleResolutionDownBy(){if(this._scaleResolutionDownBy)return this._scaleResolutionDownBy;let{settings:e}=this;return e.width===this.profile.width&&e.height===this.profile.height?1:_c()&&this.profile.width>this.profile.height&&e.height>e.width?Math.max(e.width/this.profile.height,e.height/this.profile.width,1):Math.max(e.width/this.profile.width,e.height/this.profile.height,1)}isAllowed2k4k(e){var 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 y(this,null,function*(){try{if(!this.isNeedToSwitchDevice(e))return;let r={useExactDeviceId:!0,retryWhenExactFailed:!1};e==="user"||e==="environment"?r.facingMode=e:r.deviceId=e,this.mediaTrack.stop(),yield this.capture(r),H.emit(L.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}})}listenDeviceChange(){Tt&&!Tt.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&Tt.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return y(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current camera is lost: ${JSON.stringify(e)}`),tt(this.userId,{eventId:2003,param1:7,streamType:2});let r=yield er();r[0]?this.recapture(r[0].deviceId):Tt.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return y(this,null,function*(){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 V(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,r)}close(){Tt.off("videoInputAdded",this.handleCameraAdded,this),Tt.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return y(this,null,function*(){try{yield Ft(Vo.prototype,this,"recapture").call(this,e)}catch(r){let o=(yield er()).find(s=>s.deviceId!==e);if(o)yield Ft(Vo.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))}};X([Gi(function(e){this.setContentHint(e.contentHint||"motion")})],Vo.prototype,"capture",1);var Sr=Vo;var gf=Xn();if(typeof navigator!="undefined"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:gf,exposeOrigin:!0,permittedOrigins:["*"]})}catch(i){}var z_=function(i){return y(this,null,function*(){let t=null,e=Y_(i);$.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let r=yield navigator.mediaDevices.getDisplayMedia(e);i.systemAudio&&r.getAudioTracks().length===0&&(Ds&&ei<74||Mt||Qt)&&$.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){$.warn(`screen applyConstraints failed: ${s}`)}i.captureElement&&(yield X_(o,i.captureElement))}if(i.audio){let s=Q_(i);$.info(`getUserMedia with constraints: ${JSON.stringify(s)}`),t=yield navigator.mediaDevices.getUserMedia(s),r.addTrack(t.getAudioTracks()[0])}return r})};function X_(i,t){return y(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&Xe(i.cropTo))try{if(!(((e=i.getCaptureHandle())==null?void 0:e.handle)===gf))return;let o=yield CropTarget.fromElement(t);yield i.cropTo(o)}catch(r){$.warn(`cropTo target failed ${r}`)}})}function Q_(i){let t={echoCancellation:i.echoCancellation,autoGainControl:i.autoGainControl,noiseSuppression:i.noiseSuppression,sampleRate:i.sampleRate,channelCount:i.channelCount};return V(i.microphoneId)||(t.deviceId=i.microphoneId),{audio:t,video:!1}}function Y_(i){let t={preferCurrentTab:i.preferDisplaySurface==="current-tab"||!!i.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:Mt?{max:i.width}:{ideal:i.width,max:i.width},height:Mt?{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 Ef=z_;var ji=class extends Sr{constructor(e){super(e,2);u(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600});u(this,"objectFit","contain");u(this,"isScreen",!0);this._log.id=`s-${this._log.id}`}capture(g){return y(this,arguments,function*({systemAudio:e=!1,autoGainControl:r,echoCancellation:o,noiseSuppression:s,audioTrack:n,videoTrack:d,captureElement:p,preferDisplaySurface:m}){try{let _;return d||n?(_=new MediaStream,d&&_.addTrack(d),n&&_.addTrack(n)):_=yield Ef({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:r,echoCancellation:o,noiseSuppression:s,captureElement:p,preferDisplaySurface:m}),yield this.setInputMediaStreamTrack(_.getVideoTracks()[0]),_}catch(_){throw this.log.error(`getDisplayMedia error observed ${_}`),_ instanceof he?_:new he({code:te.INITIALIZE_FAILED,name:_.name,message:_.message})}})}switchDevice(e){return y(this,null,function*(){throw new Error("Method not implemented.")})}};X([Gi(function(e){this.setContentHint(e.contentHint||"detail")})],ji.prototype,"capture",1);var Fo=class extends ui{constructor(t){super(t),this._log.id=`s-${this._log.id}`}};var Z_="registerProcessor('dumper', class extends AudioWorkletProcessor {process(inputs) {this.port.postMessage(inputs);return true;}});",Zl;function ga(i){return y(this,null,function*(){let t=et("dump");Zl||(Zl=Po(t,URL.createObjectURL(new Blob([Z_],{type:"application/javascript"})))),yield Zl;let e=new AudioWorkletNode(t,"dumper",{numberOfInputs:i.length,numberOfOutputs:0});return i.forEach((r,o)=>r.connect(e,0,o)),new ReadableStream({start(r){e.port.onmessage=o=>{r.enqueue(o.data)}},cancel(){i.forEach(r=>r.disconnect(e)),e.port.close()}})})}var gd=class extends id{constructor(e){super();this.room=e;u(this,"_localAudioTrack");u(this,"_localScreenAudioTrack");u(this,"log",$.createLogger({id:"am"}));u(this,"denoiser");u(this,"voiceChanger");u(this,"mixChangedDebounce");u(this,"encodePipeline",[]);u(this,"decodePipeline",[]);e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId))}get _localAudioPipline(){var e;return(e=this._localAudioTrack)==null?void 0:e.pipeline}dump(e){var g,_;if(!this._localAudioTrack)return;let r=[],o=[];(g=this._localAudioPipline)!=null&&g.source.node&&(r.push(this._localAudioPipline.source.node),o.push("mic")),(_=this._localAudioPipline)!=null&&_.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=[],d=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),s.abort("timeout")},e*1e3),p=()=>{for(let b=0;b<o.length;b++){let N=URL.createObjectURL(new Blob(n[b])),k=document.createElement("a");k.href=N,k.download=`${o[b]}.pcm`,k.style.display="none",document.body.appendChild(k),k.click(),URL.revokeObjectURL(N),k.remove()}clearTimeout(d),s.abort("download")},m=ga(r).then(b=>b.pipeTo(new WritableStream({write(N){N.forEach((k,P)=>n[P]=n[P]?n[P].concat(k[0]):[k[0]])}}),s).catch(N=>p));return{then:m.then.bind(m),download:p}}getPCM(e){var n;if(V(WritableStream)){this.log.warn("getPCM failed: browser not support WritableStream");return}if(!((n=this._localAudioPipline)!=null&&n.source.node)){this.log.warn("getPCM failed: no local audio track");return}this.log.warn("getPCM");let r=new Float32Array(1920),o=0,s=new AbortController;return ga([this._localAudioPipline.source.node]).then(d=>d.pipeTo(new WritableStream({write(p){p[0][0]&&(r.set(p[0][0],o),o+=p[0][0].length,o>=1920&&(o=0,e(r),r=new Float32Array(1920)))}}),s).catch(p=>this.log.warn(`stop getPCM reason:${p}`))),s}get hasScreenAudioTrack(){return this._localScreenAudioTrack!==null}get hasAudioTrack(){return!V(this._localAudioTrack)}changeInput(e){if(e instanceof Fo)return this._localScreenAudioTrack=e,e.pipeline.connect(),this.mixOnChange();if(e instanceof ui)return this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),e.pipeline.connect(),this.mixOnChange();if(e instanceof $o)return e.setOutputMediaStreamTrack(e.mediaTrack)}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 Fo?delete this._localScreenAudioTrack:e instanceof ui?delete this._localAudioTrack:e instanceof $o}addDenoiser(e){var r;this.denoiser=e,(r=this._localAudioTrack)==null||r.addDenoiser(e)}removeDenoiser(e){var r;delete this.denoiser,(r=this._localAudioTrack)==null||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()}destroy(){this.close()}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}};function _f(i=30,t=2){return Me((e,r)=>function(...o){return new Promise((s,n)=>{let d=setTimeout(()=>{let p=new he({code:te.API_CALL_TIMEOUT,message:`checkPendingPromise ${r}() timeout ${i}s`});$.warn(p),t===2?n(p):t===1&&s()},i*1e3);e.apply(this,o).then(s,n).finally(()=>{clearTimeout(d)})})})}var Um={};Jr(Um,{Events:()=>it,Inspect:()=>or,LastSink:()=>Bo,Sink:()=>de,Subscribe:()=>Ho,TimeoutError:()=>Ea,audit:()=>xT,bindCallback:()=>_T,bindNodeCallback:()=>TT,buffer:()=>aT,bufferCount:()=>nT,bufferTime:()=>ZT,call:()=>Tf,catchError:()=>xm,combineLatest:()=>Sf,concat:()=>tT,concatMap:()=>GT,concatMapTo:()=>jT,count:()=>yT,create:()=>Oe,debounce:()=>PT,debounceTime:()=>kT,defer:()=>yf,delay:()=>KT,deliver:()=>pe,dispose:()=>Ed,elementAt:()=>LT,empty:()=>Ia,every:()=>BT,exhaustMap:()=>zT,exhaustMapTo:()=>XT,filter:()=>yr,find:()=>UT,findIndex:()=>VT,first:()=>FT,fromAnimationFrame:()=>gT,fromArray:()=>uT,fromEvent:()=>be,fromEventPattern:()=>lT,fromFetch:()=>mT,fromIterable:()=>pT,fromPromise:()=>Rf,fromReadableStream:()=>fT,fromReader:()=>hT,groupBy:()=>QT,identity:()=>K_,ignoreElements:()=>vT,iif:()=>iT,inspect:()=>If,interval:()=>sm,last:()=>$T,map:()=>Ji,mapTo:()=>WT,max:()=>AT,merge:()=>im,mergeMap:()=>qT,mergeMapTo:()=>JT,min:()=>bT,never:()=>IT,nothing:()=>Ve,of:()=>dT,pairwise:()=>HT,pipe:()=>Se,race:()=>om,range:()=>ET,reduce:()=>nm,retry:()=>rI,scan:()=>Om,share:()=>li,shareReplay:()=>rT,skip:()=>DT,skipUntil:()=>NT,skipWhile:()=>yd,startWith:()=>_a,subject:()=>It,subscribe:()=>ke,sum:()=>RT,switchMap:()=>zi,switchMapTo:()=>mi,take:()=>Ar,takeLast:()=>CT,takeUntil:()=>Je,takeWhile:()=>vf,tap:()=>Sa,throttle:()=>MT,throwError:()=>ST,timeInterval:()=>YT,timeout:()=>Lm,timer:()=>Ta,toPromise:()=>eI,toReadableStream:()=>tI,withLatestFrom:()=>sT,zip:()=>oT});function Ve(...i){}var Tf=i=>i(),K_=i=>i;function Ed(){this.dispose()}var If=()=>typeof __FASTRX_DEVTOOLS__!="undefined",eT=1,or=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(t){let e=new Kl(t,this,this.streamId++);return it.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},Bo=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=Ve,this.error=Ve,this.next=Ve,this.dispose=Ve,this.subscribe=Ve,this.doDefer()}subscribe(t){return t instanceof or?t.subscribe(this):t(this),this}get bindSubscribe(){return t=>this.subscribe(t)}doDefer(){this.defers.forEach(Tf),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}},de=class extends Bo{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)}},Ho=class extends Bo{constructor(t,e=Ve,r=Ve,o=Ve){if(super(),this._next=e,this._error=r,this._complete=o,this.then=Ve,t instanceof or){let s={toString:()=>"subscribe",id:0,source:t};this.defer(()=>{it.defer(s,0)}),it.create(s),it.pipe(s),this.sourceId=s.id,this.subscribe(t),it.subscribe({id:s.id,end:!0}),e==Ve?this._next=n=>it.next(s,0,n):this.next=n=>{it.next(s,0,n),e(n)},o==Ve?this._complete=()=>it.complete(s,0):this.complete=()=>{this.dispose(),it.complete(s,0),o()},r==Ve?this._error=n=>it.complete(s,0,n):this.error=n=>{this.dispose(),it.complete(s,0,n),r()}}else this.subscribe(t)}next(t){this._next(t)}complete(){this.dispose(),this._complete()}error(t){this.dispose(),this._error(t)}};function Se(i,...t){return t.reduce((e,r)=>r(e),i)}function Oe(i,t,e){if(If()){let r=Object.defineProperties(Object.setPrototypeOf(i,or.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}});it.create(r);for(let o=0;o<e.length;o++){let s=e[o];typeof s=="function"&&s instanceof or&&it.addSource(r,s)}return r}return i}function pe(i,t){return function(...e){return r=>{if(r instanceof or){let o=Oe(s=>{let n=new i(s,...e);n.sourceId=o.id,n.subscribe(r)},t,arguments);return o.source=r,it.pipe(o),o}else return o=>r(new i(o,...e))}}}function qi(i,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:i,payload:t}})}var Kl=class extends de{constructor(t,e,r){super(t),this.source=e,this.id=r,this.sourceId=t.sourceId,this.defer(()=>{it.defer(this.source,this.id)})}next(t){it.next(this.source,this.id,t),this.sink.next(t)}complete(){it.complete(this.source,this.id),this.sink.complete()}error(t){it.complete(this.source,this.id,t),this.sink.error(t)}},it={addSource(i,t){qi("addSource",{id:i.id,name:i.toString(),source:{id:t.id,name:t.toString()}})},next(i,t,e){qi("next",{id:i.id,streamId:t,data:e&&e.toString()})},subscribe({id:i,end:t},e){qi("subscribe",{id:i,end:t,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(i,t,e){qi("complete",{id:i.id,streamId:t,err:e?e.toString():null})},defer(i,t){qi("defer",{id:i.id,streamId:t})},pipe(i){qi("pipe",{name:i.toString(),id:i.id,source:{id:i.source.id,name:i.source.toString()}})},update(i){qi("update",{id:i.id,name:i.toString()})},create(i){i.id||(i.id=eT++),qi("create",{name:i.toString(),id:i.id})}},Ea=class extends Error{constructor(t){super(`timeout after ${t}ms`),this.timeout=t}};var _d=class extends Bo{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 li(){return i=>{let t=new _d(i);if(i instanceof or){let e=Oe(r=>{t.add(r)},"share",arguments);return t.sourceId=e.id,e.source=i,it.pipe(e),e}return Oe(t.add.bind(t),"share",arguments)}}function im(...i){return Oe(t=>{let e=new de(t),r=i.length;e.complete=()=>{--r===0&&t.complete()},i.forEach(e.bindSubscribe)},"merge",arguments)}function om(...i){return Oe(t=>{let e=new Map;i.forEach(r=>{let o=new de(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 tT(...i){return Oe(t=>{let e=0,r=i.length,o=new de(t);o.complete=()=>{e<r&&!o.disposed?(o.doDefer(),o.subscribe(i[e++])):t.complete()},o.complete()},"concat",arguments)}function rT(i){return t=>{let e=new _d(t),r=[];return e.next=function(o){r.push(o),r.length>i&&r.shift(),this.sinks.forEach(s=>s.next(o))},Oe(o=>{o.defer(()=>e.remove(o)),r.forEach(s=>o.next(s)),e.add(o)},"shareReplay",arguments)}}function iT(i,t,e){return Oe(r=>i()?t(r):e(r),"iif",arguments)}function Sf(...i){return Oe(t=>{let e=i.length,r=e,o=e,s=new Array(e),n=()=>{--o===0&&t.complete()},d=(p,m)=>{let g=new de(t);g.next=_=>{--r===0?(g.next=b=>{s[m]=b,t.next(s)},g.next(_)):s[m]=_},g.complete=n,g.subscribe(p)};i.forEach(d)},"combineLatest",arguments)}function oT(...i){return Oe(t=>{let e=i.length,r=e,o=new Array(e),s=()=>{--r===0&&t.complete()},n=(d,p)=>{let m=new de(t),g=[];o[p]=g,m.next=_=>{g.push(_),o.every(b=>b.length)&&t.next(o.map(b=>b.shift()))},m.complete=s,m.subscribe(d)};i.forEach(n)},"zip",arguments)}function _a(...i){return t=>Oe((e,r=0,o=i.length)=>{for(;r<o&&!e.disposed;)e.next(i[r++]);e.disposed||e.subscribe(t)},"startWith",arguments)}var em=class extends de{constructor(t,...e){super(t);let r=new de(this.sink);r.next=o=>this.buffer=o,r.complete=Ve,r.subscribe(Sf(...e))}next(t){this.buffer&&this.sink.next([t,...this.buffer])}},sT=pe(em,"withLatestFrom"),tm=class extends de{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()}},nT=pe(tm,"bufferCount"),rm=class extends de{constructor(t,e){super(t),this.buffer=[];let r=new de(t);r.next=o=>{t.next(this.buffer),this.buffer=[]},r.complete=Ve,r.subscribe(e)}next(t){this.buffer.push(t)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},aT=pe(rm,"buffer");var cT=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 d(g){try{m(r.next(g))}catch(_){n(_)}}function p(g){try{m(r.throw(g))}catch(_){n(_)}}function m(g){g.done?s(g.value):o(g.value).then(d,p)}m((r=r.apply(i,t||[])).next())})};function It(i){let t=arguments,e=li()(Oe(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=Ve,e.complete=Ve,e.error=Ve,e}function yf(i){return Oe(t=>t.subscribe(i()),"defer",arguments)}var Af=i=>t=>{setTimeout(()=>i(t))},bf=i=>Af(t=>{for(let e=0;!t.disposed&&e<i.length;e++)t.next(i[e]);t.complete()});function dT(...i){return Oe(bf(i),"of",arguments)}function uT(i){return Oe(bf(i),"fromArray",arguments)}function sm(i){return Oe(t=>{let e=0,r=setInterval(()=>t.next(e++),i);return t.defer(()=>{clearInterval(r)}),"interval"},"interval",arguments)}function Ta(i,t){return Oe(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 Td(i,t){return e=>{let r=o=>e.next(o);e.defer(()=>t(r)),i(r)}}function lT(i,t){return Oe(Td(i,t),"fromEventPattern",arguments)}function be(i,t){if("on"in i&&"off"in i)return Oe(Td(e=>i.on(t,e),e=>i.off(t,e)),"fromEvent",arguments);if("addListener"in i&&"removeListener"in i)return Oe(Td(e=>i.addListener(t,e),e=>i.removeListener(t,e)),"fromEvent",arguments);if("addEventListener"in i)return Oe(Td(e=>i.addEventListener(t,e),e=>i.removeEventListener(t,e)),"fromEvent",arguments);throw"target is not a EventDispachter"}function Rf(i){return Oe(t=>{i.then(t.next.bind(t),t.error.bind(t))},"fromPromise",arguments)}function mT(i,t){return Oe(yf(()=>Rf(fetch(i,t))),"fromFetch",arguments)}function pT(i){return Oe(Af(t=>{try{for(let e of i){if(t.disposed)return;t.next(e)}t.complete()}catch(e){t.error(e)}}),"fromIterable",arguments)}function hT(i){let t=e=>cT(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 Oe(e=>{t(e)},"fromReader",arguments)}function fT(i){return Oe(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 gT(){return Oe(i=>{let t=requestAnimationFrame(function e(r){i.disposed||(i.next(r),t=requestAnimationFrame(e))});i.defer(()=>cancelAnimationFrame(t))},"fromAnimationFrame",arguments)}function ET(i,t){return Oe((e,r=i,o=t+i)=>{for(;r<o&&!e.disposed;)e.next(r++);return e.complete(),"range"},"range",arguments)}function _T(i,t,...e){return Oe(r=>{let o=e.concat(s=>(r.next(s),r.complete()));i.apply(t,o)},"bindCallback",arguments)}function TT(i,t,...e){return Oe(r=>{let o=e.concat((s,n)=>s?r.error(s):(r.next(n),r.complete()));i.apply(t,o)},"bindNodeCallback",arguments)}function IT(){return Oe(()=>{},"never",arguments)}function ST(i){return Oe(t=>t.error(i),"throwError",arguments)}function Ia(){return Oe(i=>i.complete(),"empty",arguments)}var Wo=class extends de{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)}},nm=pe(Wo,"reduce"),yT=i=>pe(Wo,"count")((t,e)=>i(e)?t+1:t,0),AT=()=>pe(Wo,"max")(Math.max),bT=()=>pe(Wo,"min")(Math.min),RT=()=>pe(Wo,"sum")((i,t)=>i+t,0);var am=class extends de{constructor(t,e,r){super(t),this.filter=e,this.thisArg=r}next(t){this.filter.call(this.thisArg,t)&&this.sink.next(t)}},yr=pe(am,"filter"),cm=class extends de{next(t){}},vT=pe(cm,"ignoreElements"),dm=class extends de{constructor(t,e){super(t),this.count=e}next(t){this.sink.next(t),--this.count===0&&this.complete()}},Ar=pe(dm,"take"),um=class extends de{constructor(t,e){super(t);let r=new de(t);r.next=()=>t.complete(),r.complete=Ed,r.subscribe(e)}},Je=pe(um,"takeUntil"),lm=class extends de{constructor(t,e){super(t),this.f=e}next(t){this.f(t)?this.sink.next(t):this.complete()}},vf=pe(lm,"takeWhile"),CT=i=>nm((t,e)=>(t.push(e),t.length>i&&t.shift(),t),[]),mm=class extends de{constructor(t,e){super(t),this.count=e}next(t){--this.count===0&&(this.next=super.next)}},DT=pe(mm,"skip"),pm=class extends de{constructor(t,e){super(t),t.next=Ve;let r=new de(t);r.next=()=>{r.dispose(),t.resetNext()},r.complete=Ed,r.subscribe(e)}},NT=pe(pm,"skipUntil"),hm=class extends de{constructor(t,e){super(t),this.f=e}next(t){this.f(t)||(this.next=super.next,this.next(t))}},yd=pe(hm,"skipWhile"),wT={leading:!0,trailing:!1},fm=class extends de{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)}},Id=class extends de{constructor(t,e,r=wT){super(t),this.durationSelector=e,this.config=r,this._throttle=new fm(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=Ve,this._throttle.complete(),super.complete()}},MT=pe(Id,"throttle"),OT={leading:!1,trailing:!0},xT=i=>pe(Id,"audit")(i,OT),gm=class extends de{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},Sd=class extends de{constructor(t,e){super(t),this.durationSelector=e,this._debounce=new gm(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()}},PT=pe(Sd,"debounce"),kT=i=>pe(Sd,"debounceTime")(t=>Ta(i)),Em=class extends de{constructor(t,e,r){super(t),this.count=e,this.defaultValue=r}next(t){this.count--===0&&(this.defaultValue=t,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()}},LT=pe(Em,"elementAt"),UT=i=>t=>Ar(1)(yd(e=>!i(e))(t)),_m=class extends de{constructor(t,e){super(t),this.f=e,this.i=0}next(t){this.f(t)?(this.sink.next(this.i++),this.complete()):++this.i}},VT=pe(_m,"findIndex"),Tm=class extends de{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.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},FT=pe(Tm,"first"),Im=class extends de{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()}},$T=pe(Im,"last"),Sm=class extends de{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.complete())}complete(){if(this.result===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.result);super.complete()}},BT=pe(Sm,"every");var ym=class extends de{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))}},Om=pe(ym,"scan"),Am=class extends de{constructor(){super(...arguments),this.hasLast=!1}next(t){this.hasLast?this.sink.next([this.last,t]):this.hasLast=!0,this.last=t}},HT=pe(Am,"pairwise"),Ad=class extends de{constructor(t,e,r){super(t),this.mapper=e,this.thisArg=r}next(t){super.next(this.mapper.call(this.thisArg,t))}},Ji=pe(Ad,"map"),WT=i=>pe(Ad,"mapTo")(t=>i),Bs=class extends de{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()}},Hs=class extends de{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=this.tryComplete,r.complete=r.tryComplete,r.subscribe(this.makeSource(t,this.index++))}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},bd=class extends Bs{},Rd=class extends Hs{next(t){this.subInner(t,bd),this.next=e=>{this.currentSink.dispose(),this.subInner(e,bd)}}},zi=pe(Rd,"switchMap");function Nd(i){return(t,e)=>i(()=>t,e)}var mi=Nd(pe(Rd,"switchMapTo")),bm=class extends Bs{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},vd=class extends Hs{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(),bm),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},GT=pe(vd,"concatMap"),jT=Nd(pe(vd,"concatMapTo")),Rm=class extends Bs{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},Cd=class extends Hs{constructor(){super(...arguments),this.inners=new Set}next(t){this.subInner(t,Rm),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(t=>t.resetComplete()):this.dispose()}},qT=pe(Cd,"mergeMap"),JT=Nd(pe(Cd,"mergeMapTo")),vm=class extends Bs{dispose(){this.context.resetNext(),super.dispose()}},Dd=class extends Hs{next(t){this.next=Ve,this.subInner(t,vm)}},zT=pe(Dd,"exhaustMap"),XT=Nd(pe(Dd,"exhaustMapTo")),Cm=class extends de{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=It(),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)}},QT=pe(Cm,"groupBy"),Dm=class extends de{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}},YT=pe(Dm,"timeInterval"),Nm=class extends de{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()}},ZT=pe(Nm,"bufferTime"),wm=class extends de{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)}},KT=pe(wm,"delay"),Mm=class extends de{constructor(t,e){super(t),this.selector=e}error(t){this.dispose(),this.selector(t)(this.sink)}},xm=pe(Mm,"catchError");var eI=()=>i=>new Promise((t,e)=>{let r;new Ho(i,o=>r=o,e,()=>t(r))}),tI=()=>i=>{let t;return new ReadableStream({start(e){t=new Ho(i,e.enqueue.bind(e),e.error.bind(e),e.close.bind(e))},cancel(){t.dispose()}})},ke=(i=Ve,t=Ve,e=Ve)=>r=>new Ho(r,i,t,e),Pm=class extends de{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)}))}},Sa=pe(Pm,"tap"),km=class extends de{constructor(t,e){super(t),this.timeout=e,this.id=setTimeout(()=>this.error(new Ea(this.timeout)),this.timeout)}next(t){super.next(t),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},Lm=pe(km,"timeout"),rI=(i=1/0)=>t=>{if(t instanceof or){let e=Oe(r=>{let o=i,s=new de(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,it.pipe(e),e}else return e=>{let r=i,o=new de(e);o.error=s=>{r-- >0?t(o):e.error(s)},t(o)}};var Br=class Br extends ko{constructor(e,r,o){super({userId:r.userId,sdkAppId:e.sdkAppId,mediaType:o,room:e});this.room=e;this.user=r;u(this,"tinyId");u(this,"isRemote",!0);u(this,"jitterBufferDelay",0);u(this,"availableState");u(this,"remotePublishState");u(this,"_triggerCheckDecodeSubject",It(be(this,Br.STATE_SUBSCRIBE)));this.tinyId=r.tinyId,this.availableState=new ne(`${r.userId}-${this.mediaType}-available`,"remote-track-available"),this.remotePublishState=new ne(`${r.userId}-${this.mediaType}-remote-publish`,"remote-track-publish"),Se(im(be(this,ne.STATECHANGED),be(this.remotePublishState,ne.STATECHANGED)),Ji(()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing)),ke(p=>{this.availableState.state!==(p?ne.ON:ne.OFF)&&(this.availableState.state=p?ne.ON:ne.OFF),this.updatePlayingState(p)}));let s=Se(be(this.player,Qe.ERROR),yr(p=>p.code===MediaError.MEDIA_ERR_DECODE)),n=Se(Ta(5e3),yr(()=>this.ignoreDecodeError||!this.isSubscribed||!this.isPlayCalled||!this.stat.bytesReceived?!1:this.player.isPlaying||(this.kind===D.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)?(this.reportDecodeResult(!0),!1):!0)),d=Se(om(s,n),Je(be(this,ne.INIT)));Se(this._triggerCheckDecodeSubject,yr(()=>!this.ignoreDecodeError),mi(d),ke(p=>{this.reportDecodeResult(!1,p)}))}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===Br.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===ne.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){let o=this.kind===D.AUDIO;Y[e?"addSuccessEvent":"addFailedEvent"]({key:o?504700:514702}),e||(Y.addEnum({key:o?504701:514703,value:Jn()}),Be.uploadEvent({log:`stat-decode-failed-${this.kind}-${qn()||bo()}`,userId:this.room.userId}),this._log.warn(`decode failed: isPlaying: ${this.player.isPlaying} ${this.kind===D.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?ne.ON:ne.OFF}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};u(Br,"STATE_SUBSCRIBE","subscribe"),X([_f(5,1)],Br.prototype,"waitHasMediaTrack",1),X([qe(ne.INIT,Br.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),H.emit(L.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),hd(521716,!1)],Br.prototype,"subscribe",1),X([qe(Br.STATE_SUBSCRIBE,ne.INIT,{sync:!0,success(){this.log.info("unsubscribed"),H.emit(L.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],Br.prototype,"unsubscribe",1);var Ws=Br;var $o=class extends Ws{constructor(e,r){super(e,r,1);u(this,"volume",0);u(this,"mediaType",1);u(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.audioManager}get dbVolume(){return nd.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}decodeFrame(e){if(!this.manager)return e;let r=e;for(let o of this.manager.decodePipeline)if(o&&(r=o({frame:r,track:this}),!r))return;return r}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get isRemotePublished(){return this.user.muteState.audioAvailable}};var oI=[-1,-1,1,-1,-1,1,1,1],sI=[0,0,1,0,0,1,1,1];var Bt=class extends ne{constructor(e,r){super();this.context=e;u(this,"name");u(this,"input");u(this,"output");u(this,"texture");u(this,"ctx2d",null);u(this,"fbo");u(this,"width",0);u(this,"height",0);u(this,"x",0);u(this,"y",0);u(this,"program");u(this,"vertexShader");u(this,"fragmentShader");u(this,"totalFrames",0);u(this,"dropFrames",0);u(this,"matchInputSize",!0);u(this,"texCoordBuffer");u(this,"positionBuffer");u(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0});u(this,"cost",0);u(this,"_canvas",null);u(this,"_image");u(this,"log");if(this.context.on("disconnect",this.close,this),this.name=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 kt){e.ctx&&r.create2d&&(typeof OffscreenCanvas=="function"&&Yt!==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(sI),this.positionBuffer=this.createBuffer(oI),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.PACK_ALIGNMENT,1),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 he({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 Et&&this.render(e)||this.context instanceof kt&&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 Et){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){return this.ctx2d&&e?(e instanceof ImageData?this.ctx2d.putImageData(e,r,o):(this.ctx2d.drawImage(e,r,o,s,n),typeof VideoFrame!="undefined"&&e instanceof VideoFrame&&e.close()),!0):!1}getInfo(){var _;let{totalFrames:e,x:r,y:o,width:s,height:n,name:d,cost:p}=this,m=Date.now(),g=(e-this.lastInfo.totalFrames)/((m-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:r,y:o,width:s,height:n,timestamp:m,fps:g,name:d,cost:p},ee({parent:(_=this.input)==null?void 0:_.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.PACK_ALIGNMENT,1),r.pixelStorei(r.UNPACK_ALIGNMENT,1),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,r.RGBA,r.UNSIGNED_BYTE,e),o}};X([qe(ne.INIT,"connected",{sync:!0})],Bt.prototype,"connect",1),X([qe("connected",ne.INIT,{ignoreError:!0,sync:!0})],Bt.prototype,"disconnect",1),X([qe([],"closed",{sync:!0})],Bt.prototype,"close",1);var Df=Se(sm(250),Ji(()=>performance.now()),li()),Nf=i=>t=>{let e=0,r=performance.now();Se(Df,Ji(o=>(o-r)/i>>0),yr(o=>o!=e?(e=o,!0):!1))(t)},wd=i=>t=>{let e=performance.now();Se(Df,yd(r=>r-e<i),Ar(1))(t)};var aI=[0,1,1,1,0,0,1,0],Go=class extends Bt{constructor(e,r){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},r));u(this,"_intervalId",0);u(this,"_sequence",0);u(this,"checkGLError",!1);u(this,"checkVisibilityChange");e instanceof kt?this.ctx2d=e.ctx||null:e.available&&(r!=null&&r.mirrorUpAndDown)&&this.setTexBuffer(aI)}start(e){this.log.info(`${this.name} start render ${e} fps`),At.clearTask(this._intervalId),this._intervalId=At.run("intervalInWorker",()=>{if(e!==this.context.frameRate&&(At.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof Et){let o=this.context.ctx.getError();o&&this.context.destroy(new he({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(),!0):!1}addInput(e,...r){super.addInput(e,...r),this.start(this.context.frameRate)}update(e=0){if(this._intervalId&&(At.clearTask(this._intervalId),this._intervalId=0,e===1)){this.log.info(`${this.name} use requestVideoFrameCallback`);let r=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info(`${this.name} use timer`),document.removeEventListener("visibilitychange",r))};document.addEventListener("visibilitychange",r)}this.requestFrame(this._sequence++)}removeInput(e){super.removeInput(e),At.clearTask(this._intervalId)}resize(e,r){super.resize(e,r),this.context.setSize(e,r)}close(){super.close(),At.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},Gs=class extends Go{constructor(e,r){super(e,r);u(this,"_videoTrack");u(this,"_muteOb");u(this,"_closedOb",be(this,"closed"));u(this,"_subscription");u(this,"_canvasContainer");Number(Vi)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e._canvas.captureStream().getVideoTracks(),this._muteOb=be(this._videoTrack,"mute"),Se(be(this._videoTrack,"ended"),Je(this._closedOb),ke(()=>{this.context.destroy(new he({code:te.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){this._subscription=Se(this._muteOb,Je(this._closedOb),mi(wd(5e3)),ke(()=>{var e;(e=this._videoTrack)!=null&&e.muted&&this.context.destroy(new he({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()}},Md=class extends Gs{render(t){var e;return!!((e=this.input)!=null&&e.requestFrame(t))}};var Od=class extends Gs{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 ya=class extends Bt{constructor(e,r){super(e,ee({name:"imageSource"},r));u(this,"_lastImage");u(this,"_totalFrames",0);u(this,"_autoResize",!1);u(this,"_canvasRendered");u(this,"_videoCallbackId",0);this._autoResize=(r==null?void 0:r.autoResize)!==!1,Yt===16&&(this._canvasRendered=It(),Se(this._canvasRendered,_a(this._image),zi(o=>o instanceof HTMLCanvasElement?be(o,"rendered"):Ia()),Je(be(this,"closed")),ke(()=>{this.update()})))}tryVideoFrameCallback(e){this._videoCallbackId&&e.cancelVideoFrameCallback(this._videoCallbackId),Oo()&&!document.hidden&&(this._videoCallbackId=e.requestVideoFrameCallback((r,o)=>{document.hidden||(this._totalFrames=o.presentedFrames,this.update(1))}))}_render(e,r){var d;let{width:o,height:s}=this,{image:n}=this;if(n instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(n),{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!1}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,(d=this._lastImage)==null||d.close(),this._lastImage=n);if(!this._autoResize)return!0;if(this.width===o&&this.height===s&&this.totalFrames){if(r){this.useTexture();let p=this.context.ctx;p.texSubImage2D(p.TEXTURE_2D,0,0,0,p.RGBA,p.UNSIGNED_BYTE,n)}}else{if(r){this.useTexture();let p=this.context.ctx;p.texImage2D(p.TEXTURE_2D,0,p.RGBA,p.RGBA,p.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)}},Aa=class extends ya{constructor(e,r,o){super(e,o);this._player=r;this.name="videoPlayerSource",Se(be(this._player,Qe.PLAYER_STATE_CHANGED),Je(be(this,"closed")),yr(({state:s})=>s==="PLAYING"),ke(()=>{this.tryVideoFrameCallback(this._player.element)}))}get image(){return this._player.element}},pi=class extends Aa{constructor(t,e,r){super(t,new Zt({id:r.name,track:e,muted:!0,container:null,objectFit:"contain",log:r.logger}),r),this.name="videoTrackSource",this._player.play()}replaceTrack(t){this._player.setTrack(t),this._player.play()}close(){super.close(),this._player.stop()}};var dI=`
|
|
32
32
|
// \u9876\u70B9\u7740\u8272\u5668
|
|
33
33
|
attribute vec4 a_position;
|
|
34
34
|
attribute vec2 a_texCoord;
|
|
@@ -38,7 +38,7 @@ void main() {
|
|
|
38
38
|
gl_Position = a_position;
|
|
39
39
|
v_texCoord = a_texCoord;
|
|
40
40
|
}
|
|
41
|
-
`,
|
|
41
|
+
`,uI=`
|
|
42
42
|
// \u7247\u5143\u7740\u8272\u5668
|
|
43
43
|
precision mediump float;
|
|
44
44
|
varying vec2 v_texCoord;
|
|
@@ -46,58 +46,58 @@ uniform sampler2D u_texture;
|
|
|
46
46
|
|
|
47
47
|
void main() {
|
|
48
48
|
gl_FragColor = texture2D(u_texture, v_texCoord);
|
|
49
|
-
} `;var Go=class extends ne{constructor(e){super();u(this,"frameRate");u(this,"_canvas");u(this,"log");u(this,"hasAlpha",!1);u(this,"name");u(this,"error");this.name=e.name,this.log=e.logger.createChild({id:`vc-${this.name}`}),this.frameRate=e.frameRate}set width(e){this._canvas&&(this._canvas.width=e)}get width(){var e;return((e=this._canvas)==null?void 0:e.width)||0}set height(e){this._canvas&&(this._canvas.height=e)}get height(){var e;return((e=this._canvas)==null?void 0:e.height)||0}setSize(e,r){this._canvas&&(this._canvas.width=e,this._canvas.height=r)}createVideoTrackSource(e,r){return new li(this,e,{logger:this.log,name:r})}createVideoTrackDestination(e){return new Ws(this,e)}createVideoImageSource(e,r){return new Sa(this,r?Object.assign(r,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,r){return new ya(this,e,r?Object.assign(r,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}};u(Go,"_ids",0);var nI={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},Gs=class Gs extends Go{constructor(){super(...arguments);u(this,"defaultProgam");u(this,"defaultVShader");u(this,"defaultFShader");u(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${Go._ids++}`),this.ctx=this._canvas.getContext("webgl2",nI),!this.ctx)throw new he({code:te.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,oI),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,sI),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new he({code:te.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))}),this.log.info("video context created use webgl")}destroy(e){let r="";return e&&(r=e.message,this.error=e,Y.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}set height(e){var r;(r=this.ctx)==null||r.viewport(0,0,this.width,e),super.height=e}setSize(e,r){var o;(o=this.ctx)==null||o.viewport(0,0,e,r),super.setSize(e,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}};u(Gs,"UNAVAILABLE","unavailable"),X([qe(ne.INIT,"created",{sync:!0,fail(e){Y.addFailedEvent({key:512700,error:e.cause||e})},success(){Y.addSuccessEvent({key:512700})}})],Gs.prototype,"create",1),X([qe("created",ne.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(Gs.UNAVAILABLE,e),this.removeAllListeners()}})],Gs.prototype,"destroy",1);var yt=Gs,kt=class extends Go{constructor(){super(...arguments);u(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${Go._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new he({code:te.VIDEO_MANAGER_ERROR,extraCode:2,message:"2d context not supported"});this.log.info("video context created use 2d")}destroy(e){let r="";e&&(r=e.message,this.error=e,Y.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(),Y.addSuccessEvent({key:512703})}};X([qe(ne.INIT,"created",{sync:!0,fail(e){Y.addFailedEvent({key:512701,error:e.cause||e})},success(){Y.addSuccessEvent({key:512701})}})],kt.prototype,"create",1),X([qe("created",ne.INIT,{ignoreError:!0,sync:!0})],kt.prototype,"destroy",1);function aI(i){return[15,30,45,60].reduce((e,r)=>Math.abs(r-i)<Math.abs(e-i)?r:e)}var qi=class extends Hs{constructor(e,r,o=4){super(e,r,o);u(this,"mediaType",4);u(this,"source");u(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.videoManager,this.once("first-video-frame",s=>{this.room.emit("first-video-frame",s)})}play(e,r){return(dt(r==null?void 0:r.canvasRender)?r.canvasRender:Qt===17)&&!this.source&&this.useCanvasPlayer(),super.play(e,r).then(()=>{this.player.calculateStat()})}useCanvasPlayer(){if(this.log.info(`useCanvasPlayer(), has element:${!!this.player.element}`),!this.player.element)return;let e=new kt({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});let r=new Wo(e,{name:"remotePlayer",logger:this.log});this.source=e.createVideoPlayerSource(this.player),this.source.connect(r),this.player.setCanvas(e._canvas),Do()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let r=this.decodeFPS,o=aI(r);if(!je(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(d=>d.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(d=>d.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),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)}onDecodeDowngradeStateChanged(e){this.emit("decode-downgrade-state-changed",e)}},xd=class extends qi{constructor(e,r){super(e,r,2);u(this,"mediaType",2);u(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}};var js=new Map;H.on(L.JOIN_SUCCESS,({room:i})=>{tt(i.userId,{eventId:32788})});H.on(L.LEAVE_START,({room:i})=>{tt(i.userId,{eventId:32789})});H.on(L.LOCAL_TRACK_PUBLISHED,({track:i})=>{if(i.room){let t=32769;i.mediaType===4?t=32768:i.mediaType===2&&(t=32805),tt(i.room.userId,{eventId:t})}});H.on(L.LOCAL_TRACK_UNPUBLISHED,({track:i})=>{if(i.room){let t=32771;i.mediaType===4?t=32770:i.mediaType===2&&(t=32806),tt(i.room.userId,{eventId:t})}});H.on(L.TRACK_MUTED,({track:i})=>{i.room&&(i.kind===D.AUDIO?tt(i.room.userId,{eventId:i.isRemote?32785:32772,remoteUserId:i.isRemote?i.userId:void 0}):tt(i.room.userId,{eventId:i.isRemote?32784:32773,remoteUserId:i.isRemote?i.userId:void 0}))});H.on(L.TRACK_UNMUTED,({track:i})=>{i.room&&(i.kind===D.AUDIO?tt(i.room.userId,{eventId:i.isRemote?32787:32774,remoteUserId:i.isRemote?i.userId:void 0}):tt(i.room.userId,{eventId:i.isRemote?32786:32775,remoteUserId:i.isRemote?i.userId:void 0}))});H.on(L.REMOTE_TRACK_SUBSCRIBED,({track:i})=>{i.room&&(i.mediaType===1&&tt(i.room.userId,{eventId:32777,remoteUserId:i.userId}),i.mediaType===4&&tt(i.room.userId,{eventId:32776,remoteUserId:i.userId}),i.mediaType===8&&tt(i.room.userId,{eventId:32803,remoteUserId:i.userId}))});H.on(L.REMOTE_TRACK_UNSUBSCRIBED,({track:i})=>{i.room&&(i.mediaType===1&&tt(i.room.userId,{eventId:32779,remoteUserId:i.userId}),i.mediaType===4&&tt(i.room.userId,{eventId:32778,remoteUserId:i.userId}),i.mediaType===8&&tt(i.room.userId,{eventId:32804,remoteUserId:i.userId}))});H.on(L.SWITCH_DEVICE_SUCCESS,({track:i})=>{i.room&&tt(i.room.userId,{eventId:i.kind===D.VIDEO?32780:32781})});H.on(L.LOCAL_TRACK_REPLACED,({track:i})=>{i.room&&tt(i.room.userId,{eventId:i.kind===D.VIDEO?32782:32783})});H.on(L.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&&tt(i.userId,{eventId:r})});H.on(L.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&&tt(i.userId,{eventId:s,remoteUserId:r})});H.on(L.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({implementation:i,userId:t,remoteUserId:e,codec:r,isHWCodec:o,prevImplementation:s,streamType:n})=>{let d=o?1:0;s||(d=o?3:2);let p=r==="h264"?0:2,m={eventId:4004,param1:d,param2:p,streamType:n||2};e&&(m.remoteUserId=e,m.eventId=4005),tt(t,m),Y.addEnum({key:e?514701:513701,value:d}),Y.addEnum({key:e?514700:513700,value:p})});H.on(L.LOCAL_TRACK_RECAPTURE,({track:i,error:t})=>{if(i.userId){let e={eventId:2003,param1:0};i.kind===D.AUDIO?(e.streamType=1,t&&(e.param1=2)):(e.streamType=i.streamType==="auxiliary"?7:2,t&&(e.param1=8)),tt(i.userId,e)}});function tt(i,t){let e=Ee(Z({},t),{timestamp:In()});js.has(i)?js.get(i).push(e):js.set(i,[e])}function Df(i){if(js.has(i)){let t=js.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 js.delete(i),t}return[]}var cI=Di(Ui(),1);var dI=Object.create,Ud=Object.defineProperty,uI=Object.defineProperties,Pf=Object.getOwnPropertyDescriptor,lI=Object.getOwnPropertyDescriptors,xf=Object.getOwnPropertyNames,wf=Object.getOwnPropertySymbols,mI=Object.getPrototypeOf,kf=Object.prototype.hasOwnProperty,pI=Object.prototype.propertyIsEnumerable,Vm=(i,t,e)=>t in i?Ud(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e,Aa=(i,t)=>{for(var e in t||(t={}))kf.call(t,e)&&Vm(i,e,t[e]);if(wf)for(var e of wf(t))pI.call(t,e)&&Vm(i,e,t[e]);return i},ba=(i,t)=>uI(i,lI(t)),hI=(i,t)=>function(){return t||(0,i[xf(i)[0]])((t={exports:{}}).exports,t),t.exports},fI=(i,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of xf(t))kf.call(i,o)||o===e||Ud(i,o,{get:()=>t[o],enumerable:!(r=Pf(t,o))||r.enumerable});return i},gI=(i,t,e)=>(e=i!=null?dI(mI(i)):{},fI(!t&&i&&i.__esModule?e:Ud(e,"default",{value:i,enumerable:!0}),i)),mi=(i,t,e,r)=>{for(var o,s=r>1?void 0:r?Pf(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&&Ud(t,e,s),s},Ar=(i,t,e)=>Vm(i,typeof t!="symbol"?t+"":t,e),EI=hI({"../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(m,E,_){this.fn=m,this.context=E,this.once=_||!1}function n(m,E,_,b,C){if(typeof _!="function")throw new TypeError("The listener must be a function");var k=new s(_,b||m,C),x=r?r+E:E;return m._events[x]?m._events[x].fn?m._events[x]=[m._events[x],k]:m._events[x].push(k):(m._events[x]=k,m._eventsCount++),m}function d(m,E){--m._eventsCount==0?m._events=new o:delete m._events[E]}function p(){this._events=new o,this._eventsCount=0}Object.create&&(o.prototype=Object.create(null),new o().__proto__||(r=!1)),p.prototype.eventNames=function(){var m,E,_=[];if(this._eventsCount===0)return _;for(E in m=this._events)e.call(m,E)&&_.push(r?E.slice(1):E);return Object.getOwnPropertySymbols?_.concat(Object.getOwnPropertySymbols(m)):_},p.prototype.listeners=function(m){var E=r?r+m:m,_=this._events[E];if(!_)return[];if(_.fn)return[_.fn];for(var b=0,C=_.length,k=new Array(C);b<C;b++)k[b]=_[b].fn;return k},p.prototype.listenerCount=function(m){var E=r?r+m:m,_=this._events[E];return _?_.fn?1:_.length:0},p.prototype.emit=function(m,E,_,b,C,k){var x=r?r+m:m;if(!this._events[x])return!1;var P,J,Q=this._events[x],De=arguments.length;if(Q.fn){switch(Q.once&&this.removeListener(m,Q.fn,void 0,!0),De){case 1:return Q.fn.call(Q.context),!0;case 2:return Q.fn.call(Q.context,E),!0;case 3:return Q.fn.call(Q.context,E,_),!0;case 4:return Q.fn.call(Q.context,E,_,b),!0;case 5:return Q.fn.call(Q.context,E,_,b,C),!0;case 6:return Q.fn.call(Q.context,E,_,b,C,k),!0}for(J=1,P=new Array(De-1);J<De;J++)P[J-1]=arguments[J];Q.fn.apply(Q.context,P)}else{var Ce,me=Q.length;for(J=0;J<me;J++)switch(Q[J].once&&this.removeListener(m,Q[J].fn,void 0,!0),De){case 1:Q[J].fn.call(Q[J].context);break;case 2:Q[J].fn.call(Q[J].context,E);break;case 3:Q[J].fn.call(Q[J].context,E,_);break;case 4:Q[J].fn.call(Q[J].context,E,_,b);break;default:if(!P)for(Ce=1,P=new Array(De-1);Ce<De;Ce++)P[Ce-1]=arguments[Ce];Q[J].fn.apply(Q[J].context,P)}}return!0},p.prototype.on=function(m,E,_){return n(this,m,E,_,!1)},p.prototype.once=function(m,E,_){return n(this,m,E,_,!0)},p.prototype.removeListener=function(m,E,_,b){var C=r?r+m:m;if(!this._events[C])return this;if(!E)return d(this,C),this;var k=this._events[C];if(k.fn)k.fn!==E||b&&!k.once||_&&k.context!==_||d(this,C);else{for(var x=0,P=[],J=k.length;x<J;x++)(k[x].fn!==E||b&&!k[x].once||_&&k[x].context!==_)&&P.push(k[x]);P.length?this._events[C]=P.length===1?P[0]:P:d(this,C)}return this},p.prototype.removeAllListeners=function(m){var E;return m?(E=r?r+m:m,this._events[E]&&d(this,E)):(this._events=new o,this._eventsCount=0),this},p.prototype.off=p.prototype.removeListener,p.prototype.addListener=p.prototype.on,p.prefixed=r,p.EventEmitter=p,t!==void 0&&(t.exports=p)}}),_I=gI(EI(),1),Mf=Symbol("instance"),RM=Symbol("abortCtrl"),kd=Symbol("cacheResult"),Um=class{constructor(i,t,e){this.oldState=i,this.newState=t,this.action=e,this.aborted=!1}abort(i){this.aborted=!0,va.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},Ld=class extends Error{constructor(i,t,e){super(t),this.state=i,this.message=t,this.cause=e}};function TI(i){return typeof i=="object"&&i&&"then"in i}var Ra=new Map;function Ji(i,t,e={}){return(r,o,s)=>{let n=e.action||o;if(!e.context){let p=Ra.get(r)||[];Ra.has(r)||Ra.set(r,p),p.push({from:i,to:t,action:n})}let d=s.value;s.value=function(...p){let m=this;if(e.context&&(m=Ht.get(typeof e.context=="function"?e.context.call(this,...p):e.context)),m.state===t)return e.sync?m[kd]:Promise.resolve(m[kd]);m.state instanceof Um&&m.state.action==e.abortAction&&m.state.abort(m);let E=null;Array.isArray(i)?i.length==0?m.state instanceof Um&&m.state.abort(m):typeof m.state=="string"&&i.includes(m.state)||(E=new Ld(m._state,`${m.name} ${n} to ${t} failed: current state ${m._state} not from ${i.join("|")}`)):i!==m.state&&(E=new Ld(m._state,`${m.name} ${n} to ${t} failed: current state ${m._state} not from ${i}`));let _=P=>{if(e.fail&&e.fail.call(this,P),e.sync){if(e.ignoreError)return P;throw P}return e.ignoreError?Promise.resolve(P):Promise.reject(P)};if(E)return _(E);let b=m.state,C=new Um(b,t,n);va.call(m,C);let k=P=>{var J;return m[kd]=P,C.aborted||(va.call(m,t),(J=e.success)===null||J===void 0||J.call(this,m[kd])),P},x=P=>(va.call(m,b,P),_(P));try{let P=d.apply(this,p);return TI(P)?P.then(k).catch(x):e.sync?k(P):Promise.resolve(k(P))}catch(P){return x(new Ld(m._state,`${m.name} ${n} from ${i} to ${t} failed: ${P}`,P instanceof Error?P:new Error(String(P))))}}}}function II(...i){return(t,e,r)=>{let o=r.value,s=e;r.value=function(...n){if(!i.includes(this.state.toString()))throw new Ld(this.state,`${this.name} ${s} failed: current state ${this.state} not in ${i}`);return o.apply(this,n)}}}var SI=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 va(i,t){let e=this._state;this._state=i;let r=i.toString();i&&this.emit(r,e),this.emit(Ht.STATECHANGED,i,e,t),this.updateDevTools({value:i,old:e,err:t instanceof Error?t.message:String(t)})}var Ht=class or extends _I.default{constructor(t,e,r){super(),this.name=t,this.groupName=e,this._state=or.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[Mf];o?this.name=o.name+"-"+o.count++:r[Mf]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let t=Object.getPrototypeOf(this),e=Ra.get(t)||[],r=new Set,o=[],s=[],n=new Set,d=Object.getPrototypeOf(t);Ra.has(d)&&(d.stateDiagram.forEach(m=>r.add(m)),d.allStates.forEach(m=>n.add(m))),e.forEach(({from:m,to:E,action:_})=>{typeof m=="string"?o.push({from:m,to:E,action:_}):m.length?m.forEach(b=>{o.push({from:b,to:E,action:_})}):s.push({to:E,action:_})}),o.forEach(({from:m,to:E,action:_})=>{n.add(m),n.add(E),n.add(_+"ing"),r.add(`${m} --> ${_}ing : ${_}`),r.add(`${_}ing --> ${E} : ${_} \u{1F7E2}`),r.add(`${_}ing --> ${m} : ${_} \u{1F534}`)}),s.forEach(({to:m,action:E})=>{r.add(`${E}ing --> ${m} : ${E} \u{1F7E2}`),n.forEach(_=>{_!==m&&r.add(`${_} --> ${E}ing : ${E}`)})});let p=[...r];return Object.defineProperties(t,{stateDiagram:{value:p},allStates:{value:n}}),p}static get(t){let e;return typeof t=="string"?(e=or.instances.get(t),e||or.instances.set(t,e=new or(t,void 0,Object.create(or.prototype)))):(e=or.instances2.get(t),e||or.instances2.set(t,e=new or(t.constructor.name,void 0,Object.create(or.prototype)))),e}static getState(t){var e;return(e=or.get(t))===null||e===void 0?void 0:e.state}updateDevTools(t={}){SI(or.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},t))}get state(){return this._state}set state(t){va.call(this,t)}};Ht.STATECHANGED="stateChanged",Ht.UPDATEAFSM="updateAFSM",Ht.INIT="[*]",Ht.ON="on",Ht.OFF="off",Ht.instances=new Map,Ht.instances2=new WeakMap;var qs=class extends Ht{constructor(){super(...arguments),Ar(this,"decoder"),Ar(this,"config")}initialize(){return y(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(ba(Aa({},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 yI(){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,d=0,p={wasmBinary:o,postRun:()=>{i=new p.VideoDecoder({videoInfo(m,E){n=m,d=E,console.log("video info",m,E)},yuvData(m,E){let _=n*d,b=_>>2,C=p.HEAPU32[m>>2],k=p.HEAPU32[1+(m>>2)],x=p.HEAPU32[2+(m>>2)],P=p.HEAPU8.subarray(C,C+_),J=p.HEAPU8.subarray(k,k+b),Q=p.HEAPU8.subarray(x,x+b),De=new Uint8Array(_+b+b);De.set(P),De.set(J,_),De.set(Q,_+b);let Ce=new VideoFrame(De,{codedWidth:n,codedHeight:d,format:"I420",timestamp:E});e?(s==null||s.drawImage(Ce,0,0,e.width,e.height),s==null||s.commit()):self.postMessage({type:"yuvData",videoFrame:Ce},[Ce])}}),self.postMessage({type:"ready"})}};Function("var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined;return "+r)()(p)}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:"")}}}mi([Ji([Ht.INIT,"closed"],"initialized")],qs.prototype,"initialize",1),mi([Ji("initialized","configured",{sync:!0})],qs.prototype,"configure",1),mi([II("configured")],qs.prototype,"decode",1),mi([Ji([],Ht.INIT)],qs.prototype,"reset",1),mi([Ji([],"closed",{ignoreError:!0,sync:!0})],qs.prototype,"close",1);var Js=class extends Ht{constructor(i,t,e=!1,r,o=!1){super(),this.createModule=i,this.wasmBinary=t,this.workerMode=e,this.canvas=r,this.yuvMode=o,Ar(this,"worker"),Ar(this,"decoder"),Ar(this,"config"),Ar(this,"module",{}),Ar(this,"width",0),Ar(this,"height",0)}initialize(i){return y(this,null,function*(){var t;if(this.workerMode){let r=new RegExp("\\{(.+)\\}","s").exec(yI.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=d=>{if(d.data.type==="ready")delete this.wasmBinary,n(),console.warn("worker mode initialize success");else if(d.data.type==="yuvData"){let{videoFrame:p}=d.data;this.emit("videoFrame",p)}}})}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,(e=this.decoder)==null||e.setCodec(this.config.codec,this.config.description?"avcc":"annexb",(t=this.config.description)!=null?t:""),(r=this.worker)==null||r.postMessage({type:"setCodec",codec:this.config.codec,format:this.config.description?"avcc":"annexb",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)],d=this.module.HEAPU8.subarray(o,o+e),p=this.module.HEAPU8.subarray(s,s+r),m=this.module.HEAPU8.subarray(n,n+r);if(this.yuvMode)return void this.emit("videoFrame",[d,p,m]);let E=new Uint8Array(e+r+r);E.set(d),E.set(p,e),E.set(m,e+r),this.emit("videoFrame",new VideoFrame(E,{codedWidth:this.width,codedHeight:this.height,format:"I420",timestamp:t}))}errorInfo(i){let t={errMsg:i};this.emit("error",t)}};mi([Ji([Ht.INIT,"closed"],"initialized")],Js.prototype,"initialize",1),mi([Ji("initialized","configured")],Js.prototype,"configure",1),mi([Ji([],Ht.INIT)],Js.prototype,"reset",1),mi([Ji([],"closed")],Js.prototype,"close",1);var AI=(()=>{var i=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return function(t={}){var e,r,o=t;o.ready=new Promise((a,c)=>{e=a,r=c});var s,n,d,p=Object.assign({},o),m="./this.program",E=typeof window=="object",_=typeof importScripts=="function",b=(typeof process=="object"&&typeof process.versions=="object"&&process.versions.node,"");(E||_)&&(_?b=self.location.href:typeof document!="undefined"&&document.currentScript&&(b=document.currentScript.src),i&&(b=i),b=b.indexOf("blob:")!==0?b.substr(0,b.replace(/[?#].*/,"").lastIndexOf("/")+1):"",s=a=>{var c=new XMLHttpRequest;return c.open("GET",a,!1),c.send(null),c.responseText},_&&(d=a=>{var c=new XMLHttpRequest;return c.open("GET",a,!1),c.responseType="arraybuffer",c.send(null),new Uint8Array(c.response)}),n=(a,c,l)=>{var h=new XMLHttpRequest;h.open("GET",a,!0),h.responseType="arraybuffer",h.onload=()=>{h.status==200||h.status==0&&h.response?c(h.response):l()},h.onerror=l,h.send(null)});var C,k=o.print||console.log.bind(console),x=o.printErr||console.error.bind(console);Object.assign(o,p),p=null,o.arguments&&o.arguments,o.thisProgram&&(m=o.thisProgram),o.quit&&o.quit,o.wasmBinary&&(C=o.wasmBinary);var P,J;o.noExitRuntime,typeof WebAssembly!="object"&&Cr("no native wasm support detected");var Q,De,Ce,me,Pe,Be,en,tn,rn,on=!1,vr=[],Qo=[],fi=[],ee=0,Hr=null,Wr=null;function sn(a){ee++,o.monitorRunDependencies&&o.monitorRunDependencies(ee)}function to(a){if(ee--,o.monitorRunDependencies&&o.monitorRunDependencies(ee),ee==0&&(Hr!==null&&(clearInterval(Hr),Hr=null),Wr)){var c=Wr;Wr=null,c()}}function Cr(a){o.onAbort&&o.onAbort(a),x(a="Aborted("+a+")"),on=!0,a+=". Build with -sASSERTIONS for more info.";var c=new WebAssembly.RuntimeError(a);throw r(c),c}var gi,ro,ge,Ge,Va="data:application/octet-stream;base64,";function G(a){return a.startsWith(Va)}function Gr(a){if(a==gi&&C)return new Uint8Array(C);if(d)return d(a);throw"both async and sync fetching of the wasm failed"}function Nr(a,c,l){return function(h){return C||!E&&!_||typeof fetch!="function"?Promise.resolve().then(()=>Gr(h)):fetch(h,{credentials:"same-origin"}).then(I=>{if(!I.ok)throw"failed to load wasm binary file at '"+h+"'";return I.arrayBuffer()}).catch(()=>Gr(h))}(a).then(h=>WebAssembly.instantiate(h,c)).then(h=>h).then(l,h=>{x("failed to asynchronously prepare wasm: "+h),Cr(h)})}G(gi="videodec.wasm")||(ro=gi,gi=o.locateFile?o.locateFile(ro,b):b+ro);var Ei=a=>{for(;a.length>0;)a.shift()(o)};function _i(a){this.excPtr=a,this.ptr=a-24,this.set_type=function(c){Be[this.ptr+4>>2]=c},this.get_type=function(){return Be[this.ptr+4>>2]},this.set_destructor=function(c){Be[this.ptr+8>>2]=c},this.get_destructor=function(){return Be[this.ptr+8>>2]},this.set_caught=function(c){c=c?1:0,Q[this.ptr+12|0]=c},this.get_caught=function(){return Q[this.ptr+12|0]!=0},this.set_rethrown=function(c){c=c?1:0,Q[this.ptr+13|0]=c},this.get_rethrown=function(){return Q[this.ptr+13|0]!=0},this.init=function(c,l){this.set_adjusted_ptr(0),this.set_type(c),this.set_destructor(l)},this.set_adjusted_ptr=function(c){Be[this.ptr+16>>2]=c},this.get_adjusted_ptr=function(){return Be[this.ptr+16>>2]},this.get_exception_ptr=function(){if(gn(this.get_type()))return Be[this.excPtr>>2];var c=this.get_adjusted_ptr();return c!==0?c:this.excPtr}}var V={isAbs:a=>a.charAt(0)==="/",splitPath:a=>/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(a).slice(1),normalizeArray:(a,c)=>{for(var l=0,h=a.length-1;h>=0;h--){var I=a[h];I==="."?a.splice(h,1):I===".."?(a.splice(h,1),l++):l&&(a.splice(h,1),l--)}if(c)for(;l;l--)a.unshift("..");return a},normalize:a=>{var c=V.isAbs(a),l=a.substr(-1)==="/";return(a=V.normalizeArray(a.split("/").filter(h=>!!h),!c).join("/"))||c||(a="."),a&&l&&(a+="/"),(c?"/":"")+a},dirname:a=>{var c=V.splitPath(a),l=c[0],h=c[1];return l||h?(h&&(h=h.substr(0,h.length-1)),l+h):"."},basename:a=>{if(a==="/")return"/";var c=(a=(a=V.normalize(a)).replace(/\/$/,"")).lastIndexOf("/");return c===-1?a:a.substr(c+1)},join:function(){var a=Array.prototype.slice.call(arguments);return V.normalize(a.join("/"))},join2:(a,c)=>V.normalize(a+"/"+c)},nn=a=>(nn=(()=>{if(typeof crypto=="object"&&typeof crypto.getRandomValues=="function")return c=>crypto.getRandomValues(c);Cr("initRandomDevice")})())(a),Wt={resolve:function(){for(var a="",c=!1,l=arguments.length-1;l>=-1&&!c;l--){var h=l>=0?arguments[l]:f.cwd();if(typeof h!="string")throw new TypeError("Arguments to path.resolve must be strings");if(!h)return"";a=h+"/"+a,c=V.isAbs(h)}return(c?"/":"")+(a=V.normalizeArray(a.split("/").filter(I=>!!I),!c).join("/"))||"."},relative:(a,c)=>{function l(w){for(var z=0;z<w.length&&w[z]==="";z++);for(var ie=w.length-1;ie>=0&&w[ie]==="";ie--);return z>ie?[]:w.slice(z,ie-z+1)}a=Wt.resolve(a).substr(1),c=Wt.resolve(c).substr(1);for(var h=l(a.split("/")),I=l(c.split("/")),S=Math.min(h.length,I.length),A=S,R=0;R<S;R++)if(h[R]!==I[R]){A=R;break}var M=[];for(R=A;R<h.length;R++)M.push("..");return(M=M.concat(I.slice(A))).join("/")}},Ti=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):void 0,Dt=(a,c,l)=>{for(var h=c+l,I=c;a[I]&&!(I>=h);)++I;if(I-c>16&&a.buffer&&Ti)return Ti.decode(a.subarray(c,I));for(var S="";c<I;){var A=a[c++];if(128&A){var R=63&a[c++];if((224&A)!=192){var M=63&a[c++];if((A=(240&A)==224?(15&A)<<12|R<<6|M:(7&A)<<18|R<<12|M<<6|63&a[c++])<65536)S+=String.fromCharCode(A);else{var w=A-65536;S+=String.fromCharCode(55296|w>>10,56320|1023&w)}}else S+=String.fromCharCode((31&A)<<6|R)}else S+=String.fromCharCode(A)}return S},an=[],io=a=>{for(var c=0,l=0;l<a.length;++l){var h=a.charCodeAt(l);h<=127?c++:h<=2047?c+=2:h>=55296&&h<=57343?(c+=4,++l):c+=3}return c},oo=(a,c,l,h)=>{if(!(h>0))return 0;for(var I=l,S=l+h-1,A=0;A<a.length;++A){var R=a.charCodeAt(A);if(R>=55296&&R<=57343&&(R=65536+((1023&R)<<10)|1023&a.charCodeAt(++A)),R<=127){if(l>=S)break;c[l++]=R}else if(R<=2047){if(l+1>=S)break;c[l++]=192|R>>6,c[l++]=128|63&R}else if(R<=65535){if(l+2>=S)break;c[l++]=224|R>>12,c[l++]=128|R>>6&63,c[l++]=128|63&R}else{if(l+3>=S)break;c[l++]=240|R>>18,c[l++]=128|R>>12&63,c[l++]=128|R>>6&63,c[l++]=128|63&R}}return c[l]=0,l-I};function Yo(a,c,l){var h=l>0?l:io(a)+1,I=new Array(h),S=oo(a,I,0,I.length);return c&&(I.length=S),I}var nr={ttys:[],init:function(){},shutdown:function(){},register:function(a,c){nr.ttys[a]={input:[],output:[],ops:c},f.registerDevice(a,nr.stream_ops)},stream_ops:{open:function(a){var c=nr.ttys[a.node.rdev];if(!c)throw new f.ErrnoError(43);a.tty=c,a.seekable=!1},close:function(a){a.tty.ops.fsync(a.tty)},fsync:function(a){a.tty.ops.fsync(a.tty)},read:function(a,c,l,h,I){if(!a.tty||!a.tty.ops.get_char)throw new f.ErrnoError(60);for(var S=0,A=0;A<h;A++){var R;try{R=a.tty.ops.get_char(a.tty)}catch(M){throw new f.ErrnoError(29)}if(R===void 0&&S===0)throw new f.ErrnoError(6);if(R==null)break;S++,c[l+A]=R}return S&&(a.node.timestamp=Date.now()),S},write:function(a,c,l,h,I){if(!a.tty||!a.tty.ops.put_char)throw new f.ErrnoError(60);try{for(var S=0;S<h;S++)a.tty.ops.put_char(a.tty,c[l+S])}catch(A){throw new f.ErrnoError(29)}return h&&(a.node.timestamp=Date.now()),S}},default_tty_ops:{get_char:function(a){return(()=>{if(!an.length){var c=null;if(typeof window!="undefined"&&typeof window.prompt=="function"?(c=window.prompt("Input: "))!==null&&(c+=`
|
|
49
|
+
} `;var jo=class extends ne{constructor(e){super();u(this,"frameRate");u(this,"_canvas");u(this,"log");u(this,"hasAlpha",!1);u(this,"name");u(this,"error");this.name=e.name,this.log=e.logger.createChild({id:`vc-${this.name}`}),this.frameRate=e.frameRate}set width(e){this._canvas&&(this._canvas.width=e)}get width(){var e;return((e=this._canvas)==null?void 0:e.width)||0}set height(e){this._canvas&&(this._canvas.height=e)}get height(){var e;return((e=this._canvas)==null?void 0:e.height)||0}setSize(e,r){this._canvas&&(this._canvas.width=e,this._canvas.height=r)}createVideoTrackSource(e,r){return new pi(this,e,{logger:this.log,name:r})}createVideoTrackDestination(e){return new Gs(this,e)}createVideoImageSource(e,r){return new ya(this,r?Object.assign(r,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,r){return new Aa(this,e,r?Object.assign(r,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}};u(jo,"_ids",0);var lI={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},js=class js extends jo{constructor(){super(...arguments);u(this,"defaultProgam");u(this,"defaultVShader");u(this,"defaultFShader");u(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${jo._ids++}`),this.ctx=this._canvas.getContext("webgl2",lI),!this.ctx)throw new he({code:te.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,dI),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,uI),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new he({code:te.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})}destroy(e){let r="";return e&&(r=e.message,this.error=e,Y.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}set height(e){var r;(r=this.ctx)==null||r.viewport(0,0,this.width,e),super.height=e}setSize(e,r){var o;(o=this.ctx)==null||o.viewport(0,0,e,r),super.setSize(e,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}};u(js,"UNAVAILABLE","unavailable"),X([qe(ne.INIT,"created",{sync:!0,fail(e){this.log.error("video gl context create failed",e.cause),Y.addFailedEvent({key:512700,error:e.cause||e})},success(){this.log.info("video context created use webgl"),Y.addSuccessEvent({key:512700})}})],js.prototype,"create",1),X([qe("created",ne.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(js.UNAVAILABLE,e),this.removeAllListeners()}})],js.prototype,"destroy",1);var Et=js,kt=class extends jo{constructor(){super(...arguments);u(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${jo._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new he({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,Y.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(),Y.addSuccessEvent({key:512703})}};X([qe(ne.INIT,"created",{sync:!0,fail(e){this.log.error("video 2d context create failed",e.cause),Y.addFailedEvent({key:512701,error:e.cause||e})},success(){this.log.info("video context created use 2d"),Y.addSuccessEvent({key:512701})}})],kt.prototype,"create",1),X([qe("created",ne.INIT,{ignoreError:!0,sync:!0})],kt.prototype,"destroy",1);function mI(i){return[15,30,45,60].reduce((e,r)=>Math.abs(r-i)<Math.abs(e-i)?r:e)}var Xi=class extends Ws{constructor(e,r,o=4){super(e,r,o);u(this,"mediaType",4);u(this,"source");u(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.videoManager,this.once("first-video-frame",s=>{this.room.emit("first-video-frame",s)})}play(e,r){return(nt(r==null?void 0:r.canvasRender)?r.canvasRender:Yt===17)&&!this.source&&this.useCanvasPlayer(),super.play(e,r).then(()=>{this.player.calculateStat()})}useCanvasPlayer(){if(this.log.info(`useCanvasPlayer(), has element:${!!this.player.element}`),!this.player.element)return;let e=new kt({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});let r=new Go(e,{name:"remotePlayer",logger:this.log});this.source=e.createVideoPlayerSource(this.player),this.source.connect(r),this.player.setCanvas(e._canvas),Oo()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let r=this.decodeFPS,o=mI(r);if(!je(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(d=>d.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(d=>d.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),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)}onDecodeDowngradeStateChanged(e){this.emit("decode-downgrade-state-changed",e)}},xd=class extends Xi{constructor(e,r){super(e,r,2);u(this,"mediaType",2);u(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}};var qs=new Map;H.on(L.JOIN_SUCCESS,({room:i})=>{tt(i.userId,{eventId:32788})});H.on(L.LEAVE_START,({room:i})=>{tt(i.userId,{eventId:32789})});H.on(L.LOCAL_TRACK_PUBLISHED,({track:i})=>{if(i.room){let t=32769;i.mediaType===4?t=32768:i.mediaType===2&&(t=32805),tt(i.room.userId,{eventId:t})}});H.on(L.LOCAL_TRACK_UNPUBLISHED,({track:i})=>{if(i.room){let t=32771;i.mediaType===4?t=32770:i.mediaType===2&&(t=32806),tt(i.room.userId,{eventId:t})}});H.on(L.TRACK_MUTED,({track:i})=>{i.room&&(i.kind===D.AUDIO?tt(i.room.userId,{eventId:i.isRemote?32785:32772,remoteUserId:i.isRemote?i.userId:void 0}):tt(i.room.userId,{eventId:i.isRemote?32784:32773,remoteUserId:i.isRemote?i.userId:void 0}))});H.on(L.TRACK_UNMUTED,({track:i})=>{i.room&&(i.kind===D.AUDIO?tt(i.room.userId,{eventId:i.isRemote?32787:32774,remoteUserId:i.isRemote?i.userId:void 0}):tt(i.room.userId,{eventId:i.isRemote?32786:32775,remoteUserId:i.isRemote?i.userId:void 0}))});H.on(L.REMOTE_TRACK_SUBSCRIBED,({track:i})=>{i.room&&(i.mediaType===1&&tt(i.room.userId,{eventId:32777,remoteUserId:i.userId}),i.mediaType===4&&tt(i.room.userId,{eventId:32776,remoteUserId:i.userId}),i.mediaType===8&&tt(i.room.userId,{eventId:32803,remoteUserId:i.userId}))});H.on(L.REMOTE_TRACK_UNSUBSCRIBED,({track:i})=>{i.room&&(i.mediaType===1&&tt(i.room.userId,{eventId:32779,remoteUserId:i.userId}),i.mediaType===4&&tt(i.room.userId,{eventId:32778,remoteUserId:i.userId}),i.mediaType===8&&tt(i.room.userId,{eventId:32804,remoteUserId:i.userId}))});H.on(L.SWITCH_DEVICE_SUCCESS,({track:i})=>{i.room&&tt(i.room.userId,{eventId:i.kind===D.VIDEO?32780:32781})});H.on(L.LOCAL_TRACK_REPLACED,({track:i})=>{i.room&&tt(i.room.userId,{eventId:i.kind===D.VIDEO?32782:32783})});H.on(L.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&&tt(i.userId,{eventId:r})});H.on(L.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&&tt(i.userId,{eventId:s,remoteUserId:r})});H.on(L.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({implementation:i,userId:t,remoteUserId:e,codec:r,isHWCodec:o,prevImplementation:s,streamType:n})=>{let d=o?1:0;s||(d=o?3:2);let p=r==="h264"?0:2,m={eventId:4004,param1:d,param2:p,streamType:n||2};e&&(m.remoteUserId=e,m.eventId=4005),tt(t,m),Y.addEnum({key:e?514701:513701,value:d}),Y.addEnum({key:e?514700:513700,value:p})});H.on(L.LOCAL_TRACK_RECAPTURE,({track:i,error:t})=>{if(i.userId){let e={eventId:2003,param1:0};i.kind===D.AUDIO?(e.streamType=1,t&&(e.param1=2)):(e.streamType=i.streamType==="auxiliary"?7:2,t&&(e.param1=8)),tt(i.userId,e)}});function tt(i,t){let e=Ee(ee({},t),{timestamp:Tn()});qs.has(i)?qs.get(i).push(e):qs.set(i,[e])}function wf(i){if(qs.has(i)){let t=qs.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 qs.delete(i),t}return[]}var pI=Mi($i(),1);var hI=Object.create,Vd=Object.defineProperty,fI=Object.defineProperties,Pf=Object.getOwnPropertyDescriptor,gI=Object.getOwnPropertyDescriptors,kf=Object.getOwnPropertyNames,Mf=Object.getOwnPropertySymbols,EI=Object.getPrototypeOf,Lf=Object.prototype.hasOwnProperty,_I=Object.prototype.propertyIsEnumerable,$m=(i,t,e)=>t in i?Vd(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e,kd=(i,t)=>{for(var e in t||(t={}))Lf.call(t,e)&&$m(i,e,t[e]);if(Mf)for(var e of Mf(t))_I.call(t,e)&&$m(i,e,t[e]);return i},Ld=(i,t)=>fI(i,gI(t)),TI=(i,t)=>function(){return t||(0,i[kf(i)[0]])((t={exports:{}}).exports,t),t.exports},II=(i,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of kf(t))Lf.call(i,o)||o===e||Vd(i,o,{get:()=>t[o],enumerable:!(r=Pf(t,o))||r.enumerable});return i},SI=(i,t,e)=>(e=i!=null?hI(EI(i)):{},II(!t&&i&&i.__esModule?e:Vd(e,"default",{value:i,enumerable:!0}),i)),hi=(i,t,e,r)=>{for(var o,s=r>1?void 0:r?Pf(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&&Vd(t,e,s),s},br=(i,t,e)=>$m(i,typeof t!="symbol"?t+"":t,e),yI=TI({"../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(m,g,_){this.fn=m,this.context=g,this.once=_||!1}function n(m,g,_,b,N){if(typeof _!="function")throw new TypeError("The listener must be a function");var k=new s(_,b||m,N),P=r?r+g:g;return m._events[P]?m._events[P].fn?m._events[P]=[m._events[P],k]:m._events[P].push(k):(m._events[P]=k,m._eventsCount++),m}function d(m,g){--m._eventsCount==0?m._events=new o:delete m._events[g]}function p(){this._events=new o,this._eventsCount=0}Object.create&&(o.prototype=Object.create(null),new o().__proto__||(r=!1)),p.prototype.eventNames=function(){var m,g,_=[];if(this._eventsCount===0)return _;for(g in m=this._events)e.call(m,g)&&_.push(r?g.slice(1):g);return Object.getOwnPropertySymbols?_.concat(Object.getOwnPropertySymbols(m)):_},p.prototype.listeners=function(m){var g=r?r+m:m,_=this._events[g];if(!_)return[];if(_.fn)return[_.fn];for(var b=0,N=_.length,k=new Array(N);b<N;b++)k[b]=_[b].fn;return k},p.prototype.listenerCount=function(m){var g=r?r+m:m,_=this._events[g];return _?_.fn?1:_.length:0},p.prototype.emit=function(m,g,_,b,N,k){var P=r?r+m:m;if(!this._events[P])return!1;var x,J,Q=this._events[P],Ne=arguments.length;if(Q.fn){switch(Q.once&&this.removeListener(m,Q.fn,void 0,!0),Ne){case 1:return Q.fn.call(Q.context),!0;case 2:return Q.fn.call(Q.context,g),!0;case 3:return Q.fn.call(Q.context,g,_),!0;case 4:return Q.fn.call(Q.context,g,_,b),!0;case 5:return Q.fn.call(Q.context,g,_,b,N),!0;case 6:return Q.fn.call(Q.context,g,_,b,N,k),!0}for(J=1,x=new Array(Ne-1);J<Ne;J++)x[J-1]=arguments[J];Q.fn.apply(Q.context,x)}else{var De,me=Q.length;for(J=0;J<me;J++)switch(Q[J].once&&this.removeListener(m,Q[J].fn,void 0,!0),Ne){case 1:Q[J].fn.call(Q[J].context);break;case 2:Q[J].fn.call(Q[J].context,g);break;case 3:Q[J].fn.call(Q[J].context,g,_);break;case 4:Q[J].fn.call(Q[J].context,g,_,b);break;default:if(!x)for(De=1,x=new Array(Ne-1);De<Ne;De++)x[De-1]=arguments[De];Q[J].fn.apply(Q[J].context,x)}}return!0},p.prototype.on=function(m,g,_){return n(this,m,g,_,!1)},p.prototype.once=function(m,g,_){return n(this,m,g,_,!0)},p.prototype.removeListener=function(m,g,_,b){var N=r?r+m:m;if(!this._events[N])return this;if(!g)return d(this,N),this;var k=this._events[N];if(k.fn)k.fn!==g||b&&!k.once||_&&k.context!==_||d(this,N);else{for(var P=0,x=[],J=k.length;P<J;P++)(k[P].fn!==g||b&&!k[P].once||_&&k[P].context!==_)&&x.push(k[P]);x.length?this._events[N]=x.length===1?x[0]:x:d(this,N)}return this},p.prototype.removeAllListeners=function(m){var g;return m?(g=r?r+m:m,this._events[g]&&d(this,g)):(this._events=new o,this._eventsCount=0),this},p.prototype.off=p.prototype.removeListener,p.prototype.addListener=p.prototype.on,p.prefixed=r,p.EventEmitter=p,t!==void 0&&(t.exports=p)}}),AI=SI(yI(),1),Of=Symbol("instance"),RM=Symbol("abortCtrl"),Pd=Symbol("cacheResult"),Fm=class{constructor(i,t,e){this.oldState=i,this.newState=t,this.action=e,this.aborted=!1}abort(i){this.aborted=!0,va.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},Ud=class extends Error{constructor(i,t,e){super(t),this.state=i,this.message=t,this.cause=e}};function bI(i){return typeof i=="object"&&i&&"then"in i}var Ra=new Map;function Qi(i,t,e={}){return(r,o,s)=>{let n=e.action||o;if(!e.context){let p=Ra.get(r)||[];Ra.has(r)||Ra.set(r,p),p.push({from:i,to:t,action:n})}let d=s.value;s.value=function(...p){let m=this;if(e.context&&(m=Ht.get(typeof e.context=="function"?e.context.call(this,...p):e.context)),m.state===t)return e.sync?m[Pd]:Promise.resolve(m[Pd]);m.state instanceof Fm&&m.state.action==e.abortAction&&m.state.abort(m);let g=null;Array.isArray(i)?i.length==0?m.state instanceof Fm&&m.state.abort(m):typeof m.state=="string"&&i.includes(m.state)||(g=new Ud(m._state,`${m.name} ${n} to ${t} failed: current state ${m._state} not from ${i.join("|")}`)):i!==m.state&&(g=new Ud(m._state,`${m.name} ${n} to ${t} failed: current state ${m._state} not from ${i}`));let _=x=>{if(e.fail&&e.fail.call(this,x),e.sync){if(e.ignoreError)return x;throw x}return e.ignoreError?Promise.resolve(x):Promise.reject(x)};if(g)return _(g);let b=m.state,N=new Fm(b,t,n);va.call(m,N);let k=x=>{var J;return m[Pd]=x,N.aborted||(va.call(m,t),(J=e.success)===null||J===void 0||J.call(this,m[Pd])),x},P=x=>(va.call(m,b,x),_(x));try{let x=d.apply(this,p);return bI(x)?x.then(k).catch(P):e.sync?k(x):Promise.resolve(k(x))}catch(x){return P(new Ud(m._state,`${m.name} ${n} from ${i} to ${t} failed: ${x}`,x instanceof Error?x:new Error(String(x))))}}}}function RI(...i){return(t,e,r)=>{let o=r.value,s=e;r.value=function(...n){if(!i.includes(this.state.toString()))throw new Ud(this.state,`${this.name} ${s} failed: current state ${this.state} not in ${i}`);return o.apply(this,n)}}}var vI=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 va(i,t){let e=this._state;this._state=i;let r=i.toString();i&&this.emit(r,e),this.emit(Ht.STATECHANGED,i,e,t),this.updateDevTools({value:i,old:e,err:t instanceof Error?t.message:String(t)})}var Ht=class sr extends AI.default{constructor(t,e,r){super(),this.name=t,this.groupName=e,this._state=sr.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[Of];o?this.name=o.name+"-"+o.count++:r[Of]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let t=Object.getPrototypeOf(this),e=Ra.get(t)||[],r=new Set,o=[],s=[],n=new Set,d=Object.getPrototypeOf(t);Ra.has(d)&&(d.stateDiagram.forEach(m=>r.add(m)),d.allStates.forEach(m=>n.add(m))),e.forEach(({from:m,to:g,action:_})=>{typeof m=="string"?o.push({from:m,to:g,action:_}):m.length?m.forEach(b=>{o.push({from:b,to:g,action:_})}):s.push({to:g,action:_})}),o.forEach(({from:m,to:g,action:_})=>{n.add(m),n.add(g),n.add(_+"ing"),r.add(`${m} --> ${_}ing : ${_}`),r.add(`${_}ing --> ${g} : ${_} \u{1F7E2}`),r.add(`${_}ing --> ${m} : ${_} \u{1F534}`)}),s.forEach(({to:m,action:g})=>{r.add(`${g}ing --> ${m} : ${g} \u{1F7E2}`),n.forEach(_=>{_!==m&&r.add(`${_} --> ${g}ing : ${g}`)})});let p=[...r];return Object.defineProperties(t,{stateDiagram:{value:p},allStates:{value:n}}),p}static get(t){let e;return typeof t=="string"?(e=sr.instances.get(t),e||sr.instances.set(t,e=new sr(t,void 0,Object.create(sr.prototype)))):(e=sr.instances2.get(t),e||sr.instances2.set(t,e=new sr(t.constructor.name,void 0,Object.create(sr.prototype)))),e}static getState(t){var e;return(e=sr.get(t))===null||e===void 0?void 0:e.state}updateDevTools(t={}){vI(sr.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},t))}get state(){return this._state}set state(t){va.call(this,t)}};Ht.STATECHANGED="stateChanged",Ht.UPDATEAFSM="updateAFSM",Ht.INIT="[*]",Ht.ON="on",Ht.OFF="off",Ht.instances=new Map,Ht.instances2=new WeakMap;var Js=class extends Ht{constructor(){super(...arguments),br(this,"decoder"),br(this,"config")}initialize(){return y(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(Ld(kd({},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 CI(){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,d=0,p={wasmBinary:o,postRun:()=>{i=new p.VideoDecoder({videoInfo(m,g){n=m,d=g,console.log("video info",m,g)},yuvData(m,g){let _=n*d,b=_>>2,N=p.HEAPU32[m>>2],k=p.HEAPU32[1+(m>>2)],P=p.HEAPU32[2+(m>>2)],x=p.HEAPU8.subarray(N,N+_),J=p.HEAPU8.subarray(k,k+b),Q=p.HEAPU8.subarray(P,P+b),Ne=new Uint8Array(_+b+b);Ne.set(x),Ne.set(J,_),Ne.set(Q,_+b);let De=new VideoFrame(Ne,{codedWidth:n,codedHeight:d,format:"I420",timestamp:g});e?(s==null||s.drawImage(De,0,0,e.width,e.height),s==null||s.commit()):self.postMessage({type:"yuvData",videoFrame:De},[De])}}),self.postMessage({type:"ready"})}};Function("var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined;return "+r)()(p)}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:"")}}}hi([Qi([Ht.INIT,"closed"],"initialized")],Js.prototype,"initialize",1),hi([Qi("initialized","configured",{sync:!0})],Js.prototype,"configure",1),hi([RI("configured")],Js.prototype,"decode",1),hi([Qi([],Ht.INIT,{sync:!0})],Js.prototype,"reset",1),hi([Qi([],"closed",{ignoreError:!0,sync:!0})],Js.prototype,"close",1);var ba=class extends Ht{constructor(i,t,e=!1,r,o=!1){super(),this.createModule=i,this.wasmBinary=t,this.workerMode=e,this.canvas=r,this.yuvMode=o,br(this,"worker"),br(this,"decoder"),br(this,"config"),br(this,"module",{}),br(this,"width",0),br(this,"height",0)}initialize(i){return y(this,null,function*(){var t;if(this.workerMode){let r=new RegExp("\\{(.+)\\}","s").exec(CI.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=d=>{if(d.data.type==="ready")delete this.wasmBinary,n(),console.warn("worker mode initialize success");else if(d.data.type==="yuvData"){let{videoFrame:p}=d.data;this.emit("videoFrame",p)}}})}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)],d=this.module.HEAPU8.subarray(o,o+e),p=this.module.HEAPU8.subarray(s,s+r),m=this.module.HEAPU8.subarray(n,n+r);if(this.yuvMode)return void this.emit("videoFrame",{y:d,u:p,v:m,timestamp:t});let g=new Uint8Array(e+r+r);g.set(d),g.set(p,e),g.set(m,e+r),this.emit("videoFrame",new VideoFrame(g,{codedWidth:this.width,codedHeight:this.height,format:"I420",timestamp:t}))}errorInfo(i){let t={errMsg:i};this.emit("error",t)}};hi([Qi([Ht.INIT,"closed"],"initialized")],ba.prototype,"initialize",1),hi([Qi("initialized","configured",{sync:!0})],ba.prototype,"configure",1),hi([Qi([],Ht.INIT,{sync:!0})],ba.prototype,"reset",1),hi([Qi([],"closed",{sync:!0})],ba.prototype,"close",1);var DI=(()=>{var i=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return function(t={}){var e,r,o=t;o.ready=new Promise((a,c)=>{e=a,r=c});var s,n,d,p=Object.assign({},o),m="./this.program",g=typeof window=="object",_=typeof importScripts=="function",b=(typeof process=="object"&&typeof process.versions=="object"&&process.versions.node,"");(g||_)&&(_?b=self.location.href:typeof document!="undefined"&&document.currentScript&&(b=document.currentScript.src),i&&(b=i),b=b.indexOf("blob:")!==0?b.substr(0,b.replace(/[?#].*/,"").lastIndexOf("/")+1):"",s=a=>{var c=new XMLHttpRequest;return c.open("GET",a,!1),c.send(null),c.responseText},_&&(d=a=>{var c=new XMLHttpRequest;return c.open("GET",a,!1),c.responseType="arraybuffer",c.send(null),new Uint8Array(c.response)}),n=(a,c,l)=>{var h=new XMLHttpRequest;h.open("GET",a,!0),h.responseType="arraybuffer",h.onload=()=>{h.status==200||h.status==0&&h.response?c(h.response):l()},h.onerror=l,h.send(null)});var N,k=o.print||console.log.bind(console),P=o.printErr||console.error.bind(console);Object.assign(o,p),p=null,o.arguments&&o.arguments,o.thisProgram&&(m=o.thisProgram),o.quit&&o.quit,o.wasmBinary&&(N=o.wasmBinary);var x,J;o.noExitRuntime,typeof WebAssembly!="object"&&Cr("no native wasm support detected");var Q,Ne,De,me,xe,Fe,Ks,en,tn,rn=!1,vr=[],Yo=[],Ei=[],K=0,Wr=null,Gr=null;function on(a){K++,o.monitorRunDependencies&&o.monitorRunDependencies(K)}function no(a){if(K--,o.monitorRunDependencies&&o.monitorRunDependencies(K),K==0&&(Wr!==null&&(clearInterval(Wr),Wr=null),Gr)){var c=Gr;Gr=null,c()}}function Cr(a){o.onAbort&&o.onAbort(a),P(a="Aborted("+a+")"),rn=!0,a+=". Build with -sASSERTIONS for more info.";var c=new WebAssembly.RuntimeError(a);throw r(c),c}var _i,ao,ge,Ge,Ua="data:application/octet-stream;base64,";function G(a){return a.startsWith(Ua)}function jr(a){if(a==_i&&N)return new Uint8Array(N);if(d)return d(a);throw"both async and sync fetching of the wasm failed"}function Dr(a,c,l){return function(h){return N||!g&&!_||typeof fetch!="function"?Promise.resolve().then(()=>jr(h)):fetch(h,{credentials:"same-origin"}).then(I=>{if(!I.ok)throw"failed to load wasm binary file at '"+h+"'";return I.arrayBuffer()}).catch(()=>jr(h))}(a).then(h=>WebAssembly.instantiate(h,c)).then(h=>h).then(l,h=>{P("failed to asynchronously prepare wasm: "+h),Cr(h)})}G(_i="videodec.wasm")||(ao=_i,_i=o.locateFile?o.locateFile(ao,b):b+ao);var Ti=a=>{for(;a.length>0;)a.shift()(o)};function Ii(a){this.excPtr=a,this.ptr=a-24,this.set_type=function(c){Fe[this.ptr+4>>2]=c},this.get_type=function(){return Fe[this.ptr+4>>2]},this.set_destructor=function(c){Fe[this.ptr+8>>2]=c},this.get_destructor=function(){return Fe[this.ptr+8>>2]},this.set_caught=function(c){c=c?1:0,Q[this.ptr+12|0]=c},this.get_caught=function(){return Q[this.ptr+12|0]!=0},this.set_rethrown=function(c){c=c?1:0,Q[this.ptr+13|0]=c},this.get_rethrown=function(){return Q[this.ptr+13|0]!=0},this.init=function(c,l){this.set_adjusted_ptr(0),this.set_type(c),this.set_destructor(l)},this.set_adjusted_ptr=function(c){Fe[this.ptr+16>>2]=c},this.get_adjusted_ptr=function(){return Fe[this.ptr+16>>2]},this.get_exception_ptr=function(){if(fn(this.get_type()))return Fe[this.excPtr>>2];var c=this.get_adjusted_ptr();return c!==0?c:this.excPtr}}var F={isAbs:a=>a.charAt(0)==="/",splitPath:a=>/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(a).slice(1),normalizeArray:(a,c)=>{for(var l=0,h=a.length-1;h>=0;h--){var I=a[h];I==="."?a.splice(h,1):I===".."?(a.splice(h,1),l++):l&&(a.splice(h,1),l--)}if(c)for(;l;l--)a.unshift("..");return a},normalize:a=>{var c=F.isAbs(a),l=a.substr(-1)==="/";return(a=F.normalizeArray(a.split("/").filter(h=>!!h),!c).join("/"))||c||(a="."),a&&l&&(a+="/"),(c?"/":"")+a},dirname:a=>{var c=F.splitPath(a),l=c[0],h=c[1];return l||h?(h&&(h=h.substr(0,h.length-1)),l+h):"."},basename:a=>{if(a==="/")return"/";var c=(a=(a=F.normalize(a)).replace(/\/$/,"")).lastIndexOf("/");return c===-1?a:a.substr(c+1)},join:function(){var a=Array.prototype.slice.call(arguments);return F.normalize(a.join("/"))},join2:(a,c)=>F.normalize(a+"/"+c)},sn=a=>(sn=(()=>{if(typeof crypto=="object"&&typeof crypto.getRandomValues=="function")return c=>crypto.getRandomValues(c);Cr("initRandomDevice")})())(a),Wt={resolve:function(){for(var a="",c=!1,l=arguments.length-1;l>=-1&&!c;l--){var h=l>=0?arguments[l]:f.cwd();if(typeof h!="string")throw new TypeError("Arguments to path.resolve must be strings");if(!h)return"";a=h+"/"+a,c=F.isAbs(h)}return(c?"/":"")+(a=F.normalizeArray(a.split("/").filter(I=>!!I),!c).join("/"))||"."},relative:(a,c)=>{function l(w){for(var z=0;z<w.length&&w[z]==="";z++);for(var ie=w.length-1;ie>=0&&w[ie]==="";ie--);return z>ie?[]:w.slice(z,ie-z+1)}a=Wt.resolve(a).substr(1),c=Wt.resolve(c).substr(1);for(var h=l(a.split("/")),I=l(c.split("/")),S=Math.min(h.length,I.length),A=S,R=0;R<S;R++)if(h[R]!==I[R]){A=R;break}var M=[];for(R=A;R<h.length;R++)M.push("..");return(M=M.concat(I.slice(A))).join("/")}},Si=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):void 0,Nt=(a,c,l)=>{for(var h=c+l,I=c;a[I]&&!(I>=h);)++I;if(I-c>16&&a.buffer&&Si)return Si.decode(a.subarray(c,I));for(var S="";c<I;){var A=a[c++];if(128&A){var R=63&a[c++];if((224&A)!=192){var M=63&a[c++];if((A=(240&A)==224?(15&A)<<12|R<<6|M:(7&A)<<18|R<<12|M<<6|63&a[c++])<65536)S+=String.fromCharCode(A);else{var w=A-65536;S+=String.fromCharCode(55296|w>>10,56320|1023&w)}}else S+=String.fromCharCode((31&A)<<6|R)}else S+=String.fromCharCode(A)}return S},nn=[],co=a=>{for(var c=0,l=0;l<a.length;++l){var h=a.charCodeAt(l);h<=127?c++:h<=2047?c+=2:h>=55296&&h<=57343?(c+=4,++l):c+=3}return c},uo=(a,c,l,h)=>{if(!(h>0))return 0;for(var I=l,S=l+h-1,A=0;A<a.length;++A){var R=a.charCodeAt(A);if(R>=55296&&R<=57343&&(R=65536+((1023&R)<<10)|1023&a.charCodeAt(++A)),R<=127){if(l>=S)break;c[l++]=R}else if(R<=2047){if(l+1>=S)break;c[l++]=192|R>>6,c[l++]=128|63&R}else if(R<=65535){if(l+2>=S)break;c[l++]=224|R>>12,c[l++]=128|R>>6&63,c[l++]=128|63&R}else{if(l+3>=S)break;c[l++]=240|R>>18,c[l++]=128|R>>12&63,c[l++]=128|R>>6&63,c[l++]=128|63&R}}return c[l]=0,l-I};function Zo(a,c,l){var h=l>0?l:co(a)+1,I=new Array(h),S=uo(a,I,0,I.length);return c&&(I.length=S),I}var ar={ttys:[],init:function(){},shutdown:function(){},register:function(a,c){ar.ttys[a]={input:[],output:[],ops:c},f.registerDevice(a,ar.stream_ops)},stream_ops:{open:function(a){var c=ar.ttys[a.node.rdev];if(!c)throw new f.ErrnoError(43);a.tty=c,a.seekable=!1},close:function(a){a.tty.ops.fsync(a.tty)},fsync:function(a){a.tty.ops.fsync(a.tty)},read:function(a,c,l,h,I){if(!a.tty||!a.tty.ops.get_char)throw new f.ErrnoError(60);for(var S=0,A=0;A<h;A++){var R;try{R=a.tty.ops.get_char(a.tty)}catch(M){throw new f.ErrnoError(29)}if(R===void 0&&S===0)throw new f.ErrnoError(6);if(R==null)break;S++,c[l+A]=R}return S&&(a.node.timestamp=Date.now()),S},write:function(a,c,l,h,I){if(!a.tty||!a.tty.ops.put_char)throw new f.ErrnoError(60);try{for(var S=0;S<h;S++)a.tty.ops.put_char(a.tty,c[l+S])}catch(A){throw new f.ErrnoError(29)}return h&&(a.node.timestamp=Date.now()),S}},default_tty_ops:{get_char:function(a){return(()=>{if(!nn.length){var c=null;if(typeof window!="undefined"&&typeof window.prompt=="function"?(c=window.prompt("Input: "))!==null&&(c+=`
|
|
50
50
|
`):typeof readline=="function"&&(c=readline())!==null&&(c+=`
|
|
51
|
-
`),!c)return null;an=Yo(c,!0)}return an.shift()})()},put_char:function(a,c){c===null||c===10?(k(Dt(a.output,0)),a.output=[]):c!=0&&a.output.push(c)},fsync:function(a){a.output&&a.output.length>0&&(k(Dt(a.output,0)),a.output=[])},ioctl_tcgets:function(a){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(a,c,l){return 0},ioctl_tiocgwinsz:function(a){return[24,80]}},default_tty1_ops:{put_char:function(a,c){c===null||c===10?(x(Dt(a.output,0)),a.output=[]):c!=0&&a.output.push(c)},fsync:function(a){a.output&&a.output.length>0&&(x(Dt(a.output,0)),a.output=[])}}},cn=a=>{Cr()},Te={ops_table:null,mount:a=>Te.createNode(null,"/",16895,0),createNode(a,c,l,h){if(f.isBlkdev(l)||f.isFIFO(l))throw new f.ErrnoError(63);Te.ops_table||(Te.ops_table={dir:{node:{getattr:Te.node_ops.getattr,setattr:Te.node_ops.setattr,lookup:Te.node_ops.lookup,mknod:Te.node_ops.mknod,rename:Te.node_ops.rename,unlink:Te.node_ops.unlink,rmdir:Te.node_ops.rmdir,readdir:Te.node_ops.readdir,symlink:Te.node_ops.symlink},stream:{llseek:Te.stream_ops.llseek}},file:{node:{getattr:Te.node_ops.getattr,setattr:Te.node_ops.setattr},stream:{llseek:Te.stream_ops.llseek,read:Te.stream_ops.read,write:Te.stream_ops.write,allocate:Te.stream_ops.allocate,mmap:Te.stream_ops.mmap,msync:Te.stream_ops.msync}},link:{node:{getattr:Te.node_ops.getattr,setattr:Te.node_ops.setattr,readlink:Te.node_ops.readlink},stream:{}},chrdev:{node:{getattr:Te.node_ops.getattr,setattr:Te.node_ops.setattr},stream:f.chrdev_stream_ops}});var I=f.createNode(a,c,l,h);return f.isDir(I.mode)?(I.node_ops=Te.ops_table.dir.node,I.stream_ops=Te.ops_table.dir.stream,I.contents={}):f.isFile(I.mode)?(I.node_ops=Te.ops_table.file.node,I.stream_ops=Te.ops_table.file.stream,I.usedBytes=0,I.contents=null):f.isLink(I.mode)?(I.node_ops=Te.ops_table.link.node,I.stream_ops=Te.ops_table.link.stream):f.isChrdev(I.mode)&&(I.node_ops=Te.ops_table.chrdev.node,I.stream_ops=Te.ops_table.chrdev.stream),I.timestamp=Date.now(),a&&(a.contents[c]=I,a.timestamp=I.timestamp),I},getFileDataAsTypedArray:a=>a.contents?a.contents.subarray?a.contents.subarray(0,a.usedBytes):new Uint8Array(a.contents):new Uint8Array(0),expandFileStorage(a,c){var l=a.contents?a.contents.length:0;if(!(l>=c)){c=Math.max(c,l*(l<1048576?2:1.125)>>>0),l!=0&&(c=Math.max(c,256));var h=a.contents;a.contents=new Uint8Array(c),a.usedBytes>0&&a.contents.set(h.subarray(0,a.usedBytes),0)}},resizeFileStorage(a,c){if(a.usedBytes!=c)if(c==0)a.contents=null,a.usedBytes=0;else{var l=a.contents;a.contents=new Uint8Array(c),l&&a.contents.set(l.subarray(0,Math.min(c,a.usedBytes))),a.usedBytes=c}},node_ops:{getattr(a){var c={};return c.dev=f.isChrdev(a.mode)?a.id:1,c.ino=a.id,c.mode=a.mode,c.nlink=1,c.uid=0,c.gid=0,c.rdev=a.rdev,f.isDir(a.mode)?c.size=4096:f.isFile(a.mode)?c.size=a.usedBytes:f.isLink(a.mode)?c.size=a.link.length:c.size=0,c.atime=new Date(a.timestamp),c.mtime=new Date(a.timestamp),c.ctime=new Date(a.timestamp),c.blksize=4096,c.blocks=Math.ceil(c.size/c.blksize),c},setattr(a,c){c.mode!==void 0&&(a.mode=c.mode),c.timestamp!==void 0&&(a.timestamp=c.timestamp),c.size!==void 0&&Te.resizeFileStorage(a,c.size)},lookup(a,c){throw f.genericErrors[44]},mknod:(a,c,l,h)=>Te.createNode(a,c,l,h),rename(a,c,l){if(f.isDir(a.mode)){var h;try{h=f.lookupNode(c,l)}catch(S){}if(h)for(var I in h.contents)throw new f.ErrnoError(55)}delete a.parent.contents[a.name],a.parent.timestamp=Date.now(),a.name=l,c.contents[l]=a,c.timestamp=a.parent.timestamp,a.parent=c},unlink(a,c){delete a.contents[c],a.timestamp=Date.now()},rmdir(a,c){var l=f.lookupNode(a,c);for(var h in l.contents)throw new f.ErrnoError(55);delete a.contents[c],a.timestamp=Date.now()},readdir(a){var c=[".",".."];for(var l in a.contents)a.contents.hasOwnProperty(l)&&c.push(l);return c},symlink(a,c,l){var h=Te.createNode(a,c,41471,0);return h.link=l,h},readlink(a){if(!f.isLink(a.mode))throw new f.ErrnoError(28);return a.link}},stream_ops:{read(a,c,l,h,I){var S=a.node.contents;if(I>=a.node.usedBytes)return 0;var A=Math.min(a.node.usedBytes-I,h);if(A>8&&S.subarray)c.set(S.subarray(I,I+A),l);else for(var R=0;R<A;R++)c[l+R]=S[I+R];return A},write(a,c,l,h,I,S){if(!h)return 0;var A=a.node;if(A.timestamp=Date.now(),c.subarray&&(!A.contents||A.contents.subarray)){if(S)return A.contents=c.subarray(l,l+h),A.usedBytes=h,h;if(A.usedBytes===0&&I===0)return A.contents=c.slice(l,l+h),A.usedBytes=h,h;if(I+h<=A.usedBytes)return A.contents.set(c.subarray(l,l+h),I),h}if(Te.expandFileStorage(A,I+h),A.contents.subarray&&c.subarray)A.contents.set(c.subarray(l,l+h),I);else for(var R=0;R<h;R++)A.contents[I+R]=c[l+R];return A.usedBytes=Math.max(A.usedBytes,I+h),h},llseek(a,c,l){var h=c;if(l===1?h+=a.position:l===2&&f.isFile(a.node.mode)&&(h+=a.node.usedBytes),h<0)throw new f.ErrnoError(28);return h},allocate(a,c,l){Te.expandFileStorage(a.node,c+l),a.node.usedBytes=Math.max(a.node.usedBytes,c+l)},mmap(a,c,l,h,I){if(!f.isFile(a.node.mode))throw new f.ErrnoError(43);var S,A,R=a.node.contents;if(2&I||R.buffer!==Q.buffer){if((l>0||l+c<R.length)&&(R=R.subarray?R.subarray(l,l+c):Array.prototype.slice.call(R,l,l+c)),A=!0,!(S=cn()))throw new f.ErrnoError(48);Q.set(R,S)}else A=!1,S=R.byteOffset;return{ptr:S,allocated:A}},msync:(a,c,l,h,I)=>(Te.stream_ops.write(a,c,0,h,l,!1),0)}},Eu=(a,c,l,h)=>{var I=h?"":`al ${a}`;n(a,S=>{var A;A=`Loading data file "${a}" failed (no arrayBuffer).`,S||Cr(A),c(new Uint8Array(S)),I&&to()},S=>{if(!l)throw`Loading data file "${a}" failed.`;l()}),I&&sn()},_u=o.preloadPlugins||[];function O(a,c){var l=0;return a&&(l|=365),c&&(l|=146),l}var f={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:!1,ignorePermissions:!0,ErrnoError:null,genericErrors:{},filesystems:null,syncFSRequests:0,lookupPath:(a,c={})=>{if(!(a=Wt.resolve(a)))return{path:"",node:null};if((c=Object.assign({follow_mount:!0,recurse_count:0},c)).recurse_count>8)throw new f.ErrnoError(32);for(var l=a.split("/").filter(w=>!!w),h=f.root,I="/",S=0;S<l.length;S++){var A=S===l.length-1;if(A&&c.parent)break;if(h=f.lookupNode(h,l[S]),I=V.join2(I,l[S]),f.isMountpoint(h)&&(!A||A&&c.follow_mount)&&(h=h.mounted.root),!A||c.follow)for(var R=0;f.isLink(h.mode);){var M=f.readlink(I);if(I=Wt.resolve(V.dirname(I),M),h=f.lookupPath(I,{recurse_count:c.recurse_count+1}).node,R++>40)throw new f.ErrnoError(32)}}return{path:I,node:h}},getPath:a=>{for(var c;;){if(f.isRoot(a)){var l=a.mount.mountpoint;return c?l[l.length-1]!=="/"?`${l}/${c}`:l+c:l}c=c?`${a.name}/${c}`:a.name,a=a.parent}},hashName:(a,c)=>{for(var l=0,h=0;h<c.length;h++)l=(l<<5)-l+c.charCodeAt(h)|0;return(a+l>>>0)%f.nameTable.length},hashAddNode:a=>{var c=f.hashName(a.parent.id,a.name);a.name_next=f.nameTable[c],f.nameTable[c]=a},hashRemoveNode:a=>{var c=f.hashName(a.parent.id,a.name);if(f.nameTable[c]===a)f.nameTable[c]=a.name_next;else for(var l=f.nameTable[c];l;){if(l.name_next===a){l.name_next=a.name_next;break}l=l.name_next}},lookupNode:(a,c)=>{var l=f.mayLookup(a);if(l)throw new f.ErrnoError(l,a);for(var h=f.hashName(a.id,c),I=f.nameTable[h];I;I=I.name_next){var S=I.name;if(I.parent.id===a.id&&S===c)return I}return f.lookup(a,c)},createNode:(a,c,l,h)=>{var I=new f.FSNode(a,c,l,h);return f.hashAddNode(I),I},destroyNode:a=>{f.hashRemoveNode(a)},isRoot:a=>a===a.parent,isMountpoint:a=>!!a.mounted,isFile:a=>(61440&a)==32768,isDir:a=>(61440&a)==16384,isLink:a=>(61440&a)==40960,isChrdev:a=>(61440&a)==8192,isBlkdev:a=>(61440&a)==24576,isFIFO:a=>(61440&a)==4096,isSocket:a=>!(49152&~a),flagsToPermissionString:a=>{var c=["r","w","rw"][3&a];return 512&a&&(c+="w"),c},nodePermissions:(a,c)=>f.ignorePermissions||(!c.includes("r")||292&a.mode)&&(!c.includes("w")||146&a.mode)&&(!c.includes("x")||73&a.mode)?0:2,mayLookup:a=>{var c=f.nodePermissions(a,"x");return c||(a.node_ops.lookup?0:2)},mayCreate:(a,c)=>{try{return f.lookupNode(a,c),20}catch(l){}return f.nodePermissions(a,"wx")},mayDelete:(a,c,l)=>{var h;try{h=f.lookupNode(a,c)}catch(S){return S.errno}var I=f.nodePermissions(a,"wx");if(I)return I;if(l){if(!f.isDir(h.mode))return 54;if(f.isRoot(h)||f.getPath(h)===f.cwd())return 10}else if(f.isDir(h.mode))return 31;return 0},mayOpen:(a,c)=>a?f.isLink(a.mode)?32:f.isDir(a.mode)&&(f.flagsToPermissionString(c)!=="r"||512&c)?31:f.nodePermissions(a,f.flagsToPermissionString(c)):44,MAX_OPEN_FDS:4096,nextfd:()=>{for(var a=0;a<=f.MAX_OPEN_FDS;a++)if(!f.streams[a])return a;throw new f.ErrnoError(33)},getStreamChecked:a=>{var c=f.getStream(a);if(!c)throw new f.ErrnoError(8);return c},getStream:a=>f.streams[a],createStream:(a,c=-1)=>(f.FSStream||(f.FSStream=function(){this.shared={}},f.FSStream.prototype={},Object.defineProperties(f.FSStream.prototype,{object:{get(){return this.node},set(l){this.node=l}},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(l){this.shared.flags=l}},position:{get(){return this.shared.position},set(l){this.shared.position=l}}})),a=Object.assign(new f.FSStream,a),c==-1&&(c=f.nextfd()),a.fd=c,f.streams[c]=a,a),closeStream:a=>{f.streams[a]=null},chrdev_stream_ops:{open:a=>{var c=f.getDevice(a.node.rdev);a.stream_ops=c.stream_ops,a.stream_ops.open&&a.stream_ops.open(a)},llseek:()=>{throw new f.ErrnoError(70)}},major:a=>a>>8,minor:a=>255&a,makedev:(a,c)=>a<<8|c,registerDevice:(a,c)=>{f.devices[a]={stream_ops:c}},getDevice:a=>f.devices[a],getMounts:a=>{for(var c=[],l=[a];l.length;){var h=l.pop();c.push(h),l.push.apply(l,h.mounts)}return c},syncfs:(a,c)=>{typeof a=="function"&&(c=a,a=!1),f.syncFSRequests++,f.syncFSRequests>1&&x(`warning: ${f.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`);var l=f.getMounts(f.root.mount),h=0;function I(A){return f.syncFSRequests--,c(A)}function S(A){if(A)return S.errored?void 0:(S.errored=!0,I(A));++h>=l.length&&I(null)}l.forEach(A=>{if(!A.type.syncfs)return S(null);A.type.syncfs(A,a,S)})},mount:(a,c,l)=>{var h,I=l==="/",S=!l;if(I&&f.root)throw new f.ErrnoError(10);if(!I&&!S){var A=f.lookupPath(l,{follow_mount:!1});if(l=A.path,h=A.node,f.isMountpoint(h))throw new f.ErrnoError(10);if(!f.isDir(h.mode))throw new f.ErrnoError(54)}var R={type:a,opts:c,mountpoint:l,mounts:[]},M=a.mount(R);return M.mount=R,R.root=M,I?f.root=M:h&&(h.mounted=R,h.mount&&h.mount.mounts.push(R)),M},unmount:a=>{var c=f.lookupPath(a,{follow_mount:!1});if(!f.isMountpoint(c.node))throw new f.ErrnoError(28);var l=c.node,h=l.mounted,I=f.getMounts(h);Object.keys(f.nameTable).forEach(A=>{for(var R=f.nameTable[A];R;){var M=R.name_next;I.includes(R.mount)&&f.destroyNode(R),R=M}}),l.mounted=null;var S=l.mount.mounts.indexOf(h);l.mount.mounts.splice(S,1)},lookup:(a,c)=>a.node_ops.lookup(a,c),mknod:(a,c,l)=>{var h=f.lookupPath(a,{parent:!0}).node,I=V.basename(a);if(!I||I==="."||I==="..")throw new f.ErrnoError(28);var S=f.mayCreate(h,I);if(S)throw new f.ErrnoError(S);if(!h.node_ops.mknod)throw new f.ErrnoError(63);return h.node_ops.mknod(h,I,c,l)},create:(a,c)=>(c=c!==void 0?c:438,c&=4095,c|=32768,f.mknod(a,c,0)),mkdir:(a,c)=>(c=c!==void 0?c:511,c&=1023,c|=16384,f.mknod(a,c,0)),mkdirTree:(a,c)=>{for(var l=a.split("/"),h="",I=0;I<l.length;++I)if(l[I]){h+="/"+l[I];try{f.mkdir(h,c)}catch(S){if(S.errno!=20)throw S}}},mkdev:(a,c,l)=>(l===void 0&&(l=c,c=438),c|=8192,f.mknod(a,c,l)),symlink:(a,c)=>{if(!Wt.resolve(a))throw new f.ErrnoError(44);var l=f.lookupPath(c,{parent:!0}).node;if(!l)throw new f.ErrnoError(44);var h=V.basename(c),I=f.mayCreate(l,h);if(I)throw new f.ErrnoError(I);if(!l.node_ops.symlink)throw new f.ErrnoError(63);return l.node_ops.symlink(l,h,a)},rename:(a,c)=>{var l,h,I=V.dirname(a),S=V.dirname(c),A=V.basename(a),R=V.basename(c);if(l=f.lookupPath(a,{parent:!0}).node,h=f.lookupPath(c,{parent:!0}).node,!l||!h)throw new f.ErrnoError(44);if(l.mount!==h.mount)throw new f.ErrnoError(75);var M,w=f.lookupNode(l,A),z=Wt.relative(a,S);if(z.charAt(0)!==".")throw new f.ErrnoError(28);if((z=Wt.relative(c,I)).charAt(0)!==".")throw new f.ErrnoError(55);try{M=f.lookupNode(h,R)}catch(re){}if(w!==M){var ie=f.isDir(w.mode),oe=f.mayDelete(l,A,ie);if(oe)throw new f.ErrnoError(oe);if(oe=M?f.mayDelete(h,R,ie):f.mayCreate(h,R))throw new f.ErrnoError(oe);if(!l.node_ops.rename)throw new f.ErrnoError(63);if(f.isMountpoint(w)||M&&f.isMountpoint(M))throw new f.ErrnoError(10);if(h!==l&&(oe=f.nodePermissions(l,"w")))throw new f.ErrnoError(oe);f.hashRemoveNode(w);try{l.node_ops.rename(w,h,R)}catch(re){throw re}finally{f.hashAddNode(w)}}},rmdir:a=>{var c=f.lookupPath(a,{parent:!0}).node,l=V.basename(a),h=f.lookupNode(c,l),I=f.mayDelete(c,l,!0);if(I)throw new f.ErrnoError(I);if(!c.node_ops.rmdir)throw new f.ErrnoError(63);if(f.isMountpoint(h))throw new f.ErrnoError(10);c.node_ops.rmdir(c,l),f.destroyNode(h)},readdir:a=>{var c=f.lookupPath(a,{follow:!0}).node;if(!c.node_ops.readdir)throw new f.ErrnoError(54);return c.node_ops.readdir(c)},unlink:a=>{var c=f.lookupPath(a,{parent:!0}).node;if(!c)throw new f.ErrnoError(44);var l=V.basename(a),h=f.lookupNode(c,l),I=f.mayDelete(c,l,!1);if(I)throw new f.ErrnoError(I);if(!c.node_ops.unlink)throw new f.ErrnoError(63);if(f.isMountpoint(h))throw new f.ErrnoError(10);c.node_ops.unlink(c,l),f.destroyNode(h)},readlink:a=>{var c=f.lookupPath(a).node;if(!c)throw new f.ErrnoError(44);if(!c.node_ops.readlink)throw new f.ErrnoError(28);return Wt.resolve(f.getPath(c.parent),c.node_ops.readlink(c))},stat:(a,c)=>{var l=f.lookupPath(a,{follow:!c}).node;if(!l)throw new f.ErrnoError(44);if(!l.node_ops.getattr)throw new f.ErrnoError(63);return l.node_ops.getattr(l)},lstat:a=>f.stat(a,!0),chmod:(a,c,l)=>{var h;if(typeof a=="string"?h=f.lookupPath(a,{follow:!l}).node:h=a,!h.node_ops.setattr)throw new f.ErrnoError(63);h.node_ops.setattr(h,{mode:4095&c|-4096&h.mode,timestamp:Date.now()})},lchmod:(a,c)=>{f.chmod(a,c,!0)},fchmod:(a,c)=>{var l=f.getStreamChecked(a);f.chmod(l.node,c)},chown:(a,c,l,h)=>{var I;if(typeof a=="string"?I=f.lookupPath(a,{follow:!h}).node:I=a,!I.node_ops.setattr)throw new f.ErrnoError(63);I.node_ops.setattr(I,{timestamp:Date.now()})},lchown:(a,c,l)=>{f.chown(a,c,l,!0)},fchown:(a,c,l)=>{var h=f.getStreamChecked(a);f.chown(h.node,c,l)},truncate:(a,c)=>{if(c<0)throw new f.ErrnoError(28);var l;if(typeof a=="string"?l=f.lookupPath(a,{follow:!0}).node:l=a,!l.node_ops.setattr)throw new f.ErrnoError(63);if(f.isDir(l.mode))throw new f.ErrnoError(31);if(!f.isFile(l.mode))throw new f.ErrnoError(28);var h=f.nodePermissions(l,"w");if(h)throw new f.ErrnoError(h);l.node_ops.setattr(l,{size:c,timestamp:Date.now()})},ftruncate:(a,c)=>{var l=f.getStreamChecked(a);if(!(2097155&l.flags))throw new f.ErrnoError(28);f.truncate(l.node,c)},utime:(a,c,l)=>{var h=f.lookupPath(a,{follow:!0}).node;h.node_ops.setattr(h,{timestamp:Math.max(c,l)})},open:(a,c,l)=>{if(a==="")throw new f.ErrnoError(44);var h;if(l=l===void 0?438:l,l=64&(c=typeof c=="string"?function(R){var M={r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090}[R];if(M===void 0)throw new Error(`Unknown file open mode: ${R}`);return M}(c):c)?4095&l|32768:0,typeof a=="object")h=a;else{a=V.normalize(a);try{h=f.lookupPath(a,{follow:!(131072&c)}).node}catch(R){}}var I=!1;if(64&c)if(h){if(128&c)throw new f.ErrnoError(20)}else h=f.mknod(a,l,0),I=!0;if(!h)throw new f.ErrnoError(44);if(f.isChrdev(h.mode)&&(c&=-513),65536&c&&!f.isDir(h.mode))throw new f.ErrnoError(54);if(!I){var S=f.mayOpen(h,c);if(S)throw new f.ErrnoError(S)}512&c&&!I&&f.truncate(h,0),c&=-131713;var A=f.createStream({node:h,path:f.getPath(h),flags:c,seekable:!0,position:0,stream_ops:h.stream_ops,ungotten:[],error:!1});return A.stream_ops.open&&A.stream_ops.open(A),!o.logReadFiles||1&c||(f.readFiles||(f.readFiles={}),a in f.readFiles||(f.readFiles[a]=1)),A},close:a=>{if(f.isClosed(a))throw new f.ErrnoError(8);a.getdents&&(a.getdents=null);try{a.stream_ops.close&&a.stream_ops.close(a)}catch(c){throw c}finally{f.closeStream(a.fd)}a.fd=null},isClosed:a=>a.fd===null,llseek:(a,c,l)=>{if(f.isClosed(a))throw new f.ErrnoError(8);if(!a.seekable||!a.stream_ops.llseek)throw new f.ErrnoError(70);if(l!=0&&l!=1&&l!=2)throw new f.ErrnoError(28);return a.position=a.stream_ops.llseek(a,c,l),a.ungotten=[],a.position},read:(a,c,l,h,I)=>{if(h<0||I<0)throw new f.ErrnoError(28);if(f.isClosed(a))throw new f.ErrnoError(8);if((2097155&a.flags)==1)throw new f.ErrnoError(8);if(f.isDir(a.node.mode))throw new f.ErrnoError(31);if(!a.stream_ops.read)throw new f.ErrnoError(28);var S=I!==void 0;if(S){if(!a.seekable)throw new f.ErrnoError(70)}else I=a.position;var A=a.stream_ops.read(a,c,l,h,I);return S||(a.position+=A),A},write:(a,c,l,h,I,S)=>{if(h<0||I<0)throw new f.ErrnoError(28);if(f.isClosed(a))throw new f.ErrnoError(8);if(!(2097155&a.flags))throw new f.ErrnoError(8);if(f.isDir(a.node.mode))throw new f.ErrnoError(31);if(!a.stream_ops.write)throw new f.ErrnoError(28);a.seekable&&1024&a.flags&&f.llseek(a,0,2);var A=I!==void 0;if(A){if(!a.seekable)throw new f.ErrnoError(70)}else I=a.position;var R=a.stream_ops.write(a,c,l,h,I,S);return A||(a.position+=R),R},allocate:(a,c,l)=>{if(f.isClosed(a))throw new f.ErrnoError(8);if(c<0||l<=0)throw new f.ErrnoError(28);if(!(2097155&a.flags))throw new f.ErrnoError(8);if(!f.isFile(a.node.mode)&&!f.isDir(a.node.mode))throw new f.ErrnoError(43);if(!a.stream_ops.allocate)throw new f.ErrnoError(138);a.stream_ops.allocate(a,c,l)},mmap:(a,c,l,h,I)=>{if(2&h&&!(2&I)&&(2097155&a.flags)!=2)throw new f.ErrnoError(2);if((2097155&a.flags)==1)throw new f.ErrnoError(2);if(!a.stream_ops.mmap)throw new f.ErrnoError(43);return a.stream_ops.mmap(a,c,l,h,I)},msync:(a,c,l,h,I)=>a.stream_ops.msync?a.stream_ops.msync(a,c,l,h,I):0,munmap:a=>0,ioctl:(a,c,l)=>{if(!a.stream_ops.ioctl)throw new f.ErrnoError(59);return a.stream_ops.ioctl(a,c,l)},readFile:(a,c={})=>{if(c.flags=c.flags||0,c.encoding=c.encoding||"binary",c.encoding!=="utf8"&&c.encoding!=="binary")throw new Error(`Invalid encoding type "${c.encoding}"`);var l,h=f.open(a,c.flags),I=f.stat(a).size,S=new Uint8Array(I);return f.read(h,S,0,I,0),c.encoding==="utf8"?l=Dt(S,0):c.encoding==="binary"&&(l=S),f.close(h),l},writeFile:(a,c,l={})=>{l.flags=l.flags||577;var h=f.open(a,l.flags,l.mode);if(typeof c=="string"){var I=new Uint8Array(io(c)+1),S=oo(c,I,0,I.length);f.write(h,I,0,S,void 0,l.canOwn)}else{if(!ArrayBuffer.isView(c))throw new Error("Unsupported data type");f.write(h,c,0,c.byteLength,void 0,l.canOwn)}f.close(h)},cwd:()=>f.currentPath,chdir:a=>{var c=f.lookupPath(a,{follow:!0});if(c.node===null)throw new f.ErrnoError(44);if(!f.isDir(c.node.mode))throw new f.ErrnoError(54);var l=f.nodePermissions(c.node,"x");if(l)throw new f.ErrnoError(l);f.currentPath=c.path},createDefaultDirectories:()=>{f.mkdir("/tmp"),f.mkdir("/home"),f.mkdir("/home/web_user")},createDefaultDevices:()=>{f.mkdir("/dev"),f.registerDevice(f.makedev(1,3),{read:()=>0,write:(h,I,S,A,R)=>A}),f.mkdev("/dev/null",f.makedev(1,3)),nr.register(f.makedev(5,0),nr.default_tty_ops),nr.register(f.makedev(6,0),nr.default_tty1_ops),f.mkdev("/dev/tty",f.makedev(5,0)),f.mkdev("/dev/tty1",f.makedev(6,0));var a=new Uint8Array(1024),c=0,l=()=>(c===0&&(c=nn(a).byteLength),a[--c]);f.createDevice("/dev","random",l),f.createDevice("/dev","urandom",l),f.mkdir("/dev/shm"),f.mkdir("/dev/shm/tmp")},createSpecialDirectories:()=>{f.mkdir("/proc");var a=f.mkdir("/proc/self");f.mkdir("/proc/self/fd"),f.mount({mount:()=>{var c=f.createNode(a,"fd",16895,73);return c.node_ops={lookup:(l,h)=>{var I=+h,S=f.getStreamChecked(I),A={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>S.path}};return A.parent=A,A}},c}},{},"/proc/self/fd")},createStandardStreams:()=>{o.stdin?f.createDevice("/dev","stdin",o.stdin):f.symlink("/dev/tty","/dev/stdin"),o.stdout?f.createDevice("/dev","stdout",null,o.stdout):f.symlink("/dev/tty","/dev/stdout"),o.stderr?f.createDevice("/dev","stderr",null,o.stderr):f.symlink("/dev/tty1","/dev/stderr"),f.open("/dev/stdin",0),f.open("/dev/stdout",1),f.open("/dev/stderr",1)},ensureErrnoError:()=>{f.ErrnoError||(f.ErrnoError=function(a,c){this.name="ErrnoError",this.node=c,this.setErrno=function(l){this.errno=l},this.setErrno(a),this.message="FS error"},f.ErrnoError.prototype=new Error,f.ErrnoError.prototype.constructor=f.ErrnoError,[44].forEach(a=>{f.genericErrors[a]=new f.ErrnoError(a),f.genericErrors[a].stack="<generic error, no stack>"}))},staticInit:()=>{f.ensureErrnoError(),f.nameTable=new Array(4096),f.mount(Te,{},"/"),f.createDefaultDirectories(),f.createDefaultDevices(),f.createSpecialDirectories(),f.filesystems={MEMFS:Te}},init:(a,c,l)=>{f.init.initialized=!0,f.ensureErrnoError(),o.stdin=a||o.stdin,o.stdout=c||o.stdout,o.stderr=l||o.stderr,f.createStandardStreams()},quit:()=>{f.init.initialized=!1;for(var a=0;a<f.streams.length;a++){var c=f.streams[a];c&&f.close(c)}},findObject:(a,c)=>{var l=f.analyzePath(a,c);return l.exists?l.object:null},analyzePath:(a,c)=>{try{a=(h=f.lookupPath(a,{follow:!c})).path}catch(I){}var l={isRoot:!1,exists:!1,error:0,name:null,path:null,object:null,parentExists:!1,parentPath:null,parentObject:null};try{var h=f.lookupPath(a,{parent:!0});l.parentExists=!0,l.parentPath=h.path,l.parentObject=h.node,l.name=V.basename(a),h=f.lookupPath(a,{follow:!c}),l.exists=!0,l.path=h.path,l.object=h.node,l.name=h.node.name,l.isRoot=h.path==="/"}catch(I){l.error=I.errno}return l},createPath:(a,c,l,h)=>{a=typeof a=="string"?a:f.getPath(a);for(var I=c.split("/").reverse();I.length;){var S=I.pop();if(S){var A=V.join2(a,S);try{f.mkdir(A)}catch(R){}a=A}}return A},createFile:(a,c,l,h,I)=>{var S=V.join2(typeof a=="string"?a:f.getPath(a),c),A=O(h,I);return f.create(S,A)},createDataFile:(a,c,l,h,I,S)=>{var A=c;a&&(a=typeof a=="string"?a:f.getPath(a),A=c?V.join2(a,c):a);var R=O(h,I),M=f.create(A,R);if(l){if(typeof l=="string"){for(var w=new Array(l.length),z=0,ie=l.length;z<ie;++z)w[z]=l.charCodeAt(z);l=w}f.chmod(M,146|R);var oe=f.open(M,577);f.write(oe,l,0,l.length,0,S),f.close(oe),f.chmod(M,R)}return M},createDevice:(a,c,l,h)=>{var I=V.join2(typeof a=="string"?a:f.getPath(a),c),S=O(!!l,!!h);f.createDevice.major||(f.createDevice.major=64);var A=f.makedev(f.createDevice.major++,0);return f.registerDevice(A,{open:R=>{R.seekable=!1},close:R=>{h&&h.buffer&&h.buffer.length&&h(10)},read:(R,M,w,z,ie)=>{for(var oe=0,re=0;re<z;re++){var ye;try{ye=l()}catch(Le){throw new f.ErrnoError(29)}if(ye===void 0&&oe===0)throw new f.ErrnoError(6);if(ye==null)break;oe++,M[w+re]=ye}return oe&&(R.node.timestamp=Date.now()),oe},write:(R,M,w,z,ie)=>{for(var oe=0;oe<z;oe++)try{h(M[w+oe])}catch(re){throw new f.ErrnoError(29)}return z&&(R.node.timestamp=Date.now()),oe}}),f.mkdev(I,S,A)},forceLoadFile:a=>{if(a.isDevice||a.isFolder||a.link||a.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{a.contents=Yo(s(a.url),!0),a.usedBytes=a.contents.length}catch(c){throw new f.ErrnoError(29)}},createLazyFile:(a,c,l,h,I)=>{function S(){this.lengthKnown=!1,this.chunks=[]}if(S.prototype.get=function(ie){if(!(ie>this.length-1||ie<0)){var oe=ie%this.chunkSize,re=ie/this.chunkSize|0;return this.getter(re)[oe]}},S.prototype.setDataGetter=function(ie){this.getter=ie},S.prototype.cacheLength=function(){var ie=new XMLHttpRequest;if(ie.open("HEAD",l,!1),ie.send(null),!(ie.status>=200&&ie.status<300||ie.status===304))throw new Error("Couldn't load "+l+". Status: "+ie.status);var oe,re=Number(ie.getResponseHeader("Content-length")),ye=(oe=ie.getResponseHeader("Accept-Ranges"))&&oe==="bytes",Le=(oe=ie.getResponseHeader("Content-Encoding"))&&oe==="gzip",Re=1048576;ye||(Re=re);var Ke=this;Ke.setDataGetter(Je=>{var lt=Je*Re,Ni=(Je+1)*Re-1;if(Ni=Math.min(Ni,re-1),Ke.chunks[Je]===void 0&&(Ke.chunks[Je]=((tr,mo)=>{if(tr>mo)throw new Error("invalid range ("+tr+", "+mo+") or no bytes requested!");if(mo>re-1)throw new Error("only "+re+" bytes available! programmer error!");var ot=new XMLHttpRequest;if(ot.open("GET",l,!1),re!==Re&&ot.setRequestHeader("Range","bytes="+tr+"-"+mo),ot.responseType="arraybuffer",ot.overrideMimeType&&ot.overrideMimeType("text/plain; charset=x-user-defined"),ot.send(null),!(ot.status>=200&&ot.status<300||ot.status===304))throw new Error("Couldn't load "+l+". Status: "+ot.status);return ot.response!==void 0?new Uint8Array(ot.response||[]):Yo(ot.responseText||"",!0)})(lt,Ni)),Ke.chunks[Je]===void 0)throw new Error("doXHR failed!");return Ke.chunks[Je]}),!Le&&re||(Re=re=1,re=this.getter(0).length,Re=re,k("LazyFiles on gzip forces download of the whole file when length is accessed")),this._length=re,this._chunkSize=Re,this.lengthKnown=!0},typeof XMLHttpRequest!="undefined"){if(!_)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var A=new S;Object.defineProperties(A,{length:{get:function(){return this.lengthKnown||this.cacheLength(),this._length}},chunkSize:{get:function(){return this.lengthKnown||this.cacheLength(),this._chunkSize}}});var R={isDevice:!1,contents:A}}else R={isDevice:!1,url:l};var M=f.createFile(a,c,R,h,I);R.contents?M.contents=R.contents:R.url&&(M.contents=null,M.url=R.url),Object.defineProperties(M,{usedBytes:{get:function(){return this.contents.length}}});var w={};function z(ie,oe,re,ye,Le){var Re=ie.node.contents;if(Le>=Re.length)return 0;var Ke=Math.min(Re.length-Le,ye);if(Re.slice)for(var Je=0;Je<Ke;Je++)oe[re+Je]=Re[Le+Je];else for(Je=0;Je<Ke;Je++)oe[re+Je]=Re.get(Le+Je);return Ke}return Object.keys(M.stream_ops).forEach(ie=>{var oe=M.stream_ops[ie];w[ie]=function(){return f.forceLoadFile(M),oe.apply(null,arguments)}}),w.read=(ie,oe,re,ye,Le)=>(f.forceLoadFile(M),z(ie,oe,re,ye,Le)),w.mmap=(ie,oe,re,ye,Le)=>{f.forceLoadFile(M);var Re=cn();if(!Re)throw new f.ErrnoError(48);return z(ie,Q,Re,oe,re),{ptr:Re,allocated:!0}},M.stream_ops=w,M}},Ii=(a,c)=>a?Dt(De,a,c):"",ft={DEFAULT_POLLMASK:5,calculateAt:function(a,c,l){if(V.isAbs(c))return c;var h;if(a===-100?h=f.cwd():h=ft.getStreamFromFD(a).path,c.length==0){if(!l)throw new f.ErrnoError(44);return h}return V.join2(h,c)},doStat:function(a,c,l){try{var h=a(c)}catch(R){if(R&&R.node&&V.normalize(c)!==V.normalize(f.getPath(R.node)))return-54;throw R}Pe[l>>2]=h.dev,Pe[l+4>>2]=h.mode,Be[l+8>>2]=h.nlink,Pe[l+12>>2]=h.uid,Pe[l+16>>2]=h.gid,Pe[l+20>>2]=h.rdev,Ge=[h.size>>>0,(ge=h.size,+Math.abs(ge)>=1?ge>0?+Math.floor(ge/4294967296)>>>0:~~+Math.ceil((ge-+(~~ge>>>0))/4294967296)>>>0:0)],Pe[l+24>>2]=Ge[0],Pe[l+28>>2]=Ge[1],Pe[l+32>>2]=4096,Pe[l+36>>2]=h.blocks;var I=h.atime.getTime(),S=h.mtime.getTime(),A=h.ctime.getTime();return Ge=[Math.floor(I/1e3)>>>0,(ge=Math.floor(I/1e3),+Math.abs(ge)>=1?ge>0?+Math.floor(ge/4294967296)>>>0:~~+Math.ceil((ge-+(~~ge>>>0))/4294967296)>>>0:0)],Pe[l+40>>2]=Ge[0],Pe[l+44>>2]=Ge[1],Be[l+48>>2]=I%1e3*1e3,Ge=[Math.floor(S/1e3)>>>0,(ge=Math.floor(S/1e3),+Math.abs(ge)>=1?ge>0?+Math.floor(ge/4294967296)>>>0:~~+Math.ceil((ge-+(~~ge>>>0))/4294967296)>>>0:0)],Pe[l+56>>2]=Ge[0],Pe[l+60>>2]=Ge[1],Be[l+64>>2]=S%1e3*1e3,Ge=[Math.floor(A/1e3)>>>0,(ge=Math.floor(A/1e3),+Math.abs(ge)>=1?ge>0?+Math.floor(ge/4294967296)>>>0:~~+Math.ceil((ge-+(~~ge>>>0))/4294967296)>>>0:0)],Pe[l+72>>2]=Ge[0],Pe[l+76>>2]=Ge[1],Be[l+80>>2]=A%1e3*1e3,Ge=[h.ino>>>0,(ge=h.ino,+Math.abs(ge)>=1?ge>0?+Math.floor(ge/4294967296)>>>0:~~+Math.ceil((ge-+(~~ge>>>0))/4294967296)>>>0:0)],Pe[l+88>>2]=Ge[0],Pe[l+92>>2]=Ge[1],0},doMsync:function(a,c,l,h,I){if(!f.isFile(c.node.mode))throw new f.ErrnoError(43);if(2&h)return 0;var S=De.slice(a,a+l);f.msync(c,S,I,l,h)},varargs:void 0,get:()=>(ft.varargs+=4,Pe[ft.varargs-4>>2]),getStr:a=>Ii(a),getStreamFromFD:function(a){return f.getStreamChecked(a)}};function jr(a){switch(a){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError(`Unknown type size: ${a}`)}}var Ba=void 0;function _t(a){for(var c="",l=a;De[l];)c+=Ba[De[l++]];return c}var Si={},er={},Zo={},yi=void 0;function ke(a){throw new yi(a)}var $a=void 0;function zt(a){throw new $a(a)}function so(a,c,l){function h(R){var M=l(R);M.length!==a.length&&zt("Mismatched type converter count");for(var w=0;w<a.length;++w)ar(a[w],M[w])}a.forEach(function(R){Zo[R]=c});var I=new Array(c.length),S=[],A=0;c.forEach((R,M)=>{er.hasOwnProperty(R)?I[M]=er[R]:(S.push(R),Si.hasOwnProperty(R)||(Si[R]=[]),Si[R].push(()=>{I[M]=er[R],++A===S.length&&h(I)}))}),S.length===0&&h(I)}function ar(a,c,l={}){if(!("argPackAdvance"in c))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(h,I,S={}){var A=I.name;if(h||ke(`type "${A}" must have a positive integer typeid pointer`),er.hasOwnProperty(h)){if(S.ignoreDuplicateRegistrations)return;ke(`Cannot register type '${A}' twice`)}if(er[h]=I,delete Zo[h],Si.hasOwnProperty(h)){var R=Si[h];delete Si[h],R.forEach(M=>M())}}(a,c,l)}function Ko(a){if(!(this instanceof wr)||!(a instanceof wr))return!1;for(var c=this.$$.ptrType.registeredClass,l=this.$$.ptr,h=a.$$.ptrType.registeredClass,I=a.$$.ptr;c.baseClass;)l=c.upcast(l),c=c.baseClass;for(;h.baseClass;)I=h.upcast(I),h=h.baseClass;return c===h&&l===I}function no(a){ke(a.$$.ptrType.registeredClass.name+" instance already deleted")}var es=!1;function Fa(a){}function ts(a){a.count.value-=1,a.count.value===0&&function(c){c.smartPtr?c.smartPtrType.rawDestructor(c.smartPtr):c.ptrType.registeredClass.rawDestructor(c.ptr)}(a)}function Ha(a,c,l){if(c===l)return a;if(l.baseClass===void 0)return null;var h=Ha(a,c,l.baseClass);return h===null?null:l.downcast(h)}var Wa={};function Tu(){return Object.keys(Dr).length}function rs(){var a=[];for(var c in Dr)Dr.hasOwnProperty(c)&&a.push(Dr[c]);return a}var ao=[];function dn(){for(;ao.length;){var a=ao.pop();a.$$.deleteScheduled=!1,a.delete()}}var co=void 0;function cr(a){co=a,ao.length&&co&&co(dn)}var Dr={};function Ga(a,c){return c=function(l,h){for(h===void 0&&ke("ptr should not be undefined");l.baseClass;)h=l.upcast(h),l=l.baseClass;return h}(a,c),Dr[c]}function is(a,c){return c.ptrType&&c.ptr||zt("makeClassHandle requires ptr and ptrType"),!!c.smartPtrType!=!!c.smartPtr&&zt("Both smartPtrType and smartPtr must be specified"),c.count={value:1},dr(Object.create(a,{$$:{value:c}}))}function Iu(a){var c=this.getPointee(a);if(!c)return this.destructor(a),null;var l=Ga(this.registeredClass,c);if(l!==void 0){if(l.$$.count.value===0)return l.$$.ptr=c,l.$$.smartPtr=a,l.clone();var h=l.clone();return this.destructor(a),h}function I(){return this.isSmartPointer?is(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:c,smartPtrType:this,smartPtr:a}):is(this.registeredClass.instancePrototype,{ptrType:this,ptr:a})}var S,A=this.registeredClass.getActualType(c),R=Wa[A];if(!R)return I.call(this);S=this.isConst?R.constPointerType:R.pointerType;var M=Ha(c,this.registeredClass,S.registeredClass);return M===null?I.call(this):this.isSmartPointer?is(S.registeredClass.instancePrototype,{ptrType:S,ptr:M,smartPtrType:this,smartPtr:a}):is(S.registeredClass.instancePrototype,{ptrType:S,ptr:M})}var dr=function(a){return typeof FinalizationRegistry=="undefined"?(dr=c=>c,a):(es=new FinalizationRegistry(c=>{ts(c.$$)}),Fa=c=>es.unregister(c),(dr=c=>{var l=c.$$;if(l.smartPtr){var h={$$:l};es.register(c,h,c)}return c})(a))};function ja(){if(this.$$.ptr||no(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var a,c=dr(Object.create(Object.getPrototypeOf(this),{$$:{value:(a=this.$$,{count:a.count,deleteScheduled:a.deleteScheduled,preservePointerOnDelete:a.preservePointerOnDelete,ptr:a.ptr,ptrType:a.ptrType,smartPtr:a.smartPtr,smartPtrType:a.smartPtrType})}}));return c.$$.count.value+=1,c.$$.deleteScheduled=!1,c}function qa(){this.$$.ptr||no(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&ke("Object already scheduled for deletion"),Fa(this),ts(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)}function un(){return!this.$$.ptr}function Ja(){return this.$$.ptr||no(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&ke("Object already scheduled for deletion"),ao.push(this),ao.length===1&&co&&co(dn),this.$$.deleteScheduled=!0,this}function wr(){}var za=48,Xa=57;function uo(a){if(a===void 0)return"_unknown";var c=(a=a.replace(/[^a-zA-Z0-9_]/g,"$")).charCodeAt(0);return c>=za&&c<=Xa?`_${a}`:a}function Vt(a,c){return a=uo(a),{[a]:function(){return c.apply(this,arguments)}}[a]}function ln(a,c,l){if(a[c].overloadTable===void 0){var h=a[c];a[c]=function(){return a[c].overloadTable.hasOwnProperty(arguments.length)||ke(`Function '${l}' called with an invalid number of arguments (${arguments.length}) - expects one of (${a[c].overloadTable})!`),a[c].overloadTable[arguments.length].apply(this,arguments)},a[c].overloadTable=[],a[c].overloadTable[h.argCount]=h}}function Su(a,c,l,h,I,S,A,R){this.name=a,this.constructor=c,this.instancePrototype=l,this.rawDestructor=h,this.baseClass=I,this.getActualType=S,this.upcast=A,this.downcast=R,this.pureVirtualFunctions=[]}function Ai(a,c,l){for(;c!==l;)c.upcast||ke(`Expected null or instance of ${l.name}, got an instance of ${c.name}`),a=c.upcast(a),c=c.baseClass;return a}function mn(a,c){if(c===null)return this.isReference&&ke(`null is not a valid ${this.name}`),0;c.$$||ke(`Cannot pass "${as(c)}" as a ${this.name}`),c.$$.ptr||ke(`Cannot pass deleted object as a pointer of type ${this.name}`);var l=c.$$.ptrType.registeredClass;return Ai(c.$$.ptr,l,this.registeredClass)}function yu(a,c){var l;if(c===null)return this.isReference&&ke(`null is not a valid ${this.name}`),this.isSmartPointer?(l=this.rawConstructor(),a!==null&&a.push(this.rawDestructor,l),l):0;c.$$||ke(`Cannot pass "${as(c)}" as a ${this.name}`),c.$$.ptr||ke(`Cannot pass deleted object as a pointer of type ${this.name}`),!this.isConst&&c.$$.ptrType.isConst&&ke(`Cannot convert argument of type ${c.$$.smartPtrType?c.$$.smartPtrType.name:c.$$.ptrType.name} to parameter type ${this.name}`);var h=c.$$.ptrType.registeredClass;if(l=Ai(c.$$.ptr,h,this.registeredClass),this.isSmartPointer)switch(c.$$.smartPtr===void 0&&ke("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:c.$$.smartPtrType===this?l=c.$$.smartPtr:ke(`Cannot convert argument of type ${c.$$.smartPtrType?c.$$.smartPtrType.name:c.$$.ptrType.name} to parameter type ${this.name}`);break;case 1:l=c.$$.smartPtr;break;case 2:if(c.$$.smartPtrType===this)l=c.$$.smartPtr;else{var I=c.clone();l=this.rawShare(l,vi.toHandle(function(){I.delete()})),a!==null&&a.push(this.rawDestructor,l)}break;default:ke("Unsupporting sharing policy")}return l}function Au(a,c){if(c===null)return this.isReference&&ke(`null is not a valid ${this.name}`),0;c.$$||ke(`Cannot pass "${as(c)}" as a ${this.name}`),c.$$.ptr||ke(`Cannot pass deleted object as a pointer of type ${this.name}`),c.$$.ptrType.isConst&&ke(`Cannot convert argument of type ${c.$$.ptrType.name} to parameter type ${this.name}`);var l=c.$$.ptrType.registeredClass;return Ai(c.$$.ptr,l,this.registeredClass)}function lo(a){return this.fromWireType(Pe[a>>2])}function Qa(a){return this.rawGetPointee&&(a=this.rawGetPointee(a)),a}function bu(a){this.rawDestructor&&this.rawDestructor(a)}function Ya(a){a!==null&&a.delete()}function ur(a,c,l,h,I,S,A,R,M,w,z){this.name=a,this.registeredClass=c,this.isReference=l,this.isConst=h,this.isSmartPointer=I,this.pointeeType=S,this.sharingPolicy=A,this.rawGetPointee=R,this.rawConstructor=M,this.rawShare=w,this.rawDestructor=z,I||c.baseClass!==void 0?this.toWireType=yu:h?(this.toWireType=mn,this.destructorFunction=null):(this.toWireType=Au,this.destructorFunction=null)}var os=[],Za=a=>{var c=os[a];return c||(a>=os.length&&(os.length=a+1),os[a]=c=rn.get(a)),c},Ru=(a,c,l)=>a.includes("j")?((h,I,S)=>{var A=o["dynCall_"+h];return S&&S.length?A.apply(null,[I].concat(S)):A.call(null,I)})(a,c,l):Za(c).apply(null,l),vu=(a,c)=>{var l=[];return function(){return l.length=0,Object.assign(l,arguments),Ru(a,c,l)}};function bi(a,c){var l=(a=_t(a)).includes("j")?vu(a,c):Za(c);return typeof l!="function"&&ke(`unknown function pointer with signature ${a}: ${c}`),l}var Ka=void 0;function ss(a){var c=mr(a),l=_t(c);return Tt(c),l}function ns(a,c){var l=[],h={};throw c.forEach(function I(S){h[S]||er[S]||(Zo[S]?Zo[S].forEach(I):(l.push(S),h[S]=!0))}),new Ka(`${a}: `+l.map(ss).join([", "]))}function pn(a,c){for(var l=[],h=0;h<a;h++)l.push(Be[c+4*h>>2]);return l}function ec(a){for(;a.length;){var c=a.pop();a.pop()(c)}}function hn(a,c){if(!(a instanceof Function))throw new TypeError(`new_ called with constructor type ${typeof a} which is not a function`);var l=Vt(a.name||"unknownFunctionName",function(){});l.prototype=a.prototype;var h=new l,I=a.apply(h,c);return I instanceof Object?I:h}function Ri(a,c,l,h,I,S){var A=c.length;A<2&&ke("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var R=c[1]!==null&&l!==null,M=!1,w=1;w<c.length;++w)if(c[w]!==null&&c[w].destructorFunction===void 0){M=!0;break}var z=c[0].name!=="void",ie="",oe="";for(w=0;w<A-2;++w)ie+=(w!==0?", ":"")+"arg"+w,oe+=(w!==0?", ":"")+"arg"+w+"Wired";var re=`
|
|
52
|
-
return function ${
|
|
51
|
+
`),!c)return null;nn=Zo(c,!0)}return nn.shift()})()},put_char:function(a,c){c===null||c===10?(k(Nt(a.output,0)),a.output=[]):c!=0&&a.output.push(c)},fsync:function(a){a.output&&a.output.length>0&&(k(Nt(a.output,0)),a.output=[])},ioctl_tcgets:function(a){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(a,c,l){return 0},ioctl_tiocgwinsz:function(a){return[24,80]}},default_tty1_ops:{put_char:function(a,c){c===null||c===10?(P(Nt(a.output,0)),a.output=[]):c!=0&&a.output.push(c)},fsync:function(a){a.output&&a.output.length>0&&(P(Nt(a.output,0)),a.output=[])}}},an=a=>{Cr()},Te={ops_table:null,mount:a=>Te.createNode(null,"/",16895,0),createNode(a,c,l,h){if(f.isBlkdev(l)||f.isFIFO(l))throw new f.ErrnoError(63);Te.ops_table||(Te.ops_table={dir:{node:{getattr:Te.node_ops.getattr,setattr:Te.node_ops.setattr,lookup:Te.node_ops.lookup,mknod:Te.node_ops.mknod,rename:Te.node_ops.rename,unlink:Te.node_ops.unlink,rmdir:Te.node_ops.rmdir,readdir:Te.node_ops.readdir,symlink:Te.node_ops.symlink},stream:{llseek:Te.stream_ops.llseek}},file:{node:{getattr:Te.node_ops.getattr,setattr:Te.node_ops.setattr},stream:{llseek:Te.stream_ops.llseek,read:Te.stream_ops.read,write:Te.stream_ops.write,allocate:Te.stream_ops.allocate,mmap:Te.stream_ops.mmap,msync:Te.stream_ops.msync}},link:{node:{getattr:Te.node_ops.getattr,setattr:Te.node_ops.setattr,readlink:Te.node_ops.readlink},stream:{}},chrdev:{node:{getattr:Te.node_ops.getattr,setattr:Te.node_ops.setattr},stream:f.chrdev_stream_ops}});var I=f.createNode(a,c,l,h);return f.isDir(I.mode)?(I.node_ops=Te.ops_table.dir.node,I.stream_ops=Te.ops_table.dir.stream,I.contents={}):f.isFile(I.mode)?(I.node_ops=Te.ops_table.file.node,I.stream_ops=Te.ops_table.file.stream,I.usedBytes=0,I.contents=null):f.isLink(I.mode)?(I.node_ops=Te.ops_table.link.node,I.stream_ops=Te.ops_table.link.stream):f.isChrdev(I.mode)&&(I.node_ops=Te.ops_table.chrdev.node,I.stream_ops=Te.ops_table.chrdev.stream),I.timestamp=Date.now(),a&&(a.contents[c]=I,a.timestamp=I.timestamp),I},getFileDataAsTypedArray:a=>a.contents?a.contents.subarray?a.contents.subarray(0,a.usedBytes):new Uint8Array(a.contents):new Uint8Array(0),expandFileStorage(a,c){var l=a.contents?a.contents.length:0;if(!(l>=c)){c=Math.max(c,l*(l<1048576?2:1.125)>>>0),l!=0&&(c=Math.max(c,256));var h=a.contents;a.contents=new Uint8Array(c),a.usedBytes>0&&a.contents.set(h.subarray(0,a.usedBytes),0)}},resizeFileStorage(a,c){if(a.usedBytes!=c)if(c==0)a.contents=null,a.usedBytes=0;else{var l=a.contents;a.contents=new Uint8Array(c),l&&a.contents.set(l.subarray(0,Math.min(c,a.usedBytes))),a.usedBytes=c}},node_ops:{getattr(a){var c={};return c.dev=f.isChrdev(a.mode)?a.id:1,c.ino=a.id,c.mode=a.mode,c.nlink=1,c.uid=0,c.gid=0,c.rdev=a.rdev,f.isDir(a.mode)?c.size=4096:f.isFile(a.mode)?c.size=a.usedBytes:f.isLink(a.mode)?c.size=a.link.length:c.size=0,c.atime=new Date(a.timestamp),c.mtime=new Date(a.timestamp),c.ctime=new Date(a.timestamp),c.blksize=4096,c.blocks=Math.ceil(c.size/c.blksize),c},setattr(a,c){c.mode!==void 0&&(a.mode=c.mode),c.timestamp!==void 0&&(a.timestamp=c.timestamp),c.size!==void 0&&Te.resizeFileStorage(a,c.size)},lookup(a,c){throw f.genericErrors[44]},mknod:(a,c,l,h)=>Te.createNode(a,c,l,h),rename(a,c,l){if(f.isDir(a.mode)){var h;try{h=f.lookupNode(c,l)}catch(S){}if(h)for(var I in h.contents)throw new f.ErrnoError(55)}delete a.parent.contents[a.name],a.parent.timestamp=Date.now(),a.name=l,c.contents[l]=a,c.timestamp=a.parent.timestamp,a.parent=c},unlink(a,c){delete a.contents[c],a.timestamp=Date.now()},rmdir(a,c){var l=f.lookupNode(a,c);for(var h in l.contents)throw new f.ErrnoError(55);delete a.contents[c],a.timestamp=Date.now()},readdir(a){var c=[".",".."];for(var l in a.contents)a.contents.hasOwnProperty(l)&&c.push(l);return c},symlink(a,c,l){var h=Te.createNode(a,c,41471,0);return h.link=l,h},readlink(a){if(!f.isLink(a.mode))throw new f.ErrnoError(28);return a.link}},stream_ops:{read(a,c,l,h,I){var S=a.node.contents;if(I>=a.node.usedBytes)return 0;var A=Math.min(a.node.usedBytes-I,h);if(A>8&&S.subarray)c.set(S.subarray(I,I+A),l);else for(var R=0;R<A;R++)c[l+R]=S[I+R];return A},write(a,c,l,h,I,S){if(!h)return 0;var A=a.node;if(A.timestamp=Date.now(),c.subarray&&(!A.contents||A.contents.subarray)){if(S)return A.contents=c.subarray(l,l+h),A.usedBytes=h,h;if(A.usedBytes===0&&I===0)return A.contents=c.slice(l,l+h),A.usedBytes=h,h;if(I+h<=A.usedBytes)return A.contents.set(c.subarray(l,l+h),I),h}if(Te.expandFileStorage(A,I+h),A.contents.subarray&&c.subarray)A.contents.set(c.subarray(l,l+h),I);else for(var R=0;R<h;R++)A.contents[I+R]=c[l+R];return A.usedBytes=Math.max(A.usedBytes,I+h),h},llseek(a,c,l){var h=c;if(l===1?h+=a.position:l===2&&f.isFile(a.node.mode)&&(h+=a.node.usedBytes),h<0)throw new f.ErrnoError(28);return h},allocate(a,c,l){Te.expandFileStorage(a.node,c+l),a.node.usedBytes=Math.max(a.node.usedBytes,c+l)},mmap(a,c,l,h,I){if(!f.isFile(a.node.mode))throw new f.ErrnoError(43);var S,A,R=a.node.contents;if(2&I||R.buffer!==Q.buffer){if((l>0||l+c<R.length)&&(R=R.subarray?R.subarray(l,l+c):Array.prototype.slice.call(R,l,l+c)),A=!0,!(S=an()))throw new f.ErrnoError(48);Q.set(R,S)}else A=!1,S=R.byteOffset;return{ptr:S,allocated:A}},msync:(a,c,l,h,I)=>(Te.stream_ops.write(a,c,0,h,l,!1),0)}},_u=(a,c,l,h)=>{var I=h?"":`al ${a}`;n(a,S=>{var A;A=`Loading data file "${a}" failed (no arrayBuffer).`,S||Cr(A),c(new Uint8Array(S)),I&&no()},S=>{if(!l)throw`Loading data file "${a}" failed.`;l()}),I&&on()},Tu=o.preloadPlugins||[];function O(a,c){var l=0;return a&&(l|=365),c&&(l|=146),l}var f={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:!1,ignorePermissions:!0,ErrnoError:null,genericErrors:{},filesystems:null,syncFSRequests:0,lookupPath:(a,c={})=>{if(!(a=Wt.resolve(a)))return{path:"",node:null};if((c=Object.assign({follow_mount:!0,recurse_count:0},c)).recurse_count>8)throw new f.ErrnoError(32);for(var l=a.split("/").filter(w=>!!w),h=f.root,I="/",S=0;S<l.length;S++){var A=S===l.length-1;if(A&&c.parent)break;if(h=f.lookupNode(h,l[S]),I=F.join2(I,l[S]),f.isMountpoint(h)&&(!A||A&&c.follow_mount)&&(h=h.mounted.root),!A||c.follow)for(var R=0;f.isLink(h.mode);){var M=f.readlink(I);if(I=Wt.resolve(F.dirname(I),M),h=f.lookupPath(I,{recurse_count:c.recurse_count+1}).node,R++>40)throw new f.ErrnoError(32)}}return{path:I,node:h}},getPath:a=>{for(var c;;){if(f.isRoot(a)){var l=a.mount.mountpoint;return c?l[l.length-1]!=="/"?`${l}/${c}`:l+c:l}c=c?`${a.name}/${c}`:a.name,a=a.parent}},hashName:(a,c)=>{for(var l=0,h=0;h<c.length;h++)l=(l<<5)-l+c.charCodeAt(h)|0;return(a+l>>>0)%f.nameTable.length},hashAddNode:a=>{var c=f.hashName(a.parent.id,a.name);a.name_next=f.nameTable[c],f.nameTable[c]=a},hashRemoveNode:a=>{var c=f.hashName(a.parent.id,a.name);if(f.nameTable[c]===a)f.nameTable[c]=a.name_next;else for(var l=f.nameTable[c];l;){if(l.name_next===a){l.name_next=a.name_next;break}l=l.name_next}},lookupNode:(a,c)=>{var l=f.mayLookup(a);if(l)throw new f.ErrnoError(l,a);for(var h=f.hashName(a.id,c),I=f.nameTable[h];I;I=I.name_next){var S=I.name;if(I.parent.id===a.id&&S===c)return I}return f.lookup(a,c)},createNode:(a,c,l,h)=>{var I=new f.FSNode(a,c,l,h);return f.hashAddNode(I),I},destroyNode:a=>{f.hashRemoveNode(a)},isRoot:a=>a===a.parent,isMountpoint:a=>!!a.mounted,isFile:a=>(61440&a)==32768,isDir:a=>(61440&a)==16384,isLink:a=>(61440&a)==40960,isChrdev:a=>(61440&a)==8192,isBlkdev:a=>(61440&a)==24576,isFIFO:a=>(61440&a)==4096,isSocket:a=>!(49152&~a),flagsToPermissionString:a=>{var c=["r","w","rw"][3&a];return 512&a&&(c+="w"),c},nodePermissions:(a,c)=>f.ignorePermissions||(!c.includes("r")||292&a.mode)&&(!c.includes("w")||146&a.mode)&&(!c.includes("x")||73&a.mode)?0:2,mayLookup:a=>{var c=f.nodePermissions(a,"x");return c||(a.node_ops.lookup?0:2)},mayCreate:(a,c)=>{try{return f.lookupNode(a,c),20}catch(l){}return f.nodePermissions(a,"wx")},mayDelete:(a,c,l)=>{var h;try{h=f.lookupNode(a,c)}catch(S){return S.errno}var I=f.nodePermissions(a,"wx");if(I)return I;if(l){if(!f.isDir(h.mode))return 54;if(f.isRoot(h)||f.getPath(h)===f.cwd())return 10}else if(f.isDir(h.mode))return 31;return 0},mayOpen:(a,c)=>a?f.isLink(a.mode)?32:f.isDir(a.mode)&&(f.flagsToPermissionString(c)!=="r"||512&c)?31:f.nodePermissions(a,f.flagsToPermissionString(c)):44,MAX_OPEN_FDS:4096,nextfd:()=>{for(var a=0;a<=f.MAX_OPEN_FDS;a++)if(!f.streams[a])return a;throw new f.ErrnoError(33)},getStreamChecked:a=>{var c=f.getStream(a);if(!c)throw new f.ErrnoError(8);return c},getStream:a=>f.streams[a],createStream:(a,c=-1)=>(f.FSStream||(f.FSStream=function(){this.shared={}},f.FSStream.prototype={},Object.defineProperties(f.FSStream.prototype,{object:{get(){return this.node},set(l){this.node=l}},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(l){this.shared.flags=l}},position:{get(){return this.shared.position},set(l){this.shared.position=l}}})),a=Object.assign(new f.FSStream,a),c==-1&&(c=f.nextfd()),a.fd=c,f.streams[c]=a,a),closeStream:a=>{f.streams[a]=null},chrdev_stream_ops:{open:a=>{var c=f.getDevice(a.node.rdev);a.stream_ops=c.stream_ops,a.stream_ops.open&&a.stream_ops.open(a)},llseek:()=>{throw new f.ErrnoError(70)}},major:a=>a>>8,minor:a=>255&a,makedev:(a,c)=>a<<8|c,registerDevice:(a,c)=>{f.devices[a]={stream_ops:c}},getDevice:a=>f.devices[a],getMounts:a=>{for(var c=[],l=[a];l.length;){var h=l.pop();c.push(h),l.push.apply(l,h.mounts)}return c},syncfs:(a,c)=>{typeof a=="function"&&(c=a,a=!1),f.syncFSRequests++,f.syncFSRequests>1&&P(`warning: ${f.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`);var l=f.getMounts(f.root.mount),h=0;function I(A){return f.syncFSRequests--,c(A)}function S(A){if(A)return S.errored?void 0:(S.errored=!0,I(A));++h>=l.length&&I(null)}l.forEach(A=>{if(!A.type.syncfs)return S(null);A.type.syncfs(A,a,S)})},mount:(a,c,l)=>{var h,I=l==="/",S=!l;if(I&&f.root)throw new f.ErrnoError(10);if(!I&&!S){var A=f.lookupPath(l,{follow_mount:!1});if(l=A.path,h=A.node,f.isMountpoint(h))throw new f.ErrnoError(10);if(!f.isDir(h.mode))throw new f.ErrnoError(54)}var R={type:a,opts:c,mountpoint:l,mounts:[]},M=a.mount(R);return M.mount=R,R.root=M,I?f.root=M:h&&(h.mounted=R,h.mount&&h.mount.mounts.push(R)),M},unmount:a=>{var c=f.lookupPath(a,{follow_mount:!1});if(!f.isMountpoint(c.node))throw new f.ErrnoError(28);var l=c.node,h=l.mounted,I=f.getMounts(h);Object.keys(f.nameTable).forEach(A=>{for(var R=f.nameTable[A];R;){var M=R.name_next;I.includes(R.mount)&&f.destroyNode(R),R=M}}),l.mounted=null;var S=l.mount.mounts.indexOf(h);l.mount.mounts.splice(S,1)},lookup:(a,c)=>a.node_ops.lookup(a,c),mknod:(a,c,l)=>{var h=f.lookupPath(a,{parent:!0}).node,I=F.basename(a);if(!I||I==="."||I==="..")throw new f.ErrnoError(28);var S=f.mayCreate(h,I);if(S)throw new f.ErrnoError(S);if(!h.node_ops.mknod)throw new f.ErrnoError(63);return h.node_ops.mknod(h,I,c,l)},create:(a,c)=>(c=c!==void 0?c:438,c&=4095,c|=32768,f.mknod(a,c,0)),mkdir:(a,c)=>(c=c!==void 0?c:511,c&=1023,c|=16384,f.mknod(a,c,0)),mkdirTree:(a,c)=>{for(var l=a.split("/"),h="",I=0;I<l.length;++I)if(l[I]){h+="/"+l[I];try{f.mkdir(h,c)}catch(S){if(S.errno!=20)throw S}}},mkdev:(a,c,l)=>(l===void 0&&(l=c,c=438),c|=8192,f.mknod(a,c,l)),symlink:(a,c)=>{if(!Wt.resolve(a))throw new f.ErrnoError(44);var l=f.lookupPath(c,{parent:!0}).node;if(!l)throw new f.ErrnoError(44);var h=F.basename(c),I=f.mayCreate(l,h);if(I)throw new f.ErrnoError(I);if(!l.node_ops.symlink)throw new f.ErrnoError(63);return l.node_ops.symlink(l,h,a)},rename:(a,c)=>{var l,h,I=F.dirname(a),S=F.dirname(c),A=F.basename(a),R=F.basename(c);if(l=f.lookupPath(a,{parent:!0}).node,h=f.lookupPath(c,{parent:!0}).node,!l||!h)throw new f.ErrnoError(44);if(l.mount!==h.mount)throw new f.ErrnoError(75);var M,w=f.lookupNode(l,A),z=Wt.relative(a,S);if(z.charAt(0)!==".")throw new f.ErrnoError(28);if((z=Wt.relative(c,I)).charAt(0)!==".")throw new f.ErrnoError(55);try{M=f.lookupNode(h,R)}catch(re){}if(w!==M){var ie=f.isDir(w.mode),oe=f.mayDelete(l,A,ie);if(oe)throw new f.ErrnoError(oe);if(oe=M?f.mayDelete(h,R,ie):f.mayCreate(h,R))throw new f.ErrnoError(oe);if(!l.node_ops.rename)throw new f.ErrnoError(63);if(f.isMountpoint(w)||M&&f.isMountpoint(M))throw new f.ErrnoError(10);if(h!==l&&(oe=f.nodePermissions(l,"w")))throw new f.ErrnoError(oe);f.hashRemoveNode(w);try{l.node_ops.rename(w,h,R)}catch(re){throw re}finally{f.hashAddNode(w)}}},rmdir:a=>{var c=f.lookupPath(a,{parent:!0}).node,l=F.basename(a),h=f.lookupNode(c,l),I=f.mayDelete(c,l,!0);if(I)throw new f.ErrnoError(I);if(!c.node_ops.rmdir)throw new f.ErrnoError(63);if(f.isMountpoint(h))throw new f.ErrnoError(10);c.node_ops.rmdir(c,l),f.destroyNode(h)},readdir:a=>{var c=f.lookupPath(a,{follow:!0}).node;if(!c.node_ops.readdir)throw new f.ErrnoError(54);return c.node_ops.readdir(c)},unlink:a=>{var c=f.lookupPath(a,{parent:!0}).node;if(!c)throw new f.ErrnoError(44);var l=F.basename(a),h=f.lookupNode(c,l),I=f.mayDelete(c,l,!1);if(I)throw new f.ErrnoError(I);if(!c.node_ops.unlink)throw new f.ErrnoError(63);if(f.isMountpoint(h))throw new f.ErrnoError(10);c.node_ops.unlink(c,l),f.destroyNode(h)},readlink:a=>{var c=f.lookupPath(a).node;if(!c)throw new f.ErrnoError(44);if(!c.node_ops.readlink)throw new f.ErrnoError(28);return Wt.resolve(f.getPath(c.parent),c.node_ops.readlink(c))},stat:(a,c)=>{var l=f.lookupPath(a,{follow:!c}).node;if(!l)throw new f.ErrnoError(44);if(!l.node_ops.getattr)throw new f.ErrnoError(63);return l.node_ops.getattr(l)},lstat:a=>f.stat(a,!0),chmod:(a,c,l)=>{var h;if(typeof a=="string"?h=f.lookupPath(a,{follow:!l}).node:h=a,!h.node_ops.setattr)throw new f.ErrnoError(63);h.node_ops.setattr(h,{mode:4095&c|-4096&h.mode,timestamp:Date.now()})},lchmod:(a,c)=>{f.chmod(a,c,!0)},fchmod:(a,c)=>{var l=f.getStreamChecked(a);f.chmod(l.node,c)},chown:(a,c,l,h)=>{var I;if(typeof a=="string"?I=f.lookupPath(a,{follow:!h}).node:I=a,!I.node_ops.setattr)throw new f.ErrnoError(63);I.node_ops.setattr(I,{timestamp:Date.now()})},lchown:(a,c,l)=>{f.chown(a,c,l,!0)},fchown:(a,c,l)=>{var h=f.getStreamChecked(a);f.chown(h.node,c,l)},truncate:(a,c)=>{if(c<0)throw new f.ErrnoError(28);var l;if(typeof a=="string"?l=f.lookupPath(a,{follow:!0}).node:l=a,!l.node_ops.setattr)throw new f.ErrnoError(63);if(f.isDir(l.mode))throw new f.ErrnoError(31);if(!f.isFile(l.mode))throw new f.ErrnoError(28);var h=f.nodePermissions(l,"w");if(h)throw new f.ErrnoError(h);l.node_ops.setattr(l,{size:c,timestamp:Date.now()})},ftruncate:(a,c)=>{var l=f.getStreamChecked(a);if(!(2097155&l.flags))throw new f.ErrnoError(28);f.truncate(l.node,c)},utime:(a,c,l)=>{var h=f.lookupPath(a,{follow:!0}).node;h.node_ops.setattr(h,{timestamp:Math.max(c,l)})},open:(a,c,l)=>{if(a==="")throw new f.ErrnoError(44);var h;if(l=l===void 0?438:l,l=64&(c=typeof c=="string"?function(R){var M={r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090}[R];if(M===void 0)throw new Error(`Unknown file open mode: ${R}`);return M}(c):c)?4095&l|32768:0,typeof a=="object")h=a;else{a=F.normalize(a);try{h=f.lookupPath(a,{follow:!(131072&c)}).node}catch(R){}}var I=!1;if(64&c)if(h){if(128&c)throw new f.ErrnoError(20)}else h=f.mknod(a,l,0),I=!0;if(!h)throw new f.ErrnoError(44);if(f.isChrdev(h.mode)&&(c&=-513),65536&c&&!f.isDir(h.mode))throw new f.ErrnoError(54);if(!I){var S=f.mayOpen(h,c);if(S)throw new f.ErrnoError(S)}512&c&&!I&&f.truncate(h,0),c&=-131713;var A=f.createStream({node:h,path:f.getPath(h),flags:c,seekable:!0,position:0,stream_ops:h.stream_ops,ungotten:[],error:!1});return A.stream_ops.open&&A.stream_ops.open(A),!o.logReadFiles||1&c||(f.readFiles||(f.readFiles={}),a in f.readFiles||(f.readFiles[a]=1)),A},close:a=>{if(f.isClosed(a))throw new f.ErrnoError(8);a.getdents&&(a.getdents=null);try{a.stream_ops.close&&a.stream_ops.close(a)}catch(c){throw c}finally{f.closeStream(a.fd)}a.fd=null},isClosed:a=>a.fd===null,llseek:(a,c,l)=>{if(f.isClosed(a))throw new f.ErrnoError(8);if(!a.seekable||!a.stream_ops.llseek)throw new f.ErrnoError(70);if(l!=0&&l!=1&&l!=2)throw new f.ErrnoError(28);return a.position=a.stream_ops.llseek(a,c,l),a.ungotten=[],a.position},read:(a,c,l,h,I)=>{if(h<0||I<0)throw new f.ErrnoError(28);if(f.isClosed(a))throw new f.ErrnoError(8);if((2097155&a.flags)==1)throw new f.ErrnoError(8);if(f.isDir(a.node.mode))throw new f.ErrnoError(31);if(!a.stream_ops.read)throw new f.ErrnoError(28);var S=I!==void 0;if(S){if(!a.seekable)throw new f.ErrnoError(70)}else I=a.position;var A=a.stream_ops.read(a,c,l,h,I);return S||(a.position+=A),A},write:(a,c,l,h,I,S)=>{if(h<0||I<0)throw new f.ErrnoError(28);if(f.isClosed(a))throw new f.ErrnoError(8);if(!(2097155&a.flags))throw new f.ErrnoError(8);if(f.isDir(a.node.mode))throw new f.ErrnoError(31);if(!a.stream_ops.write)throw new f.ErrnoError(28);a.seekable&&1024&a.flags&&f.llseek(a,0,2);var A=I!==void 0;if(A){if(!a.seekable)throw new f.ErrnoError(70)}else I=a.position;var R=a.stream_ops.write(a,c,l,h,I,S);return A||(a.position+=R),R},allocate:(a,c,l)=>{if(f.isClosed(a))throw new f.ErrnoError(8);if(c<0||l<=0)throw new f.ErrnoError(28);if(!(2097155&a.flags))throw new f.ErrnoError(8);if(!f.isFile(a.node.mode)&&!f.isDir(a.node.mode))throw new f.ErrnoError(43);if(!a.stream_ops.allocate)throw new f.ErrnoError(138);a.stream_ops.allocate(a,c,l)},mmap:(a,c,l,h,I)=>{if(2&h&&!(2&I)&&(2097155&a.flags)!=2)throw new f.ErrnoError(2);if((2097155&a.flags)==1)throw new f.ErrnoError(2);if(!a.stream_ops.mmap)throw new f.ErrnoError(43);return a.stream_ops.mmap(a,c,l,h,I)},msync:(a,c,l,h,I)=>a.stream_ops.msync?a.stream_ops.msync(a,c,l,h,I):0,munmap:a=>0,ioctl:(a,c,l)=>{if(!a.stream_ops.ioctl)throw new f.ErrnoError(59);return a.stream_ops.ioctl(a,c,l)},readFile:(a,c={})=>{if(c.flags=c.flags||0,c.encoding=c.encoding||"binary",c.encoding!=="utf8"&&c.encoding!=="binary")throw new Error(`Invalid encoding type "${c.encoding}"`);var l,h=f.open(a,c.flags),I=f.stat(a).size,S=new Uint8Array(I);return f.read(h,S,0,I,0),c.encoding==="utf8"?l=Nt(S,0):c.encoding==="binary"&&(l=S),f.close(h),l},writeFile:(a,c,l={})=>{l.flags=l.flags||577;var h=f.open(a,l.flags,l.mode);if(typeof c=="string"){var I=new Uint8Array(co(c)+1),S=uo(c,I,0,I.length);f.write(h,I,0,S,void 0,l.canOwn)}else{if(!ArrayBuffer.isView(c))throw new Error("Unsupported data type");f.write(h,c,0,c.byteLength,void 0,l.canOwn)}f.close(h)},cwd:()=>f.currentPath,chdir:a=>{var c=f.lookupPath(a,{follow:!0});if(c.node===null)throw new f.ErrnoError(44);if(!f.isDir(c.node.mode))throw new f.ErrnoError(54);var l=f.nodePermissions(c.node,"x");if(l)throw new f.ErrnoError(l);f.currentPath=c.path},createDefaultDirectories:()=>{f.mkdir("/tmp"),f.mkdir("/home"),f.mkdir("/home/web_user")},createDefaultDevices:()=>{f.mkdir("/dev"),f.registerDevice(f.makedev(1,3),{read:()=>0,write:(h,I,S,A,R)=>A}),f.mkdev("/dev/null",f.makedev(1,3)),ar.register(f.makedev(5,0),ar.default_tty_ops),ar.register(f.makedev(6,0),ar.default_tty1_ops),f.mkdev("/dev/tty",f.makedev(5,0)),f.mkdev("/dev/tty1",f.makedev(6,0));var a=new Uint8Array(1024),c=0,l=()=>(c===0&&(c=sn(a).byteLength),a[--c]);f.createDevice("/dev","random",l),f.createDevice("/dev","urandom",l),f.mkdir("/dev/shm"),f.mkdir("/dev/shm/tmp")},createSpecialDirectories:()=>{f.mkdir("/proc");var a=f.mkdir("/proc/self");f.mkdir("/proc/self/fd"),f.mount({mount:()=>{var c=f.createNode(a,"fd",16895,73);return c.node_ops={lookup:(l,h)=>{var I=+h,S=f.getStreamChecked(I),A={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>S.path}};return A.parent=A,A}},c}},{},"/proc/self/fd")},createStandardStreams:()=>{o.stdin?f.createDevice("/dev","stdin",o.stdin):f.symlink("/dev/tty","/dev/stdin"),o.stdout?f.createDevice("/dev","stdout",null,o.stdout):f.symlink("/dev/tty","/dev/stdout"),o.stderr?f.createDevice("/dev","stderr",null,o.stderr):f.symlink("/dev/tty1","/dev/stderr"),f.open("/dev/stdin",0),f.open("/dev/stdout",1),f.open("/dev/stderr",1)},ensureErrnoError:()=>{f.ErrnoError||(f.ErrnoError=function(a,c){this.name="ErrnoError",this.node=c,this.setErrno=function(l){this.errno=l},this.setErrno(a),this.message="FS error"},f.ErrnoError.prototype=new Error,f.ErrnoError.prototype.constructor=f.ErrnoError,[44].forEach(a=>{f.genericErrors[a]=new f.ErrnoError(a),f.genericErrors[a].stack="<generic error, no stack>"}))},staticInit:()=>{f.ensureErrnoError(),f.nameTable=new Array(4096),f.mount(Te,{},"/"),f.createDefaultDirectories(),f.createDefaultDevices(),f.createSpecialDirectories(),f.filesystems={MEMFS:Te}},init:(a,c,l)=>{f.init.initialized=!0,f.ensureErrnoError(),o.stdin=a||o.stdin,o.stdout=c||o.stdout,o.stderr=l||o.stderr,f.createStandardStreams()},quit:()=>{f.init.initialized=!1;for(var a=0;a<f.streams.length;a++){var c=f.streams[a];c&&f.close(c)}},findObject:(a,c)=>{var l=f.analyzePath(a,c);return l.exists?l.object:null},analyzePath:(a,c)=>{try{a=(h=f.lookupPath(a,{follow:!c})).path}catch(I){}var l={isRoot:!1,exists:!1,error:0,name:null,path:null,object:null,parentExists:!1,parentPath:null,parentObject:null};try{var h=f.lookupPath(a,{parent:!0});l.parentExists=!0,l.parentPath=h.path,l.parentObject=h.node,l.name=F.basename(a),h=f.lookupPath(a,{follow:!c}),l.exists=!0,l.path=h.path,l.object=h.node,l.name=h.node.name,l.isRoot=h.path==="/"}catch(I){l.error=I.errno}return l},createPath:(a,c,l,h)=>{a=typeof a=="string"?a:f.getPath(a);for(var I=c.split("/").reverse();I.length;){var S=I.pop();if(S){var A=F.join2(a,S);try{f.mkdir(A)}catch(R){}a=A}}return A},createFile:(a,c,l,h,I)=>{var S=F.join2(typeof a=="string"?a:f.getPath(a),c),A=O(h,I);return f.create(S,A)},createDataFile:(a,c,l,h,I,S)=>{var A=c;a&&(a=typeof a=="string"?a:f.getPath(a),A=c?F.join2(a,c):a);var R=O(h,I),M=f.create(A,R);if(l){if(typeof l=="string"){for(var w=new Array(l.length),z=0,ie=l.length;z<ie;++z)w[z]=l.charCodeAt(z);l=w}f.chmod(M,146|R);var oe=f.open(M,577);f.write(oe,l,0,l.length,0,S),f.close(oe),f.chmod(M,R)}return M},createDevice:(a,c,l,h)=>{var I=F.join2(typeof a=="string"?a:f.getPath(a),c),S=O(!!l,!!h);f.createDevice.major||(f.createDevice.major=64);var A=f.makedev(f.createDevice.major++,0);return f.registerDevice(A,{open:R=>{R.seekable=!1},close:R=>{h&&h.buffer&&h.buffer.length&&h(10)},read:(R,M,w,z,ie)=>{for(var oe=0,re=0;re<z;re++){var Ae;try{Ae=l()}catch(Ue){throw new f.ErrnoError(29)}if(Ae===void 0&&oe===0)throw new f.ErrnoError(6);if(Ae==null)break;oe++,M[w+re]=Ae}return oe&&(R.node.timestamp=Date.now()),oe},write:(R,M,w,z,ie)=>{for(var oe=0;oe<z;oe++)try{h(M[w+oe])}catch(re){throw new f.ErrnoError(29)}return z&&(R.node.timestamp=Date.now()),oe}}),f.mkdev(I,S,A)},forceLoadFile:a=>{if(a.isDevice||a.isFolder||a.link||a.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{a.contents=Zo(s(a.url),!0),a.usedBytes=a.contents.length}catch(c){throw new f.ErrnoError(29)}},createLazyFile:(a,c,l,h,I)=>{function S(){this.lengthKnown=!1,this.chunks=[]}if(S.prototype.get=function(ie){if(!(ie>this.length-1||ie<0)){var oe=ie%this.chunkSize,re=ie/this.chunkSize|0;return this.getter(re)[oe]}},S.prototype.setDataGetter=function(ie){this.getter=ie},S.prototype.cacheLength=function(){var ie=new XMLHttpRequest;if(ie.open("HEAD",l,!1),ie.send(null),!(ie.status>=200&&ie.status<300||ie.status===304))throw new Error("Couldn't load "+l+". Status: "+ie.status);var oe,re=Number(ie.getResponseHeader("Content-length")),Ae=(oe=ie.getResponseHeader("Accept-Ranges"))&&oe==="bytes",Ue=(oe=ie.getResponseHeader("Content-Encoding"))&&oe==="gzip",Ce=1048576;Ae||(Ce=re);var Ke=this;Ke.setDataGetter(ze=>{var pt=ze*Ce,wi=(ze+1)*Ce-1;if(wi=Math.min(wi,re-1),Ke.chunks[ze]===void 0&&(Ke.chunks[ze]=((rr,Eo)=>{if(rr>Eo)throw new Error("invalid range ("+rr+", "+Eo+") or no bytes requested!");if(Eo>re-1)throw new Error("only "+re+" bytes available! programmer error!");var ot=new XMLHttpRequest;if(ot.open("GET",l,!1),re!==Ce&&ot.setRequestHeader("Range","bytes="+rr+"-"+Eo),ot.responseType="arraybuffer",ot.overrideMimeType&&ot.overrideMimeType("text/plain; charset=x-user-defined"),ot.send(null),!(ot.status>=200&&ot.status<300||ot.status===304))throw new Error("Couldn't load "+l+". Status: "+ot.status);return ot.response!==void 0?new Uint8Array(ot.response||[]):Zo(ot.responseText||"",!0)})(pt,wi)),Ke.chunks[ze]===void 0)throw new Error("doXHR failed!");return Ke.chunks[ze]}),!Ue&&re||(Ce=re=1,re=this.getter(0).length,Ce=re,k("LazyFiles on gzip forces download of the whole file when length is accessed")),this._length=re,this._chunkSize=Ce,this.lengthKnown=!0},typeof XMLHttpRequest!="undefined"){if(!_)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var A=new S;Object.defineProperties(A,{length:{get:function(){return this.lengthKnown||this.cacheLength(),this._length}},chunkSize:{get:function(){return this.lengthKnown||this.cacheLength(),this._chunkSize}}});var R={isDevice:!1,contents:A}}else R={isDevice:!1,url:l};var M=f.createFile(a,c,R,h,I);R.contents?M.contents=R.contents:R.url&&(M.contents=null,M.url=R.url),Object.defineProperties(M,{usedBytes:{get:function(){return this.contents.length}}});var w={};function z(ie,oe,re,Ae,Ue){var Ce=ie.node.contents;if(Ue>=Ce.length)return 0;var Ke=Math.min(Ce.length-Ue,Ae);if(Ce.slice)for(var ze=0;ze<Ke;ze++)oe[re+ze]=Ce[Ue+ze];else for(ze=0;ze<Ke;ze++)oe[re+ze]=Ce.get(Ue+ze);return Ke}return Object.keys(M.stream_ops).forEach(ie=>{var oe=M.stream_ops[ie];w[ie]=function(){return f.forceLoadFile(M),oe.apply(null,arguments)}}),w.read=(ie,oe,re,Ae,Ue)=>(f.forceLoadFile(M),z(ie,oe,re,Ae,Ue)),w.mmap=(ie,oe,re,Ae,Ue)=>{f.forceLoadFile(M);var Ce=an();if(!Ce)throw new f.ErrnoError(48);return z(ie,Q,Ce,oe,re),{ptr:Ce,allocated:!0}},M.stream_ops=w,M}},yi=(a,c)=>a?Nt(Ne,a,c):"",_t={DEFAULT_POLLMASK:5,calculateAt:function(a,c,l){if(F.isAbs(c))return c;var h;if(a===-100?h=f.cwd():h=_t.getStreamFromFD(a).path,c.length==0){if(!l)throw new f.ErrnoError(44);return h}return F.join2(h,c)},doStat:function(a,c,l){try{var h=a(c)}catch(R){if(R&&R.node&&F.normalize(c)!==F.normalize(f.getPath(R.node)))return-54;throw R}xe[l>>2]=h.dev,xe[l+4>>2]=h.mode,Fe[l+8>>2]=h.nlink,xe[l+12>>2]=h.uid,xe[l+16>>2]=h.gid,xe[l+20>>2]=h.rdev,Ge=[h.size>>>0,(ge=h.size,+Math.abs(ge)>=1?ge>0?+Math.floor(ge/4294967296)>>>0:~~+Math.ceil((ge-+(~~ge>>>0))/4294967296)>>>0:0)],xe[l+24>>2]=Ge[0],xe[l+28>>2]=Ge[1],xe[l+32>>2]=4096,xe[l+36>>2]=h.blocks;var I=h.atime.getTime(),S=h.mtime.getTime(),A=h.ctime.getTime();return Ge=[Math.floor(I/1e3)>>>0,(ge=Math.floor(I/1e3),+Math.abs(ge)>=1?ge>0?+Math.floor(ge/4294967296)>>>0:~~+Math.ceil((ge-+(~~ge>>>0))/4294967296)>>>0:0)],xe[l+40>>2]=Ge[0],xe[l+44>>2]=Ge[1],Fe[l+48>>2]=I%1e3*1e3,Ge=[Math.floor(S/1e3)>>>0,(ge=Math.floor(S/1e3),+Math.abs(ge)>=1?ge>0?+Math.floor(ge/4294967296)>>>0:~~+Math.ceil((ge-+(~~ge>>>0))/4294967296)>>>0:0)],xe[l+56>>2]=Ge[0],xe[l+60>>2]=Ge[1],Fe[l+64>>2]=S%1e3*1e3,Ge=[Math.floor(A/1e3)>>>0,(ge=Math.floor(A/1e3),+Math.abs(ge)>=1?ge>0?+Math.floor(ge/4294967296)>>>0:~~+Math.ceil((ge-+(~~ge>>>0))/4294967296)>>>0:0)],xe[l+72>>2]=Ge[0],xe[l+76>>2]=Ge[1],Fe[l+80>>2]=A%1e3*1e3,Ge=[h.ino>>>0,(ge=h.ino,+Math.abs(ge)>=1?ge>0?+Math.floor(ge/4294967296)>>>0:~~+Math.ceil((ge-+(~~ge>>>0))/4294967296)>>>0:0)],xe[l+88>>2]=Ge[0],xe[l+92>>2]=Ge[1],0},doMsync:function(a,c,l,h,I){if(!f.isFile(c.node.mode))throw new f.ErrnoError(43);if(2&h)return 0;var S=Ne.slice(a,a+l);f.msync(c,S,I,l,h)},varargs:void 0,get:()=>(_t.varargs+=4,xe[_t.varargs-4>>2]),getStr:a=>yi(a),getStreamFromFD:function(a){return f.getStreamChecked(a)}};function qr(a){switch(a){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError(`Unknown type size: ${a}`)}}var Va=void 0;function St(a){for(var c="",l=a;Ne[l];)c+=Va[Ne[l++]];return c}var Ai={},tr={},Ko={},bi=void 0;function Le(a){throw new bi(a)}var Fa=void 0;function zt(a){throw new Fa(a)}function lo(a,c,l){function h(R){var M=l(R);M.length!==a.length&&zt("Mismatched type converter count");for(var w=0;w<a.length;++w)cr(a[w],M[w])}a.forEach(function(R){Ko[R]=c});var I=new Array(c.length),S=[],A=0;c.forEach((R,M)=>{tr.hasOwnProperty(R)?I[M]=tr[R]:(S.push(R),Ai.hasOwnProperty(R)||(Ai[R]=[]),Ai[R].push(()=>{I[M]=tr[R],++A===S.length&&h(I)}))}),S.length===0&&h(I)}function cr(a,c,l={}){if(!("argPackAdvance"in c))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(h,I,S={}){var A=I.name;if(h||Le(`type "${A}" must have a positive integer typeid pointer`),tr.hasOwnProperty(h)){if(S.ignoreDuplicateRegistrations)return;Le(`Cannot register type '${A}' twice`)}if(tr[h]=I,delete Ko[h],Ai.hasOwnProperty(h)){var R=Ai[h];delete Ai[h],R.forEach(M=>M())}}(a,c,l)}function es(a){if(!(this instanceof wr)||!(a instanceof wr))return!1;for(var c=this.$$.ptrType.registeredClass,l=this.$$.ptr,h=a.$$.ptrType.registeredClass,I=a.$$.ptr;c.baseClass;)l=c.upcast(l),c=c.baseClass;for(;h.baseClass;)I=h.upcast(I),h=h.baseClass;return c===h&&l===I}function mo(a){Le(a.$$.ptrType.registeredClass.name+" instance already deleted")}var ts=!1;function $a(a){}function rs(a){a.count.value-=1,a.count.value===0&&function(c){c.smartPtr?c.smartPtrType.rawDestructor(c.smartPtr):c.ptrType.registeredClass.rawDestructor(c.ptr)}(a)}function Ba(a,c,l){if(c===l)return a;if(l.baseClass===void 0)return null;var h=Ba(a,c,l.baseClass);return h===null?null:l.downcast(h)}var Ha={};function Iu(){return Object.keys(Nr).length}function is(){var a=[];for(var c in Nr)Nr.hasOwnProperty(c)&&a.push(Nr[c]);return a}var po=[];function cn(){for(;po.length;){var a=po.pop();a.$$.deleteScheduled=!1,a.delete()}}var ho=void 0;function dr(a){ho=a,po.length&&ho&&ho(cn)}var Nr={};function Wa(a,c){return c=function(l,h){for(h===void 0&&Le("ptr should not be undefined");l.baseClass;)h=l.upcast(h),l=l.baseClass;return h}(a,c),Nr[c]}function os(a,c){return c.ptrType&&c.ptr||zt("makeClassHandle requires ptr and ptrType"),!!c.smartPtrType!=!!c.smartPtr&&zt("Both smartPtrType and smartPtr must be specified"),c.count={value:1},ur(Object.create(a,{$$:{value:c}}))}function Su(a){var c=this.getPointee(a);if(!c)return this.destructor(a),null;var l=Wa(this.registeredClass,c);if(l!==void 0){if(l.$$.count.value===0)return l.$$.ptr=c,l.$$.smartPtr=a,l.clone();var h=l.clone();return this.destructor(a),h}function I(){return this.isSmartPointer?os(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:c,smartPtrType:this,smartPtr:a}):os(this.registeredClass.instancePrototype,{ptrType:this,ptr:a})}var S,A=this.registeredClass.getActualType(c),R=Ha[A];if(!R)return I.call(this);S=this.isConst?R.constPointerType:R.pointerType;var M=Ba(c,this.registeredClass,S.registeredClass);return M===null?I.call(this):this.isSmartPointer?os(S.registeredClass.instancePrototype,{ptrType:S,ptr:M,smartPtrType:this,smartPtr:a}):os(S.registeredClass.instancePrototype,{ptrType:S,ptr:M})}var ur=function(a){return typeof FinalizationRegistry=="undefined"?(ur=c=>c,a):(ts=new FinalizationRegistry(c=>{rs(c.$$)}),$a=c=>ts.unregister(c),(ur=c=>{var l=c.$$;if(l.smartPtr){var h={$$:l};ts.register(c,h,c)}return c})(a))};function Ga(){if(this.$$.ptr||mo(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var a,c=ur(Object.create(Object.getPrototypeOf(this),{$$:{value:(a=this.$$,{count:a.count,deleteScheduled:a.deleteScheduled,preservePointerOnDelete:a.preservePointerOnDelete,ptr:a.ptr,ptrType:a.ptrType,smartPtr:a.smartPtr,smartPtrType:a.smartPtrType})}}));return c.$$.count.value+=1,c.$$.deleteScheduled=!1,c}function ja(){this.$$.ptr||mo(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&Le("Object already scheduled for deletion"),$a(this),rs(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)}function dn(){return!this.$$.ptr}function qa(){return this.$$.ptr||mo(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&Le("Object already scheduled for deletion"),po.push(this),po.length===1&&ho&&ho(cn),this.$$.deleteScheduled=!0,this}function wr(){}var Ja=48,za=57;function fo(a){if(a===void 0)return"_unknown";var c=(a=a.replace(/[^a-zA-Z0-9_]/g,"$")).charCodeAt(0);return c>=Ja&&c<=za?`_${a}`:a}function Vt(a,c){return a=fo(a),{[a]:function(){return c.apply(this,arguments)}}[a]}function un(a,c,l){if(a[c].overloadTable===void 0){var h=a[c];a[c]=function(){return a[c].overloadTable.hasOwnProperty(arguments.length)||Le(`Function '${l}' called with an invalid number of arguments (${arguments.length}) - expects one of (${a[c].overloadTable})!`),a[c].overloadTable[arguments.length].apply(this,arguments)},a[c].overloadTable=[],a[c].overloadTable[h.argCount]=h}}function yu(a,c,l,h,I,S,A,R){this.name=a,this.constructor=c,this.instancePrototype=l,this.rawDestructor=h,this.baseClass=I,this.getActualType=S,this.upcast=A,this.downcast=R,this.pureVirtualFunctions=[]}function Ri(a,c,l){for(;c!==l;)c.upcast||Le(`Expected null or instance of ${l.name}, got an instance of ${c.name}`),a=c.upcast(a),c=c.baseClass;return a}function ln(a,c){if(c===null)return this.isReference&&Le(`null is not a valid ${this.name}`),0;c.$$||Le(`Cannot pass "${cs(c)}" as a ${this.name}`),c.$$.ptr||Le(`Cannot pass deleted object as a pointer of type ${this.name}`);var l=c.$$.ptrType.registeredClass;return Ri(c.$$.ptr,l,this.registeredClass)}function Au(a,c){var l;if(c===null)return this.isReference&&Le(`null is not a valid ${this.name}`),this.isSmartPointer?(l=this.rawConstructor(),a!==null&&a.push(this.rawDestructor,l),l):0;c.$$||Le(`Cannot pass "${cs(c)}" as a ${this.name}`),c.$$.ptr||Le(`Cannot pass deleted object as a pointer of type ${this.name}`),!this.isConst&&c.$$.ptrType.isConst&&Le(`Cannot convert argument of type ${c.$$.smartPtrType?c.$$.smartPtrType.name:c.$$.ptrType.name} to parameter type ${this.name}`);var h=c.$$.ptrType.registeredClass;if(l=Ri(c.$$.ptr,h,this.registeredClass),this.isSmartPointer)switch(c.$$.smartPtr===void 0&&Le("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:c.$$.smartPtrType===this?l=c.$$.smartPtr:Le(`Cannot convert argument of type ${c.$$.smartPtrType?c.$$.smartPtrType.name:c.$$.ptrType.name} to parameter type ${this.name}`);break;case 1:l=c.$$.smartPtr;break;case 2:if(c.$$.smartPtrType===this)l=c.$$.smartPtr;else{var I=c.clone();l=this.rawShare(l,Di.toHandle(function(){I.delete()})),a!==null&&a.push(this.rawDestructor,l)}break;default:Le("Unsupporting sharing policy")}return l}function bu(a,c){if(c===null)return this.isReference&&Le(`null is not a valid ${this.name}`),0;c.$$||Le(`Cannot pass "${cs(c)}" as a ${this.name}`),c.$$.ptr||Le(`Cannot pass deleted object as a pointer of type ${this.name}`),c.$$.ptrType.isConst&&Le(`Cannot convert argument of type ${c.$$.ptrType.name} to parameter type ${this.name}`);var l=c.$$.ptrType.registeredClass;return Ri(c.$$.ptr,l,this.registeredClass)}function go(a){return this.fromWireType(xe[a>>2])}function Xa(a){return this.rawGetPointee&&(a=this.rawGetPointee(a)),a}function Ru(a){this.rawDestructor&&this.rawDestructor(a)}function Qa(a){a!==null&&a.delete()}function lr(a,c,l,h,I,S,A,R,M,w,z){this.name=a,this.registeredClass=c,this.isReference=l,this.isConst=h,this.isSmartPointer=I,this.pointeeType=S,this.sharingPolicy=A,this.rawGetPointee=R,this.rawConstructor=M,this.rawShare=w,this.rawDestructor=z,I||c.baseClass!==void 0?this.toWireType=Au:h?(this.toWireType=ln,this.destructorFunction=null):(this.toWireType=bu,this.destructorFunction=null)}var ss=[],Ya=a=>{var c=ss[a];return c||(a>=ss.length&&(ss.length=a+1),ss[a]=c=tn.get(a)),c},vu=(a,c,l)=>a.includes("j")?((h,I,S)=>{var A=o["dynCall_"+h];return S&&S.length?A.apply(null,[I].concat(S)):A.call(null,I)})(a,c,l):Ya(c).apply(null,l),Cu=(a,c)=>{var l=[];return function(){return l.length=0,Object.assign(l,arguments),vu(a,c,l)}};function vi(a,c){var l=(a=St(a)).includes("j")?Cu(a,c):Ya(c);return typeof l!="function"&&Le(`unknown function pointer with signature ${a}: ${c}`),l}var Za=void 0;function ns(a){var c=pr(a),l=St(c);return yt(c),l}function as(a,c){var l=[],h={};throw c.forEach(function I(S){h[S]||tr[S]||(Ko[S]?Ko[S].forEach(I):(l.push(S),h[S]=!0))}),new Za(`${a}: `+l.map(ns).join([", "]))}function mn(a,c){for(var l=[],h=0;h<a;h++)l.push(Fe[c+4*h>>2]);return l}function Ka(a){for(;a.length;){var c=a.pop();a.pop()(c)}}function pn(a,c){if(!(a instanceof Function))throw new TypeError(`new_ called with constructor type ${typeof a} which is not a function`);var l=Vt(a.name||"unknownFunctionName",function(){});l.prototype=a.prototype;var h=new l,I=a.apply(h,c);return I instanceof Object?I:h}function Ci(a,c,l,h,I,S){var A=c.length;A<2&&Le("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var R=c[1]!==null&&l!==null,M=!1,w=1;w<c.length;++w)if(c[w]!==null&&c[w].destructorFunction===void 0){M=!0;break}var z=c[0].name!=="void",ie="",oe="";for(w=0;w<A-2;++w)ie+=(w!==0?", ":"")+"arg"+w,oe+=(w!==0?", ":"")+"arg"+w+"Wired";var re=`
|
|
52
|
+
return function ${fo(a)}(${ie}) {
|
|
53
53
|
if (arguments.length !== ${A-2}) {
|
|
54
54
|
throwBindingError('function ${a} called with ${arguments.length} arguments, expected ${A-2} args!');
|
|
55
55
|
}`;M&&(re+=`var destructors = [];
|
|
56
|
-
`);var
|
|
57
|
-
`),w=0;w<A-2;++w)re+="var arg"+w+"Wired = argType"+w+".toWireType("+
|
|
58
|
-
`,
|
|
56
|
+
`);var Ae=M?"destructors":"null",Ue=["throwBindingError","invoker","fn","runDestructors","retType","classParam"],Ce=[Le,h,I,Ka,c[0],c[1]];for(R&&(re+="var thisWired = classParam.toWireType("+Ae+`, this);
|
|
57
|
+
`),w=0;w<A-2;++w)re+="var arg"+w+"Wired = argType"+w+".toWireType("+Ae+", arg"+w+"); // "+c[w+2].name+`
|
|
58
|
+
`,Ue.push("argType"+w),Ce.push(c[w+2]);if(R&&(oe="thisWired"+(oe.length>0?", ":"")+oe),re+=(z||S?"var rv = ":"")+"invoker(fn"+(oe.length>0?", ":"")+oe+`);
|
|
59
59
|
`,M)re+=`runDestructors(destructors);
|
|
60
60
|
`;else for(w=R?1:2;w<c.length;++w){var Ke=w===1?"thisWired":"arg"+(w-2)+"Wired";c[w].destructorFunction!==null&&(re+=Ke+"_dtor("+Ke+"); // "+c[w].name+`
|
|
61
|
-
`,
|
|
61
|
+
`,Ue.push(Ke+"_dtor"),Ce.push(c[w].destructorFunction))}return z&&(re+=`var ret = retType.fromWireType(rv);
|
|
62
62
|
return ret;
|
|
63
63
|
`),re+=`}
|
|
64
|
-
`,
|
|
65
|
-
`+c.replace(/^Error(:[^\n]*)?\n/,""))})).prototype=Object.create(
|
|
64
|
+
`,Ue.push(re),pn(Function,Ue).apply(null,Ce)}function ec(){this.allocated=[void 0],this.freelist=[]}var wt=new ec;function tc(a){a>=wt.reserved&&--wt.get(a).refcount==0&&wt.free(a)}function mr(){for(var a=0,c=wt.reserved;c<wt.allocated.length;++c)wt.allocated[c]!==void 0&&++a;return a}var Di={toValue:a=>(a||Le("Cannot use deleted val. handle = "+a),wt.get(a).value),toHandle:a=>{switch(a){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:return wt.allocate({refcount:1,value:a})}}};function cs(a){if(a===null)return"null";var c=typeof a;return c==="object"||c==="array"||c==="function"?a.toString():""+a}function rc(a,c){switch(c){case 2:return function(l){return this.fromWireType(Ks[l>>2])};case 3:return function(l){return this.fromWireType(en[l>>3])};default:throw new TypeError("Unknown float type: "+a)}}function ic(a,c,l){switch(c){case 0:return l?function(h){return Q[h]}:function(h){return Ne[h]};case 1:return l?function(h){return De[h>>1]}:function(h){return me[h>>1]};case 2:return l?function(h){return xe[h>>2]}:function(h){return Fe[h>>2]};default:throw new TypeError("Unknown integer type: "+a)}}var T=typeof TextDecoder!="undefined"?new TextDecoder("utf-16le"):void 0,E=(a,c)=>{for(var l=a,h=l>>1,I=h+c/2;!(h>=I)&&me[h];)++h;if((l=h<<1)-a>32&&T)return T.decode(Ne.subarray(a,l));for(var S="",A=0;!(A>=c/2);++A){var R=De[a+2*A>>1];if(R==0)break;S+=String.fromCharCode(R)}return S},v=(a,c,l)=>{if(l===void 0&&(l=2147483647),l<2)return 0;for(var h=c,I=(l-=2)<2*a.length?l/2:a.length,S=0;S<I;++S){var A=a.charCodeAt(S);De[c>>1]=A,c+=2}return De[c>>1]=0,c-h},C=a=>2*a.length,U=(a,c)=>{for(var l=0,h="";!(l>=c/4);){var I=xe[a+4*l>>2];if(I==0)break;if(++l,I>=65536){var S=I-65536;h+=String.fromCharCode(55296|S>>10,56320|1023&S)}else h+=String.fromCharCode(I)}return h},W=(a,c,l)=>{if(l===void 0&&(l=2147483647),l<4)return 0;for(var h=c,I=h+l-4,S=0;S<a.length;++S){var A=a.charCodeAt(S);if(A>=55296&&A<=57343&&(A=65536+((1023&A)<<10)|1023&a.charCodeAt(++S)),xe[c>>2]=A,(c+=4)+4>I)break}return xe[c>>2]=0,c-h},j=a=>{for(var c=0,l=0;l<a.length;++l){var h=a.charCodeAt(l);h>=55296&&h<=57343&&++l,c+=4}return c},q={},Z=[],B=[],ce={},Re=()=>{if(!Re.strings){var a={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",_:m||"./this.program"};for(var c in ce)ce[c]===void 0?delete a[c]:a[c]=ce[c];var l=[];for(var c in a)l.push(`${c}=${a[c]}`);Re.strings=l}return Re.strings},ye,le,ve,Ze=function(a,c,l,h){a||(a=this),this.parent=a,this.mount=a.mount,this.mounted=null,this.id=f.nextInode++,this.name=c,this.mode=l,this.node_ops={},this.stream_ops={},this.rdev=h},He=365,ut=146;Object.defineProperties(Ze.prototype,{read:{get:function(){return(this.mode&He)===He},set:function(a){a?this.mode|=He:this.mode&=-366}},write:{get:function(){return(this.mode&ut)===ut},set:function(a){a?this.mode|=ut:this.mode&=-147}},isFolder:{get:function(){return f.isDir(this.mode)}},isDevice:{get:function(){return f.isChrdev(this.mode)}}}),f.FSNode=Ze,f.createPreloadedFile=function(a,c,l,h,I,S,A,R,M,w){var z=c?Wt.resolve(F.join2(a,c)):a;function ie(oe){function re(Ae){w&&w(),R||f.createDataFile(a,c,Ae,h,I,M),S&&S(),no()}(function(Ae,Ue,Ce,Ke){typeof Browser!="undefined"&&Browser.init();var ze=!1;return Tu.forEach(function(pt){ze||pt.canHandle(Ue)&&(pt.handle(Ae,Ue,Ce,Ke),ze=!0)}),ze})(oe,z,re,()=>{A&&A(),no()})||re(oe)}on(),typeof l=="string"?_u(l,oe=>ie(oe),A):ie(l)},f.staticInit(),function(){for(var a=new Array(256),c=0;c<256;++c)a[c]=String.fromCharCode(c);Va=a}(),bi=o.BindingError=class extends Error{constructor(a){super(a),this.name="BindingError"}},Fa=o.InternalError=class extends Error{constructor(a){super(a),this.name="InternalError"}},wr.prototype.isAliasOf=es,wr.prototype.clone=Ga,wr.prototype.delete=ja,wr.prototype.isDeleted=dn,wr.prototype.deleteLater=qa,o.getInheritedInstanceCount=Iu,o.getLiveInheritedInstances=is,o.flushPendingDeletes=cn,o.setDelayFunction=dr,lr.prototype.getPointee=Xa,lr.prototype.destructor=Ru,lr.prototype.argPackAdvance=8,lr.prototype.readValueFromPointer=go,lr.prototype.deleteObject=Qa,lr.prototype.fromWireType=Su,Za=o.UnboundTypeError=(ye=Error,(ve=Vt(le="UnboundTypeError",function(a){this.name=le,this.message=a;var c=new Error(a).stack;c!==void 0&&(this.stack=this.toString()+`
|
|
65
|
+
`+c.replace(/^Error(:[^\n]*)?\n/,""))})).prototype=Object.create(ye.prototype),ve.prototype.constructor=ve,ve.prototype.toString=function(){return this.message===void 0?this.name:`${this.name}: ${this.message}`},ve),Object.assign(ec.prototype,{get(a){return this.allocated[a]},has(a){return this.allocated[a]!==void 0},allocate(a){var c=this.freelist.pop()||this.allocated.length;return this.allocated[c]=a,c},free(a){this.allocated[a]=void 0,this.freelist.push(a)}}),wt.allocated.push({value:void 0},{value:null},{value:!0},{value:!1}),wt.reserved=wt.allocated.length,o.count_emval_handles=mr;var We,vt={p:function(a,c,l){throw new Ii(a).init(c,l),a},C:function(a,c,l){_t.varargs=l;try{var h=_t.getStreamFromFD(a);switch(c){case 0:return(I=_t.get())<0?-28:f.createStream(h,I).fd;case 1:case 2:case 6:case 7:return 0;case 3:return h.flags;case 4:var I=_t.get();return h.flags|=I,0;case 5:return I=_t.get(),De[I+0>>1]=2,0;case 16:case 8:default:return-28;case 9:return S=28,xe[hn()>>2]=S,-1}}catch(A){if(f===void 0||A.name!=="ErrnoError")throw A;return-A.errno}var S},w:function(a,c,l,h){_t.varargs=h;try{c=_t.getStr(c),c=_t.calculateAt(a,c);var I=h?_t.get():0;return f.open(c,l,I).fd}catch(S){if(f===void 0||S.name!=="ErrnoError")throw S;return-S.errno}},t:function(a,c,l,h,I){},n:function(a,c,l,h,I){var S=qr(l);cr(a,{name:c=St(c),fromWireType:function(A){return!!A},toWireType:function(A,R){return R?h:I},argPackAdvance:8,readValueFromPointer:function(A){var R;if(l===1)R=Q;else if(l===2)R=De;else{if(l!==4)throw new TypeError("Unknown boolean type size: "+c);R=xe}return this.fromWireType(R[A>>S])},destructorFunction:null})},r:function(a,c,l,h,I,S,A,R,M,w,z,ie,oe){z=St(z),S=vi(I,S),R&&(R=vi(A,R)),w&&(w=vi(M,w)),oe=vi(ie,oe);var re=fo(z);(function(Ae,Ue,Ce){o.hasOwnProperty(Ae)?((Ce===void 0||o[Ae].overloadTable!==void 0&&o[Ae].overloadTable[Ce]!==void 0)&&Le(`Cannot register public name '${Ae}' twice`),un(o,Ae,Ae),o.hasOwnProperty(Ce)&&Le(`Cannot register multiple overloads of a function with the same number of arguments (${Ce})!`),o[Ae].overloadTable[Ce]=Ue):(o[Ae]=Ue,Ce!==void 0&&(o[Ae].numArguments=Ce))})(re,function(){as(`Cannot construct ${z} due to unbound types`,[h])}),lo([a,c,l],h?[h]:[],function(Ae){var Ue,Ce;Ae=Ae[0],Ce=h?(Ue=Ae.registeredClass).instancePrototype:wr.prototype;var Ke=Vt(re,function(){if(Object.getPrototypeOf(this)!==ze)throw new bi("Use 'new' to construct "+z);if(pt.constructor_body===void 0)throw new bi(z+" has no accessible constructor");var ot=pt.constructor_body[arguments.length];if(ot===void 0)throw new bi(`Tried to invoke ctor of ${z} with invalid number of parameters (${arguments.length}) - expected (${Object.keys(pt.constructor_body).toString()}) parameters instead!`);return ot.apply(this,arguments)}),ze=Object.create(Ce,{constructor:{value:Ke}});Ke.prototype=ze;var pt=new yu(z,Ke,ze,oe,Ue,S,R,w);pt.baseClass&&(pt.baseClass.__derivedClasses===void 0&&(pt.baseClass.__derivedClasses=[]),pt.baseClass.__derivedClasses.push(pt));var wi=new lr(z,pt,!0,!1,!1),rr=new lr(z+"*",pt,!1,!1,!1),Eo=new lr(z+" const*",pt,!1,!0,!1);return Ha[a]={pointerType:rr,constPointerType:Eo},function(ot,bp,Du){o.hasOwnProperty(ot)||zt("Replacing nonexistant public symbol"),o[ot].overloadTable!==void 0&&Du!==void 0?o[ot].overloadTable[Du]=bp:(o[ot]=bp,o[ot].argCount=Du)}(re,Ke),[wi,rr,Eo]})},q:function(a,c,l,h,I,S){var A=mn(c,l);I=vi(h,I),lo([],[a],function(R){var M=`constructor ${(R=R[0]).name}`;if(R.registeredClass.constructor_body===void 0&&(R.registeredClass.constructor_body=[]),R.registeredClass.constructor_body[c-1]!==void 0)throw new bi(`Cannot register multiple constructors with identical number of parameters (${c-1}) for class '${R.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`);return R.registeredClass.constructor_body[c-1]=()=>{as(`Cannot construct ${R.name} due to unbound types`,A)},lo([],A,function(w){return w.splice(1,0,null),R.registeredClass.constructor_body[c-1]=Ci(M,w,null,I,S),[]}),[]})},d:function(a,c,l,h,I,S,A,R,M){var w=mn(l,h);c=St(c),S=vi(I,S),lo([],[a],function(z){var ie=`${(z=z[0]).name}.${c}`;function oe(){as(`Cannot call ${ie} due to unbound types`,w)}c.startsWith("@@")&&(c=Symbol[c.substring(2)]),R&&z.registeredClass.pureVirtualFunctions.push(c);var re=z.registeredClass.instancePrototype,Ae=re[c];return Ae===void 0||Ae.overloadTable===void 0&&Ae.className!==z.name&&Ae.argCount===l-2?(oe.argCount=l-2,oe.className=z.name,re[c]=oe):(un(re,c,ie),re[c].overloadTable[l-2]=oe),lo([],w,function(Ue){var Ce=Ci(ie,Ue,z,S,A,M);return re[c].overloadTable===void 0?(Ce.argCount=l-2,re[c]=Ce):re[c].overloadTable[l-2]=Ce,[]}),[]})},D:function(a,c){cr(a,{name:c=St(c),fromWireType:function(l){var h=Di.toValue(l);return tc(l),h},toWireType:function(l,h){return Di.toHandle(h)},argPackAdvance:8,readValueFromPointer:go,destructorFunction:null})},k:function(a,c,l){var h=qr(l);cr(a,{name:c=St(c),fromWireType:function(I){return I},toWireType:function(I,S){return S},argPackAdvance:8,readValueFromPointer:rc(c,h),destructorFunction:null})},c:function(a,c,l,h,I){c=St(c),I===-1&&(I=4294967295);var S=qr(l),A=w=>w;if(h===0){var R=32-8*l;A=w=>w<<R>>>R}var M=c.includes("unsigned");cr(a,{name:c,fromWireType:A,toWireType:M?function(w,z){return this.name,z>>>0}:function(w,z){return this.name,z},argPackAdvance:8,readValueFromPointer:ic(c,S,h!==0),destructorFunction:null})},b:function(a,c,l){var h=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][c];function I(S){var A=Fe,R=A[S>>=2],M=A[S+1];return new h(A.buffer,M,R)}cr(a,{name:l=St(l),fromWireType:I,argPackAdvance:8,readValueFromPointer:I},{ignoreDuplicateRegistrations:!0})},j:function(a,c){var l=(c=St(c))==="std::string";cr(a,{name:c,fromWireType:function(h){var I,S=Fe[h>>2],A=h+4;if(l)for(var R=A,M=0;M<=S;++M){var w=A+M;if(M==S||Ne[w]==0){var z=yi(R,w-R);I===void 0?I=z:(I+="\0",I+=z),R=w+1}}else{var ie=new Array(S);for(M=0;M<S;++M)ie[M]=String.fromCharCode(Ne[A+M]);I=ie.join("")}return yt(h),I},toWireType:function(h,I){var S;I instanceof ArrayBuffer&&(I=new Uint8Array(I));var A=typeof I=="string";A||I instanceof Uint8Array||I instanceof Uint8ClampedArray||I instanceof Int8Array||Le("Cannot pass non-string to std::string"),S=l&&A?co(I):I.length;var R=Ni(4+S+1),M=R+4;if(Fe[R>>2]=S,l&&A)uo(I,Ne,M,S+1);else if(A)for(var w=0;w<S;++w){var z=I.charCodeAt(w);z>255&&(yt(M),Le("String has UTF-16 code units that do not fit in 8 bits")),Ne[M+w]=z}else for(w=0;w<S;++w)Ne[M+w]=I[w];return h!==null&&h.push(yt,R),R},argPackAdvance:8,readValueFromPointer:go,destructorFunction:function(h){yt(h)}})},f:function(a,c,l){var h,I,S,A,R;l=St(l),c===2?(h=E,I=v,A=C,S=()=>me,R=1):c===4&&(h=U,I=W,A=j,S=()=>Fe,R=2),cr(a,{name:l,fromWireType:function(M){for(var w,z=Fe[M>>2],ie=S(),oe=M+4,re=0;re<=z;++re){var Ae=M+4+re*c;if(re==z||ie[Ae>>R]==0){var Ue=h(oe,Ae-oe);w===void 0?w=Ue:(w+="\0",w+=Ue),oe=Ae+c}}return yt(M),w},toWireType:function(M,w){typeof w!="string"&&Le(`Cannot pass non-string to C++ string type ${l}`);var z=A(w),ie=Ni(4+z+c);return Fe[ie>>2]=z>>R,I(w,ie+4,z+c),M!==null&&M.push(yt,ie),ie},argPackAdvance:8,readValueFromPointer:go,destructorFunction:function(M){yt(M)}})},o:function(a,c){cr(a,{isVoid:!0,name:c=St(c),argPackAdvance:0,fromWireType:function(){},toWireType:function(l,h){}})},g:function(a,c,l,h){var I,S;(a=Z[a])(c=Di.toValue(c),l=(S=q[I=l])===void 0?St(I):S,null,h)},m:tc,l:function(a,c){var l=function(Ue,Ce){for(var Ke,ze,pt,wi=new Array(Ue),rr=0;rr<Ue;++rr)wi[rr]=(Ke=Fe[Ce+4*rr>>2],ze="parameter "+rr,pt=void 0,(pt=tr[Ke])===void 0&&Le(ze+" has unknown type "+ns(Ke)),pt);return wi}(a,c),h=l[0],I=h.name+"_$"+l.slice(1).map(function(Ue){return Ue.name}).join("_")+"$",S=B[I];if(S!==void 0)return S;for(var A=["retType"],R=[h],M="",w=0;w<a-1;++w)M+=(w!==0?", ":"")+"arg"+w,A.push("argType"+w),R.push(l[1+w]);var z="return function "+fo("methodCaller_"+I)+`(handle, name, destructors, args) {
|
|
66
66
|
`,ie=0;for(w=0;w<a-1;++w)z+=" var arg"+w+" = argType"+w+".readValueFromPointer(args"+(ie?"+"+ie:"")+`);
|
|
67
67
|
`,ie+=l[w+1].argPackAdvance;for(z+=" var rv = handle[name]("+M+`);
|
|
68
68
|
`,w=0;w<a-1;++w)l[w+1].deleteObject&&(z+=" argType"+w+".deleteObject(arg"+w+`);
|
|
69
69
|
`);h.isVoid||(z+=` return retType.toWireType(destructors, rv);
|
|
70
70
|
`),z+=`};
|
|
71
|
-
`,A.push(z);var oe,re,ye=hn(Function,A).apply(null,R);return oe=ye,re=K.length,K.push(oe),S=re,F[I]=S,S},a:()=>{Cr("")},e:function(){return Date.now()},v:()=>De.length,A:(a,c,l)=>De.copyWithin(a,c,c+l),u:a=>{De.length,Cr("OOM")},y:(a,c)=>{var l=0;return Ae().forEach(function(h,I){var S=c+l;Be[a+4*I>>2]=S,((A,R)=>{for(var M=0;M<A.length;++M)Q[0|R++]=A.charCodeAt(M);Q[0|R]=0})(h,S),l+=h.length+1}),0},z:(a,c)=>{var l=Ae();Be[a>>2]=l.length;var h=0;return l.forEach(function(I){h+=I.length+1}),Be[c>>2]=h,0},i:function(a){try{var c=ft.getStreamFromFD(a);return f.close(c),0}catch(l){if(f===void 0||l.name!=="ErrnoError")throw l;return l.errno}},x:function(a,c){try{var l=ft.getStreamFromFD(a),h=l.tty?2:f.isDir(l.mode)?3:f.isLink(l.mode)?7:4;return Q[c|0]=h,Ce[c+2>>1]=0,Ge=[0,(ge=0,+Math.abs(ge)>=1?ge>0?+Math.floor(ge/4294967296)>>>0:~~+Math.ceil((ge-+(~~ge>>>0))/4294967296)>>>0:0)],Pe[c+8>>2]=Ge[0],Pe[c+12>>2]=Ge[1],Ge=[0,(ge=0,+Math.abs(ge)>=1?ge>0?+Math.floor(ge/4294967296)>>>0:~~+Math.ceil((ge-+(~~ge>>>0))/4294967296)>>>0:0)],Pe[c+16>>2]=Ge[0],Pe[c+20>>2]=Ge[1],0}catch(I){if(f===void 0||I.name!=="ErrnoError")throw I;return I.errno}},B:function(a,c,l,h){try{var I=((S,A,R,M)=>{for(var w=0,z=0;z<R;z++){var ie=Be[A>>2],oe=Be[A+4>>2];A+=8;var re=f.read(S,Q,ie,oe,M);if(re<0)return-1;if(w+=re,re<oe)break;M!==void 0&&(M+=re)}return w})(ft.getStreamFromFD(a),c,l);return Be[h>>2]=I,0}catch(S){if(f===void 0||S.name!=="ErrnoError")throw S;return S.errno}},s:function(a,c,l,h,I){var S,A,R=(A=l)+2097152>>>0<4194305-!!(S=c)?(S>>>0)+4294967296*A:NaN;try{if(isNaN(R))return 61;var M=ft.getStreamFromFD(a);return f.llseek(M,R,h),Ge=[M.position>>>0,(ge=M.position,+Math.abs(ge)>=1?ge>0?+Math.floor(ge/4294967296)>>>0:~~+Math.ceil((ge-+(~~ge>>>0))/4294967296)>>>0:0)],Pe[I>>2]=Ge[0],Pe[I+4>>2]=Ge[1],M.getdents&&R===0&&h===0&&(M.getdents=null),0}catch(w){if(f===void 0||w.name!=="ErrnoError")throw w;return w.errno}},h:function(a,c,l,h){try{var I=((S,A,R,M)=>{for(var w=0,z=0;z<R;z++){var ie=Be[A>>2],oe=Be[A+4>>2];A+=8;var re=f.write(S,Q,ie,oe,M);if(re<0)return-1;w+=re,M!==void 0&&(M+=re)}return w})(ft.getStreamFromFD(a),c,l);return Be[h>>2]=I,0}catch(S){if(f===void 0||S.name!=="ErrnoError")throw S;return S.errno}}},Ci=(function(){var a,c,l,h,I={a:Rt};function S(A,R){var M,w,z=A.exports;return P=(J=z).E,M=P.buffer,o.HEAP8=Q=new Int8Array(M),o.HEAP16=Ce=new Int16Array(M),o.HEAP32=Pe=new Int32Array(M),o.HEAPU8=De=new Uint8Array(M),o.HEAPU16=me=new Uint16Array(M),o.HEAPU32=Be=new Uint32Array(M),o.HEAPF32=en=new Float32Array(M),o.HEAPF64=tn=new Float64Array(M),rn=J.H,w=J.F,Qo.unshift(w),to(),z}if(sn(),o.instantiateWasm)try{return o.instantiateWasm(I,S)}catch(A){x("Module.instantiateWasm callback failed with error: "+A),r(A)}(a=C,c=gi,l=I,h=function(A){S(A.instance)},a||typeof WebAssembly.instantiateStreaming!="function"||G(c)||typeof fetch!="function"?Nr(c,l,h):fetch(c,{credentials:"same-origin"}).then(A=>WebAssembly.instantiateStreaming(A,l).then(h,function(R){return x("wasm streaming compile failed: "+R),x("falling back to ArrayBuffer instantiation"),Nr(c,l,h)}))).catch(r)}(),a=>(Ci=J.G)(a)),Tt=a=>(Tt=J.I)(a),fn=()=>(fn=J.J)(),mr=a=>(mr=J.K)(a),gn=(o.__embind_initialize_bindings=()=>(o.__embind_initialize_bindings=J.L)(),a=>(gn=J.M)(a));o.dynCall_jiji=(a,c,l,h,I)=>(o.dynCall_jiji=J.N)(a,c,l,h,I),o._ff_h264_cabac_tables=67061;function cs(){function a(){He||(He=!0,o.calledRun=!0,on||(o.noFSInit||f.init.initialized||f.init(),f.ignorePermissions=!1,nr.init(),Ei(Qo),e(o),o.onRuntimeInitialized&&o.onRuntimeInitialized(),function(){if(o.postRun)for(typeof o.postRun=="function"&&(o.postRun=[o.postRun]);o.postRun.length;)c=o.postRun.shift(),fi.unshift(c);var c;Ei(fi)}()))}ee>0||(function(){if(o.preRun)for(typeof o.preRun=="function"&&(o.preRun=[o.preRun]);o.preRun.length;)c=o.preRun.shift(),vr.unshift(c);var c;Ei(vr)}(),ee>0||(o.setStatus?(o.setStatus("Running..."),setTimeout(function(){setTimeout(function(){o.setStatus("")},1),a()},1)):a()))}if(Wr=function a(){He||cs(),He||(Wr=a)},o.preInit)for(typeof o.preInit=="function"&&(o.preInit=[o.preInit]);o.preInit.length>0;)o.preInit.pop()();return cs(),t.ready}})(),bI=AI,RI=class extends Js{constructor(i){super(bI,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)}},vI=(()=>{var i=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return function(t={}){var e,r,o=t;o.ready=new Promise((T,g)=>{e=T,r=g});var s,n=Object.assign({},o),d=typeof window=="object",p=typeof importScripts=="function",m=(typeof process=="object"&&typeof process.versions=="object"&&process.versions.node,"");(d||p)&&(p?m=self.location.href:typeof document!="undefined"&&document.currentScript&&(m=document.currentScript.src),i&&(m=i),m=m.indexOf("blob:")!==0?m.substr(0,m.replace(/[?#].*/,"").lastIndexOf("/")+1):"",p&&(s=T=>{var g=new XMLHttpRequest;return g.open("GET",T,!1),g.responseType="arraybuffer",g.send(null),new Uint8Array(g.response)}));var E,_=o.print||console.log.bind(console),b=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&&(E=o.wasmBinary);var C,k;o.noExitRuntime,typeof WebAssembly!="object"&&ee("no native wasm support detected");var x,P,J,Q,De,Ce,me,Pe,Be,en=!1,tn=[],rn=[],on=[],vr=0,Qo=null,fi=null;function ee(T){o.onAbort&&o.onAbort(T),b(T="Aborted("+T+")"),en=!0,T+=". Build with -sASSERTIONS for more info.";var g=new WebAssembly.RuntimeError(T);throw r(g),g}var Hr,Wr,sn="data:application/octet-stream;base64,";function to(T){return T.startsWith(sn)}function Cr(T){if(T==Hr&&E)return new Uint8Array(E);if(s)return s(T);throw"both async and sync fetching of the wasm failed"}function gi(T,g,v){return function(N){return E||!d&&!p||typeof fetch!="function"?Promise.resolve().then(()=>Cr(N)):fetch(N,{credentials:"same-origin"}).then(U=>{if(!U.ok)throw"failed to load wasm binary file at '"+N+"'";return U.arrayBuffer()}).catch(()=>Cr(N))}(T).then(N=>WebAssembly.instantiate(N,g)).then(N=>N).then(v,N=>{b("failed to asynchronously prepare wasm: "+N),ee(N)})}to(Hr="videodec_simd.wasm")||(Wr=Hr,Hr=o.locateFile?o.locateFile(Wr,m):m+Wr);var ro=T=>{for(;T.length>0;)T.shift()(o)};function ge(T){this.excPtr=T,this.ptr=T-24,this.set_type=function(g){Ce[this.ptr+4>>2]=g},this.get_type=function(){return Ce[this.ptr+4>>2]},this.set_destructor=function(g){Ce[this.ptr+8>>2]=g},this.get_destructor=function(){return Ce[this.ptr+8>>2]},this.set_caught=function(g){g=g?1:0,x[this.ptr+12|0]=g},this.get_caught=function(){return x[this.ptr+12|0]!=0},this.set_rethrown=function(g){g=g?1:0,x[this.ptr+13|0]=g},this.get_rethrown=function(){return x[this.ptr+13|0]!=0},this.init=function(g,v){this.set_adjusted_ptr(0),this.set_type(g),this.set_destructor(v)},this.set_adjusted_ptr=function(g){Ce[this.ptr+16>>2]=g},this.get_adjusted_ptr=function(){return Ce[this.ptr+16>>2]},this.get_exception_ptr=function(){if(ic(this.get_type()))return Ce[this.excPtr>>2];var g=this.get_adjusted_ptr();return g!==0?g:this.excPtr}}function Ge(T){switch(T){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError(`Unknown type size: ${T}`)}}var Va=void 0;function G(T){for(var g="",v=T;P[v];)g+=Va[P[v++]];return g}var Gr={},Nr={},Ei={},_i=void 0;function V(T){throw new _i(T)}var nn=void 0;function Wt(T){throw new nn(T)}function Ti(T,g,v){function N(q){var K=v(q);K.length!==T.length&&Wt("Mismatched type converter count");for(var F=0;F<T.length;++F)Dt(T[F],K[F])}T.forEach(function(q){Ei[q]=g});var U=new Array(g.length),W=[],j=0;g.forEach((q,K)=>{Nr.hasOwnProperty(q)?U[K]=Nr[q]:(W.push(q),Gr.hasOwnProperty(q)||(Gr[q]=[]),Gr[q].push(()=>{U[K]=Nr[q],++j===W.length&&N(U)}))}),W.length===0&&N(U)}function Dt(T,g,v={}){if(!("argPackAdvance"in g))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(N,U,W={}){var j=U.name;if(N||V(`type "${j}" must have a positive integer typeid pointer`),Nr.hasOwnProperty(N)){if(W.ignoreDuplicateRegistrations)return;V(`Cannot register type '${j}' twice`)}if(Nr[N]=U,delete Ei[N],Gr.hasOwnProperty(N)){var q=Gr[N];delete Gr[N],q.forEach(K=>K())}}(T,g,v)}function an(T){if(!(this instanceof zt)||!(T instanceof zt))return!1;for(var g=this.$$.ptrType.registeredClass,v=this.$$.ptr,N=T.$$.ptrType.registeredClass,U=T.$$.ptr;g.baseClass;)v=g.upcast(v),g=g.baseClass;for(;N.baseClass;)U=N.upcast(U),N=N.baseClass;return g===N&&v===U}function io(T){V(T.$$.ptrType.registeredClass.name+" instance already deleted")}var oo=!1;function Yo(T){}function nr(T){T.count.value-=1,T.count.value===0&&function(g){g.smartPtr?g.smartPtrType.rawDestructor(g.smartPtr):g.ptrType.registeredClass.rawDestructor(g.ptr)}(T)}function cn(T,g,v){if(g===v)return T;if(v.baseClass===void 0)return null;var N=cn(T,g,v.baseClass);return N===null?null:v.downcast(N)}var Te={};function Eu(){return Object.keys(jr).length}function _u(){var T=[];for(var g in jr)jr.hasOwnProperty(g)&&T.push(jr[g]);return T}var O=[];function f(){for(;O.length;){var T=O.pop();T.$$.deleteScheduled=!1,T.delete()}}var Ii=void 0;function ft(T){Ii=T,O.length&&Ii&&Ii(f)}var jr={};function Ba(T,g){return g=function(v,N){for(N===void 0&&V("ptr should not be undefined");v.baseClass;)N=v.upcast(N),v=v.baseClass;return N}(T,g),jr[g]}function _t(T,g){return g.ptrType&&g.ptr||Wt("makeClassHandle requires ptr and ptrType"),!!g.smartPtrType!=!!g.smartPtr&&Wt("Both smartPtrType and smartPtr must be specified"),g.count={value:1},er(Object.create(T,{$$:{value:g}}))}function Si(T){var g=this.getPointee(T);if(!g)return this.destructor(T),null;var v=Ba(this.registeredClass,g);if(v!==void 0){if(v.$$.count.value===0)return v.$$.ptr=g,v.$$.smartPtr=T,v.clone();var N=v.clone();return this.destructor(T),N}function U(){return this.isSmartPointer?_t(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:g,smartPtrType:this,smartPtr:T}):_t(this.registeredClass.instancePrototype,{ptrType:this,ptr:T})}var W,j=this.registeredClass.getActualType(g),q=Te[j];if(!q)return U.call(this);W=this.isConst?q.constPointerType:q.pointerType;var K=cn(g,this.registeredClass,W.registeredClass);return K===null?U.call(this):this.isSmartPointer?_t(W.registeredClass.instancePrototype,{ptrType:W,ptr:K,smartPtrType:this,smartPtr:T}):_t(W.registeredClass.instancePrototype,{ptrType:W,ptr:K})}var er=function(T){return typeof FinalizationRegistry=="undefined"?(er=g=>g,T):(oo=new FinalizationRegistry(g=>{nr(g.$$)}),Yo=g=>oo.unregister(g),(er=g=>{var v=g.$$;if(v.smartPtr){var N={$$:v};oo.register(g,N,g)}return g})(T))};function Zo(){if(this.$$.ptr||io(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var T,g=er(Object.create(Object.getPrototypeOf(this),{$$:{value:(T=this.$$,{count:T.count,deleteScheduled:T.deleteScheduled,preservePointerOnDelete:T.preservePointerOnDelete,ptr:T.ptr,ptrType:T.ptrType,smartPtr:T.smartPtr,smartPtrType:T.smartPtrType})}}));return g.$$.count.value+=1,g.$$.deleteScheduled=!1,g}function yi(){this.$$.ptr||io(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&V("Object already scheduled for deletion"),Yo(this),nr(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)}function ke(){return!this.$$.ptr}function $a(){return this.$$.ptr||io(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&V("Object already scheduled for deletion"),O.push(this),O.length===1&&Ii&&Ii(f),this.$$.deleteScheduled=!0,this}function zt(){}var so=48,ar=57;function Ko(T){if(T===void 0)return"_unknown";var g=(T=T.replace(/[^a-zA-Z0-9_]/g,"$")).charCodeAt(0);return g>=so&&g<=ar?`_${T}`:T}function no(T,g){return T=Ko(T),{[T]:function(){return g.apply(this,arguments)}}[T]}function es(T,g,v){if(T[g].overloadTable===void 0){var N=T[g];T[g]=function(){return T[g].overloadTable.hasOwnProperty(arguments.length)||V(`Function '${v}' called with an invalid number of arguments (${arguments.length}) - expects one of (${T[g].overloadTable})!`),T[g].overloadTable[arguments.length].apply(this,arguments)},T[g].overloadTable=[],T[g].overloadTable[N.argCount]=N}}function Fa(T,g,v,N,U,W,j,q){this.name=T,this.constructor=g,this.instancePrototype=v,this.rawDestructor=N,this.baseClass=U,this.getActualType=W,this.upcast=j,this.downcast=q,this.pureVirtualFunctions=[]}function ts(T,g,v){for(;g!==v;)g.upcast||V(`Expected null or instance of ${v.name}, got an instance of ${g.name}`),T=g.upcast(T),g=g.baseClass;return T}function Ha(T,g){if(g===null)return this.isReference&&V(`null is not a valid ${this.name}`),0;g.$$||V(`Cannot pass "${mn(g)}" as a ${this.name}`),g.$$.ptr||V(`Cannot pass deleted object as a pointer of type ${this.name}`);var v=g.$$.ptrType.registeredClass;return ts(g.$$.ptr,v,this.registeredClass)}function Wa(T,g){var v;if(g===null)return this.isReference&&V(`null is not a valid ${this.name}`),this.isSmartPointer?(v=this.rawConstructor(),T!==null&&T.push(this.rawDestructor,v),v):0;g.$$||V(`Cannot pass "${mn(g)}" as a ${this.name}`),g.$$.ptr||V(`Cannot pass deleted object as a pointer of type ${this.name}`),!this.isConst&&g.$$.ptrType.isConst&&V(`Cannot convert argument of type ${g.$$.smartPtrType?g.$$.smartPtrType.name:g.$$.ptrType.name} to parameter type ${this.name}`);var N=g.$$.ptrType.registeredClass;if(v=ts(g.$$.ptr,N,this.registeredClass),this.isSmartPointer)switch(g.$$.smartPtr===void 0&&V("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:g.$$.smartPtrType===this?v=g.$$.smartPtr:V(`Cannot convert argument of type ${g.$$.smartPtrType?g.$$.smartPtrType.name:g.$$.ptrType.name} to parameter type ${this.name}`);break;case 1:v=g.$$.smartPtr;break;case 2:if(g.$$.smartPtrType===this)v=g.$$.smartPtr;else{var U=g.clone();v=this.rawShare(v,Ai.toHandle(function(){U.delete()})),T!==null&&T.push(this.rawDestructor,v)}break;default:V("Unsupporting sharing policy")}return v}function Tu(T,g){if(g===null)return this.isReference&&V(`null is not a valid ${this.name}`),0;g.$$||V(`Cannot pass "${mn(g)}" as a ${this.name}`),g.$$.ptr||V(`Cannot pass deleted object as a pointer of type ${this.name}`),g.$$.ptrType.isConst&&V(`Cannot convert argument of type ${g.$$.ptrType.name} to parameter type ${this.name}`);var v=g.$$.ptrType.registeredClass;return ts(g.$$.ptr,v,this.registeredClass)}function rs(T){return this.fromWireType(De[T>>2])}function ao(T){return this.rawGetPointee&&(T=this.rawGetPointee(T)),T}function dn(T){this.rawDestructor&&this.rawDestructor(T)}function co(T){T!==null&&T.delete()}function cr(T,g,v,N,U,W,j,q,K,F,ce){this.name=T,this.registeredClass=g,this.isReference=v,this.isConst=N,this.isSmartPointer=U,this.pointeeType=W,this.sharingPolicy=j,this.rawGetPointee=q,this.rawConstructor=K,this.rawShare=F,this.rawDestructor=ce,U||g.baseClass!==void 0?this.toWireType=Wa:N?(this.toWireType=Ha,this.destructorFunction=null):(this.toWireType=Tu,this.destructorFunction=null)}var Dr=[],Ga=T=>{var g=Dr[T];return g||(T>=Dr.length&&(Dr.length=T+1),Dr[T]=g=Be.get(T)),g},is=(T,g,v)=>T.includes("j")?((N,U,W)=>{var j=o["dynCall_"+N];return W&&W.length?j.apply(null,[U].concat(W)):j.call(null,U)})(T,g,v):Ga(g).apply(null,v),Iu=(T,g)=>{var v=[];return function(){return v.length=0,Object.assign(v,arguments),is(T,g,v)}};function dr(T,g){var v=(T=G(T)).includes("j")?Iu(T,g):Ga(g);return typeof v!="function"&&V(`unknown function pointer with signature ${T}: ${g}`),v}var ja=void 0;function qa(T){var g=as(T),v=G(g);return lr(g),v}function un(T,g){var v=[],N={};throw g.forEach(function U(W){N[W]||Nr[W]||(Ei[W]?Ei[W].forEach(U):(v.push(W),N[W]=!0))}),new ja(`${T}: `+v.map(qa).join([", "]))}function Ja(T,g){for(var v=[],N=0;N<T;N++)v.push(Ce[g+4*N>>2]);return v}function wr(T){for(;T.length;){var g=T.pop();T.pop()(g)}}function za(T,g){if(!(T instanceof Function))throw new TypeError(`new_ called with constructor type ${typeof T} which is not a function`);var v=no(T.name||"unknownFunctionName",function(){});v.prototype=T.prototype;var N=new v,U=T.apply(N,g);return U instanceof Object?U:N}function Xa(T,g,v,N,U,W){var j=g.length;j<2&&V("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var q=g[1]!==null&&v!==null,K=!1,F=1;F<g.length;++F)if(g[F]!==null&&g[F].destructorFunction===void 0){K=!0;break}var ce=g[0].name!=="void",Ae="",Se="";for(F=0;F<j-2;++F)Ae+=(F!==0?", ":"")+"arg"+F,Se+=(F!==0?", ":"")+"arg"+F+"Wired";var le=`
|
|
72
|
-
return function ${
|
|
71
|
+
`,A.push(z);var oe,re,Ae=pn(Function,A).apply(null,R);return oe=Ae,re=Z.length,Z.push(oe),S=re,B[I]=S,S},a:()=>{Cr("")},e:function(){return Date.now()},v:()=>Ne.length,A:(a,c,l)=>Ne.copyWithin(a,c,c+l),u:a=>{Ne.length,Cr("OOM")},y:(a,c)=>{var l=0;return Re().forEach(function(h,I){var S=c+l;Fe[a+4*I>>2]=S,((A,R)=>{for(var M=0;M<A.length;++M)Q[0|R++]=A.charCodeAt(M);Q[0|R]=0})(h,S),l+=h.length+1}),0},z:(a,c)=>{var l=Re();Fe[a>>2]=l.length;var h=0;return l.forEach(function(I){h+=I.length+1}),Fe[c>>2]=h,0},i:function(a){try{var c=_t.getStreamFromFD(a);return f.close(c),0}catch(l){if(f===void 0||l.name!=="ErrnoError")throw l;return l.errno}},x:function(a,c){try{var l=_t.getStreamFromFD(a),h=l.tty?2:f.isDir(l.mode)?3:f.isLink(l.mode)?7:4;return Q[c|0]=h,De[c+2>>1]=0,Ge=[0,(ge=0,+Math.abs(ge)>=1?ge>0?+Math.floor(ge/4294967296)>>>0:~~+Math.ceil((ge-+(~~ge>>>0))/4294967296)>>>0:0)],xe[c+8>>2]=Ge[0],xe[c+12>>2]=Ge[1],Ge=[0,(ge=0,+Math.abs(ge)>=1?ge>0?+Math.floor(ge/4294967296)>>>0:~~+Math.ceil((ge-+(~~ge>>>0))/4294967296)>>>0:0)],xe[c+16>>2]=Ge[0],xe[c+20>>2]=Ge[1],0}catch(I){if(f===void 0||I.name!=="ErrnoError")throw I;return I.errno}},B:function(a,c,l,h){try{var I=((S,A,R,M)=>{for(var w=0,z=0;z<R;z++){var ie=Fe[A>>2],oe=Fe[A+4>>2];A+=8;var re=f.read(S,Q,ie,oe,M);if(re<0)return-1;if(w+=re,re<oe)break;M!==void 0&&(M+=re)}return w})(_t.getStreamFromFD(a),c,l);return Fe[h>>2]=I,0}catch(S){if(f===void 0||S.name!=="ErrnoError")throw S;return S.errno}},s:function(a,c,l,h,I){var S,A,R=(A=l)+2097152>>>0<4194305-!!(S=c)?(S>>>0)+4294967296*A:NaN;try{if(isNaN(R))return 61;var M=_t.getStreamFromFD(a);return f.llseek(M,R,h),Ge=[M.position>>>0,(ge=M.position,+Math.abs(ge)>=1?ge>0?+Math.floor(ge/4294967296)>>>0:~~+Math.ceil((ge-+(~~ge>>>0))/4294967296)>>>0:0)],xe[I>>2]=Ge[0],xe[I+4>>2]=Ge[1],M.getdents&&R===0&&h===0&&(M.getdents=null),0}catch(w){if(f===void 0||w.name!=="ErrnoError")throw w;return w.errno}},h:function(a,c,l,h){try{var I=((S,A,R,M)=>{for(var w=0,z=0;z<R;z++){var ie=Fe[A>>2],oe=Fe[A+4>>2];A+=8;var re=f.write(S,Q,ie,oe,M);if(re<0)return-1;w+=re,M!==void 0&&(M+=re)}return w})(_t.getStreamFromFD(a),c,l);return Fe[h>>2]=I,0}catch(S){if(f===void 0||S.name!=="ErrnoError")throw S;return S.errno}}},Ni=(function(){var a,c,l,h,I={a:vt};function S(A,R){var M,w,z=A.exports;return x=(J=z).E,M=x.buffer,o.HEAP8=Q=new Int8Array(M),o.HEAP16=De=new Int16Array(M),o.HEAP32=xe=new Int32Array(M),o.HEAPU8=Ne=new Uint8Array(M),o.HEAPU16=me=new Uint16Array(M),o.HEAPU32=Fe=new Uint32Array(M),o.HEAPF32=Ks=new Float32Array(M),o.HEAPF64=en=new Float64Array(M),tn=J.H,w=J.F,Yo.unshift(w),no(),z}if(on(),o.instantiateWasm)try{return o.instantiateWasm(I,S)}catch(A){P("Module.instantiateWasm callback failed with error: "+A),r(A)}(a=N,c=_i,l=I,h=function(A){S(A.instance)},a||typeof WebAssembly.instantiateStreaming!="function"||G(c)||typeof fetch!="function"?Dr(c,l,h):fetch(c,{credentials:"same-origin"}).then(A=>WebAssembly.instantiateStreaming(A,l).then(h,function(R){return P("wasm streaming compile failed: "+R),P("falling back to ArrayBuffer instantiation"),Dr(c,l,h)}))).catch(r)}(),a=>(Ni=J.G)(a)),yt=a=>(yt=J.I)(a),hn=()=>(hn=J.J)(),pr=a=>(pr=J.K)(a),fn=(o.__embind_initialize_bindings=()=>(o.__embind_initialize_bindings=J.L)(),a=>(fn=J.M)(a));o.dynCall_jiji=(a,c,l,h,I)=>(o.dynCall_jiji=J.N)(a,c,l,h,I),o._ff_h264_cabac_tables=67061;function ds(){function a(){We||(We=!0,o.calledRun=!0,rn||(o.noFSInit||f.init.initialized||f.init(),f.ignorePermissions=!1,ar.init(),Ti(Yo),e(o),o.onRuntimeInitialized&&o.onRuntimeInitialized(),function(){if(o.postRun)for(typeof o.postRun=="function"&&(o.postRun=[o.postRun]);o.postRun.length;)c=o.postRun.shift(),Ei.unshift(c);var c;Ti(Ei)}()))}K>0||(function(){if(o.preRun)for(typeof o.preRun=="function"&&(o.preRun=[o.preRun]);o.preRun.length;)c=o.preRun.shift(),vr.unshift(c);var c;Ti(vr)}(),K>0||(o.setStatus?(o.setStatus("Running..."),setTimeout(function(){setTimeout(function(){o.setStatus("")},1),a()},1)):a()))}if(Gr=function a(){We||ds(),We||(Gr=a)},o.preInit)for(typeof o.preInit=="function"&&(o.preInit=[o.preInit]);o.preInit.length>0;)o.preInit.pop()();return ds(),t.ready}})(),NI=DI,wI=class extends ba{constructor(i){super(NI,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)}},vM=(()=>{var i=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return function(t={}){var e,r,o=t;o.ready=new Promise((T,E)=>{e=T,r=E});var s,n=Object.assign({},o),d=typeof window=="object",p=typeof importScripts=="function",m=(typeof process=="object"&&typeof process.versions=="object"&&process.versions.node,"");(d||p)&&(p?m=self.location.href:typeof document!="undefined"&&document.currentScript&&(m=document.currentScript.src),i&&(m=i),m=m.indexOf("blob:")!==0?m.substr(0,m.replace(/[?#].*/,"").lastIndexOf("/")+1):"",p&&(s=T=>{var E=new XMLHttpRequest;return E.open("GET",T,!1),E.responseType="arraybuffer",E.send(null),new Uint8Array(E.response)}));var g,_=o.print||console.log.bind(console),b=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&&(g=o.wasmBinary);var N,k;o.noExitRuntime,typeof WebAssembly!="object"&&K("no native wasm support detected");var P,x,J,Q,Ne,De,me,xe,Fe,Ks=!1,en=[],tn=[],rn=[],vr=0,Yo=null,Ei=null;function K(T){o.onAbort&&o.onAbort(T),b(T="Aborted("+T+")"),Ks=!0,T+=". Build with -sASSERTIONS for more info.";var E=new WebAssembly.RuntimeError(T);throw r(E),E}var Wr,Gr,on="data:application/octet-stream;base64,";function no(T){return T.startsWith(on)}function Cr(T){if(T==Wr&&g)return new Uint8Array(g);if(s)return s(T);throw"both async and sync fetching of the wasm failed"}function _i(T,E,v){return function(C){return g||!d&&!p||typeof fetch!="function"?Promise.resolve().then(()=>Cr(C)):fetch(C,{credentials:"same-origin"}).then(U=>{if(!U.ok)throw"failed to load wasm binary file at '"+C+"'";return U.arrayBuffer()}).catch(()=>Cr(C))}(T).then(C=>WebAssembly.instantiate(C,E)).then(C=>C).then(v,C=>{b("failed to asynchronously prepare wasm: "+C),K(C)})}no(Wr="videodec_simd.wasm")||(Gr=Wr,Wr=o.locateFile?o.locateFile(Gr,m):m+Gr);var ao=T=>{for(;T.length>0;)T.shift()(o)};function ge(T){this.excPtr=T,this.ptr=T-24,this.set_type=function(E){De[this.ptr+4>>2]=E},this.get_type=function(){return De[this.ptr+4>>2]},this.set_destructor=function(E){De[this.ptr+8>>2]=E},this.get_destructor=function(){return De[this.ptr+8>>2]},this.set_caught=function(E){E=E?1:0,P[this.ptr+12|0]=E},this.get_caught=function(){return P[this.ptr+12|0]!=0},this.set_rethrown=function(E){E=E?1:0,P[this.ptr+13|0]=E},this.get_rethrown=function(){return P[this.ptr+13|0]!=0},this.init=function(E,v){this.set_adjusted_ptr(0),this.set_type(E),this.set_destructor(v)},this.set_adjusted_ptr=function(E){De[this.ptr+16>>2]=E},this.get_adjusted_ptr=function(){return De[this.ptr+16>>2]},this.get_exception_ptr=function(){if(rc(this.get_type()))return De[this.excPtr>>2];var E=this.get_adjusted_ptr();return E!==0?E:this.excPtr}}function Ge(T){switch(T){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError(`Unknown type size: ${T}`)}}var Ua=void 0;function G(T){for(var E="",v=T;x[v];)E+=Ua[x[v++]];return E}var jr={},Dr={},Ti={},Ii=void 0;function F(T){throw new Ii(T)}var sn=void 0;function Wt(T){throw new sn(T)}function Si(T,E,v){function C(q){var Z=v(q);Z.length!==T.length&&Wt("Mismatched type converter count");for(var B=0;B<T.length;++B)Nt(T[B],Z[B])}T.forEach(function(q){Ti[q]=E});var U=new Array(E.length),W=[],j=0;E.forEach((q,Z)=>{Dr.hasOwnProperty(q)?U[Z]=Dr[q]:(W.push(q),jr.hasOwnProperty(q)||(jr[q]=[]),jr[q].push(()=>{U[Z]=Dr[q],++j===W.length&&C(U)}))}),W.length===0&&C(U)}function Nt(T,E,v={}){if(!("argPackAdvance"in E))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(C,U,W={}){var j=U.name;if(C||F(`type "${j}" must have a positive integer typeid pointer`),Dr.hasOwnProperty(C)){if(W.ignoreDuplicateRegistrations)return;F(`Cannot register type '${j}' twice`)}if(Dr[C]=U,delete Ti[C],jr.hasOwnProperty(C)){var q=jr[C];delete jr[C],q.forEach(Z=>Z())}}(T,E,v)}function nn(T){if(!(this instanceof zt)||!(T instanceof zt))return!1;for(var E=this.$$.ptrType.registeredClass,v=this.$$.ptr,C=T.$$.ptrType.registeredClass,U=T.$$.ptr;E.baseClass;)v=E.upcast(v),E=E.baseClass;for(;C.baseClass;)U=C.upcast(U),C=C.baseClass;return E===C&&v===U}function co(T){F(T.$$.ptrType.registeredClass.name+" instance already deleted")}var uo=!1;function Zo(T){}function ar(T){T.count.value-=1,T.count.value===0&&function(E){E.smartPtr?E.smartPtrType.rawDestructor(E.smartPtr):E.ptrType.registeredClass.rawDestructor(E.ptr)}(T)}function an(T,E,v){if(E===v)return T;if(v.baseClass===void 0)return null;var C=an(T,E,v.baseClass);return C===null?null:v.downcast(C)}var Te={};function _u(){return Object.keys(qr).length}function Tu(){var T=[];for(var E in qr)qr.hasOwnProperty(E)&&T.push(qr[E]);return T}var O=[];function f(){for(;O.length;){var T=O.pop();T.$$.deleteScheduled=!1,T.delete()}}var yi=void 0;function _t(T){yi=T,O.length&&yi&&yi(f)}var qr={};function Va(T,E){return E=function(v,C){for(C===void 0&&F("ptr should not be undefined");v.baseClass;)C=v.upcast(C),v=v.baseClass;return C}(T,E),qr[E]}function St(T,E){return E.ptrType&&E.ptr||Wt("makeClassHandle requires ptr and ptrType"),!!E.smartPtrType!=!!E.smartPtr&&Wt("Both smartPtrType and smartPtr must be specified"),E.count={value:1},tr(Object.create(T,{$$:{value:E}}))}function Ai(T){var E=this.getPointee(T);if(!E)return this.destructor(T),null;var v=Va(this.registeredClass,E);if(v!==void 0){if(v.$$.count.value===0)return v.$$.ptr=E,v.$$.smartPtr=T,v.clone();var C=v.clone();return this.destructor(T),C}function U(){return this.isSmartPointer?St(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:E,smartPtrType:this,smartPtr:T}):St(this.registeredClass.instancePrototype,{ptrType:this,ptr:T})}var W,j=this.registeredClass.getActualType(E),q=Te[j];if(!q)return U.call(this);W=this.isConst?q.constPointerType:q.pointerType;var Z=an(E,this.registeredClass,W.registeredClass);return Z===null?U.call(this):this.isSmartPointer?St(W.registeredClass.instancePrototype,{ptrType:W,ptr:Z,smartPtrType:this,smartPtr:T}):St(W.registeredClass.instancePrototype,{ptrType:W,ptr:Z})}var tr=function(T){return typeof FinalizationRegistry=="undefined"?(tr=E=>E,T):(uo=new FinalizationRegistry(E=>{ar(E.$$)}),Zo=E=>uo.unregister(E),(tr=E=>{var v=E.$$;if(v.smartPtr){var C={$$:v};uo.register(E,C,E)}return E})(T))};function Ko(){if(this.$$.ptr||co(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var T,E=tr(Object.create(Object.getPrototypeOf(this),{$$:{value:(T=this.$$,{count:T.count,deleteScheduled:T.deleteScheduled,preservePointerOnDelete:T.preservePointerOnDelete,ptr:T.ptr,ptrType:T.ptrType,smartPtr:T.smartPtr,smartPtrType:T.smartPtrType})}}));return E.$$.count.value+=1,E.$$.deleteScheduled=!1,E}function bi(){this.$$.ptr||co(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&F("Object already scheduled for deletion"),Zo(this),ar(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)}function Le(){return!this.$$.ptr}function Fa(){return this.$$.ptr||co(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&F("Object already scheduled for deletion"),O.push(this),O.length===1&&yi&&yi(f),this.$$.deleteScheduled=!0,this}function zt(){}var lo=48,cr=57;function es(T){if(T===void 0)return"_unknown";var E=(T=T.replace(/[^a-zA-Z0-9_]/g,"$")).charCodeAt(0);return E>=lo&&E<=cr?`_${T}`:T}function mo(T,E){return T=es(T),{[T]:function(){return E.apply(this,arguments)}}[T]}function ts(T,E,v){if(T[E].overloadTable===void 0){var C=T[E];T[E]=function(){return T[E].overloadTable.hasOwnProperty(arguments.length)||F(`Function '${v}' called with an invalid number of arguments (${arguments.length}) - expects one of (${T[E].overloadTable})!`),T[E].overloadTable[arguments.length].apply(this,arguments)},T[E].overloadTable=[],T[E].overloadTable[C.argCount]=C}}function $a(T,E,v,C,U,W,j,q){this.name=T,this.constructor=E,this.instancePrototype=v,this.rawDestructor=C,this.baseClass=U,this.getActualType=W,this.upcast=j,this.downcast=q,this.pureVirtualFunctions=[]}function rs(T,E,v){for(;E!==v;)E.upcast||F(`Expected null or instance of ${v.name}, got an instance of ${E.name}`),T=E.upcast(T),E=E.baseClass;return T}function Ba(T,E){if(E===null)return this.isReference&&F(`null is not a valid ${this.name}`),0;E.$$||F(`Cannot pass "${ln(E)}" as a ${this.name}`),E.$$.ptr||F(`Cannot pass deleted object as a pointer of type ${this.name}`);var v=E.$$.ptrType.registeredClass;return rs(E.$$.ptr,v,this.registeredClass)}function Ha(T,E){var v;if(E===null)return this.isReference&&F(`null is not a valid ${this.name}`),this.isSmartPointer?(v=this.rawConstructor(),T!==null&&T.push(this.rawDestructor,v),v):0;E.$$||F(`Cannot pass "${ln(E)}" as a ${this.name}`),E.$$.ptr||F(`Cannot pass deleted object as a pointer of type ${this.name}`),!this.isConst&&E.$$.ptrType.isConst&&F(`Cannot convert argument of type ${E.$$.smartPtrType?E.$$.smartPtrType.name:E.$$.ptrType.name} to parameter type ${this.name}`);var C=E.$$.ptrType.registeredClass;if(v=rs(E.$$.ptr,C,this.registeredClass),this.isSmartPointer)switch(E.$$.smartPtr===void 0&&F("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:E.$$.smartPtrType===this?v=E.$$.smartPtr:F(`Cannot convert argument of type ${E.$$.smartPtrType?E.$$.smartPtrType.name:E.$$.ptrType.name} to parameter type ${this.name}`);break;case 1:v=E.$$.smartPtr;break;case 2:if(E.$$.smartPtrType===this)v=E.$$.smartPtr;else{var U=E.clone();v=this.rawShare(v,Ri.toHandle(function(){U.delete()})),T!==null&&T.push(this.rawDestructor,v)}break;default:F("Unsupporting sharing policy")}return v}function Iu(T,E){if(E===null)return this.isReference&&F(`null is not a valid ${this.name}`),0;E.$$||F(`Cannot pass "${ln(E)}" as a ${this.name}`),E.$$.ptr||F(`Cannot pass deleted object as a pointer of type ${this.name}`),E.$$.ptrType.isConst&&F(`Cannot convert argument of type ${E.$$.ptrType.name} to parameter type ${this.name}`);var v=E.$$.ptrType.registeredClass;return rs(E.$$.ptr,v,this.registeredClass)}function is(T){return this.fromWireType(Ne[T>>2])}function po(T){return this.rawGetPointee&&(T=this.rawGetPointee(T)),T}function cn(T){this.rawDestructor&&this.rawDestructor(T)}function ho(T){T!==null&&T.delete()}function dr(T,E,v,C,U,W,j,q,Z,B,ce){this.name=T,this.registeredClass=E,this.isReference=v,this.isConst=C,this.isSmartPointer=U,this.pointeeType=W,this.sharingPolicy=j,this.rawGetPointee=q,this.rawConstructor=Z,this.rawShare=B,this.rawDestructor=ce,U||E.baseClass!==void 0?this.toWireType=Ha:C?(this.toWireType=Ba,this.destructorFunction=null):(this.toWireType=Iu,this.destructorFunction=null)}var Nr=[],Wa=T=>{var E=Nr[T];return E||(T>=Nr.length&&(Nr.length=T+1),Nr[T]=E=Fe.get(T)),E},os=(T,E,v)=>T.includes("j")?((C,U,W)=>{var j=o["dynCall_"+C];return W&&W.length?j.apply(null,[U].concat(W)):j.call(null,U)})(T,E,v):Wa(E).apply(null,v),Su=(T,E)=>{var v=[];return function(){return v.length=0,Object.assign(v,arguments),os(T,E,v)}};function ur(T,E){var v=(T=G(T)).includes("j")?Su(T,E):Wa(E);return typeof v!="function"&&F(`unknown function pointer with signature ${T}: ${E}`),v}var Ga=void 0;function ja(T){var E=cs(T),v=G(E);return mr(E),v}function dn(T,E){var v=[],C={};throw E.forEach(function U(W){C[W]||Dr[W]||(Ti[W]?Ti[W].forEach(U):(v.push(W),C[W]=!0))}),new Ga(`${T}: `+v.map(ja).join([", "]))}function qa(T,E){for(var v=[],C=0;C<T;C++)v.push(De[E+4*C>>2]);return v}function wr(T){for(;T.length;){var E=T.pop();T.pop()(E)}}function Ja(T,E){if(!(T instanceof Function))throw new TypeError(`new_ called with constructor type ${typeof T} which is not a function`);var v=mo(T.name||"unknownFunctionName",function(){});v.prototype=T.prototype;var C=new v,U=T.apply(C,E);return U instanceof Object?U:C}function za(T,E,v,C,U,W){var j=E.length;j<2&&F("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var q=E[1]!==null&&v!==null,Z=!1,B=1;B<E.length;++B)if(E[B]!==null&&E[B].destructorFunction===void 0){Z=!0;break}var ce=E[0].name!=="void",Re="",ye="";for(B=0;B<j-2;++B)Re+=(B!==0?", ":"")+"arg"+B,ye+=(B!==0?", ":"")+"arg"+B+"Wired";var le=`
|
|
72
|
+
return function ${es(T)}(${Re}) {
|
|
73
73
|
if (arguments.length !== ${j-2}) {
|
|
74
74
|
throwBindingError('function ${T} called with ${arguments.length} arguments, expected ${j-2} args!');
|
|
75
|
-
}`;
|
|
76
|
-
`);var
|
|
77
|
-
`),
|
|
78
|
-
`,Ze.push("argType"+
|
|
79
|
-
`,
|
|
80
|
-
`;else for(
|
|
81
|
-
`,Ze.push(
|
|
75
|
+
}`;Z&&(le+=`var destructors = [];
|
|
76
|
+
`);var ve=Z?"destructors":"null",Ze=["throwBindingError","invoker","fn","runDestructors","retType","classParam"],He=[F,C,U,wr,E[0],E[1]];for(q&&(le+="var thisWired = classParam.toWireType("+ve+`, this);
|
|
77
|
+
`),B=0;B<j-2;++B)le+="var arg"+B+"Wired = argType"+B+".toWireType("+ve+", arg"+B+"); // "+E[B+2].name+`
|
|
78
|
+
`,Ze.push("argType"+B),He.push(E[B+2]);if(q&&(ye="thisWired"+(ye.length>0?", ":"")+ye),le+=(ce||W?"var rv = ":"")+"invoker(fn"+(ye.length>0?", ":"")+ye+`);
|
|
79
|
+
`,Z)le+=`runDestructors(destructors);
|
|
80
|
+
`;else for(B=q?1:2;B<E.length;++B){var ut=B===1?"thisWired":"arg"+(B-2)+"Wired";E[B].destructorFunction!==null&&(le+=ut+"_dtor("+ut+"); // "+E[B].name+`
|
|
81
|
+
`,Ze.push(ut+"_dtor"),He.push(E[B].destructorFunction))}return ce&&(le+=`var ret = retType.fromWireType(rv);
|
|
82
82
|
return ret;
|
|
83
83
|
`),le+=`}
|
|
84
|
-
`,Ze.push(le),
|
|
85
|
-
`+
|
|
86
|
-
`,
|
|
87
|
-
`,
|
|
88
|
-
`,
|
|
89
|
-
`);
|
|
84
|
+
`,Ze.push(le),Ja(Function,Ze).apply(null,He)}function fo(){this.allocated=[void 0],this.freelist=[]}var Vt=new fo;function un(T){T>=Vt.reserved&&--Vt.get(T).refcount==0&&Vt.free(T)}function yu(){for(var T=0,E=Vt.reserved;E<Vt.allocated.length;++E)Vt.allocated[E]!==void 0&&++T;return T}var Ri={toValue:T=>(T||F("Cannot use deleted val. handle = "+T),Vt.get(T).value),toHandle:T=>{switch(T){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:return Vt.allocate({refcount:1,value:T})}}};function ln(T){if(T===null)return"null";var E=typeof T;return E==="object"||E==="array"||E==="function"?T.toString():""+T}function Au(T,E){switch(E){case 2:return function(v){return this.fromWireType(me[v>>2])};case 3:return function(v){return this.fromWireType(xe[v>>3])};default:throw new TypeError("Unknown float type: "+T)}}function bu(T,E,v){switch(E){case 0:return v?function(C){return P[C]}:function(C){return x[C]};case 1:return v?function(C){return J[C>>1]}:function(C){return Q[C>>1]};case 2:return v?function(C){return Ne[C>>2]}:function(C){return De[C>>2]};default:throw new TypeError("Unknown integer type: "+T)}}var go=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):void 0,Xa=(T,E,v)=>{for(var C=E+v,U=E;T[U]&&!(U>=C);)++U;if(U-E>16&&T.buffer&&go)return go.decode(T.subarray(E,U));for(var W="";E<U;){var j=T[E++];if(128&j){var q=63&T[E++];if((224&j)!=192){var Z=63&T[E++];if((j=(240&j)==224?(15&j)<<12|q<<6|Z:(7&j)<<18|q<<12|Z<<6|63&T[E++])<65536)W+=String.fromCharCode(j);else{var B=j-65536;W+=String.fromCharCode(55296|B>>10,56320|1023&B)}}else W+=String.fromCharCode((31&j)<<6|q)}else W+=String.fromCharCode(j)}return W},Ru=(T,E)=>T?Xa(x,T,E):"",Qa=typeof TextDecoder!="undefined"?new TextDecoder("utf-16le"):void 0,lr=(T,E)=>{for(var v=T,C=v>>1,U=C+E/2;!(C>=U)&&Q[C];)++C;if((v=C<<1)-T>32&&Qa)return Qa.decode(x.subarray(T,v));for(var W="",j=0;!(j>=E/2);++j){var q=J[T+2*j>>1];if(q==0)break;W+=String.fromCharCode(q)}return W},ss=(T,E,v)=>{if(v===void 0&&(v=2147483647),v<2)return 0;for(var C=E,U=(v-=2)<2*T.length?v/2:T.length,W=0;W<U;++W){var j=T.charCodeAt(W);J[E>>1]=j,E+=2}return J[E>>1]=0,E-C},Ya=T=>2*T.length,vu=(T,E)=>{for(var v=0,C="";!(v>=E/4);){var U=Ne[T+4*v>>2];if(U==0)break;if(++v,U>=65536){var W=U-65536;C+=String.fromCharCode(55296|W>>10,56320|1023&W)}else C+=String.fromCharCode(U)}return C},Cu=(T,E,v)=>{if(v===void 0&&(v=2147483647),v<4)return 0;for(var C=E,U=C+v-4,W=0;W<T.length;++W){var j=T.charCodeAt(W);if(j>=55296&&j<=57343&&(j=65536+((1023&j)<<10)|1023&T.charCodeAt(++W)),Ne[E>>2]=j,(E+=4)+4>U)break}return Ne[E>>2]=0,E-C},vi=T=>{for(var E=0,v=0;v<T.length;++v){var C=T.charCodeAt(v);C>=55296&&C<=57343&&++v,E+=4}return E},Za={},ns=[],as=[],mn;mn=()=>performance.now();var Ka,pn,Ci,ec=[null,[],[]];(function(){for(var T=new Array(256),E=0;E<256;++E)T[E]=String.fromCharCode(E);Ua=T})(),Ii=o.BindingError=class extends Error{constructor(T){super(T),this.name="BindingError"}},sn=o.InternalError=class extends Error{constructor(T){super(T),this.name="InternalError"}},zt.prototype.isAliasOf=nn,zt.prototype.clone=Ko,zt.prototype.delete=bi,zt.prototype.isDeleted=Le,zt.prototype.deleteLater=Fa,o.getInheritedInstanceCount=_u,o.getLiveInheritedInstances=Tu,o.flushPendingDeletes=f,o.setDelayFunction=_t,dr.prototype.getPointee=po,dr.prototype.destructor=cn,dr.prototype.argPackAdvance=8,dr.prototype.readValueFromPointer=is,dr.prototype.deleteObject=ho,dr.prototype.fromWireType=Ai,Ga=o.UnboundTypeError=(Ka=Error,(Ci=mo(pn="UnboundTypeError",function(T){this.name=pn,this.message=T;var E=new Error(T).stack;E!==void 0&&(this.stack=this.toString()+`
|
|
85
|
+
`+E.replace(/^Error(:[^\n]*)?\n/,""))})).prototype=Object.create(Ka.prototype),Ci.prototype.constructor=Ci,Ci.prototype.toString=function(){return this.message===void 0?this.name:`${this.name}: ${this.message}`},Ci),Object.assign(fo.prototype,{get(T){return this.allocated[T]},has(T){return this.allocated[T]!==void 0},allocate(T){var E=this.freelist.pop()||this.allocated.length;return this.allocated[E]=T,E},free(T){this.allocated[T]=void 0,this.freelist.push(T)}}),Vt.allocated.push({value:void 0},{value:null},{value:!0},{value:!1}),Vt.reserved=Vt.allocated.length,o.count_emval_handles=yu;var wt,tc={o:function(T,E,v){throw new ge(T).init(E,v),T},r:function(T,E,v,C,U){},m:function(T,E,v,C,U){var W=Ge(v);Nt(T,{name:E=G(E),fromWireType:function(j){return!!j},toWireType:function(j,q){return q?C:U},argPackAdvance:8,readValueFromPointer:function(j){var q;if(v===1)q=P;else if(v===2)q=J;else{if(v!==4)throw new TypeError("Unknown boolean type size: "+E);q=Ne}return this.fromWireType(q[j>>W])},destructorFunction:null})},q:function(T,E,v,C,U,W,j,q,Z,B,ce,Re,ye){ce=G(ce),W=ur(U,W),q&&(q=ur(j,q)),B&&(B=ur(Z,B)),ye=ur(Re,ye);var le=es(ce);(function(ve,Ze,He){o.hasOwnProperty(ve)?((He===void 0||o[ve].overloadTable!==void 0&&o[ve].overloadTable[He]!==void 0)&&F(`Cannot register public name '${ve}' twice`),ts(o,ve,ve),o.hasOwnProperty(He)&&F(`Cannot register multiple overloads of a function with the same number of arguments (${He})!`),o[ve].overloadTable[He]=Ze):(o[ve]=Ze,He!==void 0&&(o[ve].numArguments=He))})(le,function(){dn(`Cannot construct ${ce} due to unbound types`,[C])}),Si([T,E,v],C?[C]:[],function(ve){var Ze,He;ve=ve[0],He=C?(Ze=ve.registeredClass).instancePrototype:zt.prototype;var ut=mo(le,function(){if(Object.getPrototypeOf(this)!==We)throw new Ii("Use 'new' to construct "+ce);if(vt.constructor_body===void 0)throw new Ii(ce+" has no accessible constructor");var pr=vt.constructor_body[arguments.length];if(pr===void 0)throw new Ii(`Tried to invoke ctor of ${ce} with invalid number of parameters (${arguments.length}) - expected (${Object.keys(vt.constructor_body).toString()}) parameters instead!`);return pr.apply(this,arguments)}),We=Object.create(He,{constructor:{value:ut}});ut.prototype=We;var vt=new $a(ce,ut,We,ye,Ze,W,q,B);vt.baseClass&&(vt.baseClass.__derivedClasses===void 0&&(vt.baseClass.__derivedClasses=[]),vt.baseClass.__derivedClasses.push(vt));var Ni=new dr(ce,vt,!0,!1,!1),yt=new dr(ce+"*",vt,!1,!1,!1),hn=new dr(ce+" const*",vt,!1,!0,!1);return Te[T]={pointerType:yt,constPointerType:hn},function(pr,fn,ds){o.hasOwnProperty(pr)||Wt("Replacing nonexistant public symbol"),o[pr].overloadTable!==void 0&&ds!==void 0?o[pr].overloadTable[ds]=fn:(o[pr]=fn,o[pr].argCount=ds)}(le,ut),[Ni,yt,hn]})},p:function(T,E,v,C,U,W){var j=qa(E,v);U=ur(C,U),Si([],[T],function(q){var Z=`constructor ${(q=q[0]).name}`;if(q.registeredClass.constructor_body===void 0&&(q.registeredClass.constructor_body=[]),q.registeredClass.constructor_body[E-1]!==void 0)throw new Ii(`Cannot register multiple constructors with identical number of parameters (${E-1}) for class '${q.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`);return q.registeredClass.constructor_body[E-1]=()=>{dn(`Cannot construct ${q.name} due to unbound types`,j)},Si([],j,function(B){return B.splice(1,0,null),q.registeredClass.constructor_body[E-1]=za(Z,B,null,U,W),[]}),[]})},d:function(T,E,v,C,U,W,j,q,Z){var B=qa(v,C);E=G(E),W=ur(U,W),Si([],[T],function(ce){var Re=`${(ce=ce[0]).name}.${E}`;function ye(){dn(`Cannot call ${Re} due to unbound types`,B)}E.startsWith("@@")&&(E=Symbol[E.substring(2)]),q&&ce.registeredClass.pureVirtualFunctions.push(E);var le=ce.registeredClass.instancePrototype,ve=le[E];return ve===void 0||ve.overloadTable===void 0&&ve.className!==ce.name&&ve.argCount===v-2?(ye.argCount=v-2,ye.className=ce.name,le[E]=ye):(ts(le,E,Re),le[E].overloadTable[v-2]=ye),Si([],B,function(Ze){var He=za(Re,Ze,ce,W,j,Z);return le[E].overloadTable===void 0?(He.argCount=v-2,le[E]=He):le[E].overloadTable[v-2]=He,[]}),[]})},u:function(T,E){Nt(T,{name:E=G(E),fromWireType:function(v){var C=Ri.toValue(v);return un(v),C},toWireType:function(v,C){return Ri.toHandle(C)},argPackAdvance:8,readValueFromPointer:is,destructorFunction:null})},k:function(T,E,v){var C=Ge(v);Nt(T,{name:E=G(E),fromWireType:function(U){return U},toWireType:function(U,W){return W},argPackAdvance:8,readValueFromPointer:Au(E,C),destructorFunction:null})},b:function(T,E,v,C,U){E=G(E),U===-1&&(U=4294967295);var W=Ge(v),j=B=>B;if(C===0){var q=32-8*v;j=B=>B<<q>>>q}var Z=E.includes("unsigned");Nt(T,{name:E,fromWireType:j,toWireType:Z?function(B,ce){return this.name,ce>>>0}:function(B,ce){return this.name,ce},argPackAdvance:8,readValueFromPointer:bu(E,W,C!==0),destructorFunction:null})},a:function(T,E,v){var C=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][E];function U(W){var j=De,q=j[W>>=2],Z=j[W+1];return new C(j.buffer,Z,q)}Nt(T,{name:v=G(v),fromWireType:U,argPackAdvance:8,readValueFromPointer:U},{ignoreDuplicateRegistrations:!0})},j:function(T,E){var v=(E=G(E))==="std::string";Nt(T,{name:E,fromWireType:function(C){var U,W=De[C>>2],j=C+4;if(v)for(var q=j,Z=0;Z<=W;++Z){var B=j+Z;if(Z==W||x[B]==0){var ce=Ru(q,B-q);U===void 0?U=ce:(U+="\0",U+=ce),q=B+1}}else{var Re=new Array(W);for(Z=0;Z<W;++Z)Re[Z]=String.fromCharCode(x[j+Z]);U=Re.join("")}return mr(C),U},toWireType:function(C,U){var W;U instanceof ArrayBuffer&&(U=new Uint8Array(U));var j=typeof U=="string";j||U instanceof Uint8Array||U instanceof Uint8ClampedArray||U instanceof Int8Array||F("Cannot pass non-string to std::string"),W=v&&j?(Re=>{for(var ye=0,le=0;le<Re.length;++le){var ve=Re.charCodeAt(le);ve<=127?ye++:ve<=2047?ye+=2:ve>=55296&&ve<=57343?(ye+=4,++le):ye+=3}return ye})(U):U.length;var q=Di(4+W+1),Z=q+4;if(De[q>>2]=W,v&&j)((Re,ye,le,ve)=>{if(!(ve>0))return 0;for(var Ze=le,He=le+ve-1,ut=0;ut<Re.length;++ut){var We=Re.charCodeAt(ut);if(We>=55296&&We<=57343&&(We=65536+((1023&We)<<10)|1023&Re.charCodeAt(++ut)),We<=127){if(le>=He)break;ye[le++]=We}else if(We<=2047){if(le+1>=He)break;ye[le++]=192|We>>6,ye[le++]=128|63&We}else if(We<=65535){if(le+2>=He)break;ye[le++]=224|We>>12,ye[le++]=128|We>>6&63,ye[le++]=128|63&We}else{if(le+3>=He)break;ye[le++]=240|We>>18,ye[le++]=128|We>>12&63,ye[le++]=128|We>>6&63,ye[le++]=128|63&We}}ye[le]=0})(U,x,Z,W+1);else if(j)for(var B=0;B<W;++B){var ce=U.charCodeAt(B);ce>255&&(mr(Z),F("String has UTF-16 code units that do not fit in 8 bits")),x[Z+B]=ce}else for(B=0;B<W;++B)x[Z+B]=U[B];return C!==null&&C.push(mr,q),q},argPackAdvance:8,readValueFromPointer:is,destructorFunction:function(C){mr(C)}})},g:function(T,E,v){var C,U,W,j,q;v=G(v),E===2?(C=lr,U=ss,j=Ya,W=()=>Q,q=1):E===4&&(C=vu,U=Cu,j=vi,W=()=>De,q=2),Nt(T,{name:v,fromWireType:function(Z){for(var B,ce=De[Z>>2],Re=W(),ye=Z+4,le=0;le<=ce;++le){var ve=Z+4+le*E;if(le==ce||Re[ve>>q]==0){var Ze=C(ye,ve-ye);B===void 0?B=Ze:(B+="\0",B+=Ze),ye=ve+E}}return mr(Z),B},toWireType:function(Z,B){typeof B!="string"&&F(`Cannot pass non-string to C++ string type ${v}`);var ce=j(B),Re=Di(4+ce+E);return De[Re>>2]=ce>>q,U(B,Re+4,ce+E),Z!==null&&Z.push(mr,Re),Re},argPackAdvance:8,readValueFromPointer:is,destructorFunction:function(Z){mr(Z)}})},n:function(T,E){Nt(T,{isVoid:!0,name:E=G(E),argPackAdvance:0,fromWireType:function(){},toWireType:function(v,C){}})},e:function(T,E,v,C){var U,W;(T=ns[T])(E=Ri.toValue(E),v=(W=Za[U=v])===void 0?G(U):W,null,C)},l:un,h:function(T,E){var v=function(Ze,He){for(var ut,We,vt,Ni=new Array(Ze),yt=0;yt<Ze;++yt)Ni[yt]=(ut=De[He+4*yt>>2],We="parameter "+yt,vt=void 0,(vt=Dr[ut])===void 0&&F(We+" has unknown type "+ja(ut)),vt);return Ni}(T,E),C=v[0],U=C.name+"_$"+v.slice(1).map(function(Ze){return Ze.name}).join("_")+"$",W=as[U];if(W!==void 0)return W;for(var j=["retType"],q=[C],Z="",B=0;B<T-1;++B)Z+=(B!==0?", ":"")+"arg"+B,j.push("argType"+B),q.push(v[1+B]);var ce="return function "+es("methodCaller_"+U)+`(handle, name, destructors, args) {
|
|
86
|
+
`,Re=0;for(B=0;B<T-1;++B)ce+=" var arg"+B+" = argType"+B+".readValueFromPointer(args"+(Re?"+"+Re:"")+`);
|
|
87
|
+
`,Re+=v[B+1].argPackAdvance;for(ce+=" var rv = handle[name]("+Z+`);
|
|
88
|
+
`,B=0;B<T-1;++B)v[B+1].deleteObject&&(ce+=" argType"+B+".deleteObject(arg"+B+`);
|
|
89
|
+
`);C.isVoid||(ce+=` return retType.toWireType(destructors, rv);
|
|
90
90
|
`),ce+=`};
|
|
91
|
-
`,j.push(ce);var Se,le,be=za(Function,j).apply(null,q);return Se=be,le=ss.length,ss.push(Se),W=le,ns[U]=W,W},f:()=>{ee("")},c:pn,t:(T,g,v)=>P.copyWithin(T,g,g+v),s:T=>{P.length,ee("OOM")},i:(T,g,v,N)=>{for(var U,W,j,q=0,K=0;K<v;K++){var F=Ce[g>>2],ce=Ce[g+4>>2];g+=8;for(var Ae=0;Ae<ce;Ae++)U=T,W=P[F+Ae],j=void 0,j=tc[U],W===0||W===10?((U===1?_:b)(Qa(j,0)),j.length=0):j.push(W);q+=ce}return Ce[N>>2]=q,0}},lr=(function(){var T,g,v,N,U={a:rc};function W(j,q){var K,F,ce=j.exports;return C=(k=ce).v,K=C.buffer,o.HEAP8=x=new Int8Array(K),o.HEAP16=J=new Int16Array(K),o.HEAP32=De=new Int32Array(K),o.HEAPU8=P=new Uint8Array(K),o.HEAPU16=Q=new Uint16Array(K),o.HEAPU32=Ce=new Uint32Array(K),o.HEAPF32=me=new Float32Array(K),o.HEAPF64=Pe=new Float64Array(K),Be=k.z,F=k.w,rn.unshift(F),function(){if(vr--,o.monitorRunDependencies&&o.monitorRunDependencies(vr),vr==0&&(Qo!==null&&(clearInterval(Qo),Qo=null),fi)){var Ae=fi;fi=null,Ae()}}(),ce}if(vr++,o.monitorRunDependencies&&o.monitorRunDependencies(vr),o.instantiateWasm)try{return o.instantiateWasm(U,W)}catch(j){b("Module.instantiateWasm callback failed with error: "+j),r(j)}(T=E,g=Hr,v=U,N=function(j){W(j.instance)},T||typeof WebAssembly.instantiateStreaming!="function"||to(g)||typeof fetch!="function"?gi(g,v,N):fetch(g,{credentials:"same-origin"}).then(j=>WebAssembly.instantiateStreaming(j,v).then(N,function(q){return b("wasm streaming compile failed: "+q),b("falling back to ArrayBuffer instantiation"),gi(g,v,N)}))).catch(r)}(),T=>(lr=k.x)(T)),vi=T=>(vi=k.y)(T),as=T=>(as=k.A)(T),ic=(o.__embind_initialize_bindings=()=>(o.__embind_initialize_bindings=k.B)(),T=>(ic=k.C)(T));o.dynCall_jiji=(T,g,v,N,U)=>(o.dynCall_jiji=k.D)(T,g,v,N,U);function oc(){function T(){wt||(wt=!0,o.calledRun=!0,en||(ro(rn),e(o),o.onRuntimeInitialized&&o.onRuntimeInitialized(),function(){if(o.postRun)for(typeof o.postRun=="function"&&(o.postRun=[o.postRun]);o.postRun.length;)g=o.postRun.shift(),on.unshift(g);var g;ro(on)}()))}vr>0||(function(){if(o.preRun)for(typeof o.preRun=="function"&&(o.preRun=[o.preRun]);o.preRun.length;)g=o.preRun.shift(),tn.unshift(g);var g;ro(tn)}(),vr>0||(o.setStatus?(o.setStatus("Running..."),setTimeout(function(){setTimeout(function(){o.setStatus("")},1),T()},1)):T()))}if(fi=function T(){wt||oc(),wt||(fi=T)},o.preInit)for(typeof o.preInit=="function"&&(o.preInit=[o.preInit]);o.preInit.length>0;)o.preInit.pop()();return oc(),t.ready}})(),CI=vI,NI=class extends Js{constructor(i){super(CI,i!=null&&i.wasmPath?fetch(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)}},DI="web.sdk.qcloud.com",wI=`https://${DI}/trtc/webrtc/v5/doc`,vM=`${wI}/zh-cn/`,Lf=(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))(Lf||{});var Vd={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"},CM=Vd.MAIN,NM=Vd.AUXILIARY,DM=Vd.BIG,wM=Vd.SMALL;var MM=Object.keys(Lf);var OM=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{};function Of(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var{toString:PM}=Object.prototype,Uf=class Vf{constructor(t){this.core=t,Ar(this,"contextMap",new Map),Ar(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 Vf.Name}getValidateRule(t){return{type:this.core.enums.BASIC_TYPE.Object}}createDecoder(t,e){switch(t){case"wasm":return this.core.rtcDectection.isSIMDSupported()?new NI(ba(Aa({},e),{wasmPath:`${this.core.assetsPath||"."}/videodec_simd.wasm`})):new RI(ba(Aa({},e),{wasmPath:`${this.core.assetsPath||"."}/videodec.wasm`}));case"webCodecs":return new qs;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 d=this.core.room.videoManager.createDecodeContext(ba(Aa({},t),{createDecoder:this.createDecoder}));return e(d.trackDoneOB,r(1),o(()=>{this.core.clearStarted(this,this.getGroup(t)),this.stop({track:n})})),this.contextMap.set(n,d),d.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=Of()-t.startPerformanceTime,{renderFreezeTotal:o,dataFreezeTotal:s}=this.getRemoteTrackFreezeDuration(e,t);r&&this.core.kvStatManager.addNumber({key:514850,value:Math.floor(o/r*100),split:1}),r&&this.core.kvStatManager.addNumber({key:514851,value:Math.floor(s/r*100),split:1}),t.inputFrameCount&&this.core.kvStatManager.addNumber({key:514852,value:Math.floor(t.decodedFrameCount/t.inputFrameCount*100),split:1})}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(ba(Aa({},t),{createDecoder:this.createDecoder})))):e.mock(this.core.enums.DECODE_FAILED_ERROR_CODE.TEST))}getRemoteTrackFreezeDuration(t,e){let r=this.core.room.badCaseDetector.getRenderFreezeMap().get(`${t.userId}_${t.streamType}`),o=this.core.room.badCaseDetector.getDataFreezeMap().get(`${t.userId}_${t.streamType}`),s=0;r&&r.freezeTimeline.forEach(({startTime:d,endTime:p})=>{d>e.startPerformanceTime&&(s+=p===0?Of()-d:p-d)});let n=0;return o&&o.durationItemList.forEach(d=>{d.startTime>e.startPerformanceTime&&(n+=d.getDuration())}),{renderFreezeTotal:s,dataFreezeTotal:n}}destroy(){this.core.innerEmitter.off("51",this.addKVReportBeforeExitRoom)}};Ar(Uf,"Name","VideoDecoderPlugin");var Bm=Uf;var ng=Di(Ui());function $m({timesInSecond:i,maxSizeInSecond:t,getSize:e}){return Me((r,o)=>{let s=new WeakMap;return H.on(L.ROOM_DESTROY,({room:n})=>s.delete(n)),function(...n){let d=s.get(this);if(d||(d={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},s.set(this,d)),d.timestamp===0?d.timestamp=Date.now():Date.now()-d.timestamp>1e3&&(d.timestamp=Date.now(),d.callCountInSecond=0,d.totalSizeInSecond=0),e&&(d.totalSizeInSecond+=e(...n)),d.timestamp!==0&&Date.now()-d.timestamp<1e3&&(d.callCountInSecond>=i||d.totalSizeInSecond>t))throw new he({code:te.INVALID_OPERATION,message:at({key:nt.CALL_FREQUENCY_LIMIT,data:{isTimes:d.callCountInSecond>=i,isSize:d.totalSizeInSecond>t,name:o,timesInSecond:i,maxSizeInSecond:t}})});d.callCountInSecond++,r.call(this,...n)}})}var MI="2025-04-07 14:30:49",Bf=!0,$f=function(){var i;Bf&&(Bf=!1,B.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${Mr}/en/index.html`),console.info(`* Changelog: ${Mr}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),B.info("TRTC Web SDK Version:",rt),Tr||B.debug("Build Time:",MI),B.info("UA:",navigator.userAgent),B.info(`URL: ${location.href}${((i=self.frameElement)==null?void 0:i.tagName)==="IFRAME"?" in iframe":""}`),qn().then(t=>{t&&B.info(fr)}))};var sr={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 ue={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},br=(O=>(O[O.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",O[O.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",O[O.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",O[O.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",O[O.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",O[O.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",O[O.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",O[O.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",O[O.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",O[O.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",O[O.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",O[O.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",O[O.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",O[O.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",O[O.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",O[O.INVALID_ROOM_ID_REQUIED=5015]="INVALID_ROOM_ID_REQUIED",O[O.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",O[O.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",O[O.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",O[O.INVALID_OPERATION=5100]="INVALID_OPERATION",O[O.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",O[O.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",O[O.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",O[O.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",O[O.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",O[O.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",O[O.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",O[O.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",O[O.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",O[O.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",O[O.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",O[O.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",O[O.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",O[O.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",O[O.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",O[O.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",O[O.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",O[O.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",O[O.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",O[O.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",O[O.DEVICE_ERROR=5300]="DEVICE_ERROR",O[O.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",O[O.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",O[O.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",O[O.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",O[O.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",O[O.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",O[O.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",O[O.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",O[O.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",O[O.SERVER_ERROR=5400]="SERVER_ERROR",O[O.NEED_TO_BUY=5401]="NEED_TO_BUY",O[O.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",O[O.OPERATION_FAILED=5500]="OPERATION_FAILED",O[O.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",O[O.REJOIN_FAILED=5502]="REJOIN_FAILED",O[O.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",O[O.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",O[O.VIDEO_DECODE_ERROR=5505]="VIDEO_DECODE_ERROR",O[O.OPERATION_ABORT=5998]="OPERATION_ABORT",O[O.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",O))(br||{});function Hf({code:i,params:t,enableDocLink:e=!1}){let r="",o,s=br[i];try{o=Ff[s]}catch(n){o=Ff.UNKNOWN_ERROR}return ze(o)?r=o(t):we(o)&&(r=o),t.fnName&&!r.includes(t.fnName)&&(r[r.length-1]!=="."&&(r+="."),r+=` thrown from ${t.fnName}()`),e&&(r+=" doc:"),r}var Ff=Ee(Z({},qt),{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: ${mt(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: ${mt(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_REQUIED(){return"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required."},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 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=jo(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=jo(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=jo(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=jo(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=jo(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=jo(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=jo(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 jo(i){if(!i)return"camera";let t=i.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var Fm=class i extends Error{constructor({code:e,extraCode:r,message:o="",messageParams:s,fnName:n="",originError:d}){var m;let p;o?p=o:p=Hf({code:e===ue.SERVER_ERROR?e:r||e,params:Z({fnName:n,error:d},s)});super(p);u(this,"name","RtcError");u(this,"code");u(this,"extraCode");u(this,"functionName");u(this,"message");u(this,"handler");u(this,"originError");this.name=br[e],this.code=e,this.extraCode=r,this.functionName=n,this.originError=d,this.message=p,this.extraCode===5302&&((m=this.originError)!=null&&m.message.includes("system"))&&(this.handler=()=>{let E={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},_={startLocalVideo:"webcam",startLocalAudio:"microphone"},b=document.createElement("a");To?b.href=`ms-settings:privacy-${_[this.functionName]}`:_r&&(b.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${E[this.functionName]}`),b.href.length>0&&b.click()})}static convertFrom(e,r,o){let s=e;if(e instanceof he){let{stack:n}=e,d={code:ue.UNKNOWN_ERROR,fnName:r,originError:e};switch(e.getCode()){case te.INVALID_PARAMETER:d.code=ue.INVALID_PARAMETER,d.message=e.message;break;case te.INVALID_OPERATION:d.code=ue.INVALID_OPERATION;break;case te.NOT_SUPPORTED:case te.NOT_SUPPORTED_H264:d.code=ue.ENV_NOT_SUPPORTED,e.getCode()===te.NOT_SUPPORTED_H264&&(d.extraCode=e.message.includes(qt.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case te.JOIN_ROOM_FAILED:d.messageParams={fnParams:o};case te.SERVER_TIMEOUT:case te.SWITCH_ROLE_FAILED:d.code=ue.SERVER_ERROR,d.extraCode=e.getExtraCode();break;case te.API_CALL_ABORTED:d.code=ue.OPERATION_ABORT;break;case te.DEVICE_NOT_FOUND:case te.DEVICE_AUTO_RECOVER_FAILED:case te.INITIALIZE_FAILED:d.code=5300,e.name&&(d.extraCode=OI(e.name));break;case te.UNKNOWN:break;default:d.code=ue.OPERATION_FAILED}s=new i(d),n&&(s.stack+=n.substr(n.indexOf(`
|
|
92
|
-
`)))}else{if(e instanceof i)return e;s=new i({code:ue.UNKNOWN_ERROR,fnName:r,originError:e})}return s}};function OI(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 ae=Fm;var Wf={type:"object",properties:{cameraId:{type:"string"},useFrontCamera:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:["string","boolean"],values:[!0,!1,"view","publish","both"]},small:{properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack}}},Gf={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}}},zs={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(i,t,e){if(we(i)&&!document.getElementById(i))throw new ae({code:ue.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:t}})}},jf={name:"userId",required:!0,type:"string"},qf={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[sr.AUDIO_PROFILE_STANDARD,sr.AUDIO_PROFILE_STANDARD_STEREO,sr.AUDIO_PROFILE_HIGH,sr.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function Ca(i,t){if(!i)throw new ae({code:ue.INVALID_OPERATION,extraCode:5101,fnName:t})}function Jf(i,t,e){if(!i)throw new ae({code:ue.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:e}})}var GO={type:"number",notLessThanZero:!0},PI={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 ae({code:ue.INVALID_OPERATION,extraCode:5104,fnName:e});if(i.roomId){if(we(i.roomId))throw new ae({code:ue.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:t}});if(!(/^[1-9]\d*$/.test(String(i.roomId))&&i.roomId<4294967295))throw new ae({code:ue.INVALID_PARAMETER,extraCode:5013,fnName:e,messageParams:{key:t}})}else if(i.strRoomId){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(i.strRoomId))throw new ae({code:ue.INVALID_PARAMETER,extraCode:5012,fnName:e,messageParams:{key:t}})}else throw new ae({code:ue.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:1e3}}}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:zs,mute:{type:["boolean","string"]},publish:{type:"boolean"},option:Wf},validate(i){var t;if(!((t=i==null?void 0:i.option)!=null&&t.videoTrack)&&si())throw new ae({code:ue.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:Ee(Z({},zs),{required:!1}),publish:{type:"boolean"},mute:{type:["boolean","string"]},option:Wf}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:qf},validate(i){var t;if(!((t=i==null?void 0:i.option)!=null&&t.audioTrack)&&si())throw new ae({code:ue.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:qf}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:zs,publish:{type:"boolean"},option:Gf},validate(i,t,e,r,o){var s;if(!((s=i==null?void 0:i.option)!=null&&s.videoTrack)){if(si())throw new ae({code:ue.ENV_NOT_SUPPORTED,extraCode:5201});if(!ta())throw new ae({code:ue.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:zs,publish:{type:"boolean"},option:Gf}},muteRemoteAudio:[jf,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[jf,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:zs,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){Ca(this._room.isJoined,e);let r=this._room.remotePublishedUserMap.get(i.userId);if(Jf(!!r,e,i),r&&(i.streamType==="main"&&!r.muteState.videoAvailable||i.streamType==="sub"&&!r.muteState.hasAuxiliary))throw new ae({code:ue.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:i}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:Ee(Z({},zs),{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){Ca(this._room.isJoined,e);let r=this._room.remotePublishedUserMap.get(i.userId);if(Jf(!!r,e,i),r&&(i.streamType==="main"&&!r.muteState.videoAvailable||i.streamType==="sub"&&!r.muteState.hasAuxiliary))throw new ae({code:ue.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!=="*"&&$(i.streamType))throw new ae({code:ue.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(i,t,e){Ca(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(!sa)throw new ae({code:ue.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new ae({code:ue.INVALID_OPERATION,fnName:e,extraCode:5108});if(i.byteLength>1e3)throw new ae({code:ue.INVALID_PARAMETER,extraCode:5018,fnName:e});if(i.byteLength===0)throw new ae({code:ue.INVALID_PARAMETER,extraCode:5017,messageParams:{key:t},fnName:e});Ca(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 ae({code:ue.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 ae({code:ue.INVALID_PARAMETER,extraCode:5018,fnName:e});if(i.byteLength===0)throw new ae({code:ue.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:t}})}}},validate(i,t,e){if(Ca(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new ae({code:ue.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:t}})}}},At={TRTC:PI};var Lt=class extends Error{};function xI(i,t){let e=go(i);for(let r=0;r<t.length;r++)kr(e[r],t[r]);return e}function kI(i){this._resolve=Promise.resolve(i)}function LI(i){this._reject=Promise.reject(i)}var zi=class zi{constructor(t,e){this.instance=t;this.group=e;u(this,"started",!1);u(this,"ops",[]);u(this,"startSame",()=>!0);u(this,"mergeUpdate",xI);let r=zi.instances.get(t);r?r.set(e,this):zi.instances.set(t,new Map([[e,this]]))}static get(t,e){if(!e)return;let r=zi.instances.get(t);return r&&r.get(e)||new zi(t,e)}static gets(t,e){let r=zi.instances.get(t),o=[];return r&&r.forEach((s,n)=>{e.test(n)&&o.push(s)}),o}action(t,e,r){let o=d=>{var p;return t===0?this.started=!0:t===3&&(this.started=!1),this.ops.shift(),(p=this.currentOp)==null||p.action(),d},s=d=>{var p,m;throw this.ops.shift(),t===0&&((p=this.currentOp)==null?void 0:p.type)===2&&this.ops.shift().reject(new Lt("start failed")),(m=this.currentOp)==null||m.action(),d},n={type:t,action:()=>e(...n.args).then(o,s),args:r,resolve:kI,reject:LI};try{switch(this.state){case 1:if(t===0)throw new Lt("already started");break;case 4:if(t===2)throw new Lt("not started");break;default:return this.cacheOp(n)}}catch(d){return Promise.reject(d)}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 Lt("already start");break;case 3:switch(t.type){case 2:throw new Lt("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new Lt("unknown state")}else switch(t.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let r=new Lt("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 Lt("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new Lt("start not allowed after update");case 0:throw new Lt("duplicate start");case 3:if(this.startSame(this.currentOp.args,t.args))throw this.ops.pop().reject(new Lt("keep start")),new Lt("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}};u(zi,"instances",new WeakMap);var pi=zi;var Bd=new WeakMap,$d=(i,t)=>{if(t instanceof Lt){let{stack:e}=t;t=new ae({code:ue.OPERATION_ABORT,message:`${i} abort: ${t.message}`,fnName:i}),e&&(t.stack+=e.substr(e.indexOf(`
|
|
93
|
-
`)))}throw t};function
|
|
94
|
-
`));function
|
|
91
|
+
`,j.push(ce);var ye,le,ve=Ja(Function,j).apply(null,q);return ye=ve,le=ns.length,ns.push(ye),W=le,as[U]=W,W},f:()=>{K("")},c:mn,t:(T,E,v)=>x.copyWithin(T,E,E+v),s:T=>{x.length,K("OOM")},i:(T,E,v,C)=>{for(var U,W,j,q=0,Z=0;Z<v;Z++){var B=De[E>>2],ce=De[E+4>>2];E+=8;for(var Re=0;Re<ce;Re++)U=T,W=x[B+Re],j=void 0,j=ec[U],W===0||W===10?((U===1?_:b)(Xa(j,0)),j.length=0):j.push(W);q+=ce}return De[C>>2]=q,0}},mr=(function(){var T,E,v,C,U={a:tc};function W(j,q){var Z,B,ce=j.exports;return N=(k=ce).v,Z=N.buffer,o.HEAP8=P=new Int8Array(Z),o.HEAP16=J=new Int16Array(Z),o.HEAP32=Ne=new Int32Array(Z),o.HEAPU8=x=new Uint8Array(Z),o.HEAPU16=Q=new Uint16Array(Z),o.HEAPU32=De=new Uint32Array(Z),o.HEAPF32=me=new Float32Array(Z),o.HEAPF64=xe=new Float64Array(Z),Fe=k.z,B=k.w,tn.unshift(B),function(){if(vr--,o.monitorRunDependencies&&o.monitorRunDependencies(vr),vr==0&&(Yo!==null&&(clearInterval(Yo),Yo=null),Ei)){var Re=Ei;Ei=null,Re()}}(),ce}if(vr++,o.monitorRunDependencies&&o.monitorRunDependencies(vr),o.instantiateWasm)try{return o.instantiateWasm(U,W)}catch(j){b("Module.instantiateWasm callback failed with error: "+j),r(j)}(T=g,E=Wr,v=U,C=function(j){W(j.instance)},T||typeof WebAssembly.instantiateStreaming!="function"||no(E)||typeof fetch!="function"?_i(E,v,C):fetch(E,{credentials:"same-origin"}).then(j=>WebAssembly.instantiateStreaming(j,v).then(C,function(q){return b("wasm streaming compile failed: "+q),b("falling back to ArrayBuffer instantiation"),_i(E,v,C)}))).catch(r)}(),T=>(mr=k.x)(T)),Di=T=>(Di=k.y)(T),cs=T=>(cs=k.A)(T),rc=(o.__embind_initialize_bindings=()=>(o.__embind_initialize_bindings=k.B)(),T=>(rc=k.C)(T));o.dynCall_jiji=(T,E,v,C,U)=>(o.dynCall_jiji=k.D)(T,E,v,C,U);function ic(){function T(){wt||(wt=!0,o.calledRun=!0,Ks||(ao(tn),e(o),o.onRuntimeInitialized&&o.onRuntimeInitialized(),function(){if(o.postRun)for(typeof o.postRun=="function"&&(o.postRun=[o.postRun]);o.postRun.length;)E=o.postRun.shift(),rn.unshift(E);var E;ao(rn)}()))}vr>0||(function(){if(o.preRun)for(typeof o.preRun=="function"&&(o.preRun=[o.preRun]);o.preRun.length;)E=o.preRun.shift(),en.unshift(E);var E;ao(en)}(),vr>0||(o.setStatus?(o.setStatus("Running..."),setTimeout(function(){setTimeout(function(){o.setStatus("")},1),T()},1)):T()))}if(Ei=function T(){wt||ic(),wt||(Ei=T)},o.preInit)for(typeof o.preInit=="function"&&(o.preInit=[o.preInit]);o.preInit.length>0;)o.preInit.pop()();return ic(),t.ready}})();var MI="web.sdk.qcloud.com",OI=`https://${MI}/trtc/webrtc/v5/doc`,CM=`${OI}/zh-cn/`,Uf=(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))(Uf||{});var Fd={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"},DM=Fd.MAIN,NM=Fd.AUXILIARY,wM=Fd.BIG,MM=Fd.SMALL;var OM=Object.keys(Uf);var xM=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{};function xf(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var{toString:PM}=Object.prototype,Vf=class Ff{constructor(t){this.core=t,br(this,"contextMap",new Map),br(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 Ff.Name}getValidateRule(t){return{type:this.core.enums.BASIC_TYPE.Object}}createDecoder(t,e){switch(t){case"wasm":return new wI(Ld(kd({},e),{wasmPath:`${this.core.assetsPath||"."}/videodec.wasm`}));case"webCodecs":return new Js;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 d=this.core.room.videoManager.createDecodeContext(Ld(kd({},t),{createDecoder:this.createDecoder}));return e(d.trackDoneOB,r(1),o(()=>{this.core.clearStarted(this,this.getGroup(t)),this.stop({track:n})})),this.contextMap.set(n,d),d.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=xf()-t.startPerformanceTime,{renderFreezeTotal:o,dataFreezeTotal:s}=this.getRemoteTrackFreezeDuration(e,t);r&&this.core.kvStatManager.addNumber({key:514850,value:Math.floor(o/r*100),split:1}),r&&this.core.kvStatManager.addNumber({key:514851,value:Math.floor(s/r*100),split:1}),t.inputFrameCount&&this.core.kvStatManager.addNumber({key:514852,value:Math.floor(t.decodedFrameCount/t.inputFrameCount*100),split:1})}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(Ld(kd({},t),{createDecoder:this.createDecoder})))):e.mock(this.core.enums.DECODE_FAILED_ERROR_CODE.TEST))}getRemoteTrackFreezeDuration(t,e){let r=this.core.room.badCaseDetector.getRenderFreezeMap().get(`${t.userId}_${t.streamType}`),o=this.core.room.badCaseDetector.getDataFreezeMap().get(`${t.userId}_${t.streamType}`),s=0;r&&r.freezeTimeline.forEach(({startTime:d,endTime:p})=>{d>e.startPerformanceTime&&(s+=p===0?xf()-d:p-d)});let n=0;return o&&o.durationItemList.forEach(d=>{d.startTime>e.startPerformanceTime&&(n+=d.getDuration())}),{renderFreezeTotal:s,dataFreezeTotal:n}}destroy(){this.core.innerEmitter.off("51",this.addKVReportBeforeExitRoom)}};br(Vf,"Name","TRTCVideoDecoder");var Bm=Vf;var lg=Mi($i());function Hm({timesInSecond:i,maxSizeInSecond:t,getSize:e}){return Me((r,o)=>{let s=new WeakMap;return H.on(L.ROOM_DESTROY,({room:n})=>s.delete(n)),function(...n){let d=s.get(this);if(d||(d={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},s.set(this,d)),d.timestamp===0?d.timestamp=Date.now():Date.now()-d.timestamp>1e3&&(d.timestamp=Date.now(),d.callCountInSecond=0,d.totalSizeInSecond=0),e&&(d.totalSizeInSecond+=e(...n)),d.timestamp!==0&&Date.now()-d.timestamp<1e3&&(d.callCountInSecond>=i||d.totalSizeInSecond>t))throw new he({code:te.INVALID_OPERATION,message:dt({key:ct.CALL_FREQUENCY_LIMIT,data:{isTimes:d.callCountInSecond>=i,isSize:d.totalSizeInSecond>t,name:o,timesInSecond:i,maxSizeInSecond:t}})});d.callCountInSecond++,r.call(this,...n)}})}var xI="2025-04-17 10:05:35",$f=!0,Bf=function(){var i;$f&&($f=!1,$.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${Mr}/en/index.html`),console.info(`* Changelog: ${Mr}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),$.info("TRTC Web SDK Version:",rt),Tr||$.debug("Build Time:",xI),$.info("UA:",navigator.userAgent),$.info(`URL: ${location.href}${((i=self.frameElement)==null?void 0:i.tagName)==="IFRAME"?" in iframe":""}`),jn().then(t=>{t&&$.info(gr)}))};var nr={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 ue={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},Rr=(O=>(O[O.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",O[O.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",O[O.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",O[O.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",O[O.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",O[O.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",O[O.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",O[O.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",O[O.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",O[O.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",O[O.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",O[O.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",O[O.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",O[O.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",O[O.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",O[O.INVALID_ROOM_ID_REQUIED=5015]="INVALID_ROOM_ID_REQUIED",O[O.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",O[O.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",O[O.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",O[O.INVALID_OPERATION=5100]="INVALID_OPERATION",O[O.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",O[O.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",O[O.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",O[O.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",O[O.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",O[O.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",O[O.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",O[O.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",O[O.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",O[O.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",O[O.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",O[O.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",O[O.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",O[O.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",O[O.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",O[O.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",O[O.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",O[O.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",O[O.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",O[O.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",O[O.DEVICE_ERROR=5300]="DEVICE_ERROR",O[O.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",O[O.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",O[O.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",O[O.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",O[O.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",O[O.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",O[O.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",O[O.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",O[O.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",O[O.SERVER_ERROR=5400]="SERVER_ERROR",O[O.NEED_TO_BUY=5401]="NEED_TO_BUY",O[O.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",O[O.OPERATION_FAILED=5500]="OPERATION_FAILED",O[O.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",O[O.REJOIN_FAILED=5502]="REJOIN_FAILED",O[O.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",O[O.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",O[O.VIDEO_DECODE_ERROR=5505]="VIDEO_DECODE_ERROR",O[O.OPERATION_ABORT=5998]="OPERATION_ABORT",O[O.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",O))(Rr||{});function Wf({code:i,params:t,enableDocLink:e=!1}){let r="",o,s=Rr[i];try{o=Hf[s]}catch(n){o=Hf.UNKNOWN_ERROR}return Xe(o)?r=o(t):we(o)&&(r=o),t.fnName&&!r.includes(t.fnName)&&(r[r.length-1]!=="."&&(r+="."),r+=` thrown from ${t.fnName}()`),e&&(r+=" doc:"),r}var Hf=Ee(ee({},qt),{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: ${ht(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: ${ht(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_REQUIED(){return"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required."},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 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=qo(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=qo(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=qo(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=qo(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=qo(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=qo(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=qo(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 qo(i){if(!i)return"camera";let t=i.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var Wm=class i extends Error{constructor({code:e,extraCode:r,message:o="",messageParams:s,fnName:n="",originError:d}){var m;let p;o?p=o:p=Wf({code:e===ue.SERVER_ERROR?e:r||e,params:ee({fnName:n,error:d},s)});super(p);u(this,"name","RtcError");u(this,"code");u(this,"extraCode");u(this,"functionName");u(this,"message");u(this,"handler");u(this,"originError");this.name=Rr[e],this.code=e,this.extraCode=r,this.functionName=n,this.originError=d,this.message=p,this.extraCode===5302&&((m=this.originError)!=null&&m.message.includes("system"))&&(this.handler=()=>{let g={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},_={startLocalVideo:"webcam",startLocalAudio:"microphone"},b=document.createElement("a");Ao?b.href=`ms-settings:privacy-${_[this.functionName]}`:_r&&(b.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${g[this.functionName]}`),b.href.length>0&&b.click()})}static convertFrom(e,r,o){let s=e;if(e instanceof he){let{stack:n}=e,d={code:ue.UNKNOWN_ERROR,fnName:r,originError:e};switch(e.getCode()){case te.INVALID_PARAMETER:d.code=ue.INVALID_PARAMETER,d.message=e.message;break;case te.INVALID_OPERATION:d.code=ue.INVALID_OPERATION;break;case te.NOT_SUPPORTED:case te.NOT_SUPPORTED_H264:d.code=ue.ENV_NOT_SUPPORTED,e.getCode()===te.NOT_SUPPORTED_H264&&(d.extraCode=e.message.includes(qt.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case te.JOIN_ROOM_FAILED:d.messageParams={fnParams:o};case te.SERVER_TIMEOUT:case te.SWITCH_ROLE_FAILED:d.code=ue.SERVER_ERROR,d.extraCode=e.getExtraCode();break;case te.API_CALL_ABORTED:d.code=ue.OPERATION_ABORT;break;case te.DEVICE_NOT_FOUND:case te.DEVICE_AUTO_RECOVER_FAILED:case te.INITIALIZE_FAILED:d.code=5300,e.name&&(d.extraCode=PI(e.name));break;case te.UNKNOWN:break;default:d.code=ue.OPERATION_FAILED}s=new i(d),n&&(s.stack+=n.substr(n.indexOf(`
|
|
92
|
+
`)))}else{if(e instanceof i)return e;s=new i({code:ue.UNKNOWN_ERROR,fnName:r,originError:e})}return s}};function PI(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 ae=Wm;var Gf={type:"object",properties:{cameraId:{type:"string"},useFrontCamera:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:["string","boolean"],values:[!0,!1,"view","publish","both"]},small:{properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack}}},jf={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}}},zs={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(i,t,e){if(we(i)&&!document.getElementById(i))throw new ae({code:ue.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:t}})}},qf={name:"userId",required:!0,type:"string"},Jf={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[nr.AUDIO_PROFILE_STANDARD,nr.AUDIO_PROFILE_STANDARD_STEREO,nr.AUDIO_PROFILE_HIGH,nr.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function Ca(i,t){if(!i)throw new ae({code:ue.INVALID_OPERATION,extraCode:5101,fnName:t})}function zf(i,t,e){if(!i)throw new ae({code:ue.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:e}})}var GO={type:"number",notLessThanZero:!0},kI={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 ae({code:ue.INVALID_OPERATION,extraCode:5104,fnName:e});if(i.roomId){if(we(i.roomId))throw new ae({code:ue.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:t}});if(!(/^[1-9]\d*$/.test(String(i.roomId))&&i.roomId<4294967295))throw new ae({code:ue.INVALID_PARAMETER,extraCode:5013,fnName:e,messageParams:{key:t}})}else if(i.strRoomId){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(i.strRoomId))throw new ae({code:ue.INVALID_PARAMETER,extraCode:5012,fnName:e,messageParams:{key:t}})}else throw new ae({code:ue.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:zs,mute:{type:["boolean","string"]},publish:{type:"boolean"},option:Gf},validate(i){var t;if(!((t=i==null?void 0:i.option)!=null&&t.videoTrack)&&ai())throw new ae({code:ue.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:Ee(ee({},zs),{required:!1}),publish:{type:"boolean"},mute:{type:["boolean","string"]},option:Gf}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:Jf},validate(i){var t;if(!((t=i==null?void 0:i.option)!=null&&t.audioTrack)&&ai())throw new ae({code:ue.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:Jf}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:zs,publish:{type:"boolean"},option:jf},validate(i,t,e,r,o){var s;if(!((s=i==null?void 0:i.option)!=null&&s.videoTrack)){if(ai())throw new ae({code:ue.ENV_NOT_SUPPORTED,extraCode:5201});if(!ta())throw new ae({code:ue.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:zs,publish:{type:"boolean"},option:jf}},muteRemoteAudio:[qf,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[qf,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:zs,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){Ca(this._room.isJoined,e);let r=this._room.remotePublishedUserMap.get(i.userId);if(zf(!!r,e,i),r&&(i.streamType==="main"&&!r.muteState.videoAvailable||i.streamType==="sub"&&!r.muteState.hasAuxiliary))throw new ae({code:ue.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:i}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:Ee(ee({},zs),{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){Ca(this._room.isJoined,e);let r=this._room.remotePublishedUserMap.get(i.userId);if(zf(!!r,e,i),r&&(i.streamType==="main"&&!r.muteState.videoAvailable||i.streamType==="sub"&&!r.muteState.hasAuxiliary))throw new ae({code:ue.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!=="*"&&V(i.streamType))throw new ae({code:ue.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(i,t,e){Ca(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(!sa)throw new ae({code:ue.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new ae({code:ue.INVALID_OPERATION,fnName:e,extraCode:5108});if(i.byteLength>1e3)throw new ae({code:ue.INVALID_PARAMETER,extraCode:5018,fnName:e});if(i.byteLength===0)throw new ae({code:ue.INVALID_PARAMETER,extraCode:5017,messageParams:{key:t},fnName:e});Ca(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 ae({code:ue.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 ae({code:ue.INVALID_PARAMETER,extraCode:5018,fnName:e});if(i.byteLength===0)throw new ae({code:ue.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:t}})}}},validate(i,t,e){if(Ca(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new ae({code:ue.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:t}})}}},bt={TRTC:kI};var Lt=class extends Error{};function LI(i,t){let e=So(i);for(let r=0;r<t.length;r++)kr(e[r],t[r]);return e}function UI(i){this._resolve=Promise.resolve(i)}function VI(i){this._reject=Promise.reject(i)}var Yi=class Yi{constructor(t,e){this.instance=t;this.group=e;u(this,"started",!1);u(this,"ops",[]);u(this,"startSame",()=>!0);u(this,"mergeUpdate",LI);let r=Yi.instances.get(t);r?r.set(e,this):Yi.instances.set(t,new Map([[e,this]]))}static get(t,e){if(!e)return;let r=Yi.instances.get(t);return r&&r.get(e)||new Yi(t,e)}static gets(t,e){let r=Yi.instances.get(t),o=[];return r&&r.forEach((s,n)=>{e.test(n)&&o.push(s)}),o}action(t,e,r){let o=d=>{var p;return t===0?this.started=!0:t===3&&(this.started=!1),this.ops.shift(),(p=this.currentOp)==null||p.action(),d},s=d=>{var p,m;throw this.ops.shift(),t===0&&((p=this.currentOp)==null?void 0:p.type)===2&&this.ops.shift().reject(new Lt("start failed")),(m=this.currentOp)==null||m.action(),d},n={type:t,action:()=>e(...n.args).then(o,s),args:r,resolve:UI,reject:VI};try{switch(this.state){case 1:if(t===0)throw new Lt("already started");break;case 4:if(t===2)throw new Lt("not started");break;default:return this.cacheOp(n)}}catch(d){return Promise.reject(d)}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 Lt("already start");break;case 3:switch(t.type){case 2:throw new Lt("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new Lt("unknown state")}else switch(t.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let r=new Lt("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 Lt("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new Lt("start not allowed after update");case 0:throw new Lt("duplicate start");case 3:if(this.startSame(this.currentOp.args,t.args))throw this.ops.pop().reject(new Lt("keep start")),new Lt("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}};u(Yi,"instances",new WeakMap);var fi=Yi;var $d=new WeakMap,Bd=(i,t)=>{if(t instanceof Lt){let{stack:e}=t;t=new ae({code:ue.OPERATION_ABORT,message:`${i} abort: ${t.message}`,fnName:i}),e&&(t.stack+=e.substr(e.indexOf(`
|
|
93
|
+
`)))}throw t};function Zi(i,t){return Me((e,r)=>function(...o){let s=fi.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(Bd.bind(null,r))):e.apply(this,o)})}function Jo(i,t){let{merge:e,debounce:r}=t||{};return Me((o,s)=>function(...n){let d=fi.get(this,typeof i=="string"?i:i.call(this,...n));if(!d)return o.apply(this,n);if(e&&(d.mergeUpdate=e.bind(this)),r&&r.isNeedToDebounce.apply(this,n)){let{delay:p,getKey:m}=r;return new Promise((g,_)=>{var k,P;let b=(k=$d.get(this))==null?void 0:k.get(m(...n));if(b){let{timeoutId:x,resolve:J}=b;clearTimeout(x),J()}let N=setTimeout(()=>{if(d.state===3||d.state===4)return g();d.action(2,o.bind(this),n).catch(Bd.bind(null,s)).then(g,_)},p);$d.has(this)?(P=$d.get(this))==null||P.set(m(...n),{timeoutId:N,resolve:g}):$d.set(this,new Map([[m(...n),{timeoutId:N,resolve:g}]]))})}return d.action(2,o.bind(this),n).catch(Bd.bind(null,s))})}function Ki(i){return Me((t,e)=>function(...r){let o=typeof i=="function"?i.call(this,...r):i;if(o instanceof RegExp)return Promise.all(fi.gets(this,o).map(n=>n.action(3,()=>Promise.resolve(),r))).then(()=>t.call(this,...r));let s=fi.get(this,o);return s?s.action(3,t.bind(this),r).catch(Bd.bind(null,e)):t.apply(this,r)})}var se={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"},Xf=new Set([se.ERROR,se.AUTOPLAY_FAILED,se.KICKED_OUT,se.REMOTE_USER_ENTER,se.REMOTE_USER_EXIT,se.REMOTE_AUDIO_AVAILABLE,se.REMOTE_AUDIO_UNAVAILABLE,se.REMOTE_VIDEO_AVAILABLE,se.REMOTE_VIDEO_UNAVAILABLE,se.CONNECTION_STATE_CHANGED,se.PUBLISH_STATE_CHANGED,se.SCREEN_SHARE_STOPPED,se.DEVICE_CHANGED,se.FIRST_VIDEO_FRAME]);function eo(i){return i==="sub"?"auxiliary":i==="auxiliary"?"sub":"main"}function Da(i){return i===nr.QOS_PREFERENCE_CLEAR?"detail":i===nr.QOS_PREFERENCE_SMOOTH?"motion":""}var jm={};Jr(jm,{bytes2ms:()=>Fp,convertObjectNumberToInt:()=>On,copyProperties:()=>Vp,deepClone:()=>So,deepMerge:()=>kr,delay:()=>xn,fibonacci:()=>yo,formatedTime:()=>gc,getConstructorName:()=>Nn,getContainerFromElement:()=>Jp,getEnv:()=>kp,getInternalVersion:()=>jp,getLoggerUrl:()=>Yr,getMuteStateFromFlag:()=>Mn,getNetworkType:()=>Cn,getNumNetworkType:()=>fc,getReconnectionTimeout:()=>Bp,getStringByteLength:()=>zp,getTurnServer:()=>qp,getUint32Version:()=>Tc,getValueType:()=>ht,getViewListFromView:()=>Es,glog:()=>Dn,ipv4ToUint32:()=>gs,isArray:()=>st,isAudioWorkletSupported:()=>Gp,isBoolean:()=>nt,isConstructor:()=>hs,isEmpty:()=>fs,isFunction:()=>Xe,isLangChinese:()=>fr,isMediaStreamTrack:()=>Hp,isNumber:()=>je,isObject:()=>Pr,isOverseaSdkAppId:()=>vn,isPlainObject:()=>Gt,isPortrait:()=>_c,isPromise:()=>xi,isRemoteTrack:()=>Wp,isString:()=>we,isUndefined:()=>V,loadImage:()=>_s,ms2bytes:()=>$p,ms2samples:()=>Hu,performanceNow:()=>_e,promiseAny:()=>wn,samples2ms:()=>Bu,setNetworkType:()=>Up,stringify:()=>ir,stringifyIncludeValue:()=>Ec,throttlePromise:()=>Ic});var zm={};Jr(zm,{ScheduleRequestType:()=>Yf,getAbilityConfig:()=>$I,getScheduleDomain:()=>Zf,isNeedToSchedule:()=>Hd,scheduleProxy:()=>ro,sendScheduleRequest:()=>Jm,setIsNeedToSchedule:()=>zo,setScheduleProxy:()=>Wd});var qm=null,Hd=!0;typeof document!="undefined"&&document.head.insertAdjacentHTML("beforeend",Object.values(Qr).map(i=>`<link rel="dns-prefetch" href="https://${i}">`).join(`\r
|
|
94
|
+
`));function zo(i){nt(i)&&i!==Hd&&(Hd=i,$.info(`setIsNeedToSchedule ${i}`))}H.on("28",()=>zo(!0));H.on("63",()=>zo(!0));H.on("84",()=>zo(!0));H.on("201",i=>{i.state==="RECONNECTING"&&zo(!0)});H.on("202",i=>{i.state==="RECONNECTING"&&zo(!0)});function FI(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=to(i,"config",D.MAIN),n=to(i,"config",D.BACKUP);for(let d of o)if(d.startTime>=e&&(d.name===s||d.name===n)&&d.transferSize>0){let p=d.name===s?D.MAIN:D.BACKUP,m=Math.round(d.duration),g=Math.round(d.domainLookupStart-d.startTime),_=d.redirectStart>0?Math.round(d.redirectEnd-d.redirectStart):0,b=d.fetchStart>0?Math.round(d.domainLookupStart-d.fetchStart):0,N=Math.round(d.domainLookupEnd-d.domainLookupStart),k=Math.round(d.requestStart-d.secureConnectionStart),P=Math.round(d.secureConnectionStart-d.connectStart),x=Math.round(d.responseStart-d.requestStart),J=Math.round(d.responseEnd-d.responseStart),Q=[N,k,P,x,J];Be.uploadEvent({log:`stat-schedule-net:${m}(${g}(${_}->${b})->${Q.join("->")}) ${p}`,userId:t}),r=Ee(ee({},r),{totalCost:m,local:g,dns:N,tcp:P,tls:k,request:x,response:J});break}}catch(o){$.error("getScheduleDetailCost error",o)}return r}function Jm(m){return y(this,arguments,function*({userId:i,sdkAppId:t,useStringRoomId:e,roomId:r,userSig:o,version:s,frameWorkType:n,role:d,latencyLevel:p}){if(!Hd&&qm)return{isCached:!0,result:qm};let g={delta:0,count:[1,1],msg:[],detail:[]};try{let _=new FormData;_.append("userId",String(i)),_.append("sdkAppId",String(t)),_.append("isStrGroupId",String(e)),_.append("groupId",String(r)),_.append("sdkVersion",s),_.append("userSig",String(o)),d&&_.append("role",String(d)),p&&_.append("latencyLevel",String(p)),n&&_.append("frameWorkType",String(n));let b=_e(),N=yield HI(_,g,t);N.config&&(N.config.loggerDomain&&_o(N.config.loggerDomain),nt(N.config.scheduleCache)&&zo(!N.config.scheduleCache)),g.delta=_e()-b;let k=FI(Number(t),i,b);return qm=N,{isCached:!1,result:N,detailCost:k}}catch(_){let b=st(_)?_[0]:_,N=je(b.code)?b.code:0,k=`schedule failed${b.message?`: ${b.message}`:""}`,P=new he({code:te.SCHEDULE_FAILED,extraCode:N,message:dt({key:ct.JOIN_ROOM_FAILED,data:{error:k,code:N}})});throw $.error(k,N),P}})}var ro={main:"",backup:""};function Wd(i){st(i)?(ro.main=i[0],ro.backup=i[1]):ro.main=i}var Yf=(r=>(r.CONFIG="config",r.TRTC_AUTO_CONF="trtcAutoConf",r.AUDIO_AI_AUTH="audioAiAuth",r))(Yf||{});function to(i,t,e=D.MAIN,r=!1){return`https://${ro[e]||Zf(i,e,r)}/api/v1/${t}`}function $I(i,t,e){let r=to(i,t),o=to(i,t,D.BACKUP),s=new URLSearchParams(e).toString(),n=fetch(`${r}?${s}`).then(p=>p.json()),d=fetch(`${o}?${s}`).then(p=>p.json());return wn([n,d])}function Zf(i,t=D.MAIN,e=!1){let r;return vn(i)?e?r=t===D.MAIN?Qr.MAIN_OVERSEA_BACKUP:Qr.BACKUP_OVERSEA:r=t===D.MAIN?Qr.MAIN_OVERSEA:Qr.BACKUP_OVERSEA:r=t===D.MAIN?Qr.MAIN:Qr.BACKUP,r}function BI(i,t,e){return new Promise((r,o)=>{Zr({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 Qf=(i,t)=>ki({retryFunction:BI,settings:{retries:3,timeout:0},onError:t,onRetrying:i});function HI(i,t,e){return new Promise((r,o)=>{let s=null;wn([Qf(n=>t.count[0]=n+1,({error:n,retry:d,retriedCount:p,retryFuncArgs:m})=>{t.msg[0]=n.message,s||(p>=1&&(m[0]=to(e,"config",D.MAIN,!0)),d())})(to(e,"config",D.MAIN),i,{get timeout(){return yo(2+t.count[0])*1e3}}),Qf(n=>t.count[1]=n+1,({error:n,retry:d,retriedCount:p,retryFuncArgs:m})=>{t.msg[1]=n.message,s||(p>=2&&(m[0]=to(e,"config",D.BACKUP,!0)),d())})(to(e,"config",D.BACKUP),i,{get timeout(){return yo(2+t.count[1])*1e3}})]).then(n=>{s=n,r(s)}).catch(o)})}var WI=i=>i.startsWith("data:application/octet-stream;base64,"),GI=i=>i.startsWith("file://"),Gd=class{constructor(){u(this,"_log");this._log=$.createLogger({id:"fd"})}download(t,e){return y(this,null,function*(){let{type:r="blob"}=e||{};t=t.replace(/(^|[^:])\/{2,}/g,"$1/");try{let o=_e(),s;if(Xe(fetch)?s=yield this.downloadWithFetch(t,r):s=yield this.downloadWithXHR(t,r),!s||!s.data)throw new Error("data is empty");let n=_e()-o;return this._log.info(`downloaded: ${t}, return type: ${r}, cost: ${n}ms`),Y.addSuccessEvent({key:522700,cost:_e()-o}),s.data}catch(o){throw this._log.error(`failed to download: ${t}, error: ${o}`),Y.addFailedEvent({key:522700,error:o}),o}})}downloadWithFetch(t,e){return y(this,null,function*(){this._log.info(`download with fetch: ${t}, return type: ${e}`);try{let r=yield fetch(t);if(!r.ok)throw new Error("network response was not ok");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=()=>{s.status===200||s.status===0&&s.response?r({data:s.response}):o(new Error("XHR failed"))},s.onerror=o,s.send(null)})}loadWasm(t,e){return y(this,null,function*(){this._log.info(`loadWasm ${t}, importObject: ${JSON.stringify(e)}`);let r=_e(),o=null,s=null;if(Xe(WebAssembly.instantiateStreaming)&&!WI(t)&&!GI(t)&&Xe(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=_e()-r;return this._log.info(`loadedWasm ${t}, cost: ${n}ms`),Y.addSuccessEvent({key:522701,cost:n}),o}throw this._log.error(`failed to loadWasm ${t}, error: ${s}`),Y.addFailedEvent({key:522701,error:s}),s})}};X([Hi({settings:{timeout:0,retries:3},onRetrying(t){this._log.warn(`download retrying: ${t}`)}})],Gd.prototype,"download",1);var Kf=new Gd;function eg({TRTC:i,room:t,errorModule:e,assetsPath:r}){return{TRTC:i,room:t,assetsPath:r,fileDownloader:Kf,innerEmitter:H,constants:$u,environment:ws,utils:jm,eventLogger:Be,log:this.room.getLogger(),loggerManager:$,errorModule:e,kvStatManager:Y,rtcDectection:Bi,trtc:this,rx:Um,enums:Sl,schedule:zm,clearStarted:(o,s)=>{let n=o.getAlias(),d=fi.instances.get(this);if(d)if(s){let p=d.get(n+s);if(!p)return;p.started=!1}else d.forEach((p,m)=>{m.startsWith(n)&&(p.started=!1)})},startGetPCM:ga,createAudioNode:ql}}var tg=(i,t)=>{let{emit:e}=i;return i.emit=(...r)=>{try{return e.apply(i,r)}catch(o){let s=dt({key:ct.CATCH_HANDLER_ERROR,data:{name:t,event:r[0]},addDocLink:!1});return $.warn(`${s}
|
|
95
95
|
|
|
96
|
-
${o.stack}`),!1}},i};var Qs=new WeakMap;function Kf(i){let t=Qs.get(i);t&&(t.forEach(e=>clearTimeout(e)),Qs.delete(i))}function eg(i,t){return Me((e,r)=>function(...o){let s=Qs.get(this);s||(s=new Map,Qs.set(this,s));let n=t(...o),d=s.get(n);if(!d||d<=0){e.apply(this,o);let p=setTimeout(()=>{var m;(m=Qs.get(this))==null||m.delete(n)},i);s.set(n,p)}else{clearTimeout(d);let p=window.setTimeout(()=>{var m;e.apply(this,o),(m=Qs.get(this))==null||m.delete(n)},i);s.set(n,p)}})}var tg="5.10.0-wasm.1";function Ut(...i){return Me((t,e)=>function(...r){try{jd.call(this,i,r,e,this._name)}catch(o){return Promise.reject(o)}return t.apply(this,r)})}function Jm(...i){return Me((t,e)=>function(...r){try{jd.call(this,i,r,e,this._name)}catch(o){throw o}return t.apply(this,r)})}function jd(i,t,e,r){if(st(i))for(let o=0;o<i.length;o++)Gd.call(this,{rule:i[o],value:t[o],key:i[o].name,fnName:e,className:r});else Gd.call(this,{rule:i,value:t[0],key:i.name,fnName:e,className:r})}function Gd({rule:i,value:t,key:e,fnName:r,className:o}){function s(p){return{code:ue.INVALID_PARAMETER,extraCode:p,fnName:r,messageParams:{key:e,rule:i,value:t}}}if($(t)){if(i.required)throw new ae(s(5001));if($(i.defaultValue)){ze(i.validate)&&i.validate.call(this,t,e,r,o,this);return}t=i.defaultValue}if(Array.isArray(i.type)){let p=!1;for(let m=0;m<i.type.length;m++)i.type[m]===null&&t===null&&(p=!0),ze(i.type[m])&&t instanceof i.type[m]&&(p=!0),we(i.type[m])&&mt(t)===i.type[m].toLowerCase()&&(p=!0);if(!p)throw new ae({code:ue.INVALID_PARAMETER,extraCode:5002,fnName:r,messageParams:{key:e,rule:{type:i.type.map(m=>ps(m)?wn(m):we(m)?m:mt(m))},value:t}})}else if(!$(i.type)&&mt(t)!==i.type)throw new ae(s(5002));if(i.allowEmpty===!1){let p=je(t)&&(t===0||Number.isNaN(t)),m=we(t)&&t.trim()==="";if(p||m)throw new ae(s(5003))}if(i.notLessThanZero&&je(t)&&t<0)throw new ae(s(5006));if(!$(i.min)&&je(t)&&t<i.min)throw new ae(s(5007));if(!$(i.max)&&je(t)&&t>i.max)throw new ae(s(5008));if(we(i.instanceOf)){if(!t||t._name!==i.instanceOf)throw new ae(s(5004))}else if(ze(i.instanceOf)&&!(t instanceof i.instanceOf))throw new ae(s(5004));if(Array.isArray(i.values)&&!i.values.includes(t))throw new ae(s(5005));let{properties:n}=i;Gt(n)&&xr(t)&&Object.keys(n).forEach(p=>{Gd.call(this,{rule:n[p],value:t&&t[p],key:`${p}`,fnName:r,className:o})});let{arrayItem:d}=i;Gt(d)&&st(t)&&t.forEach((p,m)=>{Gd.call(this,{rule:d,value:p,key:`${e}[${m}]`,fnName:r,className:o})}),ze(i.validate)&&i.validate.call(this,t,e,r,o,this)}function Ye(i={}){let{getRemoteId:t=()=>"",replaceArg:e,getKVReportKey:r,ignoreLog:o}=i;return Me((s,n)=>function(...d){var _;function p(b,C,k){if(k&&k.includes(b))return"hided";if(e){let x=e(...d);if(d[x.argIndex]===C)return x.value}if(C===d||b in d)return C;try{return C instanceof HTMLElement?`id: ${C.id} type:${mt(C)}`:(JSON.stringify(C),C)}catch(x){return`type:${mt(C)}`}}let m=this._log||B;if(o!=null&&o(...d))return s.apply(this,d);d.length>0?m.info(`${n}() ${JSON.stringify(d,(b,C)=>p(b,C,["userSig","privateMapKey"]))}`):m.info(`${n}()`);let E=r?r(...d):Xc[n];try{let b=s.apply(this,d),C=_e();return Mi(b)?b.then(k=>(m.info(`${n}() success ${t.call(this,...d)}`),Y.addSuccessEvent({key:E,cost:_e()-C}),k)).catch(k=>{var J;k=ae.convertFrom.call(this,k,n,d.length===1?d[0]:d);let x=k.extraCode||k.code,P=(J=k.message)!=null&&J.includes(x)?"":` code:${x}`;throw m.error(`${n}() failed ${t.call(this,...d)} ${k}${P} params: ${JSON.stringify(d,p)}`),Y.addFailedEvent({key:E,error:k}),k}):(Y.addSuccessEvent({key:E}),b)}catch(b){b=ae.convertFrom.call(this,b,n);let C=b.extraCode||b.code,k=(_=b.message)!=null&&_.includes(C)?"":` code:${C}`;throw m.error(`${n}() failed ${b}${k} params: ${JSON.stringify(d,p)}`),Y.addFailedEvent({key:E,error:b}),b}})}var qd=i=>Me((t,e)=>function(r,o){return y(this,null,function*(){let s=this._plugins.get(r);if(!s)throw this._log.error(`plugin ${String(r)} is not found`),new ae({code:ue.OPERATION_ABORT,message:`plugin ${String(r)} is not found`,fnName:e});if(ze(s.constructor.isSupported)&&!s.constructor.isSupported())throw this._log.error(`plugin ${String(r)} is not supported`),new ae({code:ue.ENV_NOT_SUPPORTED,message:`plugin ${String(r)} is not supported`,extraCode:5210,fnName:e});return jd.call(this,s.getValidateRule(i),[o],e,"TRTC"),t.call(this,s,o)})});var Jd=0,zm=class{constructor(t,e){u(this,"player");u(this,"publisher");u(this,"mixInput");this.mixInput=new Vs(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&&($(t.volume)||(this.volume=t.volume),$(t.loop)||(this.loop=t.loop),$(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)}}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(t=this.publisher)==null||t.play(),(e=this.player)==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 Ys(i,t){if(t&&typeof t!="function")throw new ae({code:ue.INVALID_PARAMETER,message:`start audioMixer plugin: param ${i} should be a function.`})}var Fr=class Fr{constructor(t){this.core=t;u(this,"log");u(this,"mixedMusicMap",new Map);u(this,"cacheMusicMap",new Map);Jd=Jd+1,this.log=t.log.createChild({id:`${this.getAlias()}${Jd}`}),this.log.info(`[audioMixer] created id=${this.getAlias()}${Jd}`),this.core=t}getName(){return Fr.Name}getAlias(){return"ax"}getGroup(t){return t==null?void 0:t.id}getValidateRule(t){switch(t){case"start":return Fr.startValidateRule;case"update":return Fr.updateValidateRule;case"stop":return Fr.stopValidateRule}}start(t){return y(this,null,function*(){let{room:e}=this.core;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 zm(t,e.audioManager),this.cacheMusicMap.set(r,s)),s.updateListener(t),s.updateSettings(t),yield s.play(),this.mixedMusicMap.set(r,s),this.log.info(`start mix audio track ${r} success.`),Y.addEnum({key:502700,value:3}),this.kvUpload(t)})}update(t){return y(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),$(r)||n.setOperation(r),$(o)||n.seek(o),this.kvUpload(t)})}stop(e){return y(this,arguments,function*({id:t}){var r;this.mixedMusicMap.has(t)&&(this.log.info(`remove music source, music id: ${t}`),(r=this.mixedMusicMap.get(t))==null||r.stop(),this.mixedMusicMap.delete(t)),t==="*"&&this.destroyAllMusic()})}kvUpload(t){let{track:e,loop:r,volume:o,playbackRate:s,operation:n,seekFrom:d,onTimeUpdate:p,onDurationChange:m,onEnded:E}=t;e&&Y.addCount({key:502711}),r&&Y.addCount({key:502703}),o&&Y.addCount({key:502704}),s&&Y.addCount({key:502705}),n&&Y.addCount({key:502706}),d&&Y.addCount({key:502707}),typeof p!="function"&&Y.addCount({key:502709}),typeof E!="function"&&Y.addCount({key:502710}),typeof m!="function"&&Y.addCount({key:502708})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((t,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()}};u(Fr,"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(),d=s.indexOf(n)>=0,p=o.startsWith("blob"),m=o.startsWith("data");if(!(d||p||m))throw new ae({code:ue.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:r})}if(!t.url&&!t.track)throw new ae({code:ue.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:r});Ys("onTimeUpdate",t.onTimeUpdate),Ys("onEnded",t.onEnded),Ys("onDurationChange",t.onDurationChange)}}),u(Fr,"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){Ys("onTimeUpdate",t.onTimeUpdate),Ys("onEnded",t.onEnded),Ys("onDurationChange",t.onDurationChange)}}),u(Fr,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),u(Fr,"Name","AudioMixer");var zd=Fr;var Xd=0,Xm,hi=class hi{constructor(t){this.core=t;u(this,"log");u(this,"audioContext",et("denoiser"));u(this,"workletNode");Xd=Xd+1,this.log=t.log.createChild({id:`${this.getAlias()}${Xd}`}),this.log.info(`[audioDenoiser] created id=${this.getAlias()}${Xd}`),t.assetsPath&&this.preload(`${t.assetsPath}/denoiser-wasm.js`)}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}},validate(e,r,o,s){if(!t.room.audioManager.hasAudioTrack)throw new ae({code:ue.INVALID_OPERATION,extraCode:5106,fnName:o})}}}preload(t){return Xm||(Xm=this.doPreload(t)),Xm}doPreload(t){return y(this,null,function*(){let e=yield this.core.fileDownloader.download(t,{type:"blob"}),r=URL.createObjectURL(e);try{yield Mo(this.audioContext,r)}finally{URL.revokeObjectURL(r)}})}getName(){return hi.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(t){switch(t){case"start":return hi.startValidateRule(this.core);case"update":return hi.updateValidateRule;case"stop":return hi.stopValidateRule}}start(t){return y(this,null,function*(){let{room:e}=this.core;if(yield this.preload(`${t.assetsPath}/denoiser-wasm.js`),!this.workletNode){let r=String(Date.now()).slice(0,-3),{auth:o,sign:s,status:n,message:d}=yield jI(Ee(Z({},t),{timestamp:r}));if(!o)throw this.log.info(`RTCAIDenoiser: ${t.userId} auth result: ${o}. Message: ${d}`),new ae({code:ue.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:r,sign:s,status:n}}),this.workletNode.port.onmessage=p=>{let{data:m}=p;m.type==="cost"&&this.log.debug(`[RTCAIDenoiser] ${m.value}`)}}this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(){return y(this,null,function*(){})}stop(){return y(this,null,function*(){if(!this.workletNode)return;let{room:t}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield t.audioManager.removeDenoiser(this.workletNode)})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};u(hi,"updateValidateRule",{type:"object"}),u(hi,"stopValidateRule",{type:"object"}),u(hi,"Name","AIDenoiser");var Qd=hi;function GI(i,t=D.MAIN){return`https://${Rr[t]||Da(i,t)}/api/v1/audioAiAuth`}function jI(o){return y(this,arguments,function*({sdkAppId:i,userId:t,userSig:e,timestamp:r}){let n=`${GI(i)}?sdkAppId=${i}&userId=${t}&userSig=${e}×tamp=${r}`,d=yield fetch(n),{data:{errCode:p,errMsg:m,sign:E,status:_}}=yield d.json();if(_==="1")return{auth:!0,sign:E,status:_,message:m};let b="Init RTCAIDenoiser failed.",C="";switch(p){case 1:C="Please check your params.";break;case 2:C="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:C="Server is invalid. Please contact our engineer. ";break;case 4:C="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:C="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:C="Your version is not supported.";break}return{auth:!1,status:_,message:m?`${b} Reason: ${m}. ${C}`:`${b}, ${C}`}})}var rg=Di(Ui(),1);var Qm=class extends rg.EventEmitter{constructor(){super();u(this,"observer");u(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 y(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!gt&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){$e.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)&&B.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){$e.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:r})}}},qI=new Qm,Ym=qI;function JI([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 d=0;d<r;d++)s.push(255);s.push(o);let n=new DataView(t);return s.push(...new Uint8Array(n.buffer)),s.push(128),new xo(new DataView(new Uint8Array(s).buffer),!0)}function zI(i){return i.type==="empty"||i.data.byteLength===0}function XI(i){return i.getInt32(0)===1&&i.getInt8(4)===6}function QI(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 Zm({frame:i,seiMessageList:t}){if(!t||t.length===0||i.data.byteLength===0)return i;let r=9-QI(i.data);if(r<=0)return i;let o=t.splice(0,r).reverse().map(JI),s=o.reduce((E,_)=>E+_.dataView.byteLength,0),n=new ArrayBuffer(s+i.data.byteLength),d=new DataView(n),p=new DataView(i.data),m=0;for(let E=0;E<o.length;E++)for(let _=0;_<o[E].dataView.byteLength;_++)d.setInt8(m++,o[E].dataView.getInt8(_));for(let E=0;E<i.data.byteLength;E++)d.setInt8(m++,p.getInt8(E));return i.data=n,i}function Km({frame:i,onSEI:t}){try{let e=new DataView(i.data);if(zI(i)||!XI(e))return i;let r=[],o=0,s=-1,n=-1;for(let d=0;d<i.data.byteLength;d++){let p=e.getUint8(d);if(p===0)o++;else if(p===1){if(o===2||o===3){let m=d-o;if(s===-1?s=m:n===-1&&(n=m,r.push(new xo(new DataView(e.buffer.slice(s,n)))),s=m,n=-1),!(e.getUint8(d+1)===6)){i.data=e.buffer.slice(m);break}}o=0}else o=0}t==null||t(r.reverse())}catch(e){}return i}var ep=0,wa=class wa{constructor(t){this.core=t;u(this,"log");u(this,"_seiMessageList",[]);u(this,"_smallSeiMessageList",[]);u(this,"_subStreamSeiMessageList",[]);ep++,this.log=t.log.createChild({id:`${this.getAlias()}${ep}`}),this.log.info(`[sei] created id=${this.getAlias()}${ep}`),this.core=t,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 Zm({frame:t,seiMessageList:r})}catch(r){this.log.warn(r)}return t}decode({frame:t,track:e}){return Km({frame:t,onSEI:r=>{r.forEach(o=>{this.core.trtc.emit(se.SEI_MESSAGE,{seiPayloadType:o.seiPayloadType,data:o.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"})})}})}destroy(){this.log.debug("destory"),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:oa?this.encode:Zm,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:oa?this.decode:Km,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 wa.Name}getAlias(){return"sei"}getGroup(){return"sei"}};u(wa,"autoStart",!0),u(wa,"Name","SEI");var Yd=wa;function tp({frame:i,onDump:t}){return t==null||t(),i}function rp({frame:i,onDump:t}){return t==null||t(),i}var ig={"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:
|
|
96
|
+
${o.stack}`),!1}},i};var Xs=new WeakMap;function rg(i){let t=Xs.get(i);t&&(t.forEach(e=>clearTimeout(e)),Xs.delete(i))}function ig(i,t){return Me((e,r)=>function(...o){let s=Xs.get(this);s||(s=new Map,Xs.set(this,s));let n=t(...o),d=s.get(n);if(!d||d<=0){e.apply(this,o);let p=setTimeout(()=>{var m;(m=Xs.get(this))==null||m.delete(n)},i);s.set(n,p)}else{clearTimeout(d);let p=window.setTimeout(()=>{var m;e.apply(this,o),(m=Xs.get(this))==null||m.delete(n)},i);s.set(n,p)}})}var sg="trtc-sdk-v5",ng="5.10.0-wasm.3";function Ut(...i){return Me((t,e)=>function(...r){try{qd.call(this,i,r,e,this._name)}catch(o){return Promise.reject(o)}return t.apply(this,r)})}function Xm(...i){return Me((t,e)=>function(...r){try{qd.call(this,i,r,e,this._name)}catch(o){throw o}return t.apply(this,r)})}function qd(i,t,e,r){if(st(i))for(let o=0;o<i.length;o++)jd.call(this,{rule:i[o],value:t[o],key:i[o].name,fnName:e,className:r});else jd.call(this,{rule:i,value:t[0],key:i.name,fnName:e,className:r})}function jd({rule:i,value:t,key:e,fnName:r,className:o}){function s(p){return{code:ue.INVALID_PARAMETER,extraCode:p,fnName:r,messageParams:{key:e,rule:i,value:t}}}if(V(t)){if(i.required)throw new ae(s(5001));if(V(i.defaultValue)){Xe(i.validate)&&i.validate.call(this,t,e,r,o,this);return}t=i.defaultValue}if(Array.isArray(i.type)){let p=!1;for(let m=0;m<i.type.length;m++)i.type[m]===null&&t===null&&(p=!0),Xe(i.type[m])&&t instanceof i.type[m]&&(p=!0),we(i.type[m])&&ht(t)===i.type[m].toLowerCase()&&(p=!0);if(!p)throw new ae({code:ue.INVALID_PARAMETER,extraCode:5002,fnName:r,messageParams:{key:e,rule:{type:i.type.map(m=>hs(m)?Nn(m):we(m)?m:ht(m))},value:t}})}else if(!V(i.type)&&ht(t)!==i.type)throw new ae(s(5002));if(i.allowEmpty===!1){let p=je(t)&&(t===0||Number.isNaN(t)),m=we(t)&&t.trim()==="";if(p||m)throw new ae(s(5003))}if(i.notLessThanZero&&je(t)&&t<0)throw new ae(s(5006));if(!V(i.min)&&je(t)&&t<i.min)throw new ae(s(5007));if(!V(i.max)&&je(t)&&t>i.max)throw new ae(s(5008));if(we(i.instanceOf)){if(!t||t._name!==i.instanceOf)throw new ae(s(5004))}else if(Xe(i.instanceOf)&&!(t instanceof i.instanceOf))throw new ae(s(5004));if(Array.isArray(i.values)&&!i.values.includes(t))throw new ae(s(5005));let{properties:n}=i;Gt(n)&&Pr(t)&&Object.keys(n).forEach(p=>{jd.call(this,{rule:n[p],value:t&&t[p],key:`${p}`,fnName:r,className:o})});let{arrayItem:d}=i;Gt(d)&&st(t)&&t.forEach((p,m)=>{jd.call(this,{rule:d,value:p,key:`${e}[${m}]`,fnName:r,className:o})}),Xe(i.validate)&&i.validate.call(this,t,e,r,o,this)}function Ye(i={}){let{getRemoteId:t=()=>"",replaceArg:e,getKVReportKey:r,ignoreLog:o}=i;return Me((s,n)=>function(...d){var _;function p(b,N,k){if(k&&k.includes(b))return"hided";if(e){let P=e(...d);if(d[P.argIndex]===N)return P.value}if(N===d||b in d)return N;try{return N instanceof HTMLElement?`id: ${N.id} type:${ht(N)}`:(JSON.stringify(N),N)}catch(P){return`type:${ht(N)}`}}let m=this._log||$;if(o!=null&&o(...d))return s.apply(this,d);d.length>0?m.info(`${n}() ${JSON.stringify(d,(b,N)=>p(b,N,["userSig","privateMapKey"]))}`):m.info(`${n}()`);let g=r?r(...d):zc[n];try{let b=s.apply(this,d),N=_e();return xi(b)?b.then(k=>(m.info(`${n}() success ${t.call(this,...d)}`),Y.addSuccessEvent({key:g,cost:_e()-N}),k)).catch(k=>{var J;k=ae.convertFrom.call(this,k,n,d.length===1?d[0]:d);let P=k.extraCode||k.code,x=(J=k.message)!=null&&J.includes(P)?"":` code:${P}`;throw m.error(`${n}() failed ${t.call(this,...d)} ${k}${x} params: ${JSON.stringify(d,p)}`),Y.addFailedEvent({key:g,error:k}),k}):(Y.addSuccessEvent({key:g}),b)}catch(b){b=ae.convertFrom.call(this,b,n);let N=b.extraCode||b.code,k=(_=b.message)!=null&&_.includes(N)?"":` code:${N}`;throw m.error(`${n}() failed ${b}${k} params: ${JSON.stringify(d,p)}`),Y.addFailedEvent({key:g,error:b}),b}})}var Jd=i=>Me((t,e)=>function(r,o){return y(this,null,function*(){let s=this._plugins.get(r);if(!s)throw this._log.error(`plugin ${String(r)} is not found`),new ae({code:ue.OPERATION_ABORT,message:`plugin ${String(r)} is not found`,fnName:e});if(Xe(s.constructor.isSupported)&&!s.constructor.isSupported())throw this._log.error(`plugin ${String(r)} is not supported`),new ae({code:ue.ENV_NOT_SUPPORTED,message:`plugin ${String(r)} is not supported`,extraCode:5210,fnName:e});return qd.call(this,s.getValidateRule(i),[o],e,"TRTC"),t.call(this,s,o)})});var zd=0,Qm=class{constructor(t,e){u(this,"player");u(this,"publisher");u(this,"mixInput");this.mixInput=new Fs(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&&(V(t.volume)||(this.volume=t.volume),V(t.loop)||(this.loop=t.loop),V(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)}}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(t=this.publisher)==null||t.play(),(e=this.player)==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 Qs(i,t){if(t&&typeof t!="function")throw new ae({code:ue.INVALID_PARAMETER,message:`start audioMixer plugin: param ${i} should be a function.`})}var Hr=class Hr{constructor(t){this.core=t;u(this,"log");u(this,"mixedMusicMap",new Map);u(this,"cacheMusicMap",new Map);zd=zd+1,this.log=t.log.createChild({id:`${this.getAlias()}${zd}`}),this.log.info(`[audioMixer] created id=${this.getAlias()}${zd}`),this.core=t}getName(){return Hr.Name}getAlias(){return"ax"}getGroup(t){return t==null?void 0:t.id}getValidateRule(t){switch(t){case"start":return Hr.startValidateRule;case"update":return Hr.updateValidateRule;case"stop":return Hr.stopValidateRule}}start(t){return y(this,null,function*(){let{room:e}=this.core;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 Qm(t,e.audioManager),this.cacheMusicMap.set(r,s)),s.updateListener(t),s.updateSettings(t),yield s.play(),this.mixedMusicMap.set(r,s),this.log.info(`start mix audio track ${r} success.`),Y.addEnum({key:502700,value:3}),this.kvUpload(t)})}update(t){return y(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),V(r)||n.setOperation(r),V(o)||n.seek(o),this.kvUpload(t)})}stop(e){return y(this,arguments,function*({id:t}){var r;this.mixedMusicMap.has(t)&&(this.log.info(`remove music source, music id: ${t}`),(r=this.mixedMusicMap.get(t))==null||r.stop(),this.mixedMusicMap.delete(t)),t==="*"&&this.destroyAllMusic()})}kvUpload(t){let{track:e,loop:r,volume:o,playbackRate:s,operation:n,seekFrom:d,onTimeUpdate:p,onDurationChange:m,onEnded:g}=t;e&&Y.addCount({key:502711}),r&&Y.addCount({key:502703}),o&&Y.addCount({key:502704}),s&&Y.addCount({key:502705}),n&&Y.addCount({key:502706}),d&&Y.addCount({key:502707}),typeof p!="function"&&Y.addCount({key:502709}),typeof g!="function"&&Y.addCount({key:502710}),typeof m!="function"&&Y.addCount({key:502708})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((t,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()}};u(Hr,"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(),d=s.indexOf(n)>=0,p=o.startsWith("blob"),m=o.startsWith("data");if(!(d||p||m))throw new ae({code:ue.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:r})}if(!t.url&&!t.track)throw new ae({code:ue.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:r});Qs("onTimeUpdate",t.onTimeUpdate),Qs("onEnded",t.onEnded),Qs("onDurationChange",t.onDurationChange)}}),u(Hr,"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){Qs("onTimeUpdate",t.onTimeUpdate),Qs("onEnded",t.onEnded),Qs("onDurationChange",t.onDurationChange)}}),u(Hr,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),u(Hr,"Name","AudioMixer");var Xd=Hr;var Qd=0,Ym,gi=class gi{constructor(t){this.core=t;u(this,"log");u(this,"audioContext",et("denoiser"));u(this,"workletNode");Qd=Qd+1,this.log=t.log.createChild({id:`${this.getAlias()}${Qd}`}),this.log.info(`[audioDenoiser] created id=${this.getAlias()}${Qd}`),t.assetsPath&&this.preload(`${t.assetsPath}/denoiser-wasm.js`).catch(e=>{})}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}},validate(e,r,o,s){if(!t.room.audioManager.hasAudioTrack)throw new ae({code:ue.INVALID_OPERATION,extraCode:5106,fnName:o})}}}preload(t){return Ym||(Ym=this.doPreload(t)),Ym}doPreload(t){return y(this,null,function*(){let e=yield this.core.fileDownloader.download(t,{type:"blob"}),r=URL.createObjectURL(e);try{yield Po(this.audioContext,r)}catch(o){throw this.log.error("load worklet failed",o),o}finally{URL.revokeObjectURL(r)}})}getName(){return gi.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(t){switch(t){case"start":return gi.startValidateRule(this.core);case"update":return gi.updateValidateRule;case"stop":return gi.stopValidateRule}}start(t){return y(this,null,function*(){let{room:e,schedule:r}=this.core;if(yield this.preload(`${t.assetsPath}/denoiser-wasm.js`),!this.workletNode){let o=String(Date.now()).slice(0,-3),{auth:s,sign:n,status:d,message:p}=yield jI(r,Ee(ee({},t),{timestamp:o}));if(!s)throw this.log.info(`RTCAIDenoiser: ${t.userId} auth result: ${s}. Message: ${p}`),new ae({code:ue.INVALID_PARAMETER,message:p});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:o,sign:n,status:d}}),this.workletNode.port.onmessage=m=>{var _;let{data:g}=m;if(g.type==="cost"){let b=(g==null?void 0:g.max)>20?"warn":(g==null?void 0:g.max)>10?"info":"debug";this.log[b](`avg cost: ${g.value} max: ${g==null?void 0:g.max}(${sc(new Date(g==null?void 0:g.maxCostTimestamp))}) hist: ${(_=g==null?void 0:g.hist)==null?void 0:_.join(" ")}`)}else g.type==="log"&&this.log[g.logLevel](`${g.value}`)}}this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(){return y(this,null,function*(){})}stop(){return y(this,null,function*(){if(!this.workletNode)return;let{room:t}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield t.audioManager.removeDenoiser(this.workletNode)})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};u(gi,"updateValidateRule",{type:"object"}),u(gi,"stopValidateRule",{type:"object"}),u(gi,"Name","AIDenoiser");var Yd=gi;function jI(s,n){return y(this,arguments,function*(i,{sdkAppId:t,userId:e,userSig:r,timestamp:o}){try{let{data:{errCode:d,errMsg:p,sign:m,status:g}}=yield i.getAbilityConfig(t,i.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:t,userId:e,userSig:r,timestamp:o});if(g==="1")return{auth:!0,sign:m,status:g,message:p};let _="Init RTCAIDenoiser failed.",b="";switch(d){case 1:b="Please check your params.";break;case 2:b="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:b="Server is invalid. Please contact our engineer. ";break;case 4:b="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:b="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:b="Your version is not supported.";break}return{auth:!1,status:g,message:p?`${_} Reason: ${p}. ${b}`:`${_}, ${b}`}}catch(d){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${d}`}}})}var ag=Mi($i(),1);var Zm=class extends ag.EventEmitter{constructor(){super();u(this,"observer");u(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 y(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!at&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){Be.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)&&$.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){Be.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:r})}}},qI=new Zm,Km=qI;function JI([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 d=0;d<r;d++)s.push(255);s.push(o);let n=new DataView(t);return s.push(...new Uint8Array(n.buffer)),s.push(128),new Uo(new DataView(new Uint8Array(s).buffer),!0)}function zI(i){return i.type==="empty"||i.data.byteLength===0}function XI(i){return i.getInt32(0)===1&&i.getInt8(4)===6}function QI(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 ep({frame:i,seiMessageList:t}){if(!t||t.length===0||i.data.byteLength===0)return i;let r=9-QI(i.data);if(r<=0)return i;let o=t.splice(0,r).reverse().map(JI),s=o.reduce((g,_)=>g+_.dataView.byteLength,0),n=new ArrayBuffer(s+i.data.byteLength),d=new DataView(n),p=new DataView(i.data),m=0;for(let g=0;g<o.length;g++)for(let _=0;_<o[g].dataView.byteLength;_++)d.setInt8(m++,o[g].dataView.getInt8(_));for(let g=0;g<i.data.byteLength;g++)d.setInt8(m++,p.getInt8(g));return i.data=n,i}function tp({frame:i,onSEI:t}){try{let e=new DataView(i.data);if(zI(i)||!XI(e))return i;let r=[],o=0,s=-1,n=-1;for(let d=0;d<i.data.byteLength;d++){let p=e.getUint8(d);if(p===0)o++;else if(p===1){if(o===2||o===3){let m=d-o;if(s===-1?s=m:n===-1&&(n=m,r.push(new Uo(new DataView(e.buffer.slice(s,n)))),s=m,n=-1),!(e.getUint8(d+1)===6)){i.data=e.buffer.slice(m);break}}o=0}else o=0}t==null||t(r.reverse())}catch(e){}return i}var rp=0,Na=class Na{constructor(t){this.core=t;u(this,"log");u(this,"_seiMessageList",[]);u(this,"_smallSeiMessageList",[]);u(this,"_subStreamSeiMessageList",[]);rp++,this.log=t.log.createChild({id:`${this.getAlias()}${rp}`}),this.log.info(`[sei] created id=${this.getAlias()}${rp}`),this.core=t,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 ep({frame:t,seiMessageList:r})}catch(r){this.log.warn(r)}return t}decode({frame:t,track:e}){return tp({frame:t,onSEI:r=>{r.forEach(o=>{this.core.trtc.emit(se.SEI_MESSAGE,{seiPayloadType:o.seiPayloadType,data:o.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"})})}})}destroy(){this.log.debug("destory"),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:oa?this.encode:ep,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:oa?this.decode:tp,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 Na.Name}getAlias(){return"sei"}getGroup(){return"sei"}};u(Na,"autoStart",!0),u(Na,"Name","SEI");var Zd=Na;function ip({frame:i,onDump:t}){return t==null||t(),i}function op({frame:i,onDump:t}){return t==null||t(),i}var cg={"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:
|
|
97
97
|
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.
|
|
98
98
|
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:
|
|
99
99
|
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.
|
|
100
|
-
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=>{ig[`${i}()`]={tips:`Call trtc.${i}`,color:"blue",class:"blue",textColor:"#fff"}});var ox=Object.keys(ig);var YI=0,Zd,Zs=class Zs{constructor(t){this.core=t;u(this,"_core");u(this,"log");u(this,"dumpLocalVideoMap",{});u(this,"dumpRemoteVideoMap",{});u(this,"dialog");this._core=t,this.log=t.log.createChild({id:`${this.getAlias()}${++YI}`}),this.log.info("created")}getName(){return Zs.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 y(this,null,function*(){var e;!new URLSearchParams(location.search).has("trtcDebug")&&((e=window.sessionStorage)==null?void 0:e.getItem("TRTC_ENABLE_DEBUG_PLUGIN"))!=="true"||(yield this.openDebugDiaLog(),this.addVideoProcessor())})}update(){}stop(){this.closeDebugDiaLog(),this.removeVideoProcessor()}destroy(){this.stop()}openDebugDiaLog(){return y(this,null,function*(){var t;try{if(Zd)yield Zd;else{let e=Date.now(),r=new URLSearchParams(location.search).get("trtcDebugDialogPath")||((t=window.sessionStorage)==null?void 0:t.getItem("TRTC_DEBUG_DIALOG_PATH"))||`https://unpkg.com/trtc@${rt}/assets/debug-dialog.js`;Zd=this.loadScript(r),yield Zd,this.log.info(`download debug dialog script cost: ${Date.now()-e}ms`)}this.dialog=new TRTCDebugDialog(this._core,this.log,this.dumpLocalVideoMap,this.dumpRemoteVideoMap),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(e){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(e))}})}closeDebugDiaLog(){var t;(t=this.dialog)==null||t.closeDialog(),this.dialog=null}addVideoProcessor(){this._core.room.videoManager.addEncodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.encodeVideo.bind(this):tp,type:1}),this._core.room.videoManager.addDecodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.decodeVideo.bind(this):rp,type:1})}removeVideoProcessor(){this._core.room.videoManager.removeEncodeProcessor({type:1}),this._core.room.videoManager.removeDecodeProcessor({type:1})}encodeVideo({frame:t,mediaType:e}){return tp({frame:t,onDump:()=>{if(!e)return;let r=e===2?"sub":"main",o=this.dumpLocalVideoMap[r];o&&(o.data.push(t.data),o.duration>0&&Date.now()-o.startTimestamp>o.duration*1e3&&o.onDumpEnd())}})}decodeVideo({frame:t,track:e}){return rp({frame:t,onDump:()=>{if(!e)return;let r=this.dumpRemoteVideoMap[`${e.userId}-${e.streamType}`];r&&(r.data.push(t.data),r.duration>0&&Date.now()-r.startTimestamp>r.duration*1e3&&r.onDumpEnd())}})}loadScript(t){return new Promise((e,r)=>{this.log.info(`loading debug dialog from ${t}`);let o=document.createElement("script");o.type="text/javascript",o.onload=e,o.onerror=r,o.crossOrigin="anonymous",o.src=t,document.head.append?document.head.append(o):document.getElementsByTagName("head")[0].appendChild(o)})}};u(Zs,"Name","Debug"),u(Zs,"autoStart",!0),X([Bi({settings:{timeout:3e3,retries:3},onError(t,e,r){var o;(o=t==null?void 0:t.message)!=null&&o.includes("timeout")?e():r(t)}})],Zs.prototype,"loadScript",1);var Kd=Zs;var og=i=>{switch(i){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},eu=class{constructor(t,e,r){u(this,"trackDoneOB");u(this,"startOB");u(this,"stopOB");u(this,"inputFrameCount",0);u(this,"decodedFrameCount",0);u(this,"type","auto");u(this,"config");u(this,"decoder");u(this,"_decodeSink");let{kvStatManager:o,trtc:s}=t;this.config=r.config,this.trackDoneOB=Ne(e,ne.INIT),this.stopOB=Ct(this.trackDoneOB),this.startOB=Ct(),r.type==="auto"?this.type="webCodecs":this.type=r.type;let n=Ct(),d=p=>{let m=this.pipe(e);return n.next("STARTING"),e.log.info(`decoder type: ${this.type}`),ve(m,Qe(this.stopOB),Ve(()=>{},E=>{e.log.error(E),o.addFailedEvent({key:og(this.type),error:E}),p>4?this.startOB.error(E):this.startOB.next(p+1)})),ve(m,yr(1),Mm(Ta))};ve(this.startOB,_a(0),ji(d),Qe(this.stopOB),Ve(()=>{e.player.setOutput(),n.next("STARTED")},p=>{n.next("FAILED")},()=>{o.addSuccessEvent({key:og(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 di()(e=>y(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"}))}},ZI={type:"object"},Ma=class Ma{constructor(t){this.core=t;u(this,"log");u(this,"contextMap",new Map);u(this,"decodeProcessorMap",new WeakMap);this.log=t.log.createChild({id:`${this.getAlias()}`})}getAlias(){return Ma.Name}getGroup(t){return t.track.userId+t.track.streamType}getName(){return Ma.Name}getValidateRule(t){return ZI}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 eu(this.core,r,t);return ve(o.trackDoneOB,yr(1),Ve(()=>{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 eu(this.core,t.track,t))}}};u(Ma,"Name","TRTCAudioDecoder");var Oa=Ma;var sg=0,Pa=new Set,bt=null;Mu(tg);ws.checkStorage();Ml();var KI={RtcError:ae,ErrorCode:ue,ErrorCodeDictionary:br},fe=class fe extends ng.EventEmitter{constructor(e,r){super();u(this,"_room");u(this,"_eventListened",new Set);u(this,"_localVideoTrack",null);u(this,"_localAudioTrack",null);u(this,"_localScreenTrack",null);u(this,"_localScreenAudioTrack",null);u(this,"_localVideoConfig",null);u(this,"_localScreenConfig",null);u(this,"_localAudioConfig",null);u(this,"_remoteVideoConfigMap",new Map);u(this,"_remoteAudioConfigMap",new Map);u(this,"_remoteAudioVolumeMap",new Map);u(this,"_remoteAudioMuteMap",new Map);u(this,"_mediaTrackMap",new WeakMap);u(this,"_log",B.createLogger({id:`t${++sg}`}));u(this,"_plugins",new Map);u(this,"_networkQuality",null);u(this,"_speakerId");u(this,"_getPCMAbortCtrl");this._room=new e(Z({logger:this._log,frameWorkType:fe.frameWorkType},r)),this._room.videoDecodeFallbackType=r.videoDecodeFallback,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(zd,r.assetsPath),this._use(Qd,r.assetsPath),this._use(Oa,r.assetsPath||nc),this._use(Kd),r.enableSEI&&sa&&this._use(Yd),this._room.on("audio-volume",o=>{!o.find(s=>s.userId==="")&&this._localAudioTrack&&o.push({userId:"",volume:Math.floor(this._localAudioTrack.getAudioLevel()*100)}),r.volumeType===1&&o.forEach(s=>{var d;let n=s.userId===""?this._localAudioTrack:(d=this.room.remotePublishedUserMap.get(s.userId))==null?void 0:d.remoteAudioTrack;n&&(s.volume=n.dbVolume)}),this.emit(se.AUDIO_VOLUME,{result:o.sort((s,n)=>n.volume-s.volume)})}),this._room.videoManager.on("error",o=>{this._log.error(new ae({code:ue.OPERATION_FAILED,extraCode:5504,message:o.message,originError:o}))}),this._listenEvents(),this._initActiveSpeaker(),Zf(this,"trtc")}static create(e){}static _create(e,r){$f();let o=new fe(e,r||{});return Pa.add(o),o}get room(){return this._room}_listenEvents(){Pt(this,this._room).add("peer-join",e=>{let{userId:r}=e;this.emit(se.REMOTE_USER_ENTER,{userId:r})}).add("peer-leave",e=>{this.emit(se.REMOTE_USER_EXIT,{userId:e}),this._remoteAudioVolumeMap.delete(e)}).add("banned",e=>{this._exitRoom().finally(()=>{this.emit(se.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().finally(()=>{this.emit(se.ERROR,ae.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(se.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let r=Ee(Z({},e),{uplinkRTT:Math.min(e.uplinkRTT,Rn),downlinkRTT:Math.min(e.downlinkRTT,Rn)});this.emit(se.NETWORK_QUALITY,r)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(o=>{Pt(o,o).add("player-state-changed",s=>{let n=Ee(Z({},s),{userId:e.userId});o.kind===D.VIDEO&&(n.streamType=Yi(o.streamType)),this.emit(o.kind===D.AUDIO?se.AUDIO_PLAY_STATE_CHANGED:se.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",s=>{s.getCode()===te.PLAY_NOT_ALLOWED&&this.emit(se.AUTOPLAY_FAILED,{userId:o.userId,resume:()=>o.player.resume()})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(o=>{ut(o)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:r})=>{let{userId:o}=r,s=e.audioAvailable,n=e.videoAvailable,{audioAvailable:d,videoAvailable:p}=r;d||this._remoteAudioConfigMap.delete(o),p||this._remoteVideoConfigMap.delete(`${o}_main`),r.hasAuxiliary||this._remoteVideoConfigMap.delete(`${o}_sub`),n!==p&&(p?this._onVideoAvailable({userId:o,streamType:"main"}):this._onVideoUnavailable({userId:o,streamType:"main"}),this.emit(p?se.REMOTE_VIDEO_AVAILABLE:se.REMOTE_VIDEO_UNAVAILABLE,{userId:o,streamType:"main"})),s!==d&&(d?this._onAudioAvailable({userId:o}):this._onAudioUnavailable({userId:o,muteState:r}),this.emit(d?se.REMOTE_AUDIO_AVAILABLE:se.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?se.REMOTE_VIDEO_AVAILABLE:se.REMOTE_VIDEO_UNAVAILABLE,{userId:o,streamType:"sub"}))}).add("sei-message",e=>{this.emit(se.SEI_MESSAGE,Ee(Z({},e),{streamType:Yi(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(se.ERROR,new ae({code:ue.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var s,n,d,p,m,E,_;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)||((d=this._networkQuality)==null?void 0:d.downlinkRTT)||0,Rn),upLoss:((p=this._networkQuality)==null?void 0:p.uplinkLoss)||0,downLoss:((m=this._networkQuality)==null?void 0:m.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((E=e.msg_up_stream_info.msg_audio_status)==null?void 0:E.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((_=e.msg_up_stream_info.msg_audio_status)==null?void 0:_.uint32_audio_level)||0)/ri},video:e.msg_up_stream_info.msg_video_status.filter(b=>r[b.uint32_video_stream_type]).map(b=>({bitrate:(b.uint32_video_codec_bitrate||0)/1e3,width:b.uint32_video_width,height:b.uint32_video_height,frameRate:b.uint32_video_enc_fps,videoType:r[b.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(b=>({userId:b.msg_user_info.str_identifier,audio:{bitrate:(b.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(b.msg_audio_status.uint32_audio_level||0)/ri},video:b.msg_video_status.map(C=>({bitrate:(C.uint32_video_codec_bitrate||0)/1e3,width:C.uint32_video_width,height:C.uint32_video_height,frameRate:C.uint32_video_dec_fps,videoType:r[C.uint32_video_stream_type]}))}))};this.emit(se.STATISTICS,o)}).add("custom-message",e=>{this.emit(se.CUSTOM_MESSAGE,e)}).add("layerData",e=>this.emit(se.LAYER_DATA,e)).add("first-video-frame",e=>{this.emit(se.FIRST_VIDEO_FRAME,Ee(Z({},e),{streamType:Yi(e.streamType)}))}),Pt(this,Et).add("audioInputAdded",e=>{this.emit(se.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(se.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(se.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(se.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>y(this,null,function*(){if(this.emit(se.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),bt&&bt.deviceId===bn){let r=(yield $i()).find(o=>o.deviceId===bn);r&&bt.groupId!==r.groupId&&(bt=r,this.emit(se.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}))}})).add("audioOutputRemoved",e=>y(this,null,function*(){this.emit(se.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let r=(yield $i())[0];if(!r||!bt||bt.groupId===r.groupId)return;let o=bt.deviceId===e.deviceId,s=bt.deviceId===bn&&bt.deviceId===r.deviceId;(o||s)&&(bt=r,this.emit(se.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}))}))}use(e){let r,o;"plugin"in e?(r=e.plugin,o=e.assetsPath):r=e,this._use(r,o||nc)}_use(e,r){if(this._plugins.get(e.Name)){this._log.warn("duplicate install plugin",e.Name);return}let s=new e(Yf.call(this,{TRTC:fe,room:this._room,errorModule:KI,assetsPath:r}));this._plugins.set(e.Name,s),e.autoStart&&this.startPlugin(e.Name)}enterRoom(e){return y(this,null,function*(){var p,m;let{scene:r="rtc",enableAutoPlayDialog:o=!0,autoReceiveAudio:s=!0,autoReceiveVideo:n=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!we(e.proxy)&&e.proxy.turnServer&&((m=(p=this._room).setTurnServer)==null||m.call(p,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=o,this._room.autoReceiveAudio=s,this._room.autoReceiveVideo=n,dt(e.preferHW)&&(this._room.preferHW=e.preferHW),e.playoutDelay&&(this._room.playoutDelay=e.playoutDelay),e.jitterBufferDelay&&(this._room.jitterBufferDelay=e.jitterBufferDelay);let d={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:e.role==="audience"?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language,priority:e.priority,useVp8:e.useVp8};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(d,r,fe.frameWorkType),this._checkTrackToPublish(),Ym.start()})}exitRoom(){return y(this,null,function*(){return yield this._exitRoom()})}switchRole(e,r){return y(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(){ut(this),this.removeAllListeners(),this._room.destroy(),Pa.delete(this),Pa.size===0&&Ym.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),this._plugins.forEach(e=>{var r;return(r=e.destroy)==null?void 0:r.call(e)}),this._plugins.clear(),H.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return y(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 ci(this._room.audioManager),d={},p={muted:!0};s&&($(s.microphoneId)?$(s.audioTrack)||(d.customSource=s.audioTrack):d.deviceId=s.microphoneId,s&&je(s.captureVolume)&&n.setCaptureVolume(s.captureVolume),$(s.profile)||(we(s.profile)?cc[s.profile]&&n.setProfile(cc[s.profile]):n.setProfile(s.profile)),je(s.earMonitorVolume)&&(p.muted=!(s.earMonitorVolume>0),p.volume=s.earMonitorVolume),$(s.echoCancellation)||(n.profile.echoCancellation=s.echoCancellation),$(s.noiseSuppression)||(n.profile.noiseSuppression=s.noiseSuppression),$(s.autoGainControl)||(n.profile.autoGainControl=s.autoGainControl)),n.on("5",m=>{this.emit(se.ERROR,new ae({code:ue.DEVICE_ERROR,extraCode:5309,messageParams:{error:m}}))}),n.on("2",m=>{this.emit(se.DEVICE_CHANGED,{type:"microphone",action:"active",device:m})}),n.on("4",m=>{let E;m.error&&(E=ae.convertFrom(m.error)),this.emit(se.PUBLISH_STATE_CHANGED,Ee(Z({},m),{error:E}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId),yield n.capture(d),$(o)||n.setMute(o),Pt(n,n).add("player-state-changed",m=>{this.emit(se.AUDIO_PLAY_STATE_CHANGED,Ee(Z({},m),{userId:""}))}),this.listeners(se.AUDIO_FRAME).length>0&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM(m=>{this.emit(fe.EVENT.AUDIO_FRAME,{data:m})})),this._getPCMAbortCtrl&&n.on("input-media-track-changed",()=>{this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("inputMediaTrackChanged"),this._getPCMAbortCtrl=this._room.audioManager.getPCM(m=>{this.emit(fe.EVENT.AUDIO_FRAME,{data:m})}))}),r&&this._room.isJoined&&this._room.publish(n).catch(()=>{}),this._localAudioTrack=n,this._localAudioConfig=Ee(Z({},e),{publish:r}),yield this._updateAudioPlayOption({playOption:p,track:n})})}updateLocalAudio(e){return y(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):$(s.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(s.audioTrack)),$(s.captureVolume)||this._localAudioTrack.setCaptureVolume(s.captureVolume),$(s.earMonitorVolume)||(n.muted=!(s.earMonitorVolume>0),n.volume=s.earMonitorVolume),yield this._localAudioTrack.update3A(s)),this._room.isJoined&&!$(r)&&(r&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!r&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),$(o)||this._localAudioTrack.setMute(o),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),kr(this._localAudioConfig,e)})}stopLocalAudio(){return y(this,null,function*(){this._localAudioTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),ut(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null,this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("stopLocalAudio"),delete this._getPCMAbortCtrl))})}startLocalVideo(){return y(this,arguments,function*(e={publish:!0,view:null}){if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:r,publish:o=!0,mute:s,option:n}=e,d=new Sr(this._room.videoManager),p={},m={};n&&(n.cameraId?p.deviceId=n.cameraId:$(n.useFrontCamera)?$(n.videoTrack)||(p.customSource=n.videoTrack):p.facingMode=n.useFrontCamera?D.FACING_MODE_USER:D.FACING_MODE_ENVIRONMENT,n.qosPreference&&(p.contentHint=Na(n.qosPreference)),$(n.profile)||(we(n.profile)?Or[n.profile]&&d.setProfile(Or[n.profile]):d.setProfile(n.profile)),$(n.fillMode)||(m.objectFit=n.fillMode),$(n.mirror)||(m.mirror=n.mirror),$(n.small)||(ra()?we(n.small)?d.small=Or[n.small]:n.small===!0?d.small=Or["120p"]:d.small=n.small:this._log.warn("small stream is not supported"))),d.once("first-video-frame",E=>{this.emit(se.FIRST_VIDEO_FRAME,Ee(Z({},E),{streamType:Yi(E.streamType)}))}),d.on("5",E=>{this.emit(se.ERROR,new ae({code:ue.DEVICE_ERROR,extraCode:5308,messageParams:{error:E}}))}),d.on("2",E=>{this.emit(se.DEVICE_CHANGED,{type:"camera",action:"active",device:E})}),d.on("4",E=>{let _;E.error&&(_=ae.convertFrom(E.error)),this.emit(se.PUBLISH_STATE_CHANGED,Ee(Z({},E),{error:_}))}),this._listenOutputTrackChanged(d),yield d.capture(p),$(s)||(yield d.setMute(s)),Pt(d,d).add("player-state-changed",E=>{this.emit(se.VIDEO_PLAY_STATE_CHANGED,Ee(Z({},E),{userId:"",streamType:"main"}))}),o&&this._room.isJoined&&this._room.publish(d).catch(()=>{}),this._localVideoTrack=d,this._localVideoConfig=Ee(Z({},e),{view:r,publish:o}),yield this._updateVideoPlayOption({view:r,playOption:m,track:d})})}updateLocalVideo(e){return y(this,null,function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:r,publish:o,mute:s,option:n}=e,d={};if(n)if($(n.profile)||(we(n.profile)?Or[n.profile]&&this._localVideoTrack.setProfile(Or[n.profile]):this._localVideoTrack.setProfile(n.profile),(!n.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(n.cameraId))&&$(n.useFrontCamera)&&this._localVideoTrack.applyProfile()),n.cameraId?yield this._localVideoTrack.switchDevice(n.cameraId):$(n.useFrontCamera)?$(n.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(n.videoTrack)):yield this._localVideoTrack.switchDevice(n.useFrontCamera?D.FACING_MODE_USER:D.FACING_MODE_ENVIRONMENT),$(n.fillMode)||(d.objectFit=n.fillMode),$(n.mirror)||(d.mirror=n.mirror),n.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(Na(n.qosPreference)),n.small){let p=!this._localVideoTrack.small;ra()?(n.small===!0?this._localVideoTrack.small=Or["120p"]:we(n.small)?this._localVideoTrack.small=Or[n.small]:this._localVideoTrack.small=n.small,this._room.videoManager.update(),p&&this._room.enableSmall(!0)):this._log.warn("small stream is not supported")}else n.small===!1&&this._localVideoTrack.small&&(delete this._localVideoTrack.small,this._room.videoManager.update(),this._room.enableSmall(!1));this._room.isJoined&&!$(o)&&(o&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._localVideoConfig.publish&&!o&&this._room.unpublish(this._localVideoTrack).catch(()=>{})),$(s)||(yield this._localVideoTrack.setMute(s)),yield this._updateVideoPlayOption({view:r,playOption:d,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),kr(this._localVideoConfig,e)})}stopLocalVideo(){return y(this,null,function*(){this._localVideoTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),ut(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return y(this,arguments,function*(e={publish:!0,view:null}){if(this._localScreenTrack){this._log.warn("screen share is already started");return}let{view:r=null,publish:o=!0,option:s}=e,n=new Hi(this._room.videoManager);n.on("4",_=>{let b;_.error&&(b=ae.convertFrom(_.error)),this.emit(se.PUBLISH_STATE_CHANGED,Ee(Z({},_),{error:b}))}),n.once("first-video-frame",_=>{this.emit(se.FIRST_VIDEO_FRAME,Ee(Z({},_),{streamType:Yi(_.streamType)}))}),this._listenOutputTrackChanged(n),e.streamType==="main"&&(n.mediaType=4);let d=null,p={},m={};s&&($(s.profile)||(we(s.profile)?dc[s.profile]&&n.setProfile(dc[s.profile]):n.setProfile(s.profile)),s.systemAudio&&(p.systemAudio=!0,p.echoCancellation=s.echoCancellation,p.noiseSuppression=s.noiseSuppression,p.autoGainControl=s.autoGainControl),$(s.fillMode)||(m.objectFit=s.fillMode),s.videoTrack&&(p.videoTrack=s.videoTrack),s.audioTrack&&(p.audioTrack=s.audioTrack),s.captureElement&&(p.captureElement=s.captureElement),s.preferDisplaySurface&&(p.preferDisplaySurface=s.preferDisplaySurface),s.qosPreference&&(p.contentHint=Na(s.qosPreference)));let E=yield n.capture(p);if(n.mediaTrack.addEventListener(D.ENDED,()=>{this._stopScreenShare(),this.emit(se.SCREEN_SHARE_STOPPED)}),E.getAudioTracks()[0]&&(d=new Lo(this._room.audioManager),yield d.setInputMediaStreamTrack(E.getAudioTracks()[0]),this._speakerId&&d.setAudioOutput(this._speakerId)),Pt(n,n).add("player-state-changed",_=>{this.emit(se.VIDEO_PLAY_STATE_CHANGED,Ee(Z({},_),{userId:"",streamType:"sub"}))}),o&&this._room.isJoined){let _=[n];d&&_.push(d),this._room.publish(..._).catch(()=>{})}this._localScreenTrack=n,this._localScreenAudioTrack=d,this._localScreenConfig=Ee(Z({},e),{view:r,publish:o}),yield this._updateVideoPlayOption({view:r,playOption:m,track:n})})}updateScreenShare(e){return y(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:r,publish:o,option:s}=e,n={};if(s&&($(s.fillMode)||(n.objectFit=s.fillMode),s.qosPreference)){let d=Na(s.qosPreference);this._localScreenTrack.setContentHint(d)}this._room.isJoined&&!$(o)&&(o&&!this._localScreenConfig.publish&&(this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch(()=>{})),this._localScreenConfig.publish&&!o&&(this._room.unpublish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.unpublish(this._localScreenAudioTrack).catch(()=>{}))),yield this._updateVideoPlayOption({view:r,playOption:n,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),kr(this._localScreenConfig,e)})}stopScreenShare(){return y(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return y(this,null,function*(){let{view:r,userId:o,streamType:s,option:n}=e,d=`${o}_${s}`;if(this._remoteVideoConfigMap.has(d)){this._log.warn(`remote video has already started. userId:${o}, streamType:${s}`);return}let p=this._room.remotePublishedUserMap.get(o);if(!p)return;let m={},E=s==="main"?p.remoteVideoTrack:p.remoteAuxiliaryTrack;this._listenOutputTrackChanged(E),n&&($(n.fillMode)||(m.objectFit=n.fillMode),$(n.mirror)||(m.mirror=n.mirror),m.canvasRender=n.canvasRender,s==="main"&&!$(n.small)&&(!p.remoteVideoTrack.isSubscribing&&!p.remoteVideoTrack.isSubscribed&&p.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,E.user))),yield this._room.subscribe(E),yield this._enableVideoDecodeFallback(E,s),yield this._updateVideoPlayOption({view:r,playOption:m,track:E}),this._emitTrackEvent(E),this._remoteVideoConfigMap.set(d,{config:e}),n&&!$(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:E,view:r,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:n==null?void 0:n.viewRoot})})}updateRemoteVideo(e){return y(this,null,function*(){var P,J;let{view:r,userId:o,streamType:s,option:n}=e,d=`${o}_${s}`,p=this._remoteVideoConfigMap.get(d);if(!p||!this._room.remotePublishedUserMap.has(o))return;let m={};n&&($(n.fillMode)||(m.objectFit=n.fillMode),$(n.mirror)||(m.mirror=n.mirror));let E=null,_=this._room.remotePublishedUserMap.get(o);if(s==="main"&&(_!=null&&_.muteState.hasVideo)&&(E=_.remoteVideoTrack),s==="sub"&&(_!=null&&_.muteState.hasAuxiliary)&&(E=_.remoteAuxiliaryTrack),!E)return;let{config:b}=p;s==="main"&&n&&!$(n.small)&&this._room.changeType(n.small,E.user),yield this._updateVideoPlayOption({view:r,playOption:m,track:E,prevConfig:b}),kr(b,e);let C=$(n==null?void 0:n.receiveWhenViewVisible)?(P=b.option)==null?void 0:P.receiveWhenViewVisible:n.receiveWhenViewVisible,k=$(r)?b.view:r,x=$(n==null?void 0:n.viewRoot)?(J=b.option)==null?void 0:J.viewRoot:n.viewRoot;this._observeView({remoteTrack:E,view:k,receiveWhenViewVisible:C,viewRoot:x})})}stopRemoteVideo(e){return y(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,r=!0){return y(this,null,function*(){let o=[],s=this._room.remotePublishedUserMap.get(e.userId);if(s){let{muteState:d,remoteVideoTrack:p,remoteAuxiliaryTrack:m}=s;e.streamType==="main"&&(p.stop(),d.hasVideo&&o.push(p)),e.streamType==="sub"&&(m.stop(),d.hasAuxiliary&&o.push(m))}for(let d of o)r&&(yield this._room.unsubscribe(d),this._mediaTrackMap.delete(d.outMediaTrack));let n=this._remoteVideoConfigMap.get(`${e.userId}_${e.streamType}`);n&&n.observer&&n.observer.disconnect(),this._remoteVideoConfigMap.delete(`${e.userId}_${e.streamType}`)})}muteRemoteAudio(e,r){return y(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 this._remoteAudioMuteMap.delete(e),o}})}setRemoteAudioVolume(e,r){if(e==="*"){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 y(this,null,function*(){return e.start(r)})}updatePlugin(e,r){return y(this,null,function*(){return e.update(r)})}stopPlugin(e,r){return y(this,null,function*(){return e.stop(r)})}enableAudioVolumeEvaluation(e=2e3,r=!1){this._room.enableAudioVolumeEvaluation(e,r)}on(e,r,o){return this.listeners(e).includes(r)?this:(this._log.debug("on",e),super.on(e,r,o),this._eventListened.add(e),e===fe.EVENT.AUDIO_FRAME&&!this._getPCMAbortCtrl&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM(s=>{this.emit(fe.EVENT.AUDIO_FRAME,{data:s})}),this._localAudioTrack&&this._localAudioTrack.on("input-media-track-changed",()=>{this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("inputMediaTrackChanged"),this._getPCMAbortCtrl=this._room.audioManager.getPCM(s=>{this.emit(fe.EVENT.AUDIO_FRAME,{data:s})}))})),this)}emit(e,...r){try{zf.has(e)&&this._log.debug(`emit ${e} ${JSON.stringify(r)}`)}catch(o){}return super.emit(e,...r)}off(e,r,o){var s,n;return this._log.debug("off",e),e==="*"?(this._eventListened.clear(),this.removeAllListeners(),(s=this._getPCMAbortCtrl)==null||s.abort("off"),delete this._getPCMAbortCtrl):(super.off(e,r,o),e===fe.EVENT.AUDIO_FRAME&&((n=this._getPCMAbortCtrl)==null||n.abort("off"),delete this._getPCMAbortCtrl)),this}getAudioTrack(e={userId:"",streamType:"main"}){let r,o=null,s="main",n=!1;if(we(e)?r=e:(r=e.userId,n=e.processed===!0,e.streamType&&(s=e.streamType)),r){let d=this._room.remotePublishedUserMap.get(r);d&&(o=d.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 d=this._room.remotePublishedUserMap.get(r);d&&(n=o==="main"?d.remoteVideoTrack:d.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 y(this,null,function*(){(yield $i()).forEach(o=>{o.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(se.DEVICE_CHANGED,{type:"speaker",action:"active",device:o}),bt=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: https://web.sdk.qcloud.com/trtc/webrtc/v5/doc/en/TRTC.html#.setCurrentSpeaker')})}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return y(this,null,function*(){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;this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId);try{let d=this._remoteAudioVolumeMap.get(r),p=je(d)?d:100;s.volume=p,this._remoteAudioConfigMap.set(r,e),yield this._room.subscribe(n),ve(Ne(n,"decode-failed"),Qe(Ne(n,ne.INIT)),Ve(()=>{this.startPlugin(Oa.Name,{track:n,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:s,track:n})}catch(d){throw this._remoteAudioConfigMap.delete(r),d}this._emitTrackEvent(n)})}_stopRemoteAudio(e,r=!0){return y(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}`)})}_enableVideoDecodeFallback(e,r){let o=this._room.videoDecodeFallbackType;!o||!this._plugins.has("VideoDecoderPlugin")||(this._log.debug("remote video will fall back when decode failed"),ve(Ne(e,"decode-failed"),Qe(Ne(e,ne.INIT)),Ia(()=>{this.startPlugin("VideoDecoderPlugin",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:o})}),Ho(Ne(e,"decode-downgrade-state-changed")),Ve(s=>{this.emit(se.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,Ee(Z({},s),{streamType:r,userId:e.userId}))},s=>{this._log.error("fallback",s)},()=>this._log.info("fallback complete"))))}_updateVideoPlayOption(n){return y(this,arguments,function*({view:e,playOption:r,track:o,prevConfig:s}){if(o.setMirror(r.mirror),$(e)&&s&&s.view&&!hs(r)){let d=gs(s.view);d.length>0&&(yield o.play(d,r))}if(!$(e)){let d=gs(e);d.length>0?yield o.play(d,r):o.stop()}})}_updateAudioPlayOption(s){return y(this,arguments,function*({playOption:e={},track:r,prevConfig:o}){if(!r.isPlayCalled)try{yield r.play(null,e)}catch(n){}$(e.muted)||r.setPlayerMute(e.muted),$(e.volume)||r.setAudioVolume(e.volume/100)})}_listenOutputTrackChanged(e){e.listeners("output-media-track-changed").length===0&&e.on("output-media-track-changed",()=>this._emitTrackEvent(e,!1))}_emitTrackEvent(e,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(se.TRACK,{userId:o,streamType:Yi(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)),e.length!==0)return this._room.publish(...e).catch(()=>{})}_observeView({remoteTrack:e,view:r,receiveWhenViewVisible:o=!1,viewRoot:s}){if($(r))return;let n=this._remoteVideoConfigMap.get(`${e.userId}_${Yi(e.streamType)}`);if(!n)return;let d=n.observer||void 0;if(r===null||st(r)&&r.length===0||!o){d==null||d.disconnect(),e.isSubscribed||this._room.subscribe(e).catch(()=>{});return}let m=n.visibleViewMap||new Map,E=-1;(!d||d.root!==s)&&(d==null||d.disconnect(),m.clear(),d=new IntersectionObserver(b=>{b.forEach(C=>{m.set(C.target,C.isIntersecting)}),clearTimeout(E),E=window.setTimeout(()=>{[...m.values()].find(k=>k)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:s}));let _=new Set(gs(r));m.forEach((b,C)=>{_.has(C)||(d.unobserve(C),m.delete(C))}),_.forEach(b=>{m.set(b,!0),d.observe(b)}),d.takeRecords().forEach(b=>{m.set(b.target,b.isIntersecting)}),n.visibleViewMap=m,n.observer=d}_exitRoom(){return y(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(e=>{this._stopRemoteAudio({userId:e}).catch()}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let 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(),this._remoteAudioVolumeMap.clear(),Kf(this),this._room.remotePublishedUserMap.forEach(e=>{ut(e.remoteAudioTrack),ut(e.remoteVideoTrack),ut(e.remoteAuxiliaryTrack)})})}_stopScreenShare(){return y(this,null,function*(){var e;if(this._localScreenTrack){if(this._room.isJoined){let r=[this._localScreenTrack];this._localScreenAudioTrack&&r.push(this._localScreenAudioTrack),yield(e=this._room)==null?void 0:e.unpublish(...r).catch(()=>{})}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),ut(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_onLocalTrackCaptured({track:e}){e.kind==="audio"&&(!bt||Bs(bt))&&(this._initActiveSpeaker(),H.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return y(this,null,function*(){if(bt&&!Bs(bt))this.emit(se.DEVICE_CHANGED,{type:"speaker",action:"active",device:bt});else{let e=yield $i();e[0]&&!Bs(e[0])?(bt=e[0],this.emit(se.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):H.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:Ee(Z({seiPayloadType:243},r),{small:!!((s=this._localVideoTrack)!=null&&s.small)})}),Y.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var r,o;(o=(r=this._room).sendCustomMessage)==null||o.call(r,e),Y.addCount({key:500001,useUV:!0})}static setLogLevel(e,r){B.setLogLevel(e),$(r)||(r?B.enableUploadLog():B.disableUploadLog())}static isSupported(){return Kc()}static getCameraList(e=!0){return Kt(e)}static getMicrophoneList(e=!0){return Jt(e)}static getSpeakerList(e=!0){return $i(e)}static setCurrentSpeaker(e){return y(this,null,function*(){if(gt&&(e===sr.SPEAKER||e===sr.HEADSET)){let o=yield fe.getMicrophoneList(),s="";if(o.forEach(n=>{n.label===e&&(s=n.deviceId)}),!s)return;Pa.forEach(n=>y(this,null,function*(){n._localAudioTrack&&(yield n.updateLocalAudio({option:{microphoneId:s}}))}));return}(yield $i()).forEach(o=>{o.deviceId===e&&(Pa.forEach(s=>{s._setCurrentSpeaker(e),s.emit(se.DEVICE_CHANGED,{type:"speaker",action:"active",device:o})}),bt=o)})})}static _addKVStat({type:e,key:r,value:o,base:s,useUV:n,version:d}){switch(d&&(No.version=d),e){case"count":No.addCount({key:r,useUV:n});break;case"enum":No.addEnum({key:r,value:o,useUV:n});break;case"number":No.addNumber({key:r,value:o,split:s});break}}};u(fe,"_loggerManager",B),u(fe,"EVENT",se),u(fe,"ERROR_CODE",ue),u(fe,"TYPE",sr),u(fe,"frameWorkType",30),X([Ye({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"}})})],fe.prototype,"use",1),X([Ut(At.TRTC.enterRoom),Xi("room",([e],[r])=>(e.roomId||e.strRoomId)===(r.roomId||r.strRoomId)&&e.userId===r.userId&&e.sdkAppId===r.sdkAppId),Me(e=>function(r){return this._log.setUserId(r.userId),this._log.setSdkAppId(r.sdkAppId),e.call(this,r)}),Ye()],fe.prototype,"enterRoom",1),X([Ye()],fe.prototype,"exitRoom",1),X([Ut(At.TRTC.switchRole),qo("room",{merge:(e,r)=>r}),Ye()],fe.prototype,"switchRole",1),X([Ye()],fe.prototype,"destroy",1),X([Ut(At.TRTC.startLocalAudio),Xi("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)}),Ye()],fe.prototype,"startLocalAudio",1),X([Ut(At.TRTC.updateLocalAudio),qo("audio",{debounce:{delay:200,getKey:()=>`${sg}-localAudio`,isNeedToDebounce:e=>{var r;return!$((r=e.option)==null?void 0:r.captureVolume)}}}),Ye()],fe.prototype,"updateLocalAudio",1),X([Qi("audio"),Ye()],fe.prototype,"stopLocalAudio",1),X([Ut(At.TRTC.startLocalVideo),Xi("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)}),Ye()],fe.prototype,"startLocalVideo",1),X([Ut(At.TRTC.updateLocalVideo),qo("video"),Ye()],fe.prototype,"updateLocalVideo",1),X([Qi("video"),Ye()],fe.prototype,"stopLocalVideo",1),X([Ut(At.TRTC.startScreenShare),Xi("screen",()=>!0),Ye()],fe.prototype,"startScreenShare",1),X([Ut(At.TRTC.updateScreenShare),qo("screen"),Ye()],fe.prototype,"updateScreenShare",1),X([Ye()],fe.prototype,"stopScreenShare",1),X([Ut(At.TRTC.startRemoteVideo),Xi(e=>`v${e.userId}${e.streamType}`,()=>!0),Ye({getRemoteId:e=>`${e.userId}_${e.streamType}`})],fe.prototype,"startRemoteVideo",1),X([Ut(At.TRTC.updateRemoteVideo),qo(e=>`v${e.userId}${e.streamType}`),Ye({getRemoteId:e=>`${e.userId}_${e.streamType}`})],fe.prototype,"updateRemoteVideo",1),X([Ut(At.TRTC.stopRemoteVideo),Me(e=>function(r){return y(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)})}),Ye({getRemoteId:e=>`${e.userId}_${e.streamType}`})],fe.prototype,"stopRemoteVideo",1),X([Qi(e=>`v${e.userId}${e.streamType}`)],fe.prototype,"_stopRemoteVideo",1),X([Ut(...At.TRTC.muteRemoteAudio),Ye({getRemoteId:e=>e})],fe.prototype,"muteRemoteAudio",1),X([Jm(...At.TRTC.setRemoteAudioVolume),eg(200,e=>e),Ye({getRemoteId:e=>e})],fe.prototype,"setRemoteAudioVolume",1),X([qd("start"),Fi(e=>{var r;return(r=e.afterStart)==null?void 0:r.call(e)}),Xi((e,r)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(r)),Ye({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>yl[e.getName()],ignoreLog:e=>e.getName()==="Debug"})],fe.prototype,"startPlugin",1),X([qd("update"),qo((e,r)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(r)),Ye({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Al[e.getName()]})],fe.prototype,"updatePlugin",1),X([qd("stop"),Qi((e,r)=>{if(e.disableRandomCall)return null;let o=e.getGroup(r),s=e.getAlias();return o==="*"?new RegExp(`${s}.*`):s+o}),Ye({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>bl[e.getName()]})],fe.prototype,"stopPlugin",1),X([Jm(...At.TRTC.enableAudioVolumeEvaluation)],fe.prototype,"enableAudioVolumeEvaluation",1),X([Ye()],fe.prototype,"getVideoSnapshot",1),X([Ye()],fe.prototype,"_setCurrentSpeaker",1),X([Xi(e=>`a${e.userId}`,()=>!0)],fe.prototype,"_startRemoteAudio",1),X([Me(e=>function(r){return y(this,null,function*(){return r.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(o=>this._stopRemoteAudio(Ee(Z({},r),{userId:o.userId})).catch(()=>{}))):e.call(this,r)})}),Qi(e=>`a${e.userId}`)],fe.prototype,"_stopRemoteAudio",1),X([Qi("room")],fe.prototype,"_exitRoom",1),X([Qi("screen")],fe.prototype,"_stopScreenShare",1),X([Ut(...At.TRTC.sendSEIMessage),$m({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...e)=>e[0].byteLength})],fe.prototype,"sendSEIMessage",1),X([Ut(At.TRTC.sendCustomMessage),$m({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],fe.prototype,"sendCustomMessage",1),X([Ut(At.TRTC.create)],fe,"_create",1);var ip=fe,Ks=ip;var tu=class{constructor(t,e){u(this,"_flag");u(this,"terminalType");u(this,"userId");u(this,"tinyId");u(this,"role");u(this,"remoteAudioTrack");u(this,"remoteVideoTrack");u(this,"remoteAuxiliaryTrack");this.userId=e.userId||"",this.tinyId=e.tinyId||"",this.role=e.role||"audience",this.terminalType=e.terminalType,this.remoteAudioTrack=new Uo(t,this),this.remoteVideoTrack=new qi(t,this),this.remoteAuxiliaryTrack=new xd(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 Mn(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 op=class{constructor(){u(this,"_set",new Set);H.on(L.LEAVE_SUCCESS,this.delete,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))}};function eS(){return y(this,null,function*(){let i,t;try{let _=yield Jt();i=_&&_.length}catch(_){}try{let _=yield Kt();t=_&&_.length}catch(_){}let e={microphone:i,camera:t},{isH264EncodeSupported:r,isVp8EncodeSupported:o,isH264DecodeSupported:s,isVp8DecodeSupported:n}=this.checkSystemResult.detail,d=Vi.basis(),p={webRTC:d.isWebRTCSupported,getUserMedia:d.isGetUserMediaSupported,webSocket:d.isWebSocketsSupported,screenShare:d.isScreenShareSupported,webAudio:d.isWebAudioSupported,h264Encode:r,h264Decode:s,vp8Encode:o,vp8Decode:n},m={browser:d.browser,os:d.os,trtc:p,devices:e},E={isWebCodecSupported:d.isWebCodecSupported,isMediaSessionSupported:d.isMediaSessionSupported,isWebTransportSupported:d.isWebTransportSupported};$e.uploadEvent({log:`trtcstats-${JSON.stringify(m)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(m)}`),$e.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(E)}`,userId:this.userId})})}function ag(){return Me(i=>{let t=new op;return function(e,r,o){return y(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 he({code:te.INVALID_OPERATION,message:at({key:nt.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:s,sdkAppId:this.sdkAppId,room:this}))throw new he({code:te.INVALID_OPERATION,message:at({key:nt.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}`),H.emit(L.JOIN_START,{room:this,roomId:s,params:e});let n=Lr.getEnv();n||(n=Jr.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(uc.OLD_CLOUD_LADDER)?n=Jr.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(uc.WEBRTC)&&(n=Jr.WEBRTC))),$e.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:s}),Vi.checkSystemRequirementsInternal().then(d=>{this.checkSystemResult=d,eS.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Lr.getEnv()&&(yield this.schedule(e,o));let d=yield i.call(this,e,r,o);return this.roomId=s,this._joinedTimestamp=Lr.performanceNow(),H.emit(L.JOIN_SUCCESS,{room:this}),o===30&&!e.component&&$e.uploadEvent({log:`stat-conv-${Number(Tr)}-${location.hostname}`,userId:this.userId}),d}catch(d){throw t.delete({room:this,roomId:s}),H.emit(L.JOIN_FAILED,{room:this,error:d}),d}})}})}var cg=()=>Me(i=>function(...t){return y(this,null,function*(){H.emit(L.LEAVE_START,{room:this}),yield i.call(this,...t),H.emit(L.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function dg(){return Me(i=>function(...t){return y(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(t=t.filter(r=>r.outMediaTrack&&r.state==="capture"),!t.length))return;H.emit("61",{room:this});let e=i.apply(this,t);return t.forEach(r=>r.publish(this,e)),e})})}function ug(){return Me(i=>function(...t){let e=i.apply(this,t);return t.forEach(r=>r.unpublish()),e})}function lg(){return Me(i=>function(...t){let e=i.apply(this,t);return t.forEach(r=>!r.isSubscribed&&r.subscribe(e)),e})}function tS({fn:i,context:t}){return function(...e){try{let r=i.apply(t,e);return Mi(r)?r.catch(o=>B.error(`${i.name}() error observed ${o}`)):r}catch(r){B.error(`${i.name}() error observed ${r}`)}}}var ru=class{constructor(t){u(this,"_frameWorkType");u(this,"_component");u(this,"_language");u(this,"connectionType");u(this,"_room");u(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0});u(this,"_keyPrefix");u(this,"_log");u(this,"_intervalId");u(this,"_firstPublishedUserList");u(this,"_networkQuality");u(this,"_basicInfo");u(this,"_pathJoinRoom");u(this,"_pathLeaveRoom");u(this,"_pathMainVideoMap");u(this,"_pathMainAudioMap");u(this,"_pathAuxiliaryMap");u(this,"_remoteStreamStatMap");u(this,"_localStreamStat");u(this,"_eventMap",new Map);u(this,"_captureCostSum",0);u(this,"_captureCostCount",0);u(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=B.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(e=>{e.startsWith("handle")&&ze(this[e])&&(this[e]=tS({fn:this[e],context:this}))}),this.initData(),this.installEvents()}initData(){this._firstPublishedUserList=[],this._networkQuality={totalUplinkRTT:0,totalUplinkLoss:0,count:0,totalDownlinkRTTAndLossMap:new Map},this._basicInfo={string_sdk_version:rt,uint32_os_type:15,string_device_name:"",string_http_user_agent:navigator.userAgent,string_os_version:"",uint32_avg_rtt:0,uint32_avg_up_loss:0,uint32_scene:this._room.scene==="live"?1:0,uint32_joining_duration:0,uint32_networkType:0,uint32_framework:this._frameWorkType,uint32_component:this._component,uint32_connection_type:this.connectionType,uint32_caller_coding_language:this._language,string_domain:location.hostname},this._pathJoinRoom={uint64_start_time:0,uint64_send_request_acc_ip_cmd_start_time:0,uint64_send_request_acc_ip_cmd_end_time:0,uint64_send_request_enter_room_cmd_start_time:0,uint64_send_request_enter_room_cmd_end_time:0,uint64_send_first_video_frame_time:0,uint64_recv_userlist_time:0,uint64_end_time:0,int32_send_request_acc_ip_cmd_ret:0,int32_send_request_enter_room_cmd_ret:0,int32_end_ret:0},this._pathLeaveRoom={uint64_start_time:0,uint64_send_request_exit_room_cmd_start_time:0,uint64_send_request_exit_room_cmd_end_time:0,uint64_end_time:0,int32_send_request_exit_room_cmd_ret:0,int32_end_ret:0},this._localStreamStat={totalVideoBitrate:0,totalVideoFPS:0,totalVideoHeight:0,totalVideoWidth:0,totalAudioLevel:0,videoCount:0,audioLevelCount:0,publishStartTime:0,statsToReport:{uint32_audio_capture_db:0,uint32_video_big_capture_fps:0,uint32_video_big_bitrate:0,uint32_video_big_resolution:0}},this._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,qn().then(t=>{this._basicInfo.string_os_version=So(),t?this._basicInfo.string_device_name=t.mobile?t.model:this._basicInfo.string_os_version:this._basicInfo.string_device_name=this._basicInfo.string_os_version})}addEvent(t,e){return this._eventMap.set(t,e),H.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(L.JOIN_START,this.handleJoinStart).addEvent(L.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(L.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(L.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(L.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(L.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(L.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(L.JOIN_FAILED,this.handleJoinFailed).addEvent(L.LEAVE_START,this.handleLeaveStart).addEvent(L.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(L.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(L.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(L.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(L.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(L.PUBLISH_START,this.handlePublishStart).addEvent(L.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(L.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(L.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(L.PLAY_TRACK_START,this.handlePlayStart).addEvent(L.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(L.PLAYER_STATE_CHANGED,({track:t,state:e,type:r})=>{!t.isRemote||!this.hitTest(t.room)||e==="PLAYING"&&(r===D.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))}).addEvent(L.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(L.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(L.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(L.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,d=r.hasAuxiliary;!o&&n&&this.handleRemoteStreamAdded(r.userId,"main"),!s&&d&&this.handleRemoteStreamAdded(r.userId,"auxiliary")}).addEvent(L.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)=>H.off(e,t)),this._eventMap.clear()}destroy(){this.uninstallEvents(),St.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&&($(t.params.frameWorkType)||(this._frameWorkType=t.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),$(t.params.component)||(this._component=t.params.component,this._basicInfo.uint32_component=this._component),$(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:d,request:p,response:m}=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=d,this._pathJoinRoom.int32_schedule_request=p,this._pathJoinRoom.int32_schedule_response=m}}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 he?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){this.hitTest(t.room)&&this._pathLeaveRoom.uint64_end_time===0&&(this._pathLeaveRoom.uint64_end_time=Date.now(),this._pathJoinRoom.uint64_end_time!==0?this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time:this._log.warn("pathJoinRoom endTime is 0"),this.report())}handleLeaveSendCMD(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())}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:Ee(Z({},rS),{msg_user_info:new xa({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:d}=e,p=new xa({userId:s,tinyId:n,role:d==="anchor"?20:21}),m=Date.now(),E=`${s}_${r}`,_=this._remoteStreamStatMap.get(E);_&&_.subscribeStartTime===0&&(_.subscribeStartTime=m),r==="main"?(e.muteState.hasVideo&&(o.video||o.smallVideo)&&!this._pathMainVideoMap.has(E)&&this._pathMainVideoMap.set(E,{statsToReport:{msg_user_info:p,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:s,sendSubscribeCMDTime:m}),e.muteState.hasAudio&&o.audio&&!this._pathMainAudioMap.has(E)&&this._pathMainAudioMap.set(E,{statsToReport:{msg_user_info:p,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:s,sendSubscribeCMDTime:m})):e.muteState.hasAuxiliary&&o.auxiliary&&!this._pathAuxiliaryMap.has(E)&&this._pathAuxiliaryMap.set(E,{sendSubscribeCMDTime:m})}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 d=r-this._pathJoinRoom.uint64_start_time;n.uint32_video_render_first=d,Y.addNumber({key:516820,value:d})}}(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 d=this._networkQuality.totalDownlinkRTTAndLossMap.get(o);if(d)d.totalRTT+=e,d.totalLoss+=r,s&&(d.totalVideoDelay=(d.totalVideoDelay||0)+s,d.videoDelayCount=(d.videoDelayCount||0)+1),n&&(d.totalAudioDelay=(d.totalAudioDelay||0)+n,d.audioDelayCount=(d.audioDelayCount||0)+1),d.count++;else{let p,m,E,_;s&&(m=s,E=1),n&&(p=n,_=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(o,{totalRTT:e,totalLoss:r,count:1,totalAudioDelay:p,totalVideoDelay:m,audioDelayCount:_,videoDelayCount:E})}}))}handleHeartbeatStats(t){if(this.hitTest(t.room)){let{msg_device_info:e,msg_up_stream_info:r,msg_down_stream_info:o}=t.report;if(r.msg_video_status[0]){let{uint32_video_codec_bitrate:s,uint32_video_enc_fps:n,uint32_video_width:d,uint32_video_height:p}=r.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=s,this._localStreamStat.totalVideoFPS+=n,this._localStreamStat.totalVideoWidth+=d,this._localStreamStat.totalVideoHeight+=p,this._localStreamStat.videoCount++}if(r.msg_audio_status){let{uint32_audio_level:s}=r.msg_audio_status;Math.floor(s/ri*100)>0&&(this._localStreamStat.totalAudioLevel+=s/ri,this._localStreamStat.audioLevelCount++)}o.forEach(s=>{let{msg_user_info:n,msg_audio_status:d,msg_video_status:p}=s,m=n.str_identifier,E=this._room.remotePublishedUserMap.get(m);if(p.forEach(_=>{let b=_.uint32_video_stream_type===2,C=_.uint32_video_stream_type===7,k=`${m}_${b?"main":"auxiliary"}`,x=this._remoteStreamStatMap.get(k);if(x&&(b&&(E!=null&&E.remoteVideoTrack.isSubscribed)||C&&(E!=null&&E.remoteAuxiliaryTrack))){x.totalVideoFPS+=_.uint32_video_receive_fps,x.totalVideoBitrate+=_.uint32_video_codec_bitrate,x.videoCount++,x.statsToReport.uint32_video_width===0&&(x.statsToReport.uint32_video_width=_.uint32_video_width),x.statsToReport.uint32_video_height===0&&(x.statsToReport.uint32_video_height=_.uint32_video_height);let P=b?E.remoteVideoTrack:E.remoteAuxiliaryTrack;P.stat.jitterBufferDelay&&(x.videoJitterBufferDelay=P.stat.jitterBufferDelay),P.stat.framesReceived&&(x.statsToReport.uint32_video_consume_render_rate=Math.floor(P.stat.framesDecoded/P.stat.framesReceived*_n(10,6)))}}),!hs(d)){let _=`${m}_main`,b=this._remoteStreamStatMap.get(_);this._remoteStreamStatMap.has(_)&&b&&E!=null&&E.remoteAudioTrack.isSubscribed&&(b.totalAudioBitrate+=d.uint32_audio_codec_bitrate,b.audioCount++,E.remoteAudioTrack.stat.jitterBufferDelay&&(b.audioJitterBufferDelay=E.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(d.uint32_audio_level/ri*100)>0&&(b.totalAudioLevel+=d.uint32_audio_level/ri,b.audioLevelCount++))}}),e.uint32_audio_capture_cost&&(this._captureCostSum+=e.uint32_audio_capture_cost,this._captureCostCount+=1,this._captureCostCount>=100&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0))}}handlePublishStart({room: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 he?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&us)>=0}hasAudioFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&ls)>=0}hasAuxFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&An)>=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:E,count:_,audioDelayCount:b,videoDelayCount:C,totalAudioDelay:k,totalVideoDelay:x}=o;t.statsToReport.uint32_avg_down_loss=Math.floor(E/_),b&&k&&(t.statsToReport.uint32_audio_network_p2p_delay=Math.floor(k/b),t.audioJitterBufferDelay&&(t.statsToReport.uint32_p2p_delay=Math.floor(t.statsToReport.uint32_audio_network_p2p_delay+t.audioJitterBufferDelay))),C&&x&&(t.statsToReport.uint32_video_network_p2p_delay=Math.floor(x/C))}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,D.AUDIO),t.statsToReport.uint32_video_play_time=s.getDuration(e,D.VIDEO)),t.statsToReport.uint32_video_render_first&&(t.statsToReport.uint32_video_render_first=Math.min(t.statsToReport.uint32_video_render_first,zo));let{badCaseDetector:n}=this._room,{dataFreeze:d,count:p}=n.getDataFreezeDuration(e),{renderFreeze:m}=n.getRenderFreezeDuration(e);t.statsToReport.uint32_video_block_count=p,t.statsToReport.uint32_video_block_time=Math.min(d,t.statsToReport.uint32_video_play_time),t.statsToReport.uint32_video_external_block_time=Math.min(m,t.statsToReport.uint32_video_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>zo&&(t.statsToReport.uint64_play_first_frame_time=t.statsToReport.uint64_start_enter_time+zo)}),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>zo&&(t.statsToReport.uint64_render_first_frame_time=t.statsToReport.uint64_start_enter_time+zo)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>zo&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+zo)}getReportData(){this._basicInfo.uint32_networkType=fc();let t={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new xa({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:fs(this._signalInfo.relayIp),uint32_client_ip:fs(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*_n(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:fs(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,bytes_report_buf_from_0x1:this._signalInfo.endReportExtend};return On(t),t}report(){return y(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 y(this,null,function*(){if(t.msg_path_enter_room.uint64_start_time===0)return;let e=Number(this._room.sdkAppId),r=yield Hu(t),o=r instanceof ArrayBuffer,s=`${Qr(e,wi.KEY_POINT)}&gzip=${+o}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(s,r));let d=[this.uploadKVStat(Y),this.uploadKVStat(No)];n||d.push(Yr({url:s,body:r,priority:"low"})),yield Promise.all(d)})}setConnectionType(t){this.connectionType=t,this._basicInfo.uint32_connection_type=t}uploadKVStat(t){return y(this,null,function*(){let e=t.getReportData();if(e.stats_count.length===0&&e.stats_distribution.length===0)return;e.msg_sdk_basic_info=Ee(Z({},e.msg_sdk_basic_info),{bytes_device_name:this._basicInfo.string_device_name||"",bytes_os_version:this._basicInfo.string_os_version||"",uint32_framework:this._frameWorkType,uint32_network_type:this._basicInfo.uint32_networkType||0}),this._log.debug(e);let r=yield Hu(e),o=`${Qr(+this._room.sdkAppId,wi.KV_STAT)}&gzip=${+(r instanceof ArrayBuffer)}`,s=!1;navigator.sendBeacon&&(s=navigator.sendBeacon(o,r)),s||Yr({url:o,body:r})})}};X([Bi({settings:{timeout:500,retries:3}})],ru.prototype,"upload",1);var zo=5e3,rS={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},xa=class{constructor(t){u(this,"str_identifier");u(this,"str_tinyid");u(this,"uint32_role");this.str_identifier=String(t.userId),this.str_tinyid=String(t.tinyId||0),this.uint32_role=t.role}},mg=ru;var sp=class{constructor(){u(this,"_startTime");u(this,"_endTime");this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=_e())}stop(){this._endTime===0&&(this._endTime=_e())}getDuration(){return this._endTime===0?_e()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},iu=sp;var np=class{constructor(t){u(this,"_room",null);u(this,"_durationMap");u(this,"_eventMap",new Map);this._room=t.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(L.REMOTE_TRACK_SUBSCRIBED,this.handleSubscribed).set(L.REMOTE_TRACK_UNSUBSCRIBED,this.handleUnsubscribed).set(L.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`,D.AUDIO),e.hasVideo&&!r.hasVideo&&this.stopDurationItem(`${o}_main`,D.VIDEO),e.hasAuxiliary&&!r.hasAuxiliary&&this.stopDurationItem(`${o}_auxiliary`,D.VIDEO);let s=(n=this._room)==null?void 0:n.remotePublishedUserMap.get(o);s&&(!e.hasAudio&&r.hasAudio&&s.remoteAudioTrack.isSubscribed&&this.addDuractionItem(o,D.AUDIO,"main"),!e.hasVideo&&r.hasVideo&&s.remoteVideoTrack.isSubscribed&&this.addDuractionItem(o,D.VIDEO,"main"),!e.hasAuxiliary&&r.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(o,D.VIDEO,"auxiliary"))}),this._eventMap.forEach((t,e)=>H.on(e,t,this))}uninstallEvents(){this._eventMap.forEach((t,e)=>H.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 iu,n=this._durationMap.get(o);n?this.isRecording(n[e])||n[e].push(s):this._durationMap.set(o,{userId:t,type:r,audio:e===D.AUDIO?[s]:[],video:e===D.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()}},pg=np;var ap=class{constructor(t){u(this,"_room");u(this,"_renderFreezeMap",new Map);u(this,"_isVideoPlayingEventFiredMap",new Map);u(this,"_dataFreezeMap",new Map);u(this,"_monitorFreezeData",new Map);u(this,"_eventMap",new Map);this._room=t.room,this.installEvents()}getRenderFreezeMap(){return this._renderFreezeMap}getDataFreezeMap(){return this._dataFreezeMap}installEvents(){this._eventMap.set(L.LEAVE_SUCCESS,({room:t})=>{this.hitTest(t)&&this.stop()}).set(L.PLAY_TRACK_START,this.onPlayTrackStart).set(L.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(L.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(L.PLAYER_STATE_CHANGED,({track:t,state:e,reason:r,type:o})=>{if(!(!t.isRemote||!t.room||!this.hitTest(t.room)||o!==D.VIDEO)){if(e==="PLAYING"){let s=`${t.userId}_${t.streamType}`;this._isVideoPlayingEventFiredMap.set(s,!0)}r===D.MUTE?this.onVideoTrackMuted(t):r===D.UNMUTE&&this.onVideoTrackUnmuted(t)}}).set(L.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach((t,e)=>H.on(e,t,this))}uninstallEvents(){this._eventMap.forEach((t,e)=>H.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 iu;s?s.durationItemList.push(n):this._dataFreezeMap.set(o,{userId:e,type:r,durationItemList:[n],isFreezing(){let d=this.durationItemList[this.durationItemList.length-1];return d&&d.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}){this.hitTest(t)&&e.msg_down_stream_info.forEach(r=>{let o=this._room.remotePublishedUserMap.get(r.msg_user_info.str_identifier);if(!o)return;let{userId:s,muteState:n}=o;r.msg_video_status.forEach(d=>{d.uint32_video_stream_type===2&&n.hasVideo&&!n.videoMuted&&o.remoteVideoTrack.isSubscribed&&this.handleRenderFreeze({userId:s,fps:d.uint32_video_dec_fps,type:"main"}),d.uint32_video_stream_type===7&&n.hasAuxiliary&&o.remoteAuxiliaryTrack.isSubscribed&&this.handleRenderFreeze({userId:s,fps:d.uint32_video_dec_fps,type:"auxiliary"})})})}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();n>pc?this._monitorFreezeData.set(t,{userId:e,type:r,duration:n}):o.durationItemList.pop()}getTotalDuration(t){return t.reduce((e,r)=>{let o=r.getDuration();return e+Math.min(o,5e3)},0)}handleRenderFreeze(o){return y(this,arguments,function*({userId:t,fps:e,type:r}){let s=`${t}_${r}`,n=this._renderFreezeMap.get(s);if(e<=2){let d=_e();n&&!n.isFreeze&&(n.freezeTimeline.push({startTime:d,endTime:0}),n.isFreeze=!0),n||this._renderFreezeMap.set(s,{userId:t,type:r,isFreeze:!0,freezeTimeline:[{startTime:d,endTime:0}],renderFreezeTotal:0})}else if(n&&n.isFreeze){n.isFreeze=!1;let d=n.freezeTimeline.pop();if(d){d.endTime=_e();let p=d.endTime-d.startTime;n.freezeTimeline.push(d),n.renderFreezeTotal+=Math.min(5e3,p)}}})}onPlayTrackStart({track:t}){if(!t.isRemote||!this.hitTest(t.room)||t.kind!==D.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()<pc&&r.durationItemList.pop()}e.dataFreeze=this.getTotalDuration(r.durationItemList),e.count=r.durationItemList.length}return e}getRenderFreezeDuration(t){let e=this._renderFreezeMap.get(t),r=0,o=0;if(e)if(!e.isFreeze)r=e.renderFreezeTotal;else{let s=_e(),n=e.freezeTimeline[e.freezeTimeline.length-1],d=s-n.startTime;r=e.renderFreezeTotal+Math.min(d,5e3),o=e.freezeTimeline.length}return{renderFreeze:r,count:o}}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(t){return this._isVideoPlayingEventFiredMap.has(t)?!this._isVideoPlayingEventFiredMap.get(t):!1}resetMonitor(){this._monitorFreezeData.clear()}hitTest(t){return t===this._room}destroy(){this.uninstallEvents()}},hg=ap;var gg=Di(Ui(),1);var iS=[1,0,0,0,1,1,0,1],ou=class extends Ft{constructor(t,e){if(super(t,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"mirror",logger:e}),t instanceof yt)try{this.setTexBuffer(iS)}catch(r){t.destroy(new he({code:te.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${r.message||r}`}))}}draw2d(t,e,r,o,s){if(this.ctx2d){this.ctx2d.save(),this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0);let n=super.draw2d(t,e,r,o,s);return this.ctx2d.restore(),n}return!1}render(t){var e;return(e=this.input)!=null&&e.requestFrame(t)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}};var cp=class{constructor(t,e){this.node=t;this.layout=e;u(this,"positionBuffer")}get x(){return this.layout.x||this.node.x}get y(){return this.layout.y||this.node.y}get width(){return this.layout.width||this.node.width}get height(){return this.layout.height||this.node.height}get right(){return this.x+this.width}get bottom(){return this.y+this.height}},su=class extends Ft{constructor(e,r){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:r});u(this,"inputs",[])}addInput(e,r){if(this.inputs[r.zIndex])throw new Error("input already exists");let o=new cp(e,r);this.inputs[r.zIndex]=o}resize(e,r){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 yt&&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.resize(0,0),e}removeInput(e){this.inputs[this.inputs.findIndex(r=>(r==null?void 0:r.node)===e)]=void 0}render(e){let r=this.context.ctx;if(r.clearColor(0,0,0,0),!this.inputs.reduce((s,n)=>(!n||!n.node.requestFrame(e))&&s,!0)&&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.reduce((o,s)=>(!s||!s.node.requestFrame(e))&&o,!0)&&this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height);for(let o=0;o<this.inputs.length;o++){let s=this.inputs[o];s&&this.draw2d(s.node.image,s.x,s.y,s.width,s.height)}return!0}return!1}getInfo(){let{totalFrames:e,x:r,y:o,width:s,height:n,name:d}=this,p=Date.now(),m=(e-this.lastInfo.totalFrames)/((p-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:r,y:o,width:s,height:n,timestamp:p,fps:m,name:d},Z({parent:this.inputs.filter(E=>E).map(E=>E.node.getInfo())},this.lastInfo)}close(){super.close(),this.inputs.forEach(e=>{var r,o;if(e&&((r=e.node)==null||r.disconnect(),e.positionBuffer&&this.context instanceof yt))try{(o=this.context.ctx)==null||o.deleteBuffer(e.positionBuffer)}catch(s){}})}};var oS=`#version 300 es
|
|
100
|
+
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=>{cg[`${i}()`]={tips:`Call trtc.${i}`,color:"blue",class:"blue",textColor:"#fff"}});var oP=Object.keys(cg);var YI=0,Kd,Ys=class Ys{constructor(t){this.core=t;u(this,"_core");u(this,"log");u(this,"dumpLocalVideoMap",{});u(this,"dumpRemoteVideoMap",{});u(this,"dialog");this._core=t,this.log=t.log.createChild({id:`${this.getAlias()}${++YI}`}),this.log.info("created")}getName(){return Ys.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 y(this,null,function*(){var e;!new URLSearchParams(location.search).has("trtcDebug")&&((e=window.sessionStorage)==null?void 0:e.getItem("TRTC_ENABLE_DEBUG_PLUGIN"))!=="true"||(yield this.openDebugDiaLog(),this.addVideoProcessor())})}update(){}stop(){this.closeDebugDiaLog(),this.removeVideoProcessor()}destroy(){this.stop()}openDebugDiaLog(){return y(this,null,function*(){var t;try{if(Kd)yield Kd;else{let e=Date.now(),r=new URLSearchParams(location.search).get("trtcDebugDialogPath")||((t=window.sessionStorage)==null?void 0:t.getItem("TRTC_DEBUG_DIALOG_PATH"))||`https://unpkg.com/${sg}@${rt}/assets/debug-dialog.js`;Kd=this.loadScript(r),yield Kd,this.log.info(`download debug dialog script cost: ${Date.now()-e}ms`)}this.dialog=new TRTCDebugDialog(this._core,this.log,this.dumpLocalVideoMap,this.dumpRemoteVideoMap),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(e){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(e))}})}closeDebugDiaLog(){var t;(t=this.dialog)==null||t.closeDialog(),this.dialog=null}addVideoProcessor(){this._core.room.videoManager.addEncodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.encodeVideo.bind(this):ip,type:1}),this._core.room.videoManager.addDecodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.decodeVideo.bind(this):op,type:1})}removeVideoProcessor(){this._core.room.videoManager.removeEncodeProcessor({type:1}),this._core.room.videoManager.removeDecodeProcessor({type:1})}encodeVideo({frame:t,mediaType:e}){return ip({frame:t,onDump:()=>{if(!e)return;let r=e===2?"sub":"main",o=this.dumpLocalVideoMap[r];o&&(o.data.push(t.data),o.duration>0&&Date.now()-o.startTimestamp>o.duration*1e3&&o.onDumpEnd())}})}decodeVideo({frame:t,track:e}){return op({frame:t,onDump:()=>{if(!e)return;let r=this.dumpRemoteVideoMap[`${e.userId}-${e.streamType}`];r&&(r.data.push(t.data),r.duration>0&&Date.now()-r.startTimestamp>r.duration*1e3&&r.onDumpEnd())}})}loadScript(t){return new Promise((e,r)=>{this.log.info(`loading debug dialog from ${t}`);let o=document.createElement("script");o.type="text/javascript",o.onload=e,o.onerror=r,o.crossOrigin="anonymous",o.src=t,document.head.append?document.head.append(o):document.getElementsByTagName("head")[0].appendChild(o)})}};u(Ys,"Name","Debug"),u(Ys,"autoStart",!0),X([Hi({settings:{timeout:3e3,retries:3},onError(t,e,r){var o;(o=t==null?void 0:t.message)!=null&&o.includes("timeout")?e():r(t)}})],Ys.prototype,"loadScript",1);var eu=Ys;var dg=i=>{switch(i){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},tu=class{constructor(t,e,r){u(this,"trackDoneOB");u(this,"startOB");u(this,"stopOB");u(this,"inputFrameCount",0);u(this,"decodedFrameCount",0);u(this,"type","auto");u(this,"config");u(this,"decoder");u(this,"_decodeSink");let{kvStatManager:o,trtc:s}=t;this.config=r.config,this.trackDoneOB=be(e,ne.INIT),this.stopOB=It(this.trackDoneOB),this.startOB=It(),r.type==="auto"?this.type="webCodecs":this.type=r.type;let n=It(),d=p=>{let m=this.pipe(e);return n.next("STARTING"),e.log.info(`decoder type: ${this.type}`),Se(m,Je(this.stopOB),ke(()=>{},g=>{e.log.error(g),o.addFailedEvent({key:dg(this.type),error:g}),p>4?this.startOB.error(g):this.startOB.next(p+1)})),Se(m,Ar(1),xm(Ia))};Se(this.startOB,_a(0),zi(d),Je(this.stopOB),ke(()=>{e.player.setOutput(),n.next("STARTED")},p=>{n.next("FAILED")},()=>{o.addSuccessEvent({key:dg(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 li()(e=>y(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"}))}},ZI={type:"object"},wa=class wa{constructor(t){this.core=t;u(this,"log");u(this,"contextMap",new Map);u(this,"decodeProcessorMap",new WeakMap);this.log=t.log.createChild({id:`${this.getAlias()}`})}getAlias(){return wa.Name}getGroup(t){return t.track.userId+t.track.streamType}getName(){return wa.Name}getValidateRule(t){return ZI}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 tu(this.core,r,t);return Se(o.trackDoneOB,Ar(1),ke(()=>{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 tu(this.core,t.track,t))}}};u(wa,"Name","TRTCAudioDecoder");var Ma=wa;var ug=0,Oa=new Set,Rt=null;Ou(ng);Ms.checkStorage();xl();var KI={RtcError:ae,ErrorCode:ue,ErrorCodeDictionary:Rr},fe=class fe extends lg.EventEmitter{constructor(e,r){super();u(this,"_room");u(this,"_eventListened",new Set);u(this,"_localVideoTrack",null);u(this,"_localAudioTrack",null);u(this,"_localScreenTrack",null);u(this,"_localScreenAudioTrack",null);u(this,"_localVideoConfig",null);u(this,"_localScreenConfig",null);u(this,"_localAudioConfig",null);u(this,"_remoteVideoConfigMap",new Map);u(this,"_remoteAudioConfigMap",new Map);u(this,"_remoteAudioVolumeMap",new Map);u(this,"_remoteAudioMuteMap",new Map);u(this,"_mediaTrackMap",new WeakMap);u(this,"_log",$.createLogger({id:`t${++ug}`}));u(this,"_plugins",new Map);u(this,"_networkQuality",null);u(this,"_speakerId");u(this,"_getPCMAbortCtrl");this._room=new e(ee({logger:this._log,frameWorkType:fe.frameWorkType},r)),this._room.videoDecodeFallbackType=r.videoDecodeFallback,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(Xd,r.assetsPath),this._use(Yd,r.assetsPath),this._use(Ma,r.assetsPath||nc),this._use(eu),r.enableSEI&&sa&&this._use(Zd),this._room.on("audio-volume",o=>{!o.find(s=>s.userId==="")&&this._localAudioTrack&&o.push({userId:"",volume:Math.floor(this._localAudioTrack.getAudioLevel()*100)}),r.volumeType===1&&o.forEach(s=>{var d;let n=s.userId===""?this._localAudioTrack:(d=this.room.remotePublishedUserMap.get(s.userId))==null?void 0:d.remoteAudioTrack;n&&(s.volume=n.dbVolume)}),this.emit(se.AUDIO_VOLUME,{result:o.sort((s,n)=>n.volume-s.volume)})}),this._room.videoManager.on("error",o=>{this._log.error(new ae({code:ue.OPERATION_FAILED,extraCode:5504,message:o.message,originError:o}))}),this._listenEvents(),this._initActiveSpeaker(),tg(this,"trtc")}static create(e){}static _create(e,r){Bf();let o=new fe(e,r||{});return Oa.add(o),o}get room(){return this._room}_listenEvents(){xt(this,this._room).add("peer-join",e=>{let{userId:r}=e;this.emit(se.REMOTE_USER_ENTER,{userId:r})}).add("peer-leave",e=>{this.emit(se.REMOTE_USER_EXIT,{userId:e}),this._remoteAudioVolumeMap.delete(e)}).add("banned",e=>{this._exitRoom().finally(()=>{this.emit(se.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().finally(()=>{this.emit(se.ERROR,ae.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(se.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let r=Ee(ee({},e),{uplinkRTT:Math.min(e.uplinkRTT,bn),downlinkRTT:Math.min(e.downlinkRTT,bn)});this.emit(se.NETWORK_QUALITY,r)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(o=>{xt(o,o).add("player-state-changed",s=>{let n=Ee(ee({},s),{userId:e.userId});o.kind===D.VIDEO&&(n.streamType=eo(o.streamType)),this.emit(o.kind===D.AUDIO?se.AUDIO_PLAY_STATE_CHANGED:se.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",s=>{s.getCode()===te.PLAY_NOT_ALLOWED&&this.emit(se.AUTOPLAY_FAILED,{userId:o.userId,resume:()=>o.player.resume()})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(o=>{mt(o)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:r})=>{let{userId:o}=r,s=e.audioAvailable,n=e.videoAvailable,{audioAvailable:d,videoAvailable:p}=r;d||this._remoteAudioConfigMap.delete(o),p||this._remoteVideoConfigMap.delete(`${o}_main`),r.hasAuxiliary||this._remoteVideoConfigMap.delete(`${o}_sub`),n!==p&&(p?this._onVideoAvailable({userId:o,streamType:"main"}):this._onVideoUnavailable({userId:o,streamType:"main"}),this.emit(p?se.REMOTE_VIDEO_AVAILABLE:se.REMOTE_VIDEO_UNAVAILABLE,{userId:o,streamType:"main"})),s!==d&&(d?this._onAudioAvailable({userId:o}):this._onAudioUnavailable({userId:o,muteState:r}),this.emit(d?se.REMOTE_AUDIO_AVAILABLE:se.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?se.REMOTE_VIDEO_AVAILABLE:se.REMOTE_VIDEO_UNAVAILABLE,{userId:o,streamType:"sub"}))}).add("sei-message",e=>{this.emit(se.SEI_MESSAGE,Ee(ee({},e),{streamType:eo(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(se.ERROR,new ae({code:ue.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var s,n,d,p,m,g,_;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)||((d=this._networkQuality)==null?void 0:d.downlinkRTT)||0,bn),upLoss:((p=this._networkQuality)==null?void 0:p.uplinkLoss)||0,downLoss:((m=this._networkQuality)==null?void 0:m.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((g=e.msg_up_stream_info.msg_audio_status)==null?void 0:g.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((_=e.msg_up_stream_info.msg_audio_status)==null?void 0:_.uint32_audio_level)||0)/oi},video:e.msg_up_stream_info.msg_video_status.filter(b=>r[b.uint32_video_stream_type]).map(b=>({bitrate:(b.uint32_video_codec_bitrate||0)/1e3,width:b.uint32_video_width,height:b.uint32_video_height,frameRate:b.uint32_video_enc_fps,videoType:r[b.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(b=>({userId:b.msg_user_info.str_identifier,audio:{bitrate:(b.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(b.msg_audio_status.uint32_audio_level||0)/oi},video:b.msg_video_status.map(N=>({bitrate:(N.uint32_video_codec_bitrate||0)/1e3,width:N.uint32_video_width,height:N.uint32_video_height,frameRate:N.uint32_video_dec_fps,videoType:r[N.uint32_video_stream_type]}))}))};this.emit(se.STATISTICS,o)}).add("custom-message",e=>{this.emit(se.CUSTOM_MESSAGE,e)}).add("layerData",e=>this.emit(se.LAYER_DATA,e)).add("first-video-frame",e=>{this.emit(se.FIRST_VIDEO_FRAME,Ee(ee({},e),{streamType:eo(e.streamType)}))}),xt(this,Tt).add("audioInputAdded",e=>{this.emit(se.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(se.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(se.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(se.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>y(this,null,function*(){if(this.emit(se.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Rt&&Rt.deviceId===An){let r=(yield Wi()).find(o=>o.deviceId===An);r&&Rt.groupId!==r.groupId&&(Rt=r,this.emit(se.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}))}})).add("audioOutputRemoved",e=>y(this,null,function*(){this.emit(se.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let r=(yield Wi())[0];if(!r||!Rt||Rt.groupId===r.groupId)return;let o=Rt.deviceId===e.deviceId,s=Rt.deviceId===An&&Rt.deviceId===r.deviceId;(o||s)&&(Rt=r,this.emit(se.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}))}))}use(e){let r,o;"plugin"in e?(r=e.plugin,o=e.assetsPath):r=e,this._use(r,o||nc)}_use(e,r){if(this._plugins.get(e.Name)){this._log.warn("duplicate install plugin",e.Name);return}let s=new e(eg.call(this,{TRTC:fe,room:this._room,errorModule:KI,assetsPath:r}));this._plugins.set(e.Name,s),e.autoStart&&this.startPlugin(e.Name)}enterRoom(e){return y(this,null,function*(){var p,m;let{scene:r="rtc",enableAutoPlayDialog:o=!0,autoReceiveAudio:s=!0,autoReceiveVideo:n=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!we(e.proxy)&&e.proxy.turnServer&&((m=(p=this._room).setTurnServer)==null||m.call(p,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 d={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:e.role==="audience"?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language,priority:e.priority,useVp8:e.useVp8,keepAlive:e.keepAlive};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(d,r,fe.frameWorkType),this._checkTrackToPublish(),Km.start()})}exitRoom(){return y(this,null,function*(){return yield this._exitRoom()})}switchRole(e,r){return y(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(){mt(this),this.removeAllListeners(),this._room.destroy(),Oa.delete(this),Oa.size===0&&Km.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),this._plugins.forEach(e=>{var r;return(r=e.destroy)==null?void 0:r.call(e)}),this._plugins.clear(),H.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return y(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 ui(this._room.audioManager),d={},p={muted:!0};s&&(V(s.microphoneId)?V(s.audioTrack)||(d.customSource=s.audioTrack):d.deviceId=s.microphoneId,s&&je(s.captureVolume)&&n.setCaptureVolume(s.captureVolume),V(s.profile)||(we(s.profile)?cc[s.profile]&&n.setProfile(cc[s.profile]):n.setProfile(s.profile)),je(s.earMonitorVolume)&&(p.muted=!(s.earMonitorVolume>0),p.volume=s.earMonitorVolume),V(s.echoCancellation)||(n.profile.echoCancellation=s.echoCancellation),V(s.noiseSuppression)||(n.profile.noiseSuppression=s.noiseSuppression),V(s.autoGainControl)||(n.profile.autoGainControl=s.autoGainControl)),n.on("5",m=>{this.emit(se.ERROR,new ae({code:ue.DEVICE_ERROR,extraCode:5309,messageParams:{error:m}}))}),n.on("2",m=>{this.emit(se.DEVICE_CHANGED,{type:"microphone",action:"active",device:m})}),n.on("4",m=>{let g;m.error&&(g=ae.convertFrom(m.error)),this.emit(se.PUBLISH_STATE_CHANGED,Ee(ee({},m),{error:g}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId),yield n.capture(d),V(o)||n.setMute(o),xt(n,n).add("player-state-changed",m=>{this.emit(se.AUDIO_PLAY_STATE_CHANGED,Ee(ee({},m),{userId:""}))}),this.listeners(se.AUDIO_FRAME).length>0&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM(m=>{this.emit(fe.EVENT.AUDIO_FRAME,{data:m})})),this._getPCMAbortCtrl&&n.on("input-media-track-changed",()=>{this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("inputMediaTrackChanged"),this._getPCMAbortCtrl=this._room.audioManager.getPCM(m=>{this.emit(fe.EVENT.AUDIO_FRAME,{data:m})}))}),r&&this._room.isJoined&&this._room.publish(n).catch(()=>{}),this._localAudioTrack=n,this._localAudioConfig=Ee(ee({},e),{publish:r}),yield this._updateAudioPlayOption({playOption:p,track:n})})}updateLocalAudio(e){return y(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):V(s.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(s.audioTrack)),V(s.captureVolume)||this._localAudioTrack.setCaptureVolume(s.captureVolume),V(s.earMonitorVolume)||(n.muted=!(s.earMonitorVolume>0),n.volume=s.earMonitorVolume),yield this._localAudioTrack.update3A(s)),this._room.isJoined&&!V(r)&&(r&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!r&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),V(o)||this._localAudioTrack.setMute(o),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),kr(this._localAudioConfig,e)})}stopLocalAudio(){return y(this,null,function*(){this._localAudioTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),mt(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null,this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("stopLocalAudio"),delete this._getPCMAbortCtrl))})}startLocalVideo(){return y(this,arguments,function*(e={publish:!0,view:null}){if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:r,publish:o=!0,mute:s,option:n}=e,d=new Sr(this._room.videoManager),p={},m={};nt(n==null?void 0:n.avoidCrop)&&(d.avoidCrop=n.avoidCrop),n&&(n.cameraId?p.deviceId=n.cameraId:V(n.useFrontCamera)?V(n.videoTrack)||(p.customSource=n.videoTrack):p.facingMode=n.useFrontCamera?D.FACING_MODE_USER:D.FACING_MODE_ENVIRONMENT,n.qosPreference&&(p.contentHint=Da(n.qosPreference)),V(n.profile)||(we(n.profile)?Or[n.profile]&&d.setProfile(Or[n.profile]):d.setProfile(n.profile)),V(n.fillMode)||(m.objectFit=n.fillMode),V(n.mirror)||(m.mirror=n.mirror),V(n.small)||(ra()?we(n.small)?d.small=Or[n.small]:n.small===!0?d.small=Or["120p"]:d.small=n.small:this._log.warn("small stream is not supported"))),d.once("first-video-frame",g=>{this.emit(se.FIRST_VIDEO_FRAME,Ee(ee({},g),{streamType:eo(g.streamType)}))}),d.on("5",g=>{this.emit(se.ERROR,new ae({code:ue.DEVICE_ERROR,extraCode:5308,messageParams:{error:g}}))}),d.on("2",g=>{this.emit(se.DEVICE_CHANGED,{type:"camera",action:"active",device:g})}),d.on("4",g=>{let _;g.error&&(_=ae.convertFrom(g.error)),this.emit(se.PUBLISH_STATE_CHANGED,Ee(ee({},g),{error:_}))}),this._listenOutputTrackChanged(d),yield d.capture(p),V(s)||(yield d.setMute(s)),xt(d,d).add("player-state-changed",g=>{this.emit(se.VIDEO_PLAY_STATE_CHANGED,Ee(ee({},g),{userId:"",streamType:"main"}))}),o&&this._room.isJoined&&this._room.publish(d).catch(()=>{}),this._localVideoTrack=d,this._localVideoConfig=Ee(ee({},e),{view:r,publish:o}),yield this._updateVideoPlayOption({view:r,playOption:m,track:d})})}updateLocalVideo(e){return y(this,null,function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:r,publish:o,mute:s,option:n}=e,d={};if(n)if(V(n.profile)||(we(n.profile)?Or[n.profile]&&this._localVideoTrack.setProfile(Or[n.profile]):this._localVideoTrack.setProfile(n.profile),(!n.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(n.cameraId))&&V(n.useFrontCamera)&&this._localVideoTrack.applyProfile()),n.cameraId?yield this._localVideoTrack.switchDevice(n.cameraId):V(n.useFrontCamera)?V(n.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(n.videoTrack)):yield this._localVideoTrack.switchDevice(n.useFrontCamera?D.FACING_MODE_USER:D.FACING_MODE_ENVIRONMENT),V(n.fillMode)||(d.objectFit=n.fillMode),V(n.mirror)||(d.mirror=n.mirror),n.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(Da(n.qosPreference)),n.small){let p=!this._localVideoTrack.small;ra()?(n.small===!0?this._localVideoTrack.small=Or["120p"]:we(n.small)?this._localVideoTrack.small=Or[n.small]:this._localVideoTrack.small=n.small,this._room.videoManager.update(),p&&this._room.enableSmall(!0)):this._log.warn("small stream is not supported")}else n.small===!1&&this._localVideoTrack.small&&(delete this._localVideoTrack.small,this._room.videoManager.update(),this._room.enableSmall(!1));this._room.isJoined&&!V(o)&&(o&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._localVideoConfig.publish&&!o&&this._room.unpublish(this._localVideoTrack).catch(()=>{})),V(s)||(yield this._localVideoTrack.setMute(s)),yield this._updateVideoPlayOption({view:r,playOption:d,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),kr(this._localVideoConfig,e)})}stopLocalVideo(){return y(this,null,function*(){this._localVideoTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),mt(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return y(this,arguments,function*(e={publish:!0,view:null}){if(this._localScreenTrack){this._log.warn("screen share is already started");return}let{view:r=null,publish:o=!0,option:s}=e,n=new ji(this._room.videoManager);n.on("4",_=>{let b;_.error&&(b=ae.convertFrom(_.error)),this.emit(se.PUBLISH_STATE_CHANGED,Ee(ee({},_),{error:b}))}),n.once("first-video-frame",_=>{this.emit(se.FIRST_VIDEO_FRAME,Ee(ee({},_),{streamType:eo(_.streamType)}))}),this._listenOutputTrackChanged(n),e.streamType==="main"&&(n.mediaType=4);let d=null,p={},m={};s&&(V(s.profile)||(we(s.profile)?dc[s.profile]&&n.setProfile(dc[s.profile]):n.setProfile(s.profile)),s.systemAudio&&(p.systemAudio=!0,p.echoCancellation=s.echoCancellation,p.noiseSuppression=s.noiseSuppression,p.autoGainControl=s.autoGainControl),V(s.fillMode)||(m.objectFit=s.fillMode),s.videoTrack&&(p.videoTrack=s.videoTrack),s.audioTrack&&(p.audioTrack=s.audioTrack),s.captureElement&&(p.captureElement=s.captureElement),s.preferDisplaySurface&&(p.preferDisplaySurface=s.preferDisplaySurface),s.qosPreference&&(p.contentHint=Da(s.qosPreference)));let g=yield n.capture(p);if(n.mediaTrack.addEventListener(D.ENDED,()=>{this._stopScreenShare(),this.emit(se.SCREEN_SHARE_STOPPED)}),g.getAudioTracks()[0]&&(d=new Fo(this._room.audioManager),yield d.setInputMediaStreamTrack(g.getAudioTracks()[0]),this._speakerId&&d.setAudioOutput(this._speakerId)),xt(n,n).add("player-state-changed",_=>{this.emit(se.VIDEO_PLAY_STATE_CHANGED,Ee(ee({},_),{userId:"",streamType:"sub"}))}),o&&this._room.isJoined){let _=[n];d&&_.push(d),this._room.publish(..._).catch(()=>{})}this._localScreenTrack=n,this._localScreenAudioTrack=d,this._localScreenConfig=Ee(ee({},e),{view:r,publish:o}),yield this._updateVideoPlayOption({view:r,playOption:m,track:n})})}updateScreenShare(e){return y(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:r,publish:o,option:s}=e,n={};if(s&&(V(s.fillMode)||(n.objectFit=s.fillMode),s.qosPreference)){let d=Da(s.qosPreference);this._localScreenTrack.setContentHint(d)}this._room.isJoined&&!V(o)&&(o&&!this._localScreenConfig.publish&&(this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch(()=>{})),this._localScreenConfig.publish&&!o&&(this._room.unpublish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.unpublish(this._localScreenAudioTrack).catch(()=>{}))),yield this._updateVideoPlayOption({view:r,playOption:n,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),kr(this._localScreenConfig,e)})}stopScreenShare(){return y(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return y(this,null,function*(){let{view:r,userId:o,streamType:s,option:n}=e,d=`${o}_${s}`;if(this._remoteVideoConfigMap.has(d)){this._log.warn(`remote video has already started. userId:${o}, streamType:${s}`);return}let p=this._room.remotePublishedUserMap.get(o);if(!p)return;let m={},g=s==="main"?p.remoteVideoTrack:p.remoteAuxiliaryTrack;this._listenOutputTrackChanged(g),n&&(V(n.fillMode)||(m.objectFit=n.fillMode),V(n.mirror)||(m.mirror=n.mirror),V(n.poster)||(m.poster=n.poster),m.canvasRender=n.canvasRender,s==="main"&&!V(n.small)&&(!p.remoteVideoTrack.isSubscribing&&!p.remoteVideoTrack.isSubscribed&&p.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,g.user))),yield this._room.subscribe(g),yield this._enableVideoDecodeFallback(g,s),yield this._updateVideoPlayOption({view:r,playOption:m,track:g}),this._emitTrackEvent(g),this._remoteVideoConfigMap.set(d,{config:e}),n&&!V(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:g,view:r,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:n==null?void 0:n.viewRoot})})}updateRemoteVideo(e){return y(this,null,function*(){var x,J;let{view:r,userId:o,streamType:s,option:n}=e,d=`${o}_${s}`,p=this._remoteVideoConfigMap.get(d);if(!p||!this._room.remotePublishedUserMap.has(o))return;let m={};n&&(V(n.fillMode)||(m.objectFit=n.fillMode),V(n.mirror)||(m.mirror=n.mirror));let g=null,_=this._room.remotePublishedUserMap.get(o);if(s==="main"&&(_!=null&&_.muteState.hasVideo)&&(g=_.remoteVideoTrack),s==="sub"&&(_!=null&&_.muteState.hasAuxiliary)&&(g=_.remoteAuxiliaryTrack),!g)return;let{config:b}=p;s==="main"&&n&&!V(n.small)&&this._room.changeType(n.small,g.user),yield this._updateVideoPlayOption({view:r,playOption:m,track:g,prevConfig:b}),kr(b,e);let N=V(n==null?void 0:n.receiveWhenViewVisible)?(x=b.option)==null?void 0:x.receiveWhenViewVisible:n.receiveWhenViewVisible,k=V(r)?b.view:r,P=V(n==null?void 0:n.viewRoot)?(J=b.option)==null?void 0:J.viewRoot:n.viewRoot;this._observeView({remoteTrack:g,view:k,receiveWhenViewVisible:N,viewRoot:P})})}stopRemoteVideo(e){return y(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,r=!0){return y(this,null,function*(){let o=[],s=this._room.remotePublishedUserMap.get(e.userId);if(s){let{muteState:d,remoteVideoTrack:p,remoteAuxiliaryTrack:m}=s;e.streamType==="main"&&(p.stop(),d.hasVideo&&o.push(p)),e.streamType==="sub"&&(m.stop(),d.hasAuxiliary&&o.push(m))}for(let d of o)r&&(yield this._room.unsubscribe(d),this._mediaTrackMap.delete(d.outMediaTrack));let n=this._remoteVideoConfigMap.get(`${e.userId}_${e.streamType}`);n&&n.observer&&n.observer.disconnect(),this._remoteVideoConfigMap.delete(`${e.userId}_${e.streamType}`)})}muteRemoteAudio(e,r){return y(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 this._remoteAudioMuteMap.delete(e),o}})}setRemoteAudioVolume(e,r){if(e==="*"){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 y(this,null,function*(){return e.start(r)})}updatePlugin(e,r){return y(this,null,function*(){return e.update(r)})}stopPlugin(e,r){return y(this,null,function*(){return e.stop(r)})}enableAudioVolumeEvaluation(e=2e3,r=!1){this._room.enableAudioVolumeEvaluation(e,r)}on(e,r,o){return this.listeners(e).includes(r)?this:(this._log.debug("on",e),super.on(e,r,o),this._eventListened.add(e),e===fe.EVENT.AUDIO_FRAME&&!this._getPCMAbortCtrl&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM(s=>{this.emit(fe.EVENT.AUDIO_FRAME,{data:s})}),this._localAudioTrack&&this._localAudioTrack.on("input-media-track-changed",()=>{this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("inputMediaTrackChanged"),this._getPCMAbortCtrl=this._room.audioManager.getPCM(s=>{this.emit(fe.EVENT.AUDIO_FRAME,{data:s})}))})),this)}emit(e,...r){try{Xf.has(e)&&this._log.debug(`emit ${e} ${JSON.stringify(r)}`)}catch(o){}return super.emit(e,...r)}off(e,r,o){var s,n;return this._log.debug("off",e),e==="*"?(this._eventListened.clear(),this.removeAllListeners(),(s=this._getPCMAbortCtrl)==null||s.abort("off"),delete this._getPCMAbortCtrl):(super.off(e,r,o),e===fe.EVENT.AUDIO_FRAME&&((n=this._getPCMAbortCtrl)==null||n.abort("off"),delete this._getPCMAbortCtrl)),this}getAudioTrack(e={userId:"",streamType:"main"}){let r,o=null,s="main",n=!1;if(we(e)?r=e:(r=e.userId,n=e.processed===!0,e.streamType&&(s=e.streamType)),r){let d=this._room.remotePublishedUserMap.get(r);d&&(o=d.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 d=this._room.remotePublishedUserMap.get(r);d&&(n=o==="main"?d.remoteVideoTrack:d.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 y(this,null,function*(){(yield Wi()).forEach(o=>{o.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(se.DEVICE_CHANGED,{type:"speaker",action:"active",device:o}),Rt=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: https://web.sdk.qcloud.com/trtc/webrtc/v5/doc/en/TRTC.html#.setCurrentSpeaker')})}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return y(this,null,function*(){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;this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId);try{let d=this._remoteAudioVolumeMap.get(r),p=je(d)?d:100;s.volume=p,this._remoteAudioConfigMap.set(r,e),yield this._room.subscribe(n),Se(be(n,"decode-failed"),Je(be(n,ne.INIT)),ke(()=>{this.startPlugin(Ma.Name,{track:n,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:s,track:n})}catch(d){throw this._remoteAudioConfigMap.delete(r),d}this._emitTrackEvent(n)})}_stopRemoteAudio(e,r=!0){return y(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}`)})}_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;Se(be(e,"decode-failed"),Je(be(e,ne.INIT)),Sa(()=>{this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:o})}),mi(be(e,"decode-downgrade-state-changed")),ke(n=>{s=n.state,this.emit(se.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,Ee(ee({},n),{streamType:r,userId:e.userId}))},n=>{e.log.error("fallback",n)},()=>{s==="STARTED"&&e.log.info("fallback complete")}))}_updateVideoPlayOption(n){return y(this,arguments,function*({view:e,playOption:r,track:o,prevConfig:s}){if(o.setMirror(r.mirror),V(e)&&s&&s.view&&!fs(r)){let d=Es(s.view);d.length>0&&(yield o.play(d,r))}if(!V(e)){let d=Es(e);d.length>0?yield o.play(d,r):o.stop()}})}_updateAudioPlayOption(s){return y(this,arguments,function*({playOption:e={},track:r,prevConfig:o}){if(!r.isPlayCalled)try{yield r.play(null,e)}catch(n){}V(e.muted)||r.setPlayerMute(e.muted),V(e.volume)||r.setAudioVolume(e.volume/100)})}_listenOutputTrackChanged(e){e.listeners("output-media-track-changed").length===0&&e.on("output-media-track-changed",()=>this._emitTrackEvent(e,!1))}_emitTrackEvent(e,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(se.TRACK,{userId:o,streamType:eo(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)),e.length!==0)return this._room.publish(...e).catch(()=>{})}_observeView({remoteTrack:e,view:r,receiveWhenViewVisible:o=!1,viewRoot:s}){if(V(r))return;let n=this._remoteVideoConfigMap.get(`${e.userId}_${eo(e.streamType)}`);if(!n)return;let d=n.observer||void 0;if(r===null||st(r)&&r.length===0||!o){d==null||d.disconnect(),e.isSubscribed||this._room.subscribe(e).catch(()=>{});return}let m=n.visibleViewMap||new Map,g=-1;(!d||d.root!==s)&&(d==null||d.disconnect(),m.clear(),d=new IntersectionObserver(b=>{b.forEach(N=>{m.set(N.target,N.isIntersecting)}),clearTimeout(g),g=window.setTimeout(()=>{let N=[...m.values()].find(k=>k);e.log.info(`view is${N?"":" not"} visible`),N?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:s}));let _=new Set(Es(r));m.forEach((b,N)=>{_.has(N)||(d.unobserve(N),m.delete(N))}),_.forEach(b=>{m.set(b,!0),d.observe(b)}),d.takeRecords().forEach(b=>{m.set(b.target,b.isIntersecting)}),n.visibleViewMap=m,n.observer=d}_exitRoom(){return y(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(e=>{this._stopRemoteAudio({userId:e}).catch()}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let 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(),this._remoteAudioVolumeMap.clear(),rg(this),this._room.remotePublishedUserMap.forEach(e=>{mt(e.remoteAudioTrack),mt(e.remoteVideoTrack),mt(e.remoteAuxiliaryTrack)})})}_stopScreenShare(){return y(this,null,function*(){var e;if(this._localScreenTrack){if(this._room.isJoined){let r=[this._localScreenTrack];this._localScreenAudioTrack&&r.push(this._localScreenAudioTrack),yield(e=this._room)==null?void 0:e.unpublish(...r).catch(()=>{})}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),mt(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_onLocalTrackCaptured({track:e}){e.kind==="audio"&&(!Rt||$s(Rt))&&(this._initActiveSpeaker(),H.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return y(this,null,function*(){if(Rt&&!$s(Rt))this.emit(se.DEVICE_CHANGED,{type:"speaker",action:"active",device:Rt});else{let e=yield Wi();e[0]&&!$s(e[0])?(Rt=e[0],this.emit(se.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):H.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:Ee(ee({seiPayloadType:243},r),{small:!!((s=this._localVideoTrack)!=null&&s.small)})}),Y.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var r,o;(o=(r=this._room).sendCustomMessage)==null||o.call(r,e),Y.addCount({key:500001,useUV:!0})}static setLogLevel(e,r){$.setLogLevel(e),V(r)||(r?$.enableUploadLog():$.disableUploadLog())}static isSupported(){return Zc()}static getCameraList(e=!0){return er(e)}static getMicrophoneList(e=!0){return Jt(e)}static getSpeakerList(e=!0){return Wi(e)}static setCurrentSpeaker(e){return y(this,null,function*(){if(at&&(e===nr.SPEAKER||e===nr.HEADSET)){let o=yield fe.getMicrophoneList(),s="";if(o.forEach(n=>{n.label===e&&(s=n.deviceId)}),!s)return;Oa.forEach(n=>y(this,null,function*(){n._localAudioTrack&&(yield n.updateLocalAudio({option:{microphoneId:s}}))}));return}(yield Wi()).forEach(o=>{o.deviceId===e&&(Oa.forEach(s=>{s._setCurrentSpeaker(e),s.emit(se.DEVICE_CHANGED,{type:"speaker",action:"active",device:o})}),Rt=o)})})}static _addKVStat({type:e,key:r,value:o,base:s,useUV:n,version:d}){switch(d&&(Mo.version=d),e){case"count":Mo.addCount({key:r,useUV:n});break;case"enum":Mo.addEnum({key:r,value:o,useUV:n});break;case"number":Mo.addNumber({key:r,value:o,split:s});break}}};u(fe,"_loggerManager",$),u(fe,"EVENT",se),u(fe,"ERROR_CODE",ue),u(fe,"TYPE",nr),u(fe,"frameWorkType",30),X([Ye({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"}})})],fe.prototype,"use",1),X([Ut(bt.TRTC.enterRoom),Zi("room",([e],[r])=>(e.roomId||e.strRoomId)===(r.roomId||r.strRoomId)&&e.userId===r.userId&&e.sdkAppId===r.sdkAppId),Me(e=>function(r){return this._log.setUserId(r.userId),this._log.setSdkAppId(r.sdkAppId),e.call(this,r)}),Ye()],fe.prototype,"enterRoom",1),X([Ye()],fe.prototype,"exitRoom",1),X([Ut(bt.TRTC.switchRole),Jo("room",{merge:(e,r)=>r}),Ye()],fe.prototype,"switchRole",1),X([Ye()],fe.prototype,"destroy",1),X([Ut(bt.TRTC.startLocalAudio),Zi("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)}),Ye()],fe.prototype,"startLocalAudio",1),X([Ut(bt.TRTC.updateLocalAudio),Jo("audio",{debounce:{delay:200,getKey:()=>`${ug}-localAudio`,isNeedToDebounce:e=>{var r;return!V((r=e.option)==null?void 0:r.captureVolume)}}}),Ye()],fe.prototype,"updateLocalAudio",1),X([Ki("audio"),Ye()],fe.prototype,"stopLocalAudio",1),X([Ut(bt.TRTC.startLocalVideo),Zi("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)}),Ye()],fe.prototype,"startLocalVideo",1),X([Ut(bt.TRTC.updateLocalVideo),Jo("video"),Ye()],fe.prototype,"updateLocalVideo",1),X([Ki("video"),Ye()],fe.prototype,"stopLocalVideo",1),X([Ut(bt.TRTC.startScreenShare),Zi("screen",()=>!0),Ye()],fe.prototype,"startScreenShare",1),X([Ut(bt.TRTC.updateScreenShare),Jo("screen"),Ye()],fe.prototype,"updateScreenShare",1),X([Ye()],fe.prototype,"stopScreenShare",1),X([Ut(bt.TRTC.startRemoteVideo),Zi(e=>`v${e.userId}${e.streamType}`,()=>!0),Ye({getRemoteId:e=>`${e.userId}_${e.streamType}`})],fe.prototype,"startRemoteVideo",1),X([Ut(bt.TRTC.updateRemoteVideo),Jo(e=>`v${e.userId}${e.streamType}`),Ye({getRemoteId:e=>`${e.userId}_${e.streamType}`})],fe.prototype,"updateRemoteVideo",1),X([Ut(bt.TRTC.stopRemoteVideo),Me(e=>function(r){return y(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)})}),Ye({getRemoteId:e=>`${e.userId}_${e.streamType}`})],fe.prototype,"stopRemoteVideo",1),X([Ki(e=>`v${e.userId}${e.streamType}`)],fe.prototype,"_stopRemoteVideo",1),X([Ut(...bt.TRTC.muteRemoteAudio),Ye({getRemoteId:e=>e})],fe.prototype,"muteRemoteAudio",1),X([Xm(...bt.TRTC.setRemoteAudioVolume),ig(200,e=>e),Ye({getRemoteId:e=>e})],fe.prototype,"setRemoteAudioVolume",1),X([Jd("start"),Gi(e=>{var r;return(r=e.afterStart)==null?void 0:r.call(e)}),Zi((e,r)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(r)),Ye({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>bl[e.getName()],ignoreLog:e=>e.getName()==="Debug"})],fe.prototype,"startPlugin",1),X([Jd("update"),Jo((e,r)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(r)),Ye({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Rl[e.getName()]})],fe.prototype,"updatePlugin",1),X([Jd("stop"),Ki((e,r)=>{if(e.disableRandomCall)return null;let o=e.getGroup(r),s=e.getAlias();return o==="*"?new RegExp(`${s}.*`):s+o}),Ye({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>vl[e.getName()]})],fe.prototype,"stopPlugin",1),X([Xm(...bt.TRTC.enableAudioVolumeEvaluation)],fe.prototype,"enableAudioVolumeEvaluation",1),X([Ye()],fe.prototype,"getVideoSnapshot",1),X([Ye()],fe.prototype,"_setCurrentSpeaker",1),X([Zi(e=>`a${e.userId}`,()=>!0)],fe.prototype,"_startRemoteAudio",1),X([Me(e=>function(r){return y(this,null,function*(){return r.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(o=>this._stopRemoteAudio(Ee(ee({},r),{userId:o.userId})).catch(()=>{}))):e.call(this,r)})}),Ki(e=>`a${e.userId}`)],fe.prototype,"_stopRemoteAudio",1),X([Ki("room")],fe.prototype,"_exitRoom",1),X([Ki("screen")],fe.prototype,"_stopScreenShare",1),X([Ut(...bt.TRTC.sendSEIMessage),Hm({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...e)=>e[0].byteLength})],fe.prototype,"sendSEIMessage",1),X([Ut(bt.TRTC.sendCustomMessage),Hm({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],fe.prototype,"sendCustomMessage",1),X([Ut(bt.TRTC.create)],fe,"_create",1);var sp=fe,Zs=sp;var ru=class{constructor(t,e){u(this,"_flag");u(this,"terminalType");u(this,"userId");u(this,"tinyId");u(this,"role");u(this,"remoteAudioTrack");u(this,"remoteVideoTrack");u(this,"remoteAuxiliaryTrack");this.userId=e.userId||"",this.tinyId=e.tinyId||"",this.role=e.role||"audience",this.terminalType=e.terminalType,this.remoteAudioTrack=new $o(t,this),this.remoteVideoTrack=new Xi(t,this),this.remoteAuxiliaryTrack=new xd(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 Mn(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 np=class{constructor(){u(this,"_set",new Set);H.on(L.LEAVE_SUCCESS,this.delete,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))}};function eS(){return y(this,null,function*(){let i,t;try{let _=yield Jt();i=_&&_.length}catch(_){}try{let _=yield er();t=_&&_.length}catch(_){}let e={microphone:i,camera:t},{isH264EncodeSupported:r,isVp8EncodeSupported:o,isH264DecodeSupported:s,isVp8DecodeSupported:n}=this.checkSystemResult.detail,d=Bi.basis(),p={webRTC:d.isWebRTCSupported,getUserMedia:d.isGetUserMediaSupported,webSocket:d.isWebSocketsSupported,screenShare:d.isScreenShareSupported,webAudio:d.isWebAudioSupported,h264Encode:r,h264Decode:s,vp8Encode:o,vp8Decode:n},m={browser:d.browser,os:d.os,trtc:p,devices:e},g={isWebCodecSupported:d.isWebCodecSupported,isMediaSessionSupported:d.isMediaSessionSupported,isWebTransportSupported:d.isWebTransportSupported};Be.uploadEvent({log:`trtcstats-${JSON.stringify(m)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(m)}`),Be.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(g)}`,userId:this.userId})})}function mg(){return Me(i=>{let t=new np;return function(e,r,o){return y(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 he({code:te.INVALID_OPERATION,message:dt({key:ct.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:s,sdkAppId:this.sdkAppId,room:this}))throw new he({code:te.INVALID_OPERATION,message:dt({key:ct.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}`),H.emit(L.JOIN_START,{room:this,roomId:s,params:e});let n=Lr.getEnv();n||(n=zr.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(uc.OLD_CLOUD_LADDER)?n=zr.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(uc.WEBRTC)&&(n=zr.WEBRTC))),Be.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:s}),Bi.checkSystemRequirementsInternal().then(d=>{this.checkSystemResult=d,eS.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Lr.getEnv()&&(yield this.schedule(e,o));let d=yield i.call(this,e,r,o);return this.roomId=s,this._joinedTimestamp=Lr.performanceNow(),H.emit(L.JOIN_SUCCESS,{room:this}),o===30&&!e.component&&Be.uploadEvent({log:`stat-conv-${Number(Tr)}-${location.hostname}`,userId:this.userId}),d}catch(d){throw t.delete({room:this,roomId:s}),H.emit(L.JOIN_FAILED,{room:this,error:d}),d}})}})}var pg=()=>Me(i=>function(...t){return y(this,null,function*(){H.emit(L.LEAVE_START,{room:this}),yield i.call(this,...t),H.emit(L.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function hg(){return Me(i=>function(...t){return y(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(t=t.filter(r=>r.outMediaTrack&&r.state==="capture"),!t.length))return;H.emit("61",{room:this});let e=i.apply(this,t);return t.forEach(r=>r.publish(this,e)),e})})}function fg(){return Me(i=>function(...t){let e=i.apply(this,t);return t.forEach(r=>r.unpublish()),e})}function gg(){return Me(i=>function(...t){let e=i.apply(this,t);return t.forEach(r=>!r.isSubscribed&&r.subscribe(e)),e})}function tS({fn:i,context:t}){return function(...e){try{let r=i.apply(t,e);return xi(r)?r.catch(o=>$.error(`${i.name}() error observed ${o}`)):r}catch(r){$.error(`${i.name}() error observed ${r}`)}}}var iu=class{constructor(t){u(this,"_frameWorkType");u(this,"_component");u(this,"_language");u(this,"connectionType");u(this,"_room");u(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0});u(this,"_keyPrefix");u(this,"_log");u(this,"_intervalId");u(this,"_firstPublishedUserList");u(this,"_networkQuality");u(this,"_basicInfo");u(this,"_pathJoinRoom");u(this,"_pathLeaveRoom");u(this,"_pathMainVideoMap");u(this,"_pathMainAudioMap");u(this,"_pathAuxiliaryMap");u(this,"_remoteStreamStatMap");u(this,"_localStreamStat");u(this,"_eventMap",new Map);u(this,"_captureCostSum",0);u(this,"_captureCostCount",0);u(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=$.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(e=>{e.startsWith("handle")&&Xe(this[e])&&(this[e]=tS({fn:this[e],context:this}))}),this.initData(),this.installEvents()}initData(){this._firstPublishedUserList=[],this._networkQuality={totalUplinkRTT:0,totalUplinkLoss:0,count:0,totalDownlinkRTTAndLossMap:new Map},this._basicInfo={string_sdk_version:rt,uint32_os_type:15,string_device_name:"",string_http_user_agent:navigator.userAgent,string_os_version:"",uint32_avg_rtt:0,uint32_avg_up_loss:0,uint32_scene:this._room.scene==="live"?1:0,uint32_joining_duration:0,uint32_networkType:0,uint32_framework:this._frameWorkType,uint32_component:this._component,uint32_connection_type:this.connectionType,uint32_caller_coding_language:this._language,string_domain:location.hostname},this._pathJoinRoom={uint64_start_time:0,uint64_send_request_acc_ip_cmd_start_time:0,uint64_send_request_acc_ip_cmd_end_time:0,uint64_send_request_enter_room_cmd_start_time:0,uint64_send_request_enter_room_cmd_end_time:0,uint64_send_first_video_frame_time:0,uint64_recv_userlist_time:0,uint64_end_time:0,int32_send_request_acc_ip_cmd_ret:0,int32_send_request_enter_room_cmd_ret:0,int32_end_ret:0},this._pathLeaveRoom={uint64_start_time:0,uint64_send_request_exit_room_cmd_start_time:0,uint64_send_request_exit_room_cmd_end_time:0,uint64_end_time:0,int32_send_request_exit_room_cmd_ret:0,int32_end_ret:0},this._localStreamStat={totalVideoBitrate:0,totalVideoFPS:0,totalVideoHeight:0,totalVideoWidth:0,totalAudioLevel:0,videoCount:0,audioLevelCount:0,publishStartTime:0,statsToReport:{uint32_audio_capture_db:0,uint32_video_big_capture_fps:0,uint32_video_big_bitrate:0,uint32_video_big_resolution:0}},this._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,jn().then(t=>{this._basicInfo.string_os_version=bo(),t?this._basicInfo.string_device_name=t.mobile?t.model:this._basicInfo.string_os_version:this._basicInfo.string_device_name=this._basicInfo.string_os_version})}addEvent(t,e){return this._eventMap.set(t,e),H.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(L.JOIN_START,this.handleJoinStart).addEvent(L.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(L.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(L.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(L.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(L.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(L.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(L.JOIN_FAILED,this.handleJoinFailed).addEvent(L.LEAVE_START,this.handleLeaveStart).addEvent(L.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(L.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(L.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(L.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(L.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(L.PUBLISH_START,this.handlePublishStart).addEvent(L.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(L.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(L.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(L.PLAY_TRACK_START,this.handlePlayStart).addEvent(L.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(L.PLAYER_STATE_CHANGED,({track:t,state:e,type:r})=>{!t.isRemote||!this.hitTest(t.room)||e==="PLAYING"&&(r===D.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))}).addEvent(L.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(L.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(L.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(L.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,d=r.hasAuxiliary;!o&&n&&this.handleRemoteStreamAdded(r.userId,"main"),!s&&d&&this.handleRemoteStreamAdded(r.userId,"auxiliary")}).addEvent(L.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)=>H.off(e,t)),this._eventMap.clear()}destroy(){this.uninstallEvents(),At.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&&(V(t.params.frameWorkType)||(this._frameWorkType=t.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),V(t.params.component)||(this._component=t.params.component,this._basicInfo.uint32_component=this._component),V(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:d,request:p,response:m}=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=d,this._pathJoinRoom.int32_schedule_request=p,this._pathJoinRoom.int32_schedule_response=m}}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 he?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){this.hitTest(t.room)&&this._pathLeaveRoom.uint64_end_time===0&&(this._pathLeaveRoom.uint64_end_time=Date.now(),this._pathJoinRoom.uint64_end_time!==0?this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time:this._log.warn("pathJoinRoom endTime is 0"),this.report())}handleLeaveSendCMD(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())}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:Ee(ee({},rS),{msg_user_info:new xa({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:d}=e,p=new xa({userId:s,tinyId:n,role:d==="anchor"?20:21}),m=Date.now(),g=`${s}_${r}`,_=this._remoteStreamStatMap.get(g);_&&_.subscribeStartTime===0&&(_.subscribeStartTime=m),r==="main"?(e.muteState.hasVideo&&(o.video||o.smallVideo)&&!this._pathMainVideoMap.has(g)&&this._pathMainVideoMap.set(g,{statsToReport:{msg_user_info:p,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:s,sendSubscribeCMDTime:m}),e.muteState.hasAudio&&o.audio&&!this._pathMainAudioMap.has(g)&&this._pathMainAudioMap.set(g,{statsToReport:{msg_user_info:p,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:s,sendSubscribeCMDTime:m})):e.muteState.hasAuxiliary&&o.auxiliary&&!this._pathAuxiliaryMap.has(g)&&this._pathAuxiliaryMap.set(g,{sendSubscribeCMDTime:m})}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 d=r-this._pathJoinRoom.uint64_start_time;n.uint32_video_render_first=d,Y.addNumber({key:516820,value:d})}}(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 d=this._networkQuality.totalDownlinkRTTAndLossMap.get(o);if(d)d.totalRTT+=e,d.totalLoss+=r,s&&(d.totalVideoDelay=(d.totalVideoDelay||0)+s,d.videoDelayCount=(d.videoDelayCount||0)+1),n&&(d.totalAudioDelay=(d.totalAudioDelay||0)+n,d.audioDelayCount=(d.audioDelayCount||0)+1),d.count++;else{let p,m,g,_;s&&(m=s,g=1),n&&(p=n,_=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(o,{totalRTT:e,totalLoss:r,count:1,totalAudioDelay:p,totalVideoDelay:m,audioDelayCount:_,videoDelayCount:g})}}))}handleHeartbeatStats(t){if(this.hitTest(t.room)){let{msg_device_info:e,msg_up_stream_info:r,msg_down_stream_info:o}=t.report;if(r.msg_video_status[0]){let{uint32_video_codec_bitrate:s,uint32_video_enc_fps:n,uint32_video_width:d,uint32_video_height:p}=r.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=s,this._localStreamStat.totalVideoFPS+=n,this._localStreamStat.totalVideoWidth+=d,this._localStreamStat.totalVideoHeight+=p,this._localStreamStat.videoCount++}if(r.msg_audio_status){let{uint32_audio_level:s}=r.msg_audio_status;Math.floor(s/oi*100)>0&&(this._localStreamStat.totalAudioLevel+=s/oi,this._localStreamStat.audioLevelCount++)}o.forEach(s=>{let{msg_user_info:n,msg_audio_status:d,msg_video_status:p}=s,m=n.str_identifier,g=this._room.remotePublishedUserMap.get(m);if(p.forEach(_=>{let b=_.uint32_video_stream_type===2,N=_.uint32_video_stream_type===7,k=`${m}_${b?"main":"auxiliary"}`,P=this._remoteStreamStatMap.get(k);if(P&&(b&&(g!=null&&g.remoteVideoTrack.isSubscribed)||N&&(g!=null&&g.remoteAuxiliaryTrack))){P.totalVideoFPS+=_.uint32_video_receive_fps,P.totalVideoBitrate+=_.uint32_video_codec_bitrate,P.videoCount++,P.statsToReport.uint32_video_width===0&&(P.statsToReport.uint32_video_width=_.uint32_video_width),P.statsToReport.uint32_video_height===0&&(P.statsToReport.uint32_video_height=_.uint32_video_height);let x=b?g.remoteVideoTrack:g.remoteAuxiliaryTrack;x.stat.jitterBufferDelay&&(P.videoJitterBufferDelay=x.stat.jitterBufferDelay),x.stat.framesReceived&&(P.statsToReport.uint32_video_consume_render_rate=Math.floor(x.stat.framesDecoded/x.stat.framesReceived*En(10,6)))}}),!fs(d)){let _=`${m}_main`,b=this._remoteStreamStatMap.get(_);this._remoteStreamStatMap.has(_)&&b&&g!=null&&g.remoteAudioTrack.isSubscribed&&(b.totalAudioBitrate+=d.uint32_audio_codec_bitrate,b.audioCount++,g.remoteAudioTrack.stat.jitterBufferDelay&&(b.audioJitterBufferDelay=g.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(d.uint32_audio_level/oi*100)>0&&(b.totalAudioLevel+=d.uint32_audio_level/oi,b.audioLevelCount++))}}),e.uint32_audio_capture_cost&&(this._captureCostSum+=e.uint32_audio_capture_cost,this._captureCostCount+=1,this._captureCostCount>=100&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0))}}handlePublishStart({room: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 he?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&ls)>=0}hasAudioFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&ms)>=0}hasAuxFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&yn)>=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:g,count:_,audioDelayCount:b,videoDelayCount:N,totalAudioDelay:k,totalVideoDelay:P}=o;t.statsToReport.uint32_avg_down_loss=Math.floor(g/_),b&&k&&(t.statsToReport.uint32_audio_network_p2p_delay=Math.floor(k/b),t.audioJitterBufferDelay&&(t.statsToReport.uint32_p2p_delay=Math.floor(t.statsToReport.uint32_audio_network_p2p_delay+t.audioJitterBufferDelay))),N&&P&&(t.statsToReport.uint32_video_network_p2p_delay=Math.floor(P/N))}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,D.AUDIO),t.statsToReport.uint32_video_play_time=s.getDuration(e,D.VIDEO)),t.statsToReport.uint32_video_render_first&&(t.statsToReport.uint32_video_render_first=Math.min(t.statsToReport.uint32_video_render_first,Xo));let{badCaseDetector:n}=this._room,{dataFreeze:d,count:p}=n.getDataFreezeDuration(e),{renderFreeze:m}=n.getRenderFreezeDuration(e);t.statsToReport.uint32_video_block_count=p,t.statsToReport.uint32_video_block_time=Math.min(d,t.statsToReport.uint32_video_play_time),t.statsToReport.uint32_video_external_block_time=Math.min(m,t.statsToReport.uint32_video_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>Xo&&(t.statsToReport.uint64_play_first_frame_time=t.statsToReport.uint64_start_enter_time+Xo)}),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>Xo&&(t.statsToReport.uint64_render_first_frame_time=t.statsToReport.uint64_start_enter_time+Xo)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>Xo&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+Xo)}getReportData(){this._basicInfo.uint32_networkType=fc();let t={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new xa({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:gs(this._signalInfo.relayIp),uint32_client_ip:gs(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*En(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:gs(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,bytes_report_buf_from_0x1:this._signalInfo.endReportExtend};return On(t),t}report(){return y(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 y(this,null,function*(){if(t.msg_path_enter_room.uint64_start_time===0)return;let e=Number(this._room.sdkAppId),r=yield Wu(t),o=r instanceof ArrayBuffer,s=`${Yr(e,Oi.KEY_POINT)}&gzip=${+o}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(s,r));let d=[this.uploadKVStat(Y),this.uploadKVStat(Mo)];n||d.push(Zr({url:s,body:r,priority:"low"})),yield Promise.all(d)})}setConnectionType(t){this.connectionType=t,this._basicInfo.uint32_connection_type=t}uploadKVStat(t){return y(this,null,function*(){let e=t.getReportData();if(e.stats_count.length===0&&e.stats_distribution.length===0)return;e.msg_sdk_basic_info=Ee(ee({},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=yield Wu(e),o=`${Yr(+this._room.sdkAppId,Oi.KV_STAT)}&gzip=${+(r instanceof ArrayBuffer)}`,s=!1;navigator.sendBeacon&&(s=navigator.sendBeacon(o,r)),s||Zr({url:o,body:r})})}};X([Hi({settings:{timeout:500,retries:3}})],iu.prototype,"upload",1);var Xo=5e3,rS={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},xa=class{constructor(t){u(this,"str_identifier");u(this,"str_tinyid");u(this,"uint32_role");this.str_identifier=String(t.userId),this.str_tinyid=String(t.tinyId||0),this.uint32_role=t.role}},Eg=iu;var ap=class{constructor(){u(this,"_startTime");u(this,"_endTime");this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=_e())}stop(){this._endTime===0&&(this._endTime=_e())}getDuration(){return this._endTime===0?_e()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},ou=ap;var cp=class{constructor(t){u(this,"_room",null);u(this,"_durationMap");u(this,"_eventMap",new Map);this._room=t.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(L.REMOTE_TRACK_SUBSCRIBED,this.handleSubscribed).set(L.REMOTE_TRACK_UNSUBSCRIBED,this.handleUnsubscribed).set(L.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`,D.AUDIO),e.hasVideo&&!r.hasVideo&&this.stopDurationItem(`${o}_main`,D.VIDEO),e.hasAuxiliary&&!r.hasAuxiliary&&this.stopDurationItem(`${o}_auxiliary`,D.VIDEO);let s=(n=this._room)==null?void 0:n.remotePublishedUserMap.get(o);s&&(!e.hasAudio&&r.hasAudio&&s.remoteAudioTrack.isSubscribed&&this.addDuractionItem(o,D.AUDIO,"main"),!e.hasVideo&&r.hasVideo&&s.remoteVideoTrack.isSubscribed&&this.addDuractionItem(o,D.VIDEO,"main"),!e.hasAuxiliary&&r.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(o,D.VIDEO,"auxiliary"))}),this._eventMap.forEach((t,e)=>H.on(e,t,this))}uninstallEvents(){this._eventMap.forEach((t,e)=>H.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 ou,n=this._durationMap.get(o);n?this.isRecording(n[e])||n[e].push(s):this._durationMap.set(o,{userId:t,type:r,audio:e===D.AUDIO?[s]:[],video:e===D.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()}},_g=cp;var dp=class{constructor(t){u(this,"_room");u(this,"_renderFreezeMap",new Map);u(this,"_isVideoPlayingEventFiredMap",new Map);u(this,"_dataFreezeMap",new Map);u(this,"_monitorFreezeData",new Map);u(this,"_eventMap",new Map);this._room=t.room,this.installEvents()}getRenderFreezeMap(){return this._renderFreezeMap}getDataFreezeMap(){return this._dataFreezeMap}installEvents(){this._eventMap.set(L.LEAVE_SUCCESS,({room:t})=>{this.hitTest(t)&&this.stop()}).set(L.PLAY_TRACK_START,this.onPlayTrackStart).set(L.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(L.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(L.PLAYER_STATE_CHANGED,({track:t,state:e,reason:r,type:o})=>{if(!(!t.isRemote||!t.room||!this.hitTest(t.room)||o!==D.VIDEO)){if(e==="PLAYING"){let s=`${t.userId}_${t.streamType}`;this._isVideoPlayingEventFiredMap.set(s,!0)}r===D.MUTE?this.onVideoTrackMuted(t):r===D.UNMUTE&&this.onVideoTrackUnmuted(t)}}).set(L.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach((t,e)=>H.on(e,t,this))}uninstallEvents(){this._eventMap.forEach((t,e)=>H.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 ou;s?s.durationItemList.push(n):this._dataFreezeMap.set(o,{userId:e,type:r,durationItemList:[n],isFreezing(){let d=this.durationItemList[this.durationItemList.length-1];return d&&d.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}){this.hitTest(t)&&e.msg_down_stream_info.forEach(r=>{let o=this._room.remotePublishedUserMap.get(r.msg_user_info.str_identifier);if(!o)return;let{userId:s,muteState:n}=o;r.msg_video_status.forEach(d=>{d.uint32_video_stream_type===2&&n.hasVideo&&!n.videoMuted&&o.remoteVideoTrack.isSubscribed&&this.handleRenderFreeze({userId:s,fps:d.uint32_video_dec_fps,type:"main"}),d.uint32_video_stream_type===7&&n.hasAuxiliary&&o.remoteAuxiliaryTrack.isSubscribed&&this.handleRenderFreeze({userId:s,fps:d.uint32_video_dec_fps,type:"auxiliary"})})})}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();n>pc?this._monitorFreezeData.set(t,{userId:e,type:r,duration:n}):o.durationItemList.pop()}getTotalDuration(t){return t.reduce((e,r)=>{let o=r.getDuration();return e+Math.min(o,5e3)},0)}handleRenderFreeze(o){return y(this,arguments,function*({userId:t,fps:e,type:r}){let s=`${t}_${r}`,n=this._renderFreezeMap.get(s);if(e<=2){let d=_e();n&&!n.isFreeze&&(n.freezeTimeline.push({startTime:d,endTime:0}),n.isFreeze=!0),n||this._renderFreezeMap.set(s,{userId:t,type:r,isFreeze:!0,freezeTimeline:[{startTime:d,endTime:0}],renderFreezeTotal:0})}else if(n&&n.isFreeze){n.isFreeze=!1;let d=n.freezeTimeline.pop();if(d){d.endTime=_e();let p=d.endTime-d.startTime;n.freezeTimeline.push(d),n.renderFreezeTotal+=Math.min(5e3,p)}}})}onPlayTrackStart({track:t}){if(!t.isRemote||!this.hitTest(t.room)||t.kind!==D.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()<pc&&r.durationItemList.pop()}e.dataFreeze=this.getTotalDuration(r.durationItemList),e.count=r.durationItemList.length}return e}getRenderFreezeDuration(t){let e=this._renderFreezeMap.get(t),r=0,o=0;if(e)if(!e.isFreeze)r=e.renderFreezeTotal;else{let s=_e(),n=e.freezeTimeline[e.freezeTimeline.length-1],d=s-n.startTime;r=e.renderFreezeTotal+Math.min(d,5e3),o=e.freezeTimeline.length}return{renderFreeze:r,count:o}}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(t){return this._isVideoPlayingEventFiredMap.has(t)?!this._isVideoPlayingEventFiredMap.get(t):!1}resetMonitor(){this._monitorFreezeData.clear()}hitTest(t){return t===this._room}destroy(){this.uninstallEvents()}},Tg=dp;var Sg=Mi($i(),1);var iS=[1,0,0,0,1,1,0,1],su=class extends Bt{constructor(t,e){if(super(t,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"mirror",logger:e}),t instanceof Et)try{this.setTexBuffer(iS)}catch(r){t.destroy(new he({code:te.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${r.message||r}`}))}}draw2d(t,e,r,o,s){if(this.ctx2d){this.ctx2d.save(),this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0);let n=super.draw2d(t,e,r,o,s);return this.ctx2d.restore(),n}return!1}render(t){var e;return(e=this.input)!=null&&e.requestFrame(t)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}};var up=class{constructor(t,e){this.node=t;this.layout=e;u(this,"positionBuffer")}get x(){return this.layout.x||this.node.x}get y(){return this.layout.y||this.node.y}get width(){return this.layout.width||this.node.width}get height(){return this.layout.height||this.node.height}get right(){return this.x+this.width}get bottom(){return this.y+this.height}},nu=class extends Bt{constructor(e,r){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:r});u(this,"inputs",[])}addInput(e,r){if(this.inputs[r.zIndex])throw new Error("input already exists");let o=new up(e,r);this.inputs[r.zIndex]=o}resize(e,r){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 Et&&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.resize(0,0),e}removeInput(e){this.inputs[this.inputs.findIndex(r=>(r==null?void 0:r.node)===e)]=void 0}render(e){let r=this.context.ctx;if(r.clearColor(0,0,0,0),!this.inputs.reduce((s,n)=>(!n||!n.node.requestFrame(e))&&s,!0)&&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.reduce((o,s)=>(!s||!s.node.requestFrame(e))&&o,!0)&&this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height);for(let o=0;o<this.inputs.length;o++){let s=this.inputs[o];s&&this.draw2d(s.node.image,s.x,s.y,s.width,s.height)}return!0}return!1}getInfo(){let{totalFrames:e,x:r,y:o,width:s,height:n,name:d}=this,p=Date.now(),m=(e-this.lastInfo.totalFrames)/((p-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:r,y:o,width:s,height:n,timestamp:p,fps:m,name:d},ee({parent:this.inputs.filter(g=>g).map(g=>g.node.getInfo())},this.lastInfo)}close(){super.close(),this.inputs.forEach(e=>{var r,o;if(e&&((r=e.node)==null||r.disconnect(),e.positionBuffer&&this.context instanceof Et))try{(o=this.context.ctx)==null||o.deleteBuffer(e.positionBuffer)}catch(s){}})}};var oS=`#version 300 es
|
|
101
101
|
in vec2 a_position;
|
|
102
102
|
in vec2 a_texCoord;
|
|
103
103
|
out vec2 v_texCoord;
|
|
@@ -113,7 +113,7 @@ in vec2 v_texCoord;
|
|
|
113
113
|
out vec4 outColor;
|
|
114
114
|
void main() {
|
|
115
115
|
outColor = vec4(texture(u_texture, v_texCoord).rgb, texture(mask, v_texCoord).a);
|
|
116
|
-
}`,
|
|
116
|
+
}`,au=class extends pi{constructor(e,r){super(e,r.input,{name:"vb",create2d:!1,useDefaultProgram:!1,useFbo:!1,createTexture:!0,logger:e.log});u(this,"_bgTexture");u(this,"_waterMarkTexture");u(this,"_lastMaskTexture");u(this,"_lastMaskFbo");u(this,"_textureValid",!1);u(this,"_selfieTextureValid",!1);u(this,"_selfieSegmentation");u(this,"wasm");u(this,"_prePrograme");u(this,"_segmentationMask");u(this,"_weixin",!1);r.selfieSegmentation&&(this._selfieSegmentation=r.selfieSegmentation,this._selfieSegmentation.onResults=this.onPredict.bind(this));try{this.init(r)}catch(o){e.log.error(o),e.destroy(new he({code:te.VIDEO_MANAGER_ERROR,extraCode:6,message:`init vb node error ${o.message||o}`}))}}init(e){let r=e.Wasm,o=this.context.ctx;if(this.wasm=new r.AllIn1(o),this.wasm.blurRadius=e.blurRadius||3,this.wasm.mirror=!!e.mirror,this.wasm.vbMode=e.bg==="blur"?1:e.bg instanceof HTMLImageElement?2:e.bg==="green"?3:0,e.waterMark){let{x:s,y:n,width:d,height:p}=e.waterMark;this.wasm.setWaterMark(s,n,d,p)}if(e.beautyParams){let{beauty:s,brightness:n,ruddy:d}=e.beautyParams;this.wasm.setBeauty(s,n,d,e==null?void 0:e.width,e==null?void 0:e.height)}if(this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),o.uniform1i(o.getUniformLocation(this.program,"mask"),1),e.bg instanceof HTMLImageElement&&(o.uniform1i(o.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(e.bg)),e.waterMark&&(o.uniform1i(o.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(e.waterMark.image)),o.uniform1i(o.getUniformLocation(this.program,"lastMask"),4),this._weixin){let s=this.context.createShader(o.FRAGMENT_SHADER,sS),n=this.context.createShader(o.VERTEX_SHADER,oS);this._prePrograme=this.context.createProgram(n,s),o.useProgram(this._prePrograme),this.setAttributes(this.positionBuffer,this.texCoordBuffer),o.uniform1i(o.getUniformLocation(this._prePrograme,"mask"),1)}}onPredict(e){var o;let r=this.context.ctx;this._weixin&&(this._lastMaskTexture||(this._lastMaskTexture=this.createTexture(this.image),this._lastMaskFbo=this.createFramebuffer(this._lastMaskTexture))),this.useProgram(),this._weixin?this.useTexture():this==null||this._selfieSegmentation.bindTexture(),r.activeTexture(r.TEXTURE1),(o=this._selfieSegmentation)==null||o.bindTexture2d(e),r.activeTexture(r.TEXTURE2),r.bindTexture(r.TEXTURE_2D,this._bgTexture||null),r.activeTexture(r.TEXTURE3),r.bindTexture(r.TEXTURE_2D,this._waterMarkTexture||null),this.useBufferFrame(),r.drawArrays(r.TRIANGLE_STRIP,0,4),this._segmentationMask=e,this.totalFrames++}render(e){var p,m,g,_;let r=this.context.ctx,{image:o}=this;this.tryVideoFrameCallback(o);let{videoWidth:s,videoHeight:n}=o;if(s===0||n===0)return!1;o.width=s,o.height=n;let d=!1;if(this.totalFrames)this._weixin?this.useTexture():(p=this._selfieSegmentation)==null||p.bindTexture(),d=this._selfieTextureValid,this._selfieTextureValid=!0;else{if(this.program)this.useTexture();else return!1;d=this._textureValid,this._textureValid=!0}return this.width!==s||this.height!==n||!d?(this.resize(s,n),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,r.RGBA,r.UNSIGNED_BYTE,o)):r.texSubImage2D(r.TEXTURE_2D,0,0,0,r.RGBA,r.UNSIGNED_BYTE,o),this._weixin&&(r.useProgram(this._prePrograme),this.useTexture(),this._segmentationMask&&(r.activeTexture(r.TEXTURE1),(m=this._selfieSegmentation)==null||m.bindTexture2d(this._segmentationMask),r.bindFramebuffer(r.FRAMEBUFFER,this._lastMaskFbo||null)),r.drawArrays(r.TRIANGLE_STRIP,0,4),(g=this._selfieSegmentation)==null||g.bindTexture(),this._segmentationMask?r.copyTexSubImage2D(r.TEXTURE_2D,0,0,0,0,0,s,n):r.copyTexImage2D(r.TEXTURE_2D,0,r.RGBA,0,0,s,n,0)),(_=this._selfieSegmentation)==null||_.send(s,n),this.totalFrames||(r.activeTexture(r.TEXTURE2),r.bindTexture(r.TEXTURE_2D,this._bgTexture||null),r.activeTexture(r.TEXTURE3),r.bindTexture(r.TEXTURE_2D,this._waterMarkTexture||null),r.drawArrays(r.TRIANGLE_STRIP,0,4)),!1}close(){var r;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),(r=this.wasm)==null||r.close()}};var cu=class extends Bt{constructor(e){super(e,{name:"yuv-source",useDefaultProgram:!1,create2d:!1,useFbo:!1,createTexture:!1,logger:e.log,fragmentShaderSource:`
|
|
117
117
|
precision highp float;
|
|
118
118
|
uniform sampler2D ySampler;
|
|
119
119
|
uniform sampler2D uSampler;
|
|
@@ -138,4 +138,4 @@ void main() {
|
|
|
138
138
|
void main() {
|
|
139
139
|
gl_Position = vertexPos;
|
|
140
140
|
textureCoord = texturePos;
|
|
141
|
-
}`});u(this,"yTextureRef");u(this,"uTextureRef");u(this,"vTextureRef");u(this,"Y");u(this,"U");u(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 dp=[i=>{i.codec="avc1.420028"},i=>{delete i.hardwareAcceleration}],fg=(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")},nS=0,cu=class{constructor(t){u(this,"id",nS++);u(this,"trackDoneOB");u(this,"startOB");u(this,"stopOB");u(this,"decoder");u(this,"videoContext");u(this,"gop",0);u(this,"gop_helper",0);u(this,"waitFirstKeyFrame",!0);u(this,"startTimestamp",0);u(this,"startTime",0);u(this,"startPerformanceTime",0);u(this,"inputFrameCount",0);u(this,"decodedFrameCount",0);u(this,"downgradeLevel",0);u(this,"config");u(this,"gop_before_configure",[]);u(this,"videoElement");u(this,"type","wasm");u(this,"goodType","webCodecs");u(this,"renderer","2d");u(this,"wasmOption");u(this,"createDecoder");u(this,"_decodeSink");u(this,"isReported",!1);u(this,"track");u(this,"stateChangeOB");u(this,"failedReason");let{track:e,createDecoder:r}=t;if(this.stateChangeOB=Ct(),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=Ne(e.availableState,ne.OFF),this.stopOB=Ct(this.trackDoneOB),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),ve(this.stateChangeOB,wm((o,s)=>(o!==s&&e.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:this.failedReason,prevState:o,state:s}),s),"INITIALIZED"),Qe(this.stopOB),Ve()),this.start()}start(t=0){this.waitFirstKeyFrame=!0,this.stateChangeOB.next("STARTING");let e=ve(this.pipe(this.track),Qe(this.stopOB),di());ve(e,Ve(()=>{this.track.stat.framesDecoded++},r=>{if(this.track.log.error(`${this.id} play failed: ${r} retryCount: ${t}`),Y.addFailedEvent({key:fg(this.type,this.renderer),error:r}),t>4)this.failedReason=r,this.stateChangeOB.next("FAILED");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`),Y.addSuccessEvent({key:fg(this.type,this.renderer)}),Y.addSuccessEvent({key:514704})})),ve(e,yr(1),Ve(()=>{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"&&!Nl()&&(this.renderer="2d"),this.wasmOption.yuvMode=this.renderer==="webgl"}decode(t,e=!1){var n;if(this.failedReason)return;let r=new Uint8Array(t.data)[4]&31,o=!1;switch(r){case 5:case 7:o=!0;break}if(this.inputFrameCount++,((n=this.decoder)==null?void 0:n.state)!=="configured")return this.track.log.debug(`not configured ${this.inputFrameCount}`),o&&(this.gop_before_configure=[]),this.gop_before_configure.push(Z({},t)),t;this.gop_before_configure.length>0&&!e&&(this.gop_before_configure.forEach(d=>{this.decode(d,!0)}),this.gop_before_configure=[]);let{timestamp:s}=t;if(o?(this.gop=this.gop_helper,this.gop_helper=0):this.gop_helper++,this.decoder){if(this.waitFirstKeyFrame)if(o)this.waitFirstKeyFrame=!1,this.startTimestamp=s,this.startTime=Date.now(),this.startPerformanceTime=_e();else{this.track.log.debug(`wait first key frame ${this.inputFrameCount}`);return}let d=(s-this.startTimestamp)/90,m=Date.now()-this.startTime-d,E=m<500?0:m/1e3>>0;switch(o&&(E>0?this.downgradeLevel++:this.downgradeLevel>3&&this.downgradeLevel--),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.inputFrameCount<10&&this.track.log.debug(`decode ${this.inputFrameCount} ${this.downgradeLevel} ${this.gop_helper} ${this.gop}`),this.decoder.decode(t);return}return t}pipe(t){return e=>y(this,null,function*(){this._decodeSink=e,e.defer(()=>{var s,n;(s=this.decoder)==null||s.close(),(n=this.videoContext)==null||n.destroy(),delete this._decodeSink});let{renderer:r,type:o}=this;t.log.info(`decoder type: ${this.type} renderer: ${this.renderer}`);try{switch(o){case"wasm":this.decoder=this.createDecoder(o,this.wasmOption);break;case"webCodecs":for(let s=0;s<=dp.length;s++){let{supported:n}=yield VideoDecoder.isConfigSupported(this.config);if(n)break;if(s===dp.length){e.error(3);return}dp[s](this.config)}this.decoder=this.createDecoder(o);break;case"mse":throw new Error("not supported yet")}if(this.decoder.on("videoFrame",s=>{this.decodedFrameCount++,e.next(s)}),this.decoder.on("error",s=>{t.log.error(s),e.error(o==="webCodecs"?4:8)}),yield this.decoder.initialize(this.videoElement),this.decoder.configure(this.config),o==="wasm"&&r==="webgl"){this.videoContext=new yt({frameRate:15,logger:t.log,name:t.userId}),this.videoContext.create(),this.videoContext.on(yt.UNAVAILABLE,n=>{t.log.error(n),e.error(7)});let s=new au(this.videoContext);this.decoder.on("videoCodecInfo",n=>s.resize(n.width,n.height)),this.decoder.on("videoFrame",n=>{[s.Y,s.U,s.V]=n,this.downgradeLevel===1?this.decodedFrameCount%2===0&&s.render(this.decodedFrameCount):s.render(this.decodedFrameCount)}),t.source=s,t.player.setCanvas(this.videoContext._canvas,2)}else if(r==="videoFrame"){t.player.setCanvas();let s=new MediaStreamTrackGenerator({kind:"video"}),n=s.writable.getWriter();t.setInputMediaStreamTrack(s);let d=0;this.decoder.on("videoFrame",p=>{d++,d<=10&&t.log.info(`Frame ${d} decoded width: ${p.displayWidth} height: ${p.displayHeight}`),n.write(p)}),e.defer(()=>s.onmute=null)}else{this.videoContext=new kt({frameRate:15,logger:t.log,name:t.userId}),this.videoContext.create({alpha:!1});let s=this.videoContext.createVideoImageSource();this.decoder.on("videoFrame",d=>{s.image=d,s.update()});let n=new Wo(this.videoContext,{name:"remotePlayer",logger:t.log});s.connect(n),t.source=s,t.player.setCanvas(this.videoContext._canvas,2)}}catch(s){t.log.error(s),e.error(o==="webCodecs"?2:6)}})}};var ka=class extends gg.EventEmitter{constructor(e){super();this.room=e;u(this,"videoContext");u(this,"_glVideoContext");u(this,"_2dVideoContext");u(this,"destination");u(this,"smallVideoContext");u(this,"smallDestination");u(this,"smallTrackSource");u(this,"smallImageSource");u(this,"_isMirror",!1);u(this,"cameraTrack");u(this,"cameraNode");u(this,"mirrorNode");u(this,"mixNode");u(this,"screenTrack");u(this,"screenNode");u(this,"selfModel",!1);u(this,"blurRadius",3);u(this,"arTrack");u(this,"Wasm");u(this,"waterMarkNode");u(this,"_waterMarkOption");u(this,"watermarkImageList",[]);u(this,"_beautyParams");u(this,"isUsingArTrack",!1);u(this,"_isMixScreen",!1);u(this,"_virtualBackground");u(this,"_virtualBackgroundAbortCallback");u(this,"virtualBackgroundInstance");u(this,"_bgAssetPath");u(this,"log",B.createLogger({id:"vm"}));u(this,"_checkId",0);u(this,"_use2d",!1);u(this,"_autoSwitchRenderMode",!0);u(this,"_selfieSegmentation");u(this,"encodePipeline",[]);u(this,"decodePipeline",[]);e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new kt({frameRate:15,logger:this.log,name:"s"}),this.enablePrintDetail()}get _hasVirtualBg(){return!!this._virtualBackground}get _hasWaterMark(){return this.watermarkImageList.length>0}get renderMode(){return this._autoSwitchRenderMode?"auto":this._use2d?"2d":"webgl"}set renderMode(e){if(this._autoSwitchRenderMode=e==="auto",this._autoSwitchRenderMode)return;let r=e==="2d";this._use2d!==r&&(this._use2d=r,this.clear(),this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.update())}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new kt({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this._2dVideoContext}getGlVideoContext(){if(!this._glVideoContext)this._glVideoContext=new yt({frameRate:15,logger:this.log,name:"m"});else if(this._glVideoContext.available)return this._glVideoContext;return this.initializeGlVideoContext(),this._glVideoContext}initializeGlVideoContext(){try{this._glVideoContext.create(),this._glVideoContext.on("unavailable",e=>{var 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)}}enablePrintDetail(e=2e3){this._checkId=St.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(),St.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(xi||this._isMixScreen||this._isMirror||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}sendCreateResult(e="videoCtxGl",r){let o=e==="videoCtxGl"?512700:512701;r?Y.addFailedEvent({key:o,error:r}):Y.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 yt({frameRate:15,logger:this.log,name:"m"}),this.initializeGlVideoContext(),this._glVideoContext.available)return this.videoContext=this._glVideoContext,this.videoContext.available;this.log.warn("webgl is still not available"),this.clear(),this._use2d=!0}return this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.videoContext.available}get smallTrack(){var e;return(e=this.smallDestination)==null?void 0:e.videoTrack}get hasSmall(){return!!this.smallTrack}get initialTrack(){var e;return(e=this.cameraTrack)==null?void 0:e.mediaTrack}initVirtualBackground(e){return this._selfieSegmentation=e,this._selfieSegmentation.changeModel()}_setMainOutput(e){var r;try{let o=this.cameraTrack,{small:s,settings:n,player:d}=o;s?(this.smallVideoContext.available||(this.smallVideoContext.create({alpha:!1}),this.smallDestination=new Pd(this.smallVideoContext,s,this.log)),this.smallVideoContext.frameRate=s.frameRate,this.smallDestination.resolution=s,e?(this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=e:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(e),this.smallImageSource.connect(this.smallDestination))):(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource?this.smallTrackSource.replaceTrack(this.initialTrack):(this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack,"smallTrackSource"),this.smallTrackSource.width=n.width,this.smallTrackSource.height=n.height,this.smallTrackSource.connect(this.smallDestination)))):this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource),xi&&d.setCanvas(e);let p=e&&((r=this.destination)==null?void 0:r.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),p=this.arTrack),this._selfieSegmentation&&e&&!this._use2d&&(this._selfieSegmentation._glName||this._selfieSegmentation.setCanvas(e)),this.log.info(`set main output ${p?p.label:"no output track"}`),o.setOutputMediaStreamTrack(p)}catch(o){this.log.error("set main output failed",o)}}update(){return y(this,null,function*(){var o,s;if(!this.cameraTrack||!this.cameraTrack.mediaTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:e,profile:r}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams?(this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log})),Qt===16?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof li?(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 li?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode.close(),delete this.cameraNode)),this.cameraNode||(this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraTrackSource"))):this.cameraNode?this.cameraNode.replaceTrack(this.initialTrack):this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraNodeSource"),this.cameraNode.resize(e.width,e.height)):(this.cameraNode&&this.cameraNode.close(),this.destination?this.destination.disableCheckMute():this.destination=new Od(this.videoContext,{name:"mainDestination",logger:this.log}),this.cameraNode=new nu(this.videoContext,{input:this.cameraTrack.mediaTrack,width:e.width,height:e.height,mirror:this._isMirror,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,beautyParams:this._beautyParams,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,selfieSegmentation:this._selfieSegmentation,Wasm:this.Wasm}),this.cameraNode.connect(this.destination),this.destination.enableCheckMute()),this.videoContext.frameRate=r.frameRate,this._use2d){let n=this.cameraNode;n.disconnect(),this._isMirror&&(this.mirrorNode||(this.mirrorNode=new ou(this.videoContext,this.log)),n=n.connect(this.mirrorNode),n.disconnect(),this.log.info("start mirror")),this.mixNode&&this.mixNode.close(),delete this.mixNode,(this._isMixScreen||this._hasWaterMark)&&(this.mixNode=new su(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),(o=this.waterMarkNode)==null||o.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&!this.screenNode&&(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource")),(s=this.screenNode)==null||s.connect(this.mixNode,{zIndex:0}),n=this.mixNode,this.log.info("start mix",`${this.mixNode.width}x${this.mixNode.height}`)),n.connect(this.destination)}return this.log.info(`update ${this._use2d?"2d":"webgl"}`),this._setMainOutput(this.videoContext._canvas)})}changeInput(e){var r,o,s,n;if(e instanceof Hi)return this.log.info("change screen input",(r=e.mediaTrack)==null?void 0:r.label),this.setScreenTrack(e);if(e instanceof Sr)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 d=e.mediaTrack;return e.setOutputMediaStreamTrack(d)}this.log.warn("change unknown input",(n=e.mediaTrack)==null?void 0:n.label)}removeInput(e){var r;e instanceof Hi?((r=this.screenNode)==null||r.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof Sr?(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()}setCameraTrack(e){return y(this,null,function*(){this.cameraTrack=e,this.update()})}setScreenTrack(e){return this.screenTrack=e,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)}getWatermarkImage(e,r){return y(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 he({code:te.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort((n,d)=>n.zIndex-d.zIndex),this.watermarkImageList.forEach(({image:n,x:d,y:p,width:m,height:E})=>{s.drawImage(n,d,p,m,E)}),Es(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)||((r==="mute"||r==="watermark")&&(this.watermarkImageList=this.watermarkImageList.filter(s=>s.type!==r)),this.watermarkImageList.push(e))}setBeautyParams(e){return y(this,null,function*(){this._beautyParams=e,this.update()})}stopBeauty(){return y(this,null,function*(){this._beautyParams=void 0,this.update()})}setWatermark(e){return y(this,null,function*(){var _,b;let r;try{r=yield Es((e==null?void 0:e.imageElement)||e.imageUrl)}catch(C){throw new he({code:te.INVALID_PARAMETER,message:`load image failed, url: ${e.imageUrl}`})}let{x:o=0,y:s=0,width:n=r.width,height:d=r.height,type:p="watermark",zIndex:m=2}=e;this.watermarkImageList.some(C=>C.type===p)?(this.watermarkImageList=this.watermarkImageList.filter(C=>C.type!==p),this.pushWaterMarkImageList({x:o,y:s,width:n,height:d,image:r,zIndex:m,type:p,imageUrl:e.imageUrl}),r=yield this.getWatermarkImage((_=this.cameraTrack)==null?void 0:_.settings.width,(b=this.cameraTrack)==null?void 0:b.settings.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:d,image:r,zIndex:m,type:p,imageUrl:e.imageUrl}),yield this.freshWatermark()),this.log.info("set watermark",JSON.stringify(this.watermarkImageList,(C,k)=>C==="imageUrl"?void 0:k))})}deleteWatermark(e="watermark"){return y(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 y(this,null,function*(){var r,o,s;(r=this.waterMarkNode)==null||r.close(),delete this.waterMarkNode,delete this._waterMarkOption;let e=yield this.getWatermarkImage((o=this.cameraTrack)==null?void 0:o.settings.width,(s=this.cameraTrack)==null?void 0:s.settings.height);this._waterMarkOption={x:0,y:0,width:e.width,height:e.height,image:e},this.update()})}setVirtualBackground(e){return y(this,null,function*(){if(!e)delete this._virtualBackground,delete this._virtualBackgroundAbortCallback;else{if(e.onAbort&&(this._virtualBackgroundAbortCallback=e.onAbort),this._use2d&&!this._autoSwitchRenderMode)return Promise.reject(new Error("not support virtual background in 2d mode"));this._bgAssetPath=e.assetPath,e.type==="image"?this._virtualBackground=yield Es(e.imageUrl):(this.blurRadius=e.blurLevel||this.blurRadius||3,this._virtualBackground=e.type)}if(this.log.info(`${this._virtualBackground?"start":"stop"} virtual background, ${(e==null?void 0:e.type)||""}, ${this.blurRadius||""}`),yield this.update(),this._virtualBackground&&!this._glVideoContext.available)throw new he({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._isMirror||((r=this.mirrorNode)==null||r.close(),delete this.mirrorNode),this.update())}get mirror(){return this._isMirror}enableAr(e){this.arTrack=e,this.isUsingArTrack=!0,this.update()}updateAr(){return y(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 cu(e)}clear(){var e;(e=this.videoContext)==null||e.disconnect(),delete this.destination,delete this.cameraNode,delete this.mirrorNode,delete this.screenNode,delete this.waterMarkNode}addEncodeProcessor({processor:e,type: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}};X([cf(function(e){this.log.error("update failed",e)})],ka.prototype,"update",1);var aS=0;var du=class extends ne{constructor(e){super("room");u(this,"seq",++aS);u(this,"sdkAppId");u(this,"userId");u(this,"userSig");u(this,"privateMapKey");u(this,"latencyLevel");u(this,"tinyId");u(this,"scene");u(this,"roomId");u(this,"useStringRoomId");u(this,"role","anchor");u(this,"joinParams",null);u(this,"localTracks",new Set);u(this,"enableAutoPlayDialog",!0);u(this,"autoReceiveAudio",!0);u(this,"autoReceiveVideo",!0);u(this,"proxy_ws");u(this,"proxy_wt");u(this,"proxy_unified");u(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}});u(this,"keyPointManager");u(this,"audioManager");u(this,"videoManager");u(this,"callDurationCalculator");u(this,"badCaseDetector");u(this,"scheduleResult",{domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null});u(this,"videoDecodeFallbackType");u(this,"_isUsingCachedSchedule",!1);u(this,"_log",B.createLogger({id:`r${this.seq}`}));u(this,"_joinedTimestamp",0);u(this,"_sdkType");u(this,"heartbeatReport");u(this,"quality");u(this,"enableSEI");u(this,"isDestroyed",!1);this.useStringRoomId=!!e.useStringRoomId,dt(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),dt(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),dt(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new mg({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new pg({room:this}),this.badCaseDetector=new hg({room:this}),this.audioManager=new Ed(this),this.videoManager=new ka(this)}get scriptTransformWorker(){}get isMainStreamPublished(){for(let e of this.localTracks)if(e.mediaType&4)return!0;return!1}get isAuxStreamPublished(){for(let e of this.localTracks)if(e.mediaType&2)return!0;return!1}get hasAuxStream(){for(let e of this.remotePublishedUserMap.values())if(e.muteState.hasAuxiliary)return!0;return this.isAuxStreamPublished}get localMainVideoTrack(){for(let e of this.localTracks)if(e.mediaType&4)return e;return null}get localAuxVideoTrack(){for(let e of this.localTracks)if(e.mediaType&2)return e;return null}getLogger(){return this._log}get isJoining(){return this.state.toString()==="joining"}get isJoined(){return this.state==="joined"}get isLeft(){return this.state==="left"}addTrack(e){return y(this,null,function*(){return this.publish(e)})}removeTrack(e){return y(this,null,function*(){return this.unpublish(e)})}replaceTrack(e){return y(this,null,function*(){})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(we(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(Gt(e)){let{websocketProxy:r,webtransportProxy:o,loggerProxy:s,scheduleProxy:n,unifiedProxy:d}=e;this.proxy_ws=r,this.proxy_wt=o,this.proxy_unified=d,d?(Hd([d,d]),po(`https://${d}`)):(s&&po(s),n&&Hd(n))}H.once(L.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:Rr.main,sched_back_domain:Rr.backup,signal_domain:this.proxy_ws||this.proxy_wt||""}))}getRemoteAudioStats(){return y(this,null,function*(){let e={};return this.remotePublishedUserMap.forEach(r=>{e[r.userId]=r.remoteAudioTrack.stat}),e})}getTransportStats(){return y(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 y(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 he({code:te.INVALID_OPERATION,message:at({key:nt.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(qt.INVALID_DESTROY),new he({code:te.INVALID_OPERATION,message:at({key:nt.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,H.emit(L.ROOM_DESTROY,{room:this})}schedule(e,r){return y(this,null,function*(){var s,n,d;let o=_e();try{let{isCached:p,result:m,detailCost:E}=yield jm({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:rt,userSig:this.userSig,role:this.scene==="live"?e.role:void 0,frameWorkType:r,latencyLevel:e.latencyLevel});this._isUsingCachedSchedule=p,this._log.info(`schedule cache:${+p} ${rr(m,{keysToExclude:["username","credential"]})}`),p&&H.once(L.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=Z(Z({},this.scheduleResult),m),je((s=m.config)==null?void 0:s.retryCount)&&Lu(m.config.retryCount),we((n=m.config)==null?void 0:n.loggerDomain)&&po(m.config.loggerDomain),this.videoDecodeFallbackType=((d=m.config)==null?void 0:d.videoDecodeFallback)||this.videoDecodeFallbackType,H.emit(L.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:E}),Y.addSuccessEvent({key:521700,cost:_e()-o,split:50})}catch(p){throw Y.addFailedEvent({key:521700,error:p}),p}})}sendAbilityStatus(e){}enableInsertableStreams(){return Promise.resolve()}};function Eg(i,t=!1){let e=Object.defineProperties(Ct(),{postMessage:{value:i.postMessage.bind(i)},port:{get(){return i},set(o){i.onmessage=Ue,i.onmessageerror=Ue,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 up=class extends de{constructor(t,e){super(t);let r=new de(t);r.next=Ue,e(r)}},X2=pe(up,"takeUntilComplete");var Nt={useWt:!0,useAINS:!0,useHardDecoder:"prefer-software",useHardEncoder:"prefer-software",unreliable:!1,debug:!1,assetsPath:"",enableUpload:!0},mp="__INLINE__WORKER__",_g="__INLINE__WASM__",{debug:Tg}=console;Nt.debug||(console.debug=()=>{});var lp=!mp.startsWith("__"),cS=!_g.startsWith("__");function Ig(){return`${Nt.assetsPath?`${Nt.assetsPath}/`:""}worker.js`}function Sg(){let i=Ig();return lp||i.startsWith("http")?URL.createObjectURL(new Blob([lp?atob(mp):`importScripts('${i}')`])):i}function yg(){let i=Ig();return lp?URL.createObjectURL(new Blob([atob(mp)],{type:"application/javascript"})):i.startsWith("http")?fetch(i).then(t=>t.blob().then(e=>URL.createObjectURL(e))):i}var La;function uu(){return y(this,null,function*(){let i=Nt.assetsPath?`${Nt.assetsPath}/`:"";return La||(cS?La=new TextEncoder().encode(atob(_g)).buffer:La=yield fetch(`${i}av_processing.wasm`).then(t=>t.arrayBuffer()),La)})}var pp=class{constructor(){u(this,"playPort");u(this,"playPortSent",!1);u(this,"worklet");u(this,"workletPromise")}init(){return this.workletPromise||(this.workletPromise=this._init()),this.workletPromise}_init(){return y(this,null,function*(){let t=et("player"),e=yg();try{yield t.audioWorklet.addModule(typeof e=="string"?e:yield e),B.info("global audio player worklet addModule success",e)}catch(r){throw B.error("global audio player worklet addModule failed:",r),r}return this.worklet=new AudioWorkletNode(t,"global-audio-player",{processorOptions:{wasm:yield uu(),flag:Nt},numberOfInputs:2}),B.info("global audio player worklet created",t.state),this.worklet.connect(t.destination),this.playPort=this.worklet.port,this.playPort})}playAudio(t){return y(this,null,function*(){this.playPortSent||(this.playPortSent=!0,t(yield this.init()))})}},lu=new pp;var hp=(()=>{if(typeof self=="undefined")return!1;if(!("top"in self&&self!==top)){if("showOpenFilePicker"in self)return"showOpenFilePicker"}return!1})(),i1=hp?Promise.resolve().then(function(){return mS}):Promise.resolve().then(function(){return _S});var o1=hp?Promise.resolve().then(function(){return hS}):Promise.resolve().then(function(){return IS});var dS=hp?Promise.resolve().then(function(){return gS}):Promise.resolve().then(function(){return yS});function fp(...i){return y(this,null,function*(){return(yield dS).default(...i)})}var uS=i=>y(void 0,null,function*(){let t=yield i.getFile();return t.handle=i,t}),lS=(...t)=>y(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(d=>{e[n].accept[d]=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(uS));return i[0].multiple?o:o[0]}),mS={__proto__:null,default:lS};function mu(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 mu=function(e){this.s=e,this.n=e.next},mu.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 mu(i)}var Ag=(o,s,...n)=>y(void 0,[o,s,...n],function*(i,t,e=i.name,r){let d=[],p=[];var m,E=!1,_=!1;try{for(var b,C=function(k){var x,P,J,Q=2;for(typeof Symbol!="undefined"&&(P=Symbol.asyncIterator,J=Symbol.iterator);Q--;){if(P&&(x=k[P])!=null)return x.call(k);if(J&&(x=k[J])!=null)return new mu(x.call(k));P="@@asyncIterator",J="@@iterator"}throw new TypeError("Object is not async iterable")}(i.values());E=!(b=yield C.next()).done;E=!1){let k=b.value,x=`${e}/${k.name}`;k.kind==="file"?p.push(k.getFile().then(P=>(P.directoryHandle=i,P.handle=k,Object.defineProperty(P,"webkitRelativePath",{configurable:!0,enumerable:!0,get:()=>x})))):k.kind!=="directory"||!t||r&&r(k)||d.push(Ag(k,t,x,r))}}catch(k){_=!0,m=k}finally{try{E&&C.return!=null&&(yield C.return())}finally{if(_)throw m}}return[...(yield Promise.all(d)).flat(),...yield Promise.all(p)]}),pS=(...t)=>y(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 Ag(e,i.recursive,void 0,i.skipDirectory)}),hS={__proto__:null,default:pS},fS=(s,...n)=>y(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 d=[],p=null;if(i instanceof Blob&&i.type?p=i.type:i.headers&&i.headers.get("content-type")&&(p=i.headers.get("content-type")),t.forEach((_,b)=>{d[b]={description:_.description||"Files",accept:{}},_.mimeTypes?(b===0&&p&&_.mimeTypes.push(p),_.mimeTypes.map(C=>{d[b].accept[C]=_.extensions||[]})):p?d[b].accept[p]=_.extensions||[]:d[b].accept["*/*"]=_.extensions||[]}),e)try{yield e.getFile()}catch(_){if(e=null,r)throw _}let m=e||(yield window.showSaveFilePicker({suggestedName:t[0].fileName,id:t[0].id,startIn:t[0].startIn,types:d,excludeAcceptAllOption:t[0].excludeAcceptAllOption||!1}));!e&&o&&o(m);let E=yield m.createWritable();return"stream"in i?(yield i.stream().pipeTo(E),m):"body"in i?(yield i.body.pipeTo(E),m):(yield E.write(yield i),yield E.close(),m)}),gS={__proto__:null,default:fS},ES=(...t)=>y(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(m=>m.mimeTypes||[]),...i.map(m=>m.extensions||[])].join();o.multiple=i[0].multiple||!1,o.accept=s||"",o.style.display="none",document.body.append(o);let n=m=>{typeof d=="function"&&d(),e(m)},d=i[0].legacySetup&&i[0].legacySetup(n,()=>d(r),o),p=()=>{window.removeEventListener("focus",p),o.remove()};o.addEventListener("click",()=>{window.addEventListener("focus",p)}),o.addEventListener("change",()=>{window.removeEventListener("focus",p),o.remove(),n(o.multiple?Array.from(o.files):o.files[0])}),"showPicker"in HTMLInputElement.prototype?o.showPicker():o.click()})}),_S={__proto__:null,default:ES},TS=(...t)=>y(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=d=>{typeof n=="function"&&n(),e(d)},n=i[0].legacySetup&&i[0].legacySetup(s,()=>n(r),o);o.addEventListener("change",()=>{let d=Array.from(o.files);i[0].recursive?i[0].recursive&&i[0].skipDirectory&&(d=d.filter(p=>p.webkitRelativePath.split("/").every(m=>!i[0].skipDirectory({name:m,kind:"directory"})))):d=d.filter(p=>p.webkitRelativePath.split("/").length===2),s(d)}),"showPicker"in HTMLInputElement.prototype?o.showPicker():o.click()})}),IS={__proto__:null,default:TS},SS=(e,...r)=>y(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(p,m){return y(this,null,function*(){let E=p.getReader(),_=new ReadableStream({start:k=>function x(){return y(this,null,function*(){return E.read().then(({done:P,value:J})=>{if(!P)return k.enqueue(J),x();k.close()})})}()}),b=new Response(_),C=yield b.blob();return E.releaseLock(),new Blob([C],{type:m})})}(i.body,i.headers.get("content-type"))),o.download=t.fileName||"Untitled",o.href=URL.createObjectURL(yield s);let n=()=>{typeof d=="function"&&d()},d=t.legacySetup&&t.legacySetup(n,()=>d(),o);return o.addEventListener("click",()=>{setTimeout(()=>URL.revokeObjectURL(o.href),3e4),n()}),o.click(),null}),yS={__proto__:null,default:SS};var gp=class{constructor(t){this.name=t;u(this,"ready");u(this,"worker");u(this,"ports");u(this,"ids",1);u(this,"transactions",new Map);u(this,"log");u(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){if(this.ready)return this.ready;t||(t=this.name),console.time(`createWorker_${t}`);let e=new Worker(Sg(),{name:t});return this.worker=e,this.ready=new Promise((r,o)=>y(this,null,function*(){e.onmessage=({data:{id:s,type:n,payload:d}})=>{var p;if(s)(p=this.transactions.get(s))==null||p(d),this.transactions.delete(s);else switch(n){case"error":console.timeEnd(`createWorker_${t}`),console.warn("worker error:",d),o(d);break;case"ready":console.timeEnd(`createWorker_${t}`),r(this);break;case"updateAFSM":if(d.value){let m=typeof d.old=="string"?d.old:`${d.old.action}ing`,E=typeof d.value=="string"?d.value:`${d.value.action}ing`;console.log(Ec(),d.group,d.name,m,"\u{1F449}",E)}break;case"log":console.log(d);break;case"glog":window.dispatchEvent(new CustomEvent(n,{detail:d}));break}},e.postMessage({wasm:yield uu(),flag:Nt},this.ports)}))}destroy(){var t;console.log("destroy worker",this.name),delete this.ready,(t=this.worker)==null||t.terminate()}},Ep=class{constructor(t,e,r){this.worker=t;u(this,"channel",new MessageChannel);u(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()}},_p=class i extends gp{constructor(){super("main");u(this,"switchValue",new Map);u(this,"extendChannel");u(this,"sessionCount",0)}setSwitchValue(e,r){var o;this.switchValue.set(e,r),(o=this.extendChannel)==null||o.port1.postMessage([e,r])}create(){return y(this,null,function*(){return this.ready?this.ready:(this.extendChannel=new MessageChannel,this.ports=[this.extendChannel.port2],yield Bt(i.prototype,this,"create").call(this),this.switchValue.forEach((e,r)=>{this.extendChannel.port1.postMessage([r,e])}),this)})}},Zi=new _p,Xo,AS=-1;function bg(i){return console.log(i),Xo.push(i.slice()),Xo.length>1e3&&Xo.shift(),i}function Rg(i){return y(this,null,function*(){switch(AS){case 0:this.edpl.willDecodeAudio=bg;break;case 2:this.edpl.didEncodeAudio=bg;break}yield Zi.create(),H.emit(L.JOIN_SEND_CMD,{room:this});let t=new Ep(Zi,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:d}=s;this.onWorkerEvent(n,d)}}),{err:e,data:r}=yield t.ready;if(typeof e=="number"){if(H.emit(L.JOIN_RECEIVED_CMD_RES,{room:this,code:e}),e===0)return Object.assign(this,r,{session:t});throw new he({code:te.JOIN_ROOM_FAILED,extraCode:Number(e),message:at({key:nt.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:e,errorMsg:""}})})}else throw e})}Object.defineProperties(window,{useAINS:{set:Tp},useWt:{set:bS},enableDebug:{set(i){console.debug=i?Tg:()=>{},Zi.setSwitchValue("enableDebug",i)}},useV2:{set:Ip},dump:{value(){if(Xo||(console.warn("dump audio will be activated at next time join room"),Xo=[]),!Xo.length){console.warn("no audio data to dump,try it later");return}let i=[];return Xo.forEach(t=>{i.push(new Uint16Array([t.length])),i.push(t)}),fp(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;Zi.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,Zi.extendChannel.port1.postMessage(["dump",i]),s.port2.close(),o(new Blob(e)))}});return fp(r,{fileName:i,extensions:[".pcm"]})}},hardDec:{set(i){switch(i){case!0:Nt.useHardDecoder="prefer-hardware";break;case!1:Nt.useHardDecoder="prefer-software";break;default:Nt.useHardDecoder="no-preference"}}}});function Tp(i){return y(this,null,function*(){Zi.setSwitchValue("useAINS",i)})}function Ip(i){return y(this,null,function*(){Zi.setSwitchValue("useV2",i)})}function bS(i){return y(this,null,function*(){Zi.setSwitchValue("useWt",i)})}function vg(i){let t=new MediaStreamTrackGenerator({kind:"audio"});i.setInputMediaStreamTrack(t),this.postMessage({cmd:"pullAudio",payload:{tinyId:i.tinyId,writable:t.writable}},[t.writable])}function Cg(i){return y(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),ve(Eg(r.port2),Qe(Ne(i,ne.INIT)),Ve(s=>{let{data:n,packetsReceived:d}=s;i.stat.packetsReceived=d,i.stat.framesReceived++,e++;let p=n[4]&31;if(e<=10){let E=Array.from(n.slice(0,10)).map(_=>_.toString(16).padStart(2,"0")).join(" ");this._log.info(`Frame ${e} - Size: ${n.length} bytes, Type: ${p}, Timestamp: ${Date.now()-t}ms First 10 bytes: ${E}`)}let m;switch(p){case 5:case 7:m="key";break;default:m="delta";break}i.isAvailable?i.decodeFrame({data:n.buffer,type:m,timestamp:(Date.now()-t)*1e3}):console.warn("track is not available")},()=>{},()=>{r.port2.postMessage(null),r.port2.close()}))})}var pu=[];function Dg(i){var p;let t=Ct();if(this.state!=="joined")throw new Error("Room is not joined");if(i.state==="publish")return;for(let m=0;m<=pu.length;m++)if(!pu[m]){pu[m]=this,this.index=m;break}let e=i.profile;this._log.info("start push audio",this.index,e);let r=new MessageChannel,o=i.enableEncodeFrame?new MessageChannel:null;(p=this.session)==null||p.postMessage({cmd:"pushAudio",payload:Z({index:this.index},e)},o?[r.port2,o.port2]:[r.port2]),r.port1.onmessage=m=>{m.data==null||(typeof m.data=="number"?t.next(m.data):o&&o.port1.postMessage(Ee(Z({},m.data),{data:new Uint8Array(i.encodeFrame({data:m.data.data.buffer,timestamp:m.data.timestamp}).data)})))};let s=new MediaStream,n,d=m=>{let E=s.getAudioTracks()[0];E&&(n.disconnect(),s.removeTrack(E)),s.addTrack(m),this._log.info("push audio track:",m.readyState,m.getSettings().deviceId),n=et("player").createMediaStreamSource(s),n.connect(lu.worklet,0,this.index)};ve(Ne(i,"output-media-track-changed"),Qe(Ne(i,"capture")),Ve(d,console.error,()=>{this._log.info("stop push audio",e),i.volume=0,n.disconnect(),pu[this.index]=null,o&&o.port1.postMessage(null),r.port1.postMessage(null)})),ve(t,Ia(m=>i.volume=m),Ho(Md(1e3)),Ve(()=>{i.volume=0})),d(i.outMediaTrack)}var V1=new Intl.DateTimeFormat("zh-CN",{dateStyle:"short",timeStyle:"medium"});var Sp=class{constructor(t,e,r,o){this.localTrack=t;this.type=e;this.config=r;this.port=o;u(this,"track");u(this,"label");u(this,"insertKeyFrame",!0);u(this,"encoder");u(this,"tsMap",new Map);t._log.info("create Video Encoder",r)}trans(t,e,r){let o=this.recreate(r);e.signal.addEventListener("abort",()=>{o.close()});let s=0;return t.pipeThrough(new TransformStream({transform:(n,d)=>{o.state==="configured"&&(this.tsMap.set(s,Date.now()),this.encode(n),s++,d.enqueue(n))}}),e)}encode(t){this.encoder.encode(t,{keyFrame:this.insertKeyFrame}),this.insertKeyFrame=!1}start(t,e,r){let o=this.recreate(r),s=0;t.pipeTo(new WritableStream({write:n=>{o.state==="configured"&&(s<10&&console.log(`capture ${this.label} track frame:`,s,Date.now(),n.timestamp,n.displayWidth,n.displayHeight),(n.displayWidth!==this.config.width||n.displayHeight!==this.config.height)&&(console.log("resize video track frame:",n.displayWidth,n.displayHeight,this.config.width,this.config.height),this.configure({width:n.displayWidth,height:n.displayHeight})),this.tsMap.set(s,Date.now()),this.encode(n),s<10&&console.log(`encode ${this.label} track frame:`,s),s++,n.close())}}),e).catch(n=>{console.warn(n),o.close()})}recreate(t,e=0){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===0&&H.emit(L.SEND_FIRST_VIDEO_FRAME,{room:t}),console.log(`encoded ${this.label} track frame:`,r,Date.now(),s.timestamp)),r++,this.track.enabled===!1)return;let d=null;if(this.localTrack.enableEncodeFrame){d=new Uint8Array(s.byteLength),s.copyTo(d);let p=this.localTrack.encodeFrame({data:d.buffer},this.type===3);d=new Uint8Array(p.data)}d?(this.localTrack.stat.bytesSent+=d.length,this.port.postMessage({chunk:{type:s.type,timestamp:s.timestamp,data:d,duration:s.duration},timestamp:n},[d.buffer])):(this.localTrack.stat.bytesSent+=s.byteLength,this.port.postMessage({chunk:s,timestamp:n}))},error:s=>{console.warn(s,this.config),setTimeout(()=>this.recreate(t,e+1),100)}});return this.encoder=o,this.configure({}),o}configure(t){var e;(e=this.encoder)==null||e.configure(Object.assign(this.config,t))}close(){this.port.postMessage(null),this.port.close()}};function hu(i,t){return y(this,null,function*(){let e=i.mediaType===2,r=e?"screen":"video",o={codec:"avc1.420028",avc:{format:"annexb"},hardwareAcceleration:Nt.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 Sp(i,t.type,o,s.port2);return s.port2.onmessage=d=>{if(d.data===260)n.insertKeyFrame=!0;else if(!e){let{bitrate:p}=d.data;Dn({configureBr:[d.data.bitrate,p]}),n.configure({bitrate:p})}},this._log.info("start push",r,t),n})}function wg(i){return y(this,null,function*(){let t=i.mediaType===2,e=t?"screen":"video",r={type:t?7:2,profile:i.profile,trackType:t?"screen":"camera"};!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 d=yield hu.call(this,i,r);this._log.info("VideoEncoder created",r);let p,m=E=>y(this,null,function*(){if(p==null||p.abort("track changed"),!E)return;p=new AbortController;let{width:_,height:b,displaySurface:C}=E.getSettings();_&&(d.config.width=_),b&&(d.config.height=b);let k=Xt.match(/Chrome\/(\d+)/);(k==null?void 0:k[1])==="114"&&C==="browser"&&delete d.config.hardwareAcceleration,this._log.info("push",e,"track:",E.readyState,E.getSettings());let x=new MediaStreamTrackProcessor({track:E}).readable,P="small"in i&&i.small;P?(this.smallEncoder||(this.smallEncoder=yield hu.call(this,i,{profile:P,type:3,trackType:o})),this.smallEncoder.track=E,this.smallEncoder.label="small",x=this.smallEncoder.trans(x,p,this)):this.smallEncoder&&(this.smallEncoder.close(),delete this.smallEncoder),d.track=E,d.label=e,d.start(x,p,this)});return ve(Ne(i,"output-media-track-changed"),Qe(Ne(i,"capture")),Ve(m,console.error,()=>{var E;this._log.info("stop push",e,r),p.abort("unpublish"),d.close(),(E=this.smallEncoder)==null||E.close()})),m(i.outMediaTrack)})}var Ki=class Ki extends ne{constructor(e){var r,o;super((o=(r=e.roomid)==null?void 0:r.toString())!=null?o:e.name,"volumeEvaluation");this.room=e;u(this,"enableInBackground",!1);u(this,"interval",400);e.on("joined",()=>{this.emit(Ki.INTERVALCHANGED,this.interval)}),ve(Ne(this,Ki.INTERVALCHANGED),ji(s=>this.room.state==="joined"?this.room.fromWorker("getAudioEnergy",s):ve(Nf(s),Gi(()=>[]))),Ve(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==ne.ON&&this.room.emit("audio-volume",s)}))}start(e,r){this.interval=e,this.enableInBackground=r,this.emit(Ki.INTERVALCHANGED,this.interval)}stop(){}};u(Ki,"INTERVALCHANGED","intervalChanged"),X([qe([ne.INIT,ne.OFF],ne.ON)],Ki.prototype,"start",1),X([qe([],ne.OFF)],Ki.prototype,"stop",1);var fu=Ki;var eo=class eo extends du{constructor(e){super(e);u(this,"index",0);u(this,"session");u(this,"tinyid");u(this,"roomid");u(this,"openid");u(this,"socketid");u(this,"relayip");u(this,"clientip");u(this,"remotePublishedUserMap",new Map);u(this,"bussinessInfo");u(this,"token");u(this,"audioVolumeEvalution",new fu(this));u(this,"enableAIVoice",Tp);u(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:il(),uint32_device_type:0,str_os_verion:ol(),uint32_link_type:1,str_client_version:rt,uint32_net_type:ho[Lr.getNetworkType()],ua:navigator.userAgent,version:""}});u(this,"joinAbortController",new AbortController);u(this,"smallAbortCtrl");u(this,"smallEncoder");e.tinyId&&(this.tinyId=e.tinyId,Ip(!0)),this._log||(this._log=e.logger),this.bussinessInfo=e.bussinessInfo,e.encodedDataProcessingListener&&this.setEncodedDataProcessingListener(e.encodedDataProcessingListener)}replaceTrack(e){return y(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=d=>{n.port2.close(),o(d.data)}})}fromWorker(e,r){if(this.state!="joined")throw"join room first";return o=>{var n;let s=new MessageChannel;s.port2.onmessage=d=>{d.data?o.next(d.data):o.complete()},s.port2.onmessageerror=d=>o.error(d),o.defer(()=>{s.port2.postMessage(null),s.port2.close()}),(n=this.session)==null||n.postMessage({cmd:e,payload:r},[s.port1])}}switchRole(e){return y(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 y(this,null,function*(){var p,m,E;let s=Lr.getEnv(),n=Yc(),d={isH264EncodeSupported:this.checkSystemResult.detail.isH264EncodeSupported,isVp8EncodeSupported:this.checkSystemResult.detail.isVp8EncodeSupported,frameWorkType:o,params:e,proxy_wt:(p=this.proxy_wt)==null?void 0:p.replace("https://",""),proxy_ws:(m=this.proxy_ws)==null?void 0:m.replace("wss://",""),proxy_cloud:(E=this.scheduleResult.iceServers)!=null&&E.length?this.scheduleResult.iceServers[0].urls:[],proxy_unified:this.proxy_unified,domains:this.scheduleResult.domains,env:s,osName:Ns(),browserInfo:Yc(),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:rt,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 Rg.call(this,d),console.log(this),lu.playAudio(_=>this.postMessage({cmd:"setAudioWorkletPort"},[_])),this.checkDestroy()})}leave(){return y(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())})}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 y(this,null,function*(){let e=Qe(Ne(this,"left"));ve(r=>y(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,Ve(({data:r,port:o})=>{let s=this.audioManager.decodePipeline[0]({frame:{data:r.data.buffer}});o.postMessage(Ee(Z({},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 L.RECEIVED_PUBLISHED_USER_LIST:H.emit(e,Z({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 tu(this,r);this.remotePublishedUserMap.set(r.userId,o),this.emit("remote-published",o);return;case"5":{let _=r,b=this.remotePublishedUserMap.get(_);b&&(b.remoteVideoTrack.close(),b.remoteAuxiliaryTrack.close(),b.remoteAudioTrack.close(),this.remotePublishedUserMap.delete(_),this.emit("remote-unpublished",b))}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:_,muteState:b,flag:C}=r,k=this.remotePublishedUserMap.get(b.userId);if(!k){this.emit("remote-publish-state-changed",r);return}k.flag=C}H.emit(L.REMOTE_PUBLISH_STATE_CHANGED,Z({room:this},r)),this.emit("remote-publish-state-changed",r);return;case"network-quality":this.quality=Z({},r);let{uplinkLoss:s,uplinkRTT:n,uplinkInfo:d,downlinkInfo:p,msg_down_stream_info:m}=r,E={str_sdk_version:rt,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:ho[Nn()]},msg_event_msg:Df(this.userId),str_acc_ip:this.relayip,str_client_ip:this.clientip,msg_up_stream_info:d,msg_down_stream_info:m};H.emit(L.HEARTBEAT_REPORT,{room:this,report:E}),this.emit("heartbeat-report",E),H.emit(L.NETWORK_QUALITY,{room:this,uplink:{rtt:n,loss:s},downlinks:p}),delete r.downlinkInfo;break;case"signal-connection-state-changed":H.emit(L.SIGNAL_CONNECTION_STATE_CHANGED,Z({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 y(this,null,function*(){let r=e.reduce((d,p)=>p.mediaType|d,0),o=this.sendMessage("publish",r).then(d=>d.err!==0?Promise.reject(d.err):d),s=0,n=d=>y(this,null,function*(){switch(yield o,d.muted&&(s|=d.mediaType),Pt(d,d).add("mute",()=>{this.postMessage("mute",{mediaType:d.mediaType,userId:this.userId,srctinyid:this.tinyid,remove:!0})}).add("unmute",()=>{this.postMessage("unmute",{mediaType:d.mediaType,userId:this.userId,srctinyid:this.tinyid,add:!0})}),d.mediaType){case 1:Dg.call(this,d);break;default:yield wg.call(this,d)}});yield Promise.all(e.map(n)),s&&this.postMessage("mute",{mediaType:s,srctinyid:this.tinyid,userId:this.openid,remove:!0})})}unpublish(...e){return y(this,null,function*(){e.forEach(ut)})}subscribe(...e){return y(this,null,function*(){let r=e.reduce((_,b)=>b.mediaType|_,0),{userId:o,tinyId:s,streamType:n}=e[0],d=this.remotePublishedUserMap.get(o),p=Z({},d.subscribeState),m=Object.assign(new Yn,p);m.mediaType|=r,H.emit(L.SUBSCRIBE_START,{room:this,streamType:n,remotePublishedUser:d,subscribeState:m});let E=yield this.sendMessage("subscribe",{mediaType:m.mediaType,userId:o,srctinyid:s,mediaDescription:{audioParam:{mediaType:1,payloadFmtps:[{payloadType:111,fmtp:"minptime=10;useinbandfec=1"}]},videoParam:[4,8,2].filter(_=>m.mediaType&_).map(_=>({mediaType:_,payloadFmtps:[{payloadType:100,fmtp:"packetization-mode=1;profile-level-id=42e01f"}]}))}});console.dir("subscribe",E),yield Promise.all(e.filter(_=>!_.isSubscribed).map(_=>{switch(_.mediaType){case 1:return vg.call(this,_);default:return Cg.call(this,_)}})),H.emit(L.SUBSCRIBE_SUCCESS,{room:this,streamType:n,remotePublishedUser:d})})}unsubscribe(...e){return y(this,null,function*(){let r=0;for(let o of e)r|=o.mediaType,o.unsubscribe();if(e.length){let{userId:o,streamType:s,tinyId:n}=e[0];yield this.sendMessage("unSubscribe",{mediaType:r,srctinyid:n,userId:o}),H.emit(L.UNSUBSCRIBE_SUCCESS,{room:this,streamType:s,remotePublishedUser:this.remotePublishedUserMap.get(o)})}})}enableSmall(e){return y(this,null,function*(){var r;if(e){if(this.videoManager.smallTrack){let o=this.videoManager.cameraTrack;this.smallEncoder=yield hu.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),s=e?8:4;if(o.remoteVideoTrack.mediaType===s)return;let n={srctinyid:r.tinyId,mediaType:s,userId:r.userId,mediaDescription:{audioParam:{mediaType:1,payloadFmtps:[{payloadType:111,fmtp:"minptime=10;useinbandfec=1"}]},videoParam:[4,8].filter(d=>s&d).map(d=>({mediaType:d,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"))}};X([Fi(eo.prototype.afterJoin),qe(["left",ne.INIT],"joined"),ag()],eo.prototype,"join",1),X([qe("joined","left",{ignoreError:!0}),cg()],eo.prototype,"leave",1),X([hd((...e)=>0),dg()],eo.prototype,"publish",1),X([hd((...e)=>0),ug()],eo.prototype,"unpublish",1),X([hd((...e)=>e[0].userId),lg()],eo.prototype,"subscribe",1);var gu=eo;Ks.frameWorkType=37;Ks.create=function(i){let t=Ks._create.call(this,gu,i);return t._use(Bm,i==null?void 0:i.assetsPath),i!=null&&i.assetsPath&&(Nt.assetsPath=i==null?void 0:i.assetsPath),console.log("trtc wasm sdk:",rt,"created",Nt),t};Object.assign(Ks.prototype,{_setCurrentSpeaker(i){let t=et("player");return t!=null&&t.setSinkId?t.setSinkId(i):Promise.reject("not support")},_enableVideoDecodeFallback(i,t){return y(this,null,function*(){return this.startPlugin(Bm.Name,{type:"webCodecs",renderer:"videoFrame",track:i,config:{codec:"avc1.420028"},fallback:"wasm"}),new Promise((e,r)=>{ve(Ne(i,"decode-downgrade-state-changed"),Fo(o=>o.state==="STARTED"),yr(1),xm(1e4),Qe(Ne(i,ne.INIT)),Ve(e,r))})})}});var a$=Ks;export{a$ as default};
|
|
141
|
+
}`});u(this,"yTextureRef");u(this,"uTextureRef");u(this,"vTextureRef");u(this,"Y");u(this,"U");u(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 lp=[i=>{i.codec="avc1.420028"},i=>{delete i.hardwareAcceleration}],Ig=(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 nS(i){return i[0]===0&&i[1]===0&&i[2]===0&&i[3]===1}var aS=0,du=class{constructor(t){u(this,"id",aS++);u(this,"trackDoneOB");u(this,"startOB");u(this,"stopOB");u(this,"decoder");u(this,"videoContext");u(this,"gop",0);u(this,"gop_helper",0);u(this,"waitFirstKeyFrame",!0);u(this,"startTimestamp",0);u(this,"startTime",0);u(this,"startPerformanceTime",0);u(this,"inputFrameCount",0);u(this,"decodedFrameCount",0);u(this,"decodeFrameCount",0);u(this,"downgradeLevel",0);u(this,"lastDowngradeTime",0);u(this,"lastFrameDiff",0);u(this,"lastDecodeFrameTimestamp",0);u(this,"config");u(this,"gop_before_configure",[]);u(this,"videoElement");u(this,"type","wasm");u(this,"goodType");u(this,"renderer","2d");u(this,"wasmOption");u(this,"createDecoder");u(this,"_decodeSink");u(this,"isReported",!1);u(this,"track");u(this,"stateChangeOB");u(this,"failedReason");let{track:e,createDecoder:r}=t;if(this.stateChangeOB=It(),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=be(e.availableState,ne.OFF),this.stopOB=It(this.trackDoneOB),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),Se(this.stateChangeOB,Om((o,s)=>(o!==s&&e.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:this.failedReason,prevState:o,state:s}),s),"INITIALIZED"),Je(this.stopOB),ke()),this.start()}start(t=0){this.waitFirstKeyFrame=!0,this.stateChangeOB.next("STARTING");let e=Se(this.pipe(this.track),Je(this.stopOB),li());Se(e,ke(()=>{this.track.stat.framesDecoded++},r=>{if(this.track.log.error(`${this.id} play failed: ${r} retryCount: ${t}`),Y.addFailedEvent({key:Ig(this.type,this.renderer),error:r}),t>4)this.failedReason=r,this.stateChangeOB.next("FAILED");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`),Y.addSuccessEvent({key:Ig(this.type,this.renderer)}),Y.addSuccessEvent({key:514704})})),Se(e,Ar(1),ke(()=>{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"&&!wl()&&(this.renderer="2d"),this.wasmOption.yuvMode=this.renderer==="webgl"}decode(t,e=!1){var d,p;if(this.failedReason)return;this.inputFrameCount++;let r=new Uint8Array(t.data);if(!nS(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(((d=this.decoder)==null?void 0:d.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(m=>this.decode(m,!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=_e();else{this.track.log.debug(`wait first key frame ${this.inputFrameCount}`);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} ${(p=t.getMetadata)==null?void 0:p.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=>y(this,null,function*(){this._decodeSink=e;let r,o=t.mediaTrack;e.defer(()=>{var d;t.player.setCanvas(),t.setInputMediaStreamTrack(o),r==null||r.close(),(d=this.videoContext)==null||d.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":for(let p=0;p<=lp.length;p++){let{supported:m}=yield VideoDecoder.isConfigSupported(this.config);if(m)break;if(p===lp.length){e.error(3);return}lp[p](this.config)}r=this.createDecoder(n);break;default:throw new Error("not supported yet")}let d=0;if(r.on("videoFrame",p=>{this.decodedFrameCount++,d++,(d<=10||d%500===0)&&t.log.debug(`frame ${d} ${this.decodedFrameCount}/${this.decodeFrameCount} decoded ${p.timestamp}`),Date.now()-this.lastDowngradeTime>5e3&&(this.type==="webCodecs"?this.checkDowngradeByFrameDiff():this.type==="wasm"&&this.checkDowngradeByTimestampDiff(p.timestamp)),e.next(p)}),r.on("error",p=>{t.log.error(p),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 Et({frameRate:15,logger:t.log,name:t.userId}),this.videoContext.create(),this.videoContext.on(Et.UNAVAILABLE,m=>{t.log.error(m),e.error(7)});let p=new cu(this.videoContext);r.on("videoCodecInfo",m=>p.resize(m.width,m.height)),r.on("videoFrame",m=>{({y:p.Y,u:p.U,v:p.V}=m),this.downgradeLevel===1?this.decodedFrameCount%2===0&&p.render(this.decodedFrameCount):p.render(this.decodedFrameCount)}),t.source=p,t.player.setCanvas(this.videoContext._canvas,2)}else if(s==="videoFrame"){t.player.setCanvas();let p=new MediaStreamTrackGenerator({kind:"video"}),m=p.writable.getWriter();t.setInputMediaStreamTrack(p),r.on("videoFrame",g=>m.write(g))}else{this.videoContext=new kt({frameRate:15,logger:t.log,name:t.userId}),this.videoContext.create({alpha:!1});let p=this.videoContext.createVideoImageSource();r.on("videoFrame",g=>{p.image=g,p.update()});let m=new Go(this.videoContext,{name:"remotePlayer",logger:t.log});p.connect(m),t.source=p,t.player.setCanvas(this.videoContext._canvas,2)}this.decoder=r}catch(d){t.log.error(d),e.error(n==="webCodecs"?2:6)}})}};var Pa=class extends Sg.EventEmitter{constructor(e){super();this.room=e;u(this,"videoContext");u(this,"_glVideoContext");u(this,"_2dVideoContext");u(this,"destination");u(this,"smallVideoContext");u(this,"smallDestination");u(this,"smallTrackSource");u(this,"smallImageSource");u(this,"_isMirror",!1);u(this,"cameraTrack");u(this,"cameraNode");u(this,"mirrorNode");u(this,"mixNode");u(this,"screenTrack");u(this,"screenNode");u(this,"selfModel",!1);u(this,"blurRadius",3);u(this,"arTrack");u(this,"Wasm");u(this,"waterMarkNode");u(this,"_waterMarkOption");u(this,"watermarkImageList",[]);u(this,"_beautyParams");u(this,"isUsingArTrack",!1);u(this,"_isMixScreen",!1);u(this,"_virtualBackground");u(this,"_virtualBackgroundAbortCallback");u(this,"virtualBackgroundInstance");u(this,"_bgAssetPath");u(this,"log",$.createLogger({id:"vm"}));u(this,"_checkId",0);u(this,"_use2d",!1);u(this,"_autoSwitchRenderMode",!0);u(this,"_selfieSegmentation");u(this,"encodePipeline",[]);u(this,"decodePipeline",[]);e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new kt({frameRate:15,logger:this.log,name:"s"}),this.enablePrintDetail()}get _hasVirtualBg(){return!!this._virtualBackground}get _hasWaterMark(){return this.watermarkImageList.length>0}get renderMode(){return this._autoSwitchRenderMode?"auto":this._use2d?"2d":"webgl"}set renderMode(e){if(this._autoSwitchRenderMode=e==="auto",this._autoSwitchRenderMode)return;let r=e==="2d";this._use2d!==r&&(this._use2d=r,this.clear(),this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.update())}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new kt({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this._2dVideoContext}getGlVideoContext(){if(!this._glVideoContext)this._glVideoContext=new Et({frameRate:15,logger:this.log,name:"m"});else if(this._glVideoContext.available)return this._glVideoContext;return this.initializeGlVideoContext(),this._glVideoContext}initializeGlVideoContext(){try{this._glVideoContext.create(),this._glVideoContext.on(Et.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)}}enablePrintDetail(e=2e3){this._checkId=At.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(),At.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(Ui||this._isMixScreen||this._isMirror||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}sendCreateResult(e="videoCtxGl",r){let o=e==="videoCtxGl"?512700:512701;r?Y.addFailedEvent({key:o,error:r}):Y.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 Et({frameRate:15,logger:this.log,name:"m"}),this.initializeGlVideoContext(),this._glVideoContext.available)return this.videoContext=this._glVideoContext,this.videoContext.available;this.log.warn("webgl is still not available"),this.clear(),this._use2d=!0}return this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.videoContext.available}get smallTrack(){var e;return(e=this.smallDestination)==null?void 0:e.videoTrack}get hasSmall(){return!!this.smallTrack}get initialTrack(){var e;return(e=this.cameraTrack)==null?void 0:e.mediaTrack}initVirtualBackground(e){return this._selfieSegmentation=e,this._selfieSegmentation.changeModel()}setSmallVideo(e,r){if(e){if(!this.smallVideoContext.available){if(this.smallVideoContext.create({alpha:!1}),!this.smallVideoContext.available)return;this.smallDestination=new Od(this.smallVideoContext,e,this.log),this.smallVideoContext.on(Et.UNAVAILABLE,o=>{this.log.warn("small video context lost",o)})}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.connect(this.smallDestination))):(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource?this.smallTrackSource.replaceTrack(this.initialTrack):(this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack,"smallTrackSource"),this.smallTrackSource.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;this.setSmallVideo(s,e),Ui&&n.setCanvas(e);let d=e&&((r=this.destination)==null?void 0:r.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),d=this.arTrack),this._selfieSegmentation&&e&&!this._use2d&&(this._selfieSegmentation._glName||this._selfieSegmentation.setCanvas(e)),this.log.info(`set main output ${d?d.label:"no output track"}`),o.setOutputMediaStreamTrack(d)}catch(o){this.log.error("set main output failed",o)}}update(){return y(this,null,function*(){var o,s;if(!this.cameraTrack||!this.cameraTrack.mediaTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:e,profile:r}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams?(this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log})),Yt===16?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof pi?(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 pi?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode.close(),delete this.cameraNode)),this.cameraNode||(this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraTrackSource"))):this.cameraNode?this.cameraNode.replaceTrack(this.initialTrack):this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraNodeSource"),this.cameraNode.resize(e.width,e.height)):(this.cameraNode&&this.cameraNode.close(),this.destination?this.destination.disableCheckMute():this.destination=new Md(this.videoContext,{name:"mainDestination",logger:this.log}),this.cameraNode=new au(this.videoContext,{input:this.cameraTrack.mediaTrack,width:e.width,height:e.height,mirror:this._isMirror,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,beautyParams:this._beautyParams,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,selfieSegmentation:this._selfieSegmentation,Wasm:this.Wasm}),this.cameraNode.connect(this.destination),this.destination.enableCheckMute()),this.videoContext.frameRate=r.frameRate,this._use2d){let n=this.cameraNode;n.disconnect(),this._isMirror&&(this.mirrorNode||(this.mirrorNode=new su(this.videoContext,this.log)),n=n.connect(this.mirrorNode),n.disconnect(),this.log.info("start mirror")),this.mixNode&&this.mixNode.close(),delete this.mixNode,(this._isMixScreen||this._hasWaterMark)&&(this.mixNode=new nu(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),(o=this.waterMarkNode)==null||o.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&!this.screenNode&&(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource")),(s=this.screenNode)==null||s.connect(this.mixNode,{zIndex:0}),n=this.mixNode,this.log.info("start mix",`${this.mixNode.width}x${this.mixNode.height}`)),n.connect(this.destination)}return this.log.info(`update ${this._use2d?"2d":"webgl"}`),this._setMainOutput(this.videoContext._canvas)})}changeInput(e){var r,o,s,n;if(e instanceof ji)return this.log.info("change screen input",(r=e.mediaTrack)==null?void 0:r.label),this.setScreenTrack(e);if(e instanceof Sr)return this.log.info("change video input",(o=e.mediaTrack)==null?void 0:o.label),this.setCameraTrack(e);if(e instanceof Xi){this.log.info("change remote input",(s=e.mediaTrack)==null?void 0:s.label);let d=e.mediaTrack;return e.setOutputMediaStreamTrack(d)}this.log.warn("change unknown input",(n=e.mediaTrack)==null?void 0:n.label)}removeInput(e){var r;e instanceof ji?((r=this.screenNode)==null||r.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof Sr?(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof Xi&&e.source&&e.source.context.destroy()}setCameraTrack(e){return y(this,null,function*(){this.cameraTrack=e,this.update()})}setScreenTrack(e){return this.screenTrack=e,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)}getWatermarkImage(e,r){return y(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 he({code:te.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort((n,d)=>n.zIndex-d.zIndex),this.watermarkImageList.forEach(({image:n,x:d,y:p,width:m,height:g})=>{s.drawImage(n,d,p,m,g)}),_s(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)||((r==="mute"||r==="watermark")&&(this.watermarkImageList=this.watermarkImageList.filter(s=>s.type!==r)),this.watermarkImageList.push(e))}setBeautyParams(e){return y(this,null,function*(){this._beautyParams=e,this.update()})}stopBeauty(){return y(this,null,function*(){this._beautyParams=void 0,this.update()})}setWatermark(e){return y(this,null,function*(){var _,b;let r;try{r=yield _s((e==null?void 0:e.imageElement)||e.imageUrl)}catch(N){throw new he({code:te.INVALID_PARAMETER,message:`load image failed, url: ${e.imageUrl}`})}let{x:o=0,y:s=0,width:n=r.width,height:d=r.height,type:p="watermark",zIndex:m=2}=e;this.watermarkImageList.some(N=>N.type===p)?(this.watermarkImageList=this.watermarkImageList.filter(N=>N.type!==p),this.pushWaterMarkImageList({x:o,y:s,width:n,height:d,image:r,zIndex:m,type:p,imageUrl:e.imageUrl}),r=yield this.getWatermarkImage((_=this.cameraTrack)==null?void 0:_.settings.width,(b=this.cameraTrack)==null?void 0:b.settings.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:d,image:r,zIndex:m,type:p,imageUrl:e.imageUrl}),yield this.freshWatermark()),this.log.info("set watermark",JSON.stringify(this.watermarkImageList,(N,k)=>N==="imageUrl"?void 0:k))})}deleteWatermark(e="watermark"){return y(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 y(this,null,function*(){var r,o,s;(r=this.waterMarkNode)==null||r.close(),delete this.waterMarkNode,delete this._waterMarkOption;let e=yield this.getWatermarkImage((o=this.cameraTrack)==null?void 0:o.settings.width,(s=this.cameraTrack)==null?void 0:s.settings.height);this._waterMarkOption={x:0,y:0,width:e.width,height:e.height,image:e},this.update()})}setVirtualBackground(e){return y(this,null,function*(){if(!e)delete this._virtualBackground,delete this._virtualBackgroundAbortCallback;else{if(e.onAbort&&(this._virtualBackgroundAbortCallback=e.onAbort),this._use2d&&!this._autoSwitchRenderMode)return Promise.reject(new Error("not support virtual background in 2d mode"));this._bgAssetPath=e.assetPath,e.type==="image"?this._virtualBackground=yield _s(e.imageUrl):(this.blurRadius=e.blurLevel||this.blurRadius||3,this._virtualBackground=e.type)}if(this.log.info(`${this._virtualBackground?"start":"stop"} virtual background, ${(e==null?void 0:e.type)||""}, ${this.blurRadius||""}`),yield this.update(),this._virtualBackground&&!this._glVideoContext.available)throw new he({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._isMirror||((r=this.mirrorNode)==null||r.close(),delete this.mirrorNode),this.update())}get mirror(){return this._isMirror}enableAr(e){this.arTrack=e,this.isUsingArTrack=!0,this.update()}updateAr(){return y(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 du(e)}clear(){var e;(e=this.videoContext)==null||e.disconnect(),delete this.destination,delete this.cameraNode,delete this.mirrorNode,delete this.screenNode,delete this.waterMarkNode}addEncodeProcessor({processor:e,type: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}};X([df(function(e){this.log.error("update failed",e)})],Pa.prototype,"update",1);var cS=0;var uu=class extends ne{constructor(e){super("room");u(this,"seq",++cS);u(this,"sdkAppId");u(this,"userId");u(this,"userSig");u(this,"privateMapKey");u(this,"latencyLevel");u(this,"tinyId");u(this,"scene");u(this,"roomId");u(this,"useStringRoomId");u(this,"role","anchor");u(this,"joinParams",null);u(this,"localTracks",new Set);u(this,"enableAutoPlayDialog",!0);u(this,"autoReceiveAudio",!0);u(this,"autoReceiveVideo",!0);u(this,"proxy_ws");u(this,"proxy_wt");u(this,"proxy_unified");u(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}});u(this,"keyPointManager");u(this,"audioManager");u(this,"videoManager");u(this,"callDurationCalculator");u(this,"badCaseDetector");u(this,"scheduleResult",{domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null});u(this,"videoDecodeFallbackType");u(this,"_isUsingCachedSchedule",!1);u(this,"_log",$.createLogger({id:`r${this.seq}`}));u(this,"_joinedTimestamp",0);u(this,"_sdkType");u(this,"heartbeatReport");u(this,"quality");u(this,"enableSEI");u(this,"isDestroyed",!1);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 Eg({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new _g({room:this}),this.badCaseDetector=new Tg({room:this}),this.audioManager=new gd(this),this.videoManager=new Pa(this)}get scriptTransformWorker(){}get isMainStreamPublished(){for(let e of this.localTracks)if(e.mediaType&4)return!0;return!1}get isAuxStreamPublished(){for(let e of this.localTracks)if(e.mediaType&2)return!0;return!1}get hasAuxStream(){for(let e of this.remotePublishedUserMap.values())if(e.muteState.hasAuxiliary)return!0;return this.isAuxStreamPublished}get localMainVideoTrack(){for(let e of this.localTracks)if(e.mediaType&4)return e;return null}get localAuxVideoTrack(){for(let e of this.localTracks)if(e.mediaType&2)return e;return null}getLogger(){return this._log}get isJoining(){return this.state.toString()==="joining"}get isJoined(){return this.state==="joined"}get isLeft(){return this.state==="left"}addTrack(e){return y(this,null,function*(){return this.publish(e)})}removeTrack(e){return y(this,null,function*(){return this.unpublish(e)})}replaceTrack(e){return y(this,null,function*(){})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(we(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(Gt(e)){let{websocketProxy:r,webtransportProxy:o,loggerProxy:s,scheduleProxy:n,unifiedProxy:d}=e;this.proxy_ws=r,this.proxy_wt=o,this.proxy_unified=d,d?(Wd([d,d]),_o(`https://${d}`)):(s&&_o(s),n&&Wd(n))}H.once(L.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:ro.main,sched_back_domain:ro.backup,signal_domain:this.proxy_ws||this.proxy_wt||""}))}getRemoteAudioStats(){return y(this,null,function*(){let e={};return this.remotePublishedUserMap.forEach(r=>{e[r.userId]=r.remoteAudioTrack.stat}),e})}getTransportStats(){return y(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 y(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 he({code:te.INVALID_OPERATION,message:dt({key:ct.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(qt.INVALID_DESTROY),new he({code:te.INVALID_OPERATION,message:dt({key:ct.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,H.emit(L.ROOM_DESTROY,{room:this})}schedule(e,r){return y(this,null,function*(){var s,n,d;let o=_e();try{let{isCached:p,result:m,detailCost:g}=yield Jm({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:rt,userSig:this.userSig,role:this.scene==="live"?e.role:void 0,frameWorkType:r,latencyLevel:e.latencyLevel});this._isUsingCachedSchedule=p,this._log.info(`schedule cache:${+p} ${ir(m,{keysToExclude:["username","credential"]})}`),p&&H.once(L.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=ee(ee({},this.scheduleResult),m),je((s=m.config)==null?void 0:s.retryCount)&&Uu(m.config.retryCount),we((n=m.config)==null?void 0:n.loggerDomain)&&_o(m.config.loggerDomain),this.videoDecodeFallbackType=((d=m.config)==null?void 0:d.videoDecodeFallback)||this.videoDecodeFallbackType,H.emit(L.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:g}),Y.addSuccessEvent({key:521700,cost:_e()-o,split:50})}catch(p){throw Y.addFailedEvent({key:521700,error:p}),p}})}sendAbilityStatus(e){}enableInsertableStreams(){return Promise.resolve()}};function yg(i,t=!1){let e=Object.defineProperties(It(),{postMessage:{value:i.postMessage.bind(i)},port:{get(){return i},set(o){i.onmessage=Ve,i.onmessageerror=Ve,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 mp=class extends de{constructor(t,e){super(t);let r=new de(t);r.next=Ve,e(r)}},J2=pe(mp,"takeUntilComplete");var Dt={useWt:!0,useAINS:!0,useHardDecoder:"prefer-software",useHardEncoder:"prefer-software",unreliable:!1,debug:!1,assetsPath:"",enableUpload:!0},hp="__INLINE__WORKER__",Ag="__INLINE__WASM__",{debug:bg}=console;Dt.debug||(console.debug=()=>{});var pp=!hp.startsWith("__"),dS=!Ag.startsWith("__");function Rg(){return`${Dt.assetsPath?`${Dt.assetsPath}/`:""}worker.js`}function vg(){let i=Rg();return pp||i.startsWith("http")?URL.createObjectURL(new Blob([pp?atob(hp):`importScripts('${i}')`])):i}function Cg(){let i=Rg();return pp?URL.createObjectURL(new Blob([atob(hp)],{type:"application/javascript"})):i.startsWith("http")?fetch(i).then(t=>t.blob().then(e=>URL.createObjectURL(e))):i}var ka;function lu(){return y(this,null,function*(){let i=Dt.assetsPath?`${Dt.assetsPath}/`:"";return ka||(dS?ka=new TextEncoder().encode(atob(Ag)).buffer:ka=yield fetch(`${i}av_processing.wasm`).then(t=>t.arrayBuffer()),ka)})}var fp=class{constructor(){u(this,"playPort");u(this,"playPortSent",!1);u(this,"worklet");u(this,"workletPromise")}init(){return this.workletPromise||(this.workletPromise=this._init()),this.workletPromise}_init(){return y(this,null,function*(){let t=et("player"),e=Cg();try{yield t.audioWorklet.addModule(typeof e=="string"?e:yield e),$.info("global audio player worklet addModule success",e)}catch(r){throw $.error("global audio player worklet addModule failed:",r),r}return this.worklet=new AudioWorkletNode(t,"global-audio-player",{processorOptions:{wasm:yield lu(),flag:Dt},numberOfInputs:2}),$.info("global audio player worklet created",t.state),this.worklet.connect(t.destination),this.playPort=this.worklet.port,this.playPort})}playAudio(t){return y(this,null,function*(){this.playPortSent||(this.playPortSent=!0,t(yield this.init()))})}},mu=new fp;var gp=(()=>{if(typeof self=="undefined")return!1;if(!("top"in self&&self!==top)){if("showOpenFilePicker"in self)return"showOpenFilePicker"}return!1})(),t1=gp?Promise.resolve().then(function(){return pS}):Promise.resolve().then(function(){return TS});var r1=gp?Promise.resolve().then(function(){return fS}):Promise.resolve().then(function(){return SS});var uS=gp?Promise.resolve().then(function(){return ES}):Promise.resolve().then(function(){return AS});function Ep(...i){return y(this,null,function*(){return(yield uS).default(...i)})}var lS=i=>y(void 0,null,function*(){let t=yield i.getFile();return t.handle=i,t}),mS=(...t)=>y(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(d=>{e[n].accept[d]=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(lS));return i[0].multiple?o:o[0]}),pS={__proto__:null,default:mS};function pu(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 pu=function(e){this.s=e,this.n=e.next},pu.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 pu(i)}var Dg=(o,s,...n)=>y(void 0,[o,s,...n],function*(i,t,e=i.name,r){let d=[],p=[];var m,g=!1,_=!1;try{for(var b,N=function(k){var P,x,J,Q=2;for(typeof Symbol!="undefined"&&(x=Symbol.asyncIterator,J=Symbol.iterator);Q--;){if(x&&(P=k[x])!=null)return P.call(k);if(J&&(P=k[J])!=null)return new pu(P.call(k));x="@@asyncIterator",J="@@iterator"}throw new TypeError("Object is not async iterable")}(i.values());g=!(b=yield N.next()).done;g=!1){let k=b.value,P=`${e}/${k.name}`;k.kind==="file"?p.push(k.getFile().then(x=>(x.directoryHandle=i,x.handle=k,Object.defineProperty(x,"webkitRelativePath",{configurable:!0,enumerable:!0,get:()=>P})))):k.kind!=="directory"||!t||r&&r(k)||d.push(Dg(k,t,P,r))}}catch(k){_=!0,m=k}finally{try{g&&N.return!=null&&(yield N.return())}finally{if(_)throw m}}return[...(yield Promise.all(d)).flat(),...yield Promise.all(p)]}),hS=(...t)=>y(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 Dg(e,i.recursive,void 0,i.skipDirectory)}),fS={__proto__:null,default:hS},gS=(s,...n)=>y(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 d=[],p=null;if(i instanceof Blob&&i.type?p=i.type:i.headers&&i.headers.get("content-type")&&(p=i.headers.get("content-type")),t.forEach((_,b)=>{d[b]={description:_.description||"Files",accept:{}},_.mimeTypes?(b===0&&p&&_.mimeTypes.push(p),_.mimeTypes.map(N=>{d[b].accept[N]=_.extensions||[]})):p?d[b].accept[p]=_.extensions||[]:d[b].accept["*/*"]=_.extensions||[]}),e)try{yield e.getFile()}catch(_){if(e=null,r)throw _}let m=e||(yield window.showSaveFilePicker({suggestedName:t[0].fileName,id:t[0].id,startIn:t[0].startIn,types:d,excludeAcceptAllOption:t[0].excludeAcceptAllOption||!1}));!e&&o&&o(m);let g=yield m.createWritable();return"stream"in i?(yield i.stream().pipeTo(g),m):"body"in i?(yield i.body.pipeTo(g),m):(yield g.write(yield i),yield g.close(),m)}),ES={__proto__:null,default:gS},_S=(...t)=>y(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(m=>m.mimeTypes||[]),...i.map(m=>m.extensions||[])].join();o.multiple=i[0].multiple||!1,o.accept=s||"",o.style.display="none",document.body.append(o);let n=m=>{typeof d=="function"&&d(),e(m)},d=i[0].legacySetup&&i[0].legacySetup(n,()=>d(r),o),p=()=>{window.removeEventListener("focus",p),o.remove()};o.addEventListener("click",()=>{window.addEventListener("focus",p)}),o.addEventListener("change",()=>{window.removeEventListener("focus",p),o.remove(),n(o.multiple?Array.from(o.files):o.files[0])}),"showPicker"in HTMLInputElement.prototype?o.showPicker():o.click()})}),TS={__proto__:null,default:_S},IS=(...t)=>y(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=d=>{typeof n=="function"&&n(),e(d)},n=i[0].legacySetup&&i[0].legacySetup(s,()=>n(r),o);o.addEventListener("change",()=>{let d=Array.from(o.files);i[0].recursive?i[0].recursive&&i[0].skipDirectory&&(d=d.filter(p=>p.webkitRelativePath.split("/").every(m=>!i[0].skipDirectory({name:m,kind:"directory"})))):d=d.filter(p=>p.webkitRelativePath.split("/").length===2),s(d)}),"showPicker"in HTMLInputElement.prototype?o.showPicker():o.click()})}),SS={__proto__:null,default:IS},yS=(e,...r)=>y(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(p,m){return y(this,null,function*(){let g=p.getReader(),_=new ReadableStream({start:k=>function P(){return y(this,null,function*(){return g.read().then(({done:x,value:J})=>{if(!x)return k.enqueue(J),P();k.close()})})}()}),b=new Response(_),N=yield b.blob();return g.releaseLock(),new Blob([N],{type:m})})}(i.body,i.headers.get("content-type"))),o.download=t.fileName||"Untitled",o.href=URL.createObjectURL(yield s);let n=()=>{typeof d=="function"&&d()},d=t.legacySetup&&t.legacySetup(n,()=>d(),o);return o.addEventListener("click",()=>{setTimeout(()=>URL.revokeObjectURL(o.href),3e4),n()}),o.click(),null}),AS={__proto__:null,default:yS};var _p=class{constructor(t){this.name=t;u(this,"ready");u(this,"worker");u(this,"ports");u(this,"ids",1);u(this,"transactions",new Map);u(this,"log");u(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){if(this.ready)return this.ready;t||(t=this.name),console.time(`createWorker_${t}`);let e=new Worker(vg(),{name:t});return this.worker=e,this.ready=new Promise((r,o)=>y(this,null,function*(){e.onmessage=({data:{id:s,type:n,payload:d}})=>{var p;if(s)(p=this.transactions.get(s))==null||p(d),this.transactions.delete(s);else switch(n){case"error":console.timeEnd(`createWorker_${t}`),console.warn("worker error:",d),o(d);break;case"ready":console.timeEnd(`createWorker_${t}`),r(this);break;case"updateAFSM":if(d.value){let m=typeof d.old=="string"?d.old:`${d.old.action}ing`,g=typeof d.value=="string"?d.value:`${d.value.action}ing`;console.log(gc(),d.group,d.name,m,"\u{1F449}",g)}break;case"log":console.log(d);break;case"glog":window.dispatchEvent(new CustomEvent(n,{detail:d}));break}},e.postMessage({wasm:yield lu(),flag:Dt},this.ports)}))}destroy(){var t;console.log("destroy worker",this.name),delete this.ready,(t=this.worker)==null||t.terminate()}},Tp=class{constructor(t,e,r){this.worker=t;u(this,"channel",new MessageChannel);u(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()}},Ip=class i extends _p{constructor(){super("main");u(this,"switchValue",new Map);u(this,"extendChannel");u(this,"sessionCount",0)}setSwitchValue(e,r){var o;this.switchValue.set(e,r),(o=this.extendChannel)==null||o.port1.postMessage([e,r])}create(){return y(this,null,function*(){return this.ready?this.ready:(this.extendChannel=new MessageChannel,this.ports=[this.extendChannel.port2],yield Ft(i.prototype,this,"create").call(this),this.switchValue.forEach((e,r)=>{this.extendChannel.port1.postMessage([r,e])}),this)})}},io=new Ip,Qo,bS=-1;function Ng(i){return console.log(i),Qo.push(i.slice()),Qo.length>1e3&&Qo.shift(),i}function wg(i){return y(this,null,function*(){switch(bS){case 0:this.edpl.willDecodeAudio=Ng;break;case 2:this.edpl.didEncodeAudio=Ng;break}yield io.create(),H.emit(L.JOIN_SEND_CMD,{room:this});let t=new Tp(io,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:d}=s;this.onWorkerEvent(n,d)}}),{err:e,data:r}=yield t.ready;if(typeof e=="number"){if(H.emit(L.JOIN_RECEIVED_CMD_RES,{room:this,code:e}),e===0)return Object.assign(this,r,{session:t});throw new he({code:te.JOIN_ROOM_FAILED,extraCode:Number(e),message:dt({key:ct.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:e,errorMsg:""}})})}else throw e})}Object.defineProperties(window,{useAINS:{set:Sp},useWt:{set:RS},enableDebug:{set(i){console.debug=i?bg:()=>{},io.setSwitchValue("enableDebug",i)}},useV2:{set:yp},dump:{value(){if(Qo||(console.warn("dump audio will be activated at next time join room"),Qo=[]),!Qo.length){console.warn("no audio data to dump,try it later");return}let i=[];return Qo.forEach(t=>{i.push(new Uint16Array([t.length])),i.push(t)}),Ep(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;io.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,io.extendChannel.port1.postMessage(["dump",i]),s.port2.close(),o(new Blob(e)))}});return Ep(r,{fileName:i,extensions:[".pcm"]})}},hardDec:{set(i){switch(i){case!0:Dt.useHardDecoder="prefer-hardware";break;case!1:Dt.useHardDecoder="prefer-software";break;default:Dt.useHardDecoder="no-preference"}}}});function Sp(i){return y(this,null,function*(){io.setSwitchValue("useAINS",i)})}function yp(i){return y(this,null,function*(){io.setSwitchValue("useV2",i)})}function RS(i){return y(this,null,function*(){io.setSwitchValue("useWt",i)})}function Mg(i){let t=new MediaStreamTrackGenerator({kind:"audio"});i.setInputMediaStreamTrack(t),this.postMessage({cmd:"pullAudio",payload:{tinyId:i.tinyId,writable:t.writable}},[t.writable])}function Og(i){return y(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),Se(yg(r.port2),Je(be(i,ne.INIT)),ke(s=>{let{data:n,packetsReceived:d}=s;i.stat.packetsReceived=d,i.stat.framesReceived++,e++;let p=n[4]&31;if(e<=10){let g=Array.from(n.slice(0,10)).map(_=>_.toString(16).padStart(2,"0")).join(" ");this._log.info(`Frame ${e} - Size: ${n.length} bytes, Type: ${p}, Timestamp: ${Date.now()-t}ms First 10 bytes: ${g}`)}let m;switch(p){case 5:case 7:m="key";break;default:m="delta";break}i.isAvailable?i.decodeFrame({data:n.buffer,type:m,timestamp:(Date.now()-t)*1e3}):console.warn("track is not available")},()=>{},()=>{r.port2.postMessage(null),r.port2.close()}))})}var hu=[];function Pg(i){var p;let t=It();if(this.state!=="joined")throw new Error("Room is not joined");if(i.state==="publish")return;for(let m=0;m<=hu.length;m++)if(!hu[m]){hu[m]=this,this.index=m;break}let e=i.profile;this._log.info("start push audio",this.index,e);let r=new MessageChannel,o=i.enableEncodeFrame?new MessageChannel:null;(p=this.session)==null||p.postMessage({cmd:"pushAudio",payload:ee({index:this.index},e)},o?[r.port2,o.port2]:[r.port2]),r.port1.onmessage=m=>{m.data==null||(typeof m.data=="number"?t.next(m.data):o&&o.port1.postMessage(Ee(ee({},m.data),{data:new Uint8Array(i.encodeFrame({data:m.data.data.buffer,timestamp:m.data.timestamp}).data)})))};let s=new MediaStream,n,d=m=>{let g=s.getAudioTracks()[0];g&&(n.disconnect(),s.removeTrack(g)),s.addTrack(m),this._log.info("push audio track:",m.readyState,m.getSettings().deviceId),n=et("player").createMediaStreamSource(s),n.connect(mu.worklet,0,this.index)};Se(be(i,"output-media-track-changed"),Je(be(i,"capture")),ke(d,console.error,()=>{this._log.info("stop push audio",e),i.volume=0,n.disconnect(),hu[this.index]=null,o&&o.port1.postMessage(null),r.port1.postMessage(null)})),Se(t,Sa(m=>i.volume=m),mi(wd(1e3)),ke(()=>{i.volume=0})),d(i.outMediaTrack)}var L1=new Intl.DateTimeFormat("zh-CN",{dateStyle:"short",timeStyle:"medium"});var Ap=class{constructor(t,e,r,o){this.localTrack=t;this.type=e;this.config=r;this.port=o;u(this,"track");u(this,"label");u(this,"insertKeyFrame",!0);u(this,"encoder");u(this,"tsMap",new Map);t._log.info("create Video Encoder",r)}trans(t,e,r){let o=this.recreate(r);e.signal.addEventListener("abort",()=>{o.close()});let s=0;return t.pipeThrough(new TransformStream({transform:(n,d)=>{o.state==="configured"&&(this.tsMap.set(s,Date.now()),this.encode(n),s++,d.enqueue(n))}}),e)}encode(t){this.encoder.encode(t,{keyFrame:this.insertKeyFrame}),this.insertKeyFrame=!1}start(t,e,r){let o=this.recreate(r),s=0;t.pipeTo(new WritableStream({write:n=>{o.state==="configured"&&(s<10&&console.log(`capture ${this.label} track frame:`,s,Date.now(),n.timestamp,n.displayWidth,n.displayHeight),(n.displayWidth!==this.config.width||n.displayHeight!==this.config.height)&&(console.log("resize video track frame:",n.displayWidth,n.displayHeight,this.config.width,this.config.height),this.configure({width:n.displayWidth,height:n.displayHeight})),this.tsMap.set(s,Date.now()),this.encode(n),s<10&&console.log(`encode ${this.label} track frame:`,s),s++,n.close())}}),e).catch(n=>{console.warn(n),o.close()})}recreate(t,e=0){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===0&&H.emit(L.SEND_FIRST_VIDEO_FRAME,{room:t}),console.log(`encoded ${this.label} track frame:`,r,Date.now(),s.timestamp)),r++,this.track.enabled===!1)return;let d=null;if(this.localTrack.enableEncodeFrame){d=new Uint8Array(s.byteLength),s.copyTo(d);let p=this.localTrack.encodeFrame({data:d.buffer},this.type===3);d=new Uint8Array(p.data)}d?(this.localTrack.stat.bytesSent+=d.length,this.port.postMessage({chunk:{type:s.type,timestamp:s.timestamp,data:d,duration:s.duration},timestamp:n},[d.buffer])):(this.localTrack.stat.bytesSent+=s.byteLength,this.port.postMessage({chunk:s,timestamp:n}))},error:s=>{console.warn(s,this.config),setTimeout(()=>this.recreate(t,e+1),100)}});return this.encoder=o,this.configure({}),o}configure(t){var e;(e=this.encoder)==null||e.configure(Object.assign(this.config,t))}close(){this.port.postMessage(null),this.port.close()}};function fu(i,t){return y(this,null,function*(){let e=i.mediaType===2,r=e?"screen":"video",o={codec:"avc1.420028",avc:{format:"annexb"},hardwareAcceleration:Dt.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 Ap(i,t.type,o,s.port2);return s.port2.onmessage=d=>{if(d.data===260)n.insertKeyFrame=!0;else if(!e){let{bitrate:p}=d.data;Dn({configureBr:[d.data.bitrate,p]}),n.configure({bitrate:p})}},this._log.info("start push",r,t),n})}function kg(i){return y(this,null,function*(){let t=i.mediaType===2,e=t?"screen":"video",r={type:t?7:2,profile:i.profile,trackType:t?"screen":"camera"};!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 d=yield fu.call(this,i,r);this._log.info("VideoEncoder created",r);let p,m=g=>y(this,null,function*(){if(p==null||p.abort("track changed"),!g)return;p=new AbortController;let{width:_,height:b,displaySurface:N}=g.getSettings();_&&(d.config.width=_),b&&(d.config.height=b);let k=Xt.match(/Chrome\/(\d+)/);(k==null?void 0:k[1])==="114"&&N==="browser"&&delete d.config.hardwareAcceleration,this._log.info("push",e,"track:",g.readyState,g.getSettings());let P=new MediaStreamTrackProcessor({track:g}).readable,x="small"in i&&i.small;x?(this.smallEncoder||(this.smallEncoder=yield fu.call(this,i,{profile:x,type:3,trackType:o})),this.smallEncoder.track=g,this.smallEncoder.label="small",P=this.smallEncoder.trans(P,p,this)):this.smallEncoder&&(this.smallEncoder.close(),delete this.smallEncoder),d.track=g,d.label=e,d.start(P,p,this)});return Se(be(i,"output-media-track-changed"),Je(be(i,"capture")),ke(m,console.error,()=>{var g;this._log.info("stop push",e,r),p.abort("unpublish"),d.close(),(g=this.smallEncoder)==null||g.close()})),m(i.outMediaTrack)})}var oo=class oo extends ne{constructor(e){var r,o;super((o=(r=e.roomid)==null?void 0:r.toString())!=null?o:e.name,"volumeEvaluation");this.room=e;u(this,"enableInBackground",!1);u(this,"interval",400);e.on("joined",()=>{this.emit(oo.INTERVALCHANGED,this.interval)}),Se(be(this,oo.INTERVALCHANGED),zi(s=>this.room.state==="joined"?this.room.fromWorker("getAudioEnergy",s):Se(Nf(s),Ji(()=>[]))),ke(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==ne.ON&&this.room.emit("audio-volume",s)}))}start(e,r){this.interval=e,this.enableInBackground=r,this.emit(oo.INTERVALCHANGED,this.interval)}stop(){}};u(oo,"INTERVALCHANGED","intervalChanged"),X([qe([ne.INIT,ne.OFF],ne.ON)],oo.prototype,"start",1),X([qe([],ne.OFF)],oo.prototype,"stop",1);var gu=oo;var so=class so extends uu{constructor(e){super(e);u(this,"index",0);u(this,"session");u(this,"tinyid");u(this,"roomid");u(this,"openid");u(this,"socketid");u(this,"relayip");u(this,"clientip");u(this,"remotePublishedUserMap",new Map);u(this,"bussinessInfo");u(this,"token");u(this,"audioVolumeEvalution",new gu(this));u(this,"enableAIVoice",Sp);u(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:sl(),uint32_device_type:0,str_os_verion:nl(),uint32_link_type:1,str_client_version:rt,uint32_net_type:To[Lr.getNetworkType()],ua:navigator.userAgent,version:""}});u(this,"joinAbortController",new AbortController);u(this,"smallAbortCtrl");u(this,"smallEncoder");e.tinyId&&(this.tinyId=e.tinyId,yp(!0)),this._log||(this._log=e.logger),this.bussinessInfo=e.bussinessInfo,e.encodedDataProcessingListener&&this.setEncodedDataProcessingListener(e.encodedDataProcessingListener)}replaceTrack(e){return y(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=d=>{n.port2.close(),o(d.data)}})}fromWorker(e,r){if(this.state!="joined")throw"join room first";return o=>{var n;let s=new MessageChannel;s.port2.onmessage=d=>{d.data?o.next(d.data):o.complete()},s.port2.onmessageerror=d=>o.error(d),o.defer(()=>{s.port2.postMessage(null),s.port2.close()}),(n=this.session)==null||n.postMessage({cmd:e,payload:r},[s.port1])}}switchRole(e){return y(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 y(this,null,function*(){var p,m,g;let s=Lr.getEnv(),n=Qc(),d={isH264EncodeSupported:this.checkSystemResult.detail.isH264EncodeSupported,isVp8EncodeSupported:this.checkSystemResult.detail.isVp8EncodeSupported,frameWorkType:o,params:e,proxy_wt:(p=this.proxy_wt)==null?void 0:p.replace("https://",""),proxy_ws:(m=this.proxy_ws)==null?void 0:m.replace("wss://",""),proxy_cloud:(g=this.scheduleResult.iceServers)!=null&&g.length?this.scheduleResult.iceServers[0].urls:[],proxy_unified:this.proxy_unified,domains:this.scheduleResult.domains,env:s,osName:Ns(),browserInfo:Qc(),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:rt,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 wg.call(this,d),console.log(this),mu.playAudio(_=>this.postMessage({cmd:"setAudioWorkletPort"},[_])),this.checkDestroy()})}leave(){return y(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())})}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 y(this,null,function*(){let e=Je(be(this,"left"));Se(r=>y(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,ke(({data:r,port:o})=>{let s=this.audioManager.decodePipeline[0]({frame:{data:r.data.buffer}});o.postMessage(Ee(ee({},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 L.RECEIVED_PUBLISHED_USER_LIST:H.emit(e,ee({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 ru(this,r);this.remotePublishedUserMap.set(r.userId,o),this.emit("remote-published",o);return;case"5":{let _=r,b=this.remotePublishedUserMap.get(_);b&&(b.remoteVideoTrack.close(),b.remoteAuxiliaryTrack.close(),b.remoteAudioTrack.close(),this.remotePublishedUserMap.delete(_),this.emit("remote-unpublished",b))}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:_,muteState:b,flag:N}=r,k=this.remotePublishedUserMap.get(b.userId);if(!k){this.emit("remote-publish-state-changed",r);return}k.flag=N}H.emit(L.REMOTE_PUBLISH_STATE_CHANGED,ee({room:this},r)),this.emit("remote-publish-state-changed",r);return;case"network-quality":this.quality=ee({},r);let{uplinkLoss:s,uplinkRTT:n,uplinkInfo:d,downlinkInfo:p,msg_down_stream_info:m}=r,g={str_sdk_version:rt,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:To[Cn()]},msg_event_msg:wf(this.userId),str_acc_ip:this.relayip,str_client_ip:this.clientip,msg_up_stream_info:d,msg_down_stream_info:m};H.emit(L.HEARTBEAT_REPORT,{room:this,report:g}),this.emit("heartbeat-report",g),H.emit(L.NETWORK_QUALITY,{room:this,uplink:{rtt:n,loss:s},downlinks:p}),delete r.downlinkInfo;break;case"signal-connection-state-changed":H.emit(L.SIGNAL_CONNECTION_STATE_CHANGED,ee({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 y(this,null,function*(){let r=e.reduce((d,p)=>p.mediaType|d,0),o=this.sendMessage("publish",r).then(d=>d.err!==0?Promise.reject(d.err):d),s=0,n=d=>y(this,null,function*(){switch(yield o,d.muted&&(s|=d.mediaType),xt(d,d).add("mute",()=>{this.postMessage("mute",{mediaType:d.mediaType,userId:this.userId,srctinyid:this.tinyid,remove:!0})}).add("unmute",()=>{this.postMessage("unmute",{mediaType:d.mediaType,userId:this.userId,srctinyid:this.tinyid,add:!0})}),d.mediaType){case 1:Pg.call(this,d);break;default:yield kg.call(this,d)}});yield Promise.all(e.map(n)),s&&this.postMessage("mute",{mediaType:s,srctinyid:this.tinyid,userId:this.openid,remove:!0})})}unpublish(...e){return y(this,null,function*(){e.forEach(mt)})}subscribe(...e){return y(this,null,function*(){let r=e.reduce((_,b)=>b.mediaType|_,0),{userId:o,tinyId:s,streamType:n}=e[0],d=this.remotePublishedUserMap.get(o),p=ee({},d.subscribeState),m=Object.assign(new Qn,p);m.mediaType|=r,H.emit(L.SUBSCRIBE_START,{room:this,streamType:n,remotePublishedUser:d,subscribeState:m});let g=yield this.sendMessage("subscribe",{mediaType:m.mediaType,userId:o,srctinyid:s,mediaDescription:{audioParam:{mediaType:1,payloadFmtps:[{payloadType:111,fmtp:"minptime=10;useinbandfec=1"}]},videoParam:[4,8,2].filter(_=>m.mediaType&_).map(_=>({mediaType:_,payloadFmtps:[{payloadType:100,fmtp:"packetization-mode=1;profile-level-id=42e01f"}]}))}});console.dir("subscribe",g),yield Promise.all(e.filter(_=>!_.isSubscribed).map(_=>{switch(_.mediaType){case 1:return Mg.call(this,_);default:return Og.call(this,_)}})),H.emit(L.SUBSCRIBE_SUCCESS,{room:this,streamType:n,remotePublishedUser:d})})}unsubscribe(...e){return y(this,null,function*(){let r=0;for(let o of e)r|=o.mediaType,o.unsubscribe();if(e.length){let{userId:o,streamType:s,tinyId:n}=e[0];yield this.sendMessage("unSubscribe",{mediaType:r,srctinyid:n,userId:o}),H.emit(L.UNSUBSCRIBE_SUCCESS,{room:this,streamType:s,remotePublishedUser:this.remotePublishedUserMap.get(o)})}})}enableSmall(e){return y(this,null,function*(){var r;if(e){if(this.videoManager.smallTrack){let o=this.videoManager.cameraTrack;this.smallEncoder=yield fu.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),s=e?8:4;if(o.remoteVideoTrack.mediaType===s)return;let n={srctinyid:r.tinyId,mediaType:s,userId:r.userId,mediaDescription:{audioParam:{mediaType:1,payloadFmtps:[{payloadType:111,fmtp:"minptime=10;useinbandfec=1"}]},videoParam:[4,8].filter(d=>s&d).map(d=>({mediaType:d,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"))}};X([Gi(so.prototype.afterJoin),qe(["left",ne.INIT],"joined"),mg()],so.prototype,"join",1),X([qe("joined","left",{ignoreError:!0}),pg()],so.prototype,"leave",1),X([pd((...e)=>0),hg()],so.prototype,"publish",1),X([pd((...e)=>0),fg()],so.prototype,"unpublish",1),X([pd((...e)=>e[0].userId),gg()],so.prototype,"subscribe",1);var Eu=so;Zs.frameWorkType=37;Zs.create=function(i){let t=Zs._create.call(this,Eu,i);return t._use(Bm,i==null?void 0:i.assetsPath),i!=null&&i.assetsPath&&(Dt.assetsPath=i==null?void 0:i.assetsPath),console.log("trtc wasm sdk:",rt,"created",Dt),t};Object.assign(Zs.prototype,{_setCurrentSpeaker(i){let t=et("player");return t!=null&&t.setSinkId?t.setSinkId(i):Promise.reject("not support")},_enableVideoDecodeFallback(i,t){return y(this,null,function*(){return this.startPlugin(Bm.Name,{type:"webCodecs",renderer:"videoFrame",track:i,config:{codec:"avc1.420028"},fallback:"wasm"}),new Promise((e,r)=>{Se(be(i,"decode-downgrade-state-changed"),yr(o=>o.state==="STARTED"),Ar(1),Lm(1e4),Je(be(i,ne.INIT)),ke(e,r))})})}});var s$=Zs;export{s$ as default};
|