trtc-sdk-v5 5.6.2-beta.2 → 5.6.2-beta.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/trtc.esm.js CHANGED
@@ -22,17 +22,17 @@ Refer to: ${xd("en",a)}
22
22
  clearInterval(timerID);
23
23
  }
24
24
  };
25
- `],{type:"application/javascript"})));e.onmessage=t=>{t.data==="tick"&&(i.callback(),i.loopCount+=1,this.isBreakLoop(i)&&e.postMessage("stop"))},i.worker=e,e.postMessage("start")}static timeout(i){let e=()=>{if(i.callback(),i.loopCount+=1,!this.isBreakLoop(i))return i.timeoutID=setTimeout(e,i.delay)};return i.timeoutID=setTimeout(e,i.delay)}static ric(i){let e=B(),t,s=()=>{if(t=B()-e,t>=i.delay&&(e=B()-Math.floor(t%i.delay),i.callback(),i.loopCount+=1),!this.isBreakLoop(i))return i.ricID=fu(s,{timeout:i.delay})};return i.ricID=fu(s,{timeout:i.delay})}static raf(i){i.delay=(1e3/i.fps).toFixed(2);let e=B(),t,s=()=>{if(document.hidden&&i.backgroundTask)return t=B()-e,e=B(),i.callback(),i.loopCount+=1,this.isBreakLoop(i)?void 0:i.timeoutID=setTimeout(s,i.delay-Math.floor(t%i.delay));if(t=B()-e,t>=i.delay&&(e=B()-Math.floor(t%i.delay),i.callback(),i.loopCount+=1),!this.isBreakLoop(i))return i.rafID=requestAnimationFrame(s)};if(i.rafID=requestAnimationFrame(s),i.backgroundTask){let n=()=>{if(document.hidden){let o=B()-e;o>=i.delay?s():i.timeoutID=setTimeout(s,i.delay-o)}};document.addEventListener("visibilitychange",n),i.onVisibilitychange=n,document.hidden&&n()}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:s,ricID:n,onVisibilitychange:o,worker:a}=this.taskMap.get(i);return a&&a.terminate(),e&&clearInterval(e),t&&clearTimeout(t),s&&Vm(s),n&&wm(n),o&&document.removeEventListener("visibilitychange",o),this.taskMap.delete(i),!0}static isBreakLoop(i){return this.taskMap.has(i.taskID)?i.count!==0&&i.loopCount>=i.count?(this.clearTask(i.taskID),!0):!1:!0}};vs.taskMap=new Map,vs.currentTaskID=1;var Z=vs;var eE={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:h.SEI_MESSAGE,ERROR:"error"};var Pe={LOADED_DATA:h.LOADEDDATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed"};var jt={};$r(jt,{create:()=>we,remove:()=>pe});var Os=new WeakMap;function we(r,i){Os.has(r)||Os.set(r,[]);let e=Os.get(r),s={add:(n,o)=>("addEventListener"in i?(e.push(i.removeEventListener.bind(i,n,o)),i.addEventListener(n,o)):(e.push(i.off.bind(i,n,o)),i.on(n,o)),s)};return s}function pe(r){let i=Os.get(r);i&&(i.forEach(e=>e()),Os.delete(r))}var qt=class extends V{constructor(e,t){super(e.id,`${t}-player`);this.kind=t;u(this,"id");u(this,"element",null);u(this,"track");u(this,"url");u(this,"attr");u(this,"muted");u(this,"_log");u(this,"_pausedRetryCount");u(this,"_isElementPlayingFired",!1);u(this,"_interval");this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=sa,this._state="STOPPED",this.bindTrackEvents(),this._log.info(`create ${t}-player ${this.id}`)}get isPlaying(){return this._state==="PLAYING"}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.bindAutoPlayEvent(),yield this.element.play()}catch(e){let t=D({key:v.PLAY_FAILED,data:{media:this.kind,error:e}});if(this.track&&!this.track.muted&&this._log.warn(e),t.includes("NotAllowedError"))throw new C({code:I.PLAY_NOT_ALLOWED,message:t})}})}stop(){this.unbindEvents(),this._isElementPlayingFired=!1,this.element&&(this.element.remove(),this.element.srcObject=null,this.element=null),this.handleStopped(h.ENDED),this._interval>0&&Z.clearTask(this._interval)}pause(){var e;this.isPlaying&&((e=this.element)==null||e.pause())}resume(){return this.isPlaying?Promise.resolve():Ea?this.replay():this.play().catch(()=>{})}setMuted(e){this.element&&(this.element.muted=e),this.muted=e}replay(){return this.stop(),this.play().catch(()=>{})}bindElementEvents(){if(this.element){let e=this.handleElementEvent.bind(this);return we(this.element,this.element).add(h.PLAYING,e).add(h.ENDED,e).add(h.PAUSE,e).add(h.ERROR,e).add(h.LOADEDDATA,e)}}bindTrackEvents(){if(this.track){let e=this.handleTrackEvent.bind(this);jt==null||jt.create(this.track,this.track).add(h.ENDED,e).add(h.MUTE,e).add(h.UNMUTE,e),this.track.readyState===h.ENDED&&this.handleTrackEvent({type:h.ENDED}),this.track.muted&&this.handleTrackEvent({type:h.MUTE})}}bindAutoPlayEvent(){T.on(f.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(){this.track&&pe(this.track)}unbindEvents(){this.element&&pe(this.element),this.unbindTrackEvents(),T.off(f.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case h.PLAYING:this._isElementPlayingFired=!0,this._log.info(`${this.kind} player is playing`),this.handlePlaying(h.PLAYING),this._interval&&(Z.clearTask(this._interval),this._interval=-1);break;case h.ENDED:this._log.info(`${this.kind} player is ended`),this.handleStopped(h.ENDED);break;case h.PAUSE:this._log.info(`${this.kind} player is paused`),this.handlePaused(h.PAUSE),Ue&&(this._interval=Z.run(ci,()=>{this.element&&this._state==="PAUSED"&&this.resume()},{delay:3e3}));break;case h.ERROR:if(this.element&&this.element.error){let{code:s,message:n}=this.element.error;this._log.error(`${this.kind} player error observed. code: ${s} message: ${n} userAgent: ${navigator.userAgent}`),ee.uploadEvent({log:`stat-${this.kind}-${Le.PLAYER_ERROR}-${s}-${navigator.userAgent}`,error:this.element.error})}break;case h.LOADEDDATA:this.kind===h.VIDEO&&this.emit(Pe.LOADED_DATA);break}}handleTrackEvent(e){switch(e.type){case h.ENDED:this._log.info(`${this.kind} track is ended`),this.handleStopped(h.ENDED);break;case h.MUTE:this._log.info(`${this.kind} track is unable to provide media output`),this.handlePaused(h.MUTE);break;case h.UNMUTE:this._log.info(`${this.kind} track is able to provide media output`),this._isElementPlayingFired&&this.handlePlaying(h.UNMUTE);break}}handlePlaying(e){this.emit(Pe.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this.emit(Pe.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this.emit(Pe.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};b([oe([],"PLAYING",{sync:!0})],qt.prototype,"handlePlaying",1),b([oe("PLAYING","PAUSED",{ignoreError:!0,sync:!0})],qt.prototype,"handlePaused",1),b([oe([],"STOPPED",{sync:!0})],qt.prototype,"handleStopped",1);var Kt="trtc_autoplay",Ba=`${Kt}_mask`,Tr=`${Kt}_wrapper`,gu=`${Kt}_header`,$a=`${Kt}_content`,Gn=`${Kt}_action_wrapper`,Ha=`${Kt}_question`,Fa=`${Kt}_collapse`,Wn=`${Kt}_action_confirm`,Tu=`${Kt}_detail`,Su="#2473E8",Wa="dialog",Um=`${Wa}-show`,Bm=`${Wa}-1`,$m=`${Wa}-2`,Iu=!1,Ja=()=>!!document.querySelector(`.${Tr}`),Ru=`${mt}/${Et()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,Au=`<br><a href='${Ru}' target='_blank'>${Et()?"\u5176\u4ED6\u65B9\u6848\uFF1F":"Any other solution?"}</a>`,Hm=`${Et()?`\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${Au}`:`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. ${Au}`}`,Ga=class{constructor(){u(this,"content","\u97F3\u89C6\u9891\u64AD\u653E\u88AB\u6D4F\u89C8\u5668\u62E6\u622A\uFF0C\u8BF7\u70B9\u51FB\u201C\u6062\u590D\u64AD\u653E\u201D\u3002");u(this,"_dialogNode",null);u(this,"_bodyPosition","");u(this,"_showDetail",!1);u(this,"_isCollapseClicked",!1);u(this,"_isQuestionClicked",!1);if(Et()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!Iu){let i=document.createElement("style");i.innerHTML=`.${Ba}{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;}.${Ba} div:not(.${Gn}){display:block !important;}.${Tr}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${Tr} a{color:${Su};}.${gu}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${$a}{margin:8px 0;}.${Gn}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${Fa}{margin-right:auto;cursor:pointer}.${Ha}{height:100%;line-height:16px;cursor:pointer;}.${Wn}{margin-left:8px;color:#fff;background:${Su};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${Wn}:hover{opacity:0.9;}.${Fa},.${Wn},.${$a},.${Ha}{font-size:14px;}@media screen and (max-width:750px){.${Tr}{width:80vw;}}`,document.head.appendChild(i),Iu=!0}this.addDiaLog()}createDiaLog(){let i=document.createElement("template");i.innerHTML=`<div class="${Ba}"><div class='${Tr}'><div class='${gu}'>${location.host}</div><div class='${$a}'>${this.content}</div><div class='${Tu}' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">${Hm}</div><div class='${Gn}'></div></div></div>`.trim();let e=document.createElement("button");e.className=Wn,e.innerText=Et()?"\u6062\u590D\u64AD\u653E":"Resume",e.onclick=this.onConfirm.bind(this);let t=document.createElement("div");t.className=Ha,t.innerHTML=`<?xml version="1.0" encoding="UTF-8"?>
25
+ `],{type:"application/javascript"})));e.onmessage=t=>{t.data==="tick"&&(i.callback(),i.loopCount+=1,this.isBreakLoop(i)&&e.postMessage("stop"))},i.worker=e,e.postMessage("start")}static timeout(i){let e=()=>{if(i.callback(),i.loopCount+=1,!this.isBreakLoop(i))return i.timeoutID=setTimeout(e,i.delay)};return i.timeoutID=setTimeout(e,i.delay)}static ric(i){let e=B(),t,s=()=>{if(t=B()-e,t>=i.delay&&(e=B()-Math.floor(t%i.delay),i.callback(),i.loopCount+=1),!this.isBreakLoop(i))return i.ricID=fu(s,{timeout:i.delay})};return i.ricID=fu(s,{timeout:i.delay})}static raf(i){i.delay=(1e3/i.fps).toFixed(2);let e=B(),t,s=()=>{if(document.hidden&&i.backgroundTask)return t=B()-e,e=B(),i.callback(),i.loopCount+=1,this.isBreakLoop(i)?void 0:i.timeoutID=setTimeout(s,i.delay-Math.floor(t%i.delay));if(t=B()-e,t>=i.delay&&(e=B()-Math.floor(t%i.delay),i.callback(),i.loopCount+=1),!this.isBreakLoop(i))return i.rafID=requestAnimationFrame(s)};if(i.rafID=requestAnimationFrame(s),i.backgroundTask){let n=()=>{if(document.hidden){let o=B()-e;o>=i.delay?s():i.timeoutID=setTimeout(s,i.delay-o)}};document.addEventListener("visibilitychange",n),i.onVisibilitychange=n,document.hidden&&n()}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:s,ricID:n,onVisibilitychange:o,worker:a}=this.taskMap.get(i);return a&&a.terminate(),e&&clearInterval(e),t&&clearTimeout(t),s&&Vm(s),n&&wm(n),o&&document.removeEventListener("visibilitychange",o),this.taskMap.delete(i),!0}static isBreakLoop(i){return this.taskMap.has(i.taskID)?i.count!==0&&i.loopCount>=i.count?(this.clearTask(i.taskID),!0):!1:!0}};vs.taskMap=new Map,vs.currentTaskID=1;var Z=vs;var eE={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:h.SEI_MESSAGE,ERROR:"error"};var Pe={LOADED_DATA:h.LOADEDDATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed"};var jt={};$r(jt,{create:()=>we,remove:()=>pe});var Os=new WeakMap;function we(r,i){Os.has(r)||Os.set(r,[]);let e=Os.get(r),s={add:(n,o)=>("addEventListener"in i?(e.push(i.removeEventListener.bind(i,n,o)),i.addEventListener(n,o)):(e.push(i.off.bind(i,n,o)),i.on(n,o)),s)};return s}function pe(r){let i=Os.get(r);i&&(i.forEach(e=>e()),Os.delete(r))}var qt=class extends V{constructor(e,t){super(e.id,`${t}-player`);this.kind=t;u(this,"id");u(this,"element",null);u(this,"track");u(this,"url");u(this,"attr");u(this,"muted");u(this,"_log");u(this,"_pausedRetryCount");u(this,"_isElementPlayingFired",!1);u(this,"_interval");this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=sa,this._state="STOPPED",this.bindTrackEvents(),this._log.info(`create ${t}-player ${this.id}`)}get isPlaying(){return this._state==="PLAYING"}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.bindAutoPlayEvent(),yield this.element.play()}catch(e){let t=D({key:v.PLAY_FAILED,data:{media:this.kind,error:e}});if(this.track&&!this.track.muted&&this._log.warn(e),t.includes("NotAllowedError"))throw new C({code:I.PLAY_NOT_ALLOWED,message:t})}})}stop(){this.unbindEvents(),this._isElementPlayingFired=!1,this.element&&(this.element.remove(),this.element.srcObject=null,this.element=null),this.handleStopped(h.ENDED),this._interval>0&&Z.clearTask(this._interval)}pause(){var e;this.isPlaying&&((e=this.element)==null||e.pause())}resume(){return this._log.info("resume"),this.isPlaying?Promise.resolve():Ea?this.replay():this.play().catch(()=>{})}setMuted(e){this.element&&(this.element.muted=e),this.muted=e}replay(){return this.stop(),this.play().catch(()=>{})}bindElementEvents(){if(this.element){let e=this.handleElementEvent.bind(this);return we(this.element,this.element).add(h.PLAYING,e).add(h.ENDED,e).add(h.PAUSE,e).add(h.ERROR,e).add(h.LOADEDDATA,e)}}bindTrackEvents(){if(this.track){let e=this.handleTrackEvent.bind(this);jt==null||jt.create(this.track,this.track).add(h.ENDED,e).add(h.MUTE,e).add(h.UNMUTE,e),this.track.readyState===h.ENDED&&this.handleTrackEvent({type:h.ENDED}),this.track.muted&&this.handleTrackEvent({type:h.MUTE})}}bindAutoPlayEvent(){T.on(f.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(){this.track&&pe(this.track)}unbindEvents(){this.element&&pe(this.element),this.unbindTrackEvents(),T.off(f.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case h.PLAYING:this._isElementPlayingFired=!0,this._log.info(`${this.kind} player is playing`),this.handlePlaying(h.PLAYING),this._interval&&(Z.clearTask(this._interval),this._interval=-1);break;case h.ENDED:this._log.info(`${this.kind} player is ended`),this.handleStopped(h.ENDED);break;case h.PAUSE:this._log.info(`${this.kind} player is paused`),this.handlePaused(h.PAUSE),Ue&&(this._interval=Z.run(ci,()=>{this.element&&this._state==="PAUSED"&&this.resume()},{delay:3e3}));break;case h.ERROR:if(this.element&&this.element.error){let{code:s,message:n}=this.element.error;this._log.error(`${this.kind} player error observed. code: ${s} message: ${n} userAgent: ${navigator.userAgent}`),ee.uploadEvent({log:`stat-${this.kind}-${Le.PLAYER_ERROR}-${s}-${navigator.userAgent}`,error:this.element.error})}break;case h.LOADEDDATA:this.kind===h.VIDEO&&this.emit(Pe.LOADED_DATA);break}}handleTrackEvent(e){switch(e.type){case h.ENDED:this._log.info(`${this.kind} track is ended`),this.handleStopped(h.ENDED);break;case h.MUTE:this._log.info(`${this.kind} track is unable to provide media output`),this.handlePaused(h.MUTE);break;case h.UNMUTE:this._log.info(`${this.kind} track is able to provide media output`),this._isElementPlayingFired&&this.handlePlaying(h.UNMUTE);break}}handlePlaying(e){this.emit(Pe.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this.emit(Pe.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this.emit(Pe.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};b([oe([],"PLAYING",{sync:!0})],qt.prototype,"handlePlaying",1),b([oe("PLAYING","PAUSED",{ignoreError:!0,sync:!0})],qt.prototype,"handlePaused",1),b([oe([],"STOPPED",{sync:!0})],qt.prototype,"handleStopped",1);var Kt="trtc_autoplay",Ba=`${Kt}_mask`,Tr=`${Kt}_wrapper`,gu=`${Kt}_header`,$a=`${Kt}_content`,Gn=`${Kt}_action_wrapper`,Ha=`${Kt}_question`,Fa=`${Kt}_collapse`,Wn=`${Kt}_action_confirm`,Tu=`${Kt}_detail`,Su="#2473E8",Wa="dialog",Um=`${Wa}-show`,Bm=`${Wa}-1`,$m=`${Wa}-2`,Iu=!1,Ja=()=>!!document.querySelector(`.${Tr}`),Ru=`${mt}/${Et()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,Au=`<br><a href='${Ru}' target='_blank'>${Et()?"\u5176\u4ED6\u65B9\u6848\uFF1F":"Any other solution?"}</a>`,Hm=`${Et()?`\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${Au}`:`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. ${Au}`}`,Ga=class{constructor(){u(this,"content","\u97F3\u89C6\u9891\u64AD\u653E\u88AB\u6D4F\u89C8\u5668\u62E6\u622A\uFF0C\u8BF7\u70B9\u51FB\u201C\u6062\u590D\u64AD\u653E\u201D\u3002");u(this,"_dialogNode",null);u(this,"_bodyPosition","");u(this,"_showDetail",!1);u(this,"_isCollapseClicked",!1);u(this,"_isQuestionClicked",!1);if(Et()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!Iu){let i=document.createElement("style");i.innerHTML=`.${Ba}{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;}.${Ba} div:not(.${Gn}){display:block !important;}.${Tr}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${Tr} a{color:${Su};}.${gu}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${$a}{margin:8px 0;}.${Gn}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${Fa}{margin-right:auto;cursor:pointer}.${Ha}{height:100%;line-height:16px;cursor:pointer;}.${Wn}{margin-left:8px;color:#fff;background:${Su};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${Wn}:hover{opacity:0.9;}.${Fa},.${Wn},.${$a},.${Ha}{font-size:14px;}@media screen and (max-width:750px){.${Tr}{width:80vw;}}`,document.head.appendChild(i),Iu=!0}this.addDiaLog()}createDiaLog(){let i=document.createElement("template");i.innerHTML=`<div class="${Ba}"><div class='${Tr}'><div class='${gu}'>${location.host}</div><div class='${$a}'>${this.content}</div><div class='${Tu}' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">${Hm}</div><div class='${Gn}'></div></div></div>`.trim();let e=document.createElement("button");e.className=Wn,e.innerText=Et()?"\u6062\u590D\u64AD\u653E":"Resume",e.onclick=this.onConfirm.bind(this);let t=document.createElement("div");t.className=Ha,t.innerHTML=`<?xml version="1.0" encoding="UTF-8"?>
26
26
  <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">
27
27
  <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"/>
28
28
  <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"/>
29
29
  <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"/>
30
30
  </svg>
31
- `,t.onclick=this.onQuestionClick.bind(this);let s=document.createElement("div");s.className=Fa,s.innerText=`${Et()?"\u8BE6\u60C5 >":"Detail >"}`,s.onclick=this.onCollapseClick.bind(this);let n=i.content.firstChild,o=n.querySelector(`.${Gn}`);return o.appendChild(s),o.appendChild(t),o.appendChild(e),n}addDiaLog(){Ja()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${Tr}`).onclick=i=>i.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",A.info("show autoplay dialog"),ee.uploadEvent({log:Um}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){A.warn("confirm clicked, try resume stream"),T.emit(f.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let i=this._dialogNode.querySelector(`.${Tu}`);i.style.visibility=`${this._showDetail?"hidden":"visible"}`,i.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||ee.uploadEvent({log:Bm}),this._isCollapseClicked=!0}onQuestionClick(){window.open(Ru,"_blank"),this._isQuestionClicked||ee.uploadEvent({log:$m}),this._isQuestionClicked=!0}},Cu=Ga;var ut=class extends qt{constructor(e){super(e,h.VIDEO);u(this,"viewMirror",!1);u(this,"objectFit");u(this,"container");u(this,"canvas");this.container=e.container,this.canvas=e.canvas,E(e.viewMirror)||(this.viewMirror=e.viewMirror),E(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}initializeElement(){var t;let e=document.createElement(h.VIDEO);this.track&&(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,(t=this.container)==null||t.appendChild(this.elementToRender),this.bindElementEvents()}get styleAttribute(){let e=`width: 100%; height: 100%; object-fit: ${this.objectFit};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(h.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(h.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent)}handleElementEvent(e){var s;super.handleElementEvent(e);let t=e.type;if(t===h.PAUSE&&(this.container&&document.getElementById(this.container.id)||this._log.warn(`${this.kind} player has been remove, element ID: ${(s=this.container)==null?void 0:s.id}`),this._pausedRetryCount>0&&!Ja()&&(this._log.info(`${this.kind} player auto resume when paused`),this.resume(),this._pausedRetryCount--)),this.viewMirror&&this.element){let n=this.element.style.transform;t===h.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=n.replace("scaleX(-1)",""):t===h.LEAVE_PICTURE_IN_PICTURE&&!n.includes("scaleX")&&(this.element.style.transform=`${n} scaleX(-1)`)}}setCanvas(e){var t,s;this.canvas!==e&&((t=this.canvas)==null||t.remove(),e==null||e.setAttribute("style",this.styleAttribute),this.canvas=e,e&&((s=this.container)==null||s.appendChild(e)))}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}stop(){var e;super.stop(),(e=this.canvas)==null||e.remove()}play(){return this.element?this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender):this.initializeElement(),super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(Pe.MEDIA_TRACK_CHANGED,e),e!==null&&(this.bindTrackEvents(),this.element&&(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}};function gi(r,i){return p(this,null,function*(){if(!r.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield r.audioWorklet.addModule(i),A.info("worklet addModule success")}catch(e){throw A.info(`worklet addModule catch error. ${e.message}`),e}})}typeof window!="undefined"&&(window.AudioContext=window.AudioContext||window.webkitAudioContext||window.mozAudioContext);var Pi=new window.AudioContext({sampleRate:48e3}),Jn=()=>{Pi.state==="suspended"?(Pi.resume(),document.addEventListener("click",Jn)):Pi.state==="interrupted"?Pi.resume():document.removeEventListener("click",Jn)};document.addEventListener("click",Jn);Pi.onstatechange=()=>{A.info(`context state: ${Pi.state}`),Jn()};var $e=r=>Pi;var Fm=1,Gm=0,jn=class{constructor(i=!0){this.countMap=new Map;this.distributionMap=new Map;this.log=A.createLogger({id:"kv"});i&&(T.on("102",({track:e,cost:t})=>{this.addSuccessEvent({key:e.kind===h.AUDIO?qn.START_MICROPHONE:ja.START_CAMERA,cost:t})}),T.on("103",({track:e,error:t})=>{this.addFailedEvent({key:e.kind===h.AUDIO?qn.START_MICROPHONE:ja.START_CAMERA,error:t})}))}getReportData(){let i={msg_sdk_basic_info:{uint32_sdk_version:va(this.version||Se),uint32_terminal_type:15,bytes_device_name:"",bytes_os_version:"",uint32_framework:30,uint32_network_type:0},stats_count:[...this.countMap.entries()].map(([e,t])=>({uint32_key:e,uint32_count:t})),stats_distribution:[...this.distributionMap.entries()].map(([e,t])=>({uint32_key:e,distribution_items:[...t.entries()].map(([s,n])=>({uint32_item_key:s,uint32_item_value:n}))}))};return this.countMap.clear(),this.distributionMap.clear(),i}clear(){this.countMap.clear(),this.distributionMap.clear()}isEnumKey(i){let e=+String(i).slice(-3);return e>=700&&e<799}isErrorCodeKey(i){let e=+String(i).slice(-3);return e>=600&&e<699}isCountKey(i){let e=+String(i).slice(-3);return e>=0&&e<599}isNumberKey(i){let e=+String(i).slice(-3);return e>=800&&e<899}addCount({key:i,useUV:e=!1}){if(!this.isCountKey(i)){this.log.debug(`${i} is not count key, last 3 number should be 0~599`);return}e&&this.countMap.has(i)||this.countMap.set(i,(this.countMap.get(i)||0)+1)}addEnum({key:i,value:e,useUV:t=!0}){var n;if(!this.isEnumKey(i))return this.log.debug(`${i} is not enum key, last 3 number should be 700~799`);if(t&&this.countMap.has(i))return;this.countMap.set(i,(this.countMap.get(i)||0)+1);let s=((n=this.distributionMap)==null?void 0:n.get(i))||new Map;s.set(e,(s.get(e)||0)+1),this.distributionMap.set(i,s)}addNumber({key:i,value:e,split:t=100,useUV:s=!1}){var a;if(!this.isNumberKey(i))return this.log.debug(`${i} is not number key, last 3 number should be 800~899`);if(s&&this.countMap.has(i))return;this.countMap.set(i,(this.countMap.get(i)||0)+1);let n=((a=this.distributionMap)==null?void 0:a.get(i))||new Map,o=0;if(re(t))o=Math.floor(e/t);else for(let c=t.length-1;c>0;c--)if(e>t[c]){o=c;break}n.set(o,(n.get(o)||0)+1),this.distributionMap.set(i,n)}addSuccessEvent({key:i,cost:e,timeKey:t,split:s}){if(!!i&&(this.addEnum({key:i,value:Fm,useUV:!1}),e)){let n=+String(i).slice(-3);n<800&&n>=700?this.addNumber({key:t||i+100,value:e,split:s}):t||this.log.debug(`time stat ignored, ${i}`)}}addFailedEvent({key:i,error:e}){if(!i)return;let t=I.UNKNOWN;re(e)?t=e:(!E(e.extraCode)||!E(e.code))&&(t=e.extraCode||e.code),this.addEnum({key:i,value:Gm,useUV:!1}),this.addEnum({key:i,value:t,useUV:!1})}},qa=(J=>(J[J.enterRoom=500700]="enterRoom",J[J.exitRoom=500701]="exitRoom",J[J.switchRole=500702]="switchRole",J[J.destroy=500703]="destroy",J[J.startLocalAudio=500704]="startLocalAudio",J[J.updateLocalAudio=500705]="updateLocalAudio",J[J.stopLocalAudio=500706]="stopLocalAudio",J[J.startLocalVideo=500707]="startLocalVideo",J[J.updateLocalVideo=500708]="updateLocalVideo",J[J.stopLocalVideo=500709]="stopLocalVideo",J[J.startScreenShare=500710]="startScreenShare",J[J.updateScreenShare=500711]="updateScreenShare",J[J.stopScreenShare=500712]="stopScreenShare",J[J.startRemoteVideo=500713]="startRemoteVideo",J[J.updateRemoteVideo=500714]="updateRemoteVideo",J[J.stopRemoteVideo=500715]="stopRemoteVideo",J[J.muteRemoteAudio=500716]="muteRemoteAudio",J[J.setRemoteAudioVolume=500717]="setRemoteAudioVolume",J))(qa||{}),Ka=(n=>(n[n.AudioMixer=550700]="AudioMixer",n[n.AIDenoiser=551700]="AIDenoiser",n[n.VirtualBackground=570700]="VirtualBackground",n[n.Beauty=571700]="Beauty",n[n.Watermark=572700]="Watermark",n))(Ka||{}),Xa=(n=>(n[n.AudioMixer=550701]="AudioMixer",n[n.AIDenoiser=551701]="AIDenoiser",n[n.VirtualBackground=570701]="VirtualBackground",n[n.Beauty=571701]="Beauty",n[n.Watermark=572701]="Watermark",n))(Xa||{}),Qa=(n=>(n[n.AudioMixer=550702]="AudioMixer",n[n.AIDenoiser=551702]="AIDenoiser",n[n.VirtualBackground=570702]="VirtualBackground",n[n.Beauty=571702]="Beauty",n[n.Watermark=572702]="Watermark",n))(Qa||{}),qn=(t=>(t[t.START_MICROPHONE=501700]="START_MICROPHONE",t[t.MICROPHONE_CAHNNELS=501701]="MICROPHONE_CAHNNELS",t[t.MICROPHONE_SAMPLERATE=501702]="MICROPHONE_SAMPLERATE",t))(qn||{});var ja=(i=>(i[i.START_CAMERA=511700]="START_CAMERA",i))(ja||{});var Wm=new jn(!0),wi=new jn(!1);var w=Wm;var Xt=class{constructor(){u(this,"node");u(this,"pre",new Set);u(this,"next",new Set);u(this,"context");u(this,"connectedNodes",new Set)}setContext(i){this.context=i,this.node&&i.addMixWeight()}removeContext(){var i;this.node&&((i=this.context)==null||i.reduceMixWeight()),delete this.context}setNode(i){var e;if(!this.node)try{(e=this.context)==null||e.addMixWeight(),this.node=i,this.preNodeReconnect(),this.reconnect(),w.addSuccessEvent({key:502701})}catch(t){A.error(t),w.addFailedEvent({key:502701,error:t})}}deleteNode(){var i;if(!!this.node)try{this._disconnect(),delete this.node,(i=this.context)==null||i.reduceMixWeight(),this.preNodeReconnect(),w.addSuccessEvent({key:502702})}catch(e){A.error(e),w.addFailedEvent({key:502702,error:e})}}preNodeReconnect(){this.pre.forEach(i=>{i.node?i.reconnect():i.preNodeReconnect()})}connectNext(i){this.next.forEach(e=>i._connect(e.node)||e.connectNext(i))}_connect(i){return!this.node||!i?!1:(this.node.connect(i),this.connectedNodes.add(i),!0)}_disconnect(){this.connectedNodes.forEach(i=>{var e;return(e=this.node)==null?void 0:e.disconnect(i)}),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(...i){return i.forEach(e=>{this.next.add(e),e.pre.add(this)}),this}},Kn=class extends Xt{constructor(e=256){super();this.fftSize=e;u(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,s=0,n=0,o=`M${s},${n}`;for(let a=0;a<e.length;a++)n=e[a]/128*100/2,o+=`L${s},${n}`,s+=t;return o}},Ds=class{constructor(){u(this,"source",new Xt);u(this,"gain",new Xt);u(this,"destination",new Xt)}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(this.source.node.context.createGain()),this.gain.node.gain.value=i}replaceSource(i){this.source.deleteNode(),this.source.setNode(Jm(i))}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}},Sr=class extends Ds{constructor(e){super();this.context=e;u(this,"denoiser",new Xt);this.source.pipeTo(this.denoiser.pipeTo(this.gain.pipeTo(this.destination)))}connect(){this.context.inputs.has(this)||(this.destination.setNode(this.context.destination),this.source.setContext(this.context),this.denoiser.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.denoiser.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.denoiser.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}},Xn=class{constructor(){u(this,"audioContext",$e("audio-mixer"));u(this,"destination",this.audioContext.createMediaStreamDestination());u(this,"inputs",new Set);u(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]}},yu=new WeakMap;function Jm(r){let i=yu.get(r);if(i)return i;let e=$e();if(r instanceof HTMLAudioElement)i=e.createMediaElementSource(r);else if(r instanceof MediaStreamTrack)i=e.createMediaStreamSource(new MediaStream([r]));else return r;return yu.set(r,i),i}var jm='class VolumeMeter extends AudioWorkletProcessor{constructor(){super(),this.volume=0,this.intervalTime=200,this.tick=this.intervalTime,this.isStop=!1,this.port.onmessage=t=>{let{data:e}=t;switch(e.name){case"setIntervalTime":this.intervalTime=e.intervalTime;break;case"stop":this.isStop=!0}}}process(t){let e=t[0];if(this.isStop)return!1;if(e.length>0){let i=e[0],s=0;for(let l=0;l<i.length;++l)s=Math.max(Math.abs(i[l]),s);this.volume=s,this.tick-=i.length,this.tick<0&&(this.tick+=this.intervalTime/1e3*sampleRate,this.port.postMessage({volume:this.volume}))}return!0}}registerProcessor("volume-meter",VolumeMeter);',Vi=class{constructor(i){u(this,"_volume",0);u(this,"_log");u(this,"_scriptProcessorNode",null);u(this,"_audioWorkletNode",null);u(this,"_interval",200);u(this,"ready",this.preload());let{log:e}=i;this._log=e,T.on(f.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){return Vi.workletReady||(Vi.workletReady=gi(Vi.audioContext,URL.createObjectURL(new Blob([jm],{type:"application/javascript"})))),Vi.workletReady.then(()=>this.initAudioWorklet()).catch(()=>this.initScriptProcessor())}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(Vi.audioContext,"volume-meter"),this._audioWorkletNode.port.onmessage=i=>{this._volume=i.data.volume||0},this.handleAudioLevelInterval({interval:this._interval})}catch(i){ee.logFailedEvent({userId:this._log.userId,eventType:Le.LOAD_WORKLET,error:i}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=$e("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=i=>{let e=i.inputBuffer.getChannelData(0),t=0;for(let s=0;s<e.length;++s)t+=e[s]*e[s];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,T.off(f.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}handleAudioLevelInterval(i){var t;let{interval:e}=i;this._interval=e,(t=this._audioWorkletNode)==null||t.port.postMessage({name:"setIntervalTime",intervalTime:e})}},Ms=Vi;u(Ms,"audioContext",$e("volume-meter")),u(Ms,"workletReady");var Qn=class extends Xt{constructor(e){super();u(this,"_volumeMeter");this._volumeMeter=new Ms(e)}deleteNode(){this._volumeMeter.destroy(),super.deleteNode()}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()}};var Ou=Ae(ke(),1);var bu=r=>i=>i.deviceId===r;var ks=class{constructor(i,e="Input"){u(this,"kind");u(this,"type");u(this,"devices",[]);this.kind=i,this.type=e}update(i,e){let t=i.filter(s=>s.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);if(this.devices.length===1&&Ir(this.devices[0])){this.devices=t;return}e&&(t.forEach(s=>{if(s.deviceId&&!this.devices.find(bu(s.deviceId))){let n=`${this.kind}${this.type}Added`;A.warn(`${n}: ${JSON.stringify(s)}`),e.emit(n,s)}}),this.devices.forEach(s=>{if(s.deviceId&&!t.find(bu(s.deviceId))){let n=`${this.kind}${this.type}Removed`;A.warn(`${n}: ${JSON.stringify(s)}`),e.emit(n,s)}})),this.devices=t}hasDevice(i){return!!this.devices.find(e=>e.deviceId===i)}},za=class extends Ou.EventEmitter{constructor(){super();u(this,"audioInputs",new ks(h.AUDIO));u(this,"videoInputs",new ks(h.VIDEO));u(this,"audioOutputs",new ks(h.AUDIO,"Output"));this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||Z.run(Oi,()=>{this.update()},{delay:1e4}))}init(){zn().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 zn(e);return this.audioInputs.update(t,this),this.videoInputs.update(t,this),this.audioOutputs.update(t,this),this})}},_e=Wr||zi?null:new za;function Ir(r){return r.deviceId===r.groupId&&r.groupId===""}function zn(){return p(this,arguments,function*(r=0){if(Wt()||!Bn())return[];let i=yield navigator.mediaDevices.enumerateDevices();if(r!==0){let e={audio:!1,video:!1};if(i.forEach(t=>{Ir(t)&&(t.kind===h.AUDIO_INPUT?e.audio=!0:t.kind===h.VIDEO_INPUT&&(e.video=!0))}),r===2&&(e.audio=!1),r===1&&(e.video=!1),e.audio||e.video){let t;try{t=yield navigator.mediaDevices.getUserMedia(e)}catch(s){A.debug("capture before getDevices failed: ",s)}i=yield navigator.mediaDevices.enumerateDevices(),t==null||t.getTracks().forEach(s=>s.stop())}}return i.map((e,t)=>{let s={kind:e.kind,deviceId:e.deviceId,groupId:e.groupId,label:e.label||`${e.kind}_${t}`};return e.deviceId.length>0&&Ya.add(`${e.deviceId}_${e.kind}`),e.getCapabilities&&(s.getCapabilities=()=>e.getCapabilities()),s})})}function Ve(r=!1){return _e.update(r?1:0).then(i=>i.audioInputs.devices)}function He(r=!1){return _e.update(r?2:0).then(i=>i.videoInputs.devices)}var vu=!1;function Du(){return p(this,null,function*(){try{vu||(vu=!0,A.info(`speakers:${(yield Ui()).map(r=>` ${r.deviceId.slice(0,8)}: ${r.label}`)}`))}catch(r){}})}function Ui(r=!1){return p(this,null,function*(){return _e.update(r?1:0).then(i=>i.audioOutputs.devices)})}var Ya=new Set;function Mu(r){if(r instanceof CanvasCaptureMediaStreamTrack||!(r instanceof MediaStreamTrack))return!1;let i=r.label.toLocaleLowerCase();if(i.includes("camera")||i.includes("webcam"))return!0;let t=`${((r==null?void 0:r.getSettings())||{}).deviceId}_${h.VIDEO_INPUT}`;return!!Ya.has(t)}function ku(r){if(r instanceof CanvasCaptureMediaStreamTrack||!(r instanceof MediaStreamTrack))return!1;let i=r.label.toLocaleLowerCase();if(i.includes("mic")||i.includes("\u9EA6\u514B\u98CE"))return!0;let t=`${((r==null?void 0:r.getSettings())||{}).deviceId}_${h.AUDIO_INPUT}`;return!!Ya.has(t)}function Za(r,i){return p(this,null,function*(){let t=(yield Ve()).find(s=>s.deviceId===vi);return(t==null?void 0:t.groupId)===r&&t.label===i})}function Lu(n){return p(this,arguments,function*({newDeviceId:r,oldDeviceId:i,oldGroupId:e,oldLabel:t,kind:s}){return r!==i?!1:s===h.AUDIO&&r===vi?yield Za(e,t):!0})}var ec=class extends Ds{constructor(e){super();this.log=e;u(this,"volumeMeter");u(this,"analyser",new Kn);this.volumeMeter=new Qn({log:this.log})}destory(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode()}},Ar=class extends qt{constructor(e){super(e,h.AUDIO);u(this,"_outputDeviceId");u(this,"_volume",1);u(this,"_destination",$e("player").createMediaStreamDestination());u(this,"pipeline");u(this,"volumeMeterMode","worklet");this.pipeline=new ec(this._log)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(){if((li==="15.2"||li==="15.3"||li==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}let t=new Audio;t.setAttribute("autoplay","autoplay"),t.srcObject=this.getMediaStream(),t.muted=this.muted,this.element=t,this.bindElementEvents()}play(){return p(this,null,function*(){if(!!this.track)return this.pipeline.source.node||this.pipeline.replaceSource(this.track),this.element||this.initializeElement(),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),this.volumeMeterMode==="worklet"?this.pipeline.volumeMeter.init():this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode($e("player").createAnalyser()),this.setVolume(this._volume),Du(),Re(Ar.prototype,this,"play").call(this)})}stop(){this.pipeline.destory(),super.stop()}setSinkId(e){return p(this,null,function*(){var t,s;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield(s=(t=this.element).setSinkId)==null?void 0:s.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()}},Yn=class extends Ar{constructor(i){super(i),this.pipeline.source.pipeTo(this.pipeline.volumeMeter,this.pipeline.destination)}setTrack(i){this.track!==i&&(this.unbindTrackEvents(),this.track=i,this.emit(Pe.MEDIA_TRACK_CHANGED,i),i?(this.bindTrackEvents(),this.pipeline.replaceSource(i),!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([i]))):this.pipeline.source.deleteNode())}setSourceNode(i){!i||this.pipeline.source.node===i||(this.pipeline.replaceSource(i),i instanceof MediaStreamAudioSourceNode?this.pipeline.destination.setNode(this._destination):this.pipeline.destination.deleteNode(),this.element&&(this.element.srcObject=this.getMediaStream(),this.element.play().catch(()=>{}),this.setVolume(this._volume)))}setVolume(i){this._volume=i,this.element&&(this.element.volume=i)}},Zn=class extends Ar{constructor(e){super(e);u(this,"_sourceElement");this.pipeline.source.pipeTo(this.pipeline.gain.pipeTo(this.pipeline.volumeMeter,this.pipeline.destination))}setTrack(e){this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(Pe.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.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){this._volume=e,this.useDestination?(this.pipeline.setVolume(e),this._log.info(`set pipeline volume: ${e}`)):e<=1?(this.element?this._log.info(`set element volume: ${e}`):this._log.info("set element volume: no element"),this.element&&(this.element.volume=e)):(this._log.info(`start set pipeline volume: ${e}`),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),pe(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play()))}stop(){this.pipeline.destory(),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop()}};var Bi=class extends V{constructor({userId:e,sdkAppId:t,mediaType:s,room:n,PlayerClass:o=s===1?Zn:ut}){var a;super();u(this,"id",gs());u(this,"userId","");u(this,"isRemote");u(this,"mediaType");u(this,"room");u(this,"user");u(this,"_log");u(this,"_inputTrack");u(this,"_outputTrack");u(this,"isPlayCalled");u(this,"container",null);u(this,"player");u(this,"subVideoPlayerMap");u(this,"muted",!1);u(this,"abortCtrl");u(this,"objectFit","cover");u(this,"mirror");u(this,"isScreen",!1);u(this,"manager");u(this,"trackSettings");this.userId=e||"",this.mediaType=s,this._log=A.createLogger({id:`${this.kind[0]}t`,userId:(a=n||this.room)==null?void 0:a.userId,remoteUserId:this instanceof Fe?void 0:this.userId,sdkAppId:t,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof Fe}),this.player=new o({id:this.userId||this.id,track:null,muted:!1,container:null,log:this.log}),this.player.on(Pe.PLAYER_STATE_CHANGED,c=>{T.emit(f.PLAYER_STATE_CHANGED,N({track:this},c)),this.emit("player-state-changed",c)}),this.kind===h.VIDEO&&(this.player.on(Pe.LOADED_DATA,()=>{T.emit(f.VIDEO_LOADED_DATA,{track:this})}),this.player.on(Pe.MEDIA_TRACK_CHANGED,c=>{var d;(d=this.subVideoPlayerMap)==null||d.forEach(l=>l.setTrack(c))}))}get log(){return this._log||A}get kind(){return this.mediaType===1?h.AUDIO:h.VIDEO}get strMediaType(){return this.mediaType===4?h.VIDEO:this.mediaType===2?h.SCREEN:h.AUDIO}get streamType(){return(this.mediaType&2)===0?"main":"auxiliary"}play(e,t){return p(this,null,function*(){let s=de(e)?e[0]:e;if(this.isPlayCalled){this.log.info(`play update options: ${JSON.stringify(t)}`),t&&!E(t.muted)&&this.setPlayerMute(t.muted),t&&!E(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof ut&&(this.player.setObjectFit(this.objectFit),this.container!==s&&s&&(this.container=s,this.player.setContainer(s)),de(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t)));return}if(t&&!E(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===h.VIDEO)&&this.setPlayerMute(!0),t&&!E(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof ut&&this.player.setObjectFit(this.objectFit),this.isPlayCalled=!0,s&&(this.container=s,this.player instanceof ut&&this.player.setContainer(s)),T.emit(f.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(),de(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(n){throw this.handleAutoPlayFailed(),this.emit("error",n),n}})}setMirror(e,t){if(this.isScreen||this.kind!==h.VIDEO||E(e)||e===this.mirror)return;this.mirror=e;let s=this.player;t&&(s=t);let n=this.manager;if(ue(this.mirror)){s.setViewMirror(this.mirror),n&&(n.mirror=!1);return}switch(this.mirror){case"view":{n&&(n.mirror=!1),s.setViewMirror(!0);break}case"publish":{n&&(n.mirror=!0),s.setViewMirror(!0);break}case"both":n&&(n.mirror=!0),s.setViewMirror(!1)}}playSubContainer(e,t){return p(this,null,function*(){if(!this._outputTrack||this.kind===h.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((n,o)=>{var a;e.find(c=>o===c)||(n.stop(),(a=this.subVideoPlayerMap)==null||a.delete(o))});for(let[n,o]of e.entries()){let a=this.subVideoPlayerMap.get(o);a?t&&(E(t.objectFit)||a.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(o,new ut({id:this.userId||this.id,track:this.playerMediaTrack,container:o,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:`vp-sub${n+1}`})}))}let s=[...this.subVideoPlayerMap.values()];for(let n of s)n.setViewMirror(this.player.mirror),yield n.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(){!this.isPlayCalled||(this.isPlayCalled=!1,this.player&&(this.log.info(`stop ${this.kind} player`),this.player.stop()),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(e=>{e.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()}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),T.emit(e?f.TRACK_MUTED:f.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}setInputMediaStreamTrack(e){var s;let t=this._inputTrack;if(e!==t)return this._inputTrack=e,this.trackSettings=(s=e.getSettings)==null?void 0:s.call(e),e.enabled=!this.muted,this.emit("input-media-track-changed",e||null,t||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var s;let t=this._outputTrack;e!==t&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",(s=e.getSettings)==null?void 0:s.call(e).deviceId,e.label),this._outputTrack=e,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(()=>this.handleAutoPlayFailed()),this.log.info(`playing state updated, play ${this.kind}`);return}}else if(!this.player.isStopped){this.player.stop(),this.log.info(`playing state updated, stop ${this.kind}`);return}}this.log.debug(`updatePlayingState abort ${this.isPlayCalled} ${e} ${this.player.isStopped}`)}handleAutoPlayFailed(){if(this.room&&this.room.enableAutoPlayDialog)new Cu;else{let e=()=>{this.resume().then(()=>{document.removeEventListener("click",e,!0),document.removeEventListener("touchstart",e,!0)})};document.addEventListener("click",e,!0),document.addEventListener("touchstart",e,!0)}}getVideoFrame(){return this.player instanceof ut?this.player.getVideoFrame():""}};b([oe([],V.INIT,{sync:!0})],Bi.prototype,"close",1);var qm=Object.prototype.hasOwnProperty,{toString:$g}=Object.prototype;function Km(r){if(r==null)return!0;if(typeof r=="boolean")return!1;if(typeof r=="number")return r===0;if(typeof r=="string"||typeof r=="function"||Array.isArray(r))return r.length===0;if(r instanceof Error)return r.message==="";if(Be(r))switch(Object.prototype.toString.call(r)){case"[object File]":case"[object Map]":case"[object Set]":return r.size===0;case"[object Object]":{for(let i in r)if(qm.call(r,i))return!1;return!0}}return!1}var yt=Km;var Xm=function(r){return p(this,null,function*(){let i=zm(r);A.info(`getUserMedia with constraints: ${JSON.stringify(i)}`);let e=[],t=[],s=["label","deviceId"];i.audio&&(e=yield Ve(),A.info(`microphones: ${dt(e,{keysToInclude:s})}`)),i.video&&(t=yield He(),A.info(`cameras: ${dt(t,{keysToInclude:s})}`));try{let n=yield navigator.mediaDevices.getUserMedia(i);return Va&&n.getTracks().forEach(o=>{A.info(`${o.kind} capabilities: ${dt(o.getCapabilities(),{keysToInclude:fn})}`)}),n}catch(n){let{message:o}=n;throw n.name==="NotFoundError"&&(r.video&&t&&t.length===0&&(o=D({key:v.CAMERA_NOT_FOUND})),r.audio&&e&&e.length===0&&(o=D({key:v.MICROPHONE_NOT_FOUND}))),new C({code:I.INITIALIZE_FAILED,name:n.name,message:o,constraint:n.constraint})}})},Qm=gt({retryFunction:Xm,settings:{retries:3,timeout:500},onError:({error:r,retry:i,reject:e,retryFuncArgs:t,retriedCount:s})=>{let n=s+1;r.name==="NotReadableError"||r.name==="OverconstrainedError"?(n===1?t[0].video&&(t[0].maxResolution=!1,t[0].frameRate&&(t[0].frameRate=t[0].frameRate>10?10:5)):n===2?t[0].useDeviceIdOnly=!0:n===3&&!t[0].useExactDeviceId&&(t[0].useTrueAsConstraint=!0),i()):e(r),t[0].microphoneId&&xu(t[0].microphoneId,!1),t[0].cameraId&&xu(t[0].cameraId,!0)},onRetrying:r=>{A.warn(`getUserMedia NotReadableError observed, retrying [${r}/3]`)},onRetryFailed:r=>{ee.logFailedEvent({eventType:Le.GET_USER_MEDIA_RETRY,error:r})},onRetrySuccess:r=>{ee.logSuccessEvent({eventType:Le.GET_USER_MEDIA_RETRY}),ee.uploadEvent({log:`stat-${Le.GET_USER_MEDIA_RETRY}-success-${r}`})}});function xu(r,i){return p(this,null,function*(){let t=(i?yield He():yield Ve()).find(s=>s.deviceId===r);t&&X(t.getCapabilities)&&A.warn(dt(t.getCapabilities(),{keysToInclude:fn}))})}function zm(r){return{audio:Ym(r),video:Zm(r)}}function Ym(r){if(!r.audio)return!1;if(r.useTrueAsConstraint)return!0;let i={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:r.sampleRate};return!yt(r.microphoneId)&&(i.deviceId=r.useExactDeviceId?{exact:r.microphoneId}:r.microphoneId,r.useDeviceIdOnly)?i:(re(r.channelCount)&&(i.channelCount=r.channelCount),ue(r.echoCancellation)&&!r.echoCancellation&&(i.echoCancellation=!1),ue(r.noiseSuppression)&&!r.noiseSuppression&&(i.noiseSuppression=!1),ue(r.autoGainControl)&&!r.autoGainControl&&(i.autoGainControl=!1),yt(i)?!0:i)}function Zm(r){if(!r.video)return!1;if(r.useTrueAsConstraint)return!0;let{maxResolution:i=!0}=r,e={};return r.cameraId?e.deviceId=r.useExactDeviceId?{exact:r.cameraId}:r.cameraId:r.facingMode&&(e.facingMode=r.facingMode),r.useDeviceIdOnly&&!yt(e)?e:(r.width&&(e.width={ideal:r.width},i&&!Y&&(e.width.max=r.width)),r.height&&(e.height={ideal:r.height},i&&!Y&&(e.height.max=r.height)),Y&&ft&&r.width&&r.height&&r.width*r.height<352*288&&(e.width=r.width,e.height=r.height),r.frameRate&&(e.frameRate=r.frameRate),yt(e)?!0:e)}var Pu=Qm;function eo(r){return F((i,e)=>function(...t){return p(this,null,function*(){return yield r.apply(this,t),i.apply(this,t)})})}function to(r){return F((i,e)=>function(...t){return p(this,null,function*(){return r.call(this,i.apply(this,t))})})}function F(r){return function(i,e,t){return t.value=r(t.value,e),t}}var wu=(()=>{let r=!1,i=document.visibilityState;return()=>{document.visibilityState!==i&&A.info(`visibility change: ${document.visibilityState}`),!r&&(document.addEventListener("visibilitychange",()=>{A.info(`visibility change: ${document.visibilityState}`),i=document.visibilityState}),r=!0)}})();var ep=0,io=class{constructor(){this.log=A.createLogger({id:`fq${++ep}`});this.isRunning=!1;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 n,o;let t=N({},i),s=new Promise((a,c)=>{t.resolve=a,t.reject=c});return t.promise=s,e?this.length<=1?this.queue.push(t):(o=(n=this.lastQueueItem)==null?void 0:n.promise)==null||o.then(t.resolve,t.reject):this.queue.push(t),this.log.debug(`push ${this.length}`),this.isRunning||this.callNext(),s}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:s,reject:n}=this.queue[0];this.isRunning=!0,i.apply(t,e).then(s,n).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},xs=new WeakMap,ro=new WeakMap;function Nt(r=!1){return function(i,e,t){let s=t.value;return t.value=function(...n){let o=xs.get(this)||new io;return xs.set(this,o),o.push({fn:s,args:n,context:this},r)},t}}function Vu(r){return function(i,e,t){let s=t.value;return t.value=function(...n){let o=xs.get(this);if(o){let a=o.queue.filter((c,d)=>{if(d===0)return!0;let l=!0;return c.args.forEach(m=>{n.find(_=>_===m)||(l=!1)}),l?(c.reject(new C({code:I.API_CALL_ABORTED,message:r})),!1):!0});o.queue=a}return s.apply(this,n)},t}}function so(r){return function(i,e,t){let s=t.value;return t.value=function(...n){var a,c,d;let o=[];return(c=(a=xs.get(this))==null?void 0:a.queue)==null||c.forEach(l=>o.push(l)),(d=ro.get(this))==null||d.forEach(l=>l==null?void 0:l.queue.forEach(m=>o.push(m))),o.forEach(l=>{l.reject(new C({code:I.API_CALL_ABORTED,message:r}))}),xs.delete(this),ro.delete(this),s.apply(this,n)},t}}function Rr(r){return function(i,e,t){let s=t.value,n=o=>r(...o);return t.value=function(...o){let a=ro.get(this)||new Map,c=a.get(n(o))||new io;return a.set(n(o),c),ro.set(this,a),c.push({fn:s,args:o,context:this})},t}}var Fe=class extends Bi{constructor(e,t){super({mediaType:e,PlayerClass:t});u(this,"isRemote",!1);u(this,"deviceId");u(this,"groupId","");u(this,"label","");u(this,"_isRecapturing",!1);u(this,"_lastRecaptureTime",0);u(this,"_onMuteTimeoutId",-1);u(this,"profile");this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this)}get isPublished(){return this.state==="publish"}installTrackEvent(e){we(e,e).add(h.MUTE,this.onTrackMuted).add(h.UNMUTE,this.onTrackUnmuted).add(h.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===h.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){pe(e)}setStateToCapture(){}capture(e){return p(this,null,function*(){var t;try{let s=B();T.emit(f.LOCAL_TRACK_CAPTURE_START,{track:this});let n;e.customSource?(n=new MediaStream,n.addTrack(e.customSource)):((t=this.mediaTrack)==null||t.stop(),n=yield Pu(e));let o=n.getTracks()[0];return yield this.setInputMediaStreamTrack(o),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),T.emit(f.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:B()-s}),n}catch(s){throw T.emit(f.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:s}),this.log.error(`getUserMedia error observed ${s}`),s}})}setInputMediaStreamTrack(e){this.state===V.INIT&&this.setStateToCapture(),this._inputTrack&&this.uninstallTrackEvent(this._inputTrack);let t=super.setInputMediaStreamTrack(e);return this.installTrackEvent(e),t}setOutputMediaStreamTrack(e){var t;return super.setOutputMediaStreamTrack(e),(t=this.room)==null?void 0:t.replaceTrack(this)}publish(e,t){return this.room=e,this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),t}unpublish(){this.room&&this.room.localTracks.delete(this),T.emit(f.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return p(this,null,function*(){if(this.mediaTrack&&Rt){let{deviceId:e,groupId:t}=this.mediaTrack.getSettings(),{label:s}=this.mediaTrack;(yield Lu({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=s,t&&(this.groupId=t),zn().then(o=>{let a=o.find(c=>c.deviceId===e);a&&this.emit("2",a)}))}})}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(e=!1){return!(!this.deviceId||!this.mediaTrack||this.kind===h.AUDIO&&!ku(this.mediaTrack)||this.kind===h.VIDEO&&!Mu(this.mediaTrack)||this._isRecapturing||e&&ft&&Xe)}onTrackMuted(){if(wu(),!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<er){setTimeout(()=>this.onTrackMuted(),er);return}this._onMuteTimeoutId=setTimeout(()=>p(this,null,function*(){var e;if((e=this.mediaTrack)!=null&&e.muted){if((Ue||ye)&&document.visibilityState!=="visible")return;this.recapture(yield this.getRecoverCaptureDeviceId())}}),5e3)}}onTrackUnmuted(){this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return p(this,null,function*(){if(!!this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<er){setTimeout(()=>this.onTrackEnded(),er);return}this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e){return p(this,null,function*(){var s;if(this._isRecapturing||!this._inputTrack)return;this.log.warn("recapture trying"),(s=this._inputTrack)==null||s.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let t={useExactDeviceId:!0};if(e==="user"||e==="environment")t.facingMode=e;else{let n;(this.kind==="audio"?yield Ve():yield He()).find(a=>a.deviceId===e)&&(n=e),t.deviceId=n}return this.capture(t).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId})}).catch(n=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${n.message}`),this.emit("5",n)})})}getRecoverCaptureDeviceId(){return p(this,null,function*(){let e=this instanceof ae;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let s=(Ps.get(t)||0)+1;if(Ps.set(t,s),s>=3){let n=e?(yield He()).find(o=>!Ps.has(o.deviceId)):(yield Ve()).find(o=>!Ps.has(o.deviceId));n&&(this.log.warn(`${t} capture fail ${s} times, change new ${n.deviceId}`),t=n.deviceId)}}return t})}close(){var e;super.close(),this._inputTrack&&(this._inputTrack.stop(),this.uninstallTrackEvent(this._inputTrack)),(e=this.manager)==null||e.removeInput(this)}};b([oe(V.INIT,"capture",{ignoreError:!0,sync:!0})],Fe.prototype,"setStateToCapture",1),b([Nt()],Fe.prototype,"capture",1),b([oe("capture","publish",{ignoreError:!0,success(){this.room.localTracks.add(this),T.emit(f.LOCAL_TRACK_PUBLISHED,{track:this}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"})},fail(r){let i="error",e=r.cause;e.message.includes("timeout")?i="timeout":e.code===I.API_CALL_ABORTED&&(i="api-call"),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:i,error:e})}})],Fe.prototype,"publish",1),b([F(r=>function(){return p(this,null,function*(){let i=this.state==="publish"?"started":"starting";r.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:i,reason:"api-call"})})}),oe([],"capture",{sync:!0})],Fe.prototype,"unpublish",1);var Ps=new Map;T.on(f.SWITCH_DEVICE_SUCCESS,r=>{r.track.deviceId&&Ps.delete(r.track.deviceId)});var Ne=class extends Fe{constructor(e){super(1,Yn);u(this,"mediaType",1);u(this,"volume",0);u(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40});u(this,"playerMuted",!0);u(this,"pipeline");this.manager=e,this.pipeline=new Sr(e),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this)}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}get playerMediaTrack(){return this.mediaTrack}setInputMediaStreamTrack(e){return p(this,null,function*(){yield Re(Ne.prototype,this,"setInputMediaStreamTrack").call(this,e);let t=this.trackSettings||{};w.addEnum({key:501701,value:t.channelCount||0,useUV:!1}),w.addEnum({key:501702,value:t.sampleRate||0,useUV:!1}),w.addEnum({key:502700,value:0});let{sampleRate:s,channelCount:n}=t;this._log.info(`local audio track input ${JSON.stringify({sampleRate:s,channelCount:n})}`),this.pipeline.replaceSource(e),this.updatePlayingState(!!e)})}capture({deviceId:e,customSource:t,useExactDeviceId:s=!1}){return super.capture({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:s,customSource:t})}switchDevice(e){return p(this,null,function*(){if(!!this.mediaTrack){if(this.deviceId===e)if(e===vi){if(yield Za(this.groupId,this.label))return}else return;try{this.log.info(`switchDevice audio to: ${e}`),this.mediaTrack&&this.mediaTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0}),this.room&&(yield this.room.replaceTrack(this)),T.emit(f.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(){_e&&!_e.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&_e.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return p(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current microphone is lost: ${JSON.stringify(e)}`);let t=yield Ve();t[0]?this.recapture(t[0].deviceId):_e.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.log.warn(`microphone added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)}update3A(n){return p(this,arguments,function*({echoCancellation:e,noiseSuppression:t,autoGainControl:s}){let o=!1;!E(e)&&e!==this.profile.echoCancellation&&(this.profile.echoCancellation=e,o=!0),!E(t)&&t!==this.profile.noiseSuppression&&(this.profile.noiseSuppression=t,o=!0),!E(s)&&s!==this.profile.autoGainControl&&(this.profile.autoGainControl=s,o=!0),o&&this.deviceId&&(yield this.recapture(this.deviceId))})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&w.addEnum({key:502700,value:2}),this.resetPlayerSource()}enableTrackANS(e){if(!this._inputTrack)return;let t=this._inputTrack.getConstraints();return t.noiseSuppression=e,this._inputTrack.applyConstraints(t).catch(s=>this._log.warn(`${e?"enable":"disable"} ANS failed `,s))}addDenoiser(e){var t;if(Ut<=92&&((t=this.trackSettings)==null?void 0:t.sampleRate)!==48e3){this._log.warn("denoiser only support sampleRate 48000 before chrome 93");return}w.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.resetPlayerSource(),this.enableTrackANS(!1)}removeDenoiser(e){this.pipeline.denoiser.node===e&&(this.pipeline.denoiser.deleteNode(),this.resetPlayerSource(),this.enableTrackANS(!0))}resetPlayerSource(){this.player.setSourceNode(this.pipeline.gain.node||this.pipeline.denoiser.node||this.pipeline.source.node)}close(){this.pipeline.remove(),_e.off("audioInputAdded",this.handleMicrophoneAdded,this),_e.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}recapture(e){return p(this,null,function*(){try{yield Re(Ne.prototype,this,"recapture").call(this,e)}catch(t){let s=(yield Ve()).find(n=>n.deviceId!==e);if(s)yield Re(Ne.prototype,this,"recapture").call(this,s.deviceId);else throw t}})}};var ae=class extends Fe{constructor(e,t=4){super(t,ut);u(this,"profile",{width:640,height:480,frameRate:15,bitrate:500});u(this,"states",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0});u(this,"small");u(this,"isNeedToSetBandwidth");u(this,"muteImage");u(this,"manager");this.manager=e;let s=()=>{this.isAllowed2k4k(this.profile)?this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1}):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),this.setProfile(L(N({},this.profile),{width:1920,height:1080})),this.applyProfile())};this.on("input-media-track-changed",s),this.on("publish",s),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(!(!Rt||!this.mediaTrack))return this.mediaTrack.getSettings().facingMode}setMute(e){return p(this,null,function*(){var t,s,n;if(Q(e)){if(this.muteImage===e)return;yield(t=this.manager)==null?void 0:t.deleteWatermark("mute"),yield(s=this.manager)==null?void 0:s.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:e}),this.muteImage=e,Re(ae.prototype,this,"setMute").call(this,!1)}else yield(n=this.manager)==null?void 0:n.deleteWatermark("mute"),this.muteImage=void 0,Re(ae.prototype,this,"setMute").call(this,e)})}capture({deviceId:e,facingMode:t,useExactDeviceId:s=!1,customSource:n}){return super.capture({audio:!1,video:!0,facingMode:t||this.facingMode,cameraId:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:s,customSource:n})}setProfile(e){let t=N({},e),s=t.width>t.height;t.width*t.height<=160*120&&ye&&Mi&&(this.log.warn(`resolution is ${t.width}*${t.height}, fallback to 240*180`),t.width=s?240:180,t.height=s?180:240,t.bitrate=Math.max(t.bitrate,150)),t.width*t.height>1280*720&&ga&&(t.width=s?1280:720,t.height=s?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),t.bitrate&&(this.isNeedToSetBandwidth=t.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile)?super.setProfile(t):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),super.setProfile(L(N({},this.profile),{width:1920,height:1080})))}applyProfile(){var s;if(!this.mediaTrack)return;let e=this.settings;if(e.height!==this.profile.height||e.width!==this.profile.width||e.frameRate!==this.profile.frameRate)return(s=this.mediaTrack)==null?void 0:s.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}).then(()=>{if(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)return this.isNeedToSetBandwidth=!1,this.room.setBandWidth({bandwidth:this.profile.bitrate,type:h.VIDEO,videoType:h.BIG})})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate};return Rt&&this.mediaTrack&&Object.assign(e,this.mediaTrack.getSettings()),e}get scaleResolutionDownBy(){let{settings:e}=this;return e.width===this.profile.width&&e.height===this.profile.height?1:ba()&&this.profile.width>this.profile.height&&e.height>e.width?Math.max(e.width/this.profile.height,e.height/this.profile.width,1):Math.max(e.width/this.profile.width,e.height/this.profile.height,1)}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))return;let t={useExactDeviceId:!0};e==="user"||e==="environment"?t.facingMode=e:t.deviceId=e,this.mediaTrack.stop(),yield this.capture(t),T.emit(f.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}})}listenDeviceChange(){_e&&!_e.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&_e.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return p(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current camera is lost: ${JSON.stringify(e)}`);let t=yield He();t[0]?this.recapture(t[0].deviceId):_e.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return p(this,null,function*(){this.log.warn(`camera added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)})}play(e,t){return p(this,null,function*(){return E(this.mirror)&&!this.isScreen&&this.setMirror("view"),Re(ae.prototype,this,"play").call(this,e,t)})}close(){_e.off("videoInputAdded",this.handleCameraAdded,this),_e.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return p(this,null,function*(){try{yield Re(ae.prototype,this,"recapture").call(this,e)}catch(t){let s=(yield He()).find(n=>n.deviceId!==e);if(s)yield Re(ae.prototype,this,"recapture").call(this,s.deviceId);else throw t}})}};var Bu=gs();if(navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:Bu,exposeOrigin:!0,permittedOrigins:["*"]})}catch(r){}var np=function(r){return p(this,null,function*(){let i=null,e=cp(r);A.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let t=yield navigator.mediaDevices.getDisplayMedia(e);r.systemAudio&&t.getAudioTracks().length===0&&(dr&&Ut<74||Xe||Y)&&A.warn("Your browser not support capture system audio");let s=t.getVideoTracks()[0];if(s){if(r.frameRate)try{yield s.applyConstraints({frameRate:{min:r.frameRate,ideal:r.frameRate},width:r.width,height:r.height})}catch(n){A.warn(`screen applyConstraints failed: ${n}`)}r.captureElement&&(yield op(s,r.captureElement))}if(r.audio){let n=ap(r);A.info(`getUserMedia with constraints: ${JSON.stringify(n)}`),i=yield navigator.mediaDevices.getUserMedia(n),t.addTrack(i.getAudioTracks()[0])}return t})};function op(r,i){return p(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&X(r.cropTo))try{if(!(((e=r.getCaptureHandle())==null?void 0:e.handle)===Bu))return;let s=yield CropTarget.fromElement(i);yield r.cropTo(s)}catch(t){A.warn(`cropTo target failed ${t}`)}})}function ap(r){let i={echoCancellation:r.echoCancellation,autoGainControl:r.autoGainControl,noiseSuppression:r.noiseSuppression,sampleRate:r.sampleRate,channelCount:r.channelCount};return E(r.microphoneId)||(i.deviceId=r.microphoneId),{audio:i,video:!1}}function cp(r){let i={preferCurrentTab:r.preferDisplaySurface==="current-tab",systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:Xe?{max:r.width}:{ideal:r.width,max:r.width},height:Xe?{max:r.height}:{ideal:r.height,max:r.height},frameRate:r.frameRate,displaySurface:r.preferDisplaySurface||"monitor"};if(i.video=e,r.systemAudio){let{echoCancellation:t=!0,noiseSuppression:s=!1,autoGainControl:n=!1}=r;i.audio={echoCancellation:t,noiseSuppression:s,autoGainControl:n,sampleRate:48e3}}return i}var $u=np;var Ge=class extends ae{constructor(e){super(e,2);u(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600});u(this,"objectFit","contain");u(this,"isScreen",!0);this._log.id=`s-${this._log.id}`}capture(l){return p(this,arguments,function*({systemAudio:e=!1,autoGainControl:t,echoCancellation:s,noiseSuppression:n,audioTrack:o,videoTrack:a,captureElement:c,preferDisplaySurface:d}){try{let m;return a||o?(m=new MediaStream,a&&m.addTrack(a),o&&m.addTrack(o)):m=yield $u({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:t,echoCancellation:s,noiseSuppression:n,captureElement:c,preferDisplaySurface:d}),yield this.setInputMediaStreamTrack(m.getVideoTracks()[0]),m}catch(m){throw this.log.error(`getDisplayMedia error observed ${m}`),m instanceof C?m:new C({code:I.INITIALIZE_FAILED,name:m.name,message:m.message})}})}switchDevice(e){return p(this,null,function*(){throw new Error("Method not implemented.")})}};var bt=class extends Ne{constructor(i){super(i),this._log.id=`s-${this._log.id}`}};var dp="registerProcessor('dumper', class extends AudioWorkletProcessor {process(inputs) {this.port.postMessage(inputs);return true;}});",tc;function Hu(r){return p(this,null,function*(){let i=$e("dump");tc||(tc=gi(i,URL.createObjectURL(new Blob([dp],{type:"application/javascript"})))),yield tc;let e=new AudioWorkletNode(i,"dumper",{numberOfInputs:r.length,numberOfOutputs:0});return r.forEach((t,s)=>t.connect(e,0,s)),new ReadableStream({start(t){e.port.onmessage=s=>{t.enqueue(s.data)}},cancel(){r.forEach(t=>t.disconnect(e)),e.port.close()}})})}var no=class extends Xn{constructor(e){super();this.room=e;u(this,"_localAudioTrack");u(this,"_localScreenAudioTrack");u(this,"log",A.createLogger({id:"am"}));u(this,"denoiser");e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId))}get _localAudioPipline(){var e;return(e=this._localAudioTrack)==null?void 0:e.pipeline}dump(e){var l,m;if(!this._localAudioTrack)return;let t=[],s=[];(l=this._localAudioPipline)!=null&&l.source.node&&(t.push(this._localAudioPipline.source.node),s.push("mic")),(m=this._localAudioPipline)!=null&&m.denoiser.node&&(t.push(this._localAudioPipline.denoiser.node),s.push("mic-processed")),this.mixWeight>1&&(t.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),s.push("mix")),this.log.info(`dump audio track ${s}, duration: ${e}`);let n=new AbortController,o=[],a=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),n.abort("timeout")},e*1e3),c=()=>{for(let _=0;_<s.length;_++){let g=URL.createObjectURL(new Blob(o[_])),R=document.createElement("a");R.href=g,R.download=`${s[_]}.pcm`,R.style.display="none",document.body.appendChild(R),R.click(),URL.revokeObjectURL(g),R.remove()}clearTimeout(a),n.abort("download")},d=Hu(t).then(_=>_.pipeTo(new WritableStream({write(g){g.forEach((R,y)=>o[y]=o[y]?o[y].concat(R[0]):[R[0]])}}),n).catch(g=>c));return{then:d.then.bind(d),download:c}}get hasScreenAudioTrack(){return this._localScreenAudioTrack!==null}get hasAudioTrack(){return this._localAudioTrack!==null}changeInput(e){var t;if(e instanceof bt)this._localScreenAudioTrack=e,e.pipeline.connect(),this.mixOnChange();else if(e instanceof Ne)this._localAudioTrack=e,this.destination.channelCount=((t=e.trackSettings)==null?void 0:t.channelCount)||1,this.denoiser&&e.addDenoiser(this.denoiser),e.pipeline.connect(),this.mixOnChange();else if(e instanceof Qt)return e.setOutputMediaStreamTrack(e.mediaTrack)}mixOnChange(){var e,t;(e=this._localAudioTrack)==null||e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),(t=this._localScreenAudioTrack)==null||t.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)}removeInput(e){e instanceof bt?delete this._localScreenAudioTrack:e instanceof Ne?delete this._localAudioTrack:e instanceof Qt}addDenoiser(e){var t;this.denoiser=e,(t=this._localAudioTrack)==null||t.addDenoiser(e)}removeDenoiser(e){var t;delete this.denoiser,(t=this._localAudioTrack)==null||t.removeDenoiser(e)}destroy(){this.close()}};function oo(r=30,i=2){return F((e,t)=>function(...s){return new Promise((n,o)=>{let a=setTimeout(()=>{let c=new C({code:I.API_CALL_TIMEOUT,message:`checkPendingPromise ${t}() timeout ${r}s`});A.warn(c),i===2?o(c):i===1&&n()},r*1e3);e.apply(this,s).then(n,o).finally(()=>{clearTimeout(a)})})})}var ic=class extends Bi{constructor(e,t,s){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:s,room:e});this.room=e;this.user=t;u(this,"tinyId");u(this,"isRemote",!0);this.tinyId=t.tinyId}setMute(e){this.hasFlag&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.hasFlag&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}waitHasMediaTrack(){return new Promise(e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)})}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===ic.STATE_SUBSCRIBE}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}updatePlayingState(e){if(this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.hasFlag||!this.outMediaTrack)){this.log.info(`abort play, isSubscribed:${this.isSubscribed} hasFlag:${this.hasFlag} hasTrack:${!!this.outMediaTrack}`);return}super.updatePlayingState(e)}}onFlagChanged(){this.updatePlayingState(this.hasFlag)}},Ye=ic;u(Ye,"STATE_SUBSCRIBE","subscribe"),b([oo(5,1)],Ye.prototype,"waitHasMediaTrack",1),b([oe(V.INIT,Ye.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),T.emit(f.REMOTE_TRACK_SUBSCRIBED,{track:this}),this.updatePlayingState(!0)},ignoreError:!0})],Ye.prototype,"subscribe",1),b([oe(Ye.STATE_SUBSCRIBE,V.INIT,{sync:!0,success(){this.log.info("unsubscribed"),this.updatePlayingState(!1),T.emit(f.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],Ye.prototype,"unsubscribe",1);var Qt=class extends Ye{constructor(e,t){super(e,t,1);u(this,"volume",0);u(this,"mediaType",1);u(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.audioManager}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get hasFlag(){return this.user.muteState.hasAudio&&!this.user.muteState.audioMuted}isFlagChanged(e){let t=e.hasAudio&&!e.audioMuted;return this.hasFlag||(this.volume=0),this.hasFlag!==t}};var vt=class extends Ye{constructor(e,t,s=4){super(e,t,s);u(this,"mediaType",4);u(this,"source");u(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.videoManager}get isBig(){return this.mediaType===4}get isSmall(){return this.mediaType===8}changeType(e){this.room.changeType(e,this.user)}get hasFlag(){return this.user.muteState.hasVideo&&!this.user.muteState.videoMuted}isFlagChanged(e){let t=e.hasVideo&&!e.videoMuted;return this.hasFlag!==t}setMirror(e){e==="publish"||e==="both"||super.setMirror(e)}},Cr=class extends vt{constructor(e,t){super(e,t,2);u(this,"mediaType",2);u(this,"objectFit","contain")}get hasFlag(){return this.user.muteState.hasAuxiliary}isFlagChanged(e){let t=e.hasAuxiliary;return this.hasFlag!==t}};function fe(...r){}var up=r=>r();function sc(){this.dispose()}var lp=()=>typeof __FASTRX_DEVTOOLS__!="undefined",hp=1,zt=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(i){let e=new rc(i,this,this.streamId++);return lt.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},ws=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=fe,this.error=fe,this.next=fe,this.dispose=fe,this.subscribe=fe,this.doDefer()}subscribe(i){return i instanceof zt?i.subscribe(this):i(this),this}get bindSubscribe(){return i=>this.subscribe(i)}doDefer(){this.defers.forEach(up),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}},U=class extends ws{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)}};function Fu(r,...i){return i.reduce((e,t)=>t(e),r)}function Yt(r,i,e){if(lp()){let t=Object.defineProperties(Object.setPrototypeOf(r,zt.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}});lt.create(t);for(let s=0;s<e.length;s++){let n=e[s];typeof n=="function"&&n instanceof zt&&lt.addSource(t,n)}return t}return r}function G(r,i){return function(...e){return t=>{if(t instanceof zt){let s=Yt(n=>{let o=new r(n,...e);o.sourceId=s.id,o.subscribe(t)},i,arguments);return s.source=t,lt.pipe(s),s}else return s=>t(new r(s,...e))}}}function Ti(r,i){window.postMessage({source:"fastrx-devtools-backend",payload:{event:r,payload:i}})}var rc=class extends U{constructor(i,e,t){super(i),this.source=e,this.id=t,this.sourceId=i.sourceId,this.defer(()=>{lt.defer(this.source,this.id)})}next(i){lt.next(this.source,this.id,i),this.sink.next(i)}complete(){lt.complete(this.source,this.id),this.sink.complete()}error(i){lt.complete(this.source,this.id,i),this.sink.error(i)}},lt={addSource(r,i){Ti("addSource",{id:r.id,name:r.toString(),source:{id:i.id,name:i.toString()}})},next(r,i,e){Ti("next",{id:r.id,streamId:i,data:e&&e.toString()})},subscribe({id:r,end:i},e){Ti("subscribe",{id:r,end:i,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(r,i,e){Ti("complete",{id:r.id,streamId:i,err:e?e.toString():null})},defer(r,i){Ti("defer",{id:r.id,streamId:i})},pipe(r){Ti("pipe",{name:r.toString(),id:r.id,source:{id:r.source.id,name:r.source.toString()}})},update(r){Ti("update",{id:r.id,name:r.toString()})},create(r){r.id||(r.id=hp++),Ti("create",{name:r.toString(),id:r.id})}},ao=class extends Error{constructor(i){super(`timeout after ${i}ms`),this.timeout=i}};var nc=class extends ws{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 co(){return r=>{let i=new nc(r);if(r instanceof zt){let e=Yt(t=>{i.add(t)},"share",arguments);return i.sourceId=e.id,e.source=r,lt.pipe(e),e}return Yt(i.add.bind(i),"share",arguments)}}function mp(...r){return Yt(i=>{let e=r.length,t=e,s=e,n=new Array(e),o=()=>{--s===0&&i.complete()},a=(c,d)=>{let l=new U(i);l.next=m=>{--t===0?(l.next=_=>{n[d]=_,i.next(n)},l.next(m)):n[d]=m},l.complete=o,l.subscribe(c)};r.forEach(a)},"combineLatest",arguments)}var oc=class extends U{constructor(i,...e){super(i);let t=new U(this.sink);t.next=s=>this.buffer=s,t.complete=fe,t.subscribe(mp(...e))}next(i){this.buffer&&this.sink.next([i,...this.buffer])}},hI=G(oc,"withLatestFrom"),ac=class extends U{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()}},mI=G(ac,"bufferCount"),cc=class extends U{constructor(i,e){super(i),this.buffer=[];let t=new U(i);t.next=s=>{i.next(this.buffer),this.buffer=[]},t.complete=fe,t.subscribe(e)}next(i){this.buffer.push(i)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},pI=G(cc,"buffer");function dc(r){let i=arguments,e=co()(Yt(t=>{e.next=s=>t.next(s),e.complete=()=>t.complete(),e.error=s=>t.error(s),r&&t.subscribe(r)},"subject",i));return e.next=fe,e.complete=fe,e.error=fe,e}function Gu(r){return Yt(i=>{let e=0,t=setInterval(()=>i.next(e++),r);return i.defer(()=>{clearInterval(t)}),"interval"},"interval",arguments)}var uc=class extends U{constructor(i,e,t){super(i),this.f=e;let s=()=>{this.sink.next(this.acc),this.sink.complete()};typeof t=="undefined"?this.next=n=>{this.acc=n,this.complete=s,this.resetNext()}:(this.acc=t,this.complete=s)}next(i){this.acc=this.f(this.acc,i)}},pp=G(uc,"reduce");var lc=class extends U{constructor(i,e,t){super(i),this.filter=e,this.thisArg=t}next(i){this.filter.call(this.thisArg,i)&&this.sink.next(i)}},_p=G(lc,"filter"),hc=class extends U{next(i){}},yI=G(hc,"ignoreElements"),mc=class extends U{constructor(i,e){super(i),this.count=e}next(i){this.sink.next(i),--this.count===0&&this.complete()}},fp=G(mc,"take"),pc=class extends U{constructor(i,e){super(i);let t=new U(i);t.next=()=>i.complete(),t.complete=sc,t.subscribe(e)}},NI=G(pc,"takeUntil"),_c=class extends U{constructor(i,e){super(i),this.f=e}next(i){this.f(i)?this.sink.next(i):this.complete()}},Ep=G(_c,"takeWhile");var fc=class extends U{constructor(i,e){super(i),this.count=e}next(i){--this.count===0&&(this.next=super.next)}},bI=G(fc,"skip"),Ec=class extends U{constructor(i,e){super(i),i.next=fe;let t=new U(i);t.next=()=>{t.dispose(),i.resetNext()},t.complete=sc,t.subscribe(e)}},vI=G(Ec,"skipUntil"),gc=class extends U{constructor(i,e){super(i),this.f=e}next(i){this.f(i)||(this.next=super.next,this.next(i))}},gp=G(gc,"skipWhile"),Tp={leading:!0,trailing:!1},Tc=class extends U{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)}},Sc=class extends U{constructor(i,e,t=Tp){super(i),this.durationSelector=e,this.config=t,this._throttle=new Tc(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=fe,this._throttle.complete(),super.complete()}},OI=G(Sc,"throttle");var Ic=class extends U{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},Ac=class extends U{constructor(i,e){super(i),this.durationSelector=e,this._debounce=new Ic(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()}},DI=G(Ac,"debounce");var Rc=class extends U{constructor(i,e,t){super(i),this.count=e,this.defaultValue=t}next(i){this.count--===0&&(this.defaultValue=i,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()}},MI=G(Rc,"elementAt");var Cc=class extends U{constructor(i,e){super(i),this.f=e,this.i=0}next(i){this.f(i)?(this.sink.next(this.i++),this.complete()):++this.i}},kI=G(Cc,"findIndex"),yc=class extends U{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.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},LI=G(yc,"first"),Nc=class extends U{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()}},xI=G(Nc,"last"),bc=class extends U{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.complete())}complete(){if(this.result===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.result);super.complete()}},PI=G(bc,"every");var vc=class extends U{constructor(i,e,t){super(i),this.f=e,typeof t=="undefined"?this.next=s=>{this.acc=s,this.resetNext(),this.sink.next(this.acc)}:this.acc=t}next(i){this.sink.next(this.acc=this.f(this.acc,i))}},BI=G(vc,"scan"),Oc=class extends U{constructor(){super(...arguments),this.hasLast=!1}next(i){this.hasLast?this.sink.next([this.last,i]):this.hasLast=!0,this.last=i}},$I=G(Oc,"pairwise"),Dc=class extends U{constructor(i,e,t){super(i),this.mapper=e,this.thisArg=t}next(i){super.next(this.mapper.call(this.thisArg,i))}},Wu=G(Dc,"map");var yr=class extends U{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()}},Nr=class extends U{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=this.tryComplete,t.complete=t.tryComplete,t.subscribe(this.makeSource(i,this.index++))}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},uo=class extends yr{},lo=class extends Nr{next(i){this.subInner(i,uo),this.next=e=>{this.currentSink.dispose(),this.subInner(e,uo)}}},Sp=G(lo,"switchMap");function _o(r){return(i,e)=>r(()=>i,e)}var HI=_o(G(lo,"switchMapTo")),Mc=class extends yr{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},ho=class extends Nr{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(),Mc),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},FI=G(ho,"concatMap"),GI=_o(G(ho,"concatMapTo")),kc=class extends yr{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},mo=class extends Nr{constructor(){super(...arguments),this.inners=new Set}next(i){this.subInner(i,kc),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(i=>i.resetComplete()):this.dispose()}},WI=G(mo,"mergeMap"),JI=_o(G(mo,"mergeMapTo")),Lc=class extends yr{dispose(){this.context.resetNext(),super.dispose()}},po=class extends Nr{next(i){this.next=fe,this.subInner(i,Lc)}},jI=G(po,"exhaustMap"),qI=_o(G(po,"exhaustMapTo")),xc=class extends U{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=dc(),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)}},KI=G(xc,"groupBy"),Pc=class extends U{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}},XI=G(Pc,"timeInterval"),wc=class extends U{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()}},QI=G(wc,"bufferTime"),Vc=class extends U{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:s}=e;super.next(s),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)}},zI=G(Vc,"delay"),Uc=class extends U{constructor(i,e){super(i),this.selector=e}error(i){this.dispose(),this.selector(i)(this.sink)}},YI=G(Uc,"catchError");var Bc=class extends U{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)}))}},iA=G(Bc,"tap"),$c=class extends U{constructor(i,e){super(i),this.timeout=e,this.id=setTimeout(()=>this.error(new ao(this.timeout)),this.timeout)}next(i){super.next(i),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},rA=G($c,"timeout");var SA=Fu(Gu(250),Wu(()=>performance.now()),co());var br=new Map;T.on(f.JOIN_SUCCESS,({room:r})=>{ge(r.userId,{eventId:32788,eventDesc:"join room"})});T.on(f.LEAVE_START,({room:r})=>{ge(r.userId,{eventId:32789,eventDesc:"leave room"})});T.on(f.LOCAL_TRACK_PUBLISHED,({track:r})=>{if(r.room){let i=32769;r.mediaType===4?i=32768:r.mediaType===2&&(i=32805),ge(r.room.userId,{eventId:i,eventDesc:`publish ${r.kind}`})}});T.on(f.LOCAL_TRACK_UNPUBLISHED,({track:r})=>{if(r.room){let i=32771;r.mediaType===4?i=32770:r.mediaType===2&&(i=32806),ge(r.room.userId,{eventId:i,eventDesc:`unpublish ${r.kind}`})}});T.on(f.TRACK_MUTED,({track:r})=>{r.room&&(r.kind===h.AUDIO?ge(r.room.userId,{eventId:r.isRemote?32785:32772,eventDesc:"mute audio",remoteUserId:r.isRemote?r.userId:void 0}):ge(r.room.userId,{eventId:r.isRemote?32784:32773,eventDesc:"mute video",remoteUserId:r.isRemote?r.userId:void 0}))});T.on(f.TRACK_UNMUTED,({track:r})=>{r.room&&(r.kind===h.AUDIO?ge(r.room.userId,{eventId:r.isRemote?32787:32774,eventDesc:"unmute audio",remoteUserId:r.isRemote?r.userId:void 0}):ge(r.room.userId,{eventId:r.isRemote?32786:32775,eventDesc:"unmute video",remoteUserId:r.isRemote?r.userId:void 0}))});T.on(f.REMOTE_TRACK_SUBSCRIBED,({track:r})=>{!r.room||(r.mediaType===1&&ge(r.room.userId,{eventId:32777,eventDesc:`${h.SUBSCRIBE} ${r.kind}`,remoteUserId:r.userId}),r.mediaType===4&&ge(r.room.userId,{eventId:32776,eventDesc:`${h.SUBSCRIBE} ${r.kind}`,remoteUserId:r.userId}),r.mediaType===8&&ge(r.room.userId,{eventId:32803,eventDesc:`${h.SUBSCRIBE} ${h.SMALL_VIDEO}`,remoteUserId:r.userId}))});T.on(f.REMOTE_TRACK_UNSUBSCRIBED,({track:r})=>{!r.room||(r.mediaType===1&&ge(r.room.userId,{eventId:32779,eventDesc:`${h.UNSUBSCRIBE} ${r.kind}`,remoteUserId:r.userId}),r.mediaType===4&&ge(r.room.userId,{eventId:32778,eventDesc:`${h.UNSUBSCRIBE} ${r.kind}`,remoteUserId:r.userId}),r.mediaType===8&&ge(r.room.userId,{eventId:32804,eventDesc:`${h.UNSUBSCRIBE} ${h.SMALL_VIDEO}`,remoteUserId:r.userId}))});T.on(f.SWITCH_DEVICE_SUCCESS,({track:r})=>{r.room&&ge(r.room.userId,{eventId:r.kind===h.VIDEO?32780:32781,eventDesc:`switch ${r.kind===h.VIDEO?"camera":"microphone"}`})});T.on(f.LOCAL_TRACK_REPLACED,({track:r})=>{r.room&&ge(r.room.userId,{eventId:r.kind===h.VIDEO?32782:32783,eventDesc:`replace ${r.kind}`})});T.on(f.SIGNAL_CONNECTION_STATE_CHANGED,({room:r,prevState:i,state:e})=>{let t,s;switch(e){case"CONNECTED":i==="RECONNECTING"?(t=32795,s="signal reconnected"):(t=32791,s="signal connected");break;case"DISCONNECTED":i==="RECONNECTING"?(t=32796,s="signal reconnect fail"):(t=32790,s="signal disconnected");break;case"RECONNECTING":t=32794,s="signal reconnecting";break}t&&s&&ge(r.userId,{eventId:t,eventDesc:s})});T.on(f.PEER_CONNECTION_STATE_CHANGED,({room:r,prevState:i,state:e,remoteUserId:t})=>{let s=!!t,n=s?"downlink":"uplink",o,a;switch(e){case"CONNECTED":i==="RECONNECTING"?(o=s?32801:32798,a=`${n} reconnected`):(o=s?32793:32792,a=`${n} connected`);break;case"DISCONNECTED":i==="RECONNECTING"&&(o=s?32802:32799,a=`${n} reconnect fail`);break;case"RECONNECTING":o=s?32800:32797,a=`${n} reconnecting`;break}o&&a&&ge(r.userId,{eventId:o,eventDesc:a,remoteUserId:t})});function ge(r,i){let e=L(N({},i),{timestamp:Fr()});br.has(r)?br.get(r).push(e):br.set(r,[e])}function Ju(r){if(br.has(r)){let i=br.get(r).map(e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,str_event_json:e.eventDesc}));return br.delete(r),i}return[]}var ju=Ae(ke(),1);var fo=class extends ju.EventEmitter{constructor(e,t,s="userId"){super();this.mySelfId=e;this._log=t;this.key=s;u(this,"userMap",new Map);u(this,"remotePublishedUserMap",new Map)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:s,tinyId:n,role:o}=e;if(this.userMap.has(t))return;let a={userId:s,tinyId:n,role:o===20?"anchor":"audience"};this.userMap.set(t,a),this.emit("1",a)}deleteUser(e,t){let s=this.userMap.get(e);if(!s)return;let n=`peer leave [${e}]`;E(t)||(n+=`:${na[t]}`),this._log.info(n);let o=this.remotePublishedUserMap.get(e);if(o){let a=o.muteState;o.flag=0,this.emit("5",o.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:a,muteState:o.muteState,flag:0})}this.userMap.delete(e),this.emit("2",s.userId)}setUserList(e){this.userMap.forEach(t=>{e.findIndex(s=>s[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 s=t[this.key];if(e.findIndex(n=>n[this.key]===t[this.key])<0){this._log.info(`remote [${s}] unpublish`);let n=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(s),this.emit("6",{prevMuteState:n,muteState:t.muteState,flag:0})}}),e.forEach(t=>{var l;let s=t[this.key];if(s===this.mySelfId)return;let{flag:n,userId:o,tinyId:a}=t,c=_i(n,o),d=(l=this.remotePublishedUserMap.get(s))==null?void 0:l.muteState;if(d){let m=this.remotePublishedUserMap.get(s);m&&m.flag!==n&&(m.flag=n,this._log.info(`remote publish updated: ${JSON.stringify(m.muteState)}`),this.emit("6",{prevMuteState:d,muteState:c,flag:n}))}else this._log.info(`remote publish. state: ${JSON.stringify(c)}`),this.addUser({userId:o,tinyId:a,role:20}),this.emit("3",t),this.emit("6",{prevMuteState:_i(0,o),muteState:c,flag:n})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function Hc({timesInSecond:r,maxSizeInSecond:i,getSize:e}){return F((t,s)=>{let n=new Map;return T.on(f.ROOM_DESTROY,({room:o})=>n.delete(o)),function(...o){let a=n.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},n.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(...o)),a.timestamp!==0&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=r||a.totalSizeInSecond>i))throw new C({code:I.INVALID_OPERATION,message:D({key:v.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=r,isSize:a.totalSizeInSecond>i,name:s,timesInSecond:r,maxSizeInSecond:i}})});a.callCountInSecond++,t.call(this,...o)}})}var qu=!0,Ku=function(){var r;qu&&(qu=!1,A.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${mt}/en/index.html`),console.info(`* Changelog: ${mt}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),A.info("TRTC Web SDK Version:",Se),A.info("UA:",navigator.userAgent),A.info(`URL: ${location.href}${((r=self.frameElement)==null?void 0:r.tagName)==="IFRAME"?" in iframe":""}`),cs().then(i=>{if(i){let e=`UAData: ${i.platform}/${i.platformVersion}`;i.architecture&&i.bitness&&(e+=` ${i.architecture}/${i.bitness}`),i.mobile&&(e+=" mobile"),i.model&&(e+=` model: ${i.model}`),i.fullVersionList&&(e+=` ${i.fullVersionList.filter(t=>t.brand!=="Not/A)Brand").map(t=>`${t.brand}/${t.version}`).join(",")}`),A.info(e)}}))};var Ze={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"};var k={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},Ot=(S=>(S[S.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",S[S.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",S[S.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",S[S.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",S[S.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",S[S.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",S[S.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",S[S.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",S[S.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",S[S.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",S[S.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",S[S.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",S[S.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",S[S.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",S[S.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",S[S.INVALID_ROOM_ID_REQUIED=5015]="INVALID_ROOM_ID_REQUIED",S[S.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",S[S.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",S[S.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",S[S.INVALID_OPERATION=5100]="INVALID_OPERATION",S[S.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",S[S.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",S[S.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",S[S.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",S[S.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",S[S.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",S[S.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",S[S.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",S[S.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",S[S.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",S[S.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",S[S.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",S[S.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",S[S.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",S[S.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",S[S.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",S[S.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",S[S.DEVICE_ERROR=5300]="DEVICE_ERROR",S[S.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",S[S.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",S[S.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",S[S.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",S[S.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",S[S.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",S[S.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",S[S.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",S[S.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",S[S.SERVER_ERROR=5400]="SERVER_ERROR",S[S.NEED_TO_BUY=5401]="NEED_TO_BUY",S[S.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",S[S.OPERATION_FAILED=5500]="OPERATION_FAILED",S[S.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",S[S.REJOIN_FAILED=5502]="REJOIN_FAILED",S[S.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",S[S.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",S[S.OPERATION_ABORT=5998]="OPERATION_ABORT",S[S.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",S))(Ot||{});function Qu({code:r,params:i,enableDocLink:e=!1}){let t="",s,n=Ot[r];try{s=Xu[n]}catch(o){s=Xu.UNKNOWN_ERROR}return X(s)?t=s(i):Q(s)&&(t=s),i.fnName&&!t.includes(i.fnName)&&(t[t.length-1]!=="."&&(t+="."),t+=` thrown from ${i.fnName}()`),e&&(t+=" doc:"),t}var Xu=L(N({},Ee),{INVALID_PARAMETER({fnName:r}){return`the parameters of the '${r}' you called does not meet the requirements, please check the API documentation.`},INVALID_PARAMETER_REQUIRED({key:r,rule:i,fnName:e,value:t}){return`'${r||i.name}' is a required param when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_TYPE({key:r,rule:i,fnName:e,value:t}){let s=`${r||i.name}`,n="";return Array.isArray(i.type)?n=i.type.join("|"):n=i.type,`'${s}' must be type of ${n} when calling ${e}(), received type: ${he(t)}.`},INVALID_PARAMETER_EMPTY({key:r,rule:i,fnName:e,value:t}){return`'${r||i.name}' cannot be '${t}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:r,rule:i,fnName:e,value:t}){let s=`${r||i.name}`,n=`${i.instanceOf.name||i.instanceOf}`;return`'${s}' must be instanceof ${n} when calling ${e}(), received type: ${he(t)}.`},INVALID_PARAMETER_RANGE({key:r,rule:i,fnName:e,value:t}){return`'${r||i.name}' must be one of ${i.values.join("|")} when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_LESS_THAN_ZERO({key:r,rule:i,fnName:e}){return`'${r||i.name}' cannot be less than 0 when calling ${e}().`},INVALID_PARAMETER_MIN({key:r,rule:i,value:e}){return`the min value of ${r||i.name} is ${i.min}, received: ${e}.`},INVALID_PARAMETER_MAX({key:r,rule:i,value:e}){return`the max value of ${r||i.name} is ${i.max}, received: ${e}.`},INVALID_ELEMENT_ID({key:r,fnName:i}){return`'${r}' is not found in the document object when calling ${i}().`},INVALID_ELEMENT_ID_TYPE({key:r,fnName:i,type:e}){return`the element corresponding to '${r}' must be instanceof HTMLElement when calling ${i}(), received: ${e}.`},INVALID_STREAM_ID({key:r}){return`'${r}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},INVALID_ROOM_ID_STRING({key:r}){return`'${r}' must be a valid string.`},INVALID_ROOM_ID_INTEGER({key:r}){return`'${r}' must be an integer between [1, 4294967294].`},INVALID_ROOM_ID_INTEGER_STRING({key:r}){return`'${r}' must be an integer but go a string, use 'parseInt' to convert it or use 'strRoomId' instead.`},INVALID_ROOM_ID_REQUIED(){return"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required."},INVALID_STREAM_TYPE:({fnName:r})=>`'streamType' is required when 'userId' is not '*', calling ${r}()`,INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION({fnName:r}){return`the API '${r}' you called does not meet the requirements, please check the API documentation.`},INVALID_OPERATION_NOT_JOINED({fnName:r}){return`cannot ${r} because you are not enter room yet.`},INVALID_OPERATION_REMOTE_USER_NOT_EXIST({fnName:r,value:i}){return`cannot ${r} because remote user(userId: ${i.userId}) does not publishing stream.`},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST({fnName:r,value:i}){return`cannot ${r} because remote user(userId: ${i.userId}) does not publishing ${i.streamType} video.`},INVALID_OPERATION_REPEAT_CALL({fnName:r}){return`you are already ${r}(), cannot repeated call '${r}'.`},INVALID_OPERATION_NEED_VIDEO({fnName:r}){return`cannot call '${r}' because the camera is not turned on.`},INVALID_OPERATION_NEED_AUDIO({fnName:r}){return`cannot call '${r}' because the microphone is not turned on.`},INVALID_BUFFER_EMPTY:({key:r})=>`the buffer size of paramerter '${r}' cannot be empty`,INVALID_BUFFER_OVERSIZE:()=>"buffer size is over 1000 Bytes",INVALID_ROLE_AUDIENCE:()=>`role: '${"audience"}' cannot call this api.`,ENV_NOT_SUPPORTED({fnName:r}){return`the current browser does not support the capability of the function '${r}' 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:r}){return`cannot call ${r} because the browser version is too low, please upgrade to the latest version`},DEVICE_ERROR({fnName:r,error:i}){return`'${r}' got device exception${i?`, error: ${i.toString()}.`:"."}`},DEVICE_NOT_FOUND_ERROR({fnName:r,deviceType:i=$i(r),error:e}){return`NotFoundError, no ${i} detected, please check your device and the configuration on '${r}'${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_ALLOWED_ERROR({fnName:r,deviceType:i=$i(r),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:r,deviceType:i=$i(r),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:r,deviceType:i=$i(r),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:r,deviceType:i=$i(r),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:r,deviceType:i=$i(r),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:r,deviceType:i=$i(r),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:r}){return`camera recover capture failed ${(r==null?void 0:r.name)||""}: ${(r==null?void 0:r.originMessage)||(r==null?void 0:r.message)}`},MICROPHONE_RECOVER_FAILED({error:r}){return`microphone recover capture failed ${(r==null?void 0:r.name)||""}: ${(r==null?void 0:r.originMessage)||(r==null?void 0:r.message)}`},OPERATION_FAILED({fnName:r,error:i}){return`'${r}' 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:r}){return`an error was caught on trtc.on('${r}', handler), please check your code on 'handler'.`},VIDEO_CONTEXT_ERROR({reason:r,error:i}){return`video context error ${r} ${(i==null?void 0:i.name)||""} ${(i==null?void 0:i.message)||""}`},SERVER_ERROR({fnName:r,error:i}){return`'${r}' got server error: ${i==null?void 0:i.toString()}, please check the SDK documentation.`},NEED_TO_BUY({value:r,url:i}){return`You need to buy packages for ${r}. Refer to: ${i}`},ACCOUNT_NO_MONEY:({fnParams:r})=>`your TRTC account run out of credit, please recharge.${r.sdkAppId?` SDKAppId: ${r.sdkAppId}`:""}`,OPERATION_ABORT({fnName:r}){return`'${r}' abort`},UNKNOWN_ERROR({fnName:r,error:i}){return`'${r}' throw unknown exception${i?`, error: ${i.toString()}.`:"."}`}});function $i(r){if(!r)return"camera";let i=r.toLowerCase();return i.includes("screen")?"screen share":i.includes("audio")?"microphone":"camera"}var Hi=class extends Error{constructor({code:e,extraCode:t,message:s="",messageParams:n,fnName:o="",originError:a}){var d;let c;s?c=s:c=Qu({code:t||e,params:N({fnName:o,error:a},n)});super(c);u(this,"name","RtcError");u(this,"code");u(this,"extraCode");u(this,"functionName");u(this,"message");u(this,"handler");u(this,"originError");this.name=Ot[e],this.code=e,this.extraCode=t,this.functionName=o,this.originError=a,this.message=c,this.extraCode===5302&&((d=this.originError)==null?void 0:d.message.includes("system"))&&(this.handler=()=>{let l={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},m={startLocalVideo:"webcam",startLocalAudio:"microphone"},_=document.createElement("a");di?_.href=`ms-settings:privacy-${m[this.functionName]}`:ft&&(_.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${l[this.functionName]}`),_.href.length>0&&_.click()})}static convertFrom(e,t,s){let n=e;if(e instanceof C){let{stack:o}=e,a={code:k.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case I.INVALID_PARAMETER:a.code=k.INVALID_PARAMETER,a.message=e.message;break;case I.INVALID_OPERATION:a.code=k.INVALID_OPERATION;break;case I.NOT_SUPPORTED:case I.NOT_SUPPORTED_H264:a.code=k.ENV_NOT_SUPPORTED,e.getCode()===I.NOT_SUPPORTED_H264&&(a.extraCode=e.message.includes(Ee.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case I.JOIN_ROOM_FAILED:a.messageParams={fnParams:s};case I.SERVER_TIMEOUT:case I.SWITCH_ROLE_FAILED:a.code=k.SERVER_ERROR,a.extraCode=e.getExtraCode();break;case I.API_CALL_ABORTED:a.code=k.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=Ip(e.name));break;case I.UNKNOWN:break;default:a.code=k.OPERATION_FAILED}n=new Hi(a),o&&(n.stack+=o.substr(o.indexOf(`
32
- `)))}else{if(e instanceof Hi)return e;n=new Hi({code:k.UNKNOWN_ERROR,fnName:t,originError:e})}return n}};function Ip(r){let i;switch(r){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 M=Hi;var zu={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:{properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack}}},Yu={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}}},vr={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(r,i,e){if(Q(r)&&!document.getElementById(r))throw new M({code:k.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:i}})}},Zu={name:"userId",required:!0,type:"string"},el={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[Ze.AUDIO_PROFILE_STANDARD,Ze.AUDIO_PROFILE_STANDARD_STEREO,Ze.AUDIO_PROFILE_HIGH,Ze.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function Vs(r,i){if(!r)throw new M({code:k.INVALID_OPERATION,extraCode:5101,fnName:i})}function tl(r,i,e){if(!r)throw new M({code:k.INVALID_OPERATION,extraCode:5102,fnName:i,messageParams:{value:e}})}var lC={type:"number",notLessThanZero:!0},Ap={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(r,i,e){if(this._room.isJoined)throw new M({code:k.INVALID_OPERATION,extraCode:5104,fnName:e});if(r.roomId){if(Q(r.roomId))throw new M({code:k.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:i}});if(!(/^[1-9]\d*$/.test(String(r.roomId))&&r.roomId<4294967295))throw new M({code:k.INVALID_PARAMETER,extraCode:5013,fnName:e,messageParams:{key:i}})}else if(r.strRoomId){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(r.strRoomId))throw new M({code:k.INVALID_PARAMETER,extraCode:5012,fnName:e,messageParams:{key:i}})}else throw new M({code:k.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"}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:vr,mute:{type:["boolean","string"]},publish:{type:"boolean"},option:zu},validate(r){var i;if(!((i=r==null?void 0:r.option)!=null&&i.videoTrack)&&Wt())throw new M({code:k.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:L(N({},vr),{required:!1}),publish:{type:"boolean"},mute:{type:["boolean","string"]},option:zu}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:el},validate(r){var i;if(!((i=r==null?void 0:r.option)!=null&&i.audioTrack)&&Wt())throw new M({code:k.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:el}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:vr,publish:{type:"boolean"},option:Yu},validate(r,i,e,t,s){var n;if(!((n=r==null?void 0:r.option)!=null&&n.videoTrack)&&Wt())throw new M({code:k.ENV_NOT_SUPPORTED,extraCode:5201});if(!Ss())throw new M({code:k.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:vr,publish:{type:"boolean"},option:Yu}},muteRemoteAudio:[Zu,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[Zu,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:vr,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(r,i,e){Vs(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(r.userId);if(tl(!!t,e,r),t&&(r.streamType==="main"&&!t.muteState.videoAvailable||r.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new M({code:k.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:r}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:L(N({},vr),{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(r,i,e){Vs(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(r.userId);if(tl(!!t,e,r),t&&(r.streamType==="main"&&!t.muteState.videoAvailable||r.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new M({code:k.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:r}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(r,i,e){if(r.userId!=="*"&&E(r.streamType))throw new M({code:k.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(r,i,e){Vs(this._room.isJoining||this._room.isJoined,e)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(r,i,e,t){if(!Ei)throw new M({code:k.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new M({code:k.INVALID_OPERATION,messageParams:{key:v.SEI_DISABLED}});if(r.byteLength>1e3)throw new M({code:k.INVALID_PARAMETER,extraCode:5018,fnName:e});if(r.byteLength===0)throw new M({code:k.INVALID_PARAMETER,extraCode:5017,messageParams:{key:i},fnName:e});if(Vs(this._room.isJoined,e),!this._room.isMainStreamPublished)throw new M({code:k.INVALID_PARAMETER,messageParams:{key:v.SEI_BEFORE_PUBLISH}})}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]}}}],sendCustomMessage:{name:"message",required:!0,type:"object",properties:{cmdId:{type:"number",required:!0,min:1,max:10},data:{instanceOf:ArrayBuffer,required:!0,validate(r,i,e,t){if(r.byteLength>1e3)throw new M({code:k.INVALID_PARAMETER,extraCode:5018,fnName:e});if(r.byteLength===0)throw new M({code:k.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:i}})}}},validate(r,i,e){if(Vs(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new M({code:k.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:i}})}}},Te={TRTC:Ap};var be=class extends Error{};function Rp(r,i){let e=pr(r);for(let t=0;t<i.length;t++)$t(e[t],i[t]);return e}function Cp(r){this._resolve=Promise.resolve(r)}function yp(r){this._reject=Promise.reject(r)}var Or=class{constructor(i,e){this.instance=i;this.group=e;u(this,"started",!1);u(this,"ops",[]);u(this,"startSame",()=>!0);u(this,"mergeUpdate",Rp);let t=Or.instances.get(i);t?t.set(e,this):Or.instances.set(i,new Map([[e,this]]))}static get(i,e){let t=Or.instances.get(i);return t&&t.get(e)||new Or(i,e)}action(i,e,t){let s=a=>{var c;return i===0?this.started=!0:i===3&&(this.started=!1),this.ops.shift(),(c=this.currentOp)==null||c.action(),a},n=a=>{var c,d;throw this.ops.shift(),i===0&&((c=this.currentOp)==null?void 0:c.type)===2&&this.ops.shift().reject(new be("start failed")),(d=this.currentOp)==null||d.action(),a},o={type:i,action:()=>e(...o.args).then(s,n),args:t,resolve:Cp,reject:yp};try{switch(this.state){case 1:if(i===0)throw new be("already started");break;case 4:if(i===2)throw new be("not started");break;default:return this.cacheOp(o)}}catch(a){return Promise.reject(a)}return this.ops.push(o),o.promise=e(...o.args).then(s,n)}cacheOp(i){if(this.ops.length===1)switch(this.state){case 0:case 2:if(i.type===0)throw new be("already start");break;case 3:switch(i.type){case 2:throw new be("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new be("unknown state")}else switch(i.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let t=new be("keep stop");if(this.ops.slice(1).forEach(s=>s.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 be("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new be("start not allowed after update");case 0:throw new be("duplicate start");case 3:if(this.startSame(this.currentOp.args,i.args))throw this.ops.pop().reject(new be("keep start")),new be("already start")}}i.promise=new Promise((t,s)=>{i._resolve?i._resolve.then(t):i.resolve=t,i._reject?i._reject.catch(s):i.reject=s});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}},Zt=Or;u(Zt,"instances",new WeakMap);var go=new WeakMap,To=(r,i)=>{if(i instanceof be){let{stack:e}=i;i=new M({code:k.OPERATION_ABORT,message:`${r} abort: ${i.message}`,fnName:r}),e&&(i.stack+=e.substr(e.indexOf(`
31
+ `,t.onclick=this.onQuestionClick.bind(this);let s=document.createElement("div");s.className=Fa,s.innerText=`${Et()?"\u8BE6\u60C5 >":"Detail >"}`,s.onclick=this.onCollapseClick.bind(this);let n=i.content.firstChild,o=n.querySelector(`.${Gn}`);return o.appendChild(s),o.appendChild(t),o.appendChild(e),n}addDiaLog(){Ja()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${Tr}`).onclick=i=>i.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",A.info("show autoplay dialog"),ee.uploadEvent({log:Um}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){A.warn("confirm clicked, try resume stream"),T.emit(f.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let i=this._dialogNode.querySelector(`.${Tu}`);i.style.visibility=`${this._showDetail?"hidden":"visible"}`,i.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||ee.uploadEvent({log:Bm}),this._isCollapseClicked=!0}onQuestionClick(){window.open(Ru,"_blank"),this._isQuestionClicked||ee.uploadEvent({log:$m}),this._isQuestionClicked=!0}},Cu=Ga;var ut=class extends qt{constructor(e){super(e,h.VIDEO);u(this,"viewMirror",!1);u(this,"objectFit");u(this,"container");u(this,"canvas");this.container=e.container,this.canvas=e.canvas,E(e.viewMirror)||(this.viewMirror=e.viewMirror),E(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}initializeElement(){var t;let e=document.createElement(h.VIDEO);this.track&&(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,(t=this.container)==null||t.appendChild(this.elementToRender),this.bindElementEvents()}get styleAttribute(){let e=`width: 100%; height: 100%; object-fit: ${this.objectFit};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(h.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(h.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent)}handleElementEvent(e){var s;super.handleElementEvent(e);let t=e.type;if(t===h.PAUSE&&(this.container&&document.getElementById(this.container.id)||this._log.warn(`${this.kind} player has been remove, element ID: ${(s=this.container)==null?void 0:s.id}`),this._pausedRetryCount>0&&!Ja()&&(this._log.info(`${this.kind} player auto resume when paused`),this.resume(),this._pausedRetryCount--)),this.viewMirror&&this.element){let n=this.element.style.transform;t===h.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=n.replace("scaleX(-1)",""):t===h.LEAVE_PICTURE_IN_PICTURE&&!n.includes("scaleX")&&(this.element.style.transform=`${n} scaleX(-1)`)}}setCanvas(e){var t,s;this.canvas!==e&&((t=this.canvas)==null||t.remove(),e==null||e.setAttribute("style",this.styleAttribute),this.canvas=e,e&&((s=this.container)==null||s.appendChild(e)))}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}stop(){var e;super.stop(),(e=this.canvas)==null||e.remove()}play(){return this.element?this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender):this.initializeElement(),super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(Pe.MEDIA_TRACK_CHANGED,e),e!==null&&(this.bindTrackEvents(),this.element&&(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}};function gi(r,i){return p(this,null,function*(){if(!r.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield r.audioWorklet.addModule(i),A.info("worklet addModule success")}catch(e){throw A.info(`worklet addModule catch error. ${e.message}`),e}})}typeof window!="undefined"&&(window.AudioContext=window.AudioContext||window.webkitAudioContext||window.mozAudioContext);var Pi=new window.AudioContext({sampleRate:48e3}),Jn=()=>{Pi.state==="suspended"?(Pi.resume(),document.addEventListener("click",Jn)):Pi.state==="interrupted"?Pi.resume():document.removeEventListener("click",Jn)};document.addEventListener("click",Jn);Pi.onstatechange=()=>{A.info(`context state: ${Pi.state}`),Jn()};var $e=r=>Pi;var Fm=1,Gm=0,jn=class{constructor(i=!0){this.countMap=new Map;this.distributionMap=new Map;this.log=A.createLogger({id:"kv"});i&&(T.on("102",({track:e,cost:t})=>{this.addSuccessEvent({key:e.kind===h.AUDIO?qn.START_MICROPHONE:ja.START_CAMERA,cost:t})}),T.on("103",({track:e,error:t})=>{this.addFailedEvent({key:e.kind===h.AUDIO?qn.START_MICROPHONE:ja.START_CAMERA,error:t})}))}getReportData(){let i={msg_sdk_basic_info:{uint32_sdk_version:va(this.version||Se),uint32_terminal_type:15,bytes_device_name:"",bytes_os_version:"",uint32_framework:30,uint32_network_type:0},stats_count:[...this.countMap.entries()].map(([e,t])=>({uint32_key:e,uint32_count:t})),stats_distribution:[...this.distributionMap.entries()].map(([e,t])=>({uint32_key:e,distribution_items:[...t.entries()].map(([s,n])=>({uint32_item_key:s,uint32_item_value:n}))}))};return this.countMap.clear(),this.distributionMap.clear(),i}clear(){this.countMap.clear(),this.distributionMap.clear()}isEnumKey(i){let e=+String(i).slice(-3);return e>=700&&e<799}isErrorCodeKey(i){let e=+String(i).slice(-3);return e>=600&&e<699}isCountKey(i){let e=+String(i).slice(-3);return e>=0&&e<599}isNumberKey(i){let e=+String(i).slice(-3);return e>=800&&e<899}addCount({key:i,useUV:e=!1}){if(!this.isCountKey(i)){this.log.debug(`${i} is not count key, last 3 number should be 0~599`);return}e&&this.countMap.has(i)||this.countMap.set(i,(this.countMap.get(i)||0)+1)}addEnum({key:i,value:e,useUV:t=!0}){var n;if(!this.isEnumKey(i))return this.log.debug(`${i} is not enum key, last 3 number should be 700~799`);if(t&&this.countMap.has(i))return;this.countMap.set(i,(this.countMap.get(i)||0)+1);let s=((n=this.distributionMap)==null?void 0:n.get(i))||new Map;s.set(e,(s.get(e)||0)+1),this.distributionMap.set(i,s)}addNumber({key:i,value:e,split:t=100,useUV:s=!1}){var a;if(!this.isNumberKey(i))return this.log.debug(`${i} is not number key, last 3 number should be 800~899`);if(s&&this.countMap.has(i))return;this.countMap.set(i,(this.countMap.get(i)||0)+1);let n=((a=this.distributionMap)==null?void 0:a.get(i))||new Map,o=0;if(re(t))o=Math.floor(e/t);else for(let c=t.length-1;c>0;c--)if(e>t[c]){o=c;break}n.set(o,(n.get(o)||0)+1),this.distributionMap.set(i,n)}addSuccessEvent({key:i,cost:e,timeKey:t,split:s}){if(!!i&&(this.addEnum({key:i,value:Fm,useUV:!1}),e)){let n=+String(i).slice(-3);n<800&&n>=700?this.addNumber({key:t||i+100,value:e,split:s}):t||this.log.debug(`time stat ignored, ${i}`)}}addFailedEvent({key:i,error:e}){if(!i)return;let t=I.UNKNOWN;re(e)?t=e:(!E(e.extraCode)||!E(e.code))&&(t=e.extraCode||e.code),this.addEnum({key:i,value:Gm,useUV:!1}),this.addEnum({key:i,value:t,useUV:!1})}},qa=(J=>(J[J.enterRoom=500700]="enterRoom",J[J.exitRoom=500701]="exitRoom",J[J.switchRole=500702]="switchRole",J[J.destroy=500703]="destroy",J[J.startLocalAudio=500704]="startLocalAudio",J[J.updateLocalAudio=500705]="updateLocalAudio",J[J.stopLocalAudio=500706]="stopLocalAudio",J[J.startLocalVideo=500707]="startLocalVideo",J[J.updateLocalVideo=500708]="updateLocalVideo",J[J.stopLocalVideo=500709]="stopLocalVideo",J[J.startScreenShare=500710]="startScreenShare",J[J.updateScreenShare=500711]="updateScreenShare",J[J.stopScreenShare=500712]="stopScreenShare",J[J.startRemoteVideo=500713]="startRemoteVideo",J[J.updateRemoteVideo=500714]="updateRemoteVideo",J[J.stopRemoteVideo=500715]="stopRemoteVideo",J[J.muteRemoteAudio=500716]="muteRemoteAudio",J[J.setRemoteAudioVolume=500717]="setRemoteAudioVolume",J))(qa||{}),Ka=(n=>(n[n.AudioMixer=550700]="AudioMixer",n[n.AIDenoiser=551700]="AIDenoiser",n[n.VirtualBackground=570700]="VirtualBackground",n[n.Beauty=571700]="Beauty",n[n.Watermark=572700]="Watermark",n))(Ka||{}),Xa=(n=>(n[n.AudioMixer=550701]="AudioMixer",n[n.AIDenoiser=551701]="AIDenoiser",n[n.VirtualBackground=570701]="VirtualBackground",n[n.Beauty=571701]="Beauty",n[n.Watermark=572701]="Watermark",n))(Xa||{}),Qa=(n=>(n[n.AudioMixer=550702]="AudioMixer",n[n.AIDenoiser=551702]="AIDenoiser",n[n.VirtualBackground=570702]="VirtualBackground",n[n.Beauty=571702]="Beauty",n[n.Watermark=572702]="Watermark",n))(Qa||{}),qn=(t=>(t[t.START_MICROPHONE=501700]="START_MICROPHONE",t[t.MICROPHONE_CAHNNELS=501701]="MICROPHONE_CAHNNELS",t[t.MICROPHONE_SAMPLERATE=501702]="MICROPHONE_SAMPLERATE",t))(qn||{});var ja=(i=>(i[i.START_CAMERA=511700]="START_CAMERA",i))(ja||{});var Wm=new jn(!0),wi=new jn(!1);var w=Wm;var Xt=class{constructor(){this.pre=new Set;this.next=new Set;this.connectedNodes=new Set}setContext(i){this.context=i,this.node&&i.addMixWeight()}removeContext(){var i;this.node&&((i=this.context)==null||i.reduceMixWeight()),delete this.context}setNode(i){var e;if(!this.node)try{(e=this.context)==null||e.addMixWeight(),this.node=i,this.preNodeReconnect(),this.reconnect(),w.addSuccessEvent({key:502701})}catch(t){A.error(t),w.addFailedEvent({key:502701,error:t})}}deleteNode(){var i;if(!!this.node)try{this._disconnect(),delete this.node,(i=this.context)==null||i.reduceMixWeight(),this.preNodeReconnect(),w.addSuccessEvent({key:502702})}catch(e){A.error(e),w.addFailedEvent({key:502702,error:e})}}preNodeReconnect(){this.pre.forEach(i=>{i.node?i.reconnect():i.preNodeReconnect()})}connectNext(i){this.next.forEach(e=>i._connect(e.node)||e.connectNext(i))}_connect(i){return!this.node||!i?!1:(this.node.connect(i),this.connectedNodes.add(i),!0)}_disconnect(){this.connectedNodes.forEach(i=>{var e;return(e=this.node)==null?void 0:e.disconnect(i)}),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(...i){return i.forEach(e=>{this.next.add(e),e.pre.add(this)}),this}},Kn=class extends Xt{constructor(e=256){super();this.fftSize=e;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,s=0,n=0,o=`M${s},${n}`;for(let a=0;a<e.length;a++)n=e[a]/128*100/2,o+=`L${s},${n}`,s+=t;return o}},Ds=class{constructor(){this.source=new Xt;this.gain=new Xt;this.destination=new Xt}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(this.source.node.context.createGain()),this.gain.node.gain.value=i}replaceSource(i){this.source.deleteNode(),this.source.setNode(Jm(i))}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}},Sr=class extends Ds{constructor(e){super();this.context=e;this.denoiser=new Xt;this.source.pipeTo(this.denoiser.pipeTo(this.gain.pipeTo(this.destination)))}connect(){this.context.inputs.has(this)||(this.destination.setNode(this.context.destination),this.source.setContext(this.context),this.denoiser.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.denoiser.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.denoiser.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}},Xn=class{constructor(){this.audioContext=$e("audio-mixer");this.destination=this.audioContext.createMediaStreamDestination();this.inputs=new Set;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]}},yu=new WeakMap;function Jm(r){let i=yu.get(r);if(i)return i;let e=$e();if(r instanceof HTMLAudioElement)i=e.createMediaElementSource(r);else if(r instanceof MediaStreamTrack)i=e.createMediaStreamSource(new MediaStream([r]));else return r;return yu.set(r,i),i}var jm='class VolumeMeter extends AudioWorkletProcessor{constructor(){super(),this.volume=0,this.intervalTime=200,this.tick=this.intervalTime,this.isStop=!1,this.port.onmessage=t=>{let{data:e}=t;switch(e.name){case"setIntervalTime":this.intervalTime=e.intervalTime;break;case"stop":this.isStop=!0}}}process(t){let e=t[0];if(this.isStop)return!1;if(e.length>0){let i=e[0],s=0;for(let l=0;l<i.length;++l)s=Math.max(Math.abs(i[l]),s);this.volume=s,this.tick-=i.length,this.tick<0&&(this.tick+=this.intervalTime/1e3*sampleRate,this.port.postMessage({volume:this.volume}))}return!0}}registerProcessor("volume-meter",VolumeMeter);',Vi=class{constructor(i){u(this,"_volume",0);u(this,"_log");u(this,"_scriptProcessorNode",null);u(this,"_audioWorkletNode",null);u(this,"_interval",200);u(this,"ready",this.preload());let{log:e}=i;this._log=e,T.on(f.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){return Vi.workletReady||(Vi.workletReady=gi(Vi.audioContext,URL.createObjectURL(new Blob([jm],{type:"application/javascript"})))),Vi.workletReady.then(()=>this.initAudioWorklet()).catch(()=>this.initScriptProcessor())}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(Vi.audioContext,"volume-meter"),this._audioWorkletNode.port.onmessage=i=>{this._volume=i.data.volume||0},this.handleAudioLevelInterval({interval:this._interval})}catch(i){ee.logFailedEvent({userId:this._log.userId,eventType:Le.LOAD_WORKLET,error:i}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=$e("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=i=>{let e=i.inputBuffer.getChannelData(0),t=0;for(let s=0;s<e.length;++s)t+=e[s]*e[s];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,T.off(f.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}handleAudioLevelInterval(i){var t;let{interval:e}=i;this._interval=e,(t=this._audioWorkletNode)==null||t.port.postMessage({name:"setIntervalTime",intervalTime:e})}},Ms=Vi;u(Ms,"audioContext",$e("volume-meter")),u(Ms,"workletReady");var Qn=class extends Xt{constructor(e){super();u(this,"_volumeMeter");this._volumeMeter=new Ms(e)}deleteNode(){this._volumeMeter.destroy(),super.deleteNode()}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()}};var Ou=Ae(ke(),1);var bu=r=>i=>i.deviceId===r;var ks=class{constructor(i,e="Input"){u(this,"kind");u(this,"type");u(this,"devices",[]);this.kind=i,this.type=e}update(i,e){let t=i.filter(s=>s.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);if(this.devices.length===1&&Ir(this.devices[0])){this.devices=t;return}e&&(t.forEach(s=>{if(s.deviceId&&!this.devices.find(bu(s.deviceId))){let n=`${this.kind}${this.type}Added`;A.warn(`${n}: ${JSON.stringify(s)}`),e.emit(n,s)}}),this.devices.forEach(s=>{if(s.deviceId&&!t.find(bu(s.deviceId))){let n=`${this.kind}${this.type}Removed`;A.warn(`${n}: ${JSON.stringify(s)}`),e.emit(n,s)}})),this.devices=t}hasDevice(i){return!!this.devices.find(e=>e.deviceId===i)}},za=class extends Ou.EventEmitter{constructor(){super();u(this,"audioInputs",new ks(h.AUDIO));u(this,"videoInputs",new ks(h.VIDEO));u(this,"audioOutputs",new ks(h.AUDIO,"Output"));this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||Z.run(Oi,()=>{this.update()},{delay:1e4}))}init(){zn().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 zn(e);return this.audioInputs.update(t,this),this.videoInputs.update(t,this),this.audioOutputs.update(t,this),this})}},_e=Wr||zi?null:new za;function Ir(r){return r.deviceId===r.groupId&&r.groupId===""}function zn(){return p(this,arguments,function*(r=0){if(Wt()||!Bn())return[];let i=yield navigator.mediaDevices.enumerateDevices();if(r!==0){let e={audio:!1,video:!1};if(i.forEach(t=>{Ir(t)&&(t.kind===h.AUDIO_INPUT?e.audio=!0:t.kind===h.VIDEO_INPUT&&(e.video=!0))}),r===2&&(e.audio=!1),r===1&&(e.video=!1),e.audio||e.video){let t;try{t=yield navigator.mediaDevices.getUserMedia(e)}catch(s){A.debug("capture before getDevices failed: ",s)}i=yield navigator.mediaDevices.enumerateDevices(),t==null||t.getTracks().forEach(s=>s.stop())}}return i.map((e,t)=>{let s={kind:e.kind,deviceId:e.deviceId,groupId:e.groupId,label:e.label||`${e.kind}_${t}`};return e.deviceId.length>0&&Ya.add(`${e.deviceId}_${e.kind}`),e.getCapabilities&&(s.getCapabilities=()=>e.getCapabilities()),s})})}function Ve(r=!1){return _e.update(r?1:0).then(i=>i.audioInputs.devices)}function He(r=!1){return _e.update(r?2:0).then(i=>i.videoInputs.devices)}var vu=!1;function Du(){return p(this,null,function*(){try{vu||(vu=!0,A.info(`speakers:${(yield Ui()).map(r=>` ${r.deviceId.slice(0,8)}: ${r.label}`)}`))}catch(r){}})}function Ui(r=!1){return p(this,null,function*(){return _e.update(r?1:0).then(i=>i.audioOutputs.devices)})}var Ya=new Set;function Mu(r){if(r instanceof CanvasCaptureMediaStreamTrack||!(r instanceof MediaStreamTrack))return!1;let i=r.label.toLocaleLowerCase();if(i.includes("camera")||i.includes("webcam"))return!0;let t=`${((r==null?void 0:r.getSettings())||{}).deviceId}_${h.VIDEO_INPUT}`;return!!Ya.has(t)}function ku(r){if(r instanceof CanvasCaptureMediaStreamTrack||!(r instanceof MediaStreamTrack))return!1;let i=r.label.toLocaleLowerCase();if(i.includes("mic")||i.includes("\u9EA6\u514B\u98CE"))return!0;let t=`${((r==null?void 0:r.getSettings())||{}).deviceId}_${h.AUDIO_INPUT}`;return!!Ya.has(t)}function Za(r,i){return p(this,null,function*(){let t=(yield Ve()).find(s=>s.deviceId===vi);return(t==null?void 0:t.groupId)===r&&t.label===i})}function Lu(n){return p(this,arguments,function*({newDeviceId:r,oldDeviceId:i,oldGroupId:e,oldLabel:t,kind:s}){return r!==i?!1:s===h.AUDIO&&r===vi?yield Za(e,t):!0})}var ec=class extends Ds{constructor(e){super();this.log=e;u(this,"volumeMeter");u(this,"analyser",new Kn);this.volumeMeter=new Qn({log:this.log})}destory(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode()}},Ar=class extends qt{constructor(e){super(e,h.AUDIO);u(this,"_outputDeviceId");u(this,"_volume",1);u(this,"_destination",$e("player").createMediaStreamDestination());u(this,"pipeline");u(this,"volumeMeterMode","worklet");this.pipeline=new ec(this._log)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(){if((li==="15.2"||li==="15.3"||li==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}let t=new Audio;t.setAttribute("autoplay","autoplay"),t.srcObject=this.getMediaStream(),t.muted=this.muted,this.element=t,this.bindElementEvents()}play(){return p(this,null,function*(){if(!!this.track)return this.pipeline.source.node||this.pipeline.replaceSource(this.track),this.element||this.initializeElement(),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),this.volumeMeterMode==="worklet"?this.pipeline.volumeMeter.init():this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode($e("player").createAnalyser()),this.setVolume(this._volume),Du(),Re(Ar.prototype,this,"play").call(this)})}stop(){this.pipeline.destory(),super.stop()}setSinkId(e){return p(this,null,function*(){var t,s;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield(s=(t=this.element).setSinkId)==null?void 0:s.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()}},Yn=class extends Ar{constructor(i){super(i),this.pipeline.source.pipeTo(this.pipeline.volumeMeter,this.pipeline.destination)}setTrack(i){this.track!==i&&(this.unbindTrackEvents(),this.track=i,this.emit(Pe.MEDIA_TRACK_CHANGED,i),i?(this.bindTrackEvents(),this.pipeline.replaceSource(i),!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([i]))):this.pipeline.source.deleteNode())}setSourceNode(i){!i||this.pipeline.source.node===i||(this.pipeline.replaceSource(i),i instanceof MediaStreamAudioSourceNode?this.pipeline.destination.setNode(this._destination):this.pipeline.destination.deleteNode(),this.element&&(this.element.srcObject=this.getMediaStream(),this.element.play().catch(()=>{}),this.setVolume(this._volume)))}setVolume(i){this._volume=i,this.element&&(this.element.volume=i)}},Zn=class extends Ar{constructor(e){super(e);u(this,"_sourceElement");this.pipeline.source.pipeTo(this.pipeline.gain.pipeTo(this.pipeline.volumeMeter,this.pipeline.destination))}setTrack(e){this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(Pe.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.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){this._volume=e,this.useDestination?(this.pipeline.setVolume(e),this._log.info(`set pipeline volume: ${e}`)):e<=1?(this.element?this._log.info(`set element volume: ${e}`):this._log.info("set element volume: no element"),this.element&&(this.element.volume=e)):(this._log.info(`start set pipeline volume: ${e}`),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),pe(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play()))}stop(){this.pipeline.destory(),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop()}};var Bi=class extends V{constructor({userId:e,sdkAppId:t,mediaType:s,room:n,PlayerClass:o=s===1?Zn:ut}){var a;super();u(this,"id",gs());u(this,"userId","");u(this,"isRemote");u(this,"mediaType");u(this,"room");u(this,"user");u(this,"_log");u(this,"_inputTrack");u(this,"_outputTrack");u(this,"isPlayCalled");u(this,"container",null);u(this,"player");u(this,"subVideoPlayerMap");u(this,"muted",!1);u(this,"abortCtrl");u(this,"objectFit","cover");u(this,"mirror");u(this,"isScreen",!1);u(this,"manager");u(this,"trackSettings");this.userId=e||"",this.mediaType=s,this._log=A.createLogger({id:`${this.kind[0]}t`,userId:(a=n||this.room)==null?void 0:a.userId,remoteUserId:this instanceof Fe?void 0:this.userId,sdkAppId:t,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof Fe}),this.player=new o({id:this.userId||this.id,track:null,muted:!1,container:null,log:this.log}),this.player.on(Pe.PLAYER_STATE_CHANGED,c=>{T.emit(f.PLAYER_STATE_CHANGED,N({track:this},c)),this.emit("player-state-changed",c)}),this.kind===h.VIDEO&&(this.player.on(Pe.LOADED_DATA,()=>{T.emit(f.VIDEO_LOADED_DATA,{track:this})}),this.player.on(Pe.MEDIA_TRACK_CHANGED,c=>{var d;(d=this.subVideoPlayerMap)==null||d.forEach(l=>l.setTrack(c))}))}get log(){return this._log||A}get kind(){return this.mediaType===1?h.AUDIO:h.VIDEO}get strMediaType(){return this.mediaType===4?h.VIDEO:this.mediaType===2?h.SCREEN:h.AUDIO}get streamType(){return(this.mediaType&2)===0?"main":"auxiliary"}play(e,t){return p(this,null,function*(){let s=de(e)?e[0]:e;if(this.isPlayCalled){this.log.info(`play update options: ${JSON.stringify(t)}`),t&&!E(t.muted)&&this.setPlayerMute(t.muted),t&&!E(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof ut&&(this.player.setObjectFit(this.objectFit),this.container!==s&&s&&(this.container=s,this.player.setContainer(s)),de(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t)));return}if(t&&!E(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===h.VIDEO)&&this.setPlayerMute(!0),t&&!E(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof ut&&this.player.setObjectFit(this.objectFit),this.isPlayCalled=!0,s&&(this.container=s,this.player instanceof ut&&this.player.setContainer(s)),T.emit(f.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(),de(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(n){throw this.handleAutoPlayFailed(),this.emit("error",n),n}})}setMirror(e,t){if(this.isScreen||this.kind!==h.VIDEO||E(e)||e===this.mirror)return;this.mirror=e;let s=this.player;t&&(s=t);let n=this.manager;if(ue(this.mirror)){s.setViewMirror(this.mirror),n&&(n.mirror=!1);return}switch(this.mirror){case"view":{n&&(n.mirror=!1),s.setViewMirror(!0);break}case"publish":{n&&(n.mirror=!0),s.setViewMirror(!0);break}case"both":n&&(n.mirror=!0),s.setViewMirror(!1)}}playSubContainer(e,t){return p(this,null,function*(){if(!this._outputTrack||this.kind===h.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((n,o)=>{var a;e.find(c=>o===c)||(n.stop(),(a=this.subVideoPlayerMap)==null||a.delete(o))});for(let[n,o]of e.entries()){let a=this.subVideoPlayerMap.get(o);a?t&&(E(t.objectFit)||a.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(o,new ut({id:this.userId||this.id,track:this.playerMediaTrack,container:o,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:`vp-sub${n+1}`})}))}let s=[...this.subVideoPlayerMap.values()];for(let n of s)n.setViewMirror(this.player.mirror),yield n.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(){!this.isPlayCalled||(this.isPlayCalled=!1,this.player&&(this.log.info(`stop ${this.kind} player`),this.player.stop()),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(e=>{e.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()}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),T.emit(e?f.TRACK_MUTED:f.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}setInputMediaStreamTrack(e){var s;let t=this._inputTrack;if(e!==t)return this._inputTrack=e,this.trackSettings=(s=e.getSettings)==null?void 0:s.call(e),e.enabled=!this.muted,this.emit("input-media-track-changed",e||null,t||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var s;let t=this._outputTrack;e!==t&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",(s=e.getSettings)==null?void 0:s.call(e).deviceId,e.label),this._outputTrack=e,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(()=>this.handleAutoPlayFailed()),this.log.info(`playing state updated, play ${this.kind}`);return}}else if(!this.player.isStopped){this.player.stop(),this.log.info(`playing state updated, stop ${this.kind}`);return}}this.log.debug(`updatePlayingState abort ${this.isPlayCalled} ${e} ${this.player.isStopped}`)}handleAutoPlayFailed(){if(this.room&&this.room.enableAutoPlayDialog)new Cu;else{let e=()=>{this.resume().then(()=>{document.removeEventListener("click",e,!0)})};document.addEventListener("click",e,!0)}}getVideoFrame(){return this.player instanceof ut?this.player.getVideoFrame():""}};b([oe([],V.INIT,{sync:!0})],Bi.prototype,"close",1);var qm=Object.prototype.hasOwnProperty,{toString:$g}=Object.prototype;function Km(r){if(r==null)return!0;if(typeof r=="boolean")return!1;if(typeof r=="number")return r===0;if(typeof r=="string"||typeof r=="function"||Array.isArray(r))return r.length===0;if(r instanceof Error)return r.message==="";if(Be(r))switch(Object.prototype.toString.call(r)){case"[object File]":case"[object Map]":case"[object Set]":return r.size===0;case"[object Object]":{for(let i in r)if(qm.call(r,i))return!1;return!0}}return!1}var yt=Km;var Xm=function(r){return p(this,null,function*(){let i=zm(r);A.info(`getUserMedia with constraints: ${JSON.stringify(i)}`);let e=[],t=[],s=["label","deviceId"];i.audio&&(e=yield Ve(),A.info(`microphones: ${dt(e,{keysToInclude:s})}`)),i.video&&(t=yield He(),A.info(`cameras: ${dt(t,{keysToInclude:s})}`));try{let n=yield navigator.mediaDevices.getUserMedia(i);return Va&&n.getTracks().forEach(o=>{A.info(`${o.kind} capabilities: ${dt(o.getCapabilities(),{keysToInclude:fn})}`)}),n}catch(n){let{message:o}=n;throw n.name==="NotFoundError"&&(r.video&&t&&t.length===0&&(o=D({key:v.CAMERA_NOT_FOUND})),r.audio&&e&&e.length===0&&(o=D({key:v.MICROPHONE_NOT_FOUND}))),new C({code:I.INITIALIZE_FAILED,name:n.name,message:o,constraint:n.constraint})}})},Qm=gt({retryFunction:Xm,settings:{retries:3,timeout:500},onError:({error:r,retry:i,reject:e,retryFuncArgs:t,retriedCount:s})=>{let n=s+1;r.name==="NotReadableError"||r.name==="OverconstrainedError"?(n===1?t[0].video&&(t[0].maxResolution=!1,t[0].frameRate&&(t[0].frameRate=t[0].frameRate>10?10:5)):n===2?t[0].useDeviceIdOnly=!0:n===3&&!t[0].useExactDeviceId&&(t[0].useTrueAsConstraint=!0),i()):e(r),t[0].microphoneId&&xu(t[0].microphoneId,!1),t[0].cameraId&&xu(t[0].cameraId,!0)},onRetrying:r=>{A.warn(`getUserMedia NotReadableError observed, retrying [${r}/3]`)},onRetryFailed:r=>{ee.logFailedEvent({eventType:Le.GET_USER_MEDIA_RETRY,error:r})},onRetrySuccess:r=>{ee.logSuccessEvent({eventType:Le.GET_USER_MEDIA_RETRY}),ee.uploadEvent({log:`stat-${Le.GET_USER_MEDIA_RETRY}-success-${r}`})}});function xu(r,i){return p(this,null,function*(){let t=(i?yield He():yield Ve()).find(s=>s.deviceId===r);t&&X(t.getCapabilities)&&A.warn(dt(t.getCapabilities(),{keysToInclude:fn}))})}function zm(r){return{audio:Ym(r),video:Zm(r)}}function Ym(r){if(!r.audio)return!1;if(r.useTrueAsConstraint)return!0;let i={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:r.sampleRate};return!yt(r.microphoneId)&&(i.deviceId=r.useExactDeviceId?{exact:r.microphoneId}:r.microphoneId,r.useDeviceIdOnly)?i:(re(r.channelCount)&&(i.channelCount=r.channelCount),ue(r.echoCancellation)&&!r.echoCancellation&&(i.echoCancellation=!1),ue(r.noiseSuppression)&&!r.noiseSuppression&&(i.noiseSuppression=!1),ue(r.autoGainControl)&&!r.autoGainControl&&(i.autoGainControl=!1),yt(i)?!0:i)}function Zm(r){if(!r.video)return!1;if(r.useTrueAsConstraint)return!0;let{maxResolution:i=!0}=r,e={};return r.cameraId?e.deviceId=r.useExactDeviceId?{exact:r.cameraId}:r.cameraId:r.facingMode&&(e.facingMode=r.facingMode),r.useDeviceIdOnly&&!yt(e)?e:(r.width&&(e.width={ideal:r.width},i&&!Y&&(e.width.max=r.width)),r.height&&(e.height={ideal:r.height},i&&!Y&&(e.height.max=r.height)),Y&&ft&&r.width&&r.height&&r.width*r.height<352*288&&(e.width=r.width,e.height=r.height),r.frameRate&&(e.frameRate=r.frameRate),yt(e)?!0:e)}var Pu=Qm;function eo(r){return F((i,e)=>function(...t){return p(this,null,function*(){return yield r.apply(this,t),i.apply(this,t)})})}function to(r){return F((i,e)=>function(...t){return p(this,null,function*(){return r.call(this,i.apply(this,t))})})}function F(r){return function(i,e,t){return t.value=r(t.value,e),t}}var wu=(()=>{let r=!1,i=document.visibilityState;return()=>{document.visibilityState!==i&&A.info(`visibility change: ${document.visibilityState}`),!r&&(document.addEventListener("visibilitychange",()=>{A.info(`visibility change: ${document.visibilityState}`),i=document.visibilityState}),r=!0)}})();var ep=0,io=class{constructor(){this.log=A.createLogger({id:`fq${++ep}`});this.isRunning=!1;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 n,o;let t=N({},i),s=new Promise((a,c)=>{t.resolve=a,t.reject=c});return t.promise=s,e?this.length<=1?this.queue.push(t):(o=(n=this.lastQueueItem)==null?void 0:n.promise)==null||o.then(t.resolve,t.reject):this.queue.push(t),this.log.debug(`push ${this.length}`),this.isRunning||this.callNext(),s}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:s,reject:n}=this.queue[0];this.isRunning=!0,i.apply(t,e).then(s,n).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},xs=new WeakMap,ro=new WeakMap;function Nt(r=!1){return function(i,e,t){let s=t.value;return t.value=function(...n){let o=xs.get(this)||new io;return xs.set(this,o),o.push({fn:s,args:n,context:this},r)},t}}function Vu(r){return function(i,e,t){let s=t.value;return t.value=function(...n){let o=xs.get(this);if(o){let a=o.queue.filter((c,d)=>{if(d===0)return!0;let l=!0;return c.args.forEach(m=>{n.find(_=>_===m)||(l=!1)}),l?(c.reject(new C({code:I.API_CALL_ABORTED,message:r})),!1):!0});o.queue=a}return s.apply(this,n)},t}}function so(r){return function(i,e,t){let s=t.value;return t.value=function(...n){var a,c,d;let o=[];return(c=(a=xs.get(this))==null?void 0:a.queue)==null||c.forEach(l=>o.push(l)),(d=ro.get(this))==null||d.forEach(l=>l==null?void 0:l.queue.forEach(m=>o.push(m))),o.forEach(l=>{l.reject(new C({code:I.API_CALL_ABORTED,message:r}))}),xs.delete(this),ro.delete(this),s.apply(this,n)},t}}function Rr(r){return function(i,e,t){let s=t.value,n=o=>r(...o);return t.value=function(...o){let a=ro.get(this)||new Map,c=a.get(n(o))||new io;return a.set(n(o),c),ro.set(this,a),c.push({fn:s,args:o,context:this})},t}}var Fe=class extends Bi{constructor(e,t){super({mediaType:e,PlayerClass:t});u(this,"isRemote",!1);u(this,"deviceId");u(this,"groupId","");u(this,"label","");u(this,"_isRecapturing",!1);u(this,"_lastRecaptureTime",0);u(this,"_onMuteTimeoutId",-1);u(this,"profile");this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this)}get isPublished(){return this.state==="publish"}installTrackEvent(e){we(e,e).add(h.MUTE,this.onTrackMuted).add(h.UNMUTE,this.onTrackUnmuted).add(h.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===h.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){pe(e)}setStateToCapture(){}capture(e){return p(this,null,function*(){var t;try{let s=B();T.emit(f.LOCAL_TRACK_CAPTURE_START,{track:this});let n;e.customSource?(n=new MediaStream,n.addTrack(e.customSource)):((t=this.mediaTrack)==null||t.stop(),n=yield Pu(e));let o=n.getTracks()[0];return yield this.setInputMediaStreamTrack(o),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),T.emit(f.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:B()-s}),n}catch(s){throw T.emit(f.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:s}),this.log.error(`getUserMedia error observed ${s}`),s}})}setInputMediaStreamTrack(e){this.state===V.INIT&&this.setStateToCapture(),this._inputTrack&&this.uninstallTrackEvent(this._inputTrack);let t=super.setInputMediaStreamTrack(e);return this.installTrackEvent(e),t}setOutputMediaStreamTrack(e){var t;return super.setOutputMediaStreamTrack(e),(t=this.room)==null?void 0:t.replaceTrack(this)}publish(e,t){return this.room=e,this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),t}unpublish(){this.room&&this.room.localTracks.delete(this),T.emit(f.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return p(this,null,function*(){if(this.mediaTrack&&Rt){let{deviceId:e,groupId:t}=this.mediaTrack.getSettings(),{label:s}=this.mediaTrack;(yield Lu({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=s,t&&(this.groupId=t),zn().then(o=>{let a=o.find(c=>c.deviceId===e);a&&this.emit("2",a)}))}})}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(e=!1){return!(!this.deviceId||!this.mediaTrack||this.kind===h.AUDIO&&!ku(this.mediaTrack)||this.kind===h.VIDEO&&!Mu(this.mediaTrack)||this._isRecapturing||e&&ft&&Xe)}onTrackMuted(){if(wu(),!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<er){setTimeout(()=>this.onTrackMuted(),er);return}this._onMuteTimeoutId=setTimeout(()=>p(this,null,function*(){var e;if((e=this.mediaTrack)!=null&&e.muted){if((Ue||ye)&&document.visibilityState!=="visible")return;this.recapture(yield this.getRecoverCaptureDeviceId())}}),5e3)}}onTrackUnmuted(){this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return p(this,null,function*(){if(!!this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<er){setTimeout(()=>this.onTrackEnded(),er);return}this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e){return p(this,null,function*(){var s;if(this._isRecapturing||!this._inputTrack)return;this.log.warn("recapture trying"),(s=this._inputTrack)==null||s.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let t={useExactDeviceId:!0};if(e==="user"||e==="environment")t.facingMode=e;else{let n;(this.kind==="audio"?yield Ve():yield He()).find(a=>a.deviceId===e)&&(n=e),t.deviceId=n}return this.capture(t).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId})}).catch(n=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${n.message}`),this.emit("5",n)})})}getRecoverCaptureDeviceId(){return p(this,null,function*(){let e=this instanceof ae;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let s=(Ps.get(t)||0)+1;if(Ps.set(t,s),s>=3){let n=e?(yield He()).find(o=>!Ps.has(o.deviceId)):(yield Ve()).find(o=>!Ps.has(o.deviceId));n&&(this.log.warn(`${t} capture fail ${s} times, change new ${n.deviceId}`),t=n.deviceId)}}return t})}close(){var e;super.close(),this._inputTrack&&(this._inputTrack.stop(),this.uninstallTrackEvent(this._inputTrack)),(e=this.manager)==null||e.removeInput(this)}};b([oe(V.INIT,"capture",{ignoreError:!0,sync:!0})],Fe.prototype,"setStateToCapture",1),b([Nt()],Fe.prototype,"capture",1),b([oe("capture","publish",{ignoreError:!0,success(){this.room.localTracks.add(this),T.emit(f.LOCAL_TRACK_PUBLISHED,{track:this}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"})},fail(r){let i="error",e=r.cause;e.message.includes("timeout")?i="timeout":e.code===I.API_CALL_ABORTED&&(i="api-call"),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:i,error:e})}})],Fe.prototype,"publish",1),b([F(r=>function(){return p(this,null,function*(){let i=this.state==="publish"?"started":"starting";r.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:i,reason:"api-call"})})}),oe([],"capture",{sync:!0})],Fe.prototype,"unpublish",1);var Ps=new Map;T.on(f.SWITCH_DEVICE_SUCCESS,r=>{r.track.deviceId&&Ps.delete(r.track.deviceId)});var Ne=class extends Fe{constructor(e){super(1,Yn);u(this,"mediaType",1);u(this,"volume",0);u(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40});u(this,"playerMuted",!0);u(this,"pipeline");this.manager=e,this.pipeline=new Sr(e),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this)}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}get playerMediaTrack(){return this.mediaTrack}setInputMediaStreamTrack(e){return p(this,null,function*(){yield Re(Ne.prototype,this,"setInputMediaStreamTrack").call(this,e);let t=this.trackSettings||{};w.addEnum({key:501701,value:t.channelCount||0,useUV:!1}),w.addEnum({key:501702,value:t.sampleRate||0,useUV:!1}),w.addEnum({key:502700,value:0});let{sampleRate:s,channelCount:n}=t;this._log.info(`local audio track input ${JSON.stringify({sampleRate:s,channelCount:n})}`),this.pipeline.replaceSource(e),this.updatePlayingState(!!e)})}capture({deviceId:e,customSource:t,useExactDeviceId:s=!1}){return super.capture({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:s,customSource:t})}switchDevice(e){return p(this,null,function*(){if(!!this.mediaTrack){if(this.deviceId===e)if(e===vi){if(yield Za(this.groupId,this.label))return}else return;try{this.log.info(`switchDevice audio to: ${e}`),this.mediaTrack&&this.mediaTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0}),this.room&&(yield this.room.replaceTrack(this)),T.emit(f.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(){_e&&!_e.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&_e.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return p(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current microphone is lost: ${JSON.stringify(e)}`);let t=yield Ve();t[0]?this.recapture(t[0].deviceId):_e.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.log.warn(`microphone added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)}update3A(n){return p(this,arguments,function*({echoCancellation:e,noiseSuppression:t,autoGainControl:s}){let o=!1;!E(e)&&e!==this.profile.echoCancellation&&(this.profile.echoCancellation=e,o=!0),!E(t)&&t!==this.profile.noiseSuppression&&(this.profile.noiseSuppression=t,o=!0),!E(s)&&s!==this.profile.autoGainControl&&(this.profile.autoGainControl=s,o=!0),o&&this.deviceId&&(yield this.recapture(this.deviceId))})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&w.addEnum({key:502700,value:2}),this.resetPlayerSource()}enableTrackANS(e){if(!this._inputTrack)return;let t=this._inputTrack.getConstraints();return t.noiseSuppression=e,this._inputTrack.applyConstraints(t).catch(s=>this._log.warn(`${e?"enable":"disable"} ANS failed `,s))}addDenoiser(e){var t;if(Ut<=92&&((t=this.trackSettings)==null?void 0:t.sampleRate)!==48e3){this._log.warn("denoiser only support sampleRate 48000 before chrome 93");return}w.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.resetPlayerSource(),this.enableTrackANS(!1)}removeDenoiser(e){this.pipeline.denoiser.node===e&&(this.pipeline.denoiser.deleteNode(),this.resetPlayerSource(),this.enableTrackANS(!0))}resetPlayerSource(){this.player.setSourceNode(this.pipeline.gain.node||this.pipeline.denoiser.node||this.pipeline.source.node)}close(){this.pipeline.remove(),_e.off("audioInputAdded",this.handleMicrophoneAdded,this),_e.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}recapture(e){return p(this,null,function*(){try{yield Re(Ne.prototype,this,"recapture").call(this,e)}catch(t){let s=(yield Ve()).find(n=>n.deviceId!==e);if(s)yield Re(Ne.prototype,this,"recapture").call(this,s.deviceId);else throw t}})}};var ae=class extends Fe{constructor(e,t=4){super(t,ut);u(this,"profile",{width:640,height:480,frameRate:15,bitrate:500});u(this,"states",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0});u(this,"small");u(this,"isNeedToSetBandwidth");u(this,"muteImage");u(this,"manager");this.manager=e;let s=()=>{this.isAllowed2k4k(this.profile)?this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1}):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),this.setProfile(L(N({},this.profile),{width:1920,height:1080})),this.applyProfile())};this.on("input-media-track-changed",s),this.on("publish",s),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(!(!Rt||!this.mediaTrack))return this.mediaTrack.getSettings().facingMode}setMute(e){return p(this,null,function*(){var t,s,n;if(Q(e)){if(this.muteImage===e)return;yield(t=this.manager)==null?void 0:t.deleteWatermark("mute"),yield(s=this.manager)==null?void 0:s.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:e}),this.muteImage=e,Re(ae.prototype,this,"setMute").call(this,!1)}else yield(n=this.manager)==null?void 0:n.deleteWatermark("mute"),this.muteImage=void 0,Re(ae.prototype,this,"setMute").call(this,e)})}capture({deviceId:e,facingMode:t,useExactDeviceId:s=!1,customSource:n}){return super.capture({audio:!1,video:!0,facingMode:t||this.facingMode,cameraId:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:s,customSource:n})}setProfile(e){let t=N({},e),s=t.width>t.height;t.width*t.height<=160*120&&ye&&Mi&&(this.log.warn(`resolution is ${t.width}*${t.height}, fallback to 240*180`),t.width=s?240:180,t.height=s?180:240,t.bitrate=Math.max(t.bitrate,150)),t.width*t.height>1280*720&&ga&&(t.width=s?1280:720,t.height=s?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),t.bitrate&&(this.isNeedToSetBandwidth=t.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile)?super.setProfile(t):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),super.setProfile(L(N({},this.profile),{width:1920,height:1080})))}applyProfile(){var s;if(!this.mediaTrack)return;let e=this.settings;if(e.height!==this.profile.height||e.width!==this.profile.width||e.frameRate!==this.profile.frameRate)return(s=this.mediaTrack)==null?void 0:s.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}).then(()=>{if(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)return this.isNeedToSetBandwidth=!1,this.room.setBandWidth({bandwidth:this.profile.bitrate,type:h.VIDEO,videoType:h.BIG})})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate};return Rt&&this.mediaTrack&&Object.assign(e,this.mediaTrack.getSettings()),e}get scaleResolutionDownBy(){let{settings:e}=this;return e.width===this.profile.width&&e.height===this.profile.height?1:ba()&&this.profile.width>this.profile.height&&e.height>e.width?Math.max(e.width/this.profile.height,e.height/this.profile.width,1):Math.max(e.width/this.profile.width,e.height/this.profile.height,1)}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))return;let t={useExactDeviceId:!0};e==="user"||e==="environment"?t.facingMode=e:t.deviceId=e,this.mediaTrack.stop(),yield this.capture(t),T.emit(f.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}})}listenDeviceChange(){_e&&!_e.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&_e.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return p(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current camera is lost: ${JSON.stringify(e)}`);let t=yield He();t[0]?this.recapture(t[0].deviceId):_e.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return p(this,null,function*(){this.log.warn(`camera added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)})}play(e,t){return p(this,null,function*(){return E(this.mirror)&&!this.isScreen&&this.setMirror("view"),Re(ae.prototype,this,"play").call(this,e,t)})}close(){_e.off("videoInputAdded",this.handleCameraAdded,this),_e.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return p(this,null,function*(){try{yield Re(ae.prototype,this,"recapture").call(this,e)}catch(t){let s=(yield He()).find(n=>n.deviceId!==e);if(s)yield Re(ae.prototype,this,"recapture").call(this,s.deviceId);else throw t}})}};var Bu=gs();if(navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:Bu,exposeOrigin:!0,permittedOrigins:["*"]})}catch(r){}var np=function(r){return p(this,null,function*(){let i=null,e=cp(r);A.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let t=yield navigator.mediaDevices.getDisplayMedia(e);r.systemAudio&&t.getAudioTracks().length===0&&(dr&&Ut<74||Xe||Y)&&A.warn("Your browser not support capture system audio");let s=t.getVideoTracks()[0];if(s){if(r.frameRate)try{yield s.applyConstraints({frameRate:{min:r.frameRate,ideal:r.frameRate},width:r.width,height:r.height})}catch(n){A.warn(`screen applyConstraints failed: ${n}`)}r.captureElement&&(yield op(s,r.captureElement))}if(r.audio){let n=ap(r);A.info(`getUserMedia with constraints: ${JSON.stringify(n)}`),i=yield navigator.mediaDevices.getUserMedia(n),t.addTrack(i.getAudioTracks()[0])}return t})};function op(r,i){return p(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&X(r.cropTo))try{if(!(((e=r.getCaptureHandle())==null?void 0:e.handle)===Bu))return;let s=yield CropTarget.fromElement(i);yield r.cropTo(s)}catch(t){A.warn(`cropTo target failed ${t}`)}})}function ap(r){let i={echoCancellation:r.echoCancellation,autoGainControl:r.autoGainControl,noiseSuppression:r.noiseSuppression,sampleRate:r.sampleRate,channelCount:r.channelCount};return E(r.microphoneId)||(i.deviceId=r.microphoneId),{audio:i,video:!1}}function cp(r){let i={preferCurrentTab:r.preferDisplaySurface==="current-tab",systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:Xe?{max:r.width}:{ideal:r.width,max:r.width},height:Xe?{max:r.height}:{ideal:r.height,max:r.height},frameRate:r.frameRate,displaySurface:r.preferDisplaySurface||"monitor"};if(i.video=e,r.systemAudio){let{echoCancellation:t=!0,noiseSuppression:s=!1,autoGainControl:n=!1}=r;i.audio={echoCancellation:t,noiseSuppression:s,autoGainControl:n,sampleRate:48e3}}return i}var $u=np;var Ge=class extends ae{constructor(e){super(e,2);u(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600});u(this,"objectFit","contain");u(this,"isScreen",!0);this._log.id=`s-${this._log.id}`}capture(l){return p(this,arguments,function*({systemAudio:e=!1,autoGainControl:t,echoCancellation:s,noiseSuppression:n,audioTrack:o,videoTrack:a,captureElement:c,preferDisplaySurface:d}){try{let m;return a||o?(m=new MediaStream,a&&m.addTrack(a),o&&m.addTrack(o)):m=yield $u({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:t,echoCancellation:s,noiseSuppression:n,captureElement:c,preferDisplaySurface:d}),yield this.setInputMediaStreamTrack(m.getVideoTracks()[0]),m}catch(m){throw this.log.error(`getDisplayMedia error observed ${m}`),m instanceof C?m:new C({code:I.INITIALIZE_FAILED,name:m.name,message:m.message})}})}switchDevice(e){return p(this,null,function*(){throw new Error("Method not implemented.")})}};var bt=class extends Ne{constructor(i){super(i),this._log.id=`s-${this._log.id}`}};var dp="registerProcessor('dumper', class extends AudioWorkletProcessor {process(inputs) {this.port.postMessage(inputs);return true;}});",tc;function Hu(r){return p(this,null,function*(){let i=$e("dump");tc||(tc=gi(i,URL.createObjectURL(new Blob([dp],{type:"application/javascript"})))),yield tc;let e=new AudioWorkletNode(i,"dumper",{numberOfInputs:r.length,numberOfOutputs:0});return r.forEach((t,s)=>t.connect(e,0,s)),new ReadableStream({start(t){e.port.onmessage=s=>{t.enqueue(s.data)}},cancel(){r.forEach(t=>t.disconnect(e)),e.port.close()}})})}var no=class extends Xn{constructor(e){super();this.room=e;u(this,"_localAudioTrack");u(this,"_localScreenAudioTrack");u(this,"log",A.createLogger({id:"am"}));u(this,"denoiser");e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId))}get _localAudioPipline(){var e;return(e=this._localAudioTrack)==null?void 0:e.pipeline}dump(e){var l,m;if(!this._localAudioTrack)return;let t=[],s=[];(l=this._localAudioPipline)!=null&&l.source.node&&(t.push(this._localAudioPipline.source.node),s.push("mic")),(m=this._localAudioPipline)!=null&&m.denoiser.node&&(t.push(this._localAudioPipline.denoiser.node),s.push("mic-processed")),this.mixWeight>1&&(t.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),s.push("mix")),this.log.info(`dump audio track ${s}, duration: ${e}`);let n=new AbortController,o=[],a=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),n.abort("timeout")},e*1e3),c=()=>{for(let _=0;_<s.length;_++){let g=URL.createObjectURL(new Blob(o[_])),R=document.createElement("a");R.href=g,R.download=`${s[_]}.pcm`,R.style.display="none",document.body.appendChild(R),R.click(),URL.revokeObjectURL(g),R.remove()}clearTimeout(a),n.abort("download")},d=Hu(t).then(_=>_.pipeTo(new WritableStream({write(g){g.forEach((R,y)=>o[y]=o[y]?o[y].concat(R[0]):[R[0]])}}),n).catch(g=>c));return{then:d.then.bind(d),download:c}}get hasScreenAudioTrack(){return this._localScreenAudioTrack!==null}get hasAudioTrack(){return this._localAudioTrack!==null}changeInput(e){var t;if(e instanceof bt)this._localScreenAudioTrack=e,e.pipeline.connect(),this.mixOnChange();else if(e instanceof Ne)this._localAudioTrack=e,this.destination.channelCount=((t=e.trackSettings)==null?void 0:t.channelCount)||1,this.denoiser&&e.addDenoiser(this.denoiser),e.pipeline.connect(),this.mixOnChange();else if(e instanceof Qt)return e.setOutputMediaStreamTrack(e.mediaTrack)}mixOnChange(){var e,t;(e=this._localAudioTrack)==null||e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),(t=this._localScreenAudioTrack)==null||t.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)}removeInput(e){e instanceof bt?delete this._localScreenAudioTrack:e instanceof Ne?delete this._localAudioTrack:e instanceof Qt}addDenoiser(e){var t;this.denoiser=e,(t=this._localAudioTrack)==null||t.addDenoiser(e)}removeDenoiser(e){var t;delete this.denoiser,(t=this._localAudioTrack)==null||t.removeDenoiser(e)}destroy(){this.close()}};function oo(r=30,i=2){return F((e,t)=>function(...s){return new Promise((n,o)=>{let a=setTimeout(()=>{let c=new C({code:I.API_CALL_TIMEOUT,message:`checkPendingPromise ${t}() timeout ${r}s`});A.warn(c),i===2?o(c):i===1&&n()},r*1e3);e.apply(this,s).then(n,o).finally(()=>{clearTimeout(a)})})})}var ic=class extends Bi{constructor(e,t,s){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:s,room:e});this.room=e;this.user=t;u(this,"tinyId");u(this,"isRemote",!0);this.tinyId=t.tinyId}setMute(e){this.hasFlag&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.hasFlag&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}waitHasMediaTrack(){return new Promise(e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)})}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===ic.STATE_SUBSCRIBE}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}updatePlayingState(e){if(this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.hasFlag||!this.outMediaTrack)){this.log.info(`abort play, isSubscribed:${this.isSubscribed} hasFlag:${this.hasFlag} hasTrack:${!!this.outMediaTrack}`);return}super.updatePlayingState(e)}}onFlagChanged(){this.updatePlayingState(this.hasFlag)}},Ye=ic;u(Ye,"STATE_SUBSCRIBE","subscribe"),b([oo(5,1)],Ye.prototype,"waitHasMediaTrack",1),b([oe(V.INIT,Ye.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),T.emit(f.REMOTE_TRACK_SUBSCRIBED,{track:this}),this.updatePlayingState(!0)},ignoreError:!0})],Ye.prototype,"subscribe",1),b([oe(Ye.STATE_SUBSCRIBE,V.INIT,{sync:!0,success(){this.log.info("unsubscribed"),this.updatePlayingState(!1),T.emit(f.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],Ye.prototype,"unsubscribe",1);var Qt=class extends Ye{constructor(e,t){super(e,t,1);u(this,"volume",0);u(this,"mediaType",1);u(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.audioManager}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get hasFlag(){return this.user.muteState.hasAudio&&!this.user.muteState.audioMuted}isFlagChanged(e){let t=e.hasAudio&&!e.audioMuted;return this.hasFlag||(this.volume=0),this.hasFlag!==t}};var vt=class extends Ye{constructor(e,t,s=4){super(e,t,s);u(this,"mediaType",4);u(this,"source");u(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.videoManager}get isBig(){return this.mediaType===4}get isSmall(){return this.mediaType===8}changeType(e){this.room.changeType(e,this.user)}get hasFlag(){return this.user.muteState.hasVideo&&!this.user.muteState.videoMuted}isFlagChanged(e){let t=e.hasVideo&&!e.videoMuted;return this.hasFlag!==t}setMirror(e){e==="publish"||e==="both"||super.setMirror(e)}},Cr=class extends vt{constructor(e,t){super(e,t,2);u(this,"mediaType",2);u(this,"objectFit","contain")}get hasFlag(){return this.user.muteState.hasAuxiliary}isFlagChanged(e){let t=e.hasAuxiliary;return this.hasFlag!==t}};function fe(...r){}var up=r=>r();function sc(){this.dispose()}var lp=()=>typeof __FASTRX_DEVTOOLS__!="undefined",hp=1,zt=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(i){let e=new rc(i,this,this.streamId++);return lt.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},ws=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=fe,this.error=fe,this.next=fe,this.dispose=fe,this.subscribe=fe,this.doDefer()}subscribe(i){return i instanceof zt?i.subscribe(this):i(this),this}get bindSubscribe(){return i=>this.subscribe(i)}doDefer(){this.defers.forEach(up),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}},U=class extends ws{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)}};function Fu(r,...i){return i.reduce((e,t)=>t(e),r)}function Yt(r,i,e){if(lp()){let t=Object.defineProperties(Object.setPrototypeOf(r,zt.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}});lt.create(t);for(let s=0;s<e.length;s++){let n=e[s];typeof n=="function"&&n instanceof zt&&lt.addSource(t,n)}return t}return r}function G(r,i){return function(...e){return t=>{if(t instanceof zt){let s=Yt(n=>{let o=new r(n,...e);o.sourceId=s.id,o.subscribe(t)},i,arguments);return s.source=t,lt.pipe(s),s}else return s=>t(new r(s,...e))}}}function Ti(r,i){window.postMessage({source:"fastrx-devtools-backend",payload:{event:r,payload:i}})}var rc=class extends U{constructor(i,e,t){super(i),this.source=e,this.id=t,this.sourceId=i.sourceId,this.defer(()=>{lt.defer(this.source,this.id)})}next(i){lt.next(this.source,this.id,i),this.sink.next(i)}complete(){lt.complete(this.source,this.id),this.sink.complete()}error(i){lt.complete(this.source,this.id,i),this.sink.error(i)}},lt={addSource(r,i){Ti("addSource",{id:r.id,name:r.toString(),source:{id:i.id,name:i.toString()}})},next(r,i,e){Ti("next",{id:r.id,streamId:i,data:e&&e.toString()})},subscribe({id:r,end:i},e){Ti("subscribe",{id:r,end:i,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(r,i,e){Ti("complete",{id:r.id,streamId:i,err:e?e.toString():null})},defer(r,i){Ti("defer",{id:r.id,streamId:i})},pipe(r){Ti("pipe",{name:r.toString(),id:r.id,source:{id:r.source.id,name:r.source.toString()}})},update(r){Ti("update",{id:r.id,name:r.toString()})},create(r){r.id||(r.id=hp++),Ti("create",{name:r.toString(),id:r.id})}},ao=class extends Error{constructor(i){super(`timeout after ${i}ms`),this.timeout=i}};var nc=class extends ws{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 co(){return r=>{let i=new nc(r);if(r instanceof zt){let e=Yt(t=>{i.add(t)},"share",arguments);return i.sourceId=e.id,e.source=r,lt.pipe(e),e}return Yt(i.add.bind(i),"share",arguments)}}function mp(...r){return Yt(i=>{let e=r.length,t=e,s=e,n=new Array(e),o=()=>{--s===0&&i.complete()},a=(c,d)=>{let l=new U(i);l.next=m=>{--t===0?(l.next=_=>{n[d]=_,i.next(n)},l.next(m)):n[d]=m},l.complete=o,l.subscribe(c)};r.forEach(a)},"combineLatest",arguments)}var oc=class extends U{constructor(i,...e){super(i);let t=new U(this.sink);t.next=s=>this.buffer=s,t.complete=fe,t.subscribe(mp(...e))}next(i){this.buffer&&this.sink.next([i,...this.buffer])}},hI=G(oc,"withLatestFrom"),ac=class extends U{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()}},mI=G(ac,"bufferCount"),cc=class extends U{constructor(i,e){super(i),this.buffer=[];let t=new U(i);t.next=s=>{i.next(this.buffer),this.buffer=[]},t.complete=fe,t.subscribe(e)}next(i){this.buffer.push(i)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},pI=G(cc,"buffer");function dc(r){let i=arguments,e=co()(Yt(t=>{e.next=s=>t.next(s),e.complete=()=>t.complete(),e.error=s=>t.error(s),r&&t.subscribe(r)},"subject",i));return e.next=fe,e.complete=fe,e.error=fe,e}function Gu(r){return Yt(i=>{let e=0,t=setInterval(()=>i.next(e++),r);return i.defer(()=>{clearInterval(t)}),"interval"},"interval",arguments)}var uc=class extends U{constructor(i,e,t){super(i),this.f=e;let s=()=>{this.sink.next(this.acc),this.sink.complete()};typeof t=="undefined"?this.next=n=>{this.acc=n,this.complete=s,this.resetNext()}:(this.acc=t,this.complete=s)}next(i){this.acc=this.f(this.acc,i)}},pp=G(uc,"reduce");var lc=class extends U{constructor(i,e,t){super(i),this.filter=e,this.thisArg=t}next(i){this.filter.call(this.thisArg,i)&&this.sink.next(i)}},_p=G(lc,"filter"),hc=class extends U{next(i){}},yI=G(hc,"ignoreElements"),mc=class extends U{constructor(i,e){super(i),this.count=e}next(i){this.sink.next(i),--this.count===0&&this.complete()}},fp=G(mc,"take"),pc=class extends U{constructor(i,e){super(i);let t=new U(i);t.next=()=>i.complete(),t.complete=sc,t.subscribe(e)}},NI=G(pc,"takeUntil"),_c=class extends U{constructor(i,e){super(i),this.f=e}next(i){this.f(i)?this.sink.next(i):this.complete()}},Ep=G(_c,"takeWhile");var fc=class extends U{constructor(i,e){super(i),this.count=e}next(i){--this.count===0&&(this.next=super.next)}},bI=G(fc,"skip"),Ec=class extends U{constructor(i,e){super(i),i.next=fe;let t=new U(i);t.next=()=>{t.dispose(),i.resetNext()},t.complete=sc,t.subscribe(e)}},vI=G(Ec,"skipUntil"),gc=class extends U{constructor(i,e){super(i),this.f=e}next(i){this.f(i)||(this.next=super.next,this.next(i))}},gp=G(gc,"skipWhile"),Tp={leading:!0,trailing:!1},Tc=class extends U{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)}},Sc=class extends U{constructor(i,e,t=Tp){super(i),this.durationSelector=e,this.config=t,this._throttle=new Tc(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=fe,this._throttle.complete(),super.complete()}},OI=G(Sc,"throttle");var Ic=class extends U{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},Ac=class extends U{constructor(i,e){super(i),this.durationSelector=e,this._debounce=new Ic(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()}},DI=G(Ac,"debounce");var Rc=class extends U{constructor(i,e,t){super(i),this.count=e,this.defaultValue=t}next(i){this.count--===0&&(this.defaultValue=i,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()}},MI=G(Rc,"elementAt");var Cc=class extends U{constructor(i,e){super(i),this.f=e,this.i=0}next(i){this.f(i)?(this.sink.next(this.i++),this.complete()):++this.i}},kI=G(Cc,"findIndex"),yc=class extends U{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.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},LI=G(yc,"first"),Nc=class extends U{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()}},xI=G(Nc,"last"),bc=class extends U{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.complete())}complete(){if(this.result===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.result);super.complete()}},PI=G(bc,"every");var vc=class extends U{constructor(i,e,t){super(i),this.f=e,typeof t=="undefined"?this.next=s=>{this.acc=s,this.resetNext(),this.sink.next(this.acc)}:this.acc=t}next(i){this.sink.next(this.acc=this.f(this.acc,i))}},BI=G(vc,"scan"),Oc=class extends U{constructor(){super(...arguments),this.hasLast=!1}next(i){this.hasLast?this.sink.next([this.last,i]):this.hasLast=!0,this.last=i}},$I=G(Oc,"pairwise"),Dc=class extends U{constructor(i,e,t){super(i),this.mapper=e,this.thisArg=t}next(i){super.next(this.mapper.call(this.thisArg,i))}},Wu=G(Dc,"map");var yr=class extends U{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()}},Nr=class extends U{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=this.tryComplete,t.complete=t.tryComplete,t.subscribe(this.makeSource(i,this.index++))}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},uo=class extends yr{},lo=class extends Nr{next(i){this.subInner(i,uo),this.next=e=>{this.currentSink.dispose(),this.subInner(e,uo)}}},Sp=G(lo,"switchMap");function _o(r){return(i,e)=>r(()=>i,e)}var HI=_o(G(lo,"switchMapTo")),Mc=class extends yr{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},ho=class extends Nr{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(),Mc),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},FI=G(ho,"concatMap"),GI=_o(G(ho,"concatMapTo")),kc=class extends yr{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},mo=class extends Nr{constructor(){super(...arguments),this.inners=new Set}next(i){this.subInner(i,kc),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(i=>i.resetComplete()):this.dispose()}},WI=G(mo,"mergeMap"),JI=_o(G(mo,"mergeMapTo")),Lc=class extends yr{dispose(){this.context.resetNext(),super.dispose()}},po=class extends Nr{next(i){this.next=fe,this.subInner(i,Lc)}},jI=G(po,"exhaustMap"),qI=_o(G(po,"exhaustMapTo")),xc=class extends U{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=dc(),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)}},KI=G(xc,"groupBy"),Pc=class extends U{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}},XI=G(Pc,"timeInterval"),wc=class extends U{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()}},QI=G(wc,"bufferTime"),Vc=class extends U{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:s}=e;super.next(s),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)}},zI=G(Vc,"delay"),Uc=class extends U{constructor(i,e){super(i),this.selector=e}error(i){this.dispose(),this.selector(i)(this.sink)}},YI=G(Uc,"catchError");var Bc=class extends U{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)}))}},iA=G(Bc,"tap"),$c=class extends U{constructor(i,e){super(i),this.timeout=e,this.id=setTimeout(()=>this.error(new ao(this.timeout)),this.timeout)}next(i){super.next(i),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},rA=G($c,"timeout");var SA=Fu(Gu(250),Wu(()=>performance.now()),co());var br=new Map;T.on(f.JOIN_SUCCESS,({room:r})=>{ge(r.userId,{eventId:32788,eventDesc:"join room"})});T.on(f.LEAVE_START,({room:r})=>{ge(r.userId,{eventId:32789,eventDesc:"leave room"})});T.on(f.LOCAL_TRACK_PUBLISHED,({track:r})=>{if(r.room){let i=32769;r.mediaType===4?i=32768:r.mediaType===2&&(i=32805),ge(r.room.userId,{eventId:i,eventDesc:`publish ${r.kind}`})}});T.on(f.LOCAL_TRACK_UNPUBLISHED,({track:r})=>{if(r.room){let i=32771;r.mediaType===4?i=32770:r.mediaType===2&&(i=32806),ge(r.room.userId,{eventId:i,eventDesc:`unpublish ${r.kind}`})}});T.on(f.TRACK_MUTED,({track:r})=>{r.room&&(r.kind===h.AUDIO?ge(r.room.userId,{eventId:r.isRemote?32785:32772,eventDesc:"mute audio",remoteUserId:r.isRemote?r.userId:void 0}):ge(r.room.userId,{eventId:r.isRemote?32784:32773,eventDesc:"mute video",remoteUserId:r.isRemote?r.userId:void 0}))});T.on(f.TRACK_UNMUTED,({track:r})=>{r.room&&(r.kind===h.AUDIO?ge(r.room.userId,{eventId:r.isRemote?32787:32774,eventDesc:"unmute audio",remoteUserId:r.isRemote?r.userId:void 0}):ge(r.room.userId,{eventId:r.isRemote?32786:32775,eventDesc:"unmute video",remoteUserId:r.isRemote?r.userId:void 0}))});T.on(f.REMOTE_TRACK_SUBSCRIBED,({track:r})=>{!r.room||(r.mediaType===1&&ge(r.room.userId,{eventId:32777,eventDesc:`${h.SUBSCRIBE} ${r.kind}`,remoteUserId:r.userId}),r.mediaType===4&&ge(r.room.userId,{eventId:32776,eventDesc:`${h.SUBSCRIBE} ${r.kind}`,remoteUserId:r.userId}),r.mediaType===8&&ge(r.room.userId,{eventId:32803,eventDesc:`${h.SUBSCRIBE} ${h.SMALL_VIDEO}`,remoteUserId:r.userId}))});T.on(f.REMOTE_TRACK_UNSUBSCRIBED,({track:r})=>{!r.room||(r.mediaType===1&&ge(r.room.userId,{eventId:32779,eventDesc:`${h.UNSUBSCRIBE} ${r.kind}`,remoteUserId:r.userId}),r.mediaType===4&&ge(r.room.userId,{eventId:32778,eventDesc:`${h.UNSUBSCRIBE} ${r.kind}`,remoteUserId:r.userId}),r.mediaType===8&&ge(r.room.userId,{eventId:32804,eventDesc:`${h.UNSUBSCRIBE} ${h.SMALL_VIDEO}`,remoteUserId:r.userId}))});T.on(f.SWITCH_DEVICE_SUCCESS,({track:r})=>{r.room&&ge(r.room.userId,{eventId:r.kind===h.VIDEO?32780:32781,eventDesc:`switch ${r.kind===h.VIDEO?"camera":"microphone"}`})});T.on(f.LOCAL_TRACK_REPLACED,({track:r})=>{r.room&&ge(r.room.userId,{eventId:r.kind===h.VIDEO?32782:32783,eventDesc:`replace ${r.kind}`})});T.on(f.SIGNAL_CONNECTION_STATE_CHANGED,({room:r,prevState:i,state:e})=>{let t,s;switch(e){case"CONNECTED":i==="RECONNECTING"?(t=32795,s="signal reconnected"):(t=32791,s="signal connected");break;case"DISCONNECTED":i==="RECONNECTING"?(t=32796,s="signal reconnect fail"):(t=32790,s="signal disconnected");break;case"RECONNECTING":t=32794,s="signal reconnecting";break}t&&s&&ge(r.userId,{eventId:t,eventDesc:s})});T.on(f.PEER_CONNECTION_STATE_CHANGED,({room:r,prevState:i,state:e,remoteUserId:t})=>{let s=!!t,n=s?"downlink":"uplink",o,a;switch(e){case"CONNECTED":i==="RECONNECTING"?(o=s?32801:32798,a=`${n} reconnected`):(o=s?32793:32792,a=`${n} connected`);break;case"DISCONNECTED":i==="RECONNECTING"&&(o=s?32802:32799,a=`${n} reconnect fail`);break;case"RECONNECTING":o=s?32800:32797,a=`${n} reconnecting`;break}o&&a&&ge(r.userId,{eventId:o,eventDesc:a,remoteUserId:t})});function ge(r,i){let e=L(N({},i),{timestamp:Fr()});br.has(r)?br.get(r).push(e):br.set(r,[e])}function Ju(r){if(br.has(r)){let i=br.get(r).map(e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,str_event_json:e.eventDesc}));return br.delete(r),i}return[]}var ju=Ae(ke(),1);var fo=class extends ju.EventEmitter{constructor(e,t,s="userId"){super();this.mySelfId=e;this._log=t;this.key=s;u(this,"userMap",new Map);u(this,"remotePublishedUserMap",new Map)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:s,tinyId:n,role:o}=e;if(this.userMap.has(t))return;let a={userId:s,tinyId:n,role:o===20?"anchor":"audience"};this.userMap.set(t,a),this.emit("1",a)}deleteUser(e,t){let s=this.userMap.get(e);if(!s)return;let n=`peer leave [${e}]`;E(t)||(n+=`:${na[t]}`),this._log.info(n);let o=this.remotePublishedUserMap.get(e);if(o){let a=o.muteState;o.flag=0,this.emit("5",o.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:a,muteState:o.muteState,flag:0})}this.userMap.delete(e),this.emit("2",s.userId)}setUserList(e){this.userMap.forEach(t=>{e.findIndex(s=>s[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 s=t[this.key];if(e.findIndex(n=>n[this.key]===t[this.key])<0){this._log.info(`remote [${s}] unpublish`);let n=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(s),this.emit("6",{prevMuteState:n,muteState:t.muteState,flag:0})}}),e.forEach(t=>{var l;let s=t[this.key];if(s===this.mySelfId)return;let{flag:n,userId:o,tinyId:a}=t,c=_i(n,o),d=(l=this.remotePublishedUserMap.get(s))==null?void 0:l.muteState;if(d){let m=this.remotePublishedUserMap.get(s);m&&m.flag!==n&&(m.flag=n,this._log.info(`remote publish updated: ${JSON.stringify(m.muteState)}`),this.emit("6",{prevMuteState:d,muteState:c,flag:n}))}else this._log.info(`remote publish. state: ${JSON.stringify(c)}`),this.addUser({userId:o,tinyId:a,role:20}),this.emit("3",t),this.emit("6",{prevMuteState:_i(0,o),muteState:c,flag:n})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function Hc({timesInSecond:r,maxSizeInSecond:i,getSize:e}){return F((t,s)=>{let n=new Map;return T.on(f.ROOM_DESTROY,({room:o})=>n.delete(o)),function(...o){let a=n.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},n.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(...o)),a.timestamp!==0&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=r||a.totalSizeInSecond>i))throw new C({code:I.INVALID_OPERATION,message:D({key:v.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=r,isSize:a.totalSizeInSecond>i,name:s,timesInSecond:r,maxSizeInSecond:i}})});a.callCountInSecond++,t.call(this,...o)}})}var qu=!0,Ku=function(){var r;qu&&(qu=!1,A.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${mt}/en/index.html`),console.info(`* Changelog: ${mt}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),A.info("TRTC Web SDK Version:",Se),A.info("UA:",navigator.userAgent),A.info(`URL: ${location.href}${((r=self.frameElement)==null?void 0:r.tagName)==="IFRAME"?" in iframe":""}`),cs().then(i=>{if(i){let e=`UAData: ${i.platform}/${i.platformVersion}`;i.architecture&&i.bitness&&(e+=` ${i.architecture}/${i.bitness}`),i.mobile&&(e+=" mobile"),i.model&&(e+=` model: ${i.model}`),i.fullVersionList&&(e+=` ${i.fullVersionList.filter(t=>t.brand!=="Not/A)Brand").map(t=>`${t.brand}/${t.version}`).join(",")}`),A.info(e)}}))};var Ze={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"};var k={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},Ot=(S=>(S[S.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",S[S.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",S[S.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",S[S.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",S[S.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",S[S.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",S[S.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",S[S.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",S[S.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",S[S.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",S[S.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",S[S.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",S[S.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",S[S.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",S[S.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",S[S.INVALID_ROOM_ID_REQUIED=5015]="INVALID_ROOM_ID_REQUIED",S[S.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",S[S.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",S[S.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",S[S.INVALID_OPERATION=5100]="INVALID_OPERATION",S[S.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",S[S.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",S[S.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",S[S.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",S[S.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",S[S.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",S[S.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",S[S.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",S[S.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",S[S.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",S[S.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",S[S.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",S[S.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",S[S.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",S[S.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",S[S.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",S[S.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",S[S.DEVICE_ERROR=5300]="DEVICE_ERROR",S[S.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",S[S.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",S[S.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",S[S.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",S[S.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",S[S.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",S[S.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",S[S.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",S[S.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",S[S.SERVER_ERROR=5400]="SERVER_ERROR",S[S.NEED_TO_BUY=5401]="NEED_TO_BUY",S[S.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",S[S.OPERATION_FAILED=5500]="OPERATION_FAILED",S[S.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",S[S.REJOIN_FAILED=5502]="REJOIN_FAILED",S[S.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",S[S.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",S[S.OPERATION_ABORT=5998]="OPERATION_ABORT",S[S.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",S))(Ot||{});function Qu({code:r,params:i,enableDocLink:e=!1}){let t="",s,n=Ot[r];try{s=Xu[n]}catch(o){s=Xu.UNKNOWN_ERROR}return X(s)?t=s(i):Q(s)&&(t=s),i.fnName&&!t.includes(i.fnName)&&(t[t.length-1]!=="."&&(t+="."),t+=` thrown from ${i.fnName}()`),e&&(t+=" doc:"),t}var Xu=L(N({},Ee),{INVALID_PARAMETER({fnName:r}){return`the parameters of the '${r}' you called does not meet the requirements, please check the API documentation.`},INVALID_PARAMETER_REQUIRED({key:r,rule:i,fnName:e,value:t}){return`'${r||i.name}' is a required param when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_TYPE({key:r,rule:i,fnName:e,value:t}){let s=`${r||i.name}`,n="";return Array.isArray(i.type)?n=i.type.join("|"):n=i.type,`'${s}' must be type of ${n} when calling ${e}(), received type: ${he(t)}.`},INVALID_PARAMETER_EMPTY({key:r,rule:i,fnName:e,value:t}){return`'${r||i.name}' cannot be '${t}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:r,rule:i,fnName:e,value:t}){let s=`${r||i.name}`,n=`${i.instanceOf.name||i.instanceOf}`;return`'${s}' must be instanceof ${n} when calling ${e}(), received type: ${he(t)}.`},INVALID_PARAMETER_RANGE({key:r,rule:i,fnName:e,value:t}){return`'${r||i.name}' must be one of ${i.values.join("|")} when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_LESS_THAN_ZERO({key:r,rule:i,fnName:e}){return`'${r||i.name}' cannot be less than 0 when calling ${e}().`},INVALID_PARAMETER_MIN({key:r,rule:i,value:e}){return`the min value of ${r||i.name} is ${i.min}, received: ${e}.`},INVALID_PARAMETER_MAX({key:r,rule:i,value:e}){return`the max value of ${r||i.name} is ${i.max}, received: ${e}.`},INVALID_ELEMENT_ID({key:r,fnName:i}){return`'${r}' is not found in the document object when calling ${i}().`},INVALID_ELEMENT_ID_TYPE({key:r,fnName:i,type:e}){return`the element corresponding to '${r}' must be instanceof HTMLElement when calling ${i}(), received: ${e}.`},INVALID_STREAM_ID({key:r}){return`'${r}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},INVALID_ROOM_ID_STRING({key:r}){return`'${r}' must be a valid string.`},INVALID_ROOM_ID_INTEGER({key:r}){return`'${r}' must be an integer between [1, 4294967294].`},INVALID_ROOM_ID_INTEGER_STRING({key:r}){return`'${r}' must be an integer but go a string, use 'parseInt' to convert it or use 'strRoomId' instead.`},INVALID_ROOM_ID_REQUIED(){return"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required."},INVALID_STREAM_TYPE:({fnName:r})=>`'streamType' is required when 'userId' is not '*', calling ${r}()`,INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION({fnName:r}){return`the API '${r}' you called does not meet the requirements, please check the API documentation.`},INVALID_OPERATION_NOT_JOINED({fnName:r}){return`cannot ${r} because you are not enter room yet.`},INVALID_OPERATION_REMOTE_USER_NOT_EXIST({fnName:r,value:i}){return`cannot ${r} because remote user(userId: ${i.userId}) does not publishing stream.`},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST({fnName:r,value:i}){return`cannot ${r} because remote user(userId: ${i.userId}) does not publishing ${i.streamType} video.`},INVALID_OPERATION_REPEAT_CALL({fnName:r}){return`you are already ${r}(), cannot repeated call '${r}'.`},INVALID_OPERATION_NEED_VIDEO({fnName:r}){return`cannot call '${r}' because the camera is not turned on.`},INVALID_OPERATION_NEED_AUDIO({fnName:r}){return`cannot call '${r}' because the microphone is not turned on.`},INVALID_BUFFER_EMPTY:({key:r})=>`the buffer size of paramerter '${r}' cannot be empty`,INVALID_BUFFER_OVERSIZE:()=>"buffer size is over 1000 Bytes",INVALID_ROLE_AUDIENCE:()=>`role: '${"audience"}' cannot call this api.`,ENV_NOT_SUPPORTED({fnName:r}){return`the current browser does not support the capability of the function '${r}' 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:r}){return`cannot call ${r} because the browser version is too low, please upgrade to the latest version`},DEVICE_ERROR({fnName:r,error:i}){return`'${r}' got device exception${i?`, error: ${i.toString()}.`:"."}`},DEVICE_NOT_FOUND_ERROR({fnName:r,deviceType:i=$i(r),error:e}){return`NotFoundError, no ${i} detected, please check your device and the configuration on '${r}'${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_ALLOWED_ERROR({fnName:r,deviceType:i=$i(r),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:r,deviceType:i=$i(r),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:r,deviceType:i=$i(r),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:r,deviceType:i=$i(r),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:r,deviceType:i=$i(r),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:r,deviceType:i=$i(r),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:r}){return`camera recover capture failed ${(r==null?void 0:r.name)||""}: ${(r==null?void 0:r.originMessage)||(r==null?void 0:r.message)}`},MICROPHONE_RECOVER_FAILED({error:r}){return`microphone recover capture failed ${(r==null?void 0:r.name)||""}: ${(r==null?void 0:r.originMessage)||(r==null?void 0:r.message)}`},OPERATION_FAILED({fnName:r,error:i}){return`'${r}' 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:r}){return`an error was caught on trtc.on('${r}', handler), please check your code on 'handler'.`},VIDEO_CONTEXT_ERROR({reason:r,error:i}){return`video context error ${r} ${(i==null?void 0:i.name)||""} ${(i==null?void 0:i.message)||""}`},SERVER_ERROR({fnName:r,error:i}){return`'${r}' got server error: ${i==null?void 0:i.toString()}, please check the SDK documentation.`},NEED_TO_BUY({value:r,url:i}){return`You need to buy packages for ${r}. Refer to: ${i}`},ACCOUNT_NO_MONEY:({fnParams:r})=>`your TRTC account run out of credit, please recharge.${r.sdkAppId?` SDKAppId: ${r.sdkAppId}`:""}`,OPERATION_ABORT({fnName:r}){return`'${r}' abort`},UNKNOWN_ERROR({fnName:r,error:i}){return`'${r}' throw unknown exception${i?`, error: ${i.toString()}.`:"."}`}});function $i(r){if(!r)return"camera";let i=r.toLowerCase();return i.includes("screen")?"screen share":i.includes("audio")?"microphone":"camera"}var Hi=class extends Error{constructor({code:e,extraCode:t,message:s="",messageParams:n,fnName:o="",originError:a}){var d;let c;s?c=s:c=Qu({code:t||e,params:N({fnName:o,error:a},n)});super(c);u(this,"name","RtcError");u(this,"code");u(this,"extraCode");u(this,"functionName");u(this,"message");u(this,"handler");u(this,"originError");this.name=Ot[e],this.code=e,this.extraCode=t,this.functionName=o,this.originError=a,this.message=c,this.extraCode===5302&&((d=this.originError)==null?void 0:d.message.includes("system"))&&(this.handler=()=>{let l={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},m={startLocalVideo:"webcam",startLocalAudio:"microphone"},_=document.createElement("a");di?_.href=`ms-settings:privacy-${m[this.functionName]}`:ft&&(_.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${l[this.functionName]}`),_.href.length>0&&_.click()})}static convertFrom(e,t,s){let n=e;if(e instanceof C){let{stack:o}=e,a={code:k.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case I.INVALID_PARAMETER:a.code=k.INVALID_PARAMETER,a.message=e.message;break;case I.INVALID_OPERATION:a.code=k.INVALID_OPERATION;break;case I.NOT_SUPPORTED:case I.NOT_SUPPORTED_H264:a.code=k.ENV_NOT_SUPPORTED,e.getCode()===I.NOT_SUPPORTED_H264&&(a.extraCode=e.message.includes(Ee.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case I.JOIN_ROOM_FAILED:a.messageParams={fnParams:s};case I.SERVER_TIMEOUT:case I.SWITCH_ROLE_FAILED:a.code=k.SERVER_ERROR,a.extraCode=e.getExtraCode();break;case I.API_CALL_ABORTED:a.code=k.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=Ip(e.name));break;case I.UNKNOWN:break;default:a.code=k.OPERATION_FAILED}n=new Hi(a),o&&(n.stack+=o.substr(o.indexOf(`
32
+ `)))}else{if(e instanceof Hi)return e;n=new Hi({code:k.UNKNOWN_ERROR,fnName:t,originError:e})}return n}};function Ip(r){let i;switch(r){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 M=Hi;var zu={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:{properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack}}},Yu={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}}},vr={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(r,i,e){if(Q(r)&&!document.getElementById(r))throw new M({code:k.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:i}})}},Zu={name:"userId",required:!0,type:"string"},el={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[Ze.AUDIO_PROFILE_STANDARD,Ze.AUDIO_PROFILE_STANDARD_STEREO,Ze.AUDIO_PROFILE_HIGH,Ze.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function Vs(r,i){if(!r)throw new M({code:k.INVALID_OPERATION,extraCode:5101,fnName:i})}function tl(r,i,e){if(!r)throw new M({code:k.INVALID_OPERATION,extraCode:5102,fnName:i,messageParams:{value:e}})}var lC={type:"number",notLessThanZero:!0},Ap={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(r,i,e){if(this._room.isJoined)throw new M({code:k.INVALID_OPERATION,extraCode:5104,fnName:e});if(r.roomId){if(Q(r.roomId))throw new M({code:k.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:i}});if(!(/^[1-9]\d*$/.test(String(r.roomId))&&r.roomId<4294967295))throw new M({code:k.INVALID_PARAMETER,extraCode:5013,fnName:e,messageParams:{key:i}})}else if(r.strRoomId){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(r.strRoomId))throw new M({code:k.INVALID_PARAMETER,extraCode:5012,fnName:e,messageParams:{key:i}})}else throw new M({code:k.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"}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:vr,mute:{type:["boolean","string"]},publish:{type:"boolean"},option:zu},validate(r){var i;if(!((i=r==null?void 0:r.option)!=null&&i.videoTrack)&&Wt())throw new M({code:k.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:L(N({},vr),{required:!1}),publish:{type:"boolean"},mute:{type:["boolean","string"]},option:zu}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:el},validate(r){var i;if(!((i=r==null?void 0:r.option)!=null&&i.audioTrack)&&Wt())throw new M({code:k.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:el}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:vr,publish:{type:"boolean"},option:Yu},validate(r,i,e,t,s){var n;if(!((n=r==null?void 0:r.option)!=null&&n.videoTrack)&&Wt())throw new M({code:k.ENV_NOT_SUPPORTED,extraCode:5201});if(!Ss())throw new M({code:k.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:vr,publish:{type:"boolean"},option:Yu}},muteRemoteAudio:[Zu,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[Zu,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:vr,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(r,i,e){Vs(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(r.userId);if(tl(!!t,e,r),t&&(r.streamType==="main"&&!t.muteState.videoAvailable||r.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new M({code:k.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:r}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:L(N({},vr),{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(r,i,e){Vs(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(r.userId);if(tl(!!t,e,r),t&&(r.streamType==="main"&&!t.muteState.videoAvailable||r.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new M({code:k.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:r}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(r,i,e){if(r.userId!=="*"&&E(r.streamType))throw new M({code:k.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(r,i,e){Vs(this._room.isJoining||this._room.isJoined,e)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(r,i,e,t){if(!Ei)throw new M({code:k.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new M({code:k.INVALID_OPERATION,messageParams:{key:v.SEI_DISABLED}});if(r.byteLength>1e3)throw new M({code:k.INVALID_PARAMETER,extraCode:5018,fnName:e});if(r.byteLength===0)throw new M({code:k.INVALID_PARAMETER,extraCode:5017,messageParams:{key:i},fnName:e});if(Vs(this._room.isJoined,e),!this._room.isMainStreamPublished)throw new M({code:k.INVALID_PARAMETER,messageParams:{key:v.SEI_BEFORE_PUBLISH}})}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]}}}],sendCustomMessage:{name:"message",required:!0,type:"object",properties:{cmdId:{type:"number",required:!0,min:1,max:10},data:{instanceOf:ArrayBuffer,required:!0,validate(r,i,e,t){if(r.byteLength>1e3)throw new M({code:k.INVALID_PARAMETER,extraCode:5018,fnName:e});if(r.byteLength===0)throw new M({code:k.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:i}})}}},validate(r,i,e){if(Vs(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new M({code:k.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:i}})}}},Te={TRTC:Ap};var be=class extends Error{};function Rp(r,i){let e=pr(r);for(let t=0;t<i.length;t++)$t(e[t],i[t]);return e}function Cp(r){this._resolve=Promise.resolve(r)}function yp(r){this._reject=Promise.reject(r)}var Or=class{constructor(i,e){this.instance=i;this.group=e;this.started=!1;this.ops=[];this.startSame=()=>!0;this.mergeUpdate=Rp;let t=Or.instances.get(i);t?t.set(e,this):Or.instances.set(i,new Map([[e,this]]))}static get(i,e){let t=Or.instances.get(i);return t&&t.get(e)||new Or(i,e)}action(i,e,t){let s=a=>{var c;return i===0?this.started=!0:i===3&&(this.started=!1),this.ops.shift(),(c=this.currentOp)==null||c.action(),a},n=a=>{var c,d;throw this.ops.shift(),i===0&&((c=this.currentOp)==null?void 0:c.type)===2&&this.ops.shift().reject(new be("start failed")),(d=this.currentOp)==null||d.action(),a},o={type:i,action:()=>e(...o.args).then(s,n),args:t,resolve:Cp,reject:yp};try{switch(this.state){case 1:if(i===0)throw new be("already started");break;case 4:if(i===2)throw new be("not started");break;default:return this.cacheOp(o)}}catch(a){return Promise.reject(a)}return this.ops.push(o),o.promise=e(...o.args).then(s,n)}cacheOp(i){if(this.ops.length===1)switch(this.state){case 0:case 2:if(i.type===0)throw new be("already start");break;case 3:switch(i.type){case 2:throw new be("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new be("unknown state")}else switch(i.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let t=new be("keep stop");if(this.ops.slice(1).forEach(s=>s.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 be("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new be("start not allowed after update");case 0:throw new be("duplicate start");case 3:if(this.startSame(this.currentOp.args,i.args))throw this.ops.pop().reject(new be("keep start")),new be("already start")}}i.promise=new Promise((t,s)=>{i._resolve?i._resolve.then(t):i.resolve=t,i._reject?i._reject.catch(s):i.reject=s});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}},Zt=Or;Zt.instances=new WeakMap;var go=new WeakMap,To=(r,i)=>{if(i instanceof be){let{stack:e}=i;i=new M({code:k.OPERATION_ABORT,message:`${r} abort: ${i.message}`,fnName:r}),e&&(i.stack+=e.substr(e.indexOf(`
33
33
  `)))}throw i};function Si(r,i){return F((e,t)=>function(...s){let n=Zt.get(this,typeof r=="string"?r:r.call(this,...s));return i&&(n.startSame=i.bind(this)),n.action(0,e.bind(this),s).catch(To.bind(null,t))})}function Fi(r,i){let{merge:e,debounce:t}=i||{};return F((s,n)=>function(...o){let a=Zt.get(this,typeof r=="string"?r:r.call(this,...o));if(e&&(a.mergeUpdate=e.bind(this)),t&&t.isNeedToDebounce.apply(this,o)){let{delay:c,getKey:d}=t;return new Promise((l,m)=>{var R,y;let _=(R=go.get(this))==null?void 0:R.get(d(...o));if(_){let{timeoutId:x,resolve:ie}=_;clearTimeout(x),ie()}let g=setTimeout(()=>{if(a.state===3||a.state===4)return l();a.action(2,s.bind(this),o).catch(To.bind(null,n)).then(l,m)},c);go.has(this)?(y=go.get(this))==null||y.set(d(...o),{timeoutId:g,resolve:l}):go.set(this,new Map([[d(...o),{timeoutId:g,resolve:l}]]))})}return a.action(2,s.bind(this),o).catch(To.bind(null,n))})}function Ii(r){return F((i,e)=>function(...t){return Zt.get(this,typeof r=="string"?r:r.call(this,...t)).action(3,i.bind(this),t).catch(To.bind(null,e))})}var $={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",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"};function Us(r){return r==="sub"?"auxiliary":r==="auxiliary"?"sub":"main"}function Gi(r){return r===Ze.QOS_PREFERENCE_CLEAR?"detail":r===Ze.QOS_PREFERENCE_SMOOTH?"motion":""}function sl(r,i,e){return{room:r,assetsPath:e,innerEmitter:T,constants:oa,environment:lr,utils:Me,eventLogger:ee,log:r.getLogger(),errorModule:i,kvStatManager:w,clearStarted(t,s){let n=t.getAlias(),o=Zt.instances.get(r);if(!!o)if(s){let a=o.get(n+s);if(!a)return;a.started=!1}else o.forEach((a,c)=>{c.startsWith(n)&&(a.started=!1)})}}}var nl=(r,i)=>{let{emit:e}=r;return r.emit=(...t)=>{try{return e.apply(r,t)}catch(s){let n=D({key:v.CATCH_HANDLER_ERROR,data:{name:i,event:t[0]},addDocLink:!1});return A.warn(`${n}
34
34
 
35
- ${s.stack}`),!1}},r};var So=new WeakMap;function ol(r,i){return F((e,t)=>function(...s){var a,c;let n=(a=So.get(this))==null?void 0:a.get(i(...s));n&&n>0&&clearTimeout(n);let o=window.setTimeout(()=>{e.apply(this,s)},r);So.has(this)?(c=So.get(this))==null||c.set(i(...s),o):So.set(this,new Map([[i(...s),o]]))})}var al="5.6.2-beta.2";function ve(...r){return F((i,e)=>function(...t){try{Ao.call(this,r,t,e,this._name)}catch(s){return Promise.reject(s)}return i.apply(this,t)})}function Fc(...r){return F((i,e)=>function(...t){try{Ao.call(this,r,t,e,this._name)}catch(s){throw s}return i.apply(this,t)})}function Ao(r,i,e,t){if(de(r))for(let s=0;s<r.length;s++)Io.call(this,{rule:r[s],value:i[s],key:r[s].name,fnName:e,className:t});else Io.call(this,{rule:r,value:i[0],key:r.name,fnName:e,className:t})}function Io({rule:r,value:i,key:e,fnName:t,className:s}){function n(c){return{code:k.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:r,value:i}}}if(E(i)){if(r.required)throw new M(n(5001));if(E(r.defaultValue)){X(r.validate)&&r.validate.call(this,i,e,t,s,this);return}i=r.defaultValue}if(Array.isArray(r.type)){let c=!1;for(let d=0;d<r.type.length;d++)r.type[d]===null&&i===null&&(c=!0),X(r.type[d])&&i instanceof r.type[d]&&(c=!0),Q(r.type[d])&&he(i)===r.type[d].toLowerCase()&&(c=!0);if(!c)throw new M({code:k.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:r.type.map(d=>ps(d)?wn(d):Q(d)?d:he(d))},value:i}})}else if(!E(r.type)&&he(i)!==r.type)throw new M(n(5002));if(r.allowEmpty===!1){let c=re(i)&&(i===0||Number.isNaN(i)),d=Q(i)&&i.trim()==="";if(c||d)throw new M(n(5003))}if(r.notLessThanZero&&re(i)&&i<0)throw new M(n(5006));if(!E(r.min)&&re(i)&&i<r.min)throw new M(n(5007));if(!E(r.max)&&re(i)&&i>r.max)throw new M(n(5008));if(Q(r.instanceOf)){if(!i||i._name!==r.instanceOf)throw new M(n(5004))}else if(X(r.instanceOf)&&!(i instanceof r.instanceOf))throw new M(n(5004));if(Array.isArray(r.values)&&!r.values.includes(i))throw new M(n(5005));let{properties:o}=r;Be(o)&&ct(i)&&Object.keys(o).forEach(c=>{Io.call(this,{rule:o[c],value:i&&i[c],key:`${c}`,fnName:t,className:s})});let{arrayItem:a}=r;Be(a)&&de(i)&&i.forEach((c,d)=>{Io.call(this,{rule:a,value:c,key:`${e}[${d}]`,fnName:t,className:s})}),X(r.validate)&&r.validate.call(this,i,e,t,s,this)}function ne(r={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t}=r;return F((s,n)=>function(...o){function a(l,m,_){if(_&&_.includes(l))return"hided";if(e){let g=e(...o);if(o[g.argIndex]===m)return g.value}if(m===o||l in o)return m;try{return m instanceof HTMLElement?`id: ${m.id} type:${he(m)}`:(JSON.stringify(m),m)}catch(g){return`type:${he(m)}`}}let c=this._log||A;o.length>0?c.info(`${n}() ${JSON.stringify(o,(l,m)=>a(l,m,["userSig","privateMapKey"]))}`):c.info(`${n}()`);let d=t?t(...o):qa[n];try{let l=s.apply(this,o),m=B();return ms(l)?l.then(_=>(c.info(`${n}() success ${i.call(this,...o)}`),w.addSuccessEvent({key:d,cost:B()-m}),_)).catch(_=>{throw _=M.convertFrom.call(this,_,n,o.length===1?o[0]:o),c.error(`${n}() failed ${i.call(this,...o)} ${_} params: ${JSON.stringify(o,a)}`),w.addFailedEvent({key:d,error:_}),_}):(w.addSuccessEvent({key:d}),l)}catch(l){throw l=M.convertFrom.call(this,l,n),c.error(`${n}() failed ${l} params: ${JSON.stringify(o,a)}`),w.addFailedEvent({key:d,error:l}),l}})}var Ro=r=>F((i,e)=>function(t,s){return p(this,null,function*(){let n=this._plugins.get(t);if(!n)throw this._log.error(`plugin ${String(t)} is not found`),new M({code:k.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});return Ao.call(this,n.getValidateRule(r),[s],e,"TRTC"),i.call(this,n,s)})});var Co=0,Gc=class{constructor(i,e){u(this,"player");u(this,"publisher");u(this,"mixInput");this.mixInput=new Sr(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),i.loop&&(this.loop=i.loop),i.volume&&(this.volume=i.volume),this.mixInput.connect()}reset(){this.seek(0),this.mixInput.connect()}seek(i){!this.player||i<0&&i>this.player.duration||(this.player.currentTime=i,this.publisher.currentTime=i)}play(){var i,e;return(i=this.publisher)==null||i.play(),(e=this.player)==null?void 0:e.play()}pause(){var i,e;(i=this.player)==null||i.pause(),(e=this.publisher)==null||e.pause()}stop(){var i;(i=this.player)==null||i.pause(),this.mixInput.disconnect()}setOperation(i){i==="pause"&&this.pause(),i==="resume"&&(this.pause(),this.play()),i==="stop"&&(this.pause(),this.seek(0))}set volume(i){!this.player||!this.publisher||(this.player.volume=i,this.publisher.volume=i)}set loop(i){!this.player||!this.publisher||(this.player.loop=i,this.publisher.loop=i)}},Dr=class{constructor(i){this.core=i;u(this,"log");u(this,"mixedMusicMap",new Map);u(this,"cacheMusicMap",new Map);Co=Co+1,this.log=i.log.createChild({id:`${this.getAlias()}${Co}`}),this.log.info(`[audioMixer] created id=${this.getAlias()}${Co}`),this.core=i}getName(){return Dr.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return Dr.startValidateRule;case"update":return Dr.updateValidateRule;case"stop":return Dr.stopValidateRule}}start(i){return p(this,null,function*(){let{room:e}=this.core;this.log.info(`add music source, id: ${i.id} url: ${i.url}, track: ${i.track}`);let{id:t,url:s}=i;if(this.mixedMusicMap.has(t))return;let n=this.cacheMusicMap.get(t);n?i.url?n.reset():(n.mixInput.replaceSource(i.track),n.mixInput.connect()):(n=new Gc(i,e.audioManager),this.cacheMusicMap.set(t,n)),yield n.play(),this.mixedMusicMap.set(t,n),this.log.info(`start mix audio track ${t} success.`),w.addEnum({key:502700,value:3})})}update(i){return p(this,null,function*(){let{id:e,volume:t,loop:s,operation:n,seekFrom:o}=i;this.log.info(`update music source, ${JSON.stringify(i)}`);let a=this.mixedMusicMap.get(e);if(!a){this.log.warn(`update music source failed, music id: ${e} not found.`);return}E(t)||(a.volume=t),E(s)||(a.loop=s),E(n)||a.setOperation(n),E(o)||a.seek(o)})}stop(e){return p(this,arguments,function*({id:i}){var t;this.mixedMusicMap.has(i)&&(this.log.info(`remove music source, music id: ${i}`),(t=this.mixedMusicMap.get(i))==null||t.stop(),this.mixedMusicMap.delete(i)),i==="*"&&this.destroyAllMusic()})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((i,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()}},Ai=Dr;u(Ai,"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 s=i.url.split("?")[0],n=["mp3","ogg","wav","flac"],o=s.split(".").pop(),a=n.indexOf(o)>=0,c=s.startsWith("blob"),d=s.startsWith("data");if(!(a||c||d))throw new M({code:k.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new M({code:k.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t})}}),u(Ai,"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"]}}}),u(Ai,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),u(Ai,"Name","AudioMixer");var cl=r=>(r=Number(r),r>0&&r<14e8);var yo=0,Mr=class{constructor(i){this.core=i;u(this,"log");u(this,"workletReady");u(this,"audioContext",$e("denoiser"));u(this,"workletNode");yo=yo+1,this.log=i.log.createChild({id:`${this.getAlias()}${yo}`}),this.log.info(`[audioDenoiser] created id=${this.getAlias()}${yo}`),i.assetsPath&&(this.workletReady=gi(this.audioContext,`${i.assetsPath}/denoiser-wasm.js`),this.workletReady.catch(e=>{this.log.error(`Init assets from ${i.assetsPath} failed! Reason: ${e}`)}))}static startValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,t,s,n){if(!i.room.audioManager.hasAudioTrack)throw new M({code:k.INVALID_OPERATION,extraCode:5106,fnName:s})}}}getName(){return Mr.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(i){switch(i){case"start":return Mr.startValidateRule(this.core);case"update":return Mr.updateValidateRule;case"stop":return Mr.stopValidateRule}}start(i){return p(this,null,function*(){let{room:e}=this.core;if(this.workletReady||(this.workletReady=gi(this.audioContext,`${i.assetsPath}/denoiser-wasm.js`),this.workletReady.catch(t=>{this.log.error(`Init assets from ${i.assetsPath} failed! Reason: ${t}`)})),!this.workletNode){let t=String(Date.now()).slice(0,-3),{auth:s,sign:n,status:o,message:a}=yield vp(L(N({},i),{timestamp:t}));if(!s)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${s}. Message: ${a}`),new M({code:k.INVALID_PARAMETER,message:a});yield this.workletReady,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:t,sign:n,status:o}}),this.workletNode.port.onmessage=c=>{let{data:d}=c;d.type==="cost"&&this.log.debug(`[RTCAIDenoiser] ${d.value}`)}}this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(){return p(this,null,function*(){})}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)})}destroy(){}},Wi=Mr;u(Wi,"updateValidateRule",{type:"object"}),u(Wi,"stopValidateRule",{type:"object"}),u(Wi,"Name","AIDenoiser");var dl={MAIN:"schedule.cloud-rtc.com",MAIN_OVERSEA:"schedule.rtc.tencentcloud.com"};function bp(r){let i;return cl(r)?i=dl.MAIN_OVERSEA:i=dl.MAIN,i}function vp(s){return p(this,arguments,function*({sdkAppId:r,userId:i,userSig:e,timestamp:t}){let o=`https://${bp(r)}/api/v1/audioAiAuth?sdkAppId=${r}&userId=${i}&userSig=${e}&timestamp=${t}`,a=yield fetch(o),{data:{errCode:c,errMsg:d,sign:l,status:m}}=yield a.json();if(m==="1")return{auth:!0,sign:l,status:m,message:d};let _="Init RTCAIDenoiser failed.",g="";switch(c){case 1:g="Please check your params.";break;case 2:g="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:g="Server is invalid. Please contact our engineer. ";break;case 4:g="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:g="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:g="Your version is not supported.";break}return{auth:!1,status:m,message:d?`${_} Reason: ${d}. ${g}`:`${_}, ${g}`}})}var ul=0,Wc=new Set,Oe=null;jo(al);var Op={RtcError:M,ErrorCode:k,ErrorCodeDictionary:Ot},Bs=class extends hl.EventEmitter{constructor(e,t){super();u(this,"_room");u(this,"_eventListened",new Set);u(this,"_localVideoTrack",null);u(this,"_localAudioTrack",null);u(this,"_localScreenTrack",null);u(this,"_localScreenAudioTrack",null);u(this,"_localVideoConfig",null);u(this,"_localScreenConfig",null);u(this,"_localAudioConfig",null);u(this,"_remoteVideoConfigMap",new Map);u(this,"_remoteAudioConfigMap",new Map);u(this,"_remoteAudioMuteMap",new Map);u(this,"_mediaTrackMap",new WeakMap);u(this,"_log",A.createLogger({id:`t${++ul}`}));u(this,"_plugins",new Map);u(this,"_networkQuality",null);u(this,"_speakerId");this._room=new e(N({logger:this._log,frameWorkType:Bs.frameWorkType},t)),this._log.debug(JSON.stringify(t)),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(s){return this._room.audioManager.dump(s)}}}),t.plugins&&t.plugins.forEach(s=>{this._use(s,t.assetsPath)}),this._use(Ai,t.assetsPath),this._use(Wi,t.assetsPath),this._room.on("audio-volume",s=>{!s.find(n=>n.userId==="")&&this._localAudioTrack&&s.push({userId:"",volume:Math.floor(this._localAudioTrack.getAudioLevel()*100)}),this.emit($.AUDIO_VOLUME,{result:s.sort((n,o)=>o.volume-n.volume)})}),this._room.videoManager.on("error",({reason:s,error:n})=>{this._log.error(new M({code:k.OPERATION_FAILED,extraCode:5504,messageParams:{reason:s,error:n}}))}),this._listenEvents(),this._initActiveSpeaker(),nl(this,"trtc")}static create(e){}static _create(e,t){Ku();let s=new Bs(e,t||{});return Wc.add(s),s}_listenEvents(){we(this,this._room).add("peer-join",e=>{let{userId:t}=e;this.emit($.REMOTE_USER_ENTER,{userId:t})}).add("peer-leave",e=>{this.emit($.REMOTE_USER_EXIT,{userId:e})}).add("banned",e=>{this._exitRoom().then(()=>{this.emit($.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().then(()=>{this.emit($.ERROR,M.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit($.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e,this.emit($.NETWORK_QUALITY,e)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(s=>{we(s,s).add("player-state-changed",n=>{let o=L(N({},n),{userId:e.userId});s.kind===h.VIDEO&&(o.streamType=Us(s.streamType)),this.emit(s.kind===h.AUDIO?$.AUDIO_PLAY_STATE_CHANGED:$.VIDEO_PLAY_STATE_CHANGED,o)}).add("error",n=>{n.getCode()===I.PLAY_NOT_ALLOWED&&this.emit($.AUTOPLAY_FAILED,{userId:s.userId})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(s=>{pe(s)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:t})=>{let{userId:s}=t,n=e.audioAvailable,o=e.videoAvailable,{audioAvailable:a,videoAvailable:c}=t;a||this._remoteAudioConfigMap.delete(s),c||this._remoteVideoConfigMap.delete(`${s}_${"main"}`),t.hasAuxiliary||this._remoteVideoConfigMap.delete(`${s}_${"sub"}`),n!==a&&(this.emit(a?$.REMOTE_AUDIO_AVAILABLE:$.REMOTE_AUDIO_UNAVAILABLE,{userId:s}),a?this._onAudioAvailable({userId:s}):this._onAudioUnavailable({userId:s,muteState:t})),o!==c&&(this.emit(c?$.REMOTE_VIDEO_AVAILABLE:$.REMOTE_VIDEO_UNAVAILABLE,{userId:s,streamType:"main"}),c?this._onVideoAvailable({userId:s,streamType:"main"}):this._onVideoUnavailable({userId:s,streamType:"main"})),e.hasAuxiliary!==t.hasAuxiliary&&(this.emit(t.hasAuxiliary?$.REMOTE_VIDEO_AVAILABLE:$.REMOTE_VIDEO_UNAVAILABLE,{userId:s,streamType:"sub"}),t.hasAuxiliary?this._onVideoAvailable({userId:s,streamType:"sub"}):this._onVideoUnavailable({userId:s,streamType:"sub"}))}).add("firewall-restriction",()=>{this.emit($.ERROR,new M({code:k.OPERATION_FAILED,extraCode:5501}))}).add("sei-message",e=>{this.emit($.SEI_MESSAGE,L(N({},e),{streamType:Us(e.streamType)}))}).add("heartbeat-report",e=>{var n,o,a,c,d,l,m;let t={2:"big",3:"small",7:"sub"},s={rtt:e.msg_up_stream_info.msg_network_status.uint32_rtt||((n=e.msg_down_stream_info[0])==null?void 0:n.msg_network_status.uint32_rtt)||((o=this._networkQuality)==null?void 0:o.uplinkRTT)||((a=this._networkQuality)==null?void 0:a.downlinkRTT)||0,upLoss:((c=this._networkQuality)==null?void 0:c.uplinkLoss)||0,downLoss:((d=this._networkQuality)==null?void 0:d.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((l=e.msg_up_stream_info.msg_audio_status)==null?void 0:l.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((m=e.msg_up_stream_info.msg_audio_status)==null?void 0:m.uint32_audio_level)||0)/st},video:e.msg_up_stream_info.msg_video_status.filter(_=>t[_.uint32_video_stream_type]).map(_=>({bitrate:(_.uint32_video_codec_bitrate||0)/1e3,width:_.uint32_video_width,height:_.uint32_video_height,frameRate:_.uint32_video_enc_fps,videoType:t[_.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(_=>({userId:_.msg_user_info.str_identifier,audio:{bitrate:(_.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(_.msg_audio_status.uint32_audio_level||0)/st},video:_.msg_video_status.map(g=>({bitrate:(g.uint32_video_codec_bitrate||0)/1e3,width:g.uint32_video_width,height:g.uint32_video_height,frameRate:g.uint32_video_dec_fps,videoType:t[g.uint32_video_stream_type]}))}))};this.emit($.STATISTICS,s)}).add("custom-message",e=>{this.emit($.CUSTOM_MESSAGE,e)}),we(this,_e).add("audioInputAdded",e=>{this.emit($.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit($.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit($.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit($.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>p(this,null,function*(){if(this.emit($.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Oe&&Oe.deviceId===Xr){let t=(yield Ui()).find(s=>s.deviceId===Xr);t&&Oe.groupId!==t.groupId&&(Oe=t,this.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}})).add("audioOutputRemoved",e=>p(this,null,function*(){this.emit($.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield Ui())[0];t&&Oe&&(Oe.deviceId===e.deviceId||Oe.deviceId===Xr&&Oe.groupId!==t.groupId)&&(Oe=t,this.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}))}use(e){let t,s;"plugin"in e?(t=e.plugin,s=e.assetsPath):t=e,this._use(t,s||"https://web.sdk.qcloud.com/trtc/webrtc/v5/assets/")}_use(e,t){if(this._plugins.get(e.Name)){this._log.warn("duplicate install plugin",e.Name);return}let n=new e(sl(this._room,Op,t));this._plugins.set(e.Name,n)}enterRoom(e){return p(this,null,function*(){var c,d;let{scene:t="rtc",enableAutoPlayDialog:s=!0,autoReceiveAudio:n=!0,autoReceiveVideo:o=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!Q(e.proxy)&&e.proxy.turnServer&&((d=(c=this._room).setTurnServer)==null||d.call(c,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=s,this._room.autoReceiveAudio=n,this._room.autoReceiveVideo=o,ue(e.enableHWEncoder)&&(this._room.enableHWEncoder=e.enableHWEncoder);let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,role:e.role==="audience"?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(a,t,Bs.frameWorkType),this._checkTrackToPublish()})}exitRoom(){return p(this,null,function*(){return yield this._exitRoom()})}switchRole(e,t){return p(this,null,function*(){t!=null&&t.privateMapKey&&(this._room.privateMapKey=t.privateMapKey),yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){pe(this),this.removeAllListeners(),this._room.destroy(),Wc.delete(this),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),this._plugins.forEach(e=>{var t;return(t=e.destroy)==null?void 0:t.call(e)})}startLocalAudio(){return p(this,arguments,function*(e={publish:!0}){if(this._localAudioTrack){this._log.warn("local audio is already started");return}let{publish:t=!0,mute:s,option:n}=e,o=new Ne(this._room.audioManager),a={},c={muted:!0};n&&(E(n.microphoneId)?E(n.audioTrack)||(a.customSource=n.audioTrack):a.deviceId=n.microphoneId,n&&re(n.captureVolume)&&o.setCaptureVolume(n.captureVolume),E(n.profile)||(Q(n.profile)?un[n.profile]&&o.setProfile(un[n.profile]):o.setProfile(n.profile)),re(n.earMonitorVolume)&&(c.muted=!(n.earMonitorVolume>0),c.volume=n.earMonitorVolume),E(n.echoCancellation)||(o.profile.echoCancellation=n.echoCancellation),E(n.noiseSuppression)||(o.profile.noiseSuppression=n.noiseSuppression),E(n.autoGainControl)||(o.profile.autoGainControl=n.autoGainControl)),o.on("5",d=>{this.emit($.ERROR,new M({code:k.DEVICE_ERROR,extraCode:5309,messageParams:{error:d}}))}),o.on("2",d=>{this.emit($.DEVICE_CHANGED,{type:"microphone",action:"active",device:d})}),o.on("4",d=>{let l;d.error&&(l=M.convertFrom(d.error)),this.emit($.PUBLISH_STATE_CHANGED,L(N({},d),{error:l}))}),this._listenOutputTrackChanged(o),this._speakerId&&o.setAudioOutput(this._speakerId),yield o.capture(a),E(s)||o.setMute(s),we(o,o).add("player-state-changed",d=>{this.emit($.AUDIO_PLAY_STATE_CHANGED,L(N({},d),{userId:""}))}),t&&this._room.isJoined&&this._room.publish(o).catch(()=>{}),this._localAudioTrack=o,this._localAudioConfig=L(N({},e),{publish:t}),yield this._updateAudioPlayOption({playOption:c,track:o})})}updateLocalAudio(e){return p(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:s,option:n}=e,o={};n&&(n.microphoneId?yield this._localAudioTrack.switchDevice(n.microphoneId):E(n.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(n.audioTrack)),E(n.captureVolume)||this._localAudioTrack.setCaptureVolume(n.captureVolume),E(n.earMonitorVolume)||(o.muted=!(n.earMonitorVolume>0),o.volume=n.earMonitorVolume),yield this._localAudioTrack.update3A(n)),this._room.isJoined&&!E(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),E(s)||this._localAudioTrack.setMute(s),yield this._updateAudioPlayOption({playOption:o,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),$t(this._localAudioConfig,e)})}stopLocalAudio(){return p(this,null,function*(){!this._localAudioTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),pe(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)})}startLocalVideo(){return p(this,arguments,function*(e={publish:!0,view:null}){if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:t,publish:s=!0,mute:n,option:o}=e,a=new ae(this._room.videoManager),c={},d={};if(o&&(o.cameraId?c.deviceId=o.cameraId:E(o.useFrontCamera)?E(o.videoTrack)||(c.customSource=o.videoTrack):c.facingMode=o.useFrontCamera?h.FACING_MODE_USER:h.FACING_MODE_ENVIRONMENT,E(o.profile)||(Q(o.profile)?qe[o.profile]&&a.setProfile(qe[o.profile]):a.setProfile(o.profile)),E(o.fillMode)||(d.objectFit=o.fillMode),E(o.mirror)||(d.mirror=o.mirror),E(o.small)||(Is()?Q(o.small)?a.small=qe[o.small]:o.small===!0?a.small=qe["120p"]:a.small=o.small:this._log.warn("small stream is not supported"))),a.on("5",l=>{this.emit($.ERROR,new M({code:k.DEVICE_ERROR,extraCode:5308,messageParams:{error:l}}))}),a.on("2",l=>{this.emit($.DEVICE_CHANGED,{type:"camera",action:"active",device:l})}),a.on("4",l=>{let m;l.error&&(m=M.convertFrom(l.error)),this.emit($.PUBLISH_STATE_CHANGED,L(N({},l),{error:m}))}),this._listenOutputTrackChanged(a),yield a.capture(c),E(n)||(yield a.setMute(n)),a.mediaTrack)if(o!=null&&o.qosPreference){let l=Gi(o.qosPreference);a.mediaTrack.contentHint=l}else o!=null&&o.videoTrack||(a.mediaTrack.contentHint=Gi(Ze.QOS_PREFERENCE_SMOOTH));we(a,a).add("player-state-changed",l=>{this.emit($.VIDEO_PLAY_STATE_CHANGED,L(N({},l),{userId:"",streamType:"main"}))}),s&&this._room.isJoined&&this._room.publish(a).catch(()=>{}),this._localVideoTrack=a,this._localVideoConfig=L(N({},e),{view:t,publish:s}),yield this._updateVideoPlayOption({view:t,playOption:d,track:a})})}updateLocalVideo(e){return p(this,null,function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:s,mute:n,option:o}=e,a={};if(o){if(E(o.profile)||(Q(o.profile)?qe[o.profile]&&this._localVideoTrack.setProfile(qe[o.profile]):this._localVideoTrack.setProfile(o.profile),(!o.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(o.cameraId))&&E(o.useFrontCamera)&&this._localVideoTrack.applyProfile()),o.cameraId?yield this._localVideoTrack.switchDevice(o.cameraId):E(o.useFrontCamera)?E(o.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(o.videoTrack)):yield this._localVideoTrack.switchDevice(o.useFrontCamera?h.FACING_MODE_USER:h.FACING_MODE_ENVIRONMENT),E(o.fillMode)||(a.objectFit=o.fillMode),E(o.mirror)||(a.mirror=o.mirror),o.qosPreference&&this._localVideoTrack.mediaTrack){let c=Gi(o.qosPreference);this._localVideoTrack.mediaTrack.contentHint=c}if(o.small){let c=!this._localVideoTrack.small;Is()?(o.small===!0?this._localVideoTrack.small=qe["120p"]:Q(o.small)?this._localVideoTrack.small=qe[o.small]:this._localVideoTrack.small=o.small,this._room.videoManager.update(),c&&this._room.enableSmall(!0)):this._log.warn("small stream is not supported")}else o.small===!1&&this._localVideoTrack.small&&(delete this._localVideoTrack.small,this._room.videoManager.update(),this._room.enableSmall(!1))}this._room.isJoined&&!E(s)&&(s&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._localVideoConfig.publish&&!s&&this._room.unpublish(this._localVideoTrack).catch(()=>{})),E(n)||(yield this._localVideoTrack.setMute(n)),yield this._updateVideoPlayOption({view:t,playOption:a,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),$t(this._localVideoConfig,e)})}stopLocalVideo(){return p(this,null,function*(){!this._localVideoTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),pe(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return p(this,arguments,function*(e={publish:!0,view:null}){if(this._localScreenTrack){this._log.warn("screen share is already started");return}let{view:t=null,publish:s=!0,option:n}=e,o=new Ge(this._room.videoManager);o.on("4",m=>{let _;m.error&&(_=M.convertFrom(m.error)),this.emit($.PUBLISH_STATE_CHANGED,L(N({},m),{error:_}))}),this._listenOutputTrackChanged(o);let a=null,c={},d={};n&&(E(n.profile)||(Q(n.profile)?ln[n.profile]&&o.setProfile(ln[n.profile]):o.setProfile(n.profile)),n.systemAudio&&(c.systemAudio=!0,c.echoCancellation=n.echoCancellation,c.noiseSuppression=n.noiseSuppression,c.autoGainControl=n.autoGainControl),E(n.fillMode)||(d.objectFit=n.fillMode),n.videoTrack&&(c.videoTrack=n.videoTrack),n.audioTrack&&(c.audioTrack=n.audioTrack),n.captureElement&&(c.captureElement=n.captureElement),n.preferDisplaySurface&&(c.preferDisplaySurface=n.preferDisplaySurface));let l=yield o.capture(c);if(n!=null&&n.qosPreference){let m=Gi(n.qosPreference);o.mediaTrack.contentHint=m}else n!=null&&n.videoTrack||(o.mediaTrack.contentHint=Gi(Ze.QOS_PREFERENCE_CLEAR));if(o.mediaTrack.addEventListener(h.ENDED,()=>{this._stopScreenShare(),this.emit($.SCREEN_SHARE_STOPPED)}),l.getAudioTracks()[0]&&(a=new bt(this._room.audioManager),a.setInputMediaStreamTrack(l.getAudioTracks()[0]),this._speakerId&&a.setAudioOutput(this._speakerId)),we(o,o).add("player-state-changed",m=>{this.emit($.VIDEO_PLAY_STATE_CHANGED,L(N({},m),{userId:"",streamType:"sub"}))}),s&&this._room.isJoined){let m=[o];a&&m.push(a),this._room.publish(...m).catch(()=>{})}this._localScreenTrack=o,this._localScreenAudioTrack=a,this._localScreenConfig=L(N({},e),{view:t,publish:s}),yield this._updateVideoPlayOption({view:t,playOption:d,track:o})})}updateScreenShare(e){return p(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:s,option:n}=e,o={};if(n&&(E(n.fillMode)||(o.objectFit=n.fillMode),n.qosPreference)){let a=Gi(n.qosPreference);this._localScreenTrack.mediaTrack.contentHint=a}this._room.isJoined&&!E(s)&&(s&&!this._localScreenConfig.publish&&(this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch(()=>{})),this._localScreenConfig.publish&&!s&&(this._room.unpublish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.unpublish(this._localScreenAudioTrack).catch(()=>{}))),yield this._updateVideoPlayOption({view:t,playOption:o,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),$t(this._localScreenConfig,e)})}stopScreenShare(){return p(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return p(this,null,function*(){let{view:t,userId:s,streamType:n,option:o}=e,a=`${s}_${n}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${s}, streamType:${n}`);return}let c=this._room.remotePublishedUserMap.get(s);if(!c)return;let d={},l=n==="main"?c.remoteVideoTrack:c.remoteAuxiliaryTrack;this._listenOutputTrackChanged(l),o&&(E(o.fillMode)||(d.objectFit=o.fillMode),E(o.mirror)||(d.mirror=o.mirror),n==="main"&&!E(o.small)&&(c.remoteVideoTrack.setMediaType(o.small?8:4),this._room.changeType(o.small,l.user))),yield this._room.subscribe(l),yield this._updateVideoPlayOption({view:t,playOption:d,track:l}),this._emitTrackEvent(l),this._remoteVideoConfigMap.set(a,{config:e}),o&&!E(o.receiveWhenViewVisible)&&this._observeView({remoteTrack:l,view:t,receiveWhenViewVisible:o.receiveWhenViewVisible,viewRoot:o==null?void 0:o.viewRoot})})}updateRemoteVideo(e){return p(this,null,function*(){var x,ie;let{view:t,userId:s,streamType:n,option:o}=e,a=`${s}_${n}`,c=this._remoteVideoConfigMap.get(a);if(!c||!this._room.remotePublishedUserMap.has(s))return;let d={};o&&(E(o.fillMode)||(d.objectFit=o.fillMode),E(o.mirror)||(d.mirror=o.mirror));let l=null,m=this._room.remotePublishedUserMap.get(s);if(n==="main"&&(m==null?void 0:m.muteState.hasVideo)&&(l=m.remoteVideoTrack),n==="sub"&&(m==null?void 0:m.muteState.hasAuxiliary)&&(l=m.remoteAuxiliaryTrack),!l)return;let{config:_}=c;n==="main"&&o&&!E(o.small)&&this._room.changeType(o.small,l.user),yield this._updateVideoPlayOption({view:t,playOption:d,track:l,prevConfig:_}),$t(_,e);let g=E(o==null?void 0:o.receiveWhenViewVisible)?(x=_.option)==null?void 0:x.receiveWhenViewVisible:o.receiveWhenViewVisible,R=E(t)?_.view:t,y=E(o==null?void 0:o.viewRoot)?(ie=_.option)==null?void 0:ie.viewRoot:o.viewRoot;this._observeView({remoteTrack:l,view:R,receiveWhenViewVisible:g,viewRoot:y})})}stopRemoteVideo(e){return p(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,t=!0){return p(this,null,function*(){let s=[],n=this._room.remotePublishedUserMap.get(e.userId);if(n){let{muteState:a,remoteVideoTrack:c,remoteAuxiliaryTrack:d}=n;e.streamType==="main"&&(c.stop(),a.hasVideo&&s.push(c)),e.streamType==="sub"&&(d.stop(),a.hasAuxiliary&&s.push(d))}for(let a of s)t&&(yield this._room.unsubscribe(a),this._mediaTrackMap.get(a.outMediaTrack)===a.userId&&this._mediaTrackMap.delete(a.outMediaTrack));let o=this._remoteVideoConfigMap.get(`${e.userId}_${e.streamType}`);o&&o.observer&&o.observer.disconnect(),this._remoteVideoConfigMap.delete(`${e.userId}_${e.streamType}`)})}muteRemoteAudio(e,t){return p(this,null,function*(){if(e==="*")if(t)yield this._stopRemoteAudio({userId:e});else{let s=[...this._room.remotePublishedUserMap.values()];for(let n of s)n.muteState.hasAudio&&(yield this._startRemoteAudio({userId:n.userId}))}else t?yield this._stopRemoteAudio({userId:e}):yield this._startRemoteAudio({userId:e});this._remoteAudioMuteMap.set(e,t)})}setRemoteAudioVolume(e,t){if(e==="*"){let s=[...this._room.remotePublishedUserMap.values()];for(let n of s)this._updateAudioPlayOption({playOption:{volume:t},track:n.remoteAudioTrack})}else if(e){let s=this._room.remotePublishedUserMap.get(e);s&&this._updateAudioPlayOption({playOption:{volume:t},track:s.remoteAudioTrack})}}startPlugin(e,t){return p(this,null,function*(){return e.start(t)})}updatePlugin(e,t){return p(this,null,function*(){return e.update(t)})}stopPlugin(e,t){return p(this,null,function*(){return e.stop(t)})}enableAudioVolumeEvaluation(e=2e3,t=!1){this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,s){return this.listeners(e).includes(t)?this:(super.on(e,t,s),this._eventListened.add(e),this)}off(e,t,s){return e==="*"?(this._eventListened.clear(),this.removeAllListeners()):super.off(e,t,s),this}getAudioTrack(e={userId:"",streamType:"main"}){var n,o;let t,s="main";if(Q(e)?t=e:(t=e.userId,e.streamType&&(s=e.streamType)),t){let a=this._room.remotePublishedUserMap.get(t);if(a)return a.remoteAudioTrack.mediaTrack}else return s==="sub"?((n=this._localScreenAudioTrack)==null?void 0:n.mediaTrack)||null:((o=this._localAudioTrack)==null?void 0:o.mediaTrack)||null;return null}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:t="",streamType:s="main"}=e;if(t===""){if(s==="main"&&this._localVideoTrack)return this._localVideoTrack.mediaTrack;if(s==="sub"&&this._localScreenTrack)return this._localScreenTrack.mediaTrack}else{let n=this._room.remotePublishedUserMap.get(t);if(n)return s==="main"?n.remoteVideoTrack.mediaTrack:n.remoteAuxiliaryTrack.mediaTrack}return null}getVideoSnapshot(e={}){let{userId:t,streamType:s="main"}=e;if(t){let n=this._room.remotePublishedUserMap.get(t);if(s==="main"&&(n==null?void 0:n.muteState.hasVideo))return n.remoteVideoTrack.getVideoFrame();if(s==="sub"&&(n==null?void 0:n.muteState.hasAuxiliary))return n.remoteAuxiliaryTrack.getVideoFrame()}else{if(s==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(s==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}setCurrentSpeaker(e){var t,s;this._speakerId=e,(t=this._localAudioTrack)==null||t.setAudioOutput(e),(s=this._localScreenAudioTrack)==null||s.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(n=>n.remoteAudioTrack.setAudioOutput(e))}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return p(this,null,function*(){let{userId:t,option:s}=e;if(this._remoteAudioConfigMap.has(t)){this._log.warn(`remote audio has already started. userId:${t}`);return}let n=this._room.remotePublishedUserMap.get(t);if(!n)return;let o={};s&&(E(s.volume)||(o.volume=s.volume));let a=n.remoteAudioTrack;this._listenOutputTrackChanged(a),this._speakerId&&a.setAudioOutput(this._speakerId);try{this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(a),yield this._updateAudioPlayOption({playOption:o,track:a})}catch(c){throw this._remoteAudioConfigMap.delete(t),c}this._emitTrackEvent(a)})}_stopRemoteAudio(e,t=!0){return p(this,null,function*(){let s=this._room.remotePublishedUserMap.get(e.userId);s&&(s.remoteAudioTrack.stop(),s.muteState.hasAudio&&t&&(yield this._room.unsubscribe(s.remoteAudioTrack)),this._mediaTrackMap.get(s.remoteAudioTrack.outMediaTrack)===e.userId&&this._mediaTrackMap.delete(s.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete(`${e.userId}`)})}_updateVideoPlayOption(o){return p(this,arguments,function*({view:e,playOption:t,track:s,prevConfig:n}){if(s.setMirror(t.mirror),E(e)&&n&&n.view&&!ya(t)){let a=fs(n.view);a.length>0&&(yield s.play(a,t))}if(!E(e)){let a=fs(e);a.length>0?yield s.play(a,t):s.stop()}})}_updateAudioPlayOption(n){return p(this,arguments,function*({playOption:e={},track:t,prevConfig:s}){if(!t.isPlayCalled)try{yield t.play(null,e)}catch(o){}E(e.muted)||t.setPlayerMute(e.muted),E(e.volume)||t.setAudioVolume(e.volume/100)})}_listenOutputTrackChanged(e){e.listeners("output-media-track-changed").length===0&&e.on("output-media-track-changed",()=>this._emitTrackEvent(e))}_emitTrackEvent(e){let t=e.isRemote?e.userId:"";e.outMediaTrack&&this._mediaTrackMap.get(e.outMediaTrack)!==t&&(this._mediaTrackMap.set(e.outMediaTrack,t),this.emit($.TRACK,{userId:t,streamType:Us(e.streamType),track:e.outMediaTrack}))}_checkTrackToPublish(){var t,s,n;let e=[];if(((t=this._localAudioConfig)==null?void 0:t.publish)&&this._localAudioTrack&&e.push(this._localAudioTrack),((s=this._localVideoConfig)==null?void 0:s.publish)&&this._localVideoTrack&&e.push(this._localVideoTrack),(n=this._localScreenConfig)!=null&&n.publish&&(this._localScreenTrack&&e.push(this._localScreenTrack),this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack)),e.length!==0)return this._room.publish(...e).catch(()=>{})}_observeView({remoteTrack:e,view:t,receiveWhenViewVisible:s=!1,viewRoot:n}){if(E(t))return;let o=this._remoteVideoConfigMap.get(`${e.userId}_${Us(e.streamType)}`);if(!o)return;let a=o.observer||void 0;if(t===null||de(t)&&t.length===0||!s){a==null||a.disconnect(),e.isSubscribed||this._room.subscribe(e).catch(()=>{});return}let d=o.visibleViewMap||new Map,l=-1;(!a||a.root!==n)&&(a==null||a.disconnect(),d.clear(),a=new IntersectionObserver(_=>{_.forEach(g=>{d.set(g.target,g.isIntersecting)}),clearTimeout(l),l=window.setTimeout(()=>{[...d.values()].find(R=>R)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:n}));let m=new Set(fs(t));d.forEach((_,g)=>{m.has(g)||(a.unobserve(g),d.delete(g))}),m.forEach(_=>{d.set(_,!0),a.observe(_)}),a.takeRecords().forEach(_=>{d.set(_.target,_.isIntersecting)}),o.visibleViewMap=d,o.observer=a}_exitRoom(){return p(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(e=>{this._stopRemoteAudio({userId:e}).catch()}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let t=e.includes("main")?"main":"sub",s=e.split(`_${t}`)[0];s&&this._stopRemoteVideo({userId:s,streamType:t}).catch()}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._room.remotePublishedUserMap.forEach(e=>{pe(e.remoteAudioTrack),pe(e.remoteVideoTrack),pe(e.remoteAuxiliaryTrack)})})}_stopScreenShare(){return p(this,null,function*(){var e;if(!!this._localScreenTrack){if(this._room.isJoined){let t=[this._localScreenTrack];this._localScreenAudioTrack&&t.push(this._localScreenAudioTrack),yield(e=this._room)==null?void 0:e.unpublish(...t).catch(()=>{})}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),pe(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_initActiveSpeaker(){return p(this,null,function*(){if(Oe&&!Ir(Oe))this.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:Oe});else{let e=yield Ui();if(e[0]&&!Ir(e[0]))Oe=e[0],this.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]});else{let t=({track:s})=>{s.kind==="audio"&&(!Oe||Ir(Oe))&&(this._initActiveSpeaker(),T.off("102",this._initActiveSpeaker))};T.on("102",t)}}})}_onAudioAvailable({userId:e}){let t=this._remoteAudioMuteMap.has(e)?this._remoteAudioMuteMap.get(e):this._remoteAudioMuteMap.get("*");(t===!1||this._room.autoReceiveAudio&&!t)&&this._doStartRemoteAudio({userId:e}).catch(()=>{})}_onVideoAvailable({userId:e,streamType:t}){if(!this._room.autoReceiveVideo)return;let s=this._room.remotePublishedUserMap.get(e);if(s){let n=t==="main"?s.remoteVideoTrack:s.remoteAuxiliaryTrack;this._room.subscribe(n).then(()=>{this._emitTrackEvent(n)}).catch(()=>{})}}_onAudioUnavailable({userId:e,muteState:t}){t.hasAudio&&t.audioMuted||this._stopRemoteAudio({userId:e},!1).catch(()=>{})}_onVideoUnavailable({userId:e,streamType:t}){this._stopRemoteVideo({userId:e,streamType:t},!1).catch(()=>{})}sendSEIMessage(e,t){this._room.sendSEI(e,t||{seiPayloadType:243})}sendCustomMessage(e){var t,s;(s=(t=this._room).sendCustomMessage)==null||s.call(t,e)}static setLogLevel(e,t){A.setLogLevel(e),E(t)||(t?A.enableUploadLog():A.disableUploadLog())}static isSupported(){return Hn()}static getCameraList(){return He(!0)}static getMicrophoneList(){return Ve(!0)}static getSpeakerList(){return Ui(!0)}static setCurrentSpeaker(e){return p(this,null,function*(){(yield Ui()).forEach(s=>{s.deviceId===e&&(Wc.forEach(n=>{n.setCurrentSpeaker(e),n.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:s})}),Oe=s)})})}static _addKVStat({type:e,key:t,value:s,base:n,useUV:o,version:a}){switch(a&&(wi.version=a),e){case"count":wi.addCount({key:t,useUV:o});break;case"enum":wi.addEnum({key:t,value:s,useUV:o});break;case"number":wi.addNumber({key:t,value:s,split:n});break}}},K=Bs;u(K,"_loggerManager",A),u(K,"EVENT",$),u(K,"ERROR_CODE",k),u(K,"TYPE",Ze),u(K,"frameWorkType",30),b([ne({replaceArg:r=>({argIndex:0,value:{name:"plugin"in r?r.plugin.Name:r.Name,assetsPath:"assetsPath"in r?r==null?void 0:r.assetsPath:"default"}})})],K.prototype,"use",1),b([ve(Te.TRTC.enterRoom),Si("room",([r],[i])=>(r.roomId||r.strRoomId)===(i.roomId||i.strRoomId)&&r.userId===i.userId&&r.sdkAppId===i.sdkAppId),F(r=>function(i){return this._log.setUserId(i.userId),this._log.setSdkAppId(i.sdkAppId),r.call(this,i)}),ne()],K.prototype,"enterRoom",1),b([ne()],K.prototype,"exitRoom",1),b([ve(Te.TRTC.switchRole),Fi("room",{merge:(r,i)=>i}),ne()],K.prototype,"switchRole",1),b([ne()],K.prototype,"destroy",1),b([ve(Te.TRTC.startLocalAudio),Si("audio",([r],[i])=>{var e,t;return((e=r==null?void 0:r.option)==null?void 0:e.microphoneId)===((t=i==null?void 0:i.option)==null?void 0:t.microphoneId)}),ne()],K.prototype,"startLocalAudio",1),b([ve(Te.TRTC.updateLocalAudio),Fi("audio",{debounce:{delay:200,getKey:()=>`${ul}-localAudio`,isNeedToDebounce:r=>{var i;return!E((i=r.option)==null?void 0:i.captureVolume)}}}),ne()],K.prototype,"updateLocalAudio",1),b([Ii("audio"),ne()],K.prototype,"stopLocalAudio",1),b([ve(Te.TRTC.startLocalVideo),Si("video",([r],[i])=>{var e,t;return((e=r==null?void 0:r.option)==null?void 0:e.cameraId)===((t=i==null?void 0:i.option)==null?void 0:t.cameraId)}),ne()],K.prototype,"startLocalVideo",1),b([ve(Te.TRTC.updateLocalVideo),Fi("video"),ne()],K.prototype,"updateLocalVideo",1),b([Ii("video"),ne()],K.prototype,"stopLocalVideo",1),b([ve(Te.TRTC.startScreenShare),Si("screen",()=>!0),ne()],K.prototype,"startScreenShare",1),b([ve(Te.TRTC.updateScreenShare),Fi("screen"),ne()],K.prototype,"updateScreenShare",1),b([ne()],K.prototype,"stopScreenShare",1),b([ve(Te.TRTC.startRemoteVideo),Si(r=>`v${r.userId}${r.streamType}`,()=>!0),ne({getRemoteId:r=>`${r.userId}_${r.streamType}`})],K.prototype,"startRemoteVideo",1),b([ve(Te.TRTC.updateRemoteVideo),Fi(r=>`v${r.userId}${r.streamType}`),ne({getRemoteId:r=>`${r.userId}_${r.streamType}`})],K.prototype,"updateRemoteVideo",1),b([ve(Te.TRTC.stopRemoteVideo),F(r=>function(i){return p(this,null,function*(){if(i.userId==="*"){let e=[];return this._room.remotePublishedUserMap.forEach(t=>{this._remoteVideoConfigMap.has(`${t.userId}_${"main"}`)&&e.push(this.stopRemoteVideo({streamType:"main",userId:t.userId}).catch(()=>{})),this._remoteVideoConfigMap.has(`${t.userId}_${"sub"}`)&&e.push(this.stopRemoteVideo({streamType:"sub",userId:t.userId}).catch(()=>{}))}),Promise.all(e)}return r.call(this,i)})}),ne({getRemoteId:r=>`${r.userId}_${r.streamType}`})],K.prototype,"stopRemoteVideo",1),b([Ii(r=>`v${r.userId}${r.streamType}`)],K.prototype,"_stopRemoteVideo",1),b([ve(...Te.TRTC.muteRemoteAudio),ne({getRemoteId:r=>r})],K.prototype,"muteRemoteAudio",1),b([Fc(...Te.TRTC.setRemoteAudioVolume),ol(200,r=>r),ne({getRemoteId:r=>r})],K.prototype,"setRemoteAudioVolume",1),b([Ro("start"),Si((r,i)=>r.getAlias()+r.getGroup(i)),ne({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>Ka[r.getName()]})],K.prototype,"startPlugin",1),b([Ro("update"),Fi((r,i)=>r.getAlias()+r.getGroup(i)),ne({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>Xa[r.getName()]})],K.prototype,"updatePlugin",1),b([Ro("stop"),Ii((r,i)=>r.getAlias()+r.getGroup(i)),ne({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>Qa[r.getName()]})],K.prototype,"stopPlugin",1),b([Fc(...Te.TRTC.enableAudioVolumeEvaluation)],K.prototype,"enableAudioVolumeEvaluation",1),b([ne()],K.prototype,"getVideoSnapshot",1),b([ne()],K.prototype,"setCurrentSpeaker",1),b([Si(r=>`a${r.userId}`,()=>!0)],K.prototype,"_startRemoteAudio",1),b([F(r=>function(i){return p(this,null,function*(){return i.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(e=>this._stopRemoteAudio(L(N({},i),{userId:e.userId})).catch(()=>{}))):r.call(this,i)})}),Ii(r=>`a${r.userId}`)],K.prototype,"_stopRemoteAudio",1),b([Ii("room")],K.prototype,"_exitRoom",1),b([Ii("screen")],K.prototype,"_stopScreenShare",1),b([ve(...Te.TRTC.sendSEIMessage),Hc({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...r)=>r[0].byteLength})],K.prototype,"sendSEIMessage",1),b([ve(Te.TRTC.sendCustomMessage),Hc({timesInSecond:30,maxSizeInSecond:8e3,getSize:r=>r.data.byteLength})],K.prototype,"sendCustomMessage",1),b([ve(Te.TRTC.create)],K,"_create",1);var $s=K;var Jc=class{constructor(){this._set=new Set;T.on(f.LEAVE_SUCCESS,this.delete,this)}add({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,e||i.roomId,i.sdkAppId,i.useStringRoomId);this._set.add(t)}delete({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,i.roomId||e,i.sdkAppId,i.useStringRoomId);this._set.delete(t)}getKey(i,e,t,s){return`${t}_${e}_${i}_${s}`}isJoined({userId:i,roomId:e,sdkAppId:t,room:s}){return s.scene==="rtc"?!1:this._set.has(this.getKey(i,e,t,s.useStringRoomId))}};function Dp(){return p(this,null,function*(){let r,i;try{let m=yield Ve();r=m&&m.length}catch(m){}try{let m=yield He();i=m&&m.length}catch(m){}let e={microphone:r,camera:i},{isH264EncodeSupported:t,isVp8EncodeSupported:s,isH264DecodeSupported:n,isVp8DecodeSupported:o}=this.checkSystemResult.detail,a=Jt.basis(),c={webRTC:a.isWebRTCSupported,getUserMedia:a.isGetUserMediaSupported,webSocket:a.isWebSocketsSupported,screenShare:a.isScreenShareSupported,webAudio:a.isWebAudioSupported,h264Encode:t,h264Decode:n,vp8Encode:s,vp8Decode:o},d={browser:a.browser,os:a.os,trtc:c,devices:e},l={isWebCodecSupported:a.isWebCodecSupported,isMediaSessionSupported:a.isMediaSessionSupported,isWebTransportSupported:a.isWebTransportSupported};ee.uploadEvent({log:`trtcstats-${JSON.stringify(d)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(d)}`),ee.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(l)}`,userId:this.userId})})}function ml(){return F(r=>{let i=new Jc;return function(e,t,s){return p(this,null,function*(){let n=String(e.roomId||e.strRoomId);if(this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.userSig=e.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=t,e.privateMapKey=e.privateMapKey||"",this.isJoined)throw new C({code:I.INVALID_OPERATION,message:D({key:v.INVALID_JOIN})});if(this.checkDestroy(),i.isJoined({userId:this.userId,roomId:n,sdkAppId:this.sdkAppId,room:this}))throw new C({code:I.INVALID_OPERATION,message:D({key:v.REPEAT_JOIN,data:this.userId})});i.add({room:this,roomId:n}),this.role=e.role===21?"audience":"anchor",this._log.info(`Join() => joining room: ${n} useStringRoomId: ${this.useStringRoomId} scene: ${this.scene} role: ${this.role}`),T.emit(f.JOIN_START,{room:this,roomId:n,params:e}),this.checkSystemResult=yield Jt.checkSystemRequirementsInternal(),this.checkDestroy();let o=Me.getEnv();o||(o=Lt.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(hn.OLD_CLOUD_LADDER)?o=Lt.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(hn.WEBRTC)&&(o=Lt.WEBRTC))),ee.setConfig({env:o,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:n}),Dp.call(this);let{isH264EncodeSupported:a,isVp8EncodeSupported:c}=this.checkSystemResult.detail;if(!Jt.isWebRTCSupported()||!a&&!c)throw new C({code:I.NOT_SUPPORTED,message:D({key:v.NOT_SUPPORTED_WEBRTC})});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Me.getEnv()&&(yield this.schedule(n,s));let d=yield r.call(this,e,t,s);return this.roomId=n,this._joinedTimestamp=Me.performanceNow(),T.emit(f.JOIN_SUCCESS,{room:this}),ee.uploadEvent({log:`stat-conv-${Number(at)}-${location.hostname}`,userId:this.userId}),d}catch(d){throw i.delete({room:this,roomId:n}),T.emit(f.JOIN_FAILED,{room:this,error:d}),d}})}})}var pl=()=>F(r=>function(...i){return p(this,null,function*(){T.emit(f.LEAVE_START,{room:this}),yield r.call(this),T.emit(f.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function _l(){return F(r=>function(...i){let e=r.apply(this,i);return i.forEach(t=>!t.isSubscribed&&t.subscribe(e)),e})}var El=Ae(ke(),1);var fl=Symbol("instance"),hb=Symbol("abortCtrl"),jc=Symbol("cacheResult"),Ji=class{constructor(i,e,t){this.oldState=i,this.newState=e,this.action=t,this.aborted=!1}abort(i){this.aborted=!0,Gs.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},Hs=class extends Error{constructor(i,e,t){super(e),this.state=i,this.message=e,this.cause=t}};function Mp(r){return typeof r=="object"&&r&&"then"in r}var Fs=new Map;function qc(r,i,e={}){return(t,s,n)=>{let o=e.action||s;if(!e.context){let c=Fs.get(t)||[];Fs.has(t)||Fs.set(t,c),c.push({from:r,to:i,action:o})}let a=n.value;n.value=function(...c){let d=this;if(e.context&&(d=te.get(typeof e.context=="function"?e.context.call(this,...c):e.context)),d.state===i)return d[jc];d.state instanceof Ji&&d.state.action==e.abortAction&&d.state.abort(d);let l=null;if(Array.isArray(r)?r.length==0?d.state instanceof Ji&&d.state.abort(d):(typeof d.state!="string"||!r.includes(d.state))&&(l=new Hs(d._state,`${d.name} ${o} to ${i} failed: current state ${d._state} not in from config`)):r!==d.state&&(l=new Hs(d._state,`${d.name} ${o} to ${i} failed: current state ${d._state} not from ${r}`)),l)if(e.fail)e.fail.call(this,l);else{if(e.ignoreError)return l;throw l}let m=d.state,_=new Ji(m,i,o);Gs.call(d,_);let g=y=>{var x;return d[jc]=y,_.aborted||(Gs.call(d,i),(x=e.success)===null||x===void 0||x.call(this,d[jc])),y},R=y=>{let x=y instanceof Error?y.message:String(y);if(Gs.call(d,m,y),e.fail)e.fail.call(this,new Hs(d._state,`action '${o}' failed :${x}`,y instanceof Error?y:new Error(x)));else{if(e.ignoreError)return y;throw y}};try{let y=a.apply(this,c);return Mp(y)?y.then(g).catch(R):g(y)}catch(y){R(y)}}}}var kp=(()=>typeof window!="undefined"&&window.__AFSM__?(e,t)=>{window.dispatchEvent(new CustomEvent(e,{detail:t}))}:typeof importScripts!="undefined"?(e,t)=>{postMessage({type:e,payload:t})}:()=>{})();function Gs(r,i){let e=this._state;this._state=r;let t=r.toString();r&&this.emit(t,e),this.emit(te.STATECHANGED,r,e,i),this.updateDevTools({value:r,old:e,err:i instanceof Error?i.message:String(i)})}var te=class extends El.default{constructor(i,e,t){super(),this.name=i,this.groupName=e,this._state=te.INIT,i||(i=Date.now().toString(36)),t?Object.setPrototypeOf(this,t):t=Object.getPrototypeOf(this),e||(this.groupName=this.constructor.name);let s=t[fl];s?this.name=s.name+"-"+s.count++:t[fl]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let i=Object.getPrototypeOf(this),e=Fs.get(i)||[],t=new Set,s=[],n=[],o=new Set,a=Object.getPrototypeOf(i);Fs.has(a)&&(a.stateDiagram.forEach(d=>t.add(d)),a.allStates.forEach(d=>o.add(d))),e.forEach(({from:d,to:l,action:m})=>{typeof d=="string"?s.push({from:d,to:l,action:m}):d.length?d.forEach(_=>{s.push({from:_,to:l,action:m})}):n.push({to:l,action:m})}),s.forEach(({from:d,to:l,action:m})=>{o.add(d),o.add(l),o.add(m+"ing"),t.add(`${d} --> ${m}ing : ${m}`),t.add(`${m}ing --> ${l} : ${m} \u{1F7E2}`),t.add(`${m}ing --> ${d} : ${m} \u{1F534}`)}),n.forEach(({to:d,action:l})=>{t.add(`${l}ing --> ${d} : ${l} \u{1F7E2}`),o.forEach(m=>{m!==d&&t.add(`${m} --> ${l}ing : ${l}`)})});let c=[...t];return Object.defineProperties(i,{stateDiagram:{value:c},allStates:{value:o}}),c}static get(i){let e;return typeof i=="string"?(e=te.instances.get(i),e||te.instances.set(i,e=new te(i,void 0,Object.create(te.prototype)))):(e=te.instances2.get(i),e||te.instances2.set(i,e=new te(i.constructor.name,void 0,Object.create(te.prototype)))),e}static getState(i){var e;return(e=te.get(i))===null||e===void 0?void 0:e.state}updateDevTools(i={}){kp(te.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){Gs.call(this,i)}};te.STATECHANGED="stateChanged";te.UPDATEAFSM="updateAFSM";te.INIT="[*]";te.ON="on";te.OFF="off";te.instances=new Map;te.instances2=new WeakMap;var Tl=Ae(ke());var le={SETUP_SUCCESS:"1",SETUP_FAILED:"5",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",DISCONNECTED:"5",RECONNECT_FAILED:"4"};var ht={CLIENT_BANNED:9,CHANNEL_SETUP_RESULT:19,CHANNEL_RECONNECT_RESULT:514,JOIN_ROOM_RESULT:20,PEER_JOIN:4134,PEER_LEAVE:4135,STREAM_ADDED:16,STREAM_REMOVED:18,UPLINK_NETWORK_STATS:22,UPDATE_REMOTE_MUTE_STAT:23,PUBLISH_RESULT:4098,PUBLISH_STATE_CHANGE_RESULT:4112,UNPUBLISH_RESULT:4100,SUBSCRIBE_RESULT:4102,UNSUBSCRIBE_RESULT:4104,SUBSCRIBE_CHANGE_RESULT:4106,MUTE_RESULT:4108,UPDATE_OFFER_RESULT:4128,START_PUBLISH_TENCENT_CDN_RES:1286,STOP_PUBLISH_TENCENT_CDN_RES:1288,START_PUBLISH_GIVEN_CDN_RES:777,STOP_PUBLISH_GIVEN_CDN_RES:779,START_MIX_TRANSCODE_RES:781,STOP_MIX_TRANSCODE_RES:783,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772,REBUILD_PEER_CONNECTION_RES:4150,SPC_PUBLISH_RESULT:4146,SPC_SUBSCRIBE_RESULT:4156,ABILITY_STATUS_REPORT_RESULT:4158,SERVER_FIRST_PACKAGE_RECEIVED:5e3,RECEIVE_CUSTOM_MSG:4140},gl=[ht.UPDATE_REMOTE_MUTE_STAT,ht.UPLINK_NETWORK_STATS,ht.USER_LIST_RES,ht.MUTE_RESULT,ht.SERVER_FIRST_PACKAGE_RECEIVED,ht.RECEIVE_CUSTOM_MSG],P={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",USER_LIST_RES:"user-list-res",SWITCH_ROLE_RES:"switch_role_res",MUTE_RESULT:"mute-result",UPDATE_CONSTRAINT_CONFIG_RES:"update-contraint-config-res",REBUILD_PEER_CONNECTION_RES:"rebuild-pc-res",SPC_PUBLISH_RESULT:"spc-publish-result",SPC_SUBSCRIBE_RESULT:"spc-subscribe-result",ABILITY_STATUS_REPORT_RESULT:"ability-status-report",SERVER_FIRST_PACKAGE_RECEIVED:"first-pkg-received",RECEIVE_CUSTOM_MSG:"receive-custom-msg"},W={PUBLISH_CHANGE:"publish_change",JOIN_ROOM:"join",LEAVE_ROOM:"leave",ON_QUALITY_REPORT:"quality_report",UPDATE_MUTE_STAT:"mute_uplink",PUBLISH:"publish",PUBLISH_STATE_CHANGE:"publish_state_change",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",RECEIVE_DATA_USER_LIST:"receive_data_userlist",UNSUBSCRIBE:"unsubscribe",SUBSCRIBE_CHANGE:"subscribe_change",START_PUBLISH_TENCENT_CDN:"start_publishing",STOP_PUBLISH_TENCENT_CDN:"stop_publishing",START_PUBLISH_GIVEN_CDN:"start_push_user_cdn",STOP_PUBLISH_GIVEN_CDN:"stop_push_user_cdn",START_MIX_TRANSCODE:"start_mcu_mix",STOP_MIX_TRANSCODE:"stop_mcu_mix",GET_USER_LIST:"get_user_list",SWITCH_ROLE:"change_role",UPDATE_CONSTRAINT_CONFIG:"update_constraint_config",REBUILD_PEER_CONNECTION:"rebuild_pc",READY_TO_RECEIVE_DATA:"ready_to_receive",SPC_JOIN_ROOM:"join/v2",SPC_PUBLISH:"publish/v2",SPC_SUBSCRIBE:"subscribe/v3",ABILITY_STATUS_REPORT:"ability_status_report",RECONNECT_WS:"reconnect",SEND_CUSTOM_MSG:"channel_msg"};var ei=new WeakMap;function Ri({settings:r={retries:5,timeout:2e3},onError:i,onRetrying:e,onRetryFailed:t}){return function(s,n,o){let a=gt({retryFunction:o.value,settings:r,onError({error:c,retry:d,reject:l,retryFuncArgs:m}){i&&i.call(this,c,()=>{var _;(_=ei.get(s))!=null&&_.has(n)?d():l(c)},l,m)},onRetrying(c,d){var l;X(e)&&e.call(this,c,d),(l=ei.get(s))!=null&&l.has(n)&&(ei.get(s).get(n).stopRetry=d)},onRetryFailed:t});return o.value=function(...c){let d=ei.get(s);return d?d.set(n,{args:c}):ei.set(s,new Map([[n,{args:c}]])),a.apply(this,c).finally(()=>{var l;return(l=ei.get(s))==null?void 0:l.delete(n)})},o}}function Ws({fnName:r,callback:i,validateArgs:e=!0}){return function(t,s,n){let o=n.value;return n.value=function(...a){var c,d;if((c=ei.get(t))!=null&&c.has(r)){let{stopRetry:l,args:m}=ei.get(t).get(r),_=!0;if(e){for(let g of m)if(!a.find(R=>R===g)){_=!1;break}}_&&(i&&i.apply(this,a),l&&l(),(d=ei.get(t))==null||d.delete(r))}return o.apply(this,a)},n}}var No=new Set;function Sl(r){let i=[...No.values()].find(e=>e.room.userId===r&&!e.room.isJoined);return i||null}var kr=class extends Tl.default{constructor(e){var s,n;super();u(this,"room");u(this,"url");u(this,"backupUrl");u(this,"race");u(this,"destroyed",!1);u(this,"_socketInUse");u(this,"_socket");u(this,"_backupSocket");u(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0});u(this,"_currentState","DISCONNECTED");u(this,"_isReconnecting",!1);u(this,"_seq",0);u(this,"_log");u(this,"_lastMessageTime",-1);u(this,"_connnectStartTime",-1);u(this,"_stopConnectRetry");u(this,"bytesSent",0);u(this,"bytesReceived",0);u(this,"keepAlive",!1);this.room=e.room,this.race=E(e.race)?!0:e.race,(((n=(s=this.room.scheduleResult)==null?void 0:s.config)==null?void 0:n.keepAliveClient)||0)-No.size>0&&this.room.enableSPC&&(this.keepAlive=!0,No.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=A.createLogger({id:"ws",userId:this.userId,sdkAppId:this.sdkAppId}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get urlParam(){let e=`?sdkAppId=${encodeURIComponent(this.sdkAppId)}&userId=${encodeURIComponent(this.userId)}&userSig=${encodeURIComponent(this.userSig)}&keepAlive=${encodeURIComponent(Number(this.keepAlive))}`;return this.race?`${e}&race=1`:e}get _urlWithParam(){return`${this.url}${this.race?"/v2/ws":""}${this.urlParam}`}get _backupUrlWithParam(){return`${this.backupUrl}${this.race?"/v2/ws":""}${this.urlParam}`}get isConnected(){return this._currentState==="CONNECTED"}get isConnecting(){return this._currentState==="CONNECTING"}get sdkAppId(){return this.room.sdkAppId}get userId(){return this.room.userId}get userSig(){return this.room.userSig}get isOnline(){return this._currentState==="CONNECTED"&&Date.now()-this._lastMessageTime<12*1e3}connect(){return p(this,arguments,function*(e=10*1e3){if(this.isConnected)return Promise.resolve();this._log.info(`connect to [${this.url}, ${this.backupUrl}]${e?` timeout: ${e}`:""} keepAlive: ${Number(this.keepAlive)}`),this.emitConnectionStateChanged("CONNECTING"),this._connnectStartTime=B();let t=[this.connectWS({url:this._urlWithParam,isMain:!0,timeout:e})];this.race&&this._backupUrlWithParam!==this._urlWithParam&&t.push(this.connectWS({url:this._backupUrlWithParam,isMain:!1,timeout:e})),this._socketInUse=yield ls(t),this.unbindAndCloseSocket(this._socketInUse===this._socket?h.BACKUP:h.MAIN),this.emitConnectionStateChanged("CONNECTED")})}connectWS({url:e,timeout:t,isMain:s}){let n=new WebSocket(e);this.bindSocket(n),s?this._socket=n:this._backupSocket=n;let o=-1;return new Promise((a,c)=>{n.onclose=c,n.onerror=c,n.onopen=()=>a(n),t&&(o=setTimeout(()=>{this.unbindAndCloseSocket(s?h.MAIN:h.BACKUP),c(new C({code:I.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))},t))}).finally(()=>{n.onclose=null,n.onerror=null,n.onopen=null,clearTimeout(o)})}bindSocket(e){e.addEventListener("close",this.onclose),e.addEventListener("error",this.onerror),e.addEventListener("message",this.onmessage)}unbindSocket(e){e.removeEventListener("close",this.onclose),e.removeEventListener("error",this.onerror),e.removeEventListener("message",this.onmessage)}unbindAndCloseSocket(e){if(e===h.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(t){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(t){}this._backupSocket=null}}onclose(e){if(e.target===this._socketInUse&&(this._log.warn(`${e.target===this._socket?"main":"backup"} is closed code:${e.code} ${e.reason}`),this.emitConnectionStateChanged("DISCONNECTED"),!e.wasClean||e.code!==1e3)){this._socketInUse.onclose=null,this._socketInUse.close(4011);let t=this._socketInUse===this._socket;this.unbindAndCloseSocket(t?h.MAIN:h.BACKUP),this._socketInUse=null,this.reconnect()}}onerror(e){this._log.error(`${e.target===this._socket?"main":"backup"} error observed`),e.target===this._socketInUse&&(this.unbindAndCloseSocket(h.MAIN),this.unbindAndCloseSocket(h.BACKUP),this._socketInUse=null,this.reconnect())}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=Vn(e.data);let t=JSON.parse(e.data),{cmd:s,data:n}=t,o=Object.values(ht),c=Object.keys(ht)[o.indexOf(s)],d=P[c];switch(gl.includes(s)||(this._log.debug(`received ${s} msg: ${e.data}`),d&&this._log.info(`Received event: [ ${d} ]`)),s){case ht.CHANNEL_SETUP_RESULT:{if(t.code===0)this._signalInfo.clientIp=n.clientIp,this._signalInfo.signalIp=n.signalInnerIp,n.svrTime&&Cd(n.svrTime),this._log.info("ChannelSetup Success"),w.addSuccessEvent({key:521701,cost:B()-this._connnectStartTime}),this._connnectStartTime=-1,this.emit(le.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let l=new C({code:I.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:D({key:v.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error(`${t.code}, ${t.message}`),this.close(),w.addFailedEvent({key:521701,error:l}),this.emit(le.SETUP_FAILED,l)}break}case ht.JOIN_ROOM_RESULT:{t.code===0&&(this._signalInfo.relayIp=n.relayOuterIp,this._signalInfo.relayInnerIp=n.relayInnerIp,this._signalInfo.relayPort=n.relayPort,this._signalInfo.tinyId=t.tinyId,this._log.info(`signalIp:${this._signalInfo.signalIp} clientIp:${this._signalInfo.clientIp} relayIp: ${this._signalInfo.relayIp}`)),this.emit(d,{data:t});break}default:this.emit(d,{data:t});break}}reGetSignalChannelUrl(){return p(this,null,function*(){try{St(!0),yield this.room.schedule(this.room.roomId);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(e){}})}reconnect(){return p(this,null,function*(){if(!this._isReconnecting){if(!this.room.isJoined&&this.keepAlive){this.close();return}this._isReconnecting=!0;try{this._log.warn("reconnect"),yield this.connect();let{roomId:e,useStringRoomId:t}=this.room,{relayIp:s,relayInnerIp:n,relayPort:o}=this._signalInfo,{data:a}=yield this.sendWaitForResponse({command:W.RECONNECT_WS,data:{roomId:e,useStringRoomId:t,relayInnerIp:n,relayOuterIp:s,relayPort:o},responseCommand:P.CHANNEL_RECONNECT_RESULT});a.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),w.addSuccessEvent({key:521702,cost:B()-this._connnectStartTime}),this._connnectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(w.addFailedEvent({key:521702,error:a.code}),this._log.warn(`reconnect failed, ${a.code} ${a.message}`),this.room.reJoin())}catch(e){this._log.error(e),this.room.reJoin()}}})}send(e,t={}){if(this.isConnected&&!this.room.isLeft){let s={cmd:e,data:t,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},n=JSON.stringify(s);return this._socketInUse.send(n),this.bytesSent+=Vn(n),s.seq}}sendWaitForResponse({command:e,data:t,timeout:s=5e3,responseCommand:n,commandDesc:o,enableLog:a=!0}){return new Promise((c,d)=>{let l=setTimeout(()=>{this.off(n,m);let g=new C({code:I.API_CALL_TIMEOUT,message:D({key:v.API_CALL_TIMEOUT,data:{commandDesc:o,command:e}})});a&&this._log.warn(g),d(g)},s),m=g=>{g.data.seq===_&&(clearTimeout(l),this.off(n,m),c(g))};this.on(n,m);let _=this.send(e,t)})}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:s,retries:n=0,retryTimeout:o=0}=e;return gt({retryFunction:this.sendWaitForResponse,onError:({retry:a})=>{this.isOnline?a():(this._log.warn(`retry ${s} when connected`),this.once(le.CONNECTED,a))},onRetrying:a=>{this._log.warn(`${t||s} timeout observed, retrying [${a}/${n}]`)},settings:{retries:n,timeout:o},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),No.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(h.MAIN),this.unbindAndCloseSocket(h.BACKUP),this.emitConnectionStateChanged("DISCONNECTED")}destroy(){this.close(),this.destroyed=!0}stopKeepAliveIn(e=3600){if(this.keepAlive){this._log.info(`stopKeepAlive in ${e}s`);let t=setTimeout(()=>{this.keepAlive=!1,this._log.info(`close due to not used ${e}s`),this.close()},e*1e3),s=n=>{n instanceof Ji&&n.action==="join"&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(t),this.room.off(te.STATECHANGED,s))};this.room.on(te.STATECHANGED,s)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info(`${this._currentState} -> ${e}`),this.emit(le.CONNECTION_STATE_CHANGED,{prevState:this._currentState,state:e}),this._currentState=e,e==="CONNECTED"?this.emit(le.CONNECTED):e==="DISCONNECTED"&&this.emit(le.DISCONNECTED))}};b([Ri({settings:{retries:1/0,timeout:2e3},onError(r,i){!this.room.isDestroyed&&!this.destroyed&&i()},onRetrying(r,i){this._log.warn(`retrying to connect ${r}`),r>=3&&r%3===0&&this.reGetSignalChannelUrl(),i&&(this._stopConnectRetry=i,(this.room.isDestroyed||this.destroyed)&&i())}})],kr.prototype,"connect",1);var Il=Ae(ke());var Kc=0,Xc=!1,vo=new Set,xp=r=>Kc>2&&!Xc&&vo.size===0&&r,Qc=!1,We=class{constructor(i){u(this,"userId");u(this,"tinyId");u(this,"_sdpSemantics");u(this,"_isUplink");u(this,"_room");u(this,"_log");u(this,"_signalChannel");u(this,"_isErrorObserved",!1);u(this,"_waitForPeerConnectionConnectedPromise");u(this,"_waitForPeerConnectionConnectedPromiseReject",null);u(this,"_peerConnection",null);u(this,"_emitter",new Il.default);u(this,"_currentState","DISCONNECTED");u(this,"_isReconnecting",!1);u(this,"_reconnectionCount",0);u(this,"_reconnectionTimer",-1);u(this,"_isFirstConnection",!0);u(this,"_prevTime",-1);u(this,"_enableSEI");u(this,"_sei");u(this,"_localAddress");u(this,"_remoteAddress");this.userId=i.userId,this.tinyId=i.tinyId,this._room=i.room,this._sdpSemantics=i.room.sdpSemantics,this._isUplink=i.isUplink,this._log=A.createLogger({id:"n-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=i.signalChannel,this._enableSEI=i.enableSEI}beforeConnect(){this._prevTime<0&&(this._prevTime=B())}afterConnect(i){return p(this,null,function*(){try{yield i,this._isFirstConnection?(this._isFirstConnection=!1,w.addSuccessEvent({key:521705,cost:Math.min(B()-this._prevTime,30*1e3)})):this._isReconnecting&&w.addSuccessEvent({key:521706,cost:B()-this._prevTime}),this._prevTime=-1}catch(e){throw this._isFirstConnection?(this._isFirstConnection=!1,w.addFailedEvent({key:521705,error:e})):this._isReconnecting&&this._reconnectionCount>=3&&w.addFailedEvent({key:521706,error:e}),e}})}initialize(){let i={encodedInsertableStreams:this._enableSEI&&Ei,iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"};this._peerConnection=new RTCPeerConnection(i),this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this)}close(i){this._log.info("close connection"),this._emitter.emit("closed",i),this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this._sei&&(this._sei.destroy(),this._sei=null),vo.delete(this)}closePeerConnection(i=!1){this._peerConnection&&(this._log.info("close pc"),this._peerConnection.onconnectionstatechange=null,this._peerConnection.close(),this._peerConnection=null,i&&this.emitConnectionStateChangedEvent("DISCONNECTED")),this._waitForPeerConnectionConnectedPromiseReject&&this._waitForPeerConnectionConnectedPromiseReject(new C({code:I.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return it;let i=null;if(this._isUplink){if(!gr()||this._peerConnection.getSenders().length===0)return it;i=this._peerConnection.getSenders()[0].transport}else{if(!xi()||this._peerConnection.getReceivers().length===0)return it;i=this._peerConnection.getReceivers()[0].transport}return i?i.state:it}onConnectionStateChange(i){let e=this._peerConnection.iceConnectionState,t=this.getDTLSTransportState();if(this._log.info(`connectionState: ${i.target.connectionState}, ICE: ${e}, DTLS: ${t}`),i.target.connectionState===se.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),i.target.connectionState===se.FAILED||i.target.connectionState===se.CLOSED){let s=`connection ${i.target.connectionState}. ICE Transport state: ${e}, DTLS Transport state: ${t}`,n=new C({message:s,code:I.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",n)}(i.target.connectionState===se.CONNECTED||i.target.connectionState===se.COMPLETED)&&(this.logSelectedCandidate(),ee.logSuccessEvent({userId:this._room.userId,eventType:Le.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(i){return i===this._currentState?!1:(i==="CONNECTED"?(Kc=0,Xc=!1,Qc=!0,vo.add(this)):vo.delete(this),T.emit(f.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:i,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:i}),this._currentState=i,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}logSelectedCandidate(){return p(this,null,function*(){if(!this._peerConnection)return;let i=yield this._peerConnection.getStats();for(let[,e]of i)if(fi(e)){let t=i.get(e.localCandidateId),s=i.get(e.remoteCandidateId);t&&(this._log.info(`local candidate: ${t.candidateType} ${t.protocol}:${t.ip||t.address}:${t.port} ${t.networkType||""} ${t.candidateType==="relay"?`relayProtocol:${t.relayProtocol}`:""}`),this._localAddress=`${t.ip||t.address}:${t.port}`),s&&(this._log.info(`remote candidate: ${s.candidateType} ${s.protocol}:${s.ip||s.address}:${s.port}`),this._remoteAddress=`${s.protocol}:${s.ip||s.address}`);break}})}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise?this._waitForPeerConnectionConnectedPromise:(this._waitForPeerConnectionConnectedPromise=new Promise((i,e)=>{if(this._currentState==="CONNECTED")return i();this._waitForPeerConnectionConnectedPromiseReject=e;let t=a=>{a.state==="CONNECTED"&&(clearTimeout(o),n(),i())},s=({room:a})=>{a===this._room&&(clearTimeout(o),n(),e(new C({code:I.API_CALL_ABORTED,message:D({key:v.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{T.off(f.LEAVE_SUCCESS,s,this),this._emitter.off("connection-state-changed",t,this)},o=setTimeout(()=>{n();let a=new C({code:I.API_CALL_TIMEOUT,message:"connection timeout"});Kc+=1,xp(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),Xc=!0,this._emitter.emit("firewall-restriction")),e(a)},Kr);T.on(f.LEAVE_SUCCESS,s,this),this._emitter.on("connection-state-changed",t,this)}),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally(()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null}),this._waitForPeerConnectionConnectedPromise)}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(le.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=Pt()){this._log.warn(`SDK has tried reconnect for ${this._reconnectionCount} times, but all failed, please check your network`),this.stopReconnection();let i=new C({code:this._isUplink?I.UPLINK_RECONNECTION_FAILED:I.DOWNLINK_RECONNECTION_FAILED,message:D({key:this._isUplink?v.UPLINK_RECONNECTION_FAILED:v.DOWNLINK_RECONNECTION_FAILED})});return this.emitConnectionStateChangedEvent("DISCONNECTED"),this._emitter.emit("error",i),-1}return this._signalChannel.isConnected?(this._reconnectionCount+=1,this._log.warn(`reconnect() trying [${this._reconnectionCount}]`),1):(this._log.warn("reconnect() signal channel is not connected, suspend reconnection until signal is connected"),this._signalChannel.once(le.CONNECTED,this.reconnect,this),-1)}on(i,e,t){this._emitter.on(i,e,t)}off(i,e,t){this._emitter.off(i,e,t)}getIsReconnecting(){return this._isReconnecting}get isH264(){var i,e;return!!((e=(i=this._peerConnection)==null?void 0:i.remoteDescription)!=null&&e.sdp.includes("H264"))}};var ed=Ae(Zc());var ce=function(r){return ed.default.parse(r)},et=function(r){return ed.default.write(r)},Ol=function(r){let i=ce(r);return i.media.forEach(e=>{e.type===h.AUDIO&&e.fmtp.forEach(t=>{t.config+=";sprop-stereo=1;stereo=1"})}),et(i)};function Dl(r){let i=ce(r);return i.media.forEach(e=>{var t,s;if(e.type===h.VIDEO){let n=new Set;e.rtp.forEach(({payload:a,codec:c})=>c==="H264"&&n.add(a)),e.fmtp.forEach(({payload:a,config:c})=>{let d=c.match(/apt=(\d+)/);d&&d[1]&&n.has(Number(d[1]))&&n.add(a)});let o=({payload:a})=>!n.has(a);e.rtp=e.rtp.filter(o),e.rtcpFb=(t=e.rtcpFb)==null?void 0:t.filter(o),e.fmtp=e.fmtp.filter(o),e.payloads=(s=e.payloads)==null?void 0:s.split(" ").filter(a=>!n.has(Number(a))).join(" ")}}),et(i)}function Oo(r){return Object.keys(r).filter(i=>r[i])}var id=class extends We{constructor(e){super(L(N({},e),{isUplink:!1}));u(this,"_flag",0);u(this,"role","anchor");u(this,"remoteAudioTrack");u(this,"remoteVideoTrack");u(this,"remoteAuxiliaryTrack");u(this,"ssrc",{audio:0,video:0,auxiliary:0});u(this,"_isSDPExchanging",!1);this.flag=e.flag,this.remoteAudioTrack=e.remoteAudioTrack||new Qt(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new vt(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new Cr(this._room,this)}get subscribeState(){let e={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(this.remoteVideoTrack.mediaType&8?e.smallVideo=!0:e.video=!0),this.remoteAudioTrack.isSubscribed&&(e.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(e.auxiliary=!0),e}get muteState(){return _i(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,s,n;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(s=this.remoteVideoTrack)==null||s.onFlagChanged(),(n=this.remoteAuxiliaryTrack)==null||n.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===h.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var n,o;let t=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&t!==e&&((n=this.remoteVideoTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e}),(o=this.remoteAuxiliaryTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e})),s}onTrack(e){let t=e.streams[0],{track:s}=e,n=t.id===qr?h.MAIN:h.AUXILIARY;this._log.debug(`ontrack ${n} ${s.kind}`);let o=h.AUDIO;s.kind===h.VIDEO&&(o=n===h.MAIN?h.VIDEO:h.AUXILIARY);let a=this.remoteAudioTrack;o===h.VIDEO?a=this.remoteVideoTrack:o===h.AUXILIARY&&(a=this.remoteAuxiliaryTrack),a.setInputMediaStreamTrack(s)}addRRTRLine(e){let t=e.split(`\r
35
+ ${s.stack}`),!1}},r};var So=new WeakMap;function ol(r,i){return F((e,t)=>function(...s){var a,c;let n=(a=So.get(this))==null?void 0:a.get(i(...s));n&&n>0&&clearTimeout(n);let o=window.setTimeout(()=>{e.apply(this,s)},r);So.has(this)?(c=So.get(this))==null||c.set(i(...s),o):So.set(this,new Map([[i(...s),o]]))})}var al="5.6.2-beta.4";function ve(...r){return F((i,e)=>function(...t){try{Ao.call(this,r,t,e,this._name)}catch(s){return Promise.reject(s)}return i.apply(this,t)})}function Fc(...r){return F((i,e)=>function(...t){try{Ao.call(this,r,t,e,this._name)}catch(s){throw s}return i.apply(this,t)})}function Ao(r,i,e,t){if(de(r))for(let s=0;s<r.length;s++)Io.call(this,{rule:r[s],value:i[s],key:r[s].name,fnName:e,className:t});else Io.call(this,{rule:r,value:i[0],key:r.name,fnName:e,className:t})}function Io({rule:r,value:i,key:e,fnName:t,className:s}){function n(c){return{code:k.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:r,value:i}}}if(E(i)){if(r.required)throw new M(n(5001));if(E(r.defaultValue)){X(r.validate)&&r.validate.call(this,i,e,t,s,this);return}i=r.defaultValue}if(Array.isArray(r.type)){let c=!1;for(let d=0;d<r.type.length;d++)r.type[d]===null&&i===null&&(c=!0),X(r.type[d])&&i instanceof r.type[d]&&(c=!0),Q(r.type[d])&&he(i)===r.type[d].toLowerCase()&&(c=!0);if(!c)throw new M({code:k.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:r.type.map(d=>ps(d)?wn(d):Q(d)?d:he(d))},value:i}})}else if(!E(r.type)&&he(i)!==r.type)throw new M(n(5002));if(r.allowEmpty===!1){let c=re(i)&&(i===0||Number.isNaN(i)),d=Q(i)&&i.trim()==="";if(c||d)throw new M(n(5003))}if(r.notLessThanZero&&re(i)&&i<0)throw new M(n(5006));if(!E(r.min)&&re(i)&&i<r.min)throw new M(n(5007));if(!E(r.max)&&re(i)&&i>r.max)throw new M(n(5008));if(Q(r.instanceOf)){if(!i||i._name!==r.instanceOf)throw new M(n(5004))}else if(X(r.instanceOf)&&!(i instanceof r.instanceOf))throw new M(n(5004));if(Array.isArray(r.values)&&!r.values.includes(i))throw new M(n(5005));let{properties:o}=r;Be(o)&&ct(i)&&Object.keys(o).forEach(c=>{Io.call(this,{rule:o[c],value:i&&i[c],key:`${c}`,fnName:t,className:s})});let{arrayItem:a}=r;Be(a)&&de(i)&&i.forEach((c,d)=>{Io.call(this,{rule:a,value:c,key:`${e}[${d}]`,fnName:t,className:s})}),X(r.validate)&&r.validate.call(this,i,e,t,s,this)}function ne(r={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t}=r;return F((s,n)=>function(...o){function a(l,m,_){if(_&&_.includes(l))return"hided";if(e){let g=e(...o);if(o[g.argIndex]===m)return g.value}if(m===o||l in o)return m;try{return m instanceof HTMLElement?`id: ${m.id} type:${he(m)}`:(JSON.stringify(m),m)}catch(g){return`type:${he(m)}`}}let c=this._log||A;o.length>0?c.info(`${n}() ${JSON.stringify(o,(l,m)=>a(l,m,["userSig","privateMapKey"]))}`):c.info(`${n}()`);let d=t?t(...o):qa[n];try{let l=s.apply(this,o),m=B();return ms(l)?l.then(_=>(c.info(`${n}() success ${i.call(this,...o)}`),w.addSuccessEvent({key:d,cost:B()-m}),_)).catch(_=>{throw _=M.convertFrom.call(this,_,n,o.length===1?o[0]:o),c.error(`${n}() failed ${i.call(this,...o)} ${_} params: ${JSON.stringify(o,a)}`),w.addFailedEvent({key:d,error:_}),_}):(w.addSuccessEvent({key:d}),l)}catch(l){throw l=M.convertFrom.call(this,l,n),c.error(`${n}() failed ${l} params: ${JSON.stringify(o,a)}`),w.addFailedEvent({key:d,error:l}),l}})}var Ro=r=>F((i,e)=>function(t,s){return p(this,null,function*(){let n=this._plugins.get(t);if(!n)throw this._log.error(`plugin ${String(t)} is not found`),new M({code:k.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});return Ao.call(this,n.getValidateRule(r),[s],e,"TRTC"),i.call(this,n,s)})});var Co=0,Gc=class{constructor(i,e){u(this,"player");u(this,"publisher");u(this,"mixInput");this.mixInput=new Sr(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),i.loop&&(this.loop=i.loop),i.volume&&(this.volume=i.volume),this.mixInput.connect()}reset(){this.seek(0),this.mixInput.connect()}seek(i){!this.player||i<0&&i>this.player.duration||(this.player.currentTime=i,this.publisher.currentTime=i)}play(){var i,e;return(i=this.publisher)==null||i.play(),(e=this.player)==null?void 0:e.play()}pause(){var i,e;(i=this.player)==null||i.pause(),(e=this.publisher)==null||e.pause()}stop(){var i;(i=this.player)==null||i.pause(),this.mixInput.disconnect()}setOperation(i){i==="pause"&&this.pause(),i==="resume"&&(this.pause(),this.play()),i==="stop"&&(this.pause(),this.seek(0))}set volume(i){!this.player||!this.publisher||(this.player.volume=i,this.publisher.volume=i)}set loop(i){!this.player||!this.publisher||(this.player.loop=i,this.publisher.loop=i)}},Dr=class{constructor(i){this.core=i;u(this,"log");u(this,"mixedMusicMap",new Map);u(this,"cacheMusicMap",new Map);Co=Co+1,this.log=i.log.createChild({id:`${this.getAlias()}${Co}`}),this.log.info(`[audioMixer] created id=${this.getAlias()}${Co}`),this.core=i}getName(){return Dr.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return Dr.startValidateRule;case"update":return Dr.updateValidateRule;case"stop":return Dr.stopValidateRule}}start(i){return p(this,null,function*(){let{room:e}=this.core;this.log.info(`add music source, id: ${i.id} url: ${i.url}, track: ${i.track}`);let{id:t,url:s}=i;if(this.mixedMusicMap.has(t))return;let n=this.cacheMusicMap.get(t);n?i.url?n.reset():(n.mixInput.replaceSource(i.track),n.mixInput.connect()):(n=new Gc(i,e.audioManager),this.cacheMusicMap.set(t,n)),yield n.play(),this.mixedMusicMap.set(t,n),this.log.info(`start mix audio track ${t} success.`),w.addEnum({key:502700,value:3})})}update(i){return p(this,null,function*(){let{id:e,volume:t,loop:s,operation:n,seekFrom:o}=i;this.log.info(`update music source, ${JSON.stringify(i)}`);let a=this.mixedMusicMap.get(e);if(!a){this.log.warn(`update music source failed, music id: ${e} not found.`);return}E(t)||(a.volume=t),E(s)||(a.loop=s),E(n)||a.setOperation(n),E(o)||a.seek(o)})}stop(e){return p(this,arguments,function*({id:i}){var t;this.mixedMusicMap.has(i)&&(this.log.info(`remove music source, music id: ${i}`),(t=this.mixedMusicMap.get(i))==null||t.stop(),this.mixedMusicMap.delete(i)),i==="*"&&this.destroyAllMusic()})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((i,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()}},Ai=Dr;u(Ai,"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 s=i.url.split("?")[0],n=["mp3","ogg","wav","flac"],o=s.split(".").pop(),a=n.indexOf(o)>=0,c=s.startsWith("blob"),d=s.startsWith("data");if(!(a||c||d))throw new M({code:k.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new M({code:k.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t})}}),u(Ai,"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"]}}}),u(Ai,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),u(Ai,"Name","AudioMixer");var cl=r=>(r=Number(r),r>0&&r<14e8);var yo=0,Mr=class{constructor(i){this.core=i;u(this,"log");u(this,"workletReady");u(this,"audioContext",$e("denoiser"));u(this,"workletNode");yo=yo+1,this.log=i.log.createChild({id:`${this.getAlias()}${yo}`}),this.log.info(`[audioDenoiser] created id=${this.getAlias()}${yo}`),i.assetsPath&&(this.workletReady=gi(this.audioContext,`${i.assetsPath}/denoiser-wasm.js`),this.workletReady.catch(e=>{this.log.error(`Init assets from ${i.assetsPath} failed! Reason: ${e}`)}))}static startValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,t,s,n){if(!i.room.audioManager.hasAudioTrack)throw new M({code:k.INVALID_OPERATION,extraCode:5106,fnName:s})}}}getName(){return Mr.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(i){switch(i){case"start":return Mr.startValidateRule(this.core);case"update":return Mr.updateValidateRule;case"stop":return Mr.stopValidateRule}}start(i){return p(this,null,function*(){let{room:e}=this.core;if(this.workletReady||(this.workletReady=gi(this.audioContext,`${i.assetsPath}/denoiser-wasm.js`),this.workletReady.catch(t=>{this.log.error(`Init assets from ${i.assetsPath} failed! Reason: ${t}`)})),!this.workletNode){let t=String(Date.now()).slice(0,-3),{auth:s,sign:n,status:o,message:a}=yield vp(L(N({},i),{timestamp:t}));if(!s)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${s}. Message: ${a}`),new M({code:k.INVALID_PARAMETER,message:a});yield this.workletReady,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:t,sign:n,status:o}}),this.workletNode.port.onmessage=c=>{let{data:d}=c;d.type==="cost"&&this.log.debug(`[RTCAIDenoiser] ${d.value}`)}}this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(){return p(this,null,function*(){})}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)})}destroy(){}},Wi=Mr;u(Wi,"updateValidateRule",{type:"object"}),u(Wi,"stopValidateRule",{type:"object"}),u(Wi,"Name","AIDenoiser");var dl={MAIN:"schedule.cloud-rtc.com",MAIN_OVERSEA:"schedule.rtc.tencentcloud.com"};function bp(r){let i;return cl(r)?i=dl.MAIN_OVERSEA:i=dl.MAIN,i}function vp(s){return p(this,arguments,function*({sdkAppId:r,userId:i,userSig:e,timestamp:t}){let o=`https://${bp(r)}/api/v1/audioAiAuth?sdkAppId=${r}&userId=${i}&userSig=${e}&timestamp=${t}`,a=yield fetch(o),{data:{errCode:c,errMsg:d,sign:l,status:m}}=yield a.json();if(m==="1")return{auth:!0,sign:l,status:m,message:d};let _="Init RTCAIDenoiser failed.",g="";switch(c){case 1:g="Please check your params.";break;case 2:g="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:g="Server is invalid. Please contact our engineer. ";break;case 4:g="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:g="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:g="Your version is not supported.";break}return{auth:!1,status:m,message:d?`${_} Reason: ${d}. ${g}`:`${_}, ${g}`}})}var ul=0,Wc=new Set,Oe=null;jo(al);var Op={RtcError:M,ErrorCode:k,ErrorCodeDictionary:Ot},Bs=class extends hl.EventEmitter{constructor(e,t){super();u(this,"_room");u(this,"_eventListened",new Set);u(this,"_localVideoTrack",null);u(this,"_localAudioTrack",null);u(this,"_localScreenTrack",null);u(this,"_localScreenAudioTrack",null);u(this,"_localVideoConfig",null);u(this,"_localScreenConfig",null);u(this,"_localAudioConfig",null);u(this,"_remoteVideoConfigMap",new Map);u(this,"_remoteAudioConfigMap",new Map);u(this,"_remoteAudioMuteMap",new Map);u(this,"_mediaTrackMap",new WeakMap);u(this,"_log",A.createLogger({id:`t${++ul}`}));u(this,"_plugins",new Map);u(this,"_networkQuality",null);u(this,"_speakerId");this._room=new e(N({logger:this._log,frameWorkType:Bs.frameWorkType},t)),this._log.debug(JSON.stringify(t)),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(s){return this._room.audioManager.dump(s)}}}),t.plugins&&t.plugins.forEach(s=>{this._use(s,t.assetsPath)}),this._use(Ai,t.assetsPath),this._use(Wi,t.assetsPath),this._room.on("audio-volume",s=>{!s.find(n=>n.userId==="")&&this._localAudioTrack&&s.push({userId:"",volume:Math.floor(this._localAudioTrack.getAudioLevel()*100)}),this.emit($.AUDIO_VOLUME,{result:s.sort((n,o)=>o.volume-n.volume)})}),this._room.videoManager.on("error",({reason:s,error:n})=>{this._log.error(new M({code:k.OPERATION_FAILED,extraCode:5504,messageParams:{reason:s,error:n}}))}),this._listenEvents(),this._initActiveSpeaker(),nl(this,"trtc")}static create(e){}static _create(e,t){Ku();let s=new Bs(e,t||{});return Wc.add(s),s}_listenEvents(){we(this,this._room).add("peer-join",e=>{let{userId:t}=e;this.emit($.REMOTE_USER_ENTER,{userId:t})}).add("peer-leave",e=>{this.emit($.REMOTE_USER_EXIT,{userId:e})}).add("banned",e=>{this._exitRoom().then(()=>{this.emit($.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().then(()=>{this.emit($.ERROR,M.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit($.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e,this.emit($.NETWORK_QUALITY,e)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(s=>{we(s,s).add("player-state-changed",n=>{let o=L(N({},n),{userId:e.userId});s.kind===h.VIDEO&&(o.streamType=Us(s.streamType)),this.emit(s.kind===h.AUDIO?$.AUDIO_PLAY_STATE_CHANGED:$.VIDEO_PLAY_STATE_CHANGED,o)}).add("error",n=>{n.getCode()===I.PLAY_NOT_ALLOWED&&this.emit($.AUTOPLAY_FAILED,{userId:s.userId})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(s=>{pe(s)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:t})=>{let{userId:s}=t,n=e.audioAvailable,o=e.videoAvailable,{audioAvailable:a,videoAvailable:c}=t;a||this._remoteAudioConfigMap.delete(s),c||this._remoteVideoConfigMap.delete(`${s}_${"main"}`),t.hasAuxiliary||this._remoteVideoConfigMap.delete(`${s}_${"sub"}`),n!==a&&(this.emit(a?$.REMOTE_AUDIO_AVAILABLE:$.REMOTE_AUDIO_UNAVAILABLE,{userId:s}),a?this._onAudioAvailable({userId:s}):this._onAudioUnavailable({userId:s,muteState:t})),o!==c&&(this.emit(c?$.REMOTE_VIDEO_AVAILABLE:$.REMOTE_VIDEO_UNAVAILABLE,{userId:s,streamType:"main"}),c?this._onVideoAvailable({userId:s,streamType:"main"}):this._onVideoUnavailable({userId:s,streamType:"main"})),e.hasAuxiliary!==t.hasAuxiliary&&(this.emit(t.hasAuxiliary?$.REMOTE_VIDEO_AVAILABLE:$.REMOTE_VIDEO_UNAVAILABLE,{userId:s,streamType:"sub"}),t.hasAuxiliary?this._onVideoAvailable({userId:s,streamType:"sub"}):this._onVideoUnavailable({userId:s,streamType:"sub"}))}).add("firewall-restriction",()=>{this.emit($.ERROR,new M({code:k.OPERATION_FAILED,extraCode:5501}))}).add("sei-message",e=>{this.emit($.SEI_MESSAGE,L(N({},e),{streamType:Us(e.streamType)}))}).add("heartbeat-report",e=>{var n,o,a,c,d,l,m;let t={2:"big",3:"small",7:"sub"},s={rtt:e.msg_up_stream_info.msg_network_status.uint32_rtt||((n=e.msg_down_stream_info[0])==null?void 0:n.msg_network_status.uint32_rtt)||((o=this._networkQuality)==null?void 0:o.uplinkRTT)||((a=this._networkQuality)==null?void 0:a.downlinkRTT)||0,upLoss:((c=this._networkQuality)==null?void 0:c.uplinkLoss)||0,downLoss:((d=this._networkQuality)==null?void 0:d.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((l=e.msg_up_stream_info.msg_audio_status)==null?void 0:l.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((m=e.msg_up_stream_info.msg_audio_status)==null?void 0:m.uint32_audio_level)||0)/st},video:e.msg_up_stream_info.msg_video_status.filter(_=>t[_.uint32_video_stream_type]).map(_=>({bitrate:(_.uint32_video_codec_bitrate||0)/1e3,width:_.uint32_video_width,height:_.uint32_video_height,frameRate:_.uint32_video_enc_fps,videoType:t[_.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(_=>({userId:_.msg_user_info.str_identifier,audio:{bitrate:(_.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(_.msg_audio_status.uint32_audio_level||0)/st},video:_.msg_video_status.map(g=>({bitrate:(g.uint32_video_codec_bitrate||0)/1e3,width:g.uint32_video_width,height:g.uint32_video_height,frameRate:g.uint32_video_dec_fps,videoType:t[g.uint32_video_stream_type]}))}))};this.emit($.STATISTICS,s)}).add("custom-message",e=>{this.emit($.CUSTOM_MESSAGE,e)}),we(this,_e).add("audioInputAdded",e=>{this.emit($.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit($.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit($.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit($.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>p(this,null,function*(){if(this.emit($.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Oe&&Oe.deviceId===Xr){let t=(yield Ui()).find(s=>s.deviceId===Xr);t&&Oe.groupId!==t.groupId&&(Oe=t,this.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}})).add("audioOutputRemoved",e=>p(this,null,function*(){this.emit($.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield Ui())[0];t&&Oe&&(Oe.deviceId===e.deviceId||Oe.deviceId===Xr&&Oe.groupId!==t.groupId)&&(Oe=t,this.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}))}use(e){let t,s;"plugin"in e?(t=e.plugin,s=e.assetsPath):t=e,this._use(t,s||"https://web.sdk.qcloud.com/trtc/webrtc/v5/assets/")}_use(e,t){if(this._plugins.get(e.Name)){this._log.warn("duplicate install plugin",e.Name);return}let n=new e(sl(this._room,Op,t));this._plugins.set(e.Name,n)}enterRoom(e){return p(this,null,function*(){var c,d;let{scene:t="rtc",enableAutoPlayDialog:s=!0,autoReceiveAudio:n=!0,autoReceiveVideo:o=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!Q(e.proxy)&&e.proxy.turnServer&&((d=(c=this._room).setTurnServer)==null||d.call(c,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=s,this._room.autoReceiveAudio=n,this._room.autoReceiveVideo=o,ue(e.enableHWEncoder)&&(this._room.enableHWEncoder=e.enableHWEncoder);let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,role:e.role==="audience"?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(a,t,Bs.frameWorkType),this._checkTrackToPublish()})}exitRoom(){return p(this,null,function*(){return yield this._exitRoom()})}switchRole(e,t){return p(this,null,function*(){t!=null&&t.privateMapKey&&(this._room.privateMapKey=t.privateMapKey),yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){pe(this),this.removeAllListeners(),this._room.destroy(),Wc.delete(this),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),this._plugins.forEach(e=>{var t;return(t=e.destroy)==null?void 0:t.call(e)})}startLocalAudio(){return p(this,arguments,function*(e={publish:!0}){if(this._localAudioTrack){this._log.warn("local audio is already started");return}let{publish:t=!0,mute:s,option:n}=e,o=new Ne(this._room.audioManager),a={},c={muted:!0};n&&(E(n.microphoneId)?E(n.audioTrack)||(a.customSource=n.audioTrack):a.deviceId=n.microphoneId,n&&re(n.captureVolume)&&o.setCaptureVolume(n.captureVolume),E(n.profile)||(Q(n.profile)?un[n.profile]&&o.setProfile(un[n.profile]):o.setProfile(n.profile)),re(n.earMonitorVolume)&&(c.muted=!(n.earMonitorVolume>0),c.volume=n.earMonitorVolume),E(n.echoCancellation)||(o.profile.echoCancellation=n.echoCancellation),E(n.noiseSuppression)||(o.profile.noiseSuppression=n.noiseSuppression),E(n.autoGainControl)||(o.profile.autoGainControl=n.autoGainControl)),o.on("5",d=>{this.emit($.ERROR,new M({code:k.DEVICE_ERROR,extraCode:5309,messageParams:{error:d}}))}),o.on("2",d=>{this.emit($.DEVICE_CHANGED,{type:"microphone",action:"active",device:d})}),o.on("4",d=>{let l;d.error&&(l=M.convertFrom(d.error)),this.emit($.PUBLISH_STATE_CHANGED,L(N({},d),{error:l}))}),this._listenOutputTrackChanged(o),this._speakerId&&o.setAudioOutput(this._speakerId),yield o.capture(a),E(s)||o.setMute(s),we(o,o).add("player-state-changed",d=>{this.emit($.AUDIO_PLAY_STATE_CHANGED,L(N({},d),{userId:""}))}),t&&this._room.isJoined&&this._room.publish(o).catch(()=>{}),this._localAudioTrack=o,this._localAudioConfig=L(N({},e),{publish:t}),yield this._updateAudioPlayOption({playOption:c,track:o})})}updateLocalAudio(e){return p(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:s,option:n}=e,o={};n&&(n.microphoneId?yield this._localAudioTrack.switchDevice(n.microphoneId):E(n.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(n.audioTrack)),E(n.captureVolume)||this._localAudioTrack.setCaptureVolume(n.captureVolume),E(n.earMonitorVolume)||(o.muted=!(n.earMonitorVolume>0),o.volume=n.earMonitorVolume),yield this._localAudioTrack.update3A(n)),this._room.isJoined&&!E(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),E(s)||this._localAudioTrack.setMute(s),yield this._updateAudioPlayOption({playOption:o,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),$t(this._localAudioConfig,e)})}stopLocalAudio(){return p(this,null,function*(){!this._localAudioTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),pe(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)})}startLocalVideo(){return p(this,arguments,function*(e={publish:!0,view:null}){if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:t,publish:s=!0,mute:n,option:o}=e,a=new ae(this._room.videoManager),c={},d={};if(o&&(o.cameraId?c.deviceId=o.cameraId:E(o.useFrontCamera)?E(o.videoTrack)||(c.customSource=o.videoTrack):c.facingMode=o.useFrontCamera?h.FACING_MODE_USER:h.FACING_MODE_ENVIRONMENT,E(o.profile)||(Q(o.profile)?qe[o.profile]&&a.setProfile(qe[o.profile]):a.setProfile(o.profile)),E(o.fillMode)||(d.objectFit=o.fillMode),E(o.mirror)||(d.mirror=o.mirror),E(o.small)||(Is()?Q(o.small)?a.small=qe[o.small]:o.small===!0?a.small=qe["120p"]:a.small=o.small:this._log.warn("small stream is not supported"))),a.on("5",l=>{this.emit($.ERROR,new M({code:k.DEVICE_ERROR,extraCode:5308,messageParams:{error:l}}))}),a.on("2",l=>{this.emit($.DEVICE_CHANGED,{type:"camera",action:"active",device:l})}),a.on("4",l=>{let m;l.error&&(m=M.convertFrom(l.error)),this.emit($.PUBLISH_STATE_CHANGED,L(N({},l),{error:m}))}),this._listenOutputTrackChanged(a),yield a.capture(c),E(n)||(yield a.setMute(n)),a.mediaTrack)if(o!=null&&o.qosPreference){let l=Gi(o.qosPreference);a.mediaTrack.contentHint=l}else o!=null&&o.videoTrack||(a.mediaTrack.contentHint=Gi(Ze.QOS_PREFERENCE_SMOOTH));we(a,a).add("player-state-changed",l=>{this.emit($.VIDEO_PLAY_STATE_CHANGED,L(N({},l),{userId:"",streamType:"main"}))}),s&&this._room.isJoined&&this._room.publish(a).catch(()=>{}),this._localVideoTrack=a,this._localVideoConfig=L(N({},e),{view:t,publish:s}),yield this._updateVideoPlayOption({view:t,playOption:d,track:a})})}updateLocalVideo(e){return p(this,null,function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:s,mute:n,option:o}=e,a={};if(o){if(E(o.profile)||(Q(o.profile)?qe[o.profile]&&this._localVideoTrack.setProfile(qe[o.profile]):this._localVideoTrack.setProfile(o.profile),(!o.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(o.cameraId))&&E(o.useFrontCamera)&&this._localVideoTrack.applyProfile()),o.cameraId?yield this._localVideoTrack.switchDevice(o.cameraId):E(o.useFrontCamera)?E(o.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(o.videoTrack)):yield this._localVideoTrack.switchDevice(o.useFrontCamera?h.FACING_MODE_USER:h.FACING_MODE_ENVIRONMENT),E(o.fillMode)||(a.objectFit=o.fillMode),E(o.mirror)||(a.mirror=o.mirror),o.qosPreference&&this._localVideoTrack.mediaTrack){let c=Gi(o.qosPreference);this._localVideoTrack.mediaTrack.contentHint=c}if(o.small){let c=!this._localVideoTrack.small;Is()?(o.small===!0?this._localVideoTrack.small=qe["120p"]:Q(o.small)?this._localVideoTrack.small=qe[o.small]:this._localVideoTrack.small=o.small,this._room.videoManager.update(),c&&this._room.enableSmall(!0)):this._log.warn("small stream is not supported")}else o.small===!1&&this._localVideoTrack.small&&(delete this._localVideoTrack.small,this._room.videoManager.update(),this._room.enableSmall(!1))}this._room.isJoined&&!E(s)&&(s&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._localVideoConfig.publish&&!s&&this._room.unpublish(this._localVideoTrack).catch(()=>{})),E(n)||(yield this._localVideoTrack.setMute(n)),yield this._updateVideoPlayOption({view:t,playOption:a,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),$t(this._localVideoConfig,e)})}stopLocalVideo(){return p(this,null,function*(){!this._localVideoTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),pe(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return p(this,arguments,function*(e={publish:!0,view:null}){if(this._localScreenTrack){this._log.warn("screen share is already started");return}let{view:t=null,publish:s=!0,option:n}=e,o=new Ge(this._room.videoManager);o.on("4",m=>{let _;m.error&&(_=M.convertFrom(m.error)),this.emit($.PUBLISH_STATE_CHANGED,L(N({},m),{error:_}))}),this._listenOutputTrackChanged(o);let a=null,c={},d={};n&&(E(n.profile)||(Q(n.profile)?ln[n.profile]&&o.setProfile(ln[n.profile]):o.setProfile(n.profile)),n.systemAudio&&(c.systemAudio=!0,c.echoCancellation=n.echoCancellation,c.noiseSuppression=n.noiseSuppression,c.autoGainControl=n.autoGainControl),E(n.fillMode)||(d.objectFit=n.fillMode),n.videoTrack&&(c.videoTrack=n.videoTrack),n.audioTrack&&(c.audioTrack=n.audioTrack),n.captureElement&&(c.captureElement=n.captureElement),n.preferDisplaySurface&&(c.preferDisplaySurface=n.preferDisplaySurface));let l=yield o.capture(c);if(n!=null&&n.qosPreference){let m=Gi(n.qosPreference);o.mediaTrack.contentHint=m}else n!=null&&n.videoTrack||(o.mediaTrack.contentHint=Gi(Ze.QOS_PREFERENCE_CLEAR));if(o.mediaTrack.addEventListener(h.ENDED,()=>{this._stopScreenShare(),this.emit($.SCREEN_SHARE_STOPPED)}),l.getAudioTracks()[0]&&(a=new bt(this._room.audioManager),a.setInputMediaStreamTrack(l.getAudioTracks()[0]),this._speakerId&&a.setAudioOutput(this._speakerId)),we(o,o).add("player-state-changed",m=>{this.emit($.VIDEO_PLAY_STATE_CHANGED,L(N({},m),{userId:"",streamType:"sub"}))}),s&&this._room.isJoined){let m=[o];a&&m.push(a),this._room.publish(...m).catch(()=>{})}this._localScreenTrack=o,this._localScreenAudioTrack=a,this._localScreenConfig=L(N({},e),{view:t,publish:s}),yield this._updateVideoPlayOption({view:t,playOption:d,track:o})})}updateScreenShare(e){return p(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:s,option:n}=e,o={};if(n&&(E(n.fillMode)||(o.objectFit=n.fillMode),n.qosPreference)){let a=Gi(n.qosPreference);this._localScreenTrack.mediaTrack.contentHint=a}this._room.isJoined&&!E(s)&&(s&&!this._localScreenConfig.publish&&(this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch(()=>{})),this._localScreenConfig.publish&&!s&&(this._room.unpublish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.unpublish(this._localScreenAudioTrack).catch(()=>{}))),yield this._updateVideoPlayOption({view:t,playOption:o,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),$t(this._localScreenConfig,e)})}stopScreenShare(){return p(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return p(this,null,function*(){let{view:t,userId:s,streamType:n,option:o}=e,a=`${s}_${n}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${s}, streamType:${n}`);return}let c=this._room.remotePublishedUserMap.get(s);if(!c)return;let d={},l=n==="main"?c.remoteVideoTrack:c.remoteAuxiliaryTrack;this._listenOutputTrackChanged(l),o&&(E(o.fillMode)||(d.objectFit=o.fillMode),E(o.mirror)||(d.mirror=o.mirror),n==="main"&&!E(o.small)&&(c.remoteVideoTrack.setMediaType(o.small?8:4),this._room.changeType(o.small,l.user))),yield this._room.subscribe(l),yield this._updateVideoPlayOption({view:t,playOption:d,track:l}),this._emitTrackEvent(l),this._remoteVideoConfigMap.set(a,{config:e}),o&&!E(o.receiveWhenViewVisible)&&this._observeView({remoteTrack:l,view:t,receiveWhenViewVisible:o.receiveWhenViewVisible,viewRoot:o==null?void 0:o.viewRoot})})}updateRemoteVideo(e){return p(this,null,function*(){var x,ie;let{view:t,userId:s,streamType:n,option:o}=e,a=`${s}_${n}`,c=this._remoteVideoConfigMap.get(a);if(!c||!this._room.remotePublishedUserMap.has(s))return;let d={};o&&(E(o.fillMode)||(d.objectFit=o.fillMode),E(o.mirror)||(d.mirror=o.mirror));let l=null,m=this._room.remotePublishedUserMap.get(s);if(n==="main"&&(m==null?void 0:m.muteState.hasVideo)&&(l=m.remoteVideoTrack),n==="sub"&&(m==null?void 0:m.muteState.hasAuxiliary)&&(l=m.remoteAuxiliaryTrack),!l)return;let{config:_}=c;n==="main"&&o&&!E(o.small)&&this._room.changeType(o.small,l.user),yield this._updateVideoPlayOption({view:t,playOption:d,track:l,prevConfig:_}),$t(_,e);let g=E(o==null?void 0:o.receiveWhenViewVisible)?(x=_.option)==null?void 0:x.receiveWhenViewVisible:o.receiveWhenViewVisible,R=E(t)?_.view:t,y=E(o==null?void 0:o.viewRoot)?(ie=_.option)==null?void 0:ie.viewRoot:o.viewRoot;this._observeView({remoteTrack:l,view:R,receiveWhenViewVisible:g,viewRoot:y})})}stopRemoteVideo(e){return p(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,t=!0){return p(this,null,function*(){let s=[],n=this._room.remotePublishedUserMap.get(e.userId);if(n){let{muteState:a,remoteVideoTrack:c,remoteAuxiliaryTrack:d}=n;e.streamType==="main"&&(c.stop(),a.hasVideo&&s.push(c)),e.streamType==="sub"&&(d.stop(),a.hasAuxiliary&&s.push(d))}for(let a of s)t&&(yield this._room.unsubscribe(a),this._mediaTrackMap.get(a.outMediaTrack)===a.userId&&this._mediaTrackMap.delete(a.outMediaTrack));let o=this._remoteVideoConfigMap.get(`${e.userId}_${e.streamType}`);o&&o.observer&&o.observer.disconnect(),this._remoteVideoConfigMap.delete(`${e.userId}_${e.streamType}`)})}muteRemoteAudio(e,t){return p(this,null,function*(){if(e==="*")if(t)yield this._stopRemoteAudio({userId:e});else{let s=[...this._room.remotePublishedUserMap.values()];for(let n of s)n.muteState.hasAudio&&(yield this._startRemoteAudio({userId:n.userId}))}else t?yield this._stopRemoteAudio({userId:e}):yield this._startRemoteAudio({userId:e});this._remoteAudioMuteMap.set(e,t)})}setRemoteAudioVolume(e,t){if(e==="*"){let s=[...this._room.remotePublishedUserMap.values()];for(let n of s)this._updateAudioPlayOption({playOption:{volume:t},track:n.remoteAudioTrack})}else if(e){let s=this._room.remotePublishedUserMap.get(e);s&&this._updateAudioPlayOption({playOption:{volume:t},track:s.remoteAudioTrack})}}startPlugin(e,t){return p(this,null,function*(){return e.start(t)})}updatePlugin(e,t){return p(this,null,function*(){return e.update(t)})}stopPlugin(e,t){return p(this,null,function*(){return e.stop(t)})}enableAudioVolumeEvaluation(e=2e3,t=!1){this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,s){return this.listeners(e).includes(t)?this:(super.on(e,t,s),this._eventListened.add(e),this)}off(e,t,s){return e==="*"?(this._eventListened.clear(),this.removeAllListeners()):super.off(e,t,s),this}getAudioTrack(e={userId:"",streamType:"main"}){var n,o;let t,s="main";if(Q(e)?t=e:(t=e.userId,e.streamType&&(s=e.streamType)),t){let a=this._room.remotePublishedUserMap.get(t);if(a)return a.remoteAudioTrack.mediaTrack}else return s==="sub"?((n=this._localScreenAudioTrack)==null?void 0:n.mediaTrack)||null:((o=this._localAudioTrack)==null?void 0:o.mediaTrack)||null;return null}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:t="",streamType:s="main"}=e;if(t===""){if(s==="main"&&this._localVideoTrack)return this._localVideoTrack.mediaTrack;if(s==="sub"&&this._localScreenTrack)return this._localScreenTrack.mediaTrack}else{let n=this._room.remotePublishedUserMap.get(t);if(n)return s==="main"?n.remoteVideoTrack.mediaTrack:n.remoteAuxiliaryTrack.mediaTrack}return null}getVideoSnapshot(e={}){let{userId:t,streamType:s="main"}=e;if(t){let n=this._room.remotePublishedUserMap.get(t);if(s==="main"&&(n==null?void 0:n.muteState.hasVideo))return n.remoteVideoTrack.getVideoFrame();if(s==="sub"&&(n==null?void 0:n.muteState.hasAuxiliary))return n.remoteAuxiliaryTrack.getVideoFrame()}else{if(s==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(s==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}setCurrentSpeaker(e){var t,s;this._speakerId=e,(t=this._localAudioTrack)==null||t.setAudioOutput(e),(s=this._localScreenAudioTrack)==null||s.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(n=>n.remoteAudioTrack.setAudioOutput(e))}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return p(this,null,function*(){let{userId:t,option:s}=e;if(this._remoteAudioConfigMap.has(t)){this._log.warn(`remote audio has already started. userId:${t}`);return}let n=this._room.remotePublishedUserMap.get(t);if(!n)return;let o={};s&&(E(s.volume)||(o.volume=s.volume));let a=n.remoteAudioTrack;this._listenOutputTrackChanged(a),this._speakerId&&a.setAudioOutput(this._speakerId);try{this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(a),yield this._updateAudioPlayOption({playOption:o,track:a})}catch(c){throw this._remoteAudioConfigMap.delete(t),c}this._emitTrackEvent(a)})}_stopRemoteAudio(e,t=!0){return p(this,null,function*(){let s=this._room.remotePublishedUserMap.get(e.userId);s&&(s.remoteAudioTrack.stop(),s.muteState.hasAudio&&t&&(yield this._room.unsubscribe(s.remoteAudioTrack)),this._mediaTrackMap.get(s.remoteAudioTrack.outMediaTrack)===e.userId&&this._mediaTrackMap.delete(s.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete(`${e.userId}`)})}_updateVideoPlayOption(o){return p(this,arguments,function*({view:e,playOption:t,track:s,prevConfig:n}){if(s.setMirror(t.mirror),E(e)&&n&&n.view&&!ya(t)){let a=fs(n.view);a.length>0&&(yield s.play(a,t))}if(!E(e)){let a=fs(e);a.length>0?yield s.play(a,t):s.stop()}})}_updateAudioPlayOption(n){return p(this,arguments,function*({playOption:e={},track:t,prevConfig:s}){if(!t.isPlayCalled)try{yield t.play(null,e)}catch(o){}E(e.muted)||t.setPlayerMute(e.muted),E(e.volume)||t.setAudioVolume(e.volume/100)})}_listenOutputTrackChanged(e){e.listeners("output-media-track-changed").length===0&&e.on("output-media-track-changed",()=>this._emitTrackEvent(e))}_emitTrackEvent(e){let t=e.isRemote?e.userId:"";e.outMediaTrack&&this._mediaTrackMap.get(e.outMediaTrack)!==t&&(this._mediaTrackMap.set(e.outMediaTrack,t),this.emit($.TRACK,{userId:t,streamType:Us(e.streamType),track:e.outMediaTrack}))}_checkTrackToPublish(){var t,s,n;let e=[];if(((t=this._localAudioConfig)==null?void 0:t.publish)&&this._localAudioTrack&&e.push(this._localAudioTrack),((s=this._localVideoConfig)==null?void 0:s.publish)&&this._localVideoTrack&&e.push(this._localVideoTrack),(n=this._localScreenConfig)!=null&&n.publish&&(this._localScreenTrack&&e.push(this._localScreenTrack),this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack)),e.length!==0)return this._room.publish(...e).catch(()=>{})}_observeView({remoteTrack:e,view:t,receiveWhenViewVisible:s=!1,viewRoot:n}){if(E(t))return;let o=this._remoteVideoConfigMap.get(`${e.userId}_${Us(e.streamType)}`);if(!o)return;let a=o.observer||void 0;if(t===null||de(t)&&t.length===0||!s){a==null||a.disconnect(),e.isSubscribed||this._room.subscribe(e).catch(()=>{});return}let d=o.visibleViewMap||new Map,l=-1;(!a||a.root!==n)&&(a==null||a.disconnect(),d.clear(),a=new IntersectionObserver(_=>{_.forEach(g=>{d.set(g.target,g.isIntersecting)}),clearTimeout(l),l=window.setTimeout(()=>{[...d.values()].find(R=>R)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:n}));let m=new Set(fs(t));d.forEach((_,g)=>{m.has(g)||(a.unobserve(g),d.delete(g))}),m.forEach(_=>{d.set(_,!0),a.observe(_)}),a.takeRecords().forEach(_=>{d.set(_.target,_.isIntersecting)}),o.visibleViewMap=d,o.observer=a}_exitRoom(){return p(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(e=>{this._stopRemoteAudio({userId:e}).catch()}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let t=e.includes("main")?"main":"sub",s=e.split(`_${t}`)[0];s&&this._stopRemoteVideo({userId:s,streamType:t}).catch()}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._room.remotePublishedUserMap.forEach(e=>{pe(e.remoteAudioTrack),pe(e.remoteVideoTrack),pe(e.remoteAuxiliaryTrack)})})}_stopScreenShare(){return p(this,null,function*(){var e;if(!!this._localScreenTrack){if(this._room.isJoined){let t=[this._localScreenTrack];this._localScreenAudioTrack&&t.push(this._localScreenAudioTrack),yield(e=this._room)==null?void 0:e.unpublish(...t).catch(()=>{})}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),pe(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_initActiveSpeaker(){return p(this,null,function*(){if(Oe&&!Ir(Oe))this.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:Oe});else{let e=yield Ui();if(e[0]&&!Ir(e[0]))Oe=e[0],this.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]});else{let t=({track:s})=>{s.kind==="audio"&&(!Oe||Ir(Oe))&&(this._initActiveSpeaker(),T.off("102",this._initActiveSpeaker))};T.on("102",t)}}})}_onAudioAvailable({userId:e}){let t=this._remoteAudioMuteMap.has(e)?this._remoteAudioMuteMap.get(e):this._remoteAudioMuteMap.get("*");(t===!1||this._room.autoReceiveAudio&&!t)&&this._doStartRemoteAudio({userId:e}).catch(()=>{})}_onVideoAvailable({userId:e,streamType:t}){if(!this._room.autoReceiveVideo)return;let s=this._room.remotePublishedUserMap.get(e);if(s){let n=t==="main"?s.remoteVideoTrack:s.remoteAuxiliaryTrack;this._room.subscribe(n).then(()=>{this._emitTrackEvent(n)}).catch(()=>{})}}_onAudioUnavailable({userId:e,muteState:t}){t.hasAudio&&t.audioMuted||this._stopRemoteAudio({userId:e},!1).catch(()=>{})}_onVideoUnavailable({userId:e,streamType:t}){this._stopRemoteVideo({userId:e,streamType:t},!1).catch(()=>{})}sendSEIMessage(e,t){this._room.sendSEI(e,t||{seiPayloadType:243})}sendCustomMessage(e){var t,s;(s=(t=this._room).sendCustomMessage)==null||s.call(t,e)}static setLogLevel(e,t){A.setLogLevel(e),E(t)||(t?A.enableUploadLog():A.disableUploadLog())}static isSupported(){return Hn()}static getCameraList(){return He(!0)}static getMicrophoneList(){return Ve(!0)}static getSpeakerList(){return Ui(!0)}static setCurrentSpeaker(e){return p(this,null,function*(){(yield Ui()).forEach(s=>{s.deviceId===e&&(Wc.forEach(n=>{n.setCurrentSpeaker(e),n.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:s})}),Oe=s)})})}static _addKVStat({type:e,key:t,value:s,base:n,useUV:o,version:a}){switch(a&&(wi.version=a),e){case"count":wi.addCount({key:t,useUV:o});break;case"enum":wi.addEnum({key:t,value:s,useUV:o});break;case"number":wi.addNumber({key:t,value:s,split:n});break}}},K=Bs;u(K,"_loggerManager",A),u(K,"EVENT",$),u(K,"ERROR_CODE",k),u(K,"TYPE",Ze),u(K,"frameWorkType",30),b([ne({replaceArg:r=>({argIndex:0,value:{name:"plugin"in r?r.plugin.Name:r.Name,assetsPath:"assetsPath"in r?r==null?void 0:r.assetsPath:"default"}})})],K.prototype,"use",1),b([ve(Te.TRTC.enterRoom),Si("room",([r],[i])=>(r.roomId||r.strRoomId)===(i.roomId||i.strRoomId)&&r.userId===i.userId&&r.sdkAppId===i.sdkAppId),F(r=>function(i){return this._log.setUserId(i.userId),this._log.setSdkAppId(i.sdkAppId),r.call(this,i)}),ne()],K.prototype,"enterRoom",1),b([ne()],K.prototype,"exitRoom",1),b([ve(Te.TRTC.switchRole),Fi("room",{merge:(r,i)=>i}),ne()],K.prototype,"switchRole",1),b([ne()],K.prototype,"destroy",1),b([ve(Te.TRTC.startLocalAudio),Si("audio",([r],[i])=>{var e,t;return((e=r==null?void 0:r.option)==null?void 0:e.microphoneId)===((t=i==null?void 0:i.option)==null?void 0:t.microphoneId)}),ne()],K.prototype,"startLocalAudio",1),b([ve(Te.TRTC.updateLocalAudio),Fi("audio",{debounce:{delay:200,getKey:()=>`${ul}-localAudio`,isNeedToDebounce:r=>{var i;return!E((i=r.option)==null?void 0:i.captureVolume)}}}),ne()],K.prototype,"updateLocalAudio",1),b([Ii("audio"),ne()],K.prototype,"stopLocalAudio",1),b([ve(Te.TRTC.startLocalVideo),Si("video",([r],[i])=>{var e,t;return((e=r==null?void 0:r.option)==null?void 0:e.cameraId)===((t=i==null?void 0:i.option)==null?void 0:t.cameraId)}),ne()],K.prototype,"startLocalVideo",1),b([ve(Te.TRTC.updateLocalVideo),Fi("video"),ne()],K.prototype,"updateLocalVideo",1),b([Ii("video"),ne()],K.prototype,"stopLocalVideo",1),b([ve(Te.TRTC.startScreenShare),Si("screen",()=>!0),ne()],K.prototype,"startScreenShare",1),b([ve(Te.TRTC.updateScreenShare),Fi("screen"),ne()],K.prototype,"updateScreenShare",1),b([ne()],K.prototype,"stopScreenShare",1),b([ve(Te.TRTC.startRemoteVideo),Si(r=>`v${r.userId}${r.streamType}`,()=>!0),ne({getRemoteId:r=>`${r.userId}_${r.streamType}`})],K.prototype,"startRemoteVideo",1),b([ve(Te.TRTC.updateRemoteVideo),Fi(r=>`v${r.userId}${r.streamType}`),ne({getRemoteId:r=>`${r.userId}_${r.streamType}`})],K.prototype,"updateRemoteVideo",1),b([ve(Te.TRTC.stopRemoteVideo),F(r=>function(i){return p(this,null,function*(){if(i.userId==="*"){let e=[];return this._room.remotePublishedUserMap.forEach(t=>{this._remoteVideoConfigMap.has(`${t.userId}_${"main"}`)&&e.push(this.stopRemoteVideo({streamType:"main",userId:t.userId}).catch(()=>{})),this._remoteVideoConfigMap.has(`${t.userId}_${"sub"}`)&&e.push(this.stopRemoteVideo({streamType:"sub",userId:t.userId}).catch(()=>{}))}),Promise.all(e)}return r.call(this,i)})}),ne({getRemoteId:r=>`${r.userId}_${r.streamType}`})],K.prototype,"stopRemoteVideo",1),b([Ii(r=>`v${r.userId}${r.streamType}`)],K.prototype,"_stopRemoteVideo",1),b([ve(...Te.TRTC.muteRemoteAudio),ne({getRemoteId:r=>r})],K.prototype,"muteRemoteAudio",1),b([Fc(...Te.TRTC.setRemoteAudioVolume),ol(200,r=>r),ne({getRemoteId:r=>r})],K.prototype,"setRemoteAudioVolume",1),b([Ro("start"),Si((r,i)=>r.getAlias()+r.getGroup(i)),ne({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>Ka[r.getName()]})],K.prototype,"startPlugin",1),b([Ro("update"),Fi((r,i)=>r.getAlias()+r.getGroup(i)),ne({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>Xa[r.getName()]})],K.prototype,"updatePlugin",1),b([Ro("stop"),Ii((r,i)=>r.getAlias()+r.getGroup(i)),ne({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>Qa[r.getName()]})],K.prototype,"stopPlugin",1),b([Fc(...Te.TRTC.enableAudioVolumeEvaluation)],K.prototype,"enableAudioVolumeEvaluation",1),b([ne()],K.prototype,"getVideoSnapshot",1),b([ne()],K.prototype,"setCurrentSpeaker",1),b([Si(r=>`a${r.userId}`,()=>!0)],K.prototype,"_startRemoteAudio",1),b([F(r=>function(i){return p(this,null,function*(){return i.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(e=>this._stopRemoteAudio(L(N({},i),{userId:e.userId})).catch(()=>{}))):r.call(this,i)})}),Ii(r=>`a${r.userId}`)],K.prototype,"_stopRemoteAudio",1),b([Ii("room")],K.prototype,"_exitRoom",1),b([Ii("screen")],K.prototype,"_stopScreenShare",1),b([ve(...Te.TRTC.sendSEIMessage),Hc({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...r)=>r[0].byteLength})],K.prototype,"sendSEIMessage",1),b([ve(Te.TRTC.sendCustomMessage),Hc({timesInSecond:30,maxSizeInSecond:8e3,getSize:r=>r.data.byteLength})],K.prototype,"sendCustomMessage",1),b([ve(Te.TRTC.create)],K,"_create",1);var $s=K;var Jc=class{constructor(){this._set=new Set;T.on(f.LEAVE_SUCCESS,this.delete,this)}add({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,e||i.roomId,i.sdkAppId,i.useStringRoomId);this._set.add(t)}delete({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,i.roomId||e,i.sdkAppId,i.useStringRoomId);this._set.delete(t)}getKey(i,e,t,s){return`${t}_${e}_${i}_${s}`}isJoined({userId:i,roomId:e,sdkAppId:t,room:s}){return s.scene==="rtc"?!1:this._set.has(this.getKey(i,e,t,s.useStringRoomId))}};function Dp(){return p(this,null,function*(){let r,i;try{let m=yield Ve();r=m&&m.length}catch(m){}try{let m=yield He();i=m&&m.length}catch(m){}let e={microphone:r,camera:i},{isH264EncodeSupported:t,isVp8EncodeSupported:s,isH264DecodeSupported:n,isVp8DecodeSupported:o}=this.checkSystemResult.detail,a=Jt.basis(),c={webRTC:a.isWebRTCSupported,getUserMedia:a.isGetUserMediaSupported,webSocket:a.isWebSocketsSupported,screenShare:a.isScreenShareSupported,webAudio:a.isWebAudioSupported,h264Encode:t,h264Decode:n,vp8Encode:s,vp8Decode:o},d={browser:a.browser,os:a.os,trtc:c,devices:e},l={isWebCodecSupported:a.isWebCodecSupported,isMediaSessionSupported:a.isMediaSessionSupported,isWebTransportSupported:a.isWebTransportSupported};ee.uploadEvent({log:`trtcstats-${JSON.stringify(d)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(d)}`),ee.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(l)}`,userId:this.userId})})}function ml(){return F(r=>{let i=new Jc;return function(e,t,s){return p(this,null,function*(){let n=String(e.roomId||e.strRoomId);if(this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.userSig=e.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=t,e.privateMapKey=e.privateMapKey||"",this.isJoined)throw new C({code:I.INVALID_OPERATION,message:D({key:v.INVALID_JOIN})});if(this.checkDestroy(),i.isJoined({userId:this.userId,roomId:n,sdkAppId:this.sdkAppId,room:this}))throw new C({code:I.INVALID_OPERATION,message:D({key:v.REPEAT_JOIN,data:this.userId})});i.add({room:this,roomId:n}),this.role=e.role===21?"audience":"anchor",this._log.info(`Join() => joining room: ${n} useStringRoomId: ${this.useStringRoomId} scene: ${this.scene} role: ${this.role}`),T.emit(f.JOIN_START,{room:this,roomId:n,params:e}),this.checkSystemResult=yield Jt.checkSystemRequirementsInternal(),this.checkDestroy();let o=Me.getEnv();o||(o=Lt.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(hn.OLD_CLOUD_LADDER)?o=Lt.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(hn.WEBRTC)&&(o=Lt.WEBRTC))),ee.setConfig({env:o,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:n}),Dp.call(this);let{isH264EncodeSupported:a,isVp8EncodeSupported:c}=this.checkSystemResult.detail;if(!Jt.isWebRTCSupported()||!a&&!c)throw new C({code:I.NOT_SUPPORTED,message:D({key:v.NOT_SUPPORTED_WEBRTC})});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Me.getEnv()&&(yield this.schedule(n,s));let d=yield r.call(this,e,t,s);return this.roomId=n,this._joinedTimestamp=Me.performanceNow(),T.emit(f.JOIN_SUCCESS,{room:this}),ee.uploadEvent({log:`stat-conv-${Number(at)}-${location.hostname}`,userId:this.userId}),d}catch(d){throw i.delete({room:this,roomId:n}),T.emit(f.JOIN_FAILED,{room:this,error:d}),d}})}})}var pl=()=>F(r=>function(...i){return p(this,null,function*(){T.emit(f.LEAVE_START,{room:this}),yield r.call(this),T.emit(f.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function _l(){return F(r=>function(...i){let e=r.apply(this,i);return i.forEach(t=>!t.isSubscribed&&t.subscribe(e)),e})}var El=Ae(ke(),1);var fl=Symbol("instance"),hb=Symbol("abortCtrl"),jc=Symbol("cacheResult"),Ji=class{constructor(i,e,t){this.oldState=i,this.newState=e,this.action=t,this.aborted=!1}abort(i){this.aborted=!0,Gs.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},Hs=class extends Error{constructor(i,e,t){super(e),this.state=i,this.message=e,this.cause=t}};function Mp(r){return typeof r=="object"&&r&&"then"in r}var Fs=new Map;function qc(r,i,e={}){return(t,s,n)=>{let o=e.action||s;if(!e.context){let c=Fs.get(t)||[];Fs.has(t)||Fs.set(t,c),c.push({from:r,to:i,action:o})}let a=n.value;n.value=function(...c){let d=this;if(e.context&&(d=te.get(typeof e.context=="function"?e.context.call(this,...c):e.context)),d.state===i)return d[jc];d.state instanceof Ji&&d.state.action==e.abortAction&&d.state.abort(d);let l=null;if(Array.isArray(r)?r.length==0?d.state instanceof Ji&&d.state.abort(d):(typeof d.state!="string"||!r.includes(d.state))&&(l=new Hs(d._state,`${d.name} ${o} to ${i} failed: current state ${d._state} not in from config`)):r!==d.state&&(l=new Hs(d._state,`${d.name} ${o} to ${i} failed: current state ${d._state} not from ${r}`)),l)if(e.fail)e.fail.call(this,l);else{if(e.ignoreError)return l;throw l}let m=d.state,_=new Ji(m,i,o);Gs.call(d,_);let g=y=>{var x;return d[jc]=y,_.aborted||(Gs.call(d,i),(x=e.success)===null||x===void 0||x.call(this,d[jc])),y},R=y=>{let x=y instanceof Error?y.message:String(y);if(Gs.call(d,m,y),e.fail)e.fail.call(this,new Hs(d._state,`action '${o}' failed :${x}`,y instanceof Error?y:new Error(x)));else{if(e.ignoreError)return y;throw y}};try{let y=a.apply(this,c);return Mp(y)?y.then(g).catch(R):g(y)}catch(y){R(y)}}}}var kp=(()=>typeof window!="undefined"&&window.__AFSM__?(e,t)=>{window.dispatchEvent(new CustomEvent(e,{detail:t}))}:typeof importScripts!="undefined"?(e,t)=>{postMessage({type:e,payload:t})}:()=>{})();function Gs(r,i){let e=this._state;this._state=r;let t=r.toString();r&&this.emit(t,e),this.emit(te.STATECHANGED,r,e,i),this.updateDevTools({value:r,old:e,err:i instanceof Error?i.message:String(i)})}var te=class extends El.default{constructor(i,e,t){super(),this.name=i,this.groupName=e,this._state=te.INIT,i||(i=Date.now().toString(36)),t?Object.setPrototypeOf(this,t):t=Object.getPrototypeOf(this),e||(this.groupName=this.constructor.name);let s=t[fl];s?this.name=s.name+"-"+s.count++:t[fl]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let i=Object.getPrototypeOf(this),e=Fs.get(i)||[],t=new Set,s=[],n=[],o=new Set,a=Object.getPrototypeOf(i);Fs.has(a)&&(a.stateDiagram.forEach(d=>t.add(d)),a.allStates.forEach(d=>o.add(d))),e.forEach(({from:d,to:l,action:m})=>{typeof d=="string"?s.push({from:d,to:l,action:m}):d.length?d.forEach(_=>{s.push({from:_,to:l,action:m})}):n.push({to:l,action:m})}),s.forEach(({from:d,to:l,action:m})=>{o.add(d),o.add(l),o.add(m+"ing"),t.add(`${d} --> ${m}ing : ${m}`),t.add(`${m}ing --> ${l} : ${m} \u{1F7E2}`),t.add(`${m}ing --> ${d} : ${m} \u{1F534}`)}),n.forEach(({to:d,action:l})=>{t.add(`${l}ing --> ${d} : ${l} \u{1F7E2}`),o.forEach(m=>{m!==d&&t.add(`${m} --> ${l}ing : ${l}`)})});let c=[...t];return Object.defineProperties(i,{stateDiagram:{value:c},allStates:{value:o}}),c}static get(i){let e;return typeof i=="string"?(e=te.instances.get(i),e||te.instances.set(i,e=new te(i,void 0,Object.create(te.prototype)))):(e=te.instances2.get(i),e||te.instances2.set(i,e=new te(i.constructor.name,void 0,Object.create(te.prototype)))),e}static getState(i){var e;return(e=te.get(i))===null||e===void 0?void 0:e.state}updateDevTools(i={}){kp(te.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){Gs.call(this,i)}};te.STATECHANGED="stateChanged";te.UPDATEAFSM="updateAFSM";te.INIT="[*]";te.ON="on";te.OFF="off";te.instances=new Map;te.instances2=new WeakMap;var Tl=Ae(ke());var le={SETUP_SUCCESS:"1",SETUP_FAILED:"5",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",DISCONNECTED:"5",RECONNECT_FAILED:"4"};var ht={CLIENT_BANNED:9,CHANNEL_SETUP_RESULT:19,CHANNEL_RECONNECT_RESULT:514,JOIN_ROOM_RESULT:20,PEER_JOIN:4134,PEER_LEAVE:4135,STREAM_ADDED:16,STREAM_REMOVED:18,UPLINK_NETWORK_STATS:22,UPDATE_REMOTE_MUTE_STAT:23,PUBLISH_RESULT:4098,PUBLISH_STATE_CHANGE_RESULT:4112,UNPUBLISH_RESULT:4100,SUBSCRIBE_RESULT:4102,UNSUBSCRIBE_RESULT:4104,SUBSCRIBE_CHANGE_RESULT:4106,MUTE_RESULT:4108,UPDATE_OFFER_RESULT:4128,START_PUBLISH_TENCENT_CDN_RES:1286,STOP_PUBLISH_TENCENT_CDN_RES:1288,START_PUBLISH_GIVEN_CDN_RES:777,STOP_PUBLISH_GIVEN_CDN_RES:779,START_MIX_TRANSCODE_RES:781,STOP_MIX_TRANSCODE_RES:783,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772,REBUILD_PEER_CONNECTION_RES:4150,SPC_PUBLISH_RESULT:4146,SPC_SUBSCRIBE_RESULT:4156,ABILITY_STATUS_REPORT_RESULT:4158,SERVER_FIRST_PACKAGE_RECEIVED:5e3,RECEIVE_CUSTOM_MSG:4140},gl=[ht.UPDATE_REMOTE_MUTE_STAT,ht.UPLINK_NETWORK_STATS,ht.USER_LIST_RES,ht.MUTE_RESULT,ht.SERVER_FIRST_PACKAGE_RECEIVED,ht.RECEIVE_CUSTOM_MSG],P={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",USER_LIST_RES:"user-list-res",SWITCH_ROLE_RES:"switch_role_res",MUTE_RESULT:"mute-result",UPDATE_CONSTRAINT_CONFIG_RES:"update-contraint-config-res",REBUILD_PEER_CONNECTION_RES:"rebuild-pc-res",SPC_PUBLISH_RESULT:"spc-publish-result",SPC_SUBSCRIBE_RESULT:"spc-subscribe-result",ABILITY_STATUS_REPORT_RESULT:"ability-status-report",SERVER_FIRST_PACKAGE_RECEIVED:"first-pkg-received",RECEIVE_CUSTOM_MSG:"receive-custom-msg"},W={PUBLISH_CHANGE:"publish_change",JOIN_ROOM:"join",LEAVE_ROOM:"leave",ON_QUALITY_REPORT:"quality_report",UPDATE_MUTE_STAT:"mute_uplink",PUBLISH:"publish",PUBLISH_STATE_CHANGE:"publish_state_change",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",RECEIVE_DATA_USER_LIST:"receive_data_userlist",UNSUBSCRIBE:"unsubscribe",SUBSCRIBE_CHANGE:"subscribe_change",START_PUBLISH_TENCENT_CDN:"start_publishing",STOP_PUBLISH_TENCENT_CDN:"stop_publishing",START_PUBLISH_GIVEN_CDN:"start_push_user_cdn",STOP_PUBLISH_GIVEN_CDN:"stop_push_user_cdn",START_MIX_TRANSCODE:"start_mcu_mix",STOP_MIX_TRANSCODE:"stop_mcu_mix",GET_USER_LIST:"get_user_list",SWITCH_ROLE:"change_role",UPDATE_CONSTRAINT_CONFIG:"update_constraint_config",REBUILD_PEER_CONNECTION:"rebuild_pc",READY_TO_RECEIVE_DATA:"ready_to_receive",SPC_JOIN_ROOM:"join/v2",SPC_PUBLISH:"publish/v2",SPC_SUBSCRIBE:"subscribe/v3",ABILITY_STATUS_REPORT:"ability_status_report",RECONNECT_WS:"reconnect",SEND_CUSTOM_MSG:"channel_msg"};var ei=new WeakMap;function Ri({settings:r={retries:5,timeout:2e3},onError:i,onRetrying:e,onRetryFailed:t}){return function(s,n,o){let a=gt({retryFunction:o.value,settings:r,onError({error:c,retry:d,reject:l,retryFuncArgs:m}){i&&i.call(this,c,()=>{var _;(_=ei.get(s))!=null&&_.has(n)?d():l(c)},l,m)},onRetrying(c,d){var l;X(e)&&e.call(this,c,d),(l=ei.get(s))!=null&&l.has(n)&&(ei.get(s).get(n).stopRetry=d)},onRetryFailed:t});return o.value=function(...c){let d=ei.get(s);return d?d.set(n,{args:c}):ei.set(s,new Map([[n,{args:c}]])),a.apply(this,c).finally(()=>{var l;return(l=ei.get(s))==null?void 0:l.delete(n)})},o}}function Ws({fnName:r,callback:i,validateArgs:e=!0}){return function(t,s,n){let o=n.value;return n.value=function(...a){var c,d;if((c=ei.get(t))!=null&&c.has(r)){let{stopRetry:l,args:m}=ei.get(t).get(r),_=!0;if(e){for(let g of m)if(!a.find(R=>R===g)){_=!1;break}}_&&(i&&i.apply(this,a),l&&l(),(d=ei.get(t))==null||d.delete(r))}return o.apply(this,a)},n}}var No=new Set;function Sl(r){let i=[...No.values()].find(e=>e.room.userId===r&&!e.room.isJoined);return i||null}var kr=class extends Tl.default{constructor(e){var s,n;super();u(this,"room");u(this,"url");u(this,"backupUrl");u(this,"race");u(this,"destroyed",!1);u(this,"_socketInUse");u(this,"_socket");u(this,"_backupSocket");u(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0});u(this,"_currentState","DISCONNECTED");u(this,"_isReconnecting",!1);u(this,"_seq",0);u(this,"_log");u(this,"_lastMessageTime",-1);u(this,"_connnectStartTime",-1);u(this,"_stopConnectRetry");u(this,"bytesSent",0);u(this,"bytesReceived",0);u(this,"keepAlive",!1);this.room=e.room,this.race=E(e.race)?!0:e.race,(((n=(s=this.room.scheduleResult)==null?void 0:s.config)==null?void 0:n.keepAliveClient)||0)-No.size>0&&this.room.enableSPC&&(this.keepAlive=!0,No.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=A.createLogger({id:"ws",userId:this.userId,sdkAppId:this.sdkAppId}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get urlParam(){let e=`?sdkAppId=${encodeURIComponent(this.sdkAppId)}&userId=${encodeURIComponent(this.userId)}&userSig=${encodeURIComponent(this.userSig)}&keepAlive=${encodeURIComponent(Number(this.keepAlive))}`;return this.race?`${e}&race=1`:e}get _urlWithParam(){return`${this.url}${this.race?"/v2/ws":""}${this.urlParam}`}get _backupUrlWithParam(){return`${this.backupUrl}${this.race?"/v2/ws":""}${this.urlParam}`}get isConnected(){return this._currentState==="CONNECTED"}get isConnecting(){return this._currentState==="CONNECTING"}get sdkAppId(){return this.room.sdkAppId}get userId(){return this.room.userId}get userSig(){return this.room.userSig}get isOnline(){return this._currentState==="CONNECTED"&&Date.now()-this._lastMessageTime<12*1e3}connect(){return p(this,arguments,function*(e=10*1e3){if(this.isConnected)return Promise.resolve();this._log.info(`connect to [${this.url}, ${this.backupUrl}]${e?` timeout: ${e}`:""} keepAlive: ${Number(this.keepAlive)}`),this.emitConnectionStateChanged("CONNECTING"),this._connnectStartTime=B();let t=[this.connectWS({url:this._urlWithParam,isMain:!0,timeout:e})];this.race&&this._backupUrlWithParam!==this._urlWithParam&&t.push(this.connectWS({url:this._backupUrlWithParam,isMain:!1,timeout:e})),this._socketInUse=yield ls(t),this.unbindAndCloseSocket(this._socketInUse===this._socket?h.BACKUP:h.MAIN),this.emitConnectionStateChanged("CONNECTED")})}connectWS({url:e,timeout:t,isMain:s}){let n=new WebSocket(e);this.bindSocket(n),s?this._socket=n:this._backupSocket=n;let o=-1;return new Promise((a,c)=>{n.onclose=c,n.onerror=c,n.onopen=()=>a(n),t&&(o=setTimeout(()=>{this.unbindAndCloseSocket(s?h.MAIN:h.BACKUP),c(new C({code:I.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))},t))}).finally(()=>{n.onclose=null,n.onerror=null,n.onopen=null,clearTimeout(o)})}bindSocket(e){e.addEventListener("close",this.onclose),e.addEventListener("error",this.onerror),e.addEventListener("message",this.onmessage)}unbindSocket(e){e.removeEventListener("close",this.onclose),e.removeEventListener("error",this.onerror),e.removeEventListener("message",this.onmessage)}unbindAndCloseSocket(e){if(e===h.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(t){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(t){}this._backupSocket=null}}onclose(e){if(e.target===this._socketInUse&&(this._log.warn(`${e.target===this._socket?"main":"backup"} is closed code:${e.code} ${e.reason}`),this.emitConnectionStateChanged("DISCONNECTED"),!e.wasClean||e.code!==1e3)){this._socketInUse.onclose=null,this._socketInUse.close(4011);let t=this._socketInUse===this._socket;this.unbindAndCloseSocket(t?h.MAIN:h.BACKUP),this._socketInUse=null,this.reconnect()}}onerror(e){this._log.error(`${e.target===this._socket?"main":"backup"} error observed`),e.target===this._socketInUse&&(this.unbindAndCloseSocket(h.MAIN),this.unbindAndCloseSocket(h.BACKUP),this._socketInUse=null,this.reconnect())}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=Vn(e.data);let t=JSON.parse(e.data),{cmd:s,data:n}=t,o=Object.values(ht),c=Object.keys(ht)[o.indexOf(s)],d=P[c];switch(gl.includes(s)||(this._log.debug(`received ${s} msg: ${e.data}`),d&&this._log.info(`Received event: [ ${d} ]`)),s){case ht.CHANNEL_SETUP_RESULT:{if(t.code===0)this._signalInfo.clientIp=n.clientIp,this._signalInfo.signalIp=n.signalInnerIp,n.svrTime&&Cd(n.svrTime),this._log.info("ChannelSetup Success"),w.addSuccessEvent({key:521701,cost:B()-this._connnectStartTime}),this._connnectStartTime=-1,this.emit(le.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let l=new C({code:I.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:D({key:v.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error(`${t.code}, ${t.message}`),this.close(),w.addFailedEvent({key:521701,error:l}),this.emit(le.SETUP_FAILED,l)}break}case ht.JOIN_ROOM_RESULT:{t.code===0&&(this._signalInfo.relayIp=n.relayOuterIp,this._signalInfo.relayInnerIp=n.relayInnerIp,this._signalInfo.relayPort=n.relayPort,this._signalInfo.tinyId=t.tinyId,this._log.info(`signalIp:${this._signalInfo.signalIp} clientIp:${this._signalInfo.clientIp} relayIp: ${this._signalInfo.relayIp}`)),this.emit(d,{data:t});break}default:this.emit(d,{data:t});break}}reGetSignalChannelUrl(){return p(this,null,function*(){try{St(!0),yield this.room.schedule(this.room.roomId);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(e){}})}reconnect(){return p(this,null,function*(){if(!this._isReconnecting){if(!this.room.isJoined&&this.keepAlive){this.close();return}this._isReconnecting=!0;try{this._log.warn("reconnect"),yield this.connect();let{roomId:e,useStringRoomId:t}=this.room,{relayIp:s,relayInnerIp:n,relayPort:o}=this._signalInfo,{data:a}=yield this.sendWaitForResponse({command:W.RECONNECT_WS,data:{roomId:e,useStringRoomId:t,relayInnerIp:n,relayOuterIp:s,relayPort:o},responseCommand:P.CHANNEL_RECONNECT_RESULT});a.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),w.addSuccessEvent({key:521702,cost:B()-this._connnectStartTime}),this._connnectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(w.addFailedEvent({key:521702,error:a.code}),this._log.warn(`reconnect failed, ${a.code} ${a.message}`),this.room.reJoin())}catch(e){this._log.error(e),this.room.reJoin()}}})}send(e,t={}){if(this.isConnected&&!this.room.isLeft){let s={cmd:e,data:t,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},n=JSON.stringify(s);return this._socketInUse.send(n),this.bytesSent+=Vn(n),s.seq}}sendWaitForResponse({command:e,data:t,timeout:s=5e3,responseCommand:n,commandDesc:o,enableLog:a=!0}){return new Promise((c,d)=>{let l=setTimeout(()=>{this.off(n,m);let g=new C({code:I.API_CALL_TIMEOUT,message:D({key:v.API_CALL_TIMEOUT,data:{commandDesc:o,command:e}})});a&&this._log.warn(g),d(g)},s),m=g=>{g.data.seq===_&&(clearTimeout(l),this.off(n,m),c(g))};this.on(n,m);let _=this.send(e,t)})}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:s,retries:n=0,retryTimeout:o=0}=e;return gt({retryFunction:this.sendWaitForResponse,onError:({retry:a})=>{this.isOnline?a():(this._log.warn(`retry ${s} when connected`),this.once(le.CONNECTED,a))},onRetrying:a=>{this._log.warn(`${t||s} timeout observed, retrying [${a}/${n}]`)},settings:{retries:n,timeout:o},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),No.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(h.MAIN),this.unbindAndCloseSocket(h.BACKUP),this.emitConnectionStateChanged("DISCONNECTED")}destroy(){this.close(),this.destroyed=!0}stopKeepAliveIn(e=3600){if(this.keepAlive){this._log.info(`stopKeepAlive in ${e}s`);let t=setTimeout(()=>{this.keepAlive=!1,this._log.info(`close due to not used ${e}s`),this.close()},e*1e3),s=n=>{n instanceof Ji&&n.action==="join"&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(t),this.room.off(te.STATECHANGED,s))};this.room.on(te.STATECHANGED,s)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info(`${this._currentState} -> ${e}`),this.emit(le.CONNECTION_STATE_CHANGED,{prevState:this._currentState,state:e}),this._currentState=e,e==="CONNECTED"?this.emit(le.CONNECTED):e==="DISCONNECTED"&&this.emit(le.DISCONNECTED))}};b([Ri({settings:{retries:1/0,timeout:2e3},onError(r,i){!this.room.isDestroyed&&!this.destroyed&&i()},onRetrying(r,i){this._log.warn(`retrying to connect ${r}`),r>=3&&r%3===0&&this.reGetSignalChannelUrl(),i&&(this._stopConnectRetry=i,(this.room.isDestroyed||this.destroyed)&&i())}})],kr.prototype,"connect",1);var Il=Ae(ke());var Kc=0,Xc=!1,vo=new Set,xp=r=>Kc>2&&!Xc&&vo.size===0&&r,Qc=!1,We=class{constructor(i){u(this,"userId");u(this,"tinyId");u(this,"_sdpSemantics");u(this,"_isUplink");u(this,"_room");u(this,"_log");u(this,"_signalChannel");u(this,"_isErrorObserved",!1);u(this,"_waitForPeerConnectionConnectedPromise");u(this,"_waitForPeerConnectionConnectedPromiseReject",null);u(this,"_peerConnection",null);u(this,"_emitter",new Il.default);u(this,"_currentState","DISCONNECTED");u(this,"_isReconnecting",!1);u(this,"_reconnectionCount",0);u(this,"_reconnectionTimer",-1);u(this,"_isFirstConnection",!0);u(this,"_prevTime",-1);u(this,"_enableSEI");u(this,"_sei");u(this,"_localAddress");u(this,"_remoteAddress");this.userId=i.userId,this.tinyId=i.tinyId,this._room=i.room,this._sdpSemantics=i.room.sdpSemantics,this._isUplink=i.isUplink,this._log=A.createLogger({id:"n-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=i.signalChannel,this._enableSEI=i.enableSEI}beforeConnect(){this._prevTime<0&&(this._prevTime=B())}afterConnect(i){return p(this,null,function*(){try{yield i,this._isFirstConnection?(this._isFirstConnection=!1,w.addSuccessEvent({key:521705,cost:Math.min(B()-this._prevTime,30*1e3)})):this._isReconnecting&&w.addSuccessEvent({key:521706,cost:B()-this._prevTime}),this._prevTime=-1}catch(e){throw this._isFirstConnection?(this._isFirstConnection=!1,w.addFailedEvent({key:521705,error:e})):this._isReconnecting&&this._reconnectionCount>=3&&w.addFailedEvent({key:521706,error:e}),e}})}initialize(){let i={encodedInsertableStreams:this._enableSEI&&Ei,iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"};this._peerConnection=new RTCPeerConnection(i),this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this)}close(i){this._log.info("close connection"),this._emitter.emit("closed",i),this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this._sei&&(this._sei.destroy(),this._sei=null),vo.delete(this)}closePeerConnection(i=!1){this._peerConnection&&(this._log.info("close pc"),this._peerConnection.onconnectionstatechange=null,this._peerConnection.close(),this._peerConnection=null,i&&this.emitConnectionStateChangedEvent("DISCONNECTED")),this._waitForPeerConnectionConnectedPromiseReject&&this._waitForPeerConnectionConnectedPromiseReject(new C({code:I.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return it;let i=null;if(this._isUplink){if(!gr()||this._peerConnection.getSenders().length===0)return it;i=this._peerConnection.getSenders()[0].transport}else{if(!xi()||this._peerConnection.getReceivers().length===0)return it;i=this._peerConnection.getReceivers()[0].transport}return i?i.state:it}onConnectionStateChange(i){let e=this._peerConnection.iceConnectionState,t=this.getDTLSTransportState();if(this._log.info(`connectionState: ${i.target.connectionState}, ICE: ${e}, DTLS: ${t}`),i.target.connectionState===se.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),i.target.connectionState===se.FAILED||i.target.connectionState===se.CLOSED){let s=`connection ${i.target.connectionState}. ICE Transport state: ${e}, DTLS Transport state: ${t}`,n=new C({message:s,code:I.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",n)}(i.target.connectionState===se.CONNECTED||i.target.connectionState===se.COMPLETED)&&(this.logSelectedCandidate(),ee.logSuccessEvent({userId:this._room.userId,eventType:Le.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(i){return i===this._currentState?!1:(i==="CONNECTED"?(Kc=0,Xc=!1,Qc=!0,vo.add(this)):vo.delete(this),T.emit(f.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:i,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:i}),this._currentState=i,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}logSelectedCandidate(){return p(this,null,function*(){if(!this._peerConnection)return;let i=yield this._peerConnection.getStats();for(let[,e]of i)if(fi(e)){let t=i.get(e.localCandidateId),s=i.get(e.remoteCandidateId);t&&(this._log.info(`local candidate: ${t.candidateType} ${t.protocol}:${t.ip||t.address}:${t.port} ${t.networkType||""} ${t.candidateType==="relay"?`relayProtocol:${t.relayProtocol}`:""}`),this._localAddress=`${t.ip||t.address}:${t.port}`),s&&(this._log.info(`remote candidate: ${s.candidateType} ${s.protocol}:${s.ip||s.address}:${s.port}`),this._remoteAddress=`${s.protocol}:${s.ip||s.address}`);break}})}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise?this._waitForPeerConnectionConnectedPromise:(this._waitForPeerConnectionConnectedPromise=new Promise((i,e)=>{if(this._currentState==="CONNECTED")return i();this._waitForPeerConnectionConnectedPromiseReject=e;let t=a=>{a.state==="CONNECTED"&&(clearTimeout(o),n(),i())},s=({room:a})=>{a===this._room&&(clearTimeout(o),n(),e(new C({code:I.API_CALL_ABORTED,message:D({key:v.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{T.off(f.LEAVE_SUCCESS,s,this),this._emitter.off("connection-state-changed",t,this)},o=setTimeout(()=>{n();let a=new C({code:I.API_CALL_TIMEOUT,message:"connection timeout"});Kc+=1,xp(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),Xc=!0,this._emitter.emit("firewall-restriction")),e(a)},Kr);T.on(f.LEAVE_SUCCESS,s,this),this._emitter.on("connection-state-changed",t,this)}),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally(()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null}),this._waitForPeerConnectionConnectedPromise)}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(le.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=Pt()){this._log.warn(`SDK has tried reconnect for ${this._reconnectionCount} times, but all failed, please check your network`),this.stopReconnection();let i=new C({code:this._isUplink?I.UPLINK_RECONNECTION_FAILED:I.DOWNLINK_RECONNECTION_FAILED,message:D({key:this._isUplink?v.UPLINK_RECONNECTION_FAILED:v.DOWNLINK_RECONNECTION_FAILED})});return this.emitConnectionStateChangedEvent("DISCONNECTED"),this._emitter.emit("error",i),-1}return this._signalChannel.isConnected?(this._reconnectionCount+=1,this._log.warn(`reconnect() trying [${this._reconnectionCount}]`),1):(this._log.warn("reconnect() signal channel is not connected, suspend reconnection until signal is connected"),this._signalChannel.once(le.CONNECTED,this.reconnect,this),-1)}on(i,e,t){this._emitter.on(i,e,t)}off(i,e,t){this._emitter.off(i,e,t)}getIsReconnecting(){return this._isReconnecting}get isH264(){var i,e;return!!((e=(i=this._peerConnection)==null?void 0:i.remoteDescription)!=null&&e.sdp.includes("H264"))}};var ed=Ae(Zc());var ce=function(r){return ed.default.parse(r)},et=function(r){return ed.default.write(r)},Ol=function(r){let i=ce(r);return i.media.forEach(e=>{e.type===h.AUDIO&&e.fmtp.forEach(t=>{t.config+=";sprop-stereo=1;stereo=1"})}),et(i)};function Dl(r){let i=ce(r);return i.media.forEach(e=>{var t,s;if(e.type===h.VIDEO){let n=new Set;e.rtp.forEach(({payload:a,codec:c})=>c==="H264"&&n.add(a)),e.fmtp.forEach(({payload:a,config:c})=>{let d=c.match(/apt=(\d+)/);d&&d[1]&&n.has(Number(d[1]))&&n.add(a)});let o=({payload:a})=>!n.has(a);e.rtp=e.rtp.filter(o),e.rtcpFb=(t=e.rtcpFb)==null?void 0:t.filter(o),e.fmtp=e.fmtp.filter(o),e.payloads=(s=e.payloads)==null?void 0:s.split(" ").filter(a=>!n.has(Number(a))).join(" ")}}),et(i)}function Oo(r){return Object.keys(r).filter(i=>r[i])}var id=class extends We{constructor(e){super(L(N({},e),{isUplink:!1}));u(this,"_flag",0);u(this,"role","anchor");u(this,"remoteAudioTrack");u(this,"remoteVideoTrack");u(this,"remoteAuxiliaryTrack");u(this,"ssrc",{audio:0,video:0,auxiliary:0});u(this,"_isSDPExchanging",!1);this.flag=e.flag,this.remoteAudioTrack=e.remoteAudioTrack||new Qt(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new vt(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new Cr(this._room,this)}get subscribeState(){let e={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(this.remoteVideoTrack.mediaType&8?e.smallVideo=!0:e.video=!0),this.remoteAudioTrack.isSubscribed&&(e.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(e.auxiliary=!0),e}get muteState(){return _i(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,s,n;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(s=this.remoteVideoTrack)==null||s.onFlagChanged(),(n=this.remoteAuxiliaryTrack)==null||n.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===h.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var n,o;let t=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&t!==e&&((n=this.remoteVideoTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e}),(o=this.remoteAuxiliaryTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e})),s}onTrack(e){let t=e.streams[0],{track:s}=e,n=t.id===qr?h.MAIN:h.AUXILIARY;this._log.debug(`ontrack ${n} ${s.kind}`);let o=h.AUDIO;s.kind===h.VIDEO&&(o=n===h.MAIN?h.VIDEO:h.AUXILIARY);let a=this.remoteAudioTrack;o===h.VIDEO?a=this.remoteVideoTrack:o===h.AUXILIARY&&(a=this.remoteAuxiliaryTrack),a.setInputMediaStreamTrack(s)}addRRTRLine(e){let t=e.split(`\r
36
36
  `),s=new Map;t.forEach((o,a)=>{/^a=rtcp-fb:/.test(o)&&t[a+1]&&!/^a=rtcp-fb:/.test(t[a+1])&&s.set(a+1,`${o.match(/^a=rtcp-fb:\d+/)[0]} rrtr`)});let n=[...s];for(let o=0;o<n.length;o++){let[a,c]=n[o];t.splice(a+o,0,c)}return t.join(`\r
37
37
  `)}addSPSDescription(e){let t=ce(e);return t.media.forEach(s=>{s.type===h.VIDEO&&s.fmtp.forEach(n=>{n.config+=";sps-pps-idr-in-keyframe=1"})}),et(t)}removeSDESDescription(e){let t=["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"],s=ce(e);return s.media.forEach(n=>{!n.ext||(n.ext=n.ext.filter(o=>!t.includes(o.uri)))}),et(s)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return p(this,null,function*(){var s,n;try{if((((s=this._peerConnection)==null?void 0:s.connectionState)===se.NEW||((n=this._peerConnection)==null?void 0:n.connectionState)===se.CONNECTING)&&(yield this.waitForPeerConnectionConnected()),this.isSubscriptionStateNotChanged(e)){this._peerConnection||(this.initialize(),yield this.connect(e));return}if(this._log.info(`subscribe ${t} ${JSON.stringify(e)}`),this._peerConnection||this._isSDPExchanging){let o="subscribe_change";Object.values(e).find(a=>a===!0)||(o="unsubscribe"),yield this.sendSubscription(o,e)}else this.initialize(),yield this.connect(e)}catch(o){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${o.message} ${JSON.stringify(this.muteState)}`),new C({code:I.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):o}})}unsubscribe(s){return p(this,arguments,function*({remoteTracks:e,streamType:t}){if(this._currentState==="CONNECTED"&&(t==="main"&&!this.isMainStreamSubscribed||t==="auxiliary"&&!this.isAuxStreamSubscribed)){this._log.info(`${t} stream already unsubscribed`);return}let n=N({},this.subscribeState);e.forEach(a=>{switch(a.mediaType){case 1:n.audio=!1;break;case 4:n.video=!1;break;case 8:n.smallVideo=!1;break;case 2:n.auxiliary=!1;break;default:break}});let o="subscribe_change";Object.values(n).find(a=>a===!0)||(o="unsubscribe"),this._log.info(`${o==="unsubscribe"?o:"subscribe"} ${t} [${Oo(n)}]`),yield this.sendSubscription(o,n),o==="unsubscribe"&&(this.closePeerConnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"))})}sendSubscription(e,t=this.subscribeState){let s={srcTinyId:this.tinyId,srcUserId:this.userId},n=W.UNSUBSCRIBE,o=P.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(s={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},n=W.SUBSCRIBE_CHANGE,o=P.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:n,data:s,responseCommand:o,timeout:1e4}).then(({data:a})=>{if(a.code!==0){let c=new C({code:a.code,message:D({key:v.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(c),c}})}connect(){return p(this,arguments,function*(e=this.subscribeState){try{yield this.exchangeSDP(e),yield this.waitForPeerConnectionConnected()}catch(t){throw this.closePeerConnection(!0),t}})}exchangeSDP(e){return p(this,null,function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info("createOffer success, sending offer");let{type:t,sdp:s}=this._peerConnection.localDescription,n={type:t,sdp:s,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},o=yield this._signalChannel.sendWaitForResponse({command:W.SUBSCRIBE,commandDesc:"exchange sdp",data:n,responseCommand:P.SUBSCRIBE_RESULT,timeout:ra});if(!this._peerConnection){let a=new C({code:I.INVALID_OPERATION,message:D({key:v.CONNECTION_CLOSED})});throw this._log.warn(a),a}yield this.onSubscribeResult(o),this._isSDPExchanging=!1}catch(t){throw this._isSDPExchanging=!1,t}})}createOffer(){return p(this,null,function*(){let e={voiceActivityDetection:!1};Qe()&&this._sdpSemantics===ai?(this._peerConnection.addTransceiver(h.AUDIO,{direction:j.RECVONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:j.RECVONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:j.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:s}=yield $n();s||(this._log.warn("remove h264 desc from sdp"),t.sdp=Dl(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=Ol(t.sdp),this._sdpSemantics===ai&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this._peerConnection.setLocalDescription(t)})}onSubscribeResult(e){return p(this,null,function*(){let{code:t,message:s=""}=e&&e.data||{},{type:n,sdp:o}=e&&e.data&&e.data.data||{};if(t===bi)throw new C({code:I.NOT_SUPPORTED_H264,message:D({key:v.NOT_SUPPORTED_H264DECODE})});try{if(t!==0)throw new C({code:t,message:D({key:v.EXCHANGE_SDP_FAILED,data:{errMsg:s}})});this._log.debug(`accept remote answer: ${o}`),yield this._peerConnection.setRemoteDescription({type:n,sdp:o}),this._sei&&(this._sei.handleEncodedStreams(),this._sei.onSEIMessage=a=>{this._emitter.emit("sei-message",L(N({},a),{userId:this.userId}))}),this.updateSSRC(o)}catch(a){throw this._log.error(a),a}})}updateSSRC(e){try{ce(e).media.forEach(s=>{if(!!s.ssrcs)if(s.type===h.AUDIO){let n=s.ssrcs.find(o=>{var a;return(a=o.value)==null?void 0:a.includes(qr)});n&&(this.ssrc.audio=Number(n.id))}else{let n=s.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(qr)}),o=s.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(Yo)});n&&(this.ssrc.video=Number(n.id)),o&&(this.ssrc.auxiliary=Number(o.id))}})}catch(t){}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return p(this,null,function*(){if(!(Re(id.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch(t){let s=It(this._reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${s/1e3}s`),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},s)}})}getIsReconnecting(){return this._isReconnecting}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}getCurrentState(){return this._currentState}setDelay({audioDelay:e,videoDelay:t}){this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=t}},js=id;b([F(r=>function(...i){return new Promise((e,t)=>{let s=n=>{this._emitter.off("closed",s),t(new C({code:I.API_CALL_ABORTED,message:D({key:v.CONNECTION_ABORTED,data:n})}))};this._emitter.on("closed",s),r.apply(this,i).then(e,t).finally(()=>{this._emitter.off("closed",s)})})})],js.prototype,"subscribe",1),b([to(We.prototype.afterConnect),eo(We.prototype.beforeConnect)],js.prototype,"connect",1);var td=js;var kl={voiceActivityDetection:!1},rd=class extends We{constructor(e){super(L(N({},e),{isUplink:!0}));u(this,"localMainAudioTrack",null);u(this,"localMainVideoTrack",null);u(this,"localAuxAudioTrack",null);u(this,"localAuxVideoTrack",null);u(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0});u(this,"_isPublishingAux",!1);u(this,"_publishingLocalAudioTrack");u(this,"_publishingLocalVideoTrack");u(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0});u(this,"flag",0)}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}get publishState(){var t,s,n,o;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(At()?(e.audio=!!((t=a[0])!=null&&t.track),e.bigVideo=!!((s=a[1])!=null&&s.track),e.smallVideo=!!((n=a[2])!=null&&n.track),e.auxVideo=!!((o=a[3])!=null&&o.track)):a.forEach(c=>{c.track&&(c.track.kind===h.AUDIO?e.audio=!0:(e.bigVideo=!0,this._room.videoManager.hasSmall&&(e.smallVideo=!0)))}))}return e}initialize(){super.initialize(),this.installEvents()}reset(){this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this.uninstallEvents()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this._emitter.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this._emitter.on("connection-state-changed",this.handleConnectionStateChange,this)}uninstallEvents(){this._emitter.off("connection-state-changed",this.handleConnectionStateChange,this)}emitConnectionStateChangedEvent(e,t){var o,a,c;let s=this._currentState,n=super.emitConnectionStateChangedEvent(e);return n&&s!==e&&(t?t.emit("connection-state-changed",{prevState:s,state:e}):((o=this.localMainVideoTrack)==null||o.emit("connection-state-changed",{prevState:s,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:s,state:e}),(c=this._publishingLocalVideoTrack)==null||c.emit("connection-state-changed",{prevState:s,state:e}))),n}publish(n){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:s}){var a;this._peerConnection||this.initialize(),e&&(this._publishingLocalAudioTrack=e),t&&(this._publishingLocalVideoTrack=t),this._isPublishingAux=s;let o;t&&!s&&t.small&&(o=this._room.videoManager.smallTrack),this.sendMediaSettings(),Qe()?yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:o,isAuxiliary:s}):yield this.publishByAddTrack({localAudioTrack:e,localVideoTrack:t,smallTrack:o}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,s?(t&&(this.localAuxVideoTrack=t),e&&(this.localAuxAudioTrack=e)):(t&&(this.localMainVideoTrack=t),e&&(this.localMainAudioTrack=e)),(a=this._sei)==null||a.handleEncodedStreams(),this.installTrackMuteEvents(e,t),this.sendMutedFlag()})}publishByTransceiver(o){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:s,isAuxiliary:n}){this._log.info("publish by transceiver");let a=new MediaStream,c=t==null?void 0:t.outMediaTrack,d=e==null?void 0:e.outMediaTrack;d&&a.addTrack(d),c&&a.addTrack(c);let l=this._peerConnection.getTransceivers();if(l.length===0)this._peerConnection.addTransceiver(d||h.AUDIO,{direction:j.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(n?h.VIDEO:c||h.VIDEO,{direction:j.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(s||h.VIDEO,{direction:j.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(n?c||h.VIDEO:h.VIDEO,{direction:j.SENDONLY,streams:[a]}),yield this.connect();else{let m=[];if(d&&(l[0].sender.track||m.push(0),yield l[0].sender.replaceTrack(d),yield this.setBandwidth({bandwidth:(e==null?void 0:e.profile.bitrate)||40,type:h.AUDIO})),c){let _=n?3:1;yield l[_].sender.replaceTrack(c),yield this.setBandwidth({bandwidth:t.profile.bitrate,type:h.VIDEO,videoType:n?h.AUXILIARY:h.BIG}),m.push(_),s&&(yield l[2].sender.replaceTrack(s),yield this.setBandwidth({bandwidth:t.small.bitrate,type:h.VIDEO,videoType:h.SMALL}),m.push(2))}yield this.setTransceiverDirection(j.SENDONLY,m),yield this.doPublishChange(),t==null||t.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),t==null||t.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"})}})}publishByAddTrack(n){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:s}){this._log.info("publish by addtrack");let o=t==null?void 0:t.outMediaTrack,a=e==null?void 0:e.outMediaTrack;if(this._peerConnection&&this._peerConnection.connectionState!=="new"){e&&a&&(yield this.addTrack(e)),o&&(yield this.addTrack(t));return}let c=new MediaStream;if(a&&c.addTrack(a),o&&c.addTrack(o),a&&this._peerConnection.addTrack(a,c),o&&(this._peerConnection.addTrack(o,c),s)){let d=new MediaStream;d.addTrack(s),this._peerConnection.addTrack(s,d)}yield this.connect()})}enableSmall(e){return p(this,null,function*(){let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.setTransceiverDirection(j.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(j.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()})}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(s){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){if(!At()){if(e&&e.outMediaTrack&&!t&&this.localMainVideoTrack){yield this.removeTrack(e),this.localMainAudioTrack=null;return}if(t&&t.outMediaTrack&&!e&&this.localMainAudioTrack){yield this.removeTrack(t),this.localMainVideoTrack=null;return}yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),this.emitConnectionStateChangedEvent("DISCONNECTED",t);return}let n=t&&t===this.localAuxVideoTrack,o=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),c=[];e&&(yield a[0].replaceTrack(null),c.push(0),n?this.localAuxAudioTrack=null:this.localMainAudioTrack=null),o&&(n?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=L(N({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),c.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=L(N({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),c.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.setTransceiverDirection(j.INACTIVE,c),yield this.doPublishChange(!1)):yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),t==null||t.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return p(this,null,function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},s=yield this._signalChannel.sendWaitForResponse({command:W.PUBLISH_STATE_CHANGE,data:t,responseCommand:P.PUBLISH_STATE_CHANGE_RESULT,enableLog:e});this.checkPublishResultCode(s.data.code,s.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:W.UNPUBLISH,commandDesc:"unpublish",responseCommand:P.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===I.API_CALL_TIMEOUT)return Promise.resolve();throw t})}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let s=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:n,localAuxVideoTrack:o}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?o=this._publishingLocalVideoTrack:n=this._publishingLocalVideoTrack),Rt){if(s&&s.outMediaTrack){let a=s.outMediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=s.profile.bitrate*1e3,this._mediaSettings.audioFs=a.sampleRate||0}if(n&&n.outMediaTrack){let a=n.outMediaTrack.getSettings();this._mediaSettings.videoWidth=a.width||0,this._mediaSettings.videoHeight=a.height||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=n.profile.bitrate*1e3,n.small&&(this._mediaSettings.smallVideoWidth=n.small.width,this._mediaSettings.smallVideoHeight=n.small.height,this._mediaSettings.smallVideoFps=n.small.frameRate,this._mediaSettings.smallVideoBps=n.small.bitrate*1e3)}if(o&&o.outMediaTrack){let a=o.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=a.width||0,this._mediaSettings.auxVideoHeight=a.height||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=o.profile.bitrate*1e3}}else s&&s.outMediaTrack&&(this._mediaSettings.audioChannel=s.profile.channelCount,this._mediaSettings.audioBps=s.profile.bitrate*1e3,this._mediaSettings.audioFs=s.profile.sampleRate),n&&n.outMediaTrack&&(this._mediaSettings.videoWidth=n.profile.width,this._mediaSettings.videoHeight=n.profile.height,this._mediaSettings.videoFps=n.profile.frameRate,this._mediaSettings.videoBps=n.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:W.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:P.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return p(this,null,function*(){var s;if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is adding ${e.kind} track to current published local ${t?h.AUXILIARY:h.MAIN} stream`),(s=this._sei)==null||s.handleEncodedStreams(),Qe()?yield this.addTrackByTransceiver(e,t):yield this.addTrackBySender(e)})}addTrackByTransceiver(e,t){return p(this,null,function*(){var n;if(!e.mediaTrack)return;let s=this._peerConnection.getTransceivers();if(e.kind===h.AUDIO)yield s[0].sender.replaceTrack(e.outMediaTrack);else{let o=t?3:1;yield s[o].sender.replaceTrack(e.outMediaTrack),o===1&&((n=this.localMainVideoTrack)==null?void 0:n.small)&&(yield s[2].sender.replaceTrack(this._room.videoManager.smallTrack)),s[o].direction===j.INACTIVE&&(yield this.setTransceiverDirection(j.SENDONLY,[o]))}this.updateMediaSettings(),yield this.doPublishChange()})}addTrackBySender(e){return p(this,null,function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;At()&&this._peerConnection.getTransceivers().findIndex(n=>n.direction==="stopped")>=0&&(this._log.warn("transceiver is stopping, negotiate sdp first"),yield this.updateOffer("remove",t));let s=this._peerConnection.getSenders().find(n=>n.track&&n.track.kind===t.kind);if(s&&s.track){this._log.warn("sender already exists, remove sender first");let n=s.track;this.removeSender(s),yield this.updateOffer("remove",n)}if(t&&this._peerConnection.addTrack(t,new MediaStream([t])),t.kind===h.VIDEO&&e instanceof ae&&e.small){let n=new MediaStream,{smallTrack:o}=this._room.videoManager;n.addTrack(o),this._peerConnection.addTrack(o,n)}yield this.updateOffer("add",t)})}isNeedToResetOfferOrder(){if(this._sdpSemantics===Yi||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=ce(e);for(let s=0;s<t.media.length;s++)if(Number(t.media[s].mid)===0&&t.media[s].type===h.VIDEO)return!0;return!1}removeSender(e){let t=null;At()&&(t=this._peerConnection.getTransceivers().find(s=>s.sender&&s.sender.track===e.track)),this._peerConnection.removeTrack(e),t&&X(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return p(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${t?h.AUXILIARY:h.MAIN} stream`),Qe()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)})}removeTrackByTransceiver(e,t){return p(this,null,function*(){if(!e.outMediaTrack)return;let s=this._peerConnection.getTransceivers();if(e.kind===h.AUDIO)yield s[0].sender.replaceTrack(null);else{let n=t?3:1;yield s[n].sender.replaceTrack(null),n===1&&e.small&&(yield s[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(j.INACTIVE,[n])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,t){return p(this,null,function*(){if(!Y)return;let s=!1,n=!1;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let o=this._peerConnection.getTransceivers();if(t.forEach(d=>{o[d].direction!==e&&(o[d].direction=e,s=!0)}),s){this._log.info("updating offer");let d=yield this._peerConnection.createOffer();yield this._peerConnection.setLocalDescription(d)}let a=-1,c=this._peerConnection.remoteDescription.sdp.split(`\r
38
38
  `).map(d=>{if(d.match(new RegExp(`a=(${j.INACTIVE}|${j.RECVONLY}|${j.SENDONLY})`))&&a++,t.includes(a)){if(e===j.INACTIVE&&d.includes(`a=${j.RECVONLY}`))return n=!0,`a=${e}`;if(e===j.SENDONLY&&d.includes(`a=${j.INACTIVE}`))return n=!0,`a=${j.RECVONLY}`}return d}).join(`\r
@@ -74,9 +74,9 @@ in vec2 v_texCoord;
74
74
  out vec4 outColor;
75
75
  void main() {
76
76
  outColor = vec4(texture(u_texture, v_texCoord).rgb, texture(mask, v_texCoord).a);
77
- }`,Vo=class extends wr{constructor(e,t){super(e,t.input,{name:"vb",create2d:!1,useDefaultProgram:!1,useFbo:!1,createTexture:!0});u(this,"ready",!1);u(this,"_bgTexture");u(this,"_waterMarkTexture");u(this,"_lastMaskTexture");u(this,"_lastMaskFbo");u(this,"_textureValid",!1);u(this,"_selfieTextureValid",!1);u(this,"_selfieSegmentation");u(this,"wasm");u(this,"_prePrograme");u(this,"_segmentationMask");u(this,"_weixin",!1);this._selfieSegmentation=t.selfieSegmentation,this._selfieSegmentation.onResults=this.onPredict.bind(this),this.init(t).catch(()=>this.context.destroy(new Error("selfie_segmentation init faild")))}init(e){return p(this,null,function*(){let t=e.Wasm,s=this.context.ctx;if(this.wasm=new t.AllIn1(s),this.wasm.blurRadius=e.blurRadius||3,this.wasm.mirror=!!e.mirror,this.wasm.vbMode=e.bg==="blur"?1:e.bg instanceof HTMLImageElement?2:e.bg==="green"?3:0,e.waterMark){let{x:n,y:o,width:a,height:c}=e.waterMark;this.wasm.setWaterMark(n,o,a,c)}if(this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),s.uniform1i(s.getUniformLocation(this.program,"mask"),1),e.bg instanceof HTMLImageElement&&(s.uniform1i(s.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(e.bg)),e.waterMark&&(s.uniform1i(s.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(e.waterMark.image)),s.uniform1i(s.getUniformLocation(this.program,"lastMask"),4),this._weixin){let n=this.context.createShader(s.FRAGMENT_SHADER,t_),o=this.context.createShader(s.VERTEX_SHADER,e_);this._prePrograme=this.context.createProgram(o,n),s.useProgram(this._prePrograme),this.setAttributes(this.positionBuffer,this.texCoordBuffer),s.uniform1i(s.getUniformLocation(this._prePrograme,"mask"),1)}this.ready=!0})}onPredict(e){let t=this.context.ctx;this._weixin&&(this._lastMaskTexture||(this._lastMaskTexture=this.createTexture(this.image),this._lastMaskFbo=this.createFramebuffer(this._lastMaskTexture))),this.useProgram(),this._weixin?this.useTexture():this._selfieSegmentation.bindTexture(),t.activeTexture(t.TEXTURE1),this._selfieSegmentation.bindTexture2d(e),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),this.useBufferFrame(),t.drawArrays(t.TRIANGLE_STRIP,0,4),this._segmentationMask=e,this.totalFrames++}render(e){let t=this.context.ctx;if(typeof this.image.getVideoPlaybackQuality=="function"&&!ui){let c=this.image.getVideoPlaybackQuality().totalVideoFrames;if(this._totalFrames===c)return!1;this._totalFrames=c,this.dropFrames=this._totalFrames-this.totalFrames}let{videoWidth:s,videoHeight:n}=this.image;this.image.width=s,this.image.height=n;let o=!1;if(this.totalFrames)this._weixin?this.useTexture():this._selfieSegmentation.bindTexture(),o=this._selfieTextureValid,this._selfieTextureValid=!0;else{if(this.program)this.useTexture();else return!1;o=this._textureValid,this._textureValid=!0}return this.width!==s||this.height!==n||!o?(this.resize(s,n),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.image)):t.texSubImage2D(t.TEXTURE_2D,0,0,0,t.RGBA,t.UNSIGNED_BYTE,this.image),this.ready&&(this._weixin&&(t.useProgram(this._prePrograme),this.useTexture(),this._segmentationMask&&(t.activeTexture(t.TEXTURE1),this._selfieSegmentation.bindTexture2d(this._segmentationMask),t.bindFramebuffer(t.FRAMEBUFFER,this._lastMaskFbo||null)),t.drawArrays(t.TRIANGLE_STRIP,0,4),this._selfieSegmentation.bindTexture(),this._segmentationMask?t.copyTexSubImage2D(t.TEXTURE_2D,0,0,0,0,0,s,n):t.copyTexImage2D(t.TEXTURE_2D,0,t.RGBA,0,0,s,n,0)),this._selfieSegmentation.send(s,n)),this.totalFrames||(t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),t.drawArrays(t.TRIANGLE_STRIP,0,4)),!1}close(){var t;super.close();let e=this.context.ctx;this._bgTexture&&e.deleteTexture(this._bgTexture),this._waterMarkTexture&&e.deleteTexture(this._waterMarkTexture),this._lastMaskTexture&&e.deleteTexture(this._lastMaskTexture),this._lastMaskFbo&&e.deleteFramebuffer(this._lastMaskFbo),this._prePrograme&&e.deleteProgram(this._prePrograme),(t=this.wasm)==null||t.close()}};var Uo=class extends Vl.EventEmitter{constructor(e){super();this.room=e;u(this,"videoContext");u(this,"_glVideoContext");u(this,"_2dVideoContext");u(this,"destination");u(this,"smallVideoContext");u(this,"smallDestination");u(this,"smallTrackSource");u(this,"smallImageSource");u(this,"_isMirror",!1);u(this,"cameraTrack");u(this,"cameraNode");u(this,"mirrorNode");u(this,"mixNode");u(this,"screenTrack");u(this,"screenNode");u(this,"selfModel",!1);u(this,"blurRadius",3);u(this,"arTrack");u(this,"Wasm");u(this,"waterMarkNode");u(this,"_waterMarkOption");u(this,"watermarkImageList",[]);u(this,"_isMixScreen",!1);u(this,"_virtualBackground");u(this,"virtualBackgroundInstance");u(this,"isUsingArTrack",!1);u(this,"_bgAssetPath");u(this,"log",A.createLogger({id:"vm"}));u(this,"_checkId",0);u(this,"_use2d",!1);u(this,"_autoSwitchRenderMode",!0);u(this,"_selfieSegmentation");e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new je({frameRate:15,logger:this.log,name:"s"}),this.enablePrintDetail()}get _hasVirtualBg(){return!!this._virtualBackground}get _hasWaterMark(){return this.watermarkImageList.length>0}get renderMode(){return this._autoSwitchRenderMode?"auto":this._use2d?"2d":"webgl"}set renderMode(e){if(this._autoSwitchRenderMode=e==="auto",this._autoSwitchRenderMode)return;let t=e==="2d";this._use2d!==t&&(this._use2d=t,this.clear(),this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.update())}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new je({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this.sendCreateResult("videoCtx2d",this._2dVideoContext.ctx?void 0:new Error("create 2d context failed")),this._2dVideoContext}getGlVideoContext(){if(!this._glVideoContext)this._glVideoContext=new Ie({frameRate:15,logger:this.log,name:"m"});else if(this._glVideoContext.available)return this._glVideoContext;try{this._glVideoContext.create(),this.sendCreateResult(),this._glVideoContext.on("unavailable",(e,t)=>{this.emit("error",{reason:e,error:t}),this.log.warn("video context unavailable",e,t),this.sendCreateResult("videoCtxGl",t||new Error(e)),this.update()})}catch(e){this.emit("error",{reason:"create",error:e}),this.sendCreateResult("videoCtxGl",e)}return this._glVideoContext}enablePrintDetail(e=2e3){this._checkId=Z.run(Oi,()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:e})}destroy(){var e,t;(e=this._2dVideoContext)==null||e.destroy(),(t=this._glVideoContext)==null||t.destroy(),this.smallVideoContext.destroy(),Z.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(ui||this._isMixScreen||this._isMirror||this._hasWaterMark||this._hasVirtualBg)&&this.checkOrCreateVideoContext()}sendCreateResult(e="videoCtxGl",t){let s=e==="videoCtxGl"?512700:512701;t?w.addFailedEvent({key:s,error:t}):w.addSuccessEvent({key:s})}checkOrCreateVideoContext(){let e=this._use2d;if(this._autoSwitchRenderMode&&(this._use2d=!this._hasVirtualBg),this.videoContext)if(this.videoContext.available){let t=!this.videoContext.hasAlpha&&this.needAlpha;if(this._autoSwitchRenderMode&&e===this._hasVirtualBg)this.clear();else if(t)if(this._use2d)this.clear();else return!0;else return!0}else this.clear(),this._use2d=!0;return this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.videoContext.available}get smallTrack(){var e;return(e=this.smallDestination)==null?void 0:e.videoTrack}get hasSmall(){return!!this.smallTrack}get initialTrack(){var e;return(e=this.cameraTrack)==null?void 0:e.mediaTrack}initVirtualBackground(e){return this._selfieSegmentation=e,this._selfieSegmentation.changeModel()}_setMainOutput(e){var c;let t=this.cameraTrack,{small:s,settings:n,player:o}=t;s?(this.smallVideoContext.available||(this.smallVideoContext.create({alpha:!1}),this.smallDestination=new Lo(this.smallVideoContext,s)),this.smallVideoContext.frameRate=s.frameRate,this.smallDestination.resolution=s,e?(this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=e:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(e),this.smallImageSource.connect(this.smallDestination))):(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource?this.smallTrackSource.replaceTrack(this.initialTrack):(this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack),this.smallTrackSource.width=n.width,this.smallTrackSource.height=n.height,this.smallTrackSource.connect(this.smallDestination)))):this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource),ui&&o.setCanvas(e);let a=e&&((c=this.destination)==null?void 0:c.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),a=this.arTrack),this._selfieSegmentation&&e&&(this._selfieSegmentation._glName||this._selfieSegmentation.setCanvas(e)),t.setOutputMediaStreamTrack(a)}update(){return p(this,null,function*(){var s,n;if(!this.cameraTrack||!this.cameraTrack.mediaTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:e,profile:t}=this.cameraTrack;if(this._use2d||!this._selfieSegmentation?(this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination"})),this.cameraNode?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack),this.cameraNode.resize(e.width,e.height))):(this.cameraNode&&this.cameraNode.close(),this.destination||(this.destination=new ko(this.videoContext,{name:"mainDestination"})),this.cameraNode=new Vo(this.videoContext,{input:this.cameraTrack.mediaTrack,mirror:this._isMirror,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,selfieSegmentation:this._selfieSegmentation,Wasm:this.Wasm}),this.cameraNode.connect(this.destination)),this.videoContext.frameRate=t.frameRate,this._use2d){let o=this.cameraNode;o.disconnect(),this._isMirror&&(this.mirrorNode||(this.mirrorNode=new Po(this.videoContext)),o=o.connect(this.mirrorNode),o.disconnect(),this.log.info("start mirror")),this.mixNode&&this.mixNode.close(),delete this.mixNode,(this._isMixScreen||this._hasWaterMark)&&(this.mixNode=new wo(this.videoContext),o.connect(this.mixNode,{zIndex:1}),this._hasWaterMark&&!this.waterMarkNode&&this._waterMarkOption&&(this.waterMarkNode=this.videoContext.createVideoImageSource(this._waterMarkOption.image,{autoResize:!1}),this.waterMarkNode.resize(this._waterMarkOption.width,this._waterMarkOption.height),this.waterMarkNode.x=this._waterMarkOption.x,this.waterMarkNode.y=this._waterMarkOption.y),(s=this.waterMarkNode)==null||s.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&!this.screenNode&&(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack)),(n=this.screenNode)==null||n.connect(this.mixNode,{zIndex:0}),o=this.mixNode,this.log.info("start mix",`${this.mixNode.width}x${this.mixNode.height}`)),o.connect(this.destination)}return this._setMainOutput(this.videoContext._canvas)})}changeInput(e){var t;if(this.log.info("change input",(t=e._inputTrack)==null?void 0:t.label),e instanceof Ge)return this.setScreenTrack(e);if(e instanceof ae)return this.setCameraTrack(e);if(e instanceof vt){let s=e.mediaTrack;if(as===17&&!e.source&&e.player.element){let n=new je({frameRate:15,logger:this.log,name:e.userId});n.create({alpha:!1});let o=n.createVideoImageSource(e.player.element);e.source=o;let a=new Qs(n);o.connect(a),e.player.setCanvas(n._canvas)}return e.setOutputMediaStreamTrack(s)}}removeInput(e){var t;e instanceof Ge?((t=this.screenNode)==null||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof ae?(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof vt&&e.source&&e.source.context.destroy()}setCameraTrack(e){return p(this,null,function*(){this.cameraTrack=e,this.update()})}setScreenTrack(e){return this.screenTrack=e,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)}getWatermarkImage(e,t){return p(this,null,function*(){let s=document.createElement("canvas");t&&e&&(s.height=t,s.width=e);let n=s.getContext("2d");if(!n)throw new C({code:I.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort((o,a)=>o.zIndex-a.zIndex),this.watermarkImageList.forEach(({image:o,x:a,y:c,width:d,height:l})=>{n.drawImage(o,a,c,d,l)}),Es(s.toDataURL())})}pushWaterMarkImageList(e){let{type:t}=e;this.watermarkImageList.some(n=>n.imageUrl===e.imageUrl&&n.height===e.height&&n.width===e.width&&n.x===e.x&&n.y===e.y&&n.type===e.type&&n.zIndex===e.zIndex)||((t==="mute"||t==="watermark")&&(this.watermarkImageList=this.watermarkImageList.filter(n=>n.type!==t)),this.watermarkImageList.push(e))}setWatermark(e){return p(this,null,function*(){let t;try{t=yield Es((e==null?void 0:e.imageElement)||e.imageUrl)}catch(l){throw new C({code:I.INVALID_PARAMETER,message:`load image failed, url: ${e.imageUrl}`})}let{x:s=0,y:n=0,width:o=t.width,height:a=t.height,type:c="watermark",zIndex:d=2}=e;this.pushWaterMarkImageList({x:s,y:n,width:o,height:a,image:t,zIndex:d,type:c,imageUrl:e.imageUrl}),yield this.freshWatermark(),this.log.info("set watermark",JSON.stringify(this.watermarkImageList))})}deleteWatermark(e="watermark"){return p(this,null,function*(){this.watermarkImageList=this.watermarkImageList.filter(t=>t.type!==e),this.log.info("delete watermark",e,JSON.stringify(this.watermarkImageList)),yield this.freshWatermark()})}freshWatermark(){return p(this,null,function*(){var t,s,n;(t=this.waterMarkNode)==null||t.close(),delete this.waterMarkNode,delete this._waterMarkOption;let e=yield this.getWatermarkImage((s=this.cameraTrack)==null?void 0:s.settings.width,(n=this.cameraTrack)==null?void 0:n.settings.height);this._waterMarkOption={x:0,y:0,width:e.width,height:e.height,image:e},this.update()})}setVirtualBackground(e){return p(this,null,function*(){if(!e)this._virtualBackground=void 0;else{if(this._use2d&&!this._autoSwitchRenderMode)return Promise.reject(new Error("not support virtual background in 2d mode"));this._bgAssetPath=e.assetPath,e.type==="image"?this._virtualBackground=yield Es(e.imageUrl):(this.blurRadius=e.blurRadius||3,this._virtualBackground=e.type)}this.log.info(`${this._virtualBackground?"start":"stop"} visual background, ${(e==null?void 0:e.type)||""}`),this.update()})}get mixScreen(){return this._isMixScreen}set mixScreen(e){var t;this._isMixScreen=e,this._isMixScreen||((t=this.screenNode)==null||t.close(),delete this.screenNode),this.update()}set mirror(e){var t;this._isMirror!==e&&(this._isMirror=e,this._isMirror||((t=this.mirrorNode)==null||t.close(),delete this.mirrorNode),this.update())}get mirror(){return this._isMirror}enableAr(e){this.arTrack=e,this.isUsingArTrack=!0,this.update()}updateAr(){return p(this,null,function*(){var e;!((e=this.cameraTrack)!=null&&e.mediaTrack)||(yield this.virtualBackgroundInstance.ar.updateInputTrack(this.cameraTrack.mediaTrack.clone()))})}disableAr(){var e;this.isUsingArTrack=!1,(e=this.arTrack)==null||e.stop(),this.arTrack=void 0,this.update()}clear(){var e;(e=this.videoContext)==null||e.disconnect(),delete this.destination,delete this.cameraNode,delete this.mirrorNode,delete this.screenNode,delete this.waterMarkNode}};var i_=0;var Bo=class extends V{constructor(e){super("room");this.seq=++i_;this.role="anchor";this.localTracks=new Set;this.enableAutoPlayDialog=!0;this.autoReceiveAudio=!0;this.autoReceiveVideo=!0;this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null};this._isUsingCachedSchedule=!1;this._log=A.createLogger({id:`r${this.seq}`});this._joinedTimestamp=0;this.isDestroyed=!1;this.useStringRoomId=!!e.useStringRoomId,ue(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),ue(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),ue(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new xl({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new Pl({room:this}),this.badCaseDetector=new wl({room:this}),this.audioManager=new no(this),this.videoManager=new Uo(this)}get isMainStreamPublished(){for(let e of this.localTracks)if(e.mediaType&4)return!0;return!1}get isAuxStreamPublished(){for(let e of this.localTracks)if(e.mediaType&2)return!0;return!1}get hasAuxStream(){for(let e of this.remotePublishedUserMap.values())if(e.muteState.hasAuxiliary)return!0;return this.isAuxStreamPublished}getLogger(){return this._log}get isJoining(){return this.state.toString()==="joining"}get isJoined(){return this.state==="joined"}get isLeft(){return this.state==="left"}addTrack(e){return p(this,null,function*(){return this.publish(e)})}removeTrack(e){return p(this,null,function*(){return this.unpublish(e)})}replaceTrack(e){return p(this,null,function*(){})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(Q(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(Be(e)){let{websocketProxy:t,webtransportProxy:s,loggerProxy:n,scheduleProxy:o,unifiedProxy:a}=e;this.proxy_ws=t,this.proxy_wt=s,this.proxy_unified=a,a?(Ra([a,a]),yi(`https://${a}`)):(n&&yi(n),o&&Ra(o))}T.once(f.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:mi.main,sched_back_domain:mi.backup,signal_domain:this.proxy_ws||this.proxy_wt||""}))}getRemoteAudioStats(){return p(this,null,function*(){let e={};return this.remotePublishedUserMap.forEach(t=>{e[t.userId]=t.remoteAudioTrack.stat}),e})}getTransportStats(){return p(this,null,function*(){var t;let e={rtt:((t=this.quality)==null?void 0:t.uplinkRTT)||0,downlinksRTT:{}};if(this.quality)for(let s of this.quality.downlinkInfo)e.downlinksRTT[s.userId]=s.rtt;return e})}getRemoteVideoStats(){return p(this,arguments,function*(e="main"){let t={};return this.remotePublishedUserMap.forEach(s=>{let n=e==="auxiliary"?s.remoteAuxiliaryTrack:s.remoteVideoTrack;t[s.userId]=n.stat}),t})}checkDestroy(){if(this.isDestroyed)throw new C({code:I.INVALID_OPERATION,message:D({key:v.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(Ee.INVALID_DESTROY),new C({code:I.INVALID_OPERATION,message:D({key:v.INVALID_DESTROY})});this._log.info("destroy room"),this.audioManager.destroy(),this.videoManager.destroy(),this.keyPointManager.destroy(),this.callDurationCalculator.destroy(),this.badCaseDetector.destroy(),this.isDestroyed=!0,T.emit(f.ROOM_DESTROY,{room:this})}schedule(e,t){return p(this,null,function*(){var n,o;let s=B();try{let{isCached:a,result:c,detailCost:d}=yield Ud({userId:this.userId,sdkAppId:this.sdkAppId,roomId:e,useStringRoomId:this.useStringRoomId,version:Se,userSig:this.userSig,frameWorkType:t});this._isUsingCachedSchedule=a,this._log.info(`schedule cache:${+a} ${dt(c,{keysToExclude:["username","credential"]})}`),a&&T.once(f.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=N(N({},this.scheduleResult),c),re((n=c.config)==null?void 0:n.retryCount)&&ta(c.config.retryCount),Q((o=c.config)==null?void 0:o.loggerDomain)&&yi(c.config.loggerDomain),T.emit(f.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:d}),w.addSuccessEvent({key:521700,cost:B()-s,split:50})}catch(a){throw w.addFailedEvent({key:521700,error:a}),a}})}};var Wl=Ae(ke());var dd=Ae(Zc()),Ul=r=>{let i=ce(r),e={audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0};return i.media.forEach((t,s)=>{var n;if(t.ssrcs&&!E(t.ssrcs[0].id)){let o=Number(t.ssrcs[0].id),a=Number((n=t.ssrcs.filter(c=>c.attribute==="cname")[1])==null?void 0:n.id);switch(s){case 0:e.audioSsrc=o;break;case 1:e.bigVideoSsrc=o,e.bigVideoRtxSsrc=a;break;case 2:e.smallVideoSsrc=o,e.smallVideoRtxSsrc=a;break;case 3:e.auxVideoSsrc=o,e.auxVideoRtxSsrc=a;break}}}),e},Bl=(r,i)=>{var a,c;let e=ce(r),t={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],extensions:[]},useDataChannel:i};t.ice.ufrag=String(e.media[0].iceUfrag),t.ice.password=e.media[0].icePwd||"",e.fingerprint&&(t.dtls.hash=e.fingerprint.type,t.dtls.fingerprint=e.fingerprint.hash,t.dtls.setup=e.setup||""),e.media[0].fingerprint&&(t.dtls.hash=e.media[0].fingerprint.type,t.dtls.fingerprint=e.media[0].fingerprint.hash),t.dtls.setup=e.media[0].setup||"";let s=e.media[0],n=e.media[1];s.ext&&(t.audio.extensions=s.ext.map(d=>({id:d.value,uri:d.uri}))),n.ext&&(t.video.extensions=n.ext.map(d=>({id:d.value,uri:d.uri})));let o={codec:s.rtp[0].codec,fmtp:s.fmtp[0].config,payload:s.fmtp[0].payload,rate:s.rtp[0].rate,channel:s.rtp[0].encoding,rtcpFb:[],rtx:0};(a=s.rtcpFb)==null||a.forEach(({payload:d,type:l,subtype:m})=>{if(d===o.payload){let _={id:l,params:[]};m&&_.params.push(m),o.rtcpFb.push(_)}}),t.audio.codecs.push(o);for(let d=0;d<n.rtp.length;d++){if(["rtx","red","ulpfec"].includes(n.rtp[d].codec))continue;let l=n.fmtp.filter(m=>m.payload===n.rtp[d].payload)[0];t.video.codecs.push({payload:n.rtp[d].payload,codec:n.rtp[d].codec,fmtp:l?l.config:"",rate:n.rtp[d].rate,rtx:((c=n.rtp[d+1])==null?void 0:c.codec)==="rtx"?n.rtp[d+1].payload:0,rtcpFb:((n==null?void 0:n.rtcpFb)||[]).filter(m=>m.payload===n.rtp[d].payload).map(({type:m,subtype:_})=>({id:m,params:_?[_]:[]}))})}return t},$l=({serverAbility:r,clientAbility:i,offerSDP:e,enableCustomMessage:t})=>{let s=ce(e),n={extmapAllowMixed:"extmap-allow-mixed",groups:s.groups,icelite:"ice-lite",media:[],msidSemantic:{semantic:"",token:"WMS"},name:"-",origin:{address:"127.0.0.1",username:"-",sessionId:String(Date.now()),sessionVersion:1,netType:"IN",ipVer:4},timing:{start:0,stop:0},version:0},o={candidates:r.candidates.map(a=>({component:1,foundation:"1",generation:0,ip:a.ip,port:a.port,priority:a.priority,transport:a.foundation,type:a.type})),connection:{version:4,ip:"0.0.0.0"},direction:h.TRANSCEIVER_DIRECTION_RECVONLY,ext:r.audio.extensions.map(a=>({value:a.id,uri:a.uri})),fingerprint:{type:r.dtls.hash,hash:r.dtls.fingerprint},fmtp:[{payload:r.audio.codecs[0].payload,config:r.audio.codecs[0].fmtp}],icePwd:r.ice.password,iceUfrag:r.ice.ufrag,mid:"0",payloads:String(r.audio.codecs[0].payload),port:s.media[0].port,protocol:s.media[0].protocol,type:h.AUDIO,setup:r.dtls.setup,rtcpFb:r.audio.codecs[0].rtcpfb.map(a=>({payload:r.audio.codecs[0].payload,type:a.id,subtype:a.params[0]})),rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[{payload:r.audio.codecs[0].payload,codec:r.audio.codecs[0].codec,rate:r.audio.codecs[0].rate,encoding:r.audio.codecs[0].channels}]};return n.media.push(o),[1,2,3].forEach(a=>{n.media.push(ud({mid:a,serverAbility:r,clientAbility:i,parsedOffer:s}))}),t&&n.media.push(s.media.find(a=>a.mid==="dc")),et(n)},ud=({mid:r,serverAbility:i,clientAbility:e,parsedOffer:t,useAllCodec:s=!1})=>{let n={candidates:i.candidates.map(o=>({component:1,foundation:"1",generation:0,ip:o.ip,port:o.port,priority:o.priority,transport:o.foundation,type:o.type})),connection:{version:4,ip:"0.0.0.0"},direction:h.TRANSCEIVER_DIRECTION_RECVONLY,ext:i.video.extensions.map(o=>({value:o.id,uri:o.uri})),fingerprint:{type:i.dtls.hash,hash:i.dtls.fingerprint},fmtp:[],icePwd:i.ice.password,iceUfrag:i.ice.ufrag,mid:String(r),payloads:"",port:t.media[0].port,protocol:t.media[0].protocol,type:h.VIDEO,setup:i.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(i.video.codecs.length>0)if(s)for(let o=0;o<i.video.codecs.length;o++)$o(n,i.video.codecs[o]);else{let o=i.video.codecs.findIndex(a=>a.codec.toLowerCase()===(i.useVp8?"vp8":"h264"));$o(n,i.video.codecs[o])}else if(s)for(let o=0;o<e.video.codecs.length;o++)$o(n,e.video.codecs[o]);else $o(n,e.video.codecs[0]);return n.payloads=n.payloads.trim(),n},$o=(r,i)=>{r.payloads=`${r.payloads} ${i.payload}`,r.fmtp.push({payload:i.payload,config:i.fmtp}),r.rtcpFb=[...r.rtcpFb||[],...(i.rtcpfb||i.rtcpFb).map(e=>({payload:i.payload,type:e.id,subtype:e.params[0]}))],r.rtp.push({payload:i.payload,codec:i.codec.toUpperCase(),rate:i.rate}),i.rtx&&(r.payloads=`${r.payloads} ${i.rtx}`,r.fmtp.push({payload:i.rtx,config:`apt=${i.payload}`}),r.rtp.push({payload:i.rtx,codec:"rtx",rate:i.rate}))};function r_(r){let i=new Set(["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"]);r.ext&&(r.ext=r.ext.filter(e=>!i.has(e.uri)))}function s_(r){if(!r.rtcpFb)return;let i=[];r.rtcpFb.forEach((e,t)=>{var s;i.push(e),r.rtcpFb&&((s=r.rtcpFb[t+1])==null?void 0:s.payload)!==e.payload&&e.type!=="rrtr"&&i.push({payload:e.payload,type:"rrtr"})}),r.rtcpFb=i}function n_(r){r.type===h.VIDEO&&r.fmtp&&r.fmtp.forEach(i=>{i.config.includes("apt")||(i.config+=";sps-pps-idr-in-keyframe=1")})}function o_(r){r.type===h.AUDIO&&r.fmtp&&r.fmtp.forEach(i=>{i.config+=";sprop-stereo=1;stereo=1"})}var Hl=r=>{let i=dd.default.parse(r);return i.media.forEach(e=>{var t;(e.type===h.AUDIO||e.type===h.VIDEO)&&(s_(e),n_(e),o_(e),r_(e)),((t=e.payloads)==null?void 0:t.includes("datachannel"))&&i.groups&&e.mid&&(i.groups[0].mids=i.groups[0].mids.replace(e.mid,"dc"),e.mid="dc")}),dd.default.write(i)};var Ys=class{constructor(i,e=!1){this.dataView=i;this.isSEI&&(e?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let i=this.seiPayloadStartIndex,e=this.dataView.byteLength-2,t=[],s=0;for(let o=i;o<=e;o++){let a=this.dataView.getInt8(o);switch(a){case 0:case 1:case 2:case 3:s===2&&(t.push(3),s=0),a==0?s++:s=0,t.push(a);break;default:s=0,t.push(a);break}}t.push(this.dataView.getInt8(this.dataView.byteLength-1));let n=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=n}removePreventionByte(){let i=this.seiPayloadStartIndex,e=this.dataView.byteLength-1,t=[],s=0;for(let o=i;o<=e;o++)switch(this.dataView.getInt8(o)){case 0:s++,t.push(this.dataView.getInt8(o));break;case 3:s!==2&&t.push(this.dataView.getInt8(o)),s=0;break;default:t.push(this.dataView.getInt8(o)),s=0;break}let n=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=n}get isSEI(){return this.dataView.getUint8(4)===6}get seiPayloadStartIndex(){let i=6;for(let e=6;e<this.dataView.buffer.byteLength&&(i++,this.dataView.getUint8(e)===255);e++);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++){let o=this.dataView.getUint8(n);if(e++,o===255)i+=255;else{i+=o;break}}let t=new ArrayBuffer(i),s=new DataView(t);for(let n=0;n<t.byteLength;n++,e++)s.setInt8(n,this.dataView.getInt8(e));return s}};var ld=class{constructor(i,e){this._singlePC=i;this._log=e;u(this,"_seiMessageList",[]);u(this,"_smallSeiMessageList",[]);u(this,"_seiPayloadType",243);u(this,"_seiAbortMap",new Map);u(this,"_nonSeiAbortMap",new Map);u(this,"onSEIMessage",null)}isRunning(i){return this._seiAbortMap.has(i)}start(i){let e=i.direction===h.TRANSCEIVER_DIRECTION_SENDONLY,t=(e?i.sender:i.receiver).createEncodedStreams(),s=t.readable,n=t.writable,o=new TransformStream({transform:e?(c,d)=>this.encodeVideoFrame(c,d,i):(c,d)=>this.decodeVideoFrame(c,d,i)}),a=new AbortController;s.pipeThrough(o).pipeTo(n,a).catch(c=>{c!=="destroy"&&this._log.warn(c)}),this._seiAbortMap.set(i,a)}restart(i){this.stop(i),this.start(i)}stop(i){var e;(e=this._seiAbortMap.get(i))==null||e.abort(),this._seiAbortMap.delete(i)}destroy(){this._seiAbortMap.forEach(i=>i.abort("destroy")),this._seiAbortMap.clear(),this._nonSeiAbortMap.forEach(i=>i.abort("destroy")),this._nonSeiAbortMap.clear(),this.onSEIMessage=null}handleEncodedStreams(){try{this._singlePC.getPeerConnection().getTransceivers().forEach((e,t)=>{var s,n;if(!(e.direction==="inactive"||!e.mid))if(t<4)t===1||t===2?this.isRunning(e)||this.start(e):this._nonSeiAbortMap.has(e)||this.pipeSenderOrReceiver(e);else{let o=(t-4)%3===1,a=(t-4)%3===2;((n=(s=e.receiver)==null?void 0:s.track)==null?void 0:n.kind)===h.VIDEO&&(o||a)?this.isRunning(e)||this.start(e):this._nonSeiAbortMap.has(e)||this.pipeSenderOrReceiver(e)}})}catch(i){this._log.warn(i)}}pipeSenderOrReceiver(i){let t=i.direction===h.TRANSCEIVER_DIRECTION_SENDONLY?i.sender:i.receiver,{readable:s,writable:n}=t.createEncodedStreams(),o=new AbortController;this._nonSeiAbortMap.set(i,o),s.pipeTo(n,o).catch(()=>{})}push(i,e){var s,n;e&&e.seiPayloadType&&(this._seiPayloadType=e.seiPayloadType),this._seiMessageList.push(i),((n=(s=this._singlePC.getPeerConnection())==null?void 0:s.getSenders()[2])==null?void 0:n.track)&&this._smallSeiMessageList.push(i)}hasSEI(i){let e=new DataView(i);return e.getInt32(0)===1&&e.getInt8(4)===6}isEmptyFrame(i){return i.type==="empty"||i.data.byteLength===0}getNaluCount(i){let e=0,t=0,s=new DataView(i);for(let n=0;n<i.byteLength;n++)switch(s.getUint8(n)){case 0:e++;break;case 1:(e===2||e===3)&&t++,e=0;break;default:e=0;break}return t}encodeVideoFrame(i,e,t){try{let s=Number(t.mid)===2?this._smallSeiMessageList:this._seiMessageList;if(this._singlePC.isUsingH264&&s.length>0&&!this.isEmptyFrame(i)){let n=this.getNaluCount(i.data),o=9-n;if(o<=0)return;let a=s.splice(0,o).reverse().map(this.encodeSEINalu.bind(this)),c=a.reduce((g,R)=>g+R.dataView.byteLength,0),d=new ArrayBuffer(c+i.data.byteLength),l=new DataView(d),m=new DataView(i.data),_=0;for(let g=0;g<a.length;g++)for(let R=0;R<a[g].dataView.byteLength;R++)l.setInt8(_++,a[g].dataView.getInt8(R));for(let g=0;g<i.data.byteLength;g++)l.setInt8(_++,m.getInt8(g));i.data=d,this._log.debug(`${a.length} sei sent`)}}catch(s){this._log.warn(s)}e.enqueue(i)}decodeVideoFrame(i,e,t){try{if(this._singlePC.isUsingH264&&!this.isEmptyFrame(i)&&this.hasSEI(i.data)){let s=[],n=new DataView(i.data),o=0,a=-1,c=-1;for(let d=0;d<i.data.byteLength;d++){let l=n.getUint8(d);if(l===0)o++;else if(l===1){if(o===2||o===3){let m=d-o;if(a===-1?a=m:c===-1&&(c=m,s.push(new Ys(new DataView(n.buffer.slice(a,c)))),a=m,c=-1),!(n.getUint8(d+1)===6)){i.data=new DataView(n.buffer.slice(m)).buffer;break}}o=0}else o=0}this._log.debug(`${s.length} sei received`),X(this.onSEIMessage)&&s.reverse().forEach(d=>{let l=Number(t.mid);this.onSEIMessage({seiPayloadType:d.seiPayloadType,data:d.seiPayload.buffer,mid:l,streamType:(l-4)%3===2?"auxiliary":"main"})})}}catch(s){this._log.warn(s)}e.enqueue(i)}encodeSEINalu(i){let e=i.byteLength,t=parseInt(String(e/255),10),s=e%255,n=[];n.push(0,0,0,1,6,this._seiPayloadType);for(let a=0;a<t;a++)n.push(255);n.push(s);let o=new DataView(i);return n.push(...new Uint8Array(o.buffer)),n.push(128),new Ys(new DataView(new Uint8Array(n).buffer),!0)}},Fl=ld;var Dt=(c=>(c.TRACK="track",c.DATA_CHANNEL_MESSAGE="data_channel_msg",c[c.CONNECTION_STATE_CHANGED="connection-state-changed"]="CONNECTION_STATE_CHANGED",c[c.FIREWALL_RESTRICTION="firewall-restriction"]="FIREWALL_RESTRICTION",c.RECONNECTED="spc-reconnected",c.RECONNECT_FAILED="spc-reconnect-failed",c.ERROR="error",c.SEI_MESSAGE="sei-message",c))(Dt||{}),Jl=0,jl=!1,a_=new Set,c_=r=>Jl>2&&!jl&&a_.size===0&&r,d_=1,ri=class extends Wl.default{constructor({signalChannel:e,room:t,enableCustomMessage:s}){super();u(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0});u(this,"currentState","DISCONNECTED");u(this,"_room");u(this,"_signalChannel");u(this,"_peerConnection",null);u(this,"_datachannel",null);u(this,"_enableCustomMessage");u(this,"_log");u(this,"_downlinkMIDMap",new Map);u(this,"_downlinkMIDUserIDMap",new Map);u(this,"_reconnectionTimer",-1);u(this,"reconnectionCount",0);u(this,"clientAbility");u(this,"_serverAbility",null);u(this,"addDownlinkQueue",new Set);u(this,"removeDownlinkQueue",new Set);u(this,"_parsedAnswer",null);u(this,"_updateSDPPromise",null);u(this,"_waitForPCConnectedPromise");u(this,"_waitForPCConnectedPromiseReject",null);u(this,"_isSDPLogged",!1);u(this,"seiCodec",null);this._room=t,this._enableCustomMessage=s,this._signalChannel=e,this._log=A.createLogger({id:`spc${d_++}`,userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableSEI&&Ei&&(this._log.info("create sei codec"),this.seiCodec=new Fl(this,this._log),this.seiCodec.onSEIMessage=n=>{this.emit("sei-message",{userId:this._downlinkMIDUserIDMap.get(n.mid),data:n.data,seiPayloadType:n.seiPayloadType,streamType:n.streamType})})}get isH264EncodeSupported(){let e=this._room.checkSystemResult.detail.isH264EncodeSupported;return this._serverAbility&&(e=e&&!!this._serverAbility.video.codecs.find(t=>t.codec.toLowerCase()==="h264")),e}get isVP8EncodeSupported(){let e=this._room.checkSystemResult.detail.isVp8EncodeSupported;return this._serverAbility&&(e=e&&this._serverAbility.useVp8),e}get videoCodec(){var e;return(e=this._serverAbility)!=null&&e.useVp8?"vp8":"h264"}get isUsingH264(){return this.videoCodec==="h264"}get uplinkSSRC(){return this._peerConnection&&this._peerConnection.localDescription?Ul(this._peerConnection.localDescription.sdp):{audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0}}get isReconnecting(){return this.currentState==="RECONNECTING"||this._reconnectionTimer>0||this.reconnectionCount>0}get dtlsTransport(){if(!this._peerConnection)return null;let e=this._peerConnection.getSenders();return e.length===0?null:e[0].transport}initialize(){return p(this,null,function*(){let e;try{return this._peerConnection=new RTCPeerConnection({encodedInsertableStreams:this._room.enableSEI&&Ei,offerExtmapAllowMixed:!0,iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._room.sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"}),this._peerConnection.oniceconnectionstatechange=()=>{if(!this._peerConnection)return;let t=this._peerConnection.iceConnectionState;this._log.debug(`ice state: ${t}`),t==="checking"&&this.stat.iceStartTime===0?this.stat.iceStartTime=Date.now():t==="connected"&&this.stat.iceEndTime===0&&(this.stat.iceEndTime=Date.now())},this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this._peerConnection.ontrack=t=>this.emit("track",t),this._enableCustomMessage&&(this._datachannel=this._peerConnection.createDataChannel(`${this._room.userId}dc`),this._datachannel.binaryType="arraybuffer",this._datachannel.onopen=()=>{this._log.info("datachannel open")},this._datachannel.onclose=()=>{this._log.warn("datachannel close")},this._datachannel.onmessage=t=>{let s=new md(t.data);this.emit("data_channel_msg",{data:s})},this._datachannel.onerror=t=>{this._log.warn("datachannel error",t)}),this._peerConnection.addTransceiver(h.AUDIO,{direction:h.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:h.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:h.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:h.TRANSCEIVER_DIRECTION_SENDONLY}),e=yield this._peerConnection.createOffer(),yield this.setOffer(e),this.dtlsTransport&&(this.dtlsTransport.onstatechange=()=>{let{dtlsTransport:t}=this;!t||(this._log.debug(`dtls state: ${t.state}`),t.state==="connecting"&&this.stat.dtlsStartTime===0?this.stat.dtlsStartTime=Date.now():t.state==="connected"&&this.stat.dtlsEndTime===0&&(this.stat.dtlsEndTime=Date.now()))}),this.clientAbility=Bl(e.sdp,this._enableCustomMessage),w.addSuccessEvent({key:521707}),this.clientAbility}catch(t){throw w.addFailedEvent({key:521707,error:t}),this._log.error(`initialize failed ${t}
77
+ }`,Vo=class extends wr{constructor(e,t){super(e,t.input,{name:"vb",create2d:!1,useDefaultProgram:!1,useFbo:!1,createTexture:!0});u(this,"ready",!1);u(this,"_bgTexture");u(this,"_waterMarkTexture");u(this,"_lastMaskTexture");u(this,"_lastMaskFbo");u(this,"_textureValid",!1);u(this,"_selfieTextureValid",!1);u(this,"_selfieSegmentation");u(this,"wasm");u(this,"_prePrograme");u(this,"_segmentationMask");u(this,"_weixin",!1);this._selfieSegmentation=t.selfieSegmentation,this._selfieSegmentation.onResults=this.onPredict.bind(this),this.init(t).catch(()=>this.context.destroy(new Error("selfie_segmentation init faild")))}init(e){return p(this,null,function*(){let t=e.Wasm,s=this.context.ctx;if(this.wasm=new t.AllIn1(s),this.wasm.blurRadius=e.blurRadius||3,this.wasm.mirror=!!e.mirror,this.wasm.vbMode=e.bg==="blur"?1:e.bg instanceof HTMLImageElement?2:e.bg==="green"?3:0,e.waterMark){let{x:n,y:o,width:a,height:c}=e.waterMark;this.wasm.setWaterMark(n,o,a,c)}if(this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),s.uniform1i(s.getUniformLocation(this.program,"mask"),1),e.bg instanceof HTMLImageElement&&(s.uniform1i(s.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(e.bg)),e.waterMark&&(s.uniform1i(s.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(e.waterMark.image)),s.uniform1i(s.getUniformLocation(this.program,"lastMask"),4),this._weixin){let n=this.context.createShader(s.FRAGMENT_SHADER,t_),o=this.context.createShader(s.VERTEX_SHADER,e_);this._prePrograme=this.context.createProgram(o,n),s.useProgram(this._prePrograme),this.setAttributes(this.positionBuffer,this.texCoordBuffer),s.uniform1i(s.getUniformLocation(this._prePrograme,"mask"),1)}this.ready=!0})}onPredict(e){let t=this.context.ctx;this._weixin&&(this._lastMaskTexture||(this._lastMaskTexture=this.createTexture(this.image),this._lastMaskFbo=this.createFramebuffer(this._lastMaskTexture))),this.useProgram(),this._weixin?this.useTexture():this._selfieSegmentation.bindTexture(),t.activeTexture(t.TEXTURE1),this._selfieSegmentation.bindTexture2d(e),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),this.useBufferFrame(),t.drawArrays(t.TRIANGLE_STRIP,0,4),this._segmentationMask=e,this.totalFrames++}render(e){let t=this.context.ctx;if(typeof this.image.getVideoPlaybackQuality=="function"&&!ui){let c=this.image.getVideoPlaybackQuality().totalVideoFrames;if(this._totalFrames===c)return!1;this._totalFrames=c,this.dropFrames=this._totalFrames-this.totalFrames}let{videoWidth:s,videoHeight:n}=this.image;this.image.width=s,this.image.height=n;let o=!1;if(this.totalFrames)this._weixin?this.useTexture():this._selfieSegmentation.bindTexture(),o=this._selfieTextureValid,this._selfieTextureValid=!0;else{if(this.program)this.useTexture();else return!1;o=this._textureValid,this._textureValid=!0}return this.width!==s||this.height!==n||!o?(this.resize(s,n),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.image)):t.texSubImage2D(t.TEXTURE_2D,0,0,0,t.RGBA,t.UNSIGNED_BYTE,this.image),this.ready&&(this._weixin&&(t.useProgram(this._prePrograme),this.useTexture(),this._segmentationMask&&(t.activeTexture(t.TEXTURE1),this._selfieSegmentation.bindTexture2d(this._segmentationMask),t.bindFramebuffer(t.FRAMEBUFFER,this._lastMaskFbo||null)),t.drawArrays(t.TRIANGLE_STRIP,0,4),this._selfieSegmentation.bindTexture(),this._segmentationMask?t.copyTexSubImage2D(t.TEXTURE_2D,0,0,0,0,0,s,n):t.copyTexImage2D(t.TEXTURE_2D,0,t.RGBA,0,0,s,n,0)),this._selfieSegmentation.send(s,n)),this.totalFrames||(t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),t.drawArrays(t.TRIANGLE_STRIP,0,4)),!1}close(){var t;super.close();let e=this.context.ctx;this._bgTexture&&e.deleteTexture(this._bgTexture),this._waterMarkTexture&&e.deleteTexture(this._waterMarkTexture),this._lastMaskTexture&&e.deleteTexture(this._lastMaskTexture),this._lastMaskFbo&&e.deleteFramebuffer(this._lastMaskFbo),this._prePrograme&&e.deleteProgram(this._prePrograme),(t=this.wasm)==null||t.close()}};var Uo=class extends Vl.EventEmitter{constructor(e){super();this.room=e;u(this,"videoContext");u(this,"_glVideoContext");u(this,"_2dVideoContext");u(this,"destination");u(this,"smallVideoContext");u(this,"smallDestination");u(this,"smallTrackSource");u(this,"smallImageSource");u(this,"_isMirror",!1);u(this,"cameraTrack");u(this,"cameraNode");u(this,"mirrorNode");u(this,"mixNode");u(this,"screenTrack");u(this,"screenNode");u(this,"selfModel",!1);u(this,"blurRadius",3);u(this,"arTrack");u(this,"Wasm");u(this,"waterMarkNode");u(this,"_waterMarkOption");u(this,"watermarkImageList",[]);u(this,"_isMixScreen",!1);u(this,"_virtualBackground");u(this,"virtualBackgroundInstance");u(this,"isUsingArTrack",!1);u(this,"_bgAssetPath");u(this,"log",A.createLogger({id:"vm"}));u(this,"_checkId",0);u(this,"_use2d",!1);u(this,"_autoSwitchRenderMode",!0);u(this,"_selfieSegmentation");e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new je({frameRate:15,logger:this.log,name:"s"}),this.enablePrintDetail()}get _hasVirtualBg(){return!!this._virtualBackground}get _hasWaterMark(){return this.watermarkImageList.length>0}get renderMode(){return this._autoSwitchRenderMode?"auto":this._use2d?"2d":"webgl"}set renderMode(e){if(this._autoSwitchRenderMode=e==="auto",this._autoSwitchRenderMode)return;let t=e==="2d";this._use2d!==t&&(this._use2d=t,this.clear(),this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.update())}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new je({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this.sendCreateResult("videoCtx2d",this._2dVideoContext.ctx?void 0:new Error("create 2d context failed")),this._2dVideoContext}getGlVideoContext(){if(!this._glVideoContext)this._glVideoContext=new Ie({frameRate:15,logger:this.log,name:"m"});else if(this._glVideoContext.available)return this._glVideoContext;try{this._glVideoContext.create(),this.sendCreateResult(),this._glVideoContext.on("unavailable",(e,t)=>{this.emit("error",{reason:e,error:t}),this.log.warn("video context unavailable",e,t),this.sendCreateResult("videoCtxGl",t||new Error(e)),this.update()})}catch(e){this.emit("error",{reason:"create",error:e}),this.sendCreateResult("videoCtxGl",e)}return this._glVideoContext}enablePrintDetail(e=2e3){this._checkId=Z.run(Oi,()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:e})}destroy(){var e,t;(e=this._2dVideoContext)==null||e.destroy(),(t=this._glVideoContext)==null||t.destroy(),this.smallVideoContext.destroy(),Z.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(ui||this._isMixScreen||this._isMirror||this._hasWaterMark||this._hasVirtualBg)&&this.checkOrCreateVideoContext()}sendCreateResult(e="videoCtxGl",t){let s=e==="videoCtxGl"?512700:512701;t?w.addFailedEvent({key:s,error:t}):w.addSuccessEvent({key:s})}checkOrCreateVideoContext(){let e=this._use2d;if(this._autoSwitchRenderMode&&(this._use2d=!this._hasVirtualBg),this.videoContext)if(this.videoContext.available){let t=!this.videoContext.hasAlpha&&this.needAlpha;if(this._autoSwitchRenderMode&&e===this._hasVirtualBg)this.clear();else if(t)if(this._use2d)this.clear();else return!0;else return!0}else this.clear(),this._use2d=!0;return this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.videoContext.available}get smallTrack(){var e;return(e=this.smallDestination)==null?void 0:e.videoTrack}get hasSmall(){return!!this.smallTrack}get initialTrack(){var e;return(e=this.cameraTrack)==null?void 0:e.mediaTrack}initVirtualBackground(e){return this._selfieSegmentation=e,this._selfieSegmentation.changeModel()}_setMainOutput(e){var t;try{let s=this.cameraTrack,{small:n,settings:o,player:a}=s;n?(this.smallVideoContext.available||(this.smallVideoContext.create({alpha:!1}),this.smallDestination=new Lo(this.smallVideoContext,n)),this.smallVideoContext.frameRate=n.frameRate,this.smallDestination.resolution=n,e?(this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=e:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(e),this.smallImageSource.connect(this.smallDestination))):(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource?this.smallTrackSource.replaceTrack(this.initialTrack):(this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack),this.smallTrackSource.width=o.width,this.smallTrackSource.height=o.height,this.smallTrackSource.connect(this.smallDestination)))):this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource),ui&&a.setCanvas(e);let c=e&&((t=this.destination)==null?void 0:t.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),c=this.arTrack),this._selfieSegmentation&&e&&!this._use2d&&(this._selfieSegmentation._glName||this._selfieSegmentation.setCanvas(e)),this.log.info(`set main output ${c?c.label:"no output track"}`),s.setOutputMediaStreamTrack(c)}catch(s){this.log.error("set main output failed",s)}}update(){return p(this,null,function*(){var s,n;if(!this.cameraTrack||!this.cameraTrack.mediaTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:e,profile:t}=this.cameraTrack;if(this._use2d||!this._virtualBackground?(this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination"})),this.cameraNode?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack),this.cameraNode.resize(e.width,e.height))):(this.cameraNode&&this.cameraNode.close(),this.destination||(this.destination=new ko(this.videoContext,{name:"mainDestination"})),this.cameraNode=new Vo(this.videoContext,{input:this.cameraTrack.mediaTrack,mirror:this._isMirror,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,selfieSegmentation:this._selfieSegmentation,Wasm:this.Wasm}),this.cameraNode.connect(this.destination)),this.videoContext.frameRate=t.frameRate,this._use2d){let o=this.cameraNode;o.disconnect(),this._isMirror&&(this.mirrorNode||(this.mirrorNode=new Po(this.videoContext)),o=o.connect(this.mirrorNode),o.disconnect(),this.log.info("start mirror")),this.mixNode&&this.mixNode.close(),delete this.mixNode,(this._isMixScreen||this._hasWaterMark)&&(this.mixNode=new wo(this.videoContext),o.connect(this.mixNode,{zIndex:1}),this._hasWaterMark&&!this.waterMarkNode&&this._waterMarkOption&&(this.waterMarkNode=this.videoContext.createVideoImageSource(this._waterMarkOption.image,{autoResize:!1}),this.waterMarkNode.resize(this._waterMarkOption.width,this._waterMarkOption.height),this.waterMarkNode.x=this._waterMarkOption.x,this.waterMarkNode.y=this._waterMarkOption.y),(s=this.waterMarkNode)==null||s.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&!this.screenNode&&(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack)),(n=this.screenNode)==null||n.connect(this.mixNode,{zIndex:0}),o=this.mixNode,this.log.info("start mix",`${this.mixNode.width}x${this.mixNode.height}`)),o.connect(this.destination)}return this.log.info(`update ${this._use2d?"2d":"webgl"}`),this._setMainOutput(this.videoContext._canvas)})}changeInput(e){var t,s,n,o;if(e instanceof Ge)return this.log.info("change screen input",(t=e.mediaTrack)==null?void 0:t.label),this.setScreenTrack(e);if(e instanceof ae)return this.log.info("change video input",(s=e.mediaTrack)==null?void 0:s.label),this.setCameraTrack(e);if(e instanceof vt){this.log.info("change remote input",(n=e.mediaTrack)==null?void 0:n.label);let a=e.mediaTrack;if(as===17&&!e.source&&e.player.element){let c=new je({frameRate:15,logger:this.log,name:e.userId});c.create({alpha:!1});let d=c.createVideoImageSource(e.player.element);e.source=d;let l=new Qs(c);d.connect(l),e.player.setCanvas(c._canvas)}return e.setOutputMediaStreamTrack(a)}this.log.warn("change unknown input",(o=e.mediaTrack)==null?void 0:o.label)}removeInput(e){var t;e instanceof Ge?((t=this.screenNode)==null||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof ae?(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof vt&&e.source&&e.source.context.destroy()}setCameraTrack(e){return p(this,null,function*(){this.cameraTrack=e,this.update()})}setScreenTrack(e){return this.screenTrack=e,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)}getWatermarkImage(e,t){return p(this,null,function*(){let s=document.createElement("canvas");t&&e&&(s.height=t,s.width=e);let n=s.getContext("2d");if(!n)throw new C({code:I.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort((o,a)=>o.zIndex-a.zIndex),this.watermarkImageList.forEach(({image:o,x:a,y:c,width:d,height:l})=>{n.drawImage(o,a,c,d,l)}),Es(s.toDataURL())})}pushWaterMarkImageList(e){let{type:t}=e;this.watermarkImageList.some(n=>n.imageUrl===e.imageUrl&&n.height===e.height&&n.width===e.width&&n.x===e.x&&n.y===e.y&&n.type===e.type&&n.zIndex===e.zIndex)||((t==="mute"||t==="watermark")&&(this.watermarkImageList=this.watermarkImageList.filter(n=>n.type!==t)),this.watermarkImageList.push(e))}setWatermark(e){return p(this,null,function*(){let t;try{t=yield Es((e==null?void 0:e.imageElement)||e.imageUrl)}catch(l){throw new C({code:I.INVALID_PARAMETER,message:`load image failed, url: ${e.imageUrl}`})}let{x:s=0,y:n=0,width:o=t.width,height:a=t.height,type:c="watermark",zIndex:d=2}=e;this.pushWaterMarkImageList({x:s,y:n,width:o,height:a,image:t,zIndex:d,type:c,imageUrl:e.imageUrl}),yield this.freshWatermark(),this.log.info("set watermark",JSON.stringify(this.watermarkImageList))})}deleteWatermark(e="watermark"){return p(this,null,function*(){this.watermarkImageList=this.watermarkImageList.filter(t=>t.type!==e),this.log.info("delete watermark",e,JSON.stringify(this.watermarkImageList)),yield this.freshWatermark()})}freshWatermark(){return p(this,null,function*(){var t,s,n;(t=this.waterMarkNode)==null||t.close(),delete this.waterMarkNode,delete this._waterMarkOption;let e=yield this.getWatermarkImage((s=this.cameraTrack)==null?void 0:s.settings.width,(n=this.cameraTrack)==null?void 0:n.settings.height);this._waterMarkOption={x:0,y:0,width:e.width,height:e.height,image:e},this.update()})}setVirtualBackground(e){return p(this,null,function*(){if(!e)this._virtualBackground=void 0;else{if(this._use2d&&!this._autoSwitchRenderMode)return Promise.reject(new Error("not support virtual background in 2d mode"));this._bgAssetPath=e.assetPath,e.type==="image"?this._virtualBackground=yield Es(e.imageUrl):(this.blurRadius=e.blurRadius||3,this._virtualBackground=e.type)}this.log.info(`${this._virtualBackground?"start":"stop"} visual background, ${(e==null?void 0:e.type)||""}`),this.update()})}get mixScreen(){return this._isMixScreen}set mixScreen(e){var t;this._isMixScreen=e,this._isMixScreen||((t=this.screenNode)==null||t.close(),delete this.screenNode),this.update()}set mirror(e){var t;this._isMirror!==e&&(this._isMirror=e,this._isMirror||((t=this.mirrorNode)==null||t.close(),delete this.mirrorNode),this.update())}get mirror(){return this._isMirror}enableAr(e){this.arTrack=e,this.isUsingArTrack=!0,this.update()}updateAr(){return p(this,null,function*(){var e;!((e=this.cameraTrack)!=null&&e.mediaTrack)||(yield this.virtualBackgroundInstance.ar.updateInputTrack(this.cameraTrack.mediaTrack.clone()))})}disableAr(){var e;this.isUsingArTrack=!1,(e=this.arTrack)==null||e.stop(),this.arTrack=void 0,this.update()}clear(){var e;(e=this.videoContext)==null||e.disconnect(),delete this.destination,delete this.cameraNode,delete this.mirrorNode,delete this.screenNode,delete this.waterMarkNode}};var i_=0;var Bo=class extends V{constructor(e){super("room");this.seq=++i_;this.role="anchor";this.localTracks=new Set;this.enableAutoPlayDialog=!0;this.autoReceiveAudio=!0;this.autoReceiveVideo=!0;this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null};this._isUsingCachedSchedule=!1;this._log=A.createLogger({id:`r${this.seq}`});this._joinedTimestamp=0;this.isDestroyed=!1;this.useStringRoomId=!!e.useStringRoomId,ue(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),ue(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),ue(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new xl({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new Pl({room:this}),this.badCaseDetector=new wl({room:this}),this.audioManager=new no(this),this.videoManager=new Uo(this)}get isMainStreamPublished(){for(let e of this.localTracks)if(e.mediaType&4)return!0;return!1}get isAuxStreamPublished(){for(let e of this.localTracks)if(e.mediaType&2)return!0;return!1}get hasAuxStream(){for(let e of this.remotePublishedUserMap.values())if(e.muteState.hasAuxiliary)return!0;return this.isAuxStreamPublished}getLogger(){return this._log}get isJoining(){return this.state.toString()==="joining"}get isJoined(){return this.state==="joined"}get isLeft(){return this.state==="left"}addTrack(e){return p(this,null,function*(){return this.publish(e)})}removeTrack(e){return p(this,null,function*(){return this.unpublish(e)})}replaceTrack(e){return p(this,null,function*(){})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(Q(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(Be(e)){let{websocketProxy:t,webtransportProxy:s,loggerProxy:n,scheduleProxy:o,unifiedProxy:a}=e;this.proxy_ws=t,this.proxy_wt=s,this.proxy_unified=a,a?(Ra([a,a]),yi(`https://${a}`)):(n&&yi(n),o&&Ra(o))}T.once(f.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:mi.main,sched_back_domain:mi.backup,signal_domain:this.proxy_ws||this.proxy_wt||""}))}getRemoteAudioStats(){return p(this,null,function*(){let e={};return this.remotePublishedUserMap.forEach(t=>{e[t.userId]=t.remoteAudioTrack.stat}),e})}getTransportStats(){return p(this,null,function*(){var t;let e={rtt:((t=this.quality)==null?void 0:t.uplinkRTT)||0,downlinksRTT:{}};if(this.quality)for(let s of this.quality.downlinkInfo)e.downlinksRTT[s.userId]=s.rtt;return e})}getRemoteVideoStats(){return p(this,arguments,function*(e="main"){let t={};return this.remotePublishedUserMap.forEach(s=>{let n=e==="auxiliary"?s.remoteAuxiliaryTrack:s.remoteVideoTrack;t[s.userId]=n.stat}),t})}checkDestroy(){if(this.isDestroyed)throw new C({code:I.INVALID_OPERATION,message:D({key:v.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(Ee.INVALID_DESTROY),new C({code:I.INVALID_OPERATION,message:D({key:v.INVALID_DESTROY})});this._log.info("destroy room"),this.audioManager.destroy(),this.videoManager.destroy(),this.keyPointManager.destroy(),this.callDurationCalculator.destroy(),this.badCaseDetector.destroy(),this.isDestroyed=!0,T.emit(f.ROOM_DESTROY,{room:this})}schedule(e,t){return p(this,null,function*(){var n,o;let s=B();try{let{isCached:a,result:c,detailCost:d}=yield Ud({userId:this.userId,sdkAppId:this.sdkAppId,roomId:e,useStringRoomId:this.useStringRoomId,version:Se,userSig:this.userSig,frameWorkType:t});this._isUsingCachedSchedule=a,this._log.info(`schedule cache:${+a} ${dt(c,{keysToExclude:["username","credential"]})}`),a&&T.once(f.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=N(N({},this.scheduleResult),c),re((n=c.config)==null?void 0:n.retryCount)&&ta(c.config.retryCount),Q((o=c.config)==null?void 0:o.loggerDomain)&&yi(c.config.loggerDomain),T.emit(f.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:d}),w.addSuccessEvent({key:521700,cost:B()-s,split:50})}catch(a){throw w.addFailedEvent({key:521700,error:a}),a}})}};var Wl=Ae(ke());var dd=Ae(Zc()),Ul=r=>{let i=ce(r),e={audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0};return i.media.forEach((t,s)=>{var n;if(t.ssrcs&&!E(t.ssrcs[0].id)){let o=Number(t.ssrcs[0].id),a=Number((n=t.ssrcs.filter(c=>c.attribute==="cname")[1])==null?void 0:n.id);switch(s){case 0:e.audioSsrc=o;break;case 1:e.bigVideoSsrc=o,e.bigVideoRtxSsrc=a;break;case 2:e.smallVideoSsrc=o,e.smallVideoRtxSsrc=a;break;case 3:e.auxVideoSsrc=o,e.auxVideoRtxSsrc=a;break}}}),e},Bl=(r,i)=>{var a,c;let e=ce(r),t={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],extensions:[]},useDataChannel:i};t.ice.ufrag=String(e.media[0].iceUfrag),t.ice.password=e.media[0].icePwd||"",e.fingerprint&&(t.dtls.hash=e.fingerprint.type,t.dtls.fingerprint=e.fingerprint.hash,t.dtls.setup=e.setup||""),e.media[0].fingerprint&&(t.dtls.hash=e.media[0].fingerprint.type,t.dtls.fingerprint=e.media[0].fingerprint.hash),t.dtls.setup=e.media[0].setup||"";let s=e.media[0],n=e.media[1];s.ext&&(t.audio.extensions=s.ext.map(d=>({id:d.value,uri:d.uri}))),n.ext&&(t.video.extensions=n.ext.map(d=>({id:d.value,uri:d.uri})));let o={codec:s.rtp[0].codec,fmtp:s.fmtp[0].config,payload:s.fmtp[0].payload,rate:s.rtp[0].rate,channel:s.rtp[0].encoding,rtcpFb:[],rtx:0};(a=s.rtcpFb)==null||a.forEach(({payload:d,type:l,subtype:m})=>{if(d===o.payload){let _={id:l,params:[]};m&&_.params.push(m),o.rtcpFb.push(_)}}),t.audio.codecs.push(o);for(let d=0;d<n.rtp.length;d++){if(["rtx","red","ulpfec"].includes(n.rtp[d].codec))continue;let l=n.fmtp.filter(m=>m.payload===n.rtp[d].payload)[0];t.video.codecs.push({payload:n.rtp[d].payload,codec:n.rtp[d].codec,fmtp:l?l.config:"",rate:n.rtp[d].rate,rtx:((c=n.rtp[d+1])==null?void 0:c.codec)==="rtx"?n.rtp[d+1].payload:0,rtcpFb:((n==null?void 0:n.rtcpFb)||[]).filter(m=>m.payload===n.rtp[d].payload).map(({type:m,subtype:_})=>({id:m,params:_?[_]:[]}))})}return t},$l=({serverAbility:r,clientAbility:i,offerSDP:e,enableCustomMessage:t})=>{let s=ce(e),n={extmapAllowMixed:"extmap-allow-mixed",groups:s.groups,icelite:"ice-lite",media:[],msidSemantic:{semantic:"",token:"WMS"},name:"-",origin:{address:"127.0.0.1",username:"-",sessionId:String(Date.now()),sessionVersion:1,netType:"IN",ipVer:4},timing:{start:0,stop:0},version:0},o={candidates:r.candidates.map(a=>({component:1,foundation:"1",generation:0,ip:a.ip,port:a.port,priority:a.priority,transport:a.foundation,type:a.type})),connection:{version:4,ip:"0.0.0.0"},direction:h.TRANSCEIVER_DIRECTION_RECVONLY,ext:r.audio.extensions.map(a=>({value:a.id,uri:a.uri})),fingerprint:{type:r.dtls.hash,hash:r.dtls.fingerprint},fmtp:[{payload:r.audio.codecs[0].payload,config:r.audio.codecs[0].fmtp}],icePwd:r.ice.password,iceUfrag:r.ice.ufrag,mid:"0",payloads:String(r.audio.codecs[0].payload),port:s.media[0].port,protocol:s.media[0].protocol,type:h.AUDIO,setup:r.dtls.setup,rtcpFb:r.audio.codecs[0].rtcpfb.map(a=>({payload:r.audio.codecs[0].payload,type:a.id,subtype:a.params[0]})),rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[{payload:r.audio.codecs[0].payload,codec:r.audio.codecs[0].codec,rate:r.audio.codecs[0].rate,encoding:r.audio.codecs[0].channels}]};return n.media.push(o),[1,2,3].forEach(a=>{n.media.push(ud({mid:a,serverAbility:r,clientAbility:i,parsedOffer:s}))}),t&&n.media.push(s.media.find(a=>a.mid==="dc")),et(n)},ud=({mid:r,serverAbility:i,clientAbility:e,parsedOffer:t,useAllCodec:s=!1})=>{let n={candidates:i.candidates.map(o=>({component:1,foundation:"1",generation:0,ip:o.ip,port:o.port,priority:o.priority,transport:o.foundation,type:o.type})),connection:{version:4,ip:"0.0.0.0"},direction:h.TRANSCEIVER_DIRECTION_RECVONLY,ext:i.video.extensions.map(o=>({value:o.id,uri:o.uri})),fingerprint:{type:i.dtls.hash,hash:i.dtls.fingerprint},fmtp:[],icePwd:i.ice.password,iceUfrag:i.ice.ufrag,mid:String(r),payloads:"",port:t.media[0].port,protocol:t.media[0].protocol,type:h.VIDEO,setup:i.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(i.video.codecs.length>0)if(s)for(let o=0;o<i.video.codecs.length;o++)$o(n,i.video.codecs[o]);else{let o=i.video.codecs.findIndex(a=>a.codec.toLowerCase()===(i.useVp8?"vp8":"h264"));$o(n,i.video.codecs[o])}else if(s)for(let o=0;o<e.video.codecs.length;o++)$o(n,e.video.codecs[o]);else $o(n,e.video.codecs[0]);return n.payloads=n.payloads.trim(),n},$o=(r,i)=>{r.payloads=`${r.payloads} ${i.payload}`,r.fmtp.push({payload:i.payload,config:i.fmtp}),r.rtcpFb=[...r.rtcpFb||[],...(i.rtcpfb||i.rtcpFb).map(e=>({payload:i.payload,type:e.id,subtype:e.params[0]}))],r.rtp.push({payload:i.payload,codec:i.codec.toUpperCase(),rate:i.rate}),i.rtx&&(r.payloads=`${r.payloads} ${i.rtx}`,r.fmtp.push({payload:i.rtx,config:`apt=${i.payload}`}),r.rtp.push({payload:i.rtx,codec:"rtx",rate:i.rate}))};function r_(r){let i=new Set(["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"]);r.ext&&(r.ext=r.ext.filter(e=>!i.has(e.uri)))}function s_(r){if(!r.rtcpFb)return;let i=[];r.rtcpFb.forEach((e,t)=>{var s;i.push(e),r.rtcpFb&&((s=r.rtcpFb[t+1])==null?void 0:s.payload)!==e.payload&&e.type!=="rrtr"&&i.push({payload:e.payload,type:"rrtr"})}),r.rtcpFb=i}function n_(r){r.type===h.VIDEO&&r.fmtp&&r.fmtp.forEach(i=>{i.config.includes("apt")||(i.config+=";sps-pps-idr-in-keyframe=1")})}function o_(r){r.type===h.AUDIO&&r.fmtp&&r.fmtp.forEach(i=>{i.config+=";sprop-stereo=1;stereo=1"})}var Hl=r=>{let i=dd.default.parse(r);return i.media.forEach(e=>{var t;(e.type===h.AUDIO||e.type===h.VIDEO)&&(s_(e),n_(e),o_(e),r_(e)),((t=e.payloads)==null?void 0:t.includes("datachannel"))&&i.groups&&e.mid&&(i.groups[0].mids=i.groups[0].mids.replace(e.mid,"dc"),e.mid="dc")}),dd.default.write(i)};var Ys=class{constructor(i,e=!1){this.dataView=i;this.isSEI&&(e?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let i=this.seiPayloadStartIndex,e=this.dataView.byteLength-2,t=[],s=0;for(let o=i;o<=e;o++){let a=this.dataView.getInt8(o);switch(a){case 0:case 1:case 2:case 3:s===2&&(t.push(3),s=0),a==0?s++:s=0,t.push(a);break;default:s=0,t.push(a);break}}t.push(this.dataView.getInt8(this.dataView.byteLength-1));let n=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=n}removePreventionByte(){let i=this.seiPayloadStartIndex,e=this.dataView.byteLength-1,t=[],s=0;for(let o=i;o<=e;o++)switch(this.dataView.getInt8(o)){case 0:s++,t.push(this.dataView.getInt8(o));break;case 3:s!==2&&t.push(this.dataView.getInt8(o)),s=0;break;default:t.push(this.dataView.getInt8(o)),s=0;break}let n=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=n}get isSEI(){return this.dataView.getUint8(4)===6}get seiPayloadStartIndex(){let i=6;for(let e=6;e<this.dataView.buffer.byteLength&&(i++,this.dataView.getUint8(e)===255);e++);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++){let o=this.dataView.getUint8(n);if(e++,o===255)i+=255;else{i+=o;break}}let t=new ArrayBuffer(i),s=new DataView(t);for(let n=0;n<t.byteLength;n++,e++)s.setInt8(n,this.dataView.getInt8(e));return s}};var ld=class{constructor(i,e){this._singlePC=i;this._log=e;u(this,"_seiMessageList",[]);u(this,"_smallSeiMessageList",[]);u(this,"_seiPayloadType",243);u(this,"_seiAbortMap",new Map);u(this,"_nonSeiAbortMap",new Map);u(this,"onSEIMessage",null)}isRunning(i){return this._seiAbortMap.has(i)}start(i){let e=i.direction===h.TRANSCEIVER_DIRECTION_SENDONLY,t=(e?i.sender:i.receiver).createEncodedStreams(),s=t.readable,n=t.writable,o=new TransformStream({transform:e?(c,d)=>this.encodeVideoFrame(c,d,i):(c,d)=>this.decodeVideoFrame(c,d,i)}),a=new AbortController;s.pipeThrough(o).pipeTo(n,a).catch(c=>{c!=="destroy"&&this._log.warn(c)}),this._seiAbortMap.set(i,a)}restart(i){this.stop(i),this.start(i)}stop(i){var e;(e=this._seiAbortMap.get(i))==null||e.abort(),this._seiAbortMap.delete(i)}destroy(){this._seiAbortMap.forEach(i=>i.abort("destroy")),this._seiAbortMap.clear(),this._nonSeiAbortMap.forEach(i=>i.abort("destroy")),this._nonSeiAbortMap.clear(),this.onSEIMessage=null}handleEncodedStreams(){try{this._singlePC.getPeerConnection().getTransceivers().forEach((e,t)=>{var s,n;if(!(e.direction==="inactive"||!e.mid))if(t<4)t===1||t===2?this.isRunning(e)||this.start(e):this._nonSeiAbortMap.has(e)||this.pipeSenderOrReceiver(e);else{let o=(t-4)%3===1,a=(t-4)%3===2;((n=(s=e.receiver)==null?void 0:s.track)==null?void 0:n.kind)===h.VIDEO&&(o||a)?this.isRunning(e)||this.start(e):this._nonSeiAbortMap.has(e)||this.pipeSenderOrReceiver(e)}})}catch(i){this._log.warn(i)}}pipeSenderOrReceiver(i){let t=i.direction===h.TRANSCEIVER_DIRECTION_SENDONLY?i.sender:i.receiver,{readable:s,writable:n}=t.createEncodedStreams(),o=new AbortController;this._nonSeiAbortMap.set(i,o),s.pipeTo(n,o).catch(()=>{})}push(i,e){var s,n;e&&e.seiPayloadType&&(this._seiPayloadType=e.seiPayloadType),this._seiMessageList.push(i),((n=(s=this._singlePC.getPeerConnection())==null?void 0:s.getSenders()[2])==null?void 0:n.track)&&this._smallSeiMessageList.push(i)}hasSEI(i){let e=new DataView(i);return e.getInt32(0)===1&&e.getInt8(4)===6}isEmptyFrame(i){return i.type==="empty"||i.data.byteLength===0}getNaluCount(i){let e=0,t=0,s=new DataView(i);for(let n=0;n<i.byteLength;n++)switch(s.getUint8(n)){case 0:e++;break;case 1:(e===2||e===3)&&t++,e=0;break;default:e=0;break}return t}encodeVideoFrame(i,e,t){try{let s=Number(t.mid)===2?this._smallSeiMessageList:this._seiMessageList;if(this._singlePC.isUsingH264&&s.length>0&&!this.isEmptyFrame(i)){let n=this.getNaluCount(i.data),o=9-n;if(o<=0)return;let a=s.splice(0,o).reverse().map(this.encodeSEINalu.bind(this)),c=a.reduce((g,R)=>g+R.dataView.byteLength,0),d=new ArrayBuffer(c+i.data.byteLength),l=new DataView(d),m=new DataView(i.data),_=0;for(let g=0;g<a.length;g++)for(let R=0;R<a[g].dataView.byteLength;R++)l.setInt8(_++,a[g].dataView.getInt8(R));for(let g=0;g<i.data.byteLength;g++)l.setInt8(_++,m.getInt8(g));i.data=d,this._log.debug(`${a.length} sei sent`)}}catch(s){this._log.warn(s)}e.enqueue(i)}decodeVideoFrame(i,e,t){try{if(this._singlePC.isUsingH264&&!this.isEmptyFrame(i)&&this.hasSEI(i.data)){let s=[],n=new DataView(i.data),o=0,a=-1,c=-1;for(let d=0;d<i.data.byteLength;d++){let l=n.getUint8(d);if(l===0)o++;else if(l===1){if(o===2||o===3){let m=d-o;if(a===-1?a=m:c===-1&&(c=m,s.push(new Ys(new DataView(n.buffer.slice(a,c)))),a=m,c=-1),!(n.getUint8(d+1)===6)){i.data=new DataView(n.buffer.slice(m)).buffer;break}}o=0}else o=0}this._log.debug(`${s.length} sei received`),X(this.onSEIMessage)&&s.reverse().forEach(d=>{let l=Number(t.mid);this.onSEIMessage({seiPayloadType:d.seiPayloadType,data:d.seiPayload.buffer,mid:l,streamType:(l-4)%3===2?"auxiliary":"main"})})}}catch(s){this._log.warn(s)}e.enqueue(i)}encodeSEINalu(i){let e=i.byteLength,t=parseInt(String(e/255),10),s=e%255,n=[];n.push(0,0,0,1,6,this._seiPayloadType);for(let a=0;a<t;a++)n.push(255);n.push(s);let o=new DataView(i);return n.push(...new Uint8Array(o.buffer)),n.push(128),new Ys(new DataView(new Uint8Array(n).buffer),!0)}},Fl=ld;var Dt=(c=>(c.TRACK="track",c.DATA_CHANNEL_MESSAGE="data_channel_msg",c[c.CONNECTION_STATE_CHANGED="connection-state-changed"]="CONNECTION_STATE_CHANGED",c[c.FIREWALL_RESTRICTION="firewall-restriction"]="FIREWALL_RESTRICTION",c.RECONNECTED="spc-reconnected",c.RECONNECT_FAILED="spc-reconnect-failed",c.ERROR="error",c.SEI_MESSAGE="sei-message",c))(Dt||{}),Jl=0,jl=!1,a_=new Set,c_=r=>Jl>2&&!jl&&a_.size===0&&r,d_=1,ri=class extends Wl.default{constructor({signalChannel:e,room:t,enableCustomMessage:s}){super();u(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0});u(this,"currentState","DISCONNECTED");u(this,"_room");u(this,"_signalChannel");u(this,"_peerConnection",null);u(this,"_datachannel",null);u(this,"_enableCustomMessage");u(this,"_log");u(this,"_downlinkMIDMap",new Map);u(this,"_downlinkMIDUserIDMap",new Map);u(this,"_reconnectionTimer",-1);u(this,"reconnectionCount",0);u(this,"clientAbility");u(this,"_serverAbility",null);u(this,"addDownlinkQueue",new Set);u(this,"removeDownlinkQueue",new Set);u(this,"_parsedAnswer",null);u(this,"_updateSDPPromise",null);u(this,"_waitForPCConnectedPromise");u(this,"_waitForPCConnectedPromiseReject",null);u(this,"_isSDPLogged",!1);u(this,"seiCodec",null);this._room=t,this._enableCustomMessage=s,this._signalChannel=e,this._log=A.createLogger({id:`spc${d_++}`,userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableSEI&&Ei&&(this._log.info("create sei codec"),this.seiCodec=new Fl(this,this._log),this.seiCodec.onSEIMessage=n=>{this.emit("sei-message",{userId:this._downlinkMIDUserIDMap.get(n.mid),data:n.data,seiPayloadType:n.seiPayloadType,streamType:n.streamType})})}get isH264EncodeSupported(){let e=this._room.checkSystemResult.detail.isH264EncodeSupported;return this._serverAbility&&(e=e&&!!this._serverAbility.video.codecs.find(t=>t.codec.toLowerCase()==="h264")),e}get isVP8EncodeSupported(){let e=this._room.checkSystemResult.detail.isVp8EncodeSupported;return this._serverAbility&&(e=e&&this._serverAbility.useVp8),e}get videoCodec(){var e;return(e=this._serverAbility)!=null&&e.useVp8?"vp8":"h264"}get isUsingH264(){return this.videoCodec==="h264"}get uplinkSSRC(){return this._peerConnection&&this._peerConnection.localDescription?Ul(this._peerConnection.localDescription.sdp):{audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0}}get isReconnecting(){return this.currentState==="RECONNECTING"||this._reconnectionTimer>0||this.reconnectionCount>0}get dtlsTransport(){if(!this._peerConnection)return null;let e=this._peerConnection.getSenders();return e.length===0?null:e[0].transport}initialize(){return p(this,null,function*(){let e;try{return this._peerConnection=new RTCPeerConnection({encodedInsertableStreams:this._room.enableSEI&&Ei,offerExtmapAllowMixed:!0,iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._room.sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"}),this._peerConnection.oniceconnectionstatechange=()=>{if(!this._peerConnection)return;let t=this._peerConnection.iceConnectionState;this._log.debug(`ice state: ${t}`),t==="checking"&&this.stat.iceStartTime===0?this.stat.iceStartTime=Date.now():t==="connected"&&this.stat.iceEndTime===0&&(this.stat.iceEndTime=Date.now())},this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this._peerConnection.ontrack=t=>this.emit("track",t),this._enableCustomMessage&&(this._datachannel=this._peerConnection.createDataChannel(`${this._room.userId}dc`),this._datachannel.binaryType="arraybuffer",this._datachannel.onopen=()=>{this._log.info("datachannel open")},this._datachannel.onclose=()=>{this._log.warn("datachannel close")},this._datachannel.onmessage=t=>{let s=new md(t.data);this.emit("data_channel_msg",{data:s})},this._datachannel.onerror=t=>{this._log.warn("datachannel error",t)}),this._peerConnection.addTransceiver(h.AUDIO,{direction:h.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:h.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:h.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:h.TRANSCEIVER_DIRECTION_SENDONLY}),e=yield this._peerConnection.createOffer(),yield this.setOffer(e),this.dtlsTransport&&(this.dtlsTransport.onstatechange=()=>{let{dtlsTransport:t}=this;!t||(this._log.debug(`dtls state: ${t.state}`),t.state==="connecting"&&this.stat.dtlsStartTime===0?this.stat.dtlsStartTime=Date.now():t.state==="connected"&&this.stat.dtlsEndTime===0&&(this.stat.dtlsEndTime=Date.now()))}),this.clientAbility=Bl(e.sdp,this._enableCustomMessage),w.addSuccessEvent({key:521707}),this.clientAbility}catch(t){throw w.addFailedEvent({key:521707,error:t}),this._log.error(`initialize failed ${t}
78
78
  offer: ${e==null?void 0:e.sdp}`),t}})}connect(e,t=!1){return p(this,null,function*(){var s;try{if(this.currentState==="CONNECTED")return;let n=B(),o={type:"answer",sdp:$l({serverAbility:e,clientAbility:this.clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(o),yield this.waitForPeerConnectionConnected(),t||w.addSuccessEvent({key:521703,cost:B()-n}),(s=this.seiCodec)==null||s.handleEncodedStreams()}catch(n){let o=n instanceof C&&n.code===I.API_CALL_ABORTED;throw o||this._log.error(`connect failed: ${n}`,e),this.reset(),!o&&!this.isReconnecting&&(w.addFailedEvent({key:521703,error:n}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),n}})}reconnect(){return p(this,null,function*(){if(this._reconnectionTimer!==-1){this._log.warn("reconnect() is reconnecting, ignore current reconnection");return}if(!this._signalChannel.isConnected){this._log.warn("reconnect() wait signal channel is connected"),this._signalChannel.once(le.CONNECTED,this.reconnect,this);return}try{this.reconnectionCount++,this._log.warn(`reconnect() trying [${this.reconnectionCount}]`),this.reset();let e=yield this.initialize(),t=yield this._signalChannel.sendWaitForResponse({command:W.REBUILD_PEER_CONNECTION,responseCommand:P.REBUILD_PEER_CONNECTION_RES,data:{ability:e},enableLog:!1});if(t.data.code!==0)throw new C({code:t.data.code,message:t.data.message});yield this.connect(t.data.data.ability,!0),w.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),T.emit(f.SPC_RECONNECTED,{room:this._room}),this.emit("spc-reconnected")}catch(e){if(!this.isReconnecting)return;if(e!=null&&e.message.includes("timeout")){let t=It(this.reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${t/1e3}s`),this._reconnectionTimer=window.setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},t)}else this._log.error(`reconnect() failed ${e==null?void 0:e.code} ${e}`),w.addFailedEvent({key:521704,error:e}),this.reconnectionCount>=Pt()&&this._log.warn(`SDK has tried reconnect for ${Pt()} times, but all failed, please check your network`),this.stopReconnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.emit("error")}})}getPeerConnection(){return this._peerConnection}startReconnection(){return p(this,null,function*(){this._log.warn("start reconnect"),this._updateSDPPromise=null,this.emitConnectionStateChangedEvent("RECONNECTING"),yield this.reconnect()})}stopReconnection(){this.isReconnecting&&(this._log.info("stop reconnect"),this.reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(le.CONNECTED,this.reconnect,this))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&((e=this._peerConnection)==null?void 0:e.connectionState)===se.CLOSED&&this.startReconnection()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}onConnectionStateChange(e){let t=this._peerConnection.iceConnectionState,s=this.getDTLSTransportState();this._log.info(`connectionState: ${e.target.connectionState} ICE: ${t} DTLS: ${s}`),e.target.connectionState===se.CONNECTING&&(this.stat.peerConnectionStartTime===0&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(e.target.connectionState===se.FAILED||e.target.connectionState===se.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),(e.target.connectionState===se.CONNECTED||e.target.connectionState===se.COMPLETED)&&(this.stat.peerConnectionEndTime===0&&(this.stat.peerConnectionEndTime=Date.now()),T.emit(f.SINGLE_CONNECTION_STAT,{room:this._room,stat:{ice:this.stat.iceEndTime-this.stat.iceStartTime,dtls:this.stat.dtlsEndTime-this.stat.dtlsStartTime,peerConnection:this.stat.peerConnectionEndTime-this.stat.peerConnectionStartTime}}),this.logSelectedCandidate(),this.emitConnectionStateChangedEvent("CONNECTED"))}getDTLSTransportState(){if(!this._peerConnection)return it;let e=null;return!gr()||this._peerConnection.getSenders().length===0?it:(e=this._peerConnection.getSenders()[0].transport,!xi()||this._peerConnection.getReceivers().length===0?it:e?e.state:it)}emitConnectionStateChangedEvent(e){e!==this.currentState&&(this.currentState==="RECONNECTING"&&e==="CONNECTING"||(this.emit(Dt.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:e}),this.currentState=e))}logSelectedCandidate(){return p(this,null,function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[t,s]of e)if(fi(s)){let n=e.get(s.localCandidateId),o=e.get(s.remoteCandidateId);n&&(this._log.info(`local candidate: ${n.candidateType} ${n.protocol}:${n.ip||n.address}:${n.port} ${n.networkType||""} ${n.candidateType==="relay"?`relayProtocol:${n.relayProtocol}`:""}`),n.networkType&&Ca(n.networkType)),o&&this._log.info(`remote candidate: ${o.candidateType} ${o.protocol}:${o.ip||o.address}:${o.port}`);break}})}waitForPeerConnectionConnected(){return this._waitForPCConnectedPromise?this._waitForPCConnectedPromise:(this._waitForPCConnectedPromise=new Promise((e,t)=>{if(this.currentState==="CONNECTED")return e();this._waitForPCConnectedPromiseReject=t;let s=c=>{c.state==="CONNECTED"&&(clearTimeout(a),o(),e())},n=({room:c})=>{c===this._room&&(clearTimeout(a),o(),t(new C({code:I.API_CALL_ABORTED,message:D({key:v.CONNECTION_ABORTED,data:"leave room"})})))},o=()=>{T.off(f.LEAVE_SUCCESS,n,this),this.off(Dt.CONNECTION_STATE_CHANGED,s,this)},a=setTimeout(()=>{o();let c=new C({code:I.API_CALL_TIMEOUT,message:"connection timeout"});Jl+=1,c_(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),jl=!0,this.emit(Dt.FIREWALL_RESTRICTION)),t(c)},Kr);T.on(f.LEAVE_SUCCESS,n,this),this.on(Dt.CONNECTION_STATE_CHANGED,s,this)}),this._waitForPCConnectedPromise=this._waitForPCConnectedPromise.finally(()=>{this._waitForPCConnectedPromise=null,this._waitForPCConnectedPromiseReject=null}),this._waitForPCConnectedPromise)}waitForReconnected(){return this.isReconnecting?new Promise((e,t)=>{this.once("spc-reconnected",e),this.once("error",t)}):Promise.resolve()}addDownlink(e){return p(this,null,function*(){var t;if(this._log.info(`addDownlink(${e.userId}) trying`),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise),this.updateLocalAndRemoteSDPConfig(e),this.addDownlinkQueue.size===0)try{yield this.updateSDP(),(t=this.seiCodec)==null||t.handleEncodedStreams(),this._log.info(`addDownlink(${e.userId}) done`)}catch(s){this._log.error(`addDownlink(${e.userId}) failed ${s}`),yield this.startReconnection()}})}updateLocalAndRemoteSDPConfig({ssrc:e,userId:t,tinyId:s}){if(!this._peerConnection)return;this._log.info(`updateLocalAndRemoteSDPConfig ${t} ${JSON.stringify(e)}`);let n=this._peerConnection.getTransceivers().filter(_=>_.direction==="inactive").slice(0,3).map(_=>(_.direction=h.TRANSCEIVER_DIRECTION_RECVONLY,Number(_.mid)));this._parsedAnswer||(this._parsedAnswer=ce(this._peerConnection.remoteDescription.sdp));let o=this._parsedAnswer.media.filter(_=>{var g;return(g=_.ssrcs)==null?void 0:g.find(R=>{var y;return(y=R.value)==null?void 0:y.includes(s)})}),a,c,d;if(o.length===3)a=o[0],c=o[1],d=o[2];else if(n.length===3)a=this._parsedAnswer.media.find(_=>Number(_.mid)===Number(n[0])),c=this._parsedAnswer.media.find(_=>Number(_.mid)===Number(n[1])),d=this._parsedAnswer.media.find(_=>Number(_.mid)===Number(n[2]));else if(n.length===0){this._peerConnection.addTransceiver(h.AUDIO,{direction:h.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:h.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:h.TRANSCEIVER_DIRECTION_RECVONLY}),a=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let _=ud({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:ce(this._peerConnection.localDescription.sdp),useAllCodec:!0});c=JSON.parse(JSON.stringify(_)),d=JSON.parse(JSON.stringify(_)),a.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(a),c.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(c),d.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(d)}a.direction=h.TRANSCEIVER_DIRECTION_SENDONLY;let l=`${s}-${e.audio}`;a.ssrcs=[{id:e.audio,attribute:"cname",value:`${l}`},{id:e.audio,attribute:"msid",value:`${l}-${h.MAIN} ${l}-audio`}],c.direction=h.TRANSCEIVER_DIRECTION_SENDONLY,c.ssrcs=[{id:e.video,attribute:"cname",value:`${l}`},{id:e.video,attribute:"msid",value:`${l}-${h.MAIN} ${l}-bigvideo`},{id:e.videoRtx,attribute:"cname",value:`${l}`},{id:e.videoRtx,attribute:"msid",value:`${l}-${h.MAIN} ${l}-bigvideo`}],c.ssrcGroups=[{semantics:"FID",ssrcs:`${e.video} ${e.videoRtx}`}],d.direction=h.TRANSCEIVER_DIRECTION_SENDONLY;let m=`${l}-aux`;d.ssrcs=[{id:e.auxiliary,attribute:"cname",value:m},{id:e.auxiliary,attribute:"msid",value:`${m} ${l}-aux${h.VIDEO}`},{id:e.auxiliaryRtx,attribute:"cname",value:`${m} ${l}-aux${h.VIDEO}`},{id:e.auxiliaryRtx,attribute:"msid",value:`${m} ${l}-aux${h.VIDEO}`}],d.ssrcGroups=[{semantics:"FID",ssrcs:`${e.auxiliary} ${e.auxiliaryRtx}`}],this._parsedAnswer.groups&&(this._parsedAnswer.groups[0].mids=this._parsedAnswer.media.map(_=>_.mid).join(" ")),this._downlinkMIDMap.set(t,[a.mid,c.mid,d.mid]),this._downlinkMIDUserIDMap.set(a.mid,t),this._downlinkMIDUserIDMap.set(c.mid,t),this._downlinkMIDUserIDMap.set(d.mid,t)}removeDownlink(e){return p(this,null,function*(){if(!this._downlinkMIDMap.has(e)||!this._peerConnection)return;this._log.info(`removeDownlink(${e}) trying`),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise);let t=this._downlinkMIDMap.get(e),s=!1;this._peerConnection.getTransceivers().forEach(n=>{t!=null&&t.includes(Number(n.mid))&&(s=!0,n.direction="inactive")}),this._parsedAnswer||(this._parsedAnswer=ce(this._peerConnection.remoteDescription.sdp)),this._parsedAnswer.media.forEach(n=>{t!=null&&t.includes(Number(n.mid))&&(s=!0,n.direction="inactive",n.ssrcs=[],n.ssrcGroups=[])}),this.removeDownlinkQueue.size===0&&s&&(yield this.updateSDP()),this._downlinkMIDMap.delete(e),t==null||t.forEach(n=>this._downlinkMIDUserIDMap.delete(n)),this._log.info(`removeDownlink(${e}) done`)})}setBandwidth(e){return p(this,null,function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:s,smallVideo:n,auxVideo:o}=e;try{if(Rs()){let a=this._peerConnection.getSenders().slice(0,4);for(let d=0;d<a.length;d++){let l=a[d],m;d===0&&t?m=t:d===1&&s?m=s:d===2&&n?m=n:d===3&&o&&(m=o),m&&(yield this.setSenderMaxBitrate(l,m))}let c=!1;s&&a[1].track&&(c=this.setStartBitrate(1,s)),o&&a[3].track&&(c=this.setStartBitrate(3,o)||c),c&&(yield this.updateSDP())}else yield this.setBandwidthBySDP(e);this._log.info(`setBandwidth ${JSON.stringify(e)}`)}catch(a){this._log.error(`failed to set bandwidth: ${a}`)}})}setStartBitrate(e,t){var s,n;return(s=this._peerConnection)!=null&&s.remoteDescription&&(this._parsedAnswer||(this._parsedAnswer=ce(this._peerConnection.remoteDescription.sdp)),(n=this._parsedAnswer.media[e])!=null&&n.fmtp[0])?(this._parsedAnswer.media[e].fmtp[0].config+=`;x-google-start-bitrate=${t>5e3?5e3:t}`,!0):!1}setSenderMaxBitrate(e,t){let s=e.getParameters();return(!s.encodings||s.encodings.length===0)&&(s.encodings=[{}]),t==="unlimited"?delete s.encodings[0].maxBitrate:s.encodings[0].maxBitrate=t*1e3,e.setParameters(s)}setBandwidthBySDP({audio:e,bigVideo:t,smallVideo:s,auxVideo:n}){if(!this._peerConnection||!this._peerConnection.localDescription)return;let o=ce(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=ce(this._peerConnection.remoteDescription.sdp));let a=Y?"TIAS":"AS";e&&(o.media[0].bandwidth=[{type:a,limit:Y?e*1e3:e}],this._parsedAnswer.media[0].bandwidth=[{type:a,limit:Y?e*1e3:e}]),t&&(o.media[1].bandwidth=[{type:a,limit:Y?t*1e3:t}],this._parsedAnswer.media[1].bandwidth=[{type:a,limit:Y?t*1e3:t}]),s&&(o.media[2].bandwidth=[{type:a,limit:Y?s*1e3:s}],this._parsedAnswer.media[2].bandwidth=[{type:a,limit:Y?s*1e3:s}]),n&&(o.media[3].bandwidth=[{type:a,limit:Y?n*1e3:n}],this._parsedAnswer.media[3].bandwidth=[{type:a,limit:Y?n*1e3:n}]);let c={type:"offer",sdp:et(o)};return this.updateSDP({localDescription:c})}setScaleResolutionDownBy(e,t){if(t===1)return;let s=e.getParameters();return(!s.encodings||s.encodings.length===0)&&(s.encodings=[{}]),s.encodings[0].scaleResolutionDownBy=t,e.setParameters(s)}updateSDP({localDescription:e}={}){if(!this._parsedAnswer)return Promise.resolve();let t=et(this._parsedAnswer);return this._updateSDPPromise=new Promise((s,n)=>p(this,null,function*(){var o,a;try{!e&&this._peerConnection&&(this._log.info("creating offer"),e=yield this._peerConnection.createOffer()),e&&(yield this.setOffer(e)),yield this.setAnswer({type:"answer",sdp:t}),this._updateSDPPromise=null,s()}catch(c){this._log.error(c),!this._isSDPLogged&&this._peerConnection&&(this._log.warn(`current offer: ${this.filterSDPDirection((o=this._peerConnection.localDescription)==null?void 0:o.sdp)}
79
79
  next offer: ${this.filterSDPDirection(e==null?void 0:e.sdp)}`),this._log.warn(`current answer: ${this.filterSDPDirection((a=this._peerConnection.remoteDescription)==null?void 0:a.sdp)}
80
80
  next answer: ${this.filterSDPDirection(t)}`),this._log.warn(`offer: ${e==null?void 0:e.sdp}`),this._log.warn(`answer: ${t}`),this._log.warn(`transceivers: ${JSON.stringify(this._peerConnection.getTransceivers().map(({mid:d,currentDirection:l,direction:m,stopped:_})=>({mid:d,currentDirection:l,direction:m,stopped:_})))}`),this._log.warn(`parsedAnswer: ${JSON.stringify(this._parsedAnswer)}`),this._isSDPLogged=!0),this._updateSDPPromise=null,n(c)}})),this._updateSDPPromise}filterSDPDirection(e=""){return ce(e).media.map(s=>s.direction)}setOffer(e){return this._log.info("setting offer"),this._peerConnection.setLocalDescription({type:"offer",sdp:Hl(e.sdp)})}setAnswer(e){return this._log.info("setting answer"),this._room.enableHWEncoder&&e.sdp&&(e.sdp=e.sdp.replaceAll("42e01f","42001f")),this._peerConnection.setRemoteDescription(e)}sendDataChannelMessage(e){var t;(t=this._datachannel)==null||t.send(e)}reset(){var e;(e=this._peerConnection)==null||e.close(),this._waitForPCConnectedPromise=null,this._parsedAnswer=null}close(){this._log.info("close pc"),this.seiCodec&&(this.seiCodec.destroy(),this.seiCodec=null),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners()}sendSEI(e,t){var s;(s=this.seiCodec)==null||s.push(e,t)}};b([so("reconnect")],ri.prototype,"startReconnection",1),b([Rr(r=>r.userId)],ri.prototype,"addDownlink",1),b([Rr(r=>r)],ri.prototype,"removeDownlink",1),b([Nt(!0)],ri.prototype,"updateSDP",1);var hd=class{constructor(i){u(this,"tag");u(this,"len");u(this,"data");let e=new DataView(i);this.tag=e.getUint16(),this.len=e.getUint16(2),this.data=new Uint8Array(i).slice(4,2+2+this.len).buffer}},md=class{constructor(i){u(this,"tinyId");u(this,"data");let e=new DataView(i),t=0,s=[];for(;t<e.byteLength;){let n=e.getUint16(t+2),o=new hd(new Uint8Array(i).slice(t,t+2+2+n).buffer);s.push(o),t+=2+2+n}s.forEach(n=>{n.tag===1?this.tinyId=new TextDecoder().decode(n.data):n.tag===2&&(this.data=n.data)})}},Gl=new Set;function Xi(){let r=Math.floor(Math.random()*4294967296);return Gl.has(r)?Xi():(Gl.add(r),r)}var ql=Ae(ke());var Qi=class extends ql.default{constructor(e){super();u(this,"userId");u(this,"tinyId");u(this,"_sdpSemantics");u(this,"_isUplink");u(this,"_room");u(this,"_log");u(this,"_signalChannel");u(this,"_currentState","DISCONNECTED");u(this,"_prevTime",-1);u(this,"_enableSEI");this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=A.createLogger({id:"n",userId:this._room.userId,remoteUserId:this._isUplink?void 0:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=e.signalChannel,this._enableSEI=e.enableSEI}get _peerConnection(){var e;return((e=this.singlePC)==null?void 0:e.getPeerConnection())||null}get singlePC(){return this._room.singlePC}close(e){this._log.info("close connection"),this.emit("closed",e)}emitConnectionStateChangedEvent(e){return e===this._currentState?!1:(T.emit(f.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:e,remoteUserId:this._isUplink?void 0:this.userId}),this.emit("connection-state-changed",{prevState:this._currentState,state:e}),this._currentState=e,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}getCurrentState(){return this._currentState}get isH264(){var e,t;return!!((t=(e=this._peerConnection)==null?void 0:e.remoteDescription)!=null&&t.sdp.includes("H264"))}};var pd=class extends Qi{constructor(e){super(L(N({},e),{isUplink:!0}));u(this,"localMainAudioTrack",null);u(this,"localMainVideoTrack",null);u(this,"localAuxAudioTrack",null);u(this,"localAuxVideoTrack",null);u(this,"_isPublishingAux",!1);u(this,"_publishingLocalAudioTrack");u(this,"_publishingLocalVideoTrack");u(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0});u(this,"_flag",0);u(this,"_checkPublishStateTimeoutId",-1);this.initialize()}get ssrc(){if(!this.singlePC)return{audio:0,video:0,videoRtx:0,small:0,smallRtx:0,auxiliary:0,auxiliaryRtx:0};let{audioSsrc:e,bigVideoSsrc:t,bigVideoRtxSsrc:s,smallVideoSsrc:n,smallVideoRtxSsrc:o,auxVideoSsrc:a,auxVideoRtxSsrc:c}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:s||0,small:n||0,smallRtx:o||0,auxiliary:a||0,auxiliaryRtx:c||0}}get flag(){return this._flag}set flag(e){this._flag!==e&&(this._flag=e,this.checkPublishState())}checkPublishState(e=!1){if(!e&&this._checkPublishStateTimeoutId>0)return;let{publishState:t,serverPublishState:s}=this,n=Object.keys(t).find(o=>t[o]!==s[o]);if(n)if(e)this._log.warn(`publish state not matched, ${n} local:${t[n]} server:${s[n]} ${ds()}`),w.addCount({key:521e3});else{this._checkPublishStateTimeoutId=Z.run(ci,()=>this.checkPublishState(!0),{delay:10*1e3,count:1});return}Z.clearTask(this._checkPublishStateTimeoutId),this._checkPublishStateTimeoutId=-1}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}get publishState(){var t,s,n,o;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(At()?(e.audio=!!((t=a[0])!=null&&t.track),e.bigVideo=!!((s=a[1])!=null&&s.track),e.smallVideo=!!((n=a[2])!=null&&n.track),e.auxVideo=!!((o=a[3])!=null&&o.track)):a.forEach(c=>{c.track&&(c.track.kind===h.AUDIO?e.audio=!0:(e.bigVideo=!0,this._room.videoManager.hasSmall&&(e.smallVideo=!0)))}))}return e}get serverPublishState(){return{audio:!!(this.flag&oi),bigVideo:!!(this.flag&ni),smallVideo:!!(this.flag&jr),auxVideo:!!(this.flag&Ni)}}get muteState(){var e,t,s;return{audio:!!((e=this.localMainAudioTrack)!=null&&e.muted),bigVideo:!!((t=this.localMainVideoTrack)!=null&&t.muted),auxVideo:!!((s=this.localAuxVideoTrack)!=null&&s.muted)}}initialize(){this.installEvents()}reset(){this.uninstallEvents(),this.uninstallTrackMuteEvents(this.localMainAudioTrack,this.localMainVideoTrack,this.localAuxVideoTrack)}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){var e;this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||(e=this.singlePC)==null||e.on("spc-reconnected",this.onSinglePCReconnected,this)}uninstallEvents(){var e;this.off("connection-state-changed",this.handleConnectionStateChange,this),(e=this.singlePC)==null||e.off("spc-reconnected",this.onSinglePCReconnected,this)}emitConnectionStateChangedEvent(e,t){var o,a,c;let s=this._currentState,n=super.emitConnectionStateChangedEvent(e);return n&&s!==e&&(t?t.emit("connection-state-changed",{prevState:s,state:e}):((o=this.localMainVideoTrack)==null||o.emit("connection-state-changed",{prevState:s,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:s,state:e}),(c=this._publishingLocalVideoTrack)==null||c.emit("connection-state-changed",{prevState:s,state:e}))),n}publish(n){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:s}){var d,l,m,_,g,R,y;if(!this.singlePC)return;yield this.singlePC.waitForPeerConnectionConnected();let{publishState:o,muteState:a}=this;if(e&&(this._publishingLocalAudioTrack=e,o.audio=!0,a.audio=e.muted),t){if(!this.singlePC.isH264EncodeSupported&&!this.singlePC.isVP8EncodeSupported)throw new C({code:I.NOT_SUPPORTED_H264,message:D({key:v.NOT_SUPPORTED_H264ENCODE})});ye&&Vt()===115&&t.profile.width*t.profile.height<=640*360&&(this._log.warn("fallback video to 480p"),t.setProfile(qe["480p_2"]),yield t.applyProfile()),this._publishingLocalVideoTrack=t,s?(o.auxVideo=!0,a.auxVideo=t.muted):(o.bigVideo=!0,a.bigVideo=t.muted)}this._isPublishingAux=s;let c;if(t&&!s&&t.small&&(c=this._room.videoManager.smallTrack,o.smallVideo=!0),yield this._signalChannel.sendWaitForResponseWithRetry({command:W.SPC_PUBLISH,responseCommand:P.SPC_PUBLISH_RESULT,data:L(N({},this.singlePC.uplinkSSRC),{state:o,muteState:a}),retries:3}),yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:c,isAuxiliary:s}),(d=this.singlePC.seiCodec)==null||d.handleEncodedStreams(),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,s)t&&(this.localAuxVideoTrack=t),e&&(this.localAuxAudioTrack=e);else{if(t){this.localMainVideoTrack=t;let{scaleResolutionDownBy:x}=t;x>1&&(this._log.warn(`setScaleResolutionDownBy main ${x}`),yield this.singlePC.setScaleResolutionDownBy(this._peerConnection.getSenders()[1],x))}e&&(this.localMainAudioTrack=e)}yield this.singlePC.setBandwidth({audio:((l=this.localMainAudioTrack)==null?void 0:l.profile.bitrate)||((m=this.localAuxAudioTrack)==null?void 0:m.profile.bitrate),bigVideo:(_=this.localMainVideoTrack)==null?void 0:_.profile.bitrate,smallVideo:(R=(g=this.localMainVideoTrack)==null?void 0:g.small)==null?void 0:R.bitrate,auxVideo:(y=this.localAuxVideoTrack)==null?void 0:y.profile.bitrate}),this.sendMediaSettings(),this.installTrackMuteEvents(e,t)})}publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:s,isAuxiliary:n}){if(!Qe())return;this._log.info("publish by transceiver");let o=t==null?void 0:t.outMediaTrack,a=e==null?void 0:e.outMediaTrack,c=this._peerConnection.getTransceivers(),d=[],l=[];if(a){let _=c[0].sender.replaceTrack(a);l.push(0),d.push(_)}if(o)if(n){let _=c[3].sender.replaceTrack(o);l.push(3),d.push(_)}else{let _=c[1].sender.replaceTrack(o);l.push(1),d.push(_)}if(s){let _=c[2].sender.replaceTrack(s);l.push(2),d.push(_)}let m=this.setTransceiverDirection(j.SENDONLY,l);return d.push(m),Promise.all(d)}enableSmall(e){return p(this,null,function*(){if(!this.singlePC)return;let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.setTransceiverDirection(j.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(j.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()})}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(s){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){let n=t&&t===this.localAuxVideoTrack,o=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),c=[];e&&(yield a[0].replaceTrack(null),c.push(0),n?this.localAuxAudioTrack=null:this.localMainAudioTrack=null),o&&(n?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=L(N({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),c.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=L(N({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),c.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.setTransceiverDirection(j.INACTIVE,c),yield this.doPublishChange(!1)):yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),t==null||t.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return p(this,null,function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},s=yield this._signalChannel.sendWaitForResponseWithRetry({command:W.PUBLISH_STATE_CHANGE,data:t,responseCommand:P.PUBLISH_STATE_CHANGE_RESULT,enableLog:e,retries:3});this.checkPublishResultCode(s.data.code,s.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:W.UNPUBLISH,commandDesc:"unpublish",responseCommand:P.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===I.API_CALL_TIMEOUT)return Promise.resolve();throw t})}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let s=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:n,localAuxVideoTrack:o}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?o=this._publishingLocalVideoTrack:n=this._publishingLocalVideoTrack),Rt){if(s&&s.outMediaTrack){let a=s.outMediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=s.profile.bitrate*1e3,this._mediaSettings.audioFs=a.sampleRate||0}if(n&&n.outMediaTrack){let a=n.outMediaTrack.getSettings();this._mediaSettings.videoWidth=a.width||0,this._mediaSettings.videoHeight=a.height||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=n.profile.bitrate*1e3,n.small&&(this._mediaSettings.smallVideoWidth=n.small.width,this._mediaSettings.smallVideoHeight=n.small.height,this._mediaSettings.smallVideoFps=n.small.frameRate,this._mediaSettings.smallVideoBps=n.small.bitrate*1e3)}if(o&&o.outMediaTrack){let a=o.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=a.width||0,this._mediaSettings.auxVideoHeight=a.height||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=o.profile.bitrate*1e3}}else s&&s.outMediaTrack&&(this._mediaSettings.audioChannel=s.profile.channelCount,this._mediaSettings.audioBps=s.profile.bitrate*1e3,this._mediaSettings.audioFs=s.profile.sampleRate),n&&n.outMediaTrack&&(this._mediaSettings.videoWidth=n.profile.width,this._mediaSettings.videoHeight=n.profile.height,this._mediaSettings.videoFps=n.profile.frameRate,this._mediaSettings.videoBps=n.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:W.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:P.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return p(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is adding ${e.kind} track to current published local ${t?h.AUXILIARY:h.MAIN} stream`),At()&&(yield this.addTrackByTransceiver(e,t))})}addTrackByTransceiver(e,t){return p(this,null,function*(){var n;if(!e.mediaTrack)return;let s=this._peerConnection.getTransceivers();if(e.kind===h.AUDIO)yield s[0].sender.replaceTrack(e.outMediaTrack);else{let o=t?3:1;yield s[o].sender.replaceTrack(e.outMediaTrack),o===1&&((n=this.localMainVideoTrack)==null?void 0:n.small)&&(yield s[2].sender.replaceTrack(this._room.videoManager.smallTrack)),s[o].direction===j.INACTIVE&&(yield this.setTransceiverDirection(j.SENDONLY,[o]))}this.updateMediaSettings(),yield this.doPublishChange()})}removeTrack(e){return p(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${t?h.AUXILIARY:h.MAIN} stream`),At()&&(yield this.removeTrackByTransceiver(e,t))})}removeTrackByTransceiver(e,t){return p(this,null,function*(){if(!e.mediaTrack)return;let s=this._peerConnection.getTransceivers();if(e.kind===h.AUDIO)yield s[0].sender.replaceTrack(null);else{let n=t?3:1;yield s[n].sender.replaceTrack(null),n===1&&this._room.videoManager.hasSmall&&(yield s[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(j.INACTIVE,[n])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,t){return p(this,null,function*(){if(!Y)return;let s=!1,n=!1;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let o=this._peerConnection.getTransceivers();if(t.forEach(d=>{o[d].direction!==e&&(o[d].direction=e,s=!0)}),s){this._log.info("updating offer");let d=yield this._peerConnection.createOffer();yield this._peerConnection.setLocalDescription(d)}let a=-1,c=this._peerConnection.remoteDescription.sdp.split(`\r
81
81
  `).map(d=>{if(d.match(new RegExp(`a=(${j.INACTIVE}|${j.RECVONLY}|${j.SENDONLY})`))&&a++,t.includes(a)){if(e===j.INACTIVE&&d.includes(`a=${j.RECVONLY}`))return n=!0,`a=${e}`;if(e===j.SENDONLY&&d.includes(`a=${j.INACTIVE}`))return n=!0,`a=${j.RECVONLY}`}return d}).join(`\r
82
- `);n&&(this._log.info("updating answer"),yield this._peerConnection.setRemoteDescription({type:"answer",sdp:c}))})}replaceTrack(e){return p(this,null,function*(){var o;let t=(o=this._peerConnection)==null?void 0:o.getSenders(),s=e.outMediaTrack||e.mediaTrack;if(!t||t.length===0||!s||t.find(a=>a.track===s))return;let n=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is replacing ${s.kind} track on ${n?h.AUXILIARY:h.MAIN} stream`),s.kind===h.AUDIO&&t[0]&&(yield t[0].replaceTrack(s)),s.kind===h.VIDEO&&(!n&&t[1]&&(yield t[1].replaceTrack(s)),n&&t[3]&&(yield t[3].replaceTrack(s)))})}setBandwidth(n){return p(this,arguments,function*({bandwidth:e,type:t,videoType:s}){if(this.singlePC){let o={};t===h.AUDIO?o.audio=e:s==="big"?o.bigVideo=e:s==="small"?o.smallVideo=e:o.auxVideo=e,yield this.singlePC.setBandwidth(o)}})}sendMutedFlag(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info(`send muted state: ${JSON.stringify(this.muteState)}`),this._signalChannel.sendWaitForResponseWithRetry({command:W.UPDATE_MUTE_STAT,responseCommand:P.MUTE_RESULT,data:this.muteState,retries:3}).catch(()=>{}))}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&T.emit(f.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(e=h.VIDEO){if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===h.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===h.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===h.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===h.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===bi?(this._log.error(Ee.NOT_SUPPORTED_H264ENCODE),new C({code:I.NOT_SUPPORTED_H264,message:D({key:v.NOT_SUPPORTED_H264ENCODE})})):new C({code:I.UNKNOWN,message:D({key:v.SIGNAL_RESPONSE_FAILED,data:{signalResponse:P.PUBLISH_RESULT,code:e,message:t}})})}onSinglePCReconnected(){return p(this,null,function*(){this.isMainStreamPublished&&(this._log.warn("republish main stream"),yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(this._log.warn("republish aux stream"),yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0}))})}},_d=pd;function Kl(r){return Object.keys(r).filter(i=>r[i])}var Zs=class extends Qi{constructor(e){super(L(N({},e),{isUplink:!1}));u(this,"_flag",0);u(this,"role","anchor");u(this,"remoteAudioTrack");u(this,"remoteVideoTrack");u(this,"remoteAuxiliaryTrack");u(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0});this.flag=e.flag,this.remoteAudioTrack=new Qt(this._room,this),this.remoteVideoTrack=new vt(this._room,this),this.remoteAuxiliaryTrack=new Cr(this._room,this),this.initialize()}get subscribeState(){return{audio:this.remoteAudioTrack.isSubscribed||this.remoteAudioTrack.isSubscribing,video:this.remoteVideoTrack.isBig&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),smallVideo:this.remoteVideoTrack.isSmall&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),auxiliary:this.remoteAuxiliaryTrack.isSubscribed||this.remoteAuxiliaryTrack.isSubscribing}}get muteState(){return _i(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,s,n;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(s=this.remoteVideoTrack)==null||s.onFlagChanged(),(n=this.remoteAuxiliaryTrack)==null||n.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===h.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents(),this.removeDownlink()}installEvents(){!this.singlePC||(this.listeners("track").includes(this.onTrack)||this.singlePC.on("track",this.onTrack,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||this.singlePC.on("spc-reconnected",this.onSinglePCReconnected,this))}uninstallEvents(){!this.singlePC||(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this))}emitConnectionStateChangedEvent(e){var n,o;let t=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&t!==e&&((n=this.remoteVideoTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e}),(o=this.remoteAuxiliaryTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e})),s}onTrack(e){let t=e.streams[0],{track:s}=e;if(!t.id.includes(this.tinyId))return;let o=t.id.includes("aux")?"auxiliary":"main";this._log.debug(`ontrack ${o} ${s.kind}`);let a=h.AUDIO;s.kind===h.VIDEO&&(a=o===h.MAIN?h.VIDEO:h.AUXILIARY);let c=this.remoteAudioTrack;a===h.VIDEO?c=this.remoteVideoTrack:a===h.AUXILIARY&&(c=this.remoteAuxiliaryTrack),c.setInputMediaStreamTrack(s)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return p(this,null,function*(){try{if(this.isSubscriptionStateNotChanged(e))return;if(this._log.info(`subscribe ${t} ${Kl(e)}`),this.hasSSRC){let s="subscribe_change";Object.values(e).find(n=>n===!0)||(s="unsubscribe"),yield this.sendSubscription(s,e)}else yield this.doSubscribe(e),this.checkTrackEnded(e)}catch(s){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${s.message} ${JSON.stringify(this.muteState)}`),new C({code:I.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):s}})}checkTrackEnded(e){var t,s,n;(e.audio&&((t=this.remoteAudioTrack.mediaTrack)==null?void 0:t.readyState)==="ended"||e.video&&((s=this.remoteVideoTrack.mediaTrack)==null?void 0:s.readyState)==="ended"||e.auxiliary&&((n=this.remoteAuxiliaryTrack.mediaTrack)==null?void 0:n.readState)==="ended")&&this.singlePC&&!this.singlePC.isReconnecting&&(this._log.warn("remote track ended start spc reconnect"),this.singlePC.startReconnection())}unsubscribe(s){return p(this,arguments,function*({remoteTracks:e,streamType:t}){var a;if(t==="main"&&!this.isMainStreamSubscribed||t==="auxiliary"&&!this.isAuxStreamSubscribed){this._log.info(`${t} stream already unsubscribed`);return}let n=N({},this.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:n.audio=!1;break;case 4:n.video=!1;break;case 8:n.smallVideo=!1;break;case 2:n.auxiliary=!1;break;default:break}});let o="subscribe_change";Object.values(n).find(c=>c===!0)||(o="unsubscribe"),this._log.info(`${o==="unsubscribe"?o:"subscribe"} ${t} [${Kl(n)}]`),o==="unsubscribe"&&((a=this.singlePC)==null||a.removeDownlinkQueue.add(this.tinyId)),yield this.sendSubscription(o,n),o==="unsubscribe"&&(yield this.removeDownlink())})}sendSubscription(e,t=this.subscribeState){let s={srcTinyId:this.tinyId,srcUserId:this.userId},n=W.UNSUBSCRIBE,o=P.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(s={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},n=W.SUBSCRIBE_CHANGE,o=P.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponseWithRetry({command:n,data:s,responseCommand:o,timeout:1e4,retries:3}).then(({data:a})=>{if(a.code!==0){let c=new C({code:a.code,message:D({key:v.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(c),c}})}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}setDelay({audioDelay:e,videoDelay:t}){this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=t}onSinglePCReconnected(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary)&&(this._log.warn(`resubscribe ${JSON.stringify(this.subscribeState)}`),this.doSubscribe(this.subscribeState))}get hasSSRC(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}doSubscribe(){return p(this,arguments,function*(e=this.subscribeState,t=!0){if(!!this.singlePC){if(this.singlePC.addDownlinkQueue.add(this.tinyId),yield this.singlePC.waitForPeerConnectionConnected(),t||!this.hasSSRC){let s={audioSsrc:Xi(),bigVideoSsrc:Xi(),bigVideoRtxSsrc:Xi(),auxVideoSsrc:Xi(),auxVideoRtxSsrc:Xi()},{audioSsrc:n,bigVideoSsrc:o,bigVideoRtxSsrc:a,auxVideoSsrc:c,auxVideoRtxSsrc:d}=s;this.ssrc={audio:n,video:o,videoRtx:a,auxiliary:c,auxiliaryRtx:d},this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc});try{let l=yield this._signalChannel.sendWaitForResponseWithRetry({command:W.SPC_SUBSCRIBE,responseCommand:P.SPC_SUBSCRIBE_RESULT,data:{srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo,customData:!1,ssrc:s},retries:3,retryTimeout:0});if(l.data.code!==0)throw new C({code:l.data.code,message:l.data.message})}catch(l){throw yield this.removeDownlink(),l}return}this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc})}})}removeDownlink(){return p(this,null,function*(){!this.singlePC||(this.ssrc={audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0},this.singlePC.removeDownlinkQueue.delete(this.tinyId),yield this.singlePC.removeDownlink(this.userId))})}};b([Nt(),F(r=>function(...i){return new Promise((e,t)=>{let s=n=>{this.off("closed",s),t(new C({code:I.API_CALL_ABORTED,message:D({key:v.CONNECTION_ABORTED,data:n})}))};this.on("closed",s),r.apply(this,i).then(e,t).finally(()=>{this.off("closed",s)})})})],Zs.prototype,"subscribe",1),b([Nt()],Zs.prototype,"unsubscribe",1);var Xl=Zs;function Ql(){return F(r=>function(...i){return p(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(i=i.filter(t=>t.outMediaTrack&&t.state==="capture"),!i.length))return;T.emit("61",{room:this});let e=r.apply(this,i);return i.forEach(t=>t.publish(this,e)),e})})}function zl(){return F(r=>function(...i){let e=r.apply(this,i);return i.forEach(t=>t.unpublish()),e})}var Yl=Ae(ke());function u_(){return Math.floor(Math.random()*16383)}var fd=class extends Yl.EventEmitter{constructor(e,t){super();this.room=e;this.signalChannel=t;u(this,"log");u(this,"cmdIdSeqMap",new Map);u(this,"messageMap",new Map);this.log=A.createLogger({id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),t.on(P.RECEIVE_CUSTOM_MSG,this.onReceiveMsg)}send({cmdId:e,data:t}){let s=this.cmdIdSeqMap.get(e)||u_(),n={cmdId:e,msg:btoa(String.fromCharCode(...new Uint8Array(t))),ordered:!0,reliable:!0,streamSeq:s};this.cmdIdSeqMap.set(e,s+1),this.signalChannel.send(W.SEND_CUSTOM_MSG,n)}onReceiveMsg(e){let{data:t}=e.data,s=this.room.tinyIdToUserIdMap.get(t.srcTinyId);if(s){let n={userId:s,cmdId:t.cmdId,seq:t.streamSeq,data:Uint8Array.from(atob(t.msg),o=>o.charCodeAt(0)).buffer};if(t.ordered){let o=`${s}_${n.cmdId}`,a=this.messageMap.get(o);if(!a||Math.abs(a.lastSeq-n.seq)>fd.SEQ_INTERVAL)this.messageMap.set(o,{lastSeq:n.seq,cachedMessageMap:new Map}),this.emitMessage(n);else if(n.seq>a.lastSeq){if(n.seq===a.lastSeq+1)this.emitMessage(n);else if(!a.cachedMessageMap.has(n.seq)){let c=setTimeout(()=>this.emitMessage(n,!0),5e3);a.cachedMessageMap.set(n.seq,{message:n,timeoutId:c})}}else this.log.debug(`drop message ${n.userId}-${n.cmdId}-${n.seq}`)}else this.emit("message",n)}}emitMessage(e,t=!1){var a;let s=this.messageMap.get(`${e.userId}_${e.cmdId}`),n=e;if(s){if(t){let c=[...s.cachedMessageMap.values()].sort((d,l)=>d.message.seq-l.message.seq);c[0]&&(n=c[0].message)}n.seq-s.lastSeq>1&&this.log.debug(`msg lost userId: ${n.userId} seq: ${s.lastSeq} -> ${n.seq}`),s.lastSeq=n.seq,clearTimeout((a=s.cachedMessageMap.get(n.seq))==null?void 0:a.timeoutId),s.cachedMessageMap.delete(n.seq)}this.emit("message",n);let o=s==null?void 0:s.cachedMessageMap.get(n.seq+1);o&&this.emitMessage(o.message)}},en=fd;u(en,"SEQ_INTERVAL",300);var{isString:Zl,isUndefined:Vr,getNetworkType:l_,isEmpty:tn}=Me,Mt=class extends Bo{constructor(e){super(e);this._heartbeat=-1;this._lastHeartBeatTime=-1;this._joinTimeout=-1;this._firstPublishedList=null;this._joinReject=null;this._isRelayChanged=!1;this._signalChannel=null;this.uplinkConnection=null;this.singlePC=null;this.enableSPC=As;this._changeBigSmallRecords=new Map;this._networkQuality=null;this._turnServers=[];this._syncUserListInterval=-1;this._smallStreamConfig={bitrate:100,frameRate:15,height:120,width:160};this.enableSEI=!1;this._enableAudioVolumeEvaluation=!1;this._audioVolumeIntervalId=0;this._enableMultiAuxStream=!1;this._pureAudioPushMode=!1;this.enableHWEncoder=!1;this._stats=new Ks(this,this._log),this.userManager=new fo(this.userId,this._log),this._version=Se,this.sdpSemantics=Yi,Vr(e.sdpSemantics)?Jt.isUnifiedPlanDefault()&&(this.sdpSemantics=ai):this.sdpSemantics=e.sdpSemantics,this._log.info(`sdpSemantics: ${this.sdpSemantics}, netType: ${l_()}`),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=Vr(e.enableMultiAuxStream)?!1:e.enableMultiAuxStream,this.enableSEI=e.enableSEI,!Vr(e.enableSPC)&&As&&(this.enableSPC=e.enableSPC),this.enableHWEncoder=e.enableHWEncoder||!1,this._initBusinessInfo(e)}get isMainStreamPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.isMainStreamPublished)}get isMainAudioPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.localMainAudioTrack)}get isAuxStreamPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.isAuxStreamPublished)}get hasAuxStream(){return[...this.remotePublishedUserMap.values()].findIndex(e=>e.muteState.hasAuxiliary)>=0}get userMap(){return this.userManager.userMap}get remotePublishedUserMap(){return this.userManager.remotePublishedUserMap}get tinyIdToUserIdMap(){return new Map([...this.userMap.values()].map(e=>[e.tinyId,e.userId]))}join(e,t,s){return p(this,null,function*(){return this.userManager.mySelfId=this.userId,this.userManager.on("1",n=>{this.emit("peer-join",n)}),this.userManager.on("2",n=>{this.closeDownLinkConnection(n,"remote user exitRoom"),this.emit("peer-leave",n)}),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",o=>{var n=Sd(o,[]);T.emit(f.REMOTE_PUBLISH_STATE_CHANGED,N({room:this},n)),this.emit("remote-publish-state-changed",N({},n))}),this._joinOptions=e,new Promise((n,o)=>p(this,null,function*(){var a,c;this._joinReject=o;try{this.checkDestroy();try{yield Promise.all([this.initialize(),this.initSinglePC()])}catch(d){if(d instanceof C&&d.code===I.SPC_INITIALIZED_FAILED)(a=this._signalChannel)==null||a.destroy(),yield this.initialize();else return o(d)}yield this.doJoin(e,(c=this.singlePC)==null?void 0:c.clientAbility),n(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(d){o(d)}this._joinReject=null}))})}initSinglePC(){return p(this,null,function*(){if(!(!this.enableSPC||this.singlePC)){this.singlePC=new ri({signalChannel:this._signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.on("sei-message",e=>this.emit("sei-message",e)),this.singlePC.once("error",()=>this.fallbackToMPC());try{return yield this.singlePC.initialize()}catch(e){throw this.fallbackToMPC(),new C({code:I.SPC_INITIALIZED_FAILED,message:e==null?void 0:e.message})}}})}doJoin(e,t){return new Promise((s,n)=>p(this,null,function*(){var c,d,l;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),this._signalChannel.once(le.SETUP_FAILED,m=>{this.clearJoinTimeout(),T.emit(f.JOIN_SIGNAL_CONNECTION_END,{room:this,error:m}),n(m)}),ue((d=(c=this.scheduleResult)==null?void 0:c.config)==null?void 0:d.singlePC)&&As&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2);let o={roomId:String(e.roomId||e.strRoomId),useStringRoomId:this.useStringRoomId,privateMapKey:this.privateMapKey,trtcRole:e.role,trtcScene:this.scene==="live"?2:1,sdpSemantics:this.sdpSemantics,version:this._version,ua:navigator&&navigator.userAgent||"",terminalType:Ta(),netType:_r(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig};this._log.debug(`join room signal data: ${JSON.stringify(o)}`);let a=5e3;((l=this.scheduleResult.config)==null?void 0:l.enterRoomTimeout)&&this.scheduleResult.config.enterRoomTimeout>=1&&(a=this.scheduleResult.config.enterRoomTimeout*1e3),this._joinTimeout=window.setTimeout(()=>{n(new C({code:I.JOIN_ROOM_FAILED,message:D({key:v.JOIN_ROOM_TIMEOUT})}))},a),T.emit(f.JOIN_SEND_CMD,{room:this}),this._signalChannel.send(this.singlePC?W.SPC_JOIN_ROOM:W.JOIN_ROOM,o),this._signalChannel.once(P.JOIN_ROOM_RESULT,m=>{this.clearJoinTimeout();let{code:_,message:g,data:R,tinyId:y}=m.data;T.emit(f.JOIN_RECEIVED_CMD_RES,{room:this,code:_}),_===0?(this._log.info("Join room success, start heartbeat"),y&&(this.tinyId=y),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=R.publishers,this.singlePC&&this.singlePC.connect(R.ability).catch(()=>{}),s()):(this._log.error(`Join room failed result: ${_} error: ${g}`),n(new C({code:I.JOIN_ROOM_FAILED,extraCode:_,message:D({key:v.JOIN_ROOM_FAILED,data:{error:g,code:_}})})))})}))}reJoin(e=!0){return p(this,null,function*(){if(!this.isJoined){this._log.warn("reJoin abort");return}try{this._log.warn(`reJoin pending: ${this._joinOptions.roomId}`);let t,s=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,s.push(this.initSinglePC().then(n=>(t=n,n)))),this._signalChannel&&(this._signalChannel.race=e,this._signalChannel.close(),s.push(this._signalChannel.connect())),yield Promise.all(s),yield this.doJoin(L(N({},this._joinOptions),{role:this.role==="anchor"?20:21,privateMapKey:this.privateMapKey}),t),this._log.warn("reJoin success"),ee.logSuccessEvent({userId:this.userId,eventType:Le.REJOIN}),this.singlePC){let n=o=>{var a;o.state==="CONNECTED"&&((a=this.singlePC)==null||a.off(Dt.CONNECTION_STATE_CHANGED,n),this.uplinkConnection instanceof _d&&this.uplinkConnection.onSinglePCReconnected(),this.remotePublishedUserMap.forEach(c=>{c.installEvents(),c.onSinglePCReconnected()}))};this.singlePC.on(Dt.CONNECTION_STATE_CHANGED,n),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof Do&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(t){this._log.warn(`reJoin fail ${t}`),this.reset(),ee.logFailedEvent({userId:this.userId,eventType:Le.REJOIN,error:t}),this.emit("error",new C({code:I.JOIN_ROOM_FAILED,message:D({key:v.REJOIN_ROOM_FAILED,data:{roomId:this._joinOptions.roomId}})}))}})}initialize(){return p(this,null,function*(){let{mainUrl:e,backupUrl:t}=this.getSignalChannelUrl(),s=this._signalChannel||Sl(this.userId),n=!!(s&&s.isConnected&&s.keepAlive);return this._log.info(`${n?"reuse":"setup"} signal channel`),n?(s.url=e,s.backupUrl=t,s.room=this,this._signalChannel=s):(this._signalChannel=new kr({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:e,backupUrl:t,race:this.enableSPC&&!this.proxy_ws,room:this}),this._customMessageManager=new en(this,this._signalChannel),this._customMessageManager.on("message",o=>{this.emit("custom-message",o)})),this._networkQuality||(this._networkQuality=new qi({signalChannel:this._signalChannel,room:this}),this._networkQuality.on(qi.EVENT_NETWORK_QUALITY,o=>{this.emit("network-quality",o)})),we(this,this._signalChannel).add(le.CONNECTION_STATE_CHANGED,o=>{T.emit(f.SIGNAL_CONNECTION_STATE_CHANGED,N({room:this},o)),this.emit("signal-connection-state-changed",o)}).add(le.RECONNECT_FAILED,o=>{this.reset(),this.emit("error",o)}).add(P.PEER_JOIN,o=>{let{srcTinyId:a,userId:c,role:d}=o.data.data;this.userManager.addUser({userId:c,tinyId:a,role:d})}).add(P.PEER_LEAVE,o=>{let{userId:a,reason:c=0}=o.data.data;this.userManager.deleteUser(a,c)}).add(P.UPDATE_REMOTE_MUTE_STAT,o=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=10*1e3&&this.doHeartbeat(),this.onPublishedUserList(o.data)}).add(P.CLIENT_BANNED,o=>{let a=o.data.data,{reason:c}=a;if(ee.uploadEvent({log:`stat-banned:${c}`,userId:this.userId}),c==="user_time_out"){this._log.warn(`${c} last heart beat time: ${this._lastHeartBeatTime} interval: ${Date.now()-this._lastHeartBeatTime}, visibility: ${document.visibilityState}`),this.reJoin();return}this._log[c==="kick"?"error":"info"](`user was banned because of [${c}]`),this.reset(),this.emit("banned",{reason:c})}),this._signalChannel.once(le.SETUP_SUCCESS,o=>{this.tinyId=o.signalInfo.tinyId,T.emit(f.JOIN_SIGNAL_CONNECTION_END,{room:this})}),T.emit(f.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this._signalChannel.connect(),n&&T.emit(f.JOIN_SIGNAL_CONNECTION_END,{room:this}),n})}setSignalChannel(e){this._signalChannel=e,e||pe(this)}leave(){return p(this,null,function*(){var e;try{yield this.doHeartbeat()}catch(t){}this._log.info("leave() => leaving room"),T.emit(f.LEAVE_SEND_CMD,{room:this}),(e=this._signalChannel)==null||e.send(W.LEAVE_ROOM)})}clearNetworkQuality(){this._networkQuality&&(this._networkQuality.stop(),this._networkQuality=null)}closeConnections(){this.remotePublishedUserMap.forEach(e=>{this.closeDownLinkConnection(e.userId,"you exitRoom")})}clearJoinTimeout(){clearTimeout(this._joinTimeout),this._joinTimeout=-1}startHeartbeat(){this._heartbeat===-1&&(this._heartbeat=Z.run(pt,this.doHeartbeat.bind(this),{delay:2e3}))}stopHeartbeat(){this._heartbeat!==-1&&(this._log.info("stopHeartbeat"),Z.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return p(this,null,function*(){var a;let e=this.badCaseDetector.getMonitorFreeze(),t=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:e});if(this.badCaseDetector.resetMonitor(),!((a=this._signalChannel)!=null&&a.isConnected))return;let s=this._signalChannel.isConnected?Ju(this.userId):[],n=N({str_sdk_version:Gr,uint64_datetime:new Date().getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_device_info:{uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:_r()},msg_event_msg:s,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},t);T.emit(f.HEARTBEAT_REPORT,{room:this,report:n}),this._signalChannel.send(W.ON_QUALITY_REPORT,n),this.emit("heartbeat-report",L(N({},n),{bytes_sent:this._stats.totalBytesSent+this._signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this._signalChannel.bytesReceived}));let o=Date.now();this._lastHeartBeatTime>0&&o-this._lastHeartBeatTime>1e4&&this._log.warn(`heartbeat took ${o-this._lastHeartBeatTime}`),this._signalChannel.isConnected&&(this._lastHeartBeatTime=o),!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)})}onPublishedUserList(e){if(!this.isJoined)return;let t=e.data.userList.map(({userId:s,srcTinyId:n,flag:o})=>{s===this.userId&&this.uplinkConnection&&(this.uplinkConnection.flag=o);let a=this.remotePublishedUserMap.get(s);return a&&this.checkSubscribeBigSmallVideo(a),{userId:s,tinyId:n,flag:o}});T.emit(f.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:t}),this.userManager.setRemotePublishedUserList(t)}closeUplink(e="you unpublished"){this.uplinkConnection&&(this.localTracks.size>0&&this.uplinkConnection.doUnpublish(),this.uplinkConnection.close(e),this.uplinkConnection=null),this.localTracks.forEach(t=>t.unpublish()),this.localTracks.clear()}createDownlinkConnection({userId:e,tinyId:t,flag:s}){let n=new(this.singlePC?Xl:td)({userId:e,tinyId:t,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,flag:s});this.userManager.addRemotePublishedUser(n),this.installDownlinkEvents(n,e),this.emit("remote-published",n)}closeDownLinkConnection(e,t="remote user unpublished"){let s=this.remotePublishedUserMap.get(e);s&&(s.close(t),this.emit("remote-unpublished",s))}installDownlinkEvents(e,t){e.on("error",s=>{let n=s.getCode();n!==I.ICE_TRANSPORT_ERROR&&(n===I.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",s))}),e.on("connection-state-changed",s=>{this.emit("media-connection-state-changed",L(N({},s),{userId:e.userId}))}),e.on("firewall-restriction",()=>{this.emit("firewall-restriction")})}startSyncUserListInterval(){this._syncUserListInterval===-1&&(this._syncUserListInterval=Z.run(pt,this.syncUserList.bind(this)))}stopSyncUserListInterval(){Z.clearTask(this._syncUserListInterval),this._syncUserListInterval=-1}syncUserList(){return this.getUserList().then(e=>{this.userManager.setUserList(e)}).catch(e=>{this._log.debug(`sync user list failed: ${e}`)})}getUserList(){var e;return(e=this._signalChannel)!=null&&e.isConnected?this._signalChannel.sendWaitForResponse({command:W.GET_USER_LIST,responseCommand:P.USER_LIST_RES,enableLog:!1,timeout:2e3}).then(({data:t})=>{let{code:s,message:n}=t;if(s===0)return(t.data&&t.data.userList||[]).map(({userId:a,srcTinyId:c,role:d})=>({userId:a,tinyId:c,role:d}));throw D({key:v.SIGNAL_RESPONSE_FAILED,data:{signalResponse:P.USER_LIST_RES,code:s,message:n}})}):Promise.reject("not connected")}getAllConnections(){let e=[...this.remotePublishedUserMap.values()];return this.uplinkConnection&&e.push(this.uplinkConnection),e}isRelayMaybeFailed(){if(this._signalChannel&&!this._signalChannel.isOnline||!Qc)return!1;if(this.singlePC)return this.singlePC.reconnectionCount>6;let e=this.getAllConnections();if(e.length===0)return!1;for(let t=0;t<e.length;t++)if(e[t].getReconnectionCount()<6)return!1;return!0}checkConnectionsToReconnect(){var e;this.singlePC?((e=this.singlePC.getPeerConnection())==null?void 0:e.connectionState)===se.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach(s=>{if(s instanceof We&&!s.getIsReconnecting()){let n=s.getPeerConnection();n&&n.connectionState===se.CLOSED&&(this._log.warn(`[${s.getUserId()}] pc is closed but not reconnect`),s.startReconnection())}})}fallbackToMPC(){return p(this,null,function*(){var e;if(this._log.warn("fallback to multi pc"),ee.uploadEvent({log:"stat-fallback",userId:this.userId}),this.enableSPC=!1,(e=this.singlePC)==null||e.close(),this.singlePC=null,this.isJoined&&(yield this.reJoin(!1)),this.uplinkConnection){let t=this.uplinkConnection;this.uplinkConnection=new Do({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}),t.isMainStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:t.localMainAudioTrack,localVideoTrack:t.localMainVideoTrack,isAuxiliary:!1})),t.isAuxStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:t.localAuxAudioTrack,localVideoTrack:t.localAuxVideoTrack,isAuxiliary:!0})),t.close()}this.remotePublishedUserMap.forEach(t=>{let s=new td({userId:t.userId,tinyId:t.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,flag:t.flag,remoteAudioTrack:t.remoteAudioTrack,remoteVideoTrack:t.remoteVideoTrack,remoteAuxiliaryTrack:t.remoteAuxiliaryTrack});this.installDownlinkEvents(s,t.userId),this.remotePublishedUserMap.set(t.userId,s),t.isMainStreamSubscribed&&s.subscribe(t.subscribeState,"main"),t.isAuxStreamSubscribed&&s.subscribe(t.subscribeState,"auxiliary")})})}destroy(){this.isDestroyed||(this._signalChannel&&(this._log.info("destroying SignalChannel"),this._signalChannel.close(),this._signalChannel=null),super.destroy(),this._joinReject&&(this._joinReject(new C({code:I.INVALID_OPERATION,message:D({key:v.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners())}switchRole(e){return p(this,null,function*(){this.role!==e&&(e==="audience"&&this.uplinkConnection&&this.closeUplink("you switch role to audience"),yield this.doSwitchRole(e))})}doSwitchRole(e){let t={command:W.SWITCH_ROLE,data:{role:e==="anchor"?20:21,privateMapKey:this.privateMapKey},responseCommand:P.SWITCH_ROLE_RES,retries:1};return this._log.info(`switchRole signal data: ${JSON.stringify(t.data)}`),this._signalChannel.sendWaitForResponseWithRetry(t).then(s=>{let{code:n,message:o}=s.data;if(n!==0)throw new C({code:I.SWITCH_ROLE_FAILED,message:D({key:v.SWITCH_ROLE_FAILED,data:{message:o,code:n}})});this.role=e}).catch(s=>{throw s instanceof C&&s.getCode()===I.API_CALL_TIMEOUT&&(s=new C({code:I.SWITCH_ROLE_FAILED,message:D({key:v.SWITCH_ROLE_TIMEOUT})})),this._log.error(s),s})}publish(...e){return p(this,null,function*(){let t={},s={};e.forEach(c=>{c instanceof Ne&&(c instanceof bt?s.audio=c:t.audio=c),c instanceof ae&&(c instanceof Ge&&c.mediaType===2?s.video=c:t.video=c)});let n=tn(t),o=tn(s);(!n||!o)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new _d({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}):this.uplinkConnection=new Do({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}),this.uplinkConnection.on("connection-state-changed",c=>{this.emit("media-connection-state-changed",L(N({},c),{userId:this.userId}))}),this.uplinkConnection.on("firewall-restriction",()=>{this.emit("firewall-restriction")}),this.uplinkConnection.on("error",c=>{let d=c.getCode();d!==I.ICE_TRANSPORT_ERROR&&(d===I.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",c))}));let a=e.map(c=>c.kind).join(",");n||(this._log.info(`publish() => main ${a}`),yield this.uplinkConnection.publish({localAudioTrack:t.audio,localVideoTrack:t.video,isAuxiliary:!1}),this._log.info("main is published")),o||(this._log.info(`publish() => aux ${a}`),yield this.uplinkConnection.publish({localAudioTrack:s.audio,localVideoTrack:s.video,isAuxiliary:!0}),this._log.info("aux is published"))})}unpublish(...e){return p(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||!this.isMainStreamPublished&&!this.isAuxStreamPublished||!this.uplinkConnection)return;let t={},s={};e.forEach(n=>{!n.mediaTrack||!n.isPublished||(n instanceof Ne&&(n instanceof bt?s.audio=n:t.audio=n),n instanceof ae&&(n instanceof Ge&&n.mediaType===2?s.video=n:t.video=n))});try{let n=e.map(o=>o.kind).join(",");tn(t)||(this._log.info(`unpublish() => main ${n}`),yield this.uplinkConnection.unpublish({localAudioTrack:t.audio,localVideoTrack:t.video})),tn(s)||(this._log.info(`unpublish() => aux ${n}`),yield this.uplinkConnection.unpublish({localAudioTrack:s.audio,localVideoTrack:s.video}))}catch(n){}this.localTracks.size===0&&this.closeUplink("you unpublished")})}addTrack(e){if(!this.uplinkConnection||!e.mediaTrack)return Promise.resolve();let t=this.uplinkConnection.addTrack(e);return e.publish(this,t),t}removeTrack(e){return!this.uplinkConnection||!e.mediaTrack?Promise.resolve():this.uplinkConnection.removeTrack(e).then(t=>(e.unpublish(),t))}replaceTrack(e){return!this.uplinkConnection||!e.mediaTrack||!wa()?Promise.resolve():this.uplinkConnection.replaceTrack(e).then(t=>{T.emit(f.LOCAL_TRACK_REPLACED,{track:e})})}setBandWidth(e){return p(this,null,function*(){!this.uplinkConnection||(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())})}enableSmall(e){return p(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:h.VIDEO,videoType:h.SMALL,bandwidth:this.uplinkConnection.localMainVideoTrack.small.bitrate})),yield this.uplinkConnection.enableSmall(e)})}subscribe(...e){return p(this,null,function*(){if(e=e.filter(o=>!o.isSubscribed),e.length===0)return;let{userId:t}=e[0],s=this.remotePublishedUserMap.get(t);if(!s)return;let n=e.find(o=>o.mediaType===2)?"auxiliary":"main";try{let o=N({},s.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:o.audio=!0;break;case 4:o.video=!0;break;case 8:o.smallVideo=!0;break;case 2:o.auxiliary=!0;break}});let a=this._changeBigSmallRecords.get(t);a&&a.options.smallVideo&&s.muteState.hasSmall&&o.video&&(o.video=!1,o.smallVideo=!0),T.emit(f.SUBSCRIBE_START,{room:this,streamType:n,remotePublishedUser:s,subscribeState:o}),this._log.info(`subscribe() => ${t} ${n} [${Oo(o)}] prev: [${Oo(s.subscribeState)}]`),yield s.subscribe(o,n),this._log.info(`subscribe ${t} ${n} done`);for(let c of e)c.mediaTrack||(yield c.waitHasMediaTrack());T.emit(f.SUBSCRIBE_SUCCESS,{room:this,streamType:n,remotePublishedUser:s})}catch(o){let a=o instanceof C?o.getCode():I.UNKNOWN,c=o;throw o instanceof C?a===I.REMOTE_STREAM_NOT_EXIST&&(c=new C({code:I.API_CALL_ABORTED,message:D({key:v.API_CALL_ABORTED,data:{message:o.message,userId:t,streamType:n}})}),this._log.warn(c)):(c=new C({code:a,message:D({key:v.SUBSCRIBE_FAILED,data:{message:o.message,userId:t,streamType:n}})}),this._log.error(c)),c}})}unsubscribe(...e){return p(this,null,function*(){let{userId:t}=e[0],s=this.remotePublishedUserMap.get(t);if(!s)return;let n=e.find(o=>o.mediaType===2)?"auxiliary":"main";this._log.info(`unsubscribe() => ${t} ${n}`);try{yield s.unsubscribe({remoteTracks:e,streamType:n})}catch(o){this._log.warn(`unsubscribe() => failed ${o}`)}e.forEach(o=>{o.unsubscribe(),o.mediaType===8&&o.setMediaType(4)}),T.emit(f.UNSUBSCRIBE_SUCCESS,{room:this,streamType:n,remotePublishedUser:s})})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAudioVolumeEvaluation(e=2e3,t){if(e<=0){this._enableAudioVolumeEvaluation=!1,Z.clearTask(this._audioVolumeIntervalId);return}e=Math.floor(Math.max(e,100)),T.emit(f.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&Z.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=Z.run(Qr,()=>{var n;let s=[];(n=this.remotePublishedUserMap)==null||n.forEach(o=>{if(o.muteState.hasAudio){let a=Math.floor(o.remoteAudioTrack.getAudioLevel()*100);s.push({userId:o.userId,volume:a})}}),this.emit("audio-volume",s)},{fps:1e3/e,backgroundTask:t})}getLocalAudioStats(){return p(this,null,function*(){let e={};if(e[this.userId]={bytesSent:0,packetsSent:0},this.uplinkConnection){let t=yield this._stats.getSenderStats(this.uplinkConnection);e[this.userId]={bytesSent:t.audio.bytesSent,packetsSent:t.audio.packetsSent}}return e})}getLocalVideoStats(){return p(this,null,function*(){let e={};if(e[this.userId]={bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0},this.uplinkConnection){let{video:{bytesSent:t,packetsSent:s,framesEncoded:n,framesSent:o,frameWidth:a,frameHeight:c}}=yield this._stats.getSenderStats(this.uplinkConnection);e[this.userId]={bytesSent:t,packetsSent:s,framesEncoded:n,framesSent:o,frameWidth:a,frameHeight:c}}return e})}getTransportStats(){return p(this,null,function*(){let e={rtt:0,downlinksRTT:{}};if(this.uplinkConnection){let t=yield this._stats.getSenderStats(this.uplinkConnection);e.rtt=t.rtt}for(let[,t]of this.remotePublishedUserMap){let s=yield this._stats.getReceiverStats(t);e.downlinksRTT[s.userId]=s.rtt}return e})}getRemoteVideoStats(e){return p(this,null,function*(){let t={};for(let[s,n]of this.remotePublishedUserMap)e==="main"&&n.muteState.hasVideo&&(t[s]=n.remoteVideoTrack.stat),e==="auxiliary"&&n.muteState.hasAuxiliary&&(t[s]=n.remoteAuxiliaryTrack.stat);return t})}getRemoteAudioStats(){return p(this,null,function*(){let e={};for(let[t,s]of this.remotePublishedUserMap)s.muteState.hasAudio&&(e[t]=s.remoteAudioTrack.stat);return e})}setTurnServer(e,t){this._log.info(`set turn server: ${JSON.stringify(e)} ${t||""}`);let s=[];Array.isArray(e)?e.forEach(n=>s.push(Me.getTurnServer(n))):Me.isPlainObject(e)&&s.push(Me.getTurnServer(e)),this._turnServers=s,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this._signalChannel.sendWaitForResponse({command:W.START_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:P.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this._signalChannel.sendWaitForResponse({command:W.STOP_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:P.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"})}sendStartPublishCDN(e,t=!0){return this._signalChannel.sendWaitForResponse({command:t?W.START_PUBLISH_TENCENT_CDN:W.START_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?P.START_PUBLISH_TENCENT_CDN_RES:P.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"})}sendStopPublishCDN(e,t=!0){return this._signalChannel.sendWaitForResponse({command:t?W.STOP_PUBLISH_TENCENT_CDN:W.STOP_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?P.STOP_PUBLISH_TENCENT_CDN_RES:P.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}sendAbilityStatus(e){var t;(t=this._signalChannel)==null||t.sendWaitForResponse({command:W.ABILITY_STATUS_REPORT,data:e,timeout:5e3,responseCommand:P.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch(s=>{})}getIceServers(){return this._turnServers.length===0&&this.scheduleResult.iceServers?this.scheduleResult.iceServers:this._turnServers}getIceTransportPolicy(){return this._iceTransportPolicy||this.scheduleResult.iceTransportPolicy||"all"}getLogger(){return this._log}enableAIVoice(){throw new Error("Method not implemented.")}getSignalChannelUrl(){let e={mainUrl:"",backupUrl:""},t=Me.getEnv();return t?(e.mainUrl=`wss://${t}.rtc.qq.com`,e.backupUrl=e.mainUrl):this.proxy_ws?(e.mainUrl=this.proxy_ws,e.backupUrl=e.mainUrl):Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(e.mainUrl=`wss://${this.scheduleResult.domains[0]}`,e.backupUrl=e.mainUrl,this.scheduleResult.domains[1]&&(e.backupUrl=`wss://${this.scheduleResult.domains[1]}`)),e}getSignalInfo(){var e;return((e=this._signalChannel)==null?void 0:e.getSignalInfo())||{clientIp:"",relayIp:""}}reset(e=!1){this.stopSyncUserListInterval(),this.stopHeartbeat(),this.closeConnections(),this.clearNetworkQuality(),this.closeUplink("you exitRoom"),this._signalChannel&&(e&&this._signalChannel.keepAlive&&this._signalChannel.isConnected?this._signalChannel.stopKeepAliveIn(3600):this._signalChannel.close(),this.setSignalChannel(null)),this._stats.reset(),this.userManager.clear(),this.userManager.removeAllListeners(),this.singlePC&&(this.singlePC.close(),this.singlePC=null),this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}}checkSubscribeBigSmallVideo(e){return p(this,null,function*(){let{subscribeState:t,userId:s,muteState:{hasSmall:n,hasVideo:o}}=e;if(!n&&!o||!t.video&&!t.smallVideo)return;let a=this._changeBigSmallRecords.get(s);if(!a||a.isSubscribing||a.reSubscribeCount<=0)return;let{options:c,reSubscribeCount:d}=a;if(c.video&&t.video||c.smallVideo&&t.smallVideo&&n)return;let l={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:c.video,smallVideo:c.smallVideo};try{if(!n&&l.smallVideo&&(l.video=!0,l.smallVideo=!1),l.smallVideo===t.smallVideo&&l.video===t.video)return;a.isSubscribing=!0,a.reSubscribeCount=d-1,yield e.subscribe(l,"main"),e.remoteVideoTrack.setMediaType(l.smallVideo?8:4),this._log.info(`change [${s}] to ${l.smallVideo?"small":"big"} video successfully. count ${Zi-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount=Zi}catch(m){this._log.info(`change [${s}] to ${l.smallVideo?"small":"big"} video failed. count ${Zi-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount===0&&this._changeBigSmallRecords.delete(s)}})}changeType(e,t){let n={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:Zi};this._changeBigSmallRecords.set(t.userId,n),this._log.info(`set [${t.userId}] video prefer type: ${e?"small":"big"}`)}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(e){this._businessInfo=e.businessInfo;let t={};if(Zl(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!Vr(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new C({code:I.INVALID_PARAMETER,message:D({key:v.INVALID_PURE_AUDIO})});this._pureAudioPushMode=e.pureAudioPushMode,t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.pure_audio_push_mod=this._pureAudioPushMode}if(!Vr(e.userDefineRecordId)){let s=/^[A-Za-z0-9_-]{1,64}$/gi;if(e.userDefineRecordId.match(s)===null)throw new C({code:I.INVALID_PARAMETER,message:D({key:v.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!Vr(e.userDefinePushArgs))if(Zl(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256)t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_push_args=e.userDefinePushArgs;else throw new C({code:I.INVALID_PARAMETER,message:D({key:v.INVALID_USER_DEFINE_PUSH_ARGS})});tn(t)||(this._businessInfo=JSON.stringify(t))}sendSEI(e,t){this.singlePC&&this.singlePC.sendSEI(e,t)}sendCustomMessage(e){var t;(t=this._customMessageManager)==null||t.send(e)}};b([qc(["left",te.INIT],"joined"),Ri({settings:{retries:1,timeout:0},onError(r,i,e){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),St(!0),this.reset(),i()):this._signalChannel&&this._signalChannel.isConnected&&this._signalChannel.keepAlive?(this._log.warn("is using keepAlive ws, retry join"),this._signalChannel.close(),this.reset(),i()):(this.reset(),this._log.error(r),e(r))}}),ml()],Mt.prototype,"join",1),b([qc("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),pl(),so("leave room"),Ws({fnName:"publish",validateArgs:!1}),Ws({fnName:"unsubscribe",validateArgs:!1})],Mt.prototype,"leave",1),b([Nt(),Ql(),Ri({settings:{retries:Pt,timeout:r=>It(r)},onError(r,i,e){var t;(t=r.message)!=null&&t.includes("timeout")?(this._log.warn("publish timeout"),i()):(this._log.error(`publish failed: ${r}`),e(r),T.emit(f.PUBLISH_FAILED,{room:this}))}})],Mt.prototype,"publish",1),b([Ws({fnName:"publish"}),Vu("api-call"),Nt(),zl()],Mt.prototype,"unpublish",1),b([Rr((...r)=>r[0].userId),oo(),_l(),Ri({settings:{retries:Pt,timeout:r=>It(r)},onError(r,i,e,t){r.message.includes("timeout")?(this._log.warn("subscribe timeout"),i()):(this._log.error(`subscribe failed: ${r}`),e(r),T.emit(f.SUBSCRIBE_FAILED,{room:this,remoteTracks:t}))}})],Mt.prototype,"subscribe",1),b([Ws({fnName:"subscribe",callback(...r){this.singlePC||r.forEach(i=>{let e=this.remotePublishedUserMap.get(i.userId);e&&!e.isMainStreamSubscribed&&!e.isAuxStreamSubscribed&&e.close("you unsubscribed")})}}),Rr((...r)=>r[0].userId)],Mt.prototype,"unsubscribe",1);$s.create=$s._create.bind($s,Mt);var ux=$s;export{ux as default};
82
+ `);n&&(this._log.info("updating answer"),yield this._peerConnection.setRemoteDescription({type:"answer",sdp:c}))})}replaceTrack(e){return p(this,null,function*(){var o;let t=(o=this._peerConnection)==null?void 0:o.getSenders(),s=e.outMediaTrack||e.mediaTrack;if(!t||t.length===0||!s||t.find(a=>a.track===s))return;let n=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is replacing ${s.kind} track on ${n?h.AUXILIARY:h.MAIN} stream`),s.kind===h.AUDIO&&t[0]&&(yield t[0].replaceTrack(s)),s.kind===h.VIDEO&&(!n&&t[1]&&(yield t[1].replaceTrack(s)),n&&t[3]&&(yield t[3].replaceTrack(s)))})}setBandwidth(n){return p(this,arguments,function*({bandwidth:e,type:t,videoType:s}){if(this.singlePC){let o={};t===h.AUDIO?o.audio=e:s==="big"?o.bigVideo=e:s==="small"?o.smallVideo=e:o.auxVideo=e,yield this.singlePC.setBandwidth(o)}})}sendMutedFlag(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info(`send muted state: ${JSON.stringify(this.muteState)}`),this._signalChannel.sendWaitForResponseWithRetry({command:W.UPDATE_MUTE_STAT,responseCommand:P.MUTE_RESULT,data:this.muteState,retries:3}).catch(()=>{}))}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&T.emit(f.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(e=h.VIDEO){if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===h.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===h.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===h.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===h.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===bi?(this._log.error(Ee.NOT_SUPPORTED_H264ENCODE),new C({code:I.NOT_SUPPORTED_H264,message:D({key:v.NOT_SUPPORTED_H264ENCODE})})):new C({code:I.UNKNOWN,message:D({key:v.SIGNAL_RESPONSE_FAILED,data:{signalResponse:P.PUBLISH_RESULT,code:e,message:t}})})}onSinglePCReconnected(){return p(this,null,function*(){this.isMainStreamPublished&&(this._log.warn("republish main stream"),yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(this._log.warn("republish aux stream"),yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0}))})}},_d=pd;function Kl(r){return Object.keys(r).filter(i=>r[i])}var Zs=class extends Qi{constructor(e){super(L(N({},e),{isUplink:!1}));u(this,"_flag",0);u(this,"role","anchor");u(this,"remoteAudioTrack");u(this,"remoteVideoTrack");u(this,"remoteAuxiliaryTrack");u(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0});this.flag=e.flag,this.remoteAudioTrack=new Qt(this._room,this),this.remoteVideoTrack=new vt(this._room,this),this.remoteAuxiliaryTrack=new Cr(this._room,this),this.initialize()}get subscribeState(){return{audio:this.remoteAudioTrack.isSubscribed||this.remoteAudioTrack.isSubscribing,video:this.remoteVideoTrack.isBig&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),smallVideo:this.remoteVideoTrack.isSmall&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),auxiliary:this.remoteAuxiliaryTrack.isSubscribed||this.remoteAuxiliaryTrack.isSubscribing}}get muteState(){return _i(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,s,n;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(s=this.remoteVideoTrack)==null||s.onFlagChanged(),(n=this.remoteAuxiliaryTrack)==null||n.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===h.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents(),this.removeDownlink()}installEvents(){!this.singlePC||(this.listeners("track").includes(this.onTrack)||this.singlePC.on("track",this.onTrack,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||this.singlePC.on("spc-reconnected",this.onSinglePCReconnected,this))}uninstallEvents(){!this.singlePC||(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this))}emitConnectionStateChangedEvent(e){var n,o;let t=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&t!==e&&((n=this.remoteVideoTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e}),(o=this.remoteAuxiliaryTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e})),s}onTrack(e){let t=e.streams[0],{track:s}=e;if(!t.id.includes(this.tinyId))return;let o=t.id.includes("aux")?"auxiliary":"main";this._log.debug(`ontrack ${o} ${s.kind}`);let a=h.AUDIO;s.kind===h.VIDEO&&(a=o===h.MAIN?h.VIDEO:h.AUXILIARY);let c=this.remoteAudioTrack;a===h.VIDEO?c=this.remoteVideoTrack:a===h.AUXILIARY&&(c=this.remoteAuxiliaryTrack),c.setInputMediaStreamTrack(s)}subscribe(e,t){return p(this,null,function*(){try{if(this._log.info(`subscribe ${t} ${Kl(e)}`),this.hasSSRC){let s="subscribe_change";Object.values(e).find(n=>n===!0)||(s="unsubscribe"),yield this.sendSubscription(s,e)}else yield this.doSubscribe(e),this.checkTrackEnded(e)}catch(s){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${s.message} ${JSON.stringify(this.muteState)}`),new C({code:I.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):s}})}checkTrackEnded(e){var t,s,n;(e.audio&&((t=this.remoteAudioTrack.mediaTrack)==null?void 0:t.readyState)==="ended"||e.video&&((s=this.remoteVideoTrack.mediaTrack)==null?void 0:s.readyState)==="ended"||e.auxiliary&&((n=this.remoteAuxiliaryTrack.mediaTrack)==null?void 0:n.readState)==="ended")&&this.singlePC&&!this.singlePC.isReconnecting&&(this._log.warn("remote track ended start spc reconnect"),this.singlePC.startReconnection())}unsubscribe(s){return p(this,arguments,function*({remoteTracks:e,streamType:t}){var a;if(t==="main"&&!this.isMainStreamSubscribed||t==="auxiliary"&&!this.isAuxStreamSubscribed){this._log.info(`${t} stream already unsubscribed`);return}let n=N({},this.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:n.audio=!1;break;case 4:n.video=!1;break;case 8:n.smallVideo=!1;break;case 2:n.auxiliary=!1;break;default:break}});let o="subscribe_change";Object.values(n).find(c=>c===!0)||(o="unsubscribe"),this._log.info(`${o==="unsubscribe"?o:"subscribe"} ${t} [${Kl(n)}]`),o==="unsubscribe"&&((a=this.singlePC)==null||a.removeDownlinkQueue.add(this.tinyId)),yield this.sendSubscription(o,n),o==="unsubscribe"&&(yield this.removeDownlink())})}sendSubscription(e,t=this.subscribeState){let s={srcTinyId:this.tinyId,srcUserId:this.userId},n=W.UNSUBSCRIBE,o=P.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(s={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},n=W.SUBSCRIBE_CHANGE,o=P.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponseWithRetry({command:n,data:s,responseCommand:o,timeout:1e4,retries:3}).then(({data:a})=>{if(a.code!==0){let c=new C({code:a.code,message:D({key:v.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(c),c}})}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}setDelay({audioDelay:e,videoDelay:t}){this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=t}onSinglePCReconnected(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary)&&(this._log.warn(`resubscribe ${JSON.stringify(this.subscribeState)}`),this.doSubscribe(this.subscribeState))}get hasSSRC(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}doSubscribe(){return p(this,arguments,function*(e=this.subscribeState,t=!0){if(!!this.singlePC){if(this.singlePC.addDownlinkQueue.add(this.tinyId),yield this.singlePC.waitForPeerConnectionConnected(),t||!this.hasSSRC){let s={audioSsrc:Xi(),bigVideoSsrc:Xi(),bigVideoRtxSsrc:Xi(),auxVideoSsrc:Xi(),auxVideoRtxSsrc:Xi()},{audioSsrc:n,bigVideoSsrc:o,bigVideoRtxSsrc:a,auxVideoSsrc:c,auxVideoRtxSsrc:d}=s;this.ssrc={audio:n,video:o,videoRtx:a,auxiliary:c,auxiliaryRtx:d},this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc});try{let l=yield this._signalChannel.sendWaitForResponseWithRetry({command:W.SPC_SUBSCRIBE,responseCommand:P.SPC_SUBSCRIBE_RESULT,data:{srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo,customData:!1,ssrc:s},retries:3,retryTimeout:0});if(l.data.code!==0)throw new C({code:l.data.code,message:l.data.message})}catch(l){throw yield this.removeDownlink(),l}return}this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc})}})}removeDownlink(){return p(this,null,function*(){!this.singlePC||(this.ssrc={audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0},this.singlePC.removeDownlinkQueue.delete(this.tinyId),yield this.singlePC.removeDownlink(this.userId))})}};b([Nt(),F(r=>function(...i){return new Promise((e,t)=>{let s=n=>{this.off("closed",s),t(new C({code:I.API_CALL_ABORTED,message:D({key:v.CONNECTION_ABORTED,data:n})}))};this.on("closed",s),r.apply(this,i).then(e,t).finally(()=>{this.off("closed",s)})})})],Zs.prototype,"subscribe",1),b([Nt()],Zs.prototype,"unsubscribe",1);var Xl=Zs;function Ql(){return F(r=>function(...i){return p(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(i=i.filter(t=>t.outMediaTrack&&t.state==="capture"),!i.length))return;T.emit("61",{room:this});let e=r.apply(this,i);return i.forEach(t=>t.publish(this,e)),e})})}function zl(){return F(r=>function(...i){let e=r.apply(this,i);return i.forEach(t=>t.unpublish()),e})}var Yl=Ae(ke());function u_(){return Math.floor(Math.random()*16383)}var fd=class extends Yl.EventEmitter{constructor(e,t){super();this.room=e;this.signalChannel=t;u(this,"log");u(this,"cmdIdSeqMap",new Map);u(this,"messageMap",new Map);this.log=A.createLogger({id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),t.on(P.RECEIVE_CUSTOM_MSG,this.onReceiveMsg)}send({cmdId:e,data:t}){let s=this.cmdIdSeqMap.get(e)||u_(),n={cmdId:e,msg:btoa(String.fromCharCode(...new Uint8Array(t))),ordered:!0,reliable:!0,streamSeq:s};this.cmdIdSeqMap.set(e,s+1),this.signalChannel.send(W.SEND_CUSTOM_MSG,n)}onReceiveMsg(e){let{data:t}=e.data,s=this.room.tinyIdToUserIdMap.get(t.srcTinyId);if(s){let n={userId:s,cmdId:t.cmdId,seq:t.streamSeq,data:Uint8Array.from(atob(t.msg),o=>o.charCodeAt(0)).buffer};if(t.ordered){let o=`${s}_${n.cmdId}`,a=this.messageMap.get(o);if(!a||Math.abs(a.lastSeq-n.seq)>fd.SEQ_INTERVAL)this.messageMap.set(o,{lastSeq:n.seq,cachedMessageMap:new Map}),this.emitMessage(n);else if(n.seq>a.lastSeq){if(n.seq===a.lastSeq+1)this.emitMessage(n);else if(!a.cachedMessageMap.has(n.seq)){let c=setTimeout(()=>this.emitMessage(n,!0),5e3);a.cachedMessageMap.set(n.seq,{message:n,timeoutId:c})}}else this.log.debug(`drop message ${n.userId}-${n.cmdId}-${n.seq}`)}else this.emit("message",n)}}emitMessage(e,t=!1){var a;let s=this.messageMap.get(`${e.userId}_${e.cmdId}`),n=e;if(s){if(t){let c=[...s.cachedMessageMap.values()].sort((d,l)=>d.message.seq-l.message.seq);c[0]&&(n=c[0].message)}n.seq-s.lastSeq>1&&this.log.debug(`msg lost userId: ${n.userId} seq: ${s.lastSeq} -> ${n.seq}`),s.lastSeq=n.seq,clearTimeout((a=s.cachedMessageMap.get(n.seq))==null?void 0:a.timeoutId),s.cachedMessageMap.delete(n.seq)}this.emit("message",n);let o=s==null?void 0:s.cachedMessageMap.get(n.seq+1);o&&this.emitMessage(o.message)}},en=fd;u(en,"SEQ_INTERVAL",300);var{isString:Zl,isUndefined:Vr,getNetworkType:l_,isEmpty:tn}=Me,Mt=class extends Bo{constructor(e){super(e);this._heartbeat=-1;this._lastHeartBeatTime=-1;this._joinTimeout=-1;this._firstPublishedList=null;this._joinReject=null;this._isRelayChanged=!1;this._signalChannel=null;this.uplinkConnection=null;this.singlePC=null;this.enableSPC=As;this._changeBigSmallRecords=new Map;this._networkQuality=null;this._turnServers=[];this._syncUserListInterval=-1;this._smallStreamConfig={bitrate:100,frameRate:15,height:120,width:160};this.enableSEI=!1;this._enableAudioVolumeEvaluation=!1;this._audioVolumeIntervalId=0;this._enableMultiAuxStream=!1;this._pureAudioPushMode=!1;this.enableHWEncoder=!1;this._stats=new Ks(this,this._log),this.userManager=new fo(this.userId,this._log),this._version=Se,this.sdpSemantics=Yi,Vr(e.sdpSemantics)?Jt.isUnifiedPlanDefault()&&(this.sdpSemantics=ai):this.sdpSemantics=e.sdpSemantics,this._log.info(`sdpSemantics: ${this.sdpSemantics}, netType: ${l_()}`),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=Vr(e.enableMultiAuxStream)?!1:e.enableMultiAuxStream,this.enableSEI=e.enableSEI,!Vr(e.enableSPC)&&As&&(this.enableSPC=e.enableSPC),this.enableHWEncoder=e.enableHWEncoder||!1,this._initBusinessInfo(e)}get isMainStreamPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.isMainStreamPublished)}get isMainAudioPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.localMainAudioTrack)}get isAuxStreamPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.isAuxStreamPublished)}get hasAuxStream(){return[...this.remotePublishedUserMap.values()].findIndex(e=>e.muteState.hasAuxiliary)>=0}get userMap(){return this.userManager.userMap}get remotePublishedUserMap(){return this.userManager.remotePublishedUserMap}get tinyIdToUserIdMap(){return new Map([...this.userMap.values()].map(e=>[e.tinyId,e.userId]))}join(e,t,s){return p(this,null,function*(){return this.userManager.mySelfId=this.userId,this.userManager.on("1",n=>{this.emit("peer-join",n)}),this.userManager.on("2",n=>{this.closeDownLinkConnection(n,"remote user exitRoom"),this.emit("peer-leave",n)}),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",o=>{var n=Sd(o,[]);T.emit(f.REMOTE_PUBLISH_STATE_CHANGED,N({room:this},n)),this.emit("remote-publish-state-changed",N({},n))}),this._joinOptions=e,new Promise((n,o)=>p(this,null,function*(){var a,c;this._joinReject=o;try{this.checkDestroy();try{yield Promise.all([this.initialize(),this.initSinglePC()])}catch(d){if(d instanceof C&&d.code===I.SPC_INITIALIZED_FAILED)(a=this._signalChannel)==null||a.destroy(),yield this.initialize();else return o(d)}yield this.doJoin(e,(c=this.singlePC)==null?void 0:c.clientAbility),n(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(d){o(d)}this._joinReject=null}))})}initSinglePC(){return p(this,null,function*(){if(!(!this.enableSPC||this.singlePC)){this.singlePC=new ri({signalChannel:this._signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.on("sei-message",e=>this.emit("sei-message",e)),this.singlePC.once("error",()=>this.fallbackToMPC());try{return yield this.singlePC.initialize()}catch(e){throw this.fallbackToMPC(),new C({code:I.SPC_INITIALIZED_FAILED,message:e==null?void 0:e.message})}}})}doJoin(e,t){return new Promise((s,n)=>p(this,null,function*(){var c,d,l;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),this._signalChannel.once(le.SETUP_FAILED,m=>{this.clearJoinTimeout(),T.emit(f.JOIN_SIGNAL_CONNECTION_END,{room:this,error:m}),n(m)}),ue((d=(c=this.scheduleResult)==null?void 0:c.config)==null?void 0:d.singlePC)&&As&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2);let o={roomId:String(e.roomId||e.strRoomId),useStringRoomId:this.useStringRoomId,privateMapKey:this.privateMapKey,trtcRole:e.role,trtcScene:this.scene==="live"?2:1,sdpSemantics:this.sdpSemantics,version:this._version,ua:navigator&&navigator.userAgent||"",terminalType:Ta(),netType:_r(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig};this._log.debug(`join room signal data: ${JSON.stringify(o)}`);let a=5e3;((l=this.scheduleResult.config)==null?void 0:l.enterRoomTimeout)&&this.scheduleResult.config.enterRoomTimeout>=1&&(a=this.scheduleResult.config.enterRoomTimeout*1e3),this._joinTimeout=window.setTimeout(()=>{n(new C({code:I.JOIN_ROOM_FAILED,message:D({key:v.JOIN_ROOM_TIMEOUT})}))},a),T.emit(f.JOIN_SEND_CMD,{room:this}),this._signalChannel.send(this.singlePC?W.SPC_JOIN_ROOM:W.JOIN_ROOM,o),this._signalChannel.once(P.JOIN_ROOM_RESULT,m=>{this.clearJoinTimeout();let{code:_,message:g,data:R,tinyId:y}=m.data;T.emit(f.JOIN_RECEIVED_CMD_RES,{room:this,code:_}),_===0?(this._log.info("Join room success, start heartbeat"),y&&(this.tinyId=y),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=R.publishers,this.singlePC&&this.singlePC.connect(R.ability).catch(()=>{}),s()):(this._log.error(`Join room failed result: ${_} error: ${g}`),n(new C({code:I.JOIN_ROOM_FAILED,extraCode:_,message:D({key:v.JOIN_ROOM_FAILED,data:{error:g,code:_}})})))})}))}reJoin(e=!0){return p(this,null,function*(){if(!this.isJoined){this._log.warn("reJoin abort");return}try{this._log.warn(`reJoin pending: ${this._joinOptions.roomId}`);let t,s=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,s.push(this.initSinglePC().then(n=>(t=n,n)))),this._signalChannel&&(this._signalChannel.race=e,this._signalChannel.close(),s.push(this._signalChannel.connect())),yield Promise.all(s),yield this.doJoin(L(N({},this._joinOptions),{role:this.role==="anchor"?20:21,privateMapKey:this.privateMapKey}),t),this._log.warn("reJoin success"),ee.logSuccessEvent({userId:this.userId,eventType:Le.REJOIN}),this.singlePC){let n=o=>{var a;o.state==="CONNECTED"&&((a=this.singlePC)==null||a.off(Dt.CONNECTION_STATE_CHANGED,n),this.uplinkConnection instanceof _d&&this.uplinkConnection.onSinglePCReconnected(),this.remotePublishedUserMap.forEach(c=>{c.installEvents(),c.onSinglePCReconnected()}))};this.singlePC.on(Dt.CONNECTION_STATE_CHANGED,n),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof Do&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(t){this._log.warn(`reJoin fail ${t}`),this.reset(),ee.logFailedEvent({userId:this.userId,eventType:Le.REJOIN,error:t}),this.emit("error",new C({code:I.JOIN_ROOM_FAILED,message:D({key:v.REJOIN_ROOM_FAILED,data:{roomId:this._joinOptions.roomId}})}))}})}initialize(){return p(this,null,function*(){let{mainUrl:e,backupUrl:t}=this.getSignalChannelUrl(),s=this._signalChannel||Sl(this.userId),n=!!(s&&s.isConnected&&s.keepAlive);return this._log.info(`${n?"reuse":"setup"} signal channel`),n?(s.url=e,s.backupUrl=t,s.room=this,this._signalChannel=s):(this._signalChannel=new kr({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:e,backupUrl:t,race:this.enableSPC&&!this.proxy_ws,room:this}),this._customMessageManager=new en(this,this._signalChannel),this._customMessageManager.on("message",o=>{this.emit("custom-message",o)})),this._networkQuality||(this._networkQuality=new qi({signalChannel:this._signalChannel,room:this}),this._networkQuality.on(qi.EVENT_NETWORK_QUALITY,o=>{this.emit("network-quality",o)})),we(this,this._signalChannel).add(le.CONNECTION_STATE_CHANGED,o=>{T.emit(f.SIGNAL_CONNECTION_STATE_CHANGED,N({room:this},o)),this.emit("signal-connection-state-changed",o)}).add(le.RECONNECT_FAILED,o=>{this.reset(),this.emit("error",o)}).add(P.PEER_JOIN,o=>{let{srcTinyId:a,userId:c,role:d}=o.data.data;this.userManager.addUser({userId:c,tinyId:a,role:d})}).add(P.PEER_LEAVE,o=>{let{userId:a,reason:c=0}=o.data.data;this.userManager.deleteUser(a,c)}).add(P.UPDATE_REMOTE_MUTE_STAT,o=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=10*1e3&&this.doHeartbeat(),this.onPublishedUserList(o.data)}).add(P.CLIENT_BANNED,o=>{let a=o.data.data,{reason:c}=a;if(ee.uploadEvent({log:`stat-banned:${c}`,userId:this.userId}),c==="user_time_out"){this._log.warn(`${c} last heart beat time: ${this._lastHeartBeatTime} interval: ${Date.now()-this._lastHeartBeatTime}, visibility: ${document.visibilityState}`),this.reJoin();return}this._log[c==="kick"?"error":"info"](`user was banned because of [${c}]`),this.reset(),this.emit("banned",{reason:c})}),this._signalChannel.once(le.SETUP_SUCCESS,o=>{this.tinyId=o.signalInfo.tinyId,T.emit(f.JOIN_SIGNAL_CONNECTION_END,{room:this})}),T.emit(f.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this._signalChannel.connect(),n&&T.emit(f.JOIN_SIGNAL_CONNECTION_END,{room:this}),n})}setSignalChannel(e){this._signalChannel=e,e||pe(this)}leave(){return p(this,null,function*(){var e;try{yield this.doHeartbeat()}catch(t){}this._log.info("leave() => leaving room"),T.emit(f.LEAVE_SEND_CMD,{room:this}),(e=this._signalChannel)==null||e.send(W.LEAVE_ROOM)})}clearNetworkQuality(){this._networkQuality&&(this._networkQuality.stop(),this._networkQuality=null)}closeConnections(){this.remotePublishedUserMap.forEach(e=>{this.closeDownLinkConnection(e.userId,"you exitRoom")})}clearJoinTimeout(){clearTimeout(this._joinTimeout),this._joinTimeout=-1}startHeartbeat(){this._heartbeat===-1&&(this._heartbeat=Z.run(pt,this.doHeartbeat.bind(this),{delay:2e3}))}stopHeartbeat(){this._heartbeat!==-1&&(this._log.info("stopHeartbeat"),Z.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return p(this,null,function*(){var a;let e=this.badCaseDetector.getMonitorFreeze(),t=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:e});if(this.badCaseDetector.resetMonitor(),!((a=this._signalChannel)!=null&&a.isConnected))return;let s=this._signalChannel.isConnected?Ju(this.userId):[],n=N({str_sdk_version:Gr,uint64_datetime:new Date().getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_device_info:{uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:_r()},msg_event_msg:s,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},t);T.emit(f.HEARTBEAT_REPORT,{room:this,report:n}),this._signalChannel.send(W.ON_QUALITY_REPORT,n),this.emit("heartbeat-report",L(N({},n),{bytes_sent:this._stats.totalBytesSent+this._signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this._signalChannel.bytesReceived}));let o=Date.now();this._lastHeartBeatTime>0&&o-this._lastHeartBeatTime>1e4&&this._log.warn(`heartbeat took ${o-this._lastHeartBeatTime}`),this._signalChannel.isConnected&&(this._lastHeartBeatTime=o),!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)})}onPublishedUserList(e){if(!this.isJoined)return;let t=e.data.userList.map(({userId:s,srcTinyId:n,flag:o})=>{s===this.userId&&this.uplinkConnection&&(this.uplinkConnection.flag=o);let a=this.remotePublishedUserMap.get(s);return a&&this.checkSubscribeBigSmallVideo(a),{userId:s,tinyId:n,flag:o}});T.emit(f.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:t}),this.userManager.setRemotePublishedUserList(t)}closeUplink(e="you unpublished"){this.uplinkConnection&&(this.localTracks.size>0&&this.uplinkConnection.doUnpublish(),this.uplinkConnection.close(e),this.uplinkConnection=null),this.localTracks.forEach(t=>t.unpublish()),this.localTracks.clear()}createDownlinkConnection({userId:e,tinyId:t,flag:s}){let n=new(this.singlePC?Xl:td)({userId:e,tinyId:t,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,flag:s});this.userManager.addRemotePublishedUser(n),this.installDownlinkEvents(n,e),this.emit("remote-published",n)}closeDownLinkConnection(e,t="remote user unpublished"){let s=this.remotePublishedUserMap.get(e);s&&(s.close(t),this.emit("remote-unpublished",s))}installDownlinkEvents(e,t){e.on("error",s=>{let n=s.getCode();n!==I.ICE_TRANSPORT_ERROR&&(n===I.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",s))}),e.on("connection-state-changed",s=>{this.emit("media-connection-state-changed",L(N({},s),{userId:e.userId}))}),e.on("firewall-restriction",()=>{this.emit("firewall-restriction")})}startSyncUserListInterval(){this._syncUserListInterval===-1&&(this._syncUserListInterval=Z.run(pt,this.syncUserList.bind(this)))}stopSyncUserListInterval(){Z.clearTask(this._syncUserListInterval),this._syncUserListInterval=-1}syncUserList(){return this.getUserList().then(e=>{this.userManager.setUserList(e)}).catch(e=>{this._log.debug(`sync user list failed: ${e}`)})}getUserList(){var e;return(e=this._signalChannel)!=null&&e.isConnected?this._signalChannel.sendWaitForResponse({command:W.GET_USER_LIST,responseCommand:P.USER_LIST_RES,enableLog:!1,timeout:2e3}).then(({data:t})=>{let{code:s,message:n}=t;if(s===0)return(t.data&&t.data.userList||[]).map(({userId:a,srcTinyId:c,role:d})=>({userId:a,tinyId:c,role:d}));throw D({key:v.SIGNAL_RESPONSE_FAILED,data:{signalResponse:P.USER_LIST_RES,code:s,message:n}})}):Promise.reject("not connected")}getAllConnections(){let e=[...this.remotePublishedUserMap.values()];return this.uplinkConnection&&e.push(this.uplinkConnection),e}isRelayMaybeFailed(){if(this._signalChannel&&!this._signalChannel.isOnline||!Qc)return!1;if(this.singlePC)return this.singlePC.reconnectionCount>6;let e=this.getAllConnections();if(e.length===0)return!1;for(let t=0;t<e.length;t++)if(e[t].getReconnectionCount()<6)return!1;return!0}checkConnectionsToReconnect(){var e;this.singlePC?((e=this.singlePC.getPeerConnection())==null?void 0:e.connectionState)===se.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach(s=>{if(s instanceof We&&!s.getIsReconnecting()){let n=s.getPeerConnection();n&&n.connectionState===se.CLOSED&&(this._log.warn(`[${s.getUserId()}] pc is closed but not reconnect`),s.startReconnection())}})}fallbackToMPC(){return p(this,null,function*(){var e;if(this._log.warn("fallback to multi pc"),ee.uploadEvent({log:"stat-fallback",userId:this.userId}),this.enableSPC=!1,(e=this.singlePC)==null||e.close(),this.singlePC=null,this.isJoined&&(yield this.reJoin(!1)),this.uplinkConnection){let t=this.uplinkConnection;this.uplinkConnection=new Do({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}),t.isMainStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:t.localMainAudioTrack,localVideoTrack:t.localMainVideoTrack,isAuxiliary:!1})),t.isAuxStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:t.localAuxAudioTrack,localVideoTrack:t.localAuxVideoTrack,isAuxiliary:!0})),t.close()}this.remotePublishedUserMap.forEach(t=>{let s=new td({userId:t.userId,tinyId:t.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,flag:t.flag,remoteAudioTrack:t.remoteAudioTrack,remoteVideoTrack:t.remoteVideoTrack,remoteAuxiliaryTrack:t.remoteAuxiliaryTrack});this.installDownlinkEvents(s,t.userId),this.remotePublishedUserMap.set(t.userId,s),t.isMainStreamSubscribed&&s.subscribe(t.subscribeState,"main"),t.isAuxStreamSubscribed&&s.subscribe(t.subscribeState,"auxiliary")})})}destroy(){this.isDestroyed||(this._signalChannel&&(this._log.info("destroying SignalChannel"),this._signalChannel.close(),this._signalChannel=null),super.destroy(),this._joinReject&&(this._joinReject(new C({code:I.INVALID_OPERATION,message:D({key:v.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners())}switchRole(e){return p(this,null,function*(){this.role!==e&&(e==="audience"&&this.uplinkConnection&&this.closeUplink("you switch role to audience"),yield this.doSwitchRole(e))})}doSwitchRole(e){let t={command:W.SWITCH_ROLE,data:{role:e==="anchor"?20:21,privateMapKey:this.privateMapKey},responseCommand:P.SWITCH_ROLE_RES,retries:1};return this._log.info(`switchRole signal data: ${JSON.stringify(t.data)}`),this._signalChannel.sendWaitForResponseWithRetry(t).then(s=>{let{code:n,message:o}=s.data;if(n!==0)throw new C({code:I.SWITCH_ROLE_FAILED,message:D({key:v.SWITCH_ROLE_FAILED,data:{message:o,code:n}})});this.role=e}).catch(s=>{throw s instanceof C&&s.getCode()===I.API_CALL_TIMEOUT&&(s=new C({code:I.SWITCH_ROLE_FAILED,message:D({key:v.SWITCH_ROLE_TIMEOUT})})),this._log.error(s),s})}publish(...e){return p(this,null,function*(){let t={},s={};e.forEach(c=>{c instanceof Ne&&(c instanceof bt?s.audio=c:t.audio=c),c instanceof ae&&(c instanceof Ge&&c.mediaType===2?s.video=c:t.video=c)});let n=tn(t),o=tn(s);(!n||!o)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new _d({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}):this.uplinkConnection=new Do({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}),this.uplinkConnection.on("connection-state-changed",c=>{this.emit("media-connection-state-changed",L(N({},c),{userId:this.userId}))}),this.uplinkConnection.on("firewall-restriction",()=>{this.emit("firewall-restriction")}),this.uplinkConnection.on("error",c=>{let d=c.getCode();d!==I.ICE_TRANSPORT_ERROR&&(d===I.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",c))}));let a=e.map(c=>c.kind).join(",");n||(this._log.info(`publish() => main ${a}`),yield this.uplinkConnection.publish({localAudioTrack:t.audio,localVideoTrack:t.video,isAuxiliary:!1}),this._log.info("main is published")),o||(this._log.info(`publish() => aux ${a}`),yield this.uplinkConnection.publish({localAudioTrack:s.audio,localVideoTrack:s.video,isAuxiliary:!0}),this._log.info("aux is published"))})}unpublish(...e){return p(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||!this.isMainStreamPublished&&!this.isAuxStreamPublished||!this.uplinkConnection)return;let t={},s={};e.forEach(n=>{!n.mediaTrack||!n.isPublished||(n instanceof Ne&&(n instanceof bt?s.audio=n:t.audio=n),n instanceof ae&&(n instanceof Ge&&n.mediaType===2?s.video=n:t.video=n))});try{let n=e.map(o=>o.kind).join(",");tn(t)||(this._log.info(`unpublish() => main ${n}`),yield this.uplinkConnection.unpublish({localAudioTrack:t.audio,localVideoTrack:t.video})),tn(s)||(this._log.info(`unpublish() => aux ${n}`),yield this.uplinkConnection.unpublish({localAudioTrack:s.audio,localVideoTrack:s.video}))}catch(n){}this.localTracks.size===0&&this.closeUplink("you unpublished")})}addTrack(e){if(!this.uplinkConnection||!e.mediaTrack)return Promise.resolve();let t=this.uplinkConnection.addTrack(e);return e.publish(this,t),t}removeTrack(e){return!this.uplinkConnection||!e.mediaTrack?Promise.resolve():this.uplinkConnection.removeTrack(e).then(t=>(e.unpublish(),t))}replaceTrack(e){return!this.uplinkConnection||!e.mediaTrack||!wa()?Promise.resolve():this.uplinkConnection.replaceTrack(e).then(t=>{T.emit(f.LOCAL_TRACK_REPLACED,{track:e})})}setBandWidth(e){return p(this,null,function*(){!this.uplinkConnection||(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())})}enableSmall(e){return p(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:h.VIDEO,videoType:h.SMALL,bandwidth:this.uplinkConnection.localMainVideoTrack.small.bitrate})),yield this.uplinkConnection.enableSmall(e)})}subscribe(...e){return p(this,null,function*(){if(e=e.filter(o=>!o.isSubscribed),e.length===0)return;let{userId:t}=e[0],s=this.remotePublishedUserMap.get(t);if(!s)return;let n=e.find(o=>o.mediaType===2)?"auxiliary":"main";try{let o=N({},s.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:o.audio=!0;break;case 4:o.video=!0;break;case 8:o.smallVideo=!0;break;case 2:o.auxiliary=!0;break}});let a=this._changeBigSmallRecords.get(t);a&&a.options.smallVideo&&s.muteState.hasSmall&&o.video&&(o.video=!1,o.smallVideo=!0),T.emit(f.SUBSCRIBE_START,{room:this,streamType:n,remotePublishedUser:s,subscribeState:o}),this._log.info(`subscribe() => ${t} ${n} [${Oo(o)}] prev: [${Oo(s.subscribeState)}]`),yield s.subscribe(o,n),this._log.info(`subscribe ${t} ${n} done`);for(let c of e)c.mediaTrack||(yield c.waitHasMediaTrack());T.emit(f.SUBSCRIBE_SUCCESS,{room:this,streamType:n,remotePublishedUser:s})}catch(o){let a=o instanceof C?o.getCode():I.UNKNOWN,c=o;throw o instanceof C?a===I.REMOTE_STREAM_NOT_EXIST&&(c=new C({code:I.API_CALL_ABORTED,message:D({key:v.API_CALL_ABORTED,data:{message:o.message,userId:t,streamType:n}})}),this._log.warn(c)):(c=new C({code:a,message:D({key:v.SUBSCRIBE_FAILED,data:{message:o.message,userId:t,streamType:n}})}),this._log.error(c)),c}})}unsubscribe(...e){return p(this,null,function*(){let{userId:t}=e[0],s=this.remotePublishedUserMap.get(t);if(!s)return;let n=e.find(o=>o.mediaType===2)?"auxiliary":"main";this._log.info(`unsubscribe() => ${t} ${n}`);try{yield s.unsubscribe({remoteTracks:e,streamType:n})}catch(o){this._log.warn(`unsubscribe() => failed ${o}`)}e.forEach(o=>{o.unsubscribe(),o.mediaType===8&&o.setMediaType(4)}),T.emit(f.UNSUBSCRIBE_SUCCESS,{room:this,streamType:n,remotePublishedUser:s})})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAudioVolumeEvaluation(e=2e3,t){if(e<=0){this._enableAudioVolumeEvaluation=!1,Z.clearTask(this._audioVolumeIntervalId);return}e=Math.floor(Math.max(e,100)),T.emit(f.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&Z.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=Z.run(Qr,()=>{var n;let s=[];(n=this.remotePublishedUserMap)==null||n.forEach(o=>{if(o.muteState.hasAudio){let a=Math.floor(o.remoteAudioTrack.getAudioLevel()*100);s.push({userId:o.userId,volume:a})}}),this.emit("audio-volume",s)},{fps:1e3/e,backgroundTask:t})}getLocalAudioStats(){return p(this,null,function*(){let e={};if(e[this.userId]={bytesSent:0,packetsSent:0},this.uplinkConnection){let t=yield this._stats.getSenderStats(this.uplinkConnection);e[this.userId]={bytesSent:t.audio.bytesSent,packetsSent:t.audio.packetsSent}}return e})}getLocalVideoStats(){return p(this,null,function*(){let e={};if(e[this.userId]={bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0},this.uplinkConnection){let{video:{bytesSent:t,packetsSent:s,framesEncoded:n,framesSent:o,frameWidth:a,frameHeight:c}}=yield this._stats.getSenderStats(this.uplinkConnection);e[this.userId]={bytesSent:t,packetsSent:s,framesEncoded:n,framesSent:o,frameWidth:a,frameHeight:c}}return e})}getTransportStats(){return p(this,null,function*(){let e={rtt:0,downlinksRTT:{}};if(this.uplinkConnection){let t=yield this._stats.getSenderStats(this.uplinkConnection);e.rtt=t.rtt}for(let[,t]of this.remotePublishedUserMap){let s=yield this._stats.getReceiverStats(t);e.downlinksRTT[s.userId]=s.rtt}return e})}getRemoteVideoStats(e){return p(this,null,function*(){let t={};for(let[s,n]of this.remotePublishedUserMap)e==="main"&&n.muteState.hasVideo&&(t[s]=n.remoteVideoTrack.stat),e==="auxiliary"&&n.muteState.hasAuxiliary&&(t[s]=n.remoteAuxiliaryTrack.stat);return t})}getRemoteAudioStats(){return p(this,null,function*(){let e={};for(let[t,s]of this.remotePublishedUserMap)s.muteState.hasAudio&&(e[t]=s.remoteAudioTrack.stat);return e})}setTurnServer(e,t){this._log.info(`set turn server: ${JSON.stringify(e)} ${t||""}`);let s=[];Array.isArray(e)?e.forEach(n=>s.push(Me.getTurnServer(n))):Me.isPlainObject(e)&&s.push(Me.getTurnServer(e)),this._turnServers=s,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this._signalChannel.sendWaitForResponse({command:W.START_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:P.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this._signalChannel.sendWaitForResponse({command:W.STOP_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:P.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"})}sendStartPublishCDN(e,t=!0){return this._signalChannel.sendWaitForResponse({command:t?W.START_PUBLISH_TENCENT_CDN:W.START_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?P.START_PUBLISH_TENCENT_CDN_RES:P.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"})}sendStopPublishCDN(e,t=!0){return this._signalChannel.sendWaitForResponse({command:t?W.STOP_PUBLISH_TENCENT_CDN:W.STOP_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?P.STOP_PUBLISH_TENCENT_CDN_RES:P.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}sendAbilityStatus(e){var t;(t=this._signalChannel)==null||t.sendWaitForResponse({command:W.ABILITY_STATUS_REPORT,data:e,timeout:5e3,responseCommand:P.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch(s=>{})}getIceServers(){return this._turnServers.length===0&&this.scheduleResult.iceServers?this.scheduleResult.iceServers:this._turnServers}getIceTransportPolicy(){return this._iceTransportPolicy||this.scheduleResult.iceTransportPolicy||"all"}getLogger(){return this._log}enableAIVoice(){throw new Error("Method not implemented.")}getSignalChannelUrl(){let e={mainUrl:"",backupUrl:""},t=Me.getEnv();return t?(e.mainUrl=`wss://${t}.rtc.qq.com`,e.backupUrl=e.mainUrl):this.proxy_ws?(e.mainUrl=this.proxy_ws,e.backupUrl=e.mainUrl):Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(e.mainUrl=`wss://${this.scheduleResult.domains[0]}`,e.backupUrl=e.mainUrl,this.scheduleResult.domains[1]&&(e.backupUrl=`wss://${this.scheduleResult.domains[1]}`)),e}getSignalInfo(){var e;return((e=this._signalChannel)==null?void 0:e.getSignalInfo())||{clientIp:"",relayIp:""}}reset(e=!1){this.stopSyncUserListInterval(),this.stopHeartbeat(),this.closeConnections(),this.clearNetworkQuality(),this.closeUplink("you exitRoom"),this._signalChannel&&(e&&this._signalChannel.keepAlive&&this._signalChannel.isConnected?this._signalChannel.stopKeepAliveIn(3600):this._signalChannel.close(),this.setSignalChannel(null)),this._stats.reset(),this.userManager.clear(),this.userManager.removeAllListeners(),this.singlePC&&(this.singlePC.close(),this.singlePC=null),this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}}checkSubscribeBigSmallVideo(e){return p(this,null,function*(){let{subscribeState:t,userId:s,muteState:{hasSmall:n,hasVideo:o}}=e;if(!n&&!o||!t.video&&!t.smallVideo)return;let a=this._changeBigSmallRecords.get(s);if(!a||a.isSubscribing||a.reSubscribeCount<=0)return;let{options:c,reSubscribeCount:d}=a;if(c.video&&t.video||c.smallVideo&&t.smallVideo&&n)return;let l={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:c.video,smallVideo:c.smallVideo};try{if(!n&&l.smallVideo&&(l.video=!0,l.smallVideo=!1),l.smallVideo===t.smallVideo&&l.video===t.video)return;a.isSubscribing=!0,a.reSubscribeCount=d-1,yield e.subscribe(l,"main"),e.remoteVideoTrack.setMediaType(l.smallVideo?8:4),this._log.info(`change [${s}] to ${l.smallVideo?"small":"big"} video successfully. count ${Zi-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount=Zi}catch(m){this._log.info(`change [${s}] to ${l.smallVideo?"small":"big"} video failed. count ${Zi-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount===0&&this._changeBigSmallRecords.delete(s)}})}changeType(e,t){let n={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:Zi};this._changeBigSmallRecords.set(t.userId,n),this._log.info(`set [${t.userId}] video prefer type: ${e?"small":"big"}`)}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(e){this._businessInfo=e.businessInfo;let t={};if(Zl(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!Vr(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new C({code:I.INVALID_PARAMETER,message:D({key:v.INVALID_PURE_AUDIO})});this._pureAudioPushMode=e.pureAudioPushMode,t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.pure_audio_push_mod=this._pureAudioPushMode}if(!Vr(e.userDefineRecordId)){let s=/^[A-Za-z0-9_-]{1,64}$/gi;if(e.userDefineRecordId.match(s)===null)throw new C({code:I.INVALID_PARAMETER,message:D({key:v.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!Vr(e.userDefinePushArgs))if(Zl(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256)t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_push_args=e.userDefinePushArgs;else throw new C({code:I.INVALID_PARAMETER,message:D({key:v.INVALID_USER_DEFINE_PUSH_ARGS})});tn(t)||(this._businessInfo=JSON.stringify(t))}sendSEI(e,t){this.singlePC&&this.singlePC.sendSEI(e,t)}sendCustomMessage(e){var t;(t=this._customMessageManager)==null||t.send(e)}};b([qc(["left",te.INIT],"joined"),Ri({settings:{retries:1,timeout:0},onError(r,i,e){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),St(!0),this.reset(),i()):this._signalChannel&&this._signalChannel.isConnected&&this._signalChannel.keepAlive?(this._log.warn("is using keepAlive ws, retry join"),this._signalChannel.close(),this.reset(),i()):(this.reset(),this._log.error(r),e(r))}}),ml()],Mt.prototype,"join",1),b([qc("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),pl(),so("leave room"),Ws({fnName:"publish",validateArgs:!1}),Ws({fnName:"unsubscribe",validateArgs:!1})],Mt.prototype,"leave",1),b([Nt(),Ql(),Ri({settings:{retries:Pt,timeout:r=>It(r)},onError(r,i,e){var t;(t=r.message)!=null&&t.includes("timeout")?(this._log.warn("publish timeout"),i()):(this._log.error(`publish failed: ${r}`),e(r),T.emit(f.PUBLISH_FAILED,{room:this}))}})],Mt.prototype,"publish",1),b([Ws({fnName:"publish"}),Vu("api-call"),Nt(),zl()],Mt.prototype,"unpublish",1),b([Rr((...r)=>r[0].userId),oo(),_l(),Ri({settings:{retries:Pt,timeout:r=>It(r)},onError(r,i,e,t){r.message.includes("timeout")?(this._log.warn("subscribe timeout"),i()):(this._log.error(`subscribe failed: ${r}`),e(r),T.emit(f.SUBSCRIBE_FAILED,{room:this,remoteTracks:t}))}})],Mt.prototype,"subscribe",1),b([Ws({fnName:"subscribe",callback(...r){this.singlePC||r.forEach(i=>{let e=this.remotePublishedUserMap.get(i.userId);e&&!e.isMainStreamSubscribed&&!e.isAuxStreamSubscribed&&e.close("you unsubscribed")})}}),Rr((...r)=>r[0].userId)],Mt.prototype,"unsubscribe",1);$s.create=$s._create.bind($s,Mt);var ux=$s;export{ux as default};