trtc-sdk-v5 5.14.2-wasm.3 → 5.14.2-wasm.4

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/trtc.esm.js CHANGED
@@ -90,13 +90,13 @@ return ret;
90
90
  `);x.isVoid||(he+=` return retType.toWireType(destructors, rv);
91
91
  `),he+=`};
92
92
  `,J.push(he);var Ne,Ee,xe=Yc(Function,J).apply(null,K);return Ne=xe,Ee=Xs.length,Xs.push(Ne),G=Ee,Qs[$]=G,G},f:()=>{Ir("")},c:sa,t:(S,T,w)=>C.copyWithin(S,T,T+w),s:S=>{C.length,Ir("OOM")},i:(S,T,w,x)=>{for(var $,G,J,K=0,te=0;te<w;te++){var j=ge[T>>2],he=ge[T+4>>2];T+=8;for(var Me=0;Me<he;Me++)$=S,G=C[j+Me],J=void 0,J=sd[$],G===0||G===10?(($===1?f:g)(Ko(J,0)),J.length=0):J.push(G);K+=he}return ge[x>>2]=K,0}},Lr=(function(){var S,T,w,x,$={a:nd};function G(J,K){var te,j,he=J.exports;return A=(R=he).v,te=A.buffer,o.HEAP8=N=new Int8Array(te),o.HEAP16=P=new Int16Array(te),o.HEAP32=H=new Int32Array(te),o.HEAPU8=C=new Uint8Array(te),o.HEAPU16=z=new Uint16Array(te),o.HEAPU32=ge=new Uint32Array(te),o.HEAPF32=Ue=new Float32Array(te),o.HEAPF64=W=new Float64Array(te),we=R.z,j=R.w,Zn.unshift(j),function(){if(Yr--,o.monitorRunDependencies&&o.monitorRunDependencies(Yr),Yr==0&&(Ws!==null&&(clearInterval(Ws),Ws=null),eo)){var Me=eo;eo=null,Me()}}(),he}if(Yr++,o.monitorRunDependencies&&o.monitorRunDependencies(Yr),o.instantiateWasm)try{return o.instantiateWasm($,G)}catch(J){g("Module.instantiateWasm callback failed with error: "+J),r(J)}(S=p,T=_i,w=$,x=function(J){G(J.instance)},S||typeof WebAssembly.instantiateStreaming!="function"||re(T)||typeof fetch!="function"?Zr(T,w,x):fetch(T,{credentials:"same-origin"}).then(J=>WebAssembly.instantiateStreaming(J,w).then(x,function(K){return g("wasm streaming compile failed: "+K),g("falling back to ArrayBuffer instantiation"),Zr(T,w,x)}))).catch(r)}(),S=>(Lr=R.x)(S)),lo=S=>(lo=R.y)(S),Ys=S=>(Ys=R.A)(S),ad=(o.__embind_initialize_bindings=()=>(o.__embind_initialize_bindings=R.B)(),S=>(ad=R.C)(S));o.dynCall_jiji=(S,T,w,x,$)=>(o.dynCall_jiji=R.D)(S,T,w,x,$);function cd(){function S(){qt||(qt=!0,o.calledRun=!0,Ki||(Ii(Zn),e(o),o.onRuntimeInitialized&&o.onRuntimeInitialized(),function(){if(o.postRun)for(typeof o.postRun=="function"&&(o.postRun=[o.postRun]);o.postRun.length;)T=o.postRun.shift(),Kn.unshift(T);var T;Ii(Kn)}()))}Yr>0||(function(){if(o.preRun)for(typeof o.preRun=="function"&&(o.preRun=[o.preRun]);o.preRun.length;)T=o.preRun.shift(),Yn.unshift(T);var T;Ii(Yn)}(),Yr>0||(o.setStatus?(o.setStatus("Running..."),setTimeout(function(){setTimeout(function(){o.setStatus("")},1),S()},1)):S()))}if(eo=function S(){qt||cd(),qt||(eo=S)},o.preInit)for(typeof o.preInit=="function"&&(o.preInit=[o.preInit]);o.preInit.length>0;)o.preInit.pop()();return cd(),t.ready}})();var T_=(i=>(i.ROOM_DESTROY="1",i.JOIN_START="21",i.JOIN_SCHEDULE_SUCCESS="22",i.JOIN_SIGNAL_CONNECTION_START="23",i.JOIN_SIGNAL_CONNECTION_END="24",i.JOIN_SEND_CMD="25",i.JOIN_RECEIVED_CMD_RES="26",i.JOIN_SUCCESS="27",i.JOIN_FAILED="28",i.LEAVE_START="51",i.LEAVE_SEND_CMD="52",i.LEAVE_SUCCESS="53",i.PUBLISH_START="61",i.SEND_FIRST_VIDEO_FRAME="62",i.PUBLISH_FAILED="63",i.SUBSCRIBE_START="81",i.SUBSCRIBE_SUCCESS="82",i.SUBSCRIBE_FAILED="84",i.UNSUBSCRIBE_SUCCESS="83",i.LOCAL_TRACK_CAPTURE_START="101",i.LOCAL_TRACK_CAPTURE_SUCCESS="102",i.LOCAL_TRACK_CAPTURE_FAILED="103",i.LOCAL_TRACK_PUBLISHED="104",i.LOCAL_TRACK_UNPUBLISHED="105",i.LOCAL_TRACK_REPLACED="106",i.SWITCH_DEVICE_SUCCESS="107",i.TRACK_MUTED="108",i.TRACK_UNMUTED="109",i.REMOTE_TRACK_SUBSCRIBED="110",i.REMOTE_TRACK_UNSUBSCRIBED="111",i.LOCAL_TRACK_RECAPTURE="112",i.LOCAL_AUDIO_STARTED="113",i.LOCAL_AUDIO_STOPPED="114",i.REMOTE_AUDIO_STARTED="115",i.REMOTE_AUDIO_STOPPED="116",i.PLAY_TRACK_START="151",i.PLAYER_STATE_CHANGED="152",i.VIDEO_LOADED_DATA="153",i.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",i.AUDIO_CONTEXT_LONG_SUSPENDED="155",i.REMOTE_VIDEO_PLAY_START="156",i.REMOTE_VIDEO_PLAY_FINISH="157",i.SIGNAL_CONNECTION_STATE_CHANGED="201",i.PEER_CONNECTION_STATE_CHANGED="202",i.SINGLE_CONNECTION_STAT="203",i.SPC_RECONNECTED="204",i.HEARTBEAT_REPORT="251",i.RECEIVED_PUBLISHED_USER_LIST="252",i.REMOTE_PUBLISH_STATE_CHANGED="253",i.AUDIO_LEVEL_INTERVAL="260",i.NETWORK_QUALITY="261",i.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",i.QUALITY_LIMITATION_CHANGED="263",i.LOG="264",i.AUDIO_PROCESSOR_DEBUG="265",i.SSO_SWITCH="266",i.SWITCH_ROOM_START="401",i.SWITCH_ROOM_SUCCESS="407",i.SWITCH_ROOM_FAILED="408",i))(T_||{}),ab="5.0.0",cb=typeof importScripts!="undefined",db=typeof registerProcessor!="undefined",ub="",lb="web.sdk.qcloud.com",mb=`https://${lb}/trtc/webrtc/doc`,AU=`${mb}/zh-cn/`,hb="https://yun.tim.qq.com",pb="https://apisgp.my-imcloud.com",fb={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},ks=(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))(ks||{});var I_={"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}},yU=I_["480p_2"],bU=I_["120p_2"],cl={CANVAS:"canvas",AUDIO:"audio",VIDEO:"video",SCREEN:"screen",SMALL:"small",BIG:"big",AUXILIARY:"auxiliary",SMALL_VIDEO:"smallVideo",FACING_MODE_USER:"user",FACING_MODE_ENVIRONMENT:"environment",MUTE:"mute",UNMUTE:"unmute",ENDED:"ended",PLAYING:"playing",PAUSE:"pause",ERROR:"error",LOADEDDATA:"loadeddata",LOADEDMETADATA:"loadedmetadata",AUDIO_INPUT:"audioinput",VIDEO_INPUT:"videoinput",DETAIL:"detail",TEXT:"text",MAIN:"main",BACKUP:"backup",BANNED:"banned",KICK:"kick",USER_TIME_OUT:"user_time_out",ROOM_DISBAND:"room_disband",SEI_MESSAGE:"sei-message",ADD:"add",REMOVE:"remove",REPLACE:"replace",TRACK:"track",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",TRANSCEIVER_DIRECTION_SENDONLY:"sendonly",TRANSCEIVER_DIRECTION_RECVONLY:"recvonly",ENTER_PICTURE_IN_PICTURE:"enterpictureinpicture",LEAVE_PICTURE_IN_PICTURE:"leavepictureinpicture",RESIZE:"resize",TIME_UPDATE:"timeupdate"},RU=cl.MAIN,vU=cl.AUXILIARY,CU=cl.BIG,NU=cl.SMALL;var DU=Object.keys(ks);var gb=function(i,t,e,r){return new(e||(e=Promise))(function(o,s){function n(l){try{d(r.next(l))}catch(p){s(p)}}function a(l){try{d(r.throw(l))}catch(p){s(p)}}function d(l){var p;l.done?o(l.value):(p=l.value,p instanceof e?p:new e(function(f){f(p)})).then(n,a)}d((r=r.apply(i,t||[])).next())})},$p=Symbol(32),Hp=Symbol(16),Wp=Symbol(8),Gn=class{constructor(i){this.g=i,this.consumed=0,i&&(this.need=i.next().value)}setG(i){this.g=i,this.demand(i.next().value,!0)}consume(){this.buffer&&this.consumed&&(this.buffer.copyWithin(0,this.consumed),this.buffer=this.buffer.subarray(0,this.buffer.length-this.consumed),this.consumed=0)}demand(i,t){return t&&this.consume(),this.need=i,this.flush()}read(i){return gb(this,void 0,void 0,function*(){return this.lastReadPromise&&(yield this.lastReadPromise),this.lastReadPromise=new Promise((t,e)=>{var r;this.reject=e,this.resolve=o=>{delete this.lastReadPromise,delete this.resolve,delete this.need,t(o)},this.demand(i,!0)||(r=this.pull)===null||r===void 0||r.call(this,i)})})}readU32(){return this.read($p)}readU16(){return this.read(Hp)}readU8(){return this.read(Wp)}close(){var i;this.g&&this.g.return(),this.buffer&&this.buffer.subarray(0,0),(i=this.reject)===null||i===void 0||i.call(this,new Error("EOF")),delete this.lastReadPromise}flush(){if(!this.buffer||!this.need)return;let i=null,t=this.buffer.subarray(this.consumed),e=0,r=o=>t.length<(e=o);if(typeof this.need=="number"){if(r(this.need))return;i=t.subarray(0,e)}else if(this.need===$p){if(r(4))return;i=t[0]<<24|t[1]<<16|t[2]<<8|t[3]}else if(this.need===Hp){if(r(2))return;i=t[0]<<8|t[1]}else if(this.need===Wp){if(r(1))return;i=t[0]}else if("buffer"in this.need){if("byteOffset"in this.need){if(r(this.need.byteLength-this.need.byteOffset))return;new Uint8Array(this.need.buffer,this.need.byteOffset).set(t.subarray(0,e)),i=this.need}else if(this.g)return void this.g.throw(new Error("Unsupported type"))}else{if(r(this.need.byteLength))return;new Uint8Array(this.need).set(t.subarray(0,e)),i=this.need}return this.consumed+=e,this.g?this.demand(this.g.next(i).value,!0):this.resolve&&this.resolve(i),i}write(i){if(i instanceof Uint8Array?this.malloc(i.length).set(i):"buffer"in i?this.malloc(i.byteLength).set(new Uint8Array(i.buffer,i.byteOffset,i.byteLength)):this.malloc(i.byteLength).set(new Uint8Array(i)),!this.g&&!this.resolve)return new Promise(t=>this.pull=t);this.flush()}writeU32(i){this.malloc(4).set([i>>24&255,i>>16&255,i>>8&255,255&i]),this.flush()}writeU16(i){this.malloc(2).set([i>>8&255,255&i]),this.flush()}writeU8(i){this.malloc(1)[0]=i,this.flush()}malloc(i){if(this.buffer){let t=this.buffer.length,e=t+i;if(e<=this.buffer.buffer.byteLength-this.buffer.byteOffset)this.buffer=new Uint8Array(this.buffer.buffer,this.buffer.byteOffset,e);else{let r=new Uint8Array(e);r.set(this.buffer),this.buffer=r}return this.buffer.subarray(t,e)}return this.buffer=new Uint8Array(i),this.buffer}};Gn.U32=$p,Gn.U16=Hp,Gn.U8=Wp;var Eb=128,_b=127,wU=~_b,OU=Math.pow(2,31);function Lp(i){let t=new Gn;for(;i>=128;)t.malloc(1)[0]=255&i|Eb,i>>>=7;return t.malloc(1)[0]=255&i,t.buffer||new Uint8Array(0)}function Gp(i,t=0){let e=new Gn,r=t<<3;switch(typeof i){case"boolean":let o=e.malloc(2);o[0]=r,o[1]=i?1:0;break;case"number":e.malloc(1)[0]=r,e.write(Lp(i));break;case"string":e.malloc(1)[0]=2|r;let s=new TextEncoder().encode(i);e.write(Lp(s.length));let n=e.malloc(s.length);for(let d=0;d<s.length;d++)n[d]=s[d];break;case"object":let a=new Gn;if(Array.isArray(i))for(let d=0;d<i.length;d++){let l=Gp(i[d],d+1);l&&a.write(l)}else{let d=1;for(let l in i){let p=Gp(i[l],d++);p&&a.write(p)}}t===0?a.buffer&&e.write(a.buffer):(e.malloc(1)[0]=2|r,a.buffer&&(e.write(Lp(a.buffer.length)),e.write(a.buffer)))}return e.buffer||new Uint8Array(0)}var o_=class{constructor(){tt(this,"buffer"),this.buffer=[]}get data(){return this.buffer}get length(){return this.buffer.length}writeInt32(i){this.buffer.push(i>>>24&255),this.buffer.push(i>>>16&255),this.buffer.push(i>>>8&255),this.buffer.push(255&i)}writeInt16(i){this.buffer.push(i>>>8&255),this.buffer.push(255&i)}writeByte(i){this.buffer.push(255&i)}writeBytes(i){for(let t=0;t<i.length;t++)this.buffer.push(i[t])}};function s_(i,t,e){i[e]=t>>>24&255,i[e+1]=t>>>16&255,i[e+2]=t>>>8&255,i[e+3]=255&t}function ur(i,t){return i[t]<<24|i[t+1]<<16|i[t+2]<<8|i[t+3]}function n_(i,t){return i[t]}function _c(i,t,e){return new TextDecoder().decode(Tb(i,t,e))}function Tb(i,t,e){return i.slice(t,t+e)}var kp=0,jp=2654435769,qp=16,a_=4,Rc=2,vc=7;function Ib(i,t,e,r="AVQualityReportSvc.C2S",o=2e3,s=2,n=30){return{version:o,encryption:s,d2:"",d2Len:0,uinType:n,uin:"",uinLen:0,reqHead:{seqNumber:e,appId:i,appidAtThird:new Uint8Array(0),a2:"",a2Len:0,serviceCmd:r,serviceCmdLen:0,cookie:"",cookieLen:0,imei:"",imeiLen:0,ksid:"",ksidLen:0,clientVersionInfo:"",clientVersionInfoLen:0},busiBuff:t}}function Sb(i,t){let e=new o_,r=Ib(t,i,kp);kp=kp+1&2147483647,e.writeInt32(0),e.writeInt32(r.version),e.writeByte(r.encryption);let o=new TextEncoder().encode(r.d2);e.writeInt32(o.length+4),o&&e.writeBytes(o),e.writeByte(r.uinType);let s=new TextEncoder().encode(r.uin);e.writeInt32(s.length+4),s.length&&e.writeBytes(s);let n=new o_;n.writeInt32(0),n.writeInt32(r.reqHead.seqNumber),n.writeInt32(r.reqHead.appId),n.writeByte(r.reqHead.appId>>>24&255),n.writeByte(r.reqHead.appId>>>16&255),n.writeByte(r.reqHead.appId>>>8&255),n.writeByte(255&r.reqHead.appId);for(let z=4;z<16;z++)n.writeByte(0);let a=new TextEncoder().encode(r.reqHead.a2);n.writeInt32(a.length+4),a.length&&n.writeBytes(a);let d=new TextEncoder().encode(r.reqHead.serviceCmd);n.writeInt32(d.length+4),d.length&&n.writeBytes(d);let l=new TextEncoder().encode(r.reqHead.cookie);n.writeInt32(l.length+4),l.length&&n.writeBytes(l);let p=new TextEncoder().encode(r.reqHead.imei);n.writeInt32(p.length+4),p.length&&n.writeBytes(p);let f=new TextEncoder().encode(r.reqHead.ksid);n.writeInt32(f.length+4),f.length&&n.writeBytes(f);let g=new TextEncoder().encode(r.reqHead.clientVersionInfo);n.writeInt16(g.length+2),g.length&&n.writeBytes(g);let A=n.length;n.data[0]=A>>>24&255,n.data[1]=A>>>16&255,n.data[2]=A>>>8&255,n.data[3]=255&A,zp(i)&&(i=new TextEncoder().encode(i)),n.writeInt32(i.length+4),i.length&&n.writeBytes(i);let R=new Uint8Array(n.data),N=null;r.encryption===1?N=new TextEncoder().encode(r.uin):r.encryption===2&&(N=new Uint8Array(16)),N&&(R=Ab(R,N)),e.writeBytes(R);let C=new Uint8Array(e.data),P=C.length;return C[0]=P>>>24&255,C[1]=P>>>16&255,C[2]=P>>>8&255,C[3]=255&P,C}function Ab(i,t){let e=i.length,r=(e+1+Rc+vc)%8;r&&(r=8-r);let o=new Uint8Array(e+1+Rc+vc+r),s=0,n=new Uint8Array(8),a=new Uint8Array(8),d=new Uint8Array(8),l=0;n[0]=248&Math.floor(256*Math.random())|r,l=1;for(let f=0;f<r;f++)n[l]=255&Math.floor(256*Math.random()),l+=1;for(let f=0;f<Rc;)if(l<8&&(n[l]=255&Math.floor(256*Math.random()),l+=1,f+=1),l===8){Up(n,t,a,d,o,s),s+=8,l=0;for(let g=0;g<8;g++)d[g]=o[s-8+g]}let p=0;for(;p<e;)if(l<8&&(n[l]=i[p],l+=1,p+=1),l===8){Up(n,t,a,d,o,s),s+=8,l=0;for(let f=0;f<8;f++)d[f]=o[s-8+f]}for(let f=0;f<vc;)if(l<8&&(n[l]=0,l+=1,f+=1),l===8){Up(n,t,a,d,o,s),s+=8,l=0;for(let g=0;g<8;g++)d[g]=o[s-8+g]}return o}function Up(i,t,e,r,o,s){for(let n=0;n<8;n++)i[n]^=r[n];yb(i,t,o,s);for(let n=0;n<8;n++)o[s+n]^=e[n];for(let n=0;n<8;n++)e[n]=i[n]}function yb(i,t,e,r){let o=ur(i,0),s=ur(i,4),n=[];for(let d=0;d<4;d++)n[d]=ur(t,4*d);let a=0;for(let d=0;d<qp;d++)a+=jp,a>>>=0,o+=(s<<4)+n[0]^s+a^(s>>>5)+n[1],o>>>=0,s+=(o<<4)+n[2]^o+a^(o>>>5)+n[3],s>>>=0;s_(e,o,r),s_(e,s,r+4)}var bb=0,S_=function(){return Date.now()+bb},Rb=function(){let i=new Date;return i.setTime(S_()),i.toLocaleString()},vb=function(i){let t=String(i.getMilliseconds());return"padStart"in String.prototype&&(t=t.toString().padStart(3,"0")),`${i.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")}:${t}`};function Cb(i){let t=Nb(i);return t==null?void 0:t.busiBuff}function Nb(i){try{let t={},e=0;t.totalLength=ur(i,e),e+=4,t.version=ur(i,e),e+=4,t.encryption=n_(i,e),e+=1,t.uinType=n_(i,e),e+=1,t.uinLength=ur(i,e),e+=4,t.uin=t.uinLength>4?_c(i,e,t.uinLength-4):"",e+=t.uinLength-4;let r=i.slice(e);if(t.encryption===2){let o=new Uint8Array(16).fill(0);i=Db(r,o),t.decrypted=!0,e=0}else i=r,e=0;return t.rspHeadLength=ur(i,e),e+=4,t.seqNo=ur(i,e),e+=4,t.retCode=ur(i,e),e+=4,t.retStrLength=ur(i,e),e+=4,t.retStr=t.retStrLength?_c(i,e,t.retStrLength-4):"",e+=t.retStrLength-4,t.serviceCmdLength=ur(i,e),e+=4,t.serviceCmd=t.serviceCmdLength?_c(i,e,t.serviceCmdLength-4):"",e+=t.serviceCmdLength-4,t.cookieLength=ur(i,e),e+=4,t.cookie=t.cookieLength?_c(i,e,t.cookieLength-4):"",e+=t.cookieLength-4,t.flag=ur(i,e),e+=4,t.busiBuffLength=ur(i,e),e+=4,t.busiBuff=t.busiBuffLength?_c(i,e,t.busiBuffLength-4):"",e+=t.busiBuffLength-4,t}catch(t){}}function A_(i,t){let e=i[0]<<24|i[1]<<16|i[2]<<8|i[3],r=i[4]<<24|i[5]<<16|i[6]<<8|i[7];e>>>=0,r>>>=0;let o=jp*qp>>>0;for(let s=0;s<qp;s++)r-=(e<<a_)+t[2]^e+o^(e>>>5)+t[3],r>>>=0,e-=(r<<a_)+t[0]^r+o^(r>>>5)+t[1],e>>>=0,o-=jp,o>>>=0;return new Uint8Array([e>>>24&255,e>>>16&255,e>>>8&255,255&e,r>>>24&255,r>>>16&255,r>>>8&255,255&r])}function Db(i,t){let e=0,r=new Uint8Array(8).fill(0),o=A_(new Uint8Array(i.slice(0,8)),t),s=7&o[0],n=i.length-1-s-Rc-vc,a=new Uint8Array(n),d=0,l=r,p=i.slice(0,8);e=8;let f=1;f+=s;for(let A=1;A<=Rc;)if(f<8)f++,A++;else if(f===8){let R=Vp(i,e,l,p,o,t);l=R.ivPreCrypt,p=R.ivCurCrypt,o=R.debiBuf,e=R.bufPos,f=0}let g=n;for(;g>0;)if(f<8)a[d++]=o[f]^l[f],f++,g--;else if(f===8){let A=Vp(i,e,l,p,o,t);l=A.ivPreCrypt,p=A.ivCurCrypt,o=A.debiBuf,e=A.bufPos,f=0}for(let A=1;A<=vc;)if(f<8)o[f],l[f],f++,A++;else if(f===8){if(e>=i.length)break;let R=Vp(i,e,l,p,o,t);if(!R.success)break;l=R.ivPreCrypt,p=R.ivCurCrypt,o=R.debiBuf,e=R.bufPos,f=0}return a}function Vp(i,t,e,r,o,s){if(t+8>i.length)return{success:!1};let n=new Uint8Array(r),a=i.slice(t,t+8),d=new Uint8Array(8);for(let l=0;l<8;l++)d[l]=o[l]^a[l];return{success:!0,ivPreCrypt:n,ivCurCrypt:a,debiBuf:A_(d,s),bufPos:t+8}}var c_=typeof TextDecoder!="undefined"?new TextDecoder:void 0;function wb({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(d=>d.clone().json().then(l=>({data:l}),()=>d.arrayBuffer().then(l=>({data:Cb(new Uint8Array(l))||(c_?c_.decode(l):l)})))).then(s,n);let a=new XMLHttpRequest;a.onreadystatechange=()=>{if(a.readyState===4)if(a.status>=200&&a.status<300)try{let d=JSON.parse(a.response);s({data:d})}catch(d){s({data:a.response})}else n({status:a.status,statusText:a.statusText||"request failed!"})},a.timeout=r||5e3,a.open(e,i,!0),a.send(t)})}var Ob=Object.prototype.hasOwnProperty,Tc=i=>typeof i=="function",Hn=i=>i===void 0,Mb=i=>typeof i=="boolean",xb=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 Pb(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(xb(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(Ob.call(i,t))return!1;return!0}return!1}var Lb=0,kb=1,d_=2;function Ub({retryFunction:i,settings:t,onError:e,onRetrying:r,onRetryFailed:o,onRetrySuccess:s,context:n}){return function(...a){let{retries:d=5,timeout:l=1e3}=t,p=0,f=-1,g=Lb,A=(R,N)=>y(this,null,function*(){let C=n||this;try{let P=yield i.apply(C,a);p>0&&s&&s.call(this,p),p=0,R(P)}catch(P){let z=()=>{clearTimeout(f),p=0,g=d_,N(P)},H=()=>{g!==d_&&p<(Tc(d)?d():d)?(p++,g=kb,Tc(r)&&r.call(this,p,z),f=window.setTimeout(()=>{f=-1,A(R,N)},Tc(l)?l(p):l)):(z(),Tc(o)&&o.call(this,P))};Tc(e)?e.call(this,{error:P,retry:H,reject:N,retryFuncArgs:a,retriedCount:p}):H()}});return new Promise(A)}}var Vb=Ub,Fp=class y_{constructor(t){tt(this,"_parentPath"),tt(this,"userId"),tt(this,"remoteUserId"),tt(this,"id"),tt(this,"sdkAppId"),tt(this,"type"),tt(this,"isLocal"),this.id=t.id,this.userId=t.userId,this.sdkAppId=t.sdkAppId,this.remoteUserId=t.remoteUserId,this.isLocal=!Mb(t.isLocal)||t.isLocal,this.type=this.isLocal?"":t.type}getFullId(){return this._parentPath&&this.id?`${this._parentPath}-${this.id}`:this._parentPath?this._parentPath:this.id}createChild(t){let e=new y_({id:t.id,userId:Hn(t.userId)?this.userId:t.userId,sdkAppId:Hn(t.sdkAppId)?this.sdkAppId:t.sdkAppId,type:Hn(t.type)?this.type:t.type,isLocal:Hn(t.isLocal)?this.isLocal:t.isLocal,remoteUserId:Hn(t.remoteUserId)?this.remoteUserId:t.remoteUserId});return e.bindParent(this),e}bindParent(t){let e=t.getFullId();this._parentPath!==e&&(this.debug(`bind logger parent: ${t.id}`),this._parentPath=e,this.userId=t.userId||this.userId,this.sdkAppId=t.sdkAppId||this.sdkAppId)}setUserId(t){this.userId=t}setSdkAppId(t){this.sdkAppId=t}log(t,e){let r=this.isLocal?this.userId:this.remoteUserId,o=this.getFullId();e.unshift(`[${this.isLocal?"\u2191":"\u2193"}${this.type&&this.type!=="main"?"*":""}${o}${r?`|${r}`:""}]`),TR.log(t,e,Hn(this.userId)||Pb(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)}},pi=typeof navigator=="undefined"?"":navigator.userAgent,Re=i=>new RegExp(i,"i").test(pi),Rt=i=>{if(Re(i)){let t=new RegExp(`${i}\\/([\\d.]+)`),e=pi.match(t);if(e&&e[1])return e[1]}return""},dl=i=>{if(Re(i)){let t=new RegExp(`${i}\\/(\\d+)`),e=pi.match(t);if(e&&e[1])return parseFloat(e[1])}return NaN},u_=/AppleWebKit\/([\d.]+)/i.exec(pi),Fb=u_?parseFloat(u_[1]):NaN,b_=Re("iPad"),R_=typeof navigator!="undefined"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&Re("Macintosh"),v_=Re("iPhone")&&!b_,Bb=Re("iPod"),Xp=v_||b_||Bb||R_,Cc=Re("Android"),C_=function(){if(Cc){let i=pi.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}(),MU=Cc&&Re("webkit")&&C_<2.3,xU=Cc&&C_<5&&Fb<537,$b=Re("Firefox"),Hb=Rt("Firefox"),PU=dl("Firefox"),N_=Re("Edge"),Wb=Rt("Edge"),D_=Re("Edg"),Gb=Rt("Edg"),LU=dl("Edg"),w_=Re("SogouMobileBrowser"),jb=Rt("SogouMobileBrowser"),O_=Re("MetaSr\\s"),qb=Rt("MetaSr\\s"),Us=Re("TBS"),zb=Rt("TBS"),M_=Re("XWEB"),Jb=Rt("XWEB"),kU=Re("MSIE\\s8\\.0"),Xb=Re("MSIE\\/\\d+"),UU=function(){if(Xb){let i=/MSIE\s(\d+)\.\d/.exec(pi),t=i&&parseFloat(i[1]);return!t&&/Trident\/7.0/i.test(pi)&&/rv:11.0/.test(pi)&&(t=11),t}return NaN}(),Qb=Re("(micromessenger|webbrowser)"),Yb=Rt("MicroMessenger"),Qp=!Us&&Re("MQQBrowser")&&Re("COVC"),Yp=!Us&&Re("MQQBrowser")&&!Re("COVC"),l_=Yp||Qp?Rt("MQQBrowser"):"",x_=!Us&&Re(" QQBrowser"),Zb=Rt(" QQBrowser"),P_=!Us&&Re("QQBrowserLite"),Kb=Rt("QQBrowserLite"),L_=!Us&&Re("MQBHD"),eR=Rt("MQBHD"),VU=Re("Windows"),FU=!Xp&&Re("MAC OS X"),BU=!Cc&&Re("Linux"),$U=Re("CrOS"),HU=Re("MicroMessenger"),WU=Re("UCBrowser"),GU=Re("Electron"),k_=Re("MiuiBrowser"),tR=Rt("MiuiBrowser"),U_=Re("HuaweiBrowser"),jU=Re("Huawei")||Re("HUAWEI"),qU=Re("Honor")||Re("HONOR"),rR=Rt("HuaweiBrowser"),V_=Re("SamsungBrowser"),iR=Rt("SamsungBrowser"),F_=Re("HeyTapBrowser"),oR=Rt("HeyTapBrowser"),B_=Re("VivoBrowser"),sR=Rt("VivoBrowser"),zU=Re("OpenHarmony"),JU=Rt("OpenHarmony"),nR=()=>dl("Chrome"),m_=Re("CriOS"),$_=Re("Chrome"),aR=!N_&&!O_&&!w_&&!Us&&!M_&&!D_&&!x_&&!k_&&!U_&&!V_&&!F_&&!B_&&$_,cR=Re("HeadlessChrome"),XU=nR(),dR=Rt("Chrome"),QU=dl("Electron"),uR=!$_&&!Yp&&!Qp&&!P_&&!L_&&Re("Safari"),H_=Rt("Version"),YU=/Android.*(wv|.0.0.0)/.test(pi),W_=(()=>{if(R_)return H_;if(Xp){let i=pi.match(/OS (\d+)_(\d+)/i);if(i&&i[1]){let t=i[1];return i[2]&&(t+=`.${i[2]}`),t}}return""})(),ZU=Number(W_.split(".")[0]),KU=(()=>{let i=Number(W_.split(".")[0]);return i===14||i===13})(),eV=typeof location!="undefined"&&(location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1"),tV=lR();function lR(){let i=new Map([[$b,["Firefox",Hb]],[D_,["Edg",Gb]],[aR,["Chrome",dR]],[m_,["ChiOS",Rt("CriOS")]],[uR&&!m_,["Safari",H_]],[Us,["TBS",zb]],[M_,["XWEB",Jb]],[Qb&&v_,["WeChat",Yb]],[x_,["QQ(Win)",Zb]],[Yp,["QQ(Mobile)",l_]],[Qp,["QQ(Mobile X5)",l_]],[P_,["QQ(Mac)",Kb]],[L_,["QQ(iPad)",eR]],[k_,["MI",tR]],[U_,["HW",rR]],[V_,["Samsung",iR]],[F_,["OPPO",oR]],[B_,["VIVO",sR]],[N_,["EDGE",Wb]],[w_,["SogouMobile",jb]],[O_,["Sogou",qb]]]),t="unknown",e="unknown";return i.has(!0)&&([t,e]=i.get(!0)),{name:t,version:e}}var mR=E_(__(),1),hR=new mR.default,Lo=hR,ol=T_,pR=class{constructor(){tt(this,"enable",!1),tt(this,"ssoFailCount",0),Lo.on("22",({schedule:i})=>{var t;(t=i==null?void 0:i.config)!=null&&t.sso&&Lo.emit("266",{enable:!0})}),Lo.on("266",({enable:i})=>{this.enable=i})}handleUploadFailed(){this.ssoFailCount++,this.ssoFailCount>3&&Lo.emit("266",{enable:!1})}},h_=new pR,fR="%cTRTC%c%s",gR="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",ER="display: inline",G_=class j_{constructor(){tt(this,"_isEnableUploadLog",!0),tt(this,"_localJoinedUser",new Map),tt(this,"_queue",[]),tt(this,"_timeoutId",-1),tt(this,"_logLevel",1),tt(this,"_logLevelToUpload",2),cb||db||(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){Lo.on(ol.JOIN_SCHEDULE_SUCCESS,({schedule:t})=>{var e;(e=t==null?void 0:t.config)!=null&&e.logLevelToUpload&&ks[t.config.logLevelToUpload]&&(this._logLevelToUpload=t.config.logLevelToUpload)}),Lo.on(ol.JOIN_START,({params:t})=>{this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload()}),Lo.on(ol.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(zp(r.userId)&&AR(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:a,logs:d}=o[s],l={timestamp:Rb(),sdkAppId:String(a),userId:n,version:ab,log:d.map(g=>g.log).join(`
93
- `)},p=JSON.stringify(l),f=h_.enable?RR(l,2002,a):p;yield this.uploadLogWithRetry(f,a,f instanceof Uint8Array,p),d.forEach(g=>g.uploaded=!0)}}catch(o){}let r=e.filter(o=>!o.uploaded);r.length>0&&(this._queue=r.concat(this._queue))})}uploadLogWithRetry(t,e,r,o){return Vb({retryFunction:()=>wb({url:SR(e,fb.LOG),body:t,timeout:5e3,priority:"low"}).then(s=>{r&&s.data!=="ok"&&(h_.handleUploadFailed(),this.uploadLogWithRetry(o,e,!1,o))}),settings:{retries:3,timeout:2e3},onError:({retry:s})=>{s()}})()}getPrefix(t){let e=new Date;return e.setTime(S_()),`[${vb(e)}] <${ks[t]}>`}getLogLevel(){return this._logLevel}setLogLevel(t){q_(ks[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(zp(t))return t;try{return t instanceof Error?t.toString():JSON.stringify(t)}catch(e){return""}}addLogToQueue(t,e,r=!0,o,s){let n={log:e.reduce((a,d)=>`${a} ${this.logChunkToString(d)}`.trim(),""),level:t,userId:o,sdkAppId:s,forAllJoinedClients:r};Lo.emit(ol.LOG,{log:n}),this._isEnableUploadLog&&t>=this._logLevelToUpload&&this._queue.push(n)}log(t,e,r=!0,o,s){var n;if(e.unshift(this.getPrefix(t)),this.addLogToQueue(t,e,r,o,s),t<this._logLevel)return;let a=((n=ks[t])==null?void 0:n.toLowerCase())||"info";j_.PRINT_LOG_TAG?console[a](fR,gR,ER,...e):console[a](...e)}debug(...t){this.log(1,t)}info(...t){this.log(2,t)}warn(...t){this.log(3,t)}error(...t){this.log(4,t)}createLogger(t){if(t.parent instanceof Fp){let e=t,{parent:r}=e,o=Qy(e,["parent"]),s=new Fp(o);return s.bindParent(r),s}return new Fp(t)}checkURLParam(){let t=new URLSearchParams(location.search).get("logLevelToUpload"),e=t?Number(t):-1;ks[e]&&(this._logLevelToUpload=e)}getQueue(){return this._queue}};tt(G_,"PRINT_LOG_TAG",!(Xp||Cc||cR));var _R=G_,TR=new _R,IR=i=>Number(i)<14e8,SR=function(i,t){let e;return e=ub||(IR(i)?pb:hb),`${e}/v5/AVQualityReportSvc/C2S?random=${Math.floor(Math.random()*ri(2,31))}&sdkappid=${i}&cmdtype=${t}`},rV=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},q_=i=>i===void 0,zp=i=>typeof i=="string",AR=i=>typeof i=="number",iV=typeof HTMLMediaElement!="undefined"&&"setSinkId"in HTMLMediaElement.prototype;function yR(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var{toString:oV}=Object.prototype;function bR(i,t,e,r){let o={data:i,random:Math.floor(Math.random()*2147483648),sdkAppId:e};return q_(r)||(o=Ac(Sc({},o),{gzip:+r})),{uint32_sdkappid:0,uint64_from_uin:0,uint32_timestamp:0,uint32_seq:0,msg_common_info:{msg_device_info:{enum_device_type:0,str_device_brand:"",str_device_model:"",str_device_board:"",str_device_cpu_abi:""},msg_system_info:{enum_os_type:0,str_os_version:"",msg_network_info:0},msg_network_info:{enum_network_type:0}},msg_report_content:{uint32_type:t,bytes_report_data:JSON.stringify(o)}}}function RR(i,t,e,r){try{let o=bR(i,t,e,r);return Sb(Gp(o),e)}catch(o){return JSON.stringify(i)}}var z_=class J_{constructor(t){this.core=t,tt(this,"contextMap",new Map),tt(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 J_.Name}getValidateRule(t){return{type:this.core.enums.BASIC_TYPE.Object}}createDecoder(t,e){var r;switch(t){case"wasm":let s=((r=this.core.assetsPath)==null?void 0:r.replace(/\/+$/,""))||".";return new nb(Ac(Sc({},e),{wasmPath:`${s}/videodec.wasm`}));case"webCodecs":return new Wn;case"mse":throw new Error("mse decoder not supported yet");default:throw new Error("Unsupported decoder type")}}start(t){this.decodeProcessorMap.set(t.track,this.decode(t)),this.core.room.videoManager.addDecodeProcessor({processor:({frame:e,track:r})=>{var o;return((o=this.decodeProcessorMap.get(r))==null?void 0:o({frame:e,track:r}))||e},type:3})}decode(t){let{pipe:e,take:r,subscribe:o}=this.core.rx;return({frame:s,track:n})=>{if(n!==t.track||s.type==="empty")return s;if(this.contextMap.has(n))return this.contextMap.get(n).decode(s);let a=this.core.room.videoManager.createDecodeContext(Ac(Sc({},t),{createDecoder:this.createDecoder}));return e(a.trackDoneOB,r(1),o(()=>{this.core.clearStarted(this,this.getGroup(t)),this.stop({track:n})})),this.contextMap.set(n,a),a.decode(s)}}stop(t){if(t!=null&&t.track){let e=this.contextMap.get(t.track);e&&(e.close("stop"),this.report(e,t.track),this.contextMap.delete(t.track))}else this.contextMap.forEach((e,r)=>{e.close("stop"),this.contextMap.delete(r)});this.contextMap.size===0&&this.core.room.videoManager.removeDecodeProcessor({type:3})}report(t,e){if(t.isReported)return;t.isReported=!0;let r=yR()-t.startPerformanceTime,{renderFreezeTotal:o,dataFreezeTotal:s}=this.getRemoteTrackFreezeDuration(e,t),n=`report health data: ${t.track.userId} ${t.track.streamType} ${t.type}+${t.renderer} goodType\uFF1A${t.goodType} ${t.failedReason?`failedReason: ${t.failedReason}`:""}`;r&&(this.core.kvStatManager.addNumber({key:514850,value:Math.floor(o/r*100),split:1,max:100}),n+=` RENDER_FREEZE_RATE: ${Math.floor(o/r*100)}%`),r&&(this.core.kvStatManager.addNumber({key:514851,value:Math.floor(s/r*100),split:1,max:100}),n+=` DATA_FREEZE_RATE: ${Math.floor(s/r*100)}%`),t.inputFrameCount&&(this.core.kvStatManager.addNumber({key:514852,value:Math.floor(t.decodedFrameCount/t.inputFrameCount*100),split:1,max:100}),n+=` VIDEO_CONSUME_RENDER_RATE: ${Math.floor(t.decodedFrameCount/t.inputFrameCount*100)}%`),this.core.log.info(n)}addKVReportBeforeExitRoom({room:t}){t===this.core.room&&this.contextMap.forEach((e,r)=>{this.report(e,r)})}update(t){let e=this.contextMap.get(t.track);e&&(t.type!=="mock"?(e.close("update"),this.contextMap.set(t.track,this.core.room.videoManager.createDecodeContext(Ac(Sc({},t),{createDecoder:this.createDecoder})))):e.mock(this.core.enums.DECODE_FAILED_ERROR_CODE.TEST))}getRemoteTrackFreezeDuration(t,e){let r=this.core.room.badCaseDetector.getDataFreezeMap().get(`${t.userId}_${t.streamType}`),o=this.core.room.badCaseDetector.getRenderFreezeDuration(`${t.userId}_${t.streamType}`),s=0;return r&&r.durationItemList.forEach(n=>{n.startTime>e.startPerformanceTime&&(s+=n.getDuration())}),{renderFreezeTotal:o,dataFreezeTotal:s}}destroy(){this.core.innerEmitter.off("51",this.addKVReportBeforeExitRoom)}};tt(z_,"Name","TRTCVideoDecoder");var Zp=z_;var yT=bi(ki());function Kp({timesInSecond:i,maxSizeInSecond:t,getSize:e}){return Pe((r,o)=>{let s=new WeakMap;return U.on(B.ROOM_DESTROY,({room:n})=>s.delete(n)),function(...n){let a=s.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},s.set(this,a)),a.timestamp===0?a.timestamp=Date.now():Date.now()-a.timestamp>1e3&&(a.timestamp=Date.now(),a.callCountInSecond=0,a.totalSizeInSecond=0),e&&(a.totalSizeInSecond+=e(...n)),a.timestamp!==0&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=i||a.totalSizeInSecond>t))throw new se({code:q.INVALID_OPERATION,message:We({key:He.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=i,isSize:a.totalSizeInSecond>t,name:o,timesInSecond:i,maxSizeInSecond:t}})});a.callCountInSecond++,r.call(this,...n)}})}var vR="2025-12-08 15:52:55",X_=!0,Q_=function(){var i;if(X_){X_=!1,F.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${or}/en/index.html`),console.info(`* Changelog: ${or}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),F.info("TRTC Web SDK Version:",pt),jr||F.debug("Build Time:",vR);let t=`UA: ${navigator.userAgent}
93
+ `)},p=JSON.stringify(l),f=h_.enable?RR(l,2002,a):p;yield this.uploadLogWithRetry(f,a,f instanceof Uint8Array,p),d.forEach(g=>g.uploaded=!0)}}catch(o){}let r=e.filter(o=>!o.uploaded);r.length>0&&(this._queue=r.concat(this._queue))})}uploadLogWithRetry(t,e,r,o){return Vb({retryFunction:()=>wb({url:SR(e,fb.LOG),body:t,timeout:5e3,priority:"low"}).then(s=>{r&&s.data!=="ok"&&(h_.handleUploadFailed(),this.uploadLogWithRetry(o,e,!1,o))}),settings:{retries:3,timeout:2e3},onError:({retry:s})=>{s()}})()}getPrefix(t){let e=new Date;return e.setTime(S_()),`[${vb(e)}] <${ks[t]}>`}getLogLevel(){return this._logLevel}setLogLevel(t){q_(ks[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(zp(t))return t;try{return t instanceof Error?t.toString():JSON.stringify(t)}catch(e){return""}}addLogToQueue(t,e,r=!0,o,s){let n={log:e.reduce((a,d)=>`${a} ${this.logChunkToString(d)}`.trim(),""),level:t,userId:o,sdkAppId:s,forAllJoinedClients:r};Lo.emit(ol.LOG,{log:n}),this._isEnableUploadLog&&t>=this._logLevelToUpload&&this._queue.push(n)}log(t,e,r=!0,o,s){var n;if(e.unshift(this.getPrefix(t)),this.addLogToQueue(t,e,r,o,s),t<this._logLevel)return;let a=((n=ks[t])==null?void 0:n.toLowerCase())||"info";j_.PRINT_LOG_TAG?console[a](fR,gR,ER,...e):console[a](...e)}debug(...t){this.log(1,t)}info(...t){this.log(2,t)}warn(...t){this.log(3,t)}error(...t){this.log(4,t)}createLogger(t){if(t.parent instanceof Fp){let e=t,{parent:r}=e,o=Qy(e,["parent"]),s=new Fp(o);return s.bindParent(r),s}return new Fp(t)}checkURLParam(){let t=new URLSearchParams(location.search).get("logLevelToUpload"),e=t?Number(t):-1;ks[e]&&(this._logLevelToUpload=e)}getQueue(){return this._queue}};tt(G_,"PRINT_LOG_TAG",!(Xp||Cc||cR));var _R=G_,TR=new _R,IR=i=>Number(i)<14e8,SR=function(i,t){let e;return e=ub||(IR(i)?pb:hb),`${e}/v5/AVQualityReportSvc/C2S?random=${Math.floor(Math.random()*ri(2,31))}&sdkappid=${i}&cmdtype=${t}`},rV=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},q_=i=>i===void 0,zp=i=>typeof i=="string",AR=i=>typeof i=="number",iV=typeof HTMLMediaElement!="undefined"&&"setSinkId"in HTMLMediaElement.prototype;function yR(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var{toString:oV}=Object.prototype;function bR(i,t,e,r){let o={data:i,random:Math.floor(Math.random()*2147483648),sdkAppId:e};return q_(r)||(o=Ac(Sc({},o),{gzip:+r})),{uint32_sdkappid:0,uint64_from_uin:0,uint32_timestamp:0,uint32_seq:0,msg_common_info:{msg_device_info:{enum_device_type:0,str_device_brand:"",str_device_model:"",str_device_board:"",str_device_cpu_abi:""},msg_system_info:{enum_os_type:0,str_os_version:"",msg_network_info:0},msg_network_info:{enum_network_type:0}},msg_report_content:{uint32_type:t,bytes_report_data:JSON.stringify(o)}}}function RR(i,t,e,r){try{let o=bR(i,t,e,r);return Sb(Gp(o),e)}catch(o){return JSON.stringify(i)}}var z_=class J_{constructor(t){this.core=t,tt(this,"contextMap",new Map),tt(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 J_.Name}getValidateRule(t){return{type:this.core.enums.BASIC_TYPE.Object}}createDecoder(t,e){var r;switch(t){case"wasm":let s=((r=this.core.assetsPath)==null?void 0:r.replace(/\/+$/,""))||".";return new nb(Ac(Sc({},e),{wasmPath:`${s}/videodec.wasm`}));case"webCodecs":return new Wn;case"mse":throw new Error("mse decoder not supported yet");default:throw new Error("Unsupported decoder type")}}start(t){this.decodeProcessorMap.set(t.track,this.decode(t)),this.core.room.videoManager.addDecodeProcessor({processor:({frame:e,track:r})=>{var o;return((o=this.decodeProcessorMap.get(r))==null?void 0:o({frame:e,track:r}))||e},type:3})}decode(t){let{pipe:e,take:r,subscribe:o}=this.core.rx;return({frame:s,track:n})=>{if(n!==t.track||s.type==="empty")return s;if(this.contextMap.has(n))return this.contextMap.get(n).decode(s);let a=this.core.room.videoManager.createDecodeContext(Ac(Sc({},t),{createDecoder:this.createDecoder}));return e(a.trackDoneOB,r(1),o(()=>{this.core.clearStarted(this,this.getGroup(t)),this.stop({track:n})})),this.contextMap.set(n,a),a.decode(s)}}stop(t){if(t!=null&&t.track){let e=this.contextMap.get(t.track);e&&(e.close("stop"),this.report(e,t.track),this.contextMap.delete(t.track))}else this.contextMap.forEach((e,r)=>{e.close("stop"),this.contextMap.delete(r)});this.contextMap.size===0&&this.core.room.videoManager.removeDecodeProcessor({type:3})}report(t,e){if(t.isReported)return;t.isReported=!0;let r=yR()-t.startPerformanceTime,{renderFreezeTotal:o,dataFreezeTotal:s}=this.getRemoteTrackFreezeDuration(e,t),n=`report health data: ${t.track.userId} ${t.track.streamType} ${t.type}+${t.renderer} goodType\uFF1A${t.goodType} ${t.failedReason?`failedReason: ${t.failedReason}`:""}`;r&&(this.core.kvStatManager.addNumber({key:514850,value:Math.floor(o/r*100),split:1,max:100}),n+=` RENDER_FREEZE_RATE: ${Math.floor(o/r*100)}%`),r&&(this.core.kvStatManager.addNumber({key:514851,value:Math.floor(s/r*100),split:1,max:100}),n+=` DATA_FREEZE_RATE: ${Math.floor(s/r*100)}%`),t.inputFrameCount&&(this.core.kvStatManager.addNumber({key:514852,value:Math.floor(t.decodedFrameCount/t.inputFrameCount*100),split:1,max:100}),n+=` VIDEO_CONSUME_RENDER_RATE: ${Math.floor(t.decodedFrameCount/t.inputFrameCount*100)}%`),this.core.log.info(n)}addKVReportBeforeExitRoom({room:t}){t===this.core.room&&this.contextMap.forEach((e,r)=>{this.report(e,r)})}update(t){let e=this.contextMap.get(t.track);e&&(t.type!=="mock"?(e.close("update"),this.contextMap.set(t.track,this.core.room.videoManager.createDecodeContext(Ac(Sc({},t),{createDecoder:this.createDecoder})))):e.mock(this.core.enums.DECODE_FAILED_ERROR_CODE.TEST))}getRemoteTrackFreezeDuration(t,e){let r=this.core.room.badCaseDetector.getDataFreezeMap().get(`${t.userId}_${t.streamType}`),o=this.core.room.badCaseDetector.getRenderFreezeDuration(`${t.userId}_${t.streamType}`),s=0;return r&&r.durationItemList.forEach(n=>{n.startTime>e.startPerformanceTime&&(s+=n.getDuration())}),{renderFreezeTotal:o,dataFreezeTotal:s}}destroy(){this.core.innerEmitter.off("51",this.addKVReportBeforeExitRoom)}};tt(z_,"Name","TRTCVideoDecoder");var Zp=z_;var yT=bi(ki());function Kp({timesInSecond:i,maxSizeInSecond:t,getSize:e}){return Pe((r,o)=>{let s=new WeakMap;return U.on(B.ROOM_DESTROY,({room:n})=>s.delete(n)),function(...n){let a=s.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},s.set(this,a)),a.timestamp===0?a.timestamp=Date.now():Date.now()-a.timestamp>1e3&&(a.timestamp=Date.now(),a.callCountInSecond=0,a.totalSizeInSecond=0),e&&(a.totalSizeInSecond+=e(...n)),a.timestamp!==0&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=i||a.totalSizeInSecond>t))throw new se({code:q.INVALID_OPERATION,message:We({key:He.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=i,isSize:a.totalSizeInSecond>t,name:o,timesInSecond:i,maxSizeInSecond:t}})});a.callCountInSecond++,r.call(this,...n)}})}var vR="2025-12-15 18:25:44",X_=!0,Q_=function(){var i;if(X_){X_=!1,F.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${or}/en/index.html`),console.info(`* Changelog: ${or}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),F.info("TRTC Web SDK Version:",pt),jr||F.debug("Build Time:",vR);let t=`UA: ${navigator.userAgent}
94
94
  CPU core: ${navigator.hardwareConcurrency}, GPU: ${$m()}`,e=navigator.deviceMemory;e&&(t+=`, minRAM: ${e}GB`),F.info(t),F.info(`URL: ${location.href}${((i=self.frameElement)==null?void 0:i.tagName)==="IFRAME"?" in iframe":""}`),hs().then(r=>{r&&F.info(Hr)})}};var Vs={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 ne={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},Tr=(L=>(L[L.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",L[L.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",L[L.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",L[L.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",L[L.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",L[L.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",L[L.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",L[L.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",L[L.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",L[L.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",L[L.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",L[L.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",L[L.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",L[L.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",L[L.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",L[L.INVALID_ROOM_ID_REQUIRED=5015]="INVALID_ROOM_ID_REQUIRED",L[L.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",L[L.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",L[L.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",L[L.INVALID_ROOM_ID_TYPE_MISMATCH=5019]="INVALID_ROOM_ID_TYPE_MISMATCH",L[L.INVALID_ROOM_ID_DUPLICATE=5020]="INVALID_ROOM_ID_DUPLICATE",L[L.INVALID_OPERATION=5100]="INVALID_OPERATION",L[L.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",L[L.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",L[L.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",L[L.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",L[L.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",L[L.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",L[L.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",L[L.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",L[L.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",L[L.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",L[L.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",L[L.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",L[L.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",L[L.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",L[L.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",L[L.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",L[L.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",L[L.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",L[L.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",L[L.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",L[L.DEVICE_ERROR=5300]="DEVICE_ERROR",L[L.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",L[L.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",L[L.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",L[L.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",L[L.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",L[L.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",L[L.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",L[L.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",L[L.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",L[L.NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX=5310]="NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX",L[L.SERVER_ERROR=5400]="SERVER_ERROR",L[L.NEED_TO_BUY=5401]="NEED_TO_BUY",L[L.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",L[L.OPERATION_FAILED=5500]="OPERATION_FAILED",L[L.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",L[L.REJOIN_FAILED=5502]="REJOIN_FAILED",L[L.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",L[L.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",L[L.VIDEO_ENCODE_FAILED=5505]="VIDEO_ENCODE_FAILED",L[L.AUDIO_ENCODE_FAILED=5506]="AUDIO_ENCODE_FAILED",L[L.VIDEO_DECODE_FAILED=5507]="VIDEO_DECODE_FAILED",L[L.AUDIO_DECODE_FAILED=5508]="AUDIO_DECODE_FAILED",L[L.OPERATION_ABORT=5998]="OPERATION_ABORT",L[L.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",L))(Tr||{});function Z_({code:i,params:t,enableDocLink:e=!1}){let r="",o,s=Tr[i];try{o=Y_[s]}catch(n){o=Y_.UNKNOWN_ERROR}return Xe(o)?r=o(t):Oe(o)&&(r=o),t.fnName&&!r.includes(t.fnName)&&(r[r.length-1]!=="."&&(r+="."),r+=` thrown from ${t.fnName}()`),e&&(r+=" doc:"),r}var Y_=_e(Y({},ar),{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: ${ft(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: ${ft(r)}.`},INVALID_PARAMETER_RANGE({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' must be one of ${t.values.join("|")} when calling ${e}(), received: ${r}.`},INVALID_PARAMETER_LESS_THAN_ZERO({key:i,rule:t,fnName:e}){return`'${i||t.name}' cannot be less than 0 when calling ${e}().`},INVALID_PARAMETER_MIN({key:i,rule:t,value:e}){return`the min value of ${i||t.name} is ${t.min}, received: ${e}.`},INVALID_PARAMETER_MAX({key:i,rule:t,value:e}){return`the max value of ${i||t.name} is ${t.max}, received: ${e}.`},INVALID_ELEMENT_ID({key:i,fnName:t}){return`'${i}' is not found in the document object when calling ${t}().`},INVALID_ELEMENT_ID_TYPE({key:i,fnName:t,type:e}){return`the element corresponding to '${i}' must be instanceof HTMLElement when calling ${t}(), received: ${e}.`},INVALID_STREAM_ID({key:i}){return`'${i}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},INVALID_ROOM_ID_STRING({key:i}){return`'${i}' must be a valid string.`},INVALID_ROOM_ID_INTEGER({key:i}){return`'${i}' must be an integer between [1, 4294967294].`},INVALID_ROOM_ID_INTEGER_STRING({key:i}){return`'${i}' must be an integer but go a string, use 'parseInt' to convert it or use 'strRoomId' instead.`},INVALID_ROOM_ID_REQUIRED(){return"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required."},INVALID_ROOM_ID_TYPE_MISMATCH({key:i}){return`The type of target roomId must match the current roomId. Current room is using '${i}', but received '${i==="strRoomId"?"roomId":"strRoomId"}'.`},INVALID_ROOM_ID_DUPLICATE({key:i}){return`the target '${i}' must not be the same as the current '${i}'.`},INVALID_STREAM_TYPE:({fnName:i})=>`'streamType' is required when 'userId' is not '*', calling ${i}()`,INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION({fnName:i}){return`the API '${i}' you called does not meet the requirements, please check the API documentation.`},INVALID_OPERATION_NOT_JOINED({fnName:i}){return`cannot ${i} because you are not enter room yet.`},INVALID_OPERATION_REMOTE_USER_NOT_EXIST({fnName:i,value:t}){return`cannot ${i} because remote user(userId: ${t.userId}) does not publishing stream.`},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST({fnName:i,value:t}){return`cannot ${i} because remote user(userId: ${t.userId}) does not publishing ${t.streamType} video.`},INVALID_OPERATION_REPEAT_CALL({fnName:i}){return`you are already ${i}(), cannot repeated call '${i}'.`},INVALID_OPERATION_NEED_VIDEO({fnName:i}){return`cannot call '${i}' because the camera is not turned on.`},INVALID_OPERATION_NEED_AUDIO({fnName:i}){return`cannot call '${i}' because the microphone or screen share is not turned on.`},INVALID_BUFFER_EMPTY:({key:i})=>`the buffer size of paramerter '${i}' cannot be empty`,INVALID_BUFFER_OVERSIZE:()=>"buffer size is over 1000 Bytes",INVALID_ROLE_AUDIENCE:()=>"role: 'audience' cannot call this api.",INVALID_NOT_ENABLE_SEI:()=>"you need to enable SEI in TRTC.create({ enableSEI: true })",INVALID_NEED_CALL_PUBLISHED:({fnName:i})=>`you need to call ${i}() after publish stream.`,ENV_NOT_SUPPORTED({fnName:i}){return`the current browser does not support the capability of the function '${i}' you are calling, please check the API documentation.`},NOT_SUPPORTED_WEBRTC:"the current browser does not support WebRTC capability, please check the SDK documentation.",NOT_SUPPORTED_H264_ENCODE:"this browser does not support H264 encode.",NOT_SUPPORTED_H264_DECODE:"this browser does not support H264 decode.",NOT_SUPPORTED_SCREEN_SHARE:"this browser does not support screen share, please check the browser version.",NOT_SUPPORTED_SMALL_VIDEO:"this browser does not support small video, please check the browser version.",NOT_SUPPORTED_SEI:"this browser does not support SEI, please check the browser version.",NOT_SUPPORTED_WEBGL:"this browser does not support WebGL, please check the browser version.",NOT_SUPPORTED_CHROME_VERSION({fnName:i}){return`cannot call ${i} because the browser version is too low, please upgrade to the latest version`},DEVICE_ERROR({fnName:i,error:t}){return`'${i}' got device exception${t?`, error: ${t.toString()}.`:"."}`},DEVICE_NOT_FOUND_ERROR({fnName:i,deviceType:t=Fs(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=Fs(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=Fs(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=Fs(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=Fs(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=Fs(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=Fs(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 Fs(i){if(!i)return"camera";let t=i.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var ef=class i extends Error{constructor({code:e,extraCode:r,message:o="",messageParams:s,fnName:n="",originError:a,data:d}){var p;let l;o?l=o:l=Z_({code:e===ne.SERVER_ERROR?e:r||e,params:Y({fnName:n,error:a},s)});super(l);m(this,"name","RtcError");m(this,"code");m(this,"extraCode");m(this,"functionName");m(this,"message");m(this,"data");m(this,"handler");m(this,"originError");this.name=Tr[e],this.code=e,this.extraCode=r,this.functionName=n,this.originError=a,this.message=l,this.data=d,this.extraCode===5302&&((p=this.originError)!=null&&p.message.includes("system"))&&(this.handler=()=>{let f={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},g={startLocalVideo:"webcam",startLocalAudio:"microphone"},A=document.createElement("a");ms?A.href=`ms-settings:privacy-${g[this.functionName]}`:Gr&&(A.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${f[this.functionName]}`),A.href.length>0&&A.click()})}static convertFrom(e,r,o){let s=e;if(e instanceof se){let{stack:n}=e,a={code:ne.UNKNOWN_ERROR,fnName:r,originError:e};switch(e.getCode()){case q.INVALID_PARAMETER:a.code=ne.INVALID_PARAMETER,a.message=e.message;break;case q.INVALID_OPERATION:a.code=ne.INVALID_OPERATION;break;case q.NOT_SUPPORTED:case q.NOT_SUPPORTED_H264:a.code=ne.ENV_NOT_SUPPORTED,e.getCode()===q.NOT_SUPPORTED_H264&&(a.extraCode=e.message.includes(ar.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case q.JOIN_ROOM_FAILED:a.messageParams={fnParams:o};case q.SERVER_TIMEOUT:case q.SWITCH_ROLE_FAILED:case q.SWITCH_ROOM_FAILED:a.code=ne.SERVER_ERROR,a.extraCode=e.getExtraCode();break;case q.API_CALL_ABORTED:a.code=ne.OPERATION_ABORT;break;case q.DEVICE_NOT_FOUND:case q.DEVICE_AUTO_RECOVER_FAILED:case q.INITIALIZE_FAILED:a.code=5300,e.name&&(a.extraCode=CR(e.name));break;case q.VIDEO_ENCODE_FAILED:a.extraCode=5505;case q.AUDIO_ENCODE_FAILED:a.extraCode=5506,a.code=ne.OPERATION_FAILED;break;case q.UNKNOWN:break;default:a.code=ne.OPERATION_FAILED}s=new i(a),n&&(s.stack+=n.substr(n.indexOf(`
95
95
  `)))}else{if(e instanceof i)return e;s=new i({code:ne.UNKNOWN_ERROR,fnName:r,originError:e})}return s}};function CR(i){let t;switch(i){case"NotFoundError":t=5301;break;case"NotAllowedError":t=5302;break;case"NotReadableError":t=5303;break;case"OverconstrainedError":t=5304;break;case"InvalidStateError":t=5305;break;case"SecurityError":t=5306;break;case"AbortError":t=5307;break;default:t=5300}return t}var oe=ef;function fi(i){return i==="sub"?"auxiliary":i==="auxiliary"?"sub":"main"}function Nc(i){return i===Vs.QOS_PREFERENCE_CLEAR?"detail":i===Vs.QOS_PREFERENCE_SMOOTH?"motion":""}function jn(i,t){let e=t?cm:pa;return Nm(i)?Y(Y({},e),i):Vr[i]?Vr[i]:e}var K_={type:"object",properties:{cameraId:{type:"string"},useFrontCamera:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:["string","boolean"],values:[!0,!1,"view","publish","both"]},small:{type:["string","object","boolean"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack}}},eT={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}}},qn={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(i,t,e){if(Oe(i)&&!document.getElementById(i))throw new oe({code:ne.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:t}})}},tT={name:"userId",required:!0,type:"string"},rT={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{type:["string","object"],properties:{bitrate:{type:"number"},channelCount:{type:"number"}}},echoCancellation:{values:[!0,!1,"remote-only","all"]},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function zn(i,t){if(!i)throw new oe({code:ne.INVALID_OPERATION,extraCode:5101,fnName:t})}function iT(i,t,e){if(!i)throw new oe({code:ne.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:e}})}function oT(i,t,e){if(!(/^[1-9]\d*$/.test(String(i))&&i<4294967295))throw new oe({code:ne.INVALID_PARAMETER,extraCode:5013,fnName:t,messageParams:{key:e}})}function sT(i,t,e){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(i))throw new oe({code:ne.INVALID_PARAMETER,extraCode:5012,fnName:t,messageParams:{key:e}})}var w2={type:"number",notLessThanZero:!0},NR=(i,t)=>i.width*i.height>=t.width*t.height&&i.frameRate>=t.frameRate&&i.bitrate>=t.bitrate;function nT(i){var r;if(!((r=i==null?void 0:i.option)!=null&&r.small))return;if(!gu()){F.warn("small stream is not supported"),delete i.option.small;return}let t=jn(i.option.profile),e=jn(i.option.small,!0);if(!NR(t,e)){F.warn(`small stream profile must be less than big stream profile. Big: ${JSON.stringify(t)}, Small: ${JSON.stringify(e)}`),delete i.option.small;return}}var DR={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(i,t,e){if(this._room.isJoined)throw new oe({code:ne.INVALID_OPERATION,extraCode:5104,fnName:e});if(i.roomId){if(Oe(i.roomId))throw new oe({code:ne.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:t}});oT(i.roomId,e,t)}else if(i.strRoomId)sT(i.strRoomId,e,t);else throw new oe({code:ne.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:qn,mute:{type:["boolean","string"]},publish:{type:"boolean"},capture:{required:!1,type:"boolean"},option:K_},validate(i){var t,e;if(!((t=i==null?void 0:i.option)!=null&&t.videoTrack)&&Hi())throw new oe({code:ne.ENV_NOT_SUPPORTED,extraCode:5201});(e=i==null?void 0:i.option)!=null&&e.small&&nT(i)}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:_e(Y({},qn),{required:!1}),publish:{type:"boolean"},capture:{required:!1,type:"boolean"},mute:{type:["boolean","string"]},option:K_},validate(i){var t;(t=i==null?void 0:i.option)!=null&&t.small&&nT(i)}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:rT},validate(i){var t;if(!((t=i==null?void 0:i.option)!=null&&t.audioTrack)&&Hi())throw new oe({code:ne.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:rT}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:qn,publish:{type:"boolean"},option:eT},validate(i,t,e,r,o){var s;if(!((s=i==null?void 0:i.option)!=null&&s.videoTrack)){if(Hi())throw new oe({code:ne.ENV_NOT_SUPPORTED,extraCode:5201});if(!qa())throw new oe({code:ne.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:qn,publish:{type:"boolean"},option:eT}},muteRemoteAudio:[tT,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[tT,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:qn,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){zn(this._room.isJoined,e);let r=this._room.remotePublishedUserMap.get(i.userId);if(iT(!!r,e,i),r&&(i.streamType==="main"&&!r.muteState.videoAvailable||i.streamType==="sub"&&!r.muteState.hasAuxiliary))throw new oe({code:ne.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:i}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:_e(Y({},qn),{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){zn(this._room.isJoined,e);let r=this._room.remotePublishedUserMap.get(i.userId);if(iT(!!r,e,i),r&&(i.streamType==="main"&&!r.muteState.videoAvailable||i.streamType==="sub"&&!r.muteState.hasAuxiliary))throw new oe({code:ne.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!=="*"&&O(i.streamType))throw new oe({code:ne.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(i,t,e){zn(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(!Ja)throw new oe({code:ne.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new oe({code:ne.INVALID_OPERATION,fnName:e,extraCode:5108});if(i.byteLength>1e3)throw new oe({code:ne.INVALID_PARAMETER,extraCode:5018,fnName:e});if(i.byteLength===0)throw new oe({code:ne.INVALID_PARAMETER,extraCode:5017,messageParams:{key:t},fnName:e});zn(this._room.isJoined,e)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(i,t,e){if(!i&&!this._room.isMainStreamPublished||i&&!this._room.isAuxStreamPublished)throw new oe({code:ne.INVALID_OPERATION,extraCode:5109,messageParams:{key:t},fnName:e})}}}}],sendCustomMessage:{name:"message",required:!0,type:"object",properties:{cmdId:{type:"number",required:!0,min:1,max:10},data:{instanceOf:ArrayBuffer,required:!0,validate(i,t,e,r){if(i.byteLength>1e3)throw new oe({code:ne.INVALID_PARAMETER,extraCode:5018,fnName:e});if(i.byteLength===0)throw new oe({code:ne.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:t}})}}},validate(i,t,e){if(zn(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new oe({code:ne.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:t}})}},switchRoom:{name:"switchRoomConfig",type:"object",required:!0,validate(i,t,e){if(zn(this._room.isJoined,e),this._room.useStringRoomId&&i.strRoomId===this._room.roomId||!this._room.useStringRoomId&&i.roomId===Number(this._room.roomId))throw new oe({code:ne.INVALID_PARAMETER,extraCode:5020,fnName:e,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(i.roomId&&this._room.useStringRoomId||!i.roomId&&i.strRoomId&&!this._room.useStringRoomId)throw new oe({code:ne.INVALID_PARAMETER,extraCode:5019,fnName:e,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(i.roomId)oT(i.roomId,e,t);else if(i.strRoomId)sT(i.strRoomId,e,t);else throw new oe({code:ne.INVALID_PARAMETER,extraCode:5015,fnName:e})},properties:{roomId:{type:"number"},strRoomId:{type:"string"},privateMapKey:{type:"string"},userSig:{type:"string",required:!0},autoSubscribeCount:{type:"number",min:0,max:50}}}},Ot={TRTC:DR};var Qt=class extends Error{};function wR(i,t){let e=ss(i);for(let r=0;r<t.length;r++)Br(e[r],t[r]);return e}function OR(i){this._resolve=Promise.resolve(i)}function MR(i){this._reject=Promise.reject(i)}var ko=class ko{constructor(t,e){this.instance=t;this.group=e;m(this,"started",!1);m(this,"ops",[]);m(this,"startSame",()=>!0);m(this,"mergeUpdate",wR);let r=ko.instances.get(t);r?r.set(e,this):ko.instances.set(t,new Map([[e,this]]))}static get(t,e){if(!e)return;let r=ko.instances.get(t);return r&&r.get(e)||new ko(t,e)}static gets(t,e){let r=ko.instances.get(t),o=[];return r&&r.forEach((s,n)=>{e.test(n)&&o.push(s)}),o}action(t,e,r){let o=a=>{var d;return t===0?this.started=!0:t===3&&(this.started=!1),this.ops.shift(),(d=this.currentOp)==null||d.action(),a},s=a=>{var d,l;throw this.ops.shift(),t===0&&((d=this.currentOp)==null?void 0:d.type)===2&&this.ops.shift().reject(new Qt("start failed")),(l=this.currentOp)==null||l.action(),a},n={type:t,action:()=>e(...n.args).then(o,s),args:r,resolve:OR,reject:MR};try{switch(this.state){case 1:if(t===0)throw new Qt("already started");break;case 4:if(t===2)throw new Qt("not started");break;default:return this.cacheOp(n)}}catch(a){return Promise.reject(a)}return this.ops.push(n),n.promise=e(...n.args).then(o,s)}cacheOp(t){if(this.ops.length===1)switch(this.state){case 0:case 2:if(t.type===0)throw new Qt("already start");break;case 3:switch(t.type){case 2:throw new Qt("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new Qt("unknown state")}else switch(t.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let r=new Qt("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 Qt("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new Qt("start not allowed after update");case 0:throw new Qt("duplicate start");case 3:if(this.startSame(this.currentOp.args,t.args))throw this.ops.pop().reject(new Qt("keep start")),new Qt("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}};m(ko,"instances",new WeakMap);var Xi=ko;var ll=new WeakMap,ml=(i,t)=>{if(t instanceof Qt){let{stack:e}=t;t=new oe({code:ne.OPERATION_ABORT,message:`${i} abort: ${t.message}`,fnName:i}),e&&(t.stack+=e.substr(e.indexOf(`
96
96
  `)))}throw t};function Uo(i,t){return Pe((e,r)=>function(...o){let s=Xi.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(ml.bind(null,r))):e.apply(this,o)})}function Bs(i,t){let{merge:e,debounce:r}=t||{};return Pe((o,s)=>function(...n){let a=Xi.get(this,typeof i=="string"?i:i.call(this,...n));if(!a)return o.apply(this,n);if(e&&(a.mergeUpdate=e.bind(this)),r&&r.isNeedToDebounce.apply(this,n)){let{delay:d,getKey:l}=r;return new Promise((p,f)=>{var R,N;let g=(R=ll.get(this))==null?void 0:R.get(l(...n));if(g){let{timeoutId:C,resolve:P}=g;clearTimeout(C),P()}let A=setTimeout(()=>{if(a.state===3||a.state===4)return p();a.action(2,o.bind(this),n).catch(ml.bind(null,s)).then(p,f)},d);ll.has(this)?(N=ll.get(this))==null||N.set(l(...n),{timeoutId:A,resolve:p}):ll.set(this,new Map([[l(...n),{timeoutId:A,resolve:p}]]))})}return a.action(2,o.bind(this),n).catch(ml.bind(null,s))})}function Vo(i){return Pe((t,e)=>function(...r){let o=typeof i=="function"?i.call(this,...r):i;if(o instanceof RegExp)return Promise.all(Xi.gets(this,o).map(n=>n.action(3,()=>Promise.resolve(),r))).then(()=>t.call(this,...r));let s=Xi.get(this,o);return s?s.action(3,t.bind(this),r).catch(ml.bind(null,e)):t.apply(this,r)})}function Fo(){return function(i,t,e){return i.prototype[t]=function(){let r=this._log||console,o=`"${t}" is a static method. Use TRTC.${t}() instead. See: ${or}/en/TRTC.html#.${t}`;r.warn(o)},e}}var ie={ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",KICKED_OUT:"kicked-out",REMOTE_USER_ENTER:"remote-user-enter",REMOTE_USER_EXIT:"remote-user-exit",REMOTE_AUDIO_AVAILABLE:"remote-audio-available",REMOTE_AUDIO_UNAVAILABLE:"remote-audio-unavailable",REMOTE_VIDEO_AVAILABLE:"remote-video-available",REMOTE_VIDEO_UNAVAILABLE:"remote-video-unavailable",AUDIO_VOLUME:"audio-volume",AUDIO_FRAME:"audio-frame",NETWORK_QUALITY:"network-quality",CONNECTION_STATE_CHANGED:"connection-state-changed",AUDIO_PLAY_STATE_CHANGED:"audio-play-state-changed",VIDEO_PLAY_STATE_CHANGED:"video-play-state-changed",SCREEN_SHARE_STOPPED:"screen-share-stopped",DEVICE_CHANGED:"device-changed",PUBLISH_STATE_CHANGED:"publish-state-changed",TRACK:"track",STATISTICS:"statistics",SEI_MESSAGE:"sei-message",CUSTOM_MESSAGE:"custom-message",VIDEO_DECODE_DOWNGRADE_STATE_CHANGED:"video-decode-downgrade-state-changed",LAYER_DATA:"layerData",FIRST_VIDEO_FRAME:"first-video-frame",PERMISSION_STATE_CHANGE:"permission-state-change",VIDEO_SIZE_CHANGED:"video-size-changed"},aT=new Set([ie.AUDIO_VOLUME,ie.AUDIO_FRAME,ie.NETWORK_QUALITY,ie.STATISTICS,ie.SEI_MESSAGE,ie.CUSTOM_MESSAGE,ie.LAYER_DATA]);var of={};yi(of,{ScheduleRequestType:()=>uT,getAbilityConfig:()=>LR,getScheduleDomain:()=>fl,isNeedToSchedule:()=>hl,scheduleProxy:()=>gi,sendScheduleRequest:()=>rf,setIsNeedToSchedule:()=>Qi,setScheduleProxy:()=>pl});var tf=null,dT=0,xR=48*3600*1e3,hl=!0;typeof document!="undefined"&&document.head.insertAdjacentHTML("beforeend",Object.values(Ci).map(i=>`<link rel="dns-prefetch" href="https://${i}">`).join(`\r
97
97
  `));function Qi(i){Ye(i)&&i!==hl&&(hl=i,F.info(`setIsNeedToSchedule ${i}`),i||(dT=Date.now()+xR))}U.on("28",()=>Qi(!0));U.on("63",()=>Qi(!0));U.on("84",()=>Qi(!0));U.on("201",i=>{i.state==="RECONNECTING"&&Qi(!0)});U.on("202",i=>{i.state==="RECONNECTING"&&Qi(!0)});function PR(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=Bo(i,"config",M.MAIN),n=Bo(i,"config",M.BACKUP);for(let a of o)if(a.startTime>=e&&(a.name===s||a.name===n)&&a.transferSize>0){let d=a.name===s?M.MAIN:M.BACKUP,l=Math.round(a.duration),p=Math.round(a.domainLookupStart-a.startTime),f=a.redirectStart>0?Math.round(a.redirectEnd-a.redirectStart):0,g=a.fetchStart>0?Math.round(a.domainLookupStart-a.fetchStart):0,A=Math.round(a.domainLookupEnd-a.domainLookupStart),R=Math.round(a.requestStart-a.secureConnectionStart),N=Math.round(a.secureConnectionStart-a.connectStart),C=Math.round(a.responseStart-a.requestStart),P=Math.round(a.responseEnd-a.responseStart),z=[A,R,N,C,P];qe.uploadEvent({log:`stat-schedule-net:${l}(${p}(${f}->${g})->${z.join("->")}) ${d}`,userId:t}),r=_e(Y({},r),{totalCost:l,local:p,dns:A,tcp:N,tls:R,request:C,response:P});break}}catch(o){F.error("getScheduleDetailCost error",o)}return r}function rf(l){return y(this,arguments,function*({userId:i,sdkAppId:t,useStringRoomId:e,roomId:r,userSig:o,version:s,frameWorkType:n,role:a,latencyLevel:d}){var f;if(!hl&&tf&&dT>Date.now())return{isCached:!0,result:tf};let p={delta:0,count:[1,1],msg:[],detail:[]};try{let g=new FormData;g.append("userId",String(i)),g.append("sdkAppId",String(t)),g.append("isStrGroupId",String(e)),g.append("groupId",String(r)),g.append("sdkVersion",s),g.append("userSig",String(o));let A=((f=yield hs())==null?void 0:f.model)||Zd();A&&g.append("model",A);let R=Li();R&&g.append("osString",R),a&&g.append("role",String(a)),d&&g.append("latencyLevel",String(d)),n&&g.append("frameWorkType",String(n));let N=Te(),C=yield UR(g,p,t);C.config&&(C.config.loggerDomain&&ts(C.config.loggerDomain),Ye(C.config.scheduleCache)&&Qi(!C.config.scheduleCache)),p.delta=Te()-N;let P=PR(Number(t),i,N);return tf=C,{isCached:!1,result:C,detailCost:P}}catch(g){let A=mt(g)?g[0]:g,R=Fe(A.code)?A.code:0,N=`schedule failed${A.message?`: ${A.message}`:""}`,C=new se({code:q.SCHEDULE_FAILED,extraCode:R,message:We({key:He.JOIN_ROOM_FAILED,data:{error:N,code:R}})});throw F.error(N,R),C}})}var gi={main:"",backup:""};function pl(i){mt(i)?(gi.main=i[0],gi.backup=i[1]):gi.main=i}var uT=(r=>(r.CONFIG="config",r.TRTC_AUTO_CONF="trtcAutoConf",r.AUDIO_AI_AUTH="audioAiAuth",r))(uT||{});function Bo(i,t,e=M.MAIN,r=!1){return`https://${gi[e]||fl(i,e,r)}/api/v1/${t}`}function LR(i,t,e){let r=Bo(i,t),o=Bo(i,t,M.BACKUP),s=new URLSearchParams(e).toString(),n=fetch(`${r}?${s}`).then(d=>d.json()),a=fetch(`${o}?${s}`).then(d=>d.json());return Ia([n,a])}function fl(i,t=M.MAIN,e=!1){let r;return Rr(i)?e?r=t===M.MAIN?Ci.MAIN_OVERSEA_BACKUP:Ci.BACKUP_OVERSEA:r=t===M.MAIN?Ci.MAIN_OVERSEA:Ci.BACKUP_OVERSEA:r=t===M.MAIN?Ci.MAIN:Ci.BACKUP,r}function kR(i,t,e){return new Promise((r,o)=>{wi({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 cT=(i,t)=>Eo({retryFunction:kR,settings:{retries:3,timeout:0},onError:t,onRetrying:i});function UR(i,t,e){return new Promise((r,o)=>{let s=null;Ia([cT(n=>t.count[0]=n+1,({error:n,retry:a,retriedCount:d,retryFuncArgs:l})=>{t.msg[0]=n.message,s||(d>=1&&(l[0]=Bo(e,"config",M.MAIN,!0)),a())})(Bo(e,"config",M.MAIN),i,{get timeout(){return ns(2+t.count[0])*1e3}}),cT(n=>t.count[1]=n+1,({error:n,retry:a,retriedCount:d,retryFuncArgs:l})=>{t.msg[1]=n.message,s||(d>=2&&(l[0]=Bo(e,"config",M.BACKUP,!0)),a())})(Bo(e,"config",M.BACKUP),i,{get timeout(){return ns(2+t.count[1])*1e3}})]).then(n=>{s=n,r(s)}).catch(o)})}var VR=i=>i.startsWith("data:application/octet-stream;base64,"),FR=i=>i.startsWith("file://"),Dc=class{constructor(){m(this,"_log");this._log=F.createLogger({id:"fd"})}download(t,e){return y(this,null,function*(){let{type:r="blob"}=e||{};t=ds(t);try{let o=Te(),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=Te()-o;return this._log.info(`downloaded: ${t}, return type: ${r}, cost: ${n}ms`),X.addSuccessEvent({key:522700,cost:Te()-o}),s.data}catch(o){throw this._log.error(`failed to download: ${t}, error: ${o}`),X.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){let s=new Error(`network response was not ok: ${r.status}`);throw s.status=r.status,s}let o;return e==="arraybuffer"?o=yield r.arrayBuffer():o=yield r.blob(),{data:o}}catch(r){throw r}})}downloadWithXHR(t,e){return this._log.info(`download with xhr: ${t}, return type: ${e}`),new Promise((r,o)=>{let s=new XMLHttpRequest;s.open("GET",t,!0),s.responseType=e,s.onload=()=>{if(s.status===200||s.status===0&&s.response)r({data:s.response});else{let n=new Error(`XHR failed, status: ${s.status}`);n.status=s.status,o(n)}},s.onerror=o,s.send(null)})}loadWasm(t,e){return y(this,null,function*(){this._log.info(`loadWasm ${t}, importObject: ${JSON.stringify(e)}`);let r=Te(),o=null,s=null;if(Xe(WebAssembly.instantiateStreaming)&&!VR(t)&&!FR(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=Te()-r;return this._log.info(`loadedWasm ${t}, cost: ${n}ms`),X.addSuccessEvent({key:522701,cost:n}),o}throw this._log.error(`failed to loadWasm ${t}, error: ${s}`),X.addFailedEvent({key:522701,error:s}),s})}loadScript(t){this._log.info(`loadScript ${t}`);let e=Te();return new Promise((r,o)=>{let s=document.createElement("script");s.type="text/javascript",s.onload=()=>{this._log.info(`loadedScript ${t}, cost: ${Te()-e}ms`),X.addSuccessEvent({key:522702,cost:Te()-e,split:1e3}),r(s)},s.onerror=n=>{this._log.error(`failed to loadScript ${t}, error: ${(n==null?void 0:n.message)||JSON.stringify(n)}`),X.addFailedEvent({key:522702}),o(n)},s.crossOrigin="anonymous",s.src=t,document.head.append?document.head.append(s):document.getElementsByTagName("head")[0].appendChild(s)})}};Z([As({settings:{timeout:0,retries:3},onError(t,e,r){var o;(t==null?void 0:t.status)===404||(o=t==null?void 0:t.message)!=null&&o.includes("404")?(this._log.warn("download 404, stop retry"),r(t)):e()},onRetrying(t){this._log.warn(`download retrying: ${t}`)}})],Dc.prototype,"download",1),Z([As({settings:{timeout:3e3,retries:3},onRetrying(t){this._log.warn(`loadScript retrying: ${t}`)}})],Dc.prototype,"loadScript",1);var wc=new Dc;function lT({TRTC:i,room:t,errorModule:e,assetsPath:r}){return{TRTC:i,LocalMixVideoTrack:Ps,LocalVideoTrack:_r,LocalScreenTrack:mi,room:t,assetsPath:r,fileDownloader:wc,innerEmitter:U,INNER_EVENT:B,constants:mm,environment:bn,utils:wp,eventLogger:qe,log:this.room.getLogger(),loggerManager:F,errorModule:e,kvStatManager:X,rtcDectection:bo,trtc:this,rx:Cp,enums:ah,schedule:of,getDevices:Mn,initVisionTaskRegistry:(o,s="/mediapipe/vision.js")=>y(this,null,function*(){window.VisionTaskRegistry||(yield wc.loadScript(`${o}/${s}`.replace(/([^:]\/)\/+/g,"$1"))),yield(yield window.VisionTaskRegistry.getInstance(o)).preloadModels([window.VisionTaskType.ImageSegmenter])}),audioContext:ze(),deviceDetector:dt,AudioPlayer:Pn,showAutoPlayDialog:Dn,Timer:gt,clearStarted:(o,s)=>{let n=o.getAlias(),a=Xi.instances.get(this);if(a)if(s){let d=a.get(n+s);if(!d)return;d.started=!1}else a.forEach((d,l)=>{l.startsWith(n)&&(d.started=!1)})},startGetPCM:Ec,createAudioNode:sc,getNetworkTimeOffset:Ff,validateSourceNode:()=>{var o;if(ot&&!((o=this.room.audioManager._localAudioPipline)!=null&&o.source.node))throw new oe({code:ne.DEVICE_ERROR,extraCode:5310,message:"The audio processing plugin cannot be used due to the microphone's sampling rate is not 48KHz in Firefox. Please switch to another browser such as Chrome."})}}}var mT=(i,t)=>{let{emit:e}=i;return i.emit=(...r)=>{try{return e.apply(i,r)}catch(o){let s=We({key:He.CATCH_HANDLER_ERROR,data:{name:t,event:r[0]},addDocLink:!1});return F.warn(`${s}
98
98
 
99
- ${o.stack}`),!1}},i};var Jn=new WeakMap;function hT(i){let t=Jn.get(i);t&&(t.forEach(e=>clearTimeout(e)),Jn.delete(i))}function pT(i,t){return Pe((e,r)=>function(...o){let s=Jn.get(this);s||(s=new Map,Jn.set(this,s));let n=t(...o),a=s.get(n);if(!a||a<=0){e.apply(this,o);let d=setTimeout(()=>{var l;(l=Jn.get(this))==null||l.delete(n)},i);s.set(n,d)}else{clearTimeout(a);let d=window.setTimeout(()=>{var l;e.apply(this,o),(l=Jn.get(this))==null||l.delete(n)},i);s.set(n,d)}})}var gT="trtc-sdk-v5",sf="5.14.2-wasm.3";function $t(...i){return Pe((t,e)=>function(...r){try{El.call(this,i,r,e,this._name)}catch(o){return Promise.reject(o)}return t.apply(this,r)})}function nf(...i){return Pe((t,e)=>function(...r){try{El.call(this,i,r,e,this._name)}catch(o){throw o}return t.apply(this,r)})}function El(i,t,e,r){if(mt(i))for(let o=0;o<i.length;o++)gl.call(this,{rule:i[o],value:t[o],key:i[o].name,fnName:e,className:r});else gl.call(this,{rule:i,value:t[0],key:i.name,fnName:e,className:r})}function gl({rule:i,value:t,key:e,fnName:r,className:o}){function s(d){return{code:ne.INVALID_PARAMETER,extraCode:d,fnName:r,messageParams:{key:e,rule:i,value:t}}}if(O(t)){if(i.required)throw new oe(s(5001));if(O(i.defaultValue)){Xe(i.validate)&&i.validate.call(this,t,e,r,o,this);return}t=i.defaultValue}if(Array.isArray(i.type)){let d=!1;for(let l=0;l<i.type.length;l++)i.type[l]===null&&t===null&&(d=!0),Xe(i.type[l])&&t instanceof i.type[l]&&(d=!0),Oe(i.type[l])&&ft(t)===i.type[l].toLowerCase()&&(d=!0);if(!d)throw new oe({code:ne.INVALID_PARAMETER,extraCode:5002,fnName:r,messageParams:{key:e,rule:{type:i.type.map(l=>as(l)?dn(l):Oe(l)?l:ft(l))},value:t}})}else if(!O(i.type)&&ft(t)!==i.type)throw new oe(s(5002));if(i.allowEmpty===!1){let d=Fe(t)&&(t===0||Number.isNaN(t)),l=Oe(t)&&t.trim()==="";if(d||l)throw new oe(s(5003))}if(i.notLessThanZero&&Fe(t)&&t<0)throw new oe(s(5006));if(!O(i.min)&&Fe(t)&&t<i.min)throw new oe(s(5007));if(!O(i.max)&&Fe(t)&&t>i.max)throw new oe(s(5008));if(Oe(i.instanceOf)){if(!t||t._name!==i.instanceOf)throw new oe(s(5004))}else if(Xe(i.instanceOf)&&!(t instanceof i.instanceOf))throw new oe(s(5004));if(Array.isArray(i.values)&&!i.values.includes(t))throw new oe(s(5005));let{properties:n}=i;Jt(n)&&pr(t)&&Object.keys(n).forEach(d=>{gl.call(this,{rule:n[d],value:t&&t[d],key:`${d}`,fnName:r,className:o})});let{arrayItem:a}=i;Jt(a)&&mt(t)&&t.forEach((d,l)=>{gl.call(this,{rule:a,value:d,key:`${e}[${l}]`,fnName:r,className:o})}),Xe(i.validate)&&i.validate.call(this,t,e,r,o,this)}function nt(i={}){let{getRemoteId:t=()=>"",replaceArg:e,getKVReportKey:r,ignoreLog:o,ignoreErrorLog:s}=i;return Pe((n,a)=>function(...d){var A,R,N;function l(C,P,z){if(z&&z.includes(C))return"hided";if(e){let H=e(...d);if(d[H.argIndex]===P)return H.value}if(P===d||C in d)return P;try{return P instanceof HTMLElement?`id: ${P.id} type:${ft(P)}`:P instanceof MediaStreamTrack?Dd(P):(JSON.stringify(P),P)}catch(H){return`type:${ft(P)}`}}let p=this._log||F;if(o!=null&&o(...d))return n.apply(this,d);d.length>0?p.info(`${a}() ${JSON.stringify(d,(C,P)=>l(C,P,["userSig","privateMapKey"]))}`):p.info(`${a}()`);let f=r?r(...d):uu[a],g=(s==null?void 0:s(...d))||!1;try{let C=n.apply(this,d),P=Te();if(fo(C)){let z=`${a.includes("Plugin")?`${((R=(A=d[0]).getName)==null?void 0:R.call(A))||""} `:" "}`;return C.then(H=>(p.info(`${a}() success ${z}${t.call(this,...d)}`),X.addSuccessEvent({key:f,cost:Te()-P}),H)).catch(H=>{var W;H=oe.convertFrom.call(this,H,a,d.length===1?d[0]:d);let ge=H.extraCode||H.code,Ue=(W=H.message)!=null&&W.includes(ge)?"":` code:${ge}`;throw g||p.error(`${a}() failed ${z}${t.call(this,...d)} ${H}${Ue} params: ${JSON.stringify(d,l)}`),X.addFailedEvent({key:f,error:H}),H})}return X.addSuccessEvent({key:f}),C}catch(C){C=oe.convertFrom.call(this,C,a);let P=C.extraCode||C.code,z=(N=C.message)!=null&&N.includes(P)?"":` code:${P}`;throw g||p.error(`${a}() failed ${C}${z} params: ${JSON.stringify(d,l)}`),X.addFailedEvent({key:f,error:C}),C}})}var _l=i=>Pe((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 oe({code:ne.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 oe({code:ne.ENV_NOT_SUPPORTED,message:`plugin ${String(r)} is not supported`,extraCode:5210,fnName:e});return El.call(this,s.getValidateRule(i),[o],e,"TRTC"),t.call(this,s,o)})});var Tl=0,af,Yi=class Yi{constructor(t){this.core=t;m(this,"log");m(this,"customAudioReferenceMap",new Map);m(this,"audioRefId",0);m(this,"audioContext",ze());m(this,"localAudioWorkletNode");m(this,"screenAudioWorkletNode");m(this,"mixNode");m(this,"silentNode");Tl=Tl+1,this.log=t.log.createChild({id:`${this.getAlias()}${Tl}`}),this.log.info(`created id=${this.getAlias()}${Tl}`),this.installEvent()}static getStartValidateRule(t){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,r,o,s){if(!t.room.audioManager.hasAudioTrack&&!t.room.audioManager.hasScreenAudioTrack)throw new oe({code:ne.INVALID_OPERATION,extraCode:5106,fnName:o})}}}preload(t){return af||(af=this.doPreload(t)),af}doPreload(t){return y(this,null,function*(){let e=yield this.core.fileDownloader.download(t,{type:"blob"}),r=URL.createObjectURL(e);try{yield Gi(this.audioContext,r)}catch(o){this.log.error(`preload audioProcessor failed. ${o}`)}finally{URL.revokeObjectURL(r)}})}getName(){return Yi.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(t){switch(t){case"start":return Yi.getStartValidateRule(this.core);case"update":return Yi.updateValidateRule;case"stop":return Yi.stopValidateRule}}start(t){return y(this,null,function*(){var g,A,R,N;let{room:e}=this.core,{sdkAppId:r,userId:o,userSig:s,assetsPath:n=this.core.assetsPath,audioReference:a,processLevel:d,enableDump:l,isLocalAudioNeedAudioProcess:p=!0,isScreenAudioNeedAudioProcess:f=!1}=t;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=p,this.core.room.audioManager.isScreenAudioNeedAudioProcess=f,!n)throw new oe({code:ne.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload(`${n}/audioProcessor-wasm.js`),p&&!this.localAudioWorkletNode){let{sign:C,status:P,timestamp:z}=yield this.getAuthData(r,o,s);this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",r,o,z,C,P,e)}if(f&&!this.screenAudioWorkletNode){let{sign:C,status:P,timestamp:z}=yield this.getAuthData(r,o,s);this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",r,o,z,C,P,e)}this.mixNode||(this.mixNode=this.audioContext.createGain(),this.mixNode.gain.value=1),this.silentNode||(this.silentNode=this.audioContext.createConstantSource(),this.silentNode.offset.setValueAtTime(0,this.audioContext.currentTime),this.silentNode.start()),(g=this.localAudioWorkletNode)==null||g.port.postMessage({type:"enable"}),(A=this.screenAudioWorkletNode)==null||A.port.postMessage({type:"enable"}),e.audioManager.addAudioProcessor(this.mixNode,this.silentNode,this.localAudioWorkletNode,this.screenAudioWorkletNode),O(a)||a.forEach(C=>{this.customAudioReferenceMap.set(C,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:C,refId:`o-${this.audioRefId++}`})}),O(d)||(R=this.localAudioWorkletNode)==null||R.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:d}}),O(l)||(N=this.localAudioWorkletNode)==null||N.port.postMessage({type:"dump",data:{enable:l}})})}update(t){return y(this,null,function*(){var s,n,a;let{audioReference:e,enableDump:r,processLevel:o}=t;O(e)||(this.customAudioReferenceMap.forEach((d,l)=>{this.customAudioReferenceMap.delete(l),this.core.room.audioManager.updateAudioReference({type:"remove",refId:d})}),e.forEach(d=>{this.customAudioReferenceMap.set(d,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:d,refId:`o-${this.audioRefId++}`})})),O(o)||(s=this.localAudioWorkletNode)==null||s.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:o}}),O(r)||((n=this.localAudioWorkletNode)==null||n.port.postMessage({type:"dump",data:{enable:r}}),(a=this.screenAudioWorkletNode)==null||a.port.postMessage({type:"dump",data:{enable:r}}))})}stop(){return y(this,null,function*(){var e,r;let{room:t}=this.core;(e=this.localAudioWorkletNode)==null||e.port.postMessage({type:"disable"}),(r=this.screenAudioWorkletNode)==null||r.port.postMessage({type:"disable"}),yield t.audioManager.removeAudioProcessor(this.localAudioWorkletNode,this.screenAudioWorkletNode)})}destroy(){this.localAudioWorkletNode&&(this.localAudioWorkletNode.port.onmessage=null),this.screenAudioWorkletNode&&(this.screenAudioWorkletNode.port.onmessage=null),this.uninstallEvent()}getAuthData(t,e,r){return y(this,null,function*(){let o=String(Date.now()).slice(0,-3),{auth:s,sign:n,status:a,message:d}=yield $R({sdkAppId:t,userSig:r,userId:e,timestamp:o});if(!s)throw this.log.info(`audioProcessor: ${e} auth result: ${s}. Message: ${d}`),new oe({code:ne.INVALID_PARAMETER,message:d});return{sign:n,status:a,timestamp:o}})}initWorkletNode(t,e,r,o,s,n,a,d){t.port.postMessage({type:"init",data:{sdkAppId:String(r),userId:o,timestamp:s,sign:n,status:a}}),t.port.onmessage=l=>{var f;let{data:p}=l;switch(p.type){case"cost":let g=(p==null?void 0:p.value)>10?"info":"debug";this.log[g](`${e==="localAudio"?"":`[${e}] `}avg cost: ${p.value} max: ${p==null?void 0:p.max}(${Ks(new Date(p==null?void 0:p.maxCostTimestamp))}) hist: ${(f=p==null?void 0:p.hist)==null?void 0:f.join(" ")}`);return;case"log":this.log[p.logLevel](`${e==="localAudio"?"":`[${e}] `}${p.value}`);return;case"dump":U.emit("265",{room:d,data:p.value,type:e==="localAudio"?"dump":"dump-screen-audio"});return}}}handleLocalAudioStarted(t){return y(this,null,function*(){var e;if(!(!this.hitTest(t.room)||((e=this.core.room.scheduleResult.config)==null?void 0:e.audioProcessor)!==!0))try{yield this.core.trtc.startPlugin("AudioProcessor",{sdkAppId:this.core.room.sdkAppId,userId:this.core.room.userId,userSig:this.core.room.userSig}),this.log.warn("audio processor auto start success")}catch(r){this.log.warn(`audio processor auto start failed, error: ${r}`)}})}handleLocalAudioStopped(t){return y(this,null,function*(){var e;!this.hitTest(t.room)||((e=this.core.room.scheduleResult.config)==null?void 0:e.audioProcessor)!==!0||(yield this.core.trtc.stopPlugin("AudioProcessor"))})}installEvent(){this.core.innerEmitter.on("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.on("114",this.handleLocalAudioStopped,this)}uninstallEvent(){this.core.innerEmitter.off("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.off("114",this.handleLocalAudioStopped,this)}hitTest(t){return t===this.core.room}};m(Yi,"updateValidateRule",{type:"object"}),m(Yi,"stopValidateRule",{type:"object"}),m(Yi,"Name","AudioProcessor");var Il=Yi;function BR(i,t=M.MAIN){return`https://${gi[t]||fl(i,t)}/api/v1/audioAiAuth`}function $R(o){return y(this,arguments,function*({sdkAppId:i,userId:t,userSig:e,timestamp:r}){let n=`${BR(i)}?sdkAppId=${i}&userId=${t}&userSig=${e}&timestamp=${r}`,a=yield fetch(n),{data:{errCode:d,errMsg:l,sign:p,status:f}}=yield a.json();if(f==="1")return{auth:!0,sign:p,status:f,message:l};let g=Rr(i)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",A="Init RTCAudioProcessor failed.",R="";switch(d){case 1:R="Please check your params.";break;case 2:R=`You need to buy packages. Refer to: ${g}`;break;case 3:R="Server is invalid. Please contact our engineer. ";break;case 4:R=`Your packages is not active. Refer to: ${g}`;break;case 5:R=`Your packages is expired. Refer to: ${g}`;break;case 6:R="Your version is not supported.";break}return{auth:!1,status:f,message:l?`${A} Reason: ${l}. ${R}`:`${A}, ${R}`}})}var Sl=0,cf=class{constructor(t,e){m(this,"audioObjectURL");m(this,"player");m(this,"publisher");m(this,"mixInput");this.mixInput=new On(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&&(O(t.volume)||(this.volume=t.volume),O(t.loop)||(this.loop=t.loop),O(t.playbackRate)||(this.playbackRate=t.playbackRate))}updateListener(t){if(this.player){if(t.onDurationChange){let{onDurationChange:e}=t;this.player.ondurationchange=r=>{e(r.target.duration)}}if(t.onTimeUpdate){let e=t.onTimeUpdate,{player:r}=this;r.ontimeupdate=()=>{e(r.currentTime,r.duration)}}t.onEnded&&(this.player.onended=t.onEnded)}}reload(t){return y(this,null,function*(){if(t.url){let e=yield wc.download(t.url,{retries:3,type:"blob"});this.audioObjectURL&&URL.revokeObjectURL(this.audioObjectURL),this.audioObjectURL=URL.createObjectURL(e),this.player&&this.publisher?(this.player.src=this.audioObjectURL,this.publisher.src=this.audioObjectURL):(this.player=new Audio(this.audioObjectURL),this.player.crossOrigin="anonymous",this.publisher=new Audio(this.audioObjectURL),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher),this.updateListener(t),this.updateSettings(t))}else this.mixInput.replaceSource(t.track)})}reset(){this.seek(0),this.mixInput.connect()}seek(t){this.player&&(t<0&&t>this.player.duration||(this.player.currentTime=t,this.publisher.currentTime=t))}play(){var t,e;return Promise.all([(t=this.player)==null?void 0:t.play(),(e=this.publisher)==null?void 0:e.play()])}pause(){var t,e;(t=this.player)==null||t.pause(),(e=this.publisher)==null||e.pause()}stop(){var t;(t=this.player)==null||t.pause(),this.mixInput.disconnect()}setOperation(t){t==="pause"&&this.pause(),t==="resume"&&(this.pause(),this.play()),t==="stop"&&(this.pause(),this.seek(0))}set volume(t){!this.player||!this.publisher||(this.player.volume=t,this.publisher.volume=t)}set loop(t){!this.player||!this.publisher||(this.player.loop=t,this.publisher.loop=t)}set playbackRate(t){!this.player||!this.publisher||(this.player.playbackRate=t,this.publisher.playbackRate=t)}};function Xn(i,t){if(t&&typeof t!="function")throw new oe({code:ne.INVALID_PARAMETER,message:`start audioMixer plugin: param ${i} should be a function.`})}var Ei=class Ei{constructor(t){this.core=t;m(this,"log");m(this,"mixedMusicMap",new Map);m(this,"cacheMusicMap",new Map);Sl=Sl+1,this.log=t.log.createChild({id:`${this.getAlias()}${Sl}`}),this.log.info(`created id=${this.getAlias()}${Sl}`)}getName(){return Ei.Name}getAlias(){return"ax"}getGroup(t){return t==null?void 0:t.id}getValidateRule(t){switch(t){case"start":return Ei.startValidateRule;case"update":return Ei.updateValidateRule;case"stop":return Ei.stopValidateRule}}start(t){return y(this,null,function*(){let{room:e}=this.core;this.core.validateSourceNode(),this.log.info(`add music source, id: ${t.id} url: ${t.url}, track: ${t.track}`);let{id:r,url:o}=t;if(this.mixedMusicMap.has(r))return;let s=this.cacheMusicMap.get(r);s?t.url?s.reset():(s.mixInput.replaceSource(t.track),s.mixInput.connect()):(s=new cf(t,e.audioManager),this.cacheMusicMap.set(r,s)),s.updateListener(t),s.updateSettings(t);try{yield s.play()}catch(n){yield this.handleAutoPlayFailed(s,t,n)}this.mixedMusicMap.set(r,s),s.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"add",audioReference:s.mixInput.source.node,refId:`ax-${r}`}),this.log.info(`start mix audio track ${r} success.`),X.addEnum({key:502700,value:3}),this.kvUpload(t)})}handleAutoPlayFailed(t,e,r){return y(this,null,function*(){if(r.name==="NotSupportedError")this.log.error(`play failed, try to reload source. error: ${r}`),yield t.reload(e),yield t.play();else if(r.name==="NotAllowedError")if(this.core.room.enableAutoPlayDialog){let o=()=>{var s;(s=t.play())==null||s.finally(()=>{U.off("154",o,this)})};U.on("154",o,this),Dn()}else this.core.trtc.emit(ie.AUTOPLAY_FAILED,{userId:"",mediaType:"audio",resume:()=>y(this,null,function*(){return t.play()})});else throw r})}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),O(r)||n.setOperation(r),O(o)||n.seek(o),this.kvUpload(t)})}stop(e){return y(this,arguments,function*({id:t}){if(this.mixedMusicMap.has(t)){this.log.info(`remove music source, music id: ${t}`);let r=this.mixedMusicMap.get(t);r!=null&&r.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:r.mixInput.source.node,refId:`ax-${t}`}),r==null||r.stop(),this.mixedMusicMap.delete(t)}t==="*"&&this.destroyAllMusic()})}kvUpload(t){let{track:e,loop:r,volume:o,playbackRate:s,operation:n,seekFrom:a,onTimeUpdate:d,onDurationChange:l,onEnded:p}=t;e&&X.addCount({key:502009}),r&&X.addCount({key:502001}),o&&X.addCount({key:502002}),s&&X.addCount({key:502003}),n&&X.addCount({key:502004}),a&&X.addCount({key:502005}),typeof d!="function"&&X.addCount({key:502007}),typeof p!="function"&&X.addCount({key:502008}),typeof l!="function"&&X.addCount({key:502006})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((t,e)=>{t!=null&&t.mixInput.track&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:t.mixInput.track,refId:e}),this.stop({id:e})})}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}};m(Ei,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(t,e,r){if(t.url&&t.url!=="*"){let o=t.url.split("?")[0],s=["mp3","ogg","wav","flac"],n=o.split(".").pop(),a=s.indexOf(n)>=0,d=o.startsWith("blob"),l=o.startsWith("data");if(!(a||d||l))throw new oe({code:ne.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:r})}if(!t.url&&!t.track)throw new oe({code:ne.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:r});Xn("onTimeUpdate",t.onTimeUpdate),Xn("onEnded",t.onEnded),Xn("onDurationChange",t.onDurationChange)}}),m(Ei,"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){Xn("onTimeUpdate",t.onTimeUpdate),Xn("onEnded",t.onEnded),Xn("onDurationChange",t.onDurationChange)}}),m(Ei,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),m(Ei,"Name","AudioMixer");var Al=Ei;var yl=0,df,Zi=class Zi{constructor(t){this.core=t;m(this,"log");m(this,"audioContext",ze("denoiser"));m(this,"workletNode");m(this,"config",{enableFarFieldReduce:!1,farFieldReduceThreshold:.5});yl=yl+1,this.log=t.log.createChild({id:`${this.getAlias()}${yl}`}),this.log.info(`created id=${this.getAlias()}${yl}`)}static startValidateRule(t){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0},mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}},validate(e,r,o,s){if(!t.room.audioManager.hasAudioTrack)throw new oe({code:ne.INVALID_OPERATION,extraCode:5106,fnName:o})}}}preload(t){return df||(df=this.doPreload(t)),df}doPreload(t){return y(this,null,function*(){let e=yield this.core.fileDownloader.download(t,{type:"blob"}),r=URL.createObjectURL(e);try{yield Gi(this.audioContext,r)}catch(o){throw this.log.error("load worklet failed",o),o}finally{URL.revokeObjectURL(r)}})}getName(){return Zi.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser"}getValidateRule(t){switch(t){case"start":return Zi.startValidateRule(this.core);case"update":return Zi.updateValidateRule;case"stop":return Zi.stopValidateRule}}start(t){return y(this,null,function*(){let{room:e,schedule:r}=this.core,{assetsPath:o=this.core.assetsPath}=t;if(!o)throw new oe({code:ne.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload(`${o}/denoiser-wasm${Ih()?"":"-nosimd"}.js`),!this.workletNode){let s=String(Date.now()).slice(0,-3),{auth:n,sign:a,status:d,message:l}=yield WR(r,_e(Y({},t),{timestamp:s}));if(!n)throw this.log.info(`RTCAIDenoiser: ${t.userId} auth result: ${n}. Message: ${l}`),new oe({code:ne.INVALID_PARAMETER,message:l});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(t.sdkAppId),userId:t.userId,timestamp:s,sign:a,status:d}}),this.workletNode.port.onmessage=p=>{var g;let{data:f}=p;if(f.type==="cost"){let A=(f==null?void 0:f.max)>20?"warn":(f==null?void 0:f.max)>10?"info":"debug";this.log[A](`avg cost: ${f.value} max: ${f==null?void 0:f.max}(${Ks(new Date(f==null?void 0:f.maxCostTimestamp))}) hist: ${(g=f==null?void 0:f.hist)==null?void 0:g.join(" ")}`)}else f.type==="log"&&this.log[f.logLevel](`${f.value}`)}}this.updateConfig(t),this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(t){return y(this,null,function*(){this.updateConfig(t)})}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)})}updateConfig(t){if(!this.workletNode)return;let e=!1;O(t.mode)||(t.mode===0?this.config.enableFarFieldReduce=!1:t.mode===1&&(this.config.enableFarFieldReduce=!0),e=!0),O(t.farFieldReduceThreshold)||(this.config.farFieldReduceThreshold=t.farFieldReduceThreshold,e=!0),e&&this.workletNode.port.postMessage({type:"setConfig",data:this.config})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};m(Zi,"updateValidateRule",{type:"object",properties:{mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}}}),m(Zi,"stopValidateRule",{type:"object"}),m(Zi,"Name","AIDenoiser");var bl=Zi;function WR(s,n){return y(this,arguments,function*(i,{sdkAppId:t,userId:e,userSig:r,timestamp:o}){try{let{data:{errCode:a,errMsg:d,sign:l,status:p}}=yield i.getAbilityConfig(t,i.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:t,userId:e,userSig:r,timestamp:o});if(p==="1")return{auth:!0,sign:l,status:p,message:d};let f=Rr(t)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",g="Init RTCAIDenoiser failed.",A="";switch(a){case 1:A="Please check your params.";break;case 2:A=`You need to buy packages. Refer to: ${f}`;break;case 3:A="Server is invalid. Please contact our engineer. ";break;case 4:A=`Your packages is not active. Refer to: ${f}`;break;case 5:A=`Your packages is expired. Refer to: ${f}`;break;case 6:A="Your version is not supported.";break}return{auth:!1,status:p,message:d?`${g} Reason: ${d}. ${A}`:`${g}, ${A}`}}catch(a){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${a}`}}})}var _T=bi(ki(),1);var uf=class extends _T.EventEmitter{constructor(){super();m(this,"observer");m(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){qe.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)&&F.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){qe.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:r})}}},GR=new uf,lf=GR;function jR([i,t]){let e=t.byteLength,r=parseInt(String(e/255),10),o=e%255,s=[];s.push(0,0,0,1,6,i);for(let a=0;a<r;a++)s.push(255);s.push(o);let n=new DataView(t);return s.push(...new Uint8Array(n.buffer)),s.push(128),new Os(new DataView(new Uint8Array(s).buffer),!0)}function qR(i){return i.type==="empty"||i.data.byteLength===0}function zR(i){return i.getInt32(0)===1&&i.getInt8(4)===6}function JR(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 mf({frame:i,seiMessageList:t}){if(!t||t.length===0||i.data.byteLength===0)return i;let r=9-JR(i.data);if(r<=0)return i;let o=t.splice(0,r).reverse().map(jR),s=o.reduce((p,f)=>p+f.dataView.byteLength,0),n=new ArrayBuffer(s+i.data.byteLength),a=new DataView(n),d=new DataView(i.data),l=0;for(let p=0;p<o.length;p++)for(let f=0;f<o[p].dataView.byteLength;f++)a.setInt8(l++,o[p].dataView.getInt8(f));for(let p=0;p<i.data.byteLength;p++)a.setInt8(l++,d.getInt8(p));return i.data=n,i}function hf({frame:i,onSEI:t}){try{let e=new DataView(i.data);if(qR(i)||!zR(e))return i;let r=[],o=0,s=-1,n=-1;for(let a=0;a<i.data.byteLength;a++){let d=e.getUint8(a);if(d===0)o++;else if(d===1){if(o===2||o===3){let l=a-o;if(s===-1?s=l:n===-1&&(n=l,r.push(new Os(new DataView(e.buffer.slice(s,n)))),s=l,n=-1),!(e.getUint8(a+1)===6)){i.data=e.buffer.slice(l);break}}o=0}else o=0}t==null||t(r.reverse())}catch(e){}return i}var pf=0,Oc=class Oc{constructor(t){this.core=t;m(this,"log");m(this,"_seiMessageList",[]);m(this,"_smallSeiMessageList",[]);m(this,"_subStreamSeiMessageList",[]);pf++,this.log=t.log.createChild({id:`${this.getAlias()}${pf}`}),this.log.info(`[sei] created id=${this.getAlias()}${pf}`),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 mf({frame:t,seiMessageList:r})}catch(r){this.log.warn(r)}return t}decode({frame:t,track:e}){return hf({frame:t,onSEI:r=>{r.forEach(o=>{this.core.trtc.emit(ie.SEI_MESSAGE,{seiPayloadType:o.seiPayloadType,data:o.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"})})}})}destroy(){this.log.debug("destroy"),this.stop(),delete this.core}getValidateRule(t){switch(t){case"start":return{type:"object"};case"update":return{type:"object"};case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:Is?this.encode:mf,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:Is?this.decode:hf,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 Oc.Name}getAlias(){return"sei"}getGroup(){return"sei"}};m(Oc,"autoStart",!0),m(Oc,"Name","SEI");var Rl=Oc;var XR=0,vl,Mc=class Mc{constructor(t){this.core=t;m(this,"_core");m(this,"log");m(this,"dialog");this._core=t,this.log=t.log.createChild({id:`${this.getAlias()}${++XR}`}),this.log.info("created")}getName(){return Mc.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())})}update(e){return y(this,arguments,function*({visible:t}){t?yield this.openDebugDiaLog():this.closeDebugDiaLog()})}stop(){this.closeDebugDiaLog()}destroy(){this.stop()}openDebugDiaLog(){return y(this,null,function*(){var t;if(!this.dialog)try{if(vl)yield vl;else{let e=new URLSearchParams(location.search).get("trtcDebugDialogPath")||((t=window.sessionStorage)==null?void 0:t.getItem("TRTC_DEBUG_DIALOG_PATH"))||`https://unpkg.com/${gT}@${pt}/assets/debug-dialog.js`;vl=this._core.fileDownloader.loadScript(e),yield vl}this.dialog=new TRTCDebugDialog(this._core,this.log),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(e){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(e))}})}closeDebugDiaLog(){this.dialog&&(this.dialog.closeDialog(),this.dialog=null)}};m(Mc,"Name","Debug"),m(Mc,"autoStart",!0);var Cl=Mc;var TT=i=>{switch(i){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},Nl=class{constructor(t,e,r){m(this,"trackDoneOB");m(this,"startOB");m(this,"stopOB");m(this,"inputFrameCount",0);m(this,"decodedFrameCount",0);m(this,"type","auto");m(this,"config");m(this,"decoder");m(this,"_decodeSink");let{kvStatManager:o,trtc:s}=t;this.config=r.config,this.trackDoneOB=Ae(e,ue.INIT),this.stopOB=bt(),this.startOB=bt(),r.type==="auto"?this.type="webCodecs":this.type=r.type;let n=bt(),a=d=>{let l=this.pipe(e);return n.next("STARTING"),e.log.info(`decoder type: ${this.type}`),ye(l,Je(this.stopOB),Le(()=>{},p=>{e.log.error(p),o.addFailedEvent({key:TT(this.type),error:p}),d>4?this.startOB.error(p):this.startOB.next(d+1)})),ye(l,Qr(1),yp(hc))};ye(this.startOB,lc(0),ui(a),Je(this.stopOB),Le(()=>{e.player.setOutput(),n.next("STARTED")},d=>{n.next("FAILED")},()=>{o.addSuccessEvent({key:TT(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 ji()(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"}))}},QR={type:"object"},xc=class xc{constructor(t){this.core=t;m(this,"log");m(this,"contextMap",new Map);m(this,"decodeProcessorMap",new WeakMap);this.log=t.log.createChild({id:`${this.getAlias()}`})}getAlias(){return xc.Name}getGroup(t){return t.track.userId+t.track.streamType}getName(){return xc.Name}getValidateRule(t){return QR}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 Nl(this.core,r,t);return ye(o.trackDoneOB,Qr(1),Le(()=>{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 Nl(this.core,t.track,t))}}};m(xc,"Name","TRTCAudioDecoder");var Pc=xc;var Dl=class{constructor(){m(this,"log");this.log=F.createLogger({id:"exp"})}call(t,e){return y(this,null,function*(){return Xe(this[t])?this[t](e):Promise.reject(new se({code:q.INVALID_PARAMETER,message:We({key:He.API_NOT_EXIST,data:{name:t}})}))})}enableAudioFrameEvent(t){return y(this,null,function*(){let{trtcInstance:e,enable:r,userId:o,sampleRate:s=48e3,channelCount:n=1,port:a}=t,{audioManager:d}=e.room,{getPCMAbortCtrlMap:l,audioFrameEventConfigMap:p}=d;if(p.set(o,{enable:r,sampleRate:s,channelCount:n,port:a}),r)if(o==="*")e.room.remotePublishedUserMap.forEach(f=>{if(f.remoteAudioTrack.isAvailable){if(l.get(f.userId))return;let g=d.getPCM(A=>{e.emit(ie.AUDIO_FRAME,A)},f.userId);l.set(f.userId,g)}});else{if(l.get(o))return;let f=d.getPCM(g=>{e.emit(ie.AUDIO_FRAME,g)},o);l.set(o,f)}else if(o==="*")e.room.remotePublishedUserMap.forEach(f=>{if(f.remoteAudioTrack.isSubscribed){let{userId:g}=f,A=l.get(g);A==null||A.abort("disable"),l.delete(g)}});else{let f=l.get(o);f==null||f.abort("disable"),l.delete(o)}})}resumeRemotePlayer(t){return y(this,null,function*(){if(t.userId==="*"){let r=[];return t.trtcInstance.room.remotePublishedUserMap.forEach(o=>{let{remoteAudioTrack:s,remoteVideoTrack:n,remoteAuxiliaryTrack:a}=o;t.streamType?t.streamType==="main"?(s.isAvailable&&r.push(s.player.resume()),n.isAvailable&&r.push(n.player.resume())):a.isAvailable&&r.push(a.player.resume()):(s.isAvailable&&r.push(s.player.resume()),n.isAvailable&&r.push(n.player.resume()),a.isAvailable&&r.push(a.player.resume()))}),Promise.all(r)}let e=t.trtcInstance.room.remotePublishedUserMap.get(t.userId);if(e)return t.streamType==="main"?Promise.all([e.remoteAudioTrack.player.resume(),e.remoteVideoTrack.player.resume()]):e.remoteAuxiliaryTrack.player.resume()})}pauseRemotePlayer(t){if(t.userId==="*")t.trtcInstance.room.remotePublishedUserMap.forEach(e=>{let{remoteAudioTrack:r,remoteVideoTrack:o,remoteAuxiliaryTrack:s}=e;t.streamType?t.streamType==="main"?(r.isAvailable&&r.player.pause(),o.isAvailable&&o.player.pause()):s.isAvailable&&s.player.pause():(r.isAvailable&&r.player.pause(),o.isAvailable&&o.player.pause(),s.isAvailable&&s.player.pause())});else{let e=t.trtcInstance.room.remotePublishedUserMap.get(t.userId);e&&(t.streamType==="main"?(e.remoteAudioTrack.player.pause(),e.remoteVideoTrack.player.pause()):e.remoteAuxiliaryTrack.player.pause())}}};Z([r_({name:"options",type:"object",required:!0,properties:{enable:{required:!0,type:"boolean"},userId:{required:!0,type:"string"},sampleRate:{type:"number",values:[8e3,16e3,32e3,44100,48e3]},channelCount:{type:"number",values:[1,2]},port:{type:"messageport"}}})],Dl.prototype,"enableAudioFrameEvent",1);var IT=new Dl;var ST=bi(ki(),1);var ff=class extends ST.EventEmitter{constructor(){super();m(this,"states",{});m(this,"permissionChangeHandler");m(this,"log");this.log=F.createLogger({id:"pm"}),this.permissionChangeHandler=()=>{var e,r;this.emit("permission-state-change",{camera:(e=this.states.camera)==null?void 0:e.state,microphone:(r=this.states.microphone)==null?void 0:r.state})}}request(e){return y(this,null,function*(){if(this.log.info(`request ${e.join(", ")}`),e.length===0)return Promise.resolve();(yield navigator.mediaDevices.getUserMedia({video:e.includes("camera"),audio:e.includes("microphone")})).getTracks().forEach(o=>o.stop())})}get(e){return y(this,null,function*(){try{return this.states[e]||(this.states[e]=yield navigator.permissions.query({name:e}),this.states[e].addEventListener("change",this.permissionChangeHandler)),this.log.info(`get ${e} permission state: ${this.states[e].state}`),this.states[e].state}catch(r){return this.log.error(`get ${e} permission failed, error: ${r instanceof Error?r.message:r}`),null}})}destroy(){Object.values(this.states).forEach(e=>{e==null||e.removeEventListener("change",this.permissionChangeHandler)}),this.states={}}},Lc=new ff;var AT=0,kc=new Set,kt=null;om(sf);Rn.checkStorage();var pe=class pe extends yT.EventEmitter{constructor(e,r){super();m(this,"_room");m(this,"_eventListened",new Set);m(this,"_localVideoTrack",null);m(this,"_localAudioTrack",null);m(this,"_localScreenTrack",null);m(this,"_localScreenAudioTrack",null);m(this,"_localVideoConfig",null);m(this,"_localScreenConfig",null);m(this,"_localAudioConfig",null);m(this,"_remoteVideoConfigMap",new Map);m(this,"_remoteAudioConfigMap",new Map);m(this,"_remoteAudioVolumeMap",new Map);m(this,"_remoteAudioMuteMap",new Map);m(this,"_mediaTrackMap",new WeakMap);m(this,"_log",F.createLogger({id:`t${++AT}`}));m(this,"_plugins",new Map);m(this,"_networkQuality",null);m(this,"_speakerId");m(this,"enterRoomParams");m(this,"_enableAutoSwitchWhenRecapturing",!0);this._room=new e(Y({logger:this._log,frameWorkType:pe.frameWorkType},r)),this._room.videoDecodeFallbackType=r.videoDecodeFallback,Ye(r.enableAutoSwitchWhenRecapturing)&&(this._enableAutoSwitchWhenRecapturing=r.enableAutoSwitchWhenRecapturing),this._log.info(`create() ${JSON.stringify(r,(o,s)=>o==="plugins"?s.map(n=>n.Name):s)}`),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(o){return this._room.audioManager.dump(o)}}}),r.plugins&&r.plugins.forEach(o=>{this._use(o,r.assetsPath)}),this._use(Al,r.assetsPath),this._use(Il,r.assetsPath),this._use(bl,r.assetsPath),this._use(Pc,r.assetsPath),this._use(Cl),r.enableSEI&&Ja&&this._use(Rl),this._room.on("audio-volume",o=>{var s,n;!o.find(a=>a.userId==="")&&this._localAudioTrack&&o.push({userId:"",volume:Math.floor(((s=this._localAudioTrack.getInternalAudioLevelAfter3A())!=null?s:this._localAudioTrack.getAudioLevel())*100),floatVolume:(n=this._localAudioTrack.getInternalAudioLevelAfter3A())!=null?n:this._localAudioTrack.getInternalAudioLevel()}),r.volumeType===1&&o.forEach(a=>{var l;let d=a.userId===""?this._localAudioTrack:(l=this.room.remotePublishedUserMap.get(a.userId))==null?void 0:l.remoteAudioTrack;d&&(a.volume=d.dbVolume)}),r.enableDbVolume&&o.forEach(a=>{var l;let d=a.userId===""?this._localAudioTrack:(l=this.room.remotePublishedUserMap.get(a.userId))==null?void 0:l.remoteAudioTrack;d&&(a.volume=d.dbVolume)}),this.emit(ie.AUDIO_VOLUME,{result:o.sort((a,d)=>d.volume-a.volume)})}),this._room.videoManager.on("error",o=>{this._log.error(new oe({code:ne.OPERATION_FAILED,extraCode:5504,message:o.message,originError:o}))}),this._listenEvents(),this._initActiveSpeaker(),mT(this,"trtc")}static create(e){}static _create(e,r){Q_();let o=new pe(e,r||{});return kc.add(o),o.__v_skip=!0,o}get room(){return this._room}_listenEvents(){Ft(this,this._room).add("peer-join",e=>{let{userId:r}=e;this.emit(ie.REMOTE_USER_ENTER,{userId:r})}).add("peer-leave",e=>{this.emit(ie.REMOTE_USER_EXIT,{userId:e})}).add("banned",e=>{Qi(!0),this._exitRoom().finally(()=>{this.emit(ie.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().finally(()=>{this.emit(ie.ERROR,oe.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(ie.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let r=_e(Y({},e),{uplinkRTT:Math.min(e.uplinkRTT,Ea),downlinkRTT:Math.min(e.downlinkRTT,Ea)});this.emit(ie.NETWORK_QUALITY,r)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(o=>{Ft(o,o).add("player-state-changed",s=>{let n=_e(Y({},s),{userId:e.userId});o.kind===M.VIDEO&&(n.streamType=fi(o.streamType)),this.emit(o.kind===M.AUDIO?ie.AUDIO_PLAY_STATE_CHANGED:ie.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",s=>{s.getCode()===q.PLAY_NOT_ALLOWED&&this.emit(ie.AUTOPLAY_FAILED,{userId:o.userId,mediaType:o.strMediaType,resume:()=>o.player.resume()})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(o=>{At(o)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:r})=>{let{userId:o}=r,s=e.audioAvailable,n=e.videoAvailable,{audioAvailable:a,videoAvailable:d}=r;a||this._remoteAudioConfigMap.delete(o),d||this._removeRemoteVideoConfig(o,"main"),r.hasAuxiliary||this._removeRemoteVideoConfig(o,"sub"),n!==d&&(d?this._onVideoAvailable({userId:o,streamType:"main"}):this._onVideoUnavailable({userId:o,streamType:"main"}),this.emit(d?ie.REMOTE_VIDEO_AVAILABLE:ie.REMOTE_VIDEO_UNAVAILABLE,{userId:o,streamType:"main"})),s!==a&&(a?this._onAudioAvailable({userId:o}):this._onAudioUnavailable({userId:o,muteState:r}),this.emit(a?ie.REMOTE_AUDIO_AVAILABLE:ie.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?ie.REMOTE_VIDEO_AVAILABLE:ie.REMOTE_VIDEO_UNAVAILABLE,{userId:o,streamType:"sub"}))}).add("sei-message",e=>{this.emit(ie.SEI_MESSAGE,_e(Y({},e),{streamType:fi(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(ie.ERROR,new oe({code:ne.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var s,n,a,d,l,p,f;let r={2:"big",3:"small",7:"sub"},o={rtt:Math.min(e.msg_up_stream_info.msg_network_status.uint32_rtt||((s=e.msg_down_stream_info[0])==null?void 0:s.msg_network_status.uint32_rtt)||((n=this._networkQuality)==null?void 0:n.uplinkRTT)||((a=this._networkQuality)==null?void 0:a.downlinkRTT)||0,Ea),upLoss:((d=this._networkQuality)==null?void 0:d.uplinkLoss)||0,downLoss:((l=this._networkQuality)==null?void 0:l.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((p=e.msg_up_stream_info.msg_audio_status)==null?void 0:p.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((f=e.msg_up_stream_info.msg_audio_status)==null?void 0:f.uint32_audio_level)||0)/Fi},video:e.msg_up_stream_info.msg_video_status.filter(g=>r[g.uint32_video_stream_type]).map(g=>({bitrate:(g.uint32_video_codec_bitrate||0)/1e3,width:g.uint32_video_width,height:g.uint32_video_height,frameRate:g.uint32_video_enc_fps,videoType:r[g.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(g=>({userId:g.msg_user_info.str_identifier,audio:{bitrate:(g.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(g.msg_audio_status.uint32_audio_level||0)/Fi,point2pointDelay:(g.msg_audio_status.uint32_audio_p2p_delay||0)+(g.msg_audio_status.uint32_audio_cache_ms||0),jitterBufferDelay:g.msg_audio_status.uint32_audio_cache_ms||0},video:g.msg_video_status.map(A=>({bitrate:(A.uint32_video_codec_bitrate||0)/1e3,width:A.uint32_video_width,height:A.uint32_video_height,frameRate:A.uint32_video_dec_fps,videoType:r[A.uint32_video_stream_type],point2pointDelay:(A.uint32_video_p2p_delay||0)+(A.uint32_video_cache_ms||0),jitterBufferDelay:A.uint32_video_cache_ms||0,codec:A.uint32_video_codec}))}))};this.emit(ie.STATISTICS,o)}).add("custom-message",e=>{this.emit(ie.CUSTOM_MESSAGE,e)}).add("layerData",e=>this.emit(ie.LAYER_DATA,e)).add("first-video-frame",e=>{this.emit(ie.FIRST_VIDEO_FRAME,_e(Y({},e),{streamType:fi(e.streamType)}))}).add("audio-frame",e=>{this.emit(ie.AUDIO_FRAME,e)}),Ft(this,dt).add("audioInputAdded",e=>{this.emit(ie.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(ie.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(ie.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(ie.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>y(this,null,function*(){if(this.emit(ie.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),kt&&kt.deviceId===ga){let r=(yield Co()).find(o=>o.deviceId===ga);r&&kt.groupId!==r.groupId&&(kt=r,this.emit(ie.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}))}})).add("audioOutputRemoved",e=>y(this,null,function*(){this.emit(ie.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let r=(yield Co())[0];if(!r||!kt||kt.groupId===r.groupId)return;let o=kt.deviceId===e.deviceId,s=kt.deviceId===ga&&kt.deviceId===r.deviceId;(o||s)&&(kt=r,this.emit(ie.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}))})),Ft(this,Lc).add("permission-state-change",e=>{this.emit(ie.PERMISSION_STATE_CHANGE,e)}),this.room.enableSEI&&this.on(ie.SEI_MESSAGE,e=>{var o;let r=(o=this.room.remotePublishedUserMap.get(e.userId))==null?void 0:o.remoteVideoTrack;r&&r.updateAlphaRenderInfo(e)})}getNetworkTime(){return Ri()}use(e){let r,o;return"plugin"in e?(r=e.plugin,o=e.assetsPath):r=e,r.Name==="Chorus"&&(this.room.enableChorus=!0),this._use(r,o)}_use(e,r){let o=this._plugins.get(e.Name);if(o)return this._log.warn("duplicate install plugin",e.Name),o;let s=new e(lT.call(this,{TRTC:pe,room:this._room,assetsPath:r,errorModule:{RtcError:oe,ErrorCode:ne,CoreErrorCode:q,ErrorCodeDictionary:Tr}}));return this._plugins.set(e.Name,s),s.__v_skip=!0,e.autoStart&&this.startPlugin(e.Name),s}enterRoom(e){return y(this,null,function*(){var d,l;this.enterRoomParams=e;let{scene:r="rtc",enableAutoPlayDialog:o=!0,autoReceiveAudio:s=!0,autoReceiveVideo:n=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!Oe(e.proxy)&&e.proxy.turnServer&&((l=(d=this._room).setTurnServer)==null||l.call(d,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=o,this._room.autoReceiveAudio=s,this._room.autoReceiveVideo=n,Ye(e.preferHW)&&(this._room.preferHW=e.preferHW),e.playoutDelay&&(this._room.playoutDelay=e.playoutDelay),e.jitterBufferDelay&&(this._room.jitterBufferDelay=e.jitterBufferDelay);let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:e.role==="audience"?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language,priority:e.priority,useVp8:e.useVp8,useH265:e.useH265||!1,keepAlive:e.keepAlive};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(a,r,pe.frameWorkType),this._checkTrackToPublish(),lf.start()})}exitRoom(){return y(this,null,function*(){return yield this._exitRoom()})}switchRoom(e){return y(this,null,function*(){if(this.room.isSwitchRoomSupported())try{this._clearRemoteTracks(),yield this._room.switchRoom(e)}catch(r){if(r instanceof la&&(r.code===q.API_CALL_TIMEOUT||r.code===q.SWITCH_ROOM_FAILED))this._log.warn(`switchRoom ${r.code===q.API_CALL_TIMEOUT?"timeout":"failed"}, fallback to exitRoom() and enterRoom()`),yield this._rejoinRoom(e);else throw r}else yield this._rejoinRoom(e)})}_rejoinRoom(e){return y(this,null,function*(){yield this.exitRoom();let r=Y(Y({},this.enterRoomParams),e);yield this.enterRoom(r)})}_clearRemoteTracks(){new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(e=>{this._stopRemoteAudio({userId:e}).catch(()=>{})}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let r=e.includes("main")?"main":"sub",o=e.split(`_${r}`)[0];o&&this._stopRemoteVideo({userId:o,streamType:r}).catch(()=>{})}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),hT(this),this._room.remotePublishedUserMap.forEach(e=>{At(e.remoteAudioTrack),At(e.remoteVideoTrack),At(e.remoteAuxiliaryTrack)})}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(){this._plugins.forEach(e=>{var r;return(r=e.destroy)==null?void 0:r.call(e)}),this._plugins.clear(),At(this),this.removeAllListeners(),this._room.destroy(),kc.delete(this),kc.size===0&&lf.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),U.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 li(this._room.audioManager),a={},d={muted:!0};s&&(O(s.microphoneId)?O(s.audioTrack)||(a.customSource=s.audioTrack):a.deviceId=s.microphoneId,s&&Fe(s.captureVolume)&&n.setCaptureVolume(s.captureVolume),O(s.profile)||(Oe(s.profile)?pd[s.profile]&&n.setProfile(pd[s.profile]):n.setProfile(s.profile)),Fe(s.earMonitorVolume)&&(d.muted=!(s.earMonitorVolume>0),d.volume=s.earMonitorVolume),O(s.echoCancellation)||(n.profile.echoCancellation=s.echoCancellation),O(s.noiseSuppression)||(n.profile.noiseSuppression=s.noiseSuppression),O(s.autoGainControl)||(n.profile.autoGainControl=s.autoGainControl),Ye(this._enableAutoSwitchWhenRecapturing)&&(n.enableAutoSwitchWhenRecapturing=this._enableAutoSwitchWhenRecapturing)),n.on("5",l=>{this.emit(ie.ERROR,new oe({code:ne.DEVICE_ERROR,extraCode:5309,messageParams:{error:l}}))}),n.on("2",l=>{this.emit(ie.DEVICE_CHANGED,{type:"microphone",action:"active",device:l})}),n.on("4",l=>{let p;l.error&&(p=oe.convertFrom(l.error)),this.emit(ie.PUBLISH_STATE_CHANGED,_e(Y({},l),{error:p}))}),n.on("6",()=>{}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId),yield n.capture(a),O(o)||n.setMute(o),Ft(n,n).add("player-state-changed",l=>{this.emit(ie.AUDIO_PLAY_STATE_CHANGED,_e(Y({},l),{userId:""}))}),r&&this._room.isJoined&&this._room.publish(n).catch(()=>{}),this._localAudioTrack=n,this._localAudioConfig=_e(Y({},e),{publish:r}),yield this._updateAudioPlayOption({playOption:d,track:n}),U.emit("113",{userId:"",room:this.room})})}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):O(s.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(s.audioTrack)),O(s.captureVolume)||this._localAudioTrack.setCaptureVolume(s.captureVolume),O(s.earMonitorVolume)||(n.muted=!(s.earMonitorVolume>0),n.volume=s.earMonitorVolume),yield this._localAudioTrack.update3A(s)),this._room.isJoined&&!O(r)&&(r&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!r&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),O(o)||this._localAudioTrack.setMute(o),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),Br(this._localAudioConfig,e)})}stopLocalAudio(){return y(this,null,function*(){this._localAudioTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),U.emit("114",{userId:"",room:this.room}),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),At(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)})}startLocalVideo(){return y(this,arguments,function*(e={publish:!0,view:null,capture:!0}){var f;if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:r,publish:o=!0,capture:s=!0,mute:n,option:a}=e,d=new _r(this._room.videoManager),l={},p={};a&&(Ye(a.avoidCropping)&&(d.avoidCropping=a.avoidCropping),a.cameraId?l.deviceId=a.cameraId:O(a.useFrontCamera)?O(a.videoTrack)||(l.customSource=a.videoTrack):l.facingMode=a.useFrontCamera?M.FACING_MODE_USER:M.FACING_MODE_ENVIRONMENT,O(a.retryWhenExactFailed)||(l.retryWhenExactFailed=a.retryWhenExactFailed),a.qosPreference&&(l.contentHint=Nc(a.qosPreference)),O(a.profile)||(Oe(a.profile)?Vr[a.profile]&&d.setProfile(Vr[a.profile]):d.setProfile(a.profile)),O(a.fillMode)||(p.objectFit=a.fillMode),O(a.mirror)||(p.mirror=a.mirror),O(a.small)||(O(a.smallMode)||(this._room.smallMode=a.smallMode),Ye(a.small)&&a.small===!1?d.stopSmall():d.updateSmallConfig(jn(a.small,!0))),O(a.rotation)||d.setRotation(a.rotation),Ye(this._enableAutoSwitchWhenRecapturing)&&(d.enableAutoSwitchWhenRecapturing=this._enableAutoSwitchWhenRecapturing)),d.once("first-video-frame",g=>{this.emit(ie.FIRST_VIDEO_FRAME,_e(Y({},g),{streamType:fi(g.streamType)}))}),d.on("5",g=>{this.emit(ie.ERROR,new oe({code:ne.DEVICE_ERROR,extraCode:5308,messageParams:{error:g}}))}),d.on("2",g=>{this.emit(ie.DEVICE_CHANGED,{type:"camera",action:"active",device:g})}),d.on("4",g=>{let A;g.error&&(A=oe.convertFrom(g.error)),this.emit(ie.PUBLISH_STATE_CHANGED,_e(Y({},g),{error:A}))}),d.on("6",()=>{}),this._listenOutputTrackChanged(d),s?yield d.capture(l):(f=d.manager)==null||f.changeInput(d),O(n)||(yield d.setMute(n)),Ft(d,d).add("player-state-changed",g=>{this.emit(ie.VIDEO_PLAY_STATE_CHANGED,_e(Y({},g),{userId:"",streamType:"main"}))}).add("video-size-changed",g=>{this.emit(ie.VIDEO_SIZE_CHANGED,_e(Y({},g),{streamType:fi(g.streamType)}))}),o&&this._room.isJoined&&this._room.publish(d).catch(()=>{}),this._localVideoTrack=d,this._localVideoConfig=_e(Y({},e),{view:r,publish:o,capture:s}),yield this._updateVideoPlayOption({view:r,playOption:p,track:d})})}updateLocalVideo(e){return y(this,null,function*(){var l,p,f;if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:r,publish:o,mute:s,capture:n,option:a}=e,d={};if(this._localVideoConfig.capture)n!==!1?a!=null&&a.cameraId?yield this._localVideoTrack.switchDevice(a==null?void 0:a.cameraId):O(a==null?void 0:a.useFrontCamera)?O(a==null?void 0:a.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(a==null?void 0:a.videoTrack)):yield this._localVideoTrack.switchDevice(a!=null&&a.useFrontCamera?M.FACING_MODE_USER:M.FACING_MODE_ENVIRONMENT):this._localVideoTrack.stopCapture();else if(n){let g={};g.deviceId=(a==null?void 0:a.cameraId)||((l=this._localVideoConfig.option)==null?void 0:l.cameraId),g.facingMode=a!=null&&a.useFrontCamera||(p=this._localVideoConfig.option)!=null&&p.useFrontCamera?M.FACING_MODE_USER:M.FACING_MODE_ENVIRONMENT,g.customSource=(a==null?void 0:a.videoTrack)||((f=this._localVideoConfig.option)==null?void 0:f.videoTrack),yield this._localVideoTrack.capture(g)}a&&(O(a.profile)||(Oe(a.profile)?Vr[a.profile]&&this._localVideoTrack.setProfile(Vr[a.profile]):this._localVideoTrack.setProfile(a.profile),(!a.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(a.cameraId))&&O(a.useFrontCamera)&&(yield this._localVideoTrack.applyProfile())),O(a.fillMode)||(d.objectFit=a.fillMode),O(a.mirror)||(d.mirror=a.mirror),O(a.rotation)||this._localVideoTrack.setRotation(a.rotation),a.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(Nc(a.qosPreference)),O(a.small)||(Ye(a.small)&&!a.small?this._localVideoTrack.stopSmall():this._localVideoTrack.updateSmallConfig(jn(a.small,!0)))),this._room.isJoined&&O(o)&&this._localVideoConfig.publish&&n&&!this._localVideoConfig.capture&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._room.isJoined&&((o!=null?o:this._localVideoConfig.publish)?this._room.publish(this._localVideoTrack).catch(()=>{}):this._room.unpublish(this._localVideoTrack).catch(()=>{})),O(s)||(yield this._localVideoTrack.setMute(s)),yield this._updateVideoPlayOption({view:r,playOption:d,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),Br(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(),At(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return y(this,arguments,function*(e={publish:!0,view:null}){var g,A;if(this._localScreenTrack){this._log.warn("screen share is already started");return}let{view:r=null,publish:o=!0,muteSystemAudio:s,option:n}=e,a=new mi(this._room.videoManager);a.on("4",R=>{let N;R.error&&(N=oe.convertFrom(R.error)),this.emit(ie.PUBLISH_STATE_CHANGED,_e(Y({},R),{error:N}))}),a.once("first-video-frame",R=>{this.emit(ie.FIRST_VIDEO_FRAME,_e(Y({},R),{streamType:fi(R.streamType)}))}),this._listenOutputTrackChanged(a),e.streamType==="main"&&(a.mediaType=4);let d=null,l={},p={};n&&(O(n.profile)||(Oe(n.profile)?fd[n.profile]&&a.setProfile(fd[n.profile]):a.setProfile(n.profile)),n.systemAudio&&(l.systemAudio=!0,l.echoCancellation=n.echoCancellation,l.noiseSuppression=n.noiseSuppression,l.autoGainControl=n.autoGainControl),O(n.fillMode)||(p.objectFit=n.fillMode),n.videoTrack&&(l.videoTrack=n.videoTrack),n.audioTrack&&(l.audioTrack=n.audioTrack),n.captureElement&&(l.captureElement=n.captureElement),n.preferDisplaySurface&&(l.preferDisplaySurface=n.preferDisplaySurface),n.qosPreference&&(l.contentHint=Nc(n.qosPreference)));let f=yield a.capture(l);if(a.mediaTrack.addEventListener(M.ENDED,()=>{this._stopScreenShare(),this.emit(ie.SCREEN_SHARE_STOPPED)}),f.getAudioTracks()[0]){d=new Ls(this._room.audioManager);let R=f.getAudioTracks()[0];(g=e.option)!=null&&g.systemAudio&&!((A=e.option)!=null&&A.audioTrack)&&(d.sourceTrack=R),yield d.setInputMediaStreamTrack(R),Ye(s)&&d.mediaTrack&&(d.mediaTrack.enabled=!s),this._speakerId&&d.setAudioOutput(this._speakerId)}if(Ft(a,a).add("player-state-changed",R=>{this.emit(ie.VIDEO_PLAY_STATE_CHANGED,_e(Y({},R),{userId:"",streamType:"sub"}))}),o&&this._room.isJoined){let R=[a];d&&(R.push(d),this._checkScreenAudioEchoCancellation(a,d)),R.forEach(N=>this._room.publish(N).catch(()=>{}))}this._localScreenTrack=a,this._localScreenAudioTrack=d,this._localScreenConfig=_e(Y({},e),{view:r,publish:o}),yield this._updateVideoPlayOption({view:r,playOption:p,track:a})})}updateScreenShare(e){return y(this,null,function*(){var d;if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:r,publish:o,muteSystemAudio:s,option:n}=e,a={};if(n&&(O(n.fillMode)||(a.objectFit=n.fillMode),n.qosPreference)){let l=Nc(n.qosPreference);this._localScreenTrack.setContentHint(l)}if(this._room.isJoined&&!O(o)){if(o&&!this._localScreenConfig.publish){let l=[this._localScreenTrack];this._localScreenAudioTrack&&l.push(this._localScreenAudioTrack),l.forEach(p=>this._room.publish(p).catch(()=>{}))}if(this._localScreenConfig.publish&&!o){let l=[this._localScreenTrack];this._localScreenAudioTrack&&l.push(this._localScreenAudioTrack),l.forEach(p=>this._room.unpublish(p).catch(()=>{}))}}(d=this._localScreenAudioTrack)!=null&&d.mediaTrack&&Ye(s)&&(this._localScreenAudioTrack.mediaTrack.enabled=!s),yield this._updateVideoPlayOption({view:r,playOption:a,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),Br(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,a=`${o}_${s}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${o}, streamType:${s}`);return}let d=this._room.remotePublishedUserMap.get(o);if(!d)return;let l={},p=s==="main"?d.remoteVideoTrack:d.remoteAuxiliaryTrack;p.on("decode-failed",f=>{this.emit(ie.ERROR,new oe({code:ne.OPERATION_FAILED,extraCode:5507,message:"video decode failed"}))}),p.on("video-size-changed",f=>{this.emit(ie.VIDEO_SIZE_CHANGED,_e(Y({},f),{streamType:fi(f.streamType)}))}),this._listenOutputTrackChanged(p),n&&(O(n.fillMode)||(l.objectFit=n.fillMode),O(n.mirror)||(l.mirror=n.mirror),O(n.poster)||(l.poster=n.poster),l.canvasRender=n.canvasRender,s==="main"&&!O(n.small)&&(!d.remoteVideoTrack.isSubscribing&&!d.remoteVideoTrack.isSubscribed&&d.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,p.user)),O(n.draggable)||p.setDraggable(n.draggable)),yield this._room.subscribe(p),yield this._enableVideoDecodeFallback(p,s),yield this._updateVideoPlayOption({view:r,playOption:l,track:p}),this._emitTrackEvent(p),this._remoteVideoConfigMap.set(a,{config:e}),n&&!O(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:p,view:r,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:n==null?void 0:n.viewRoot})})}updateRemoteVideo(e){return y(this,null,function*(){var P,z;let{view:r,userId:o,streamType:s,option:n,mute:a}=e,d=`${o}_${s}`,l=this._remoteVideoConfigMap.get(d);if(!l||!this._room.remotePublishedUserMap.has(o))return;let p={};n&&(O(n.fillMode)||(p.objectFit=n.fillMode),O(n.mirror)||(p.mirror=n.mirror));let f=null,g=this._room.remotePublishedUserMap.get(o);if(s==="main"&&(g!=null&&g.muteState.hasVideo)&&(f=g.remoteVideoTrack),s==="sub"&&(g!=null&&g.muteState.hasAuxiliary)&&(f=g.remoteAuxiliaryTrack),!f)return;let{config:A}=l;s==="main"&&n&&!O(n.small)&&this._room.changeType(n.small,f.user),n&&!O(n.draggable)&&f.setDraggable(n.draggable),Ye(a)&&(f.ignoreUpdatePlayingState=!0,a?(yield f.player.pause(),yield this.room.unsubscribe(f)):(yield this.room.subscribe(f),yield f.player.resume())),yield this._updateVideoPlayOption({view:r,playOption:p,track:f,prevConfig:A}),Br(A,e);let R=O(n==null?void 0:n.receiveWhenViewVisible)?(P=A.option)==null?void 0:P.receiveWhenViewVisible:n.receiveWhenViewVisible,N=O(r)?A.view:r,C=O(n==null?void 0:n.viewRoot)?(z=A.option)==null?void 0:z.viewRoot:n.viewRoot;this._observeView({remoteTrack:f,view:N,receiveWhenViewVisible:R,viewRoot:C})})}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:n,remoteVideoTrack:a,remoteAuxiliaryTrack:d}=s;e.streamType==="main"&&(a.stop(),n.hasVideo&&o.push(a)),e.streamType==="sub"&&(d.stop(),n.hasAuxiliary&&o.push(d))}for(let n of o)r&&(delete n.ignoreUpdatePlayingState,yield this._room.unsubscribe(n),this._mediaTrackMap.delete(n.outMediaTrack));this._removeRemoteVideoConfig(e.userId,e.streamType)})}_removeRemoteVideoConfig(e,r){let o=`${e}_${r}`,s=this._remoteVideoConfigMap.get(o);s&&s.observer&&s.observer.disconnect(),this._remoteVideoConfigMap.delete(o)}muteRemoteAudio(e,r){return 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 o.code!==ne.OPERATION_ABORT&&this._remoteAudioMuteMap.delete(e),o}})}setRemoteAudioVolume(e,r){if(e==="*"){this._remoteAudioVolumeMap.set("*",r),this._remoteAudioVolumeMap.forEach((s,n)=>this._remoteAudioVolumeMap.set(n,r));let o=[...this._room.remotePublishedUserMap.values()];for(let s of o)this._remoteAudioVolumeMap.set(s.userId,r),s.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:r},track:s.remoteAudioTrack})}else if(e){let o=this._room.remotePublishedUserMap.get(e);this._remoteAudioVolumeMap.set(e,r),o&&o.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:r},track:o.remoteAudioTrack})}}startPlugin(e,r){return 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){if(this.listeners(e).includes(r))return this;if(this._log.debug("on",e),super.on(e,r,o),this._eventListened.add(e),this.listeners(ie.AUDIO_FRAME).length>0){let{audioFrameEventConfigMap:s}=this.room.audioManager;s.get("")||s.set("",{enable:!0}),this._localAudioTrack&&this.room.audioManager.handleLocalTrackStarted({userId:"",room:this.room})}return this}emit(e,...r){try{aT.has(e)||this._log.debug(`emit ${e} ${JSON.stringify(r)}`)}catch(o){}return super.emit(e,...r)}off(e,r,o){if(this._log.debug("off",e),e==="*"?(this._eventListened.clear(),this.removeAllListeners()):super.off(e,r,o),(e===pe.EVENT.AUDIO_FRAME||e==="*")&&this.listeners(pe.EVENT.AUDIO_FRAME).length===0){let{getPCMAbortCtrlMap:s}=this.room.audioManager;s.forEach(n=>{n==null||n.abort("off")}),s.clear()}return this}getAudioTrack(e={userId:"",streamType:"main"}){let r,o=null,s="main",n=!1;if(Oe(e)?r=e:(r=e.userId,n=e.processed===!0,e.streamType&&(s=e.streamType)),r){let a=this._room.remotePublishedUserMap.get(r);a&&(o=a.remoteAudioTrack)}else o=s==="sub"?this._localScreenAudioTrack:this._localAudioTrack;return o?n&&o.outMediaTrack&&o.outMediaTrack!==o.mediaTrack?o.outMediaTrack.clone():o.mediaTrack:null}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:r="",streamType:o="main",processed:s=!1}=e,n=null;if(r==="")o==="main"&&this._localVideoTrack&&(n=this._localVideoTrack),o==="sub"&&this._localScreenTrack&&(n=this._localScreenTrack);else{let a=this._room.remotePublishedUserMap.get(r);a&&(n=o==="main"?a.remoteVideoTrack:a.remoteAuxiliaryTrack)}return n?s&&n.outMediaTrack&&n.outMediaTrack!==n.mediaTrack?n.outMediaTrack.clone():n.mediaTrack:null}getVideoSnapshot(e={}){let{userId:r,streamType:o="main"}=e;if(r){let s=this._room.remotePublishedUserMap.get(r);if(o==="main"&&(s!=null&&s.muteState.hasVideo))return s.remoteVideoTrack.getVideoFrame();if(o==="sub"&&(s!=null&&s.muteState.hasAuxiliary))return s.remoteAuxiliaryTrack.getVideoFrame()}else{if(o==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(o==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(e){var r,o;this._speakerId=e,(r=this._localAudioTrack)==null||r.setAudioOutput(e),(o=this._localScreenAudioTrack)==null||o.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(s=>s.remoteAudioTrack.setAudioOutput(e))}setCurrentSpeaker(e){return y(this,null,function*(){(yield Co()).forEach(o=>{o.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(ie.DEVICE_CHANGED,{type:"speaker",action:"active",device:o}),kt=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: ${or}/en/TRTC.html#.setCurrentSpeaker`)})}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return y(this,null,function*(){var a;let{userId:r}=e;if(this._remoteAudioConfigMap.has(r)){this._log.warn(`remote audio has already started. userId:${r}`);return}let o=this._room.remotePublishedUserMap.get(r);if(!o)return;let s={},n=o.remoteAudioTrack;n.on("decode-failed",d=>{this.emit(ie.ERROR,new oe({code:ne.OPERATION_FAILED,extraCode:5508,message:"audio decode failed"}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId);try{let d=(a=this._remoteAudioVolumeMap.get(r))!=null?a:this._remoteAudioVolumeMap.get("*"),l=Fe(d)?d:100;s.volume=l,this._remoteAudioConfigMap.set(r,e),yield this._room.subscribe(n),ye(Ae(n,"decode-failed"),Je(Ae(n,ue.INIT)),Le(()=>{this.startPlugin(Pc.Name,{track:n,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:s,track:n}),U.emit("115",{userId:r,room:this.room}),n.outMediaTrack&&this.room.audioManager.updateAudioReference({type:"add",audioReference:n.outMediaTrack,refId:`ra-${r}`})}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}`),U.emit("116",{userId:e.userId,room:this.room}),this.room.audioManager.updateAudioReference({type:"remove",refId:`ra-${e.userId}`})})}_enableVideoDecodeFallback(e,r){let o=this._room.videoDecodeFallbackType;if(!o||!this._plugins.has("TRTCVideoDecoder"))return;e.log.debug("remote video will fall back when decode failed",e.id);let s;ye(Ae(e,"decode-failed"),Je(Ae(e,ue.INIT)),Ds(()=>{this._room.downlinkVideoCodec!=="h265"&&this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:o})}),qi(Ae(e,"decode-downgrade-state-changed")),Le(n=>{s=n.state,this.emit(ie.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,_e(Y({},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),O(e)&&s&&s.view&&!un(r)){let a=mn(s.view);a.length>0&&(yield o.play(a,r))}if(!O(e)){let a=mn(e);a.length>0?yield o.play(a,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){}if(O(e.muted)||r.setPlayerMute(e.muted),O(e.volume)||r.setAudioVolume(e.volume/100),r instanceof li&&r.mediaTrack){let n=e.muted===!1&&!O(e.volume)&&e.volume>0?"add":"remove";this.room.audioManager.updateAudioReference({type:n,audioReference:r.mediaTrack,refId:"em"})}else if(r instanceof zi){let n=e.muted?0:e.volume;if(O(n))return;this.room.audioManager.updateAudioReference({type:"updateVolume",refId:`ra-${r.userId}`,volume:e.volume})}})}_listenOutputTrackChanged(e){e.listeners("output-media-track-changed").length===0&&e.on("output-media-track-changed",()=>this._emitTrackEvent(e,!1))}_emitTrackEvent(e,r=!0){let o=e.isRemote?e.userId:"";e.outMediaTrack&&(r&&this._mediaTrackMap.get(e.outMediaTrack)===o||(this._mediaTrackMap.set(e.outMediaTrack,o),this.emit(ie.TRACK,{userId:o,streamType:fi(e.streamType),track:e.outMediaTrack,sourceTrack:e.mediaTrack})))}_checkTrackToPublish(){var r,o,s;let e=[];if((r=this._localAudioConfig)!=null&&r.publish&&this._localAudioTrack&&e.push(this._localAudioTrack),(o=this._localVideoConfig)!=null&&o.publish&&this._localVideoTrack&&e.push(this._localVideoTrack),(s=this._localScreenConfig)!=null&&s.publish&&(this._localScreenTrack&&e.push(this._localScreenTrack),this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack),this._checkScreenAudioEchoCancellation(this._localScreenTrack,this._localScreenAudioTrack)),e.length!==0)return Promise.all(e.map(n=>this._room.publish(n).catch(()=>{})))}_observeView({remoteTrack:e,view:r,receiveWhenViewVisible:o,viewRoot:s}){if(O(r)||O(o))return;let n=this._remoteVideoConfigMap.get(`${e.userId}_${fi(e.streamType)}`);if(!n)return;let a=n.observer||void 0;if(r===null||mt(r)&&r.length===0||!o){a==null||a.disconnect(),e.isSubscribed||(this._log.info("_observeView observer disconnect, resubscribe",e.userId,e.strMediaType),this._room.subscribe(e).catch(()=>{}));return}let l=n.visibleViewMap||new Map,p=-1;(!a||a.root!==s)&&(a==null||a.disconnect(),l.clear(),a=new IntersectionObserver(g=>{g.forEach(A=>{l.set(A.target,A.isIntersecting),e.log.info(`view ${A.target.id} is${A.isIntersecting?"":" not"} visible`)}),clearTimeout(p),p=window.setTimeout(()=>{[...l.values()].find(R=>R)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:s}));let f=new Set(mn(r));l.forEach((g,A)=>{f.has(A)||(a.unobserve(A),l.delete(A))}),f.forEach(g=>{l.set(g,!0),a.observe(g)}),a.takeRecords().forEach(g=>{l.set(g.target,g.isIntersecting)}),n.visibleViewMap=l,n.observer=a}_exitRoom(){return y(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),this._clearRemoteTracks()})}_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 Promise.all(r.map(o=>this._room.unpublish(o).catch(()=>{})))}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(((e=this._localScreenAudioTrack.trackSettings)==null?void 0:e.echoCancellation)===!1&&this.stopPlugin("AudioProcessor"),this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),At(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_checkScreenAudioEchoCancellation(e,r){return y(this,null,function*(){var s,n;if(!e||!r)return;let o=(s=e.trackSettings)==null?void 0:s.displaySurface;if(((n=r.trackSettings)==null?void 0:n.echoCancellation)===!1&&(o==="monitor"||o==="browser"&&e.isShareCurrentTab)){this._log.warn("echoCancellation of screen audio track is disable. Try starting audioProcessor plugin");try{yield this.startPlugin("AudioProcessor",{sdkAppId:Number(this.room.sdkAppId),userId:this._room.userId,userSig:this.room.userSig,isScreenAudioNeedAudioProcess:!0,isLocalAudioNeedAudioProcess:!1})}catch(a){this._log.warn("start audioProcessor plugin failed: ",a)}}})}_onLocalTrackCaptured({track:e}){e.kind==="audio"&&(!kt||xn(kt))&&(this._initActiveSpeaker(),U.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return y(this,null,function*(){if(kt&&!xn(kt))this.emit(ie.DEVICE_CHANGED,{type:"speaker",action:"active",device:kt});else{let e=yield Co();e[0]&&!xn(e[0])?(kt=e[0],this.emit(ie.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):U.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:_e(Y({seiPayloadType:243},r),{small:!!((s=this._localVideoTrack)!=null&&s.small)})}),X.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var r,o;(o=(r=this._room).sendCustomMessage)==null||o.call(r,e),X.addCount({key:500001,useUV:!0})}callExperimentalAPI(e,r){return y(this,null,function*(){return this._log.info(`callExperimentalAPI(${e}, ${JSON.stringify(r)})`),IT.call(e,Y({trtcInstance:this},r))})}static setLogLevel(e,r){F.setLogLevel(e),O(r)||(r?F.enableUploadLog():F.disableUploadLog())}static isSupported(){return fu(pe.frameWorkType)}static getPermissions(o){return y(this,arguments,function*({request:e=!0,types:r=["camera","microphone"]}){e&&(yield Lc.request(r).catch(a=>{var d;return F.error(`getPermissions request failed, error: ${(d=a==null?void 0:a.message)!=null?d:a}`)}));let[s,n]=yield Promise.all([Lc.get("camera"),Lc.get("microphone")]);return{camera:s,microphone:n}})}static getCameraList(e=!0){return dr(e)}static getMicrophoneList(e=!0){return cr(e)}static getSpeakerList(e=!0){return Co(e)}static setCurrentSpeaker(e){return y(this,null,function*(){if(at&&(e===Vs.SPEAKER||e===Vs.HEADSET)){let o=yield pe.getMicrophoneList(),s="";if(o.forEach(n=>{n.label===e&&(s=n.deviceId)}),!s)return;kc.forEach(n=>y(this,null,function*(){n._localAudioTrack&&(yield n.updateLocalAudio({option:{microphoneId:s}}))}));return}(yield Co()).forEach(o=>{o.deviceId===e&&(kc.forEach(s=>{s._setCurrentSpeaker(e),s.emit(ie.DEVICE_CHANGED,{type:"speaker",action:"active",device:o})}),kt=o)})})}static _addKVStat({type:e,key:r,value:o,base:s,useUV:n,version:a,max:d}){switch(a&&(Ts.version=a),e){case"count":Ts.addCount({key:r,useUV:n});break;case"enum":Ts.addEnum({key:r,value:o,useUV:n});break;case"number":Ts.addNumber({key:r,value:o,split:s,max:d});break}}};m(pe,"VERSION",sf),m(pe,"_loggerManager",F),m(pe,"EVENT",ie),m(pe,"ERROR_CODE",ne),m(pe,"TYPE",Vs),m(pe,"frameWorkType",30),Z([nt({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"}})})],pe.prototype,"use",1),Z([$t(Ot.TRTC.enterRoom),Uo("room",([e],[r])=>(e.roomId||e.strRoomId)===(r.roomId||r.strRoomId)&&e.userId===r.userId&&e.sdkAppId===r.sdkAppId),Pe(e=>function(r){return this._log.setUserId(r.userId),this._log.setSdkAppId(r.sdkAppId),e.call(this,r)}),nt()],pe.prototype,"enterRoom",1),Z([nt()],pe.prototype,"exitRoom",1),Z([$t(Ot.TRTC.switchRoom),nt(),Ou()],pe.prototype,"switchRoom",1),Z([$t(Ot.TRTC.switchRole),Bs("room",{merge:(e,r)=>r}),nt()],pe.prototype,"switchRole",1),Z([nt()],pe.prototype,"destroy",1),Z([$t(Ot.TRTC.startLocalAudio),Uo("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)}),nt()],pe.prototype,"startLocalAudio",1),Z([$t(Ot.TRTC.updateLocalAudio),Bs("audio",{debounce:{delay:200,getKey:()=>`${AT}-localAudio`,isNeedToDebounce:e=>{var r;return!O((r=e.option)==null?void 0:r.captureVolume)}}}),nt()],pe.prototype,"updateLocalAudio",1),Z([Vo("audio"),nt()],pe.prototype,"stopLocalAudio",1),Z([$t(Ot.TRTC.startLocalVideo),Uo("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)}),nt()],pe.prototype,"startLocalVideo",1),Z([$t(Ot.TRTC.updateLocalVideo),Bs("video"),nt()],pe.prototype,"updateLocalVideo",1),Z([Vo("video"),nt()],pe.prototype,"stopLocalVideo",1),Z([$t(Ot.TRTC.startScreenShare),Uo("screen",()=>!0),nt()],pe.prototype,"startScreenShare",1),Z([$t(Ot.TRTC.updateScreenShare),Bs("screen"),nt()],pe.prototype,"updateScreenShare",1),Z([nt()],pe.prototype,"stopScreenShare",1),Z([$t(Ot.TRTC.startRemoteVideo),Uo(e=>`v${e.userId}${e.streamType}`,()=>!0),nt({getRemoteId:e=>`${e.userId}_${e.streamType}`})],pe.prototype,"startRemoteVideo",1),Z([$t(Ot.TRTC.updateRemoteVideo),Bs(e=>`v${e.userId}${e.streamType}`),nt({getRemoteId:e=>`${e.userId}_${e.streamType}`})],pe.prototype,"updateRemoteVideo",1),Z([$t(Ot.TRTC.stopRemoteVideo),Pe(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)})}),nt({getRemoteId:e=>`${e.userId}_${e.streamType}`})],pe.prototype,"stopRemoteVideo",1),Z([Vo(e=>`v${e.userId}${e.streamType}`)],pe.prototype,"_stopRemoteVideo",1),Z([$t(...Ot.TRTC.muteRemoteAudio),nt({getRemoteId:e=>e})],pe.prototype,"muteRemoteAudio",1),Z([nf(...Ot.TRTC.setRemoteAudioVolume),pT(200,e=>e),nt({getRemoteId:e=>e})],pe.prototype,"setRemoteAudioVolume",1),Z([_l("start"),No(e=>{var r;return(r=e.afterStart)==null?void 0:r.call(e)}),Uo((e,r)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(r)),nt({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>dh[e.getName()],ignoreLog:e=>e.getName()==="Debug",ignoreErrorLog:e=>e.getName()==="AudioProcessor"})],pe.prototype,"startPlugin",1),Z([_l("update"),Bs((e,r)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(r),{merge:(e,r)=>(Br(e[1],r[1]),e)}),nt({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>uh[e.getName()]})],pe.prototype,"updatePlugin",1),Z([_l("stop"),Vo((e,r)=>{if(e.disableRandomCall)return null;let o=e.getGroup(r),s=e.getAlias();return o==="*"?new RegExp(`${s}.*`):s+o}),nt({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>lh[e.getName()]})],pe.prototype,"stopPlugin",1),Z([nf(...Ot.TRTC.enableAudioVolumeEvaluation)],pe.prototype,"enableAudioVolumeEvaluation",1),Z([nt()],pe.prototype,"getVideoSnapshot",1),Z([nt()],pe.prototype,"_setCurrentSpeaker",1),Z([Uo(e=>`a${e.userId}`,()=>!0)],pe.prototype,"_startRemoteAudio",1),Z([Pe(e=>function(r){return y(this,null,function*(){return r.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(o=>this._stopRemoteAudio(_e(Y({},r),{userId:o.userId})).catch(()=>{}))):e.call(this,r)})}),Vo(e=>`a${e.userId}`)],pe.prototype,"_stopRemoteAudio",1),Z([Vo("room")],pe.prototype,"_exitRoom",1),Z([Vo("screen")],pe.prototype,"_stopScreenShare",1),Z([$t(...Ot.TRTC.sendSEIMessage),Kp({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...e)=>e[0].byteLength})],pe.prototype,"sendSEIMessage",1),Z([$t(Ot.TRTC.sendCustomMessage),Kp({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],pe.prototype,"sendCustomMessage",1),Z([Fo()],pe,"create",1),Z([$t(Ot.TRTC.create)],pe,"_create",1),Z([Fo()],pe,"setLogLevel",1),Z([Fo()],pe,"isSupported",1),Z([Fo()],pe,"getPermissions",1),Z([Fo()],pe,"getCameraList",1),Z([Fo()],pe,"getMicrophoneList",1),Z([Fo()],pe,"getSpeakerList",1);var gf=pe,Qn=gf;var wl=class{constructor(t,e){m(this,"_flag");m(this,"terminalType");m(this,"userId");m(this,"tinyId");m(this,"role");m(this,"remoteAudioTrack");m(this,"remoteVideoTrack");m(this,"remoteAuxiliaryTrack");this.userId=e.userId||"",this.tinyId=e.tinyId||"",this.role=e.role||"audience",this.terminalType=e.terminalType,this.remoteAudioTrack=new zi(t,this),this.remoteVideoTrack=new xo(t,this),this.remoteAuxiliaryTrack=new tl(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 cs(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 Ef=class{constructor(){m(this,"_set",new Set);U.on(B.LEAVE_SUCCESS,this.delete,this),U.on(B.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess,this)}add({room:t,roomId:e}){if(t.scene==="rtc")return;let r=this.getKey(t.userId,e||t.roomId,t.sdkAppId,t.useStringRoomId);this._set.add(r)}delete({room:t,roomId:e}){if(t.scene==="rtc")return;let r=this.getKey(t.userId,t.roomId||e,t.sdkAppId,t.useStringRoomId);this._set.delete(r)}getKey(t,e,r,o){return`${r}_${e}_${t}_${o}`}isJoined({userId:t,roomId:e,sdkAppId:r,room:o}){return o.scene==="rtc"?!1:this._set.has(this.getKey(t,e,r,o.useStringRoomId))}handleSwitchRoomSuccess({room:t,currentRoomId:e,targetRoomId:r}){t.scene!=="rtc"&&(this._set.delete(this.getKey(t.userId,e,t.sdkAppId,t.useStringRoomId)),this._set.add(this.getKey(t.userId,r,t.sdkAppId,t.useStringRoomId)))}};function YR(){return y(this,null,function*(){let i,t;try{let A=yield cr();i=A&&A.length}catch(A){}try{let A=yield dr();t=A&&A.length}catch(A){}let e={microphone:i,camera:t},{isH264EncodeSupported:r,isVp8EncodeSupported:o,isH264DecodeSupported:s,isVp8DecodeSupported:n,isH265EncodeSupported:a,isH265DecodeSupported:d}=this.checkSystemResult.detail,l=bo.basis(),p={webRTC:l.isWebRTCSupported,getUserMedia:l.isGetUserMediaSupported,webSocket:l.isWebSocketsSupported,screenShare:l.isScreenShareSupported,webAudio:l.isWebAudioSupported,h264Encode:r,h264Decode:s,vp8Encode:o,vp8Decode:n,h265Encode:a,h265Decode:d},f={browser:l.browser,os:l.os,trtc:p,devices:e},g={isWebCodecSupported:l.isWebCodecSupported,isMediaSessionSupported:l.isMediaSessionSupported,isWebTransportSupported:l.isWebTransportSupported};qe.uploadEvent({log:`trtcstats-${JSON.stringify(f)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(f)}`),qe.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(g)}`,userId:this.userId}),Ah()})}function bT(){return Pe(i=>{let t=new Ef;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 se({code:q.INVALID_OPERATION,message:We({key:He.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:s,sdkAppId:this.sdkAppId,room:this}))throw new se({code:q.INVALID_OPERATION,message:We({key:He.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}`),U.emit(B.JOIN_START,{room:this,roomId:s,params:e});let n=si.getEnv();n||(n=vi.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(gd.OLD_CLOUD_LADDER)?n=vi.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(gd.WEBRTC)&&(n=vi.WEBRTC))),qe.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:s}),bo.checkSystemRequirementsInternal(o).then(a=>{this.checkSystemResult=a,YR.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!si.getEnv()&&(yield this.schedule(e,o));let a=yield i.call(this,e,r,o);return this.roomId=s,this._joinedTimestamp=si.performanceNow(),U.emit(B.JOIN_SUCCESS,{room:this}),o===30&&!e.component&&qe.uploadEvent({log:`stat-conv-${Number(jr)}-${location.hostname}`,userId:this.userId}),a}catch(a){throw t.delete({room:this,roomId:s}),U.emit(B.JOIN_FAILED,{room:this,error:a}),a}})}})}var RT=()=>Pe(i=>function(...t){return y(this,null,function*(){U.emit(B.LEAVE_START,{room:this}),yield i.call(this,...t),U.emit(B.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function vT(){return Pe(i=>function(...t){return y(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(t=t.filter(r=>r.outMediaTrack&&r.state==="ready"),!t.length))return;U.emit("61",{room:this});let e=i.apply(this,t);return Promise.all(t.map(r=>r.publish(this,e)))})})}function CT(){return Pe(i=>function(...t){let e=i.apply(this,t);return t.forEach(r=>r.unpublish()),e})}function NT(){return Pe(i=>function(...t){let e=i.apply(this,t);return t.forEach(r=>!r.isSubscribed&&r.subscribe(e)),e})}function ZR({fn:i,context:t}){return function(...e){try{let r=i.apply(t,e);return fo(r)?r.catch(o=>F.error(`${i.name}() error observed ${o}`)):r}catch(r){F.error(`${i.name}() error observed ${r}`)}}}var Ol=class{constructor(t){m(this,"_frameWorkType");m(this,"_component");m(this,"_language");m(this,"connectionType");m(this,"_room");m(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,reportToken:void 0});m(this,"_keyPrefix");m(this,"_log");m(this,"_intervalId");m(this,"_firstPublishedUserList");m(this,"_networkQuality");m(this,"_basicInfo");m(this,"_pathJoinRoom");m(this,"_pathLeaveRoom");m(this,"_pathMainVideoMap");m(this,"_pathMainAudioMap");m(this,"_pathAuxiliaryMap");m(this,"_remoteStreamStatMap");m(this,"_localStreamStat");m(this,"_eventMap",new Map);m(this,"_captureCostSum",0);m(this,"_captureCostCount",0);m(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=F.createLogger({parent:this._room.getLogger(),id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(e=>{e.startsWith("handle")&&Xe(this[e])&&(this[e]=ZR({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:pt,uint32_os_type:15,string_device_name:"",string_http_user_agent:navigator.userAgent,string_os_version:"",uint32_avg_rtt:0,uint32_avg_up_loss:0,uint32_scene:this._room.scene==="live"?1:0,uint32_joining_duration:0,uint32_networkType:0,uint32_framework:this._frameWorkType,uint32_component:this._component,uint32_connection_type:this.connectionType,uint32_caller_coding_language:this._language,string_domain:location.hostname},this._pathJoinRoom={uint64_start_time:0,uint64_send_request_acc_ip_cmd_start_time:0,uint64_send_request_acc_ip_cmd_end_time:0,uint64_send_request_enter_room_cmd_start_time:0,uint64_send_request_enter_room_cmd_end_time:0,uint64_send_first_video_frame_time:0,uint64_recv_userlist_time:0,uint64_end_time:0,int32_send_request_acc_ip_cmd_ret:0,int32_send_request_enter_room_cmd_ret:0,int32_end_ret:0},this._pathLeaveRoom={uint64_start_time:0,uint64_send_request_exit_room_cmd_start_time:0,uint64_send_request_exit_room_cmd_end_time:0,uint64_end_time:0,int32_send_request_exit_room_cmd_ret:0,int32_end_ret:0},this._localStreamStat={totalVideoBitrate:0,totalVideoFPS:0,totalVideoHeight:0,totalVideoWidth:0,totalAudioLevel:0,videoCount:0,audioLevelCount:0,publishStartTime:0,statsToReport:{uint32_audio_capture_db:0,uint32_video_big_capture_fps:0,uint32_video_big_bitrate:0,uint32_video_big_resolution:0,uint32_audio_capture_thread_health_zero_cnt:0,uint32_after3a_silence_duration:0}},this._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,hs().then(()=>{this._basicInfo.string_os_version=Li(),this._basicInfo.string_device_name=ps()||this._basicInfo.string_os_version})}addEvent(t,e){return this._eventMap.set(t,e),U.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(B.JOIN_START,this.handleJoinStart).addEvent(B.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(B.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(B.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(B.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(B.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(B.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(B.JOIN_FAILED,this.handleJoinFailed).addEvent(B.LEAVE_START,this.handleLeaveStart).addEvent(B.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(B.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(B.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(B.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(B.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(B.PUBLISH_START,this.handlePublishStart).addEvent(B.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(B.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(B.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(B.PLAY_TRACK_START,this.handlePlayStart).addEvent(B.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(B.PLAYER_STATE_CHANGED,({track:t,state:e,type:r})=>{!t.isRemote||!this.hitTest(t.room)||e==="PLAYING"&&(r===M.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))}).addEvent(B.SWITCH_ROOM_START,this.handleSwitchRoomStart).addEvent(B.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess).addEvent(B.SWITCH_ROOM_FAILED,this.handleSwitchRoomFailed).addEvent(B.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(B.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(B.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(B.REMOTE_PUBLISH_STATE_CHANGED,({room:t,prevMuteState:e,muteState:r})=>{if(!this.hitTest(t))return;let o=e.hasAudio||e.hasVideo||e.hasSmall,s=e.hasAuxiliary,n=r.hasAudio||r.hasVideo||r.hasSmall,a=r.hasAuxiliary;!o&&n&&this.handleRemoteStreamAdded(r.userId,"main"),!s&&a&&this.handleRemoteStreamAdded(r.userId,"auxiliary")}).addEvent(B.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)=>U.off(e,t)),this._eventMap.clear()}destroy(){this.uninstallEvents(),gt.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&&(O(t.params.frameWorkType)||(this._frameWorkType=t.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),O(t.params.component)||(this._component=t.params.component,this._basicInfo.uint32_component=this._component),O(t.params.language)||(this._language=t.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleJoinScheduleSuccess({room:t,detailCost:e}){if(this.hitTest(t)&&e){let{totalCost:r,local:o,dns:s,tcp:n,tls:a,request:d,response:l}=e;this._pathJoinRoom.int32_schedule_cost=r,this._pathJoinRoom.int32_schedule_local=o,this._pathJoinRoom.int32_schedule_dns=s,this._pathJoinRoom.int32_schedule_tcp=n,this._pathJoinRoom.int32_schedule_tls=a,this._pathJoinRoom.int32_schedule_request=d,this._pathJoinRoom.int32_schedule_response=l}}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 se?Number(e.getExtraCode()||e.getCode()):q.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}handleJoinSendCMD(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now())}handleJoinReceivedCMDResponce(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=t.code,t.code!==0&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}handleJoinSuccess(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_end_time===0&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=t.room.getSignalInfo())}handleJoinFailed({room:t,error:e}){this.hitTest(t)&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret===0&&(this._pathJoinRoom.int32_end_ret=e.code||this._pathJoinRoom.int32_send_request_enter_room_cmd_ret||this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret),setTimeout(()=>{this.report()}))}handleReceivedPublishUserList(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_recv_userlist_time===0&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=t.publishedUserList||[])}handleSendFirstVideoFrame({room:t}){this.hitTest(t)&&this._pathJoinRoom.uint64_send_first_video_frame_time===0&&this._pathJoinRoom.uint64_start_time!==0&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now())}handleLeaveStart(t){this.hitTest(t.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(t){var e;if(this.hitTest(t.room)&&this._pathLeaveRoom.uint64_end_time===0){if(this._pathLeaveRoom.uint64_end_time=Date.now(),this._pathJoinRoom.uint64_end_time!==0){this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time;let r=(e=this._room.audioManager.localAudioTrack)==null?void 0:e.after3aSilenceStartTime;r&&(this._localStreamStat.statsToReport.uint32_after3a_silence_duration=Te()-r)}else this._log.warn("pathJoinRoom endTime is 0");this.report()}}handleLeaveSendCMD(t){this.hitTest(t.room)&&(this._pathLeaveRoom.uint64_send_request_exit_room_cmd_start_time=Date.now(),this._pathLeaveRoom.uint64_send_request_exit_room_cmd_end_time=Date.now())}handleSwitchRoomStart(t){if(this.hitTest(t.room)){let e=Date.now();this.report().then(()=>{this._pathJoinRoom.uint64_start_time=e,this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=e})}}handleSwitchRoomSuccess({room:t}){if(this.hitTest(t)&&this._pathJoinRoom.uint64_end_time===0){let e=Date.now();this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=e,this._pathJoinRoom.uint64_end_time=e,this._pathJoinRoom.int32_end_ret}}handleSwitchRoomFailed({room:t,error:e}){if(this.hitTest(t)){let r=Date.now();this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=r,this._pathJoinRoom.uint64_end_time=r,e&&(this._pathJoinRoom.int32_end_ret=e instanceof se?Number(e.getExtraCode()||e.getCode()):q.UNKNOWN)}}handleRemoteStreamAdded(t,e){var o;let r=`${t}_${e}`;if(!this._remoteStreamStatMap.has(r)){let s={userId:t,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:_e(Y({},KR),{msg_user_info:new Uc({userId:t,tinyId:(o=this._room.remotePublishedUserMap.get(t))==null?void 0:o.tinyId,role:20})})};s.statsToReport.uint32_stream_type=e==="main"?2:7,this._remoteStreamStatMap.set(r,s)}}handleSubscribeStart({room:t,remotePublishedUser:e,streamType:r,subscribeState:o}){if(!this.hitTest(t))return;let{userId:s,tinyId:n,role:a}=e,d=new Uc({userId:s,tinyId:n,role:a==="anchor"?20:21}),l=Date.now(),p=`${s}_${r}`,f=this._remoteStreamStatMap.get(p);f&&f.subscribeStartTime===0&&(f.subscribeStartTime=l),r==="main"?(e.muteState.hasVideo&&(o.video||o.smallVideo)&&!this._pathMainVideoMap.has(p)&&this._pathMainVideoMap.set(p,{statsToReport:{msg_user_info:d,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:s,sendSubscribeCMDTime:l}),e.muteState.hasAudio&&o.audio&&!this._pathMainAudioMap.has(p)&&this._pathMainAudioMap.set(p,{statsToReport:{msg_user_info:d,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:s,sendSubscribeCMDTime:l})):e.muteState.hasAuxiliary&&o.auxiliary&&!this._pathAuxiliaryMap.has(p)&&this._pathAuxiliaryMap.set(p,{sendSubscribeCMDTime:l})}handleSubscribed({room:t,remotePublishedUser:e,streamType:r}){if(this.hitTest(t)){let o=`${e.userId}_${r}`,s=this._remoteStreamStatMap.get(o);s&&s.subscribedTime===0&&(s.subscribedTime=Date.now())}}handlePlayStart({track:t}){if(!t.isRemote||!this.hitTest(t.room))return;let e=`${t.userId}_${t.streamType}`,r=this._remoteStreamStatMap.get(e);(r==null?void 0:r.playStreamTime)===0&&(r.playStreamTime=Date.now())}handleVideoLoadedData({track:t}){if(!t.isRemote||!this.hitTest(t.room))return;let e=`${t.userId}_${t.streamType}`,r=this._pathMainVideoMap.get(e);r&&r.statsToReport.uint64_combine_first_frame_time===0&&(r.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(t){let e=`${t.userId}_${t.streamType}`,r=Date.now(),o=this._pathMainVideoMap.get(e),s=this._remoteStreamStatMap.get(e);if(s){let{statsToReport:n}=s;if(!n.uint32_video_render_first&&t.streamType==="main"?this.hasVideoFlag(t.userId):this.hasAuxFlag(t.userId)){let a=r-this._pathJoinRoom.uint64_start_time;n.uint32_video_render_first=a,X.addNumber({key:516820,value:a})}}(o==null?void 0:o.statsToReport.uint64_render_first_frame_time)===0&&(o.statsToReport.uint64_render_first_frame_time=r)}handleAudioPlaying(t){let e=`${t.userId}_${t.streamType}`,r=this._pathMainAudioMap.get(e);r&&r.statsToReport.uint64_play_first_frame_time===0&&(r.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(t){this.hitTest(t.room)&&(this._networkQuality.totalUplinkLoss+=t.uplink.loss,this._networkQuality.totalUplinkRTT+=t.uplink.rtt,this._networkQuality.count++,t.downlinks.forEach(({rtt:e,loss:r,userId:o,videoDelay:s,audioDelay:n})=>{let a=this._networkQuality.totalDownlinkRTTAndLossMap.get(o);if(a)a.totalRTT+=e,a.totalLoss+=r,s&&(a.totalVideoDelay=(a.totalVideoDelay||0)+s,a.videoDelayCount=(a.videoDelayCount||0)+1),n&&(a.totalAudioDelay=(a.totalAudioDelay||0)+n,a.audioDelayCount=(a.audioDelayCount||0)+1),a.count++;else{let d,l,p,f;s&&(l=s,p=1),n&&(d=n,f=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(o,{totalRTT:e,totalLoss:r,count:1,totalAudioDelay:d,totalVideoDelay:l,audioDelayCount:f,videoDelayCount:p})}}))}handleHeartbeatStats(t){var e;if(this.hitTest(t.room)){let{msg_device_info:r,msg_up_stream_info:o,msg_down_stream_info:s}=t.report;if(o.msg_video_status[0]){let{uint32_video_codec_bitrate:n,uint32_video_enc_fps:a,uint32_video_width:d,uint32_video_height:l}=o.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=n,this._localStreamStat.totalVideoFPS+=a,this._localStreamStat.totalVideoWidth+=d,this._localStreamStat.totalVideoHeight+=l,this._localStreamStat.videoCount++}if(o.msg_audio_status){let{uint32_audio_level:n}=o.msg_audio_status;Math.floor(n/Fi*100)>0&&(this._localStreamStat.totalAudioLevel+=n/Fi,this._localStreamStat.audioLevelCount++)}s.forEach(n=>{let{msg_user_info:a,msg_audio_status:d,msg_video_status:l}=n,p=a.str_identifier,f=this._room.remotePublishedUserMap.get(p);if(l.forEach(g=>{let A=g.uint32_video_stream_type===2,R=g.uint32_video_stream_type===7,N=`${p}_${A?"main":"auxiliary"}`,C=this._remoteStreamStatMap.get(N);if(C&&(A&&(f!=null&&f.remoteVideoTrack.isSubscribed)||R&&(f!=null&&f.remoteAuxiliaryTrack))){C.totalVideoFPS+=g.uint32_video_receive_fps,C.totalVideoBitrate+=g.uint32_video_codec_bitrate,C.videoCount++,C.statsToReport.uint32_video_width===0&&(C.statsToReport.uint32_video_width=g.uint32_video_width),C.statsToReport.uint32_video_height===0&&(C.statsToReport.uint32_video_height=g.uint32_video_height);let P=A?f.remoteVideoTrack:f.remoteAuxiliaryTrack;P.stat.jitterBufferDelay&&(C.videoJitterBufferDelay=P.stat.jitterBufferDelay),P.stat.framesReceived&&(C.statsToReport.uint32_video_consume_render_rate=Math.floor(P.stat.framesDecoded/P.stat.framesReceived*ri(10,6)))}}),!un(d)){let g=`${p}_main`,A=this._remoteStreamStatMap.get(g);this._remoteStreamStatMap.has(g)&&A&&f!=null&&f.remoteAudioTrack.isSubscribed&&(A.totalAudioBitrate+=d.uint32_audio_codec_bitrate,A.audioCount++,f.remoteAudioTrack.stat.jitterBufferDelay&&(A.audioJitterBufferDelay=f.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(d.uint32_audio_level/Fi*100)>0&&(A.totalAudioLevel+=d.uint32_audio_level/Fi,A.audioLevelCount++),d.uint32_audio_block_time&&(A.statsToReport.uint32_audio_block_time+=d.uint32_audio_block_time))}}),r.uint32_audio_capture_cost&&(this._captureCostSum+=r.uint32_audio_capture_cost,this._captureCostCount+=1,this._captureCostCount>=100&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0)),r.uint32_audio_capture_cost===0&&((e=this._room.audioManager.localAudioTrack)==null?void 0:e.muted)===!1&&(this._localStreamStat.statsToReport.uint32_audio_capture_thread_health_zero_cnt+=1)}}handlePublishStart({room:t}){this.hitTest(t)&&this._localStreamStat.publishStartTime===0&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart({track:t}){t.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),t.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess({track:t}){t.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=0,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),t.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=0,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed({track:t,error:e}){let o={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[e.name]||(e instanceof se?e.getExtraCode()||e.getCode():q.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&tn)>=0}hasAudioFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&rn)>=0}hasAuxFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&fa)>=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:p,count:f,audioDelayCount:g,videoDelayCount:A,totalAudioDelay:R,totalVideoDelay:N}=o;t.statsToReport.uint32_avg_down_loss=Math.floor(p/f),g&&R&&(t.statsToReport.uint32_audio_network_p2p_delay=Math.floor(R/g),t.audioJitterBufferDelay&&(t.statsToReport.uint32_p2p_delay=Math.floor(t.statsToReport.uint32_audio_network_p2p_delay+t.audioJitterBufferDelay))),A&&N&&(t.statsToReport.uint32_video_network_p2p_delay=Math.floor(N/A))}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,M.AUDIO),t.statsToReport.uint32_video_play_time=s.getDuration(e,M.VIDEO)),t.statsToReport.uint32_video_render_first&&(t.statsToReport.uint32_video_render_first=Math.min(t.statsToReport.uint32_video_render_first,$s));let{badCaseDetector:n}=this._room,{dataFreeze:a,count:d}=n.getDataFreezeDuration(e),{renderFreeze:l}=n.getRenderFreezeDuration(e);t.statsToReport.uint32_video_block_count=d,t.statsToReport.uint32_video_block_time=Math.min(a,t.statsToReport.uint32_video_play_time),t.statsToReport.uint32_video_external_block_time=Math.min(l,t.statsToReport.uint32_video_play_time),t.statsToReport.uint32_audio_block_time=Math.min(t.statsToReport.uint32_audio_block_time,t.statsToReport.uint32_audio_play_time),n.isBlackStream(e)&&t.statsToReport.uint32_video_avg_fps===0?t.statsToReport.uint32_video_black_screen_subjective=1:t.statsToReport.uint32_video_black_screen_subjective=0}),this._pathMainAudioMap.forEach((t,e)=>{if(!this.hasAudioFlag(t.userId)){this._pathMainAudioMap.delete(e);return}t.statsToReport.uint64_play_first_frame_time-t.statsToReport.uint64_start_enter_time>$s&&(t.statsToReport.uint64_play_first_frame_time=t.statsToReport.uint64_start_enter_time+$s)}),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>$s&&(t.statsToReport.uint64_render_first_frame_time=t.statsToReport.uint64_start_enter_time+$s)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>$s&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+$s)}getReportData(){this._basicInfo.uint32_networkType=Rd();let t={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new Uc({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:ln(this._signalInfo.relayIp),uint32_client_ip:ln(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*ri(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:ln(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,bytes_report_buf_from_0x1:this._signalInfo.endReportExtend,str_user_sig:this._room.userSig,bytes_report_token:this._signalInfo.reportToken};return Aa(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=Io.enable?Di(t,2001,e):yield vm(t),o=r instanceof ArrayBuffer,s=`${Ni(e,po.KEY_POINT)}&gzip=${+o}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(s,r));let a=[this.uploadKVStat(X),this.uploadKVStat(Ts)];n||a.push(wi({url:s,body:r,priority:"low"})),yield Promise.all(a)})}setConnectionType(t){this.connectionType=t,this._basicInfo.uint32_connection_type=t}uploadKVStat(t){return y(this,null,function*(){let e=t.getReportData(this._room.userSig,this._signalInfo.reportToken);if(e.stats_count.length===0&&e.stats_distribution.length===0)return;e.msg_sdk_basic_info=_e(Y({},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=Io.enable?Di(e,2003,this._room.sdkAppId):yield vm(e),o=r instanceof ArrayBuffer,s=`${Ni(+this._room.sdkAppId,po.KV_STAT)}&gzip=${+o}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(s,r)),n||wi({url:s,body:r})})}};Z([As({settings:{timeout:500,retries:3}})],Ol.prototype,"upload",1);var $s=5e3,KR={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},Uc=class{constructor(t){m(this,"str_identifier");m(this,"str_tinyid");m(this,"uint32_role");this.str_identifier=String(t.userId),this.str_tinyid=String(t.tinyId||0),this.uint32_role=t.role}},DT=Ol;var _f=class{constructor(){m(this,"_startTime");m(this,"_endTime");this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=Te())}stop(){this._endTime===0&&(this._endTime=Te())}getDuration(){return this._endTime===0?Te()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},Ml=_f;var Tf=class{constructor(t){m(this,"_room",null);m(this,"_durationMap");m(this,"_eventMap",new Map);this._room=t.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(B.REMOTE_TRACK_SUBSCRIBED,this.handleSubscribed).set(B.REMOTE_TRACK_UNSUBSCRIBED,this.handleUnsubscribed).set(B.REMOTE_PUBLISH_STATE_CHANGED,({room:t,prevMuteState:e,muteState:r})=>{var n;let{userId:o}=r;if(!this.hitTest(t))return;e.hasAudio&&!r.hasAudio&&this.stopDurationItem(`${o}_main`,M.AUDIO),e.hasVideo&&!r.hasVideo&&this.stopDurationItem(`${o}_main`,M.VIDEO),e.hasAuxiliary&&!r.hasAuxiliary&&this.stopDurationItem(`${o}_auxiliary`,M.VIDEO);let s=(n=this._room)==null?void 0:n.remotePublishedUserMap.get(o);s&&(!e.hasAudio&&r.hasAudio&&s.remoteAudioTrack.isSubscribed&&this.addDuractionItem(o,M.AUDIO,"main"),!e.hasVideo&&r.hasVideo&&s.remoteVideoTrack.isSubscribed&&this.addDuractionItem(o,M.VIDEO,"main"),!e.hasAuxiliary&&r.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(o,M.VIDEO,"auxiliary"))}),this._eventMap.forEach((t,e)=>U.on(e,t,this))}uninstallEvents(){this._eventMap.forEach((t,e)=>U.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 Ml,n=this._durationMap.get(o);n?this.isRecording(n[e])||n[e].push(s):this._durationMap.set(o,{userId:t,type:r,audio:e===M.AUDIO?[s]:[],video:e===M.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()}},wT=Tf;var If=class{constructor(){m(this,"renderFreezeMap",new Map);m(this,"dataFreezeMap",new Map)}get(t,e){let r=this.renderFreezeMap.get(t),o=this.dataFreezeMap.get(t);return e?e==="data"?o:r:(ct||ot)&&r&&o&&r.duration>o.duration?r:o}set(t,e,r){r==="data"?this.dataFreezeMap.set(t,e):this.renderFreezeMap.set(t,e)}clear(){this.renderFreezeMap.clear(),this.dataFreezeMap.clear()}},Sf=class{constructor(t){m(this,"_room");m(this,"_renderFreezeMap",new Map);m(this,"_isVideoPlayingEventFiredMap",new Map);m(this,"_dataFreezeMap",new Map);m(this,"_monitorFreezeData",new If);m(this,"_eventMap",new Map);m(this,"_videoEncodeFailedCount",0);m(this,"_audioEncodeFailedCount",0);m(this,"_encodeFailedThreshold",3);m(this,"eventListenerMap",new Map);this._room=t.room,this.installEvents()}getRenderFreezeMap(){return this._renderFreezeMap}getDataFreezeMap(){return this._dataFreezeMap}installEvents(){this._eventMap.set(B.LEAVE_SUCCESS,({room:t})=>{this.hitTest(t)&&this.stop()}).set(B.PLAY_TRACK_START,this.onPlayTrackStart).set(B.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(B.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(B.PLAYER_STATE_CHANGED,({track:t,state:e,reason:r,type:o})=>{if(!(!t.isRemote||!t.room||!this.hitTest(t.room)||o!==M.VIDEO)){if(e==="PLAYING"){let s=`${t.userId}_${t.streamType}`;this._isVideoPlayingEventFiredMap.set(s,!0)}r===M.MUTE?this.onVideoTrackMuted(t):r===M.UNMUTE&&this.onVideoTrackUnmuted(t)}}).set(B.HEARTBEAT_REPORT,this.onHearBeatReport).set(B.REMOTE_VIDEO_PLAY_START,this.onRemoteVideoPlayStart).set(B.REMOTE_VIDEO_PLAY_FINISH,this.onRemoteVideoPlayEnd),this._eventMap.forEach((t,e)=>U.on(e,t,this))}uninstallEvents(){this._eventMap.forEach((t,e)=>U.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 Ml;s?s.durationItemList.push(n):this._dataFreezeMap.set(o,{userId:e,type:r,durationItemList:[n],isFreezing(){let a=this.durationItemList[this.durationItemList.length-1];return a&&a.endTime===0}})}onVideoTrackUnmuted(t){if(!t.isSubscribed)return;let{userId:e,streamType:r}=t,o=`${e}_${r}`;this.stopDataFreeze({key:o,userId:e,type:r})}onHearBeatReport({room:t,report:e}){if(this.hitTest(t)){if(e.msg_up_stream_info.msg_video_status){let r=e.msg_up_stream_info.msg_video_status,o=Array.from(this._room.localTracks).find(n=>n.kind==="video"&&!n.isScreen),s=(o==null?void 0:o.stat.bytesSent)||0;if((o==null?void 0:o.isMediaTrackActive)===!1||s<=0||o!=null&&o.isUseCustomSource)return;r.forEach(n=>{n.uint32_video_stream_type===2&&(n.uint32_video_capture_fps!==0&&n.uint32_video_codec_bitrate===0&&n.uint32_video_enc_fps===0&&(o!=null&&o.isPublished)?(this._videoEncodeFailedCount+=1,this._videoEncodeFailedCount===this._encodeFailedThreshold&&qe.uploadEvent({userId:this._room.userId,log:`stat-${yr.VIDEO_ENCODE_FAILED_DURING_CALL}`})):this._videoEncodeFailedCount=0)})}if(e.msg_up_stream_info.msg_audio_status){let r=e.msg_up_stream_info.msg_audio_status,o=Array.from(this._room.localTracks).find(n=>n.kind==="audio"),s=(o==null?void 0:o.stat.bytesSent)||0;if((o==null?void 0:o.isMediaTrackActive)===!1||s<=0)return;r.uint32_audio_codec_bitrate===0&&(o!=null&&o.isPublished)?(this._audioEncodeFailedCount+=1,this._audioEncodeFailedCount===this._encodeFailedThreshold&&qe.uploadEvent({userId:this._room.userId,log:`stat-${yr.AUDIO_ENCODE_FAILED_DURING_CALL}`})):this._audioEncodeFailedCount=0}}}stopDataFreeze({key:t,userId:e,type:r}){let o=this._dataFreezeMap.get(t);if(!o||!o.isFreezing())return;let s=o.durationItemList[o.durationItemList.length-1];s.stop();let n=s.getDuration();if(n>Td){let a=this._monitorFreezeData.get(t,"data");this._monitorFreezeData.set(t,{userId:e,type:r,duration:a?a.duration+n:n},"data")}else o.durationItemList.pop()}getTotalDuration(t){return t.reduce((e,r)=>{let o=r.getDuration();return e+Math.min(o,5e3)},0)}onPlayTrackStart({track:t}){if(!t.isRemote||!this.hitTest(t.room)||t.kind!==M.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()<Td&&r.durationItemList.pop()}e.dataFreeze=this.getTotalDuration(r.durationItemList),e.count=r.durationItemList.length}return e}getRenderFreezeDuration(t){let e={renderFreeze:0,count:0},r=this._renderFreezeMap.get(t);return r&&(e.renderFreeze=r.totalDuration,e.count=r.count),e}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(t){return this._isVideoPlayingEventFiredMap.has(t)?!this._isVideoPlayingEventFiredMap.get(t):!1}onRemoteVideoPlayStart({track:t,player:e}){var n;if(!zr())return;let r=0,o=()=>{document.hidden||(r=0)};document.addEventListener("visibilitychange",o);let s=(a,d)=>{var l;if(r){let p=t.decodeFPS,f=p>0&&p<=5?600+1e3/p:600,g=d.presentationTime-r;if(g>f){g=Math.min(g,5e3);let A=`${t.userId}_${t.streamType}`,R=this._monitorFreezeData.get(A,"render");R?R.duration+=g:this._monitorFreezeData.set(A,{userId:t.userId,type:t.streamType,duration:g},"render");let N=this._renderFreezeMap.get(A);N?(N.totalDuration+=g,N.count+=1):this._renderFreezeMap.set(A,{userId:t.userId,type:t.streamType,totalDuration:g,count:1})}}r=d.presentationTime,(l=e.element)==null||l.requestVideoFrameCallback(s)};(n=e.element)==null||n.requestVideoFrameCallback(s),this.eventListenerMap.set(`${t.userId}_${t.streamType}`,{onVisibilityChange:o})}onRemoteVideoPlayEnd({track:t,player:e}){let r=`${t.userId}_${t.streamType}`,o=this.eventListenerMap.get(r);o&&document.removeEventListener("visibilitychange",o.onVisibilityChange)}resetMonitor(){this._monitorFreezeData.clear()}hitTest(t){return t===this._room}destroy(){this.uninstallEvents()}},OT=Sf;var PT=bi(ki(),1);var xl=class{constructor(t,e,r,o,s,n=4/3){this.vbMode=t;this.faceDetectorHash=r;this.visionTaskRegistry=o;this.logger=s;m(this,"animationState");m(this,"originalAspect");m(this,"totalOffsetX",0);m(this,"totalOffsetY",0);m(this,"defaultScaleRatio",.1);m(this,"isRecovering",!1);m(this,"boundaryY",280);m(this,"lastActionTime",0);m(this,"restTime",400);this.animationState={current:null,target:null,animating:!1,debounceTimer:null,startTime:0,duration:3e3,debounceTime:150,movementThreshold:30,debounceThreshold:15},this.addEvent(this.vbMode,!!this.faceDetectorHash),this.originalAspect=n||4/3,this.visionTaskRegistry.setVideo(this.faceDetectorHash,e)}addEvent(t,e,r){let s=[{key:570704,error:r!=null?r:e?void 0:11},{key:570705,error:r!=null?r:e?void 0:22}][t-1];s&&(e?X.addSuccessEvent({key:s.key}):X.addFailedEvent({key:s.key,error:s.error}))}actionCentering(t){let e=Date.now();if(this.animation(),!this.faceDetectorHash||e-this.lastActionTime<this.restTime||this.animationState.animating)return;let{videoWidth:r,videoHeight:o}=t;this.animationState.debounceThreshold=r/30,this.animationState.movementThreshold=r/20,this.boundaryY=o*.6;try{let s=this.visionTaskRegistry.getResult(this.faceDetectorHash);if(s.detections.length<=0){this.vbMode===1&&this.recoverOriginal(r,o);return}let n=s.detections[0].boundingBox,a=n.originX,d=n.originY,l=n.width,p=n.height;this.vbMode===1?this.dualStageCropping(r,o,a,d,l,p):this.vbMode===2&&this.movingPortrait(r,o,a,d,l,p)}catch(s){this.logger.error(s)}this.lastActionTime=e}calculateBoundary(t,e,r,o){let s,n;return t>e/2?(s=e-r-o,n=r-s):(s=r,n=0),{min:s,offset:n}}calculateTargetPosition(t,e,r,o,s,n,a=.4){let d=t+r/2,l=e+o/2,p,f,{min:g,offset:A}=this.calculateBoundary(d,s,t,r),{min:R,offset:N}=this.calculateBoundary(l,n,e,o);return p=2*g+r,f=2*R+o,p/f>this.originalAspect?(p=f*this.originalAspect,A=d-p/2):(f=p/this.originalAspect,N=l-f/2),r/s>a&&(A=0,N=0,p=s,f=n),A=Math.max(0,Math.min(A,s-p)),N=Math.max(0,Math.min(N,n-f)),{sx:A,sy:N,cropWidth:p,cropHeight:f,timestamp:Date.now()}}processFacePositionCrop(t,e,r){if(!this.animationState.current||!this.animationState.target){let a={sx:0,sy:0,cropWidth:e,cropHeight:r,timestamp:Date.now()};this.animationState.current=a,this.animationState.target=a;return}let o=this.positionDistance(this.animationState.target,t),s=this.positionDistance(this.animationState.current,t),n=this.animationState.current.cropWidth/e;o>this.animationState.debounceThreshold*n&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&s>this.animationState.movementThreshold*n&&(this.animationState.target=t,this.animationState.debounceTimer=setTimeout(()=>{this.animationState.startTime=Date.now(),this.animationState.animating=!0},this.animationState.debounceTime))}processFacePositionPortrait(t){if(!this.animationState.current||!this.animationState.target){this.animationState.current=Y({},t),this.animationState.target=Y({},t);return}let e=this.positionDistance(this.animationState.current,t),r=this.positionDistance(this.animationState.target,t);e>this.animationState.debounceThreshold&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&r>this.animationState.movementThreshold&&(this.animationState.current=t,this.animationState.debounceTimer=setTimeout(()=>{this.animationState.startTime=Date.now(),this.animationState.animating=!0},this.animationState.debounceTime))}animation(){if(!this.animationState.animating)return;let t=Date.now()-this.animationState.startTime,e=Math.min(t/this.animationState.duration,1),r=o=>o<.5?2*o*o:-1+(4-2*o)*o;if(this.animationState.current&&this.animationState.target){let o=(this.animationState.target.sx-this.animationState.current.sx)*r(e);this.animationState.current.sx+=o,this.totalOffsetX+=o;let s=(this.animationState.target.sy-this.animationState.current.sy)*r(e);if(this.animationState.current.sy+=s,this.totalOffsetY+=s,this.animationState.current.cropWidth+=(this.animationState.target.cropWidth-this.animationState.current.cropWidth)*r(e),this.animationState.current.cropHeight+=(this.animationState.target.cropHeight-this.animationState.current.cropHeight)*r(e),this.animationState.current.scaleRatio&&this.animationState.target.scaleRatio&&(this.animationState.current.scaleRatio+=(this.animationState.target.scaleRatio-this.animationState.current.scaleRatio)*r(e)),Fe(this.animationState.current.scaleOffsetX)&&Fe(this.animationState.target.scaleOffsetX)&&Fe(this.animationState.current.scaleOffsetY)&&Fe(this.animationState.target.scaleOffsetY)){let n=(this.animationState.target.scaleOffsetX-this.animationState.current.scaleOffsetX)*r(e);this.animationState.current.scaleOffsetX+=n;let a=(this.animationState.target.scaleOffsetY-this.animationState.current.scaleOffsetY)*r(e);this.animationState.current.scaleOffsetY+=a}}e>=1&&(this.animationState.animating=!1,this.animationState.current=this.animationState.target,this.isRecovering=!1)}positionDistance(t,e){return Math.sqrt(ri(t.sx-e.sx,2)+ri(t.sy-e.sy,2))}recoverOriginal(t,e){this.animationState.target={sx:0,sy:0,cropWidth:t,cropHeight:e,timestamp:Date.now()},this.animationState.animating=!0,this.animationState.startTime=Date.now(),this.isRecovering=!0}dualStageCropping(t,e,r,o,s,n,a=.3){if(this.isRecovering)return;let d=this.calculateTargetPosition(r,o,s,n,t,e);this.processFacePositionCrop(d,t,e),s*n/d.cropWidth/d.cropHeight>a&&this.recoverOriginal(t,e)}movingPortrait(t,e,r,o,s,n){var d,l,p,f,g,A,R,N,C,P,z,H;let a={sx:r+s/2+this.totalOffsetX,sy:o+n/2+this.totalOffsetY,cropWidth:t,cropHeight:e,scaleRatio:(l=(d=this.animationState.current)==null?void 0:d.scaleRatio)!=null?l:1,scaleOffsetX:(f=(p=this.animationState.current)==null?void 0:p.scaleOffsetX)!=null?f:0,scaleOffsetY:(A=(g=this.animationState.current)==null?void 0:g.scaleOffsetY)!=null?A:0,timestamp:Date.now()};this.animationState.target={sx:t/2,sy:o+n/2,cropWidth:t,cropHeight:e,scaleRatio:(N=(R=this.animationState.target)==null?void 0:R.scaleRatio)!=null?N:1,scaleOffsetX:(P=(C=this.animationState.target)==null?void 0:C.scaleOffsetX)!=null?P:0,scaleOffsetY:(H=(z=this.animationState.target)==null?void 0:z.scaleOffsetY)!=null?H:0,timestamp:Date.now()},this.animationState.animating||(this.animationState.target.scaleRatio=Math.sqrt(s*n/t/e/this.defaultScaleRatio),this.animationState.target.scaleOffsetX=-this.animationState.target.scaleRatio/2+.5,this.animationState.target.scaleOffsetY=-this.animationState.target.scaleRatio+1,(this.animationState.target.sy-this.animationState.target.scaleOffsetY*this.animationState.target.cropHeight)/this.animationState.target.scaleRatio<this.boundaryY&&(this.animationState.target.scaleOffsetY=(this.animationState.target.sy-this.boundaryY*this.animationState.target.scaleRatio)/this.animationState.target.cropHeight)),this.processFacePositionPortrait(a)}set aspectRatio(t){this.originalAspect=t}get current(){return this.animationState.current}get offset(){return{offsetX:this.totalOffsetX,offsetY:this.totalOffsetY}}get targetCrop(){return this.animationState.target}};var ev=`#version 300 es
99
+ ${o.stack}`),!1}},i};var Jn=new WeakMap;function hT(i){let t=Jn.get(i);t&&(t.forEach(e=>clearTimeout(e)),Jn.delete(i))}function pT(i,t){return Pe((e,r)=>function(...o){let s=Jn.get(this);s||(s=new Map,Jn.set(this,s));let n=t(...o),a=s.get(n);if(!a||a<=0){e.apply(this,o);let d=setTimeout(()=>{var l;(l=Jn.get(this))==null||l.delete(n)},i);s.set(n,d)}else{clearTimeout(a);let d=window.setTimeout(()=>{var l;e.apply(this,o),(l=Jn.get(this))==null||l.delete(n)},i);s.set(n,d)}})}var gT="trtc-sdk-v5",sf="5.14.2-wasm.4";function $t(...i){return Pe((t,e)=>function(...r){try{El.call(this,i,r,e,this._name)}catch(o){return Promise.reject(o)}return t.apply(this,r)})}function nf(...i){return Pe((t,e)=>function(...r){try{El.call(this,i,r,e,this._name)}catch(o){throw o}return t.apply(this,r)})}function El(i,t,e,r){if(mt(i))for(let o=0;o<i.length;o++)gl.call(this,{rule:i[o],value:t[o],key:i[o].name,fnName:e,className:r});else gl.call(this,{rule:i,value:t[0],key:i.name,fnName:e,className:r})}function gl({rule:i,value:t,key:e,fnName:r,className:o}){function s(d){return{code:ne.INVALID_PARAMETER,extraCode:d,fnName:r,messageParams:{key:e,rule:i,value:t}}}if(O(t)){if(i.required)throw new oe(s(5001));if(O(i.defaultValue)){Xe(i.validate)&&i.validate.call(this,t,e,r,o,this);return}t=i.defaultValue}if(Array.isArray(i.type)){let d=!1;for(let l=0;l<i.type.length;l++)i.type[l]===null&&t===null&&(d=!0),Xe(i.type[l])&&t instanceof i.type[l]&&(d=!0),Oe(i.type[l])&&ft(t)===i.type[l].toLowerCase()&&(d=!0);if(!d)throw new oe({code:ne.INVALID_PARAMETER,extraCode:5002,fnName:r,messageParams:{key:e,rule:{type:i.type.map(l=>as(l)?dn(l):Oe(l)?l:ft(l))},value:t}})}else if(!O(i.type)&&ft(t)!==i.type)throw new oe(s(5002));if(i.allowEmpty===!1){let d=Fe(t)&&(t===0||Number.isNaN(t)),l=Oe(t)&&t.trim()==="";if(d||l)throw new oe(s(5003))}if(i.notLessThanZero&&Fe(t)&&t<0)throw new oe(s(5006));if(!O(i.min)&&Fe(t)&&t<i.min)throw new oe(s(5007));if(!O(i.max)&&Fe(t)&&t>i.max)throw new oe(s(5008));if(Oe(i.instanceOf)){if(!t||t._name!==i.instanceOf)throw new oe(s(5004))}else if(Xe(i.instanceOf)&&!(t instanceof i.instanceOf))throw new oe(s(5004));if(Array.isArray(i.values)&&!i.values.includes(t))throw new oe(s(5005));let{properties:n}=i;Jt(n)&&pr(t)&&Object.keys(n).forEach(d=>{gl.call(this,{rule:n[d],value:t&&t[d],key:`${d}`,fnName:r,className:o})});let{arrayItem:a}=i;Jt(a)&&mt(t)&&t.forEach((d,l)=>{gl.call(this,{rule:a,value:d,key:`${e}[${l}]`,fnName:r,className:o})}),Xe(i.validate)&&i.validate.call(this,t,e,r,o,this)}function nt(i={}){let{getRemoteId:t=()=>"",replaceArg:e,getKVReportKey:r,ignoreLog:o,ignoreErrorLog:s}=i;return Pe((n,a)=>function(...d){var A,R,N;function l(C,P,z){if(z&&z.includes(C))return"hided";if(e){let H=e(...d);if(d[H.argIndex]===P)return H.value}if(P===d||C in d)return P;try{return P instanceof HTMLElement?`id: ${P.id} type:${ft(P)}`:P instanceof MediaStreamTrack?Dd(P):(JSON.stringify(P),P)}catch(H){return`type:${ft(P)}`}}let p=this._log||F;if(o!=null&&o(...d))return n.apply(this,d);d.length>0?p.info(`${a}() ${JSON.stringify(d,(C,P)=>l(C,P,["userSig","privateMapKey"]))}`):p.info(`${a}()`);let f=r?r(...d):uu[a],g=(s==null?void 0:s(...d))||!1;try{let C=n.apply(this,d),P=Te();if(fo(C)){let z=`${a.includes("Plugin")?`${((R=(A=d[0]).getName)==null?void 0:R.call(A))||""} `:" "}`;return C.then(H=>(p.info(`${a}() success ${z}${t.call(this,...d)}`),X.addSuccessEvent({key:f,cost:Te()-P}),H)).catch(H=>{var W;H=oe.convertFrom.call(this,H,a,d.length===1?d[0]:d);let ge=H.extraCode||H.code,Ue=(W=H.message)!=null&&W.includes(ge)?"":` code:${ge}`;throw g||p.error(`${a}() failed ${z}${t.call(this,...d)} ${H}${Ue} params: ${JSON.stringify(d,l)}`),X.addFailedEvent({key:f,error:H}),H})}return X.addSuccessEvent({key:f}),C}catch(C){C=oe.convertFrom.call(this,C,a);let P=C.extraCode||C.code,z=(N=C.message)!=null&&N.includes(P)?"":` code:${P}`;throw g||p.error(`${a}() failed ${C}${z} params: ${JSON.stringify(d,l)}`),X.addFailedEvent({key:f,error:C}),C}})}var _l=i=>Pe((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 oe({code:ne.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 oe({code:ne.ENV_NOT_SUPPORTED,message:`plugin ${String(r)} is not supported`,extraCode:5210,fnName:e});return El.call(this,s.getValidateRule(i),[o],e,"TRTC"),t.call(this,s,o)})});var Tl=0,af,Yi=class Yi{constructor(t){this.core=t;m(this,"log");m(this,"customAudioReferenceMap",new Map);m(this,"audioRefId",0);m(this,"audioContext",ze());m(this,"localAudioWorkletNode");m(this,"screenAudioWorkletNode");m(this,"mixNode");m(this,"silentNode");Tl=Tl+1,this.log=t.log.createChild({id:`${this.getAlias()}${Tl}`}),this.log.info(`created id=${this.getAlias()}${Tl}`),this.installEvent()}static getStartValidateRule(t){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,r,o,s){if(!t.room.audioManager.hasAudioTrack&&!t.room.audioManager.hasScreenAudioTrack)throw new oe({code:ne.INVALID_OPERATION,extraCode:5106,fnName:o})}}}preload(t){return af||(af=this.doPreload(t)),af}doPreload(t){return y(this,null,function*(){let e=yield this.core.fileDownloader.download(t,{type:"blob"}),r=URL.createObjectURL(e);try{yield Gi(this.audioContext,r)}catch(o){this.log.error(`preload audioProcessor failed. ${o}`)}finally{URL.revokeObjectURL(r)}})}getName(){return Yi.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(t){switch(t){case"start":return Yi.getStartValidateRule(this.core);case"update":return Yi.updateValidateRule;case"stop":return Yi.stopValidateRule}}start(t){return y(this,null,function*(){var g,A,R,N;let{room:e}=this.core,{sdkAppId:r,userId:o,userSig:s,assetsPath:n=this.core.assetsPath,audioReference:a,processLevel:d,enableDump:l,isLocalAudioNeedAudioProcess:p=!0,isScreenAudioNeedAudioProcess:f=!1}=t;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=p,this.core.room.audioManager.isScreenAudioNeedAudioProcess=f,!n)throw new oe({code:ne.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload(`${n}/audioProcessor-wasm.js`),p&&!this.localAudioWorkletNode){let{sign:C,status:P,timestamp:z}=yield this.getAuthData(r,o,s);this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",r,o,z,C,P,e)}if(f&&!this.screenAudioWorkletNode){let{sign:C,status:P,timestamp:z}=yield this.getAuthData(r,o,s);this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",r,o,z,C,P,e)}this.mixNode||(this.mixNode=this.audioContext.createGain(),this.mixNode.gain.value=1),this.silentNode||(this.silentNode=this.audioContext.createConstantSource(),this.silentNode.offset.setValueAtTime(0,this.audioContext.currentTime),this.silentNode.start()),(g=this.localAudioWorkletNode)==null||g.port.postMessage({type:"enable"}),(A=this.screenAudioWorkletNode)==null||A.port.postMessage({type:"enable"}),e.audioManager.addAudioProcessor(this.mixNode,this.silentNode,this.localAudioWorkletNode,this.screenAudioWorkletNode),O(a)||a.forEach(C=>{this.customAudioReferenceMap.set(C,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:C,refId:`o-${this.audioRefId++}`})}),O(d)||(R=this.localAudioWorkletNode)==null||R.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:d}}),O(l)||(N=this.localAudioWorkletNode)==null||N.port.postMessage({type:"dump",data:{enable:l}})})}update(t){return y(this,null,function*(){var s,n,a;let{audioReference:e,enableDump:r,processLevel:o}=t;O(e)||(this.customAudioReferenceMap.forEach((d,l)=>{this.customAudioReferenceMap.delete(l),this.core.room.audioManager.updateAudioReference({type:"remove",refId:d})}),e.forEach(d=>{this.customAudioReferenceMap.set(d,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:d,refId:`o-${this.audioRefId++}`})})),O(o)||(s=this.localAudioWorkletNode)==null||s.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:o}}),O(r)||((n=this.localAudioWorkletNode)==null||n.port.postMessage({type:"dump",data:{enable:r}}),(a=this.screenAudioWorkletNode)==null||a.port.postMessage({type:"dump",data:{enable:r}}))})}stop(){return y(this,null,function*(){var e,r;let{room:t}=this.core;(e=this.localAudioWorkletNode)==null||e.port.postMessage({type:"disable"}),(r=this.screenAudioWorkletNode)==null||r.port.postMessage({type:"disable"}),yield t.audioManager.removeAudioProcessor(this.localAudioWorkletNode,this.screenAudioWorkletNode)})}destroy(){this.localAudioWorkletNode&&(this.localAudioWorkletNode.port.onmessage=null),this.screenAudioWorkletNode&&(this.screenAudioWorkletNode.port.onmessage=null),this.uninstallEvent()}getAuthData(t,e,r){return y(this,null,function*(){let o=String(Date.now()).slice(0,-3),{auth:s,sign:n,status:a,message:d}=yield $R({sdkAppId:t,userSig:r,userId:e,timestamp:o});if(!s)throw this.log.info(`audioProcessor: ${e} auth result: ${s}. Message: ${d}`),new oe({code:ne.INVALID_PARAMETER,message:d});return{sign:n,status:a,timestamp:o}})}initWorkletNode(t,e,r,o,s,n,a,d){t.port.postMessage({type:"init",data:{sdkAppId:String(r),userId:o,timestamp:s,sign:n,status:a}}),t.port.onmessage=l=>{var f;let{data:p}=l;switch(p.type){case"cost":let g=(p==null?void 0:p.value)>10?"info":"debug";this.log[g](`${e==="localAudio"?"":`[${e}] `}avg cost: ${p.value} max: ${p==null?void 0:p.max}(${Ks(new Date(p==null?void 0:p.maxCostTimestamp))}) hist: ${(f=p==null?void 0:p.hist)==null?void 0:f.join(" ")}`);return;case"log":this.log[p.logLevel](`${e==="localAudio"?"":`[${e}] `}${p.value}`);return;case"dump":U.emit("265",{room:d,data:p.value,type:e==="localAudio"?"dump":"dump-screen-audio"});return}}}handleLocalAudioStarted(t){return y(this,null,function*(){var e;if(!(!this.hitTest(t.room)||((e=this.core.room.scheduleResult.config)==null?void 0:e.audioProcessor)!==!0))try{yield this.core.trtc.startPlugin("AudioProcessor",{sdkAppId:this.core.room.sdkAppId,userId:this.core.room.userId,userSig:this.core.room.userSig}),this.log.warn("audio processor auto start success")}catch(r){this.log.warn(`audio processor auto start failed, error: ${r}`)}})}handleLocalAudioStopped(t){return y(this,null,function*(){var e;!this.hitTest(t.room)||((e=this.core.room.scheduleResult.config)==null?void 0:e.audioProcessor)!==!0||(yield this.core.trtc.stopPlugin("AudioProcessor"))})}installEvent(){this.core.innerEmitter.on("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.on("114",this.handleLocalAudioStopped,this)}uninstallEvent(){this.core.innerEmitter.off("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.off("114",this.handleLocalAudioStopped,this)}hitTest(t){return t===this.core.room}};m(Yi,"updateValidateRule",{type:"object"}),m(Yi,"stopValidateRule",{type:"object"}),m(Yi,"Name","AudioProcessor");var Il=Yi;function BR(i,t=M.MAIN){return`https://${gi[t]||fl(i,t)}/api/v1/audioAiAuth`}function $R(o){return y(this,arguments,function*({sdkAppId:i,userId:t,userSig:e,timestamp:r}){let n=`${BR(i)}?sdkAppId=${i}&userId=${t}&userSig=${e}&timestamp=${r}`,a=yield fetch(n),{data:{errCode:d,errMsg:l,sign:p,status:f}}=yield a.json();if(f==="1")return{auth:!0,sign:p,status:f,message:l};let g=Rr(i)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",A="Init RTCAudioProcessor failed.",R="";switch(d){case 1:R="Please check your params.";break;case 2:R=`You need to buy packages. Refer to: ${g}`;break;case 3:R="Server is invalid. Please contact our engineer. ";break;case 4:R=`Your packages is not active. Refer to: ${g}`;break;case 5:R=`Your packages is expired. Refer to: ${g}`;break;case 6:R="Your version is not supported.";break}return{auth:!1,status:f,message:l?`${A} Reason: ${l}. ${R}`:`${A}, ${R}`}})}var Sl=0,cf=class{constructor(t,e){m(this,"audioObjectURL");m(this,"player");m(this,"publisher");m(this,"mixInput");this.mixInput=new On(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&&(O(t.volume)||(this.volume=t.volume),O(t.loop)||(this.loop=t.loop),O(t.playbackRate)||(this.playbackRate=t.playbackRate))}updateListener(t){if(this.player){if(t.onDurationChange){let{onDurationChange:e}=t;this.player.ondurationchange=r=>{e(r.target.duration)}}if(t.onTimeUpdate){let e=t.onTimeUpdate,{player:r}=this;r.ontimeupdate=()=>{e(r.currentTime,r.duration)}}t.onEnded&&(this.player.onended=t.onEnded)}}reload(t){return y(this,null,function*(){if(t.url){let e=yield wc.download(t.url,{retries:3,type:"blob"});this.audioObjectURL&&URL.revokeObjectURL(this.audioObjectURL),this.audioObjectURL=URL.createObjectURL(e),this.player&&this.publisher?(this.player.src=this.audioObjectURL,this.publisher.src=this.audioObjectURL):(this.player=new Audio(this.audioObjectURL),this.player.crossOrigin="anonymous",this.publisher=new Audio(this.audioObjectURL),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher),this.updateListener(t),this.updateSettings(t))}else this.mixInput.replaceSource(t.track)})}reset(){this.seek(0),this.mixInput.connect()}seek(t){this.player&&(t<0&&t>this.player.duration||(this.player.currentTime=t,this.publisher.currentTime=t))}play(){var t,e;return Promise.all([(t=this.player)==null?void 0:t.play(),(e=this.publisher)==null?void 0:e.play()])}pause(){var t,e;(t=this.player)==null||t.pause(),(e=this.publisher)==null||e.pause()}stop(){var t;(t=this.player)==null||t.pause(),this.mixInput.disconnect()}setOperation(t){t==="pause"&&this.pause(),t==="resume"&&(this.pause(),this.play()),t==="stop"&&(this.pause(),this.seek(0))}set volume(t){!this.player||!this.publisher||(this.player.volume=t,this.publisher.volume=t)}set loop(t){!this.player||!this.publisher||(this.player.loop=t,this.publisher.loop=t)}set playbackRate(t){!this.player||!this.publisher||(this.player.playbackRate=t,this.publisher.playbackRate=t)}};function Xn(i,t){if(t&&typeof t!="function")throw new oe({code:ne.INVALID_PARAMETER,message:`start audioMixer plugin: param ${i} should be a function.`})}var Ei=class Ei{constructor(t){this.core=t;m(this,"log");m(this,"mixedMusicMap",new Map);m(this,"cacheMusicMap",new Map);Sl=Sl+1,this.log=t.log.createChild({id:`${this.getAlias()}${Sl}`}),this.log.info(`created id=${this.getAlias()}${Sl}`)}getName(){return Ei.Name}getAlias(){return"ax"}getGroup(t){return t==null?void 0:t.id}getValidateRule(t){switch(t){case"start":return Ei.startValidateRule;case"update":return Ei.updateValidateRule;case"stop":return Ei.stopValidateRule}}start(t){return y(this,null,function*(){let{room:e}=this.core;this.core.validateSourceNode(),this.log.info(`add music source, id: ${t.id} url: ${t.url}, track: ${t.track}`);let{id:r,url:o}=t;if(this.mixedMusicMap.has(r))return;let s=this.cacheMusicMap.get(r);s?t.url?s.reset():(s.mixInput.replaceSource(t.track),s.mixInput.connect()):(s=new cf(t,e.audioManager),this.cacheMusicMap.set(r,s)),s.updateListener(t),s.updateSettings(t);try{yield s.play()}catch(n){yield this.handleAutoPlayFailed(s,t,n)}this.mixedMusicMap.set(r,s),s.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"add",audioReference:s.mixInput.source.node,refId:`ax-${r}`}),this.log.info(`start mix audio track ${r} success.`),X.addEnum({key:502700,value:3}),this.kvUpload(t)})}handleAutoPlayFailed(t,e,r){return y(this,null,function*(){if(r.name==="NotSupportedError")this.log.error(`play failed, try to reload source. error: ${r}`),yield t.reload(e),yield t.play();else if(r.name==="NotAllowedError")if(this.core.room.enableAutoPlayDialog){let o=()=>{var s;(s=t.play())==null||s.finally(()=>{U.off("154",o,this)})};U.on("154",o,this),Dn()}else this.core.trtc.emit(ie.AUTOPLAY_FAILED,{userId:"",mediaType:"audio",resume:()=>y(this,null,function*(){return t.play()})});else throw r})}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),O(r)||n.setOperation(r),O(o)||n.seek(o),this.kvUpload(t)})}stop(e){return y(this,arguments,function*({id:t}){if(this.mixedMusicMap.has(t)){this.log.info(`remove music source, music id: ${t}`);let r=this.mixedMusicMap.get(t);r!=null&&r.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:r.mixInput.source.node,refId:`ax-${t}`}),r==null||r.stop(),this.mixedMusicMap.delete(t)}t==="*"&&this.destroyAllMusic()})}kvUpload(t){let{track:e,loop:r,volume:o,playbackRate:s,operation:n,seekFrom:a,onTimeUpdate:d,onDurationChange:l,onEnded:p}=t;e&&X.addCount({key:502009}),r&&X.addCount({key:502001}),o&&X.addCount({key:502002}),s&&X.addCount({key:502003}),n&&X.addCount({key:502004}),a&&X.addCount({key:502005}),typeof d!="function"&&X.addCount({key:502007}),typeof p!="function"&&X.addCount({key:502008}),typeof l!="function"&&X.addCount({key:502006})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((t,e)=>{t!=null&&t.mixInput.track&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:t.mixInput.track,refId:e}),this.stop({id:e})})}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}};m(Ei,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(t,e,r){if(t.url&&t.url!=="*"){let o=t.url.split("?")[0],s=["mp3","ogg","wav","flac"],n=o.split(".").pop(),a=s.indexOf(n)>=0,d=o.startsWith("blob"),l=o.startsWith("data");if(!(a||d||l))throw new oe({code:ne.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:r})}if(!t.url&&!t.track)throw new oe({code:ne.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:r});Xn("onTimeUpdate",t.onTimeUpdate),Xn("onEnded",t.onEnded),Xn("onDurationChange",t.onDurationChange)}}),m(Ei,"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){Xn("onTimeUpdate",t.onTimeUpdate),Xn("onEnded",t.onEnded),Xn("onDurationChange",t.onDurationChange)}}),m(Ei,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),m(Ei,"Name","AudioMixer");var Al=Ei;var yl=0,df,Zi=class Zi{constructor(t){this.core=t;m(this,"log");m(this,"audioContext",ze("denoiser"));m(this,"workletNode");m(this,"config",{enableFarFieldReduce:!1,farFieldReduceThreshold:.5});yl=yl+1,this.log=t.log.createChild({id:`${this.getAlias()}${yl}`}),this.log.info(`created id=${this.getAlias()}${yl}`)}static startValidateRule(t){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0},mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}},validate(e,r,o,s){if(!t.room.audioManager.hasAudioTrack)throw new oe({code:ne.INVALID_OPERATION,extraCode:5106,fnName:o})}}}preload(t){return df||(df=this.doPreload(t)),df}doPreload(t){return y(this,null,function*(){let e=yield this.core.fileDownloader.download(t,{type:"blob"}),r=URL.createObjectURL(e);try{yield Gi(this.audioContext,r)}catch(o){throw this.log.error("load worklet failed",o),o}finally{URL.revokeObjectURL(r)}})}getName(){return Zi.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser"}getValidateRule(t){switch(t){case"start":return Zi.startValidateRule(this.core);case"update":return Zi.updateValidateRule;case"stop":return Zi.stopValidateRule}}start(t){return y(this,null,function*(){let{room:e,schedule:r}=this.core,{assetsPath:o=this.core.assetsPath}=t;if(!o)throw new oe({code:ne.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload(`${o}/denoiser-wasm${Ih()?"":"-nosimd"}.js`),!this.workletNode){let s=String(Date.now()).slice(0,-3),{auth:n,sign:a,status:d,message:l}=yield WR(r,_e(Y({},t),{timestamp:s}));if(!n)throw this.log.info(`RTCAIDenoiser: ${t.userId} auth result: ${n}. Message: ${l}`),new oe({code:ne.INVALID_PARAMETER,message:l});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(t.sdkAppId),userId:t.userId,timestamp:s,sign:a,status:d}}),this.workletNode.port.onmessage=p=>{var g;let{data:f}=p;if(f.type==="cost"){let A=(f==null?void 0:f.max)>20?"warn":(f==null?void 0:f.max)>10?"info":"debug";this.log[A](`avg cost: ${f.value} max: ${f==null?void 0:f.max}(${Ks(new Date(f==null?void 0:f.maxCostTimestamp))}) hist: ${(g=f==null?void 0:f.hist)==null?void 0:g.join(" ")}`)}else f.type==="log"&&this.log[f.logLevel](`${f.value}`)}}this.updateConfig(t),this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(t){return y(this,null,function*(){this.updateConfig(t)})}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)})}updateConfig(t){if(!this.workletNode)return;let e=!1;O(t.mode)||(t.mode===0?this.config.enableFarFieldReduce=!1:t.mode===1&&(this.config.enableFarFieldReduce=!0),e=!0),O(t.farFieldReduceThreshold)||(this.config.farFieldReduceThreshold=t.farFieldReduceThreshold,e=!0),e&&this.workletNode.port.postMessage({type:"setConfig",data:this.config})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};m(Zi,"updateValidateRule",{type:"object",properties:{mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}}}),m(Zi,"stopValidateRule",{type:"object"}),m(Zi,"Name","AIDenoiser");var bl=Zi;function WR(s,n){return y(this,arguments,function*(i,{sdkAppId:t,userId:e,userSig:r,timestamp:o}){try{let{data:{errCode:a,errMsg:d,sign:l,status:p}}=yield i.getAbilityConfig(t,i.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:t,userId:e,userSig:r,timestamp:o});if(p==="1")return{auth:!0,sign:l,status:p,message:d};let f=Rr(t)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",g="Init RTCAIDenoiser failed.",A="";switch(a){case 1:A="Please check your params.";break;case 2:A=`You need to buy packages. Refer to: ${f}`;break;case 3:A="Server is invalid. Please contact our engineer. ";break;case 4:A=`Your packages is not active. Refer to: ${f}`;break;case 5:A=`Your packages is expired. Refer to: ${f}`;break;case 6:A="Your version is not supported.";break}return{auth:!1,status:p,message:d?`${g} Reason: ${d}. ${A}`:`${g}, ${A}`}}catch(a){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${a}`}}})}var _T=bi(ki(),1);var uf=class extends _T.EventEmitter{constructor(){super();m(this,"observer");m(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){qe.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)&&F.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){qe.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:r})}}},GR=new uf,lf=GR;function jR([i,t]){let e=t.byteLength,r=parseInt(String(e/255),10),o=e%255,s=[];s.push(0,0,0,1,6,i);for(let a=0;a<r;a++)s.push(255);s.push(o);let n=new DataView(t);return s.push(...new Uint8Array(n.buffer)),s.push(128),new Os(new DataView(new Uint8Array(s).buffer),!0)}function qR(i){return i.type==="empty"||i.data.byteLength===0}function zR(i){return i.getInt32(0)===1&&i.getInt8(4)===6}function JR(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 mf({frame:i,seiMessageList:t}){if(!t||t.length===0||i.data.byteLength===0)return i;let r=9-JR(i.data);if(r<=0)return i;let o=t.splice(0,r).reverse().map(jR),s=o.reduce((p,f)=>p+f.dataView.byteLength,0),n=new ArrayBuffer(s+i.data.byteLength),a=new DataView(n),d=new DataView(i.data),l=0;for(let p=0;p<o.length;p++)for(let f=0;f<o[p].dataView.byteLength;f++)a.setInt8(l++,o[p].dataView.getInt8(f));for(let p=0;p<i.data.byteLength;p++)a.setInt8(l++,d.getInt8(p));return i.data=n,i}function hf({frame:i,onSEI:t}){try{let e=new DataView(i.data);if(qR(i)||!zR(e))return i;let r=[],o=0,s=-1,n=-1;for(let a=0;a<i.data.byteLength;a++){let d=e.getUint8(a);if(d===0)o++;else if(d===1){if(o===2||o===3){let l=a-o;if(s===-1?s=l:n===-1&&(n=l,r.push(new Os(new DataView(e.buffer.slice(s,n)))),s=l,n=-1),!(e.getUint8(a+1)===6)){i.data=e.buffer.slice(l);break}}o=0}else o=0}t==null||t(r.reverse())}catch(e){}return i}var pf=0,Oc=class Oc{constructor(t){this.core=t;m(this,"log");m(this,"_seiMessageList",[]);m(this,"_smallSeiMessageList",[]);m(this,"_subStreamSeiMessageList",[]);pf++,this.log=t.log.createChild({id:`${this.getAlias()}${pf}`}),this.log.info(`[sei] created id=${this.getAlias()}${pf}`),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 mf({frame:t,seiMessageList:r})}catch(r){this.log.warn(r)}return t}decode({frame:t,track:e}){return hf({frame:t,onSEI:r=>{r.forEach(o=>{this.core.trtc.emit(ie.SEI_MESSAGE,{seiPayloadType:o.seiPayloadType,data:o.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"})})}})}destroy(){this.log.debug("destroy"),this.stop(),delete this.core}getValidateRule(t){switch(t){case"start":return{type:"object"};case"update":return{type:"object"};case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:Is?this.encode:mf,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:Is?this.decode:hf,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 Oc.Name}getAlias(){return"sei"}getGroup(){return"sei"}};m(Oc,"autoStart",!0),m(Oc,"Name","SEI");var Rl=Oc;var XR=0,vl,Mc=class Mc{constructor(t){this.core=t;m(this,"_core");m(this,"log");m(this,"dialog");this._core=t,this.log=t.log.createChild({id:`${this.getAlias()}${++XR}`}),this.log.info("created")}getName(){return Mc.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())})}update(e){return y(this,arguments,function*({visible:t}){t?yield this.openDebugDiaLog():this.closeDebugDiaLog()})}stop(){this.closeDebugDiaLog()}destroy(){this.stop()}openDebugDiaLog(){return y(this,null,function*(){var t;if(!this.dialog)try{if(vl)yield vl;else{let e=new URLSearchParams(location.search).get("trtcDebugDialogPath")||((t=window.sessionStorage)==null?void 0:t.getItem("TRTC_DEBUG_DIALOG_PATH"))||`https://unpkg.com/${gT}@${pt}/assets/debug-dialog.js`;vl=this._core.fileDownloader.loadScript(e),yield vl}this.dialog=new TRTCDebugDialog(this._core,this.log),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(e){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(e))}})}closeDebugDiaLog(){this.dialog&&(this.dialog.closeDialog(),this.dialog=null)}};m(Mc,"Name","Debug"),m(Mc,"autoStart",!0);var Cl=Mc;var TT=i=>{switch(i){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},Nl=class{constructor(t,e,r){m(this,"trackDoneOB");m(this,"startOB");m(this,"stopOB");m(this,"inputFrameCount",0);m(this,"decodedFrameCount",0);m(this,"type","auto");m(this,"config");m(this,"decoder");m(this,"_decodeSink");let{kvStatManager:o,trtc:s}=t;this.config=r.config,this.trackDoneOB=Ae(e,ue.INIT),this.stopOB=bt(),this.startOB=bt(),r.type==="auto"?this.type="webCodecs":this.type=r.type;let n=bt(),a=d=>{let l=this.pipe(e);return n.next("STARTING"),e.log.info(`decoder type: ${this.type}`),ye(l,Je(this.stopOB),Le(()=>{},p=>{e.log.error(p),o.addFailedEvent({key:TT(this.type),error:p}),d>4?this.startOB.error(p):this.startOB.next(d+1)})),ye(l,Qr(1),yp(hc))};ye(this.startOB,lc(0),ui(a),Je(this.stopOB),Le(()=>{e.player.setOutput(),n.next("STARTED")},d=>{n.next("FAILED")},()=>{o.addSuccessEvent({key:TT(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 ji()(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"}))}},QR={type:"object"},xc=class xc{constructor(t){this.core=t;m(this,"log");m(this,"contextMap",new Map);m(this,"decodeProcessorMap",new WeakMap);this.log=t.log.createChild({id:`${this.getAlias()}`})}getAlias(){return xc.Name}getGroup(t){return t.track.userId+t.track.streamType}getName(){return xc.Name}getValidateRule(t){return QR}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 Nl(this.core,r,t);return ye(o.trackDoneOB,Qr(1),Le(()=>{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 Nl(this.core,t.track,t))}}};m(xc,"Name","TRTCAudioDecoder");var Pc=xc;var Dl=class{constructor(){m(this,"log");this.log=F.createLogger({id:"exp"})}call(t,e){return y(this,null,function*(){return Xe(this[t])?this[t](e):Promise.reject(new se({code:q.INVALID_PARAMETER,message:We({key:He.API_NOT_EXIST,data:{name:t}})}))})}enableAudioFrameEvent(t){return y(this,null,function*(){let{trtcInstance:e,enable:r,userId:o,sampleRate:s=48e3,channelCount:n=1,port:a}=t,{audioManager:d}=e.room,{getPCMAbortCtrlMap:l,audioFrameEventConfigMap:p}=d;if(p.set(o,{enable:r,sampleRate:s,channelCount:n,port:a}),r)if(o==="*")e.room.remotePublishedUserMap.forEach(f=>{if(f.remoteAudioTrack.isAvailable){if(l.get(f.userId))return;let g=d.getPCM(A=>{e.emit(ie.AUDIO_FRAME,A)},f.userId);l.set(f.userId,g)}});else{if(l.get(o))return;let f=d.getPCM(g=>{e.emit(ie.AUDIO_FRAME,g)},o);l.set(o,f)}else if(o==="*")e.room.remotePublishedUserMap.forEach(f=>{if(f.remoteAudioTrack.isSubscribed){let{userId:g}=f,A=l.get(g);A==null||A.abort("disable"),l.delete(g)}});else{let f=l.get(o);f==null||f.abort("disable"),l.delete(o)}})}resumeRemotePlayer(t){return y(this,null,function*(){if(t.userId==="*"){let r=[];return t.trtcInstance.room.remotePublishedUserMap.forEach(o=>{let{remoteAudioTrack:s,remoteVideoTrack:n,remoteAuxiliaryTrack:a}=o;t.streamType?t.streamType==="main"?(s.isAvailable&&r.push(s.player.resume()),n.isAvailable&&r.push(n.player.resume())):a.isAvailable&&r.push(a.player.resume()):(s.isAvailable&&r.push(s.player.resume()),n.isAvailable&&r.push(n.player.resume()),a.isAvailable&&r.push(a.player.resume()))}),Promise.all(r)}let e=t.trtcInstance.room.remotePublishedUserMap.get(t.userId);if(e)return t.streamType==="main"?Promise.all([e.remoteAudioTrack.player.resume(),e.remoteVideoTrack.player.resume()]):e.remoteAuxiliaryTrack.player.resume()})}pauseRemotePlayer(t){if(t.userId==="*")t.trtcInstance.room.remotePublishedUserMap.forEach(e=>{let{remoteAudioTrack:r,remoteVideoTrack:o,remoteAuxiliaryTrack:s}=e;t.streamType?t.streamType==="main"?(r.isAvailable&&r.player.pause(),o.isAvailable&&o.player.pause()):s.isAvailable&&s.player.pause():(r.isAvailable&&r.player.pause(),o.isAvailable&&o.player.pause(),s.isAvailable&&s.player.pause())});else{let e=t.trtcInstance.room.remotePublishedUserMap.get(t.userId);e&&(t.streamType==="main"?(e.remoteAudioTrack.player.pause(),e.remoteVideoTrack.player.pause()):e.remoteAuxiliaryTrack.player.pause())}}};Z([r_({name:"options",type:"object",required:!0,properties:{enable:{required:!0,type:"boolean"},userId:{required:!0,type:"string"},sampleRate:{type:"number",values:[8e3,16e3,32e3,44100,48e3]},channelCount:{type:"number",values:[1,2]},port:{type:"messageport"}}})],Dl.prototype,"enableAudioFrameEvent",1);var IT=new Dl;var ST=bi(ki(),1);var ff=class extends ST.EventEmitter{constructor(){super();m(this,"states",{});m(this,"permissionChangeHandler");m(this,"log");this.log=F.createLogger({id:"pm"}),this.permissionChangeHandler=()=>{var e,r;this.emit("permission-state-change",{camera:(e=this.states.camera)==null?void 0:e.state,microphone:(r=this.states.microphone)==null?void 0:r.state})}}request(e){return y(this,null,function*(){if(this.log.info(`request ${e.join(", ")}`),e.length===0)return Promise.resolve();(yield navigator.mediaDevices.getUserMedia({video:e.includes("camera"),audio:e.includes("microphone")})).getTracks().forEach(o=>o.stop())})}get(e){return y(this,null,function*(){try{return this.states[e]||(this.states[e]=yield navigator.permissions.query({name:e}),this.states[e].addEventListener("change",this.permissionChangeHandler)),this.log.info(`get ${e} permission state: ${this.states[e].state}`),this.states[e].state}catch(r){return this.log.error(`get ${e} permission failed, error: ${r instanceof Error?r.message:r}`),null}})}destroy(){Object.values(this.states).forEach(e=>{e==null||e.removeEventListener("change",this.permissionChangeHandler)}),this.states={}}},Lc=new ff;var AT=0,kc=new Set,kt=null;om(sf);Rn.checkStorage();var pe=class pe extends yT.EventEmitter{constructor(e,r){super();m(this,"_room");m(this,"_eventListened",new Set);m(this,"_localVideoTrack",null);m(this,"_localAudioTrack",null);m(this,"_localScreenTrack",null);m(this,"_localScreenAudioTrack",null);m(this,"_localVideoConfig",null);m(this,"_localScreenConfig",null);m(this,"_localAudioConfig",null);m(this,"_remoteVideoConfigMap",new Map);m(this,"_remoteAudioConfigMap",new Map);m(this,"_remoteAudioVolumeMap",new Map);m(this,"_remoteAudioMuteMap",new Map);m(this,"_mediaTrackMap",new WeakMap);m(this,"_log",F.createLogger({id:`t${++AT}`}));m(this,"_plugins",new Map);m(this,"_networkQuality",null);m(this,"_speakerId");m(this,"enterRoomParams");m(this,"_enableAutoSwitchWhenRecapturing",!0);this._room=new e(Y({logger:this._log,frameWorkType:pe.frameWorkType},r)),this._room.videoDecodeFallbackType=r.videoDecodeFallback,Ye(r.enableAutoSwitchWhenRecapturing)&&(this._enableAutoSwitchWhenRecapturing=r.enableAutoSwitchWhenRecapturing),this._log.info(`create() ${JSON.stringify(r,(o,s)=>o==="plugins"?s.map(n=>n.Name):s)}`),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(o){return this._room.audioManager.dump(o)}}}),r.plugins&&r.plugins.forEach(o=>{this._use(o,r.assetsPath)}),this._use(Al,r.assetsPath),this._use(Il,r.assetsPath),this._use(bl,r.assetsPath),this._use(Pc,r.assetsPath),this._use(Cl),r.enableSEI&&Ja&&this._use(Rl),this._room.on("audio-volume",o=>{var s,n;!o.find(a=>a.userId==="")&&this._localAudioTrack&&o.push({userId:"",volume:Math.floor(((s=this._localAudioTrack.getInternalAudioLevelAfter3A())!=null?s:this._localAudioTrack.getAudioLevel())*100),floatVolume:(n=this._localAudioTrack.getInternalAudioLevelAfter3A())!=null?n:this._localAudioTrack.getInternalAudioLevel()}),r.volumeType===1&&o.forEach(a=>{var l;let d=a.userId===""?this._localAudioTrack:(l=this.room.remotePublishedUserMap.get(a.userId))==null?void 0:l.remoteAudioTrack;d&&(a.volume=d.dbVolume)}),r.enableDbVolume&&o.forEach(a=>{var l;let d=a.userId===""?this._localAudioTrack:(l=this.room.remotePublishedUserMap.get(a.userId))==null?void 0:l.remoteAudioTrack;d&&(a.volume=d.dbVolume)}),this.emit(ie.AUDIO_VOLUME,{result:o.sort((a,d)=>d.volume-a.volume)})}),this._room.videoManager.on("error",o=>{this._log.error(new oe({code:ne.OPERATION_FAILED,extraCode:5504,message:o.message,originError:o}))}),this._listenEvents(),this._initActiveSpeaker(),mT(this,"trtc")}static create(e){}static _create(e,r){Q_();let o=new pe(e,r||{});return kc.add(o),o.__v_skip=!0,o}get room(){return this._room}_listenEvents(){Ft(this,this._room).add("peer-join",e=>{let{userId:r}=e;this.emit(ie.REMOTE_USER_ENTER,{userId:r})}).add("peer-leave",e=>{this.emit(ie.REMOTE_USER_EXIT,{userId:e})}).add("banned",e=>{Qi(!0),this._exitRoom().finally(()=>{this.emit(ie.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().finally(()=>{this.emit(ie.ERROR,oe.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(ie.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let r=_e(Y({},e),{uplinkRTT:Math.min(e.uplinkRTT,Ea),downlinkRTT:Math.min(e.downlinkRTT,Ea)});this.emit(ie.NETWORK_QUALITY,r)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(o=>{Ft(o,o).add("player-state-changed",s=>{let n=_e(Y({},s),{userId:e.userId});o.kind===M.VIDEO&&(n.streamType=fi(o.streamType)),this.emit(o.kind===M.AUDIO?ie.AUDIO_PLAY_STATE_CHANGED:ie.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",s=>{s.getCode()===q.PLAY_NOT_ALLOWED&&this.emit(ie.AUTOPLAY_FAILED,{userId:o.userId,mediaType:o.strMediaType,resume:()=>o.player.resume()})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(o=>{At(o)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:r})=>{let{userId:o}=r,s=e.audioAvailable,n=e.videoAvailable,{audioAvailable:a,videoAvailable:d}=r;a||this._remoteAudioConfigMap.delete(o),d||this._removeRemoteVideoConfig(o,"main"),r.hasAuxiliary||this._removeRemoteVideoConfig(o,"sub"),n!==d&&(d?this._onVideoAvailable({userId:o,streamType:"main"}):this._onVideoUnavailable({userId:o,streamType:"main"}),this.emit(d?ie.REMOTE_VIDEO_AVAILABLE:ie.REMOTE_VIDEO_UNAVAILABLE,{userId:o,streamType:"main"})),s!==a&&(a?this._onAudioAvailable({userId:o}):this._onAudioUnavailable({userId:o,muteState:r}),this.emit(a?ie.REMOTE_AUDIO_AVAILABLE:ie.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?ie.REMOTE_VIDEO_AVAILABLE:ie.REMOTE_VIDEO_UNAVAILABLE,{userId:o,streamType:"sub"}))}).add("sei-message",e=>{this.emit(ie.SEI_MESSAGE,_e(Y({},e),{streamType:fi(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(ie.ERROR,new oe({code:ne.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var s,n,a,d,l,p,f;let r={2:"big",3:"small",7:"sub"},o={rtt:Math.min(e.msg_up_stream_info.msg_network_status.uint32_rtt||((s=e.msg_down_stream_info[0])==null?void 0:s.msg_network_status.uint32_rtt)||((n=this._networkQuality)==null?void 0:n.uplinkRTT)||((a=this._networkQuality)==null?void 0:a.downlinkRTT)||0,Ea),upLoss:((d=this._networkQuality)==null?void 0:d.uplinkLoss)||0,downLoss:((l=this._networkQuality)==null?void 0:l.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((p=e.msg_up_stream_info.msg_audio_status)==null?void 0:p.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((f=e.msg_up_stream_info.msg_audio_status)==null?void 0:f.uint32_audio_level)||0)/Fi},video:e.msg_up_stream_info.msg_video_status.filter(g=>r[g.uint32_video_stream_type]).map(g=>({bitrate:(g.uint32_video_codec_bitrate||0)/1e3,width:g.uint32_video_width,height:g.uint32_video_height,frameRate:g.uint32_video_enc_fps,videoType:r[g.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(g=>({userId:g.msg_user_info.str_identifier,audio:{bitrate:(g.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(g.msg_audio_status.uint32_audio_level||0)/Fi,point2pointDelay:(g.msg_audio_status.uint32_audio_p2p_delay||0)+(g.msg_audio_status.uint32_audio_cache_ms||0),jitterBufferDelay:g.msg_audio_status.uint32_audio_cache_ms||0},video:g.msg_video_status.map(A=>({bitrate:(A.uint32_video_codec_bitrate||0)/1e3,width:A.uint32_video_width,height:A.uint32_video_height,frameRate:A.uint32_video_dec_fps,videoType:r[A.uint32_video_stream_type],point2pointDelay:(A.uint32_video_p2p_delay||0)+(A.uint32_video_cache_ms||0),jitterBufferDelay:A.uint32_video_cache_ms||0,codec:A.uint32_video_codec}))}))};this.emit(ie.STATISTICS,o)}).add("custom-message",e=>{this.emit(ie.CUSTOM_MESSAGE,e)}).add("layerData",e=>this.emit(ie.LAYER_DATA,e)).add("first-video-frame",e=>{this.emit(ie.FIRST_VIDEO_FRAME,_e(Y({},e),{streamType:fi(e.streamType)}))}).add("audio-frame",e=>{this.emit(ie.AUDIO_FRAME,e)}),Ft(this,dt).add("audioInputAdded",e=>{this.emit(ie.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(ie.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(ie.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(ie.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>y(this,null,function*(){if(this.emit(ie.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),kt&&kt.deviceId===ga){let r=(yield Co()).find(o=>o.deviceId===ga);r&&kt.groupId!==r.groupId&&(kt=r,this.emit(ie.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}))}})).add("audioOutputRemoved",e=>y(this,null,function*(){this.emit(ie.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let r=(yield Co())[0];if(!r||!kt||kt.groupId===r.groupId)return;let o=kt.deviceId===e.deviceId,s=kt.deviceId===ga&&kt.deviceId===r.deviceId;(o||s)&&(kt=r,this.emit(ie.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}))})),Ft(this,Lc).add("permission-state-change",e=>{this.emit(ie.PERMISSION_STATE_CHANGE,e)}),this.room.enableSEI&&this.on(ie.SEI_MESSAGE,e=>{var o;let r=(o=this.room.remotePublishedUserMap.get(e.userId))==null?void 0:o.remoteVideoTrack;r&&r.updateAlphaRenderInfo(e)})}getNetworkTime(){return Ri()}use(e){let r,o;return"plugin"in e?(r=e.plugin,o=e.assetsPath):r=e,r.Name==="Chorus"&&(this.room.enableChorus=!0),this._use(r,o)}_use(e,r){let o=this._plugins.get(e.Name);if(o)return this._log.warn("duplicate install plugin",e.Name),o;let s=new e(lT.call(this,{TRTC:pe,room:this._room,assetsPath:r,errorModule:{RtcError:oe,ErrorCode:ne,CoreErrorCode:q,ErrorCodeDictionary:Tr}}));return this._plugins.set(e.Name,s),s.__v_skip=!0,e.autoStart&&this.startPlugin(e.Name),s}enterRoom(e){return y(this,null,function*(){var d,l;this.enterRoomParams=e;let{scene:r="rtc",enableAutoPlayDialog:o=!0,autoReceiveAudio:s=!0,autoReceiveVideo:n=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!Oe(e.proxy)&&e.proxy.turnServer&&((l=(d=this._room).setTurnServer)==null||l.call(d,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=o,this._room.autoReceiveAudio=s,this._room.autoReceiveVideo=n,Ye(e.preferHW)&&(this._room.preferHW=e.preferHW),e.playoutDelay&&(this._room.playoutDelay=e.playoutDelay),e.jitterBufferDelay&&(this._room.jitterBufferDelay=e.jitterBufferDelay);let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:e.role==="audience"?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language,priority:e.priority,useVp8:e.useVp8,useH265:e.useH265||!1,keepAlive:e.keepAlive};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(a,r,pe.frameWorkType),this._checkTrackToPublish(),lf.start()})}exitRoom(){return y(this,null,function*(){return yield this._exitRoom()})}switchRoom(e){return y(this,null,function*(){if(this.room.isSwitchRoomSupported())try{this._clearRemoteTracks(),yield this._room.switchRoom(e)}catch(r){if(r instanceof la&&(r.code===q.API_CALL_TIMEOUT||r.code===q.SWITCH_ROOM_FAILED))this._log.warn(`switchRoom ${r.code===q.API_CALL_TIMEOUT?"timeout":"failed"}, fallback to exitRoom() and enterRoom()`),yield this._rejoinRoom(e);else throw r}else yield this._rejoinRoom(e)})}_rejoinRoom(e){return y(this,null,function*(){yield this.exitRoom();let r=Y(Y({},this.enterRoomParams),e);yield this.enterRoom(r)})}_clearRemoteTracks(){new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(e=>{this._stopRemoteAudio({userId:e}).catch(()=>{})}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let r=e.includes("main")?"main":"sub",o=e.split(`_${r}`)[0];o&&this._stopRemoteVideo({userId:o,streamType:r}).catch(()=>{})}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),hT(this),this._room.remotePublishedUserMap.forEach(e=>{At(e.remoteAudioTrack),At(e.remoteVideoTrack),At(e.remoteAuxiliaryTrack)})}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(){this._plugins.forEach(e=>{var r;return(r=e.destroy)==null?void 0:r.call(e)}),this._plugins.clear(),At(this),this.removeAllListeners(),this._room.destroy(),kc.delete(this),kc.size===0&&lf.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),U.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 li(this._room.audioManager),a={},d={muted:!0};s&&(O(s.microphoneId)?O(s.audioTrack)||(a.customSource=s.audioTrack):a.deviceId=s.microphoneId,s&&Fe(s.captureVolume)&&n.setCaptureVolume(s.captureVolume),O(s.profile)||(Oe(s.profile)?pd[s.profile]&&n.setProfile(pd[s.profile]):n.setProfile(s.profile)),Fe(s.earMonitorVolume)&&(d.muted=!(s.earMonitorVolume>0),d.volume=s.earMonitorVolume),O(s.echoCancellation)||(n.profile.echoCancellation=s.echoCancellation),O(s.noiseSuppression)||(n.profile.noiseSuppression=s.noiseSuppression),O(s.autoGainControl)||(n.profile.autoGainControl=s.autoGainControl),Ye(this._enableAutoSwitchWhenRecapturing)&&(n.enableAutoSwitchWhenRecapturing=this._enableAutoSwitchWhenRecapturing)),n.on("5",l=>{this.emit(ie.ERROR,new oe({code:ne.DEVICE_ERROR,extraCode:5309,messageParams:{error:l}}))}),n.on("2",l=>{this.emit(ie.DEVICE_CHANGED,{type:"microphone",action:"active",device:l})}),n.on("4",l=>{let p;l.error&&(p=oe.convertFrom(l.error)),this.emit(ie.PUBLISH_STATE_CHANGED,_e(Y({},l),{error:p}))}),n.on("6",()=>{}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId),yield n.capture(a),O(o)||n.setMute(o),Ft(n,n).add("player-state-changed",l=>{this.emit(ie.AUDIO_PLAY_STATE_CHANGED,_e(Y({},l),{userId:""}))}),r&&this._room.isJoined&&this._room.publish(n).catch(()=>{}),this._localAudioTrack=n,this._localAudioConfig=_e(Y({},e),{publish:r}),yield this._updateAudioPlayOption({playOption:d,track:n}),U.emit("113",{userId:"",room:this.room})})}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):O(s.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(s.audioTrack)),O(s.captureVolume)||this._localAudioTrack.setCaptureVolume(s.captureVolume),O(s.earMonitorVolume)||(n.muted=!(s.earMonitorVolume>0),n.volume=s.earMonitorVolume),yield this._localAudioTrack.update3A(s)),this._room.isJoined&&!O(r)&&(r&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!r&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),O(o)||this._localAudioTrack.setMute(o),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),Br(this._localAudioConfig,e)})}stopLocalAudio(){return y(this,null,function*(){this._localAudioTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),U.emit("114",{userId:"",room:this.room}),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),At(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)})}startLocalVideo(){return y(this,arguments,function*(e={publish:!0,view:null,capture:!0}){var f;if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:r,publish:o=!0,capture:s=!0,mute:n,option:a}=e,d=new _r(this._room.videoManager),l={},p={};a&&(Ye(a.avoidCropping)&&(d.avoidCropping=a.avoidCropping),a.cameraId?l.deviceId=a.cameraId:O(a.useFrontCamera)?O(a.videoTrack)||(l.customSource=a.videoTrack):l.facingMode=a.useFrontCamera?M.FACING_MODE_USER:M.FACING_MODE_ENVIRONMENT,O(a.retryWhenExactFailed)||(l.retryWhenExactFailed=a.retryWhenExactFailed),a.qosPreference&&(l.contentHint=Nc(a.qosPreference)),O(a.profile)||(Oe(a.profile)?Vr[a.profile]&&d.setProfile(Vr[a.profile]):d.setProfile(a.profile)),O(a.fillMode)||(p.objectFit=a.fillMode),O(a.mirror)||(p.mirror=a.mirror),O(a.small)||(O(a.smallMode)||(this._room.smallMode=a.smallMode),Ye(a.small)&&a.small===!1?d.stopSmall():d.updateSmallConfig(jn(a.small,!0))),O(a.rotation)||d.setRotation(a.rotation),Ye(this._enableAutoSwitchWhenRecapturing)&&(d.enableAutoSwitchWhenRecapturing=this._enableAutoSwitchWhenRecapturing)),d.once("first-video-frame",g=>{this.emit(ie.FIRST_VIDEO_FRAME,_e(Y({},g),{streamType:fi(g.streamType)}))}),d.on("5",g=>{this.emit(ie.ERROR,new oe({code:ne.DEVICE_ERROR,extraCode:5308,messageParams:{error:g}}))}),d.on("2",g=>{this.emit(ie.DEVICE_CHANGED,{type:"camera",action:"active",device:g})}),d.on("4",g=>{let A;g.error&&(A=oe.convertFrom(g.error)),this.emit(ie.PUBLISH_STATE_CHANGED,_e(Y({},g),{error:A}))}),d.on("6",()=>{}),this._listenOutputTrackChanged(d),s?yield d.capture(l):(f=d.manager)==null||f.changeInput(d),O(n)||(yield d.setMute(n)),Ft(d,d).add("player-state-changed",g=>{this.emit(ie.VIDEO_PLAY_STATE_CHANGED,_e(Y({},g),{userId:"",streamType:"main"}))}).add("video-size-changed",g=>{this.emit(ie.VIDEO_SIZE_CHANGED,_e(Y({},g),{streamType:fi(g.streamType)}))}),o&&this._room.isJoined&&this._room.publish(d).catch(()=>{}),this._localVideoTrack=d,this._localVideoConfig=_e(Y({},e),{view:r,publish:o,capture:s}),yield this._updateVideoPlayOption({view:r,playOption:p,track:d})})}updateLocalVideo(e){return y(this,null,function*(){var l,p,f;if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:r,publish:o,mute:s,capture:n,option:a}=e,d={};if(this._localVideoConfig.capture)n!==!1?a!=null&&a.cameraId?yield this._localVideoTrack.switchDevice(a==null?void 0:a.cameraId):O(a==null?void 0:a.useFrontCamera)?O(a==null?void 0:a.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(a==null?void 0:a.videoTrack)):yield this._localVideoTrack.switchDevice(a!=null&&a.useFrontCamera?M.FACING_MODE_USER:M.FACING_MODE_ENVIRONMENT):this._localVideoTrack.stopCapture();else if(n){let g={};g.deviceId=(a==null?void 0:a.cameraId)||((l=this._localVideoConfig.option)==null?void 0:l.cameraId),g.facingMode=a!=null&&a.useFrontCamera||(p=this._localVideoConfig.option)!=null&&p.useFrontCamera?M.FACING_MODE_USER:M.FACING_MODE_ENVIRONMENT,g.customSource=(a==null?void 0:a.videoTrack)||((f=this._localVideoConfig.option)==null?void 0:f.videoTrack),yield this._localVideoTrack.capture(g)}a&&(O(a.profile)||(Oe(a.profile)?Vr[a.profile]&&this._localVideoTrack.setProfile(Vr[a.profile]):this._localVideoTrack.setProfile(a.profile),(!a.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(a.cameraId))&&O(a.useFrontCamera)&&(yield this._localVideoTrack.applyProfile())),O(a.fillMode)||(d.objectFit=a.fillMode),O(a.mirror)||(d.mirror=a.mirror),O(a.rotation)||this._localVideoTrack.setRotation(a.rotation),a.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(Nc(a.qosPreference)),O(a.small)||(Ye(a.small)&&!a.small?this._localVideoTrack.stopSmall():this._localVideoTrack.updateSmallConfig(jn(a.small,!0)))),this._room.isJoined&&O(o)&&this._localVideoConfig.publish&&n&&!this._localVideoConfig.capture&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._room.isJoined&&((o!=null?o:this._localVideoConfig.publish)?this._room.publish(this._localVideoTrack).catch(()=>{}):this._room.unpublish(this._localVideoTrack).catch(()=>{})),O(s)||(yield this._localVideoTrack.setMute(s)),yield this._updateVideoPlayOption({view:r,playOption:d,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),Br(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(),At(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return y(this,arguments,function*(e={publish:!0,view:null}){var g,A;if(this._localScreenTrack){this._log.warn("screen share is already started");return}let{view:r=null,publish:o=!0,muteSystemAudio:s,option:n}=e,a=new mi(this._room.videoManager);a.on("4",R=>{let N;R.error&&(N=oe.convertFrom(R.error)),this.emit(ie.PUBLISH_STATE_CHANGED,_e(Y({},R),{error:N}))}),a.once("first-video-frame",R=>{this.emit(ie.FIRST_VIDEO_FRAME,_e(Y({},R),{streamType:fi(R.streamType)}))}),this._listenOutputTrackChanged(a),e.streamType==="main"&&(a.mediaType=4);let d=null,l={},p={};n&&(O(n.profile)||(Oe(n.profile)?fd[n.profile]&&a.setProfile(fd[n.profile]):a.setProfile(n.profile)),n.systemAudio&&(l.systemAudio=!0,l.echoCancellation=n.echoCancellation,l.noiseSuppression=n.noiseSuppression,l.autoGainControl=n.autoGainControl),O(n.fillMode)||(p.objectFit=n.fillMode),n.videoTrack&&(l.videoTrack=n.videoTrack),n.audioTrack&&(l.audioTrack=n.audioTrack),n.captureElement&&(l.captureElement=n.captureElement),n.preferDisplaySurface&&(l.preferDisplaySurface=n.preferDisplaySurface),n.qosPreference&&(l.contentHint=Nc(n.qosPreference)));let f=yield a.capture(l);if(a.mediaTrack.addEventListener(M.ENDED,()=>{this._stopScreenShare(),this.emit(ie.SCREEN_SHARE_STOPPED)}),f.getAudioTracks()[0]){d=new Ls(this._room.audioManager);let R=f.getAudioTracks()[0];(g=e.option)!=null&&g.systemAudio&&!((A=e.option)!=null&&A.audioTrack)&&(d.sourceTrack=R),yield d.setInputMediaStreamTrack(R),Ye(s)&&d.mediaTrack&&(d.mediaTrack.enabled=!s),this._speakerId&&d.setAudioOutput(this._speakerId)}if(Ft(a,a).add("player-state-changed",R=>{this.emit(ie.VIDEO_PLAY_STATE_CHANGED,_e(Y({},R),{userId:"",streamType:"sub"}))}),o&&this._room.isJoined){let R=[a];d&&(R.push(d),this._checkScreenAudioEchoCancellation(a,d)),R.forEach(N=>this._room.publish(N).catch(()=>{}))}this._localScreenTrack=a,this._localScreenAudioTrack=d,this._localScreenConfig=_e(Y({},e),{view:r,publish:o}),yield this._updateVideoPlayOption({view:r,playOption:p,track:a})})}updateScreenShare(e){return y(this,null,function*(){var d;if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:r,publish:o,muteSystemAudio:s,option:n}=e,a={};if(n&&(O(n.fillMode)||(a.objectFit=n.fillMode),n.qosPreference)){let l=Nc(n.qosPreference);this._localScreenTrack.setContentHint(l)}if(this._room.isJoined&&!O(o)){if(o&&!this._localScreenConfig.publish){let l=[this._localScreenTrack];this._localScreenAudioTrack&&l.push(this._localScreenAudioTrack),l.forEach(p=>this._room.publish(p).catch(()=>{}))}if(this._localScreenConfig.publish&&!o){let l=[this._localScreenTrack];this._localScreenAudioTrack&&l.push(this._localScreenAudioTrack),l.forEach(p=>this._room.unpublish(p).catch(()=>{}))}}(d=this._localScreenAudioTrack)!=null&&d.mediaTrack&&Ye(s)&&(this._localScreenAudioTrack.mediaTrack.enabled=!s),yield this._updateVideoPlayOption({view:r,playOption:a,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),Br(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,a=`${o}_${s}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${o}, streamType:${s}`);return}let d=this._room.remotePublishedUserMap.get(o);if(!d)return;let l={},p=s==="main"?d.remoteVideoTrack:d.remoteAuxiliaryTrack;p.on("decode-failed",f=>{this.emit(ie.ERROR,new oe({code:ne.OPERATION_FAILED,extraCode:5507,message:"video decode failed"}))}),p.on("video-size-changed",f=>{this.emit(ie.VIDEO_SIZE_CHANGED,_e(Y({},f),{streamType:fi(f.streamType)}))}),this._listenOutputTrackChanged(p),n&&(O(n.fillMode)||(l.objectFit=n.fillMode),O(n.mirror)||(l.mirror=n.mirror),O(n.poster)||(l.poster=n.poster),l.canvasRender=n.canvasRender,s==="main"&&!O(n.small)&&(!d.remoteVideoTrack.isSubscribing&&!d.remoteVideoTrack.isSubscribed&&d.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,p.user)),O(n.draggable)||p.setDraggable(n.draggable)),yield this._room.subscribe(p),yield this._enableVideoDecodeFallback(p,s),yield this._updateVideoPlayOption({view:r,playOption:l,track:p}),this._emitTrackEvent(p),this._remoteVideoConfigMap.set(a,{config:e}),n&&!O(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:p,view:r,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:n==null?void 0:n.viewRoot})})}updateRemoteVideo(e){return y(this,null,function*(){var P,z;let{view:r,userId:o,streamType:s,option:n,mute:a}=e,d=`${o}_${s}`,l=this._remoteVideoConfigMap.get(d);if(!l||!this._room.remotePublishedUserMap.has(o))return;let p={};n&&(O(n.fillMode)||(p.objectFit=n.fillMode),O(n.mirror)||(p.mirror=n.mirror));let f=null,g=this._room.remotePublishedUserMap.get(o);if(s==="main"&&(g!=null&&g.muteState.hasVideo)&&(f=g.remoteVideoTrack),s==="sub"&&(g!=null&&g.muteState.hasAuxiliary)&&(f=g.remoteAuxiliaryTrack),!f)return;let{config:A}=l;s==="main"&&n&&!O(n.small)&&this._room.changeType(n.small,f.user),n&&!O(n.draggable)&&f.setDraggable(n.draggable),Ye(a)&&(f.ignoreUpdatePlayingState=!0,a?(yield f.player.pause(),yield this.room.unsubscribe(f)):(yield this.room.subscribe(f),yield f.player.resume())),yield this._updateVideoPlayOption({view:r,playOption:p,track:f,prevConfig:A}),Br(A,e);let R=O(n==null?void 0:n.receiveWhenViewVisible)?(P=A.option)==null?void 0:P.receiveWhenViewVisible:n.receiveWhenViewVisible,N=O(r)?A.view:r,C=O(n==null?void 0:n.viewRoot)?(z=A.option)==null?void 0:z.viewRoot:n.viewRoot;this._observeView({remoteTrack:f,view:N,receiveWhenViewVisible:R,viewRoot:C})})}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:n,remoteVideoTrack:a,remoteAuxiliaryTrack:d}=s;e.streamType==="main"&&(a.stop(),n.hasVideo&&o.push(a)),e.streamType==="sub"&&(d.stop(),n.hasAuxiliary&&o.push(d))}for(let n of o)r&&(delete n.ignoreUpdatePlayingState,yield this._room.unsubscribe(n),this._mediaTrackMap.delete(n.outMediaTrack));this._removeRemoteVideoConfig(e.userId,e.streamType)})}_removeRemoteVideoConfig(e,r){let o=`${e}_${r}`,s=this._remoteVideoConfigMap.get(o);s&&s.observer&&s.observer.disconnect(),this._remoteVideoConfigMap.delete(o)}muteRemoteAudio(e,r){return 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 o.code!==ne.OPERATION_ABORT&&this._remoteAudioMuteMap.delete(e),o}})}setRemoteAudioVolume(e,r){if(e==="*"){this._remoteAudioVolumeMap.set("*",r),this._remoteAudioVolumeMap.forEach((s,n)=>this._remoteAudioVolumeMap.set(n,r));let o=[...this._room.remotePublishedUserMap.values()];for(let s of o)this._remoteAudioVolumeMap.set(s.userId,r),s.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:r},track:s.remoteAudioTrack})}else if(e){let o=this._room.remotePublishedUserMap.get(e);this._remoteAudioVolumeMap.set(e,r),o&&o.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:r},track:o.remoteAudioTrack})}}startPlugin(e,r){return 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){if(this.listeners(e).includes(r))return this;if(this._log.debug("on",e),super.on(e,r,o),this._eventListened.add(e),this.listeners(ie.AUDIO_FRAME).length>0){let{audioFrameEventConfigMap:s}=this.room.audioManager;s.get("")||s.set("",{enable:!0}),this._localAudioTrack&&this.room.audioManager.handleLocalTrackStarted({userId:"",room:this.room})}return this}emit(e,...r){try{aT.has(e)||this._log.debug(`emit ${e} ${JSON.stringify(r)}`)}catch(o){}return super.emit(e,...r)}off(e,r,o){if(this._log.debug("off",e),e==="*"?(this._eventListened.clear(),this.removeAllListeners()):super.off(e,r,o),(e===pe.EVENT.AUDIO_FRAME||e==="*")&&this.listeners(pe.EVENT.AUDIO_FRAME).length===0){let{getPCMAbortCtrlMap:s}=this.room.audioManager;s.forEach(n=>{n==null||n.abort("off")}),s.clear()}return this}getAudioTrack(e={userId:"",streamType:"main"}){let r,o=null,s="main",n=!1;if(Oe(e)?r=e:(r=e.userId,n=e.processed===!0,e.streamType&&(s=e.streamType)),r){let a=this._room.remotePublishedUserMap.get(r);a&&(o=a.remoteAudioTrack)}else o=s==="sub"?this._localScreenAudioTrack:this._localAudioTrack;return o?n&&o.outMediaTrack&&o.outMediaTrack!==o.mediaTrack?o.outMediaTrack.clone():o.mediaTrack:null}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:r="",streamType:o="main",processed:s=!1}=e,n=null;if(r==="")o==="main"&&this._localVideoTrack&&(n=this._localVideoTrack),o==="sub"&&this._localScreenTrack&&(n=this._localScreenTrack);else{let a=this._room.remotePublishedUserMap.get(r);a&&(n=o==="main"?a.remoteVideoTrack:a.remoteAuxiliaryTrack)}return n?s&&n.outMediaTrack&&n.outMediaTrack!==n.mediaTrack?n.outMediaTrack.clone():n.mediaTrack:null}getVideoSnapshot(e={}){let{userId:r,streamType:o="main"}=e;if(r){let s=this._room.remotePublishedUserMap.get(r);if(o==="main"&&(s!=null&&s.muteState.hasVideo))return s.remoteVideoTrack.getVideoFrame();if(o==="sub"&&(s!=null&&s.muteState.hasAuxiliary))return s.remoteAuxiliaryTrack.getVideoFrame()}else{if(o==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(o==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(e){var r,o;this._speakerId=e,(r=this._localAudioTrack)==null||r.setAudioOutput(e),(o=this._localScreenAudioTrack)==null||o.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(s=>s.remoteAudioTrack.setAudioOutput(e))}setCurrentSpeaker(e){return y(this,null,function*(){(yield Co()).forEach(o=>{o.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(ie.DEVICE_CHANGED,{type:"speaker",action:"active",device:o}),kt=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: ${or}/en/TRTC.html#.setCurrentSpeaker`)})}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return y(this,null,function*(){var a;let{userId:r}=e;if(this._remoteAudioConfigMap.has(r)){this._log.warn(`remote audio has already started. userId:${r}`);return}let o=this._room.remotePublishedUserMap.get(r);if(!o)return;let s={},n=o.remoteAudioTrack;n.on("decode-failed",d=>{this.emit(ie.ERROR,new oe({code:ne.OPERATION_FAILED,extraCode:5508,message:"audio decode failed"}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId);try{let d=(a=this._remoteAudioVolumeMap.get(r))!=null?a:this._remoteAudioVolumeMap.get("*"),l=Fe(d)?d:100;this._remoteAudioConfigMap.set(r,e),yield this._room.subscribe(n),ye(Ae(n,"decode-failed"),Je(Ae(n,ue.INIT)),Le(()=>{this.startPlugin(Pc.Name,{track:n,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:s,track:n}),U.emit("115",{userId:r,room:this.room}),n.outMediaTrack&&this.room.audioManager.updateAudioReference({type:"add",audioReference:n.outMediaTrack,refId:`ra-${r}`})}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}`),U.emit("116",{userId:e.userId,room:this.room}),this.room.audioManager.updateAudioReference({type:"remove",refId:`ra-${e.userId}`})})}_enableVideoDecodeFallback(e,r){let o=this._room.videoDecodeFallbackType;if(!o||!this._plugins.has("TRTCVideoDecoder"))return;e.log.debug("remote video will fall back when decode failed",e.id);let s;ye(Ae(e,"decode-failed"),Je(Ae(e,ue.INIT)),Ds(()=>{this._room.downlinkVideoCodec!=="h265"&&this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:o})}),qi(Ae(e,"decode-downgrade-state-changed")),Le(n=>{s=n.state,this.emit(ie.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,_e(Y({},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),O(e)&&s&&s.view&&!un(r)){let a=mn(s.view);a.length>0&&(yield o.play(a,r))}if(!O(e)){let a=mn(e);a.length>0?yield o.play(a,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){}if(O(e.muted)||r.setPlayerMute(e.muted),O(e.volume)||r.setAudioVolume(e.volume/100),r instanceof li&&r.mediaTrack){let n=e.muted===!1&&!O(e.volume)&&e.volume>0?"add":"remove";this.room.audioManager.updateAudioReference({type:n,audioReference:r.mediaTrack,refId:"em"})}else if(r instanceof zi){let n=e.muted?0:e.volume;if(O(n))return;this.room.audioManager.updateAudioReference({type:"updateVolume",refId:`ra-${r.userId}`,volume:e.volume})}})}_listenOutputTrackChanged(e){e.listeners("output-media-track-changed").length===0&&e.on("output-media-track-changed",()=>this._emitTrackEvent(e,!1))}_emitTrackEvent(e,r=!0){let o=e.isRemote?e.userId:"";e.outMediaTrack&&(r&&this._mediaTrackMap.get(e.outMediaTrack)===o||(this._mediaTrackMap.set(e.outMediaTrack,o),this.emit(ie.TRACK,{userId:o,streamType:fi(e.streamType),track:e.outMediaTrack,sourceTrack:e.mediaTrack})))}_checkTrackToPublish(){var r,o,s;let e=[];if((r=this._localAudioConfig)!=null&&r.publish&&this._localAudioTrack&&e.push(this._localAudioTrack),(o=this._localVideoConfig)!=null&&o.publish&&this._localVideoTrack&&e.push(this._localVideoTrack),(s=this._localScreenConfig)!=null&&s.publish&&(this._localScreenTrack&&e.push(this._localScreenTrack),this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack),this._checkScreenAudioEchoCancellation(this._localScreenTrack,this._localScreenAudioTrack)),e.length!==0)return Promise.all(e.map(n=>this._room.publish(n).catch(()=>{})))}_observeView({remoteTrack:e,view:r,receiveWhenViewVisible:o,viewRoot:s}){if(O(r)||O(o))return;let n=this._remoteVideoConfigMap.get(`${e.userId}_${fi(e.streamType)}`);if(!n)return;let a=n.observer||void 0;if(r===null||mt(r)&&r.length===0||!o){a==null||a.disconnect(),e.isSubscribed||(this._log.info("_observeView observer disconnect, resubscribe",e.userId,e.strMediaType),this._room.subscribe(e).catch(()=>{}));return}let l=n.visibleViewMap||new Map,p=-1;(!a||a.root!==s)&&(a==null||a.disconnect(),l.clear(),a=new IntersectionObserver(g=>{g.forEach(A=>{l.set(A.target,A.isIntersecting),e.log.info(`view ${A.target.id} is${A.isIntersecting?"":" not"} visible`)}),clearTimeout(p),p=window.setTimeout(()=>{[...l.values()].find(R=>R)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:s}));let f=new Set(mn(r));l.forEach((g,A)=>{f.has(A)||(a.unobserve(A),l.delete(A))}),f.forEach(g=>{l.set(g,!0),a.observe(g)}),a.takeRecords().forEach(g=>{l.set(g.target,g.isIntersecting)}),n.visibleViewMap=l,n.observer=a}_exitRoom(){return y(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),this._clearRemoteTracks()})}_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 Promise.all(r.map(o=>this._room.unpublish(o).catch(()=>{})))}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(((e=this._localScreenAudioTrack.trackSettings)==null?void 0:e.echoCancellation)===!1&&this.stopPlugin("AudioProcessor"),this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),At(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_checkScreenAudioEchoCancellation(e,r){return y(this,null,function*(){var s,n;if(!e||!r)return;let o=(s=e.trackSettings)==null?void 0:s.displaySurface;if(((n=r.trackSettings)==null?void 0:n.echoCancellation)===!1&&(o==="monitor"||o==="browser"&&e.isShareCurrentTab)){this._log.warn("echoCancellation of screen audio track is disable. Try starting audioProcessor plugin");try{yield this.startPlugin("AudioProcessor",{sdkAppId:Number(this.room.sdkAppId),userId:this._room.userId,userSig:this.room.userSig,isScreenAudioNeedAudioProcess:!0,isLocalAudioNeedAudioProcess:!1})}catch(a){this._log.warn("start audioProcessor plugin failed: ",a)}}})}_onLocalTrackCaptured({track:e}){e.kind==="audio"&&(!kt||xn(kt))&&(this._initActiveSpeaker(),U.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return y(this,null,function*(){if(kt&&!xn(kt))this.emit(ie.DEVICE_CHANGED,{type:"speaker",action:"active",device:kt});else{let e=yield Co();e[0]&&!xn(e[0])?(kt=e[0],this.emit(ie.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):U.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:_e(Y({seiPayloadType:243},r),{small:!!((s=this._localVideoTrack)!=null&&s.small)})}),X.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var r,o;(o=(r=this._room).sendCustomMessage)==null||o.call(r,e),X.addCount({key:500001,useUV:!0})}callExperimentalAPI(e,r){return y(this,null,function*(){return this._log.info(`callExperimentalAPI(${e}, ${JSON.stringify(r)})`),IT.call(e,Y({trtcInstance:this},r))})}static setLogLevel(e,r){F.setLogLevel(e),O(r)||(r?F.enableUploadLog():F.disableUploadLog())}static isSupported(){return fu(pe.frameWorkType)}static getPermissions(o){return y(this,arguments,function*({request:e=!0,types:r=["camera","microphone"]}){e&&(yield Lc.request(r).catch(a=>{var d;return F.error(`getPermissions request failed, error: ${(d=a==null?void 0:a.message)!=null?d:a}`)}));let[s,n]=yield Promise.all([Lc.get("camera"),Lc.get("microphone")]);return{camera:s,microphone:n}})}static getCameraList(e=!0){return dr(e)}static getMicrophoneList(e=!0){return cr(e)}static getSpeakerList(e=!0){return Co(e)}static setCurrentSpeaker(e){return y(this,null,function*(){if(at&&(e===Vs.SPEAKER||e===Vs.HEADSET)){let o=yield pe.getMicrophoneList(),s="";if(o.forEach(n=>{n.label===e&&(s=n.deviceId)}),!s)return;kc.forEach(n=>y(this,null,function*(){n._localAudioTrack&&(yield n.updateLocalAudio({option:{microphoneId:s}}))}));return}(yield Co()).forEach(o=>{o.deviceId===e&&(kc.forEach(s=>{s._setCurrentSpeaker(e),s.emit(ie.DEVICE_CHANGED,{type:"speaker",action:"active",device:o})}),kt=o)})})}static _addKVStat({type:e,key:r,value:o,base:s,useUV:n,version:a,max:d}){switch(a&&(Ts.version=a),e){case"count":Ts.addCount({key:r,useUV:n});break;case"enum":Ts.addEnum({key:r,value:o,useUV:n});break;case"number":Ts.addNumber({key:r,value:o,split:s,max:d});break}}};m(pe,"VERSION",sf),m(pe,"_loggerManager",F),m(pe,"EVENT",ie),m(pe,"ERROR_CODE",ne),m(pe,"TYPE",Vs),m(pe,"frameWorkType",30),Z([nt({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"}})})],pe.prototype,"use",1),Z([$t(Ot.TRTC.enterRoom),Uo("room",([e],[r])=>(e.roomId||e.strRoomId)===(r.roomId||r.strRoomId)&&e.userId===r.userId&&e.sdkAppId===r.sdkAppId),Pe(e=>function(r){return this._log.setUserId(r.userId),this._log.setSdkAppId(r.sdkAppId),e.call(this,r)}),nt()],pe.prototype,"enterRoom",1),Z([nt()],pe.prototype,"exitRoom",1),Z([$t(Ot.TRTC.switchRoom),nt(),Ou()],pe.prototype,"switchRoom",1),Z([$t(Ot.TRTC.switchRole),Bs("room",{merge:(e,r)=>r}),nt()],pe.prototype,"switchRole",1),Z([nt()],pe.prototype,"destroy",1),Z([$t(Ot.TRTC.startLocalAudio),Uo("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)}),nt()],pe.prototype,"startLocalAudio",1),Z([$t(Ot.TRTC.updateLocalAudio),Bs("audio",{debounce:{delay:200,getKey:()=>`${AT}-localAudio`,isNeedToDebounce:e=>{var r;return!O((r=e.option)==null?void 0:r.captureVolume)}}}),nt()],pe.prototype,"updateLocalAudio",1),Z([Vo("audio"),nt()],pe.prototype,"stopLocalAudio",1),Z([$t(Ot.TRTC.startLocalVideo),Uo("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)}),nt()],pe.prototype,"startLocalVideo",1),Z([$t(Ot.TRTC.updateLocalVideo),Bs("video"),nt()],pe.prototype,"updateLocalVideo",1),Z([Vo("video"),nt()],pe.prototype,"stopLocalVideo",1),Z([$t(Ot.TRTC.startScreenShare),Uo("screen",()=>!0),nt()],pe.prototype,"startScreenShare",1),Z([$t(Ot.TRTC.updateScreenShare),Bs("screen"),nt()],pe.prototype,"updateScreenShare",1),Z([nt()],pe.prototype,"stopScreenShare",1),Z([$t(Ot.TRTC.startRemoteVideo),Uo(e=>`v${e.userId}${e.streamType}`,()=>!0),nt({getRemoteId:e=>`${e.userId}_${e.streamType}`})],pe.prototype,"startRemoteVideo",1),Z([$t(Ot.TRTC.updateRemoteVideo),Bs(e=>`v${e.userId}${e.streamType}`),nt({getRemoteId:e=>`${e.userId}_${e.streamType}`})],pe.prototype,"updateRemoteVideo",1),Z([$t(Ot.TRTC.stopRemoteVideo),Pe(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)})}),nt({getRemoteId:e=>`${e.userId}_${e.streamType}`})],pe.prototype,"stopRemoteVideo",1),Z([Vo(e=>`v${e.userId}${e.streamType}`)],pe.prototype,"_stopRemoteVideo",1),Z([$t(...Ot.TRTC.muteRemoteAudio),nt({getRemoteId:e=>e})],pe.prototype,"muteRemoteAudio",1),Z([nf(...Ot.TRTC.setRemoteAudioVolume),pT(200,e=>e),nt({getRemoteId:e=>e})],pe.prototype,"setRemoteAudioVolume",1),Z([_l("start"),No(e=>{var r;return(r=e.afterStart)==null?void 0:r.call(e)}),Uo((e,r)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(r)),nt({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>dh[e.getName()],ignoreLog:e=>e.getName()==="Debug",ignoreErrorLog:e=>e.getName()==="AudioProcessor"})],pe.prototype,"startPlugin",1),Z([_l("update"),Bs((e,r)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(r),{merge:(e,r)=>(Br(e[1],r[1]),e)}),nt({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>uh[e.getName()]})],pe.prototype,"updatePlugin",1),Z([_l("stop"),Vo((e,r)=>{if(e.disableRandomCall)return null;let o=e.getGroup(r),s=e.getAlias();return o==="*"?new RegExp(`${s}.*`):s+o}),nt({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>lh[e.getName()]})],pe.prototype,"stopPlugin",1),Z([nf(...Ot.TRTC.enableAudioVolumeEvaluation)],pe.prototype,"enableAudioVolumeEvaluation",1),Z([nt()],pe.prototype,"getVideoSnapshot",1),Z([nt()],pe.prototype,"_setCurrentSpeaker",1),Z([Uo(e=>`a${e.userId}`,()=>!0)],pe.prototype,"_startRemoteAudio",1),Z([Pe(e=>function(r){return y(this,null,function*(){return r.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(o=>this._stopRemoteAudio(_e(Y({},r),{userId:o.userId})).catch(()=>{}))):e.call(this,r)})}),Vo(e=>`a${e.userId}`)],pe.prototype,"_stopRemoteAudio",1),Z([Vo("room")],pe.prototype,"_exitRoom",1),Z([Vo("screen")],pe.prototype,"_stopScreenShare",1),Z([$t(...Ot.TRTC.sendSEIMessage),Kp({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...e)=>e[0].byteLength})],pe.prototype,"sendSEIMessage",1),Z([$t(Ot.TRTC.sendCustomMessage),Kp({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],pe.prototype,"sendCustomMessage",1),Z([Fo()],pe,"create",1),Z([$t(Ot.TRTC.create)],pe,"_create",1),Z([Fo()],pe,"setLogLevel",1),Z([Fo()],pe,"isSupported",1),Z([Fo()],pe,"getPermissions",1),Z([Fo()],pe,"getCameraList",1),Z([Fo()],pe,"getMicrophoneList",1),Z([Fo()],pe,"getSpeakerList",1);var gf=pe,Qn=gf;var wl=class{constructor(t,e){m(this,"_flag");m(this,"terminalType");m(this,"userId");m(this,"tinyId");m(this,"role");m(this,"remoteAudioTrack");m(this,"remoteVideoTrack");m(this,"remoteAuxiliaryTrack");this.userId=e.userId||"",this.tinyId=e.tinyId||"",this.role=e.role||"audience",this.terminalType=e.terminalType,this.remoteAudioTrack=new zi(t,this),this.remoteVideoTrack=new xo(t,this),this.remoteAuxiliaryTrack=new tl(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 cs(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 Ef=class{constructor(){m(this,"_set",new Set);U.on(B.LEAVE_SUCCESS,this.delete,this),U.on(B.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess,this)}add({room:t,roomId:e}){if(t.scene==="rtc")return;let r=this.getKey(t.userId,e||t.roomId,t.sdkAppId,t.useStringRoomId);this._set.add(r)}delete({room:t,roomId:e}){if(t.scene==="rtc")return;let r=this.getKey(t.userId,t.roomId||e,t.sdkAppId,t.useStringRoomId);this._set.delete(r)}getKey(t,e,r,o){return`${r}_${e}_${t}_${o}`}isJoined({userId:t,roomId:e,sdkAppId:r,room:o}){return o.scene==="rtc"?!1:this._set.has(this.getKey(t,e,r,o.useStringRoomId))}handleSwitchRoomSuccess({room:t,currentRoomId:e,targetRoomId:r}){t.scene!=="rtc"&&(this._set.delete(this.getKey(t.userId,e,t.sdkAppId,t.useStringRoomId)),this._set.add(this.getKey(t.userId,r,t.sdkAppId,t.useStringRoomId)))}};function YR(){return y(this,null,function*(){let i,t;try{let A=yield cr();i=A&&A.length}catch(A){}try{let A=yield dr();t=A&&A.length}catch(A){}let e={microphone:i,camera:t},{isH264EncodeSupported:r,isVp8EncodeSupported:o,isH264DecodeSupported:s,isVp8DecodeSupported:n,isH265EncodeSupported:a,isH265DecodeSupported:d}=this.checkSystemResult.detail,l=bo.basis(),p={webRTC:l.isWebRTCSupported,getUserMedia:l.isGetUserMediaSupported,webSocket:l.isWebSocketsSupported,screenShare:l.isScreenShareSupported,webAudio:l.isWebAudioSupported,h264Encode:r,h264Decode:s,vp8Encode:o,vp8Decode:n,h265Encode:a,h265Decode:d},f={browser:l.browser,os:l.os,trtc:p,devices:e},g={isWebCodecSupported:l.isWebCodecSupported,isMediaSessionSupported:l.isMediaSessionSupported,isWebTransportSupported:l.isWebTransportSupported};qe.uploadEvent({log:`trtcstats-${JSON.stringify(f)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(f)}`),qe.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(g)}`,userId:this.userId}),Ah()})}function bT(){return Pe(i=>{let t=new Ef;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 se({code:q.INVALID_OPERATION,message:We({key:He.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:s,sdkAppId:this.sdkAppId,room:this}))throw new se({code:q.INVALID_OPERATION,message:We({key:He.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}`),U.emit(B.JOIN_START,{room:this,roomId:s,params:e});let n=si.getEnv();n||(n=vi.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(gd.OLD_CLOUD_LADDER)?n=vi.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(gd.WEBRTC)&&(n=vi.WEBRTC))),qe.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:s}),bo.checkSystemRequirementsInternal(o).then(a=>{this.checkSystemResult=a,YR.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!si.getEnv()&&(yield this.schedule(e,o));let a=yield i.call(this,e,r,o);return this.roomId=s,this._joinedTimestamp=si.performanceNow(),U.emit(B.JOIN_SUCCESS,{room:this}),o===30&&!e.component&&qe.uploadEvent({log:`stat-conv-${Number(jr)}-${location.hostname}`,userId:this.userId}),a}catch(a){throw t.delete({room:this,roomId:s}),U.emit(B.JOIN_FAILED,{room:this,error:a}),a}})}})}var RT=()=>Pe(i=>function(...t){return y(this,null,function*(){U.emit(B.LEAVE_START,{room:this}),yield i.call(this,...t),U.emit(B.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function vT(){return Pe(i=>function(...t){return y(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(t=t.filter(r=>r.outMediaTrack&&r.state==="ready"),!t.length))return;U.emit("61",{room:this});let e=i.apply(this,t);return Promise.all(t.map(r=>r.publish(this,e)))})})}function CT(){return Pe(i=>function(...t){let e=i.apply(this,t);return t.forEach(r=>r.unpublish()),e})}function NT(){return Pe(i=>function(...t){let e=i.apply(this,t);return t.forEach(r=>!r.isSubscribed&&r.subscribe(e)),e})}function ZR({fn:i,context:t}){return function(...e){try{let r=i.apply(t,e);return fo(r)?r.catch(o=>F.error(`${i.name}() error observed ${o}`)):r}catch(r){F.error(`${i.name}() error observed ${r}`)}}}var Ol=class{constructor(t){m(this,"_frameWorkType");m(this,"_component");m(this,"_language");m(this,"connectionType");m(this,"_room");m(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,reportToken:void 0});m(this,"_keyPrefix");m(this,"_log");m(this,"_intervalId");m(this,"_firstPublishedUserList");m(this,"_networkQuality");m(this,"_basicInfo");m(this,"_pathJoinRoom");m(this,"_pathLeaveRoom");m(this,"_pathMainVideoMap");m(this,"_pathMainAudioMap");m(this,"_pathAuxiliaryMap");m(this,"_remoteStreamStatMap");m(this,"_localStreamStat");m(this,"_eventMap",new Map);m(this,"_captureCostSum",0);m(this,"_captureCostCount",0);m(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=F.createLogger({parent:this._room.getLogger(),id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(e=>{e.startsWith("handle")&&Xe(this[e])&&(this[e]=ZR({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:pt,uint32_os_type:15,string_device_name:"",string_http_user_agent:navigator.userAgent,string_os_version:"",uint32_avg_rtt:0,uint32_avg_up_loss:0,uint32_scene:this._room.scene==="live"?1:0,uint32_joining_duration:0,uint32_networkType:0,uint32_framework:this._frameWorkType,uint32_component:this._component,uint32_connection_type:this.connectionType,uint32_caller_coding_language:this._language,string_domain:location.hostname},this._pathJoinRoom={uint64_start_time:0,uint64_send_request_acc_ip_cmd_start_time:0,uint64_send_request_acc_ip_cmd_end_time:0,uint64_send_request_enter_room_cmd_start_time:0,uint64_send_request_enter_room_cmd_end_time:0,uint64_send_first_video_frame_time:0,uint64_recv_userlist_time:0,uint64_end_time:0,int32_send_request_acc_ip_cmd_ret:0,int32_send_request_enter_room_cmd_ret:0,int32_end_ret:0},this._pathLeaveRoom={uint64_start_time:0,uint64_send_request_exit_room_cmd_start_time:0,uint64_send_request_exit_room_cmd_end_time:0,uint64_end_time:0,int32_send_request_exit_room_cmd_ret:0,int32_end_ret:0},this._localStreamStat={totalVideoBitrate:0,totalVideoFPS:0,totalVideoHeight:0,totalVideoWidth:0,totalAudioLevel:0,videoCount:0,audioLevelCount:0,publishStartTime:0,statsToReport:{uint32_audio_capture_db:0,uint32_video_big_capture_fps:0,uint32_video_big_bitrate:0,uint32_video_big_resolution:0,uint32_audio_capture_thread_health_zero_cnt:0,uint32_after3a_silence_duration:0}},this._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,hs().then(()=>{this._basicInfo.string_os_version=Li(),this._basicInfo.string_device_name=ps()||this._basicInfo.string_os_version})}addEvent(t,e){return this._eventMap.set(t,e),U.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(B.JOIN_START,this.handleJoinStart).addEvent(B.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(B.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(B.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(B.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(B.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(B.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(B.JOIN_FAILED,this.handleJoinFailed).addEvent(B.LEAVE_START,this.handleLeaveStart).addEvent(B.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(B.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(B.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(B.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(B.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(B.PUBLISH_START,this.handlePublishStart).addEvent(B.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(B.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(B.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(B.PLAY_TRACK_START,this.handlePlayStart).addEvent(B.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(B.PLAYER_STATE_CHANGED,({track:t,state:e,type:r})=>{!t.isRemote||!this.hitTest(t.room)||e==="PLAYING"&&(r===M.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))}).addEvent(B.SWITCH_ROOM_START,this.handleSwitchRoomStart).addEvent(B.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess).addEvent(B.SWITCH_ROOM_FAILED,this.handleSwitchRoomFailed).addEvent(B.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(B.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(B.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(B.REMOTE_PUBLISH_STATE_CHANGED,({room:t,prevMuteState:e,muteState:r})=>{if(!this.hitTest(t))return;let o=e.hasAudio||e.hasVideo||e.hasSmall,s=e.hasAuxiliary,n=r.hasAudio||r.hasVideo||r.hasSmall,a=r.hasAuxiliary;!o&&n&&this.handleRemoteStreamAdded(r.userId,"main"),!s&&a&&this.handleRemoteStreamAdded(r.userId,"auxiliary")}).addEvent(B.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)=>U.off(e,t)),this._eventMap.clear()}destroy(){this.uninstallEvents(),gt.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&&(O(t.params.frameWorkType)||(this._frameWorkType=t.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),O(t.params.component)||(this._component=t.params.component,this._basicInfo.uint32_component=this._component),O(t.params.language)||(this._language=t.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleJoinScheduleSuccess({room:t,detailCost:e}){if(this.hitTest(t)&&e){let{totalCost:r,local:o,dns:s,tcp:n,tls:a,request:d,response:l}=e;this._pathJoinRoom.int32_schedule_cost=r,this._pathJoinRoom.int32_schedule_local=o,this._pathJoinRoom.int32_schedule_dns=s,this._pathJoinRoom.int32_schedule_tcp=n,this._pathJoinRoom.int32_schedule_tls=a,this._pathJoinRoom.int32_schedule_request=d,this._pathJoinRoom.int32_schedule_response=l}}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 se?Number(e.getExtraCode()||e.getCode()):q.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}handleJoinSendCMD(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now())}handleJoinReceivedCMDResponce(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=t.code,t.code!==0&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}handleJoinSuccess(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_end_time===0&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=t.room.getSignalInfo())}handleJoinFailed({room:t,error:e}){this.hitTest(t)&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret===0&&(this._pathJoinRoom.int32_end_ret=e.code||this._pathJoinRoom.int32_send_request_enter_room_cmd_ret||this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret),setTimeout(()=>{this.report()}))}handleReceivedPublishUserList(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_recv_userlist_time===0&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=t.publishedUserList||[])}handleSendFirstVideoFrame({room:t}){this.hitTest(t)&&this._pathJoinRoom.uint64_send_first_video_frame_time===0&&this._pathJoinRoom.uint64_start_time!==0&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now())}handleLeaveStart(t){this.hitTest(t.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(t){var e;if(this.hitTest(t.room)&&this._pathLeaveRoom.uint64_end_time===0){if(this._pathLeaveRoom.uint64_end_time=Date.now(),this._pathJoinRoom.uint64_end_time!==0){this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time;let r=(e=this._room.audioManager.localAudioTrack)==null?void 0:e.after3aSilenceStartTime;r&&(this._localStreamStat.statsToReport.uint32_after3a_silence_duration=Te()-r)}else this._log.warn("pathJoinRoom endTime is 0");this.report()}}handleLeaveSendCMD(t){this.hitTest(t.room)&&(this._pathLeaveRoom.uint64_send_request_exit_room_cmd_start_time=Date.now(),this._pathLeaveRoom.uint64_send_request_exit_room_cmd_end_time=Date.now())}handleSwitchRoomStart(t){if(this.hitTest(t.room)){let e=Date.now();this.report().then(()=>{this._pathJoinRoom.uint64_start_time=e,this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=e})}}handleSwitchRoomSuccess({room:t}){if(this.hitTest(t)&&this._pathJoinRoom.uint64_end_time===0){let e=Date.now();this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=e,this._pathJoinRoom.uint64_end_time=e,this._pathJoinRoom.int32_end_ret}}handleSwitchRoomFailed({room:t,error:e}){if(this.hitTest(t)){let r=Date.now();this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=r,this._pathJoinRoom.uint64_end_time=r,e&&(this._pathJoinRoom.int32_end_ret=e instanceof se?Number(e.getExtraCode()||e.getCode()):q.UNKNOWN)}}handleRemoteStreamAdded(t,e){var o;let r=`${t}_${e}`;if(!this._remoteStreamStatMap.has(r)){let s={userId:t,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:_e(Y({},KR),{msg_user_info:new Uc({userId:t,tinyId:(o=this._room.remotePublishedUserMap.get(t))==null?void 0:o.tinyId,role:20})})};s.statsToReport.uint32_stream_type=e==="main"?2:7,this._remoteStreamStatMap.set(r,s)}}handleSubscribeStart({room:t,remotePublishedUser:e,streamType:r,subscribeState:o}){if(!this.hitTest(t))return;let{userId:s,tinyId:n,role:a}=e,d=new Uc({userId:s,tinyId:n,role:a==="anchor"?20:21}),l=Date.now(),p=`${s}_${r}`,f=this._remoteStreamStatMap.get(p);f&&f.subscribeStartTime===0&&(f.subscribeStartTime=l),r==="main"?(e.muteState.hasVideo&&(o.video||o.smallVideo)&&!this._pathMainVideoMap.has(p)&&this._pathMainVideoMap.set(p,{statsToReport:{msg_user_info:d,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:s,sendSubscribeCMDTime:l}),e.muteState.hasAudio&&o.audio&&!this._pathMainAudioMap.has(p)&&this._pathMainAudioMap.set(p,{statsToReport:{msg_user_info:d,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:s,sendSubscribeCMDTime:l})):e.muteState.hasAuxiliary&&o.auxiliary&&!this._pathAuxiliaryMap.has(p)&&this._pathAuxiliaryMap.set(p,{sendSubscribeCMDTime:l})}handleSubscribed({room:t,remotePublishedUser:e,streamType:r}){if(this.hitTest(t)){let o=`${e.userId}_${r}`,s=this._remoteStreamStatMap.get(o);s&&s.subscribedTime===0&&(s.subscribedTime=Date.now())}}handlePlayStart({track:t}){if(!t.isRemote||!this.hitTest(t.room))return;let e=`${t.userId}_${t.streamType}`,r=this._remoteStreamStatMap.get(e);(r==null?void 0:r.playStreamTime)===0&&(r.playStreamTime=Date.now())}handleVideoLoadedData({track:t}){if(!t.isRemote||!this.hitTest(t.room))return;let e=`${t.userId}_${t.streamType}`,r=this._pathMainVideoMap.get(e);r&&r.statsToReport.uint64_combine_first_frame_time===0&&(r.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(t){let e=`${t.userId}_${t.streamType}`,r=Date.now(),o=this._pathMainVideoMap.get(e),s=this._remoteStreamStatMap.get(e);if(s){let{statsToReport:n}=s;if(!n.uint32_video_render_first&&t.streamType==="main"?this.hasVideoFlag(t.userId):this.hasAuxFlag(t.userId)){let a=r-this._pathJoinRoom.uint64_start_time;n.uint32_video_render_first=a,X.addNumber({key:516820,value:a})}}(o==null?void 0:o.statsToReport.uint64_render_first_frame_time)===0&&(o.statsToReport.uint64_render_first_frame_time=r)}handleAudioPlaying(t){let e=`${t.userId}_${t.streamType}`,r=this._pathMainAudioMap.get(e);r&&r.statsToReport.uint64_play_first_frame_time===0&&(r.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(t){this.hitTest(t.room)&&(this._networkQuality.totalUplinkLoss+=t.uplink.loss,this._networkQuality.totalUplinkRTT+=t.uplink.rtt,this._networkQuality.count++,t.downlinks.forEach(({rtt:e,loss:r,userId:o,videoDelay:s,audioDelay:n})=>{let a=this._networkQuality.totalDownlinkRTTAndLossMap.get(o);if(a)a.totalRTT+=e,a.totalLoss+=r,s&&(a.totalVideoDelay=(a.totalVideoDelay||0)+s,a.videoDelayCount=(a.videoDelayCount||0)+1),n&&(a.totalAudioDelay=(a.totalAudioDelay||0)+n,a.audioDelayCount=(a.audioDelayCount||0)+1),a.count++;else{let d,l,p,f;s&&(l=s,p=1),n&&(d=n,f=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(o,{totalRTT:e,totalLoss:r,count:1,totalAudioDelay:d,totalVideoDelay:l,audioDelayCount:f,videoDelayCount:p})}}))}handleHeartbeatStats(t){var e;if(this.hitTest(t.room)){let{msg_device_info:r,msg_up_stream_info:o,msg_down_stream_info:s}=t.report;if(o.msg_video_status[0]){let{uint32_video_codec_bitrate:n,uint32_video_enc_fps:a,uint32_video_width:d,uint32_video_height:l}=o.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=n,this._localStreamStat.totalVideoFPS+=a,this._localStreamStat.totalVideoWidth+=d,this._localStreamStat.totalVideoHeight+=l,this._localStreamStat.videoCount++}if(o.msg_audio_status){let{uint32_audio_level:n}=o.msg_audio_status;Math.floor(n/Fi*100)>0&&(this._localStreamStat.totalAudioLevel+=n/Fi,this._localStreamStat.audioLevelCount++)}s.forEach(n=>{let{msg_user_info:a,msg_audio_status:d,msg_video_status:l}=n,p=a.str_identifier,f=this._room.remotePublishedUserMap.get(p);if(l.forEach(g=>{let A=g.uint32_video_stream_type===2,R=g.uint32_video_stream_type===7,N=`${p}_${A?"main":"auxiliary"}`,C=this._remoteStreamStatMap.get(N);if(C&&(A&&(f!=null&&f.remoteVideoTrack.isSubscribed)||R&&(f!=null&&f.remoteAuxiliaryTrack))){C.totalVideoFPS+=g.uint32_video_receive_fps,C.totalVideoBitrate+=g.uint32_video_codec_bitrate,C.videoCount++,C.statsToReport.uint32_video_width===0&&(C.statsToReport.uint32_video_width=g.uint32_video_width),C.statsToReport.uint32_video_height===0&&(C.statsToReport.uint32_video_height=g.uint32_video_height);let P=A?f.remoteVideoTrack:f.remoteAuxiliaryTrack;P.stat.jitterBufferDelay&&(C.videoJitterBufferDelay=P.stat.jitterBufferDelay),P.stat.framesReceived&&(C.statsToReport.uint32_video_consume_render_rate=Math.floor(P.stat.framesDecoded/P.stat.framesReceived*ri(10,6)))}}),!un(d)){let g=`${p}_main`,A=this._remoteStreamStatMap.get(g);this._remoteStreamStatMap.has(g)&&A&&f!=null&&f.remoteAudioTrack.isSubscribed&&(A.totalAudioBitrate+=d.uint32_audio_codec_bitrate,A.audioCount++,f.remoteAudioTrack.stat.jitterBufferDelay&&(A.audioJitterBufferDelay=f.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(d.uint32_audio_level/Fi*100)>0&&(A.totalAudioLevel+=d.uint32_audio_level/Fi,A.audioLevelCount++),d.uint32_audio_block_time&&(A.statsToReport.uint32_audio_block_time+=d.uint32_audio_block_time))}}),r.uint32_audio_capture_cost&&(this._captureCostSum+=r.uint32_audio_capture_cost,this._captureCostCount+=1,this._captureCostCount>=100&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0)),r.uint32_audio_capture_cost===0&&((e=this._room.audioManager.localAudioTrack)==null?void 0:e.muted)===!1&&(this._localStreamStat.statsToReport.uint32_audio_capture_thread_health_zero_cnt+=1)}}handlePublishStart({room:t}){this.hitTest(t)&&this._localStreamStat.publishStartTime===0&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart({track:t}){t.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),t.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess({track:t}){t.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=0,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),t.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=0,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed({track:t,error:e}){let o={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[e.name]||(e instanceof se?e.getExtraCode()||e.getCode():q.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&tn)>=0}hasAudioFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&rn)>=0}hasAuxFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&fa)>=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:p,count:f,audioDelayCount:g,videoDelayCount:A,totalAudioDelay:R,totalVideoDelay:N}=o;t.statsToReport.uint32_avg_down_loss=Math.floor(p/f),g&&R&&(t.statsToReport.uint32_audio_network_p2p_delay=Math.floor(R/g),t.audioJitterBufferDelay&&(t.statsToReport.uint32_p2p_delay=Math.floor(t.statsToReport.uint32_audio_network_p2p_delay+t.audioJitterBufferDelay))),A&&N&&(t.statsToReport.uint32_video_network_p2p_delay=Math.floor(N/A))}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,M.AUDIO),t.statsToReport.uint32_video_play_time=s.getDuration(e,M.VIDEO)),t.statsToReport.uint32_video_render_first&&(t.statsToReport.uint32_video_render_first=Math.min(t.statsToReport.uint32_video_render_first,$s));let{badCaseDetector:n}=this._room,{dataFreeze:a,count:d}=n.getDataFreezeDuration(e),{renderFreeze:l}=n.getRenderFreezeDuration(e);t.statsToReport.uint32_video_block_count=d,t.statsToReport.uint32_video_block_time=Math.min(a,t.statsToReport.uint32_video_play_time),t.statsToReport.uint32_video_external_block_time=Math.min(l,t.statsToReport.uint32_video_play_time),t.statsToReport.uint32_audio_block_time=Math.min(t.statsToReport.uint32_audio_block_time,t.statsToReport.uint32_audio_play_time),n.isBlackStream(e)&&t.statsToReport.uint32_video_avg_fps===0?t.statsToReport.uint32_video_black_screen_subjective=1:t.statsToReport.uint32_video_black_screen_subjective=0}),this._pathMainAudioMap.forEach((t,e)=>{if(!this.hasAudioFlag(t.userId)){this._pathMainAudioMap.delete(e);return}t.statsToReport.uint64_play_first_frame_time-t.statsToReport.uint64_start_enter_time>$s&&(t.statsToReport.uint64_play_first_frame_time=t.statsToReport.uint64_start_enter_time+$s)}),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>$s&&(t.statsToReport.uint64_render_first_frame_time=t.statsToReport.uint64_start_enter_time+$s)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>$s&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+$s)}getReportData(){this._basicInfo.uint32_networkType=Rd();let t={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new Uc({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:ln(this._signalInfo.relayIp),uint32_client_ip:ln(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*ri(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:ln(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,bytes_report_buf_from_0x1:this._signalInfo.endReportExtend,str_user_sig:this._room.userSig,bytes_report_token:this._signalInfo.reportToken};return Aa(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=Io.enable?Di(t,2001,e):yield vm(t),o=r instanceof ArrayBuffer,s=`${Ni(e,po.KEY_POINT)}&gzip=${+o}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(s,r));let a=[this.uploadKVStat(X),this.uploadKVStat(Ts)];n||a.push(wi({url:s,body:r,priority:"low"})),yield Promise.all(a)})}setConnectionType(t){this.connectionType=t,this._basicInfo.uint32_connection_type=t}uploadKVStat(t){return y(this,null,function*(){let e=t.getReportData(this._room.userSig,this._signalInfo.reportToken);if(e.stats_count.length===0&&e.stats_distribution.length===0)return;e.msg_sdk_basic_info=_e(Y({},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=Io.enable?Di(e,2003,this._room.sdkAppId):yield vm(e),o=r instanceof ArrayBuffer,s=`${Ni(+this._room.sdkAppId,po.KV_STAT)}&gzip=${+o}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(s,r)),n||wi({url:s,body:r})})}};Z([As({settings:{timeout:500,retries:3}})],Ol.prototype,"upload",1);var $s=5e3,KR={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},Uc=class{constructor(t){m(this,"str_identifier");m(this,"str_tinyid");m(this,"uint32_role");this.str_identifier=String(t.userId),this.str_tinyid=String(t.tinyId||0),this.uint32_role=t.role}},DT=Ol;var _f=class{constructor(){m(this,"_startTime");m(this,"_endTime");this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=Te())}stop(){this._endTime===0&&(this._endTime=Te())}getDuration(){return this._endTime===0?Te()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},Ml=_f;var Tf=class{constructor(t){m(this,"_room",null);m(this,"_durationMap");m(this,"_eventMap",new Map);this._room=t.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(B.REMOTE_TRACK_SUBSCRIBED,this.handleSubscribed).set(B.REMOTE_TRACK_UNSUBSCRIBED,this.handleUnsubscribed).set(B.REMOTE_PUBLISH_STATE_CHANGED,({room:t,prevMuteState:e,muteState:r})=>{var n;let{userId:o}=r;if(!this.hitTest(t))return;e.hasAudio&&!r.hasAudio&&this.stopDurationItem(`${o}_main`,M.AUDIO),e.hasVideo&&!r.hasVideo&&this.stopDurationItem(`${o}_main`,M.VIDEO),e.hasAuxiliary&&!r.hasAuxiliary&&this.stopDurationItem(`${o}_auxiliary`,M.VIDEO);let s=(n=this._room)==null?void 0:n.remotePublishedUserMap.get(o);s&&(!e.hasAudio&&r.hasAudio&&s.remoteAudioTrack.isSubscribed&&this.addDuractionItem(o,M.AUDIO,"main"),!e.hasVideo&&r.hasVideo&&s.remoteVideoTrack.isSubscribed&&this.addDuractionItem(o,M.VIDEO,"main"),!e.hasAuxiliary&&r.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(o,M.VIDEO,"auxiliary"))}),this._eventMap.forEach((t,e)=>U.on(e,t,this))}uninstallEvents(){this._eventMap.forEach((t,e)=>U.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 Ml,n=this._durationMap.get(o);n?this.isRecording(n[e])||n[e].push(s):this._durationMap.set(o,{userId:t,type:r,audio:e===M.AUDIO?[s]:[],video:e===M.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()}},wT=Tf;var If=class{constructor(){m(this,"renderFreezeMap",new Map);m(this,"dataFreezeMap",new Map)}get(t,e){let r=this.renderFreezeMap.get(t),o=this.dataFreezeMap.get(t);return e?e==="data"?o:r:(ct||ot)&&r&&o&&r.duration>o.duration?r:o}set(t,e,r){r==="data"?this.dataFreezeMap.set(t,e):this.renderFreezeMap.set(t,e)}clear(){this.renderFreezeMap.clear(),this.dataFreezeMap.clear()}},Sf=class{constructor(t){m(this,"_room");m(this,"_renderFreezeMap",new Map);m(this,"_isVideoPlayingEventFiredMap",new Map);m(this,"_dataFreezeMap",new Map);m(this,"_monitorFreezeData",new If);m(this,"_eventMap",new Map);m(this,"_videoEncodeFailedCount",0);m(this,"_audioEncodeFailedCount",0);m(this,"_encodeFailedThreshold",3);m(this,"eventListenerMap",new Map);this._room=t.room,this.installEvents()}getRenderFreezeMap(){return this._renderFreezeMap}getDataFreezeMap(){return this._dataFreezeMap}installEvents(){this._eventMap.set(B.LEAVE_SUCCESS,({room:t})=>{this.hitTest(t)&&this.stop()}).set(B.PLAY_TRACK_START,this.onPlayTrackStart).set(B.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(B.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(B.PLAYER_STATE_CHANGED,({track:t,state:e,reason:r,type:o})=>{if(!(!t.isRemote||!t.room||!this.hitTest(t.room)||o!==M.VIDEO)){if(e==="PLAYING"){let s=`${t.userId}_${t.streamType}`;this._isVideoPlayingEventFiredMap.set(s,!0)}r===M.MUTE?this.onVideoTrackMuted(t):r===M.UNMUTE&&this.onVideoTrackUnmuted(t)}}).set(B.HEARTBEAT_REPORT,this.onHearBeatReport).set(B.REMOTE_VIDEO_PLAY_START,this.onRemoteVideoPlayStart).set(B.REMOTE_VIDEO_PLAY_FINISH,this.onRemoteVideoPlayEnd),this._eventMap.forEach((t,e)=>U.on(e,t,this))}uninstallEvents(){this._eventMap.forEach((t,e)=>U.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 Ml;s?s.durationItemList.push(n):this._dataFreezeMap.set(o,{userId:e,type:r,durationItemList:[n],isFreezing(){let a=this.durationItemList[this.durationItemList.length-1];return a&&a.endTime===0}})}onVideoTrackUnmuted(t){if(!t.isSubscribed)return;let{userId:e,streamType:r}=t,o=`${e}_${r}`;this.stopDataFreeze({key:o,userId:e,type:r})}onHearBeatReport({room:t,report:e}){if(this.hitTest(t)){if(e.msg_up_stream_info.msg_video_status){let r=e.msg_up_stream_info.msg_video_status,o=Array.from(this._room.localTracks).find(n=>n.kind==="video"&&!n.isScreen),s=(o==null?void 0:o.stat.bytesSent)||0;if((o==null?void 0:o.isMediaTrackActive)===!1||s<=0||o!=null&&o.isUseCustomSource)return;r.forEach(n=>{n.uint32_video_stream_type===2&&(n.uint32_video_capture_fps!==0&&n.uint32_video_codec_bitrate===0&&n.uint32_video_enc_fps===0&&(o!=null&&o.isPublished)?(this._videoEncodeFailedCount+=1,this._videoEncodeFailedCount===this._encodeFailedThreshold&&qe.uploadEvent({userId:this._room.userId,log:`stat-${yr.VIDEO_ENCODE_FAILED_DURING_CALL}`})):this._videoEncodeFailedCount=0)})}if(e.msg_up_stream_info.msg_audio_status){let r=e.msg_up_stream_info.msg_audio_status,o=Array.from(this._room.localTracks).find(n=>n.kind==="audio"),s=(o==null?void 0:o.stat.bytesSent)||0;if((o==null?void 0:o.isMediaTrackActive)===!1||s<=0)return;r.uint32_audio_codec_bitrate===0&&(o!=null&&o.isPublished)?(this._audioEncodeFailedCount+=1,this._audioEncodeFailedCount===this._encodeFailedThreshold&&qe.uploadEvent({userId:this._room.userId,log:`stat-${yr.AUDIO_ENCODE_FAILED_DURING_CALL}`})):this._audioEncodeFailedCount=0}}}stopDataFreeze({key:t,userId:e,type:r}){let o=this._dataFreezeMap.get(t);if(!o||!o.isFreezing())return;let s=o.durationItemList[o.durationItemList.length-1];s.stop();let n=s.getDuration();if(n>Td){let a=this._monitorFreezeData.get(t,"data");this._monitorFreezeData.set(t,{userId:e,type:r,duration:a?a.duration+n:n},"data")}else o.durationItemList.pop()}getTotalDuration(t){return t.reduce((e,r)=>{let o=r.getDuration();return e+Math.min(o,5e3)},0)}onPlayTrackStart({track:t}){if(!t.isRemote||!this.hitTest(t.room)||t.kind!==M.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()<Td&&r.durationItemList.pop()}e.dataFreeze=this.getTotalDuration(r.durationItemList),e.count=r.durationItemList.length}return e}getRenderFreezeDuration(t){let e={renderFreeze:0,count:0},r=this._renderFreezeMap.get(t);return r&&(e.renderFreeze=r.totalDuration,e.count=r.count),e}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(t){return this._isVideoPlayingEventFiredMap.has(t)?!this._isVideoPlayingEventFiredMap.get(t):!1}onRemoteVideoPlayStart({track:t,player:e}){var n;if(!zr())return;let r=0,o=()=>{document.hidden||(r=0)};document.addEventListener("visibilitychange",o);let s=(a,d)=>{var l;if(r){let p=t.decodeFPS,f=p>0&&p<=5?600+1e3/p:600,g=d.presentationTime-r;if(g>f){g=Math.min(g,5e3);let A=`${t.userId}_${t.streamType}`,R=this._monitorFreezeData.get(A,"render");R?R.duration+=g:this._monitorFreezeData.set(A,{userId:t.userId,type:t.streamType,duration:g},"render");let N=this._renderFreezeMap.get(A);N?(N.totalDuration+=g,N.count+=1):this._renderFreezeMap.set(A,{userId:t.userId,type:t.streamType,totalDuration:g,count:1})}}r=d.presentationTime,(l=e.element)==null||l.requestVideoFrameCallback(s)};(n=e.element)==null||n.requestVideoFrameCallback(s),this.eventListenerMap.set(`${t.userId}_${t.streamType}`,{onVisibilityChange:o})}onRemoteVideoPlayEnd({track:t,player:e}){let r=`${t.userId}_${t.streamType}`,o=this.eventListenerMap.get(r);o&&document.removeEventListener("visibilitychange",o.onVisibilityChange)}resetMonitor(){this._monitorFreezeData.clear()}hitTest(t){return t===this._room}destroy(){this.uninstallEvents()}},OT=Sf;var PT=bi(ki(),1);var xl=class{constructor(t,e,r,o,s,n=4/3){this.vbMode=t;this.faceDetectorHash=r;this.visionTaskRegistry=o;this.logger=s;m(this,"animationState");m(this,"originalAspect");m(this,"totalOffsetX",0);m(this,"totalOffsetY",0);m(this,"defaultScaleRatio",.1);m(this,"isRecovering",!1);m(this,"boundaryY",280);m(this,"lastActionTime",0);m(this,"restTime",400);this.animationState={current:null,target:null,animating:!1,debounceTimer:null,startTime:0,duration:3e3,debounceTime:150,movementThreshold:30,debounceThreshold:15},this.addEvent(this.vbMode,!!this.faceDetectorHash),this.originalAspect=n||4/3,this.visionTaskRegistry.setVideo(this.faceDetectorHash,e)}addEvent(t,e,r){let s=[{key:570704,error:r!=null?r:e?void 0:11},{key:570705,error:r!=null?r:e?void 0:22}][t-1];s&&(e?X.addSuccessEvent({key:s.key}):X.addFailedEvent({key:s.key,error:s.error}))}actionCentering(t){let e=Date.now();if(this.animation(),!this.faceDetectorHash||e-this.lastActionTime<this.restTime||this.animationState.animating)return;let{videoWidth:r,videoHeight:o}=t;this.animationState.debounceThreshold=r/30,this.animationState.movementThreshold=r/20,this.boundaryY=o*.6;try{let s=this.visionTaskRegistry.getResult(this.faceDetectorHash);if(s.detections.length<=0){this.vbMode===1&&this.recoverOriginal(r,o);return}let n=s.detections[0].boundingBox,a=n.originX,d=n.originY,l=n.width,p=n.height;this.vbMode===1?this.dualStageCropping(r,o,a,d,l,p):this.vbMode===2&&this.movingPortrait(r,o,a,d,l,p)}catch(s){this.logger.error(s)}this.lastActionTime=e}calculateBoundary(t,e,r,o){let s,n;return t>e/2?(s=e-r-o,n=r-s):(s=r,n=0),{min:s,offset:n}}calculateTargetPosition(t,e,r,o,s,n,a=.4){let d=t+r/2,l=e+o/2,p,f,{min:g,offset:A}=this.calculateBoundary(d,s,t,r),{min:R,offset:N}=this.calculateBoundary(l,n,e,o);return p=2*g+r,f=2*R+o,p/f>this.originalAspect?(p=f*this.originalAspect,A=d-p/2):(f=p/this.originalAspect,N=l-f/2),r/s>a&&(A=0,N=0,p=s,f=n),A=Math.max(0,Math.min(A,s-p)),N=Math.max(0,Math.min(N,n-f)),{sx:A,sy:N,cropWidth:p,cropHeight:f,timestamp:Date.now()}}processFacePositionCrop(t,e,r){if(!this.animationState.current||!this.animationState.target){let a={sx:0,sy:0,cropWidth:e,cropHeight:r,timestamp:Date.now()};this.animationState.current=a,this.animationState.target=a;return}let o=this.positionDistance(this.animationState.target,t),s=this.positionDistance(this.animationState.current,t),n=this.animationState.current.cropWidth/e;o>this.animationState.debounceThreshold*n&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&s>this.animationState.movementThreshold*n&&(this.animationState.target=t,this.animationState.debounceTimer=setTimeout(()=>{this.animationState.startTime=Date.now(),this.animationState.animating=!0},this.animationState.debounceTime))}processFacePositionPortrait(t){if(!this.animationState.current||!this.animationState.target){this.animationState.current=Y({},t),this.animationState.target=Y({},t);return}let e=this.positionDistance(this.animationState.current,t),r=this.positionDistance(this.animationState.target,t);e>this.animationState.debounceThreshold&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&r>this.animationState.movementThreshold&&(this.animationState.current=t,this.animationState.debounceTimer=setTimeout(()=>{this.animationState.startTime=Date.now(),this.animationState.animating=!0},this.animationState.debounceTime))}animation(){if(!this.animationState.animating)return;let t=Date.now()-this.animationState.startTime,e=Math.min(t/this.animationState.duration,1),r=o=>o<.5?2*o*o:-1+(4-2*o)*o;if(this.animationState.current&&this.animationState.target){let o=(this.animationState.target.sx-this.animationState.current.sx)*r(e);this.animationState.current.sx+=o,this.totalOffsetX+=o;let s=(this.animationState.target.sy-this.animationState.current.sy)*r(e);if(this.animationState.current.sy+=s,this.totalOffsetY+=s,this.animationState.current.cropWidth+=(this.animationState.target.cropWidth-this.animationState.current.cropWidth)*r(e),this.animationState.current.cropHeight+=(this.animationState.target.cropHeight-this.animationState.current.cropHeight)*r(e),this.animationState.current.scaleRatio&&this.animationState.target.scaleRatio&&(this.animationState.current.scaleRatio+=(this.animationState.target.scaleRatio-this.animationState.current.scaleRatio)*r(e)),Fe(this.animationState.current.scaleOffsetX)&&Fe(this.animationState.target.scaleOffsetX)&&Fe(this.animationState.current.scaleOffsetY)&&Fe(this.animationState.target.scaleOffsetY)){let n=(this.animationState.target.scaleOffsetX-this.animationState.current.scaleOffsetX)*r(e);this.animationState.current.scaleOffsetX+=n;let a=(this.animationState.target.scaleOffsetY-this.animationState.current.scaleOffsetY)*r(e);this.animationState.current.scaleOffsetY+=a}}e>=1&&(this.animationState.animating=!1,this.animationState.current=this.animationState.target,this.isRecovering=!1)}positionDistance(t,e){return Math.sqrt(ri(t.sx-e.sx,2)+ri(t.sy-e.sy,2))}recoverOriginal(t,e){this.animationState.target={sx:0,sy:0,cropWidth:t,cropHeight:e,timestamp:Date.now()},this.animationState.animating=!0,this.animationState.startTime=Date.now(),this.isRecovering=!0}dualStageCropping(t,e,r,o,s,n,a=.3){if(this.isRecovering)return;let d=this.calculateTargetPosition(r,o,s,n,t,e);this.processFacePositionCrop(d,t,e),s*n/d.cropWidth/d.cropHeight>a&&this.recoverOriginal(t,e)}movingPortrait(t,e,r,o,s,n){var d,l,p,f,g,A,R,N,C,P,z,H;let a={sx:r+s/2+this.totalOffsetX,sy:o+n/2+this.totalOffsetY,cropWidth:t,cropHeight:e,scaleRatio:(l=(d=this.animationState.current)==null?void 0:d.scaleRatio)!=null?l:1,scaleOffsetX:(f=(p=this.animationState.current)==null?void 0:p.scaleOffsetX)!=null?f:0,scaleOffsetY:(A=(g=this.animationState.current)==null?void 0:g.scaleOffsetY)!=null?A:0,timestamp:Date.now()};this.animationState.target={sx:t/2,sy:o+n/2,cropWidth:t,cropHeight:e,scaleRatio:(N=(R=this.animationState.target)==null?void 0:R.scaleRatio)!=null?N:1,scaleOffsetX:(P=(C=this.animationState.target)==null?void 0:C.scaleOffsetX)!=null?P:0,scaleOffsetY:(H=(z=this.animationState.target)==null?void 0:z.scaleOffsetY)!=null?H:0,timestamp:Date.now()},this.animationState.animating||(this.animationState.target.scaleRatio=Math.sqrt(s*n/t/e/this.defaultScaleRatio),this.animationState.target.scaleOffsetX=-this.animationState.target.scaleRatio/2+.5,this.animationState.target.scaleOffsetY=-this.animationState.target.scaleRatio+1,(this.animationState.target.sy-this.animationState.target.scaleOffsetY*this.animationState.target.cropHeight)/this.animationState.target.scaleRatio<this.boundaryY&&(this.animationState.target.scaleOffsetY=(this.animationState.target.sy-this.boundaryY*this.animationState.target.scaleRatio)/this.animationState.target.cropHeight)),this.processFacePositionPortrait(a)}set aspectRatio(t){this.originalAspect=t}get current(){return this.animationState.current}get offset(){return{offsetX:this.totalOffsetX,offsetY:this.totalOffsetY}}get targetCrop(){return this.animationState.target}};var ev=`#version 300 es
100
100
  in vec2 a_position;
101
101
  in vec2 a_texCoord;
102
102
  out vec2 v_texCoord;
@@ -137,4 +137,4 @@ void main() {
137
137
  void main() {
138
138
  gl_Position = vertexPos;
139
139
  textureCoord = texturePos;
140
- }`});m(this,"yTextureRef");m(this,"uTextureRef");m(this,"vTextureRef");m(this,"Y");m(this,"U");m(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 MT=(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 rv(i){return i[0]===0&&i[1]===0&&i[2]===0&&i[3]===1}var iv=0,kl=class{constructor(t){m(this,"id",iv++);m(this,"trackDoneOB");m(this,"startOB");m(this,"stopOB");m(this,"decoder");m(this,"videoContext");m(this,"gop",0);m(this,"gop_helper",0);m(this,"waitFirstKeyFrame",!0);m(this,"startTimestamp",0);m(this,"startTime",0);m(this,"startPerformanceTime",0);m(this,"inputFrameCount",0);m(this,"decodedFrameCount",0);m(this,"decodeFrameCount",0);m(this,"downgradeLevel",0);m(this,"lastDowngradeTime",0);m(this,"lastFrameDiff",0);m(this,"lastDecodeFrameTimestamp",0);m(this,"config");m(this,"gop_before_configure",[]);m(this,"videoElement");m(this,"type","wasm");m(this,"goodType");m(this,"renderer","2d");m(this,"wasmOption");m(this,"createDecoder");m(this,"_decodeSink");m(this,"isReported",!1);m(this,"track");m(this,"stateChangeOB");m(this,"failedReason");let{track:e,createDecoder:r}=t;if(this.stateChangeOB=bt(),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=Ae(e.availableState,ue.OFF),this.stopOB=bt(),t.type==="auto"){switch(t.fallback){case"wasm":this.type="wasm",this.renderer="webgl";break;case"wasm_2d":this.type="wasm",this.renderer="2d";break;case"wasm_video":this.type="wasm",this.renderer="videoFrame";break;default:this.type="webCodecs"}this.wasmOption.yuvMode=this.renderer==="webgl"}else this.type=t.type;this.changeRenderer(this.renderer),ye(this.stateChangeOB,Ap((o,s)=>(o!==s&&e.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:this.failedReason,prevState:o,state:s}),s),"INITIALIZED"),Je(this.stopOB),Le()),this.start()}start(t=0){this.waitFirstKeyFrame=!0,this.stateChangeOB.next("STARTING");let e=ye(this.pipe(this.track),Je(this.stopOB),ji());ye(e,Le(()=>{this.track.stat.framesDecoded++},r=>{if(this.track.log.error(`${this.id} play failed: ${r} retryCount: ${t}`),X.addFailedEvent({key:MT(this.type,this.renderer),error:r}),t>4)this.failedReason=r,this.stateChangeOB.next("FAILED"),X.addFailedEvent({key:514704});else{if(this.goodType){this.start(t);return}switch(this.type){case"webCodecs":this.type="wasm",this.changeRenderer("webgl");break;case"wasm":switch(this.renderer){case"webgl":this.changeRenderer("videoFrame");break}}this.start(t+1)}},()=>{this.track.log.warn(`${this.id} decoderOB completed`),X.addSuccessEvent({key:MT(this.type,this.renderer)}),X.addSuccessEvent({key:514704})})),ye(e,Qr(1),Le(()=>{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"&&!fh()&&(this.renderer="2d"),this.wasmOption.yuvMode=this.renderer==="webgl"}decode(t,e=!1){var a,d;if(this.failedReason)return;this.inputFrameCount++;let r=new Uint8Array(t.data);if(!rv(r)||r.length<5)return this.stateChangeOB.next("FAILED"),this.close(`not h26x frame ${r.subarray(0,5)}`),t;let o=r[4]&31,s=!1;switch(o){case 5:case 7:s=!0;break}if(((a=this.decoder)==null?void 0:a.state)!=="configured")return this.track.log.debug(`not configured ${this.inputFrameCount}`),s&&(this.gop_before_configure=[]),this.gop_before_configure.push({data:t.data,timestamp:t.timestamp,type:t.type}),t;this.gop_before_configure.length>0&&!e&&(this.gop_before_configure.forEach(l=>this.decode(l,!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=Te();else{this.track.log.debug(`wait first key frame ${this.inputFrameCount} ${r.subarray(0,5).join(" ")}`);return}switch(this.downgradeLevel){case 0:break;case 1:break;case 2:if(this.gop_helper>this.gop>>1)return;break;case 3:if(this.gop_helper>0)return;break;default:return}(this.decodeFrameCount<10||this.decodeFrameCount%500===0)&&this.track.log.debug(`decode ${this.decodeFrameCount} gop: ${this.gop} ${n} ${(d=t.getMetadata)==null?void 0:d.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 a;o&&(t.player.setCanvas(),t.setInputMediaStreamTrack(o)),r==null||r.close(),(a=this.videoContext)==null||a.destroy(),delete this._decodeSink});let{renderer:s,type:n}=this;t.log.info(`decoder type: ${this.type} renderer: ${this.renderer}`);try{switch(n){case"wasm":r=this.createDecoder(n,this.wasmOption);break;case"webCodecs":r=this.createDecoder(n);break;default:throw new Error("not supported yet")}let a=0;if(r.on("videoFrame",d=>{this.decodedFrameCount++,a++,(a<=10||a%500===0)&&t.log.debug(`frame ${a} ${this.decodedFrameCount}/${this.decodeFrameCount} decoded ${d.timestamp}`),Date.now()-this.lastDowngradeTime>5e3&&(this.type==="webCodecs"?this.checkDowngradeByFrameDiff():this.type==="wasm"&&this.checkDowngradeByTimestampDiff(d.timestamp)),e.next(d)}),r.on("error",d=>{t.log.error(d),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 Nt({frameRate:15,logger:t.log,name:t.userId}),this.videoContext.create(),this.videoContext.on(Nt.UNAVAILABLE,l=>{t.log.error(l),e.error(7)});let d=new Ll(this.videoContext);r.on("videoCodecInfo",l=>d.resize(l.width,l.height)),r.on("videoFrame",l=>{({y:d.Y,u:d.U,v:d.V}=l),this.downgradeLevel===1?this.decodedFrameCount%2===0&&d.render(this.decodedFrameCount):d.render(this.decodedFrameCount)}),t.source=d,t.player.setCanvas(this.videoContext._canvas,2)}else if(s==="videoFrame"){t.player.setCanvas();let d=new MediaStreamTrackGenerator({kind:"video"}),l=d.writable.getWriter();t.setInputMediaStreamTrack(d),r.on("videoFrame",p=>l.write(p))}else{this.videoContext=new Lt({frameRate:15,logger:t.log,name:t.userId}),this.videoContext.create({alpha:!1});let d=this.videoContext.createVideoImageSource();r.on("videoFrame",p=>{try{d.image=p,d.update()}catch(f){delete this.goodType,t.log.error(f),e.error(11)}});let l=new Ms(this.videoContext,{name:"remotePlayer",logger:t.log});d.connect(l),t.source=d,t.player.setCanvas(this.videoContext._canvas,2)}this.decoder=r}catch(a){t.log.error(a),e.error(n==="webCodecs"?2:6)}})}};var xT=Promise.resolve(),Vc=class extends PT.EventEmitter{constructor(e){super();this.room=e;m(this,"videoContext");m(this,"_glVideoContext");m(this,"_2dVideoContext");m(this,"destination");m(this,"smallVideoContext");m(this,"smallDestination");m(this,"smallTrackSource");m(this,"smallImageSource");m(this,"_isMirror",!1);m(this,"_rotation",0);m(this,"cameraTrack");m(this,"cameraNode");m(this,"transformNode");m(this,"mixNode");m(this,"screenTrack");m(this,"screenNode");m(this,"selfModel",!1);m(this,"blurRadius",3);m(this,"arTrack");m(this,"_enableFaceCentering",!1);m(this,"_enableEffectOptimization",!1);m(this,"onAbort");m(this,"_color");m(this,"Wasm");m(this,"waterMarkNode");m(this,"_waterMarkOption");m(this,"watermarkImageList",[]);m(this,"_beautyParams");m(this,"isUsingArTrack",!1);m(this,"mixTrack");m(this,"_isMixScreen",!1);m(this,"_virtualBackground");m(this,"_virtualBackgroundAbortCallback");m(this,"virtualBackgroundInstance");m(this,"_bgAssetPath");m(this,"log");m(this,"_mat4");m(this,"_postProcessing");m(this,"_checkId",0);m(this,"_use2d",!1);m(this,"_autoSwitchRenderMode",!0);m(this,"encodePipeline",[]);m(this,"decodePipeline",[]);m(this,"updated",xT);m(this,"_updateFlag",!1);this.log=F.createLogger({parent:e==null?void 0:e.getLogger(),id:"vm",userId:e==null?void 0:e.userId,sdkAppId:e==null?void 0:e.sdkAppId}),this.smallVideoContext=new Lt({frameRate:15,logger:this.log,name:"s"}),this.enablePrintDetail()}get smallMode(){var e;return((e=this.room)==null?void 0:e.smallMode)||"canvas"}get _hasVirtualBg(){return!!this._virtualBackground}get _hasWaterMark(){return this.watermarkImageList.length>0}get _isRotate(){return this._rotation!==0}get _isTransform(){return this._isMirror||this._isRotate}get renderMode(){return this._autoSwitchRenderMode?"auto":this._use2d?"2d":"webgl"}set renderMode(e){if(this._autoSwitchRenderMode=e==="auto",this._autoSwitchRenderMode)return;let r=e==="2d";this._use2d!==r&&(this._use2d=r,this.clear(),this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.update())}get cameraResolution(){var o;let{width:e,height:r}=((o=this.cameraTrack)==null?void 0:o.settings)||{};return fr(this._rotation)?{width:r,height:e}:{width:e,height:r}}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new Lt({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this._2dVideoContext}getGlVideoContext(){if(!this._glVideoContext)this._glVideoContext=new Nt({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(Lm<=22),this._glVideoContext.on(Nt.UNAVAILABLE,e=>{var r;this.emit("error",e),this.log.warn("video context unavailable",e),(r=this._virtualBackgroundAbortCallback)==null||r.call(this,e),this.update().catch(o=>{this.log.error(o)})})}catch(e){this.emit("error",e)}}initVirtualBackground(e,r,o){this.onAbort=e,this._mat4=r,this._postProcessing=o}enablePrintDetail(e=2e3){this._checkId=gt.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(),gt.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(vr||this._isMixScreen||this._isTransform||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}sendCreateResult(e="videoCtxGl",r){let o=e==="videoCtxGl"?512700:512701;r?X.addFailedEvent({key:o,error:r}):X.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 Nt({frameRate:15,logger:this.log,name:"m"}),this.initializeGlVideoContext(),this._glVideoContext.available)return this.videoContext=this._glVideoContext,this.videoContext.available;this.log.warn("webgl is still not available"),this.clear(),this._use2d=!0}return this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.videoContext.available}get smallTrack(){var e;return(e=this.smallDestination)==null?void 0:e.videoTrack}get hasSmall(){return!!this.smallTrack}get initialTrack(){var e;return(e=this.cameraTrack)==null?void 0:e.mediaTrack}setSmallVideo(e,r){if(this.smallMode!=="api")if(e){if(!this.smallVideoContext.available){if(this.smallVideoContext.create({alpha:!1}),!this.smallVideoContext.available)return;this.smallDestination=new Qu(this.smallVideoContext,e,this.log),this.smallVideoContext.on(Nt.UNAVAILABLE,o=>{this.log.warn("small video context lost",o)})}if(this.smallVideoContext.frameRate=e.frameRate,this.smallDestination.resolution=e,r)this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=r:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(r),this.smallImageSource.resize(r.width,r.height),this.smallImageSource.connect(this.smallDestination));else if(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource)this.smallTrackSource.replaceTrack(this.initialTrack);else{this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack,"smallTrackSource");let{width:o,height:s}=this.cameraTrack.settings;this.smallTrackSource.resize(o,s),this.smallTrackSource.connect(this.smallDestination)}}else this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource)}_setMainOutput(e){var r;try{let o=this.cameraTrack,{small:s,player:n}=o;vr&&n.setCanvas(e);let a=e&&((r=this.destination)==null?void 0:r.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),a=this.arTrack),this.log.info(`set main output ${a?a.label:"no output track"}`),this.setSmallVideo(s,e),o.setOutputMediaStreamTrack(a)}catch(o){this.log.error("set main output failed",o)}}update(e=!1){return y(this,null,function*(){var s;if(!this.cameraTrack||!this.initialTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:r,profile:o}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams)this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log}),this.destination.on(_t.RENDER,n=>{var a;(a=this.cameraTrack)==null||a.emit("render",n)})),Vt===16?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof Dr?(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 Dr?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode.close(),delete this.cameraNode)),this.cameraNode||(this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraTrackSource"))):this.cameraNode?this.cameraNode.replaceTrack(this.initialTrack):this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraNodeSource"),this.cameraNode.resize(r.width,r.height);else if(e&&this.cameraNode&&this.destination)this.cameraNode.replaceTrack(this.initialTrack);else{this.cameraNode&&this.cameraNode.close(),this.destination?this.destination.disableCheckMute():(this.destination=new Xu(this.videoContext,{name:"mainDestination",logger:this.log}),this.destination.on(_t.RENDER,l=>{var p;(p=this.cameraTrack)==null||p.emit("render",l)}));let{width:n,height:a}=this.cameraResolution,d=yield this.getWatermarkImage(n,a);this._waterMarkOption={x:0,y:0,width:d.width,height:d.height,image:d},this.cameraNode=new Pl(this.videoContext,{input:this.initialTrack,width:n,height:a,mirror:this._isMirror,rotation:this._rotation,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,beautyParams:this._beautyParams,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,Wasm:this.Wasm,enableFaceCentering:this._enableFaceCentering,enableEffectOptimization:this._enableEffectOptimization,onAbort:this.onAbort,mat4:this._mat4,postProcessing:this._postProcessing,color:this._color}),this.cameraNode.connect(this.destination),this.destination.enableCheckMute(),yield this.cameraNode.predictReady}if(this.videoContext.frameRate=o.frameRate,this._use2d){let n=this.cameraNode;if(n.disconnect(),this._isTransform&&(this.transformNode?(this.transformNode.mirror=this._isMirror,this.transformNode.rotation=this._rotation):this.transformNode=new wr(this.videoContext,this.log,this._isMirror,this._rotation),n=n.connect(this.transformNode),n.disconnect(),this.log.info(`start mirror ${this._isMirror} rotate ${this.rotation}`)),this.mixNode&&this.mixNode.close(),delete this.mixNode,this._isMixScreen||this._hasWaterMark){if(this.mixNode=new Fn(this.videoContext,this.log),n.connect(this.mixNode,{zIndex:1}),this._hasWaterMark&&!this.waterMarkNode&&this._waterMarkOption)this.waterMarkNode=this.videoContext.createVideoImageSource(this._waterMarkOption.image,{autoResize:!1,logger:this.log}),this.waterMarkNode.resize(this._waterMarkOption.width,this._waterMarkOption.height),this.waterMarkNode.x=this._waterMarkOption.x,this.waterMarkNode.y=this._waterMarkOption.y;else if(this.waterMarkNode){let{width:d,height:l}=this.cameraResolution;this.waterMarkNode.image=yield this.getWatermarkImage(d,l),d&&l&&this.waterMarkNode.resize(d,l)}(s=this.waterMarkNode)==null||s.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&(this.screenNode||(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource"),this.screenNode.resize(this.screenTrack.settings.width,this.screenTrack.settings.height)),this.screenNode.shouldUpdate=!1,this.screenNode.connect(this.mixNode,{zIndex:0})),n=this.mixNode,this.log.info("start mix",`${this.mixNode.width}x${this.mixNode.height}`)}n.connect(this.destination)}return this.log.info(`update ${this._use2d?"2d":"webgl"}`),this._setMainOutput(this.videoContext.canvas)})}clearLastFrame(){var e;this.destination&&((e=this.destination.ctx2d)==null||e.clearRect(0,0,this.destination.width,this.destination.height))}changeInput(e){var r,o,s,n,a;if(e instanceof mi)return this.log.info("change screen input",(r=e.mediaTrack)==null?void 0:r.label),this.setScreenTrack(e);if(e instanceof _r)return this.log.info("change video input",(o=e.mediaTrack)==null?void 0:o.label),this.setCameraTrack(e);if(e instanceof xo){this.log.info("change remote input",(s=e.mediaTrack)==null?void 0:s.label);let d=e.mediaTrack;return e.setOutputMediaStreamTrack(d)}if(e instanceof Ps)return this.log.info("change mix input",(n=e.outMediaTrack)==null?void 0:n.label),this.setMixTrack(e);this.log.warn("change unknown input",(a=e.mediaTrack)==null?void 0:a.label)}removeInput(e){var r;e instanceof mi?((r=this.screenNode)==null||r.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof _r?this._isMixScreen?(delete this.cameraNode,this.cameraTrack._inputTrack=null,this.update()):(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof xo?e.source&&e.source.context.destroy():e instanceof Ps&&(delete this.mixTrack,this.update())}setMixTrack(e){this.mixTrack=e}setCameraTrack(e){return this.cameraTrack=e,this.update(!0)}setScreenTrack(e){return y(this,null,function*(){return this.screenTrack=e,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):yield this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)})}getWatermarkImage(e,r){return 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 se({code:q.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort((n,a)=>n.zIndex-a.zIndex),this.watermarkImageList.forEach(({image:n,x:a,y:d,width:l,height:p,fillVideo:f})=>{let g=f&&e||l,A=f&&r||p,R=f?0:a,N=f?0:d;s.drawImage(n,R,N,g,A)}),hn(o.toDataURL())})}pushWaterMarkImageList(e){let{type:r}=e;this.watermarkImageList.some(s=>s.imageUrl===e.imageUrl&&s.height===e.height&&s.width===e.width&&s.x===e.x&&s.y===e.y&&s.type===e.type&&s.zIndex===e.zIndex&&s.fillVideo===e.fillVideo)||((r==="mute"||r==="watermark")&&(this.watermarkImageList=this.watermarkImageList.filter(s=>s.type!==r)),this.watermarkImageList.push(e))}setBeautyParams(e){return 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*(){let r;try{r=yield hn((e==null?void 0:e.imageElement)||e.imageUrl)}catch(g){throw new se({code:q.INVALID_PARAMETER,message:`load image failed, url: ${e.imageUrl}`})}let{x:o=0,y:s=0,width:n=r.width,height:a=r.height,type:d="watermark",zIndex:l=2,fillVideo:p=!1}=e;this.watermarkImageList.some(g=>g.type===d)?(this.watermarkImageList=this.watermarkImageList.filter(g=>g.type!==d),this.pushWaterMarkImageList({x:o,y:s,width:n,height:a,image:r,zIndex:l,type:d,imageUrl:e.imageUrl,fillVideo:p}),r=yield this.getWatermarkImage(this.cameraResolution.width,this.cameraResolution.height),this._waterMarkOption={x:0,y:0,width:r.width,height:r.height,image:r},this.waterMarkNode?(this.waterMarkNode.x=0,this.waterMarkNode.y=0,this.waterMarkNode.resize(r.width,r.height),this.waterMarkNode.image=r):this.update()):(this.pushWaterMarkImageList({x:o,y:s,width:n,height:a,image:r,zIndex:l,type:d,imageUrl:e.imageUrl,fillVideo:p}),yield this.freshWatermark()),this.log.info("set watermark",JSON.stringify(this.watermarkImageList,(g,A)=>g==="imageUrl"?void 0:A))})}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 s;(s=this.waterMarkNode)==null||s.close(),delete this.waterMarkNode,delete this._waterMarkOption;let{width:e,height:r}=this.cameraResolution,o=yield this.getWatermarkImage(e,r);this._waterMarkOption={x:0,y:0,width:o.width,height:o.height,image:o},this.update()})}setVirtualBackground(e){return y(this,null,function*(){var r,o,s;if(!e)delete this._virtualBackground,delete this._virtualBackgroundAbortCallback;else{if(e.onAbort&&(this._virtualBackgroundAbortCallback=e.onAbort),this._use2d&&!this._autoSwitchRenderMode)return Promise.reject(new Error("not support virtual background in 2d mode"));this._bgAssetPath=e.assetPath,e.type==="image"?this._virtualBackground=yield hn(e.imageUrl):(this.blurRadius=e.blurLevel||this.blurRadius||3,this._virtualBackground=e.type),this._enableFaceCentering=(r=e.enableFaceCentering)!=null?r:this._enableFaceCentering,this._enableEffectOptimization=(o=e.enableEffectOptimization)!=null?o:this._enableEffectOptimization,this._color=(s=e.color)!=null?s:[0,1,0]}if(this.log.info(`${this._virtualBackground?"start":"stop"} virtual background, ${(e==null?void 0:e.type)||""}, ${this.blurRadius||""}`),yield this.update(),this._virtualBackground&&!this._glVideoContext.available)throw new se({code:q.INVALID_OPERATION,message:`webgl context create failed, ${this._glVideoContext.error}`})})}get mixScreen(){return this._isMixScreen}set mixScreen(e){var r;this._isMixScreen=e,this._isMixScreen||((r=this.screenNode)==null||r.close(),delete this.screenNode),this.update()}set mirror(e){var r;this._isMirror!==e&&(this._isMirror=e,this._isTransform||((r=this.transformNode)==null||r.close(),delete this.transformNode),this.update())}get mirror(){return this._isMirror}set rotation(e){var r;this._rotation!==e&&(this._rotation=e,this._isTransform||((r=this.transformNode)==null||r.close(),delete this.transformNode),this.update())}get rotation(){return this._rotation}enableAr(e){this.arTrack=e,this.isUsingArTrack=!0,this.update()}updateAr(){return 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 kl(e)}clear(){var e,r;(e=this.videoContext)==null||e.disconnect(),(r=this.destination)==null||r.removeAllListeners(),delete this.destination,delete this.cameraNode,delete this.transformNode,delete this.screenNode,delete this.waterMarkNode}addEncodeProcessor({processor:e,type:r}){var o;this.encodePipeline.includes(e)||(this.encodePipeline[r]=e,(o=this.room)==null||o.enableInsertableStreams())}addDecodeProcessor({processor:e,type:r}){var o;this.decodePipeline.includes(e)||(this.decodePipeline[r]=e,(o=this.room)==null||o.enableInsertableStreams())}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}};Z([VE(function(e){this.log.error("update failed",e)}),Pe(e=>function(...r){return y(this,null,function*(){this._updateFlag||(this._updateFlag=!0,yield xT,this.updated=new Promise((o,s)=>{e.apply(this,r).then(o,s),setTimeout(s,5e3,new se({code:q.API_CALL_TIMEOUT,message:"update timeout"}))}),this._updateFlag=!1,yield this.updated)})})],Vc.prototype,"update",1);var ov=0;var Ul=class extends ue{constructor(e){super("room");m(this,"seq",++ov);m(this,"sdkAppId");m(this,"userId");m(this,"userSig");m(this,"privateMapKey");m(this,"latencyLevel");m(this,"tinyId");m(this,"scene");m(this,"roomId");m(this,"useStringRoomId");m(this,"role","anchor");m(this,"joinParams",null);m(this,"localPublishFlag",0);m(this,"localTracks",new Set);m(this,"enableAutoPlayDialog",!0);m(this,"autoReceiveAudio",!0);m(this,"autoReceiveVideo",!0);m(this,"proxy_ws");m(this,"proxy_wt");m(this,"proxy_unified");m(this,"checkSystemResult",{result:!0,detail:{isBrowserSupported:!0,isWebRTCSupported:!0,isWebCodecsSupported:!0,isMediaDevicesSupported:!0,isScreenShareSupported:!0,isSmallStreamSupported:!0,isH264EncodeSupported:!0,isVp8EncodeSupported:!0,isH264DecodeSupported:!0,isVp8DecodeSupported:!0,isH265EncodeSupported:!0,isH265DecodeSupported:!0}});m(this,"keyPointManager");m(this,"audioManager");m(this,"videoManager");m(this,"callDurationCalculator");m(this,"badCaseDetector");m(this,"scheduleResult",{domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null});m(this,"videoDecodeFallbackType");m(this,"smallMode","canvas");m(this,"enableChorus",!1);m(this,"_isUsingCachedSchedule",!1);m(this,"_log");m(this,"_joinedTimestamp",0);m(this,"_sdkType");m(this,"heartbeatReport");m(this,"heartbeatCount",0);m(this,"quality");m(this,"enableSEI");m(this,"isDestroyed",!1);this._log=F.createLogger({parent:e.logger,id:`r${this.seq}`}),this.useStringRoomId=!!e.useStringRoomId,Ye(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),Ye(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),Ye(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new DT({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new wT({room:this}),this.badCaseDetector=new OT({room:this}),this.audioManager=new Ku(this),this.videoManager=new Vc(this)}get videoCodec(){return"h264"}get scriptTransformWorker(){}get isMainStreamPublished(){for(let e of this.localTracks)if(e.mediaType&4)return!0;return!1}get isAuxStreamPublished(){for(let e of this.localTracks)if(e.mediaType&2)return!0;return!1}get hasAuxStream(){for(let e of this.remotePublishedUserMap.values())if(e.muteState.hasAuxiliary)return!0;return this.isAuxStreamPublished}get localMainAudioTrack(){for(let e of this.localTracks)if(e.mediaType&1)return e;return null}get localMainVideoTrack(){for(let e of this.localTracks)if(e.mediaType&4)return e;return null}get localAuxVideoTrack(){for(let e of this.localTracks)if(e.mediaType&2)return e;return null}get publishState(){let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};return this.localTracks.forEach(r=>{if(r.isPublished||r.isPublishing)switch(r.mediaType){case 1:e.audio=!0;break;case 4:e.bigVideo=!0,e.smallVideo=r.hasSmall;break;case 2:e.auxVideo=!0;default:break}}),e}get muteState(){var e,r,o;return{audio:!!((e=this.localMainAudioTrack)!=null&&e.muted),bigVideo:!!((r=this.localMainVideoTrack)!=null&&r.muted),auxVideo:!!((o=this.localAuxVideoTrack)!=null&&o.muted)}}getLogger(){return this._log}get isJoining(){return this.state.toString()==="joining"}get isJoined(){return this.state==="joined"}get isLeft(){return this.state==="left"}addTrack(e){return 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(Oe(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(Jt(e)){let{websocketProxy:r,webtransportProxy:o,loggerProxy:s,scheduleProxy:n,unifiedProxy:a}=e;this.proxy_ws=r,this.proxy_wt=o,this.proxy_unified=a,a?(pl([a,a]),ts(`https://${a}`)):(s&&ts(s),n&&pl(n))}U.once(B.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:gi.main,sched_back_domain:gi.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 se({code:q.INVALID_OPERATION,message:We({key:He.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(ar.INVALID_DESTROY),new se({code:q.INVALID_OPERATION,message:We({key:He.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,U.emit(B.ROOM_DESTROY,{room:this})}schedule(e,r){return y(this,null,function*(){var s,n,a,d;let o=Te();try{let{isCached:l,result:p,detailCost:f}=yield rf({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:pt,userSig:this.userSig,role:this.scene==="live"?e.role:void 0,frameWorkType:r,latencyLevel:e.latencyLevel});this._isUsingCachedSchedule=l,this._log.info(`schedule cache:${+l} ${br(p,{keysToExclude:["username","credential"]})}`),l&&U.once(B.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=Y(Y({},this.scheduleResult),p),Fe((s=p.config)==null?void 0:s.retryCount)&&um(p.config.retryCount),Oe((n=p.config)==null?void 0:n.loggerDomain)&&ts(p.config.loggerDomain),this.videoDecodeFallbackType=((a=p.config)==null?void 0:a.videoDecodeFallback)||this.videoDecodeFallbackType,this.smallMode=((d=p.config)==null?void 0:d.smallMode)||this.smallMode,U.emit(B.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:f}),X.addSuccessEvent({key:521700,cost:Te()-o})}catch(l){throw X.addFailedEvent({key:521700,error:l}),l}})}sendAbilityStatus(e){}enableInsertableStreams(){return Promise.resolve()}switchRoom(e){return Promise.reject()}isSwitchRoomSupported(){return!1}};function LT(i,t=!1){let e=Object.defineProperties(bt(),{postMessage:{value:i.postMessage.bind(i)},port:{get(){return i},set(o){i.onmessage=Ge,i.onmessageerror=Ge,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 Af=class extends fe{constructor(t,e){super(t);let r=new fe(t);r.next=Ge,e(r)}},jG=Ie(Af,"takeUntilComplete");var Ht={useWt:!0,useAINS:!0,useHardDecoder:"prefer-software",useHardEncoder:"prefer-software",unreliable:!1,debug:!1,assetsPath:"",enableUpload:!0},kT="__INLINE__WORKER__",UT="__INLINE__WASM__",{debug:VT}=console;Ht.debug||(console.debug=()=>{});var sv=!kT.startsWith("__"),nv=!UT.startsWith("__");function Vl(){let i=ds(`${Ht.assetsPath?`${Ht.assetsPath}/`:""}worker.js`);return sv?URL.createObjectURL(new Blob([atob(kT)],{type:"application/javascript"})):i.startsWith("http")?fetch(i).then(t=>t.blob().then(e=>URL.createObjectURL(e))):i}var Fc;function Fl(){return y(this,null,function*(){let i=Ht.assetsPath?`${Ht.assetsPath}/`:"";return Fc||(nv?Fc=new TextEncoder().encode(atob(UT)).buffer:Fc=yield fetch(ds(`${i}av_processing.wasm`)).then(t=>t.arrayBuffer()),Fc)})}var yf=class{constructor(){m(this,"playPort");m(this,"playPortSent",!1);m(this,"worklet");m(this,"workletPromise")}init(){return this.workletPromise||(this.workletPromise=this._init()),this.workletPromise}_init(){return y(this,null,function*(){let t=ze("player"),e=Vl();try{yield t.audioWorklet.addModule(typeof e=="string"?e:yield e),F.info("global audio player worklet addModule success",e)}catch(r){throw F.error("global audio player worklet addModule failed:",r),r}return this.worklet=new AudioWorkletNode(t,"global-audio-player",{processorOptions:{wasm:yield Fl(),flag:Ht},numberOfInputs:2}),F.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*(){var r;yield this.init();let e=new MessageChannel;(r=this.playPort)==null||r.postMessage(null,[e.port1]),t(e.port2)})}},Bc=new yf;var bf=(()=>{if(typeof self=="undefined")return!1;if(!("top"in self&&self!==top)){if("showOpenFilePicker"in self)return"showOpenFilePicker"}return!1})(),KG=bf?Promise.resolve().then(function(){return uv}):Promise.resolve().then(function(){return gv});var e5=bf?Promise.resolve().then(function(){return mv}):Promise.resolve().then(function(){return _v});var av=bf?Promise.resolve().then(function(){return pv}):Promise.resolve().then(function(){return Iv});function Rf(...i){return y(this,null,function*(){return(yield av).default(...i)})}var cv=i=>y(void 0,null,function*(){let t=yield i.getFile();return t.handle=i,t}),dv=(...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(a=>{e[n].accept[a]=s.extensions||[]}):e[n].accept["*/*"]=s.extensions||[]});let r=yield window.showOpenFilePicker({id:i[0].id,startIn:i[0].startIn,types:e,multiple:i[0].multiple||!1,excludeAcceptAllOption:i[0].excludeAcceptAllOption||!1}),o=yield Promise.all(r.map(cv));return i[0].multiple?o:o[0]}),uv={__proto__:null,default:dv};function Bl(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 Bl=function(e){this.s=e,this.n=e.next},Bl.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 Bl(i)}var FT=(o,s,...n)=>y(void 0,[o,s,...n],function*(i,t,e=i.name,r){let a=[],d=[];var l,p=!1,f=!1;try{for(var g,A=function(R){var N,C,P,z=2;for(typeof Symbol!="undefined"&&(C=Symbol.asyncIterator,P=Symbol.iterator);z--;){if(C&&(N=R[C])!=null)return N.call(R);if(P&&(N=R[P])!=null)return new Bl(N.call(R));C="@@asyncIterator",P="@@iterator"}throw new TypeError("Object is not async iterable")}(i.values());p=!(g=yield A.next()).done;p=!1){let R=g.value,N=`${e}/${R.name}`;R.kind==="file"?d.push(R.getFile().then(C=>(C.directoryHandle=i,C.handle=R,Object.defineProperty(C,"webkitRelativePath",{configurable:!0,enumerable:!0,get:()=>N})))):R.kind!=="directory"||!t||r&&r(R)||a.push(FT(R,t,N,r))}}catch(R){f=!0,l=R}finally{try{p&&A.return!=null&&(yield A.return())}finally{if(f)throw l}}return[...(yield Promise.all(a)).flat(),...yield Promise.all(d)]}),lv=(...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 FT(e,i.recursive,void 0,i.skipDirectory)}),mv={__proto__:null,default:lv},hv=(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 a=[],d=null;if(i instanceof Blob&&i.type?d=i.type:i.headers&&i.headers.get("content-type")&&(d=i.headers.get("content-type")),t.forEach((f,g)=>{a[g]={description:f.description||"Files",accept:{}},f.mimeTypes?(g===0&&d&&f.mimeTypes.push(d),f.mimeTypes.map(A=>{a[g].accept[A]=f.extensions||[]})):d?a[g].accept[d]=f.extensions||[]:a[g].accept["*/*"]=f.extensions||[]}),e)try{yield e.getFile()}catch(f){if(e=null,r)throw f}let l=e||(yield window.showSaveFilePicker({suggestedName:t[0].fileName,id:t[0].id,startIn:t[0].startIn,types:a,excludeAcceptAllOption:t[0].excludeAcceptAllOption||!1}));!e&&o&&o(l);let p=yield l.createWritable();return"stream"in i?(yield i.stream().pipeTo(p),l):"body"in i?(yield i.body.pipeTo(p),l):(yield p.write(yield i),yield p.close(),l)}),pv={__proto__:null,default:hv},fv=(...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(l=>l.mimeTypes||[]),...i.map(l=>l.extensions||[])].join();o.multiple=i[0].multiple||!1,o.accept=s||"",o.style.display="none",document.body.append(o);let n=l=>{typeof a=="function"&&a(),e(l)},a=i[0].legacySetup&&i[0].legacySetup(n,()=>a(r),o),d=()=>{window.removeEventListener("focus",d),o.remove()};o.addEventListener("click",()=>{window.addEventListener("focus",d)}),o.addEventListener("change",()=>{window.removeEventListener("focus",d),o.remove(),n(o.multiple?Array.from(o.files):o.files[0])}),"showPicker"in HTMLInputElement.prototype?o.showPicker():o.click()})}),gv={__proto__:null,default:fv},Ev=(...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=a=>{typeof n=="function"&&n(),e(a)},n=i[0].legacySetup&&i[0].legacySetup(s,()=>n(r),o);o.addEventListener("change",()=>{let a=Array.from(o.files);i[0].recursive?i[0].recursive&&i[0].skipDirectory&&(a=a.filter(d=>d.webkitRelativePath.split("/").every(l=>!i[0].skipDirectory({name:l,kind:"directory"})))):a=a.filter(d=>d.webkitRelativePath.split("/").length===2),s(a)}),"showPicker"in HTMLInputElement.prototype?o.showPicker():o.click()})}),_v={__proto__:null,default:Ev},Tv=(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(d,l){return y(this,null,function*(){let p=d.getReader(),f=new ReadableStream({start:R=>function N(){return y(this,null,function*(){return p.read().then(({done:C,value:P})=>{if(!C)return R.enqueue(P),N();R.close()})})}()}),g=new Response(f),A=yield g.blob();return p.releaseLock(),new Blob([A],{type:l})})}(i.body,i.headers.get("content-type"))),o.download=t.fileName||"Untitled",o.href=URL.createObjectURL(yield s);let n=()=>{typeof a=="function"&&a()},a=t.legacySetup&&t.legacySetup(n,()=>a(),o);return o.addEventListener("click",()=>{setTimeout(()=>URL.revokeObjectURL(o.href),3e4),n()}),o.click(),null}),Iv={__proto__:null,default:Tv};var vf=class{constructor(t){this.name=t;m(this,"ready");m(this,"worker");m(this,"ports");m(this,"ids",1);m(this,"transactions",new Map);m(this,"log");m(this,"addTransaction",t=>(this.transactions.set(++this.ids,t),this.ids))}postMessage(t,e){var r;(r=this.worker)==null||r.postMessage(t,e)}create(t){return y(this,null,function*(){if(this.ready)return this.ready;t||(t=this.name),console.time(`createWorker_${t}`);let e=Vl(),r=new Worker(typeof e=="string"?e:yield e,{name:t});return this.worker=r,this.ready=new Promise((o,s)=>y(this,null,function*(){r.onmessage=({data:{id:n,type:a,payload:d}})=>{var l;if(n)(l=this.transactions.get(n))==null||l(d),this.transactions.delete(n);else switch(a){case"error":console.timeEnd(`createWorker_${t}`),console.warn("worker error:",d),s(d);break;case"ready":console.timeEnd(`createWorker_${t}`),o(this);break;case"updateAFSM":if(d.value){let p=typeof d.old=="string"?d.old:`${d.old.action}ing`,f=typeof d.value=="string"?d.value:`${d.value.action}ing`;console.log(vd(),d.group,d.name,p,"\u{1F449}",f)}break;case"log":console.log(d);break;case"glog":window.dispatchEvent(new CustomEvent(a,{detail:d}));break}},r.postMessage({wasm:yield Fl(),flag:Ht},this.ports)}))})}destroy(){var t;console.log("destroy worker",this.name),delete this.ready,(t=this.worker)==null||t.terminate()}},Cf=class{constructor(t,e,r){this.worker=t;m(this,"channel",new MessageChannel);m(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()}},Nf=class i extends vf{constructor(){super("main");m(this,"switchValue",new Map);m(this,"extendChannel");m(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 wt(i.prototype,this,"create").call(this),this.switchValue.forEach((e,r)=>{this.extendChannel.port1.postMessage([r,e])}),this)})}},$o=new Nf,Hs,$T=-1;function BT(i){return console.log(i),Hs.push(i.slice()),Hs.length>1e3&&Hs.shift(),i}function HT(i){return y(this,null,function*(){switch($T){case 0:this.edpl.willDecodeAudio=BT;break;case 2:this.edpl.didEncodeAudio=BT;break}yield $o.create(),U.emit(B.JOIN_SEND_CMD,{room:this});let t=new Cf($o,i,o=>{let s=o.data;if(typeof s=="string")this.onWorkerEvent(s);else if(s==null)this.onWorkerEvent("client-banned",0),t.destroy();else{let{cmd:n,payload:a}=s;this.onWorkerEvent(n,a)}}),{err:e,data:r}=yield t.ready;if(typeof e=="number"){if(U.emit(B.JOIN_RECEIVED_CMD_RES,{room:this,code:e}),e===0)return Object.assign(this,r,{session:t});throw new se({code:q.JOIN_ROOM_FAILED,extraCode:Number(e),message:We({key:He.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:e,errorMsg:""}})})}else throw e})}Object.defineProperties(window,{useAINS:{set:Df},useWt:{set:Sv},enableDebug:{set(i){console.debug=i?VT:()=>{},$o.setSwitchValue("enableDebug",i)}},useV2:{set:wf},dump:{value(i=0){if($T=i,Hs||(console.warn("dump audio will be activated at next time join room"),Hs=[]),!Hs.length){console.warn("no audio data to dump,try it later");return}let t=[];return Hs.forEach(e=>{t.push(new Uint16Array([e.length])),t.push(e)}),Rf(new Blob(t),{fileName:"audio dump hex",extensions:[".hex"]})}},dumpAudio:{value(i="audio",t=2e3){let e=[],r=new Promise(o=>{let s=new MessageChannel;$o.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,$o.extendChannel.port1.postMessage(["dump",i]),s.port2.close(),o(new Blob(e)))}});return Rf(r,{fileName:i,extensions:[".pcm"]})}},hardDec:{set(i){switch(i){case!0:Ht.useHardDecoder="prefer-hardware";break;case!1:Ht.useHardDecoder="prefer-software";break;default:Ht.useHardDecoder="no-preference"}}}});function Df(i){return y(this,null,function*(){$o.setSwitchValue("useAINS",i)})}function wf(i){return y(this,null,function*(){$o.setSwitchValue("useV2",i)})}function Sv(i){return y(this,null,function*(){$o.setSwitchValue("useWt",i)})}function WT(i){let t=new MediaStreamTrackGenerator({kind:"audio"});i.setInputMediaStreamTrack(t),i.player.setVolume(0),this.postMessage({cmd:"pullAudio",payload:{tinyId:i.tinyId,writable:t.writable}},[t.writable])}function GT(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),ye(LT(r.port2),Je(Ae(i,ue.INIT)),Le(s=>{let{data:n,packetsReceived:a}=s;i.stat.packetsReceived=a,i.stat.framesReceived++,e++;let d=n[4]&31;if(e<=10){let p=Array.from(n.slice(0,10)).map(f=>f.toString(16).padStart(2,"0")).join(" ");this._log.info(`Frame ${e} - Size: ${n.length} bytes, Type: ${d}, Timestamp: ${Date.now()-t}ms First 10 bytes: ${p}`)}let l;switch(d){case 5:case 7:l="key";break;default:l="delta";break}i.isAvailable?i.decodeFrame({data:n.buffer,type:l,timestamp:(Date.now()-t)*1e3}):console.warn("track is not available")},()=>{},()=>{r.port2.postMessage(null),r.port2.close()}))})}var $l=[];function qT(i){var d;let t=bt();if(this.state!=="joined")throw new Error("Room is not joined");if(i.state==="publish")return;for(let l=0;l<=$l.length;l++)if(!$l[l]){$l[l]=this,this.index=l;break}let e=i.profile;this._log.info("start push audio",this.index,e);let r=new MessageChannel,o=i.enableEncryptFrame?new MessageChannel:null;(d=this.session)==null||d.postMessage({cmd:"pushAudio",payload:Y({index:this.index},e)},o?[r.port2,o.port2]:[r.port2]),r.port1.onmessage=l=>{l.data==null||(typeof l.data=="number"?t.next(l.data):o&&o.port1.postMessage(_e(Y({},l.data),{data:new Uint8Array(i.encodeFrame({data:l.data.data.buffer,timestamp:l.data.timestamp}).data)})))};let s=new MediaStream,n,a=l=>{let p=s.getAudioTracks()[0];p&&(n.disconnect(),s.removeTrack(p)),s.addTrack(l),this._log.info("push audio track:",l.readyState,l.getSettings().deviceId),n=ze("player").createMediaStreamSource(s),n.connect(Bc.worklet,0,this.index)};ye(Ae(i,"output-media-track-changed"),Je(Ae(i,"ready")),Le(a,console.error,()=>{this._log.info("stop push audio",e),i.volume=0,n.disconnect(),$l[this.index]=null,o&&o.port1.postMessage(null),r.port1.postMessage(null)})),ye(t,Ds(l=>i.volume=l),qi(Ju(1e3)),Le(()=>{i.volume=0})),a(i.outMediaTrack)}var P5=new Intl.DateTimeFormat("zh-CN",{dateStyle:"short",timeStyle:"medium"});var Of=class{constructor(t,e,r,o){this.localTrack=t;this.type=e;this.config=r;this.port=o;m(this,"track");m(this,"label");m(this,"insertKeyFrame",!0);m(this,"session");m(this,"tsMap",new Map);t._log.info("create Video Encoder",r)}trans(t,e,r){return y(this,null,function*(){let o=yield this.recreate(r,{recreateCount:0,frameEncoded:0,selectConfigIndex:0});e.signal.addEventListener("abort",()=>{o.encoder.close()});let s=0;return t.pipeThrough(new TransformStream({transform:(n,a)=>{o.encoder.state==="configured"&&(this.tsMap.set(s,Date.now()),this.encode(n),s++,a.enqueue(n))}}),e)})}encode(t){var e,r;(r=(e=this.session)==null?void 0:e.encoder)==null||r.encode(t,{keyFrame:this.insertKeyFrame}),this.insertKeyFrame=!1}start(t,e,r){return y(this,null,function*(){let o=yield this.recreate(r,{recreateCount:0,frameEncoded:0,selectConfigIndex:0});this.session=o;let s=0;t.pipeTo(new WritableStream({write:n=>{o.encoder.state==="configured"&&(s<10&&this.localTrack.log.info(`capture ${this.label} track frame:`,s,Date.now(),n.timestamp,n.displayWidth,n.displayHeight),(n.displayWidth!==this.config.width||n.displayHeight!==this.config.height)&&(this.localTrack.log.info("resize video track frame:",n.displayWidth,n.displayHeight,this.config.width,this.config.height),this.configure({width:n.displayWidth,height:n.displayHeight},o)),this.tsMap.set(s,Date.now()),this.encode(n),s<10&&this.localTrack.log.info(`encode ${this.label} track frame:`,s),s++,n.close())}}),e).catch(n=>{this.localTrack.log.warn(n),o.encoder.close()})})}recreate(t,e){return y(this,null,function*(){let r=0,o=new VideoEncoder({output:s=>{let n=this.tsMap.get(r);if(this.tsMap.delete(s.timestamp),r<10&&(r===0&&e.recreateCount===0&&U.emit(B.SEND_FIRST_VIDEO_FRAME,{room:t}),this.localTrack.log.info(`encoded ${this.label} track frame:`,r,Date.now(),s.timestamp)),r++,e.frameEncoded=r,this.track.enabled===!1)return;let a=null;if(this.localTrack.enableEncodeFrame){a=new Uint8Array(s.byteLength),s.copyTo(a);let d=this.localTrack.encodeFrame({data:a.buffer},this.type===3);a=new Uint8Array(d.data)}a?(this.localTrack.stat.bytesSent+=a.length,this.port.postMessage({chunk:{type:s.type,timestamp:s.timestamp,data:a,duration:s.duration},timestamp:n},[a.buffer])):(this.localTrack.stat.bytesSent+=s.byteLength,this.port.postMessage({chunk:s,timestamp:n}))},error:s=>{this.localTrack.log.warn(s,this.config),e.recreateCount++,setTimeout(()=>this.recreate(t,e),100)}});return e.encoder=o,yield this.configure(null,e),e})}configure(t,e){return y(this,null,function*(){var r;t&&Object.assign(this.config,t),(r=e.encoder)==null||r.configure(this.config)})}close(){this.port.postMessage(null),this.port.close()}};function Hl(i,t){return y(this,null,function*(){let e=i.mediaType===2,r=e?"screen":"video",o={codec:"avc1.420028",latencyMode:"realtime",avc:{format:"annexb"},hardwareAcceleration:Ht.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 Of(i,t.type,o,s.port2);return s.port2.onmessage=a=>{if(a.data===260)n.insertKeyFrame=!0;else if(!e){let{bitrate:d}=a.data;Ta({configureBr:[a.data.bitrate,d]}),n.session&&n.configure({bitrate:d},n.session)}},this._log.info("start push",r,t),n})}function zT(i){return y(this,null,function*(){var p;let t=i.mediaType===2,e=t?"screen":"video",r={type:t?7:2,profile:i.profile,trackType:t?"screen":"camera",crypto:!!((p=i.manager)!=null&&p.encodePipeline[0])};!t&&i.outMediaTrack instanceof CanvasCaptureMediaStreamTrack&&(r.trackType="canvas");let{trackType:o}=r,{width:s,height:n}=i.outMediaTrack.getSettings();r.profile.width=s,r.profile.height=n;let a=yield Hl.call(this,i,r);this._log.info("VideoEncoder created",r);let d,l=f=>y(this,null,function*(){if(d==null||d.abort("track changed"),!f)return;d=new AbortController;let{width:g,height:A,displaySurface:R}=f.getSettings();g&&(a.config.width=g),A&&(a.config.height=A);let N=sr.match(/Chrome\/(\d+)/);(N==null?void 0:N[1])==="114"&&R==="browser"&&delete a.config.hardwareAcceleration,this._log.info("push",e,"track:",f.readyState,f.getSettings());let C;if(typeof MediaStreamTrackProcessor!="undefined"&&!(f instanceof CanvasCaptureMediaStreamTrack))C=new MediaStreamTrackProcessor({track:f}).readable;else{let z;C=new ReadableStream({start(H){i.on("render",ge=>{if(!(i.player.mode===0&&!document.hidden))try{H.enqueue(new VideoFrame(ge,{timestamp:performance.now()*1e3}))}catch(Ue){console.warn(Ue)}})},pull(H){return y(this,null,function*(){if(i.player.mode===0&&zr()&&i.player.element)return new Promise(ge=>{i.player.element.requestVideoFrameCallback((Ue,W)=>{try{let we=new VideoFrame(i.player.element);H.enqueue(we)}catch(we){console.warn(we)}ge()})})})}})}let P="small"in i&&i.small;return P?(this.smallEncoder||(this.smallEncoder=yield Hl.call(this,i,{profile:P,type:3,trackType:o})),this.smallEncoder.track=f,this.smallEncoder.label="small",C=yield this.smallEncoder.trans(C,d,this)):this.smallEncoder&&(this.smallEncoder.close(),delete this.smallEncoder),a.track=f,a.label=e,a.start(C,d,this)});return ye(Ae(i,"output-media-track-changed"),Je(Ae(i,"ready")),Le(l,console.error,()=>{var f;this._log.info("stop push",e,r),d.abort("unpublish"),a.close(),(f=this.smallEncoder)==null||f.close()})),l(i.outMediaTrack)})}var Ho=class Ho extends ue{constructor(e){var r,o;super((o=(r=e.roomid)==null?void 0:r.toString())!=null?o:e.name,"volumeEvaluation");this.room=e;m(this,"enableInBackground",!1);m(this,"interval",400);e.on("joined",()=>{this.emit(Ho.INTERVALCHANGED,this.interval)}),ye(Ae(this,Ho.INTERVALCHANGED),ui(s=>this.room.state==="joined"?this.room.fromWorker("getAudioEnergy",s):ye(ZE(s),wo(()=>[]))),Le(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==ue.ON&&this.room.emit("audio-volume",s)}))}start(e,r){this.interval=e,this.enableInBackground=r,this.emit(Ho.INTERVALCHANGED,this.interval)}stop(){}};m(Ho,"INTERVALCHANGED","intervalChanged"),Z([et([ue.INIT,ue.OFF],ue.ON)],Ho.prototype,"start",1),Z([et([],ue.OFF)],Ho.prototype,"stop",1);var Wl=Ho;var Wo=class Wo extends Ul{constructor(e){super(e);m(this,"index",0);m(this,"session");m(this,"tinyid");m(this,"roomid");m(this,"openid");m(this,"socketid");m(this,"relayip");m(this,"clientip");m(this,"remotePublishedUserMap",new Map);m(this,"bussinessInfo");m(this,"token");m(this,"audioVolumeEvalution",new Wl(this));m(this,"enableAIVoice",Df);m(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:Wm(),uint32_device_type:0,str_os_verion:Gm(),uint32_link_type:1,str_client_version:pt,uint32_net_type:rs[si.getNetworkType()],ua:navigator.userAgent,version:""}});m(this,"joinAbortController",new AbortController);m(this,"smallAbortCtrl");m(this,"smallEncoder");e.tinyId&&(this.tinyId=e.tinyId,wf(!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=a=>{n.port2.close(),o(a.data)}})}fromWorker(e,r){if(this.state!="joined")throw"join room first";return o=>{var n;let s=new MessageChannel;s.port2.onmessage=a=>{a.data?o.next(a.data):o.complete()},s.port2.onmessageerror=a=>o.error(a),o.defer(()=>{s.port2.postMessage(null),s.port2.close()}),(n=this.session)==null||n.postMessage({cmd:e,payload:r},[s.port1])}}switchRole(e){return 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 d,l,p;let s=si.getEnv(),n=hu(),a={isH264EncodeSupported:this.checkSystemResult.detail.isH264EncodeSupported,isVp8EncodeSupported:this.checkSystemResult.detail.isVp8EncodeSupported,frameWorkType:o,params:e,proxy_wt:(d=this.proxy_wt)==null?void 0:d.replace("https://",""),proxy_ws:(l=this.proxy_ws)==null?void 0:l.replace("wss://",""),proxy_cloud:(p=this.scheduleResult.iceServers)!=null&&p.length?this.scheduleResult.iceServers[0].urls:[],proxy_unified:this.proxy_unified,domains:this.scheduleResult.domains,env:s,osName:yn(),browserInfo:hu(),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:pt,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 HT.call(this,a),console.log(this),Bc.playAudio(f=>this.postMessage({cmd:"setAudioWorkletPort"},[f])),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()),this.localTracks.clear()})}getSignalInfo(){return{tinyId:this.tinyid,clientIp:this.clientip,signalIp:"",relayIp:this.relayip,relayInnerIp:"",relayPort:0}}enableAudioVolumeEvaluation(e=2e3,r=!1){e<=0?this.audioVolumeEvalution.stop():this.audioVolumeEvalution.start(e,r)}getLocalAudioStats(){return this.sendMessage("getLocalAudioStats")}getLocalVideoStats(){return this.sendMessage("getLocalVideoStats")}afterJoin(){return y(this,null,function*(){let e=Je(Ae(this,"left")),r=this.audioManager.decodePipeline.some(o=>o);ye(o=>y(this,null,function*(){let s=new MessageChannel;s.port2.onmessage=n=>{n.data?o.next({data:n.data,port:s.port2}):o.complete()},s.port2.onmessageerror=n=>o.error(n),o.defer(()=>{s.port2.postMessage(null),s.port2.close()}),this.postMessage({cmd:"decodeAudio",payload:r},[s.port1])}),e,Le(({data:o,port:s})=>{var a;let n={data:o.data.buffer};for(let[d,l]of this.audioManager.decodePipeline.entries())if(l&&(n=l({frame:n,track:(a=this.remotePublishedUserMap.get(o.userId))==null?void 0:a.remoteAudioTrack}),!n))return;s.postMessage(_e(Y({},o),{data:new Uint8Array(n.data)}),[n.data])}))})}onWorkerEvent(e,r){switch(e!=="network-quality"&&console.info(this.userId,"onWorkerEvent",e,JSON.stringify(r)),e){case B.RECEIVED_PUBLISHED_USER_LIST:U.emit(e,Y({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 wl(this,r);this.remotePublishedUserMap.set(r.userId,o),this.emit("remote-published",o);return;case"5":{let f=r,g=this.remotePublishedUserMap.get(f);g&&(g.remoteVideoTrack.close(),g.remoteAuxiliaryTrack.close(),g.remoteAudioTrack.close(),this.remotePublishedUserMap.delete(f),this.emit("remote-unpublished",g))}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:f,muteState:g,flag:A}=r,R=this.remotePublishedUserMap.get(g.userId);if(!R){this.emit("remote-publish-state-changed",r);return}R.flag=A}U.emit(B.REMOTE_PUBLISH_STATE_CHANGED,Y({room:this},r)),this.emit("remote-publish-state-changed",r);return;case"7":this.localPublishFlag!==r.flag&&(this.localPublishFlag=r.flag,this.emit("local-publish-flag-changed",r.flag));return;case"network-quality":this.quality=Y({},r);let{uplinkLoss:s,uplinkRTT:n,uplinkInfo:a,downlinkInfo:d,msg_down_stream_info:l}=r,p={str_sdk_version:pt,uint64_datetime:Date.now(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyid},msg_device_info:{uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:rs[cn()]},msg_event_msg:t_(this.userId),str_acc_ip:this.relayip,str_client_ip:this.clientip,msg_up_stream_info:a,msg_down_stream_info:l};U.emit(B.HEARTBEAT_REPORT,{room:this,report:p}),this.emit("heartbeat-report",p),U.emit(B.NETWORK_QUALITY,{room:this,uplink:{rtt:n,loss:s},downlinks:d}),delete r.downlinkInfo;break;case"signal-connection-state-changed":U.emit(B.SIGNAL_CONNECTION_STATE_CHANGED,Y({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*(){switch(yield this.sendMessage("publish",e.mediaType).then(r=>r.err!==0?Promise.reject(r.err):r),Ft(e,e).add("mute",()=>{this.postMessage("mute",{mediaType:e.mediaType,userId:this.userId,srctinyid:this.tinyid,remove:!0})}).add("unmute",()=>{this.postMessage("unmute",{mediaType:e.mediaType,userId:this.userId,srctinyid:this.tinyid,add:!0})}),e.mediaType){case 1:yield Bc.init(),qT.call(this,e);break;default:yield zT.call(this,e)}e.muted&&this.postMessage("mute",{mediaType:e.mediaType,srctinyid:this.tinyid,userId:this.openid,remove:!0})})}unpublish(e){return y(this,null,function*(){At(e)})}subscribe(...e){return y(this,null,function*(){let r=e.reduce((f,g)=>g.mediaType|f,0),{userId:o,tinyId:s,streamType:n}=e[0],a=this.remotePublishedUserMap.get(o),d=Y({},a.subscribeState),l=Object.assign(new Va,d);l.mediaType|=r,U.emit(B.SUBSCRIBE_START,{room:this,streamType:n,remotePublishedUser:a,subscribeState:l});let p=yield this.sendMessage("subscribe",{mediaType:l.mediaType,userId:o,srctinyid:s,mediaDescription:{audioParam:{mediaType:1,payloadFmtps:[{payloadType:111,fmtp:"minptime=10;useinbandfec=1"}]},videoParam:[4,8,2].filter(f=>l.mediaType&f).map(f=>({mediaType:f,payloadFmtps:[{payloadType:100,fmtp:"packetization-mode=1;profile-level-id=42e01f"}]}))}});console.dir("subscribe",p),yield Promise.all(e.filter(f=>!f.isSubscribed).map(f=>{switch(f.mediaType){case 1:return WT.call(this,f);default:return GT.call(this,f)}})),U.emit(B.SUBSCRIBE_SUCCESS,{room:this,streamType:n,remotePublishedUser:a})})}unsubscribe(...e){return y(this,null,function*(){let r=0;for(let o of e)r|=o.mediaType;if(e.length){let{userId:o,streamType:s,tinyId:n}=e[0];yield this.sendMessage("unSubscribe",{mediaType:r,srctinyid:n,userId:o});for(let a of e)a.unsubscribe();U.emit(B.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 Hl.call(this,o,{profile:o.small,type:3,trackType:"camera"});let s=new MediaStreamTrackProcessor({track:this.videoManager.smallTrack}).readable;this.smallEncoder.track=this.videoManager.smallTrack,this.smallEncoder.label="small",this.smallAbortCtrl=new AbortController,this.smallEncoder.start(s,this.smallAbortCtrl,this),this._log.info("push small")}}else(r=this.smallAbortCtrl)==null||r.abort("stop"),this.smallEncoder&&(this.smallEncoder.close(),delete this.smallEncoder)})}changeType(e,r){let o=this.remotePublishedUserMap.get(r.userId);if(!o)return;let s=e?8:4;if(o.remoteVideoTrack.mediaType===s)return;let n={srctinyid:o.tinyId,mediaType:s,userId:r.userId,mediaDescription:{audioParam:{mediaType:1,payloadFmtps:[{payloadType:111,fmtp:"minptime=10;useinbandfec=1"}]},videoParam:[4,8].filter(a=>s&a).map(a=>({mediaType:a,payloadFmtps:[{payloadType:100,fmtp:"packetization-mode=1;profile-level-id=42e01f"}]}))}};o.remoteVideoTrack.mediaType=n.mediaType,this.postMessage("changetype",n)}destroy(){this.isDestroyed||(super.destroy(),this.isDestroyed=!0,this.joinAbortController.abort("destroy"))}};Z([No(Wo.prototype.afterJoin),et(["left",ue.INIT],"joined"),bT()],Wo.prototype,"join",1),Z([et("joined","left",{ignoreError:!0}),RT()],Wo.prototype,"leave",1),Z([Mu(e=>e.mediaType),vT()],Wo.prototype,"publish",1),Z([Mu(e=>e.mediaType),CT()],Wo.prototype,"unpublish",1),Z([Mu((...e)=>e[0].userId),NT()],Wo.prototype,"subscribe",1);var Gl=Wo;Qn.frameWorkType=37;Qn.create=function(i){let t=Qn._create.call(this,Gl,i);return t._use(Zp,i==null?void 0:i.assetsPath),i!=null&&i.assetsPath&&(Ht.assetsPath=i==null?void 0:i.assetsPath),console.log("trtc wasm sdk:",pt,"created",Ht),t};Object.assign(Qn.prototype,{_setCurrentSpeaker(i){let t=ze("player");return t!=null&&t.setSinkId?t.setSinkId(i):Promise.reject("not support")},_enableVideoDecodeFallback(i,t){return y(this,null,function*(){return this.startPlugin(Zp.Name,{type:"webCodecs",renderer:"videoFrame",track:i,config:{codec:"avc1.640028",hardwareAcceleration:"prefer-software",optimizeForLatency:!0},fallback:"wasm"}),new Promise((e,r)=>{ye(Ae(i,"decode-downgrade-state-changed"),tr(o=>o.state==="STARTED"),Qr(1),vp(1e4),Je(Ae(i,ue.INIT)),Le(e,r))})})}});Sh(37);var a6=Qn;export{a6 as default};
140
+ }`});m(this,"yTextureRef");m(this,"uTextureRef");m(this,"vTextureRef");m(this,"Y");m(this,"U");m(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 MT=(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 rv(i){return i[0]===0&&i[1]===0&&i[2]===0&&i[3]===1}var iv=0,kl=class{constructor(t){m(this,"id",iv++);m(this,"trackDoneOB");m(this,"startOB");m(this,"stopOB");m(this,"decoder");m(this,"videoContext");m(this,"gop",0);m(this,"gop_helper",0);m(this,"waitFirstKeyFrame",!0);m(this,"startTimestamp",0);m(this,"startTime",0);m(this,"startPerformanceTime",0);m(this,"inputFrameCount",0);m(this,"decodedFrameCount",0);m(this,"decodeFrameCount",0);m(this,"downgradeLevel",0);m(this,"lastDowngradeTime",0);m(this,"lastFrameDiff",0);m(this,"lastDecodeFrameTimestamp",0);m(this,"config");m(this,"gop_before_configure",[]);m(this,"videoElement");m(this,"type","wasm");m(this,"goodType");m(this,"renderer","2d");m(this,"wasmOption");m(this,"createDecoder");m(this,"_decodeSink");m(this,"isReported",!1);m(this,"track");m(this,"stateChangeOB");m(this,"failedReason");let{track:e,createDecoder:r}=t;if(this.stateChangeOB=bt(),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=Ae(e.availableState,ue.OFF),this.stopOB=bt(),t.type==="auto"){switch(t.fallback){case"wasm":this.type="wasm",this.renderer="webgl";break;case"wasm_2d":this.type="wasm",this.renderer="2d";break;case"wasm_video":this.type="wasm",this.renderer="videoFrame";break;default:this.type="webCodecs"}this.wasmOption.yuvMode=this.renderer==="webgl"}else this.type=t.type;this.changeRenderer(this.renderer),ye(this.stateChangeOB,Ap((o,s)=>(o!==s&&e.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:this.failedReason,prevState:o,state:s}),s),"INITIALIZED"),Je(this.stopOB),Le()),this.start()}start(t=0){this.waitFirstKeyFrame=!0,this.stateChangeOB.next("STARTING");let e=ye(this.pipe(this.track),Je(this.stopOB),ji());ye(e,Le(()=>{this.track.stat.framesDecoded++},r=>{if(this.track.log.error(`${this.id} play failed: ${r} retryCount: ${t}`),X.addFailedEvent({key:MT(this.type,this.renderer),error:r}),t>4)this.failedReason=r,this.stateChangeOB.next("FAILED"),X.addFailedEvent({key:514704});else{if(this.goodType){this.start(t);return}switch(this.type){case"webCodecs":this.type="wasm",this.changeRenderer("webgl");break;case"wasm":switch(this.renderer){case"webgl":this.changeRenderer("videoFrame");break}}this.start(t+1)}},()=>{this.track.log.warn(`${this.id} decoderOB completed`),X.addSuccessEvent({key:MT(this.type,this.renderer)}),X.addSuccessEvent({key:514704})})),ye(e,Qr(1),Le(()=>{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"&&!fh()&&(this.renderer="2d"),this.wasmOption.yuvMode=this.renderer==="webgl"}decode(t,e=!1){var a,d;if(this.failedReason)return;this.inputFrameCount++;let r=new Uint8Array(t.data);if(!rv(r)||r.length<5)return this.stateChangeOB.next("FAILED"),this.close(`not h26x frame ${r.subarray(0,5)}`),t;let o=r[4]&31,s=!1;switch(o){case 5:case 7:s=!0;break}if(((a=this.decoder)==null?void 0:a.state)!=="configured")return this.track.log.debug(`not configured ${this.inputFrameCount}`),s&&(this.gop_before_configure=[]),this.gop_before_configure.push({data:t.data,timestamp:t.timestamp,type:t.type}),t;this.gop_before_configure.length>0&&!e&&(this.gop_before_configure.forEach(l=>this.decode(l,!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=Te();else{this.track.log.debug(`wait first key frame ${this.inputFrameCount} ${r.subarray(0,5).join(" ")}`);return}switch(this.downgradeLevel){case 0:break;case 1:break;case 2:if(this.gop_helper>this.gop>>1)return;break;case 3:if(this.gop_helper>0)return;break;default:return}(this.decodeFrameCount<10||this.decodeFrameCount%500===0)&&this.track.log.debug(`decode ${this.decodeFrameCount} gop: ${this.gop} ${n} ${(d=t.getMetadata)==null?void 0:d.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 a;o&&(t.player.setCanvas(),t.setInputMediaStreamTrack(o)),r==null||r.close(),(a=this.videoContext)==null||a.destroy(),delete this._decodeSink});let{renderer:s,type:n}=this;t.log.info(`decoder type: ${this.type} renderer: ${this.renderer}`);try{switch(n){case"wasm":r=this.createDecoder(n,this.wasmOption);break;case"webCodecs":r=this.createDecoder(n);break;default:throw new Error("not supported yet")}let a=0;if(r.on("videoFrame",d=>{this.decodedFrameCount++,a++,(a<=10||a%500===0)&&t.log.debug(`frame ${a} ${this.decodedFrameCount}/${this.decodeFrameCount} decoded ${d.timestamp}`),Date.now()-this.lastDowngradeTime>5e3&&(this.type==="webCodecs"?this.checkDowngradeByFrameDiff():this.type==="wasm"&&this.checkDowngradeByTimestampDiff(d.timestamp)),e.next(d)}),r.on("error",d=>{t.log.error(d),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 Nt({frameRate:15,logger:t.log,name:t.userId}),this.videoContext.create(),this.videoContext.on(Nt.UNAVAILABLE,l=>{t.log.error(l),e.error(7)});let d=new Ll(this.videoContext);r.on("videoCodecInfo",l=>d.resize(l.width,l.height)),r.on("videoFrame",l=>{({y:d.Y,u:d.U,v:d.V}=l),this.downgradeLevel===1?this.decodedFrameCount%2===0&&d.render(this.decodedFrameCount):d.render(this.decodedFrameCount)}),t.source=d,t.player.setCanvas(this.videoContext._canvas,2)}else if(s==="videoFrame"){t.player.setCanvas();let d=new MediaStreamTrackGenerator({kind:"video"}),l=d.writable.getWriter();t.setInputMediaStreamTrack(d),r.on("videoFrame",p=>l.write(p))}else{this.videoContext=new Lt({frameRate:15,logger:t.log,name:t.userId}),this.videoContext.create({alpha:!1});let d=this.videoContext.createVideoImageSource();r.on("videoFrame",p=>{try{d.image=p,d.update()}catch(f){delete this.goodType,t.log.error(f),e.error(11)}});let l=new Ms(this.videoContext,{name:"remotePlayer",logger:t.log});d.connect(l),t.source=d,t.player.setCanvas(this.videoContext._canvas,2)}this.decoder=r}catch(a){t.log.error(a),e.error(n==="webCodecs"?2:6)}})}};var xT=Promise.resolve(),Vc=class extends PT.EventEmitter{constructor(e){super();this.room=e;m(this,"videoContext");m(this,"_glVideoContext");m(this,"_2dVideoContext");m(this,"destination");m(this,"smallVideoContext");m(this,"smallDestination");m(this,"smallTrackSource");m(this,"smallImageSource");m(this,"_isMirror",!1);m(this,"_rotation",0);m(this,"cameraTrack");m(this,"cameraNode");m(this,"transformNode");m(this,"mixNode");m(this,"screenTrack");m(this,"screenNode");m(this,"selfModel",!1);m(this,"blurRadius",3);m(this,"arTrack");m(this,"_enableFaceCentering",!1);m(this,"_enableEffectOptimization",!1);m(this,"onAbort");m(this,"_color");m(this,"Wasm");m(this,"waterMarkNode");m(this,"_waterMarkOption");m(this,"watermarkImageList",[]);m(this,"_beautyParams");m(this,"isUsingArTrack",!1);m(this,"mixTrack");m(this,"_isMixScreen",!1);m(this,"_virtualBackground");m(this,"_virtualBackgroundAbortCallback");m(this,"virtualBackgroundInstance");m(this,"_bgAssetPath");m(this,"log");m(this,"_mat4");m(this,"_postProcessing");m(this,"_checkId",0);m(this,"_use2d",!1);m(this,"_autoSwitchRenderMode",!0);m(this,"encodePipeline",[]);m(this,"decodePipeline",[]);m(this,"updated",xT);m(this,"_updateFlag",!1);this.log=F.createLogger({parent:e==null?void 0:e.getLogger(),id:"vm",userId:e==null?void 0:e.userId,sdkAppId:e==null?void 0:e.sdkAppId}),this.smallVideoContext=new Lt({frameRate:15,logger:this.log,name:"s"}),this.enablePrintDetail()}get smallMode(){var e;return((e=this.room)==null?void 0:e.smallMode)||"canvas"}get _hasVirtualBg(){return!!this._virtualBackground}get _hasWaterMark(){return this.watermarkImageList.length>0}get _isRotate(){return this._rotation!==0}get _isTransform(){return this._isMirror||this._isRotate}get renderMode(){return this._autoSwitchRenderMode?"auto":this._use2d?"2d":"webgl"}set renderMode(e){if(this._autoSwitchRenderMode=e==="auto",this._autoSwitchRenderMode)return;let r=e==="2d";this._use2d!==r&&(this._use2d=r,this.clear(),this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.update())}get cameraResolution(){var o;let{width:e,height:r}=((o=this.cameraTrack)==null?void 0:o.settings)||{};return fr(this._rotation)?{width:r,height:e}:{width:e,height:r}}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new Lt({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this._2dVideoContext}getGlVideoContext(){if(!this._glVideoContext)this._glVideoContext=new Nt({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(Lm<=22),this._glVideoContext.on(Nt.UNAVAILABLE,e=>{var r;this.emit("error",e),this.log.warn("video context unavailable",e),(r=this._virtualBackgroundAbortCallback)==null||r.call(this,e),this.update().catch(o=>{this.log.error(o)})})}catch(e){this.emit("error",e)}}initVirtualBackground(e,r,o){this.onAbort=e,this._mat4=r,this._postProcessing=o}enablePrintDetail(e=2e3){this._checkId=gt.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(),gt.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(vr||this._isMixScreen||this._isTransform||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}sendCreateResult(e="videoCtxGl",r){let o=e==="videoCtxGl"?512700:512701;r?X.addFailedEvent({key:o,error:r}):X.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 Nt({frameRate:15,logger:this.log,name:"m"}),this.initializeGlVideoContext(),this._glVideoContext.available)return this.videoContext=this._glVideoContext,this.videoContext.available;this.log.warn("webgl is still not available"),this.clear(),this._use2d=!0}return this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.videoContext.available}get smallTrack(){var e;return(e=this.smallDestination)==null?void 0:e.videoTrack}get hasSmall(){return!!this.smallTrack}get initialTrack(){var e;return(e=this.cameraTrack)==null?void 0:e.mediaTrack}setSmallVideo(e,r){if(this.smallMode!=="api")if(e){if(!this.smallVideoContext.available){if(this.smallVideoContext.create({alpha:!1}),!this.smallVideoContext.available)return;this.smallDestination=new Qu(this.smallVideoContext,e,this.log),this.smallVideoContext.on(Nt.UNAVAILABLE,o=>{this.log.warn("small video context lost",o)})}if(this.smallVideoContext.frameRate=e.frameRate,this.smallDestination.resolution=e,r)this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=r:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(r),this.smallImageSource.resize(r.width,r.height),this.smallImageSource.connect(this.smallDestination));else if(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource)this.smallTrackSource.replaceTrack(this.initialTrack);else{this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack,"smallTrackSource");let{width:o,height:s}=this.cameraTrack.settings;this.smallTrackSource.resize(o,s),this.smallTrackSource.connect(this.smallDestination)}}else this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource)}_setMainOutput(e){var r;try{let o=this.cameraTrack,{small:s,player:n}=o;vr&&n.setCanvas(e);let a=e&&((r=this.destination)==null?void 0:r.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),a=this.arTrack),this.log.info(`set main output ${a?a.label:"no output track"}`),this.setSmallVideo(s,e),o.setOutputMediaStreamTrack(a)}catch(o){this.log.error("set main output failed",o)}}update(e=!1){return y(this,null,function*(){var s;if(!this.cameraTrack||!this.initialTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:r,profile:o}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams)this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log}),this.destination.on(_t.RENDER,n=>{var a;(a=this.cameraTrack)==null||a.emit("render",n)})),Vt===16?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof Dr?(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 Dr?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode.close(),delete this.cameraNode)),this.cameraNode||(this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraTrackSource"))):this.cameraNode?this.cameraNode.replaceTrack(this.initialTrack):this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraNodeSource"),this.cameraNode.resize(r.width,r.height);else if(e&&this.cameraNode&&this.destination)this.cameraNode.replaceTrack(this.initialTrack);else{this.cameraNode&&this.cameraNode.close(),this.destination?this.destination.disableCheckMute():(this.destination=new Xu(this.videoContext,{name:"mainDestination",logger:this.log}),this.destination.on(_t.RENDER,l=>{var p;(p=this.cameraTrack)==null||p.emit("render",l)}));let{width:n,height:a}=this.cameraResolution,d=yield this.getWatermarkImage(n,a);this._waterMarkOption={x:0,y:0,width:d.width,height:d.height,image:d},this.cameraNode=new Pl(this.videoContext,{input:this.initialTrack,width:n,height:a,mirror:this._isMirror,rotation:this._rotation,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,beautyParams:this._beautyParams,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,Wasm:this.Wasm,enableFaceCentering:this._enableFaceCentering,enableEffectOptimization:this._enableEffectOptimization,onAbort:this.onAbort,mat4:this._mat4,postProcessing:this._postProcessing,color:this._color}),this.cameraNode.connect(this.destination),this.destination.enableCheckMute(),yield this.cameraNode.predictReady}if(this.videoContext.frameRate=o.frameRate,this._use2d){let n=this.cameraNode;if(n.disconnect(),this._isTransform&&(this.transformNode?(this.transformNode.mirror=this._isMirror,this.transformNode.rotation=this._rotation):this.transformNode=new wr(this.videoContext,this.log,this._isMirror,this._rotation),n=n.connect(this.transformNode),n.disconnect(),this.log.info(`start mirror ${this._isMirror} rotate ${this.rotation}`)),this.mixNode&&this.mixNode.close(),delete this.mixNode,this._isMixScreen||this._hasWaterMark){if(this.mixNode=new Fn(this.videoContext,this.log),n.connect(this.mixNode,{zIndex:1}),this._hasWaterMark&&!this.waterMarkNode&&this._waterMarkOption)this.waterMarkNode=this.videoContext.createVideoImageSource(this._waterMarkOption.image,{autoResize:!1,logger:this.log}),this.waterMarkNode.resize(this._waterMarkOption.width,this._waterMarkOption.height),this.waterMarkNode.x=this._waterMarkOption.x,this.waterMarkNode.y=this._waterMarkOption.y;else if(this.waterMarkNode){let{width:d,height:l}=this.cameraResolution;this.waterMarkNode.image=yield this.getWatermarkImage(d,l),d&&l&&this.waterMarkNode.resize(d,l)}(s=this.waterMarkNode)==null||s.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&(this.screenNode||(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource"),this.screenNode.resize(this.screenTrack.settings.width,this.screenTrack.settings.height)),this.screenNode.shouldUpdate=!1,this.screenNode.connect(this.mixNode,{zIndex:0})),n=this.mixNode,this.log.info("start mix",`${this.mixNode.width}x${this.mixNode.height}`)}n.connect(this.destination)}return this.log.info(`update ${this._use2d?"2d":"webgl"}`),this._setMainOutput(this.videoContext.canvas)})}clearLastFrame(){var e;this.destination&&((e=this.destination.ctx2d)==null||e.clearRect(0,0,this.destination.width,this.destination.height))}changeInput(e){var r,o,s,n,a;if(e instanceof mi)return this.log.info("change screen input",(r=e.mediaTrack)==null?void 0:r.label),this.setScreenTrack(e);if(e instanceof _r)return this.log.info("change video input",(o=e.mediaTrack)==null?void 0:o.label),this.setCameraTrack(e);if(e instanceof xo){this.log.info("change remote input",(s=e.mediaTrack)==null?void 0:s.label);let d=e.mediaTrack;return e.setOutputMediaStreamTrack(d)}if(e instanceof Ps)return this.log.info("change mix input",(n=e.outMediaTrack)==null?void 0:n.label),this.setMixTrack(e);this.log.warn("change unknown input",(a=e.mediaTrack)==null?void 0:a.label)}removeInput(e){var r;e instanceof mi?((r=this.screenNode)==null||r.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof _r?this._isMixScreen?(delete this.cameraNode,this.cameraTrack._inputTrack=null,this.update()):(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof xo?e.source&&e.source.context.destroy():e instanceof Ps&&(delete this.mixTrack,this.update())}setMixTrack(e){this.mixTrack=e}setCameraTrack(e){return this.cameraTrack=e,this.update(!0)}setScreenTrack(e){return y(this,null,function*(){return this.screenTrack=e,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):yield this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)})}getWatermarkImage(e,r){return 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 se({code:q.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort((n,a)=>n.zIndex-a.zIndex),this.watermarkImageList.forEach(({image:n,x:a,y:d,width:l,height:p,fillVideo:f})=>{let g=f&&e||l,A=f&&r||p,R=f?0:a,N=f?0:d;s.drawImage(n,R,N,g,A)}),hn(o.toDataURL())})}pushWaterMarkImageList(e){let{type:r}=e;this.watermarkImageList.some(s=>s.imageUrl===e.imageUrl&&s.height===e.height&&s.width===e.width&&s.x===e.x&&s.y===e.y&&s.type===e.type&&s.zIndex===e.zIndex&&s.fillVideo===e.fillVideo)||((r==="mute"||r==="watermark")&&(this.watermarkImageList=this.watermarkImageList.filter(s=>s.type!==r)),this.watermarkImageList.push(e))}setBeautyParams(e){return 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*(){let r;try{r=yield hn((e==null?void 0:e.imageElement)||e.imageUrl)}catch(g){throw new se({code:q.INVALID_PARAMETER,message:`load image failed, url: ${e.imageUrl}`})}let{x:o=0,y:s=0,width:n=r.width,height:a=r.height,type:d="watermark",zIndex:l=2,fillVideo:p=!1}=e;this.watermarkImageList.some(g=>g.type===d)?(this.watermarkImageList=this.watermarkImageList.filter(g=>g.type!==d),this.pushWaterMarkImageList({x:o,y:s,width:n,height:a,image:r,zIndex:l,type:d,imageUrl:e.imageUrl,fillVideo:p}),r=yield this.getWatermarkImage(this.cameraResolution.width,this.cameraResolution.height),this._waterMarkOption={x:0,y:0,width:r.width,height:r.height,image:r},this.waterMarkNode?(this.waterMarkNode.x=0,this.waterMarkNode.y=0,this.waterMarkNode.resize(r.width,r.height),this.waterMarkNode.image=r):this.update()):(this.pushWaterMarkImageList({x:o,y:s,width:n,height:a,image:r,zIndex:l,type:d,imageUrl:e.imageUrl,fillVideo:p}),yield this.freshWatermark()),this.log.info("set watermark",JSON.stringify(this.watermarkImageList,(g,A)=>g==="imageUrl"?void 0:A))})}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 s;(s=this.waterMarkNode)==null||s.close(),delete this.waterMarkNode,delete this._waterMarkOption;let{width:e,height:r}=this.cameraResolution,o=yield this.getWatermarkImage(e,r);this._waterMarkOption={x:0,y:0,width:o.width,height:o.height,image:o},this.update()})}setVirtualBackground(e){return y(this,null,function*(){var r,o,s;if(!e)delete this._virtualBackground,delete this._virtualBackgroundAbortCallback;else{if(e.onAbort&&(this._virtualBackgroundAbortCallback=e.onAbort),this._use2d&&!this._autoSwitchRenderMode)return Promise.reject(new Error("not support virtual background in 2d mode"));this._bgAssetPath=e.assetPath,e.type==="image"?this._virtualBackground=yield hn(e.imageUrl):(this.blurRadius=e.blurLevel||this.blurRadius||3,this._virtualBackground=e.type),this._enableFaceCentering=(r=e.enableFaceCentering)!=null?r:this._enableFaceCentering,this._enableEffectOptimization=(o=e.enableEffectOptimization)!=null?o:this._enableEffectOptimization,this._color=(s=e.color)!=null?s:[0,1,0]}if(this.log.info(`${this._virtualBackground?"start":"stop"} virtual background, ${(e==null?void 0:e.type)||""}, ${this.blurRadius||""}`),yield this.update(),this._virtualBackground&&!this._glVideoContext.available)throw new se({code:q.INVALID_OPERATION,message:`webgl context create failed, ${this._glVideoContext.error}`})})}get mixScreen(){return this._isMixScreen}set mixScreen(e){var r;this._isMixScreen=e,this._isMixScreen||((r=this.screenNode)==null||r.close(),delete this.screenNode),this.update()}set mirror(e){var r;this._isMirror!==e&&(this._isMirror=e,this._isTransform||((r=this.transformNode)==null||r.close(),delete this.transformNode),this.update())}get mirror(){return this._isMirror}set rotation(e){var r;this._rotation!==e&&(this._rotation=e,this._isTransform||((r=this.transformNode)==null||r.close(),delete this.transformNode),this.update())}get rotation(){return this._rotation}enableAr(e){this.arTrack=e,this.isUsingArTrack=!0,this.update()}updateAr(){return 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 kl(e)}clear(){var e,r;(e=this.videoContext)==null||e.disconnect(),(r=this.destination)==null||r.removeAllListeners(),delete this.destination,delete this.cameraNode,delete this.transformNode,delete this.screenNode,delete this.waterMarkNode}addEncodeProcessor({processor:e,type:r}){var o;this.encodePipeline.includes(e)||(this.encodePipeline[r]=e,(o=this.room)==null||o.enableInsertableStreams())}addDecodeProcessor({processor:e,type:r}){var o;this.decodePipeline.includes(e)||(this.decodePipeline[r]=e,(o=this.room)==null||o.enableInsertableStreams())}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}};Z([VE(function(e){this.log.error("update failed",e)}),Pe(e=>function(...r){return y(this,null,function*(){this._updateFlag||(this._updateFlag=!0,yield xT,this.updated=new Promise((o,s)=>{e.apply(this,r).then(o,s),setTimeout(s,5e3,new se({code:q.API_CALL_TIMEOUT,message:"update timeout"}))}),this._updateFlag=!1,yield this.updated)})})],Vc.prototype,"update",1);var ov=0;var Ul=class extends ue{constructor(e){super("room");m(this,"seq",++ov);m(this,"sdkAppId");m(this,"userId");m(this,"userSig");m(this,"privateMapKey");m(this,"latencyLevel");m(this,"tinyId");m(this,"scene");m(this,"roomId");m(this,"useStringRoomId");m(this,"role","anchor");m(this,"joinParams",null);m(this,"localPublishFlag",0);m(this,"localTracks",new Set);m(this,"enableAutoPlayDialog",!0);m(this,"autoReceiveAudio",!0);m(this,"autoReceiveVideo",!0);m(this,"proxy_ws");m(this,"proxy_wt");m(this,"proxy_unified");m(this,"checkSystemResult",{result:!0,detail:{isBrowserSupported:!0,isWebRTCSupported:!0,isWebCodecsSupported:!0,isMediaDevicesSupported:!0,isScreenShareSupported:!0,isSmallStreamSupported:!0,isH264EncodeSupported:!0,isVp8EncodeSupported:!0,isH264DecodeSupported:!0,isVp8DecodeSupported:!0,isH265EncodeSupported:!0,isH265DecodeSupported:!0}});m(this,"keyPointManager");m(this,"audioManager");m(this,"videoManager");m(this,"callDurationCalculator");m(this,"badCaseDetector");m(this,"scheduleResult",{domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null});m(this,"videoDecodeFallbackType");m(this,"smallMode","canvas");m(this,"enableChorus",!1);m(this,"_isUsingCachedSchedule",!1);m(this,"_log");m(this,"_joinedTimestamp",0);m(this,"_sdkType");m(this,"heartbeatReport");m(this,"heartbeatCount",0);m(this,"quality");m(this,"enableSEI");m(this,"isDestroyed",!1);this._log=F.createLogger({parent:e.logger,id:`r${this.seq}`}),this.useStringRoomId=!!e.useStringRoomId,Ye(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),Ye(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),Ye(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new DT({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new wT({room:this}),this.badCaseDetector=new OT({room:this}),this.audioManager=new Ku(this),this.videoManager=new Vc(this)}get videoCodec(){return"h264"}get scriptTransformWorker(){}get isMainStreamPublished(){for(let e of this.localTracks)if(e.mediaType&4)return!0;return!1}get isAuxStreamPublished(){for(let e of this.localTracks)if(e.mediaType&2)return!0;return!1}get hasAuxStream(){for(let e of this.remotePublishedUserMap.values())if(e.muteState.hasAuxiliary)return!0;return this.isAuxStreamPublished}get localMainAudioTrack(){for(let e of this.localTracks)if(e.mediaType&1)return e;return null}get localMainVideoTrack(){for(let e of this.localTracks)if(e.mediaType&4)return e;return null}get localAuxVideoTrack(){for(let e of this.localTracks)if(e.mediaType&2)return e;return null}get publishState(){let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};return this.localTracks.forEach(r=>{if(r.isPublished||r.isPublishing)switch(r.mediaType){case 1:e.audio=!0;break;case 4:e.bigVideo=!0,e.smallVideo=r.hasSmall;break;case 2:e.auxVideo=!0;default:break}}),e}get muteState(){var e,r,o;return{audio:!!((e=this.localMainAudioTrack)!=null&&e.muted),bigVideo:!!((r=this.localMainVideoTrack)!=null&&r.muted),auxVideo:!!((o=this.localAuxVideoTrack)!=null&&o.muted)}}getLogger(){return this._log}get isJoining(){return this.state.toString()==="joining"}get isJoined(){return this.state==="joined"}get isLeft(){return this.state==="left"}addTrack(e){return 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(Oe(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(Jt(e)){let{websocketProxy:r,webtransportProxy:o,loggerProxy:s,scheduleProxy:n,unifiedProxy:a}=e;this.proxy_ws=r,this.proxy_wt=o,this.proxy_unified=a,a?(pl([a,a]),ts(`https://${a}`)):(s&&ts(s),n&&pl(n))}U.once(B.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:gi.main,sched_back_domain:gi.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 se({code:q.INVALID_OPERATION,message:We({key:He.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(ar.INVALID_DESTROY),new se({code:q.INVALID_OPERATION,message:We({key:He.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,U.emit(B.ROOM_DESTROY,{room:this})}schedule(e,r){return y(this,null,function*(){var s,n,a,d;let o=Te();try{let{isCached:l,result:p,detailCost:f}=yield rf({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:pt,userSig:this.userSig,role:this.scene==="live"?e.role:void 0,frameWorkType:r,latencyLevel:e.latencyLevel});this._isUsingCachedSchedule=l,this._log.info(`schedule cache:${+l} ${br(p,{keysToExclude:["username","credential"]})}`),l&&U.once(B.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=Y(Y({},this.scheduleResult),p),Fe((s=p.config)==null?void 0:s.retryCount)&&um(p.config.retryCount),Oe((n=p.config)==null?void 0:n.loggerDomain)&&ts(p.config.loggerDomain),this.videoDecodeFallbackType=((a=p.config)==null?void 0:a.videoDecodeFallback)||this.videoDecodeFallbackType,this.smallMode=((d=p.config)==null?void 0:d.smallMode)||this.smallMode,U.emit(B.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:f}),X.addSuccessEvent({key:521700,cost:Te()-o})}catch(l){throw X.addFailedEvent({key:521700,error:l}),l}})}sendAbilityStatus(e){}enableInsertableStreams(){return Promise.resolve()}switchRoom(e){return Promise.reject()}isSwitchRoomSupported(){return!1}};function LT(i,t=!1){let e=Object.defineProperties(bt(),{postMessage:{value:i.postMessage.bind(i)},port:{get(){return i},set(o){i.onmessage=Ge,i.onmessageerror=Ge,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 Af=class extends fe{constructor(t,e){super(t);let r=new fe(t);r.next=Ge,e(r)}},qG=Ie(Af,"takeUntilComplete");var Ht={useWt:!0,useAINS:!0,useHardDecoder:"prefer-software",useHardEncoder:"prefer-software",unreliable:!1,debug:!1,assetsPath:"",enableUpload:!0},kT="__INLINE__WORKER__",UT="__INLINE__WASM__",{debug:VT}=console;Ht.debug||(console.debug=()=>{});var sv=!kT.startsWith("__"),nv=!UT.startsWith("__");function Vl(){let i=ds(`${Ht.assetsPath?`${Ht.assetsPath}/`:""}worker.js`);return sv?URL.createObjectURL(new Blob([atob(kT)],{type:"application/javascript"})):i.startsWith("http")?fetch(i).then(t=>t.blob().then(e=>URL.createObjectURL(e))):i}var Fc;function Fl(){return y(this,null,function*(){let i=Ht.assetsPath?`${Ht.assetsPath}/`:"";return Fc||(nv?Fc=new TextEncoder().encode(atob(UT)).buffer:Fc=yield fetch(ds(`${i}av_processing.wasm`)).then(t=>t.arrayBuffer()),Fc)})}var yf=class{constructor(){m(this,"playPort");m(this,"playPortSent",!1);m(this,"worklet");m(this,"workletPromise")}init(){return this.workletPromise||(this.workletPromise=this._init()),this.workletPromise}_init(){return y(this,null,function*(){let t=ze("player"),e=Vl();try{yield t.audioWorklet.addModule(typeof e=="string"?e:yield e),F.info("global audio player worklet addModule success",e)}catch(r){throw F.error("global audio player worklet addModule failed:",r),r}return this.worklet=new AudioWorkletNode(t,"global-audio-player",{processorOptions:{wasm:yield Fl(),flag:Ht},numberOfInputs:2}),F.info("global audio player worklet created",t.state),this.playPort=this.worklet.port,this.playPort})}playAudio(t){return y(this,null,function*(){var r;yield this.init();let e=new MessageChannel;(r=this.playPort)==null||r.postMessage(null,[e.port1]),t(e.port2)})}},Bc=new yf;var bf=(()=>{if(typeof self=="undefined")return!1;if(!("top"in self&&self!==top)){if("showOpenFilePicker"in self)return"showOpenFilePicker"}return!1})(),e5=bf?Promise.resolve().then(function(){return uv}):Promise.resolve().then(function(){return gv});var t5=bf?Promise.resolve().then(function(){return mv}):Promise.resolve().then(function(){return _v});var av=bf?Promise.resolve().then(function(){return pv}):Promise.resolve().then(function(){return Iv});function Rf(...i){return y(this,null,function*(){return(yield av).default(...i)})}var cv=i=>y(void 0,null,function*(){let t=yield i.getFile();return t.handle=i,t}),dv=(...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(a=>{e[n].accept[a]=s.extensions||[]}):e[n].accept["*/*"]=s.extensions||[]});let r=yield window.showOpenFilePicker({id:i[0].id,startIn:i[0].startIn,types:e,multiple:i[0].multiple||!1,excludeAcceptAllOption:i[0].excludeAcceptAllOption||!1}),o=yield Promise.all(r.map(cv));return i[0].multiple?o:o[0]}),uv={__proto__:null,default:dv};function Bl(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 Bl=function(e){this.s=e,this.n=e.next},Bl.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 Bl(i)}var FT=(o,s,...n)=>y(void 0,[o,s,...n],function*(i,t,e=i.name,r){let a=[],d=[];var l,p=!1,f=!1;try{for(var g,A=function(R){var N,C,P,z=2;for(typeof Symbol!="undefined"&&(C=Symbol.asyncIterator,P=Symbol.iterator);z--;){if(C&&(N=R[C])!=null)return N.call(R);if(P&&(N=R[P])!=null)return new Bl(N.call(R));C="@@asyncIterator",P="@@iterator"}throw new TypeError("Object is not async iterable")}(i.values());p=!(g=yield A.next()).done;p=!1){let R=g.value,N=`${e}/${R.name}`;R.kind==="file"?d.push(R.getFile().then(C=>(C.directoryHandle=i,C.handle=R,Object.defineProperty(C,"webkitRelativePath",{configurable:!0,enumerable:!0,get:()=>N})))):R.kind!=="directory"||!t||r&&r(R)||a.push(FT(R,t,N,r))}}catch(R){f=!0,l=R}finally{try{p&&A.return!=null&&(yield A.return())}finally{if(f)throw l}}return[...(yield Promise.all(a)).flat(),...yield Promise.all(d)]}),lv=(...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 FT(e,i.recursive,void 0,i.skipDirectory)}),mv={__proto__:null,default:lv},hv=(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 a=[],d=null;if(i instanceof Blob&&i.type?d=i.type:i.headers&&i.headers.get("content-type")&&(d=i.headers.get("content-type")),t.forEach((f,g)=>{a[g]={description:f.description||"Files",accept:{}},f.mimeTypes?(g===0&&d&&f.mimeTypes.push(d),f.mimeTypes.map(A=>{a[g].accept[A]=f.extensions||[]})):d?a[g].accept[d]=f.extensions||[]:a[g].accept["*/*"]=f.extensions||[]}),e)try{yield e.getFile()}catch(f){if(e=null,r)throw f}let l=e||(yield window.showSaveFilePicker({suggestedName:t[0].fileName,id:t[0].id,startIn:t[0].startIn,types:a,excludeAcceptAllOption:t[0].excludeAcceptAllOption||!1}));!e&&o&&o(l);let p=yield l.createWritable();return"stream"in i?(yield i.stream().pipeTo(p),l):"body"in i?(yield i.body.pipeTo(p),l):(yield p.write(yield i),yield p.close(),l)}),pv={__proto__:null,default:hv},fv=(...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(l=>l.mimeTypes||[]),...i.map(l=>l.extensions||[])].join();o.multiple=i[0].multiple||!1,o.accept=s||"",o.style.display="none",document.body.append(o);let n=l=>{typeof a=="function"&&a(),e(l)},a=i[0].legacySetup&&i[0].legacySetup(n,()=>a(r),o),d=()=>{window.removeEventListener("focus",d),o.remove()};o.addEventListener("click",()=>{window.addEventListener("focus",d)}),o.addEventListener("change",()=>{window.removeEventListener("focus",d),o.remove(),n(o.multiple?Array.from(o.files):o.files[0])}),"showPicker"in HTMLInputElement.prototype?o.showPicker():o.click()})}),gv={__proto__:null,default:fv},Ev=(...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=a=>{typeof n=="function"&&n(),e(a)},n=i[0].legacySetup&&i[0].legacySetup(s,()=>n(r),o);o.addEventListener("change",()=>{let a=Array.from(o.files);i[0].recursive?i[0].recursive&&i[0].skipDirectory&&(a=a.filter(d=>d.webkitRelativePath.split("/").every(l=>!i[0].skipDirectory({name:l,kind:"directory"})))):a=a.filter(d=>d.webkitRelativePath.split("/").length===2),s(a)}),"showPicker"in HTMLInputElement.prototype?o.showPicker():o.click()})}),_v={__proto__:null,default:Ev},Tv=(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(d,l){return y(this,null,function*(){let p=d.getReader(),f=new ReadableStream({start:R=>function N(){return y(this,null,function*(){return p.read().then(({done:C,value:P})=>{if(!C)return R.enqueue(P),N();R.close()})})}()}),g=new Response(f),A=yield g.blob();return p.releaseLock(),new Blob([A],{type:l})})}(i.body,i.headers.get("content-type"))),o.download=t.fileName||"Untitled",o.href=URL.createObjectURL(yield s);let n=()=>{typeof a=="function"&&a()},a=t.legacySetup&&t.legacySetup(n,()=>a(),o);return o.addEventListener("click",()=>{setTimeout(()=>URL.revokeObjectURL(o.href),3e4),n()}),o.click(),null}),Iv={__proto__:null,default:Tv};var vf=class{constructor(t){this.name=t;m(this,"ready");m(this,"worker");m(this,"ports");m(this,"ids",1);m(this,"transactions",new Map);m(this,"log");m(this,"addTransaction",t=>(this.transactions.set(++this.ids,t),this.ids))}postMessage(t,e){var r;(r=this.worker)==null||r.postMessage(t,e)}create(t){return y(this,null,function*(){if(this.ready)return this.ready;t||(t=this.name),console.time(`createWorker_${t}`);let e=Vl(),r=new Worker(typeof e=="string"?e:yield e,{name:t});return this.worker=r,this.ready=new Promise((o,s)=>y(this,null,function*(){r.onmessage=({data:{id:n,type:a,payload:d}})=>{var l;if(n)(l=this.transactions.get(n))==null||l(d),this.transactions.delete(n);else switch(a){case"error":console.timeEnd(`createWorker_${t}`),console.warn("worker error:",d),s(d);break;case"ready":console.timeEnd(`createWorker_${t}`),o(this);break;case"updateAFSM":if(d.value){let p=typeof d.old=="string"?d.old:`${d.old.action}ing`,f=typeof d.value=="string"?d.value:`${d.value.action}ing`;console.log(vd(),d.group,d.name,p,"\u{1F449}",f)}break;case"log":console.log(d);break;case"glog":window.dispatchEvent(new CustomEvent(a,{detail:d}));break}},r.postMessage({wasm:yield Fl(),flag:Ht},this.ports)}))})}destroy(){var t;console.log("destroy worker",this.name),delete this.ready,(t=this.worker)==null||t.terminate()}},Cf=class{constructor(t,e,r){this.worker=t;m(this,"channel",new MessageChannel);m(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()}},Nf=class i extends vf{constructor(){super("main");m(this,"switchValue",new Map);m(this,"extendChannel");m(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 wt(i.prototype,this,"create").call(this),this.switchValue.forEach((e,r)=>{this.extendChannel.port1.postMessage([r,e])}),this)})}},$o=new Nf,Hs,$T=-1;function BT(i){return console.log(i),Hs.push(i.slice()),Hs.length>1e3&&Hs.shift(),i}function HT(i){return y(this,null,function*(){switch($T){case 0:this.edpl.willDecodeAudio=BT;break;case 2:this.edpl.didEncodeAudio=BT;break}yield $o.create(),U.emit(B.JOIN_SEND_CMD,{room:this});let t=new Cf($o,i,o=>{let s=o.data;if(typeof s=="string")this.onWorkerEvent(s);else if(s==null)this.onWorkerEvent("client-banned",0),t.destroy();else{let{cmd:n,payload:a}=s;this.onWorkerEvent(n,a)}}),{err:e,data:r}=yield t.ready;if(typeof e=="number"){if(U.emit(B.JOIN_RECEIVED_CMD_RES,{room:this,code:e}),e===0)return Object.assign(this,r,{session:t});throw new se({code:q.JOIN_ROOM_FAILED,extraCode:Number(e),message:We({key:He.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:e,errorMsg:""}})})}else throw e})}Object.defineProperties(window,{useAINS:{set:Df},useWt:{set:Sv},enableDebug:{set(i){console.debug=i?VT:()=>{},$o.setSwitchValue("enableDebug",i)}},useV2:{set:wf},dump:{value(i=0){if($T=i,Hs||(console.warn("dump audio will be activated at next time join room"),Hs=[]),!Hs.length){console.warn("no audio data to dump,try it later");return}let t=[];return Hs.forEach(e=>{t.push(new Uint16Array([e.length])),t.push(e)}),Rf(new Blob(t),{fileName:"audio dump hex",extensions:[".hex"]})}},dumpAudio:{value(i="audio",t=2e3){let e=[],r=new Promise(o=>{let s=new MessageChannel;$o.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,$o.extendChannel.port1.postMessage(["dump",i]),s.port2.close(),o(new Blob(e)))}});return Rf(r,{fileName:i,extensions:[".pcm"]})}},hardDec:{set(i){switch(i){case!0:Ht.useHardDecoder="prefer-hardware";break;case!1:Ht.useHardDecoder="prefer-software";break;default:Ht.useHardDecoder="no-preference"}}}});function Df(i){return y(this,null,function*(){$o.setSwitchValue("useAINS",i)})}function wf(i){return y(this,null,function*(){$o.setSwitchValue("useV2",i)})}function Sv(i){return y(this,null,function*(){$o.setSwitchValue("useWt",i)})}function WT(i){let t=new MediaStreamTrackGenerator({kind:"audio"});i.setInputMediaStreamTrack(t),this.postMessage({cmd:"pullAudio",payload:{tinyId:i.tinyId,writable:t.writable}},[t.writable])}function GT(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),ye(LT(r.port2),Je(Ae(i,ue.INIT)),Le(s=>{let{data:n,packetsReceived:a}=s;i.stat.packetsReceived=a,i.stat.framesReceived++,e++;let d=n[4]&31;if(e<=10){let p=Array.from(n.slice(0,10)).map(f=>f.toString(16).padStart(2,"0")).join(" ");this._log.info(`Frame ${e} - Size: ${n.length} bytes, Type: ${d}, Timestamp: ${Date.now()-t}ms First 10 bytes: ${p}`)}let l;switch(d){case 5:case 7:l="key";break;default:l="delta";break}i.isAvailable?i.decodeFrame({data:n.buffer,type:l,timestamp:(Date.now()-t)*1e3}):console.warn("track is not available")},()=>{},()=>{r.port2.postMessage(null),r.port2.close()}))})}var $l=[];function qT(i){var d;let t=bt();if(this.state!=="joined")throw new Error("Room is not joined");if(i.state==="publish")return;for(let l=0;l<=$l.length;l++)if(!$l[l]){$l[l]=this,this.index=l;break}let e=i.profile;this._log.info("start push audio",this.index,e);let r=new MessageChannel,o=i.enableEncryptFrame?new MessageChannel:null;(d=this.session)==null||d.postMessage({cmd:"pushAudio",payload:Y({index:this.index},e)},o?[r.port2,o.port2]:[r.port2]),r.port1.onmessage=l=>{l.data==null||(typeof l.data=="number"?t.next(l.data):o&&o.port1.postMessage(_e(Y({},l.data),{data:new Uint8Array(i.encodeFrame({data:l.data.data.buffer,timestamp:l.data.timestamp}).data)})))};let s=new MediaStream,n,a=l=>{let p=s.getAudioTracks()[0];p&&(n.disconnect(),s.removeTrack(p)),s.addTrack(l),this._log.info("push audio track:",l.readyState,l.getSettings().deviceId),n=ze("player").createMediaStreamSource(s),n.connect(Bc.worklet,0,this.index)};ye(Ae(i,"output-media-track-changed"),Je(Ae(i,"ready")),Le(a,console.error,()=>{this._log.info("stop push audio",e),i.volume=0,n.disconnect(),$l[this.index]=null,o&&o.port1.postMessage(null),r.port1.postMessage(null)})),ye(t,Ds(l=>i.volume=l),qi(Ju(1e3)),Le(()=>{i.volume=0})),a(i.outMediaTrack)}var L5=new Intl.DateTimeFormat("zh-CN",{dateStyle:"short",timeStyle:"medium"});var Of=class{constructor(t,e,r,o){this.localTrack=t;this.type=e;this.config=r;this.port=o;m(this,"track");m(this,"label");m(this,"insertKeyFrame",!0);m(this,"session");m(this,"tsMap",new Map);t._log.info("create Video Encoder",r)}trans(t,e,r){return y(this,null,function*(){let o=yield this.recreate(r,{recreateCount:0,frameEncoded:0,selectConfigIndex:0});e.signal.addEventListener("abort",()=>{o.encoder.close()});let s=0;return t.pipeThrough(new TransformStream({transform:(n,a)=>{o.encoder.state==="configured"&&(this.tsMap.set(s,Date.now()),this.encode(n),s++,a.enqueue(n))}}),e)})}encode(t){var e,r;(r=(e=this.session)==null?void 0:e.encoder)==null||r.encode(t,{keyFrame:this.insertKeyFrame}),this.insertKeyFrame=!1}start(t,e,r){return y(this,null,function*(){let o=yield this.recreate(r,{recreateCount:0,frameEncoded:0,selectConfigIndex:0});this.session=o;let s=0;t.pipeTo(new WritableStream({write:n=>{o.encoder.state==="configured"&&(s<10&&this.localTrack.log.info(`capture ${this.label} track frame:`,s,Date.now(),n.timestamp,n.displayWidth,n.displayHeight),(n.displayWidth!==this.config.width||n.displayHeight!==this.config.height)&&(this.localTrack.log.info("resize video track frame:",n.displayWidth,n.displayHeight,this.config.width,this.config.height),this.configure({width:n.displayWidth,height:n.displayHeight},o)),this.tsMap.set(s,Date.now()),this.encode(n),s<10&&this.localTrack.log.info(`encode ${this.label} track frame:`,s),s++,n.close())}}),e).catch(n=>{this.localTrack.log.warn(n),o.encoder.close()})})}recreate(t,e){return y(this,null,function*(){let r=0,o=new VideoEncoder({output:s=>{let n=this.tsMap.get(r);if(this.tsMap.delete(s.timestamp),r<10&&(r===0&&e.recreateCount===0&&U.emit(B.SEND_FIRST_VIDEO_FRAME,{room:t}),this.localTrack.log.info(`encoded ${this.label} track frame:`,r,Date.now(),s.timestamp)),r++,e.frameEncoded=r,this.track.enabled===!1)return;let a=null;if(this.localTrack.enableEncodeFrame){a=new Uint8Array(s.byteLength),s.copyTo(a);let d=this.localTrack.encodeFrame({data:a.buffer},this.type===3);a=new Uint8Array(d.data)}a?(this.localTrack.stat.bytesSent+=a.length,this.port.postMessage({chunk:{type:s.type,timestamp:s.timestamp,data:a,duration:s.duration},timestamp:n},[a.buffer])):(this.localTrack.stat.bytesSent+=s.byteLength,this.port.postMessage({chunk:s,timestamp:n}))},error:s=>{this.localTrack.log.warn(s,this.config),e.recreateCount++,setTimeout(()=>this.recreate(t,e),100)}});return e.encoder=o,yield this.configure(null,e),e})}configure(t,e){return y(this,null,function*(){var r;t&&Object.assign(this.config,t),(r=e.encoder)==null||r.configure(this.config)})}close(){this.port.postMessage(null),this.port.close()}};function Hl(i,t){return y(this,null,function*(){let e=i.mediaType===2,r=e?"screen":"video",o={codec:"avc1.420028",latencyMode:"realtime",avc:{format:"annexb"},hardwareAcceleration:Ht.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 Of(i,t.type,o,s.port2);return s.port2.onmessage=a=>{if(a.data===260)n.insertKeyFrame=!0;else if(!e){let{bitrate:d}=a.data;Ta({configureBr:[a.data.bitrate,d]}),n.session&&n.configure({bitrate:d},n.session)}},this._log.info("start push",r,t),n})}function zT(i){return y(this,null,function*(){var p;let t=i.mediaType===2,e=t?"screen":"video",r={type:t?7:2,profile:i.profile,trackType:t?"screen":"camera",crypto:!!((p=i.manager)!=null&&p.encodePipeline[0])};!t&&i.outMediaTrack instanceof CanvasCaptureMediaStreamTrack&&(r.trackType="canvas");let{trackType:o}=r,{width:s,height:n}=i.outMediaTrack.getSettings();r.profile.width=s,r.profile.height=n;let a=yield Hl.call(this,i,r);this._log.info("VideoEncoder created",r);let d,l=f=>y(this,null,function*(){if(d==null||d.abort("track changed"),!f)return;d=new AbortController;let{width:g,height:A,displaySurface:R}=f.getSettings();g&&(a.config.width=g),A&&(a.config.height=A);let N=sr.match(/Chrome\/(\d+)/);(N==null?void 0:N[1])==="114"&&R==="browser"&&delete a.config.hardwareAcceleration,this._log.info("push",e,"track:",f.readyState,f.getSettings());let C;if(typeof MediaStreamTrackProcessor!="undefined"&&!(f instanceof CanvasCaptureMediaStreamTrack))C=new MediaStreamTrackProcessor({track:f}).readable;else{let z;C=new ReadableStream({start(H){i.on("render",ge=>{if(!(i.player.mode===0&&!document.hidden))try{H.enqueue(new VideoFrame(ge,{timestamp:performance.now()*1e3}))}catch(Ue){console.warn(Ue)}})},pull(H){return y(this,null,function*(){if(i.player.mode===0&&zr()&&i.player.element)return new Promise(ge=>{i.player.element.requestVideoFrameCallback((Ue,W)=>{try{let we=new VideoFrame(i.player.element);H.enqueue(we)}catch(we){console.warn(we)}ge()})})})}})}let P="small"in i&&i.small;return P?(this.smallEncoder||(this.smallEncoder=yield Hl.call(this,i,{profile:P,type:3,trackType:o})),this.smallEncoder.track=f,this.smallEncoder.label="small",C=yield this.smallEncoder.trans(C,d,this)):this.smallEncoder&&(this.smallEncoder.close(),delete this.smallEncoder),a.track=f,a.label=e,a.start(C,d,this)});return ye(Ae(i,"output-media-track-changed"),Je(Ae(i,"ready")),Le(l,console.error,()=>{var f;this._log.info("stop push",e,r),d.abort("unpublish"),a.close(),(f=this.smallEncoder)==null||f.close()})),l(i.outMediaTrack)})}var Ho=class Ho extends ue{constructor(e){var r,o;super((o=(r=e.roomid)==null?void 0:r.toString())!=null?o:e.name,"volumeEvaluation");this.room=e;m(this,"enableInBackground",!1);m(this,"interval",400);e.on("joined",()=>{this.emit(Ho.INTERVALCHANGED,this.interval)}),ye(Ae(this,Ho.INTERVALCHANGED),ui(s=>this.room.state==="joined"?this.room.fromWorker("getAudioEnergy",s):ye(ZE(s),wo(()=>[]))),Le(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==ue.ON&&this.room.emit("audio-volume",s)}))}start(e,r){this.interval=e,this.enableInBackground=r,this.emit(Ho.INTERVALCHANGED,this.interval)}stop(){}};m(Ho,"INTERVALCHANGED","intervalChanged"),Z([et([ue.INIT,ue.OFF],ue.ON)],Ho.prototype,"start",1),Z([et([],ue.OFF)],Ho.prototype,"stop",1);var Wl=Ho;var Wo=class Wo extends Ul{constructor(e){super(e);m(this,"index",0);m(this,"session");m(this,"tinyid");m(this,"roomid");m(this,"openid");m(this,"socketid");m(this,"relayip");m(this,"clientip");m(this,"remotePublishedUserMap",new Map);m(this,"bussinessInfo");m(this,"token");m(this,"audioVolumeEvalution",new Wl(this));m(this,"enableAIVoice",Df);m(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:Wm(),uint32_device_type:0,str_os_verion:Gm(),uint32_link_type:1,str_client_version:pt,uint32_net_type:rs[si.getNetworkType()],ua:navigator.userAgent,version:""}});m(this,"joinAbortController",new AbortController);m(this,"smallAbortCtrl");m(this,"smallEncoder");e.tinyId&&(this.tinyId=e.tinyId,wf(!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=a=>{n.port2.close(),o(a.data)}})}fromWorker(e,r){if(this.state!="joined")throw"join room first";return o=>{var n;let s=new MessageChannel;s.port2.onmessage=a=>{a.data?o.next(a.data):o.complete()},s.port2.onmessageerror=a=>o.error(a),o.defer(()=>{s.port2.postMessage(null),s.port2.close()}),(n=this.session)==null||n.postMessage({cmd:e,payload:r},[s.port1])}}switchRole(e){return 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 d,l,p;let s=si.getEnv(),n=hu(),a={isH264EncodeSupported:this.checkSystemResult.detail.isH264EncodeSupported,isVp8EncodeSupported:this.checkSystemResult.detail.isVp8EncodeSupported,frameWorkType:o,params:e,proxy_wt:(d=this.proxy_wt)==null?void 0:d.replace("https://",""),proxy_ws:(l=this.proxy_ws)==null?void 0:l.replace("wss://",""),proxy_cloud:(p=this.scheduleResult.iceServers)!=null&&p.length?this.scheduleResult.iceServers[0].urls:[],proxy_unified:this.proxy_unified,domains:this.scheduleResult.domains,env:s,osName:yn(),browserInfo:hu(),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:pt,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 HT.call(this,a),console.log(this),Bc.playAudio(f=>this.postMessage({cmd:"setAudioWorkletPort"},[f])),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()),this.localTracks.clear()})}getSignalInfo(){return{tinyId:this.tinyid,clientIp:this.clientip,signalIp:"",relayIp:this.relayip,relayInnerIp:"",relayPort:0}}enableAudioVolumeEvaluation(e=2e3,r=!1){e<=0?this.audioVolumeEvalution.stop():this.audioVolumeEvalution.start(e,r)}getLocalAudioStats(){return this.sendMessage("getLocalAudioStats")}getLocalVideoStats(){return this.sendMessage("getLocalVideoStats")}afterJoin(){return y(this,null,function*(){let e=Je(Ae(this,"left")),r=this.audioManager.decodePipeline.some(o=>o);ye(o=>y(this,null,function*(){let s=new MessageChannel;s.port2.onmessage=n=>{n.data?o.next({data:n.data,port:s.port2}):o.complete()},s.port2.onmessageerror=n=>o.error(n),o.defer(()=>{s.port2.postMessage(null),s.port2.close()}),this.postMessage({cmd:"decodeAudio",payload:r},[s.port1])}),e,Le(({data:o,port:s})=>{var a;let n={data:o.data.buffer};for(let[d,l]of this.audioManager.decodePipeline.entries())if(l&&(n=l({frame:n,track:(a=this.remotePublishedUserMap.get(o.userId))==null?void 0:a.remoteAudioTrack}),!n))return;s.postMessage(_e(Y({},o),{data:new Uint8Array(n.data)}),[n.data])}))})}onWorkerEvent(e,r){switch(e!=="network-quality"&&console.info(this.userId,"onWorkerEvent",e,JSON.stringify(r)),e){case B.RECEIVED_PUBLISHED_USER_LIST:U.emit(e,Y({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 wl(this,r);this.remotePublishedUserMap.set(r.userId,o),this.emit("remote-published",o);return;case"5":{let f=r,g=this.remotePublishedUserMap.get(f);g&&(g.remoteVideoTrack.close(),g.remoteAuxiliaryTrack.close(),g.remoteAudioTrack.close(),this.remotePublishedUserMap.delete(f),this.emit("remote-unpublished",g))}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:f,muteState:g,flag:A}=r,R=this.remotePublishedUserMap.get(g.userId);if(!R){this.emit("remote-publish-state-changed",r);return}R.flag=A}U.emit(B.REMOTE_PUBLISH_STATE_CHANGED,Y({room:this},r)),this.emit("remote-publish-state-changed",r);return;case"7":this.localPublishFlag!==r.flag&&(this.localPublishFlag=r.flag,this.emit("local-publish-flag-changed",r.flag));return;case"network-quality":this.quality=Y({},r);let{uplinkLoss:s,uplinkRTT:n,uplinkInfo:a,downlinkInfo:d,msg_down_stream_info:l}=r,p={str_sdk_version:pt,uint64_datetime:Date.now(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyid},msg_device_info:{uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:rs[cn()]},msg_event_msg:t_(this.userId),str_acc_ip:this.relayip,str_client_ip:this.clientip,msg_up_stream_info:a,msg_down_stream_info:l};U.emit(B.HEARTBEAT_REPORT,{room:this,report:p}),this.emit("heartbeat-report",p),U.emit(B.NETWORK_QUALITY,{room:this,uplink:{rtt:n,loss:s},downlinks:d}),delete r.downlinkInfo;break;case"signal-connection-state-changed":U.emit(B.SIGNAL_CONNECTION_STATE_CHANGED,Y({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*(){switch(yield this.sendMessage("publish",e.mediaType).then(r=>r.err!==0?Promise.reject(r.err):r),Ft(e,e).add("mute",()=>{this.postMessage("mute",{mediaType:e.mediaType,userId:this.userId,srctinyid:this.tinyid,remove:!0})}).add("unmute",()=>{this.postMessage("unmute",{mediaType:e.mediaType,userId:this.userId,srctinyid:this.tinyid,add:!0})}),e.mediaType){case 1:yield Bc.init(),qT.call(this,e);break;default:yield zT.call(this,e)}e.muted&&this.postMessage("mute",{mediaType:e.mediaType,srctinyid:this.tinyid,userId:this.openid,remove:!0})})}unpublish(e){return y(this,null,function*(){At(e)})}subscribe(...e){return y(this,null,function*(){let r=e.reduce((f,g)=>g.mediaType|f,0),{userId:o,tinyId:s,streamType:n}=e[0],a=this.remotePublishedUserMap.get(o),d=Y({},a.subscribeState),l=Object.assign(new Va,d);l.mediaType|=r,U.emit(B.SUBSCRIBE_START,{room:this,streamType:n,remotePublishedUser:a,subscribeState:l});let p=yield this.sendMessage("subscribe",{mediaType:l.mediaType,userId:o,srctinyid:s,mediaDescription:{audioParam:{mediaType:1,payloadFmtps:[{payloadType:111,fmtp:"minptime=10;useinbandfec=1"}]},videoParam:[4,8,2].filter(f=>l.mediaType&f).map(f=>({mediaType:f,payloadFmtps:[{payloadType:100,fmtp:"packetization-mode=1;profile-level-id=42e01f"}]}))}});console.dir("subscribe",p),yield Promise.all(e.filter(f=>!f.isSubscribed).map(f=>{switch(f.mediaType){case 1:return WT.call(this,f);default:return GT.call(this,f)}})),U.emit(B.SUBSCRIBE_SUCCESS,{room:this,streamType:n,remotePublishedUser:a})})}unsubscribe(...e){return y(this,null,function*(){let r=0;for(let o of e)r|=o.mediaType;if(e.length){let{userId:o,streamType:s,tinyId:n}=e[0];yield this.sendMessage("unSubscribe",{mediaType:r,srctinyid:n,userId:o});for(let a of e)a.unsubscribe();U.emit(B.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 Hl.call(this,o,{profile:o.small,type:3,trackType:"camera"});let s=new MediaStreamTrackProcessor({track:this.videoManager.smallTrack}).readable;this.smallEncoder.track=this.videoManager.smallTrack,this.smallEncoder.label="small",this.smallAbortCtrl=new AbortController,this.smallEncoder.start(s,this.smallAbortCtrl,this),this._log.info("push small")}}else(r=this.smallAbortCtrl)==null||r.abort("stop"),this.smallEncoder&&(this.smallEncoder.close(),delete this.smallEncoder)})}changeType(e,r){let o=this.remotePublishedUserMap.get(r.userId);if(!o)return;let s=e?8:4;if(o.remoteVideoTrack.mediaType===s)return;let n={srctinyid:o.tinyId,mediaType:s,userId:r.userId,mediaDescription:{audioParam:{mediaType:1,payloadFmtps:[{payloadType:111,fmtp:"minptime=10;useinbandfec=1"}]},videoParam:[4,8].filter(a=>s&a).map(a=>({mediaType:a,payloadFmtps:[{payloadType:100,fmtp:"packetization-mode=1;profile-level-id=42e01f"}]}))}};o.remoteVideoTrack.mediaType=n.mediaType,this.postMessage("changetype",n)}destroy(){this.isDestroyed||(super.destroy(),this.isDestroyed=!0,this.joinAbortController.abort("destroy"))}};Z([No(Wo.prototype.afterJoin),et(["left",ue.INIT],"joined"),bT()],Wo.prototype,"join",1),Z([et("joined","left",{ignoreError:!0}),RT()],Wo.prototype,"leave",1),Z([Mu(e=>e.mediaType),vT()],Wo.prototype,"publish",1),Z([Mu(e=>e.mediaType),CT()],Wo.prototype,"unpublish",1),Z([Mu((...e)=>e[0].userId),NT()],Wo.prototype,"subscribe",1);var Gl=Wo;Qn.frameWorkType=37;Qn.create=function(i){let t=Qn._create.call(this,Gl,i);return t._use(Zp,i==null?void 0:i.assetsPath),i!=null&&i.assetsPath&&(Ht.assetsPath=i==null?void 0:i.assetsPath),console.log("trtc wasm sdk:",pt,"created",Ht),t};Object.assign(Qn.prototype,{_setCurrentSpeaker(i){let t=ze("player");return t!=null&&t.setSinkId?t.setSinkId(i):Promise.reject("not support")},_enableVideoDecodeFallback(i,t){return y(this,null,function*(){return this.startPlugin(Zp.Name,{type:"webCodecs",renderer:"videoFrame",track:i,config:{codec:"avc1.640028",hardwareAcceleration:"prefer-software",optimizeForLatency:!0},fallback:"wasm"}),new Promise((e,r)=>{ye(Ae(i,"decode-downgrade-state-changed"),tr(o=>o.state==="STARTED"),Qr(1),vp(1e4),Je(Ae(i,ue.INIT)),Le(e,r))})})}});Sh(37);var c6=Qn;export{c6 as default};