trtc-sdk-v5 5.11.1-wasm.1 → 5.11.1-wasm.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/plugins/cdn-streaming/package.json +1 -1
- package/plugins/cross-room/package.json +1 -1
- package/plugins/custom-encryption/package.json +1 -1
- package/plugins/device-detector/package.json +1 -1
- package/plugins/small-stream-auto-switcher/package.json +1 -1
- package/plugins/video-decoder/package.json +1 -1
- package/plugins/video-effect/basic-beauty/package.json +1 -1
- package/plugins/video-effect/beauty/package.json +1 -1
- package/plugins/video-effect/video-mixer/package.json +1 -1
- package/plugins/video-effect/virtual-background/package.json +1 -1
- package/plugins/video-effect/watermark/package.json +1 -1
- package/plugins/voice-changer/package.json +1 -1
- package/trtc.esm.js +3 -3
- package/trtc.js +1 -1
package/trtc.esm.js
CHANGED
|
@@ -88,17 +88,17 @@ return ret;
|
|
|
88
88
|
`,W=0;W<S-1;++W)C[W+1].deleteObject&&(he+=" argType"+W+".deleteObject(arg"+W+`);
|
|
89
89
|
`);D.isVoid||(he+=` return retType.toWireType(destructors, rv);
|
|
90
90
|
`),he+=`};
|
|
91
|
-
`,G.push(he);var Re,ge,De=ec(Function,G).apply(null,J);return Re=De,ge=Es.length,Es.push(Re),H=ge,_s[F]=H,H},f:()=>{sr("")},c:Tn,t:(S,T,C)=>M.copyWithin(S,T,T+C),s:S=>{M.length,sr("OOM")},i:(S,T,C,D)=>{for(var F,H,G,J=0,K=0;K<C;K++){var W=ae[T>>2],he=ae[T+4>>2];T+=8;for(var Ne=0;Ne<he;Ne++)F=S,H=M[W+Ne],G=void 0,G=cc[F],H===0||H===10?((F===1?g:_)(No(G,0)),G.length=0):G.push(H);J+=he}return ae[D>>2]=J,0}},gr=(function(){var S,T,C,D,F={a:dc};function H(G,J){var K,W,he=G.exports;return v=(L=he).v,K=v.buffer,o.HEAP8=x=new Int8Array(K),o.HEAP16=B=new Int16Array(K),o.HEAP32=pe=new Int32Array(K),o.HEAPU8=M=new Uint8Array(K),o.HEAPU16=ee=new Uint16Array(K),o.HEAPU32=ae=new Uint32Array(K),o.HEAPF32=Xe=new Float32Array(K),o.HEAPF64=X=new Float64Array(K),Ue=L.z,W=L.w,mn.unshift(W),function(){if(Mr--,o.monitorRunDependencies&&o.monitorRunDependencies(Mr),Mr==0&&(us!==null&&(clearInterval(us),us=null),Di)){var Ne=Di;Di=null,Ne()}}(),he}if(Mr++,o.monitorRunDependencies&&o.monitorRunDependencies(Mr),o.instantiateWasm)try{return o.instantiateWasm(F,H)}catch(G){_("Module.instantiateWasm callback failed with error: "+G),r(G)}(S=E,T=te,C=F,D=function(G){H(G.instance)},S||typeof WebAssembly.instantiateStreaming!="function"||ls(T)||typeof fetch!="function"?wr(T,C,D):fetch(T,{credentials:"same-origin"}).then(G=>WebAssembly.instantiateStreaming(G,C).then(D,function(J){return _("wasm streaming compile failed: "+J),_("falling back to ArrayBuffer instantiation"),wr(T,C,D)}))).catch(r)}(),S=>(gr=L.x)(S)),$i=S=>($i=L.y)(S),Ts=S=>(Ts=L.A)(S),uc=(o.__embind_initialize_bindings=()=>(o.__embind_initialize_bindings=L.B)(),S=>(uc=L.C)(S));o.dynCall_jiji=(S,T,C,D,F)=>(o.dynCall_jiji=L.D)(S,T,C,D,F);function lc(){function S(){kt||(kt=!0,o.calledRun=!0,_o||(Qr(mn),e(o),o.onRuntimeInitialized&&o.onRuntimeInitialized(),function(){if(o.postRun)for(typeof o.postRun=="function"&&(o.postRun=[o.postRun]);o.postRun.length;)T=o.postRun.shift(),pn.unshift(T);var T;Qr(pn)}()))}Mr>0||(function(){if(o.preRun)for(typeof o.preRun=="function"&&(o.preRun=[o.preRun]);o.preRun.length;)T=o.preRun.shift(),ln.unshift(T);var T;Qr(ln)}(),Mr>0||(o.setStatus?(o.setStatus("Running..."),setTimeout(function(){setTimeout(function(){o.setStatus("")},1),S()},1)):S()))}if(Di=function S(){kt||lc(),kt||(Di=S)},o.preInit)for(typeof o.preInit=="function"&&(o.preInit=[o.preInit]);o.preInit.length>0;)o.preInit.pop()();return lc(),t.ready}})();var tS="web.sdk.qcloud.com",rS=`https://${tS}/trtc/webrtc/v5/doc`,lO=`${rS}/zh-cn/`,ig=(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))(ig||{});var og={"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}},mO=og["480p_2"],pO=og["120p_2"],eu={CANVAS:"canvas",AUDIO:"audio",VIDEO:"video",SCREEN:"screen",SMALL:"small",BIG:"big",AUXILIARY:"auxiliary",SMALL_VIDEO:"smallVideo",FACING_MODE_USER:"user",FACING_MODE_ENVIRONMENT:"environment",MUTE:"mute",UNMUTE:"unmute",ENDED:"ended",PLAYING:"playing",PAUSE:"pause",ERROR:"error",LOADEDDATA:"loadeddata",LOADEDMETADATA:"loadedmetadata",AUDIO_INPUT:"audioinput",VIDEO_INPUT:"videoinput",DETAIL:"detail",TEXT:"text",MAIN:"main",BACKUP:"backup",BANNED:"banned",KICK:"kick",USER_TIME_OUT:"user_time_out",ROOM_DISBAND:"room_disband",SEI_MESSAGE:"sei-message",ADD:"add",REMOVE:"remove",REPLACE:"replace",TRACK:"track",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",TRANSCEIVER_DIRECTION_SENDONLY:"sendonly",TRANSCEIVER_DIRECTION_RECVONLY:"recvonly",ENTER_PICTURE_IN_PICTURE:"enterpictureinpicture",LEAVE_PICTURE_IN_PICTURE:"leavepictureinpicture"},hO=eu.MAIN,fO=eu.AUXILIARY,gO=eu.BIG,EO=eu.SMALL;var _O=Object.keys(ig);var TO=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{};function Kf(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var{toString:IO}=Object.prototype,sg=class ng{constructor(t){this.core=t,Dr(this,"contextMap",new Map),Dr(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 ng.Name}getValidateRule(t){return{type:this.core.enums.BASIC_TYPE.Object}}createDecoder(t,e){switch(t){case"wasm":return new eS(Yd(Qd({},e),{wasmPath:`${this.core.assetsPath||"."}/videodec.wasm`}));case"webCodecs":return new on;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 c=this.core.room.videoManager.createDecodeContext(Yd(Qd({},t),{createDecoder:this.createDecoder}));return e(c.trackDoneOB,r(1),o(()=>{this.core.clearStarted(this,this.getGroup(t)),this.stop({track:n})})),this.contextMap.set(n,c),c.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=Kf()-t.startPerformanceTime,{renderFreezeTotal:o,dataFreezeTotal:s}=this.getRemoteTrackFreezeDuration(e,t);r&&this.core.kvStatManager.addNumber({key:514850,value:Math.floor(o/r*100),split:1,max:100}),r&&this.core.kvStatManager.addNumber({key:514851,value:Math.floor(s/r*100),split:1,max:100}),t.inputFrameCount&&this.core.kvStatManager.addNumber({key:514852,value:Math.floor(t.decodedFrameCount/t.inputFrameCount*100),split:1,max:100})}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(Yd(Qd({},t),{createDecoder:this.createDecoder})))):e.mock(this.core.enums.DECODE_FAILED_ERROR_CODE.TEST))}getRemoteTrackFreezeDuration(t,e){let r=this.core.room.badCaseDetector.getRenderFreezeMap().get(`${t.userId}_${t.streamType}`),o=this.core.room.badCaseDetector.getDataFreezeMap().get(`${t.userId}_${t.streamType}`),s=0;r&&r.freezeTimeline.forEach(({startTime:c,endTime:l})=>{c>e.startPerformanceTime&&(s+=l===0?Kf()-c:l-c)});let n=0;return o&&o.durationItemList.forEach(c=>{c.startTime>e.startPerformanceTime&&(n+=c.getDuration())}),{renderFreezeTotal:s,dataFreezeTotal:n}}destroy(){this.core.innerEmitter.off("51",this.addKVReportBeforeExitRoom)}};Dr(sg,"Name","TRTCVideoDecoder");var ap=sg;var Lg=Gi(Zi());function cp({timesInSecond:i,maxSizeInSecond:t,getSize:e}){return xe((r,o)=>{let s=new WeakMap;return V.on(U.ROOM_DESTROY,({room:n})=>s.delete(n)),function(...n){let c=s.get(this);if(c||(c={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},s.set(this,c)),c.timestamp===0?c.timestamp=Date.now():Date.now()-c.timestamp>1e3&&(c.timestamp=Date.now(),c.callCountInSecond=0,c.totalSizeInSecond=0),e&&(c.totalSizeInSecond+=e(...n)),c.timestamp!==0&&Date.now()-c.timestamp<1e3&&(c.callCountInSecond>=i||c.totalSizeInSecond>t))throw new ue({code:q.INVALID_OPERATION,message:Be({key:$e.CALL_FREQUENCY_LIMIT,data:{isTimes:c.callCountInSecond>=i,isSize:c.totalSizeInSecond>t,name:o,timesInSecond:i,maxSizeInSecond:t}})});c.callCountInSecond++,r.call(this,...n)}})}var iS="2025-06-
|
|
91
|
+
`,G.push(he);var Re,ge,De=ec(Function,G).apply(null,J);return Re=De,ge=Es.length,Es.push(Re),H=ge,_s[F]=H,H},f:()=>{sr("")},c:Tn,t:(S,T,C)=>M.copyWithin(S,T,T+C),s:S=>{M.length,sr("OOM")},i:(S,T,C,D)=>{for(var F,H,G,J=0,K=0;K<C;K++){var W=ae[T>>2],he=ae[T+4>>2];T+=8;for(var Ne=0;Ne<he;Ne++)F=S,H=M[W+Ne],G=void 0,G=cc[F],H===0||H===10?((F===1?g:_)(No(G,0)),G.length=0):G.push(H);J+=he}return ae[D>>2]=J,0}},gr=(function(){var S,T,C,D,F={a:dc};function H(G,J){var K,W,he=G.exports;return v=(L=he).v,K=v.buffer,o.HEAP8=x=new Int8Array(K),o.HEAP16=B=new Int16Array(K),o.HEAP32=pe=new Int32Array(K),o.HEAPU8=M=new Uint8Array(K),o.HEAPU16=ee=new Uint16Array(K),o.HEAPU32=ae=new Uint32Array(K),o.HEAPF32=Xe=new Float32Array(K),o.HEAPF64=X=new Float64Array(K),Ue=L.z,W=L.w,mn.unshift(W),function(){if(Mr--,o.monitorRunDependencies&&o.monitorRunDependencies(Mr),Mr==0&&(us!==null&&(clearInterval(us),us=null),Di)){var Ne=Di;Di=null,Ne()}}(),he}if(Mr++,o.monitorRunDependencies&&o.monitorRunDependencies(Mr),o.instantiateWasm)try{return o.instantiateWasm(F,H)}catch(G){_("Module.instantiateWasm callback failed with error: "+G),r(G)}(S=E,T=te,C=F,D=function(G){H(G.instance)},S||typeof WebAssembly.instantiateStreaming!="function"||ls(T)||typeof fetch!="function"?wr(T,C,D):fetch(T,{credentials:"same-origin"}).then(G=>WebAssembly.instantiateStreaming(G,C).then(D,function(J){return _("wasm streaming compile failed: "+J),_("falling back to ArrayBuffer instantiation"),wr(T,C,D)}))).catch(r)}(),S=>(gr=L.x)(S)),$i=S=>($i=L.y)(S),Ts=S=>(Ts=L.A)(S),uc=(o.__embind_initialize_bindings=()=>(o.__embind_initialize_bindings=L.B)(),S=>(uc=L.C)(S));o.dynCall_jiji=(S,T,C,D,F)=>(o.dynCall_jiji=L.D)(S,T,C,D,F);function lc(){function S(){kt||(kt=!0,o.calledRun=!0,_o||(Qr(mn),e(o),o.onRuntimeInitialized&&o.onRuntimeInitialized(),function(){if(o.postRun)for(typeof o.postRun=="function"&&(o.postRun=[o.postRun]);o.postRun.length;)T=o.postRun.shift(),pn.unshift(T);var T;Qr(pn)}()))}Mr>0||(function(){if(o.preRun)for(typeof o.preRun=="function"&&(o.preRun=[o.preRun]);o.preRun.length;)T=o.preRun.shift(),ln.unshift(T);var T;Qr(ln)}(),Mr>0||(o.setStatus?(o.setStatus("Running..."),setTimeout(function(){setTimeout(function(){o.setStatus("")},1),S()},1)):S()))}if(Di=function S(){kt||lc(),kt||(Di=S)},o.preInit)for(typeof o.preInit=="function"&&(o.preInit=[o.preInit]);o.preInit.length>0;)o.preInit.pop()();return lc(),t.ready}})();var tS="web.sdk.qcloud.com",rS=`https://${tS}/trtc/webrtc/v5/doc`,lO=`${rS}/zh-cn/`,ig=(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))(ig||{});var og={"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}},mO=og["480p_2"],pO=og["120p_2"],eu={CANVAS:"canvas",AUDIO:"audio",VIDEO:"video",SCREEN:"screen",SMALL:"small",BIG:"big",AUXILIARY:"auxiliary",SMALL_VIDEO:"smallVideo",FACING_MODE_USER:"user",FACING_MODE_ENVIRONMENT:"environment",MUTE:"mute",UNMUTE:"unmute",ENDED:"ended",PLAYING:"playing",PAUSE:"pause",ERROR:"error",LOADEDDATA:"loadeddata",LOADEDMETADATA:"loadedmetadata",AUDIO_INPUT:"audioinput",VIDEO_INPUT:"videoinput",DETAIL:"detail",TEXT:"text",MAIN:"main",BACKUP:"backup",BANNED:"banned",KICK:"kick",USER_TIME_OUT:"user_time_out",ROOM_DISBAND:"room_disband",SEI_MESSAGE:"sei-message",ADD:"add",REMOVE:"remove",REPLACE:"replace",TRACK:"track",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",TRANSCEIVER_DIRECTION_SENDONLY:"sendonly",TRANSCEIVER_DIRECTION_RECVONLY:"recvonly",ENTER_PICTURE_IN_PICTURE:"enterpictureinpicture",LEAVE_PICTURE_IN_PICTURE:"leavepictureinpicture"},hO=eu.MAIN,fO=eu.AUXILIARY,gO=eu.BIG,EO=eu.SMALL;var _O=Object.keys(ig);var TO=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{};function Kf(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var{toString:IO}=Object.prototype,sg=class ng{constructor(t){this.core=t,Dr(this,"contextMap",new Map),Dr(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 ng.Name}getValidateRule(t){return{type:this.core.enums.BASIC_TYPE.Object}}createDecoder(t,e){switch(t){case"wasm":return new eS(Yd(Qd({},e),{wasmPath:`${this.core.assetsPath||"."}/videodec.wasm`}));case"webCodecs":return new on;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 c=this.core.room.videoManager.createDecodeContext(Yd(Qd({},t),{createDecoder:this.createDecoder}));return e(c.trackDoneOB,r(1),o(()=>{this.core.clearStarted(this,this.getGroup(t)),this.stop({track:n})})),this.contextMap.set(n,c),c.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=Kf()-t.startPerformanceTime,{renderFreezeTotal:o,dataFreezeTotal:s}=this.getRemoteTrackFreezeDuration(e,t);r&&this.core.kvStatManager.addNumber({key:514850,value:Math.floor(o/r*100),split:1,max:100}),r&&this.core.kvStatManager.addNumber({key:514851,value:Math.floor(s/r*100),split:1,max:100}),t.inputFrameCount&&this.core.kvStatManager.addNumber({key:514852,value:Math.floor(t.decodedFrameCount/t.inputFrameCount*100),split:1,max:100})}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(Yd(Qd({},t),{createDecoder:this.createDecoder})))):e.mock(this.core.enums.DECODE_FAILED_ERROR_CODE.TEST))}getRemoteTrackFreezeDuration(t,e){let r=this.core.room.badCaseDetector.getRenderFreezeMap().get(`${t.userId}_${t.streamType}`),o=this.core.room.badCaseDetector.getDataFreezeMap().get(`${t.userId}_${t.streamType}`),s=0;r&&r.freezeTimeline.forEach(({startTime:c,endTime:l})=>{c>e.startPerformanceTime&&(s+=l===0?Kf()-c:l-c)});let n=0;return o&&o.durationItemList.forEach(c=>{c.startTime>e.startPerformanceTime&&(n+=c.getDuration())}),{renderFreezeTotal:s,dataFreezeTotal:n}}destroy(){this.core.innerEmitter.off("51",this.addKVReportBeforeExitRoom)}};Dr(sg,"Name","TRTCVideoDecoder");var ap=sg;var Lg=Gi(Zi());function cp({timesInSecond:i,maxSizeInSecond:t,getSize:e}){return xe((r,o)=>{let s=new WeakMap;return V.on(U.ROOM_DESTROY,({room:n})=>s.delete(n)),function(...n){let c=s.get(this);if(c||(c={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},s.set(this,c)),c.timestamp===0?c.timestamp=Date.now():Date.now()-c.timestamp>1e3&&(c.timestamp=Date.now(),c.callCountInSecond=0,c.totalSizeInSecond=0),e&&(c.totalSizeInSecond+=e(...n)),c.timestamp!==0&&Date.now()-c.timestamp<1e3&&(c.callCountInSecond>=i||c.totalSizeInSecond>t))throw new ue({code:q.INVALID_OPERATION,message:Be({key:$e.CALL_FREQUENCY_LIMIT,data:{isTimes:c.callCountInSecond>=i,isSize:c.totalSizeInSecond>t,name:o,timesInSecond:i,maxSizeInSecond:t}})});c.callCountInSecond++,r.call(this,...n)}})}var iS="2025-06-17 10:38:54",ag=!0,cg=function(){var i;if(ag){ag=!1,$.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${kr}/en/index.html`),console.info(`* Changelog: ${kr}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),$.info("TRTC Web SDK Version:",at),Rr||$.debug("Build Time:",iS);let t=`UA: ${navigator.userAgent}
|
|
92
92
|
CPU core: ${navigator.hardwareConcurrency}, GPU: ${vl()}`,e=navigator.deviceMemory;e&&(t+=`, minRAM: ${e}GB`),$.info(t),$.info(`URL: ${location.href}${((i=self.frameElement)==null?void 0:i.tagName)==="IFRAME"?" in iframe":""}`),$o().then(r=>{r&&$.info(Ar)})}};var mr={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 le={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},pr=(w=>(w[w.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",w[w.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",w[w.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",w[w.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",w[w.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",w[w.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",w[w.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",w[w.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",w[w.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",w[w.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",w[w.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",w[w.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",w[w.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",w[w.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",w[w.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",w[w.INVALID_ROOM_ID_REQUIRED=5015]="INVALID_ROOM_ID_REQUIRED",w[w.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",w[w.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",w[w.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",w[w.INVALID_ROOM_ID_TYPE_MISMATCH=5019]="INVALID_ROOM_ID_TYPE_MISMATCH",w[w.INVALID_ROOM_ID_DUPLICATE=5020]="INVALID_ROOM_ID_DUPLICATE",w[w.INVALID_OPERATION=5100]="INVALID_OPERATION",w[w.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",w[w.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",w[w.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",w[w.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",w[w.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",w[w.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",w[w.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",w[w.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",w[w.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",w[w.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",w[w.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",w[w.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",w[w.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",w[w.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",w[w.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",w[w.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",w[w.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",w[w.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",w[w.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",w[w.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",w[w.DEVICE_ERROR=5300]="DEVICE_ERROR",w[w.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",w[w.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",w[w.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",w[w.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",w[w.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",w[w.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",w[w.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",w[w.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",w[w.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",w[w.SERVER_ERROR=5400]="SERVER_ERROR",w[w.NEED_TO_BUY=5401]="NEED_TO_BUY",w[w.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",w[w.OPERATION_FAILED=5500]="OPERATION_FAILED",w[w.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",w[w.REJOIN_FAILED=5502]="REJOIN_FAILED",w[w.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",w[w.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",w[w.VIDEO_DECODE_ERROR=5505]="VIDEO_DECODE_ERROR",w[w.OPERATION_ABORT=5998]="OPERATION_ABORT",w[w.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",w))(pr||{});function ug({code:i,params:t,enableDocLink:e=!1}){let r="",o,s=pr[i];try{o=dg[s]}catch(n){o=dg.UNKNOWN_ERROR}return We(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 dg=Te(z({},Xt),{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: ${ct(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: ${ct(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=ss(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=ss(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=ss(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=ss(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=ss(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=ss(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=ss(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 ss(i){if(!i)return"camera";let t=i.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var dp=class i extends Error{constructor({code:e,extraCode:r,message:o="",messageParams:s,fnName:n="",originError:c}){var m;let l;o?l=o:l=ug({code:e===le.SERVER_ERROR?e:r||e,params:z({fnName:n,error:c},s)});super(l);u(this,"name","RtcError");u(this,"code");u(this,"extraCode");u(this,"functionName");u(this,"message");u(this,"handler");u(this,"originError");this.name=pr[e],this.code=e,this.extraCode=r,this.functionName=n,this.originError=c,this.message=l,this.extraCode===5302&&((m=this.originError)!=null&&m.message.includes("system"))&&(this.handler=()=>{let E={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},g={startLocalVideo:"webcam",startLocalAudio:"microphone"},_=document.createElement("a");Fo?_.href=`ms-settings:privacy-${g[this.functionName]}`:br&&(_.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${E[this.functionName]}`),_.href.length>0&&_.click()})}static convertFrom(e,r,o){let s=e;if(e instanceof ue){let{stack:n}=e,c={code:le.UNKNOWN_ERROR,fnName:r,originError:e};switch(e.getCode()){case q.INVALID_PARAMETER:c.code=le.INVALID_PARAMETER,c.message=e.message;break;case q.INVALID_OPERATION:c.code=le.INVALID_OPERATION;break;case q.NOT_SUPPORTED:case q.NOT_SUPPORTED_H264:c.code=le.ENV_NOT_SUPPORTED,e.getCode()===q.NOT_SUPPORTED_H264&&(c.extraCode=e.message.includes(Xt.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case q.JOIN_ROOM_FAILED:c.messageParams={fnParams:o};case q.SERVER_TIMEOUT:case q.SWITCH_ROLE_FAILED:case q.SWITCH_ROOM_FAILED:c.code=le.SERVER_ERROR,c.extraCode=e.getExtraCode();break;case q.API_CALL_ABORTED:c.code=le.OPERATION_ABORT;break;case q.DEVICE_NOT_FOUND:case q.DEVICE_AUTO_RECOVER_FAILED:case q.INITIALIZE_FAILED:c.code=5300,e.name&&(c.extraCode=oS(e.name));break;case q.UNKNOWN:break;default:c.code=le.OPERATION_FAILED}s=new i(c),n&&(s.stack+=n.substr(n.indexOf(`
|
|
93
93
|
`)))}else{if(e instanceof i)return e;s=new i({code:le.UNKNOWN_ERROR,fnName:r,originError:e})}return s}};function oS(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=dp;function uo(i){return i==="sub"?"auxiliary":i==="auxiliary"?"sub":"main"}function xa(i){return i===mr.QOS_PREFERENCE_CLEAR?"detail":i===mr.QOS_PREFERENCE_SMOOTH?"motion":""}function sn(i,t){let e=t?tl:Nn;return ll(i)?z(z({},e),i):Tr[i]?Tr[i]:e}var lg={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}}},mg={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}}},nn={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(i,t,e){if(Oe(i)&&!document.getElementById(i))throw new ne({code:le.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:t}})}},pg={name:"userId",required:!0,type:"string"},hg={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[mr.AUDIO_PROFILE_STANDARD,mr.AUDIO_PROFILE_STANDARD_STEREO,mr.AUDIO_PROFILE_HIGH,mr.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function an(i,t){if(!i)throw new ne({code:le.INVALID_OPERATION,extraCode:5101,fnName:t})}function fg(i,t,e){if(!i)throw new ne({code:le.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:e}})}function gg(i,t,e){if(!(/^[1-9]\d*$/.test(String(i))&&i<4294967295))throw new ne({code:le.INVALID_PARAMETER,extraCode:5013,fnName:t,messageParams:{key:e}})}function Eg(i,t,e){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(i))throw new ne({code:le.INVALID_PARAMETER,extraCode:5012,fnName:t,messageParams:{key:e}})}var B0={type:"number",notLessThanZero:!0},sS=(i,t)=>i.width*i.height>=t.width*t.height&&i.frameRate>=t.frameRate&&i.bitrate>=t.bitrate;function _g(i){var r;if(!((r=i==null?void 0:i.option)!=null&&r.small))return;if(!dd()){$.warn("small stream is not supported"),delete i.option.small;return}let t=sn(i.option.profile),e=sn(i.option.small,!0);if(!sS(t,e)){$.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 nS={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:le.INVALID_OPERATION,extraCode:5104,fnName:e});if(i.roomId){if(Oe(i.roomId))throw new ne({code:le.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:t}});gg(i.roomId,e,t)}else if(i.strRoomId)Eg(i.strRoomId,e,t);else throw new ne({code:le.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:nn,mute:{type:["boolean","string"]},publish:{type:"boolean"},capture:{required:!1,type:"boolean"},option:lg},validate(i){var t,e;if(!((t=i==null?void 0:i.option)!=null&&t.videoTrack)&&fi())throw new ne({code:le.ENV_NOT_SUPPORTED,extraCode:5201});(e=i==null?void 0:i.option)!=null&&e.small&&_g(i)}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:Te(z({},nn),{required:!1}),publish:{type:"boolean"},capture:{required:!1,type:"boolean"},mute:{type:["boolean","string"]},option:lg},validate(i){var t;(t=i==null?void 0:i.option)!=null&&t.small&&_g(i)}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:hg},validate(i){var t;if(!((t=i==null?void 0:i.option)!=null&&t.audioTrack)&&fi())throw new ne({code:le.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:hg}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:nn,publish:{type:"boolean"},option:mg},validate(i,t,e,r,o){var s;if(!((s=i==null?void 0:i.option)!=null&&s.videoTrack)){if(fi())throw new ne({code:le.ENV_NOT_SUPPORTED,extraCode:5201});if(!aa())throw new ne({code:le.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:nn,publish:{type:"boolean"},option:mg}},muteRemoteAudio:[pg,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[pg,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:nn,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){an(this._room.isJoined,e);let r=this._room.remotePublishedUserMap.get(i.userId);if(fg(!!r,e,i),r&&(i.streamType==="main"&&!r.muteState.videoAvailable||i.streamType==="sub"&&!r.muteState.hasAuxiliary))throw new ne({code:le.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:i}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:Te(z({},nn),{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){an(this._room.isJoined,e);let r=this._room.remotePublishedUserMap.get(i.userId);if(fg(!!r,e,i),r&&(i.streamType==="main"&&!r.muteState.videoAvailable||i.streamType==="sub"&&!r.muteState.hasAuxiliary))throw new ne({code:le.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:i}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(i,t,e){if(i.userId!=="*"&&P(i.streamType))throw new ne({code:le.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(i,t,e){an(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(!ua)throw new ne({code:le.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new ne({code:le.INVALID_OPERATION,fnName:e,extraCode:5108});if(i.byteLength>1e3)throw new ne({code:le.INVALID_PARAMETER,extraCode:5018,fnName:e});if(i.byteLength===0)throw new ne({code:le.INVALID_PARAMETER,extraCode:5017,messageParams:{key:t},fnName:e});an(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:le.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:le.INVALID_PARAMETER,extraCode:5018,fnName:e});if(i.byteLength===0)throw new ne({code:le.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:t}})}}},validate(i,t,e){if(an(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new ne({code:le.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:t}})}},switchRoom:{name:"switchRoomConfig",type:"object",required:!0,validate(i,t,e){if(an(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:le.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:le.INVALID_PARAMETER,extraCode:5019,fnName:e,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(i.roomId)gg(i.roomId,e,t);else if(i.strRoomId)Eg(i.strRoomId,e,t);else throw new ne({code:le.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}}}},yt={TRTC:nS};var $t=class extends Error{};function aS(i,t){let e=Po(i);for(let r=0;r<t.length;r++)dr(e[r],t[r]);return e}function cS(i){this._resolve=Promise.resolve(i)}function dS(i){this._reject=Promise.reject(i)}var lo=class lo{constructor(t,e){this.instance=t;this.group=e;u(this,"started",!1);u(this,"ops",[]);u(this,"startSame",()=>!0);u(this,"mergeUpdate",aS);let r=lo.instances.get(t);r?r.set(e,this):lo.instances.set(t,new Map([[e,this]]))}static get(t,e){if(!e)return;let r=lo.instances.get(t);return r&&r.get(e)||new lo(t,e)}static gets(t,e){let r=lo.instances.get(t),o=[];return r&&r.forEach((s,n)=>{e.test(n)&&o.push(s)}),o}action(t,e,r){let o=c=>{var l;return t===0?this.started=!0:t===3&&(this.started=!1),this.ops.shift(),(l=this.currentOp)==null||l.action(),c},s=c=>{var l,m;throw this.ops.shift(),t===0&&((l=this.currentOp)==null?void 0:l.type)===2&&this.ops.shift().reject(new $t("start failed")),(m=this.currentOp)==null||m.action(),c},n={type:t,action:()=>e(...n.args).then(o,s),args:r,resolve:cS,reject:dS};try{switch(this.state){case 1:if(t===0)throw new $t("already started");break;case 4:if(t===2)throw new $t("not started");break;default:return this.cacheOp(n)}}catch(c){return Promise.reject(c)}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 $t("already start");break;case 3:switch(t.type){case 2:throw new $t("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new $t("unknown state")}else switch(t.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let r=new $t("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 $t("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new $t("start not allowed after update");case 0:throw new $t("duplicate start");case 3:if(this.startSame(this.currentOp.args,t.args))throw this.ops.pop().reject(new $t("keep start")),new $t("already start")}}t.promise=new Promise((r,o)=>{t._resolve?t._resolve.then(r):t.resolve=r,t._reject?t._reject.catch(o):t.reject=o});let{action:e}=t;return t.action=()=>e().then(t.resolve,t.reject),this.ops.push(t),t.promise}get lastOp(){return this.ops[this.ops.length-1]}get lastOpType(){return this.lastOp.type}get currentOp(){return this.ops[0]}get state(){return this.currentOp?this.currentOp.type:this.started?1:4}};u(lo,"instances",new WeakMap);var Ri=lo;var tu=new WeakMap,ru=(i,t)=>{if(t instanceof $t){let{stack:e}=t;t=new ne({code:le.OPERATION_ABORT,message:`${i} abort: ${t.message}`,fnName:i}),e&&(t.stack+=e.substr(e.indexOf(`
|
|
94
94
|
`)))}throw t};function mo(i,t){return xe((e,r)=>function(...o){let s=Ri.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(ru.bind(null,r))):e.apply(this,o)})}function ns(i,t){let{merge:e,debounce:r}=t||{};return xe((o,s)=>function(...n){let c=Ri.get(this,typeof i=="string"?i:i.call(this,...n));if(!c)return o.apply(this,n);if(e&&(c.mergeUpdate=e.bind(this)),r&&r.isNeedToDebounce.apply(this,n)){let{delay:l,getKey:m}=r;return new Promise((E,g)=>{var L,x;let _=(L=tu.get(this))==null?void 0:L.get(m(...n));if(_){let{timeoutId:M,resolve:B}=_;clearTimeout(M),B()}let v=setTimeout(()=>{if(c.state===3||c.state===4)return E();c.action(2,o.bind(this),n).catch(ru.bind(null,s)).then(E,g)},l);tu.has(this)?(x=tu.get(this))==null||x.set(m(...n),{timeoutId:v,resolve:E}):tu.set(this,new Map([[m(...n),{timeoutId:v,resolve:E}]]))})}return c.action(2,o.bind(this),n).catch(ru.bind(null,s))})}function po(i){return xe((t,e)=>function(...r){let o=typeof i=="function"?i.call(this,...r):i;if(o instanceof RegExp)return Promise.all(Ri.gets(this,o).map(n=>n.action(3,()=>Promise.resolve(),r))).then(()=>t.call(this,...r));let s=Ri.get(this,o);return s?s.action(3,t.bind(this),r).catch(ru.bind(null,e)):t.apply(this,r)})}var re={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"},Tg=new Set([re.ERROR,re.AUTOPLAY_FAILED,re.KICKED_OUT,re.REMOTE_USER_ENTER,re.REMOTE_USER_EXIT,re.REMOTE_AUDIO_AVAILABLE,re.REMOTE_AUDIO_UNAVAILABLE,re.REMOTE_VIDEO_AVAILABLE,re.REMOTE_VIDEO_UNAVAILABLE,re.CONNECTION_STATE_CHANGED,re.PUBLISH_STATE_CHANGED,re.SCREEN_SHARE_STOPPED,re.DEVICE_CHANGED,re.FIRST_VIDEO_FRAME]);var lp={};Kr(lp,{bytes2ms:()=>ih,calculateScaleResolutionDownNumber:()=>Cc,convertObjectNumberToInt:()=>Vn,copyProperties:()=>rh,deepClone:()=>Po,deepMerge:()=>dr,delay:()=>Fn,fibonacci:()=>ko,formatedTime:()=>yc,getConstructorName:()=>vs,getContainerFromElement:()=>lh,getEnv:()=>Kp,getInternalVersion:()=>dh,getLoggerUrl:()=>oi,getMediaStreamTrackInfo:()=>vc,getMuteStateFromFlag:()=>Ln,getNetworkType:()=>xn,getNumNetworkType:()=>Ac,getReconnectionTimeout:()=>sh,getStringByteLength:()=>mh,getTurnServer:()=>uh,getUint32Version:()=>bc,getValueType:()=>ct,getViewListFromView:()=>Ds,glog:()=>Pn,ipv4ToUint32:()=>Ns,isArray:()=>ot,isAudioWorkletSupported:()=>ch,isBoolean:()=>st,isConstructor:()=>Lo,isEmpty:()=>Cs,isFunction:()=>We,isLangChinese:()=>Sr,isMediaStreamTrack:()=>nh,isNumber:()=>ke,isObject:()=>Ir,isOverseaSdkAppId:()=>ii,isPlainObject:()=>Lt,isPortrait:()=>cl,isPromise:()=>qi,isRemoteTrack:()=>ah,isRotate90Or270:()=>si,isString:()=>Oe,isUndefined:()=>P,loadImage:()=>Ms,ms2bytes:()=>oh,ms2samples:()=>al,normalizeUrl:()=>Uo,performanceNow:()=>Ie,promiseAny:()=>kn,samples2ms:()=>nl,setNetworkType:()=>th,stringify:()=>cr,stringifyIncludeValue:()=>Un,throttlePromise:()=>Rc});var hp={};Kr(hp,{ScheduleRequestType:()=>Sg,getAbilityConfig:()=>lS,getScheduleDomain:()=>su,isNeedToSchedule:()=>iu,scheduleProxy:()=>Jr,sendScheduleRequest:()=>pp,setIsNeedToSchedule:()=>as,setScheduleProxy:()=>ou});var mp=null,iu=!0;typeof document!="undefined"&&document.head.insertAdjacentHTML("beforeend",Object.values(ri).map(i=>`<link rel="dns-prefetch" href="https://${i}">`).join(`\r
|
|
95
95
|
`));function as(i){st(i)&&i!==iu&&(iu=i,$.info(`setIsNeedToSchedule ${i}`))}V.on("28",()=>as(!0));V.on("63",()=>as(!0));V.on("84",()=>as(!0));V.on("201",i=>{i.state==="RECONNECTING"&&as(!0)});V.on("202",i=>{i.state==="RECONNECTING"&&as(!0)});function uS(i,t,e){let r={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let o=performance.getEntriesByType("resource"),s=ho(i,"config",N.MAIN),n=ho(i,"config",N.BACKUP);for(let c of o)if(c.startTime>=e&&(c.name===s||c.name===n)&&c.transferSize>0){let l=c.name===s?N.MAIN:N.BACKUP,m=Math.round(c.duration),E=Math.round(c.domainLookupStart-c.startTime),g=c.redirectStart>0?Math.round(c.redirectEnd-c.redirectStart):0,_=c.fetchStart>0?Math.round(c.domainLookupStart-c.fetchStart):0,v=Math.round(c.domainLookupEnd-c.domainLookupStart),L=Math.round(c.requestStart-c.secureConnectionStart),x=Math.round(c.secureConnectionStart-c.connectStart),M=Math.round(c.responseStart-c.requestStart),B=Math.round(c.responseEnd-c.responseStart),ee=[v,L,x,M,B];je.uploadEvent({log:`stat-schedule-net:${m}(${E}(${g}->${_})->${ee.join("->")}) ${l}`,userId:t}),r=Te(z({},r),{totalCost:m,local:E,dns:v,tcp:x,tls:L,request:M,response:B});break}}catch(o){$.error("getScheduleDetailCost error",o)}return r}function pp(m){return A(this,arguments,function*({userId:i,sdkAppId:t,useStringRoomId:e,roomId:r,userSig:o,version:s,frameWorkType:n,role:c,latencyLevel:l}){if(!iu&&mp)return{isCached:!0,result:mp};let E={delta:0,count:[1,1],msg:[],detail:[]};try{let g=new FormData;g.append("userId",String(i)),g.append("sdkAppId",String(t)),g.append("isStrGroupId",String(e)),g.append("groupId",String(r)),g.append("sdkVersion",s),g.append("userSig",String(o));let _=yield $o();_!=null&&_.model&&g.append("model",String(_==null?void 0:_.model)),c&&g.append("role",String(c)),l&&g.append("latencyLevel",String(l)),n&&g.append("frameWorkType",String(n));let v=Ie(),L=yield pS(g,E,t);L.config&&(L.config.loggerDomain&&Mo(L.config.loggerDomain),st(L.config.scheduleCache)&&as(!L.config.scheduleCache)),E.delta=Ie()-v;let x=uS(Number(t),i,v);return mp=L,{isCached:!1,result:L,detailCost:x}}catch(g){let _=ot(g)?g[0]:g,v=ke(_.code)?_.code:0,L=`schedule failed${_.message?`: ${_.message}`:""}`,x=new ue({code:q.SCHEDULE_FAILED,extraCode:v,message:Be({key:$e.JOIN_ROOM_FAILED,data:{error:L,code:v}})});throw $.error(L,v),x}})}var Jr={main:"",backup:""};function ou(i){ot(i)?(Jr.main=i[0],Jr.backup=i[1]):Jr.main=i}var Sg=(r=>(r.CONFIG="config",r.TRTC_AUTO_CONF="trtcAutoConf",r.AUDIO_AI_AUTH="audioAiAuth",r))(Sg||{});function ho(i,t,e=N.MAIN,r=!1){return`https://${Jr[e]||su(i,e,r)}/api/v1/${t}`}function lS(i,t,e){let r=ho(i,t),o=ho(i,t,N.BACKUP),s=new URLSearchParams(e).toString(),n=fetch(`${r}?${s}`).then(l=>l.json()),c=fetch(`${o}?${s}`).then(l=>l.json());return kn([n,c])}function su(i,t=N.MAIN,e=!1){let r;return ii(i)?e?r=t===N.MAIN?ri.MAIN_OVERSEA_BACKUP:ri.BACKUP_OVERSEA:r=t===N.MAIN?ri.MAIN_OVERSEA:ri.BACKUP_OVERSEA:r=t===N.MAIN?ri.MAIN:ri.BACKUP,r}function mS(i,t,e){return new Promise((r,o)=>{ni({url:i,body:t,timeout:e.timeout,priority:"high"}).then(s=>{s.data.code===0?r(s.data.data):o({code:s.data.code,message:s.data.msg})}).catch(o)})}var Ig=(i,t)=>zi({retryFunction:mS,settings:{retries:3,timeout:0},onError:t,onRetrying:i});function pS(i,t,e){return new Promise((r,o)=>{let s=null;kn([Ig(n=>t.count[0]=n+1,({error:n,retry:c,retriedCount:l,retryFuncArgs:m})=>{t.msg[0]=n.message,s||(l>=1&&(m[0]=ho(e,"config",N.MAIN,!0)),c())})(ho(e,"config",N.MAIN),i,{get timeout(){return ko(2+t.count[0])*1e3}}),Ig(n=>t.count[1]=n+1,({error:n,retry:c,retriedCount:l,retryFuncArgs:m})=>{t.msg[1]=n.message,s||(l>=2&&(m[0]=ho(e,"config",N.BACKUP,!0)),c())})(ho(e,"config",N.BACKUP),i,{get timeout(){return ko(2+t.count[1])*1e3}})]).then(n=>{s=n,r(s)}).catch(o)})}var hS=i=>i.startsWith("data:application/octet-stream;base64,"),fS=i=>i.startsWith("file://"),Pa=class{constructor(){u(this,"_log");this._log=$.createLogger({id:"fd"})}download(t,e){return A(this,null,function*(){let{type:r="blob"}=e||{};t=Uo(t);try{let o=Ie(),s;if(We(fetch)?s=yield this.downloadWithFetch(t,r):s=yield this.downloadWithXHR(t,r),!s||!s.data)throw new Error("data is empty");let n=Ie()-o;return this._log.info(`downloaded: ${t}, return type: ${r}, cost: ${n}ms`),Q.addSuccessEvent({key:522700,cost:Ie()-o}),s.data}catch(o){throw this._log.error(`failed to download: ${t}, error: ${o}`),Q.addFailedEvent({key:522700,error:o}),o}})}downloadWithFetch(t,e){return A(this,null,function*(){this._log.info(`download with fetch: ${t}, return type: ${e}`);try{let r=yield fetch(t);if(!r.ok){let s=new Error(`network response was not ok: ${r.status}`);throw s.status=r.status,s}let o;return e==="arraybuffer"?o=yield r.arrayBuffer():o=yield r.blob(),{data:o}}catch(r){throw r}})}downloadWithXHR(t,e){return this._log.info(`download with xhr: ${t}, return type: ${e}`),new Promise((r,o)=>{let s=new XMLHttpRequest;s.open("GET",t,!0),s.responseType=e,s.onload=()=>{if(s.status===200||s.status===0&&s.response)r({data:s.response});else{let n=new Error(`XHR failed, status: ${s.status}`);n.status=s.status,o(n)}},s.onerror=o,s.send(null)})}loadWasm(t,e){return A(this,null,function*(){this._log.info(`loadWasm ${t}, importObject: ${JSON.stringify(e)}`);let r=Ie(),o=null,s=null;if(We(WebAssembly.instantiateStreaming)&&!hS(t)&&!fS(t)&&We(fetch))try{let n=fetch(t);o=(yield WebAssembly.instantiateStreaming(n,e)).instance}catch(n){s=n}if(!o)try{let n=yield this.download(t,{type:"arraybuffer"});o=(yield WebAssembly.instantiate(n,e)).instance}catch(n){s=n}if(o){let n=Ie()-r;return this._log.info(`loadedWasm ${t}, cost: ${n}ms`),Q.addSuccessEvent({key:522701,cost:n}),o}throw this._log.error(`failed to loadWasm ${t}, error: ${s}`),Q.addFailedEvent({key:522701,error:s}),s})}loadScript(t){this._log.info(`loadScript ${t}`);let e=Ie();return new Promise((r,o)=>{let s=document.createElement("script");s.type="text/javascript",s.onload=()=>{this._log.info(`loadedScript ${t}, cost: ${Ie()-e}ms`),Q.addSuccessEvent({key:522702,cost:Ie()-e,split:1e3}),r(s)},s.onerror=n=>{this._log.error(`failed to loadScript ${t}, error: ${n}`),Q.addFailedEvent({key:522702}),o(n)},s.crossOrigin="anonymous",s.src=t,document.head.append?document.head.append(s):document.getElementsByTagName("head")[0].appendChild(s)})}};Z([zo({settings:{timeout:0,retries:3},onError(t,e,r){var o;(t==null?void 0:t.status)===404||(o=t==null?void 0:t.message)!=null&&o.includes("404")?(this._log.warn("download 404, stop retry"),r(t)):e()},onRetrying(t){this._log.warn(`download retrying: ${t}`)}})],Pa.prototype,"download",1),Z([zo({settings:{timeout:3e3,retries:3},onRetrying(t){this._log.warn(`loadScript retrying: ${t}`)}})],Pa.prototype,"loadScript",1);var Ag=new Pa;function yg({TRTC:i,room:t,errorModule:e,assetsPath:r}){return{TRTC:i,room:t,assetsPath:r,fileDownloader:Ag,innerEmitter:V,constants:sl,environment:Bs,utils:lp,eventLogger:je,log:this.room.getLogger(),loggerManager:$,errorModule:e,kvStatManager:Q,rtcDectection:eo,trtc:this,rx:ip,enums:Wl,schedule:hp,clearStarted:(o,s)=>{let n=o.getAlias(),c=Ri.instances.get(this);if(c)if(s){let l=c.get(n+s);if(!l)return;l.started=!1}else c.forEach((l,m)=>{m.startsWith(n)&&(l.started=!1)})},startGetPCM:Aa,createAudioNode:_a}}var bg=(i,t)=>{let{emit:e}=i;return i.emit=(...r)=>{try{return e.apply(i,r)}catch(o){let s=Be({key:$e.CATCH_HANDLER_ERROR,data:{name:t,event:r[0]},addDocLink:!1});return $.warn(`${s}
|
|
96
96
|
|
|
97
|
-
${o.stack}`),!1}},i};var cn=new WeakMap;function Rg(i){let t=cn.get(i);t&&(t.forEach(e=>clearTimeout(e)),cn.delete(i))}function vg(i,t){return xe((e,r)=>function(...o){let s=cn.get(this);s||(s=new Map,cn.set(this,s));let n=t(...o),c=s.get(n);if(!c||c<=0){e.apply(this,o);let l=setTimeout(()=>{var m;(m=cn.get(this))==null||m.delete(n)},i);s.set(n,l)}else{clearTimeout(c);let l=window.setTimeout(()=>{var m;e.apply(this,o),(m=cn.get(this))==null||m.delete(n)},i);s.set(n,l)}})}var Ng="trtc-sdk-v5",Dg="5.11.1-wasm.1";function Mt(...i){return xe((t,e)=>function(...r){try{au.call(this,i,r,e,this._name)}catch(o){return Promise.reject(o)}return t.apply(this,r)})}function fp(...i){return xe((t,e)=>function(...r){try{au.call(this,i,r,e,this._name)}catch(o){throw o}return t.apply(this,r)})}function au(i,t,e,r){if(ot(i))for(let o=0;o<i.length;o++)nu.call(this,{rule:i[o],value:t[o],key:i[o].name,fnName:e,className:r});else nu.call(this,{rule:i,value:t[0],key:i.name,fnName:e,className:r})}function nu({rule:i,value:t,key:e,fnName:r,className:o}){function s(l){return{code:le.INVALID_PARAMETER,extraCode:l,fnName:r,messageParams:{key:e,rule:i,value:t}}}if(P(t)){if(i.required)throw new ne(s(5001));if(P(i.defaultValue)){We(i.validate)&&i.validate.call(this,t,e,r,o,this);return}t=i.defaultValue}if(Array.isArray(i.type)){let l=!1;for(let m=0;m<i.type.length;m++)i.type[m]===null&&t===null&&(l=!0),We(i.type[m])&&t instanceof i.type[m]&&(l=!0),Oe(i.type[m])&&ct(t)===i.type[m].toLowerCase()&&(l=!0);if(!l)throw new ne({code:le.INVALID_PARAMETER,extraCode:5002,fnName:r,messageParams:{key:e,rule:{type:i.type.map(m=>Lo(m)?vs(m):Oe(m)?m:ct(m))},value:t}})}else if(!P(i.type)&&ct(t)!==i.type)throw new ne(s(5002));if(i.allowEmpty===!1){let l=ke(t)&&(t===0||Number.isNaN(t)),m=Oe(t)&&t.trim()==="";if(l||m)throw new ne(s(5003))}if(i.notLessThanZero&&ke(t)&&t<0)throw new ne(s(5006));if(!P(i.min)&&ke(t)&&t<i.min)throw new ne(s(5007));if(!P(i.max)&&ke(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(We(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;Lt(n)&&Ir(t)&&Object.keys(n).forEach(l=>{nu.call(this,{rule:n[l],value:t&&t[l],key:`${l}`,fnName:r,className:o})});let{arrayItem:c}=i;Lt(c)&&ot(t)&&t.forEach((l,m)=>{nu.call(this,{rule:c,value:l,key:`${e}[${m}]`,fnName:r,className:o})}),We(i.validate)&&i.validate.call(this,t,e,r,o,this)}function tt(i={}){let{getRemoteId:t=()=>"",replaceArg:e,getKVReportKey:r,ignoreLog:o,ignoreErrorLog:s}=i;return xe((n,c)=>function(...l){var v,L,x;function m(M,B,ee){if(ee&&ee.includes(M))return"hided";if(e){let pe=e(...l);if(l[pe.argIndex]===B)return pe.value}if(B===l||M in l)return B;try{return B instanceof HTMLElement?`id: ${B.id} type:${ct(B)}`:B instanceof MediaStreamTrack?vc(B):(JSON.stringify(B),B)}catch(pe){return`type:${ct(B)}`}}let E=this._log||$;if(o!=null&&o(...l))return n.apply(this,l);l.length>0?E.info(`${c}() ${JSON.stringify(l,(M,B)=>m(M,B,["userSig","privateMapKey"]))}`):E.info(`${c}()`);let g=r?r(...l):od[c],_=(s==null?void 0:s(...l))||!1;try{let M=n.apply(this,l),B=Ie();if(qi(M)){let ee=`${c.includes("Plugin")?`${((L=(v=l[0]).getName)==null?void 0:L.call(v))||""} `:" "}`;return M.then(pe=>(E.info(`${c}() success ${ee}${t.call(this,...l)}`),Q.addSuccessEvent({key:g,cost:Ie()-B}),pe)).catch(pe=>{var X;pe=ne.convertFrom.call(this,pe,c,l.length===1?l[0]:l);let ae=pe.extraCode||pe.code,Xe=(X=pe.message)!=null&&X.includes(ae)?"":` code:${ae}`;throw _||E.error(`${c}() failed ${ee}${t.call(this,...l)} ${pe}${Xe} params: ${JSON.stringify(l,m)}`),Q.addFailedEvent({key:g,error:pe}),pe})}return Q.addSuccessEvent({key:g}),M}catch(M){M=ne.convertFrom.call(this,M,c);let B=M.extraCode||M.code,ee=(x=M.message)!=null&&x.includes(B)?"":` code:${B}`;throw _||E.error(`${c}() failed ${M}${ee} params: ${JSON.stringify(l,m)}`),Q.addFailedEvent({key:g,error:M}),M}})}var cu=i=>xe((t,e)=>function(r,o){return A(this,null,function*(){let s=this._plugins.get(r);if(!s)throw this._log.error(`plugin ${String(r)} is not found`),new ne({code:le.OPERATION_ABORT,message:`plugin ${String(r)} is not found`,fnName:e});if(We(s.constructor.isSupported)&&!s.constructor.isSupported())throw this._log.error(`plugin ${String(r)} is not supported`),new ne({code:le.ENV_NOT_SUPPORTED,message:`plugin ${String(r)} is not supported`,extraCode:5210,fnName:e});return au.call(this,s.getValidateRule(i),[o],e,"TRTC"),t.call(this,s,o)})});var du=0,gp,vi=class vi{constructor(t){this.core=t;u(this,"log");u(this,"customAudioReferenceMap",new Map);u(this,"audioRefId",0);u(this,"audioContext",ze());u(this,"localAudioWorkletNode");u(this,"screenAudioWorkletNode");u(this,"mixNode");u(this,"silentNode");du=du+1,this.log=t.log.createChild({id:`${this.getAlias()}${du}`}),this.log.info(`created id=${this.getAlias()}${du}`)}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:le.INVALID_OPERATION,extraCode:5106,fnName:o})}}}preload(t){return gp||(gp=this.doPreload(t)),gp}doPreload(t){return A(this,null,function*(){let e=yield this.core.fileDownloader.download(t,{type:"blob"}),r=URL.createObjectURL(e);try{yield _i(this.audioContext,r)}catch(o){this.log.error(`preload audioProcessor failed. ${o}`)}finally{URL.revokeObjectURL(r)}})}getName(){return vi.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(t){switch(t){case"start":return vi.getStartValidateRule(this.core);case"update":return vi.updateValidateRule;case"stop":return vi.stopValidateRule}}start(t){return A(this,null,function*(){let{room:e}=this.core,{sdkAppId:r,userId:o,assetsPath:s=this.core.assetsPath,audioReference:n,processLevel:c,enableDump:l,isLocalAudioNeedAudioProcess:m=!0,isScreenAudioNeedAudioProcess:E=!0}=t;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=m,this.core.room.audioManager.isScreenAudioNeedAudioProcess=E,!s)throw new ne({code:le.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(yield this.preload(`${s}/audioProcessor-wasm.js`),!this.localAudioWorkletNode||!this.screenAudioWorkletNode){let g=String(Date.now()).slice(0,-3),{auth:_,sign:v,status:L,message:x}=yield ES(Te(z({},t),{timestamp:g}));if(!_)throw this.log.info(`audioProcessor: ${o} auth result: ${_}. Message: ${x}`),new ne({code:le.INVALID_PARAMETER,message:x});this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",r,o,g,v,L,e),this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",r,o,g,v,L,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.port.postMessage({type:"enable"}),this.screenAudioWorkletNode.port.postMessage({type:"enable"}),e.audioManager.addAudioProcessor(this.localAudioWorkletNode,this.mixNode,this.silentNode,this.screenAudioWorkletNode),P(n)||n.forEach(g=>{this.customAudioReferenceMap.set(g,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:g,refId:`o-${this.audioRefId++}`})}),P(c)||this.localAudioWorkletNode.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:c}}),P(l)||this.localAudioWorkletNode.port.postMessage({type:"dump",data:{enable:l}})})}update(t){return A(this,null,function*(){if(!this.localAudioWorkletNode||!this.screenAudioWorkletNode)return;let{audioReference:e,enableDump:r,processLevel:o}=t;P(e)||(this.customAudioReferenceMap.forEach((s,n)=>{this.customAudioReferenceMap.delete(n),this.core.room.audioManager.updateAudioReference({type:"remove",refId:s})}),e.forEach(s=>{this.customAudioReferenceMap.set(s,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:s,refId:`o-${this.audioRefId++}`})})),P(o)||this.localAudioWorkletNode.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:o}}),P(r)||(this.localAudioWorkletNode.port.postMessage({type:"dump",data:{enable:r}}),this.screenAudioWorkletNode.port.postMessage({type:"dump",data:{enable:r}}))})}stop(){return A(this,null,function*(){if(!this.localAudioWorkletNode||!this.mixNode||!this.silentNode||!this.screenAudioWorkletNode)return;let{room:t}=this.core;this.localAudioWorkletNode.port.postMessage({type:"disable"}),this.screenAudioWorkletNode.port.postMessage({type:"disable"}),yield t.audioManager.removeAudioProcessor(this.localAudioWorkletNode,this.mixNode,this.silentNode,this.screenAudioWorkletNode)})}destroy(){this.localAudioWorkletNode&&(this.localAudioWorkletNode.port.onmessage=null),this.screenAudioWorkletNode&&(this.screenAudioWorkletNode.port.onmessage=null)}initWorkletNode(t,e,r,o,s,n,c,l){t.port.postMessage({type:"init",data:{sdkAppId:String(r),userId:o,timestamp:s,sign:n,status:c}}),t.port.onmessage=m=>{var g;let{data:E}=m;switch(E.type){case"cost":let _=(E==null?void 0:E.value)>10?"info":"debug";this.log[_](`[${e}] avg cost: ${E.value} max: ${E==null?void 0:E.max}(${Ss(new Date(E==null?void 0:E.maxCostTimestamp))}) hist: ${(g=E==null?void 0:E.hist)==null?void 0:g.join(" ")}`);return;case"log":this.log[E.logLevel](`[${e}] ${E.value}`);return;case"dump":V.emit("265",{room:l,data:E.value,type:e==="localAudio"?"dump":"dump-screen-audio"});return}}}};u(vi,"updateValidateRule",{type:"object"}),u(vi,"stopValidateRule",{type:"object"}),u(vi,"Name","AudioProcessor");var uu=vi;function gS(i,t=N.MAIN){return`https://${Jr[t]||su(i,t)}/api/v1/audioAiAuth`}function ES(o){return A(this,arguments,function*({sdkAppId:i,userId:t,userSig:e,timestamp:r}){let n=`${gS(i)}?sdkAppId=${i}&userId=${t}&userSig=${e}×tamp=${r}`,c=yield fetch(n),{data:{errCode:l,errMsg:m,sign:E,status:g}}=yield c.json();if(g==="1")return{auth:!0,sign:E,status:g,message:m};let _=ii(i)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",v="Init RTCAudioProcessor failed.",L="";switch(l){case 1:L="Please check your params.";break;case 2:L=`You need to buy packages. Refer to: ${_}`;break;case 3:L="Server is invalid. Please contact our engineer. ";break;case 4:L=`Your packages is not active. Refer to: ${_}`;break;case 5:L=`Your packages is expired. Refer to: ${_}`;break;case 6:L="Your version is not supported.";break}return{auth:!1,status:g,message:m?`${v} Reason: ${m}. ${L}`:`${v}, ${L}`}})}var lu=0,Ep=class{constructor(t,e){u(this,"player");u(this,"publisher");u(this,"mixInput");this.mixInput=new Xs(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&&(P(t.volume)||(this.volume=t.volume),P(t.loop)||(this.loop=t.loop),P(t.playbackRate)||(this.playbackRate=t.playbackRate))}updateListener(t){if(this.player){if(t.onDurationChange){let{onDurationChange:e}=t;this.player.ondurationchange=r=>{e(r.target.duration)}}if(t.onTimeUpdate){let e=t.onTimeUpdate,{player:r}=this;r.ontimeupdate=()=>{e(r.currentTime,r.duration)}}t.onEnded&&(this.player.onended=t.onEnded)}}reset(){this.seek(0),this.mixInput.connect()}seek(t){this.player&&(t<0&&t>this.player.duration||(this.player.currentTime=t,this.publisher.currentTime=t))}play(){var t,e;return(t=this.publisher)==null||t.play(),(e=this.player)==null?void 0:e.play()}pause(){var t,e;(t=this.player)==null||t.pause(),(e=this.publisher)==null||e.pause()}stop(){var t;(t=this.player)==null||t.pause(),this.mixInput.disconnect()}setOperation(t){t==="pause"&&this.pause(),t==="resume"&&(this.pause(),this.play()),t==="stop"&&(this.pause(),this.seek(0))}set volume(t){!this.player||!this.publisher||(this.player.volume=t,this.publisher.volume=t)}set loop(t){!this.player||!this.publisher||(this.player.loop=t,this.publisher.loop=t)}set playbackRate(t){!this.player||!this.publisher||(this.player.playbackRate=t,this.publisher.playbackRate=t)}};function dn(i,t){if(t&&typeof t!="function")throw new ne({code:le.INVALID_PARAMETER,message:`start audioMixer plugin: param ${i} should be a function.`})}var zr=class zr{constructor(t){this.core=t;u(this,"log");u(this,"mixedMusicMap",new Map);u(this,"cacheMusicMap",new Map);lu=lu+1,this.log=t.log.createChild({id:`${this.getAlias()}${lu}`}),this.log.info(`created id=${this.getAlias()}${lu}`)}getName(){return zr.Name}getAlias(){return"ax"}getGroup(t){return t==null?void 0:t.id}getValidateRule(t){switch(t){case"start":return zr.startValidateRule;case"update":return zr.updateValidateRule;case"stop":return zr.stopValidateRule}}start(t){return A(this,null,function*(){let{room:e}=this.core;this.log.info(`add music source, id: ${t.id} url: ${t.url}, track: ${t.track}`);let{id:r,url:o}=t;if(this.mixedMusicMap.has(r))return;let s=this.cacheMusicMap.get(r);s?t.url?s.reset():(s.mixInput.replaceSource(t.track),s.mixInput.connect()):(s=new Ep(t,e.audioManager),this.cacheMusicMap.set(r,s)),s.updateListener(t),s.updateSettings(t),yield s.play(),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.`),Q.addEnum({key:502700,value:3}),this.kvUpload(t)})}update(t){return A(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),P(r)||n.setOperation(r),P(o)||n.seek(o),this.kvUpload(t)})}stop(e){return A(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:c,onTimeUpdate:l,onDurationChange:m,onEnded:E}=t;e&&Q.addCount({key:502711}),r&&Q.addCount({key:502703}),o&&Q.addCount({key:502704}),s&&Q.addCount({key:502705}),n&&Q.addCount({key:502706}),c&&Q.addCount({key:502707}),typeof l!="function"&&Q.addCount({key:502709}),typeof E!="function"&&Q.addCount({key:502710}),typeof m!="function"&&Q.addCount({key:502708})}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()}};u(zr,"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(),c=s.indexOf(n)>=0,l=o.startsWith("blob"),m=o.startsWith("data");if(!(c||l||m))throw new ne({code:le.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:le.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:r});dn("onTimeUpdate",t.onTimeUpdate),dn("onEnded",t.onEnded),dn("onDurationChange",t.onDurationChange)}}),u(zr,"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){dn("onTimeUpdate",t.onTimeUpdate),dn("onEnded",t.onEnded),dn("onDurationChange",t.onDurationChange)}}),u(zr,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),u(zr,"Name","AudioMixer");var mu=zr;var pu=0,_p,Ci=class Ci{constructor(t){this.core=t;u(this,"log");u(this,"audioContext",ze("denoiser"));u(this,"workletNode");pu=pu+1,this.log=t.log.createChild({id:`${this.getAlias()}${pu}`}),this.log.info(`created id=${this.getAlias()}${pu}`)}static startValidateRule(t){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,r,o,s){if(!t.room.audioManager.hasAudioTrack)throw new ne({code:le.INVALID_OPERATION,extraCode:5106,fnName:o})}}}preload(t){return _p||(_p=this.doPreload(t)),_p}doPreload(t){return A(this,null,function*(){let e=yield this.core.fileDownloader.download(t,{type:"blob"}),r=URL.createObjectURL(e);try{yield _i(this.audioContext,r)}catch(o){throw this.log.error("load worklet failed",o),o}finally{URL.revokeObjectURL(r)}})}getName(){return Ci.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(t){switch(t){case"start":return Ci.startValidateRule(this.core);case"update":return Ci.updateValidateRule;case"stop":return Ci.stopValidateRule}}start(t){return A(this,null,function*(){let{room:e,schedule:r}=this.core,{assetsPath:o=this.core.assetsPath}=t;if(!o)throw new ne({code:le.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(yield this.preload(`${o}/denoiser-wasm.js`),!this.workletNode){let s=String(Date.now()).slice(0,-3),{auth:n,sign:c,status:l,message:m}=yield TS(r,Te(z({},t),{timestamp:s}));if(!n)throw this.log.info(`RTCAIDenoiser: ${t.userId} auth result: ${n}. Message: ${m}`),new ne({code:le.INVALID_PARAMETER,message:m});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:c,status:l}}),this.workletNode.port.onmessage=E=>{var _;let{data:g}=E;if(g.type==="cost"){let v=(g==null?void 0:g.max)>20?"warn":(g==null?void 0:g.max)>10?"info":"debug";this.log[v](`avg cost: ${g.value} max: ${g==null?void 0:g.max}(${Ss(new Date(g==null?void 0:g.maxCostTimestamp))}) hist: ${(_=g==null?void 0:g.hist)==null?void 0:_.join(" ")}`)}else g.type==="log"&&this.log[g.logLevel](`${g.value}`)}}this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(){return A(this,null,function*(){})}stop(){return A(this,null,function*(){if(!this.workletNode)return;let{room:t}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield t.audioManager.removeDenoiser(this.workletNode)})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};u(Ci,"updateValidateRule",{type:"object"}),u(Ci,"stopValidateRule",{type:"object"}),u(Ci,"Name","AIDenoiser");var hu=Ci;function TS(s,n){return A(this,arguments,function*(i,{sdkAppId:t,userId:e,userSig:r,timestamp:o}){try{let{data:{errCode:c,errMsg:l,sign:m,status:E}}=yield i.getAbilityConfig(t,i.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:t,userId:e,userSig:r,timestamp:o});if(E==="1")return{auth:!0,sign:m,status:E,message:l};let g=ii(t)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",_="Init RTCAIDenoiser failed.",v="";switch(c){case 1:v="Please check your params.";break;case 2:v=`You need to buy packages. Refer to: ${g}`;break;case 3:v="Server is invalid. Please contact our engineer. ";break;case 4:v=`Your packages is not active. Refer to: ${g}`;break;case 5:v=`Your packages is expired. Refer to: ${g}`;break;case 6:v="Your version is not supported.";break}return{auth:!1,status:E,message:l?`${_} Reason: ${l}. ${v}`:`${_}, ${v}`}}catch(c){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${c}`}}})}var wg=Gi(Zi(),1);var Tp=class extends wg.EventEmitter{constructor(){super();u(this,"observer");u(this,"state","nominal");this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return A(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!mt&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){je.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let r=this.stateNum,o=e[e.length-1];this.state=o.state,(this.stateNum>3||r>3)&&$.info(`${o.source}: ${o.state}`),this.emit("state-changed",{type:o.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(r){je.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:r})}}},IS=new Tp,Ip=IS;function SS([i,t]){let e=t.byteLength,r=parseInt(String(e/255),10),o=e%255,s=[];s.push(0,0,0,1,6,i);for(let c=0;c<r;c++)s.push(255);s.push(o);let n=new DataView(t);return s.push(...new Uint8Array(n.buffer)),s.push(128),new Yo(new DataView(new Uint8Array(s).buffer),!0)}function AS(i){return i.type==="empty"||i.data.byteLength===0}function yS(i){return i.getInt32(0)===1&&i.getInt8(4)===6}function bS(i){let t=0,e=0,r=new DataView(i);for(let o=0;o<i.byteLength;o++)switch(r.getUint8(o)){case 0:t++;break;case 1:(t===2||t===3)&&e++,t=0;break;default:t=0;break}return e}function Sp({frame:i,seiMessageList:t}){if(!t||t.length===0||i.data.byteLength===0)return i;let r=9-bS(i.data);if(r<=0)return i;let o=t.splice(0,r).reverse().map(SS),s=o.reduce((E,g)=>E+g.dataView.byteLength,0),n=new ArrayBuffer(s+i.data.byteLength),c=new DataView(n),l=new DataView(i.data),m=0;for(let E=0;E<o.length;E++)for(let g=0;g<o[E].dataView.byteLength;g++)c.setInt8(m++,o[E].dataView.getInt8(g));for(let E=0;E<i.data.byteLength;E++)c.setInt8(m++,l.getInt8(E));return i.data=n,i}function Ap({frame:i,onSEI:t}){try{let e=new DataView(i.data);if(AS(i)||!yS(e))return i;let r=[],o=0,s=-1,n=-1;for(let c=0;c<i.data.byteLength;c++){let l=e.getUint8(c);if(l===0)o++;else if(l===1){if(o===2||o===3){let m=c-o;if(s===-1?s=m:n===-1&&(n=m,r.push(new Yo(new DataView(e.buffer.slice(s,n)))),s=m,n=-1),!(e.getUint8(c+1)===6)){i.data=e.buffer.slice(m);break}}o=0}else o=0}t==null||t(r.reverse())}catch(e){}return i}var yp=0,ka=class ka{constructor(t){this.core=t;u(this,"log");u(this,"_seiMessageList",[]);u(this,"_smallSeiMessageList",[]);u(this,"_subStreamSeiMessageList",[]);yp++,this.log=t.log.createChild({id:`${this.getAlias()}${yp}`}),this.log.info(`[sei] created id=${this.getAlias()}${yp}`),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 Sp({frame:t,seiMessageList:r})}catch(r){this.log.warn(r)}return t}decode({frame:t,track:e}){return Ap({frame:t,onSEI:r=>{r.forEach(o=>{this.core.trtc.emit(re.SEI_MESSAGE,{seiPayloadType:o.seiPayloadType,data:o.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"})})}})}destroy(){this.log.debug("destory"),this.stop(),delete this.core}getValidateRule(t){switch(t){case"start":return{type:"object"};case"update":return{type:"object"};case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:da?this.encode:Sp,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:da?this.decode:Ap,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 ka.Name}getAlias(){return"sei"}getGroup(){return"sei"}};u(ka,"autoStart",!0),u(ka,"Name","SEI");var fu=ka;function bp({frame:i,onDump:t}){return t==null||t(),i}function Rp({frame:i,onDump:t}){return t==null||t(),i}var Og={"play() error: NotAllowedError:":{tips:i=>i.includes("main <video>")||i.includes("main <audio>")?"Remote stream auto play is restricted and playback fails":"Local stream playback failure, generally only occurs in Android WeChat devices, no need to handle",color:"red",class:"red"},"updateStream() try to recover local stream":{tips:"Device acquisition exception, automatic recovery is in progress"},"updateStream() recover local stream successfully":{tips:"Device acquisition exception, automatic recovery is successful"},"updateStream() failed to recover local stream":{tips:"Device acquisition exception, automatic recovery failed"},"main stream - video track is muted":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is muted":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is muted":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unable to provide media output":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is unable to provide media output":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is unable to provide media output":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unmuted":{tips:"Received enough playback video data"},"main stream - audio track is unmuted":{tips:"Received enough playback audio data"},"auxiliary stream - video track is unmuted":{tips:"Received enough playback screen sharing data"},"main stream - audio player track is ended":{tips:"Remote audio track stopped"},"main stream - video player track is ended":{tips:"Remote video track stopped"},"auxiliary stream - video player track is ended":{tips:"Received enough playback screen sharing data"},"stream - video track is muted":{tips:"Camera capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"stream - video track is unable to provide media output":{tips:"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked, and the customer needs to re-acquire. SDK v4.11.4+ will automatically resume acquisition without customer intervention",color:"orange"},"video track is unable to provide media output":{tips:i=>i.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"stream - audio track is muted":{tips:"Microphone capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"audio track is unable to provide media output":{tips:i=>i.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"Microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio track is unable to provide media output":{tips:"The microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"is adding audio track to current published local stream":{tips:"add audio track",color:"orange"},"is removing audio track from current published local stream":{tips:"remove audio track",color:"orange"},"is removing video track from current published local stream":{tips:"remove video track",color:"orange"},"is adding video track to current published local stream":{tips:"add video track",color:"orange"},"is replacing audio track to current published local main stream":{tips:"replace audio track",color:"orange"},"is replacing video track to current published local main stream":{tips:"replace video track",color:"orange"},"downlink network quality change":{tips:"Downstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"uplink network quality change":{tips:"Upstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"localStream mute video":{tips:"mute upstream video stream",color:"orange"},"localStream unmute video":{tips:"unmute upstream video stream",color:"orange"},"localStream mute audio":{tips:"mute upstream audio stream",color:"orange"},"localStream unmute audio":{tips:"unmute upstream audio stream",color:"orange"},"black detected":{tips:"Detect black screen, which means fps = 0. It is usually caused by network, and the network will be recovered after a while. If the network is normal but has not been restored, it is an abnormal situation."},'main stream start to play with options: {"muted":true}':{tips:"Play the remote stream in silent mode. Generally, the remote stream does not need to be played in silent mode. You need to confirm whether the parameters passed in the client stream.play API call are correct.",color:"orange"},"main stream - audio player is starting playing":{tips:"Remote stream audio playback success",color:"#0dd90d",class:"success"},"main stream - video player is starting playing":{tips:"Remote stream video playback success",color:"#0dd90d",class:"success"},"video player is playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"audio player is playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"stream - video player is starting playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"stream - audio player is starting playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"switch camera success":{tips:"Switch camera success",color:"#0dd90d",class:"success"},"switch microphone success":{tips:"Switch microphone success",color:"#0dd90d",class:"success"},gotStream:{tips:"Local stream capture success"},"local stream is published successfully":{tips:"Publish success",color:"#0dd90d",class:"success"},"encoderImplementation change to OpenH264":{tips:"Use software encoding"},"encoderImplementation change to ExternalEncoder":{tips:"Use hardware encoding"},"getUserMedia with constraints":{tips:"Start media (camera/microphone) capture"},"getDisplayMedia with constraints":{tips:"Start screen sharing capture"},"client-banned":{tips:"Kicked out of the room",color:"red",class:"red",textColor:"#fff"},user_timeout:{tips:"The backend is too long without receiving SDK heartbeat, which is usually caused by the JS thread being blocked for a long time. If the reproduction probability is high, the application browser Performance tool analyzes where the JS thread is blocked.",color:"red",class:"red",textColor:"#fff"},"schedule failed":{tips:"Signaling request failed, does not affect the normal room entry process, SDK will connect to the default signaling domain."},"updateStream() video flag is true, but no camera detected, set video to false":{tips:"When trying to resume camera acquisition, the camera acquisition is not resumed because it is detected that there is no camera.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to bandwidth":{tips:"bandwidth estimation is not enough to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to cpu":{tips:"cpu load is too high to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: hidden":{tips:"User page switched to backend, in mobile devices, this will cause the device to pause the capture, and it will be restored when the user switches backend to the frontend.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: visible":{tips:"User page switched to frontend",color:"orange",class:"orange",textColor:"#fff"},"main stream - audio player is paused":{tips:`The remote stream audio playback is paused, which usually has two possibilities:
|
|
97
|
+
${o.stack}`),!1}},i};var cn=new WeakMap;function Rg(i){let t=cn.get(i);t&&(t.forEach(e=>clearTimeout(e)),cn.delete(i))}function vg(i,t){return xe((e,r)=>function(...o){let s=cn.get(this);s||(s=new Map,cn.set(this,s));let n=t(...o),c=s.get(n);if(!c||c<=0){e.apply(this,o);let l=setTimeout(()=>{var m;(m=cn.get(this))==null||m.delete(n)},i);s.set(n,l)}else{clearTimeout(c);let l=window.setTimeout(()=>{var m;e.apply(this,o),(m=cn.get(this))==null||m.delete(n)},i);s.set(n,l)}})}var Ng="trtc-sdk-v5",Dg="5.11.1-wasm.2";function Mt(...i){return xe((t,e)=>function(...r){try{au.call(this,i,r,e,this._name)}catch(o){return Promise.reject(o)}return t.apply(this,r)})}function fp(...i){return xe((t,e)=>function(...r){try{au.call(this,i,r,e,this._name)}catch(o){throw o}return t.apply(this,r)})}function au(i,t,e,r){if(ot(i))for(let o=0;o<i.length;o++)nu.call(this,{rule:i[o],value:t[o],key:i[o].name,fnName:e,className:r});else nu.call(this,{rule:i,value:t[0],key:i.name,fnName:e,className:r})}function nu({rule:i,value:t,key:e,fnName:r,className:o}){function s(l){return{code:le.INVALID_PARAMETER,extraCode:l,fnName:r,messageParams:{key:e,rule:i,value:t}}}if(P(t)){if(i.required)throw new ne(s(5001));if(P(i.defaultValue)){We(i.validate)&&i.validate.call(this,t,e,r,o,this);return}t=i.defaultValue}if(Array.isArray(i.type)){let l=!1;for(let m=0;m<i.type.length;m++)i.type[m]===null&&t===null&&(l=!0),We(i.type[m])&&t instanceof i.type[m]&&(l=!0),Oe(i.type[m])&&ct(t)===i.type[m].toLowerCase()&&(l=!0);if(!l)throw new ne({code:le.INVALID_PARAMETER,extraCode:5002,fnName:r,messageParams:{key:e,rule:{type:i.type.map(m=>Lo(m)?vs(m):Oe(m)?m:ct(m))},value:t}})}else if(!P(i.type)&&ct(t)!==i.type)throw new ne(s(5002));if(i.allowEmpty===!1){let l=ke(t)&&(t===0||Number.isNaN(t)),m=Oe(t)&&t.trim()==="";if(l||m)throw new ne(s(5003))}if(i.notLessThanZero&&ke(t)&&t<0)throw new ne(s(5006));if(!P(i.min)&&ke(t)&&t<i.min)throw new ne(s(5007));if(!P(i.max)&&ke(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(We(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;Lt(n)&&Ir(t)&&Object.keys(n).forEach(l=>{nu.call(this,{rule:n[l],value:t&&t[l],key:`${l}`,fnName:r,className:o})});let{arrayItem:c}=i;Lt(c)&&ot(t)&&t.forEach((l,m)=>{nu.call(this,{rule:c,value:l,key:`${e}[${m}]`,fnName:r,className:o})}),We(i.validate)&&i.validate.call(this,t,e,r,o,this)}function tt(i={}){let{getRemoteId:t=()=>"",replaceArg:e,getKVReportKey:r,ignoreLog:o,ignoreErrorLog:s}=i;return xe((n,c)=>function(...l){var v,L,x;function m(M,B,ee){if(ee&&ee.includes(M))return"hided";if(e){let pe=e(...l);if(l[pe.argIndex]===B)return pe.value}if(B===l||M in l)return B;try{return B instanceof HTMLElement?`id: ${B.id} type:${ct(B)}`:B instanceof MediaStreamTrack?vc(B):(JSON.stringify(B),B)}catch(pe){return`type:${ct(B)}`}}let E=this._log||$;if(o!=null&&o(...l))return n.apply(this,l);l.length>0?E.info(`${c}() ${JSON.stringify(l,(M,B)=>m(M,B,["userSig","privateMapKey"]))}`):E.info(`${c}()`);let g=r?r(...l):od[c],_=(s==null?void 0:s(...l))||!1;try{let M=n.apply(this,l),B=Ie();if(qi(M)){let ee=`${c.includes("Plugin")?`${((L=(v=l[0]).getName)==null?void 0:L.call(v))||""} `:" "}`;return M.then(pe=>(E.info(`${c}() success ${ee}${t.call(this,...l)}`),Q.addSuccessEvent({key:g,cost:Ie()-B}),pe)).catch(pe=>{var X;pe=ne.convertFrom.call(this,pe,c,l.length===1?l[0]:l);let ae=pe.extraCode||pe.code,Xe=(X=pe.message)!=null&&X.includes(ae)?"":` code:${ae}`;throw _||E.error(`${c}() failed ${ee}${t.call(this,...l)} ${pe}${Xe} params: ${JSON.stringify(l,m)}`),Q.addFailedEvent({key:g,error:pe}),pe})}return Q.addSuccessEvent({key:g}),M}catch(M){M=ne.convertFrom.call(this,M,c);let B=M.extraCode||M.code,ee=(x=M.message)!=null&&x.includes(B)?"":` code:${B}`;throw _||E.error(`${c}() failed ${M}${ee} params: ${JSON.stringify(l,m)}`),Q.addFailedEvent({key:g,error:M}),M}})}var cu=i=>xe((t,e)=>function(r,o){return A(this,null,function*(){let s=this._plugins.get(r);if(!s)throw this._log.error(`plugin ${String(r)} is not found`),new ne({code:le.OPERATION_ABORT,message:`plugin ${String(r)} is not found`,fnName:e});if(We(s.constructor.isSupported)&&!s.constructor.isSupported())throw this._log.error(`plugin ${String(r)} is not supported`),new ne({code:le.ENV_NOT_SUPPORTED,message:`plugin ${String(r)} is not supported`,extraCode:5210,fnName:e});return au.call(this,s.getValidateRule(i),[o],e,"TRTC"),t.call(this,s,o)})});var du=0,gp,vi=class vi{constructor(t){this.core=t;u(this,"log");u(this,"customAudioReferenceMap",new Map);u(this,"audioRefId",0);u(this,"audioContext",ze());u(this,"localAudioWorkletNode");u(this,"screenAudioWorkletNode");u(this,"mixNode");u(this,"silentNode");du=du+1,this.log=t.log.createChild({id:`${this.getAlias()}${du}`}),this.log.info(`created id=${this.getAlias()}${du}`)}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:le.INVALID_OPERATION,extraCode:5106,fnName:o})}}}preload(t){return gp||(gp=this.doPreload(t)),gp}doPreload(t){return A(this,null,function*(){let e=yield this.core.fileDownloader.download(t,{type:"blob"}),r=URL.createObjectURL(e);try{yield _i(this.audioContext,r)}catch(o){this.log.error(`preload audioProcessor failed. ${o}`)}finally{URL.revokeObjectURL(r)}})}getName(){return vi.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(t){switch(t){case"start":return vi.getStartValidateRule(this.core);case"update":return vi.updateValidateRule;case"stop":return vi.stopValidateRule}}start(t){return A(this,null,function*(){let{room:e}=this.core,{sdkAppId:r,userId:o,assetsPath:s=this.core.assetsPath,audioReference:n,processLevel:c,enableDump:l,isLocalAudioNeedAudioProcess:m=!0,isScreenAudioNeedAudioProcess:E=!0}=t;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=m,this.core.room.audioManager.isScreenAudioNeedAudioProcess=E,!s)throw new ne({code:le.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(yield this.preload(`${s}/audioProcessor-wasm.js`),!this.localAudioWorkletNode||!this.screenAudioWorkletNode){let g=String(Date.now()).slice(0,-3),{auth:_,sign:v,status:L,message:x}=yield ES(Te(z({},t),{timestamp:g}));if(!_)throw this.log.info(`audioProcessor: ${o} auth result: ${_}. Message: ${x}`),new ne({code:le.INVALID_PARAMETER,message:x});this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",r,o,g,v,L,e),this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",r,o,g,v,L,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.port.postMessage({type:"enable"}),this.screenAudioWorkletNode.port.postMessage({type:"enable"}),e.audioManager.addAudioProcessor(this.localAudioWorkletNode,this.mixNode,this.silentNode,this.screenAudioWorkletNode),P(n)||n.forEach(g=>{this.customAudioReferenceMap.set(g,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:g,refId:`o-${this.audioRefId++}`})}),P(c)||this.localAudioWorkletNode.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:c}}),P(l)||this.localAudioWorkletNode.port.postMessage({type:"dump",data:{enable:l}})})}update(t){return A(this,null,function*(){if(!this.localAudioWorkletNode||!this.screenAudioWorkletNode)return;let{audioReference:e,enableDump:r,processLevel:o}=t;P(e)||(this.customAudioReferenceMap.forEach((s,n)=>{this.customAudioReferenceMap.delete(n),this.core.room.audioManager.updateAudioReference({type:"remove",refId:s})}),e.forEach(s=>{this.customAudioReferenceMap.set(s,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:s,refId:`o-${this.audioRefId++}`})})),P(o)||this.localAudioWorkletNode.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:o}}),P(r)||(this.localAudioWorkletNode.port.postMessage({type:"dump",data:{enable:r}}),this.screenAudioWorkletNode.port.postMessage({type:"dump",data:{enable:r}}))})}stop(){return A(this,null,function*(){if(!this.localAudioWorkletNode||!this.mixNode||!this.silentNode||!this.screenAudioWorkletNode)return;let{room:t}=this.core;this.localAudioWorkletNode.port.postMessage({type:"disable"}),this.screenAudioWorkletNode.port.postMessage({type:"disable"}),yield t.audioManager.removeAudioProcessor(this.localAudioWorkletNode,this.mixNode,this.silentNode,this.screenAudioWorkletNode)})}destroy(){this.localAudioWorkletNode&&(this.localAudioWorkletNode.port.onmessage=null),this.screenAudioWorkletNode&&(this.screenAudioWorkletNode.port.onmessage=null)}initWorkletNode(t,e,r,o,s,n,c,l){t.port.postMessage({type:"init",data:{sdkAppId:String(r),userId:o,timestamp:s,sign:n,status:c}}),t.port.onmessage=m=>{var g;let{data:E}=m;switch(E.type){case"cost":let _=(E==null?void 0:E.value)>10?"info":"debug";this.log[_](`[${e}] avg cost: ${E.value} max: ${E==null?void 0:E.max}(${Ss(new Date(E==null?void 0:E.maxCostTimestamp))}) hist: ${(g=E==null?void 0:E.hist)==null?void 0:g.join(" ")}`);return;case"log":this.log[E.logLevel](`[${e}] ${E.value}`);return;case"dump":V.emit("265",{room:l,data:E.value,type:e==="localAudio"?"dump":"dump-screen-audio"});return}}}};u(vi,"updateValidateRule",{type:"object"}),u(vi,"stopValidateRule",{type:"object"}),u(vi,"Name","AudioProcessor");var uu=vi;function gS(i,t=N.MAIN){return`https://${Jr[t]||su(i,t)}/api/v1/audioAiAuth`}function ES(o){return A(this,arguments,function*({sdkAppId:i,userId:t,userSig:e,timestamp:r}){let n=`${gS(i)}?sdkAppId=${i}&userId=${t}&userSig=${e}×tamp=${r}`,c=yield fetch(n),{data:{errCode:l,errMsg:m,sign:E,status:g}}=yield c.json();if(g==="1")return{auth:!0,sign:E,status:g,message:m};let _=ii(i)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",v="Init RTCAudioProcessor failed.",L="";switch(l){case 1:L="Please check your params.";break;case 2:L=`You need to buy packages. Refer to: ${_}`;break;case 3:L="Server is invalid. Please contact our engineer. ";break;case 4:L=`Your packages is not active. Refer to: ${_}`;break;case 5:L=`Your packages is expired. Refer to: ${_}`;break;case 6:L="Your version is not supported.";break}return{auth:!1,status:g,message:m?`${v} Reason: ${m}. ${L}`:`${v}, ${L}`}})}var lu=0,Ep=class{constructor(t,e){u(this,"player");u(this,"publisher");u(this,"mixInput");this.mixInput=new Xs(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&&(P(t.volume)||(this.volume=t.volume),P(t.loop)||(this.loop=t.loop),P(t.playbackRate)||(this.playbackRate=t.playbackRate))}updateListener(t){if(this.player){if(t.onDurationChange){let{onDurationChange:e}=t;this.player.ondurationchange=r=>{e(r.target.duration)}}if(t.onTimeUpdate){let e=t.onTimeUpdate,{player:r}=this;r.ontimeupdate=()=>{e(r.currentTime,r.duration)}}t.onEnded&&(this.player.onended=t.onEnded)}}reset(){this.seek(0),this.mixInput.connect()}seek(t){this.player&&(t<0&&t>this.player.duration||(this.player.currentTime=t,this.publisher.currentTime=t))}play(){var t,e;return(t=this.publisher)==null||t.play(),(e=this.player)==null?void 0:e.play()}pause(){var t,e;(t=this.player)==null||t.pause(),(e=this.publisher)==null||e.pause()}stop(){var t;(t=this.player)==null||t.pause(),this.mixInput.disconnect()}setOperation(t){t==="pause"&&this.pause(),t==="resume"&&(this.pause(),this.play()),t==="stop"&&(this.pause(),this.seek(0))}set volume(t){!this.player||!this.publisher||(this.player.volume=t,this.publisher.volume=t)}set loop(t){!this.player||!this.publisher||(this.player.loop=t,this.publisher.loop=t)}set playbackRate(t){!this.player||!this.publisher||(this.player.playbackRate=t,this.publisher.playbackRate=t)}};function dn(i,t){if(t&&typeof t!="function")throw new ne({code:le.INVALID_PARAMETER,message:`start audioMixer plugin: param ${i} should be a function.`})}var zr=class zr{constructor(t){this.core=t;u(this,"log");u(this,"mixedMusicMap",new Map);u(this,"cacheMusicMap",new Map);lu=lu+1,this.log=t.log.createChild({id:`${this.getAlias()}${lu}`}),this.log.info(`created id=${this.getAlias()}${lu}`)}getName(){return zr.Name}getAlias(){return"ax"}getGroup(t){return t==null?void 0:t.id}getValidateRule(t){switch(t){case"start":return zr.startValidateRule;case"update":return zr.updateValidateRule;case"stop":return zr.stopValidateRule}}start(t){return A(this,null,function*(){let{room:e}=this.core;this.log.info(`add music source, id: ${t.id} url: ${t.url}, track: ${t.track}`);let{id:r,url:o}=t;if(this.mixedMusicMap.has(r))return;let s=this.cacheMusicMap.get(r);s?t.url?s.reset():(s.mixInput.replaceSource(t.track),s.mixInput.connect()):(s=new Ep(t,e.audioManager),this.cacheMusicMap.set(r,s)),s.updateListener(t),s.updateSettings(t),yield s.play(),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.`),Q.addEnum({key:502700,value:3}),this.kvUpload(t)})}update(t){return A(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),P(r)||n.setOperation(r),P(o)||n.seek(o),this.kvUpload(t)})}stop(e){return A(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:c,onTimeUpdate:l,onDurationChange:m,onEnded:E}=t;e&&Q.addCount({key:502711}),r&&Q.addCount({key:502703}),o&&Q.addCount({key:502704}),s&&Q.addCount({key:502705}),n&&Q.addCount({key:502706}),c&&Q.addCount({key:502707}),typeof l!="function"&&Q.addCount({key:502709}),typeof E!="function"&&Q.addCount({key:502710}),typeof m!="function"&&Q.addCount({key:502708})}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()}};u(zr,"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(),c=s.indexOf(n)>=0,l=o.startsWith("blob"),m=o.startsWith("data");if(!(c||l||m))throw new ne({code:le.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:le.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:r});dn("onTimeUpdate",t.onTimeUpdate),dn("onEnded",t.onEnded),dn("onDurationChange",t.onDurationChange)}}),u(zr,"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){dn("onTimeUpdate",t.onTimeUpdate),dn("onEnded",t.onEnded),dn("onDurationChange",t.onDurationChange)}}),u(zr,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),u(zr,"Name","AudioMixer");var mu=zr;var pu=0,_p,Ci=class Ci{constructor(t){this.core=t;u(this,"log");u(this,"audioContext",ze("denoiser"));u(this,"workletNode");pu=pu+1,this.log=t.log.createChild({id:`${this.getAlias()}${pu}`}),this.log.info(`created id=${this.getAlias()}${pu}`)}static startValidateRule(t){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,r,o,s){if(!t.room.audioManager.hasAudioTrack)throw new ne({code:le.INVALID_OPERATION,extraCode:5106,fnName:o})}}}preload(t){return _p||(_p=this.doPreload(t)),_p}doPreload(t){return A(this,null,function*(){let e=yield this.core.fileDownloader.download(t,{type:"blob"}),r=URL.createObjectURL(e);try{yield _i(this.audioContext,r)}catch(o){throw this.log.error("load worklet failed",o),o}finally{URL.revokeObjectURL(r)}})}getName(){return Ci.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(t){switch(t){case"start":return Ci.startValidateRule(this.core);case"update":return Ci.updateValidateRule;case"stop":return Ci.stopValidateRule}}start(t){return A(this,null,function*(){let{room:e,schedule:r}=this.core,{assetsPath:o=this.core.assetsPath}=t;if(!o)throw new ne({code:le.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(yield this.preload(`${o}/denoiser-wasm.js`),!this.workletNode){let s=String(Date.now()).slice(0,-3),{auth:n,sign:c,status:l,message:m}=yield TS(r,Te(z({},t),{timestamp:s}));if(!n)throw this.log.info(`RTCAIDenoiser: ${t.userId} auth result: ${n}. Message: ${m}`),new ne({code:le.INVALID_PARAMETER,message:m});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:c,status:l}}),this.workletNode.port.onmessage=E=>{var _;let{data:g}=E;if(g.type==="cost"){let v=(g==null?void 0:g.max)>20?"warn":(g==null?void 0:g.max)>10?"info":"debug";this.log[v](`avg cost: ${g.value} max: ${g==null?void 0:g.max}(${Ss(new Date(g==null?void 0:g.maxCostTimestamp))}) hist: ${(_=g==null?void 0:g.hist)==null?void 0:_.join(" ")}`)}else g.type==="log"&&this.log[g.logLevel](`${g.value}`)}}this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(){return A(this,null,function*(){})}stop(){return A(this,null,function*(){if(!this.workletNode)return;let{room:t}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield t.audioManager.removeDenoiser(this.workletNode)})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};u(Ci,"updateValidateRule",{type:"object"}),u(Ci,"stopValidateRule",{type:"object"}),u(Ci,"Name","AIDenoiser");var hu=Ci;function TS(s,n){return A(this,arguments,function*(i,{sdkAppId:t,userId:e,userSig:r,timestamp:o}){try{let{data:{errCode:c,errMsg:l,sign:m,status:E}}=yield i.getAbilityConfig(t,i.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:t,userId:e,userSig:r,timestamp:o});if(E==="1")return{auth:!0,sign:m,status:E,message:l};let g=ii(t)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",_="Init RTCAIDenoiser failed.",v="";switch(c){case 1:v="Please check your params.";break;case 2:v=`You need to buy packages. Refer to: ${g}`;break;case 3:v="Server is invalid. Please contact our engineer. ";break;case 4:v=`Your packages is not active. Refer to: ${g}`;break;case 5:v=`Your packages is expired. Refer to: ${g}`;break;case 6:v="Your version is not supported.";break}return{auth:!1,status:E,message:l?`${_} Reason: ${l}. ${v}`:`${_}, ${v}`}}catch(c){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${c}`}}})}var wg=Gi(Zi(),1);var Tp=class extends wg.EventEmitter{constructor(){super();u(this,"observer");u(this,"state","nominal");this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return A(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!mt&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){je.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let r=this.stateNum,o=e[e.length-1];this.state=o.state,(this.stateNum>3||r>3)&&$.info(`${o.source}: ${o.state}`),this.emit("state-changed",{type:o.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(r){je.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:r})}}},IS=new Tp,Ip=IS;function SS([i,t]){let e=t.byteLength,r=parseInt(String(e/255),10),o=e%255,s=[];s.push(0,0,0,1,6,i);for(let c=0;c<r;c++)s.push(255);s.push(o);let n=new DataView(t);return s.push(...new Uint8Array(n.buffer)),s.push(128),new Yo(new DataView(new Uint8Array(s).buffer),!0)}function AS(i){return i.type==="empty"||i.data.byteLength===0}function yS(i){return i.getInt32(0)===1&&i.getInt8(4)===6}function bS(i){let t=0,e=0,r=new DataView(i);for(let o=0;o<i.byteLength;o++)switch(r.getUint8(o)){case 0:t++;break;case 1:(t===2||t===3)&&e++,t=0;break;default:t=0;break}return e}function Sp({frame:i,seiMessageList:t}){if(!t||t.length===0||i.data.byteLength===0)return i;let r=9-bS(i.data);if(r<=0)return i;let o=t.splice(0,r).reverse().map(SS),s=o.reduce((E,g)=>E+g.dataView.byteLength,0),n=new ArrayBuffer(s+i.data.byteLength),c=new DataView(n),l=new DataView(i.data),m=0;for(let E=0;E<o.length;E++)for(let g=0;g<o[E].dataView.byteLength;g++)c.setInt8(m++,o[E].dataView.getInt8(g));for(let E=0;E<i.data.byteLength;E++)c.setInt8(m++,l.getInt8(E));return i.data=n,i}function Ap({frame:i,onSEI:t}){try{let e=new DataView(i.data);if(AS(i)||!yS(e))return i;let r=[],o=0,s=-1,n=-1;for(let c=0;c<i.data.byteLength;c++){let l=e.getUint8(c);if(l===0)o++;else if(l===1){if(o===2||o===3){let m=c-o;if(s===-1?s=m:n===-1&&(n=m,r.push(new Yo(new DataView(e.buffer.slice(s,n)))),s=m,n=-1),!(e.getUint8(c+1)===6)){i.data=e.buffer.slice(m);break}}o=0}else o=0}t==null||t(r.reverse())}catch(e){}return i}var yp=0,ka=class ka{constructor(t){this.core=t;u(this,"log");u(this,"_seiMessageList",[]);u(this,"_smallSeiMessageList",[]);u(this,"_subStreamSeiMessageList",[]);yp++,this.log=t.log.createChild({id:`${this.getAlias()}${yp}`}),this.log.info(`[sei] created id=${this.getAlias()}${yp}`),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 Sp({frame:t,seiMessageList:r})}catch(r){this.log.warn(r)}return t}decode({frame:t,track:e}){return Ap({frame:t,onSEI:r=>{r.forEach(o=>{this.core.trtc.emit(re.SEI_MESSAGE,{seiPayloadType:o.seiPayloadType,data:o.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"})})}})}destroy(){this.log.debug("destory"),this.stop(),delete this.core}getValidateRule(t){switch(t){case"start":return{type:"object"};case"update":return{type:"object"};case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:da?this.encode:Sp,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:da?this.decode:Ap,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 ka.Name}getAlias(){return"sei"}getGroup(){return"sei"}};u(ka,"autoStart",!0),u(ka,"Name","SEI");var fu=ka;function bp({frame:i,onDump:t}){return t==null||t(),i}function Rp({frame:i,onDump:t}){return t==null||t(),i}var Og={"play() error: NotAllowedError:":{tips:i=>i.includes("main <video>")||i.includes("main <audio>")?"Remote stream auto play is restricted and playback fails":"Local stream playback failure, generally only occurs in Android WeChat devices, no need to handle",color:"red",class:"red"},"updateStream() try to recover local stream":{tips:"Device acquisition exception, automatic recovery is in progress"},"updateStream() recover local stream successfully":{tips:"Device acquisition exception, automatic recovery is successful"},"updateStream() failed to recover local stream":{tips:"Device acquisition exception, automatic recovery failed"},"main stream - video track is muted":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is muted":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is muted":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unable to provide media output":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is unable to provide media output":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is unable to provide media output":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unmuted":{tips:"Received enough playback video data"},"main stream - audio track is unmuted":{tips:"Received enough playback audio data"},"auxiliary stream - video track is unmuted":{tips:"Received enough playback screen sharing data"},"main stream - audio player track is ended":{tips:"Remote audio track stopped"},"main stream - video player track is ended":{tips:"Remote video track stopped"},"auxiliary stream - video player track is ended":{tips:"Received enough playback screen sharing data"},"stream - video track is muted":{tips:"Camera capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"stream - video track is unable to provide media output":{tips:"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked, and the customer needs to re-acquire. SDK v4.11.4+ will automatically resume acquisition without customer intervention",color:"orange"},"video track is unable to provide media output":{tips:i=>i.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"stream - audio track is muted":{tips:"Microphone capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"audio track is unable to provide media output":{tips:i=>i.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"Microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio track is unable to provide media output":{tips:"The microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"is adding audio track to current published local stream":{tips:"add audio track",color:"orange"},"is removing audio track from current published local stream":{tips:"remove audio track",color:"orange"},"is removing video track from current published local stream":{tips:"remove video track",color:"orange"},"is adding video track to current published local stream":{tips:"add video track",color:"orange"},"is replacing audio track to current published local main stream":{tips:"replace audio track",color:"orange"},"is replacing video track to current published local main stream":{tips:"replace video track",color:"orange"},"downlink network quality change":{tips:"Downstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"uplink network quality change":{tips:"Upstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"localStream mute video":{tips:"mute upstream video stream",color:"orange"},"localStream unmute video":{tips:"unmute upstream video stream",color:"orange"},"localStream mute audio":{tips:"mute upstream audio stream",color:"orange"},"localStream unmute audio":{tips:"unmute upstream audio stream",color:"orange"},"black detected":{tips:"Detect black screen, which means fps = 0. It is usually caused by network, and the network will be recovered after a while. If the network is normal but has not been restored, it is an abnormal situation."},'main stream start to play with options: {"muted":true}':{tips:"Play the remote stream in silent mode. Generally, the remote stream does not need to be played in silent mode. You need to confirm whether the parameters passed in the client stream.play API call are correct.",color:"orange"},"main stream - audio player is starting playing":{tips:"Remote stream audio playback success",color:"#0dd90d",class:"success"},"main stream - video player is starting playing":{tips:"Remote stream video playback success",color:"#0dd90d",class:"success"},"video player is playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"audio player is playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"stream - video player is starting playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"stream - audio player is starting playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"switch camera success":{tips:"Switch camera success",color:"#0dd90d",class:"success"},"switch microphone success":{tips:"Switch microphone success",color:"#0dd90d",class:"success"},gotStream:{tips:"Local stream capture success"},"local stream is published successfully":{tips:"Publish success",color:"#0dd90d",class:"success"},"encoderImplementation change to OpenH264":{tips:"Use software encoding"},"encoderImplementation change to ExternalEncoder":{tips:"Use hardware encoding"},"getUserMedia with constraints":{tips:"Start media (camera/microphone) capture"},"getDisplayMedia with constraints":{tips:"Start screen sharing capture"},"client-banned":{tips:"Kicked out of the room",color:"red",class:"red",textColor:"#fff"},user_timeout:{tips:"The backend is too long without receiving SDK heartbeat, which is usually caused by the JS thread being blocked for a long time. If the reproduction probability is high, the application browser Performance tool analyzes where the JS thread is blocked.",color:"red",class:"red",textColor:"#fff"},"schedule failed":{tips:"Signaling request failed, does not affect the normal room entry process, SDK will connect to the default signaling domain."},"updateStream() video flag is true, but no camera detected, set video to false":{tips:"When trying to resume camera acquisition, the camera acquisition is not resumed because it is detected that there is no camera.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to bandwidth":{tips:"bandwidth estimation is not enough to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to cpu":{tips:"cpu load is too high to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: hidden":{tips:"User page switched to backend, in mobile devices, this will cause the device to pause the capture, and it will be restored when the user switches backend to the frontend.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: visible":{tips:"User page switched to frontend",color:"orange",class:"orange",textColor:"#fff"},"main stream - audio player is paused":{tips:`The remote stream audio playback is paused, which usually has two possibilities:
|
|
98
98
|
1. The business side passes in the div tag container for playing audio and video to be removed by the business side from the DOM.
|
|
99
99
|
2. If the user is in Chrome 70 and below, when the div container is moved, the playback will be paused.`,color:"orange",class:"orange",textColor:"#fff"},"main stream - video player is paused":{tips:`The remote stream video playback is paused, which usually has two possibilities:
|
|
100
100
|
1. The business side passes in the div tag container for playing audio and video to be removed by the business side from the DOM.
|
|
101
|
-
2. If the user is in Chrome 70 and below, when the div container is moved, the playback will be paused.`,color:"orange",class:"orange",textColor:"#fff"},'"displaySurface":"window"':{tips:"Screen sharing captures the application window",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"monitor"':{tips:"Screen sharing captures the entire screen",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"browser"':{tips:"Screen sharing captures a certain tab page",color:"blue",class:"blue",textColor:"#fff"},updateMediaSettings:{tips:"The resolution and frame rate below are the actual resolution and frame rate captured",color:"blue",class:"blue",textColor:"#fff"},"main stream start to play with":{tips:"Call remoteStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"stream start to play with":{tips:"Call localStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"main setAudioVolume to 0":{tips:"Business side calls remoteStream.setAudioVolume(0) interface to set the playback volume to 0, which will cause the playback to be silent",color:"orange",class:"orange",textColor:"#fff"},"screen sharing was stopped because the video track is ended":{tips:"Screen sharing capture stopped, possible reasons: user clicks the stop button, the window/page shared by the user is closed, etc.",color:"orange",class:"orange",textColor:"#fff"},"Join() => joining room":{tips:"Call client.join interface",color:"blue",class:"blue",textColor:"#fff"},"publish() => publishing local stream":{tips:"Call client.publish interface",color:"blue",class:"blue",textColor:"#fff"},"subscribe() => subscribe to":{tips:"Call client.subscribe interface",color:"blue",class:"blue",textColor:"#fff"},"switchRole() => switch role":{tips:"Call client.switchRole interface",color:"blue",class:"blue",textColor:"#fff"}};["enterRoom","exitRoom","switchRole","destroy","startLocalAudio","updateLocalAudio","stopLocalAudio","startLocalVideo","updateLocalVideo","stopLocalVideo","startScreenShare","updateScreenShare","stopScreenShare","startRemoteVideo","updateRemoteVideo","stopRemoteVideo","muteRemoteAudio","setRemoteAudioVolume"].forEach(i=>{Og[`${i}()`]={tips:`Call trtc.${i}`,color:"blue",class:"blue",textColor:"#fff"}});var _k=Object.keys(Og);var RS=0,gu,La=class La{constructor(t){this.core=t;u(this,"_core");u(this,"log");u(this,"dumpLocalVideoMap",{});u(this,"dumpRemoteVideoMap",{});u(this,"dialog");this._core=t,this.log=t.log.createChild({id:`${this.getAlias()}${++RS}`}),this.log.info("created")}getName(){return La.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 A(this,null,function*(){var e;!new URLSearchParams(location.search).has("trtcDebug")&&((e=window.sessionStorage)==null?void 0:e.getItem("TRTC_ENABLE_DEBUG_PLUGIN"))!=="true"||(yield this.openDebugDiaLog(),this.addVideoProcessor())})}update(e){return A(this,arguments,function*({forceOpen:t}){P(t)&&(t?(yield this.openDebugDiaLog(),this.addVideoProcessor()):(this.closeDebugDiaLog(),this.removeVideoProcessor()))})}stop(){this.closeDebugDiaLog(),this.removeVideoProcessor()}destroy(){this.stop()}openDebugDiaLog(){return A(this,null,function*(){var t;if(!this.dialog)try{if(gu)yield gu;else{let e=new URLSearchParams(location.search).get("trtcDebugDialogPath")||((t=window.sessionStorage)==null?void 0:t.getItem("TRTC_DEBUG_DIALOG_PATH"))||`https://unpkg.com/${Ng}@${at}/assets/debug-dialog.js`;gu=this._core.fileDownloader.loadScript(e),yield gu}this.dialog=new TRTCDebugDialog(this._core,this.log,this.dumpLocalVideoMap,this.dumpRemoteVideoMap),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(e){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(e))}})}closeDebugDiaLog(){this.dialog&&(this.dialog.closeDialog(),this.dialog=null)}addVideoProcessor(){this._core.room.videoManager.addEncodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.encodeVideo.bind(this):bp,type:1}),this._core.room.videoManager.addDecodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.decodeVideo.bind(this):Rp,type:1})}removeVideoProcessor(){this._core.room.videoManager.removeEncodeProcessor({type:1}),this._core.room.videoManager.removeDecodeProcessor({type:1})}encodeVideo({frame:t,mediaType:e}){return bp({frame:t,onDump:()=>{if(!e)return;let r=e===2?"sub":"main",o=this.dumpLocalVideoMap[r];o&&(o.data.push(t.data.slice(0)),o.duration>0&&Date.now()-o.startTimestamp>o.duration*1e3&&o.onDumpEnd())}})}decodeVideo({frame:t,track:e}){return Rp({frame:t,onDump:()=>{if(!e)return;let r=this.dumpRemoteVideoMap[`${e.userId}-${e.streamType}`];r&&(r.data.push(t.data.slice(0)),r.duration>0&&Date.now()-r.startTimestamp>r.duration*1e3&&r.onDumpEnd())}})}};u(La,"Name","Debug"),u(La,"autoStart",!0);var Eu=La;var xg=i=>{switch(i){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},_u=class{constructor(t,e,r){u(this,"trackDoneOB");u(this,"startOB");u(this,"stopOB");u(this,"inputFrameCount",0);u(this,"decodedFrameCount",0);u(this,"type","auto");u(this,"config");u(this,"decoder");u(this,"_decodeSink");let{kvStatManager:o,trtc:s}=t;this.config=r.config,this.trackDoneOB=Ce(e,de.INIT),this.stopOB=At(),this.startOB=At(),r.type==="auto"?this.type="webCodecs":this.type=r.type;let n=At(),c=l=>{let m=this.pipe(e);return n.next("STARTING"),e.log.info(`decoder type: ${this.type}`),be(m,Ye(this.stopOB),Le(()=>{},E=>{e.log.error(E),o.addFailedEvent({key:xg(this.type),error:E}),l>4?this.startOB.error(E):this.startOB.next(l+1)})),be(m,Nr(1),Km(va))};be(this.startOB,ba(0),no(c),Ye(this.stopOB),Le(()=>{e.player.setOutput(),n.next("STARTED")},l=>{n.next("FAILED")},()=>{o.addSuccessEvent({key:xg(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 Si()(e=>A(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"}))}},vS={type:"object"},Ua=class Ua{constructor(t){this.core=t;u(this,"log");u(this,"contextMap",new Map);u(this,"decodeProcessorMap",new WeakMap);this.log=t.log.createChild({id:`${this.getAlias()}`})}getAlias(){return Ua.Name}getGroup(t){return t.track.userId+t.track.streamType}getName(){return Ua.Name}getValidateRule(t){return vS}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 _u(this.core,r,t);return be(o.trackDoneOB,Nr(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 _u(this.core,t.track,t))}}};u(Ua,"Name","TRTCAudioDecoder");var Va=Ua;var Tu=class{constructor(){u(this,"log");this.log=$.createLogger({id:"exp"})}call(t,e){return A(this,null,function*(){return We(this[t])?this[t](e):Promise.reject(new ue({code:q.INVALID_PARAMETER,message:Be({key:$e.API_NOT_EXIST,data:{name:t}})}))})}enableAudioFrameEvent(t){return A(this,null,function*(){let{trtcInstance:e,enable:r,userId:o,sampleRate:s=48e3,channelCount:n=1,port:c}=t,{audioManager:l}=e.room,{getPCMAbortCtrlMap:m,audioFrameEventConfigMap:E}=l;if(E.set(o,{enable:r,sampleRate:s,channelCount:n,port:c}),r)if(o==="*")e.room.remotePublishedUserMap.forEach(g=>{if(g.remoteAudioTrack.isAvailable){if(m.get(g.userId))return;let _=l.getPCM(v=>{e.emit(re.AUDIO_FRAME,v)},g.userId);m.set(g.userId,_)}});else{if(m.get(o))return;let g=l.getPCM(_=>{e.emit(re.AUDIO_FRAME,_)},o);m.set(o,g)}else if(o==="*")e.room.remotePublishedUserMap.forEach(g=>{if(g.remoteAudioTrack.isSubscribed){let{userId:_}=g,v=m.get(_);v==null||v.abort("disable"),m.delete(_)}});else{let g=m.get(o);g==null||g.abort("disable"),m.delete(o)}})}};Z([Qf({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"}}})],Tu.prototype,"enableAudioFrameEvent",1);var Pg=new Tu;var kg=0,Fa=new Set,Ct=null;Yu(Dg);Hs.checkStorage();var CS={RtcError:ne,ErrorCode:le,ErrorCodeDictionary:pr},Se=class Se extends Lg.EventEmitter{constructor(e,r){super();u(this,"_room");u(this,"_eventListened",new Set);u(this,"_localVideoTrack",null);u(this,"_localAudioTrack",null);u(this,"_localScreenTrack",null);u(this,"_localScreenAudioTrack",null);u(this,"_localVideoConfig",null);u(this,"_localScreenConfig",null);u(this,"_localAudioConfig",null);u(this,"_remoteVideoConfigMap",new Map);u(this,"_remoteAudioConfigMap",new Map);u(this,"_remoteAudioVolumeMap",new Map);u(this,"_remoteAudioMuteMap",new Map);u(this,"_mediaTrackMap",new WeakMap);u(this,"_log",$.createLogger({id:`t${++kg}`}));u(this,"_plugins",new Map);u(this,"_networkQuality",null);u(this,"_speakerId");u(this,"enterRoomParams");this._room=new e(z({logger:this._log,frameWorkType:Se.frameWorkType},r)),this._room.videoDecodeFallbackType=r.videoDecodeFallback,this._log.info(`create() ${JSON.stringify(r,(o,s)=>o==="plugins"?s.map(n=>n.Name):s)}`),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(o){return this._room.audioManager.dump(o)}}}),r.plugins&&r.plugins.forEach(o=>{this._use(o,r.assetsPath)}),this._use(mu,r.assetsPath),this._use(uu,r.assetsPath),this._use(hu,r.assetsPath),this._use(Va,r.assetsPath||pc),this._use(Eu),r.enableSEI&&ua&&this._use(fu),this._room.on("audio-volume",o=>{!o.find(s=>s.userId==="")&&this._localAudioTrack&&o.push({userId:"",volume:Math.floor(this._localAudioTrack.getAudioLevel()*100)}),r.volumeType===1&&o.forEach(s=>{var c;let n=s.userId===""?this._localAudioTrack:(c=this.room.remotePublishedUserMap.get(s.userId))==null?void 0:c.remoteAudioTrack;n&&(s.volume=n.dbVolume)}),this.emit(re.AUDIO_VOLUME,{result:o.sort((s,n)=>n.volume-s.volume)})}),this._room.videoManager.on("error",o=>{this._log.error(new ne({code:le.OPERATION_FAILED,extraCode:5504,message:o.message,originError:o}))}),this._listenEvents(),this._initActiveSpeaker(),bg(this,"trtc")}static create(e){}static _create(e,r){cg();let o=new Se(e,r||{});return Fa.add(o),o}get room(){return this._room}_listenEvents(){Vt(this,this._room).add("peer-join",e=>{let{userId:r}=e;this.emit(re.REMOTE_USER_ENTER,{userId:r})}).add("peer-leave",e=>{this.emit(re.REMOTE_USER_EXIT,{userId:e}),this._remoteAudioVolumeMap.delete(e)}).add("banned",e=>{this._exitRoom().finally(()=>{this.emit(re.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().finally(()=>{this.emit(re.ERROR,ne.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(re.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let r=Te(z({},e),{uplinkRTT:Math.min(e.uplinkRTT,wn),downlinkRTT:Math.min(e.downlinkRTT,wn)});this.emit(re.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(z({},s),{userId:e.userId});o.kind===N.VIDEO&&(n.streamType=uo(o.streamType)),this.emit(o.kind===N.AUDIO?re.AUDIO_PLAY_STATE_CHANGED:re.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",s=>{s.getCode()===q.PLAY_NOT_ALLOWED&&this.emit(re.AUTOPLAY_FAILED,{userId:o.userId,mediaType:o.strMediaType,resume:()=>o.player.resume()})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(o=>{ht(o)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:r})=>{let{userId:o}=r,s=e.audioAvailable,n=e.videoAvailable,{audioAvailable:c,videoAvailable:l}=r;c||this._remoteAudioConfigMap.delete(o),l||this._removeRemoteVideoConfig(o,"main"),r.hasAuxiliary||this._removeRemoteVideoConfig(o,"sub"),n!==l&&(l?this._onVideoAvailable({userId:o,streamType:"main"}):this._onVideoUnavailable({userId:o,streamType:"main"}),this.emit(l?re.REMOTE_VIDEO_AVAILABLE:re.REMOTE_VIDEO_UNAVAILABLE,{userId:o,streamType:"main"})),s!==c&&(c?this._onAudioAvailable({userId:o}):this._onAudioUnavailable({userId:o,muteState:r}),this.emit(c?re.REMOTE_AUDIO_AVAILABLE:re.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?re.REMOTE_VIDEO_AVAILABLE:re.REMOTE_VIDEO_UNAVAILABLE,{userId:o,streamType:"sub"}))}).add("sei-message",e=>{this.emit(re.SEI_MESSAGE,Te(z({},e),{streamType:uo(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(re.ERROR,new ne({code:le.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var s,n,c,l,m,E,g;let r={2:"big",3:"small",7:"sub"},o={rtt:Math.min(e.msg_up_stream_info.msg_network_status.uint32_rtt||((s=e.msg_down_stream_info[0])==null?void 0:s.msg_network_status.uint32_rtt)||((n=this._networkQuality)==null?void 0:n.uplinkRTT)||((c=this._networkQuality)==null?void 0:c.downlinkRTT)||0,wn),upLoss:((l=this._networkQuality)==null?void 0:l.uplinkLoss)||0,downLoss:((m=this._networkQuality)==null?void 0:m.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((E=e.msg_up_stream_info.msg_audio_status)==null?void 0:E.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((g=e.msg_up_stream_info.msg_audio_status)==null?void 0:g.uint32_audio_level)||0)/mi},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)/mi,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(v=>({bitrate:(v.uint32_video_codec_bitrate||0)/1e3,width:v.uint32_video_width,height:v.uint32_video_height,frameRate:v.uint32_video_dec_fps,videoType:r[v.uint32_video_stream_type],point2pointDelay:(v.uint32_video_p2p_delay||0)+(v.uint32_video_cache_ms||0),jitterBufferDelay:v.uint32_video_cache_ms||0}))}))};this.emit(re.STATISTICS,o)}).add("custom-message",e=>{this.emit(re.CUSTOM_MESSAGE,e)}).add("layerData",e=>this.emit(re.LAYER_DATA,e)).add("first-video-frame",e=>{this.emit(re.FIRST_VIDEO_FRAME,Te(z({},e),{streamType:uo(e.streamType)}))}).add("audio-frame",e=>{this.emit(re.AUDIO_FRAME,e)}),Vt(this,St).add("audioInputAdded",e=>{this.emit(re.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(re.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(re.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(re.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>A(this,null,function*(){if(this.emit(re.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Ct&&Ct.deviceId===Mn){let r=(yield to()).find(o=>o.deviceId===Mn);r&&Ct.groupId!==r.groupId&&(Ct=r,this.emit(re.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}))}})).add("audioOutputRemoved",e=>A(this,null,function*(){this.emit(re.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let r=(yield to())[0];if(!r||!Ct||Ct.groupId===r.groupId)return;let o=Ct.deviceId===e.deviceId,s=Ct.deviceId===Mn&&Ct.deviceId===r.deviceId;(o||s)&&(Ct=r,this.emit(re.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}))}))}use(e){let r,o;"plugin"in e?(r=e.plugin,o=e.assetsPath):r=e,this._use(r,o||pc)}_use(e,r){if(this._plugins.get(e.Name)){this._log.warn("duplicate install plugin",e.Name);return}let s=new e(yg.call(this,{TRTC:Se,room:this._room,errorModule:CS,assetsPath:r}));this._plugins.set(e.Name,s),e.autoStart&&this.startPlugin(e.Name)}enterRoom(e){return A(this,null,function*(){var l,m;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&&((m=(l=this._room).setTurnServer)==null||m.call(l,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=o,this._room.autoReceiveAudio=s,this._room.autoReceiveVideo=n,st(e.preferHW)&&(this._room.preferHW=e.preferHW),e.playoutDelay&&(this._room.playoutDelay=e.playoutDelay),e.jitterBufferDelay&&(this._room.jitterBufferDelay=e.jitterBufferDelay);let c={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:e.role==="audience"?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language,priority:e.priority,useVp8:e.useVp8,keepAlive:e.keepAlive};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(c,r,Se.frameWorkType),this._checkTrackToPublish(),Ip.start()})}exitRoom(){return A(this,null,function*(){return yield this._exitRoom()})}switchRoom(e){return A(this,null,function*(){if(this.room.isSwitchRoomSupported())yield this._room.switchRoom(e);else{yield this.exitRoom();let r=z(z({},this.enterRoomParams),e);yield this.enterRoom(r)}})}switchRole(e,r){return A(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(){ht(this),this.removeAllListeners(),this._room.destroy(),Fa.delete(this),Fa.size===0&&Ip.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),this._plugins.forEach(e=>{var r;return(r=e.destroy)==null?void 0:r.call(e)}),this._plugins.clear(),V.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return A(this,arguments,function*(e={publish:!0}){if(this._localAudioTrack){this._log.warn("local audio is already started");return}let{publish:r=!0,mute:o,option:s}=e,n=new jr(this._room.audioManager),c={},l={muted:!0};s&&(P(s.microphoneId)?P(s.audioTrack)||(c.customSource=s.audioTrack):c.deviceId=s.microphoneId,s&&ke(s.captureVolume)&&n.setCaptureVolume(s.captureVolume),P(s.profile)||(Oe(s.profile)?fc[s.profile]&&n.setProfile(fc[s.profile]):n.setProfile(s.profile)),ke(s.earMonitorVolume)&&(l.muted=!(s.earMonitorVolume>0),l.volume=s.earMonitorVolume),P(s.echoCancellation)||(n.profile.echoCancellation=s.echoCancellation),P(s.noiseSuppression)||(n.profile.noiseSuppression=s.noiseSuppression),P(s.autoGainControl)||(n.profile.autoGainControl=s.autoGainControl)),n.on("5",m=>{this.emit(re.ERROR,new ne({code:le.DEVICE_ERROR,extraCode:5309,messageParams:{error:m}}))}),n.on("2",m=>{this.emit(re.DEVICE_CHANGED,{type:"microphone",action:"active",device:m})}),n.on("4",m=>{let E;m.error&&(E=ne.convertFrom(m.error)),this.emit(re.PUBLISH_STATE_CHANGED,Te(z({},m),{error:E}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId),yield n.capture(c),P(o)||n.setMute(o),Vt(n,n).add("player-state-changed",m=>{this.emit(re.AUDIO_PLAY_STATE_CHANGED,Te(z({},m),{userId:""}))}),r&&this._room.isJoined&&this._room.publish(n).catch(()=>{}),this._localAudioTrack=n,this._localAudioConfig=Te(z({},e),{publish:r}),yield this._updateAudioPlayOption({playOption:l,track:n}),V.emit("113",{userId:"",room:this.room})})}updateLocalAudio(e){return A(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:r,mute:o,option:s}=e,n={};s&&(s.microphoneId?yield this._localAudioTrack.switchDevice(s.microphoneId):P(s.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(s.audioTrack)),P(s.captureVolume)||this._localAudioTrack.setCaptureVolume(s.captureVolume),P(s.earMonitorVolume)||(n.muted=!(s.earMonitorVolume>0),n.volume=s.earMonitorVolume),yield this._localAudioTrack.update3A(s)),this._room.isJoined&&!P(r)&&(r&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!r&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),P(o)||this._localAudioTrack.setMute(o),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),dr(this._localAudioConfig,e)})}stopLocalAudio(){return A(this,null,function*(){this._localAudioTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),V.emit("114",{userId:"",room:this.room}),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),ht(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)})}startLocalVideo(){return A(this,arguments,function*(e={publish:!0,view:null,capture:!0}){var g;if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:r,publish:o=!0,capture:s=!0,mute:n,option:c}=e,l=new Cr(this._room.videoManager),m={},E={};st(c==null?void 0:c.avoidCropping)&&(l.avoidCropping=c.avoidCropping),c&&(c.cameraId?m.deviceId=c.cameraId:P(c.useFrontCamera)?P(c.videoTrack)||(m.customSource=c.videoTrack):m.facingMode=c.useFrontCamera?N.FACING_MODE_USER:N.FACING_MODE_ENVIRONMENT,P(c.retryWhenExactFailed)||(m.retryWhenExactFailed=c.retryWhenExactFailed),c.qosPreference&&(m.contentHint=xa(c.qosPreference)),P(c.profile)||(Oe(c.profile)?Tr[c.profile]&&l.setProfile(Tr[c.profile]):l.setProfile(c.profile)),P(c.fillMode)||(E.objectFit=c.fillMode),P(c.mirror)||(E.mirror=c.mirror),P(c.small)||(P(c.smallMode)||(this._room.smallMode=c.smallMode),st(c.small)&&c.small===!1?l.stopSmall():l.updateSmallConfig(sn(c.small,!0))),P(c.rotation)||l.setRotation(c.rotation)),l.once("first-video-frame",_=>{this.emit(re.FIRST_VIDEO_FRAME,Te(z({},_),{streamType:uo(_.streamType)}))}),l.on("5",_=>{this.emit(re.ERROR,new ne({code:le.DEVICE_ERROR,extraCode:5308,messageParams:{error:_}}))}),l.on("2",_=>{this.emit(re.DEVICE_CHANGED,{type:"camera",action:"active",device:_})}),l.on("4",_=>{let v;_.error&&(v=ne.convertFrom(_.error)),this.emit(re.PUBLISH_STATE_CHANGED,Te(z({},_),{error:v}))}),this._listenOutputTrackChanged(l),s?yield l.capture(m):(g=l.manager)==null||g.changeInput(l),P(n)||(yield l.setMute(n)),Vt(l,l).add("player-state-changed",_=>{this.emit(re.VIDEO_PLAY_STATE_CHANGED,Te(z({},_),{userId:"",streamType:"main"}))}),o&&this._room.isJoined&&this._room.publish(l).catch(()=>{}),this._localVideoTrack=l,this._localVideoConfig=Te(z({},e),{view:r,publish:o,capture:s}),yield this._updateVideoPlayOption({view:r,playOption:E,track:l})})}updateLocalVideo(e){return A(this,null,function*(){var m,E,g;if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:r,publish:o,mute:s,capture:n,option:c}=e,l={};if(this._localVideoConfig.capture)n!==!1?c!=null&&c.cameraId?yield this._localVideoTrack.switchDevice(c==null?void 0:c.cameraId):P(c==null?void 0:c.useFrontCamera)?P(c==null?void 0:c.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(c==null?void 0:c.videoTrack)):yield this._localVideoTrack.switchDevice(c!=null&&c.useFrontCamera?N.FACING_MODE_USER:N.FACING_MODE_ENVIRONMENT):this._localVideoTrack.stopCapture();else if(n){let _={};_.deviceId=(c==null?void 0:c.cameraId)||((m=this._localVideoConfig.option)==null?void 0:m.cameraId),_.facingMode=c!=null&&c.useFrontCamera||(E=this._localVideoConfig.option)!=null&&E.useFrontCamera?N.FACING_MODE_USER:N.FACING_MODE_ENVIRONMENT,_.customSource=(c==null?void 0:c.videoTrack)||((g=this._localVideoConfig.option)==null?void 0:g.videoTrack),yield this._localVideoTrack.capture(_)}c&&(P(c.profile)||(Oe(c.profile)?Tr[c.profile]&&this._localVideoTrack.setProfile(Tr[c.profile]):this._localVideoTrack.setProfile(c.profile),(!c.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(c.cameraId))&&P(c.useFrontCamera)&&(yield this._localVideoTrack.applyProfile())),P(c.fillMode)||(l.objectFit=c.fillMode),P(c.mirror)||(l.mirror=c.mirror),P(c.rotation)||this._localVideoTrack.setRotation(c.rotation),c.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(xa(c.qosPreference)),P(c.small)||(st(c.small)&&!c.small?this._localVideoTrack.stopSmall():this._localVideoTrack.updateSmallConfig(sn(c.small,!0)))),this._room.isJoined&&P(o)&&this._localVideoConfig.publish&&n&&!this._localVideoConfig.capture&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._room.isJoined&&((o!=null?o:this._localVideoConfig.publish)?this._room.publish(this._localVideoTrack).catch(()=>{}):this._room.unpublish(this._localVideoTrack).catch(()=>{})),P(s)||(yield this._localVideoTrack.setMute(s)),yield this._updateVideoPlayOption({view:r,playOption:l,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),dr(this._localVideoConfig,e)})}stopLocalVideo(){return A(this,null,function*(){this._localVideoTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),ht(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return A(this,arguments,function*(e={publish:!0,view:null}){if(this._localScreenTrack){this._log.warn("screen share is already started");return}let{view:r=null,publish:o=!0,option:s}=e,n=new io(this._room.videoManager);n.on("4",g=>{let _;g.error&&(_=ne.convertFrom(g.error)),this.emit(re.PUBLISH_STATE_CHANGED,Te(z({},g),{error:_}))}),n.once("first-video-frame",g=>{this.emit(re.FIRST_VIDEO_FRAME,Te(z({},g),{streamType:uo(g.streamType)}))}),this._listenOutputTrackChanged(n),e.streamType==="main"&&(n.mediaType=4);let c=null,l={},m={};s&&(P(s.profile)||(Oe(s.profile)?gc[s.profile]&&n.setProfile(gc[s.profile]):n.setProfile(s.profile)),s.systemAudio&&(l.systemAudio=!0,l.echoCancellation=s.echoCancellation,l.noiseSuppression=s.noiseSuppression,l.autoGainControl=s.autoGainControl),P(s.fillMode)||(m.objectFit=s.fillMode),s.videoTrack&&(l.videoTrack=s.videoTrack),s.audioTrack&&(l.audioTrack=s.audioTrack),s.captureElement&&(l.captureElement=s.captureElement),s.preferDisplaySurface&&(l.preferDisplaySurface=s.preferDisplaySurface),s.qosPreference&&(l.contentHint=xa(s.qosPreference)));let E=yield n.capture(l);if(n.mediaTrack.addEventListener(N.ENDED,()=>{this._stopScreenShare(),this.emit(re.SCREEN_SHARE_STOPPED)}),E.getAudioTracks()[0]&&(c=new Ko(this._room.audioManager),yield c.setInputMediaStreamTrack(E.getAudioTracks()[0]),this._speakerId&&c.setAudioOutput(this._speakerId)),Vt(n,n).add("player-state-changed",g=>{this.emit(re.VIDEO_PLAY_STATE_CHANGED,Te(z({},g),{userId:"",streamType:"sub"}))}),o&&this._room.isJoined){let g=[n];c&&(g.push(c),this._checkScreenAudioEchoCancellation(n,c)),this._room.publish(...g).catch(()=>{})}this._localScreenTrack=n,this._localScreenAudioTrack=c,this._localScreenConfig=Te(z({},e),{view:r,publish:o}),yield this._updateVideoPlayOption({view:r,playOption:m,track:n})})}updateScreenShare(e){return A(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:r,publish:o,option:s}=e,n={};if(s&&(P(s.fillMode)||(n.objectFit=s.fillMode),s.qosPreference)){let c=xa(s.qosPreference);this._localScreenTrack.setContentHint(c)}this._room.isJoined&&!P(o)&&(o&&!this._localScreenConfig.publish&&(this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch(()=>{})),this._localScreenConfig.publish&&!o&&(this._room.unpublish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.unpublish(this._localScreenAudioTrack).catch(()=>{}))),yield this._updateVideoPlayOption({view:r,playOption:n,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),dr(this._localScreenConfig,e)})}stopScreenShare(){return A(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return A(this,null,function*(){let{view:r,userId:o,streamType:s,option:n}=e,c=`${o}_${s}`;if(this._remoteVideoConfigMap.has(c)){this._log.warn(`remote video has already started. userId:${o}, streamType:${s}`);return}let l=this._room.remotePublishedUserMap.get(o);if(!l)return;let m={},E=s==="main"?l.remoteVideoTrack:l.remoteAuxiliaryTrack;this._listenOutputTrackChanged(E),n&&(P(n.fillMode)||(m.objectFit=n.fillMode),P(n.mirror)||(m.mirror=n.mirror),P(n.poster)||(m.poster=n.poster),m.canvasRender=n.canvasRender,s==="main"&&!P(n.small)&&(!l.remoteVideoTrack.isSubscribing&&!l.remoteVideoTrack.isSubscribed&&l.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,E.user))),yield this._room.subscribe(E),yield this._enableVideoDecodeFallback(E,s),yield this._updateVideoPlayOption({view:r,playOption:m,track:E}),this._emitTrackEvent(E),this._remoteVideoConfigMap.set(c,{config:e}),n&&!P(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:E,view:r,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:n==null?void 0:n.viewRoot})})}updateRemoteVideo(e){return A(this,null,function*(){var M,B;let{view:r,userId:o,streamType:s,option:n}=e,c=`${o}_${s}`,l=this._remoteVideoConfigMap.get(c);if(!l||!this._room.remotePublishedUserMap.has(o))return;let m={};n&&(P(n.fillMode)||(m.objectFit=n.fillMode),P(n.mirror)||(m.mirror=n.mirror));let E=null,g=this._room.remotePublishedUserMap.get(o);if(s==="main"&&(g!=null&&g.muteState.hasVideo)&&(E=g.remoteVideoTrack),s==="sub"&&(g!=null&&g.muteState.hasAuxiliary)&&(E=g.remoteAuxiliaryTrack),!E)return;let{config:_}=l;s==="main"&&n&&!P(n.small)&&this._room.changeType(n.small,E.user),yield this._updateVideoPlayOption({view:r,playOption:m,track:E,prevConfig:_}),dr(_,e);let v=P(n==null?void 0:n.receiveWhenViewVisible)?(M=_.option)==null?void 0:M.receiveWhenViewVisible:n.receiveWhenViewVisible,L=P(r)?_.view:r,x=P(n==null?void 0:n.viewRoot)?(B=_.option)==null?void 0:B.viewRoot:n.viewRoot;this._observeView({remoteTrack:E,view:L,receiveWhenViewVisible:v,viewRoot:x})})}stopRemoteVideo(e){return A(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,r=!0){return A(this,null,function*(){let o=[],s=this._room.remotePublishedUserMap.get(e.userId);if(s){let{muteState:n,remoteVideoTrack:c,remoteAuxiliaryTrack:l}=s;e.streamType==="main"&&(c.stop(),n.hasVideo&&o.push(c)),e.streamType==="sub"&&(l.stop(),n.hasAuxiliary&&o.push(l))}for(let n of o)r&&(yield this._room.unsubscribe(n),this._mediaTrackMap.delete(n.outMediaTrack));this._removeRemoteVideoConfig(e.userId,e.streamType)})}_removeRemoteVideoConfig(e,r){let o=`${e}_${r}`,s=this._remoteVideoConfigMap.get(o);s&&s.observer&&s.observer.disconnect(),this._remoteVideoConfigMap.delete(o)}muteRemoteAudio(e,r){return A(this,null,function*(){this._remoteAudioMuteMap.set(e,r);try{if(e==="*")if(r)yield this._stopRemoteAudio({userId:e});else{let o=[...this._room.remotePublishedUserMap.values()];for(let s of o)s.muteState.hasAudio&&!this._remoteAudioConfigMap.has(s.userId)&&(yield this._startRemoteAudio({userId:s.userId}))}else r?yield this._stopRemoteAudio({userId:e}):this._remoteAudioConfigMap.has(e)||(yield this._startRemoteAudio({userId:e}))}catch(o){throw this._remoteAudioMuteMap.delete(e),o}})}setRemoteAudioVolume(e,r){if(e==="*"){let o=[...this._room.remotePublishedUserMap.values()];for(let s of o)this._remoteAudioVolumeMap.set(s.userId,r),s.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:r},track:s.remoteAudioTrack})}else if(e){let o=this._room.remotePublishedUserMap.get(e);this._remoteAudioVolumeMap.set(e,r),o&&o.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:r},track:o.remoteAudioTrack})}}startPlugin(e,r){return A(this,null,function*(){return e.start(r)})}updatePlugin(e,r){return A(this,null,function*(){return e.update(r)})}stopPlugin(e,r){return A(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(re.AUDIO_FRAME).length>0){let{audioFrameEventConfigMap:s}=this.room.audioManager;s.get("")||s.set("",{enable:!0}),this._localAudioTrack&&this.room.audioManager.handleLocalTrackStarted({userId:"",room:this.room})}return this}emit(e,...r){try{Tg.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===Se.EVENT.AUDIO_FRAME||e==="*")&&this.listeners(Se.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 c=this._room.remotePublishedUserMap.get(r);c&&(o=c.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 c=this._room.remotePublishedUserMap.get(r);c&&(n=o==="main"?c.remoteVideoTrack:c.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 A(this,null,function*(){(yield to()).forEach(o=>{o.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(re.DEVICE_CHANGED,{type:"speaker",action:"active",device:o}),Ct=o)}),this._log.warn('the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: https://web.sdk.qcloud.com/trtc/webrtc/v5/doc/en/TRTC.html#.setCurrentSpeaker')})}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return A(this,null,function*(){let{userId:r}=e;if(this._remoteAudioConfigMap.has(r)){this._log.warn(`remote audio has already started. userId:${r}`);return}let o=this._room.remotePublishedUserMap.get(r);if(!o)return;let s={},n=o.remoteAudioTrack;this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId);try{let c=this._remoteAudioVolumeMap.get(r),l=ke(c)?c:100;s.volume=l,this._remoteAudioConfigMap.set(r,e),yield this._room.subscribe(n),be(Ce(n,"decode-failed"),Ye(Ce(n,de.INIT)),Le(()=>{this.startPlugin(Va.Name,{track:n,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:s,track:n}),V.emit("115",{userId:r,room:this.room}),n.outMediaTrack&&this.room.audioManager.updateAudioReference({type:"add",audioReference:n.outMediaTrack,refId:`ra-${r}`})}catch(c){throw this._remoteAudioConfigMap.delete(r),c}this._emitTrackEvent(n)})}_stopRemoteAudio(e,r=!0){return A(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}`),V.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(Ce(e,"decode-failed"),Ye(Ce(e,de.INIT)),Ca(()=>{this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:o})}),Ai(Ce(e,"decode-downgrade-state-changed")),Le(n=>{s=n.state,this.emit(re.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,Te(z({},n),{streamType:r,userId:e.userId}))},n=>{e.log.error("fallback",n)},()=>{s==="STARTED"&&e.log.info("fallback complete")}))}_updateVideoPlayOption(n){return A(this,arguments,function*({view:e,playOption:r,track:o,prevConfig:s}){if(o.setMirror(r.mirror),P(e)&&s&&s.view&&!Cs(r)){let c=Ds(s.view);c.length>0&&(yield o.play(c,r))}if(!P(e)){let c=Ds(e);c.length>0?yield o.play(c,r):o.stop()}})}_updateAudioPlayOption(s){return A(this,arguments,function*({playOption:e={},track:r,prevConfig:o}){if(!r.isPlayCalled)try{yield r.play(null,e)}catch(n){}if(P(e.muted)||r.setPlayerMute(e.muted),P(e.volume)||r.setAudioVolume(e.volume/100),r instanceof jr&&r.mediaTrack){let n=e.muted===!1&&!P(e.volume)&&e.volume>0?"add":"remove";this.room.audioManager.updateAudioReference({type:n,audioReference:r.mediaTrack,refId:"em"})}else if(r instanceof Ii){let n=e.muted?0:e.volume;if(P(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(re.TRACK,{userId:o,streamType:uo(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 this._room.publish(...e).catch(()=>{})}_observeView({remoteTrack:e,view:r,receiveWhenViewVisible:o=!1,viewRoot:s}){if(P(r))return;let n=this._remoteVideoConfigMap.get(`${e.userId}_${uo(e.streamType)}`);if(!n)return;let c=n.observer||void 0;if(r===null||ot(r)&&r.length===0||!o){c==null||c.disconnect(),e.isSubscribed||this._room.subscribe(e).catch(()=>{});return}let m=n.visibleViewMap||new Map,E=-1;(!c||c.root!==s)&&(c==null||c.disconnect(),m.clear(),c=new IntersectionObserver(_=>{_.forEach(v=>{m.set(v.target,v.isIntersecting),e.log.info(`view ${v.target.id} is${v.isIntersecting?"":" not"} visible`)}),clearTimeout(E),E=window.setTimeout(()=>{[...m.values()].find(L=>L)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:s}));let g=new Set(Ds(r));m.forEach((_,v)=>{g.has(v)||(c.unobserve(v),m.delete(v))}),g.forEach(_=>{m.set(_,!0),c.observe(_)}),c.takeRecords().forEach(_=>{m.set(_.target,_.isIntersecting)}),n.visibleViewMap=m,n.observer=c}_exitRoom(){return A(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(e=>{this._stopRemoteAudio({userId:e}).catch()}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let r=e.includes("main")?"main":"sub",o=e.split(`_${r}`)[0];o&&this._stopRemoteVideo({userId:o,streamType:r}).catch()}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._remoteAudioVolumeMap.clear(),Rg(this),this._room.remotePublishedUserMap.forEach(e=>{ht(e.remoteAudioTrack),ht(e.remoteVideoTrack),ht(e.remoteAuxiliaryTrack)})})}_stopScreenShare(){return A(this,null,function*(){var e,r;if(this._localScreenTrack){if(this._room.isJoined){let o=[this._localScreenTrack];this._localScreenAudioTrack&&o.push(this._localScreenAudioTrack),yield(e=this._room)==null?void 0:e.unpublish(...o).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),ht(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_checkScreenAudioEchoCancellation(e,r){return A(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(c){this._log.warn("start audioProcessor plugin failed: ",c)}}})}_onLocalTrackCaptured({track:e}){e.kind==="audio"&&(!Ct||Qs(Ct))&&(this._initActiveSpeaker(),V.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return A(this,null,function*(){if(Ct&&!Qs(Ct))this.emit(re.DEVICE_CHANGED,{type:"speaker",action:"active",device:Ct});else{let e=yield to();e[0]&&!Qs(e[0])?(Ct=e[0],this.emit(re.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):V.on("102",this._onLocalTrackCaptured,this)}})}_onAudioAvailable({userId:e}){let r=this._remoteAudioMuteMap.has(e)?this._remoteAudioMuteMap.get(e):this._remoteAudioMuteMap.get("*");(r===!1||this._room.autoReceiveAudio&&!r)&&this._doStartRemoteAudio({userId:e}).catch(()=>{})}_onVideoAvailable({userId:e,streamType:r}){if(!this._room.autoReceiveVideo)return;let o=this._room.remotePublishedUserMap.get(e);if(o){let s=r==="main"?o.remoteVideoTrack:o.remoteAuxiliaryTrack,n=[s];this._room.autoReceiveAudio&&o.remoteAudioTrack.isAvailable&&n.push(o.remoteAudioTrack),this._room.subscribe(...n).then(()=>{this._emitTrackEvent(s)}).catch(()=>{})}}_onAudioUnavailable({userId:e,muteState:r}){r.hasAudio&&r.audioMuted||this._stopRemoteAudio({userId:e},!1).catch(()=>{})}_onVideoUnavailable({userId:e,streamType:r}){this._stopRemoteVideo({userId:e,streamType:r},!1).catch(()=>{})}sendSEIMessage(e,r){var s;let o=this._plugins.get("SEI");o&&(o.update({buffer:e,options:Te(z({seiPayloadType:243},r),{small:!!((s=this._localVideoTrack)!=null&&s.small)})}),Q.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var r,o;(o=(r=this._room).sendCustomMessage)==null||o.call(r,e),Q.addCount({key:500001,useUV:!0})}callExperimentalAPI(e,r){return A(this,null,function*(){return this._log.info(`callExperimentalAPI(${e}, ${JSON.stringify(r)})`),Pg.call(e,z({trtcInstance:this},r))})}static setLogLevel(e,r){$.setLogLevel(e),P(r)||(r?$.enableUploadLog():$.disableUploadLog())}static isSupported(){return cd()}static getCameraList(e=!0){return ir(e)}static getMicrophoneList(e=!0){return Qt(e)}static getSpeakerList(e=!0){return to(e)}static setCurrentSpeaker(e){return A(this,null,function*(){if(mt&&(e===mr.SPEAKER||e===mr.HEADSET)){let o=yield Se.getMicrophoneList(),s="";if(o.forEach(n=>{n.label===e&&(s=n.deviceId)}),!s)return;Fa.forEach(n=>A(this,null,function*(){n._localAudioTrack&&(yield n.updateLocalAudio({option:{microphoneId:s}}))}));return}(yield to()).forEach(o=>{o.deviceId===e&&(Fa.forEach(s=>{s._setCurrentSpeaker(e),s.emit(re.DEVICE_CHANGED,{type:"speaker",action:"active",device:o})}),Ct=o)})})}static _addKVStat({type:e,key:r,value:o,base:s,useUV:n,version:c,max:l}){switch(c&&(qo.version=c),e){case"count":qo.addCount({key:r,useUV:n});break;case"enum":qo.addEnum({key:r,value:o,useUV:n});break;case"number":qo.addNumber({key:r,value:o,split:s,max:l});break}}};u(Se,"_loggerManager",$),u(Se,"EVENT",re),u(Se,"ERROR_CODE",le),u(Se,"TYPE",mr),u(Se,"frameWorkType",30),Z([tt({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"}})})],Se.prototype,"use",1),Z([Mt(yt.TRTC.enterRoom),mo("room",([e],[r])=>(e.roomId||e.strRoomId)===(r.roomId||r.strRoomId)&&e.userId===r.userId&&e.sdkAppId===r.sdkAppId),xe(e=>function(r){return this._log.setUserId(r.userId),this._log.setSdkAppId(r.sdkAppId),e.call(this,r)}),tt()],Se.prototype,"enterRoom",1),Z([tt()],Se.prototype,"exitRoom",1),Z([Mt(yt.TRTC.switchRoom),tt(),Rd()],Se.prototype,"switchRoom",1),Z([Mt(yt.TRTC.switchRole),ns("room",{merge:(e,r)=>r}),tt()],Se.prototype,"switchRole",1),Z([tt()],Se.prototype,"destroy",1),Z([Mt(yt.TRTC.startLocalAudio),mo("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)}),tt()],Se.prototype,"startLocalAudio",1),Z([Mt(yt.TRTC.updateLocalAudio),ns("audio",{debounce:{delay:200,getKey:()=>`${kg}-localAudio`,isNeedToDebounce:e=>{var r;return!P((r=e.option)==null?void 0:r.captureVolume)}}}),tt()],Se.prototype,"updateLocalAudio",1),Z([po("audio"),tt()],Se.prototype,"stopLocalAudio",1),Z([Mt(yt.TRTC.startLocalVideo),mo("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)}),tt()],Se.prototype,"startLocalVideo",1),Z([Mt(yt.TRTC.updateLocalVideo),ns("video"),tt()],Se.prototype,"updateLocalVideo",1),Z([po("video"),tt()],Se.prototype,"stopLocalVideo",1),Z([Mt(yt.TRTC.startScreenShare),mo("screen",()=>!0),tt()],Se.prototype,"startScreenShare",1),Z([Mt(yt.TRTC.updateScreenShare),ns("screen"),tt()],Se.prototype,"updateScreenShare",1),Z([tt()],Se.prototype,"stopScreenShare",1),Z([Mt(yt.TRTC.startRemoteVideo),mo(e=>`v${e.userId}${e.streamType}`,()=>!0),tt({getRemoteId:e=>`${e.userId}_${e.streamType}`})],Se.prototype,"startRemoteVideo",1),Z([Mt(yt.TRTC.updateRemoteVideo),ns(e=>`v${e.userId}${e.streamType}`),tt({getRemoteId:e=>`${e.userId}_${e.streamType}`})],Se.prototype,"updateRemoteVideo",1),Z([Mt(yt.TRTC.stopRemoteVideo),xe(e=>function(r){return A(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)})}),tt({getRemoteId:e=>`${e.userId}_${e.streamType}`})],Se.prototype,"stopRemoteVideo",1),Z([po(e=>`v${e.userId}${e.streamType}`)],Se.prototype,"_stopRemoteVideo",1),Z([Mt(...yt.TRTC.muteRemoteAudio),tt({getRemoteId:e=>e})],Se.prototype,"muteRemoteAudio",1),Z([fp(...yt.TRTC.setRemoteAudioVolume),vg(200,e=>e),tt({getRemoteId:e=>e})],Se.prototype,"setRemoteAudioVolume",1),Z([cu("start"),ro(e=>{var r;return(r=e.afterStart)==null?void 0:r.call(e)}),mo((e,r)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(r)),tt({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>jl[e.getName()],ignoreLog:e=>e.getName()==="Debug",ignoreErrorLog:e=>e.getName()==="AudioProcessor"})],Se.prototype,"startPlugin",1),Z([cu("update"),ns((e,r)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(r)),tt({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>ql[e.getName()]})],Se.prototype,"updatePlugin",1),Z([cu("stop"),po((e,r)=>{if(e.disableRandomCall)return null;let o=e.getGroup(r),s=e.getAlias();return o==="*"?new RegExp(`${s}.*`):s+o}),tt({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Jl[e.getName()]})],Se.prototype,"stopPlugin",1),Z([fp(...yt.TRTC.enableAudioVolumeEvaluation)],Se.prototype,"enableAudioVolumeEvaluation",1),Z([tt()],Se.prototype,"getVideoSnapshot",1),Z([tt()],Se.prototype,"_setCurrentSpeaker",1),Z([mo(e=>`a${e.userId}`,()=>!0)],Se.prototype,"_startRemoteAudio",1),Z([xe(e=>function(r){return A(this,null,function*(){return r.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(o=>this._stopRemoteAudio(Te(z({},r),{userId:o.userId})).catch(()=>{}))):e.call(this,r)})}),po(e=>`a${e.userId}`)],Se.prototype,"_stopRemoteAudio",1),Z([po("room")],Se.prototype,"_exitRoom",1),Z([po("screen")],Se.prototype,"_stopScreenShare",1),Z([Mt(...yt.TRTC.sendSEIMessage),cp({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...e)=>e[0].byteLength})],Se.prototype,"sendSEIMessage",1),Z([Mt(yt.TRTC.sendCustomMessage),cp({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],Se.prototype,"sendCustomMessage",1),Z([Mt(yt.TRTC.create)],Se,"_create",1);var vp=Se,un=vp;var Iu=class{constructor(t,e){u(this,"_flag");u(this,"terminalType");u(this,"userId");u(this,"tinyId");u(this,"role");u(this,"remoteAudioTrack");u(this,"remoteVideoTrack");u(this,"remoteAuxiliaryTrack");this.userId=e.userId||"",this.tinyId=e.tinyId||"",this.role=e.role||"audience",this.terminalType=e.terminalType,this.remoteAudioTrack=new Ii(t,this),this.remoteVideoTrack=new ao(t,this),this.remoteAuxiliaryTrack=new Jd(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 Ln(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 Cp=class{constructor(){u(this,"_set",new Set);V.on(U.LEAVE_SUCCESS,this.delete,this),V.on(U.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 NS(){return A(this,null,function*(){let i,t;try{let g=yield Qt();i=g&&g.length}catch(g){}try{let g=yield ir();t=g&&g.length}catch(g){}let e={microphone:i,camera:t},{isH264EncodeSupported:r,isVp8EncodeSupported:o,isH264DecodeSupported:s,isVp8DecodeSupported:n}=this.checkSystemResult.detail,c=eo.basis(),l={webRTC:c.isWebRTCSupported,getUserMedia:c.isGetUserMediaSupported,webSocket:c.isWebSocketsSupported,screenShare:c.isScreenShareSupported,webAudio:c.isWebAudioSupported,h264Encode:r,h264Decode:s,vp8Encode:o,vp8Decode:n},m={browser:c.browser,os:c.os,trtc:l,devices:e},E={isWebCodecSupported:c.isWebCodecSupported,isMediaSessionSupported:c.isMediaSessionSupported,isWebTransportSupported:c.isWebTransportSupported};je.uploadEvent({log:`trtcstats-${JSON.stringify(m)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(m)}`),je.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(E)}`,userId:this.userId})})}function Ug(){return xe(i=>{let t=new Cp;return function(e,r,o){return A(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 ue({code:q.INVALID_OPERATION,message:Be({key:$e.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:s,sdkAppId:this.sdkAppId,room:this}))throw new ue({code:q.INVALID_OPERATION,message:Be({key:$e.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}`),V.emit(U.JOIN_START,{room:this,roomId:s,params:e});let n=Ur.getEnv();n||(n=ei.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(Ec.OLD_CLOUD_LADDER)?n=ei.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(Ec.WEBRTC)&&(n=ei.WEBRTC))),je.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:s}),eo.checkSystemRequirementsInternal(o).then(c=>{this.checkSystemResult=c,NS.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Ur.getEnv()&&(yield this.schedule(e,o));let c=yield i.call(this,e,r,o);return this.roomId=s,this._joinedTimestamp=Ur.performanceNow(),V.emit(U.JOIN_SUCCESS,{room:this}),o===30&&!e.component&&je.uploadEvent({log:`stat-conv-${Number(Rr)}-${location.hostname}`,userId:this.userId}),c}catch(c){throw t.delete({room:this,roomId:s}),V.emit(U.JOIN_FAILED,{room:this,error:c}),c}})}})}var Vg=()=>xe(i=>function(...t){return A(this,null,function*(){V.emit(U.LEAVE_START,{room:this}),yield i.call(this,...t),V.emit(U.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function Fg(){return xe(i=>function(...t){return A(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(t=t.filter(r=>r.outMediaTrack&&r.state==="ready"),!t.length))return;V.emit("61",{room:this});let e=i.apply(this,t);return t.forEach(r=>r.publish(this,e)),e})})}function $g(){return xe(i=>function(...t){let e=i.apply(this,t);return t.forEach(r=>r.unpublish()),e})}function Bg(){return xe(i=>function(...t){let e=i.apply(this,t);return t.forEach(r=>!r.isSubscribed&&r.subscribe(e)),e})}function DS({fn:i,context:t}){return function(...e){try{let r=i.apply(t,e);return qi(r)?r.catch(o=>$.error(`${i.name}() error observed ${o}`)):r}catch(r){$.error(`${i.name}() error observed ${r}`)}}}var Su=class{constructor(t){u(this,"_frameWorkType");u(this,"_component");u(this,"_language");u(this,"connectionType");u(this,"_room");u(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0});u(this,"_keyPrefix");u(this,"_log");u(this,"_intervalId");u(this,"_firstPublishedUserList");u(this,"_networkQuality");u(this,"_basicInfo");u(this,"_pathJoinRoom");u(this,"_pathLeaveRoom");u(this,"_pathMainVideoMap");u(this,"_pathMainAudioMap");u(this,"_pathAuxiliaryMap");u(this,"_remoteStreamStatMap");u(this,"_localStreamStat");u(this,"_eventMap",new Map);u(this,"_captureCostSum",0);u(this,"_captureCostCount",0);u(this,"isDestroyed",!1);this._frameWorkType=t.frameWorkType||30,this._component=t.component||0,this.connectionType=t.connectionType||1,this._language=t.language||0,this._room=t.room,this._keyPrefix="key_point",this._log=$.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(e=>{e.startsWith("handle")&&We(this[e])&&(this[e]=DS({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:at,uint32_os_type:15,string_device_name:"",string_http_user_agent:navigator.userAgent,string_os_version:"",uint32_avg_rtt:0,uint32_avg_up_loss:0,uint32_scene:this._room.scene==="live"?1:0,uint32_joining_duration:0,uint32_networkType:0,uint32_framework:this._frameWorkType,uint32_component:this._component,uint32_connection_type:this.connectionType,uint32_caller_coding_language:this._language,string_domain:location.hostname},this._pathJoinRoom={uint64_start_time:0,uint64_send_request_acc_ip_cmd_start_time:0,uint64_send_request_acc_ip_cmd_end_time:0,uint64_send_request_enter_room_cmd_start_time:0,uint64_send_request_enter_room_cmd_end_time:0,uint64_send_first_video_frame_time:0,uint64_recv_userlist_time:0,uint64_end_time:0,int32_send_request_acc_ip_cmd_ret:0,int32_send_request_enter_room_cmd_ret:0,int32_end_ret:0},this._pathLeaveRoom={uint64_start_time:0,uint64_send_request_exit_room_cmd_start_time:0,uint64_send_request_exit_room_cmd_end_time:0,uint64_end_time:0,int32_send_request_exit_room_cmd_ret:0,int32_end_ret:0},this._localStreamStat={totalVideoBitrate:0,totalVideoFPS:0,totalVideoHeight:0,totalVideoWidth:0,totalAudioLevel:0,videoCount:0,audioLevelCount:0,publishStartTime:0,statsToReport:{uint32_audio_capture_db:0,uint32_video_big_capture_fps:0,uint32_video_big_bitrate:0,uint32_video_big_resolution:0}},this._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,$o().then(t=>{this._basicInfo.string_os_version=Bo(),t?this._basicInfo.string_device_name=t.mobile?t.model:this._basicInfo.string_os_version:this._basicInfo.string_device_name=this._basicInfo.string_os_version})}addEvent(t,e){return this._eventMap.set(t,e),V.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(U.JOIN_START,this.handleJoinStart).addEvent(U.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(U.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(U.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(U.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(U.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(U.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(U.JOIN_FAILED,this.handleJoinFailed).addEvent(U.LEAVE_START,this.handleLeaveStart).addEvent(U.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(U.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(U.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(U.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(U.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(U.PUBLISH_START,this.handlePublishStart).addEvent(U.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(U.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(U.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(U.PLAY_TRACK_START,this.handlePlayStart).addEvent(U.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(U.PLAYER_STATE_CHANGED,({track:t,state:e,type:r})=>{!t.isRemote||!this.hitTest(t.room)||e==="PLAYING"&&(r===N.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))}).addEvent(U.SWITCH_ROOM_START,this.handleSwitchRoomStart).addEvent(U.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess).addEvent(U.SWITCH_ROOM_FAILED,this.handleSwitchRoomFailed).addEvent(U.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(U.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(U.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(U.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,c=r.hasAuxiliary;!o&&n&&this.handleRemoteStreamAdded(r.userId,"main"),!s&&c&&this.handleRemoteStreamAdded(r.userId,"auxiliary")}).addEvent(U.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)=>V.off(e,t)),this._eventMap.clear()}destroy(){this.uninstallEvents(),vt.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&&(P(t.params.frameWorkType)||(this._frameWorkType=t.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),P(t.params.component)||(this._component=t.params.component,this._basicInfo.uint32_component=this._component),P(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:c,request:l,response:m}=e;this._pathJoinRoom.int32_schedule_cost=r,this._pathJoinRoom.int32_schedule_local=o,this._pathJoinRoom.int32_schedule_dns=s,this._pathJoinRoom.int32_schedule_tcp=n,this._pathJoinRoom.int32_schedule_tls=c,this._pathJoinRoom.int32_schedule_request=l,this._pathJoinRoom.int32_schedule_response=m}}handleSignalConnectionStart({room:t}){this.hitTest(t)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time=Date.now())}handleSignalConnectionEnd({room:t,error:e}){this.hitTest(t)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time=Date.now(),e&&(this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret=e instanceof ue?Number(e.getExtraCode()||e.getCode()):q.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}handleJoinSendCMD(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now())}handleJoinReceivedCMDResponce(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=t.code,t.code!==0&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}handleJoinSuccess(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_end_time===0&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=t.room.getSignalInfo())}handleJoinFailed({room:t,error:e}){this.hitTest(t)&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret===0&&(this._pathJoinRoom.int32_end_ret=e.code||this._pathJoinRoom.int32_send_request_enter_room_cmd_ret||this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret),setTimeout(()=>{this.report()}))}handleReceivedPublishUserList(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_recv_userlist_time===0&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=t.publishedUserList||[])}handleSendFirstVideoFrame({room:t}){this.hitTest(t)&&this._pathJoinRoom.uint64_send_first_video_frame_time===0&&this._pathJoinRoom.uint64_start_time!==0&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now())}handleLeaveStart(t){this.hitTest(t.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(t){this.hitTest(t.room)&&this._pathLeaveRoom.uint64_end_time===0&&(this._pathLeaveRoom.uint64_end_time=Date.now(),this._pathJoinRoom.uint64_end_time!==0?this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time:this._log.warn("pathJoinRoom endTime is 0"),this.report())}handleLeaveSendCMD(t){this.hitTest(t.room)&&(this._pathLeaveRoom.uint64_send_request_exit_room_cmd_start_time=Date.now(),this._pathLeaveRoom.uint64_send_request_exit_room_cmd_end_time=Date.now())}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 ue?Number(e.getExtraCode()||e.getCode()):q.UNKNOWN)}}handleRemoteStreamAdded(t,e){var o;let r=`${t}_${e}`;if(!this._remoteStreamStatMap.has(r)){let s={userId:t,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:Te(z({},MS),{msg_user_info:new $a({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:c}=e,l=new $a({userId:s,tinyId:n,role:c==="anchor"?20:21}),m=Date.now(),E=`${s}_${r}`,g=this._remoteStreamStatMap.get(E);g&&g.subscribeStartTime===0&&(g.subscribeStartTime=m),r==="main"?(e.muteState.hasVideo&&(o.video||o.smallVideo)&&!this._pathMainVideoMap.has(E)&&this._pathMainVideoMap.set(E,{statsToReport:{msg_user_info:l,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:s,sendSubscribeCMDTime:m}),e.muteState.hasAudio&&o.audio&&!this._pathMainAudioMap.has(E)&&this._pathMainAudioMap.set(E,{statsToReport:{msg_user_info:l,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:s,sendSubscribeCMDTime:m})):e.muteState.hasAuxiliary&&o.auxiliary&&!this._pathAuxiliaryMap.has(E)&&this._pathAuxiliaryMap.set(E,{sendSubscribeCMDTime:m})}handleSubscribed({room:t,remotePublishedUser:e,streamType:r}){if(this.hitTest(t)){let o=`${e.userId}_${r}`,s=this._remoteStreamStatMap.get(o);s&&s.subscribedTime===0&&(s.subscribedTime=Date.now())}}handlePlayStart({track:t}){if(!t.isRemote||!this.hitTest(t.room))return;let e=`${t.userId}_${t.streamType}`,r=this._remoteStreamStatMap.get(e);(r==null?void 0:r.playStreamTime)===0&&(r.playStreamTime=Date.now())}handleVideoLoadedData({track:t}){if(!t.isRemote||!this.hitTest(t.room))return;let e=`${t.userId}_${t.streamType}`,r=this._pathMainVideoMap.get(e);r&&r.statsToReport.uint64_combine_first_frame_time===0&&(r.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(t){let e=`${t.userId}_${t.streamType}`,r=Date.now(),o=this._pathMainVideoMap.get(e),s=this._remoteStreamStatMap.get(e);if(s){let{statsToReport:n}=s;if(!n.uint32_video_render_first&&t.streamType==="main"?this.hasVideoFlag(t.userId):this.hasAuxFlag(t.userId)){let c=r-this._pathJoinRoom.uint64_start_time;n.uint32_video_render_first=c,Q.addNumber({key:516820,value:c})}}(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 c=this._networkQuality.totalDownlinkRTTAndLossMap.get(o);if(c)c.totalRTT+=e,c.totalLoss+=r,s&&(c.totalVideoDelay=(c.totalVideoDelay||0)+s,c.videoDelayCount=(c.videoDelayCount||0)+1),n&&(c.totalAudioDelay=(c.totalAudioDelay||0)+n,c.audioDelayCount=(c.audioDelayCount||0)+1),c.count++;else{let l,m,E,g;s&&(m=s,E=1),n&&(l=n,g=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(o,{totalRTT:e,totalLoss:r,count:1,totalAudioDelay:l,totalVideoDelay:m,audioDelayCount:g,videoDelayCount:E})}}))}handleHeartbeatStats(t){if(this.hitTest(t.room)){let{msg_device_info:e,msg_up_stream_info:r,msg_down_stream_info:o}=t.report;if(r.msg_video_status[0]){let{uint32_video_codec_bitrate:s,uint32_video_enc_fps:n,uint32_video_width:c,uint32_video_height:l}=r.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=s,this._localStreamStat.totalVideoFPS+=n,this._localStreamStat.totalVideoWidth+=c,this._localStreamStat.totalVideoHeight+=l,this._localStreamStat.videoCount++}if(r.msg_audio_status){let{uint32_audio_level:s}=r.msg_audio_status;Math.floor(s/mi*100)>0&&(this._localStreamStat.totalAudioLevel+=s/mi,this._localStreamStat.audioLevelCount++)}o.forEach(s=>{let{msg_user_info:n,msg_audio_status:c,msg_video_status:l}=s,m=n.str_identifier,E=this._room.remotePublishedUserMap.get(m);if(l.forEach(g=>{let _=g.uint32_video_stream_type===2,v=g.uint32_video_stream_type===7,L=`${m}_${_?"main":"auxiliary"}`,x=this._remoteStreamStatMap.get(L);if(x&&(_&&(E!=null&&E.remoteVideoTrack.isSubscribed)||v&&(E!=null&&E.remoteAuxiliaryTrack))){x.totalVideoFPS+=g.uint32_video_receive_fps,x.totalVideoBitrate+=g.uint32_video_codec_bitrate,x.videoCount++,x.statsToReport.uint32_video_width===0&&(x.statsToReport.uint32_video_width=g.uint32_video_width),x.statsToReport.uint32_video_height===0&&(x.statsToReport.uint32_video_height=g.uint32_video_height);let M=_?E.remoteVideoTrack:E.remoteAuxiliaryTrack;M.stat.jitterBufferDelay&&(x.videoJitterBufferDelay=M.stat.jitterBufferDelay),M.stat.framesReceived&&(x.statsToReport.uint32_video_consume_render_rate=Math.floor(M.stat.framesDecoded/M.stat.framesReceived*Wi(10,6)))}}),!Cs(c)){let g=`${m}_main`,_=this._remoteStreamStatMap.get(g);this._remoteStreamStatMap.has(g)&&_&&E!=null&&E.remoteAudioTrack.isSubscribed&&(_.totalAudioBitrate+=c.uint32_audio_codec_bitrate,_.audioCount++,E.remoteAudioTrack.stat.jitterBufferDelay&&(_.audioJitterBufferDelay=E.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(c.uint32_audio_level/mi*100)>0&&(_.totalAudioLevel+=c.uint32_audio_level/mi,_.audioLevelCount++))}}),e.uint32_audio_capture_cost&&(this._captureCostSum+=e.uint32_audio_capture_cost,this._captureCostCount+=1,this._captureCostCount>=100&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0))}}handlePublishStart({room:t}){this.hitTest(t)&&this._localStreamStat.publishStartTime===0&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart({track:t}){t.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),t.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess({track:t}){t.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=0,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),t.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=0,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed({track:t,error:e}){let o={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[e.name]||(e instanceof ue?e.getExtraCode()||e.getCode():q.UNKNOWN);t.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=o,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),t.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=o,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}hasVideoFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&ys)>=0}hasAudioFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&bs)>=0}hasAuxFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&Dn)>=0}hitTest(t){return t===this._room}prepareReport(){if(this._captureCostCount>0&&!this._basicInfo.uint32_audio_capture_cost&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0),this._networkQuality.count>0&&(this._basicInfo.uint32_avg_rtt=Math.floor(this._networkQuality.totalUplinkRTT/this._networkQuality.count),this._basicInfo.uint32_avg_up_loss=Math.floor(this._networkQuality.totalUplinkLoss/this._networkQuality.count)),this._localStreamStat.videoCount>0){this._localStreamStat.statsToReport.uint32_video_big_capture_fps=Math.floor(this._localStreamStat.totalVideoFPS/this._localStreamStat.videoCount),this._localStreamStat.statsToReport.uint32_video_big_bitrate=Math.floor(this._localStreamStat.totalVideoBitrate/this._localStreamStat.videoCount);let t=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),e=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=t<<16|e}this._localStreamStat.audioLevelCount>0&&(this._localStreamStat.statsToReport.uint32_audio_capture_db=Math.floor(this._localStreamStat.totalAudioLevel/this._localStreamStat.audioLevelCount*100)),this._remoteStreamStatMap.forEach((t,e)=>{let{userId:r}=t,o=this._networkQuality.totalDownlinkRTTAndLossMap.get(r);if(o){let{totalLoss:E,count:g,audioDelayCount:_,videoDelayCount:v,totalAudioDelay:L,totalVideoDelay:x}=o;t.statsToReport.uint32_avg_down_loss=Math.floor(E/g),_&&L&&(t.statsToReport.uint32_audio_network_p2p_delay=Math.floor(L/_),t.audioJitterBufferDelay&&(t.statsToReport.uint32_p2p_delay=Math.floor(t.statsToReport.uint32_audio_network_p2p_delay+t.audioJitterBufferDelay))),v&&x&&(t.statsToReport.uint32_video_network_p2p_delay=Math.floor(x/v))}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,N.AUDIO),t.statsToReport.uint32_video_play_time=s.getDuration(e,N.VIDEO)),t.statsToReport.uint32_video_render_first&&(t.statsToReport.uint32_video_render_first=Math.min(t.statsToReport.uint32_video_render_first,cs));let{badCaseDetector:n}=this._room,{dataFreeze:c,count:l}=n.getDataFreezeDuration(e),{renderFreeze:m}=n.getRenderFreezeDuration(e);t.statsToReport.uint32_video_block_count=l,t.statsToReport.uint32_video_block_time=Math.min(c,t.statsToReport.uint32_video_play_time),t.statsToReport.uint32_video_external_block_time=Math.min(m,t.statsToReport.uint32_video_play_time),n.isBlackStream(e)&&t.statsToReport.uint32_video_avg_fps===0?t.statsToReport.uint32_video_black_screen_subjective=1:t.statsToReport.uint32_video_black_screen_subjective=0}),this._pathMainAudioMap.forEach((t,e)=>{if(!this.hasAudioFlag(t.userId)){this._pathMainAudioMap.delete(e);return}t.statsToReport.uint64_play_first_frame_time-t.statsToReport.uint64_start_enter_time>cs&&(t.statsToReport.uint64_play_first_frame_time=t.statsToReport.uint64_start_enter_time+cs)}),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>cs&&(t.statsToReport.uint64_render_first_frame_time=t.statsToReport.uint64_start_enter_time+cs)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>cs&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+cs)}getReportData(){this._basicInfo.uint32_networkType=Ac();let t={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new $a({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:Ns(this._signalInfo.relayIp),uint32_client_ip:Ns(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*Wi(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:Ns(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,bytes_report_buf_from_0x1:this._signalInfo.endReportExtend};return Vn(t),t}report(){return A(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 A(this,null,function*(){if(t.msg_path_enter_room.uint64_start_time===0)return;let e=Number(this._room.sdkAppId),r=yield dl(t),o=r instanceof ArrayBuffer,s=`${oi(e,ji.KEY_POINT)}&gzip=${+o}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(s,r));let c=[this.uploadKVStat(Q),this.uploadKVStat(qo)];n||c.push(ni({url:s,body:r,priority:"low"})),yield Promise.all(c)})}setConnectionType(t){this.connectionType=t,this._basicInfo.uint32_connection_type=t}uploadKVStat(t){return A(this,null,function*(){let e=t.getReportData();if(e.stats_count.length===0&&e.stats_distribution.length===0)return;e.msg_sdk_basic_info=Te(z({},e.msg_sdk_basic_info),{bytes_device_name:this._basicInfo.string_device_name||"",bytes_os_version:this._basicInfo.string_os_version||"",uint32_framework:this._frameWorkType,uint32_network_type:this._basicInfo.uint32_networkType||0}),this._log.debug(e);let r=yield dl(e),o=`${oi(+this._room.sdkAppId,ji.KV_STAT)}&gzip=${+(r instanceof ArrayBuffer)}`,s=!1;navigator.sendBeacon&&(s=navigator.sendBeacon(o,r)),s||ni({url:o,body:r})})}};Z([zo({settings:{timeout:500,retries:3}})],Su.prototype,"upload",1);var cs=5e3,MS={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},$a=class{constructor(t){u(this,"str_identifier");u(this,"str_tinyid");u(this,"uint32_role");this.str_identifier=String(t.userId),this.str_tinyid=String(t.tinyId||0),this.uint32_role=t.role}},Hg=Su;var Np=class{constructor(){u(this,"_startTime");u(this,"_endTime");this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=Ie())}stop(){this._endTime===0&&(this._endTime=Ie())}getDuration(){return this._endTime===0?Ie()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},Au=Np;var Dp=class{constructor(t){u(this,"_room",null);u(this,"_durationMap");u(this,"_eventMap",new Map);this._room=t.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(U.REMOTE_TRACK_SUBSCRIBED,this.handleSubscribed).set(U.REMOTE_TRACK_UNSUBSCRIBED,this.handleUnsubscribed).set(U.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`,N.AUDIO),e.hasVideo&&!r.hasVideo&&this.stopDurationItem(`${o}_main`,N.VIDEO),e.hasAuxiliary&&!r.hasAuxiliary&&this.stopDurationItem(`${o}_auxiliary`,N.VIDEO);let s=(n=this._room)==null?void 0:n.remotePublishedUserMap.get(o);s&&(!e.hasAudio&&r.hasAudio&&s.remoteAudioTrack.isSubscribed&&this.addDuractionItem(o,N.AUDIO,"main"),!e.hasVideo&&r.hasVideo&&s.remoteVideoTrack.isSubscribed&&this.addDuractionItem(o,N.VIDEO,"main"),!e.hasAuxiliary&&r.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(o,N.VIDEO,"auxiliary"))}),this._eventMap.forEach((t,e)=>V.on(e,t,this))}uninstallEvents(){this._eventMap.forEach((t,e)=>V.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 Au,n=this._durationMap.get(o);n?this.isRecording(n[e])||n[e].push(s):this._durationMap.set(o,{userId:t,type:r,audio:e===N.AUDIO?[s]:[],video:e===N.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()}},Wg=Dp;var Mp=class{constructor(t){u(this,"_room");u(this,"_renderFreezeMap",new Map);u(this,"_isVideoPlayingEventFiredMap",new Map);u(this,"_dataFreezeMap",new Map);u(this,"_monitorFreezeData",new Map);u(this,"_eventMap",new Map);this._room=t.room,this.installEvents()}getRenderFreezeMap(){return this._renderFreezeMap}getDataFreezeMap(){return this._dataFreezeMap}installEvents(){this._eventMap.set(U.LEAVE_SUCCESS,({room:t})=>{this.hitTest(t)&&this.stop()}).set(U.PLAY_TRACK_START,this.onPlayTrackStart).set(U.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(U.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(U.PLAYER_STATE_CHANGED,({track:t,state:e,reason:r,type:o})=>{if(!(!t.isRemote||!t.room||!this.hitTest(t.room)||o!==N.VIDEO)){if(e==="PLAYING"){let s=`${t.userId}_${t.streamType}`;this._isVideoPlayingEventFiredMap.set(s,!0)}r===N.MUTE?this.onVideoTrackMuted(t):r===N.UNMUTE&&this.onVideoTrackUnmuted(t)}}).set(U.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach((t,e)=>V.on(e,t,this))}uninstallEvents(){this._eventMap.forEach((t,e)=>V.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 Au;s?s.durationItemList.push(n):this._dataFreezeMap.set(o,{userId:e,type:r,durationItemList:[n],isFreezing(){let c=this.durationItemList[this.durationItemList.length-1];return c&&c.endTime===0}})}onVideoTrackUnmuted(t){if(!t.isSubscribed)return;let{userId:e,streamType:r}=t,o=`${e}_${r}`;this.stopDataFreeze({key:o,userId:e,type:r})}onHearBeatReport({room:t,report:e}){this.hitTest(t)&&e.msg_down_stream_info.forEach(r=>{let o=this._room.remotePublishedUserMap.get(r.msg_user_info.str_identifier);if(!o)return;let{userId:s,muteState:n}=o;r.msg_video_status.forEach(c=>{c.uint32_video_stream_type===2&&n.hasVideo&&!n.videoMuted&&o.remoteVideoTrack.isSubscribed&&this.handleRenderFreeze({userId:s,fps:c.uint32_video_dec_fps,type:"main"}),c.uint32_video_stream_type===7&&n.hasAuxiliary&&o.remoteAuxiliaryTrack.isSubscribed&&this.handleRenderFreeze({userId:s,fps:c.uint32_video_dec_fps,type:"auxiliary"})})})}stopDataFreeze({key:t,userId:e,type:r}){let o=this._dataFreezeMap.get(t);if(!o||!o.isFreezing())return;let s=o.durationItemList[o.durationItemList.length-1];s.stop();let n=s.getDuration();n>Ic?this._monitorFreezeData.set(t,{userId:e,type:r,duration:n}):o.durationItemList.pop()}getTotalDuration(t){return t.reduce((e,r)=>{let o=r.getDuration();return e+Math.min(o,5e3)},0)}handleRenderFreeze(o){return A(this,arguments,function*({userId:t,fps:e,type:r}){let s=`${t}_${r}`,n=this._renderFreezeMap.get(s);if(e<=2){let c=Ie();n&&!n.isFreeze&&(n.freezeTimeline.push({startTime:c,endTime:0}),n.isFreeze=!0),n||this._renderFreezeMap.set(s,{userId:t,type:r,isFreeze:!0,freezeTimeline:[{startTime:c,endTime:0}],renderFreezeTotal:0})}else if(n&&n.isFreeze){n.isFreeze=!1;let c=n.freezeTimeline.pop();if(c){c.endTime=Ie();let l=c.endTime-c.startTime;n.freezeTimeline.push(c),n.renderFreezeTotal+=Math.min(5e3,l)}}})}onPlayTrackStart({track:t}){if(!t.isRemote||!this.hitTest(t.room)||t.kind!==N.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()<Ic&&r.durationItemList.pop()}e.dataFreeze=this.getTotalDuration(r.durationItemList),e.count=r.durationItemList.length}return e}getRenderFreezeDuration(t){let e=this._renderFreezeMap.get(t),r=0,o=0;if(e)if(!e.isFreeze)r=e.renderFreezeTotal;else{let s=Ie(),n=e.freezeTimeline[e.freezeTimeline.length-1],c=s-n.startTime;r=e.renderFreezeTotal+Math.min(c,5e3),o=e.freezeTimeline.length}return{renderFreeze:r,count:o}}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(t){return this._isVideoPlayingEventFiredMap.has(t)?!this._isVideoPlayingEventFiredMap.get(t):!1}resetMonitor(){this._monitorFreezeData.clear()}hitTest(t){return t===this._room}destroy(){this.uninstallEvents()}},Gg=Mp;var qg=Gi(Zi(),1);var wS=[1,0,0,0,1,1,0,1],yu=class extends Gt{constructor(e,r,o,s){super(e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"transform",logger:r});u(this,"mirror",!1);u(this,"rotation",0);if(o&&(this.mirror=o),s&&(this.rotation=s),e instanceof Tt)try{this.setTexBuffer(wS)}catch(n){e.destroy(new ue({code:q.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${n.message||n}`}))}}draw2d(e,r,o,s,n){if(this.ctx2d){this.ctx2d.save(),this.mirror&&(this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0)),this.rotation===90?(this.ctx2d.translate(s,0),this.ctx2d.rotate(Math.PI/2),this.ctx2d.scale(n/s,s/n)):this.rotation===180?(this.ctx2d.translate(this.width,this.height),this.ctx2d.rotate(Math.PI)):this.rotation===270&&(this.ctx2d.translate(0,n),this.ctx2d.rotate(3*Math.PI/2),this.ctx2d.scale(n/s,s/n));let c=super.draw2d(e,r,o,s,n);return this.ctx2d.restore(),c}return!1}render(e){var r;return(r=this.input)!=null&&r.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}};var wp=class{constructor(t,e){this.node=t;this.layout=e;u(this,"positionBuffer")}get x(){return this.layout.x||this.node.x}get y(){return this.layout.y||this.node.y}get width(){return this.layout.width||this.node.width}get height(){return this.layout.height||this.node.height}get right(){return this.x+this.width}get bottom(){return this.y+this.height}},Ba=class extends Gt{constructor(e,r){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,matchInputSize:!1,logger:r});u(this,"inputs",[])}addInput(e,r){if(this.inputs[r.zIndex])throw new Error("input already exists");let o=new wp(e,r);this.inputs[r.zIndex]=o}changeInputLayout(e,r){let o=this.inputs.findIndex(s=>s?s.node===e:!1);o<0||Object.entries(r).forEach(([s,n])=>{P(n)||(this.inputs[o].layout[s]=n)})}resize(e,r){if(!this.matchInputSize){super.resize(e,r);return}let o=this.inputs.reduce((s,n)=>n?Object.assign(s,{width:Math.max(s.width,n.right),height:Math.max(s.height,n.bottom)}):s,{width:0,height:0});super.resize(o.width,o.height),this.context instanceof Tt&&this.inputs.forEach(s=>{if(s){let n=this.layout2texCoords(s);s.positionBuffer?this.changeBufferData(s.positionBuffer,n):s.positionBuffer=this.createBuffer(n)}})}connect(e,...r){return super.connect(e,...r),this.matchInputSize&&this.resize(0,0),e}removeInput(e){this.inputs[this.inputs.findIndex(r=>(r==null?void 0:r.node)===e)]=void 0}render(e){let r=this.context.ctx;if(r.clearColor(0,0,0,0),this.inputs.reduce((s,n)=>(n==null?void 0:n.node.requestFrame(e))||s,!1)&&r){this.useProgram(),r.enable(r.BLEND),r.blendFunc(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let s=0;s<this.inputs.length;s++){let n=this.inputs[s];n&&(n.node.useTexture(),this.draw(n.positionBuffer))}return!0}return!1}render2d(e){if(this.inputs.reduce((o,s)=>(s==null?void 0:s.node.requestFrame(e))||o,!1)&&this.ctx2d){this.ctx2d.fillStyle="black",this.ctx2d.fillRect(0,0,this.width,this.height);for(let o=0;o<this.inputs.length;o++){let s=this.inputs[o];s&&this.draw2d(s.node.image,s.x,s.y,s.width,s.height)}return!0}return!1}getInfo(){let{totalFrames:e,x:r,y:o,width:s,height:n,name:c}=this,l=Date.now(),m=(e-this.lastInfo.totalFrames)/((l-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:r,y:o,width:s,height:n,timestamp:l,fps:m,name:c},z({parent:this.inputs.filter(E=>E).map(E=>E.node.getInfo())},this.lastInfo)}close(){super.close(),this.inputs.forEach(e=>{var r,o;if(e&&((r=e.node)==null||r.disconnect(),e.positionBuffer&&this.context instanceof Tt))try{(o=this.context.ctx)==null||o.deleteBuffer(e.positionBuffer)}catch(s){}})}};var bu=class{constructor(t,e,r,o=4/3){this.vbMode=t;this.faceDetector=e;this.logger=r;u(this,"animationState");u(this,"originalAspect");u(this,"totalOffsetX",0);u(this,"totalOffsetY",0);u(this,"defaultScaleRatio",.1);u(this,"isRecovering",!1);u(this,"boundaryY",280);u(this,"lastActionTime",0);u(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.faceDetector),this.originalAspect=o||4/3}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?Q.addSuccessEvent({key:s.key}):Q.addFailedEvent({key:s.key,error:s.error}))}actionCentering(t){let e=Date.now();if(this.animation(),!this.faceDetector||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;try{let s=this.faceDetector.detectForVideo(t,Date.now());if(s.detections.length<=0){this.vbMode===1&&this.recoverOriginal(r,o);return}let n=s.detections[0].boundingBox,c=n.originX,l=n.originY,m=n.width,E=n.height;this.vbMode===1?this.dualStageCropping(r,o,c,l,m,E):this.vbMode===2&&this.movingPortrait(r,o,c,l,m,E)}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,c=.4){let l=t+r/2,m=e+o/2,E,g,{min:_,offset:v}=this.calculateBoundary(l,s,t,r),{min:L,offset:x}=this.calculateBoundary(m,n,e,o);return E=2*_+r,g=2*L+o,E/g>this.originalAspect?(E=g*this.originalAspect,v=l-E/2):(g=E/this.originalAspect,x=m-g/2),r/s>c&&(v=0,x=0,E=s,g=n),v=Math.max(0,Math.min(v,s-E)),x=Math.max(0,Math.min(x,n-g)),{sx:v,sy:x,cropWidth:E,cropHeight:g,timestamp:Date.now()}}processFacePositionCrop(t,e,r){if(!this.animationState.current||!this.animationState.target){let c={sx:0,sy:0,cropWidth:e,cropHeight:r,timestamp:Date.now()};this.animationState.current=c,this.animationState.target=c;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=z({},t),this.animationState.target=z({},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)),ke(this.animationState.current.scaleOffsetX)&&ke(this.animationState.target.scaleOffsetX)&&ke(this.animationState.current.scaleOffsetY)&&ke(this.animationState.target.scaleOffsetY)){let n=(this.animationState.target.scaleOffsetX-this.animationState.current.scaleOffsetX)*r(e);this.animationState.current.scaleOffsetX+=n;let c=(this.animationState.target.scaleOffsetY-this.animationState.current.scaleOffsetY)*r(e);this.animationState.current.scaleOffsetY+=c}}e>=1&&(this.animationState.animating=!1,this.animationState.current=this.animationState.target,this.isRecovering=!1)}positionDistance(t,e){return Math.sqrt(Wi(t.sx-e.sx,2)+Wi(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,c=.3){if(this.isRecovering)return;let l=this.calculateTargetPosition(r,o,s,n,t,e);this.processFacePositionCrop(l,t,e),s*n/l.cropWidth/l.cropHeight>c&&this.recoverOriginal(t,e)}movingPortrait(t,e,r,o,s,n){var l,m,E,g,_,v,L,x,M,B,ee,pe;let c={sx:r+s/2+this.totalOffsetX,sy:o+n/2+this.totalOffsetY,cropWidth:t,cropHeight:e,scaleRatio:(m=(l=this.animationState.current)==null?void 0:l.scaleRatio)!=null?m:1,scaleOffsetX:(g=(E=this.animationState.current)==null?void 0:E.scaleOffsetX)!=null?g:0,scaleOffsetY:(v=(_=this.animationState.current)==null?void 0:_.scaleOffsetY)!=null?v:0,timestamp:Date.now()};this.animationState.target={sx:t/2,sy:o+n/2,cropWidth:t,cropHeight:e,scaleRatio:(x=(L=this.animationState.target)==null?void 0:L.scaleRatio)!=null?x:1,scaleOffsetX:(B=(M=this.animationState.target)==null?void 0:M.scaleOffsetX)!=null?B:0,scaleOffsetY:(pe=(ee=this.animationState.target)==null?void 0:ee.scaleOffsetY)!=null?pe: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(c)}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 OS=`#version 300 es
|
|
101
|
+
2. If the user is in Chrome 70 and below, when the div container is moved, the playback will be paused.`,color:"orange",class:"orange",textColor:"#fff"},'"displaySurface":"window"':{tips:"Screen sharing captures the application window",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"monitor"':{tips:"Screen sharing captures the entire screen",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"browser"':{tips:"Screen sharing captures a certain tab page",color:"blue",class:"blue",textColor:"#fff"},updateMediaSettings:{tips:"The resolution and frame rate below are the actual resolution and frame rate captured",color:"blue",class:"blue",textColor:"#fff"},"main stream start to play with":{tips:"Call remoteStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"stream start to play with":{tips:"Call localStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"main setAudioVolume to 0":{tips:"Business side calls remoteStream.setAudioVolume(0) interface to set the playback volume to 0, which will cause the playback to be silent",color:"orange",class:"orange",textColor:"#fff"},"screen sharing was stopped because the video track is ended":{tips:"Screen sharing capture stopped, possible reasons: user clicks the stop button, the window/page shared by the user is closed, etc.",color:"orange",class:"orange",textColor:"#fff"},"Join() => joining room":{tips:"Call client.join interface",color:"blue",class:"blue",textColor:"#fff"},"publish() => publishing local stream":{tips:"Call client.publish interface",color:"blue",class:"blue",textColor:"#fff"},"subscribe() => subscribe to":{tips:"Call client.subscribe interface",color:"blue",class:"blue",textColor:"#fff"},"switchRole() => switch role":{tips:"Call client.switchRole interface",color:"blue",class:"blue",textColor:"#fff"}};["enterRoom","exitRoom","switchRole","destroy","startLocalAudio","updateLocalAudio","stopLocalAudio","startLocalVideo","updateLocalVideo","stopLocalVideo","startScreenShare","updateScreenShare","stopScreenShare","startRemoteVideo","updateRemoteVideo","stopRemoteVideo","muteRemoteAudio","setRemoteAudioVolume"].forEach(i=>{Og[`${i}()`]={tips:`Call trtc.${i}`,color:"blue",class:"blue",textColor:"#fff"}});var _k=Object.keys(Og);var RS=0,gu,La=class La{constructor(t){this.core=t;u(this,"_core");u(this,"log");u(this,"dumpLocalVideoMap",{});u(this,"dumpRemoteVideoMap",{});u(this,"dialog");this._core=t,this.log=t.log.createChild({id:`${this.getAlias()}${++RS}`}),this.log.info("created")}getName(){return La.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 A(this,null,function*(){var e;!new URLSearchParams(location.search).has("trtcDebug")&&((e=window.sessionStorage)==null?void 0:e.getItem("TRTC_ENABLE_DEBUG_PLUGIN"))!=="true"||(yield this.openDebugDiaLog(),this.addVideoProcessor())})}update(e){return A(this,arguments,function*({forceOpen:t}){P(t)&&(t?(yield this.openDebugDiaLog(),this.addVideoProcessor()):(this.closeDebugDiaLog(),this.removeVideoProcessor()))})}stop(){this.closeDebugDiaLog(),this.removeVideoProcessor()}destroy(){this.stop()}openDebugDiaLog(){return A(this,null,function*(){var t;if(!this.dialog)try{if(gu)yield gu;else{let e=new URLSearchParams(location.search).get("trtcDebugDialogPath")||((t=window.sessionStorage)==null?void 0:t.getItem("TRTC_DEBUG_DIALOG_PATH"))||`https://unpkg.com/${Ng}@${at}/assets/debug-dialog.js`;gu=this._core.fileDownloader.loadScript(e),yield gu}this.dialog=new TRTCDebugDialog(this._core,this.log,this.dumpLocalVideoMap,this.dumpRemoteVideoMap),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(e){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(e))}})}closeDebugDiaLog(){this.dialog&&(this.dialog.closeDialog(),this.dialog=null)}addVideoProcessor(){this._core.room.videoManager.addEncodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.encodeVideo.bind(this):bp,type:1}),this._core.room.videoManager.addDecodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.decodeVideo.bind(this):Rp,type:1})}removeVideoProcessor(){this._core.room.videoManager.removeEncodeProcessor({type:1}),this._core.room.videoManager.removeDecodeProcessor({type:1})}encodeVideo({frame:t,mediaType:e}){return bp({frame:t,onDump:()=>{if(!e)return;let r=e===2?"sub":"main",o=this.dumpLocalVideoMap[r];o&&(o.data.push(t.data.slice(0)),o.duration>0&&Date.now()-o.startTimestamp>o.duration*1e3&&o.onDumpEnd())}})}decodeVideo({frame:t,track:e}){return Rp({frame:t,onDump:()=>{if(!e)return;let r=this.dumpRemoteVideoMap[`${e.userId}-${e.streamType}`];r&&(r.data.push(t.data.slice(0)),r.duration>0&&Date.now()-r.startTimestamp>r.duration*1e3&&r.onDumpEnd())}})}};u(La,"Name","Debug"),u(La,"autoStart",!0);var Eu=La;var xg=i=>{switch(i){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},_u=class{constructor(t,e,r){u(this,"trackDoneOB");u(this,"startOB");u(this,"stopOB");u(this,"inputFrameCount",0);u(this,"decodedFrameCount",0);u(this,"type","auto");u(this,"config");u(this,"decoder");u(this,"_decodeSink");let{kvStatManager:o,trtc:s}=t;this.config=r.config,this.trackDoneOB=Ce(e,de.INIT),this.stopOB=At(),this.startOB=At(),r.type==="auto"?this.type="webCodecs":this.type=r.type;let n=At(),c=l=>{let m=this.pipe(e);return n.next("STARTING"),e.log.info(`decoder type: ${this.type}`),be(m,Ye(this.stopOB),Le(()=>{},E=>{e.log.error(E),o.addFailedEvent({key:xg(this.type),error:E}),l>4?this.startOB.error(E):this.startOB.next(l+1)})),be(m,Nr(1),Km(va))};be(this.startOB,ba(0),no(c),Ye(this.stopOB),Le(()=>{e.player.setOutput(),n.next("STARTED")},l=>{n.next("FAILED")},()=>{o.addSuccessEvent({key:xg(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 Si()(e=>A(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"}))}},vS={type:"object"},Ua=class Ua{constructor(t){this.core=t;u(this,"log");u(this,"contextMap",new Map);u(this,"decodeProcessorMap",new WeakMap);this.log=t.log.createChild({id:`${this.getAlias()}`})}getAlias(){return Ua.Name}getGroup(t){return t.track.userId+t.track.streamType}getName(){return Ua.Name}getValidateRule(t){return vS}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 _u(this.core,r,t);return be(o.trackDoneOB,Nr(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 _u(this.core,t.track,t))}}};u(Ua,"Name","TRTCAudioDecoder");var Va=Ua;var Tu=class{constructor(){u(this,"log");this.log=$.createLogger({id:"exp"})}call(t,e){return A(this,null,function*(){return We(this[t])?this[t](e):Promise.reject(new ue({code:q.INVALID_PARAMETER,message:Be({key:$e.API_NOT_EXIST,data:{name:t}})}))})}enableAudioFrameEvent(t){return A(this,null,function*(){let{trtcInstance:e,enable:r,userId:o,sampleRate:s=48e3,channelCount:n=1,port:c}=t,{audioManager:l}=e.room,{getPCMAbortCtrlMap:m,audioFrameEventConfigMap:E}=l;if(E.set(o,{enable:r,sampleRate:s,channelCount:n,port:c}),r)if(o==="*")e.room.remotePublishedUserMap.forEach(g=>{if(g.remoteAudioTrack.isAvailable){if(m.get(g.userId))return;let _=l.getPCM(v=>{e.emit(re.AUDIO_FRAME,v)},g.userId);m.set(g.userId,_)}});else{if(m.get(o))return;let g=l.getPCM(_=>{e.emit(re.AUDIO_FRAME,_)},o);m.set(o,g)}else if(o==="*")e.room.remotePublishedUserMap.forEach(g=>{if(g.remoteAudioTrack.isSubscribed){let{userId:_}=g,v=m.get(_);v==null||v.abort("disable"),m.delete(_)}});else{let g=m.get(o);g==null||g.abort("disable"),m.delete(o)}})}};Z([Qf({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"}}})],Tu.prototype,"enableAudioFrameEvent",1);var Pg=new Tu;var kg=0,Fa=new Set,Ct=null;Yu(Dg);Hs.checkStorage();var CS={RtcError:ne,ErrorCode:le,ErrorCodeDictionary:pr},Se=class Se extends Lg.EventEmitter{constructor(e,r){super();u(this,"_room");u(this,"_eventListened",new Set);u(this,"_localVideoTrack",null);u(this,"_localAudioTrack",null);u(this,"_localScreenTrack",null);u(this,"_localScreenAudioTrack",null);u(this,"_localVideoConfig",null);u(this,"_localScreenConfig",null);u(this,"_localAudioConfig",null);u(this,"_remoteVideoConfigMap",new Map);u(this,"_remoteAudioConfigMap",new Map);u(this,"_remoteAudioVolumeMap",new Map);u(this,"_remoteAudioMuteMap",new Map);u(this,"_mediaTrackMap",new WeakMap);u(this,"_log",$.createLogger({id:`t${++kg}`}));u(this,"_plugins",new Map);u(this,"_networkQuality",null);u(this,"_speakerId");u(this,"enterRoomParams");this._room=new e(z({logger:this._log,frameWorkType:Se.frameWorkType},r)),this._room.videoDecodeFallbackType=r.videoDecodeFallback,this._log.info(`create() ${JSON.stringify(r,(o,s)=>o==="plugins"?s.map(n=>n.Name):s)}`),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(o){return this._room.audioManager.dump(o)}}}),r.plugins&&r.plugins.forEach(o=>{this._use(o,r.assetsPath)}),this._use(mu,r.assetsPath),this._use(uu,r.assetsPath),this._use(hu,r.assetsPath),this._use(Va,r.assetsPath||pc),this._use(Eu),r.enableSEI&&ua&&this._use(fu),this._room.on("audio-volume",o=>{!o.find(s=>s.userId==="")&&this._localAudioTrack&&o.push({userId:"",volume:Math.floor(this._localAudioTrack.getAudioLevel()*100)}),r.volumeType===1&&o.forEach(s=>{var c;let n=s.userId===""?this._localAudioTrack:(c=this.room.remotePublishedUserMap.get(s.userId))==null?void 0:c.remoteAudioTrack;n&&(s.volume=n.dbVolume)}),this.emit(re.AUDIO_VOLUME,{result:o.sort((s,n)=>n.volume-s.volume)})}),this._room.videoManager.on("error",o=>{this._log.error(new ne({code:le.OPERATION_FAILED,extraCode:5504,message:o.message,originError:o}))}),this._listenEvents(),this._initActiveSpeaker(),bg(this,"trtc")}static create(e){}static _create(e,r){cg();let o=new Se(e,r||{});return Fa.add(o),o}get room(){return this._room}_listenEvents(){Vt(this,this._room).add("peer-join",e=>{let{userId:r}=e;this.emit(re.REMOTE_USER_ENTER,{userId:r})}).add("peer-leave",e=>{this.emit(re.REMOTE_USER_EXIT,{userId:e}),this._remoteAudioVolumeMap.delete(e)}).add("banned",e=>{this._exitRoom().finally(()=>{this.emit(re.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().finally(()=>{this.emit(re.ERROR,ne.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(re.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let r=Te(z({},e),{uplinkRTT:Math.min(e.uplinkRTT,wn),downlinkRTT:Math.min(e.downlinkRTT,wn)});this.emit(re.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(z({},s),{userId:e.userId});o.kind===N.VIDEO&&(n.streamType=uo(o.streamType)),this.emit(o.kind===N.AUDIO?re.AUDIO_PLAY_STATE_CHANGED:re.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",s=>{s.getCode()===q.PLAY_NOT_ALLOWED&&this.emit(re.AUTOPLAY_FAILED,{userId:o.userId,mediaType:o.strMediaType,resume:()=>o.player.resume()})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(o=>{ht(o)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:r})=>{let{userId:o}=r,s=e.audioAvailable,n=e.videoAvailable,{audioAvailable:c,videoAvailable:l}=r;c||this._remoteAudioConfigMap.delete(o),l||this._removeRemoteVideoConfig(o,"main"),r.hasAuxiliary||this._removeRemoteVideoConfig(o,"sub"),n!==l&&(l?this._onVideoAvailable({userId:o,streamType:"main"}):this._onVideoUnavailable({userId:o,streamType:"main"}),this.emit(l?re.REMOTE_VIDEO_AVAILABLE:re.REMOTE_VIDEO_UNAVAILABLE,{userId:o,streamType:"main"})),s!==c&&(c?this._onAudioAvailable({userId:o}):this._onAudioUnavailable({userId:o,muteState:r}),this.emit(c?re.REMOTE_AUDIO_AVAILABLE:re.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?re.REMOTE_VIDEO_AVAILABLE:re.REMOTE_VIDEO_UNAVAILABLE,{userId:o,streamType:"sub"}))}).add("sei-message",e=>{this.emit(re.SEI_MESSAGE,Te(z({},e),{streamType:uo(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(re.ERROR,new ne({code:le.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var s,n,c,l,m,E,g;let r={2:"big",3:"small",7:"sub"},o={rtt:Math.min(e.msg_up_stream_info.msg_network_status.uint32_rtt||((s=e.msg_down_stream_info[0])==null?void 0:s.msg_network_status.uint32_rtt)||((n=this._networkQuality)==null?void 0:n.uplinkRTT)||((c=this._networkQuality)==null?void 0:c.downlinkRTT)||0,wn),upLoss:((l=this._networkQuality)==null?void 0:l.uplinkLoss)||0,downLoss:((m=this._networkQuality)==null?void 0:m.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((E=e.msg_up_stream_info.msg_audio_status)==null?void 0:E.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((g=e.msg_up_stream_info.msg_audio_status)==null?void 0:g.uint32_audio_level)||0)/mi},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)/mi,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(v=>({bitrate:(v.uint32_video_codec_bitrate||0)/1e3,width:v.uint32_video_width,height:v.uint32_video_height,frameRate:v.uint32_video_dec_fps,videoType:r[v.uint32_video_stream_type],point2pointDelay:(v.uint32_video_p2p_delay||0)+(v.uint32_video_cache_ms||0),jitterBufferDelay:v.uint32_video_cache_ms||0}))}))};this.emit(re.STATISTICS,o)}).add("custom-message",e=>{this.emit(re.CUSTOM_MESSAGE,e)}).add("layerData",e=>this.emit(re.LAYER_DATA,e)).add("first-video-frame",e=>{this.emit(re.FIRST_VIDEO_FRAME,Te(z({},e),{streamType:uo(e.streamType)}))}).add("audio-frame",e=>{this.emit(re.AUDIO_FRAME,e)}),Vt(this,St).add("audioInputAdded",e=>{this.emit(re.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(re.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(re.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(re.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>A(this,null,function*(){if(this.emit(re.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Ct&&Ct.deviceId===Mn){let r=(yield to()).find(o=>o.deviceId===Mn);r&&Ct.groupId!==r.groupId&&(Ct=r,this.emit(re.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}))}})).add("audioOutputRemoved",e=>A(this,null,function*(){this.emit(re.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let r=(yield to())[0];if(!r||!Ct||Ct.groupId===r.groupId)return;let o=Ct.deviceId===e.deviceId,s=Ct.deviceId===Mn&&Ct.deviceId===r.deviceId;(o||s)&&(Ct=r,this.emit(re.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}))}))}use(e){let r,o;"plugin"in e?(r=e.plugin,o=e.assetsPath):r=e,this._use(r,o||pc)}_use(e,r){if(this._plugins.get(e.Name)){this._log.warn("duplicate install plugin",e.Name);return}let s=new e(yg.call(this,{TRTC:Se,room:this._room,errorModule:CS,assetsPath:r}));this._plugins.set(e.Name,s),e.autoStart&&this.startPlugin(e.Name)}enterRoom(e){return A(this,null,function*(){var l,m;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&&((m=(l=this._room).setTurnServer)==null||m.call(l,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=o,this._room.autoReceiveAudio=s,this._room.autoReceiveVideo=n,st(e.preferHW)&&(this._room.preferHW=e.preferHW),e.playoutDelay&&(this._room.playoutDelay=e.playoutDelay),e.jitterBufferDelay&&(this._room.jitterBufferDelay=e.jitterBufferDelay);let c={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:e.role==="audience"?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language,priority:e.priority,useVp8:e.useVp8,keepAlive:e.keepAlive};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(c,r,Se.frameWorkType),this._checkTrackToPublish(),Ip.start()})}exitRoom(){return A(this,null,function*(){return yield this._exitRoom()})}switchRoom(e){return A(this,null,function*(){if(this.room.isSwitchRoomSupported())yield this._room.switchRoom(e);else{yield this.exitRoom();let r=z(z({},this.enterRoomParams),e);yield this.enterRoom(r)}})}switchRole(e,r){return A(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(){ht(this),this.removeAllListeners(),this._room.destroy(),Fa.delete(this),Fa.size===0&&Ip.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),this._plugins.forEach(e=>{var r;return(r=e.destroy)==null?void 0:r.call(e)}),this._plugins.clear(),V.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return A(this,arguments,function*(e={publish:!0}){if(this._localAudioTrack){this._log.warn("local audio is already started");return}let{publish:r=!0,mute:o,option:s}=e,n=new jr(this._room.audioManager),c={},l={muted:!0};s&&(P(s.microphoneId)?P(s.audioTrack)||(c.customSource=s.audioTrack):c.deviceId=s.microphoneId,s&&ke(s.captureVolume)&&n.setCaptureVolume(s.captureVolume),P(s.profile)||(Oe(s.profile)?fc[s.profile]&&n.setProfile(fc[s.profile]):n.setProfile(s.profile)),ke(s.earMonitorVolume)&&(l.muted=!(s.earMonitorVolume>0),l.volume=s.earMonitorVolume),P(s.echoCancellation)||(n.profile.echoCancellation=s.echoCancellation),P(s.noiseSuppression)||(n.profile.noiseSuppression=s.noiseSuppression),P(s.autoGainControl)||(n.profile.autoGainControl=s.autoGainControl)),n.on("5",m=>{this.emit(re.ERROR,new ne({code:le.DEVICE_ERROR,extraCode:5309,messageParams:{error:m}}))}),n.on("2",m=>{this.emit(re.DEVICE_CHANGED,{type:"microphone",action:"active",device:m})}),n.on("4",m=>{let E;m.error&&(E=ne.convertFrom(m.error)),this.emit(re.PUBLISH_STATE_CHANGED,Te(z({},m),{error:E}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId),yield n.capture(c),P(o)||n.setMute(o),Vt(n,n).add("player-state-changed",m=>{this.emit(re.AUDIO_PLAY_STATE_CHANGED,Te(z({},m),{userId:""}))}),r&&this._room.isJoined&&this._room.publish(n).catch(()=>{}),this._localAudioTrack=n,this._localAudioConfig=Te(z({},e),{publish:r}),yield this._updateAudioPlayOption({playOption:l,track:n}),V.emit("113",{userId:"",room:this.room})})}updateLocalAudio(e){return A(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:r,mute:o,option:s}=e,n={};s&&(s.microphoneId?yield this._localAudioTrack.switchDevice(s.microphoneId):P(s.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(s.audioTrack)),P(s.captureVolume)||this._localAudioTrack.setCaptureVolume(s.captureVolume),P(s.earMonitorVolume)||(n.muted=!(s.earMonitorVolume>0),n.volume=s.earMonitorVolume),yield this._localAudioTrack.update3A(s)),this._room.isJoined&&!P(r)&&(r&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!r&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),P(o)||this._localAudioTrack.setMute(o),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),dr(this._localAudioConfig,e)})}stopLocalAudio(){return A(this,null,function*(){this._localAudioTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),V.emit("114",{userId:"",room:this.room}),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),ht(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)})}startLocalVideo(){return A(this,arguments,function*(e={publish:!0,view:null,capture:!0}){var g;if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:r,publish:o=!0,capture:s=!0,mute:n,option:c}=e,l=new Cr(this._room.videoManager),m={},E={};st(c==null?void 0:c.avoidCropping)&&(l.avoidCropping=c.avoidCropping),c&&(c.cameraId?m.deviceId=c.cameraId:P(c.useFrontCamera)?P(c.videoTrack)||(m.customSource=c.videoTrack):m.facingMode=c.useFrontCamera?N.FACING_MODE_USER:N.FACING_MODE_ENVIRONMENT,P(c.retryWhenExactFailed)||(m.retryWhenExactFailed=c.retryWhenExactFailed),c.qosPreference&&(m.contentHint=xa(c.qosPreference)),P(c.profile)||(Oe(c.profile)?Tr[c.profile]&&l.setProfile(Tr[c.profile]):l.setProfile(c.profile)),P(c.fillMode)||(E.objectFit=c.fillMode),P(c.mirror)||(E.mirror=c.mirror),P(c.small)||(P(c.smallMode)||(this._room.smallMode=c.smallMode),st(c.small)&&c.small===!1?l.stopSmall():l.updateSmallConfig(sn(c.small,!0))),P(c.rotation)||l.setRotation(c.rotation)),l.once("first-video-frame",_=>{this.emit(re.FIRST_VIDEO_FRAME,Te(z({},_),{streamType:uo(_.streamType)}))}),l.on("5",_=>{this.emit(re.ERROR,new ne({code:le.DEVICE_ERROR,extraCode:5308,messageParams:{error:_}}))}),l.on("2",_=>{this.emit(re.DEVICE_CHANGED,{type:"camera",action:"active",device:_})}),l.on("4",_=>{let v;_.error&&(v=ne.convertFrom(_.error)),this.emit(re.PUBLISH_STATE_CHANGED,Te(z({},_),{error:v}))}),this._listenOutputTrackChanged(l),s?yield l.capture(m):(g=l.manager)==null||g.changeInput(l),P(n)||(yield l.setMute(n)),Vt(l,l).add("player-state-changed",_=>{this.emit(re.VIDEO_PLAY_STATE_CHANGED,Te(z({},_),{userId:"",streamType:"main"}))}),o&&this._room.isJoined&&this._room.publish(l).catch(()=>{}),this._localVideoTrack=l,this._localVideoConfig=Te(z({},e),{view:r,publish:o,capture:s}),yield this._updateVideoPlayOption({view:r,playOption:E,track:l})})}updateLocalVideo(e){return A(this,null,function*(){var m,E,g;if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:r,publish:o,mute:s,capture:n,option:c}=e,l={};if(this._localVideoConfig.capture)n!==!1?c!=null&&c.cameraId?yield this._localVideoTrack.switchDevice(c==null?void 0:c.cameraId):P(c==null?void 0:c.useFrontCamera)?P(c==null?void 0:c.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(c==null?void 0:c.videoTrack)):yield this._localVideoTrack.switchDevice(c!=null&&c.useFrontCamera?N.FACING_MODE_USER:N.FACING_MODE_ENVIRONMENT):this._localVideoTrack.stopCapture();else if(n){let _={};_.deviceId=(c==null?void 0:c.cameraId)||((m=this._localVideoConfig.option)==null?void 0:m.cameraId),_.facingMode=c!=null&&c.useFrontCamera||(E=this._localVideoConfig.option)!=null&&E.useFrontCamera?N.FACING_MODE_USER:N.FACING_MODE_ENVIRONMENT,_.customSource=(c==null?void 0:c.videoTrack)||((g=this._localVideoConfig.option)==null?void 0:g.videoTrack),yield this._localVideoTrack.capture(_)}c&&(P(c.profile)||(Oe(c.profile)?Tr[c.profile]&&this._localVideoTrack.setProfile(Tr[c.profile]):this._localVideoTrack.setProfile(c.profile),(!c.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(c.cameraId))&&P(c.useFrontCamera)&&(yield this._localVideoTrack.applyProfile())),P(c.fillMode)||(l.objectFit=c.fillMode),P(c.mirror)||(l.mirror=c.mirror),P(c.rotation)||this._localVideoTrack.setRotation(c.rotation),c.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(xa(c.qosPreference)),P(c.small)||(st(c.small)&&!c.small?this._localVideoTrack.stopSmall():this._localVideoTrack.updateSmallConfig(sn(c.small,!0)))),this._room.isJoined&&P(o)&&this._localVideoConfig.publish&&n&&!this._localVideoConfig.capture&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._room.isJoined&&((o!=null?o:this._localVideoConfig.publish)?this._room.publish(this._localVideoTrack).catch(()=>{}):this._room.unpublish(this._localVideoTrack).catch(()=>{})),P(s)||(yield this._localVideoTrack.setMute(s)),yield this._updateVideoPlayOption({view:r,playOption:l,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),dr(this._localVideoConfig,e)})}stopLocalVideo(){return A(this,null,function*(){this._localVideoTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),ht(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return A(this,arguments,function*(e={publish:!0,view:null}){if(this._localScreenTrack){this._log.warn("screen share is already started");return}let{view:r=null,publish:o=!0,option:s}=e,n=new io(this._room.videoManager);n.on("4",g=>{let _;g.error&&(_=ne.convertFrom(g.error)),this.emit(re.PUBLISH_STATE_CHANGED,Te(z({},g),{error:_}))}),n.once("first-video-frame",g=>{this.emit(re.FIRST_VIDEO_FRAME,Te(z({},g),{streamType:uo(g.streamType)}))}),this._listenOutputTrackChanged(n),e.streamType==="main"&&(n.mediaType=4);let c=null,l={},m={};s&&(P(s.profile)||(Oe(s.profile)?gc[s.profile]&&n.setProfile(gc[s.profile]):n.setProfile(s.profile)),s.systemAudio&&(l.systemAudio=!0,l.echoCancellation=s.echoCancellation,l.noiseSuppression=s.noiseSuppression,l.autoGainControl=s.autoGainControl),P(s.fillMode)||(m.objectFit=s.fillMode),s.videoTrack&&(l.videoTrack=s.videoTrack),s.audioTrack&&(l.audioTrack=s.audioTrack),s.captureElement&&(l.captureElement=s.captureElement),s.preferDisplaySurface&&(l.preferDisplaySurface=s.preferDisplaySurface),s.qosPreference&&(l.contentHint=xa(s.qosPreference)));let E=yield n.capture(l);if(n.mediaTrack.addEventListener(N.ENDED,()=>{this._stopScreenShare(),this.emit(re.SCREEN_SHARE_STOPPED)}),E.getAudioTracks()[0]&&(c=new Ko(this._room.audioManager),yield c.setInputMediaStreamTrack(E.getAudioTracks()[0]),this._speakerId&&c.setAudioOutput(this._speakerId)),Vt(n,n).add("player-state-changed",g=>{this.emit(re.VIDEO_PLAY_STATE_CHANGED,Te(z({},g),{userId:"",streamType:"sub"}))}),o&&this._room.isJoined){let g=[n];c&&(g.push(c),this._checkScreenAudioEchoCancellation(n,c)),this._room.publish(...g).catch(()=>{})}this._localScreenTrack=n,this._localScreenAudioTrack=c,this._localScreenConfig=Te(z({},e),{view:r,publish:o}),yield this._updateVideoPlayOption({view:r,playOption:m,track:n})})}updateScreenShare(e){return A(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:r,publish:o,option:s}=e,n={};if(s&&(P(s.fillMode)||(n.objectFit=s.fillMode),s.qosPreference)){let c=xa(s.qosPreference);this._localScreenTrack.setContentHint(c)}this._room.isJoined&&!P(o)&&(o&&!this._localScreenConfig.publish&&(this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch(()=>{})),this._localScreenConfig.publish&&!o&&(this._room.unpublish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.unpublish(this._localScreenAudioTrack).catch(()=>{}))),yield this._updateVideoPlayOption({view:r,playOption:n,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),dr(this._localScreenConfig,e)})}stopScreenShare(){return A(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return A(this,null,function*(){let{view:r,userId:o,streamType:s,option:n}=e,c=`${o}_${s}`;if(this._remoteVideoConfigMap.has(c)){this._log.warn(`remote video has already started. userId:${o}, streamType:${s}`);return}let l=this._room.remotePublishedUserMap.get(o);if(!l)return;let m={},E=s==="main"?l.remoteVideoTrack:l.remoteAuxiliaryTrack;this._listenOutputTrackChanged(E),n&&(P(n.fillMode)||(m.objectFit=n.fillMode),P(n.mirror)||(m.mirror=n.mirror),P(n.poster)||(m.poster=n.poster),m.canvasRender=n.canvasRender,s==="main"&&!P(n.small)&&(!l.remoteVideoTrack.isSubscribing&&!l.remoteVideoTrack.isSubscribed&&l.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,E.user))),yield this._room.subscribe(E),yield this._enableVideoDecodeFallback(E,s),yield this._updateVideoPlayOption({view:r,playOption:m,track:E}),this._emitTrackEvent(E),this._remoteVideoConfigMap.set(c,{config:e}),n&&!P(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:E,view:r,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:n==null?void 0:n.viewRoot})})}updateRemoteVideo(e){return A(this,null,function*(){var M,B;let{view:r,userId:o,streamType:s,option:n}=e,c=`${o}_${s}`,l=this._remoteVideoConfigMap.get(c);if(!l||!this._room.remotePublishedUserMap.has(o))return;let m={};n&&(P(n.fillMode)||(m.objectFit=n.fillMode),P(n.mirror)||(m.mirror=n.mirror));let E=null,g=this._room.remotePublishedUserMap.get(o);if(s==="main"&&(g!=null&&g.muteState.hasVideo)&&(E=g.remoteVideoTrack),s==="sub"&&(g!=null&&g.muteState.hasAuxiliary)&&(E=g.remoteAuxiliaryTrack),!E)return;let{config:_}=l;s==="main"&&n&&!P(n.small)&&this._room.changeType(n.small,E.user),yield this._updateVideoPlayOption({view:r,playOption:m,track:E,prevConfig:_}),dr(_,e);let v=P(n==null?void 0:n.receiveWhenViewVisible)?(M=_.option)==null?void 0:M.receiveWhenViewVisible:n.receiveWhenViewVisible,L=P(r)?_.view:r,x=P(n==null?void 0:n.viewRoot)?(B=_.option)==null?void 0:B.viewRoot:n.viewRoot;this._observeView({remoteTrack:E,view:L,receiveWhenViewVisible:v,viewRoot:x})})}stopRemoteVideo(e){return A(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,r=!0){return A(this,null,function*(){let o=[],s=this._room.remotePublishedUserMap.get(e.userId);if(s){let{muteState:n,remoteVideoTrack:c,remoteAuxiliaryTrack:l}=s;e.streamType==="main"&&(c.stop(),n.hasVideo&&o.push(c)),e.streamType==="sub"&&(l.stop(),n.hasAuxiliary&&o.push(l))}for(let n of o)r&&(yield this._room.unsubscribe(n),this._mediaTrackMap.delete(n.outMediaTrack));this._removeRemoteVideoConfig(e.userId,e.streamType)})}_removeRemoteVideoConfig(e,r){let o=`${e}_${r}`,s=this._remoteVideoConfigMap.get(o);s&&s.observer&&s.observer.disconnect(),this._remoteVideoConfigMap.delete(o)}muteRemoteAudio(e,r){return A(this,null,function*(){this._remoteAudioMuteMap.set(e,r);try{if(e==="*")if(r)yield this._stopRemoteAudio({userId:e});else{let o=[...this._room.remotePublishedUserMap.values()];for(let s of o)s.muteState.hasAudio&&!this._remoteAudioConfigMap.has(s.userId)&&(yield this._startRemoteAudio({userId:s.userId}))}else r?yield this._stopRemoteAudio({userId:e}):this._remoteAudioConfigMap.has(e)||(yield this._startRemoteAudio({userId:e}))}catch(o){throw this._remoteAudioMuteMap.delete(e),o}})}setRemoteAudioVolume(e,r){if(e==="*"){let o=[...this._room.remotePublishedUserMap.values()];for(let s of o)this._remoteAudioVolumeMap.set(s.userId,r),s.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:r},track:s.remoteAudioTrack})}else if(e){let o=this._room.remotePublishedUserMap.get(e);this._remoteAudioVolumeMap.set(e,r),o&&o.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:r},track:o.remoteAudioTrack})}}startPlugin(e,r){return A(this,null,function*(){return e.start(r)})}updatePlugin(e,r){return A(this,null,function*(){return e.update(r)})}stopPlugin(e,r){return A(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(re.AUDIO_FRAME).length>0){let{audioFrameEventConfigMap:s}=this.room.audioManager;s.get("")||s.set("",{enable:!0}),this._localAudioTrack&&this.room.audioManager.handleLocalTrackStarted({userId:"",room:this.room})}return this}emit(e,...r){try{Tg.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===Se.EVENT.AUDIO_FRAME||e==="*")&&this.listeners(Se.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 c=this._room.remotePublishedUserMap.get(r);c&&(o=c.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 c=this._room.remotePublishedUserMap.get(r);c&&(n=o==="main"?c.remoteVideoTrack:c.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 A(this,null,function*(){(yield to()).forEach(o=>{o.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(re.DEVICE_CHANGED,{type:"speaker",action:"active",device:o}),Ct=o)}),this._log.warn('the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: https://web.sdk.qcloud.com/trtc/webrtc/v5/doc/en/TRTC.html#.setCurrentSpeaker')})}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return A(this,null,function*(){let{userId:r}=e;if(this._remoteAudioConfigMap.has(r)){this._log.warn(`remote audio has already started. userId:${r}`);return}let o=this._room.remotePublishedUserMap.get(r);if(!o)return;let s={},n=o.remoteAudioTrack;this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId);try{let c=this._remoteAudioVolumeMap.get(r),l=ke(c)?c:100;s.volume=l,this._remoteAudioConfigMap.set(r,e),yield this._room.subscribe(n),be(Ce(n,"decode-failed"),Ye(Ce(n,de.INIT)),Le(()=>{this.startPlugin(Va.Name,{track:n,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:s,track:n}),V.emit("115",{userId:r,room:this.room}),n.outMediaTrack&&this.room.audioManager.updateAudioReference({type:"add",audioReference:n.outMediaTrack,refId:`ra-${r}`})}catch(c){throw this._remoteAudioConfigMap.delete(r),c}this._emitTrackEvent(n)})}_stopRemoteAudio(e,r=!0){return A(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}`),V.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(Ce(e,"decode-failed"),Ye(Ce(e,de.INIT)),Ca(()=>{this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:o})}),Ai(Ce(e,"decode-downgrade-state-changed")),Le(n=>{s=n.state,this.emit(re.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,Te(z({},n),{streamType:r,userId:e.userId}))},n=>{e.log.error("fallback",n)},()=>{s==="STARTED"&&e.log.info("fallback complete")}))}_updateVideoPlayOption(n){return A(this,arguments,function*({view:e,playOption:r,track:o,prevConfig:s}){if(o.setMirror(r.mirror),P(e)&&s&&s.view&&!Cs(r)){let c=Ds(s.view);c.length>0&&(yield o.play(c,r))}if(!P(e)){let c=Ds(e);c.length>0?yield o.play(c,r):o.stop()}})}_updateAudioPlayOption(s){return A(this,arguments,function*({playOption:e={},track:r,prevConfig:o}){if(!r.isPlayCalled)try{yield r.play(null,e)}catch(n){}if(P(e.muted)||r.setPlayerMute(e.muted),P(e.volume)||r.setAudioVolume(e.volume/100),r instanceof jr&&r.mediaTrack){let n=e.muted===!1&&!P(e.volume)&&e.volume>0?"add":"remove";this.room.audioManager.updateAudioReference({type:n,audioReference:r.mediaTrack,refId:"em"})}else if(r instanceof Ii){let n=e.muted?0:e.volume;if(P(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(re.TRACK,{userId:o,streamType:uo(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 this._room.publish(...e).catch(()=>{})}_observeView({remoteTrack:e,view:r,receiveWhenViewVisible:o=!1,viewRoot:s}){if(P(r))return;let n=this._remoteVideoConfigMap.get(`${e.userId}_${uo(e.streamType)}`);if(!n)return;let c=n.observer||void 0;if(r===null||ot(r)&&r.length===0||!o){c==null||c.disconnect(),e.isSubscribed||this._room.subscribe(e).catch(()=>{});return}let m=n.visibleViewMap||new Map,E=-1;(!c||c.root!==s)&&(c==null||c.disconnect(),m.clear(),c=new IntersectionObserver(_=>{_.forEach(v=>{m.set(v.target,v.isIntersecting),e.log.info(`view ${v.target.id} is${v.isIntersecting?"":" not"} visible`)}),clearTimeout(E),E=window.setTimeout(()=>{[...m.values()].find(L=>L)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:s}));let g=new Set(Ds(r));m.forEach((_,v)=>{g.has(v)||(c.unobserve(v),m.delete(v))}),g.forEach(_=>{m.set(_,!0),c.observe(_)}),c.takeRecords().forEach(_=>{m.set(_.target,_.isIntersecting)}),n.visibleViewMap=m,n.observer=c}_exitRoom(){return A(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(e=>{this._stopRemoteAudio({userId:e}).catch()}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let r=e.includes("main")?"main":"sub",o=e.split(`_${r}`)[0];o&&this._stopRemoteVideo({userId:o,streamType:r}).catch()}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._remoteAudioVolumeMap.clear(),Rg(this),this._room.remotePublishedUserMap.forEach(e=>{ht(e.remoteAudioTrack),ht(e.remoteVideoTrack),ht(e.remoteAuxiliaryTrack)})})}_stopScreenShare(){return A(this,null,function*(){var e,r;if(this._localScreenTrack){if(this._room.isJoined){let o=[this._localScreenTrack];this._localScreenAudioTrack&&o.push(this._localScreenAudioTrack),yield(e=this._room)==null?void 0:e.unpublish(...o).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),ht(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_checkScreenAudioEchoCancellation(e,r){return A(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(c){this._log.warn("start audioProcessor plugin failed: ",c)}}})}_onLocalTrackCaptured({track:e}){e.kind==="audio"&&(!Ct||Qs(Ct))&&(this._initActiveSpeaker(),V.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return A(this,null,function*(){if(Ct&&!Qs(Ct))this.emit(re.DEVICE_CHANGED,{type:"speaker",action:"active",device:Ct});else{let e=yield to();e[0]&&!Qs(e[0])?(Ct=e[0],this.emit(re.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):V.on("102",this._onLocalTrackCaptured,this)}})}_onAudioAvailable({userId:e}){let r=this._remoteAudioMuteMap.has(e)?this._remoteAudioMuteMap.get(e):this._remoteAudioMuteMap.get("*");(r===!1||this._room.autoReceiveAudio&&!r)&&this._doStartRemoteAudio({userId:e}).catch(()=>{})}_onVideoAvailable({userId:e,streamType:r}){if(!this._room.autoReceiveVideo)return;let o=this._room.remotePublishedUserMap.get(e);if(o){let s=r==="main"?o.remoteVideoTrack:o.remoteAuxiliaryTrack,n=[s];this._room.autoReceiveAudio&&o.remoteAudioTrack.isAvailable&&n.push(o.remoteAudioTrack),this._room.subscribe(...n).then(()=>{this._emitTrackEvent(s)}).catch(()=>{})}}_onAudioUnavailable({userId:e,muteState:r}){r.hasAudio&&r.audioMuted||this._stopRemoteAudio({userId:e},!1).catch(()=>{})}_onVideoUnavailable({userId:e,streamType:r}){this._stopRemoteVideo({userId:e,streamType:r},!1).catch(()=>{})}sendSEIMessage(e,r){var s;let o=this._plugins.get("SEI");o&&(o.update({buffer:e,options:Te(z({seiPayloadType:243},r),{small:!!((s=this._localVideoTrack)!=null&&s.small)})}),Q.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var r,o;(o=(r=this._room).sendCustomMessage)==null||o.call(r,e),Q.addCount({key:500001,useUV:!0})}callExperimentalAPI(e,r){return A(this,null,function*(){return this._log.info(`callExperimentalAPI(${e}, ${JSON.stringify(r)})`),Pg.call(e,z({trtcInstance:this},r))})}static setLogLevel(e,r){$.setLogLevel(e),P(r)||(r?$.enableUploadLog():$.disableUploadLog())}static isSupported(){return cd(Se.frameWorkType)}static getCameraList(e=!0){return ir(e)}static getMicrophoneList(e=!0){return Qt(e)}static getSpeakerList(e=!0){return to(e)}static setCurrentSpeaker(e){return A(this,null,function*(){if(mt&&(e===mr.SPEAKER||e===mr.HEADSET)){let o=yield Se.getMicrophoneList(),s="";if(o.forEach(n=>{n.label===e&&(s=n.deviceId)}),!s)return;Fa.forEach(n=>A(this,null,function*(){n._localAudioTrack&&(yield n.updateLocalAudio({option:{microphoneId:s}}))}));return}(yield to()).forEach(o=>{o.deviceId===e&&(Fa.forEach(s=>{s._setCurrentSpeaker(e),s.emit(re.DEVICE_CHANGED,{type:"speaker",action:"active",device:o})}),Ct=o)})})}static _addKVStat({type:e,key:r,value:o,base:s,useUV:n,version:c,max:l}){switch(c&&(qo.version=c),e){case"count":qo.addCount({key:r,useUV:n});break;case"enum":qo.addEnum({key:r,value:o,useUV:n});break;case"number":qo.addNumber({key:r,value:o,split:s,max:l});break}}};u(Se,"_loggerManager",$),u(Se,"EVENT",re),u(Se,"ERROR_CODE",le),u(Se,"TYPE",mr),u(Se,"frameWorkType",30),Z([tt({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"}})})],Se.prototype,"use",1),Z([Mt(yt.TRTC.enterRoom),mo("room",([e],[r])=>(e.roomId||e.strRoomId)===(r.roomId||r.strRoomId)&&e.userId===r.userId&&e.sdkAppId===r.sdkAppId),xe(e=>function(r){return this._log.setUserId(r.userId),this._log.setSdkAppId(r.sdkAppId),e.call(this,r)}),tt()],Se.prototype,"enterRoom",1),Z([tt()],Se.prototype,"exitRoom",1),Z([Mt(yt.TRTC.switchRoom),tt(),Rd()],Se.prototype,"switchRoom",1),Z([Mt(yt.TRTC.switchRole),ns("room",{merge:(e,r)=>r}),tt()],Se.prototype,"switchRole",1),Z([tt()],Se.prototype,"destroy",1),Z([Mt(yt.TRTC.startLocalAudio),mo("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)}),tt()],Se.prototype,"startLocalAudio",1),Z([Mt(yt.TRTC.updateLocalAudio),ns("audio",{debounce:{delay:200,getKey:()=>`${kg}-localAudio`,isNeedToDebounce:e=>{var r;return!P((r=e.option)==null?void 0:r.captureVolume)}}}),tt()],Se.prototype,"updateLocalAudio",1),Z([po("audio"),tt()],Se.prototype,"stopLocalAudio",1),Z([Mt(yt.TRTC.startLocalVideo),mo("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)}),tt()],Se.prototype,"startLocalVideo",1),Z([Mt(yt.TRTC.updateLocalVideo),ns("video"),tt()],Se.prototype,"updateLocalVideo",1),Z([po("video"),tt()],Se.prototype,"stopLocalVideo",1),Z([Mt(yt.TRTC.startScreenShare),mo("screen",()=>!0),tt()],Se.prototype,"startScreenShare",1),Z([Mt(yt.TRTC.updateScreenShare),ns("screen"),tt()],Se.prototype,"updateScreenShare",1),Z([tt()],Se.prototype,"stopScreenShare",1),Z([Mt(yt.TRTC.startRemoteVideo),mo(e=>`v${e.userId}${e.streamType}`,()=>!0),tt({getRemoteId:e=>`${e.userId}_${e.streamType}`})],Se.prototype,"startRemoteVideo",1),Z([Mt(yt.TRTC.updateRemoteVideo),ns(e=>`v${e.userId}${e.streamType}`),tt({getRemoteId:e=>`${e.userId}_${e.streamType}`})],Se.prototype,"updateRemoteVideo",1),Z([Mt(yt.TRTC.stopRemoteVideo),xe(e=>function(r){return A(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)})}),tt({getRemoteId:e=>`${e.userId}_${e.streamType}`})],Se.prototype,"stopRemoteVideo",1),Z([po(e=>`v${e.userId}${e.streamType}`)],Se.prototype,"_stopRemoteVideo",1),Z([Mt(...yt.TRTC.muteRemoteAudio),tt({getRemoteId:e=>e})],Se.prototype,"muteRemoteAudio",1),Z([fp(...yt.TRTC.setRemoteAudioVolume),vg(200,e=>e),tt({getRemoteId:e=>e})],Se.prototype,"setRemoteAudioVolume",1),Z([cu("start"),ro(e=>{var r;return(r=e.afterStart)==null?void 0:r.call(e)}),mo((e,r)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(r)),tt({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>jl[e.getName()],ignoreLog:e=>e.getName()==="Debug",ignoreErrorLog:e=>e.getName()==="AudioProcessor"})],Se.prototype,"startPlugin",1),Z([cu("update"),ns((e,r)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(r)),tt({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>ql[e.getName()]})],Se.prototype,"updatePlugin",1),Z([cu("stop"),po((e,r)=>{if(e.disableRandomCall)return null;let o=e.getGroup(r),s=e.getAlias();return o==="*"?new RegExp(`${s}.*`):s+o}),tt({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Jl[e.getName()]})],Se.prototype,"stopPlugin",1),Z([fp(...yt.TRTC.enableAudioVolumeEvaluation)],Se.prototype,"enableAudioVolumeEvaluation",1),Z([tt()],Se.prototype,"getVideoSnapshot",1),Z([tt()],Se.prototype,"_setCurrentSpeaker",1),Z([mo(e=>`a${e.userId}`,()=>!0)],Se.prototype,"_startRemoteAudio",1),Z([xe(e=>function(r){return A(this,null,function*(){return r.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(o=>this._stopRemoteAudio(Te(z({},r),{userId:o.userId})).catch(()=>{}))):e.call(this,r)})}),po(e=>`a${e.userId}`)],Se.prototype,"_stopRemoteAudio",1),Z([po("room")],Se.prototype,"_exitRoom",1),Z([po("screen")],Se.prototype,"_stopScreenShare",1),Z([Mt(...yt.TRTC.sendSEIMessage),cp({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...e)=>e[0].byteLength})],Se.prototype,"sendSEIMessage",1),Z([Mt(yt.TRTC.sendCustomMessage),cp({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],Se.prototype,"sendCustomMessage",1),Z([Mt(yt.TRTC.create)],Se,"_create",1);var vp=Se,un=vp;var Iu=class{constructor(t,e){u(this,"_flag");u(this,"terminalType");u(this,"userId");u(this,"tinyId");u(this,"role");u(this,"remoteAudioTrack");u(this,"remoteVideoTrack");u(this,"remoteAuxiliaryTrack");this.userId=e.userId||"",this.tinyId=e.tinyId||"",this.role=e.role||"audience",this.terminalType=e.terminalType,this.remoteAudioTrack=new Ii(t,this),this.remoteVideoTrack=new ao(t,this),this.remoteAuxiliaryTrack=new Jd(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 Ln(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 Cp=class{constructor(){u(this,"_set",new Set);V.on(U.LEAVE_SUCCESS,this.delete,this),V.on(U.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 NS(){return A(this,null,function*(){let i,t;try{let g=yield Qt();i=g&&g.length}catch(g){}try{let g=yield ir();t=g&&g.length}catch(g){}let e={microphone:i,camera:t},{isH264EncodeSupported:r,isVp8EncodeSupported:o,isH264DecodeSupported:s,isVp8DecodeSupported:n}=this.checkSystemResult.detail,c=eo.basis(),l={webRTC:c.isWebRTCSupported,getUserMedia:c.isGetUserMediaSupported,webSocket:c.isWebSocketsSupported,screenShare:c.isScreenShareSupported,webAudio:c.isWebAudioSupported,h264Encode:r,h264Decode:s,vp8Encode:o,vp8Decode:n},m={browser:c.browser,os:c.os,trtc:l,devices:e},E={isWebCodecSupported:c.isWebCodecSupported,isMediaSessionSupported:c.isMediaSessionSupported,isWebTransportSupported:c.isWebTransportSupported};je.uploadEvent({log:`trtcstats-${JSON.stringify(m)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(m)}`),je.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(E)}`,userId:this.userId})})}function Ug(){return xe(i=>{let t=new Cp;return function(e,r,o){return A(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 ue({code:q.INVALID_OPERATION,message:Be({key:$e.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:s,sdkAppId:this.sdkAppId,room:this}))throw new ue({code:q.INVALID_OPERATION,message:Be({key:$e.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}`),V.emit(U.JOIN_START,{room:this,roomId:s,params:e});let n=Ur.getEnv();n||(n=ei.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(Ec.OLD_CLOUD_LADDER)?n=ei.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(Ec.WEBRTC)&&(n=ei.WEBRTC))),je.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:s}),eo.checkSystemRequirementsInternal(o).then(c=>{this.checkSystemResult=c,NS.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Ur.getEnv()&&(yield this.schedule(e,o));let c=yield i.call(this,e,r,o);return this.roomId=s,this._joinedTimestamp=Ur.performanceNow(),V.emit(U.JOIN_SUCCESS,{room:this}),o===30&&!e.component&&je.uploadEvent({log:`stat-conv-${Number(Rr)}-${location.hostname}`,userId:this.userId}),c}catch(c){throw t.delete({room:this,roomId:s}),V.emit(U.JOIN_FAILED,{room:this,error:c}),c}})}})}var Vg=()=>xe(i=>function(...t){return A(this,null,function*(){V.emit(U.LEAVE_START,{room:this}),yield i.call(this,...t),V.emit(U.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function Fg(){return xe(i=>function(...t){return A(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(t=t.filter(r=>r.outMediaTrack&&r.state==="ready"),!t.length))return;V.emit("61",{room:this});let e=i.apply(this,t);return t.forEach(r=>r.publish(this,e)),e})})}function $g(){return xe(i=>function(...t){let e=i.apply(this,t);return t.forEach(r=>r.unpublish()),e})}function Bg(){return xe(i=>function(...t){let e=i.apply(this,t);return t.forEach(r=>!r.isSubscribed&&r.subscribe(e)),e})}function DS({fn:i,context:t}){return function(...e){try{let r=i.apply(t,e);return qi(r)?r.catch(o=>$.error(`${i.name}() error observed ${o}`)):r}catch(r){$.error(`${i.name}() error observed ${r}`)}}}var Su=class{constructor(t){u(this,"_frameWorkType");u(this,"_component");u(this,"_language");u(this,"connectionType");u(this,"_room");u(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0});u(this,"_keyPrefix");u(this,"_log");u(this,"_intervalId");u(this,"_firstPublishedUserList");u(this,"_networkQuality");u(this,"_basicInfo");u(this,"_pathJoinRoom");u(this,"_pathLeaveRoom");u(this,"_pathMainVideoMap");u(this,"_pathMainAudioMap");u(this,"_pathAuxiliaryMap");u(this,"_remoteStreamStatMap");u(this,"_localStreamStat");u(this,"_eventMap",new Map);u(this,"_captureCostSum",0);u(this,"_captureCostCount",0);u(this,"isDestroyed",!1);this._frameWorkType=t.frameWorkType||30,this._component=t.component||0,this.connectionType=t.connectionType||1,this._language=t.language||0,this._room=t.room,this._keyPrefix="key_point",this._log=$.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(e=>{e.startsWith("handle")&&We(this[e])&&(this[e]=DS({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:at,uint32_os_type:15,string_device_name:"",string_http_user_agent:navigator.userAgent,string_os_version:"",uint32_avg_rtt:0,uint32_avg_up_loss:0,uint32_scene:this._room.scene==="live"?1:0,uint32_joining_duration:0,uint32_networkType:0,uint32_framework:this._frameWorkType,uint32_component:this._component,uint32_connection_type:this.connectionType,uint32_caller_coding_language:this._language,string_domain:location.hostname},this._pathJoinRoom={uint64_start_time:0,uint64_send_request_acc_ip_cmd_start_time:0,uint64_send_request_acc_ip_cmd_end_time:0,uint64_send_request_enter_room_cmd_start_time:0,uint64_send_request_enter_room_cmd_end_time:0,uint64_send_first_video_frame_time:0,uint64_recv_userlist_time:0,uint64_end_time:0,int32_send_request_acc_ip_cmd_ret:0,int32_send_request_enter_room_cmd_ret:0,int32_end_ret:0},this._pathLeaveRoom={uint64_start_time:0,uint64_send_request_exit_room_cmd_start_time:0,uint64_send_request_exit_room_cmd_end_time:0,uint64_end_time:0,int32_send_request_exit_room_cmd_ret:0,int32_end_ret:0},this._localStreamStat={totalVideoBitrate:0,totalVideoFPS:0,totalVideoHeight:0,totalVideoWidth:0,totalAudioLevel:0,videoCount:0,audioLevelCount:0,publishStartTime:0,statsToReport:{uint32_audio_capture_db:0,uint32_video_big_capture_fps:0,uint32_video_big_bitrate:0,uint32_video_big_resolution:0}},this._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,$o().then(t=>{this._basicInfo.string_os_version=Bo(),t?this._basicInfo.string_device_name=t.mobile?t.model:this._basicInfo.string_os_version:this._basicInfo.string_device_name=this._basicInfo.string_os_version})}addEvent(t,e){return this._eventMap.set(t,e),V.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(U.JOIN_START,this.handleJoinStart).addEvent(U.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(U.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(U.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(U.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(U.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(U.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(U.JOIN_FAILED,this.handleJoinFailed).addEvent(U.LEAVE_START,this.handleLeaveStart).addEvent(U.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(U.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(U.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(U.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(U.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(U.PUBLISH_START,this.handlePublishStart).addEvent(U.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(U.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(U.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(U.PLAY_TRACK_START,this.handlePlayStart).addEvent(U.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(U.PLAYER_STATE_CHANGED,({track:t,state:e,type:r})=>{!t.isRemote||!this.hitTest(t.room)||e==="PLAYING"&&(r===N.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))}).addEvent(U.SWITCH_ROOM_START,this.handleSwitchRoomStart).addEvent(U.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess).addEvent(U.SWITCH_ROOM_FAILED,this.handleSwitchRoomFailed).addEvent(U.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(U.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(U.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(U.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,c=r.hasAuxiliary;!o&&n&&this.handleRemoteStreamAdded(r.userId,"main"),!s&&c&&this.handleRemoteStreamAdded(r.userId,"auxiliary")}).addEvent(U.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)=>V.off(e,t)),this._eventMap.clear()}destroy(){this.uninstallEvents(),vt.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&&(P(t.params.frameWorkType)||(this._frameWorkType=t.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),P(t.params.component)||(this._component=t.params.component,this._basicInfo.uint32_component=this._component),P(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:c,request:l,response:m}=e;this._pathJoinRoom.int32_schedule_cost=r,this._pathJoinRoom.int32_schedule_local=o,this._pathJoinRoom.int32_schedule_dns=s,this._pathJoinRoom.int32_schedule_tcp=n,this._pathJoinRoom.int32_schedule_tls=c,this._pathJoinRoom.int32_schedule_request=l,this._pathJoinRoom.int32_schedule_response=m}}handleSignalConnectionStart({room:t}){this.hitTest(t)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time=Date.now())}handleSignalConnectionEnd({room:t,error:e}){this.hitTest(t)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time=Date.now(),e&&(this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret=e instanceof ue?Number(e.getExtraCode()||e.getCode()):q.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}handleJoinSendCMD(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now())}handleJoinReceivedCMDResponce(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=t.code,t.code!==0&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}handleJoinSuccess(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_end_time===0&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=t.room.getSignalInfo())}handleJoinFailed({room:t,error:e}){this.hitTest(t)&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret===0&&(this._pathJoinRoom.int32_end_ret=e.code||this._pathJoinRoom.int32_send_request_enter_room_cmd_ret||this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret),setTimeout(()=>{this.report()}))}handleReceivedPublishUserList(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_recv_userlist_time===0&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=t.publishedUserList||[])}handleSendFirstVideoFrame({room:t}){this.hitTest(t)&&this._pathJoinRoom.uint64_send_first_video_frame_time===0&&this._pathJoinRoom.uint64_start_time!==0&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now())}handleLeaveStart(t){this.hitTest(t.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(t){this.hitTest(t.room)&&this._pathLeaveRoom.uint64_end_time===0&&(this._pathLeaveRoom.uint64_end_time=Date.now(),this._pathJoinRoom.uint64_end_time!==0?this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time:this._log.warn("pathJoinRoom endTime is 0"),this.report())}handleLeaveSendCMD(t){this.hitTest(t.room)&&(this._pathLeaveRoom.uint64_send_request_exit_room_cmd_start_time=Date.now(),this._pathLeaveRoom.uint64_send_request_exit_room_cmd_end_time=Date.now())}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 ue?Number(e.getExtraCode()||e.getCode()):q.UNKNOWN)}}handleRemoteStreamAdded(t,e){var o;let r=`${t}_${e}`;if(!this._remoteStreamStatMap.has(r)){let s={userId:t,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:Te(z({},MS),{msg_user_info:new $a({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:c}=e,l=new $a({userId:s,tinyId:n,role:c==="anchor"?20:21}),m=Date.now(),E=`${s}_${r}`,g=this._remoteStreamStatMap.get(E);g&&g.subscribeStartTime===0&&(g.subscribeStartTime=m),r==="main"?(e.muteState.hasVideo&&(o.video||o.smallVideo)&&!this._pathMainVideoMap.has(E)&&this._pathMainVideoMap.set(E,{statsToReport:{msg_user_info:l,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:s,sendSubscribeCMDTime:m}),e.muteState.hasAudio&&o.audio&&!this._pathMainAudioMap.has(E)&&this._pathMainAudioMap.set(E,{statsToReport:{msg_user_info:l,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:s,sendSubscribeCMDTime:m})):e.muteState.hasAuxiliary&&o.auxiliary&&!this._pathAuxiliaryMap.has(E)&&this._pathAuxiliaryMap.set(E,{sendSubscribeCMDTime:m})}handleSubscribed({room:t,remotePublishedUser:e,streamType:r}){if(this.hitTest(t)){let o=`${e.userId}_${r}`,s=this._remoteStreamStatMap.get(o);s&&s.subscribedTime===0&&(s.subscribedTime=Date.now())}}handlePlayStart({track:t}){if(!t.isRemote||!this.hitTest(t.room))return;let e=`${t.userId}_${t.streamType}`,r=this._remoteStreamStatMap.get(e);(r==null?void 0:r.playStreamTime)===0&&(r.playStreamTime=Date.now())}handleVideoLoadedData({track:t}){if(!t.isRemote||!this.hitTest(t.room))return;let e=`${t.userId}_${t.streamType}`,r=this._pathMainVideoMap.get(e);r&&r.statsToReport.uint64_combine_first_frame_time===0&&(r.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(t){let e=`${t.userId}_${t.streamType}`,r=Date.now(),o=this._pathMainVideoMap.get(e),s=this._remoteStreamStatMap.get(e);if(s){let{statsToReport:n}=s;if(!n.uint32_video_render_first&&t.streamType==="main"?this.hasVideoFlag(t.userId):this.hasAuxFlag(t.userId)){let c=r-this._pathJoinRoom.uint64_start_time;n.uint32_video_render_first=c,Q.addNumber({key:516820,value:c})}}(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 c=this._networkQuality.totalDownlinkRTTAndLossMap.get(o);if(c)c.totalRTT+=e,c.totalLoss+=r,s&&(c.totalVideoDelay=(c.totalVideoDelay||0)+s,c.videoDelayCount=(c.videoDelayCount||0)+1),n&&(c.totalAudioDelay=(c.totalAudioDelay||0)+n,c.audioDelayCount=(c.audioDelayCount||0)+1),c.count++;else{let l,m,E,g;s&&(m=s,E=1),n&&(l=n,g=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(o,{totalRTT:e,totalLoss:r,count:1,totalAudioDelay:l,totalVideoDelay:m,audioDelayCount:g,videoDelayCount:E})}}))}handleHeartbeatStats(t){if(this.hitTest(t.room)){let{msg_device_info:e,msg_up_stream_info:r,msg_down_stream_info:o}=t.report;if(r.msg_video_status[0]){let{uint32_video_codec_bitrate:s,uint32_video_enc_fps:n,uint32_video_width:c,uint32_video_height:l}=r.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=s,this._localStreamStat.totalVideoFPS+=n,this._localStreamStat.totalVideoWidth+=c,this._localStreamStat.totalVideoHeight+=l,this._localStreamStat.videoCount++}if(r.msg_audio_status){let{uint32_audio_level:s}=r.msg_audio_status;Math.floor(s/mi*100)>0&&(this._localStreamStat.totalAudioLevel+=s/mi,this._localStreamStat.audioLevelCount++)}o.forEach(s=>{let{msg_user_info:n,msg_audio_status:c,msg_video_status:l}=s,m=n.str_identifier,E=this._room.remotePublishedUserMap.get(m);if(l.forEach(g=>{let _=g.uint32_video_stream_type===2,v=g.uint32_video_stream_type===7,L=`${m}_${_?"main":"auxiliary"}`,x=this._remoteStreamStatMap.get(L);if(x&&(_&&(E!=null&&E.remoteVideoTrack.isSubscribed)||v&&(E!=null&&E.remoteAuxiliaryTrack))){x.totalVideoFPS+=g.uint32_video_receive_fps,x.totalVideoBitrate+=g.uint32_video_codec_bitrate,x.videoCount++,x.statsToReport.uint32_video_width===0&&(x.statsToReport.uint32_video_width=g.uint32_video_width),x.statsToReport.uint32_video_height===0&&(x.statsToReport.uint32_video_height=g.uint32_video_height);let M=_?E.remoteVideoTrack:E.remoteAuxiliaryTrack;M.stat.jitterBufferDelay&&(x.videoJitterBufferDelay=M.stat.jitterBufferDelay),M.stat.framesReceived&&(x.statsToReport.uint32_video_consume_render_rate=Math.floor(M.stat.framesDecoded/M.stat.framesReceived*Wi(10,6)))}}),!Cs(c)){let g=`${m}_main`,_=this._remoteStreamStatMap.get(g);this._remoteStreamStatMap.has(g)&&_&&E!=null&&E.remoteAudioTrack.isSubscribed&&(_.totalAudioBitrate+=c.uint32_audio_codec_bitrate,_.audioCount++,E.remoteAudioTrack.stat.jitterBufferDelay&&(_.audioJitterBufferDelay=E.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(c.uint32_audio_level/mi*100)>0&&(_.totalAudioLevel+=c.uint32_audio_level/mi,_.audioLevelCount++))}}),e.uint32_audio_capture_cost&&(this._captureCostSum+=e.uint32_audio_capture_cost,this._captureCostCount+=1,this._captureCostCount>=100&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0))}}handlePublishStart({room:t}){this.hitTest(t)&&this._localStreamStat.publishStartTime===0&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart({track:t}){t.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),t.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess({track:t}){t.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=0,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),t.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=0,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed({track:t,error:e}){let o={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[e.name]||(e instanceof ue?e.getExtraCode()||e.getCode():q.UNKNOWN);t.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=o,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),t.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=o,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}hasVideoFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&ys)>=0}hasAudioFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&bs)>=0}hasAuxFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&Dn)>=0}hitTest(t){return t===this._room}prepareReport(){if(this._captureCostCount>0&&!this._basicInfo.uint32_audio_capture_cost&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0),this._networkQuality.count>0&&(this._basicInfo.uint32_avg_rtt=Math.floor(this._networkQuality.totalUplinkRTT/this._networkQuality.count),this._basicInfo.uint32_avg_up_loss=Math.floor(this._networkQuality.totalUplinkLoss/this._networkQuality.count)),this._localStreamStat.videoCount>0){this._localStreamStat.statsToReport.uint32_video_big_capture_fps=Math.floor(this._localStreamStat.totalVideoFPS/this._localStreamStat.videoCount),this._localStreamStat.statsToReport.uint32_video_big_bitrate=Math.floor(this._localStreamStat.totalVideoBitrate/this._localStreamStat.videoCount);let t=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),e=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=t<<16|e}this._localStreamStat.audioLevelCount>0&&(this._localStreamStat.statsToReport.uint32_audio_capture_db=Math.floor(this._localStreamStat.totalAudioLevel/this._localStreamStat.audioLevelCount*100)),this._remoteStreamStatMap.forEach((t,e)=>{let{userId:r}=t,o=this._networkQuality.totalDownlinkRTTAndLossMap.get(r);if(o){let{totalLoss:E,count:g,audioDelayCount:_,videoDelayCount:v,totalAudioDelay:L,totalVideoDelay:x}=o;t.statsToReport.uint32_avg_down_loss=Math.floor(E/g),_&&L&&(t.statsToReport.uint32_audio_network_p2p_delay=Math.floor(L/_),t.audioJitterBufferDelay&&(t.statsToReport.uint32_p2p_delay=Math.floor(t.statsToReport.uint32_audio_network_p2p_delay+t.audioJitterBufferDelay))),v&&x&&(t.statsToReport.uint32_video_network_p2p_delay=Math.floor(x/v))}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,N.AUDIO),t.statsToReport.uint32_video_play_time=s.getDuration(e,N.VIDEO)),t.statsToReport.uint32_video_render_first&&(t.statsToReport.uint32_video_render_first=Math.min(t.statsToReport.uint32_video_render_first,cs));let{badCaseDetector:n}=this._room,{dataFreeze:c,count:l}=n.getDataFreezeDuration(e),{renderFreeze:m}=n.getRenderFreezeDuration(e);t.statsToReport.uint32_video_block_count=l,t.statsToReport.uint32_video_block_time=Math.min(c,t.statsToReport.uint32_video_play_time),t.statsToReport.uint32_video_external_block_time=Math.min(m,t.statsToReport.uint32_video_play_time),n.isBlackStream(e)&&t.statsToReport.uint32_video_avg_fps===0?t.statsToReport.uint32_video_black_screen_subjective=1:t.statsToReport.uint32_video_black_screen_subjective=0}),this._pathMainAudioMap.forEach((t,e)=>{if(!this.hasAudioFlag(t.userId)){this._pathMainAudioMap.delete(e);return}t.statsToReport.uint64_play_first_frame_time-t.statsToReport.uint64_start_enter_time>cs&&(t.statsToReport.uint64_play_first_frame_time=t.statsToReport.uint64_start_enter_time+cs)}),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>cs&&(t.statsToReport.uint64_render_first_frame_time=t.statsToReport.uint64_start_enter_time+cs)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>cs&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+cs)}getReportData(){this._basicInfo.uint32_networkType=Ac();let t={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new $a({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:Ns(this._signalInfo.relayIp),uint32_client_ip:Ns(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*Wi(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:Ns(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,bytes_report_buf_from_0x1:this._signalInfo.endReportExtend};return Vn(t),t}report(){return A(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 A(this,null,function*(){if(t.msg_path_enter_room.uint64_start_time===0)return;let e=Number(this._room.sdkAppId),r=yield dl(t),o=r instanceof ArrayBuffer,s=`${oi(e,ji.KEY_POINT)}&gzip=${+o}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(s,r));let c=[this.uploadKVStat(Q),this.uploadKVStat(qo)];n||c.push(ni({url:s,body:r,priority:"low"})),yield Promise.all(c)})}setConnectionType(t){this.connectionType=t,this._basicInfo.uint32_connection_type=t}uploadKVStat(t){return A(this,null,function*(){let e=t.getReportData();if(e.stats_count.length===0&&e.stats_distribution.length===0)return;e.msg_sdk_basic_info=Te(z({},e.msg_sdk_basic_info),{bytes_device_name:this._basicInfo.string_device_name||"",bytes_os_version:this._basicInfo.string_os_version||"",uint32_framework:this._frameWorkType,uint32_network_type:this._basicInfo.uint32_networkType||0}),this._log.debug(e);let r=yield dl(e),o=`${oi(+this._room.sdkAppId,ji.KV_STAT)}&gzip=${+(r instanceof ArrayBuffer)}`,s=!1;navigator.sendBeacon&&(s=navigator.sendBeacon(o,r)),s||ni({url:o,body:r})})}};Z([zo({settings:{timeout:500,retries:3}})],Su.prototype,"upload",1);var cs=5e3,MS={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},$a=class{constructor(t){u(this,"str_identifier");u(this,"str_tinyid");u(this,"uint32_role");this.str_identifier=String(t.userId),this.str_tinyid=String(t.tinyId||0),this.uint32_role=t.role}},Hg=Su;var Np=class{constructor(){u(this,"_startTime");u(this,"_endTime");this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=Ie())}stop(){this._endTime===0&&(this._endTime=Ie())}getDuration(){return this._endTime===0?Ie()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},Au=Np;var Dp=class{constructor(t){u(this,"_room",null);u(this,"_durationMap");u(this,"_eventMap",new Map);this._room=t.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(U.REMOTE_TRACK_SUBSCRIBED,this.handleSubscribed).set(U.REMOTE_TRACK_UNSUBSCRIBED,this.handleUnsubscribed).set(U.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`,N.AUDIO),e.hasVideo&&!r.hasVideo&&this.stopDurationItem(`${o}_main`,N.VIDEO),e.hasAuxiliary&&!r.hasAuxiliary&&this.stopDurationItem(`${o}_auxiliary`,N.VIDEO);let s=(n=this._room)==null?void 0:n.remotePublishedUserMap.get(o);s&&(!e.hasAudio&&r.hasAudio&&s.remoteAudioTrack.isSubscribed&&this.addDuractionItem(o,N.AUDIO,"main"),!e.hasVideo&&r.hasVideo&&s.remoteVideoTrack.isSubscribed&&this.addDuractionItem(o,N.VIDEO,"main"),!e.hasAuxiliary&&r.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(o,N.VIDEO,"auxiliary"))}),this._eventMap.forEach((t,e)=>V.on(e,t,this))}uninstallEvents(){this._eventMap.forEach((t,e)=>V.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 Au,n=this._durationMap.get(o);n?this.isRecording(n[e])||n[e].push(s):this._durationMap.set(o,{userId:t,type:r,audio:e===N.AUDIO?[s]:[],video:e===N.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()}},Wg=Dp;var Mp=class{constructor(t){u(this,"_room");u(this,"_renderFreezeMap",new Map);u(this,"_isVideoPlayingEventFiredMap",new Map);u(this,"_dataFreezeMap",new Map);u(this,"_monitorFreezeData",new Map);u(this,"_eventMap",new Map);this._room=t.room,this.installEvents()}getRenderFreezeMap(){return this._renderFreezeMap}getDataFreezeMap(){return this._dataFreezeMap}installEvents(){this._eventMap.set(U.LEAVE_SUCCESS,({room:t})=>{this.hitTest(t)&&this.stop()}).set(U.PLAY_TRACK_START,this.onPlayTrackStart).set(U.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(U.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(U.PLAYER_STATE_CHANGED,({track:t,state:e,reason:r,type:o})=>{if(!(!t.isRemote||!t.room||!this.hitTest(t.room)||o!==N.VIDEO)){if(e==="PLAYING"){let s=`${t.userId}_${t.streamType}`;this._isVideoPlayingEventFiredMap.set(s,!0)}r===N.MUTE?this.onVideoTrackMuted(t):r===N.UNMUTE&&this.onVideoTrackUnmuted(t)}}).set(U.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach((t,e)=>V.on(e,t,this))}uninstallEvents(){this._eventMap.forEach((t,e)=>V.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 Au;s?s.durationItemList.push(n):this._dataFreezeMap.set(o,{userId:e,type:r,durationItemList:[n],isFreezing(){let c=this.durationItemList[this.durationItemList.length-1];return c&&c.endTime===0}})}onVideoTrackUnmuted(t){if(!t.isSubscribed)return;let{userId:e,streamType:r}=t,o=`${e}_${r}`;this.stopDataFreeze({key:o,userId:e,type:r})}onHearBeatReport({room:t,report:e}){this.hitTest(t)&&e.msg_down_stream_info.forEach(r=>{let o=this._room.remotePublishedUserMap.get(r.msg_user_info.str_identifier);if(!o)return;let{userId:s,muteState:n}=o;r.msg_video_status.forEach(c=>{c.uint32_video_stream_type===2&&n.hasVideo&&!n.videoMuted&&o.remoteVideoTrack.isSubscribed&&this.handleRenderFreeze({userId:s,fps:c.uint32_video_dec_fps,type:"main"}),c.uint32_video_stream_type===7&&n.hasAuxiliary&&o.remoteAuxiliaryTrack.isSubscribed&&this.handleRenderFreeze({userId:s,fps:c.uint32_video_dec_fps,type:"auxiliary"})})})}stopDataFreeze({key:t,userId:e,type:r}){let o=this._dataFreezeMap.get(t);if(!o||!o.isFreezing())return;let s=o.durationItemList[o.durationItemList.length-1];s.stop();let n=s.getDuration();n>Ic?this._monitorFreezeData.set(t,{userId:e,type:r,duration:n}):o.durationItemList.pop()}getTotalDuration(t){return t.reduce((e,r)=>{let o=r.getDuration();return e+Math.min(o,5e3)},0)}handleRenderFreeze(o){return A(this,arguments,function*({userId:t,fps:e,type:r}){let s=`${t}_${r}`,n=this._renderFreezeMap.get(s);if(e<=2){let c=Ie();n&&!n.isFreeze&&(n.freezeTimeline.push({startTime:c,endTime:0}),n.isFreeze=!0),n||this._renderFreezeMap.set(s,{userId:t,type:r,isFreeze:!0,freezeTimeline:[{startTime:c,endTime:0}],renderFreezeTotal:0})}else if(n&&n.isFreeze){n.isFreeze=!1;let c=n.freezeTimeline.pop();if(c){c.endTime=Ie();let l=c.endTime-c.startTime;n.freezeTimeline.push(c),n.renderFreezeTotal+=Math.min(5e3,l)}}})}onPlayTrackStart({track:t}){if(!t.isRemote||!this.hitTest(t.room)||t.kind!==N.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()<Ic&&r.durationItemList.pop()}e.dataFreeze=this.getTotalDuration(r.durationItemList),e.count=r.durationItemList.length}return e}getRenderFreezeDuration(t){let e=this._renderFreezeMap.get(t),r=0,o=0;if(e)if(!e.isFreeze)r=e.renderFreezeTotal;else{let s=Ie(),n=e.freezeTimeline[e.freezeTimeline.length-1],c=s-n.startTime;r=e.renderFreezeTotal+Math.min(c,5e3),o=e.freezeTimeline.length}return{renderFreeze:r,count:o}}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(t){return this._isVideoPlayingEventFiredMap.has(t)?!this._isVideoPlayingEventFiredMap.get(t):!1}resetMonitor(){this._monitorFreezeData.clear()}hitTest(t){return t===this._room}destroy(){this.uninstallEvents()}},Gg=Mp;var qg=Gi(Zi(),1);var wS=[1,0,0,0,1,1,0,1],yu=class extends Gt{constructor(e,r,o,s){super(e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"transform",logger:r});u(this,"mirror",!1);u(this,"rotation",0);if(o&&(this.mirror=o),s&&(this.rotation=s),e instanceof Tt)try{this.setTexBuffer(wS)}catch(n){e.destroy(new ue({code:q.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${n.message||n}`}))}}draw2d(e,r,o,s,n){if(this.ctx2d){this.ctx2d.save(),this.mirror&&(this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0)),this.rotation===90?(this.ctx2d.translate(s,0),this.ctx2d.rotate(Math.PI/2),this.ctx2d.scale(n/s,s/n)):this.rotation===180?(this.ctx2d.translate(this.width,this.height),this.ctx2d.rotate(Math.PI)):this.rotation===270&&(this.ctx2d.translate(0,n),this.ctx2d.rotate(3*Math.PI/2),this.ctx2d.scale(n/s,s/n));let c=super.draw2d(e,r,o,s,n);return this.ctx2d.restore(),c}return!1}render(e){var r;return(r=this.input)!=null&&r.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}};var wp=class{constructor(t,e){this.node=t;this.layout=e;u(this,"positionBuffer")}get x(){return this.layout.x||this.node.x}get y(){return this.layout.y||this.node.y}get width(){return this.layout.width||this.node.width}get height(){return this.layout.height||this.node.height}get right(){return this.x+this.width}get bottom(){return this.y+this.height}},Ba=class extends Gt{constructor(e,r){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,matchInputSize:!1,logger:r});u(this,"inputs",[])}addInput(e,r){if(this.inputs[r.zIndex])throw new Error("input already exists");let o=new wp(e,r);this.inputs[r.zIndex]=o}changeInputLayout(e,r){let o=this.inputs.findIndex(s=>s?s.node===e:!1);o<0||Object.entries(r).forEach(([s,n])=>{P(n)||(this.inputs[o].layout[s]=n)})}resize(e,r){if(!this.matchInputSize){super.resize(e,r);return}let o=this.inputs.reduce((s,n)=>n?Object.assign(s,{width:Math.max(s.width,n.right),height:Math.max(s.height,n.bottom)}):s,{width:0,height:0});super.resize(o.width,o.height),this.context instanceof Tt&&this.inputs.forEach(s=>{if(s){let n=this.layout2texCoords(s);s.positionBuffer?this.changeBufferData(s.positionBuffer,n):s.positionBuffer=this.createBuffer(n)}})}connect(e,...r){return super.connect(e,...r),this.matchInputSize&&this.resize(0,0),e}removeInput(e){this.inputs[this.inputs.findIndex(r=>(r==null?void 0:r.node)===e)]=void 0}render(e){let r=this.context.ctx;if(r.clearColor(0,0,0,0),this.inputs.reduce((s,n)=>(n==null?void 0:n.node.requestFrame(e))||s,!1)&&r){this.useProgram(),r.enable(r.BLEND),r.blendFunc(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let s=0;s<this.inputs.length;s++){let n=this.inputs[s];n&&(n.node.useTexture(),this.draw(n.positionBuffer))}return!0}return!1}render2d(e){if(this.inputs.reduce((o,s)=>(s==null?void 0:s.node.requestFrame(e))||o,!1)&&this.ctx2d){this.ctx2d.fillStyle="black",this.ctx2d.fillRect(0,0,this.width,this.height);for(let o=0;o<this.inputs.length;o++){let s=this.inputs[o];s&&this.draw2d(s.node.image,s.x,s.y,s.width,s.height)}return!0}return!1}getInfo(){let{totalFrames:e,x:r,y:o,width:s,height:n,name:c}=this,l=Date.now(),m=(e-this.lastInfo.totalFrames)/((l-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:r,y:o,width:s,height:n,timestamp:l,fps:m,name:c},z({parent:this.inputs.filter(E=>E).map(E=>E.node.getInfo())},this.lastInfo)}close(){super.close(),this.inputs.forEach(e=>{var r,o;if(e&&((r=e.node)==null||r.disconnect(),e.positionBuffer&&this.context instanceof Tt))try{(o=this.context.ctx)==null||o.deleteBuffer(e.positionBuffer)}catch(s){}})}};var bu=class{constructor(t,e,r,o=4/3){this.vbMode=t;this.faceDetector=e;this.logger=r;u(this,"animationState");u(this,"originalAspect");u(this,"totalOffsetX",0);u(this,"totalOffsetY",0);u(this,"defaultScaleRatio",.1);u(this,"isRecovering",!1);u(this,"boundaryY",280);u(this,"lastActionTime",0);u(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.faceDetector),this.originalAspect=o||4/3}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?Q.addSuccessEvent({key:s.key}):Q.addFailedEvent({key:s.key,error:s.error}))}actionCentering(t){let e=Date.now();if(this.animation(),!this.faceDetector||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;try{let s=this.faceDetector.detectForVideo(t,Date.now());if(s.detections.length<=0){this.vbMode===1&&this.recoverOriginal(r,o);return}let n=s.detections[0].boundingBox,c=n.originX,l=n.originY,m=n.width,E=n.height;this.vbMode===1?this.dualStageCropping(r,o,c,l,m,E):this.vbMode===2&&this.movingPortrait(r,o,c,l,m,E)}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,c=.4){let l=t+r/2,m=e+o/2,E,g,{min:_,offset:v}=this.calculateBoundary(l,s,t,r),{min:L,offset:x}=this.calculateBoundary(m,n,e,o);return E=2*_+r,g=2*L+o,E/g>this.originalAspect?(E=g*this.originalAspect,v=l-E/2):(g=E/this.originalAspect,x=m-g/2),r/s>c&&(v=0,x=0,E=s,g=n),v=Math.max(0,Math.min(v,s-E)),x=Math.max(0,Math.min(x,n-g)),{sx:v,sy:x,cropWidth:E,cropHeight:g,timestamp:Date.now()}}processFacePositionCrop(t,e,r){if(!this.animationState.current||!this.animationState.target){let c={sx:0,sy:0,cropWidth:e,cropHeight:r,timestamp:Date.now()};this.animationState.current=c,this.animationState.target=c;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=z({},t),this.animationState.target=z({},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)),ke(this.animationState.current.scaleOffsetX)&&ke(this.animationState.target.scaleOffsetX)&&ke(this.animationState.current.scaleOffsetY)&&ke(this.animationState.target.scaleOffsetY)){let n=(this.animationState.target.scaleOffsetX-this.animationState.current.scaleOffsetX)*r(e);this.animationState.current.scaleOffsetX+=n;let c=(this.animationState.target.scaleOffsetY-this.animationState.current.scaleOffsetY)*r(e);this.animationState.current.scaleOffsetY+=c}}e>=1&&(this.animationState.animating=!1,this.animationState.current=this.animationState.target,this.isRecovering=!1)}positionDistance(t,e){return Math.sqrt(Wi(t.sx-e.sx,2)+Wi(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,c=.3){if(this.isRecovering)return;let l=this.calculateTargetPosition(r,o,s,n,t,e);this.processFacePositionCrop(l,t,e),s*n/l.cropWidth/l.cropHeight>c&&this.recoverOriginal(t,e)}movingPortrait(t,e,r,o,s,n){var l,m,E,g,_,v,L,x,M,B,ee,pe;let c={sx:r+s/2+this.totalOffsetX,sy:o+n/2+this.totalOffsetY,cropWidth:t,cropHeight:e,scaleRatio:(m=(l=this.animationState.current)==null?void 0:l.scaleRatio)!=null?m:1,scaleOffsetX:(g=(E=this.animationState.current)==null?void 0:E.scaleOffsetX)!=null?g:0,scaleOffsetY:(v=(_=this.animationState.current)==null?void 0:_.scaleOffsetY)!=null?v:0,timestamp:Date.now()};this.animationState.target={sx:t/2,sy:o+n/2,cropWidth:t,cropHeight:e,scaleRatio:(x=(L=this.animationState.target)==null?void 0:L.scaleRatio)!=null?x:1,scaleOffsetX:(B=(M=this.animationState.target)==null?void 0:M.scaleOffsetX)!=null?B:0,scaleOffsetY:(pe=(ee=this.animationState.target)==null?void 0:ee.scaleOffsetY)!=null?pe: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(c)}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 OS=`#version 300 es
|
|
102
102
|
in vec2 a_position;
|
|
103
103
|
in vec2 a_texCoord;
|
|
104
104
|
out vec2 v_texCoord;
|