trtc-sdk-v5 5.14.2-beta.8 → 5.14.2-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/assets/debug-dialog.js +1 -1
- package/index.d.ts +5 -1
- package/package.json +1 -1
- package/plugins/cdn-streaming/package.json +1 -1
- package/plugins/chorus/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/lebplayer/lebplayer.esm.d.ts +254 -21
- package/plugins/lebplayer/lebplayer.esm.js +1 -1
- package/plugins/lebplayer/lebplayer.umd.js +1 -1
- package/plugins/lebplayer/package.json +1 -1
- package/plugins/small-stream-auto-switcher/package.json +1 -1
- package/plugins/video-decoder/package.json +1 -1
- package/plugins/video-effect/basic-beauty/package.json +1 -1
- package/plugins/video-effect/beauty/package.json +1 -1
- package/plugins/video-effect/video-mixer/package.json +1 -1
- package/plugins/video-effect/virtual-background/package.json +1 -1
- package/plugins/video-effect/watermark/package.json +1 -1
- package/plugins/voice-changer/package.json +1 -1
- package/trtc.esm.js +4 -4
- package/trtc.js +1 -1
package/trtc.esm.js
CHANGED
|
@@ -24,13 +24,13 @@ Refer to: ${cp("en",a)}
|
|
|
24
24
|
}
|
|
25
25
|
};
|
|
26
26
|
`],{type:"application/javascript"}))),Be.sharedWorker.onmessage=e=>{var t;if(e.data.type==="tick"){let r=Be.workerTasks.get(e.data.taskId);r&&(Be.isBreakLoop(r)?((t=Be.sharedWorker)==null||t.postMessage({type:"stop",taskId:r.taskID}),Be.workerTasks.delete(r.taskID)):(r.callback(),r.loopCount+=1))}}),Be.workerTasks.set(i.taskID,i),Be.sharedWorker.postMessage({taskId:i.taskID,delay:i.delay,type:"start"})}static timeout(i){let e=()=>{if(i.callback(),i.loopCount+=1,!Be.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),!Be.isBreakLoop(i))return i.ricID=wp(r,{timeout:i.delay})};return i.ricID=wp(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,Be.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),!Be.isBreakLoop(i))return i.rafID=requestAnimationFrame(r)};if(i.rafID=requestAnimationFrame(r),i.backgroundTask){let s=()=>{if(document.hidden){let n=U()-e;n>=i.delay?r():i.timeoutID=setTimeout(r,i.delay-n)}};document.addEventListener("visibilitychange",s),i.onVisibilitychange=s,document.hidden&&s()}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:s,onVisibilitychange:n}=this.taskMap.get(i);return e&&clearInterval(e),t&&clearTimeout(t),r&&Lp&&Lp(r),s&&BT(s),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(Be,"taskMap",new Map),d(Be,"currentTaskID",1),d(Be,"sharedWorker",null),d(Be,"workerTasks",new Map);var pu=Be,oe=pu;var HC={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:f.SEI_MESSAGE,ERROR:"error"};var ue={LOAD_START:f.LOADSTART,LOADED_DATA:f.LOADEDDATA,LOADED_META_DATA:f.LOADEDMETADATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error",RESIZE:f.RESIZE,TIME_UPDATE:"time-update"};var vi={};Vi(vi,{create:()=>tt,remove:()=>Le});var Rn=new WeakMap;function tt(o,i){Rn.has(o)||Rn.set(o,[]);let e=Rn.get(o),r={add:(s,n)=>("addEventListener"in i?(e.push(i.removeEventListener.bind(i,s,n)),i.addEventListener(s,n)):(e.push(i.off.bind(i,s,n)),i.on(s,n)),r)};return r}function Le(o){let i=Rn.get(o);i&&(i.forEach(e=>e()),Rn.delete(o))}var _u=class{constructor(){d(this,"_roomIdMap",new Map);d(this,"_configs");typeof registerProcessor=="undefined"&&(this._configs={sdkAppId:"",userId:"",version:$e,env:Bi.QCLOUD,browserVersion:Ci.name+Ci.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){oi||!R.isAbleToUpload||this._configs.env===Bi.QCLOUD&&this.uploadEventToKibana(L(O({},i),{result:"success"}))}logFailedEvent(i){if(oi||!R.isAbleToUpload)return;let{eventType:e,code:t,error:r,userId:s}=i,n={roomId:this._roomIdMap.get(s||this._configs.userId),userId:s,eventType:e,result:"failed",code:t||(r==null?void 0:r.extraCode)||(r==null?void 0:r.code)||I.UNKNOWN};this._configs.env===Bi.QCLOUD&&this.uploadEventToKibana(L(O({},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:la(),sdkAppId:this._configs.sdkAppId,userId:e||this._configs.userId,version:$e,log:i};t&&(r.errorInfo=t.message,t.stack&&(r.errorInfo+=`
|
|
27
|
-
${t.stack}`));let s=Ir.enable?Gi(r,2002,Number(this._configs.sdkAppId)):JSON.stringify(r);this.sendRequest(Wi(this._configs.sdkAppId,mr.LOG),s)}sendRequest(i,e){setTimeout(()=>qi({url:i,body:e,priority:"low"}).catch(()=>{}),2e3)}},se=new _u;var Ni=new WeakMap;function Mt({settings:o={retries:5,timeout:2e3},onError:i,onRetrying:e,onRetryFailed:t}){return function(r,s,n){let a=Ai({retryFunction:n.value,settings:o,onError({error:c,retry:l,reject:u,retryFuncArgs:h}){var m;i?i.call(this,c,()=>{var _;(_=Ni.get(r))!=null&&_.has(s)?l():u(c)},u,h):(m=Ni.get(r))!=null&&m.has(s)?l():u(c)},onRetrying(c,l){var u;Ii(e)&&e.call(this,c,l),(u=Ni.get(r))!=null&&u.has(s)&&(Ni.get(r).get(s).stopRetry=l)},onRetryFailed:t});return n.value=function(...c){let l=Ni.get(r);return l?l.set(s,{args:c}):Ni.set(r,new Map([[s,{args:c}]])),a.apply(this,c).finally(()=>{var u;return(u=Ni.get(r))==null?void 0:u.delete(s)})},n}}function yn({fnName:o,callback:i,validateArgs:e=!0}){return function(t,r,s){let n=s.value;return s.value=function(...a){var c,l;if((c=Ni.get(t))!=null&&c.has(o)){let{stopRetry:u,args:h}=Ni.get(t).get(o),m=!0;if(e){for(let _ of h)if(!a.find(g=>g===_)){m=!1;break}}m&&(i&&i.apply(this,a),u&&u(),(l=Ni.get(t))==null||l.delete(o))}return n.apply(this,a)},s}}var mi=class extends J{constructor(e,t){super(e.id,`${t}-player`);this.options=e;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,"_isPausedByUserCall",!1);d(this,"_pausedRetryCount");d(this,"_isElementPlayingFired",!1);d(this,"_interval");d(this,"_delayDestroyTimeoutId",0);d(this,"_playSuccessResolve");d(this,"_isReplayByRecreateMediaStreamCalled",!1);d(this,"isPlayCalled",!1);d(this,"isInAutoPlayFailedState",!1);this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=$r,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 p(this,null,function*(){if(!this.isPlaying)try{this.isPlayCalled=!0,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=H({key:F.PLAY_FAILED,data:{media:this.kind,error:e}});if(this._log.warn(e),t.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new D({code:I.PLAY_NOT_ALLOWED,message:t})}})}stop(e=0){var t;this.isPlayCalled=!1,this._isElementPlayingFired=!1,this.unbindEvents(),e>0&&!Ft?this._delayDestroyTimeoutId||((t=this.element)==null||t.remove(),this._log.info(`destroy element after 3 * ${e}`),this._delayDestroyTimeoutId=setTimeout(()=>this.destroyElement(),3*e)):this.destroyElement(),this.handleStopped(f.ENDED),this._interval>0&&oe.clearTask(this._interval)}destroyElement(){this.element&&(this._log.debug("destroy element"),this.element.remove(),this.element.src="",this.element.srcObject=null,this.element=null),clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0}pause(){var e;this._log.info("pause"),this._isPausedByUserCall=!0,(e=this.element)==null||e.pause()}resume(){return this._isPausedByUserCall=!1,this.doResume()}doResume(){return this._log.info("resume"),this._isPausedByUserCall||this.isPlaying?Promise.resolve():Ml?this.replay():(this.element&&this.track&&Ve&&We>=128&&(this.element.srcObject=new MediaStream([this.track])),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 tt(this.element,this.element).add(f.PLAYING,e).add(f.ENDED,e).add(f.PAUSE,e).add(f.ERROR,e).add(f.LOADSTART,e).add(f.LOADEDDATA,e).add(f.LOADEDMETADATA,e)}}bindTrackEvents(e=this.track){if(e){let t=this.handleTrackEvent.bind(this);vi==null||vi.create(e,e).add(f.ENDED,t).add(f.MUTE,t).add(f.UNMUTE,t),e.readyState===f.ENDED&&this.handleTrackEvent({type:f.ENDED}),e.muted&&this.handleTrackEvent({type:f.MUTE})}}bindAutoPlayEvent(){S.on(A.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(e=this.track){e&&Le(e)}unbindEvents(){this.element&&Le(this.element),this.unbindTrackEvents(),S.off(A.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case f.PLAYING:br()||(this.isInAutoPlayFailedState=!1),this._isElementPlayingFired=!0,this._log.info(`${this.kind} player is playing`),this.handlePlaying(f.PLAYING),this._interval&&(oe.clearTask(this._interval),this._interval=-1);break;case f.ENDED:this._log.info(`${this.kind} player is ended`),this.handleStopped(f.ENDED);break;case f.PAUSE:this._log.info(`${this.kind} player is paused`),this.handlePaused(f.PAUSE),ge&&(this._interval=oe.run("timeout",()=>{this.element&&this._state==="PAUSED"&&this.doResume()},{delay:3e3}));break;case f.ERROR:if(this.element&&this.element.error){this.handlePaused(f.ERROR);let{code:r,message:s}=this.element.error;this._log.error(`${this.kind} ${this._log.isLocal?"local":"remote"} MediaError code: ${r} message: ${s} userAgent: ${navigator.userAgent}`),se.uploadEvent({log:`stat-${this.kind}-${Ze.PLAYER_ERROR}-${r}-${navigator.userAgent}`,error:this.element.error}),bl||rn?this.emit(ue.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case f.LOADEDDATA:this.kind===f.VIDEO&&this.emit(ue.LOADED_DATA);break;case f.LOADEDMETADATA:this.kind===f.VIDEO&&this.emit(ue.LOADED_META_DATA);break;case f.LOADSTART:this.emit(ue.LOAD_START);break}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then(()=>{this._log.warn("replayByRecreateMediaStream success"),se.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),v.addSuccessEvent({key:this.kind===f.AUDIO?506700:516700})}).catch(()=>{var t;this._log.error("replayByRecreateMediaStream failed"),se.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),v.addFailedEvent({key:this.kind===f.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)=>{Ke(e).then(()=>{this.element&&(this.element.srcObject=null,this.element.srcObject=new MediaStream([this.track]),this._log.warn("recreated mediaStream"),this.element.onerror=()=>{var s,n,a;this._log.warn(`element onerror ${(n=(s=this.element)==null?void 0:s.error)==null?void 0:n.code} fired after recreated mediaStream`),r((a=this.element)==null?void 0:a.error)}),Ke(5e3).then(()=>{var s,n;(!this.isPlaying||(s=this.element)!=null&&s.error)&&r((n=this.element)==null?void 0:n.error),t()})})}).finally(()=>{this.element&&(this.element.onerror=null)})}handleTrackEvent(e){return p(this,null,function*(){switch(e.type){case f.ENDED:this.handleStopped(f.ENDED);break;case f.MUTE:this.handlePaused(f.MUTE);break;case f.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.doResume()),this.element&&!this.element.paused&&this._isElementPlayingFired&&this.handlePlaying(f.UNMUTE));break}})}handlePlaying(e){var t;return this._log.debug("handlePlaying",e),(t=this._playSuccessResolve)==null||t.call(this,e),e}handlePaused(e){return this._log.debug("handlePaused",e),e}handleStopped(e){return this._log.debug("handleStopped",e),e}getElement(){return this.element}};d(mi,"PlayerEvent",ue),M([Mt({settings:{retries:2,timeout:0},onError(e,t,r,s){s[0]=(s[0]||1e3)+1e3,t()}})],mi.prototype,"doReplayByRecreateMediaStream",1),M([ye([],"PLAYING",{sync:!0,success(e){this.emit(ue.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}})],mi.prototype,"handlePlaying",1),M([ye("PLAYING","PAUSED",{ignoreError:!0,sync:!0,success(e){this.emit(ue.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}})],mi.prototype,"handlePaused",1),M([ye([],"STOPPED",{sync:!0,success(e){this.emit(ue.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}})],mi.prototype,"handleStopped",1);var er="trtc_autoplay",gu=`${er}_mask`,bn=`${er}_wrapper`,xp=`${er}_header`,Tu=`${er}_content`,Ac=`${er}_action_wrapper`,Eu=`${er}_question`,Su=`${er}_collapse`,Cc=`${er}_action_confirm`,Up=`${er}_detail`,Vp="#2473E8",Cu="dialog",$T=`${Cu}-show`,WT=`${Cu}-1`,GT=`${Cu}-2`,Fp=!1,Iu=!1,br=()=>Iu,Hp=`${ft}/${Yt()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,Bp=`<br><a href='${Hp}' target='_blank'>${Yt()?"\u5176\u4ED6\u65B9\u6848\uFF1F":"Any other solution?"}</a>`,qT=`${Yt()?`\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${Bp}`:`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. ${Bp}`}`,Au=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(Yt()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!Fp){let i=document.createElement("style");i.innerHTML=`.${gu}{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;}.${gu} div:not(.${Ac}){display:block !important;}.${bn}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${bn} a{color:${Vp};}.${xp}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${Tu}{margin:8px 0;}.${Ac}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${Su}{margin-right:auto;cursor:pointer}.${Eu}{height:100%;line-height:16px;cursor:pointer;}.${Cc}{margin-left:8px;color:#fff;background:${Vp};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${Cc}:hover{opacity:0.9;}.${Su},.${Cc},.${Tu},.${Eu}{font-size:14px;}@media screen and (max-width:750px){.${bn}{width:80vw;}}`,document.head.appendChild(i),Fp=!0}this.addDiaLog()}createDiaLog(){let i=document.createElement("template");i.innerHTML=`<div class="${gu}"><div class='${bn}'><div class='${xp}'>${location.host}</div><div class='${Tu}'>${this.content}</div><div class='${Up}' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">${qT}</div><div class='${Ac}'></div></div></div>`.trim();let e=document.createElement("button");e.className=Cc,e.innerText=Yt()?"\u6062\u590D\u64AD\u653E":"Resume",e.onclick=this.onConfirm.bind(this);let t=document.createElement("div");t.className=Eu,t.innerHTML=`<?xml version="1.0" encoding="UTF-8"?>
|
|
27
|
+
${t.stack}`));let s=Ir.enable?Gi(r,2002,Number(this._configs.sdkAppId)):JSON.stringify(r);this.sendRequest(Wi(this._configs.sdkAppId,mr.LOG),s)}sendRequest(i,e){setTimeout(()=>qi({url:i,body:e,priority:"low"}).catch(()=>{}),2e3)}},se=new _u;var Ni=new WeakMap;function Mt({settings:o={retries:5,timeout:2e3},onError:i,onRetrying:e,onRetryFailed:t}){return function(r,s,n){let a=Ai({retryFunction:n.value,settings:o,onError({error:c,retry:l,reject:u,retryFuncArgs:h}){var m;i?i.call(this,c,()=>{var _;(_=Ni.get(r))!=null&&_.has(s)?l():u(c)},u,h):(m=Ni.get(r))!=null&&m.has(s)?l():u(c)},onRetrying(c,l){var u;Ii(e)&&e.call(this,c,l),(u=Ni.get(r))!=null&&u.has(s)&&(Ni.get(r).get(s).stopRetry=l)},onRetryFailed:t});return n.value=function(...c){let l=Ni.get(r);return l?l.set(s,{args:c}):Ni.set(r,new Map([[s,{args:c}]])),a.apply(this,c).finally(()=>{var u;return(u=Ni.get(r))==null?void 0:u.delete(s)})},n}}function yn({fnName:o,callback:i,validateArgs:e=!0}){return function(t,r,s){let n=s.value;return s.value=function(...a){var c,l;if((c=Ni.get(t))!=null&&c.has(o)){let{stopRetry:u,args:h}=Ni.get(t).get(o),m=!0;if(e){for(let _ of h)if(!a.find(g=>g===_)){m=!1;break}}m&&(i&&i.apply(this,a),u&&u(),(l=Ni.get(t))==null||l.delete(o))}return n.apply(this,a)},s}}var mi=class extends J{constructor(e,t){super(e.id,`${t}-player`);this.options=e;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,"_isPausedByUserCall",!1);d(this,"_pausedRetryCount");d(this,"_isElementPlayingFired",!1);d(this,"_interval");d(this,"_delayDestroyTimeoutId",0);d(this,"_playSuccessResolve");d(this,"_isReplayByRecreateMediaStreamCalled",!1);d(this,"isPlayCalled",!1);d(this,"isInAutoPlayFailedState",!1);this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=$r,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 p(this,null,function*(){if(!this.isPlaying)try{this.isPlayCalled=!0,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=H({key:F.PLAY_FAILED,data:{media:this.kind,error:e}});if(this._log.warn(e),t.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new D({code:I.PLAY_NOT_ALLOWED,message:t})}})}stop(e=0){var t;this.isPlayCalled=!1,this._isElementPlayingFired=!1,this.unbindEvents(),e>0&&!Ft?this._delayDestroyTimeoutId||((t=this.element)==null||t.remove(),this._log.info(`destroy element after 3 * ${e}`),this._delayDestroyTimeoutId=setTimeout(()=>this.destroyElement(),3*e)):this.destroyElement(),this.handleStopped(f.ENDED),this._interval>0&&oe.clearTask(this._interval)}destroyElement(){this.element&&(this._log.debug("destroy element"),this.element.remove(),this.element.src="",this.element.srcObject=null,this.element=null),clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0}pause(){var e;this._log.info("pause"),this._isPausedByUserCall=!0,(e=this.element)==null||e.pause()}resume(){return this._isPausedByUserCall=!1,this.doResume()}doResume(){return this._log.info("resume"),this._isPausedByUserCall||this.isPlaying?Promise.resolve():Ml?this.replay():(this.element&&this.track&&Ve&&We>=128&&(this.element.srcObject=new MediaStream([this.track])),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 tt(this.element,this.element).add(f.PLAYING,e).add(f.ENDED,e).add(f.PAUSE,e).add(f.ERROR,e).add(f.LOADSTART,e).add(f.LOADEDDATA,e).add(f.LOADEDMETADATA,e)}}bindTrackEvents(e=this.track){if(e){let t=this.handleTrackEvent.bind(this);vi==null||vi.create(e,e).add(f.ENDED,t).add(f.MUTE,t).add(f.UNMUTE,t),e.readyState===f.ENDED&&this.handleTrackEvent({type:f.ENDED}),e.muted&&this.handleTrackEvent({type:f.MUTE})}}bindAutoPlayEvent(){S.on(A.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(e=this.track){e&&Le(e)}unbindEvents(){this.element&&Le(this.element),this.unbindTrackEvents(),S.off(A.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case f.PLAYING:br()||(this.isInAutoPlayFailedState=!1),this._isElementPlayingFired=!0,this._log.info(`${this.kind} player is playing`),this.handlePlaying(f.PLAYING),this._interval&&(oe.clearTask(this._interval),this._interval=-1);break;case f.ENDED:this._log.info(`${this.kind} player is ended`),this.handleStopped(f.ENDED);break;case f.PAUSE:this._log.info(`${this.kind} player is paused`),this.handlePaused(f.PAUSE),ge&&(this._interval=oe.run("timeout",()=>{this.element&&this._state==="PAUSED"&&!this._isPausedByUserCall&&this.doResume()},{delay:3e3}));break;case f.ERROR:if(this.element&&this.element.error){this.handlePaused(f.ERROR);let{code:r,message:s}=this.element.error;this._log.error(`${this.kind} ${this._log.isLocal?"local":"remote"} MediaError code: ${r} message: ${s} userAgent: ${navigator.userAgent}`),se.uploadEvent({log:`stat-${this.kind}-${Ze.PLAYER_ERROR}-${r}-${navigator.userAgent}`,error:this.element.error}),bl||rn?this.emit(ue.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case f.LOADEDDATA:this.kind===f.VIDEO&&this.emit(ue.LOADED_DATA);break;case f.LOADEDMETADATA:this.kind===f.VIDEO&&this.emit(ue.LOADED_META_DATA);break;case f.LOADSTART:this.emit(ue.LOAD_START);break}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then(()=>{this._log.warn("replayByRecreateMediaStream success"),se.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),v.addSuccessEvent({key:this.kind===f.AUDIO?506700:516700})}).catch(()=>{var t;this._log.error("replayByRecreateMediaStream failed"),se.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),v.addFailedEvent({key:this.kind===f.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)=>{Ke(e).then(()=>{this.element&&(this.element.srcObject=null,this.element.srcObject=new MediaStream([this.track]),this._log.warn("recreated mediaStream"),this.element.onerror=()=>{var s,n,a;this._log.warn(`element onerror ${(n=(s=this.element)==null?void 0:s.error)==null?void 0:n.code} fired after recreated mediaStream`),r((a=this.element)==null?void 0:a.error)}),Ke(5e3).then(()=>{var s,n;(!this.isPlaying||(s=this.element)!=null&&s.error)&&r((n=this.element)==null?void 0:n.error),t()})})}).finally(()=>{this.element&&(this.element.onerror=null)})}handleTrackEvent(e){return p(this,null,function*(){let t=e.type;switch(this.options.enableLogTrackState&&this._log[t===f.UNMUTE?"info":"warn"](`track ${t}`),t){case f.ENDED:this.handleStopped(f.ENDED);break;case f.MUTE:this.handlePaused(f.MUTE);break;case f.UNMUTE:this.mode>0?this.handlePlaying(this.mode.toString()):this.element&&(this.element.paused&&!this._isPausedByUserCall&&(this._log.warn("track unmuted and element is paused, resume"),yield this.doResume()),this.element&&!this.element.paused&&this._isElementPlayingFired&&this.handlePlaying(f.UNMUTE));break}})}handlePlaying(e){var t;return this._log.debug("handlePlaying",e),(t=this._playSuccessResolve)==null||t.call(this,e),e}handlePaused(e){return this._log.debug("handlePaused",e),e}handleStopped(e){return this._log.debug("handleStopped",e),e}getElement(){return this.element}};d(mi,"PlayerEvent",ue),M([Mt({settings:{retries:2,timeout:0},onError(e,t,r,s){s[0]=(s[0]||1e3)+1e3,t()}})],mi.prototype,"doReplayByRecreateMediaStream",1),M([ye([],"PLAYING",{sync:!0,success(e){this.emit(ue.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}})],mi.prototype,"handlePlaying",1),M([ye("PLAYING","PAUSED",{ignoreError:!0,sync:!0,success(e){this.emit(ue.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}})],mi.prototype,"handlePaused",1),M([ye([],"STOPPED",{sync:!0,success(e){this.emit(ue.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}})],mi.prototype,"handleStopped",1);var er="trtc_autoplay",gu=`${er}_mask`,bn=`${er}_wrapper`,xp=`${er}_header`,Tu=`${er}_content`,Ac=`${er}_action_wrapper`,Eu=`${er}_question`,Su=`${er}_collapse`,Cc=`${er}_action_confirm`,Up=`${er}_detail`,Vp="#2473E8",Cu="dialog",$T=`${Cu}-show`,WT=`${Cu}-1`,GT=`${Cu}-2`,Fp=!1,Iu=!1,br=()=>Iu,Hp=`${ft}/${Yt()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,Bp=`<br><a href='${Hp}' target='_blank'>${Yt()?"\u5176\u4ED6\u65B9\u6848\uFF1F":"Any other solution?"}</a>`,qT=`${Yt()?`\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${Bp}`:`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. ${Bp}`}`,Au=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(Yt()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!Fp){let i=document.createElement("style");i.innerHTML=`.${gu}{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;}.${gu} div:not(.${Ac}){display:block !important;}.${bn}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${bn} a{color:${Vp};}.${xp}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${Tu}{margin:8px 0;}.${Ac}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${Su}{margin-right:auto;cursor:pointer}.${Eu}{height:100%;line-height:16px;cursor:pointer;}.${Cc}{margin-left:8px;color:#fff;background:${Vp};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${Cc}:hover{opacity:0.9;}.${Su},.${Cc},.${Tu},.${Eu}{font-size:14px;}@media screen and (max-width:750px){.${bn}{width:80vw;}}`,document.head.appendChild(i),Fp=!0}this.addDiaLog()}createDiaLog(){let i=document.createElement("template");i.innerHTML=`<div class="${gu}"><div class='${bn}'><div class='${xp}'>${location.host}</div><div class='${Tu}'>${this.content}</div><div class='${Up}' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">${qT}</div><div class='${Ac}'></div></div></div>`.trim();let e=document.createElement("button");e.className=Cc,e.innerText=Yt()?"\u6062\u590D\u64AD\u653E":"Resume",e.onclick=this.onConfirm.bind(this);let t=document.createElement("div");t.className=Eu,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"/>
|
|
31
31
|
<path d="m512 673.7c-17.665 0-32.001-14.336-32.001-31.999v-54.112c0-52.353 40-92.352 75.328-127.65 25.887-25.92 52.672-52.672 52.672-74.017 0-53.343-43.072-96.735-95.999-96.735-53.823 0-95.999 41.536-95.999 94.559 0 17.665-14.336 31.999-32.001 31.999s-32.001-14.336-32.001-31.999c0-87.424 71.775-158.56 160-158.56s160 72.095 160 160.74c0 47.904-36.32 84.192-71.424 119.3-27.84 27.776-56.576 56.512-56.576 82.336v54.112c0 17.665-14.336 32.032-32.001 32.032z" p-id="2033"/>
|
|
32
32
|
</svg>
|
|
33
|
-
`,t.onclick=this.onQuestionClick.bind(this);let r=document.createElement("div");r.className=Su,r.innerText=`${Yt()?"\u8BE6\u60C5 >":"Detail >"}`,r.onclick=this.onCollapseClick.bind(this);let s=i.content.firstChild,n=s.querySelector(`.${Ac}`);return n.appendChild(r),n.appendChild(t),n.appendChild(e),s}addDiaLog(){br()||(Iu=!0,this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${bn}`).onclick=i=>i.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",R.info("show autoplay dialog"),se.uploadEvent({log:$T}))}deleteDialog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null,Iu=!1)}onConfirm(){R.warn("confirm clicked, try resume stream"),S.emit(A.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDialog()}onCollapseClick(){let i=this._dialogNode.querySelector(`.${Up}`);i.style.visibility=`${this._showDetail?"hidden":"visible"}`,i.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||se.uploadEvent({log:WT}),this._isCollapseClicked=!0}onQuestionClick(){window.open(Hp,"_blank"),this._isQuestionClicked||se.uploadEvent({log:GT}),this._isQuestionClicked=!0}},vn=null;function ns(){vn||(vn=new Au)}function $p(){vn&&(vn.deleteDialog(),vn=null)}var it=class o extends mi{constructor(e){super(e,f.VIDEO);d(this,"stat",{});d(this,"_calculateTimeout",-1);d(this,"viewMirror",!1);d(this,"objectFit");d(this,"container");d(this,"canvas");d(this,"shouldRenderAlpha",!1);d(this,"_preSize",{width:0,height:0});d(this,"posterImg");this.mode=e.canvas?1:0,this.container=e.container,this.canvas=e.canvas,T(e.viewMirror)||(this.viewMirror=e.viewMirror),T(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}get isPlaying(){var e;return this._state!=="PLAYING"||this.element&&this.element.paused?!1:((e=this.track)==null?void 0:e.readyState)==="live"&&!this.track.muted}initializeElement(){var t;let e=document.createElement(f.VIDEO);this.track&&this.mode!==2&&(e.srcObject=new MediaStream([this.track])),e.muted=!0,e.setAttribute("id",`video_${this.id}`),e.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),e.setAttribute("autoplay","autoplay"),e.setAttribute("playsinline","playsinline"),this.element=e,_e&&(e.poster="noposter"),(t=this.container)==null||t.appendChild(this.elementToRender),this.bindElementEvents(),this.calculateStat()}get styleAttribute(){let e=`width: 100%; height: 100%; object-fit: ${this.objectFit};${this.shouldRenderAlpha?"":"background-color: black"};`;return this.viewMirror&&(e+="transform: scaleX(-1);"),e}setContainer(e){var t;this.container=e,this.track&&this.elementToRender&&((t=this.container)==null||t.appendChild(this.elementToRender))}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),e&&e.add(f.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(f.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent).add(f.RESIZE,this.handleElementEvent)}handleTrackEvent(e){var t;return e.type===f.MUTE&&((t=this.stat)!=null&&t.fps)&&(this.stat.fps=0),super.handleTrackEvent(e)}handleElementEvent(e){var r,s,n,a,c,l;if(this.mode===2)return;super.handleElementEvent(e);let t=e.type;if(t===f.PAUSE&&(this.container&&!this.container.isConnected&&(this._log.warn(`${this.kind} player has been remove, element ID: ${this.container.id}`),Ke(500).then(()=>{var u;(u=this.container)!=null&&u.isConnected&&(this._pausedRetryCount=$r,this._log.info(`view container ${this.container.id} is in dom, reset pausedRetryCount`))})),this._pausedRetryCount>0&&!br()&&!this._isPausedByUserCall&&(this._log.info(`[${$r-this._pausedRetryCount+1}/${$r}] ${this.kind} player auto resume when paused`),this.doResume(),this._pausedRetryCount--),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){let u=this.element.style.transform;t===f.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=u.replace("scaleX(-1)",""):t===f.LEAVE_PICTURE_IN_PICTURE&&!u.includes("scaleX")&&(this.element.style.transform=`${u} scaleX(-1)`)}t===f.RESIZE&&(this._preSize.height!==((r=this.element)==null?void 0:r.videoHeight)||this._preSize.width!==((s=this.element)==null?void 0:s.videoWidth))&&(this._log.info(`video size changed to ${(n=this.element)==null?void 0:n.videoWidth}x${(a=this.element)==null?void 0:a.videoHeight}`),this._preSize.height=((c=this.element)==null?void 0:c.videoHeight)||0,this._preSize.width=((l=this.element)==null?void 0:l.videoWidth)||0,this.emit(ue.RESIZE,{newWidth:this._preSize.width,newHeight:this._preSize.height}))}setCanvas(e,t=1){var r,s,n,a;this.canvas!==e&&((r=this.canvas)==null||r.remove(),e==null||e.setAttribute("style",this.styleAttribute),this.canvas=e,this.mode=e?t:0,this.mode===2&&this.setTrack(e.captureStream().getVideoTracks()[0]),e?((s=this.element)==null||s.remove(),(n=this.container)==null||n.appendChild(e)):this.element&&((a=this.container)==null||a.appendChild(this.element)))}setAttr(e){let t=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},e);t.style=Object.assign({width:"100%",height:"100%"},t.style),super.setAttr(t)}get mirror(){return this.viewMirror}setRect(e,t){this.elementToRender&&(this.elementToRender.style.width=`${e}px`,this.elementToRender.style.height=`${t}px`)}setViewMirror(e){this.elementToRender&&(this.elementToRender.style.transform=e?"scaleX(-1)":""),this.viewMirror=e}setObjectFit(e){this.elementToRender&&(this.elementToRender.style.objectFit=`${e}`),this.objectFit=e}setPoster(e,t=!1){return new Promise(r=>{if(this.element)if(this._log.info("setPoster",e.slice(0,10)),this.element.poster=e,t&&(Re||K)){if(e==="")this.removePosterImg();else if(!this.posterImg){let s=document.createElement("img");s.src=e,s.style=`position:absolute;top:0;left:0;${this.styleAttribute}`,s.onload=()=>p(this,null,function*(){var n;s.decode&&(yield s.decode()),this.posterImg=s,(n=this.container)==null||n.appendChild(s),r()})}}else r()})}removePosterImg(){this.posterImg&&(this.posterImg.remove(),URL.revokeObjectURL(this.posterImg.src),delete this.posterImg)}pause(){return p(this,null,function*(){return(Ve&&We>=128||K||Re)&&(yield this.setPoster(this.getVideoFrame(),!0)),Pe(o.prototype,this,"pause").call(this)})}resume(){return this.posterImg&&this.setPoster("",!0),super.resume()}stop(e=0){var t;super.stop(e),(t=this.canvas)==null||t.remove(),this.removePosterImg()}play(){return this.element?this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender):this.initializeElement(),this.mode===2?Promise.resolve():super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(ue.MEDIA_TRACK_CHANGED,e),e!==null&&(this.bindTrackEvents(),this.element&&this.mode!==2&&(this.element.srcObject=new MediaStream([e]),this.element.remove()),this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender)))}getVideoFrame(){if(this.canvas)return this.canvas.toDataURL("image/png");if(!this.element)return"";let e=document.createElement("canvas");return e.width=this.element.videoWidth,e.height=this.element.videoHeight,e.getContext("2d").drawImage(this.element,0,0),e.toDataURL("image/png")}getElement(){return this.element}calculateStat(){try{if(Ki()&&this.element&&this._calculateTimeout<0){let e=0,t=null,r=(s,n)=>{this.stat.width=n.width,this.stat.height=n.height,t&&(this.stat.fps=Math.round((n.presentedFrames-t.presentedFrames)/(s-e)*1e3)),e=s,t=n,this._calculateTimeout=-1,this.element&&(this._calculateTimeout=setTimeout(()=>{var a;return(a=this.element)==null?void 0:a.requestVideoFrameCallback(r)},2e3))};this.element.requestVideoFrameCallback(r)}}catch(e){this._log.warn("init stat failed",e)}}enterFullscreen(){return p(this,null,function*(){let e=this.elementToRender;if(!e)throw this._log.warn("no element to render, cannot enter fullscreen"),new Error("No element available for fullscreen");try{if(e.requestFullscreen)yield e.requestFullscreen();else if(e.webkitRequestFullscreen)yield e.webkitRequestFullscreen();else if(e.webkitEnterFullscreen)yield e.webkitEnterFullscreen();else if(e.mozRequestFullScreen)yield e.mozRequestFullScreen();else if(e.msRequestFullscreen)yield e.msRequestFullscreen();else throw this._log.warn("fullscreen API not supported"),new Error("Fullscreen API not supported");this._log.info("entered fullscreen mode")}catch(t){throw this._log.error("failed to enter fullscreen:",t),t}})}exitFullscreen(){return p(this,null,function*(){try{if(document.exitFullscreen)yield document.exitFullscreen();else if(document.webkitExitFullscreen)yield document.webkitExitFullscreen();else if(document.mozCancelFullScreen)yield document.mozCancelFullScreen();else if(document.msExitFullscreen)yield document.msExitFullscreen();else throw this._log.warn("exit fullscreen API not supported"),new Error("Exit fullscreen API not supported");this._log.info("exited fullscreen mode")}catch(e){throw this._log.error("failed to exit fullscreen:",e),e}})}isFullscreen(){let e=this.elementToRender;return e?(document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement)===e:!1}toggleFullscreen(){return p(this,null,function*(){this.isFullscreen()?yield this.exitFullscreen():yield this.enterFullscreen()})}enterPictureInPicture(){return p(this,null,function*(){if(!this.element)throw new Error("No video element available for picture-in-picture");if(this.canvas&&this.mode!==1)throw new Error("Picture-in-picture is not supported for canvas-only mode");let{element:e}=this;try{if(this._log.warn(!!e.requestPictureInPicture,!!e.webkitSetPresentationMode),e.requestPictureInPicture){this._log.info("requestPictureInPicture");let t=yield e.requestPictureInPicture();return this._log.info("entered picture-in-picture mode"),t}if(e.webkitSetPresentationMode)return this._log.info("webkitSetPresentationMode"),yield e.webkitSetPresentationMode("picture-in-picture"),this._log.info("entered picture-in-picture mode (webkit)"),{};throw new Error("Picture-in-picture API not supported")}catch(t){throw this._log.error("failed to enter picture-in-picture:",t.name,t.message),t}})}exitPictureInPicture(){return p(this,null,function*(){try{if(document.pictureInPictureElement&&document.exitPictureInPicture)yield document.exitPictureInPicture(),this._log.info("exited picture-in-picture mode");else if(this.element&&this.element.webkitSetPresentationMode)yield this.element.webkitSetPresentationMode("inline"),this._log.info("exited picture-in-picture mode (webkit)");else throw this._log.warn("exit picture-in-picture API not supported or not in PiP mode"),new Error("Exit picture-in-picture API not supported or not in PiP mode")}catch(e){throw this._log.error("failed to exit picture-in-picture:",e),e}})}isPictureInPicture(){if(!this.element)return!1;let{element:e}=this;return document.pictureInPictureElement?document.pictureInPictureElement===e:e.webkitPresentationMode?e.webkitPresentationMode==="picture-in-picture":!1}togglePictureInPicture(){return p(this,null,function*(){this.isPictureInPicture()?yield this.exitPictureInPicture():yield this.enterPictureInPicture()})}};function tr(o,i){return p(this,null,function*(){if(!o.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield o.audioWorklet.addModule(i),R.info("worklet addModule success")}catch(e){throw R.info(`worklet addModule catch error. ${e.message}`),e}})}var Nn;typeof AudioContext!="undefined"?Nn=AudioContext:typeof webkitAudioContext!="undefined"?Nn=webkitAudioContext:typeof mozAudioContext!="undefined"&&(Nn=mozAudioContext);var vu=1500,rt,Wp=-1,Rc=0,Dn=-1,bu=!1,Gp=0,qp=-1,Jp=-1;jp();function jp(){try{if(rt)return;rt=new Nn({sampleRate:48e3}),rt.onstatechange=()=>{R.info(`context state: ${rt.state}${rt.state!=="running"?` visibilityState: ${document.visibilityState}`:""}`),as()},clearTimeout(Wp)}catch(o){R.error(`initAudioContext failed: ${o} typeof AudioContextClass: ${typeof Nn}`),Wp=setTimeout(jp,1e3)}}var as=()=>{rt.state==="suspended"?(Rc=U(),JT(),vr(),document.addEventListener("click",as)):rt.state==="interrupted"?vr():(Rc&&(v.addNumber({key:507800,value:U()-Rc,split:[0,500,1e3,1500,2e3,3e3,4e3,5e3,1e4,3e4],max:6e4}),Rc=0),jT(),document.removeEventListener("visibilitychange",as),document.removeEventListener("click",as))},Ru=0,yu=-1;function vr(){return new Promise((o,i)=>{if(rt.state==="running")return o();Date.now()-Ru<1e3?(clearTimeout(yu),yu=setTimeout(()=>{Ru=Date.now(),rt.resume().then(o,i)},1e3)):(clearTimeout(yu),Ru=Date.now(),rt.resume().then(o,i))}).catch(o=>{R.warn(`context resume failed: ${o}`),document.addEventListener("visibilitychange",as)})}document.addEventListener("click",as);function JT(){Dn===-1&&(Dn=setTimeout(()=>{rt.state==="suspended"&&(bu=!0,S.emit("155",{isSuspended:!0}))},vu))}function jT(){Dn!==-1&&(clearTimeout(Dn),Dn=-1,bu&&(bu=!1,S.emit("155",{isSuspended:!1})))}function Xp(){if(!ge||Jp!==-1)return;let o=()=>{U()-Gp<500||(rt&&rt.state==="running"&&rt.currentTime===qp&&(R.warn("context is fake running, auto resume"),rt.suspend().catch(i=>{R.warn(`context suspend failed: ${i}`)})),qp=rt.currentTime,Gp=U())};Jp=setInterval(()=>{o()},2e3),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&o()})}var Ee=o=>rt;var xe=class{constructor(i){this.name=i;d(this,"node");d(this,"node2");d(this,"pre",new Set);d(this,"next",new Set);d(this,"context");d(this,"connectedNodes",new Set);d(this,"nextInputChannelMap",new Map);d(this,"_channelCount",1)}get channelCount(){return this._channelCount}set channelCount(i){this._channelCount=i,this.setChannelCount(this.node,i),this.setChannelCount(this.node2,i),this.next.forEach(e=>e.channelCount=i)}setChannelCount(i,e){!i||i instanceof ScriptProcessorNode||(i.channelCountMode="explicit",i.channelCount=e||this.channelCount||1)}setContext(i){this.context=i,this.node&&i.addMixWeight()}removeContext(){var i;this.node&&((i=this.context)==null||i.reduceMixWeight()),delete this.context}replaceNode(i){var e;if(i!==this.node)try{this.node?this._disconnect():(e=this.context)==null||e.addMixWeight(),this.node=i,this.setChannelCount(this.node),this.preNodeReconnect(),this.reconnect()}catch(t){R.error(t)}}setNode(i,e){var t;if(!this.node)try{(t=this.context)==null||t.addMixWeight(),this.node=i,this.setChannelCount(this.node),e&&(this.node2=e,this.setChannelCount(this.node2)),this.preNodeReconnect(),this.reconnect(),v.addSuccessEvent({key:502701})}catch(r){R.error(r),v.addFailedEvent({key:502701,error:r})}}deleteNode(){var i;if(this.node)try{this._disconnect(),delete this.node,delete this.node2,(i=this.context)==null||i.reduceMixWeight(),this.preNodeReconnect(),v.addSuccessEvent({key:502702})}catch(e){R.error(e),v.addFailedEvent({key:502702,error:e})}}preNodeReconnect(){this.pre.forEach(i=>{i.node?i.reconnect():i.preNodeReconnect()})}connectNext(i){this.next.forEach(e=>{let t=this.nextInputChannelMap.get(e);i._connect(e.node,t)||e.connectNext(i)})}_connect(i,e=0){return!this.node||!i?!1:((this.node2||this.node).connect(i,0,e),this.connectedNodes.add(i),!0)}_disconnect(){this.connectedNodes.forEach(i=>{var e;return(e=this.node2||this.node)==null?void 0:e.disconnect(i)}),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(i,e=0){return this.next.add(i),i.pre.add(this),this.nextInputChannelMap.set(i,e),i}},yc=class extends xe{constructor(e=256){super();this.fftSize=e;d(this,"dataArray",new Uint8Array(0))}setNode(e){e.fftSize=this.fftSize,this.dataArray=new Uint8Array(e.frequencyBinCount),super.setNode(e)}getByteTimeDomainData(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),this.dataArray}get level(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),Math.max(...this.dataArray)/128-1}get timeDomainPathData(){let e=this.getByteTimeDomainData(),t=1,r=0,s=0,n=`M${r},${s}`;for(let a=0;a<e.length;a++)s=e[a]/128*100/2,n+=`L${r},${s}`,r+=t;return n}},Mn=class{constructor(){d(this,"source",new xe);d(this,"gain",new xe);d(this,"destination",new xe)}get volume(){var i;return((i=this.gain.node)==null?void 0:i.gain.value)||1}setVolume(i){if(i===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(Ee().createGain()),this.gain.node.gain.value=i}replaceSource(i){let e=On(i);e&&this.source.replaceNode(e)}get track(){var i;return(i=this.stream)==null?void 0:i.getAudioTracks()[0]}get stream(){var i;return(i=this.destination.node)==null?void 0:i.stream}},cs=class extends Mn{constructor(e){super();this.context=e;d(this,"aec",new xe("aec"));d(this,"mixNode",new xe("mixNode"));d(this,"silentNode",new xe("silentNode"));d(this,"denoiser",new xe("denoiser"));d(this,"voiceChanger",new xe("voiceChanger"));this.source.pipeTo(this.aec).pipeTo(this.denoiser).pipeTo(this.voiceChanger).pipeTo(this.gain).pipeTo(this.destination),this.silentNode.pipeTo(this.mixNode).pipeTo(this.aec,1)}get isProcessEnabled(){return this.aec.node||this.denoiser.node||this.voiceChanger.node||this.gain.node}connect(){this.context.inputs.has(this)||(this.destination.setNode(this.context.destination),this.source.setContext(this.context),this.aec.setContext(this.context),this.silentNode.setContext(this.context),this.mixNode.setContext(this.context),this.denoiser.setContext(this.context),this.voiceChanger.setContext(this.context),this.gain.setContext(this.context),this.context.inputs.add(this))}disconnect(){this.context.inputs.has(this)&&(this.destination.deleteNode(),this.source.removeContext(),this.aec.removeContext(),this.silentNode.removeContext(),this.mixNode.removeContext(),this.denoiser.removeContext(),this.voiceChanger.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.aec.deleteNode(),this.silentNode.deleteNode(),this.mixNode.deleteNode(),this.denoiser.deleteNode(),this.voiceChanger.deleteNode(),this.source.deleteNode(),this.disconnect()}setVolume(e){if(e===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(this.context.audioContext.createGain()),this.gain.node.gain.value=e}},bc=class{constructor(){d(this,"audioContext",Ee("audio-mixer"));d(this,"destination",this.audioContext.createMediaStreamDestination());d(this,"inputs",new Set);d(this,"mixWeight",0);this.destination.channelCount=1}addMixWeight(i=1){this.mixWeight+=i,this.mixWeight-1===i+1>>1&&this.mixOnChange()}reduceMixWeight(i=1){this.addMixWeight(-i)}close(){this.inputs.forEach(i=>i.remove())}get mixTrack(){return this.destination.stream.getAudioTracks()[0]}},zp=new WeakMap;function On(o){try{let i=zp.get(o);if(i)return i;let e=Ee();if(o instanceof HTMLAudioElement)i=e.createMediaElementSource(o);else if(o instanceof MediaStreamTrack)i=e.createMediaStreamSource(new MediaStream([o]));else return o;return zp.set(o,i),i}catch(i){if(K&&i instanceof Error&&i.name==="NotSupportedError")R.warn(i);else throw i}}var Ot=class Ot{constructor(i){d(this,"_volume",0);d(this,"_volumeDb",0);d(this,"_log");d(this,"_scriptProcessorNode",null);d(this,"_audioWorkletNode",null);d(this,"_interval",200);d(this,"ready",this.preload());let{log:e}=i;this._log=e,S.on(A.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-Ot.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!Ot.workletReady){let i='class VolumeMeterWorklet extends AudioWorkletProcessor{constructor(){super(),this.volume=0,this.intervalTime=200,this.tick=200,this.isStop=!1,this.cache=[],this.sentFirstInfo1=!1,this.unmute=!1,this.port.onmessage=t=>{var e=t.data;switch(e.name){case"chunk":this.cache.push(...e.data),this.sentFirstInfo1||(this.port.postMessage({cl:e.data.length}),this.sentFirstInfo1=!0);break;case"setIntervalTime":this.intervalTime=e.intervalTime;break;case"unmute":this.unmute=!0;break;case"stop":this.isStop=!0}}}process(t,s){t=t[0],s=s[0];if(t||s){if(this.isStop)return!1;var i=s&&s[0]?s[0].length:0,h=this.cache.length,a=(i<h?(s[0].set(this.cache.slice(0,i)),this.cache=this.cache.slice(i)):this.unmute&&s[0].set(t[0]),(i<h?s:t)[0]);if(a){let e=0;for(let t=0;t<a.length;++t)e=Math.max(Math.abs(a[t]),e);s=a.reduce((t,e)=>t+e*e,0)/a.length;this.volume=e,this.tick-=a.length,this.tick<0&&(this.tick+=this.intervalTime/1e3*sampleRate,this.port.postMessage({volume:this.volume,volumeDb:Math.max(10*Math.log10(s)+100,0)/100,cacheLen:h,outputLen:i}))}}return!0}}registerProcessor("volume-meter",VolumeMeterWorklet);';Ot.workletReady=tr(Ot.audioContext,URL.createObjectURL(new Blob([i],{type:"application/javascript"})))}return Ot.workletReady.then(()=>this.initAudioWorklet()).catch(i=>(this._log.error(`volumeMeter preload error: ${i}`),this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(Ot.audioContext,"volume-meter");let i=!1;this._audioWorkletNode.port.onmessage=e=>{Ot.lastMessageTime=Date.now(),this._volume=e.data.volume||0,this._volumeDb=e.data.volumeDb||0,!i&&e.data.cacheLen&&e.data.outputLen&&(this._log.warn("worklet play success"),i=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(i){this._log.error(`volumeMeter init audio worklet error: ${i}`),se.logFailedEvent({userId:this._log.userId,eventType:Ze.LOAD_WORKLET,error:i}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=Ee("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=i=>{Ot.lastMessageTime=Date.now();let e=i.inputBuffer.getChannelData(0),t=0;for(let r=0;r<e.length;++r)t+=e[r]*e[r];this._volume=Math.sqrt(t/e.length)||0}}catch(i){this._log.error(`volumeMeter init script processor error: ${i}`)}}destroy(){this._scriptProcessorNode&&(this._scriptProcessorNode.onaudioprocess=null),this._audioWorkletNode&&(this._audioWorkletNode.port.postMessage({name:"stop"}),this._audioWorkletNode.port.onmessage=null),this._audioWorkletNode=null,this._scriptProcessorNode=null,S.off(A.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}getVolumeDb(){return Math.floor(this._volumeDb*100)}handleAudioLevelInterval(i){var t;let{interval:e}=i;this._interval=e,(t=this._audioWorkletNode)==null||t.port.postMessage({name:"setIntervalTime",intervalTime:e})}};d(Ot,"lastMessageTime",0),d(Ot,"audioContext",Ee("volume-meter")),d(Ot,"workletReady");var vc=Ot,kn=class extends xe{constructor(e){super();d(this,"_volumeMeter");this._volumeMeter=new vc(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return p(this,null,function*(){yield this._volumeMeter.preload(),this.setNode(this._volumeMeter.node)})}getCalculatedVolume(){return this._volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this._volumeMeter.getInternalAudioLevel()}getVolumeDb(){return this._volumeMeter.getVolumeDb()}write(e){if(this.node){let t=e.allocationSize({planeIndex:0}),r=new Float32Array(t>>2);e.copyTo(r,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:r},[r.buffer]),e.close()}}},so=vc;var Kp=qe(at(),1);var Yp=o=>i=>i.deviceId===o;var Pn=class{constructor(i,e){d(this,"kind");d(this,"type");d(this,"devices",[]);this.kind=i,this.type=e}update(i,e){let t=i.filter(r=>r.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);if(this.devices.length===1&&ls(this.devices[0])){this.devices=t;return}e&&(t.forEach(r=>{if(r.deviceId&&!this.devices.find(Yp(r.deviceId))){let s=`${this.kind}${this.type}Added`;R.warn(`${s}: ${JSON.stringify(r)}`),e.emit(s,r)}}),this.devices.forEach(r=>{if(r.deviceId&&!t.find(Yp(r.deviceId))){let s=`${this.kind}${this.type}Removed`;R.warn(`${s}: ${JSON.stringify(r)}`),e.emit(s,r)}})),this.devices=t}hasDevice(i){return!!this.devices.find(e=>e.deviceId===i)}},Nu=class extends Kp.EventEmitter{constructor(){super();d(this,"audioInputs",new Pn(f.AUDIO,"Input"));d(this,"videoInputs",new Pn(f.VIDEO,"Input"));d(this,"audioOutputs",new Pn(f.AUDIO,"Output"));this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||oe.run("interval",()=>{this.update()},{delay:1e4}))}init(){ds().then(e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)})}update(){return p(this,arguments,function*(e=0){let t=yield ds(e);return this.audioInputs.update(t,this),this.videoInputs.update(t,this),this.audioOutputs.update(t,this),this})}hasBlueTooth(){var t;if(((t=Ee())==null?void 0:t.outputLatency)*1e3>150)return!0;let e=["bluetooth","air","wireless","bt","tws","buds","headset","headphone"];return this.audioOutputs.devices.some(r=>e.some(s=>r.label.toLowerCase().includes(s)))||this.audioInputs.devices.some(r=>e.some(s=>r.label.toLowerCase().includes(s)))}},be=xs||Do?null:new Nu;function ls(o){return o.deviceId===o.groupId&&o.groupId===""}function ds(){return p(this,arguments,function*(o=0){if(Zi()||!pc())return[];let i=yield navigator.mediaDevices.enumerateDevices();if(o!==0){let e={audio:!1,video:!1};if(i.forEach(t=>{ls(t)&&(t.kind===f.AUDIO_INPUT?e.audio=!0:t.kind===f.VIDEO_INPUT&&(e.video=!0))}),o===2&&(e.audio=!1),o===1&&(e.video=!1),e.audio||e.video){let t;try{t=yield navigator.mediaDevices.getUserMedia(e),e.audio&&vr()}catch(r){R.debug("capture before getDevices failed: ",r)}i=yield navigator.mediaDevices.enumerateDevices(),t==null||t.getTracks().forEach(r=>r.stop())}}return i.map((e,t)=>{let r={kind:e.kind,deviceId:e.deviceId,groupId:e.groupId,label:e.label||`${e.kind}_${t}`};return e.deviceId.length>0&&Du.add(`${e.deviceId}_${e.kind}`),e.getCapabilities&&(r.getCapabilities=()=>e.getCapabilities()),r})})}function It(o=!1){return be.update(o?1:0).then(i=>i.audioInputs.devices)}function At(o=!1){return be.update(o?2:0).then(i=>i.videoInputs.devices)}var Zp=!1;function ef(){return p(this,null,function*(){try{Zp||(Zp=!0,R.info(`speakers:${(yield Nr()).map(o=>` ${o.deviceId.slice(0,8)}: ${o.label}`)}`))}catch(o){}})}function Nr(o=!1){return p(this,null,function*(){return(ge||Re)&&(o=!1),be.update(o?1:0).then(i=>i.audioOutputs.devices)})}var Du=new Set;function tf(o){if(o instanceof CanvasCaptureMediaStreamTrack||!(o instanceof MediaStreamTrack))return!1;let i=o.label.toLocaleLowerCase();if(i.includes("camera")||i.includes("webcam"))return!0;let t=`${((o==null?void 0:o.getSettings())||{}).deviceId}_${f.VIDEO_INPUT}`;return!!Du.has(t)}function rf(o){if(o instanceof CanvasCaptureMediaStreamTrack||!(o instanceof MediaStreamTrack))return!1;let i=o.label.toLocaleLowerCase();if(i.includes("mic")||i.includes("\u9EA6\u514B\u98CE"))return!0;let t=`${((o==null?void 0:o.getSettings())||{}).deviceId}_${f.AUDIO_INPUT}`;return!!Du.has(t)}function Mu(o,i){return p(this,null,function*(){let t=(yield It()).find(r=>r.deviceId===Wr);return!i&&(t==null?void 0:t.groupId)===o||(t==null?void 0:t.groupId)===o&&t.label===i})}function of(s){return p(this,arguments,function*({newDeviceId:o,oldDeviceId:i,oldGroupId:e,oldLabel:t,kind:r}){return o!==i?!1:r===f.AUDIO&&o===Wr?yield Mu(e,t):!0})}var Nc,Ou=class extends Mn{constructor(e){super();this.log=e;d(this,"volumeMeter");d(this,"volumeMeterAfter3A");d(this,"volumeDestination");d(this,"analyser",new yc);this.volumeMeter=new kn({log:this.log}),this.volumeMeterAfter3A=new kn({log:this.log}),this.volumeDestination=new xe,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},us=class o extends mi{constructor(e){super(e,f.AUDIO);d(this,"_outputDeviceId");d(this,"_volume",1);d(this,"_destination",Ee("player").createMediaStreamDestination());d(this,"pipeline");d(this,"volumeMeterMode","worklet");d(this,"enableVolumeControlInIOS");this.enableVolumeControlInIOS=e.enableVolumeControlInIOS,this.mode=0,e.url&&(this.url=e.url),this.pipeline=new Ou(this._log)}setTrack(e){}get duration(){var e;return Math.floor((((e=this.element)==null?void 0:e.duration)||0)*1e3)}get currentTime(){var e;return Math.floor((((e=this.element)==null?void 0:e.currentTime)||0)*1e3)}set currentTime(e){this.element&&(this.element.currentTime=e/1e3)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(e){if((Tt==="15.2"||Tt==="15.3"||Tt==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}let r=Nc||new Audio;r.setAttribute("autoplay","autoplay"),r.srcObject=this.getMediaStream(),r.muted=this.muted,this.url&&(r.crossOrigin="anonymous",r.src=this.url),this.element=r,z(e)&&(this.element.volume=Math.min(Math.max(e,0),1)),r===Nc&&(Nc=void 0),this.options.enableTimeupdateEvent&&(this.element.ontimeupdate=()=>this.emit(ue.TIME_UPDATE,this.currentTime)),this.bindElementEvents()}play(e){return p(this,null,function*(){if(!(!this.track&&!this.url))return!this.pipeline.source.node&&this.track&&this.pipeline.replaceSource(this.track),this.element||this.initializeElement(e==null?void 0:e.volume),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),this.volumeMeterMode==="worklet"?(this.pipeline.volumeMeter.init(),this.pipeline.volumeMeterAfter3A.init()):this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(Ee("player").createAnalyser()),ef(),Pe(o.prototype,this,"play").call(this)})}stop(e=0){this.pipeline.destroy(),super.stop(e)}setVolume(e){this._volume=e,this.element&&(this.element.volume=e)}setSinkId(e){return p(this,null,function*(){var t,r;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield(r=(t=this.element).setSinkId)==null?void 0:r.call(t,e))})}get useDestination(){return!!this.pipeline.stream}setLoop(e){this.element&&(this.element.loop=e)}getAudioLevel(){return this.pipeline.volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this.pipeline.volumeMeter.getInternalAudioLevel()}getInternalAudioLevelAfter3A(){return this.pipeline.volumeMeterAfter3A.getInternalAudioLevel()}},Dc=class extends us{setTrack(i){this.track!==i&&(this.unbindTrackEvents(),this.track=i,this.emit(ue.MEDIA_TRACK_CHANGED,i),i&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([i]))))}},hs=class extends us{constructor(e){super(e);d(this,"_sourceElement");d(this,"_output",new xe);this.pipeline.source.pipeTo(this.pipeline.gain),this.pipeline.gain.pipeTo(this.pipeline.volumeMeter).pipeTo(this._output),this.pipeline.gain.pipeTo(this.pipeline.destination)}setOutput(){this.mode=1,this._output.setNode(Ee("player").destination)}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var t,r,s;((r=(t=this.element)==null?void 0:t.error)==null?void 0:r.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(ue.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([e]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e])),this.pipeline.source.channelCount=((s=e.getSettings())==null?void 0:s.channelCount)||1,this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){if(this._volume=e,this.useDestination)this.pipeline.setVolume(e),this._log.info(`set pipeline volume: ${e}`);else if(e<=1&&!ge)this.element?(this._log.info(`set element volume: ${e}`),this.element.volume=e):this._log.info("set element volume: no element");else{if(ge)if(this.enableVolumeControlInIOS)Xp();else return;if(K&&!this.pipeline.source.node){this._log.warn("set pipeline volume failed: no source node");return}this._log.info(`start set pipeline volume: ${e}`),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),Le(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play())}}stop(e=0){this.pipeline.destroy();let t=this._sourceElement||this.element;t&&Ft&&(Nc=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}};var no=class extends J{constructor({userId:e,sdkAppId:t,mediaType:r,room:s,PlayerClass:n=r===1?hs:it}){var a;super();d(this,"id",cn());d(this,"userId","");d(this,"isRemote");d(this,"mediaType");d(this,"room");d(this,"user");d(this,"_log");d(this,"_inputTrack");d(this,"_outputTrack");d(this,"isPlayCalled");d(this,"container",null);d(this,"player");d(this,"subVideoPlayerMap");d(this,"muted",!1);d(this,"abortCtrl");d(this,"objectFit","cover");d(this,"mirror");d(this,"rotation");d(this,"isScreen",!1);d(this,"manager");d(this,"trackSettings");d(this,"isFirstVideoFrameEmitted",!1);this.userId=e||"",this.mediaType=r,this._log=R.createLogger({parent:s==null?void 0:s.getLogger(),id:`${this.kind[0]}t`,userId:(a=s||this.room)==null?void 0:a.userId,remoteUserId:this instanceof pi?void 0:this.userId,sdkAppId:t,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof pi}),this.player=new n({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log,enableVolumeControlInIOS:s==null?void 0:s.enableVolumeControlInIOS}),this.player.on(ue.PLAYER_STATE_CHANGED,c=>{if(S.emit(A.PLAYER_STATE_CHANGED,O({track:this},c)),this.emit("player-state-changed",c),c.state==="PLAYING"&&this.room){let l=!0;for(let{remoteAudioTrack:u,remoteVideoTrack:h,remoteAuxiliaryTrack:m}of[...this.room.remotePublishedUserMap.values()])if(u.isAvailable&&!u.player.isPlaying||h.isAvailable&&!h.player.isPlaying||m.isAvailable&&!m.player.isPlaying){l=!1;break}l&&br()&&$p()}}),this.kind===f.VIDEO&&(this.player.on(ue.LOADED_DATA,()=>{this.emitFirstVideoFrameEvent(ue.LOADED_DATA),S.emit(A.VIDEO_LOADED_DATA,{track:this})}),this.player.on(ue.LOADED_META_DATA,()=>{this.emitFirstVideoFrameEvent(ue.LOADED_META_DATA)}),this.player.on(ue.MEDIA_TRACK_CHANGED,c=>{var l;(l=this.subVideoPlayerMap)==null||l.forEach(u=>u.setTrack(c))}),this.player.on(ue.RESIZE,c=>{this.emitFirstVideoFrameEvent(ue.RESIZE),this.emit("video-size-changed",O({userId:this.userId,streamType:this.mediaType===2?"auxiliary":"main"},c))})),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(ue.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||R}get kind(){return this.mediaType===1?f.AUDIO:f.VIDEO}get isAudio(){return this.kind===f.AUDIO}get strMediaType(){return this.mediaType===4?f.VIDEO:this.mediaType===2?f.SCREEN:f.AUDIO}get streamType(){return(this.mediaType&2)===0?"main":"auxiliary"}get isMediaTrackActive(){return this.mediaTrack?!this.mediaTrack.muted&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled:!1}play(e,t){return p(this,null,function*(){let r=Ie(e)?e[0]:e;if(this.isPlayCalled){this.log.info(`play update options: ${JSON.stringify(t)}`),t&&!T(t.muted)&&this.setPlayerMute(t.muted),t&&!T(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof it&&(this.player.setObjectFit(this.objectFit),this.container!==r&&r&&(this.container=r,this.player.setContainer(r)),Ie(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t)));return}if(t&&!T(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===f.VIDEO)&&this.setPlayerMute(!0),t&&!T(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof it&&(this.player.setObjectFit(this.objectFit),t&&!T(t.poster)&&this.player.setPoster(t.poster)),this.isPlayCalled=!0,r&&(this.container=r,this.player instanceof it&&this.player.setContainer(r)),S.emit(A.PLAY_TRACK_START,{track:this}),!this._outputTrack){this.log.info("play has not mediaTrack, abort");return}this._log.info(`play with options: ${JSON.stringify(t)}`);try{this.player.setTrack(this.playerMediaTrack),yield this.player.play(t),Ie(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(s){throw this.handleAutoPlayFailed(s),s}})}setMirror(e,t){if(this.isScreen||this.kind!==f.VIDEO||T(e)||e===this.mirror)return;this.mirror=e;let r=this.player;t&&(r=t);let s=this.manager;if(he(this.mirror)){r.setViewMirror(this.mirror),!this.isRemote&&s&&(s.mirror=!1);return}switch(this.mirror){case"view":{s&&(s.mirror=!1),r.setViewMirror(!0);break}case"publish":{s&&(s.mirror=!0),r.setViewMirror(!0);break}case"both":s&&(s.mirror=!0),r.setViewMirror(!1)}}playSubContainer(e,t){return p(this,null,function*(){if(!this._outputTrack||this.kind===f.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((s,n)=>{var a;e.find(c=>n===c)||(s.stop(),(a=this.subVideoPlayerMap)==null||a.delete(n))});for(let[s,n]of e.entries()){let a=this.subVideoPlayerMap.get(n);a?t&&(T(t.objectFit)||a.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new it({id:this.userId||this.id,track:this.playerMediaTrack,container:n,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:`vp-sub${s+1}`})}))}let r=[...this.subVideoPlayerMap.values()];for(let s of r)s.setViewMirror(this.player.mirror),yield s.play()})}setAudioOutput(e){return this.player.setSinkId(e)}setAudioVolume(e){this.player.setVolume(e)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var e;return((e=this.player)==null?void 0:e.getInternalAudioLevel())||0}stop(e=!1){this.isPlayCalled&&(this.isPlayCalled=!1,this.isFirstVideoFrameEmitted=!1,this.player&&(this.log.info(`stop ${this.kind} player`),this.player.stop(Sl(this)&&!e?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(t=>{t.stop()}),this.container=null)}resume(){return p(this,null,function*(){var e;this.isPlayCalled&&(yield(e=this.player)==null?void 0:e.resume())})}close(){this.log.info("close"),this.isPlayCalled&&this.stop(!0)}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),S.emit(e?A.TRACK_MUTED:A.TRACK_UNMUTED,{track:this})}setPlayerMute(e){this.player.setMuted(e)}get mediaTrack(){return this._inputTrack||null}get outMediaTrack(){return this._outputTrack||null}get playerMediaTrack(){return this.outMediaTrack}installTrackEvent(e){tt(e,e).add(f.MUTE,this.onTrackMuted).add(f.UNMUTE,this.onTrackUnmuted).add(f.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===f.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){Le(e)}setInputMediaStreamTrack(e){var r;let t=this._inputTrack;if(e!==t)return this._inputTrack=e,this.trackSettings=(r=e.getSettings)==null?void 0:r.call(e),e.enabled=!this.muted,t&&this.uninstallTrackEvent(t),this.installTrackEvent(e),this.emit("input-media-track-changed",e||null,t||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var r;let t=this._outputTrack;e!==t&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",(r=e.getSettings)==null?void 0:r.call(e).deviceId,e.label),this._outputTrack=e,this._inputTrack&&(this._outputTrack.contentHint=this._inputTrack.contentHint,this._outputTrack.enabled=this._inputTrack.enabled),this.updatePlayingState(!!e),this.emit("output-media-track-changed",e))}setMediaType(e){this.mediaType=e}updatePlayingState(e){if(this.isPlayCalled){if(e){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped){this.player.play().catch(t=>this.handleAutoPlayFailed(t)),this.log.info(`playing state updated, play ${this.kind}`);return}}else if(!this.player.isStopped){this.player.stop(Sl(this)?this.jitterBufferDelay:0),this.log.info(`playing state updated, stop ${this.kind}`);return}}this.log.debug(`updatePlayingState abort ${this.isPlayCalled} ${e} ${this.player.isStopped}`)}handleAutoPlayFailed(e){return p(this,null,function*(){var r;this.log.warn("handleAutoPlayFailed",e);let t=()=>{this.resume().then(()=>{document.removeEventListener("click",t,!0)})};if(this.room&&this.room.enableAutoPlayDialog){if((Ji||ji)&&(yield Ke(100),(r=this.player)!=null&&r.isPlaying))return;ns()}else document.addEventListener("click",t,!0);S.once(A.LOCAL_TRACK_CAPTURE_SUCCESS,({track:s})=>{s.kind==="audio"&&br()&&!this.player.isPlaying&&this.isRemote&&this.isAvailable&&t()}),this.emit("error",e)})}getVideoFrame(){return this.player instanceof it?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(e){var n,a,c;if(this.isFirstVideoFrameEmitted)return;let t=(n=this.mediaTrack)==null?void 0:n.getSettings(),r=(t==null?void 0:t.width)||((a=this.player.element)==null?void 0:a.videoWidth)||0,s=(t==null?void 0:t.height)||((c=this.player.element)==null?void 0:c.videoHeight)||0;e===ue.RESIZE&&!r&&!s||e===ue.LOADED_META_DATA&&!r&&!s||(e===ue.LOADED_DATA&&!r&&!s&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,bt(this.rotation)&&([r,s]=[s,r]),this.emit("first-video-frame",{width:r,height:s,streamType:this.streamType,userId:this.isRemote?this.userId:""}))}onTrackMuted(){this._log.warn(`${this.kind} track is unable to provide media output`)}onTrackUnmuted(){this._log.info(`${this.kind} track is able to provide media output`)}onTrackEnded(){this._log.warn(`${this.kind} track ended`)}};M([ye([],J.INIT,{sync:!0})],no.prototype,"close",1);var XT=Object.prototype.hasOwnProperty,{toString:vb}=Object.prototype;function zT(o){if(o==null)return!0;if(typeof o=="boolean")return!1;if(typeof o=="number")return o===0;if(typeof o=="string"||typeof o=="function"||Array.isArray(o))return o.length===0;if(o instanceof Error)return o.message==="";if(dt(o))switch(Object.prototype.toString.call(o)){case"[object File]":case"[object Map]":case"[object Set]":return o.size===0;case"[object Object]":{for(let i in o)if(XT.call(o,i))return!1;return!0}}return!1}var fi=zT;var QT=function(o){return p(this,null,function*(){let i=ZT(o);R.info(`getUserMedia with constraints: ${JSON.stringify(i)}`);let e=[],t=[],r=["label","deviceId","groupId"];if(i.audio&&(e=yield It(),R.info(`microphones: ${_t(e.map(s=>L(O({},s),{groupId:s.groupId.substring(0,8)})),{keysToInclude:r})}`)),i.video&&(t=yield At(),R.info(`cameras: ${_t(t,{keysToInclude:r})}`),!he(i.video)&&i.video.facingMode==="user"&&!i.video.deviceId)){let n=t.filter(a=>!a.label.includes("infrared")).find(a=>a.label.includes("facing front"));n&&(i.video.deviceId=n.deviceId,R.info(`exclude infrared camera: ${JSON.stringify(i)}`))}try{let s=yield navigator.mediaDevices.getUserMedia(i);return cu&&s.getTracks().forEach(n=>{var c;let a=n.getCapabilities();R.info(`${n.kind} capabilities: ${_t(a,{keysToInclude:Ia})}`),!T(o.echoCancellation)&&((c=a.echoCancellation)==null?void 0:c.indexOf(o.echoCancellation))===-1&&R.warn(`Invalid argument for 'echoCancellation'. Expected one of [${JSON.stringify(a.echoCancellation)}], but received '${o.echoCancellation}'`)}),i.audio&&vr(),s}catch(s){let{message:n}=s;throw s.name==="NotFoundError"&&(o.video&&t&&t.length===0&&(n=H({key:F.CAMERA_NOT_FOUND})),o.audio&&e&&e.length===0&&(n=H({key:F.MICROPHONE_NOT_FOUND}))),new D({code:I.INITIALIZE_FAILED,name:s.name,message:n,constraint:s.constraint})}})},YT=Ai({retryFunction:QT,settings:{retries:3,timeout:500},onError:({error:o,retry:i,reject:e,retryFuncArgs:t,retriedCount:r})=>{let s=r+1;o.name==="NotReadableError"||o.name==="OverconstrainedError"||o.name==="AbortError"?(s===1?(t[0].video&&(t[0].maxResolution=!1,(!Re||t[0].width*t[0].height<=1920*1080)&&t[0].frameRate&&(t[0].frameRate=t[0].frameRate>10?10:5)),t[0].retryWhenExactFailed&&t[0].useExactDeviceId&&(t[0].useExactDeviceId=!1)):s===2?t[0].useDeviceIdOnly=!0:s===3&&!t[0].useExactDeviceId&&(t[0].useTrueAsConstraint=!0),i()):e(o),t[0].microphoneId&&sf(t[0].microphoneId,!1),t[0].cameraId&&sf(t[0].cameraId,!0)},onRetrying:o=>{R.warn(`getUserMedia NotReadableError observed, retrying [${o}/3]`)},onRetryFailed:o=>{se.logFailedEvent({eventType:Ze.GET_USER_MEDIA_RETRY,error:o})},onRetrySuccess:o=>{se.logSuccessEvent({eventType:Ze.GET_USER_MEDIA_RETRY}),se.uploadEvent({log:`stat-${Ze.GET_USER_MEDIA_RETRY}-success-${o}`})}});function sf(o,i){return p(this,null,function*(){let t=(i?yield At():yield It()).find(r=>r.deviceId===o);t&&le(t.getCapabilities)&&R.warn(_t(t.getCapabilities(),{keysToInclude:Ia}))})}function ZT(o){return{audio:KT(o),video:eE(o)}}function KT(o){if(!o.audio)return!1;if(o.useTrueAsConstraint)return!0;let i={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:o.sampleRate};return!fi(o.microphoneId)&&(i.deviceId=o.useExactDeviceId?{exact:o.microphoneId}:o.microphoneId,o.useDeviceIdOnly)?i:(z(o.channelCount)&&(i.channelCount=o.channelCount),(he(o.echoCancellation)||o.echoCancellation==="remote-only"||o.echoCancellation==="all")&&(i.echoCancellation=o.echoCancellation),he(o.noiseSuppression)&&!o.noiseSuppression&&(i.noiseSuppression=!1),he(o.autoGainControl)&&!o.autoGainControl&&(i.autoGainControl=!1),fi(i)?!0:i)}function eE(o){if(!o.video)return!1;if(o.useTrueAsConstraint)return!0;let{maxResolution:i=!0}=o,e={};return o.cameraId?e.deviceId=o.useExactDeviceId?{exact:o.cameraId}:o.cameraId:o.facingMode&&(e.facingMode=o.facingMode),o.useDeviceIdOnly&&!fi(e)?e:(o.width&&(e.width={ideal:o.width},i&&!K&&(e.width.max=o.width)),o.height&&(e.height={ideal:o.height},i&&!K&&(e.height.max=o.height)),K&&ri&&o.width&&o.height&&o.width*o.height<352*288&&(e.width=o.width,e.height=o.height),o.frameRate&&(e.frameRate=o.frameRate),fi(e)?!0:e)}var nf=YT;function Mc(o){return Q((i,e)=>function(...t){return p(this,null,function*(){return yield o.apply(this,t),i.apply(this,t)})})}function Ct(o){return Q((i,e)=>function(...t){return p(this,null,function*(){let r=yield i.apply(this,t);return yield o.call(this,...t),r})})}function Oc(o){return Q((i,e)=>function(...t){return p(this,null,function*(){try{return yield i.apply(this,t)}catch(r){o.call(this,r)}})})}function Q(o){return function(i,e,t){return t.value=o(t.value,e),t}}var af=(()=>{let o=!1,i=document.visibilityState;return()=>{document.visibilityState!==i&&R.info(`visibility change: ${document.visibilityState}`),!o&&(document.addEventListener("visibilitychange",()=>{R.info(`visibility change: ${document.visibilityState}`),i=document.visibilityState}),o=!0)}})();var tE=0,kc=class{constructor(){d(this,"log",R.createLogger({id:`fq${++tE}`}));d(this,"isRunning",!1);d(this,"queue",[])}get length(){return this.queue.length}get lastQueueItem(){return this.length===0?null:this.queue[this.length-1]}push(i,e=!1){var s,n;let t=O({},i),r=new Promise((a,c)=>{t.resolve=a,t.reject=c});return t.promise=r,e?this.length<=1?this.queue.push(t):(n=(s=this.lastQueueItem)==null?void 0:s.promise)==null||n.then(t.resolve,t.reject):this.queue.push(t),this.log.debug(`push ${this.length}`),this.isRunning||this.callNext(),r}shift(){let i=this.queue.shift();return this.log.debug(`shift ${this.length}`),i}callNext(){if(this.isRunning||this.length===0)return;this.log.debug("callNext ",this.length);let{fn:i,args:e,context:t,resolve:r,reject:s}=this.queue[0];this.isRunning=!0,i.apply(t,e).then(r,s).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},Pc=new WeakMap,wc=new WeakMap;function ir(o=!1){return function(i,e,t){let r=t.value;return t.value=function(...s){let n=Pc.get(this)||new kc;return Pc.set(this,n),n.push({fn:r,args:s,context:this},o)},t}}function Lc(o){return function(i,e,t){let r=t.value;return t.value=function(...s){var a,c,l;let n=[];return(c=(a=Pc.get(this))==null?void 0:a.queue)==null||c.forEach(u=>n.push(u)),(l=wc.get(this))==null||l.forEach(u=>u==null?void 0:u.queue.forEach(h=>n.push(h))),n.forEach(u=>{u.reject(new D({code:I.API_CALL_ABORTED,message:o}))}),Pc.delete(this),wc.delete(this),r.apply(this,s)},t}}function _i(o){return function(i,e,t){let r=t.value,s=n=>o(...n);return t.value=function(...n){let a=wc.get(this)||new Map,c=a.get(s(n))||new kc;return a.set(s(n),c),wc.set(this,a),c.push({fn:r,args:n,context:this})},t}}function Rt(o,i){return Q((e,t)=>function(...r){let s=o;try{let n=e.apply(this,r),a=U();return Tr(n)?n.then(c=>(i?v.addSuccessEvent({key:s,cost:U()-a}):v.addSuccessEvent({key:s}),c)).catch(c=>{throw v.addFailedEvent({key:s,error:c}),c}):(v.addSuccessEvent({key:s}),n)}catch(n){throw v.addFailedEvent({key:s,error:n}),n}})}var gh={};Vi(gh,{Events:()=>Oe,Inspect:()=>Ht,LastSink:()=>ao,Sink:()=>j,Subscribe:()=>co,TimeoutError:()=>wn,audit:()=>VE,bindCallback:()=>CE,bindNodeCallback:()=>RE,buffer:()=>lE,bufferCount:()=>dE,bufferTime:()=>rS,call:()=>cf,catchError:()=>ph,combineLatest:()=>lf,concat:()=>oE,concatMap:()=>zE,concatMapTo:()=>QE,count:()=>vE,create:()=>ae,debounce:()=>FE,debounceTime:()=>BE,defer:()=>uf,delay:()=>oS,deliver:()=>X,dispose:()=>xc,elementAt:()=>HE,empty:()=>Vn,every:()=>JE,exhaustMap:()=>KE,exhaustMapTo:()=>eS,expand:()=>sS,filter:()=>$t,find:()=>$E,findIndex:()=>WE,first:()=>GE,fromAnimationFrame:()=>IE,fromArray:()=>fE,fromEvent:()=>ce,fromEventPattern:()=>_E,fromFetch:()=>gE,fromIterable:()=>TE,fromPromise:()=>pf,fromReadableStream:()=>SE,fromReader:()=>EE,groupBy:()=>tS,identity:()=>iE,ignoreElements:()=>OE,iif:()=>nE,inspect:()=>df,interval:()=>Vu,last:()=>qE,map:()=>Fn,mapTo:()=>XE,max:()=>NE,merge:()=>Ln,mergeMap:()=>YE,mergeMapTo:()=>ZE,min:()=>DE,never:()=>yE,nothing:()=>pe,of:()=>pE,pairwise:()=>jE,pipe:()=>de,race:()=>xu,range:()=>AE,reduce:()=>Fu,retry:()=>dS,scan:()=>mh,setAsapScheduler:()=>mE,share:()=>rr,shareReplay:()=>sE,skip:()=>PE,skipUntil:()=>wE,skipWhile:()=>Hc,startWith:()=>xn,subject:()=>ot,subscribe:()=>Te,sum:()=>ME,switchMap:()=>Mr,switchMapTo:()=>mo,take:()=>or,takeLast:()=>kE,takeUntil:()=>ke,takeWhile:()=>ff,tap:()=>Bn,throttle:()=>xE,throwError:()=>bE,timeInterval:()=>iS,timeout:()=>cS,timer:()=>Un,toPromise:()=>nS,toReadableStream:()=>aS,withLatestFrom:()=>cE,zip:()=>aE});function pe(...o){}var cf=o=>o(),iE=o=>o;function xc(){this.dispose()}var df=()=>typeof __FASTRX_DEVTOOLS__!="undefined",rE=1,Ht=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(i){let e=new ku(i,this,this.streamId++);return Oe.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},ao=class{constructor(){this.defers=new Set,this.disposed=!1}next(i){}complete(){this.dispose()}error(i){this.dispose()}get bindDispose(){return()=>this.dispose()}dispose(){this.disposed=!0,this.complete=pe,this.error=pe,this.next=pe,this.dispose=pe,this.subscribe=pe,this.doDefer()}subscribe(i){return i instanceof Ht?i.subscribe(this):i(this),this}get bindSubscribe(){return i=>this.subscribe(i)}doDefer(){this.defers.forEach(cf),this.defers.clear()}defer(i){this.defers.add(i)}removeDefer(i){this.defers.delete(i)}reset(){this.disposed=!1,delete this.complete,delete this.next,delete this.dispose,delete this.next,delete this.subscribe}resetNext(){delete this.next}resetComplete(){delete this.complete}resetError(){delete this.error}},j=class extends ao{constructor(i){super(),this.sink=i,i.defer(this.bindDispose)}next(i){this.sink.next(i)}complete(){this.sink.complete()}error(i){this.sink.error(i)}},co=class extends ao{constructor(i,e=pe,t=pe,r=pe){if(super(),this._next=e,this._error=t,this._complete=r,this.then=pe,i instanceof Ht){let s={toString:()=>"subscribe",id:0,source:i};this.defer(()=>{Oe.defer(s,0)}),Oe.create(s),Oe.pipe(s),this.sourceId=s.id,this.subscribe(i),Oe.subscribe({id:s.id,end:!0}),e==pe?this._next=n=>Oe.next(s,0,n):this.next=n=>{Oe.next(s,0,n),e(n)},r==pe?this._complete=()=>Oe.complete(s,0):this.complete=()=>{this.dispose(),Oe.complete(s,0),r()},t==pe?this._error=n=>Oe.complete(s,0,n):this.error=n=>{this.dispose(),Oe.complete(s,0,n),t(n)}}else this.subscribe(i)}next(i){this._next(i)}complete(){this.dispose(),this._complete()}error(i){this.dispose(),this._error(i)}};function de(o,...i){return i.reduce((e,t)=>t(e),o)}function ae(o,i,e){if(df()){let t=Object.defineProperties(Object.setPrototypeOf(o,Ht.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:i,writable:!0,configurable:!0},args:{value:e,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});Oe.create(t);for(let r=0;r<e.length;r++){let s=e[r];typeof s=="function"&&s instanceof Ht&&Oe.addSource(t,s)}return t}return o}function X(o,i){return function(...e){return t=>{if(t instanceof Ht){let r=ae(s=>{let n=new o(s,...e);n.sourceId=r.id,n.subscribe(t)},i,arguments);return r.source=t,Oe.pipe(r),r}else return r=>t(new o(r,...e))}}}function Dr(o,i){window.postMessage({source:"fastrx-devtools-backend",payload:{event:o,payload:i}})}var ku=class extends j{constructor(i,e,t){super(i),this.source=e,this.id=t,this.sourceId=i.sourceId,this.defer(()=>{Oe.defer(this.source,this.id)})}next(i){Oe.next(this.source,this.id,i),this.sink.next(i)}complete(){Oe.complete(this.source,this.id),this.sink.complete()}error(i){Oe.complete(this.source,this.id,i),this.sink.error(i)}},Oe={addSource(o,i){Dr("addSource",{id:o.id,name:o.toString(),source:{id:i.id,name:i.toString()}})},next(o,i,e){Dr("next",{id:o.id,streamId:i,data:e&&e.toString()})},subscribe({id:o,end:i},e){Dr("subscribe",{id:o,end:i,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(o,i,e){Dr("complete",{id:o.id,streamId:i,err:e?e.toString():null})},defer(o,i){Dr("defer",{id:o.id,streamId:i})},pipe(o){Dr("pipe",{name:o.toString(),id:o.id,source:{id:o.source.id,name:o.source.toString()}})},update(o){Dr("update",{id:o.id,name:o.toString()})},create(o){o.id||(o.id=rE++),Dr("create",{name:o.toString(),id:o.id})}},wn=class extends Error{constructor(i){super(`timeout after ${i}ms`),this.timeout=i}};var Uc=class extends ao{constructor(i){super(),this.source=i,this.sinks=new Set}add(i){i.defer(()=>this.remove(i)),this.sinks.add(i).size===1&&(this.reset(),this.subscribe(this.source))}remove(i){this.sinks.delete(i),this.sinks.size===0&&this.dispose()}next(i){this.sinks.forEach(e=>e.next(i))}complete(){this.sinks.forEach(i=>i.complete()),this.sinks.clear()}error(i){this.sinks.forEach(e=>e.error(i)),this.sinks.clear()}};function rr(){return o=>{let i=new Uc(o);if(o instanceof Ht){let e=ae(t=>{i.add(t)},"share",arguments);return i.sourceId=e.id,e.source=o,Oe.pipe(e),e}return ae(i.add.bind(i),"share",arguments)}}function Ln(...o){return ae(i=>{let e=new j(i),t=o.length;e.complete=()=>{--t===0&&i.complete()},o.forEach(e.bindSubscribe)},"merge",arguments)}function xu(...o){return ae(i=>{let e=new Map;o.forEach(t=>{let r=new j(i);e.set(t,r),r.complete=()=>{e.delete(t),e.size===0?i.complete():r.dispose()},r.next=s=>{e.delete(t),e.forEach(n=>n.dispose()),r.resetNext(),r.resetComplete(),r.next(s)}}),o.forEach(t=>e.get(t).subscribe(t))},"race",arguments)}function oE(...o){return ae(i=>{let e=0,t=o.length,r=new j(i);r.complete=()=>{e<t&&!r.disposed?(r.doDefer(),r.subscribe(o[e++])):i.complete()},r.complete()},"concat",arguments)}function sE(o){return i=>{let e=new Uc(i),t=[];return e.next=function(r){t.push(r),t.length>o&&t.shift(),this.sinks.forEach(s=>s.next(r))},ae(r=>{r.defer(()=>e.remove(r)),t.forEach(s=>r.next(s)),e.add(r)},"shareReplay",arguments)}}function nE(o,i,e){return ae(t=>o()?i(t):e(t),"iif",arguments)}function lf(...o){return ae(i=>{let e=o.length,t=e,r=e,s=new Array(e),n=()=>{--r===0&&i.complete()},a=(c,l)=>{let u=new j(i);u.next=h=>{t--,u.next=m=>{s[l]=m,t===0&&i.next(s)},u.next(h)},u.complete=n,u.subscribe(c)};o.forEach(a)},"combineLatest",arguments)}function aE(...o){return ae(i=>{let e=o.length,t=e,r=new Array(e),s=()=>{--t===0&&i.complete()},n=(a,c)=>{let l=new j(i),u=[];r[c]=u,l.next=h=>{u.push(h),r.every(m=>m.length)&&i.next(r.map(m=>m.shift()))},l.complete=s,l.subscribe(a)};o.forEach(n)},"zip",arguments)}function xn(...o){return i=>ae((e,t=0,r=o.length)=>{for(;t<r&&!e.disposed;)e.next(o[t++]);e.disposed||e.subscribe(i)},"startWith",arguments)}var Pu=class extends j{constructor(i,...e){super(i);let t=new j(this.sink);t.next=r=>this.buffer=r,t.complete=pe,t.subscribe(lf(...e))}next(i){this.buffer&&this.sink.next([i,...this.buffer])}},cE=X(Pu,"withLatestFrom"),wu=class extends j{constructor(i,e,t){super(i),this.bufferSize=e,this.startBufferEvery=t,this.buffer=[],this.count=0,this.startBufferEvery&&(this.buffers=[[]])}next(i){this.startBufferEvery?(this.count++===this.startBufferEvery&&(this.buffers.push([]),this.count=1),this.buffers.forEach(e=>{e.push(i)}),this.buffers[0].length===this.bufferSize&&this.sink.next(this.buffers.shift())):(this.buffer.push(i),this.buffer.length===this.bufferSize&&(this.sink.next(this.buffer),this.buffer=[]))}complete(){this.buffer.length?this.sink.next(this.buffer):this.buffers.length&&this.buffers.forEach(i=>this.sink.next(i)),super.complete()}},dE=X(wu,"bufferCount"),Lu=class extends j{constructor(i,e){super(i),this.buffer=[];let t=new j(i);t.next=r=>{i.next(this.buffer),this.buffer=[]},t.complete=pe,t.subscribe(e)}next(i){this.buffer.push(i)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},lE=X(Lu,"buffer");var uE=function(o,i,e,t){function r(s){return s instanceof e?s:new e(function(n){n(s)})}return new(e||(e=Promise))(function(s,n){function a(u){try{l(t.next(u))}catch(h){n(h)}}function c(u){try{l(t.throw(u))}catch(h){n(h)}}function l(u){u.done?s(u.value):r(u.value).then(a,c)}l((t=t.apply(o,i||[])).next())})};function ot(o){let i=arguments,e=rr()(ae(t=>{e.next=r=>t.next(r),e.complete=()=>t.complete(),e.error=r=>t.error(r),o&&t.subscribe(o)},"subject",i));return e.next=pe,e.complete=pe,e.error=pe,e}function uf(o){return ae(i=>i.subscribe(o()),"defer",arguments)}var ms={promise:o=>{Promise.resolve().then(o)},setImmediate:typeof setImmediate!="undefined"?o=>setImmediate(o):null,setTimeout:o=>setTimeout(o,0)},hE=()=>typeof Promise!="undefined"?ms.promise:ms.setImmediate?ms.setImmediate:ms.setTimeout,Uu=hE(),hf=o=>i=>{Uu(()=>o(i))},mE=o=>{typeof o=="function"?Uu=o:ms[o]&&(Uu=ms[o])};var mf=o=>hf(i=>{for(let e=0;!i.disposed&&e<o.length;e++)i.next(o[e]);i.complete()});function pE(...o){return ae(mf(o),"of",arguments)}function fE(o){return ae(mf(o),"fromArray",arguments)}function Vu(o){return ae(i=>{let e=0,t=setInterval(()=>i.next(e++),o);return i.defer(()=>{clearInterval(t)}),"interval"},"interval",arguments)}function Un(o,i){return ae(e=>{let t=0,r=setTimeout(()=>{if(e.removeDefer(s),e.next(t++),i){let n=setInterval(()=>e.next(t++),i);e.defer(()=>{clearInterval(n)})}else e.complete()},o),s=()=>clearTimeout(r);e.defer(s)},"timer",arguments)}function Vc(o,i){return e=>{let t=r=>e.next(r);e.defer(()=>i(t)),o(t)}}function _E(o,i){return ae(Vc(o,i),"fromEventPattern",arguments)}function ce(o,i){if("on"in o&&"off"in o)return ae(Vc(e=>o.on(i,e),e=>o.off(i,e)),"fromEvent",arguments);if("addListener"in o&&"removeListener"in o)return ae(Vc(e=>o.addListener(i,e),e=>o.removeListener(i,e)),"fromEvent",arguments);if("addEventListener"in o)return ae(Vc(e=>o.addEventListener(i,e),e=>o.removeEventListener(i,e)),"fromEvent",arguments);throw"target is not a EventDispachter"}function pf(o){return ae(i=>{o.then(i.next.bind(i),i.error.bind(i))},"fromPromise",arguments)}function gE(o,i){return ae(uf(()=>pf(fetch(o,i))),"fromFetch",arguments)}function TE(o){return ae(hf(i=>{try{for(let e of o){if(i.disposed)return;i.next(e)}i.complete()}catch(e){i.error(e)}}),"fromIterable",arguments)}function EE(o){let i=e=>uE(this,void 0,void 0,function*(){if(e.disposed)return;let{done:t,value:r}=yield o.read();if(t){e.complete();return}else e.next(r),i(e)});return ae(e=>{i(e)},"fromReader",arguments)}function SE(o){return ae(i=>{let e=new AbortController,t=e.signal;i.defer(()=>e.abort("cancelled")),o.pipeTo(new WritableStream({write(r){i.next(r)},close(){i.complete()},abort(r){i.error(r)}}),{signal:t}).then(()=>i.complete(),r=>i.error(r))},"fromReadableStream",arguments)}function IE(){return ae(o=>{let i=requestAnimationFrame(function e(t){o.disposed||(o.next(t),i=requestAnimationFrame(e))});o.defer(()=>cancelAnimationFrame(i))},"fromAnimationFrame",arguments)}function AE(o,i){return ae((e,t=o,r=i+o)=>{for(;t<r&&!e.disposed;)e.next(t++);return e.complete(),"range"},"range",arguments)}function CE(o,i,...e){return ae(t=>{let r=e.concat(s=>(t.next(s),t.complete()));o.apply(i,r)},"bindCallback",arguments)}function RE(o,i,...e){return ae(t=>{let r=e.concat((s,n)=>s?t.error(s):(t.next(n),t.complete()));o.apply(i,r)},"bindNodeCallback",arguments)}function yE(){return ae(()=>{},"never",arguments)}function bE(o){return ae(i=>i.error(o),"throwError",arguments)}function Vn(){return ae(o=>o.complete(),"empty",arguments)}var lo=class extends j{constructor(i,e,t){super(i),this.f=e;let r=()=>{this.sink.next(this.acc),this.sink.complete()};typeof t=="undefined"?this.next=s=>{this.acc=s,this.complete=r,this.resetNext()}:(this.acc=t,this.complete=r)}next(i){this.acc=this.f(this.acc,i)}},Fu=X(lo,"reduce"),vE=o=>X(lo,"count")((i,e)=>o(e)?i+1:i,0),NE=()=>X(lo,"max")(Math.max),DE=()=>X(lo,"min")(Math.min),ME=()=>X(lo,"sum")((o,i)=>o+i,0);var Bu=class extends j{constructor(i,e,t){super(i),this.filter=e,this.thisArg=t}next(i){this.filter.call(this.thisArg,i)&&this.sink.next(i)}},$t=X(Bu,"filter"),Hu=class extends j{next(i){}},OE=X(Hu,"ignoreElements"),$u=class extends j{constructor(i,e){super(i),this.count=e}next(i){this.sink.next(i),--this.count===0&&(this.doDefer(),this.complete())}},or=X($u,"take"),Wu=class extends j{constructor(i,e){super(i);let t=new j(i);t.next=()=>{t.doDefer(),i.complete()},t.complete=xc,t.subscribe(e)}},ke=X(Wu,"takeUntil"),Gu=class extends j{constructor(i,e){super(i),this.f=e}next(i){this.f(i)?this.sink.next(i):(this.doDefer(),this.complete())}},ff=X(Gu,"takeWhile"),kE=o=>Fu((i,e)=>(i.push(e),i.length>o&&i.shift(),i),[]),qu=class extends j{constructor(i,e){super(i),this.count=e}next(i){--this.count===0&&(this.next=super.next)}},PE=X(qu,"skip"),Ju=class extends j{constructor(i,e){super(i),i.next=pe;let t=new j(i);t.next=()=>{t.doDefer(),i.resetNext()},t.complete=xc,t.subscribe(e)}},wE=X(Ju,"skipUntil"),ju=class extends j{constructor(i,e){super(i),this.f=e}next(i){this.f(i)||(this.next=super.next,this.next(i))}},Hc=X(ju,"skipWhile"),LE={leading:!0,trailing:!1},Xu=class extends j{constructor(i,e,t){super(i),this.durationSelector=e,this.trailing=t}cacheValue(i){this.last=i,this.disposed&&this.throttle(i)}send(i){this.sink.next(i),this.throttle(i)}throttle(i){this.reset(),this.subscribe(this.durationSelector(i))}next(){this.complete()}complete(){this.dispose(),this.trailing&&this.send(this.last)}},Fc=class extends j{constructor(i,e,t=LE){super(i),this.durationSelector=e,this.config=t,this._throttle=new Xu(this.sink,this.durationSelector,this.config.trailing),this._throttle.dispose()}next(i){this._throttle.disposed&&this.config.leading?this._throttle.send(i):this._throttle.cacheValue(i)}complete(){this._throttle.throttle=pe,this._throttle.complete(),super.complete()}},xE=X(Fc,"throttle"),UE={leading:!1,trailing:!0},VE=o=>X(Fc,"audit")(o,UE),zu=class extends j{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},Bc=class extends j{constructor(i,e){super(i),this.durationSelector=e,this._debounce=new zu(this.sink),this._debounce.dispose()}next(i){this._debounce.dispose(),this._debounce.reset(),this._debounce.last=i,this._debounce.subscribe(this.durationSelector(i))}complete(){this._debounce.complete(),super.complete()}},FE=X(Bc,"debounce"),BE=o=>X(Bc,"debounceTime")(i=>Un(o)),Qu=class extends j{constructor(i,e,t){super(i),this.count=e,this.defaultValue=t}next(i){this.count--===0&&(this.defaultValue=i,this.doDefer(),this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("not enough elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},HE=X(Qu,"elementAt"),$E=o=>i=>or(1)(Hc(e=>!o(e))(i)),Yu=class extends j{constructor(i,e){super(i),this.f=e,this.i=0}next(i){this.f(i)?(this.sink.next(this.i++),this.doDefer(),this.complete()):++this.i}},WE=X(Yu,"findIndex"),Zu=class extends j{constructor(i,e,t){super(i),this.f=e,this.defaultValue=t,this.index=0}next(i){(!this.f||this.f(i,this.index++))&&(this.defaultValue=i,this.doDefer(),this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},GE=X(Zu,"first"),Ku=class extends j{constructor(i,e,t){super(i),this.f=e,this.defaultValue=t,this.index=0}next(i){(!this.f||this.f(i,this.index++))&&(this.defaultValue=i)}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},qE=X(Ku,"last"),eh=class extends j{constructor(i,e){super(i),this.predicate=e,this.index=0}next(i){this.predicate(i,this.index++)?this.result=!0:(this.result=!1,this.doDefer(),this.complete())}complete(){if(this.result===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.result);super.complete()}},JE=X(eh,"every");var th=class extends j{constructor(i,e,t){super(i),this.f=e,typeof t=="undefined"?this.next=r=>{this.acc=r,this.resetNext(),this.sink.next(this.acc)}:this.acc=t}next(i){this.sink.next(this.acc=this.f(this.acc,i))}},mh=X(th,"scan"),ih=class extends j{constructor(){super(...arguments),this.hasLast=!1}next(i){this.hasLast?this.sink.next([this.last,i]):this.hasLast=!0,this.last=i}},jE=X(ih,"pairwise"),$c=class extends j{constructor(i,e,t){super(i),this.mapper=e,this.thisArg=t}next(i){super.next(this.mapper.call(this.thisArg,i))}},Fn=X($c,"map"),XE=o=>X($c,"mapTo")(i=>o),uo=class extends j{constructor(i,e,t){super(i),this.data=e,this.context=t}next(i){let e=this.context.combineResults;e?this.sink.next(e(this.data,i)):this.sink.next(i)}tryComplete(){this.context.resetComplete(),this.dispose()}},ho=class o extends j{constructor(i,e,t){super(i),this.makeSource=e,this.combineResults=t,this.index=0}subInner(i,e){let t=this.currentSink=new e(this.sink,i,this);this.complete===o.prototype.complete&&(this.complete=this.tryComplete),t.complete=t.tryComplete,t.subscribe(this.makeSource(i,this.index++))}complete(){this.sink.complete()}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},Wc=class extends uo{},Gc=class extends ho{next(i){this.subInner(i,Wc),this.next=e=>{this.currentSink.dispose(),this.subInner(e,Wc)}}},Mr=X(Gc,"switchMap");function Xc(o){return(i,e)=>o(()=>i,e)}var mo=Xc(X(Gc,"switchMapTo")),rh=class extends uo{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},qc=class extends ho{constructor(){super(...arguments),this.sources=[],this.next2=this.sources.push.bind(this.sources)}next(i){this.next2(i),this.subNext()}subNext(){this.next=this.next2,this.subInner(this.sources.shift(),rh),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},zE=X(qc,"concatMap"),QE=Xc(X(qc,"concatMapTo")),oh=class extends uo{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},Jc=class extends ho{constructor(){super(...arguments),this.inners=new Set}next(i){this.subInner(i,oh),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(i=>i.resetComplete()):this.dispose()}},YE=X(Jc,"mergeMap"),ZE=Xc(X(Jc,"mergeMapTo")),sh=class extends uo{dispose(){this.context.resetNext(),super.dispose()}},jc=class extends ho{next(i){this.next=pe,this.subInner(i,sh)}},KE=X(jc,"exhaustMap"),eS=Xc(X(jc,"exhaustMapTo")),nh=class extends j{constructor(i,e){super(i),this.f=e,this.groups=new Map}next(i){let e=this.f(i),t=this.groups.get(e);typeof t=="undefined"&&(t=ot(),t.key=e,this.groups.set(e,t),super.next(t)),t.next(i)}complete(){this.groups.forEach(i=>i.complete()),super.complete()}error(i){this.groups.forEach(e=>e.error(i)),super.error(i)}},tS=X(nh,"groupBy"),ah=class extends j{constructor(){super(...arguments),this.start=new Date}next(i){this.sink.next({value:i,interval:Number(new Date)-Number(this.start)}),this.start=new Date}},iS=X(ah,"timeInterval"),ch=class extends j{constructor(i,e){super(i),this.miniseconds=e,this.buffer=[],this.id=setInterval(()=>{this.sink.next(this.buffer.concat()),this.buffer.length=0},this.miniseconds)}next(i){this.buffer.push(i)}complete(){this.sink.next(this.buffer),super.complete()}dispose(){clearInterval(this.id),super.dispose()}},rS=X(ch,"bufferTime"),dh=class extends j{constructor(i,e){super(i),this.buffer=[],this.delayTime=e}dispose(){clearTimeout(this.timeoutId),super.dispose()}delay(i){this.timeoutId=setTimeout(()=>{let e=this.buffer.shift();if(e){let{time:t,data:r}=e;super.next(r),this.buffer.length&&this.delay(Number(this.buffer[0].time)-Number(t))}},i)}next(i){this.buffer.length||this.delay(this.delayTime),this.buffer.push({time:new Date,data:i})}complete(){this.timeoutId=setTimeout(()=>super.complete(),this.delayTime)}},oS=X(dh,"delay"),lh=class extends j{constructor(i,e){super(i),this.selector=e}error(i){this.dispose(),this.selector(i)(this.sink)}},ph=X(lh,"catchError"),uh=class extends uo{tryComplete(){let i=this.context.inners.delete(this);super.dispose(),i&&this.context.checkComplete()}next(i){this.sink.next(i),this.context.expandValue(i)}},hh=class extends ho{constructor(i,e){super(i,e),this.project=e,this.inners=new Set,this.sourceCompleted=!1}next(i){this.sink.next(i),this.expandValue(i)}expandValue(i){let e=new uh(this.sink,i,this);this.currentSink=e,this.complete=this.tryComplete,e.complete=e.tryComplete,this.inners.add(e),e.subscribe(this.makeSource(i,this.index++))}complete(){this.sourceCompleted=!0,this.checkComplete()}checkComplete(){this.sourceCompleted&&this.inners.size===0&&(this.resetComplete(),super.complete())}tryComplete(){this.sourceCompleted=!0,this.checkComplete()}},sS=X(hh,"expand");var nS=()=>o=>new Promise((i,e)=>{let t;new co(o,r=>t=r,e,()=>i(t))}),aS=()=>o=>{let i;return new ReadableStream({start(e){i=new co(o,e.enqueue.bind(e),e.error.bind(e),e.close.bind(e))},cancel(){i.dispose()}})},Te=(o=pe,i=pe,e=pe)=>t=>new co(t,o,i,e),fh=class extends j{constructor(i,e){super(i),e instanceof Function?this.next=t=>{e(t),i.next(t)}:(e.next&&(this.next=t=>{e.next(t),i.next(t)}),e.complete&&(this.complete=()=>{e.complete(),i.complete()}),e.error&&(this.error=t=>{e.error(t),i.error(t)}))}},Bn=X(fh,"tap"),_h=class extends j{constructor(i,e){super(i),this.timeout=e,this.id=setTimeout(()=>this.error(new wn(this.timeout)),this.timeout)}next(i){super.next(i),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},cS=X(_h,"timeout"),dS=(o=1/0)=>i=>{if(i instanceof Ht){let e=ae(t=>{let r=o,s=new j(t);s.error=n=>{r-- >0?s.subscribe(i):t.error(n)},s.sourceId=e.id,s.subscribe(i)},"retry",[o]);return e.source=i,Oe.pipe(e),e}else return e=>{let t=o,r=new j(e);r.error=s=>{t-- >0?i(r):e.error(s)},i(r)}};var ps=(e=>(e[e.AUTO_SWITCH_NEW_DEVICE=0]="AUTO_SWITCH_NEW_DEVICE",e[e.WAIT_CURRENT_DEVICE=1]="WAIT_CURRENT_DEVICE",e))(ps||{}),po=class po extends no{constructor(e,t){super({mediaType:e,PlayerClass:t});d(this,"isRemote",!1);d(this,"deviceId");d(this,"groupId","");d(this,"label","");d(this,"sourceTrack");d(this,"enableAutoSwitchWhenRecapturing",!0);d(this,"_isRecapturing",!1);d(this,"_lastRecaptureTime",0);d(this,"_onMuteTimeoutId",-1);d(this,"_encodeCheckTimeoutId",-1);d(this,"recaptureMode",0);d(this,"profile");d(this,"retryEncodeFailed")}get enableEncodeFrame(){return!1}get isPublishing(){return this.state.toString()==="publishing"}get isPublished(){return this.state==="publish"}get isUseCustomSource(){return this.sourceTrack&&this.mediaTrack&&this.sourceTrack!==this.mediaTrack}encodeFrame(e,t){throw new Error("Method not implemented.")}installTrackEvent(e){e.addEventListener(f.MUTE,this.onTrackMuted),e.addEventListener(f.UNMUTE,this.onTrackUnmuted),e.addEventListener(f.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===f.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){e.removeEventListener(f.MUTE,this.onTrackMuted),e.removeEventListener(f.UNMUTE,this.onTrackUnmuted),e.removeEventListener(f.ENDED,this.onTrackEnded)}setStateToReady(){}capture(e,t=!1){return p(this,null,function*(){var s;let r=this.sourceTrack;try{let n=U();S.emit(A.LOCAL_TRACK_CAPTURE_START,{track:this});let a;e.customSource?(a=new MediaStream,a.addTrack(e.customSource)):(t||(s=this.sourceTrack)==null||s.stop(),a=yield nf(e));let c=a.getTracks()[0];return yield this.setInputMediaStreamTrack(c),e.customSource||(this.sourceTrack=c,this.updateDeviceIdInUse(),this.listenDeviceChange()),S.emit(A.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:U()-n}),a}catch(n){throw S.emit(A.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:n}),this.log.error(`getUserMedia error observed ${n}`),n}finally{t&&(r==null||r.stop())}})}setOutputMediaStreamTrack(e){var t;if(super.setOutputMediaStreamTrack(e),this.setStateToReady(),this.isPublishing||this.isPublished)return(t=this.room)==null?void 0:t.replaceTrack(this)}get hasFlag(){var t,r;let e=Kt(((t=this.room)==null?void 0:t.localPublishFlag)||0,((r=this.room)==null?void 0:r.userId)||"");return this.mediaType===4&&e.hasVideo||this.mediaType===1&&e.hasAudio||this.mediaType===2&&e.hasAuxiliary}publish(e,t){return p(this,null,function*(){return this.room=e,this.room.localTracks.add(this),this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.bindParent(e.getLogger()),yield t,this._checkPublishFlag(e)})}_checkPublishFlag(e){return new Promise((t,r)=>p(this,null,function*(){var l,u,h,m;let s=()=>r(new D({code:I.API_CALL_ABORTED,message:"publish aborted"}));if(this.hasFlag||this.muted?t():((this.state===J.INIT||this.state==="ready")&&s(),de(ce(e,"local-publish-flag-changed"),$t(()=>this.hasFlag),ke(Ln(ce(this,J.INIT),ce(this,"ready"))),Te(t,r,s))),(((u=(l=this.room)==null?void 0:l.networkQuality)==null?void 0:u.uplinkNetworkQuality)||0)>3)return t();let a=e.heartbeatCount,c=((m=(h=this.mediaTrack)==null?void 0:h.stats)==null?void 0:m.totalFrames)||0;this._encodeCheckTimeoutId=setTimeout(()=>p(this,null,function*(){var g,E,C,k,re,P,Qe;if((((E=(g=this.room)==null?void 0:g.networkQuality)==null?void 0:E.uplinkNetworkQuality)||0)>3||e.heartbeatCount-a<3)return t();if((this.isPublished||this.isPublishing)&&this.isMediaTrackActive){if((C=this.mediaTrack)!=null&&C.stats){let te=this.mediaTrack.stats.totalFrames||0;te-c===0&&this.log.warn("capture totalFrames is 0 during encode check, totalFrames",te)}let N=this.kind===f.AUDIO,b=this.stat.bytesSent>0;if(v[b?"addSuccessEvent":"addFailedEvent"]({key:N?503700:513702}),!N){let te=((re=(k=this.room)==null?void 0:k.videoCodec)==null?void 0:re.toUpperCase())||"H264",ve={H264:513704,H265:513705,VP8:513706}[te];ve&&v[b?"addSuccessEvent":"addFailedEvent"]({key:ve})}if(!b){if(v.addEnum({key:N?503701:513703,value:Zr()}),se.uploadEvent({log:`stat-encode-failed-${this.kind}-${si()||ni()}`,userId:this.userId}),this.log.warn(N?"encode failed":`${(Qe=(P=this.room)==null?void 0:P.videoCodec)==null?void 0:Qe.toUpperCase()} encode failed`),this.retryEncodeFailed&&(this.log.warn("retry encode"),yield this.retryEncodeFailed(this),this.stat.bytesSent>0||this.hasFlag||(yield Ke(5e3),this.stat.bytesSent>0||this.hasFlag)))return t();this.emit("6",this),r(new D({message:`${this.strMediaType} encode failed`,code:N?I.AUDIO_ENCODE_FAILED:I.VIDEO_ENCODE_FAILED}))}}}),1e4)}))}unpublish(){this.room&&this.room.localTracks.delete(this),this.log.info("unpublish"),S.emit(A.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return p(this,null,function*(){if(this.sourceTrack&&yi){let{deviceId:e,groupId:t}=this.sourceTrack.getSettings(),{label:r}=this.sourceTrack;(yield of({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=r,t&&(this.groupId=t),ds().then(n=>{let a=n.find(c=>{let l=c.deviceId===e;return t&&(l=l&&c.groupId===t),l});a&&this.emit("2",a)}))}})}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(e=!1){return!(!this.deviceId||!this.sourceTrack||this.kind===f.AUDIO&&!rf(this.sourceTrack)||this.kind===f.VIDEO&&!tf(this.sourceTrack)||this._isRecapturing||e&&ri&&Re)}onTrackMuted(){if(super.onTrackMuted(),af(),!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<ko){setTimeout(()=>this.onTrackMuted(),ko);return}this._onMuteTimeoutId=setTimeout(()=>p(this,null,function*(){var e;if((e=this.sourceTrack)!=null&&e.muted){if((ge||_e)&&document.visibilityState!=="visible")return;this.recapture(yield this.getRecoverCaptureDeviceId())}}),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return p(this,null,function*(){if(Pe(po.prototype,this,"onTrackEnded").call(this),!!this.isNeedToRecapture()&&this.recaptureMode===0){if(Date.now()-this._lastRecaptureTime<ko){setTimeout(()=>this.onTrackEnded(),ko);return}this.emit("7"),this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e,t=!1){return p(this,null,function*(){var n;if(this._isRecapturing||!this.sourceTrack)return;this.log.warn("recapture trying");let r=this.sourceTrack;t||(n=this.sourceTrack)==null||n.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let s={useExactDeviceId:!0};if(e==="user"||e==="environment")s.facingMode=e;else{let a;(this.kind==="audio"?yield It():yield At()).find(l=>l.deviceId===e)&&(a=e),s.deviceId=a}return this.capture(s,t).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),S.emit(A.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(a=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${a.message}`),this.emit("5",a),S.emit(A.LOCAL_TRACK_RECAPTURE,{track:this,error:a})}).finally(()=>{t&&(r==null||r.stop())})})}getRecoverCaptureDeviceId(){return p(this,null,function*(){let e=this instanceof je;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let r=(Hn.get(t)||0)+1;if(Hn.set(t,r),r>=3&&this.enableAutoSwitchWhenRecapturing){let s=e?(yield At()).find(n=>!Hn.has(n.deviceId)):(yield It()).find(n=>!Hn.has(n.deviceId));s&&(this.log.warn(`${t} capture fail ${r} times, change new ${s.deviceId}`),t=s.deviceId)}}return t})}stopCapture(){var e;this.sourceTrack&&(this.sourceTrack.stop(),this.uninstallTrackEvent(this.sourceTrack)),this._inputTrack&&this.uninstallTrackEvent(this._inputTrack),(e=this.manager)==null||e.removeInput(this)}close(){super.close(),this.stopCapture()}};M([ye(J.INIT,"ready",{ignoreError:!0,sync:!0})],po.prototype,"setStateToReady",1),M([ir()],po.prototype,"capture",1),M([ye("ready","publish",{ignoreError:!0,success(){S.emit(A.LOCAL_TRACK_PUBLISHED,{track:this,room:this.room}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),this.log.info("published")},fail(e){var n;(n=this.room)==null||n.localTracks.delete(this);let t="error",r=e instanceof D?e:e.cause instanceof D?e.cause:e,s=!1;r instanceof D&&(r.message.includes("timeout")?t="timeout":r.code===I.API_CALL_ABORTED&&(s=!0,t="api-call")),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:t,error:r}),this.log[s?"info":"error"]("publish failed",r)}}),Rt(521714,!1)],po.prototype,"publish",1),M([Q(e=>function(){return p(this,null,function*(){let t=this.state==="publish"?"started":"starting";e.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:t,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)})}),ye([],"ready",{sync:!0})],po.prototype,"unpublish",1);var pi=po,Hn=new Map;S.on(A.SWITCH_DEVICE_SUCCESS,o=>{o.track.deviceId&&Hn.delete(o.track.deviceId)});var kt=class o extends pi{constructor(e){super(1,Dc);d(this,"mediaType",1);d(this,"volume",0);d(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40});d(this,"playerMuted",!0);d(this,"pipeline");d(this,"earMonitorGainNode",new xe);d(this,"_output",new xe);d(this,"codecPipeline",[]);d(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0});d(this,"mixedAudioReferenceMap",new Map);d(this,"isAudioContextLongSuspended",!1);d(this,"after3aSilenceStartTime",0);this.manager=e,this.pipeline=new cs(e),this.pipeline.source.pipeTo(this.player.pipeline.volumeMeter),this.pipeline.gain.pipeTo(this.earMonitorGainNode).pipeTo(this._output),this.pipeline.gain.pipeTo(this.player.pipeline.volumeMeterAfter3A),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this),S.on(A.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this)}get dbVolume(){return so.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}getInternalAudioLevelAfter3A(){if(this.pipeline.aec.node||this.pipeline.denoiser.node)return this.player.getInternalAudioLevelAfter3A()}updateAfter3aSilenceStartTime(e){T(e)||(e===0&&!this.after3aSilenceStartTime?this.after3aSilenceStartTime=U():e>0&&(this.after3aSilenceStartTime=0))}setInputMediaStreamTrack(e){return p(this,null,function*(){let t=this.trackSettings||{};v.addEnum({key:501701,value:t.channelCount||0,useUV:!1}),v.addEnum({key:501702,value:t.sampleRate||0,useUV:!1}),v.addEnum({key:502700,value:0});let{sampleRate:r,channelCount:s}=t;this._log.info(`local audio track input ${JSON.stringify({sampleRate:r,channelCount:s})}`),this.pipeline.source.channelCount=s||1,this.pipeline.replaceSource(e),yield Pe(o.prototype,this,"setInputMediaStreamTrack").call(this,e),this.updatePlayingState(!!e)})}capture(a){return p(this,arguments,function*({deviceId:e,customSource:t,useExactDeviceId:r=!0,retryWhenExactFailed:s},n=!1){let c=yield Pe(o.prototype,this,"capture").call(this,{video:!1,audio:!0,microphoneId:e,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:r,retryWhenExactFailed:s,customSource:t},n);return vr(),c})}switchDevice(e){return p(this,null,function*(){if(this.mediaTrack){if(this.deviceId===e&&!this.isUseCustomSource)if(e===Wr){if(yield Mu(this.groupId,this.label))return}else return;try{this.log.info(`switchDevice audio to: ${e}`),this.sourceTrack&&this.sourceTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0,retryWhenExactFailed:!1}),S.emit(A.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(t){throw this.log.error(`switch microphone failed ${t}`),this.deviceId&&this.recapture(this.deviceId),t}}})}listenDeviceChange(){be&&!be.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&be.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return p(this,null,function*(){if(e.deviceId===this.deviceId){let t=this.recaptureMode===1;if(this.log.warn(`RecaptureMode: ${ps[this.recaptureMode]}. Current microphone is lost: ${JSON.stringify(e)}`),this.recaptureMode===0){Ne(this.userId,{eventId:2003,param1:6,streamType:1});let r=yield It();r[0]?this.recapture(r[0].deviceId):t=!0}t&&be.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.recaptureMode===1&&e.deviceId!==this.deviceId||(be.off("audioInputAdded",this.handleMicrophoneAdded,this),this.log.warn(`microphone added: ${JSON.stringify(e)}`),this.recapture(e.deviceId))}update3A(s){return p(this,arguments,function*({echoCancellation:e,noiseSuppression:t,autoGainControl:r}){let n=this.sourceTrack||this.mediaTrack;if(!n)return;let a=n.getConstraints(),c=!1;!T(e)&&e!==this.profile.echoCancellation&&(this.profile.echoCancellation=e,a.echoCancellation=e,c=!0),!T(t)&&t!==this.profile.noiseSuppression&&(this.profile.noiseSuppression=t,a.noiseSuppression=t,c=!0),!T(r)&&r!==this.profile.autoGainControl&&(this.profile.autoGainControl=r,a.autoGainControl=r,c=!0),c&&(K||Re?yield n.applyConstraints(a).catch(l=>this._log.warn("update3A failed: ",l)):this.deviceId&&(yield this.recapture(this.deviceId,!0)))})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&v.addEnum({key:502700,value:2})}setAudioVolume(e){super.setAudioVolume(0),ge&&this.player.setMuted(!0),this.earMonitorGainNode.node||(this.earMonitorGainNode.setNode(Ee().createGain()),this._output.setNode(Ee().destination)),this.earMonitorGainNode.node.gain.value=e}enableTrackANS(e){return this.update3A({noiseSuppression:e})}enableTrackAEC(e){if(this.sourceTrack&&!(Re||ge))return this.update3A({echoCancellation:e})}addDenoiser(e){var t;if(We<=92&&((t=this.trackSettings)==null?void 0:t.sampleRate)!==48e3){this._log.warn("denoiser only support sampleRate 48000 before chrome 93");return}v.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.enableTrackANS(!1)}mixAudioReference(e,t){if(this.mixedAudioReferenceMap.has(t))return;this.log.info(`mixAudioReference() => ${t}`);let r=On(e);if(!r)return;let s=new xe,n=Ee().createGain();n.gain.value=1;let a=new xe;s.pipeTo(a).pipeTo(this.pipeline.mixNode),s.setNode(r),a.setNode(n),this.mixedAudioReferenceMap.set(t,[s,a])}unMixAudioReference(e){let[t,r]=this.mixedAudioReferenceMap.get(e)||[];t&&(this.log.info(`unMixAudioReference() => ${e}`),t.deleteNode(),r==null||r.deleteNode(),this.mixedAudioReferenceMap.delete(e))}setAudioReferenceVolume(e,t){let[r,s]=this.mixedAudioReferenceMap.get(e)||[];s!=null&&s.node&&(s.node.gain.value=t/100,this.log.info(`setAudioReferenceVolume() => ${e} ${s.node.gain.value}`))}addAudioProcessor(e,t,r){this.pipeline.silentNode.setNode(r),this.pipeline.mixNode.setNode(t),this.pipeline.aec.setNode(e)}removeDenoiser(e){if(this.pipeline.denoiser.node===e)return this.pipeline.denoiser.deleteNode(),this.enableTrackANS(!0)}removeAudioProcessor(e){this.pipeline.aec.node===e&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode())}close(){this.mixedAudioReferenceMap.forEach(([e,t])=>{e.deleteNode(),t.deleteNode()}),this.mixedAudioReferenceMap.clear(),this.pipeline.remove(),this.earMonitorGainNode.deleteNode(),this._output.deleteNode(),be.off("audioInputAdded",this.handleMicrophoneAdded,this),be.off("audioInputRemoved",this.handleMicrophoneRemoved,this),S.off(A.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this),super.close()}recapture(e,t=!1){return p(this,null,function*(){try{yield Pe(o.prototype,this,"recapture").call(this,e,t)}catch(r){let s=(yield It()).find(n=>n.deviceId!==e);if(s)yield Pe(o.prototype,this,"recapture").call(this,s.deviceId);else throw r}})}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduceRight((t,r)=>r?r({frame:t,ntp:Fi()}):t,e):e}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}get enableEncryptFrame(){return this.manager&&!!this.manager.encodePipeline[0]}handleAudioContextLongSuspended({isSuspended:e}){if(this.pipeline.isProcessEnabled)if(e){this.isAudioContextLongSuspended=!0,this.log.warn(`context has suspended for ${vu/1e3} seconds, change to source audio${Ft?"":", non-Safari"}`);let t=this.sourceTrack||this.mediaTrack;t&&this.setOutputMediaStreamTrack(t)}else this.isAudioContextLongSuspended=!1,this.log.warn("context has resumed, change to processed audio"),this.pipeline.track&&this.setOutputMediaStreamTrack(this.pipeline.track)}setOutputMediaStreamTrack(e){if(this.isAudioContextLongSuspended){let t=this.sourceTrack||this.mediaTrack;t&&(e=t)}super.setOutputMediaStreamTrack(e)}};function zc(o,i=!1){let e=new DataView(o),t=[],r=0;for(;r<e.byteLength;){let s=0;if(r+4<=e.byteLength&&e.getUint8(r)===0&&e.getUint8(r+1)===0&&e.getUint8(r+2)===0&&e.getUint8(r+3)===1)s=4;else if(r+3<=e.byteLength&&e.getUint8(r)===0&&e.getUint8(r+1)===0&&e.getUint8(r+2)===1)s=3;else{r+=1;continue}let n=-1;for(let h=r+s;h<e.byteLength;h+=1){if(h+4<=e.byteLength&&e.getUint8(h)===0&&e.getUint8(h+1)===0&&e.getUint8(h+2)===0&&e.getUint8(h+3)===1){n=h;break}if(h+3<=e.byteLength&&e.getUint8(h)===0&&e.getUint8(h+1)===0&&e.getUint8(h+2)===1){n=h;break}}let a=n===-1?e.byteLength:n,c=a-r,l=new ArrayBuffer(c),u=new DataView(l);for(let h=0;h<c;h+=1)u.setUint8(h,e.getUint8(r+h));t.push(new sr(u,i)),r=a}return t}var sr=class{constructor(i,e=!1){this.dataView=i;this.isSEI&&(e?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let{seiPayloadStartIndex:i}=this,e=this.dataView.byteLength-2,t=[],r=0;for(let n=i;n<=e;n++){let a=this.dataView.getInt8(n);switch(a){case 0:case 1:case 2:case 3:r===2&&(t.push(3),r=0),a===0?r+=1:r=0,t.push(a);break;default:r=0,t.push(a);break}}t.push(this.dataView.getInt8(this.dataView.byteLength-1));let s=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=s}removePreventionByte(){let{seiPayloadStartIndex:i}=this,e=this.dataView.byteLength-1,t=[],r=0;for(let n=i;n<=e;n++)switch(this.dataView.getInt8(n)){case 0:r++,t.push(this.dataView.getInt8(n));break;case 3:r!==2&&t.push(this.dataView.getInt8(n)),r=0;break;default:t.push(this.dataView.getInt8(n)),r=0;break}let s=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=s}get seiPayloadStartIndex(){let i=6;for(let e=6;e<this.dataView.buffer.byteLength&&(i+=1,this.dataView.getUint8(e)===255);e+=1);return i}get seiPayloadType(){return this.isSEI?this.dataView.getUint8(5):null}get seiPayload(){if(!this.isSEI)return null;let i=0,e=6;for(let n=6;n<this.dataView.buffer.byteLength;n+=1){let a=this.dataView.getUint8(n);if(e+=1,a===255)i+=255;else{i+=a;break}}let t=new ArrayBuffer(i),r=new DataView(t),s=e;for(let n=0;n<t.byteLength;n+=1)r.setInt8(n,this.dataView.getInt8(s+n));return r}get naluType(){let i=this.getStartCodeLength();return i>=this.dataView.byteLength?0:this.dataView.getUint8(i)&31}getStartCodeLength(){return this.dataView.byteLength>=4&&this.dataView.getUint8(0)===0&&this.dataView.getUint8(1)===0&&this.dataView.getUint8(2)===0&&this.dataView.getUint8(3)===1?4:this.dataView.byteLength>=3&&this.dataView.getUint8(0)===0&&this.dataView.getUint8(1)===0&&this.dataView.getUint8(2)===1?3:0}get isIDR(){return this.naluType===5}get isSPS(){return this.naluType===7}get isPPS(){return this.naluType===8}get isSEI(){return this.naluType===6}};var Qc=class{constructor(){d(this,"_seiMessageList",[]);d(this,"_smallSeiMessageList",[]);d(this,"_seiPayloadType",243)}encodeSEINalu(i){let e=i.byteLength,t=parseInt(String(e/255),10),r=e%255,s=[];s.push(0,0,0,1,6,this._seiPayloadType);for(let a=0;a<t;a++)s.push(255);s.push(r);let n=new DataView(i);return s.push(...new Uint8Array(n.buffer)),s.push(128),new sr(new DataView(new Uint8Array(s).buffer),!0)}sendSEI(i,e){e!=null&&e.seiPayloadType&&(this._seiPayloadType=e.seiPayloadType),this._seiMessageList.push(i),e!=null&&e.small&&this._smallSeiMessageList.push(i)}isEmpty(){return!this._seiMessageList.length}getNaluCount(i){let e=0,t=0,r=new DataView(i);for(let s=0;s<i.byteLength;s++)switch(r.getUint8(s)){case 0:e++;break;case 1:(e===2||e===3)&&t++,e=0;break;default:e=0;break}return t}encode(i,e){let t=e?this._smallSeiMessageList:this._seiMessageList;if(t.length>0&&i.data.byteLength>0){let s=9-this.getNaluCount(i.data);if(s<=0)return 0;let n=t.splice(0,s).reverse().map(this.encodeSEINalu.bind(this)),a=n.reduce((m,_)=>m+_.dataView.byteLength,0),c=new ArrayBuffer(a+i.data.byteLength),l=new DataView(c),u=new DataView(i.data),h=0;for(let m=0;m<n.length;m++)for(let _=0;_<n[m].dataView.byteLength;_++)l.setInt8(h++,n[m].dataView.getInt8(_));for(let m=0;m<i.data.byteLength;m++)l.setInt8(h++,u.getInt8(m));return i.data=c,n.length}return 0}};var Or=class Or extends pi{constructor(e,t=4){super(t,it);d(this,"profile",O({},pr));d(this,"avoidCropping",!1);d(this,"_scaleResolutionDownBy");d(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0,framesCaptured:0});d(this,"small");d(this,"isNeedToSetBandwidth");d(this,"muteImage");d(this,"manager");d(this,"_seiCodec",new Qc);this.manager=e;let r=()=>{var s;if(this.isAllowed2k4k(this.profile))this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1});else{let n=Ut(((s=this.room)==null?void 0:s.sdkAppId)||0)?ha:ua;this.log.warn(`Resolution is reset to 1080p, need to upgrade ability here ${n}`),this.setProfile(L(O({},this.profile),{width:1920,height:1080})),this.applyProfile()}};this.on("input-media-track-changed",r),this.on("publish",r),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(!(!yi||!this.mediaTrack))return this.mediaTrack.getSettings().facingMode}get contentHint(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)||""}get isQosClearFirst(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)==="detail"}get hasSmall(){var e;return!!((e=this.manager)!=null&&e.hasSmall)}setMute(e){return p(this,null,function*(){var t,r,s;if(ie(e)){if(this.muteImage===e)return;yield(t=this.manager)==null?void 0:t.deleteWatermark("mute"),yield(r=this.manager)==null?void 0:r.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:e,fillVideo:!0}),this.muteImage=e,Pe(Or.prototype,this,"setMute").call(this,!1)}else this.muteImage&&(yield(s=this.manager)==null?void 0:s.deleteWatermark("mute"),this.muteImage=void 0),Pe(Or.prototype,this,"setMute").call(this,e)})}capture(a){return p(this,arguments,function*({deviceId:e,facingMode:t,useExactDeviceId:r=!0,customSource:s,retryWhenExactFailed:n=!0}){let c={audio:!1,video:!0,facingMode:t||this.facingMode,cameraId:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:r,retryWhenExactFailed:n,customSource:s};if(c.facingMode==="environment"){let l=yield this.getDeviceIdWhenUsingBackCamera();l&&(c.cameraId=l)}return Pe(Or.prototype,this,"capture").call(this,c)})}setProfile(e){var r;let t=this.fallbackProfile(e);if(t.bitrate&&(this.isNeedToSetBandwidth=t.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile))super.setProfile(t);else{let s=Ut(((r=this.room)==null?void 0:r.sdkAppId)||0)?ha:ua;this.log.warn(`Resolution is reset to 1080p, need to upgrade ability here ${s}`),super.setProfile(L(O({},this.profile),{width:1920,height:1080}))}}applyProfile(){return p(this,null,function*(){var a;if(!this.mediaTrack)return;let{width:e=0,height:t=0}=(this.sourceTrack||this.mediaTrack).getSettings(),r=e*t,s=this.settings,n=s.height!==this.profile.height||s.width!==this.profile.width||s.frameRate!==this.profile.frameRate;if(n&&(et===16&&this.deviceId?yield this.recapture(this.deviceId):(yield(a=this.sourceTrack||this.mediaTrack)==null?void 0:a.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}),this.manager&&this.manager.changeInput(this)),this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1})),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth){this.isNeedToSetBandwidth=!1;let{width:c=0,height:l=0}=(this.sourceTrack||this.mediaTrack).getSettings(),u=c*l;if(n&&u&&r&&u===r){this.log.warn("set bandwidth failed: resolution is not changed");return}return this.room.setBandWidth({bandwidth:this.profile.bitrate,type:f.VIDEO,videoType:f.BIG})}})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},t=this.sourceTrack||this.mediaTrack;return yi&&t&&Object.assign(e,t.getSettings()),e}get scaleResolutionDownBy(){return this._scaleResolutionDownBy?this._scaleResolutionDownBy:Ho(this.settings,this.profile)}isAllowed2k4k(e){var t;return!this.room||!this.room.scheduleResult||this.isScreen||e.height*e.width<2560*1440?!0:((t=this.room.scheduleResult.trtcAutoConf)==null?void 0:t["2k4k"])===1}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}switchDevice(e){return p(this,null,function*(){try{if(!this.isNeedToSwitchDevice(e)&&!this.isUseCustomSource)return;let t={useExactDeviceId:!0,retryWhenExactFailed:!1};e==="user"||e==="environment"?t.facingMode=e:t.deviceId=e,this.sourceTrack&&this.sourceTrack.stop(),yield this.capture(t),S.emit(A.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(t){throw this.log.error(`switch camera failed ${t}`),this.deviceId&&this.recapture(this.deviceId),t}})}getDeviceIdWhenUsingBackCamera(){return p(this,null,function*(){let e;try{if(rn&&!Qo&&du){let r=(yield At(!0)).map(n=>{var a;return L(O({},n),{capabilities:(a=n.getCapabilities)==null?void 0:a.call(n)})}).filter(n=>{var a,c;return(c=(a=n.capabilities)==null?void 0:a.facingMode)==null?void 0:c.includes("environment")}),s=r[0];r.forEach(n=>{var u,h,m,_;let{capabilities:a}=n,c=(u=a.width)!=null&&u.max&&((h=a.height)!=null&&h.max)?a.width.max*a.height.max:0,l=(m=s.capabilities.width)!=null&&m.max&&((_=s.capabilities.height)!=null&&_.max)?s.capabilities.width.max*s.capabilities.height.max:0;c>l&&(s=n)}),s!=null&&s.capabilities&&(this._log.info("use max resolution back camera",s),e=s.deviceId)}}catch(t){this._log.warn("get max res camera failed",t)}return e})}updateSmallConfig(e){var r,s;this._log.info(`update small stream config: ${JSON.stringify(e)}`);let t=!this.small;this.small=this.fallbackProfile(e,!0),(r=this.manager)==null||r.update(),t&&((s=this.room)==null||s.enableSmall(!0)),this.log.info("update small stream config success")}fallbackProfile(e,t=!1){let r=e.width>e.height,s=O({},e);return e.width*e.height<=160*120&&_e&&Ve&&(this.log.warn(`${t?"small ":""}resolution is ${e.width}*${e.height}, fallback to 240*180 for android chrome`),s.width=r?240:180,s.height=r?180:240,s.bitrate=Math.max(e.bitrate,150)),e.width*e.height>1280*720&&Ol&&(s.width=r?1280:720,s.height=r?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),nn(Tt,"14.3")&&Dl(Tt,"14.0",!0)&&this.on("7",()=>{let n=this.profile.width>this.profile.height;this.profile.width*this.profile.height>640*480?(this.profile.width=n?640:480,this.profile.height=n?480:640,this.log.warn("reduce the resolution to 480p on iOS 14.0 ~ 14.2")):this.profile.width*this.profile.height>640*360&&(this.profile.width=n?640:360,this.profile.height=n?360:640,this.log.warn("reduce the resolution to 360p on iOS 14.0 ~ 14.2"))}),!t&&this.avoidCropping&&(Ve||K)&&!an()&&e.width*e.height<=640*360&&e.width/e.height===16/9&&(this._scaleResolutionDownBy=1280/e.width,e.width=1280,e.height=720,this.log.warn(`capture 720p, scale: ${this._scaleResolutionDownBy}`)),s}stopSmall(){var e,t;this.small&&(delete this.small,(e=this.manager)==null||e.update(),(t=this.room)==null||t.enableSmall(!1))}listenDeviceChange(){be&&!be.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&be.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return p(this,null,function*(){if(e.deviceId===this.deviceId){let t=this.recaptureMode===1;if(this.log.warn(`RecaptureMode: ${ps[this.recaptureMode]}. Current camera is lost: ${JSON.stringify(e)}`),this.recaptureMode===0){Ne(this.userId,{eventId:2003,param1:7,streamType:2});let r=yield At();r[0]?this.recapture(r[0].deviceId):t=!0}t&&be.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return p(this,null,function*(){this.recaptureMode===1&&e.deviceId!==this.deviceId||(be.off("videoInputAdded",this.handleCameraAdded,this),this.log.warn(`camera added: ${JSON.stringify(e)}`),this.recapture(e.deviceId))})}encodeFrame(e,t){if(!this.manager)return e;let r=t?8:this.mediaType;return this.manager.encodePipeline.reduceRight((s,n)=>n?n({frame:s,mediaType:r}):s,e)}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}play(e,t){return T(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,t)}close(){be.off("videoInputAdded",this.handleCameraAdded,this),be.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return p(this,null,function*(){try{yield Pe(Or.prototype,this,"recapture").call(this,e)}catch(t){let r=(yield At()).find(s=>s.deviceId!==e);if(r)yield Pe(Or.prototype,this,"recapture").call(this,r.deviceId);else throw t}})}setContentHint(e){this.mediaTrack&&"contentHint"in this.mediaTrack&&(this.mediaTrack.contentHint!==e&&(this.log.info(`setContentHint ${e}`),this.mediaTrack.contentHint=e),this.outMediaTrack&&this.outMediaTrack.contentHint!==e&&(this.outMediaTrack.contentHint=e))}setRotation(e){this.manager&&(this.isScreen||T(e)||e!==this.rotation&&(this.rotation=e,this.manager.rotation=e))}};M([Ct(function(e){this.setContentHint(e.contentHint||"motion")})],Or.prototype,"capture",1);var je=Or;var Eh={};Vi(Eh,{REPORT_TYPE:()=>$o,buildSSOPackage:()=>Gi,bytes2ms:()=>Mm,calculateScaleResolutionDownNumber:()=>Ho,concatArrayBuffers:()=>ka,convertObjectNumberToInt:()=>Js,copyProperties:()=>Dm,deepClone:()=>Gr,deepCloneBasic:()=>ya,deepMerge:()=>ei,delay:()=>Ke,fibonacci:()=>Jr,formatedTime:()=>Fm,getConstructorName:()=>xo,getContainerFromElement:()=>Vm,getEnv:()=>bm,getFirst16Bits:()=>Hm,getInternalVersion:()=>xm,getLast16Bits:()=>Pa,getLoggerUrl:()=>Wi,getMediaStreamTrackInfo:()=>Oa,getMuteStateFromFlag:()=>Kt,getNetworkType:()=>ba,getNumNetworkType:()=>qr,getReconnectionTimeout:()=>Zt,getStringByteLength:()=>qs,getTurnServer:()=>Um,getUint32Version:()=>Na,getValueType:()=>Me,getViewListFromView:()=>Fo,glog:()=>_l,ipv4ToUint32:()=>Vo,isArray:()=>Ie,isAudioWorkletSupported:()=>wm,isBoolean:()=>he,isConstructor:()=>jr,isEmpty:()=>Uo,isFunction:()=>le,isLangChinese:()=>Yt,isMediaStreamTrack:()=>km,isNumber:()=>z,isObject:()=>yt,isOverseaSdkAppId:()=>Ut,isPlainObject:()=>dt,isPortrait:()=>gl,isPromise:()=>Tr,isRemoteTrack:()=>Pm,isRotate90Or270:()=>bt,isSetSinkIdSupported:()=>Lm,isString:()=>ie,isUndefined:()=>T,loadImage:()=>Bo,loadVideo:()=>Bm,ms2bytes:()=>Om,ms2samples:()=>fl,normalizeUrl:()=>Ma,performanceNow:()=>U,promiseAny:()=>Xr,samples2ms:()=>pl,setNetworkTypeFromWebRTC:()=>va,stringify:()=>_t,stringifyIncludeValue:()=>Gs,throttlePromise:()=>Da});var hS=[-1,-1,1,-1,-1,1,1,1],mS=[0,0,1,0,0,1,1,1];var kr=class kr extends J{constructor(e,t){super();this.context=e;d(this,"name");d(this,"input");d(this,"output");d(this,"texture");d(this,"ctx2d",null);d(this,"fbo");d(this,"width",0);d(this,"height",0);d(this,"x",0);d(this,"y",0);d(this,"program");d(this,"vertexShader");d(this,"fragmentShader");d(this,"totalFrames",0);d(this,"dropFrames",0);d(this,"matchInputSize",!0);d(this,"texCoordBuffer");d(this,"positionBuffer");d(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0});d(this,"cost",0);d(this,"_canvas",null);d(this,"_image");d(this,"log");if(this.context.on("disconnect",this.close,this),this.name=t.name,this.log=t.logger,this.matchInputSize=t.matchInputSize!==!1,this.width=t.width||e.width,this.height=t.height||e.height,this._image=t.image,e instanceof Xe){e.ctx&&t.create2d&&(typeof OffscreenCanvas=="function"&&et!==16?this._canvas=new OffscreenCanvas(this.width,this.height):(this._canvas=document.createElement("canvas"),this._canvas.width=this.width,this._canvas.height=this.height),this.ctx2d=this._canvas.getContext("2d"),this._image=this._canvas);return}try{let r=e.ctx;this.texCoordBuffer=this.createBuffer(mS),this.positionBuffer=this.createBuffer(hS),t.createTexture!==!1&&(this.texture=r.createTexture(),this.useTexture(),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.pixelStorei(r.UNPACK_ALIGNMENT,1)),t.useFbo&&(this.fbo=r.createFramebuffer(),this.useBufferFrame(),this.useTexture(),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,this.width,this.height,0,r.RGBA,r.UNSIGNED_BYTE,null),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,this.texture,0)),t.useDefaultProgram?this.program=e.defaultProgam:(t.vertexShaderSource||t.fragmentShaderSource)&&(this.vertexShader=t.vertexShaderSource?e.createShader(r.VERTEX_SHADER,t.vertexShaderSource):e.defaultVShader,this.fragmentShader=t.fragmentShaderSource?e.createShader(r.FRAGMENT_SHADER,t.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(r){this.context.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${r.message||r}`}))}}get image(){return this._image}set image(e){this._image=e}createFramebuffer(e){let t=this.context.ctx,r=t.createFramebuffer();return t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0),r}connect(e,...t){return e.addInput(this,...t),this.output=e,e}addInput(e,...t){this.input=e,this.matchInputSize&&e.width&&e.height&&this.resize(e.width,e.height)}requestFrame(e){let t=Date.now();if(this.context instanceof He&&this.render(e)||this.context instanceof Xe&&this.render2d(e))this.totalFrames++;else return!1;return this.cost=Date.now()-t,!0}render2d(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?this.draw2d(this.input.image,0,0,this.width,this.height):!1}update(e=0){var t;(t=this.output)==null||t.update(e)}disconnect(...e){var t;(t=this.output)==null||t.removeInput(this,...e),delete this.output}removeInput(e,...t){delete this.input}close(){var e,t;if(this.context.off("disconnect",this.close,this),(e=this.output)==null||e.removeInput(this),delete this.output,(t=this.input)==null||t.disconnect(),this.context instanceof He){let r=this.context.ctx;r.deleteBuffer(this.texCoordBuffer),r.deleteBuffer(this.positionBuffer),this.fbo&&r.deleteFramebuffer(this.fbo),this.texture&&r.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&r.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&r.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&r.deleteProgram(this.program)}this._canvas&&(this._canvas.width=0,this._canvas.height=0,this.ctx2d=null),this.removeAllListeners()}useTexture(){this.useTextures(this.texture)}useInputTexture(){var e;this.useTextures((e=this.input)==null?void 0:e.texture)}useTextures(...e){let t=this.context.ctx;e.forEach((r,s)=>{r&&(t.activeTexture(t.TEXTURE0+s),t.bindTexture(t.TEXTURE_2D,r))})}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}createBuffer(e){let t=this.context.ctx,r=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,r),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW),r}setTexBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}setPosBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}changeBufferData(e,t){let r=this.context.ctx;r.bindBuffer(r.ARRAY_BUFFER,e),r.bufferData(r.ARRAY_BUFFER,new Float32Array(t),r.STATIC_DRAW)}setAttributes(...e){let t=this.context.ctx;e.forEach((r,s)=>{t.enableVertexAttribArray(s),t.bindBuffer(t.ARRAY_BUFFER,r),t.vertexAttribPointer(s,2,t.FLOAT,!1,0,0)})}getVertexPoint(e,t){return[e/this.width*2-1,t/this.height*2-1]}layout2texCoords(e){return[...this.getVertexPoint(e.x,e.y),...this.getVertexPoint(e.x+e.width,e.y),...this.getVertexPoint(e.x,e.y+e.height),...this.getVertexPoint(e.x+e.width,e.y+e.height)]}resize(e,t){if(!(this.width===e&&this.height===t)){if(this.width=e,this.height=t,this._canvas&&(this._canvas.width=e,this._canvas.height=t),this.texture&&this.fbo){this.useTexture();let r=this.context.ctx;r.texImage2D(r.TEXTURE_2D,0,r.RGBA,e,t,0,r.RGBA,r.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(e,t)}}draw(e,t){this.setAttributes(e||this.positionBuffer,t||this.texCoordBuffer);let r=this.context.ctx;r.drawArrays(r.TRIANGLE_STRIP,0,4)}draw2d(e,t,r,s,n,a,c,l,u){let h=!T(a)&&!T(c)&&!T(l)&&!T(u);return this.ctx2d&&e?(e instanceof ImageData?(h?this.ctx2d.putImageData(e,t,r,a,c,l,u):this.ctx2d.putImageData(e,t,r),this.emit(kr.RENDER,this.ctx2d.canvas)):(h?this.ctx2d.drawImage(e,a,c,l,u,t,r,s,n):this.ctx2d.drawImage(e,t,r,s,n),this.emit(kr.RENDER,e)),typeof VideoFrame!="undefined"&&e instanceof VideoFrame&&e.close(),!0):!1}drawBackGround2d(e){this.ctx2d&&(this.ctx2d.save(),this.ctx2d.fillStyle=e,this.ctx2d.fillRect(0,0,this.width,this.height),this.ctx2d.restore())}getInfo(){var h;let{totalFrames:e,x:t,y:r,width:s,height:n,name:a,cost:c}=this,l=Date.now(),u=(e-this.lastInfo.totalFrames)/((l-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:r,width:s,height:n,timestamp:l,fps:u,name:a,cost:c},O({parent:(h=this.input)==null?void 0:h.getInfo()},this.lastInfo)}createTexture(e){let t=this.context.ctx,r=t.createTexture();return this.useTextures(r),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.pixelStorei(t.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),r}};d(kr,"RENDER","render"),M([ye(J.INIT,"connected",{sync:!0})],kr.prototype,"connect",1),M([ye("connected",J.INIT,{ignoreError:!0,sync:!0})],kr.prototype,"disconnect",1),M([ye([],"closed",{sync:!0})],kr.prototype,"close",1);var Ue=kr;var pS=de(Vu(250),Fn(()=>performance.now()),rr());var _f=o=>i=>{let e=performance.now();de(pS,Hc(t=>t-e<o),or(1))(i)};var _S=[0,1,1,1,0,0,1,0],fo=class extends Ue{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t));d(this,"_intervalId",0);d(this,"_sequence",0);d(this,"checkGLError",!1);d(this,"checkVisibilityChange");e instanceof Xe?this.ctx2d=e.ctx||null:e.available&&(t!=null&&t.mirrorUpAndDown)&&this.setTexBuffer(_S)}start(e){this.log.info(`${this.name} start render ${e} fps`),oe.clearTask(this._intervalId),this._intervalId=oe.run("intervalInWorker",()=>{if(e!==this.context.frameRate&&(oe.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof He){let r=this.context.ctx.getError();r&&this.context.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:5,message:`${this.name} req ${this._sequence} render ${this.totalFrames} faild ${r}`}))}},{fps:this.context.frameRate})}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),this.emit(Ue.RENDER,this.context._canvas),!0):!1}addInput(e,...t){super.addInput(e,...t),this.start(this.context.frameRate)}update(e=0){this.state!=="closed"&&(this._intervalId&&(oe.clearTask(this._intervalId),this._intervalId=0,e===1&&(this.log.info(`${this.name} use requestVideoFrameCallback`),this.checkVisibilityChange=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info(`${this.name} use timer`),document.removeEventListener("visibilitychange",this.checkVisibilityChange))},document.addEventListener("visibilitychange",this.checkVisibilityChange))),this.requestFrame(this._sequence++))}removeInput(e){super.removeInput(e),oe.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}close(){super.close(),oe.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},fs=class extends fo{constructor(e,t){super(e,t);d(this,"_videoTrack");d(this,"_muteOb");d(this,"_closedOb",ce(this,"closed"));d(this,"_subscription");d(this,"_canvasContainer");Number(Xi)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e.canvas.captureStream().getVideoTracks(),this._muteOb=ce(this._videoTrack,"mute"),de(ce(this._videoTrack,"ended"),ke(this._closedOb),Te(()=>{this.context.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){this._subscription=de(this._muteOb,ke(this._closedOb),mo(_f(5e3)),$t(()=>{var e;return!!((e=this._videoTrack)!=null&&e.muted)&&!document.hidden}),Te(()=>{this.context.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:7,message:"video track muted"}))}))}disableCheckMute(){var e;(e=this._subscription)==null||e.dispose()}get videoTrack(){return this._videoTrack}putCanvasIntoDom(){!this.context._canvas||!this._canvasContainer||document.getElementById(this.context._canvas.id)||(this.log.info(`${this.name} put canvas to body`),document.body.appendChild(this._canvasContainer),this._canvasContainer.appendChild(this.context._canvas))}render(e){return this.putCanvasIntoDom(),super.render(e)}render2d(e){return this.putCanvasIntoDom(),super.render2d(e)}close(){var e,t;super.close(),(e=this._videoTrack)==null||e.stop(),delete this._videoTrack,(t=this._canvasContainer)==null||t.remove()}},Yc=class extends fs{render(i){var t;let e=!!((t=this.input)!=null&&t.requestFrame(i));if(this.context._canvas2d){let r=this.context._canvas2d.getContext("2d");r.clearRect(0,0,this.context._canvas2d.width,this.context._canvas2d.height),r.drawImage(this.context._canvas,0,0,this.context._canvas2d.width,this.context._canvas2d.height)}return e}};var Zc=class extends fs{constructor(e,t,r){super(e,{name:"smallDestination",logger:r});this.resolution=t}resize(e,t){let r,s=e*t,n=this.resolution.width*this.resolution.height;this.log.info(`big res: ${e}*${t} small res: ${this.resolution.width}*${this.resolution.height} `),s>n?r=s/n:(this.log.warn(`Small stream resolution is not smaller than big stream, which is invalid. big: ${e} * ${t} small: ${this.resolution.width} * ${this.resolution.height}`),r=s/(160*120)),super.resize(e/Math.sqrt(r),t/Math.sqrt(r))}};var $n=class extends Ue{constructor(e,t){super(e,O({name:"imageSource"},t));d(this,"_lastImage");d(this,"_totalFrames",0);d(this,"_autoResize",!1);d(this,"_canvasRendered");d(this,"videoCallbackId",0);d(this,"waitingFirstFrame",!0);d(this,"shouldUpdate",!0);this._autoResize=(t==null?void 0:t.autoResize)!==!1,et===16&&(this._canvasRendered=ot(),de(this._canvasRendered,xn(this._image),Mr(r=>r instanceof HTMLCanvasElement?ce(r,"rendered"):Vn()),ke(ce(this,"closed")),Te(()=>{this.update()})))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){if(!this.shouldUpdate)return;let e=this.image;this.videoCallbackId&&e.cancelVideoFrameCallback(this.videoCallbackId),Ki()&&!document.hidden&&(this.videoCallbackId=e.requestVideoFrameCallback((t,r)=>{this.waitingFirstFrame&&this.onFirstFrame(),document.hidden||(this._totalFrames=r.presentedFrames,this.update(1))}))}_render(e,t){var a;let{width:r,height:s}=this,{image:n}=this;if(n instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(),{videoWidth:r,videoHeight:s}=n,!r||!s)return!1;n.width=r,n.height=s}else if(n instanceof HTMLImageElement||n instanceof ImageData||n instanceof ImageBitmap){if({width:r,height:s}=n,n!==this._lastImage)this._lastImage=n;else if(r===this.width&&s===this.height)return!0}else n instanceof HTMLCanvasElement||n instanceof OffscreenCanvas?({width:r,height:s}=n,this._lastImage=n):typeof VideoFrame!="undefined"&&n instanceof VideoFrame&&({displayWidth:r,displayHeight:s}=n,(a=this._lastImage)==null||a.close(),this._lastImage=n);if(!this._autoResize)return!0;if(this.width===r&&this.height===s&&this.totalFrames){if(t){this.useTexture();let c=this.context.ctx;c.texSubImage2D(c.TEXTURE_2D,0,0,0,c.RGBA,c.UNSIGNED_BYTE,n)}}else{if(t){this.useTexture();let c=this.context.ctx;c.texImage2D(c.TEXTURE_2D,0,c.RGBA,c.RGBA,c.UNSIGNED_BYTE,n)}this.resize(r,s)}return!0}get image(){return this._image}set image(e){var t;(t=this._canvasRendered)==null||t.next(e),this._image=e}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},Wn=class extends $n{constructor(e,t,r){super(e,r);this._player=t;this.name="videoPlayerSource",de(ce(this._player,ue.PLAYER_STATE_CHANGED),ke(ce(this,"closed")),$t(({state:s})=>s==="PLAYING"),Te(()=>{this.tryVideoFrameCallback()}))}get image(){return this._player.element}},Wt=class extends Wn{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(i,e,t){super(i,new it({id:t.name,track:e,muted:!0,container:null,objectFit:"contain",log:t.logger}),t),this.name="videoTrackSource",this._player.play()}replaceTrack(i){this.waitingFirstFrame=!0,this._player.setTrack(i),this._player.play()}close(){super.close(),this._player.stop()}},Kc=class extends Ue{constructor(e,t,r){super(e,L(O({name:"textSource"},r),{create2d:!0}));d(this,"hasChange",!0);d(this,"content","");this.ctx2d.textBaseline="top",this.content=t.content||"",t.font&&(this.font=t.font),t.color&&(this.color=t.color)}set font(e){this.ctx2d&&(this.ctx2d.font=e,this.hasChange=!0)}get font(){var e;return((e=this.ctx2d)==null?void 0:e.font)||""}set color(e){this.ctx2d&&(this.ctx2d.fillStyle=e,this.hasChange=!0)}get color(){var e;return((e=this.ctx2d)==null?void 0:e.fillStyle)||""}render2d(e){return this.ctx2d&&this.hasChange?(this.ctx2d.clearRect(0,0,this.width,this.height),this.drawMultilineText(0,0),this.hasChange=!1,!0):!1}render(e){return!1}resize(e,t){if(!this.ctx2d)return;let{color:r,font:s}=this;super.resize(e,t),this.color=r,this.font=s}drawMultilineText(e=0,t=0,r=1.2){if(!this.ctx2d)return;let s=this.ctx2d.measureText(this.content);t+=s.fontBoundingBoxAscent||s.actualBoundingBoxAscent||0;let n=this.font.match(/(\d+)px/),c=(n?parseInt(n[1],10):16)*r,l=this.content.split(`
|
|
33
|
+
`,t.onclick=this.onQuestionClick.bind(this);let r=document.createElement("div");r.className=Su,r.innerText=`${Yt()?"\u8BE6\u60C5 >":"Detail >"}`,r.onclick=this.onCollapseClick.bind(this);let s=i.content.firstChild,n=s.querySelector(`.${Ac}`);return n.appendChild(r),n.appendChild(t),n.appendChild(e),s}addDiaLog(){br()||(Iu=!0,this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${bn}`).onclick=i=>i.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",R.info("show autoplay dialog"),se.uploadEvent({log:$T}))}deleteDialog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null,Iu=!1)}onConfirm(){R.warn("confirm clicked, try resume stream"),S.emit(A.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDialog()}onCollapseClick(){let i=this._dialogNode.querySelector(`.${Up}`);i.style.visibility=`${this._showDetail?"hidden":"visible"}`,i.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||se.uploadEvent({log:WT}),this._isCollapseClicked=!0}onQuestionClick(){window.open(Hp,"_blank"),this._isQuestionClicked||se.uploadEvent({log:GT}),this._isQuestionClicked=!0}},vn=null;function ns(){vn||(vn=new Au)}function $p(){vn&&(vn.deleteDialog(),vn=null)}var it=class o extends mi{constructor(e){super(e,f.VIDEO);d(this,"stat",{});d(this,"_calculateTimeout",-1);d(this,"viewMirror",!1);d(this,"objectFit","cover");d(this,"container");d(this,"canvas");d(this,"shouldRenderAlpha",!1);d(this,"_preSize",{width:0,height:0});d(this,"posterImg");this.mode=e.canvas?1:0,this.container=e.container,this.canvas=e.canvas,T(e.viewMirror)||(this.viewMirror=e.viewMirror),T(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}get isPlaying(){var e;return this._state!=="PLAYING"||this.element&&this.element.paused?!1:((e=this.track)==null?void 0:e.readyState)==="live"&&!this.track.muted}initializeElement(){var t;let e=document.createElement(f.VIDEO);this.track&&this.mode!==2&&(e.srcObject=new MediaStream([this.track])),e.muted=!0,e.setAttribute("id",`video_${this.id}`),e.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),e.setAttribute("autoplay","autoplay"),e.setAttribute("playsinline","playsinline"),this.element=e,_e&&(e.poster="noposter"),(t=this.container)==null||t.appendChild(this.elementToRender),this.bindElementEvents(),this.calculateStat()}get styleAttribute(){let e=`width: 100%; height: 100%; object-fit: ${this.objectFit};${this.shouldRenderAlpha?"":"background-color: black"};`;return this.viewMirror&&(e+="transform: scaleX(-1);"),e}setContainer(e){var t;this.container=e,this.track&&this.elementToRender&&((t=this.container)==null||t.appendChild(this.elementToRender))}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),e&&e.add(f.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(f.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent).add(f.RESIZE,this.handleElementEvent)}handleTrackEvent(e){var t;return e.type===f.MUTE&&((t=this.stat)!=null&&t.fps)&&(this.stat.fps=0),super.handleTrackEvent(e)}handleElementEvent(e){var r,s,n,a,c,l;if(this.mode===2)return;super.handleElementEvent(e);let t=e.type;if(t===f.PAUSE&&(this.container&&!this.container.isConnected&&(this._log.warn(`${this.kind} player has been remove, element ID: ${this.container.id}`),Ke(500).then(()=>{var u;(u=this.container)!=null&&u.isConnected&&(this._pausedRetryCount=$r,this._log.info(`view container ${this.container.id} is in dom, reset pausedRetryCount`))})),this._pausedRetryCount>0&&!br()&&!this._isPausedByUserCall&&(this._log.info(`[${$r-this._pausedRetryCount+1}/${$r}] ${this.kind} player auto resume when paused`),this.doResume(),this._pausedRetryCount--),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){let u=this.element.style.transform;t===f.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=u.replace("scaleX(-1)",""):t===f.LEAVE_PICTURE_IN_PICTURE&&!u.includes("scaleX")&&(this.element.style.transform=`${u} scaleX(-1)`)}t===f.RESIZE&&(this._preSize.height!==((r=this.element)==null?void 0:r.videoHeight)||this._preSize.width!==((s=this.element)==null?void 0:s.videoWidth))&&(this._log.info(`video size changed to ${(n=this.element)==null?void 0:n.videoWidth}x${(a=this.element)==null?void 0:a.videoHeight}`),this._preSize.height=((c=this.element)==null?void 0:c.videoHeight)||0,this._preSize.width=((l=this.element)==null?void 0:l.videoWidth)||0,this.emit(ue.RESIZE,{newWidth:this._preSize.width,newHeight:this._preSize.height}))}setCanvas(e,t=1){var r,s,n,a;this.canvas!==e&&((r=this.canvas)==null||r.remove(),e==null||e.setAttribute("style",this.styleAttribute),this.canvas=e,this.mode=e?t:0,this.mode===2&&this.setTrack(e.captureStream().getVideoTracks()[0]),e?((s=this.element)==null||s.remove(),(n=this.container)==null||n.appendChild(e)):this.element&&((a=this.container)==null||a.appendChild(this.element)))}setAttr(e){let t=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},e);t.style=Object.assign({width:"100%",height:"100%"},t.style),super.setAttr(t)}get mirror(){return this.viewMirror}setRect(e,t){this.elementToRender&&(this.elementToRender.style.width=`${e}px`,this.elementToRender.style.height=`${t}px`)}setViewMirror(e){this.elementToRender&&(this.elementToRender.style.transform=e?"scaleX(-1)":""),this.viewMirror=e}setObjectFit(e){this.elementToRender&&(this.elementToRender.style.objectFit=`${e}`),this.objectFit=e}setPoster(e,t=!1){return new Promise(r=>{if(this.element)if(this._log.info("setPoster",e.slice(0,10)),this.element.poster=e,t&&(Re||K)){if(e==="")this.removePosterImg();else if(!this.posterImg){let s=document.createElement("img");s.src=e,s.style=`${this.styleAttribute}`,s.onload=()=>p(this,null,function*(){var n;s.decode&&(yield s.decode()),this.posterImg=s,this.elementToRender&&(this.elementToRender.style.display="none"),(n=this.container)==null||n.appendChild(s),r()})}}else r()})}removePosterImg(){this.posterImg&&(this.posterImg.remove(),this.elementToRender&&(this.elementToRender.style.display=""),URL.revokeObjectURL(this.posterImg.src),delete this.posterImg)}pause(e=!0){return p(this,null,function*(){return(Ve&&We>=128||e&&(K||Re))&&(yield this.setPoster(this.getVideoFrame(),!0)),Pe(o.prototype,this,"pause").call(this)})}resume(){return this.posterImg&&this.setPoster("",!0),super.resume()}stop(e=0){var t;super.stop(e),(t=this.canvas)==null||t.remove(),this.removePosterImg()}play(){return this.element?this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender):this.initializeElement(),this.mode===2?Promise.resolve():super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(ue.MEDIA_TRACK_CHANGED,e),e!==null&&(this.bindTrackEvents(),this.element&&this.mode!==2&&(this.element.srcObject=new MediaStream([e]),this.element.remove()),this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender)))}getVideoFrame(){if(this.canvas)return this.canvas.toDataURL("image/png");if(!this.element)return"";let e=document.createElement("canvas");return e.width=this.element.videoWidth,e.height=this.element.videoHeight,e.getContext("2d").drawImage(this.element,0,0),e.toDataURL("image/png")}getElement(){return this.element}calculateStat(){try{if(Ki()&&this.element&&this._calculateTimeout<0){let e=0,t=null,r=(s,n)=>{this.stat.width=n.width,this.stat.height=n.height,t&&(this.stat.fps=Math.round((n.presentedFrames-t.presentedFrames)/(s-e)*1e3)),e=s,t=n,this._calculateTimeout=-1,this.element&&(this._calculateTimeout=setTimeout(()=>{var a;return(a=this.element)==null?void 0:a.requestVideoFrameCallback(r)},2e3))};this.element.requestVideoFrameCallback(r)}}catch(e){this._log.warn("init stat failed",e)}}enterFullscreen(){return p(this,null,function*(){let e=this.elementToRender;if(!e)throw this._log.warn("no element to render, cannot enter fullscreen"),new Error("No element available for fullscreen");try{if(e.requestFullscreen)yield e.requestFullscreen();else if(e.webkitRequestFullscreen)yield e.webkitRequestFullscreen();else if(e.webkitEnterFullscreen)yield e.webkitEnterFullscreen();else if(e.mozRequestFullScreen)yield e.mozRequestFullScreen();else if(e.msRequestFullscreen)yield e.msRequestFullscreen();else throw this._log.warn("fullscreen API not supported"),new Error("Fullscreen API not supported");this._log.info("entered fullscreen mode")}catch(t){throw this._log.error("failed to enter fullscreen:",t),t}})}exitFullscreen(){return p(this,null,function*(){try{if(document.exitFullscreen)yield document.exitFullscreen();else if(document.webkitExitFullscreen)yield document.webkitExitFullscreen();else if(document.mozCancelFullScreen)yield document.mozCancelFullScreen();else if(document.msExitFullscreen)yield document.msExitFullscreen();else throw this._log.warn("exit fullscreen API not supported"),new Error("Exit fullscreen API not supported");this._log.info("exited fullscreen mode")}catch(e){throw this._log.error("failed to exit fullscreen:",e),e}})}isFullscreen(){let e=this.elementToRender;return e?(document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement)===e:!1}toggleFullscreen(){return p(this,null,function*(){this.isFullscreen()?yield this.exitFullscreen():yield this.enterFullscreen()})}enterPictureInPicture(){return p(this,null,function*(){if(!this.element)throw new Error("No video element available for picture-in-picture");if(this.canvas&&this.mode!==1)throw new Error("Picture-in-picture is not supported for canvas-only mode");let{element:e}=this;try{if(this._log.warn(!!e.requestPictureInPicture,!!e.webkitSetPresentationMode),e.requestPictureInPicture){this._log.info("requestPictureInPicture");let t=yield e.requestPictureInPicture();return this._log.info("entered picture-in-picture mode"),t}if(e.webkitSetPresentationMode)return this._log.info("webkitSetPresentationMode"),yield e.webkitSetPresentationMode("picture-in-picture"),this._log.info("entered picture-in-picture mode (webkit)"),{};throw new Error("Picture-in-picture API not supported")}catch(t){throw this._log.error("failed to enter picture-in-picture:",t.name,t.message),t}})}exitPictureInPicture(){return p(this,null,function*(){try{if(document.pictureInPictureElement&&document.exitPictureInPicture)yield document.exitPictureInPicture(),this._log.info("exited picture-in-picture mode");else if(this.element&&this.element.webkitSetPresentationMode)yield this.element.webkitSetPresentationMode("inline"),this._log.info("exited picture-in-picture mode (webkit)");else throw this._log.warn("exit picture-in-picture API not supported or not in PiP mode"),new Error("Exit picture-in-picture API not supported or not in PiP mode")}catch(e){throw this._log.error("failed to exit picture-in-picture:",e),e}})}isPictureInPicture(){if(!this.element)return!1;let{element:e}=this;return document.pictureInPictureElement?document.pictureInPictureElement===e:e.webkitPresentationMode?e.webkitPresentationMode==="picture-in-picture":!1}togglePictureInPicture(){return p(this,null,function*(){this.isPictureInPicture()?yield this.exitPictureInPicture():yield this.enterPictureInPicture()})}};function tr(o,i){return p(this,null,function*(){if(!o.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield o.audioWorklet.addModule(i),R.info("worklet addModule success")}catch(e){throw R.info(`worklet addModule catch error. ${e.message}`),e}})}var Nn;typeof AudioContext!="undefined"?Nn=AudioContext:typeof webkitAudioContext!="undefined"?Nn=webkitAudioContext:typeof mozAudioContext!="undefined"&&(Nn=mozAudioContext);var vu=1500,rt,Wp=-1,Rc=0,Dn=-1,bu=!1,Gp=0,qp=-1,Jp=-1;jp();function jp(){try{if(rt)return;rt=new Nn({sampleRate:48e3}),rt.onstatechange=()=>{R.info(`context state: ${rt.state}${rt.state!=="running"?` visibilityState: ${document.visibilityState}`:""}`),as()},clearTimeout(Wp)}catch(o){R.error(`initAudioContext failed: ${o} typeof AudioContextClass: ${typeof Nn}`),Wp=setTimeout(jp,1e3)}}var as=()=>{rt.state==="suspended"?(Rc=U(),JT(),vr(),document.addEventListener("click",as)):rt.state==="interrupted"?vr():(Rc&&(v.addNumber({key:507800,value:U()-Rc,split:[0,500,1e3,1500,2e3,3e3,4e3,5e3,1e4,3e4],max:6e4}),Rc=0),jT(),document.removeEventListener("visibilitychange",as),document.removeEventListener("click",as))},Ru=0,yu=-1;function vr(){return new Promise((o,i)=>{if(rt.state==="running")return o();Date.now()-Ru<1e3?(clearTimeout(yu),yu=setTimeout(()=>{Ru=Date.now(),rt.resume().then(o,i)},1e3)):(clearTimeout(yu),Ru=Date.now(),rt.resume().then(o,i))}).catch(o=>{R.warn(`context resume failed: ${o}`),document.addEventListener("visibilitychange",as)})}document.addEventListener("click",as);function JT(){Dn===-1&&(Dn=setTimeout(()=>{rt.state==="suspended"&&(bu=!0,S.emit("155",{isSuspended:!0}))},vu))}function jT(){Dn!==-1&&(clearTimeout(Dn),Dn=-1,bu&&(bu=!1,S.emit("155",{isSuspended:!1})))}function Xp(){if(!ge||Jp!==-1)return;let o=()=>{U()-Gp<500||(rt&&rt.state==="running"&&rt.currentTime===qp&&(R.warn("context is fake running, auto resume"),rt.suspend().catch(i=>{R.warn(`context suspend failed: ${i}`)})),qp=rt.currentTime,Gp=U())};Jp=setInterval(()=>{o()},2e3),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&o()})}var Ee=o=>rt;var xe=class{constructor(i){this.name=i;d(this,"node");d(this,"node2");d(this,"pre",new Set);d(this,"next",new Set);d(this,"context");d(this,"connectedNodes",new Set);d(this,"nextInputChannelMap",new Map);d(this,"_channelCount",1)}get channelCount(){return this._channelCount}set channelCount(i){this._channelCount=i,this.setChannelCount(this.node,i),this.setChannelCount(this.node2,i),this.next.forEach(e=>e.channelCount=i)}setChannelCount(i,e){!i||i instanceof ScriptProcessorNode||(i.channelCountMode="explicit",i.channelCount=e||this.channelCount||1)}setContext(i){this.context=i,this.node&&i.addMixWeight()}removeContext(){var i;this.node&&((i=this.context)==null||i.reduceMixWeight()),delete this.context}replaceNode(i){var e;if(i!==this.node)try{this.node?this._disconnect():(e=this.context)==null||e.addMixWeight(),this.node=i,this.setChannelCount(this.node),this.preNodeReconnect(),this.reconnect()}catch(t){R.error(t)}}setNode(i,e){var t;if(!this.node)try{(t=this.context)==null||t.addMixWeight(),this.node=i,this.setChannelCount(this.node),e&&(this.node2=e,this.setChannelCount(this.node2)),this.preNodeReconnect(),this.reconnect(),v.addSuccessEvent({key:502701})}catch(r){R.error(r),v.addFailedEvent({key:502701,error:r})}}deleteNode(){var i;if(this.node)try{this._disconnect(),delete this.node,delete this.node2,(i=this.context)==null||i.reduceMixWeight(),this.preNodeReconnect(),v.addSuccessEvent({key:502702})}catch(e){R.error(e),v.addFailedEvent({key:502702,error:e})}}preNodeReconnect(){this.pre.forEach(i=>{i.node?i.reconnect():i.preNodeReconnect()})}connectNext(i){this.next.forEach(e=>{let t=this.nextInputChannelMap.get(e);i._connect(e.node,t)||e.connectNext(i)})}_connect(i,e=0){return!this.node||!i?!1:((this.node2||this.node).connect(i,0,e),this.connectedNodes.add(i),!0)}_disconnect(){this.connectedNodes.forEach(i=>{var e;return(e=this.node2||this.node)==null?void 0:e.disconnect(i)}),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(i,e=0){return this.next.add(i),i.pre.add(this),this.nextInputChannelMap.set(i,e),i}},yc=class extends xe{constructor(e=256){super();this.fftSize=e;d(this,"dataArray",new Uint8Array(0))}setNode(e){e.fftSize=this.fftSize,this.dataArray=new Uint8Array(e.frequencyBinCount),super.setNode(e)}getByteTimeDomainData(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),this.dataArray}get level(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),Math.max(...this.dataArray)/128-1}get timeDomainPathData(){let e=this.getByteTimeDomainData(),t=1,r=0,s=0,n=`M${r},${s}`;for(let a=0;a<e.length;a++)s=e[a]/128*100/2,n+=`L${r},${s}`,r+=t;return n}},Mn=class{constructor(){d(this,"source",new xe);d(this,"gain",new xe);d(this,"destination",new xe)}get volume(){var i;return((i=this.gain.node)==null?void 0:i.gain.value)||1}setVolume(i){if(i===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(Ee().createGain()),this.gain.node.gain.value=i}replaceSource(i){let e=On(i);e&&this.source.replaceNode(e)}get track(){var i;return(i=this.stream)==null?void 0:i.getAudioTracks()[0]}get stream(){var i;return(i=this.destination.node)==null?void 0:i.stream}},cs=class extends Mn{constructor(e){super();this.context=e;d(this,"aec",new xe("aec"));d(this,"mixNode",new xe("mixNode"));d(this,"silentNode",new xe("silentNode"));d(this,"denoiser",new xe("denoiser"));d(this,"voiceChanger",new xe("voiceChanger"));this.source.pipeTo(this.aec).pipeTo(this.denoiser).pipeTo(this.voiceChanger).pipeTo(this.gain).pipeTo(this.destination),this.silentNode.pipeTo(this.mixNode).pipeTo(this.aec,1)}get isProcessEnabled(){return this.aec.node||this.denoiser.node||this.voiceChanger.node||this.gain.node}connect(){this.context.inputs.has(this)||(this.destination.setNode(this.context.destination),this.source.setContext(this.context),this.aec.setContext(this.context),this.silentNode.setContext(this.context),this.mixNode.setContext(this.context),this.denoiser.setContext(this.context),this.voiceChanger.setContext(this.context),this.gain.setContext(this.context),this.context.inputs.add(this))}disconnect(){this.context.inputs.has(this)&&(this.destination.deleteNode(),this.source.removeContext(),this.aec.removeContext(),this.silentNode.removeContext(),this.mixNode.removeContext(),this.denoiser.removeContext(),this.voiceChanger.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.aec.deleteNode(),this.silentNode.deleteNode(),this.mixNode.deleteNode(),this.denoiser.deleteNode(),this.voiceChanger.deleteNode(),this.source.deleteNode(),this.disconnect()}setVolume(e){if(e===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(this.context.audioContext.createGain()),this.gain.node.gain.value=e}},bc=class{constructor(){d(this,"audioContext",Ee("audio-mixer"));d(this,"destination",this.audioContext.createMediaStreamDestination());d(this,"inputs",new Set);d(this,"mixWeight",0);this.destination.channelCount=1}addMixWeight(i=1){this.mixWeight+=i,this.mixWeight-1===i+1>>1&&this.mixOnChange()}reduceMixWeight(i=1){this.addMixWeight(-i)}close(){this.inputs.forEach(i=>i.remove())}get mixTrack(){return this.destination.stream.getAudioTracks()[0]}},zp=new WeakMap;function On(o){try{let i=zp.get(o);if(i)return i;let e=Ee();if(o instanceof HTMLAudioElement)i=e.createMediaElementSource(o);else if(o instanceof MediaStreamTrack)i=e.createMediaStreamSource(new MediaStream([o]));else return o;return zp.set(o,i),i}catch(i){if(K&&i instanceof Error&&i.name==="NotSupportedError")R.warn(i);else throw i}}var Ot=class Ot{constructor(i){d(this,"_volume",0);d(this,"_volumeDb",0);d(this,"_log");d(this,"_scriptProcessorNode",null);d(this,"_audioWorkletNode",null);d(this,"_interval",200);d(this,"ready",this.preload());let{log:e}=i;this._log=e,S.on(A.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-Ot.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!Ot.workletReady){let i='class VolumeMeterWorklet extends AudioWorkletProcessor{constructor(){super(),this.volume=0,this.intervalTime=200,this.tick=200,this.isStop=!1,this.cache=[],this.sentFirstInfo1=!1,this.unmute=!1,this.port.onmessage=t=>{var e=t.data;switch(e.name){case"chunk":this.cache.push(...e.data),this.sentFirstInfo1||(this.port.postMessage({cl:e.data.length}),this.sentFirstInfo1=!0);break;case"setIntervalTime":this.intervalTime=e.intervalTime;break;case"unmute":this.unmute=!0;break;case"stop":this.isStop=!0}}}process(t,s){t=t[0],s=s[0];if(t||s){if(this.isStop)return!1;var i=s&&s[0]?s[0].length:0,h=this.cache.length,a=(i<h?(s[0].set(this.cache.slice(0,i)),this.cache=this.cache.slice(i)):this.unmute&&s[0].set(t[0]),(i<h?s:t)[0]);if(a){let e=0;for(let t=0;t<a.length;++t)e=Math.max(Math.abs(a[t]),e);s=a.reduce((t,e)=>t+e*e,0)/a.length;this.volume=e,this.tick-=a.length,this.tick<0&&(this.tick+=this.intervalTime/1e3*sampleRate,this.port.postMessage({volume:this.volume,volumeDb:Math.max(10*Math.log10(s)+100,0)/100,cacheLen:h,outputLen:i}))}}return!0}}registerProcessor("volume-meter",VolumeMeterWorklet);';Ot.workletReady=tr(Ot.audioContext,URL.createObjectURL(new Blob([i],{type:"application/javascript"})))}return Ot.workletReady.then(()=>this.initAudioWorklet()).catch(i=>(this._log.error(`volumeMeter preload error: ${i}`),this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(Ot.audioContext,"volume-meter");let i=!1;this._audioWorkletNode.port.onmessage=e=>{Ot.lastMessageTime=Date.now(),this._volume=e.data.volume||0,this._volumeDb=e.data.volumeDb||0,!i&&e.data.cacheLen&&e.data.outputLen&&(this._log.warn("worklet play success"),i=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(i){this._log.error(`volumeMeter init audio worklet error: ${i}`),se.logFailedEvent({userId:this._log.userId,eventType:Ze.LOAD_WORKLET,error:i}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=Ee("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=i=>{Ot.lastMessageTime=Date.now();let e=i.inputBuffer.getChannelData(0),t=0;for(let r=0;r<e.length;++r)t+=e[r]*e[r];this._volume=Math.sqrt(t/e.length)||0}}catch(i){this._log.error(`volumeMeter init script processor error: ${i}`)}}destroy(){this._scriptProcessorNode&&(this._scriptProcessorNode.onaudioprocess=null),this._audioWorkletNode&&(this._audioWorkletNode.port.postMessage({name:"stop"}),this._audioWorkletNode.port.onmessage=null),this._audioWorkletNode=null,this._scriptProcessorNode=null,S.off(A.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}getVolumeDb(){return Math.floor(this._volumeDb*100)}handleAudioLevelInterval(i){var t;let{interval:e}=i;this._interval=e,(t=this._audioWorkletNode)==null||t.port.postMessage({name:"setIntervalTime",intervalTime:e})}};d(Ot,"lastMessageTime",0),d(Ot,"audioContext",Ee("volume-meter")),d(Ot,"workletReady");var vc=Ot,kn=class extends xe{constructor(e){super();d(this,"_volumeMeter");this._volumeMeter=new vc(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return p(this,null,function*(){yield this._volumeMeter.preload(),this.setNode(this._volumeMeter.node)})}getCalculatedVolume(){return this._volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this._volumeMeter.getInternalAudioLevel()}getVolumeDb(){return this._volumeMeter.getVolumeDb()}write(e){if(this.node){let t=e.allocationSize({planeIndex:0}),r=new Float32Array(t>>2);e.copyTo(r,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:r},[r.buffer]),e.close()}}},so=vc;var Kp=qe(at(),1);var Yp=o=>i=>i.deviceId===o;var Pn=class{constructor(i,e){d(this,"kind");d(this,"type");d(this,"devices",[]);this.kind=i,this.type=e}update(i,e){let t=i.filter(r=>r.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);if(this.devices.length===1&&ls(this.devices[0])){this.devices=t;return}e&&(t.forEach(r=>{if(r.deviceId&&!this.devices.find(Yp(r.deviceId))){let s=`${this.kind}${this.type}Added`;R.warn(`${s}: ${JSON.stringify(r)}`),e.emit(s,r)}}),this.devices.forEach(r=>{if(r.deviceId&&!t.find(Yp(r.deviceId))){let s=`${this.kind}${this.type}Removed`;R.warn(`${s}: ${JSON.stringify(r)}`),e.emit(s,r)}})),this.devices=t}hasDevice(i){return!!this.devices.find(e=>e.deviceId===i)}},Nu=class extends Kp.EventEmitter{constructor(){super();d(this,"audioInputs",new Pn(f.AUDIO,"Input"));d(this,"videoInputs",new Pn(f.VIDEO,"Input"));d(this,"audioOutputs",new Pn(f.AUDIO,"Output"));this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||oe.run("interval",()=>{this.update()},{delay:1e4}))}init(){ds().then(e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)})}update(){return p(this,arguments,function*(e=0){let t=yield ds(e);return this.audioInputs.update(t,this),this.videoInputs.update(t,this),this.audioOutputs.update(t,this),this})}hasBlueTooth(){var t;if(((t=Ee())==null?void 0:t.outputLatency)*1e3>150)return!0;let e=["bluetooth","air","wireless","bt","tws","buds","headset","headphone"];return this.audioOutputs.devices.some(r=>e.some(s=>r.label.toLowerCase().includes(s)))||this.audioInputs.devices.some(r=>e.some(s=>r.label.toLowerCase().includes(s)))}},be=xs||Do?null:new Nu;function ls(o){return o.deviceId===o.groupId&&o.groupId===""}function ds(){return p(this,arguments,function*(o=0){if(Zi()||!pc())return[];let i=yield navigator.mediaDevices.enumerateDevices();if(o!==0){let e={audio:!1,video:!1};if(i.forEach(t=>{ls(t)&&(t.kind===f.AUDIO_INPUT?e.audio=!0:t.kind===f.VIDEO_INPUT&&(e.video=!0))}),o===2&&(e.audio=!1),o===1&&(e.video=!1),e.audio||e.video){let t;try{t=yield navigator.mediaDevices.getUserMedia(e),e.audio&&vr()}catch(r){R.debug("capture before getDevices failed: ",r)}i=yield navigator.mediaDevices.enumerateDevices(),t==null||t.getTracks().forEach(r=>r.stop())}}return i.map((e,t)=>{let r={kind:e.kind,deviceId:e.deviceId,groupId:e.groupId,label:e.label||`${e.kind}_${t}`};return e.deviceId.length>0&&Du.add(`${e.deviceId}_${e.kind}`),e.getCapabilities&&(r.getCapabilities=()=>e.getCapabilities()),r})})}function It(o=!1){return be.update(o?1:0).then(i=>i.audioInputs.devices)}function At(o=!1){return be.update(o?2:0).then(i=>i.videoInputs.devices)}var Zp=!1;function ef(){return p(this,null,function*(){try{Zp||(Zp=!0,R.info(`speakers:${(yield Nr()).map(o=>` ${o.deviceId.slice(0,8)}: ${o.label}`)}`))}catch(o){}})}function Nr(o=!1){return p(this,null,function*(){return(ge||Re)&&(o=!1),be.update(o?1:0).then(i=>i.audioOutputs.devices)})}var Du=new Set;function tf(o){if(o instanceof CanvasCaptureMediaStreamTrack||!(o instanceof MediaStreamTrack))return!1;let i=o.label.toLocaleLowerCase();if(i.includes("camera")||i.includes("webcam"))return!0;let t=`${((o==null?void 0:o.getSettings())||{}).deviceId}_${f.VIDEO_INPUT}`;return!!Du.has(t)}function rf(o){if(o instanceof CanvasCaptureMediaStreamTrack||!(o instanceof MediaStreamTrack))return!1;let i=o.label.toLocaleLowerCase();if(i.includes("mic")||i.includes("\u9EA6\u514B\u98CE"))return!0;let t=`${((o==null?void 0:o.getSettings())||{}).deviceId}_${f.AUDIO_INPUT}`;return!!Du.has(t)}function Mu(o,i){return p(this,null,function*(){let t=(yield It()).find(r=>r.deviceId===Wr);return!i&&(t==null?void 0:t.groupId)===o||(t==null?void 0:t.groupId)===o&&t.label===i})}function of(s){return p(this,arguments,function*({newDeviceId:o,oldDeviceId:i,oldGroupId:e,oldLabel:t,kind:r}){return o!==i?!1:r===f.AUDIO&&o===Wr?yield Mu(e,t):!0})}var Nc,Ou=class extends Mn{constructor(e){super();this.log=e;d(this,"volumeMeter");d(this,"volumeMeterAfter3A");d(this,"volumeDestination");d(this,"analyser",new yc);this.volumeMeter=new kn({log:this.log}),this.volumeMeterAfter3A=new kn({log:this.log}),this.volumeDestination=new xe,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},us=class o extends mi{constructor(e){super(e,f.AUDIO);d(this,"_outputDeviceId");d(this,"_volume",1);d(this,"_destination",Ee("player").createMediaStreamDestination());d(this,"pipeline");d(this,"volumeMeterMode","worklet");d(this,"enableVolumeControlInIOS");this.enableVolumeControlInIOS=e.enableVolumeControlInIOS,this.mode=0,e.url&&(this.url=e.url),this.pipeline=new Ou(this._log)}setTrack(e){}get duration(){var e;return Math.floor((((e=this.element)==null?void 0:e.duration)||0)*1e3)}get currentTime(){var e;return Math.floor((((e=this.element)==null?void 0:e.currentTime)||0)*1e3)}set currentTime(e){this.element&&(this.element.currentTime=e/1e3)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(e){if((Tt==="15.2"||Tt==="15.3"||Tt==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}let r=Nc||new Audio;r.setAttribute("autoplay","autoplay"),r.srcObject=this.getMediaStream(),r.muted=this.muted,this.url&&(r.crossOrigin="anonymous",r.src=this.url),this.element=r,z(e)&&(this.element.volume=Math.min(Math.max(e,0),1)),r===Nc&&(Nc=void 0),this.options.enableTimeupdateEvent&&(this.element.ontimeupdate=()=>this.emit(ue.TIME_UPDATE,this.currentTime)),this.bindElementEvents()}play(e){return p(this,null,function*(){if(!(!this.track&&!this.url))return!this.pipeline.source.node&&this.track&&this.pipeline.replaceSource(this.track),this.element||this.initializeElement(e==null?void 0:e.volume),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),this.volumeMeterMode==="worklet"?(this.pipeline.volumeMeter.init(),this.pipeline.volumeMeterAfter3A.init()):this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(Ee("player").createAnalyser()),ef(),Pe(o.prototype,this,"play").call(this)})}stop(e=0){this.pipeline.destroy(),super.stop(e)}setVolume(e){this._volume=e,this.element&&(this.element.volume=e)}setSinkId(e){return p(this,null,function*(){var t,r;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield(r=(t=this.element).setSinkId)==null?void 0:r.call(t,e))})}get useDestination(){return!!this.pipeline.stream}setLoop(e){this.element&&(this.element.loop=e)}getAudioLevel(){return this.pipeline.volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this.pipeline.volumeMeter.getInternalAudioLevel()}getInternalAudioLevelAfter3A(){return this.pipeline.volumeMeterAfter3A.getInternalAudioLevel()}},Dc=class extends us{setTrack(i){this.track!==i&&(this.unbindTrackEvents(),this.track=i,this.emit(ue.MEDIA_TRACK_CHANGED,i),i&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([i]))))}},hs=class extends us{constructor(e){super(e);d(this,"_sourceElement");d(this,"_output",new xe);this.pipeline.source.pipeTo(this.pipeline.gain),this.pipeline.gain.pipeTo(this.pipeline.volumeMeter).pipeTo(this._output),this.pipeline.gain.pipeTo(this.pipeline.destination)}setOutput(){this.mode=1,this._output.setNode(Ee("player").destination)}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var t,r,s;((r=(t=this.element)==null?void 0:t.error)==null?void 0:r.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(ue.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([e]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e])),this.pipeline.source.channelCount=((s=e.getSettings())==null?void 0:s.channelCount)||1,this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){if(this._volume=e,this.useDestination)this.pipeline.setVolume(e),this._log.info(`set pipeline volume: ${e}`);else if(e<=1&&!ge)this.element?(this._log.info(`set element volume: ${e}`),this.element.volume=e):this._log.info("set element volume: no element");else{if(ge)if(this.enableVolumeControlInIOS)Xp();else return;if(K&&!this.pipeline.source.node){this._log.warn("set pipeline volume failed: no source node");return}this._log.info(`start set pipeline volume: ${e}`),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),Le(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play())}}stop(e=0){this.pipeline.destroy();let t=this._sourceElement||this.element;t&&Ft&&(Nc=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}};var no=class extends J{constructor({userId:e,sdkAppId:t,mediaType:r,room:s,PlayerClass:n=r===1?hs:it}){var a;super();d(this,"id",cn());d(this,"userId","");d(this,"isRemote");d(this,"mediaType");d(this,"room");d(this,"user");d(this,"_log");d(this,"_inputTrack");d(this,"_outputTrack");d(this,"isPlayCalled");d(this,"container",null);d(this,"player");d(this,"subVideoPlayerMap");d(this,"muted",!1);d(this,"abortCtrl");d(this,"objectFit","cover");d(this,"mirror");d(this,"rotation");d(this,"isScreen",!1);d(this,"manager");d(this,"trackSettings");d(this,"isFirstVideoFrameEmitted",!1);this.userId=e||"",this.mediaType=r,this._log=R.createLogger({parent:s==null?void 0:s.getLogger(),id:`${this.kind[0]}t`,userId:(a=s||this.room)==null?void 0:a.userId,remoteUserId:this instanceof pi?void 0:this.userId,sdkAppId:t,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof pi}),this.player=new n({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log,enableVolumeControlInIOS:s==null?void 0:s.enableVolumeControlInIOS}),this.player.on(ue.PLAYER_STATE_CHANGED,c=>{if(S.emit(A.PLAYER_STATE_CHANGED,O({track:this},c)),this.emit("player-state-changed",c),c.state==="PLAYING"&&this.room){let l=!0;for(let{remoteAudioTrack:u,remoteVideoTrack:h,remoteAuxiliaryTrack:m}of[...this.room.remotePublishedUserMap.values()])if(u.isAvailable&&!u.player.isPlaying||h.isAvailable&&!h.player.isPlaying||m.isAvailable&&!m.player.isPlaying){l=!1;break}l&&br()&&$p()}}),this.kind===f.VIDEO&&(this.player.on(ue.LOADED_DATA,()=>{this.emitFirstVideoFrameEvent(ue.LOADED_DATA),S.emit(A.VIDEO_LOADED_DATA,{track:this})}),this.player.on(ue.LOADED_META_DATA,()=>{this.emitFirstVideoFrameEvent(ue.LOADED_META_DATA)}),this.player.on(ue.MEDIA_TRACK_CHANGED,c=>{var l;(l=this.subVideoPlayerMap)==null||l.forEach(u=>u.setTrack(c))}),this.player.on(ue.RESIZE,c=>{this.emitFirstVideoFrameEvent(ue.RESIZE),this.emit("video-size-changed",O({userId:this.userId,streamType:this.mediaType===2?"auxiliary":"main"},c))})),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(ue.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||R}get kind(){return this.mediaType===1?f.AUDIO:f.VIDEO}get isAudio(){return this.kind===f.AUDIO}get strMediaType(){return this.mediaType===4?f.VIDEO:this.mediaType===2?f.SCREEN:f.AUDIO}get streamType(){return(this.mediaType&2)===0?"main":"auxiliary"}get isMediaTrackActive(){return this.mediaTrack?!this.mediaTrack.muted&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled:!1}play(e,t){return p(this,null,function*(){let r=Ie(e)?e[0]:e;if(this.isPlayCalled){this.log.info(`play update options: ${JSON.stringify(t)}`),t&&!T(t.muted)&&this.setPlayerMute(t.muted),t&&!T(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof it&&(this.player.setObjectFit(this.objectFit),this.container!==r&&r&&(this.container=r,this.player.setContainer(r)),Ie(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t)));return}if(t&&!T(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===f.VIDEO)&&this.setPlayerMute(!0),t&&!T(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof it&&(this.player.setObjectFit(this.objectFit),t&&!T(t.poster)&&this.player.setPoster(t.poster)),this.isPlayCalled=!0,r&&(this.container=r,this.player instanceof it&&this.player.setContainer(r)),S.emit(A.PLAY_TRACK_START,{track:this}),!this._outputTrack){this.log.info("play has not mediaTrack, abort");return}this._log.info(`play with options: ${JSON.stringify(t)}`);try{this.player.setTrack(this.playerMediaTrack),yield this.player.play(t),Ie(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(s){throw this.handleAutoPlayFailed(s),s}})}setMirror(e,t){if(this.isScreen||this.kind!==f.VIDEO||T(e)||e===this.mirror)return;this.mirror=e;let r=this.player;t&&(r=t);let s=this.manager;if(he(this.mirror)){r.setViewMirror(this.mirror),!this.isRemote&&s&&(s.mirror=!1);return}switch(this.mirror){case"view":{s&&(s.mirror=!1),r.setViewMirror(!0);break}case"publish":{s&&(s.mirror=!0),r.setViewMirror(!0);break}case"both":s&&(s.mirror=!0),r.setViewMirror(!1)}}playSubContainer(e,t){return p(this,null,function*(){if(!this._outputTrack||this.kind===f.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((s,n)=>{var a;e.find(c=>n===c)||(s.stop(),(a=this.subVideoPlayerMap)==null||a.delete(n))});for(let[s,n]of e.entries()){let a=this.subVideoPlayerMap.get(n);a?t&&(T(t.objectFit)||a.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new it({id:this.userId||this.id,track:this.playerMediaTrack,container:n,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:`vp-sub${s+1}`})}))}let r=[...this.subVideoPlayerMap.values()];for(let s of r)s.setViewMirror(this.player.mirror),yield s.play()})}setAudioOutput(e){return this.player.setSinkId(e)}setAudioVolume(e){this.player.setVolume(e)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var e;return((e=this.player)==null?void 0:e.getInternalAudioLevel())||0}stop(e=!1){this.isPlayCalled&&(this.isPlayCalled=!1,this.isFirstVideoFrameEmitted=!1,this.player&&(this.log.info(`stop ${this.kind} player`),this.player.stop(Sl(this)&&!e?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(t=>{t.stop()}),this.container=null)}resume(){return p(this,null,function*(){var e;this.isPlayCalled&&(yield(e=this.player)==null?void 0:e.resume())})}close(){this.log.info("close"),this.isPlayCalled&&this.stop(!0)}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),S.emit(e?A.TRACK_MUTED:A.TRACK_UNMUTED,{track:this})}setPlayerMute(e){this.player.setMuted(e)}get mediaTrack(){return this._inputTrack||null}get outMediaTrack(){return this._outputTrack||null}get playerMediaTrack(){return this.outMediaTrack}installTrackEvent(e){tt(e,e).add(f.MUTE,this.onTrackMuted).add(f.UNMUTE,this.onTrackUnmuted).add(f.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===f.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){Le(e)}setInputMediaStreamTrack(e){var r;let t=this._inputTrack;if(e!==t)return this._inputTrack=e,this.trackSettings=(r=e.getSettings)==null?void 0:r.call(e),e.enabled=!this.muted,t&&this.uninstallTrackEvent(t),this.installTrackEvent(e),this.emit("input-media-track-changed",e||null,t||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var r;let t=this._outputTrack;e!==t&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",(r=e.getSettings)==null?void 0:r.call(e).deviceId,e.label),this._outputTrack=e,this._inputTrack&&(this._outputTrack.contentHint=this._inputTrack.contentHint,this._outputTrack.enabled=this._inputTrack.enabled),this.updatePlayingState(!!e),this.emit("output-media-track-changed",e))}setMediaType(e){this.mediaType=e}updatePlayingState(e){if(this.isPlayCalled){if(e){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped){this.player.play().catch(t=>this.handleAutoPlayFailed(t)),this.log.info(`playing state updated, play ${this.kind}`);return}}else if(!this.player.isStopped){this.player.stop(Sl(this)?this.jitterBufferDelay:0),this.log.info(`playing state updated, stop ${this.kind}`);return}}this.log.debug(`updatePlayingState abort ${this.isPlayCalled} ${e} ${this.player.isStopped}`)}handleAutoPlayFailed(e){return p(this,null,function*(){var r;this.log.warn("handleAutoPlayFailed",e);let t=()=>{this.resume().then(()=>{document.removeEventListener("click",t,!0)})};if(this.room&&this.room.enableAutoPlayDialog){if((Ji||ji)&&(yield Ke(100),(r=this.player)!=null&&r.isPlaying))return;ns()}else document.addEventListener("click",t,!0);S.once(A.LOCAL_TRACK_CAPTURE_SUCCESS,({track:s})=>{s.kind==="audio"&&br()&&!this.player.isPlaying&&this.isRemote&&this.isAvailable&&t()}),this.emit("error",e)})}getVideoFrame(){return this.player instanceof it?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(e){var n,a,c;if(this.isFirstVideoFrameEmitted)return;let t=(n=this.mediaTrack)==null?void 0:n.getSettings(),r=(t==null?void 0:t.width)||((a=this.player.element)==null?void 0:a.videoWidth)||0,s=(t==null?void 0:t.height)||((c=this.player.element)==null?void 0:c.videoHeight)||0;e===ue.RESIZE&&!r&&!s||e===ue.LOADED_META_DATA&&!r&&!s||(e===ue.LOADED_DATA&&!r&&!s&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,bt(this.rotation)&&([r,s]=[s,r]),this.emit("first-video-frame",{width:r,height:s,streamType:this.streamType,userId:this.isRemote?this.userId:""}))}onTrackMuted(){this._log.warn(`${this.kind} track is unable to provide media output`)}onTrackUnmuted(){this._log.info(`${this.kind} track is able to provide media output`)}onTrackEnded(){this._log.warn(`${this.kind} track ended`)}};M([ye([],J.INIT,{sync:!0})],no.prototype,"close",1);var XT=Object.prototype.hasOwnProperty,{toString:vb}=Object.prototype;function zT(o){if(o==null)return!0;if(typeof o=="boolean")return!1;if(typeof o=="number")return o===0;if(typeof o=="string"||typeof o=="function"||Array.isArray(o))return o.length===0;if(o instanceof Error)return o.message==="";if(dt(o))switch(Object.prototype.toString.call(o)){case"[object File]":case"[object Map]":case"[object Set]":return o.size===0;case"[object Object]":{for(let i in o)if(XT.call(o,i))return!1;return!0}}return!1}var fi=zT;var QT=function(o){return p(this,null,function*(){let i=ZT(o);R.info(`getUserMedia with constraints: ${JSON.stringify(i)}`);let e=[],t=[],r=["label","deviceId","groupId"];if(i.audio&&(e=yield It(),R.info(`microphones: ${_t(e.map(s=>L(O({},s),{groupId:s.groupId.substring(0,8)})),{keysToInclude:r})}`)),i.video&&(t=yield At(),R.info(`cameras: ${_t(t,{keysToInclude:r})}`),!he(i.video)&&i.video.facingMode==="user"&&!i.video.deviceId)){let n=t.filter(a=>!a.label.includes("infrared")).find(a=>a.label.includes("facing front"));n&&(i.video.deviceId=n.deviceId,R.info(`exclude infrared camera: ${JSON.stringify(i)}`))}try{let s=yield navigator.mediaDevices.getUserMedia(i);return cu&&s.getTracks().forEach(n=>{var c;let a=n.getCapabilities();R.info(`${n.kind} capabilities: ${_t(a,{keysToInclude:Ia})}`),!T(o.echoCancellation)&&((c=a.echoCancellation)==null?void 0:c.indexOf(o.echoCancellation))===-1&&R.warn(`Invalid argument for 'echoCancellation'. Expected one of [${JSON.stringify(a.echoCancellation)}], but received '${o.echoCancellation}'`)}),i.audio&&vr(),s}catch(s){let{message:n}=s;throw s.name==="NotFoundError"&&(o.video&&t&&t.length===0&&(n=H({key:F.CAMERA_NOT_FOUND})),o.audio&&e&&e.length===0&&(n=H({key:F.MICROPHONE_NOT_FOUND}))),new D({code:I.INITIALIZE_FAILED,name:s.name,message:n,constraint:s.constraint})}})},YT=Ai({retryFunction:QT,settings:{retries:3,timeout:500},onError:({error:o,retry:i,reject:e,retryFuncArgs:t,retriedCount:r})=>{let s=r+1;o.name==="NotReadableError"||o.name==="OverconstrainedError"||o.name==="AbortError"?(s===1?(t[0].video&&(t[0].maxResolution=!1,(!Re||t[0].width*t[0].height<=1920*1080)&&t[0].frameRate&&(t[0].frameRate=t[0].frameRate>10?10:5)),t[0].retryWhenExactFailed&&t[0].useExactDeviceId&&(t[0].useExactDeviceId=!1)):s===2?t[0].useDeviceIdOnly=!0:s===3&&!t[0].useExactDeviceId&&(t[0].useTrueAsConstraint=!0),i()):e(o),t[0].microphoneId&&sf(t[0].microphoneId,!1),t[0].cameraId&&sf(t[0].cameraId,!0)},onRetrying:o=>{R.warn(`getUserMedia NotReadableError observed, retrying [${o}/3]`)},onRetryFailed:o=>{se.logFailedEvent({eventType:Ze.GET_USER_MEDIA_RETRY,error:o})},onRetrySuccess:o=>{se.logSuccessEvent({eventType:Ze.GET_USER_MEDIA_RETRY}),se.uploadEvent({log:`stat-${Ze.GET_USER_MEDIA_RETRY}-success-${o}`})}});function sf(o,i){return p(this,null,function*(){let t=(i?yield At():yield It()).find(r=>r.deviceId===o);t&&le(t.getCapabilities)&&R.warn(_t(t.getCapabilities(),{keysToInclude:Ia}))})}function ZT(o){return{audio:KT(o),video:eE(o)}}function KT(o){if(!o.audio)return!1;if(o.useTrueAsConstraint)return!0;let i={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:o.sampleRate};return!fi(o.microphoneId)&&(i.deviceId=o.useExactDeviceId?{exact:o.microphoneId}:o.microphoneId,o.useDeviceIdOnly)?i:(z(o.channelCount)&&(i.channelCount=o.channelCount),(he(o.echoCancellation)||o.echoCancellation==="remote-only"||o.echoCancellation==="all")&&(i.echoCancellation=o.echoCancellation),he(o.noiseSuppression)&&!o.noiseSuppression&&(i.noiseSuppression=!1),he(o.autoGainControl)&&!o.autoGainControl&&(i.autoGainControl=!1),fi(i)?!0:i)}function eE(o){if(!o.video)return!1;if(o.useTrueAsConstraint)return!0;let{maxResolution:i=!0}=o,e={};return o.cameraId?e.deviceId=o.useExactDeviceId?{exact:o.cameraId}:o.cameraId:o.facingMode&&(e.facingMode=o.facingMode),o.useDeviceIdOnly&&!fi(e)?e:(o.width&&(e.width={ideal:o.width},i&&!K&&(e.width.max=o.width)),o.height&&(e.height={ideal:o.height},i&&!K&&(e.height.max=o.height)),K&&ri&&o.width&&o.height&&o.width*o.height<352*288&&(e.width=o.width,e.height=o.height),o.frameRate&&(e.frameRate=o.frameRate),fi(e)?!0:e)}var nf=YT;function Mc(o){return Q((i,e)=>function(...t){return p(this,null,function*(){return yield o.apply(this,t),i.apply(this,t)})})}function Ct(o){return Q((i,e)=>function(...t){return p(this,null,function*(){let r=yield i.apply(this,t);return yield o.call(this,...t),r})})}function Oc(o){return Q((i,e)=>function(...t){return p(this,null,function*(){try{return yield i.apply(this,t)}catch(r){o.call(this,r)}})})}function Q(o){return function(i,e,t){return t.value=o(t.value,e),t}}var af=(()=>{let o=!1,i=document.visibilityState;return()=>{document.visibilityState!==i&&R.info(`visibility change: ${document.visibilityState}`),!o&&(document.addEventListener("visibilitychange",()=>{R.info(`visibility change: ${document.visibilityState}`),i=document.visibilityState}),o=!0)}})();var tE=0,kc=class{constructor(){d(this,"log",R.createLogger({id:`fq${++tE}`}));d(this,"isRunning",!1);d(this,"queue",[])}get length(){return this.queue.length}get lastQueueItem(){return this.length===0?null:this.queue[this.length-1]}push(i,e=!1){var s,n;let t=O({},i),r=new Promise((a,c)=>{t.resolve=a,t.reject=c});return t.promise=r,e?this.length<=1?this.queue.push(t):(n=(s=this.lastQueueItem)==null?void 0:s.promise)==null||n.then(t.resolve,t.reject):this.queue.push(t),this.log.debug(`push ${this.length}`),this.isRunning||this.callNext(),r}shift(){let i=this.queue.shift();return this.log.debug(`shift ${this.length}`),i}callNext(){if(this.isRunning||this.length===0)return;this.log.debug("callNext ",this.length);let{fn:i,args:e,context:t,resolve:r,reject:s}=this.queue[0];this.isRunning=!0,i.apply(t,e).then(r,s).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},Pc=new WeakMap,wc=new WeakMap;function ir(o=!1){return function(i,e,t){let r=t.value;return t.value=function(...s){let n=Pc.get(this)||new kc;return Pc.set(this,n),n.push({fn:r,args:s,context:this},o)},t}}function Lc(o){return function(i,e,t){let r=t.value;return t.value=function(...s){var a,c,l;let n=[];return(c=(a=Pc.get(this))==null?void 0:a.queue)==null||c.forEach(u=>n.push(u)),(l=wc.get(this))==null||l.forEach(u=>u==null?void 0:u.queue.forEach(h=>n.push(h))),n.forEach(u=>{u.reject(new D({code:I.API_CALL_ABORTED,message:o}))}),Pc.delete(this),wc.delete(this),r.apply(this,s)},t}}function _i(o){return function(i,e,t){let r=t.value,s=n=>o(...n);return t.value=function(...n){let a=wc.get(this)||new Map,c=a.get(s(n))||new kc;return a.set(s(n),c),wc.set(this,a),c.push({fn:r,args:n,context:this})},t}}function Rt(o,i){return Q((e,t)=>function(...r){let s=o;try{let n=e.apply(this,r),a=U();return Tr(n)?n.then(c=>(i?v.addSuccessEvent({key:s,cost:U()-a}):v.addSuccessEvent({key:s}),c)).catch(c=>{throw v.addFailedEvent({key:s,error:c}),c}):(v.addSuccessEvent({key:s}),n)}catch(n){throw v.addFailedEvent({key:s,error:n}),n}})}var gh={};Vi(gh,{Events:()=>Oe,Inspect:()=>Ht,LastSink:()=>ao,Sink:()=>j,Subscribe:()=>co,TimeoutError:()=>wn,audit:()=>VE,bindCallback:()=>CE,bindNodeCallback:()=>RE,buffer:()=>lE,bufferCount:()=>dE,bufferTime:()=>rS,call:()=>cf,catchError:()=>ph,combineLatest:()=>lf,concat:()=>oE,concatMap:()=>zE,concatMapTo:()=>QE,count:()=>vE,create:()=>ae,debounce:()=>FE,debounceTime:()=>BE,defer:()=>uf,delay:()=>oS,deliver:()=>X,dispose:()=>xc,elementAt:()=>HE,empty:()=>Vn,every:()=>JE,exhaustMap:()=>KE,exhaustMapTo:()=>eS,expand:()=>sS,filter:()=>$t,find:()=>$E,findIndex:()=>WE,first:()=>GE,fromAnimationFrame:()=>IE,fromArray:()=>fE,fromEvent:()=>ce,fromEventPattern:()=>_E,fromFetch:()=>gE,fromIterable:()=>TE,fromPromise:()=>pf,fromReadableStream:()=>SE,fromReader:()=>EE,groupBy:()=>tS,identity:()=>iE,ignoreElements:()=>OE,iif:()=>nE,inspect:()=>df,interval:()=>Vu,last:()=>qE,map:()=>Fn,mapTo:()=>XE,max:()=>NE,merge:()=>Ln,mergeMap:()=>YE,mergeMapTo:()=>ZE,min:()=>DE,never:()=>yE,nothing:()=>pe,of:()=>pE,pairwise:()=>jE,pipe:()=>de,race:()=>xu,range:()=>AE,reduce:()=>Fu,retry:()=>dS,scan:()=>mh,setAsapScheduler:()=>mE,share:()=>rr,shareReplay:()=>sE,skip:()=>PE,skipUntil:()=>wE,skipWhile:()=>Hc,startWith:()=>xn,subject:()=>ot,subscribe:()=>Te,sum:()=>ME,switchMap:()=>Mr,switchMapTo:()=>mo,take:()=>or,takeLast:()=>kE,takeUntil:()=>ke,takeWhile:()=>ff,tap:()=>Bn,throttle:()=>xE,throwError:()=>bE,timeInterval:()=>iS,timeout:()=>cS,timer:()=>Un,toPromise:()=>nS,toReadableStream:()=>aS,withLatestFrom:()=>cE,zip:()=>aE});function pe(...o){}var cf=o=>o(),iE=o=>o;function xc(){this.dispose()}var df=()=>typeof __FASTRX_DEVTOOLS__!="undefined",rE=1,Ht=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(i){let e=new ku(i,this,this.streamId++);return Oe.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},ao=class{constructor(){this.defers=new Set,this.disposed=!1}next(i){}complete(){this.dispose()}error(i){this.dispose()}get bindDispose(){return()=>this.dispose()}dispose(){this.disposed=!0,this.complete=pe,this.error=pe,this.next=pe,this.dispose=pe,this.subscribe=pe,this.doDefer()}subscribe(i){return i instanceof Ht?i.subscribe(this):i(this),this}get bindSubscribe(){return i=>this.subscribe(i)}doDefer(){this.defers.forEach(cf),this.defers.clear()}defer(i){this.defers.add(i)}removeDefer(i){this.defers.delete(i)}reset(){this.disposed=!1,delete this.complete,delete this.next,delete this.dispose,delete this.next,delete this.subscribe}resetNext(){delete this.next}resetComplete(){delete this.complete}resetError(){delete this.error}},j=class extends ao{constructor(i){super(),this.sink=i,i.defer(this.bindDispose)}next(i){this.sink.next(i)}complete(){this.sink.complete()}error(i){this.sink.error(i)}},co=class extends ao{constructor(i,e=pe,t=pe,r=pe){if(super(),this._next=e,this._error=t,this._complete=r,this.then=pe,i instanceof Ht){let s={toString:()=>"subscribe",id:0,source:i};this.defer(()=>{Oe.defer(s,0)}),Oe.create(s),Oe.pipe(s),this.sourceId=s.id,this.subscribe(i),Oe.subscribe({id:s.id,end:!0}),e==pe?this._next=n=>Oe.next(s,0,n):this.next=n=>{Oe.next(s,0,n),e(n)},r==pe?this._complete=()=>Oe.complete(s,0):this.complete=()=>{this.dispose(),Oe.complete(s,0),r()},t==pe?this._error=n=>Oe.complete(s,0,n):this.error=n=>{this.dispose(),Oe.complete(s,0,n),t(n)}}else this.subscribe(i)}next(i){this._next(i)}complete(){this.dispose(),this._complete()}error(i){this.dispose(),this._error(i)}};function de(o,...i){return i.reduce((e,t)=>t(e),o)}function ae(o,i,e){if(df()){let t=Object.defineProperties(Object.setPrototypeOf(o,Ht.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:i,writable:!0,configurable:!0},args:{value:e,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});Oe.create(t);for(let r=0;r<e.length;r++){let s=e[r];typeof s=="function"&&s instanceof Ht&&Oe.addSource(t,s)}return t}return o}function X(o,i){return function(...e){return t=>{if(t instanceof Ht){let r=ae(s=>{let n=new o(s,...e);n.sourceId=r.id,n.subscribe(t)},i,arguments);return r.source=t,Oe.pipe(r),r}else return r=>t(new o(r,...e))}}}function Dr(o,i){window.postMessage({source:"fastrx-devtools-backend",payload:{event:o,payload:i}})}var ku=class extends j{constructor(i,e,t){super(i),this.source=e,this.id=t,this.sourceId=i.sourceId,this.defer(()=>{Oe.defer(this.source,this.id)})}next(i){Oe.next(this.source,this.id,i),this.sink.next(i)}complete(){Oe.complete(this.source,this.id),this.sink.complete()}error(i){Oe.complete(this.source,this.id,i),this.sink.error(i)}},Oe={addSource(o,i){Dr("addSource",{id:o.id,name:o.toString(),source:{id:i.id,name:i.toString()}})},next(o,i,e){Dr("next",{id:o.id,streamId:i,data:e&&e.toString()})},subscribe({id:o,end:i},e){Dr("subscribe",{id:o,end:i,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(o,i,e){Dr("complete",{id:o.id,streamId:i,err:e?e.toString():null})},defer(o,i){Dr("defer",{id:o.id,streamId:i})},pipe(o){Dr("pipe",{name:o.toString(),id:o.id,source:{id:o.source.id,name:o.source.toString()}})},update(o){Dr("update",{id:o.id,name:o.toString()})},create(o){o.id||(o.id=rE++),Dr("create",{name:o.toString(),id:o.id})}},wn=class extends Error{constructor(i){super(`timeout after ${i}ms`),this.timeout=i}};var Uc=class extends ao{constructor(i){super(),this.source=i,this.sinks=new Set}add(i){i.defer(()=>this.remove(i)),this.sinks.add(i).size===1&&(this.reset(),this.subscribe(this.source))}remove(i){this.sinks.delete(i),this.sinks.size===0&&this.dispose()}next(i){this.sinks.forEach(e=>e.next(i))}complete(){this.sinks.forEach(i=>i.complete()),this.sinks.clear()}error(i){this.sinks.forEach(e=>e.error(i)),this.sinks.clear()}};function rr(){return o=>{let i=new Uc(o);if(o instanceof Ht){let e=ae(t=>{i.add(t)},"share",arguments);return i.sourceId=e.id,e.source=o,Oe.pipe(e),e}return ae(i.add.bind(i),"share",arguments)}}function Ln(...o){return ae(i=>{let e=new j(i),t=o.length;e.complete=()=>{--t===0&&i.complete()},o.forEach(e.bindSubscribe)},"merge",arguments)}function xu(...o){return ae(i=>{let e=new Map;o.forEach(t=>{let r=new j(i);e.set(t,r),r.complete=()=>{e.delete(t),e.size===0?i.complete():r.dispose()},r.next=s=>{e.delete(t),e.forEach(n=>n.dispose()),r.resetNext(),r.resetComplete(),r.next(s)}}),o.forEach(t=>e.get(t).subscribe(t))},"race",arguments)}function oE(...o){return ae(i=>{let e=0,t=o.length,r=new j(i);r.complete=()=>{e<t&&!r.disposed?(r.doDefer(),r.subscribe(o[e++])):i.complete()},r.complete()},"concat",arguments)}function sE(o){return i=>{let e=new Uc(i),t=[];return e.next=function(r){t.push(r),t.length>o&&t.shift(),this.sinks.forEach(s=>s.next(r))},ae(r=>{r.defer(()=>e.remove(r)),t.forEach(s=>r.next(s)),e.add(r)},"shareReplay",arguments)}}function nE(o,i,e){return ae(t=>o()?i(t):e(t),"iif",arguments)}function lf(...o){return ae(i=>{let e=o.length,t=e,r=e,s=new Array(e),n=()=>{--r===0&&i.complete()},a=(c,l)=>{let u=new j(i);u.next=h=>{t--,u.next=m=>{s[l]=m,t===0&&i.next(s)},u.next(h)},u.complete=n,u.subscribe(c)};o.forEach(a)},"combineLatest",arguments)}function aE(...o){return ae(i=>{let e=o.length,t=e,r=new Array(e),s=()=>{--t===0&&i.complete()},n=(a,c)=>{let l=new j(i),u=[];r[c]=u,l.next=h=>{u.push(h),r.every(m=>m.length)&&i.next(r.map(m=>m.shift()))},l.complete=s,l.subscribe(a)};o.forEach(n)},"zip",arguments)}function xn(...o){return i=>ae((e,t=0,r=o.length)=>{for(;t<r&&!e.disposed;)e.next(o[t++]);e.disposed||e.subscribe(i)},"startWith",arguments)}var Pu=class extends j{constructor(i,...e){super(i);let t=new j(this.sink);t.next=r=>this.buffer=r,t.complete=pe,t.subscribe(lf(...e))}next(i){this.buffer&&this.sink.next([i,...this.buffer])}},cE=X(Pu,"withLatestFrom"),wu=class extends j{constructor(i,e,t){super(i),this.bufferSize=e,this.startBufferEvery=t,this.buffer=[],this.count=0,this.startBufferEvery&&(this.buffers=[[]])}next(i){this.startBufferEvery?(this.count++===this.startBufferEvery&&(this.buffers.push([]),this.count=1),this.buffers.forEach(e=>{e.push(i)}),this.buffers[0].length===this.bufferSize&&this.sink.next(this.buffers.shift())):(this.buffer.push(i),this.buffer.length===this.bufferSize&&(this.sink.next(this.buffer),this.buffer=[]))}complete(){this.buffer.length?this.sink.next(this.buffer):this.buffers.length&&this.buffers.forEach(i=>this.sink.next(i)),super.complete()}},dE=X(wu,"bufferCount"),Lu=class extends j{constructor(i,e){super(i),this.buffer=[];let t=new j(i);t.next=r=>{i.next(this.buffer),this.buffer=[]},t.complete=pe,t.subscribe(e)}next(i){this.buffer.push(i)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},lE=X(Lu,"buffer");var uE=function(o,i,e,t){function r(s){return s instanceof e?s:new e(function(n){n(s)})}return new(e||(e=Promise))(function(s,n){function a(u){try{l(t.next(u))}catch(h){n(h)}}function c(u){try{l(t.throw(u))}catch(h){n(h)}}function l(u){u.done?s(u.value):r(u.value).then(a,c)}l((t=t.apply(o,i||[])).next())})};function ot(o){let i=arguments,e=rr()(ae(t=>{e.next=r=>t.next(r),e.complete=()=>t.complete(),e.error=r=>t.error(r),o&&t.subscribe(o)},"subject",i));return e.next=pe,e.complete=pe,e.error=pe,e}function uf(o){return ae(i=>i.subscribe(o()),"defer",arguments)}var ms={promise:o=>{Promise.resolve().then(o)},setImmediate:typeof setImmediate!="undefined"?o=>setImmediate(o):null,setTimeout:o=>setTimeout(o,0)},hE=()=>typeof Promise!="undefined"?ms.promise:ms.setImmediate?ms.setImmediate:ms.setTimeout,Uu=hE(),hf=o=>i=>{Uu(()=>o(i))},mE=o=>{typeof o=="function"?Uu=o:ms[o]&&(Uu=ms[o])};var mf=o=>hf(i=>{for(let e=0;!i.disposed&&e<o.length;e++)i.next(o[e]);i.complete()});function pE(...o){return ae(mf(o),"of",arguments)}function fE(o){return ae(mf(o),"fromArray",arguments)}function Vu(o){return ae(i=>{let e=0,t=setInterval(()=>i.next(e++),o);return i.defer(()=>{clearInterval(t)}),"interval"},"interval",arguments)}function Un(o,i){return ae(e=>{let t=0,r=setTimeout(()=>{if(e.removeDefer(s),e.next(t++),i){let n=setInterval(()=>e.next(t++),i);e.defer(()=>{clearInterval(n)})}else e.complete()},o),s=()=>clearTimeout(r);e.defer(s)},"timer",arguments)}function Vc(o,i){return e=>{let t=r=>e.next(r);e.defer(()=>i(t)),o(t)}}function _E(o,i){return ae(Vc(o,i),"fromEventPattern",arguments)}function ce(o,i){if("on"in o&&"off"in o)return ae(Vc(e=>o.on(i,e),e=>o.off(i,e)),"fromEvent",arguments);if("addListener"in o&&"removeListener"in o)return ae(Vc(e=>o.addListener(i,e),e=>o.removeListener(i,e)),"fromEvent",arguments);if("addEventListener"in o)return ae(Vc(e=>o.addEventListener(i,e),e=>o.removeEventListener(i,e)),"fromEvent",arguments);throw"target is not a EventDispachter"}function pf(o){return ae(i=>{o.then(i.next.bind(i),i.error.bind(i))},"fromPromise",arguments)}function gE(o,i){return ae(uf(()=>pf(fetch(o,i))),"fromFetch",arguments)}function TE(o){return ae(hf(i=>{try{for(let e of o){if(i.disposed)return;i.next(e)}i.complete()}catch(e){i.error(e)}}),"fromIterable",arguments)}function EE(o){let i=e=>uE(this,void 0,void 0,function*(){if(e.disposed)return;let{done:t,value:r}=yield o.read();if(t){e.complete();return}else e.next(r),i(e)});return ae(e=>{i(e)},"fromReader",arguments)}function SE(o){return ae(i=>{let e=new AbortController,t=e.signal;i.defer(()=>e.abort("cancelled")),o.pipeTo(new WritableStream({write(r){i.next(r)},close(){i.complete()},abort(r){i.error(r)}}),{signal:t}).then(()=>i.complete(),r=>i.error(r))},"fromReadableStream",arguments)}function IE(){return ae(o=>{let i=requestAnimationFrame(function e(t){o.disposed||(o.next(t),i=requestAnimationFrame(e))});o.defer(()=>cancelAnimationFrame(i))},"fromAnimationFrame",arguments)}function AE(o,i){return ae((e,t=o,r=i+o)=>{for(;t<r&&!e.disposed;)e.next(t++);return e.complete(),"range"},"range",arguments)}function CE(o,i,...e){return ae(t=>{let r=e.concat(s=>(t.next(s),t.complete()));o.apply(i,r)},"bindCallback",arguments)}function RE(o,i,...e){return ae(t=>{let r=e.concat((s,n)=>s?t.error(s):(t.next(n),t.complete()));o.apply(i,r)},"bindNodeCallback",arguments)}function yE(){return ae(()=>{},"never",arguments)}function bE(o){return ae(i=>i.error(o),"throwError",arguments)}function Vn(){return ae(o=>o.complete(),"empty",arguments)}var lo=class extends j{constructor(i,e,t){super(i),this.f=e;let r=()=>{this.sink.next(this.acc),this.sink.complete()};typeof t=="undefined"?this.next=s=>{this.acc=s,this.complete=r,this.resetNext()}:(this.acc=t,this.complete=r)}next(i){this.acc=this.f(this.acc,i)}},Fu=X(lo,"reduce"),vE=o=>X(lo,"count")((i,e)=>o(e)?i+1:i,0),NE=()=>X(lo,"max")(Math.max),DE=()=>X(lo,"min")(Math.min),ME=()=>X(lo,"sum")((o,i)=>o+i,0);var Bu=class extends j{constructor(i,e,t){super(i),this.filter=e,this.thisArg=t}next(i){this.filter.call(this.thisArg,i)&&this.sink.next(i)}},$t=X(Bu,"filter"),Hu=class extends j{next(i){}},OE=X(Hu,"ignoreElements"),$u=class extends j{constructor(i,e){super(i),this.count=e}next(i){this.sink.next(i),--this.count===0&&(this.doDefer(),this.complete())}},or=X($u,"take"),Wu=class extends j{constructor(i,e){super(i);let t=new j(i);t.next=()=>{t.doDefer(),i.complete()},t.complete=xc,t.subscribe(e)}},ke=X(Wu,"takeUntil"),Gu=class extends j{constructor(i,e){super(i),this.f=e}next(i){this.f(i)?this.sink.next(i):(this.doDefer(),this.complete())}},ff=X(Gu,"takeWhile"),kE=o=>Fu((i,e)=>(i.push(e),i.length>o&&i.shift(),i),[]),qu=class extends j{constructor(i,e){super(i),this.count=e}next(i){--this.count===0&&(this.next=super.next)}},PE=X(qu,"skip"),Ju=class extends j{constructor(i,e){super(i),i.next=pe;let t=new j(i);t.next=()=>{t.doDefer(),i.resetNext()},t.complete=xc,t.subscribe(e)}},wE=X(Ju,"skipUntil"),ju=class extends j{constructor(i,e){super(i),this.f=e}next(i){this.f(i)||(this.next=super.next,this.next(i))}},Hc=X(ju,"skipWhile"),LE={leading:!0,trailing:!1},Xu=class extends j{constructor(i,e,t){super(i),this.durationSelector=e,this.trailing=t}cacheValue(i){this.last=i,this.disposed&&this.throttle(i)}send(i){this.sink.next(i),this.throttle(i)}throttle(i){this.reset(),this.subscribe(this.durationSelector(i))}next(){this.complete()}complete(){this.dispose(),this.trailing&&this.send(this.last)}},Fc=class extends j{constructor(i,e,t=LE){super(i),this.durationSelector=e,this.config=t,this._throttle=new Xu(this.sink,this.durationSelector,this.config.trailing),this._throttle.dispose()}next(i){this._throttle.disposed&&this.config.leading?this._throttle.send(i):this._throttle.cacheValue(i)}complete(){this._throttle.throttle=pe,this._throttle.complete(),super.complete()}},xE=X(Fc,"throttle"),UE={leading:!1,trailing:!0},VE=o=>X(Fc,"audit")(o,UE),zu=class extends j{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},Bc=class extends j{constructor(i,e){super(i),this.durationSelector=e,this._debounce=new zu(this.sink),this._debounce.dispose()}next(i){this._debounce.dispose(),this._debounce.reset(),this._debounce.last=i,this._debounce.subscribe(this.durationSelector(i))}complete(){this._debounce.complete(),super.complete()}},FE=X(Bc,"debounce"),BE=o=>X(Bc,"debounceTime")(i=>Un(o)),Qu=class extends j{constructor(i,e,t){super(i),this.count=e,this.defaultValue=t}next(i){this.count--===0&&(this.defaultValue=i,this.doDefer(),this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("not enough elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},HE=X(Qu,"elementAt"),$E=o=>i=>or(1)(Hc(e=>!o(e))(i)),Yu=class extends j{constructor(i,e){super(i),this.f=e,this.i=0}next(i){this.f(i)?(this.sink.next(this.i++),this.doDefer(),this.complete()):++this.i}},WE=X(Yu,"findIndex"),Zu=class extends j{constructor(i,e,t){super(i),this.f=e,this.defaultValue=t,this.index=0}next(i){(!this.f||this.f(i,this.index++))&&(this.defaultValue=i,this.doDefer(),this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},GE=X(Zu,"first"),Ku=class extends j{constructor(i,e,t){super(i),this.f=e,this.defaultValue=t,this.index=0}next(i){(!this.f||this.f(i,this.index++))&&(this.defaultValue=i)}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},qE=X(Ku,"last"),eh=class extends j{constructor(i,e){super(i),this.predicate=e,this.index=0}next(i){this.predicate(i,this.index++)?this.result=!0:(this.result=!1,this.doDefer(),this.complete())}complete(){if(this.result===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.result);super.complete()}},JE=X(eh,"every");var th=class extends j{constructor(i,e,t){super(i),this.f=e,typeof t=="undefined"?this.next=r=>{this.acc=r,this.resetNext(),this.sink.next(this.acc)}:this.acc=t}next(i){this.sink.next(this.acc=this.f(this.acc,i))}},mh=X(th,"scan"),ih=class extends j{constructor(){super(...arguments),this.hasLast=!1}next(i){this.hasLast?this.sink.next([this.last,i]):this.hasLast=!0,this.last=i}},jE=X(ih,"pairwise"),$c=class extends j{constructor(i,e,t){super(i),this.mapper=e,this.thisArg=t}next(i){super.next(this.mapper.call(this.thisArg,i))}},Fn=X($c,"map"),XE=o=>X($c,"mapTo")(i=>o),uo=class extends j{constructor(i,e,t){super(i),this.data=e,this.context=t}next(i){let e=this.context.combineResults;e?this.sink.next(e(this.data,i)):this.sink.next(i)}tryComplete(){this.context.resetComplete(),this.dispose()}},ho=class o extends j{constructor(i,e,t){super(i),this.makeSource=e,this.combineResults=t,this.index=0}subInner(i,e){let t=this.currentSink=new e(this.sink,i,this);this.complete===o.prototype.complete&&(this.complete=this.tryComplete),t.complete=t.tryComplete,t.subscribe(this.makeSource(i,this.index++))}complete(){this.sink.complete()}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},Wc=class extends uo{},Gc=class extends ho{next(i){this.subInner(i,Wc),this.next=e=>{this.currentSink.dispose(),this.subInner(e,Wc)}}},Mr=X(Gc,"switchMap");function Xc(o){return(i,e)=>o(()=>i,e)}var mo=Xc(X(Gc,"switchMapTo")),rh=class extends uo{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},qc=class extends ho{constructor(){super(...arguments),this.sources=[],this.next2=this.sources.push.bind(this.sources)}next(i){this.next2(i),this.subNext()}subNext(){this.next=this.next2,this.subInner(this.sources.shift(),rh),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},zE=X(qc,"concatMap"),QE=Xc(X(qc,"concatMapTo")),oh=class extends uo{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},Jc=class extends ho{constructor(){super(...arguments),this.inners=new Set}next(i){this.subInner(i,oh),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(i=>i.resetComplete()):this.dispose()}},YE=X(Jc,"mergeMap"),ZE=Xc(X(Jc,"mergeMapTo")),sh=class extends uo{dispose(){this.context.resetNext(),super.dispose()}},jc=class extends ho{next(i){this.next=pe,this.subInner(i,sh)}},KE=X(jc,"exhaustMap"),eS=Xc(X(jc,"exhaustMapTo")),nh=class extends j{constructor(i,e){super(i),this.f=e,this.groups=new Map}next(i){let e=this.f(i),t=this.groups.get(e);typeof t=="undefined"&&(t=ot(),t.key=e,this.groups.set(e,t),super.next(t)),t.next(i)}complete(){this.groups.forEach(i=>i.complete()),super.complete()}error(i){this.groups.forEach(e=>e.error(i)),super.error(i)}},tS=X(nh,"groupBy"),ah=class extends j{constructor(){super(...arguments),this.start=new Date}next(i){this.sink.next({value:i,interval:Number(new Date)-Number(this.start)}),this.start=new Date}},iS=X(ah,"timeInterval"),ch=class extends j{constructor(i,e){super(i),this.miniseconds=e,this.buffer=[],this.id=setInterval(()=>{this.sink.next(this.buffer.concat()),this.buffer.length=0},this.miniseconds)}next(i){this.buffer.push(i)}complete(){this.sink.next(this.buffer),super.complete()}dispose(){clearInterval(this.id),super.dispose()}},rS=X(ch,"bufferTime"),dh=class extends j{constructor(i,e){super(i),this.buffer=[],this.delayTime=e}dispose(){clearTimeout(this.timeoutId),super.dispose()}delay(i){this.timeoutId=setTimeout(()=>{let e=this.buffer.shift();if(e){let{time:t,data:r}=e;super.next(r),this.buffer.length&&this.delay(Number(this.buffer[0].time)-Number(t))}},i)}next(i){this.buffer.length||this.delay(this.delayTime),this.buffer.push({time:new Date,data:i})}complete(){this.timeoutId=setTimeout(()=>super.complete(),this.delayTime)}},oS=X(dh,"delay"),lh=class extends j{constructor(i,e){super(i),this.selector=e}error(i){this.dispose(),this.selector(i)(this.sink)}},ph=X(lh,"catchError"),uh=class extends uo{tryComplete(){let i=this.context.inners.delete(this);super.dispose(),i&&this.context.checkComplete()}next(i){this.sink.next(i),this.context.expandValue(i)}},hh=class extends ho{constructor(i,e){super(i,e),this.project=e,this.inners=new Set,this.sourceCompleted=!1}next(i){this.sink.next(i),this.expandValue(i)}expandValue(i){let e=new uh(this.sink,i,this);this.currentSink=e,this.complete=this.tryComplete,e.complete=e.tryComplete,this.inners.add(e),e.subscribe(this.makeSource(i,this.index++))}complete(){this.sourceCompleted=!0,this.checkComplete()}checkComplete(){this.sourceCompleted&&this.inners.size===0&&(this.resetComplete(),super.complete())}tryComplete(){this.sourceCompleted=!0,this.checkComplete()}},sS=X(hh,"expand");var nS=()=>o=>new Promise((i,e)=>{let t;new co(o,r=>t=r,e,()=>i(t))}),aS=()=>o=>{let i;return new ReadableStream({start(e){i=new co(o,e.enqueue.bind(e),e.error.bind(e),e.close.bind(e))},cancel(){i.dispose()}})},Te=(o=pe,i=pe,e=pe)=>t=>new co(t,o,i,e),fh=class extends j{constructor(i,e){super(i),e instanceof Function?this.next=t=>{e(t),i.next(t)}:(e.next&&(this.next=t=>{e.next(t),i.next(t)}),e.complete&&(this.complete=()=>{e.complete(),i.complete()}),e.error&&(this.error=t=>{e.error(t),i.error(t)}))}},Bn=X(fh,"tap"),_h=class extends j{constructor(i,e){super(i),this.timeout=e,this.id=setTimeout(()=>this.error(new wn(this.timeout)),this.timeout)}next(i){super.next(i),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},cS=X(_h,"timeout"),dS=(o=1/0)=>i=>{if(i instanceof Ht){let e=ae(t=>{let r=o,s=new j(t);s.error=n=>{r-- >0?s.subscribe(i):t.error(n)},s.sourceId=e.id,s.subscribe(i)},"retry",[o]);return e.source=i,Oe.pipe(e),e}else return e=>{let t=o,r=new j(e);r.error=s=>{t-- >0?i(r):e.error(s)},i(r)}};var ps=(e=>(e[e.AUTO_SWITCH_NEW_DEVICE=0]="AUTO_SWITCH_NEW_DEVICE",e[e.WAIT_CURRENT_DEVICE=1]="WAIT_CURRENT_DEVICE",e))(ps||{}),po=class po extends no{constructor(e,t){super({mediaType:e,PlayerClass:t});d(this,"isRemote",!1);d(this,"deviceId");d(this,"groupId","");d(this,"label","");d(this,"sourceTrack");d(this,"enableAutoSwitchWhenRecapturing",!0);d(this,"_isRecapturing",!1);d(this,"_lastRecaptureTime",0);d(this,"_onMuteTimeoutId",-1);d(this,"_encodeCheckTimeoutId",-1);d(this,"recaptureMode",0);d(this,"profile");d(this,"retryEncodeFailed")}get enableEncodeFrame(){return!1}get isPublishing(){return this.state.toString()==="publishing"}get isPublished(){return this.state==="publish"}get isUseCustomSource(){return this.sourceTrack&&this.mediaTrack&&this.sourceTrack!==this.mediaTrack}encodeFrame(e,t){throw new Error("Method not implemented.")}installTrackEvent(e){e.addEventListener(f.MUTE,this.onTrackMuted),e.addEventListener(f.UNMUTE,this.onTrackUnmuted),e.addEventListener(f.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===f.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){e.removeEventListener(f.MUTE,this.onTrackMuted),e.removeEventListener(f.UNMUTE,this.onTrackUnmuted),e.removeEventListener(f.ENDED,this.onTrackEnded)}setStateToReady(){}capture(e,t=!1){return p(this,null,function*(){var s;let r=this.sourceTrack;try{let n=U();S.emit(A.LOCAL_TRACK_CAPTURE_START,{track:this});let a;e.customSource?(a=new MediaStream,a.addTrack(e.customSource)):(t||(s=this.sourceTrack)==null||s.stop(),a=yield nf(e));let c=a.getTracks()[0];return yield this.setInputMediaStreamTrack(c),e.customSource||(this.sourceTrack=c,this.updateDeviceIdInUse(),this.listenDeviceChange()),S.emit(A.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:U()-n}),a}catch(n){throw S.emit(A.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:n}),this.log.error(`getUserMedia error observed ${n}`),n}finally{t&&(r==null||r.stop())}})}setOutputMediaStreamTrack(e){var t;if(super.setOutputMediaStreamTrack(e),this.setStateToReady(),this.isPublishing||this.isPublished)return(t=this.room)==null?void 0:t.replaceTrack(this)}get hasFlag(){var t,r;let e=Kt(((t=this.room)==null?void 0:t.localPublishFlag)||0,((r=this.room)==null?void 0:r.userId)||"");return this.mediaType===4&&e.hasVideo||this.mediaType===1&&e.hasAudio||this.mediaType===2&&e.hasAuxiliary}publish(e,t){return p(this,null,function*(){return this.room=e,this.room.localTracks.add(this),this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.bindParent(e.getLogger()),yield t,this._checkPublishFlag(e)})}_checkPublishFlag(e){return new Promise((t,r)=>p(this,null,function*(){var l,u,h,m;let s=()=>r(new D({code:I.API_CALL_ABORTED,message:"publish aborted"}));if(this.hasFlag||this.muted?t():((this.state===J.INIT||this.state==="ready")&&s(),de(ce(e,"local-publish-flag-changed"),$t(()=>this.hasFlag),ke(Ln(ce(this,J.INIT),ce(this,"ready"))),Te(t,r,s))),(((u=(l=this.room)==null?void 0:l.networkQuality)==null?void 0:u.uplinkNetworkQuality)||0)>3)return t();let a=e.heartbeatCount,c=((m=(h=this.mediaTrack)==null?void 0:h.stats)==null?void 0:m.totalFrames)||0;this._encodeCheckTimeoutId=setTimeout(()=>p(this,null,function*(){var g,E,C,k,re,P,Qe;if((((E=(g=this.room)==null?void 0:g.networkQuality)==null?void 0:E.uplinkNetworkQuality)||0)>3||e.heartbeatCount-a<3)return t();if((this.isPublished||this.isPublishing)&&this.isMediaTrackActive){if((C=this.mediaTrack)!=null&&C.stats){let te=this.mediaTrack.stats.totalFrames||0;te-c===0&&this.log.warn("capture totalFrames is 0 during encode check, totalFrames",te)}let N=this.kind===f.AUDIO,b=this.stat.bytesSent>0;if(v[b?"addSuccessEvent":"addFailedEvent"]({key:N?503700:513702}),!N){let te=((re=(k=this.room)==null?void 0:k.videoCodec)==null?void 0:re.toUpperCase())||"H264",ve={H264:513704,H265:513705,VP8:513706}[te];ve&&v[b?"addSuccessEvent":"addFailedEvent"]({key:ve})}if(!b){if(v.addEnum({key:N?503701:513703,value:Zr()}),se.uploadEvent({log:`stat-encode-failed-${this.kind}-${si()||ni()}`,userId:this.userId}),this.log.warn(N?"encode failed":`${(Qe=(P=this.room)==null?void 0:P.videoCodec)==null?void 0:Qe.toUpperCase()} encode failed`),this.retryEncodeFailed&&(this.log.warn("retry encode"),yield this.retryEncodeFailed(this),this.stat.bytesSent>0||this.hasFlag||(yield Ke(5e3),this.stat.bytesSent>0||this.hasFlag)))return t();this.emit("6",this),r(new D({message:`${this.strMediaType} encode failed`,code:N?I.AUDIO_ENCODE_FAILED:I.VIDEO_ENCODE_FAILED}))}}}),1e4)}))}unpublish(){this.room&&this.room.localTracks.delete(this),this.log.info("unpublish"),S.emit(A.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return p(this,null,function*(){if(this.sourceTrack&&yi){let{deviceId:e,groupId:t}=this.sourceTrack.getSettings(),{label:r}=this.sourceTrack;(yield of({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=r,t&&(this.groupId=t),ds().then(n=>{let a=n.find(c=>{let l=c.deviceId===e;return t&&(l=l&&c.groupId===t),l});a&&this.emit("2",a)}))}})}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(e=!1){return!(!this.deviceId||!this.sourceTrack||this.kind===f.AUDIO&&!rf(this.sourceTrack)||this.kind===f.VIDEO&&!tf(this.sourceTrack)||this._isRecapturing||e&&ri&&Re)}onTrackMuted(){if(super.onTrackMuted(),af(),!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<ko){setTimeout(()=>this.onTrackMuted(),ko);return}this._onMuteTimeoutId=setTimeout(()=>p(this,null,function*(){var e;if((e=this.sourceTrack)!=null&&e.muted){if((ge||_e)&&document.visibilityState!=="visible")return;this.recapture(yield this.getRecoverCaptureDeviceId())}}),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return p(this,null,function*(){if(Pe(po.prototype,this,"onTrackEnded").call(this),!!this.isNeedToRecapture()&&this.recaptureMode===0){if(Date.now()-this._lastRecaptureTime<ko){setTimeout(()=>this.onTrackEnded(),ko);return}this.emit("7"),this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e,t=!1){return p(this,null,function*(){var n;if(this._isRecapturing||!this.sourceTrack)return;this.log.warn("recapture trying");let r=this.sourceTrack;t||(n=this.sourceTrack)==null||n.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let s={useExactDeviceId:!0};if(e==="user"||e==="environment")s.facingMode=e;else{let a;(this.kind==="audio"?yield It():yield At()).find(l=>l.deviceId===e)&&(a=e),s.deviceId=a}return this.capture(s,t).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),S.emit(A.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(a=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${a.message}`),this.emit("5",a),S.emit(A.LOCAL_TRACK_RECAPTURE,{track:this,error:a})}).finally(()=>{t&&(r==null||r.stop())})})}getRecoverCaptureDeviceId(){return p(this,null,function*(){let e=this instanceof je;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let r=(Hn.get(t)||0)+1;if(Hn.set(t,r),r>=3&&this.enableAutoSwitchWhenRecapturing){let s=e?(yield At()).find(n=>!Hn.has(n.deviceId)):(yield It()).find(n=>!Hn.has(n.deviceId));s&&(this.log.warn(`${t} capture fail ${r} times, change new ${s.deviceId}`),t=s.deviceId)}}return t})}stopCapture(){var e;this.sourceTrack&&(this.sourceTrack.stop(),this.uninstallTrackEvent(this.sourceTrack)),this._inputTrack&&this.uninstallTrackEvent(this._inputTrack),(e=this.manager)==null||e.removeInput(this)}close(){super.close(),this.stopCapture()}};M([ye(J.INIT,"ready",{ignoreError:!0,sync:!0})],po.prototype,"setStateToReady",1),M([ir()],po.prototype,"capture",1),M([ye("ready","publish",{ignoreError:!0,success(){S.emit(A.LOCAL_TRACK_PUBLISHED,{track:this,room:this.room}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),this.log.info("published")},fail(e){var n;(n=this.room)==null||n.localTracks.delete(this);let t="error",r=e instanceof D?e:e.cause instanceof D?e.cause:e,s=!1;r instanceof D&&(r.message.includes("timeout")?t="timeout":r.code===I.API_CALL_ABORTED&&(s=!0,t="api-call")),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:t,error:r}),this.log[s?"info":"error"]("publish failed",r)}}),Rt(521714,!1)],po.prototype,"publish",1),M([Q(e=>function(){return p(this,null,function*(){let t=this.state==="publish"?"started":"starting";e.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:t,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)})}),ye([],"ready",{sync:!0})],po.prototype,"unpublish",1);var pi=po,Hn=new Map;S.on(A.SWITCH_DEVICE_SUCCESS,o=>{o.track.deviceId&&Hn.delete(o.track.deviceId)});var kt=class o extends pi{constructor(e){super(1,Dc);d(this,"mediaType",1);d(this,"volume",0);d(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40});d(this,"playerMuted",!0);d(this,"pipeline");d(this,"earMonitorGainNode",new xe);d(this,"_output",new xe);d(this,"codecPipeline",[]);d(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0});d(this,"mixedAudioReferenceMap",new Map);d(this,"isAudioContextLongSuspended",!1);d(this,"after3aSilenceStartTime",0);this.manager=e,this.pipeline=new cs(e),this.pipeline.source.pipeTo(this.player.pipeline.volumeMeter),this.pipeline.gain.pipeTo(this.earMonitorGainNode).pipeTo(this._output),this.pipeline.gain.pipeTo(this.player.pipeline.volumeMeterAfter3A),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this),S.on(A.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this)}get dbVolume(){return so.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}getInternalAudioLevelAfter3A(){if(this.pipeline.aec.node||this.pipeline.denoiser.node)return this.player.getInternalAudioLevelAfter3A()}updateAfter3aSilenceStartTime(e){T(e)||(e===0&&!this.after3aSilenceStartTime?this.after3aSilenceStartTime=U():e>0&&(this.after3aSilenceStartTime=0))}setInputMediaStreamTrack(e){return p(this,null,function*(){let t=this.trackSettings||{};v.addEnum({key:501701,value:t.channelCount||0,useUV:!1}),v.addEnum({key:501702,value:t.sampleRate||0,useUV:!1}),v.addEnum({key:502700,value:0});let{sampleRate:r,channelCount:s}=t;this._log.info(`local audio track input ${JSON.stringify({sampleRate:r,channelCount:s})}`),this.pipeline.source.channelCount=s||1,this.pipeline.replaceSource(e),yield Pe(o.prototype,this,"setInputMediaStreamTrack").call(this,e),this.updatePlayingState(!!e)})}capture(a){return p(this,arguments,function*({deviceId:e,customSource:t,useExactDeviceId:r=!0,retryWhenExactFailed:s},n=!1){let c=yield Pe(o.prototype,this,"capture").call(this,{video:!1,audio:!0,microphoneId:e,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:r,retryWhenExactFailed:s,customSource:t},n);return vr(),c})}switchDevice(e){return p(this,null,function*(){if(this.mediaTrack){if(this.deviceId===e&&!this.isUseCustomSource)if(e===Wr){if(yield Mu(this.groupId,this.label))return}else return;try{this.log.info(`switchDevice audio to: ${e}`),this.sourceTrack&&this.sourceTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0,retryWhenExactFailed:!1}),S.emit(A.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(t){throw this.log.error(`switch microphone failed ${t}`),this.deviceId&&this.recapture(this.deviceId),t}}})}listenDeviceChange(){be&&!be.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&be.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return p(this,null,function*(){if(e.deviceId===this.deviceId){let t=this.recaptureMode===1;if(this.log.warn(`RecaptureMode: ${ps[this.recaptureMode]}. Current microphone is lost: ${JSON.stringify(e)}`),this.recaptureMode===0){Ne(this.userId,{eventId:2003,param1:6,streamType:1});let r=yield It();r[0]?this.recapture(r[0].deviceId):t=!0}t&&be.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.recaptureMode===1&&e.deviceId!==this.deviceId||(be.off("audioInputAdded",this.handleMicrophoneAdded,this),this.log.warn(`microphone added: ${JSON.stringify(e)}`),this.recapture(e.deviceId))}update3A(s){return p(this,arguments,function*({echoCancellation:e,noiseSuppression:t,autoGainControl:r}){let n=this.sourceTrack||this.mediaTrack;if(!n)return;let a=n.getConstraints(),c=!1;!T(e)&&e!==this.profile.echoCancellation&&(this.profile.echoCancellation=e,a.echoCancellation=e,c=!0),!T(t)&&t!==this.profile.noiseSuppression&&(this.profile.noiseSuppression=t,a.noiseSuppression=t,c=!0),!T(r)&&r!==this.profile.autoGainControl&&(this.profile.autoGainControl=r,a.autoGainControl=r,c=!0),c&&(K||Re?yield n.applyConstraints(a).catch(l=>this._log.warn("update3A failed: ",l)):this.deviceId&&(yield this.recapture(this.deviceId,!0)))})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&v.addEnum({key:502700,value:2})}setAudioVolume(e){super.setAudioVolume(0),ge&&this.player.setMuted(!0),this.earMonitorGainNode.node||(this.earMonitorGainNode.setNode(Ee().createGain()),this._output.setNode(Ee().destination)),this.earMonitorGainNode.node.gain.value=e}enableTrackANS(e){return this.update3A({noiseSuppression:e})}enableTrackAEC(e){if(this.sourceTrack&&!(Re||ge))return this.update3A({echoCancellation:e})}addDenoiser(e){var t;if(We<=92&&((t=this.trackSettings)==null?void 0:t.sampleRate)!==48e3){this._log.warn("denoiser only support sampleRate 48000 before chrome 93");return}v.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.enableTrackANS(!1)}mixAudioReference(e,t){if(this.mixedAudioReferenceMap.has(t))return;this.log.info(`mixAudioReference() => ${t}`);let r=On(e);if(!r)return;let s=new xe,n=Ee().createGain();n.gain.value=1;let a=new xe;s.pipeTo(a).pipeTo(this.pipeline.mixNode),s.setNode(r),a.setNode(n),this.mixedAudioReferenceMap.set(t,[s,a])}unMixAudioReference(e){let[t,r]=this.mixedAudioReferenceMap.get(e)||[];t&&(this.log.info(`unMixAudioReference() => ${e}`),t.deleteNode(),r==null||r.deleteNode(),this.mixedAudioReferenceMap.delete(e))}setAudioReferenceVolume(e,t){let[r,s]=this.mixedAudioReferenceMap.get(e)||[];s!=null&&s.node&&(s.node.gain.value=t/100,this.log.info(`setAudioReferenceVolume() => ${e} ${s.node.gain.value}`))}addAudioProcessor(e,t,r){this.pipeline.silentNode.setNode(r),this.pipeline.mixNode.setNode(t),this.pipeline.aec.setNode(e)}removeDenoiser(e){if(this.pipeline.denoiser.node===e)return this.pipeline.denoiser.deleteNode(),this.enableTrackANS(!0)}removeAudioProcessor(e){this.pipeline.aec.node===e&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode())}close(){this.mixedAudioReferenceMap.forEach(([e,t])=>{e.deleteNode(),t.deleteNode()}),this.mixedAudioReferenceMap.clear(),this.pipeline.remove(),this.earMonitorGainNode.deleteNode(),this._output.deleteNode(),be.off("audioInputAdded",this.handleMicrophoneAdded,this),be.off("audioInputRemoved",this.handleMicrophoneRemoved,this),S.off(A.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this),super.close()}recapture(e,t=!1){return p(this,null,function*(){try{yield Pe(o.prototype,this,"recapture").call(this,e,t)}catch(r){let s=(yield It()).find(n=>n.deviceId!==e);if(s)yield Pe(o.prototype,this,"recapture").call(this,s.deviceId);else throw r}})}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduceRight((t,r)=>r?r({frame:t,ntp:Fi()}):t,e):e}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}get enableEncryptFrame(){return this.manager&&!!this.manager.encodePipeline[0]}handleAudioContextLongSuspended({isSuspended:e}){if(this.pipeline.isProcessEnabled)if(e){this.isAudioContextLongSuspended=!0,this.log.warn(`context has suspended for ${vu/1e3} seconds, change to source audio${Ft?"":", non-Safari"}`);let t=this.sourceTrack||this.mediaTrack;t&&this.setOutputMediaStreamTrack(t)}else this.isAudioContextLongSuspended=!1,this.log.warn("context has resumed, change to processed audio"),this.pipeline.track&&this.setOutputMediaStreamTrack(this.pipeline.track)}setOutputMediaStreamTrack(e){if(this.isAudioContextLongSuspended){let t=this.sourceTrack||this.mediaTrack;t&&(e=t)}super.setOutputMediaStreamTrack(e)}};function zc(o,i=!1){let e=new DataView(o),t=[],r=0;for(;r<e.byteLength;){let s=0;if(r+4<=e.byteLength&&e.getUint8(r)===0&&e.getUint8(r+1)===0&&e.getUint8(r+2)===0&&e.getUint8(r+3)===1)s=4;else if(r+3<=e.byteLength&&e.getUint8(r)===0&&e.getUint8(r+1)===0&&e.getUint8(r+2)===1)s=3;else{r+=1;continue}let n=-1;for(let h=r+s;h<e.byteLength;h+=1){if(h+4<=e.byteLength&&e.getUint8(h)===0&&e.getUint8(h+1)===0&&e.getUint8(h+2)===0&&e.getUint8(h+3)===1){n=h;break}if(h+3<=e.byteLength&&e.getUint8(h)===0&&e.getUint8(h+1)===0&&e.getUint8(h+2)===1){n=h;break}}let a=n===-1?e.byteLength:n,c=a-r,l=new ArrayBuffer(c),u=new DataView(l);for(let h=0;h<c;h+=1)u.setUint8(h,e.getUint8(r+h));t.push(new sr(u,i)),r=a}return t}var sr=class{constructor(i,e=!1){this.dataView=i;this.isSEI&&(e?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let{seiPayloadStartIndex:i}=this,e=this.dataView.byteLength-2,t=[],r=0;for(let n=i;n<=e;n++){let a=this.dataView.getInt8(n);switch(a){case 0:case 1:case 2:case 3:r===2&&(t.push(3),r=0),a===0?r+=1:r=0,t.push(a);break;default:r=0,t.push(a);break}}t.push(this.dataView.getInt8(this.dataView.byteLength-1));let s=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=s}removePreventionByte(){let{seiPayloadStartIndex:i}=this,e=this.dataView.byteLength-1,t=[],r=0;for(let n=i;n<=e;n++)switch(this.dataView.getInt8(n)){case 0:r++,t.push(this.dataView.getInt8(n));break;case 3:r!==2&&t.push(this.dataView.getInt8(n)),r=0;break;default:t.push(this.dataView.getInt8(n)),r=0;break}let s=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=s}get seiPayloadStartIndex(){let i=6;for(let e=6;e<this.dataView.buffer.byteLength&&(i+=1,this.dataView.getUint8(e)===255);e+=1);return i}get seiPayloadType(){return this.isSEI?this.dataView.getUint8(5):null}get seiPayload(){if(!this.isSEI)return null;let i=0,e=6;for(let n=6;n<this.dataView.buffer.byteLength;n+=1){let a=this.dataView.getUint8(n);if(e+=1,a===255)i+=255;else{i+=a;break}}let t=new ArrayBuffer(i),r=new DataView(t),s=e;for(let n=0;n<t.byteLength;n+=1)r.setInt8(n,this.dataView.getInt8(s+n));return r}get naluType(){let i=this.getStartCodeLength();return i>=this.dataView.byteLength?0:this.dataView.getUint8(i)&31}getStartCodeLength(){return this.dataView.byteLength>=4&&this.dataView.getUint8(0)===0&&this.dataView.getUint8(1)===0&&this.dataView.getUint8(2)===0&&this.dataView.getUint8(3)===1?4:this.dataView.byteLength>=3&&this.dataView.getUint8(0)===0&&this.dataView.getUint8(1)===0&&this.dataView.getUint8(2)===1?3:0}get isIDR(){return this.naluType===5}get isSPS(){return this.naluType===7}get isPPS(){return this.naluType===8}get isSEI(){return this.naluType===6}};var Qc=class{constructor(){d(this,"_seiMessageList",[]);d(this,"_smallSeiMessageList",[]);d(this,"_seiPayloadType",243)}encodeSEINalu(i){let e=i.byteLength,t=parseInt(String(e/255),10),r=e%255,s=[];s.push(0,0,0,1,6,this._seiPayloadType);for(let a=0;a<t;a++)s.push(255);s.push(r);let n=new DataView(i);return s.push(...new Uint8Array(n.buffer)),s.push(128),new sr(new DataView(new Uint8Array(s).buffer),!0)}sendSEI(i,e){e!=null&&e.seiPayloadType&&(this._seiPayloadType=e.seiPayloadType),this._seiMessageList.push(i),e!=null&&e.small&&this._smallSeiMessageList.push(i)}isEmpty(){return!this._seiMessageList.length}getNaluCount(i){let e=0,t=0,r=new DataView(i);for(let s=0;s<i.byteLength;s++)switch(r.getUint8(s)){case 0:e++;break;case 1:(e===2||e===3)&&t++,e=0;break;default:e=0;break}return t}encode(i,e){let t=e?this._smallSeiMessageList:this._seiMessageList;if(t.length>0&&i.data.byteLength>0){let s=9-this.getNaluCount(i.data);if(s<=0)return 0;let n=t.splice(0,s).reverse().map(this.encodeSEINalu.bind(this)),a=n.reduce((m,_)=>m+_.dataView.byteLength,0),c=new ArrayBuffer(a+i.data.byteLength),l=new DataView(c),u=new DataView(i.data),h=0;for(let m=0;m<n.length;m++)for(let _=0;_<n[m].dataView.byteLength;_++)l.setInt8(h++,n[m].dataView.getInt8(_));for(let m=0;m<i.data.byteLength;m++)l.setInt8(h++,u.getInt8(m));return i.data=c,n.length}return 0}};var Or=class Or extends pi{constructor(e,t=4){super(t,it);d(this,"profile",O({},pr));d(this,"avoidCropping",!1);d(this,"_scaleResolutionDownBy");d(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0,framesCaptured:0});d(this,"small");d(this,"isNeedToSetBandwidth");d(this,"muteImage");d(this,"manager");d(this,"_seiCodec",new Qc);this.manager=e;let r=()=>{var s;if(this.isAllowed2k4k(this.profile))this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1});else{let n=Ut(((s=this.room)==null?void 0:s.sdkAppId)||0)?ha:ua;this.log.warn(`Resolution is reset to 1080p, need to upgrade ability here ${n}`),this.setProfile(L(O({},this.profile),{width:1920,height:1080})),this.applyProfile()}};this.on("input-media-track-changed",r),this.on("publish",r),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(!(!yi||!this.mediaTrack))return this.mediaTrack.getSettings().facingMode}get contentHint(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)||""}get isQosClearFirst(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)==="detail"}get hasSmall(){var e;return!!((e=this.manager)!=null&&e.hasSmall)}setMute(e){return p(this,null,function*(){var t,r,s;if(ie(e)){if(this.muteImage===e)return;yield(t=this.manager)==null?void 0:t.deleteWatermark("mute"),yield(r=this.manager)==null?void 0:r.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:e,fillVideo:!0}),this.muteImage=e,Pe(Or.prototype,this,"setMute").call(this,!1)}else this.muteImage&&(yield(s=this.manager)==null?void 0:s.deleteWatermark("mute"),this.muteImage=void 0),Pe(Or.prototype,this,"setMute").call(this,e)})}capture(a){return p(this,arguments,function*({deviceId:e,facingMode:t,useExactDeviceId:r=!0,customSource:s,retryWhenExactFailed:n=!0}){let c={audio:!1,video:!0,facingMode:t||this.facingMode,cameraId:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:r,retryWhenExactFailed:n,customSource:s};if(c.facingMode==="environment"){let l=yield this.getDeviceIdWhenUsingBackCamera();l&&(c.cameraId=l)}return Pe(Or.prototype,this,"capture").call(this,c)})}setProfile(e){var r;let t=this.fallbackProfile(e);if(t.bitrate&&(this.isNeedToSetBandwidth=t.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile))super.setProfile(t);else{let s=Ut(((r=this.room)==null?void 0:r.sdkAppId)||0)?ha:ua;this.log.warn(`Resolution is reset to 1080p, need to upgrade ability here ${s}`),super.setProfile(L(O({},this.profile),{width:1920,height:1080}))}}applyProfile(){return p(this,null,function*(){var a;if(!this.mediaTrack)return;let{width:e=0,height:t=0}=(this.sourceTrack||this.mediaTrack).getSettings(),r=e*t,s=this.settings,n=s.height!==this.profile.height||s.width!==this.profile.width||s.frameRate!==this.profile.frameRate;if(n&&(et===16&&this.deviceId?yield this.recapture(this.deviceId):(yield(a=this.sourceTrack||this.mediaTrack)==null?void 0:a.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}),this.manager&&this.manager.changeInput(this)),this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1})),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth){this.isNeedToSetBandwidth=!1;let{width:c=0,height:l=0}=(this.sourceTrack||this.mediaTrack).getSettings(),u=c*l;if(n&&u&&r&&u===r){this.log.warn("set bandwidth failed: resolution is not changed");return}return this.room.setBandWidth({bandwidth:this.profile.bitrate,type:f.VIDEO,videoType:f.BIG})}})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},t=this.sourceTrack||this.mediaTrack;return yi&&t&&Object.assign(e,t.getSettings()),e}get scaleResolutionDownBy(){return this._scaleResolutionDownBy?this._scaleResolutionDownBy:Ho(this.settings,this.profile)}isAllowed2k4k(e){var t;return!this.room||!this.room.scheduleResult||this.isScreen||e.height*e.width<2560*1440?!0:((t=this.room.scheduleResult.trtcAutoConf)==null?void 0:t["2k4k"])===1}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}switchDevice(e){return p(this,null,function*(){try{if(!this.isNeedToSwitchDevice(e)&&!this.isUseCustomSource)return;let t={useExactDeviceId:!0,retryWhenExactFailed:!1};e==="user"||e==="environment"?t.facingMode=e:t.deviceId=e,this.sourceTrack&&this.sourceTrack.stop(),yield this.capture(t),S.emit(A.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(t){throw this.log.error(`switch camera failed ${t}`),this.deviceId&&this.recapture(this.deviceId),t}})}getDeviceIdWhenUsingBackCamera(){return p(this,null,function*(){let e;try{if(rn&&!Qo&&du){let r=(yield At(!0)).map(n=>{var a;return L(O({},n),{capabilities:(a=n.getCapabilities)==null?void 0:a.call(n)})}).filter(n=>{var a,c;return(c=(a=n.capabilities)==null?void 0:a.facingMode)==null?void 0:c.includes("environment")}),s=r[0];r.forEach(n=>{var u,h,m,_;let{capabilities:a}=n,c=(u=a.width)!=null&&u.max&&((h=a.height)!=null&&h.max)?a.width.max*a.height.max:0,l=(m=s.capabilities.width)!=null&&m.max&&((_=s.capabilities.height)!=null&&_.max)?s.capabilities.width.max*s.capabilities.height.max:0;c>l&&(s=n)}),s!=null&&s.capabilities&&(this._log.info("use max resolution back camera",s),e=s.deviceId)}}catch(t){this._log.warn("get max res camera failed",t)}return e})}updateSmallConfig(e){var r,s;this._log.info(`update small stream config: ${JSON.stringify(e)}`);let t=!this.small;this.small=this.fallbackProfile(e,!0),(r=this.manager)==null||r.update(),t&&((s=this.room)==null||s.enableSmall(!0)),this.log.info("update small stream config success")}fallbackProfile(e,t=!1){let r=e.width>e.height,s=O({},e);return e.width*e.height<=160*120&&_e&&Ve&&(this.log.warn(`${t?"small ":""}resolution is ${e.width}*${e.height}, fallback to 240*180 for android chrome`),s.width=r?240:180,s.height=r?180:240,s.bitrate=Math.max(e.bitrate,150)),e.width*e.height>1280*720&&Ol&&(s.width=r?1280:720,s.height=r?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),nn(Tt,"14.3")&&Dl(Tt,"14.0",!0)&&this.on("7",()=>{let n=this.profile.width>this.profile.height;this.profile.width*this.profile.height>640*480?(this.profile.width=n?640:480,this.profile.height=n?480:640,this.log.warn("reduce the resolution to 480p on iOS 14.0 ~ 14.2")):this.profile.width*this.profile.height>640*360&&(this.profile.width=n?640:360,this.profile.height=n?360:640,this.log.warn("reduce the resolution to 360p on iOS 14.0 ~ 14.2"))}),!t&&this.avoidCropping&&(Ve||K)&&!an()&&e.width*e.height<=640*360&&e.width/e.height===16/9&&(this._scaleResolutionDownBy=1280/e.width,e.width=1280,e.height=720,this.log.warn(`capture 720p, scale: ${this._scaleResolutionDownBy}`)),s}stopSmall(){var e,t;this.small&&(delete this.small,(e=this.manager)==null||e.update(),(t=this.room)==null||t.enableSmall(!1))}listenDeviceChange(){be&&!be.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&be.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return p(this,null,function*(){if(e.deviceId===this.deviceId){let t=this.recaptureMode===1;if(this.log.warn(`RecaptureMode: ${ps[this.recaptureMode]}. Current camera is lost: ${JSON.stringify(e)}`),this.recaptureMode===0){Ne(this.userId,{eventId:2003,param1:7,streamType:2});let r=yield At();r[0]?this.recapture(r[0].deviceId):t=!0}t&&be.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return p(this,null,function*(){this.recaptureMode===1&&e.deviceId!==this.deviceId||(be.off("videoInputAdded",this.handleCameraAdded,this),this.log.warn(`camera added: ${JSON.stringify(e)}`),this.recapture(e.deviceId))})}encodeFrame(e,t){if(!this.manager)return e;let r=t?8:this.mediaType;return this.manager.encodePipeline.reduceRight((s,n)=>n?n({frame:s,mediaType:r}):s,e)}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}play(e,t){return T(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,t)}close(){be.off("videoInputAdded",this.handleCameraAdded,this),be.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return p(this,null,function*(){try{yield Pe(Or.prototype,this,"recapture").call(this,e)}catch(t){let r=(yield At()).find(s=>s.deviceId!==e);if(r)yield Pe(Or.prototype,this,"recapture").call(this,r.deviceId);else throw t}})}setContentHint(e){this.mediaTrack&&"contentHint"in this.mediaTrack&&(this.mediaTrack.contentHint!==e&&(this.log.info(`setContentHint ${e}`),this.mediaTrack.contentHint=e),this.outMediaTrack&&this.outMediaTrack.contentHint!==e&&(this.outMediaTrack.contentHint=e))}setRotation(e){this.manager&&(this.isScreen||T(e)||e!==this.rotation&&(this.rotation=e,this.manager.rotation=e))}};M([Ct(function(e){this.setContentHint(e.contentHint||"motion")})],Or.prototype,"capture",1);var je=Or;var Eh={};Vi(Eh,{REPORT_TYPE:()=>$o,buildSSOPackage:()=>Gi,bytes2ms:()=>Mm,calculateScaleResolutionDownNumber:()=>Ho,concatArrayBuffers:()=>ka,convertObjectNumberToInt:()=>Js,copyProperties:()=>Dm,deepClone:()=>Gr,deepCloneBasic:()=>ya,deepMerge:()=>ei,delay:()=>Ke,fibonacci:()=>Jr,formatedTime:()=>Fm,getConstructorName:()=>xo,getContainerFromElement:()=>Vm,getEnv:()=>bm,getFirst16Bits:()=>Hm,getInternalVersion:()=>xm,getLast16Bits:()=>Pa,getLoggerUrl:()=>Wi,getMediaStreamTrackInfo:()=>Oa,getMuteStateFromFlag:()=>Kt,getNetworkType:()=>ba,getNumNetworkType:()=>qr,getReconnectionTimeout:()=>Zt,getStringByteLength:()=>qs,getTurnServer:()=>Um,getUint32Version:()=>Na,getValueType:()=>Me,getViewListFromView:()=>Fo,glog:()=>_l,ipv4ToUint32:()=>Vo,isArray:()=>Ie,isAudioWorkletSupported:()=>wm,isBoolean:()=>he,isConstructor:()=>jr,isEmpty:()=>Uo,isFunction:()=>le,isLangChinese:()=>Yt,isMediaStreamTrack:()=>km,isNumber:()=>z,isObject:()=>yt,isOverseaSdkAppId:()=>Ut,isPlainObject:()=>dt,isPortrait:()=>gl,isPromise:()=>Tr,isRemoteTrack:()=>Pm,isRotate90Or270:()=>bt,isSetSinkIdSupported:()=>Lm,isString:()=>ie,isUndefined:()=>T,loadImage:()=>Bo,loadVideo:()=>Bm,ms2bytes:()=>Om,ms2samples:()=>fl,normalizeUrl:()=>Ma,performanceNow:()=>U,promiseAny:()=>Xr,samples2ms:()=>pl,setNetworkTypeFromWebRTC:()=>va,stringify:()=>_t,stringifyIncludeValue:()=>Gs,throttlePromise:()=>Da});var hS=[-1,-1,1,-1,-1,1,1,1],mS=[0,0,1,0,0,1,1,1];var kr=class kr extends J{constructor(e,t){super();this.context=e;d(this,"name");d(this,"input");d(this,"output");d(this,"texture");d(this,"ctx2d",null);d(this,"fbo");d(this,"width",0);d(this,"height",0);d(this,"x",0);d(this,"y",0);d(this,"program");d(this,"vertexShader");d(this,"fragmentShader");d(this,"totalFrames",0);d(this,"dropFrames",0);d(this,"matchInputSize",!0);d(this,"texCoordBuffer");d(this,"positionBuffer");d(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0});d(this,"cost",0);d(this,"_canvas",null);d(this,"_image");d(this,"log");if(this.context.on("disconnect",this.close,this),this.name=t.name,this.log=t.logger,this.matchInputSize=t.matchInputSize!==!1,this.width=t.width||e.width,this.height=t.height||e.height,this._image=t.image,e instanceof Xe){e.ctx&&t.create2d&&(typeof OffscreenCanvas=="function"&&et!==16?this._canvas=new OffscreenCanvas(this.width,this.height):(this._canvas=document.createElement("canvas"),this._canvas.width=this.width,this._canvas.height=this.height),this.ctx2d=this._canvas.getContext("2d"),this._image=this._canvas);return}try{let r=e.ctx;this.texCoordBuffer=this.createBuffer(mS),this.positionBuffer=this.createBuffer(hS),t.createTexture!==!1&&(this.texture=r.createTexture(),this.useTexture(),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.pixelStorei(r.UNPACK_ALIGNMENT,1)),t.useFbo&&(this.fbo=r.createFramebuffer(),this.useBufferFrame(),this.useTexture(),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,this.width,this.height,0,r.RGBA,r.UNSIGNED_BYTE,null),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,this.texture,0)),t.useDefaultProgram?this.program=e.defaultProgam:(t.vertexShaderSource||t.fragmentShaderSource)&&(this.vertexShader=t.vertexShaderSource?e.createShader(r.VERTEX_SHADER,t.vertexShaderSource):e.defaultVShader,this.fragmentShader=t.fragmentShaderSource?e.createShader(r.FRAGMENT_SHADER,t.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(r){this.context.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${r.message||r}`}))}}get image(){return this._image}set image(e){this._image=e}createFramebuffer(e){let t=this.context.ctx,r=t.createFramebuffer();return t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0),r}connect(e,...t){return e.addInput(this,...t),this.output=e,e}addInput(e,...t){this.input=e,this.matchInputSize&&e.width&&e.height&&this.resize(e.width,e.height)}requestFrame(e){let t=Date.now();if(this.context instanceof He&&this.render(e)||this.context instanceof Xe&&this.render2d(e))this.totalFrames++;else return!1;return this.cost=Date.now()-t,!0}render2d(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?this.draw2d(this.input.image,0,0,this.width,this.height):!1}update(e=0){var t;(t=this.output)==null||t.update(e)}disconnect(...e){var t;(t=this.output)==null||t.removeInput(this,...e),delete this.output}removeInput(e,...t){delete this.input}close(){var e,t;if(this.context.off("disconnect",this.close,this),(e=this.output)==null||e.removeInput(this),delete this.output,(t=this.input)==null||t.disconnect(),this.context instanceof He){let r=this.context.ctx;r.deleteBuffer(this.texCoordBuffer),r.deleteBuffer(this.positionBuffer),this.fbo&&r.deleteFramebuffer(this.fbo),this.texture&&r.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&r.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&r.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&r.deleteProgram(this.program)}this._canvas&&(this._canvas.width=0,this._canvas.height=0,this.ctx2d=null),this.removeAllListeners()}useTexture(){this.useTextures(this.texture)}useInputTexture(){var e;this.useTextures((e=this.input)==null?void 0:e.texture)}useTextures(...e){let t=this.context.ctx;e.forEach((r,s)=>{r&&(t.activeTexture(t.TEXTURE0+s),t.bindTexture(t.TEXTURE_2D,r))})}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}createBuffer(e){let t=this.context.ctx,r=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,r),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW),r}setTexBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}setPosBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}changeBufferData(e,t){let r=this.context.ctx;r.bindBuffer(r.ARRAY_BUFFER,e),r.bufferData(r.ARRAY_BUFFER,new Float32Array(t),r.STATIC_DRAW)}setAttributes(...e){let t=this.context.ctx;e.forEach((r,s)=>{t.enableVertexAttribArray(s),t.bindBuffer(t.ARRAY_BUFFER,r),t.vertexAttribPointer(s,2,t.FLOAT,!1,0,0)})}getVertexPoint(e,t){return[e/this.width*2-1,t/this.height*2-1]}layout2texCoords(e){return[...this.getVertexPoint(e.x,e.y),...this.getVertexPoint(e.x+e.width,e.y),...this.getVertexPoint(e.x,e.y+e.height),...this.getVertexPoint(e.x+e.width,e.y+e.height)]}resize(e,t){if(!(this.width===e&&this.height===t)){if(this.width=e,this.height=t,this._canvas&&(this._canvas.width=e,this._canvas.height=t),this.texture&&this.fbo){this.useTexture();let r=this.context.ctx;r.texImage2D(r.TEXTURE_2D,0,r.RGBA,e,t,0,r.RGBA,r.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(e,t)}}draw(e,t){this.setAttributes(e||this.positionBuffer,t||this.texCoordBuffer);let r=this.context.ctx;r.drawArrays(r.TRIANGLE_STRIP,0,4)}draw2d(e,t,r,s,n,a,c,l,u){let h=!T(a)&&!T(c)&&!T(l)&&!T(u);return this.ctx2d&&e?(e instanceof ImageData?(h?this.ctx2d.putImageData(e,t,r,a,c,l,u):this.ctx2d.putImageData(e,t,r),this.emit(kr.RENDER,this.ctx2d.canvas)):(h?this.ctx2d.drawImage(e,a,c,l,u,t,r,s,n):this.ctx2d.drawImage(e,t,r,s,n),this.emit(kr.RENDER,e)),typeof VideoFrame!="undefined"&&e instanceof VideoFrame&&e.close(),!0):!1}drawBackGround2d(e){this.ctx2d&&(this.ctx2d.save(),this.ctx2d.fillStyle=e,this.ctx2d.fillRect(0,0,this.width,this.height),this.ctx2d.restore())}getInfo(){var h;let{totalFrames:e,x:t,y:r,width:s,height:n,name:a,cost:c}=this,l=Date.now(),u=(e-this.lastInfo.totalFrames)/((l-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:r,width:s,height:n,timestamp:l,fps:u,name:a,cost:c},O({parent:(h=this.input)==null?void 0:h.getInfo()},this.lastInfo)}createTexture(e){let t=this.context.ctx,r=t.createTexture();return this.useTextures(r),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.pixelStorei(t.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),r}};d(kr,"RENDER","render"),M([ye(J.INIT,"connected",{sync:!0})],kr.prototype,"connect",1),M([ye("connected",J.INIT,{ignoreError:!0,sync:!0})],kr.prototype,"disconnect",1),M([ye([],"closed",{sync:!0})],kr.prototype,"close",1);var Ue=kr;var pS=de(Vu(250),Fn(()=>performance.now()),rr());var _f=o=>i=>{let e=performance.now();de(pS,Hc(t=>t-e<o),or(1))(i)};var _S=[0,1,1,1,0,0,1,0],fo=class extends Ue{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t));d(this,"_intervalId",0);d(this,"_sequence",0);d(this,"checkGLError",!1);d(this,"checkVisibilityChange");e instanceof Xe?this.ctx2d=e.ctx||null:e.available&&(t!=null&&t.mirrorUpAndDown)&&this.setTexBuffer(_S)}start(e){this.log.info(`${this.name} start render ${e} fps`),oe.clearTask(this._intervalId),this._intervalId=oe.run("intervalInWorker",()=>{if(e!==this.context.frameRate&&(oe.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof He){let r=this.context.ctx.getError();r&&this.context.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:5,message:`${this.name} req ${this._sequence} render ${this.totalFrames} faild ${r}`}))}},{fps:this.context.frameRate})}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),this.emit(Ue.RENDER,this.context._canvas),!0):!1}addInput(e,...t){super.addInput(e,...t),this.start(this.context.frameRate)}update(e=0){this.state!=="closed"&&(this._intervalId&&(oe.clearTask(this._intervalId),this._intervalId=0,e===1&&(this.log.info(`${this.name} use requestVideoFrameCallback`),this.checkVisibilityChange=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info(`${this.name} use timer`),document.removeEventListener("visibilitychange",this.checkVisibilityChange))},document.addEventListener("visibilitychange",this.checkVisibilityChange))),this.requestFrame(this._sequence++))}removeInput(e){super.removeInput(e),oe.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}close(){super.close(),oe.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},fs=class extends fo{constructor(e,t){super(e,t);d(this,"_videoTrack");d(this,"_muteOb");d(this,"_closedOb",ce(this,"closed"));d(this,"_subscription");d(this,"_canvasContainer");Number(Xi)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e.canvas.captureStream().getVideoTracks(),this._muteOb=ce(this._videoTrack,"mute"),de(ce(this._videoTrack,"ended"),ke(this._closedOb),Te(()=>{this.context.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){this._subscription=de(this._muteOb,ke(this._closedOb),mo(_f(5e3)),$t(()=>{var e;return!!((e=this._videoTrack)!=null&&e.muted)&&!document.hidden}),Te(()=>{this.context.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:7,message:"video track muted"}))}))}disableCheckMute(){var e;(e=this._subscription)==null||e.dispose()}get videoTrack(){return this._videoTrack}putCanvasIntoDom(){!this.context._canvas||!this._canvasContainer||document.getElementById(this.context._canvas.id)||(this.log.info(`${this.name} put canvas to body`),document.body.appendChild(this._canvasContainer),this._canvasContainer.appendChild(this.context._canvas))}render(e){return this.putCanvasIntoDom(),super.render(e)}render2d(e){return this.putCanvasIntoDom(),super.render2d(e)}close(){var e,t;super.close(),(e=this._videoTrack)==null||e.stop(),delete this._videoTrack,(t=this._canvasContainer)==null||t.remove()}},Yc=class extends fs{render(i){var t;let e=!!((t=this.input)!=null&&t.requestFrame(i));if(this.context._canvas2d){let r=this.context._canvas2d.getContext("2d");r.clearRect(0,0,this.context._canvas2d.width,this.context._canvas2d.height),r.drawImage(this.context._canvas,0,0,this.context._canvas2d.width,this.context._canvas2d.height)}return e}};var Zc=class extends fs{constructor(e,t,r){super(e,{name:"smallDestination",logger:r});this.resolution=t}resize(e,t){let r,s=e*t,n=this.resolution.width*this.resolution.height;this.log.info(`big res: ${e}*${t} small res: ${this.resolution.width}*${this.resolution.height} `),s>n?r=s/n:(this.log.warn(`Small stream resolution is not smaller than big stream, which is invalid. big: ${e} * ${t} small: ${this.resolution.width} * ${this.resolution.height}`),r=s/(160*120)),super.resize(e/Math.sqrt(r),t/Math.sqrt(r))}};var $n=class extends Ue{constructor(e,t){super(e,O({name:"imageSource"},t));d(this,"_lastImage");d(this,"_totalFrames",0);d(this,"_autoResize",!1);d(this,"_canvasRendered");d(this,"videoCallbackId",0);d(this,"waitingFirstFrame",!0);d(this,"shouldUpdate",!0);this._autoResize=(t==null?void 0:t.autoResize)!==!1,et===16&&(this._canvasRendered=ot(),de(this._canvasRendered,xn(this._image),Mr(r=>r instanceof HTMLCanvasElement?ce(r,"rendered"):Vn()),ke(ce(this,"closed")),Te(()=>{this.update()})))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){if(!this.shouldUpdate)return;let e=this.image;this.videoCallbackId&&e.cancelVideoFrameCallback(this.videoCallbackId),Ki()&&!document.hidden&&(this.videoCallbackId=e.requestVideoFrameCallback((t,r)=>{this.waitingFirstFrame&&this.onFirstFrame(),document.hidden||(this._totalFrames=r.presentedFrames,this.update(1))}))}_render(e,t){var a;let{width:r,height:s}=this,{image:n}=this;if(n instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(),{videoWidth:r,videoHeight:s}=n,!r||!s)return!1;n.width=r,n.height=s}else if(n instanceof HTMLImageElement||n instanceof ImageData||n instanceof ImageBitmap){if({width:r,height:s}=n,n!==this._lastImage)this._lastImage=n;else if(r===this.width&&s===this.height)return!0}else n instanceof HTMLCanvasElement||n instanceof OffscreenCanvas?({width:r,height:s}=n,this._lastImage=n):typeof VideoFrame!="undefined"&&n instanceof VideoFrame&&({displayWidth:r,displayHeight:s}=n,(a=this._lastImage)==null||a.close(),this._lastImage=n);if(!this._autoResize)return!0;if(this.width===r&&this.height===s&&this.totalFrames){if(t){this.useTexture();let c=this.context.ctx;c.texSubImage2D(c.TEXTURE_2D,0,0,0,c.RGBA,c.UNSIGNED_BYTE,n)}}else{if(t){this.useTexture();let c=this.context.ctx;c.texImage2D(c.TEXTURE_2D,0,c.RGBA,c.RGBA,c.UNSIGNED_BYTE,n)}this.resize(r,s)}return!0}get image(){return this._image}set image(e){var t;(t=this._canvasRendered)==null||t.next(e),this._image=e}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},Wn=class extends $n{constructor(e,t,r){super(e,r);this._player=t;this.name="videoPlayerSource",de(ce(this._player,ue.PLAYER_STATE_CHANGED),ke(ce(this,"closed")),$t(({state:s})=>s==="PLAYING"),Te(()=>{this.tryVideoFrameCallback()}))}get image(){return this._player.element}},Wt=class extends Wn{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(i,e,t){super(i,new it({id:t.name,track:e,muted:!0,container:null,objectFit:"contain",log:t.logger}),t),this.name="videoTrackSource",this._player.play()}replaceTrack(i){this.waitingFirstFrame=!0,this._player.setTrack(i),this._player.play()}close(){super.close(),this._player.stop()}},Kc=class extends Ue{constructor(e,t,r){super(e,L(O({name:"textSource"},r),{create2d:!0}));d(this,"hasChange",!0);d(this,"content","");this.ctx2d.textBaseline="top",this.content=t.content||"",t.font&&(this.font=t.font),t.color&&(this.color=t.color)}set font(e){this.ctx2d&&(this.ctx2d.font=e,this.hasChange=!0)}get font(){var e;return((e=this.ctx2d)==null?void 0:e.font)||""}set color(e){this.ctx2d&&(this.ctx2d.fillStyle=e,this.hasChange=!0)}get color(){var e;return((e=this.ctx2d)==null?void 0:e.fillStyle)||""}render2d(e){return this.ctx2d&&this.hasChange?(this.ctx2d.clearRect(0,0,this.width,this.height),this.drawMultilineText(0,0),this.hasChange=!1,!0):!1}render(e){return!1}resize(e,t){if(!this.ctx2d)return;let{color:r,font:s}=this;super.resize(e,t),this.color=r,this.font=s}drawMultilineText(e=0,t=0,r=1.2){if(!this.ctx2d)return;let s=this.ctx2d.measureText(this.content);t+=s.fontBoundingBoxAscent||s.actualBoundingBoxAscent||0;let n=this.font.match(/(\d+)px/),c=(n?parseInt(n[1],10):16)*r,l=this.content.split(`
|
|
34
34
|
`);for(let u=0;u<l.length;u++)this.ctx2d.fillText(l[u],e,t+u*c)}};var TS=`
|
|
35
35
|
// \u9876\u70B9\u7740\u8272\u5668
|
|
36
36
|
attribute vec4 a_position;
|
|
@@ -49,7 +49,7 @@ uniform sampler2D u_texture;
|
|
|
49
49
|
|
|
50
50
|
void main() {
|
|
51
51
|
gl_FragColor = texture2D(u_texture, v_texCoord);
|
|
52
|
-
} `;var _o=class extends J{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}get canvas(){return this._canvas}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 Wt(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new fs(this,e)}createVideoImageSource(e,t){return new $n(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new Wn(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}createTextSource(e,t){return new Kc(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}};d(_o,"_ids",0);var SS={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},_s=class _s extends _o{constructor(){super(...arguments);d(this,"defaultProgam");d(this,"defaultVShader");d(this,"defaultFShader");d(this,"ctx");d(this,"_canvas2d")}get canvas(){return this._canvas2d||this._canvas}create(e=!1){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${_o._ids++}`),e&&(this._canvas2d=document.createElement("canvas")),this.ctx=this._canvas.getContext("webgl2",SS),!this.ctx)throw new D({code:I.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,TS),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,ES),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})}destroy(e){let t="";return e&&(t=e.message,this.error=e,v.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,this._canvas2d&&(this._canvas2d.width=e)}set height(e){var t;(t=this.ctx)==null||t.viewport(0,0,this.width,e),super.height=e,this._canvas2d&&(this._canvas2d.height=e)}setSize(e,t){var r;(r=this.ctx)==null||r.viewport(0,0,e,t),super.setSize(e,t),this._canvas2d&&(this._canvas2d.width=e,this._canvas2d.height=t)}createShader(e,t){let r=this.ctx,s=r.createShader(e);return r.shaderSource(s,t),r.compileShader(s),s}createProgram(e,t){let r=this.ctx,s=r.createProgram();return r.attachShader(s,e),r.attachShader(s,t),r.linkProgram(s),r.getProgramParameter(s,r.LINK_STATUS)||this.log.error(r.getProgramInfoLog(s)),s}};d(_s,"UNAVAILABLE","unavailable"),M([ye(J.INIT,"created",{sync:!0,fail(e){this.log.error("video gl context create failed",e.cause),v.addFailedEvent({key:512700,error:e.cause||e})},success(){this.log.info("video context created use webgl"),v.addSuccessEvent({key:512700})}})],_s.prototype,"create",1),M([ye("created",J.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(_s.UNAVAILABLE,e),this.removeAllListeners()}})],_s.prototype,"destroy",1);var He=_s,Xe=class extends _o{constructor(){super(...arguments);d(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${_o._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:e.alpha,willReadFrequently:e.willReadFrequently}),!this.ctx)throw new D({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,v.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(),v.addSuccessEvent({key:512703})}};M([ye(J.INIT,"created",{sync:!0,fail(e){this.log.error("video 2d context create failed",e.cause),v.addFailedEvent({key:512701,error:e.cause||e})},success(){this.log.info("video context created use 2d"),v.addSuccessEvent({key:512701})}})],Xe.prototype,"create",1),M([ye("created",J.INIT,{ignoreError:!0,sync:!0})],Xe.prototype,"destroy",1);function IS(o,i,e,t,r,s=!1){s&&([e,t]=[t,e]);let n={sWidth:o,sHeight:i,dWidth:e,dHeight:t,sx:0,sy:0,dx:0,dy:0};if(o===0||i===0)return n;switch(r){case void 0:case"fill":break;case"contain":{let a=Math.min(e/o,t/i);n.dWidth=o*a,n.dHeight=i*a,n.dx=(e-n.dWidth)/2,n.dy=(t-n.dHeight)/2;break}case"cover":{let a=Math.max(e/o,t/i),c=e/a,l=t/a;n.sx=(o-c)/2,n.sy=(i-l)/2,n.sWidth=c,n.sHeight=l;break}}return n}var Ih=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}get fillMode(){return this.layout.fillMode}get rotation(){return this.layout.rotation}get hidden(){return!!this.layout.hidden}},gs=class extends Ue{constructor(e,t){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:t});d(this,"inputs",[]);d(this,"backgroundColor","black")}addInput(e,t){let r=0,s=this.inputs.length;for(;r<s;){let a=Math.floor((r+s)/2);if(this.inputs[a].layout.zIndex<t.zIndex)r=a+1;else if(this.inputs[a].layout.zIndex>t.zIndex)s=a;else throw new Error(`input already exists at zIndex ${t.zIndex}`)}let n=new Ih(e,t);this.inputs.splice(r,0,n)}changeInputLayout(e,t){let r=this.inputs.findIndex(g=>g.node===e);if(r<0)return;let{x:s,y:n,width:a,height:c,zIndex:l,fillMode:u,rotation:h,hidden:m}=t;if(!T(l)&&this.inputs.some(g=>g.layout.zIndex===l&&g.node!==e))throw new Error(`input already exists at zIndex ${t.zIndex}`);let _=this.inputs[r];T(s)||(_.layout.x=s),T(n)||(_.layout.y=n),T(a)||(_.layout.width=a),T(c)||(_.layout.height=c),T(h)||(_.layout.rotation=h),T(m)||(_.layout.hidden=m),u&&(_.layout.fillMode=u),!T(l)&&l!==_.layout.zIndex&&(_.layout.zIndex=l,this.inputs.sort((g,E)=>g.layout.zIndex-E.layout.zIndex))}hasInput(e){return this.inputs.some(t=>t.node===e)}hasNoInput(){return this.inputs.length===0}resize(e,t){if(!this.matchInputSize){super.resize(e,t);return}let r=this.inputs.reduce((s,n)=>n?Object.assign(s,{width:Math.max(s.width,n.right),height:Math.max(s.height,n.bottom)}):s,{width:0,height:0});super.resize(r.width,r.height),this.context instanceof He&&this.inputs.forEach(s=>{if(s){let n=this.layout2texCoords(s);s.positionBuffer?this.changeBufferData(s.positionBuffer,n):s.positionBuffer=this.createBuffer(n)}})}connect(e,...t){return super.connect(e,...t),this.drawBackGround2d(this.backgroundColor),this.matchInputSize&&this.resize(0,0),e}removeInput(e){this.inputs=this.inputs.filter(t=>t.node!==e),this.inputs.length===0&&this.drawBackGround2d(this.backgroundColor)}render(e){let t=this.context.ctx;if(t.clearColor(0,0,0,0),this.inputs.reduce((s,n)=>n.node.requestFrame(e)||s,!1)&&t){this.useProgram(),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let s=0;s<this.inputs.length;s++){let n=this.inputs[s];n&&(n.node.useTexture(),this.draw(n.positionBuffer))}return!0}return!1}render2d(e){if(this.inputs.forEach(t=>t.node.requestFrame(e)),this.ctx2d){this.drawBackGround2d(this.backgroundColor);for(let t=0;t<this.inputs.length;t++){let r=this.inputs[t];if(r.hidden)continue;let s=IS(r.node.width,r.node.height,r.width,r.height,r.fillMode,bt(r.rotation));this.draw2d(r.node.image,r.x+s.dx,r.y+s.dy,s.dWidth,s.dHeight,s.sx,s.sy,s.sWidth,s.sHeight)}return!0}return!1}debugLayout(e,t,r,s,n=!1){this.ctx2d&&(n&&([r,s]=[s,r]),this.ctx2d.save(),this.ctx2d.strokeStyle="red",this.ctx2d.lineWidth=2,this.ctx2d.strokeRect(e,t,r,s),this.ctx2d.restore())}getInfo(){let{totalFrames:e,x:t,y:r,width:s,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:s,height:n,timestamp:c,fps:l,name:a},O({parent:this.inputs.filter(u=>u).map(u=>u.node.getInfo())},this.lastInfo)}removeAllInputs(){this.inputs.forEach(e=>{var t;if(e.node.disconnect(),e.positionBuffer&&this.context instanceof He)try{(t=this.context.ctx)==null||t.deleteBuffer(e.positionBuffer)}catch(r){}})}close(){super.close(),this.removeAllInputs()}};var AS=[1,0,0,0,1,1,0,1],Gt=class extends Ue{constructor(e,t,r,s){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),s&&(this.rotation=s),e instanceof He)try{this.setTexBuffer(AS)}catch(n){e.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${n.message||n}`}))}}draw2d(e,t,r,s,n){if(this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height),this.ctx2d.save(),this.mirror&&(this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0)),this.rotation===90?(this.ctx2d.translate(s,0),this.ctx2d.rotate(Math.PI/2),this.ctx2d.scale(n/s,s/n)):this.rotation===180?(this.ctx2d.translate(this.width,this.height),this.ctx2d.rotate(Math.PI)):this.rotation===270&&(this.ctx2d.translate(0,n),this.ctx2d.rotate(3*Math.PI/2),this.ctx2d.scale(n/s,s/n));let a=super.draw2d(e,t,r,s,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}resize(e,t){bt(this.rotation)&&([e,t]=[t,e]),super.resize(e,t)}};var go=class extends pi{constructor(e,t=4){super(t,it);d(this,"inputLocalVideoTracks",new Map);d(this,"inputLocalScreenTracks",new Map);d(this,"cameraNodeMap",new Map);d(this,"screenNodeMap",new Map);d(this,"textNodeMap",new Map);d(this,"imageNodeMap",new Map);d(this,"videoNodeMap",new Map);d(this,"endedIds",new Set);d(this,"videoContext");d(this,"mixNode");d(this,"destination");d(this,"manager");d(this,"stat");d(this,"_checkId",0);d(this,"autoSetFps",!0);this.manager=e,this.log.id+="mix",this.create2dVideoContext(),this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log}),this.destination.on(Ue.RENDER,r=>{this.emit("render",r)}),this.mixNode=new gs(this.videoContext,this.log),this.mixNode.matchInputSize=!1}listenDeviceChange(){throw new Error("Method not implemented.")}enablePrintDetail(e=2e3){this._checkId=oe.run("interval",()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:e})}create2dVideoContext(){this.videoContext?this.videoContext.destroy():this.videoContext=new Xe({frameRate:15,logger:this.log,name:"mix-ctx"}),this.videoContext.create({alpha:!1})}setFps(e){this.autoSetFps=!1,this.videoContext.frameRate=e;for(let t of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])t.shouldUpdate=!1;setTimeout(()=>{var t;return(t=this.destination)==null?void 0:t.start(this.videoContext.frameRate)},500)}setFpsAuto(){var s;if(!this.autoSetFps)return;for(let n of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])n.shouldUpdate=!1;let e=null,t=0,r=!0;for(let[n,a]of this.inputLocalVideoTracks)if(a.profile.frameRate>t){if(this.endedIds.has(n)){let c=this.cameraNodeMap.get(n);c&&c.image.cancelVideoFrameCallback(c.videoCallbackId);continue}t=a.profile.frameRate,e=n}for(let[n,a]of this.inputLocalScreenTracks)if(a.profile.frameRate>t){if(this.endedIds.has(n)){let c=this.screenNodeMap.get(n);c&&c.image.cancelVideoFrameCallback(c.videoCallbackId);continue}t=a.profile.frameRate,e=n,r=!1}if(e!==null){let n=r?this.cameraNodeMap.get(e):this.screenNodeMap.get(e);n&&(n.shouldUpdate=!0,n.tryVideoFrameCallback()),this.log.info("set mix fps: ",t)}else(s=this.destination)==null||s.start(this.videoContext.frameRate),this.log.info("fallback to timer, fps: ",this.videoContext.frameRate)}setMixBackground(e){this.mixNode&&(this.mixNode.backgroundColor=e)}resizeMixCanvas(e,t){var r;(r=this.mixNode)==null||r.resize(e,t)}startMix(){return p(this,null,function*(){var e;if(!this.mixNode||!this.destination)throw new Error("can't mix without necessary conditions");this.mixNode.disconnect(),this.mixNode.connect(this.destination),Ft&&this.player.setCanvas(this.videoContext._canvas),this.setOutputMediaStreamTrack(this.destination.videoTrack),(e=this.manager)==null||e.changeInput(this)})}addCameraSource(e,t,r){if(this.inputLocalVideoTracks.has(e)||this.cameraNodeMap.has(e))throw new Error(`There is already a cameraSource with the same ID: ${e}`);let{mediaTrack:s}=t;if(!s)throw new Error("no mediaTrack, add cameraSource failed");t.recaptureMode=1,tt(this,be).add("videoInputRemoved",a=>{a.deviceId===t.deviceId&&(this.endedIds.add(e),this.setFpsAuto())}),t.on("output-media-track-changed",()=>{this.endedIds.delete(e),this.updateCameraSource(e,r,t.mediaTrack)});let n;et===16&&s instanceof CanvasCaptureMediaStreamTrack?n=this.videoContext.createVideoImageSource(s.canvas,{name:"cameraCanvasSource",logger:this.log}):n=this.videoContext.createVideoTrackSource(s,"cameraNodeSource"),n.resize(t.settings.width,t.settings.height),n.shouldUpdate=!1,this._connectMix(n,r,"cover"),this.inputLocalVideoTracks.set(e,t),this.cameraNodeMap.set(e,n),this.setFpsAuto()}addScreenSource(e,t,r){if(this.inputLocalScreenTracks.has(e)||this.screenNodeMap.has(e))throw new Error(`There is already a screenSource with the same ID: ${e}`);let{mediaTrack:s}=t;if(!s)throw new Error("no mediaTrack, add cameraSource failed");let n=this.videoContext.createVideoTrackSource(s,"screenNodeSource");n.resize(t.settings.width,t.settings.height),n.shouldUpdate=!1,this._connectMix(n,r),this.inputLocalScreenTracks.set(e,t),this.screenNodeMap.set(e,n),this.setFpsAuto()}addTextSource(e){let{id:t,content:r="",font:s,color:n,layout:a}=e;if(this.textNodeMap.has(t))throw new Error(`There is already a textSource with the same ID: ${t}`);let c=this.videoContext.createTextSource({content:r,font:s,color:n});c.resize(a.width,a.height),this._connectMix(c,a),this.textNodeMap.set(t,c)}addImageSource(e,t,r){if(this.imageNodeMap.has(e))throw new Error(`There is already a imageSource with the same ID: ${e}`);let s=this.videoContext.createVideoImageSource(t,{autoResize:!1,logger:this.log});s.resize(t.width,t.height),this._connectMix(s,r),this.imageNodeMap.set(e,s)}addVideoSource(e,t,r){if(this.videoNodeMap.has(e))throw new Error(`There is already a videoSource with the same ID: ${e}`);let s=this.videoContext.createVideoImageSource(t,{autoResize:!1,logger:this.log});s.resize(t.videoWidth,t.videoHeight),s.shouldUpdate=!1,this._connectMix(s,r),this.videoNodeMap.set(e,s)}updateCameraSource(e,t,r=null,s){let n=this.cameraNodeMap.get(e);if(n){if(r){if(et===16&&r instanceof CanvasCaptureMediaStreamTrack)if(n instanceof Wt){let l=n.output;n.close(),n=this.videoContext.createVideoImageSource(r.canvas,{name:"cameraCanvasSource",logger:this.log}),n.connect(l),this.cameraNodeMap.set(e,n)}else n.image=r.canvas;else if(n instanceof Wt)n.replaceTrack(r);else{let l=n.output;n.close(),n=this.videoContext.createVideoTrackSource(r,"cameraNodeSource"),n.connect(l),this.cameraNodeMap.set(e,n)}let{width:a,height:c}=r.getSettings();a&&c&&n.resize(a,c)}s&&n.resize(s.width,s.height),(s||r)&&this.setFpsAuto(),this._changeMixLayout(n,t)}}updateScreenSource(e,t){let r=this.screenNodeMap.get(e);r&&this._changeMixLayout(r,t)}updateTextSource(e){let{id:t,content:r,font:s,color:n,layout:a}=e,c=this.textNodeMap.get(t);c&&(T(r)||(c.content=r),T(s)||(c.font=s),T(n)||(c.color=n),c.resize(a.width,a.height),this._changeMixLayout(c,a))}updateImageSource(e,t,r){let s=this.imageNodeMap.get(e);s&&(r&&(s.image=r,s.resize(r.width,r.height)),this._changeMixLayout(s,t))}updateVideoSource(e,t,r){let s=this.videoNodeMap.get(e);if(s){if(r){let n=s.image;n instanceof HTMLVideoElement&&this.stopVideoElement(n),s.image=r,s.resize(r.videoWidth,r.videoHeight)}this._changeMixLayout(s,t)}}_connectMix(e,t,r="contain"){if(!this.mixNode)return;let{mirror:s,rotation:n}=t;e.disconnect();let a=new Gt(this.videoContext,this.log,s,n);a=e.connect(a),t.fillMode||(t.fillMode=r),a.connect(this.mixNode,t)}_changeMixLayout(e,t){if(!this.mixNode)return;let{mirror:r,rotation:s}=t,n=e.output||e;n instanceof Gt&&(T(r)||(n.mirror=r),T(s)||(n.rotation=s),n.resize(e.width,e.height)),this.mixNode.changeInputLayout(n,t)}removeCameraSource(e){let t=this.inputLocalVideoTracks.get(e);if(!t)return;t.close(),this.inputLocalVideoTracks.delete(e);let r=this.cameraNodeMap.get(e);r&&(r.output instanceof Gt&&r.output.close(),r.close(),this.cameraNodeMap.delete(e)),this.checkAfterRemove(!0)}removeScreenSource(e){let t=this.inputLocalScreenTracks.get(e);if(!t)return;t.close(),this.inputLocalScreenTracks.delete(e);let r=this.screenNodeMap.get(e);r&&(r.output instanceof Gt&&r.output.close(),r.close(),this.screenNodeMap.delete(e)),this.checkAfterRemove(!0)}removeTextSource(e){let t=this.textNodeMap.get(e);t&&(t.output instanceof Gt&&t.output.close(),t.close(),this.textNodeMap.delete(e)),this.checkAfterRemove()}removeImageSource(e){let t=this.imageNodeMap.get(e);t&&(t.output instanceof Gt&&t.output.close(),t.close(),this.imageNodeMap.delete(e)),this.checkAfterRemove()}removeVideoSource(e){let t=this.videoNodeMap.get(e);t&&(t.output instanceof Gt&&t.output.close(),t.image instanceof HTMLVideoElement&&this.stopVideoElement(t.image),t.close(),this.videoNodeMap.delete(e)),this.checkAfterRemove()}checkAfterRemove(e=!1){e&&this.setFpsAuto()}stopVideoElement(e){e.pause(),e.src="",e.srcObject=null,e.remove()}close(){var e;super.close(),oe.clearTask(this._checkId),(e=this.videoContext)==null||e.destroy(),delete this.mixNode,delete this.destination;for(let t of[...this.inputLocalVideoTracks.values(),...this.inputLocalScreenTracks.values()])t.close();this.inputLocalVideoTracks.clear(),this.inputLocalScreenTracks.clear(),this.cameraNodeMap.clear(),this.screenNodeMap.clear(),this.textNodeMap.clear(),this.imageNodeMap.clear(),Le(this);for(let t of this.videoNodeMap.values())t.image instanceof HTMLVideoElement&&this.stopVideoElement(t.image);this.videoNodeMap.clear(),this.log.info("localMixVideoTrack close, stop mix")}};var ed=cn();if(typeof navigator!="undefined"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:ed,exposeOrigin:!0,permittedOrigins:["*"]})}catch(o){}var CS=function(o){return p(this,null,function*(){let i=null,e=bS(o);R.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let t=yield navigator.mediaDevices.getDisplayMedia(e);o.systemAudio&&t.getAudioTracks().length===0&&(Zo&&We<74||Re||K)&&R.warn("Your browser not support capture system audio");let r=t.getVideoTracks()[0];if(r){if(o.frameRate)try{yield r.applyConstraints({frameRate:{min:o.frameRate,ideal:o.frameRate},width:o.width,height:o.height})}catch(s){R.warn(`screen applyConstraints failed: ${s}`)}o.captureElement&&(yield RS(r,o.captureElement))}if(o.audio){let s=yS(o);R.info(`getUserMedia with constraints: ${JSON.stringify(s)}`),i=yield navigator.mediaDevices.getUserMedia(s),t.addTrack(i.getAudioTracks()[0])}return t})};function RS(o,i){return p(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&le(o.cropTo))try{if(!(((e=o.getCaptureHandle())==null?void 0:e.handle)===ed))return;let r=yield CropTarget.fromElement(i);yield o.cropTo(r)}catch(t){R.warn(`cropTo target failed ${t}`)}})}function yS(o){let i={echoCancellation:o.echoCancellation,autoGainControl:o.autoGainControl,noiseSuppression:o.noiseSuppression,sampleRate:o.sampleRate,channelCount:o.channelCount};return T(o.microphoneId)||(i.deviceId=o.microphoneId),{audio:i,video:!1}}function bS(o){let i={preferCurrentTab:o.preferDisplaySurface==="current-tab"||!!o.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:Re?{max:o.width}:{ideal:o.width,max:o.width},height:Re?{max:o.height}:{ideal:o.height,max:o.height},frameRate:o.frameRate,displaySurface:o.preferDisplaySurface||"monitor"};if(i.video=e,o.systemAudio){let{echoCancellation:t=!0,noiseSuppression:r=!1,autoGainControl:s=!1}=o;i.audio={echoCancellation:t,noiseSuppression:r,autoGainControl:s,sampleRate:48e3}}return i}var gf=CS;var Pt=class extends je{constructor(e){super(e,2);d(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600});d(this,"objectFit","contain");d(this,"isScreen",!0);this._log.id=`s-${this._log.id}`}get isShareCurrentTab(){var e,t;try{return ed===((t=(e=this.mediaTrack)==null?void 0:e.getCaptureHandle())==null?void 0:t.handle)}catch(r){return}}capture(u){return p(this,arguments,function*({systemAudio:e=!1,autoGainControl:t,echoCancellation:r,noiseSuppression:s,audioTrack:n,videoTrack:a,captureElement:c,preferDisplaySurface:l}){try{let h;return a||n?(h=new MediaStream,a&&h.addTrack(a),n&&h.addTrack(n)):(h=yield gf({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:t,echoCancellation:r,noiseSuppression:s,captureElement:c,preferDisplaySurface:l}),this.sourceTrack=h.getVideoTracks()[0]),yield this.setInputMediaStreamTrack(h.getVideoTracks()[0]),h}catch(h){throw this.log.error(`getDisplayMedia error observed ${h}`),h instanceof D?h:new D({code:I.INITIALIZE_FAILED,name:h.name,message:h.message})}})}switchDevice(e){return p(this,null,function*(){throw new Error("Method not implemented.")})}};M([Ct(function(e){this.setContentHint(e.contentHint||"detail")})],Pt.prototype,"capture",1);var To=class extends kt{constructor(i){super(i),this._log.id=`s-${this._log.id}`,this.isScreen=!0}addAudioProcessor(i,e,t){this.pipeline.silentNode.setNode(t),this.pipeline.mixNode.setNode(e),this.pipeline.aec.setNode(i),this.enableTrackAEC(!1)}removeAudioProcessor(i){this.pipeline.aec.node===i&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode(),this.enableTrackAEC(!0))}};var vS='registerProcessor("dumper",class extends AudioWorkletProcessor{constructor(e){super(),this.sourceSampleRate=e.processorOptions.sourceSampleRate||48e3,this.targetSampleRate=e.processorOptions.targetSampleRate||48e3,this.port.onmessage=e=>{this.port2=e.data.port}}process(e){return(this.port2||this.port).postMessage(this.resampleAll(e,this.sourceSampleRate,this.targetSampleRate)),!0}resampleAll(r,s,a){if(s===a)return r;var o=[];for(let t=0;t<r.length;t++){o[t]=[];for(let e=0;e<r[t].length;e++)o[t][e]=this.resample(r[t][e],s,a)}return o}resample(t,e,r){if(e===r)return t;var s=Math.round(t.length*(this.targetSampleRate/this.sourceSampleRate)),a=new Float32Array(s),o=(t.length-1)/(s-1);a[0]=t[0];for(let e=1;e<s-1;e++){var l=e*o,p=Math.floor(l),h=Math.ceil(l);a[e]=t[p]+(t[h]-t[p])*(l-p)}return a[s-1]=t[t.length-1],a}});',Ah;function Gn(o,i=48e3,e=1,t){return p(this,null,function*(){let r=Ee("dump");Ah||(Ah=tr(r,URL.createObjectURL(new Blob([vS],{type:"application/javascript"})))),yield Ah;let s=r.sampleRate,n=new AudioWorkletNode(r,"dumper",{numberOfInputs:o.length,numberOfOutputs:0,processorOptions:{sourceSampleRate:s,targetSampleRate:i}});return n.channelCountMode="explicit",n.channelCount=e,t&&n.port.postMessage({port:t},[t]),o.forEach((a,c)=>a.connect(n,0,c)),new ReadableStream({start(a){n.port.onmessage=c=>{a.enqueue(c.data)}},cancel(){o.forEach(a=>a.disconnect(n)),n.port.close()}})})}var td=class extends bc{constructor(e){super();this.room=e;d(this,"_localAudioTrack");d(this,"_localScreenAudioTrack");d(this,"log");d(this,"denoiser");d(this,"voiceChanger");d(this,"mixChangedDebounce");d(this,"audioProcessor");d(this,"encodePipeline",[]);d(this,"decodePipeline",[]);d(this,"getPCMAbortCtrlMap",new Map);d(this,"audioFrameEventConfigMap",new Map);d(this,"audioReferenceMap",new Map);d(this,"isLocalAudioNeedAudioProcess",!1);d(this,"isScreenAudioNeedAudioProcess",!1);this.log=R.createLogger({parent:e==null?void 0:e.getLogger(),id:"am",userId:e==null?void 0:e.userId,sdkAppId:e==null?void 0:e.sdkAppId}),this.installEvent()}get localAudioTrack(){return this._localAudioTrack}get _localAudioPipline(){var e;return(e=this._localAudioTrack)==null?void 0:e.pipeline}get _localScreenAudioPipeline(){var e;return(e=this._localScreenAudioTrack)==null?void 0:e.pipeline}dump(e){var u,h;if(!this._localAudioTrack)return;let t=[],r=[];(u=this._localAudioPipline)!=null&&u.source.node&&(t.push(this._localAudioPipline.source.node),r.push("mic")),(h=this._localAudioPipline)!=null&&h.denoiser.node&&(t.push(this._localAudioPipline.denoiser.node),r.push("mic-processed")),this.mixWeight>1&&(t.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),r.push("mix")),this.log.info(`dump audio track ${r}, duration: ${e}`);let s=new AbortController,n=[],a=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),s.abort("timeout")},e*1e3),c=()=>{for(let m=0;m<r.length;m++){let _=URL.createObjectURL(new Blob(n[m])),g=document.createElement("a");g.href=_,g.download=`${r[m]}.pcm`,g.style.display="none",document.body.appendChild(g),g.click(),URL.revokeObjectURL(_),g.remove()}clearTimeout(a),s.abort("download")},l=Gn(t).then(m=>m.pipeTo(new WritableStream({write(_){_.forEach((g,E)=>n[E]=n[E]?n[E].concat(g[0]):[g[0]])}}),s).catch(_=>c));return{then:l.then.bind(l),download:c}}getPCM(e,t){var k,re,P;if(typeof WritableStream=="undefined"){this.log.warn("getPCM failed: browser not support WritableStream");return}let{enable:r,sampleRate:s=48e3,channelCount:n=1,port:a}=(t===""?this.audioFrameEventConfigMap.get(""):this.audioFrameEventConfigMap.get(t)||this.audioFrameEventConfigMap.get("*"))||{};if(!r)return;this.log.info(`getPCM ${t||"local"}`);let c=Math.floor(s*.04),l=new Float32Array(c),u=new Float32Array(c),h,m,_=0,g=new AbortController,E=t===""?(k=this._localAudioTrack)==null?void 0:k.mediaTrack:(P=(re=this.room)==null?void 0:re.remotePublishedUserMap.get(t))==null?void 0:P.remoteAudioTrack.mediaTrack;if(!E){this.log.info(`getPCM failed: ${t||"local"} has no audio track`);return}let C=Ee().createMediaStreamSource(new MediaStream([E]));return Gn([C],s,n,a).then(Qe=>Qe.pipeTo(new WritableStream({write(N){N[0][0]&&(_+N[0][0].length>c?(l.set(N[0][0].subarray(0,c-_),_),h=N[0][0].subarray(c-_),N[0][1]&&(u.set(N[0][1].subarray(0,c-_),_),m=N[0][1].subarray(c-_)),_+=c-_):(h&&(l.set(h,_),_+=h.length,h=void 0),m&&(u.set(m,_),m=void 0),l.set(N[0][0],_),N[0][1]&&u.set(N[0][1],_),_+=N[0][0].length),_>=c&&(_=0,e({userId:t,sampleRate:s,channelCount:n,data:n===1?l:[l,u]}),l=new Float32Array(c),u=new Float32Array(c)))}}),g).catch(N=>this.log.warn(`stop getPCM reason:${N}`))),g}get hasScreenAudioTrack(){return!T(this._localScreenAudioTrack)}get hasAudioTrack(){return!T(this._localAudioTrack)}changeInput(e){var t,r;if(e instanceof To)return this._localScreenAudioTrack=e,this.isScreenAudioNeedAudioProcess&&((t=this.audioProcessor)!=null&&t.screenAudioWorkletNode)&&(e.addAudioProcessor(this.audioProcessor.screenAudioWorkletNode,this.audioProcessor.mixNode,this.audioProcessor.silentNode),this.audioReferenceMap.forEach((s,n)=>{e.mixAudioReference(s,n)})),e.pipeline.connect(),this.mixOnChange();if(e instanceof kt)return this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),this.isLocalAudioNeedAudioProcess&&((r=this.audioProcessor)!=null&&r.localAudioWorkletNode)&&(e.addAudioProcessor(this.audioProcessor.localAudioWorkletNode,this.audioProcessor.mixNode,this.audioProcessor.silentNode),this.audioReferenceMap.forEach((s,n)=>{e.mixAudioReference(s,n)})),e.pipeline.connect(),this.mixOnChange();if(e instanceof gi)return e.setOutputMediaStreamTrack(e.mediaTrack)}mixAudioReference(e,t){var r;(r=this._localAudioTrack)==null||r.mixAudioReference(e,t)}unMixAudioReference(e){var t;(t=this._localAudioTrack)==null||t.unMixAudioReference(e)}setAudioReferenceVolume(e,t){var r;(r=this._localAudioTrack)==null||r.setAudioReferenceVolume(e,t)}mixOnChange(){return this.mixChangedDebounce||(this.mixChangedDebounce=Promise.resolve().then(()=>{var e,t;return delete this.mixChangedDebounce,Promise.all([(e=this._localAudioTrack)==null?void 0:e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),(t=this._localScreenAudioTrack)==null?void 0:t.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)])})),this.mixChangedDebounce}removeInput(e){e instanceof To?delete this._localScreenAudioTrack:e instanceof kt?delete this._localAudioTrack:e instanceof gi}addDenoiser(e){var t;this.denoiser=e,(t=this._localAudioTrack)==null||t.addDenoiser(e)}addAudioProcessor(e,t,r,s){var n;this.audioProcessor={localAudioWorkletNode:r,mixNode:e,silentNode:t,screenAudioWorkletNode:s},this.isLocalAudioNeedAudioProcess&&this._localAudioTrack&&r&&(this._localAudioTrack.addAudioProcessor(r,e,t),this.audioReferenceMap.forEach((a,c)=>{var l;(l=this._localAudioTrack)==null||l.mixAudioReference(a,c)})),this.isScreenAudioNeedAudioProcess&&this._localScreenAudioTrack&&s&&((n=this._localScreenAudioTrack)==null||n.addAudioProcessor(s,e,t),this.audioReferenceMap.forEach((a,c)=>{var l;(l=this._localScreenAudioTrack)==null||l.mixAudioReference(a,c)}))}removeDenoiser(e){var t;return delete this.denoiser,(t=this._localAudioTrack)==null?void 0:t.removeDenoiser(e)}addVoiceChanger(e,t){var r;this.voiceChanger=[e,t],(r=this._localAudioTrack)==null||r.pipeline.voiceChanger.setNode(e,t)}removeVoiceChanger(){var e;delete this.voiceChanger,(e=this._localAudioTrack)==null||e.pipeline.voiceChanger.deleteNode()}removeAudioProcessor(e,t){var r,s;delete this.audioProcessor,(r=this._localAudioTrack)==null||r.removeAudioProcessor(e),(s=this._localScreenAudioTrack)==null||s.removeAudioProcessor(t)}destroy(){this.close(),this.audioReferenceMap.clear(),this.getPCMAbortCtrlMap.forEach(e=>e==null?void 0:e.abort("destroy")),this.getPCMAbortCtrlMap.clear(),this.audioFrameEventConfigMap.clear(),this.uninstallEvent()}addEncodeProcessor({processor:e,type:t}){var r;this.encodePipeline.includes(e)||(this.encodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}addDecodeProcessor({processor:e,type:t}){var r;this.decodePipeline.includes(e)||(this.decodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}handleLocalTrackStarted({room:e,userId:t}){var s;if(e!==this.room||this.getPCMAbortCtrlMap.get(t))return;let r=this.getPCM(n=>{var a;(a=this.room)==null||a.emit("audio-frame",n)},"");this.getPCMAbortCtrlMap.set(t,r),this.getPCMAbortCtrlMap.get(t)&&((s=this._localAudioTrack)==null||s.on("input-media-track-changed",()=>{let n=this.getPCMAbortCtrlMap.get(t);n&&(n.abort("inputMediaTrackChanged"),n=this.getPCM(a=>{var c;(c=this.room)==null||c.emit("audio-frame",a)},""),this.getPCMAbortCtrlMap.set(t,n))}))}handleLocalTrackStopped({room:e,userId:t}){if(e!==this.room)return;let r=this.getPCMAbortCtrlMap.get(t);r&&(r.abort("stopLocalAudio"),this.getPCMAbortCtrlMap.delete(t))}handleRemoteTrackStarted({room:e,userId:t}){if(e===this.room&&!this.getPCMAbortCtrlMap.get(t)){let r=this.room.audioManager.getPCM(s=>{var n;(n=this.room)==null||n.emit("audio-frame",s)},t);this.getPCMAbortCtrlMap.set(t,r)}}handleRemoteTrackStopped({room:e,userId:t}){if(e!==this.room)return;let r=this.getPCMAbortCtrlMap.get(t);r&&(r.abort("stopRemoteAudio"),this.getPCMAbortCtrlMap.delete(t))}installEvent(){S.on("113",this.handleLocalTrackStarted,this),S.on("114",this.handleLocalTrackStopped,this),S.on("115",this.handleRemoteTrackStarted,this),S.on("116",this.handleRemoteTrackStopped,this)}uninstallEvent(){S.off("113",this.handleLocalTrackStarted),S.off("114",this.handleLocalTrackStopped),S.off("115",this.handleRemoteTrackStarted),S.off("116",this.handleRemoteTrackStopped)}updateAudioReference({type:e,audioReference:t,refId:r,volume:s}){if(e==="add"){if(this.audioReferenceMap.get(r)||!t||(this.audioReferenceMap.set(r,t),!this.audioProcessor))return;this.mixAudioReference(t,r)}else if(e==="remove")this.audioReferenceMap.get(r)&&(this.audioReferenceMap.delete(r),this.unMixAudioReference(r));else if(e==="updateVolume"){if(!this.audioProcessor||T(s))return;this.setAudioReferenceVolume(r,s)}}};function Eo(o=30,i=2){return Q((e,t)=>function(...r){return new Promise((s,n)=>{let a=setTimeout(()=>{let c=new D({code:I.API_CALL_TIMEOUT,message:`checkPendingPromise ${t}() timeout ${o}s`});(this.log||this._log||R).warn(c),i===2?n(c):i===1&&s()},o*1e3);this._checkPendingPromiseSet||(this._checkPendingPromiseSet=new Set),this._checkPendingPromiseSet.add(a),e.apply(this,r).then(s,n).finally(()=>{clearTimeout(a),this._checkPendingPromiseSet&&a&&this._checkPendingPromiseSet.delete(a)})})})}function Tf(){return Q((o,i)=>function(...e){return this._checkPendingPromiseSet&&(this._checkPendingPromiseSet.forEach(t=>clearTimeout(t)),this._checkPendingPromiseSet.clear()),o.apply(this,e)})}var Mi=class Mi extends no{constructor(e,t,r){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:r,room:e});this.room=e;this.user=t;d(this,"tinyId");d(this,"isRemote",!0);d(this,"jitterBufferDelay",0);d(this,"availableState");d(this,"remotePublishState");d(this,"_triggerCheckDecodeSubject",ot(ce(this,Mi.STATE_SUBSCRIBE)));d(this,"ignoreUpdatePlayingState");this.tinyId=t.tinyId,this.availableState=new J(`${t.userId}-${this.mediaType}-available`,"remote-track-available"),this.remotePublishState=new J(`${t.userId}-${this.mediaType}-remote-publish`,"remote-track-publish"),de(Ln(ce(this,J.STATECHANGED),ce(this.remotePublishState,J.STATECHANGED)),Fn(()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing)),Te(c=>{this.availableState.state!==(c?J.ON:J.OFF)&&(this.availableState.state=c?J.ON:J.OFF),!(this.isRemotePublished&&this.ignoreUpdatePlayingState)&&this.updatePlayingState(c)}));let s=de(ce(this.player,ue.ERROR),$t(c=>c.code===MediaError.MEDIA_ERR_DECODE)),n=de(Un(5e3),$t(()=>this.ignoreDecodeError||!this.isSubscribed||!this.isPlayCalled||!this.stat.bytesReceived?!1:this.player.isPlaying||(this.kind===f.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)?(this.reportDecodeResult(!0),!1):!0)),a=de(xu(s,n),ke(ce(this,J.INIT)));de(this._triggerCheckDecodeSubject,$t(()=>!this.ignoreDecodeError),mo(a),Te(c=>{this.reportDecodeResult(!1,c)}))}setMute(e){this.isRemotePublished&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.isRemotePublished&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}checkDecodeResult(){this._triggerCheckDecodeSubject.next(!0)}waitHasMediaTrack(){return new Promise(e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)})}get ignoreDecodeError(){var t,r;return(((r=(t=this.room)==null?void 0:t.networkQuality)==null?void 0:r.downlinkNetworkQuality)||0)>3||this.player.isInAutoPlayFailedState}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===Mi.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===J.ON}get isNeedPlay(){return this.isAvailable&&this.isPlayCalled}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}reportDecodeResult(e,t){var s,n;let r=this.kind===f.AUDIO;if(v[e?"addSuccessEvent":"addFailedEvent"]({key:r?504700:514702}),!r){let a=((s=this.room)==null?void 0:s.downlinkVideoCodec.toUpperCase())||"H264";v[e?"addSuccessEvent":"addFailedEvent"]({key:rs[`DECODE_${a}_RESULT`]}),e||this.log.warn(`${(n=this.room)==null?void 0:n.downlinkVideoCodec} decode failed`)}e||(v.addEnum({key:r?504701:514703,value:Zr()}),se.uploadEvent({log:`stat-decode-failed-${this.kind}-${si()||ni()}`,userId:this.room.userId}),this._log.warn(`decode failed: isPlaying: ${this.player.isPlaying} ${this.kind===f.AUDIO?`audioLevel: ${this.getAudioLevel()}`:`framesDecoded: ${this.stat.framesDecoded>0}`}`),this.emit("decode-failed",{error:t}))}updatePlayingState(e){if(this.player.isPlayCalled&&this.player.setTrack(this.playerMediaTrack),this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.isRemotePublished||!this.outMediaTrack)){this.log.info(`abort play, isSubscribed: ${this.isSubscribed} isAvailable: ${this.isRemotePublished} hasTrack: ${!!this.outMediaTrack} `);return}super.updatePlayingState(e)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.remotePublishState.state=this.isRemotePublished?J.ON:J.OFF,this.emit("remote-publish-changed",this.isRemotePublished)}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};d(Mi,"STATE_SUBSCRIBE","subscribe"),M([Eo(5,1)],Mi.prototype,"waitHasMediaTrack",1),M([ye(J.INIT,Mi.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),S.emit(A.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),Rt(521716,!1)],Mi.prototype,"subscribe",1),M([ye(Mi.STATE_SUBSCRIBE,J.INIT,{sync:!0,success(){this.log.info("unsubscribed"),S.emit(A.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],Mi.prototype,"unsubscribe",1);var Ts=Mi;var gi=class extends Ts{constructor(e,t){super(e,t,1);d(this,"volume",0);d(this,"mediaType",1);d(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.audioManager}get dbVolume(){return so.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}onPlayerError(e){this.enableDecodeFrame&&(this._log.warn("use audio decoder"),this.room.enableInsertableStreams())}get enableDecodeFrame(){var e,t;return this.manager?this.manager.decodePipeline.some(r=>r)||((t=(e=this.player.element)==null?void 0:e.error)==null?void 0:t.code)===MediaError.MEDIA_ERR_DECODE&&Ec().AudioDecoder&&hi:!1}get enableDecryptFrame(){return this.manager&&!!this.manager.decodePipeline[0]}decodeFrame(e){if(!this.manager)return e;let t=e;for(let[r,s]of this.manager.decodePipeline.entries()){if(!s)continue;let n={frame:e,track:this};if(r===1&&this.isAvailable&&this.room.role==="audience"&&(n.onAudioFrameNTPTime=({ntp:a,frame:c,hasLeavingTag:l})=>{this.emit("audio-frame-with-ntp",{ntp:a,frame:c,hasLeavingTag:l})}),t=s(n),!t)return}return t}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get isRemotePublished(){return this.user.muteState.audioAvailable}};var id=class extends Ue{constructor(e,t,r,s,n){super(e,{useDefaultProgram:!0,useFbo:!0,name:"alpha",create2d:!0,logger:t});this.setContainer=s;d(this,"initStat",{alphaStitchingType:1});d(this,"end",ot());d(this,"minSize",320);d(this,"maxSize",1280);d(this,"draggable",!1);d(this,"startDragX",0);d(this,"startDragY",0);d(this,"left",0);d(this,"top",0);d(this,"baseWidth",320);d(this,"baseRatio");d(this,"container");this.initStat=n,this.draggable=r,this.bindDragEvents()}bindDragEvents(){let e=this.context._canvas;if(e)if(this.draggable){let t=ke(this.end);de(ce(e,"mousedown"),Bn(this.startDrag.bind(this)),Mr(()=>de(ce(window,"mousemove"),ke(ce(window,"mouseup")))),t,Te(this.doDrag.bind(this))),de(ce(e,"dblclick"),t,Te(this.resetPosition.bind(this))),de(ce(e,"wheel"),t,Te(this.handleZoom.bind(this))),this.renderCanvas()}else{if(!this.container)return;this.container.style.removeProperty("left"),this.container.style.removeProperty("top"),this.end.next()}}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}startDrag(e){e.preventDefault(),e.button===0&&(this.startDragX=e.clientX-this.left,this.startDragY=e.clientY-this.top)}renderCanvas(){let{container:e}=this;e||this.setContainer(),!(!e||!this.baseRatio||!this.draggable)&&(e.style.setProperty("width",`${this.baseWidth}px`),e.style.setProperty("height",`${this.baseWidth/this.baseRatio}px`),e.style.setProperty("position","fixed"),e.style.setProperty("left",`${this.left}px`),e.style.setProperty("top",`${this.top}px`))}doDrag(e){e.preventDefault(),this.left=e.clientX-this.startDragX,this.top=e.clientY-this.startDragY,this.renderCanvas()}handleZoom(e){e.preventDefault();let t=.1,r=e.deltaY,s=this.context._canvas;s&&(this.baseWidth||(this.baseWidth=s.offsetWidth),r<0?this.baseWidth=Math.min(this.baseWidth*(1+t),this.maxSize):this.baseWidth=Math.max(this.baseWidth*(1-t),this.minSize),this.renderCanvas())}resetPosition(){this.left=0,this.top=0,this.renderCanvas()}onRatioReset(){this.renderCanvas()}draw2d(e,t,r,s,n){var _;let{ctx2d:a}=this,c=this.context._canvas;if(!a||!c)return!1;let l=super.draw2d(e,t,r,s,n),u=a.getImageData(0,0,s,n),{data:h}=u,m=!1;if(this.initStat.alphaStitchingType===1){let g=Math.floor(s/2);for(let E=0;E<n;E++)for(let C=0;C<g;C++){let k=(E*s+C)*4,re=C+g,P=(E*s+re)*4,Qe=h[P];h[P+3]=0;let N=Qe>=100;h[k+3]=N?255:0}m=super.draw2d(u,0,0,0,0,g,n),c.width=g}else if(this.initStat.alphaStitchingType===2){let g=Math.floor(n/2);for(let E=0;E<g;E++)for(let C=0;C<s;C++){let k=(E*s+C)*4,P=((E+g)*s+C)*4,Qe=h[P];h[P+3]=0;let N=Qe>=100;h[k+3]=N?255:0}m=super.draw2d(u,0,0,0,0,s,g),c.height=g}return(_=this.context.ctx)==null||_.clearRect(0,0,s,n),l&&m}close(){this.baseRatio=void 0,this.end.next(),this.end.complete()}};function MS(o){return[15,30,45,60].reduce((e,t)=>Math.abs(t-o)<Math.abs(e-o)?t:e)}var Oi=class extends Ts{constructor(e,t,r=4){super(e,t,r);d(this,"mediaType",4);d(this,"source");d(this,"shouldRenderAlpha",!1);d(this,"alphaNode");d(this,"shouldBeDraggable",!0);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.on("first-video-frame",s=>{this.room.emit("first-video-frame",s)})}isAlphaSei(e){if(this.userId!==e.userId||e.seiPayloadType!==50)return!1;let t=new Uint8Array(e.data);return t.length%3!==0||t[0]!==0||t[1]!==1?!1:t}play(e,t){return(he(t==null?void 0:t.canvasRender)?t.canvasRender:et===17)&&!this.source&&this.useCanvasPlayer(),super.play(e,t).then(()=>{this.player.calculateStat(),S.emit("156",{track:this,player:this.player})})}updateAlphaRenderInfo(e){let t=this.isAlphaSei(e);if(t)if(!this.alphaNode)this.shouldRenderAlpha=!0,this.player.shouldRenderAlpha=!0,this.useCanvasPlayer(t[2]);else{let r=t[2];if(this.alphaNode.baseRatio&&this.alphaNode.initStat.alphaStitchingType===r)return;this.alphaNode.initStat={alphaStitchingType:r};let s=this.player.getElement();if(s){let n=s.videoWidth/s.videoHeight;n&&(this.alphaNode.baseRatio=n*(r===1?.5:2),this.alphaNode.onRatioReset())}this.player.canvas&&(this.player.canvas.id=this.generateAlphaCanvasName(r))}}generateAlphaCanvasName(e){let t="alpha",r=hn[e];return`${t}_${r}_${this.userId}`}useCanvasPlayer(e){if(this.log.info(`useCanvasPlayer(), has element:${!!this.player.element}`),!this.player.element)return;let t=new Xe({frameRate:15,logger:this.log,name:this.shouldRenderAlpha&&e?this.generateAlphaCanvasName(e):this.userId});t.create({alpha:this.shouldRenderAlpha,willReadFrequently:this.shouldRenderAlpha});let r=new fo(t,{name:"remotePlayer",logger:this.log});if(this.source=t.createVideoPlayerSource(this.player),this.player.setCanvas(t._canvas),this.shouldRenderAlpha&&e){let s=()=>{!this.player.container||!this.alphaNode||(this.alphaNode.container=this.player.container,this.alphaNode.renderCanvas())},n=new id(t,this.log,this.shouldBeDraggable,s,{alphaStitchingType:e});this.source.connect(n),n.connect(r),this.alphaNode=n}else this.source.connect(r);Ki()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,t),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let t=this.decodeFPS,r=MS(t);if(!z(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),S.emit("157",{track:this,player:this.player}),this.alphaNode&&this.alphaNode.close(),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)}setDraggable(e){this.shouldBeDraggable=e,this.alphaNode&&(this.alphaNode.draggable=e,this.alphaNode.bindDragEvents())}onDecodeDowngradeStateChanged(e){this.emit("decode-downgrade-state-changed",e)}},Es=class extends Oi{constructor(e,t){super(e,t,2);d(this,"mediaType",2);d(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}};var Ss=new Map;S.on(A.JOIN_SUCCESS,({room:o})=>{Ne(o.userId,{eventId:32788})});S.on(A.LEAVE_START,({room:o})=>{Ne(o.userId,{eventId:32789})});S.on(A.LOCAL_TRACK_PUBLISHED,({track:o})=>{if(o.room){let i=32769;o.mediaType===4?i=32768:o.mediaType===2&&(i=32805),Ne(o.room.userId,{eventId:i})}});S.on(A.LOCAL_TRACK_UNPUBLISHED,({track:o})=>{if(o.room){let i=32771;o.mediaType===4?i=32770:o.mediaType===2&&(i=32806),Ne(o.room.userId,{eventId:i})}});S.on(A.TRACK_MUTED,({track:o})=>{o.room&&(o.kind===f.AUDIO?Ne(o.room.userId,{eventId:o.isRemote?32785:32772,remoteUserId:o.isRemote?o.userId:void 0}):Ne(o.room.userId,{eventId:o.isRemote?32784:32773,remoteUserId:o.isRemote?o.userId:void 0}))});S.on(A.TRACK_UNMUTED,({track:o})=>{o.room&&(o.kind===f.AUDIO?Ne(o.room.userId,{eventId:o.isRemote?32787:32774,remoteUserId:o.isRemote?o.userId:void 0}):Ne(o.room.userId,{eventId:o.isRemote?32786:32775,remoteUserId:o.isRemote?o.userId:void 0}))});S.on(A.REMOTE_TRACK_SUBSCRIBED,({track:o})=>{o.room&&(o.mediaType===1&&Ne(o.room.userId,{eventId:32777,remoteUserId:o.userId}),o.mediaType===4&&Ne(o.room.userId,{eventId:32776,remoteUserId:o.userId}),o.mediaType===8&&Ne(o.room.userId,{eventId:32803,remoteUserId:o.userId}))});S.on(A.REMOTE_TRACK_UNSUBSCRIBED,({track:o})=>{o.room&&(o.mediaType===1&&Ne(o.room.userId,{eventId:32779,remoteUserId:o.userId}),o.mediaType===4&&Ne(o.room.userId,{eventId:32778,remoteUserId:o.userId}),o.mediaType===8&&Ne(o.room.userId,{eventId:32804,remoteUserId:o.userId}))});S.on(A.SWITCH_DEVICE_SUCCESS,({track:o})=>{o.room&&Ne(o.room.userId,{eventId:o.kind===f.VIDEO?32780:32781})});S.on(A.LOCAL_TRACK_REPLACED,({track:o})=>{o.room&&Ne(o.room.userId,{eventId:o.kind===f.VIDEO?32782:32783})});S.on(A.SIGNAL_CONNECTION_STATE_CHANGED,({room:o,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&&Ne(o.userId,{eventId:t})});S.on(A.PEER_CONNECTION_STATE_CHANGED,({room:o,prevState:i,state:e,remoteUserId:t})=>{let r=!!t,s;switch(e){case"CONNECTED":i==="RECONNECTING"?s=r?32801:32798:s=r?32793:32792;break;case"DISCONNECTED":i==="RECONNECTING"&&(s=r?32802:32799);break;case"RECONNECTING":s=r?32800:32797;break}s&&Ne(o.userId,{eventId:s,remoteUserId:t})});S.on(A.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({implementation:o,userId:i,remoteUserId:e,codec:t,isHWCodec:r,prevImplementation:s,streamType:n})=>{let a=r?1:0;s||(a=r?3:2);let c={H264:0,H265:1,VP8:2}[t.toUpperCase()],l={eventId:4004,param1:a,param2:c,streamType:n||2};e&&(l.remoteUserId=e,l.eventId=4005),Ne(i,l),v.addEnum({key:e?514701:513701,value:a}),v.addEnum({key:e?514700:513700,value:c})});S.on(A.LOCAL_TRACK_RECAPTURE,({track:o,error:i})=>{if(o.userId){let e={eventId:2003,param1:0};o.kind===f.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType=o.streamType==="auxiliary"?7:2,i&&(e.param1=8)),Ne(o.userId,e)}});function Ne(o,i){let e=L(O({},i),{timestamp:Fi()});Ss.has(o)?Ss.get(o).push(e):Ss.set(o,[e])}function Ef(o){if(Ss.has(o)){let i=Ss.get(o).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 Ss.delete(o),i}return[]}function Sf(...o){return Q((i,e)=>function(...t){return OS.call(this,o,t,e,this._name),i.apply(this,t)})}function OS(o,i,e,t){try{if(Ie(o))for(let r=0;r<o.length;r++)rd.call(this,{rule:o[r],value:i[r],key:o[r].name,fnName:e,className:t});else rd.call(this,{rule:o,value:i[0],key:o.name,fnName:e,className:t})}catch(r){throw R.error(r),r}}function rd({rule:o,value:i,key:e,fnName:t,className:r}){if(T(i)){if(o.required)throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_PARAMETER_REQUIRED,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(T(o.defaultValue))return;i=o.defaultValue}if(Array.isArray(o.type)){let a=!1;for(let c=0;c<o.type.length;c++)o.type[c]===null&&i===null&&(a=!0),le(o.type[c])&&i instanceof o.type[c]&&(a=!0),ie(o.type[c])&&Me(i)===o.type[c].toLowerCase()&&(a=!0);if(!a)throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_PARAMETER_TYPE,data:{key:e,rule:{type:o.type.map(c=>jr(c)?xo(c):ie(c)?c:Me(c))},fnName:t,value:i},link:{className:r,fnName:t}})})}else if(!T(o.type)&&Me(i)!==o.type)throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_PARAMETER_TYPE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(o.allowEmpty===!1){let a=z(i)&&(i===0||Number.isNaN(i)),c=ie(i)&&i.trim()==="";if(a||c)throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_PARAMETER_EMPTY,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})})}if(o.notLessThanZero&&z(i)&&i<0)throw new D({code:I.INVALID_PARAMETER,message:H({key:F.CANNOT_LESS_THAN_ZERO,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(!T(o.min)&&z(i)&&i<o.min)throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_PARAMETER_MIN,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(!T(o.max)&&z(i)&&i>o.max)throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_PARAMETER_MAX,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(ie(o.instanceOf)){if(!i||i._name!==o.instanceOf)throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})})}else if(le(o.instanceOf)&&!(i instanceof o.instanceOf))throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(o.values&&!o.values.includes(i))throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_PARAMETER_RANGE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});let{properties:s}=o;dt(s)&&yt(i)&&Object.keys(s).forEach(a=>{rd.call(this,{rule:s[a],value:i&&i[a],key:`${e}.${a}`,fnName:t,className:r})});let{arrayItem:n}=o;dt(n)&&Ie(i)&&i.forEach((a,c)=>{rd.call(this,{rule:n,value:a,key:`${e}[${c}]`,fnName:t,className:r})}),le(o.validate)&&o.validate.call(this,i,e,t,r,this)}var If=qe(at(),1);var od=class extends If.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:s,role:n}=e;if(this.userMap.has(t))return;let a={userId:r,tinyId:s,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 s=`peer leave [${e}]`;T(t)||(s+=`:${rl[t]}`),this._log.info(s);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(s=>s[this.key]===t[this.key])<0){this._log.info(`remote [${r}] unpublish`);let s=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(r),this.emit("6",{prevMuteState:s,muteState:t.muteState,flag:0})}}),e.forEach(t=>{var u;let r=t[this.key];if(r===this.mySelfId){this.emit("7",t);return}let{flag:s,userId:n,tinyId:a}=t,c=Kt(s,n),l=(u=this.remotePublishedUserMap.get(r))==null?void 0:u.muteState;if(l){let h=this.remotePublishedUserMap.get(r);h&&h.flag!==s&&(h.flag=s,this._log.info(`remote publish updated: ${JSON.stringify(h.muteState)}`),this.emit("6",{prevMuteState:l,muteState:c,flag:s}))}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:Kt(0,n),muteState:c,flag:s})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function Ch({timesInSecond:o,maxSizeInSecond:i,getSize:e}){return Q((t,r)=>{let s=new WeakMap;return S.on(A.ROOM_DESTROY,({room:n})=>s.delete(n)),function(...n){let a=s.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},s.set(this,a)),a.timestamp===0?a.timestamp=Date.now():Date.now()-a.timestamp>1e3&&(a.timestamp=Date.now(),a.callCountInSecond=0,a.totalSizeInSecond=0),e&&(a.totalSizeInSecond+=e(...n)),a.timestamp!==0&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=o||a.totalSizeInSecond>i))throw new D({code:I.INVALID_OPERATION,message:H({key:F.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=o,isSize:a.totalSizeInSecond>i,name:r,timesInSecond:o,maxSizeInSecond:i}})});a.callCountInSecond++,t.call(this,...n)}})}var kS="2025-12-02 15:26:17",Af=!0,Cf=function(){var o;if(Af){Af=!1,R.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${ft}/en/index.html`),console.info(`* Changelog: ${ft}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),R.info("TRTC Web SDK Version:",$e),oi||R.debug("Build Time:",kS);let i=`UA: ${navigator.userAgent}
|
|
52
|
+
} `;var _o=class extends J{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}get canvas(){return this._canvas}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 Wt(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new fs(this,e)}createVideoImageSource(e,t){return new $n(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new Wn(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}createTextSource(e,t){return new Kc(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}};d(_o,"_ids",0);var SS={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},_s=class _s extends _o{constructor(){super(...arguments);d(this,"defaultProgam");d(this,"defaultVShader");d(this,"defaultFShader");d(this,"ctx");d(this,"_canvas2d")}get canvas(){return this._canvas2d||this._canvas}create(e=!1){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${_o._ids++}`),e&&(this._canvas2d=document.createElement("canvas")),this.ctx=this._canvas.getContext("webgl2",SS),!this.ctx)throw new D({code:I.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,TS),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,ES),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})}destroy(e){let t="";return e&&(t=e.message,this.error=e,v.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,this._canvas2d&&(this._canvas2d.width=e)}set height(e){var t;(t=this.ctx)==null||t.viewport(0,0,this.width,e),super.height=e,this._canvas2d&&(this._canvas2d.height=e)}setSize(e,t){var r;(r=this.ctx)==null||r.viewport(0,0,e,t),super.setSize(e,t),this._canvas2d&&(this._canvas2d.width=e,this._canvas2d.height=t)}createShader(e,t){let r=this.ctx,s=r.createShader(e);return r.shaderSource(s,t),r.compileShader(s),s}createProgram(e,t){let r=this.ctx,s=r.createProgram();return r.attachShader(s,e),r.attachShader(s,t),r.linkProgram(s),r.getProgramParameter(s,r.LINK_STATUS)||this.log.error(r.getProgramInfoLog(s)),s}};d(_s,"UNAVAILABLE","unavailable"),M([ye(J.INIT,"created",{sync:!0,fail(e){this.log.error("video gl context create failed",e.cause),v.addFailedEvent({key:512700,error:e.cause||e})},success(){this.log.info("video context created use webgl"),v.addSuccessEvent({key:512700})}})],_s.prototype,"create",1),M([ye("created",J.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(_s.UNAVAILABLE,e),this.removeAllListeners()}})],_s.prototype,"destroy",1);var He=_s,Xe=class extends _o{constructor(){super(...arguments);d(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${_o._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:e.alpha,willReadFrequently:e.willReadFrequently}),!this.ctx)throw new D({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,v.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(),v.addSuccessEvent({key:512703})}};M([ye(J.INIT,"created",{sync:!0,fail(e){this.log.error("video 2d context create failed",e.cause),v.addFailedEvent({key:512701,error:e.cause||e})},success(){this.log.info("video context created use 2d"),v.addSuccessEvent({key:512701})}})],Xe.prototype,"create",1),M([ye("created",J.INIT,{ignoreError:!0,sync:!0})],Xe.prototype,"destroy",1);function IS(o,i,e,t,r,s=!1){s&&([e,t]=[t,e]);let n={sWidth:o,sHeight:i,dWidth:e,dHeight:t,sx:0,sy:0,dx:0,dy:0};if(o===0||i===0)return n;switch(r){case void 0:case"fill":break;case"contain":{let a=Math.min(e/o,t/i);n.dWidth=o*a,n.dHeight=i*a,n.dx=(e-n.dWidth)/2,n.dy=(t-n.dHeight)/2;break}case"cover":{let a=Math.max(e/o,t/i),c=e/a,l=t/a;n.sx=(o-c)/2,n.sy=(i-l)/2,n.sWidth=c,n.sHeight=l;break}}return n}var Ih=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}get fillMode(){return this.layout.fillMode}get rotation(){return this.layout.rotation}get hidden(){return!!this.layout.hidden}},gs=class extends Ue{constructor(e,t){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:t});d(this,"inputs",[]);d(this,"backgroundColor","black")}addInput(e,t){let r=0,s=this.inputs.length;for(;r<s;){let a=Math.floor((r+s)/2);if(this.inputs[a].layout.zIndex<t.zIndex)r=a+1;else if(this.inputs[a].layout.zIndex>t.zIndex)s=a;else throw new Error(`input already exists at zIndex ${t.zIndex}`)}let n=new Ih(e,t);this.inputs.splice(r,0,n)}changeInputLayout(e,t){let r=this.inputs.findIndex(g=>g.node===e);if(r<0)return;let{x:s,y:n,width:a,height:c,zIndex:l,fillMode:u,rotation:h,hidden:m}=t;if(!T(l)&&this.inputs.some(g=>g.layout.zIndex===l&&g.node!==e))throw new Error(`input already exists at zIndex ${t.zIndex}`);let _=this.inputs[r];T(s)||(_.layout.x=s),T(n)||(_.layout.y=n),T(a)||(_.layout.width=a),T(c)||(_.layout.height=c),T(h)||(_.layout.rotation=h),T(m)||(_.layout.hidden=m),u&&(_.layout.fillMode=u),!T(l)&&l!==_.layout.zIndex&&(_.layout.zIndex=l,this.inputs.sort((g,E)=>g.layout.zIndex-E.layout.zIndex))}hasInput(e){return this.inputs.some(t=>t.node===e)}hasNoInput(){return this.inputs.length===0}resize(e,t){if(!this.matchInputSize){super.resize(e,t);return}let r=this.inputs.reduce((s,n)=>n?Object.assign(s,{width:Math.max(s.width,n.right),height:Math.max(s.height,n.bottom)}):s,{width:0,height:0});super.resize(r.width,r.height),this.context instanceof He&&this.inputs.forEach(s=>{if(s){let n=this.layout2texCoords(s);s.positionBuffer?this.changeBufferData(s.positionBuffer,n):s.positionBuffer=this.createBuffer(n)}})}connect(e,...t){return super.connect(e,...t),this.drawBackGround2d(this.backgroundColor),this.matchInputSize&&this.resize(0,0),e}removeInput(e){this.inputs=this.inputs.filter(t=>t.node!==e),this.inputs.length===0&&this.drawBackGround2d(this.backgroundColor)}render(e){let t=this.context.ctx;if(t.clearColor(0,0,0,0),this.inputs.reduce((s,n)=>n.node.requestFrame(e)||s,!1)&&t){this.useProgram(),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let s=0;s<this.inputs.length;s++){let n=this.inputs[s];n&&(n.node.useTexture(),this.draw(n.positionBuffer))}return!0}return!1}render2d(e){if(this.inputs.forEach(t=>t.node.requestFrame(e)),this.ctx2d){this.drawBackGround2d(this.backgroundColor);for(let t=0;t<this.inputs.length;t++){let r=this.inputs[t];if(r.hidden)continue;let s=IS(r.node.width,r.node.height,r.width,r.height,r.fillMode,bt(r.rotation));this.draw2d(r.node.image,r.x+s.dx,r.y+s.dy,s.dWidth,s.dHeight,s.sx,s.sy,s.sWidth,s.sHeight)}return!0}return!1}debugLayout(e,t,r,s,n=!1){this.ctx2d&&(n&&([r,s]=[s,r]),this.ctx2d.save(),this.ctx2d.strokeStyle="red",this.ctx2d.lineWidth=2,this.ctx2d.strokeRect(e,t,r,s),this.ctx2d.restore())}getInfo(){let{totalFrames:e,x:t,y:r,width:s,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:s,height:n,timestamp:c,fps:l,name:a},O({parent:this.inputs.filter(u=>u).map(u=>u.node.getInfo())},this.lastInfo)}removeAllInputs(){this.inputs.forEach(e=>{var t;if(e.node.disconnect(),e.positionBuffer&&this.context instanceof He)try{(t=this.context.ctx)==null||t.deleteBuffer(e.positionBuffer)}catch(r){}})}close(){super.close(),this.removeAllInputs()}};var AS=[1,0,0,0,1,1,0,1],Gt=class extends Ue{constructor(e,t,r,s){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),s&&(this.rotation=s),e instanceof He)try{this.setTexBuffer(AS)}catch(n){e.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${n.message||n}`}))}}draw2d(e,t,r,s,n){if(this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height),this.ctx2d.save(),this.mirror&&(this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0)),this.rotation===90?(this.ctx2d.translate(s,0),this.ctx2d.rotate(Math.PI/2),this.ctx2d.scale(n/s,s/n)):this.rotation===180?(this.ctx2d.translate(this.width,this.height),this.ctx2d.rotate(Math.PI)):this.rotation===270&&(this.ctx2d.translate(0,n),this.ctx2d.rotate(3*Math.PI/2),this.ctx2d.scale(n/s,s/n));let a=super.draw2d(e,t,r,s,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}resize(e,t){bt(this.rotation)&&([e,t]=[t,e]),super.resize(e,t)}};var go=class extends pi{constructor(e,t=4){super(t,it);d(this,"inputLocalVideoTracks",new Map);d(this,"inputLocalScreenTracks",new Map);d(this,"cameraNodeMap",new Map);d(this,"screenNodeMap",new Map);d(this,"textNodeMap",new Map);d(this,"imageNodeMap",new Map);d(this,"videoNodeMap",new Map);d(this,"endedIds",new Set);d(this,"videoContext");d(this,"mixNode");d(this,"destination");d(this,"manager");d(this,"stat");d(this,"_checkId",0);d(this,"autoSetFps",!0);this.manager=e,this.log.id+="mix",this.create2dVideoContext(),this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log}),this.destination.on(Ue.RENDER,r=>{this.emit("render",r)}),this.mixNode=new gs(this.videoContext,this.log),this.mixNode.matchInputSize=!1}listenDeviceChange(){throw new Error("Method not implemented.")}enablePrintDetail(e=2e3){this._checkId=oe.run("interval",()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:e})}create2dVideoContext(){this.videoContext?this.videoContext.destroy():this.videoContext=new Xe({frameRate:15,logger:this.log,name:"mix-ctx"}),this.videoContext.create({alpha:!1})}setFps(e){this.autoSetFps=!1,this.videoContext.frameRate=e;for(let t of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])t.shouldUpdate=!1;setTimeout(()=>{var t;return(t=this.destination)==null?void 0:t.start(this.videoContext.frameRate)},500)}setFpsAuto(){var s;if(!this.autoSetFps)return;for(let n of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])n.shouldUpdate=!1;let e=null,t=0,r=!0;for(let[n,a]of this.inputLocalVideoTracks)if(a.profile.frameRate>t){if(this.endedIds.has(n)){let c=this.cameraNodeMap.get(n);c&&c.image.cancelVideoFrameCallback(c.videoCallbackId);continue}t=a.profile.frameRate,e=n}for(let[n,a]of this.inputLocalScreenTracks)if(a.profile.frameRate>t){if(this.endedIds.has(n)){let c=this.screenNodeMap.get(n);c&&c.image.cancelVideoFrameCallback(c.videoCallbackId);continue}t=a.profile.frameRate,e=n,r=!1}if(e!==null){let n=r?this.cameraNodeMap.get(e):this.screenNodeMap.get(e);n&&(n.shouldUpdate=!0,n.tryVideoFrameCallback()),this.log.info("set mix fps: ",t)}else(s=this.destination)==null||s.start(this.videoContext.frameRate),this.log.info("fallback to timer, fps: ",this.videoContext.frameRate)}setMixBackground(e){this.mixNode&&(this.mixNode.backgroundColor=e)}resizeMixCanvas(e,t){var r;(r=this.mixNode)==null||r.resize(e,t)}startMix(){return p(this,null,function*(){var e;if(!this.mixNode||!this.destination)throw new Error("can't mix without necessary conditions");this.mixNode.disconnect(),this.mixNode.connect(this.destination),Ft&&this.player.setCanvas(this.videoContext._canvas),this.setOutputMediaStreamTrack(this.destination.videoTrack),(e=this.manager)==null||e.changeInput(this)})}addCameraSource(e,t,r){if(this.inputLocalVideoTracks.has(e)||this.cameraNodeMap.has(e))throw new Error(`There is already a cameraSource with the same ID: ${e}`);let{mediaTrack:s}=t;if(!s)throw new Error("no mediaTrack, add cameraSource failed");t.recaptureMode=1,tt(this,be).add("videoInputRemoved",a=>{a.deviceId===t.deviceId&&(this.endedIds.add(e),this.setFpsAuto())}),t.on("output-media-track-changed",()=>{this.endedIds.delete(e),this.updateCameraSource(e,r,t.mediaTrack)});let n;et===16&&s instanceof CanvasCaptureMediaStreamTrack?n=this.videoContext.createVideoImageSource(s.canvas,{name:"cameraCanvasSource",logger:this.log}):n=this.videoContext.createVideoTrackSource(s,"cameraNodeSource"),n.resize(t.settings.width,t.settings.height),n.shouldUpdate=!1,this._connectMix(n,r,"cover"),this.inputLocalVideoTracks.set(e,t),this.cameraNodeMap.set(e,n),this.setFpsAuto()}addScreenSource(e,t,r){if(this.inputLocalScreenTracks.has(e)||this.screenNodeMap.has(e))throw new Error(`There is already a screenSource with the same ID: ${e}`);let{mediaTrack:s}=t;if(!s)throw new Error("no mediaTrack, add cameraSource failed");let n=this.videoContext.createVideoTrackSource(s,"screenNodeSource");n.resize(t.settings.width,t.settings.height),n.shouldUpdate=!1,this._connectMix(n,r),this.inputLocalScreenTracks.set(e,t),this.screenNodeMap.set(e,n),this.setFpsAuto()}addTextSource(e){let{id:t,content:r="",font:s,color:n,layout:a}=e;if(this.textNodeMap.has(t))throw new Error(`There is already a textSource with the same ID: ${t}`);let c=this.videoContext.createTextSource({content:r,font:s,color:n});c.resize(a.width,a.height),this._connectMix(c,a),this.textNodeMap.set(t,c)}addImageSource(e,t,r){if(this.imageNodeMap.has(e))throw new Error(`There is already a imageSource with the same ID: ${e}`);let s=this.videoContext.createVideoImageSource(t,{autoResize:!1,logger:this.log});s.resize(t.width,t.height),this._connectMix(s,r),this.imageNodeMap.set(e,s)}addVideoSource(e,t,r){if(this.videoNodeMap.has(e))throw new Error(`There is already a videoSource with the same ID: ${e}`);let s=this.videoContext.createVideoImageSource(t,{autoResize:!1,logger:this.log});s.resize(t.videoWidth,t.videoHeight),s.shouldUpdate=!1,this._connectMix(s,r),this.videoNodeMap.set(e,s)}updateCameraSource(e,t,r=null,s){let n=this.cameraNodeMap.get(e);if(n){if(r){if(et===16&&r instanceof CanvasCaptureMediaStreamTrack)if(n instanceof Wt){let l=n.output;n.close(),n=this.videoContext.createVideoImageSource(r.canvas,{name:"cameraCanvasSource",logger:this.log}),n.connect(l),this.cameraNodeMap.set(e,n)}else n.image=r.canvas;else if(n instanceof Wt)n.replaceTrack(r);else{let l=n.output;n.close(),n=this.videoContext.createVideoTrackSource(r,"cameraNodeSource"),n.connect(l),this.cameraNodeMap.set(e,n)}let{width:a,height:c}=r.getSettings();a&&c&&n.resize(a,c)}s&&n.resize(s.width,s.height),(s||r)&&this.setFpsAuto(),this._changeMixLayout(n,t)}}updateScreenSource(e,t){let r=this.screenNodeMap.get(e);r&&this._changeMixLayout(r,t)}updateTextSource(e){let{id:t,content:r,font:s,color:n,layout:a}=e,c=this.textNodeMap.get(t);c&&(T(r)||(c.content=r),T(s)||(c.font=s),T(n)||(c.color=n),c.resize(a.width,a.height),this._changeMixLayout(c,a))}updateImageSource(e,t,r){let s=this.imageNodeMap.get(e);s&&(r&&(s.image=r,s.resize(r.width,r.height)),this._changeMixLayout(s,t))}updateVideoSource(e,t,r){let s=this.videoNodeMap.get(e);if(s){if(r){let n=s.image;n instanceof HTMLVideoElement&&this.stopVideoElement(n),s.image=r,s.resize(r.videoWidth,r.videoHeight)}this._changeMixLayout(s,t)}}_connectMix(e,t,r="contain"){if(!this.mixNode)return;let{mirror:s,rotation:n}=t;e.disconnect();let a=new Gt(this.videoContext,this.log,s,n);a=e.connect(a),t.fillMode||(t.fillMode=r),a.connect(this.mixNode,t)}_changeMixLayout(e,t){if(!this.mixNode)return;let{mirror:r,rotation:s}=t,n=e.output||e;n instanceof Gt&&(T(r)||(n.mirror=r),T(s)||(n.rotation=s),n.resize(e.width,e.height)),this.mixNode.changeInputLayout(n,t)}removeCameraSource(e){let t=this.inputLocalVideoTracks.get(e);if(!t)return;t.close(),this.inputLocalVideoTracks.delete(e);let r=this.cameraNodeMap.get(e);r&&(r.output instanceof Gt&&r.output.close(),r.close(),this.cameraNodeMap.delete(e)),this.checkAfterRemove(!0)}removeScreenSource(e){let t=this.inputLocalScreenTracks.get(e);if(!t)return;t.close(),this.inputLocalScreenTracks.delete(e);let r=this.screenNodeMap.get(e);r&&(r.output instanceof Gt&&r.output.close(),r.close(),this.screenNodeMap.delete(e)),this.checkAfterRemove(!0)}removeTextSource(e){let t=this.textNodeMap.get(e);t&&(t.output instanceof Gt&&t.output.close(),t.close(),this.textNodeMap.delete(e)),this.checkAfterRemove()}removeImageSource(e){let t=this.imageNodeMap.get(e);t&&(t.output instanceof Gt&&t.output.close(),t.close(),this.imageNodeMap.delete(e)),this.checkAfterRemove()}removeVideoSource(e){let t=this.videoNodeMap.get(e);t&&(t.output instanceof Gt&&t.output.close(),t.image instanceof HTMLVideoElement&&this.stopVideoElement(t.image),t.close(),this.videoNodeMap.delete(e)),this.checkAfterRemove()}checkAfterRemove(e=!1){e&&this.setFpsAuto()}stopVideoElement(e){e.pause(),e.src="",e.srcObject=null,e.remove()}close(){var e;super.close(),oe.clearTask(this._checkId),(e=this.videoContext)==null||e.destroy(),delete this.mixNode,delete this.destination;for(let t of[...this.inputLocalVideoTracks.values(),...this.inputLocalScreenTracks.values()])t.close();this.inputLocalVideoTracks.clear(),this.inputLocalScreenTracks.clear(),this.cameraNodeMap.clear(),this.screenNodeMap.clear(),this.textNodeMap.clear(),this.imageNodeMap.clear(),Le(this);for(let t of this.videoNodeMap.values())t.image instanceof HTMLVideoElement&&this.stopVideoElement(t.image);this.videoNodeMap.clear(),this.log.info("localMixVideoTrack close, stop mix")}};var ed=cn();if(typeof navigator!="undefined"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:ed,exposeOrigin:!0,permittedOrigins:["*"]})}catch(o){}var CS=function(o){return p(this,null,function*(){let i=null,e=bS(o);R.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let t=yield navigator.mediaDevices.getDisplayMedia(e);o.systemAudio&&t.getAudioTracks().length===0&&(Zo&&We<74||Re||K)&&R.warn("Your browser not support capture system audio");let r=t.getVideoTracks()[0];if(r){if(o.frameRate)try{yield r.applyConstraints({frameRate:{min:o.frameRate,ideal:o.frameRate},width:o.width,height:o.height})}catch(s){R.warn(`screen applyConstraints failed: ${s}`)}o.captureElement&&(yield RS(r,o.captureElement))}if(o.audio){let s=yS(o);R.info(`getUserMedia with constraints: ${JSON.stringify(s)}`),i=yield navigator.mediaDevices.getUserMedia(s),t.addTrack(i.getAudioTracks()[0])}return t})};function RS(o,i){return p(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&le(o.cropTo))try{if(!(((e=o.getCaptureHandle())==null?void 0:e.handle)===ed))return;let r=yield CropTarget.fromElement(i);yield o.cropTo(r)}catch(t){R.warn(`cropTo target failed ${t}`)}})}function yS(o){let i={echoCancellation:o.echoCancellation,autoGainControl:o.autoGainControl,noiseSuppression:o.noiseSuppression,sampleRate:o.sampleRate,channelCount:o.channelCount};return T(o.microphoneId)||(i.deviceId=o.microphoneId),{audio:i,video:!1}}function bS(o){let i={preferCurrentTab:o.preferDisplaySurface==="current-tab"||!!o.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:Re?{max:o.width}:{ideal:o.width,max:o.width},height:Re?{max:o.height}:{ideal:o.height,max:o.height},frameRate:o.frameRate,displaySurface:o.preferDisplaySurface||"monitor"};if(i.video=e,o.systemAudio){let{echoCancellation:t=!0,noiseSuppression:r=!1,autoGainControl:s=!1}=o;i.audio={echoCancellation:t,noiseSuppression:r,autoGainControl:s,sampleRate:48e3}}return i}var gf=CS;var Pt=class extends je{constructor(e){super(e,2);d(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600});d(this,"objectFit","contain");d(this,"isScreen",!0);this._log.id=`s-${this._log.id}`}get isShareCurrentTab(){var e,t;try{return ed===((t=(e=this.mediaTrack)==null?void 0:e.getCaptureHandle())==null?void 0:t.handle)}catch(r){return}}capture(u){return p(this,arguments,function*({systemAudio:e=!1,autoGainControl:t,echoCancellation:r,noiseSuppression:s,audioTrack:n,videoTrack:a,captureElement:c,preferDisplaySurface:l}){try{let h;return a||n?(h=new MediaStream,a&&h.addTrack(a),n&&h.addTrack(n)):(h=yield gf({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:t,echoCancellation:r,noiseSuppression:s,captureElement:c,preferDisplaySurface:l}),this.sourceTrack=h.getVideoTracks()[0]),yield this.setInputMediaStreamTrack(h.getVideoTracks()[0]),h}catch(h){throw this.log.error(`getDisplayMedia error observed ${h}`),h instanceof D?h:new D({code:I.INITIALIZE_FAILED,name:h.name,message:h.message})}})}switchDevice(e){return p(this,null,function*(){throw new Error("Method not implemented.")})}};M([Ct(function(e){this.setContentHint(e.contentHint||"detail")})],Pt.prototype,"capture",1);var To=class extends kt{constructor(i){super(i),this._log.id=`s-${this._log.id}`,this.isScreen=!0}addAudioProcessor(i,e,t){this.pipeline.silentNode.setNode(t),this.pipeline.mixNode.setNode(e),this.pipeline.aec.setNode(i),this.enableTrackAEC(!1)}removeAudioProcessor(i){this.pipeline.aec.node===i&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode(),this.enableTrackAEC(!0))}};var vS='registerProcessor("dumper",class extends AudioWorkletProcessor{constructor(e){super(),this.sourceSampleRate=e.processorOptions.sourceSampleRate||48e3,this.targetSampleRate=e.processorOptions.targetSampleRate||48e3,this.port.onmessage=e=>{this.port2=e.data.port}}process(e){return(this.port2||this.port).postMessage(this.resampleAll(e,this.sourceSampleRate,this.targetSampleRate)),!0}resampleAll(r,s,a){if(s===a)return r;var o=[];for(let t=0;t<r.length;t++){o[t]=[];for(let e=0;e<r[t].length;e++)o[t][e]=this.resample(r[t][e],s,a)}return o}resample(t,e,r){if(e===r)return t;var s=Math.round(t.length*(this.targetSampleRate/this.sourceSampleRate)),a=new Float32Array(s),o=(t.length-1)/(s-1);a[0]=t[0];for(let e=1;e<s-1;e++){var l=e*o,p=Math.floor(l),h=Math.ceil(l);a[e]=t[p]+(t[h]-t[p])*(l-p)}return a[s-1]=t[t.length-1],a}});',Ah;function Gn(o,i=48e3,e=1,t){return p(this,null,function*(){let r=Ee("dump");Ah||(Ah=tr(r,URL.createObjectURL(new Blob([vS],{type:"application/javascript"})))),yield Ah;let s=r.sampleRate,n=new AudioWorkletNode(r,"dumper",{numberOfInputs:o.length,numberOfOutputs:0,processorOptions:{sourceSampleRate:s,targetSampleRate:i}});return n.channelCountMode="explicit",n.channelCount=e,t&&n.port.postMessage({port:t},[t]),o.forEach((a,c)=>a.connect(n,0,c)),new ReadableStream({start(a){n.port.onmessage=c=>{a.enqueue(c.data)}},cancel(){o.forEach(a=>a.disconnect(n)),n.port.close()}})})}var td=class extends bc{constructor(e){super();this.room=e;d(this,"_localAudioTrack");d(this,"_localScreenAudioTrack");d(this,"log");d(this,"denoiser");d(this,"voiceChanger");d(this,"mixChangedDebounce");d(this,"audioProcessor");d(this,"encodePipeline",[]);d(this,"decodePipeline",[]);d(this,"getPCMAbortCtrlMap",new Map);d(this,"audioFrameEventConfigMap",new Map);d(this,"audioReferenceMap",new Map);d(this,"isLocalAudioNeedAudioProcess",!1);d(this,"isScreenAudioNeedAudioProcess",!1);this.log=R.createLogger({parent:e==null?void 0:e.getLogger(),id:"am",userId:e==null?void 0:e.userId,sdkAppId:e==null?void 0:e.sdkAppId}),this.installEvent()}get localAudioTrack(){return this._localAudioTrack}get _localAudioPipline(){var e;return(e=this._localAudioTrack)==null?void 0:e.pipeline}get _localScreenAudioPipeline(){var e;return(e=this._localScreenAudioTrack)==null?void 0:e.pipeline}dump(e){var u,h;if(!this._localAudioTrack)return;let t=[],r=[];(u=this._localAudioPipline)!=null&&u.source.node&&(t.push(this._localAudioPipline.source.node),r.push("mic")),(h=this._localAudioPipline)!=null&&h.denoiser.node&&(t.push(this._localAudioPipline.denoiser.node),r.push("mic-processed")),this.mixWeight>1&&(t.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),r.push("mix")),this.log.info(`dump audio track ${r}, duration: ${e}`);let s=new AbortController,n=[],a=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),s.abort("timeout")},e*1e3),c=()=>{for(let m=0;m<r.length;m++){let _=URL.createObjectURL(new Blob(n[m])),g=document.createElement("a");g.href=_,g.download=`${r[m]}.pcm`,g.style.display="none",document.body.appendChild(g),g.click(),URL.revokeObjectURL(_),g.remove()}clearTimeout(a),s.abort("download")},l=Gn(t).then(m=>m.pipeTo(new WritableStream({write(_){_.forEach((g,E)=>n[E]=n[E]?n[E].concat(g[0]):[g[0]])}}),s).catch(_=>c));return{then:l.then.bind(l),download:c}}getPCM(e,t){var k,re,P;if(typeof WritableStream=="undefined"){this.log.warn("getPCM failed: browser not support WritableStream");return}let{enable:r,sampleRate:s=48e3,channelCount:n=1,port:a}=(t===""?this.audioFrameEventConfigMap.get(""):this.audioFrameEventConfigMap.get(t)||this.audioFrameEventConfigMap.get("*"))||{};if(!r)return;this.log.info(`getPCM ${t||"local"}`);let c=Math.floor(s*.04),l=new Float32Array(c),u=new Float32Array(c),h,m,_=0,g=new AbortController,E=t===""?(k=this._localAudioTrack)==null?void 0:k.mediaTrack:(P=(re=this.room)==null?void 0:re.remotePublishedUserMap.get(t))==null?void 0:P.remoteAudioTrack.mediaTrack;if(!E){this.log.info(`getPCM failed: ${t||"local"} has no audio track`);return}let C=Ee().createMediaStreamSource(new MediaStream([E]));return Gn([C],s,n,a).then(Qe=>Qe.pipeTo(new WritableStream({write(N){N[0][0]&&(_+N[0][0].length>c?(l.set(N[0][0].subarray(0,c-_),_),h=N[0][0].subarray(c-_),N[0][1]&&(u.set(N[0][1].subarray(0,c-_),_),m=N[0][1].subarray(c-_)),_+=c-_):(h&&(l.set(h,_),_+=h.length,h=void 0),m&&(u.set(m,_),m=void 0),l.set(N[0][0],_),N[0][1]&&u.set(N[0][1],_),_+=N[0][0].length),_>=c&&(_=0,e({userId:t,sampleRate:s,channelCount:n,data:n===1?l:[l,u]}),l=new Float32Array(c),u=new Float32Array(c)))}}),g).catch(N=>this.log.warn(`stop getPCM reason:${N}`))),g}get hasScreenAudioTrack(){return!T(this._localScreenAudioTrack)}get hasAudioTrack(){return!T(this._localAudioTrack)}changeInput(e){var t,r;if(e instanceof To)return this._localScreenAudioTrack=e,this.isScreenAudioNeedAudioProcess&&((t=this.audioProcessor)!=null&&t.screenAudioWorkletNode)&&(e.addAudioProcessor(this.audioProcessor.screenAudioWorkletNode,this.audioProcessor.mixNode,this.audioProcessor.silentNode),this.audioReferenceMap.forEach((s,n)=>{e.mixAudioReference(s,n)})),e.pipeline.connect(),this.mixOnChange();if(e instanceof kt)return this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),this.isLocalAudioNeedAudioProcess&&((r=this.audioProcessor)!=null&&r.localAudioWorkletNode)&&(e.addAudioProcessor(this.audioProcessor.localAudioWorkletNode,this.audioProcessor.mixNode,this.audioProcessor.silentNode),this.audioReferenceMap.forEach((s,n)=>{e.mixAudioReference(s,n)})),e.pipeline.connect(),this.mixOnChange();if(e instanceof gi)return e.setOutputMediaStreamTrack(e.mediaTrack)}mixAudioReference(e,t){var r;(r=this._localAudioTrack)==null||r.mixAudioReference(e,t)}unMixAudioReference(e){var t;(t=this._localAudioTrack)==null||t.unMixAudioReference(e)}setAudioReferenceVolume(e,t){var r;(r=this._localAudioTrack)==null||r.setAudioReferenceVolume(e,t)}mixOnChange(){return this.mixChangedDebounce||(this.mixChangedDebounce=Promise.resolve().then(()=>{var e,t;return delete this.mixChangedDebounce,Promise.all([(e=this._localAudioTrack)==null?void 0:e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),(t=this._localScreenAudioTrack)==null?void 0:t.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)])})),this.mixChangedDebounce}removeInput(e){e instanceof To?delete this._localScreenAudioTrack:e instanceof kt?delete this._localAudioTrack:e instanceof gi}addDenoiser(e){var t;this.denoiser=e,(t=this._localAudioTrack)==null||t.addDenoiser(e)}addAudioProcessor(e,t,r,s){var n;this.audioProcessor={localAudioWorkletNode:r,mixNode:e,silentNode:t,screenAudioWorkletNode:s},this.isLocalAudioNeedAudioProcess&&this._localAudioTrack&&r&&(this._localAudioTrack.addAudioProcessor(r,e,t),this.audioReferenceMap.forEach((a,c)=>{var l;(l=this._localAudioTrack)==null||l.mixAudioReference(a,c)})),this.isScreenAudioNeedAudioProcess&&this._localScreenAudioTrack&&s&&((n=this._localScreenAudioTrack)==null||n.addAudioProcessor(s,e,t),this.audioReferenceMap.forEach((a,c)=>{var l;(l=this._localScreenAudioTrack)==null||l.mixAudioReference(a,c)}))}removeDenoiser(e){var t;return delete this.denoiser,(t=this._localAudioTrack)==null?void 0:t.removeDenoiser(e)}addVoiceChanger(e,t){var r;this.voiceChanger=[e,t],(r=this._localAudioTrack)==null||r.pipeline.voiceChanger.setNode(e,t)}removeVoiceChanger(){var e;delete this.voiceChanger,(e=this._localAudioTrack)==null||e.pipeline.voiceChanger.deleteNode()}removeAudioProcessor(e,t){var r,s;delete this.audioProcessor,(r=this._localAudioTrack)==null||r.removeAudioProcessor(e),(s=this._localScreenAudioTrack)==null||s.removeAudioProcessor(t)}destroy(){this.close(),this.audioReferenceMap.clear(),this.getPCMAbortCtrlMap.forEach(e=>e==null?void 0:e.abort("destroy")),this.getPCMAbortCtrlMap.clear(),this.audioFrameEventConfigMap.clear(),this.uninstallEvent()}addEncodeProcessor({processor:e,type:t}){var r;this.encodePipeline.includes(e)||(this.encodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}addDecodeProcessor({processor:e,type:t}){var r;this.decodePipeline.includes(e)||(this.decodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}handleLocalTrackStarted({room:e,userId:t}){var s;if(e!==this.room||this.getPCMAbortCtrlMap.get(t))return;let r=this.getPCM(n=>{var a;(a=this.room)==null||a.emit("audio-frame",n)},"");this.getPCMAbortCtrlMap.set(t,r),this.getPCMAbortCtrlMap.get(t)&&((s=this._localAudioTrack)==null||s.on("input-media-track-changed",()=>{let n=this.getPCMAbortCtrlMap.get(t);n&&(n.abort("inputMediaTrackChanged"),n=this.getPCM(a=>{var c;(c=this.room)==null||c.emit("audio-frame",a)},""),this.getPCMAbortCtrlMap.set(t,n))}))}handleLocalTrackStopped({room:e,userId:t}){if(e!==this.room)return;let r=this.getPCMAbortCtrlMap.get(t);r&&(r.abort("stopLocalAudio"),this.getPCMAbortCtrlMap.delete(t))}handleRemoteTrackStarted({room:e,userId:t}){if(e===this.room&&!this.getPCMAbortCtrlMap.get(t)){let r=this.room.audioManager.getPCM(s=>{var n;(n=this.room)==null||n.emit("audio-frame",s)},t);this.getPCMAbortCtrlMap.set(t,r)}}handleRemoteTrackStopped({room:e,userId:t}){if(e!==this.room)return;let r=this.getPCMAbortCtrlMap.get(t);r&&(r.abort("stopRemoteAudio"),this.getPCMAbortCtrlMap.delete(t))}installEvent(){S.on("113",this.handleLocalTrackStarted,this),S.on("114",this.handleLocalTrackStopped,this),S.on("115",this.handleRemoteTrackStarted,this),S.on("116",this.handleRemoteTrackStopped,this)}uninstallEvent(){S.off("113",this.handleLocalTrackStarted),S.off("114",this.handleLocalTrackStopped),S.off("115",this.handleRemoteTrackStarted),S.off("116",this.handleRemoteTrackStopped)}updateAudioReference({type:e,audioReference:t,refId:r,volume:s}){if(e==="add"){if(this.audioReferenceMap.get(r)||!t||(this.audioReferenceMap.set(r,t),!this.audioProcessor))return;this.mixAudioReference(t,r)}else if(e==="remove")this.audioReferenceMap.get(r)&&(this.audioReferenceMap.delete(r),this.unMixAudioReference(r));else if(e==="updateVolume"){if(!this.audioProcessor||T(s))return;this.setAudioReferenceVolume(r,s)}}};function Eo(o=30,i=2){return Q((e,t)=>function(...r){return new Promise((s,n)=>{let a=setTimeout(()=>{let c=new D({code:I.API_CALL_TIMEOUT,message:`checkPendingPromise ${t}() timeout ${o}s`});(this.log||this._log||R).warn(c),i===2?n(c):i===1&&s()},o*1e3);this._checkPendingPromiseSet||(this._checkPendingPromiseSet=new Set),this._checkPendingPromiseSet.add(a),e.apply(this,r).then(s,n).finally(()=>{clearTimeout(a),this._checkPendingPromiseSet&&a&&this._checkPendingPromiseSet.delete(a)})})})}function Tf(){return Q((o,i)=>function(...e){return this._checkPendingPromiseSet&&(this._checkPendingPromiseSet.forEach(t=>clearTimeout(t)),this._checkPendingPromiseSet.clear()),o.apply(this,e)})}var Mi=class Mi extends no{constructor(e,t,r){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:r,room:e});this.room=e;this.user=t;d(this,"tinyId");d(this,"isRemote",!0);d(this,"jitterBufferDelay",0);d(this,"availableState");d(this,"remotePublishState");d(this,"_triggerCheckDecodeSubject",ot(ce(this,Mi.STATE_SUBSCRIBE)));d(this,"ignoreUpdatePlayingState");this.tinyId=t.tinyId,this.availableState=new J(`${t.userId}-${this.mediaType}-available`,"remote-track-available"),this.remotePublishState=new J(`${t.userId}-${this.mediaType}-remote-publish`,"remote-track-publish"),de(Ln(ce(this,J.STATECHANGED),ce(this.remotePublishState,J.STATECHANGED)),Fn(()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing)),Te(c=>{this.availableState.state!==(c?J.ON:J.OFF)&&(this.availableState.state=c?J.ON:J.OFF),!(this.isRemotePublished&&this.ignoreUpdatePlayingState)&&this.updatePlayingState(c)}));let s=de(ce(this.player,ue.ERROR),$t(c=>c.code===MediaError.MEDIA_ERR_DECODE)),n=de(Un(5e3),$t(()=>this.ignoreDecodeError||!this.isSubscribed||!this.isPlayCalled||!this.stat.bytesReceived?!1:this.player.isPlaying||(this.kind===f.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)?(this.reportDecodeResult(!0),!1):!0)),a=de(xu(s,n),ke(ce(this,J.INIT)));de(this._triggerCheckDecodeSubject,$t(()=>!this.ignoreDecodeError),mo(a),Te(c=>{this.reportDecodeResult(!1,c)}))}setMute(e){this.isRemotePublished&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.isRemotePublished&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}checkDecodeResult(){this._triggerCheckDecodeSubject.next(!0)}waitHasMediaTrack(){return new Promise(e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)})}get ignoreDecodeError(){var t,r;return(((r=(t=this.room)==null?void 0:t.networkQuality)==null?void 0:r.downlinkNetworkQuality)||0)>3||this.player.isInAutoPlayFailedState}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===Mi.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===J.ON}get isNeedPlay(){return this.isAvailable&&this.isPlayCalled}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}reportDecodeResult(e,t){var s,n;let r=this.kind===f.AUDIO;if(v[e?"addSuccessEvent":"addFailedEvent"]({key:r?504700:514702}),!r){let a=((s=this.room)==null?void 0:s.downlinkVideoCodec.toUpperCase())||"H264";v[e?"addSuccessEvent":"addFailedEvent"]({key:rs[`DECODE_${a}_RESULT`]}),e||this.log.warn(`${(n=this.room)==null?void 0:n.downlinkVideoCodec} decode failed`)}e||(v.addEnum({key:r?504701:514703,value:Zr()}),se.uploadEvent({log:`stat-decode-failed-${this.kind}-${si()||ni()}`,userId:this.room.userId}),this._log.warn(`decode failed: isPlaying: ${this.player.isPlaying} ${this.kind===f.AUDIO?`audioLevel: ${this.getAudioLevel()}`:`framesDecoded: ${this.stat.framesDecoded>0}`}`),this.emit("decode-failed",{error:t}))}updatePlayingState(e){if(this.player.isPlayCalled&&this.player.setTrack(this.playerMediaTrack),this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.isRemotePublished||!this.outMediaTrack)){this.log.info(`abort play, isSubscribed: ${this.isSubscribed} isAvailable: ${this.isRemotePublished} hasTrack: ${!!this.outMediaTrack} `);return}super.updatePlayingState(e)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.remotePublishState.state=this.isRemotePublished?J.ON:J.OFF,this.emit("remote-publish-changed",this.isRemotePublished)}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};d(Mi,"STATE_SUBSCRIBE","subscribe"),M([Eo(5,1)],Mi.prototype,"waitHasMediaTrack",1),M([ye(J.INIT,Mi.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),S.emit(A.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),Rt(521716,!1)],Mi.prototype,"subscribe",1),M([ye(Mi.STATE_SUBSCRIBE,J.INIT,{sync:!0,success(){this.log.info("unsubscribed"),S.emit(A.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],Mi.prototype,"unsubscribe",1);var Ts=Mi;var gi=class extends Ts{constructor(e,t){super(e,t,1);d(this,"volume",0);d(this,"mediaType",1);d(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.audioManager}get dbVolume(){return so.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}onPlayerError(e){this.enableDecodeFrame&&(this._log.warn("use audio decoder"),this.room.enableInsertableStreams())}get enableDecodeFrame(){var e,t;return this.manager?this.manager.decodePipeline.some(r=>r)||((t=(e=this.player.element)==null?void 0:e.error)==null?void 0:t.code)===MediaError.MEDIA_ERR_DECODE&&Ec().AudioDecoder&&hi:!1}get enableDecryptFrame(){return this.manager&&!!this.manager.decodePipeline[0]}decodeFrame(e){if(!this.manager)return e;let t=e;for(let[r,s]of this.manager.decodePipeline.entries()){if(!s)continue;let n={frame:e,track:this};if(r===1&&this.isAvailable&&this.room.role==="audience"&&(n.onAudioFrameNTPTime=({ntp:a,frame:c,hasLeavingTag:l})=>{this.emit("audio-frame-with-ntp",{ntp:a,frame:c,hasLeavingTag:l})}),t=s(n),!t)return}return t}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get isRemotePublished(){return this.user.muteState.audioAvailable}};var id=class extends Ue{constructor(e,t,r,s,n){super(e,{useDefaultProgram:!0,useFbo:!0,name:"alpha",create2d:!0,logger:t});this.setContainer=s;d(this,"initStat",{alphaStitchingType:1});d(this,"end",ot());d(this,"minSize",320);d(this,"maxSize",1280);d(this,"draggable",!1);d(this,"startDragX",0);d(this,"startDragY",0);d(this,"left",0);d(this,"top",0);d(this,"baseWidth",320);d(this,"baseRatio");d(this,"container");this.initStat=n,this.draggable=r,this.bindDragEvents()}bindDragEvents(){let e=this.context._canvas;if(e)if(this.draggable){let t=ke(this.end);de(ce(e,"mousedown"),Bn(this.startDrag.bind(this)),Mr(()=>de(ce(window,"mousemove"),ke(ce(window,"mouseup")))),t,Te(this.doDrag.bind(this))),de(ce(e,"dblclick"),t,Te(this.resetPosition.bind(this))),de(ce(e,"wheel"),t,Te(this.handleZoom.bind(this))),this.renderCanvas()}else{if(!this.container)return;this.container.style.removeProperty("left"),this.container.style.removeProperty("top"),this.end.next()}}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}startDrag(e){e.preventDefault(),e.button===0&&(this.startDragX=e.clientX-this.left,this.startDragY=e.clientY-this.top)}renderCanvas(){let{container:e}=this;e||this.setContainer(),!(!e||!this.baseRatio||!this.draggable)&&(e.style.setProperty("width",`${this.baseWidth}px`),e.style.setProperty("height",`${this.baseWidth/this.baseRatio}px`),e.style.setProperty("position","fixed"),e.style.setProperty("left",`${this.left}px`),e.style.setProperty("top",`${this.top}px`))}doDrag(e){e.preventDefault(),this.left=e.clientX-this.startDragX,this.top=e.clientY-this.startDragY,this.renderCanvas()}handleZoom(e){e.preventDefault();let t=.1,r=e.deltaY,s=this.context._canvas;s&&(this.baseWidth||(this.baseWidth=s.offsetWidth),r<0?this.baseWidth=Math.min(this.baseWidth*(1+t),this.maxSize):this.baseWidth=Math.max(this.baseWidth*(1-t),this.minSize),this.renderCanvas())}resetPosition(){this.left=0,this.top=0,this.renderCanvas()}onRatioReset(){this.renderCanvas()}draw2d(e,t,r,s,n){var _;let{ctx2d:a}=this,c=this.context._canvas;if(!a||!c)return!1;let l=super.draw2d(e,t,r,s,n),u=a.getImageData(0,0,s,n),{data:h}=u,m=!1;if(this.initStat.alphaStitchingType===1){let g=Math.floor(s/2);for(let E=0;E<n;E++)for(let C=0;C<g;C++){let k=(E*s+C)*4,re=C+g,P=(E*s+re)*4,Qe=h[P];h[P+3]=0;let N=Qe>=100;h[k+3]=N?255:0}m=super.draw2d(u,0,0,0,0,g,n),c.width=g}else if(this.initStat.alphaStitchingType===2){let g=Math.floor(n/2);for(let E=0;E<g;E++)for(let C=0;C<s;C++){let k=(E*s+C)*4,P=((E+g)*s+C)*4,Qe=h[P];h[P+3]=0;let N=Qe>=100;h[k+3]=N?255:0}m=super.draw2d(u,0,0,0,0,s,g),c.height=g}return(_=this.context.ctx)==null||_.clearRect(0,0,s,n),l&&m}close(){this.baseRatio=void 0,this.end.next(),this.end.complete()}};function MS(o){return[15,30,45,60].reduce((e,t)=>Math.abs(t-o)<Math.abs(e-o)?t:e)}var Oi=class extends Ts{constructor(e,t,r=4){super(e,t,r);d(this,"mediaType",4);d(this,"source");d(this,"shouldRenderAlpha",!1);d(this,"alphaNode");d(this,"shouldBeDraggable",!0);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.on("first-video-frame",s=>{this.room.emit("first-video-frame",s)})}isAlphaSei(e){if(this.userId!==e.userId||e.seiPayloadType!==50)return!1;let t=new Uint8Array(e.data);return t.length%3!==0||t[0]!==0||t[1]!==1?!1:t}play(e,t){return(he(t==null?void 0:t.canvasRender)?t.canvasRender:et===17)&&!this.source&&this.useCanvasPlayer(),super.play(e,t).then(()=>{this.player.calculateStat(),S.emit("156",{track:this,player:this.player})})}updateAlphaRenderInfo(e){let t=this.isAlphaSei(e);if(t)if(!this.alphaNode)this.shouldRenderAlpha=!0,this.player.shouldRenderAlpha=!0,this.useCanvasPlayer(t[2]);else{let r=t[2];if(this.alphaNode.baseRatio&&this.alphaNode.initStat.alphaStitchingType===r)return;this.alphaNode.initStat={alphaStitchingType:r};let s=this.player.getElement();if(s){let n=s.videoWidth/s.videoHeight;n&&(this.alphaNode.baseRatio=n*(r===1?.5:2),this.alphaNode.onRatioReset())}this.player.canvas&&(this.player.canvas.id=this.generateAlphaCanvasName(r))}}generateAlphaCanvasName(e){let t="alpha",r=hn[e];return`${t}_${r}_${this.userId}`}useCanvasPlayer(e){if(this.log.info(`useCanvasPlayer(), has element:${!!this.player.element}`),!this.player.element)return;let t=new Xe({frameRate:15,logger:this.log,name:this.shouldRenderAlpha&&e?this.generateAlphaCanvasName(e):this.userId});t.create({alpha:this.shouldRenderAlpha,willReadFrequently:this.shouldRenderAlpha});let r=new fo(t,{name:"remotePlayer",logger:this.log});if(this.source=t.createVideoPlayerSource(this.player),this.player.setCanvas(t._canvas),this.shouldRenderAlpha&&e){let s=()=>{!this.player.container||!this.alphaNode||(this.alphaNode.container=this.player.container,this.alphaNode.renderCanvas())},n=new id(t,this.log,this.shouldBeDraggable,s,{alphaStitchingType:e});this.source.connect(n),n.connect(r),this.alphaNode=n}else this.source.connect(r);Ki()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,t),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let t=this.decodeFPS,r=MS(t);if(!z(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),S.emit("157",{track:this,player:this.player}),this.alphaNode&&this.alphaNode.close(),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)}setDraggable(e){this.shouldBeDraggable=e,this.alphaNode&&(this.alphaNode.draggable=e,this.alphaNode.bindDragEvents())}onDecodeDowngradeStateChanged(e){this.emit("decode-downgrade-state-changed",e)}},Es=class extends Oi{constructor(e,t){super(e,t,2);d(this,"mediaType",2);d(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}};var Ss=new Map;S.on(A.JOIN_SUCCESS,({room:o})=>{Ne(o.userId,{eventId:32788})});S.on(A.LEAVE_START,({room:o})=>{Ne(o.userId,{eventId:32789})});S.on(A.LOCAL_TRACK_PUBLISHED,({track:o})=>{if(o.room){let i=32769;o.mediaType===4?i=32768:o.mediaType===2&&(i=32805),Ne(o.room.userId,{eventId:i})}});S.on(A.LOCAL_TRACK_UNPUBLISHED,({track:o})=>{if(o.room){let i=32771;o.mediaType===4?i=32770:o.mediaType===2&&(i=32806),Ne(o.room.userId,{eventId:i})}});S.on(A.TRACK_MUTED,({track:o})=>{o.room&&(o.kind===f.AUDIO?Ne(o.room.userId,{eventId:o.isRemote?32785:32772,remoteUserId:o.isRemote?o.userId:void 0}):Ne(o.room.userId,{eventId:o.isRemote?32784:32773,remoteUserId:o.isRemote?o.userId:void 0}))});S.on(A.TRACK_UNMUTED,({track:o})=>{o.room&&(o.kind===f.AUDIO?Ne(o.room.userId,{eventId:o.isRemote?32787:32774,remoteUserId:o.isRemote?o.userId:void 0}):Ne(o.room.userId,{eventId:o.isRemote?32786:32775,remoteUserId:o.isRemote?o.userId:void 0}))});S.on(A.REMOTE_TRACK_SUBSCRIBED,({track:o})=>{o.room&&(o.mediaType===1&&Ne(o.room.userId,{eventId:32777,remoteUserId:o.userId}),o.mediaType===4&&Ne(o.room.userId,{eventId:32776,remoteUserId:o.userId}),o.mediaType===8&&Ne(o.room.userId,{eventId:32803,remoteUserId:o.userId}))});S.on(A.REMOTE_TRACK_UNSUBSCRIBED,({track:o})=>{o.room&&(o.mediaType===1&&Ne(o.room.userId,{eventId:32779,remoteUserId:o.userId}),o.mediaType===4&&Ne(o.room.userId,{eventId:32778,remoteUserId:o.userId}),o.mediaType===8&&Ne(o.room.userId,{eventId:32804,remoteUserId:o.userId}))});S.on(A.SWITCH_DEVICE_SUCCESS,({track:o})=>{o.room&&Ne(o.room.userId,{eventId:o.kind===f.VIDEO?32780:32781})});S.on(A.LOCAL_TRACK_REPLACED,({track:o})=>{o.room&&Ne(o.room.userId,{eventId:o.kind===f.VIDEO?32782:32783})});S.on(A.SIGNAL_CONNECTION_STATE_CHANGED,({room:o,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&&Ne(o.userId,{eventId:t})});S.on(A.PEER_CONNECTION_STATE_CHANGED,({room:o,prevState:i,state:e,remoteUserId:t})=>{let r=!!t,s;switch(e){case"CONNECTED":i==="RECONNECTING"?s=r?32801:32798:s=r?32793:32792;break;case"DISCONNECTED":i==="RECONNECTING"&&(s=r?32802:32799);break;case"RECONNECTING":s=r?32800:32797;break}s&&Ne(o.userId,{eventId:s,remoteUserId:t})});S.on(A.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({implementation:o,userId:i,remoteUserId:e,codec:t,isHWCodec:r,prevImplementation:s,streamType:n})=>{let a=r?1:0;s||(a=r?3:2);let c={H264:0,H265:1,VP8:2}[t.toUpperCase()],l={eventId:4004,param1:a,param2:c,streamType:n||2};e&&(l.remoteUserId=e,l.eventId=4005),Ne(i,l),v.addEnum({key:e?514701:513701,value:a}),v.addEnum({key:e?514700:513700,value:c})});S.on(A.LOCAL_TRACK_RECAPTURE,({track:o,error:i})=>{if(o.userId){let e={eventId:2003,param1:0};o.kind===f.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType=o.streamType==="auxiliary"?7:2,i&&(e.param1=8)),Ne(o.userId,e)}});function Ne(o,i){let e=L(O({},i),{timestamp:Fi()});Ss.has(o)?Ss.get(o).push(e):Ss.set(o,[e])}function Ef(o){if(Ss.has(o)){let i=Ss.get(o).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 Ss.delete(o),i}return[]}function Sf(...o){return Q((i,e)=>function(...t){return OS.call(this,o,t,e,this._name),i.apply(this,t)})}function OS(o,i,e,t){try{if(Ie(o))for(let r=0;r<o.length;r++)rd.call(this,{rule:o[r],value:i[r],key:o[r].name,fnName:e,className:t});else rd.call(this,{rule:o,value:i[0],key:o.name,fnName:e,className:t})}catch(r){throw R.error(r),r}}function rd({rule:o,value:i,key:e,fnName:t,className:r}){if(T(i)){if(o.required)throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_PARAMETER_REQUIRED,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(T(o.defaultValue))return;i=o.defaultValue}if(Array.isArray(o.type)){let a=!1;for(let c=0;c<o.type.length;c++)o.type[c]===null&&i===null&&(a=!0),le(o.type[c])&&i instanceof o.type[c]&&(a=!0),ie(o.type[c])&&Me(i)===o.type[c].toLowerCase()&&(a=!0);if(!a)throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_PARAMETER_TYPE,data:{key:e,rule:{type:o.type.map(c=>jr(c)?xo(c):ie(c)?c:Me(c))},fnName:t,value:i},link:{className:r,fnName:t}})})}else if(!T(o.type)&&Me(i)!==o.type)throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_PARAMETER_TYPE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(o.allowEmpty===!1){let a=z(i)&&(i===0||Number.isNaN(i)),c=ie(i)&&i.trim()==="";if(a||c)throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_PARAMETER_EMPTY,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})})}if(o.notLessThanZero&&z(i)&&i<0)throw new D({code:I.INVALID_PARAMETER,message:H({key:F.CANNOT_LESS_THAN_ZERO,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(!T(o.min)&&z(i)&&i<o.min)throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_PARAMETER_MIN,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(!T(o.max)&&z(i)&&i>o.max)throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_PARAMETER_MAX,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(ie(o.instanceOf)){if(!i||i._name!==o.instanceOf)throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})})}else if(le(o.instanceOf)&&!(i instanceof o.instanceOf))throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(o.values&&!o.values.includes(i))throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_PARAMETER_RANGE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});let{properties:s}=o;dt(s)&&yt(i)&&Object.keys(s).forEach(a=>{rd.call(this,{rule:s[a],value:i&&i[a],key:`${e}.${a}`,fnName:t,className:r})});let{arrayItem:n}=o;dt(n)&&Ie(i)&&i.forEach((a,c)=>{rd.call(this,{rule:n,value:a,key:`${e}[${c}]`,fnName:t,className:r})}),le(o.validate)&&o.validate.call(this,i,e,t,r,this)}var If=qe(at(),1);var od=class extends If.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:s,role:n}=e;if(this.userMap.has(t))return;let a={userId:r,tinyId:s,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 s=`peer leave [${e}]`;T(t)||(s+=`:${rl[t]}`),this._log.info(s);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(s=>s[this.key]===t[this.key])<0){this._log.info(`remote [${r}] unpublish`);let s=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(r),this.emit("6",{prevMuteState:s,muteState:t.muteState,flag:0})}}),e.forEach(t=>{var u;let r=t[this.key];if(r===this.mySelfId){this.emit("7",t);return}let{flag:s,userId:n,tinyId:a}=t,c=Kt(s,n),l=(u=this.remotePublishedUserMap.get(r))==null?void 0:u.muteState;if(l){let h=this.remotePublishedUserMap.get(r);h&&h.flag!==s&&(h.flag=s,this._log.info(`remote publish updated: ${JSON.stringify(h.muteState)}`),this.emit("6",{prevMuteState:l,muteState:c,flag:s}))}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:Kt(0,n),muteState:c,flag:s})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function Ch({timesInSecond:o,maxSizeInSecond:i,getSize:e}){return Q((t,r)=>{let s=new WeakMap;return S.on(A.ROOM_DESTROY,({room:n})=>s.delete(n)),function(...n){let a=s.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},s.set(this,a)),a.timestamp===0?a.timestamp=Date.now():Date.now()-a.timestamp>1e3&&(a.timestamp=Date.now(),a.callCountInSecond=0,a.totalSizeInSecond=0),e&&(a.totalSizeInSecond+=e(...n)),a.timestamp!==0&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=o||a.totalSizeInSecond>i))throw new D({code:I.INVALID_OPERATION,message:H({key:F.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=o,isSize:a.totalSizeInSecond>i,name:r,timesInSecond:o,maxSizeInSecond:i}})});a.callCountInSecond++,t.call(this,...n)}})}var kS="2025-12-03 22:09:33",Af=!0,Cf=function(){var o;if(Af){Af=!1,R.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${ft}/en/index.html`),console.info(`* Changelog: ${ft}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),R.info("TRTC Web SDK Version:",$e),oi||R.debug("Build Time:",kS);let i=`UA: ${navigator.userAgent}
|
|
53
53
|
CPU core: ${navigator.hardwareConcurrency}, GPU: ${Pl()}`,e=navigator.deviceMemory;e&&(i+=`, minRAM: ${e}GB`),R.info(i),R.info(`URL: ${location.href}${((o=self.frameElement)==null?void 0:o.tagName)==="IFRAME"?" in iframe":""}`),Yr().then(t=>{t&&R.info(ti)})}};var So={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 $={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},wt=(y=>(y[y.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",y[y.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",y[y.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",y[y.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",y[y.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",y[y.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",y[y.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",y[y.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",y[y.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",y[y.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",y[y.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",y[y.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",y[y.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",y[y.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",y[y.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",y[y.INVALID_ROOM_ID_REQUIRED=5015]="INVALID_ROOM_ID_REQUIRED",y[y.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",y[y.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",y[y.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",y[y.INVALID_ROOM_ID_TYPE_MISMATCH=5019]="INVALID_ROOM_ID_TYPE_MISMATCH",y[y.INVALID_ROOM_ID_DUPLICATE=5020]="INVALID_ROOM_ID_DUPLICATE",y[y.INVALID_OPERATION=5100]="INVALID_OPERATION",y[y.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",y[y.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",y[y.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",y[y.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",y[y.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",y[y.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",y[y.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",y[y.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",y[y.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",y[y.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",y[y.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",y[y.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",y[y.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",y[y.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",y[y.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",y[y.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",y[y.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",y[y.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",y[y.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",y[y.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",y[y.DEVICE_ERROR=5300]="DEVICE_ERROR",y[y.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",y[y.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",y[y.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",y[y.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",y[y.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",y[y.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",y[y.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",y[y.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",y[y.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",y[y.NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX=5310]="NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX",y[y.SERVER_ERROR=5400]="SERVER_ERROR",y[y.NEED_TO_BUY=5401]="NEED_TO_BUY",y[y.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",y[y.OPERATION_FAILED=5500]="OPERATION_FAILED",y[y.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",y[y.REJOIN_FAILED=5502]="REJOIN_FAILED",y[y.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",y[y.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",y[y.VIDEO_ENCODE_FAILED=5505]="VIDEO_ENCODE_FAILED",y[y.AUDIO_ENCODE_FAILED=5506]="AUDIO_ENCODE_FAILED",y[y.VIDEO_DECODE_FAILED=5507]="VIDEO_DECODE_FAILED",y[y.AUDIO_DECODE_FAILED=5508]="AUDIO_DECODE_FAILED",y[y.OPERATION_ABORT=5998]="OPERATION_ABORT",y[y.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",y))(wt||{});function yf({code:o,params:i,enableDocLink:e=!1}){let t="",r,s=wt[o];try{r=Rf[s]}catch(n){r=Rf.UNKNOWN_ERROR}return le(r)?t=r(i):ie(r)&&(t=r),i.fnName&&!t.includes(i.fnName)&&(t[t.length-1]!=="."&&(t+="."),t+=` thrown from ${i.fnName}()`),e&&(t+=" doc:"),t}var Rf=L(O({},Je),{INVALID_PARAMETER({fnName:o}){return`the parameters of the '${o}' you called does not meet the requirements, please check the API documentation.`},INVALID_PARAMETER_REQUIRED({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' is a required param when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_TYPE({key:o,rule:i,fnName:e,value:t}){let r=`${o||i.name}`,s="";return Array.isArray(i.type)?s=i.type.join("|"):s=i.type,`'${r}' must be type of ${s} when calling ${e}(), received type: ${Me(t)}.`},INVALID_PARAMETER_EMPTY({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' cannot be '${t}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:o,rule:i,fnName:e,value:t}){let r=`${o||i.name}`,s=`${i.instanceOf.name||i.instanceOf}`;return`'${r}' must be instanceof ${s} when calling ${e}(), received type: ${Me(t)}.`},INVALID_PARAMETER_RANGE({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' must be one of ${i.values.join("|")} when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_LESS_THAN_ZERO({key:o,rule:i,fnName:e}){return`'${o||i.name}' cannot be less than 0 when calling ${e}().`},INVALID_PARAMETER_MIN({key:o,rule:i,value:e}){return`the min value of ${o||i.name} is ${i.min}, received: ${e}.`},INVALID_PARAMETER_MAX({key:o,rule:i,value:e}){return`the max value of ${o||i.name} is ${i.max}, received: ${e}.`},INVALID_ELEMENT_ID({key:o,fnName:i}){return`'${o}' is not found in the document object when calling ${i}().`},INVALID_ELEMENT_ID_TYPE({key:o,fnName:i,type:e}){return`the element corresponding to '${o}' must be instanceof HTMLElement when calling ${i}(), received: ${e}.`},INVALID_STREAM_ID({key:o}){return`'${o}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},INVALID_ROOM_ID_STRING({key:o}){return`'${o}' must be a valid string.`},INVALID_ROOM_ID_INTEGER({key:o}){return`'${o}' must be an integer between [1, 4294967294].`},INVALID_ROOM_ID_INTEGER_STRING({key:o}){return`'${o}' 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:o}){return`The type of target roomId must match the current roomId. Current room is using '${o}', but received '${o==="strRoomId"?"roomId":"strRoomId"}'.`},INVALID_ROOM_ID_DUPLICATE({key:o}){return`the target '${o}' must not be the same as the current '${o}'.`},INVALID_STREAM_TYPE:({fnName:o})=>`'streamType' is required when 'userId' is not '*', calling ${o}()`,INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION({fnName:o}){return`the API '${o}' you called does not meet the requirements, please check the API documentation.`},INVALID_OPERATION_NOT_JOINED({fnName:o}){return`cannot ${o} because you are not enter room yet.`},INVALID_OPERATION_REMOTE_USER_NOT_EXIST({fnName:o,value:i}){return`cannot ${o} because remote user(userId: ${i.userId}) does not publishing stream.`},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST({fnName:o,value:i}){return`cannot ${o} because remote user(userId: ${i.userId}) does not publishing ${i.streamType} video.`},INVALID_OPERATION_REPEAT_CALL({fnName:o}){return`you are already ${o}(), cannot repeated call '${o}'.`},INVALID_OPERATION_NEED_VIDEO({fnName:o}){return`cannot call '${o}' because the camera is not turned on.`},INVALID_OPERATION_NEED_AUDIO({fnName:o}){return`cannot call '${o}' because the microphone or screen share is not turned on.`},INVALID_BUFFER_EMPTY:({key:o})=>`the buffer size of paramerter '${o}' 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:o})=>`you need to call ${o}() after publish stream.`,ENV_NOT_SUPPORTED({fnName:o}){return`the current browser does not support the capability of the function '${o}' 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:o}){return`cannot call ${o} because the browser version is too low, please upgrade to the latest version`},DEVICE_ERROR({fnName:o,error:i}){return`'${o}' got device exception${i?`, error: ${i.toString()}.`:"."}`},DEVICE_NOT_FOUND_ERROR({fnName:o,deviceType:i=Io(o),error:e}){return`NotFoundError, no ${i} detected, please check your device and the configuration on '${o}'${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_ALLOWED_ERROR({fnName:o,deviceType:i=Io(o),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:o,deviceType:i=Io(o),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:o,deviceType:i=Io(o),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:o,deviceType:i=Io(o),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:o,deviceType:i=Io(o),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:o,deviceType:i=Io(o),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:o}){return`camera recover capture failed ${(o==null?void 0:o.name)||""}: ${(o==null?void 0:o.originMessage)||(o==null?void 0:o.message)}`},MICROPHONE_RECOVER_FAILED({error:o}){return`microphone recover capture failed ${(o==null?void 0:o.name)||""}: ${(o==null?void 0:o.originMessage)||(o==null?void 0:o.message)}`},OPERATION_FAILED({fnName:o,error:i}){return`'${o}' 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:o}){return`an error was caught on trtc.on('${o}', handler), please check your code on 'handler'.`},VIDEO_CONTEXT_ERROR({reason:o,error:i}){return`video context error ${o} ${(i==null?void 0:i.name)||""} ${(i==null?void 0:i.message)||""}`},SERVER_ERROR({fnName:o,error:i}){return`'${o}' got server error: ${i==null?void 0:i.toString()}, please check the SDK documentation.`},NEED_TO_BUY({value:o,url:i}){return`You need to buy packages for ${o}. Refer to: ${i}`},ACCOUNT_NO_MONEY:({fnParams:o})=>`your TRTC account run out of credit, please recharge.${o.sdkAppId?` SDKAppId: ${o.sdkAppId}`:""}`,OPERATION_ABORT({fnName:o}){return`'${o}' abort`},UNKNOWN_ERROR({fnName:o,error:i}){return`'${o}' throw unknown exception${i?`, error: ${i.toString()}.`:"."}`}});function Io(o){if(!o)return"camera";let i=o.toLowerCase();return i.includes("screen")?"screen share":i.includes("audio")?"microphone":"camera"}var Rh=class o extends Error{constructor({code:e,extraCode:t,message:r="",messageParams:s,fnName:n="",originError:a,data:c}){var u;let l;r?l=r:l=yf({code:e===$.SERVER_ERROR?e:t||e,params:O({fnName:n,error:a},s)});super(l);d(this,"name","RtcError");d(this,"code");d(this,"extraCode");d(this,"functionName");d(this,"message");d(this,"data");d(this,"handler");d(this,"originError");this.name=wt[e],this.code=e,this.extraCode=t,this.functionName=n,this.originError=a,this.message=l,this.data=c,this.extraCode===5302&&((u=this.originError)!=null&&u.message.includes("system"))&&(this.handler=()=>{let h={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},m={startLocalVideo:"webcam",startLocalAudio:"microphone"},_=document.createElement("a");Qr?_.href=`ms-settings:privacy-${m[this.functionName]}`:ri&&(_.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${h[this.functionName]}`),_.href.length>0&&_.click()})}static convertFrom(e,t,r){let s=e;if(e instanceof D){let{stack:n}=e,a={code:$.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case I.INVALID_PARAMETER:a.code=$.INVALID_PARAMETER,a.message=e.message;break;case I.INVALID_OPERATION:a.code=$.INVALID_OPERATION;break;case I.NOT_SUPPORTED:case I.NOT_SUPPORTED_H264:a.code=$.ENV_NOT_SUPPORTED,e.getCode()===I.NOT_SUPPORTED_H264&&(a.extraCode=e.message.includes(Je.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=$.SERVER_ERROR,a.extraCode=e.getExtraCode();break;case I.API_CALL_ABORTED:a.code=$.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=PS(e.name));break;case I.VIDEO_ENCODE_FAILED:a.extraCode=5505;case I.AUDIO_ENCODE_FAILED:a.extraCode=5506,a.code=$.OPERATION_FAILED;break;case I.UNKNOWN:break;default:a.code=$.OPERATION_FAILED}s=new o(a),n&&(s.stack+=n.substr(n.indexOf(`
|
|
54
54
|
`)))}else{if(e instanceof o)return e;s=new o({code:$.UNKNOWN_ERROR,fnName:t,originError:e})}return s}};function PS(o){let i;switch(o){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 V=Rh;function ki(o){return o==="sub"?"auxiliary":o==="auxiliary"?"sub":"main"}function qn(o){return o===So.QOS_PREFERENCE_CLEAR?"detail":o===So.QOS_PREFERENCE_SMOOTH?"motion":""}function Is(o,i){let e=i?zd:pr;return Il(o)?O(O({},e),o):zt[o]?zt[o]:e}var bf={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}}},vf={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}}},As={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(o,i,e){if(ie(o)&&!document.getElementById(o))throw new V({code:$.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:i}})}},Nf={name:"userId",required:!0,type:"string"},Df={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{type:["string","object"],properties:{bitrate:{type:"number"},channelCount:{type:"number"}}},echoCancellation:{values:[!0,!1,"remote-only","all"]},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function Cs(o,i){if(!o)throw new V({code:$.INVALID_OPERATION,extraCode:5101,fnName:i})}function Mf(o,i,e){if(!o)throw new V({code:$.INVALID_OPERATION,extraCode:5102,fnName:i,messageParams:{value:e}})}function Of(o,i,e){if(!(/^[1-9]\d*$/.test(String(o))&&o<4294967295))throw new V({code:$.INVALID_PARAMETER,extraCode:5013,fnName:i,messageParams:{key:e}})}function kf(o,i,e){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(o))throw new V({code:$.INVALID_PARAMETER,extraCode:5012,fnName:i,messageParams:{key:e}})}var Fw={type:"number",notLessThanZero:!0},wS=(o,i)=>o.width*o.height>=i.width*i.height&&o.frameRate>=i.frameRate&&o.bitrate>=i.bitrate;function Pf(o){var t;if(!((t=o==null?void 0:o.option)!=null&&t.small))return;if(!Tc()){R.warn("small stream is not supported"),delete o.option.small;return}let i=Is(o.option.profile),e=Is(o.option.small,!0);if(!wS(i,e)){R.warn(`small stream profile must be less than big stream profile. Big: ${JSON.stringify(i)}, Small: ${JSON.stringify(e)}`),delete o.option.small;return}}var LS={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(o,i,e){if(this._room.isJoined)throw new V({code:$.INVALID_OPERATION,extraCode:5104,fnName:e});if(o.roomId){if(ie(o.roomId))throw new V({code:$.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:i}});Of(o.roomId,e,i)}else if(o.strRoomId)kf(o.strRoomId,e,i);else throw new V({code:$.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:As,mute:{type:["boolean","string"]},publish:{type:"boolean"},capture:{required:!1,type:"boolean"},option:bf},validate(o){var i,e;if(!((i=o==null?void 0:o.option)!=null&&i.videoTrack)&&Zi())throw new V({code:$.ENV_NOT_SUPPORTED,extraCode:5201});(e=o==null?void 0:o.option)!=null&&e.small&&Pf(o)}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:L(O({},As),{required:!1}),publish:{type:"boolean"},capture:{required:!1,type:"boolean"},mute:{type:["boolean","string"]},option:bf},validate(o){var i;(i=o==null?void 0:o.option)!=null&&i.small&&Pf(o)}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:Df},validate(o){var i;if(!((i=o==null?void 0:o.option)!=null&&i.audioTrack)&&Zi())throw new V({code:$.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:Df}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:As,publish:{type:"boolean"},option:vf},validate(o,i,e,t,r){var s;if(!((s=o==null?void 0:o.option)!=null&&s.videoTrack)){if(Zi())throw new V({code:$.ENV_NOT_SUPPORTED,extraCode:5201});if(!_n())throw new V({code:$.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:As,publish:{type:"boolean"},option:vf}},muteRemoteAudio:[Nf,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[Nf,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:As,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(o,i,e){Cs(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(o.userId);if(Mf(!!t,e,o),t&&(o.streamType==="main"&&!t.muteState.videoAvailable||o.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new V({code:$.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:o}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:L(O({},As),{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(o,i,e){Cs(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(o.userId);if(Mf(!!t,e,o),t&&(o.streamType==="main"&&!t.muteState.videoAvailable||o.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new V({code:$.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:o}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(o,i,e){if(o.userId!=="*"&&T(o.streamType))throw new V({code:$.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(o,i,e){Cs(this._room.isJoining||this._room.isJoined,e)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(o,i,e,t){if(!En)throw new V({code:$.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new V({code:$.INVALID_OPERATION,fnName:e,extraCode:5108});if(o.byteLength>1e3)throw new V({code:$.INVALID_PARAMETER,extraCode:5018,fnName:e});if(o.byteLength===0)throw new V({code:$.INVALID_PARAMETER,extraCode:5017,messageParams:{key:i},fnName:e});Cs(this._room.isJoined,e)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(o,i,e){if(!o&&!this._room.isMainStreamPublished||o&&!this._room.isAuxStreamPublished)throw new V({code:$.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(o,i,e,t){if(o.byteLength>1e3)throw new V({code:$.INVALID_PARAMETER,extraCode:5018,fnName:e});if(o.byteLength===0)throw new V({code:$.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:i}})}}},validate(o,i,e){if(Cs(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new V({code:$.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:i}})}},switchRoom:{name:"switchRoomConfig",type:"object",required:!0,validate(o,i,e){if(Cs(this._room.isJoined,e),this._room.useStringRoomId&&o.strRoomId===this._room.roomId||!this._room.useStringRoomId&&o.roomId===Number(this._room.roomId))throw new V({code:$.INVALID_PARAMETER,extraCode:5020,fnName:e,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(o.roomId&&this._room.useStringRoomId||!o.roomId&&o.strRoomId&&!this._room.useStringRoomId)throw new V({code:$.INVALID_PARAMETER,extraCode:5019,fnName:e,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(o.roomId)Of(o.roomId,e,i);else if(o.strRoomId)kf(o.strRoomId,e,i);else throw new V({code:$.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}}}},Ge={TRTC:LS};var ut=class extends Error{};function xS(o,i){let e=Gr(o);for(let t=0;t<i.length;t++)ei(e[t],i[t]);return e}function US(o){this._resolve=Promise.resolve(o)}function VS(o){this._reject=Promise.reject(o)}var Pr=class Pr{constructor(i,e){this.instance=i;this.group=e;d(this,"started",!1);d(this,"ops",[]);d(this,"startSame",()=>!0);d(this,"mergeUpdate",xS);let t=Pr.instances.get(i);t?t.set(e,this):Pr.instances.set(i,new Map([[e,this]]))}static get(i,e){if(!e)return;let t=Pr.instances.get(i);return t&&t.get(e)||new Pr(i,e)}static gets(i,e){let t=Pr.instances.get(i),r=[];return t&&t.forEach((s,n)=>{e.test(n)&&r.push(s)}),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},s=a=>{var c,l;throw this.ops.shift(),i===0&&((c=this.currentOp)==null?void 0:c.type)===2&&this.ops.shift().reject(new ut("start failed")),(l=this.currentOp)==null||l.action(),a},n={type:i,action:()=>e(...n.args).then(r,s),args:t,resolve:US,reject:VS};try{switch(this.state){case 1:if(i===0)throw new ut("already started");break;case 4:if(i===2)throw new ut("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,s)}cacheOp(i){if(this.ops.length===1)switch(this.state){case 0:case 2:if(i.type===0)throw new ut("already start");break;case 3:switch(i.type){case 2:throw new ut("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new ut("unknown state")}else switch(i.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let t=new ut("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 ut("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new ut("start not allowed after update");case 0:throw new ut("duplicate start");case 3:if(this.startSame(this.currentOp.args,i.args))throw this.ops.pop().reject(new ut("keep start")),new ut("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(Pr,"instances",new WeakMap);var nr=Pr;var nd=new WeakMap,ad=(o,i)=>{if(i instanceof ut){let{stack:e}=i;i=new V({code:$.OPERATION_ABORT,message:`${o} abort: ${i.message}`,fnName:o}),e&&(i.stack+=e.substr(e.indexOf(`
|
|
55
55
|
`)))}throw i};function wr(o,i){return Q((e,t)=>function(...r){let s=nr.get(this,typeof o=="string"?o:o.call(this,...r));return s?(i&&(s.startSame=i.bind(this)),s.action(0,e.bind(this),r).catch(ad.bind(null,t))):e.apply(this,r)})}function Ao(o,i){let{merge:e,debounce:t}=i||{};return Q((r,s)=>function(...n){let a=nr.get(this,typeof o=="string"?o:o.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((u,h)=>{var g,E;let m=(g=nd.get(this))==null?void 0:g.get(l(...n));if(m){let{timeoutId:C,resolve:k}=m;clearTimeout(C),k()}let _=setTimeout(()=>{if(a.state===3||a.state===4)return u();a.action(2,r.bind(this),n).catch(ad.bind(null,s)).then(u,h)},c);nd.has(this)?(E=nd.get(this))==null||E.set(l(...n),{timeoutId:_,resolve:u}):nd.set(this,new Map([[l(...n),{timeoutId:_,resolve:u}]]))})}return a.action(2,r.bind(this),n).catch(ad.bind(null,s))})}function Lr(o){return Q((i,e)=>function(...t){let r=typeof o=="function"?o.call(this,...t):o;if(r instanceof RegExp)return Promise.all(nr.gets(this,r).map(n=>n.action(3,()=>Promise.resolve(),t))).then(()=>i.call(this,...t));let s=nr.get(this,r);return s?s.action(3,i.bind(this),t).catch(ad.bind(null,e)):i.apply(this,t)})}function xr(){return function(o,i,e){return o.prototype[i]=function(){let t=this._log||console,r=`"${i}" is a static method. Use TRTC.${i}() instead. See: ${ft}/en/TRTC.html#.${i}`;t.warn(r)},e}}var x={ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",KICKED_OUT:"kicked-out",REMOTE_USER_ENTER:"remote-user-enter",REMOTE_USER_EXIT:"remote-user-exit",REMOTE_AUDIO_AVAILABLE:"remote-audio-available",REMOTE_AUDIO_UNAVAILABLE:"remote-audio-unavailable",REMOTE_VIDEO_AVAILABLE:"remote-video-available",REMOTE_VIDEO_UNAVAILABLE:"remote-video-unavailable",AUDIO_VOLUME:"audio-volume",AUDIO_FRAME:"audio-frame",NETWORK_QUALITY:"network-quality",CONNECTION_STATE_CHANGED:"connection-state-changed",AUDIO_PLAY_STATE_CHANGED:"audio-play-state-changed",VIDEO_PLAY_STATE_CHANGED:"video-play-state-changed",SCREEN_SHARE_STOPPED:"screen-share-stopped",DEVICE_CHANGED:"device-changed",PUBLISH_STATE_CHANGED:"publish-state-changed",TRACK:"track",STATISTICS:"statistics",SEI_MESSAGE:"sei-message",CUSTOM_MESSAGE:"custom-message",VIDEO_DECODE_DOWNGRADE_STATE_CHANGED:"video-decode-downgrade-state-changed",LAYER_DATA:"layerData",FIRST_VIDEO_FRAME:"first-video-frame",PERMISSION_STATE_CHANGE:"permission-state-change",VIDEO_SIZE_CHANGED:"video-size-changed"},wf=new Set([x.AUDIO_VOLUME,x.AUDIO_FRAME,x.NETWORK_QUALITY,x.STATISTICS,x.SEI_MESSAGE,x.CUSTOM_MESSAGE,x.LAYER_DATA]);var vh={};Vi(vh,{ScheduleRequestType:()=>Uf,getAbilityConfig:()=>HS,getScheduleDomain:()=>ld,isNeedToSchedule:()=>cd,scheduleProxy:()=>Pi,sendScheduleRequest:()=>bh,setIsNeedToSchedule:()=>Lt,setScheduleProxy:()=>dd});var yh=null,xf=0,FS=48*3600*1e3,cd=!0;typeof document!="undefined"&&document.head.insertAdjacentHTML("beforeend",Object.values($i).map(o=>`<link rel="dns-prefetch" href="https://${o}">`).join(`\r
|
|
@@ -61,7 +61,7 @@ CPU core: ${navigator.hardwareConcurrency}, GPU: ${Pl()}`,e=navigator.deviceMemo
|
|
|
61
61
|
${e.map(l=>l.toString()).join(`
|
|
62
62
|
`)};(${t})();${r}})()`,n=new Blob([s],{type:"text/javascript"}),a=URL.createObjectURL(n),c=new Worker(a);return URL.revokeObjectURL(a),c}function Bf({TRTC:o,room:i,errorModule:e,assetsPath:t}){return{TRTC:o,LocalMixVideoTrack:go,LocalVideoTrack:je,LocalScreenTrack:Pt,room:i,assetsPath:t,fileDownloader:jn,innerEmitter:S,INNER_EVENT:A,constants:ol,environment:Ko,utils:Eh,eventLogger:se,log:this.room.getLogger(),loggerManager:R,errorModule:e,kvStatManager:v,rtcDectection:bi,trtc:this,rx:gh,enums:Yl,schedule:vh,getDevices:ds,initVisionTaskRegistry:(r,s="/mediapipe/vision.js")=>p(this,null,function*(){window.VisionTaskRegistry||(yield jn.loadScript(`${r}/${s}`.replace(/([^:]\/)\/+/g,"$1"))),yield(yield window.VisionTaskRegistry.getInstance(r)).preloadModels([window.VisionTaskType.ImageSegmenter])}),audioContext:Ee(),deviceDetector:be,AudioPlayer:us,RemoteAudioPlayer:hs,VideoPlayer:it,showAutoPlayDialog:ns,Timer:oe,clearStarted:(r,s)=>{let n=r.getAlias(),a=nr.instances.get(this);if(a)if(s){let c=a.get(n+s);if(!c)return;c.started=!1}else a.forEach((c,l)=>{l.startsWith(n)&&(c.started=!1)})},startGetPCM:Gn,createAudioNode:On,getNetworkTimeOffset:Em,validateSourceNode:()=>{var r;if(K&&!((r=this.room.audioManager._localAudioPipline)!=null&&r.source.node))throw new V({code:$.DEVICE_ERROR,extraCode:5310,message:"The audio processing plugin cannot be used due to the microphone's sampling rate is not 48KHz in Firefox. Please switch to another browser such as Chrome."})},createScriptTransformWorker:ud}}var Hf=(o,i)=>{let{emit:e}=o;return o.emit=(...t)=>{try{return e.apply(o,t)}catch(r){let s=H({key:F.CATCH_HANDLER_ERROR,data:{name:i,event:t[0]},addDocLink:!1});return R.warn(`${s}
|
|
63
63
|
|
|
64
|
-
${r.stack}`),!1}},o};var Rs=new WeakMap;function $f(o){let i=Rs.get(o);i&&(i.forEach(e=>clearTimeout(e)),Rs.delete(o))}function Wf(o,i){return Q((e,t)=>function(...r){let s=Rs.get(this);s||(s=new Map,Rs.set(this,s));let n=i(...r),a=s.get(n);if(!a||a<=0){e.apply(this,r);let c=setTimeout(()=>{var l;(l=Rs.get(this))==null||l.delete(n)},o);s.set(n,c)}else{clearTimeout(a);let c=window.setTimeout(()=>{var l;e.apply(this,r),(l=Rs.get(this))==null||l.delete(n)},o);s.set(n,c)}})}var qf="trtc-sdk-v5",wh="5.14.2-beta.8";function st(...o){return Q((i,e)=>function(...t){try{md.call(this,o,t,e,this._name)}catch(r){return Promise.reject(r)}return i.apply(this,t)})}function Lh(...o){return Q((i,e)=>function(...t){try{md.call(this,o,t,e,this._name)}catch(r){throw r}return i.apply(this,t)})}function md(o,i,e,t){if(Ie(o))for(let r=0;r<o.length;r++)hd.call(this,{rule:o[r],value:i[r],key:o[r].name,fnName:e,className:t});else hd.call(this,{rule:o,value:i[0],key:o.name,fnName:e,className:t})}function hd({rule:o,value:i,key:e,fnName:t,className:r}){function s(c){return{code:$.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:o,value:i}}}if(T(i)){if(o.required)throw new V(s(5001));if(T(o.defaultValue)){le(o.validate)&&o.validate.call(this,i,e,t,r,this);return}i=o.defaultValue}if(Array.isArray(o.type)){let c=!1;for(let l=0;l<o.type.length;l++)o.type[l]===null&&i===null&&(c=!0),le(o.type[l])&&i instanceof o.type[l]&&(c=!0),ie(o.type[l])&&Me(i)===o.type[l].toLowerCase()&&(c=!0);if(!c)throw new V({code:$.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:o.type.map(l=>jr(l)?xo(l):ie(l)?l:Me(l))},value:i}})}else if(!T(o.type)&&Me(i)!==o.type)throw new V(s(5002));if(o.allowEmpty===!1){let c=z(i)&&(i===0||Number.isNaN(i)),l=ie(i)&&i.trim()==="";if(c||l)throw new V(s(5003))}if(o.notLessThanZero&&z(i)&&i<0)throw new V(s(5006));if(!T(o.min)&&z(i)&&i<o.min)throw new V(s(5007));if(!T(o.max)&&z(i)&&i>o.max)throw new V(s(5008));if(ie(o.instanceOf)){if(!i||i._name!==o.instanceOf)throw new V(s(5004))}else if(le(o.instanceOf)&&!(i instanceof o.instanceOf))throw new V(s(5004));if(Array.isArray(o.values)&&!o.values.includes(i))throw new V(s(5005));let{properties:n}=o;dt(n)&&yt(i)&&Object.keys(n).forEach(c=>{hd.call(this,{rule:n[c],value:i&&i[c],key:`${c}`,fnName:t,className:r})});let{arrayItem:a}=o;dt(a)&&Ie(i)&&i.forEach((c,l)=>{hd.call(this,{rule:a,value:c,key:`${e}[${l}]`,fnName:t,className:r})}),le(o.validate)&&o.validate.call(this,i,e,t,r,this)}function Ae(o={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t,ignoreLog:r,ignoreErrorLog:s}=o;return Q((n,a)=>function(...c){var _,g,E;function l(C,k,re){if(re&&re.includes(C))return"hided";if(e){let P=e(...c);if(c[P.argIndex]===k)return P.value}if(k===c||C in c)return k;try{return k instanceof HTMLElement?`id: ${k.id} type:${Me(k)}`:k instanceof MediaStreamTrack?Oa(k):(JSON.stringify(k),k)}catch(P){return`type:${Me(k)}`}}let u=this._log||R;if(r!=null&&r(...c))return n.apply(this,c);c.length>0?u.info(`${a}() ${JSON.stringify(c,(C,k)=>l(C,k,["userSig","privateMapKey"]))}`):u.info(`${a}()`);let h=t?t(...c):uc[a],m=(s==null?void 0:s(...c))||!1;try{let C=n.apply(this,c),k=U();if(Tr(C)){let re=`${a.includes("Plugin")?`${((g=(_=c[0]).getName)==null?void 0:g.call(_))||""} `:" "}`;return C.then(P=>(u.info(`${a}() success ${re}${i.call(this,...c)}`),v.addSuccessEvent({key:h,cost:U()-k}),P)).catch(P=>{var b;P=V.convertFrom.call(this,P,a,c.length===1?c[0]:c);let Qe=P.extraCode||P.code,N=(b=P.message)!=null&&b.includes(Qe)?"":` code:${Qe}`;throw m||u.error(`${a}() failed ${re}${i.call(this,...c)} ${P}${N} params: ${JSON.stringify(c,l)}`),v.addFailedEvent({key:h,error:P}),P})}return v.addSuccessEvent({key:h}),C}catch(C){C=V.convertFrom.call(this,C,a);let k=C.extraCode||C.code,re=(E=C.message)!=null&&E.includes(k)?"":` code:${k}`;throw m||u.error(`${a}() failed ${C}${re} params: ${JSON.stringify(c,l)}`),v.addFailedEvent({key:h,error:C}),C}})}var pd=o=>Q((i,e)=>function(t,r){return p(this,null,function*(){let s=this._plugins.get(t);if(!s)throw this._log.error(`plugin ${String(t)} is not found`),new V({code:$.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});if(le(s.constructor.isSupported)&&!s.constructor.isSupported())throw this._log.error(`plugin ${String(t)} is not supported`),new V({code:$.ENV_NOT_SUPPORTED,message:`plugin ${String(t)} is not supported`,extraCode:5210,fnName:e});return md.call(this,s.getValidateRule(o),[r],e,"TRTC"),i.call(this,s,r)})});var fd=0,xh,ar=class ar{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");fd=fd+1,this.log=i.log.createChild({id:`${this.getAlias()}${fd}`}),this.log.info(`created id=${this.getAlias()}${fd}`),this.installEvent()}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,s){if(!i.room.audioManager.hasAudioTrack&&!i.room.audioManager.hasScreenAudioTrack)throw new V({code:$.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return xh||(xh=this.doPreload(i)),xh}doPreload(i){return p(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield tr(this.audioContext,t)}catch(r){this.log.error(`preload audioProcessor failed. ${r}`)}finally{URL.revokeObjectURL(t)}})}getName(){return ar.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(i){switch(i){case"start":return ar.getStartValidateRule(this.core);case"update":return ar.updateValidateRule;case"stop":return ar.stopValidateRule}}start(i){return p(this,null,function*(){var m,_,g,E;let{room:e}=this.core,{sdkAppId:t,userId:r,userSig:s,assetsPath:n=this.core.assetsPath,audioReference:a,processLevel:c,enableDump:l,isLocalAudioNeedAudioProcess:u=!0,isScreenAudioNeedAudioProcess:h=!1}=i;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=u,this.core.room.audioManager.isScreenAudioNeedAudioProcess=h,!n)throw new V({code:$.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload(`${n}/audioProcessor-wasm.js`),u&&!this.localAudioWorkletNode){let{sign:C,status:k,timestamp:re}=yield this.getAuthData(t,r,s);this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",t,r,re,C,k,e)}if(h&&!this.screenAudioWorkletNode){let{sign:C,status:k,timestamp:re}=yield this.getAuthData(t,r,s);this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",t,r,re,C,k,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()),(m=this.localAudioWorkletNode)==null||m.port.postMessage({type:"enable"}),(_=this.screenAudioWorkletNode)==null||_.port.postMessage({type:"enable"}),e.audioManager.addAudioProcessor(this.mixNode,this.silentNode,this.localAudioWorkletNode,this.screenAudioWorkletNode),T(a)||a.forEach(C=>{this.customAudioReferenceMap.set(C,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:C,refId:`o-${this.audioRefId++}`})}),T(c)||(g=this.localAudioWorkletNode)==null||g.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:c}}),T(l)||(E=this.localAudioWorkletNode)==null||E.port.postMessage({type:"dump",data:{enable:l}})})}update(i){return p(this,null,function*(){var s,n,a;let{audioReference:e,enableDump:t,processLevel:r}=i;T(e)||(this.customAudioReferenceMap.forEach((c,l)=>{this.customAudioReferenceMap.delete(l),this.core.room.audioManager.updateAudioReference({type:"remove",refId:c})}),e.forEach(c=>{this.customAudioReferenceMap.set(c,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:c,refId:`o-${this.audioRefId++}`})})),T(r)||(s=this.localAudioWorkletNode)==null||s.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:r}}),T(t)||((n=this.localAudioWorkletNode)==null||n.port.postMessage({type:"dump",data:{enable:t}}),(a=this.screenAudioWorkletNode)==null||a.port.postMessage({type:"dump",data:{enable:t}}))})}stop(){return p(this,null,function*(){var e,t;let{room:i}=this.core;(e=this.localAudioWorkletNode)==null||e.port.postMessage({type:"disable"}),(t=this.screenAudioWorkletNode)==null||t.port.postMessage({type:"disable"}),yield i.audioManager.removeAudioProcessor(this.localAudioWorkletNode,this.screenAudioWorkletNode)})}destroy(){this.localAudioWorkletNode&&(this.localAudioWorkletNode.port.onmessage=null),this.screenAudioWorkletNode&&(this.screenAudioWorkletNode.port.onmessage=null),this.uninstallEvent()}getAuthData(i,e,t){return p(this,null,function*(){let r=String(Date.now()).slice(0,-3),{auth:s,sign:n,status:a,message:c}=yield jS({sdkAppId:i,userSig:t,userId:e,timestamp:r});if(!s)throw this.log.info(`audioProcessor: ${e} auth result: ${s}. Message: ${c}`),new V({code:$.INVALID_PARAMETER,message:c});return{sign:n,status:a,timestamp:r}})}initWorkletNode(i,e,t,r,s,n,a,c){i.port.postMessage({type:"init",data:{sdkAppId:String(t),userId:r,timestamp:s,sign:n,status:a}}),i.port.onmessage=l=>{var h;let{data:u}=l;switch(u.type){case"cost":let m=(u==null?void 0:u.value)>10?"info":"debug";this.log[m](`${e==="localAudio"?"":`[${e}] `}avg cost: ${u.value} max: ${u==null?void 0:u.max}(${No(new Date(u==null?void 0:u.maxCostTimestamp))}) hist: ${(h=u==null?void 0:u.hist)==null?void 0:h.join(" ")}`);return;case"log":this.log[u.logLevel](`${e==="localAudio"?"":`[${e}] `}${u.value}`);return;case"dump":S.emit("265",{room:c,data:u.value,type:e==="localAudio"?"dump":"dump-screen-audio"});return}}}handleLocalAudioStarted(i){return p(this,null,function*(){var e;if(!(!this.hitTest(i.room)||((e=this.core.room.scheduleResult.config)==null?void 0:e.audioProcessor)!==!0))try{yield this.core.trtc.startPlugin("AudioProcessor",{sdkAppId:this.core.room.sdkAppId,userId:this.core.room.userId,userSig:this.core.room.userSig}),this.log.warn("audio processor auto start success")}catch(t){this.log.warn(`audio processor auto start failed, error: ${t}`)}})}handleLocalAudioStopped(i){return p(this,null,function*(){var e;!this.hitTest(i.room)||((e=this.core.room.scheduleResult.config)==null?void 0:e.audioProcessor)!==!0||(yield this.core.trtc.stopPlugin("AudioProcessor"))})}installEvent(){this.core.innerEmitter.on("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.on("114",this.handleLocalAudioStopped,this)}uninstallEvent(){this.core.innerEmitter.off("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.off("114",this.handleLocalAudioStopped,this)}hitTest(i){return i===this.core.room}};d(ar,"updateValidateRule",{type:"object"}),d(ar,"stopValidateRule",{type:"object"}),d(ar,"Name","AudioProcessor");var _d=ar;function JS(o,i=f.MAIN){return`https://${Pi[i]||ld(o,i)}/api/v1/audioAiAuth`}function jS(r){return p(this,arguments,function*({sdkAppId:o,userId:i,userSig:e,timestamp:t}){let n=`${JS(o)}?sdkAppId=${o}&userId=${i}&userSig=${e}×tamp=${t}`,a=yield fetch(n),{data:{errCode:c,errMsg:l,sign:u,status:h}}=yield a.json();if(h==="1")return{auth:!0,sign:u,status:h,message:l};let m=Ut(o)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",_="Init RTCAudioProcessor failed.",g="";switch(c){case 1:g="Please check your params.";break;case 2:g=`You need to buy packages. Refer to: ${m}`;break;case 3:g="Server is invalid. Please contact our engineer. ";break;case 4:g=`Your packages is not active. Refer to: ${m}`;break;case 5:g=`Your packages is expired. Refer to: ${m}`;break;case 6:g="Your version is not supported.";break}return{auth:!1,status:h,message:l?`${_} Reason: ${l}. ${g}`:`${_}, ${g}`}})}var gd=0,Uh=class{constructor(i,e){d(this,"audioObjectURL");d(this,"player");d(this,"publisher");d(this,"mixInput");this.mixInput=new cs(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)}}reload(i){return p(this,null,function*(){if(i.url){let e=yield jn.download(i.url,{retries:3,type:"blob"});this.audioObjectURL&&URL.revokeObjectURL(this.audioObjectURL),this.audioObjectURL=URL.createObjectURL(e),this.player&&this.publisher?(this.player.src=this.audioObjectURL,this.publisher.src=this.audioObjectURL):(this.player=new Audio(this.audioObjectURL),this.player.crossOrigin="anonymous",this.publisher=new Audio(this.audioObjectURL),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher),this.updateListener(i),this.updateSettings(i))}else this.mixInput.replaceSource(i.track)})}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 Promise.all([(i=this.player)==null?void 0:i.play(),(e=this.publisher)==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 ys(o,i){if(i&&typeof i!="function")throw new V({code:$.INVALID_PARAMETER,message:`start audioMixer plugin: param ${o} should be a function.`})}var wi=class wi{constructor(i){this.core=i;d(this,"log");d(this,"mixedMusicMap",new Map);d(this,"cacheMusicMap",new Map);gd=gd+1,this.log=i.log.createChild({id:`${this.getAlias()}${gd}`}),this.log.info(`created id=${this.getAlias()}${gd}`)}getName(){return wi.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return wi.startValidateRule;case"update":return wi.updateValidateRule;case"stop":return wi.stopValidateRule}}start(i){return p(this,null,function*(){let{room:e}=this.core;this.core.validateSourceNode(),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 s=this.cacheMusicMap.get(t);s?i.url?s.reset():(s.mixInput.replaceSource(i.track),s.mixInput.connect()):(s=new Uh(i,e.audioManager),this.cacheMusicMap.set(t,s)),s.updateListener(i),s.updateSettings(i);try{yield s.play()}catch(n){yield this.handleAutoPlayFailed(s,i,n)}this.mixedMusicMap.set(t,s),s.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"add",audioReference:s.mixInput.source.node,refId:`ax-${t}`}),this.log.info(`start mix audio track ${t} success.`),v.addEnum({key:502700,value:3}),this.kvUpload(i)})}handleAutoPlayFailed(i,e,t){return p(this,null,function*(){if(t.name==="NotSupportedError")this.log.error(`play failed, try to reload source. error: ${t}`),yield i.reload(e),yield i.play();else if(t.name==="NotAllowedError")if(this.core.room.enableAutoPlayDialog){let r=()=>{var s;(s=i.play())==null||s.finally(()=>{S.off("154",r,this)})};S.on("154",r,this),ns()}else this.core.trtc.emit(x.AUTOPLAY_FAILED,{userId:"",mediaType:"audio",resume:()=>p(this,null,function*(){return i.play()})});else throw t})}update(i){return p(this,null,function*(){let{id:e,operation:t,seekFrom:r,playbackRate:s}=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 p(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:s,operation:n,seekFrom:a,onTimeUpdate:c,onDurationChange:l,onEnded:u}=i;e&&v.addCount({key:502009}),t&&v.addCount({key:502001}),r&&v.addCount({key:502002}),s&&v.addCount({key:502003}),n&&v.addCount({key:502004}),a&&v.addCount({key:502005}),typeof c!="function"&&v.addCount({key:502007}),typeof u!="function"&&v.addCount({key:502008}),typeof l!="function"&&v.addCount({key:502006})}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(wi,"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],s=["mp3","ogg","wav","flac"],n=r.split(".").pop(),a=s.indexOf(n)>=0,c=r.startsWith("blob"),l=r.startsWith("data");if(!(a||c||l))throw new V({code:$.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new V({code:$.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});ys("onTimeUpdate",i.onTimeUpdate),ys("onEnded",i.onEnded),ys("onDurationChange",i.onDurationChange)}}),d(wi,"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){ys("onTimeUpdate",i.onTimeUpdate),ys("onEnded",i.onEnded),ys("onDurationChange",i.onDurationChange)}}),d(wi,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),d(wi,"Name","AudioMixer");var Td=wi;var Ed=0,Vh,cr=class cr{constructor(i){this.core=i;d(this,"log");d(this,"audioContext",Ee("denoiser"));d(this,"workletNode");d(this,"config",{enableFarFieldReduce:!1,farFieldReduceThreshold:.5});Ed=Ed+1,this.log=i.log.createChild({id:`${this.getAlias()}${Ed}`}),this.log.info(`created id=${this.getAlias()}${Ed}`)}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},mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}},validate(e,t,r,s){if(!i.room.audioManager.hasAudioTrack)throw new V({code:$.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return Vh||(Vh=this.doPreload(i)),Vh}doPreload(i){return p(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield tr(this.audioContext,t)}catch(r){throw this.log.error("load worklet failed",r),r}finally{URL.revokeObjectURL(t)}})}getName(){return cr.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser"}getValidateRule(i){switch(i){case"start":return cr.startValidateRule(this.core);case"update":return cr.updateValidateRule;case"stop":return cr.stopValidateRule}}start(i){return p(this,null,function*(){let{room:e,schedule:t}=this.core,{assetsPath:r=this.core.assetsPath}=i;if(!r)throw new V({code:$.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload(`${r}/denoiser-wasm${uu()?"":"-nosimd"}.js`),!this.workletNode){let s=String(Date.now()).slice(0,-3),{auth:n,sign:a,status:c,message:l}=yield zS(t,L(O({},i),{timestamp:s}));if(!n)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${n}. Message: ${l}`),new V({code:$.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:s,sign:a,status:c}}),this.workletNode.port.onmessage=u=>{var m;let{data:h}=u;if(h.type==="cost"){let _=(h==null?void 0:h.max)>20?"warn":(h==null?void 0:h.max)>10?"info":"debug";this.log[_](`avg cost: ${h.value} max: ${h==null?void 0:h.max}(${No(new Date(h==null?void 0:h.maxCostTimestamp))}) hist: ${(m=h==null?void 0:h.hist)==null?void 0:m.join(" ")}`)}else h.type==="log"&&this.log[h.logLevel](`${h.value}`)}}this.updateConfig(i),this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(i){return p(this,null,function*(){this.updateConfig(i)})}stop(){return p(this,null,function*(){if(!this.workletNode)return;let{room:i}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield i.audioManager.removeDenoiser(this.workletNode)})}updateConfig(i){if(!this.workletNode)return;let e=!1;T(i.mode)||(i.mode===0?this.config.enableFarFieldReduce=!1:i.mode===1&&(this.config.enableFarFieldReduce=!0),e=!0),T(i.farFieldReduceThreshold)||(this.config.farFieldReduceThreshold=i.farFieldReduceThreshold,e=!0),e&&this.workletNode.port.postMessage({type:"setConfig",data:this.config})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};d(cr,"updateValidateRule",{type:"object",properties:{mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}}}),d(cr,"stopValidateRule",{type:"object"}),d(cr,"Name","AIDenoiser");var Sd=cr;function zS(s,n){return p(this,arguments,function*(o,{sdkAppId:i,userId:e,userSig:t,timestamp:r}){try{let{data:{errCode:a,errMsg:c,sign:l,status:u}}=yield o.getAbilityConfig(i,o.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:i,userId:e,userSig:t,timestamp:r});if(u==="1")return{auth:!0,sign:l,status:u,message:c};let h=Ut(i)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",m="Init RTCAIDenoiser failed.",_="";switch(a){case 1:_="Please check your params.";break;case 2:_=`You need to buy packages. Refer to: ${h}`;break;case 3:_="Server is invalid. Please contact our engineer. ";break;case 4:_=`Your packages is not active. Refer to: ${h}`;break;case 5:_=`Your packages is expired. Refer to: ${h}`;break;case 6:_="Your version is not supported.";break}return{auth:!1,status:u,message:c?`${m} Reason: ${c}. ${_}`:`${m}, ${_}`}}catch(a){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${a}`}}})}var jf=qe(at(),1);var Fh=class extends jf.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 p(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!_e&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){se.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)&&R.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){se.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},QS=new Fh,Bh=QS;var Hh=0,Xn=class Xn{constructor(i){this.core=i;d(this,"log");d(this,"_seiMessageList",[]);d(this,"_smallSeiMessageList",[]);d(this,"_subStreamSeiMessageList",[]);Hh++,this.log=i.log.createChild({id:`${this.getAlias()}${Hh}`}),this.log.info(`[sei] created id=${this.getAlias()}${Hh}`),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 kh({frame:i,seiMessageList:t})}catch(t){this.log.warn(t)}return i}decode({frame:i,track:e}){return Ph({frame:i,onSEI:t=>{t.forEach(r=>{e!=null&&e.userId?this.core.trtc.emit(x.SEI_MESSAGE,{seiPayloadType:r.seiPayloadType,data:r.seiPayload.buffer,userId:(e==null?void 0:e.userId)||"",streamType:(e==null?void 0:e.mediaType)===2?"sub":"main"}):this.core.innerEmitter.emit(this.core.INNER_EVENT.SEI_MESSAGE,{room:this.core.room,nalu:r})})}})}destroy(){this.log.debug("destroy"),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:hi?this.encode:kh,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:hi?this.decode:Ph,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update({buffer:i,options:e}){var s;let t=[e.seiPayloadType,i],r=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(t):(this._seiMessageList.push(t),r&&this._smallSeiMessageList.push(t)),(s=this.core.room.scriptTransformWorker)==null||s.postMessage({type:"sei",data:t,isMain:!e.toSubStream,small:r})}getName(){return Xn.Name}getAlias(){return"sei"}getGroup(){return"sei"}};d(Xn,"autoStart",!0),d(Xn,"Name","SEI");var Id=Xn;function $h({frame:o,onDump:i}){return i==null||i(),o}function Wh({frame:o,onDump:i}){return i==null||i(),o}var Xf={"play() error: NotAllowedError:":{tips:o=>o.includes("main <video>")||o.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:o=>o.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:o=>o.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:
|
|
64
|
+
${r.stack}`),!1}},o};var Rs=new WeakMap;function $f(o){let i=Rs.get(o);i&&(i.forEach(e=>clearTimeout(e)),Rs.delete(o))}function Wf(o,i){return Q((e,t)=>function(...r){let s=Rs.get(this);s||(s=new Map,Rs.set(this,s));let n=i(...r),a=s.get(n);if(!a||a<=0){e.apply(this,r);let c=setTimeout(()=>{var l;(l=Rs.get(this))==null||l.delete(n)},o);s.set(n,c)}else{clearTimeout(a);let c=window.setTimeout(()=>{var l;e.apply(this,r),(l=Rs.get(this))==null||l.delete(n)},o);s.set(n,c)}})}var qf="trtc-sdk-v5",wh="5.14.2-beta.9";function st(...o){return Q((i,e)=>function(...t){try{md.call(this,o,t,e,this._name)}catch(r){return Promise.reject(r)}return i.apply(this,t)})}function Lh(...o){return Q((i,e)=>function(...t){try{md.call(this,o,t,e,this._name)}catch(r){throw r}return i.apply(this,t)})}function md(o,i,e,t){if(Ie(o))for(let r=0;r<o.length;r++)hd.call(this,{rule:o[r],value:i[r],key:o[r].name,fnName:e,className:t});else hd.call(this,{rule:o,value:i[0],key:o.name,fnName:e,className:t})}function hd({rule:o,value:i,key:e,fnName:t,className:r}){function s(c){return{code:$.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:o,value:i}}}if(T(i)){if(o.required)throw new V(s(5001));if(T(o.defaultValue)){le(o.validate)&&o.validate.call(this,i,e,t,r,this);return}i=o.defaultValue}if(Array.isArray(o.type)){let c=!1;for(let l=0;l<o.type.length;l++)o.type[l]===null&&i===null&&(c=!0),le(o.type[l])&&i instanceof o.type[l]&&(c=!0),ie(o.type[l])&&Me(i)===o.type[l].toLowerCase()&&(c=!0);if(!c)throw new V({code:$.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:o.type.map(l=>jr(l)?xo(l):ie(l)?l:Me(l))},value:i}})}else if(!T(o.type)&&Me(i)!==o.type)throw new V(s(5002));if(o.allowEmpty===!1){let c=z(i)&&(i===0||Number.isNaN(i)),l=ie(i)&&i.trim()==="";if(c||l)throw new V(s(5003))}if(o.notLessThanZero&&z(i)&&i<0)throw new V(s(5006));if(!T(o.min)&&z(i)&&i<o.min)throw new V(s(5007));if(!T(o.max)&&z(i)&&i>o.max)throw new V(s(5008));if(ie(o.instanceOf)){if(!i||i._name!==o.instanceOf)throw new V(s(5004))}else if(le(o.instanceOf)&&!(i instanceof o.instanceOf))throw new V(s(5004));if(Array.isArray(o.values)&&!o.values.includes(i))throw new V(s(5005));let{properties:n}=o;dt(n)&&yt(i)&&Object.keys(n).forEach(c=>{hd.call(this,{rule:n[c],value:i&&i[c],key:`${c}`,fnName:t,className:r})});let{arrayItem:a}=o;dt(a)&&Ie(i)&&i.forEach((c,l)=>{hd.call(this,{rule:a,value:c,key:`${e}[${l}]`,fnName:t,className:r})}),le(o.validate)&&o.validate.call(this,i,e,t,r,this)}function Ae(o={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t,ignoreLog:r,ignoreErrorLog:s}=o;return Q((n,a)=>function(...c){var _,g,E;function l(C,k,re){if(re&&re.includes(C))return"hided";if(e){let P=e(...c);if(c[P.argIndex]===k)return P.value}if(k===c||C in c)return k;try{return k instanceof HTMLElement?`id: ${k.id} type:${Me(k)}`:k instanceof MediaStreamTrack?Oa(k):(JSON.stringify(k),k)}catch(P){return`type:${Me(k)}`}}let u=this._log||R;if(r!=null&&r(...c))return n.apply(this,c);c.length>0?u.info(`${a}() ${JSON.stringify(c,(C,k)=>l(C,k,["userSig","privateMapKey"]))}`):u.info(`${a}()`);let h=t?t(...c):uc[a],m=(s==null?void 0:s(...c))||!1;try{let C=n.apply(this,c),k=U();if(Tr(C)){let re=`${a.includes("Plugin")?`${((g=(_=c[0]).getName)==null?void 0:g.call(_))||""} `:" "}`;return C.then(P=>(u.info(`${a}() success ${re}${i.call(this,...c)}`),v.addSuccessEvent({key:h,cost:U()-k}),P)).catch(P=>{var b;P=V.convertFrom.call(this,P,a,c.length===1?c[0]:c);let Qe=P.extraCode||P.code,N=(b=P.message)!=null&&b.includes(Qe)?"":` code:${Qe}`;throw m||u.error(`${a}() failed ${re}${i.call(this,...c)} ${P}${N} params: ${JSON.stringify(c,l)}`),v.addFailedEvent({key:h,error:P}),P})}return v.addSuccessEvent({key:h}),C}catch(C){C=V.convertFrom.call(this,C,a);let k=C.extraCode||C.code,re=(E=C.message)!=null&&E.includes(k)?"":` code:${k}`;throw m||u.error(`${a}() failed ${C}${re} params: ${JSON.stringify(c,l)}`),v.addFailedEvent({key:h,error:C}),C}})}var pd=o=>Q((i,e)=>function(t,r){return p(this,null,function*(){let s=this._plugins.get(t);if(!s)throw this._log.error(`plugin ${String(t)} is not found`),new V({code:$.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});if(le(s.constructor.isSupported)&&!s.constructor.isSupported())throw this._log.error(`plugin ${String(t)} is not supported`),new V({code:$.ENV_NOT_SUPPORTED,message:`plugin ${String(t)} is not supported`,extraCode:5210,fnName:e});return md.call(this,s.getValidateRule(o),[r],e,"TRTC"),i.call(this,s,r)})});var fd=0,xh,ar=class ar{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");fd=fd+1,this.log=i.log.createChild({id:`${this.getAlias()}${fd}`}),this.log.info(`created id=${this.getAlias()}${fd}`),this.installEvent()}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,s){if(!i.room.audioManager.hasAudioTrack&&!i.room.audioManager.hasScreenAudioTrack)throw new V({code:$.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return xh||(xh=this.doPreload(i)),xh}doPreload(i){return p(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield tr(this.audioContext,t)}catch(r){this.log.error(`preload audioProcessor failed. ${r}`)}finally{URL.revokeObjectURL(t)}})}getName(){return ar.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(i){switch(i){case"start":return ar.getStartValidateRule(this.core);case"update":return ar.updateValidateRule;case"stop":return ar.stopValidateRule}}start(i){return p(this,null,function*(){var m,_,g,E;let{room:e}=this.core,{sdkAppId:t,userId:r,userSig:s,assetsPath:n=this.core.assetsPath,audioReference:a,processLevel:c,enableDump:l,isLocalAudioNeedAudioProcess:u=!0,isScreenAudioNeedAudioProcess:h=!1}=i;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=u,this.core.room.audioManager.isScreenAudioNeedAudioProcess=h,!n)throw new V({code:$.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload(`${n}/audioProcessor-wasm.js`),u&&!this.localAudioWorkletNode){let{sign:C,status:k,timestamp:re}=yield this.getAuthData(t,r,s);this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",t,r,re,C,k,e)}if(h&&!this.screenAudioWorkletNode){let{sign:C,status:k,timestamp:re}=yield this.getAuthData(t,r,s);this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",t,r,re,C,k,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()),(m=this.localAudioWorkletNode)==null||m.port.postMessage({type:"enable"}),(_=this.screenAudioWorkletNode)==null||_.port.postMessage({type:"enable"}),e.audioManager.addAudioProcessor(this.mixNode,this.silentNode,this.localAudioWorkletNode,this.screenAudioWorkletNode),T(a)||a.forEach(C=>{this.customAudioReferenceMap.set(C,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:C,refId:`o-${this.audioRefId++}`})}),T(c)||(g=this.localAudioWorkletNode)==null||g.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:c}}),T(l)||(E=this.localAudioWorkletNode)==null||E.port.postMessage({type:"dump",data:{enable:l}})})}update(i){return p(this,null,function*(){var s,n,a;let{audioReference:e,enableDump:t,processLevel:r}=i;T(e)||(this.customAudioReferenceMap.forEach((c,l)=>{this.customAudioReferenceMap.delete(l),this.core.room.audioManager.updateAudioReference({type:"remove",refId:c})}),e.forEach(c=>{this.customAudioReferenceMap.set(c,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:c,refId:`o-${this.audioRefId++}`})})),T(r)||(s=this.localAudioWorkletNode)==null||s.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:r}}),T(t)||((n=this.localAudioWorkletNode)==null||n.port.postMessage({type:"dump",data:{enable:t}}),(a=this.screenAudioWorkletNode)==null||a.port.postMessage({type:"dump",data:{enable:t}}))})}stop(){return p(this,null,function*(){var e,t;let{room:i}=this.core;(e=this.localAudioWorkletNode)==null||e.port.postMessage({type:"disable"}),(t=this.screenAudioWorkletNode)==null||t.port.postMessage({type:"disable"}),yield i.audioManager.removeAudioProcessor(this.localAudioWorkletNode,this.screenAudioWorkletNode)})}destroy(){this.localAudioWorkletNode&&(this.localAudioWorkletNode.port.onmessage=null),this.screenAudioWorkletNode&&(this.screenAudioWorkletNode.port.onmessage=null),this.uninstallEvent()}getAuthData(i,e,t){return p(this,null,function*(){let r=String(Date.now()).slice(0,-3),{auth:s,sign:n,status:a,message:c}=yield jS({sdkAppId:i,userSig:t,userId:e,timestamp:r});if(!s)throw this.log.info(`audioProcessor: ${e} auth result: ${s}. Message: ${c}`),new V({code:$.INVALID_PARAMETER,message:c});return{sign:n,status:a,timestamp:r}})}initWorkletNode(i,e,t,r,s,n,a,c){i.port.postMessage({type:"init",data:{sdkAppId:String(t),userId:r,timestamp:s,sign:n,status:a}}),i.port.onmessage=l=>{var h;let{data:u}=l;switch(u.type){case"cost":let m=(u==null?void 0:u.value)>10?"info":"debug";this.log[m](`${e==="localAudio"?"":`[${e}] `}avg cost: ${u.value} max: ${u==null?void 0:u.max}(${No(new Date(u==null?void 0:u.maxCostTimestamp))}) hist: ${(h=u==null?void 0:u.hist)==null?void 0:h.join(" ")}`);return;case"log":this.log[u.logLevel](`${e==="localAudio"?"":`[${e}] `}${u.value}`);return;case"dump":S.emit("265",{room:c,data:u.value,type:e==="localAudio"?"dump":"dump-screen-audio"});return}}}handleLocalAudioStarted(i){return p(this,null,function*(){var e;if(!(!this.hitTest(i.room)||((e=this.core.room.scheduleResult.config)==null?void 0:e.audioProcessor)!==!0))try{yield this.core.trtc.startPlugin("AudioProcessor",{sdkAppId:this.core.room.sdkAppId,userId:this.core.room.userId,userSig:this.core.room.userSig}),this.log.warn("audio processor auto start success")}catch(t){this.log.warn(`audio processor auto start failed, error: ${t}`)}})}handleLocalAudioStopped(i){return p(this,null,function*(){var e;!this.hitTest(i.room)||((e=this.core.room.scheduleResult.config)==null?void 0:e.audioProcessor)!==!0||(yield this.core.trtc.stopPlugin("AudioProcessor"))})}installEvent(){this.core.innerEmitter.on("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.on("114",this.handleLocalAudioStopped,this)}uninstallEvent(){this.core.innerEmitter.off("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.off("114",this.handleLocalAudioStopped,this)}hitTest(i){return i===this.core.room}};d(ar,"updateValidateRule",{type:"object"}),d(ar,"stopValidateRule",{type:"object"}),d(ar,"Name","AudioProcessor");var _d=ar;function JS(o,i=f.MAIN){return`https://${Pi[i]||ld(o,i)}/api/v1/audioAiAuth`}function jS(r){return p(this,arguments,function*({sdkAppId:o,userId:i,userSig:e,timestamp:t}){let n=`${JS(o)}?sdkAppId=${o}&userId=${i}&userSig=${e}×tamp=${t}`,a=yield fetch(n),{data:{errCode:c,errMsg:l,sign:u,status:h}}=yield a.json();if(h==="1")return{auth:!0,sign:u,status:h,message:l};let m=Ut(o)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",_="Init RTCAudioProcessor failed.",g="";switch(c){case 1:g="Please check your params.";break;case 2:g=`You need to buy packages. Refer to: ${m}`;break;case 3:g="Server is invalid. Please contact our engineer. ";break;case 4:g=`Your packages is not active. Refer to: ${m}`;break;case 5:g=`Your packages is expired. Refer to: ${m}`;break;case 6:g="Your version is not supported.";break}return{auth:!1,status:h,message:l?`${_} Reason: ${l}. ${g}`:`${_}, ${g}`}})}var gd=0,Uh=class{constructor(i,e){d(this,"audioObjectURL");d(this,"player");d(this,"publisher");d(this,"mixInput");this.mixInput=new cs(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)}}reload(i){return p(this,null,function*(){if(i.url){let e=yield jn.download(i.url,{retries:3,type:"blob"});this.audioObjectURL&&URL.revokeObjectURL(this.audioObjectURL),this.audioObjectURL=URL.createObjectURL(e),this.player&&this.publisher?(this.player.src=this.audioObjectURL,this.publisher.src=this.audioObjectURL):(this.player=new Audio(this.audioObjectURL),this.player.crossOrigin="anonymous",this.publisher=new Audio(this.audioObjectURL),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher),this.updateListener(i),this.updateSettings(i))}else this.mixInput.replaceSource(i.track)})}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 Promise.all([(i=this.player)==null?void 0:i.play(),(e=this.publisher)==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 ys(o,i){if(i&&typeof i!="function")throw new V({code:$.INVALID_PARAMETER,message:`start audioMixer plugin: param ${o} should be a function.`})}var wi=class wi{constructor(i){this.core=i;d(this,"log");d(this,"mixedMusicMap",new Map);d(this,"cacheMusicMap",new Map);gd=gd+1,this.log=i.log.createChild({id:`${this.getAlias()}${gd}`}),this.log.info(`created id=${this.getAlias()}${gd}`)}getName(){return wi.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return wi.startValidateRule;case"update":return wi.updateValidateRule;case"stop":return wi.stopValidateRule}}start(i){return p(this,null,function*(){let{room:e}=this.core;this.core.validateSourceNode(),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 s=this.cacheMusicMap.get(t);s?i.url?s.reset():(s.mixInput.replaceSource(i.track),s.mixInput.connect()):(s=new Uh(i,e.audioManager),this.cacheMusicMap.set(t,s)),s.updateListener(i),s.updateSettings(i);try{yield s.play()}catch(n){yield this.handleAutoPlayFailed(s,i,n)}this.mixedMusicMap.set(t,s),s.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"add",audioReference:s.mixInput.source.node,refId:`ax-${t}`}),this.log.info(`start mix audio track ${t} success.`),v.addEnum({key:502700,value:3}),this.kvUpload(i)})}handleAutoPlayFailed(i,e,t){return p(this,null,function*(){if(t.name==="NotSupportedError")this.log.error(`play failed, try to reload source. error: ${t}`),yield i.reload(e),yield i.play();else if(t.name==="NotAllowedError")if(this.core.room.enableAutoPlayDialog){let r=()=>{var s;(s=i.play())==null||s.finally(()=>{S.off("154",r,this)})};S.on("154",r,this),ns()}else this.core.trtc.emit(x.AUTOPLAY_FAILED,{userId:"",mediaType:"audio",resume:()=>p(this,null,function*(){return i.play()})});else throw t})}update(i){return p(this,null,function*(){let{id:e,operation:t,seekFrom:r,playbackRate:s}=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 p(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:s,operation:n,seekFrom:a,onTimeUpdate:c,onDurationChange:l,onEnded:u}=i;e&&v.addCount({key:502009}),t&&v.addCount({key:502001}),r&&v.addCount({key:502002}),s&&v.addCount({key:502003}),n&&v.addCount({key:502004}),a&&v.addCount({key:502005}),typeof c!="function"&&v.addCount({key:502007}),typeof u!="function"&&v.addCount({key:502008}),typeof l!="function"&&v.addCount({key:502006})}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(wi,"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],s=["mp3","ogg","wav","flac"],n=r.split(".").pop(),a=s.indexOf(n)>=0,c=r.startsWith("blob"),l=r.startsWith("data");if(!(a||c||l))throw new V({code:$.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new V({code:$.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});ys("onTimeUpdate",i.onTimeUpdate),ys("onEnded",i.onEnded),ys("onDurationChange",i.onDurationChange)}}),d(wi,"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){ys("onTimeUpdate",i.onTimeUpdate),ys("onEnded",i.onEnded),ys("onDurationChange",i.onDurationChange)}}),d(wi,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),d(wi,"Name","AudioMixer");var Td=wi;var Ed=0,Vh,cr=class cr{constructor(i){this.core=i;d(this,"log");d(this,"audioContext",Ee("denoiser"));d(this,"workletNode");d(this,"config",{enableFarFieldReduce:!1,farFieldReduceThreshold:.5});Ed=Ed+1,this.log=i.log.createChild({id:`${this.getAlias()}${Ed}`}),this.log.info(`created id=${this.getAlias()}${Ed}`)}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},mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}},validate(e,t,r,s){if(!i.room.audioManager.hasAudioTrack)throw new V({code:$.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return Vh||(Vh=this.doPreload(i)),Vh}doPreload(i){return p(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield tr(this.audioContext,t)}catch(r){throw this.log.error("load worklet failed",r),r}finally{URL.revokeObjectURL(t)}})}getName(){return cr.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser"}getValidateRule(i){switch(i){case"start":return cr.startValidateRule(this.core);case"update":return cr.updateValidateRule;case"stop":return cr.stopValidateRule}}start(i){return p(this,null,function*(){let{room:e,schedule:t}=this.core,{assetsPath:r=this.core.assetsPath}=i;if(!r)throw new V({code:$.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload(`${r}/denoiser-wasm${uu()?"":"-nosimd"}.js`),!this.workletNode){let s=String(Date.now()).slice(0,-3),{auth:n,sign:a,status:c,message:l}=yield zS(t,L(O({},i),{timestamp:s}));if(!n)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${n}. Message: ${l}`),new V({code:$.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:s,sign:a,status:c}}),this.workletNode.port.onmessage=u=>{var m;let{data:h}=u;if(h.type==="cost"){let _=(h==null?void 0:h.max)>20?"warn":(h==null?void 0:h.max)>10?"info":"debug";this.log[_](`avg cost: ${h.value} max: ${h==null?void 0:h.max}(${No(new Date(h==null?void 0:h.maxCostTimestamp))}) hist: ${(m=h==null?void 0:h.hist)==null?void 0:m.join(" ")}`)}else h.type==="log"&&this.log[h.logLevel](`${h.value}`)}}this.updateConfig(i),this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(i){return p(this,null,function*(){this.updateConfig(i)})}stop(){return p(this,null,function*(){if(!this.workletNode)return;let{room:i}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield i.audioManager.removeDenoiser(this.workletNode)})}updateConfig(i){if(!this.workletNode)return;let e=!1;T(i.mode)||(i.mode===0?this.config.enableFarFieldReduce=!1:i.mode===1&&(this.config.enableFarFieldReduce=!0),e=!0),T(i.farFieldReduceThreshold)||(this.config.farFieldReduceThreshold=i.farFieldReduceThreshold,e=!0),e&&this.workletNode.port.postMessage({type:"setConfig",data:this.config})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};d(cr,"updateValidateRule",{type:"object",properties:{mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}}}),d(cr,"stopValidateRule",{type:"object"}),d(cr,"Name","AIDenoiser");var Sd=cr;function zS(s,n){return p(this,arguments,function*(o,{sdkAppId:i,userId:e,userSig:t,timestamp:r}){try{let{data:{errCode:a,errMsg:c,sign:l,status:u}}=yield o.getAbilityConfig(i,o.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:i,userId:e,userSig:t,timestamp:r});if(u==="1")return{auth:!0,sign:l,status:u,message:c};let h=Ut(i)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",m="Init RTCAIDenoiser failed.",_="";switch(a){case 1:_="Please check your params.";break;case 2:_=`You need to buy packages. Refer to: ${h}`;break;case 3:_="Server is invalid. Please contact our engineer. ";break;case 4:_=`Your packages is not active. Refer to: ${h}`;break;case 5:_=`Your packages is expired. Refer to: ${h}`;break;case 6:_="Your version is not supported.";break}return{auth:!1,status:u,message:c?`${m} Reason: ${c}. ${_}`:`${m}, ${_}`}}catch(a){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${a}`}}})}var jf=qe(at(),1);var Fh=class extends jf.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 p(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!_e&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){se.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)&&R.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){se.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},QS=new Fh,Bh=QS;var Hh=0,Xn=class Xn{constructor(i){this.core=i;d(this,"log");d(this,"_seiMessageList",[]);d(this,"_smallSeiMessageList",[]);d(this,"_subStreamSeiMessageList",[]);Hh++,this.log=i.log.createChild({id:`${this.getAlias()}${Hh}`}),this.log.info(`[sei] created id=${this.getAlias()}${Hh}`),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 kh({frame:i,seiMessageList:t})}catch(t){this.log.warn(t)}return i}decode({frame:i,track:e}){return Ph({frame:i,onSEI:t=>{t.forEach(r=>{e!=null&&e.userId?this.core.trtc.emit(x.SEI_MESSAGE,{seiPayloadType:r.seiPayloadType,data:r.seiPayload.buffer,userId:(e==null?void 0:e.userId)||"",streamType:(e==null?void 0:e.mediaType)===2?"sub":"main"}):this.core.innerEmitter.emit(this.core.INNER_EVENT.SEI_MESSAGE,{room:this.core.room,nalu:r})})}})}destroy(){this.log.debug("destroy"),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:hi?this.encode:kh,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:hi?this.decode:Ph,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update({buffer:i,options:e}){var s;let t=[e.seiPayloadType,i],r=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(t):(this._seiMessageList.push(t),r&&this._smallSeiMessageList.push(t)),(s=this.core.room.scriptTransformWorker)==null||s.postMessage({type:"sei",data:t,isMain:!e.toSubStream,small:r})}getName(){return Xn.Name}getAlias(){return"sei"}getGroup(){return"sei"}};d(Xn,"autoStart",!0),d(Xn,"Name","SEI");var Id=Xn;function $h({frame:o,onDump:i}){return i==null||i(),o}function Wh({frame:o,onDump:i}){return i==null||i(),o}var Xf={"play() error: NotAllowedError:":{tips:o=>o.includes("main <video>")||o.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:o=>o.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:o=>o.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:
|
|
65
65
|
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
66
|
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:
|
|
67
67
|
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.
|