trtc-sdk-v5 5.11.0-beta.7 → 5.11.0-beta.9
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/small-stream-auto-switcher/small-stream-auto-switcher.esm.js +1 -1
- package/plugins/small-stream-auto-switcher/small-stream-auto-switcher.umd.js +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 +4 -4
- package/trtc.js +1 -1
package/trtc.esm.js
CHANGED
|
@@ -24,7 +24,7 @@ Refer to: ${xh("en",a)}
|
|
|
24
24
|
}
|
|
25
25
|
};
|
|
26
26
|
`],{type:"application/javascript"}))),Me.sharedWorker.onmessage=e=>{var t;if(e.data.type==="tick"){let r=Me.workerTasks.get(e.data.taskId);r&&(Me.isBreakLoop(r)?((t=Me.sharedWorker)==null||t.postMessage({type:"stop",taskId:r.taskID}),Me.workerTasks.delete(r.taskID)):(r.callback(),r.loopCount+=1))}}),Me.workerTasks.set(i.taskID,i),Me.sharedWorker.postMessage({taskId:i.taskID,delay:i.delay,type:"start"})}static timeout(i){let e=()=>{if(i.callback(),i.loopCount+=1,!Me.isBreakLoop(i))return i.timeoutID=setTimeout(e,i.delay)};return i.timeoutID=setTimeout(e,i.delay)}static ric(i){let e=U(),t,r=()=>{if(t=U()-e,t>=i.delay&&(e=U()-Math.floor(t%i.delay),i.callback(),i.loopCount+=1),!Me.isBreakLoop(i))return i.ricID=im(r,{timeout:i.delay})};return i.ricID=im(r,{timeout:i.delay})}static raf(i){let e=U(),t,r=()=>{if(document.hidden&&i.backgroundTask)return t=U()-e,e=U(),i.callback(),i.loopCount+=1,Me.isBreakLoop(i)?void 0:i.timeoutID=setTimeout(r,i.delay-Math.floor(t%i.delay));if(t=U()-e,t>=i.delay&&(e=U()-Math.floor(t%i.delay),i.callback(),i.loopCount+=1),!Me.isBreakLoop(i))return i.rafID=requestAnimationFrame(r)};if(i.rafID=requestAnimationFrame(r),i.backgroundTask){let o=()=>{if(document.hidden){let n=U()-e;n>=i.delay?r():i.timeoutID=setTimeout(r,i.delay-n)}};document.addEventListener("visibilitychange",o),i.onVisibilitychange=o,document.hidden&&o()}return i.taskID}static hasTask(i){return this.taskMap.has(i)}static clearTask(i){if(!this.taskMap.has(i))return!0;let{intervalID:e,timeoutID:t,rafID:r,ricID:o,onVisibilitychange:n}=this.taskMap.get(i);return e&&clearInterval(e),t&&clearTimeout(t),r&&rm&&rm(r),o&&J_(o),n&&document.removeEventListener("visibilitychange",n),this.taskMap.delete(i),!0}static isBreakLoop(i){return this.hasTask(i.taskID)?i.count!==0&&i.loopCount>=i.count?(this.clearTask(i.taskID),!0):!1:!0}};d(Me,"taskMap",new Map),d(Me,"currentTaskID",1),d(Me,"sharedWorker",null),d(Me,"workerTasks",new Map);var Zd=Me,oe=Zd;var mI={STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",STREAM_UPDATED:"stream-updated",STREAM_SUBSCRIBED:"stream-subscribed",CONNECTION_STATE_CHANGED:"connection-state-changed",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",MUTE_AUDIO:"mute-audio",MUTE_VIDEO:"mute-video",UNMUTE_AUDIO:"unmute-audio",UNMUTE_VIDEO:"unmute-video",CLIENT_BANNED:"client-banned",NETWORK_QUALITY:"network-quality",AUDIO_VOLUME:"audio-volume",SEI_MESSAGE:p.SEI_MESSAGE,ERROR:"error"};var ue={LOADED_DATA:p.LOADEDDATA,LOADED_META_DATA:p.LOADEDMETADATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error"};var ai={};Si(ai,{create:()=>qe,remove:()=>ve});var $o=new WeakMap;function qe(s,i){$o.has(s)||$o.set(s,[]);let e=$o.get(s),r={add:(o,n)=>("addEventListener"in i?(e.push(i.removeEventListener.bind(i,o,n)),i.addEventListener(o,n)):(e.push(i.off.bind(i,o,n)),i.on(o,n)),r)};return r}function ve(s){let i=$o.get(s);i&&(i.forEach(e=>e()),$o.delete(s))}var el=class{constructor(){d(this,"_roomIdMap",new Map);d(this,"_configs");typeof registerProcessor=="undefined"&&(this._configs={sdkAppId:"",userId:"",version:Pe,env:Ii.QCLOUD,browserVersion:Zt.name+Zt.version,ua:navigator.userAgent})}setConfig({sdkAppId:i,env:e,userId:t,roomId:r}){i!==this._configs.sdkAppId&&(this._configs.sdkAppId=String(i)),this._configs.env=e,this._configs.userId=t,this._roomIdMap.set(t,String(r))}logSuccessEvent(i){Vt||!C.isAbleToUpload||this._configs.env===Ii.QCLOUD&&this.uploadEventToKibana(L(N({},i),{result:"success"}))}logFailedEvent(i){if(Vt||!C.isAbleToUpload)return;let{eventType:e,code:t,error:r,userId:o}=i,n={roomId:this._roomIdMap.get(o||this._configs.userId),userId:o,eventType:e,result:"failed",code:t||(r==null?void 0:r.extraCode)||(r==null?void 0:r.code)||I.UNKNOWN};this._configs.env===Ii.QCLOUD&&this.uploadEventToKibana(L(N({},n),{error:r}))}uploadEventToKibana(i){let e=`stat-${i.eventType}-${i.result}`;(i.eventType==="delta-join"||i.eventType==="delta-leave"||i.eventType==="delta-publish")&&(e=`${i.eventType}:${i.delta}`),this.uploadEvent({log:e,userId:i.userId}),i.result==="failed"&&(e=`stat-${i.eventType}-${i.result}-${i.code}`,this.uploadEvent({log:e,userId:i.userId,error:i.error}))}uploadEvent({log:i,userId:e,error:t}){let r={timestamp:An(),sdkAppId:this._configs.sdkAppId,userId:e||this._configs.userId,version:Pe,log:i};t&&(r.errorInfo=t.message,t.stack&&(r.errorInfo+=`
|
|
27
|
-
${t.stack}`)),this.sendRequest(yi(this._configs.sdkAppId,Ki.LOG),r)}sendRequest(i,e){setTimeout(()=>Di({url:i,body:JSON.stringify(e),priority:"low"}).catch(()=>{}),2e3)}},re=new el;var ci=new WeakMap;function pt({settings:s={retries:5,timeout:2e3},onError:i,onRetrying:e,onRetryFailed:t}){return function(r,o,n){let a=Yt({retryFunction:n.value,settings:s,onError({error:c,retry:l,reject:h,retryFuncArgs:u}){var m;i?i.call(this,c,()=>{var g;(g=ci.get(r))!=null&&g.has(o)?l():h(c)},h,u):(m=ci.get(r))!=null&&m.has(o)?l():h(c)},onRetrying(c,l){var h;Qt(e)&&e.call(this,c,l),(h=ci.get(r))!=null&&h.has(o)&&(ci.get(r).get(o).stopRetry=l)},onRetryFailed:t});return n.value=function(...c){let l=ci.get(r);return l?l.set(o,{args:c}):ci.set(r,new Map([[o,{args:c}]])),a.apply(this,c).finally(()=>{var h;return(h=ci.get(r))==null?void 0:h.delete(o)})},n}}function Ho({fnName:s,callback:i,validateArgs:e=!0}){return function(t,r,o){let n=o.value;return o.value=function(...a){var c,l;if((c=ci.get(t))!=null&&c.has(s)){let{stopRetry:h,args:u}=ci.get(t).get(s),m=!0;if(e){for(let g of u)if(!a.find(D=>D===g)){m=!1;break}}m&&(i&&i.apply(this,a),h&&h(),(l=ci.get(t))==null||l.delete(s))}return n.apply(this,a)},o}}var di=class extends H{constructor(e,t){super(e.id,`${t}-player`);this.kind=t;d(this,"id");d(this,"element",null);d(this,"track");d(this,"url");d(this,"attr");d(this,"mode");d(this,"muted");d(this,"_log");d(this,"_pausedRetryCount");d(this,"_isElementPlayingFired",!1);d(this,"_interval");d(this,"_delayDestroyTimeoutId",0);d(this,"_playSuccessResolve");d(this,"_isReplayByRecreateMediaStreamCalled",!1);d(this,"isInAutoPlayFailedState",!1);this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=Ir,this._state="STOPPED",this.bindTrackEvents(),this._log.info(`create ${t}-player ${this.id}`)}get isPlaying(){var e;return this._state==="PLAYING"&&((e=this.element)==null?void 0:e.paused)===!1}get isPaused(){return this._state==="PAUSED"}get isStopped(){return this._state==="STOPPED"}setAttr(e){this.attr=e}setUrl(e){this.track&&(this.unbindTrackEvents(),this.element&&(this.element.srcObject=null),this.track=null),e!==this.url&&(this.url=e,e!==null&&this.element&&(this.element.crossOrigin="anonymous",this.element.src=e))}play(){return f(this,null,function*(){if(!this.isPlaying)try{this._delayDestroyTimeoutId&&(clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0,this.bindTrackEvents(),this.bindElementEvents()),this.bindAutoPlayEvent(),yield new Promise((e,t)=>{this._playSuccessResolve=e,this.element.play().then(e,t)})}catch(e){let t=x({key:P.PLAY_FAILED,data:{media:this.kind,error:e}});if(this._log.warn(e),t.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new y({code:I.PLAY_NOT_ALLOWED,message:t})}})}stop(e=0){this._isElementPlayingFired=!1,this.unbindEvents(),e>0&&!nr?this._delayDestroyTimeoutId||(this._log.info(`destroy element after 3 * ${e}`),this._delayDestroyTimeoutId=setTimeout(()=>this.destroyElement(),3*e)):this.destroyElement(),this.handleStopped(p.ENDED),this._interval>0&&oe.clearTask(this._interval)}destroyElement(){this.element&&(this._log.debug("destroy element"),this.element.remove(),this.element.srcObject=null,this.element=null),clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0}pause(){var e;this.isPlaying&&((e=this.element)==null||e.pause())}resume(){return this._log.info("resume"),this.isPlaying?Promise.resolve():Sd?this.replay():this.play().catch(()=>{})}setMuted(e){this.element&&(this.element.muted=e),this.muted=e}replay(){return this.stop(),this.play().catch(()=>{})}bindElementEvents(){if(this.element){let e=this.handleElementEvent.bind(this);return qe(this.element,this.element).add(p.PLAYING,e).add(p.ENDED,e).add(p.PAUSE,e).add(p.ERROR,e).add(p.LOADEDDATA,e).add(p.LOADEDMETADATA,e)}}bindTrackEvents(e=this.track){if(e){let t=this.handleTrackEvent.bind(this);ai==null||ai.create(e,e).add(p.ENDED,t).add(p.MUTE,t).add(p.UNMUTE,t),e.readyState===p.ENDED&&this.handleTrackEvent({type:p.ENDED}),e.muted&&this.handleTrackEvent({type:p.MUTE})}}bindAutoPlayEvent(){E.on(A.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(e=this.track){e&&ve(e)}unbindEvents(){this.element&&ve(this.element),this.unbindTrackEvents(),E.off(A.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case p.PLAYING:this.isInAutoPlayFailedState=!1,this._isElementPlayingFired=!0,this._log.info(`${this.kind} player is playing`),this.handlePlaying(p.PLAYING),this._interval&&(oe.clearTask(this._interval),this._interval=-1);break;case p.ENDED:this._log.info(`${this.kind} player is ended`),this.handleStopped(p.ENDED);break;case p.PAUSE:this._log.info(`${this.kind} player is paused`),this.handlePaused(p.PAUSE),Ie&&(this._interval=oe.run("timeout",()=>{this.element&&this._state==="PAUSED"&&this.resume()},{delay:3e3}));break;case p.ERROR:if(this.element&&this.element.error){this.handlePaused(p.ERROR);let{code:r,message:o}=this.element.error;this._log.error(`${this.kind} ${this._log.isLocal?"local":"remote"} MediaError code: ${r} message: ${o} userAgent: ${navigator.userAgent}`),re.uploadEvent({log:`stat-${this.kind}-${st.PLAYER_ERROR}-${r}-${navigator.userAgent}`,error:this.element.error}),_d||fd?this.emit(ue.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case p.LOADEDDATA:this.kind===p.VIDEO&&this.emit(ue.LOADED_DATA);break;case p.LOADEDMETADATA:this.kind===p.VIDEO&&this.emit(ue.LOADED_META_DATA);break}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then(()=>{this._log.warn("replayByRecreateMediaStream success"),re.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),b.addSuccessEvent({key:this.kind===p.AUDIO?506700:516700})}).catch(()=>{var t;this._log.error("replayByRecreateMediaStream failed"),re.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),b.addFailedEvent({key:this.kind===p.AUDIO?506700:516700,error:(t=this.element)==null?void 0:t.error}),this.emit(ue.ERROR,e)})}doReplayByRecreateMediaStream(e){return this._log.warn(`delay ${e}ms to recreate mediaStream`),new Promise((t,r)=>{Ni(e).then(()=>{this.element&&(this.element.srcObject=null,this.element.srcObject=new MediaStream([this.track]),this._log.warn("recreated mediaStream"),this.element.onerror=()=>{var o,n,a;this._log.warn(`element onerror ${(n=(o=this.element)==null?void 0:o.error)==null?void 0:n.code} fired after recreated mediaStream`),r((a=this.element)==null?void 0:a.error)}),Ni(5e3).then(()=>{var o,n;(!this.isPlaying||(o=this.element)!=null&&o.error)&&r((n=this.element)==null?void 0:n.error),t()})})}).finally(()=>{this.element&&(this.element.onerror=null)})}handleTrackEvent(e){switch(e.type){case p.ENDED:this.handleStopped(p.ENDED);break;case p.MUTE:this.handlePaused(p.MUTE);break;case p.UNMUTE:this._isElementPlayingFired?this.handlePlaying(p.UNMUTE):this.mode>0&&this.handlePlaying(this.mode.toString()),this.isPaused&&this._log.isLocal&&(this._log.warn("track unmuted, resume"),this.resume());break}}handlePlaying(e){var t;(t=this._playSuccessResolve)==null||t.call(this,e),this.emit(ue.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this.emit(ue.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this.emit(ue.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};v([pt({settings:{retries:2,timeout:0},onError(e,t,r,o){o[0]=(o[0]||1e3)+1e3,t()}})],di.prototype,"doReplayByRecreateMediaStream",1),v([Te([],"PLAYING",{sync:!0})],di.prototype,"handlePlaying",1),v([Te("PLAYING","PAUSED",{ignoreError:!0,sync:!0})],di.prototype,"handlePaused",1),v([Te([],"STOPPED",{sync:!0})],di.prototype,"handleStopped",1);var Vi="trtc_autoplay",tl=`${Vi}_mask`,Ds=`${Vi}_wrapper`,sm=`${Vi}_header`,il=`${Vi}_content`,Sa=`${Vi}_action_wrapper`,rl=`${Vi}_question`,sl=`${Vi}_collapse`,Ia=`${Vi}_action_confirm`,om=`${Vi}_detail`,nm="#2473E8",nl="dialog",j_=`${nl}-show`,X_=`${nl}-1`,z_=`${nl}-2`,am=!1,al=()=>!!document.querySelector(`.${Ds}`),dm=`${Xt}/${kt()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,cm=`<br><a href='${dm}' target='_blank'>${kt()?"\u5176\u4ED6\u65B9\u6848\uFF1F":"Any other solution?"}</a>`,Q_=`${kt()?`\u6D4F\u89C8\u5668\u81EA\u52A8\u64AD\u653E\u7B56\u7565\uFF1A\u5728\u7528\u6237\u4E0E\u9875\u9762\u4EA7\u751F\u4EA4\u4E92\uFF08\u70B9\u51FB\u3001\u89E6\u6478\uFF09\u4E4B\u524D\uFF0C\u6D4F\u89C8\u5668\u7981\u6B62\u64AD\u653E\u6709\u58F0\u5A92\u4F53\u3002\u8BE5\u5F39\u7A97\u7528\u4E8E\u5E2E\u52A9\u7528\u6237\u6062\u590D\u97F3\u89C6\u9891\u64AD\u653E\u3002${cm}`:`Autoplay Policy: Before user interacts with the web page (clicking, touching), page will not be allowed to play media with sound. This Dialog is used to help users resume playback. ${cm}`}`,ol=class{constructor(){d(this,"content","\u97F3\u89C6\u9891\u64AD\u653E\u88AB\u6D4F\u89C8\u5668\u62E6\u622A\uFF0C\u8BF7\u70B9\u51FB\u201C\u6062\u590D\u64AD\u653E\u201D\u3002");d(this,"_dialogNode",null);d(this,"_bodyPosition","");d(this,"_showDetail",!1);d(this,"_isCollapseClicked",!1);d(this,"_isQuestionClicked",!1);if(kt()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!am){let i=document.createElement("style");i.innerHTML=`.${tl}{position:fixed;top:0;left:0;right:0;bottom:0;width:100vw;height:100vh;display:flex;justify-content:center;align-items:center;background:rgba(0,0,0,0.5);z-index:1500;}.${tl} div:not(.${Sa}){display:block !important;}.${Ds}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${Ds} a{color:${nm};}.${sm}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${il}{margin:8px 0;}.${Sa}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${sl}{margin-right:auto;cursor:pointer}.${rl}{height:100%;line-height:16px;cursor:pointer;}.${Ia}{margin-left:8px;color:#fff;background:${nm};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${Ia}:hover{opacity:0.9;}.${sl},.${Ia},.${il},.${rl}{font-size:14px;}@media screen and (max-width:750px){.${Ds}{width:80vw;}}`,document.head.appendChild(i),am=!0}this.addDiaLog()}createDiaLog(){let i=document.createElement("template");i.innerHTML=`<div class="${tl}"><div class='${Ds}'><div class='${sm}'>${location.host}</div><div class='${il}'>${this.content}</div><div class='${om}' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">${Q_}</div><div class='${Sa}'></div></div></div>`.trim();let e=document.createElement("button");e.className=Ia,e.innerText=kt()?"\u6062\u590D\u64AD\u653E":"Resume",e.onclick=this.onConfirm.bind(this);let t=document.createElement("div");t.className=rl,t.innerHTML=`<?xml version="1.0" encoding="UTF-8"?>
|
|
27
|
+
${t.stack}`)),this.sendRequest(yi(this._configs.sdkAppId,Ki.LOG),r)}sendRequest(i,e){setTimeout(()=>Di({url:i,body:JSON.stringify(e),priority:"low"}).catch(()=>{}),2e3)}},re=new el;var ci=new WeakMap;function pt({settings:s={retries:5,timeout:2e3},onError:i,onRetrying:e,onRetryFailed:t}){return function(r,o,n){let a=Yt({retryFunction:n.value,settings:s,onError({error:c,retry:l,reject:h,retryFuncArgs:u}){var m;i?i.call(this,c,()=>{var g;(g=ci.get(r))!=null&&g.has(o)?l():h(c)},h,u):(m=ci.get(r))!=null&&m.has(o)?l():h(c)},onRetrying(c,l){var h;Qt(e)&&e.call(this,c,l),(h=ci.get(r))!=null&&h.has(o)&&(ci.get(r).get(o).stopRetry=l)},onRetryFailed:t});return n.value=function(...c){let l=ci.get(r);return l?l.set(o,{args:c}):ci.set(r,new Map([[o,{args:c}]])),a.apply(this,c).finally(()=>{var h;return(h=ci.get(r))==null?void 0:h.delete(o)})},n}}function Ho({fnName:s,callback:i,validateArgs:e=!0}){return function(t,r,o){let n=o.value;return o.value=function(...a){var c,l;if((c=ci.get(t))!=null&&c.has(s)){let{stopRetry:h,args:u}=ci.get(t).get(s),m=!0;if(e){for(let g of u)if(!a.find(D=>D===g)){m=!1;break}}m&&(i&&i.apply(this,a),h&&h(),(l=ci.get(t))==null||l.delete(s))}return n.apply(this,a)},o}}var di=class extends H{constructor(e,t){super(e.id,`${t}-player`);this.kind=t;d(this,"id");d(this,"element",null);d(this,"track");d(this,"url");d(this,"attr");d(this,"mode");d(this,"muted");d(this,"_log");d(this,"_pausedRetryCount");d(this,"_isElementPlayingFired",!1);d(this,"_interval");d(this,"_delayDestroyTimeoutId",0);d(this,"_playSuccessResolve");d(this,"_isReplayByRecreateMediaStreamCalled",!1);d(this,"isInAutoPlayFailedState",!1);this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=Ir,this._state="STOPPED",this.bindTrackEvents(),this._log.info(`create ${t}-player ${this.id}`)}get isPlaying(){var e;return this._state==="PLAYING"&&((e=this.element)==null?void 0:e.paused)===!1}get isPaused(){var e;return this._state==="PAUSED"||((e=this.element)==null?void 0:e.paused)===!0}get isStopped(){return this._state==="STOPPED"}setAttr(e){this.attr=e}setUrl(e){this.track&&(this.unbindTrackEvents(),this.element&&(this.element.srcObject=null),this.track=null),e!==this.url&&(this.url=e,e!==null&&this.element&&(this.element.crossOrigin="anonymous",this.element.src=e))}play(){return f(this,null,function*(){if(!this.isPlaying)try{this._delayDestroyTimeoutId&&(clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0,this.bindTrackEvents(),this.bindElementEvents()),this.bindAutoPlayEvent(),yield new Promise((e,t)=>{this._playSuccessResolve=e,this.element.play().then(e,t)})}catch(e){let t=x({key:P.PLAY_FAILED,data:{media:this.kind,error:e}});if(this._log.warn(e),t.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new y({code:I.PLAY_NOT_ALLOWED,message:t})}})}stop(e=0){this._isElementPlayingFired=!1,this.unbindEvents(),e>0&&!nr?this._delayDestroyTimeoutId||(this._log.info(`destroy element after 3 * ${e}`),this._delayDestroyTimeoutId=setTimeout(()=>this.destroyElement(),3*e)):this.destroyElement(),this.handleStopped(p.ENDED),this._interval>0&&oe.clearTask(this._interval)}destroyElement(){this.element&&(this._log.debug("destroy element"),this.element.remove(),this.element.srcObject=null,this.element=null),clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0}pause(){var e;this.isPlaying&&((e=this.element)==null||e.pause())}resume(){return this._log.info("resume"),this.isPlaying?Promise.resolve():Sd?this.replay():this.play().catch(()=>{})}setMuted(e){this.element&&(this.element.muted=e),this.muted=e}replay(){return this.stop(),this.play().catch(()=>{})}bindElementEvents(){if(this.element){let e=this.handleElementEvent.bind(this);return qe(this.element,this.element).add(p.PLAYING,e).add(p.ENDED,e).add(p.PAUSE,e).add(p.ERROR,e).add(p.LOADEDDATA,e).add(p.LOADEDMETADATA,e)}}bindTrackEvents(e=this.track){if(e){let t=this.handleTrackEvent.bind(this);ai==null||ai.create(e,e).add(p.ENDED,t).add(p.MUTE,t).add(p.UNMUTE,t),e.readyState===p.ENDED&&this.handleTrackEvent({type:p.ENDED}),e.muted&&this.handleTrackEvent({type:p.MUTE})}}bindAutoPlayEvent(){E.on(A.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(e=this.track){e&&ve(e)}unbindEvents(){this.element&&ve(this.element),this.unbindTrackEvents(),E.off(A.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case p.PLAYING:this.isInAutoPlayFailedState=!1,this._isElementPlayingFired=!0,this._log.info(`${this.kind} player is playing`),this.handlePlaying(p.PLAYING),this._interval&&(oe.clearTask(this._interval),this._interval=-1);break;case p.ENDED:this._log.info(`${this.kind} player is ended`),this.handleStopped(p.ENDED);break;case p.PAUSE:this._log.info(`${this.kind} player is paused`),this.handlePaused(p.PAUSE),Ie&&(this._interval=oe.run("timeout",()=>{this.element&&this._state==="PAUSED"&&this.resume()},{delay:3e3}));break;case p.ERROR:if(this.element&&this.element.error){this.handlePaused(p.ERROR);let{code:r,message:o}=this.element.error;this._log.error(`${this.kind} ${this._log.isLocal?"local":"remote"} MediaError code: ${r} message: ${o} userAgent: ${navigator.userAgent}`),re.uploadEvent({log:`stat-${this.kind}-${st.PLAYER_ERROR}-${r}-${navigator.userAgent}`,error:this.element.error}),_d||fd?this.emit(ue.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case p.LOADEDDATA:this.kind===p.VIDEO&&this.emit(ue.LOADED_DATA);break;case p.LOADEDMETADATA:this.kind===p.VIDEO&&this.emit(ue.LOADED_META_DATA);break}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then(()=>{this._log.warn("replayByRecreateMediaStream success"),re.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),b.addSuccessEvent({key:this.kind===p.AUDIO?506700:516700})}).catch(()=>{var t;this._log.error("replayByRecreateMediaStream failed"),re.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),b.addFailedEvent({key:this.kind===p.AUDIO?506700:516700,error:(t=this.element)==null?void 0:t.error}),this.emit(ue.ERROR,e)})}doReplayByRecreateMediaStream(e){return this._log.warn(`delay ${e}ms to recreate mediaStream`),new Promise((t,r)=>{Ni(e).then(()=>{this.element&&(this.element.srcObject=null,this.element.srcObject=new MediaStream([this.track]),this._log.warn("recreated mediaStream"),this.element.onerror=()=>{var o,n,a;this._log.warn(`element onerror ${(n=(o=this.element)==null?void 0:o.error)==null?void 0:n.code} fired after recreated mediaStream`),r((a=this.element)==null?void 0:a.error)}),Ni(5e3).then(()=>{var o,n;(!this.isPlaying||(o=this.element)!=null&&o.error)&&r((n=this.element)==null?void 0:n.error),t()})})}).finally(()=>{this.element&&(this.element.onerror=null)})}handleTrackEvent(e){return f(this,null,function*(){switch(e.type){case p.ENDED:this.handleStopped(p.ENDED);break;case p.MUTE:this.handlePaused(p.MUTE);break;case p.UNMUTE:this.mode>0?this.handlePlaying(this.mode.toString()):this.element&&(this.element.paused&&(this._log.warn("track unmuted and element is paused, resume"),yield this.resume()),!this.element.paused&&this._isElementPlayingFired&&this.handlePlaying(p.UNMUTE));break}})}handlePlaying(e){var t;this._log.debug("handlePlaying",e),(t=this._playSuccessResolve)==null||t.call(this,e),this.emit(ue.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this._log.debug("handlePaused",e),this.emit(ue.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this._log.debug("handleStopped",e),this.emit(ue.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};v([pt({settings:{retries:2,timeout:0},onError(e,t,r,o){o[0]=(o[0]||1e3)+1e3,t()}})],di.prototype,"doReplayByRecreateMediaStream",1),v([Te([],"PLAYING",{sync:!0})],di.prototype,"handlePlaying",1),v([Te("PLAYING","PAUSED",{ignoreError:!0,sync:!0})],di.prototype,"handlePaused",1),v([Te([],"STOPPED",{sync:!0})],di.prototype,"handleStopped",1);var Vi="trtc_autoplay",tl=`${Vi}_mask`,Ds=`${Vi}_wrapper`,sm=`${Vi}_header`,il=`${Vi}_content`,Sa=`${Vi}_action_wrapper`,rl=`${Vi}_question`,sl=`${Vi}_collapse`,Ia=`${Vi}_action_confirm`,om=`${Vi}_detail`,nm="#2473E8",nl="dialog",j_=`${nl}-show`,X_=`${nl}-1`,z_=`${nl}-2`,am=!1,al=()=>!!document.querySelector(`.${Ds}`),dm=`${Xt}/${kt()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,cm=`<br><a href='${dm}' target='_blank'>${kt()?"\u5176\u4ED6\u65B9\u6848\uFF1F":"Any other solution?"}</a>`,Q_=`${kt()?`\u6D4F\u89C8\u5668\u81EA\u52A8\u64AD\u653E\u7B56\u7565\uFF1A\u5728\u7528\u6237\u4E0E\u9875\u9762\u4EA7\u751F\u4EA4\u4E92\uFF08\u70B9\u51FB\u3001\u89E6\u6478\uFF09\u4E4B\u524D\uFF0C\u6D4F\u89C8\u5668\u7981\u6B62\u64AD\u653E\u6709\u58F0\u5A92\u4F53\u3002\u8BE5\u5F39\u7A97\u7528\u4E8E\u5E2E\u52A9\u7528\u6237\u6062\u590D\u97F3\u89C6\u9891\u64AD\u653E\u3002${cm}`:`Autoplay Policy: Before user interacts with the web page (clicking, touching), page will not be allowed to play media with sound. This Dialog is used to help users resume playback. ${cm}`}`,ol=class{constructor(){d(this,"content","\u97F3\u89C6\u9891\u64AD\u653E\u88AB\u6D4F\u89C8\u5668\u62E6\u622A\uFF0C\u8BF7\u70B9\u51FB\u201C\u6062\u590D\u64AD\u653E\u201D\u3002");d(this,"_dialogNode",null);d(this,"_bodyPosition","");d(this,"_showDetail",!1);d(this,"_isCollapseClicked",!1);d(this,"_isQuestionClicked",!1);if(kt()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!am){let i=document.createElement("style");i.innerHTML=`.${tl}{position:fixed;top:0;left:0;right:0;bottom:0;width:100vw;height:100vh;display:flex;justify-content:center;align-items:center;background:rgba(0,0,0,0.5);z-index:1500;}.${tl} div:not(.${Sa}){display:block !important;}.${Ds}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${Ds} a{color:${nm};}.${sm}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${il}{margin:8px 0;}.${Sa}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${sl}{margin-right:auto;cursor:pointer}.${rl}{height:100%;line-height:16px;cursor:pointer;}.${Ia}{margin-left:8px;color:#fff;background:${nm};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${Ia}:hover{opacity:0.9;}.${sl},.${Ia},.${il},.${rl}{font-size:14px;}@media screen and (max-width:750px){.${Ds}{width:80vw;}}`,document.head.appendChild(i),am=!0}this.addDiaLog()}createDiaLog(){let i=document.createElement("template");i.innerHTML=`<div class="${tl}"><div class='${Ds}'><div class='${sm}'>${location.host}</div><div class='${il}'>${this.content}</div><div class='${om}' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">${Q_}</div><div class='${Sa}'></div></div></div>`.trim();let e=document.createElement("button");e.className=Ia,e.innerText=kt()?"\u6062\u590D\u64AD\u653E":"Resume",e.onclick=this.onConfirm.bind(this);let t=document.createElement("div");t.className=rl,t.innerHTML=`<?xml version="1.0" encoding="UTF-8"?>
|
|
28
28
|
<svg class="icon" width="18" height="18" p-id="2030" t="1639646523624" version="1.1" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
|
|
29
29
|
<path d="m464 784.35c0 26.51 21.49 48 48 48s48-21.49 48-48-21.49-48-48-48-48 21.49-48 48z" p-id="2031"/>
|
|
30
30
|
<path d="m512 960c-247.04 0-448-200.96-448-448s200.96-448 448-448 448 200.96 448 448-200.96 448-448 448zm0-831.71c-211.58 0-383.71 172.13-383.71 383.71 0 211.55 172.13 383.71 383.71 383.71 211.55 0 383.71-172.16 383.71-383.71 0-211.58-172.16-383.71-383.71-383.71z" p-id="2032"/>
|
|
@@ -48,13 +48,13 @@ uniform sampler2D u_texture;
|
|
|
48
48
|
|
|
49
49
|
void main() {
|
|
50
50
|
gl_FragColor = texture2D(u_texture, v_texCoord);
|
|
51
|
-
} `;var jr=class extends H{constructor(e){super();d(this,"frameRate");d(this,"_canvas");d(this,"log");d(this,"hasAlpha",!1);d(this,"name");d(this,"error");this.name=e.name,this.log=e.logger.createChild({id:`vc-${this.name}`}),this.frameRate=e.frameRate}set width(e){this._canvas&&(this._canvas.width=e)}get width(){var e;return((e=this._canvas)==null?void 0:e.width)||0}set height(e){this._canvas&&(this._canvas.height=e)}get height(){var e;return((e=this._canvas)==null?void 0:e.height)||0}setSize(e,t){this._canvas&&(this._canvas.width=e,this._canvas.height=t)}createVideoTrackSource(e,t){return new Ji(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new Vs(this,e)}createVideoImageSource(e,t){return new tn(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new rn(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}};d(jr,"_ids",0);var NT={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},Bs=class Bs extends jr{constructor(){super(...arguments);d(this,"defaultProgam");d(this,"defaultVShader");d(this,"defaultFShader");d(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${jr._ids++}`),this.ctx=this._canvas.getContext("webgl2",NT),!this.ctx)throw new y({code:I.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,yT),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,bT),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new y({code:I.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})}destroy(e){let t="";return e&&(t=e.message,this.error=e,b.addFailedEvent({key:512702,error:e})),this.disconnect(),this.log.info(`video context destroy${t}`?`: ${t}`:""),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),e}set width(e){var t;(t=this.ctx)==null||t.viewport(0,0,e,this.height),super.width=e}set height(e){var t;(t=this.ctx)==null||t.viewport(0,0,this.width,e),super.height=e}setSize(e,t){var r;(r=this.ctx)==null||r.viewport(0,0,e,t),super.setSize(e,t)}createShader(e,t){let r=this.ctx,o=r.createShader(e);return r.shaderSource(o,t),r.compileShader(o),o}createProgram(e,t){let r=this.ctx,o=r.createProgram();return r.attachShader(o,e),r.attachShader(o,t),r.linkProgram(o),r.getProgramParameter(o,r.LINK_STATUS)||this.log.error(r.getProgramInfoLog(o)),o}};d(Bs,"UNAVAILABLE","unavailable"),v([Te(H.INIT,"created",{sync:!0,fail(e){this.log.error("video gl context create failed",e.cause),b.addFailedEvent({key:512700,error:e.cause||e})},success(){this.log.info("video context created use webgl"),b.addSuccessEvent({key:512700})}})],Bs.prototype,"create",1),v([Te("created",H.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(Bs.UNAVAILABLE,e),this.removeAllListeners()}})],Bs.prototype,"destroy",1);var ke=Bs,Xe=class extends jr{constructor(){super(...arguments);d(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${jr._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new y({code:I.VIDEO_MANAGER_ERROR,extraCode:2,message:"2d context not supported"});this._canvas.addEventListener("contextlost",()=>{this.log.error("2d context lost")}),this._canvas.addEventListener("contextrestored",()=>{this.log.warn("2d context restored")})}destroy(e){let t="";e&&(t=e.message,this.error=e,b.addFailedEvent({key:512703,error:e})),this.disconnect(),this.log.info(`video context destroy ${t?`: ${t}`:""}`),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners(),b.addSuccessEvent({key:512703})}};v([Te(H.INIT,"created",{sync:!0,fail(e){this.log.error("video 2d context create failed",e.cause),b.addFailedEvent({key:512701,error:e.cause||e})},success(){this.log.info("video context created use 2d"),b.addSuccessEvent({key:512701})}})],Xe.prototype,"create",1),v([Te("created",H.INIT,{ignoreError:!0,sync:!0})],Xe.prototype,"destroy",1);function vT(s){return[15,30,45,60].reduce((e,t)=>Math.abs(t-s)<Math.abs(e-s)?t:e)}var fi=class extends Us{constructor(e,t,r=4){super(e,t,r);d(this,"mediaType",4);d(this,"source");d(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.videoManager,this.once("first-video-frame",o=>{this.room.emit("first-video-frame",o)})}play(e,t){return(me(t==null?void 0:t.canvasRender)?t.canvasRender:nt===17)&&!this.source&&this.useCanvasPlayer(),super.play(e,t).then(()=>{this.player.calculateStat()})}useCanvasPlayer(){if(this.log.info(`useCanvasPlayer(), has element:${!!this.player.element}`),!this.player.element)return;let e=new Xe({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});let t=new qr(e,{name:"remotePlayer",logger:this.log});this.source=e.createVideoPlayerSource(this.player),this.source.connect(t),this.player.setCanvas(e._canvas),Ur()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let t=this.decodeFPS,r=vT(t);if(!q(t)||t<=0){this.log.debug(`updateCanvasPlayerFPS() ignore decoder: ${t} `);return}if(r===e.frameRate){this.log.debug(`updateCanvasPlayerFPS() ignore ClosestFPS ${r} == ${e.frameRate}`);return}this.log.info(`updateCanvasPlayerFPS() decoder: ${t}, closest: ${r}, current: ${e.frameRate}`),e.frameRate=r}get decodeFPS(){var n;let{msg_video_status:e}=((n=this.room.heartbeatReport)==null?void 0:n.msg_down_stream_info.find(a=>a.msg_user_info.str_identifier===this.userId))||{},t=this.mediaType===2?7:this.isSmall?3:2;if(!e||e.length===0)return 0;let r=e.find(a=>a.uint32_video_stream_type===t);return(r==null?void 0:r.uint32_video_dec_fps)||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),super.stop()}decodeFrame(e){if(!this.manager)return e;for(let t of this.manager.decodePipeline)if(t&&(e=t({frame:e,track:this}),!e))return;return e}get isBig(){return this.mediaType===4}get isSmall(){return this.mediaType===8}changeType(e){this.room.changeType(e,this.user)}get isRemotePublished(){return this.user.muteState.videoAvailable}setMirror(e){e==="publish"||e==="both"||super.setMirror(e)}onDecodeDowngradeStateChanged(e){this.emit("decode-downgrade-state-changed",e)}},Fs=class extends fi{constructor(e,t){super(e,t,2);d(this,"mediaType",2);d(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}};var $s=new Map;E.on(A.JOIN_SUCCESS,({room:s})=>{Ae(s.userId,{eventId:32788})});E.on(A.LEAVE_START,({room:s})=>{Ae(s.userId,{eventId:32789})});E.on(A.LOCAL_TRACK_PUBLISHED,({track:s})=>{if(s.room){let i=32769;s.mediaType===4?i=32768:s.mediaType===2&&(i=32805),Ae(s.room.userId,{eventId:i})}});E.on(A.LOCAL_TRACK_UNPUBLISHED,({track:s})=>{if(s.room){let i=32771;s.mediaType===4?i=32770:s.mediaType===2&&(i=32806),Ae(s.room.userId,{eventId:i})}});E.on(A.TRACK_MUTED,({track:s})=>{s.room&&(s.kind===p.AUDIO?Ae(s.room.userId,{eventId:s.isRemote?32785:32772,remoteUserId:s.isRemote?s.userId:void 0}):Ae(s.room.userId,{eventId:s.isRemote?32784:32773,remoteUserId:s.isRemote?s.userId:void 0}))});E.on(A.TRACK_UNMUTED,({track:s})=>{s.room&&(s.kind===p.AUDIO?Ae(s.room.userId,{eventId:s.isRemote?32787:32774,remoteUserId:s.isRemote?s.userId:void 0}):Ae(s.room.userId,{eventId:s.isRemote?32786:32775,remoteUserId:s.isRemote?s.userId:void 0}))});E.on(A.REMOTE_TRACK_SUBSCRIBED,({track:s})=>{s.room&&(s.mediaType===1&&Ae(s.room.userId,{eventId:32777,remoteUserId:s.userId}),s.mediaType===4&&Ae(s.room.userId,{eventId:32776,remoteUserId:s.userId}),s.mediaType===8&&Ae(s.room.userId,{eventId:32803,remoteUserId:s.userId}))});E.on(A.REMOTE_TRACK_UNSUBSCRIBED,({track:s})=>{s.room&&(s.mediaType===1&&Ae(s.room.userId,{eventId:32779,remoteUserId:s.userId}),s.mediaType===4&&Ae(s.room.userId,{eventId:32778,remoteUserId:s.userId}),s.mediaType===8&&Ae(s.room.userId,{eventId:32804,remoteUserId:s.userId}))});E.on(A.SWITCH_DEVICE_SUCCESS,({track:s})=>{s.room&&Ae(s.room.userId,{eventId:s.kind===p.VIDEO?32780:32781})});E.on(A.LOCAL_TRACK_REPLACED,({track:s})=>{s.room&&Ae(s.room.userId,{eventId:s.kind===p.VIDEO?32782:32783})});E.on(A.SIGNAL_CONNECTION_STATE_CHANGED,({room:s,prevState:i,state:e})=>{let t;switch(e){case"CONNECTED":i==="RECONNECTING"?t=32795:t=32791;break;case"DISCONNECTED":i==="RECONNECTING"?t=32796:t=32790;break;case"RECONNECTING":t=32794;break}t&&Ae(s.userId,{eventId:t})});E.on(A.PEER_CONNECTION_STATE_CHANGED,({room:s,prevState:i,state:e,remoteUserId:t})=>{let r=!!t,o;switch(e){case"CONNECTED":i==="RECONNECTING"?o=r?32801:32798:o=r?32793:32792;break;case"DISCONNECTED":i==="RECONNECTING"&&(o=r?32802:32799);break;case"RECONNECTING":o=r?32800:32797;break}o&&Ae(s.userId,{eventId:o,remoteUserId:t})});E.on(A.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({implementation:s,userId:i,remoteUserId:e,codec:t,isHWCodec:r,prevImplementation:o,streamType:n})=>{let a=r?1:0;o||(a=r?3:2);let c=t==="h264"?0:2,l={eventId:4004,param1:a,param2:c,streamType:n||2};e&&(l.remoteUserId=e,l.eventId=4005),Ae(i,l),b.addEnum({key:e?514701:513701,value:a}),b.addEnum({key:e?514700:513700,value:c})});E.on(A.LOCAL_TRACK_RECAPTURE,({track:s,error:i})=>{if(s.userId){let e={eventId:2003,param1:0};s.kind===p.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType=s.streamType==="auxiliary"?7:2,i&&(e.param1=8)),Ae(s.userId,e)}});function Ae(s,i){let e=L(N({},i),{timestamp:to()});$s.has(s)?$s.get(s).push(e):$s.set(s,[e])}function Vm(s){if($s.has(s)){let i=$s.get(s).map(e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,uint32_param1:e.param1,uint32_param2:e.param2,uint32_video_stream_type:e.streamType}));return $s.delete(s),i}return[]}function Bm(...s){return Q((i,e)=>function(...t){return DT.call(this,s,t,e,this._name),i.apply(this,t)})}function DT(s,i,e,t){try{if(Se(s))for(let r=0;r<s.length;r++)tc.call(this,{rule:s[r],value:i[r],key:s[r].name,fnName:e,className:t});else tc.call(this,{rule:s,value:i[0],key:s.name,fnName:e,className:t})}catch(r){throw C.error(r),r}}function tc({rule:s,value:i,key:e,fnName:t,className:r}){if(T(i)){if(s.required)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_REQUIRED,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(T(s.defaultValue))return;i=s.defaultValue}if(Array.isArray(s.type)){let a=!1;for(let c=0;c<s.type.length;c++)s.type[c]===null&&i===null&&(a=!0),ne(s.type[c])&&i instanceof s.type[c]&&(a=!0),ee(s.type[c])&&Re(i)===s.type[c].toLowerCase()&&(a=!0);if(!a)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_TYPE,data:{key:e,rule:{type:s.type.map(c=>br(c)?ns(c):ee(c)?c:Re(c))},fnName:t,value:i},link:{className:r,fnName:t}})})}else if(!T(s.type)&&Re(i)!==s.type)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_TYPE,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(s.allowEmpty===!1){let a=q(i)&&(i===0||Number.isNaN(i)),c=ee(i)&&i.trim()==="";if(a||c)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_EMPTY,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})})}if(s.notLessThanZero&&q(i)&&i<0)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.CANNOT_LESS_THAN_ZERO,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(!T(s.min)&&q(i)&&i<s.min)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_MIN,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(!T(s.max)&&q(i)&&i>s.max)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_MAX,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(ee(s.instanceOf)){if(!i||i._name!==s.instanceOf)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})})}else if(ne(s.instanceOf)&&!(i instanceof s.instanceOf))throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(s.values&&!s.values.includes(i))throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_RANGE,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});let{properties:o}=s;Je(o)&&Mt(i)&&Object.keys(o).forEach(a=>{tc.call(this,{rule:o[a],value:i&&i[a],key:`${e}.${a}`,fnName:t,className:r})});let{arrayItem:n}=s;Je(n)&&Se(i)&&i.forEach((a,c)=>{tc.call(this,{rule:n,value:a,key:`${e}[${c}]`,fnName:t,className:r})}),ne(s.validate)&&s.validate.call(this,i,e,t,r,this)}var Fm=$e(Ye(),1);var ic=class extends Fm.EventEmitter{constructor(e,t,r="userId"){super();this.mySelfId=e;this._log=t;this.key=r;d(this,"userMap",new Map);d(this,"remotePublishedUserMap",new Map)}get hasRobotUser(){return!![...this.remotePublishedUserMap.values()].find(e=>e.isRobot)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:r,tinyId:o,role:n}=e;if(this.userMap.has(t))return;let a={userId:r,tinyId:o,role:n===20?"anchor":"audience"};this.userMap.set(t,a),this.emit("1",a)}deleteUser(e,t){let r=this.userMap.get(e);if(!r)return;let o=`peer leave [${e}]`;T(t)||(o+=`:${Kc[t]}`),this._log.info(o);let n=this.remotePublishedUserMap.get(e);if(n){let a=n.muteState;n.flag=0,this.emit("5",n.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:a,muteState:n.muteState,flag:0})}this.userMap.delete(e),this.emit("2",r.userId)}setUserList(e){this.userMap.forEach(t=>{e.findIndex(r=>r[this.key]===t[this.key])<0&&this.deleteUser(t[this.key],0)}),e.forEach(t=>{!this.userMap.has(t[this.key])&&t[this.key]!==this.mySelfId&&this.addUser(t)})}addRemotePublishedUser(e){this.remotePublishedUserMap.has(e[this.key])||this.remotePublishedUserMap.set(e[this.key],e)}deleteRemotePublishedUser(e){this.remotePublishedUserMap.has(e)&&this.remotePublishedUserMap.delete(e)}setRemotePublishedUserList(e){this.remotePublishedUserMap.forEach(t=>{let r=t[this.key];if(e.findIndex(o=>o[this.key]===t[this.key])<0){this._log.info(`remote [${r}] unpublish`);let o=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(r),this.emit("6",{prevMuteState:o,muteState:t.muteState,flag:0})}}),e.forEach(t=>{var h;let r=t[this.key];if(r===this.mySelfId)return;let{flag:o,userId:n,tinyId:a}=t,c=bi(o,n),l=(h=this.remotePublishedUserMap.get(r))==null?void 0:h.muteState;if(l){let u=this.remotePublishedUserMap.get(r);u&&u.flag!==o&&(u.flag=o,this._log.info(`remote publish updated: ${JSON.stringify(u.muteState)}`),this.emit("6",{prevMuteState:l,muteState:c,flag:o}))}else this._log.info(`remote publish. state: ${JSON.stringify(c)}`),this.addUser({userId:n,tinyId:a,role:20}),this.emit("3",t),this.emit("6",{prevMuteState:bi(0,n),muteState:c,flag:o})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function tu({timesInSecond:s,maxSizeInSecond:i,getSize:e}){return Q((t,r)=>{let o=new WeakMap;return E.on(A.ROOM_DESTROY,({room:n})=>o.delete(n)),function(...n){let a=o.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},o.set(this,a)),a.timestamp===0?a.timestamp=Date.now():Date.now()-a.timestamp>1e3&&(a.timestamp=Date.now(),a.callCountInSecond=0,a.totalSizeInSecond=0),e&&(a.totalSizeInSecond+=e(...n)),a.timestamp!==0&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=s||a.totalSizeInSecond>i))throw new y({code:I.INVALID_OPERATION,message:x({key:P.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=s,isSize:a.totalSizeInSecond>i,name:r,timesInSecond:s,maxSizeInSecond:i}})});a.callCountInSecond++,t.call(this,...n)}})}var OT="2025-06-12 15:20:00",$m=!0,Hm=function(){var s;if($m){$m=!1,C.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${Xt}/en/index.html`),console.info(`* Changelog: ${Xt}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),C.info("TRTC Web SDK Version:",Pe),Vt||C.debug("Build Time:",OT);let i=`UA: ${navigator.userAgent}
|
|
51
|
+
} `;var jr=class extends H{constructor(e){super();d(this,"frameRate");d(this,"_canvas");d(this,"log");d(this,"hasAlpha",!1);d(this,"name");d(this,"error");this.name=e.name,this.log=e.logger.createChild({id:`vc-${this.name}`}),this.frameRate=e.frameRate}set width(e){this._canvas&&(this._canvas.width=e)}get width(){var e;return((e=this._canvas)==null?void 0:e.width)||0}set height(e){this._canvas&&(this._canvas.height=e)}get height(){var e;return((e=this._canvas)==null?void 0:e.height)||0}setSize(e,t){this._canvas&&(this._canvas.width=e,this._canvas.height=t)}createVideoTrackSource(e,t){return new Ji(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new Vs(this,e)}createVideoImageSource(e,t){return new tn(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new rn(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}};d(jr,"_ids",0);var NT={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},Bs=class Bs extends jr{constructor(){super(...arguments);d(this,"defaultProgam");d(this,"defaultVShader");d(this,"defaultFShader");d(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${jr._ids++}`),this.ctx=this._canvas.getContext("webgl2",NT),!this.ctx)throw new y({code:I.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,yT),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,bT),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new y({code:I.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})}destroy(e){let t="";return e&&(t=e.message,this.error=e,b.addFailedEvent({key:512702,error:e})),this.disconnect(),this.log.info(`video context destroy${t}`?`: ${t}`:""),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),e}set width(e){var t;(t=this.ctx)==null||t.viewport(0,0,e,this.height),super.width=e}set height(e){var t;(t=this.ctx)==null||t.viewport(0,0,this.width,e),super.height=e}setSize(e,t){var r;(r=this.ctx)==null||r.viewport(0,0,e,t),super.setSize(e,t)}createShader(e,t){let r=this.ctx,o=r.createShader(e);return r.shaderSource(o,t),r.compileShader(o),o}createProgram(e,t){let r=this.ctx,o=r.createProgram();return r.attachShader(o,e),r.attachShader(o,t),r.linkProgram(o),r.getProgramParameter(o,r.LINK_STATUS)||this.log.error(r.getProgramInfoLog(o)),o}};d(Bs,"UNAVAILABLE","unavailable"),v([Te(H.INIT,"created",{sync:!0,fail(e){this.log.error("video gl context create failed",e.cause),b.addFailedEvent({key:512700,error:e.cause||e})},success(){this.log.info("video context created use webgl"),b.addSuccessEvent({key:512700})}})],Bs.prototype,"create",1),v([Te("created",H.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(Bs.UNAVAILABLE,e),this.removeAllListeners()}})],Bs.prototype,"destroy",1);var ke=Bs,Xe=class extends jr{constructor(){super(...arguments);d(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${jr._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new y({code:I.VIDEO_MANAGER_ERROR,extraCode:2,message:"2d context not supported"});this._canvas.addEventListener("contextlost",()=>{this.log.error("2d context lost")}),this._canvas.addEventListener("contextrestored",()=>{this.log.warn("2d context restored")})}destroy(e){let t="";e&&(t=e.message,this.error=e,b.addFailedEvent({key:512703,error:e})),this.disconnect(),this.log.info(`video context destroy ${t?`: ${t}`:""}`),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners(),b.addSuccessEvent({key:512703})}};v([Te(H.INIT,"created",{sync:!0,fail(e){this.log.error("video 2d context create failed",e.cause),b.addFailedEvent({key:512701,error:e.cause||e})},success(){this.log.info("video context created use 2d"),b.addSuccessEvent({key:512701})}})],Xe.prototype,"create",1),v([Te("created",H.INIT,{ignoreError:!0,sync:!0})],Xe.prototype,"destroy",1);function vT(s){return[15,30,45,60].reduce((e,t)=>Math.abs(t-s)<Math.abs(e-s)?t:e)}var fi=class extends Us{constructor(e,t,r=4){super(e,t,r);d(this,"mediaType",4);d(this,"source");d(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.videoManager,this.once("first-video-frame",o=>{this.room.emit("first-video-frame",o)})}play(e,t){return(me(t==null?void 0:t.canvasRender)?t.canvasRender:nt===17)&&!this.source&&this.useCanvasPlayer(),super.play(e,t).then(()=>{this.player.calculateStat()})}useCanvasPlayer(){if(this.log.info(`useCanvasPlayer(), has element:${!!this.player.element}`),!this.player.element)return;let e=new Xe({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});let t=new qr(e,{name:"remotePlayer",logger:this.log});this.source=e.createVideoPlayerSource(this.player),this.source.connect(t),this.player.setCanvas(e._canvas),Ur()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let t=this.decodeFPS,r=vT(t);if(!q(t)||t<=0){this.log.debug(`updateCanvasPlayerFPS() ignore decoder: ${t} `);return}if(r===e.frameRate){this.log.debug(`updateCanvasPlayerFPS() ignore ClosestFPS ${r} == ${e.frameRate}`);return}this.log.info(`updateCanvasPlayerFPS() decoder: ${t}, closest: ${r}, current: ${e.frameRate}`),e.frameRate=r}get decodeFPS(){var n;let{msg_video_status:e}=((n=this.room.heartbeatReport)==null?void 0:n.msg_down_stream_info.find(a=>a.msg_user_info.str_identifier===this.userId))||{},t=this.mediaType===2?7:this.isSmall?3:2;if(!e||e.length===0)return 0;let r=e.find(a=>a.uint32_video_stream_type===t);return(r==null?void 0:r.uint32_video_dec_fps)||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),super.stop()}decodeFrame(e){if(!this.manager)return e;for(let t of this.manager.decodePipeline)if(t&&(e=t({frame:e,track:this}),!e))return;return e}get isBig(){return this.mediaType===4}get isSmall(){return this.mediaType===8}changeType(e){this.room.changeType(e,this.user)}get isRemotePublished(){return this.user.muteState.videoAvailable}setMirror(e){e==="publish"||e==="both"||super.setMirror(e)}onDecodeDowngradeStateChanged(e){this.emit("decode-downgrade-state-changed",e)}},Fs=class extends fi{constructor(e,t){super(e,t,2);d(this,"mediaType",2);d(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}};var $s=new Map;E.on(A.JOIN_SUCCESS,({room:s})=>{Ae(s.userId,{eventId:32788})});E.on(A.LEAVE_START,({room:s})=>{Ae(s.userId,{eventId:32789})});E.on(A.LOCAL_TRACK_PUBLISHED,({track:s})=>{if(s.room){let i=32769;s.mediaType===4?i=32768:s.mediaType===2&&(i=32805),Ae(s.room.userId,{eventId:i})}});E.on(A.LOCAL_TRACK_UNPUBLISHED,({track:s})=>{if(s.room){let i=32771;s.mediaType===4?i=32770:s.mediaType===2&&(i=32806),Ae(s.room.userId,{eventId:i})}});E.on(A.TRACK_MUTED,({track:s})=>{s.room&&(s.kind===p.AUDIO?Ae(s.room.userId,{eventId:s.isRemote?32785:32772,remoteUserId:s.isRemote?s.userId:void 0}):Ae(s.room.userId,{eventId:s.isRemote?32784:32773,remoteUserId:s.isRemote?s.userId:void 0}))});E.on(A.TRACK_UNMUTED,({track:s})=>{s.room&&(s.kind===p.AUDIO?Ae(s.room.userId,{eventId:s.isRemote?32787:32774,remoteUserId:s.isRemote?s.userId:void 0}):Ae(s.room.userId,{eventId:s.isRemote?32786:32775,remoteUserId:s.isRemote?s.userId:void 0}))});E.on(A.REMOTE_TRACK_SUBSCRIBED,({track:s})=>{s.room&&(s.mediaType===1&&Ae(s.room.userId,{eventId:32777,remoteUserId:s.userId}),s.mediaType===4&&Ae(s.room.userId,{eventId:32776,remoteUserId:s.userId}),s.mediaType===8&&Ae(s.room.userId,{eventId:32803,remoteUserId:s.userId}))});E.on(A.REMOTE_TRACK_UNSUBSCRIBED,({track:s})=>{s.room&&(s.mediaType===1&&Ae(s.room.userId,{eventId:32779,remoteUserId:s.userId}),s.mediaType===4&&Ae(s.room.userId,{eventId:32778,remoteUserId:s.userId}),s.mediaType===8&&Ae(s.room.userId,{eventId:32804,remoteUserId:s.userId}))});E.on(A.SWITCH_DEVICE_SUCCESS,({track:s})=>{s.room&&Ae(s.room.userId,{eventId:s.kind===p.VIDEO?32780:32781})});E.on(A.LOCAL_TRACK_REPLACED,({track:s})=>{s.room&&Ae(s.room.userId,{eventId:s.kind===p.VIDEO?32782:32783})});E.on(A.SIGNAL_CONNECTION_STATE_CHANGED,({room:s,prevState:i,state:e})=>{let t;switch(e){case"CONNECTED":i==="RECONNECTING"?t=32795:t=32791;break;case"DISCONNECTED":i==="RECONNECTING"?t=32796:t=32790;break;case"RECONNECTING":t=32794;break}t&&Ae(s.userId,{eventId:t})});E.on(A.PEER_CONNECTION_STATE_CHANGED,({room:s,prevState:i,state:e,remoteUserId:t})=>{let r=!!t,o;switch(e){case"CONNECTED":i==="RECONNECTING"?o=r?32801:32798:o=r?32793:32792;break;case"DISCONNECTED":i==="RECONNECTING"&&(o=r?32802:32799);break;case"RECONNECTING":o=r?32800:32797;break}o&&Ae(s.userId,{eventId:o,remoteUserId:t})});E.on(A.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({implementation:s,userId:i,remoteUserId:e,codec:t,isHWCodec:r,prevImplementation:o,streamType:n})=>{let a=r?1:0;o||(a=r?3:2);let c=t==="h264"?0:2,l={eventId:4004,param1:a,param2:c,streamType:n||2};e&&(l.remoteUserId=e,l.eventId=4005),Ae(i,l),b.addEnum({key:e?514701:513701,value:a}),b.addEnum({key:e?514700:513700,value:c})});E.on(A.LOCAL_TRACK_RECAPTURE,({track:s,error:i})=>{if(s.userId){let e={eventId:2003,param1:0};s.kind===p.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType=s.streamType==="auxiliary"?7:2,i&&(e.param1=8)),Ae(s.userId,e)}});function Ae(s,i){let e=L(N({},i),{timestamp:to()});$s.has(s)?$s.get(s).push(e):$s.set(s,[e])}function Vm(s){if($s.has(s)){let i=$s.get(s).map(e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,uint32_param1:e.param1,uint32_param2:e.param2,uint32_video_stream_type:e.streamType}));return $s.delete(s),i}return[]}function Bm(...s){return Q((i,e)=>function(...t){return DT.call(this,s,t,e,this._name),i.apply(this,t)})}function DT(s,i,e,t){try{if(Se(s))for(let r=0;r<s.length;r++)tc.call(this,{rule:s[r],value:i[r],key:s[r].name,fnName:e,className:t});else tc.call(this,{rule:s,value:i[0],key:s.name,fnName:e,className:t})}catch(r){throw C.error(r),r}}function tc({rule:s,value:i,key:e,fnName:t,className:r}){if(T(i)){if(s.required)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_REQUIRED,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(T(s.defaultValue))return;i=s.defaultValue}if(Array.isArray(s.type)){let a=!1;for(let c=0;c<s.type.length;c++)s.type[c]===null&&i===null&&(a=!0),ne(s.type[c])&&i instanceof s.type[c]&&(a=!0),ee(s.type[c])&&Re(i)===s.type[c].toLowerCase()&&(a=!0);if(!a)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_TYPE,data:{key:e,rule:{type:s.type.map(c=>br(c)?ns(c):ee(c)?c:Re(c))},fnName:t,value:i},link:{className:r,fnName:t}})})}else if(!T(s.type)&&Re(i)!==s.type)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_TYPE,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(s.allowEmpty===!1){let a=q(i)&&(i===0||Number.isNaN(i)),c=ee(i)&&i.trim()==="";if(a||c)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_EMPTY,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})})}if(s.notLessThanZero&&q(i)&&i<0)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.CANNOT_LESS_THAN_ZERO,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(!T(s.min)&&q(i)&&i<s.min)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_MIN,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(!T(s.max)&&q(i)&&i>s.max)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_MAX,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(ee(s.instanceOf)){if(!i||i._name!==s.instanceOf)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})})}else if(ne(s.instanceOf)&&!(i instanceof s.instanceOf))throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(s.values&&!s.values.includes(i))throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_RANGE,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});let{properties:o}=s;Je(o)&&Mt(i)&&Object.keys(o).forEach(a=>{tc.call(this,{rule:o[a],value:i&&i[a],key:`${e}.${a}`,fnName:t,className:r})});let{arrayItem:n}=s;Je(n)&&Se(i)&&i.forEach((a,c)=>{tc.call(this,{rule:n,value:a,key:`${e}[${c}]`,fnName:t,className:r})}),ne(s.validate)&&s.validate.call(this,i,e,t,r,this)}var Fm=$e(Ye(),1);var ic=class extends Fm.EventEmitter{constructor(e,t,r="userId"){super();this.mySelfId=e;this._log=t;this.key=r;d(this,"userMap",new Map);d(this,"remotePublishedUserMap",new Map)}get hasRobotUser(){return!![...this.remotePublishedUserMap.values()].find(e=>e.isRobot)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:r,tinyId:o,role:n}=e;if(this.userMap.has(t))return;let a={userId:r,tinyId:o,role:n===20?"anchor":"audience"};this.userMap.set(t,a),this.emit("1",a)}deleteUser(e,t){let r=this.userMap.get(e);if(!r)return;let o=`peer leave [${e}]`;T(t)||(o+=`:${Kc[t]}`),this._log.info(o);let n=this.remotePublishedUserMap.get(e);if(n){let a=n.muteState;n.flag=0,this.emit("5",n.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:a,muteState:n.muteState,flag:0})}this.userMap.delete(e),this.emit("2",r.userId)}setUserList(e){this.userMap.forEach(t=>{e.findIndex(r=>r[this.key]===t[this.key])<0&&this.deleteUser(t[this.key],0)}),e.forEach(t=>{!this.userMap.has(t[this.key])&&t[this.key]!==this.mySelfId&&this.addUser(t)})}addRemotePublishedUser(e){this.remotePublishedUserMap.has(e[this.key])||this.remotePublishedUserMap.set(e[this.key],e)}deleteRemotePublishedUser(e){this.remotePublishedUserMap.has(e)&&this.remotePublishedUserMap.delete(e)}setRemotePublishedUserList(e){this.remotePublishedUserMap.forEach(t=>{let r=t[this.key];if(e.findIndex(o=>o[this.key]===t[this.key])<0){this._log.info(`remote [${r}] unpublish`);let o=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(r),this.emit("6",{prevMuteState:o,muteState:t.muteState,flag:0})}}),e.forEach(t=>{var h;let r=t[this.key];if(r===this.mySelfId)return;let{flag:o,userId:n,tinyId:a}=t,c=bi(o,n),l=(h=this.remotePublishedUserMap.get(r))==null?void 0:h.muteState;if(l){let u=this.remotePublishedUserMap.get(r);u&&u.flag!==o&&(u.flag=o,this._log.info(`remote publish updated: ${JSON.stringify(u.muteState)}`),this.emit("6",{prevMuteState:l,muteState:c,flag:o}))}else this._log.info(`remote publish. state: ${JSON.stringify(c)}`),this.addUser({userId:n,tinyId:a,role:20}),this.emit("3",t),this.emit("6",{prevMuteState:bi(0,n),muteState:c,flag:o})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function tu({timesInSecond:s,maxSizeInSecond:i,getSize:e}){return Q((t,r)=>{let o=new WeakMap;return E.on(A.ROOM_DESTROY,({room:n})=>o.delete(n)),function(...n){let a=o.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},o.set(this,a)),a.timestamp===0?a.timestamp=Date.now():Date.now()-a.timestamp>1e3&&(a.timestamp=Date.now(),a.callCountInSecond=0,a.totalSizeInSecond=0),e&&(a.totalSizeInSecond+=e(...n)),a.timestamp!==0&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=s||a.totalSizeInSecond>i))throw new y({code:I.INVALID_OPERATION,message:x({key:P.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=s,isSize:a.totalSizeInSecond>i,name:r,timesInSecond:s,maxSizeInSecond:i}})});a.callCountInSecond++,t.call(this,...n)}})}var OT="2025-06-12 19:31:34",$m=!0,Hm=function(){var s;if($m){$m=!1,C.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${Xt}/en/index.html`),console.info(`* Changelog: ${Xt}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),C.info("TRTC Web SDK Version:",Pe),Vt||C.debug("Build Time:",OT);let i=`UA: ${navigator.userAgent}
|
|
52
52
|
CPU core: ${navigator.hardwareConcurrency}, GPU: ${Cd()}`,e=navigator.deviceMemory;e&&(i+=`, minRAM: ${e}GB`),C.info(i),C.info(`URL: ${location.href}${((s=self.frameElement)==null?void 0:s.tagName)==="IFRAME"?" in iframe":""}`),Or().then(t=>{t&&C.info(xt)})}};var yt={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 B={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},bt=(R=>(R[R.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",R[R.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",R[R.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",R[R.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",R[R.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",R[R.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",R[R.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",R[R.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",R[R.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",R[R.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",R[R.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",R[R.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",R[R.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",R[R.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",R[R.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",R[R.INVALID_ROOM_ID_REQUIRED=5015]="INVALID_ROOM_ID_REQUIRED",R[R.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",R[R.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",R[R.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",R[R.INVALID_ROOM_ID_TYPE_MISMATCH=5019]="INVALID_ROOM_ID_TYPE_MISMATCH",R[R.INVALID_ROOM_ID_DUPLICATE=5020]="INVALID_ROOM_ID_DUPLICATE",R[R.INVALID_OPERATION=5100]="INVALID_OPERATION",R[R.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",R[R.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",R[R.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",R[R.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",R[R.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",R[R.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",R[R.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",R[R.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",R[R.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",R[R.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",R[R.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",R[R.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",R[R.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",R[R.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",R[R.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",R[R.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",R[R.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",R[R.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",R[R.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",R[R.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",R[R.DEVICE_ERROR=5300]="DEVICE_ERROR",R[R.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",R[R.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",R[R.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",R[R.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",R[R.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",R[R.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",R[R.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",R[R.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",R[R.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",R[R.SERVER_ERROR=5400]="SERVER_ERROR",R[R.NEED_TO_BUY=5401]="NEED_TO_BUY",R[R.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",R[R.OPERATION_FAILED=5500]="OPERATION_FAILED",R[R.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",R[R.REJOIN_FAILED=5502]="REJOIN_FAILED",R[R.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",R[R.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",R[R.VIDEO_DECODE_ERROR=5505]="VIDEO_DECODE_ERROR",R[R.OPERATION_ABORT=5998]="OPERATION_ABORT",R[R.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",R))(bt||{});function Wm({code:s,params:i,enableDocLink:e=!1}){let t="",r,o=bt[s];try{r=Gm[o]}catch(n){r=Gm.UNKNOWN_ERROR}return ne(r)?t=r(i):ee(r)&&(t=r),i.fnName&&!t.includes(i.fnName)&&(t[t.length-1]!=="."&&(t+="."),t+=` thrown from ${i.fnName}()`),e&&(t+=" doc:"),t}var Gm=L(N({},Ve),{INVALID_PARAMETER({fnName:s}){return`the parameters of the '${s}' you called does not meet the requirements, please check the API documentation.`},INVALID_PARAMETER_REQUIRED({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' is a required param when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_TYPE({key:s,rule:i,fnName:e,value:t}){let r=`${s||i.name}`,o="";return Array.isArray(i.type)?o=i.type.join("|"):o=i.type,`'${r}' must be type of ${o} when calling ${e}(), received type: ${Re(t)}.`},INVALID_PARAMETER_EMPTY({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' cannot be '${t}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:s,rule:i,fnName:e,value:t}){let r=`${s||i.name}`,o=`${i.instanceOf.name||i.instanceOf}`;return`'${r}' must be instanceof ${o} when calling ${e}(), received type: ${Re(t)}.`},INVALID_PARAMETER_RANGE({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' must be one of ${i.values.join("|")} when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_LESS_THAN_ZERO({key:s,rule:i,fnName:e}){return`'${s||i.name}' cannot be less than 0 when calling ${e}().`},INVALID_PARAMETER_MIN({key:s,rule:i,value:e}){return`the min value of ${s||i.name} is ${i.min}, received: ${e}.`},INVALID_PARAMETER_MAX({key:s,rule:i,value:e}){return`the max value of ${s||i.name} is ${i.max}, received: ${e}.`},INVALID_ELEMENT_ID({key:s,fnName:i}){return`'${s}' is not found in the document object when calling ${i}().`},INVALID_ELEMENT_ID_TYPE({key:s,fnName:i,type:e}){return`the element corresponding to '${s}' must be instanceof HTMLElement when calling ${i}(), received: ${e}.`},INVALID_STREAM_ID({key:s}){return`'${s}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},INVALID_ROOM_ID_STRING({key:s}){return`'${s}' must be a valid string.`},INVALID_ROOM_ID_INTEGER({key:s}){return`'${s}' must be an integer between [1, 4294967294].`},INVALID_ROOM_ID_INTEGER_STRING({key:s}){return`'${s}' 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:s}){return`The type of target roomId must match the current roomId. Current room is using '${s}', but received '${s==="strRoomId"?"roomId":"strRoomId"}'.`},INVALID_ROOM_ID_DUPLICATE({key:s}){return`the target '${s}' must not be the same as the current '${s}'.`},INVALID_STREAM_TYPE:({fnName:s})=>`'streamType' is required when 'userId' is not '*', calling ${s}()`,INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION({fnName:s}){return`the API '${s}' you called does not meet the requirements, please check the API documentation.`},INVALID_OPERATION_NOT_JOINED({fnName:s}){return`cannot ${s} because you are not enter room yet.`},INVALID_OPERATION_REMOTE_USER_NOT_EXIST({fnName:s,value:i}){return`cannot ${s} because remote user(userId: ${i.userId}) does not publishing stream.`},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST({fnName:s,value:i}){return`cannot ${s} because remote user(userId: ${i.userId}) does not publishing ${i.streamType} video.`},INVALID_OPERATION_REPEAT_CALL({fnName:s}){return`you are already ${s}(), cannot repeated call '${s}'.`},INVALID_OPERATION_NEED_VIDEO({fnName:s}){return`cannot call '${s}' because the camera is not turned on.`},INVALID_OPERATION_NEED_AUDIO({fnName:s}){return`cannot call '${s}' because the microphone or screen share is not turned on.`},INVALID_BUFFER_EMPTY:({key:s})=>`the buffer size of paramerter '${s}' 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:s})=>`you need to call ${s}() after publish stream.`,ENV_NOT_SUPPORTED({fnName:s}){return`the current browser does not support the capability of the function '${s}' 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:s}){return`cannot call ${s} because the browser version is too low, please upgrade to the latest version`},DEVICE_ERROR({fnName:s,error:i}){return`'${s}' got device exception${i?`, error: ${i.toString()}.`:"."}`},DEVICE_NOT_FOUND_ERROR({fnName:s,deviceType:i=Xr(s),error:e}){return`NotFoundError, no ${i} detected, please check your device and the configuration on '${s}'${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_ALLOWED_ERROR({fnName:s,deviceType:i=Xr(s),error:e}){return`NotAllowedError, you have disabled ${i} access, please allow the current application to use the ${i}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_READABLE_ERROR({fnName:s,deviceType:i=Xr(s),error:e}){return`NotReadableError, the ${i} maybe in use by another APP, please check if the device is pre-occupied by another APP.`},DEVICE_OVERCONSTRAINED_ERROR({fnName:s,deviceType:i=Xr(s),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:s,deviceType:i=Xr(s),error:e}){return`InvalidStateError, after the user clicks and interacts with the page, turn on the ${i}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_SECURITY_ERROR({fnName:s,deviceType:i=Xr(s),error:e}){return`SecurityError, check whether the system security policy restricts the use of the ${i}, and it is recommended to turn on the ${i} after the user interacts with the page${e?`, error: ${e.toString()}.`:"."}`},DEVICE_ABORT_ERROR({fnName:s,deviceType:i=Xr(s),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:s}){return`camera recover capture failed ${(s==null?void 0:s.name)||""}: ${(s==null?void 0:s.originMessage)||(s==null?void 0:s.message)}`},MICROPHONE_RECOVER_FAILED({error:s}){return`microphone recover capture failed ${(s==null?void 0:s.name)||""}: ${(s==null?void 0:s.originMessage)||(s==null?void 0:s.message)}`},OPERATION_FAILED({fnName:s,error:i}){return`'${s}' failed, reason: ${i==null?void 0:i.toString()}`},FIREWALL_RESTRICTION(){return"media connection failure due to firewall restrictions, please try to change your network."},EVENT_HANDLER_ERROR({eventName:s}){return`an error was caught on trtc.on('${s}', handler), please check your code on 'handler'.`},VIDEO_CONTEXT_ERROR({reason:s,error:i}){return`video context error ${s} ${(i==null?void 0:i.name)||""} ${(i==null?void 0:i.message)||""}`},SERVER_ERROR({fnName:s,error:i}){return`'${s}' got server error: ${i==null?void 0:i.toString()}, please check the SDK documentation.`},NEED_TO_BUY({value:s,url:i}){return`You need to buy packages for ${s}. Refer to: ${i}`},ACCOUNT_NO_MONEY:({fnParams:s})=>`your TRTC account run out of credit, please recharge.${s.sdkAppId?` SDKAppId: ${s.sdkAppId}`:""}`,OPERATION_ABORT({fnName:s}){return`'${s}' abort`},UNKNOWN_ERROR({fnName:s,error:i}){return`'${s}' throw unknown exception${i?`, error: ${i.toString()}.`:"."}`}});function Xr(s){if(!s)return"camera";let i=s.toLowerCase();return i.includes("screen")?"screen share":i.includes("audio")?"microphone":"camera"}var iu=class s extends Error{constructor({code:e,extraCode:t,message:r="",messageParams:o,fnName:n="",originError:a}){var l;let c;r?c=r:c=Wm({code:e===B.SERVER_ERROR?e:t||e,params:N({fnName:n,error:a},o)});super(c);d(this,"name","RtcError");d(this,"code");d(this,"extraCode");d(this,"functionName");d(this,"message");d(this,"handler");d(this,"originError");this.name=bt[e],this.code=e,this.extraCode=t,this.functionName=n,this.originError=a,this.message=c,this.extraCode===5302&&((l=this.originError)!=null&&l.message.includes("system"))&&(this.handler=()=>{let h={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},u={startLocalVideo:"webcam",startLocalAudio:"microphone"},m=document.createElement("a");Dr?m.href=`ms-settings:privacy-${u[this.functionName]}`:Ut&&(m.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${h[this.functionName]}`),m.href.length>0&&m.click()})}static convertFrom(e,t,r){let o=e;if(e instanceof y){let{stack:n}=e,a={code:B.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case I.INVALID_PARAMETER:a.code=B.INVALID_PARAMETER,a.message=e.message;break;case I.INVALID_OPERATION:a.code=B.INVALID_OPERATION;break;case I.NOT_SUPPORTED:case I.NOT_SUPPORTED_H264:a.code=B.ENV_NOT_SUPPORTED,e.getCode()===I.NOT_SUPPORTED_H264&&(a.extraCode=e.message.includes(Ve.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case I.JOIN_ROOM_FAILED:a.messageParams={fnParams:r};case I.SERVER_TIMEOUT:case I.SWITCH_ROLE_FAILED:case I.SWITCH_ROOM_FAILED:a.code=B.SERVER_ERROR,a.extraCode=e.getExtraCode();break;case I.API_CALL_ABORTED:a.code=B.OPERATION_ABORT;break;case I.DEVICE_NOT_FOUND:case I.DEVICE_AUTO_RECOVER_FAILED:case I.INITIALIZE_FAILED:a.code=5300,e.name&&(a.extraCode=MT(e.name));break;case I.UNKNOWN:break;default:a.code=B.OPERATION_FAILED}o=new s(a),n&&(o.stack+=n.substr(n.indexOf(`
|
|
53
53
|
`)))}else{if(e instanceof s)return e;o=new s({code:B.UNKNOWN_ERROR,fnName:t,originError:e})}return o}};function MT(s){let i;switch(s){case"NotFoundError":i=5301;break;case"NotAllowedError":i=5302;break;case"NotReadableError":i=5303;break;case"OverconstrainedError":i=5304;break;case"InvalidStateError":i=5305;break;case"SecurityError":i=5306;break;case"AbortError":i=5307;break;default:i=5300}return i}var w=iu;function hr(s){return s==="sub"?"auxiliary":s==="auxiliary"?"sub":"main"}function sn(s){return s===yt.QOS_PREFERENCE_CLEAR?"detail":s===yt.QOS_PREFERENCE_SMOOTH?"motion":""}function Hs(s,i){let e=i?Jc:er;return cd(s)?N(N({},e),s):Dt[s]?Dt[s]:e}var Jm={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}}},qm={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}}},Gs={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(s,i,e){if(ee(s)&&!document.getElementById(s))throw new w({code:B.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:i}})}},jm={name:"userId",required:!0,type:"string"},Xm={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[yt.AUDIO_PROFILE_STANDARD,yt.AUDIO_PROFILE_STANDARD_STEREO,yt.AUDIO_PROFILE_HIGH,yt.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function Ws(s,i){if(!s)throw new w({code:B.INVALID_OPERATION,extraCode:5101,fnName:i})}function zm(s,i,e){if(!s)throw new w({code:B.INVALID_OPERATION,extraCode:5102,fnName:i,messageParams:{value:e}})}function Qm(s,i,e){if(!(/^[1-9]\d*$/.test(String(s))&&s<4294967295))throw new w({code:B.INVALID_PARAMETER,extraCode:5013,fnName:i,messageParams:{key:e}})}function Ym(s,i,e){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(s))throw new w({code:B.INVALID_PARAMETER,extraCode:5012,fnName:i,messageParams:{key:e}})}var GO={type:"number",notLessThanZero:!0},kT=(s,i)=>s.width*s.height>=i.width*i.height&&s.frameRate>=i.frameRate&&s.bitrate>=i.bitrate;function Zm(s){var t;if(!((t=s==null?void 0:s.option)!=null&&t.small))return;if(!ga()){C.warn("small stream is not supported"),delete s.option.small;return}let i=Hs(s.option.profile),e=Hs(s.option.small,!0);if(!kT(i,e)){C.warn(`small stream profile must be less than big stream profile. Big: ${JSON.stringify(i)}, Small: ${JSON.stringify(e)}`),delete s.option.small;return}}var PT={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(s,i,e){if(this._room.isJoined)throw new w({code:B.INVALID_OPERATION,extraCode:5104,fnName:e});if(s.roomId){if(ee(s.roomId))throw new w({code:B.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:i}});Qm(s.roomId,e,i)}else if(s.strRoomId)Ym(s.strRoomId,e,i);else throw new w({code:B.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:Gs,mute:{type:["boolean","string"]},publish:{type:"boolean"},capture:{required:!1,type:"boolean"},option:Jm},validate(s){var i,e;if(!((i=s==null?void 0:s.option)!=null&&i.videoTrack)&&wi())throw new w({code:B.ENV_NOT_SUPPORTED,extraCode:5201});(e=s==null?void 0:s.option)!=null&&e.small&&Zm(s)}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:L(N({},Gs),{required:!1}),publish:{type:"boolean"},capture:{required:!1,type:"boolean"},mute:{type:["boolean","string"]},option:Jm},validate(s){var i;(i=s==null?void 0:s.option)!=null&&i.small&&Zm(s)}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:Xm},validate(s){var i;if(!((i=s==null?void 0:s.option)!=null&&i.audioTrack)&&wi())throw new w({code:B.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:Xm}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:Gs,publish:{type:"boolean"},option:qm},validate(s,i,e,t,r){var o;if(!((o=s==null?void 0:s.option)!=null&&o.videoTrack)){if(wi())throw new w({code:B.ENV_NOT_SUPPORTED,extraCode:5201});if(!Po())throw new w({code:B.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:Gs,publish:{type:"boolean"},option:qm}},muteRemoteAudio:[jm,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[jm,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:Gs,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(s,i,e){Ws(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(s.userId);if(zm(!!t,e,s),t&&(s.streamType==="main"&&!t.muteState.videoAvailable||s.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new w({code:B.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:s}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:L(N({},Gs),{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(s,i,e){Ws(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(s.userId);if(zm(!!t,e,s),t&&(s.streamType==="main"&&!t.muteState.videoAvailable||s.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new w({code:B.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:s}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(s,i,e){if(s.userId!=="*"&&T(s.streamType))throw new w({code:B.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(s,i,e){Ws(this._room.isJoining||this._room.isJoined,e)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(s,i,e,t){if(!wo)throw new w({code:B.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new w({code:B.INVALID_OPERATION,fnName:e,extraCode:5108});if(s.byteLength>1e3)throw new w({code:B.INVALID_PARAMETER,extraCode:5018,fnName:e});if(s.byteLength===0)throw new w({code:B.INVALID_PARAMETER,extraCode:5017,messageParams:{key:i},fnName:e});Ws(this._room.isJoined,e)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(s,i,e){if(!s&&!this._room.isMainStreamPublished||s&&!this._room.isAuxStreamPublished)throw new w({code:B.INVALID_OPERATION,extraCode:5109,messageParams:{key:i},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(s,i,e,t){if(s.byteLength>1e3)throw new w({code:B.INVALID_PARAMETER,extraCode:5018,fnName:e});if(s.byteLength===0)throw new w({code:B.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:i}})}}},validate(s,i,e){if(Ws(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new w({code:B.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:i}})}},switchRoom:{name:"switchRoomConfig",type:"object",required:!0,validate(s,i,e){if(Ws(this._room.isJoined,e),this._room.useStringRoomId&&s.strRoomId===this._room.roomId||!this._room.useStringRoomId&&s.roomId===Number(this._room.roomId))throw new w({code:B.INVALID_PARAMETER,extraCode:5020,fnName:e,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(s.roomId&&this._room.useStringRoomId||!s.roomId&&s.strRoomId&&!this._room.useStringRoomId)throw new w({code:B.INVALID_PARAMETER,extraCode:5019,fnName:e,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(s.roomId)Qm(s.roomId,e,i);else if(s.strRoomId)Ym(s.strRoomId,e,i);else throw new w({code:B.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}}}},we={TRTC:PT};var ze=class extends Error{};function xT(s,i){let e=Rr(s);for(let t=0;t<i.length;t++)It(e[t],i[t]);return e}function LT(s){this._resolve=Promise.resolve(s)}function wT(s){this._reject=Promise.reject(s)}var mr=class mr{constructor(i,e){this.instance=i;this.group=e;d(this,"started",!1);d(this,"ops",[]);d(this,"startSame",()=>!0);d(this,"mergeUpdate",xT);let t=mr.instances.get(i);t?t.set(e,this):mr.instances.set(i,new Map([[e,this]]))}static get(i,e){if(!e)return;let t=mr.instances.get(i);return t&&t.get(e)||new mr(i,e)}static gets(i,e){let t=mr.instances.get(i),r=[];return t&&t.forEach((o,n)=>{e.test(n)&&r.push(o)}),r}action(i,e,t){let r=a=>{var c;return i===0?this.started=!0:i===3&&(this.started=!1),this.ops.shift(),(c=this.currentOp)==null||c.action(),a},o=a=>{var c,l;throw this.ops.shift(),i===0&&((c=this.currentOp)==null?void 0:c.type)===2&&this.ops.shift().reject(new ze("start failed")),(l=this.currentOp)==null||l.action(),a},n={type:i,action:()=>e(...n.args).then(r,o),args:t,resolve:LT,reject:wT};try{switch(this.state){case 1:if(i===0)throw new ze("already started");break;case 4:if(i===2)throw new ze("not started");break;default:return this.cacheOp(n)}}catch(a){return Promise.reject(a)}return this.ops.push(n),n.promise=e(...n.args).then(r,o)}cacheOp(i){if(this.ops.length===1)switch(this.state){case 0:case 2:if(i.type===0)throw new ze("already start");break;case 3:switch(i.type){case 2:throw new ze("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new ze("unknown state")}else switch(i.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let t=new ze("keep stop");if(this.ops.slice(1).forEach(r=>r.reject(t)),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,i.args),this.lastOp.promise;case 3:throw new ze("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new ze("start not allowed after update");case 0:throw new ze("duplicate start");case 3:if(this.startSame(this.currentOp.args,i.args))throw this.ops.pop().reject(new ze("keep start")),new ze("already start")}}i.promise=new Promise((t,r)=>{i._resolve?i._resolve.then(t):i.resolve=t,i._reject?i._reject.catch(r):i.reject=r});let{action:e}=i;return i.action=()=>e().then(i.resolve,i.reject),this.ops.push(i),i.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}};d(mr,"instances",new WeakMap);var qi=mr;var rc=new WeakMap,sc=(s,i)=>{if(i instanceof ze){let{stack:e}=i;i=new w({code:B.OPERATION_ABORT,message:`${s} abort: ${i.message}`,fnName:s}),e&&(i.stack+=e.substr(e.indexOf(`
|
|
54
54
|
`)))}throw i};function pr(s,i){return Q((e,t)=>function(...r){let o=qi.get(this,typeof s=="string"?s:s.call(this,...r));return o?(i&&(o.startSame=i.bind(this)),o.action(0,e.bind(this),r).catch(sc.bind(null,t))):e.apply(this,r)})}function zr(s,i){let{merge:e,debounce:t}=i||{};return Q((r,o)=>function(...n){let a=qi.get(this,typeof s=="string"?s:s.call(this,...n));if(!a)return r.apply(this,n);if(e&&(a.mergeUpdate=e.bind(this)),t&&t.isNeedToDebounce.apply(this,n)){let{delay:c,getKey:l}=t;return new Promise((h,u)=>{var D,_;let m=(D=rc.get(this))==null?void 0:D.get(l(...n));if(m){let{timeoutId:S,resolve:O}=m;clearTimeout(S),O()}let g=setTimeout(()=>{if(a.state===3||a.state===4)return h();a.action(2,r.bind(this),n).catch(sc.bind(null,o)).then(h,u)},c);rc.has(this)?(_=rc.get(this))==null||_.set(l(...n),{timeoutId:g,resolve:h}):rc.set(this,new Map([[l(...n),{timeoutId:g,resolve:h}]]))})}return a.action(2,r.bind(this),n).catch(sc.bind(null,o))})}function fr(s){return Q((i,e)=>function(...t){let r=typeof s=="function"?s.call(this,...t):s;if(r instanceof RegExp)return Promise.all(qi.gets(this,r).map(n=>n.action(3,()=>Promise.resolve(),t))).then(()=>i.call(this,...t));let o=qi.get(this,r);return o?o.action(3,i.bind(this),t).catch(sc.bind(null,e)):i.apply(this,t)})}var k={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"},Km=new Set([k.ERROR,k.AUTOPLAY_FAILED,k.KICKED_OUT,k.REMOTE_USER_ENTER,k.REMOTE_USER_EXIT,k.REMOTE_AUDIO_AVAILABLE,k.REMOTE_AUDIO_UNAVAILABLE,k.REMOTE_VIDEO_AVAILABLE,k.REMOTE_VIDEO_UNAVAILABLE,k.CONNECTION_STATE_CHANGED,k.PUBLISH_STATE_CHANGED,k.SCREEN_SHARE_STOPPED,k.DEVICE_CHANGED,k.FIRST_VIDEO_FRAME]);var su={};Si(su,{bytes2ms:()=>ah,calculateScaleResolutionDownNumber:()=>us,convertObjectNumberToInt:()=>mo,copyProperties:()=>nh,deepClone:()=>Rr,deepMerge:()=>It,delay:()=>Ni,fibonacci:()=>yr,formatedTime:()=>fh,getConstructorName:()=>ns,getContainerFromElement:()=>ph,getEnv:()=>sh,getInternalVersion:()=>hh,getLoggerUrl:()=>yi,getMediaStreamTrackInfo:()=>Vn,getMuteStateFromFlag:()=>bi,getNetworkType:()=>td,getNumNetworkType:()=>Cr,getReconnectionTimeout:()=>Pt,getStringByteLength:()=>ho,getTurnServer:()=>mh,getUint32Version:()=>Ln,getValueType:()=>Re,getViewListFromView:()=>ds,glog:()=>sd,ipv4ToUint32:()=>cs,isArray:()=>Se,isAudioWorkletSupported:()=>uh,isBoolean:()=>me,isConstructor:()=>br,isEmpty:()=>as,isFunction:()=>ne,isLangChinese:()=>kt,isMediaStreamTrack:()=>dh,isNumber:()=>q,isObject:()=>Mt,isOverseaSdkAppId:()=>Ci,isPlainObject:()=>Je,isPortrait:()=>od,isPromise:()=>sr,isRemoteTrack:()=>lh,isRotate90Or270:()=>vi,isString:()=>ee,isUndefined:()=>T,loadImage:()=>ls,ms2bytes:()=>ch,ms2samples:()=>rd,normalizeUrl:()=>Un,performanceNow:()=>U,promiseAny:()=>Nr,samples2ms:()=>id,setNetworkType:()=>Pn,stringify:()=>St,stringifyIncludeValue:()=>xn,throttlePromise:()=>wn});var au={};Si(au,{ScheduleRequestType:()=>tp,getAbilityConfig:()=>VT,getScheduleDomain:()=>ac,isNeedToSchedule:()=>oc,scheduleProxy:()=>_i,sendScheduleRequest:()=>nu,setIsNeedToSchedule:()=>Wt,setScheduleProxy:()=>nc});var ou=null,oc=!0;typeof document!="undefined"&&document.head.insertAdjacentHTML("beforeend",Object.values(Ri).map(s=>`<link rel="dns-prefetch" href="https://${s}">`).join(`\r
|
|
55
55
|
`));function Wt(s){me(s)&&s!==oc&&(oc=s,C.info(`setIsNeedToSchedule ${s}`))}E.on("28",()=>Wt(!0));E.on("63",()=>Wt(!0));E.on("84",()=>Wt(!0));E.on("201",s=>{s.state==="RECONNECTING"&&Wt(!0)});E.on("202",s=>{s.state==="RECONNECTING"&&Wt(!0)});function UT(s,i,e){let t={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let r=performance.getEntriesByType("resource"),o=_r(s,"config",p.MAIN),n=_r(s,"config",p.BACKUP);for(let a of r)if(a.startTime>=e&&(a.name===o||a.name===n)&&a.transferSize>0){let c=a.name===o?p.MAIN:p.BACKUP,l=Math.round(a.duration),h=Math.round(a.domainLookupStart-a.startTime),u=a.redirectStart>0?Math.round(a.redirectEnd-a.redirectStart):0,m=a.fetchStart>0?Math.round(a.domainLookupStart-a.fetchStart):0,g=Math.round(a.domainLookupEnd-a.domainLookupStart),D=Math.round(a.requestStart-a.secureConnectionStart),_=Math.round(a.secureConnectionStart-a.connectStart),S=Math.round(a.responseStart-a.requestStart),O=Math.round(a.responseEnd-a.responseStart),K=[g,D,_,S,O];re.uploadEvent({log:`stat-schedule-net:${l}(${h}(${u}->${m})->${K.join("->")}) ${c}`,userId:i}),t=L(N({},t),{totalCost:l,local:h,dns:g,tcp:_,tls:D,request:S,response:O});break}}catch(r){C.error("getScheduleDetailCost error",r)}return t}function nu(l){return f(this,arguments,function*({userId:s,sdkAppId:i,useStringRoomId:e,roomId:t,userSig:r,version:o,frameWorkType:n,role:a,latencyLevel:c}){if(!oc&&ou)return{isCached:!0,result:ou};let h={delta:0,count:[1,1],msg:[],detail:[]};try{let u=new FormData;u.append("userId",String(s)),u.append("sdkAppId",String(i)),u.append("isStrGroupId",String(e)),u.append("groupId",String(t)),u.append("sdkVersion",o),u.append("userSig",String(r));let m=yield Or();m!=null&&m.model&&u.append("model",String(m==null?void 0:m.model)),a&&u.append("role",String(a)),c&&u.append("latencyLevel",String(c)),n&&u.append("frameWorkType",String(n));let g=U(),D=yield FT(u,h,i);D.config&&(D.config.loggerDomain&&Tr(D.config.loggerDomain),me(D.config.scheduleCache)&&Wt(!D.config.scheduleCache)),h.delta=U()-g;let _=UT(Number(i),s,g);return ou=D,{isCached:!1,result:D,detailCost:_}}catch(u){let m=Se(u)?u[0]:u,g=q(m.code)?m.code:0,D=`schedule failed${m.message?`: ${m.message}`:""}`,_=new y({code:I.SCHEDULE_FAILED,extraCode:g,message:x({key:P.JOIN_ROOM_FAILED,data:{error:D,code:g}})});throw C.error(D,g),_}})}var _i={main:"",backup:""};function nc(s){Se(s)?(_i.main=s[0],_i.backup=s[1]):_i.main=s}var tp=(t=>(t.CONFIG="config",t.TRTC_AUTO_CONF="trtcAutoConf",t.AUDIO_AI_AUTH="audioAiAuth",t))(tp||{});function _r(s,i,e=p.MAIN,t=!1){return`https://${_i[e]||ac(s,e,t)}/api/v1/${i}`}function VT(s,i,e){let t=_r(s,i),r=_r(s,i,p.BACKUP),o=new URLSearchParams(e).toString(),n=fetch(`${t}?${o}`).then(c=>c.json()),a=fetch(`${r}?${o}`).then(c=>c.json());return Nr([n,a])}function ac(s,i=p.MAIN,e=!1){let t;return Ci(s)?e?t=i===p.MAIN?Ri.MAIN_OVERSEA_BACKUP:Ri.BACKUP_OVERSEA:t=i===p.MAIN?Ri.MAIN_OVERSEA:Ri.BACKUP_OVERSEA:t=i===p.MAIN?Ri.MAIN:Ri.BACKUP,t}function BT(s,i,e){return new Promise((t,r)=>{Di({url:s,body:i,timeout:e.timeout,priority:"high"}).then(o=>{o.data.code===0?t(o.data.data):r({code:o.data.code,message:o.data.msg})}).catch(r)})}var ep=(s,i)=>Yt({retryFunction:BT,settings:{retries:3,timeout:0},onError:i,onRetrying:s});function FT(s,i,e){return new Promise((t,r)=>{let o=null;Nr([ep(n=>i.count[0]=n+1,({error:n,retry:a,retriedCount:c,retryFuncArgs:l})=>{i.msg[0]=n.message,o||(c>=1&&(l[0]=_r(e,"config",p.MAIN,!0)),a())})(_r(e,"config",p.MAIN),s,{get timeout(){return yr(2+i.count[0])*1e3}}),ep(n=>i.count[1]=n+1,({error:n,retry:a,retriedCount:c,retryFuncArgs:l})=>{i.msg[1]=n.message,o||(c>=2&&(l[0]=_r(e,"config",p.BACKUP,!0)),a())})(_r(e,"config",p.BACKUP),s,{get timeout(){return yr(2+i.count[1])*1e3}})]).then(n=>{o=n,t(o)}).catch(r)})}var $T=s=>s.startsWith("data:application/octet-stream;base64,"),HT=s=>s.startsWith("file://"),on=class{constructor(){d(this,"_log");this._log=C.createLogger({id:"fd"})}download(i,e){return f(this,null,function*(){let{type:t="blob"}=e||{};i=Un(i);try{let r=U(),o;if(ne(fetch)?o=yield this.downloadWithFetch(i,t):o=yield this.downloadWithXHR(i,t),!o||!o.data)throw new Error("data is empty");let n=U()-r;return this._log.info(`downloaded: ${i}, return type: ${t}, cost: ${n}ms`),b.addSuccessEvent({key:522700,cost:U()-r}),o.data}catch(r){throw this._log.error(`failed to download: ${i}, error: ${r}`),b.addFailedEvent({key:522700,error:r}),r}})}downloadWithFetch(i,e){return f(this,null,function*(){this._log.info(`download with fetch: ${i}, return type: ${e}`);try{let t=yield fetch(i);if(!t.ok){let o=new Error(`network response was not ok: ${t.status}`);throw o.status=t.status,o}let r;return e==="arraybuffer"?r=yield t.arrayBuffer():r=yield t.blob(),{data:r}}catch(t){throw t}})}downloadWithXHR(i,e){return this._log.info(`download with xhr: ${i}, return type: ${e}`),new Promise((t,r)=>{let o=new XMLHttpRequest;o.open("GET",i,!0),o.responseType=e,o.onload=()=>{if(o.status===200||o.status===0&&o.response)t({data:o.response});else{let n=new Error(`XHR failed, status: ${o.status}`);n.status=o.status,r(n)}},o.onerror=r,o.send(null)})}loadWasm(i,e){return f(this,null,function*(){this._log.info(`loadWasm ${i}, importObject: ${JSON.stringify(e)}`);let t=U(),r=null,o=null;if(ne(WebAssembly.instantiateStreaming)&&!$T(i)&&!HT(i)&&ne(fetch))try{let n=fetch(i);r=(yield WebAssembly.instantiateStreaming(n,e)).instance}catch(n){o=n}if(!r)try{let n=yield this.download(i,{type:"arraybuffer"});r=(yield WebAssembly.instantiate(n,e)).instance}catch(n){o=n}if(r){let n=U()-t;return this._log.info(`loadedWasm ${i}, cost: ${n}ms`),b.addSuccessEvent({key:522701,cost:n}),r}throw this._log.error(`failed to loadWasm ${i}, error: ${o}`),b.addFailedEvent({key:522701,error:o}),o})}loadScript(i){this._log.info(`loadScript ${i}`);let e=U();return new Promise((t,r)=>{let o=document.createElement("script");o.type="text/javascript",o.onload=()=>{this._log.info(`loadedScript ${i}, cost: ${U()-e}ms`),b.addSuccessEvent({key:522702,cost:U()-e,split:1e3}),t(o)},o.onerror=n=>{this._log.error(`failed to loadScript ${i}, error: ${n}`),b.addFailedEvent({key:522702}),r(n)},o.crossOrigin="anonymous",o.src=i,document.head.append?document.head.append(o):document.getElementsByTagName("head")[0].appendChild(o)})}};v([pt({settings:{timeout:0,retries:3},onError(i,e,t){var r;(i==null?void 0:i.status)===404||(r=i==null?void 0:i.message)!=null&&r.includes("404")?(this._log.warn("download 404, stop retry"),t(i)):e()},onRetrying(i){this._log.warn(`download retrying: ${i}`)}})],on.prototype,"download",1),v([pt({settings:{timeout:3e3,retries:3},onRetrying(i){this._log.warn(`loadScript retrying: ${i}`)}})],on.prototype,"loadScript",1);var ip=new on;function rp({TRTC:s,room:i,errorModule:e,assetsPath:t}){return{TRTC:s,room:i,assetsPath:t,fileDownloader:ip,innerEmitter:E,constants:ed,environment:Rs,utils:su,eventLogger:re,log:this.room.getLogger(),loggerManager:C,errorModule:e,kvStatManager:b,rtcDectection:ni,trtc:this,rx:Kl,enums:Bd,schedule:au,clearStarted:(r,o)=>{let n=r.getAlias(),a=qi.instances.get(this);if(a)if(o){let c=a.get(n+o);if(!c)return;c.started=!1}else a.forEach((c,l)=>{l.startsWith(n)&&(c.started=!1)})},startGetPCM:zo,createAudioNode:Jo}}var sp=(s,i)=>{let{emit:e}=s;return s.emit=(...t)=>{try{return e.apply(s,t)}catch(r){let o=x({key:P.CATCH_HANDLER_ERROR,data:{name:i,event:t[0]},addDocLink:!1});return C.warn(`${o}
|
|
56
56
|
|
|
57
|
-
${r.stack}`),!1}},s};var Js=new WeakMap;function op(s){let i=Js.get(s);i&&(i.forEach(e=>clearTimeout(e)),Js.delete(s))}function np(s,i){return Q((e,t)=>function(...r){let o=Js.get(this);o||(o=new Map,Js.set(this,o));let n=i(...r),a=o.get(n);if(!a||a<=0){e.apply(this,r);let c=setTimeout(()=>{var l;(l=Js.get(this))==null||l.delete(n)},s);o.set(n,c)}else{clearTimeout(a);let c=window.setTimeout(()=>{var l;e.apply(this,r),(l=Js.get(this))==null||l.delete(n)},s);o.set(n,c)}})}var cp="trtc-sdk-v5",dp="5.11.0-beta.7";function Ge(...s){return Q((i,e)=>function(...t){try{dc.call(this,s,t,e,this._name)}catch(r){return Promise.reject(r)}return i.apply(this,t)})}function cu(...s){return Q((i,e)=>function(...t){try{dc.call(this,s,t,e,this._name)}catch(r){throw r}return i.apply(this,t)})}function dc(s,i,e,t){if(Se(s))for(let r=0;r<s.length;r++)cc.call(this,{rule:s[r],value:i[r],key:s[r].name,fnName:e,className:t});else cc.call(this,{rule:s,value:i[0],key:s.name,fnName:e,className:t})}function cc({rule:s,value:i,key:e,fnName:t,className:r}){function o(c){return{code:B.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:s,value:i}}}if(T(i)){if(s.required)throw new w(o(5001));if(T(s.defaultValue)){ne(s.validate)&&s.validate.call(this,i,e,t,r,this);return}i=s.defaultValue}if(Array.isArray(s.type)){let c=!1;for(let l=0;l<s.type.length;l++)s.type[l]===null&&i===null&&(c=!0),ne(s.type[l])&&i instanceof s.type[l]&&(c=!0),ee(s.type[l])&&Re(i)===s.type[l].toLowerCase()&&(c=!0);if(!c)throw new w({code:B.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:s.type.map(l=>br(l)?ns(l):ee(l)?l:Re(l))},value:i}})}else if(!T(s.type)&&Re(i)!==s.type)throw new w(o(5002));if(s.allowEmpty===!1){let c=q(i)&&(i===0||Number.isNaN(i)),l=ee(i)&&i.trim()==="";if(c||l)throw new w(o(5003))}if(s.notLessThanZero&&q(i)&&i<0)throw new w(o(5006));if(!T(s.min)&&q(i)&&i<s.min)throw new w(o(5007));if(!T(s.max)&&q(i)&&i>s.max)throw new w(o(5008));if(ee(s.instanceOf)){if(!i||i._name!==s.instanceOf)throw new w(o(5004))}else if(ne(s.instanceOf)&&!(i instanceof s.instanceOf))throw new w(o(5004));if(Array.isArray(s.values)&&!s.values.includes(i))throw new w(o(5005));let{properties:n}=s;Je(n)&&Mt(i)&&Object.keys(n).forEach(c=>{cc.call(this,{rule:n[c],value:i&&i[c],key:`${c}`,fnName:t,className:r})});let{arrayItem:a}=s;Je(a)&&Se(i)&&i.forEach((c,l)=>{cc.call(this,{rule:a,value:c,key:`${e}[${l}]`,fnName:t,className:r})}),ne(s.validate)&&s.validate.call(this,i,e,t,r,this)}function fe(s={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t,ignoreLog:r,ignoreErrorLog:o}=s;return Q((n,a)=>function(...c){var g,D,_;function l(S,O,K){if(K&&K.includes(S))return"hided";if(e){let G=e(...c);if(c[G.argIndex]===O)return G.value}if(O===c||S in c)return O;try{return O instanceof HTMLElement?`id: ${O.id} type:${Re(O)}`:O instanceof MediaStreamTrack?Vn(O):(JSON.stringify(O),O)}catch(G){return`type:${Re(O)}`}}let h=this._log||C;if(r!=null&&r(...c))return n.apply(this,c);c.length>0?h.info(`${a}() ${JSON.stringify(c,(S,O)=>l(S,O,["userSig","privateMapKey"]))}`):h.info(`${a}()`);let u=t?t(...c):ua[a],m=(o==null?void 0:o(...c))||!1;try{let S=n.apply(this,c),O=U();if(sr(S)){let K=`${a.includes("Plugin")?`${((D=(g=c[0]).getName)==null?void 0:D.call(g))||""} `:" "}`;return S.then(G=>(h.info(`${a}() success ${K}${i.call(this,...c)}`),b.addSuccessEvent({key:u,cost:U()-O}),G)).catch(G=>{var J;G=w.convertFrom.call(this,G,a,c.length===1?c[0]:c);let Z=G.extraCode||G.code,_e=(J=G.message)!=null&&J.includes(Z)?"":` code:${Z}`;throw m||h.error(`${a}() failed ${K}${i.call(this,...c)} ${G}${_e} params: ${JSON.stringify(c,l)}`),b.addFailedEvent({key:u,error:G}),G})}return b.addSuccessEvent({key:u}),S}catch(S){S=w.convertFrom.call(this,S,a);let O=S.extraCode||S.code,K=(_=S.message)!=null&&_.includes(O)?"":` code:${O}`;throw m||h.error(`${a}() failed ${S}${K} params: ${JSON.stringify(c,l)}`),b.addFailedEvent({key:u,error:S}),S}})}var lc=s=>Q((i,e)=>function(t,r){return f(this,null,function*(){let o=this._plugins.get(t);if(!o)throw this._log.error(`plugin ${String(t)} is not found`),new w({code:B.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});if(ne(o.constructor.isSupported)&&!o.constructor.isSupported())throw this._log.error(`plugin ${String(t)} is not supported`),new w({code:B.ENV_NOT_SUPPORTED,message:`plugin ${String(t)} is not supported`,extraCode:5210,fnName:e});return dc.call(this,o.getValidateRule(s),[r],e,"TRTC"),i.call(this,o,r)})});var uc=0,du,ji=class ji{constructor(i){this.core=i;d(this,"log");d(this,"customAudioReferenceMap",new Map);d(this,"audioRefId",0);d(this,"audioContext",Ee());d(this,"localAudioWorkletNode");d(this,"screenAudioWorkletNode");d(this,"mixNode");d(this,"silentNode");uc=uc+1,this.log=i.log.createChild({id:`${this.getAlias()}${uc}`}),this.log.info(`created id=${this.getAlias()}${uc}`)}static getStartValidateRule(i){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,t,r,o){if(!i.room.audioManager.hasAudioTrack&&!i.room.audioManager.hasScreenAudioTrack)throw new w({code:B.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return du||(du=this.doPreload(i)),du}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield Bi(this.audioContext,t)}catch(r){this.log.error(`preload audioProcessor failed. ${r}`)}finally{URL.revokeObjectURL(t)}})}getName(){return ji.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(i){switch(i){case"start":return ji.getStartValidateRule(this.core);case"update":return ji.updateValidateRule;case"stop":return ji.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e}=this.core,{sdkAppId:t,userId:r,assetsPath:o=this.core.assetsPath,audioReference:n,processLevel:a,enableDump:c,isLocalAudioNeedAudioProcess:l=!0,isScreenAudioNeedAudioProcess:h=!0}=i;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=l,this.core.room.audioManager.isScreenAudioNeedAudioProcess=h,!o)throw new w({code:B.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}/audioProcessor-wasm.js`),!this.localAudioWorkletNode||!this.screenAudioWorkletNode){let u=String(Date.now()).slice(0,-3),{auth:m,sign:g,status:D,message:_}=yield WT(L(N({},i),{timestamp:u}));if(!m)throw this.log.info(`audioProcessor: ${r} auth result: ${m}. Message: ${_}`),new w({code:B.INVALID_PARAMETER,message:_});this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",t,r,u,g,D,e),this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",t,r,u,g,D,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),T(n)||n.forEach(u=>{this.customAudioReferenceMap.set(u,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:u,refId:`o-${this.audioRefId++}`})}),T(a)||this.localAudioWorkletNode.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:a}}),T(c)||this.localAudioWorkletNode.port.postMessage({type:"dump",data:{enable:c}})})}update(i){return f(this,null,function*(){if(!this.localAudioWorkletNode||!this.screenAudioWorkletNode)return;let{audioReference:e,enableDump:t,processLevel:r}=i;T(e)||(this.customAudioReferenceMap.forEach((o,n)=>{this.customAudioReferenceMap.delete(n),this.core.room.audioManager.updateAudioReference({type:"remove",refId:o})}),e.forEach(o=>{this.customAudioReferenceMap.set(o,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:o,refId:`o-${this.audioRefId++}`})})),T(r)||this.localAudioWorkletNode.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:r}}),T(t)||(this.localAudioWorkletNode.port.postMessage({type:"dump",data:{enable:t}}),this.screenAudioWorkletNode.port.postMessage({type:"dump",data:{enable:t}}))})}stop(){return f(this,null,function*(){if(!this.localAudioWorkletNode||!this.mixNode||!this.silentNode||!this.screenAudioWorkletNode)return;let{room:i}=this.core;this.localAudioWorkletNode.port.postMessage({type:"disable"}),this.screenAudioWorkletNode.port.postMessage({type:"disable"}),yield i.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(i,e,t,r,o,n,a,c){i.port.postMessage({type:"init",data:{sdkAppId:String(t),userId:r,timestamp:o,sign:n,status:a}}),i.port.onmessage=l=>{var u;let{data:h}=l;switch(h.type){case"cost":let m=(h==null?void 0:h.value)>10?"info":"debug";this.log[m](`[${e}] avg cost: ${h.value} max: ${h==null?void 0:h.max}(${ts(new Date(h==null?void 0:h.maxCostTimestamp))}) hist: ${(u=h==null?void 0:h.hist)==null?void 0:u.join(" ")}`);return;case"log":this.log[h.logLevel](`[${e}] ${h.value}`);return;case"dump":E.emit("265",{room:c,data:h.value,type:e==="localAudio"?"dump":"dump-screen-audio"});return}}}};d(ji,"updateValidateRule",{type:"object"}),d(ji,"stopValidateRule",{type:"object"}),d(ji,"Name","AudioProcessor");var hc=ji;function GT(s,i=p.MAIN){return`https://${_i[i]||ac(s,i)}/api/v1/audioAiAuth`}function WT(r){return f(this,arguments,function*({sdkAppId:s,userId:i,userSig:e,timestamp:t}){let n=`${GT(s)}?sdkAppId=${s}&userId=${i}&userSig=${e}×tamp=${t}`,a=yield fetch(n),{data:{errCode:c,errMsg:l,sign:h,status:u}}=yield a.json();if(u==="1")return{auth:!0,sign:h,status:u,message:l};let m=Ci(s)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",g="Init RTCAudioProcessor failed.",D="";switch(c){case 1:D="Please check your params.";break;case 2:D=`You need to buy packages. Refer to: ${m}`;break;case 3:D="Server is invalid. Please contact our engineer. ";break;case 4:D=`Your packages is not active. Refer to: ${m}`;break;case 5:D=`Your packages is expired. Refer to: ${m}`;break;case 6:D="Your version is not supported.";break}return{auth:!1,status:u,message:l?`${g} Reason: ${l}. ${D}`:`${g}, ${D}`}})}var mc=0,lu=class{constructor(i,e){d(this,"player");d(this,"publisher");d(this,"mixInput");this.mixInput=new ks(e),i.url?(this.player=new Audio(i.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(i.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(i.track),this.mixInput.connect()}updateSettings(i){this.player&&(T(i.volume)||(this.volume=i.volume),T(i.loop)||(this.loop=i.loop),T(i.playbackRate)||(this.playbackRate=i.playbackRate))}updateListener(i){if(this.player){if(i.onDurationChange){let{onDurationChange:e}=i;this.player.ondurationchange=t=>{e(t.target.duration)}}if(i.onTimeUpdate){let e=i.onTimeUpdate,{player:t}=this;t.ontimeupdate=()=>{e(t.currentTime,t.duration)}}i.onEnded&&(this.player.onended=i.onEnded)}}reset(){this.seek(0),this.mixInput.connect()}seek(i){this.player&&(i<0&&i>this.player.duration||(this.player.currentTime=i,this.publisher.currentTime=i))}play(){var i,e;return(i=this.publisher)==null||i.play(),(e=this.player)==null?void 0:e.play()}pause(){var i,e;(i=this.player)==null||i.pause(),(e=this.publisher)==null||e.pause()}stop(){var i;(i=this.player)==null||i.pause(),this.mixInput.disconnect()}setOperation(i){i==="pause"&&this.pause(),i==="resume"&&(this.pause(),this.play()),i==="stop"&&(this.pause(),this.seek(0))}set volume(i){!this.player||!this.publisher||(this.player.volume=i,this.publisher.volume=i)}set loop(i){!this.player||!this.publisher||(this.player.loop=i,this.publisher.loop=i)}set playbackRate(i){!this.player||!this.publisher||(this.player.playbackRate=i,this.publisher.playbackRate=i)}};function qs(s,i){if(i&&typeof i!="function")throw new w({code:B.INVALID_PARAMETER,message:`start audioMixer plugin: param ${s} should be a function.`})}var gi=class gi{constructor(i){this.core=i;d(this,"log");d(this,"mixedMusicMap",new Map);d(this,"cacheMusicMap",new Map);mc=mc+1,this.log=i.log.createChild({id:`${this.getAlias()}${mc}`}),this.log.info(`created id=${this.getAlias()}${mc}`)}getName(){return gi.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return gi.startValidateRule;case"update":return gi.updateValidateRule;case"stop":return gi.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e}=this.core;this.log.info(`add music source, id: ${i.id} url: ${i.url}, track: ${i.track}`);let{id:t,url:r}=i;if(this.mixedMusicMap.has(t))return;let o=this.cacheMusicMap.get(t);o?i.url?o.reset():(o.mixInput.replaceSource(i.track),o.mixInput.connect()):(o=new lu(i,e.audioManager),this.cacheMusicMap.set(t,o)),o.updateListener(i),o.updateSettings(i),yield o.play(),this.mixedMusicMap.set(t,o),o.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"add",audioReference:o.mixInput.source.node,refId:`ax-${t}`}),this.log.info(`start mix audio track ${t} success.`),b.addEnum({key:502700,value:3}),this.kvUpload(i)})}update(i){return f(this,null,function*(){let{id:e,operation:t,seekFrom:r,playbackRate:o}=i;this.log.info(`update music source, ${JSON.stringify(i)}`);let n=this.mixedMusicMap.get(e);if(!n){this.log.warn(`update music source failed, music id: ${e} not found.`);return}n.updateSettings(i),n.updateListener(i),T(t)||n.setOperation(t),T(r)||n.seek(r),this.kvUpload(i)})}stop(e){return f(this,arguments,function*({id:i}){if(this.mixedMusicMap.has(i)){this.log.info(`remove music source, music id: ${i}`);let t=this.mixedMusicMap.get(i);t!=null&&t.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:t.mixInput.source.node,refId:`ax-${i}`}),t==null||t.stop(),this.mixedMusicMap.delete(i)}i==="*"&&this.destroyAllMusic()})}kvUpload(i){let{track:e,loop:t,volume:r,playbackRate:o,operation:n,seekFrom:a,onTimeUpdate:c,onDurationChange:l,onEnded:h}=i;e&&b.addCount({key:502711}),t&&b.addCount({key:502703}),r&&b.addCount({key:502704}),o&&b.addCount({key:502705}),n&&b.addCount({key:502706}),a&&b.addCount({key:502707}),typeof c!="function"&&b.addCount({key:502709}),typeof h!="function"&&b.addCount({key:502710}),typeof l!="function"&&b.addCount({key:502708})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((i,e)=>{i!=null&&i.mixInput.track&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:i.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()}};d(gi,"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(i,e,t){if(i.url&&i.url!=="*"){let r=i.url.split("?")[0],o=["mp3","ogg","wav","flac"],n=r.split(".").pop(),a=o.indexOf(n)>=0,c=r.startsWith("blob"),l=r.startsWith("data");if(!(a||c||l))throw new w({code:B.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new w({code:B.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});qs("onTimeUpdate",i.onTimeUpdate),qs("onEnded",i.onEnded),qs("onDurationChange",i.onDurationChange)}}),d(gi,"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(i,e,t){qs("onTimeUpdate",i.onTimeUpdate),qs("onEnded",i.onEnded),qs("onDurationChange",i.onDurationChange)}}),d(gi,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),d(gi,"Name","AudioMixer");var pc=gi;var fc=0,uu,Xi=class Xi{constructor(i){this.core=i;d(this,"log");d(this,"audioContext",Ee("denoiser"));d(this,"workletNode");fc=fc+1,this.log=i.log.createChild({id:`${this.getAlias()}${fc}`}),this.log.info(`created id=${this.getAlias()}${fc}`)}static startValidateRule(i){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,t,r,o){if(!i.room.audioManager.hasAudioTrack)throw new w({code:B.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return uu||(uu=this.doPreload(i)),uu}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield Bi(this.audioContext,t)}catch(r){throw this.log.error("load worklet failed",r),r}finally{URL.revokeObjectURL(t)}})}getName(){return Xi.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(i){switch(i){case"start":return Xi.startValidateRule(this.core);case"update":return Xi.updateValidateRule;case"stop":return Xi.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e,schedule:t}=this.core,{assetsPath:r=this.core.assetsPath}=i;if(!r)throw new w({code:B.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(yield this.preload(`${r}/denoiser-wasm.js`),!this.workletNode){let o=String(Date.now()).slice(0,-3),{auth:n,sign:a,status:c,message:l}=yield qT(t,L(N({},i),{timestamp:o}));if(!n)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${n}. Message: ${l}`),new w({code:B.INVALID_PARAMETER,message:l});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(i.sdkAppId),userId:i.userId,timestamp:o,sign:a,status:c}}),this.workletNode.port.onmessage=h=>{var m;let{data:u}=h;if(u.type==="cost"){let g=(u==null?void 0:u.max)>20?"warn":(u==null?void 0:u.max)>10?"info":"debug";this.log[g](`avg cost: ${u.value} max: ${u==null?void 0:u.max}(${ts(new Date(u==null?void 0:u.maxCostTimestamp))}) hist: ${(m=u==null?void 0:u.hist)==null?void 0:m.join(" ")}`)}else u.type==="log"&&this.log[u.logLevel](`${u.value}`)}}this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(){return f(this,null,function*(){})}stop(){return f(this,null,function*(){if(!this.workletNode)return;let{room:i}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield i.audioManager.removeDenoiser(this.workletNode)})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};d(Xi,"updateValidateRule",{type:"object"}),d(Xi,"stopValidateRule",{type:"object"}),d(Xi,"Name","AIDenoiser");var _c=Xi;function qT(o,n){return f(this,arguments,function*(s,{sdkAppId:i,userId:e,userSig:t,timestamp:r}){try{let{data:{errCode:a,errMsg:c,sign:l,status:h}}=yield s.getAbilityConfig(i,s.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:i,userId:e,userSig:t,timestamp:r});if(h==="1")return{auth:!0,sign:l,status:h,message:c};let u=Ci(i)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",m="Init RTCAIDenoiser failed.",g="";switch(a){case 1:g="Please check your params.";break;case 2:g=`You need to buy packages. Refer to: ${u}`;break;case 3:g="Server is invalid. Please contact our engineer. ";break;case 4:g=`Your packages is not active. Refer to: ${u}`;break;case 5:g=`Your packages is expired. Refer to: ${u}`;break;case 6:g="Your version is not supported.";break}return{auth:!1,status:h,message:c?`${m} Reason: ${c}. ${g}`:`${m}, ${g}`}}catch(a){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${a}`}}})}var up=$e(Ye(),1);var hu=class extends up.EventEmitter{constructor(){super();d(this,"observer");d(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 f(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!pe&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){re.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let t=this.stateNum,r=e[e.length-1];this.state=r.state,(this.stateNum>3||t>3)&&C.info(`${r.source}: ${r.state}`),this.emit("state-changed",{type:r.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(t){re.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},jT=new hu,mu=jT;function pu([s,i]){let e=i.byteLength,t=parseInt(String(e/255),10),r=e%255,o=[];o.push(0,0,0,1,6,s);for(let a=0;a<t;a++)o.push(255);o.push(r);let n=new DataView(i);return o.push(...new Uint8Array(n.buffer)),o.push(128),new Hi(new DataView(new Uint8Array(o).buffer),!0)}function fu(s){return s.type==="empty"||s.data.byteLength===0}function _u(s){return s.getInt32(0)===1&&s.getInt8(4)===6}function gu(s){let i=0,e=0,t=new DataView(s);for(let r=0;r<s.byteLength;r++)switch(t.getUint8(r)){case 0:i++;break;case 1:(i===2||i===3)&&e++,i=0;break;default:i=0;break}return e}function Tu({frame:s,seiMessageList:i}){if(!i||i.length===0||s.data.byteLength===0)return s;let t=9-gu(s.data);if(t<=0)return s;let r=i.splice(0,t).reverse().map(pu),o=r.reduce((h,u)=>h+u.dataView.byteLength,0),n=new ArrayBuffer(o+s.data.byteLength),a=new DataView(n),c=new DataView(s.data),l=0;for(let h=0;h<r.length;h++)for(let u=0;u<r[h].dataView.byteLength;u++)a.setInt8(l++,r[h].dataView.getInt8(u));for(let h=0;h<s.data.byteLength;h++)a.setInt8(l++,c.getInt8(h));return s.data=n,s}function Eu({frame:s,onSEI:i}){try{let e=new DataView(s.data);if(fu(s)||!_u(e))return s;let t=[],r=0,o=-1,n=-1;for(let a=0;a<s.data.byteLength;a++){let c=e.getUint8(a);if(c===0)r++;else if(c===1){if(r===2||r===3){let l=a-r;if(o===-1?o=l:n===-1&&(n=l,t.push(new Hi(new DataView(e.buffer.slice(o,n)))),o=l,n=-1),!(e.getUint8(a+1)===6)){s.data=e.buffer.slice(l);break}}r=0}else r=0}i==null||i(t.reverse())}catch(e){}return s}var Su=0,nn=class nn{constructor(i){this.core=i;d(this,"log");d(this,"_seiMessageList",[]);d(this,"_smallSeiMessageList",[]);d(this,"_subStreamSeiMessageList",[]);Su++,this.log=i.log.createChild({id:`${this.getAlias()}${Su}`}),this.log.info(`[sei] created id=${this.getAlias()}${Su}`),this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode({frame:i,mediaType:e}){try{let t=e===8?this._smallSeiMessageList:e===2?this._subStreamSeiMessageList:this._seiMessageList;return Tu({frame:i,seiMessageList:t})}catch(t){this.log.warn(t)}return i}decode({frame:i,track:e}){return Eu({frame:i,onSEI:t=>{t.forEach(r=>{this.core.trtc.emit(k.SEI_MESSAGE,{seiPayloadType:r.seiPayloadType,data:r.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"})})}})}destroy(){this.log.debug("destory"),this.stop(),delete this.core}getValidateRule(i){switch(i){case"start":return{type:"object"};case"update":return{type:"object"};case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:Ui?this.encode:Tu,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:Ui?this.decode:Eu,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update({buffer:i,options:e}){var o;let t=[e.seiPayloadType,i],r=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(t):(this._seiMessageList.push(t),r&&this._smallSeiMessageList.push(t)),(o=this.core.room.scriptTransformWorker)==null||o.postMessage({type:"sei",data:t,isMain:!e.toSubStream,small:r})}getName(){return nn.Name}getAlias(){return"sei"}getGroup(){return"sei"}};d(nn,"autoStart",!0),d(nn,"Name","SEI");var gc=nn;function Iu({frame:s,onDump:i}){return i==null||i(),s}function Au({frame:s,onDump:i}){return i==null||i(),s}var hp={"play() error: NotAllowedError:":{tips:s=>s.includes("main <video>")||s.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:s=>s.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:s=>s.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:
|
|
57
|
+
${r.stack}`),!1}},s};var Js=new WeakMap;function op(s){let i=Js.get(s);i&&(i.forEach(e=>clearTimeout(e)),Js.delete(s))}function np(s,i){return Q((e,t)=>function(...r){let o=Js.get(this);o||(o=new Map,Js.set(this,o));let n=i(...r),a=o.get(n);if(!a||a<=0){e.apply(this,r);let c=setTimeout(()=>{var l;(l=Js.get(this))==null||l.delete(n)},s);o.set(n,c)}else{clearTimeout(a);let c=window.setTimeout(()=>{var l;e.apply(this,r),(l=Js.get(this))==null||l.delete(n)},s);o.set(n,c)}})}var cp="trtc-sdk-v5",dp="5.11.0-beta.9";function Ge(...s){return Q((i,e)=>function(...t){try{dc.call(this,s,t,e,this._name)}catch(r){return Promise.reject(r)}return i.apply(this,t)})}function cu(...s){return Q((i,e)=>function(...t){try{dc.call(this,s,t,e,this._name)}catch(r){throw r}return i.apply(this,t)})}function dc(s,i,e,t){if(Se(s))for(let r=0;r<s.length;r++)cc.call(this,{rule:s[r],value:i[r],key:s[r].name,fnName:e,className:t});else cc.call(this,{rule:s,value:i[0],key:s.name,fnName:e,className:t})}function cc({rule:s,value:i,key:e,fnName:t,className:r}){function o(c){return{code:B.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:s,value:i}}}if(T(i)){if(s.required)throw new w(o(5001));if(T(s.defaultValue)){ne(s.validate)&&s.validate.call(this,i,e,t,r,this);return}i=s.defaultValue}if(Array.isArray(s.type)){let c=!1;for(let l=0;l<s.type.length;l++)s.type[l]===null&&i===null&&(c=!0),ne(s.type[l])&&i instanceof s.type[l]&&(c=!0),ee(s.type[l])&&Re(i)===s.type[l].toLowerCase()&&(c=!0);if(!c)throw new w({code:B.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:s.type.map(l=>br(l)?ns(l):ee(l)?l:Re(l))},value:i}})}else if(!T(s.type)&&Re(i)!==s.type)throw new w(o(5002));if(s.allowEmpty===!1){let c=q(i)&&(i===0||Number.isNaN(i)),l=ee(i)&&i.trim()==="";if(c||l)throw new w(o(5003))}if(s.notLessThanZero&&q(i)&&i<0)throw new w(o(5006));if(!T(s.min)&&q(i)&&i<s.min)throw new w(o(5007));if(!T(s.max)&&q(i)&&i>s.max)throw new w(o(5008));if(ee(s.instanceOf)){if(!i||i._name!==s.instanceOf)throw new w(o(5004))}else if(ne(s.instanceOf)&&!(i instanceof s.instanceOf))throw new w(o(5004));if(Array.isArray(s.values)&&!s.values.includes(i))throw new w(o(5005));let{properties:n}=s;Je(n)&&Mt(i)&&Object.keys(n).forEach(c=>{cc.call(this,{rule:n[c],value:i&&i[c],key:`${c}`,fnName:t,className:r})});let{arrayItem:a}=s;Je(a)&&Se(i)&&i.forEach((c,l)=>{cc.call(this,{rule:a,value:c,key:`${e}[${l}]`,fnName:t,className:r})}),ne(s.validate)&&s.validate.call(this,i,e,t,r,this)}function fe(s={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t,ignoreLog:r,ignoreErrorLog:o}=s;return Q((n,a)=>function(...c){var g,D,_;function l(S,O,K){if(K&&K.includes(S))return"hided";if(e){let G=e(...c);if(c[G.argIndex]===O)return G.value}if(O===c||S in c)return O;try{return O instanceof HTMLElement?`id: ${O.id} type:${Re(O)}`:O instanceof MediaStreamTrack?Vn(O):(JSON.stringify(O),O)}catch(G){return`type:${Re(O)}`}}let h=this._log||C;if(r!=null&&r(...c))return n.apply(this,c);c.length>0?h.info(`${a}() ${JSON.stringify(c,(S,O)=>l(S,O,["userSig","privateMapKey"]))}`):h.info(`${a}()`);let u=t?t(...c):ua[a],m=(o==null?void 0:o(...c))||!1;try{let S=n.apply(this,c),O=U();if(sr(S)){let K=`${a.includes("Plugin")?`${((D=(g=c[0]).getName)==null?void 0:D.call(g))||""} `:" "}`;return S.then(G=>(h.info(`${a}() success ${K}${i.call(this,...c)}`),b.addSuccessEvent({key:u,cost:U()-O}),G)).catch(G=>{var J;G=w.convertFrom.call(this,G,a,c.length===1?c[0]:c);let Z=G.extraCode||G.code,_e=(J=G.message)!=null&&J.includes(Z)?"":` code:${Z}`;throw m||h.error(`${a}() failed ${K}${i.call(this,...c)} ${G}${_e} params: ${JSON.stringify(c,l)}`),b.addFailedEvent({key:u,error:G}),G})}return b.addSuccessEvent({key:u}),S}catch(S){S=w.convertFrom.call(this,S,a);let O=S.extraCode||S.code,K=(_=S.message)!=null&&_.includes(O)?"":` code:${O}`;throw m||h.error(`${a}() failed ${S}${K} params: ${JSON.stringify(c,l)}`),b.addFailedEvent({key:u,error:S}),S}})}var lc=s=>Q((i,e)=>function(t,r){return f(this,null,function*(){let o=this._plugins.get(t);if(!o)throw this._log.error(`plugin ${String(t)} is not found`),new w({code:B.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});if(ne(o.constructor.isSupported)&&!o.constructor.isSupported())throw this._log.error(`plugin ${String(t)} is not supported`),new w({code:B.ENV_NOT_SUPPORTED,message:`plugin ${String(t)} is not supported`,extraCode:5210,fnName:e});return dc.call(this,o.getValidateRule(s),[r],e,"TRTC"),i.call(this,o,r)})});var uc=0,du,ji=class ji{constructor(i){this.core=i;d(this,"log");d(this,"customAudioReferenceMap",new Map);d(this,"audioRefId",0);d(this,"audioContext",Ee());d(this,"localAudioWorkletNode");d(this,"screenAudioWorkletNode");d(this,"mixNode");d(this,"silentNode");uc=uc+1,this.log=i.log.createChild({id:`${this.getAlias()}${uc}`}),this.log.info(`created id=${this.getAlias()}${uc}`)}static getStartValidateRule(i){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,t,r,o){if(!i.room.audioManager.hasAudioTrack&&!i.room.audioManager.hasScreenAudioTrack)throw new w({code:B.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return du||(du=this.doPreload(i)),du}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield Bi(this.audioContext,t)}catch(r){this.log.error(`preload audioProcessor failed. ${r}`)}finally{URL.revokeObjectURL(t)}})}getName(){return ji.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(i){switch(i){case"start":return ji.getStartValidateRule(this.core);case"update":return ji.updateValidateRule;case"stop":return ji.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e}=this.core,{sdkAppId:t,userId:r,assetsPath:o=this.core.assetsPath,audioReference:n,processLevel:a,enableDump:c,isLocalAudioNeedAudioProcess:l=!0,isScreenAudioNeedAudioProcess:h=!0}=i;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=l,this.core.room.audioManager.isScreenAudioNeedAudioProcess=h,!o)throw new w({code:B.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}/audioProcessor-wasm.js`),!this.localAudioWorkletNode||!this.screenAudioWorkletNode){let u=String(Date.now()).slice(0,-3),{auth:m,sign:g,status:D,message:_}=yield WT(L(N({},i),{timestamp:u}));if(!m)throw this.log.info(`audioProcessor: ${r} auth result: ${m}. Message: ${_}`),new w({code:B.INVALID_PARAMETER,message:_});this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",t,r,u,g,D,e),this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",t,r,u,g,D,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),T(n)||n.forEach(u=>{this.customAudioReferenceMap.set(u,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:u,refId:`o-${this.audioRefId++}`})}),T(a)||this.localAudioWorkletNode.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:a}}),T(c)||this.localAudioWorkletNode.port.postMessage({type:"dump",data:{enable:c}})})}update(i){return f(this,null,function*(){if(!this.localAudioWorkletNode||!this.screenAudioWorkletNode)return;let{audioReference:e,enableDump:t,processLevel:r}=i;T(e)||(this.customAudioReferenceMap.forEach((o,n)=>{this.customAudioReferenceMap.delete(n),this.core.room.audioManager.updateAudioReference({type:"remove",refId:o})}),e.forEach(o=>{this.customAudioReferenceMap.set(o,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:o,refId:`o-${this.audioRefId++}`})})),T(r)||this.localAudioWorkletNode.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:r}}),T(t)||(this.localAudioWorkletNode.port.postMessage({type:"dump",data:{enable:t}}),this.screenAudioWorkletNode.port.postMessage({type:"dump",data:{enable:t}}))})}stop(){return f(this,null,function*(){if(!this.localAudioWorkletNode||!this.mixNode||!this.silentNode||!this.screenAudioWorkletNode)return;let{room:i}=this.core;this.localAudioWorkletNode.port.postMessage({type:"disable"}),this.screenAudioWorkletNode.port.postMessage({type:"disable"}),yield i.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(i,e,t,r,o,n,a,c){i.port.postMessage({type:"init",data:{sdkAppId:String(t),userId:r,timestamp:o,sign:n,status:a}}),i.port.onmessage=l=>{var u;let{data:h}=l;switch(h.type){case"cost":let m=(h==null?void 0:h.value)>10?"info":"debug";this.log[m](`[${e}] avg cost: ${h.value} max: ${h==null?void 0:h.max}(${ts(new Date(h==null?void 0:h.maxCostTimestamp))}) hist: ${(u=h==null?void 0:h.hist)==null?void 0:u.join(" ")}`);return;case"log":this.log[h.logLevel](`[${e}] ${h.value}`);return;case"dump":E.emit("265",{room:c,data:h.value,type:e==="localAudio"?"dump":"dump-screen-audio"});return}}}};d(ji,"updateValidateRule",{type:"object"}),d(ji,"stopValidateRule",{type:"object"}),d(ji,"Name","AudioProcessor");var hc=ji;function GT(s,i=p.MAIN){return`https://${_i[i]||ac(s,i)}/api/v1/audioAiAuth`}function WT(r){return f(this,arguments,function*({sdkAppId:s,userId:i,userSig:e,timestamp:t}){let n=`${GT(s)}?sdkAppId=${s}&userId=${i}&userSig=${e}×tamp=${t}`,a=yield fetch(n),{data:{errCode:c,errMsg:l,sign:h,status:u}}=yield a.json();if(u==="1")return{auth:!0,sign:h,status:u,message:l};let m=Ci(s)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",g="Init RTCAudioProcessor failed.",D="";switch(c){case 1:D="Please check your params.";break;case 2:D=`You need to buy packages. Refer to: ${m}`;break;case 3:D="Server is invalid. Please contact our engineer. ";break;case 4:D=`Your packages is not active. Refer to: ${m}`;break;case 5:D=`Your packages is expired. Refer to: ${m}`;break;case 6:D="Your version is not supported.";break}return{auth:!1,status:u,message:l?`${g} Reason: ${l}. ${D}`:`${g}, ${D}`}})}var mc=0,lu=class{constructor(i,e){d(this,"player");d(this,"publisher");d(this,"mixInput");this.mixInput=new ks(e),i.url?(this.player=new Audio(i.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(i.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(i.track),this.mixInput.connect()}updateSettings(i){this.player&&(T(i.volume)||(this.volume=i.volume),T(i.loop)||(this.loop=i.loop),T(i.playbackRate)||(this.playbackRate=i.playbackRate))}updateListener(i){if(this.player){if(i.onDurationChange){let{onDurationChange:e}=i;this.player.ondurationchange=t=>{e(t.target.duration)}}if(i.onTimeUpdate){let e=i.onTimeUpdate,{player:t}=this;t.ontimeupdate=()=>{e(t.currentTime,t.duration)}}i.onEnded&&(this.player.onended=i.onEnded)}}reset(){this.seek(0),this.mixInput.connect()}seek(i){this.player&&(i<0&&i>this.player.duration||(this.player.currentTime=i,this.publisher.currentTime=i))}play(){var i,e;return(i=this.publisher)==null||i.play(),(e=this.player)==null?void 0:e.play()}pause(){var i,e;(i=this.player)==null||i.pause(),(e=this.publisher)==null||e.pause()}stop(){var i;(i=this.player)==null||i.pause(),this.mixInput.disconnect()}setOperation(i){i==="pause"&&this.pause(),i==="resume"&&(this.pause(),this.play()),i==="stop"&&(this.pause(),this.seek(0))}set volume(i){!this.player||!this.publisher||(this.player.volume=i,this.publisher.volume=i)}set loop(i){!this.player||!this.publisher||(this.player.loop=i,this.publisher.loop=i)}set playbackRate(i){!this.player||!this.publisher||(this.player.playbackRate=i,this.publisher.playbackRate=i)}};function qs(s,i){if(i&&typeof i!="function")throw new w({code:B.INVALID_PARAMETER,message:`start audioMixer plugin: param ${s} should be a function.`})}var gi=class gi{constructor(i){this.core=i;d(this,"log");d(this,"mixedMusicMap",new Map);d(this,"cacheMusicMap",new Map);mc=mc+1,this.log=i.log.createChild({id:`${this.getAlias()}${mc}`}),this.log.info(`created id=${this.getAlias()}${mc}`)}getName(){return gi.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return gi.startValidateRule;case"update":return gi.updateValidateRule;case"stop":return gi.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e}=this.core;this.log.info(`add music source, id: ${i.id} url: ${i.url}, track: ${i.track}`);let{id:t,url:r}=i;if(this.mixedMusicMap.has(t))return;let o=this.cacheMusicMap.get(t);o?i.url?o.reset():(o.mixInput.replaceSource(i.track),o.mixInput.connect()):(o=new lu(i,e.audioManager),this.cacheMusicMap.set(t,o)),o.updateListener(i),o.updateSettings(i),yield o.play(),this.mixedMusicMap.set(t,o),o.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"add",audioReference:o.mixInput.source.node,refId:`ax-${t}`}),this.log.info(`start mix audio track ${t} success.`),b.addEnum({key:502700,value:3}),this.kvUpload(i)})}update(i){return f(this,null,function*(){let{id:e,operation:t,seekFrom:r,playbackRate:o}=i;this.log.info(`update music source, ${JSON.stringify(i)}`);let n=this.mixedMusicMap.get(e);if(!n){this.log.warn(`update music source failed, music id: ${e} not found.`);return}n.updateSettings(i),n.updateListener(i),T(t)||n.setOperation(t),T(r)||n.seek(r),this.kvUpload(i)})}stop(e){return f(this,arguments,function*({id:i}){if(this.mixedMusicMap.has(i)){this.log.info(`remove music source, music id: ${i}`);let t=this.mixedMusicMap.get(i);t!=null&&t.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:t.mixInput.source.node,refId:`ax-${i}`}),t==null||t.stop(),this.mixedMusicMap.delete(i)}i==="*"&&this.destroyAllMusic()})}kvUpload(i){let{track:e,loop:t,volume:r,playbackRate:o,operation:n,seekFrom:a,onTimeUpdate:c,onDurationChange:l,onEnded:h}=i;e&&b.addCount({key:502711}),t&&b.addCount({key:502703}),r&&b.addCount({key:502704}),o&&b.addCount({key:502705}),n&&b.addCount({key:502706}),a&&b.addCount({key:502707}),typeof c!="function"&&b.addCount({key:502709}),typeof h!="function"&&b.addCount({key:502710}),typeof l!="function"&&b.addCount({key:502708})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((i,e)=>{i!=null&&i.mixInput.track&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:i.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()}};d(gi,"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(i,e,t){if(i.url&&i.url!=="*"){let r=i.url.split("?")[0],o=["mp3","ogg","wav","flac"],n=r.split(".").pop(),a=o.indexOf(n)>=0,c=r.startsWith("blob"),l=r.startsWith("data");if(!(a||c||l))throw new w({code:B.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new w({code:B.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});qs("onTimeUpdate",i.onTimeUpdate),qs("onEnded",i.onEnded),qs("onDurationChange",i.onDurationChange)}}),d(gi,"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(i,e,t){qs("onTimeUpdate",i.onTimeUpdate),qs("onEnded",i.onEnded),qs("onDurationChange",i.onDurationChange)}}),d(gi,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),d(gi,"Name","AudioMixer");var pc=gi;var fc=0,uu,Xi=class Xi{constructor(i){this.core=i;d(this,"log");d(this,"audioContext",Ee("denoiser"));d(this,"workletNode");fc=fc+1,this.log=i.log.createChild({id:`${this.getAlias()}${fc}`}),this.log.info(`created id=${this.getAlias()}${fc}`)}static startValidateRule(i){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,t,r,o){if(!i.room.audioManager.hasAudioTrack)throw new w({code:B.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return uu||(uu=this.doPreload(i)),uu}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield Bi(this.audioContext,t)}catch(r){throw this.log.error("load worklet failed",r),r}finally{URL.revokeObjectURL(t)}})}getName(){return Xi.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(i){switch(i){case"start":return Xi.startValidateRule(this.core);case"update":return Xi.updateValidateRule;case"stop":return Xi.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e,schedule:t}=this.core,{assetsPath:r=this.core.assetsPath}=i;if(!r)throw new w({code:B.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(yield this.preload(`${r}/denoiser-wasm.js`),!this.workletNode){let o=String(Date.now()).slice(0,-3),{auth:n,sign:a,status:c,message:l}=yield qT(t,L(N({},i),{timestamp:o}));if(!n)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${n}. Message: ${l}`),new w({code:B.INVALID_PARAMETER,message:l});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(i.sdkAppId),userId:i.userId,timestamp:o,sign:a,status:c}}),this.workletNode.port.onmessage=h=>{var m;let{data:u}=h;if(u.type==="cost"){let g=(u==null?void 0:u.max)>20?"warn":(u==null?void 0:u.max)>10?"info":"debug";this.log[g](`avg cost: ${u.value} max: ${u==null?void 0:u.max}(${ts(new Date(u==null?void 0:u.maxCostTimestamp))}) hist: ${(m=u==null?void 0:u.hist)==null?void 0:m.join(" ")}`)}else u.type==="log"&&this.log[u.logLevel](`${u.value}`)}}this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(){return f(this,null,function*(){})}stop(){return f(this,null,function*(){if(!this.workletNode)return;let{room:i}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield i.audioManager.removeDenoiser(this.workletNode)})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};d(Xi,"updateValidateRule",{type:"object"}),d(Xi,"stopValidateRule",{type:"object"}),d(Xi,"Name","AIDenoiser");var _c=Xi;function qT(o,n){return f(this,arguments,function*(s,{sdkAppId:i,userId:e,userSig:t,timestamp:r}){try{let{data:{errCode:a,errMsg:c,sign:l,status:h}}=yield s.getAbilityConfig(i,s.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:i,userId:e,userSig:t,timestamp:r});if(h==="1")return{auth:!0,sign:l,status:h,message:c};let u=Ci(i)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",m="Init RTCAIDenoiser failed.",g="";switch(a){case 1:g="Please check your params.";break;case 2:g=`You need to buy packages. Refer to: ${u}`;break;case 3:g="Server is invalid. Please contact our engineer. ";break;case 4:g=`Your packages is not active. Refer to: ${u}`;break;case 5:g=`Your packages is expired. Refer to: ${u}`;break;case 6:g="Your version is not supported.";break}return{auth:!1,status:h,message:c?`${m} Reason: ${c}. ${g}`:`${m}, ${g}`}}catch(a){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${a}`}}})}var up=$e(Ye(),1);var hu=class extends up.EventEmitter{constructor(){super();d(this,"observer");d(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 f(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!pe&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){re.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let t=this.stateNum,r=e[e.length-1];this.state=r.state,(this.stateNum>3||t>3)&&C.info(`${r.source}: ${r.state}`),this.emit("state-changed",{type:r.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(t){re.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},jT=new hu,mu=jT;function pu([s,i]){let e=i.byteLength,t=parseInt(String(e/255),10),r=e%255,o=[];o.push(0,0,0,1,6,s);for(let a=0;a<t;a++)o.push(255);o.push(r);let n=new DataView(i);return o.push(...new Uint8Array(n.buffer)),o.push(128),new Hi(new DataView(new Uint8Array(o).buffer),!0)}function fu(s){return s.type==="empty"||s.data.byteLength===0}function _u(s){return s.getInt32(0)===1&&s.getInt8(4)===6}function gu(s){let i=0,e=0,t=new DataView(s);for(let r=0;r<s.byteLength;r++)switch(t.getUint8(r)){case 0:i++;break;case 1:(i===2||i===3)&&e++,i=0;break;default:i=0;break}return e}function Tu({frame:s,seiMessageList:i}){if(!i||i.length===0||s.data.byteLength===0)return s;let t=9-gu(s.data);if(t<=0)return s;let r=i.splice(0,t).reverse().map(pu),o=r.reduce((h,u)=>h+u.dataView.byteLength,0),n=new ArrayBuffer(o+s.data.byteLength),a=new DataView(n),c=new DataView(s.data),l=0;for(let h=0;h<r.length;h++)for(let u=0;u<r[h].dataView.byteLength;u++)a.setInt8(l++,r[h].dataView.getInt8(u));for(let h=0;h<s.data.byteLength;h++)a.setInt8(l++,c.getInt8(h));return s.data=n,s}function Eu({frame:s,onSEI:i}){try{let e=new DataView(s.data);if(fu(s)||!_u(e))return s;let t=[],r=0,o=-1,n=-1;for(let a=0;a<s.data.byteLength;a++){let c=e.getUint8(a);if(c===0)r++;else if(c===1){if(r===2||r===3){let l=a-r;if(o===-1?o=l:n===-1&&(n=l,t.push(new Hi(new DataView(e.buffer.slice(o,n)))),o=l,n=-1),!(e.getUint8(a+1)===6)){s.data=e.buffer.slice(l);break}}r=0}else r=0}i==null||i(t.reverse())}catch(e){}return s}var Su=0,nn=class nn{constructor(i){this.core=i;d(this,"log");d(this,"_seiMessageList",[]);d(this,"_smallSeiMessageList",[]);d(this,"_subStreamSeiMessageList",[]);Su++,this.log=i.log.createChild({id:`${this.getAlias()}${Su}`}),this.log.info(`[sei] created id=${this.getAlias()}${Su}`),this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode({frame:i,mediaType:e}){try{let t=e===8?this._smallSeiMessageList:e===2?this._subStreamSeiMessageList:this._seiMessageList;return Tu({frame:i,seiMessageList:t})}catch(t){this.log.warn(t)}return i}decode({frame:i,track:e}){return Eu({frame:i,onSEI:t=>{t.forEach(r=>{this.core.trtc.emit(k.SEI_MESSAGE,{seiPayloadType:r.seiPayloadType,data:r.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"})})}})}destroy(){this.log.debug("destory"),this.stop(),delete this.core}getValidateRule(i){switch(i){case"start":return{type:"object"};case"update":return{type:"object"};case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:Ui?this.encode:Tu,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:Ui?this.decode:Eu,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update({buffer:i,options:e}){var o;let t=[e.seiPayloadType,i],r=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(t):(this._seiMessageList.push(t),r&&this._smallSeiMessageList.push(t)),(o=this.core.room.scriptTransformWorker)==null||o.postMessage({type:"sei",data:t,isMain:!e.toSubStream,small:r})}getName(){return nn.Name}getAlias(){return"sei"}getGroup(){return"sei"}};d(nn,"autoStart",!0),d(nn,"Name","SEI");var gc=nn;function Iu({frame:s,onDump:i}){return i==null||i(),s}function Au({frame:s,onDump:i}){return i==null||i(),s}var hp={"play() error: NotAllowedError:":{tips:s=>s.includes("main <video>")||s.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:s=>s.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:s=>s.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:
|
|
58
58
|
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.
|
|
59
59
|
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:
|
|
60
60
|
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.
|
|
@@ -66,7 +66,7 @@ ${r.stack}`),!1}},s};var Js=new WeakMap;function op(s){let i=Js.get(s);i&&(i.for
|
|
|
66
66
|
`:c)),e}updateAudioBandwidthRestriction(e,t){let r="AS";return ae&&(r="TIAS",t=t*1e3),e=e.replace(/m=audio (.*)\r\nc=IN (.*)\r\n/,`m=audio $1\r
|
|
67
67
|
c=IN $2\r
|
|
68
68
|
b=${r}:${t}\r
|
|
69
|
-
`),e}removeBandwidthRestriction(e){return e.replace(/b=AS:.*\r\n/,"").replace(/b=TIAS:.*\r\n/,"")}removeVideoOrientation(e){return e.replace(/urn:3gpp:video-orientation/,"")}connect(){return f(this,null,function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(e){throw this.closePeerConnection(!0),this.uninstallEvents(),e}})}exchangeSDP(){return f(this,null,function*(){try{yield this.createOffer(),this._log.info("createOffer success, sending offer to remote server"),yield this.doExchangeSDP()}catch(e){throw e}})}createOffer(){return f(this,null,function*(){try{let e=yield this._peerConnection.createOffer(xp);yield this.setOffer(e),e.sdp&&this.updateSSRC(e.sdp)}catch(e){throw e}})}doExchangeSDP(){let e={command:Y.PUBLISH,responseCommand:F.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof ut||this.localAuxVideoTrack instanceof ut,state:this.publishState,constraintConfig:this._mediaSettings},enableLog:!1};return this._log.debug(`sending sdp offer: ${e.data.sdp}`),this._signalChannel.sendWaitForResponse(e).then(t=>{let{code:r,message:o,data:n}=t.data;return r===0?this.acceptAnswer(n):this.checkPublishResultCode(r,o)})}setSDPDirection(e,t,r="all"){let o=ye(e);return o.media.forEach(n=>{(r==="all"||n.type===r)&&(n.direction=t)}),Nt(o)}acceptAnswer(e){return f(this,null,function*(){var t,r,o,n,a;try{let c;if(this._publishingLocalAudioTrack||this._publishingLocalVideoTrack||this.isMainStreamPublished){let u=((t=this._publishingLocalVideoTrack)==null?void 0:t.profile.bitrate)||((r=this.localMainVideoTrack)==null?void 0:r.profile.bitrate),m=((o=this._publishingLocalAudioTrack)==null?void 0:o.profile.bitrate)||((n=this.localMainAudioTrack)==null?void 0:n.profile.bitrate);if(u){let g=this._isPublishingAux?p.AUXILIARY:p.BIG;c=yield this.setBandwidth({bandwidth:u,type:p.VIDEO,sdp:c,videoType:g})}m&&(c=yield this.setBandwidth({bandwidth:m,type:p.AUDIO,sdp:c}))}if(c=this.removeVideoOrientation(e.sdp),(a=this._publishingLocalVideoTrack)!=null&&a.small){let{smallStreamConfig:u}=this._room;c=yield this.setBandwidth({bandwidth:this._publishingLocalVideoTrack.small.bitrate||u.bitrate,type:p.VIDEO,videoType:p.SMALL,sdp:c})}let h={type:e.type,sdp:c};yield this.setAnswer(h),this._log.debug(`accepted answer: ${c}`)}catch(c){throw this._log.error(`failed to accept remote answer ${c}`),c}})}sendMutedFlag(e){var o,n,a;if(e===this.localAuxAudioTrack||e===this.localAuxVideoTrack)return;let r={audio:!!((o=this.localMainAudioTrack)!=null&&o.muted),bigVideo:!!((n=this.localMainVideoTrack)!=null&&n.muted),auxVideo:!!((a=this.localAuxVideoTrack)!=null&&a.muted)};this._log.info(`send muted state: ${JSON.stringify(r)}`),this._signalChannel.send(Y.UPDATE_MUTE_STAT,r)}getIsReconnecting(){return this._isReconnecting}reconnect(){return f(this,null,function*(){if(!(He(Qs.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:Y.UNPUBLISH,responseCommand:F.UNPUBLISH_RESULT,enableLog:!1}),this.closePeerConnection(),this.initialize(),this.isMainStreamPublished&&(yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0})),this._log.warn("reconnect() uplink reconnect successfully"),this.stopReconnection()}catch(t){let r=Pt(this._reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${r/1e3}s`),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},r)}})}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&E.emit(A.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{ye(e).media.forEach((r,o)=>{if(r.type===p.AUDIO){let n=r.ssrcs&&r.ssrcs[0];n&&(this.ssrc.audio=Number(n.id))}else{if(this._sdpSemantics===rs&&r.ssrcGroups){r.ssrcGroups.forEach((a,c)=>{let l=Number(a.ssrcs.split(" ")[0]);c===0?this.ssrc.video=l:c===1&&(this.ssrc.small=l)});return}let n=r.ssrcs&&r.ssrcs[0];if(!n)return;switch(o){case 1:this.ssrc.video=Number(n.id);break;case 2:this.ssrc.small=Number(n.id);break;case 3:this.ssrc.auxiliary=Number(n.id);break;default:break}}})}catch(t){}}getVideoTrackId(e=p.VIDEO){if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===p.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===p.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===p.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===p.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===Sr?(this._log.error(Ve.NOT_SUPPORTED_H264ENCODE),new y({code:I.NOT_SUPPORTED_H264,message:x({key:P.NOT_SUPPORTED_H264ENCODE})})):new y({code:I.UNKNOWN,message:x({key:P.SIGNAL_RESPONSE_FAILED,data:{signalResponse:F.PUBLISH_RESULT,code:e,message:t}})})}};v([Q(e=>function(...t){return new Promise((r,o)=>{let n=a=>{this._emitter.off("closed",n),o(new y({code:I.API_CALL_ABORTED,message:x({key:P.CONNECTION_ABORTED,data:a})}))};this._emitter.on("closed",n),e.apply(this,t).then(r,o).finally(()=>{this._emitter.off("closed",n)})})})],Qs.prototype,"publish",1),v([lt(521715,!1)],Qs.prototype,"unpublish",1),v([et(rt.prototype.afterConnect),Ma(rt.prototype.beforeConnect)],Qs.prototype,"connect",1);var xu=Qs,mn=xu;var pn=class{constructor(i,e){this.room=i;d(this,"_log");d(this,"_prevReportTime",0);d(this,"_prevReport",{});d(this,"_prevStats",null);d(this,"_prevEncoderImplementation","");d(this,"_prevAuxEncoderImpl","");d(this,"_prevQualityLimitationReason","");d(this,"_prevAuxQualityLimitationReason","");d(this,"_prevDecoderImplementationMap",new Map);d(this,"totalBytesSent",0);d(this,"totalBytesReceived",0);d(this,"_spcStats",null);this._log=e}get statInterval(){return this._prevReportTime===0?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(i){return f(this,null,function*(){var o;let e={audio:{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0},video:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},small:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},auxiliary:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},rtt:0},t=i.getPeerConnection(),r=i.getSSRC();if(t)try{if((this._spcStats||(yield t.getStats())).forEach(a=>{var h,u,m;let c,l;if(a.type==="outbound-rtp")if((a.mediaType||a.kind)===p.VIDEO){if(a.ssrc===r.video?(c=p.VIDEO,l=i.localMainVideoTrack):a.ssrc===r.small?c=p.SMALL:a.ssrc===r.auxiliary&&(l=i.localAuxVideoTrack,c=p.AUXILIARY),!c)return;if(e[c].bytesSent=a.bytesSent,e[c].packetsSent=a.packetsSent,e[c].framesEncoded=a.framesEncoded,T(a.keyFramesEncoded)||(e[c].keyFramesEncoded=a.keyFramesEncoded),T(a.nackCount)||(e[c].nackCount=a.nackCount),T(a.pliCount)||(e[c].pliCount=a.pliCount),T(a.retransmittedPacketsSent)||(e[c].retransmittedPacketsSent=a.retransmittedPacketsSent),T(a.totalEncodeTime)||(e[c].totalEncodeTime=a.totalEncodeTime),T(a.totalPacketSendDelay)||(e[c].totalPacketSendDelay=a.totalPacketSendDelay),!T(a.encoderImplementation)&&(c===p.VIDEO&&this._prevEncoderImplementation!==a.encoderImplementation||c===p.AUXILIARY&&this._prevAuxEncoderImpl!==a.encoderImplementation)){let D=2,_=this._prevEncoderImplementation;c===p.AUXILIARY&&(D=7,_=this._prevAuxEncoderImpl),E.emit("262",{userId:i.userId,streamType:D,prevImplementation:_,implementation:a.encoderImplementation,codec:i.videoCodec,isHWCodec:a.powerEfficientEncoder}),this[c===p.VIDEO?"_prevEncoderImplementation":"_prevAuxEncoderImpl"]=a.encoderImplementation,this._log.info(`${c===p.AUXILIARY?"aux ":""}encoderImplementation change to ${a.encoderImplementation}(${i.videoCodec}) HWEncoder: ${a.powerEfficientEncoder}`)}a.ssrc===r.video?!T(a.qualityLimitationReason)&&a.bytesSent!==0&&this._prevQualityLimitationReason!==a.qualityLimitationReason&&(this._log.info(`qualityLimitationReason change to ${a.qualityLimitationReason}`),E.emit("263",{userId:i.userId,reason:a.qualityLimitationReason,prevReason:this._prevQualityLimitationReason,streamType:2,isQosClearFirst:(h=i.localMainVideoTrack)==null?void 0:h.isQosClearFirst}),this._prevQualityLimitationReason=a.qualityLimitationReason):a.ssrc===r.auxiliary&&!T(a.qualityLimitationReason)&&a.bytesSent!==0&&this._prevAuxQualityLimitationReason!==a.qualityLimitationReason&&(this._log.info(`aux qualityLimitationReason change to ${a.qualityLimitationReason}`),E.emit("263",{userId:i.userId,reason:a.qualityLimitationReason,prevReason:this._prevAuxQualityLimitationReason,streamType:7,isQosClearFirst:(u=i.localAuxVideoTrack)==null?void 0:u.isQosClearFirst}),this._prevAuxQualityLimitationReason=a.qualityLimitationReason)}else e.audio.bytesSent=a.bytesSent,e.audio.packetsSent=a.packetsSent;else a.type==="candidate-pair"?cr(a)&&(this.totalBytesSent=a.bytesSent,q(a.currentRoundTripTime)&&(e.rtt=Math.floor(a.currentRoundTripTime*1e3))):a.type==="media-source"&&(a.kind===p.AUDIO?(e.audio.audioLevel=a.audioLevel||0,e.audio.totalAudioEnergy=a.totalAudioEnergy||0,a.echoReturnLoss,a.totalSamplesDuration&&(e.audio.totalSamplesDuration=a.totalSamplesDuration)):a.kind===p.VIDEO&&(a.trackIdentifier===i.getVideoTrackId(p.VIDEO)?e.video.fpsCapture=a.framesPerSecond:a.trackIdentifier===i.getVideoTrackId(p.AUXILIARY)?e.auxiliary.fpsCapture=a.framesPerSecond:e.small.fpsCapture=a.framesPerSecond));if(!T(a.audioLevel)&&((m=i.localMainAudioTrack)!=null&&m.mediaTrack)&&a.trackIdentifier===i.localMainAudioTrack.mediaTrack.id&&(e.audio.audioLevel=a.audioLevel||0),!T(a.frameWidth)){let g=p.SMALL;a.trackIdentifier===i.getVideoTrackId(p.VIDEO)||a.ssrc===r.video?g=p.VIDEO:(a.trackIdentifier===i.getVideoTrackId(p.AUXILIARY)||a.ssrc===r.auxiliary)&&(g=p.AUXILIARY),e[g].frameWidth=a.frameWidth,e[g].frameHeight=a.frameHeight,e[g].framesSent=a.framesSent}}),i.localMainAudioTrack){let a=i.localMainAudioTrack.getInternalAudioLevel();e.audio.micAudioLevel=a,e.audio.audioLevel===0&&(e.audio.audioLevel=a)}this.totalBytesSent||(this.totalBytesSent+=e.audio.bytesSent+e.video.bytesSent+e.auxiliary.bytesSent),Object.keys(e).forEach(a=>{a===p.AUDIO?(i.localMainAudioTrack&&(i.localMainAudioTrack.stat=e[a]),i.localAuxAudioTrack&&(i.localAuxAudioTrack.stat=e[a])):a===p.VIDEO?i.localMainVideoTrack&&(i.localMainVideoTrack.stat=e[a]):a===p.AUXILIARY&&i.localAuxVideoTrack&&(i.localAuxVideoTrack.stat=e[a])})}catch(n){this._log.warn(`failed to getStats on sender connection ${n}`)}return e.rtt===0&&(e.rtt=((o=this.room.networkQuality)==null?void 0:o.uplinkRTT)||0),e})}getReceiverStats(i){return f(this,null,function*(){var r,o,n;let e={tinyId:i.tinyId,userId:i.userId,rtt:0,hasAudio:!1,hasVideo:!1,hasAuxiliary:!1,isSmallSubscribed:!1,audio:{bytesReceived:0,packetsReceived:0,packetsLost:0,p2pDelay:0,totalJitter:0,totalJitterCount:0,audioLevel:0,totalAudioEnergy:0,insertedSamplesForDeceleration:0,removedSamplesForAcceleration:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,freezeCount:0,totalFreezesDuration:0,totalJitter:0,totalJitterCount:0,p2pDelay:0},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,totalJitter:0,totalJitterCount:0,p2pDelay:0}},t=i.getPeerConnection();if(t)try{let{ssrc:a}=i,{muteState:c,subscribeState:l}=i;(this._spcStats||(yield t.getStats())).forEach(u=>{if(u.type==="inbound-rtp"){let m=(u.mediaType||u.kind)===p.AUDIO;if(m){if(u.ssrc!==a.audio||!c.hasAudio)return;e.audio.packetsReceived=u.packetsReceived,e.audio.bytesReceived=u.bytesReceived,e.audio.packetsLost=u.packetsLost,u.insertedSamplesForDeceleration&&(e.audio.insertedSamplesForDeceleration=u.insertedSamplesForDeceleration),u.removedSamplesForAcceleration&&(e.audio.removedSamplesForAcceleration=u.removedSamplesForAcceleration),u.totalSamplesDuration&&(e.audio.totalSamplesDuration=u.totalSamplesDuration),u.totalSamplesReceived&&(e.audio.totalSamplesReceived=u.totalSamplesReceived),u.concealedSamples&&(e.audio.concealedSamples=u.concealedSamples),u.silentConcealedSamples&&(e.audio.silentConcealedSamples=u.silentConcealedSamples);let{remoteAudioTrack:g}=i;g.stat.packetsReceived=u.packetsReceived,g.stat.bytesReceived=u.bytesReceived,g.stat.packetsLost=u.packetsLost,e.audio.p2pDelay=g.stat.end2EndDelay,e.hasAudio=!0}else{if(ae&&u.bytesReceived===0)return;let g;u.ssrc===a.video&&c.hasVideo&&(e.video.packetsReceived=u.packetsReceived,e.video.bytesReceived=u.bytesReceived,e.video.packetsLost=u.packetsLost,e.video.framesReceived=u.framesReceived,e.video.framesDecoded=u.framesDecoded,e.video.fpsDecoded=u.framesPerSecond,e.hasVideo=!0,g=i.remoteVideoTrack,c.hasSmall&&l.smallVideo&&(e.isSmallSubscribed=!0),u.decoderImplementation&&(!this._prevDecoderImplementationMap.has(e.userId)||this._prevDecoderImplementationMap.get(e.userId)!==u.decoderImplementation)&&(this._log.info(`${e.userId} decoderImplementation change to ${u.decoderImplementation} HWDecoder: ${u.powerEfficientDecoder}`),E.emit("262",{userId:this.room.userId,remoteUserId:e.userId,prevImplementation:this._prevDecoderImplementationMap.get(e.userId),implementation:u.decoderImplementation,codec:i.videoCodec,isHWCodec:u.powerEfficientDecoder}),this._prevDecoderImplementationMap.set(e.userId,u.decoderImplementation))),u.ssrc===a.auxiliary&&c.hasAuxiliary&&(e.auxiliary.packetsReceived=u.packetsReceived,e.auxiliary.bytesReceived=u.bytesReceived,e.auxiliary.packetsLost=u.packetsLost,e.auxiliary.framesReceived=u.framesReceived,e.auxiliary.framesDecoded=u.framesDecoded,e.auxiliary.fpsDecoded=u.framesPerSecond,g=i.remoteAuxiliaryTrack,e.auxiliary.p2pDelay=g.stat.end2EndDelay,e.hasAuxiliary=!0),g&&(g.stat.packetsReceived=u.packetsReceived,g.stat.bytesReceived=u.bytesReceived,g.stat.packetsLost=u.packetsLost,g.stat.framesReceived=u.framesReceived,g.stat.framesDecoded=u.framesDecoded,u.jitterBufferDelay&&(g.stat.jitterBufferDelay=Math.floor(u.jitterBufferDelay/u.jitterBufferEmittedCount*1e3)),e.video.p2pDelay=g.stat.end2EndDelay)}u.jitterBufferDelay&&(m?(e.audio.totalJitter=u.jitterBufferDelay,e.audio.totalJitterCount=u.jitterBufferEmittedCount):u.ssrc===a.video&&c.hasVideo?(e.video.totalJitter=u.jitterBufferDelay,e.video.totalJitterCount=u.jitterBufferEmittedCount):u.ssrc===a.auxiliary&&c.hasAuxiliary&&(e.auxiliary.totalJitter=u.jitterBufferDelay,e.auxiliary.totalJitterCount=u.jitterBufferEmittedCount))}else u.type==="candidate-pair"&&cr(u)&&(this.totalBytesReceived=u.bytesReceived,q(u.currentRoundTripTime)&&(e.rtt=Math.floor(u.currentRoundTripTime*1e3)));T(u.frameWidth)||((u.trackIdentifier===i.getMainStreamVideoTrackId()||u.ssrc===a.video)&&(e.video.frameWidth=u.frameWidth,e.video.frameHeight=u.frameHeight,i.remoteVideoTrack.stat.frameWidth=u.frameWidth,i.remoteVideoTrack.stat.frameHeight=u.frameHeight),(u.trackIdentifier===i.getAuxStreamVideoTrackId()||u.ssrc===a.auxiliary)&&(e.auxiliary.frameWidth=u.frameWidth,e.auxiliary.frameHeight=u.frameHeight,i.remoteAuxiliaryTrack.stat.frameWidth=u.frameWidth,i.remoteAuxiliaryTrack.stat.frameHeight=u.frameHeight)),!T(u.audioLevel)&&i.muteState.audioAvailable&&i.remoteAudioTrack.mediaTrack&&u.trackIdentifier===i.remoteAudioTrack.mediaTrack.id&&(e.audio.audioLevel=u.audioLevel||0,e.audio.totalAudioEnergy=u.totalAudioEnergy||0)}),e.audio.audioLevel===0&&i.muteState.audioAvailable&&(e.audio.audioLevel=i.remoteAudioTrack.getInternalAudioLevel()||0),this.totalBytesReceived||(this.totalBytesReceived+=e.audio.bytesReceived+e.video.bytesReceived+e.auxiliary.bytesReceived),T((r=i.remoteVideoTrack.player.stat)==null?void 0:r.fps)||(e.video.fpsRender=i.remoteVideoTrack.player.stat.fps),T((o=i.remoteAuxiliaryTrack.player.stat)==null?void 0:o.fps)||(e.auxiliary.fpsRender=i.remoteAuxiliaryTrack.player.stat.fps)}catch(a){this._log.warn(`failed to getStats on receiver connection ${a}`)}return e.rtt===0&&(e.rtt=((n=this.room.networkQuality)==null?void 0:n.uplinkRTT)||0),e})}getStats(i,e){return f(this,null,function*(){let t={},r=[];if(this.room.singlePC){let o=this.room.singlePC.getPeerConnection();if(!o)return{senderStats:t,receiverStats:r};let n=U(),a=yield o.getStats(),c=U();c-n>2e3&&this._log.warn(`getStats cost ${c-n}ms`);let l=[],h=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source"]);a.forEach(u=>h.has(u.type)&&l.push(u)),this._spcStats=l}i&&(t=yield this.getSenderStats(i));for(let[o,n]of e){let a=yield this.getReceiverStats(n);r.push(a)}return{senderStats:t,receiverStats:r}})}getDifferenceValue(i,e){if(li(i))return e;let t=e-i;return t<0?0:t}prepareReport({stats:i,report:e,freezeMap:t}){var m,g,D;if(!li(i.senderStats)){let _={uint32_audio_level:i.senderStats.audio.audioLevel*At,uint32_audio_energy:(i.senderStats.audio.totalAudioEnergy||0)*1e6,uint32_audio_codec_bitrate:i.senderStats.audio.bytesSent};i.senderStats.audio.micAudioLevel&&(_.uint32_mic_audio_level=i.senderStats.audio.micAudioLevel*At),i.senderStats.audio.totalSamplesDuration&&(e.msg_device_info.uint32_audio_capture_cost=i.senderStats.audio.totalSamplesDuration);let S=[];if(i.senderStats.video.bytesSent){let K={uint32_video_stream_type:2,uint32_video_codec_fps:i.senderStats.video.framesSent,uint32_video_capture_fps:i.senderStats.video.fpsCapture,uint32_video_width:i.senderStats.video.frameWidth,uint32_video_height:i.senderStats.video.frameHeight,uint32_video_codec_bitrate:i.senderStats.video.bytesSent,uint32_video_enc_fps:i.senderStats.video.framesEncoded,uint32_key_frame_count:i.senderStats.video.keyFramesEncoded,uint32_nack_count:i.senderStats.video.nackCount,uint32_pli_count:i.senderStats.video.pliCount,uint32_encode_cost:(i.senderStats.video.totalEncodeTime||0)*1e3,uint32_send_packet_cost:(i.senderStats.video.totalPacketSendDelay||0)*1e3,uint32_video_arq_packets:i.senderStats.video.retransmittedPacketsSent};S.push(K)}if(i.senderStats.small.bytesSent){let K={uint32_video_stream_type:3,uint32_video_codec_fps:i.senderStats.small.framesSent||0,uint32_video_capture_fps:i.senderStats.small.fpsCapture||0,uint32_video_width:i.senderStats.small.frameWidth||0,uint32_video_height:i.senderStats.small.frameHeight||0,uint32_video_codec_bitrate:i.senderStats.small.bytesSent,uint32_video_enc_fps:i.senderStats.small.framesEncoded||0,uint32_key_frame_count:i.senderStats.small.keyFramesEncoded,uint32_nack_count:i.senderStats.small.nackCount,uint32_pli_count:i.senderStats.small.pliCount,uint32_encode_cost:(i.senderStats.small.totalEncodeTime||0)*1e3,uint32_send_packet_cost:(i.senderStats.small.totalPacketSendDelay||0)*1e3,uint32_video_arq_packets:i.senderStats.small.retransmittedPacketsSent};S.push(K)}if(i.senderStats.auxiliary.bytesSent){let K={uint32_video_stream_type:7,uint32_video_codec_fps:i.senderStats.auxiliary.framesSent||0,uint32_video_capture_fps:i.senderStats.auxiliary.fpsCapture||0,uint32_video_width:i.senderStats.auxiliary.frameWidth||0,uint32_video_height:i.senderStats.auxiliary.frameHeight||0,uint32_video_codec_bitrate:i.senderStats.auxiliary.bytesSent,uint32_video_enc_fps:i.senderStats.auxiliary.framesEncoded||0,uint32_key_frame_count:i.senderStats.auxiliary.keyFramesEncoded,uint32_nack_count:i.senderStats.auxiliary.nackCount,uint32_pli_count:i.senderStats.auxiliary.pliCount,uint32_encode_cost:(i.senderStats.auxiliary.totalEncodeTime||0)*1e3,uint32_send_packet_cost:(i.senderStats.auxiliary.totalPacketSendDelay||0)*1e3,uint32_video_arq_packets:i.senderStats.auxiliary.retransmittedPacketsSent};S.push(K)}let O={uint32_bitrate:0,uint32_lost:0,uint32_rtt:i.senderStats.rtt};e.msg_up_stream_info={msg_audio_status:_,msg_video_status:S,msg_network_status:O}}let r=(m=Ee())==null?void 0:m.playoutStats;r&&(e.msg_device_info.uint32_audio_play_cost=r.totalFramesDuration);let{statInterval:o}=this;e.msg_down_stream_info=[],i.receiverStats.forEach(_=>{let S={msg_user_info:{str_identifier:_.userId,uint64_tinyid:_.tinyId},msg_network_status:{uint32_rtt:_.rtt,uint32_bitrate:0,uint32_lost:0},msg_audio_status:{},msg_video_status:[]};if(_.hasAudio){let O={uint32_audio_p2p_delay:_.audio.p2pDelay,uint32_audio_cache_ms:_.audio.totalJitter,uint32_audio_cache_ms_count:_.audio.totalJitterCount,uint32_audio_codec_bitrate:_.audio.bytesReceived,uint32_audio_total_bitrate:_.audio.bytesReceived,uint32_audio_level:_.audio.audioLevel*1e8,uint32_audio_energy:_.audio.totalAudioEnergy*1e6,uint32_audio_receive:_.audio.packetsReceived,uint32_audio_origin_lost:_.audio.packetsLost};S.msg_audio_status=O}if(_.hasVideo){let O=t.get(`${_.userId}_${Xc}`),K=O?O.duration:0,G={uint32_video_stream_type:_.isSmallSubscribed?3:2,uint32_video_receive_fps:_.video.framesReceived,uint32_video_width:_.video.frameWidth,uint32_video_height:_.video.frameHeight,uint32_video_codec_bitrate:_.video.bytesReceived,uint32_video_receive:_.video.packetsReceived,uint32_video_origin_lost:_.video.packetsLost,uint32_video_block_time:K,uint32_video_dec_fps:_.video.framesDecoded,uint32_video_codec_fps:_.video.fpsRender,uint32_video_cache_ms:_.video.totalJitter,uint32_video_cache_ms_count:_.video.totalJitterCount,uint32_video_p2p_delay:_.video.p2pDelay};S.msg_video_status.push(G)}if(_.hasAuxiliary){let O=t.get(`${_.userId}_${zc}`),K=O?O.duration:0,G={uint32_video_stream_type:7,uint32_video_receive_fps:_.auxiliary.framesReceived,uint32_video_width:_.auxiliary.frameWidth,uint32_video_height:_.auxiliary.frameHeight,uint32_video_codec_bitrate:_.auxiliary.bytesReceived,uint32_video_receive:_.auxiliary.packetsReceived+_.auxiliary.packetsLost,uint32_video_origin_lost:_.auxiliary.packetsLost,uint32_video_block_time:K,uint32_video_dec_fps:_.auxiliary.framesDecoded,uint32_video_codec_fps:_.video.fpsRender,uint32_video_cache_ms:_.auxiliary.totalJitter,uint32_video_cache_ms_count:_.auxiliary.totalJitterCount,uint32_video_p2p_delay:_.auxiliary.p2pDelay};S.msg_video_status.push(G)}e.msg_down_stream_info.push(S)});let n=this._prevReport,a=this._prevStats;if(this._prevReport=JSON.parse(JSON.stringify(e)),this._prevStats=JSON.parse(JSON.stringify(i)),e.msg_up_stream_info.msg_audio_status&&n.msg_up_stream_info.msg_audio_status){let _=n.msg_up_stream_info.msg_audio_status,S=e.msg_up_stream_info.msg_audio_status;if(_.uint32_audio_codec_bitrate===0)S.uint32_audio_codec_bitrate=0;else{let O=this.getDifferenceValue(_.uint32_audio_codec_bitrate,S.uint32_audio_codec_bitrate);S.uint32_audio_codec_bitrate=Math.round(O*8/o),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=S.uint32_audio_codec_bitrate}(g=n.msg_device_info)!=null&&g.uint32_audio_capture_cost?e.msg_device_info.uint32_audio_capture_cost=2*Math.floor(this.getDifferenceValue(n.msg_device_info.uint32_audio_capture_cost,e.msg_device_info.uint32_audio_capture_cost)*1e3/o):delete e.msg_device_info.uint32_audio_capture_cost}let c=n.msg_up_stream_info.msg_video_status;e.msg_up_stream_info.msg_video_status.forEach(_=>{let S=c.find(_e=>_e.uint32_video_stream_type===_.uint32_video_stream_type);if(!S||S.uint32_video_codec_bitrate===0){_.uint32_video_codec_bitrate=0,_.uint32_video_enc_fps=0,_.uint32_video_codec_fps=0;return}let O=0,K=0,G=0;S&&_.uint32_video_codec_bitrate>=S.uint32_video_codec_bitrate&&(O=S.uint32_video_codec_bitrate,K=S.uint32_video_enc_fps,G=S.uint32_video_codec_fps);let Z=this.getDifferenceValue(O,_.uint32_video_codec_bitrate);_.uint32_video_codec_bitrate=Math.round(Z*8/o),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=_.uint32_video_codec_bitrate,_.uint32_video_enc_fps=Math.round(this.getDifferenceValue(K,_.uint32_video_enc_fps)/o),_.uint32_video_codec_fps=Math.round(this.getDifferenceValue(G,_.uint32_video_codec_fps)/o),S.uint32_video_width===0&&S.uint32_video_height===0&&S.uint32_video_codec_fps===0&&(_.uint32_video_codec_fps=_.uint32_video_enc_fps),T(S.uint32_key_frame_count)||(_.uint32_key_frame_count=Math.round(this.getDifferenceValue(S.uint32_key_frame_count,_.uint32_key_frame_count))),T(S.uint32_nack_count)||(_.uint32_nack_count=Math.round(this.getDifferenceValue(S.uint32_nack_count,_.uint32_nack_count))),T(S.uint32_pli_count)||(_.uint32_pli_count=Math.round(this.getDifferenceValue(S.uint32_pli_count,_.uint32_pli_count))),T(S.uint32_video_arq_packets)||(_.uint32_video_arq_packets=Math.round(this.getDifferenceValue(S.uint32_video_arq_packets,_.uint32_video_arq_packets))),T(S.uint32_encode_cost)||(_.uint32_encode_cost=Math.round(this.getDifferenceValue(S.uint32_encode_cost,_.uint32_encode_cost)/o)),T(S.uint32_send_packet_cost)||(_.uint32_send_packet_cost=Math.round(this.getDifferenceValue(S.uint32_send_packet_cost,_.uint32_send_packet_cost)/o))});let h=n.msg_down_stream_info;e.msg_down_stream_info=e.msg_down_stream_info.filter(_=>h.find(S=>S.msg_user_info.uint64_tinyid===_.msg_user_info.uint64_tinyid));let u=e.msg_down_stream_info;return u.forEach(_=>{let S=h.find(O=>O.msg_user_info.uint64_tinyid===_.msg_user_info.uint64_tinyid);if(!li(_.msg_audio_status)&&!li(S.msg_audio_status)){let O=_.msg_audio_status,K=S.msg_audio_status,G=this.getDifferenceValue(K.uint32_audio_cache_ms_count,O.uint32_audio_cache_ms_count);delete O.uint32_audio_cache_ms_count,O.uint32_audio_cache_ms=Math.floor(1e3*this.getDifferenceValue(K.uint32_audio_cache_ms,O.uint32_audio_cache_ms)/G)||0;let Z=this.room.remotePublishedUserMap.get(_.msg_user_info.str_identifier);Z&&(Z.remoteAudioTrack.stat.jitterBufferDelay=O.uint32_audio_cache_ms),O.uint32_audio_origin_lost=this.getDifferenceValue(K.uint32_audio_origin_lost,O.uint32_audio_origin_lost),O.uint32_audio_receive=this.getDifferenceValue(K.uint32_audio_receive,O.uint32_audio_receive),O.uint32_audio_receive+=O.uint32_audio_origin_lost;let _e=this.getDifferenceValue(K.uint32_audio_codec_bitrate,O.uint32_audio_codec_bitrate);O.uint32_audio_codec_bitrate=Math.round(_e*8/o),O.uint32_audio_total_bitrate=Math.round(_e*8/o)}else _.msg_audio_status={};if(_.msg_video_status&&S.msg_video_status){let O=S.msg_video_status;_.msg_video_status=_.msg_video_status.filter(G=>O.find(Z=>Z.uint32_video_stream_type===G.uint32_video_stream_type)),_.msg_video_status.forEach(G=>{let Z=O.find(gf=>gf.uint32_video_stream_type===G.uint32_video_stream_type),_e=Z.uint32_video_receive,J=Z.uint32_video_origin_lost,uf=Z.uint32_video_codec_bitrate,hf=Z.uint32_video_receive_fps,mf=Z.uint32_video_dec_fps;G.uint32_video_origin_lost=this.getDifferenceValue(J,G.uint32_video_origin_lost),G.uint32_video_receive=this.getDifferenceValue(_e,G.uint32_video_receive)+G.uint32_video_origin_lost;let pf=this.getDifferenceValue(uf,G.uint32_video_codec_bitrate);G.uint32_video_codec_bitrate=Math.round(pf*8/o);let ff=this.getDifferenceValue(hf,G.uint32_video_receive_fps);G.uint32_video_receive_fps=Math.round(ff/o),G.uint32_video_dec_fps=Math.round(this.getDifferenceValue(mf,G.uint32_video_dec_fps)/o);let _f=this.getDifferenceValue(Z.uint32_video_cache_ms_count,G.uint32_video_cache_ms_count);delete G.uint32_video_cache_ms_count,G.uint32_video_cache_ms=Math.floor(1e3*this.getDifferenceValue(Z.uint32_video_cache_ms,G.uint32_video_cache_ms)/_f)||0})}}),(D=n.msg_device_info)!=null&&D.uint32_audio_play_cost?e.msg_device_info.uint32_audio_play_cost=2*Math.floor(this.getDifferenceValue(n.msg_device_info.uint32_audio_play_cost,e.msg_device_info.uint32_audio_play_cost)/o):delete e.msg_device_info.uint32_audio_play_cost,a&&i.receiverStats.forEach(_=>{if(_.audio.concealedSamples&&_.audio.totalSamplesReceived){let S=a.receiverStats.find(O=>O.userId===_.userId);if(S&&S.audio.concealedSamples&&S.audio.totalSamplesReceived){let O=(_.audio.silentConcealedSamples||0)-(S.audio.silentConcealedSamples||0),K=_.audio.concealedSamples-S.audio.concealedSamples,G=_.audio.totalSamplesReceived-S.audio.totalSamplesReceived,Z=Math.floor((K-O)/G*1e3*o);if(Z>o*1e3/5){let _e=u.find(J=>J.msg_user_info.str_identifier===_.userId);_e&&(_e.msg_audio_status.uint32_audio_block_time=Z)}}}}),e}getStatsReport(r){return f(this,arguments,function*({uplinkConnection:i,downlinkConnections:e,freezeMap:t}){let o={msg_device_info:{},msg_up_stream_info:{msg_audio_status:{uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_level:0,uint32_audio_energy:0},msg_video_status:[],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}},msg_down_stream_info:[{msg_user_info:{str_identifier:"",uint64_tinyid:0},msg_audio_status:{uint32_audio_cache_ms:0,uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_total_bitrate:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_final_lost:0},msg_video_status:[{uint32_video_cache_ms:0,uint32_video_stream_type:0,uint32_video_receive_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_codec_bitrate:0,uint32_video_receive:0,uint32_video_origin_lost:0,uint32_video_block_time:0,uint32_video_dec_fps:0}],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}}]},n=yield this.getStats(i,e);return JSON.stringify(this._prevReport)==="{}"&&(this._prevReport=JSON.parse(JSON.stringify(o))),this.prepareReport({stats:n,report:o,freezeMap:t}),this._prevReportTime=Date.now(),o})}reset(){this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map}};var Up=$e(Ye());function Lp(s){let i={totalCost:0,local:0,redirect:0,httpCache:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let e=performance.getEntriesByType("resource").reverse();for(let t of e)if(t.name===s){let r=Math.round(t.duration),o=Math.max(Math.round(t.domainLookupStart-t.startTime),0),n=t.redirectStart>0?Math.max(Math.round(t.redirectEnd-t.redirectStart),0):0,a=t.fetchStart>0?Math.max(Math.round(t.domainLookupStart-t.fetchStart),0):0,c=Math.round(t.domainLookupEnd-t.domainLookupStart),l=Math.round(t.requestStart-t.secureConnectionStart),h=Math.round(t.secureConnectionStart-t.connectStart),u=Math.round(t.responseStart-t.requestStart),m=Math.round(t.responseEnd-(t.responseStart||t.startTime));i=L(N({},i),{totalCost:r,local:o,redirect:n,httpCache:a,dns:c,tcp:h,tls:l,request:u,response:m});break}}catch(e){}return i}function wp(s){return new Promise(i=>f(this,null,function*(){let e=setTimeout(()=>{i({totalCost:1e4,local:0,dns:0,tcp:0,tls:0,request:0,response:0})},1e4),t=Date.now(),r=`https://${s}/?t=${t}`;try{yield fetch(r)}catch(n){}clearTimeout(e);let o=Lp(r);o.totalCost===0&&(o.totalCost=Date.now()-t),i(o)}))}var dE=700,Yr=class Yr extends Up.default{constructor({signalChannel:e,room:t}){super();d(this,"_room");d(this,"_signalChannel");d(this,"_log");d(this,"uplinkRTT",0);d(this,"uplinkLoss",0);d(this,"downlinkRTT",0);d(this,"downlinkLoss",0);d(this,"pingResults",{});d(this,"_downlinkPrevStatMap",new Map);d(this,"_downlinkLossAndRTTMap",new Map);d(this,"_interval",-1);d(this,"_uplinkNetworkQuality",0);d(this,"_downlinkNetworkQuality",0);this._room=t,this._signalChannel=e,this._log=C.createLogger({id:"q",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this.initialize()}get uplinkNetworkQuality(){return this._uplinkNetworkQuality}set uplinkNetworkQuality(e){e!==this._uplinkNetworkQuality&&this._log.info(`uplink ${this.uplinkNetworkQuality} -> ${e}, rtt: ${this.uplinkRTT}, loss: ${this.uplinkLoss} ws-rtt: ${this._signalChannel.rtt}`),this._uplinkNetworkQuality=e}get downlinkNetworkQuality(){return this._downlinkNetworkQuality}set downlinkNetworkQuality(e){if(e!==this._downlinkNetworkQuality){let{rtt:t,loss:r}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._log.info(`downlink ${this.downlinkNetworkQuality} -> ${e}, rtt: ${t}, loss: ${r} ws-rtt: ${this._signalChannel.rtt}`)}this._downlinkNetworkQuality=e}initialize(){this._signalChannel.on(F.UPLINK_NETWORK_STATS,e=>{this.handleUplinkNetworkQuality(e)}),this._signalChannel.on(Ne.CONNECTION_STATE_CHANGED,this.handleSignalConnectionStateChange.bind(this)),this.start()}handleUplinkNetworkQuality(e){var c,l;if(e.data.code!==0)return;let t=e.data.data;if(t.delay&&this.updateDelay(t.delay),this._room.signalChannel&&t.wsRtt&&(this._room.signalChannel.rtt=t.wsRtt),!this._room.uplinkConnection){this.uplinkNetworkQuality=0,this.uplinkLoss=0,this.uplinkRTT=0;return}let r=(l=(c=this._room)==null?void 0:c.uplinkConnection)==null?void 0:l.getPeerConnection();if(r&&this.isPeerConnectionDisconnected(r)){this.uplinkNetworkQuality=6,this.uplinkLoss=0,this.uplinkRTT=0;return}let o=t.expectAudPkg+t.expectVidPkg,n=t.recvAudPkg+t.recvVidPkg,a=o-n;o===0&&n===0||(a<=0?this.uplinkLoss=0:this.uplinkLoss=Math.round(a/o*100),this.uplinkRTT=t.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this.uplinkLoss,this.uplinkRTT))}handleDownlinkNetworkQuality(){return f(this,null,function*(){if(this._room.remotePublishedUserMap.size===0){this.downlinkNetworkQuality=0;return}let e=[...this._room.remotePublishedUserMap.values()],t=e.filter(a=>{var c;return((c=a.getPeerConnection())==null?void 0:c.connectionState)===ge.CONNECTED});if(e.filter(a=>this.isPeerConnectionDisconnected(a.getPeerConnection())).length===e.length){this.downlinkNetworkQuality=6;return}for(let a=0;a<t.length;a++){let c=t[a].getPeerConnection();if(!c)return;let{rtt:l,totalPacketsLost:h,totalPacketsReceived:u}=yield this.getStat(c);if(!this._downlinkPrevStatMap.has(c)){this._downlinkPrevStatMap.set(c,{totalPacketsLost:h,totalPacketsReceived:u});continue}let m=0,g=this._downlinkPrevStatMap.get(c),D=h-g.totalPacketsLost,_=u-g.totalPacketsReceived;D<=0||_<0?m=0:m=Math.round(D/(D+_)*100),this._downlinkPrevStatMap.set(c,{totalPacketsLost:h,totalPacketsReceived:u}),this._downlinkLossAndRTTMap.set(c,{rtt:l,loss:m,userId:t[a].getUserId(),audioDelay:t[a].remoteAudioTrack.stat.end2EndDelay,videoDelay:t[a].remoteVideoTrack.stat.end2EndDelay})}if([...this._downlinkPrevStatMap.keys()].forEach(a=>{this.isPeerConnectionDisconnected(a)&&(this._downlinkPrevStatMap.delete(a),this._downlinkLossAndRTTMap.delete(a))}),this._downlinkLossAndRTTMap.size===0){this.downlinkRTT=0,this.downlinkLoss=0,this.downlinkNetworkQuality=0;return}let{rtt:o,loss:n}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this.downlinkRTT=o,this.downlinkLoss=n,this.downlinkNetworkQuality=this.getNetworkQuality(n,o)})}getStat(e){return f(this,null,function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!wr())return t;let r=e.getReceivers();try{for(let o=0;o<r.length;o++)(yield r[o].getStats()).forEach(c=>{c.type==="candidate-pair"&&q(c.currentRoundTripTime)&&(t.rtt=Math.round(c.currentRoundTripTime*1e3)),c.type==="inbound-rtp"&&(c.mediaType===p.AUDIO||c.mediaType===p.VIDEO)&&(t.totalPacketsLost+=c.packetsLost,t.totalPacketsReceived+=c.packetsReceived)});return t.rtt===0&&(t.rtt=this.uplinkRTT),t}catch(o){return t}})}getAverageLossAndRTT(e){let t={rtt:0,loss:0};return Array.isArray(e)&&e.length>0&&(e.forEach(r=>{t.rtt+=r.rtt,t.loss+=r.loss}),Object.keys(t).forEach(r=>{t[r]=Math.round(t[r]/e.length)})),t}getNetworkQuality(e,t){return e>50||t>500?5:e>30||t>350?4:e>20||t>200?3:e>10||t>100?2:e>=0||t>=0?1:0}handleSignalConnectionStateChange(e){e.state==="DISCONNECTED"?(this.uplinkRTT=0,this.uplinkLoss=0,this.uplinkNetworkQuality=6):e.state==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=5)}handleUplinkConnectionStateChange({state:e}){e==="DISCONNECTED"?(this.uplinkLoss=0,this.uplinkRTT=0,this.uplinkNetworkQuality=6):e==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=5)}isPeerConnectionDisconnected(e){return!!(e&&(e.connectionState===ge.DISCONNECTED||e.connectionState===ge.FAILED||e.connectionState===ge.CLOSED))}setUplinkConnection(e){this._room.uplinkConnection=e,this._room.uplinkConnection?this._room.uplinkConnection.on("connection-state-changed",this.handleUplinkConnectionStateChange.bind(this)):(this.uplinkNetworkQuality=0,this.uplinkRTT=0,this.uplinkLoss=0)}start(){if(this._interval!==-1){this._log.info("network quality calculating is already started");return}this._log.debug("start network quality calculating"),this._interval=oe.run("ric",()=>{var n;this.handleDownlinkNetworkQuality();let e=[...this._downlinkLossAndRTTMap.values()];E.emit(A.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this.uplinkRTT,loss:this.uplinkLoss},downlinks:e});let t=(n=this._room.scheduleResult.config)==null?void 0:n.pingDomainInfo,r={uplinkNetworkQuality:this.uplinkNetworkQuality,downlinkNetworkQuality:this.downlinkNetworkQuality,uplinkRTT:this.uplinkRTT,uplinkLoss:this.uplinkLoss,downlinkRTT:this.downlinkRTT,downlinkLoss:this.downlinkLoss};t&&(r=L(N({},r),{pingResults:this.uplinkRTT>t.rttThreshold||this.downlinkRTT>t.rttThreshold?this.pingResults:{}})),this.emit(Yr.EVENT_NETWORK_QUALITY,r);let o=Date.now();if(t&&(this.uplinkRTT>t.rttThreshold||this.downlinkRTT>t.rttThreshold)&&o-Yr.lastPingTime>t.interval*1e3){Yr.lastPingTime=Date.now();let a=t.domain.map(c=>wp(c).then(l=>({domain:c,cost:l.totalCost})));Promise.all(a).then(c=>{this.pingResults.isPoorNetwork=c.some(l=>l.cost>dE),this.pingResults.timestamp=o,this.pingResults.data=c,c.forEach(l=>{b.addSuccessEvent({key:521718,cost:l.cost})}),this._log.warn(`All ping results: ${JSON.stringify(c)}`)}).catch(c=>{this._log.warn(`Error during pinging domains: ${c}`)})}},{delay:2e3})}stop(){this._log.debug("stopped"),this._interval!==-1&&(oe.clearTask(this._interval),this._interval=-1),this._downlinkLossAndRTTMap.clear(),this._downlinkPrevStatMap.clear()}updateDelay(e){let{tinyIdToUserIdMap:t}=this._room;e.forEach(({srcTinyId:r,videoDelay:o,audioDelay:n})=>{let a=t.get(r);if(a){let c=this._room.remotePublishedUserMap.get(a);c==null||c.setDelay({videoDelay:o,audioDelay:n})}})}};d(Yr,"EVENT_NETWORK_QUALITY","0"),d(Yr,"lastPingTime",0);var Ys=Yr;function lE({fn:s,context:i}){return function(...e){try{let t=s.apply(i,e);return sr(t)?t.catch(r=>C.error(`${s.name}() error observed ${r}`)):t}catch(t){C.error(`${s.name}() error observed ${t}`)}}}var yc=class{constructor(i){d(this,"_frameWorkType");d(this,"_component");d(this,"_language");d(this,"connectionType");d(this,"_room");d(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0});d(this,"_keyPrefix");d(this,"_log");d(this,"_intervalId");d(this,"_firstPublishedUserList");d(this,"_networkQuality");d(this,"_basicInfo");d(this,"_pathJoinRoom");d(this,"_pathLeaveRoom");d(this,"_pathMainVideoMap");d(this,"_pathMainAudioMap");d(this,"_pathAuxiliaryMap");d(this,"_remoteStreamStatMap");d(this,"_localStreamStat");d(this,"_eventMap",new Map);d(this,"_captureCostSum",0);d(this,"_captureCostCount",0);d(this,"isDestroyed",!1);this._frameWorkType=i.frameWorkType||30,this._component=i.component||0,this.connectionType=i.connectionType||1,this._language=i.language||0,this._room=i.room,this._keyPrefix="key_point",this._log=C.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(e=>{e.startsWith("handle")&&ne(this[e])&&(this[e]=lE({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:Pe,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,Or().then(i=>{this._basicInfo.string_os_version=Pi(),i?this._basicInfo.string_device_name=i.mobile?i.model:this._basicInfo.string_os_version:this._basicInfo.string_device_name=this._basicInfo.string_os_version})}addEvent(i,e){return this._eventMap.set(i,e),E.on(i,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(A.JOIN_START,this.handleJoinStart).addEvent(A.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(A.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(A.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(A.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(A.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(A.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(A.JOIN_FAILED,this.handleJoinFailed).addEvent(A.LEAVE_START,this.handleLeaveStart).addEvent(A.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(A.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(A.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(A.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(A.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(A.PUBLISH_START,this.handlePublishStart).addEvent(A.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(A.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(A.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(A.PLAY_TRACK_START,this.handlePlayStart).addEvent(A.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(A.PLAYER_STATE_CHANGED,({track:i,state:e,type:t})=>{!i.isRemote||!this.hitTest(i.room)||e==="PLAYING"&&(t===p.AUDIO?this.handleAudioPlaying(i):this.handleVideoPlaying(i))}).addEvent(A.SWITCH_ROOM_START,this.handleSwitchRoomStart).addEvent(A.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess).addEvent(A.SWITCH_ROOM_FAILED,this.handleSwitchRoomFailed).addEvent(A.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(A.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(A.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(A.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{if(!this.hitTest(i))return;let r=e.hasAudio||e.hasVideo||e.hasSmall,o=e.hasAuxiliary,n=t.hasAudio||t.hasVideo||t.hasSmall,a=t.hasAuxiliary;!r&&n&&this.handleRemoteStreamAdded(t.userId,"main"),!o&&a&&this.handleRemoteStreamAdded(t.userId,"auxiliary")}).addEvent(A.SINGLE_CONNECTION_STAT,({room:i,stat:e})=>{this.hitTest(i)&&(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((i,e)=>E.off(e,i)),this._eventMap.clear()}destroy(){this.uninstallEvents(),oe.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(i){this.hitTest(i.room)&&(this._pathJoinRoom.uint64_start_time===0&&(this._pathJoinRoom.uint64_start_time=Date.now()),i.params&&(T(i.params.frameWorkType)||(this._frameWorkType=i.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),T(i.params.component)||(this._component=i.params.component,this._basicInfo.uint32_component=this._component),T(i.params.language)||(this._language=i.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleJoinScheduleSuccess({room:i,detailCost:e}){if(this.hitTest(i)&&e){let{totalCost:t,local:r,dns:o,tcp:n,tls:a,request:c,response:l}=e;this._pathJoinRoom.int32_schedule_cost=t,this._pathJoinRoom.int32_schedule_local=r,this._pathJoinRoom.int32_schedule_dns=o,this._pathJoinRoom.int32_schedule_tcp=n,this._pathJoinRoom.int32_schedule_tls=a,this._pathJoinRoom.int32_schedule_request=c,this._pathJoinRoom.int32_schedule_response=l}}handleSignalConnectionStart({room:i}){this.hitTest(i)&&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:i,error:e}){this.hitTest(i)&&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 y?Number(e.getExtraCode()||e.getCode()):I.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}handleJoinSendCMD(i){this.hitTest(i.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(i){this.hitTest(i.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=i.code,i.code!==0&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}handleJoinSuccess(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_end_time===0&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=i.room.getSignalInfo())}handleJoinFailed({room:i,error:e}){this.hitTest(i)&&(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(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_recv_userlist_time===0&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=i.publishedUserList||[])}handleSendFirstVideoFrame({room:i}){this.hitTest(i)&&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(i){this.hitTest(i.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(i){this.hitTest(i.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(i){this.hitTest(i.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(i){if(this.hitTest(i.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:i}){if(this.hitTest(i)&&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:i,error:e}){if(this.hitTest(i)){let t=Date.now();this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=t,this._pathJoinRoom.uint64_end_time=t,e&&(this._pathJoinRoom.int32_end_ret=e instanceof y?Number(e.getExtraCode()||e.getCode()):I.UNKNOWN)}}handleRemoteStreamAdded(i,e){var r;let t=`${i}_${e}`;if(!this._remoteStreamStatMap.has(t)){let o={userId:i,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:L(N({},uE),{msg_user_info:new fn({userId:i,tinyId:(r=this._room.remotePublishedUserMap.get(i))==null?void 0:r.tinyId,role:20})})};o.statsToReport.uint32_stream_type=e==="main"?2:7,this._remoteStreamStatMap.set(t,o)}}handleSubscribeStart({room:i,remotePublishedUser:e,streamType:t,subscribeState:r}){if(!this.hitTest(i))return;let{userId:o,tinyId:n,role:a}=e,c=new fn({userId:o,tinyId:n,role:a==="anchor"?20:21}),l=Date.now(),h=`${o}_${t}`,u=this._remoteStreamStatMap.get(h);u&&u.subscribeStartTime===0&&(u.subscribeStartTime=l),t==="main"?(e.muteState.hasVideo&&(r.video||r.smallVideo)&&!this._pathMainVideoMap.has(h)&&this._pathMainVideoMap.set(h,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:o,sendSubscribeCMDTime:l}),e.muteState.hasAudio&&r.audio&&!this._pathMainAudioMap.has(h)&&this._pathMainAudioMap.set(h,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:o,sendSubscribeCMDTime:l})):e.muteState.hasAuxiliary&&r.auxiliary&&!this._pathAuxiliaryMap.has(h)&&this._pathAuxiliaryMap.set(h,{sendSubscribeCMDTime:l})}handleSubscribed({room:i,remotePublishedUser:e,streamType:t}){if(this.hitTest(i)){let r=`${e.userId}_${t}`,o=this._remoteStreamStatMap.get(r);o&&o.subscribedTime===0&&(o.subscribedTime=Date.now())}}handlePlayStart({track:i}){if(!i.isRemote||!this.hitTest(i.room))return;let e=`${i.userId}_${i.streamType}`,t=this._remoteStreamStatMap.get(e);(t==null?void 0:t.playStreamTime)===0&&(t.playStreamTime=Date.now())}handleVideoLoadedData({track:i}){if(!i.isRemote||!this.hitTest(i.room))return;let e=`${i.userId}_${i.streamType}`,t=this._pathMainVideoMap.get(e);t&&t.statsToReport.uint64_combine_first_frame_time===0&&(t.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(i){let e=`${i.userId}_${i.streamType}`,t=Date.now(),r=this._pathMainVideoMap.get(e),o=this._remoteStreamStatMap.get(e);if(o){let{statsToReport:n}=o;if(!n.uint32_video_render_first&&i.streamType==="main"?this.hasVideoFlag(i.userId):this.hasAuxFlag(i.userId)){let a=t-this._pathJoinRoom.uint64_start_time;n.uint32_video_render_first=a,b.addNumber({key:516820,value:a})}}(r==null?void 0:r.statsToReport.uint64_render_first_frame_time)===0&&(r.statsToReport.uint64_render_first_frame_time=t)}handleAudioPlaying(i){let e=`${i.userId}_${i.streamType}`,t=this._pathMainAudioMap.get(e);t&&t.statsToReport.uint64_play_first_frame_time===0&&(t.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(i){this.hitTest(i.room)&&(this._networkQuality.totalUplinkLoss+=i.uplink.loss,this._networkQuality.totalUplinkRTT+=i.uplink.rtt,this._networkQuality.count++,i.downlinks.forEach(({rtt:e,loss:t,userId:r,videoDelay:o,audioDelay:n})=>{let a=this._networkQuality.totalDownlinkRTTAndLossMap.get(r);if(a)a.totalRTT+=e,a.totalLoss+=t,o&&(a.totalVideoDelay=(a.totalVideoDelay||0)+o,a.videoDelayCount=(a.videoDelayCount||0)+1),n&&(a.totalAudioDelay=(a.totalAudioDelay||0)+n,a.audioDelayCount=(a.audioDelayCount||0)+1),a.count++;else{let c,l,h,u;o&&(l=o,h=1),n&&(c=n,u=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(r,{totalRTT:e,totalLoss:t,count:1,totalAudioDelay:c,totalVideoDelay:l,audioDelayCount:u,videoDelayCount:h})}}))}handleHeartbeatStats(i){if(this.hitTest(i.room)){let{msg_device_info:e,msg_up_stream_info:t,msg_down_stream_info:r}=i.report;if(t.msg_video_status[0]){let{uint32_video_codec_bitrate:o,uint32_video_enc_fps:n,uint32_video_width:a,uint32_video_height:c}=t.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=o,this._localStreamStat.totalVideoFPS+=n,this._localStreamStat.totalVideoWidth+=a,this._localStreamStat.totalVideoHeight+=c,this._localStreamStat.videoCount++}if(t.msg_audio_status){let{uint32_audio_level:o}=t.msg_audio_status;Math.floor(o/At*100)>0&&(this._localStreamStat.totalAudioLevel+=o/At,this._localStreamStat.audioLevelCount++)}r.forEach(o=>{let{msg_user_info:n,msg_audio_status:a,msg_video_status:c}=o,l=n.str_identifier,h=this._room.remotePublishedUserMap.get(l);if(c.forEach(u=>{let m=u.uint32_video_stream_type===2,g=u.uint32_video_stream_type===7,D=`${l}_${m?"main":"auxiliary"}`,_=this._remoteStreamStatMap.get(D);if(_&&(m&&(h!=null&&h.remoteVideoTrack.isSubscribed)||g&&(h!=null&&h.remoteAuxiliaryTrack))){_.totalVideoFPS+=u.uint32_video_receive_fps,_.totalVideoBitrate+=u.uint32_video_codec_bitrate,_.videoCount++,_.statsToReport.uint32_video_width===0&&(_.statsToReport.uint32_video_width=u.uint32_video_width),_.statsToReport.uint32_video_height===0&&(_.statsToReport.uint32_video_height=u.uint32_video_height);let S=m?h.remoteVideoTrack:h.remoteAuxiliaryTrack;S.stat.jitterBufferDelay&&(_.videoJitterBufferDelay=S.stat.jitterBufferDelay),S.stat.framesReceived&&(_.statsToReport.uint32_video_consume_render_rate=Math.floor(S.stat.framesDecoded/S.stat.framesReceived*Zi(10,6)))}}),!as(a)){let u=`${l}_main`,m=this._remoteStreamStatMap.get(u);this._remoteStreamStatMap.has(u)&&m&&h!=null&&h.remoteAudioTrack.isSubscribed&&(m.totalAudioBitrate+=a.uint32_audio_codec_bitrate,m.audioCount++,h.remoteAudioTrack.stat.jitterBufferDelay&&(m.audioJitterBufferDelay=h.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(a.uint32_audio_level/At*100)>0&&(m.totalAudioLevel+=a.uint32_audio_level/At,m.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:i}){this.hitTest(i)&&this._localStreamStat.publishStartTime===0&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart({track:i}){i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess({track:i}){i.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()),i.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:i,error:e}){let r={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[e.name]||(e instanceof y?e.getExtraCode()||e.getCode():I.UNKNOWN);i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=r,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=r,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}hasVideoFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&tr)>=0}hasAudioFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&ir)>=0}hasAuxFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&Er)>=0}hitTest(i){return i===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 i=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),e=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=i<<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((i,e)=>{let{userId:t}=i,r=this._networkQuality.totalDownlinkRTTAndLossMap.get(t);if(r){let{totalLoss:h,count:u,audioDelayCount:m,videoDelayCount:g,totalAudioDelay:D,totalVideoDelay:_}=r;i.statsToReport.uint32_avg_down_loss=Math.floor(h/u),m&&D&&(i.statsToReport.uint32_audio_network_p2p_delay=Math.floor(D/m),i.audioJitterBufferDelay&&(i.statsToReport.uint32_p2p_delay=Math.floor(i.statsToReport.uint32_audio_network_p2p_delay+i.audioJitterBufferDelay))),g&&_&&(i.statsToReport.uint32_video_network_p2p_delay=Math.floor(_/g))}i.videoCount>0&&(i.statsToReport.uint32_video_avg_fps=Math.floor(i.totalVideoFPS/i.videoCount),i.statsToReport.uint32_video_avg_bitrate=Math.floor(i.totalVideoBitrate/i.videoCount)),i.audioCount>0&&(i.statsToReport.uint32_audio_recv_bitrate=i.statsToReport.uint32_audio_bitrate=Math.floor(i.totalAudioBitrate/i.audioCount)),i.audioLevelCount>0&&(i.statsToReport.uint32_audio_play_db=Math.floor(i.totalAudioLevel/i.audioLevelCount*100));let{callDurationCalculator:o}=this._room;o&&(i.statsToReport.uint32_audio_play_time=o.getDuration(e,p.AUDIO),i.statsToReport.uint32_video_play_time=o.getDuration(e,p.VIDEO)),i.statsToReport.uint32_video_render_first&&(i.statsToReport.uint32_video_render_first=Math.min(i.statsToReport.uint32_video_render_first,Zr));let{badCaseDetector:n}=this._room,{dataFreeze:a,count:c}=n.getDataFreezeDuration(e),{renderFreeze:l}=n.getRenderFreezeDuration(e);i.statsToReport.uint32_video_block_count=c,i.statsToReport.uint32_video_block_time=Math.min(a,i.statsToReport.uint32_video_play_time),i.statsToReport.uint32_video_external_block_time=Math.min(l,i.statsToReport.uint32_video_play_time),n.isBlackStream(e)&&i.statsToReport.uint32_video_avg_fps===0?i.statsToReport.uint32_video_black_screen_subjective=1:i.statsToReport.uint32_video_black_screen_subjective=0}),this._pathMainAudioMap.forEach((i,e)=>{if(!this.hasAudioFlag(i.userId)){this._pathMainAudioMap.delete(e);return}i.statsToReport.uint64_play_first_frame_time-i.statsToReport.uint64_start_enter_time>Zr&&(i.statsToReport.uint64_play_first_frame_time=i.statsToReport.uint64_start_enter_time+Zr)}),this._pathMainVideoMap.forEach((i,e)=>{if(!this.hasVideoFlag(i.userId)){this._pathMainVideoMap.delete(e);return}i.statsToReport.uint64_render_first_frame_time-i.statsToReport.uint64_start_enter_time>Zr&&(i.statsToReport.uint64_render_first_frame_time=i.statsToReport.uint64_start_enter_time+Zr)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>Zr&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+Zr)}getReportData(){this._basicInfo.uint32_networkType=Cr();let i={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new fn({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:cs(this._signalInfo.relayIp),uint32_client_ip:cs(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*Zi(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:cs(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,bytes_report_buf_from_0x1:this._signalInfo.endReportExtend};return mo(i),i}report(){return f(this,null,function*(){try{this.prepareReport();let i=this.getReportData();yield this.upload(i),this.initData()}catch(i){this._log.warn(i)}finally{this.isDestroyed&&(this._room=null)}})}upload(i){return f(this,null,function*(){if(i.msg_path_enter_room.uint64_start_time===0)return;let e=Number(this._room.sdkAppId),t=yield nd(i),r=t instanceof ArrayBuffer,o=`${yi(e,Ki.KEY_POINT)}&gzip=${+r}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(o,t));let a=[this.uploadKVStat(b),this.uploadKVStat(Lr)];n||a.push(Di({url:o,body:t,priority:"low"})),yield Promise.all(a)})}setConnectionType(i){this.connectionType=i,this._basicInfo.uint32_connection_type=i}uploadKVStat(i){return f(this,null,function*(){let e=i.getReportData();if(e.stats_count.length===0&&e.stats_distribution.length===0)return;e.msg_sdk_basic_info=L(N({},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 t=yield nd(e),r=`${yi(+this._room.sdkAppId,Ki.KV_STAT)}&gzip=${+(t instanceof ArrayBuffer)}`,o=!1;navigator.sendBeacon&&(o=navigator.sendBeacon(r,t)),o||Di({url:r,body:t})})}};v([pt({settings:{timeout:500,retries:3}})],yc.prototype,"upload",1);var Zr=5e3,uE={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},fn=class{constructor(i){d(this,"str_identifier");d(this,"str_tinyid");d(this,"uint32_role");this.str_identifier=String(i.userId),this.str_tinyid=String(i.tinyId||0),this.uint32_role=i.role}},Vp=yc;var Lu=class{constructor(){d(this,"_startTime");d(this,"_endTime");this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=U())}stop(){this._endTime===0&&(this._endTime=U())}getDuration(){return this._endTime===0?U()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},bc=Lu;var wu=class{constructor(i){d(this,"_room",null);d(this,"_durationMap");d(this,"_eventMap",new Map);this._room=i.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(A.REMOTE_TRACK_SUBSCRIBED,this.handleSubscribed).set(A.REMOTE_TRACK_UNSUBSCRIBED,this.handleUnsubscribed).set(A.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{var n;let{userId:r}=t;if(!this.hitTest(i))return;e.hasAudio&&!t.hasAudio&&this.stopDurationItem(`${r}_main`,p.AUDIO),e.hasVideo&&!t.hasVideo&&this.stopDurationItem(`${r}_main`,p.VIDEO),e.hasAuxiliary&&!t.hasAuxiliary&&this.stopDurationItem(`${r}_auxiliary`,p.VIDEO);let o=(n=this._room)==null?void 0:n.remotePublishedUserMap.get(r);o&&(!e.hasAudio&&t.hasAudio&&o.remoteAudioTrack.isSubscribed&&this.addDuractionItem(r,p.AUDIO,"main"),!e.hasVideo&&t.hasVideo&&o.remoteVideoTrack.isSubscribed&&this.addDuractionItem(r,p.VIDEO,"main"),!e.hasAuxiliary&&t.hasAuxiliary&&o.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(r,p.VIDEO,"auxiliary"))}),this._eventMap.forEach((i,e)=>E.on(e,i,this))}uninstallEvents(){this._eventMap.forEach((i,e)=>E.off(e,i,this)),this._eventMap.clear()}handleSubscribed({track:i}){if(!this.hitTest(i.room))return;let{userId:e,streamType:t,kind:r}=i;i.isSubscribed?this.addDuractionItem(e,r,t):this.stopDurationItem(`${e}_${t}`,r)}handleUnsubscribed({track:i}){this.hitTest(i.room)&&this.stopDurationItem(`${i.userId}_${i.streamType}`,i.kind)}isRecording(i){return i.findIndex(e=>e.endTime===0)>=0}addDuractionItem(i,e,t){let r=`${i}_${t}`,o=new bc,n=this._durationMap.get(r);n?this.isRecording(n[e])||n[e].push(o):this._durationMap.set(r,{userId:i,type:t,audio:e===p.AUDIO?[o]:[],video:e===p.AUDIO?[]:[o]})}stopDurationItem(i,e){if(this._durationMap.has(i)){let r=this._durationMap.get(i)[e].find(o=>o.endTime===0);r&&r.stop()}}hitTest(i){return this._room===i}getDuration(i,e){return this._durationMap.has(i)?this._durationMap.get(i)[e].reduce((r,o)=>r+o.getDuration(),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},Bp=wu;var Uu=class{constructor(i){d(this,"_room");d(this,"_renderFreezeMap",new Map);d(this,"_isVideoPlayingEventFiredMap",new Map);d(this,"_dataFreezeMap",new Map);d(this,"_monitorFreezeData",new Map);d(this,"_eventMap",new Map);this._room=i.room,this.installEvents()}getRenderFreezeMap(){return this._renderFreezeMap}getDataFreezeMap(){return this._dataFreezeMap}installEvents(){this._eventMap.set(A.LEAVE_SUCCESS,({room:i})=>{this.hitTest(i)&&this.stop()}).set(A.PLAY_TRACK_START,this.onPlayTrackStart).set(A.UNSUBSCRIBE_SUCCESS,({room:i,streamType:e,remotePublishedUser:t})=>{if(!this.hitTest(i))return;let{userId:r}=t,o=`${r}_${e}`;this.stopDataFreeze({key:o,userId:r,type:e})}).set(A.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{if(!this.hitTest(i))return;let{userId:r}=t;if(e.hasVideo&&!t.hasVideo){let o="main",n=`${t.userId}_${o}`;this.stopDataFreeze({key:n,userId:r,type:o})}if(e.hasAuxiliary&&!t.hasAuxiliary){let o="auxiliary",n=`${t.userId}_${o}`;this.stopDataFreeze({key:n,userId:r,type:o})}}).set(A.PLAYER_STATE_CHANGED,({track:i,state:e,reason:t,type:r})=>{if(!(!i.isRemote||!i.room||!this.hitTest(i.room)||r!==p.VIDEO)){if(e==="PLAYING"){let o=`${i.userId}_${i.streamType}`;this._isVideoPlayingEventFiredMap.set(o,!0)}t===p.MUTE?this.onVideoTrackMuted(i):t===p.UNMUTE&&this.onVideoTrackUnmuted(i)}}).set(A.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach((i,e)=>E.on(e,i,this))}uninstallEvents(){this._eventMap.forEach((i,e)=>E.off(e,i,this)),this._eventMap.clear()}stop(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}onVideoTrackMuted(i){if(!i.isSubscribed)return;let{userId:e,streamType:t}=i,r=`${e}_${t}`,o=this._dataFreezeMap.get(r),n=new bc;o?o.durationItemList.push(n):this._dataFreezeMap.set(r,{userId:e,type:t,durationItemList:[n],isFreezing(){let a=this.durationItemList[this.durationItemList.length-1];return a&&a.endTime===0}})}onVideoTrackUnmuted(i){if(!i.isSubscribed)return;let{userId:e,streamType:t}=i,r=`${e}_${t}`;this.stopDataFreeze({key:r,userId:e,type:t})}onHearBeatReport({room:i,report:e}){this.hitTest(i)&&e.msg_down_stream_info.forEach(t=>{let r=this._room.remotePublishedUserMap.get(t.msg_user_info.str_identifier);if(!r)return;let{userId:o,muteState:n}=r;t.msg_video_status.forEach(a=>{a.uint32_video_stream_type===2&&n.hasVideo&&!n.videoMuted&&r.remoteVideoTrack.isSubscribed&&this.handleRenderFreeze({userId:o,fps:a.uint32_video_dec_fps,type:"main"}),a.uint32_video_stream_type===7&&n.hasAuxiliary&&r.remoteAuxiliaryTrack.isSubscribed&&this.handleRenderFreeze({userId:o,fps:a.uint32_video_dec_fps,type:"auxiliary"})})})}stopDataFreeze({key:i,userId:e,type:t}){let r=this._dataFreezeMap.get(i);if(!r||!r.isFreezing())return;let o=r.durationItemList[r.durationItemList.length-1];o.stop();let n=o.getDuration();n>Mn?this._monitorFreezeData.set(i,{userId:e,type:t,duration:n}):r.durationItemList.pop()}getTotalDuration(i){return i.reduce((e,t)=>{let r=t.getDuration();return e+Math.min(r,5e3)},0)}handleRenderFreeze(r){return f(this,arguments,function*({userId:i,fps:e,type:t}){let o=`${i}_${t}`,n=this._renderFreezeMap.get(o);if(e<=2){let a=U();n&&!n.isFreeze&&(n.freezeTimeline.push({startTime:a,endTime:0}),n.isFreeze=!0),n||this._renderFreezeMap.set(o,{userId:i,type:t,isFreeze:!0,freezeTimeline:[{startTime:a,endTime:0}],renderFreezeTotal:0})}else if(n&&n.isFreeze){n.isFreeze=!1;let a=n.freezeTimeline.pop();if(a){a.endTime=U();let c=a.endTime-a.startTime;n.freezeTimeline.push(a),n.renderFreezeTotal+=Math.min(5e3,c)}}})}onPlayTrackStart({track:i}){if(!i.isRemote||!this.hitTest(i.room)||i.kind!==p.VIDEO||!i.isRemotePublished)return;let e=`${i.userId}_${i.streamType}`;this._isVideoPlayingEventFiredMap.has(e)||this._isVideoPlayingEventFiredMap.set(e,!1)}getDataFreezeDuration(i){let e={dataFreeze:0,count:0},t=this._dataFreezeMap.get(i);if(t){if(t.isFreezing()){let r=t.durationItemList[t.durationItemList.length-1];r.stop(),r.getDuration()<Mn&&t.durationItemList.pop()}e.dataFreeze=this.getTotalDuration(t.durationItemList),e.count=t.durationItemList.length}return e}getRenderFreezeDuration(i){let e=this._renderFreezeMap.get(i),t=0,r=0;if(e)if(!e.isFreeze)t=e.renderFreezeTotal;else{let o=U(),n=e.freezeTimeline[e.freezeTimeline.length-1],a=o-n.startTime;t=e.renderFreezeTotal+Math.min(a,5e3),r=e.freezeTimeline.length}return{renderFreeze:t,count:r}}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(i){return this._isVideoPlayingEventFiredMap.has(i)?!this._isVideoPlayingEventFiredMap.get(i):!1}resetMonitor(){this._monitorFreezeData.clear()}hitTest(i){return i===this._room}destroy(){this.uninstallEvents()}},Fp=Uu;var Hp=$e(Ye(),1);var hE=[1,0,0,0,1,1,0,1],Nc=class extends it{constructor(e,t,r,o){super(e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"transform",logger:t});d(this,"mirror",!1);d(this,"rotation",0);if(r&&(this.mirror=r),o&&(this.rotation=o),e instanceof ke)try{this.setTexBuffer(hE)}catch(n){e.destroy(new y({code:I.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${n.message||n}`}))}}draw2d(e,t,r,o,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(o,0),this.ctx2d.rotate(Math.PI/2),this.ctx2d.scale(n/o,o/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/o,o/n));let a=super.draw2d(e,t,r,o,n);return this.ctx2d.restore(),a}return!1}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}};var Vu=class{constructor(i,e){this.node=i;this.layout=e;d(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}},_n=class extends it{constructor(e,t){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,matchInputSize:!1,logger:t});d(this,"inputs",[])}addInput(e,t){if(this.inputs[t.zIndex])throw new Error("input already exists");let r=new Vu(e,t);this.inputs[t.zIndex]=r}changeInputLayout(e,t){let r=this.inputs.findIndex(o=>o?o.node===e:!1);r<0||Object.entries(t).forEach(([o,n])=>{T(n)||(this.inputs[r].layout[o]=n)})}resize(e,t){if(!this.matchInputSize){super.resize(e,t);return}let r=this.inputs.reduce((o,n)=>n?Object.assign(o,{width:Math.max(o.width,n.right),height:Math.max(o.height,n.bottom)}):o,{width:0,height:0});super.resize(r.width,r.height),this.context instanceof ke&&this.inputs.forEach(o=>{if(o){let n=this.layout2texCoords(o);o.positionBuffer?this.changeBufferData(o.positionBuffer,n):o.positionBuffer=this.createBuffer(n)}})}connect(e,...t){return super.connect(e,...t),this.matchInputSize&&this.resize(0,0),e}removeInput(e){this.inputs[this.inputs.findIndex(t=>(t==null?void 0:t.node)===e)]=void 0}render(e){let t=this.context.ctx;if(t.clearColor(0,0,0,0),this.inputs.reduce((o,n)=>(n==null?void 0:n.node.requestFrame(e))||o,!1)&&t){this.useProgram(),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let o=0;o<this.inputs.length;o++){let n=this.inputs[o];n&&(n.node.useTexture(),this.draw(n.positionBuffer))}return!0}return!1}render2d(e){if(this.inputs.reduce((r,o)=>(o==null?void 0:o.node.requestFrame(e))||r,!1)&&this.ctx2d){this.ctx2d.fillStyle="black",this.ctx2d.fillRect(0,0,this.width,this.height);for(let r=0;r<this.inputs.length;r++){let o=this.inputs[r];o&&this.draw2d(o.node.image,o.x,o.y,o.width,o.height)}return!0}return!1}getInfo(){let{totalFrames:e,x:t,y:r,width:o,height:n,name:a}=this,c=Date.now(),l=(e-this.lastInfo.totalFrames)/((c-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:r,width:o,height:n,timestamp:c,fps:l,name:a},N({parent:this.inputs.filter(h=>h).map(h=>h.node.getInfo())},this.lastInfo)}close(){super.close(),this.inputs.forEach(e=>{var t,r;if(e&&((t=e.node)==null||t.disconnect(),e.positionBuffer&&this.context instanceof ke))try{(r=this.context.ctx)==null||r.deleteBuffer(e.positionBuffer)}catch(o){}})}};var vc=class{constructor(i,e,t,r=4/3){this.vbMode=i;this.faceDetector=e;this.logger=t;d(this,"animationState");d(this,"originalAspect");d(this,"totalOffsetX",0);d(this,"totalOffsetY",0);d(this,"defaultScaleRatio",.1);d(this,"isRecovering",!1);d(this,"boundaryY",280);d(this,"lastActionTime",0);d(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=r||4/3}addEvent(i,e,t){let o=[{key:570704,error:t!=null?t:e?void 0:11},{key:570705,error:t!=null?t:e?void 0:22}][i-1];o&&(e?b.addSuccessEvent({key:o.key}):b.addFailedEvent({key:o.key,error:o.error}))}actionCentering(i){let e=Date.now();if(this.animation(),!this.faceDetector||e-this.lastActionTime<this.restTime||this.animationState.animating)return;let{videoWidth:t,videoHeight:r}=i;this.animationState.debounceThreshold=t/30,this.animationState.movementThreshold=t/20;try{let o=this.faceDetector.detectForVideo(i,Date.now());if(o.detections.length<=0){this.recoverOriginal(t,r);return}let n=o.detections[0].boundingBox,a=n.originX,c=n.originY,l=n.width,h=n.height;this.vbMode===1?this.dualStageCropping(t,r,a,c,l,h):this.vbMode===2&&this.movingPortrait(t,r,a,c,l,h)}catch(o){this.logger.error(o)}this.lastActionTime=e}calculateBoundary(i,e,t,r){let o,n;return i>e/2?(o=e-t-r,n=t-o):(o=t,n=0),{min:o,offset:n}}calculateTargetPosition(i,e,t,r,o,n,a=.4){let c=i+t/2,l=e+r/2,h,u,{min:m,offset:g}=this.calculateBoundary(c,o,i,t),{min:D,offset:_}=this.calculateBoundary(l,n,e,r);return h=2*m+t,u=2*D+r,h/u>this.originalAspect?(h=u*this.originalAspect,g=c-h/2):(u=h/this.originalAspect,_=l-u/2),t/o>a&&(g=0,_=0,h=o,u=n),g=Math.max(0,Math.min(g,o-h)),_=Math.max(0,Math.min(_,n-u)),{sx:g,sy:_,cropWidth:h,cropHeight:u,timestamp:Date.now()}}processFacePositionCrop(i,e,t){if(!this.animationState.current||!this.animationState.target){let a={sx:0,sy:0,cropWidth:e,cropHeight:t,timestamp:Date.now()};this.animationState.current=a,this.animationState.target=a;return}let r=this.positionDistance(this.animationState.target,i),o=this.positionDistance(this.animationState.current,i),n=this.animationState.current.cropWidth/e;r>this.animationState.debounceThreshold*n&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&o>this.animationState.movementThreshold*n&&(this.animationState.target=i,this.animationState.debounceTimer=setTimeout(()=>{this.animationState.startTime=Date.now(),this.animationState.animating=!0},this.animationState.debounceTime))}processFacePositionPortrait(i){if(!this.animationState.current||!this.animationState.target){this.animationState.current=N({},i),this.animationState.target=N({},i);return}let e=this.positionDistance(this.animationState.current,i),t=this.positionDistance(this.animationState.target,i);e>this.animationState.debounceThreshold&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&t>this.animationState.movementThreshold&&(this.animationState.current=i,this.animationState.debounceTimer=setTimeout(()=>{this.animationState.startTime=Date.now(),this.animationState.animating=!0},this.animationState.debounceTime))}animation(){if(!this.animationState.animating)return;let i=Date.now()-this.animationState.startTime,e=Math.min(i/this.animationState.duration,1),t=r=>r<.5?2*r*r:-1+(4-2*r)*r;if(this.animationState.current&&this.animationState.target){let r=(this.animationState.target.sx-this.animationState.current.sx)*t(e);this.animationState.current.sx+=r,this.totalOffsetX+=r;let o=(this.animationState.target.sy-this.animationState.current.sy)*t(e);if(this.animationState.current.sy+=o,this.totalOffsetY+=o,this.animationState.current.cropWidth+=(this.animationState.target.cropWidth-this.animationState.current.cropWidth)*t(e),this.animationState.current.cropHeight+=(this.animationState.target.cropHeight-this.animationState.current.cropHeight)*t(e),this.animationState.current.scaleRatio&&this.animationState.target.scaleRatio&&(this.animationState.current.scaleRatio+=(this.animationState.target.scaleRatio-this.animationState.current.scaleRatio)*t(e)),q(this.animationState.current.scaleOffsetX)&&q(this.animationState.target.scaleOffsetX)&&q(this.animationState.current.scaleOffsetY)&&q(this.animationState.target.scaleOffsetY)){let n=(this.animationState.target.scaleOffsetX-this.animationState.current.scaleOffsetX)*t(e);this.animationState.current.scaleOffsetX+=n;let a=(this.animationState.target.scaleOffsetY-this.animationState.current.scaleOffsetY)*t(e);this.animationState.current.scaleOffsetY+=a}}e>=1&&(this.animationState.animating=!1,this.animationState.current=this.animationState.target,this.isRecovering=!1)}positionDistance(i,e){return Math.sqrt(Zi(i.sx-e.sx,2)+Zi(i.sy-e.sy,2))}recoverOriginal(i,e){this.animationState.target={sx:0,sy:0,cropWidth:i,cropHeight:e,timestamp:Date.now()},this.animationState.animating=!0,this.animationState.startTime=Date.now(),this.isRecovering=!0}dualStageCropping(i,e,t,r,o,n,a=.3){if(this.isRecovering)return;let c=this.calculateTargetPosition(t,r,o,n,i,e);this.processFacePositionCrop(c,i,e),o*n/c.cropWidth/c.cropHeight>a&&this.recoverOriginal(i,e)}movingPortrait(i,e,t,r,o,n){var c,l,h,u,m,g,D,_,S,O,K,G;let a={sx:t+o/2+this.totalOffsetX,sy:r+n/2+this.totalOffsetY,cropWidth:i,cropHeight:e,scaleRatio:(l=(c=this.animationState.current)==null?void 0:c.scaleRatio)!=null?l:1,scaleOffsetX:(u=(h=this.animationState.current)==null?void 0:h.scaleOffsetX)!=null?u:0,scaleOffsetY:(g=(m=this.animationState.current)==null?void 0:m.scaleOffsetY)!=null?g:0,timestamp:Date.now()};this.animationState.target={sx:i/2,sy:r+n/2,cropWidth:i,cropHeight:e,scaleRatio:(_=(D=this.animationState.target)==null?void 0:D.scaleRatio)!=null?_:1,scaleOffsetX:(O=(S=this.animationState.target)==null?void 0:S.scaleOffsetX)!=null?O:0,scaleOffsetY:(G=(K=this.animationState.target)==null?void 0:K.scaleOffsetY)!=null?G:0,timestamp:Date.now()},this.animationState.animating||(this.animationState.target.scaleRatio=Math.sqrt(o*n/i/e/this.defaultScaleRatio),this.animationState.target.scaleOffsetX=-this.animationState.target.scaleRatio/2+.5,this.animationState.target.scaleOffsetY=-this.animationState.target.scaleRatio+1,(this.animationState.target.sy-this.animationState.target.scaleOffsetY*this.animationState.target.cropHeight)/this.animationState.target.scaleRatio<this.boundaryY&&(this.animationState.target.scaleOffsetY=(this.animationState.target.sy-this.boundaryY*this.animationState.target.scaleRatio)/this.animationState.target.cropHeight)),this.processFacePositionPortrait(a)}set aspectRatio(i){this.originalAspect=i}get current(){return this.animationState.current}get offset(){return{offsetX:this.totalOffsetX,offsetY:this.totalOffsetY}}get targetCrop(){return this.animationState.target}};var mE=`#version 300 es
|
|
69
|
+
`),e}removeBandwidthRestriction(e){return e.replace(/b=AS:.*\r\n/,"").replace(/b=TIAS:.*\r\n/,"")}removeVideoOrientation(e){return e.replace(/urn:3gpp:video-orientation/,"")}connect(){return f(this,null,function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(e){throw this.closePeerConnection(!0),this.uninstallEvents(),e}})}exchangeSDP(){return f(this,null,function*(){try{yield this.createOffer(),this._log.info("createOffer success, sending offer to remote server"),yield this.doExchangeSDP()}catch(e){throw e}})}createOffer(){return f(this,null,function*(){try{let e=yield this._peerConnection.createOffer(xp);yield this.setOffer(e),e.sdp&&this.updateSSRC(e.sdp)}catch(e){throw e}})}doExchangeSDP(){let e={command:Y.PUBLISH,responseCommand:F.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof ut||this.localAuxVideoTrack instanceof ut,state:this.publishState,constraintConfig:this._mediaSettings},enableLog:!1};return this._log.debug(`sending sdp offer: ${e.data.sdp}`),this._signalChannel.sendWaitForResponse(e).then(t=>{let{code:r,message:o,data:n}=t.data;return r===0?this.acceptAnswer(n):this.checkPublishResultCode(r,o)})}setSDPDirection(e,t,r="all"){let o=ye(e);return o.media.forEach(n=>{(r==="all"||n.type===r)&&(n.direction=t)}),Nt(o)}acceptAnswer(e){return f(this,null,function*(){var t,r,o,n,a;try{let c;if(this._publishingLocalAudioTrack||this._publishingLocalVideoTrack||this.isMainStreamPublished){let u=((t=this._publishingLocalVideoTrack)==null?void 0:t.profile.bitrate)||((r=this.localMainVideoTrack)==null?void 0:r.profile.bitrate),m=((o=this._publishingLocalAudioTrack)==null?void 0:o.profile.bitrate)||((n=this.localMainAudioTrack)==null?void 0:n.profile.bitrate);if(u){let g=this._isPublishingAux?p.AUXILIARY:p.BIG;c=yield this.setBandwidth({bandwidth:u,type:p.VIDEO,sdp:c,videoType:g})}m&&(c=yield this.setBandwidth({bandwidth:m,type:p.AUDIO,sdp:c}))}if(c=this.removeVideoOrientation(e.sdp),(a=this._publishingLocalVideoTrack)!=null&&a.small){let{smallStreamConfig:u}=this._room;c=yield this.setBandwidth({bandwidth:this._publishingLocalVideoTrack.small.bitrate||u.bitrate,type:p.VIDEO,videoType:p.SMALL,sdp:c})}let h={type:e.type,sdp:c};yield this.setAnswer(h),this._log.debug(`accepted answer: ${c}`)}catch(c){throw this._log.error(`failed to accept remote answer ${c}`),c}})}sendMutedFlag(e){var o,n,a;if(e===this.localAuxAudioTrack||e===this.localAuxVideoTrack)return;let r={audio:!!((o=this.localMainAudioTrack)!=null&&o.muted),bigVideo:!!((n=this.localMainVideoTrack)!=null&&n.muted),auxVideo:!!((a=this.localAuxVideoTrack)!=null&&a.muted)};this._log.info(`send muted state: ${JSON.stringify(r)}`),this._signalChannel.send(Y.UPDATE_MUTE_STAT,r)}getIsReconnecting(){return this._isReconnecting}reconnect(){return f(this,null,function*(){if(!(He(Qs.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:Y.UNPUBLISH,responseCommand:F.UNPUBLISH_RESULT,enableLog:!1}),this.closePeerConnection(),this.initialize(),this.isMainStreamPublished&&(yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0})),this._log.warn("reconnect() uplink reconnect successfully"),this.stopReconnection()}catch(t){let r=Pt(this._reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${r/1e3}s`),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},r)}})}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&E.emit(A.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{ye(e).media.forEach((r,o)=>{if(r.type===p.AUDIO){let n=r.ssrcs&&r.ssrcs[0];n&&(this.ssrc.audio=Number(n.id))}else{if(this._sdpSemantics===rs&&r.ssrcGroups){r.ssrcGroups.forEach((a,c)=>{let l=Number(a.ssrcs.split(" ")[0]);c===0?this.ssrc.video=l:c===1&&(this.ssrc.small=l)});return}let n=r.ssrcs&&r.ssrcs[0];if(!n)return;switch(o){case 1:this.ssrc.video=Number(n.id);break;case 2:this.ssrc.small=Number(n.id);break;case 3:this.ssrc.auxiliary=Number(n.id);break;default:break}}})}catch(t){}}getVideoTrackId(e=p.VIDEO){if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===p.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===p.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===p.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===p.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===Sr?(this._log.error(Ve.NOT_SUPPORTED_H264ENCODE),new y({code:I.NOT_SUPPORTED_H264,message:x({key:P.NOT_SUPPORTED_H264ENCODE})})):new y({code:I.UNKNOWN,message:x({key:P.SIGNAL_RESPONSE_FAILED,data:{signalResponse:F.PUBLISH_RESULT,code:e,message:t}})})}};v([Q(e=>function(...t){return new Promise((r,o)=>{let n=a=>{this._emitter.off("closed",n),o(new y({code:I.API_CALL_ABORTED,message:x({key:P.CONNECTION_ABORTED,data:a})}))};this._emitter.on("closed",n),e.apply(this,t).then(r,o).finally(()=>{this._emitter.off("closed",n)})})})],Qs.prototype,"publish",1),v([lt(521715,!1)],Qs.prototype,"unpublish",1),v([et(rt.prototype.afterConnect),Ma(rt.prototype.beforeConnect)],Qs.prototype,"connect",1);var xu=Qs,mn=xu;var pn=class{constructor(i,e){this.room=i;d(this,"_log");d(this,"_prevReportTime",0);d(this,"_prevReport",{});d(this,"_prevStats",null);d(this,"_prevEncoderImplementation","");d(this,"_prevAuxEncoderImpl","");d(this,"_prevQualityLimitationReason","");d(this,"_prevAuxQualityLimitationReason","");d(this,"_prevDecoderImplementationMap",new Map);d(this,"totalBytesSent",0);d(this,"totalBytesReceived",0);d(this,"_spcStats",null);this._log=e}get statInterval(){return this._prevReportTime===0?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(i){return f(this,null,function*(){var o;let e={audio:{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0},video:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},small:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},auxiliary:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},rtt:0},t=i.getPeerConnection(),r=i.getSSRC();if(t)try{if((this._spcStats||(yield t.getStats())).forEach(a=>{var h,u,m;let c,l;if(a.type==="outbound-rtp")if((a.mediaType||a.kind)===p.VIDEO){if(a.ssrc===r.video?(c=p.VIDEO,l=i.localMainVideoTrack):a.ssrc===r.small?c=p.SMALL:a.ssrc===r.auxiliary&&(l=i.localAuxVideoTrack,c=p.AUXILIARY),!c)return;if(e[c].bytesSent=a.bytesSent,e[c].packetsSent=a.packetsSent,e[c].framesEncoded=a.framesEncoded,T(a.keyFramesEncoded)||(e[c].keyFramesEncoded=a.keyFramesEncoded),T(a.nackCount)||(e[c].nackCount=a.nackCount),T(a.pliCount)||(e[c].pliCount=a.pliCount),T(a.retransmittedPacketsSent)||(e[c].retransmittedPacketsSent=a.retransmittedPacketsSent),T(a.totalEncodeTime)||(e[c].totalEncodeTime=a.totalEncodeTime),T(a.totalPacketSendDelay)||(e[c].totalPacketSendDelay=a.totalPacketSendDelay),!T(a.encoderImplementation)&&(c===p.VIDEO&&this._prevEncoderImplementation!==a.encoderImplementation||c===p.AUXILIARY&&this._prevAuxEncoderImpl!==a.encoderImplementation)){let D=2,_=this._prevEncoderImplementation;c===p.AUXILIARY&&(D=7,_=this._prevAuxEncoderImpl),E.emit("262",{userId:i.userId,streamType:D,prevImplementation:_,implementation:a.encoderImplementation,codec:i.videoCodec,isHWCodec:a.powerEfficientEncoder}),this[c===p.VIDEO?"_prevEncoderImplementation":"_prevAuxEncoderImpl"]=a.encoderImplementation,this._log.info(`${c===p.AUXILIARY?"aux ":""}encoderImplementation change to ${a.encoderImplementation}(${i.videoCodec}) HWEncoder: ${a.powerEfficientEncoder}`)}a.ssrc===r.video?!T(a.qualityLimitationReason)&&a.bytesSent!==0&&this._prevQualityLimitationReason!==a.qualityLimitationReason&&(this._log.info(`qualityLimitationReason change to ${a.qualityLimitationReason}`),E.emit("263",{userId:i.userId,reason:a.qualityLimitationReason,prevReason:this._prevQualityLimitationReason,streamType:2,isQosClearFirst:(h=i.localMainVideoTrack)==null?void 0:h.isQosClearFirst}),this._prevQualityLimitationReason=a.qualityLimitationReason):a.ssrc===r.auxiliary&&!T(a.qualityLimitationReason)&&a.bytesSent!==0&&this._prevAuxQualityLimitationReason!==a.qualityLimitationReason&&(this._log.info(`aux qualityLimitationReason change to ${a.qualityLimitationReason}`),E.emit("263",{userId:i.userId,reason:a.qualityLimitationReason,prevReason:this._prevAuxQualityLimitationReason,streamType:7,isQosClearFirst:(u=i.localAuxVideoTrack)==null?void 0:u.isQosClearFirst}),this._prevAuxQualityLimitationReason=a.qualityLimitationReason)}else e.audio.bytesSent=a.bytesSent,e.audio.packetsSent=a.packetsSent;else a.type==="candidate-pair"?cr(a)&&(this.totalBytesSent=a.bytesSent,q(a.currentRoundTripTime)&&(e.rtt=Math.floor(a.currentRoundTripTime*1e3))):a.type==="media-source"&&(a.kind===p.AUDIO?(e.audio.audioLevel=a.audioLevel||0,e.audio.totalAudioEnergy=a.totalAudioEnergy||0,a.echoReturnLoss,a.totalSamplesDuration&&(e.audio.totalSamplesDuration=a.totalSamplesDuration)):a.kind===p.VIDEO&&(a.trackIdentifier===i.getVideoTrackId(p.VIDEO)?e.video.fpsCapture=a.framesPerSecond:a.trackIdentifier===i.getVideoTrackId(p.AUXILIARY)?e.auxiliary.fpsCapture=a.framesPerSecond:e.small.fpsCapture=a.framesPerSecond));if(!T(a.audioLevel)&&((m=i.localMainAudioTrack)!=null&&m.mediaTrack)&&a.trackIdentifier===i.localMainAudioTrack.mediaTrack.id&&(e.audio.audioLevel=a.audioLevel||0),!T(a.frameWidth)){let g=p.SMALL;a.trackIdentifier===i.getVideoTrackId(p.VIDEO)||a.ssrc===r.video?g=p.VIDEO:(a.trackIdentifier===i.getVideoTrackId(p.AUXILIARY)||a.ssrc===r.auxiliary)&&(g=p.AUXILIARY),e[g].frameWidth=a.frameWidth,e[g].frameHeight=a.frameHeight,e[g].framesSent=a.framesSent}}),i.localMainAudioTrack){let a=i.localMainAudioTrack.getInternalAudioLevel();e.audio.micAudioLevel=a,e.audio.audioLevel===0&&(e.audio.audioLevel=a)}this.totalBytesSent||(this.totalBytesSent+=e.audio.bytesSent+e.video.bytesSent+e.auxiliary.bytesSent),Object.keys(e).forEach(a=>{a===p.AUDIO?(i.localMainAudioTrack&&(i.localMainAudioTrack.stat=e[a]),i.localAuxAudioTrack&&(i.localAuxAudioTrack.stat=e[a])):a===p.VIDEO?i.localMainVideoTrack&&(i.localMainVideoTrack.stat=e[a]):a===p.AUXILIARY&&i.localAuxVideoTrack&&(i.localAuxVideoTrack.stat=e[a])})}catch(n){this._log.warn(`failed to getStats on sender connection ${n}`)}return e.rtt===0&&(e.rtt=((o=this.room.networkQuality)==null?void 0:o.uplinkRTT)||0),e})}getReceiverStats(i){return f(this,null,function*(){var r,o,n;let e={tinyId:i.tinyId,userId:i.userId,rtt:0,hasAudio:!1,hasVideo:!1,hasAuxiliary:!1,isSmallSubscribed:!1,audio:{bytesReceived:0,packetsReceived:0,packetsLost:0,p2pDelay:0,totalJitter:0,totalJitterCount:0,audioLevel:0,totalAudioEnergy:0,insertedSamplesForDeceleration:0,removedSamplesForAcceleration:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,freezeCount:0,totalFreezesDuration:0,totalJitter:0,totalJitterCount:0,p2pDelay:0},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,totalJitter:0,totalJitterCount:0,p2pDelay:0}},t=i.getPeerConnection();if(t)try{let{ssrc:a}=i,{muteState:c,subscribeState:l}=i;(this._spcStats||(yield t.getStats())).forEach(u=>{if(u.type==="inbound-rtp"){let m=(u.mediaType||u.kind)===p.AUDIO;if(m){if(u.ssrc!==a.audio||!c.hasAudio)return;e.audio.packetsReceived=u.packetsReceived,e.audio.bytesReceived=u.bytesReceived,e.audio.packetsLost=u.packetsLost,u.insertedSamplesForDeceleration&&(e.audio.insertedSamplesForDeceleration=u.insertedSamplesForDeceleration),u.removedSamplesForAcceleration&&(e.audio.removedSamplesForAcceleration=u.removedSamplesForAcceleration),u.totalSamplesDuration&&(e.audio.totalSamplesDuration=u.totalSamplesDuration),u.totalSamplesReceived&&(e.audio.totalSamplesReceived=u.totalSamplesReceived),u.concealedSamples&&(e.audio.concealedSamples=u.concealedSamples),u.silentConcealedSamples&&(e.audio.silentConcealedSamples=u.silentConcealedSamples);let{remoteAudioTrack:g}=i;g.stat.packetsReceived=u.packetsReceived,g.stat.bytesReceived=u.bytesReceived,g.stat.packetsLost=u.packetsLost,e.audio.p2pDelay=g.stat.end2EndDelay,e.hasAudio=!0}else{if(ae&&u.bytesReceived===0)return;let g;u.ssrc===a.video&&c.hasVideo&&(e.video.packetsReceived=u.packetsReceived,e.video.bytesReceived=u.bytesReceived,e.video.packetsLost=u.packetsLost,e.video.framesReceived=u.framesReceived,e.video.framesDecoded=u.framesDecoded,e.video.fpsDecoded=u.framesPerSecond,e.hasVideo=!0,g=i.remoteVideoTrack,c.hasSmall&&l.smallVideo&&(e.isSmallSubscribed=!0),u.decoderImplementation&&(!this._prevDecoderImplementationMap.has(e.userId)||this._prevDecoderImplementationMap.get(e.userId)!==u.decoderImplementation)&&(this._log.info(`${e.userId} decoderImplementation change to ${u.decoderImplementation} HWDecoder: ${u.powerEfficientDecoder}`),E.emit("262",{userId:this.room.userId,remoteUserId:e.userId,prevImplementation:this._prevDecoderImplementationMap.get(e.userId),implementation:u.decoderImplementation,codec:i.videoCodec,isHWCodec:u.powerEfficientDecoder}),this._prevDecoderImplementationMap.set(e.userId,u.decoderImplementation))),u.ssrc===a.auxiliary&&c.hasAuxiliary&&(e.auxiliary.packetsReceived=u.packetsReceived,e.auxiliary.bytesReceived=u.bytesReceived,e.auxiliary.packetsLost=u.packetsLost,e.auxiliary.framesReceived=u.framesReceived,e.auxiliary.framesDecoded=u.framesDecoded,e.auxiliary.fpsDecoded=u.framesPerSecond,g=i.remoteAuxiliaryTrack,e.auxiliary.p2pDelay=g.stat.end2EndDelay,e.hasAuxiliary=!0),g&&(g.stat.packetsReceived=u.packetsReceived,g.stat.bytesReceived=u.bytesReceived,g.stat.packetsLost=u.packetsLost,g.stat.framesReceived=u.framesReceived,g.stat.framesDecoded=u.framesDecoded,u.jitterBufferDelay&&(g.stat.jitterBufferDelay=Math.floor(u.jitterBufferDelay/u.jitterBufferEmittedCount*1e3)),e.video.p2pDelay=g.stat.end2EndDelay)}u.jitterBufferDelay&&(m?(e.audio.totalJitter=u.jitterBufferDelay,e.audio.totalJitterCount=u.jitterBufferEmittedCount):u.ssrc===a.video&&c.hasVideo?(e.video.totalJitter=u.jitterBufferDelay,e.video.totalJitterCount=u.jitterBufferEmittedCount):u.ssrc===a.auxiliary&&c.hasAuxiliary&&(e.auxiliary.totalJitter=u.jitterBufferDelay,e.auxiliary.totalJitterCount=u.jitterBufferEmittedCount))}else u.type==="candidate-pair"&&cr(u)&&(this.totalBytesReceived=u.bytesReceived,q(u.currentRoundTripTime)&&(e.rtt=Math.floor(u.currentRoundTripTime*1e3)));T(u.frameWidth)||((u.trackIdentifier===i.getMainStreamVideoTrackId()||u.ssrc===a.video)&&(e.video.frameWidth=u.frameWidth,e.video.frameHeight=u.frameHeight,i.remoteVideoTrack.stat.frameWidth=u.frameWidth,i.remoteVideoTrack.stat.frameHeight=u.frameHeight),(u.trackIdentifier===i.getAuxStreamVideoTrackId()||u.ssrc===a.auxiliary)&&(e.auxiliary.frameWidth=u.frameWidth,e.auxiliary.frameHeight=u.frameHeight,i.remoteAuxiliaryTrack.stat.frameWidth=u.frameWidth,i.remoteAuxiliaryTrack.stat.frameHeight=u.frameHeight)),!T(u.audioLevel)&&i.muteState.audioAvailable&&i.remoteAudioTrack.mediaTrack&&u.trackIdentifier===i.remoteAudioTrack.mediaTrack.id&&(e.audio.audioLevel=u.audioLevel||0,e.audio.totalAudioEnergy=u.totalAudioEnergy||0)}),e.audio.audioLevel===0&&i.muteState.audioAvailable&&(e.audio.audioLevel=i.remoteAudioTrack.getInternalAudioLevel()||0),this.totalBytesReceived||(this.totalBytesReceived+=e.audio.bytesReceived+e.video.bytesReceived+e.auxiliary.bytesReceived),T((r=i.remoteVideoTrack.player.stat)==null?void 0:r.fps)||(e.video.fpsRender=i.remoteVideoTrack.player.stat.fps),T((o=i.remoteAuxiliaryTrack.player.stat)==null?void 0:o.fps)||(e.auxiliary.fpsRender=i.remoteAuxiliaryTrack.player.stat.fps)}catch(a){this._log.warn(`failed to getStats on receiver connection ${a}`)}return e.rtt===0&&(e.rtt=((n=this.room.networkQuality)==null?void 0:n.uplinkRTT)||0),e})}getStats(i,e){return f(this,null,function*(){let t={},r=[];if(this.room.singlePC){let o=this.room.singlePC.getPeerConnection();if(!o)return{senderStats:t,receiverStats:r};let n=U(),a=yield o.getStats(),c=U();c-n>2e3&&this._log.warn(`getStats cost ${c-n}ms`);let l=[],h=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source"]);a.forEach(u=>h.has(u.type)&&l.push(u)),this._spcStats=l}i&&(t=yield this.getSenderStats(i));for(let[o,n]of e){let a=yield this.getReceiverStats(n);r.push(a)}return{senderStats:t,receiverStats:r}})}getDifferenceValue(i,e){if(li(i))return e;let t=e-i;return t<0?0:t}prepareReport({stats:i,report:e,freezeMap:t}){var m,g,D;if(!li(i.senderStats)){let _={uint32_audio_level:i.senderStats.audio.audioLevel*At,uint32_audio_energy:(i.senderStats.audio.totalAudioEnergy||0)*1e6,uint32_audio_codec_bitrate:i.senderStats.audio.bytesSent};i.senderStats.audio.micAudioLevel&&(_.uint32_mic_audio_level=i.senderStats.audio.micAudioLevel*At),i.senderStats.audio.totalSamplesDuration&&(e.msg_device_info.uint32_audio_capture_cost=i.senderStats.audio.totalSamplesDuration);let S=[];if(i.senderStats.video.bytesSent){let K={uint32_video_stream_type:2,uint32_video_codec_fps:i.senderStats.video.framesSent,uint32_video_capture_fps:i.senderStats.video.fpsCapture,uint32_video_width:i.senderStats.video.frameWidth,uint32_video_height:i.senderStats.video.frameHeight,uint32_video_codec_bitrate:i.senderStats.video.bytesSent,uint32_video_enc_fps:i.senderStats.video.framesEncoded,uint32_key_frame_count:i.senderStats.video.keyFramesEncoded,uint32_nack_count:i.senderStats.video.nackCount,uint32_pli_count:i.senderStats.video.pliCount,uint32_encode_cost:(i.senderStats.video.totalEncodeTime||0)*1e3,uint32_send_packet_cost:(i.senderStats.video.totalPacketSendDelay||0)*1e3,uint32_video_arq_packets:i.senderStats.video.retransmittedPacketsSent};S.push(K)}if(i.senderStats.small.bytesSent){let K={uint32_video_stream_type:3,uint32_video_codec_fps:i.senderStats.small.framesSent||0,uint32_video_capture_fps:i.senderStats.small.fpsCapture||0,uint32_video_width:i.senderStats.small.frameWidth||0,uint32_video_height:i.senderStats.small.frameHeight||0,uint32_video_codec_bitrate:i.senderStats.small.bytesSent,uint32_video_enc_fps:i.senderStats.small.framesEncoded||0,uint32_key_frame_count:i.senderStats.small.keyFramesEncoded,uint32_nack_count:i.senderStats.small.nackCount,uint32_pli_count:i.senderStats.small.pliCount,uint32_encode_cost:(i.senderStats.small.totalEncodeTime||0)*1e3,uint32_send_packet_cost:(i.senderStats.small.totalPacketSendDelay||0)*1e3,uint32_video_arq_packets:i.senderStats.small.retransmittedPacketsSent};S.push(K)}if(i.senderStats.auxiliary.bytesSent){let K={uint32_video_stream_type:7,uint32_video_codec_fps:i.senderStats.auxiliary.framesSent||0,uint32_video_capture_fps:i.senderStats.auxiliary.fpsCapture||0,uint32_video_width:i.senderStats.auxiliary.frameWidth||0,uint32_video_height:i.senderStats.auxiliary.frameHeight||0,uint32_video_codec_bitrate:i.senderStats.auxiliary.bytesSent,uint32_video_enc_fps:i.senderStats.auxiliary.framesEncoded||0,uint32_key_frame_count:i.senderStats.auxiliary.keyFramesEncoded,uint32_nack_count:i.senderStats.auxiliary.nackCount,uint32_pli_count:i.senderStats.auxiliary.pliCount,uint32_encode_cost:(i.senderStats.auxiliary.totalEncodeTime||0)*1e3,uint32_send_packet_cost:(i.senderStats.auxiliary.totalPacketSendDelay||0)*1e3,uint32_video_arq_packets:i.senderStats.auxiliary.retransmittedPacketsSent};S.push(K)}let O={uint32_bitrate:0,uint32_lost:0,uint32_rtt:i.senderStats.rtt};e.msg_up_stream_info={msg_audio_status:_,msg_video_status:S,msg_network_status:O}}let r=(m=Ee())==null?void 0:m.playoutStats;r&&(e.msg_device_info.uint32_audio_play_cost=r.totalFramesDuration);let{statInterval:o}=this;e.msg_down_stream_info=[],i.receiverStats.forEach(_=>{let S={msg_user_info:{str_identifier:_.userId,uint64_tinyid:_.tinyId},msg_network_status:{uint32_rtt:_.rtt,uint32_bitrate:0,uint32_lost:0},msg_audio_status:{},msg_video_status:[]};if(_.hasAudio){let O={uint32_audio_p2p_delay:_.audio.p2pDelay,uint32_audio_cache_ms:_.audio.totalJitter,uint32_audio_cache_ms_count:_.audio.totalJitterCount,uint32_audio_codec_bitrate:_.audio.bytesReceived,uint32_audio_total_bitrate:_.audio.bytesReceived,uint32_audio_level:_.audio.audioLevel*1e8,uint32_audio_energy:_.audio.totalAudioEnergy*1e6,uint32_audio_receive:_.audio.packetsReceived,uint32_audio_origin_lost:_.audio.packetsLost};S.msg_audio_status=O}if(_.hasVideo){let O=t.get(`${_.userId}_${Xc}`),K=O?O.duration:0,G={uint32_video_stream_type:_.isSmallSubscribed?3:2,uint32_video_receive_fps:_.video.framesReceived,uint32_video_width:_.video.frameWidth,uint32_video_height:_.video.frameHeight,uint32_video_codec_bitrate:_.video.bytesReceived,uint32_video_receive:_.video.packetsReceived,uint32_video_origin_lost:_.video.packetsLost,uint32_video_block_time:K,uint32_video_dec_fps:_.video.framesDecoded,uint32_video_codec_fps:_.video.fpsRender,uint32_video_cache_ms:_.video.totalJitter,uint32_video_cache_ms_count:_.video.totalJitterCount,uint32_video_p2p_delay:_.video.p2pDelay};S.msg_video_status.push(G)}if(_.hasAuxiliary){let O=t.get(`${_.userId}_${zc}`),K=O?O.duration:0,G={uint32_video_stream_type:7,uint32_video_receive_fps:_.auxiliary.framesReceived,uint32_video_width:_.auxiliary.frameWidth,uint32_video_height:_.auxiliary.frameHeight,uint32_video_codec_bitrate:_.auxiliary.bytesReceived,uint32_video_receive:_.auxiliary.packetsReceived+_.auxiliary.packetsLost,uint32_video_origin_lost:_.auxiliary.packetsLost,uint32_video_block_time:K,uint32_video_dec_fps:_.auxiliary.framesDecoded,uint32_video_codec_fps:_.video.fpsRender,uint32_video_cache_ms:_.auxiliary.totalJitter,uint32_video_cache_ms_count:_.auxiliary.totalJitterCount,uint32_video_p2p_delay:_.auxiliary.p2pDelay};S.msg_video_status.push(G)}e.msg_down_stream_info.push(S)});let n=this._prevReport,a=this._prevStats;if(this._prevReport=JSON.parse(JSON.stringify(e)),this._prevStats=JSON.parse(JSON.stringify(i)),e.msg_up_stream_info.msg_audio_status&&n.msg_up_stream_info.msg_audio_status){let _=n.msg_up_stream_info.msg_audio_status,S=e.msg_up_stream_info.msg_audio_status;if(_.uint32_audio_codec_bitrate===0)S.uint32_audio_codec_bitrate=0;else{let O=this.getDifferenceValue(_.uint32_audio_codec_bitrate,S.uint32_audio_codec_bitrate);S.uint32_audio_codec_bitrate=Math.round(O*8/o),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=S.uint32_audio_codec_bitrate}(g=n.msg_device_info)!=null&&g.uint32_audio_capture_cost?e.msg_device_info.uint32_audio_capture_cost=2*Math.floor(this.getDifferenceValue(n.msg_device_info.uint32_audio_capture_cost,e.msg_device_info.uint32_audio_capture_cost)*1e3/o):delete e.msg_device_info.uint32_audio_capture_cost}let c=n.msg_up_stream_info.msg_video_status;e.msg_up_stream_info.msg_video_status.forEach(_=>{let S=c.find(_e=>_e.uint32_video_stream_type===_.uint32_video_stream_type);if(!S||S.uint32_video_codec_bitrate===0){_.uint32_video_codec_bitrate=0,_.uint32_video_enc_fps=0,_.uint32_video_codec_fps=0;return}let O=0,K=0,G=0;S&&_.uint32_video_codec_bitrate>=S.uint32_video_codec_bitrate&&(O=S.uint32_video_codec_bitrate,K=S.uint32_video_enc_fps,G=S.uint32_video_codec_fps);let Z=this.getDifferenceValue(O,_.uint32_video_codec_bitrate);_.uint32_video_codec_bitrate=Math.round(Z*8/o),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=_.uint32_video_codec_bitrate,_.uint32_video_enc_fps=Math.round(this.getDifferenceValue(K,_.uint32_video_enc_fps)/o),_.uint32_video_codec_fps=Math.round(this.getDifferenceValue(G,_.uint32_video_codec_fps)/o),S.uint32_video_width===0&&S.uint32_video_height===0&&S.uint32_video_codec_fps===0&&(_.uint32_video_codec_fps=_.uint32_video_enc_fps),T(S.uint32_key_frame_count)||(_.uint32_key_frame_count=Math.round(this.getDifferenceValue(S.uint32_key_frame_count,_.uint32_key_frame_count))),T(S.uint32_nack_count)||(_.uint32_nack_count=Math.round(this.getDifferenceValue(S.uint32_nack_count,_.uint32_nack_count))),T(S.uint32_pli_count)||(_.uint32_pli_count=Math.round(this.getDifferenceValue(S.uint32_pli_count,_.uint32_pli_count))),T(S.uint32_video_arq_packets)||(_.uint32_video_arq_packets=Math.round(this.getDifferenceValue(S.uint32_video_arq_packets,_.uint32_video_arq_packets))),T(S.uint32_encode_cost)||(_.uint32_encode_cost=Math.round(this.getDifferenceValue(S.uint32_encode_cost,_.uint32_encode_cost)/o)),T(S.uint32_send_packet_cost)||(_.uint32_send_packet_cost=Math.round(this.getDifferenceValue(S.uint32_send_packet_cost,_.uint32_send_packet_cost)/o))});let h=n.msg_down_stream_info;e.msg_down_stream_info=e.msg_down_stream_info.filter(_=>h.find(S=>S.msg_user_info.uint64_tinyid===_.msg_user_info.uint64_tinyid));let u=e.msg_down_stream_info;return u.forEach(_=>{let S=h.find(O=>O.msg_user_info.uint64_tinyid===_.msg_user_info.uint64_tinyid);if(!li(_.msg_audio_status)&&!li(S.msg_audio_status)){let O=_.msg_audio_status,K=S.msg_audio_status,G=this.getDifferenceValue(K.uint32_audio_cache_ms_count,O.uint32_audio_cache_ms_count);delete O.uint32_audio_cache_ms_count,O.uint32_audio_cache_ms=Math.floor(1e3*this.getDifferenceValue(K.uint32_audio_cache_ms,O.uint32_audio_cache_ms)/G)||0;let Z=this.room.remotePublishedUserMap.get(_.msg_user_info.str_identifier);Z&&(Z.remoteAudioTrack.stat.jitterBufferDelay=O.uint32_audio_cache_ms),O.uint32_audio_origin_lost=this.getDifferenceValue(K.uint32_audio_origin_lost,O.uint32_audio_origin_lost),O.uint32_audio_receive=this.getDifferenceValue(K.uint32_audio_receive,O.uint32_audio_receive),O.uint32_audio_receive+=O.uint32_audio_origin_lost;let _e=this.getDifferenceValue(K.uint32_audio_codec_bitrate,O.uint32_audio_codec_bitrate);O.uint32_audio_codec_bitrate=Math.round(_e*8/o),O.uint32_audio_total_bitrate=Math.round(_e*8/o)}else _.msg_audio_status={};if(_.msg_video_status&&S.msg_video_status){let O=S.msg_video_status;_.msg_video_status=_.msg_video_status.filter(G=>O.find(Z=>Z.uint32_video_stream_type===G.uint32_video_stream_type)),_.msg_video_status.forEach(G=>{let Z=O.find(gf=>gf.uint32_video_stream_type===G.uint32_video_stream_type),_e=Z.uint32_video_receive,J=Z.uint32_video_origin_lost,uf=Z.uint32_video_codec_bitrate,hf=Z.uint32_video_receive_fps,mf=Z.uint32_video_dec_fps;G.uint32_video_origin_lost=this.getDifferenceValue(J,G.uint32_video_origin_lost),G.uint32_video_receive=this.getDifferenceValue(_e,G.uint32_video_receive)+G.uint32_video_origin_lost;let pf=this.getDifferenceValue(uf,G.uint32_video_codec_bitrate);G.uint32_video_codec_bitrate=Math.round(pf*8/o);let ff=this.getDifferenceValue(hf,G.uint32_video_receive_fps);G.uint32_video_receive_fps=Math.round(ff/o),G.uint32_video_dec_fps=Math.round(this.getDifferenceValue(mf,G.uint32_video_dec_fps)/o);let _f=this.getDifferenceValue(Z.uint32_video_cache_ms_count,G.uint32_video_cache_ms_count);delete G.uint32_video_cache_ms_count,G.uint32_video_cache_ms=Math.floor(1e3*this.getDifferenceValue(Z.uint32_video_cache_ms,G.uint32_video_cache_ms)/_f)||0})}}),(D=n.msg_device_info)!=null&&D.uint32_audio_play_cost?e.msg_device_info.uint32_audio_play_cost=2*Math.floor(this.getDifferenceValue(n.msg_device_info.uint32_audio_play_cost,e.msg_device_info.uint32_audio_play_cost)/o):delete e.msg_device_info.uint32_audio_play_cost,a&&i.receiverStats.forEach(_=>{if(_.audio.concealedSamples&&_.audio.totalSamplesReceived){let S=a.receiverStats.find(O=>O.userId===_.userId);if(S&&S.audio.concealedSamples&&S.audio.totalSamplesReceived){let O=(_.audio.silentConcealedSamples||0)-(S.audio.silentConcealedSamples||0),K=_.audio.concealedSamples-S.audio.concealedSamples,G=_.audio.totalSamplesReceived-S.audio.totalSamplesReceived,Z=Math.floor((K-O)/G*1e3*o);if(Z>o*1e3/5){let _e=u.find(J=>J.msg_user_info.str_identifier===_.userId);_e&&(_e.msg_audio_status.uint32_audio_block_time=Z)}}}}),e}getStatsReport(r){return f(this,arguments,function*({uplinkConnection:i,downlinkConnections:e,freezeMap:t}){let o={msg_device_info:{},msg_up_stream_info:{msg_audio_status:{uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_level:0,uint32_audio_energy:0},msg_video_status:[],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}},msg_down_stream_info:[{msg_user_info:{str_identifier:"",uint64_tinyid:0},msg_audio_status:{uint32_audio_cache_ms:0,uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_total_bitrate:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_final_lost:0},msg_video_status:[{uint32_video_cache_ms:0,uint32_video_stream_type:0,uint32_video_receive_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_codec_bitrate:0,uint32_video_receive:0,uint32_video_origin_lost:0,uint32_video_block_time:0,uint32_video_dec_fps:0}],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}}]},n=yield this.getStats(i,e);return JSON.stringify(this._prevReport)==="{}"&&(this._prevReport=JSON.parse(JSON.stringify(o))),this.prepareReport({stats:n,report:o,freezeMap:t}),this._prevReportTime=Date.now(),o})}reset(){this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map}};var Up=$e(Ye());function Lp(s){let i={totalCost:0,local:0,redirect:0,httpCache:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let e=performance.getEntriesByType("resource").reverse();for(let t of e)if(t.name===s){let r=Math.round(t.duration),o=Math.max(Math.round(t.domainLookupStart-t.startTime),0),n=t.redirectStart>0?Math.max(Math.round(t.redirectEnd-t.redirectStart),0):0,a=t.fetchStart>0?Math.max(Math.round(t.domainLookupStart-t.fetchStart),0):0,c=Math.round(t.domainLookupEnd-t.domainLookupStart),l=Math.round(t.requestStart-t.secureConnectionStart),h=Math.round(t.secureConnectionStart-t.connectStart),u=Math.round(t.responseStart-t.requestStart),m=Math.round(t.responseEnd-(t.responseStart||t.startTime));i=L(N({},i),{totalCost:r,local:o,redirect:n,httpCache:a,dns:c,tcp:h,tls:l,request:u,response:m});break}}catch(e){}return i}function wp(s){return new Promise(i=>f(this,null,function*(){let e=setTimeout(()=>{i({totalCost:1e4,local:0,dns:0,tcp:0,tls:0,request:0,response:0})},1e4),t=Date.now(),r=`https://${s}/?t=${t}`;try{yield fetch(r)}catch(n){}clearTimeout(e);let o=Lp(r);o.totalCost===0&&(o.totalCost=Date.now()-t),i(o)}))}var dE=700,Yr=class Yr extends Up.default{constructor({signalChannel:e,room:t}){super();d(this,"_room");d(this,"_signalChannel");d(this,"_log");d(this,"uplinkRTT",0);d(this,"uplinkLoss",0);d(this,"downlinkRTT",0);d(this,"downlinkLoss",0);d(this,"pingResults",{});d(this,"_downlinkPrevStatMap",new Map);d(this,"_downlinkLossAndRTTMap",new Map);d(this,"_interval",-1);d(this,"_uplinkNetworkQuality",0);d(this,"_downlinkNetworkQuality",0);this._room=t,this._signalChannel=e,this._log=C.createLogger({id:"q",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this.initialize()}get uplinkNetworkQuality(){return this._uplinkNetworkQuality}set uplinkNetworkQuality(e){e!==this._uplinkNetworkQuality&&this._log.info(`uplink ${this.uplinkNetworkQuality} -> ${e}, rtt: ${this.uplinkRTT}, loss: ${this.uplinkLoss} ws-rtt: ${this._signalChannel.rtt}`),this._uplinkNetworkQuality=e}get downlinkNetworkQuality(){return this._downlinkNetworkQuality}set downlinkNetworkQuality(e){if(e!==this._downlinkNetworkQuality){let{rtt:t,loss:r}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._log.info(`downlink ${this.downlinkNetworkQuality} -> ${e}, rtt: ${t}, loss: ${r} ws-rtt: ${this._signalChannel.rtt}`)}this._downlinkNetworkQuality=e}initialize(){this._signalChannel.on(F.UPLINK_NETWORK_STATS,e=>{this.handleUplinkNetworkQuality(e)}),this._signalChannel.on(Ne.CONNECTION_STATE_CHANGED,this.handleSignalConnectionStateChange.bind(this)),this.start()}handleUplinkNetworkQuality(e){var c,l;if(e.data.code!==0)return;let t=e.data.data;if(t.delay&&this.updateDelay(t.delay),this._room.signalChannel&&t.wsRtt&&(this._room.signalChannel.rtt=t.wsRtt),!this._room.uplinkConnection){this.uplinkNetworkQuality=0,this.uplinkLoss=0,this.uplinkRTT=0;return}let r=(l=(c=this._room)==null?void 0:c.uplinkConnection)==null?void 0:l.getPeerConnection();if(r&&this.isPeerConnectionDisconnected(r)){this.uplinkNetworkQuality=6,this.uplinkLoss=0,this.uplinkRTT=0;return}let o=t.expectAudPkg+t.expectVidPkg,n=t.recvAudPkg+t.recvVidPkg,a=o-n;o===0&&n===0||(a<=0?this.uplinkLoss=0:this.uplinkLoss=Math.round(a/o*100),this.uplinkRTT=t.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this.uplinkLoss,this.uplinkRTT))}handleDownlinkNetworkQuality(){return f(this,null,function*(){if(this._room.remotePublishedUserMap.size===0){this.downlinkNetworkQuality=0;return}let e=[...this._room.remotePublishedUserMap.values()],t=e.filter(a=>{var c;return((c=a.getPeerConnection())==null?void 0:c.connectionState)===ge.CONNECTED});if(e.filter(a=>this.isPeerConnectionDisconnected(a.getPeerConnection())).length===e.length){this.downlinkNetworkQuality=6;return}for(let a=0;a<t.length;a++){let c=t[a].getPeerConnection();if(!c)return;let{rtt:l,totalPacketsLost:h,totalPacketsReceived:u}=yield this.getStat(c);if(!this._downlinkPrevStatMap.has(c)){this._downlinkPrevStatMap.set(c,{totalPacketsLost:h,totalPacketsReceived:u});continue}let m=0,g=this._downlinkPrevStatMap.get(c),D=h-g.totalPacketsLost,_=u-g.totalPacketsReceived;D<=0||_<0?m=0:m=Math.round(D/(D+_)*100),this._downlinkPrevStatMap.set(c,{totalPacketsLost:h,totalPacketsReceived:u}),this._downlinkLossAndRTTMap.set(c,{rtt:l,loss:m,userId:t[a].getUserId(),audioDelay:t[a].remoteAudioTrack.stat.end2EndDelay,videoDelay:t[a].remoteVideoTrack.stat.end2EndDelay})}if([...this._downlinkPrevStatMap.keys()].forEach(a=>{this.isPeerConnectionDisconnected(a)&&(this._downlinkPrevStatMap.delete(a),this._downlinkLossAndRTTMap.delete(a))}),this._downlinkLossAndRTTMap.size===0){this.downlinkRTT=0,this.downlinkLoss=0,this.downlinkNetworkQuality=0;return}let{rtt:o,loss:n}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this.downlinkRTT=o,this.downlinkLoss=n,this.downlinkNetworkQuality=this.getNetworkQuality(n,o)})}getStat(e){return f(this,null,function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!wr())return t;let r=e.getReceivers();try{for(let o=0;o<r.length;o++)(yield r[o].getStats()).forEach(c=>{c.type==="candidate-pair"&&q(c.currentRoundTripTime)&&(t.rtt=Math.round(c.currentRoundTripTime*1e3)),c.type==="inbound-rtp"&&(c.mediaType===p.AUDIO||c.mediaType===p.VIDEO)&&(t.totalPacketsLost+=c.packetsLost,t.totalPacketsReceived+=c.packetsReceived)});return t.rtt===0&&(t.rtt=this.uplinkRTT),t}catch(o){return t}})}getAverageLossAndRTT(e){let t={rtt:0,loss:0};return Array.isArray(e)&&e.length>0&&(e.forEach(r=>{t.rtt+=r.rtt,t.loss+=r.loss}),Object.keys(t).forEach(r=>{t[r]=Math.round(t[r]/e.length)})),t}getNetworkQuality(e,t){return e>50||t>500?5:e>30||t>350?4:e>20||t>200?3:e>10||t>100?2:e>=0||t>=0?1:0}handleSignalConnectionStateChange(e){e.state==="DISCONNECTED"?(this.uplinkRTT=0,this.uplinkLoss=0,this.uplinkNetworkQuality=6):e.state==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=5)}handleUplinkConnectionStateChange({state:e}){e==="DISCONNECTED"?(this.uplinkLoss=0,this.uplinkRTT=0,this.uplinkNetworkQuality=6):e==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=5)}isPeerConnectionDisconnected(e){return!!(e&&(e.connectionState===ge.DISCONNECTED||e.connectionState===ge.FAILED||e.connectionState===ge.CLOSED))}setUplinkConnection(e){this._room.uplinkConnection=e,this._room.uplinkConnection?this._room.uplinkConnection.on("connection-state-changed",this.handleUplinkConnectionStateChange.bind(this)):(this.uplinkNetworkQuality=0,this.uplinkRTT=0,this.uplinkLoss=0)}start(){if(this._interval!==-1){this._log.info("network quality calculating is already started");return}this._log.debug("start network quality calculating"),this._interval=oe.run("ric",()=>{var n;this.handleDownlinkNetworkQuality();let e=[...this._downlinkLossAndRTTMap.values()];E.emit(A.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this.uplinkRTT,loss:this.uplinkLoss},downlinks:e});let t=(n=this._room.scheduleResult.config)==null?void 0:n.pingDomainInfo,r={uplinkNetworkQuality:this.uplinkNetworkQuality,downlinkNetworkQuality:this.downlinkNetworkQuality,uplinkRTT:this.uplinkRTT,uplinkLoss:this.uplinkLoss,downlinkRTT:this.downlinkRTT,downlinkLoss:this.downlinkLoss};t&&(r=L(N({},r),{pingResults:this.uplinkRTT>t.rttThreshold||this.downlinkRTT>t.rttThreshold?this.pingResults:{}})),this.emit(Yr.EVENT_NETWORK_QUALITY,r);let o=Date.now();if(t&&(this.uplinkRTT>t.rttThreshold||this.downlinkRTT>t.rttThreshold)&&o-Yr.lastPingTime>t.interval*1e3){Yr.lastPingTime=Date.now();let a=t.domain.map(c=>wp(c).then(l=>({domain:c,cost:l.totalCost})));Promise.all(a).then(c=>{this.pingResults.isPoorNetwork=c.some(l=>l.cost>dE),this.pingResults.timestamp=o,this.pingResults.data=c,c.forEach(l=>{b.addSuccessEvent({key:521718,cost:l.cost})}),this._log.warn(`All ping results: ${JSON.stringify(c)}`)}).catch(c=>{this._log.warn(`Error during pinging domains: ${c}`)})}},{delay:2e3})}stop(){this._log.debug("stopped"),this._interval!==-1&&(oe.clearTask(this._interval),this._interval=-1),this._downlinkLossAndRTTMap.clear(),this._downlinkPrevStatMap.clear()}updateDelay(e){let{tinyIdToUserIdMap:t}=this._room;e.forEach(({srcTinyId:r,videoDelay:o,audioDelay:n})=>{let a=t.get(r);if(a){let c=this._room.remotePublishedUserMap.get(a);c==null||c.setDelay({videoDelay:o,audioDelay:n})}})}};d(Yr,"EVENT_NETWORK_QUALITY","0"),d(Yr,"lastPingTime",0);var Ys=Yr;function lE({fn:s,context:i}){return function(...e){try{let t=s.apply(i,e);return sr(t)?t.catch(r=>C.error(`${s.name}() error observed ${r}`)):t}catch(t){C.error(`${s.name}() error observed ${t}`)}}}var yc=class{constructor(i){d(this,"_frameWorkType");d(this,"_component");d(this,"_language");d(this,"connectionType");d(this,"_room");d(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0});d(this,"_keyPrefix");d(this,"_log");d(this,"_intervalId");d(this,"_firstPublishedUserList");d(this,"_networkQuality");d(this,"_basicInfo");d(this,"_pathJoinRoom");d(this,"_pathLeaveRoom");d(this,"_pathMainVideoMap");d(this,"_pathMainAudioMap");d(this,"_pathAuxiliaryMap");d(this,"_remoteStreamStatMap");d(this,"_localStreamStat");d(this,"_eventMap",new Map);d(this,"_captureCostSum",0);d(this,"_captureCostCount",0);d(this,"isDestroyed",!1);this._frameWorkType=i.frameWorkType||30,this._component=i.component||0,this.connectionType=i.connectionType||1,this._language=i.language||0,this._room=i.room,this._keyPrefix="key_point",this._log=C.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(e=>{e.startsWith("handle")&&ne(this[e])&&(this[e]=lE({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:Pe,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,Or().then(i=>{this._basicInfo.string_os_version=Pi(),i?this._basicInfo.string_device_name=i.mobile?i.model:this._basicInfo.string_os_version:this._basicInfo.string_device_name=this._basicInfo.string_os_version})}addEvent(i,e){return this._eventMap.set(i,e),E.on(i,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(A.JOIN_START,this.handleJoinStart).addEvent(A.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(A.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(A.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(A.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(A.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(A.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(A.JOIN_FAILED,this.handleJoinFailed).addEvent(A.LEAVE_START,this.handleLeaveStart).addEvent(A.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(A.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(A.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(A.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(A.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(A.PUBLISH_START,this.handlePublishStart).addEvent(A.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(A.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(A.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(A.PLAY_TRACK_START,this.handlePlayStart).addEvent(A.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(A.PLAYER_STATE_CHANGED,({track:i,state:e,type:t})=>{!i.isRemote||!this.hitTest(i.room)||e==="PLAYING"&&(t===p.AUDIO?this.handleAudioPlaying(i):this.handleVideoPlaying(i))}).addEvent(A.SWITCH_ROOM_START,this.handleSwitchRoomStart).addEvent(A.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess).addEvent(A.SWITCH_ROOM_FAILED,this.handleSwitchRoomFailed).addEvent(A.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(A.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(A.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(A.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{if(!this.hitTest(i))return;let r=e.hasAudio||e.hasVideo||e.hasSmall,o=e.hasAuxiliary,n=t.hasAudio||t.hasVideo||t.hasSmall,a=t.hasAuxiliary;!r&&n&&this.handleRemoteStreamAdded(t.userId,"main"),!o&&a&&this.handleRemoteStreamAdded(t.userId,"auxiliary")}).addEvent(A.SINGLE_CONNECTION_STAT,({room:i,stat:e})=>{this.hitTest(i)&&(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((i,e)=>E.off(e,i)),this._eventMap.clear()}destroy(){this.uninstallEvents(),oe.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(i){this.hitTest(i.room)&&(this._pathJoinRoom.uint64_start_time===0&&(this._pathJoinRoom.uint64_start_time=Date.now()),i.params&&(T(i.params.frameWorkType)||(this._frameWorkType=i.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),T(i.params.component)||(this._component=i.params.component,this._basicInfo.uint32_component=this._component),T(i.params.language)||(this._language=i.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleJoinScheduleSuccess({room:i,detailCost:e}){if(this.hitTest(i)&&e){let{totalCost:t,local:r,dns:o,tcp:n,tls:a,request:c,response:l}=e;this._pathJoinRoom.int32_schedule_cost=t,this._pathJoinRoom.int32_schedule_local=r,this._pathJoinRoom.int32_schedule_dns=o,this._pathJoinRoom.int32_schedule_tcp=n,this._pathJoinRoom.int32_schedule_tls=a,this._pathJoinRoom.int32_schedule_request=c,this._pathJoinRoom.int32_schedule_response=l}}handleSignalConnectionStart({room:i}){this.hitTest(i)&&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:i,error:e}){this.hitTest(i)&&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 y?Number(e.getExtraCode()||e.getCode()):I.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}handleJoinSendCMD(i){this.hitTest(i.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(i){this.hitTest(i.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=i.code,i.code!==0&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}handleJoinSuccess(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_end_time===0&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=i.room.getSignalInfo())}handleJoinFailed({room:i,error:e}){this.hitTest(i)&&(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(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_recv_userlist_time===0&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=i.publishedUserList||[])}handleSendFirstVideoFrame({room:i}){this.hitTest(i)&&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(i){this.hitTest(i.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(i){this.hitTest(i.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(i){this.hitTest(i.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(i){if(this.hitTest(i.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:i}){if(this.hitTest(i)&&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:i,error:e}){if(this.hitTest(i)){let t=Date.now();this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=t,this._pathJoinRoom.uint64_end_time=t,e&&(this._pathJoinRoom.int32_end_ret=e instanceof y?Number(e.getExtraCode()||e.getCode()):I.UNKNOWN)}}handleRemoteStreamAdded(i,e){var r;let t=`${i}_${e}`;if(!this._remoteStreamStatMap.has(t)){let o={userId:i,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:L(N({},uE),{msg_user_info:new fn({userId:i,tinyId:(r=this._room.remotePublishedUserMap.get(i))==null?void 0:r.tinyId,role:20})})};o.statsToReport.uint32_stream_type=e==="main"?2:7,this._remoteStreamStatMap.set(t,o)}}handleSubscribeStart({room:i,remotePublishedUser:e,streamType:t,subscribeState:r}){if(!this.hitTest(i))return;let{userId:o,tinyId:n,role:a}=e,c=new fn({userId:o,tinyId:n,role:a==="anchor"?20:21}),l=Date.now(),h=`${o}_${t}`,u=this._remoteStreamStatMap.get(h);u&&u.subscribeStartTime===0&&(u.subscribeStartTime=l),t==="main"?(e.muteState.hasVideo&&(r.video||r.smallVideo)&&!this._pathMainVideoMap.has(h)&&this._pathMainVideoMap.set(h,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:o,sendSubscribeCMDTime:l}),e.muteState.hasAudio&&r.audio&&!this._pathMainAudioMap.has(h)&&this._pathMainAudioMap.set(h,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:o,sendSubscribeCMDTime:l})):e.muteState.hasAuxiliary&&r.auxiliary&&!this._pathAuxiliaryMap.has(h)&&this._pathAuxiliaryMap.set(h,{sendSubscribeCMDTime:l})}handleSubscribed({room:i,remotePublishedUser:e,streamType:t}){if(this.hitTest(i)){let r=`${e.userId}_${t}`,o=this._remoteStreamStatMap.get(r);o&&o.subscribedTime===0&&(o.subscribedTime=Date.now())}}handlePlayStart({track:i}){if(!i.isRemote||!this.hitTest(i.room))return;let e=`${i.userId}_${i.streamType}`,t=this._remoteStreamStatMap.get(e);(t==null?void 0:t.playStreamTime)===0&&(t.playStreamTime=Date.now())}handleVideoLoadedData({track:i}){if(!i.isRemote||!this.hitTest(i.room))return;let e=`${i.userId}_${i.streamType}`,t=this._pathMainVideoMap.get(e);t&&t.statsToReport.uint64_combine_first_frame_time===0&&(t.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(i){let e=`${i.userId}_${i.streamType}`,t=Date.now(),r=this._pathMainVideoMap.get(e),o=this._remoteStreamStatMap.get(e);if(o){let{statsToReport:n}=o;if(!n.uint32_video_render_first&&i.streamType==="main"?this.hasVideoFlag(i.userId):this.hasAuxFlag(i.userId)){let a=t-this._pathJoinRoom.uint64_start_time;n.uint32_video_render_first=a,b.addNumber({key:516820,value:a})}}(r==null?void 0:r.statsToReport.uint64_render_first_frame_time)===0&&(r.statsToReport.uint64_render_first_frame_time=t)}handleAudioPlaying(i){let e=`${i.userId}_${i.streamType}`,t=this._pathMainAudioMap.get(e);t&&t.statsToReport.uint64_play_first_frame_time===0&&(t.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(i){this.hitTest(i.room)&&(this._networkQuality.totalUplinkLoss+=i.uplink.loss,this._networkQuality.totalUplinkRTT+=i.uplink.rtt,this._networkQuality.count++,i.downlinks.forEach(({rtt:e,loss:t,userId:r,videoDelay:o,audioDelay:n})=>{let a=this._networkQuality.totalDownlinkRTTAndLossMap.get(r);if(a)a.totalRTT+=e,a.totalLoss+=t,o&&(a.totalVideoDelay=(a.totalVideoDelay||0)+o,a.videoDelayCount=(a.videoDelayCount||0)+1),n&&(a.totalAudioDelay=(a.totalAudioDelay||0)+n,a.audioDelayCount=(a.audioDelayCount||0)+1),a.count++;else{let c,l,h,u;o&&(l=o,h=1),n&&(c=n,u=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(r,{totalRTT:e,totalLoss:t,count:1,totalAudioDelay:c,totalVideoDelay:l,audioDelayCount:u,videoDelayCount:h})}}))}handleHeartbeatStats(i){if(this.hitTest(i.room)){let{msg_device_info:e,msg_up_stream_info:t,msg_down_stream_info:r}=i.report;if(t.msg_video_status[0]){let{uint32_video_codec_bitrate:o,uint32_video_enc_fps:n,uint32_video_width:a,uint32_video_height:c}=t.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=o,this._localStreamStat.totalVideoFPS+=n,this._localStreamStat.totalVideoWidth+=a,this._localStreamStat.totalVideoHeight+=c,this._localStreamStat.videoCount++}if(t.msg_audio_status){let{uint32_audio_level:o}=t.msg_audio_status;Math.floor(o/At*100)>0&&(this._localStreamStat.totalAudioLevel+=o/At,this._localStreamStat.audioLevelCount++)}r.forEach(o=>{let{msg_user_info:n,msg_audio_status:a,msg_video_status:c}=o,l=n.str_identifier,h=this._room.remotePublishedUserMap.get(l);if(c.forEach(u=>{let m=u.uint32_video_stream_type===2,g=u.uint32_video_stream_type===7,D=`${l}_${m?"main":"auxiliary"}`,_=this._remoteStreamStatMap.get(D);if(_&&(m&&(h!=null&&h.remoteVideoTrack.isSubscribed)||g&&(h!=null&&h.remoteAuxiliaryTrack))){_.totalVideoFPS+=u.uint32_video_receive_fps,_.totalVideoBitrate+=u.uint32_video_codec_bitrate,_.videoCount++,_.statsToReport.uint32_video_width===0&&(_.statsToReport.uint32_video_width=u.uint32_video_width),_.statsToReport.uint32_video_height===0&&(_.statsToReport.uint32_video_height=u.uint32_video_height);let S=m?h.remoteVideoTrack:h.remoteAuxiliaryTrack;S.stat.jitterBufferDelay&&(_.videoJitterBufferDelay=S.stat.jitterBufferDelay),S.stat.framesReceived&&(_.statsToReport.uint32_video_consume_render_rate=Math.floor(S.stat.framesDecoded/S.stat.framesReceived*Zi(10,6)))}}),!as(a)){let u=`${l}_main`,m=this._remoteStreamStatMap.get(u);this._remoteStreamStatMap.has(u)&&m&&h!=null&&h.remoteAudioTrack.isSubscribed&&(m.totalAudioBitrate+=a.uint32_audio_codec_bitrate,m.audioCount++,h.remoteAudioTrack.stat.jitterBufferDelay&&(m.audioJitterBufferDelay=h.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(a.uint32_audio_level/At*100)>0&&(m.totalAudioLevel+=a.uint32_audio_level/At,m.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:i}){this.hitTest(i)&&this._localStreamStat.publishStartTime===0&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart({track:i}){i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess({track:i}){i.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()),i.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:i,error:e}){let r={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[e.name]||(e instanceof y?e.getExtraCode()||e.getCode():I.UNKNOWN);i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=r,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=r,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}hasVideoFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&tr)>=0}hasAudioFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&ir)>=0}hasAuxFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&Er)>=0}hitTest(i){return i===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 i=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),e=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=i<<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((i,e)=>{let{userId:t}=i,r=this._networkQuality.totalDownlinkRTTAndLossMap.get(t);if(r){let{totalLoss:h,count:u,audioDelayCount:m,videoDelayCount:g,totalAudioDelay:D,totalVideoDelay:_}=r;i.statsToReport.uint32_avg_down_loss=Math.floor(h/u),m&&D&&(i.statsToReport.uint32_audio_network_p2p_delay=Math.floor(D/m),i.audioJitterBufferDelay&&(i.statsToReport.uint32_p2p_delay=Math.floor(i.statsToReport.uint32_audio_network_p2p_delay+i.audioJitterBufferDelay))),g&&_&&(i.statsToReport.uint32_video_network_p2p_delay=Math.floor(_/g))}i.videoCount>0&&(i.statsToReport.uint32_video_avg_fps=Math.floor(i.totalVideoFPS/i.videoCount),i.statsToReport.uint32_video_avg_bitrate=Math.floor(i.totalVideoBitrate/i.videoCount)),i.audioCount>0&&(i.statsToReport.uint32_audio_recv_bitrate=i.statsToReport.uint32_audio_bitrate=Math.floor(i.totalAudioBitrate/i.audioCount)),i.audioLevelCount>0&&(i.statsToReport.uint32_audio_play_db=Math.floor(i.totalAudioLevel/i.audioLevelCount*100));let{callDurationCalculator:o}=this._room;o&&(i.statsToReport.uint32_audio_play_time=o.getDuration(e,p.AUDIO),i.statsToReport.uint32_video_play_time=o.getDuration(e,p.VIDEO)),i.statsToReport.uint32_video_render_first&&(i.statsToReport.uint32_video_render_first=Math.min(i.statsToReport.uint32_video_render_first,Zr));let{badCaseDetector:n}=this._room,{dataFreeze:a,count:c}=n.getDataFreezeDuration(e),{renderFreeze:l}=n.getRenderFreezeDuration(e);i.statsToReport.uint32_video_block_count=c,i.statsToReport.uint32_video_block_time=Math.min(a,i.statsToReport.uint32_video_play_time),i.statsToReport.uint32_video_external_block_time=Math.min(l,i.statsToReport.uint32_video_play_time),n.isBlackStream(e)&&i.statsToReport.uint32_video_avg_fps===0?i.statsToReport.uint32_video_black_screen_subjective=1:i.statsToReport.uint32_video_black_screen_subjective=0}),this._pathMainAudioMap.forEach((i,e)=>{if(!this.hasAudioFlag(i.userId)){this._pathMainAudioMap.delete(e);return}i.statsToReport.uint64_play_first_frame_time-i.statsToReport.uint64_start_enter_time>Zr&&(i.statsToReport.uint64_play_first_frame_time=i.statsToReport.uint64_start_enter_time+Zr)}),this._pathMainVideoMap.forEach((i,e)=>{if(!this.hasVideoFlag(i.userId)){this._pathMainVideoMap.delete(e);return}i.statsToReport.uint64_render_first_frame_time-i.statsToReport.uint64_start_enter_time>Zr&&(i.statsToReport.uint64_render_first_frame_time=i.statsToReport.uint64_start_enter_time+Zr)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>Zr&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+Zr)}getReportData(){this._basicInfo.uint32_networkType=Cr();let i={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new fn({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:cs(this._signalInfo.relayIp),uint32_client_ip:cs(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*Zi(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:cs(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,bytes_report_buf_from_0x1:this._signalInfo.endReportExtend};return mo(i),i}report(){return f(this,null,function*(){try{this.prepareReport();let i=this.getReportData();yield this.upload(i),this.initData()}catch(i){this._log.warn(i)}finally{this.isDestroyed&&(this._room=null)}})}upload(i){return f(this,null,function*(){if(i.msg_path_enter_room.uint64_start_time===0)return;let e=Number(this._room.sdkAppId),t=yield nd(i),r=t instanceof ArrayBuffer,o=`${yi(e,Ki.KEY_POINT)}&gzip=${+r}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(o,t));let a=[this.uploadKVStat(b),this.uploadKVStat(Lr)];n||a.push(Di({url:o,body:t,priority:"low"})),yield Promise.all(a)})}setConnectionType(i){this.connectionType=i,this._basicInfo.uint32_connection_type=i}uploadKVStat(i){return f(this,null,function*(){let e=i.getReportData();if(e.stats_count.length===0&&e.stats_distribution.length===0)return;e.msg_sdk_basic_info=L(N({},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 t=yield nd(e),r=`${yi(+this._room.sdkAppId,Ki.KV_STAT)}&gzip=${+(t instanceof ArrayBuffer)}`,o=!1;navigator.sendBeacon&&(o=navigator.sendBeacon(r,t)),o||Di({url:r,body:t})})}};v([pt({settings:{timeout:500,retries:3}})],yc.prototype,"upload",1);var Zr=5e3,uE={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},fn=class{constructor(i){d(this,"str_identifier");d(this,"str_tinyid");d(this,"uint32_role");this.str_identifier=String(i.userId),this.str_tinyid=String(i.tinyId||0),this.uint32_role=i.role}},Vp=yc;var Lu=class{constructor(){d(this,"_startTime");d(this,"_endTime");this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=U())}stop(){this._endTime===0&&(this._endTime=U())}getDuration(){return this._endTime===0?U()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},bc=Lu;var wu=class{constructor(i){d(this,"_room",null);d(this,"_durationMap");d(this,"_eventMap",new Map);this._room=i.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(A.REMOTE_TRACK_SUBSCRIBED,this.handleSubscribed).set(A.REMOTE_TRACK_UNSUBSCRIBED,this.handleUnsubscribed).set(A.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{var n;let{userId:r}=t;if(!this.hitTest(i))return;e.hasAudio&&!t.hasAudio&&this.stopDurationItem(`${r}_main`,p.AUDIO),e.hasVideo&&!t.hasVideo&&this.stopDurationItem(`${r}_main`,p.VIDEO),e.hasAuxiliary&&!t.hasAuxiliary&&this.stopDurationItem(`${r}_auxiliary`,p.VIDEO);let o=(n=this._room)==null?void 0:n.remotePublishedUserMap.get(r);o&&(!e.hasAudio&&t.hasAudio&&o.remoteAudioTrack.isSubscribed&&this.addDuractionItem(r,p.AUDIO,"main"),!e.hasVideo&&t.hasVideo&&o.remoteVideoTrack.isSubscribed&&this.addDuractionItem(r,p.VIDEO,"main"),!e.hasAuxiliary&&t.hasAuxiliary&&o.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(r,p.VIDEO,"auxiliary"))}),this._eventMap.forEach((i,e)=>E.on(e,i,this))}uninstallEvents(){this._eventMap.forEach((i,e)=>E.off(e,i,this)),this._eventMap.clear()}handleSubscribed({track:i}){if(!this.hitTest(i.room))return;let{userId:e,streamType:t,kind:r}=i;i.isSubscribed?this.addDuractionItem(e,r,t):this.stopDurationItem(`${e}_${t}`,r)}handleUnsubscribed({track:i}){this.hitTest(i.room)&&this.stopDurationItem(`${i.userId}_${i.streamType}`,i.kind)}isRecording(i){return i.findIndex(e=>e.endTime===0)>=0}addDuractionItem(i,e,t){let r=`${i}_${t}`,o=new bc,n=this._durationMap.get(r);n?this.isRecording(n[e])||n[e].push(o):this._durationMap.set(r,{userId:i,type:t,audio:e===p.AUDIO?[o]:[],video:e===p.AUDIO?[]:[o]})}stopDurationItem(i,e){if(this._durationMap.has(i)){let r=this._durationMap.get(i)[e].find(o=>o.endTime===0);r&&r.stop()}}hitTest(i){return this._room===i}getDuration(i,e){return this._durationMap.has(i)?this._durationMap.get(i)[e].reduce((r,o)=>r+o.getDuration(),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},Bp=wu;var Uu=class{constructor(i){d(this,"_room");d(this,"_renderFreezeMap",new Map);d(this,"_isVideoPlayingEventFiredMap",new Map);d(this,"_dataFreezeMap",new Map);d(this,"_monitorFreezeData",new Map);d(this,"_eventMap",new Map);this._room=i.room,this.installEvents()}getRenderFreezeMap(){return this._renderFreezeMap}getDataFreezeMap(){return this._dataFreezeMap}installEvents(){this._eventMap.set(A.LEAVE_SUCCESS,({room:i})=>{this.hitTest(i)&&this.stop()}).set(A.PLAY_TRACK_START,this.onPlayTrackStart).set(A.UNSUBSCRIBE_SUCCESS,({room:i,streamType:e,remotePublishedUser:t})=>{if(!this.hitTest(i))return;let{userId:r}=t,o=`${r}_${e}`;this.stopDataFreeze({key:o,userId:r,type:e})}).set(A.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{if(!this.hitTest(i))return;let{userId:r}=t;if(e.hasVideo&&!t.hasVideo){let o="main",n=`${t.userId}_${o}`;this.stopDataFreeze({key:n,userId:r,type:o})}if(e.hasAuxiliary&&!t.hasAuxiliary){let o="auxiliary",n=`${t.userId}_${o}`;this.stopDataFreeze({key:n,userId:r,type:o})}}).set(A.PLAYER_STATE_CHANGED,({track:i,state:e,reason:t,type:r})=>{if(!(!i.isRemote||!i.room||!this.hitTest(i.room)||r!==p.VIDEO)){if(e==="PLAYING"){let o=`${i.userId}_${i.streamType}`;this._isVideoPlayingEventFiredMap.set(o,!0)}t===p.MUTE?this.onVideoTrackMuted(i):t===p.UNMUTE&&this.onVideoTrackUnmuted(i)}}).set(A.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach((i,e)=>E.on(e,i,this))}uninstallEvents(){this._eventMap.forEach((i,e)=>E.off(e,i,this)),this._eventMap.clear()}stop(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}onVideoTrackMuted(i){if(!i.isSubscribed)return;let{userId:e,streamType:t}=i,r=`${e}_${t}`,o=this._dataFreezeMap.get(r),n=new bc;o?o.durationItemList.push(n):this._dataFreezeMap.set(r,{userId:e,type:t,durationItemList:[n],isFreezing(){let a=this.durationItemList[this.durationItemList.length-1];return a&&a.endTime===0}})}onVideoTrackUnmuted(i){if(!i.isSubscribed)return;let{userId:e,streamType:t}=i,r=`${e}_${t}`;this.stopDataFreeze({key:r,userId:e,type:t})}onHearBeatReport({room:i,report:e}){this.hitTest(i)&&e.msg_down_stream_info.forEach(t=>{let r=this._room.remotePublishedUserMap.get(t.msg_user_info.str_identifier);if(!r)return;let{userId:o,muteState:n}=r;t.msg_video_status.forEach(a=>{a.uint32_video_stream_type===2&&n.hasVideo&&!n.videoMuted&&r.remoteVideoTrack.isSubscribed&&this.handleRenderFreeze({userId:o,fps:a.uint32_video_dec_fps,type:"main"}),a.uint32_video_stream_type===7&&n.hasAuxiliary&&r.remoteAuxiliaryTrack.isSubscribed&&this.handleRenderFreeze({userId:o,fps:a.uint32_video_dec_fps,type:"auxiliary"})})})}stopDataFreeze({key:i,userId:e,type:t}){let r=this._dataFreezeMap.get(i);if(!r||!r.isFreezing())return;let o=r.durationItemList[r.durationItemList.length-1];o.stop();let n=o.getDuration();n>Mn?this._monitorFreezeData.set(i,{userId:e,type:t,duration:n}):r.durationItemList.pop()}getTotalDuration(i){return i.reduce((e,t)=>{let r=t.getDuration();return e+Math.min(r,5e3)},0)}handleRenderFreeze(r){return f(this,arguments,function*({userId:i,fps:e,type:t}){let o=`${i}_${t}`,n=this._renderFreezeMap.get(o);if(e<=2){let a=U();n&&!n.isFreeze&&(n.freezeTimeline.push({startTime:a,endTime:0}),n.isFreeze=!0),n||this._renderFreezeMap.set(o,{userId:i,type:t,isFreeze:!0,freezeTimeline:[{startTime:a,endTime:0}],renderFreezeTotal:0})}else if(n&&n.isFreeze){n.isFreeze=!1;let a=n.freezeTimeline.pop();if(a){a.endTime=U();let c=a.endTime-a.startTime;n.freezeTimeline.push(a),n.renderFreezeTotal+=Math.min(5e3,c)}}})}onPlayTrackStart({track:i}){if(!i.isRemote||!this.hitTest(i.room)||i.kind!==p.VIDEO||!i.isRemotePublished)return;let e=`${i.userId}_${i.streamType}`;this._isVideoPlayingEventFiredMap.has(e)||this._isVideoPlayingEventFiredMap.set(e,!1)}getDataFreezeDuration(i){let e={dataFreeze:0,count:0},t=this._dataFreezeMap.get(i);if(t){if(t.isFreezing()){let r=t.durationItemList[t.durationItemList.length-1];r.stop(),r.getDuration()<Mn&&t.durationItemList.pop()}e.dataFreeze=this.getTotalDuration(t.durationItemList),e.count=t.durationItemList.length}return e}getRenderFreezeDuration(i){let e=this._renderFreezeMap.get(i),t=0,r=0;if(e)if(!e.isFreeze)t=e.renderFreezeTotal;else{let o=U(),n=e.freezeTimeline[e.freezeTimeline.length-1],a=o-n.startTime;t=e.renderFreezeTotal+Math.min(a,5e3),r=e.freezeTimeline.length}return{renderFreeze:t,count:r}}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(i){return this._isVideoPlayingEventFiredMap.has(i)?!this._isVideoPlayingEventFiredMap.get(i):!1}resetMonitor(){this._monitorFreezeData.clear()}hitTest(i){return i===this._room}destroy(){this.uninstallEvents()}},Fp=Uu;var Hp=$e(Ye(),1);var hE=[1,0,0,0,1,1,0,1],Nc=class extends it{constructor(e,t,r,o){super(e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"transform",logger:t});d(this,"mirror",!1);d(this,"rotation",0);if(r&&(this.mirror=r),o&&(this.rotation=o),e instanceof ke)try{this.setTexBuffer(hE)}catch(n){e.destroy(new y({code:I.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${n.message||n}`}))}}draw2d(e,t,r,o,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(o,0),this.ctx2d.rotate(Math.PI/2),this.ctx2d.scale(n/o,o/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/o,o/n));let a=super.draw2d(e,t,r,o,n);return this.ctx2d.restore(),a}return!1}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}};var Vu=class{constructor(i,e){this.node=i;this.layout=e;d(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}},_n=class extends it{constructor(e,t){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,matchInputSize:!1,logger:t});d(this,"inputs",[])}addInput(e,t){if(this.inputs[t.zIndex])throw new Error("input already exists");let r=new Vu(e,t);this.inputs[t.zIndex]=r}changeInputLayout(e,t){let r=this.inputs.findIndex(o=>o?o.node===e:!1);r<0||Object.entries(t).forEach(([o,n])=>{T(n)||(this.inputs[r].layout[o]=n)})}resize(e,t){if(!this.matchInputSize){super.resize(e,t);return}let r=this.inputs.reduce((o,n)=>n?Object.assign(o,{width:Math.max(o.width,n.right),height:Math.max(o.height,n.bottom)}):o,{width:0,height:0});super.resize(r.width,r.height),this.context instanceof ke&&this.inputs.forEach(o=>{if(o){let n=this.layout2texCoords(o);o.positionBuffer?this.changeBufferData(o.positionBuffer,n):o.positionBuffer=this.createBuffer(n)}})}connect(e,...t){return super.connect(e,...t),this.matchInputSize&&this.resize(0,0),e}removeInput(e){this.inputs[this.inputs.findIndex(t=>(t==null?void 0:t.node)===e)]=void 0}render(e){let t=this.context.ctx;if(t.clearColor(0,0,0,0),this.inputs.reduce((o,n)=>(n==null?void 0:n.node.requestFrame(e))||o,!1)&&t){this.useProgram(),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let o=0;o<this.inputs.length;o++){let n=this.inputs[o];n&&(n.node.useTexture(),this.draw(n.positionBuffer))}return!0}return!1}render2d(e){if(this.inputs.reduce((r,o)=>(o==null?void 0:o.node.requestFrame(e))||r,!1)&&this.ctx2d){this.ctx2d.fillStyle="black",this.ctx2d.fillRect(0,0,this.width,this.height);for(let r=0;r<this.inputs.length;r++){let o=this.inputs[r];o&&this.draw2d(o.node.image,o.x,o.y,o.width,o.height)}return!0}return!1}getInfo(){let{totalFrames:e,x:t,y:r,width:o,height:n,name:a}=this,c=Date.now(),l=(e-this.lastInfo.totalFrames)/((c-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:r,width:o,height:n,timestamp:c,fps:l,name:a},N({parent:this.inputs.filter(h=>h).map(h=>h.node.getInfo())},this.lastInfo)}close(){super.close(),this.inputs.forEach(e=>{var t,r;if(e&&((t=e.node)==null||t.disconnect(),e.positionBuffer&&this.context instanceof ke))try{(r=this.context.ctx)==null||r.deleteBuffer(e.positionBuffer)}catch(o){}})}};var vc=class{constructor(i,e,t,r=4/3){this.vbMode=i;this.faceDetector=e;this.logger=t;d(this,"animationState");d(this,"originalAspect");d(this,"totalOffsetX",0);d(this,"totalOffsetY",0);d(this,"defaultScaleRatio",.1);d(this,"isRecovering",!1);d(this,"boundaryY",280);d(this,"lastActionTime",0);d(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=r||4/3}addEvent(i,e,t){let o=[{key:570704,error:t!=null?t:e?void 0:11},{key:570705,error:t!=null?t:e?void 0:22}][i-1];o&&(e?b.addSuccessEvent({key:o.key}):b.addFailedEvent({key:o.key,error:o.error}))}actionCentering(i){let e=Date.now();if(this.animation(),!this.faceDetector||e-this.lastActionTime<this.restTime||this.animationState.animating)return;let{videoWidth:t,videoHeight:r}=i;this.animationState.debounceThreshold=t/30,this.animationState.movementThreshold=t/20;try{let o=this.faceDetector.detectForVideo(i,Date.now());if(o.detections.length<=0){this.vbMode===1&&this.recoverOriginal(t,r);return}let n=o.detections[0].boundingBox,a=n.originX,c=n.originY,l=n.width,h=n.height;this.vbMode===1?this.dualStageCropping(t,r,a,c,l,h):this.vbMode===2&&this.movingPortrait(t,r,a,c,l,h)}catch(o){this.logger.error(o)}this.lastActionTime=e}calculateBoundary(i,e,t,r){let o,n;return i>e/2?(o=e-t-r,n=t-o):(o=t,n=0),{min:o,offset:n}}calculateTargetPosition(i,e,t,r,o,n,a=.4){let c=i+t/2,l=e+r/2,h,u,{min:m,offset:g}=this.calculateBoundary(c,o,i,t),{min:D,offset:_}=this.calculateBoundary(l,n,e,r);return h=2*m+t,u=2*D+r,h/u>this.originalAspect?(h=u*this.originalAspect,g=c-h/2):(u=h/this.originalAspect,_=l-u/2),t/o>a&&(g=0,_=0,h=o,u=n),g=Math.max(0,Math.min(g,o-h)),_=Math.max(0,Math.min(_,n-u)),{sx:g,sy:_,cropWidth:h,cropHeight:u,timestamp:Date.now()}}processFacePositionCrop(i,e,t){if(!this.animationState.current||!this.animationState.target){let a={sx:0,sy:0,cropWidth:e,cropHeight:t,timestamp:Date.now()};this.animationState.current=a,this.animationState.target=a;return}let r=this.positionDistance(this.animationState.target,i),o=this.positionDistance(this.animationState.current,i),n=this.animationState.current.cropWidth/e;r>this.animationState.debounceThreshold*n&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&o>this.animationState.movementThreshold*n&&(this.animationState.target=i,this.animationState.debounceTimer=setTimeout(()=>{this.animationState.startTime=Date.now(),this.animationState.animating=!0},this.animationState.debounceTime))}processFacePositionPortrait(i){if(!this.animationState.current||!this.animationState.target){this.animationState.current=N({},i),this.animationState.target=N({},i);return}let e=this.positionDistance(this.animationState.current,i),t=this.positionDistance(this.animationState.target,i);e>this.animationState.debounceThreshold&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&t>this.animationState.movementThreshold&&(this.animationState.current=i,this.animationState.debounceTimer=setTimeout(()=>{this.animationState.startTime=Date.now(),this.animationState.animating=!0},this.animationState.debounceTime))}animation(){if(!this.animationState.animating)return;let i=Date.now()-this.animationState.startTime,e=Math.min(i/this.animationState.duration,1),t=r=>r<.5?2*r*r:-1+(4-2*r)*r;if(this.animationState.current&&this.animationState.target){let r=(this.animationState.target.sx-this.animationState.current.sx)*t(e);this.animationState.current.sx+=r,this.totalOffsetX+=r;let o=(this.animationState.target.sy-this.animationState.current.sy)*t(e);if(this.animationState.current.sy+=o,this.totalOffsetY+=o,this.animationState.current.cropWidth+=(this.animationState.target.cropWidth-this.animationState.current.cropWidth)*t(e),this.animationState.current.cropHeight+=(this.animationState.target.cropHeight-this.animationState.current.cropHeight)*t(e),this.animationState.current.scaleRatio&&this.animationState.target.scaleRatio&&(this.animationState.current.scaleRatio+=(this.animationState.target.scaleRatio-this.animationState.current.scaleRatio)*t(e)),q(this.animationState.current.scaleOffsetX)&&q(this.animationState.target.scaleOffsetX)&&q(this.animationState.current.scaleOffsetY)&&q(this.animationState.target.scaleOffsetY)){let n=(this.animationState.target.scaleOffsetX-this.animationState.current.scaleOffsetX)*t(e);this.animationState.current.scaleOffsetX+=n;let a=(this.animationState.target.scaleOffsetY-this.animationState.current.scaleOffsetY)*t(e);this.animationState.current.scaleOffsetY+=a}}e>=1&&(this.animationState.animating=!1,this.animationState.current=this.animationState.target,this.isRecovering=!1)}positionDistance(i,e){return Math.sqrt(Zi(i.sx-e.sx,2)+Zi(i.sy-e.sy,2))}recoverOriginal(i,e){this.animationState.target={sx:0,sy:0,cropWidth:i,cropHeight:e,timestamp:Date.now()},this.animationState.animating=!0,this.animationState.startTime=Date.now(),this.isRecovering=!0}dualStageCropping(i,e,t,r,o,n,a=.3){if(this.isRecovering)return;let c=this.calculateTargetPosition(t,r,o,n,i,e);this.processFacePositionCrop(c,i,e),o*n/c.cropWidth/c.cropHeight>a&&this.recoverOriginal(i,e)}movingPortrait(i,e,t,r,o,n){var c,l,h,u,m,g,D,_,S,O,K,G;let a={sx:t+o/2+this.totalOffsetX,sy:r+n/2+this.totalOffsetY,cropWidth:i,cropHeight:e,scaleRatio:(l=(c=this.animationState.current)==null?void 0:c.scaleRatio)!=null?l:1,scaleOffsetX:(u=(h=this.animationState.current)==null?void 0:h.scaleOffsetX)!=null?u:0,scaleOffsetY:(g=(m=this.animationState.current)==null?void 0:m.scaleOffsetY)!=null?g:0,timestamp:Date.now()};this.animationState.target={sx:i/2,sy:r+n/2,cropWidth:i,cropHeight:e,scaleRatio:(_=(D=this.animationState.target)==null?void 0:D.scaleRatio)!=null?_:1,scaleOffsetX:(O=(S=this.animationState.target)==null?void 0:S.scaleOffsetX)!=null?O:0,scaleOffsetY:(G=(K=this.animationState.target)==null?void 0:K.scaleOffsetY)!=null?G:0,timestamp:Date.now()},this.animationState.animating||(this.animationState.target.scaleRatio=Math.sqrt(o*n/i/e/this.defaultScaleRatio),this.animationState.target.scaleOffsetX=-this.animationState.target.scaleRatio/2+.5,this.animationState.target.scaleOffsetY=-this.animationState.target.scaleRatio+1,(this.animationState.target.sy-this.animationState.target.scaleOffsetY*this.animationState.target.cropHeight)/this.animationState.target.scaleRatio<this.boundaryY&&(this.animationState.target.scaleOffsetY=(this.animationState.target.sy-this.boundaryY*this.animationState.target.scaleRatio)/this.animationState.target.cropHeight)),this.processFacePositionPortrait(a)}set aspectRatio(i){this.originalAspect=i}get current(){return this.animationState.current}get offset(){return{offsetX:this.totalOffsetX,offsetY:this.totalOffsetY}}get targetCrop(){return this.animationState.target}};var mE=`#version 300 es
|
|
70
70
|
in vec2 a_position;
|
|
71
71
|
in vec2 a_texCoord;
|
|
72
72
|
out vec2 v_texCoord;
|