trtc-sdk-v5 5.8.2-beta.7 → 5.8.2-beta.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trtc-sdk-v5",
3
- "version": "5.8.2-beta.7",
3
+ "version": "5.8.2-beta.8",
4
4
  "description": "Tencent Cloud RTC SDK for Web",
5
5
  "main": "trtc.js",
6
6
  "types": "index.d.ts",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rtc-plugin/cdn-streaming",
3
- "version": "5.8.2-beta.7",
3
+ "version": "5.8.2-beta.8",
4
4
  "description": "TRTC Web SDK 5.x CDN streaming plugin",
5
5
  "main": "./cdn-streaming.esm.js",
6
6
  "author": "longyuqi <longyuqi@tencent.com>",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rtc-plugin/cross-room",
3
- "version": "5.8.2-beta.7",
3
+ "version": "5.8.2-beta.8",
4
4
  "description": "TRTC Web SDK 5.x Cross Room plugin",
5
5
  "main": "./cross-room.esm.js",
6
6
  "author": "rychouwei <rychouwei@tencent.com>",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rtc-plugin/debug",
3
- "version": "5.8.2-beta.7",
3
+ "version": "5.8.2-beta.8",
4
4
  "description": "TRTC Web SDK Debug Plugin",
5
5
  "main": "./debug.esm.js",
6
6
  "author": "leochliu <leochliu@tencent.com>",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rtc-plugin/device-detector",
3
- "version": "5.8.2-beta.7",
3
+ "version": "5.8.2-beta.8",
4
4
  "description": "TRTC Web SDK 5.x device detector plugin",
5
5
  "main": "./device-detector.esm.js",
6
6
  "author": "edwards <edwards@tencent.com>",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rtc-plugin/basic-beauty",
3
- "version": "5.8.2-beta.7",
3
+ "version": "5.8.2-beta.8",
4
4
  "description": "TRTC Web SDK 5.x basic-beauty plugin",
5
5
  "main": "./basic-beauty.esm.js",
6
6
  "author": "longyuqi <longyuqi@tencent.com>",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rtc-plugin/beauty",
3
- "version": "5.8.2-beta.7",
3
+ "version": "5.8.2-beta.8",
4
4
  "description": "TRTC Web SDK 5.x beauty plugin",
5
5
  "main": "./beauty.esm.js",
6
6
  "author": "longyuqi <longyuqi@tencent.com>",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rtc-plugin/virtual-background",
3
- "version": "5.8.2-beta.7",
3
+ "version": "5.8.2-beta.8",
4
4
  "description": "TRTC Web SDK 5.x virtual background plugin",
5
5
  "main": "./virtual-background.esm.js",
6
6
  "author": "longyuqi <longyuqi@tencent.com>",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rtc-plugin/watermark",
3
- "version": "5.8.2-beta.7",
3
+ "version": "5.8.2-beta.8",
4
4
  "description": "TRTC Web SDK 5.x watermark plugin",
5
5
  "main": "./watermark.esm.js",
6
6
  "author": "longyuqi <longyuqi@tencent.com>",
package/trtc.esm.js CHANGED
@@ -23,7 +23,7 @@ ${t.stack}`)),this.sendRequest(Ai(this._configs.sdkAppId,mi.LOG),s)}sendRequest(
23
23
  clearInterval(timerID);
24
24
  }
25
25
  };
26
- `],{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=x(),t,s=()=>{if(t=x()-e,t>=i.delay&&(e=x()-Math.floor(t%i.delay),i.callback(),i.loopCount+=1),!this.isBreakLoop(i))return i.ricID=Fl(s,{timeout:i.delay})};return i.ricID=Fl(s,{timeout:i.delay})}static raf(i){i.delay=(1e3/i.fps).toFixed(2);let e=x(),t,s=()=>{if(document.hidden&&i.backgroundTask)return t=x()-e,e=x(),i.callback(),i.loopCount+=1,this.isBreakLoop(i)?void 0:i.timeoutID=setTimeout(s,i.delay-Math.floor(t%i.delay));if(t=x()-e,t>=i.delay&&(e=x()-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 o=()=>{if(document.hidden){let n=x()-e;n>=i.delay?s():i.timeoutID=setTimeout(s,i.delay-n)}};document.addEventListener("visibilitychange",o),i.onVisibilitychange=o,document.hidden&&o()}return i.taskID}static hasTask(i){return this.taskMap.has(i)}static clearTask(i){if(!this.taskMap.has(i))return!0;let{intervalID:e,timeoutID:t,rafID:s,ricID:o,onVisibilitychange:n,worker:a}=this.taskMap.get(i);return a&&a.terminate(),e&&clearInterval(e),t&&clearTimeout(t),s&&Ap(s),o&&Ip(o),n&&document.removeEventListener("visibilitychange",n),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}};Hs.taskMap=new Map,Hs.currentTaskID=1;var re=Hs;var WE={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 ve={LOADED_DATA:h.LOADEDDATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error"};var wt={};ts(wt,{create:()=>De,remove:()=>me});var Gs=new WeakMap;function De(r,i){Gs.has(r)||Gs.set(r,[]);let e=Gs.get(r),s={add:(o,n)=>("addEventListener"in i?(e.push(i.removeEventListener.bind(i,o,n)),i.addEventListener(o,n)):(e.push(i.off.bind(i,o,n)),i.on(o,n)),s)};return s}function me(r){let i=Gs.get(r);i&&(i.forEach(e=>e()),Gs.delete(r))}var Vt=new WeakMap;function it({settings:r={retries:5,timeout:2e3},onError:i,onRetrying:e,onRetryFailed:t}){return function(s,o,n){let a=Dt({retryFunction:n.value,settings:r,onError({error:c,retry:d,reject:u,retryFuncArgs:p}){var m;i?i.call(this,c,()=>{var f;(f=Vt.get(s))!=null&&f.has(o)?d():u(c)},u,p):(m=Vt.get(s))!=null&&m.has(o)?d():u(c)},onRetrying(c,d){var u;vt(e)&&e.call(this,c,d),(u=Vt.get(s))!=null&&u.has(o)&&(Vt.get(s).get(o).stopRetry=d)},onRetryFailed:t});return n.value=function(...c){let d=Vt.get(s);return d?d.set(o,{args:c}):Vt.set(s,new Map([[o,{args:c}]])),a.apply(this,c).finally(()=>{var u;return(u=Vt.get(s))==null?void 0:u.delete(o)})},n}}function Ws({fnName:r,callback:i,validateArgs:e=!0}){return function(t,s,o){let n=o.value;return o.value=function(...a){var c,d;if((c=Vt.get(t))!=null&&c.has(r)){let{stopRetry:u,args:p}=Vt.get(t).get(r),m=!0;if(e){for(let f of p)if(!a.find(R=>R===f)){m=!1;break}}m&&(i&&i.apply(this,a),u&&u(),(d=Vt.get(t))==null||d.delete(r))}return n.apply(this,a)},o}}var Cp=1,Rp=0,dn=class{constructor(i=!0){this.countMap=new Map;this.distributionMap=new Map;this.log=I.createLogger({id:"kv"});i&&(g.on("102",({track:e,cost:t})=>{this.addSuccessEvent({key:e.kind===h.AUDIO?ln.START_MICROPHONE:oc.START_CAMERA,cost:t})}),g.on("103",({track:e,error:t})=>{this.addFailedEvent({key:e.kind===h.AUDIO?ln.START_MICROPHONE:oc.START_CAMERA,error:t})}))}getReportData(){let i={msg_sdk_basic_info:{uint32_sdk_version:qa(this.version||Re),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,o])=>({uint32_item_key:s,uint32_item_value:o}))}))};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 o;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=((o=this.distributionMap)==null?void 0:o.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 o=((a=this.distributionMap)==null?void 0:a.get(i))||new Map,n=0;if(ee(t))n=Math.floor(e/t);else for(let c=t.length-1;c>0;c--)if(e>t[c]){n=c;break}o.set(n,(o.get(n)||0)+1),this.distributionMap.set(i,o)}addSuccessEvent({key:i,cost:e,timeKey:t,split:s}){if(!!i&&(this.addEnum({key:i,value:Cp,useUV:!1}),e)){let o=+String(i).slice(-3);o<800&&o>=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=A.UNKNOWN;e&&(ee(e)?t=e:(!T(e.extraCode)||!T(e.code))&&(t=e.extraCode||e.code)),this.addEnum({key:i,value:Rp,useUV:!1}),this.addEnum({key:i,value:t,useUV:!1})}},un=(G=>(G[G.enterRoom=500700]="enterRoom",G[G.exitRoom=500701]="exitRoom",G[G.switchRole=500702]="switchRole",G[G.destroy=500703]="destroy",G[G.startLocalAudio=500704]="startLocalAudio",G[G.updateLocalAudio=500705]="updateLocalAudio",G[G.stopLocalAudio=500706]="stopLocalAudio",G[G.startLocalVideo=500707]="startLocalVideo",G[G.updateLocalVideo=500708]="updateLocalVideo",G[G.stopLocalVideo=500709]="stopLocalVideo",G[G.startScreenShare=500710]="startScreenShare",G[G.updateScreenShare=500711]="updateScreenShare",G[G.stopScreenShare=500712]="stopScreenShare",G[G.startRemoteVideo=500713]="startRemoteVideo",G[G.updateRemoteVideo=500714]="updateRemoteVideo",G[G.stopRemoteVideo=500715]="stopRemoteVideo",G[G.muteRemoteAudio=500716]="muteRemoteAudio",G[G.setRemoteAudioVolume=500717]="setRemoteAudioVolume",G[G.use=500718]="use",G[G.sendSEIMessage=5e5]="sendSEIMessage",G[G.sendCustomMessage=500001]="sendCustomMessage",G))(un||{}),nc=(d=>(d[d.AudioMixer=550700]="AudioMixer",d[d.AIDenoiser=551700]="AIDenoiser",d[d.VirtualBackground=570700]="VirtualBackground",d[d.Beauty=571700]="Beauty",d[d.Watermark=572700]="Watermark",d[d.BasicBeauty=574700]="BasicBeauty",d[d.CDNStreaming=590700]="CDNStreaming",d[d.DeviceDetector=591700]="DeviceDetector",d[d.Debug=592700]="Debug",d))(nc||{}),ac=(d=>(d[d.AudioMixer=550701]="AudioMixer",d[d.AIDenoiser=551701]="AIDenoiser",d[d.VirtualBackground=570701]="VirtualBackground",d[d.Beauty=571701]="Beauty",d[d.Watermark=572701]="Watermark",d[d.BasicBeauty=574701]="BasicBeauty",d[d.CDNStreaming=590701]="CDNStreaming",d[d.DeviceDetector=591701]="DeviceDetector",d[d.Debug=592701]="Debug",d))(ac||{}),cc=(d=>(d[d.AudioMixer=550702]="AudioMixer",d[d.AIDenoiser=551702]="AIDenoiser",d[d.VirtualBackground=570702]="VirtualBackground",d[d.Beauty=571702]="Beauty",d[d.Watermark=572702]="Watermark",d[d.BasicBeauty=574702]="BasicBeauty",d[d.CDNStreaming=590702]="CDNStreaming",d[d.DeviceDetector=591702]="DeviceDetector",d[d.Debug=592702]="Debug",d))(cc||{});var ln=(t=>(t[t.START_MICROPHONE=501700]="START_MICROPHONE",t[t.MICROPHONE_CAHNNELS=501701]="MICROPHONE_CAHNNELS",t[t.MICROPHONE_SAMPLERATE=501702]="MICROPHONE_SAMPLERATE",t))(ln||{});var oc=(i=>(i[i.START_CAMERA=511700]="START_CAMERA",i))(oc||{});var yp=new dn(!0),Gi=new dn(!1);var D=yp;var Ut=class extends F{constructor(e,t){super(e.id,`${t}-player`);this.kind=t;l(this,"id");l(this,"element",null);l(this,"track");l(this,"url");l(this,"attr");l(this,"muted");l(this,"_log");l(this,"_pausedRetryCount");l(this,"_isElementPlayingFired",!1);l(this,"_interval");l(this,"_delayDestroyTimeoutId",0);l(this,"_isReplayByRecreateMediaStreamIng",!1);this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=Ca,this._state="STOPPED",this.bindTrackEvents(),this._log.info(`create ${t}-player ${this.id}`)}get isPlaying(){var e;return this._state==="PLAYING"&&((e=this.element)==null?void 0:e.paused)===!1}get 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 _(this,null,function*(){if(!this.isPlaying)try{this._delayDestroyTimeoutId&&(clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0,this.bindTrackEvents(),this.bindElementEvents()),this.bindAutoPlayEvent(),yield this.element.play()}catch(e){let t=L({key:M.PLAY_FAILED,data:{media:this.kind,error:e}});if(this.track&&!this.track.muted&&this._log.warn(e),t.includes("NotAllowedError"))throw new b({code:A.PLAY_NOT_ALLOWED,message:t})}})}stop(e=0){this._isElementPlayingFired=!1,this.unbindEvents(),e>0?this._delayDestroyTimeoutId||(this._log.info(`destroy element after 3 * ${e}`),this._delayDestroyTimeoutId=setTimeout(()=>this.destroyElement(),3*e)):this.destroyElement(),this.handleStopped(h.ENDED),this._interval>0&&re.clearTask(this._interval)}destroyElement(){this.element&&(this._log.debug("destroy element"),this.element.remove(),this.element.srcObject=null,this.element=null),clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0}pause(){var e;this.isPlaying&&((e=this.element)==null||e.pause())}resume(){return this._log.info("resume"),this.isPlaying?Promise.resolve():Pa?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 De(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);wt==null||wt.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(){g.on(E.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(){this.track&&me(this.track)}unbindEvents(){this.element&&me(this.element),this.unbindTrackEvents(),g.off(E.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&&(re.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),We&&(this._interval=re.run(gi,()=>{this.element&&this._state==="PAUSED"&&this.resume()},{delay:3e3}));break;case h.ERROR:if(this.element&&this.element.error){this.handlePaused(h.ERROR);let{code:s,message:o}=this.element.error;this._log.error(`${this.kind} ${this._log.isLocal?"local":"remote"} MediaError code: ${s} message: ${o} userAgent: ${navigator.userAgent}`),Z.uploadEvent({log:`stat-${this.kind}-${Ve.PLAYER_ERROR}-${s}-${navigator.userAgent}`,error:this.element.error}),this.replayByRecreateMediaStream(this.element.error)}break;case h.LOADEDDATA:this.kind===h.VIDEO&&this.emit(ve.LOADED_DATA);break}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamIng)return this._isReplayByRecreateMediaStreamIng=!0,this.doReplayByRecreateMediaStream(1e3).then(()=>{this._log.warn("replayByRecreateMediaStream success"),Z.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),D.addSuccessEvent({key:this.kind===h.AUDIO?506700:516700})}).catch(()=>{var t;this._log.error("replayByRecreateMediaStream failed"),Z.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),D.addFailedEvent({key:this.kind===h.AUDIO?506700:516700,error:(t=this.element)==null?void 0:t.error}),this.emit(ve.ERROR,e)}).finally(()=>{this._isReplayByRecreateMediaStreamIng=!1})}doReplayByRecreateMediaStream(e){return this._log.warn(`delay ${e}ms to recreate mediaStream`),new Promise((t,s)=>{tn(e).then(()=>{this.element&&(this.element.srcObject=null,this.element.srcObject=new MediaStream([this.track]),this._log.warn("recreated mediaStream"),this.element.onerror=()=>{var o,n,a;this._log.warn(`element onerror ${(n=(o=this.element)==null?void 0:o.error)==null?void 0:n.code} fired after recreated mediaStream`),s((a=this.element)==null?void 0:a.error)}),tn(5e3).then(()=>{var o,n;(!this.isPlaying||((o=this.element)==null?void 0:o.error))&&s((n=this.element)==null?void 0:n.error),t()})})}).finally(()=>{this.element&&(this.element.onerror=null)})}handleTrackEvent(e){switch(e.type){case h.ENDED:this.handleStopped(h.ENDED);break;case h.MUTE:this.handlePaused(h.MUTE);break;case h.UNMUTE:this._isElementPlayingFired&&this.handlePlaying(h.UNMUTE);break}}handlePlaying(e){this.emit(ve.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this.emit(ve.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this.emit(ve.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};y([it({settings:{retries:2,timeout:0},onError(r,i,e,t){t[0]=(t[0]||1e3)+1e3,i()}})],Ut.prototype,"doReplayByRecreateMediaStream",1),y([le([],"PLAYING",{sync:!0})],Ut.prototype,"handlePlaying",1),y([le("PLAYING","PAUSED",{ignoreError:!0,sync:!0})],Ut.prototype,"handlePaused",1),y([le([],"STOPPED",{sync:!0})],Ut.prototype,"handleStopped",1);var oi="trtc_autoplay",dc=`${oi}_mask`,Lr=`${oi}_wrapper`,Gl=`${oi}_header`,lc=`${oi}_content`,hn=`${oi}_action_wrapper`,uc=`${oi}_question`,hc=`${oi}_collapse`,mn=`${oi}_action_confirm`,Wl=`${oi}_detail`,Jl="#2473E8",pc="dialog",bp=`${pc}-show`,Np=`${pc}-1`,vp=`${pc}-2`,jl=!1,_c=()=>!!document.querySelector(`.${Lr}`),Xl=`${Ct}/${Nt()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,ql=`<br><a href='${Xl}' target='_blank'>${Nt()?"\u5176\u4ED6\u65B9\u6848\uFF1F":"Any other solution?"}</a>`,Dp=`${Nt()?`\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${ql}`:`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. ${ql}`}`,mc=class{constructor(){l(this,"content","\u97F3\u89C6\u9891\u64AD\u653E\u88AB\u6D4F\u89C8\u5668\u62E6\u622A\uFF0C\u8BF7\u70B9\u51FB\u201C\u6062\u590D\u64AD\u653E\u201D\u3002");l(this,"_dialogNode",null);l(this,"_bodyPosition","");l(this,"_showDetail",!1);l(this,"_isCollapseClicked",!1);l(this,"_isQuestionClicked",!1);if(Nt()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!jl){let i=document.createElement("style");i.innerHTML=`.${dc}{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;}.${dc} div:not(.${hn}){display:block !important;}.${Lr}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${Lr} a{color:${Jl};}.${Gl}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${lc}{margin:8px 0;}.${hn}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${hc}{margin-right:auto;cursor:pointer}.${uc}{height:100%;line-height:16px;cursor:pointer;}.${mn}{margin-left:8px;color:#fff;background:${Jl};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${mn}:hover{opacity:0.9;}.${hc},.${mn},.${lc},.${uc}{font-size:14px;}@media screen and (max-width:750px){.${Lr}{width:80vw;}}`,document.head.appendChild(i),jl=!0}this.addDiaLog()}createDiaLog(){let i=document.createElement("template");i.innerHTML=`<div class="${dc}"><div class='${Lr}'><div class='${Gl}'>${location.host}</div><div class='${lc}'>${this.content}</div><div class='${Wl}' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">${Dp}</div><div class='${hn}'></div></div></div>`.trim();let e=document.createElement("button");e.className=mn,e.innerText=Nt()?"\u6062\u590D\u64AD\u653E":"Resume",e.onclick=this.onConfirm.bind(this);let t=document.createElement("div");t.className=uc,t.innerHTML=`<?xml version="1.0" encoding="UTF-8"?>
26
+ `],{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=x(),t,s=()=>{if(t=x()-e,t>=i.delay&&(e=x()-Math.floor(t%i.delay),i.callback(),i.loopCount+=1),!this.isBreakLoop(i))return i.ricID=Fl(s,{timeout:i.delay})};return i.ricID=Fl(s,{timeout:i.delay})}static raf(i){i.delay=(1e3/i.fps).toFixed(2);let e=x(),t,s=()=>{if(document.hidden&&i.backgroundTask)return t=x()-e,e=x(),i.callback(),i.loopCount+=1,this.isBreakLoop(i)?void 0:i.timeoutID=setTimeout(s,i.delay-Math.floor(t%i.delay));if(t=x()-e,t>=i.delay&&(e=x()-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 o=()=>{if(document.hidden){let n=x()-e;n>=i.delay?s():i.timeoutID=setTimeout(s,i.delay-n)}};document.addEventListener("visibilitychange",o),i.onVisibilitychange=o,document.hidden&&o()}return i.taskID}static hasTask(i){return this.taskMap.has(i)}static clearTask(i){if(!this.taskMap.has(i))return!0;let{intervalID:e,timeoutID:t,rafID:s,ricID:o,onVisibilitychange:n,worker:a}=this.taskMap.get(i);return a&&a.terminate(),e&&clearInterval(e),t&&clearTimeout(t),s&&Ap(s),o&&Ip(o),n&&document.removeEventListener("visibilitychange",n),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}};Hs.taskMap=new Map,Hs.currentTaskID=1;var re=Hs;var WE={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 ve={LOADED_DATA:h.LOADEDDATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error"};var wt={};ts(wt,{create:()=>De,remove:()=>me});var Gs=new WeakMap;function De(r,i){Gs.has(r)||Gs.set(r,[]);let e=Gs.get(r),s={add:(o,n)=>("addEventListener"in i?(e.push(i.removeEventListener.bind(i,o,n)),i.addEventListener(o,n)):(e.push(i.off.bind(i,o,n)),i.on(o,n)),s)};return s}function me(r){let i=Gs.get(r);i&&(i.forEach(e=>e()),Gs.delete(r))}var Vt=new WeakMap;function it({settings:r={retries:5,timeout:2e3},onError:i,onRetrying:e,onRetryFailed:t}){return function(s,o,n){let a=Dt({retryFunction:n.value,settings:r,onError({error:c,retry:d,reject:u,retryFuncArgs:p}){var m;i?i.call(this,c,()=>{var f;(f=Vt.get(s))!=null&&f.has(o)?d():u(c)},u,p):(m=Vt.get(s))!=null&&m.has(o)?d():u(c)},onRetrying(c,d){var u;vt(e)&&e.call(this,c,d),(u=Vt.get(s))!=null&&u.has(o)&&(Vt.get(s).get(o).stopRetry=d)},onRetryFailed:t});return n.value=function(...c){let d=Vt.get(s);return d?d.set(o,{args:c}):Vt.set(s,new Map([[o,{args:c}]])),a.apply(this,c).finally(()=>{var u;return(u=Vt.get(s))==null?void 0:u.delete(o)})},n}}function Ws({fnName:r,callback:i,validateArgs:e=!0}){return function(t,s,o){let n=o.value;return o.value=function(...a){var c,d;if((c=Vt.get(t))!=null&&c.has(r)){let{stopRetry:u,args:p}=Vt.get(t).get(r),m=!0;if(e){for(let f of p)if(!a.find(R=>R===f)){m=!1;break}}m&&(i&&i.apply(this,a),u&&u(),(d=Vt.get(t))==null||d.delete(r))}return n.apply(this,a)},o}}var Cp=1,Rp=0,dn=class{constructor(i=!0){this.countMap=new Map;this.distributionMap=new Map;this.log=I.createLogger({id:"kv"});i&&(g.on("102",({track:e,cost:t})=>{this.addSuccessEvent({key:e.kind===h.AUDIO?ln.START_MICROPHONE:oc.START_CAMERA,cost:t})}),g.on("103",({track:e,error:t})=>{this.addFailedEvent({key:e.kind===h.AUDIO?ln.START_MICROPHONE:oc.START_CAMERA,error:t})}))}getReportData(){let i={msg_sdk_basic_info:{uint32_sdk_version:qa(this.version||Re),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,o])=>({uint32_item_key:s,uint32_item_value:o}))}))};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 o;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=((o=this.distributionMap)==null?void 0:o.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 o=((a=this.distributionMap)==null?void 0:a.get(i))||new Map,n=0;if(ee(t))n=Math.floor(e/t);else for(let c=t.length-1;c>0;c--)if(e>t[c]){n=c;break}o.set(n,(o.get(n)||0)+1),this.distributionMap.set(i,o)}addSuccessEvent({key:i,cost:e,timeKey:t,split:s}){if(!!i&&(this.addEnum({key:i,value:Cp,useUV:!1}),e)){let o=+String(i).slice(-3);o<800&&o>=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=A.UNKNOWN;e&&(ee(e)?t=e:(!T(e.extraCode)||!T(e.code))&&(t=e.extraCode||e.code)),this.addEnum({key:i,value:Rp,useUV:!1}),this.addEnum({key:i,value:t,useUV:!1})}},un=(G=>(G[G.enterRoom=500700]="enterRoom",G[G.exitRoom=500701]="exitRoom",G[G.switchRole=500702]="switchRole",G[G.destroy=500703]="destroy",G[G.startLocalAudio=500704]="startLocalAudio",G[G.updateLocalAudio=500705]="updateLocalAudio",G[G.stopLocalAudio=500706]="stopLocalAudio",G[G.startLocalVideo=500707]="startLocalVideo",G[G.updateLocalVideo=500708]="updateLocalVideo",G[G.stopLocalVideo=500709]="stopLocalVideo",G[G.startScreenShare=500710]="startScreenShare",G[G.updateScreenShare=500711]="updateScreenShare",G[G.stopScreenShare=500712]="stopScreenShare",G[G.startRemoteVideo=500713]="startRemoteVideo",G[G.updateRemoteVideo=500714]="updateRemoteVideo",G[G.stopRemoteVideo=500715]="stopRemoteVideo",G[G.muteRemoteAudio=500716]="muteRemoteAudio",G[G.setRemoteAudioVolume=500717]="setRemoteAudioVolume",G[G.use=500718]="use",G[G.sendSEIMessage=5e5]="sendSEIMessage",G[G.sendCustomMessage=500001]="sendCustomMessage",G))(un||{}),nc=(d=>(d[d.AudioMixer=550700]="AudioMixer",d[d.AIDenoiser=551700]="AIDenoiser",d[d.VirtualBackground=570700]="VirtualBackground",d[d.Beauty=571700]="Beauty",d[d.Watermark=572700]="Watermark",d[d.BasicBeauty=574700]="BasicBeauty",d[d.CDNStreaming=590700]="CDNStreaming",d[d.DeviceDetector=591700]="DeviceDetector",d[d.Debug=592700]="Debug",d))(nc||{}),ac=(d=>(d[d.AudioMixer=550701]="AudioMixer",d[d.AIDenoiser=551701]="AIDenoiser",d[d.VirtualBackground=570701]="VirtualBackground",d[d.Beauty=571701]="Beauty",d[d.Watermark=572701]="Watermark",d[d.BasicBeauty=574701]="BasicBeauty",d[d.CDNStreaming=590701]="CDNStreaming",d[d.DeviceDetector=591701]="DeviceDetector",d[d.Debug=592701]="Debug",d))(ac||{}),cc=(d=>(d[d.AudioMixer=550702]="AudioMixer",d[d.AIDenoiser=551702]="AIDenoiser",d[d.VirtualBackground=570702]="VirtualBackground",d[d.Beauty=571702]="Beauty",d[d.Watermark=572702]="Watermark",d[d.BasicBeauty=574702]="BasicBeauty",d[d.CDNStreaming=590702]="CDNStreaming",d[d.DeviceDetector=591702]="DeviceDetector",d[d.Debug=592702]="Debug",d))(cc||{});var ln=(t=>(t[t.START_MICROPHONE=501700]="START_MICROPHONE",t[t.MICROPHONE_CAHNNELS=501701]="MICROPHONE_CAHNNELS",t[t.MICROPHONE_SAMPLERATE=501702]="MICROPHONE_SAMPLERATE",t))(ln||{});var oc=(i=>(i[i.START_CAMERA=511700]="START_CAMERA",i))(oc||{});var yp=new dn(!0),Gi=new dn(!1);var D=yp;var Ut=class extends F{constructor(e,t){super(e.id,`${t}-player`);this.kind=t;l(this,"id");l(this,"element",null);l(this,"track");l(this,"url");l(this,"attr");l(this,"muted");l(this,"_log");l(this,"_pausedRetryCount");l(this,"_isElementPlayingFired",!1);l(this,"_interval");l(this,"_delayDestroyTimeoutId",0);l(this,"_isReplayByRecreateMediaStreamCalled",!1);this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=Ca,this._state="STOPPED",this.bindTrackEvents(),this._log.info(`create ${t}-player ${this.id}`)}get isPlaying(){var e;return this._state==="PLAYING"&&((e=this.element)==null?void 0:e.paused)===!1}get 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 _(this,null,function*(){if(!this.isPlaying)try{this._delayDestroyTimeoutId&&(clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0,this.bindTrackEvents(),this.bindElementEvents()),this.bindAutoPlayEvent(),yield this.element.play()}catch(e){let t=L({key:M.PLAY_FAILED,data:{media:this.kind,error:e}});if(this.track&&!this.track.muted&&this._log.warn(e),t.includes("NotAllowedError"))throw new b({code:A.PLAY_NOT_ALLOWED,message:t})}})}stop(e=0){this._isElementPlayingFired=!1,this.unbindEvents(),e>0?this._delayDestroyTimeoutId||(this._log.info(`destroy element after 3 * ${e}`),this._delayDestroyTimeoutId=setTimeout(()=>this.destroyElement(),3*e)):this.destroyElement(),this.handleStopped(h.ENDED),this._interval>0&&re.clearTask(this._interval)}destroyElement(){this.element&&(this._log.debug("destroy element"),this.element.remove(),this.element.srcObject=null,this.element=null),clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0}pause(){var e;this.isPlaying&&((e=this.element)==null||e.pause())}resume(){return this._log.info("resume"),this.isPlaying?Promise.resolve():Pa?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 De(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);wt==null||wt.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(){g.on(E.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(){this.track&&me(this.track)}unbindEvents(){this.element&&me(this.element),this.unbindTrackEvents(),g.off(E.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&&(re.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),We&&(this._interval=re.run(gi,()=>{this.element&&this._state==="PAUSED"&&this.resume()},{delay:3e3}));break;case h.ERROR:if(this.element&&this.element.error){this.handlePaused(h.ERROR);let{code:s,message:o}=this.element.error;this._log.error(`${this.kind} ${this._log.isLocal?"local":"remote"} MediaError code: ${s} message: ${o} userAgent: ${navigator.userAgent}`),Z.uploadEvent({log:`stat-${this.kind}-${Ve.PLAYER_ERROR}-${s}-${navigator.userAgent}`,error:this.element.error}),this.replayByRecreateMediaStream(this.element.error)}break;case h.LOADEDDATA:this.kind===h.VIDEO&&this.emit(ve.LOADED_DATA);break}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then(()=>{this._log.warn("replayByRecreateMediaStream success"),Z.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),D.addSuccessEvent({key:this.kind===h.AUDIO?506700:516700})}).catch(()=>{var t;this._log.error("replayByRecreateMediaStream failed"),Z.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),D.addFailedEvent({key:this.kind===h.AUDIO?506700:516700,error:(t=this.element)==null?void 0:t.error}),this.emit(ve.ERROR,e)})}doReplayByRecreateMediaStream(e){return this._log.warn(`delay ${e}ms to recreate mediaStream`),new Promise((t,s)=>{tn(e).then(()=>{this.element&&(this.element.srcObject=null,this.element.srcObject=new MediaStream([this.track]),this._log.warn("recreated mediaStream"),this.element.onerror=()=>{var o,n,a;this._log.warn(`element onerror ${(n=(o=this.element)==null?void 0:o.error)==null?void 0:n.code} fired after recreated mediaStream`),s((a=this.element)==null?void 0:a.error)}),tn(5e3).then(()=>{var o,n;(!this.isPlaying||((o=this.element)==null?void 0:o.error))&&s((n=this.element)==null?void 0:n.error),t()})})}).finally(()=>{this.element&&(this.element.onerror=null)})}handleTrackEvent(e){switch(e.type){case h.ENDED:this.handleStopped(h.ENDED);break;case h.MUTE:this.handlePaused(h.MUTE);break;case h.UNMUTE:this._isElementPlayingFired&&this.handlePlaying(h.UNMUTE);break}}handlePlaying(e){this.emit(ve.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this.emit(ve.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this.emit(ve.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};y([it({settings:{retries:2,timeout:0},onError(r,i,e,t){t[0]=(t[0]||1e3)+1e3,i()}})],Ut.prototype,"doReplayByRecreateMediaStream",1),y([le([],"PLAYING",{sync:!0})],Ut.prototype,"handlePlaying",1),y([le("PLAYING","PAUSED",{ignoreError:!0,sync:!0})],Ut.prototype,"handlePaused",1),y([le([],"STOPPED",{sync:!0})],Ut.prototype,"handleStopped",1);var oi="trtc_autoplay",dc=`${oi}_mask`,Lr=`${oi}_wrapper`,Gl=`${oi}_header`,lc=`${oi}_content`,hn=`${oi}_action_wrapper`,uc=`${oi}_question`,hc=`${oi}_collapse`,mn=`${oi}_action_confirm`,Wl=`${oi}_detail`,Jl="#2473E8",pc="dialog",bp=`${pc}-show`,Np=`${pc}-1`,vp=`${pc}-2`,jl=!1,_c=()=>!!document.querySelector(`.${Lr}`),Xl=`${Ct}/${Nt()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,ql=`<br><a href='${Xl}' target='_blank'>${Nt()?"\u5176\u4ED6\u65B9\u6848\uFF1F":"Any other solution?"}</a>`,Dp=`${Nt()?`\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${ql}`:`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. ${ql}`}`,mc=class{constructor(){l(this,"content","\u97F3\u89C6\u9891\u64AD\u653E\u88AB\u6D4F\u89C8\u5668\u62E6\u622A\uFF0C\u8BF7\u70B9\u51FB\u201C\u6062\u590D\u64AD\u653E\u201D\u3002");l(this,"_dialogNode",null);l(this,"_bodyPosition","");l(this,"_showDetail",!1);l(this,"_isCollapseClicked",!1);l(this,"_isQuestionClicked",!1);if(Nt()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!jl){let i=document.createElement("style");i.innerHTML=`.${dc}{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;}.${dc} div:not(.${hn}){display:block !important;}.${Lr}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${Lr} a{color:${Jl};}.${Gl}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${lc}{margin:8px 0;}.${hn}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${hc}{margin-right:auto;cursor:pointer}.${uc}{height:100%;line-height:16px;cursor:pointer;}.${mn}{margin-left:8px;color:#fff;background:${Jl};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${mn}:hover{opacity:0.9;}.${hc},.${mn},.${lc},.${uc}{font-size:14px;}@media screen and (max-width:750px){.${Lr}{width:80vw;}}`,document.head.appendChild(i),jl=!0}this.addDiaLog()}createDiaLog(){let i=document.createElement("template");i.innerHTML=`<div class="${dc}"><div class='${Lr}'><div class='${Gl}'>${location.host}</div><div class='${lc}'>${this.content}</div><div class='${Wl}' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">${Dp}</div><div class='${hn}'></div></div></div>`.trim();let e=document.createElement("button");e.className=mn,e.innerText=Nt()?"\u6062\u590D\u64AD\u653E":"Resume",e.onclick=this.onConfirm.bind(this);let t=document.createElement("div");t.className=uc,t.innerHTML=`<?xml version="1.0" encoding="UTF-8"?>
27
27
  <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">
28
28
  <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"/>
29
29
  <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"/>
@@ -62,7 +62,7 @@ void main() {
62
62
  `)))}else{if(e instanceof Yi)return e;o=new Yi({code:w.UNKNOWN_ERROR,fnName:t,originError:e})}return o}};function p_(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 k=Yi;var Ru={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}}},Gr={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(r,i,e){if(z(r)&&!document.getElementById(r))throw new k({code:w.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:i}})}},bu={name:"userId",required:!0,type:"string"},Nu={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[st.AUDIO_PROFILE_STANDARD,st.AUDIO_PROFILE_STANDARD_STEREO,st.AUDIO_PROFILE_HIGH,st.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function io(r,i){if(!r)throw new k({code:w.INVALID_OPERATION,extraCode:5101,fnName:i})}function vu(r,i,e){if(!r)throw new k({code:w.INVALID_OPERATION,extraCode:5102,fnName:i,messageParams:{value:e}})}var jy={type:"number",notLessThanZero:!0},__={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 k({code:w.INVALID_OPERATION,extraCode:5104,fnName:e});if(r.roomId){if(z(r.roomId))throw new k({code:w.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:i}});if(!(/^[1-9]\d*$/.test(String(r.roomId))&&r.roomId<4294967295))throw new k({code:w.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 k({code:w.INVALID_PARAMETER,extraCode:5012,fnName:e,messageParams:{key:i}})}else throw new k({code:w.INVALID_PARAMETER,extraCode:5015,fnName:e})},properties:{sdkAppId:{required:!0,type:"number",allowEmpty:!1},userId:{required:!0,type:"string",allowEmpty:!1},userSig:{required:!0,type:"string",allowEmpty:!1},scene:{type:"string",values:["live","rtc"]},role:{type:"string",values:["audience","anchor"]},roomId:{type:["string","number"]},strRoomId:{type:"string"},proxy:{type:["object","string"],properties:{websocketProxy:{type:"string"},turnServer:{type:["object","array"],properties:{url:{required:!0,type:"string"},username:{type:"string"},credential:{type:"string"},credentialType:{type:"string",values:["password"]}}},loggerProxy:{type:"string"},webtransportProxy:{type:"string"}}},enableAutoPlayDialog:{type:"boolean"},userDefineRecordId:{type:"string"},latencyLevel:{type:"number"}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:Gr,mute:{type:["boolean","string"]},publish:{type:"boolean"},option:Ru},validate(r){var i;if(!((i=r==null?void 0:r.option)!=null&&i.videoTrack)&&ri())throw new k({code:w.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:P(N({},Gr),{required:!1}),publish:{type:"boolean"},mute:{type:["boolean","string"]},option:Ru}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:Nu},validate(r){var i;if(!((i=r==null?void 0:r.option)!=null&&i.audioTrack)&&ri())throw new k({code:w.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:Nu}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:Gr,publish:{type:"boolean"},option:yu},validate(r,i,e,t,s){var o;if(!((o=r==null?void 0:r.option)!=null&&o.videoTrack)&&ri())throw new k({code:w.ENV_NOT_SUPPORTED,extraCode:5201});if(!Ps())throw new k({code:w.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:Gr,publish:{type:"boolean"},option:yu}},muteRemoteAudio:[bu,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[bu,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:Gr,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){io(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(r.userId);if(vu(!!t,e,r),t&&(r.streamType==="main"&&!t.muteState.videoAvailable||r.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new k({code:w.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:r}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:P(N({},Gr),{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){io(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(r.userId);if(vu(!!t,e,r),t&&(r.streamType==="main"&&!t.muteState.videoAvailable||r.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new k({code:w.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!=="*"&&T(r.streamType))throw new k({code:w.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(r,i,e){io(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(!si)throw new k({code:w.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new k({code:w.INVALID_OPERATION,fnName:e,extraCode:5108});if(r.byteLength>1e3)throw new k({code:w.INVALID_PARAMETER,extraCode:5018,fnName:e});if(r.byteLength===0)throw new k({code:w.INVALID_PARAMETER,extraCode:5017,messageParams:{key:i},fnName:e});io(this._room.isJoined,e)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(r,i,e){if(!r&&!this._room.isMainStreamPublished||r&&!this._room.isAuxStreamPublished)throw new k({code:w.INVALID_OPERATION,extraCode:5109,messageParams:{key:i},fnName:e})}}}}],sendCustomMessage:{name:"message",required:!0,type:"object",properties:{cmdId:{type:"number",required:!0,min:1,max:10},data:{instanceOf:ArrayBuffer,required:!0,validate(r,i,e,t){if(r.byteLength>1e3)throw new k({code:w.INVALID_PARAMETER,extraCode:5018,fnName:e});if(r.byteLength===0)throw new k({code:w.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:i}})}}},validate(r,i,e){if(io(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new k({code:w.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:i}})}}},Ce={TRTC:__};var Me=class extends Error{};function f_(r,i){let e=br(r);for(let t=0;t<i.length;t++)ei(e[t],i[t]);return e}function E_(r){this._resolve=Promise.resolve(r)}function g_(r){this._reject=Promise.reject(r)}var Ki=class{constructor(i,e){this.instance=i;this.group=e;this.started=!1;this.ops=[];this.startSame=()=>!0;this.mergeUpdate=f_;let t=Ki.instances.get(i);t?t.set(e,this):Ki.instances.set(i,new Map([[e,this]]))}static get(i,e){if(!e)return;let t=Ki.instances.get(i);return t&&t.get(e)||new Ki(i,e)}static gets(i,e){let t=Ki.instances.get(i),s=[];return t&&t.forEach((o,n)=>{e.test(n)&&s.push(o)}),s}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},o=a=>{var c,d;throw this.ops.shift(),i===0&&((c=this.currentOp)==null?void 0:c.type)===2&&this.ops.shift().reject(new Me("start failed")),(d=this.currentOp)==null||d.action(),a},n={type:i,action:()=>e(...n.args).then(s,o),args:t,resolve:E_,reject:g_};try{switch(this.state){case 1:if(i===0)throw new Me("already started");break;case 4:if(i===2)throw new Me("not started");break;default:return this.cacheOp(n)}}catch(a){return Promise.reject(a)}return this.ops.push(n),n.promise=e(...n.args).then(s,o)}cacheOp(i){if(this.ops.length===1)switch(this.state){case 0:case 2:if(i.type===0)throw new Me("already start");break;case 3:switch(i.type){case 2:throw new Me("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new Me("unknown state")}else switch(i.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let t=new Me("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 Me("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new Me("start not allowed after update");case 0:throw new Me("duplicate start");case 3:if(this.startSame(this.currentOp.args,i.args))throw this.ops.pop().reject(new Me("keep start")),new Me("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}},Gt=Ki;Gt.instances=new WeakMap;var Hn=new WeakMap,Gn=(r,i)=>{if(i instanceof Me){let{stack:e}=i;i=new k({code:w.OPERATION_ABORT,message:`${r} abort: ${i.message}`,fnName:r}),e&&(i.stack+=e.substr(e.indexOf(`
63
63
  `)))}throw i};function Mi(r,i){return W((e,t)=>function(...s){let o=Gt.get(this,typeof r=="string"?r:r.call(this,...s));return o?(i&&(o.startSame=i.bind(this)),o.action(0,e.bind(this),s).catch(Gn.bind(null,t))):e.apply(this,s)})}function Zi(r,i){let{merge:e,debounce:t}=i||{};return W((s,o)=>function(...n){let a=Gt.get(this,typeof r=="string"?r:r.call(this,...n));if(!a)return s.apply(this,n);if(e&&(a.mergeUpdate=e.bind(this)),t&&t.isNeedToDebounce.apply(this,n)){let{delay:c,getKey:d}=t;return new Promise((u,p)=>{var R,C;let m=(R=Hn.get(this))==null?void 0:R.get(d(...n));if(m){let{timeoutId:v,resolve:U}=m;clearTimeout(v),U()}let f=setTimeout(()=>{if(a.state===3||a.state===4)return u();a.action(2,s.bind(this),n).catch(Gn.bind(null,o)).then(u,p)},c);Hn.has(this)?(C=Hn.get(this))==null||C.set(d(...n),{timeoutId:f,resolve:u}):Hn.set(this,new Map([[d(...n),{timeoutId:f,resolve:u}]]))})}return a.action(2,s.bind(this),n).catch(Gn.bind(null,o))})}function ki(r){return W((i,e)=>function(...t){let s=typeof r=="function"?r.call(this,...t):r;if(s instanceof RegExp)return Promise.all(Gt.gets(this,s).map(n=>n.action(3,()=>Promise.resolve(),t))).then(()=>i.call(this,...t));let o=Gt.get(this,s);return o?o.action(3,i.bind(this),t).catch(Gn.bind(null,e)):i.apply(this,t)})}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 er(r){return r==="sub"?"auxiliary":r==="auxiliary"?"sub":"main"}function tr(r){return r===st.QOS_PREFERENCE_CLEAR?"detail":r===st.QOS_PREFERENCE_SMOOTH?"motion":""}var T_=r=>r.startsWith("data:application/octet-stream;base64,"),S_=r=>r.startsWith("file://"),Wn=class{constructor(){l(this,"_log");this._log=I.createLogger({id:"fd"})}download(i,e){return _(this,null,function*(){let{type:t="blob"}=e||{};try{let s=x(),o;if(K(fetch)?o=yield this.downloadWithFetch(i,t):o=yield this.downloadWithXHR(i,t),!o||!o.data)throw new Error("data is empty");let n=x()-s;return this._log.info(`downloaded: ${i}, return type: ${t}, cost: ${n}ms`),D.addSuccessEvent({key:522700,cost:x()-s}),o.data}catch(s){throw this._log.error(`failed to download: ${i}, error: ${s}`),D.addFailedEvent({key:522700,error:s}),s}})}downloadWithFetch(i,e){return _(this,null,function*(){this._log.info(`download with fetch: ${i}, return type: ${e}`);try{let t=yield fetch(i);if(!t.ok)throw new Error("network response was not ok");let s;return e==="arraybuffer"?s=yield t.arrayBuffer():s=yield t.blob(),{data:s}}catch(t){throw t}})}downloadWithXHR(i,e){return this._log.info(`download with xhr: ${i}, return type: ${e}`),new Promise((t,s)=>{let o=new XMLHttpRequest;o.open("GET",i,!0),o.responseType=e,o.onload=()=>{o.status===200||o.status===0&&o.response?t({data:o.response}):s(new Error("XHR failed"))},o.onerror=s,o.send(null)})}loadWasm(i,e){return _(this,null,function*(){this._log.info(`loadWasm ${i}, importObject: ${JSON.stringify(e)}`);let t=x(),s=null,o=null;if(K(WebAssembly.instantiateStreaming)&&!T_(i)&&!S_(i)&&K(fetch))try{let n=fetch(i);s=(yield WebAssembly.instantiateStreaming(n,e)).instance}catch(n){o=n}if(!s)try{let n=yield this.download(i,{type:"arraybuffer"});s=(yield WebAssembly.instantiate(n,e)).instance}catch(n){o=n}if(s){let n=x()-t;return this._log.info(`loadedWasm ${i}, cost: ${n}ms`),D.addSuccessEvent({key:522701,cost:n}),s}throw this._log.error(`failed to loadWasm ${i}, error: ${o}`),D.addFailedEvent({key:522701,error:o}),o})}};y([it({settings:{timeout:0,retries:3},onRetrying(r){this._log.warn(`download retrying: ${r}`)}})],Wn.prototype,"download",1);var Du=new Wn;function Ou({TRTC:r,room:i,errorModule:e,assetsPath:t}){return{TRTC:r,room:i,assetsPath:t,fileDownloader:Du,innerEmitter:g,constants:ya,environment:Cr,utils:we,eventLogger:Z,log:this.room.getLogger(),loggerManager:I,errorModule:e,kvStatManager:D,rtcDectection:ft,trtc:this,clearStarted:(s,o)=>{let n=s.getAlias(),a=Gt.instances.get(this);if(!!a)if(o){let c=a.get(n+o);if(!c)return;c.started=!1}else a.forEach((c,d)=>{d.startsWith(n)&&(c.started=!1)})}}}var Mu=(r,i)=>{let{emit:e}=r;return r.emit=(...t)=>{try{return e.apply(r,t)}catch(s){let o=L({key:M.CATCH_HANDLER_ERROR,data:{name:i,event:t[0]},addDocLink:!1});return I.warn(`${o}
64
64
 
65
- ${s.stack}`),!1}},r};var Jn=new WeakMap;function ku(r,i){return W((e,t)=>function(...s){var a,c;let o=(a=Jn.get(this))==null?void 0:a.get(i(...s));o&&o>0&&clearTimeout(o);let n=window.setTimeout(()=>{e.apply(this,s)},r);Jn.has(this)?(c=Jn.get(this))==null||c.set(i(...s),n):Jn.set(this,new Map([[i(...s),n]]))})}var Lu="5.8.2-beta.7";function ke(...r){return W((i,e)=>function(...t){try{qn.call(this,r,t,e,this._name)}catch(s){return Promise.reject(s)}return i.apply(this,t)})}function ld(...r){return W((i,e)=>function(...t){try{qn.call(this,r,t,e,this._name)}catch(s){throw s}return i.apply(this,t)})}function qn(r,i,e,t){if(he(r))for(let s=0;s<r.length;s++)jn.call(this,{rule:r[s],value:i[s],key:r[s].name,fnName:e,className:t});else jn.call(this,{rule:r,value:i[0],key:r.name,fnName:e,className:t})}function jn({rule:r,value:i,key:e,fnName:t,className:s}){function o(c){return{code:w.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:r,value:i}}}if(T(i)){if(r.required)throw new k(o(5001));if(T(r.defaultValue)){K(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),K(r.type[d])&&i instanceof r.type[d]&&(c=!0),z(r.type[d])&&fe(i)===r.type[d].toLowerCase()&&(c=!0);if(!c)throw new k({code:w.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:r.type.map(d=>Ds(d)?Ko(d):z(d)?d:fe(d))},value:i}})}else if(!T(r.type)&&fe(i)!==r.type)throw new k(o(5002));if(r.allowEmpty===!1){let c=ee(i)&&(i===0||Number.isNaN(i)),d=z(i)&&i.trim()==="";if(c||d)throw new k(o(5003))}if(r.notLessThanZero&&ee(i)&&i<0)throw new k(o(5006));if(!T(r.min)&&ee(i)&&i<r.min)throw new k(o(5007));if(!T(r.max)&&ee(i)&&i>r.max)throw new k(o(5008));if(z(r.instanceOf)){if(!i||i._name!==r.instanceOf)throw new k(o(5004))}else if(K(r.instanceOf)&&!(i instanceof r.instanceOf))throw new k(o(5004));if(Array.isArray(r.values)&&!r.values.includes(i))throw new k(o(5005));let{properties:n}=r;Je(n)&&mt(i)&&Object.keys(n).forEach(c=>{jn.call(this,{rule:n[c],value:i&&i[c],key:`${c}`,fnName:t,className:s})});let{arrayItem:a}=r;Je(a)&&he(i)&&i.forEach((c,d)=>{jn.call(this,{rule:a,value:c,key:`${e}[${d}]`,fnName:t,className:s})}),K(r.validate)&&r.validate.call(this,i,e,t,s,this)}function oe(r={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t}=r;return W((s,o)=>function(...n){function a(u,p,m){if(m&&m.includes(u))return"hided";if(e){let f=e(...n);if(n[f.argIndex]===p)return f.value}if(p===n||u in n)return p;try{return p instanceof HTMLElement?`id: ${p.id} type:${fe(p)}`:(JSON.stringify(p),p)}catch(f){return`type:${fe(p)}`}}let c=this._log||I;n.length>0?c.info(`${o}() ${JSON.stringify(n,(u,p)=>a(u,p,["userSig","privateMapKey"]))}`):c.info(`${o}()`);let d=t?t(...n):un[o];try{let u=s.apply(this,n),p=x();return vs(u)?u.then(m=>(c.info(`${o}() success ${i.call(this,...n)}`),D.addSuccessEvent({key:d,cost:x()-p}),m)).catch(m=>{throw m=k.convertFrom.call(this,m,o,n.length===1?n[0]:n),c.error(`${o}() failed ${i.call(this,...n)} ${m} params: ${JSON.stringify(n,a)}`),D.addFailedEvent({key:d,error:m}),m}):(D.addSuccessEvent({key:d}),u)}catch(u){throw u=k.convertFrom.call(this,u,o),c.error(`${o}() failed ${u} params: ${JSON.stringify(n,a)}`),D.addFailedEvent({key:d,error:u}),u}})}var Xn=r=>W((i,e)=>function(t,s){return _(this,null,function*(){let o=this._plugins.get(t);if(!o)throw this._log.error(`plugin ${String(t)} is not found`),new k({code:w.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});if(K(o.constructor.isSupported)&&!o.constructor.isSupported())throw this._log.error(`plugin ${String(t)} is not supported`),new k({code:w.ENV_NOT_SUPPORTED,message:`plugin ${String(t)} is not supported`,extraCode:5210,fnName:e});return qn.call(this,o.getValidateRule(r),[s],e,"TRTC"),i.call(this,o,s)})});var Qn=0,ud=class{constructor(i,e){l(this,"player");l(this,"publisher");l(this,"mixInput");this.mixInput=new xr(e),i.url?(this.player=new Audio(i.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(i.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(i.track),this.mixInput.connect()}updateSettings(i){!this.player||(T(i.volume)||(this.volume=i.volume),T(i.loop)||(this.loop=i.loop),T(i.playbackRate)||(this.playbackRate=i.playbackRate))}updateListener(i){if(!!this.player){if(i.onDurationChange){let{onDurationChange:e}=i;this.player.ondurationchange=t=>{e(t.target.duration)}}if(i.onTimeUpdate){let e=i.onTimeUpdate,{player:t}=this;t.ontimeupdate=()=>{e(t.currentTime,t.duration)}}i.onEnded&&(this.player.onended=i.onEnded)}}reset(){this.seek(0),this.mixInput.connect()}seek(i){!this.player||i<0&&i>this.player.duration||(this.player.currentTime=i,this.publisher.currentTime=i)}play(){var i,e;return(i=this.publisher)==null||i.play(),(e=this.player)==null?void 0:e.play()}pause(){var i,e;(i=this.player)==null||i.pause(),(e=this.publisher)==null||e.pause()}stop(){var i;(i=this.player)==null||i.pause(),this.mixInput.disconnect()}setOperation(i){i==="pause"&&this.pause(),i==="resume"&&(this.pause(),this.play()),i==="stop"&&(this.pause(),this.seek(0))}set volume(i){!this.player||!this.publisher||(this.player.volume=i,this.publisher.volume=i)}set loop(i){!this.player||!this.publisher||(this.player.loop=i,this.publisher.loop=i)}set playbackRate(i){!this.player||!this.publisher||(this.player.playbackRate=i,this.publisher.playbackRate=i)}};function Wr(r,i){if(i&&typeof i!="function")throw new k({code:w.INVALID_PARAMETER,message:`start audioMixer plugin: param ${r} should be a function.`})}var Jr=class{constructor(i){this.core=i;l(this,"log");l(this,"mixedMusicMap",new Map);l(this,"cacheMusicMap",new Map);Qn=Qn+1,this.log=i.log.createChild({id:`${this.getAlias()}${Qn}`}),this.log.info(`[audioMixer] created id=${this.getAlias()}${Qn}`),this.core=i}getName(){return Jr.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return Jr.startValidateRule;case"update":return Jr.updateValidateRule;case"stop":return Jr.stopValidateRule}}start(i){return _(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 o=this.cacheMusicMap.get(t);o?i.url?o.reset():(o.mixInput.replaceSource(i.track),o.mixInput.connect()):(o=new ud(i,e.audioManager),this.cacheMusicMap.set(t,o)),o.updateListener(i),o.updateSettings(i),yield o.play(),this.mixedMusicMap.set(t,o),this.log.info(`start mix audio track ${t} success.`),D.addEnum({key:502700,value:3}),this.kvUpload(i)})}update(i){return _(this,null,function*(){let{id:e,operation:t,seekFrom:s,playbackRate:o}=i;this.log.info(`update music source, ${JSON.stringify(i)}`);let n=this.mixedMusicMap.get(e);if(!n){this.log.warn(`update music source failed, music id: ${e} not found.`);return}n.updateSettings(i),n.updateListener(i),T(t)||n.setOperation(t),T(s)||n.seek(s),this.kvUpload(i)})}stop(e){return _(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()})}kvUpload(i){let{track:e,loop:t,volume:s,playbackRate:o,operation:n,seekFrom:a,onTimeUpdate:c,onDurationChange:d,onEnded:u}=i;e&&D.addCount({key:502711}),t&&D.addCount({key:502703}),s&&D.addCount({key:502704}),o&&D.addCount({key:502705}),n&&D.addCount({key:502706}),a&&D.addCount({key:502707}),typeof c!="function"&&D.addCount({key:502709}),typeof u!="function"&&D.addCount({key:502710}),typeof d!="function"&&D.addCount({key:502708})}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()}},Li=Jr;l(Li,"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],o=["mp3","ogg","wav","flac"],n=s.split(".").pop(),a=o.indexOf(n)>=0,c=s.startsWith("blob"),d=s.startsWith("data");if(!(a||c||d))throw new k({code:w.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new k({code:w.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});Wr("onTimeUpdate",i.onTimeUpdate),Wr("onEnded",i.onEnded),Wr("onDurationChange",i.onDurationChange)}}),l(Li,"updateValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},loop:{type:"boolean"},volume:{type:"number"},seekFrom:{type:"number"},operation:{type:"string",values:["pause","resume","stop"]}},validate(i,e,t){Wr("onTimeUpdate",i.onTimeUpdate),Wr("onEnded",i.onEnded),Wr("onDurationChange",i.onDurationChange)}}),l(Li,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),l(Li,"Name","AudioMixer");var A_=r=>(r=Number(r),r>0&&r<14e8),zn=0,hd,jr=class{constructor(i){this.core=i;l(this,"log");l(this,"audioContext",qe("denoiser"));l(this,"workletNode");zn=zn+1,this.log=i.log.createChild({id:`${this.getAlias()}${zn}`}),this.log.info(`[audioDenoiser] created id=${this.getAlias()}${zn}`),i.assetsPath&&this.preload(`${i.assetsPath}/denoiser-wasm.js`)}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,o){if(!i.room.audioManager.hasAudioTrack)throw new k({code:w.INVALID_OPERATION,extraCode:5106,fnName:s})}}}preload(i){return hd||(hd=this.doPreload(i)),hd}doPreload(i){return _(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield Wi(this.audioContext,t)}finally{URL.revokeObjectURL(t)}})}getName(){return jr.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(i){switch(i){case"start":return jr.startValidateRule(this.core);case"update":return jr.updateValidateRule;case"stop":return jr.stopValidateRule}}start(i){return _(this,null,function*(){let{room:e}=this.core;if(yield this.preload(`${i.assetsPath}/denoiser-wasm.js`),!this.workletNode){let t=String(Date.now()).slice(0,-3),{auth:s,sign:o,status:n,message:a}=yield R_(P(N({},i),{timestamp:t}));if(!s)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${s}. Message: ${a}`),new k({code:w.INVALID_PARAMETER,message:a});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:o,status:n}}),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 _(this,null,function*(){})}stop(){return _(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(){}},ir=jr;l(ir,"updateValidateRule",{type:"object"}),l(ir,"stopValidateRule",{type:"object"}),l(ir,"Name","AIDenoiser");var xu={MAIN:"schedule.cloud-rtc.com",MAIN_OVERSEA:"schedule.rtc.tencentcloud.com"};function C_(r){let i;return A_(r)?i=xu.MAIN_OVERSEA:i=xu.MAIN,i}function R_(s){return _(this,arguments,function*({sdkAppId:r,userId:i,userSig:e,timestamp:t}){let n=`https://${C_(r)}/api/v1/audioAiAuth?sdkAppId=${r}&userId=${i}&userSig=${e}&timestamp=${t}`,a=yield fetch(n),{data:{errCode:c,errMsg:d,sign:u,status:p}}=yield a.json();if(p==="1")return{auth:!0,sign:u,status:p,message:d};let m="Init RTCAIDenoiser failed.",f="";switch(c){case 1:f="Please check your params.";break;case 2:f="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:f="Server is invalid. Please contact our engineer. ";break;case 4:f="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:f="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:f="Your version is not supported.";break}return{auth:!1,status:p,message:d?`${m} Reason: ${d}. ${f}`:`${m}, ${f}`}})}var Pu=Se(Ne(),1);var md=class extends Pu.EventEmitter{constructor(){super();this.state="nominal";this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return _(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!pe&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){Z.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let t=this.stateNum,s=e[e.length-1];this.state=s.state,(this.stateNum>3||t>3)&&I.info(`${s.source}: ${s.state}`),this.emit("state-changed",{type:s.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(t){Z.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},y_=new md,pd=y_;var _d=0,gd=class{constructor(i){this.core=i;l(this,"log");l(this,"_seiMessageList",[]);l(this,"_smallSeiMessageList",[]);l(this,"_subStreamSeiMessageList",[]);l(this,"_seiWorker");_d++,this.log=i.log.createChild({id:`${this.getAlias()}${_d}`}),this.log.info(`[sei] created id=${this.getAlias()}${_d}`),this.core=i}encode(i,e){try{let t=e===8?this._smallSeiMessageList:e===2?this._subStreamSeiMessageList:this._seiMessageList,s=fd(i,t);s&&this.log.debug(`${s} sei sent`)}catch(t){this.log.warn(t)}return i}decode(i,e){return Ed(i).forEach(t=>{this.core.trtc.emit($.SEI_MESSAGE,{seiPayloadType:t.seiPayloadType,data:t.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"})}),i}destroy(){}getValidateRule(i){switch(i){case"start":return{type:"object"};case"update":return{type:"object"};case"stop":return{type:"object"}}}start(i){Ni?(this._seiWorker=b_(),this._seiWorker.onmessage=e=>{this.core.trtc.emit($.SEI_MESSAGE,P(N({},e.data),{streamType:er(e.data.streamType)}))},this._seiWorker.onerror=e=>{this.log.error("seiWorker error: ",e.message)},this.core.room.videoManager.enableSEI({seiWorker:this._seiWorker})):this.core.room.videoManager.enableSEI({encoder:this.encode.bind(this),decoder:this.decode.bind(this)})}stop(i){this.core.room.videoManager.disableSEI()}update({buffer:i,options:e}){var o;let t=[e.seiPayloadType,i],s=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(t):(this._seiMessageList.push(t),s&&this._smallSeiMessageList.push(t)),this.core.innerEmitter.emit("265",{room:this.core.room,data:t,isMain:!e.toSubStream}),(o=this._seiWorker)==null||o.postMessage({message:t,isMain:!e.toSubStream,small:s})}getName(){return gd.Name}getAlias(){return"sei"}getGroup(){return"sei"}},ro=gd;l(ro,"Name","SEI");function Uu([r,i]){let e=i.byteLength,t=parseInt(String(e/255),10),s=e%255,o=[];o.push(0,0,0,1,6,r);for(let a=0;a<t;a++)o.push(255);o.push(s);let n=new DataView(i);return o.push(...new Uint8Array(n.buffer)),o.push(128),new Di(new DataView(new Uint8Array(o).buffer),!0)}function Bu(r){return r.type==="empty"||r.data.byteLength===0}function $u(r){return r.getInt32(0)===1&&r.getInt8(4)===6}function Fu(r){let i=0,e=0,t=new DataView(r);for(let s=0;s<r.byteLength;s++)switch(t.getUint8(s)){case 0:i++;break;case 1:(i===2||i===3)&&e++,i=0;break;default:i=0;break}return e}function fd(r,i){if(i.length>0&&r.data.byteLength>0){let e=Fu(r.data),t=9-e;if(t<=0)return 0;let s=i.splice(0,t).reverse().map(Uu),o=s.reduce((u,p)=>u+p.dataView.byteLength,0),n=new ArrayBuffer(o+r.data.byteLength),a=new DataView(n),c=new DataView(r.data),d=0;for(let u=0;u<s.length;u++)for(let p=0;p<s[u].dataView.byteLength;p++)a.setInt8(d++,s[u].dataView.getInt8(p));for(let u=0;u<r.data.byteLength;u++)a.setInt8(d++,c.getInt8(u));return r.data=n,s.length}return 0}function Ed(r){try{let i=new DataView(r.data);if(Bu(r)||!$u(i))return[];let e=[],t=0,s=-1,o=-1;for(let n=0;n<r.data.byteLength;n++){let a=i.getUint8(n);if(a===0)t++;else if(a===1){if(t===2||t===3){let c=n-t;if(s===-1?s=c:o===-1&&(o=c,e.push(new Di(new DataView(i.buffer.slice(s,o)))),s=c,o=-1),!(i.getUint8(n+1)===6)){r.data=i.buffer.slice(c);break}}t=0}else t=0}return e.reverse()}catch(i){return[]}}function wu(r){return new TransformStream({transform(i,e){fd(i,r),e.enqueue(i)}})}function Vu(r,i){return new TransformStream({transform(e,t){Ed(e).forEach(s=>{self.postMessage({seiPayloadType:s.seiPayloadType,data:s.seiPayload.buffer,userId:r,streamType:i})}),t.enqueue(e)}})}function b_(){let r=[Di],i=[Fu,Bu,$u,Uu,fd,Ed,wu,Vu],e=()=>{let a=[],c=[],d=[];self.onmessage=u=>{u.data.isMain?(a.push(u.data.message),u.data.small&&d.push(u.data.message)):c.push(u.data.message)},self.onrtctransform=u=>{let{options:p}=u.transformer,m=p.isReceiver?Vu(p.userId,p.streamType):wu(p.isMain?p.small?d:a:c);u.transformer.readable.pipeThrough(m).pipeTo(u.transformer.writable)}},t=`(()=>{${r.map(a=>`const ${a.name}=(()=>${a.toString()})()`).join(`
65
+ ${s.stack}`),!1}},r};var Jn=new WeakMap;function ku(r,i){return W((e,t)=>function(...s){var a,c;let o=(a=Jn.get(this))==null?void 0:a.get(i(...s));o&&o>0&&clearTimeout(o);let n=window.setTimeout(()=>{e.apply(this,s)},r);Jn.has(this)?(c=Jn.get(this))==null||c.set(i(...s),n):Jn.set(this,new Map([[i(...s),n]]))})}var Lu="5.8.2-beta.8";function ke(...r){return W((i,e)=>function(...t){try{qn.call(this,r,t,e,this._name)}catch(s){return Promise.reject(s)}return i.apply(this,t)})}function ld(...r){return W((i,e)=>function(...t){try{qn.call(this,r,t,e,this._name)}catch(s){throw s}return i.apply(this,t)})}function qn(r,i,e,t){if(he(r))for(let s=0;s<r.length;s++)jn.call(this,{rule:r[s],value:i[s],key:r[s].name,fnName:e,className:t});else jn.call(this,{rule:r,value:i[0],key:r.name,fnName:e,className:t})}function jn({rule:r,value:i,key:e,fnName:t,className:s}){function o(c){return{code:w.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:r,value:i}}}if(T(i)){if(r.required)throw new k(o(5001));if(T(r.defaultValue)){K(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),K(r.type[d])&&i instanceof r.type[d]&&(c=!0),z(r.type[d])&&fe(i)===r.type[d].toLowerCase()&&(c=!0);if(!c)throw new k({code:w.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:r.type.map(d=>Ds(d)?Ko(d):z(d)?d:fe(d))},value:i}})}else if(!T(r.type)&&fe(i)!==r.type)throw new k(o(5002));if(r.allowEmpty===!1){let c=ee(i)&&(i===0||Number.isNaN(i)),d=z(i)&&i.trim()==="";if(c||d)throw new k(o(5003))}if(r.notLessThanZero&&ee(i)&&i<0)throw new k(o(5006));if(!T(r.min)&&ee(i)&&i<r.min)throw new k(o(5007));if(!T(r.max)&&ee(i)&&i>r.max)throw new k(o(5008));if(z(r.instanceOf)){if(!i||i._name!==r.instanceOf)throw new k(o(5004))}else if(K(r.instanceOf)&&!(i instanceof r.instanceOf))throw new k(o(5004));if(Array.isArray(r.values)&&!r.values.includes(i))throw new k(o(5005));let{properties:n}=r;Je(n)&&mt(i)&&Object.keys(n).forEach(c=>{jn.call(this,{rule:n[c],value:i&&i[c],key:`${c}`,fnName:t,className:s})});let{arrayItem:a}=r;Je(a)&&he(i)&&i.forEach((c,d)=>{jn.call(this,{rule:a,value:c,key:`${e}[${d}]`,fnName:t,className:s})}),K(r.validate)&&r.validate.call(this,i,e,t,s,this)}function oe(r={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t}=r;return W((s,o)=>function(...n){function a(u,p,m){if(m&&m.includes(u))return"hided";if(e){let f=e(...n);if(n[f.argIndex]===p)return f.value}if(p===n||u in n)return p;try{return p instanceof HTMLElement?`id: ${p.id} type:${fe(p)}`:(JSON.stringify(p),p)}catch(f){return`type:${fe(p)}`}}let c=this._log||I;n.length>0?c.info(`${o}() ${JSON.stringify(n,(u,p)=>a(u,p,["userSig","privateMapKey"]))}`):c.info(`${o}()`);let d=t?t(...n):un[o];try{let u=s.apply(this,n),p=x();return vs(u)?u.then(m=>(c.info(`${o}() success ${i.call(this,...n)}`),D.addSuccessEvent({key:d,cost:x()-p}),m)).catch(m=>{throw m=k.convertFrom.call(this,m,o,n.length===1?n[0]:n),c.error(`${o}() failed ${i.call(this,...n)} ${m} params: ${JSON.stringify(n,a)}`),D.addFailedEvent({key:d,error:m}),m}):(D.addSuccessEvent({key:d}),u)}catch(u){throw u=k.convertFrom.call(this,u,o),c.error(`${o}() failed ${u} params: ${JSON.stringify(n,a)}`),D.addFailedEvent({key:d,error:u}),u}})}var Xn=r=>W((i,e)=>function(t,s){return _(this,null,function*(){let o=this._plugins.get(t);if(!o)throw this._log.error(`plugin ${String(t)} is not found`),new k({code:w.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});if(K(o.constructor.isSupported)&&!o.constructor.isSupported())throw this._log.error(`plugin ${String(t)} is not supported`),new k({code:w.ENV_NOT_SUPPORTED,message:`plugin ${String(t)} is not supported`,extraCode:5210,fnName:e});return qn.call(this,o.getValidateRule(r),[s],e,"TRTC"),i.call(this,o,s)})});var Qn=0,ud=class{constructor(i,e){l(this,"player");l(this,"publisher");l(this,"mixInput");this.mixInput=new xr(e),i.url?(this.player=new Audio(i.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(i.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(i.track),this.mixInput.connect()}updateSettings(i){!this.player||(T(i.volume)||(this.volume=i.volume),T(i.loop)||(this.loop=i.loop),T(i.playbackRate)||(this.playbackRate=i.playbackRate))}updateListener(i){if(!!this.player){if(i.onDurationChange){let{onDurationChange:e}=i;this.player.ondurationchange=t=>{e(t.target.duration)}}if(i.onTimeUpdate){let e=i.onTimeUpdate,{player:t}=this;t.ontimeupdate=()=>{e(t.currentTime,t.duration)}}i.onEnded&&(this.player.onended=i.onEnded)}}reset(){this.seek(0),this.mixInput.connect()}seek(i){!this.player||i<0&&i>this.player.duration||(this.player.currentTime=i,this.publisher.currentTime=i)}play(){var i,e;return(i=this.publisher)==null||i.play(),(e=this.player)==null?void 0:e.play()}pause(){var i,e;(i=this.player)==null||i.pause(),(e=this.publisher)==null||e.pause()}stop(){var i;(i=this.player)==null||i.pause(),this.mixInput.disconnect()}setOperation(i){i==="pause"&&this.pause(),i==="resume"&&(this.pause(),this.play()),i==="stop"&&(this.pause(),this.seek(0))}set volume(i){!this.player||!this.publisher||(this.player.volume=i,this.publisher.volume=i)}set loop(i){!this.player||!this.publisher||(this.player.loop=i,this.publisher.loop=i)}set playbackRate(i){!this.player||!this.publisher||(this.player.playbackRate=i,this.publisher.playbackRate=i)}};function Wr(r,i){if(i&&typeof i!="function")throw new k({code:w.INVALID_PARAMETER,message:`start audioMixer plugin: param ${r} should be a function.`})}var Jr=class{constructor(i){this.core=i;l(this,"log");l(this,"mixedMusicMap",new Map);l(this,"cacheMusicMap",new Map);Qn=Qn+1,this.log=i.log.createChild({id:`${this.getAlias()}${Qn}`}),this.log.info(`[audioMixer] created id=${this.getAlias()}${Qn}`),this.core=i}getName(){return Jr.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return Jr.startValidateRule;case"update":return Jr.updateValidateRule;case"stop":return Jr.stopValidateRule}}start(i){return _(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 o=this.cacheMusicMap.get(t);o?i.url?o.reset():(o.mixInput.replaceSource(i.track),o.mixInput.connect()):(o=new ud(i,e.audioManager),this.cacheMusicMap.set(t,o)),o.updateListener(i),o.updateSettings(i),yield o.play(),this.mixedMusicMap.set(t,o),this.log.info(`start mix audio track ${t} success.`),D.addEnum({key:502700,value:3}),this.kvUpload(i)})}update(i){return _(this,null,function*(){let{id:e,operation:t,seekFrom:s,playbackRate:o}=i;this.log.info(`update music source, ${JSON.stringify(i)}`);let n=this.mixedMusicMap.get(e);if(!n){this.log.warn(`update music source failed, music id: ${e} not found.`);return}n.updateSettings(i),n.updateListener(i),T(t)||n.setOperation(t),T(s)||n.seek(s),this.kvUpload(i)})}stop(e){return _(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()})}kvUpload(i){let{track:e,loop:t,volume:s,playbackRate:o,operation:n,seekFrom:a,onTimeUpdate:c,onDurationChange:d,onEnded:u}=i;e&&D.addCount({key:502711}),t&&D.addCount({key:502703}),s&&D.addCount({key:502704}),o&&D.addCount({key:502705}),n&&D.addCount({key:502706}),a&&D.addCount({key:502707}),typeof c!="function"&&D.addCount({key:502709}),typeof u!="function"&&D.addCount({key:502710}),typeof d!="function"&&D.addCount({key:502708})}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()}},Li=Jr;l(Li,"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],o=["mp3","ogg","wav","flac"],n=s.split(".").pop(),a=o.indexOf(n)>=0,c=s.startsWith("blob"),d=s.startsWith("data");if(!(a||c||d))throw new k({code:w.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new k({code:w.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});Wr("onTimeUpdate",i.onTimeUpdate),Wr("onEnded",i.onEnded),Wr("onDurationChange",i.onDurationChange)}}),l(Li,"updateValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},loop:{type:"boolean"},volume:{type:"number"},seekFrom:{type:"number"},operation:{type:"string",values:["pause","resume","stop"]}},validate(i,e,t){Wr("onTimeUpdate",i.onTimeUpdate),Wr("onEnded",i.onEnded),Wr("onDurationChange",i.onDurationChange)}}),l(Li,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),l(Li,"Name","AudioMixer");var A_=r=>(r=Number(r),r>0&&r<14e8),zn=0,hd,jr=class{constructor(i){this.core=i;l(this,"log");l(this,"audioContext",qe("denoiser"));l(this,"workletNode");zn=zn+1,this.log=i.log.createChild({id:`${this.getAlias()}${zn}`}),this.log.info(`[audioDenoiser] created id=${this.getAlias()}${zn}`),i.assetsPath&&this.preload(`${i.assetsPath}/denoiser-wasm.js`)}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,o){if(!i.room.audioManager.hasAudioTrack)throw new k({code:w.INVALID_OPERATION,extraCode:5106,fnName:s})}}}preload(i){return hd||(hd=this.doPreload(i)),hd}doPreload(i){return _(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield Wi(this.audioContext,t)}finally{URL.revokeObjectURL(t)}})}getName(){return jr.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(i){switch(i){case"start":return jr.startValidateRule(this.core);case"update":return jr.updateValidateRule;case"stop":return jr.stopValidateRule}}start(i){return _(this,null,function*(){let{room:e}=this.core;if(yield this.preload(`${i.assetsPath}/denoiser-wasm.js`),!this.workletNode){let t=String(Date.now()).slice(0,-3),{auth:s,sign:o,status:n,message:a}=yield R_(P(N({},i),{timestamp:t}));if(!s)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${s}. Message: ${a}`),new k({code:w.INVALID_PARAMETER,message:a});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:o,status:n}}),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 _(this,null,function*(){})}stop(){return _(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(){}},ir=jr;l(ir,"updateValidateRule",{type:"object"}),l(ir,"stopValidateRule",{type:"object"}),l(ir,"Name","AIDenoiser");var xu={MAIN:"schedule.cloud-rtc.com",MAIN_OVERSEA:"schedule.rtc.tencentcloud.com"};function C_(r){let i;return A_(r)?i=xu.MAIN_OVERSEA:i=xu.MAIN,i}function R_(s){return _(this,arguments,function*({sdkAppId:r,userId:i,userSig:e,timestamp:t}){let n=`https://${C_(r)}/api/v1/audioAiAuth?sdkAppId=${r}&userId=${i}&userSig=${e}&timestamp=${t}`,a=yield fetch(n),{data:{errCode:c,errMsg:d,sign:u,status:p}}=yield a.json();if(p==="1")return{auth:!0,sign:u,status:p,message:d};let m="Init RTCAIDenoiser failed.",f="";switch(c){case 1:f="Please check your params.";break;case 2:f="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:f="Server is invalid. Please contact our engineer. ";break;case 4:f="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:f="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:f="Your version is not supported.";break}return{auth:!1,status:p,message:d?`${m} Reason: ${d}. ${f}`:`${m}, ${f}`}})}var Pu=Se(Ne(),1);var md=class extends Pu.EventEmitter{constructor(){super();this.state="nominal";this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return _(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!pe&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){Z.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let t=this.stateNum,s=e[e.length-1];this.state=s.state,(this.stateNum>3||t>3)&&I.info(`${s.source}: ${s.state}`),this.emit("state-changed",{type:s.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(t){Z.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},y_=new md,pd=y_;var _d=0,gd=class{constructor(i){this.core=i;l(this,"log");l(this,"_seiMessageList",[]);l(this,"_smallSeiMessageList",[]);l(this,"_subStreamSeiMessageList",[]);l(this,"_seiWorker");_d++,this.log=i.log.createChild({id:`${this.getAlias()}${_d}`}),this.log.info(`[sei] created id=${this.getAlias()}${_d}`),this.core=i}encode(i,e){try{let t=e===8?this._smallSeiMessageList:e===2?this._subStreamSeiMessageList:this._seiMessageList,s=fd(i,t);s&&this.log.debug(`${s} sei sent`)}catch(t){this.log.warn(t)}return i}decode(i,e){return Ed(i).forEach(t=>{this.core.trtc.emit($.SEI_MESSAGE,{seiPayloadType:t.seiPayloadType,data:t.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"})}),i}destroy(){}getValidateRule(i){switch(i){case"start":return{type:"object"};case"update":return{type:"object"};case"stop":return{type:"object"}}}start(i){Ni?(this._seiWorker=b_(),this._seiWorker.onmessage=e=>{this.core.trtc.emit($.SEI_MESSAGE,P(N({},e.data),{streamType:er(e.data.streamType)}))},this._seiWorker.onerror=e=>{this.log.error("seiWorker error: ",e.message)},this.core.room.videoManager.enableSEI({seiWorker:this._seiWorker})):this.core.room.videoManager.enableSEI({encoder:this.encode.bind(this),decoder:this.decode.bind(this)})}stop(i){this.core.room.videoManager.disableSEI()}update({buffer:i,options:e}){var o;let t=[e.seiPayloadType,i],s=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(t):(this._seiMessageList.push(t),s&&this._smallSeiMessageList.push(t)),this.core.innerEmitter.emit("265",{room:this.core.room,data:t,isMain:!e.toSubStream}),(o=this._seiWorker)==null||o.postMessage({message:t,isMain:!e.toSubStream,small:s})}getName(){return gd.Name}getAlias(){return"sei"}getGroup(){return"sei"}},ro=gd;l(ro,"Name","SEI");function Uu([r,i]){let e=i.byteLength,t=parseInt(String(e/255),10),s=e%255,o=[];o.push(0,0,0,1,6,r);for(let a=0;a<t;a++)o.push(255);o.push(s);let n=new DataView(i);return o.push(...new Uint8Array(n.buffer)),o.push(128),new Di(new DataView(new Uint8Array(o).buffer),!0)}function Bu(r){return r.type==="empty"||r.data.byteLength===0}function $u(r){return r.getInt32(0)===1&&r.getInt8(4)===6}function Fu(r){let i=0,e=0,t=new DataView(r);for(let s=0;s<r.byteLength;s++)switch(t.getUint8(s)){case 0:i++;break;case 1:(i===2||i===3)&&e++,i=0;break;default:i=0;break}return e}function fd(r,i){if(i.length>0&&r.data.byteLength>0){let e=Fu(r.data),t=9-e;if(t<=0)return 0;let s=i.splice(0,t).reverse().map(Uu),o=s.reduce((u,p)=>u+p.dataView.byteLength,0),n=new ArrayBuffer(o+r.data.byteLength),a=new DataView(n),c=new DataView(r.data),d=0;for(let u=0;u<s.length;u++)for(let p=0;p<s[u].dataView.byteLength;p++)a.setInt8(d++,s[u].dataView.getInt8(p));for(let u=0;u<r.data.byteLength;u++)a.setInt8(d++,c.getInt8(u));return r.data=n,s.length}return 0}function Ed(r){try{let i=new DataView(r.data);if(Bu(r)||!$u(i))return[];let e=[],t=0,s=-1,o=-1;for(let n=0;n<r.data.byteLength;n++){let a=i.getUint8(n);if(a===0)t++;else if(a===1){if(t===2||t===3){let c=n-t;if(s===-1?s=c:o===-1&&(o=c,e.push(new Di(new DataView(i.buffer.slice(s,o)))),s=c,o=-1),!(i.getUint8(n+1)===6)){r.data=i.buffer.slice(c);break}}t=0}else t=0}return e.reverse()}catch(i){return[]}}function wu(r){return new TransformStream({transform(i,e){fd(i,r),e.enqueue(i)}})}function Vu(r,i){return new TransformStream({transform(e,t){Ed(e).forEach(s=>{self.postMessage({seiPayloadType:s.seiPayloadType,data:s.seiPayload.buffer,userId:r,streamType:i})}),t.enqueue(e)}})}function b_(){let r=[Di],i=[Fu,Bu,$u,Uu,fd,Ed,wu,Vu],e=()=>{let a=[],c=[],d=[];self.onmessage=u=>{u.data.isMain?(a.push(u.data.message),u.data.small&&d.push(u.data.message)):c.push(u.data.message)},self.onrtctransform=u=>{let{options:p}=u.transformer,m=p.isReceiver?Vu(p.userId,p.streamType):wu(p.isMain?p.small?d:a:c);u.transformer.readable.pipeThrough(m).pipeTo(u.transformer.writable)}},t=`(()=>{${r.map(a=>`const ${a.name}=(()=>${a.toString()})()`).join(`
66
66
  `)}
67
67
  ${i.map(a=>a.toString()).join(`
68
68
  `)};(${e})()})()`,s=new Blob([t],{type:"text/javascript"}),o=URL.createObjectURL(s),n=new Worker(o);return URL.revokeObjectURL(o),n}var Hu=0,Yn=new Set,Le=null;ma(Lu);var N_={RtcError:k,ErrorCode:w,ErrorCodeDictionary:It},qr=class extends Gu.EventEmitter{constructor(e,t){super();l(this,"_room");l(this,"_eventListened",new Set);l(this,"_localVideoTrack",null);l(this,"_localAudioTrack",null);l(this,"_localScreenTrack",null);l(this,"_localScreenAudioTrack",null);l(this,"_localVideoConfig",null);l(this,"_localScreenConfig",null);l(this,"_localAudioConfig",null);l(this,"_remoteVideoConfigMap",new Map);l(this,"_remoteAudioConfigMap",new Map);l(this,"_remoteAudioMuteMap",new Map);l(this,"_mediaTrackMap",new WeakMap);l(this,"_log",I.createLogger({id:`t${++Hu}`}));l(this,"_plugins",new Map);l(this,"_networkQuality",null);l(this,"_speakerId");this._room=new e(N({logger:this._log,frameWorkType:qr.frameWorkType},t)),this._log.debug(`TRTC.create() ${JSON.stringify(t,(s,o)=>s==="plugins"?o.map(n=>n.Name):o)}`),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(Li,t.assetsPath),this._use(ir,t.assetsPath),t.enableSEI&&si&&(this._use(ro),this.startPlugin("SEI")),this._room.on("audio-volume",s=>{!s.find(o=>o.userId==="")&&this._localAudioTrack&&s.push({userId:"",volume:Math.floor(this._localAudioTrack.getAudioLevel()*100)}),this.emit($.AUDIO_VOLUME,{result:s.sort((o,n)=>n.volume-o.volume)})}),this._room.videoManager.on("error",({reason:s,error:o})=>{this._log.error(new k({code:w.OPERATION_FAILED,extraCode:5504,messageParams:{reason:s,error:o}}))}),this._listenEvents(),this._initActiveSpeaker(),Mu(this,"trtc")}static create(e){}static _create(e,t){Iu();let s=new qr(e,t||{});return Yn.add(s),s}get room(){return this._room}_listenEvents(){De(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,k.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=>{De(s,s).add("player-state-changed",o=>{let n=P(N({},o),{userId:e.userId});s.kind===h.VIDEO&&(n.streamType=er(s.streamType)),this.emit(s.kind===h.AUDIO?$.AUDIO_PLAY_STATE_CHANGED:$.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",o=>{o.getCode()===A.PLAY_NOT_ALLOWED&&this.emit($.AUTOPLAY_FAILED,{userId:s.userId})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(s=>{me(s)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:t})=>{let{userId:s}=t,o=e.audioAvailable,n=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"}`),o!==a&&(this.emit(a?$.REMOTE_AUDIO_AVAILABLE:$.REMOTE_AUDIO_UNAVAILABLE,{userId:s}),a?this._onAudioAvailable({userId:s}):this._onAudioUnavailable({userId:s,muteState:t})),n!==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("sei-message",e=>{this.emit($.SEI_MESSAGE,P(N({},e),{streamType:er(e.streamType)}))}).add("firewall-restriction",()=>{this.emit($.ERROR,new k({code:w.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var o,n,a,c,d,u,p;let t={2:"big",3:"small",7:"sub"},s={rtt:e.msg_up_stream_info.msg_network_status.uint32_rtt||((o=e.msg_down_stream_info[0])==null?void 0:o.msg_network_status.uint32_rtt)||((n=this._networkQuality)==null?void 0:n.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:(((u=e.msg_up_stream_info.msg_audio_status)==null?void 0:u.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((p=e.msg_up_stream_info.msg_audio_status)==null?void 0:p.uint32_audio_level)||0)/ct},video:e.msg_up_stream_info.msg_video_status.filter(m=>t[m.uint32_video_stream_type]).map(m=>({bitrate:(m.uint32_video_codec_bitrate||0)/1e3,width:m.uint32_video_width,height:m.uint32_video_height,frameRate:m.uint32_video_enc_fps,videoType:t[m.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(m=>({userId:m.msg_user_info.str_identifier,audio:{bitrate:(m.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(m.msg_audio_status.uint32_audio_level||0)/ct},video:m.msg_video_status.map(f=>({bitrate:(f.uint32_video_codec_bitrate||0)/1e3,width:f.uint32_video_width,height:f.uint32_video_height,frameRate:f.uint32_video_dec_fps,videoType:t[f.uint32_video_stream_type]}))}))};this.emit($.STATISTICS,s)}).add("custom-message",e=>{this.emit($.CUSTOM_MESSAGE,e)}),De(this,ge).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=>_(this,null,function*(){if(this.emit($.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Le&&Le.deviceId===ls){let t=(yield qi()).find(s=>s.deviceId===ls);t&&Le.groupId!==t.groupId&&(Le=t,this.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}})).add("audioOutputRemoved",e=>_(this,null,function*(){this.emit($.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield qi())[0];t&&Le&&(Le.deviceId===e.deviceId||Le.deviceId===ls&&Le.groupId!==t.groupId)&&(Le=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 o=new e(Ou.call(this,{TRTC:qr,room:this._room,errorModule:N_,assetsPath:t}));this._plugins.set(e.Name,o),e.autoStart&&(this.startPlugin(e.Name),this._log.info("auto start plugin",e.Name))}enterRoom(e){return _(this,null,function*(){var c,d;let{scene:t="rtc",enableAutoPlayDialog:s=!0,autoReceiveAudio:o=!0,autoReceiveVideo:n=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!z(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=o,this._room.autoReceiveVideo=n,de(e.preferHW)&&(this._room.preferHW=e.preferHW);let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:e.role==="audience"?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,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,qr.frameWorkType),this._checkTrackToPublish(),pd.start()})}exitRoom(){return _(this,null,function*(){return yield this._exitRoom()})}switchRole(e,t){return _(this,null,function*(){t!=null&&t.privateMapKey&&(this._room.privateMapKey=t.privateMapKey),t!=null&&t.latencyLevel&&(this._room.latencyLevel=t.latencyLevel),yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){me(this),this.removeAllListeners(),this._room.destroy(),Yn.delete(this),Yn.size===0&&pd.destroy(),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 _(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:o}=e,n=new Oe(this._room.audioManager),a={},c={muted:!0};o&&(T(o.microphoneId)?T(o.audioTrack)||(a.customSource=o.audioTrack):a.deviceId=o.microphoneId,o&&ee(o.captureVolume)&&n.setCaptureVolume(o.captureVolume),T(o.profile)||(z(o.profile)?bo[o.profile]&&n.setProfile(bo[o.profile]):n.setProfile(o.profile)),ee(o.earMonitorVolume)&&(c.muted=!(o.earMonitorVolume>0),c.volume=o.earMonitorVolume),T(o.echoCancellation)||(n.profile.echoCancellation=o.echoCancellation),T(o.noiseSuppression)||(n.profile.noiseSuppression=o.noiseSuppression),T(o.autoGainControl)||(n.profile.autoGainControl=o.autoGainControl)),n.on("5",d=>{this.emit($.ERROR,new k({code:w.DEVICE_ERROR,extraCode:5309,messageParams:{error:d}}))}),n.on("2",d=>{this.emit($.DEVICE_CHANGED,{type:"microphone",action:"active",device:d})}),n.on("4",d=>{let u;d.error&&(u=k.convertFrom(d.error)),this.emit($.PUBLISH_STATE_CHANGED,P(N({},d),{error:u}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId),yield n.capture(a),T(s)||n.setMute(s),De(n,n).add("player-state-changed",d=>{this.emit($.AUDIO_PLAY_STATE_CHANGED,P(N({},d),{userId:""}))}),t&&this._room.isJoined&&this._room.publish(n).catch(()=>{}),this._localAudioTrack=n,this._localAudioConfig=P(N({},e),{publish:t}),yield this._updateAudioPlayOption({playOption:c,track:n})})}updateLocalAudio(e){return _(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:s,option:o}=e,n={};o&&(o.microphoneId?yield this._localAudioTrack.switchDevice(o.microphoneId):T(o.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(o.audioTrack)),T(o.captureVolume)||this._localAudioTrack.setCaptureVolume(o.captureVolume),T(o.earMonitorVolume)||(n.muted=!(o.earMonitorVolume>0),n.volume=o.earMonitorVolume),yield this._localAudioTrack.update3A(o)),this._room.isJoined&&!T(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),T(s)||this._localAudioTrack.setMute(s),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),ei(this._localAudioConfig,e)})}stopLocalAudio(){return _(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),me(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)})}startLocalVideo(){return _(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:o,option:n}=e,a=new ue(this._room.videoManager),c={},d={};if(n&&(n.cameraId?c.deviceId=n.cameraId:T(n.useFrontCamera)?T(n.videoTrack)||(c.customSource=n.videoTrack):c.facingMode=n.useFrontCamera?h.FACING_MODE_USER:h.FACING_MODE_ENVIRONMENT,T(n.profile)||(z(n.profile)?Ze[n.profile]&&a.setProfile(Ze[n.profile]):a.setProfile(n.profile)),T(n.fillMode)||(d.objectFit=n.fillMode),T(n.mirror)||(d.mirror=n.mirror),T(n.small)||(ws()?z(n.small)?a.small=Ze[n.small]:n.small===!0?a.small=Ze["120p"]:a.small=n.small:this._log.warn("small stream is not supported"))),a.on("5",u=>{this.emit($.ERROR,new k({code:w.DEVICE_ERROR,extraCode:5308,messageParams:{error:u}}))}),a.on("2",u=>{this.emit($.DEVICE_CHANGED,{type:"camera",action:"active",device:u})}),a.on("4",u=>{let p;u.error&&(p=k.convertFrom(u.error)),this.emit($.PUBLISH_STATE_CHANGED,P(N({},u),{error:p}))}),this._listenOutputTrackChanged(a),yield a.capture(c),T(o)||(yield a.setMute(o)),a.mediaTrack)if(n!=null&&n.qosPreference){let u=tr(n.qosPreference);a.mediaTrack.contentHint=u}else n!=null&&n.videoTrack||(a.mediaTrack.contentHint=tr(st.QOS_PREFERENCE_SMOOTH));De(a,a).add("player-state-changed",u=>{this.emit($.VIDEO_PLAY_STATE_CHANGED,P(N({},u),{userId:"",streamType:"main"}))}),s&&this._room.isJoined&&this._room.publish(a).catch(()=>{}),this._localVideoTrack=a,this._localVideoConfig=P(N({},e),{view:t,publish:s}),yield this._updateVideoPlayOption({view:t,playOption:d,track:a})})}updateLocalVideo(e){return _(this,null,function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:s,mute:o,option:n}=e,a={};if(n){if(T(n.profile)||(z(n.profile)?Ze[n.profile]&&this._localVideoTrack.setProfile(Ze[n.profile]):this._localVideoTrack.setProfile(n.profile),(!n.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(n.cameraId))&&T(n.useFrontCamera)&&this._localVideoTrack.applyProfile()),n.cameraId?yield this._localVideoTrack.switchDevice(n.cameraId):T(n.useFrontCamera)?T(n.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(n.videoTrack)):yield this._localVideoTrack.switchDevice(n.useFrontCamera?h.FACING_MODE_USER:h.FACING_MODE_ENVIRONMENT),T(n.fillMode)||(a.objectFit=n.fillMode),T(n.mirror)||(a.mirror=n.mirror),n.qosPreference&&this._localVideoTrack.mediaTrack){let c=tr(n.qosPreference);this._localVideoTrack.mediaTrack.contentHint=c}if(n.small){let c=!this._localVideoTrack.small;ws()?(n.small===!0?this._localVideoTrack.small=Ze["120p"]:z(n.small)?this._localVideoTrack.small=Ze[n.small]:this._localVideoTrack.small=n.small,this._room.videoManager.update(),c&&this._room.enableSmall(!0)):this._log.warn("small stream is not supported")}else n.small===!1&&this._localVideoTrack.small&&(delete this._localVideoTrack.small,this._room.videoManager.update(),this._room.enableSmall(!1))}this._room.isJoined&&!T(s)&&(s&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._localVideoConfig.publish&&!s&&this._room.unpublish(this._localVideoTrack).catch(()=>{})),T(o)||(yield this._localVideoTrack.setMute(o)),yield this._updateVideoPlayOption({view:t,playOption:a,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),ei(this._localVideoConfig,e)})}stopLocalVideo(){return _(this,null,function*(){!this._localVideoTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),me(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return _(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:o}=e,n=new ze(this._room.videoManager);n.on("4",p=>{let m;p.error&&(m=k.convertFrom(p.error)),this.emit($.PUBLISH_STATE_CHANGED,P(N({},p),{error:m}))}),this._listenOutputTrackChanged(n);let a=null,c={},d={};o&&(T(o.profile)||(z(o.profile)?No[o.profile]&&n.setProfile(No[o.profile]):n.setProfile(o.profile)),o.systemAudio&&(c.systemAudio=!0,c.echoCancellation=o.echoCancellation,c.noiseSuppression=o.noiseSuppression,c.autoGainControl=o.autoGainControl),T(o.fillMode)||(d.objectFit=o.fillMode),o.videoTrack&&(c.videoTrack=o.videoTrack),o.audioTrack&&(c.audioTrack=o.audioTrack),o.captureElement&&(c.captureElement=o.captureElement),o.preferDisplaySurface&&(c.preferDisplaySurface=o.preferDisplaySurface));let u=yield n.capture(c);if(o!=null&&o.qosPreference){let p=tr(o.qosPreference);n.mediaTrack.contentHint=p}else o!=null&&o.videoTrack||(n.mediaTrack.contentHint=tr(st.QOS_PREFERENCE_CLEAR));if(n.mediaTrack.addEventListener(h.ENDED,()=>{this._stopScreenShare(),this.emit($.SCREEN_SHARE_STOPPED)}),u.getAudioTracks()[0]&&(a=new Ht(this._room.audioManager),a.setInputMediaStreamTrack(u.getAudioTracks()[0]),this._speakerId&&a.setAudioOutput(this._speakerId)),De(n,n).add("player-state-changed",p=>{this.emit($.VIDEO_PLAY_STATE_CHANGED,P(N({},p),{userId:"",streamType:"sub"}))}),s&&this._room.isJoined){let p=[n];a&&p.push(a),this._room.publish(...p).catch(()=>{})}this._localScreenTrack=n,this._localScreenAudioTrack=a,this._localScreenConfig=P(N({},e),{view:t,publish:s}),yield this._updateVideoPlayOption({view:t,playOption:d,track:n})})}updateScreenShare(e){return _(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:s,option:o}=e,n={};if(o&&(T(o.fillMode)||(n.objectFit=o.fillMode),o.qosPreference)){let a=tr(o.qosPreference);this._localScreenTrack.mediaTrack.contentHint=a}this._room.isJoined&&!T(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:n,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),ei(this._localScreenConfig,e)})}stopScreenShare(){return _(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return _(this,null,function*(){let{view:t,userId:s,streamType:o,option:n}=e,a=`${s}_${o}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${s}, streamType:${o}`);return}let c=this._room.remotePublishedUserMap.get(s);if(!c)return;let d={},u=o==="main"?c.remoteVideoTrack:c.remoteAuxiliaryTrack;this._listenOutputTrackChanged(u),n&&(T(n.fillMode)||(d.objectFit=n.fillMode),T(n.mirror)||(d.mirror=n.mirror),d.canvasRender=n.canvasRender,o==="main"&&!T(n.small)&&(c.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,u.user))),yield this._room.subscribe(u),yield this._updateVideoPlayOption({view:t,playOption:d,track:u}),this._emitTrackEvent(u),this._remoteVideoConfigMap.set(a,{config:e}),n&&!T(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:u,view:t,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:n==null?void 0:n.viewRoot})})}updateRemoteVideo(e){return _(this,null,function*(){var v,U;let{view:t,userId:s,streamType:o,option:n}=e,a=`${s}_${o}`,c=this._remoteVideoConfigMap.get(a);if(!c||!this._room.remotePublishedUserMap.has(s))return;let d={};n&&(T(n.fillMode)||(d.objectFit=n.fillMode),T(n.mirror)||(d.mirror=n.mirror));let u=null,p=this._room.remotePublishedUserMap.get(s);if(o==="main"&&(p==null?void 0:p.muteState.hasVideo)&&(u=p.remoteVideoTrack),o==="sub"&&(p==null?void 0:p.muteState.hasAuxiliary)&&(u=p.remoteAuxiliaryTrack),!u)return;let{config:m}=c;o==="main"&&n&&!T(n.small)&&this._room.changeType(n.small,u.user),yield this._updateVideoPlayOption({view:t,playOption:d,track:u,prevConfig:m}),ei(m,e);let f=T(n==null?void 0:n.receiveWhenViewVisible)?(v=m.option)==null?void 0:v.receiveWhenViewVisible:n.receiveWhenViewVisible,R=T(t)?m.view:t,C=T(n==null?void 0:n.viewRoot)?(U=m.option)==null?void 0:U.viewRoot:n.viewRoot;this._observeView({remoteTrack:u,view:R,receiveWhenViewVisible:f,viewRoot:C})})}stopRemoteVideo(e){return _(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,t=!0){return _(this,null,function*(){let s=[],o=this._room.remotePublishedUserMap.get(e.userId);if(o){let{muteState:a,remoteVideoTrack:c,remoteAuxiliaryTrack:d}=o;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 n=this._remoteVideoConfigMap.get(`${e.userId}_${e.streamType}`);n&&n.observer&&n.observer.disconnect(),this._remoteVideoConfigMap.delete(`${e.userId}_${e.streamType}`)})}muteRemoteAudio(e,t){return _(this,null,function*(){if(e==="*")if(t)yield this._stopRemoteAudio({userId:e});else{let s=[...this._room.remotePublishedUserMap.values()];for(let o of s)o.muteState.hasAudio&&!this._remoteAudioConfigMap.has(o.userId)&&(yield this._startRemoteAudio({userId:o.userId}))}else t?yield this._stopRemoteAudio({userId:e}):this._remoteAudioConfigMap.has(e)||(yield this._startRemoteAudio({userId:e}));this._remoteAudioMuteMap.set(e,t)})}setRemoteAudioVolume(e,t){if(e==="*"){let s=[...this._room.remotePublishedUserMap.values()];for(let o of s)this._updateAudioPlayOption({playOption:{volume:t},track:o.remoteAudioTrack})}else if(e){let s=this._room.remotePublishedUserMap.get(e);s&&this._updateAudioPlayOption({playOption:{volume:t},track:s.remoteAudioTrack})}}startPlugin(e,t){return _(this,null,function*(){return e.start(t)})}updatePlugin(e,t){return _(this,null,function*(){return e.update(t)})}stopPlugin(e,t){return _(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:(this._log.debug("on",e),super.on(e,t,s),this._eventListened.add(e),this)}off(e,t,s){return this._log.debug("off",e),e==="*"?(this._eventListened.clear(),this.removeAllListeners()):super.off(e,t,s),this}getAudioTrack(e={userId:"",streamType:"main"}){var o,n;let t,s="main";if(z(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"?((o=this._localScreenAudioTrack)==null?void 0:o.mediaTrack)||null:((n=this._localAudioTrack)==null?void 0:n.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 o=this._room.remotePublishedUserMap.get(t);if(o)return s==="main"?o.remoteVideoTrack.mediaTrack:o.remoteAuxiliaryTrack.mediaTrack}return null}getVideoSnapshot(e={}){let{userId:t,streamType:s="main"}=e;if(t){let o=this._room.remotePublishedUserMap.get(t);if(s==="main"&&(o==null?void 0:o.muteState.hasVideo))return o.remoteVideoTrack.getVideoFrame();if(s==="sub"&&(o==null?void 0:o.muteState.hasAuxiliary))return o.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(o=>o.remoteAudioTrack.setAudioOutput(e))}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return _(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 o=this._room.remotePublishedUserMap.get(t);if(!o)return;let n={};s&&(T(s.volume)||(n.volume=s.volume));let a=o.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:n,track:a})}catch(c){throw this._remoteAudioConfigMap.delete(t),c}this._emitTrackEvent(a)})}_stopRemoteAudio(e,t=!0){return _(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(n){return _(this,arguments,function*({view:e,playOption:t,track:s,prevConfig:o}){if(s.setMirror(t.mirror),T(e)&&o&&o.view&&!Wa(t)){let a=Ms(o.view);a.length>0&&(yield s.play(a,t))}if(!T(e)){let a=Ms(e);a.length>0?yield s.play(a,t):s.stop()}})}_updateAudioPlayOption(o){return _(this,arguments,function*({playOption:e={},track:t,prevConfig:s}){if(!t.isPlayCalled)try{yield t.play(null,e)}catch(n){}T(e.muted)||t.setPlayerMute(e.muted),T(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,!1))}_emitTrackEvent(e,t=!0){let s=e.isRemote?e.userId:"";!e.outMediaTrack||t&&this._mediaTrackMap.get(e.outMediaTrack)===s||(this._mediaTrackMap.set(e.outMediaTrack,s),this.emit($.TRACK,{userId:s,streamType:er(e.streamType),track:e.outMediaTrack}))}_checkTrackToPublish(){var t,s,o;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),(o=this._localScreenConfig)!=null&&o.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:o}){if(T(t))return;let n=this._remoteVideoConfigMap.get(`${e.userId}_${er(e.streamType)}`);if(!n)return;let a=n.observer||void 0;if(t===null||he(t)&&t.length===0||!s){a==null||a.disconnect(),e.isSubscribed||this._room.subscribe(e).catch(()=>{});return}let d=n.visibleViewMap||new Map,u=-1;(!a||a.root!==o)&&(a==null||a.disconnect(),d.clear(),a=new IntersectionObserver(m=>{m.forEach(f=>{d.set(f.target,f.isIntersecting)}),clearTimeout(u),u=window.setTimeout(()=>{[...d.values()].find(R=>R)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:o}));let p=new Set(Ms(t));d.forEach((m,f)=>{p.has(f)||(a.unobserve(f),d.delete(f))}),p.forEach(m=>{d.set(m,!0),a.observe(m)}),a.takeRecords().forEach(m=>{d.set(m.target,m.isIntersecting)}),n.visibleViewMap=d,n.observer=a}_exitRoom(){return _(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=>{me(e.remoteAudioTrack),me(e.remoteVideoTrack),me(e.remoteAuxiliaryTrack)})})}_stopScreenShare(){return _(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),me(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_initActiveSpeaker(){return _(this,null,function*(){if(Le&&!Pr(Le))this.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:Le});else{let e=yield qi();if(e[0]&&!Pr(e[0]))Le=e[0],this.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]});else{let t=({track:s})=>{s.kind==="audio"&&(!Le||Pr(Le))&&(this._initActiveSpeaker(),g.off("102",this._initActiveSpeaker))};g.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 o=t==="main"?s.remoteVideoTrack:s.remoteAuxiliaryTrack;this._room.subscribe(o).then(()=>{this._emitTrackEvent(o)}).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){var o;let s=this._plugins.get("SEI");s&&(s.update({buffer:e,options:P(N({seiPayloadType:243},t),{small:!!((o=this._localVideoTrack)!=null&&o.small)})}),D.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,s;(s=(t=this._room).sendCustomMessage)==null||s.call(t,e),D.addCount({key:500001,useUV:!0})}static setLogLevel(e,t){I.setLogLevel(e),T(t)||(t?I.enableUploadLog():I.disableUploadLog())}static isSupported(){return an()}static getCameraList(e=!0){return Xe(e)}static getMicrophoneList(e=!0){return Be(e)}static getSpeakerList(e=!0){return qi(e)}static setCurrentSpeaker(e){return _(this,null,function*(){(yield qi()).forEach(s=>{s.deviceId===e&&(Yn.forEach(o=>{o.setCurrentSpeaker(e),o.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:s})}),Le=s)})})}static _addKVStat({type:e,key:t,value:s,base:o,useUV:n,version:a}){switch(a&&(Gi.version=a),e){case"count":Gi.addCount({key:t,useUV:n});break;case"enum":Gi.addEnum({key:t,value:s,useUV:n});break;case"number":Gi.addNumber({key:t,value:s,split:o});break}}},X=qr;l(X,"_loggerManager",I),l(X,"EVENT",$),l(X,"ERROR_CODE",w),l(X,"TYPE",st),l(X,"frameWorkType",30),y([oe({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"}})})],X.prototype,"use",1),y([ke(Ce.TRTC.enterRoom),Mi("room",([r],[i])=>(r.roomId||r.strRoomId)===(i.roomId||i.strRoomId)&&r.userId===i.userId&&r.sdkAppId===i.sdkAppId),W(r=>function(i){return this._log.setUserId(i.userId),this._log.setSdkAppId(i.sdkAppId),r.call(this,i)}),oe()],X.prototype,"enterRoom",1),y([oe()],X.prototype,"exitRoom",1),y([ke(Ce.TRTC.switchRole),Zi("room",{merge:(r,i)=>i}),oe()],X.prototype,"switchRole",1),y([oe()],X.prototype,"destroy",1),y([ke(Ce.TRTC.startLocalAudio),Mi("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)}),oe()],X.prototype,"startLocalAudio",1),y([ke(Ce.TRTC.updateLocalAudio),Zi("audio",{debounce:{delay:200,getKey:()=>`${Hu}-localAudio`,isNeedToDebounce:r=>{var i;return!T((i=r.option)==null?void 0:i.captureVolume)}}}),oe()],X.prototype,"updateLocalAudio",1),y([ki("audio"),oe()],X.prototype,"stopLocalAudio",1),y([ke(Ce.TRTC.startLocalVideo),Mi("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)}),oe()],X.prototype,"startLocalVideo",1),y([ke(Ce.TRTC.updateLocalVideo),Zi("video"),oe()],X.prototype,"updateLocalVideo",1),y([ki("video"),oe()],X.prototype,"stopLocalVideo",1),y([ke(Ce.TRTC.startScreenShare),Mi("screen",()=>!0),oe()],X.prototype,"startScreenShare",1),y([ke(Ce.TRTC.updateScreenShare),Zi("screen"),oe()],X.prototype,"updateScreenShare",1),y([oe()],X.prototype,"stopScreenShare",1),y([ke(Ce.TRTC.startRemoteVideo),Mi(r=>`v${r.userId}${r.streamType}`,()=>!0),oe({getRemoteId:r=>`${r.userId}_${r.streamType}`})],X.prototype,"startRemoteVideo",1),y([ke(Ce.TRTC.updateRemoteVideo),Zi(r=>`v${r.userId}${r.streamType}`),oe({getRemoteId:r=>`${r.userId}_${r.streamType}`})],X.prototype,"updateRemoteVideo",1),y([ke(Ce.TRTC.stopRemoteVideo),W(r=>function(i){return _(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)})}),oe({getRemoteId:r=>`${r.userId}_${r.streamType}`})],X.prototype,"stopRemoteVideo",1),y([ki(r=>`v${r.userId}${r.streamType}`)],X.prototype,"_stopRemoteVideo",1),y([ke(...Ce.TRTC.muteRemoteAudio),oe({getRemoteId:r=>r})],X.prototype,"muteRemoteAudio",1),y([ld(...Ce.TRTC.setRemoteAudioVolume),ku(200,r=>r),oe({getRemoteId:r=>r})],X.prototype,"setRemoteAudioVolume",1),y([Xn("start"),gt(r=>{var i;return(i=r.afterStart)==null?void 0:i.call(r)}),Mi((r,i)=>r.disableRandomCall?null:r.getAlias()+r.getGroup(i)),oe({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>nc[r.getName()]})],X.prototype,"startPlugin",1),y([Xn("update"),Zi((r,i)=>r.disableRandomCall?null:r.getAlias()+r.getGroup(i)),oe({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>ac[r.getName()]})],X.prototype,"updatePlugin",1),y([Xn("stop"),ki((r,i)=>{if(r.disableRandomCall)return null;let e=r.getGroup(i),t=r.getAlias();return e==="*"?new RegExp(`${t}.*`):t+e}),oe({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>cc[r.getName()]})],X.prototype,"stopPlugin",1),y([ld(...Ce.TRTC.enableAudioVolumeEvaluation)],X.prototype,"enableAudioVolumeEvaluation",1),y([oe()],X.prototype,"getVideoSnapshot",1),y([oe()],X.prototype,"setCurrentSpeaker",1),y([Mi(r=>`a${r.userId}`,()=>!0)],X.prototype,"_startRemoteAudio",1),y([W(r=>function(i){return _(this,null,function*(){return i.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(e=>this._stopRemoteAudio(P(N({},i),{userId:e.userId})).catch(()=>{}))):r.call(this,i)})}),ki(r=>`a${r.userId}`)],X.prototype,"_stopRemoteAudio",1),y([ki("room")],X.prototype,"_exitRoom",1),y([ki("screen")],X.prototype,"_stopScreenShare",1),y([ke(...Ce.TRTC.sendSEIMessage),ad({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...r)=>r[0].byteLength})],X.prototype,"sendSEIMessage",1),y([ke(Ce.TRTC.sendCustomMessage),ad({timesInSecond:30,maxSizeInSecond:8e3,getSize:r=>r.data.byteLength})],X.prototype,"sendCustomMessage",1),y([ke(Ce.TRTC.create)],X,"_create",1);var so=X;var Td=class{constructor(){this._set=new Set;g.on(E.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 v_(){return _(this,null,function*(){let r,i;try{let p=yield Be();r=p&&p.length}catch(p){}try{let p=yield Xe();i=p&&p.length}catch(p){}let e={microphone:r,camera:i},{isH264EncodeSupported:t,isVp8EncodeSupported:s,isH264DecodeSupported:o,isVp8DecodeSupported:n}=this.checkSystemResult.detail,a=ft.basis(),c={webRTC:a.isWebRTCSupported,getUserMedia:a.isGetUserMediaSupported,webSocket:a.isWebSocketsSupported,screenShare:a.isScreenShareSupported,webAudio:a.isWebAudioSupported,h264Encode:t,h264Decode:o,vp8Encode:s,vp8Decode:n},d={browser:a.browser,os:a.os,trtc:c,devices:e},u={isWebCodecSupported:a.isWebCodecSupported,isMediaSessionSupported:a.isMediaSessionSupported,isWebTransportSupported:a.isWebTransportSupported};Z.uploadEvent({log:`trtcstats-${JSON.stringify(d)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(d)}`),Z.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(u)}`,userId:this.userId})})}function Wu(){return W(r=>{let i=new Td;return function(e,t,s){return _(this,null,function*(){let o=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 b({code:A.INVALID_OPERATION,message:L({key:M.INVALID_JOIN})});if(this.checkDestroy(),i.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this}))throw new b({code:A.INVALID_OPERATION,message:L({key:M.REPEAT_JOIN,data:this.userId})});i.add({room:this,roomId:o}),this.role=e.role===21?"audience":"anchor",this._log.info(`Join() => joining room: ${o} useStringRoomId: ${this.useStringRoomId} scene: ${this.scene} role: ${this.role}`),g.emit(E.JOIN_START,{room:this,roomId:o,params:e}),this.checkSystemResult=yield ft.checkSystemRequirementsInternal(),this.checkDestroy();let n=we.getEnv();n||(n=qt.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(vo.OLD_CLOUD_LADDER)?n=qt.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(vo.WEBRTC)&&(n=qt.WEBRTC))),Z.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),v_.call(this);let{isH264EncodeSupported:a,isVp8EncodeSupported:c}=this.checkSystemResult.detail;if(!ft.isWebRTCSupported()||!a&&!c)throw new b({code:A.NOT_SUPPORTED,message:L({key:M.NOT_SUPPORTED_WEBRTC})});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!we.getEnv()&&(yield this.schedule(e,s));let d=yield r.call(this,e,t,s);return this.roomId=o,this._joinedTimestamp=we.performanceNow(),g.emit(E.JOIN_SUCCESS,{room:this}),s===30&&!e.component&&Z.uploadEvent({log:`stat-conv-${Number(Yt)}-${location.hostname}`,userId:this.userId}),d}catch(d){throw i.delete({room:this,roomId:o}),g.emit(E.JOIN_FAILED,{room:this,error:d}),d}})}})}var Ju=()=>W(r=>function(...i){return _(this,null,function*(){g.emit(E.LEAVE_START,{room:this}),yield r.call(this),g.emit(E.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function ju(){return W(r=>function(...i){let e=r.apply(this,i);return i.forEach(t=>!t.isSubscribed&&t.subscribe(e)),e})}var Xu=Se(Ne());var _e={SETUP_SUCCESS:"1",SETUP_FAILED:"5",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",DISCONNECTED:"5",RECONNECT_FAILED:"4"};var Wt={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},qu=[Wt.UPDATE_REMOTE_MUTE_STAT,Wt.UPLINK_NETWORK_STATS,Wt.USER_LIST_RES,Wt.MUTE_RESULT,Wt.SERVER_FIRST_PACKAGE_RECEIVED],V={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"},j={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 Kn=new Set;function Qu(r){let i=[...Kn.values()].find(e=>e.room.userId===r&&!e.room.isJoined);return i||null}var Xr=class extends Xu.default{constructor(e){var s,o;super();l(this,"room");l(this,"url");l(this,"backupUrl");l(this,"race");l(this,"destroyed",!1);l(this,"_socketInUse");l(this,"_socket");l(this,"_backupSocket");l(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0});l(this,"_currentState","DISCONNECTED");l(this,"_isReconnecting",!1);l(this,"_seq",0);l(this,"_log");l(this,"_lastMessageTime",-1);l(this,"_connnectStartTime",-1);l(this,"_stopConnectRetry");l(this,"bytesSent",0);l(this,"bytesReceived",0);l(this,"keepAlive",!1);l(this,"signalDomainWhenUnifiedProxy");this.room=e.room,this.race=T(e.race)?!0:e.race,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy,(((o=(s=this.room.scheduleResult)==null?void 0:s.config)==null?void 0:o.keepAliveClient)||0)-Kn.size>0&&this.room.enableSPC&&(this.keepAlive=!0,Kn.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=I.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.signalDomainWhenUnifiedProxy&&(e+=`&signalDomain=${encodeURIComponent(this.signalDomainWhenUnifiedProxy)}`),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 _(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=x();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 bs(t),this.unbindAndCloseSocket(this._socketInUse===this._socket?h.BACKUP:h.MAIN),this.emitConnectionStateChanged("CONNECTED")})}connectWS({url:e,timeout:t,isMain:s}){let o=new WebSocket(e);this.bindSocket(o),s?this._socket=o:this._backupSocket=o;let n=-1;return new Promise((a,c)=>{o.onclose=c,o.onerror=c,o.onopen=()=>a(o),t&&(n=setTimeout(()=>{this.unbindAndCloseSocket(s?h.MAIN:h.BACKUP),c(new b({code:A.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))},t))}).finally(()=>{o.onclose=null,o.onerror=null,o.onopen=null,clearTimeout(n)})}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`),this.emitConnectionStateChanged("DISCONNECTED"),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+=Zo(e.data);let t=JSON.parse(e.data),{cmd:s,data:o}=t,n=Object.values(Wt),c=Object.keys(Wt)[n.indexOf(s)],d=V[c]||s;switch(qu.includes(s)||(this._log.debug(`received ${s} msg: ${e.data}`),d&&this._log.info(`Received event: [ ${d} ]`)),s){case Wt.CHANNEL_SETUP_RESULT:{if(t.code===0)this._signalInfo.clientIp=o.clientIp,this._signalInfo.signalIp=o.signalInnerIp,o.svrTime&&zd(o.svrTime),this._log.info("ChannelSetup Success"),D.addSuccessEvent({key:521701,cost:x()-this._connnectStartTime}),this._connnectStartTime=-1,this.emit(_e.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let u=new b({code:A.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:L({key:M.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error(`${t.code}, ${t.message}`),this.close(),D.addFailedEvent({key:521701,error:u}),this.emit(_e.SETUP_FAILED,u)}break}case Wt.JOIN_ROOM_RESULT:{t.code===0&&(this._signalInfo.relayIp=o.relayOuterIp,this._signalInfo.relayInnerIp=o.relayInnerIp,this._signalInfo.relayPort=o.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(String(d),{data:t});break}}reGetSignalChannelUrl(){return _(this,null,function*(){try{if(!this.room.joinParams)return;kt(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(e){}})}reconnect(){return _(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:o,relayPort:n}=this._signalInfo,{data:a}=yield this.sendWaitForResponse({command:j.RECONNECT_WS,data:{roomId:e,useStringRoomId:t,relayInnerIp:o,relayOuterIp:s,relayPort:n},responseCommand:V.CHANNEL_RECONNECT_RESULT});a.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),D.addSuccessEvent({key:521702,cost:x()-this._connnectStartTime}),this._connnectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(D.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},o=JSON.stringify(s);return this._socketInUse.send(o),this.bytesSent+=Zo(o),s.seq}}sendWaitForResponse({command:e,data:t,timeout:s=5e3,responseCommand:o,commandDesc:n,enableLog:a=!0}){return new Promise((c,d)=>{let u=setTimeout(()=>{this.off(o,p);let f=new b({code:A.API_CALL_TIMEOUT,message:L({key:M.API_CALL_TIMEOUT,data:{commandDesc:n,command:e}})});a&&this._log.warn(f),d(f)},s),p=f=>{f.data.seq===m&&(clearTimeout(u),this.off(o,p),c(f))};this.on(o,p);let m=this.send(e,t)})}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:s,retries:o=0,retryTimeout:n=0}=e;return Dt({retryFunction:this.sendWaitForResponse,onError:({retry:a})=>{this.isOnline?a():(this._log.warn(`retry ${s} when connected`),this.once(_e.CONNECTED,a))},onRetrying:a=>{this._log.warn(`${t||s} timeout observed, retrying [${a}/${o}]`)},settings:{retries:o,timeout:n},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),Kn.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(),this.off(V.JOIN_ROOM_RESULT,s)},e*1e3),s=o=>{o.data.code===0&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(t),this.off(V.JOIN_ROOM_RESULT,s))};this.on(V.JOIN_ROOM_RESULT,s)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info(`${this._currentState} -> ${e}`),this.emit(_e.CONNECTION_STATE_CHANGED,{prevState:this._currentState,state:e}),this._currentState=e,e==="CONNECTED"?this.emit(_e.CONNECTED):e==="DISCONNECTED"&&this.emit(_e.DISCONNECTED))}};y([it({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())}})],Xr.prototype,"connect",1);var zu=Se(Ne());var Sd=0,Id=!1,Zn=new Set,O_=r=>Sd>2&&!Id&&Zn.size===0&&r,Ad=!1,Ke=class{constructor(i){l(this,"userId");l(this,"tinyId");l(this,"_sdpSemantics");l(this,"_isUplink");l(this,"_room");l(this,"_log");l(this,"_signalChannel");l(this,"_isErrorObserved",!1);l(this,"_waitForPeerConnectionConnectedPromise");l(this,"_waitForPeerConnectionConnectedPromiseReject",null);l(this,"_peerConnection",null);l(this,"_emitter",new zu.default);l(this,"_currentState","DISCONNECTED");l(this,"_isReconnecting",!1);l(this,"_reconnectionCount",0);l(this,"_reconnectionTimer",-1);l(this,"_isFirstConnection",!0);l(this,"_prevTime",-1);l(this,"_localAddress");l(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=I.createLogger({id:"n-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=i.signalChannel}beforeConnect(){this._prevTime<0&&(this._prevTime=x())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,D.addSuccessEvent({key:521705,cost:Math.min(x()-this._prevTime,30*1e3)})):this._isReconnecting&&D.addSuccessEvent({key:521706,cost:x()-this._prevTime}),this._prevTime=-1}catch(i){throw this._isFirstConnection?(this._isFirstConnection=!1,D.addFailedEvent({key:521705,error:i})):this._isReconnecting&&this._reconnectionCount>=3&&D.addFailedEvent({key:521706,error:i}),i}}initialize(){let i={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(),Zn.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 b({code:A.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return nt;let i=null;if(this._isUplink){if(!bi()||this._peerConnection.getSenders().length===0)return nt;i=this._peerConnection.getSenders()[0].transport}else{if(!Hi()||this._peerConnection.getReceivers().length===0)return nt;i=this._peerConnection.getReceivers()[0].transport}return i?i.state:nt}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}`,o=new b({message:s,code:A.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",o)}(i.target.connectionState===se.CONNECTED||i.target.connectionState===se.COMPLETED)&&(this.logSelectedCandidate(),Z.logSuccessEvent({userId:this._room.userId,eventType:Ve.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(i){return i===this._currentState?!1:(i==="CONNECTED"?(Sd=0,Id=!1,Ad=!0,Zn.add(this)):Zn.delete(this),g.emit(E.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 _(this,null,function*(){if(!this._peerConnection)return;let i=yield this._peerConnection.getStats();for(let[,e]of i)if(yi(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(n),o(),i())},s=({room:a})=>{a===this._room&&(clearTimeout(n),o(),e(new b({code:A.API_CALL_ABORTED,message:L({key:M.CONNECTION_ABORTED,data:"leave room"})})))},o=()=>{g.off(E.LEAVE_SUCCESS,s,this),this._emitter.off("connection-state-changed",t,this)},n=setTimeout(()=>{o();let a=new b({code:A.API_CALL_TIMEOUT,message:"connection timeout"});Sd+=1,O_(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),Id=!0,this._emitter.emit("firewall-restriction")),e(a)},ds);g.on(E.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(_e.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=Xt()){this._log.warn(`SDK has tried reconnect for ${this._reconnectionCount} times, but all failed, please check your network`),this.stopReconnection();let i=new b({code:this._isUplink?A.UPLINK_RECONNECTION_FAILED:A.DOWNLINK_RECONNECTION_FAILED,message:L({key:this._isUplink?M.UPLINK_RECONNECTION_FAILED:M.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(_e.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 bd=Se(yd());var ce=function(r){return bd.default.parse(r)},He=function(r){return bd.default.write(r)},sh=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"})}),He(i)};function oh(r){let i=ce(r);return i.media.forEach(e=>{var t,s;if(e.type===h.VIDEO){let o=new Set;e.rtp.forEach(({payload:a,codec:c})=>c==="H264"&&o.add(a)),e.fmtp.forEach(({payload:a,config:c})=>{let d=c.match(/apt=(\d+)/);d&&d[1]&&o.has(Number(d[1]))&&o.add(a)});let n=({payload:a})=>!o.has(a);e.rtp=e.rtp.filter(n),e.rtcpFb=(t=e.rtcpFb)==null?void 0:t.filter(n),e.fmtp=e.fmtp.filter(n),e.payloads=(s=e.payloads)==null?void 0:s.split(" ").filter(a=>!o.has(Number(a))).join(" ")}}),He(i)}function ea(r){return Object.keys(r).filter(i=>r[i])}var vd=class extends Ke{constructor(e){super(P(N({},e),{isUplink:!1}));l(this,"_flag",0);l(this,"role","anchor");l(this,"remoteAudioTrack");l(this,"remoteVideoTrack");l(this,"remoteAuxiliaryTrack");l(this,"ssrc",{audio:0,video:0,auxiliary:0});l(this,"_isSDPExchanging",!1);this.flag=e.flag,this.remoteAudioTrack=e.remoteAudioTrack||new ai(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new Tt(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new Br(this._room,this)}get videoCodec(){var t,s;let e=(s=(t=this._peerConnection)==null?void 0:t.remoteDescription)==null?void 0:s.sdp;return e?e.includes("H264")?"h264":"vp8":"h264"}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 Ri(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,s,o;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(s=this.remoteVideoTrack)==null||s.onFlagChanged(),(o=this.remoteAuxiliaryTrack)==null||o.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 o,n;let t=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&t!==e&&((o=this.remoteVideoTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),s}onTrack(e){let t=e.streams[0],{track:s}=e,o=t.id===cs?h.MAIN:h.AUXILIARY;this._log.debug(`ontrack ${o} ${s.kind}`);let n=h.AUDIO;s.kind===h.VIDEO&&(n=o===h.MAIN?h.VIDEO:h.AUXILIARY);let a=this.remoteAudioTrack;n===h.VIDEO?a=this.remoteVideoTrack:n===h.AUXILIARY&&(a=this.remoteAuxiliaryTrack),a.setInputMediaStreamTrack(s)}addRRTRLine(e){let t=e.split(`\r