trtc-sdk-v5 5.15.1-wasm.2 → 5.15.1-wasm.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/trtc.esm.js CHANGED
@@ -90,7 +90,7 @@ return ret;
90
90
  `);L.isVoid||(Ee+=` return retType.toWireType(destructors, rv);
91
91
  `),Ee+=`};
92
92
  `,X.push(Ee);var De,ge,Ve=ad(Function,X).apply(null,K);return De=Ve,ge=Xs.length,Xs.push(De),j=ge,da[$]=j,j},f:()=>{Ar("")},c:pd,t:(S,T,w)=>N.copyWithin(S,T,T+w),s:S=>{N.length,Ar("OOM")},i:(S,T,w,L)=>{for(var $=0,j=0;j<w;j++){var X=ae[T>>2],K=ae[T+4>>2];T+=8;for(var ie=0;ie<K;ie++)fd(S,N[X+ie]);$+=K}return ae[L>>2]=$,0}},pr=((function(){var S,T,w,L,$={a:Ys};function j(X,K){var ie,q,Ee=X.exports;return I=(R=Ee).v,ie=I.buffer,o.HEAP8=y=new Int8Array(ie),o.HEAP16=P=new Int16Array(ie),o.HEAP32=G=new Int32Array(ie),o.HEAPU8=N=new Uint8Array(ie),o.HEAPU16=W=new Uint16Array(ie),o.HEAPU32=ae=new Uint32Array(ie),o.HEAPF32=ke=new Float32Array(ie),o.HEAPF64=Me=new Float64Array(ie),Y=R.z,q=R.w,ea.unshift(q),(function(){if(ti--,o.monitorRunDependencies&&o.monitorRunDependencies(ti),ti==0&&(ra!==null&&(clearInterval(ra),ra=null),jo)){var He=jo;jo=null,He()}})(),Ee}if(ti++,o.monitorRunDependencies&&o.monitorRunDependencies(ti),o.instantiateWasm)try{return o.instantiateWasm($,j)}catch(X){_("Module.instantiateWasm callback failed with error: "+X),r(X)}(S=p,T=re,w=$,L=function(X){j(X.instance)},S||typeof WebAssembly.instantiateStreaming!="function"||Ws(T)||typeof fetch!="function"?ri(T,w,L):fetch(T,{credentials:"same-origin"}).then(X=>WebAssembly.instantiateStreaming(X,w).then(L,function(K){return _("wasm streaming compile failed: "+K),_("falling back to ArrayBuffer instantiation"),ri(T,w,L)}))).catch(r)})(),S=>(pr=R.x)(S)),ma=S=>(ma=R.y)(S),gd=S=>(gd=R.A)(S),ha=(o.__embind_initialize_bindings=()=>(o.__embind_initialize_bindings=R.B)(),S=>(ha=R.C)(S));o.dynCall_jiji=(S,T,w,L,$)=>(o.dynCall_jiji=R.D)(S,T,w,L,$);function Ed(){function S(){Qs||(Qs=!0,o.calledRun=!0,Or||(Ai(ea),e(o),o.onRuntimeInitialized&&o.onRuntimeInitialized(),(function(){if(o.postRun)for(typeof o.postRun=="function"&&(o.postRun=[o.postRun]);o.postRun.length;)Zc(o.postRun.shift());Ai(ta)})()))}ti>0||((function(){if(o.preRun)for(typeof o.preRun=="function"&&(o.preRun=[o.preRun]);o.preRun.length;)Yc(o.preRun.shift());Ai(Ye)})(),ti>0||(o.setStatus?(o.setStatus("Running..."),setTimeout(function(){setTimeout(function(){o.setStatus("")},1),S()},1)):S()))}if(jo=function S(){Qs||Ed(),Qs||(jo=S)},o.preInit)for(typeof o.preInit=="function"&&(o.preInit=[o.preInit]);o.preInit.length>0;)o.preInit.pop()();return Ed(),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_||{}),Lb="5.0.0",xb=typeof importScripts!="undefined",kb=typeof registerProcessor!="undefined",Ub="",Vb="web.sdk.qcloud.com",Fb=`https://${Vb}/trtc/webrtc/doc`,mV=`${Fb}/zh-cn/`,Bb="https://yun.tim.qq.com",$b="https://apisgp.my-imcloud.com",Hb={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 F_={"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}},hV=F_["480p_2"],pV=F_["120p_2"],Sl={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",FULLSCREEN_CHANGE:"fullscreenchange",RESIZE:"resize",TIME_UPDATE:"timeupdate"},fV=Sl.MAIN,gV=Sl.AUXILIARY,EV=Sl.BIG,_V=Sl.SMALL;var TV=Object.keys(ks);var Wb=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())})},ef=Symbol(32),tf=Symbol(16),rf=Symbol(8),zn=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 Wb(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(ef)}readU16(){return this.read(tf)}readU8(){return this.read(rf)}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===ef){if(r(4))return;i=t[0]<<24|t[1]<<16|t[2]<<8|t[3]}else if(this.need===tf){if(r(2))return;i=t[0]<<8|t[1]}else if(this.need===rf){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}};zn.U32=ef,zn.U16=tf,zn.U8=rf;var Gb=128,jb=127,IV=~jb,SV=Math.pow(2,31);function Jp(i){let t=new zn;for(;i>=128;)t.malloc(1)[0]=255&i|Gb,i>>>=7;return t.malloc(1)[0]=255&i,t.buffer||new Uint8Array(0)}function of(i,t=0){let e=new zn,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(Jp(i));break;case"string":e.malloc(1)[0]=2|r;let s=new TextEncoder().encode(i);e.write(Jp(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 zn;if(Array.isArray(i))for(let d=0;d<i.length;d++){let l=of(i[d],d+1);l&&a.write(l)}else{let d=1;for(let l in i){let p=of(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(Jp(a.buffer.length)),e.write(a.buffer)))}return e.buffer||new Uint8Array(0)}var A_=class{constructor(){st(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 y_(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 cr(i,t){return i[t]<<24|i[t+1]<<16|i[t+2]<<8|i[t+3]}function b_(i,t){return i[t]}function vc(i,t,e){return new TextDecoder().decode(qb(i,t,e))}function qb(i,t,e){return i.slice(t,t+e)}var Xp=0,sf=2654435769,nf=16,R_=4,Pc=2,Lc=7;function zb(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 Jb(i,t){let e=new A_,r=zb(t,i,Xp);Xp=Xp+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 A_;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 W=4;W<16;W++)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 _=new TextEncoder().encode(r.reqHead.clientVersionInfo);n.writeInt16(_.length+2),_.length&&n.writeBytes(_);let I=n.length;n.data[0]=I>>>24&255,n.data[1]=I>>>16&255,n.data[2]=I>>>8&255,n.data[3]=255&I,af(i)&&(i=new TextEncoder().encode(i)),n.writeInt32(i.length+4),i.length&&n.writeBytes(i);let R=new Uint8Array(n.data),y=null;r.encryption===1?y=new TextEncoder().encode(r.uin):r.encryption===2&&(y=new Uint8Array(16)),y&&(R=Xb(R,y)),e.writeBytes(R);let N=new Uint8Array(e.data),P=N.length;return N[0]=P>>>24&255,N[1]=P>>>16&255,N[2]=P>>>8&255,N[3]=255&P,N}function Xb(i,t){let e=i.length,r=(e+1+Pc+Lc)%8;r&&(r=8-r);let o=new Uint8Array(e+1+Pc+Lc+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<Pc;)if(l<8&&(n[l]=255&Math.floor(256*Math.random()),l+=1,f+=1),l===8){Qp(n,t,a,d,o,s),s+=8,l=0;for(let _=0;_<8;_++)d[_]=o[s-8+_]}let p=0;for(;p<e;)if(l<8&&(n[l]=i[p],l+=1,p+=1),l===8){Qp(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<Lc;)if(l<8&&(n[l]=0,l+=1,f+=1),l===8){Qp(n,t,a,d,o,s),s+=8,l=0;for(let _=0;_<8;_++)d[_]=o[s-8+_]}return o}function Qp(i,t,e,r,o,s){for(let n=0;n<8;n++)i[n]^=r[n];Qb(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 Qb(i,t,e,r){let o=cr(i,0),s=cr(i,4),n=[];for(let d=0;d<4;d++)n[d]=cr(t,4*d);let a=0;for(let d=0;d<nf;d++)a+=sf,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;y_(e,o,r),y_(e,s,r+4)}var Yb=0,B_=function(){return Date.now()+Yb},Zb=function(){let i=new Date;return i.setTime(B_()),i.toLocaleString()},Kb=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 eR(i){let t=tR(i);return t==null?void 0:t.busiBuff}function tR(i){try{let t={},e=0;t.totalLength=cr(i,e),e+=4,t.version=cr(i,e),e+=4,t.encryption=b_(i,e),e+=1,t.uinType=b_(i,e),e+=1,t.uinLength=cr(i,e),e+=4,t.uin=t.uinLength>4?vc(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=rR(r,o),t.decrypted=!0,e=0}else i=r,e=0;return t.rspHeadLength=cr(i,e),e+=4,t.seqNo=cr(i,e),e+=4,t.retCode=cr(i,e),e+=4,t.retStrLength=cr(i,e),e+=4,t.retStr=t.retStrLength?vc(i,e,t.retStrLength-4):"",e+=t.retStrLength-4,t.serviceCmdLength=cr(i,e),e+=4,t.serviceCmd=t.serviceCmdLength?vc(i,e,t.serviceCmdLength-4):"",e+=t.serviceCmdLength-4,t.cookieLength=cr(i,e),e+=4,t.cookie=t.cookieLength?vc(i,e,t.cookieLength-4):"",e+=t.cookieLength-4,t.flag=cr(i,e),e+=4,t.busiBuffLength=cr(i,e),e+=4,t.busiBuff=t.busiBuffLength?vc(i,e,t.busiBuffLength-4):"",e+=t.busiBuffLength-4,t}catch(t){}}function $_(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=sf*nf>>>0;for(let s=0;s<nf;s++)r-=(e<<R_)+t[2]^e+o^(e>>>5)+t[3],r>>>=0,e-=(r<<R_)+t[0]^r+o^(r>>>5)+t[1],e>>>=0,o-=sf,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 rR(i,t){let e=0,r=new Uint8Array(8).fill(0),o=$_(new Uint8Array(i.slice(0,8)),t),s=7&o[0],n=i.length-1-s-Pc-Lc,a=new Uint8Array(n),d=0,l=r,p=i.slice(0,8);e=8;let f=1;f+=s;for(let I=1;I<=Pc;)if(f<8)f++,I++;else if(f===8){let R=Yp(i,e,l,p,o,t);l=R.ivPreCrypt,p=R.ivCurCrypt,o=R.debiBuf,e=R.bufPos,f=0}let _=n;for(;_>0;)if(f<8)a[d++]=o[f]^l[f],f++,_--;else if(f===8){let I=Yp(i,e,l,p,o,t);l=I.ivPreCrypt,p=I.ivCurCrypt,o=I.debiBuf,e=I.bufPos,f=0}for(let I=1;I<=Lc;)if(f<8)o[f],l[f],f++,I++;else if(f===8){if(e>=i.length)break;let R=Yp(i,e,l,p,o,t);if(!R.success)break;l=R.ivPreCrypt,p=R.ivCurCrypt,o=R.debiBuf,e=R.bufPos,f=0}return a}function Yp(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,s),bufPos:t+8}}var v_=typeof TextDecoder!="undefined"?new TextDecoder:void 0;function iR({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:eR(new Uint8Array(l))||(v_?v_.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 oR=Object.prototype.hasOwnProperty,Cc=i=>typeof i=="function",jn=i=>i===void 0,sR=i=>typeof i=="boolean",nR=function(i){if(!i||typeof i!="object"||Object.prototype.toString.call(i)!="[object Object]")return!1;let t=Object.getPrototypeOf(i);if(t===null)return!0;let e=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return typeof e=="function"&&e instanceof e&&Function.prototype.toString.call(e)===Function.prototype.toString.call(Object)};function aR(i){if(i==null)return!0;if(typeof i=="boolean")return!1;if(typeof i=="number")return i===0;if(typeof i=="string"||typeof i=="function"||Array.isArray(i))return i.length===0;if(i instanceof Error)return i.message==="";if(nR(i))switch(Object.prototype.toString.call(i)){case"[object File]":case"[object Map]":case"[object Set]":return i.size===0;case"[object Object]":for(let t in i)if(oR.call(i,t))return!1;return!0}return!1}var cR=0,dR=1,C_=2;function uR({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,_=cR,I=(R,y)=>b(this,null,function*(){let N=n||this;try{let P=yield i.apply(N,a);p>0&&s&&s.call(this,p),p=0,R(P)}catch(P){let W=()=>{clearTimeout(f),p=0,_=C_,y(P)},G=()=>{_!==C_&&p<(Cc(d)?d():d)?(p++,_=dR,Cc(r)&&r.call(this,p,W),f=window.setTimeout(()=>{f=-1,I(R,y)},Cc(l)?l(p):l)):(W(),Cc(o)&&o.call(this,P))};Cc(e)?e.call(this,{error:P,retry:G,reject:y,retryFuncArgs:a,retriedCount:p}):G()}});return new Promise(I)}}var lR=uR,Zp=class H_{constructor(t){st(this,"_parentPath"),st(this,"userId"),st(this,"remoteUserId"),st(this,"id"),st(this,"sdkAppId"),st(this,"type"),st(this,"isLocal"),this.id=t.id,this.userId=t.userId,this.sdkAppId=t.sdkAppId,this.remoteUserId=t.remoteUserId,this.isLocal=!sR(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 H_({id:t.id,userId:jn(t.userId)?this.userId:t.userId,sdkAppId:jn(t.sdkAppId)?this.sdkAppId:t.sdkAppId,type:jn(t.type)?this.type:t.type,isLocal:jn(t.isLocal)?this.isLocal:t.isLocal,remoteUserId:jn(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}`:""}]`),qR.log(t,e,jn(this.userId)||aR(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)}},Ti=typeof navigator=="undefined"?"":navigator.userAgent,ve=i=>new RegExp(i,"i").test(Ti),Rt=i=>{if(ve(i)){let t=new RegExp(`${i}\\/([\\d.]+)`),e=Ti.match(t);if(e&&e[1])return e[1]}return""},Al=i=>{if(ve(i)){let t=new RegExp(`${i}\\/(\\d+)`),e=Ti.match(t);if(e&&e[1])return parseFloat(e[1])}return NaN},N_=/AppleWebKit\/([\d.]+)/i.exec(Ti),mR=N_?parseFloat(N_[1]):NaN,W_=ve("iPad"),G_=typeof navigator!="undefined"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&ve("Macintosh"),j_=ve("iPhone")&&!W_,hR=ve("iPod"),df=j_||W_||hR||G_,xc=ve("Android"),q_=(function(){if(xc){let i=Ti.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})(),AV=xc&&ve("webkit")&&q_<2.3,yV=xc&&q_<5&&mR<537,pR=ve("Firefox"),fR=Rt("Firefox"),bV=Al("Firefox"),z_=ve("Edge"),gR=Rt("Edge"),J_=ve("Edg"),ER=Rt("Edg"),RV=Al("Edg"),X_=ve("SogouMobileBrowser"),_R=Rt("SogouMobileBrowser"),Q_=ve("MetaSr\\s"),TR=Rt("MetaSr\\s"),Us=ve("TBS"),IR=Rt("TBS"),Y_=ve("XWEB"),SR=Rt("XWEB"),vV=ve("MSIE\\s8\\.0"),AR=ve("MSIE\\/\\d+"),CV=(function(){if(AR){let i=/MSIE\s(\d+)\.\d/.exec(Ti),t=i&&parseFloat(i[1]);return!t&&/Trident\/7.0/i.test(Ti)&&/rv:11.0/.test(Ti)&&(t=11),t}return NaN})(),yR=ve("(micromessenger|webbrowser)"),bR=Rt("MicroMessenger"),uf=!Us&&ve("MQQBrowser")&&ve("COVC"),lf=!Us&&ve("MQQBrowser")&&!ve("COVC"),D_=lf||uf?Rt("MQQBrowser"):"",Z_=!Us&&ve(" QQBrowser"),RR=Rt(" QQBrowser"),K_=!Us&&ve("QQBrowserLite"),vR=Rt("QQBrowserLite"),eT=!Us&&ve("MQBHD"),CR=Rt("MQBHD"),NV=ve("Windows"),DV=!df&&ve("MAC OS X"),wV=!xc&&ve("Linux"),MV=ve("CrOS"),OV=ve("MicroMessenger"),PV=ve("UCBrowser"),LV=ve("Electron"),tT=ve("MiuiBrowser"),NR=Rt("MiuiBrowser"),rT=ve("HuaweiBrowser"),xV=ve("Huawei")||ve("HUAWEI"),kV=ve("Honor")||ve("HONOR"),DR=Rt("HuaweiBrowser"),iT=ve("SamsungBrowser"),wR=Rt("SamsungBrowser"),oT=ve("HeyTapBrowser"),MR=Rt("HeyTapBrowser"),sT=ve("VivoBrowser"),OR=Rt("VivoBrowser"),UV=ve("OpenHarmony"),VV=Rt("OpenHarmony"),PR=()=>Al("Chrome"),w_=ve("CriOS"),mf=ve("Chrome"),LR=!z_&&!Q_&&!X_&&!Us&&!Y_&&!J_&&!Z_&&!tT&&!rT&&!iT&&!oT&&!sT&&mf,xR=ve("HeadlessChrome"),M_=PR(),FV=mf&&M_>=128&&M_<=143,kR=Rt("Chrome"),BV=Al("Electron"),UR=!mf&&!lf&&!uf&&!K_&&!eT&&ve("Safari"),nT=Rt("Version"),$V=/Android.*(wv|.0.0.0)/.test(Ti),aT=(()=>{if(G_)return nT;if(df){let i=Ti.match(/OS (\d+)_(\d+)/i);if(i&&i[1]){let t=i[1];return i[2]&&(t+=`.${i[2]}`),t}}return""})(),HV=Number(aT.split(".")[0]),WV=(()=>{let i=Number(aT.split(".")[0]);return i===14||i===13})(),GV=typeof location!="undefined"&&(location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1"),jV=VR();function VR(){let i=new Map([[pR,["Firefox",fR]],[J_,["Edg",ER]],[LR,["Chrome",kR]],[w_,["ChiOS",Rt("CriOS")]],[UR&&!w_,["Safari",nT]],[Us,["TBS",IR]],[Y_,["XWEB",SR]],[yR&&j_,["WeChat",bR]],[Z_,["QQ(Win)",RR]],[lf,["QQ(Mobile)",D_]],[uf,["QQ(Mobile X5)",D_]],[K_,["QQ(Mac)",vR]],[eT,["QQ(iPad)",CR]],[tT,["MI",NR]],[rT,["HW",DR]],[iT,["Samsung",wR]],[oT,["OPPO",MR]],[sT,["VIVO",OR]],[z_,["EDGE",gR]],[X_,["SogouMobile",_R]],[Q_,["Sogou",TR]]]),t="unknown",e="unknown";return i.has(!0)&&([t,e]=i.get(!0)),{name:t,version:e}}var FR=k_(U_(),1),BR=new FR.default,ko=BR,El=V_,$R=class{constructor(){st(this,"enable",!1),st(this,"ssoFailCount",0),ko.on("22",({schedule:i})=>{var t;(t=i==null?void 0:i.config)!=null&&t.sso&&ko.emit("266",{enable:!0})}),ko.on("266",({enable:i})=>{this.enable=i})}handleUploadFailed(){this.ssoFailCount++,this.ssoFailCount>3&&ko.emit("266",{enable:!1})}},O_=new $R,HR="%cTRTC%c%s",WR="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",GR="display: inline",cT=class dT{constructor(){st(this,"_isEnableUploadLog",!0),st(this,"_localJoinedUser",new Map),st(this,"_queue",[]),st(this,"_timeoutId",-1),st(this,"_logLevel",1),st(this,"_logLevelToUpload",2),xb||kb||(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){ko.on(El.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)}),ko.on(El.JOIN_START,({params:t})=>{this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload()}),ko.on(El.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(af(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 b(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:Zb(),sdkAppId:String(a),userId:n,version:Lb,log:d.map(_=>_.log).join(`
93
- `)},p=JSON.stringify(l),f=O_.enable?ZR(l,2002,a):p;yield this.uploadLogWithRetry(f,a,f instanceof Uint8Array,p),d.forEach(_=>_.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 lR({retryFunction:()=>iR({url:JR(e,Hb.LOG),body:t,timeout:5e3,priority:"low"}).then(s=>{r&&s.data!=="ok"&&(O_.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(B_()),`[${Kb(e)}] <${ks[t]}>`}getLogLevel(){return this._logLevel}setLogLevel(t){uT(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(af(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};ko.emit(El.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";dT.PRINT_LOG_TAG?console[a](HR,WR,GR,...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 Zp){let e=t,{parent:r}=e,o=yb(e,["parent"]),s=new Zp(o);return s.bindParent(r),s}return new Zp(t)}checkURLParam(){let t=new URLSearchParams(location.search).get("logLevelToUpload"),e=t?Number(t):-1;ks[e]&&(this._logLevelToUpload=e)}getQueue(){return this._queue}};st(cT,"PRINT_LOG_TAG",!(df||xc||xR));var jR=cT,qR=new jR,zR=i=>Number(i)<14e8,JR=function(i,t){let e;return e=Ub||(zR(i)?$b:Bb),`${e}/v5/AVQualityReportSvc/C2S?random=${Math.floor(Math.random()*ni(2,31))}&sdkappid=${i}&cmdtype=${t}`},qV=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},uT=i=>i===void 0,af=i=>typeof i=="string",XR=i=>typeof i=="number",zV=typeof HTMLMediaElement!="undefined"&&"setSinkId"in HTMLMediaElement.prototype;function QR(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var{toString:JV}=Object.prototype;function YR(i,t,e,r){let o={data:i,random:Math.floor(Math.random()*2147483648),sdkAppId:e};return uT(r)||(o=wc(Dc({},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 ZR(i,t,e,r){try{let o=YR(i,t,e,r);return Jb(of(o),e)}catch(o){return JSON.stringify(i)}}var lT=class mT{constructor(t){this.core=t,st(this,"contextMap",new Map),st(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 mT.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 Pb(wc(Dc({},e),{wasmPath:`${s}/videodec.wasm`}));case"webCodecs":return new qn;case"mse":throw new Error("mse decoder not supported yet");default:throw new Error("Unsupported decoder type")}}start(t){this.decodeProcessorMap.set(t.track,this.decode(t)),this.core.room.videoManager.addDecodeProcessor({processor:({frame:e,track:r})=>{var o;return((o=this.decodeProcessorMap.get(r))==null?void 0:o({frame:e,track:r}))||e},type:3})}decode(t){let{pipe:e,take:r,subscribe:o}=this.core.rx;return({frame:s,track:n})=>{if(n!==t.track||s.type==="empty")return s;if(this.contextMap.has(n))return this.contextMap.get(n).decode(s);let a=this.core.room.videoManager.createDecodeContext(wc(Dc({},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=QR()-t.startPerformanceTime,{renderFreezeTotal:o,dataFreezeTotal:s}=this.getRemoteTrackFreezeDuration(e,t),n=`report health data: ${t.track.userId} ${t.track.streamType} ${t.type}+${t.renderer} goodType\uFF1A${t.goodType} ${t.failedReason?`failedReason: ${t.failedReason}`:""}`;r&&(this.core.kvStatManager.addNumber({key:514850,value:Math.floor(o/r*100),split:1,max:100}),n+=` RENDER_FREEZE_RATE: ${Math.floor(o/r*100)}%`),r&&(this.core.kvStatManager.addNumber({key:514851,value:Math.floor(s/r*100),split:1,max:100}),n+=` DATA_FREEZE_RATE: ${Math.floor(s/r*100)}%`),t.inputFrameCount&&(this.core.kvStatManager.addNumber({key:514852,value:Math.floor(t.decodedFrameCount/t.inputFrameCount*100),split:1,max:100}),n+=` VIDEO_CONSUME_RENDER_RATE: ${Math.floor(t.decodedFrameCount/t.inputFrameCount*100)}%`),this.core.log.info(n)}addKVReportBeforeExitRoom({room:t}){t===this.core.room&&this.contextMap.forEach((e,r)=>{this.report(e,r)})}update(t){let e=this.contextMap.get(t.track);e&&(t.type!=="mock"?(e.close("update"),this.contextMap.set(t.track,this.core.room.videoManager.createDecodeContext(wc(Dc({},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)}};st(lT,"Name","TRTCVideoDecoder");var hf=lT;var qT=ai(mi());function pf({timesInSecond:i,maxSizeInSecond:t,getSize:e}){return Pe((r,o)=>{let s=new WeakMap;return x.on(V.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:z.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 KR="2026-01-27 13:36:44",hT=!0,pT=function(){var i;if(hT){hT=!1,B.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${ir}/en/index.html`),console.info(`* Changelog: ${ir}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),B.info("TRTC Web SDK Version:",ft),zr||B.debug("Build Time:",KR);let t=`UA: ${navigator.userAgent}
93
+ `)},p=JSON.stringify(l),f=O_.enable?ZR(l,2002,a):p;yield this.uploadLogWithRetry(f,a,f instanceof Uint8Array,p),d.forEach(_=>_.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 lR({retryFunction:()=>iR({url:JR(e,Hb.LOG),body:t,timeout:5e3,priority:"low"}).then(s=>{r&&s.data!=="ok"&&(O_.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(B_()),`[${Kb(e)}] <${ks[t]}>`}getLogLevel(){return this._logLevel}setLogLevel(t){uT(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(af(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};ko.emit(El.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";dT.PRINT_LOG_TAG?console[a](HR,WR,GR,...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 Zp){let e=t,{parent:r}=e,o=yb(e,["parent"]),s=new Zp(o);return s.bindParent(r),s}return new Zp(t)}checkURLParam(){let t=new URLSearchParams(location.search).get("logLevelToUpload"),e=t?Number(t):-1;ks[e]&&(this._logLevelToUpload=e)}getQueue(){return this._queue}};st(cT,"PRINT_LOG_TAG",!(df||xc||xR));var jR=cT,qR=new jR,zR=i=>Number(i)<14e8,JR=function(i,t){let e;return e=Ub||(zR(i)?$b:Bb),`${e}/v5/AVQualityReportSvc/C2S?random=${Math.floor(Math.random()*ni(2,31))}&sdkappid=${i}&cmdtype=${t}`},qV=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},uT=i=>i===void 0,af=i=>typeof i=="string",XR=i=>typeof i=="number",zV=typeof HTMLMediaElement!="undefined"&&"setSinkId"in HTMLMediaElement.prototype;function QR(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var{toString:JV}=Object.prototype;function YR(i,t,e,r){let o={data:i,random:Math.floor(Math.random()*2147483648),sdkAppId:e};return uT(r)||(o=wc(Dc({},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 ZR(i,t,e,r){try{let o=YR(i,t,e,r);return Jb(of(o),e)}catch(o){return JSON.stringify(i)}}var lT=class mT{constructor(t){this.core=t,st(this,"contextMap",new Map),st(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 mT.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 Pb(wc(Dc({},e),{wasmPath:`${s}/videodec.wasm`}));case"webCodecs":return new qn;case"mse":throw new Error("mse decoder not supported yet");default:throw new Error("Unsupported decoder type")}}start(t){this.decodeProcessorMap.set(t.track,this.decode(t)),this.core.room.videoManager.addDecodeProcessor({processor:({frame:e,track:r})=>{var o;return((o=this.decodeProcessorMap.get(r))==null?void 0:o({frame:e,track:r}))||e},type:3})}decode(t){let{pipe:e,take:r,subscribe:o}=this.core.rx;return({frame:s,track:n})=>{if(n!==t.track||s.type==="empty")return s;if(this.contextMap.has(n))return this.contextMap.get(n).decode(s);let a=this.core.room.videoManager.createDecodeContext(wc(Dc({},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=QR()-t.startPerformanceTime,{renderFreezeTotal:o,dataFreezeTotal:s}=this.getRemoteTrackFreezeDuration(e,t),n=`report health data: ${t.track.userId} ${t.track.streamType} ${t.type}+${t.renderer} goodType\uFF1A${t.goodType} ${t.failedReason?`failedReason: ${t.failedReason}`:""}`;r&&(this.core.kvStatManager.addNumber({key:514850,value:Math.floor(o/r*100),split:1,max:100}),n+=` RENDER_FREEZE_RATE: ${Math.floor(o/r*100)}%`),r&&(this.core.kvStatManager.addNumber({key:514851,value:Math.floor(s/r*100),split:1,max:100}),n+=` DATA_FREEZE_RATE: ${Math.floor(s/r*100)}%`),t.inputFrameCount&&(this.core.kvStatManager.addNumber({key:514852,value:Math.floor(t.decodedFrameCount/t.inputFrameCount*100),split:1,max:100}),n+=` VIDEO_CONSUME_RENDER_RATE: ${Math.floor(t.decodedFrameCount/t.inputFrameCount*100)}%`),this.core.log.info(n)}addKVReportBeforeExitRoom({room:t}){t===this.core.room&&this.contextMap.forEach((e,r)=>{this.report(e,r)})}update(t){let e=this.contextMap.get(t.track);e&&(t.type!=="mock"?(e.close("update"),this.contextMap.set(t.track,this.core.room.videoManager.createDecodeContext(wc(Dc({},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)}};st(lT,"Name","TRTCVideoDecoder");var hf=lT;var qT=ai(mi());function pf({timesInSecond:i,maxSizeInSecond:t,getSize:e}){return Pe((r,o)=>{let s=new WeakMap;return x.on(V.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:z.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 KR="2026-01-27 14:14:19",hT=!0,pT=function(){var i;if(hT){hT=!1,B.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${ir}/en/index.html`),console.info(`* Changelog: ${ir}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),B.info("TRTC Web SDK Version:",ft),zr||B.debug("Build Time:",KR);let t=`UA: ${navigator.userAgent}
94
94
  CPU core: ${navigator.hardwareConcurrency}, GPU: ${To()}`;if(it&&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`),B.info(t),B.info(`URL: ${location.href}${((i=self.frameElement)==null?void 0:i.tagName)==="IFRAME"?" in iframe":""}`),gs().then(r=>{r&&B.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=(U=>(U[U.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",U[U.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",U[U.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",U[U.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",U[U.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",U[U.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",U[U.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",U[U.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",U[U.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",U[U.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",U[U.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",U[U.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",U[U.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",U[U.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",U[U.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",U[U.INVALID_ROOM_ID_REQUIRED=5015]="INVALID_ROOM_ID_REQUIRED",U[U.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",U[U.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",U[U.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",U[U.INVALID_ROOM_ID_TYPE_MISMATCH=5019]="INVALID_ROOM_ID_TYPE_MISMATCH",U[U.INVALID_ROOM_ID_DUPLICATE=5020]="INVALID_ROOM_ID_DUPLICATE",U[U.INVALID_OPERATION=5100]="INVALID_OPERATION",U[U.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",U[U.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",U[U.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",U[U.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",U[U.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",U[U.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",U[U.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",U[U.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",U[U.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",U[U.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",U[U.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",U[U.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",U[U.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",U[U.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",U[U.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",U[U.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",U[U.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",U[U.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",U[U.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",U[U.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",U[U.DEVICE_ERROR=5300]="DEVICE_ERROR",U[U.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",U[U.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",U[U.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",U[U.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",U[U.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",U[U.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",U[U.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",U[U.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",U[U.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",U[U.NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX=5310]="NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX",U[U.SERVER_ERROR=5400]="SERVER_ERROR",U[U.NEED_TO_BUY=5401]="NEED_TO_BUY",U[U.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",U[U.OPERATION_FAILED=5500]="OPERATION_FAILED",U[U.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",U[U.REJOIN_FAILED=5502]="REJOIN_FAILED",U[U.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",U[U.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",U[U.VIDEO_ENCODE_FAILED=5505]="VIDEO_ENCODE_FAILED",U[U.AUDIO_ENCODE_FAILED=5506]="AUDIO_ENCODE_FAILED",U[U.VIDEO_DECODE_FAILED=5507]="VIDEO_DECODE_FAILED",U[U.AUDIO_DECODE_FAILED=5508]="AUDIO_DECODE_FAILED",U[U.OPERATION_ABORT=5998]="OPERATION_ABORT",U[U.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",U))(Sr||{});function gT({code:i,params:t,enableDocLink:e=!1}){let r="",o,s=Sr[i];try{o=fT[s]}catch(n){o=fT.UNKNOWN_ERROR}return Xe(o)?r=o(t):Oe(o)&&(r=o),t.fnName&&!r.includes(t.fnName)&&(r[r.length-1]!=="."&&(r+="."),r+=` thrown from ${t.fnName}()`),e&&(r+=" doc:"),r}var fT=Te(Q({},sr),{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 ff=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=gT({code:e===oe.SERVER_ERROR?e:r||e,params:Q({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"},_={startLocalVideo:"webcam",startLocalAudio:"microphone"},I=document.createElement("a");ps?I.href=`ms-settings:privacy-${_[this.functionName]}`:jr&&(I.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${f[this.functionName]}`),I.href.length>0&&I.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 z.INVALID_PARAMETER:a.code=oe.INVALID_PARAMETER,a.message=e.message;break;case z.INVALID_OPERATION:a.code=oe.INVALID_OPERATION;break;case z.NOT_SUPPORTED:case z.NOT_SUPPORTED_H264:a.code=oe.ENV_NOT_SUPPORTED,e.getCode()===z.NOT_SUPPORTED_H264&&(a.extraCode=e.message.includes(sr.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case z.JOIN_ROOM_FAILED:a.messageParams={fnParams:o};case z.SERVER_TIMEOUT:case z.SWITCH_ROLE_FAILED:case z.SWITCH_ROOM_FAILED:a.code=oe.SERVER_ERROR,a.extraCode=e.getExtraCode();break;case z.API_CALL_ABORTED:a.code=oe.OPERATION_ABORT;break;case z.DEVICE_NOT_FOUND:case z.DEVICE_AUTO_RECOVER_FAILED:case z.INITIALIZE_FAILED:a.code=5300,e.name&&(a.extraCode=ev(e.name));break;case z.VIDEO_ENCODE_FAILED:a.extraCode=5505;case z.AUDIO_ENCODE_FAILED:a.extraCode=5506,a.code=oe.OPERATION_FAILED;break;case z.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 ev(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 ne=ff;function dr(i){return i==="sub"?"auxiliary":i==="auxiliary"?"sub":"main"}function kc(i){return i===Vs.QOS_PREFERENCE_CLEAR?"detail":i===Vs.QOS_PREFERENCE_SMOOTH?"motion":""}function Jn(i,t){let e=t?Am:ya;return Wm(i)?Q(Q({},e),i):Fr[i]?Fr[i]:e}var ET={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}}},_T={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}}},Xn={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(i,t,e){if(Oe(i)&&!document.getElementById(i))throw new ne({code:oe.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:t}})}},TT={name:"userId",required:!0,type:"string"},IT={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 Qn(i,t){if(!i)throw new ne({code:oe.INVALID_OPERATION,extraCode:5101,fnName:t})}function ST(i,t,e){if(!i)throw new ne({code:oe.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:e}})}function AT(i,t,e){if(!(/^[1-9]\d*$/.test(String(i))&&i<4294967295))throw new ne({code:oe.INVALID_PARAMETER,extraCode:5013,fnName:t,messageParams:{key:e}})}function yT(i,t,e){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(i))throw new ne({code:oe.INVALID_PARAMETER,extraCode:5012,fnName:t,messageParams:{key:e}})}var I1={type:"number",notLessThanZero:!0},tv=(i,t)=>i.width*i.height>=t.width*t.height&&i.frameRate>=t.frameRate&&i.bitrate>=t.bitrate;function bT(i){var r;if(!((r=i==null?void 0:i.option)!=null&&r.small))return;if(!Du()){B.warn("small stream is not supported"),delete i.option.small;return}let t=Jn(i.option.profile),e=Jn(i.option.small,!0);if(!tv(t,e)){B.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 rv={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 ne({code:oe.INVALID_OPERATION,extraCode:5104,fnName:e});if(i.roomId){if(Oe(i.roomId))throw new ne({code:oe.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:t}});AT(i.roomId,e,t)}else if(i.strRoomId)yT(i.strRoomId,e,t);else throw new ne({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:Xn,mute:{type:["boolean","string"]},publish:{type:"boolean"},capture:{required:!1,type:"boolean"},option:ET},validate(i){var t,e;if(!((t=i==null?void 0:i.option)!=null&&t.videoTrack)&&Gi())throw new ne({code:oe.ENV_NOT_SUPPORTED,extraCode:5201});(e=i==null?void 0:i.option)!=null&&e.small&&bT(i)}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:Te(Q({},Xn),{required:!1}),publish:{type:"boolean"},capture:{required:!1,type:"boolean"},mute:{type:["boolean","string"]},option:ET},validate(i){var t;(t=i==null?void 0:i.option)!=null&&t.small&&bT(i)}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},mute:{type:["boolean","string"],values:[!0,!1,"microphone"]},muteKeepVolumeDetection:{type:"boolean"},option:IT},validate(i){var t;if(!((t=i==null?void 0:i.option)!=null&&t.audioTrack)&&Gi())throw new ne({code:oe.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:["boolean","string"],values:[!0,!1,"microphone"]},muteKeepVolumeDetection:{type:"boolean"},option:IT}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:Xn,publish:{type:"boolean"},option:_T},validate(i,t,e,r,o){var s;if(!((s=i==null?void 0:i.option)!=null&&s.videoTrack)){if(Gi())throw new ne({code:oe.ENV_NOT_SUPPORTED,extraCode:5201});if(!tc())throw new ne({code:oe.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:Xn,publish:{type:"boolean"},option:_T}},muteRemoteAudio:[TT,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[TT,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:Xn,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){Qn(this._room.isJoined,e);let r=this._room.remotePublishedUserMap.get(i.userId);if(ST(!!r,e,i),r&&(i.streamType==="main"&&!r.muteState.videoAvailable||i.streamType==="sub"&&!r.muteState.hasAuxiliary))throw new ne({code:oe.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:i}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:Te(Q({},Xn),{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){Qn(this._room.isJoined,e);let r=this._room.remotePublishedUserMap.get(i.userId);if(ST(!!r,e,i),r){if(i.streamType==="main"&&!r.muteState.videoAvailable||i.streamType==="sub"&&!r.muteState.hasAuxiliary)throw new ne({code:oe.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:i}});if(i.option){let o=i.streamType==="main"?r.remoteVideoTrack:r.remoteAuxiliaryTrack;if((i.option.pictureInPicture||i.option.fullScreen||i.option.fullScreen)&&(!o.isSubscribed||!o.player.isPlaying))throw new ne({code:oe.INVALID_OPERATION,message:"cannot set pictureInPicture or fullScreen when remote video is not playing"})}}}},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 ne({code:oe.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(i,t,e){Qn(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(!ic)throw new ne({code:oe.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new ne({code:oe.INVALID_OPERATION,fnName:e,extraCode:5108});if(i.byteLength>1e3)throw new ne({code:oe.INVALID_PARAMETER,extraCode:5018,fnName:e});if(i.byteLength===0)throw new ne({code:oe.INVALID_PARAMETER,extraCode:5017,messageParams:{key:t},fnName:e});Qn(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 ne({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 ne({code:oe.INVALID_PARAMETER,extraCode:5018,fnName:e});if(i.byteLength===0)throw new ne({code:oe.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:t}})}}},validate(i,t,e){if(Qn(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new ne({code:oe.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:t}})}},switchRoom:{name:"switchRoomConfig",type:"object",required:!0,validate(i,t,e){if(Qn(this._room.isJoined,e),this._room.useStringRoomId&&i.strRoomId===this._room.roomId||!this._room.useStringRoomId&&i.roomId===Number(this._room.roomId))throw new ne({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 ne({code:oe.INVALID_PARAMETER,extraCode:5019,fnName:e,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(i.roomId)AT(i.roomId,e,t);else if(i.strRoomId)yT(i.strRoomId,e,t);else throw new ne({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}}}},wt={TRTC:rv};var Qt=class extends Error{};function iv(i,t){let e=ns(i);for(let r=0;r<t.length;r++)$r(e[r],t[r]);return e}function ov(i){this._resolve=Promise.resolve(i)}function sv(i){this._reject=Promise.reject(i)}var Uo=class Uo{constructor(t,e){this.instance=t;this.group=e;m(this,"started",!1);m(this,"ops",[]);m(this,"startSame",()=>!0);m(this,"mergeUpdate",iv);let r=Uo.instances.get(t);r?r.set(e,this):Uo.instances.set(t,new Map([[e,this]]))}static get(t,e){if(!e)return;let r=Uo.instances.get(t);return r&&r.get(e)||new Uo(t,e)}static gets(t,e){let r=Uo.instances.get(t),o=[];return r&&r.forEach((s,n)=>{e.test(n)&&o.push(s)}),o}action(t,e,r){let o=a=>{var d;return t===0?this.started=!0:t===3&&(this.started=!1),this.ops.shift(),(d=this.currentOp)==null||d.action(),a},s=a=>{var d,l;throw this.ops.shift(),t===0&&((d=this.currentOp)==null?void 0:d.type)===2&&this.ops.shift().reject(new Qt("start failed")),(l=this.currentOp)==null||l.action(),a},n={type:t,action:()=>e(...n.args).then(o,s),args:r,resolve:ov,reject:sv};try{switch(this.state){case 1:if(t===0)throw new Qt("already started");break;case 4:if(t===2)throw new Qt("not started");break;default:return this.cacheOp(n)}}catch(a){return Promise.reject(a)}return this.ops.push(n),n.promise=e(...n.args).then(o,s)}cacheOp(t){if(this.ops.length===1)switch(this.state){case 0:case 2:if(t.type===0)throw new Qt("already start");break;case 3:switch(t.type){case 2:throw new Qt("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new Qt("unknown state")}else switch(t.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let r=new Qt("keep stop");if(this.ops.slice(1).forEach(o=>o.reject(r)),this.ops=this.ops.slice(0,1),this.state===3)return this.currentOp.promise}break;case 2:switch(this.lastOpType){case 2:return this.lastOp.args=this.mergeUpdate(this.lastOp.args,t.args),this.lastOp.promise;case 3:throw new Qt("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new Qt("start not allowed after update");case 0:throw new Qt("duplicate start");case 3:if(this.startSame(this.currentOp.args,t.args))throw this.ops.pop().reject(new Qt("keep start")),new Qt("already start")}}t.promise=new Promise((r,o)=>{t._resolve?t._resolve.then(r):t.resolve=r,t._reject?t._reject.catch(o):t.reject=o});let{action:e}=t;return t.action=()=>e().then(t.resolve,t.reject),this.ops.push(t),t.promise}get lastOp(){return this.ops[this.ops.length-1]}get lastOpType(){return this.lastOp.type}get currentOp(){return this.ops[0]}get state(){return this.currentOp?this.currentOp.type:this.started?1:4}};m(Uo,"instances",new WeakMap);var Zi=Uo;var bl=new WeakMap,Rl=(i,t)=>{if(t instanceof Qt){let{stack:e}=t;t=new ne({code:oe.OPERATION_ABORT,message:`${i} abort: ${t.message}`,fnName:i}),e&&(t.stack+=e.substr(e.indexOf(`
96
96
  `)))}throw t};function Vo(i,t){return Pe((e,r)=>function(...o){let s=Zi.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(Rl.bind(null,r))):e.apply(this,o)})}function Bs(i,t){let{merge:e,debounce:r}=t||{};return Pe((o,s)=>function(...n){let a=Zi.get(this,typeof i=="string"?i:i.call(this,...n));if(!a)return o.apply(this,n);if(e&&(a.mergeUpdate=e.bind(this)),r&&r.isNeedToDebounce.apply(this,n)){let{delay:d,getKey:l}=r;return new Promise((p,f)=>{var R,y;let _=(R=bl.get(this))==null?void 0:R.get(l(...n));if(_){let{timeoutId:N,resolve:P}=_;clearTimeout(N),P()}let I=setTimeout(()=>{if(a.state===3||a.state===4)return p();a.action(2,o.bind(this),n).catch(Rl.bind(null,s)).then(p,f)},d);bl.has(this)?(y=bl.get(this))==null||y.set(l(...n),{timeoutId:I,resolve:p}):bl.set(this,new Map([[l(...n),{timeoutId:I,resolve:p}]]))})}return a.action(2,o.bind(this),n).catch(Rl.bind(null,s))})}function Fo(i){return Pe((t,e)=>function(...r){let o=typeof i=="function"?i.call(this,...r):i;if(o instanceof RegExp)return Promise.all(Zi.gets(this,o).map(n=>n.action(3,()=>Promise.resolve(),r))).then(()=>t.call(this,...r));let s=Zi.get(this,o);return s?s.action(3,t.bind(this),r).catch(Rl.bind(null,e)):t.apply(this,r)})}function Bo(){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: ${ir}/en/TRTC.html#.${t}`;r.warn(o)},e}}var te={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",REALTIME_TRANSCRIBER_MESSAGE:"realtime-transcriber-message",REALTIME_TRANSCRIBER_STATE_CHANGED:"realtime-transcriber-state-changed",PICTURE_IN_PICTURE_STATE_CHANGED:"picture-in-picture-state-changed",FULL_SCREEN_STATE_CHANGED:"full-screen-state-changed"},RT=new Set([te.AUDIO_VOLUME,te.AUDIO_FRAME,te.NETWORK_QUALITY,te.STATISTICS,te.SEI_MESSAGE,te.CUSTOM_MESSAGE,te.LAYER_DATA]);var _f={};vi(_f,{ScheduleRequestType:()=>NT,getAbilityConfig:()=>cv,getScheduleDomain:()=>Nl,isNeedToSchedule:()=>vl,scheduleProxy:()=>ei,sendScheduleRequest:()=>Ef,setIsNeedToSchedule:()=>Ki,setScheduleProxy:()=>Cl});var gf=null,CT=0,nv=48*3600*1e3,vl=!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: ${To()}`;if(it&&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 Fc=class{constructor(t){m(this,"audioPlayer");m(this,"videoPlayer");m(this,"log");this.audioPlayer=t.audioPlayer,this.videoPlayer=t.videoPlayer,this.log=t.log.createChild({id:"pip"}),this.videoPlayer.on(ue.USER_RESUME_IN_PIP_OR_FULL_SCREEN,this.handleUserResumeInPIPOrFullScreen,this),this.videoPlayer.on(ue.USER_PAUSE_IN_PIP_OR_FULL_SCREEN,this.handleUserPauseInPIPOrFullScreen,this),this.videoPlayer.on(ue.ENTER_PICTURE_IN_PICTURE,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.on(ue.ENTER_FULL_SCREEN,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.on(ue.LEAVE_PICTURE_IN_PICTURE,this.handleLeavePIP,this),this.videoPlayer.on(ue.LEAVE_FULL_SCREEN,this.handleLeaveFullScreen,this),this.videoPlayer.on(ue.VOLUME_CHANGE,this.handleVolumeChange,this)}handleUserResumeInPIPOrFullScreen(){this.audioPlayer.isPaused&&(this.log.warn(`resume audio in ${this.videoPlayer.isPictureInPicture()?"pip":"fullscreen"}`),this.audioPlayer.doResume()),rt&&_o&&this.videoPlayer.resetSrcObjectToReplay()}handleUserPauseInPIPOrFullScreen(){this.audioPlayer.isPaused||(this.log.warn(`pause audio in ${this.videoPlayer.isPictureInPicture()?"pip":"fullscreen"}`),this.audioPlayer.doPause())}handleEnterPIPOrFullScreen(){this.videoPlayer.element&&this.audioPlayer.muted!==this.videoPlayer.element.muted&&(this.log.warn(`sync video muted to ${this.audioPlayer.muted} when enter ${this.videoPlayer.isPictureInPicture()?"pip":"fullscreen"}`),this.videoPlayer.element.muted=this.audioPlayer.muted)}handleLeavePIP(){this.audioPlayer.isPaused&&!this.audioPlayer.isPausedByUserCall&&(this.log.warn("resume after leave pip"),this.audioPlayer.doResume()),this.videoPlayer.isPaused&&!this.videoPlayer.isPausedByUserCall&&(this.log.warn("resume video after leave pip"),this.videoPlayer.doResume())}handleLeaveFullScreen(){this.audioPlayer.isPaused&&!this.audioPlayer.isPausedByUserCall&&(this.log.warn("resume audio after leave fullscreen"),this.audioPlayer.doResume()),this.videoPlayer.isPaused&&!this.videoPlayer.isPausedByUserCall&&(this.log.warn("resume video after leave fullscreen"),rt&&_o?this.videoPlayer.resetSrcObjectToReplay():this.videoPlayer.doResume())}handleVolumeChange(t){t.muted!==void 0&&this.audioPlayer.muted!==t.muted&&(this.log.warn(`sync audio muted to ${t.muted} in ${this.videoPlayer.isPictureInPicture()?"pip":"fullscreen"}`),this.audioPlayer.setMuted(t.muted))}destroy(){this.videoPlayer.off(ue.USER_RESUME_IN_PIP_OR_FULL_SCREEN,this.handleUserResumeInPIPOrFullScreen,this),this.videoPlayer.off(ue.USER_PAUSE_IN_PIP_OR_FULL_SCREEN,this.handleUserPauseInPIPOrFullScreen,this),this.videoPlayer.off(ue.ENTER_PICTURE_IN_PICTURE,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.off(ue.ENTER_FULL_SCREEN,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.off(ue.LEAVE_PICTURE_IN_PICTURE,this.handleLeavePIP,this),this.videoPlayer.off(ue.LEAVE_FULL_SCREEN,this.handleLeaveFullScreen,this),this.videoPlayer.off(ue.VOLUME_CHANGE,this.handleVolumeChange,this)}};var OT=!1,PT;function LT({TRTC:i,room:t,errorModule:e,assetsPath:r}){return{TRTC:i,LocalMixVideoTrack:Ls,LocalVideoTrack:Ir,LocalScreenTrack:Ei,room:t,assetsPath:r,fileDownloader:Vc,innerEmitter:x,INNER_EVENT:V,constants:Nm,environment:bn,utils:Wp,eventLogger:Ue,log:this.room.getLogger(),loggerManager:B,errorModule:e,kvStatManager:J,rtcDectection:Ro,trtc:this,rx:Bp,enums:Ih,schedule:_f,getDevices:Pn,initVisionTaskRegistry:(o,s,n="/mediapipe/vision.js")=>b(this,null,function*(){!window.VisionTaskRegistry&&!OT&&(OT=!0,PT=Vc.loadScript(`${o}/${n}`.replace(/([^:]\/)\/+/g,"$1"))),yield PT,yield(yield window.VisionTaskRegistry.getInstance(o)).preloadModels(s)}),audioContext:ze(),deviceDetector:lt,AudioPlayer:xn,RemoteAudioPlayer:kn,VideoPlayer:Ft,showAutoPlayDialog:Dn,Timer:mt,clearStarted:(o,s)=>{let n=o.getAlias(),a=Zi.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:Rc,createAudioNode:On,getNetworkTimeOffset:ig,validateSourceNode:()=>{var o;if(nt&&!((o=this.room.audioManager._localAudioPipline)!=null&&o.source.node))throw new ne({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:MT,AVPlayerStateSyncManager:Fc,PlayerEvent:ue}}var xT=(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 B.warn(`${s}
104
104
 
105
- ${o.stack}`),!1}},i};var Yn=new WeakMap;function kT(i){let t=Yn.get(i);t&&(t.forEach(e=>clearTimeout(e)),Yn.delete(i))}function UT(i,t){return Pe((e,r)=>function(...o){let s=Yn.get(this);s||(s=new Map,Yn.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=Yn.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=Yn.get(this))==null||l.delete(n)},i);s.set(n,d)}})}var FT="trtc-sdk-v5",Rf="5.15.1-wasm.2";function $t(...i){return Pe((t,e)=>function(...r){try{wl.call(this,i,r,e,this._name)}catch(o){return Promise.reject(o)}return t.apply(this,r)})}function vf(...i){return Pe((t,e)=>function(...r){try{wl.call(this,i,r,e,this._name)}catch(o){throw o}return t.apply(this,r)})}function wl(i,t,e,r){if(ut(i))for(let o=0;o<i.length;o++)Dl.call(this,{rule:i[o],value:t[o],key:i[o].name,fnName:e,className:r});else Dl.call(this,{rule:i,value:t[0],key:i.name,fnName:e,className:r})}function Dl({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 ne(s(5001));if(O(i.defaultValue)){Xe(i.validate)&&i.validate.call(this,t,e,r,o,this);return}t=i.defaultValue}if(Array.isArray(i.type)){let d=!1;for(let l=0;l<i.type.length;l++)i.type[l]===null&&t===null&&(d=!0),Xe(i.type[l])&&t instanceof i.type[l]&&(d=!0),Oe(i.type[l])&&gt(t)===i.type[l].toLowerCase()&&(d=!0);if(!d)throw new ne({code:oe.INVALID_PARAMETER,extraCode:5002,fnName:r,messageParams:{key:e,rule:{type:i.type.map(l=>cs(l)?dn(l):Oe(l)?l:gt(l))},value:t}})}else if(!O(i.type)&&gt(t)!==i.type)throw new ne(s(5002));if(i.allowEmpty===!1){let d=Be(t)&&(t===0||Number.isNaN(t)),l=Oe(t)&&t.trim()==="";if(d||l)throw new ne(s(5003))}if(i.notLessThanZero&&Be(t)&&t<0)throw new ne(s(5006));if(!O(i.min)&&Be(t)&&t<i.min)throw new ne(s(5007));if(!O(i.max)&&Be(t)&&t>i.max)throw new ne(s(5008));if(Oe(i.instanceOf)){if(!t||t._name!==i.instanceOf)throw new ne(s(5004))}else if(Xe(i.instanceOf)&&!(t instanceof i.instanceOf))throw new ne(s(5004));if(Array.isArray(i.values)&&!i.values.includes(t))throw new ne(s(5005));let{properties:n}=i;Jt(n)&&fr(t)&&Object.keys(n).forEach(d=>{Dl.call(this,{rule:n[d],value:t&&t[d],key:`${d}`,fnName:r,className:o})});let{arrayItem:a}=i;Jt(a)&&ut(t)&&t.forEach((d,l)=>{Dl.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 hv=0;function at(i={}){let{getRemoteId:t=()=>"",replaceArg:e,getKVReportKey:r,ignoreLog:o,ignoreErrorLog:s}=i;return Pe((n,a)=>function(...d){var R,y,N;function l(P,W,G){if(G&&G.includes(P))return"hided";if(e){let ae=e(...d);if(d[ae.argIndex]===W)return ae.value}if(W===d||P in d)return W;try{return W instanceof HTMLElement?`id: ${W.id} type:${gt(W)}`:W instanceof MediaStreamTrack?Vd(W):(JSON.stringify(W),W)}catch(ae){return`type:${gt(W)}`}}let p=(this==null?void 0:this._log)||B,f=++hv;if(o!=null&&o(...d))return n.apply(this,d);d.length>0?p.info(`${a}() ${f} ${JSON.stringify(d,(P,W)=>l(P,W,["userSig","privateMapKey"]))}`):p.info(`${a}() ${f}`);let _=r?r(...d):yu[a],I=(s==null?void 0:s(...d))||!1;try{let P=n.apply(this,d),W=pe();if(ho(P)){let G=`${a.includes("Plugin")?`${((y=(R=d[0]).getName)==null?void 0:y.call(R))||""} `:" "}`;return P.then(ae=>(p.info(`${a}() success ${f} ${G}${t.call(this,...d)}`),J.addSuccessEvent({key:_,cost:pe()-W}),ae)).catch(ae=>{var Or;ae=ne.convertFrom.call(this,ae,a,d.length===1?d[0]:d);let ke=ae.extraCode||ae.code,Me=(Or=ae.message)!=null&&Or.includes(ke)?"":` code:${ke}`,Y=(ae==null?void 0:ae.code)===oe.OPERATION_ABORT;throw I||p[Y?"warn":"error"](`${a}() failed ${f} ${G}${t.call(this,...d)} ${ae}${Me} params: ${JSON.stringify(d,l)}`),J.addFailedEvent({key:_,error:ae}),ae})}return J.addSuccessEvent({key:_}),P}catch(P){P=ne.convertFrom.call(this,P,a);let W=P.extraCode||P.code,G=(N=P.message)!=null&&N.includes(W)?"":` code:${W}`,ae=(P==null?void 0:P.code)===oe.OPERATION_ABORT;throw I||p[ae?"warn":"error"](`${a}() failed ${f} ${P}${G} params: ${JSON.stringify(d,l)}`),J.addFailedEvent({key:_,error:P}),P}})}var Ml=i=>Pe((t,e)=>function(r,o){return b(this,null,function*(){let s=this._plugins.get(r);if(!s)throw this._log.error(`plugin ${String(r)} is not found`),new ne({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 ne({code:oe.ENV_NOT_SUPPORTED,message:`plugin ${String(r)} is not supported`,extraCode:5210,fnName:e});return wl.call(this,s.getValidateRule(i),[o],e,"TRTC"),t.call(this,s,o)})});var Ol=0,Cf,eo=class eo{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");Ol=Ol+1,this.log=t.log.createChild({id:`${this.getAlias()}${Ol}`}),this.log.info(`created id=${this.getAlias()}${Ol}`),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 ne({code:oe.INVALID_OPERATION,extraCode:5106,fnName:o})}}}preload(t){return Cf||(Cf=this.doPreload(t)),Cf}doPreload(t){return b(this,null,function*(){let e=yield this.core.fileDownloader.download(t,{type:"blob"}),r=URL.createObjectURL(e);try{yield qi(this.audioContext,r)}catch(o){this.log.error(`preload audioProcessor failed. ${o}`)}finally{URL.revokeObjectURL(r)}})}getName(){return eo.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(t){switch(t){case"start":return eo.getStartValidateRule(this.core);case"update":return eo.updateValidateRule;case"stop":return eo.stopValidateRule}}start(t){return b(this,null,function*(){var _,I,R,y;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 ne({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:N,status:P,timestamp:W}=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,W,N,P,e)}if(f&&!this.screenAudioWorkletNode){let{sign:N,status:P,timestamp:W}=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,W,N,P,e)}this.mixNode||(this.mixNode=this.audioContext.createGain(),this.mixNode.gain.value=1),this.silentNode||(this.silentNode=this.audioContext.createConstantSource(),this.silentNode.offset.setValueAtTime(0,this.audioContext.currentTime),this.silentNode.start()),(_=this.localAudioWorkletNode)==null||_.port.postMessage({type:"enable"}),(I=this.screenAudioWorkletNode)==null||I.port.postMessage({type:"enable"}),e.audioManager.addAudioProcessor(this.mixNode,this.silentNode,this.localAudioWorkletNode,this.screenAudioWorkletNode),O(a)||a.forEach(N=>{this.customAudioReferenceMap.set(N,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:N,refId:`o-${this.audioRefId++}`})}),O(d)||(R=this.localAudioWorkletNode)==null||R.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:d}}),O(l)||(y=this.localAudioWorkletNode)==null||y.port.postMessage({type:"dump",data:{enable:l}})})}update(t){return b(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 b(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 b(this,null,function*(){let o=String(Date.now()).slice(0,-3),{auth:s,sign:n,status:a,message:d}=yield fv({sdkAppId:t,userSig:r,userId:e,timestamp:o});if(!s)throw this.log.info(`audioProcessor: ${e} auth result: ${s}. Message: ${d}`),new ne({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 _=(p==null?void 0:p.value)>10?"info":"debug";this.log[_](`${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":x.emit("265",{room:d,data:p.value,type:e==="localAudio"?"dump":"dump-screen-audio"});return;case"detectEcho":this.log.warn(`${e==="localAudio"?"":`[${e}] `}detect echo: ${fs()?Vi():Jr()}`);return}}}handleLocalAudioStarted(t){return b(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 b(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(eo,"updateValidateRule",{type:"object"}),m(eo,"stopValidateRule",{type:"object"}),m(eo,"Name","AudioProcessor");var Pl=eo;function pv(i,t=M.MAIN){return`https://${ei[t]||Nl(i,t)}/api/v1/audioAiAuth`}function fv(o){return b(this,arguments,function*({sdkAppId:i,userId:t,userSig:e,timestamp:r}){let n=`${pv(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 _=Rr(i)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",I="Init RTCAudioProcessor failed.",R="";switch(d){case 1:R="Please check your params.";break;case 2:R=`You need to buy packages. Refer to: ${_}`;break;case 3:R="Server is invalid. Please contact our engineer. ";break;case 4:R=`Your packages is not active. Refer to: ${_}`;break;case 5:R=`Your packages is expired. Refer to: ${_}`;break;case 6:R="Your version is not supported.";break}return{auth:!1,status:f,message:l?`${I} Reason: ${l}. ${R}`:`${I}, ${R}`}})}var Ll=0,Nf=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 b(this,null,function*(){if(t.url){let e=yield Vc.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 Zn(i,t){if(t&&typeof t!="function")throw new ne({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);Ll=Ll+1,this.log=t.log.createChild({id:`${this.getAlias()}${Ll}`}),this.log.info(`created id=${this.getAlias()}${Ll}`)}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 b(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 Nf(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.`),J.addEnum({key:502700,value:3}),this.kvUpload(t)})}handleAutoPlayFailed(t,e,r){return b(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(()=>{x.off("154",o,this)})};x.on("154",o,this),Dn()}else this.core.trtc.emit(te.AUTOPLAY_FAILED,{userId:"",mediaType:"audio",resume:()=>b(this,null,function*(){return t.play()})});else throw r})}update(t){return b(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 b(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&&J.addCount({key:502009}),r&&J.addCount({key:502001}),o&&J.addCount({key:502002}),s&&J.addCount({key:502003}),n&&J.addCount({key:502004}),a&&J.addCount({key:502005}),typeof d!="function"&&J.addCount({key:502007}),typeof p!="function"&&J.addCount({key:502008}),typeof l!="function"&&J.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 ne({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 ne({code:oe.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:r});Zn("onTimeUpdate",t.onTimeUpdate),Zn("onEnded",t.onEnded),Zn("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){Zn("onTimeUpdate",t.onTimeUpdate),Zn("onEnded",t.onEnded),Zn("onDurationChange",t.onDurationChange)}}),m(Ii,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),m(Ii,"Name","AudioMixer");var xl=Ii;var kl=0,Df,to=class to{constructor(t){this.core=t;m(this,"log");m(this,"audioContext",ze("denoiser"));m(this,"workletNode");m(this,"config",{enableFarFieldReduce:!1,farFieldReduceThreshold:.5});kl=kl+1,this.log=t.log.createChild({id:`${this.getAlias()}${kl}`}),this.log.info(`created id=${this.getAlias()}${kl}`)}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 ne({code:oe.INVALID_OPERATION,extraCode:5106,fnName:o})}}}preload(t){return Df||(Df=this.doPreload(t)),Df}doPreload(t){return b(this,null,function*(){let e=yield this.core.fileDownloader.download(t,{type:"blob"}),r=URL.createObjectURL(e);try{yield qi(this.audioContext,r)}catch(o){throw this.log.error("load worklet failed",o),o}finally{URL.revokeObjectURL(r)}})}getName(){return to.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser"}getValidateRule(t){switch(t){case"start":return to.startValidateRule(this.core);case"update":return to.updateValidateRule;case"stop":return to.stopValidateRule}}start(t){return b(this,null,function*(){let{room:e,schedule:r}=this.core,{assetsPath:o=this.core.assetsPath}=t;if(!o)throw new ne({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${Ph()?"":"-nosimd"}.js`),!this.workletNode){let s=String(Date.now()).slice(0,-3),{auth:n,sign:a,status:d,message:l}=yield Ev(r,Te(Q({},t),{timestamp:s}));if(!n)throw this.log.info(`RTCAIDenoiser: ${t.userId} auth result: ${n}. Message: ${l}`),new ne({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 _;let{data:f}=p;if(f.type==="cost"){let I=(f==null?void 0:f.max)>20?"warn":(f==null?void 0:f.max)>10?"info":"debug";this.log[I](`avg cost: ${f.value} max: ${f==null?void 0:f.max}(${Ks(new Date(f==null?void 0:f.maxCostTimestamp))}) hist: ${(_=f==null?void 0:f.hist)==null?void 0:_.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 b(this,null,function*(){this.updateConfig(t)})}stop(){return b(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(to,"updateValidateRule",{type:"object",properties:{mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}}}),m(to,"stopValidateRule",{type:"object"}),m(to,"Name","AIDenoiser");var Ul=to;function Ev(s,n){return b(this,arguments,function*(i,{sdkAppId:t,userId:e,userSig:r,timestamp:o}){try{let{data:{errCode:a,errMsg:d,sign:l,status:p}}=yield i.getAbilityConfig(t,i.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:t,userId:e,userSig:r,timestamp:o});if(p==="1")return{auth:!0,sign:l,status:p,message:d};let f=Rr(t)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",_="Init RTCAIDenoiser failed.",I="";switch(a){case 1:I="Please check your params.";break;case 2:I=`You need to buy packages. Refer to: ${f}`;break;case 3:I="Server is invalid. Please contact our engineer. ";break;case 4:I=`Your packages is not active. Refer to: ${f}`;break;case 5:I=`Your packages is expired. Refer to: ${f}`;break;case 6:I="Your version is not supported.";break}return{auth:!1,status:p,message:d?`${_} Reason: ${d}. ${I}`:`${_}, ${I}`}}catch(a){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${a}`}}})}var $T=ai(mi(),1);var wf=class extends $T.EventEmitter{constructor(){super();m(this,"observer");m(this,"state","nominal");this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return b(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!rt&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){Ue.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let r=this.stateNum,o=e[e.length-1];this.state=o.state,(this.stateNum>3||r>3)&&B.info(`${o.source}: ${o.state}`),this.emit("state-changed",{type:o.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(r){Ue.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:r})}}},_v=new wf,Mf=_v;var Of=0,Bc=class Bc{constructor(t){this.core=t;m(this,"log");m(this,"_seiMessageList",[]);m(this,"_smallSeiMessageList",[]);m(this,"_subStreamSeiMessageList",[]);Of++,this.log=t.log.createChild({id:`${this.getAlias()}${Of}`}),this.log.info(`[sei] created id=${this.getAlias()}${Of}`),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 yf({frame:t,seiMessageList:r})}catch(r){this.log.warn(r)}return t}decode({frame:t,track:e}){return bf({frame:t,onSEI:r=>{r.forEach(o=>{e!=null&&e.userId?this.core.trtc.emit(te.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:yf,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:Ss?this.decode:bf,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 Bc.Name}getAlias(){return"sei"}getGroup(){return"sei"}};m(Bc,"autoStart",!0),m(Bc,"Name","SEI");var Vl=Bc;var Tv=0,Fl,$c=class $c{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()}${++Tv}`}),this.log.info("created")}getName(){return $c.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 b(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 b(this,arguments,function*({visible:t}){t?yield this.openDebugDiaLog():this.closeDebugDiaLog()})}stop(){this.closeDebugDiaLog()}destroy(){this.stop()}openDebugDiaLog(){return b(this,null,function*(){var t;if(!this.dialog)try{if(Fl)yield Fl;else{let e=new URLSearchParams(location.search).get("trtcDebugDialogPath")||((t=window.sessionStorage)==null?void 0:t.getItem("TRTC_DEBUG_DIALOG_PATH"))||`https://unpkg.com/${FT}@${ft}/assets/debug-dialog.js`;Fl=this._core.fileDownloader.loadScript(e),yield Fl}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($c,"Name","Debug"),m($c,"autoStart",!0);var Bl=$c;var HT=i=>{switch(i){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},$l=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,he.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:HT(this.type),error:p}),d>4?this.startOB.error(p):this.startOB.next(d+1)})),be(l,Kr(1),kp(Sc))};be(this.startOB,Tc(0),fi(a),Je(this.stopOB),Le(()=>{e.player.setOutput(),n.next("STARTED")},d=>{n.next("FAILED")},()=>{o.addSuccessEvent({key:HT(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 zi()(e=>b(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"}))}},Iv={type:"object"},Hc=class Hc{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 Hc.Name}getGroup(t){return t.track.userId+t.track.streamType}getName(){return Hc.Name}getValidateRule(t){return Iv}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 $l(this.core,r,t);return be(o.trackDoneOB,Kr(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 $l(this.core,t.track,t))}}};m(Hc,"Name","TRTCAudioDecoder");var Wc=Hc;var Hl=class{constructor(){m(this,"log");this.log=B.createLogger({id:"exp"})}call(t,e){return b(this,null,function*(){return Xe(this[t])?this[t](e):Promise.reject(new ce({code:z.INVALID_PARAMETER,message:je({key:Ge.API_NOT_EXIST,data:{name:t}})}))})}enableAudioFrameEvent(t){return b(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 _=d.getPCM(I=>{e.emit(te.AUDIO_FRAME,I)},f.userId);l.set(f.userId,_)}});else{if(l.get(o))return;let f=d.getPCM(_=>{e.emit(te.AUDIO_FRAME,_)},o);l.set(o,f)}else if(o==="*")e.room.remotePublishedUserMap.forEach(f=>{if(f.remoteAudioTrack.isSubscribed){let{userId:_}=f,I=l.get(_);I==null||I.abort("disable"),l.delete(_)}});else{let f=l.get(o);f==null||f.abort("disable"),l.delete(o)}})}resumeRemotePlayer(t){return b(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([I_({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"}}})],Hl.prototype,"enableAudioFrameEvent",1);var WT=new Hl;var GT=ai(mi(),1);var Pf=class extends GT.EventEmitter{constructor(){super();m(this,"states",{});m(this,"permissionChangeHandler");m(this,"log");this.log=B.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 b(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 b(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={}}},Gc=new Pf;var jT=0,jc=new Set,kt=null;_m(Rf);Rn.checkStorage();var _e=class _e extends qT.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",B.createLogger({id:`t${++jT}`}));m(this,"_plugins",new Map);m(this,"_networkQuality",null);m(this,"_speakerId");m(this,"enterRoomParams");m(this,"_enableAutoSwitchWhenRecapturing",!0);m(this,"_autoSubscribeDataChannel",!1);this._room=new e(Q({logger:this._log,frameWorkType:_e.frameWorkType},r)),this._room.videoDecodeFallbackType=r.videoDecodeFallback,Ze(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(xl,r.assetsPath),this._use(Pl,r.assetsPath),this._use(Ul,r.assetsPath),this._use(Wc,r.assetsPath),this._use(Bl),r.enableSEI&&ic&&this._use(Vl),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(te.AUDIO_VOLUME,{result:o.sort((a,d)=>d.volume-a.volume)})}),this._room.videoManager.on("error",o=>{this._log.error(new ne({code:oe.OPERATION_FAILED,extraCode:5504,message:o.message,originError:o}))}),this._listenEvents(),this._initActiveSpeaker(),xT(this,"trtc")}static create(e){}static _create(e,r){pT();let o=new _e(e,r||{});return jc.add(o),o.__v_skip=!0,o}get room(){return this._room}_listenEvents(){Vt(this,this._room).add("peer-join",e=>{let{userId:r}=e;this.emit(te.REMOTE_USER_ENTER,{userId:r})}).add("peer-leave",({userId:e,reason:r})=>{this.emit(te.REMOTE_USER_EXIT,{userId:e,reason:r})}).add("banned",e=>{Ki(!0),this._exitRoom().finally(()=>{this.emit(te.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().finally(()=>{this.emit(te.ERROR,ne.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(te.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let r=Te(Q({},e),{uplinkRTT:Math.min(e.uplinkRTT,va),downlinkRTT:Math.min(e.downlinkRTT,va)});this.emit(te.NETWORK_QUALITY,r)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(o=>{Vt(o,o).add("player-state-changed",s=>{let n=Te(Q({},s),{userId:e.userId});o.kind===M.VIDEO&&(n.streamType=dr(o.streamType)),this.emit(o.kind===M.AUDIO?te.AUDIO_PLAY_STATE_CHANGED:te.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",s=>{s.getCode()===z.PLAY_NOT_ALLOWED&&this.emit(te.AUTOPLAY_FAILED,{userId:o.userId,mediaType:o.strMediaType,resume:()=>o.player.resume()})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(o=>{yt(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?te.REMOTE_VIDEO_AVAILABLE:te.REMOTE_VIDEO_UNAVAILABLE,{userId:o,streamType:"main"})),s!==a&&(a?this._onAudioAvailable({userId:o}):this._onAudioUnavailable({userId:o,muteState:r}),this.emit(a?te.REMOTE_AUDIO_AVAILABLE:te.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?te.REMOTE_VIDEO_AVAILABLE:te.REMOTE_VIDEO_UNAVAILABLE,{userId:o,streamType:"sub"})),e.hasDatachannel!==r.hasDatachannel&&r.hasDatachannel&&this._onDataChannelAvailable()}).add("sei-message",e=>{this.emit(te.SEI_MESSAGE,Te(Q({},e),{streamType:dr(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(te.ERROR,new ne({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,va),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)/$i},video:e.msg_up_stream_info.msg_video_status.filter(_=>r[_.uint32_video_stream_type]).map(_=>({bitrate:(_.uint32_video_codec_bitrate||0)/1e3,width:_.uint32_video_width,height:_.uint32_video_height,frameRate:_.uint32_video_enc_fps,videoType:r[_.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(_=>({userId:_.msg_user_info.str_identifier,audio:{bitrate:(_.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(_.msg_audio_status.uint32_audio_level||0)/$i,point2pointDelay:(_.msg_audio_status.uint32_audio_p2p_delay||0)+(_.msg_audio_status.uint32_audio_cache_ms||0),jitterBufferDelay:_.msg_audio_status.uint32_audio_cache_ms||0},video:_.msg_video_status.map(I=>({bitrate:(I.uint32_video_codec_bitrate||0)/1e3,width:I.uint32_video_width,height:I.uint32_video_height,frameRate:I.uint32_video_dec_fps,videoType:r[I.uint32_video_stream_type],point2pointDelay:(I.uint32_video_p2p_delay||0)+(I.uint32_video_cache_ms||0),jitterBufferDelay:I.uint32_video_cache_ms||0,codec:I.uint32_video_codec}))}))};this.emit(te.STATISTICS,o)}).add("custom-message",e=>{this.emit(te.CUSTOM_MESSAGE,e)}).add("layerData",e=>this.emit(te.LAYER_DATA,e)).add("first-video-frame",e=>{this.emit(te.FIRST_VIDEO_FRAME,Te(Q({},e),{streamType:dr(e.streamType)}))}).add("audio-frame",e=>{this.emit(te.AUDIO_FRAME,e)}).add("data-channel-message",e=>{var s,n,a,d,l;let{data:r}=e;if(r.sender==="")return;let o={segmentId:(s=r.payload)==null?void 0:s.roundid,speakerUserId:r.sender,sourceText:(n=r.payload)==null?void 0:n.text,translationTexts:(a=r.payload)==null?void 0:a.translate_msg,timestamp:(d=r.payload)==null?void 0:d.start_utc_ms,isCompleted:(l=r.payload)==null?void 0:l.end,robotId:r.robotid};o.sourceText!==""&&this.emit(te.REALTIME_TRANSCRIBER_MESSAGE,o)}).add("asr-robot-peer-join",e=>{this.emit(te.REALTIME_TRANSCRIBER_STATE_CHANGED,{state:"started",roomId:this.room.roomId,transcriberRobotId:e.userId})}).add("asr-robot-peer-leave",e=>{this.emit(te.REALTIME_TRANSCRIBER_STATE_CHANGED,{state:"stopped",roomId:this.room.roomId,transcriberRobotId:e.userId})}),Vt(this,lt).add("audioInputAdded",e=>{this.emit(te.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(te.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(te.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(te.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>b(this,null,function*(){if(this.emit(te.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),kt&&kt.deviceId===Ra){let r=(yield No()).find(o=>o.deviceId===Ra);r&&kt.groupId!==r.groupId&&(kt=r,this.emit(te.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}))}})).add("audioOutputRemoved",e=>b(this,null,function*(){this.emit(te.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let r=(yield No())[0];if(!r||!kt||kt.groupId===r.groupId)return;let o=kt.deviceId===e.deviceId,s=kt.deviceId===Ra&&kt.deviceId===r.deviceId;(o||s)&&(kt=r,this.emit(te.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}))})),Vt(this,Gc).add("permission-state-change",e=>{this.emit(te.PERMISSION_STATE_CHANGE,e)}),this.room.enableSEI&&this.on(te.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(LT.call(this,{TRTC:_e,room:this._room,assetsPath:r,errorModule:{RtcError:ne,ErrorCode:oe,CoreErrorCode:z,ErrorCodeDictionary:Sr}}));return this._plugins.set(e.Name,s),s.__v_skip=!0,e.autoStart&&this.startPlugin(e.Name),s}enterRoom(e){return b(this,null,function*(){var d,l;this.enterRoomParams=e;let{scene:r="rtc",enableAutoPlayDialog:o=!0,autoReceiveAudio:s=!0,autoReceiveVideo:n=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!Oe(e.proxy)&&e.proxy.turnServer&&((l=(d=this._room).setTurnServer)==null||l.call(d,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=o,this._room.autoReceiveAudio=s,this._room.autoReceiveVideo=n,Ze(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,enableDataChannel:this._plugins.has("RealtimeTranscriber"),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,_e.frameWorkType),this._checkTrackToPublish(),Mf.start()})}exitRoom(){return b(this,null,function*(){return yield this._exitRoom()})}switchRoom(e){return b(this,null,function*(){if(this.room.isSwitchRoomSupported())try{this._clearRemoteTracks(),yield this._room.switchRoom(e)}catch(r){if(r instanceof Ia&&(r.code===z.API_CALL_TIMEOUT||r.code===z.SWITCH_ROOM_FAILED))this._log.warn(`switchRoom ${r.code===z.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 b(this,null,function*(){yield this.exitRoom();let r=Q(Q({},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(),kT(this),this._room.remotePublishedUserMap.forEach(e=>{yt(e.remoteAudioTrack),yt(e.remoteVideoTrack),yt(e.remoteAuxiliaryTrack)})}switchRole(e,r){return b(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(),yt(this),this.removeAllListeners(),this._room.destroy(),jc.delete(this),jc.size===0&&Mf.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),x.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return b(this,arguments,function*(e={publish:!0}){if(this._localAudioTrack){this._log.warn("local audio is already started");return}let{publish:r=!0,mute:o,muteKeepVolumeDetection:s,option:n}=e,a=new gi(this._room.audioManager),d={},l={muted:!0};n&&(O(n.microphoneId)?O(n.audioTrack)||(d.customSource=n.audioTrack):d.deviceId=n.microphoneId,n&&Be(n.captureVolume)&&a.setCaptureVolume(n.captureVolume),O(n.profile)||(Oe(n.profile)?yd[n.profile]&&a.setProfile(yd[n.profile]):a.setProfile(n.profile)),Be(n.earMonitorVolume)&&(l.muted=!(n.earMonitorVolume>0),l.volume=n.earMonitorVolume),O(n.echoCancellation)||(a.profile.echoCancellation=n.echoCancellation),O(n.noiseSuppression)||(a.profile.noiseSuppression=n.noiseSuppression),O(n.autoGainControl)||(a.profile.autoGainControl=n.autoGainControl),Ze(this._enableAutoSwitchWhenRecapturing)&&(a.enableAutoSwitchWhenRecapturing=this._enableAutoSwitchWhenRecapturing)),a.on("5",p=>{this.emit(te.ERROR,new ne({code:oe.DEVICE_ERROR,extraCode:5309,messageParams:{error:p}}))}),a.on("2",p=>{this.emit(te.DEVICE_CHANGED,{type:"microphone",action:"active",device:p})}),a.on("4",p=>{let f;p.error&&(f=ne.convertFrom(p.error)),this.emit(te.PUBLISH_STATE_CHANGED,Te(Q({},p),{error:f}))}),a.on("6",()=>{}),this._listenOutputTrackChanged(a),this._speakerId&&a.setAudioOutput(this._speakerId),yield a.capture(d),O(o)||a.setMute(o,s),Vt(a,a).add("player-state-changed",p=>{this.emit(te.AUDIO_PLAY_STATE_CHANGED,Te(Q({},p),{userId:""}))}),r&&this._room.isJoined&&this._room.publish(a).catch(()=>{}),this._localAudioTrack=a,this._room.capturedLocalMainAudioTrack=a,this._localAudioConfig=Te(Q({},e),{publish:r}),yield this._updateAudioPlayOption({playOption:l,track:a}),x.emit("113",{userId:"",room:this.room})})}updateLocalAudio(e){return b(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:r,mute:o,muteKeepVolumeDetection:s,option:n}=e,a={};n&&(n.microphoneId?yield this._localAudioTrack.switchDevice(n.microphoneId):O(n.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(n.audioTrack)),O(n.captureVolume)||this._localAudioTrack.setCaptureVolume(n.captureVolume),O(n.earMonitorVolume)||(a.muted=!(n.earMonitorVolume>0),a.volume=n.earMonitorVolume),yield this._localAudioTrack.update3A(n)),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,s),yield this._updateAudioPlayOption({playOption:a,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),$r(this._localAudioConfig,e)})}stopLocalAudio(){return b(this,null,function*(){this._localAudioTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),x.emit("114",{userId:"",room:this.room}),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),yt(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null,delete this._room.capturedLocalMainAudioTrack)})}startLocalVideo(){return b(this,arguments,function*(e={publish:!0,view:null,capture:!0}){var _,I;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=o,l=new Ir(this._room.videoManager),p={},f={};a&&(Ze(a.avoidCropping)&&(l.avoidCropping=a.avoidCropping),a.cameraId?p.deviceId=a.cameraId:O(a.useFrontCamera)?O(a.videoTrack)||(p.customSource=a.videoTrack):p.facingMode=a.useFrontCamera?M.FACING_MODE_USER:M.FACING_MODE_ENVIRONMENT,O(a.retryWhenExactFailed)||(p.retryWhenExactFailed=a.retryWhenExactFailed),a.qosPreference&&(p.contentHint=kc(a.qosPreference)),O(a.profile)||(Oe(a.profile)?Fr[a.profile]&&l.setProfile(Fr[a.profile]):l.setProfile(a.profile)),O(a.fillMode)||(f.objectFit=a.fillMode),O(a.mirror)||(f.mirror=a.mirror),O(a.small)||(O(a.smallMode)||(this._room.smallMode=a.smallMode),Ze(a.small)&&a.small===!1?l.stopSmall():l.updateSmallConfig(Jn(a.small,!0))),O(a.rotation)||l.setRotation(a.rotation),Ze(this._enableAutoSwitchWhenRecapturing)&&(l.enableAutoSwitchWhenRecapturing=this._enableAutoSwitchWhenRecapturing)),l.once("first-video-frame",R=>{this.emit(te.FIRST_VIDEO_FRAME,Te(Q({},R),{streamType:dr(R.streamType)}))}),l.on("5",R=>{this.emit(te.ERROR,new ne({code:oe.DEVICE_ERROR,extraCode:5308,messageParams:{error:R}}))}),l.on("2",R=>{this.emit(te.DEVICE_CHANGED,{type:"camera",action:"active",device:R})}),l.on("4",R=>{let y;R.error&&(y=ne.convertFrom(R.error)),this.emit(te.PUBLISH_STATE_CHANGED,Te(Q({},R),{error:y}))}),l.on("6",()=>{}),this._listenOutputTrackChanged(l),s?yield l.capture(p):(_=l.manager)==null||_.changeInput(l),O(n)||(yield l.setMute(n)),Vt(l,l).add("player-state-changed",R=>{this.emit(te.VIDEO_PLAY_STATE_CHANGED,Te(Q({},R),{userId:"",streamType:"main"}))}).add("video-size-changed",R=>{this.emit(te.VIDEO_SIZE_CHANGED,Te(Q({},R),{streamType:dr(R.streamType)}))}),d&&this._room.isJoined&&(this._localScreenTrack&&((I=this._localScreenConfig)==null?void 0:I.publish)&&this._localScreenConfig.streamType==="main"?(d=!1,this._log.warn("main stream is already published, local video track will not publish")):this._room.publish(l).catch(()=>{})),this._localVideoTrack=l,this._room.capturedLocalMainVideoTrack=l,this._localVideoConfig=Te(Q({},e),{view:r,publish:d,capture:s}),yield this._updateVideoPlayOption({view:r,playOption:f,track:l})})}updateLocalVideo(e){return b(this,null,function*(){var f,_,I,R;if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:r,publish:o=!0,mute:s,capture:n,option:a,forcePublish:d=!1}=e,l=o||d,p={};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 y={};y.deviceId=(a==null?void 0:a.cameraId)||((f=this._localVideoConfig.option)==null?void 0:f.cameraId),y.facingMode=a!=null&&a.useFrontCamera||(_=this._localVideoConfig.option)!=null&&_.useFrontCamera?M.FACING_MODE_USER:M.FACING_MODE_ENVIRONMENT,y.customSource=(a==null?void 0:a.videoTrack)||((I=this._localVideoConfig.option)==null?void 0:I.videoTrack),yield this._localVideoTrack.capture(y)}a&&(O(a.profile)||(Oe(a.profile)?Fr[a.profile]&&this._localVideoTrack.setProfile(Fr[a.profile]):this._localVideoTrack.setProfile(a.profile),(!a.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(a.cameraId||a.useFrontCamera?M.FACING_MODE_USER:M.FACING_MODE_ENVIRONMENT))&&(yield this._localVideoTrack.applyProfile())),O(a.fillMode)||(p.objectFit=a.fillMode),O(a.mirror)||(p.mirror=a.mirror),O(a.rotation)||this._localVideoTrack.setRotation(a.rotation),a.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(kc(a.qosPreference)),O(a.small)||(Ze(a.small)&&!a.small?this._localVideoTrack.stopSmall():this._localVideoTrack.updateSmallConfig(Jn(a.small,!0)))),this._room.isJoined&&O(l)&&this._localVideoConfig.publish&&n&&!this._localVideoConfig.capture&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._room.isJoined&&((l!=null?l:this._localVideoConfig.publish)||d?!(this._localScreenTrack&&((R=this._localScreenConfig)==null?void 0:R.publish)&&this._localScreenConfig.streamType==="main")||d?this._room.publish(this._localVideoTrack).catch(()=>{}):(l=!1,this._log.warn("main stream is already published, local video track will not publish")):this._room.unpublish(this._localVideoTrack).catch(()=>{})),O(s)||(yield this._localVideoTrack.setMute(s)),yield this._updateVideoPlayOption({view:r,playOption:p,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),$r(this._localVideoConfig,Te(Q({},e),{publish:l}))})}stopLocalVideo(){return b(this,null,function*(){var e;this._localVideoTrack&&(this._room.isJoined&&((e=this._localVideoConfig)!=null&&e.publish)&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),yt(this._localVideoTrack),this._localVideoTrack=null,delete this._room.capturedLocalMainVideoTrack,this._localVideoConfig=null)})}startScreenShare(){return b(this,arguments,function*(e={publish:!0,view:null}){var I,R,y;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=o,d=new Ei(this._room.videoManager);d.on("4",N=>{let P;N.error&&(P=ne.convertFrom(N.error)),this.emit(te.PUBLISH_STATE_CHANGED,Te(Q({},N),{error:P}))}),d.once("first-video-frame",N=>{this.emit(te.FIRST_VIDEO_FRAME,Te(Q({},N),{streamType:dr(N.streamType)}))}),this._listenOutputTrackChanged(d),e.streamType==="main"&&(d.mediaType=4);let l=null,p={},f={};n&&(O(n.profile)||(Oe(n.profile)?bd[n.profile]&&d.setProfile(bd[n.profile]):d.setProfile(n.profile)),n.systemAudio&&(p.systemAudio=!0,p.echoCancellation=n.echoCancellation,p.noiseSuppression=n.noiseSuppression,p.autoGainControl=n.autoGainControl),O(n.fillMode)||(f.objectFit=n.fillMode),n.videoTrack&&(p.videoTrack=n.videoTrack),n.audioTrack&&(p.audioTrack=n.audioTrack),n.captureElement&&(p.captureElement=n.captureElement),n.preferDisplaySurface&&(p.preferDisplaySurface=n.preferDisplaySurface),n.qosPreference&&(p.contentHint=kc(n.qosPreference)));let _=yield d.capture(p);if(d.mediaTrack.addEventListener(M.ENDED,()=>{this._stopScreenShare(),this.emit(te.SCREEN_SHARE_STOPPED)}),_.getAudioTracks()[0]){l=new xs(this._room.audioManager);let N=_.getAudioTracks()[0];(I=e.option)!=null&&I.systemAudio&&!((R=e.option)!=null&&R.audioTrack)&&(l.sourceTrack=N),yield l.setInputMediaStreamTrack(N),Ze(s)&&l.mediaTrack&&(l.mediaTrack.enabled=!s),this._speakerId&&l.setAudioOutput(this._speakerId)}if(Vt(d,d).add("player-state-changed",N=>{this.emit(te.VIDEO_PLAY_STATE_CHANGED,Te(Q({},N),{userId:"",streamType:"sub"}))}),a&&this._room.isJoined){let N=this._localVideoTrack&&((y=this._localVideoConfig)==null?void 0:y.publish);!(e.streamType==="main"&&N)?this._room.publish(d).catch(()=>{}):(a=!1,this._log.warn("main stream is already published, screen share main will not publish")),l&&(this._checkScreenAudioEchoCancellation(d,l),this._room.publish(l).catch(()=>{}))}this._localScreenTrack=d,this._room.capturedLocalAuxVideoTrack=d,this._localScreenAudioTrack=l,this._localScreenConfig=Te(Q({},e),{view:r,publish:a}),yield this._updateVideoPlayOption({view:r,playOption:f,track:d})})}updateScreenShare(e){return b(this,null,function*(){var l,p;if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:r,publish:o,muteSystemAudio:s,option:n}=e,a=o,d={};if(n){if(O(n.fillMode)||(d.objectFit=n.fillMode),n.qosPreference){let f=kc(n.qosPreference);this._localScreenTrack.setContentHint(f)}n.videoTrack&&this._localScreenTrack.setInputMediaStreamTrack(n.videoTrack),n.audioTrack&&this._localScreenAudioTrack&&this._localScreenAudioTrack.setInputMediaStreamTrack(n.audioTrack)}if(this._room.isJoined&&!O(a)){if(a&&!this._localScreenConfig.publish){let f=this._localVideoTrack&&((l=this._localVideoConfig)==null?void 0:l.publish);!(this._localScreenConfig.streamType==="main"&&f)?this._room.publish(this._localScreenTrack).catch(()=>{}):(a=!1,this._log.warn("main stream is already published, screen share main will not publish")),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch(()=>{})}if(this._localScreenConfig.publish&&!a){let f=[this._localScreenTrack];this._localScreenAudioTrack&&f.push(this._localScreenAudioTrack),f.forEach(_=>this._room.unpublish(_).catch(()=>{}))}}(p=this._localScreenAudioTrack)!=null&&p.mediaTrack&&Ze(s)&&(this._localScreenAudioTrack.mediaTrack.enabled=!s),yield this._updateVideoPlayOption({view:r,playOption:d,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),$r(this._localScreenConfig,Te(Q({},e),{publish:a}))})}stopScreenShare(){return b(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return b(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,f=this._bindRemoteVideoTrackEvents(p);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,handlers:f}),n&&!O(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:p,view:r,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:n==null?void 0:n.viewRoot})})}updateRemoteVideo(e){return b(this,null,function*(){var P,W;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,_=this._room.remotePublishedUserMap.get(o);if(s==="main"&&(_!=null&&_.muteState.hasVideo)&&(f=_.remoteVideoTrack),s==="sub"&&(_!=null&&_.muteState.hasAuxiliary)&&(f=_.remoteAuxiliaryTrack),!f)return;let{config:I}=l;s==="main"&&n&&!O(n.small)&&this._room.changeType(n.small,f.user),n&&!O(n.draggable)&&f.setDraggable(n.draggable),n&&(Ze(n.pictureInPicture)&&(n.pictureInPicture?yield f.player.enterPictureInPicture():yield f.player.exitPictureInPicture()),Ze(n.fullScreen)&&(n.fullScreen?yield f.player.enterFullscreen():yield f.player.exitFullscreen())),Ze(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:I}),$r(I,e);let R=O(n==null?void 0:n.receiveWhenViewVisible)?(P=I.option)==null?void 0:P.receiveWhenViewVisible:n.receiveWhenViewVisible,y=O(r)?I.view:r,N=O(n==null?void 0:n.viewRoot)?(W=I.option)==null?void 0:W.viewRoot:n.viewRoot;this._observeView({remoteTrack:f,view:y,receiveWhenViewVisible:R,viewRoot:N})})}stopRemoteVideo(e){return b(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,r=!0){return b(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);if(s&&(s.observer&&s.observer.disconnect(),s.handlers)){let n=this._room.remotePublishedUserMap.get(e);if(n){let a=r==="main"?n.remoteVideoTrack:n.remoteAuxiliaryTrack;this._unbindRemoteVideoTrackEvents(a,s.handlers)}}this._remoteVideoConfigMap.delete(o)}_bindRemoteVideoTrackEvents(e){let r={onEnterPIP:()=>b(this,null,function*(){yield e.player.enterPIPPromise,this.emit(te.PICTURE_IN_PICTURE_STATE_CHANGED,{streamType:dr(e.streamType),userId:e.userId,isPictureInPicture:!0,pictureInPictureWindow:e.player.pipWindow})}),onLeavePIP:()=>{this.emit(te.PICTURE_IN_PICTURE_STATE_CHANGED,{streamType:dr(e.streamType),userId:e.userId,isPictureInPicture:!1})},onEnterFullScreen:()=>{this.emit(te.FULL_SCREEN_STATE_CHANGED,{streamType:dr(e.streamType),userId:e.userId,isFullScreen:!0})},onLeaveFullScreen:()=>{this.emit(te.FULL_SCREEN_STATE_CHANGED,{streamType:dr(e.streamType),userId:e.userId,isFullScreen:!1})},onDecodeFailed:()=>{this.emit(te.ERROR,new ne({code:oe.OPERATION_FAILED,extraCode:5507,message:"video decode failed"}))},onVideoSizeChanged:o=>{this.emit(te.VIDEO_SIZE_CHANGED,Te(Q({},o),{streamType:dr(o.streamType)}))}};return e.player.on(ue.ENTER_PICTURE_IN_PICTURE,r.onEnterPIP),e.player.on(ue.LEAVE_PICTURE_IN_PICTURE,r.onLeavePIP),e.player.on(ue.ENTER_FULL_SCREEN,r.onEnterFullScreen),e.player.on(ue.LEAVE_FULL_SCREEN,r.onLeaveFullScreen),e.on("decode-failed",r.onDecodeFailed),e.on("video-size-changed",r.onVideoSizeChanged),r}_unbindRemoteVideoTrackEvents(e,r){e.player.off(ue.ENTER_PICTURE_IN_PICTURE,r.onEnterPIP),e.player.off(ue.LEAVE_PICTURE_IN_PICTURE,r.onLeavePIP),e.player.off(ue.ENTER_FULL_SCREEN,r.onEnterFullScreen),e.player.off(ue.LEAVE_FULL_SCREEN,r.onLeaveFullScreen),e.off("decode-failed",r.onDecodeFailed),e.off("video-size-changed",r.onVideoSizeChanged)}muteRemoteAudio(e,r){return b(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 b(this,null,function*(){return e.start(r)})}updatePlugin(e,r){return b(this,null,function*(){return e.update(r)})}stopPlugin(e,r){return b(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(te.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 e==="realtime-transcriber-message"&&this._room.subscribeDataChannel(),this}emit(e,...r){try{RT.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==="realtime-transcriber-message"||e==="*")&&this.listeners("realtime-transcriber-message").length===0&&this._room.unsubscribeDataChannel(),(e===_e.EVENT.AUDIO_FRAME||e==="*")&&this.listeners(_e.EVENT.AUDIO_FRAME).length===0){let{getPCMAbortCtrlMap:s}=this.room.audioManager;s.forEach(n=>{n==null||n.abort("off")}),s.clear()}return this}getAudioTrack(e={userId:"",streamType:"main"}){let r,o=null,s="main",n=!1;if(Oe(e)?r=e:(r=e.userId,n=e.processed===!0,e.streamType&&(s=e.streamType)),r){let a=this._room.remotePublishedUserMap.get(r);a&&(o=a.remoteAudioTrack)}else o=s==="sub"?this._localScreenAudioTrack:this._localAudioTrack;return o?n&&o.outMediaTrack&&o.outMediaTrack!==o.mediaTrack?o.outMediaTrack.clone():o.mediaTrack:null}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:r="",streamType:o="main",processed:s=!1}=e,n=null;if(r==="")o==="main"&&this._localVideoTrack&&(n=this._localVideoTrack),o==="sub"&&this._localScreenTrack&&(n=this._localScreenTrack);else{let a=this._room.remotePublishedUserMap.get(r);a&&(n=o==="main"?a.remoteVideoTrack:a.remoteAuxiliaryTrack)}return n?s&&n.outMediaTrack&&n.outMediaTrack!==n.mediaTrack?n.outMediaTrack.clone():n.mediaTrack:null}getVideoSnapshot(e={}){let{userId:r,streamType:o="main"}=e;if(r){let s=this._room.remotePublishedUserMap.get(r);if(o==="main"&&(s!=null&&s.muteState.hasVideo))return s.remoteVideoTrack.getVideoFrame();if(o==="sub"&&(s!=null&&s.muteState.hasAuxiliary))return s.remoteAuxiliaryTrack.getVideoFrame()}else{if(o==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(o==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(e){var r,o;this._speakerId=e,(r=this._localAudioTrack)==null||r.setAudioOutput(e),(o=this._localScreenAudioTrack)==null||o.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(s=>s.remoteAudioTrack.setAudioOutput(e))}setCurrentSpeaker(e){return b(this,null,function*(){(yield No()).forEach(o=>{o.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(te.DEVICE_CHANGED,{type:"speaker",action:"active",device:o}),kt=o)}),this._log.warn(`the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: ${ir}/en/TRTC.html#.setCurrentSpeaker`)})}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return b(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(te.ERROR,new ne({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=Be(d)?d:100;s.volume=l,this._remoteAudioConfigMap.set(r,e),yield this._room.subscribe(n),be(ye(n,"decode-failed"),Je(ye(n,he.INIT)),Le(()=>{this.startPlugin(Wc.Name,{track:n,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:s,track:n}),x.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 b(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}`),x.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,he.INIT)),ws(()=>{this._room.downlinkVideoCodec!=="h265"&&this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:o})}),Ji(ye(e,"decode-downgrade-state-changed")),Le(n=>{s=n.state,this.emit(te.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,Te(Q({},n),{streamType:r,userId:e.userId}))},n=>{e.log.error("fallback",n)},()=>{s==="STARTED"&&e.log.info("fallback complete")}))}_updateVideoPlayOption(n){return b(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 b(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 gi&&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 Qi){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(te.TRACK,{userId:o,streamType:dr(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}_${dr(e.streamType)}`);if(!n)return;let a=n.observer||void 0;if(r===null||ut(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(_=>{_.forEach(I=>{l.set(I.target,I.isIntersecting),e.log.info(`view ${I.target.id} is${I.isIntersecting?"":" not"} visible`)}),clearTimeout(p),p=window.setTimeout(()=>{[...l.values()].find(R=>R)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:s}));let f=new Set(mn(r));l.forEach((_,I)=>{f.has(I)||(a.unobserve(I),l.delete(I))}),f.forEach(_=>{l.set(_,!0),a.observe(_)}),a.takeRecords().forEach(_=>{l.set(_.target,_.isIntersecting)}),n.visibleViewMap=l,n.observer=a}_exitRoom(){return b(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),this._clearRemoteTracks()})}_stopScreenShare(){return b(this,null,function*(){var e,r;if(this._localScreenTrack){if(this._room.isJoined){let o=[];(e=this._localScreenConfig)!=null&&e.publish&&o.push(this._localScreenTrack),this._localScreenAudioTrack&&o.push(this._localScreenAudioTrack),yield Promise.all(o.map(s=>this._room.unpublish(s).catch(()=>{})))}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(((r=this._localScreenAudioTrack.trackSettings)==null?void 0:r.echoCancellation)===!1&&this.stopPlugin("AudioProcessor"),this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),yt(this._localScreenTrack),this._localScreenTrack=null,delete this._room.capturedLocalAuxVideoTrack,this._localScreenConfig=null}})}_checkScreenAudioEchoCancellation(e,r){return b(this,null,function*(){var s,n;if(!e||!r)return;let o=(s=e.trackSettings)==null?void 0:s.displaySurface;if(((n=r.trackSettings)==null?void 0:n.echoCancellation)===!1&&(o==="monitor"||o==="browser"&&e.isShareCurrentTab)){this._log.warn("echoCancellation of screen audio track is disable. Try starting audioProcessor plugin");try{yield this.startPlugin("AudioProcessor",{sdkAppId:Number(this.room.sdkAppId),userId:this._room.userId,userSig:this.room.userSig,isScreenAudioNeedAudioProcess:!0,isLocalAudioNeedAudioProcess:!1})}catch(a){this._log.warn("start audioProcessor plugin failed: ",a)}}})}_onLocalTrackCaptured({track:e}){e.kind==="audio"&&(!kt||Ln(kt))&&(this._initActiveSpeaker(),x.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return b(this,null,function*(){if(kt&&!Ln(kt))this.emit(te.DEVICE_CHANGED,{type:"speaker",action:"active",device:kt});else{let e=yield No();e[0]&&!Ln(e[0])?(kt=e[0],this.emit(te.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):x.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(()=>{})}_onDataChannelAvailable(){if(this.listeners("realtime-transcriber-message").length>0)return this._room.subscribeDataChannel()}sendSEIMessage(e,r){var s;let o=this._plugins.get("SEI");o&&(o.update({buffer:e,options:Te(Q({seiPayloadType:243},r),{small:!!((s=this._localVideoTrack)!=null&&s.small)})}),J.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var r,o;(o=(r=this._room).sendCustomMessage)==null||o.call(r,e),J.addCount({key:500001,useUV:!0})}callExperimentalAPI(e,r){return b(this,null,function*(){return this._log.info(`callExperimentalAPI(${e}, ${JSON.stringify(r)})`),WT.call(e,Q({trtcInstance:this},r))})}static setLogLevel(e,r){B.setLogLevel(e),O(r)||(r?B.enableUploadLog():B.disableUploadLog())}static isSupported(){return Nu(_e.frameWorkType)}static getPermissions(o){return b(this,arguments,function*({request:e=!0,types:r=["camera","microphone"]}){e&&(yield Gc.request(r).catch(a=>{var d;return B.error(`getPermissions request failed, error: ${(d=a==null?void 0:a.message)!=null?d:a}`)}));let[s,n]=yield Promise.all([Gc.get("camera"),Gc.get("microphone")]);return{camera:s,microphone:n}})}static getCameraList(e=!0){return ar(e)}static getMicrophoneList(e=!0){return nr(e)}static getSpeakerList(e=!0){return No(e)}static setCurrentSpeaker(e){return b(this,null,function*(){if(rt&&(e===Vs.SPEAKER||e===Vs.HEADSET)){let o=yield _e.getMicrophoneList(),s="";if(o.forEach(n=>{n.label===e&&(s=n.deviceId)}),!s)return;jc.forEach(n=>b(null,null,function*(){n._localAudioTrack&&(yield n.updateLocalAudio({option:{microphoneId:s}}))}));return}(yield No()).forEach(o=>{o.deviceId===e&&(jc.forEach(s=>{s._setCurrentSpeaker(e),s.emit(te.DEVICE_CHANGED,{type:"speaker",action:"active",device:o})}),kt=o)})})}static _addKVStat({type:e,key:r,value:o,base:s,useUV:n,version:a,max:d}){switch(a&&(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}}get localVideoTrack(){return this._localVideoTrack}get localScreenTrack(){return this._localScreenTrack}get localScreenAudioTrack(){return this._localScreenAudioTrack}};m(_e,"VERSION",Rf),m(_e,"_loggerManager",B),m(_e,"EVENT",te),m(_e,"ERROR_CODE",oe),m(_e,"TYPE",Vs),m(_e,"frameWorkType",30),Z([at({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"}})})],_e.prototype,"use",1),Z([$t(wt.TRTC.enterRoom),Vo("room",([e],[r])=>(e.roomId||e.strRoomId)===(r.roomId||r.strRoomId)&&e.userId===r.userId&&e.sdkAppId===r.sdkAppId),Pe(e=>function(r){return this._log.setUserId(r.userId),this._log.setSdkAppId(r.sdkAppId),e.call(this,r)}),at()],_e.prototype,"enterRoom",1),Z([at()],_e.prototype,"exitRoom",1),Z([$t(wt.TRTC.switchRoom),at(),Wu()],_e.prototype,"switchRoom",1),Z([$t(wt.TRTC.switchRole),Bs("room",{merge:(e,r)=>r}),at()],_e.prototype,"switchRole",1),Z([at()],_e.prototype,"destroy",1),Z([$t(wt.TRTC.startLocalAudio),Vo("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)}),at()],_e.prototype,"startLocalAudio",1),Z([$t(wt.TRTC.updateLocalAudio),Bs("audio",{debounce:{delay:200,getKey:()=>`${jT}-localAudio`,isNeedToDebounce:e=>{var r;return!O((r=e.option)==null?void 0:r.captureVolume)}}}),at()],_e.prototype,"updateLocalAudio",1),Z([Fo("audio"),at()],_e.prototype,"stopLocalAudio",1),Z([$t(wt.TRTC.startLocalVideo),Vo("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)}),at()],_e.prototype,"startLocalVideo",1),Z([$t(wt.TRTC.updateLocalVideo),Bs("video"),at()],_e.prototype,"updateLocalVideo",1),Z([Fo("video"),at()],_e.prototype,"stopLocalVideo",1),Z([$t(wt.TRTC.startScreenShare),Vo("screen",()=>!0),at()],_e.prototype,"startScreenShare",1),Z([$t(wt.TRTC.updateScreenShare),Bs("screen"),at()],_e.prototype,"updateScreenShare",1),Z([at()],_e.prototype,"stopScreenShare",1),Z([$t(wt.TRTC.startRemoteVideo),Vo(e=>`v${e.userId}${e.streamType}`,()=>!0),at({getRemoteId:e=>`${e.userId}_${e.streamType}`})],_e.prototype,"startRemoteVideo",1),Z([$t(wt.TRTC.updateRemoteVideo),Bs(e=>`v${e.userId}${e.streamType}`),at({getRemoteId:e=>`${e.userId}_${e.streamType}`})],_e.prototype,"updateRemoteVideo",1),Z([$t(wt.TRTC.stopRemoteVideo),Pe(e=>function(r){return b(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)})}),at({getRemoteId:e=>`${e.userId}_${e.streamType}`})],_e.prototype,"stopRemoteVideo",1),Z([Fo(e=>`v${e.userId}${e.streamType}`)],_e.prototype,"_stopRemoteVideo",1),Z([$t(...wt.TRTC.muteRemoteAudio),at({getRemoteId:e=>e})],_e.prototype,"muteRemoteAudio",1),Z([vf(...wt.TRTC.setRemoteAudioVolume),UT(200,e=>e),at({getRemoteId:e=>e})],_e.prototype,"setRemoteAudioVolume",1),Z([Ml("start"),Do(e=>{var r;return(r=e.afterStart)==null?void 0:r.call(e)}),Vo((e,r)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(r)),at({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Ah[e.getName()],ignoreLog:e=>e.getName()==="Debug",ignoreErrorLog:e=>e.getName()==="AudioProcessor"})],_e.prototype,"startPlugin",1),Z([Ml("update"),Bs((e,r)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(r),{merge:(e,r)=>($r(e[1],r[1]),e)}),at({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>yh[e.getName()]})],_e.prototype,"updatePlugin",1),Z([Ml("stop"),Fo((e,r)=>{if(e.disableRandomCall)return null;let o=e.getGroup(r),s=e.getAlias();return o==="*"?new RegExp(`${s}.*`):s+o}),at({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>bh[e.getName()]})],_e.prototype,"stopPlugin",1),Z([vf(...wt.TRTC.enableAudioVolumeEvaluation)],_e.prototype,"enableAudioVolumeEvaluation",1),Z([at()],_e.prototype,"getVideoSnapshot",1),Z([at()],_e.prototype,"_setCurrentSpeaker",1),Z([Vo(e=>`a${e.userId}`,()=>!0)],_e.prototype,"_startRemoteAudio",1),Z([Pe(e=>function(r){return b(this,null,function*(){return r.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(o=>this._stopRemoteAudio(Te(Q({},r),{userId:o.userId})).catch(()=>{}))):e.call(this,r)})}),Fo(e=>`a${e.userId}`)],_e.prototype,"_stopRemoteAudio",1),Z([Fo("room")],_e.prototype,"_exitRoom",1),Z([Fo("screen")],_e.prototype,"_stopScreenShare",1),Z([$t(...wt.TRTC.sendSEIMessage),pf({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...e)=>e[0].byteLength})],_e.prototype,"sendSEIMessage",1),Z([$t(wt.TRTC.sendCustomMessage),pf({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],_e.prototype,"sendCustomMessage",1),Z([Bo()],_e,"create",1),Z([$t(wt.TRTC.create)],_e,"_create",1),Z([Bo()],_e,"setLogLevel",1),Z([Bo()],_e,"isSupported",1),Z([Bo(),at()],_e,"getPermissions",1),Z([Bo()],_e,"getCameraList",1),Z([Bo()],_e,"getMicrophoneList",1),Z([Bo()],_e,"getSpeakerList",1);var Lf=_e,Kn=Lf;var Wl=class{constructor(t,e){m(this,"_flag");m(this,"terminalType");m(this,"userId");m(this,"tinyId");m(this,"role");m(this,"remoteAudioTrack");m(this,"remoteVideoTrack");m(this,"remoteAuxiliaryTrack");this.userId=e.userId||"",this.tinyId=e.tinyId||"",this.role=e.role||"audience",this.terminalType=e.terminalType,this.remoteAudioTrack=new Qi(t,this),this.remoteVideoTrack=new Lo(t,this),this.remoteAuxiliaryTrack=new pl(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 xf=class{constructor(){m(this,"_set",new Set);x.on(V.LEAVE_SUCCESS,this.delete,this),x.on(V.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 Sv(){return b(this,null,function*(){let i,t;try{let I=yield nr();i=I&&I.length}catch(I){}try{let I=yield ar();t=I&&I.length}catch(I){}let e={microphone:i,camera:t},{isH264EncodeSupported:r,isVp8EncodeSupported:o,isH264DecodeSupported:s,isVp8DecodeSupported:n,isH265EncodeSupported:a,isH265DecodeSupported:d}=this.checkSystemResult.detail,l=Ro.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},_={isWebCodecSupported:l.isWebCodecSupported,isMediaSessionSupported:l.isMediaSessionSupported,isWebTransportSupported:l.isWebTransportSupported};Ue.uploadEvent({log:`trtcstats-${JSON.stringify(f)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(f)}`),Ue.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(_)}`,userId:this.userId}),xh()})}function zT(){return Pe(i=>{let t=new xf;return function(e,r,o){return b(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:z.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:z.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}`),x.emit(V.JOIN_START,{room:this,roomId:s,params:e});let n=ui.getEnv();n||(n=Ni.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(Rd.OLD_CLOUD_LADDER)?n=Ni.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(Rd.WEBRTC)&&(n=Ni.WEBRTC))),Ue.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:s}),Ro.checkSystemRequirementsInternal(o).then(a=>{this.checkSystemResult=a,Sv.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!ui.getEnv()&&(yield this.schedule(e,o));let a=yield i.call(this,e,r,o);return this.roomId=s,this._joinedTimestamp=ui.performanceNow(),x.emit(V.JOIN_SUCCESS,{room:this}),o===30&&!e.component&&Ue.uploadEvent({log:`stat-conv-${Number(zr)}-${location.hostname}`,userId:this.userId}),a}catch(a){throw t.delete({room:this,roomId:s}),x.emit(V.JOIN_FAILED,{room:this,error:a}),a}})}})}var JT=()=>Pe(i=>function(...t){return b(this,null,function*(){x.emit(V.LEAVE_START,{room:this}),yield i.call(this,...t),x.emit(V.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function XT(){return Pe(i=>function(...t){return b(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(t=t.filter(r=>r.outMediaTrack&&r.state==="ready"),!t.length))return;x.emit("61",{room:this});let e=i.apply(this,t);return Promise.all(t.map(r=>r.publish(this,e)))})})}function QT(){return Pe(i=>function(...t){let e=i.apply(this,t);return t.forEach(r=>r.unpublish()),e})}function YT(){return Pe(i=>function(...t){let e=i.apply(this,t);return t.forEach(r=>!r.isSubscribed&&r.subscribe(e)),e})}function Av({fn:i,context:t}){return function(...e){try{let r=i.apply(t,e);return ho(r)?r.catch(o=>B.error(`${i.name}() error observed ${o}`)):r}catch(r){B.error(`${i.name}() error observed ${r}`)}}}var Gl=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=B.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]=Av({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,gs().then(()=>{this._basicInfo.string_os_version=Jr(),this._basicInfo.string_device_name=Vi()||this._basicInfo.string_os_version})}addEvent(t,e){return this._eventMap.set(t,e),x.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(V.JOIN_START,this.handleJoinStart).addEvent(V.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(V.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(V.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(V.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(V.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(V.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(V.JOIN_FAILED,this.handleJoinFailed).addEvent(V.LEAVE_START,this.handleLeaveStart).addEvent(V.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(V.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(V.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(V.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(V.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(V.PUBLISH_START,this.handlePublishStart).addEvent(V.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(V.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(V.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(V.PLAY_TRACK_START,this.handlePlayStart).addEvent(V.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(V.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(V.SWITCH_ROOM_START,this.handleSwitchRoomStart).addEvent(V.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess).addEvent(V.SWITCH_ROOM_FAILED,this.handleSwitchRoomFailed).addEvent(V.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(V.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(V.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(V.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(V.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)=>x.off(e,t)),this._eventMap.clear()}destroy(){this.uninstallEvents(),mt.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()):z.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=pe()-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()):z.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:Te(Q({},yv),{msg_user_info:new qc({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 qc({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,J.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/$i*100)>0&&(this._localStreamStat.totalAudioLevel+=n/$i,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(_=>{let I=_.uint32_video_stream_type===2,R=_.uint32_video_stream_type===7,y=`${p}_${I?"main":"auxiliary"}`,N=this._remoteStreamStatMap.get(y);if(N&&(I&&(f!=null&&f.remoteVideoTrack.isSubscribed)||R&&(f!=null&&f.remoteAuxiliaryTrack))){N.totalVideoFPS+=_.uint32_video_receive_fps,N.totalVideoBitrate+=_.uint32_video_codec_bitrate,N.videoCount++,N.statsToReport.uint32_video_width===0&&(N.statsToReport.uint32_video_width=_.uint32_video_width),N.statsToReport.uint32_video_height===0&&(N.statsToReport.uint32_video_height=_.uint32_video_height);let P=I?f.remoteVideoTrack:f.remoteAuxiliaryTrack;P.stat.jitterBufferDelay&&(N.videoJitterBufferDelay=P.stat.jitterBufferDelay),P.stat.framesReceived&&(N.statsToReport.uint32_video_consume_render_rate=Math.floor(P.stat.framesDecoded/P.stat.framesReceived*ni(10,6)))}}),!un(d)){let _=`${p}_main`,I=this._remoteStreamStatMap.get(_);this._remoteStreamStatMap.has(_)&&I&&f!=null&&f.remoteAudioTrack.isSubscribed&&(I.totalAudioBitrate+=d.uint32_audio_codec_bitrate,I.audioCount++,f.remoteAudioTrack.stat.jitterBufferDelay&&(I.audioJitterBufferDelay=f.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(d.uint32_audio_level/$i*100)>0&&(I.totalAudioLevel+=d.uint32_audio_level/$i,I.audioLevelCount++),d.uint32_audio_block_time&&(I.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():z.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&ba)>=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:_,videoDelayCount:I,totalAudioDelay:R,totalVideoDelay:y}=o;t.statsToReport.uint32_avg_down_loss=Math.floor(p/f),_&&R&&(t.statsToReport.uint32_audio_network_p2p_delay=Math.floor(R/_),t.audioJitterBufferDelay&&(t.statsToReport.uint32_p2p_delay=Math.floor(t.statsToReport.uint32_audio_network_p2p_delay+t.audioJitterBufferDelay))),I&&y&&(t.statsToReport.uint32_video_network_p2p_delay=Math.floor(y/I))}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=Ld();let t={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new qc({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 Ma(t),t}report(){return b(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 b(this,null,function*(){if(t.msg_path_enter_room.uint64_start_time===0)return;let e=Number(this._room.sdkAppId),r=Io.enable?Oi(t,2001,e):yield Hm(t),o=r instanceof ArrayBuffer,s=`${Mi(e,mo.KEY_POINT)}&gzip=${+o}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(s,r));let a=[this.uploadKVStat(J),this.uploadKVStat(Is)];n||a.push(Pi({url:s,body:r,priority:"low"})),yield Promise.all(a)})}setConnectionType(t){this.connectionType=t,this._basicInfo.uint32_connection_type=t}uploadKVStat(r){return b(this,arguments,function*(t,e=this._room.sdkAppId){var l,p;let o=t.getReportData((l=this._room)==null?void 0:l.userSig,(p=this._signalInfo)==null?void 0:p.reportToken);if(o.stats_count.length===0&&o.stats_distribution.length===0)return;o.msg_sdk_basic_info=Te(Q({},o.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(o);let s=Io.enable?Oi(o,2003,e):yield Hm(o),n=s instanceof ArrayBuffer,a=`${Mi(+e,mo.KV_STAT)}&gzip=${+n}`,d=!1;navigator.sendBeacon&&(d=navigator.sendBeacon(a,s)),d||Pi({url:a,body:s})})}};Z([ys({settings:{timeout:500,retries:3}})],Gl.prototype,"upload",1);var $s=5e3,yv={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},qc=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}},ZT=Gl;var kf=class{constructor(){m(this,"_startTime");m(this,"_endTime");this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=pe())}stop(){this._endTime===0&&(this._endTime=pe())}getDuration(){return this._endTime===0?pe()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},jl=kf;var Uf=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(V.REMOTE_TRACK_SUBSCRIBED,this.handleSubscribed).set(V.REMOTE_TRACK_UNSUBSCRIBED,this.handleUnsubscribed).set(V.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)=>x.on(e,t,this))}uninstallEvents(){this._eventMap.forEach((t,e)=>x.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 jl,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()}},KT=Uf;var Vf=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||nt)&&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()}},Ff=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 Vf);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(V.LEAVE_SUCCESS,({room:t})=>{this.hitTest(t)&&this.stop()}).set(V.PLAY_TRACK_START,this.onPlayTrackStart).set(V.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(V.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(V.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(V.HEARTBEAT_REPORT,this.onHearBeatReport).set(V.REMOTE_VIDEO_PLAY_START,this.onRemoteVideoPlayStart).set(V.REMOTE_VIDEO_PLAY_FINISH,this.onRemoteVideoPlayEnd),this._eventMap.forEach((t,e)=>x.on(e,t,this))}uninstallEvents(){this._eventMap.forEach((t,e)=>x.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 jl;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=pe();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&&Ue.uploadEvent({userId:this._room.userId,log:`stat-${Ot.VIDEO_DECODE_FAILED_DURING_CALL}`})}else{let d=this._remoteVideoAbnormalTimestampMap.get(`${r}-decode`);d&&a-d>=this.ABNORMAL_TIME_UPPER_LIMIT&&(Ue.uploadEvent({userId:this._room.userId,log:`stat-${Ot.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){Ue.uploadEvent({userId:this._room.userId,log:`stat-${Ot.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&&(Ue.uploadEvent({userId:this._room.userId,log:`stat-${Ot.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=pe();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&&Ue.uploadEvent({userId:this._room.userId,log:`stat-${Ot.VIDEO_ENCODE_FAILED_DURING_CALL}`})}else{let a=this._videoAbnormalTimestampMap.get("local-encode");a&&n-a>=this.ABNORMAL_TIME_UPPER_LIMIT&&Ue.uploadEvent({userId:this._room.userId,log:`stat-${Ot.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=pe();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&&Ue.uploadEvent({userId:this._room.userId,log:`stat-${Ot.AUDIO_ENCODE_FAILED_DURING_CALL}`})}else{let n=this._audioAbnormalTimestampMap.get("local-encode");n&&s-n>=this.ABNORMAL_TIME_UPPER_LIMIT&&Ue.uploadEvent({userId:this._room.userId,log:`stat-${Ot.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>Nd){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()<Nd&&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(!Qr())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,_=d.presentationTime-r;if(_>f){_=Math.min(_,5e3);let I=`${t.userId}_${t.streamType}`,R=this._monitorFreezeData.get(I,"render");R?R.duration+=_:this._monitorFreezeData.set(I,{userId:t.userId,type:t.streamType,duration:_},"render");let y=this._renderFreezeMap.get(I);y?(y.totalDuration+=_,y.count+=1):this._renderFreezeMap.set(I,{userId:t.userId,type:t.streamType,totalDuration:_,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()}},eI=Ff;var iI=ai(mi(),1);var ql=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?J.addSuccessEvent({key:s.key}):J.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:_,offset:I}=this.calculateBoundary(d,s,t,r),{min:R,offset:y}=this.calculateBoundary(l,n,e,o);return p=2*_+r,f=2*R+o,p/f>this.originalAspect?(p=f*this.originalAspect,I=d-p/2):(f=p/this.originalAspect,y=l-f/2),r/s>a&&(I=0,y=0,p=s,f=n),I=Math.max(0,Math.min(I,s-p)),y=Math.max(0,Math.min(y,n-f)),{sx:I,sy:y,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=Q({},t),this.animationState.target=Q({},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)),Be(this.animationState.current.scaleOffsetX)&&Be(this.animationState.target.scaleOffsetX)&&Be(this.animationState.current.scaleOffsetY)&&Be(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,_,I,R,y,N,P,W,G;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:(I=(_=this.animationState.current)==null?void 0:_.scaleOffsetY)!=null?I:0,timestamp:Date.now()};this.animationState.target={sx:t/2,sy:o+n/2,cropWidth:t,cropHeight:e,scaleRatio:(y=(R=this.animationState.target)==null?void 0:R.scaleRatio)!=null?y:1,scaleOffsetX:(P=(N=this.animationState.target)==null?void 0:N.scaleOffsetX)!=null?P:0,scaleOffsetY:(G=(W=this.animationState.target)==null?void 0:W.scaleOffsetY)!=null?G: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 bv=`#version 300 es
105
+ ${o.stack}`),!1}},i};var Yn=new WeakMap;function kT(i){let t=Yn.get(i);t&&(t.forEach(e=>clearTimeout(e)),Yn.delete(i))}function UT(i,t){return Pe((e,r)=>function(...o){let s=Yn.get(this);s||(s=new Map,Yn.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=Yn.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=Yn.get(this))==null||l.delete(n)},i);s.set(n,d)}})}var FT="trtc-sdk-v5",Rf="5.15.1-wasm.3";function $t(...i){return Pe((t,e)=>function(...r){try{wl.call(this,i,r,e,this._name)}catch(o){return Promise.reject(o)}return t.apply(this,r)})}function vf(...i){return Pe((t,e)=>function(...r){try{wl.call(this,i,r,e,this._name)}catch(o){throw o}return t.apply(this,r)})}function wl(i,t,e,r){if(ut(i))for(let o=0;o<i.length;o++)Dl.call(this,{rule:i[o],value:t[o],key:i[o].name,fnName:e,className:r});else Dl.call(this,{rule:i,value:t[0],key:i.name,fnName:e,className:r})}function Dl({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 ne(s(5001));if(O(i.defaultValue)){Xe(i.validate)&&i.validate.call(this,t,e,r,o,this);return}t=i.defaultValue}if(Array.isArray(i.type)){let d=!1;for(let l=0;l<i.type.length;l++)i.type[l]===null&&t===null&&(d=!0),Xe(i.type[l])&&t instanceof i.type[l]&&(d=!0),Oe(i.type[l])&&gt(t)===i.type[l].toLowerCase()&&(d=!0);if(!d)throw new ne({code:oe.INVALID_PARAMETER,extraCode:5002,fnName:r,messageParams:{key:e,rule:{type:i.type.map(l=>cs(l)?dn(l):Oe(l)?l:gt(l))},value:t}})}else if(!O(i.type)&&gt(t)!==i.type)throw new ne(s(5002));if(i.allowEmpty===!1){let d=Be(t)&&(t===0||Number.isNaN(t)),l=Oe(t)&&t.trim()==="";if(d||l)throw new ne(s(5003))}if(i.notLessThanZero&&Be(t)&&t<0)throw new ne(s(5006));if(!O(i.min)&&Be(t)&&t<i.min)throw new ne(s(5007));if(!O(i.max)&&Be(t)&&t>i.max)throw new ne(s(5008));if(Oe(i.instanceOf)){if(!t||t._name!==i.instanceOf)throw new ne(s(5004))}else if(Xe(i.instanceOf)&&!(t instanceof i.instanceOf))throw new ne(s(5004));if(Array.isArray(i.values)&&!i.values.includes(t))throw new ne(s(5005));let{properties:n}=i;Jt(n)&&fr(t)&&Object.keys(n).forEach(d=>{Dl.call(this,{rule:n[d],value:t&&t[d],key:`${d}`,fnName:r,className:o})});let{arrayItem:a}=i;Jt(a)&&ut(t)&&t.forEach((d,l)=>{Dl.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 hv=0;function at(i={}){let{getRemoteId:t=()=>"",replaceArg:e,getKVReportKey:r,ignoreLog:o,ignoreErrorLog:s}=i;return Pe((n,a)=>function(...d){var R,y,N;function l(P,W,G){if(G&&G.includes(P))return"hided";if(e){let ae=e(...d);if(d[ae.argIndex]===W)return ae.value}if(W===d||P in d)return W;try{return W instanceof HTMLElement?`id: ${W.id} type:${gt(W)}`:W instanceof MediaStreamTrack?Vd(W):(JSON.stringify(W),W)}catch(ae){return`type:${gt(W)}`}}let p=(this==null?void 0:this._log)||B,f=++hv;if(o!=null&&o(...d))return n.apply(this,d);d.length>0?p.info(`${a}() ${f} ${JSON.stringify(d,(P,W)=>l(P,W,["userSig","privateMapKey"]))}`):p.info(`${a}() ${f}`);let _=r?r(...d):yu[a],I=(s==null?void 0:s(...d))||!1;try{let P=n.apply(this,d),W=pe();if(ho(P)){let G=`${a.includes("Plugin")?`${((y=(R=d[0]).getName)==null?void 0:y.call(R))||""} `:" "}`;return P.then(ae=>(p.info(`${a}() success ${f} ${G}${t.call(this,...d)}`),J.addSuccessEvent({key:_,cost:pe()-W}),ae)).catch(ae=>{var Or;ae=ne.convertFrom.call(this,ae,a,d.length===1?d[0]:d);let ke=ae.extraCode||ae.code,Me=(Or=ae.message)!=null&&Or.includes(ke)?"":` code:${ke}`,Y=(ae==null?void 0:ae.code)===oe.OPERATION_ABORT;throw I||p[Y?"warn":"error"](`${a}() failed ${f} ${G}${t.call(this,...d)} ${ae}${Me} params: ${JSON.stringify(d,l)}`),J.addFailedEvent({key:_,error:ae}),ae})}return J.addSuccessEvent({key:_}),P}catch(P){P=ne.convertFrom.call(this,P,a);let W=P.extraCode||P.code,G=(N=P.message)!=null&&N.includes(W)?"":` code:${W}`,ae=(P==null?void 0:P.code)===oe.OPERATION_ABORT;throw I||p[ae?"warn":"error"](`${a}() failed ${f} ${P}${G} params: ${JSON.stringify(d,l)}`),J.addFailedEvent({key:_,error:P}),P}})}var Ml=i=>Pe((t,e)=>function(r,o){return b(this,null,function*(){let s=this._plugins.get(r);if(!s)throw this._log.error(`plugin ${String(r)} is not found`),new ne({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 ne({code:oe.ENV_NOT_SUPPORTED,message:`plugin ${String(r)} is not supported`,extraCode:5210,fnName:e});return wl.call(this,s.getValidateRule(i),[o],e,"TRTC"),t.call(this,s,o)})});var Ol=0,Cf,eo=class eo{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");Ol=Ol+1,this.log=t.log.createChild({id:`${this.getAlias()}${Ol}`}),this.log.info(`created id=${this.getAlias()}${Ol}`),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 ne({code:oe.INVALID_OPERATION,extraCode:5106,fnName:o})}}}preload(t){return Cf||(Cf=this.doPreload(t)),Cf}doPreload(t){return b(this,null,function*(){let e=yield this.core.fileDownloader.download(t,{type:"blob"}),r=URL.createObjectURL(e);try{yield qi(this.audioContext,r)}catch(o){this.log.error(`preload audioProcessor failed. ${o}`)}finally{URL.revokeObjectURL(r)}})}getName(){return eo.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(t){switch(t){case"start":return eo.getStartValidateRule(this.core);case"update":return eo.updateValidateRule;case"stop":return eo.stopValidateRule}}start(t){return b(this,null,function*(){var _,I,R,y;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 ne({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:N,status:P,timestamp:W}=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,W,N,P,e)}if(f&&!this.screenAudioWorkletNode){let{sign:N,status:P,timestamp:W}=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,W,N,P,e)}this.mixNode||(this.mixNode=this.audioContext.createGain(),this.mixNode.gain.value=1),this.silentNode||(this.silentNode=this.audioContext.createConstantSource(),this.silentNode.offset.setValueAtTime(0,this.audioContext.currentTime),this.silentNode.start()),(_=this.localAudioWorkletNode)==null||_.port.postMessage({type:"enable"}),(I=this.screenAudioWorkletNode)==null||I.port.postMessage({type:"enable"}),e.audioManager.addAudioProcessor(this.mixNode,this.silentNode,this.localAudioWorkletNode,this.screenAudioWorkletNode),O(a)||a.forEach(N=>{this.customAudioReferenceMap.set(N,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:N,refId:`o-${this.audioRefId++}`})}),O(d)||(R=this.localAudioWorkletNode)==null||R.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:d}}),O(l)||(y=this.localAudioWorkletNode)==null||y.port.postMessage({type:"dump",data:{enable:l}})})}update(t){return b(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 b(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 b(this,null,function*(){let o=String(Date.now()).slice(0,-3),{auth:s,sign:n,status:a,message:d}=yield fv({sdkAppId:t,userSig:r,userId:e,timestamp:o});if(!s)throw this.log.info(`audioProcessor: ${e} auth result: ${s}. Message: ${d}`),new ne({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 _=(p==null?void 0:p.value)>10?"info":"debug";this.log[_](`${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":x.emit("265",{room:d,data:p.value,type:e==="localAudio"?"dump":"dump-screen-audio"});return;case"detectEcho":this.log.warn(`${e==="localAudio"?"":`[${e}] `}detect echo: ${fs()?Vi():Jr()}`);return}}}handleLocalAudioStarted(t){return b(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 b(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(eo,"updateValidateRule",{type:"object"}),m(eo,"stopValidateRule",{type:"object"}),m(eo,"Name","AudioProcessor");var Pl=eo;function pv(i,t=M.MAIN){return`https://${ei[t]||Nl(i,t)}/api/v1/audioAiAuth`}function fv(o){return b(this,arguments,function*({sdkAppId:i,userId:t,userSig:e,timestamp:r}){let n=`${pv(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 _=Rr(i)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",I="Init RTCAudioProcessor failed.",R="";switch(d){case 1:R="Please check your params.";break;case 2:R=`You need to buy packages. Refer to: ${_}`;break;case 3:R="Server is invalid. Please contact our engineer. ";break;case 4:R=`Your packages is not active. Refer to: ${_}`;break;case 5:R=`Your packages is expired. Refer to: ${_}`;break;case 6:R="Your version is not supported.";break}return{auth:!1,status:f,message:l?`${I} Reason: ${l}. ${R}`:`${I}, ${R}`}})}var Ll=0,Nf=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 b(this,null,function*(){if(t.url){let e=yield Vc.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 Zn(i,t){if(t&&typeof t!="function")throw new ne({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);Ll=Ll+1,this.log=t.log.createChild({id:`${this.getAlias()}${Ll}`}),this.log.info(`created id=${this.getAlias()}${Ll}`)}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 b(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 Nf(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.`),J.addEnum({key:502700,value:3}),this.kvUpload(t)})}handleAutoPlayFailed(t,e,r){return b(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(()=>{x.off("154",o,this)})};x.on("154",o,this),Dn()}else this.core.trtc.emit(te.AUTOPLAY_FAILED,{userId:"",mediaType:"audio",resume:()=>b(this,null,function*(){return t.play()})});else throw r})}update(t){return b(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 b(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&&J.addCount({key:502009}),r&&J.addCount({key:502001}),o&&J.addCount({key:502002}),s&&J.addCount({key:502003}),n&&J.addCount({key:502004}),a&&J.addCount({key:502005}),typeof d!="function"&&J.addCount({key:502007}),typeof p!="function"&&J.addCount({key:502008}),typeof l!="function"&&J.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 ne({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 ne({code:oe.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:r});Zn("onTimeUpdate",t.onTimeUpdate),Zn("onEnded",t.onEnded),Zn("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){Zn("onTimeUpdate",t.onTimeUpdate),Zn("onEnded",t.onEnded),Zn("onDurationChange",t.onDurationChange)}}),m(Ii,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),m(Ii,"Name","AudioMixer");var xl=Ii;var kl=0,Df,to=class to{constructor(t){this.core=t;m(this,"log");m(this,"audioContext",ze("denoiser"));m(this,"workletNode");m(this,"config",{enableFarFieldReduce:!1,farFieldReduceThreshold:.5});kl=kl+1,this.log=t.log.createChild({id:`${this.getAlias()}${kl}`}),this.log.info(`created id=${this.getAlias()}${kl}`)}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 ne({code:oe.INVALID_OPERATION,extraCode:5106,fnName:o})}}}preload(t){return Df||(Df=this.doPreload(t)),Df}doPreload(t){return b(this,null,function*(){let e=yield this.core.fileDownloader.download(t,{type:"blob"}),r=URL.createObjectURL(e);try{yield qi(this.audioContext,r)}catch(o){throw this.log.error("load worklet failed",o),o}finally{URL.revokeObjectURL(r)}})}getName(){return to.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser"}getValidateRule(t){switch(t){case"start":return to.startValidateRule(this.core);case"update":return to.updateValidateRule;case"stop":return to.stopValidateRule}}start(t){return b(this,null,function*(){let{room:e,schedule:r}=this.core,{assetsPath:o=this.core.assetsPath}=t;if(!o)throw new ne({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${Ph()?"":"-nosimd"}.js`),!this.workletNode){let s=String(Date.now()).slice(0,-3),{auth:n,sign:a,status:d,message:l}=yield Ev(r,Te(Q({},t),{timestamp:s}));if(!n)throw this.log.info(`RTCAIDenoiser: ${t.userId} auth result: ${n}. Message: ${l}`),new ne({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 _;let{data:f}=p;if(f.type==="cost"){let I=(f==null?void 0:f.max)>20?"warn":(f==null?void 0:f.max)>10?"info":"debug";this.log[I](`avg cost: ${f.value} max: ${f==null?void 0:f.max}(${Ks(new Date(f==null?void 0:f.maxCostTimestamp))}) hist: ${(_=f==null?void 0:f.hist)==null?void 0:_.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 b(this,null,function*(){this.updateConfig(t)})}stop(){return b(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(to,"updateValidateRule",{type:"object",properties:{mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}}}),m(to,"stopValidateRule",{type:"object"}),m(to,"Name","AIDenoiser");var Ul=to;function Ev(s,n){return b(this,arguments,function*(i,{sdkAppId:t,userId:e,userSig:r,timestamp:o}){try{let{data:{errCode:a,errMsg:d,sign:l,status:p}}=yield i.getAbilityConfig(t,i.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:t,userId:e,userSig:r,timestamp:o});if(p==="1")return{auth:!0,sign:l,status:p,message:d};let f=Rr(t)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",_="Init RTCAIDenoiser failed.",I="";switch(a){case 1:I="Please check your params.";break;case 2:I=`You need to buy packages. Refer to: ${f}`;break;case 3:I="Server is invalid. Please contact our engineer. ";break;case 4:I=`Your packages is not active. Refer to: ${f}`;break;case 5:I=`Your packages is expired. Refer to: ${f}`;break;case 6:I="Your version is not supported.";break}return{auth:!1,status:p,message:d?`${_} Reason: ${d}. ${I}`:`${_}, ${I}`}}catch(a){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${a}`}}})}var $T=ai(mi(),1);var wf=class extends $T.EventEmitter{constructor(){super();m(this,"observer");m(this,"state","nominal");this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return b(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!rt&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){Ue.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let r=this.stateNum,o=e[e.length-1];this.state=o.state,(this.stateNum>3||r>3)&&B.info(`${o.source}: ${o.state}`),this.emit("state-changed",{type:o.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(r){Ue.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:r})}}},_v=new wf,Mf=_v;var Of=0,Bc=class Bc{constructor(t){this.core=t;m(this,"log");m(this,"_seiMessageList",[]);m(this,"_smallSeiMessageList",[]);m(this,"_subStreamSeiMessageList",[]);Of++,this.log=t.log.createChild({id:`${this.getAlias()}${Of}`}),this.log.info(`[sei] created id=${this.getAlias()}${Of}`),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 yf({frame:t,seiMessageList:r})}catch(r){this.log.warn(r)}return t}decode({frame:t,track:e}){return bf({frame:t,onSEI:r=>{r.forEach(o=>{e!=null&&e.userId?this.core.trtc.emit(te.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:yf,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:Ss?this.decode:bf,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 Bc.Name}getAlias(){return"sei"}getGroup(){return"sei"}};m(Bc,"autoStart",!0),m(Bc,"Name","SEI");var Vl=Bc;var Tv=0,Fl,$c=class $c{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()}${++Tv}`}),this.log.info("created")}getName(){return $c.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 b(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 b(this,arguments,function*({visible:t}){t?yield this.openDebugDiaLog():this.closeDebugDiaLog()})}stop(){this.closeDebugDiaLog()}destroy(){this.stop()}openDebugDiaLog(){return b(this,null,function*(){var t;if(!this.dialog)try{if(Fl)yield Fl;else{let e=new URLSearchParams(location.search).get("trtcDebugDialogPath")||((t=window.sessionStorage)==null?void 0:t.getItem("TRTC_DEBUG_DIALOG_PATH"))||`https://unpkg.com/${FT}@${ft}/assets/debug-dialog.js`;Fl=this._core.fileDownloader.loadScript(e),yield Fl}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($c,"Name","Debug"),m($c,"autoStart",!0);var Bl=$c;var HT=i=>{switch(i){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},$l=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,he.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:HT(this.type),error:p}),d>4?this.startOB.error(p):this.startOB.next(d+1)})),be(l,Kr(1),kp(Sc))};be(this.startOB,Tc(0),fi(a),Je(this.stopOB),Le(()=>{e.player.setOutput(),n.next("STARTED")},d=>{n.next("FAILED")},()=>{o.addSuccessEvent({key:HT(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 zi()(e=>b(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"}))}},Iv={type:"object"},Hc=class Hc{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 Hc.Name}getGroup(t){return t.track.userId+t.track.streamType}getName(){return Hc.Name}getValidateRule(t){return Iv}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 $l(this.core,r,t);return be(o.trackDoneOB,Kr(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 $l(this.core,t.track,t))}}};m(Hc,"Name","TRTCAudioDecoder");var Wc=Hc;var Hl=class{constructor(){m(this,"log");this.log=B.createLogger({id:"exp"})}call(t,e){return b(this,null,function*(){return Xe(this[t])?this[t](e):Promise.reject(new ce({code:z.INVALID_PARAMETER,message:je({key:Ge.API_NOT_EXIST,data:{name:t}})}))})}enableAudioFrameEvent(t){return b(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 _=d.getPCM(I=>{e.emit(te.AUDIO_FRAME,I)},f.userId);l.set(f.userId,_)}});else{if(l.get(o))return;let f=d.getPCM(_=>{e.emit(te.AUDIO_FRAME,_)},o);l.set(o,f)}else if(o==="*")e.room.remotePublishedUserMap.forEach(f=>{if(f.remoteAudioTrack.isSubscribed){let{userId:_}=f,I=l.get(_);I==null||I.abort("disable"),l.delete(_)}});else{let f=l.get(o);f==null||f.abort("disable"),l.delete(o)}})}resumeRemotePlayer(t){return b(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([I_({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"}}})],Hl.prototype,"enableAudioFrameEvent",1);var WT=new Hl;var GT=ai(mi(),1);var Pf=class extends GT.EventEmitter{constructor(){super();m(this,"states",{});m(this,"permissionChangeHandler");m(this,"log");this.log=B.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 b(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 b(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={}}},Gc=new Pf;var jT=0,jc=new Set,kt=null;_m(Rf);Rn.checkStorage();var _e=class _e extends qT.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",B.createLogger({id:`t${++jT}`}));m(this,"_plugins",new Map);m(this,"_networkQuality",null);m(this,"_speakerId");m(this,"enterRoomParams");m(this,"_enableAutoSwitchWhenRecapturing",!0);m(this,"_autoSubscribeDataChannel",!1);this._room=new e(Q({logger:this._log,frameWorkType:_e.frameWorkType},r)),this._room.videoDecodeFallbackType=r.videoDecodeFallback,Ze(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(xl,r.assetsPath),this._use(Pl,r.assetsPath),this._use(Ul,r.assetsPath),this._use(Wc,r.assetsPath),this._use(Bl),r.enableSEI&&ic&&this._use(Vl),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(te.AUDIO_VOLUME,{result:o.sort((a,d)=>d.volume-a.volume)})}),this._room.videoManager.on("error",o=>{this._log.error(new ne({code:oe.OPERATION_FAILED,extraCode:5504,message:o.message,originError:o}))}),this._listenEvents(),this._initActiveSpeaker(),xT(this,"trtc")}static create(e){}static _create(e,r){pT();let o=new _e(e,r||{});return jc.add(o),o.__v_skip=!0,o}get room(){return this._room}_listenEvents(){Vt(this,this._room).add("peer-join",e=>{let{userId:r}=e;this.emit(te.REMOTE_USER_ENTER,{userId:r})}).add("peer-leave",({userId:e,reason:r})=>{this.emit(te.REMOTE_USER_EXIT,{userId:e,reason:r})}).add("banned",e=>{Ki(!0),this._exitRoom().finally(()=>{this.emit(te.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().finally(()=>{this.emit(te.ERROR,ne.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(te.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let r=Te(Q({},e),{uplinkRTT:Math.min(e.uplinkRTT,va),downlinkRTT:Math.min(e.downlinkRTT,va)});this.emit(te.NETWORK_QUALITY,r)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(o=>{Vt(o,o).add("player-state-changed",s=>{let n=Te(Q({},s),{userId:e.userId});o.kind===M.VIDEO&&(n.streamType=dr(o.streamType)),this.emit(o.kind===M.AUDIO?te.AUDIO_PLAY_STATE_CHANGED:te.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",s=>{s.getCode()===z.PLAY_NOT_ALLOWED&&this.emit(te.AUTOPLAY_FAILED,{userId:o.userId,mediaType:o.strMediaType,resume:()=>o.player.resume()})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(o=>{yt(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?te.REMOTE_VIDEO_AVAILABLE:te.REMOTE_VIDEO_UNAVAILABLE,{userId:o,streamType:"main"})),s!==a&&(a?this._onAudioAvailable({userId:o}):this._onAudioUnavailable({userId:o,muteState:r}),this.emit(a?te.REMOTE_AUDIO_AVAILABLE:te.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?te.REMOTE_VIDEO_AVAILABLE:te.REMOTE_VIDEO_UNAVAILABLE,{userId:o,streamType:"sub"})),e.hasDatachannel!==r.hasDatachannel&&r.hasDatachannel&&this._onDataChannelAvailable()}).add("sei-message",e=>{this.emit(te.SEI_MESSAGE,Te(Q({},e),{streamType:dr(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(te.ERROR,new ne({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,va),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)/$i},video:e.msg_up_stream_info.msg_video_status.filter(_=>r[_.uint32_video_stream_type]).map(_=>({bitrate:(_.uint32_video_codec_bitrate||0)/1e3,width:_.uint32_video_width,height:_.uint32_video_height,frameRate:_.uint32_video_enc_fps,videoType:r[_.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(_=>({userId:_.msg_user_info.str_identifier,audio:{bitrate:(_.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(_.msg_audio_status.uint32_audio_level||0)/$i,point2pointDelay:(_.msg_audio_status.uint32_audio_p2p_delay||0)+(_.msg_audio_status.uint32_audio_cache_ms||0),jitterBufferDelay:_.msg_audio_status.uint32_audio_cache_ms||0},video:_.msg_video_status.map(I=>({bitrate:(I.uint32_video_codec_bitrate||0)/1e3,width:I.uint32_video_width,height:I.uint32_video_height,frameRate:I.uint32_video_dec_fps,videoType:r[I.uint32_video_stream_type],point2pointDelay:(I.uint32_video_p2p_delay||0)+(I.uint32_video_cache_ms||0),jitterBufferDelay:I.uint32_video_cache_ms||0,codec:I.uint32_video_codec}))}))};this.emit(te.STATISTICS,o)}).add("custom-message",e=>{this.emit(te.CUSTOM_MESSAGE,e)}).add("layerData",e=>this.emit(te.LAYER_DATA,e)).add("first-video-frame",e=>{this.emit(te.FIRST_VIDEO_FRAME,Te(Q({},e),{streamType:dr(e.streamType)}))}).add("audio-frame",e=>{this.emit(te.AUDIO_FRAME,e)}).add("data-channel-message",e=>{var s,n,a,d,l;let{data:r}=e;if(r.sender==="")return;let o={segmentId:(s=r.payload)==null?void 0:s.roundid,speakerUserId:r.sender,sourceText:(n=r.payload)==null?void 0:n.text,translationTexts:(a=r.payload)==null?void 0:a.translate_msg,timestamp:(d=r.payload)==null?void 0:d.start_utc_ms,isCompleted:(l=r.payload)==null?void 0:l.end,robotId:r.robotid};o.sourceText!==""&&this.emit(te.REALTIME_TRANSCRIBER_MESSAGE,o)}).add("asr-robot-peer-join",e=>{this.emit(te.REALTIME_TRANSCRIBER_STATE_CHANGED,{state:"started",roomId:this.room.roomId,transcriberRobotId:e.userId})}).add("asr-robot-peer-leave",e=>{this.emit(te.REALTIME_TRANSCRIBER_STATE_CHANGED,{state:"stopped",roomId:this.room.roomId,transcriberRobotId:e.userId})}),Vt(this,lt).add("audioInputAdded",e=>{this.emit(te.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(te.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(te.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(te.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>b(this,null,function*(){if(this.emit(te.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),kt&&kt.deviceId===Ra){let r=(yield No()).find(o=>o.deviceId===Ra);r&&kt.groupId!==r.groupId&&(kt=r,this.emit(te.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}))}})).add("audioOutputRemoved",e=>b(this,null,function*(){this.emit(te.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let r=(yield No())[0];if(!r||!kt||kt.groupId===r.groupId)return;let o=kt.deviceId===e.deviceId,s=kt.deviceId===Ra&&kt.deviceId===r.deviceId;(o||s)&&(kt=r,this.emit(te.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}))})),Vt(this,Gc).add("permission-state-change",e=>{this.emit(te.PERMISSION_STATE_CHANGE,e)}),this.room.enableSEI&&this.on(te.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(LT.call(this,{TRTC:_e,room:this._room,assetsPath:r,errorModule:{RtcError:ne,ErrorCode:oe,CoreErrorCode:z,ErrorCodeDictionary:Sr}}));return this._plugins.set(e.Name,s),s.__v_skip=!0,e.autoStart&&this.startPlugin(e.Name),s}enterRoom(e){return b(this,null,function*(){var d,l;this.enterRoomParams=e;let{scene:r="rtc",enableAutoPlayDialog:o=!0,autoReceiveAudio:s=!0,autoReceiveVideo:n=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!Oe(e.proxy)&&e.proxy.turnServer&&((l=(d=this._room).setTurnServer)==null||l.call(d,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=o,this._room.autoReceiveAudio=s,this._room.autoReceiveVideo=n,Ze(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,enableDataChannel:this._plugins.has("RealtimeTranscriber"),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,_e.frameWorkType),this._checkTrackToPublish(),Mf.start()})}exitRoom(){return b(this,null,function*(){return yield this._exitRoom()})}switchRoom(e){return b(this,null,function*(){if(this.room.isSwitchRoomSupported())try{this._clearRemoteTracks(),yield this._room.switchRoom(e)}catch(r){if(r instanceof Ia&&(r.code===z.API_CALL_TIMEOUT||r.code===z.SWITCH_ROOM_FAILED))this._log.warn(`switchRoom ${r.code===z.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 b(this,null,function*(){yield this.exitRoom();let r=Q(Q({},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(),kT(this),this._room.remotePublishedUserMap.forEach(e=>{yt(e.remoteAudioTrack),yt(e.remoteVideoTrack),yt(e.remoteAuxiliaryTrack)})}switchRole(e,r){return b(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(),yt(this),this.removeAllListeners(),this._room.destroy(),jc.delete(this),jc.size===0&&Mf.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),x.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return b(this,arguments,function*(e={publish:!0}){if(this._localAudioTrack){this._log.warn("local audio is already started");return}let{publish:r=!0,mute:o,muteKeepVolumeDetection:s,option:n}=e,a=new gi(this._room.audioManager),d={},l={muted:!0};n&&(O(n.microphoneId)?O(n.audioTrack)||(d.customSource=n.audioTrack):d.deviceId=n.microphoneId,n&&Be(n.captureVolume)&&a.setCaptureVolume(n.captureVolume),O(n.profile)||(Oe(n.profile)?yd[n.profile]&&a.setProfile(yd[n.profile]):a.setProfile(n.profile)),Be(n.earMonitorVolume)&&(l.muted=!(n.earMonitorVolume>0),l.volume=n.earMonitorVolume),O(n.echoCancellation)||(a.profile.echoCancellation=n.echoCancellation),O(n.noiseSuppression)||(a.profile.noiseSuppression=n.noiseSuppression),O(n.autoGainControl)||(a.profile.autoGainControl=n.autoGainControl),Ze(this._enableAutoSwitchWhenRecapturing)&&(a.enableAutoSwitchWhenRecapturing=this._enableAutoSwitchWhenRecapturing)),a.on("5",p=>{this.emit(te.ERROR,new ne({code:oe.DEVICE_ERROR,extraCode:5309,messageParams:{error:p}}))}),a.on("2",p=>{this.emit(te.DEVICE_CHANGED,{type:"microphone",action:"active",device:p})}),a.on("4",p=>{let f;p.error&&(f=ne.convertFrom(p.error)),this.emit(te.PUBLISH_STATE_CHANGED,Te(Q({},p),{error:f}))}),a.on("6",()=>{}),this._listenOutputTrackChanged(a),this._speakerId&&a.setAudioOutput(this._speakerId),yield a.capture(d),O(o)||a.setMute(o,s),Vt(a,a).add("player-state-changed",p=>{this.emit(te.AUDIO_PLAY_STATE_CHANGED,Te(Q({},p),{userId:""}))}),r&&this._room.isJoined&&this._room.publish(a).catch(()=>{}),this._localAudioTrack=a,this._room.capturedLocalMainAudioTrack=a,this._localAudioConfig=Te(Q({},e),{publish:r}),yield this._updateAudioPlayOption({playOption:l,track:a}),x.emit("113",{userId:"",room:this.room})})}updateLocalAudio(e){return b(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:r,mute:o,muteKeepVolumeDetection:s,option:n}=e,a={};n&&(n.microphoneId?yield this._localAudioTrack.switchDevice(n.microphoneId):O(n.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(n.audioTrack)),O(n.captureVolume)||this._localAudioTrack.setCaptureVolume(n.captureVolume),O(n.earMonitorVolume)||(a.muted=!(n.earMonitorVolume>0),a.volume=n.earMonitorVolume),yield this._localAudioTrack.update3A(n)),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,s),yield this._updateAudioPlayOption({playOption:a,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),$r(this._localAudioConfig,e)})}stopLocalAudio(){return b(this,null,function*(){this._localAudioTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),x.emit("114",{userId:"",room:this.room}),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),yt(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null,delete this._room.capturedLocalMainAudioTrack)})}startLocalVideo(){return b(this,arguments,function*(e={publish:!0,view:null,capture:!0}){var _,I;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=o,l=new Ir(this._room.videoManager),p={},f={};a&&(Ze(a.avoidCropping)&&(l.avoidCropping=a.avoidCropping),a.cameraId?p.deviceId=a.cameraId:O(a.useFrontCamera)?O(a.videoTrack)||(p.customSource=a.videoTrack):p.facingMode=a.useFrontCamera?M.FACING_MODE_USER:M.FACING_MODE_ENVIRONMENT,O(a.retryWhenExactFailed)||(p.retryWhenExactFailed=a.retryWhenExactFailed),a.qosPreference&&(p.contentHint=kc(a.qosPreference)),O(a.profile)||(Oe(a.profile)?Fr[a.profile]&&l.setProfile(Fr[a.profile]):l.setProfile(a.profile)),O(a.fillMode)||(f.objectFit=a.fillMode),O(a.mirror)||(f.mirror=a.mirror),O(a.small)||(O(a.smallMode)||(this._room.smallMode=a.smallMode),Ze(a.small)&&a.small===!1?l.stopSmall():l.updateSmallConfig(Jn(a.small,!0))),O(a.rotation)||l.setRotation(a.rotation),Ze(this._enableAutoSwitchWhenRecapturing)&&(l.enableAutoSwitchWhenRecapturing=this._enableAutoSwitchWhenRecapturing)),l.once("first-video-frame",R=>{this.emit(te.FIRST_VIDEO_FRAME,Te(Q({},R),{streamType:dr(R.streamType)}))}),l.on("5",R=>{this.emit(te.ERROR,new ne({code:oe.DEVICE_ERROR,extraCode:5308,messageParams:{error:R}}))}),l.on("2",R=>{this.emit(te.DEVICE_CHANGED,{type:"camera",action:"active",device:R})}),l.on("4",R=>{let y;R.error&&(y=ne.convertFrom(R.error)),this.emit(te.PUBLISH_STATE_CHANGED,Te(Q({},R),{error:y}))}),l.on("6",()=>{}),this._listenOutputTrackChanged(l),s?yield l.capture(p):(_=l.manager)==null||_.changeInput(l),O(n)||(yield l.setMute(n)),Vt(l,l).add("player-state-changed",R=>{this.emit(te.VIDEO_PLAY_STATE_CHANGED,Te(Q({},R),{userId:"",streamType:"main"}))}).add("video-size-changed",R=>{this.emit(te.VIDEO_SIZE_CHANGED,Te(Q({},R),{streamType:dr(R.streamType)}))}),d&&this._room.isJoined&&(this._localScreenTrack&&((I=this._localScreenConfig)==null?void 0:I.publish)&&this._localScreenConfig.streamType==="main"?(d=!1,this._log.warn("main stream is already published, local video track will not publish")):this._room.publish(l).catch(()=>{})),this._localVideoTrack=l,this._room.capturedLocalMainVideoTrack=l,this._localVideoConfig=Te(Q({},e),{view:r,publish:d,capture:s}),yield this._updateVideoPlayOption({view:r,playOption:f,track:l})})}updateLocalVideo(e){return b(this,null,function*(){var f,_,I,R;if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:r,publish:o=!0,mute:s,capture:n,option:a,forcePublish:d=!1}=e,l=o||d,p={};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 y={};y.deviceId=(a==null?void 0:a.cameraId)||((f=this._localVideoConfig.option)==null?void 0:f.cameraId),y.facingMode=a!=null&&a.useFrontCamera||(_=this._localVideoConfig.option)!=null&&_.useFrontCamera?M.FACING_MODE_USER:M.FACING_MODE_ENVIRONMENT,y.customSource=(a==null?void 0:a.videoTrack)||((I=this._localVideoConfig.option)==null?void 0:I.videoTrack),yield this._localVideoTrack.capture(y)}a&&(O(a.profile)||(Oe(a.profile)?Fr[a.profile]&&this._localVideoTrack.setProfile(Fr[a.profile]):this._localVideoTrack.setProfile(a.profile),(!a.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(a.cameraId||a.useFrontCamera?M.FACING_MODE_USER:M.FACING_MODE_ENVIRONMENT))&&(yield this._localVideoTrack.applyProfile())),O(a.fillMode)||(p.objectFit=a.fillMode),O(a.mirror)||(p.mirror=a.mirror),O(a.rotation)||this._localVideoTrack.setRotation(a.rotation),a.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(kc(a.qosPreference)),O(a.small)||(Ze(a.small)&&!a.small?this._localVideoTrack.stopSmall():this._localVideoTrack.updateSmallConfig(Jn(a.small,!0)))),this._room.isJoined&&O(l)&&this._localVideoConfig.publish&&n&&!this._localVideoConfig.capture&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._room.isJoined&&((l!=null?l:this._localVideoConfig.publish)||d?!(this._localScreenTrack&&((R=this._localScreenConfig)==null?void 0:R.publish)&&this._localScreenConfig.streamType==="main")||d?this._room.publish(this._localVideoTrack).catch(()=>{}):(l=!1,this._log.warn("main stream is already published, local video track will not publish")):this._room.unpublish(this._localVideoTrack).catch(()=>{})),O(s)||(yield this._localVideoTrack.setMute(s)),yield this._updateVideoPlayOption({view:r,playOption:p,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),$r(this._localVideoConfig,Te(Q({},e),{publish:l}))})}stopLocalVideo(){return b(this,null,function*(){var e;this._localVideoTrack&&(this._room.isJoined&&((e=this._localVideoConfig)!=null&&e.publish)&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),yt(this._localVideoTrack),this._localVideoTrack=null,delete this._room.capturedLocalMainVideoTrack,this._localVideoConfig=null)})}startScreenShare(){return b(this,arguments,function*(e={publish:!0,view:null}){var I,R,y;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=o,d=new Ei(this._room.videoManager);d.on("4",N=>{let P;N.error&&(P=ne.convertFrom(N.error)),this.emit(te.PUBLISH_STATE_CHANGED,Te(Q({},N),{error:P}))}),d.once("first-video-frame",N=>{this.emit(te.FIRST_VIDEO_FRAME,Te(Q({},N),{streamType:dr(N.streamType)}))}),this._listenOutputTrackChanged(d),e.streamType==="main"&&(d.mediaType=4);let l=null,p={},f={};n&&(O(n.profile)||(Oe(n.profile)?bd[n.profile]&&d.setProfile(bd[n.profile]):d.setProfile(n.profile)),n.systemAudio&&(p.systemAudio=!0,p.echoCancellation=n.echoCancellation,p.noiseSuppression=n.noiseSuppression,p.autoGainControl=n.autoGainControl),O(n.fillMode)||(f.objectFit=n.fillMode),n.videoTrack&&(p.videoTrack=n.videoTrack),n.audioTrack&&(p.audioTrack=n.audioTrack),n.captureElement&&(p.captureElement=n.captureElement),n.preferDisplaySurface&&(p.preferDisplaySurface=n.preferDisplaySurface),n.qosPreference&&(p.contentHint=kc(n.qosPreference)));let _=yield d.capture(p);if(d.mediaTrack.addEventListener(M.ENDED,()=>{this._stopScreenShare(),this.emit(te.SCREEN_SHARE_STOPPED)}),_.getAudioTracks()[0]){l=new xs(this._room.audioManager);let N=_.getAudioTracks()[0];(I=e.option)!=null&&I.systemAudio&&!((R=e.option)!=null&&R.audioTrack)&&(l.sourceTrack=N),yield l.setInputMediaStreamTrack(N),Ze(s)&&l.mediaTrack&&(l.mediaTrack.enabled=!s),this._speakerId&&l.setAudioOutput(this._speakerId)}if(Vt(d,d).add("player-state-changed",N=>{this.emit(te.VIDEO_PLAY_STATE_CHANGED,Te(Q({},N),{userId:"",streamType:"sub"}))}),a&&this._room.isJoined){let N=this._localVideoTrack&&((y=this._localVideoConfig)==null?void 0:y.publish);!(e.streamType==="main"&&N)?this._room.publish(d).catch(()=>{}):(a=!1,this._log.warn("main stream is already published, screen share main will not publish")),l&&(this._checkScreenAudioEchoCancellation(d,l),this._room.publish(l).catch(()=>{}))}this._localScreenTrack=d,this._room.capturedLocalAuxVideoTrack=d,this._localScreenAudioTrack=l,this._localScreenConfig=Te(Q({},e),{view:r,publish:a}),yield this._updateVideoPlayOption({view:r,playOption:f,track:d})})}updateScreenShare(e){return b(this,null,function*(){var l,p;if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:r,publish:o,muteSystemAudio:s,option:n}=e,a=o,d={};if(n){if(O(n.fillMode)||(d.objectFit=n.fillMode),n.qosPreference){let f=kc(n.qosPreference);this._localScreenTrack.setContentHint(f)}n.videoTrack&&this._localScreenTrack.setInputMediaStreamTrack(n.videoTrack),n.audioTrack&&this._localScreenAudioTrack&&this._localScreenAudioTrack.setInputMediaStreamTrack(n.audioTrack)}if(this._room.isJoined&&!O(a)){if(a&&!this._localScreenConfig.publish){let f=this._localVideoTrack&&((l=this._localVideoConfig)==null?void 0:l.publish);!(this._localScreenConfig.streamType==="main"&&f)?this._room.publish(this._localScreenTrack).catch(()=>{}):(a=!1,this._log.warn("main stream is already published, screen share main will not publish")),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch(()=>{})}if(this._localScreenConfig.publish&&!a){let f=[this._localScreenTrack];this._localScreenAudioTrack&&f.push(this._localScreenAudioTrack),f.forEach(_=>this._room.unpublish(_).catch(()=>{}))}}(p=this._localScreenAudioTrack)!=null&&p.mediaTrack&&Ze(s)&&(this._localScreenAudioTrack.mediaTrack.enabled=!s),yield this._updateVideoPlayOption({view:r,playOption:d,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),$r(this._localScreenConfig,Te(Q({},e),{publish:a}))})}stopScreenShare(){return b(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return b(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,f=this._bindRemoteVideoTrackEvents(p);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,handlers:f}),n&&!O(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:p,view:r,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:n==null?void 0:n.viewRoot})})}updateRemoteVideo(e){return b(this,null,function*(){var P,W;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,_=this._room.remotePublishedUserMap.get(o);if(s==="main"&&(_!=null&&_.muteState.hasVideo)&&(f=_.remoteVideoTrack),s==="sub"&&(_!=null&&_.muteState.hasAuxiliary)&&(f=_.remoteAuxiliaryTrack),!f)return;let{config:I}=l;s==="main"&&n&&!O(n.small)&&this._room.changeType(n.small,f.user),n&&!O(n.draggable)&&f.setDraggable(n.draggable),n&&(Ze(n.pictureInPicture)&&(n.pictureInPicture?yield f.player.enterPictureInPicture():yield f.player.exitPictureInPicture()),Ze(n.fullScreen)&&(n.fullScreen?yield f.player.enterFullscreen():yield f.player.exitFullscreen())),Ze(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:I}),$r(I,e);let R=O(n==null?void 0:n.receiveWhenViewVisible)?(P=I.option)==null?void 0:P.receiveWhenViewVisible:n.receiveWhenViewVisible,y=O(r)?I.view:r,N=O(n==null?void 0:n.viewRoot)?(W=I.option)==null?void 0:W.viewRoot:n.viewRoot;this._observeView({remoteTrack:f,view:y,receiveWhenViewVisible:R,viewRoot:N})})}stopRemoteVideo(e){return b(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,r=!0){return b(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);if(s&&(s.observer&&s.observer.disconnect(),s.handlers)){let n=this._room.remotePublishedUserMap.get(e);if(n){let a=r==="main"?n.remoteVideoTrack:n.remoteAuxiliaryTrack;this._unbindRemoteVideoTrackEvents(a,s.handlers)}}this._remoteVideoConfigMap.delete(o)}_bindRemoteVideoTrackEvents(e){let r={onEnterPIP:()=>b(this,null,function*(){yield e.player.enterPIPPromise,this.emit(te.PICTURE_IN_PICTURE_STATE_CHANGED,{streamType:dr(e.streamType),userId:e.userId,isPictureInPicture:!0,pictureInPictureWindow:e.player.pipWindow})}),onLeavePIP:()=>{this.emit(te.PICTURE_IN_PICTURE_STATE_CHANGED,{streamType:dr(e.streamType),userId:e.userId,isPictureInPicture:!1})},onEnterFullScreen:()=>{this.emit(te.FULL_SCREEN_STATE_CHANGED,{streamType:dr(e.streamType),userId:e.userId,isFullScreen:!0})},onLeaveFullScreen:()=>{this.emit(te.FULL_SCREEN_STATE_CHANGED,{streamType:dr(e.streamType),userId:e.userId,isFullScreen:!1})},onDecodeFailed:()=>{this.emit(te.ERROR,new ne({code:oe.OPERATION_FAILED,extraCode:5507,message:"video decode failed"}))},onVideoSizeChanged:o=>{this.emit(te.VIDEO_SIZE_CHANGED,Te(Q({},o),{streamType:dr(o.streamType)}))}};return e.player.on(ue.ENTER_PICTURE_IN_PICTURE,r.onEnterPIP),e.player.on(ue.LEAVE_PICTURE_IN_PICTURE,r.onLeavePIP),e.player.on(ue.ENTER_FULL_SCREEN,r.onEnterFullScreen),e.player.on(ue.LEAVE_FULL_SCREEN,r.onLeaveFullScreen),e.on("decode-failed",r.onDecodeFailed),e.on("video-size-changed",r.onVideoSizeChanged),r}_unbindRemoteVideoTrackEvents(e,r){e.player.off(ue.ENTER_PICTURE_IN_PICTURE,r.onEnterPIP),e.player.off(ue.LEAVE_PICTURE_IN_PICTURE,r.onLeavePIP),e.player.off(ue.ENTER_FULL_SCREEN,r.onEnterFullScreen),e.player.off(ue.LEAVE_FULL_SCREEN,r.onLeaveFullScreen),e.off("decode-failed",r.onDecodeFailed),e.off("video-size-changed",r.onVideoSizeChanged)}muteRemoteAudio(e,r){return b(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 b(this,null,function*(){return e.start(r)})}updatePlugin(e,r){return b(this,null,function*(){return e.update(r)})}stopPlugin(e,r){return b(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(te.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 e==="realtime-transcriber-message"&&this._room.subscribeDataChannel(),this}emit(e,...r){try{RT.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==="realtime-transcriber-message"||e==="*")&&this.listeners("realtime-transcriber-message").length===0&&this._room.unsubscribeDataChannel(),(e===_e.EVENT.AUDIO_FRAME||e==="*")&&this.listeners(_e.EVENT.AUDIO_FRAME).length===0){let{getPCMAbortCtrlMap:s}=this.room.audioManager;s.forEach(n=>{n==null||n.abort("off")}),s.clear()}return this}getAudioTrack(e={userId:"",streamType:"main"}){let r,o=null,s="main",n=!1;if(Oe(e)?r=e:(r=e.userId,n=e.processed===!0,e.streamType&&(s=e.streamType)),r){let a=this._room.remotePublishedUserMap.get(r);a&&(o=a.remoteAudioTrack)}else o=s==="sub"?this._localScreenAudioTrack:this._localAudioTrack;return o?n&&o.outMediaTrack&&o.outMediaTrack!==o.mediaTrack?o.outMediaTrack.clone():o.mediaTrack:null}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:r="",streamType:o="main",processed:s=!1}=e,n=null;if(r==="")o==="main"&&this._localVideoTrack&&(n=this._localVideoTrack),o==="sub"&&this._localScreenTrack&&(n=this._localScreenTrack);else{let a=this._room.remotePublishedUserMap.get(r);a&&(n=o==="main"?a.remoteVideoTrack:a.remoteAuxiliaryTrack)}return n?s&&n.outMediaTrack&&n.outMediaTrack!==n.mediaTrack?n.outMediaTrack.clone():n.mediaTrack:null}getVideoSnapshot(e={}){let{userId:r,streamType:o="main"}=e;if(r){let s=this._room.remotePublishedUserMap.get(r);if(o==="main"&&(s!=null&&s.muteState.hasVideo))return s.remoteVideoTrack.getVideoFrame();if(o==="sub"&&(s!=null&&s.muteState.hasAuxiliary))return s.remoteAuxiliaryTrack.getVideoFrame()}else{if(o==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(o==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(e){var r,o;this._speakerId=e,(r=this._localAudioTrack)==null||r.setAudioOutput(e),(o=this._localScreenAudioTrack)==null||o.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(s=>s.remoteAudioTrack.setAudioOutput(e))}setCurrentSpeaker(e){return b(this,null,function*(){(yield No()).forEach(o=>{o.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(te.DEVICE_CHANGED,{type:"speaker",action:"active",device:o}),kt=o)}),this._log.warn(`the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: ${ir}/en/TRTC.html#.setCurrentSpeaker`)})}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return b(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(te.ERROR,new ne({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=Be(d)?d:100;s.volume=l,this._remoteAudioConfigMap.set(r,e),yield this._room.subscribe(n),be(ye(n,"decode-failed"),Je(ye(n,he.INIT)),Le(()=>{this.startPlugin(Wc.Name,{track:n,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:s,track:n}),x.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 b(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}`),x.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,he.INIT)),ws(()=>{this._room.downlinkVideoCodec!=="h265"&&this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:o})}),Ji(ye(e,"decode-downgrade-state-changed")),Le(n=>{s=n.state,this.emit(te.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,Te(Q({},n),{streamType:r,userId:e.userId}))},n=>{e.log.error("fallback",n)},()=>{s==="STARTED"&&e.log.info("fallback complete")}))}_updateVideoPlayOption(n){return b(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 b(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 gi&&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 Qi){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(te.TRACK,{userId:o,streamType:dr(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}_${dr(e.streamType)}`);if(!n)return;let a=n.observer||void 0;if(r===null||ut(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(_=>{_.forEach(I=>{l.set(I.target,I.isIntersecting),e.log.info(`view ${I.target.id} is${I.isIntersecting?"":" not"} visible`)}),clearTimeout(p),p=window.setTimeout(()=>{[...l.values()].find(R=>R)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:s}));let f=new Set(mn(r));l.forEach((_,I)=>{f.has(I)||(a.unobserve(I),l.delete(I))}),f.forEach(_=>{l.set(_,!0),a.observe(_)}),a.takeRecords().forEach(_=>{l.set(_.target,_.isIntersecting)}),n.visibleViewMap=l,n.observer=a}_exitRoom(){return b(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),this._clearRemoteTracks()})}_stopScreenShare(){return b(this,null,function*(){var e,r;if(this._localScreenTrack){if(this._room.isJoined){let o=[];(e=this._localScreenConfig)!=null&&e.publish&&o.push(this._localScreenTrack),this._localScreenAudioTrack&&o.push(this._localScreenAudioTrack),yield Promise.all(o.map(s=>this._room.unpublish(s).catch(()=>{})))}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(((r=this._localScreenAudioTrack.trackSettings)==null?void 0:r.echoCancellation)===!1&&this.stopPlugin("AudioProcessor"),this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),yt(this._localScreenTrack),this._localScreenTrack=null,delete this._room.capturedLocalAuxVideoTrack,this._localScreenConfig=null}})}_checkScreenAudioEchoCancellation(e,r){return b(this,null,function*(){var s,n;if(!e||!r)return;let o=(s=e.trackSettings)==null?void 0:s.displaySurface;if(((n=r.trackSettings)==null?void 0:n.echoCancellation)===!1&&(o==="monitor"||o==="browser"&&e.isShareCurrentTab)){this._log.warn("echoCancellation of screen audio track is disable. Try starting audioProcessor plugin");try{yield this.startPlugin("AudioProcessor",{sdkAppId:Number(this.room.sdkAppId),userId:this._room.userId,userSig:this.room.userSig,isScreenAudioNeedAudioProcess:!0,isLocalAudioNeedAudioProcess:!1})}catch(a){this._log.warn("start audioProcessor plugin failed: ",a)}}})}_onLocalTrackCaptured({track:e}){e.kind==="audio"&&(!kt||Ln(kt))&&(this._initActiveSpeaker(),x.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return b(this,null,function*(){if(kt&&!Ln(kt))this.emit(te.DEVICE_CHANGED,{type:"speaker",action:"active",device:kt});else{let e=yield No();e[0]&&!Ln(e[0])?(kt=e[0],this.emit(te.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):x.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(()=>{})}_onDataChannelAvailable(){if(this.listeners("realtime-transcriber-message").length>0)return this._room.subscribeDataChannel()}sendSEIMessage(e,r){var s;let o=this._plugins.get("SEI");o&&(o.update({buffer:e,options:Te(Q({seiPayloadType:243},r),{small:!!((s=this._localVideoTrack)!=null&&s.small)})}),J.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var r,o;(o=(r=this._room).sendCustomMessage)==null||o.call(r,e),J.addCount({key:500001,useUV:!0})}callExperimentalAPI(e,r){return b(this,null,function*(){return this._log.info(`callExperimentalAPI(${e}, ${JSON.stringify(r)})`),WT.call(e,Q({trtcInstance:this},r))})}static setLogLevel(e,r){B.setLogLevel(e),O(r)||(r?B.enableUploadLog():B.disableUploadLog())}static isSupported(){return Nu(_e.frameWorkType)}static getPermissions(o){return b(this,arguments,function*({request:e=!0,types:r=["camera","microphone"]}){e&&(yield Gc.request(r).catch(a=>{var d;return B.error(`getPermissions request failed, error: ${(d=a==null?void 0:a.message)!=null?d:a}`)}));let[s,n]=yield Promise.all([Gc.get("camera"),Gc.get("microphone")]);return{camera:s,microphone:n}})}static getCameraList(e=!0){return ar(e)}static getMicrophoneList(e=!0){return nr(e)}static getSpeakerList(e=!0){return No(e)}static setCurrentSpeaker(e){return b(this,null,function*(){if(rt&&(e===Vs.SPEAKER||e===Vs.HEADSET)){let o=yield _e.getMicrophoneList(),s="";if(o.forEach(n=>{n.label===e&&(s=n.deviceId)}),!s)return;jc.forEach(n=>b(null,null,function*(){n._localAudioTrack&&(yield n.updateLocalAudio({option:{microphoneId:s}}))}));return}(yield No()).forEach(o=>{o.deviceId===e&&(jc.forEach(s=>{s._setCurrentSpeaker(e),s.emit(te.DEVICE_CHANGED,{type:"speaker",action:"active",device:o})}),kt=o)})})}static _addKVStat({type:e,key:r,value:o,base:s,useUV:n,version:a,max:d}){switch(a&&(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}}get localVideoTrack(){return this._localVideoTrack}get localScreenTrack(){return this._localScreenTrack}get localScreenAudioTrack(){return this._localScreenAudioTrack}};m(_e,"VERSION",Rf),m(_e,"_loggerManager",B),m(_e,"EVENT",te),m(_e,"ERROR_CODE",oe),m(_e,"TYPE",Vs),m(_e,"frameWorkType",30),Z([at({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"}})})],_e.prototype,"use",1),Z([$t(wt.TRTC.enterRoom),Vo("room",([e],[r])=>(e.roomId||e.strRoomId)===(r.roomId||r.strRoomId)&&e.userId===r.userId&&e.sdkAppId===r.sdkAppId),Pe(e=>function(r){return this._log.setUserId(r.userId),this._log.setSdkAppId(r.sdkAppId),e.call(this,r)}),at()],_e.prototype,"enterRoom",1),Z([at()],_e.prototype,"exitRoom",1),Z([$t(wt.TRTC.switchRoom),at(),Wu()],_e.prototype,"switchRoom",1),Z([$t(wt.TRTC.switchRole),Bs("room",{merge:(e,r)=>r}),at()],_e.prototype,"switchRole",1),Z([at()],_e.prototype,"destroy",1),Z([$t(wt.TRTC.startLocalAudio),Vo("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)}),at()],_e.prototype,"startLocalAudio",1),Z([$t(wt.TRTC.updateLocalAudio),Bs("audio",{debounce:{delay:200,getKey:()=>`${jT}-localAudio`,isNeedToDebounce:e=>{var r;return!O((r=e.option)==null?void 0:r.captureVolume)}}}),at()],_e.prototype,"updateLocalAudio",1),Z([Fo("audio"),at()],_e.prototype,"stopLocalAudio",1),Z([$t(wt.TRTC.startLocalVideo),Vo("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)}),at()],_e.prototype,"startLocalVideo",1),Z([$t(wt.TRTC.updateLocalVideo),Bs("video"),at()],_e.prototype,"updateLocalVideo",1),Z([Fo("video"),at()],_e.prototype,"stopLocalVideo",1),Z([$t(wt.TRTC.startScreenShare),Vo("screen",()=>!0),at()],_e.prototype,"startScreenShare",1),Z([$t(wt.TRTC.updateScreenShare),Bs("screen"),at()],_e.prototype,"updateScreenShare",1),Z([at()],_e.prototype,"stopScreenShare",1),Z([$t(wt.TRTC.startRemoteVideo),Vo(e=>`v${e.userId}${e.streamType}`,()=>!0),at({getRemoteId:e=>`${e.userId}_${e.streamType}`})],_e.prototype,"startRemoteVideo",1),Z([$t(wt.TRTC.updateRemoteVideo),Bs(e=>`v${e.userId}${e.streamType}`),at({getRemoteId:e=>`${e.userId}_${e.streamType}`})],_e.prototype,"updateRemoteVideo",1),Z([$t(wt.TRTC.stopRemoteVideo),Pe(e=>function(r){return b(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)})}),at({getRemoteId:e=>`${e.userId}_${e.streamType}`})],_e.prototype,"stopRemoteVideo",1),Z([Fo(e=>`v${e.userId}${e.streamType}`)],_e.prototype,"_stopRemoteVideo",1),Z([$t(...wt.TRTC.muteRemoteAudio),at({getRemoteId:e=>e})],_e.prototype,"muteRemoteAudio",1),Z([vf(...wt.TRTC.setRemoteAudioVolume),UT(200,e=>e),at({getRemoteId:e=>e})],_e.prototype,"setRemoteAudioVolume",1),Z([Ml("start"),Do(e=>{var r;return(r=e.afterStart)==null?void 0:r.call(e)}),Vo((e,r)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(r)),at({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Ah[e.getName()],ignoreLog:e=>e.getName()==="Debug",ignoreErrorLog:e=>e.getName()==="AudioProcessor"})],_e.prototype,"startPlugin",1),Z([Ml("update"),Bs((e,r)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(r),{merge:(e,r)=>($r(e[1],r[1]),e)}),at({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>yh[e.getName()]})],_e.prototype,"updatePlugin",1),Z([Ml("stop"),Fo((e,r)=>{if(e.disableRandomCall)return null;let o=e.getGroup(r),s=e.getAlias();return o==="*"?new RegExp(`${s}.*`):s+o}),at({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>bh[e.getName()]})],_e.prototype,"stopPlugin",1),Z([vf(...wt.TRTC.enableAudioVolumeEvaluation)],_e.prototype,"enableAudioVolumeEvaluation",1),Z([at()],_e.prototype,"getVideoSnapshot",1),Z([at()],_e.prototype,"_setCurrentSpeaker",1),Z([Vo(e=>`a${e.userId}`,()=>!0)],_e.prototype,"_startRemoteAudio",1),Z([Pe(e=>function(r){return b(this,null,function*(){return r.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(o=>this._stopRemoteAudio(Te(Q({},r),{userId:o.userId})).catch(()=>{}))):e.call(this,r)})}),Fo(e=>`a${e.userId}`)],_e.prototype,"_stopRemoteAudio",1),Z([Fo("room")],_e.prototype,"_exitRoom",1),Z([Fo("screen")],_e.prototype,"_stopScreenShare",1),Z([$t(...wt.TRTC.sendSEIMessage),pf({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...e)=>e[0].byteLength})],_e.prototype,"sendSEIMessage",1),Z([$t(wt.TRTC.sendCustomMessage),pf({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],_e.prototype,"sendCustomMessage",1),Z([Bo()],_e,"create",1),Z([$t(wt.TRTC.create)],_e,"_create",1),Z([Bo()],_e,"setLogLevel",1),Z([Bo()],_e,"isSupported",1),Z([Bo(),at()],_e,"getPermissions",1),Z([Bo()],_e,"getCameraList",1),Z([Bo()],_e,"getMicrophoneList",1),Z([Bo()],_e,"getSpeakerList",1);var Lf=_e,Kn=Lf;var Wl=class{constructor(t,e){m(this,"_flag");m(this,"terminalType");m(this,"userId");m(this,"tinyId");m(this,"role");m(this,"remoteAudioTrack");m(this,"remoteVideoTrack");m(this,"remoteAuxiliaryTrack");this.userId=e.userId||"",this.tinyId=e.tinyId||"",this.role=e.role||"audience",this.terminalType=e.terminalType,this.remoteAudioTrack=new Qi(t,this),this.remoteVideoTrack=new Lo(t,this),this.remoteAuxiliaryTrack=new pl(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 xf=class{constructor(){m(this,"_set",new Set);x.on(V.LEAVE_SUCCESS,this.delete,this),x.on(V.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 Sv(){return b(this,null,function*(){let i,t;try{let I=yield nr();i=I&&I.length}catch(I){}try{let I=yield ar();t=I&&I.length}catch(I){}let e={microphone:i,camera:t},{isH264EncodeSupported:r,isVp8EncodeSupported:o,isH264DecodeSupported:s,isVp8DecodeSupported:n,isH265EncodeSupported:a,isH265DecodeSupported:d}=this.checkSystemResult.detail,l=Ro.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},_={isWebCodecSupported:l.isWebCodecSupported,isMediaSessionSupported:l.isMediaSessionSupported,isWebTransportSupported:l.isWebTransportSupported};Ue.uploadEvent({log:`trtcstats-${JSON.stringify(f)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(f)}`),Ue.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(_)}`,userId:this.userId}),xh()})}function zT(){return Pe(i=>{let t=new xf;return function(e,r,o){return b(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:z.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:z.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}`),x.emit(V.JOIN_START,{room:this,roomId:s,params:e});let n=ui.getEnv();n||(n=Ni.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(Rd.OLD_CLOUD_LADDER)?n=Ni.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(Rd.WEBRTC)&&(n=Ni.WEBRTC))),Ue.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:s}),Ro.checkSystemRequirementsInternal(o).then(a=>{this.checkSystemResult=a,Sv.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!ui.getEnv()&&(yield this.schedule(e,o));let a=yield i.call(this,e,r,o);return this.roomId=s,this._joinedTimestamp=ui.performanceNow(),x.emit(V.JOIN_SUCCESS,{room:this}),o===30&&!e.component&&Ue.uploadEvent({log:`stat-conv-${Number(zr)}-${location.hostname}`,userId:this.userId}),a}catch(a){throw t.delete({room:this,roomId:s}),x.emit(V.JOIN_FAILED,{room:this,error:a}),a}})}})}var JT=()=>Pe(i=>function(...t){return b(this,null,function*(){x.emit(V.LEAVE_START,{room:this}),yield i.call(this,...t),x.emit(V.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function XT(){return Pe(i=>function(...t){return b(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(t=t.filter(r=>r.outMediaTrack&&r.state==="ready"),!t.length))return;x.emit("61",{room:this});let e=i.apply(this,t);return Promise.all(t.map(r=>r.publish(this,e)))})})}function QT(){return Pe(i=>function(...t){let e=i.apply(this,t);return t.forEach(r=>r.unpublish()),e})}function YT(){return Pe(i=>function(...t){let e=i.apply(this,t);return t.forEach(r=>!r.isSubscribed&&r.subscribe(e)),e})}function Av({fn:i,context:t}){return function(...e){try{let r=i.apply(t,e);return ho(r)?r.catch(o=>B.error(`${i.name}() error observed ${o}`)):r}catch(r){B.error(`${i.name}() error observed ${r}`)}}}var Gl=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=B.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]=Av({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,gs().then(()=>{this._basicInfo.string_os_version=Jr(),this._basicInfo.string_device_name=Vi()||this._basicInfo.string_os_version})}addEvent(t,e){return this._eventMap.set(t,e),x.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(V.JOIN_START,this.handleJoinStart).addEvent(V.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(V.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(V.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(V.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(V.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(V.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(V.JOIN_FAILED,this.handleJoinFailed).addEvent(V.LEAVE_START,this.handleLeaveStart).addEvent(V.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(V.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(V.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(V.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(V.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(V.PUBLISH_START,this.handlePublishStart).addEvent(V.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(V.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(V.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(V.PLAY_TRACK_START,this.handlePlayStart).addEvent(V.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(V.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(V.SWITCH_ROOM_START,this.handleSwitchRoomStart).addEvent(V.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess).addEvent(V.SWITCH_ROOM_FAILED,this.handleSwitchRoomFailed).addEvent(V.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(V.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(V.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(V.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(V.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)=>x.off(e,t)),this._eventMap.clear()}destroy(){this.uninstallEvents(),mt.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()):z.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=pe()-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()):z.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:Te(Q({},yv),{msg_user_info:new qc({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 qc({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,J.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/$i*100)>0&&(this._localStreamStat.totalAudioLevel+=n/$i,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(_=>{let I=_.uint32_video_stream_type===2,R=_.uint32_video_stream_type===7,y=`${p}_${I?"main":"auxiliary"}`,N=this._remoteStreamStatMap.get(y);if(N&&(I&&(f!=null&&f.remoteVideoTrack.isSubscribed)||R&&(f!=null&&f.remoteAuxiliaryTrack))){N.totalVideoFPS+=_.uint32_video_receive_fps,N.totalVideoBitrate+=_.uint32_video_codec_bitrate,N.videoCount++,N.statsToReport.uint32_video_width===0&&(N.statsToReport.uint32_video_width=_.uint32_video_width),N.statsToReport.uint32_video_height===0&&(N.statsToReport.uint32_video_height=_.uint32_video_height);let P=I?f.remoteVideoTrack:f.remoteAuxiliaryTrack;P.stat.jitterBufferDelay&&(N.videoJitterBufferDelay=P.stat.jitterBufferDelay),P.stat.framesReceived&&(N.statsToReport.uint32_video_consume_render_rate=Math.floor(P.stat.framesDecoded/P.stat.framesReceived*ni(10,6)))}}),!un(d)){let _=`${p}_main`,I=this._remoteStreamStatMap.get(_);this._remoteStreamStatMap.has(_)&&I&&f!=null&&f.remoteAudioTrack.isSubscribed&&(I.totalAudioBitrate+=d.uint32_audio_codec_bitrate,I.audioCount++,f.remoteAudioTrack.stat.jitterBufferDelay&&(I.audioJitterBufferDelay=f.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(d.uint32_audio_level/$i*100)>0&&(I.totalAudioLevel+=d.uint32_audio_level/$i,I.audioLevelCount++),d.uint32_audio_block_time&&(I.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():z.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&ba)>=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:_,videoDelayCount:I,totalAudioDelay:R,totalVideoDelay:y}=o;t.statsToReport.uint32_avg_down_loss=Math.floor(p/f),_&&R&&(t.statsToReport.uint32_audio_network_p2p_delay=Math.floor(R/_),t.audioJitterBufferDelay&&(t.statsToReport.uint32_p2p_delay=Math.floor(t.statsToReport.uint32_audio_network_p2p_delay+t.audioJitterBufferDelay))),I&&y&&(t.statsToReport.uint32_video_network_p2p_delay=Math.floor(y/I))}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=Ld();let t={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new qc({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 Ma(t),t}report(){return b(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 b(this,null,function*(){if(t.msg_path_enter_room.uint64_start_time===0)return;let e=Number(this._room.sdkAppId),r=Io.enable?Oi(t,2001,e):yield Hm(t),o=r instanceof ArrayBuffer,s=`${Mi(e,mo.KEY_POINT)}&gzip=${+o}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(s,r));let a=[this.uploadKVStat(J),this.uploadKVStat(Is)];n||a.push(Pi({url:s,body:r,priority:"low"})),yield Promise.all(a)})}setConnectionType(t){this.connectionType=t,this._basicInfo.uint32_connection_type=t}uploadKVStat(r){return b(this,arguments,function*(t,e=this._room.sdkAppId){var l,p;let o=t.getReportData((l=this._room)==null?void 0:l.userSig,(p=this._signalInfo)==null?void 0:p.reportToken);if(o.stats_count.length===0&&o.stats_distribution.length===0)return;o.msg_sdk_basic_info=Te(Q({},o.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(o);let s=Io.enable?Oi(o,2003,e):yield Hm(o),n=s instanceof ArrayBuffer,a=`${Mi(+e,mo.KV_STAT)}&gzip=${+n}`,d=!1;navigator.sendBeacon&&(d=navigator.sendBeacon(a,s)),d||Pi({url:a,body:s})})}};Z([ys({settings:{timeout:500,retries:3}})],Gl.prototype,"upload",1);var $s=5e3,yv={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},qc=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}},ZT=Gl;var kf=class{constructor(){m(this,"_startTime");m(this,"_endTime");this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=pe())}stop(){this._endTime===0&&(this._endTime=pe())}getDuration(){return this._endTime===0?pe()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},jl=kf;var Uf=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(V.REMOTE_TRACK_SUBSCRIBED,this.handleSubscribed).set(V.REMOTE_TRACK_UNSUBSCRIBED,this.handleUnsubscribed).set(V.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)=>x.on(e,t,this))}uninstallEvents(){this._eventMap.forEach((t,e)=>x.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 jl,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()}},KT=Uf;var Vf=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||nt)&&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()}},Ff=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 Vf);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(V.LEAVE_SUCCESS,({room:t})=>{this.hitTest(t)&&this.stop()}).set(V.PLAY_TRACK_START,this.onPlayTrackStart).set(V.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(V.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(V.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(V.HEARTBEAT_REPORT,this.onHearBeatReport).set(V.REMOTE_VIDEO_PLAY_START,this.onRemoteVideoPlayStart).set(V.REMOTE_VIDEO_PLAY_FINISH,this.onRemoteVideoPlayEnd),this._eventMap.forEach((t,e)=>x.on(e,t,this))}uninstallEvents(){this._eventMap.forEach((t,e)=>x.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 jl;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=pe();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&&Ue.uploadEvent({userId:this._room.userId,log:`stat-${Ot.VIDEO_DECODE_FAILED_DURING_CALL}`})}else{let d=this._remoteVideoAbnormalTimestampMap.get(`${r}-decode`);d&&a-d>=this.ABNORMAL_TIME_UPPER_LIMIT&&(Ue.uploadEvent({userId:this._room.userId,log:`stat-${Ot.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){Ue.uploadEvent({userId:this._room.userId,log:`stat-${Ot.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&&(Ue.uploadEvent({userId:this._room.userId,log:`stat-${Ot.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=pe();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&&Ue.uploadEvent({userId:this._room.userId,log:`stat-${Ot.VIDEO_ENCODE_FAILED_DURING_CALL}`})}else{let a=this._videoAbnormalTimestampMap.get("local-encode");a&&n-a>=this.ABNORMAL_TIME_UPPER_LIMIT&&Ue.uploadEvent({userId:this._room.userId,log:`stat-${Ot.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=pe();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&&Ue.uploadEvent({userId:this._room.userId,log:`stat-${Ot.AUDIO_ENCODE_FAILED_DURING_CALL}`})}else{let n=this._audioAbnormalTimestampMap.get("local-encode");n&&s-n>=this.ABNORMAL_TIME_UPPER_LIMIT&&Ue.uploadEvent({userId:this._room.userId,log:`stat-${Ot.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>Nd){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()<Nd&&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(!Qr())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,_=d.presentationTime-r;if(_>f){_=Math.min(_,5e3);let I=`${t.userId}_${t.streamType}`,R=this._monitorFreezeData.get(I,"render");R?R.duration+=_:this._monitorFreezeData.set(I,{userId:t.userId,type:t.streamType,duration:_},"render");let y=this._renderFreezeMap.get(I);y?(y.totalDuration+=_,y.count+=1):this._renderFreezeMap.set(I,{userId:t.userId,type:t.streamType,totalDuration:_,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()}},eI=Ff;var iI=ai(mi(),1);var ql=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?J.addSuccessEvent({key:s.key}):J.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:_,offset:I}=this.calculateBoundary(d,s,t,r),{min:R,offset:y}=this.calculateBoundary(l,n,e,o);return p=2*_+r,f=2*R+o,p/f>this.originalAspect?(p=f*this.originalAspect,I=d-p/2):(f=p/this.originalAspect,y=l-f/2),r/s>a&&(I=0,y=0,p=s,f=n),I=Math.max(0,Math.min(I,s-p)),y=Math.max(0,Math.min(y,n-f)),{sx:I,sy:y,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=Q({},t),this.animationState.target=Q({},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)),Be(this.animationState.current.scaleOffsetX)&&Be(this.animationState.target.scaleOffsetX)&&Be(this.animationState.current.scaleOffsetY)&&Be(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,_,I,R,y,N,P,W,G;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:(I=(_=this.animationState.current)==null?void 0:_.scaleOffsetY)!=null?I:0,timestamp:Date.now()};this.animationState.target={sx:t/2,sy:o+n/2,cropWidth:t,cropHeight:e,scaleRatio:(y=(R=this.animationState.target)==null?void 0:R.scaleRatio)!=null?y:1,scaleOffsetX:(P=(N=this.animationState.target)==null?void 0:N.scaleOffsetX)!=null?P:0,scaleOffsetY:(G=(W=this.animationState.target)==null?void 0:W.scaleOffsetY)!=null?G: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 bv=`#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 tI=(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 vv(i){return i[0]===0&&i[1]===0&&i[2]===0&&i[3]===1}var Cv=0,Xl=class{constructor(t){m(this,"id",Cv++);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,he.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,xp((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),zi());be(e,Le(()=>{this.track.stat.framesDecoded++},r=>{if(this.track.log.error(`${this.id} play failed: ${r} retryCount: ${t}`),J.addFailedEvent({key:tI(this.type,this.renderer),error:r}),t>4)this.failedReason=r,this.stateChangeOB.next("FAILED"),J.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`),J.addSuccessEvent({key:tI(this.type,this.renderer)}),J.addSuccessEvent({key:514704})})),be(e,Kr(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"&&!Nh()&&(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(!vv(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=pe();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=>b(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 Ct({frameRate:15,logger:t.log,name:t.userId}),this.videoContext.create(),this.videoContext.on(Ct.UNAVAILABLE,l=>{t.log.error(l),e.error(7)});let d=new Jl(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 xt({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 rI=Promise.resolve(),zc=class extends iI.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",rI);m(this,"_updateFlag",!1);this.log=B.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 xt({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 xt({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this._2dVideoContext}getGlVideoContext(){if(!this._glVideoContext)this._glVideoContext=new Ct({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(Qm<=22),this._glVideoContext.on(Ct.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=mt.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(),mt.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(vr||this._isMixScreen||this._isTransform||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}sendCreateResult(e="videoCtxGl",r){let o=e==="videoCtxGl"?512700:512701;r?J.addFailedEvent({key:o,error:r}):J.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 Ct({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 dl(this.smallVideoContext,e,this.log),this.smallVideoContext.on(Ct.UNAVAILABLE,o=>{this.log.warn("small video context lost",o)})}if(this.smallVideoContext.frameRate=e.frameRate,this.smallDestination.resolution=e,r)this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=r:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(r),this.smallImageSource.resize(r.width,r.height),this.smallImageSource.connect(this.smallDestination));else if(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource)this.smallTrackSource.replaceTrack(this.initialTrack);else{this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack,"smallTrackSource");let{width:o,height:s}=this.cameraTrack.settings;this.smallTrackSource.resize(o,s),this.smallTrackSource.connect(this.smallDestination)}}else this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource)}_setMainOutput(e){var r;try{let o=this.cameraTrack,{small:s,player:n}=o;vr&&n.setCanvas(e);let a=e&&((r=this.destination)==null?void 0:r.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),a=this.arTrack),this.log.info(`set main output ${a?a.label:"no output track"}`),this.setSmallVideo(s,e),o.setOutputMediaStreamTrack(a)}catch(o){this.log.error("set main output failed",o)}}update(e=!1){return b(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)})),Pt===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 cl(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 zl(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 Hn(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 Ei)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 Ls)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 Ei?((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 Ls&&(delete this.mixTrack,this.update())}setMixTrack(e){this.mixTrack=e}setCameraTrack(e){return this.cameraTrack=e,this.update(!0)}setScreenTrack(e){return b(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 b(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:z.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 _=f&&e||l,I=f&&r||p,R=f?0:a,y=f?0:d;s.drawImage(n,R,y,_,I)}),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 b(this,null,function*(){this._beautyParams=e,this.update()})}stopBeauty(){return b(this,null,function*(){this._beautyParams=void 0,this.update()})}setWatermark(e){return b(this,null,function*(){let r;try{r=yield hn((e==null?void 0:e.imageElement)||e.imageUrl)}catch(_){throw new ce({code:z.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(_=>_.type===d)?(this.watermarkImageList=this.watermarkImageList.filter(_=>_.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,(_,I)=>_==="imageUrl"?void 0:I))})}deleteWatermark(e="watermark"){return b(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 b(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 b(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:z.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 b(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 Xl(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([r_(function(e){this.log.error("update failed",e)}),Pe(e=>function(...r){return b(this,null,function*(){this._updateFlag||(this._updateFlag=!0,yield rI,this.updated=new Promise((o,s)=>{e.apply(this,r).then(o,s),setTimeout(s,5e3,new ce({code:z.API_CALL_TIMEOUT,message:"update timeout"}))}),this._updateFlag=!1,yield this.updated)})})],zc.prototype,"update",1);var Nv=0;var Ql=class extends he{constructor(e){super("room");m(this,"seq",++Nv);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=B.createLogger({parent:e.logger,id:`r${this.seq}`}),this.useStringRoomId=!!e.useStringRoomId,Ze(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),Ze(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),Ze(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new ZT({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new KT({room:this}),this.badCaseDetector=new eI({room:this}),this.audioManager=new ml(this),this.videoManager=new zc(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 b(this,null,function*(){return this.publish(e)})}removeTrack(e){return b(this,null,function*(){return this.unpublish(e)})}replaceTrack(e){return b(this,null,function*(){})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(Oe(e))/^wss?:\/\//i.test(e)?this.proxy_ws=e:/^https?:\/\//i.test(e)&&(this.proxy_wt=e);else if(Jt(e)){let{websocketProxy:r,webtransportProxy:o,loggerProxy:s,scheduleProxy:n,unifiedProxy:a}=e;this.proxy_ws=r,this.proxy_wt=o,this.proxy_unified=a,a?(Cl([a,a]),is(`https://${a}`)):(s&&is(s),n&&Cl(n))}x.once(V.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:ei.main,sched_back_domain:ei.backup,signal_domain:this.proxy_ws||this.proxy_wt||""}))}getRemoteAudioStats(){return b(this,null,function*(){let e={};return this.remotePublishedUserMap.forEach(r=>{e[r.userId]=r.remoteAudioTrack.stat}),e})}getTransportStats(){return b(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 b(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:z.INVALID_OPERATION,message:je({key:Ge.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(sr.INVALID_DESTROY),new ce({code:z.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,x.emit(V.ROOM_DESTROY,{room:this})}schedule(e,r){return b(this,null,function*(){var s,n,a,d;let o=pe();try{let{isCached:l,result:p,detailCost:f}=yield Ef({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} ${br(p,{keysToExclude:["username","credential"]})}`),l&&x.once(V.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=Q(Q({},this.scheduleResult),p),Be((s=p.config)==null?void 0:s.retryCount)&&Rm(p.config.retryCount),Oe((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,x.emit(V.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:f}),J.addSuccessEvent({key:521700,cost:pe()-o})}catch(l){throw J.addFailedEvent({key:521700,error:l}),l}})}sendAbilityStatus(e){}enableInsertableStreams(){return Promise.resolve()}switchRoom(e){return Promise.reject()}isSwitchRoomSupported(){return!1}};function oI(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 Bf=class extends Ie{constructor(t,e){super(t);let r=new Ie(t);r.next=qe,e(r)}},r8=Se(Bf,"takeUntilComplete");var Ht={useWt:!0,useAINS:!0,useHardDecoder:"prefer-software",useHardEncoder:"prefer-software",unreliable:!1,debug:!1,assetsPath:"",enableUpload:!0},sI="__INLINE__WORKER__",nI="__INLINE__WASM__",{debug:aI}=console;Ht.debug||(console.debug=()=>{});var Dv=!sI.startsWith("__"),wv=!nI.startsWith("__");function Yl(){let i=us(`${Ht.assetsPath?`${Ht.assetsPath}/`:""}worker.js`);return Dv?URL.createObjectURL(new Blob([atob(sI)],{type:"application/javascript"})):i.startsWith("http")?fetch(i).then(t=>t.blob().then(e=>URL.createObjectURL(e))):i}var Jc;function Zl(){return b(this,null,function*(){let i=Ht.assetsPath?`${Ht.assetsPath}/`:"";return Jc||(wv?Jc=new TextEncoder().encode(atob(nI)).buffer:Jc=yield fetch(us(`${i}av_processing.wasm`)).then(t=>t.arrayBuffer()),Jc)})}var $f=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 b(this,null,function*(){let t=ze("player"),e=Yl();try{yield t.audioWorklet.addModule(typeof e=="string"?e:yield e),B.info("global audio player worklet addModule success",e)}catch(r){throw B.error("global audio player worklet addModule failed:",r),r}return this.worklet=new AudioWorkletNode(t,"global-audio-player",{processorOptions:{wasm:yield Zl(),flag:Ht},numberOfInputs:2}),B.info("global audio player worklet created",t.state),this.playPort=this.worklet.port,this.playPort})}playAudio(t){return b(this,null,function*(){var r;yield this.init();let e=new MessageChannel;(r=this.playPort)==null||r.postMessage(null,[e.port1]),t(e.port2)})}},Xc=new $f;var Hf=(()=>{if(typeof self=="undefined")return!1;if(!("top"in self&&self!==top)){if("showOpenFilePicker"in self)return"showOpenFilePicker"}return!1})(),u8=Hf?Promise.resolve().then(function(){return Lv}):Promise.resolve().then(function(){return Bv});var l8=Hf?Promise.resolve().then(function(){return kv}):Promise.resolve().then(function(){return Hv});var Mv=Hf?Promise.resolve().then(function(){return Vv}):Promise.resolve().then(function(){return Gv});function Wf(...i){return b(this,null,function*(){return(yield Mv).default(...i)})}var Ov=i=>b(null,null,function*(){let t=yield i.getFile();return t.handle=i,t}),Pv=(...t)=>b(null,[...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(Ov));return i[0].multiple?o:o[0]}),Lv={__proto__:null,default:Pv};function Kl(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 Kl=function(e){this.s=e,this.n=e.next},Kl.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 Kl(i)}var cI=(o,s,...n)=>b(null,[o,s,...n],function*(i,t,e=i.name,r){let a=[],d=[];var l,p=!1,f=!1;try{for(var _,I=(function(R){var y,N,P,W=2;for(typeof Symbol!="undefined"&&(N=Symbol.asyncIterator,P=Symbol.iterator);W--;){if(N&&(y=R[N])!=null)return y.call(R);if(P&&(y=R[P])!=null)return new Kl(y.call(R));N="@@asyncIterator",P="@@iterator"}throw new TypeError("Object is not async iterable")})(i.values());p=!(_=yield I.next()).done;p=!1){let R=_.value,y=`${e}/${R.name}`;R.kind==="file"?d.push(R.getFile().then(N=>(N.directoryHandle=i,N.handle=R,Object.defineProperty(N,"webkitRelativePath",{configurable:!0,enumerable:!0,get:()=>y})))):R.kind!=="directory"||!t||r&&r(R)||a.push(cI(R,t,y,r))}}catch(R){f=!0,l=R}finally{try{p&&I.return!=null&&(yield I.return())}finally{if(f)throw l}}return[...(yield Promise.all(a)).flat(),...yield Promise.all(d)]}),xv=(...t)=>b(null,[...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 cI(e,i.recursive,void 0,i.skipDirectory)}),kv={__proto__:null,default:xv},Uv=(s,...n)=>b(null,[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,_)=>{a[_]={description:f.description||"Files",accept:{}},f.mimeTypes?(_===0&&d&&f.mimeTypes.push(d),f.mimeTypes.map(I=>{a[_].accept[I]=f.extensions||[]})):d?a[_].accept[d]=f.extensions||[]:a[_].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)}),Vv={__proto__:null,default:Uv},Fv=(...t)=>b(null,[...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()})}),Bv={__proto__:null,default:Fv},$v=(...t)=>b(null,[...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()})}),Hv={__proto__:null,default:$v},Wv=(e,...r)=>b(null,[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 b(this,null,function*(){let p=d.getReader(),f=new ReadableStream({start:R=>(function y(){return b(this,null,function*(){return p.read().then(({done:N,value:P})=>{if(!N)return R.enqueue(P),y();R.close()})})})()}),_=new Response(f),I=yield _.blob();return p.releaseLock(),new Blob([I],{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}),Gv={__proto__:null,default:Wv};var Gf=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 b(this,null,function*(){if(this.ready)return this.ready;t||(t=this.name),console.time(`createWorker_${t}`);let e=Yl(),r=new Worker(typeof e=="string"?e:yield e,{name:t});return this.worker=r,this.ready=new Promise((o,s)=>b(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(xd(),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 Zl(),flag:Ht},this.ports)}))})}destroy(){var t;console.log("destroy worker",this.name),delete this.ready,(t=this.worker)==null||t.terminate()}},jf=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()}},qf=class i extends Gf{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 b(this,null,function*(){return this.ready?this.ready:(this.extendChannel=new MessageChannel,this.ports=[this.extendChannel.port2],yield Dt(i.prototype,this,"create").call(this),this.switchValue.forEach((e,r)=>{this.extendChannel.port1.postMessage([r,e])}),this)})}},Ho=new qf,Hs,uI=-1;function dI(i){return console.log(i),Hs.push(i.slice()),Hs.length>1e3&&Hs.shift(),i}function lI(i){return b(this,null,function*(){switch(uI){case 0:this.edpl.willDecodeAudio=dI;break;case 2:this.edpl.didEncodeAudio=dI;break}yield Ho.create(),x.emit(V.JOIN_SEND_CMD,{room:this});let t=new jf(Ho,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(x.emit(V.JOIN_RECEIVED_CMD_RES,{room:this,code:e}),e===0)return Object.assign(this,r,{session:t});throw new ce({code:z.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:zf,writable:!0,configurable:!0},useWt:{set:jv,writable:!0,configurable:!0},enableDebug:{set(i){console.debug=i?aI:()=>{},Ho.setSwitchValue("enableDebug",i)},writable:!0,configurable:!0},useV2:{set:Jf,writable:!0,configurable:!0},dump:{value(i=0){if(uI=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)}),Wf(new Blob(t),{fileName:"audio dump hex",extensions:[".hex"]})},writable:!0,configurable:!0},dumpAudio:{value(i="audio",t=2e3){let e=[],r=new Promise(o=>{let s=new MessageChannel;Ho.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,Ho.extendChannel.port1.postMessage(["dump",i]),s.port2.close(),o(new Blob(e)))}});return Wf(r,{fileName:i,extensions:[".pcm"]})},writable:!0,configurable:!0},hardDec:{set(i){switch(i){case!0:Ht.useHardDecoder="prefer-hardware";break;case!1:Ht.useHardDecoder="prefer-software";break;default:Ht.useHardDecoder="no-preference"}},writable:!0,configurable:!0}});function zf(i){return b(this,null,function*(){Ho.setSwitchValue("useAINS",i)})}function Jf(i){return b(this,null,function*(){Ho.setSwitchValue("useV2",i)})}function jv(i){return b(this,null,function*(){Ho.setSwitchValue("useWt",i)})}function mI(i){let t=new MediaStreamTrackGenerator({kind:"audio"});i.setInputMediaStreamTrack(t),this.postMessage({cmd:"pullAudio",payload:{tinyId:i.tinyId,writable:t.writable}},[t.writable])}function hI(i){return b(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(oI(r.port2),Je(ye(i,he.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 em=[];function fI(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<=em.length;l++)if(!em[l]){em[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:Q({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(Te(Q({},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(Xc.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(),em[this.index]=null,o&&o.port1.postMessage(null),r.port1.postMessage(null)})),be(t,ws(l=>i.volume=l),Ji(al(1e3)),Le(()=>{i.volume=0})),a(i.outMediaTrack)}var j8=new Intl.DateTimeFormat("zh-CN",{dateStyle:"short",timeStyle:"medium"});var Xf=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 b(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 b(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)),Ut===126?this.tsMap.set(s,pe()):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 b(this,null,function*(){let r=0,o=new VideoEncoder({output:s=>{let n=Ut===126?this.tsMap.get(r):(this.startTime+(s.timestamp-this.startTimestamp)/1e3&4294967295)>>>0;if(Ut===126&&this.tsMap.delete(r),r<10&&(r===0&&e.recreateCount===0&&x.emit(V.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 b(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 tm(i,t){return b(this,null,function*(){let e=i.mediaType===2,r=e?"screen":"video",o={codec:"avc1.420028",latencyMode:"realtime",avc:{format:"annexb"},hardwareAcceleration:Ht.useHardEncoder,width:t.profile.width,height:t.profile.height,framerate:t.profile.frameRate,bitrate:t.profile.bitrate*1e3},s=new MessageChannel;this.postMessage({cmd:"pushVideo",payload:t},[s.port1]);let n=new Xf(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;Na({configureBr:[a.data.bitrate,d]}),n.session&&n.configure({bitrate:d},n.session)}},this._log.info("start push",r,t),n})}function gI(i){return b(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 tm.call(this,i,r);this._log.info("VideoEncoder created",r);let d,l=f=>b(this,null,function*(){if(d==null||d.abort("track changed"),!f)return;d=new AbortController;let{width:_,height:I,displaySurface:R}=f.getSettings();_&&(a.config.width=_),I&&(a.config.height=I);let y=or.match(/Chrome\/(\d+)/);(y==null?void 0:y[1])==="114"&&R==="browser"&&delete a.config.hardwareAcceleration,this._log.info("push",e,"track:",f.readyState,f.getSettings());let N;if(typeof MediaStreamTrackProcessor!="undefined"&&!(f instanceof CanvasCaptureMediaStreamTrack))N=new MediaStreamTrackProcessor({track:f}).readable;else{let W;N=new ReadableStream({start(G){i.on("render",ae=>{if(!(i.player.mode===0&&!document.hidden))try{G.enqueue(new VideoFrame(ae,{timestamp:performance.now()*1e3}))}catch(ke){console.warn(ke)}})},pull(G){return b(this,null,function*(){if(i.player.mode===0&&Qr()&&i.player.element)return new Promise(ae=>{i.player.element.requestVideoFrameCallback((ke,Me)=>{try{let Y=new VideoFrame(i.player.element);G.enqueue(Y)}catch(Y){console.warn(Y)}ae()})})})}})}let P="small"in i&&i.small;return P?(this.smallEncoder||(this.smallEncoder=yield tm.call(this,i,{profile:P,type:3,trackType:o})),this.smallEncoder.track=f,this.smallEncoder.label="small",N=yield this.smallEncoder.trans(N,d,this)):this.smallEncoder&&(this.smallEncoder.close(),delete this.smallEncoder),a.track=f,a.label=e,a.start(N,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 Wo=class Wo extends he{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(Wo.INTERVALCHANGED,this.interval)}),be(ye(this,Wo.INTERVALCHANGED),fi(s=>this.room.state==="joined"?this.room.fromWorker("getAudioEnergy",s):be(g_(s),Mo(()=>[]))),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==he.ON&&this.room.emit("audio-volume",s)}))}start(e,r){this.interval=e,this.enableInBackground=r,this.emit(Wo.INTERVALCHANGED,this.interval)}stop(){}};m(Wo,"INTERVALCHANGED","intervalChanged"),Z([ot([he.INIT,he.OFF],he.ON)],Wo.prototype,"start",1),Z([ot([],he.OFF)],Wo.prototype,"stop",1);var rm=Wo;var Go=class Go extends Ql{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 rm(this));m(this,"enableAIVoice",zf);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:rh(),uint32_device_type:0,str_os_verion:ih(),uint32_link_type:1,str_client_version:ft,uint32_net_type:os[ui.getNetworkType()],ua:navigator.userAgent,version:""}});m(this,"joinAbortController",new AbortController);m(this,"smallAbortCtrl");m(this,"smallEncoder");e.tinyId&&(this.tinyId=e.tinyId,Jf(!0)),this._log||(this._log=e.logger),this.bussinessInfo=e.bussinessInfo,e.encodedDataProcessingListener&&this.setEncodedDataProcessingListener(e.encodedDataProcessingListener)}replaceTrack(e){return b(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 b(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 b(this,null,function*(){var d;let s=ui.getEnv(),n=vu(),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:vu(),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 lI.call(this,a),console.log(this),Xc.playAudio(l=>this.postMessage({cmd:"setAudioWorkletPort"},[l])),this.checkDestroy()})}leave(){return b(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 b(this,null,function*(){let e=Je(ye(this,"left")),r=this.audioManager.decodePipeline.some(o=>o);be(o=>b(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(Te(Q({},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 V.RECEIVED_PUBLISHED_USER_LIST:x.emit(e,Q({room:this},r));return;case"1":if(r.userId===this.userId)return;this.emit("peer-join",r);return;case"2":this.emit("peer-leave",r);return;case"3":let o=new Wl(this,r);this.remotePublishedUserMap.set(r.userId,o),this.emit("remote-published",o);return;case"5":{let f=r,_=this.remotePublishedUserMap.get(f);_&&(_.remoteVideoTrack.close(),_.remoteAuxiliaryTrack.close(),_.remoteAudioTrack.close(),this.remotePublishedUserMap.delete(f),this.emit("remote-unpublished",_))}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:_,flag:I}=r,R=this.remotePublishedUserMap.get(_.userId);if(!R){this.emit("remote-publish-state-changed",r);return}R.flag=I}x.emit(V.REMOTE_PUBLISH_STATE_CHANGED,Q({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=Q({},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:T_(this.userId),str_acc_ip:this.relayip,str_client_ip:this.clientip,msg_up_stream_info:a,msg_down_stream_info:l};x.emit(V.HEARTBEAT_REPORT,{room:this,report:p}),this.emit("heartbeat-report",p),x.emit(V.NETWORK_QUALITY,{room:this,uplink:{rtt:n,loss:s},downlinks:d}),delete r.downlinkInfo;break;case"signal-connection-state-changed":x.emit(V.SIGNAL_CONNECTION_STATE_CHANGED,Q({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 b(this,null,function*(){switch(yield this.sendMessage("publish",e.mediaType).then(r=>r.err!==0?Promise.reject(r.err):r),Vt(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 Xc.init(),fI.call(this,e);break;default:yield gI.call(this,e)}e.muted&&this.postMessage("mute",{mediaType:e.mediaType,srctinyid:this.tinyid,userId:this.openid,remove:!0})})}unpublish(e){return b(this,null,function*(){yt(e)})}subscribe(...e){return b(this,null,function*(){let r=e.reduce((f,_)=>_.mediaType|f,0),{userId:o,tinyId:s,streamType:n}=e[0],a=this.remotePublishedUserMap.get(o),d=Q({},a.subscribeState),l=Object.assign(new za,d);l.mediaType|=r,x.emit(V.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 mI.call(this,f);default:return hI.call(this,f)}})),x.emit(V.SUBSCRIBE_SUCCESS,{room:this,streamType:n,remotePublishedUser:a})})}unsubscribe(...e){return b(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();x.emit(V.UNSUBSCRIBE_SUCCESS,{room:this,streamType:s,remotePublishedUser:this.remotePublishedUserMap.get(o)})}})}enableSmall(e){return b(this,null,function*(){var r;if(e){if(this.videoManager.smallTrack){let o=this.videoManager.cameraTrack;this.smallEncoder=yield tm.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([Do(Go.prototype.afterJoin),ot(["left",he.INIT],"joined"),zT()],Go.prototype,"join",1),Z([ot("joined","left",{ignoreError:!0}),JT()],Go.prototype,"leave",1),Z([Gu(e=>e.mediaType),XT()],Go.prototype,"publish",1),Z([Gu(e=>e.mediaType),QT()],Go.prototype,"unpublish",1),Z([Gu((...e)=>e[0].userId),YT()],Go.prototype,"subscribe",1);var im=Go;Kn.frameWorkType=37;Kn.create=function(i){let t=Kn._create.call(this,im,i);return t._use(hf,i==null?void 0:i.assetsPath),i!=null&&i.assetsPath&&(Ht.assetsPath=i==null?void 0:i.assetsPath),console.log("trtc wasm sdk:",ft,"created",Ht),t};Object.assign(Kn.prototype,{_setCurrentSpeaker(i){let t=ze("player");return t!=null&&t.setSinkId?t.setSinkId(i):Promise.reject("not support")},_enableVideoDecodeFallback(i,t){return b(this,null,function*(){return this.startPlugin(hf.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"),er(o=>o.state==="STARTED"),Kr(1),Fp(1e4),Je(ye(i,he.INIT)),Le(e,r))})})}});Lh(37);var Tj=Kn;export{Tj 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 tI=(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 vv(i){return i[0]===0&&i[1]===0&&i[2]===0&&i[3]===1}var Cv=0,Xl=class{constructor(t){m(this,"id",Cv++);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,he.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,xp((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),zi());be(e,Le(()=>{this.track.stat.framesDecoded++},r=>{if(this.track.log.error(`${this.id} play failed: ${r} retryCount: ${t}`),J.addFailedEvent({key:tI(this.type,this.renderer),error:r}),t>4)this.failedReason=r,this.stateChangeOB.next("FAILED"),J.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`),J.addSuccessEvent({key:tI(this.type,this.renderer)}),J.addSuccessEvent({key:514704})})),be(e,Kr(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"&&!Nh()&&(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(!vv(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=pe();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=>b(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 Ct({frameRate:15,logger:t.log,name:t.userId}),this.videoContext.create(),this.videoContext.on(Ct.UNAVAILABLE,l=>{t.log.error(l),e.error(7)});let d=new Jl(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 xt({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 rI=Promise.resolve(),zc=class extends iI.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",rI);m(this,"_updateFlag",!1);this.log=B.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 xt({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 xt({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this._2dVideoContext}getGlVideoContext(){if(!this._glVideoContext)this._glVideoContext=new Ct({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(Qm<=22),this._glVideoContext.on(Ct.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=mt.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(),mt.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(vr||this._isMixScreen||this._isTransform||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}sendCreateResult(e="videoCtxGl",r){let o=e==="videoCtxGl"?512700:512701;r?J.addFailedEvent({key:o,error:r}):J.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 Ct({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 dl(this.smallVideoContext,e,this.log),this.smallVideoContext.on(Ct.UNAVAILABLE,o=>{this.log.warn("small video context lost",o)})}if(this.smallVideoContext.frameRate=e.frameRate,this.smallDestination.resolution=e,r)this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=r:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(r),this.smallImageSource.resize(r.width,r.height),this.smallImageSource.connect(this.smallDestination));else if(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource)this.smallTrackSource.replaceTrack(this.initialTrack);else{this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack,"smallTrackSource");let{width:o,height:s}=this.cameraTrack.settings;this.smallTrackSource.resize(o,s),this.smallTrackSource.connect(this.smallDestination)}}else this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource)}_setMainOutput(e){var r;try{let o=this.cameraTrack,{small:s,player:n}=o;vr&&n.setCanvas(e);let a=e&&((r=this.destination)==null?void 0:r.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),a=this.arTrack),this.log.info(`set main output ${a?a.label:"no output track"}`),this.setSmallVideo(s,e),o.setOutputMediaStreamTrack(a)}catch(o){this.log.error("set main output failed",o)}}update(e=!1){return b(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)})),Pt===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 cl(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 zl(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 Hn(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 Ei)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 Ls)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 Ei?((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 Ls&&(delete this.mixTrack,this.update())}setMixTrack(e){this.mixTrack=e}setCameraTrack(e){return this.cameraTrack=e,this.update(!0)}setScreenTrack(e){return b(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 b(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:z.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 _=f&&e||l,I=f&&r||p,R=f?0:a,y=f?0:d;s.drawImage(n,R,y,_,I)}),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 b(this,null,function*(){this._beautyParams=e,this.update()})}stopBeauty(){return b(this,null,function*(){this._beautyParams=void 0,this.update()})}setWatermark(e){return b(this,null,function*(){let r;try{r=yield hn((e==null?void 0:e.imageElement)||e.imageUrl)}catch(_){throw new ce({code:z.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(_=>_.type===d)?(this.watermarkImageList=this.watermarkImageList.filter(_=>_.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,(_,I)=>_==="imageUrl"?void 0:I))})}deleteWatermark(e="watermark"){return b(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 b(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 b(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:z.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 b(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 Xl(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([r_(function(e){this.log.error("update failed",e)}),Pe(e=>function(...r){return b(this,null,function*(){this._updateFlag||(this._updateFlag=!0,yield rI,this.updated=new Promise((o,s)=>{e.apply(this,r).then(o,s),setTimeout(s,5e3,new ce({code:z.API_CALL_TIMEOUT,message:"update timeout"}))}),this._updateFlag=!1,yield this.updated)})})],zc.prototype,"update",1);var Nv=0;var Ql=class extends he{constructor(e){super("room");m(this,"seq",++Nv);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=B.createLogger({parent:e.logger,id:`r${this.seq}`}),this.useStringRoomId=!!e.useStringRoomId,Ze(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),Ze(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),Ze(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new ZT({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new KT({room:this}),this.badCaseDetector=new eI({room:this}),this.audioManager=new ml(this),this.videoManager=new zc(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 b(this,null,function*(){return this.publish(e)})}removeTrack(e){return b(this,null,function*(){return this.unpublish(e)})}replaceTrack(e){return b(this,null,function*(){})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(Oe(e))/^wss?:\/\//i.test(e)?this.proxy_ws=e:/^https?:\/\//i.test(e)&&(this.proxy_wt=e);else if(Jt(e)){let{websocketProxy:r,webtransportProxy:o,loggerProxy:s,scheduleProxy:n,unifiedProxy:a}=e;this.proxy_ws=r,this.proxy_wt=o,this.proxy_unified=a,a?(Cl([a,a]),is(`https://${a}`)):(s&&is(s),n&&Cl(n))}x.once(V.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:ei.main,sched_back_domain:ei.backup,signal_domain:this.proxy_ws||this.proxy_wt||""}))}getRemoteAudioStats(){return b(this,null,function*(){let e={};return this.remotePublishedUserMap.forEach(r=>{e[r.userId]=r.remoteAudioTrack.stat}),e})}getTransportStats(){return b(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 b(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:z.INVALID_OPERATION,message:je({key:Ge.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(sr.INVALID_DESTROY),new ce({code:z.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,x.emit(V.ROOM_DESTROY,{room:this})}schedule(e,r){return b(this,null,function*(){var s,n,a,d;let o=pe();try{let{isCached:l,result:p,detailCost:f}=yield Ef({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} ${br(p,{keysToExclude:["username","credential"]})}`),l&&x.once(V.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=Q(Q({},this.scheduleResult),p),Be((s=p.config)==null?void 0:s.retryCount)&&Rm(p.config.retryCount),Oe((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,x.emit(V.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:f}),J.addSuccessEvent({key:521700,cost:pe()-o})}catch(l){throw J.addFailedEvent({key:521700,error:l}),l}})}sendAbilityStatus(e){}enableInsertableStreams(){return Promise.resolve()}switchRoom(e){return Promise.reject()}isSwitchRoomSupported(){return!1}};function oI(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 Bf=class extends Ie{constructor(t,e){super(t);let r=new Ie(t);r.next=qe,e(r)}},r8=Se(Bf,"takeUntilComplete");var Ht={useWt:!0,useAINS:!0,useHardDecoder:"prefer-software",useHardEncoder:"prefer-software",unreliable:!1,debug:!1,assetsPath:"",enableUpload:!0},sI="__INLINE__WORKER__",nI="__INLINE__WASM__",{debug:aI}=console;Ht.debug||(console.debug=()=>{});var Dv=!sI.startsWith("__"),wv=!nI.startsWith("__");function Yl(){let i=us(`${Ht.assetsPath?`${Ht.assetsPath}/`:""}worker.js`);return Dv?URL.createObjectURL(new Blob([atob(sI)],{type:"application/javascript"})):i.startsWith("http")?fetch(i).then(t=>t.blob().then(e=>URL.createObjectURL(e))):i}var Jc;function Zl(){return b(this,null,function*(){let i=Ht.assetsPath?`${Ht.assetsPath}/`:"";return Jc||(wv?Jc=new TextEncoder().encode(atob(nI)).buffer:Jc=yield fetch(us(`${i}av_processing.wasm`)).then(t=>t.arrayBuffer()),Jc)})}var $f=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 b(this,null,function*(){let t=ze("player"),e=Yl();try{yield t.audioWorklet.addModule(typeof e=="string"?e:yield e),B.info("global audio player worklet addModule success",e)}catch(r){throw B.error("global audio player worklet addModule failed:",r),r}return this.worklet=new AudioWorkletNode(t,"global-audio-player",{processorOptions:{wasm:yield Zl(),flag:Ht},numberOfInputs:2}),B.info("global audio player worklet created",t.state),this.playPort=this.worklet.port,this.playPort})}playAudio(t){return b(this,null,function*(){var r;yield this.init();let e=new MessageChannel;(r=this.playPort)==null||r.postMessage(null,[e.port1]),t(e.port2)})}},Xc=new $f;var Hf=(()=>{if(typeof self=="undefined")return!1;if(!("top"in self&&self!==top)){if("showOpenFilePicker"in self)return"showOpenFilePicker"}return!1})(),u8=Hf?Promise.resolve().then(function(){return Lv}):Promise.resolve().then(function(){return Bv});var l8=Hf?Promise.resolve().then(function(){return kv}):Promise.resolve().then(function(){return Hv});var Mv=Hf?Promise.resolve().then(function(){return Vv}):Promise.resolve().then(function(){return Gv});function Wf(...i){return b(this,null,function*(){return(yield Mv).default(...i)})}var Ov=i=>b(null,null,function*(){let t=yield i.getFile();return t.handle=i,t}),Pv=(...t)=>b(null,[...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(Ov));return i[0].multiple?o:o[0]}),Lv={__proto__:null,default:Pv};function Kl(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 Kl=function(e){this.s=e,this.n=e.next},Kl.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 Kl(i)}var cI=(o,s,...n)=>b(null,[o,s,...n],function*(i,t,e=i.name,r){let a=[],d=[];var l,p=!1,f=!1;try{for(var _,I=(function(R){var y,N,P,W=2;for(typeof Symbol!="undefined"&&(N=Symbol.asyncIterator,P=Symbol.iterator);W--;){if(N&&(y=R[N])!=null)return y.call(R);if(P&&(y=R[P])!=null)return new Kl(y.call(R));N="@@asyncIterator",P="@@iterator"}throw new TypeError("Object is not async iterable")})(i.values());p=!(_=yield I.next()).done;p=!1){let R=_.value,y=`${e}/${R.name}`;R.kind==="file"?d.push(R.getFile().then(N=>(N.directoryHandle=i,N.handle=R,Object.defineProperty(N,"webkitRelativePath",{configurable:!0,enumerable:!0,get:()=>y})))):R.kind!=="directory"||!t||r&&r(R)||a.push(cI(R,t,y,r))}}catch(R){f=!0,l=R}finally{try{p&&I.return!=null&&(yield I.return())}finally{if(f)throw l}}return[...(yield Promise.all(a)).flat(),...yield Promise.all(d)]}),xv=(...t)=>b(null,[...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 cI(e,i.recursive,void 0,i.skipDirectory)}),kv={__proto__:null,default:xv},Uv=(s,...n)=>b(null,[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,_)=>{a[_]={description:f.description||"Files",accept:{}},f.mimeTypes?(_===0&&d&&f.mimeTypes.push(d),f.mimeTypes.map(I=>{a[_].accept[I]=f.extensions||[]})):d?a[_].accept[d]=f.extensions||[]:a[_].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)}),Vv={__proto__:null,default:Uv},Fv=(...t)=>b(null,[...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()})}),Bv={__proto__:null,default:Fv},$v=(...t)=>b(null,[...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()})}),Hv={__proto__:null,default:$v},Wv=(e,...r)=>b(null,[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 b(this,null,function*(){let p=d.getReader(),f=new ReadableStream({start:R=>(function y(){return b(this,null,function*(){return p.read().then(({done:N,value:P})=>{if(!N)return R.enqueue(P),y();R.close()})})})()}),_=new Response(f),I=yield _.blob();return p.releaseLock(),new Blob([I],{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}),Gv={__proto__:null,default:Wv};var Gf=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 b(this,null,function*(){if(this.ready)return this.ready;t||(t=this.name),console.time(`createWorker_${t}`);let e=Yl(),r=new Worker(typeof e=="string"?e:yield e,{name:t});return this.worker=r,this.ready=new Promise((o,s)=>b(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(xd(),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 Zl(),flag:Ht},this.ports)}))})}destroy(){var t;console.log("destroy worker",this.name),delete this.ready,(t=this.worker)==null||t.terminate()}},jf=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()}},qf=class i extends Gf{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 b(this,null,function*(){return this.ready?this.ready:(this.extendChannel=new MessageChannel,this.ports=[this.extendChannel.port2],yield Dt(i.prototype,this,"create").call(this),this.switchValue.forEach((e,r)=>{this.extendChannel.port1.postMessage([r,e])}),this)})}},Ho=new qf,Hs,uI=-1;function dI(i){return console.log(i),Hs.push(i.slice()),Hs.length>1e3&&Hs.shift(),i}function lI(i){return b(this,null,function*(){switch(uI){case 0:this.edpl.willDecodeAudio=dI;break;case 2:this.edpl.didEncodeAudio=dI;break}yield Ho.create(),x.emit(V.JOIN_SEND_CMD,{room:this});let t=new jf(Ho,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(x.emit(V.JOIN_RECEIVED_CMD_RES,{room:this,code:e}),e===0)return Object.assign(this,r,{session:t});throw new ce({code:z.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:zf,configurable:!0},useWt:{set:jv,configurable:!0},enableDebug:{set(i){console.debug=i?aI:()=>{},Ho.setSwitchValue("enableDebug",i)},configurable:!0},useV2:{set:Jf,configurable:!0},dump:{value(i=0){if(uI=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)}),Wf(new Blob(t),{fileName:"audio dump hex",extensions:[".hex"]})},writable:!0,configurable:!0},dumpAudio:{value(i="audio",t=2e3){let e=[],r=new Promise(o=>{let s=new MessageChannel;Ho.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,Ho.extendChannel.port1.postMessage(["dump",i]),s.port2.close(),o(new Blob(e)))}});return Wf(r,{fileName:i,extensions:[".pcm"]})},writable:!0,configurable:!0},hardDec:{set(i){switch(i){case!0:Ht.useHardDecoder="prefer-hardware";break;case!1:Ht.useHardDecoder="prefer-software";break;default:Ht.useHardDecoder="no-preference"}},configurable:!0}});function zf(i){return b(this,null,function*(){Ho.setSwitchValue("useAINS",i)})}function Jf(i){return b(this,null,function*(){Ho.setSwitchValue("useV2",i)})}function jv(i){return b(this,null,function*(){Ho.setSwitchValue("useWt",i)})}function mI(i){let t=new MediaStreamTrackGenerator({kind:"audio"});i.setInputMediaStreamTrack(t),this.postMessage({cmd:"pullAudio",payload:{tinyId:i.tinyId,writable:t.writable}},[t.writable])}function hI(i){return b(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(oI(r.port2),Je(ye(i,he.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 em=[];function fI(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<=em.length;l++)if(!em[l]){em[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:Q({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(Te(Q({},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(Xc.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(),em[this.index]=null,o&&o.port1.postMessage(null),r.port1.postMessage(null)})),be(t,ws(l=>i.volume=l),Ji(al(1e3)),Le(()=>{i.volume=0})),a(i.outMediaTrack)}var j8=new Intl.DateTimeFormat("zh-CN",{dateStyle:"short",timeStyle:"medium"});var Xf=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 b(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 b(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)),Ut===126?this.tsMap.set(s,pe()):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 b(this,null,function*(){let r=0,o=new VideoEncoder({output:s=>{let n=Ut===126?this.tsMap.get(r):(this.startTime+(s.timestamp-this.startTimestamp)/1e3&4294967295)>>>0;if(Ut===126&&this.tsMap.delete(r),r<10&&(r===0&&e.recreateCount===0&&x.emit(V.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 b(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 tm(i,t){return b(this,null,function*(){let e=i.mediaType===2,r=e?"screen":"video",o={codec:"avc1.420028",latencyMode:"realtime",avc:{format:"annexb"},hardwareAcceleration:Ht.useHardEncoder,width:t.profile.width,height:t.profile.height,framerate:t.profile.frameRate,bitrate:t.profile.bitrate*1e3},s=new MessageChannel;this.postMessage({cmd:"pushVideo",payload:t},[s.port1]);let n=new Xf(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;Na({configureBr:[a.data.bitrate,d]}),n.session&&n.configure({bitrate:d},n.session)}},this._log.info("start push",r,t),n})}function gI(i){return b(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 tm.call(this,i,r);this._log.info("VideoEncoder created",r);let d,l=f=>b(this,null,function*(){if(d==null||d.abort("track changed"),!f)return;d=new AbortController;let{width:_,height:I,displaySurface:R}=f.getSettings();_&&(a.config.width=_),I&&(a.config.height=I);let y=or.match(/Chrome\/(\d+)/);(y==null?void 0:y[1])==="114"&&R==="browser"&&delete a.config.hardwareAcceleration,this._log.info("push",e,"track:",f.readyState,f.getSettings());let N;if(typeof MediaStreamTrackProcessor!="undefined"&&!(f instanceof CanvasCaptureMediaStreamTrack))N=new MediaStreamTrackProcessor({track:f}).readable;else{let W;N=new ReadableStream({start(G){i.on("render",ae=>{if(!(i.player.mode===0&&!document.hidden))try{G.enqueue(new VideoFrame(ae,{timestamp:performance.now()*1e3}))}catch(ke){console.warn(ke)}})},pull(G){return b(this,null,function*(){if(i.player.mode===0&&Qr()&&i.player.element)return new Promise(ae=>{i.player.element.requestVideoFrameCallback((ke,Me)=>{try{let Y=new VideoFrame(i.player.element);G.enqueue(Y)}catch(Y){console.warn(Y)}ae()})})})}})}let P="small"in i&&i.small;return P?(this.smallEncoder||(this.smallEncoder=yield tm.call(this,i,{profile:P,type:3,trackType:o})),this.smallEncoder.track=f,this.smallEncoder.label="small",N=yield this.smallEncoder.trans(N,d,this)):this.smallEncoder&&(this.smallEncoder.close(),delete this.smallEncoder),a.track=f,a.label=e,a.start(N,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 Wo=class Wo extends he{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(Wo.INTERVALCHANGED,this.interval)}),be(ye(this,Wo.INTERVALCHANGED),fi(s=>this.room.state==="joined"?this.room.fromWorker("getAudioEnergy",s):be(g_(s),Mo(()=>[]))),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==he.ON&&this.room.emit("audio-volume",s)}))}start(e,r){this.interval=e,this.enableInBackground=r,this.emit(Wo.INTERVALCHANGED,this.interval)}stop(){}};m(Wo,"INTERVALCHANGED","intervalChanged"),Z([ot([he.INIT,he.OFF],he.ON)],Wo.prototype,"start",1),Z([ot([],he.OFF)],Wo.prototype,"stop",1);var rm=Wo;var Go=class Go extends Ql{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 rm(this));m(this,"enableAIVoice",zf);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:rh(),uint32_device_type:0,str_os_verion:ih(),uint32_link_type:1,str_client_version:ft,uint32_net_type:os[ui.getNetworkType()],ua:navigator.userAgent,version:""}});m(this,"joinAbortController",new AbortController);m(this,"smallAbortCtrl");m(this,"smallEncoder");e.tinyId&&(this.tinyId=e.tinyId,Jf(!0)),this._log||(this._log=e.logger),this.bussinessInfo=e.bussinessInfo,e.encodedDataProcessingListener&&this.setEncodedDataProcessingListener(e.encodedDataProcessingListener)}replaceTrack(e){return b(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 b(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 b(this,null,function*(){var d;let s=ui.getEnv(),n=vu(),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:vu(),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 lI.call(this,a),console.log(this),Xc.playAudio(l=>this.postMessage({cmd:"setAudioWorkletPort"},[l])),this.checkDestroy()})}leave(){return b(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 b(this,null,function*(){let e=Je(ye(this,"left")),r=this.audioManager.decodePipeline.some(o=>o);be(o=>b(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(Te(Q({},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 V.RECEIVED_PUBLISHED_USER_LIST:x.emit(e,Q({room:this},r));return;case"1":if(r.userId===this.userId)return;this.emit("peer-join",r);return;case"2":this.emit("peer-leave",r);return;case"3":let o=new Wl(this,r);this.remotePublishedUserMap.set(r.userId,o),this.emit("remote-published",o);return;case"5":{let f=r,_=this.remotePublishedUserMap.get(f);_&&(_.remoteVideoTrack.close(),_.remoteAuxiliaryTrack.close(),_.remoteAudioTrack.close(),this.remotePublishedUserMap.delete(f),this.emit("remote-unpublished",_))}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:_,flag:I}=r,R=this.remotePublishedUserMap.get(_.userId);if(!R){this.emit("remote-publish-state-changed",r);return}R.flag=I}x.emit(V.REMOTE_PUBLISH_STATE_CHANGED,Q({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=Q({},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:T_(this.userId),str_acc_ip:this.relayip,str_client_ip:this.clientip,msg_up_stream_info:a,msg_down_stream_info:l};x.emit(V.HEARTBEAT_REPORT,{room:this,report:p}),this.emit("heartbeat-report",p),x.emit(V.NETWORK_QUALITY,{room:this,uplink:{rtt:n,loss:s},downlinks:d}),delete r.downlinkInfo;break;case"signal-connection-state-changed":x.emit(V.SIGNAL_CONNECTION_STATE_CHANGED,Q({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 b(this,null,function*(){switch(yield this.sendMessage("publish",e.mediaType).then(r=>r.err!==0?Promise.reject(r.err):r),Vt(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 Xc.init(),fI.call(this,e);break;default:yield gI.call(this,e)}e.muted&&this.postMessage("mute",{mediaType:e.mediaType,srctinyid:this.tinyid,userId:this.openid,remove:!0})})}unpublish(e){return b(this,null,function*(){yt(e)})}subscribe(...e){return b(this,null,function*(){let r=e.reduce((f,_)=>_.mediaType|f,0),{userId:o,tinyId:s,streamType:n}=e[0],a=this.remotePublishedUserMap.get(o),d=Q({},a.subscribeState),l=Object.assign(new za,d);l.mediaType|=r,x.emit(V.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 mI.call(this,f);default:return hI.call(this,f)}})),x.emit(V.SUBSCRIBE_SUCCESS,{room:this,streamType:n,remotePublishedUser:a})})}unsubscribe(...e){return b(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();x.emit(V.UNSUBSCRIBE_SUCCESS,{room:this,streamType:s,remotePublishedUser:this.remotePublishedUserMap.get(o)})}})}enableSmall(e){return b(this,null,function*(){var r;if(e){if(this.videoManager.smallTrack){let o=this.videoManager.cameraTrack;this.smallEncoder=yield tm.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([Do(Go.prototype.afterJoin),ot(["left",he.INIT],"joined"),zT()],Go.prototype,"join",1),Z([ot("joined","left",{ignoreError:!0}),JT()],Go.prototype,"leave",1),Z([Gu(e=>e.mediaType),XT()],Go.prototype,"publish",1),Z([Gu(e=>e.mediaType),QT()],Go.prototype,"unpublish",1),Z([Gu((...e)=>e[0].userId),YT()],Go.prototype,"subscribe",1);var im=Go;Kn.frameWorkType=37;Kn.create=function(i){let t=Kn._create.call(this,im,i);return t._use(hf,i==null?void 0:i.assetsPath),i!=null&&i.assetsPath&&(Ht.assetsPath=i==null?void 0:i.assetsPath),console.log("trtc wasm sdk:",ft,"created",Ht),t};Object.assign(Kn.prototype,{_setCurrentSpeaker(i){let t=ze("player");return t!=null&&t.setSinkId?t.setSinkId(i):Promise.reject("not support")},_enableVideoDecodeFallback(i,t){return b(this,null,function*(){return this.startPlugin(hf.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"),er(o=>o.state==="STARTED"),Kr(1),Fp(1e4),Je(ye(i,he.INIT)),Le(e,r))})})}});Lh(37);var Tj=Kn;export{Tj as default};