trtc-sdk-v5 5.15.0-wasm.1 → 5.15.0-wasm.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/trtc.esm.js CHANGED
@@ -90,7 +90,7 @@ return ret;
90
90
  `);P.isVoid||(ge+=` return retType.toWireType(destructors, rv);
91
91
  `),ge+=`};
92
92
  `,J.push(ge);var De,Te,Pe=Kc(Function,J).apply(null,K);return De=Pe,Te=Xs.length,Xs.push(De),G=Te,Qs[$]=G,G},f:()=>{Ar("")},c:na,t:(A,I,w)=>D.copyWithin(A,I,I+w),s:A=>{D.length,Ar("OOM")},i:(A,I,w,P)=>{for(var $,G,J,K=0,te=0;te<w;te++){var j=ne[I>>2],ge=ne[I+4>>2];I+=8;for(var Oe=0;Oe<ge;Oe++)$=A,G=D[j+Oe],J=void 0,J=ad[$],G===0||G===10?(($===1?f:T)(ts(J,0)),J.length=0):J.push(G);K+=ge}return ne[P>>2]=K,0}},kr=(function(){var A,I,w,P,$={a:cd};function G(J,K){var te,j,ge=J.exports;return _=(b=ge).v,te=_.buffer,o.HEAP8=C=new Int8Array(te),o.HEAP16=x=new Int16Array(te),o.HEAP32=W=new Int32Array(te),o.HEAPU8=D=new Uint8Array(te),o.HEAPU16=H=new Uint16Array(te),o.HEAPU32=ne=new Uint32Array(te),o.HEAPF32=Ve=new Float32Array(te),o.HEAPF64=he=new Float64Array(te),Q=b.z,j=b.w,Kn.unshift(j),function(){if(ti--,o.monitorRunDependencies&&o.monitorRunDependencies(ti),ti==0&&(Ws!==null&&(clearInterval(Ws),Ws=null),eo)){var Oe=eo;eo=null,Oe()}}(),ge}if(ti++,o.monitorRunDependencies&&o.monitorRunDependencies(ti),o.instantiateWasm)try{return o.instantiateWasm($,G)}catch(J){T("Module.instantiateWasm callback failed with error: "+J),r(J)}(A=p,I=Si,w=$,P=function(J){G(J.instance)},A||typeof WebAssembly.instantiateStreaming!="function"||re(I)||typeof fetch!="function"?ri(I,w,P):fetch(I,{credentials:"same-origin"}).then(J=>WebAssembly.instantiateStreaming(J,w).then(P,function(K){return T("wasm streaming compile failed: "+K),T("falling back to ArrayBuffer instantiation"),ri(I,w,P)}))).catch(r)}(),A=>(kr=b.x)(A)),lo=A=>(lo=b.y)(A),Ys=A=>(Ys=b.A)(A),dd=(o.__embind_initialize_bindings=()=>(o.__embind_initialize_bindings=b.B)(),A=>(dd=b.C)(A));o.dynCall_jiji=(A,I,w,P,$)=>(o.dynCall_jiji=b.D)(A,I,w,P,$);function ud(){function A(){Xt||(Xt=!0,o.calledRun=!0,Or||(yi(Kn),e(o),o.onRuntimeInitialized&&o.onRuntimeInitialized(),function(){if(o.postRun)for(typeof o.postRun=="function"&&(o.postRun=[o.postRun]);o.postRun.length;)I=o.postRun.shift(),ea.unshift(I);var I;yi(ea)}()))}ti>0||(function(){if(o.preRun)for(typeof o.preRun=="function"&&(o.preRun=[o.preRun]);o.preRun.length;)I=o.preRun.shift(),Zn.unshift(I);var I;yi(Zn)}(),ti>0||(o.setStatus?(o.setStatus("Running..."),setTimeout(function(){setTimeout(function(){o.setStatus("")},1),A()},1)):A()))}if(eo=function A(){Xt||ud(),Xt||(eo=A)},o.preInit)for(typeof o.preInit=="function"&&(o.preInit=[o.preInit]);o.preInit.length>0;)o.preInit.pop()();return ud(),t.ready}})();var v_=(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.SEI_MESSAGE="267",i.USER_PAUSE_IN_PIP="268",i.USER_RESUME_IN_PIP="269",i.ENTER_PICTURE_IN_PICTURE="270",i.LEAVE_PICTURE_IN_PICTURE="271",i.SWITCH_ROOM_START="401",i.SWITCH_ROOM_SUCCESS="407",i.SWITCH_ROOM_FAILED="408",i))(v_||{}),Tb="5.0.0",Ib=typeof importScripts!="undefined",Sb=typeof registerProcessor!="undefined",Ab="",yb="web.sdk.qcloud.com",bb=`https://${yb}/trtc/webrtc/doc`,$U=`${bb}/zh-cn/`,Rb="https://yun.tim.qq.com",vb="https://apisgp.my-imcloud.com",Cb={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 C_={"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}},HU=C_["480p_2"],WU=C_["120p_2"],pl={CANVAS:"canvas",AUDIO:"audio",VIDEO:"video",SCREEN:"screen",SMALL:"small",BIG:"big",AUXILIARY:"auxiliary",SMALL_VIDEO:"smallVideo",FACING_MODE_USER:"user",FACING_MODE_ENVIRONMENT:"environment",MUTE:"mute",UNMUTE:"unmute",ENDED:"ended",PLAYING:"playing",PAUSE:"pause",ERROR:"error",LOADSTART:"loadstart",LOADEDDATA:"loadeddata",LOADEDMETADATA:"loadedmetadata",AUDIO_INPUT:"audioinput",VIDEO_INPUT:"videoinput",DETAIL:"detail",TEXT:"text",MAIN:"main",BACKUP:"backup",BANNED:"banned",KICK:"kick",USER_TIME_OUT:"user_time_out",ROOM_DISBAND:"room_disband",SEI_MESSAGE:"sei-message",ADD:"add",REMOVE:"remove",REPLACE:"replace",TRACK:"track",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",TRANSCEIVER_DIRECTION_SENDONLY:"sendonly",TRANSCEIVER_DIRECTION_RECVONLY:"recvonly",ENTER_PICTURE_IN_PICTURE:"enterpictureinpicture",LEAVE_PICTURE_IN_PICTURE:"leavepictureinpicture",RESIZE:"resize",TIME_UPDATE:"timeupdate"},GU=pl.MAIN,jU=pl.AUXILIARY,qU=pl.BIG,zU=pl.SMALL;var JU=Object.keys(ks);var Nb=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())})},qp=Symbol(32),zp=Symbol(16),Jp=Symbol(8),jn=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 Nb(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(qp)}readU16(){return this.read(zp)}readU8(){return this.read(Jp)}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===qp){if(r(4))return;i=t[0]<<24|t[1]<<16|t[2]<<8|t[3]}else if(this.need===zp){if(r(2))return;i=t[0]<<8|t[1]}else if(this.need===Jp){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}};jn.U32=qp,jn.U16=zp,jn.U8=Jp;var Db=128,wb=127,XU=~wb,QU=Math.pow(2,31);function Bp(i){let t=new jn;for(;i>=128;)t.malloc(1)[0]=255&i|Db,i>>>=7;return t.malloc(1)[0]=255&i,t.buffer||new Uint8Array(0)}function Xp(i,t=0){let e=new jn,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(Bp(i));break;case"string":e.malloc(1)[0]=2|r;let s=new TextEncoder().encode(i);e.write(Bp(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 jn;if(Array.isArray(i))for(let d=0;d<i.length;d++){let l=Xp(i[d],d+1);l&&a.write(l)}else{let d=1;for(let l in i){let p=Xp(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(Bp(a.buffer.length)),e.write(a.buffer)))}return e.buffer||new Uint8Array(0)}var l_=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 m_(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 lr(i,t){return i[t]<<24|i[t+1]<<16|i[t+2]<<8|i[t+3]}function h_(i,t){return i[t]}function Ic(i,t,e){return new TextDecoder().decode(Mb(i,t,e))}function Mb(i,t,e){return i.slice(t,t+e)}var $p=0,Qp=2654435769,Yp=16,p_=4,Cc=2,Nc=7;function Ob(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 Pb(i,t){let e=new l_,r=Ob(t,i,$p);$p=$p+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 l_;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 H=4;H<16;H++)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 T=new TextEncoder().encode(r.reqHead.clientVersionInfo);n.writeInt16(T.length+2),T.length&&n.writeBytes(T);let _=n.length;n.data[0]=_>>>24&255,n.data[1]=_>>>16&255,n.data[2]=_>>>8&255,n.data[3]=255&_,Zp(i)&&(i=new TextEncoder().encode(i)),n.writeInt32(i.length+4),i.length&&n.writeBytes(i);let b=new Uint8Array(n.data),C=null;r.encryption===1?C=new TextEncoder().encode(r.uin):r.encryption===2&&(C=new Uint8Array(16)),C&&(b=xb(b,C)),e.writeBytes(b);let D=new Uint8Array(e.data),x=D.length;return D[0]=x>>>24&255,D[1]=x>>>16&255,D[2]=x>>>8&255,D[3]=255&x,D}function xb(i,t){let e=i.length,r=(e+1+Cc+Nc)%8;r&&(r=8-r);let o=new Uint8Array(e+1+Cc+Nc+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<Cc;)if(l<8&&(n[l]=255&Math.floor(256*Math.random()),l+=1,f+=1),l===8){Hp(n,t,a,d,o,s),s+=8,l=0;for(let T=0;T<8;T++)d[T]=o[s-8+T]}let p=0;for(;p<e;)if(l<8&&(n[l]=i[p],l+=1,p+=1),l===8){Hp(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<Nc;)if(l<8&&(n[l]=0,l+=1,f+=1),l===8){Hp(n,t,a,d,o,s),s+=8,l=0;for(let T=0;T<8;T++)d[T]=o[s-8+T]}return o}function Hp(i,t,e,r,o,s){for(let n=0;n<8;n++)i[n]^=r[n];Lb(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 Lb(i,t,e,r){let o=lr(i,0),s=lr(i,4),n=[];for(let d=0;d<4;d++)n[d]=lr(t,4*d);let a=0;for(let d=0;d<Yp;d++)a+=Qp,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;m_(e,o,r),m_(e,s,r+4)}var kb=0,N_=function(){return Date.now()+kb},Ub=function(){let i=new Date;return i.setTime(N_()),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 Fb(i){let t=Bb(i);return t==null?void 0:t.busiBuff}function Bb(i){try{let t={},e=0;t.totalLength=lr(i,e),e+=4,t.version=lr(i,e),e+=4,t.encryption=h_(i,e),e+=1,t.uinType=h_(i,e),e+=1,t.uinLength=lr(i,e),e+=4,t.uin=t.uinLength>4?Ic(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=$b(r,o),t.decrypted=!0,e=0}else i=r,e=0;return t.rspHeadLength=lr(i,e),e+=4,t.seqNo=lr(i,e),e+=4,t.retCode=lr(i,e),e+=4,t.retStrLength=lr(i,e),e+=4,t.retStr=t.retStrLength?Ic(i,e,t.retStrLength-4):"",e+=t.retStrLength-4,t.serviceCmdLength=lr(i,e),e+=4,t.serviceCmd=t.serviceCmdLength?Ic(i,e,t.serviceCmdLength-4):"",e+=t.serviceCmdLength-4,t.cookieLength=lr(i,e),e+=4,t.cookie=t.cookieLength?Ic(i,e,t.cookieLength-4):"",e+=t.cookieLength-4,t.flag=lr(i,e),e+=4,t.busiBuffLength=lr(i,e),e+=4,t.busiBuff=t.busiBuffLength?Ic(i,e,t.busiBuffLength-4):"",e+=t.busiBuffLength-4,t}catch(t){}}function D_(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=Qp*Yp>>>0;for(let s=0;s<Yp;s++)r-=(e<<p_)+t[2]^e+o^(e>>>5)+t[3],r>>>=0,e-=(r<<p_)+t[0]^r+o^(r>>>5)+t[1],e>>>=0,o-=Qp,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 $b(i,t){let e=0,r=new Uint8Array(8).fill(0),o=D_(new Uint8Array(i.slice(0,8)),t),s=7&o[0],n=i.length-1-s-Cc-Nc,a=new Uint8Array(n),d=0,l=r,p=i.slice(0,8);e=8;let f=1;f+=s;for(let _=1;_<=Cc;)if(f<8)f++,_++;else if(f===8){let b=Wp(i,e,l,p,o,t);l=b.ivPreCrypt,p=b.ivCurCrypt,o=b.debiBuf,e=b.bufPos,f=0}let T=n;for(;T>0;)if(f<8)a[d++]=o[f]^l[f],f++,T--;else if(f===8){let _=Wp(i,e,l,p,o,t);l=_.ivPreCrypt,p=_.ivCurCrypt,o=_.debiBuf,e=_.bufPos,f=0}for(let _=1;_<=Nc;)if(f<8)o[f],l[f],f++,_++;else if(f===8){if(e>=i.length)break;let b=Wp(i,e,l,p,o,t);if(!b.success)break;l=b.ivPreCrypt,p=b.ivCurCrypt,o=b.debiBuf,e=b.bufPos,f=0}return a}function Wp(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:D_(d,s),bufPos:t+8}}var f_=typeof TextDecoder!="undefined"?new TextDecoder:void 0;function Hb({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:Fb(new Uint8Array(l))||(f_?f_.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 Wb=Object.prototype.hasOwnProperty,Sc=i=>typeof i=="function",Wn=i=>i===void 0,Gb=i=>typeof i=="boolean",jb=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 qb(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(jb(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(Wb.call(i,t))return!1;return!0}return!1}var zb=0,Jb=1,g_=2;function Xb({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,T=zb,_=(b,C)=>y(this,null,function*(){let D=n||this;try{let x=yield i.apply(D,a);p>0&&s&&s.call(this,p),p=0,b(x)}catch(x){let H=()=>{clearTimeout(f),p=0,T=g_,C(x)},W=()=>{T!==g_&&p<(Sc(d)?d():d)?(p++,T=Jb,Sc(r)&&r.call(this,p,H),f=window.setTimeout(()=>{f=-1,_(b,C)},Sc(l)?l(p):l)):(H(),Sc(o)&&o.call(this,x))};Sc(e)?e.call(this,{error:x,retry:W,reject:C,retryFuncArgs:a,retriedCount:p}):W()}});return new Promise(_)}}var Qb=Xb,Gp=class w_{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=!Gb(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 w_({id:t.id,userId:Wn(t.userId)?this.userId:t.userId,sdkAppId:Wn(t.sdkAppId)?this.sdkAppId:t.sdkAppId,type:Wn(t.type)?this.type:t.type,isLocal:Wn(t.isLocal)?this.isLocal:t.isLocal,remoteUserId:Wn(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}`:""}]`),MR.log(t,e,Wn(this.userId)||qb(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)}},Ei=typeof navigator=="undefined"?"":navigator.userAgent,ve=i=>new RegExp(i,"i").test(Ei),Rt=i=>{if(ve(i)){let t=new RegExp(`${i}\\/([\\d.]+)`),e=Ei.match(t);if(e&&e[1])return e[1]}return""},fl=i=>{if(ve(i)){let t=new RegExp(`${i}\\/(\\d+)`),e=Ei.match(t);if(e&&e[1])return parseFloat(e[1])}return NaN},E_=/AppleWebKit\/([\d.]+)/i.exec(Ei),Yb=E_?parseFloat(E_[1]):NaN,M_=ve("iPad"),O_=typeof navigator!="undefined"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&ve("Macintosh"),P_=ve("iPhone")&&!M_,Zb=ve("iPod"),ef=P_||M_||Zb||O_,Dc=ve("Android"),x_=function(){if(Dc){let i=Ei.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}(),YU=Dc&&ve("webkit")&&x_<2.3,ZU=Dc&&x_<5&&Yb<537,Kb=ve("Firefox"),eR=Rt("Firefox"),KU=fl("Firefox"),L_=ve("Edge"),tR=Rt("Edge"),k_=ve("Edg"),rR=Rt("Edg"),eV=fl("Edg"),U_=ve("SogouMobileBrowser"),iR=Rt("SogouMobileBrowser"),V_=ve("MetaSr\\s"),oR=Rt("MetaSr\\s"),Us=ve("TBS"),sR=Rt("TBS"),F_=ve("XWEB"),nR=Rt("XWEB"),tV=ve("MSIE\\s8\\.0"),aR=ve("MSIE\\/\\d+"),rV=function(){if(aR){let i=/MSIE\s(\d+)\.\d/.exec(Ei),t=i&&parseFloat(i[1]);return!t&&/Trident\/7.0/i.test(Ei)&&/rv:11.0/.test(Ei)&&(t=11),t}return NaN}(),cR=ve("(micromessenger|webbrowser)"),dR=Rt("MicroMessenger"),tf=!Us&&ve("MQQBrowser")&&ve("COVC"),rf=!Us&&ve("MQQBrowser")&&!ve("COVC"),__=rf||tf?Rt("MQQBrowser"):"",B_=!Us&&ve(" QQBrowser"),uR=Rt(" QQBrowser"),$_=!Us&&ve("QQBrowserLite"),lR=Rt("QQBrowserLite"),H_=!Us&&ve("MQBHD"),mR=Rt("MQBHD"),iV=ve("Windows"),oV=!ef&&ve("MAC OS X"),sV=!Dc&&ve("Linux"),nV=ve("CrOS"),aV=ve("MicroMessenger"),cV=ve("UCBrowser"),dV=ve("Electron"),W_=ve("MiuiBrowser"),hR=Rt("MiuiBrowser"),G_=ve("HuaweiBrowser"),uV=ve("Huawei")||ve("HUAWEI"),lV=ve("Honor")||ve("HONOR"),pR=Rt("HuaweiBrowser"),j_=ve("SamsungBrowser"),fR=Rt("SamsungBrowser"),q_=ve("HeyTapBrowser"),gR=Rt("HeyTapBrowser"),z_=ve("VivoBrowser"),ER=Rt("VivoBrowser"),mV=ve("OpenHarmony"),hV=Rt("OpenHarmony"),_R=()=>fl("Chrome"),T_=ve("CriOS"),J_=ve("Chrome"),TR=!L_&&!V_&&!U_&&!Us&&!F_&&!k_&&!B_&&!W_&&!G_&&!j_&&!q_&&!z_&&J_,IR=ve("HeadlessChrome"),pV=_R(),SR=Rt("Chrome"),fV=fl("Electron"),AR=!J_&&!rf&&!tf&&!$_&&!H_&&ve("Safari"),X_=Rt("Version"),gV=/Android.*(wv|.0.0.0)/.test(Ei),Q_=(()=>{if(O_)return X_;if(ef){let i=Ei.match(/OS (\d+)_(\d+)/i);if(i&&i[1]){let t=i[1];return i[2]&&(t+=`.${i[2]}`),t}}return""})(),EV=Number(Q_.split(".")[0]),_V=(()=>{let i=Number(Q_.split(".")[0]);return i===14||i===13})(),TV=typeof location!="undefined"&&(location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1"),IV=yR();function yR(){let i=new Map([[Kb,["Firefox",eR]],[k_,["Edg",rR]],[TR,["Chrome",SR]],[T_,["ChiOS",Rt("CriOS")]],[AR&&!T_,["Safari",X_]],[Us,["TBS",sR]],[F_,["XWEB",nR]],[cR&&P_,["WeChat",dR]],[B_,["QQ(Win)",uR]],[rf,["QQ(Mobile)",__]],[tf,["QQ(Mobile X5)",__]],[$_,["QQ(Mac)",lR]],[H_,["QQ(iPad)",mR]],[W_,["MI",hR]],[G_,["HW",pR]],[j_,["Samsung",fR]],[q_,["OPPO",gR]],[z_,["VIVO",ER]],[L_,["EDGE",tR]],[U_,["SogouMobile",iR]],[V_,["Sogou",oR]]]),t="unknown",e="unknown";return i.has(!0)&&([t,e]=i.get(!0)),{name:t,version:e}}var bR=b_(R_(),1),RR=new bR.default,Uo=RR,ul=v_,vR=class{constructor(){tt(this,"enable",!1),tt(this,"ssoFailCount",0),Uo.on("22",({schedule:i})=>{var t;(t=i==null?void 0:i.config)!=null&&t.sso&&Uo.emit("266",{enable:!0})}),Uo.on("266",({enable:i})=>{this.enable=i})}handleUploadFailed(){this.ssoFailCount++,this.ssoFailCount>3&&Uo.emit("266",{enable:!1})}},I_=new vR,CR="%cTRTC%c%s",NR="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",DR="display: inline",Y_=class Z_{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),Ib||Sb||(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){Uo.on(ul.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)}),Uo.on(ul.JOIN_START,({params:t})=>{this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload()}),Uo.on(ul.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)&&xR(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:Ub(),sdkAppId:String(a),userId:n,version:Tb,log:d.map(T=>T.log).join(`
93
- `)},p=JSON.stringify(l),f=I_.enable?UR(l,2002,a):p;yield this.uploadLogWithRetry(f,a,f instanceof Uint8Array,p),d.forEach(T=>T.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 Qb({retryFunction:()=>Hb({url:PR(e,Cb.LOG),body:t,timeout:5e3,priority:"low"}).then(s=>{r&&s.data!=="ok"&&(I_.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(N_()),`[${Vb(e)}] <${ks[t]}>`}getLogLevel(){return this._logLevel}setLogLevel(t){K_(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};Uo.emit(ul.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";Z_.PRINT_LOG_TAG?console[a](CR,NR,DR,...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 Gp){let e=t,{parent:r}=e,o=cb(e,["parent"]),s=new Gp(o);return s.bindParent(r),s}return new Gp(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(Y_,"PRINT_LOG_TAG",!(ef||Dc||IR));var wR=Y_,MR=new wR,OR=i=>Number(i)<14e8,PR=function(i,t){let e;return e=Ab||(OR(i)?vb:Rb),`${e}/v5/AVQualityReportSvc/C2S?random=${Math.floor(Math.random()*ni(2,31))}&sdkappid=${i}&cmdtype=${t}`},SV=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},K_=i=>i===void 0,Zp=i=>typeof i=="string",xR=i=>typeof i=="number",AV=typeof HTMLMediaElement!="undefined"&&"setSinkId"in HTMLMediaElement.prototype;function LR(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var{toString:yV}=Object.prototype;function kR(i,t,e,r){let o={data:i,random:Math.floor(Math.random()*2147483648),sdkAppId:e};return K_(r)||(o=bc(yc({},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 UR(i,t,e,r){try{let o=kR(i,t,e,r);return Pb(Xp(o),e)}catch(o){return JSON.stringify(i)}}var eT=class tT{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 tT.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 _b(bc(yc({},e),{wasmPath:`${s}/videodec.wasm`}));case"webCodecs":return new Gn;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(bc(yc({},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=LR()-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(bc(yc({},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(eT,"Name","TRTCVideoDecoder");var of=eT;var LT=vi(ki());function sf({timesInSecond:i,maxSizeInSecond:t,getSize:e}){return xe((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 ce({code:q.INVALID_OPERATION,message:je({key:Ge.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-26 15:00:05",rT=!0,iT=function(){var i;if(rT){rT=!1,F.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${sr}/en/index.html`),console.info(`* Changelog: ${sr}/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:",ft),Jr||F.debug("Build Time:",VR);let t=`UA: ${navigator.userAgent}
93
+ `)},p=JSON.stringify(l),f=I_.enable?UR(l,2002,a):p;yield this.uploadLogWithRetry(f,a,f instanceof Uint8Array,p),d.forEach(T=>T.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 Qb({retryFunction:()=>Hb({url:PR(e,Cb.LOG),body:t,timeout:5e3,priority:"low"}).then(s=>{r&&s.data!=="ok"&&(I_.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(N_()),`[${Vb(e)}] <${ks[t]}>`}getLogLevel(){return this._logLevel}setLogLevel(t){K_(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};Uo.emit(ul.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";Z_.PRINT_LOG_TAG?console[a](CR,NR,DR,...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 Gp){let e=t,{parent:r}=e,o=cb(e,["parent"]),s=new Gp(o);return s.bindParent(r),s}return new Gp(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(Y_,"PRINT_LOG_TAG",!(ef||Dc||IR));var wR=Y_,MR=new wR,OR=i=>Number(i)<14e8,PR=function(i,t){let e;return e=Ab||(OR(i)?vb:Rb),`${e}/v5/AVQualityReportSvc/C2S?random=${Math.floor(Math.random()*ni(2,31))}&sdkappid=${i}&cmdtype=${t}`},SV=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},K_=i=>i===void 0,Zp=i=>typeof i=="string",xR=i=>typeof i=="number",AV=typeof HTMLMediaElement!="undefined"&&"setSinkId"in HTMLMediaElement.prototype;function LR(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var{toString:yV}=Object.prototype;function kR(i,t,e,r){let o={data:i,random:Math.floor(Math.random()*2147483648),sdkAppId:e};return K_(r)||(o=bc(yc({},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 UR(i,t,e,r){try{let o=kR(i,t,e,r);return Pb(Xp(o),e)}catch(o){return JSON.stringify(i)}}var eT=class tT{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 tT.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 _b(bc(yc({},e),{wasmPath:`${s}/videodec.wasm`}));case"webCodecs":return new Gn;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(bc(yc({},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=LR()-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(bc(yc({},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(eT,"Name","TRTCVideoDecoder");var of=eT;var LT=vi(ki());function sf({timesInSecond:i,maxSizeInSecond:t,getSize:e}){return xe((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 ce({code:q.INVALID_OPERATION,message:je({key:Ge.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-29 15:40:15",rT=!0,iT=function(){var i;if(rT){rT=!1,F.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${sr}/en/index.html`),console.info(`* Changelog: ${sr}/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:",ft),Jr||F.debug("Build Time:",VR);let t=`UA: ${navigator.userAgent}
94
94
  CPU core: ${navigator.hardwareConcurrency}, GPU: ${qm()}`;if(ot&&window.screen&&(window.screen.width||window.screen.height)){let r=`${window.screen.width}x${window.screen.height}@${window.devicePixelRatio}`;t+=`, screen: ${r}`}let 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":""}`),fs().then(r=>{r&&F.info(Wr)})}};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 oe={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},Sr=(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))(Sr||{});function sT({code:i,params:t,enableDocLink:e=!1}){let r="",o,s=Sr[i];try{o=oT[s]}catch(n){o=oT.UNKNOWN_ERROR}return Xe(o)?r=o(t):Me(o)&&(r=o),t.fnName&&!r.includes(t.fnName)&&(r[r.length-1]!=="."&&(r+="."),r+=` thrown from ${t.fnName}()`),e&&(r+=" doc:"),r}var oT=Ie(Y({},cr),{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: ${gt(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: ${gt(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 nf=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=sT({code:e===oe.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=Sr[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"},T={startLocalVideo:"webcam",startLocalAudio:"microphone"},_=document.createElement("a");ps?_.href=`ms-settings:privacy-${T[this.functionName]}`:zr&&(_.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${f[this.functionName]}`),_.href.length>0&&_.click()})}static convertFrom(e,r,o){let s=e;if(e instanceof ce){let{stack:n}=e,a={code:oe.UNKNOWN_ERROR,fnName:r,originError:e};switch(e.getCode()){case q.INVALID_PARAMETER:a.code=oe.INVALID_PARAMETER,a.message=e.message;break;case q.INVALID_OPERATION:a.code=oe.INVALID_OPERATION;break;case q.NOT_SUPPORTED:case q.NOT_SUPPORTED_H264:a.code=oe.ENV_NOT_SUPPORTED,e.getCode()===q.NOT_SUPPORTED_H264&&(a.extraCode=e.message.includes(cr.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=oe.SERVER_ERROR,a.extraCode=e.getExtraCode();break;case q.API_CALL_ABORTED:a.code=oe.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=FR(e.name));break;case q.VIDEO_ENCODE_FAILED:a.extraCode=5505;case q.AUDIO_ENCODE_FAILED:a.extraCode=5506,a.code=oe.OPERATION_FAILED;break;case q.UNKNOWN:break;default:a.code=oe.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:oe.UNKNOWN_ERROR,fnName:r,originError:e})}return s}};function FR(i){let t;switch(i){case"NotFoundError":t=5301;break;case"NotAllowedError":t=5302;break;case"NotReadableError":t=5303;break;case"OverconstrainedError":t=5304;break;case"InvalidStateError":t=5305;break;case"SecurityError":t=5306;break;case"AbortError":t=5307;break;default:t=5300}return t}var ae=nf;function _i(i){return i==="sub"?"auxiliary":i==="auxiliary"?"sub":"main"}function wc(i){return i===Vs.QOS_PREFERENCE_CLEAR?"detail":i===Vs.QOS_PREFERENCE_SMOOTH?"motion":""}function qn(i,t){let e=t?fm:fa;return xm(i)?Y(Y({},e),i):Fr[i]?Fr[i]:e}var nT={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}}},aT={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}}},zn={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(i,t,e){if(Me(i)&&!document.getElementById(i))throw new ae({code:oe.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:t}})}},cT={name:"userId",required:!0,type:"string"},dT={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 Jn(i,t){if(!i)throw new ae({code:oe.INVALID_OPERATION,extraCode:5101,fnName:t})}function uT(i,t,e){if(!i)throw new ae({code:oe.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:e}})}function lT(i,t,e){if(!(/^[1-9]\d*$/.test(String(i))&&i<4294967295))throw new ae({code:oe.INVALID_PARAMETER,extraCode:5013,fnName:t,messageParams:{key:e}})}function mT(i,t,e){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(i))throw new ae({code:oe.INVALID_PARAMETER,extraCode:5012,fnName:t,messageParams:{key:e}})}var X2={type:"number",notLessThanZero:!0},BR=(i,t)=>i.width*i.height>=t.width*t.height&&i.frameRate>=t.frameRate&&i.bitrate>=t.bitrate;function hT(i){var r;if(!((r=i==null?void 0:i.option)!=null&&r.small))return;if(!Su()){F.warn("small stream is not supported"),delete i.option.small;return}let t=qn(i.option.profile),e=qn(i.option.small,!0);if(!BR(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 $R={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(i,t,e){if(this._room.isJoined)throw new ae({code:oe.INVALID_OPERATION,extraCode:5104,fnName:e});if(i.roomId){if(Me(i.roomId))throw new ae({code:oe.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:t}});lT(i.roomId,e,t)}else if(i.strRoomId)mT(i.strRoomId,e,t);else throw new ae({code:oe.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:zn,mute:{type:["boolean","string"]},publish:{type:"boolean"},capture:{required:!1,type:"boolean"},option:nT},validate(i){var t,e;if(!((t=i==null?void 0:i.option)!=null&&t.videoTrack)&&Hi())throw new ae({code:oe.ENV_NOT_SUPPORTED,extraCode:5201});(e=i==null?void 0:i.option)!=null&&e.small&&hT(i)}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:Ie(Y({},zn),{required:!1}),publish:{type:"boolean"},capture:{required:!1,type:"boolean"},mute:{type:["boolean","string"]},option:nT},validate(i){var t;(t=i==null?void 0:i.option)!=null&&t.small&&hT(i)}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:dT},validate(i){var t;if(!((t=i==null?void 0:i.option)!=null&&t.audioTrack)&&Hi())throw new ae({code:oe.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:dT}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:zn,publish:{type:"boolean"},option:aT},validate(i,t,e,r,o){var s;if(!((s=i==null?void 0:i.option)!=null&&s.videoTrack)){if(Hi())throw new ae({code:oe.ENV_NOT_SUPPORTED,extraCode:5201});if(!Ja())throw new ae({code:oe.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:zn,publish:{type:"boolean"},option:aT}},muteRemoteAudio:[cT,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[cT,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:zn,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){Jn(this._room.isJoined,e);let r=this._room.remotePublishedUserMap.get(i.userId);if(uT(!!r,e,i),r&&(i.streamType==="main"&&!r.muteState.videoAvailable||i.streamType==="sub"&&!r.muteState.hasAuxiliary))throw new ae({code:oe.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:i}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:Ie(Y({},zn),{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){Jn(this._room.isJoined,e);let r=this._room.remotePublishedUserMap.get(i.userId);if(uT(!!r,e,i),r&&(i.streamType==="main"&&!r.muteState.videoAvailable||i.streamType==="sub"&&!r.muteState.hasAuxiliary))throw new ae({code:oe.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 ae({code:oe.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(i,t,e){Jn(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(!Qa)throw new ae({code:oe.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new ae({code:oe.INVALID_OPERATION,fnName:e,extraCode:5108});if(i.byteLength>1e3)throw new ae({code:oe.INVALID_PARAMETER,extraCode:5018,fnName:e});if(i.byteLength===0)throw new ae({code:oe.INVALID_PARAMETER,extraCode:5017,messageParams:{key:t},fnName:e});Jn(this._room.isJoined,e)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(i,t,e){if(!i&&!this._room.isMainStreamPublished||i&&!this._room.isAuxStreamPublished)throw new ae({code:oe.INVALID_OPERATION,extraCode:5109,messageParams:{key:t},fnName:e})}}}}],sendCustomMessage:{name:"message",required:!0,type:"object",properties:{cmdId:{type:"number",required:!0,min:1,max:10},data:{instanceOf:ArrayBuffer,required:!0,validate(i,t,e,r){if(i.byteLength>1e3)throw new ae({code:oe.INVALID_PARAMETER,extraCode:5018,fnName:e});if(i.byteLength===0)throw new ae({code:oe.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:t}})}}},validate(i,t,e){if(Jn(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new ae({code:oe.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:t}})}},switchRoom:{name:"switchRoomConfig",type:"object",required:!0,validate(i,t,e){if(Jn(this._room.isJoined,e),this._room.useStringRoomId&&i.strRoomId===this._room.roomId||!this._room.useStringRoomId&&i.roomId===Number(this._room.roomId))throw new ae({code:oe.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 ae({code:oe.INVALID_PARAMETER,extraCode:5019,fnName:e,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(i.roomId)lT(i.roomId,e,t);else if(i.strRoomId)mT(i.strRoomId,e,t);else throw new ae({code:oe.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:$R};var Kt=class extends Error{};function HR(i,t){let e=ns(i);for(let r=0;r<t.length;r++)$r(e[r],t[r]);return e}function WR(i){this._resolve=Promise.resolve(i)}function GR(i){this._reject=Promise.reject(i)}var Vo=class Vo{constructor(t,e){this.instance=t;this.group=e;m(this,"started",!1);m(this,"ops",[]);m(this,"startSame",()=>!0);m(this,"mergeUpdate",HR);let r=Vo.instances.get(t);r?r.set(e,this):Vo.instances.set(t,new Map([[e,this]]))}static get(t,e){if(!e)return;let r=Vo.instances.get(t);return r&&r.get(e)||new Vo(t,e)}static gets(t,e){let r=Vo.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 Kt("start failed")),(l=this.currentOp)==null||l.action(),a},n={type:t,action:()=>e(...n.args).then(o,s),args:r,resolve:WR,reject:GR};try{switch(this.state){case 1:if(t===0)throw new Kt("already started");break;case 4:if(t===2)throw new Kt("not started");break;default:return this.cacheOp(n)}}catch(a){return Promise.reject(a)}return this.ops.push(n),n.promise=e(...n.args).then(o,s)}cacheOp(t){if(this.ops.length===1)switch(this.state){case 0:case 2:if(t.type===0)throw new Kt("already start");break;case 3:switch(t.type){case 2:throw new Kt("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new Kt("unknown state")}else switch(t.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let r=new Kt("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 Kt("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new Kt("start not allowed after update");case 0:throw new Kt("duplicate start");case 3:if(this.startSame(this.currentOp.args,t.args))throw this.ops.pop().reject(new Kt("keep start")),new Kt("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(Vo,"instances",new WeakMap);var Qi=Vo;var El=new WeakMap,_l=(i,t)=>{if(t instanceof Kt){let{stack:e}=t;t=new ae({code:oe.OPERATION_ABORT,message:`${i} abort: ${t.message}`,fnName:i}),e&&(t.stack+=e.substr(e.indexOf(`
96
96
  `)))}throw t};function Fo(i,t){return xe((e,r)=>function(...o){let s=Qi.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(_l.bind(null,r))):e.apply(this,o)})}function Bs(i,t){let{merge:e,debounce:r}=t||{};return xe((o,s)=>function(...n){let a=Qi.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 b,C;let T=(b=El.get(this))==null?void 0:b.get(l(...n));if(T){let{timeoutId:D,resolve:x}=T;clearTimeout(D),x()}let _=setTimeout(()=>{if(a.state===3||a.state===4)return p();a.action(2,o.bind(this),n).catch(_l.bind(null,s)).then(p,f)},d);El.has(this)?(C=El.get(this))==null||C.set(l(...n),{timeoutId:_,resolve:p}):El.set(this,new Map([[l(...n),{timeoutId:_,resolve:p}]]))})}return a.action(2,o.bind(this),n).catch(_l.bind(null,s))})}function Bo(i){return xe((t,e)=>function(...r){let o=typeof i=="function"?i.call(this,...r):i;if(o instanceof RegExp)return Promise.all(Qi.gets(this,o).map(n=>n.action(3,()=>Promise.resolve(),r))).then(()=>t.call(this,...r));let s=Qi.get(this,o);return s?s.action(3,t.bind(this),r).catch(_l.bind(null,e)):t.apply(this,r)})}function $o(){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: ${sr}/en/TRTC.html#.${t}`;r.warn(o)},e}}var se={ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",KICKED_OUT:"kicked-out",REMOTE_USER_ENTER:"remote-user-enter",REMOTE_USER_EXIT:"remote-user-exit",REMOTE_AUDIO_AVAILABLE:"remote-audio-available",REMOTE_AUDIO_UNAVAILABLE:"remote-audio-unavailable",REMOTE_VIDEO_AVAILABLE:"remote-video-available",REMOTE_VIDEO_UNAVAILABLE:"remote-video-unavailable",AUDIO_VOLUME:"audio-volume",AUDIO_FRAME:"audio-frame",NETWORK_QUALITY:"network-quality",CONNECTION_STATE_CHANGED:"connection-state-changed",AUDIO_PLAY_STATE_CHANGED:"audio-play-state-changed",VIDEO_PLAY_STATE_CHANGED:"video-play-state-changed",SCREEN_SHARE_STOPPED:"screen-share-stopped",DEVICE_CHANGED:"device-changed",PUBLISH_STATE_CHANGED:"publish-state-changed",TRACK:"track",STATISTICS:"statistics",SEI_MESSAGE:"sei-message",CUSTOM_MESSAGE:"custom-message",VIDEO_DECODE_DOWNGRADE_STATE_CHANGED:"video-decode-downgrade-state-changed",LAYER_DATA:"layerData",FIRST_VIDEO_FRAME:"first-video-frame",PERMISSION_STATE_CHANGE:"permission-state-change",VIDEO_SIZE_CHANGED:"video-size-changed"},pT=new Set([se.AUDIO_VOLUME,se.AUDIO_FRAME,se.NETWORK_QUALITY,se.STATISTICS,se.SEI_MESSAGE,se.CUSTOM_MESSAGE,se.LAYER_DATA]);var df={};Ri(df,{ScheduleRequestType:()=>ET,getAbilityConfig:()=>zR,getScheduleDomain:()=>Sl,isNeedToSchedule:()=>Tl,scheduleProxy:()=>Ti,sendScheduleRequest:()=>cf,setIsNeedToSchedule:()=>Yi,setScheduleProxy:()=>Il});var af=null,gT=0,jR=48*3600*1e3,Tl=!0;typeof document!="undefined"&&document.head.insertAdjacentHTML("beforeend",Object.values(Di).map(i=>`<link rel="dns-prefetch" href="https://${i}">`).join(`\r
@@ -102,7 +102,7 @@ CPU core: ${navigator.hardwareConcurrency}, GPU: ${qm()}`;if(ot&&window.screen&&
102
102
  ${e.map(l=>l.toString()).join(`
103
103
  `)};(${r})();${o}})()`,n=new Blob([s],{type:"text/javascript"}),a=URL.createObjectURL(n),d=new Worker(a);return URL.revokeObjectURL(a),d}var ST=!1,AT;function yT({TRTC:i,room:t,errorModule:e,assetsPath:r}){return{TRTC:i,LocalMixVideoTrack:xs,LocalVideoTrack:Ir,LocalScreenTrack:fi,room:t,assetsPath:r,fileDownloader:Oc,innerEmitter:U,INNER_EVENT:B,constants:Tm,environment:bn,utils:Lp,eventLogger:Fe,log:this.room.getLogger(),loggerManager:F,errorModule:e,kvStatManager:z,rtcDectection:vo,trtc:this,rx:Op,enums:mh,schedule:df,getDevices:On,initVisionTaskRegistry:(o,s,n="/mediapipe/vision.js")=>y(this,null,function*(){!window.VisionTaskRegistry&&!ST&&(ST=!0,AT=Oc.loadScript(`${o}/${n}`.replace(/([^:]\/)\/+/g,"$1"))),yield AT,yield(yield window.VisionTaskRegistry.getInstance(o)).preloadModels(s)}),audioContext:ze(),deviceDetector:dt,AudioPlayer:xn,RemoteAudioPlayer:Ln,VideoPlayer:Ht,showAutoPlayDialog:Dn,Timer:ht,clearStarted:(o,s)=>{let n=o.getAlias(),a=Qi.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:Tc,createAudioNode:ac,getNetworkTimeOffset:Jf,validateSourceNode:()=>{var o;if(st&&!((o=this.room.audioManager._localAudioPipline)!=null&&o.source.node))throw new ae({code:oe.DEVICE_ERROR,extraCode:5310,message:"The audio processing plugin cannot be used due to the microphone's sampling rate is not 48KHz in Firefox. Please switch to another browser such as Chrome."})},createScriptTransformWorker:IT}}var bT=(i,t)=>{let{emit:e}=i;return i.emit=(...r)=>{try{return e.apply(i,r)}catch(o){let s=je({key:Ge.CATCH_HANDLER_ERROR,data:{name:t,event:r[0]},addDocLink:!1});return F.warn(`${s}
104
104
 
105
- ${o.stack}`),!1}},i};var Xn=new WeakMap;function RT(i){let t=Xn.get(i);t&&(t.forEach(e=>clearTimeout(e)),Xn.delete(i))}function vT(i,t){return xe((e,r)=>function(...o){let s=Xn.get(this);s||(s=new Map,Xn.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=Xn.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=Xn.get(this))==null||l.delete(n)},i);s.set(n,d)}})}var NT="trtc-sdk-v5",gf="5.15.0-wasm.1";function Gt(...i){return xe((t,e)=>function(...r){try{yl.call(this,i,r,e,this._name)}catch(o){return Promise.reject(o)}return t.apply(this,r)})}function Ef(...i){return xe((t,e)=>function(...r){try{yl.call(this,i,r,e,this._name)}catch(o){throw o}return t.apply(this,r)})}function yl(i,t,e,r){if(mt(i))for(let o=0;o<i.length;o++)Al.call(this,{rule:i[o],value:t[o],key:i[o].name,fnName:e,className:r});else Al.call(this,{rule:i,value:t[0],key:i.name,fnName:e,className:r})}function Al({rule:i,value:t,key:e,fnName:r,className:o}){function s(d){return{code:oe.INVALID_PARAMETER,extraCode:d,fnName:r,messageParams:{key:e,rule:i,value:t}}}if(O(t)){if(i.required)throw new ae(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),Me(i.type[l])&&gt(t)===i.type[l].toLowerCase()&&(d=!0);if(!d)throw new ae({code:oe.INVALID_PARAMETER,extraCode:5002,fnName:r,messageParams:{key:e,rule:{type:i.type.map(l=>cs(l)?dn(l):Me(l)?l:gt(l))},value:t}})}else if(!O(i.type)&&gt(t)!==i.type)throw new ae(s(5002));if(i.allowEmpty===!1){let d=$e(t)&&(t===0||Number.isNaN(t)),l=Me(t)&&t.trim()==="";if(d||l)throw new ae(s(5003))}if(i.notLessThanZero&&$e(t)&&t<0)throw new ae(s(5006));if(!O(i.min)&&$e(t)&&t<i.min)throw new ae(s(5007));if(!O(i.max)&&$e(t)&&t>i.max)throw new ae(s(5008));if(Me(i.instanceOf)){if(!t||t._name!==i.instanceOf)throw new ae(s(5004))}else if(Xe(i.instanceOf)&&!(t instanceof i.instanceOf))throw new ae(s(5004));if(Array.isArray(i.values)&&!i.values.includes(t))throw new ae(s(5005));let{properties:n}=i;Yt(n)&&fr(t)&&Object.keys(n).forEach(d=>{Al.call(this,{rule:n[d],value:t&&t[d],key:`${d}`,fnName:r,className:o})});let{arrayItem:a}=i;Yt(a)&&mt(t)&&t.forEach((d,l)=>{Al.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)}var KR=0;function nt(i={}){let{getRemoteId:t=()=>"",replaceArg:e,getKVReportKey:r,ignoreLog:o,ignoreErrorLog:s}=i;return xe((n,a)=>function(...d){var b,C,D;function l(x,H,W){if(W&&W.includes(x))return"hided";if(e){let ne=e(...d);if(d[ne.argIndex]===H)return ne.value}if(H===d||x in d)return H;try{return H instanceof HTMLElement?`id: ${H.id} type:${gt(H)}`:H instanceof MediaStreamTrack?Md(H):(JSON.stringify(H),H)}catch(ne){return`type:${gt(H)}`}}let p=(this==null?void 0:this._log)||F,f=++KR;if(o!=null&&o(...d))return n.apply(this,d);d.length>0?p.info(`${a}() ${f} ${JSON.stringify(d,(x,H)=>l(x,H,["userSig","privateMapKey"]))}`):p.info(`${a}() ${f}`);let T=r?r(...d):fu[a],_=(s==null?void 0:s(...d))||!1;try{let x=n.apply(this,d),H=fe();if(go(x)){let W=`${a.includes("Plugin")?`${((C=(b=d[0]).getName)==null?void 0:C.call(b))||""} `:" "}`;return x.then(ne=>(p.info(`${a}() success ${f} ${W}${t.call(this,...d)}`),z.addSuccessEvent({key:T,cost:fe()-H}),ne)).catch(ne=>{var Or;ne=ae.convertFrom.call(this,ne,a,d.length===1?d[0]:d);let Ve=ne.extraCode||ne.code,he=(Or=ne.message)!=null&&Or.includes(Ve)?"":` code:${Ve}`,Q=(ne==null?void 0:ne.code)===oe.OPERATION_ABORT;throw _||p[Q?"warn":"error"](`${a}() failed ${f} ${W}${t.call(this,...d)} ${ne}${he} params: ${JSON.stringify(d,l)}`),z.addFailedEvent({key:T,error:ne}),ne})}return z.addSuccessEvent({key:T}),x}catch(x){x=ae.convertFrom.call(this,x,a);let H=x.extraCode||x.code,W=(D=x.message)!=null&&D.includes(H)?"":` code:${H}`,ne=(x==null?void 0:x.code)===oe.OPERATION_ABORT;throw _||p[ne?"warn":"error"](`${a}() failed ${f} ${x}${W} params: ${JSON.stringify(d,l)}`),z.addFailedEvent({key:T,error:x}),x}})}var bl=i=>xe((t,e)=>function(r,o){return y(this,null,function*(){let s=this._plugins.get(r);if(!s)throw this._log.error(`plugin ${String(r)} is not found`),new ae({code:oe.OPERATION_ABORT,message:`plugin ${String(r)} is not found`,fnName:e});if(Xe(s.constructor.isSupported)&&!s.constructor.isSupported())throw this._log.error(`plugin ${String(r)} is not supported`),new ae({code:oe.ENV_NOT_SUPPORTED,message:`plugin ${String(r)} is not supported`,extraCode:5210,fnName:e});return yl.call(this,s.getValidateRule(i),[o],e,"TRTC"),t.call(this,s,o)})});var Rl=0,_f,Zi=class Zi{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");Rl=Rl+1,this.log=t.log.createChild({id:`${this.getAlias()}${Rl}`}),this.log.info(`created id=${this.getAlias()}${Rl}`),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 ae({code:oe.INVALID_OPERATION,extraCode:5106,fnName:o})}}}preload(t){return _f||(_f=this.doPreload(t)),_f}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 Zi.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(t){switch(t){case"start":return Zi.getStartValidateRule(this.core);case"update":return Zi.updateValidateRule;case"stop":return Zi.stopValidateRule}}start(t){return y(this,null,function*(){var T,_,b,C;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 ae({code:oe.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:D,status:x,timestamp:H}=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,H,D,x,e)}if(f&&!this.screenAudioWorkletNode){let{sign:D,status:x,timestamp:H}=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,H,D,x,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()),(T=this.localAudioWorkletNode)==null||T.port.postMessage({type:"enable"}),(_=this.screenAudioWorkletNode)==null||_.port.postMessage({type:"enable"}),e.audioManager.addAudioProcessor(this.mixNode,this.silentNode,this.localAudioWorkletNode,this.screenAudioWorkletNode),O(a)||a.forEach(D=>{this.customAudioReferenceMap.set(D,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:D,refId:`o-${this.audioRefId++}`})}),O(d)||(b=this.localAudioWorkletNode)==null||b.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:d}}),O(l)||(C=this.localAudioWorkletNode)==null||C.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 tv({sdkAppId:t,userSig:r,userId:e,timestamp:o});if(!s)throw this.log.info(`audioProcessor: ${e} auth result: ${s}. Message: ${d}`),new ae({code:oe.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 T=(p==null?void 0:p.value)>10?"info":"debug";this.log[T](`${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(Zi,"updateValidateRule",{type:"object"}),m(Zi,"stopValidateRule",{type:"object"}),m(Zi,"Name","AudioProcessor");var vl=Zi;function ev(i,t=M.MAIN){return`https://${Ti[t]||Sl(i,t)}/api/v1/audioAiAuth`}function tv(o){return y(this,arguments,function*({sdkAppId:i,userId:t,userSig:e,timestamp:r}){let n=`${ev(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 T=vr(i)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",_="Init RTCAudioProcessor failed.",b="";switch(d){case 1:b="Please check your params.";break;case 2:b=`You need to buy packages. Refer to: ${T}`;break;case 3:b="Server is invalid. Please contact our engineer. ";break;case 4:b=`Your packages is not active. Refer to: ${T}`;break;case 5:b=`Your packages is expired. Refer to: ${T}`;break;case 6:b="Your version is not supported.";break}return{auth:!1,status:f,message:l?`${_} Reason: ${l}. ${b}`:`${_}, ${b}`}})}var Cl=0,Tf=class{constructor(t,e){m(this,"audioObjectURL");m(this,"player");m(this,"publisher");m(this,"mixInput");this.mixInput=new Mn(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 Oc.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 Qn(i,t){if(t&&typeof t!="function")throw new ae({code:oe.INVALID_PARAMETER,message:`start audioMixer plugin: param ${i} should be a function.`})}var Ii=class Ii{constructor(t){this.core=t;m(this,"log");m(this,"mixedMusicMap",new Map);m(this,"cacheMusicMap",new Map);Cl=Cl+1,this.log=t.log.createChild({id:`${this.getAlias()}${Cl}`}),this.log.info(`created id=${this.getAlias()}${Cl}`)}getName(){return Ii.Name}getAlias(){return"ax"}getGroup(t){return t==null?void 0:t.id}getValidateRule(t){switch(t){case"start":return Ii.startValidateRule;case"update":return Ii.updateValidateRule;case"stop":return Ii.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 Tf(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.`),z.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(se.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&&z.addCount({key:502009}),r&&z.addCount({key:502001}),o&&z.addCount({key:502002}),s&&z.addCount({key:502003}),n&&z.addCount({key:502004}),a&&z.addCount({key:502005}),typeof d!="function"&&z.addCount({key:502007}),typeof p!="function"&&z.addCount({key:502008}),typeof l!="function"&&z.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(Ii,"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 ae({code:oe.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:r})}if(!t.url&&!t.track)throw new ae({code:oe.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:r});Qn("onTimeUpdate",t.onTimeUpdate),Qn("onEnded",t.onEnded),Qn("onDurationChange",t.onDurationChange)}}),m(Ii,"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){Qn("onTimeUpdate",t.onTimeUpdate),Qn("onEnded",t.onEnded),Qn("onDurationChange",t.onDurationChange)}}),m(Ii,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),m(Ii,"Name","AudioMixer");var Nl=Ii;var Dl=0,If,Ki=class Ki{constructor(t){this.core=t;m(this,"log");m(this,"audioContext",ze("denoiser"));m(this,"workletNode");m(this,"config",{enableFarFieldReduce:!1,farFieldReduceThreshold:.5});Dl=Dl+1,this.log=t.log.createChild({id:`${this.getAlias()}${Dl}`}),this.log.info(`created id=${this.getAlias()}${Dl}`)}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 ae({code:oe.INVALID_OPERATION,extraCode:5106,fnName:o})}}}preload(t){return If||(If=this.doPreload(t)),If}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 Ki.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser"}getValidateRule(t){switch(t){case"start":return Ki.startValidateRule(this.core);case"update":return Ki.updateValidateRule;case"stop":return Ki.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 ae({code:oe.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${Rh()?"":"-nosimd"}.js`),!this.workletNode){let s=String(Date.now()).slice(0,-3),{auth:n,sign:a,status:d,message:l}=yield iv(r,Ie(Y({},t),{timestamp:s}));if(!n)throw this.log.info(`RTCAIDenoiser: ${t.userId} auth result: ${n}. Message: ${l}`),new ae({code:oe.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 T;let{data:f}=p;if(f.type==="cost"){let _=(f==null?void 0:f.max)>20?"warn":(f==null?void 0:f.max)>10?"info":"debug";this.log[_](`avg cost: ${f.value} max: ${f==null?void 0:f.max}(${Ks(new Date(f==null?void 0:f.maxCostTimestamp))}) hist: ${(T=f==null?void 0:f.hist)==null?void 0:T.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(Ki,"updateValidateRule",{type:"object",properties:{mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}}}),m(Ki,"stopValidateRule",{type:"object"}),m(Ki,"Name","AIDenoiser");var wl=Ki;function iv(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=vr(t)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",T="Init RTCAIDenoiser failed.",_="";switch(a){case 1:_="Please check your params.";break;case 2:_=`You need to buy packages. Refer to: ${f}`;break;case 3:_="Server is invalid. Please contact our engineer. ";break;case 4:_=`Your packages is not active. Refer to: ${f}`;break;case 5:_=`Your packages is expired. Refer to: ${f}`;break;case 6:_="Your version is not supported.";break}return{auth:!1,status:p,message:d?`${T} Reason: ${d}. ${_}`:`${T}, ${_}`}}catch(a){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${a}`}}})}var wT=vi(ki(),1);var Sf=class extends wT.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){Fe.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){Fe.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:r})}}},ov=new Sf,Af=ov;var yf=0,Pc=class Pc{constructor(t){this.core=t;m(this,"log");m(this,"_seiMessageList",[]);m(this,"_smallSeiMessageList",[]);m(this,"_subStreamSeiMessageList",[]);yf++,this.log=t.log.createChild({id:`${this.getAlias()}${yf}`}),this.log.info(`[sei] created id=${this.getAlias()}${yf}`),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 pf({frame:t,seiMessageList:r})}catch(r){this.log.warn(r)}return t}decode({frame:t,track:e}){return ff({frame:t,onSEI:r=>{r.forEach(o=>{e!=null&&e.userId?this.core.trtc.emit(se.SEI_MESSAGE,{seiPayloadType:o.seiPayloadType,data:o.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"}):this.core.innerEmitter.emit(this.core.INNER_EVENT.SEI_MESSAGE,{room:this.core.room,nalu:o})})}})}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:Ss?this.encode:pf,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:Ss?this.decode:ff,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 Pc.Name}getAlias(){return"sei"}getGroup(){return"sei"}};m(Pc,"autoStart",!0),m(Pc,"Name","SEI");var Ml=Pc;var sv=0,Ol,xc=class xc{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()}${++sv}`}),this.log.info("created")}getName(){return xc.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(Ol)yield Ol;else{let e=new URLSearchParams(location.search).get("trtcDebugDialogPath")||((t=window.sessionStorage)==null?void 0:t.getItem("TRTC_DEBUG_DIALOG_PATH"))||`https://unpkg.com/${NT}@${ft}/assets/debug-dialog.js`;Ol=this._core.fileDownloader.loadScript(e),yield Ol}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(xc,"Name","Debug"),m(xc,"autoStart",!0);var Pl=xc;var MT=i=>{switch(i){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},xl=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=ye(e,me.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}`),be(l,Je(this.stopOB),Le(()=>{},p=>{e.log.error(p),o.addFailedEvent({key:MT(this.type),error:p}),d>4?this.startOB.error(p):this.startOB.next(d+1)})),be(l,ei(1),Np(fc))};be(this.startOB,hc(0),hi(a),Je(this.stopOB),Le(()=>{e.player.setOutput(),n.next("STARTED")},d=>{n.next("FAILED")},()=>{o.addSuccessEvent({key:MT(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"}))}},nv={type:"object"},Lc=class Lc{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 Lc.Name}getGroup(t){return t.track.userId+t.track.streamType}getName(){return Lc.Name}getValidateRule(t){return nv}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 xl(this.core,r,t);return be(o.trackDoneOB,ei(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 xl(this.core,t.track,t))}}};m(Lc,"Name","TRTCAudioDecoder");var kc=Lc;var Ll=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 ce({code:q.INVALID_PARAMETER,message:je({key:Ge.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 T=d.getPCM(_=>{e.emit(se.AUDIO_FRAME,_)},f.userId);l.set(f.userId,T)}});else{if(l.get(o))return;let f=d.getPCM(T=>{e.emit(se.AUDIO_FRAME,T)},o);l.set(o,f)}else if(o==="*")e.room.remotePublishedUserMap.forEach(f=>{if(f.remoteAudioTrack.isSubscribed){let{userId:T}=f,_=l.get(T);_==null||_.abort("disable"),l.delete(T)}});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(!1)):s.isAvailable&&s.player.pause(!1):(r.isAvailable&&r.player.pause(),o.isAvailable&&o.player.pause(!1),s.isAvailable&&s.player.pause(!1))});else{let e=t.trtcInstance.room.remotePublishedUserMap.get(t.userId);e&&(t.streamType==="main"?(e.remoteAudioTrack.player.pause(),e.remoteVideoTrack.player.pause(!1)):e.remoteAuxiliaryTrack.player.pause(!1))}}};Z([d_({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"}}})],Ll.prototype,"enableAudioFrameEvent",1);var OT=new Ll;var PT=vi(ki(),1);var bf=class extends PT.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={}}},Uc=new bf;var xT=0,Vc=new Set,Ft=null;lm(gf);Rn.checkStorage();var Ee=class Ee extends LT.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${++xT}`}));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:Ee.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(Nl,r.assetsPath),this._use(vl,r.assetsPath),this._use(wl,r.assetsPath),this._use(kc,r.assetsPath),this._use(Pl),r.enableSEI&&Qa&&this._use(Ml),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(se.AUDIO_VOLUME,{result:o.sort((a,d)=>d.volume-a.volume)})}),this._room.videoManager.on("error",o=>{this._log.error(new ae({code:oe.OPERATION_FAILED,extraCode:5504,message:o.message,originError:o}))}),this._listenEvents(),this._initActiveSpeaker(),bT(this,"trtc")}static create(e){}static _create(e,r){iT();let o=new Ee(e,r||{});return Vc.add(o),o.__v_skip=!0,o}get room(){return this._room}_listenEvents(){$t(this,this._room).add("peer-join",e=>{let{userId:r}=e;this.emit(se.REMOTE_USER_ENTER,{userId:r})}).add("peer-leave",({userId:e,reason:r})=>{this.emit(se.REMOTE_USER_EXIT,{userId:e,reason:r})}).add("banned",e=>{Yi(!0),this._exitRoom().finally(()=>{this.emit(se.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().finally(()=>{this.emit(se.ERROR,ae.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(se.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let r=Ie(Y({},e),{uplinkRTT:Math.min(e.uplinkRTT,_a),downlinkRTT:Math.min(e.downlinkRTT,_a)});this.emit(se.NETWORK_QUALITY,r)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(o=>{$t(o,o).add("player-state-changed",s=>{let n=Ie(Y({},s),{userId:e.userId});o.kind===M.VIDEO&&(n.streamType=_i(o.streamType)),this.emit(o.kind===M.AUDIO?se.AUDIO_PLAY_STATE_CHANGED:se.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",s=>{s.getCode()===q.PLAY_NOT_ALLOWED&&this.emit(se.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?se.REMOTE_VIDEO_AVAILABLE:se.REMOTE_VIDEO_UNAVAILABLE,{userId:o,streamType:"main"})),s!==a&&(a?this._onAudioAvailable({userId:o}):this._onAudioUnavailable({userId:o,muteState:r}),this.emit(a?se.REMOTE_AUDIO_AVAILABLE:se.REMOTE_AUDIO_UNAVAILABLE,{userId:o})),e.hasAuxiliary!==r.hasAuxiliary&&(r.hasAuxiliary?this._onVideoAvailable({userId:o,streamType:"sub"}):this._onVideoUnavailable({userId:o,streamType:"sub"}),this.emit(r.hasAuxiliary?se.REMOTE_VIDEO_AVAILABLE:se.REMOTE_VIDEO_UNAVAILABLE,{userId:o,streamType:"sub"}))}).add("sei-message",e=>{this.emit(se.SEI_MESSAGE,Ie(Y({},e),{streamType:_i(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(se.ERROR,new ae({code:oe.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,_a),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(T=>r[T.uint32_video_stream_type]).map(T=>({bitrate:(T.uint32_video_codec_bitrate||0)/1e3,width:T.uint32_video_width,height:T.uint32_video_height,frameRate:T.uint32_video_enc_fps,videoType:r[T.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(T=>({userId:T.msg_user_info.str_identifier,audio:{bitrate:(T.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(T.msg_audio_status.uint32_audio_level||0)/Fi,point2pointDelay:(T.msg_audio_status.uint32_audio_p2p_delay||0)+(T.msg_audio_status.uint32_audio_cache_ms||0),jitterBufferDelay:T.msg_audio_status.uint32_audio_cache_ms||0},video:T.msg_video_status.map(_=>({bitrate:(_.uint32_video_codec_bitrate||0)/1e3,width:_.uint32_video_width,height:_.uint32_video_height,frameRate:_.uint32_video_dec_fps,videoType:r[_.uint32_video_stream_type],point2pointDelay:(_.uint32_video_p2p_delay||0)+(_.uint32_video_cache_ms||0),jitterBufferDelay:_.uint32_video_cache_ms||0,codec:_.uint32_video_codec}))}))};this.emit(se.STATISTICS,o)}).add("custom-message",e=>{this.emit(se.CUSTOM_MESSAGE,e)}).add("layerData",e=>this.emit(se.LAYER_DATA,e)).add("first-video-frame",e=>{this.emit(se.FIRST_VIDEO_FRAME,Ie(Y({},e),{streamType:_i(e.streamType)}))}).add("audio-frame",e=>{this.emit(se.AUDIO_FRAME,e)}),$t(this,dt).add("audioInputAdded",e=>{this.emit(se.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(se.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(se.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(se.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>y(this,null,function*(){if(this.emit(se.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Ft&&Ft.deviceId===Ea){let r=(yield Do()).find(o=>o.deviceId===Ea);r&&Ft.groupId!==r.groupId&&(Ft=r,this.emit(se.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}))}})).add("audioOutputRemoved",e=>y(this,null,function*(){this.emit(se.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let r=(yield Do())[0];if(!r||!Ft||Ft.groupId===r.groupId)return;let o=Ft.deviceId===e.deviceId,s=Ft.deviceId===Ea&&Ft.deviceId===r.deviceId;(o||s)&&(Ft=r,this.emit(se.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}))})),$t(this,Uc).add("permission-state-change",e=>{this.emit(se.PERMISSION_STATE_CHANGE,e)}),this.room.enableSEI&&this.on(se.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 Ci()}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(yT.call(this,{TRTC:Ee,room:this._room,assetsPath:r,errorModule:{RtcError:ae,ErrorCode:oe,CoreErrorCode:q,ErrorCodeDictionary:Sr}}));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),!Me(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,Ee.frameWorkType),this._checkTrackToPublish(),Af.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 ma&&(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(),RT(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(),Vc.delete(this),Vc.size===0&&Af.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 pi(this._room.audioManager),a={},d={muted:!0};s&&(O(s.microphoneId)?O(s.audioTrack)||(a.customSource=s.audioTrack):a.deviceId=s.microphoneId,s&&$e(s.captureVolume)&&n.setCaptureVolume(s.captureVolume),O(s.profile)||(Me(s.profile)?gd[s.profile]&&n.setProfile(gd[s.profile]):n.setProfile(s.profile)),$e(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(se.ERROR,new ae({code:oe.DEVICE_ERROR,extraCode:5309,messageParams:{error:l}}))}),n.on("2",l=>{this.emit(se.DEVICE_CHANGED,{type:"microphone",action:"active",device:l})}),n.on("4",l=>{let p;l.error&&(p=ae.convertFrom(l.error)),this.emit(se.PUBLISH_STATE_CHANGED,Ie(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),$t(n,n).add("player-state-changed",l=>{this.emit(se.AUDIO_PLAY_STATE_CHANGED,Ie(Y({},l),{userId:""}))}),r&&this._room.isJoined&&this._room.publish(n).catch(()=>{}),this._localAudioTrack=n,this._localAudioConfig=Ie(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}),$r(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 Ir(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=wc(a.qosPreference)),O(a.profile)||(Me(a.profile)?Fr[a.profile]&&d.setProfile(Fr[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(qn(a.small,!0))),O(a.rotation)||d.setRotation(a.rotation),Ye(this._enableAutoSwitchWhenRecapturing)&&(d.enableAutoSwitchWhenRecapturing=this._enableAutoSwitchWhenRecapturing)),d.once("first-video-frame",T=>{this.emit(se.FIRST_VIDEO_FRAME,Ie(Y({},T),{streamType:_i(T.streamType)}))}),d.on("5",T=>{this.emit(se.ERROR,new ae({code:oe.DEVICE_ERROR,extraCode:5308,messageParams:{error:T}}))}),d.on("2",T=>{this.emit(se.DEVICE_CHANGED,{type:"camera",action:"active",device:T})}),d.on("4",T=>{let _;T.error&&(_=ae.convertFrom(T.error)),this.emit(se.PUBLISH_STATE_CHANGED,Ie(Y({},T),{error:_}))}),d.on("6",()=>{}),this._listenOutputTrackChanged(d),s?yield d.capture(l):(f=d.manager)==null||f.changeInput(d),O(n)||(yield d.setMute(n)),$t(d,d).add("player-state-changed",T=>{this.emit(se.VIDEO_PLAY_STATE_CHANGED,Ie(Y({},T),{userId:"",streamType:"main"}))}).add("video-size-changed",T=>{this.emit(se.VIDEO_SIZE_CHANGED,Ie(Y({},T),{streamType:_i(T.streamType)}))}),o&&this._room.isJoined&&this._room.publish(d).catch(()=>{}),this._localVideoTrack=d,this._localVideoConfig=Ie(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 T={};T.deviceId=(a==null?void 0:a.cameraId)||((l=this._localVideoConfig.option)==null?void 0:l.cameraId),T.facingMode=a!=null&&a.useFrontCamera||(p=this._localVideoConfig.option)!=null&&p.useFrontCamera?M.FACING_MODE_USER:M.FACING_MODE_ENVIRONMENT,T.customSource=(a==null?void 0:a.videoTrack)||((f=this._localVideoConfig.option)==null?void 0:f.videoTrack),yield this._localVideoTrack.capture(T)}a&&(O(a.profile)||(Me(a.profile)?Fr[a.profile]&&this._localVideoTrack.setProfile(Fr[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(wc(a.qosPreference)),O(a.small)||(Ye(a.small)&&!a.small?this._localVideoTrack.stopSmall():this._localVideoTrack.updateSmallConfig(qn(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}),$r(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 T,_;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 fi(this._room.videoManager);a.on("4",b=>{let C;b.error&&(C=ae.convertFrom(b.error)),this.emit(se.PUBLISH_STATE_CHANGED,Ie(Y({},b),{error:C}))}),a.once("first-video-frame",b=>{this.emit(se.FIRST_VIDEO_FRAME,Ie(Y({},b),{streamType:_i(b.streamType)}))}),this._listenOutputTrackChanged(a),e.streamType==="main"&&(a.mediaType=4);let d=null,l={},p={};n&&(O(n.profile)||(Me(n.profile)?Ed[n.profile]&&a.setProfile(Ed[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=wc(n.qosPreference)));let f=yield a.capture(l);if(a.mediaTrack.addEventListener(M.ENDED,()=>{this._stopScreenShare(),this.emit(se.SCREEN_SHARE_STOPPED)}),f.getAudioTracks()[0]){d=new Ls(this._room.audioManager);let b=f.getAudioTracks()[0];(T=e.option)!=null&&T.systemAudio&&!((_=e.option)!=null&&_.audioTrack)&&(d.sourceTrack=b),yield d.setInputMediaStreamTrack(b),Ye(s)&&d.mediaTrack&&(d.mediaTrack.enabled=!s),this._speakerId&&d.setAudioOutput(this._speakerId)}if($t(a,a).add("player-state-changed",b=>{this.emit(se.VIDEO_PLAY_STATE_CHANGED,Ie(Y({},b),{userId:"",streamType:"sub"}))}),o&&this._room.isJoined){let b=[a];d&&(b.push(d),this._checkScreenAudioEchoCancellation(a,d)),b.forEach(C=>this._room.publish(C).catch(()=>{}))}this._localScreenTrack=a,this._localScreenAudioTrack=d,this._localScreenConfig=Ie(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=wc(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}),$r(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(se.ERROR,new ae({code:oe.OPERATION_FAILED,extraCode:5507,message:"video decode failed"}))}),p.on("video-size-changed",f=>{this.emit(se.VIDEO_SIZE_CHANGED,Ie(Y({},f),{streamType:_i(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 x,H;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,T=this._room.remotePublishedUserMap.get(o);if(s==="main"&&(T!=null&&T.muteState.hasVideo)&&(f=T.remoteVideoTrack),s==="sub"&&(T!=null&&T.muteState.hasAuxiliary)&&(f=T.remoteAuxiliaryTrack),!f)return;let{config:_}=l;s==="main"&&n&&!O(n.small)&&this._room.changeType(n.small,f.user),n&&!O(n.draggable)&&f.setDraggable(n.draggable),n&&(Ye(n.pictureInPicture)&&(n.pictureInPicture?yield f.player.enterPictureInPicture():yield f.player.exitPictureInPicture()),Ye(n.fullScreen)&&(n.fullScreen?yield f.player.enterFullscreen():yield f.player.exitFullscreen())),Ye(a)&&(f.ignoreUpdatePlayingState=!0,a?(yield f.player.pause(),yield this.room.unsubscribe(f)):(yield this.room.subscribe(f),yield f.player.resume(!0))),yield this._updateVideoPlayOption({view:r,playOption:p,track:f,prevConfig:_}),$r(_,e);let b=O(n==null?void 0:n.receiveWhenViewVisible)?(x=_.option)==null?void 0:x.receiveWhenViewVisible:n.receiveWhenViewVisible,C=O(r)?_.view:r,D=O(n==null?void 0:n.viewRoot)?(H=_.option)==null?void 0:H.viewRoot:n.viewRoot;this._observeView({remoteTrack:f,view:C,receiveWhenViewVisible:b,viewRoot:D})})}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)&&this.room.isJoined&&(yield this._startRemoteAudio({userId:s.userId}))}else r?yield this._stopRemoteAudio({userId:e}):!this._remoteAudioConfigMap.has(e)&&this.room.isJoined&&(yield this._startRemoteAudio({userId:e}))}catch(o){throw o.code!==oe.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(se.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{pT.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===Ee.EVENT.AUDIO_FRAME||e==="*")&&this.listeners(Ee.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(Me(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 Do()).forEach(o=>{o.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(se.DEVICE_CHANGED,{type:"speaker",action:"active",device:o}),Ft=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: ${sr}/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(se.ERROR,new ae({code:oe.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=$e(d)?d:100;s.volume=l,this._remoteAudioConfigMap.set(r,e),yield this._room.subscribe(n),be(ye(n,"decode-failed"),Je(ye(n,me.INIT)),Le(()=>{this.startPlugin(kc.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;be(ye(e,"decode-failed"),Je(ye(e,me.INIT)),ws(()=>{this._room.downlinkVideoCodec!=="h265"&&this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:o})}),qi(ye(e,"decode-downgrade-state-changed")),Le(n=>{s=n.state,this.emit(se.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,Ie(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 pi&&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 Ji){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(se.TRACK,{userId:o,streamType:_i(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}_${_i(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(T=>{T.forEach(_=>{l.set(_.target,_.isIntersecting),e.log.info(`view ${_.target.id} is${_.isIntersecting?"":" not"} visible`)}),clearTimeout(p),p=window.setTimeout(()=>{[...l.values()].find(b=>b)?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((T,_)=>{f.has(_)||(a.unobserve(_),l.delete(_))}),f.forEach(T=>{l.set(T,!0),a.observe(T)}),a.takeRecords().forEach(T=>{l.set(T.target,T.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"&&(!Ft||Pn(Ft))&&(this._initActiveSpeaker(),U.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return y(this,null,function*(){if(Ft&&!Pn(Ft))this.emit(se.DEVICE_CHANGED,{type:"speaker",action:"active",device:Ft});else{let e=yield Do();e[0]&&!Pn(e[0])?(Ft=e[0],this.emit(se.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:Ie(Y({seiPayloadType:243},r),{small:!!((s=this._localVideoTrack)!=null&&s.small)})}),z.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var r,o;(o=(r=this._room).sendCustomMessage)==null||o.call(r,e),z.addCount({key:500001,useUV:!0})}callExperimentalAPI(e,r){return y(this,null,function*(){return this._log.info(`callExperimentalAPI(${e}, ${JSON.stringify(r)})`),OT.call(e,Y({trtcInstance:this},r))})}static setLogLevel(e,r){F.setLogLevel(e),O(r)||(r?F.enableUploadLog():F.disableUploadLog())}static isSupported(){return Iu(Ee.frameWorkType)}static getPermissions(o){return y(this,arguments,function*({request:e=!0,types:r=["camera","microphone"]}){e&&(yield Uc.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([Uc.get("camera"),Uc.get("microphone")]);return{camera:s,microphone:n}})}static getCameraList(e=!0){return ur(e)}static getMicrophoneList(e=!0){return dr(e)}static getSpeakerList(e=!0){return Do(e)}static setCurrentSpeaker(e){return y(this,null,function*(){if(at&&(e===Vs.SPEAKER||e===Vs.HEADSET)){let o=yield Ee.getMicrophoneList(),s="";if(o.forEach(n=>{n.label===e&&(s=n.deviceId)}),!s)return;Vc.forEach(n=>y(this,null,function*(){n._localAudioTrack&&(yield n.updateLocalAudio({option:{microphoneId:s}}))}));return}(yield Do()).forEach(o=>{o.deviceId===e&&(Vc.forEach(s=>{s._setCurrentSpeaker(e),s.emit(se.DEVICE_CHANGED,{type:"speaker",action:"active",device:o})}),Ft=o)})})}static _addKVStat({type:e,key:r,value:o,base:s,useUV:n,version:a,max:d}){switch(a&&(Is.version=a),e){case"count":Is.addCount({key:r,useUV:n});break;case"enum":Is.addEnum({key:r,value:o,useUV:n});break;case"number":Is.addNumber({key:r,value:o,split:s,max:d});break}}};m(Ee,"VERSION",gf),m(Ee,"_loggerManager",F),m(Ee,"EVENT",se),m(Ee,"ERROR_CODE",oe),m(Ee,"TYPE",Vs),m(Ee,"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"}})})],Ee.prototype,"use",1),Z([Gt(Ot.TRTC.enterRoom),Fo("room",([e],[r])=>(e.roomId||e.strRoomId)===(r.roomId||r.strRoomId)&&e.userId===r.userId&&e.sdkAppId===r.sdkAppId),xe(e=>function(r){return this._log.setUserId(r.userId),this._log.setSdkAppId(r.sdkAppId),e.call(this,r)}),nt()],Ee.prototype,"enterRoom",1),Z([nt()],Ee.prototype,"exitRoom",1),Z([Gt(Ot.TRTC.switchRoom),nt(),Lu()],Ee.prototype,"switchRoom",1),Z([Gt(Ot.TRTC.switchRole),Bs("room",{merge:(e,r)=>r}),nt()],Ee.prototype,"switchRole",1),Z([nt()],Ee.prototype,"destroy",1),Z([Gt(Ot.TRTC.startLocalAudio),Fo("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()],Ee.prototype,"startLocalAudio",1),Z([Gt(Ot.TRTC.updateLocalAudio),Bs("audio",{debounce:{delay:200,getKey:()=>`${xT}-localAudio`,isNeedToDebounce:e=>{var r;return!O((r=e.option)==null?void 0:r.captureVolume)}}}),nt()],Ee.prototype,"updateLocalAudio",1),Z([Bo("audio"),nt()],Ee.prototype,"stopLocalAudio",1),Z([Gt(Ot.TRTC.startLocalVideo),Fo("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()],Ee.prototype,"startLocalVideo",1),Z([Gt(Ot.TRTC.updateLocalVideo),Bs("video"),nt()],Ee.prototype,"updateLocalVideo",1),Z([Bo("video"),nt()],Ee.prototype,"stopLocalVideo",1),Z([Gt(Ot.TRTC.startScreenShare),Fo("screen",()=>!0),nt()],Ee.prototype,"startScreenShare",1),Z([Gt(Ot.TRTC.updateScreenShare),Bs("screen"),nt()],Ee.prototype,"updateScreenShare",1),Z([nt()],Ee.prototype,"stopScreenShare",1),Z([Gt(Ot.TRTC.startRemoteVideo),Fo(e=>`v${e.userId}${e.streamType}`,()=>!0),nt({getRemoteId:e=>`${e.userId}_${e.streamType}`})],Ee.prototype,"startRemoteVideo",1),Z([Gt(Ot.TRTC.updateRemoteVideo),Bs(e=>`v${e.userId}${e.streamType}`),nt({getRemoteId:e=>`${e.userId}_${e.streamType}`})],Ee.prototype,"updateRemoteVideo",1),Z([Gt(Ot.TRTC.stopRemoteVideo),xe(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}`})],Ee.prototype,"stopRemoteVideo",1),Z([Bo(e=>`v${e.userId}${e.streamType}`)],Ee.prototype,"_stopRemoteVideo",1),Z([Gt(...Ot.TRTC.muteRemoteAudio),nt({getRemoteId:e=>e})],Ee.prototype,"muteRemoteAudio",1),Z([Ef(...Ot.TRTC.setRemoteAudioVolume),vT(200,e=>e),nt({getRemoteId:e=>e})],Ee.prototype,"setRemoteAudioVolume",1),Z([bl("start"),wo(e=>{var r;return(r=e.afterStart)==null?void 0:r.call(e)}),Fo((e,r)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(r)),nt({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>ph[e.getName()],ignoreLog:e=>e.getName()==="Debug",ignoreErrorLog:e=>e.getName()==="AudioProcessor"})],Ee.prototype,"startPlugin",1),Z([bl("update"),Bs((e,r)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(r),{merge:(e,r)=>($r(e[1],r[1]),e)}),nt({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>fh[e.getName()]})],Ee.prototype,"updatePlugin",1),Z([bl("stop"),Bo((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=>gh[e.getName()]})],Ee.prototype,"stopPlugin",1),Z([Ef(...Ot.TRTC.enableAudioVolumeEvaluation)],Ee.prototype,"enableAudioVolumeEvaluation",1),Z([nt()],Ee.prototype,"getVideoSnapshot",1),Z([nt()],Ee.prototype,"_setCurrentSpeaker",1),Z([Fo(e=>`a${e.userId}`,()=>!0)],Ee.prototype,"_startRemoteAudio",1),Z([xe(e=>function(r){return y(this,null,function*(){return r.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(o=>this._stopRemoteAudio(Ie(Y({},r),{userId:o.userId})).catch(()=>{}))):e.call(this,r)})}),Bo(e=>`a${e.userId}`)],Ee.prototype,"_stopRemoteAudio",1),Z([Bo("room")],Ee.prototype,"_exitRoom",1),Z([Bo("screen")],Ee.prototype,"_stopScreenShare",1),Z([Gt(...Ot.TRTC.sendSEIMessage),sf({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...e)=>e[0].byteLength})],Ee.prototype,"sendSEIMessage",1),Z([Gt(Ot.TRTC.sendCustomMessage),sf({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],Ee.prototype,"sendCustomMessage",1),Z([$o()],Ee,"create",1),Z([Gt(Ot.TRTC.create)],Ee,"_create",1),Z([$o()],Ee,"setLogLevel",1),Z([$o()],Ee,"isSupported",1),Z([$o(),nt()],Ee,"getPermissions",1),Z([$o()],Ee,"getCameraList",1),Z([$o()],Ee,"getMicrophoneList",1),Z([$o()],Ee,"getSpeakerList",1);var Rf=Ee,Yn=Rf;var kl=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 Ji(t,this),this.remoteVideoTrack=new Lo(t,this),this.remoteAuxiliaryTrack=new al(t,this),this.flag=e.flag||0}get subscribeState(){let t={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(this.remoteVideoTrack.mediaType&8?t.smallVideo=!0:t.video=!0),this.remoteAudioTrack.isSubscribed&&(t.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(t.auxiliary=!0),t}get muteState(){return ds(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 vf=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 av(){return y(this,null,function*(){let i,t;try{let _=yield dr();i=_&&_.length}catch(_){}try{let _=yield ur();t=_&&_.length}catch(_){}let e={microphone:i,camera:t},{isH264EncodeSupported:r,isVp8EncodeSupported:o,isH264DecodeSupported:s,isVp8DecodeSupported:n,isH265EncodeSupported:a,isH265DecodeSupported:d}=this.checkSystemResult.detail,l=vo.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},T={isWebCodecSupported:l.isWebCodecSupported,isMediaSessionSupported:l.isMediaSessionSupported,isWebTransportSupported:l.isWebTransportSupported};Fe.uploadEvent({log:`trtcstats-${JSON.stringify(f)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(f)}`),Fe.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(T)}`,userId:this.userId}),Ch()})}function kT(){return xe(i=>{let t=new vf;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 ce({code:q.INVALID_OPERATION,message:je({key:Ge.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:s,sdkAppId:this.sdkAppId,room:this}))throw new ce({code:q.INVALID_OPERATION,message:je({key:Ge.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=di.getEnv();n||(n=Ni.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(_d.OLD_CLOUD_LADDER)?n=Ni.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(_d.WEBRTC)&&(n=Ni.WEBRTC))),Fe.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:s}),vo.checkSystemRequirementsInternal(o).then(a=>{this.checkSystemResult=a,av.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!di.getEnv()&&(yield this.schedule(e,o));let a=yield i.call(this,e,r,o);return this.roomId=s,this._joinedTimestamp=di.performanceNow(),U.emit(B.JOIN_SUCCESS,{room:this}),o===30&&!e.component&&Fe.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 UT=()=>xe(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 xe(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 FT(){return xe(i=>function(...t){let e=i.apply(this,t);return t.forEach(r=>r.unpublish()),e})}function BT(){return xe(i=>function(...t){let e=i.apply(this,t);return t.forEach(r=>!r.isSubscribed&&r.subscribe(e)),e})}function cv({fn:i,context:t}){return function(...e){try{let r=i.apply(t,e);return go(r)?r.catch(o=>F.error(`${i.name}() error observed ${o}`)):r}catch(r){F.error(`${i.name}() error observed ${r}`)}}}var Ul=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]=cv({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:ft,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,fs().then(()=>{this._basicInfo.string_os_version=Li(),this._basicInfo.string_device_name=gs()||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(),ht.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 ce?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=fe()-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 ce?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:Ie(Y({},dv),{msg_user_info:new Fc({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 Fc({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,z.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(T=>{let _=T.uint32_video_stream_type===2,b=T.uint32_video_stream_type===7,C=`${p}_${_?"main":"auxiliary"}`,D=this._remoteStreamStatMap.get(C);if(D&&(_&&(f!=null&&f.remoteVideoTrack.isSubscribed)||b&&(f!=null&&f.remoteAuxiliaryTrack))){D.totalVideoFPS+=T.uint32_video_receive_fps,D.totalVideoBitrate+=T.uint32_video_codec_bitrate,D.videoCount++,D.statsToReport.uint32_video_width===0&&(D.statsToReport.uint32_video_width=T.uint32_video_width),D.statsToReport.uint32_video_height===0&&(D.statsToReport.uint32_video_height=T.uint32_video_height);let x=_?f.remoteVideoTrack:f.remoteAuxiliaryTrack;x.stat.jitterBufferDelay&&(D.videoJitterBufferDelay=x.stat.jitterBufferDelay),x.stat.framesReceived&&(D.statsToReport.uint32_video_consume_render_rate=Math.floor(x.stat.framesDecoded/x.stat.framesReceived*ni(10,6)))}}),!un(d)){let T=`${p}_main`,_=this._remoteStreamStatMap.get(T);this._remoteStreamStatMap.has(T)&&_&&f!=null&&f.remoteAudioTrack.isSubscribed&&(_.totalAudioBitrate+=d.uint32_audio_codec_bitrate,_.audioCount++,f.remoteAudioTrack.stat.jitterBufferDelay&&(_.audioJitterBufferDelay=f.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(d.uint32_audio_level/Fi*100)>0&&(_.totalAudioLevel+=d.uint32_audio_level/Fi,_.audioLevelCount++),d.uint32_audio_block_time&&(_.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 ce?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&ga)>=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:T,videoDelayCount:_,totalAudioDelay:b,totalVideoDelay:C}=o;t.statsToReport.uint32_avg_down_loss=Math.floor(p/f),T&&b&&(t.statsToReport.uint32_audio_network_p2p_delay=Math.floor(b/T),t.audioJitterBufferDelay&&(t.statsToReport.uint32_p2p_delay=Math.floor(t.statsToReport.uint32_audio_network_p2p_delay+t.audioJitterBufferDelay))),_&&C&&(t.statsToReport.uint32_video_network_p2p_delay=Math.floor(C/_))}t.videoCount>0&&(t.statsToReport.uint32_video_avg_fps=Math.floor(t.totalVideoFPS/t.videoCount),t.statsToReport.uint32_video_avg_bitrate=Math.floor(t.totalVideoBitrate/t.videoCount)),t.audioCount>0&&(t.statsToReport.uint32_audio_recv_bitrate=t.statsToReport.uint32_audio_bitrate=Math.floor(t.totalAudioBitrate/t.audioCount)),t.audioLevelCount>0&&(t.statsToReport.uint32_audio_play_db=Math.floor(t.totalAudioLevel/t.audioLevelCount*100));let{callDurationCalculator:s}=this._room;s&&(t.statsToReport.uint32_audio_play_time=s.getDuration(e,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=Cd();let t={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new Fc({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()*ni(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 ya(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=So.enable?Mi(t,2001,e):yield Pm(t),o=r instanceof ArrayBuffer,s=`${wi(e,po.KEY_POINT)}&gzip=${+o}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(s,r));let a=[this.uploadKVStat(z),this.uploadKVStat(Is)];n||a.push(Oi({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=Ie(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=So.enable?Mi(e,2003,this._room.sdkAppId):yield Pm(e),o=r instanceof ArrayBuffer,s=`${wi(+this._room.sdkAppId,po.KV_STAT)}&gzip=${+o}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(s,r)),n||Oi({url:s,body:r})})}};Z([ys({settings:{timeout:500,retries:3}})],Ul.prototype,"upload",1);var $s=5e3,dv={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},Fc=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}},$T=Ul;var Cf=class{constructor(){m(this,"_startTime");m(this,"_endTime");this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=fe())}stop(){this._endTime===0&&(this._endTime=fe())}getDuration(){return this._endTime===0?fe()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},Vl=Cf;var Nf=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 Vl,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()}},HT=Nf;var Df=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||st)&&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()}},wf=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 Df);m(this,"_eventMap",new Map);m(this,"_videoEncodeFailedCount",0);m(this,"_audioEncodeFailedCount",0);m(this,"_encodeFailedThreshold",3);m(this,"ABNORMAL_TIME_LOWER_LIMIT",3e3);m(this,"ABNORMAL_TIME_UPPER_LIMIT",5e3);m(this,"_videoAbnormalTimestampMap",new Map);m(this,"_remoteVideoAbnormalTimestampMap",new Map);m(this,"_audioAbnormalTimestampMap",new Map);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 Vl;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}){this.hitTest(t)&&(this.localMediaTrackDetector(e),this.remoteMediaTrackDetector(e))}remoteMediaTrackDetector(t){t.msg_down_stream_info.length>0&&t.msg_down_stream_info.forEach(e=>{var s;if(e.msg_video_status.length===0)return;let r=e.msg_user_info.str_identifier,o=(s=this._room.remotePublishedUserMap.get(r))==null?void 0:s.remoteVideoTrack;e.msg_video_status.forEach(n=>{let a=fe();if(n.uint32_video_codec_bitrate!==void 0&&n.uint32_video_codec_bitrate>0&&n.uint32_video_receive_fps===0&&(o!=null&&o.muted))if(!this._remoteVideoAbnormalTimestampMap.has(`${r}-decode`))this._remoteVideoAbnormalTimestampMap.set(`${r}-decode`,a);else{let d=this._remoteVideoAbnormalTimestampMap.get(`${r}-decode`);d&&a-d>this.ABNORMAL_TIME_LOWER_LIMIT&&a-d<this.ABNORMAL_TIME_UPPER_LIMIT&&Fe.uploadEvent({userId:this._room.userId,log:`stat-${Lt.VIDEO_DECODE_FAILED_DURING_CALL}`})}else{let d=this._remoteVideoAbnormalTimestampMap.get(`${r}-decode`);d&&a-d>=this.ABNORMAL_TIME_UPPER_LIMIT&&(Fe.uploadEvent({userId:this._room.userId,log:`stat-${Lt.VIDEO_DECODE_RESUME_DURING_CALL}`}),this._remoteVideoAbnormalTimestampMap.delete(`${r}-decode`))}if(n.uint32_video_codec_bitrate!==void 0&&n.uint32_video_codec_bitrate>5e5&&n.uint32_video_dec_fps!==void 0&&n.uint32_video_dec_fps<=5)if(!this._remoteVideoAbnormalTimestampMap.has(`${r}-hardware`))this._remoteVideoAbnormalTimestampMap.set(`${r}-hardware`,a);else{let d=this._remoteVideoAbnormalTimestampMap.get(`${r}-hardware`);if(d&&a-d>this.ABNORMAL_TIME_LOWER_LIMIT/2&&a-d<this.ABNORMAL_TIME_UPPER_LIMIT*2){Fe.uploadEvent({userId:this._room.userId,log:`stat-${Lt.VIDEO_HARDWARE_DECODE_FAILED}`});let l=this._room.remotePublishedUserMap.get(r);if(l){let p=n.uint32_video_stream_type===2?l.remoteVideoTrack:l.remoteAuxiliaryTrack;p&&(p.log.warn("decode failed during call"),p.emit("decode-failed-during-call"))}}}else{let d=this._remoteVideoAbnormalTimestampMap.get(`${r}-hardware`);d&&a-d>=this.ABNORMAL_TIME_UPPER_LIMIT*2&&(Fe.uploadEvent({userId:this._room.userId,log:`stat-${Lt.VIDEO_HARDWARE_DECODE_RESUME}`}),this._remoteVideoAbnormalTimestampMap.delete(`${r}-hardware`))}})})}localMediaTrackDetector(t){if(t.msg_up_stream_info.msg_video_status){let e=t.msg_up_stream_info.msg_video_status,r=Array.from(this._room.localTracks).find(s=>s.kind==="video"&&!s.isScreen),o=(r==null?void 0:r.stat.bytesSent)||0;if((r==null?void 0:r.isMediaTrackActive)===!1||o<=0||r!=null&&r.isUseCustomSource)return;e.forEach(s=>{let n=fe();if(s.uint32_video_stream_type===2)if(s.uint32_video_capture_fps!==0&&s.uint32_video_codec_bitrate===0&&s.uint32_video_enc_fps===0&&(r!=null&&r.isPublished))if(!this._videoAbnormalTimestampMap.has("local-encode"))this._videoAbnormalTimestampMap.set("local-encode",n);else{let a=this._videoAbnormalTimestampMap.get("local-encode");a&&n-a>this.ABNORMAL_TIME_LOWER_LIMIT&&n-a<this.ABNORMAL_TIME_UPPER_LIMIT&&Fe.uploadEvent({userId:this._room.userId,log:`stat-${Lt.VIDEO_ENCODE_FAILED_DURING_CALL}`})}else{let a=this._videoAbnormalTimestampMap.get("local-encode");a&&n-a>=this.ABNORMAL_TIME_UPPER_LIMIT&&Fe.uploadEvent({userId:this._room.userId,log:`stat-${Lt.VIDEO_ENCODE_RESUME_DURING_CALL}`}),this._videoAbnormalTimestampMap.delete("local-encode")}})}if(t.msg_up_stream_info.msg_audio_status){let e=t.msg_up_stream_info.msg_audio_status,r=Array.from(this._room.localTracks).find(n=>n.kind==="audio"),o=(r==null?void 0:r.stat.bytesSent)||0;if((r==null?void 0:r.isMediaTrackActive)===!1||o<=0||r!=null&&r.isUseCustomSource)return;let s=fe();if(e.uint32_audio_codec_bitrate===0&&(r!=null&&r.isPublished))if(!this._audioAbnormalTimestampMap.has("local-encode"))this._audioAbnormalTimestampMap.set("local-encode",s);else{let n=this._audioAbnormalTimestampMap.get("local-encode");n&&s-n>this.ABNORMAL_TIME_LOWER_LIMIT&&s-n<this.ABNORMAL_TIME_UPPER_LIMIT&&Fe.uploadEvent({userId:this._room.userId,log:`stat-${Lt.AUDIO_ENCODE_FAILED_DURING_CALL}`})}else{let n=this._audioAbnormalTimestampMap.get("local-encode");n&&s-n>=this.ABNORMAL_TIME_UPPER_LIMIT&&Fe.uploadEvent({userId:this._room.userId,log:`stat-${Lt.AUDIO_ENCODE_RESUME_DURING_CALL}`}),this._audioAbnormalTimestampMap.delete("local-encode")}}}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>Sd){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()<Sd&&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(!Yr())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,T=d.presentationTime-r;if(T>f){T=Math.min(T,5e3);let _=`${t.userId}_${t.streamType}`,b=this._monitorFreezeData.get(_,"render");b?b.duration+=T:this._monitorFreezeData.set(_,{userId:t.userId,type:t.streamType,duration:T},"render");let C=this._renderFreezeMap.get(_);C?(C.totalDuration+=T,C.count+=1):this._renderFreezeMap.set(_,{userId:t.userId,type:t.streamType,totalDuration:T,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()}},WT=wf;var qT=vi(ki(),1);var Fl=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?z.addSuccessEvent({key:s.key}):z.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:T,offset:_}=this.calculateBoundary(d,s,t,r),{min:b,offset:C}=this.calculateBoundary(l,n,e,o);return p=2*T+r,f=2*b+o,p/f>this.originalAspect?(p=f*this.originalAspect,_=d-p/2):(f=p/this.originalAspect,C=l-f/2),r/s>a&&(_=0,C=0,p=s,f=n),_=Math.max(0,Math.min(_,s-p)),C=Math.max(0,Math.min(C,n-f)),{sx:_,sy:C,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)),$e(this.animationState.current.scaleOffsetX)&&$e(this.animationState.target.scaleOffsetX)&&$e(this.animationState.current.scaleOffsetY)&&$e(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(ni(t.sx-e.sx,2)+ni(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,T,_,b,C,D,x,H,W;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:(_=(T=this.animationState.current)==null?void 0:T.scaleOffsetY)!=null?_:0,timestamp:Date.now()};this.animationState.target={sx:t/2,sy:o+n/2,cropWidth:t,cropHeight:e,scaleRatio:(C=(b=this.animationState.target)==null?void 0:b.scaleRatio)!=null?C:1,scaleOffsetX:(x=(D=this.animationState.target)==null?void 0:D.scaleOffsetX)!=null?x:0,scaleOffsetY:(W=(H=this.animationState.target)==null?void 0:H.scaleOffsetY)!=null?W:0,timestamp:Date.now()},this.animationState.animating||(this.animationState.target.scaleRatio=Math.sqrt(s*n/t/e/this.defaultScaleRatio),this.animationState.target.scaleOffsetX=-this.animationState.target.scaleRatio/2+.5,this.animationState.target.scaleOffsetY=-this.animationState.target.scaleRatio+1,(this.animationState.target.sy-this.animationState.target.scaleOffsetY*this.animationState.target.cropHeight)/this.animationState.target.scaleRatio<this.boundaryY&&(this.animationState.target.scaleOffsetY=(this.animationState.target.sy-this.boundaryY*this.animationState.target.scaleRatio)/this.animationState.target.cropHeight)),this.processFacePositionPortrait(a)}set aspectRatio(t){this.originalAspect=t}get current(){return this.animationState.current}get offset(){return{offsetX:this.totalOffsetX,offsetY:this.totalOffsetY}}get targetCrop(){return this.animationState.target}};var uv=`#version 300 es
105
+ ${o.stack}`),!1}},i};var Xn=new WeakMap;function RT(i){let t=Xn.get(i);t&&(t.forEach(e=>clearTimeout(e)),Xn.delete(i))}function vT(i,t){return xe((e,r)=>function(...o){let s=Xn.get(this);s||(s=new Map,Xn.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=Xn.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=Xn.get(this))==null||l.delete(n)},i);s.set(n,d)}})}var NT="trtc-sdk-v5",gf="5.15.0-wasm.2";function Gt(...i){return xe((t,e)=>function(...r){try{yl.call(this,i,r,e,this._name)}catch(o){return Promise.reject(o)}return t.apply(this,r)})}function Ef(...i){return xe((t,e)=>function(...r){try{yl.call(this,i,r,e,this._name)}catch(o){throw o}return t.apply(this,r)})}function yl(i,t,e,r){if(mt(i))for(let o=0;o<i.length;o++)Al.call(this,{rule:i[o],value:t[o],key:i[o].name,fnName:e,className:r});else Al.call(this,{rule:i,value:t[0],key:i.name,fnName:e,className:r})}function Al({rule:i,value:t,key:e,fnName:r,className:o}){function s(d){return{code:oe.INVALID_PARAMETER,extraCode:d,fnName:r,messageParams:{key:e,rule:i,value:t}}}if(O(t)){if(i.required)throw new ae(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),Me(i.type[l])&&gt(t)===i.type[l].toLowerCase()&&(d=!0);if(!d)throw new ae({code:oe.INVALID_PARAMETER,extraCode:5002,fnName:r,messageParams:{key:e,rule:{type:i.type.map(l=>cs(l)?dn(l):Me(l)?l:gt(l))},value:t}})}else if(!O(i.type)&&gt(t)!==i.type)throw new ae(s(5002));if(i.allowEmpty===!1){let d=$e(t)&&(t===0||Number.isNaN(t)),l=Me(t)&&t.trim()==="";if(d||l)throw new ae(s(5003))}if(i.notLessThanZero&&$e(t)&&t<0)throw new ae(s(5006));if(!O(i.min)&&$e(t)&&t<i.min)throw new ae(s(5007));if(!O(i.max)&&$e(t)&&t>i.max)throw new ae(s(5008));if(Me(i.instanceOf)){if(!t||t._name!==i.instanceOf)throw new ae(s(5004))}else if(Xe(i.instanceOf)&&!(t instanceof i.instanceOf))throw new ae(s(5004));if(Array.isArray(i.values)&&!i.values.includes(t))throw new ae(s(5005));let{properties:n}=i;Yt(n)&&fr(t)&&Object.keys(n).forEach(d=>{Al.call(this,{rule:n[d],value:t&&t[d],key:`${d}`,fnName:r,className:o})});let{arrayItem:a}=i;Yt(a)&&mt(t)&&t.forEach((d,l)=>{Al.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)}var KR=0;function nt(i={}){let{getRemoteId:t=()=>"",replaceArg:e,getKVReportKey:r,ignoreLog:o,ignoreErrorLog:s}=i;return xe((n,a)=>function(...d){var b,C,D;function l(x,H,W){if(W&&W.includes(x))return"hided";if(e){let ne=e(...d);if(d[ne.argIndex]===H)return ne.value}if(H===d||x in d)return H;try{return H instanceof HTMLElement?`id: ${H.id} type:${gt(H)}`:H instanceof MediaStreamTrack?Md(H):(JSON.stringify(H),H)}catch(ne){return`type:${gt(H)}`}}let p=(this==null?void 0:this._log)||F,f=++KR;if(o!=null&&o(...d))return n.apply(this,d);d.length>0?p.info(`${a}() ${f} ${JSON.stringify(d,(x,H)=>l(x,H,["userSig","privateMapKey"]))}`):p.info(`${a}() ${f}`);let T=r?r(...d):fu[a],_=(s==null?void 0:s(...d))||!1;try{let x=n.apply(this,d),H=fe();if(go(x)){let W=`${a.includes("Plugin")?`${((C=(b=d[0]).getName)==null?void 0:C.call(b))||""} `:" "}`;return x.then(ne=>(p.info(`${a}() success ${f} ${W}${t.call(this,...d)}`),z.addSuccessEvent({key:T,cost:fe()-H}),ne)).catch(ne=>{var Or;ne=ae.convertFrom.call(this,ne,a,d.length===1?d[0]:d);let Ve=ne.extraCode||ne.code,he=(Or=ne.message)!=null&&Or.includes(Ve)?"":` code:${Ve}`,Q=(ne==null?void 0:ne.code)===oe.OPERATION_ABORT;throw _||p[Q?"warn":"error"](`${a}() failed ${f} ${W}${t.call(this,...d)} ${ne}${he} params: ${JSON.stringify(d,l)}`),z.addFailedEvent({key:T,error:ne}),ne})}return z.addSuccessEvent({key:T}),x}catch(x){x=ae.convertFrom.call(this,x,a);let H=x.extraCode||x.code,W=(D=x.message)!=null&&D.includes(H)?"":` code:${H}`,ne=(x==null?void 0:x.code)===oe.OPERATION_ABORT;throw _||p[ne?"warn":"error"](`${a}() failed ${f} ${x}${W} params: ${JSON.stringify(d,l)}`),z.addFailedEvent({key:T,error:x}),x}})}var bl=i=>xe((t,e)=>function(r,o){return y(this,null,function*(){let s=this._plugins.get(r);if(!s)throw this._log.error(`plugin ${String(r)} is not found`),new ae({code:oe.OPERATION_ABORT,message:`plugin ${String(r)} is not found`,fnName:e});if(Xe(s.constructor.isSupported)&&!s.constructor.isSupported())throw this._log.error(`plugin ${String(r)} is not supported`),new ae({code:oe.ENV_NOT_SUPPORTED,message:`plugin ${String(r)} is not supported`,extraCode:5210,fnName:e});return yl.call(this,s.getValidateRule(i),[o],e,"TRTC"),t.call(this,s,o)})});var Rl=0,_f,Zi=class Zi{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");Rl=Rl+1,this.log=t.log.createChild({id:`${this.getAlias()}${Rl}`}),this.log.info(`created id=${this.getAlias()}${Rl}`),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 ae({code:oe.INVALID_OPERATION,extraCode:5106,fnName:o})}}}preload(t){return _f||(_f=this.doPreload(t)),_f}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 Zi.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(t){switch(t){case"start":return Zi.getStartValidateRule(this.core);case"update":return Zi.updateValidateRule;case"stop":return Zi.stopValidateRule}}start(t){return y(this,null,function*(){var T,_,b,C;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 ae({code:oe.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:D,status:x,timestamp:H}=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,H,D,x,e)}if(f&&!this.screenAudioWorkletNode){let{sign:D,status:x,timestamp:H}=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,H,D,x,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()),(T=this.localAudioWorkletNode)==null||T.port.postMessage({type:"enable"}),(_=this.screenAudioWorkletNode)==null||_.port.postMessage({type:"enable"}),e.audioManager.addAudioProcessor(this.mixNode,this.silentNode,this.localAudioWorkletNode,this.screenAudioWorkletNode),O(a)||a.forEach(D=>{this.customAudioReferenceMap.set(D,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:D,refId:`o-${this.audioRefId++}`})}),O(d)||(b=this.localAudioWorkletNode)==null||b.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:d}}),O(l)||(C=this.localAudioWorkletNode)==null||C.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 tv({sdkAppId:t,userSig:r,userId:e,timestamp:o});if(!s)throw this.log.info(`audioProcessor: ${e} auth result: ${s}. Message: ${d}`),new ae({code:oe.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 T=(p==null?void 0:p.value)>10?"info":"debug";this.log[T](`${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(Zi,"updateValidateRule",{type:"object"}),m(Zi,"stopValidateRule",{type:"object"}),m(Zi,"Name","AudioProcessor");var vl=Zi;function ev(i,t=M.MAIN){return`https://${Ti[t]||Sl(i,t)}/api/v1/audioAiAuth`}function tv(o){return y(this,arguments,function*({sdkAppId:i,userId:t,userSig:e,timestamp:r}){let n=`${ev(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 T=vr(i)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",_="Init RTCAudioProcessor failed.",b="";switch(d){case 1:b="Please check your params.";break;case 2:b=`You need to buy packages. Refer to: ${T}`;break;case 3:b="Server is invalid. Please contact our engineer. ";break;case 4:b=`Your packages is not active. Refer to: ${T}`;break;case 5:b=`Your packages is expired. Refer to: ${T}`;break;case 6:b="Your version is not supported.";break}return{auth:!1,status:f,message:l?`${_} Reason: ${l}. ${b}`:`${_}, ${b}`}})}var Cl=0,Tf=class{constructor(t,e){m(this,"audioObjectURL");m(this,"player");m(this,"publisher");m(this,"mixInput");this.mixInput=new Mn(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 Oc.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 Qn(i,t){if(t&&typeof t!="function")throw new ae({code:oe.INVALID_PARAMETER,message:`start audioMixer plugin: param ${i} should be a function.`})}var Ii=class Ii{constructor(t){this.core=t;m(this,"log");m(this,"mixedMusicMap",new Map);m(this,"cacheMusicMap",new Map);Cl=Cl+1,this.log=t.log.createChild({id:`${this.getAlias()}${Cl}`}),this.log.info(`created id=${this.getAlias()}${Cl}`)}getName(){return Ii.Name}getAlias(){return"ax"}getGroup(t){return t==null?void 0:t.id}getValidateRule(t){switch(t){case"start":return Ii.startValidateRule;case"update":return Ii.updateValidateRule;case"stop":return Ii.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 Tf(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.`),z.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(se.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&&z.addCount({key:502009}),r&&z.addCount({key:502001}),o&&z.addCount({key:502002}),s&&z.addCount({key:502003}),n&&z.addCount({key:502004}),a&&z.addCount({key:502005}),typeof d!="function"&&z.addCount({key:502007}),typeof p!="function"&&z.addCount({key:502008}),typeof l!="function"&&z.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(Ii,"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 ae({code:oe.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:r})}if(!t.url&&!t.track)throw new ae({code:oe.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:r});Qn("onTimeUpdate",t.onTimeUpdate),Qn("onEnded",t.onEnded),Qn("onDurationChange",t.onDurationChange)}}),m(Ii,"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){Qn("onTimeUpdate",t.onTimeUpdate),Qn("onEnded",t.onEnded),Qn("onDurationChange",t.onDurationChange)}}),m(Ii,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),m(Ii,"Name","AudioMixer");var Nl=Ii;var Dl=0,If,Ki=class Ki{constructor(t){this.core=t;m(this,"log");m(this,"audioContext",ze("denoiser"));m(this,"workletNode");m(this,"config",{enableFarFieldReduce:!1,farFieldReduceThreshold:.5});Dl=Dl+1,this.log=t.log.createChild({id:`${this.getAlias()}${Dl}`}),this.log.info(`created id=${this.getAlias()}${Dl}`)}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 ae({code:oe.INVALID_OPERATION,extraCode:5106,fnName:o})}}}preload(t){return If||(If=this.doPreload(t)),If}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 Ki.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser"}getValidateRule(t){switch(t){case"start":return Ki.startValidateRule(this.core);case"update":return Ki.updateValidateRule;case"stop":return Ki.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 ae({code:oe.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${Rh()?"":"-nosimd"}.js`),!this.workletNode){let s=String(Date.now()).slice(0,-3),{auth:n,sign:a,status:d,message:l}=yield iv(r,Ie(Y({},t),{timestamp:s}));if(!n)throw this.log.info(`RTCAIDenoiser: ${t.userId} auth result: ${n}. Message: ${l}`),new ae({code:oe.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 T;let{data:f}=p;if(f.type==="cost"){let _=(f==null?void 0:f.max)>20?"warn":(f==null?void 0:f.max)>10?"info":"debug";this.log[_](`avg cost: ${f.value} max: ${f==null?void 0:f.max}(${Ks(new Date(f==null?void 0:f.maxCostTimestamp))}) hist: ${(T=f==null?void 0:f.hist)==null?void 0:T.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(Ki,"updateValidateRule",{type:"object",properties:{mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}}}),m(Ki,"stopValidateRule",{type:"object"}),m(Ki,"Name","AIDenoiser");var wl=Ki;function iv(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=vr(t)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",T="Init RTCAIDenoiser failed.",_="";switch(a){case 1:_="Please check your params.";break;case 2:_=`You need to buy packages. Refer to: ${f}`;break;case 3:_="Server is invalid. Please contact our engineer. ";break;case 4:_=`Your packages is not active. Refer to: ${f}`;break;case 5:_=`Your packages is expired. Refer to: ${f}`;break;case 6:_="Your version is not supported.";break}return{auth:!1,status:p,message:d?`${T} Reason: ${d}. ${_}`:`${T}, ${_}`}}catch(a){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${a}`}}})}var wT=vi(ki(),1);var Sf=class extends wT.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){Fe.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){Fe.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:r})}}},ov=new Sf,Af=ov;var yf=0,Pc=class Pc{constructor(t){this.core=t;m(this,"log");m(this,"_seiMessageList",[]);m(this,"_smallSeiMessageList",[]);m(this,"_subStreamSeiMessageList",[]);yf++,this.log=t.log.createChild({id:`${this.getAlias()}${yf}`}),this.log.info(`[sei] created id=${this.getAlias()}${yf}`),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 pf({frame:t,seiMessageList:r})}catch(r){this.log.warn(r)}return t}decode({frame:t,track:e}){return ff({frame:t,onSEI:r=>{r.forEach(o=>{e!=null&&e.userId?this.core.trtc.emit(se.SEI_MESSAGE,{seiPayloadType:o.seiPayloadType,data:o.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"}):this.core.innerEmitter.emit(this.core.INNER_EVENT.SEI_MESSAGE,{room:this.core.room,nalu:o})})}})}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:Ss?this.encode:pf,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:Ss?this.decode:ff,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 Pc.Name}getAlias(){return"sei"}getGroup(){return"sei"}};m(Pc,"autoStart",!0),m(Pc,"Name","SEI");var Ml=Pc;var sv=0,Ol,xc=class xc{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()}${++sv}`}),this.log.info("created")}getName(){return xc.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(Ol)yield Ol;else{let e=new URLSearchParams(location.search).get("trtcDebugDialogPath")||((t=window.sessionStorage)==null?void 0:t.getItem("TRTC_DEBUG_DIALOG_PATH"))||`https://unpkg.com/${NT}@${ft}/assets/debug-dialog.js`;Ol=this._core.fileDownloader.loadScript(e),yield Ol}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(xc,"Name","Debug"),m(xc,"autoStart",!0);var Pl=xc;var MT=i=>{switch(i){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},xl=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=ye(e,me.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}`),be(l,Je(this.stopOB),Le(()=>{},p=>{e.log.error(p),o.addFailedEvent({key:MT(this.type),error:p}),d>4?this.startOB.error(p):this.startOB.next(d+1)})),be(l,ei(1),Np(fc))};be(this.startOB,hc(0),hi(a),Je(this.stopOB),Le(()=>{e.player.setOutput(),n.next("STARTED")},d=>{n.next("FAILED")},()=>{o.addSuccessEvent({key:MT(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"}))}},nv={type:"object"},Lc=class Lc{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 Lc.Name}getGroup(t){return t.track.userId+t.track.streamType}getName(){return Lc.Name}getValidateRule(t){return nv}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 xl(this.core,r,t);return be(o.trackDoneOB,ei(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 xl(this.core,t.track,t))}}};m(Lc,"Name","TRTCAudioDecoder");var kc=Lc;var Ll=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 ce({code:q.INVALID_PARAMETER,message:je({key:Ge.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 T=d.getPCM(_=>{e.emit(se.AUDIO_FRAME,_)},f.userId);l.set(f.userId,T)}});else{if(l.get(o))return;let f=d.getPCM(T=>{e.emit(se.AUDIO_FRAME,T)},o);l.set(o,f)}else if(o==="*")e.room.remotePublishedUserMap.forEach(f=>{if(f.remoteAudioTrack.isSubscribed){let{userId:T}=f,_=l.get(T);_==null||_.abort("disable"),l.delete(T)}});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(!1)):s.isAvailable&&s.player.pause(!1):(r.isAvailable&&r.player.pause(),o.isAvailable&&o.player.pause(!1),s.isAvailable&&s.player.pause(!1))});else{let e=t.trtcInstance.room.remotePublishedUserMap.get(t.userId);e&&(t.streamType==="main"?(e.remoteAudioTrack.player.pause(),e.remoteVideoTrack.player.pause(!1)):e.remoteAuxiliaryTrack.player.pause(!1))}}};Z([d_({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"}}})],Ll.prototype,"enableAudioFrameEvent",1);var OT=new Ll;var PT=vi(ki(),1);var bf=class extends PT.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={}}},Uc=new bf;var xT=0,Vc=new Set,Ft=null;lm(gf);Rn.checkStorage();var Ee=class Ee extends LT.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${++xT}`}));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:Ee.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(Nl,r.assetsPath),this._use(vl,r.assetsPath),this._use(wl,r.assetsPath),this._use(kc,r.assetsPath),this._use(Pl),r.enableSEI&&Qa&&this._use(Ml),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(se.AUDIO_VOLUME,{result:o.sort((a,d)=>d.volume-a.volume)})}),this._room.videoManager.on("error",o=>{this._log.error(new ae({code:oe.OPERATION_FAILED,extraCode:5504,message:o.message,originError:o}))}),this._listenEvents(),this._initActiveSpeaker(),bT(this,"trtc")}static create(e){}static _create(e,r){iT();let o=new Ee(e,r||{});return Vc.add(o),o.__v_skip=!0,o}get room(){return this._room}_listenEvents(){$t(this,this._room).add("peer-join",e=>{let{userId:r}=e;this.emit(se.REMOTE_USER_ENTER,{userId:r})}).add("peer-leave",({userId:e,reason:r})=>{this.emit(se.REMOTE_USER_EXIT,{userId:e,reason:r})}).add("banned",e=>{Yi(!0),this._exitRoom().finally(()=>{this.emit(se.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().finally(()=>{this.emit(se.ERROR,ae.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(se.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let r=Ie(Y({},e),{uplinkRTT:Math.min(e.uplinkRTT,_a),downlinkRTT:Math.min(e.downlinkRTT,_a)});this.emit(se.NETWORK_QUALITY,r)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(o=>{$t(o,o).add("player-state-changed",s=>{let n=Ie(Y({},s),{userId:e.userId});o.kind===M.VIDEO&&(n.streamType=_i(o.streamType)),this.emit(o.kind===M.AUDIO?se.AUDIO_PLAY_STATE_CHANGED:se.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",s=>{s.getCode()===q.PLAY_NOT_ALLOWED&&this.emit(se.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?se.REMOTE_VIDEO_AVAILABLE:se.REMOTE_VIDEO_UNAVAILABLE,{userId:o,streamType:"main"})),s!==a&&(a?this._onAudioAvailable({userId:o}):this._onAudioUnavailable({userId:o,muteState:r}),this.emit(a?se.REMOTE_AUDIO_AVAILABLE:se.REMOTE_AUDIO_UNAVAILABLE,{userId:o})),e.hasAuxiliary!==r.hasAuxiliary&&(r.hasAuxiliary?this._onVideoAvailable({userId:o,streamType:"sub"}):this._onVideoUnavailable({userId:o,streamType:"sub"}),this.emit(r.hasAuxiliary?se.REMOTE_VIDEO_AVAILABLE:se.REMOTE_VIDEO_UNAVAILABLE,{userId:o,streamType:"sub"}))}).add("sei-message",e=>{this.emit(se.SEI_MESSAGE,Ie(Y({},e),{streamType:_i(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(se.ERROR,new ae({code:oe.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,_a),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(T=>r[T.uint32_video_stream_type]).map(T=>({bitrate:(T.uint32_video_codec_bitrate||0)/1e3,width:T.uint32_video_width,height:T.uint32_video_height,frameRate:T.uint32_video_enc_fps,videoType:r[T.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(T=>({userId:T.msg_user_info.str_identifier,audio:{bitrate:(T.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(T.msg_audio_status.uint32_audio_level||0)/Fi,point2pointDelay:(T.msg_audio_status.uint32_audio_p2p_delay||0)+(T.msg_audio_status.uint32_audio_cache_ms||0),jitterBufferDelay:T.msg_audio_status.uint32_audio_cache_ms||0},video:T.msg_video_status.map(_=>({bitrate:(_.uint32_video_codec_bitrate||0)/1e3,width:_.uint32_video_width,height:_.uint32_video_height,frameRate:_.uint32_video_dec_fps,videoType:r[_.uint32_video_stream_type],point2pointDelay:(_.uint32_video_p2p_delay||0)+(_.uint32_video_cache_ms||0),jitterBufferDelay:_.uint32_video_cache_ms||0,codec:_.uint32_video_codec}))}))};this.emit(se.STATISTICS,o)}).add("custom-message",e=>{this.emit(se.CUSTOM_MESSAGE,e)}).add("layerData",e=>this.emit(se.LAYER_DATA,e)).add("first-video-frame",e=>{this.emit(se.FIRST_VIDEO_FRAME,Ie(Y({},e),{streamType:_i(e.streamType)}))}).add("audio-frame",e=>{this.emit(se.AUDIO_FRAME,e)}),$t(this,dt).add("audioInputAdded",e=>{this.emit(se.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(se.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(se.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(se.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>y(this,null,function*(){if(this.emit(se.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Ft&&Ft.deviceId===Ea){let r=(yield Do()).find(o=>o.deviceId===Ea);r&&Ft.groupId!==r.groupId&&(Ft=r,this.emit(se.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}))}})).add("audioOutputRemoved",e=>y(this,null,function*(){this.emit(se.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let r=(yield Do())[0];if(!r||!Ft||Ft.groupId===r.groupId)return;let o=Ft.deviceId===e.deviceId,s=Ft.deviceId===Ea&&Ft.deviceId===r.deviceId;(o||s)&&(Ft=r,this.emit(se.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}))})),$t(this,Uc).add("permission-state-change",e=>{this.emit(se.PERMISSION_STATE_CHANGE,e)}),this.room.enableSEI&&this.on(se.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 Ci()}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(yT.call(this,{TRTC:Ee,room:this._room,assetsPath:r,errorModule:{RtcError:ae,ErrorCode:oe,CoreErrorCode:q,ErrorCodeDictionary:Sr}}));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),!Me(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,Ee.frameWorkType),this._checkTrackToPublish(),Af.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 ma&&(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(),RT(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(),Vc.delete(this),Vc.size===0&&Af.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 pi(this._room.audioManager),a={},d={muted:!0};s&&(O(s.microphoneId)?O(s.audioTrack)||(a.customSource=s.audioTrack):a.deviceId=s.microphoneId,s&&$e(s.captureVolume)&&n.setCaptureVolume(s.captureVolume),O(s.profile)||(Me(s.profile)?gd[s.profile]&&n.setProfile(gd[s.profile]):n.setProfile(s.profile)),$e(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(se.ERROR,new ae({code:oe.DEVICE_ERROR,extraCode:5309,messageParams:{error:l}}))}),n.on("2",l=>{this.emit(se.DEVICE_CHANGED,{type:"microphone",action:"active",device:l})}),n.on("4",l=>{let p;l.error&&(p=ae.convertFrom(l.error)),this.emit(se.PUBLISH_STATE_CHANGED,Ie(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),$t(n,n).add("player-state-changed",l=>{this.emit(se.AUDIO_PLAY_STATE_CHANGED,Ie(Y({},l),{userId:""}))}),r&&this._room.isJoined&&this._room.publish(n).catch(()=>{}),this._localAudioTrack=n,this._localAudioConfig=Ie(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}),$r(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 Ir(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=wc(a.qosPreference)),O(a.profile)||(Me(a.profile)?Fr[a.profile]&&d.setProfile(Fr[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(qn(a.small,!0))),O(a.rotation)||d.setRotation(a.rotation),Ye(this._enableAutoSwitchWhenRecapturing)&&(d.enableAutoSwitchWhenRecapturing=this._enableAutoSwitchWhenRecapturing)),d.once("first-video-frame",T=>{this.emit(se.FIRST_VIDEO_FRAME,Ie(Y({},T),{streamType:_i(T.streamType)}))}),d.on("5",T=>{this.emit(se.ERROR,new ae({code:oe.DEVICE_ERROR,extraCode:5308,messageParams:{error:T}}))}),d.on("2",T=>{this.emit(se.DEVICE_CHANGED,{type:"camera",action:"active",device:T})}),d.on("4",T=>{let _;T.error&&(_=ae.convertFrom(T.error)),this.emit(se.PUBLISH_STATE_CHANGED,Ie(Y({},T),{error:_}))}),d.on("6",()=>{}),this._listenOutputTrackChanged(d),s?yield d.capture(l):(f=d.manager)==null||f.changeInput(d),O(n)||(yield d.setMute(n)),$t(d,d).add("player-state-changed",T=>{this.emit(se.VIDEO_PLAY_STATE_CHANGED,Ie(Y({},T),{userId:"",streamType:"main"}))}).add("video-size-changed",T=>{this.emit(se.VIDEO_SIZE_CHANGED,Ie(Y({},T),{streamType:_i(T.streamType)}))}),o&&this._room.isJoined&&this._room.publish(d).catch(()=>{}),this._localVideoTrack=d,this._localVideoConfig=Ie(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 T={};T.deviceId=(a==null?void 0:a.cameraId)||((l=this._localVideoConfig.option)==null?void 0:l.cameraId),T.facingMode=a!=null&&a.useFrontCamera||(p=this._localVideoConfig.option)!=null&&p.useFrontCamera?M.FACING_MODE_USER:M.FACING_MODE_ENVIRONMENT,T.customSource=(a==null?void 0:a.videoTrack)||((f=this._localVideoConfig.option)==null?void 0:f.videoTrack),yield this._localVideoTrack.capture(T)}a&&(O(a.profile)||(Me(a.profile)?Fr[a.profile]&&this._localVideoTrack.setProfile(Fr[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(wc(a.qosPreference)),O(a.small)||(Ye(a.small)&&!a.small?this._localVideoTrack.stopSmall():this._localVideoTrack.updateSmallConfig(qn(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}),$r(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 T,_;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 fi(this._room.videoManager);a.on("4",b=>{let C;b.error&&(C=ae.convertFrom(b.error)),this.emit(se.PUBLISH_STATE_CHANGED,Ie(Y({},b),{error:C}))}),a.once("first-video-frame",b=>{this.emit(se.FIRST_VIDEO_FRAME,Ie(Y({},b),{streamType:_i(b.streamType)}))}),this._listenOutputTrackChanged(a),e.streamType==="main"&&(a.mediaType=4);let d=null,l={},p={};n&&(O(n.profile)||(Me(n.profile)?Ed[n.profile]&&a.setProfile(Ed[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=wc(n.qosPreference)));let f=yield a.capture(l);if(a.mediaTrack.addEventListener(M.ENDED,()=>{this._stopScreenShare(),this.emit(se.SCREEN_SHARE_STOPPED)}),f.getAudioTracks()[0]){d=new Ls(this._room.audioManager);let b=f.getAudioTracks()[0];(T=e.option)!=null&&T.systemAudio&&!((_=e.option)!=null&&_.audioTrack)&&(d.sourceTrack=b),yield d.setInputMediaStreamTrack(b),Ye(s)&&d.mediaTrack&&(d.mediaTrack.enabled=!s),this._speakerId&&d.setAudioOutput(this._speakerId)}if($t(a,a).add("player-state-changed",b=>{this.emit(se.VIDEO_PLAY_STATE_CHANGED,Ie(Y({},b),{userId:"",streamType:"sub"}))}),o&&this._room.isJoined){let b=[a];d&&(b.push(d),this._checkScreenAudioEchoCancellation(a,d)),b.forEach(C=>this._room.publish(C).catch(()=>{}))}this._localScreenTrack=a,this._localScreenAudioTrack=d,this._localScreenConfig=Ie(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=wc(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}),$r(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(se.ERROR,new ae({code:oe.OPERATION_FAILED,extraCode:5507,message:"video decode failed"}))}),p.on("video-size-changed",f=>{this.emit(se.VIDEO_SIZE_CHANGED,Ie(Y({},f),{streamType:_i(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 x,H;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,T=this._room.remotePublishedUserMap.get(o);if(s==="main"&&(T!=null&&T.muteState.hasVideo)&&(f=T.remoteVideoTrack),s==="sub"&&(T!=null&&T.muteState.hasAuxiliary)&&(f=T.remoteAuxiliaryTrack),!f)return;let{config:_}=l;s==="main"&&n&&!O(n.small)&&this._room.changeType(n.small,f.user),n&&!O(n.draggable)&&f.setDraggable(n.draggable),n&&(Ye(n.pictureInPicture)&&(n.pictureInPicture?yield f.player.enterPictureInPicture():yield f.player.exitPictureInPicture()),Ye(n.fullScreen)&&(n.fullScreen?yield f.player.enterFullscreen():yield f.player.exitFullscreen())),Ye(a)&&(f.ignoreUpdatePlayingState=!0,a?(yield f.player.pause(),yield this.room.unsubscribe(f)):(yield this.room.subscribe(f),yield f.player.resume(!0))),yield this._updateVideoPlayOption({view:r,playOption:p,track:f,prevConfig:_}),$r(_,e);let b=O(n==null?void 0:n.receiveWhenViewVisible)?(x=_.option)==null?void 0:x.receiveWhenViewVisible:n.receiveWhenViewVisible,C=O(r)?_.view:r,D=O(n==null?void 0:n.viewRoot)?(H=_.option)==null?void 0:H.viewRoot:n.viewRoot;this._observeView({remoteTrack:f,view:C,receiveWhenViewVisible:b,viewRoot:D})})}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)&&this.room.isJoined&&(yield this._startRemoteAudio({userId:s.userId}))}else r?yield this._stopRemoteAudio({userId:e}):!this._remoteAudioConfigMap.has(e)&&this.room.isJoined&&(yield this._startRemoteAudio({userId:e}))}catch(o){throw o.code!==oe.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(se.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{pT.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===Ee.EVENT.AUDIO_FRAME||e==="*")&&this.listeners(Ee.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(Me(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 Do()).forEach(o=>{o.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(se.DEVICE_CHANGED,{type:"speaker",action:"active",device:o}),Ft=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: ${sr}/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(se.ERROR,new ae({code:oe.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=$e(d)?d:100;s.volume=l,this._remoteAudioConfigMap.set(r,e),yield this._room.subscribe(n),be(ye(n,"decode-failed"),Je(ye(n,me.INIT)),Le(()=>{this.startPlugin(kc.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;be(ye(e,"decode-failed"),Je(ye(e,me.INIT)),ws(()=>{this._room.downlinkVideoCodec!=="h265"&&this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:o})}),qi(ye(e,"decode-downgrade-state-changed")),Le(n=>{s=n.state,this.emit(se.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,Ie(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 pi&&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 Ji){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(se.TRACK,{userId:o,streamType:_i(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}_${_i(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(T=>{T.forEach(_=>{l.set(_.target,_.isIntersecting),e.log.info(`view ${_.target.id} is${_.isIntersecting?"":" not"} visible`)}),clearTimeout(p),p=window.setTimeout(()=>{[...l.values()].find(b=>b)?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((T,_)=>{f.has(_)||(a.unobserve(_),l.delete(_))}),f.forEach(T=>{l.set(T,!0),a.observe(T)}),a.takeRecords().forEach(T=>{l.set(T.target,T.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"&&(!Ft||Pn(Ft))&&(this._initActiveSpeaker(),U.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return y(this,null,function*(){if(Ft&&!Pn(Ft))this.emit(se.DEVICE_CHANGED,{type:"speaker",action:"active",device:Ft});else{let e=yield Do();e[0]&&!Pn(e[0])?(Ft=e[0],this.emit(se.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:Ie(Y({seiPayloadType:243},r),{small:!!((s=this._localVideoTrack)!=null&&s.small)})}),z.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var r,o;(o=(r=this._room).sendCustomMessage)==null||o.call(r,e),z.addCount({key:500001,useUV:!0})}callExperimentalAPI(e,r){return y(this,null,function*(){return this._log.info(`callExperimentalAPI(${e}, ${JSON.stringify(r)})`),OT.call(e,Y({trtcInstance:this},r))})}static setLogLevel(e,r){F.setLogLevel(e),O(r)||(r?F.enableUploadLog():F.disableUploadLog())}static isSupported(){return Iu(Ee.frameWorkType)}static getPermissions(o){return y(this,arguments,function*({request:e=!0,types:r=["camera","microphone"]}){e&&(yield Uc.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([Uc.get("camera"),Uc.get("microphone")]);return{camera:s,microphone:n}})}static getCameraList(e=!0){return ur(e)}static getMicrophoneList(e=!0){return dr(e)}static getSpeakerList(e=!0){return Do(e)}static setCurrentSpeaker(e){return y(this,null,function*(){if(at&&(e===Vs.SPEAKER||e===Vs.HEADSET)){let o=yield Ee.getMicrophoneList(),s="";if(o.forEach(n=>{n.label===e&&(s=n.deviceId)}),!s)return;Vc.forEach(n=>y(this,null,function*(){n._localAudioTrack&&(yield n.updateLocalAudio({option:{microphoneId:s}}))}));return}(yield Do()).forEach(o=>{o.deviceId===e&&(Vc.forEach(s=>{s._setCurrentSpeaker(e),s.emit(se.DEVICE_CHANGED,{type:"speaker",action:"active",device:o})}),Ft=o)})})}static _addKVStat({type:e,key:r,value:o,base:s,useUV:n,version:a,max:d}){switch(a&&(Is.version=a),e){case"count":Is.addCount({key:r,useUV:n});break;case"enum":Is.addEnum({key:r,value:o,useUV:n});break;case"number":Is.addNumber({key:r,value:o,split:s,max:d});break}}};m(Ee,"VERSION",gf),m(Ee,"_loggerManager",F),m(Ee,"EVENT",se),m(Ee,"ERROR_CODE",oe),m(Ee,"TYPE",Vs),m(Ee,"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"}})})],Ee.prototype,"use",1),Z([Gt(Ot.TRTC.enterRoom),Fo("room",([e],[r])=>(e.roomId||e.strRoomId)===(r.roomId||r.strRoomId)&&e.userId===r.userId&&e.sdkAppId===r.sdkAppId),xe(e=>function(r){return this._log.setUserId(r.userId),this._log.setSdkAppId(r.sdkAppId),e.call(this,r)}),nt()],Ee.prototype,"enterRoom",1),Z([nt()],Ee.prototype,"exitRoom",1),Z([Gt(Ot.TRTC.switchRoom),nt(),Lu()],Ee.prototype,"switchRoom",1),Z([Gt(Ot.TRTC.switchRole),Bs("room",{merge:(e,r)=>r}),nt()],Ee.prototype,"switchRole",1),Z([nt()],Ee.prototype,"destroy",1),Z([Gt(Ot.TRTC.startLocalAudio),Fo("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()],Ee.prototype,"startLocalAudio",1),Z([Gt(Ot.TRTC.updateLocalAudio),Bs("audio",{debounce:{delay:200,getKey:()=>`${xT}-localAudio`,isNeedToDebounce:e=>{var r;return!O((r=e.option)==null?void 0:r.captureVolume)}}}),nt()],Ee.prototype,"updateLocalAudio",1),Z([Bo("audio"),nt()],Ee.prototype,"stopLocalAudio",1),Z([Gt(Ot.TRTC.startLocalVideo),Fo("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()],Ee.prototype,"startLocalVideo",1),Z([Gt(Ot.TRTC.updateLocalVideo),Bs("video"),nt()],Ee.prototype,"updateLocalVideo",1),Z([Bo("video"),nt()],Ee.prototype,"stopLocalVideo",1),Z([Gt(Ot.TRTC.startScreenShare),Fo("screen",()=>!0),nt()],Ee.prototype,"startScreenShare",1),Z([Gt(Ot.TRTC.updateScreenShare),Bs("screen"),nt()],Ee.prototype,"updateScreenShare",1),Z([nt()],Ee.prototype,"stopScreenShare",1),Z([Gt(Ot.TRTC.startRemoteVideo),Fo(e=>`v${e.userId}${e.streamType}`,()=>!0),nt({getRemoteId:e=>`${e.userId}_${e.streamType}`})],Ee.prototype,"startRemoteVideo",1),Z([Gt(Ot.TRTC.updateRemoteVideo),Bs(e=>`v${e.userId}${e.streamType}`),nt({getRemoteId:e=>`${e.userId}_${e.streamType}`})],Ee.prototype,"updateRemoteVideo",1),Z([Gt(Ot.TRTC.stopRemoteVideo),xe(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}`})],Ee.prototype,"stopRemoteVideo",1),Z([Bo(e=>`v${e.userId}${e.streamType}`)],Ee.prototype,"_stopRemoteVideo",1),Z([Gt(...Ot.TRTC.muteRemoteAudio),nt({getRemoteId:e=>e})],Ee.prototype,"muteRemoteAudio",1),Z([Ef(...Ot.TRTC.setRemoteAudioVolume),vT(200,e=>e),nt({getRemoteId:e=>e})],Ee.prototype,"setRemoteAudioVolume",1),Z([bl("start"),wo(e=>{var r;return(r=e.afterStart)==null?void 0:r.call(e)}),Fo((e,r)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(r)),nt({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>ph[e.getName()],ignoreLog:e=>e.getName()==="Debug",ignoreErrorLog:e=>e.getName()==="AudioProcessor"})],Ee.prototype,"startPlugin",1),Z([bl("update"),Bs((e,r)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(r),{merge:(e,r)=>($r(e[1],r[1]),e)}),nt({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>fh[e.getName()]})],Ee.prototype,"updatePlugin",1),Z([bl("stop"),Bo((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=>gh[e.getName()]})],Ee.prototype,"stopPlugin",1),Z([Ef(...Ot.TRTC.enableAudioVolumeEvaluation)],Ee.prototype,"enableAudioVolumeEvaluation",1),Z([nt()],Ee.prototype,"getVideoSnapshot",1),Z([nt()],Ee.prototype,"_setCurrentSpeaker",1),Z([Fo(e=>`a${e.userId}`,()=>!0)],Ee.prototype,"_startRemoteAudio",1),Z([xe(e=>function(r){return y(this,null,function*(){return r.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(o=>this._stopRemoteAudio(Ie(Y({},r),{userId:o.userId})).catch(()=>{}))):e.call(this,r)})}),Bo(e=>`a${e.userId}`)],Ee.prototype,"_stopRemoteAudio",1),Z([Bo("room")],Ee.prototype,"_exitRoom",1),Z([Bo("screen")],Ee.prototype,"_stopScreenShare",1),Z([Gt(...Ot.TRTC.sendSEIMessage),sf({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...e)=>e[0].byteLength})],Ee.prototype,"sendSEIMessage",1),Z([Gt(Ot.TRTC.sendCustomMessage),sf({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],Ee.prototype,"sendCustomMessage",1),Z([$o()],Ee,"create",1),Z([Gt(Ot.TRTC.create)],Ee,"_create",1),Z([$o()],Ee,"setLogLevel",1),Z([$o()],Ee,"isSupported",1),Z([$o(),nt()],Ee,"getPermissions",1),Z([$o()],Ee,"getCameraList",1),Z([$o()],Ee,"getMicrophoneList",1),Z([$o()],Ee,"getSpeakerList",1);var Rf=Ee,Yn=Rf;var kl=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 Ji(t,this),this.remoteVideoTrack=new Lo(t,this),this.remoteAuxiliaryTrack=new al(t,this),this.flag=e.flag||0}get subscribeState(){let t={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(this.remoteVideoTrack.mediaType&8?t.smallVideo=!0:t.video=!0),this.remoteAudioTrack.isSubscribed&&(t.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(t.auxiliary=!0),t}get muteState(){return ds(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 vf=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 av(){return y(this,null,function*(){let i,t;try{let _=yield dr();i=_&&_.length}catch(_){}try{let _=yield ur();t=_&&_.length}catch(_){}let e={microphone:i,camera:t},{isH264EncodeSupported:r,isVp8EncodeSupported:o,isH264DecodeSupported:s,isVp8DecodeSupported:n,isH265EncodeSupported:a,isH265DecodeSupported:d}=this.checkSystemResult.detail,l=vo.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},T={isWebCodecSupported:l.isWebCodecSupported,isMediaSessionSupported:l.isMediaSessionSupported,isWebTransportSupported:l.isWebTransportSupported};Fe.uploadEvent({log:`trtcstats-${JSON.stringify(f)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(f)}`),Fe.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(T)}`,userId:this.userId}),Ch()})}function kT(){return xe(i=>{let t=new vf;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 ce({code:q.INVALID_OPERATION,message:je({key:Ge.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:s,sdkAppId:this.sdkAppId,room:this}))throw new ce({code:q.INVALID_OPERATION,message:je({key:Ge.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=di.getEnv();n||(n=Ni.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(_d.OLD_CLOUD_LADDER)?n=Ni.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(_d.WEBRTC)&&(n=Ni.WEBRTC))),Fe.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:s}),vo.checkSystemRequirementsInternal(o).then(a=>{this.checkSystemResult=a,av.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!di.getEnv()&&(yield this.schedule(e,o));let a=yield i.call(this,e,r,o);return this.roomId=s,this._joinedTimestamp=di.performanceNow(),U.emit(B.JOIN_SUCCESS,{room:this}),o===30&&!e.component&&Fe.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 UT=()=>xe(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 xe(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 FT(){return xe(i=>function(...t){let e=i.apply(this,t);return t.forEach(r=>r.unpublish()),e})}function BT(){return xe(i=>function(...t){let e=i.apply(this,t);return t.forEach(r=>!r.isSubscribed&&r.subscribe(e)),e})}function cv({fn:i,context:t}){return function(...e){try{let r=i.apply(t,e);return go(r)?r.catch(o=>F.error(`${i.name}() error observed ${o}`)):r}catch(r){F.error(`${i.name}() error observed ${r}`)}}}var Ul=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]=cv({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:ft,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,fs().then(()=>{this._basicInfo.string_os_version=Li(),this._basicInfo.string_device_name=gs()||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(),ht.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 ce?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=fe()-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 ce?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:Ie(Y({},dv),{msg_user_info:new Fc({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 Fc({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,z.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(T=>{let _=T.uint32_video_stream_type===2,b=T.uint32_video_stream_type===7,C=`${p}_${_?"main":"auxiliary"}`,D=this._remoteStreamStatMap.get(C);if(D&&(_&&(f!=null&&f.remoteVideoTrack.isSubscribed)||b&&(f!=null&&f.remoteAuxiliaryTrack))){D.totalVideoFPS+=T.uint32_video_receive_fps,D.totalVideoBitrate+=T.uint32_video_codec_bitrate,D.videoCount++,D.statsToReport.uint32_video_width===0&&(D.statsToReport.uint32_video_width=T.uint32_video_width),D.statsToReport.uint32_video_height===0&&(D.statsToReport.uint32_video_height=T.uint32_video_height);let x=_?f.remoteVideoTrack:f.remoteAuxiliaryTrack;x.stat.jitterBufferDelay&&(D.videoJitterBufferDelay=x.stat.jitterBufferDelay),x.stat.framesReceived&&(D.statsToReport.uint32_video_consume_render_rate=Math.floor(x.stat.framesDecoded/x.stat.framesReceived*ni(10,6)))}}),!un(d)){let T=`${p}_main`,_=this._remoteStreamStatMap.get(T);this._remoteStreamStatMap.has(T)&&_&&f!=null&&f.remoteAudioTrack.isSubscribed&&(_.totalAudioBitrate+=d.uint32_audio_codec_bitrate,_.audioCount++,f.remoteAudioTrack.stat.jitterBufferDelay&&(_.audioJitterBufferDelay=f.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(d.uint32_audio_level/Fi*100)>0&&(_.totalAudioLevel+=d.uint32_audio_level/Fi,_.audioLevelCount++),d.uint32_audio_block_time&&(_.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 ce?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&ga)>=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:T,videoDelayCount:_,totalAudioDelay:b,totalVideoDelay:C}=o;t.statsToReport.uint32_avg_down_loss=Math.floor(p/f),T&&b&&(t.statsToReport.uint32_audio_network_p2p_delay=Math.floor(b/T),t.audioJitterBufferDelay&&(t.statsToReport.uint32_p2p_delay=Math.floor(t.statsToReport.uint32_audio_network_p2p_delay+t.audioJitterBufferDelay))),_&&C&&(t.statsToReport.uint32_video_network_p2p_delay=Math.floor(C/_))}t.videoCount>0&&(t.statsToReport.uint32_video_avg_fps=Math.floor(t.totalVideoFPS/t.videoCount),t.statsToReport.uint32_video_avg_bitrate=Math.floor(t.totalVideoBitrate/t.videoCount)),t.audioCount>0&&(t.statsToReport.uint32_audio_recv_bitrate=t.statsToReport.uint32_audio_bitrate=Math.floor(t.totalAudioBitrate/t.audioCount)),t.audioLevelCount>0&&(t.statsToReport.uint32_audio_play_db=Math.floor(t.totalAudioLevel/t.audioLevelCount*100));let{callDurationCalculator:s}=this._room;s&&(t.statsToReport.uint32_audio_play_time=s.getDuration(e,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=Cd();let t={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new Fc({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()*ni(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 ya(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=So.enable?Mi(t,2001,e):yield Pm(t),o=r instanceof ArrayBuffer,s=`${wi(e,po.KEY_POINT)}&gzip=${+o}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(s,r));let a=[this.uploadKVStat(z),this.uploadKVStat(Is)];n||a.push(Oi({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=Ie(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=So.enable?Mi(e,2003,this._room.sdkAppId):yield Pm(e),o=r instanceof ArrayBuffer,s=`${wi(+this._room.sdkAppId,po.KV_STAT)}&gzip=${+o}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(s,r)),n||Oi({url:s,body:r})})}};Z([ys({settings:{timeout:500,retries:3}})],Ul.prototype,"upload",1);var $s=5e3,dv={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},Fc=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}},$T=Ul;var Cf=class{constructor(){m(this,"_startTime");m(this,"_endTime");this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=fe())}stop(){this._endTime===0&&(this._endTime=fe())}getDuration(){return this._endTime===0?fe()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},Vl=Cf;var Nf=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 Vl,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()}},HT=Nf;var Df=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||st)&&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()}},wf=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 Df);m(this,"_eventMap",new Map);m(this,"_videoEncodeFailedCount",0);m(this,"_audioEncodeFailedCount",0);m(this,"_encodeFailedThreshold",3);m(this,"ABNORMAL_TIME_LOWER_LIMIT",3e3);m(this,"ABNORMAL_TIME_UPPER_LIMIT",5e3);m(this,"_videoAbnormalTimestampMap",new Map);m(this,"_remoteVideoAbnormalTimestampMap",new Map);m(this,"_audioAbnormalTimestampMap",new Map);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 Vl;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}){this.hitTest(t)&&(this.localMediaTrackDetector(e),this.remoteMediaTrackDetector(e))}remoteMediaTrackDetector(t){t.msg_down_stream_info.length>0&&t.msg_down_stream_info.forEach(e=>{var s;if(e.msg_video_status.length===0)return;let r=e.msg_user_info.str_identifier,o=(s=this._room.remotePublishedUserMap.get(r))==null?void 0:s.remoteVideoTrack;e.msg_video_status.forEach(n=>{let a=fe();if(n.uint32_video_codec_bitrate!==void 0&&n.uint32_video_codec_bitrate>0&&n.uint32_video_receive_fps===0&&(o!=null&&o.muted))if(!this._remoteVideoAbnormalTimestampMap.has(`${r}-decode`))this._remoteVideoAbnormalTimestampMap.set(`${r}-decode`,a);else{let d=this._remoteVideoAbnormalTimestampMap.get(`${r}-decode`);d&&a-d>this.ABNORMAL_TIME_LOWER_LIMIT&&a-d<this.ABNORMAL_TIME_UPPER_LIMIT&&Fe.uploadEvent({userId:this._room.userId,log:`stat-${Lt.VIDEO_DECODE_FAILED_DURING_CALL}`})}else{let d=this._remoteVideoAbnormalTimestampMap.get(`${r}-decode`);d&&a-d>=this.ABNORMAL_TIME_UPPER_LIMIT&&(Fe.uploadEvent({userId:this._room.userId,log:`stat-${Lt.VIDEO_DECODE_RESUME_DURING_CALL}`}),this._remoteVideoAbnormalTimestampMap.delete(`${r}-decode`))}if(n.uint32_video_codec_bitrate!==void 0&&n.uint32_video_codec_bitrate>5e5&&n.uint32_video_dec_fps!==void 0&&n.uint32_video_dec_fps<=5)if(!this._remoteVideoAbnormalTimestampMap.has(`${r}-hardware`))this._remoteVideoAbnormalTimestampMap.set(`${r}-hardware`,a);else{let d=this._remoteVideoAbnormalTimestampMap.get(`${r}-hardware`);if(d&&a-d>this.ABNORMAL_TIME_LOWER_LIMIT/2&&a-d<this.ABNORMAL_TIME_UPPER_LIMIT*2){Fe.uploadEvent({userId:this._room.userId,log:`stat-${Lt.VIDEO_HARDWARE_DECODE_FAILED}`});let l=this._room.remotePublishedUserMap.get(r);if(l){let p=n.uint32_video_stream_type===2?l.remoteVideoTrack:l.remoteAuxiliaryTrack;p&&(p.log.warn("decode failed during call"),p.emit("decode-failed-during-call"))}}}else{let d=this._remoteVideoAbnormalTimestampMap.get(`${r}-hardware`);d&&a-d>=this.ABNORMAL_TIME_UPPER_LIMIT*2&&(Fe.uploadEvent({userId:this._room.userId,log:`stat-${Lt.VIDEO_HARDWARE_DECODE_RESUME}`}),this._remoteVideoAbnormalTimestampMap.delete(`${r}-hardware`))}})})}localMediaTrackDetector(t){if(t.msg_up_stream_info.msg_video_status){let e=t.msg_up_stream_info.msg_video_status,r=Array.from(this._room.localTracks).find(s=>s.kind==="video"&&!s.isScreen),o=(r==null?void 0:r.stat.bytesSent)||0;if((r==null?void 0:r.isMediaTrackActive)===!1||o<=0||r!=null&&r.isUseCustomSource)return;e.forEach(s=>{let n=fe();if(s.uint32_video_stream_type===2)if(s.uint32_video_capture_fps!==0&&s.uint32_video_codec_bitrate===0&&s.uint32_video_enc_fps===0&&(r!=null&&r.isPublished))if(!this._videoAbnormalTimestampMap.has("local-encode"))this._videoAbnormalTimestampMap.set("local-encode",n);else{let a=this._videoAbnormalTimestampMap.get("local-encode");a&&n-a>this.ABNORMAL_TIME_LOWER_LIMIT&&n-a<this.ABNORMAL_TIME_UPPER_LIMIT&&Fe.uploadEvent({userId:this._room.userId,log:`stat-${Lt.VIDEO_ENCODE_FAILED_DURING_CALL}`})}else{let a=this._videoAbnormalTimestampMap.get("local-encode");a&&n-a>=this.ABNORMAL_TIME_UPPER_LIMIT&&Fe.uploadEvent({userId:this._room.userId,log:`stat-${Lt.VIDEO_ENCODE_RESUME_DURING_CALL}`}),this._videoAbnormalTimestampMap.delete("local-encode")}})}if(t.msg_up_stream_info.msg_audio_status){let e=t.msg_up_stream_info.msg_audio_status,r=Array.from(this._room.localTracks).find(n=>n.kind==="audio"),o=(r==null?void 0:r.stat.bytesSent)||0;if((r==null?void 0:r.isMediaTrackActive)===!1||o<=0||r!=null&&r.isUseCustomSource)return;let s=fe();if(e.uint32_audio_codec_bitrate===0&&(r!=null&&r.isPublished))if(!this._audioAbnormalTimestampMap.has("local-encode"))this._audioAbnormalTimestampMap.set("local-encode",s);else{let n=this._audioAbnormalTimestampMap.get("local-encode");n&&s-n>this.ABNORMAL_TIME_LOWER_LIMIT&&s-n<this.ABNORMAL_TIME_UPPER_LIMIT&&Fe.uploadEvent({userId:this._room.userId,log:`stat-${Lt.AUDIO_ENCODE_FAILED_DURING_CALL}`})}else{let n=this._audioAbnormalTimestampMap.get("local-encode");n&&s-n>=this.ABNORMAL_TIME_UPPER_LIMIT&&Fe.uploadEvent({userId:this._room.userId,log:`stat-${Lt.AUDIO_ENCODE_RESUME_DURING_CALL}`}),this._audioAbnormalTimestampMap.delete("local-encode")}}}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>Sd){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()<Sd&&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(!Yr())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,T=d.presentationTime-r;if(T>f){T=Math.min(T,5e3);let _=`${t.userId}_${t.streamType}`,b=this._monitorFreezeData.get(_,"render");b?b.duration+=T:this._monitorFreezeData.set(_,{userId:t.userId,type:t.streamType,duration:T},"render");let C=this._renderFreezeMap.get(_);C?(C.totalDuration+=T,C.count+=1):this._renderFreezeMap.set(_,{userId:t.userId,type:t.streamType,totalDuration:T,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()}},WT=wf;var qT=vi(ki(),1);var Fl=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?z.addSuccessEvent({key:s.key}):z.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:T,offset:_}=this.calculateBoundary(d,s,t,r),{min:b,offset:C}=this.calculateBoundary(l,n,e,o);return p=2*T+r,f=2*b+o,p/f>this.originalAspect?(p=f*this.originalAspect,_=d-p/2):(f=p/this.originalAspect,C=l-f/2),r/s>a&&(_=0,C=0,p=s,f=n),_=Math.max(0,Math.min(_,s-p)),C=Math.max(0,Math.min(C,n-f)),{sx:_,sy:C,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)),$e(this.animationState.current.scaleOffsetX)&&$e(this.animationState.target.scaleOffsetX)&&$e(this.animationState.current.scaleOffsetY)&&$e(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(ni(t.sx-e.sx,2)+ni(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,T,_,b,C,D,x,H,W;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:(_=(T=this.animationState.current)==null?void 0:T.scaleOffsetY)!=null?_:0,timestamp:Date.now()};this.animationState.target={sx:t/2,sy:o+n/2,cropWidth:t,cropHeight:e,scaleRatio:(C=(b=this.animationState.target)==null?void 0:b.scaleRatio)!=null?C:1,scaleOffsetX:(x=(D=this.animationState.target)==null?void 0:D.scaleOffsetX)!=null?x:0,scaleOffsetY:(W=(H=this.animationState.target)==null?void 0:H.scaleOffsetY)!=null?W:0,timestamp:Date.now()},this.animationState.animating||(this.animationState.target.scaleRatio=Math.sqrt(s*n/t/e/this.defaultScaleRatio),this.animationState.target.scaleOffsetX=-this.animationState.target.scaleRatio/2+.5,this.animationState.target.scaleOffsetY=-this.animationState.target.scaleRatio+1,(this.animationState.target.sy-this.animationState.target.scaleOffsetY*this.animationState.target.cropHeight)/this.animationState.target.scaleRatio<this.boundaryY&&(this.animationState.target.scaleOffsetY=(this.animationState.target.sy-this.boundaryY*this.animationState.target.scaleRatio)/this.animationState.target.cropHeight)),this.processFacePositionPortrait(a)}set aspectRatio(t){this.originalAspect=t}get current(){return this.animationState.current}get offset(){return{offsetX:this.totalOffsetX,offsetY:this.totalOffsetY}}get targetCrop(){return this.animationState.target}};var uv=`#version 300 es
106
106
  in vec2 a_position;
107
107
  in vec2 a_texCoord;
108
108
  out vec2 v_texCoord;
@@ -143,4 +143,4 @@ void main() {
143
143
  void main() {
144
144
  gl_Position = vertexPos;
145
145
  textureCoord = texturePos;
146
- }`});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 GT=(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 mv(i){return i[0]===0&&i[1]===0&&i[2]===0&&i[3]===1}var hv=0,Hl=class{constructor(t){m(this,"id",hv++);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=ye(e.availableState,me.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),be(this.stateChangeOB,Cp((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=be(this.pipe(this.track),Je(this.stopOB),ji());be(e,Le(()=>{this.track.stat.framesDecoded++},r=>{if(this.track.log.error(`${this.id} play failed: ${r} retryCount: ${t}`),z.addFailedEvent({key:GT(this.type,this.renderer),error:r}),t>4)this.failedReason=r,this.stateChangeOB.next("FAILED"),z.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`),z.addSuccessEvent({key:GT(this.type,this.renderer)}),z.addSuccessEvent({key:514704})})),be(e,ei(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"&&!Ih()&&(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(!mv(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=fe();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 $l(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 Vt({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 Os(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 jT=Promise.resolve(),Bc=class extends qT.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",jT);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 Vt({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 gr(this._rotation)?{width:r,height:e}:{width:e,height:r}}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new Vt({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($m<=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=ht.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(),ht.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(Cr||this._isMixScreen||this._isTransform||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}sendCreateResult(e="videoCtxGl",r){let o=e==="videoCtxGl"?512700:512701;r?z.addFailedEvent({key:o,error:r}):z.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 rl(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;Cr&&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)})),kt===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 tl(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 Bl(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 Bn(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 fi)return this.log.info("change screen input",(r=e.mediaTrack)==null?void 0:r.label),this.setScreenTrack(e);if(e instanceof Ir)return this.log.info("change video input",(o=e.mediaTrack)==null?void 0:o.label),this.setCameraTrack(e);if(e instanceof Lo){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 xs)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 fi?((r=this.screenNode)==null||r.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof Ir?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 Lo?e.source&&e.source.context.destroy():e instanceof xs&&(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 ce({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 T=f&&e||l,_=f&&r||p,b=f?0:a,C=f?0:d;s.drawImage(n,b,C,T,_)}),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(T){throw new ce({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(T=>T.type===d)?(this.watermarkImageList=this.watermarkImageList.filter(T=>T.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,(T,_)=>T==="imageUrl"?void 0:_))})}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 ce({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 Hl(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([jE(function(e){this.log.error("update failed",e)}),xe(e=>function(...r){return y(this,null,function*(){this._updateFlag||(this._updateFlag=!0,yield jT,this.updated=new Promise((o,s)=>{e.apply(this,r).then(o,s),setTimeout(s,5e3,new ce({code:q.API_CALL_TIMEOUT,message:"update timeout"}))}),this._updateFlag=!1,yield this.updated)})})],Bc.prototype,"update",1);var pv=0;var Wl=class extends me{constructor(e){super("room");m(this,"seq",++pv);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 $T({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new HT({room:this}),this.badCaseDetector=new WT({room:this}),this.audioManager=new sl(this),this.videoManager=new Bc(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(Me(e))/^wss?:\/\//i.test(e)?this.proxy_ws=e:/^https?:\/\//i.test(e)&&(this.proxy_wt=e);else if(Yt(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?(Il([a,a]),is(`https://${a}`)):(s&&is(s),n&&Il(n))}U.once(B.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:Ti.main,sched_back_domain:Ti.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 ce({code:q.INVALID_OPERATION,message:je({key:Ge.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(cr.INVALID_DESTROY),new ce({code:q.INVALID_OPERATION,message:je({key:Ge.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=fe();try{let{isCached:l,result:p,detailCost:f}=yield cf({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:ft,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} ${Rr(p,{keysToExclude:["username","credential"]})}`),l&&U.once(B.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=Y(Y({},this.scheduleResult),p),$e((s=p.config)==null?void 0:s.retryCount)&&Em(p.config.retryCount),Me((n=p.config)==null?void 0:n.loggerDomain)&&is(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}),z.addSuccessEvent({key:521700,cost:fe()-o})}catch(l){throw z.addFailedEvent({key:521700,error:l}),l}})}sendAbilityStatus(e){}enableInsertableStreams(){return Promise.resolve()}switchRoom(e){return Promise.reject()}isSwitchRoomSupported(){return!1}};function zT(i,t=!1){let e=Object.defineProperties(bt(),{postMessage:{value:i.postMessage.bind(i)},port:{get(){return i},set(o){i.onmessage=qe,i.onmessageerror=qe,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 Mf=class extends _e{constructor(t,e){super(t);let r=new _e(t);r.next=qe,e(r)}},A5=Se(Mf,"takeUntilComplete");var jt={useWt:!0,useAINS:!0,useHardDecoder:"prefer-software",useHardEncoder:"prefer-software",unreliable:!1,debug:!1,assetsPath:"",enableUpload:!0},JT="__INLINE__WORKER__",XT="__INLINE__WASM__",{debug:QT}=console;jt.debug||(console.debug=()=>{});var fv=!JT.startsWith("__"),gv=!XT.startsWith("__");function Gl(){let i=us(`${jt.assetsPath?`${jt.assetsPath}/`:""}worker.js`);return fv?URL.createObjectURL(new Blob([atob(JT)],{type:"application/javascript"})):i.startsWith("http")?fetch(i).then(t=>t.blob().then(e=>URL.createObjectURL(e))):i}var $c;function jl(){return y(this,null,function*(){let i=jt.assetsPath?`${jt.assetsPath}/`:"";return $c||(gv?$c=new TextEncoder().encode(atob(XT)).buffer:$c=yield fetch(us(`${i}av_processing.wasm`)).then(t=>t.arrayBuffer()),$c)})}var Of=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=Gl();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 jl(),flag:jt},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)})}},Hc=new Of;var Pf=(()=>{if(typeof self=="undefined")return!1;if(!("top"in self&&self!==top)){if("showOpenFilePicker"in self)return"showOpenFilePicker"}return!1})(),w5=Pf?Promise.resolve().then(function(){return Iv}):Promise.resolve().then(function(){return vv});var M5=Pf?Promise.resolve().then(function(){return Av}):Promise.resolve().then(function(){return Nv});var Ev=Pf?Promise.resolve().then(function(){return bv}):Promise.resolve().then(function(){return wv});function xf(...i){return y(this,null,function*(){return(yield Ev).default(...i)})}var _v=i=>y(void 0,null,function*(){let t=yield i.getFile();return t.handle=i,t}),Tv=(...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(_v));return i[0].multiple?o:o[0]}),Iv={__proto__:null,default:Tv};function ql(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 ql=function(e){this.s=e,this.n=e.next},ql.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 ql(i)}var YT=(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 T,_=function(b){var C,D,x,H=2;for(typeof Symbol!="undefined"&&(D=Symbol.asyncIterator,x=Symbol.iterator);H--;){if(D&&(C=b[D])!=null)return C.call(b);if(x&&(C=b[x])!=null)return new ql(C.call(b));D="@@asyncIterator",x="@@iterator"}throw new TypeError("Object is not async iterable")}(i.values());p=!(T=yield _.next()).done;p=!1){let b=T.value,C=`${e}/${b.name}`;b.kind==="file"?d.push(b.getFile().then(D=>(D.directoryHandle=i,D.handle=b,Object.defineProperty(D,"webkitRelativePath",{configurable:!0,enumerable:!0,get:()=>C})))):b.kind!=="directory"||!t||r&&r(b)||a.push(YT(b,t,C,r))}}catch(b){f=!0,l=b}finally{try{p&&_.return!=null&&(yield _.return())}finally{if(f)throw l}}return[...(yield Promise.all(a)).flat(),...yield Promise.all(d)]}),Sv=(...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 YT(e,i.recursive,void 0,i.skipDirectory)}),Av={__proto__:null,default:Sv},yv=(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,T)=>{a[T]={description:f.description||"Files",accept:{}},f.mimeTypes?(T===0&&d&&f.mimeTypes.push(d),f.mimeTypes.map(_=>{a[T].accept[_]=f.extensions||[]})):d?a[T].accept[d]=f.extensions||[]:a[T].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)}),bv={__proto__:null,default:yv},Rv=(...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()})}),vv={__proto__:null,default:Rv},Cv=(...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()})}),Nv={__proto__:null,default:Cv},Dv=(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:b=>function C(){return y(this,null,function*(){return p.read().then(({done:D,value:x})=>{if(!D)return b.enqueue(x),C();b.close()})})}()}),T=new Response(f),_=yield T.blob();return p.releaseLock(),new Blob([_],{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}),wv={__proto__:null,default:Dv};var Lf=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=Gl(),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(Nd(),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 jl(),flag:jt},this.ports)}))})}destroy(){var t;console.log("destroy worker",this.name),delete this.ready,(t=this.worker)==null||t.terminate()}},kf=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()}},Uf=class i extends Lf{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)})}},Wo=new Uf,Hs,KT=-1;function ZT(i){return console.log(i),Hs.push(i.slice()),Hs.length>1e3&&Hs.shift(),i}function eI(i){return y(this,null,function*(){switch(KT){case 0:this.edpl.willDecodeAudio=ZT;break;case 2:this.edpl.didEncodeAudio=ZT;break}yield Wo.create(),U.emit(B.JOIN_SEND_CMD,{room:this});let t=new kf(Wo,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 ce({code:q.JOIN_ROOM_FAILED,extraCode:Number(e),message:je({key:Ge.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:e,errorMsg:""}})})}else throw e})}Object.defineProperties(window,{useAINS:{set:Vf},useWt:{set:Mv},enableDebug:{set(i){console.debug=i?QT:()=>{},Wo.setSwitchValue("enableDebug",i)}},useV2:{set:Ff},dump:{value(i=0){if(KT=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)}),xf(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;Wo.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,Wo.extendChannel.port1.postMessage(["dump",i]),s.port2.close(),o(new Blob(e)))}});return xf(r,{fileName:i,extensions:[".pcm"]})}},hardDec:{set(i){switch(i){case!0:jt.useHardDecoder="prefer-hardware";break;case!1:jt.useHardDecoder="prefer-software";break;default:jt.useHardDecoder="no-preference"}}}});function Vf(i){return y(this,null,function*(){Wo.setSwitchValue("useAINS",i)})}function Ff(i){return y(this,null,function*(){Wo.setSwitchValue("useV2",i)})}function Mv(i){return y(this,null,function*(){Wo.setSwitchValue("useWt",i)})}function tI(i){let t=new MediaStreamTrackGenerator({kind:"audio"});i.setInputMediaStreamTrack(t),this.postMessage({cmd:"pullAudio",payload:{tinyId:i.tinyId,writable:t.writable}},[t.writable])}function rI(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),be(zT(r.port2),Je(ye(i,me.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 zl=[];function oI(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<=zl.length;l++)if(!zl[l]){zl[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(Ie(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(Hc.worklet,0,this.index)};be(ye(i,"output-media-track-changed"),Je(ye(i,"ready")),Le(a,console.error,()=>{this._log.info("stop push audio",e),i.volume=0,n.disconnect(),zl[this.index]=null,o&&o.port1.postMessage(null),r.port1.postMessage(null)})),be(t,ws(l=>i.volume=l),qi(el(1e3)),Le(()=>{i.volume=0})),a(i.outMediaTrack)}var l8=new Intl.DateTimeFormat("zh-CN",{dateStyle:"short",timeStyle:"medium"});var Bf=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);m(this,"startTime",0);m(this,"startTimestamp",0);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=>{let a=Date.now();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)),Mt===126?this.tsMap.set(s,fe()):s===0&&(this.startTime=a,this.startTimestamp=n.timestamp),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=Mt===126?this.tsMap.get(r):(this.startTime+(s.timestamp-this.startTimestamp)/1e3&4294967295)>>>0;if(Mt===126&&this.tsMap.delete(r),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 Jl(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:jt.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 Bf(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;Ia({configureBr:[a.data.bitrate,d]}),n.session&&n.configure({bitrate:d},n.session)}},this._log.info("start push",r,t),n})}function sI(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 Jl.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:T,height:_,displaySurface:b}=f.getSettings();T&&(a.config.width=T),_&&(a.config.height=_);let C=nr.match(/Chrome\/(\d+)/);(C==null?void 0:C[1])==="114"&&b==="browser"&&delete a.config.hardwareAcceleration,this._log.info("push",e,"track:",f.readyState,f.getSettings());let D;if(typeof MediaStreamTrackProcessor!="undefined"&&!(f instanceof CanvasCaptureMediaStreamTrack))D=new MediaStreamTrackProcessor({track:f}).readable;else{let H;D=new ReadableStream({start(W){i.on("render",ne=>{if(!(i.player.mode===0&&!document.hidden))try{W.enqueue(new VideoFrame(ne,{timestamp:performance.now()*1e3}))}catch(Ve){console.warn(Ve)}})},pull(W){return y(this,null,function*(){if(i.player.mode===0&&Yr()&&i.player.element)return new Promise(ne=>{i.player.element.requestVideoFrameCallback((Ve,he)=>{try{let Q=new VideoFrame(i.player.element);W.enqueue(Q)}catch(Q){console.warn(Q)}ne()})})})}})}let x="small"in i&&i.small;return x?(this.smallEncoder||(this.smallEncoder=yield Jl.call(this,i,{profile:x,type:3,trackType:o})),this.smallEncoder.track=f,this.smallEncoder.label="small",D=yield this.smallEncoder.trans(D,d,this)):this.smallEncoder&&(this.smallEncoder.close(),delete this.smallEncoder),a.track=f,a.label=e,a.start(D,d,this)});return be(ye(i,"output-media-track-changed"),Je(ye(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 Go=class Go extends me{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(Go.INTERVALCHANGED,this.interval)}),be(ye(this,Go.INTERVALCHANGED),hi(s=>this.room.state==="joined"?this.room.fromWorker("getAudioEnergy",s):be(s_(s),Oo(()=>[]))),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==me.ON&&this.room.emit("audio-volume",s)}))}start(e,r){this.interval=e,this.enableInBackground=r,this.emit(Go.INTERVALCHANGED,this.interval)}stop(){}};m(Go,"INTERVALCHANGED","intervalChanged"),Z([et([me.INIT,me.OFF],me.ON)],Go.prototype,"start",1),Z([et([],me.OFF)],Go.prototype,"stop",1);var Xl=Go;var jo=class jo extends Wl{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 Xl(this));m(this,"enableAIVoice",Vf);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:Jm(),uint32_device_type:0,str_os_verion:Xm(),uint32_link_type:1,str_client_version:ft,uint32_net_type:os[di.getNetworkType()],ua:navigator.userAgent,version:""}});m(this,"joinAbortController",new AbortController);m(this,"smallAbortCtrl");m(this,"smallEncoder");e.tinyId&&(this.tinyId=e.tinyId,Ff(!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=di.getEnv(),n=_u(),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:_u(),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:ft,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 eI.call(this,a),console.log(this),Hc.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(ye(this,"left")),r=this.audioManager.decodePipeline.some(o=>o);be(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(Ie(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 kl(this,r);this.remotePublishedUserMap.set(r.userId,o),this.emit("remote-published",o);return;case"5":{let f=r,T=this.remotePublishedUserMap.get(f);T&&(T.remoteVideoTrack.close(),T.remoteAuxiliaryTrack.close(),T.remoteAudioTrack.close(),this.remotePublishedUserMap.delete(f),this.emit("remote-unpublished",T))}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:T,flag:_}=r,b=this.remotePublishedUserMap.get(T.userId);if(!b){this.emit("remote-publish-state-changed",r);return}b.flag=_}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:ft,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:os[cn()]},msg_event_msg:c_(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),$t(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 Hc.init(),oI.call(this,e);break;default:yield sI.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,T)=>T.mediaType|f,0),{userId:o,tinyId:s,streamType:n}=e[0],a=this.remotePublishedUserMap.get(o),d=Y({},a.subscribeState),l=Object.assign(new Ba,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 tI.call(this,f);default:return rI.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 Jl.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([wo(jo.prototype.afterJoin),et(["left",me.INIT],"joined"),kT()],jo.prototype,"join",1),Z([et("joined","left",{ignoreError:!0}),UT()],jo.prototype,"leave",1),Z([ku(e=>e.mediaType),VT()],jo.prototype,"publish",1),Z([ku(e=>e.mediaType),FT()],jo.prototype,"unpublish",1),Z([ku((...e)=>e[0].userId),BT()],jo.prototype,"subscribe",1);var Ql=jo;Yn.frameWorkType=37;Yn.create=function(i){let t=Yn._create.call(this,Ql,i);return t._use(of,i==null?void 0:i.assetsPath),i!=null&&i.assetsPath&&(jt.assetsPath=i==null?void 0:i.assetsPath),console.log("trtc wasm sdk:",ft,"created",jt),t};Object.assign(Yn.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(of.Name,{type:"webCodecs",renderer:"videoFrame",track:i,config:{codec:"avc1.640028",hardwareAcceleration:"prefer-software",optimizeForLatency:!0},fallback:"wasm"}),new Promise((e,r)=>{be(ye(i,"decode-downgrade-state-changed"),rr(o=>o.state==="STARTED"),ei(1),Mp(1e4),Je(ye(i,me.INIT)),Le(e,r))})})}});vh(37);var F6=Yn;export{F6 as default};
146
+ }`});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 GT=(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 mv(i){return i[0]===0&&i[1]===0&&i[2]===0&&i[3]===1}var hv=0,Hl=class{constructor(t){m(this,"id",hv++);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=ye(e.availableState,me.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),be(this.stateChangeOB,Cp((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=be(this.pipe(this.track),Je(this.stopOB),ji());be(e,Le(()=>{this.track.stat.framesDecoded++},r=>{if(this.track.log.error(`${this.id} play failed: ${r} retryCount: ${t}`),z.addFailedEvent({key:GT(this.type,this.renderer),error:r}),t>4)this.failedReason=r,this.stateChangeOB.next("FAILED"),z.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`),z.addSuccessEvent({key:GT(this.type,this.renderer)}),z.addSuccessEvent({key:514704})})),be(e,ei(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"&&!Ih()&&(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(!mv(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=fe();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 $l(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 Vt({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 Os(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 jT=Promise.resolve(),Bc=class extends qT.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",jT);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 Vt({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 gr(this._rotation)?{width:r,height:e}:{width:e,height:r}}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new Vt({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($m<=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=ht.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(),ht.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(Cr||this._isMixScreen||this._isTransform||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}sendCreateResult(e="videoCtxGl",r){let o=e==="videoCtxGl"?512700:512701;r?z.addFailedEvent({key:o,error:r}):z.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 rl(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;Cr&&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)})),kt===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 tl(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 Bl(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 Bn(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 fi)return this.log.info("change screen input",(r=e.mediaTrack)==null?void 0:r.label),this.setScreenTrack(e);if(e instanceof Ir)return this.log.info("change video input",(o=e.mediaTrack)==null?void 0:o.label),this.setCameraTrack(e);if(e instanceof Lo){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 xs)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 fi?((r=this.screenNode)==null||r.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof Ir?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 Lo?e.source&&e.source.context.destroy():e instanceof xs&&(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 ce({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 T=f&&e||l,_=f&&r||p,b=f?0:a,C=f?0:d;s.drawImage(n,b,C,T,_)}),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(T){throw new ce({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(T=>T.type===d)?(this.watermarkImageList=this.watermarkImageList.filter(T=>T.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,(T,_)=>T==="imageUrl"?void 0:_))})}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 ce({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 Hl(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([jE(function(e){this.log.error("update failed",e)}),xe(e=>function(...r){return y(this,null,function*(){this._updateFlag||(this._updateFlag=!0,yield jT,this.updated=new Promise((o,s)=>{e.apply(this,r).then(o,s),setTimeout(s,5e3,new ce({code:q.API_CALL_TIMEOUT,message:"update timeout"}))}),this._updateFlag=!1,yield this.updated)})})],Bc.prototype,"update",1);var pv=0;var Wl=class extends me{constructor(e){super("room");m(this,"seq",++pv);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 $T({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new HT({room:this}),this.badCaseDetector=new WT({room:this}),this.audioManager=new sl(this),this.videoManager=new Bc(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(Me(e))/^wss?:\/\//i.test(e)?this.proxy_ws=e:/^https?:\/\//i.test(e)&&(this.proxy_wt=e);else if(Yt(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?(Il([a,a]),is(`https://${a}`)):(s&&is(s),n&&Il(n))}U.once(B.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:Ti.main,sched_back_domain:Ti.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 ce({code:q.INVALID_OPERATION,message:je({key:Ge.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(cr.INVALID_DESTROY),new ce({code:q.INVALID_OPERATION,message:je({key:Ge.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=fe();try{let{isCached:l,result:p,detailCost:f}=yield cf({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:ft,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} ${Rr(p,{keysToExclude:["username","credential"]})}`),l&&U.once(B.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=Y(Y({},this.scheduleResult),p),$e((s=p.config)==null?void 0:s.retryCount)&&Em(p.config.retryCount),Me((n=p.config)==null?void 0:n.loggerDomain)&&is(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}),z.addSuccessEvent({key:521700,cost:fe()-o})}catch(l){throw z.addFailedEvent({key:521700,error:l}),l}})}sendAbilityStatus(e){}enableInsertableStreams(){return Promise.resolve()}switchRoom(e){return Promise.reject()}isSwitchRoomSupported(){return!1}};function zT(i,t=!1){let e=Object.defineProperties(bt(),{postMessage:{value:i.postMessage.bind(i)},port:{get(){return i},set(o){i.onmessage=qe,i.onmessageerror=qe,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 Mf=class extends _e{constructor(t,e){super(t);let r=new _e(t);r.next=qe,e(r)}},A5=Se(Mf,"takeUntilComplete");var jt={useWt:!0,useAINS:!0,useHardDecoder:"prefer-software",useHardEncoder:"prefer-software",unreliable:!1,debug:!1,assetsPath:"",enableUpload:!0},JT="__INLINE__WORKER__",XT="__INLINE__WASM__",{debug:QT}=console;jt.debug||(console.debug=()=>{});var fv=!JT.startsWith("__"),gv=!XT.startsWith("__");function Gl(){let i=us(`${jt.assetsPath?`${jt.assetsPath}/`:""}worker.js`);return fv?URL.createObjectURL(new Blob([atob(JT)],{type:"application/javascript"})):i.startsWith("http")?fetch(i).then(t=>t.blob().then(e=>URL.createObjectURL(e))):i}var $c;function jl(){return y(this,null,function*(){let i=jt.assetsPath?`${jt.assetsPath}/`:"";return $c||(gv?$c=new TextEncoder().encode(atob(XT)).buffer:$c=yield fetch(us(`${i}av_processing.wasm`)).then(t=>t.arrayBuffer()),$c)})}var Of=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=Gl();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 jl(),flag:jt},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)})}},Hc=new Of;var Pf=(()=>{if(typeof self=="undefined")return!1;if(!("top"in self&&self!==top)){if("showOpenFilePicker"in self)return"showOpenFilePicker"}return!1})(),w5=Pf?Promise.resolve().then(function(){return Iv}):Promise.resolve().then(function(){return vv});var M5=Pf?Promise.resolve().then(function(){return Av}):Promise.resolve().then(function(){return Nv});var Ev=Pf?Promise.resolve().then(function(){return bv}):Promise.resolve().then(function(){return wv});function xf(...i){return y(this,null,function*(){return(yield Ev).default(...i)})}var _v=i=>y(void 0,null,function*(){let t=yield i.getFile();return t.handle=i,t}),Tv=(...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(_v));return i[0].multiple?o:o[0]}),Iv={__proto__:null,default:Tv};function ql(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 ql=function(e){this.s=e,this.n=e.next},ql.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 ql(i)}var YT=(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 T,_=function(b){var C,D,x,H=2;for(typeof Symbol!="undefined"&&(D=Symbol.asyncIterator,x=Symbol.iterator);H--;){if(D&&(C=b[D])!=null)return C.call(b);if(x&&(C=b[x])!=null)return new ql(C.call(b));D="@@asyncIterator",x="@@iterator"}throw new TypeError("Object is not async iterable")}(i.values());p=!(T=yield _.next()).done;p=!1){let b=T.value,C=`${e}/${b.name}`;b.kind==="file"?d.push(b.getFile().then(D=>(D.directoryHandle=i,D.handle=b,Object.defineProperty(D,"webkitRelativePath",{configurable:!0,enumerable:!0,get:()=>C})))):b.kind!=="directory"||!t||r&&r(b)||a.push(YT(b,t,C,r))}}catch(b){f=!0,l=b}finally{try{p&&_.return!=null&&(yield _.return())}finally{if(f)throw l}}return[...(yield Promise.all(a)).flat(),...yield Promise.all(d)]}),Sv=(...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 YT(e,i.recursive,void 0,i.skipDirectory)}),Av={__proto__:null,default:Sv},yv=(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,T)=>{a[T]={description:f.description||"Files",accept:{}},f.mimeTypes?(T===0&&d&&f.mimeTypes.push(d),f.mimeTypes.map(_=>{a[T].accept[_]=f.extensions||[]})):d?a[T].accept[d]=f.extensions||[]:a[T].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)}),bv={__proto__:null,default:yv},Rv=(...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()})}),vv={__proto__:null,default:Rv},Cv=(...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()})}),Nv={__proto__:null,default:Cv},Dv=(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:b=>function C(){return y(this,null,function*(){return p.read().then(({done:D,value:x})=>{if(!D)return b.enqueue(x),C();b.close()})})}()}),T=new Response(f),_=yield T.blob();return p.releaseLock(),new Blob([_],{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}),wv={__proto__:null,default:Dv};var Lf=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=Gl(),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(Nd(),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 jl(),flag:jt},this.ports)}))})}destroy(){var t;console.log("destroy worker",this.name),delete this.ready,(t=this.worker)==null||t.terminate()}},kf=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()}},Uf=class i extends Lf{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)})}},Wo=new Uf,Hs,KT=-1;function ZT(i){return console.log(i),Hs.push(i.slice()),Hs.length>1e3&&Hs.shift(),i}function eI(i){return y(this,null,function*(){switch(KT){case 0:this.edpl.willDecodeAudio=ZT;break;case 2:this.edpl.didEncodeAudio=ZT;break}yield Wo.create(),U.emit(B.JOIN_SEND_CMD,{room:this});let t=new kf(Wo,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 ce({code:q.JOIN_ROOM_FAILED,extraCode:Number(e),message:je({key:Ge.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:e,errorMsg:""}})})}else throw e})}Object.defineProperties(window,{useAINS:{set:Vf},useWt:{set:Mv},enableDebug:{set(i){console.debug=i?QT:()=>{},Wo.setSwitchValue("enableDebug",i)}},useV2:{set:Ff},dump:{value(i=0){if(KT=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)}),xf(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;Wo.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,Wo.extendChannel.port1.postMessage(["dump",i]),s.port2.close(),o(new Blob(e)))}});return xf(r,{fileName:i,extensions:[".pcm"]})}},hardDec:{set(i){switch(i){case!0:jt.useHardDecoder="prefer-hardware";break;case!1:jt.useHardDecoder="prefer-software";break;default:jt.useHardDecoder="no-preference"}}}});function Vf(i){return y(this,null,function*(){Wo.setSwitchValue("useAINS",i)})}function Ff(i){return y(this,null,function*(){Wo.setSwitchValue("useV2",i)})}function Mv(i){return y(this,null,function*(){Wo.setSwitchValue("useWt",i)})}function tI(i){let t=new MediaStreamTrackGenerator({kind:"audio"});i.setInputMediaStreamTrack(t),this.postMessage({cmd:"pullAudio",payload:{tinyId:i.tinyId,writable:t.writable}},[t.writable])}function rI(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),be(zT(r.port2),Je(ye(i,me.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 zl=[];function oI(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<=zl.length;l++)if(!zl[l]){zl[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(Ie(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(Hc.worklet,0,this.index)};be(ye(i,"output-media-track-changed"),Je(ye(i,"ready")),Le(a,console.error,()=>{this._log.info("stop push audio",e),i.volume=0,n.disconnect(),zl[this.index]=null,o&&o.port1.postMessage(null),r.port1.postMessage(null)})),be(t,ws(l=>i.volume=l),qi(el(1e3)),Le(()=>{i.volume=0})),a(i.outMediaTrack)}var l8=new Intl.DateTimeFormat("zh-CN",{dateStyle:"short",timeStyle:"medium"});var Bf=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);m(this,"startTime",0);m(this,"startTimestamp",0);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=>{let a=Date.now();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)),Mt===126?this.tsMap.set(s,fe()):s===0&&(this.startTime=a,this.startTimestamp=n.timestamp),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=Mt===126?this.tsMap.get(r):(this.startTime+(s.timestamp-this.startTimestamp)/1e3&4294967295)>>>0;if(Mt===126&&this.tsMap.delete(r),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 Jl(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:jt.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 Bf(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;Ia({configureBr:[a.data.bitrate,d]}),n.session&&n.configure({bitrate:d},n.session)}},this._log.info("start push",r,t),n})}function sI(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 Jl.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:T,height:_,displaySurface:b}=f.getSettings();T&&(a.config.width=T),_&&(a.config.height=_);let C=nr.match(/Chrome\/(\d+)/);(C==null?void 0:C[1])==="114"&&b==="browser"&&delete a.config.hardwareAcceleration,this._log.info("push",e,"track:",f.readyState,f.getSettings());let D;if(typeof MediaStreamTrackProcessor!="undefined"&&!(f instanceof CanvasCaptureMediaStreamTrack))D=new MediaStreamTrackProcessor({track:f}).readable;else{let H;D=new ReadableStream({start(W){i.on("render",ne=>{if(!(i.player.mode===0&&!document.hidden))try{W.enqueue(new VideoFrame(ne,{timestamp:performance.now()*1e3}))}catch(Ve){console.warn(Ve)}})},pull(W){return y(this,null,function*(){if(i.player.mode===0&&Yr()&&i.player.element)return new Promise(ne=>{i.player.element.requestVideoFrameCallback((Ve,he)=>{try{let Q=new VideoFrame(i.player.element);W.enqueue(Q)}catch(Q){console.warn(Q)}ne()})})})}})}let x="small"in i&&i.small;return x?(this.smallEncoder||(this.smallEncoder=yield Jl.call(this,i,{profile:x,type:3,trackType:o})),this.smallEncoder.track=f,this.smallEncoder.label="small",D=yield this.smallEncoder.trans(D,d,this)):this.smallEncoder&&(this.smallEncoder.close(),delete this.smallEncoder),a.track=f,a.label=e,a.start(D,d,this)});return be(ye(i,"output-media-track-changed"),Je(ye(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 Go=class Go extends me{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(Go.INTERVALCHANGED,this.interval)}),be(ye(this,Go.INTERVALCHANGED),hi(s=>this.room.state==="joined"?this.room.fromWorker("getAudioEnergy",s):be(s_(s),Oo(()=>[]))),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==me.ON&&this.room.emit("audio-volume",s)}))}start(e,r){this.interval=e,this.enableInBackground=r,this.emit(Go.INTERVALCHANGED,this.interval)}stop(){}};m(Go,"INTERVALCHANGED","intervalChanged"),Z([et([me.INIT,me.OFF],me.ON)],Go.prototype,"start",1),Z([et([],me.OFF)],Go.prototype,"stop",1);var Xl=Go;var jo=class jo extends Wl{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 Xl(this));m(this,"enableAIVoice",Vf);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:Jm(),uint32_device_type:0,str_os_verion:Xm(),uint32_link_type:1,str_client_version:ft,uint32_net_type:os[di.getNetworkType()],ua:navigator.userAgent,version:""}});m(this,"joinAbortController",new AbortController);m(this,"smallAbortCtrl");m(this,"smallEncoder");e.tinyId&&(this.tinyId=e.tinyId,Ff(!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;let s=di.getEnv(),n=_u(),a={isH264EncodeSupported:this.checkSystemResult.detail.isH264EncodeSupported,isVp8EncodeSupported:this.checkSystemResult.detail.isVp8EncodeSupported,frameWorkType:o,params:e,proxy_wt:this.proxy_wt,proxy_ws:this.proxy_ws,proxy_cloud:(d=this.scheduleResult.iceServers)!=null&&d.length?this.scheduleResult.iceServers[0].urls:[],proxy_unified:this.proxy_unified,domains:this.scheduleResult.domains,env:s,osName:yn(),browserInfo:_u(),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:ft,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 eI.call(this,a),console.log(this),Hc.playAudio(l=>this.postMessage({cmd:"setAudioWorkletPort"},[l])),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(ye(this,"left")),r=this.audioManager.decodePipeline.some(o=>o);be(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(Ie(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 kl(this,r);this.remotePublishedUserMap.set(r.userId,o),this.emit("remote-published",o);return;case"5":{let f=r,T=this.remotePublishedUserMap.get(f);T&&(T.remoteVideoTrack.close(),T.remoteAuxiliaryTrack.close(),T.remoteAudioTrack.close(),this.remotePublishedUserMap.delete(f),this.emit("remote-unpublished",T))}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:T,flag:_}=r,b=this.remotePublishedUserMap.get(T.userId);if(!b){this.emit("remote-publish-state-changed",r);return}b.flag=_}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:ft,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:os[cn()]},msg_event_msg:c_(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),$t(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 Hc.init(),oI.call(this,e);break;default:yield sI.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,T)=>T.mediaType|f,0),{userId:o,tinyId:s,streamType:n}=e[0],a=this.remotePublishedUserMap.get(o),d=Y({},a.subscribeState),l=Object.assign(new Ba,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 tI.call(this,f);default:return rI.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 Jl.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([wo(jo.prototype.afterJoin),et(["left",me.INIT],"joined"),kT()],jo.prototype,"join",1),Z([et("joined","left",{ignoreError:!0}),UT()],jo.prototype,"leave",1),Z([ku(e=>e.mediaType),VT()],jo.prototype,"publish",1),Z([ku(e=>e.mediaType),FT()],jo.prototype,"unpublish",1),Z([ku((...e)=>e[0].userId),BT()],jo.prototype,"subscribe",1);var Ql=jo;Yn.frameWorkType=37;Yn.create=function(i){let t=Yn._create.call(this,Ql,i);return t._use(of,i==null?void 0:i.assetsPath),i!=null&&i.assetsPath&&(jt.assetsPath=i==null?void 0:i.assetsPath),console.log("trtc wasm sdk:",ft,"created",jt),t};Object.assign(Yn.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(of.Name,{type:"webCodecs",renderer:"videoFrame",track:i,config:{codec:"avc1.640028",hardwareAcceleration:"prefer-software",optimizeForLatency:!0},fallback:"wasm"}),new Promise((e,r)=>{be(ye(i,"decode-downgrade-state-changed"),rr(o=>o.state==="STARTED"),ei(1),Mp(1e4),Je(ye(i,me.INIT)),Le(e,r))})})}});vh(37);var F6=Yn;export{F6 as default};