trtc-sdk-v5 5.10.0-wasm.3 → 5.10.0-wasm.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/trtc.esm.js CHANGED
@@ -28,7 +28,7 @@ ${r.stack}`)),this.sendRequest(Yr(this._configs.sdkAppId,Oi.LOG),o)}sendRequest(
28
28
  <path d="m512 960c-247.04 0-448-200.96-448-448s200.96-448 448-448 448 200.96 448 448-200.96 448-448 448zm0-831.71c-211.58 0-383.71 172.13-383.71 383.71 0 211.55 172.13 383.71 383.71 383.71 211.55 0 383.71-172.16 383.71-383.71 0-211.58-172.16-383.71-383.71-383.71z" p-id="2032"/>
29
29
  <path d="m512 673.7c-17.665 0-32.001-14.336-32.001-31.999v-54.112c0-52.353 40-92.352 75.328-127.65 25.887-25.92 52.672-52.672 52.672-74.017 0-53.343-43.072-96.735-95.999-96.735-53.823 0-95.999 41.536-95.999 94.559 0 17.665-14.336 31.999-32.001 31.999s-32.001-14.336-32.001-31.999c0-87.424 71.775-158.56 160-158.56s160 72.095 160 160.74c0 47.904-36.32 84.192-71.424 119.3-27.84 27.776-56.576 56.512-56.576 82.336v54.112c0 17.665-14.336 32.032-32.001 32.032z" p-id="2033"/>
30
30
  </svg>
31
- `,r.onclick=this.onQuestionClick.bind(this);let o=document.createElement("div");o.className=$l,o.innerText=`${fr()?"\u8BE6\u60C5 >":"Detail >"}`,o.onclick=this.onCollapseClick.bind(this);let s=t.content.firstChild,n=s.querySelector(`.${ed}`);return n.appendChild(o),n.appendChild(r),n.appendChild(e),s}addDiaLog(){Wl()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${Ls}`).onclick=t=>t.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",$.info("show autoplay dialog"),Be.uploadEvent({log:P_}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){$.warn("confirm clicked, try resume stream"),H.emit(L.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let t=this._dialogNode.querySelector(`.${Wh}`);t.style.visibility=`${this._showDetail?"hidden":"visible"}`,t.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||Be.uploadEvent({log:k_}),this._isCollapseClicked=!0}onQuestionClick(){window.open(Jh,"_blank"),this._isQuestionClicked||Be.uploadEvent({log:L_}),this._isQuestionClicked=!0}},zh=Bl;var Zt=class extends $r{constructor(e){super(e,D.VIDEO);u(this,"stat",{});u(this,"_calculateTimeout",-1);u(this,"viewMirror",!1);u(this,"objectFit");u(this,"container");u(this,"canvas");u(this,"canvasTrack");this.mode=e.canvas?1:0,this.container=e.container,this.canvas=e.canvas,V(e.viewMirror)||(this.viewMirror=e.viewMirror),V(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}initializeElement(){var r;let e=document.createElement(D.VIDEO);this.track&&this.mode!==2&&(e.srcObject=new MediaStream([this.track])),e.muted=!0,e.setAttribute("id",`video_${this.id}`),e.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),e.setAttribute("autoplay","autoplay"),e.setAttribute("playsinline","playsinline"),this.element=e,(r=this.container)==null||r.appendChild(this.elementToRender),this.bindElementEvents(),this.calculateStat()}get styleAttribute(){let e=`width: 100%; height: 100%; object-fit: ${this.objectFit};background-color: black;`;return this.viewMirror&&(e+="transform: scaleX(-1);"),e}setContainer(e){var r;this.container=e,(this.track||this.canvasTrack)&&this.elementToRender&&((r=this.container)==null||r.appendChild(this.elementToRender))}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),e&&e.add(D.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(D.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent)}handleTrackEvent(e){var r;super.handleTrackEvent(e),e.type===D.MUTE&&((r=this.stat)!=null&&r.fps)&&(this.stat.fps=0)}handleElementEvent(e){var o;if(this.mode===2)return;super.handleElementEvent(e);let r=e.type;if(r===D.PAUSE&&(this.container&&document.getElementById(this.container.id)||this._log.warn(`${this.kind} player has been remove, element ID: ${(o=this.container)==null?void 0:o.id}`),this._pausedRetryCount>0&&!Wl()&&(this._log.info(`${this.kind} player auto resume when paused`),this.resume(),this._pausedRetryCount--),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){let s=this.element.style.transform;r===D.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=s.replace("scaleX(-1)",""):r===D.LEAVE_PICTURE_IN_PICTURE&&!s.includes("scaleX")&&(this.element.style.transform=`${s} scaleX(-1)`)}}setCanvas(e,r=1){var o,s,n,d;this.canvas!==e&&((o=this.canvas)==null||o.remove(),e==null||e.setAttribute("style",this.styleAttribute),this.canvas=e,this.mode=e?r:0,this.mode===2&&this.setTrack(e.captureStream().getVideoTracks()[0]),e?((s=this.element)==null||s.remove(),(n=this.container)==null||n.appendChild(e)):this.element&&((d=this.container)==null||d.appendChild(this.element)))}setAttr(e){let r=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},e);r.style=Object.assign({width:"100%",height:"100%"},r.style),super.setAttr(r)}get mirror(){return this.viewMirror}setRect(e,r){this.elementToRender&&(this.elementToRender.style.width=`${e}px`,this.elementToRender.style.height=`${r}px`)}setViewMirror(e){this.elementToRender&&(this.elementToRender.style.transform=e?"scaleX(-1)":""),this.viewMirror=e}setObjectFit(e){this.elementToRender&&(this.elementToRender.style.objectFit=`${e}`),this.objectFit=e}setPoster(e){this.element&&(this.element.poster=e)}stop(e=0){var r;super.stop(e),(r=this.canvas)==null||r.remove()}play(){return this.element?this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender):this.initializeElement(),this.mode===2?Promise.resolve():super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(Qe.MEDIA_TRACK_CHANGED,e),e!==null&&(this.bindTrackEvents(),this.element&&this.mode!==2&&(this.element.srcObject=new MediaStream([e]),this.element.remove()),this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender)))}getVideoFrame(){if(this.canvas)return this.canvas.toDataURL("image/png");if(!this.element)return"";let e=document.createElement("canvas");return e.width=this.element.videoWidth,e.height=this.element.videoHeight,e.getContext("2d").drawImage(this.element,0,0),e.toDataURL("image/png")}getElement(){return this.element}calculateStat(){try{if(Oo()&&this.element&&this._calculateTimeout<0){let e=0,r=null,o=(s,n)=>{this.stat.width=n.width,this.stat.height=n.height,r&&(this.stat.fps=Math.round((n.presentedFrames-r.presentedFrames)/(s-e)*1e3)),e=s,r=n,this._calculateTimeout=-1,this.element&&(this._calculateTimeout=setTimeout(()=>{var d;return(d=this.element)==null?void 0:d.requestVideoFrameCallback(o)},2e3))};this.element.requestVideoFrameCallback(o)}}catch(e){this._log.warn("init stat failed",e)}}};function Po(i,t){return y(this,null,function*(){if(!i.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield i.audioWorklet.addModule(t),$.info("worklet addModule success")}catch(e){throw $.info(`worklet addModule catch error. ${e.message}`),e}})}var la;typeof AudioContext!="undefined"?la=AudioContext:typeof webkitAudioContext!="undefined"?la=webkitAudioContext:typeof mozAudioContext!="undefined"&&(la=mozAudioContext);var Ir,Xh=-1;Qh();function Qh(){try{if(Ir)return;Ir=new la({sampleRate:48e3}),Ir.onstatechange=()=>{$.info(`context state: ${Ir.state}${Ir.state!=="running"?` visibilityState: ${document.visibilityState}`:""}`),Us()},clearTimeout(Xh)}catch(i){$.error(`initAudioContext failed: ${i} typeof AudioContextClass: ${typeof la}`),Xh=setTimeout(Qh,1e3)}}var Us=()=>{Ir.state==="suspended"?(Vs(),document.addEventListener("click",Us)):Ir.state==="interrupted"?Vs():(document.removeEventListener("visibilitychange",Us),document.removeEventListener("click",Us))},Gl=0,jl=-1;function Vs(){return new Promise((i,t)=>{if(Ir.state==="running")return i();Date.now()-Gl<1e3?(clearTimeout(jl),jl=setTimeout(()=>{Gl=Date.now(),Ir.resume().then(i,t)},1e3)):(clearTimeout(jl),Gl=Date.now(),Ir.resume().then(i,t))}).catch(i=>{$.warn(`context resume failed: ${i}`),document.addEventListener("visibilitychange",Us)})}document.addEventListener("click",Us);var et=i=>Ir;var Pt=class{constructor(){u(this,"node");u(this,"node2");u(this,"pre",new Set);u(this,"next",new Set);u(this,"context");u(this,"connectedNodes",new Set)}setContext(t){this.context=t,this.node&&t.addMixWeight()}removeContext(){var t;this.node&&((t=this.context)==null||t.reduceMixWeight()),delete this.context}replaceNode(t){var e;if(t!==this.node)try{this.node?this._disconnect():(e=this.context)==null||e.addMixWeight(),this.node=t,this.preNodeReconnect(),this.reconnect()}catch(r){$.error(r)}}setNode(t,e){var r;if(!this.node)try{(r=this.context)==null||r.addMixWeight(),this.node=t,e&&(this.node2=e),this.preNodeReconnect(),this.reconnect(),Y.addSuccessEvent({key:502701})}catch(o){$.error(o),Y.addFailedEvent({key:502701,error:o})}}deleteNode(){var t;if(this.node)try{this._disconnect(),delete this.node,delete this.node2,(t=this.context)==null||t.reduceMixWeight(),this.preNodeReconnect(),Y.addSuccessEvent({key:502702})}catch(e){$.error(e),Y.addFailedEvent({key:502702,error:e})}}preNodeReconnect(){this.pre.forEach(t=>{t.node?t.reconnect():t.preNodeReconnect()})}connectNext(t){this.next.forEach(e=>{t._connect(e.node)||e.connectNext(t)})}_connect(t){return!this.node||!t?!1:((this.node2||this.node).connect(t),this.connectedNodes.add(t),!0)}_disconnect(){this.connectedNodes.forEach(t=>{var e;return(e=this.node2||this.node)==null?void 0:e.disconnect(t)}),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(...t){return t.forEach(e=>{this.next.add(e),e.pre.add(this)}),this}},rd=class extends Pt{constructor(e=256){super();this.fftSize=e;u(this,"dataArray",new Uint8Array(0))}setNode(e){e.fftSize=this.fftSize,this.dataArray=new Uint8Array(e.frequencyBinCount),super.setNode(e)}getByteTimeDomainData(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),this.dataArray}get level(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),Math.max(...this.dataArray)/128-1}get timeDomainPathData(){let e=this.getByteTimeDomainData(),r=1,o=0,s=0,n=`M${o},${s}`;for(let d=0;d<e.length;d++)s=e[d]/128*100/2,n+=`L${o},${s}`,o+=r;return n}},ma=class{constructor(){u(this,"source",new Pt);u(this,"gain",new Pt);u(this,"destination",new Pt)}get volume(){var t;return((t=this.gain.node)==null?void 0:t.gain.value)||1}setVolume(t){if(t===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(et().createGain()),this.gain.node.gain.value=t}replaceSource(t){this.source.replaceNode(ql(t))}get track(){var t;return(t=this.stream)==null?void 0:t.getAudioTracks()[0]}get stream(){var t;return(t=this.destination.node)==null?void 0:t.stream}},Fs=class extends ma{constructor(e){super();this.context=e;u(this,"denoiser",new Pt);u(this,"voiceChanger",new Pt);this.source.pipeTo(this.denoiser.pipeTo(this.voiceChanger.pipeTo(this.gain.pipeTo(this.destination))))}connect(){this.context.inputs.has(this)||(this.destination.setNode(this.context.destination),this.source.setContext(this.context),this.denoiser.setContext(this.context),this.voiceChanger.setContext(this.context),this.gain.setContext(this.context),this.context.inputs.add(this))}disconnect(){this.context.inputs.has(this)&&(this.destination.deleteNode(),this.source.removeContext(),this.denoiser.removeContext(),this.voiceChanger.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.denoiser.deleteNode(),this.voiceChanger.deleteNode(),this.source.deleteNode(),this.disconnect()}setVolume(e){if(e===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(this.context.audioContext.createGain()),this.gain.node.gain.value=e}},id=class{constructor(){u(this,"audioContext",et("audio-mixer"));u(this,"destination",this.audioContext.createMediaStreamDestination());u(this,"inputs",new Set);u(this,"mixWeight",0);this.destination.channelCount=1}addMixWeight(t=1){this.mixWeight+=t,this.mixWeight-1===t+1>>1&&this.mixOnChange()}reduceMixWeight(t=1){this.addMixWeight(-t)}close(){this.inputs.forEach(t=>t.remove())}get mixTrack(){return this.destination.stream.getAudioTracks()[0]}},Yh=new WeakMap;function ql(i){let t=Yh.get(i);if(t)return t;let e=et();if(i instanceof HTMLAudioElement)t=e.createMediaElementSource(i);else if(i instanceof MediaStreamTrack)t=e.createMediaStreamSource(new MediaStream([i]));else return i;return Yh.set(i,t),t}var Kt=class Kt{constructor(t){u(this,"_volume",0);u(this,"_volumeDb",0);u(this,"_log");u(this,"_scriptProcessorNode",null);u(this,"_audioWorkletNode",null);u(this,"_interval",200);u(this,"ready",this.preload());let{log:e}=t;this._log=e,H.on(L.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-Kt.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!Kt.workletReady){let t='class VolumeMeterWorklet extends AudioWorkletProcessor{constructor(){super(),this.volume=0,this.intervalTime=200,this.tick=200,this.isStop=!1,this.cache=[],this.sentFirstInfo1=!1,this.unmute=!1,this.port.onmessage=t=>{var e=t.data;switch(e.name){case"chunk":this.cache.push(...e.data),this.sentFirstInfo1||(this.port.postMessage({cl:e.data.length}),this.sentFirstInfo1=!0);break;case"setIntervalTime":this.intervalTime=e.intervalTime;break;case"unmute":this.unmute=!0;break;case"stop":this.isStop=!0}}}process(t,s){t=t[0],s=s[0];if(t||s){if(this.isStop)return!1;var i=s&&s[0]?s[0].length:0,h=this.cache.length,a=(i<h?(s[0].set(this.cache.slice(0,i)),this.cache=this.cache.slice(i)):this.unmute&&s[0].set(t[0]),(i<h?s:t)[0]);if(a){let e=0;for(let t=0;t<a.length;++t)e=Math.max(Math.abs(a[t]),e);s=a.reduce((t,e)=>t+e*e,0)/a.length;this.volume=e,this.tick-=a.length,this.tick<0&&(this.tick+=this.intervalTime/1e3*sampleRate,this.port.postMessage({volume:this.volume,volumeDb:Math.max(10*Math.log10(s)+100,0)/100,cacheLen:h,outputLen:i}))}}return!0}}registerProcessor("volume-meter",VolumeMeterWorklet);';Kt.workletReady=Po(Kt.audioContext,URL.createObjectURL(new Blob([t],{type:"application/javascript"})))}return Kt.workletReady.then(()=>this.initAudioWorklet()).catch(t=>(this._log.error(`volumeMeter preload error: ${t}`),this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(Kt.audioContext,"volume-meter");let t=!1;this._audioWorkletNode.port.onmessage=e=>{Kt.lastMessageTime=Date.now(),this._volume=e.data.volume||0,this._volumeDb=e.data.volumeDb||0,!t&&e.data.cacheLen&&e.data.outputLen&&(this._log.warn("worklet play success"),t=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(t){this._log.error(`volumeMeter init audio worklet error: ${t}`),Be.logFailedEvent({userId:this._log.userId,eventType:Xr.LOAD_WORKLET,error:t}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=et("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=t=>{Kt.lastMessageTime=Date.now();let e=t.inputBuffer.getChannelData(0),r=0;for(let o=0;o<e.length;++o)r+=e[o]*e[o];this._volume=Math.sqrt(r/e.length)||0}}catch(t){this._log.error(`volumeMeter init script processor error: ${t}`)}}destroy(){this._scriptProcessorNode&&(this._scriptProcessorNode.onaudioprocess=null),this._audioWorkletNode&&(this._audioWorkletNode.port.postMessage({name:"stop"}),this._audioWorkletNode.port.onmessage=null),this._audioWorkletNode=null,this._scriptProcessorNode=null,H.off(L.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}getVolumeDb(){return Math.floor(this._volumeDb*100)}handleAudioLevelInterval(t){var r;let{interval:e}=t;this._interval=e,(r=this._audioWorkletNode)==null||r.port.postMessage({name:"setIntervalTime",intervalTime:e})}};u(Kt,"lastMessageTime",0),u(Kt,"audioContext",et("volume-meter")),u(Kt,"workletReady");var od=Kt,sd=class extends Pt{constructor(e){super();u(this,"_volumeMeter");this._volumeMeter=new od(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return y(this,null,function*(){yield this._volumeMeter.preload(),this.setNode(this._volumeMeter.node)})}getCalculatedVolume(){return this._volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this._volumeMeter.getInternalAudioLevel()}getVolumeDb(){return this._volumeMeter.getVolumeDb()}write(e){if(this.node){let r=e.allocationSize({planeIndex:0}),o=new Float32Array(r>>2);e.copyTo(o,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:o},[o.buffer]),e.close()}}},nd=od;var tf=Mi($i(),1);var Kh=i=>t=>t.deviceId===i;var pa=class{constructor(t,e="Input"){u(this,"kind");u(this,"type");u(this,"devices",[]);this.kind=t,this.type=e}update(t,e){let r=t.filter(o=>o.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);if(this.devices.length===1&&$s(this.devices[0])){this.devices=r;return}e&&(r.forEach(o=>{if(o.deviceId&&!this.devices.find(Kh(o.deviceId))){let s=`${this.kind}${this.type}Added`;$.warn(`${s}: ${JSON.stringify(o)}`),e.emit(s,o)}}),this.devices.forEach(o=>{if(o.deviceId&&!r.find(Kh(o.deviceId))){let s=`${this.kind}${this.type}Removed`;$.warn(`${s}: ${JSON.stringify(o)}`),e.emit(s,o)}})),this.devices=r}hasDevice(t){return!!this.devices.find(e=>e.deviceId===t)}},Jl=class extends tf.EventEmitter{constructor(){super();u(this,"audioInputs",new pa(D.AUDIO));u(this,"videoInputs",new pa(D.VIDEO));u(this,"audioOutputs",new pa(D.AUDIO,"Output"));this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||At.run("interval",()=>{this.update()},{delay:1e4}))}init(){ad().then(e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)})}update(){return y(this,arguments,function*(e=0){let r=yield ad(e);return this.audioInputs.update(r,this),this.videoInputs.update(r,this),this.audioOutputs.update(r,this),this})}},Tt=In||us?null:new Jl;function $s(i){return i.deviceId===i.groupId&&i.groupId===""}function ad(){return y(this,arguments,function*(i=0){if(ai()||!Yc())return[];let t=yield navigator.mediaDevices.enumerateDevices();if(i!==0){let e={audio:!1,video:!1};if(t.forEach(r=>{$s(r)&&(r.kind===D.AUDIO_INPUT?e.audio=!0:r.kind===D.VIDEO_INPUT&&(e.video=!0))}),i===2&&(e.audio=!1),i===1&&(e.video=!1),e.audio||e.video){let r;try{r=yield navigator.mediaDevices.getUserMedia(e),e.audio&&Vs()}catch(o){$.debug("capture before getDevices failed: ",o)}t=yield navigator.mediaDevices.enumerateDevices(),r==null||r.getTracks().forEach(o=>o.stop())}}return t.map((e,r)=>{let o={kind:e.kind,deviceId:e.deviceId,groupId:e.groupId,label:e.label||`${e.kind}_${r}`};return e.deviceId.length>0&&zl.add(`${e.deviceId}_${e.kind}`),e.getCapabilities&&(o.getCapabilities=()=>e.getCapabilities()),o})})}function Jt(i=!1){return Tt.update(i?1:0).then(t=>t.audioInputs.devices)}function er(i=!1){return Tt.update(i?2:0).then(t=>t.videoInputs.devices)}var ef=!1;function rf(){return y(this,null,function*(){try{ef||(ef=!0,$.info(`speakers:${(yield Wi()).map(i=>` ${i.deviceId.slice(0,8)}: ${i.label}`)}`))}catch(i){}})}function Wi(i=!1){return y(this,null,function*(){return(lt||Mt)&&(i=!1),Tt.update(i?1:0).then(t=>t.audioOutputs.devices)})}var zl=new Set;function of(i){if(i instanceof CanvasCaptureMediaStreamTrack||!(i instanceof MediaStreamTrack))return!1;let t=i.label.toLocaleLowerCase();if(t.includes("camera")||t.includes("webcam"))return!0;let r=`${((i==null?void 0:i.getSettings())||{}).deviceId}_${D.VIDEO_INPUT}`;return!!zl.has(r)}function sf(i){if(i instanceof CanvasCaptureMediaStreamTrack||!(i instanceof MediaStreamTrack))return!1;let t=i.label.toLocaleLowerCase();if(t.includes("mic")||t.includes("\u9EA6\u514B\u98CE"))return!0;let r=`${((i==null?void 0:i.getSettings())||{}).deviceId}_${D.AUDIO_INPUT}`;return!!zl.has(r)}function Xl(i,t){return y(this,null,function*(){let r=(yield Jt()).find(o=>o.deviceId===Io);return!t&&(r==null?void 0:r.groupId)===i||(r==null?void 0:r.groupId)===i&&r.label===t})}function nf(s){return y(this,arguments,function*({newDeviceId:i,oldDeviceId:t,oldGroupId:e,oldLabel:r,kind:o}){return i!==t?!1:o===D.AUDIO&&i===Io?yield Xl(e,r):!0})}var cd,Ql=class extends ma{constructor(e){super();this.log=e;u(this,"volumeMeter");u(this,"volumeDestination");u(this,"analyser",new rd);this.volumeMeter=new sd({log:this.log}),this.volumeDestination=new Pt,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},dd=class i extends $r{constructor(e){super(e,D.AUDIO);u(this,"_outputDeviceId");u(this,"_volume",1);u(this,"_destination",et("player").createMediaStreamDestination());u(this,"pipeline");u(this,"volumeMeterMode","worklet");this.mode=0,this.pipeline=new Ql(this._log)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(e){if((Fi==="15.2"||Fi==="15.3"||Fi==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}let o=cd||new Audio;o.setAttribute("autoplay","autoplay"),o.srcObject=this.getMediaStream(),o.muted=this.muted,this.element=o,je(e)&&(this.element.volume=Math.min(Math.max(e,0),1)),o===cd&&(cd=void 0),this.bindElementEvents()}play(e){return y(this,null,function*(){if(this.track)return this.pipeline.source.node||this.pipeline.replaceSource(this.track),this.element||this.initializeElement(e==null?void 0:e.volume),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),this.volumeMeterMode==="worklet"?this.pipeline.volumeMeter.init():this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(et("player").createAnalyser()),rf(),Ft(i.prototype,this,"play").call(this)})}stop(e=0){this.pipeline.destroy(),super.stop(e)}setSinkId(e){return y(this,null,function*(){var r,o;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield(o=(r=this.element).setSinkId)==null?void 0:o.call(r,e))})}get useDestination(){return!!this.pipeline.stream}setLoop(e){this.element&&(this.element.loop=e)}getAudioLevel(){return this.pipeline.volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this.pipeline.volumeMeter.getInternalAudioLevel()}},ud=class extends dd{setTrack(t){this.track!==t&&(this.unbindTrackEvents(),this.track=t,this.emit(Qe.MEDIA_TRACK_CHANGED,t),t&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([t]))))}setVolume(t){this._volume=t,this.element&&(this.element.volume=t)}},ld=class extends dd{constructor(e){super(e);u(this,"_sourceElement");u(this,"_output",new Pt);this.pipeline.source.pipeTo(this.pipeline.gain.pipeTo(this.pipeline.volumeMeter.pipeTo(this._output),this.pipeline.destination))}setOutput(){this.mode=1,this._output.setNode(et("player").destination)}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var r,o;((o=(r=this.element)==null?void 0:r.error)==null?void 0:o.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(Qe.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([e]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e])),this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){this._volume=e,this.useDestination?(this.pipeline.setVolume(e),this._log.info(`set pipeline volume: ${e}`)):e<=1?this.element?(this._log.info(`set element volume: ${e}`),this.element.volume=e):this._log.info("set element volume: no element"):lt||(this._log.info(`start set pipeline volume: ${e}`),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),mt(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play()))}stop(e=0){this.pipeline.destroy();let r=this._sourceElement||this.element;r&&Ui&&(cd=r),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}};var ko=class extends ne{constructor({userId:e,sdkAppId:r,mediaType:o,room:s,PlayerClass:n=o===1?ld:Zt}){var d;super();u(this,"id",Xn());u(this,"userId","");u(this,"isRemote");u(this,"mediaType");u(this,"room");u(this,"user");u(this,"_log");u(this,"_inputTrack");u(this,"_outputTrack");u(this,"isPlayCalled");u(this,"container",null);u(this,"player");u(this,"subVideoPlayerMap");u(this,"muted",!1);u(this,"abortCtrl");u(this,"objectFit","cover");u(this,"mirror");u(this,"isScreen",!1);u(this,"manager");u(this,"trackSettings");u(this,"isFirstVideoFrameEmitted",!1);this.userId=e||"",this.mediaType=o,this._log=$.createLogger({id:`${this.kind[0]}t`,userId:(d=s||this.room)==null?void 0:d.userId,remoteUserId:this instanceof di?void 0:this.userId,sdkAppId:r,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof di}),this.player=new n({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log}),this.player.on(Qe.PLAYER_STATE_CHANGED,p=>{H.emit(L.PLAYER_STATE_CHANGED,ee({track:this},p)),this.emit("player-state-changed",p)}),this.kind===D.VIDEO&&(this.player.on(Qe.LOADED_DATA,()=>{this.emitFirstVideoFrameEvent(Qe.LOADED_DATA),H.emit(L.VIDEO_LOADED_DATA,{track:this})}),this.player.on(Qe.LOADED_META_DATA,()=>{this.emitFirstVideoFrameEvent(Qe.LOADED_META_DATA)}),this.player.on(Qe.MEDIA_TRACK_CHANGED,p=>{var m;(m=this.subVideoPlayerMap)==null||m.forEach(g=>g.setTrack(p))})),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(Qe.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||$}get kind(){return this.mediaType===1?D.AUDIO:D.VIDEO}get strMediaType(){return this.mediaType===4?D.VIDEO:this.mediaType===2?D.SCREEN:D.AUDIO}get streamType(){return(this.mediaType&2)===0?"main":"auxiliary"}get isMediaTrackActive(){return this.mediaTrack?!this.mediaTrack.muted&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled:!1}play(e,r){return y(this,null,function*(){let o=st(e)?e[0]:e;if(this.isPlayCalled){this.log.info(`play update options: ${JSON.stringify(r)}`),r&&!V(r.muted)&&this.setPlayerMute(r.muted),r&&!V(r.objectFit)&&(this.objectFit=r.objectFit),this.player instanceof Zt&&(this.player.setObjectFit(this.objectFit),this.container!==o&&o&&(this.container=o,this.player.setContainer(o)),st(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),r)));return}if(r&&!V(r.muted)?this.setPlayerMute(r.muted):(!this.isRemote||this.kind===D.VIDEO)&&this.setPlayerMute(!0),r&&!V(r.objectFit)&&(this.objectFit=r.objectFit),this.player instanceof Zt&&(this.player.setObjectFit(this.objectFit),r&&!V(r.poster)&&this.player.setPoster(r.poster)),this.isPlayCalled=!0,o&&(this.container=o,this.player instanceof Zt&&this.player.setContainer(o)),H.emit(L.PLAY_TRACK_START,{track:this}),!this._outputTrack){this.log.info("play has not mediaTrack, abort");return}this._log.info(`play with options: ${JSON.stringify(r)}`);try{this.player.setTrack(this.playerMediaTrack),yield this.player.play(r),st(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),r))}catch(s){throw this.handleAutoPlayFailed(s),s}})}setMirror(e,r){if(this.isScreen||this.kind!==D.VIDEO||V(e)||e===this.mirror)return;this.mirror=e;let o=this.player;r&&(o=r);let s=this.manager;if(nt(this.mirror)){o.setViewMirror(this.mirror),s&&(s.mirror=!1);return}switch(this.mirror){case"view":{s&&(s.mirror=!1),o.setViewMirror(!0);break}case"publish":{s&&(s.mirror=!0),o.setViewMirror(!0);break}case"both":s&&(s.mirror=!0),o.setViewMirror(!1)}}playSubContainer(e,r){return y(this,null,function*(){if(!this._outputTrack||this.kind===D.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((s,n)=>{var d;e.find(p=>n===p)||(s.stop(),(d=this.subVideoPlayerMap)==null||d.delete(n))});for(let[s,n]of e.entries()){let d=this.subVideoPlayerMap.get(n);d?r&&(V(r.objectFit)||d.setObjectFit(r.objectFit)):this.subVideoPlayerMap.set(n,new Zt({id:this.userId||this.id,track:this.playerMediaTrack,container:n,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:`vp-sub${s+1}`})}))}let o=[...this.subVideoPlayerMap.values()];for(let s of o)s.setViewMirror(this.player.mirror),yield s.play()})}setAudioOutput(e){return this.player.setSinkId(e)}setAudioVolume(e){this.player.setVolume(e)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var e;return((e=this.player)==null?void 0:e.getInternalAudioLevel())||0}stop(e=!1){this.isPlayCalled&&(this.isPlayCalled=!1,this.player&&(this.log.info(`stop ${this.kind} player`),this.player.stop(Gu(this)&&!e?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(r=>{r.stop()}),this.container=null)}resume(){return y(this,null,function*(){var e;this.isPlayCalled&&(yield(e=this.player)==null?void 0:e.resume())})}close(){this.log.info("close"),this.isPlayCalled&&this.stop(!0)}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),H.emit(e?L.TRACK_MUTED:L.TRACK_UNMUTED,{track:this})}setPlayerMute(e){this.player.setMuted(e)}get mediaTrack(){return this._inputTrack||null}get outMediaTrack(){return this._outputTrack||null}get playerMediaTrack(){return this.outMediaTrack}installTrackEvent(e){xt(e,e).add(D.MUTE,this.onTrackMuted).add(D.UNMUTE,this.onTrackUnmuted).add(D.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===D.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){mt(e)}setInputMediaStreamTrack(e){var o;let r=this._inputTrack;if(e!==r)return this._inputTrack=e,this.trackSettings=(o=e.getSettings)==null?void 0:o.call(e),e.enabled=!this.muted,r&&this.uninstallTrackEvent(r),this.installTrackEvent(e),this.emit("input-media-track-changed",e||null,r||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var o;let r=this._outputTrack;e!==r&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",(o=e.getSettings)==null?void 0:o.call(e).deviceId,e.label),this._outputTrack=e,this._inputTrack&&(this._outputTrack.contentHint=this._inputTrack.contentHint,this._outputTrack.enabled=this._inputTrack.enabled),this.updatePlayingState(!!e),this.emit("output-media-track-changed",e))}setMediaType(e){this.mediaType=e}updatePlayingState(e){if(this.isPlayCalled){if(e){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped){this.player.play().catch(r=>this.handleAutoPlayFailed(r)),this.log.info(`playing state updated, play ${this.kind}`);return}}else if(!this.player.isStopped){this.player.stop(Gu(this)?this.jitterBufferDelay:0),this.log.info(`playing state updated, stop ${this.kind}`);return}}this.log.debug(`updatePlayingState abort ${this.isPlayCalled} ${e} ${this.player.isStopped}`)}handleAutoPlayFailed(e){if(this.room&&this.room.enableAutoPlayDialog)new zh;else{let r=()=>{this.resume().then(()=>{document.removeEventListener("click",r,!0)})};document.addEventListener("click",r,!0)}this.emit("error",e)}getVideoFrame(){return this.player instanceof Zt?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(e){var n,d,p;if(this.isFirstVideoFrameEmitted)return;let r=(n=this.mediaTrack)==null?void 0:n.getSettings(),o=(r==null?void 0:r.width)||((d=this.player.element)==null?void 0:d.videoWidth)||0,s=(r==null?void 0:r.height)||((p=this.player.element)==null?void 0:p.videoHeight)||0;e===Qe.LOADED_META_DATA&&!o&&!s||(e===Qe.LOADED_DATA&&!o&&!s&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,this.emit("first-video-frame",{width:o,height:s,streamType:this.streamType,userId:this.isRemote?this.userId:""}))}onTrackMuted(){this._log.warn(`${this.kind} track is unable to provide media output`)}onTrackUnmuted(){this._log.info(`${this.kind} track is able to provide media output`)}onTrackEnded(){this._log.warn(`${this.kind} track ended`)}};X([qe([],ne.INIT,{sync:!0})],ko.prototype,"close",1);var V_=Object.prototype.hasOwnProperty,{toString:xR}=Object.prototype;function F_(i){if(i==null)return!0;if(typeof i=="boolean")return!1;if(typeof i=="number")return i===0;if(typeof i=="string"||typeof i=="function"||Array.isArray(i))return i.length===0;if(i instanceof Error)return i.message==="";if(Gt(i))switch(Object.prototype.toString.call(i)){case"[object File]":case"[object Map]":case"[object Set]":return i.size===0;case"[object Object]":{for(let t in i)if(V_.call(i,t))return!1;return!0}}return!1}var ha=F_;var $_=function(i){return y(this,null,function*(){let t=H_(i);$.info(`getUserMedia with constraints: ${JSON.stringify(t)}`);let e=[],r=[],o=["label","deviceId","groupId"];t.audio&&(e=yield Jt(),$.info(`microphones: ${ir(e.map(s=>Ee(ee({},s),{groupId:s.groupId.substring(0,8)})),{keysToInclude:o})}`)),t.video&&(r=yield er(),$.info(`cameras: ${ir(r,{keysToInclude:o})}`));try{let s=yield navigator.mediaDevices.getUserMedia(t);return Ml&&s.getTracks().forEach(n=>{$.info(`${n.kind} capabilities: ${ir(n.getCapabilities(),{keysToInclude:hc})}`)}),t.audio&&Vs(),s}catch(s){let{message:n}=s;throw s.name==="NotFoundError"&&(i.video&&r&&r.length===0&&(n=dt({key:ct.CAMERA_NOT_FOUND})),i.audio&&e&&e.length===0&&(n=dt({key:ct.MICROPHONE_NOT_FOUND}))),new he({code:te.INITIALIZE_FAILED,name:s.name,message:n,constraint:s.constraint})}})},B_=ki({retryFunction:$_,settings:{retries:3,timeout:500},onError:({error:i,retry:t,reject:e,retryFuncArgs:r,retriedCount:o})=>{let s=o+1;i.name==="NotReadableError"||i.name==="OverconstrainedError"?(s===1?(r[0].video&&(r[0].maxResolution=!1,(!Mt||r[0].width*r[0].height<=1920*1080)&&r[0].frameRate&&(r[0].frameRate=r[0].frameRate>10?10:5)),r[0].retryWhenExactFailed&&r[0].useExactDeviceId&&(r[0].useExactDeviceId=!1)):s===2?r[0].useDeviceIdOnly=!0:s===3&&!r[0].useExactDeviceId&&(r[0].useTrueAsConstraint=!0),t()):e(i),r[0].microphoneId&&af(r[0].microphoneId,!1),r[0].cameraId&&af(r[0].cameraId,!0)},onRetrying:i=>{$.warn(`getUserMedia NotReadableError observed, retrying [${i}/3]`)},onRetryFailed:i=>{Be.logFailedEvent({eventType:Xr.GET_USER_MEDIA_RETRY,error:i})},onRetrySuccess:i=>{Be.logSuccessEvent({eventType:Xr.GET_USER_MEDIA_RETRY}),Be.uploadEvent({log:`stat-${Xr.GET_USER_MEDIA_RETRY}-success-${i}`})}});function af(i,t){return y(this,null,function*(){let r=(t?yield er():yield Jt()).find(o=>o.deviceId===i);r&&Xe(r.getCapabilities)&&$.warn(ir(r.getCapabilities(),{keysToInclude:hc}))})}function H_(i){return{audio:W_(i),video:G_(i)}}function W_(i){if(!i.audio)return!1;if(i.useTrueAsConstraint)return!0;let t={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:i.sampleRate};return!ha(i.microphoneId)&&(t.deviceId=i.useExactDeviceId?{exact:i.microphoneId}:i.microphoneId,i.useDeviceIdOnly)?t:(je(i.channelCount)&&(t.channelCount=i.channelCount),nt(i.echoCancellation)&&!i.echoCancellation&&(t.echoCancellation=!1),nt(i.noiseSuppression)&&!i.noiseSuppression&&(t.noiseSuppression=!1),nt(i.autoGainControl)&&!i.autoGainControl&&(t.autoGainControl=!1),ha(t)?!0:t)}function G_(i){if(!i.video)return!1;if(i.useTrueAsConstraint)return!0;let{maxResolution:t=!0}=i,e={};return i.cameraId?e.deviceId=i.useExactDeviceId?{exact:i.cameraId}:i.cameraId:i.facingMode&&(e.facingMode=i.facingMode),i.useDeviceIdOnly&&!ha(e)?e:(i.width&&(e.width={ideal:i.width},t&&!Qt&&(e.width.max=i.width)),i.height&&(e.height={ideal:i.height},t&&!Qt&&(e.height.max=i.height)),Qt&&_r&&i.width&&i.height&&i.width*i.height<352*288&&(e.width=i.width,e.height=i.height),i.frameRate&&(e.frameRate=i.frameRate),ha(e)?!0:e)}var cf=B_;function Gi(i){return Me((t,e)=>function(...r){return y(this,null,function*(){let o=yield t.apply(this,r);return yield i.call(this,...r),o})})}function df(i){return Me((t,e)=>function(...r){return y(this,null,function*(){try{return yield t.apply(this,r)}catch(o){i.call(this,o)}})})}function Me(i){return function(t,e,r){return r.value=i(r.value,e),r}}var uf=(()=>{let i=!1,t=document.visibilityState;return()=>{document.visibilityState!==t&&$.info(`visibility change: ${document.visibilityState}`),!i&&(document.addEventListener("visibilitychange",()=>{$.info(`visibility change: ${document.visibilityState}`),t=document.visibilityState}),i=!0)}})();var j_=0,md=class{constructor(){u(this,"log",$.createLogger({id:`fq${++j_}`}));u(this,"isRunning",!1);u(this,"queue",[])}get length(){return this.queue.length}get lastQueueItem(){return this.length===0?null:this.queue[this.length-1]}push(t,e=!1){var s,n;let r=ee({},t),o=new Promise((d,p)=>{r.resolve=d,r.reject=p});return r.promise=o,e?this.length<=1?this.queue.push(r):(n=(s=this.lastQueueItem)==null?void 0:s.promise)==null||n.then(r.resolve,r.reject):this.queue.push(r),this.log.debug(`push ${this.length}`),this.isRunning||this.callNext(),o}shift(){let t=this.queue.shift();return this.log.debug(`shift ${this.length}`),t}callNext(){if(this.isRunning||this.length===0)return;this.log.debug("callNext ",this.length);let{fn:t,args:e,context:r,resolve:o,reject:s}=this.queue[0];this.isRunning=!0,t.apply(r,e).then(o,s).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},lf=new WeakMap,mf=new WeakMap;function pf(i=!1){return function(t,e,r){let o=r.value;return r.value=function(...s){let n=lf.get(this)||new md;return lf.set(this,n),n.push({fn:o,args:s,context:this},i)},r}}function pd(i){return function(t,e,r){let o=r.value,s=n=>i(...n);return r.value=function(...n){let d=mf.get(this)||new Map,p=d.get(s(n))||new md;return d.set(s(n),p),mf.set(this,d),p.push({fn:o,args:n,context:this})},r}}function hd(i,t){return Me((e,r)=>function(...o){let s=i;try{let n=e.apply(this,o),d=_e();return xi(n)?n.then(p=>(t?Y.addSuccessEvent({key:s,cost:_e()-d}):Y.addSuccessEvent({key:s}),p)).catch(p=>{throw Y.addFailedEvent({key:s,error:p}),p}):(Y.addSuccessEvent({key:s}),n)}catch(n){throw Y.addFailedEvent({key:s,error:n}),n}})}var Lo=class Lo extends ko{constructor(e,r){super({mediaType:e,PlayerClass:r});u(this,"isRemote",!1);u(this,"deviceId");u(this,"groupId","");u(this,"label","");u(this,"_isRecapturing",!1);u(this,"_lastRecaptureTime",0);u(this,"_onMuteTimeoutId",-1);u(this,"_encodeCheckTimeoutId",-1);u(this,"profile")}get enableEncodeFrame(){return!1}get isPublishing(){return this.state.toString()==="publishing"}get isPublished(){return this.state==="publish"}encodeFrame(e,r){throw new Error("Method not implemented.")}installTrackEvent(e){xt(e,e).add(D.MUTE,this.onTrackMuted).add(D.UNMUTE,this.onTrackUnmuted).add(D.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===D.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){mt(e)}setStateToCapture(){}capture(e){return y(this,null,function*(){var r;try{let o=_e();H.emit(L.LOCAL_TRACK_CAPTURE_START,{track:this});let s;e.customSource?(s=new MediaStream,s.addTrack(e.customSource)):((r=this.mediaTrack)==null||r.stop(),s=yield cf(e));let n=s.getTracks()[0];return yield this.setInputMediaStreamTrack(n),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),H.emit(L.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:_e()-o}),s}catch(o){throw H.emit(L.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:o}),this.log.error(`getUserMedia error observed ${o}`),o}})}setInputMediaStreamTrack(e){return this.state===ne.INIT&&this.setStateToCapture(),super.setInputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var r;if(super.setOutputMediaStreamTrack(e),this.isPublishing||this.isPublished)return(r=this.room)==null?void 0:r.replaceTrack(this)}publish(e,r){return this.room=e,this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),r}unpublish(){this.room&&this.room.localTracks.delete(this),H.emit(L.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return y(this,null,function*(){if(this.mediaTrack&&ks){let{deviceId:e,groupId:r}=this.mediaTrack.getSettings(),{label:o}=this.mediaTrack;(yield nf({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=o,r&&(this.groupId=r),ad().then(n=>{let d=n.find(p=>p.deviceId===e);d&&this.emit("2",d)}))}})}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(e=!1){return!(!this.deviceId||!this.mediaTrack||this.kind===D.AUDIO&&!sf(this.mediaTrack)||this.kind===D.VIDEO&&!of(this.mediaTrack)||this._isRecapturing||e&&_r&&Mt)}onTrackMuted(){if(super.onTrackMuted(),uf(),!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<ps){setTimeout(()=>this.onTrackMuted(),ps);return}this._onMuteTimeoutId=setTimeout(()=>y(this,null,function*(){var e;if((e=this.mediaTrack)!=null&&e.muted){if((lt||at)&&document.visibilityState!=="visible")return;this.recapture(yield this.getRecoverCaptureDeviceId())}}),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return y(this,null,function*(){if(Ft(Lo.prototype,this,"onTrackEnded").call(this),!!this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<ps){setTimeout(()=>this.onTrackEnded(),ps);return}this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e){return y(this,null,function*(){var o;if(this._isRecapturing||!this._inputTrack)return;this.log.warn("recapture trying"),(o=this._inputTrack)==null||o.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let r={useExactDeviceId:!0};if(e==="user"||e==="environment")r.facingMode=e;else{let s;(this.kind==="audio"?yield Jt():yield er()).find(d=>d.deviceId===e)&&(s=e),r.deviceId=s}return this.capture(r).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),H.emit(L.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(s=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${s.message}`),this.emit("5",s),H.emit(L.LOCAL_TRACK_RECAPTURE,{track:this,error:s})})})}getRecoverCaptureDeviceId(){return y(this,null,function*(){let e=this instanceof Sr;if(e&&this.facingMode)return this.facingMode;let{deviceId:r}=this;if(r){let o=(fa.get(r)||0)+1;if(fa.set(r,o),o>=3){let s=e?(yield er()).find(n=>!fa.has(n.deviceId)):(yield Jt()).find(n=>!fa.has(n.deviceId));s&&(this.log.warn(`${r} capture fail ${o} times, change new ${s.deviceId}`),r=s.deviceId)}}return r})}close(){var e;super.close(),this._inputTrack&&(this._inputTrack.stop(),this.uninstallTrackEvent(this._inputTrack)),(e=this.manager)==null||e.removeInput(this)}};X([qe(ne.INIT,"capture",{ignoreError:!0,sync:!0})],Lo.prototype,"setStateToCapture",1),X([pf()],Lo.prototype,"capture",1),X([qe("capture","publish",{ignoreError:!0,success(){var r,o;this.room.localTracks.add(this),H.emit(L.LOCAL_TRACK_PUBLISHED,{track:this}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),!((((o=(r=this.room)==null?void 0:r.networkQuality)==null?void 0:o.uplinkNetworkQuality)||0)>3)&&(this._encodeCheckTimeoutId=setTimeout(()=>{var n,d;if(!((((d=(n=this.room)==null?void 0:n.networkQuality)==null?void 0:d.uplinkNetworkQuality)||0)>3)&&this.isPublished&&this.isMediaTrackActive){let p=this.kind===D.AUDIO,m=this.stat.bytesSent>0;Y[m?"addSuccessEvent":"addFailedEvent"]({key:p?503700:513702}),m||(Y.addEnum({key:p?503701:513703,value:Jn()}),Be.uploadEvent({log:`stat-encode-failed-${this.kind}-${qn()||bo()}`,userId:this.userId}),this.log.warn("encode failed"),this.emit("6",this))}},5e3))},fail(e){let r="error";if(e.cause instanceof RTCError){let o=e.cause;o.message.includes("timeout")?r="timeout":o.code===te.API_CALL_ABORTED&&(r="api-call")}this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:r,error:e.cause||e})}}),hd(521714,!1)],Lo.prototype,"publish",1),X([Me(e=>function(){return y(this,null,function*(){let r=this.state==="publish"?"started":"starting";e.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:r,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)})}),qe([],"capture",{sync:!0})],Lo.prototype,"unpublish",1);var di=Lo,fa=new Map;H.on(L.SWITCH_DEVICE_SUCCESS,i=>{i.track.deviceId&&fa.delete(i.track.deviceId)});var ui=class i extends di{constructor(e){super(1,ud);u(this,"mediaType",1);u(this,"volume",0);u(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40});u(this,"playerMuted",!0);u(this,"pipeline");u(this,"earMonitorGainNode",new Pt);u(this,"_output",new Pt);u(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0});this.manager=e,this.pipeline=new Fs(e),this.pipeline.gain.pipeTo(this.earMonitorGainNode.pipeTo(this._output),this.player.pipeline.volumeMeter),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this)}get dbVolume(){return nd.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}setInputMediaStreamTrack(e){return y(this,null,function*(){let r=this.trackSettings||{};Y.addEnum({key:501701,value:r.channelCount||0,useUV:!1}),Y.addEnum({key:501702,value:r.sampleRate||0,useUV:!1}),Y.addEnum({key:502700,value:0});let{sampleRate:o,channelCount:s}=r;this._log.info(`local audio track input ${JSON.stringify({sampleRate:o,channelCount:s})}`),this.pipeline.replaceSource(e),yield Ft(i.prototype,this,"setInputMediaStreamTrack").call(this,e),this.updatePlayingState(!!e)})}capture({deviceId:e,customSource:r,useExactDeviceId:o=!0,retryWhenExactFailed:s=!0}){return super.capture({video:!1,audio:!0,microphoneId:e,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:o,retryWhenExactFailed:s,customSource:r})}switchDevice(e){return y(this,null,function*(){if(this.mediaTrack){if(this.deviceId===e)if(e===Io){if(yield Xl(this.groupId,this.label))return}else return;try{this.log.info(`switchDevice audio to: ${e}`),this.mediaTrack&&this.mediaTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0,retryWhenExactFailed:!1}),H.emit(L.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(r){throw this.log.error(`switch microphone failed ${r}`),this.deviceId&&this.recapture(this.deviceId),r}}})}listenDeviceChange(){Tt&&!Tt.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&Tt.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return y(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current microphone is lost: ${JSON.stringify(e)}`),tt(this.userId,{eventId:2003,param1:6,streamType:1});let r=yield Jt();r[0]?this.recapture(r[0].deviceId):Tt.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.log.warn(`microphone added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)}update3A(s){return y(this,arguments,function*({echoCancellation:e,noiseSuppression:r,autoGainControl:o}){let n=!1;!V(e)&&e!==this.profile.echoCancellation&&(this.profile.echoCancellation=e,n=!0),!V(r)&&r!==this.profile.noiseSuppression&&(this.profile.noiseSuppression=r,n=!0),!V(o)&&o!==this.profile.autoGainControl&&(this.profile.autoGainControl=o,n=!0),n&&this.deviceId&&(yield this.recapture(this.deviceId))})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&Y.addEnum({key:502700,value:2})}setAudioVolume(e){super.setAudioVolume(0),lt&&this.player.setMuted(!0),this.earMonitorGainNode.node||(this.earMonitorGainNode.setNode(et().createGain()),this._output.setNode(et().destination)),this.earMonitorGainNode.node.gain.value=e}enableTrackANS(e){if(!this._inputTrack)return;let r=this._inputTrack.getConstraints();return r.noiseSuppression=e,this._inputTrack.applyConstraints(r).catch(o=>this._log.warn(`${e?"enable":"disable"} ANS failed `,o))}addDenoiser(e){var r;if(ei<=92&&((r=this.trackSettings)==null?void 0:r.sampleRate)!==48e3){this._log.warn("denoiser only support sampleRate 48000 before chrome 93");return}Y.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.enableTrackANS(!1)}removeDenoiser(e){this.pipeline.denoiser.node===e&&(this.pipeline.denoiser.deleteNode(),this.enableTrackANS(!0))}close(){this.pipeline.remove(),this.earMonitorGainNode.deleteNode(),this._output.deleteNode(),Tt.off("audioInputAdded",this.handleMicrophoneAdded,this),Tt.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}recapture(e){return y(this,null,function*(){try{yield Ft(i.prototype,this,"recapture").call(this,e)}catch(r){let o=(yield Jt()).find(s=>s.deviceId!==e);if(o)yield Ft(i.prototype,this,"recapture").call(this,o.deviceId);else throw r}})}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduceRight((r,o)=>o?o({frame:r}):r,e):e}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}};var Uo=class{constructor(t,e=!1){this.dataView=t;this.isSEI&&(e?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let t=this.seiPayloadStartIndex,e=this.dataView.byteLength-2,r=[],o=0;for(let n=t;n<=e;n++){let d=this.dataView.getInt8(n);switch(d){case 0:case 1:case 2:case 3:o===2&&(r.push(3),o=0),d==0?o++:o=0,r.push(d);break;default:o=0,r.push(d);break}}r.push(this.dataView.getInt8(this.dataView.byteLength-1));let s=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,t),...r]).buffer);this.dataView=s}removePreventionByte(){let t=this.seiPayloadStartIndex,e=this.dataView.byteLength-1,r=[],o=0;for(let n=t;n<=e;n++)switch(this.dataView.getInt8(n)){case 0:o++,r.push(this.dataView.getInt8(n));break;case 3:o!==2&&r.push(this.dataView.getInt8(n)),o=0;break;default:r.push(this.dataView.getInt8(n)),o=0;break}let s=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,t),...r]).buffer);this.dataView=s}get isSEI(){return this.dataView.getUint8(4)===6}get seiPayloadStartIndex(){let t=6;for(let e=6;e<this.dataView.buffer.byteLength&&(t++,this.dataView.getUint8(e)===255);e++);return t}get seiPayloadType(){return this.isSEI?this.dataView.getUint8(5):null}get seiPayload(){if(!this.isSEI)return null;let t=0,e=6;for(let s=6;s<this.dataView.buffer.byteLength;s++){let n=this.dataView.getUint8(s);if(e++,n===255)t+=255;else{t+=n;break}}let r=new ArrayBuffer(t),o=new DataView(r);for(let s=0;s<r.byteLength;s++,e++)o.setInt8(s,this.dataView.getInt8(e));return o}};var fd=class{constructor(){u(this,"_seiMessageList",[]);u(this,"_smallSeiMessageList",[]);u(this,"_seiPayloadType",243)}encodeSEINalu(t){let e=t.byteLength,r=parseInt(String(e/255),10),o=e%255,s=[];s.push(0,0,0,1,6,this._seiPayloadType);for(let d=0;d<r;d++)s.push(255);s.push(o);let n=new DataView(t);return s.push(...new Uint8Array(n.buffer)),s.push(128),new Uo(new DataView(new Uint8Array(s).buffer),!0)}sendSEI(t,e){e!=null&&e.seiPayloadType&&(this._seiPayloadType=e.seiPayloadType),this._seiMessageList.push(t),e!=null&&e.small&&this._smallSeiMessageList.push(t)}isEmpty(){return!this._seiMessageList.length}getNaluCount(t){let e=0,r=0,o=new DataView(t);for(let s=0;s<t.byteLength;s++)switch(o.getUint8(s)){case 0:e++;break;case 1:(e===2||e===3)&&r++,e=0;break;default:e=0;break}return r}encode(t,e){let r=e?this._smallSeiMessageList:this._seiMessageList;if(r.length>0&&t.data.byteLength>0){let s=9-this.getNaluCount(t.data);if(s<=0)return 0;let n=r.splice(0,s).reverse().map(this.encodeSEINalu.bind(this)),d=n.reduce((b,N)=>b+N.dataView.byteLength,0),p=new ArrayBuffer(d+t.data.byteLength),m=new DataView(p),g=new DataView(t.data),_=0;for(let b=0;b<n.length;b++)for(let N=0;N<n[b].dataView.byteLength;N++)m.setInt8(_++,n[b].dataView.getInt8(N));for(let b=0;b<t.data.byteLength;b++)m.setInt8(_++,g.getInt8(b));return t.data=p,n.length}return 0}};var Vo=class Vo extends di{constructor(e,r=4){super(r,Zt);u(this,"profile",{width:640,height:480,frameRate:15,bitrate:500});u(this,"avoidCrop",!1);u(this,"_scaleResolutionDownBy");u(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0});u(this,"small");u(this,"isNeedToSetBandwidth");u(this,"muteImage");u(this,"manager");u(this,"_seiCodec",new fd);this.manager=e;let o=()=>{this.isAllowed2k4k(this.profile)?this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1}):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),this.setProfile(Ee(ee({},this.profile),{width:1920,height:1080})),this.applyProfile())};this.on("input-media-track-changed",o),this.on("publish",o),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(!(!ks||!this.mediaTrack))return this.mediaTrack.getSettings().facingMode}get isQosClearFirst(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)==="detail"}setMute(e){return y(this,null,function*(){var r,o,s;if(we(e)){if(this.muteImage===e)return;yield(r=this.manager)==null?void 0:r.deleteWatermark("mute"),yield(o=this.manager)==null?void 0:o.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:e}),this.muteImage=e,Ft(Vo.prototype,this,"setMute").call(this,!1)}else yield(s=this.manager)==null?void 0:s.deleteWatermark("mute"),this.muteImage=void 0,Ft(Vo.prototype,this,"setMute").call(this,e)})}capture({deviceId:e,facingMode:r,useExactDeviceId:o=!0,customSource:s,retryWhenExactFailed:n=!0}){return super.capture({audio:!1,video:!0,facingMode:r||this.facingMode,cameraId:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:o,retryWhenExactFailed:n,customSource:s})}setProfile(e){let r=ee({},e),o=r.width>r.height;r.width*r.height<=160*120&&at&&Kr&&(this.log.warn(`resolution is ${r.width}*${r.height}, fallback to 240*180`),r.width=o?240:180,r.height=o?180:240,r.bitrate=Math.max(r.bitrate,150)),r.width*r.height>1280*720&&il&&(r.width=o?1280:720,r.height=o?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),this.avoidCrop&&(Kr||Qt)&&!ol()&&r.width*r.height<=640*360&&r.width/r.height===16/9&&(this._scaleResolutionDownBy=1280/r.width,r.width=1280,r.height=720,this.log.warn(`capture 720p, scale: ${this._scaleResolutionDownBy}`)),r.bitrate&&(this.isNeedToSetBandwidth=r.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile)?super.setProfile(r):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),super.setProfile(Ee(ee({},this.profile),{width:1920,height:1080})))}applyProfile(){return y(this,null,function*(){var o;if(!this.mediaTrack)return;let e=this.settings;if(!(!(e.height!==this.profile.height||e.width!==this.profile.width||e.frameRate!==this.profile.frameRate)||!this.deviceId)&&(Yt===16?yield this.recapture(this.deviceId):(yield(o=this.mediaTrack)==null?void 0:o.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}),this.manager&&this.manager.changeInput(this)),this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1}),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth))return this.isNeedToSetBandwidth=!1,this.room.setBandWidth({bandwidth:this.profile.bitrate,type:D.VIDEO,videoType:D.BIG})})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate};return ks&&this.mediaTrack&&Object.assign(e,this.mediaTrack.getSettings()),e}get scaleResolutionDownBy(){if(this._scaleResolutionDownBy)return this._scaleResolutionDownBy;let{settings:e}=this;return e.width===this.profile.width&&e.height===this.profile.height?1:_c()&&this.profile.width>this.profile.height&&e.height>e.width?Math.max(e.width/this.profile.height,e.height/this.profile.width,1):Math.max(e.width/this.profile.width,e.height/this.profile.height,1)}isAllowed2k4k(e){var r;return!this.room||!this.room.scheduleResult||this.isScreen||e.height*e.width<2560*1440?!0:((r=this.room.scheduleResult.trtcAutoConf)==null?void 0:r["2k4k"])===1}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}switchDevice(e){return y(this,null,function*(){try{if(!this.isNeedToSwitchDevice(e))return;let r={useExactDeviceId:!0,retryWhenExactFailed:!1};e==="user"||e==="environment"?r.facingMode=e:r.deviceId=e,this.mediaTrack.stop(),yield this.capture(r),H.emit(L.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(r){throw this.log.error(`switch camera failed ${r}`),this.deviceId&&this.recapture(this.deviceId),r}})}listenDeviceChange(){Tt&&!Tt.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&Tt.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return y(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current camera is lost: ${JSON.stringify(e)}`),tt(this.userId,{eventId:2003,param1:7,streamType:2});let r=yield er();r[0]?this.recapture(r[0].deviceId):Tt.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return y(this,null,function*(){this.log.warn(`camera added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)})}encodeFrame(e,r){if(!this.manager)return e;let o=r?8:this.mediaType;return this.manager.encodePipeline.reduceRight((s,n)=>n?n({frame:s,mediaType:o}):s,e)}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}play(e,r){return V(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,r)}close(){Tt.off("videoInputAdded",this.handleCameraAdded,this),Tt.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return y(this,null,function*(){try{yield Ft(Vo.prototype,this,"recapture").call(this,e)}catch(r){let o=(yield er()).find(s=>s.deviceId!==e);if(o)yield Ft(Vo.prototype,this,"recapture").call(this,o.deviceId);else throw r}})}setContentHint(e){this.mediaTrack&&"contentHint"in this.mediaTrack&&(this.mediaTrack.contentHint!==e&&(this.log.info(`setContentHint ${e}`),this.mediaTrack.contentHint=e),this.outMediaTrack&&this.outMediaTrack.contentHint!==e&&(this.outMediaTrack.contentHint=e))}};X([Gi(function(e){this.setContentHint(e.contentHint||"motion")})],Vo.prototype,"capture",1);var Sr=Vo;var gf=Xn();if(typeof navigator!="undefined"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:gf,exposeOrigin:!0,permittedOrigins:["*"]})}catch(i){}var z_=function(i){return y(this,null,function*(){let t=null,e=Y_(i);$.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let r=yield navigator.mediaDevices.getDisplayMedia(e);i.systemAudio&&r.getAudioTracks().length===0&&(Ds&&ei<74||Mt||Qt)&&$.warn("Your browser not support capture system audio");let o=r.getVideoTracks()[0];if(o){if(i.frameRate)try{yield o.applyConstraints({frameRate:{min:i.frameRate,ideal:i.frameRate},width:i.width,height:i.height})}catch(s){$.warn(`screen applyConstraints failed: ${s}`)}i.captureElement&&(yield X_(o,i.captureElement))}if(i.audio){let s=Q_(i);$.info(`getUserMedia with constraints: ${JSON.stringify(s)}`),t=yield navigator.mediaDevices.getUserMedia(s),r.addTrack(t.getAudioTracks()[0])}return r})};function X_(i,t){return y(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&Xe(i.cropTo))try{if(!(((e=i.getCaptureHandle())==null?void 0:e.handle)===gf))return;let o=yield CropTarget.fromElement(t);yield i.cropTo(o)}catch(r){$.warn(`cropTo target failed ${r}`)}})}function Q_(i){let t={echoCancellation:i.echoCancellation,autoGainControl:i.autoGainControl,noiseSuppression:i.noiseSuppression,sampleRate:i.sampleRate,channelCount:i.channelCount};return V(i.microphoneId)||(t.deviceId=i.microphoneId),{audio:t,video:!1}}function Y_(i){let t={preferCurrentTab:i.preferDisplaySurface==="current-tab"||!!i.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:Mt?{max:i.width}:{ideal:i.width,max:i.width},height:Mt?{max:i.height}:{ideal:i.height,max:i.height},frameRate:i.frameRate,displaySurface:i.preferDisplaySurface||"monitor"};if(t.video=e,i.systemAudio){let{echoCancellation:r=!0,noiseSuppression:o=!1,autoGainControl:s=!1}=i;t.audio={echoCancellation:r,noiseSuppression:o,autoGainControl:s,sampleRate:48e3}}return t}var Ef=z_;var ji=class extends Sr{constructor(e){super(e,2);u(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600});u(this,"objectFit","contain");u(this,"isScreen",!0);this._log.id=`s-${this._log.id}`}capture(g){return y(this,arguments,function*({systemAudio:e=!1,autoGainControl:r,echoCancellation:o,noiseSuppression:s,audioTrack:n,videoTrack:d,captureElement:p,preferDisplaySurface:m}){try{let _;return d||n?(_=new MediaStream,d&&_.addTrack(d),n&&_.addTrack(n)):_=yield Ef({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:r,echoCancellation:o,noiseSuppression:s,captureElement:p,preferDisplaySurface:m}),yield this.setInputMediaStreamTrack(_.getVideoTracks()[0]),_}catch(_){throw this.log.error(`getDisplayMedia error observed ${_}`),_ instanceof he?_:new he({code:te.INITIALIZE_FAILED,name:_.name,message:_.message})}})}switchDevice(e){return y(this,null,function*(){throw new Error("Method not implemented.")})}};X([Gi(function(e){this.setContentHint(e.contentHint||"detail")})],ji.prototype,"capture",1);var Fo=class extends ui{constructor(t){super(t),this._log.id=`s-${this._log.id}`}};var Z_="registerProcessor('dumper', class extends AudioWorkletProcessor {process(inputs) {this.port.postMessage(inputs);return true;}});",Zl;function ga(i){return y(this,null,function*(){let t=et("dump");Zl||(Zl=Po(t,URL.createObjectURL(new Blob([Z_],{type:"application/javascript"})))),yield Zl;let e=new AudioWorkletNode(t,"dumper",{numberOfInputs:i.length,numberOfOutputs:0});return i.forEach((r,o)=>r.connect(e,0,o)),new ReadableStream({start(r){e.port.onmessage=o=>{r.enqueue(o.data)}},cancel(){i.forEach(r=>r.disconnect(e)),e.port.close()}})})}var gd=class extends id{constructor(e){super();this.room=e;u(this,"_localAudioTrack");u(this,"_localScreenAudioTrack");u(this,"log",$.createLogger({id:"am"}));u(this,"denoiser");u(this,"voiceChanger");u(this,"mixChangedDebounce");u(this,"encodePipeline",[]);u(this,"decodePipeline",[]);e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId))}get _localAudioPipline(){var e;return(e=this._localAudioTrack)==null?void 0:e.pipeline}dump(e){var g,_;if(!this._localAudioTrack)return;let r=[],o=[];(g=this._localAudioPipline)!=null&&g.source.node&&(r.push(this._localAudioPipline.source.node),o.push("mic")),(_=this._localAudioPipline)!=null&&_.denoiser.node&&(r.push(this._localAudioPipline.denoiser.node),o.push("mic-processed")),this.mixWeight>1&&(r.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),o.push("mix")),this.log.info(`dump audio track ${o}, duration: ${e}`);let s=new AbortController,n=[],d=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),s.abort("timeout")},e*1e3),p=()=>{for(let b=0;b<o.length;b++){let N=URL.createObjectURL(new Blob(n[b])),k=document.createElement("a");k.href=N,k.download=`${o[b]}.pcm`,k.style.display="none",document.body.appendChild(k),k.click(),URL.revokeObjectURL(N),k.remove()}clearTimeout(d),s.abort("download")},m=ga(r).then(b=>b.pipeTo(new WritableStream({write(N){N.forEach((k,P)=>n[P]=n[P]?n[P].concat(k[0]):[k[0]])}}),s).catch(N=>p));return{then:m.then.bind(m),download:p}}getPCM(e){var n;if(V(WritableStream)){this.log.warn("getPCM failed: browser not support WritableStream");return}if(!((n=this._localAudioPipline)!=null&&n.source.node)){this.log.warn("getPCM failed: no local audio track");return}this.log.warn("getPCM");let r=new Float32Array(1920),o=0,s=new AbortController;return ga([this._localAudioPipline.source.node]).then(d=>d.pipeTo(new WritableStream({write(p){p[0][0]&&(r.set(p[0][0],o),o+=p[0][0].length,o>=1920&&(o=0,e(r),r=new Float32Array(1920)))}}),s).catch(p=>this.log.warn(`stop getPCM reason:${p}`))),s}get hasScreenAudioTrack(){return this._localScreenAudioTrack!==null}get hasAudioTrack(){return!V(this._localAudioTrack)}changeInput(e){if(e instanceof Fo)return this._localScreenAudioTrack=e,e.pipeline.connect(),this.mixOnChange();if(e instanceof ui)return this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),e.pipeline.connect(),this.mixOnChange();if(e instanceof $o)return e.setOutputMediaStreamTrack(e.mediaTrack)}mixOnChange(){return this.mixChangedDebounce||(this.mixChangedDebounce=Promise.resolve().then(()=>{var e,r;return delete this.mixChangedDebounce,Promise.all([(e=this._localAudioTrack)==null?void 0:e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),(r=this._localScreenAudioTrack)==null?void 0:r.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)])})),this.mixChangedDebounce}removeInput(e){e instanceof Fo?delete this._localScreenAudioTrack:e instanceof ui?delete this._localAudioTrack:e instanceof $o}addDenoiser(e){var r;this.denoiser=e,(r=this._localAudioTrack)==null||r.addDenoiser(e)}removeDenoiser(e){var r;delete this.denoiser,(r=this._localAudioTrack)==null||r.removeDenoiser(e)}addVoiceChanger(e,r){var o;this.voiceChanger=[e,r],(o=this._localAudioTrack)==null||o.pipeline.voiceChanger.setNode(e,r)}removeVoiceChanger(){var e;delete this.voiceChanger,(e=this._localAudioTrack)==null||e.pipeline.voiceChanger.deleteNode()}destroy(){this.close()}addEncodeProcessor({processor:e,type:r}){var o;this.encodePipeline.includes(e)||(this.encodePipeline[r]=e,(o=this.room)==null||o.enableInsertableStreams())}addDecodeProcessor({processor:e,type:r}){var o;this.decodePipeline.includes(e)||(this.decodePipeline[r]=e,(o=this.room)==null||o.enableInsertableStreams())}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}};function _f(i=30,t=2){return Me((e,r)=>function(...o){return new Promise((s,n)=>{let d=setTimeout(()=>{let p=new he({code:te.API_CALL_TIMEOUT,message:`checkPendingPromise ${r}() timeout ${i}s`});$.warn(p),t===2?n(p):t===1&&s()},i*1e3);e.apply(this,o).then(s,n).finally(()=>{clearTimeout(d)})})})}var Um={};Jr(Um,{Events:()=>it,Inspect:()=>or,LastSink:()=>Bo,Sink:()=>de,Subscribe:()=>Ho,TimeoutError:()=>Ea,audit:()=>xT,bindCallback:()=>_T,bindNodeCallback:()=>TT,buffer:()=>aT,bufferCount:()=>nT,bufferTime:()=>ZT,call:()=>Tf,catchError:()=>xm,combineLatest:()=>Sf,concat:()=>tT,concatMap:()=>GT,concatMapTo:()=>jT,count:()=>yT,create:()=>Oe,debounce:()=>PT,debounceTime:()=>kT,defer:()=>yf,delay:()=>KT,deliver:()=>pe,dispose:()=>Ed,elementAt:()=>LT,empty:()=>Ia,every:()=>BT,exhaustMap:()=>zT,exhaustMapTo:()=>XT,filter:()=>yr,find:()=>UT,findIndex:()=>VT,first:()=>FT,fromAnimationFrame:()=>gT,fromArray:()=>uT,fromEvent:()=>be,fromEventPattern:()=>lT,fromFetch:()=>mT,fromIterable:()=>pT,fromPromise:()=>Rf,fromReadableStream:()=>fT,fromReader:()=>hT,groupBy:()=>QT,identity:()=>K_,ignoreElements:()=>vT,iif:()=>iT,inspect:()=>If,interval:()=>sm,last:()=>$T,map:()=>Ji,mapTo:()=>WT,max:()=>AT,merge:()=>im,mergeMap:()=>qT,mergeMapTo:()=>JT,min:()=>bT,never:()=>IT,nothing:()=>Ve,of:()=>dT,pairwise:()=>HT,pipe:()=>Se,race:()=>om,range:()=>ET,reduce:()=>nm,retry:()=>rI,scan:()=>Om,share:()=>li,shareReplay:()=>rT,skip:()=>DT,skipUntil:()=>NT,skipWhile:()=>yd,startWith:()=>_a,subject:()=>It,subscribe:()=>ke,sum:()=>RT,switchMap:()=>zi,switchMapTo:()=>mi,take:()=>Ar,takeLast:()=>CT,takeUntil:()=>Je,takeWhile:()=>vf,tap:()=>Sa,throttle:()=>MT,throwError:()=>ST,timeInterval:()=>YT,timeout:()=>Lm,timer:()=>Ta,toPromise:()=>eI,toReadableStream:()=>tI,withLatestFrom:()=>sT,zip:()=>oT});function Ve(...i){}var Tf=i=>i(),K_=i=>i;function Ed(){this.dispose()}var If=()=>typeof __FASTRX_DEVTOOLS__!="undefined",eT=1,or=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(t){let e=new Kl(t,this,this.streamId++);return it.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},Bo=class{constructor(){this.defers=new Set,this.disposed=!1}next(t){}complete(){this.dispose()}error(t){this.dispose()}get bindDispose(){return()=>this.dispose()}dispose(){this.disposed=!0,this.complete=Ve,this.error=Ve,this.next=Ve,this.dispose=Ve,this.subscribe=Ve,this.doDefer()}subscribe(t){return t instanceof or?t.subscribe(this):t(this),this}get bindSubscribe(){return t=>this.subscribe(t)}doDefer(){this.defers.forEach(Tf),this.defers.clear()}defer(t){this.defers.add(t)}removeDefer(t){this.defers.delete(t)}reset(){this.disposed=!1,delete this.complete,delete this.next,delete this.dispose,delete this.next,delete this.subscribe}resetNext(){delete this.next}resetComplete(){delete this.complete}resetError(){delete this.error}},de=class extends Bo{constructor(t){super(),this.sink=t,t.defer(this.bindDispose)}next(t){this.sink.next(t)}complete(){this.sink.complete()}error(t){this.sink.error(t)}},Ho=class extends Bo{constructor(t,e=Ve,r=Ve,o=Ve){if(super(),this._next=e,this._error=r,this._complete=o,this.then=Ve,t instanceof or){let s={toString:()=>"subscribe",id:0,source:t};this.defer(()=>{it.defer(s,0)}),it.create(s),it.pipe(s),this.sourceId=s.id,this.subscribe(t),it.subscribe({id:s.id,end:!0}),e==Ve?this._next=n=>it.next(s,0,n):this.next=n=>{it.next(s,0,n),e(n)},o==Ve?this._complete=()=>it.complete(s,0):this.complete=()=>{this.dispose(),it.complete(s,0),o()},r==Ve?this._error=n=>it.complete(s,0,n):this.error=n=>{this.dispose(),it.complete(s,0,n),r()}}else this.subscribe(t)}next(t){this._next(t)}complete(){this.dispose(),this._complete()}error(t){this.dispose(),this._error(t)}};function Se(i,...t){return t.reduce((e,r)=>r(e),i)}function Oe(i,t,e){if(If()){let r=Object.defineProperties(Object.setPrototypeOf(i,or.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:t,writable:!0,configurable:!0},args:{value:e,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});it.create(r);for(let o=0;o<e.length;o++){let s=e[o];typeof s=="function"&&s instanceof or&&it.addSource(r,s)}return r}return i}function pe(i,t){return function(...e){return r=>{if(r instanceof or){let o=Oe(s=>{let n=new i(s,...e);n.sourceId=o.id,n.subscribe(r)},t,arguments);return o.source=r,it.pipe(o),o}else return o=>r(new i(o,...e))}}}function qi(i,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:i,payload:t}})}var Kl=class extends de{constructor(t,e,r){super(t),this.source=e,this.id=r,this.sourceId=t.sourceId,this.defer(()=>{it.defer(this.source,this.id)})}next(t){it.next(this.source,this.id,t),this.sink.next(t)}complete(){it.complete(this.source,this.id),this.sink.complete()}error(t){it.complete(this.source,this.id,t),this.sink.error(t)}},it={addSource(i,t){qi("addSource",{id:i.id,name:i.toString(),source:{id:t.id,name:t.toString()}})},next(i,t,e){qi("next",{id:i.id,streamId:t,data:e&&e.toString()})},subscribe({id:i,end:t},e){qi("subscribe",{id:i,end:t,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(i,t,e){qi("complete",{id:i.id,streamId:t,err:e?e.toString():null})},defer(i,t){qi("defer",{id:i.id,streamId:t})},pipe(i){qi("pipe",{name:i.toString(),id:i.id,source:{id:i.source.id,name:i.source.toString()}})},update(i){qi("update",{id:i.id,name:i.toString()})},create(i){i.id||(i.id=eT++),qi("create",{name:i.toString(),id:i.id})}},Ea=class extends Error{constructor(t){super(`timeout after ${t}ms`),this.timeout=t}};var _d=class extends Bo{constructor(t){super(),this.source=t,this.sinks=new Set}add(t){t.defer(()=>this.remove(t)),this.sinks.add(t).size===1&&(this.reset(),this.subscribe(this.source))}remove(t){this.sinks.delete(t),this.sinks.size===0&&this.dispose()}next(t){this.sinks.forEach(e=>e.next(t))}complete(){this.sinks.forEach(t=>t.complete()),this.sinks.clear()}error(t){this.sinks.forEach(e=>e.error(t)),this.sinks.clear()}};function li(){return i=>{let t=new _d(i);if(i instanceof or){let e=Oe(r=>{t.add(r)},"share",arguments);return t.sourceId=e.id,e.source=i,it.pipe(e),e}return Oe(t.add.bind(t),"share",arguments)}}function im(...i){return Oe(t=>{let e=new de(t),r=i.length;e.complete=()=>{--r===0&&t.complete()},i.forEach(e.bindSubscribe)},"merge",arguments)}function om(...i){return Oe(t=>{let e=new Map;i.forEach(r=>{let o=new de(t);e.set(r,o),o.complete=()=>{e.delete(r),e.size===0?t.complete():o.dispose()},o.next=s=>{e.delete(r),e.forEach(n=>n.dispose()),o.resetNext(),o.resetComplete(),o.next(s)}}),i.forEach(r=>e.get(r).subscribe(r))},"race",arguments)}function tT(...i){return Oe(t=>{let e=0,r=i.length,o=new de(t);o.complete=()=>{e<r&&!o.disposed?(o.doDefer(),o.subscribe(i[e++])):t.complete()},o.complete()},"concat",arguments)}function rT(i){return t=>{let e=new _d(t),r=[];return e.next=function(o){r.push(o),r.length>i&&r.shift(),this.sinks.forEach(s=>s.next(o))},Oe(o=>{o.defer(()=>e.remove(o)),r.forEach(s=>o.next(s)),e.add(o)},"shareReplay",arguments)}}function iT(i,t,e){return Oe(r=>i()?t(r):e(r),"iif",arguments)}function Sf(...i){return Oe(t=>{let e=i.length,r=e,o=e,s=new Array(e),n=()=>{--o===0&&t.complete()},d=(p,m)=>{let g=new de(t);g.next=_=>{--r===0?(g.next=b=>{s[m]=b,t.next(s)},g.next(_)):s[m]=_},g.complete=n,g.subscribe(p)};i.forEach(d)},"combineLatest",arguments)}function oT(...i){return Oe(t=>{let e=i.length,r=e,o=new Array(e),s=()=>{--r===0&&t.complete()},n=(d,p)=>{let m=new de(t),g=[];o[p]=g,m.next=_=>{g.push(_),o.every(b=>b.length)&&t.next(o.map(b=>b.shift()))},m.complete=s,m.subscribe(d)};i.forEach(n)},"zip",arguments)}function _a(...i){return t=>Oe((e,r=0,o=i.length)=>{for(;r<o&&!e.disposed;)e.next(i[r++]);e.disposed||e.subscribe(t)},"startWith",arguments)}var em=class extends de{constructor(t,...e){super(t);let r=new de(this.sink);r.next=o=>this.buffer=o,r.complete=Ve,r.subscribe(Sf(...e))}next(t){this.buffer&&this.sink.next([t,...this.buffer])}},sT=pe(em,"withLatestFrom"),tm=class extends de{constructor(t,e,r){super(t),this.bufferSize=e,this.startBufferEvery=r,this.buffer=[],this.count=0,this.startBufferEvery&&(this.buffers=[[]])}next(t){this.startBufferEvery?(this.count++===this.startBufferEvery&&(this.buffers.push([]),this.count=1),this.buffers.forEach(e=>{e.push(t)}),this.buffers[0].length===this.bufferSize&&this.sink.next(this.buffers.shift())):(this.buffer.push(t),this.buffer.length===this.bufferSize&&(this.sink.next(this.buffer),this.buffer=[]))}complete(){this.buffer.length?this.sink.next(this.buffer):this.buffers.length&&this.buffers.forEach(t=>this.sink.next(t)),super.complete()}},nT=pe(tm,"bufferCount"),rm=class extends de{constructor(t,e){super(t),this.buffer=[];let r=new de(t);r.next=o=>{t.next(this.buffer),this.buffer=[]},r.complete=Ve,r.subscribe(e)}next(t){this.buffer.push(t)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},aT=pe(rm,"buffer");var cT=function(i,t,e,r){function o(s){return s instanceof e?s:new e(function(n){n(s)})}return new(e||(e=Promise))(function(s,n){function d(g){try{m(r.next(g))}catch(_){n(_)}}function p(g){try{m(r.throw(g))}catch(_){n(_)}}function m(g){g.done?s(g.value):o(g.value).then(d,p)}m((r=r.apply(i,t||[])).next())})};function It(i){let t=arguments,e=li()(Oe(r=>{e.next=o=>r.next(o),e.complete=()=>r.complete(),e.error=o=>r.error(o),i&&r.subscribe(i)},"subject",t));return e.next=Ve,e.complete=Ve,e.error=Ve,e}function yf(i){return Oe(t=>t.subscribe(i()),"defer",arguments)}var Af=i=>t=>{setTimeout(()=>i(t))},bf=i=>Af(t=>{for(let e=0;!t.disposed&&e<i.length;e++)t.next(i[e]);t.complete()});function dT(...i){return Oe(bf(i),"of",arguments)}function uT(i){return Oe(bf(i),"fromArray",arguments)}function sm(i){return Oe(t=>{let e=0,r=setInterval(()=>t.next(e++),i);return t.defer(()=>{clearInterval(r)}),"interval"},"interval",arguments)}function Ta(i,t){return Oe(e=>{let r=0,o=setTimeout(()=>{if(e.removeDefer(s),e.next(r++),t){let n=setInterval(()=>e.next(r++),t);e.defer(()=>{clearInterval(n)})}else e.complete()},i),s=()=>{clearTimeout(o)};e.defer(s)},"timer",arguments)}function Td(i,t){return e=>{let r=o=>e.next(o);e.defer(()=>t(r)),i(r)}}function lT(i,t){return Oe(Td(i,t),"fromEventPattern",arguments)}function be(i,t){if("on"in i&&"off"in i)return Oe(Td(e=>i.on(t,e),e=>i.off(t,e)),"fromEvent",arguments);if("addListener"in i&&"removeListener"in i)return Oe(Td(e=>i.addListener(t,e),e=>i.removeListener(t,e)),"fromEvent",arguments);if("addEventListener"in i)return Oe(Td(e=>i.addEventListener(t,e),e=>i.removeEventListener(t,e)),"fromEvent",arguments);throw"target is not a EventDispachter"}function Rf(i){return Oe(t=>{i.then(t.next.bind(t),t.error.bind(t))},"fromPromise",arguments)}function mT(i,t){return Oe(yf(()=>Rf(fetch(i,t))),"fromFetch",arguments)}function pT(i){return Oe(Af(t=>{try{for(let e of i){if(t.disposed)return;t.next(e)}t.complete()}catch(e){t.error(e)}}),"fromIterable",arguments)}function hT(i){let t=e=>cT(this,void 0,void 0,function*(){if(e.disposed)return;let{done:r,value:o}=yield i.read();if(r){e.complete();return}else e.next(o),t(e)});return Oe(e=>{t(e)},"fromReader",arguments)}function fT(i){return Oe(t=>{let e=new AbortController,r=e.signal;t.defer(()=>e.abort("cancelled")),i.pipeTo(new WritableStream({write(o){t.next(o)},close(){t.complete()},abort(o){t.error(o)}}),{signal:r}).then(()=>t.complete(),o=>t.error(o))},"fromReadableStream",arguments)}function gT(){return Oe(i=>{let t=requestAnimationFrame(function e(r){i.disposed||(i.next(r),t=requestAnimationFrame(e))});i.defer(()=>cancelAnimationFrame(t))},"fromAnimationFrame",arguments)}function ET(i,t){return Oe((e,r=i,o=t+i)=>{for(;r<o&&!e.disposed;)e.next(r++);return e.complete(),"range"},"range",arguments)}function _T(i,t,...e){return Oe(r=>{let o=e.concat(s=>(r.next(s),r.complete()));i.apply(t,o)},"bindCallback",arguments)}function TT(i,t,...e){return Oe(r=>{let o=e.concat((s,n)=>s?r.error(s):(r.next(n),r.complete()));i.apply(t,o)},"bindNodeCallback",arguments)}function IT(){return Oe(()=>{},"never",arguments)}function ST(i){return Oe(t=>t.error(i),"throwError",arguments)}function Ia(){return Oe(i=>i.complete(),"empty",arguments)}var Wo=class extends de{constructor(t,e,r){super(t),this.f=e;let o=()=>{this.sink.next(this.acc),this.sink.complete()};typeof r=="undefined"?this.next=s=>{this.acc=s,this.complete=o,this.resetNext()}:(this.acc=r,this.complete=o)}next(t){this.acc=this.f(this.acc,t)}},nm=pe(Wo,"reduce"),yT=i=>pe(Wo,"count")((t,e)=>i(e)?t+1:t,0),AT=()=>pe(Wo,"max")(Math.max),bT=()=>pe(Wo,"min")(Math.min),RT=()=>pe(Wo,"sum")((i,t)=>i+t,0);var am=class extends de{constructor(t,e,r){super(t),this.filter=e,this.thisArg=r}next(t){this.filter.call(this.thisArg,t)&&this.sink.next(t)}},yr=pe(am,"filter"),cm=class extends de{next(t){}},vT=pe(cm,"ignoreElements"),dm=class extends de{constructor(t,e){super(t),this.count=e}next(t){this.sink.next(t),--this.count===0&&this.complete()}},Ar=pe(dm,"take"),um=class extends de{constructor(t,e){super(t);let r=new de(t);r.next=()=>t.complete(),r.complete=Ed,r.subscribe(e)}},Je=pe(um,"takeUntil"),lm=class extends de{constructor(t,e){super(t),this.f=e}next(t){this.f(t)?this.sink.next(t):this.complete()}},vf=pe(lm,"takeWhile"),CT=i=>nm((t,e)=>(t.push(e),t.length>i&&t.shift(),t),[]),mm=class extends de{constructor(t,e){super(t),this.count=e}next(t){--this.count===0&&(this.next=super.next)}},DT=pe(mm,"skip"),pm=class extends de{constructor(t,e){super(t),t.next=Ve;let r=new de(t);r.next=()=>{r.dispose(),t.resetNext()},r.complete=Ed,r.subscribe(e)}},NT=pe(pm,"skipUntil"),hm=class extends de{constructor(t,e){super(t),this.f=e}next(t){this.f(t)||(this.next=super.next,this.next(t))}},yd=pe(hm,"skipWhile"),wT={leading:!0,trailing:!1},fm=class extends de{constructor(t,e,r){super(t),this.durationSelector=e,this.trailing=r}cacheValue(t){this.last=t,this.disposed&&this.throttle(t)}send(t){this.sink.next(t),this.throttle(t)}throttle(t){this.reset(),this.subscribe(this.durationSelector(t))}next(){this.complete()}complete(){this.dispose(),this.trailing&&this.send(this.last)}},Id=class extends de{constructor(t,e,r=wT){super(t),this.durationSelector=e,this.config=r,this._throttle=new fm(this.sink,this.durationSelector,this.config.trailing),this._throttle.dispose()}next(t){this._throttle.disposed&&this.config.leading?this._throttle.send(t):this._throttle.cacheValue(t)}complete(){this._throttle.throttle=Ve,this._throttle.complete(),super.complete()}},MT=pe(Id,"throttle"),OT={leading:!1,trailing:!0},xT=i=>pe(Id,"audit")(i,OT),gm=class extends de{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},Sd=class extends de{constructor(t,e){super(t),this.durationSelector=e,this._debounce=new gm(this.sink),this._debounce.dispose()}next(t){this._debounce.dispose(),this._debounce.reset(),this._debounce.last=t,this._debounce.subscribe(this.durationSelector(t))}complete(){this._debounce.complete(),super.complete()}},PT=pe(Sd,"debounce"),kT=i=>pe(Sd,"debounceTime")(t=>Ta(i)),Em=class extends de{constructor(t,e,r){super(t),this.count=e,this.defaultValue=r}next(t){this.count--===0&&(this.defaultValue=t,this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("not enough elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},LT=pe(Em,"elementAt"),UT=i=>t=>Ar(1)(yd(e=>!i(e))(t)),_m=class extends de{constructor(t,e){super(t),this.f=e,this.i=0}next(t){this.f(t)?(this.sink.next(this.i++),this.complete()):++this.i}},VT=pe(_m,"findIndex"),Tm=class extends de{constructor(t,e,r){super(t),this.f=e,this.defaultValue=r,this.index=0}next(t){(!this.f||this.f(t,this.index++))&&(this.defaultValue=t,this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},FT=pe(Tm,"first"),Im=class extends de{constructor(t,e,r){super(t),this.f=e,this.defaultValue=r,this.index=0}next(t){(!this.f||this.f(t,this.index++))&&(this.defaultValue=t)}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},$T=pe(Im,"last"),Sm=class extends de{constructor(t,e){super(t),this.predicate=e,this.index=0}next(t){this.predicate(t,this.index++)?this.result=!0:(this.result=!1,this.complete())}complete(){if(this.result===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.result);super.complete()}},BT=pe(Sm,"every");var ym=class extends de{constructor(t,e,r){super(t),this.f=e,typeof r=="undefined"?this.next=o=>{this.acc=o,this.resetNext(),this.sink.next(this.acc)}:this.acc=r}next(t){this.sink.next(this.acc=this.f(this.acc,t))}},Om=pe(ym,"scan"),Am=class extends de{constructor(){super(...arguments),this.hasLast=!1}next(t){this.hasLast?this.sink.next([this.last,t]):this.hasLast=!0,this.last=t}},HT=pe(Am,"pairwise"),Ad=class extends de{constructor(t,e,r){super(t),this.mapper=e,this.thisArg=r}next(t){super.next(this.mapper.call(this.thisArg,t))}},Ji=pe(Ad,"map"),WT=i=>pe(Ad,"mapTo")(t=>i),Bs=class extends de{constructor(t,e,r){super(t),this.data=e,this.context=r}next(t){let e=this.context.combineResults;e?this.sink.next(e(this.data,t)):this.sink.next(t)}tryComplete(){this.context.resetComplete(),this.dispose()}},Hs=class extends de{constructor(t,e,r){super(t),this.makeSource=e,this.combineResults=r,this.index=0}subInner(t,e){let r=this.currentSink=new e(this.sink,t,this);this.complete=this.tryComplete,r.complete=r.tryComplete,r.subscribe(this.makeSource(t,this.index++))}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},bd=class extends Bs{},Rd=class extends Hs{next(t){this.subInner(t,bd),this.next=e=>{this.currentSink.dispose(),this.subInner(e,bd)}}},zi=pe(Rd,"switchMap");function Nd(i){return(t,e)=>i(()=>t,e)}var mi=Nd(pe(Rd,"switchMapTo")),bm=class extends Bs{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},vd=class extends Hs{constructor(){super(...arguments),this.sources=[],this.next2=this.sources.push.bind(this.sources)}next(t){this.next2(t),this.subNext()}subNext(){this.next=this.next2,this.subInner(this.sources.shift(),bm),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},GT=pe(vd,"concatMap"),jT=Nd(pe(vd,"concatMapTo")),Rm=class extends Bs{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},Cd=class extends Hs{constructor(){super(...arguments),this.inners=new Set}next(t){this.subInner(t,Rm),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(t=>t.resetComplete()):this.dispose()}},qT=pe(Cd,"mergeMap"),JT=Nd(pe(Cd,"mergeMapTo")),vm=class extends Bs{dispose(){this.context.resetNext(),super.dispose()}},Dd=class extends Hs{next(t){this.next=Ve,this.subInner(t,vm)}},zT=pe(Dd,"exhaustMap"),XT=Nd(pe(Dd,"exhaustMapTo")),Cm=class extends de{constructor(t,e){super(t),this.f=e,this.groups=new Map}next(t){let e=this.f(t),r=this.groups.get(e);typeof r=="undefined"&&(r=It(),r.key=e,this.groups.set(e,r),super.next(r)),r.next(t)}complete(){this.groups.forEach(t=>t.complete()),super.complete()}error(t){this.groups.forEach(e=>e.error(t)),super.error(t)}},QT=pe(Cm,"groupBy"),Dm=class extends de{constructor(){super(...arguments),this.start=new Date}next(t){this.sink.next({value:t,interval:Number(new Date)-Number(this.start)}),this.start=new Date}},YT=pe(Dm,"timeInterval"),Nm=class extends de{constructor(t,e){super(t),this.miniseconds=e,this.buffer=[],this.id=setInterval(()=>{this.sink.next(this.buffer.concat()),this.buffer.length=0},this.miniseconds)}next(t){this.buffer.push(t)}complete(){this.sink.next(this.buffer),super.complete()}dispose(){clearInterval(this.id),super.dispose()}},ZT=pe(Nm,"bufferTime"),wm=class extends de{constructor(t,e){super(t),this.buffer=[],this.delayTime=e}dispose(){clearTimeout(this.timeoutId),super.dispose()}delay(t){this.timeoutId=setTimeout(()=>{let e=this.buffer.shift();if(e){let{time:r,data:o}=e;super.next(o),this.buffer.length&&this.delay(Number(this.buffer[0].time)-Number(r))}},t)}next(t){this.buffer.length||this.delay(this.delayTime),this.buffer.push({time:new Date,data:t})}complete(){this.timeoutId=setTimeout(()=>super.complete(),this.delayTime)}},KT=pe(wm,"delay"),Mm=class extends de{constructor(t,e){super(t),this.selector=e}error(t){this.dispose(),this.selector(t)(this.sink)}},xm=pe(Mm,"catchError");var eI=()=>i=>new Promise((t,e)=>{let r;new Ho(i,o=>r=o,e,()=>t(r))}),tI=()=>i=>{let t;return new ReadableStream({start(e){t=new Ho(i,e.enqueue.bind(e),e.error.bind(e),e.close.bind(e))},cancel(){t.dispose()}})},ke=(i=Ve,t=Ve,e=Ve)=>r=>new Ho(r,i,t,e),Pm=class extends de{constructor(t,e){super(t),e instanceof Function?this.next=r=>{e(r),t.next(r)}:(e.next&&(this.next=r=>{e.next(r),t.next(r)}),e.complete&&(this.complete=()=>{e.complete(),t.complete()}),e.error&&(this.error=r=>{e.error(r),t.error(r)}))}},Sa=pe(Pm,"tap"),km=class extends de{constructor(t,e){super(t),this.timeout=e,this.id=setTimeout(()=>this.error(new Ea(this.timeout)),this.timeout)}next(t){super.next(t),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},Lm=pe(km,"timeout"),rI=(i=1/0)=>t=>{if(t instanceof or){let e=Oe(r=>{let o=i,s=new de(r);s.error=n=>{o-- >0?s.subscribe(t):r.error(n)},s.sourceId=e.id,s.subscribe(t)},"retry",[i]);return e.source=t,it.pipe(e),e}else return e=>{let r=i,o=new de(e);o.error=s=>{r-- >0?t(o):e.error(s)},t(o)}};var Br=class Br extends ko{constructor(e,r,o){super({userId:r.userId,sdkAppId:e.sdkAppId,mediaType:o,room:e});this.room=e;this.user=r;u(this,"tinyId");u(this,"isRemote",!0);u(this,"jitterBufferDelay",0);u(this,"availableState");u(this,"remotePublishState");u(this,"_triggerCheckDecodeSubject",It(be(this,Br.STATE_SUBSCRIBE)));this.tinyId=r.tinyId,this.availableState=new ne(`${r.userId}-${this.mediaType}-available`,"remote-track-available"),this.remotePublishState=new ne(`${r.userId}-${this.mediaType}-remote-publish`,"remote-track-publish"),Se(im(be(this,ne.STATECHANGED),be(this.remotePublishState,ne.STATECHANGED)),Ji(()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing)),ke(p=>{this.availableState.state!==(p?ne.ON:ne.OFF)&&(this.availableState.state=p?ne.ON:ne.OFF),this.updatePlayingState(p)}));let s=Se(be(this.player,Qe.ERROR),yr(p=>p.code===MediaError.MEDIA_ERR_DECODE)),n=Se(Ta(5e3),yr(()=>this.ignoreDecodeError||!this.isSubscribed||!this.isPlayCalled||!this.stat.bytesReceived?!1:this.player.isPlaying||(this.kind===D.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)?(this.reportDecodeResult(!0),!1):!0)),d=Se(om(s,n),Je(be(this,ne.INIT)));Se(this._triggerCheckDecodeSubject,yr(()=>!this.ignoreDecodeError),mi(d),ke(p=>{this.reportDecodeResult(!1,p)}))}setMute(e){this.isRemotePublished&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.isRemotePublished&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}checkDecodeResult(){this._triggerCheckDecodeSubject.next(!0)}waitHasMediaTrack(){return new Promise(e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)})}get ignoreDecodeError(){var r,o;return(((o=(r=this.room)==null?void 0:r.networkQuality)==null?void 0:o.downlinkNetworkQuality)||0)>3||this.player.isInAutoPlayFailedState}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===Br.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===ne.ON}get isNeedPlay(){return this.isAvailable&&this.isPlayCalled}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}reportDecodeResult(e,r){let o=this.kind===D.AUDIO;Y[e?"addSuccessEvent":"addFailedEvent"]({key:o?504700:514702}),e||(Y.addEnum({key:o?504701:514703,value:Jn()}),Be.uploadEvent({log:`stat-decode-failed-${this.kind}-${qn()||bo()}`,userId:this.room.userId}),this._log.warn(`decode failed: isPlaying: ${this.player.isPlaying} ${this.kind===D.AUDIO?`audioLevel: ${this.getAudioLevel()}`:`framesDecoded: ${this.stat.framesDecoded>0}`}`),this.emit("decode-failed",{error:r}))}updatePlayingState(e){if(this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.isRemotePublished||!this.outMediaTrack)){this.log.info(`abort play, isSubscribed: ${this.isSubscribed} isAvailable: ${this.isRemotePublished} hasTrack: ${!!this.outMediaTrack} `);return}super.updatePlayingState(e)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.remotePublishState.state=this.isRemotePublished?ne.ON:ne.OFF}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};u(Br,"STATE_SUBSCRIBE","subscribe"),X([_f(5,1)],Br.prototype,"waitHasMediaTrack",1),X([qe(ne.INIT,Br.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),H.emit(L.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),hd(521716,!1)],Br.prototype,"subscribe",1),X([qe(Br.STATE_SUBSCRIBE,ne.INIT,{sync:!0,success(){this.log.info("unsubscribed"),H.emit(L.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],Br.prototype,"unsubscribe",1);var Ws=Br;var $o=class extends Ws{constructor(e,r){super(e,r,1);u(this,"volume",0);u(this,"mediaType",1);u(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.audioManager}get dbVolume(){return nd.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}decodeFrame(e){if(!this.manager)return e;let r=e;for(let o of this.manager.decodePipeline)if(o&&(r=o({frame:r,track:this}),!r))return;return r}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get isRemotePublished(){return this.user.muteState.audioAvailable}};var oI=[-1,-1,1,-1,-1,1,1,1],sI=[0,0,1,0,0,1,1,1];var Bt=class extends ne{constructor(e,r){super();this.context=e;u(this,"name");u(this,"input");u(this,"output");u(this,"texture");u(this,"ctx2d",null);u(this,"fbo");u(this,"width",0);u(this,"height",0);u(this,"x",0);u(this,"y",0);u(this,"program");u(this,"vertexShader");u(this,"fragmentShader");u(this,"totalFrames",0);u(this,"dropFrames",0);u(this,"matchInputSize",!0);u(this,"texCoordBuffer");u(this,"positionBuffer");u(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0});u(this,"cost",0);u(this,"_canvas",null);u(this,"_image");u(this,"log");if(this.context.on("disconnect",this.close,this),this.name=r.name,this.log=r.logger,this.matchInputSize=r.matchInputSize!==!1,this.width=r.width||e.width,this.height=r.height||e.height,this._image=r.image,e instanceof kt){e.ctx&&r.create2d&&(typeof OffscreenCanvas=="function"&&Yt!==16?this._canvas=new OffscreenCanvas(this.width,this.height):(this._canvas=document.createElement("canvas"),this._canvas.width=this.width,this._canvas.height=this.height),this.ctx2d=this._canvas.getContext("2d"),this._image=this._canvas);return}try{let o=e.ctx;this.texCoordBuffer=this.createBuffer(sI),this.positionBuffer=this.createBuffer(oI),r.createTexture!==!1&&(this.texture=o.createTexture(),this.useTexture(),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),o.pixelStorei(o.PACK_ALIGNMENT,1),o.pixelStorei(o.UNPACK_ALIGNMENT,1)),r.useFbo&&(this.fbo=o.createFramebuffer(),this.useBufferFrame(),this.useTexture(),o.texImage2D(o.TEXTURE_2D,0,o.RGBA,this.width,this.height,0,o.RGBA,o.UNSIGNED_BYTE,null),o.framebufferTexture2D(o.FRAMEBUFFER,o.COLOR_ATTACHMENT0,o.TEXTURE_2D,this.texture,0)),r.useDefaultProgram?this.program=e.defaultProgam:(r.vertexShaderSource||r.fragmentShaderSource)&&(this.vertexShader=r.vertexShaderSource?e.createShader(o.VERTEX_SHADER,r.vertexShaderSource):e.defaultVShader,this.fragmentShader=r.fragmentShaderSource?e.createShader(o.FRAGMENT_SHADER,r.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(o){this.context.destroy(new he({code:te.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${o.message||o}`}))}}get image(){return this._image}set image(e){this._image=e}createFramebuffer(e){let r=this.context.ctx,o=r.createFramebuffer();return r.bindFramebuffer(r.FRAMEBUFFER,o),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,e,0),o}connect(e,...r){return e.addInput(this,...r),this.output=e,e}addInput(e,...r){this.input=e,this.matchInputSize&&e.width&&e.height&&this.resize(e.width,e.height)}requestFrame(e){let r=Date.now();if(this.context instanceof Et&&this.render(e)||this.context instanceof kt&&this.render2d(e))this.totalFrames++;else return!1;return this.cost=Date.now()-r,!0}render2d(e){var r;return(r=this.input)!=null&&r.requestFrame(e)?this.draw2d(this.input.image,0,0,this.width,this.height):!1}update(e=0){var r;(r=this.output)==null||r.update(e)}disconnect(...e){var r;(r=this.output)==null||r.removeInput(this,...e),delete this.output}removeInput(e,...r){delete this.input}close(){var e,r;if(this.context.off("disconnect",this.close,this),(e=this.output)==null||e.removeInput(this),delete this.output,(r=this.input)==null||r.disconnect(),this.context instanceof Et){let o=this.context.ctx;o.deleteBuffer(this.texCoordBuffer),o.deleteBuffer(this.positionBuffer),this.fbo&&o.deleteFramebuffer(this.fbo),this.texture&&o.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&o.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&o.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&o.deleteProgram(this.program)}this._canvas&&(this._canvas.width=0,this._canvas.height=0,this.ctx2d=null),this.removeAllListeners()}useTexture(){this.useTextures(this.texture)}useInputTexture(){var e;this.useTextures((e=this.input)==null?void 0:e.texture)}useTextures(...e){let r=this.context.ctx;e.forEach((o,s)=>{o&&(r.activeTexture(r.TEXTURE0+s),r.bindTexture(r.TEXTURE_2D,o))})}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}createBuffer(e){let r=this.context.ctx,o=r.createBuffer();return r.bindBuffer(r.ARRAY_BUFFER,o),r.bufferData(r.ARRAY_BUFFER,new Float32Array(e),r.STATIC_DRAW),o}setTexBuffer(e){let r=this.context.ctx;r.bindBuffer(r.ARRAY_BUFFER,this.texCoordBuffer),r.bufferData(r.ARRAY_BUFFER,new Float32Array(e),r.STATIC_DRAW)}setPosBuffer(e){let r=this.context.ctx;r.bindBuffer(r.ARRAY_BUFFER,this.positionBuffer),r.bufferData(r.ARRAY_BUFFER,new Float32Array(e),r.STATIC_DRAW)}changeBufferData(e,r){let o=this.context.ctx;o.bindBuffer(o.ARRAY_BUFFER,e),o.bufferData(o.ARRAY_BUFFER,new Float32Array(r),o.STATIC_DRAW)}setAttributes(...e){let r=this.context.ctx;e.forEach((o,s)=>{r.enableVertexAttribArray(s),r.bindBuffer(r.ARRAY_BUFFER,o),r.vertexAttribPointer(s,2,r.FLOAT,!1,0,0)})}getVertexPoint(e,r){return[e/this.width*2-1,r/this.height*2-1]}layout2texCoords(e){return[...this.getVertexPoint(e.x,e.y),...this.getVertexPoint(e.x+e.width,e.y),...this.getVertexPoint(e.x,e.y+e.height),...this.getVertexPoint(e.x+e.width,e.y+e.height)]}resize(e,r){if(!(this.width===e&&this.height===r)){if(this.width=e,this.height=r,this._canvas&&(this._canvas.width=e,this._canvas.height=r),this.texture&&this.fbo){this.useTexture();let o=this.context.ctx;o.texImage2D(o.TEXTURE_2D,0,o.RGBA,e,r,0,o.RGBA,o.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(e,r)}}draw(e,r){this.setAttributes(e||this.positionBuffer,r||this.texCoordBuffer);let o=this.context.ctx;o.drawArrays(o.TRIANGLE_STRIP,0,4)}draw2d(e,r,o,s,n){return this.ctx2d&&e?(e instanceof ImageData?this.ctx2d.putImageData(e,r,o):(this.ctx2d.drawImage(e,r,o,s,n),typeof VideoFrame!="undefined"&&e instanceof VideoFrame&&e.close()),!0):!1}getInfo(){var _;let{totalFrames:e,x:r,y:o,width:s,height:n,name:d,cost:p}=this,m=Date.now(),g=(e-this.lastInfo.totalFrames)/((m-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:r,y:o,width:s,height:n,timestamp:m,fps:g,name:d,cost:p},ee({parent:(_=this.input)==null?void 0:_.getInfo()},this.lastInfo)}createTexture(e){let r=this.context.ctx,o=r.createTexture();return this.useTextures(o),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.pixelStorei(r.PACK_ALIGNMENT,1),r.pixelStorei(r.UNPACK_ALIGNMENT,1),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,r.RGBA,r.UNSIGNED_BYTE,e),o}};X([qe(ne.INIT,"connected",{sync:!0})],Bt.prototype,"connect",1),X([qe("connected",ne.INIT,{ignoreError:!0,sync:!0})],Bt.prototype,"disconnect",1),X([qe([],"closed",{sync:!0})],Bt.prototype,"close",1);var Df=Se(sm(250),Ji(()=>performance.now()),li()),Nf=i=>t=>{let e=0,r=performance.now();Se(Df,Ji(o=>(o-r)/i>>0),yr(o=>o!=e?(e=o,!0):!1))(t)},wd=i=>t=>{let e=performance.now();Se(Df,yd(r=>r-e<i),Ar(1))(t)};var aI=[0,1,1,1,0,0,1,0],Go=class extends Bt{constructor(e,r){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},r));u(this,"_intervalId",0);u(this,"_sequence",0);u(this,"checkGLError",!1);u(this,"checkVisibilityChange");e instanceof kt?this.ctx2d=e.ctx||null:e.available&&(r!=null&&r.mirrorUpAndDown)&&this.setTexBuffer(aI)}start(e){this.log.info(`${this.name} start render ${e} fps`),At.clearTask(this._intervalId),this._intervalId=At.run("intervalInWorker",()=>{if(e!==this.context.frameRate&&(At.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof Et){let o=this.context.ctx.getError();o&&this.context.destroy(new he({code:te.VIDEO_MANAGER_ERROR,extraCode:5,message:`${this.name} req ${this._sequence} render ${this.totalFrames} faild ${o}`}))}},{fps:this.context.frameRate})}render(e){var r;return(r=this.input)!=null&&r.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}addInput(e,...r){super.addInput(e,...r),this.start(this.context.frameRate)}update(e=0){if(this._intervalId&&(At.clearTask(this._intervalId),this._intervalId=0,e===1)){this.log.info(`${this.name} use requestVideoFrameCallback`);let r=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info(`${this.name} use timer`),document.removeEventListener("visibilitychange",r))};document.addEventListener("visibilitychange",r)}this.requestFrame(this._sequence++)}removeInput(e){super.removeInput(e),At.clearTask(this._intervalId)}resize(e,r){super.resize(e,r),this.context.setSize(e,r)}close(){super.close(),At.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},Gs=class extends Go{constructor(e,r){super(e,r);u(this,"_videoTrack");u(this,"_muteOb");u(this,"_closedOb",be(this,"closed"));u(this,"_subscription");u(this,"_canvasContainer");Number(Vi)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e._canvas.captureStream().getVideoTracks(),this._muteOb=be(this._videoTrack,"mute"),Se(be(this._videoTrack,"ended"),Je(this._closedOb),ke(()=>{this.context.destroy(new he({code:te.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){this._subscription=Se(this._muteOb,Je(this._closedOb),mi(wd(5e3)),ke(()=>{var e;(e=this._videoTrack)!=null&&e.muted&&this.context.destroy(new he({code:te.VIDEO_MANAGER_ERROR,extraCode:7,message:"video track muted"}))}))}disableCheckMute(){var e;(e=this._subscription)==null||e.dispose()}get videoTrack(){return this._videoTrack}putCanvasIntoDom(){!this.context._canvas||!this._canvasContainer||document.getElementById(this.context._canvas.id)||(this.log.info(`${this.name} put canvas to body`),document.body.appendChild(this._canvasContainer),this._canvasContainer.appendChild(this.context._canvas))}render(e){return this.putCanvasIntoDom(),super.render(e)}render2d(e){return this.putCanvasIntoDom(),super.render2d(e)}close(){var e,r;super.close(),(e=this._videoTrack)==null||e.stop(),delete this._videoTrack,(r=this._canvasContainer)==null||r.remove()}},Md=class extends Gs{render(t){var e;return!!((e=this.input)!=null&&e.requestFrame(t))}};var Od=class extends Gs{constructor(e,r,o){super(e,{name:"smallDestination",logger:o});this.resolution=r}resize(e,r){let o,s=e*r,n=this.resolution.width*this.resolution.height;this.log.info(`big res: ${e}*${r} small res: ${this.resolution.width}*${this.resolution.height} `),s>n?o=s/n:(this.log.warn(`Small stream resolution is not smaller than big stream, which is invalid. big: ${e} * ${r} small: ${this.resolution.width} * ${this.resolution.height}`),o=s/(160*120)),super.resize(e/Math.sqrt(o),r/Math.sqrt(o))}};var ya=class extends Bt{constructor(e,r){super(e,ee({name:"imageSource"},r));u(this,"_lastImage");u(this,"_totalFrames",0);u(this,"_autoResize",!1);u(this,"_canvasRendered");u(this,"_videoCallbackId",0);this._autoResize=(r==null?void 0:r.autoResize)!==!1,Yt===16&&(this._canvasRendered=It(),Se(this._canvasRendered,_a(this._image),zi(o=>o instanceof HTMLCanvasElement?be(o,"rendered"):Ia()),Je(be(this,"closed")),ke(()=>{this.update()})))}tryVideoFrameCallback(e){this._videoCallbackId&&e.cancelVideoFrameCallback(this._videoCallbackId),Oo()&&!document.hidden&&(this._videoCallbackId=e.requestVideoFrameCallback((r,o)=>{document.hidden||(this._totalFrames=o.presentedFrames,this.update(1))}))}_render(e,r){var d;let{width:o,height:s}=this,{image:n}=this;if(n instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(n),{videoWidth:o,videoHeight:s}=n,!o||!s)return!1;n.width=o,n.height=s}else if(n instanceof HTMLImageElement||n instanceof ImageData||n instanceof ImageBitmap){if({width:o,height:s}=n,n!==this._lastImage)this._lastImage=n;else if(o===this.width&&s===this.height)return!1}else n instanceof HTMLCanvasElement||n instanceof OffscreenCanvas?({width:o,height:s}=n,this._lastImage=n):typeof VideoFrame!="undefined"&&n instanceof VideoFrame&&({displayWidth:o,displayHeight:s}=n,(d=this._lastImage)==null||d.close(),this._lastImage=n);if(!this._autoResize)return!0;if(this.width===o&&this.height===s&&this.totalFrames){if(r){this.useTexture();let p=this.context.ctx;p.texSubImage2D(p.TEXTURE_2D,0,0,0,p.RGBA,p.UNSIGNED_BYTE,n)}}else{if(r){this.useTexture();let p=this.context.ctx;p.texImage2D(p.TEXTURE_2D,0,p.RGBA,p.RGBA,p.UNSIGNED_BYTE,n)}this.resize(o,s)}return!0}get image(){return this._image}set image(e){var r;(r=this._canvasRendered)==null||r.next(e),this._image=e}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},Aa=class extends ya{constructor(e,r,o){super(e,o);this._player=r;this.name="videoPlayerSource",Se(be(this._player,Qe.PLAYER_STATE_CHANGED),Je(be(this,"closed")),yr(({state:s})=>s==="PLAYING"),ke(()=>{this.tryVideoFrameCallback(this._player.element)}))}get image(){return this._player.element}},pi=class extends Aa{constructor(t,e,r){super(t,new Zt({id:r.name,track:e,muted:!0,container:null,objectFit:"contain",log:r.logger}),r),this.name="videoTrackSource",this._player.play()}replaceTrack(t){this._player.setTrack(t),this._player.play()}close(){super.close(),this._player.stop()}};var dI=`
31
+ `,r.onclick=this.onQuestionClick.bind(this);let o=document.createElement("div");o.className=$l,o.innerText=`${fr()?"\u8BE6\u60C5 >":"Detail >"}`,o.onclick=this.onCollapseClick.bind(this);let s=t.content.firstChild,n=s.querySelector(`.${ed}`);return n.appendChild(o),n.appendChild(r),n.appendChild(e),s}addDiaLog(){Wl()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${Ls}`).onclick=t=>t.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",$.info("show autoplay dialog"),Be.uploadEvent({log:P_}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){$.warn("confirm clicked, try resume stream"),H.emit(L.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let t=this._dialogNode.querySelector(`.${Wh}`);t.style.visibility=`${this._showDetail?"hidden":"visible"}`,t.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||Be.uploadEvent({log:k_}),this._isCollapseClicked=!0}onQuestionClick(){window.open(Jh,"_blank"),this._isQuestionClicked||Be.uploadEvent({log:L_}),this._isQuestionClicked=!0}},zh=Bl;var Zt=class extends $r{constructor(e){super(e,D.VIDEO);u(this,"stat",{});u(this,"_calculateTimeout",-1);u(this,"viewMirror",!1);u(this,"objectFit");u(this,"container");u(this,"canvas");u(this,"canvasTrack");this.mode=e.canvas?1:0,this.container=e.container,this.canvas=e.canvas,V(e.viewMirror)||(this.viewMirror=e.viewMirror),V(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}initializeElement(){var r;let e=document.createElement(D.VIDEO);this.track&&this.mode!==2&&(e.srcObject=new MediaStream([this.track])),e.muted=!0,e.setAttribute("id",`video_${this.id}`),e.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),e.setAttribute("autoplay","autoplay"),e.setAttribute("playsinline","playsinline"),this.element=e,(r=this.container)==null||r.appendChild(this.elementToRender),this.bindElementEvents(),this.calculateStat()}get styleAttribute(){let e=`width: 100%; height: 100%; object-fit: ${this.objectFit};background-color: black;`;return this.viewMirror&&(e+="transform: scaleX(-1);"),e}setContainer(e){var r;this.container=e,(this.track||this.canvasTrack)&&this.elementToRender&&((r=this.container)==null||r.appendChild(this.elementToRender))}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),e&&e.add(D.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(D.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent)}handleTrackEvent(e){var r;super.handleTrackEvent(e),e.type===D.MUTE&&((r=this.stat)!=null&&r.fps)&&(this.stat.fps=0)}handleElementEvent(e){var o;if(this.mode===2)return;super.handleElementEvent(e);let r=e.type;if(r===D.PAUSE&&(this.container&&document.getElementById(this.container.id)||this._log.warn(`${this.kind} player has been remove, element ID: ${(o=this.container)==null?void 0:o.id}`),this._pausedRetryCount>0&&!Wl()&&(this._log.info(`${this.kind} player auto resume when paused`),this.resume(),this._pausedRetryCount--),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){let s=this.element.style.transform;r===D.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=s.replace("scaleX(-1)",""):r===D.LEAVE_PICTURE_IN_PICTURE&&!s.includes("scaleX")&&(this.element.style.transform=`${s} scaleX(-1)`)}}setCanvas(e,r=1){var o,s,n,d;this.canvas!==e&&((o=this.canvas)==null||o.remove(),e==null||e.setAttribute("style",this.styleAttribute),this.canvas=e,this.mode=e?r:0,this.mode===2&&this.setTrack(e.captureStream().getVideoTracks()[0]),e?((s=this.element)==null||s.remove(),(n=this.container)==null||n.appendChild(e)):this.element&&((d=this.container)==null||d.appendChild(this.element)))}setAttr(e){let r=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},e);r.style=Object.assign({width:"100%",height:"100%"},r.style),super.setAttr(r)}get mirror(){return this.viewMirror}setRect(e,r){this.elementToRender&&(this.elementToRender.style.width=`${e}px`,this.elementToRender.style.height=`${r}px`)}setViewMirror(e){this.elementToRender&&(this.elementToRender.style.transform=e?"scaleX(-1)":""),this.viewMirror=e}setObjectFit(e){this.elementToRender&&(this.elementToRender.style.objectFit=`${e}`),this.objectFit=e}setPoster(e){this.element&&(this.element.poster=e)}stop(e=0){var r;super.stop(e),(r=this.canvas)==null||r.remove()}play(){return this.element?this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender):this.initializeElement(),this.mode===2?Promise.resolve():super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(Qe.MEDIA_TRACK_CHANGED,e),e!==null&&(this.bindTrackEvents(),this.element&&this.mode!==2&&(this.element.srcObject=new MediaStream([e]),this.element.remove()),this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender)))}getVideoFrame(){if(this.canvas)return this.canvas.toDataURL("image/png");if(!this.element)return"";let e=document.createElement("canvas");return e.width=this.element.videoWidth,e.height=this.element.videoHeight,e.getContext("2d").drawImage(this.element,0,0),e.toDataURL("image/png")}getElement(){return this.element}calculateStat(){try{if(Oo()&&this.element&&this._calculateTimeout<0){let e=0,r=null,o=(s,n)=>{this.stat.width=n.width,this.stat.height=n.height,r&&(this.stat.fps=Math.round((n.presentedFrames-r.presentedFrames)/(s-e)*1e3)),e=s,r=n,this._calculateTimeout=-1,this.element&&(this._calculateTimeout=setTimeout(()=>{var d;return(d=this.element)==null?void 0:d.requestVideoFrameCallback(o)},2e3))};this.element.requestVideoFrameCallback(o)}}catch(e){this._log.warn("init stat failed",e)}}};function Po(i,t){return y(this,null,function*(){if(!i.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield i.audioWorklet.addModule(t),$.info("worklet addModule success")}catch(e){throw $.info(`worklet addModule catch error. ${e.message}`),e}})}var la;typeof AudioContext!="undefined"?la=AudioContext:typeof webkitAudioContext!="undefined"?la=webkitAudioContext:typeof mozAudioContext!="undefined"&&(la=mozAudioContext);var Ir,Xh=-1;Qh();function Qh(){try{if(Ir)return;Ir=new la({sampleRate:48e3}),Ir.onstatechange=()=>{$.info(`context state: ${Ir.state}${Ir.state!=="running"?` visibilityState: ${document.visibilityState}`:""}`),Us()},clearTimeout(Xh)}catch(i){$.error(`initAudioContext failed: ${i} typeof AudioContextClass: ${typeof la}`),Xh=setTimeout(Qh,1e3)}}var Us=()=>{Ir.state==="suspended"?(Vs(),document.addEventListener("click",Us)):Ir.state==="interrupted"?Vs():(document.removeEventListener("visibilitychange",Us),document.removeEventListener("click",Us))},Gl=0,jl=-1;function Vs(){return new Promise((i,t)=>{if(Ir.state==="running")return i();Date.now()-Gl<1e3?(clearTimeout(jl),jl=setTimeout(()=>{Gl=Date.now(),Ir.resume().then(i,t)},1e3)):(clearTimeout(jl),Gl=Date.now(),Ir.resume().then(i,t))}).catch(i=>{$.warn(`context resume failed: ${i}`),document.addEventListener("visibilitychange",Us)})}document.addEventListener("click",Us);var et=i=>Ir;var Pt=class{constructor(){u(this,"node");u(this,"node2");u(this,"pre",new Set);u(this,"next",new Set);u(this,"context");u(this,"connectedNodes",new Set)}setContext(t){this.context=t,this.node&&t.addMixWeight()}removeContext(){var t;this.node&&((t=this.context)==null||t.reduceMixWeight()),delete this.context}replaceNode(t){var e;if(t!==this.node)try{this.node?this._disconnect():(e=this.context)==null||e.addMixWeight(),this.node=t,this.preNodeReconnect(),this.reconnect()}catch(r){$.error(r)}}setNode(t,e){var r;if(!this.node)try{(r=this.context)==null||r.addMixWeight(),this.node=t,e&&(this.node2=e),this.preNodeReconnect(),this.reconnect(),Y.addSuccessEvent({key:502701})}catch(o){$.error(o),Y.addFailedEvent({key:502701,error:o})}}deleteNode(){var t;if(this.node)try{this._disconnect(),delete this.node,delete this.node2,(t=this.context)==null||t.reduceMixWeight(),this.preNodeReconnect(),Y.addSuccessEvent({key:502702})}catch(e){$.error(e),Y.addFailedEvent({key:502702,error:e})}}preNodeReconnect(){this.pre.forEach(t=>{t.node?t.reconnect():t.preNodeReconnect()})}connectNext(t){this.next.forEach(e=>{t._connect(e.node)||e.connectNext(t)})}_connect(t){return!this.node||!t?!1:((this.node2||this.node).connect(t),this.connectedNodes.add(t),!0)}_disconnect(){this.connectedNodes.forEach(t=>{var e;return(e=this.node2||this.node)==null?void 0:e.disconnect(t)}),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(...t){return t.forEach(e=>{this.next.add(e),e.pre.add(this)}),this}},rd=class extends Pt{constructor(e=256){super();this.fftSize=e;u(this,"dataArray",new Uint8Array(0))}setNode(e){e.fftSize=this.fftSize,this.dataArray=new Uint8Array(e.frequencyBinCount),super.setNode(e)}getByteTimeDomainData(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),this.dataArray}get level(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),Math.max(...this.dataArray)/128-1}get timeDomainPathData(){let e=this.getByteTimeDomainData(),r=1,o=0,s=0,n=`M${o},${s}`;for(let d=0;d<e.length;d++)s=e[d]/128*100/2,n+=`L${o},${s}`,o+=r;return n}},ma=class{constructor(){u(this,"source",new Pt);u(this,"gain",new Pt);u(this,"destination",new Pt)}get volume(){var t;return((t=this.gain.node)==null?void 0:t.gain.value)||1}setVolume(t){if(t===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(et().createGain()),this.gain.node.gain.value=t}replaceSource(t){this.source.replaceNode(ql(t))}get track(){var t;return(t=this.stream)==null?void 0:t.getAudioTracks()[0]}get stream(){var t;return(t=this.destination.node)==null?void 0:t.stream}},Fs=class extends ma{constructor(e){super();this.context=e;u(this,"denoiser",new Pt);u(this,"voiceChanger",new Pt);this.source.pipeTo(this.denoiser.pipeTo(this.voiceChanger.pipeTo(this.gain.pipeTo(this.destination))))}connect(){this.context.inputs.has(this)||(this.destination.setNode(this.context.destination),this.source.setContext(this.context),this.denoiser.setContext(this.context),this.voiceChanger.setContext(this.context),this.gain.setContext(this.context),this.context.inputs.add(this))}disconnect(){this.context.inputs.has(this)&&(this.destination.deleteNode(),this.source.removeContext(),this.denoiser.removeContext(),this.voiceChanger.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.denoiser.deleteNode(),this.voiceChanger.deleteNode(),this.source.deleteNode(),this.disconnect()}setVolume(e){if(e===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(this.context.audioContext.createGain()),this.gain.node.gain.value=e}},id=class{constructor(){u(this,"audioContext",et("audio-mixer"));u(this,"destination",this.audioContext.createMediaStreamDestination());u(this,"inputs",new Set);u(this,"mixWeight",0);this.destination.channelCount=1}addMixWeight(t=1){this.mixWeight+=t,this.mixWeight-1===t+1>>1&&this.mixOnChange()}reduceMixWeight(t=1){this.addMixWeight(-t)}close(){this.inputs.forEach(t=>t.remove())}get mixTrack(){return this.destination.stream.getAudioTracks()[0]}},Yh=new WeakMap;function ql(i){let t=Yh.get(i);if(t)return t;let e=et();if(i instanceof HTMLAudioElement)t=e.createMediaElementSource(i);else if(i instanceof MediaStreamTrack)t=e.createMediaStreamSource(new MediaStream([i]));else return i;return Yh.set(i,t),t}var Kt=class Kt{constructor(t){u(this,"_volume",0);u(this,"_volumeDb",0);u(this,"_log");u(this,"_scriptProcessorNode",null);u(this,"_audioWorkletNode",null);u(this,"_interval",200);u(this,"ready",this.preload());let{log:e}=t;this._log=e,H.on(L.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-Kt.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!Kt.workletReady){let t='class VolumeMeterWorklet extends AudioWorkletProcessor{constructor(){super(),this.volume=0,this.intervalTime=200,this.tick=200,this.isStop=!1,this.cache=[],this.sentFirstInfo1=!1,this.unmute=!1,this.port.onmessage=t=>{var e=t.data;switch(e.name){case"chunk":this.cache.push(...e.data),this.sentFirstInfo1||(this.port.postMessage({cl:e.data.length}),this.sentFirstInfo1=!0);break;case"setIntervalTime":this.intervalTime=e.intervalTime;break;case"unmute":this.unmute=!0;break;case"stop":this.isStop=!0}}}process(t,s){t=t[0],s=s[0];if(t||s){if(this.isStop)return!1;var i=s&&s[0]?s[0].length:0,h=this.cache.length,a=(i<h?(s[0].set(this.cache.slice(0,i)),this.cache=this.cache.slice(i)):this.unmute&&s[0].set(t[0]),(i<h?s:t)[0]);if(a){let e=0;for(let t=0;t<a.length;++t)e=Math.max(Math.abs(a[t]),e);s=a.reduce((t,e)=>t+e*e,0)/a.length;this.volume=e,this.tick-=a.length,this.tick<0&&(this.tick+=this.intervalTime/1e3*sampleRate,this.port.postMessage({volume:this.volume,volumeDb:Math.max(10*Math.log10(s)+100,0)/100,cacheLen:h,outputLen:i}))}}return!0}}registerProcessor("volume-meter",VolumeMeterWorklet);';Kt.workletReady=Po(Kt.audioContext,URL.createObjectURL(new Blob([t],{type:"application/javascript"})))}return Kt.workletReady.then(()=>this.initAudioWorklet()).catch(t=>(this._log.error(`volumeMeter preload error: ${t}`),this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(Kt.audioContext,"volume-meter");let t=!1;this._audioWorkletNode.port.onmessage=e=>{Kt.lastMessageTime=Date.now(),this._volume=e.data.volume||0,this._volumeDb=e.data.volumeDb||0,!t&&e.data.cacheLen&&e.data.outputLen&&(this._log.warn("worklet play success"),t=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(t){this._log.error(`volumeMeter init audio worklet error: ${t}`),Be.logFailedEvent({userId:this._log.userId,eventType:Xr.LOAD_WORKLET,error:t}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=et("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=t=>{Kt.lastMessageTime=Date.now();let e=t.inputBuffer.getChannelData(0),r=0;for(let o=0;o<e.length;++o)r+=e[o]*e[o];this._volume=Math.sqrt(r/e.length)||0}}catch(t){this._log.error(`volumeMeter init script processor error: ${t}`)}}destroy(){this._scriptProcessorNode&&(this._scriptProcessorNode.onaudioprocess=null),this._audioWorkletNode&&(this._audioWorkletNode.port.postMessage({name:"stop"}),this._audioWorkletNode.port.onmessage=null),this._audioWorkletNode=null,this._scriptProcessorNode=null,H.off(L.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}getVolumeDb(){return Math.floor(this._volumeDb*100)}handleAudioLevelInterval(t){var r;let{interval:e}=t;this._interval=e,(r=this._audioWorkletNode)==null||r.port.postMessage({name:"setIntervalTime",intervalTime:e})}};u(Kt,"lastMessageTime",0),u(Kt,"audioContext",et("volume-meter")),u(Kt,"workletReady");var od=Kt,sd=class extends Pt{constructor(e){super();u(this,"_volumeMeter");this._volumeMeter=new od(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return y(this,null,function*(){yield this._volumeMeter.preload(),this.setNode(this._volumeMeter.node)})}getCalculatedVolume(){return this._volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this._volumeMeter.getInternalAudioLevel()}getVolumeDb(){return this._volumeMeter.getVolumeDb()}write(e){if(this.node){let r=e.allocationSize({planeIndex:0}),o=new Float32Array(r>>2);e.copyTo(o,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:o},[o.buffer]),e.close()}}},nd=od;var tf=Mi($i(),1);var Kh=i=>t=>t.deviceId===i;var pa=class{constructor(t,e="Input"){u(this,"kind");u(this,"type");u(this,"devices",[]);this.kind=t,this.type=e}update(t,e){let r=t.filter(o=>o.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);if(this.devices.length===1&&$s(this.devices[0])){this.devices=r;return}e&&(r.forEach(o=>{if(o.deviceId&&!this.devices.find(Kh(o.deviceId))){let s=`${this.kind}${this.type}Added`;$.warn(`${s}: ${JSON.stringify(o)}`),e.emit(s,o)}}),this.devices.forEach(o=>{if(o.deviceId&&!r.find(Kh(o.deviceId))){let s=`${this.kind}${this.type}Removed`;$.warn(`${s}: ${JSON.stringify(o)}`),e.emit(s,o)}})),this.devices=r}hasDevice(t){return!!this.devices.find(e=>e.deviceId===t)}},Jl=class extends tf.EventEmitter{constructor(){super();u(this,"audioInputs",new pa(D.AUDIO));u(this,"videoInputs",new pa(D.VIDEO));u(this,"audioOutputs",new pa(D.AUDIO,"Output"));this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||At.run("interval",()=>{this.update()},{delay:1e4}))}init(){ad().then(e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)})}update(){return y(this,arguments,function*(e=0){let r=yield ad(e);return this.audioInputs.update(r,this),this.videoInputs.update(r,this),this.audioOutputs.update(r,this),this})}},Tt=In||us?null:new Jl;function $s(i){return i.deviceId===i.groupId&&i.groupId===""}function ad(){return y(this,arguments,function*(i=0){if(ai()||!Yc())return[];let t=yield navigator.mediaDevices.enumerateDevices();if(i!==0){let e={audio:!1,video:!1};if(t.forEach(r=>{$s(r)&&(r.kind===D.AUDIO_INPUT?e.audio=!0:r.kind===D.VIDEO_INPUT&&(e.video=!0))}),i===2&&(e.audio=!1),i===1&&(e.video=!1),e.audio||e.video){let r;try{r=yield navigator.mediaDevices.getUserMedia(e),e.audio&&Vs()}catch(o){$.debug("capture before getDevices failed: ",o)}t=yield navigator.mediaDevices.enumerateDevices(),r==null||r.getTracks().forEach(o=>o.stop())}}return t.map((e,r)=>{let o={kind:e.kind,deviceId:e.deviceId,groupId:e.groupId,label:e.label||`${e.kind}_${r}`};return e.deviceId.length>0&&zl.add(`${e.deviceId}_${e.kind}`),e.getCapabilities&&(o.getCapabilities=()=>e.getCapabilities()),o})})}function Jt(i=!1){return Tt.update(i?1:0).then(t=>t.audioInputs.devices)}function er(i=!1){return Tt.update(i?2:0).then(t=>t.videoInputs.devices)}var ef=!1;function rf(){return y(this,null,function*(){try{ef||(ef=!0,$.info(`speakers:${(yield Wi()).map(i=>` ${i.deviceId.slice(0,8)}: ${i.label}`)}`))}catch(i){}})}function Wi(i=!1){return y(this,null,function*(){return(lt||Mt)&&(i=!1),Tt.update(i?1:0).then(t=>t.audioOutputs.devices)})}var zl=new Set;function of(i){if(i instanceof CanvasCaptureMediaStreamTrack||!(i instanceof MediaStreamTrack))return!1;let t=i.label.toLocaleLowerCase();if(t.includes("camera")||t.includes("webcam"))return!0;let r=`${((i==null?void 0:i.getSettings())||{}).deviceId}_${D.VIDEO_INPUT}`;return!!zl.has(r)}function sf(i){if(i instanceof CanvasCaptureMediaStreamTrack||!(i instanceof MediaStreamTrack))return!1;let t=i.label.toLocaleLowerCase();if(t.includes("mic")||t.includes("\u9EA6\u514B\u98CE"))return!0;let r=`${((i==null?void 0:i.getSettings())||{}).deviceId}_${D.AUDIO_INPUT}`;return!!zl.has(r)}function Xl(i,t){return y(this,null,function*(){let r=(yield Jt()).find(o=>o.deviceId===Io);return!t&&(r==null?void 0:r.groupId)===i||(r==null?void 0:r.groupId)===i&&r.label===t})}function nf(s){return y(this,arguments,function*({newDeviceId:i,oldDeviceId:t,oldGroupId:e,oldLabel:r,kind:o}){return i!==t?!1:o===D.AUDIO&&i===Io?yield Xl(e,r):!0})}var cd,Ql=class extends ma{constructor(e){super();this.log=e;u(this,"volumeMeter");u(this,"volumeDestination");u(this,"analyser",new rd);this.volumeMeter=new sd({log:this.log}),this.volumeDestination=new Pt,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},dd=class i extends $r{constructor(e){super(e,D.AUDIO);u(this,"_outputDeviceId");u(this,"_volume",1);u(this,"_destination",et("player").createMediaStreamDestination());u(this,"pipeline");u(this,"volumeMeterMode","worklet");this.mode=0,this.pipeline=new Ql(this._log)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(e){if((Fi==="15.2"||Fi==="15.3"||Fi==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}let o=cd||new Audio;o.setAttribute("autoplay","autoplay"),o.srcObject=this.getMediaStream(),o.muted=this.muted,this.element=o,je(e)&&(this.element.volume=Math.min(Math.max(e,0),1)),o===cd&&(cd=void 0),this.bindElementEvents()}play(e){return y(this,null,function*(){if(this.track)return this.pipeline.source.node||this.pipeline.replaceSource(this.track),this.element||this.initializeElement(e==null?void 0:e.volume),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),this.volumeMeterMode==="worklet"?this.pipeline.volumeMeter.init():this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(et("player").createAnalyser()),rf(),Ft(i.prototype,this,"play").call(this)})}stop(e=0){this.pipeline.destroy(),super.stop(e)}setSinkId(e){return y(this,null,function*(){var r,o;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield(o=(r=this.element).setSinkId)==null?void 0:o.call(r,e))})}get useDestination(){return!!this.pipeline.stream}setLoop(e){this.element&&(this.element.loop=e)}getAudioLevel(){return this.pipeline.volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this.pipeline.volumeMeter.getInternalAudioLevel()}},ud=class extends dd{setTrack(t){this.track!==t&&(this.unbindTrackEvents(),this.track=t,this.emit(Qe.MEDIA_TRACK_CHANGED,t),t&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([t]))))}setVolume(t){this._volume=t,this.element&&(this.element.volume=t)}},ld=class extends dd{constructor(e){super(e);u(this,"_sourceElement");u(this,"_output",new Pt);this.pipeline.source.pipeTo(this.pipeline.gain.pipeTo(this.pipeline.volumeMeter.pipeTo(this._output),this.pipeline.destination))}setOutput(){this.mode=1,this._output.setNode(et("player").destination)}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var r,o;((o=(r=this.element)==null?void 0:r.error)==null?void 0:o.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(Qe.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([e]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e])),this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){this._volume=e,this.useDestination?(this.pipeline.setVolume(e),this._log.info(`set pipeline volume: ${e}`)):e<=1?this.element?(this._log.info(`set element volume: ${e}`),this.element.volume=e):this._log.info("set element volume: no element"):lt||(this._log.info(`start set pipeline volume: ${e}`),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),mt(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play()))}stop(e=0){this.pipeline.destroy();let r=this._sourceElement||this.element;r&&Ui&&(cd=r),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}};var ko=class extends ne{constructor({userId:e,sdkAppId:r,mediaType:o,room:s,PlayerClass:n=o===1?ld:Zt}){var d;super();u(this,"id",Xn());u(this,"userId","");u(this,"isRemote");u(this,"mediaType");u(this,"room");u(this,"user");u(this,"_log");u(this,"_inputTrack");u(this,"_outputTrack");u(this,"isPlayCalled");u(this,"container",null);u(this,"player");u(this,"subVideoPlayerMap");u(this,"muted",!1);u(this,"abortCtrl");u(this,"objectFit","cover");u(this,"mirror");u(this,"isScreen",!1);u(this,"manager");u(this,"trackSettings");u(this,"isFirstVideoFrameEmitted",!1);this.userId=e||"",this.mediaType=o,this._log=$.createLogger({id:`${this.kind[0]}t`,userId:(d=s||this.room)==null?void 0:d.userId,remoteUserId:this instanceof di?void 0:this.userId,sdkAppId:r,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof di}),this.player=new n({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log}),this.player.on(Qe.PLAYER_STATE_CHANGED,p=>{H.emit(L.PLAYER_STATE_CHANGED,ee({track:this},p)),this.emit("player-state-changed",p)}),this.kind===D.VIDEO&&(this.player.on(Qe.LOADED_DATA,()=>{this.emitFirstVideoFrameEvent(Qe.LOADED_DATA),H.emit(L.VIDEO_LOADED_DATA,{track:this})}),this.player.on(Qe.LOADED_META_DATA,()=>{this.emitFirstVideoFrameEvent(Qe.LOADED_META_DATA)}),this.player.on(Qe.MEDIA_TRACK_CHANGED,p=>{var m;(m=this.subVideoPlayerMap)==null||m.forEach(g=>g.setTrack(p))})),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(Qe.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||$}get kind(){return this.mediaType===1?D.AUDIO:D.VIDEO}get strMediaType(){return this.mediaType===4?D.VIDEO:this.mediaType===2?D.SCREEN:D.AUDIO}get streamType(){return(this.mediaType&2)===0?"main":"auxiliary"}get isMediaTrackActive(){return this.mediaTrack?!this.mediaTrack.muted&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled:!1}play(e,r){return y(this,null,function*(){let o=st(e)?e[0]:e;if(this.isPlayCalled){this.log.info(`play update options: ${JSON.stringify(r)}`),r&&!V(r.muted)&&this.setPlayerMute(r.muted),r&&!V(r.objectFit)&&(this.objectFit=r.objectFit),this.player instanceof Zt&&(this.player.setObjectFit(this.objectFit),this.container!==o&&o&&(this.container=o,this.player.setContainer(o)),st(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),r)));return}if(r&&!V(r.muted)?this.setPlayerMute(r.muted):(!this.isRemote||this.kind===D.VIDEO)&&this.setPlayerMute(!0),r&&!V(r.objectFit)&&(this.objectFit=r.objectFit),this.player instanceof Zt&&(this.player.setObjectFit(this.objectFit),r&&!V(r.poster)&&this.player.setPoster(r.poster)),this.isPlayCalled=!0,o&&(this.container=o,this.player instanceof Zt&&this.player.setContainer(o)),H.emit(L.PLAY_TRACK_START,{track:this}),!this._outputTrack){this.log.info("play has not mediaTrack, abort");return}this._log.info(`play with options: ${JSON.stringify(r)}`);try{this.player.setTrack(this.playerMediaTrack),yield this.player.play(r),st(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),r))}catch(s){throw this.handleAutoPlayFailed(s),s}})}setMirror(e,r){if(this.isScreen||this.kind!==D.VIDEO||V(e)||e===this.mirror)return;this.mirror=e;let o=this.player;r&&(o=r);let s=this.manager;if(nt(this.mirror)){o.setViewMirror(this.mirror),s&&(s.mirror=!1);return}switch(this.mirror){case"view":{s&&(s.mirror=!1),o.setViewMirror(!0);break}case"publish":{s&&(s.mirror=!0),o.setViewMirror(!0);break}case"both":s&&(s.mirror=!0),o.setViewMirror(!1)}}playSubContainer(e,r){return y(this,null,function*(){if(!this._outputTrack||this.kind===D.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((s,n)=>{var d;e.find(p=>n===p)||(s.stop(),(d=this.subVideoPlayerMap)==null||d.delete(n))});for(let[s,n]of e.entries()){let d=this.subVideoPlayerMap.get(n);d?r&&(V(r.objectFit)||d.setObjectFit(r.objectFit)):this.subVideoPlayerMap.set(n,new Zt({id:this.userId||this.id,track:this.playerMediaTrack,container:n,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:`vp-sub${s+1}`})}))}let o=[...this.subVideoPlayerMap.values()];for(let s of o)s.setViewMirror(this.player.mirror),yield s.play()})}setAudioOutput(e){return this.player.setSinkId(e)}setAudioVolume(e){this.player.setVolume(e)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var e;return((e=this.player)==null?void 0:e.getInternalAudioLevel())||0}stop(e=!1){this.isPlayCalled&&(this.isPlayCalled=!1,this.player&&(this.log.info(`stop ${this.kind} player`),this.player.stop(Gu(this)&&!e?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(r=>{r.stop()}),this.container=null)}resume(){return y(this,null,function*(){var e;this.isPlayCalled&&(yield(e=this.player)==null?void 0:e.resume())})}close(){this.log.info("close"),this.isPlayCalled&&this.stop(!0)}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),H.emit(e?L.TRACK_MUTED:L.TRACK_UNMUTED,{track:this})}setPlayerMute(e){this.player.setMuted(e)}get mediaTrack(){return this._inputTrack||null}get outMediaTrack(){return this._outputTrack||null}get playerMediaTrack(){return this.outMediaTrack}installTrackEvent(e){xt(e,e).add(D.MUTE,this.onTrackMuted).add(D.UNMUTE,this.onTrackUnmuted).add(D.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===D.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){mt(e)}setInputMediaStreamTrack(e){var o;let r=this._inputTrack;if(e!==r)return this._inputTrack=e,this.trackSettings=(o=e.getSettings)==null?void 0:o.call(e),e.enabled=!this.muted,r&&this.uninstallTrackEvent(r),this.installTrackEvent(e),this.emit("input-media-track-changed",e||null,r||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var o;let r=this._outputTrack;e!==r&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",(o=e.getSettings)==null?void 0:o.call(e).deviceId,e.label),this._outputTrack=e,this._inputTrack&&(this._outputTrack.contentHint=this._inputTrack.contentHint,this._outputTrack.enabled=this._inputTrack.enabled),this.updatePlayingState(!!e),this.emit("output-media-track-changed",e))}setMediaType(e){this.mediaType=e}updatePlayingState(e){if(this.isPlayCalled){if(e){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped){this.player.play().catch(r=>this.handleAutoPlayFailed(r)),this.log.info(`playing state updated, play ${this.kind}`);return}}else if(!this.player.isStopped){this.player.stop(Gu(this)?this.jitterBufferDelay:0),this.log.info(`playing state updated, stop ${this.kind}`);return}}this.log.debug(`updatePlayingState abort ${this.isPlayCalled} ${e} ${this.player.isStopped}`)}handleAutoPlayFailed(e){if(this.room&&this.room.enableAutoPlayDialog)new zh;else{let r=()=>{this.resume().then(()=>{document.removeEventListener("click",r,!0)})};document.addEventListener("click",r,!0)}this.emit("error",e)}getVideoFrame(){return this.player instanceof Zt?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(e){var n,d,p;if(this.isFirstVideoFrameEmitted)return;let r=(n=this.mediaTrack)==null?void 0:n.getSettings(),o=(r==null?void 0:r.width)||((d=this.player.element)==null?void 0:d.videoWidth)||0,s=(r==null?void 0:r.height)||((p=this.player.element)==null?void 0:p.videoHeight)||0;e===Qe.LOADED_META_DATA&&!o&&!s||(e===Qe.LOADED_DATA&&!o&&!s&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,this.emit("first-video-frame",{width:o,height:s,streamType:this.streamType,userId:this.isRemote?this.userId:""}))}onTrackMuted(){this._log.warn(`${this.kind} track is unable to provide media output`)}onTrackUnmuted(){this._log.info(`${this.kind} track is able to provide media output`)}onTrackEnded(){this._log.warn(`${this.kind} track ended`)}};X([qe([],ne.INIT,{sync:!0})],ko.prototype,"close",1);var V_=Object.prototype.hasOwnProperty,{toString:xR}=Object.prototype;function F_(i){if(i==null)return!0;if(typeof i=="boolean")return!1;if(typeof i=="number")return i===0;if(typeof i=="string"||typeof i=="function"||Array.isArray(i))return i.length===0;if(i instanceof Error)return i.message==="";if(Gt(i))switch(Object.prototype.toString.call(i)){case"[object File]":case"[object Map]":case"[object Set]":return i.size===0;case"[object Object]":{for(let t in i)if(V_.call(i,t))return!1;return!0}}return!1}var ha=F_;var $_=function(i){return y(this,null,function*(){let t=H_(i);$.info(`getUserMedia with constraints: ${JSON.stringify(t)}`);let e=[],r=[],o=["label","deviceId","groupId"];t.audio&&(e=yield Jt(),$.info(`microphones: ${ir(e.map(s=>Ee(ee({},s),{groupId:s.groupId.substring(0,8)})),{keysToInclude:o})}`)),t.video&&(r=yield er(),$.info(`cameras: ${ir(r,{keysToInclude:o})}`));try{let s=yield navigator.mediaDevices.getUserMedia(t);return Ml&&s.getTracks().forEach(n=>{$.info(`${n.kind} capabilities: ${ir(n.getCapabilities(),{keysToInclude:hc})}`)}),t.audio&&Vs(),s}catch(s){let{message:n}=s;throw s.name==="NotFoundError"&&(i.video&&r&&r.length===0&&(n=dt({key:ct.CAMERA_NOT_FOUND})),i.audio&&e&&e.length===0&&(n=dt({key:ct.MICROPHONE_NOT_FOUND}))),new he({code:te.INITIALIZE_FAILED,name:s.name,message:n,constraint:s.constraint})}})},B_=ki({retryFunction:$_,settings:{retries:3,timeout:500},onError:({error:i,retry:t,reject:e,retryFuncArgs:r,retriedCount:o})=>{let s=o+1;i.name==="NotReadableError"||i.name==="OverconstrainedError"?(s===1?(r[0].video&&(r[0].maxResolution=!1,(!Mt||r[0].width*r[0].height<=1920*1080)&&r[0].frameRate&&(r[0].frameRate=r[0].frameRate>10?10:5)),r[0].retryWhenExactFailed&&r[0].useExactDeviceId&&(r[0].useExactDeviceId=!1)):s===2?r[0].useDeviceIdOnly=!0:s===3&&!r[0].useExactDeviceId&&(r[0].useTrueAsConstraint=!0),t()):e(i),r[0].microphoneId&&af(r[0].microphoneId,!1),r[0].cameraId&&af(r[0].cameraId,!0)},onRetrying:i=>{$.warn(`getUserMedia NotReadableError observed, retrying [${i}/3]`)},onRetryFailed:i=>{Be.logFailedEvent({eventType:Xr.GET_USER_MEDIA_RETRY,error:i})},onRetrySuccess:i=>{Be.logSuccessEvent({eventType:Xr.GET_USER_MEDIA_RETRY}),Be.uploadEvent({log:`stat-${Xr.GET_USER_MEDIA_RETRY}-success-${i}`})}});function af(i,t){return y(this,null,function*(){let r=(t?yield er():yield Jt()).find(o=>o.deviceId===i);r&&Xe(r.getCapabilities)&&$.warn(ir(r.getCapabilities(),{keysToInclude:hc}))})}function H_(i){return{audio:W_(i),video:G_(i)}}function W_(i){if(!i.audio)return!1;if(i.useTrueAsConstraint)return!0;let t={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:i.sampleRate};return!ha(i.microphoneId)&&(t.deviceId=i.useExactDeviceId?{exact:i.microphoneId}:i.microphoneId,i.useDeviceIdOnly)?t:(je(i.channelCount)&&(t.channelCount=i.channelCount),nt(i.echoCancellation)&&!i.echoCancellation&&(t.echoCancellation=!1),nt(i.noiseSuppression)&&!i.noiseSuppression&&(t.noiseSuppression=!1),nt(i.autoGainControl)&&!i.autoGainControl&&(t.autoGainControl=!1),ha(t)?!0:t)}function G_(i){if(!i.video)return!1;if(i.useTrueAsConstraint)return!0;let{maxResolution:t=!0}=i,e={};return i.cameraId?e.deviceId=i.useExactDeviceId?{exact:i.cameraId}:i.cameraId:i.facingMode&&(e.facingMode=i.facingMode),i.useDeviceIdOnly&&!ha(e)?e:(i.width&&(e.width={ideal:i.width},t&&!Qt&&(e.width.max=i.width)),i.height&&(e.height={ideal:i.height},t&&!Qt&&(e.height.max=i.height)),Qt&&_r&&i.width&&i.height&&i.width*i.height<352*288&&(e.width=i.width,e.height=i.height),i.frameRate&&(e.frameRate=i.frameRate),ha(e)?!0:e)}var cf=B_;function Gi(i){return Me((t,e)=>function(...r){return y(this,null,function*(){let o=yield t.apply(this,r);return yield i.call(this,...r),o})})}function df(i){return Me((t,e)=>function(...r){return y(this,null,function*(){try{return yield t.apply(this,r)}catch(o){i.call(this,o)}})})}function Me(i){return function(t,e,r){return r.value=i(r.value,e),r}}var uf=(()=>{let i=!1,t=document.visibilityState;return()=>{document.visibilityState!==t&&$.info(`visibility change: ${document.visibilityState}`),!i&&(document.addEventListener("visibilitychange",()=>{$.info(`visibility change: ${document.visibilityState}`),t=document.visibilityState}),i=!0)}})();var j_=0,md=class{constructor(){u(this,"log",$.createLogger({id:`fq${++j_}`}));u(this,"isRunning",!1);u(this,"queue",[])}get length(){return this.queue.length}get lastQueueItem(){return this.length===0?null:this.queue[this.length-1]}push(t,e=!1){var s,n;let r=ee({},t),o=new Promise((d,p)=>{r.resolve=d,r.reject=p});return r.promise=o,e?this.length<=1?this.queue.push(r):(n=(s=this.lastQueueItem)==null?void 0:s.promise)==null||n.then(r.resolve,r.reject):this.queue.push(r),this.log.debug(`push ${this.length}`),this.isRunning||this.callNext(),o}shift(){let t=this.queue.shift();return this.log.debug(`shift ${this.length}`),t}callNext(){if(this.isRunning||this.length===0)return;this.log.debug("callNext ",this.length);let{fn:t,args:e,context:r,resolve:o,reject:s}=this.queue[0];this.isRunning=!0,t.apply(r,e).then(o,s).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},lf=new WeakMap,mf=new WeakMap;function pf(i=!1){return function(t,e,r){let o=r.value;return r.value=function(...s){let n=lf.get(this)||new md;return lf.set(this,n),n.push({fn:o,args:s,context:this},i)},r}}function pd(i){return function(t,e,r){let o=r.value,s=n=>i(...n);return r.value=function(...n){let d=mf.get(this)||new Map,p=d.get(s(n))||new md;return d.set(s(n),p),mf.set(this,d),p.push({fn:o,args:n,context:this})},r}}function hd(i,t){return Me((e,r)=>function(...o){let s=i;try{let n=e.apply(this,o),d=_e();return xi(n)?n.then(p=>(t?Y.addSuccessEvent({key:s,cost:_e()-d}):Y.addSuccessEvent({key:s}),p)).catch(p=>{throw Y.addFailedEvent({key:s,error:p}),p}):(Y.addSuccessEvent({key:s}),n)}catch(n){throw Y.addFailedEvent({key:s,error:n}),n}})}var Lo=class Lo extends ko{constructor(e,r){super({mediaType:e,PlayerClass:r});u(this,"isRemote",!1);u(this,"deviceId");u(this,"groupId","");u(this,"label","");u(this,"_isRecapturing",!1);u(this,"_lastRecaptureTime",0);u(this,"_onMuteTimeoutId",-1);u(this,"_encodeCheckTimeoutId",-1);u(this,"profile")}get enableEncodeFrame(){return!1}get isPublishing(){return this.state.toString()==="publishing"}get isPublished(){return this.state==="publish"}encodeFrame(e,r){throw new Error("Method not implemented.")}installTrackEvent(e){xt(e,e).add(D.MUTE,this.onTrackMuted).add(D.UNMUTE,this.onTrackUnmuted).add(D.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===D.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){mt(e)}setStateToCapture(){}capture(e){return y(this,null,function*(){var r;try{let o=_e();H.emit(L.LOCAL_TRACK_CAPTURE_START,{track:this});let s;e.customSource?(s=new MediaStream,s.addTrack(e.customSource)):((r=this.mediaTrack)==null||r.stop(),s=yield cf(e));let n=s.getTracks()[0];return yield this.setInputMediaStreamTrack(n),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),H.emit(L.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:_e()-o}),s}catch(o){throw H.emit(L.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:o}),this.log.error(`getUserMedia error observed ${o}`),o}})}setInputMediaStreamTrack(e){return this.state===ne.INIT&&this.setStateToCapture(),super.setInputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var r;if(super.setOutputMediaStreamTrack(e),this.isPublishing||this.isPublished)return(r=this.room)==null?void 0:r.replaceTrack(this)}publish(e,r){return this.room=e,this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),r}unpublish(){this.room&&this.room.localTracks.delete(this),H.emit(L.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return y(this,null,function*(){if(this.mediaTrack&&ks){let{deviceId:e,groupId:r}=this.mediaTrack.getSettings(),{label:o}=this.mediaTrack;(yield nf({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=o,r&&(this.groupId=r),ad().then(n=>{let d=n.find(p=>p.deviceId===e);d&&this.emit("2",d)}))}})}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(e=!1){return!(!this.deviceId||!this.mediaTrack||this.kind===D.AUDIO&&!sf(this.mediaTrack)||this.kind===D.VIDEO&&!of(this.mediaTrack)||this._isRecapturing||e&&_r&&Mt)}onTrackMuted(){if(super.onTrackMuted(),uf(),!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<ps){setTimeout(()=>this.onTrackMuted(),ps);return}this._onMuteTimeoutId=setTimeout(()=>y(this,null,function*(){var e;if((e=this.mediaTrack)!=null&&e.muted){if((lt||at)&&document.visibilityState!=="visible")return;this.recapture(yield this.getRecoverCaptureDeviceId())}}),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return y(this,null,function*(){if(Ft(Lo.prototype,this,"onTrackEnded").call(this),!!this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<ps){setTimeout(()=>this.onTrackEnded(),ps);return}this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e){return y(this,null,function*(){var o;if(this._isRecapturing||!this._inputTrack)return;this.log.warn("recapture trying"),(o=this._inputTrack)==null||o.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let r={useExactDeviceId:!0};if(e==="user"||e==="environment")r.facingMode=e;else{let s;(this.kind==="audio"?yield Jt():yield er()).find(d=>d.deviceId===e)&&(s=e),r.deviceId=s}return this.capture(r).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),H.emit(L.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(s=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${s.message}`),this.emit("5",s),H.emit(L.LOCAL_TRACK_RECAPTURE,{track:this,error:s})})})}getRecoverCaptureDeviceId(){return y(this,null,function*(){let e=this instanceof Sr;if(e&&this.facingMode)return this.facingMode;let{deviceId:r}=this;if(r){let o=(fa.get(r)||0)+1;if(fa.set(r,o),o>=3){let s=e?(yield er()).find(n=>!fa.has(n.deviceId)):(yield Jt()).find(n=>!fa.has(n.deviceId));s&&(this.log.warn(`${r} capture fail ${o} times, change new ${s.deviceId}`),r=s.deviceId)}}return r})}close(){var e;super.close(),this._inputTrack&&(this._inputTrack.stop(),this.uninstallTrackEvent(this._inputTrack)),(e=this.manager)==null||e.removeInput(this)}};X([qe(ne.INIT,"capture",{ignoreError:!0,sync:!0})],Lo.prototype,"setStateToCapture",1),X([pf()],Lo.prototype,"capture",1),X([qe("capture","publish",{ignoreError:!0,success(){var r,o;this.room.localTracks.add(this),H.emit(L.LOCAL_TRACK_PUBLISHED,{track:this}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),!((((o=(r=this.room)==null?void 0:r.networkQuality)==null?void 0:o.uplinkNetworkQuality)||0)>3)&&(this._encodeCheckTimeoutId=setTimeout(()=>{var n,d;if(!((((d=(n=this.room)==null?void 0:n.networkQuality)==null?void 0:d.uplinkNetworkQuality)||0)>3)&&this.isPublished&&this.isMediaTrackActive){let p=this.kind===D.AUDIO,m=this.stat.bytesSent>0;Y[m?"addSuccessEvent":"addFailedEvent"]({key:p?503700:513702}),m||(Y.addEnum({key:p?503701:513703,value:Jn()}),Be.uploadEvent({log:`stat-encode-failed-${this.kind}-${qn()||bo()}`,userId:this.userId}),this.log.warn("encode failed"),this.emit("6",this))}},5e3))},fail(e){let r="error";if(e.cause instanceof RTCError){let o=e.cause;o.message.includes("timeout")?r="timeout":o.code===te.API_CALL_ABORTED&&(r="api-call")}this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:r,error:e.cause||e})}}),hd(521714,!1)],Lo.prototype,"publish",1),X([Me(e=>function(){return y(this,null,function*(){let r=this.state==="publish"?"started":"starting";e.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:r,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)})}),qe([],"capture",{sync:!0})],Lo.prototype,"unpublish",1);var di=Lo,fa=new Map;H.on(L.SWITCH_DEVICE_SUCCESS,i=>{i.track.deviceId&&fa.delete(i.track.deviceId)});var ui=class i extends di{constructor(e){super(1,ud);u(this,"mediaType",1);u(this,"volume",0);u(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40});u(this,"playerMuted",!0);u(this,"pipeline");u(this,"earMonitorGainNode",new Pt);u(this,"_output",new Pt);u(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0});this.manager=e,this.pipeline=new Fs(e),this.pipeline.gain.pipeTo(this.earMonitorGainNode.pipeTo(this._output),this.player.pipeline.volumeMeter),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this)}get dbVolume(){return nd.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}setInputMediaStreamTrack(e){return y(this,null,function*(){let r=this.trackSettings||{};Y.addEnum({key:501701,value:r.channelCount||0,useUV:!1}),Y.addEnum({key:501702,value:r.sampleRate||0,useUV:!1}),Y.addEnum({key:502700,value:0});let{sampleRate:o,channelCount:s}=r;this._log.info(`local audio track input ${JSON.stringify({sampleRate:o,channelCount:s})}`),this.pipeline.replaceSource(e),yield Ft(i.prototype,this,"setInputMediaStreamTrack").call(this,e),this.updatePlayingState(!!e)})}capture({deviceId:e,customSource:r,useExactDeviceId:o=!0,retryWhenExactFailed:s=!0}){return super.capture({video:!1,audio:!0,microphoneId:e,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:o,retryWhenExactFailed:s,customSource:r})}switchDevice(e){return y(this,null,function*(){if(this.mediaTrack){if(this.deviceId===e)if(e===Io){if(yield Xl(this.groupId,this.label))return}else return;try{this.log.info(`switchDevice audio to: ${e}`),this.mediaTrack&&this.mediaTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0,retryWhenExactFailed:!1}),H.emit(L.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(r){throw this.log.error(`switch microphone failed ${r}`),this.deviceId&&this.recapture(this.deviceId),r}}})}listenDeviceChange(){Tt&&!Tt.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&Tt.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return y(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current microphone is lost: ${JSON.stringify(e)}`),tt(this.userId,{eventId:2003,param1:6,streamType:1});let r=yield Jt();r[0]?this.recapture(r[0].deviceId):Tt.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.log.warn(`microphone added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)}update3A(s){return y(this,arguments,function*({echoCancellation:e,noiseSuppression:r,autoGainControl:o}){let n=!1;!V(e)&&e!==this.profile.echoCancellation&&(this.profile.echoCancellation=e,n=!0),!V(r)&&r!==this.profile.noiseSuppression&&(this.profile.noiseSuppression=r,n=!0),!V(o)&&o!==this.profile.autoGainControl&&(this.profile.autoGainControl=o,n=!0),n&&this.deviceId&&(yield this.recapture(this.deviceId))})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&Y.addEnum({key:502700,value:2})}setAudioVolume(e){super.setAudioVolume(0),lt&&this.player.setMuted(!0),this.earMonitorGainNode.node||(this.earMonitorGainNode.setNode(et().createGain()),this._output.setNode(et().destination)),this.earMonitorGainNode.node.gain.value=e}enableTrackANS(e){if(!this._inputTrack)return;let r=this._inputTrack.getConstraints();return r.noiseSuppression=e,this._inputTrack.applyConstraints(r).catch(o=>this._log.warn(`${e?"enable":"disable"} ANS failed `,o))}addDenoiser(e){var r;if(ei<=92&&((r=this.trackSettings)==null?void 0:r.sampleRate)!==48e3){this._log.warn("denoiser only support sampleRate 48000 before chrome 93");return}Y.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.enableTrackANS(!1)}removeDenoiser(e){this.pipeline.denoiser.node===e&&(this.pipeline.denoiser.deleteNode(),this.enableTrackANS(!0))}close(){this.pipeline.remove(),this.earMonitorGainNode.deleteNode(),this._output.deleteNode(),Tt.off("audioInputAdded",this.handleMicrophoneAdded,this),Tt.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}recapture(e){return y(this,null,function*(){try{yield Ft(i.prototype,this,"recapture").call(this,e)}catch(r){let o=(yield Jt()).find(s=>s.deviceId!==e);if(o)yield Ft(i.prototype,this,"recapture").call(this,o.deviceId);else throw r}})}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduceRight((r,o)=>o?o({frame:r}):r,e):e}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}};var Uo=class{constructor(t,e=!1){this.dataView=t;this.isSEI&&(e?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let t=this.seiPayloadStartIndex,e=this.dataView.byteLength-2,r=[],o=0;for(let n=t;n<=e;n++){let d=this.dataView.getInt8(n);switch(d){case 0:case 1:case 2:case 3:o===2&&(r.push(3),o=0),d==0?o++:o=0,r.push(d);break;default:o=0,r.push(d);break}}r.push(this.dataView.getInt8(this.dataView.byteLength-1));let s=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,t),...r]).buffer);this.dataView=s}removePreventionByte(){let t=this.seiPayloadStartIndex,e=this.dataView.byteLength-1,r=[],o=0;for(let n=t;n<=e;n++)switch(this.dataView.getInt8(n)){case 0:o++,r.push(this.dataView.getInt8(n));break;case 3:o!==2&&r.push(this.dataView.getInt8(n)),o=0;break;default:r.push(this.dataView.getInt8(n)),o=0;break}let s=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,t),...r]).buffer);this.dataView=s}get isSEI(){return this.dataView.getUint8(4)===6}get seiPayloadStartIndex(){let t=6;for(let e=6;e<this.dataView.buffer.byteLength&&(t++,this.dataView.getUint8(e)===255);e++);return t}get seiPayloadType(){return this.isSEI?this.dataView.getUint8(5):null}get seiPayload(){if(!this.isSEI)return null;let t=0,e=6;for(let s=6;s<this.dataView.buffer.byteLength;s++){let n=this.dataView.getUint8(s);if(e++,n===255)t+=255;else{t+=n;break}}let r=new ArrayBuffer(t),o=new DataView(r);for(let s=0;s<r.byteLength;s++,e++)o.setInt8(s,this.dataView.getInt8(e));return o}};var fd=class{constructor(){u(this,"_seiMessageList",[]);u(this,"_smallSeiMessageList",[]);u(this,"_seiPayloadType",243)}encodeSEINalu(t){let e=t.byteLength,r=parseInt(String(e/255),10),o=e%255,s=[];s.push(0,0,0,1,6,this._seiPayloadType);for(let d=0;d<r;d++)s.push(255);s.push(o);let n=new DataView(t);return s.push(...new Uint8Array(n.buffer)),s.push(128),new Uo(new DataView(new Uint8Array(s).buffer),!0)}sendSEI(t,e){e!=null&&e.seiPayloadType&&(this._seiPayloadType=e.seiPayloadType),this._seiMessageList.push(t),e!=null&&e.small&&this._smallSeiMessageList.push(t)}isEmpty(){return!this._seiMessageList.length}getNaluCount(t){let e=0,r=0,o=new DataView(t);for(let s=0;s<t.byteLength;s++)switch(o.getUint8(s)){case 0:e++;break;case 1:(e===2||e===3)&&r++,e=0;break;default:e=0;break}return r}encode(t,e){let r=e?this._smallSeiMessageList:this._seiMessageList;if(r.length>0&&t.data.byteLength>0){let s=9-this.getNaluCount(t.data);if(s<=0)return 0;let n=r.splice(0,s).reverse().map(this.encodeSEINalu.bind(this)),d=n.reduce((b,N)=>b+N.dataView.byteLength,0),p=new ArrayBuffer(d+t.data.byteLength),m=new DataView(p),g=new DataView(t.data),_=0;for(let b=0;b<n.length;b++)for(let N=0;N<n[b].dataView.byteLength;N++)m.setInt8(_++,n[b].dataView.getInt8(N));for(let b=0;b<t.data.byteLength;b++)m.setInt8(_++,g.getInt8(b));return t.data=p,n.length}return 0}};var Vo=class Vo extends di{constructor(e,r=4){super(r,Zt);u(this,"profile",{width:640,height:480,frameRate:15,bitrate:500});u(this,"avoidCropping",!1);u(this,"_scaleResolutionDownBy");u(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0});u(this,"small");u(this,"isNeedToSetBandwidth");u(this,"muteImage");u(this,"manager");u(this,"_seiCodec",new fd);this.manager=e;let o=()=>{this.isAllowed2k4k(this.profile)?this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1}):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),this.setProfile(Ee(ee({},this.profile),{width:1920,height:1080})),this.applyProfile())};this.on("input-media-track-changed",o),this.on("publish",o),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(!(!ks||!this.mediaTrack))return this.mediaTrack.getSettings().facingMode}get isQosClearFirst(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)==="detail"}setMute(e){return y(this,null,function*(){var r,o,s;if(we(e)){if(this.muteImage===e)return;yield(r=this.manager)==null?void 0:r.deleteWatermark("mute"),yield(o=this.manager)==null?void 0:o.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:e}),this.muteImage=e,Ft(Vo.prototype,this,"setMute").call(this,!1)}else yield(s=this.manager)==null?void 0:s.deleteWatermark("mute"),this.muteImage=void 0,Ft(Vo.prototype,this,"setMute").call(this,e)})}capture({deviceId:e,facingMode:r,useExactDeviceId:o=!0,customSource:s,retryWhenExactFailed:n=!0}){return super.capture({audio:!1,video:!0,facingMode:r||this.facingMode,cameraId:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:o,retryWhenExactFailed:n,customSource:s})}setProfile(e){let r=ee({},e),o=r.width>r.height;r.width*r.height<=160*120&&at&&Kr&&(this.log.warn(`resolution is ${r.width}*${r.height}, fallback to 240*180`),r.width=o?240:180,r.height=o?180:240,r.bitrate=Math.max(r.bitrate,150)),r.width*r.height>1280*720&&il&&(r.width=o?1280:720,r.height=o?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),this.avoidCropping&&(Kr||Qt)&&!ol()&&r.width*r.height<=640*360&&r.width/r.height===16/9&&(this._scaleResolutionDownBy=1280/r.width,r.width=1280,r.height=720,this.log.warn(`capture 720p, scale: ${this._scaleResolutionDownBy}`)),r.bitrate&&(this.isNeedToSetBandwidth=r.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile)?super.setProfile(r):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),super.setProfile(Ee(ee({},this.profile),{width:1920,height:1080})))}applyProfile(){return y(this,null,function*(){var o;if(!this.mediaTrack)return;let e=this.settings;if(!(!(e.height!==this.profile.height||e.width!==this.profile.width||e.frameRate!==this.profile.frameRate)||!this.deviceId)&&(Yt===16?yield this.recapture(this.deviceId):(yield(o=this.mediaTrack)==null?void 0:o.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}),this.manager&&this.manager.changeInput(this)),this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1}),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth))return this.isNeedToSetBandwidth=!1,this.room.setBandWidth({bandwidth:this.profile.bitrate,type:D.VIDEO,videoType:D.BIG})})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate};return ks&&this.mediaTrack&&Object.assign(e,this.mediaTrack.getSettings()),e}get scaleResolutionDownBy(){if(this._scaleResolutionDownBy)return this._scaleResolutionDownBy;let{settings:e}=this;return e.width===this.profile.width&&e.height===this.profile.height?1:_c()&&this.profile.width>this.profile.height&&e.height>e.width?Math.max(e.width/this.profile.height,e.height/this.profile.width,1):Math.max(e.width/this.profile.width,e.height/this.profile.height,1)}isAllowed2k4k(e){var r;return!this.room||!this.room.scheduleResult||this.isScreen||e.height*e.width<2560*1440?!0:((r=this.room.scheduleResult.trtcAutoConf)==null?void 0:r["2k4k"])===1}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}switchDevice(e){return y(this,null,function*(){try{if(!this.isNeedToSwitchDevice(e))return;let r={useExactDeviceId:!0,retryWhenExactFailed:!1};e==="user"||e==="environment"?r.facingMode=e:r.deviceId=e,this.mediaTrack.stop(),yield this.capture(r),H.emit(L.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(r){throw this.log.error(`switch camera failed ${r}`),this.deviceId&&this.recapture(this.deviceId),r}})}listenDeviceChange(){Tt&&!Tt.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&Tt.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return y(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current camera is lost: ${JSON.stringify(e)}`),tt(this.userId,{eventId:2003,param1:7,streamType:2});let r=yield er();r[0]?this.recapture(r[0].deviceId):Tt.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return y(this,null,function*(){this.log.warn(`camera added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)})}encodeFrame(e,r){if(!this.manager)return e;let o=r?8:this.mediaType;return this.manager.encodePipeline.reduceRight((s,n)=>n?n({frame:s,mediaType:o}):s,e)}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}play(e,r){return V(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,r)}close(){Tt.off("videoInputAdded",this.handleCameraAdded,this),Tt.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return y(this,null,function*(){try{yield Ft(Vo.prototype,this,"recapture").call(this,e)}catch(r){let o=(yield er()).find(s=>s.deviceId!==e);if(o)yield Ft(Vo.prototype,this,"recapture").call(this,o.deviceId);else throw r}})}setContentHint(e){this.mediaTrack&&"contentHint"in this.mediaTrack&&(this.mediaTrack.contentHint!==e&&(this.log.info(`setContentHint ${e}`),this.mediaTrack.contentHint=e),this.outMediaTrack&&this.outMediaTrack.contentHint!==e&&(this.outMediaTrack.contentHint=e))}};X([Gi(function(e){this.setContentHint(e.contentHint||"motion")})],Vo.prototype,"capture",1);var Sr=Vo;var gf=Xn();if(typeof navigator!="undefined"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:gf,exposeOrigin:!0,permittedOrigins:["*"]})}catch(i){}var z_=function(i){return y(this,null,function*(){let t=null,e=Y_(i);$.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let r=yield navigator.mediaDevices.getDisplayMedia(e);i.systemAudio&&r.getAudioTracks().length===0&&(Ds&&ei<74||Mt||Qt)&&$.warn("Your browser not support capture system audio");let o=r.getVideoTracks()[0];if(o){if(i.frameRate)try{yield o.applyConstraints({frameRate:{min:i.frameRate,ideal:i.frameRate},width:i.width,height:i.height})}catch(s){$.warn(`screen applyConstraints failed: ${s}`)}i.captureElement&&(yield X_(o,i.captureElement))}if(i.audio){let s=Q_(i);$.info(`getUserMedia with constraints: ${JSON.stringify(s)}`),t=yield navigator.mediaDevices.getUserMedia(s),r.addTrack(t.getAudioTracks()[0])}return r})};function X_(i,t){return y(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&Xe(i.cropTo))try{if(!(((e=i.getCaptureHandle())==null?void 0:e.handle)===gf))return;let o=yield CropTarget.fromElement(t);yield i.cropTo(o)}catch(r){$.warn(`cropTo target failed ${r}`)}})}function Q_(i){let t={echoCancellation:i.echoCancellation,autoGainControl:i.autoGainControl,noiseSuppression:i.noiseSuppression,sampleRate:i.sampleRate,channelCount:i.channelCount};return V(i.microphoneId)||(t.deviceId=i.microphoneId),{audio:t,video:!1}}function Y_(i){let t={preferCurrentTab:i.preferDisplaySurface==="current-tab"||!!i.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:Mt?{max:i.width}:{ideal:i.width,max:i.width},height:Mt?{max:i.height}:{ideal:i.height,max:i.height},frameRate:i.frameRate,displaySurface:i.preferDisplaySurface||"monitor"};if(t.video=e,i.systemAudio){let{echoCancellation:r=!0,noiseSuppression:o=!1,autoGainControl:s=!1}=i;t.audio={echoCancellation:r,noiseSuppression:o,autoGainControl:s,sampleRate:48e3}}return t}var Ef=z_;var ji=class extends Sr{constructor(e){super(e,2);u(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600});u(this,"objectFit","contain");u(this,"isScreen",!0);this._log.id=`s-${this._log.id}`}capture(g){return y(this,arguments,function*({systemAudio:e=!1,autoGainControl:r,echoCancellation:o,noiseSuppression:s,audioTrack:n,videoTrack:d,captureElement:p,preferDisplaySurface:m}){try{let _;return d||n?(_=new MediaStream,d&&_.addTrack(d),n&&_.addTrack(n)):_=yield Ef({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:r,echoCancellation:o,noiseSuppression:s,captureElement:p,preferDisplaySurface:m}),yield this.setInputMediaStreamTrack(_.getVideoTracks()[0]),_}catch(_){throw this.log.error(`getDisplayMedia error observed ${_}`),_ instanceof he?_:new he({code:te.INITIALIZE_FAILED,name:_.name,message:_.message})}})}switchDevice(e){return y(this,null,function*(){throw new Error("Method not implemented.")})}};X([Gi(function(e){this.setContentHint(e.contentHint||"detail")})],ji.prototype,"capture",1);var Fo=class extends ui{constructor(t){super(t),this._log.id=`s-${this._log.id}`}};var Z_="registerProcessor('dumper', class extends AudioWorkletProcessor {process(inputs) {this.port.postMessage(inputs);return true;}});",Zl;function ga(i){return y(this,null,function*(){let t=et("dump");Zl||(Zl=Po(t,URL.createObjectURL(new Blob([Z_],{type:"application/javascript"})))),yield Zl;let e=new AudioWorkletNode(t,"dumper",{numberOfInputs:i.length,numberOfOutputs:0});return i.forEach((r,o)=>r.connect(e,0,o)),new ReadableStream({start(r){e.port.onmessage=o=>{r.enqueue(o.data)}},cancel(){i.forEach(r=>r.disconnect(e)),e.port.close()}})})}var gd=class extends id{constructor(e){super();this.room=e;u(this,"_localAudioTrack");u(this,"_localScreenAudioTrack");u(this,"log",$.createLogger({id:"am"}));u(this,"denoiser");u(this,"voiceChanger");u(this,"mixChangedDebounce");u(this,"encodePipeline",[]);u(this,"decodePipeline",[]);e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId))}get _localAudioPipline(){var e;return(e=this._localAudioTrack)==null?void 0:e.pipeline}dump(e){var g,_;if(!this._localAudioTrack)return;let r=[],o=[];(g=this._localAudioPipline)!=null&&g.source.node&&(r.push(this._localAudioPipline.source.node),o.push("mic")),(_=this._localAudioPipline)!=null&&_.denoiser.node&&(r.push(this._localAudioPipline.denoiser.node),o.push("mic-processed")),this.mixWeight>1&&(r.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),o.push("mix")),this.log.info(`dump audio track ${o}, duration: ${e}`);let s=new AbortController,n=[],d=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),s.abort("timeout")},e*1e3),p=()=>{for(let b=0;b<o.length;b++){let N=URL.createObjectURL(new Blob(n[b])),k=document.createElement("a");k.href=N,k.download=`${o[b]}.pcm`,k.style.display="none",document.body.appendChild(k),k.click(),URL.revokeObjectURL(N),k.remove()}clearTimeout(d),s.abort("download")},m=ga(r).then(b=>b.pipeTo(new WritableStream({write(N){N.forEach((k,P)=>n[P]=n[P]?n[P].concat(k[0]):[k[0]])}}),s).catch(N=>p));return{then:m.then.bind(m),download:p}}getPCM(e){var n;if(V(WritableStream)){this.log.warn("getPCM failed: browser not support WritableStream");return}if(!((n=this._localAudioPipline)!=null&&n.source.node)){this.log.warn("getPCM failed: no local audio track");return}this.log.warn("getPCM");let r=new Float32Array(1920),o=0,s=new AbortController;return ga([this._localAudioPipline.source.node]).then(d=>d.pipeTo(new WritableStream({write(p){p[0][0]&&(r.set(p[0][0],o),o+=p[0][0].length,o>=1920&&(o=0,e(r),r=new Float32Array(1920)))}}),s).catch(p=>this.log.warn(`stop getPCM reason:${p}`))),s}get hasScreenAudioTrack(){return this._localScreenAudioTrack!==null}get hasAudioTrack(){return!V(this._localAudioTrack)}changeInput(e){if(e instanceof Fo)return this._localScreenAudioTrack=e,e.pipeline.connect(),this.mixOnChange();if(e instanceof ui)return this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),e.pipeline.connect(),this.mixOnChange();if(e instanceof $o)return e.setOutputMediaStreamTrack(e.mediaTrack)}mixOnChange(){return this.mixChangedDebounce||(this.mixChangedDebounce=Promise.resolve().then(()=>{var e,r;return delete this.mixChangedDebounce,Promise.all([(e=this._localAudioTrack)==null?void 0:e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),(r=this._localScreenAudioTrack)==null?void 0:r.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)])})),this.mixChangedDebounce}removeInput(e){e instanceof Fo?delete this._localScreenAudioTrack:e instanceof ui?delete this._localAudioTrack:e instanceof $o}addDenoiser(e){var r;this.denoiser=e,(r=this._localAudioTrack)==null||r.addDenoiser(e)}removeDenoiser(e){var r;delete this.denoiser,(r=this._localAudioTrack)==null||r.removeDenoiser(e)}addVoiceChanger(e,r){var o;this.voiceChanger=[e,r],(o=this._localAudioTrack)==null||o.pipeline.voiceChanger.setNode(e,r)}removeVoiceChanger(){var e;delete this.voiceChanger,(e=this._localAudioTrack)==null||e.pipeline.voiceChanger.deleteNode()}destroy(){this.close()}addEncodeProcessor({processor:e,type:r}){var o;this.encodePipeline.includes(e)||(this.encodePipeline[r]=e,(o=this.room)==null||o.enableInsertableStreams())}addDecodeProcessor({processor:e,type:r}){var o;this.decodePipeline.includes(e)||(this.decodePipeline[r]=e,(o=this.room)==null||o.enableInsertableStreams())}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}};function _f(i=30,t=2){return Me((e,r)=>function(...o){return new Promise((s,n)=>{let d=setTimeout(()=>{let p=new he({code:te.API_CALL_TIMEOUT,message:`checkPendingPromise ${r}() timeout ${i}s`});$.warn(p),t===2?n(p):t===1&&s()},i*1e3);e.apply(this,o).then(s,n).finally(()=>{clearTimeout(d)})})})}var Um={};Jr(Um,{Events:()=>it,Inspect:()=>or,LastSink:()=>Bo,Sink:()=>de,Subscribe:()=>Ho,TimeoutError:()=>Ea,audit:()=>xT,bindCallback:()=>_T,bindNodeCallback:()=>TT,buffer:()=>aT,bufferCount:()=>nT,bufferTime:()=>ZT,call:()=>Tf,catchError:()=>xm,combineLatest:()=>Sf,concat:()=>tT,concatMap:()=>GT,concatMapTo:()=>jT,count:()=>yT,create:()=>Oe,debounce:()=>PT,debounceTime:()=>kT,defer:()=>yf,delay:()=>KT,deliver:()=>pe,dispose:()=>Ed,elementAt:()=>LT,empty:()=>Ia,every:()=>BT,exhaustMap:()=>zT,exhaustMapTo:()=>XT,filter:()=>yr,find:()=>UT,findIndex:()=>VT,first:()=>FT,fromAnimationFrame:()=>gT,fromArray:()=>uT,fromEvent:()=>be,fromEventPattern:()=>lT,fromFetch:()=>mT,fromIterable:()=>pT,fromPromise:()=>Rf,fromReadableStream:()=>fT,fromReader:()=>hT,groupBy:()=>QT,identity:()=>K_,ignoreElements:()=>vT,iif:()=>iT,inspect:()=>If,interval:()=>sm,last:()=>$T,map:()=>Ji,mapTo:()=>WT,max:()=>AT,merge:()=>im,mergeMap:()=>qT,mergeMapTo:()=>JT,min:()=>bT,never:()=>IT,nothing:()=>Ve,of:()=>dT,pairwise:()=>HT,pipe:()=>Se,race:()=>om,range:()=>ET,reduce:()=>nm,retry:()=>rI,scan:()=>Om,share:()=>li,shareReplay:()=>rT,skip:()=>DT,skipUntil:()=>NT,skipWhile:()=>yd,startWith:()=>_a,subject:()=>It,subscribe:()=>ke,sum:()=>RT,switchMap:()=>zi,switchMapTo:()=>mi,take:()=>Ar,takeLast:()=>CT,takeUntil:()=>Je,takeWhile:()=>vf,tap:()=>Sa,throttle:()=>MT,throwError:()=>ST,timeInterval:()=>YT,timeout:()=>Lm,timer:()=>Ta,toPromise:()=>eI,toReadableStream:()=>tI,withLatestFrom:()=>sT,zip:()=>oT});function Ve(...i){}var Tf=i=>i(),K_=i=>i;function Ed(){this.dispose()}var If=()=>typeof __FASTRX_DEVTOOLS__!="undefined",eT=1,or=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(t){let e=new Kl(t,this,this.streamId++);return it.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},Bo=class{constructor(){this.defers=new Set,this.disposed=!1}next(t){}complete(){this.dispose()}error(t){this.dispose()}get bindDispose(){return()=>this.dispose()}dispose(){this.disposed=!0,this.complete=Ve,this.error=Ve,this.next=Ve,this.dispose=Ve,this.subscribe=Ve,this.doDefer()}subscribe(t){return t instanceof or?t.subscribe(this):t(this),this}get bindSubscribe(){return t=>this.subscribe(t)}doDefer(){this.defers.forEach(Tf),this.defers.clear()}defer(t){this.defers.add(t)}removeDefer(t){this.defers.delete(t)}reset(){this.disposed=!1,delete this.complete,delete this.next,delete this.dispose,delete this.next,delete this.subscribe}resetNext(){delete this.next}resetComplete(){delete this.complete}resetError(){delete this.error}},de=class extends Bo{constructor(t){super(),this.sink=t,t.defer(this.bindDispose)}next(t){this.sink.next(t)}complete(){this.sink.complete()}error(t){this.sink.error(t)}},Ho=class extends Bo{constructor(t,e=Ve,r=Ve,o=Ve){if(super(),this._next=e,this._error=r,this._complete=o,this.then=Ve,t instanceof or){let s={toString:()=>"subscribe",id:0,source:t};this.defer(()=>{it.defer(s,0)}),it.create(s),it.pipe(s),this.sourceId=s.id,this.subscribe(t),it.subscribe({id:s.id,end:!0}),e==Ve?this._next=n=>it.next(s,0,n):this.next=n=>{it.next(s,0,n),e(n)},o==Ve?this._complete=()=>it.complete(s,0):this.complete=()=>{this.dispose(),it.complete(s,0),o()},r==Ve?this._error=n=>it.complete(s,0,n):this.error=n=>{this.dispose(),it.complete(s,0,n),r()}}else this.subscribe(t)}next(t){this._next(t)}complete(){this.dispose(),this._complete()}error(t){this.dispose(),this._error(t)}};function Se(i,...t){return t.reduce((e,r)=>r(e),i)}function Oe(i,t,e){if(If()){let r=Object.defineProperties(Object.setPrototypeOf(i,or.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:t,writable:!0,configurable:!0},args:{value:e,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});it.create(r);for(let o=0;o<e.length;o++){let s=e[o];typeof s=="function"&&s instanceof or&&it.addSource(r,s)}return r}return i}function pe(i,t){return function(...e){return r=>{if(r instanceof or){let o=Oe(s=>{let n=new i(s,...e);n.sourceId=o.id,n.subscribe(r)},t,arguments);return o.source=r,it.pipe(o),o}else return o=>r(new i(o,...e))}}}function qi(i,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:i,payload:t}})}var Kl=class extends de{constructor(t,e,r){super(t),this.source=e,this.id=r,this.sourceId=t.sourceId,this.defer(()=>{it.defer(this.source,this.id)})}next(t){it.next(this.source,this.id,t),this.sink.next(t)}complete(){it.complete(this.source,this.id),this.sink.complete()}error(t){it.complete(this.source,this.id,t),this.sink.error(t)}},it={addSource(i,t){qi("addSource",{id:i.id,name:i.toString(),source:{id:t.id,name:t.toString()}})},next(i,t,e){qi("next",{id:i.id,streamId:t,data:e&&e.toString()})},subscribe({id:i,end:t},e){qi("subscribe",{id:i,end:t,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(i,t,e){qi("complete",{id:i.id,streamId:t,err:e?e.toString():null})},defer(i,t){qi("defer",{id:i.id,streamId:t})},pipe(i){qi("pipe",{name:i.toString(),id:i.id,source:{id:i.source.id,name:i.source.toString()}})},update(i){qi("update",{id:i.id,name:i.toString()})},create(i){i.id||(i.id=eT++),qi("create",{name:i.toString(),id:i.id})}},Ea=class extends Error{constructor(t){super(`timeout after ${t}ms`),this.timeout=t}};var _d=class extends Bo{constructor(t){super(),this.source=t,this.sinks=new Set}add(t){t.defer(()=>this.remove(t)),this.sinks.add(t).size===1&&(this.reset(),this.subscribe(this.source))}remove(t){this.sinks.delete(t),this.sinks.size===0&&this.dispose()}next(t){this.sinks.forEach(e=>e.next(t))}complete(){this.sinks.forEach(t=>t.complete()),this.sinks.clear()}error(t){this.sinks.forEach(e=>e.error(t)),this.sinks.clear()}};function li(){return i=>{let t=new _d(i);if(i instanceof or){let e=Oe(r=>{t.add(r)},"share",arguments);return t.sourceId=e.id,e.source=i,it.pipe(e),e}return Oe(t.add.bind(t),"share",arguments)}}function im(...i){return Oe(t=>{let e=new de(t),r=i.length;e.complete=()=>{--r===0&&t.complete()},i.forEach(e.bindSubscribe)},"merge",arguments)}function om(...i){return Oe(t=>{let e=new Map;i.forEach(r=>{let o=new de(t);e.set(r,o),o.complete=()=>{e.delete(r),e.size===0?t.complete():o.dispose()},o.next=s=>{e.delete(r),e.forEach(n=>n.dispose()),o.resetNext(),o.resetComplete(),o.next(s)}}),i.forEach(r=>e.get(r).subscribe(r))},"race",arguments)}function tT(...i){return Oe(t=>{let e=0,r=i.length,o=new de(t);o.complete=()=>{e<r&&!o.disposed?(o.doDefer(),o.subscribe(i[e++])):t.complete()},o.complete()},"concat",arguments)}function rT(i){return t=>{let e=new _d(t),r=[];return e.next=function(o){r.push(o),r.length>i&&r.shift(),this.sinks.forEach(s=>s.next(o))},Oe(o=>{o.defer(()=>e.remove(o)),r.forEach(s=>o.next(s)),e.add(o)},"shareReplay",arguments)}}function iT(i,t,e){return Oe(r=>i()?t(r):e(r),"iif",arguments)}function Sf(...i){return Oe(t=>{let e=i.length,r=e,o=e,s=new Array(e),n=()=>{--o===0&&t.complete()},d=(p,m)=>{let g=new de(t);g.next=_=>{--r===0?(g.next=b=>{s[m]=b,t.next(s)},g.next(_)):s[m]=_},g.complete=n,g.subscribe(p)};i.forEach(d)},"combineLatest",arguments)}function oT(...i){return Oe(t=>{let e=i.length,r=e,o=new Array(e),s=()=>{--r===0&&t.complete()},n=(d,p)=>{let m=new de(t),g=[];o[p]=g,m.next=_=>{g.push(_),o.every(b=>b.length)&&t.next(o.map(b=>b.shift()))},m.complete=s,m.subscribe(d)};i.forEach(n)},"zip",arguments)}function _a(...i){return t=>Oe((e,r=0,o=i.length)=>{for(;r<o&&!e.disposed;)e.next(i[r++]);e.disposed||e.subscribe(t)},"startWith",arguments)}var em=class extends de{constructor(t,...e){super(t);let r=new de(this.sink);r.next=o=>this.buffer=o,r.complete=Ve,r.subscribe(Sf(...e))}next(t){this.buffer&&this.sink.next([t,...this.buffer])}},sT=pe(em,"withLatestFrom"),tm=class extends de{constructor(t,e,r){super(t),this.bufferSize=e,this.startBufferEvery=r,this.buffer=[],this.count=0,this.startBufferEvery&&(this.buffers=[[]])}next(t){this.startBufferEvery?(this.count++===this.startBufferEvery&&(this.buffers.push([]),this.count=1),this.buffers.forEach(e=>{e.push(t)}),this.buffers[0].length===this.bufferSize&&this.sink.next(this.buffers.shift())):(this.buffer.push(t),this.buffer.length===this.bufferSize&&(this.sink.next(this.buffer),this.buffer=[]))}complete(){this.buffer.length?this.sink.next(this.buffer):this.buffers.length&&this.buffers.forEach(t=>this.sink.next(t)),super.complete()}},nT=pe(tm,"bufferCount"),rm=class extends de{constructor(t,e){super(t),this.buffer=[];let r=new de(t);r.next=o=>{t.next(this.buffer),this.buffer=[]},r.complete=Ve,r.subscribe(e)}next(t){this.buffer.push(t)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},aT=pe(rm,"buffer");var cT=function(i,t,e,r){function o(s){return s instanceof e?s:new e(function(n){n(s)})}return new(e||(e=Promise))(function(s,n){function d(g){try{m(r.next(g))}catch(_){n(_)}}function p(g){try{m(r.throw(g))}catch(_){n(_)}}function m(g){g.done?s(g.value):o(g.value).then(d,p)}m((r=r.apply(i,t||[])).next())})};function It(i){let t=arguments,e=li()(Oe(r=>{e.next=o=>r.next(o),e.complete=()=>r.complete(),e.error=o=>r.error(o),i&&r.subscribe(i)},"subject",t));return e.next=Ve,e.complete=Ve,e.error=Ve,e}function yf(i){return Oe(t=>t.subscribe(i()),"defer",arguments)}var Af=i=>t=>{setTimeout(()=>i(t))},bf=i=>Af(t=>{for(let e=0;!t.disposed&&e<i.length;e++)t.next(i[e]);t.complete()});function dT(...i){return Oe(bf(i),"of",arguments)}function uT(i){return Oe(bf(i),"fromArray",arguments)}function sm(i){return Oe(t=>{let e=0,r=setInterval(()=>t.next(e++),i);return t.defer(()=>{clearInterval(r)}),"interval"},"interval",arguments)}function Ta(i,t){return Oe(e=>{let r=0,o=setTimeout(()=>{if(e.removeDefer(s),e.next(r++),t){let n=setInterval(()=>e.next(r++),t);e.defer(()=>{clearInterval(n)})}else e.complete()},i),s=()=>{clearTimeout(o)};e.defer(s)},"timer",arguments)}function Td(i,t){return e=>{let r=o=>e.next(o);e.defer(()=>t(r)),i(r)}}function lT(i,t){return Oe(Td(i,t),"fromEventPattern",arguments)}function be(i,t){if("on"in i&&"off"in i)return Oe(Td(e=>i.on(t,e),e=>i.off(t,e)),"fromEvent",arguments);if("addListener"in i&&"removeListener"in i)return Oe(Td(e=>i.addListener(t,e),e=>i.removeListener(t,e)),"fromEvent",arguments);if("addEventListener"in i)return Oe(Td(e=>i.addEventListener(t,e),e=>i.removeEventListener(t,e)),"fromEvent",arguments);throw"target is not a EventDispachter"}function Rf(i){return Oe(t=>{i.then(t.next.bind(t),t.error.bind(t))},"fromPromise",arguments)}function mT(i,t){return Oe(yf(()=>Rf(fetch(i,t))),"fromFetch",arguments)}function pT(i){return Oe(Af(t=>{try{for(let e of i){if(t.disposed)return;t.next(e)}t.complete()}catch(e){t.error(e)}}),"fromIterable",arguments)}function hT(i){let t=e=>cT(this,void 0,void 0,function*(){if(e.disposed)return;let{done:r,value:o}=yield i.read();if(r){e.complete();return}else e.next(o),t(e)});return Oe(e=>{t(e)},"fromReader",arguments)}function fT(i){return Oe(t=>{let e=new AbortController,r=e.signal;t.defer(()=>e.abort("cancelled")),i.pipeTo(new WritableStream({write(o){t.next(o)},close(){t.complete()},abort(o){t.error(o)}}),{signal:r}).then(()=>t.complete(),o=>t.error(o))},"fromReadableStream",arguments)}function gT(){return Oe(i=>{let t=requestAnimationFrame(function e(r){i.disposed||(i.next(r),t=requestAnimationFrame(e))});i.defer(()=>cancelAnimationFrame(t))},"fromAnimationFrame",arguments)}function ET(i,t){return Oe((e,r=i,o=t+i)=>{for(;r<o&&!e.disposed;)e.next(r++);return e.complete(),"range"},"range",arguments)}function _T(i,t,...e){return Oe(r=>{let o=e.concat(s=>(r.next(s),r.complete()));i.apply(t,o)},"bindCallback",arguments)}function TT(i,t,...e){return Oe(r=>{let o=e.concat((s,n)=>s?r.error(s):(r.next(n),r.complete()));i.apply(t,o)},"bindNodeCallback",arguments)}function IT(){return Oe(()=>{},"never",arguments)}function ST(i){return Oe(t=>t.error(i),"throwError",arguments)}function Ia(){return Oe(i=>i.complete(),"empty",arguments)}var Wo=class extends de{constructor(t,e,r){super(t),this.f=e;let o=()=>{this.sink.next(this.acc),this.sink.complete()};typeof r=="undefined"?this.next=s=>{this.acc=s,this.complete=o,this.resetNext()}:(this.acc=r,this.complete=o)}next(t){this.acc=this.f(this.acc,t)}},nm=pe(Wo,"reduce"),yT=i=>pe(Wo,"count")((t,e)=>i(e)?t+1:t,0),AT=()=>pe(Wo,"max")(Math.max),bT=()=>pe(Wo,"min")(Math.min),RT=()=>pe(Wo,"sum")((i,t)=>i+t,0);var am=class extends de{constructor(t,e,r){super(t),this.filter=e,this.thisArg=r}next(t){this.filter.call(this.thisArg,t)&&this.sink.next(t)}},yr=pe(am,"filter"),cm=class extends de{next(t){}},vT=pe(cm,"ignoreElements"),dm=class extends de{constructor(t,e){super(t),this.count=e}next(t){this.sink.next(t),--this.count===0&&this.complete()}},Ar=pe(dm,"take"),um=class extends de{constructor(t,e){super(t);let r=new de(t);r.next=()=>t.complete(),r.complete=Ed,r.subscribe(e)}},Je=pe(um,"takeUntil"),lm=class extends de{constructor(t,e){super(t),this.f=e}next(t){this.f(t)?this.sink.next(t):this.complete()}},vf=pe(lm,"takeWhile"),CT=i=>nm((t,e)=>(t.push(e),t.length>i&&t.shift(),t),[]),mm=class extends de{constructor(t,e){super(t),this.count=e}next(t){--this.count===0&&(this.next=super.next)}},DT=pe(mm,"skip"),pm=class extends de{constructor(t,e){super(t),t.next=Ve;let r=new de(t);r.next=()=>{r.dispose(),t.resetNext()},r.complete=Ed,r.subscribe(e)}},NT=pe(pm,"skipUntil"),hm=class extends de{constructor(t,e){super(t),this.f=e}next(t){this.f(t)||(this.next=super.next,this.next(t))}},yd=pe(hm,"skipWhile"),wT={leading:!0,trailing:!1},fm=class extends de{constructor(t,e,r){super(t),this.durationSelector=e,this.trailing=r}cacheValue(t){this.last=t,this.disposed&&this.throttle(t)}send(t){this.sink.next(t),this.throttle(t)}throttle(t){this.reset(),this.subscribe(this.durationSelector(t))}next(){this.complete()}complete(){this.dispose(),this.trailing&&this.send(this.last)}},Id=class extends de{constructor(t,e,r=wT){super(t),this.durationSelector=e,this.config=r,this._throttle=new fm(this.sink,this.durationSelector,this.config.trailing),this._throttle.dispose()}next(t){this._throttle.disposed&&this.config.leading?this._throttle.send(t):this._throttle.cacheValue(t)}complete(){this._throttle.throttle=Ve,this._throttle.complete(),super.complete()}},MT=pe(Id,"throttle"),OT={leading:!1,trailing:!0},xT=i=>pe(Id,"audit")(i,OT),gm=class extends de{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},Sd=class extends de{constructor(t,e){super(t),this.durationSelector=e,this._debounce=new gm(this.sink),this._debounce.dispose()}next(t){this._debounce.dispose(),this._debounce.reset(),this._debounce.last=t,this._debounce.subscribe(this.durationSelector(t))}complete(){this._debounce.complete(),super.complete()}},PT=pe(Sd,"debounce"),kT=i=>pe(Sd,"debounceTime")(t=>Ta(i)),Em=class extends de{constructor(t,e,r){super(t),this.count=e,this.defaultValue=r}next(t){this.count--===0&&(this.defaultValue=t,this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("not enough elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},LT=pe(Em,"elementAt"),UT=i=>t=>Ar(1)(yd(e=>!i(e))(t)),_m=class extends de{constructor(t,e){super(t),this.f=e,this.i=0}next(t){this.f(t)?(this.sink.next(this.i++),this.complete()):++this.i}},VT=pe(_m,"findIndex"),Tm=class extends de{constructor(t,e,r){super(t),this.f=e,this.defaultValue=r,this.index=0}next(t){(!this.f||this.f(t,this.index++))&&(this.defaultValue=t,this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},FT=pe(Tm,"first"),Im=class extends de{constructor(t,e,r){super(t),this.f=e,this.defaultValue=r,this.index=0}next(t){(!this.f||this.f(t,this.index++))&&(this.defaultValue=t)}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},$T=pe(Im,"last"),Sm=class extends de{constructor(t,e){super(t),this.predicate=e,this.index=0}next(t){this.predicate(t,this.index++)?this.result=!0:(this.result=!1,this.complete())}complete(){if(this.result===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.result);super.complete()}},BT=pe(Sm,"every");var ym=class extends de{constructor(t,e,r){super(t),this.f=e,typeof r=="undefined"?this.next=o=>{this.acc=o,this.resetNext(),this.sink.next(this.acc)}:this.acc=r}next(t){this.sink.next(this.acc=this.f(this.acc,t))}},Om=pe(ym,"scan"),Am=class extends de{constructor(){super(...arguments),this.hasLast=!1}next(t){this.hasLast?this.sink.next([this.last,t]):this.hasLast=!0,this.last=t}},HT=pe(Am,"pairwise"),Ad=class extends de{constructor(t,e,r){super(t),this.mapper=e,this.thisArg=r}next(t){super.next(this.mapper.call(this.thisArg,t))}},Ji=pe(Ad,"map"),WT=i=>pe(Ad,"mapTo")(t=>i),Bs=class extends de{constructor(t,e,r){super(t),this.data=e,this.context=r}next(t){let e=this.context.combineResults;e?this.sink.next(e(this.data,t)):this.sink.next(t)}tryComplete(){this.context.resetComplete(),this.dispose()}},Hs=class extends de{constructor(t,e,r){super(t),this.makeSource=e,this.combineResults=r,this.index=0}subInner(t,e){let r=this.currentSink=new e(this.sink,t,this);this.complete=this.tryComplete,r.complete=r.tryComplete,r.subscribe(this.makeSource(t,this.index++))}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},bd=class extends Bs{},Rd=class extends Hs{next(t){this.subInner(t,bd),this.next=e=>{this.currentSink.dispose(),this.subInner(e,bd)}}},zi=pe(Rd,"switchMap");function Nd(i){return(t,e)=>i(()=>t,e)}var mi=Nd(pe(Rd,"switchMapTo")),bm=class extends Bs{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},vd=class extends Hs{constructor(){super(...arguments),this.sources=[],this.next2=this.sources.push.bind(this.sources)}next(t){this.next2(t),this.subNext()}subNext(){this.next=this.next2,this.subInner(this.sources.shift(),bm),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},GT=pe(vd,"concatMap"),jT=Nd(pe(vd,"concatMapTo")),Rm=class extends Bs{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},Cd=class extends Hs{constructor(){super(...arguments),this.inners=new Set}next(t){this.subInner(t,Rm),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(t=>t.resetComplete()):this.dispose()}},qT=pe(Cd,"mergeMap"),JT=Nd(pe(Cd,"mergeMapTo")),vm=class extends Bs{dispose(){this.context.resetNext(),super.dispose()}},Dd=class extends Hs{next(t){this.next=Ve,this.subInner(t,vm)}},zT=pe(Dd,"exhaustMap"),XT=Nd(pe(Dd,"exhaustMapTo")),Cm=class extends de{constructor(t,e){super(t),this.f=e,this.groups=new Map}next(t){let e=this.f(t),r=this.groups.get(e);typeof r=="undefined"&&(r=It(),r.key=e,this.groups.set(e,r),super.next(r)),r.next(t)}complete(){this.groups.forEach(t=>t.complete()),super.complete()}error(t){this.groups.forEach(e=>e.error(t)),super.error(t)}},QT=pe(Cm,"groupBy"),Dm=class extends de{constructor(){super(...arguments),this.start=new Date}next(t){this.sink.next({value:t,interval:Number(new Date)-Number(this.start)}),this.start=new Date}},YT=pe(Dm,"timeInterval"),Nm=class extends de{constructor(t,e){super(t),this.miniseconds=e,this.buffer=[],this.id=setInterval(()=>{this.sink.next(this.buffer.concat()),this.buffer.length=0},this.miniseconds)}next(t){this.buffer.push(t)}complete(){this.sink.next(this.buffer),super.complete()}dispose(){clearInterval(this.id),super.dispose()}},ZT=pe(Nm,"bufferTime"),wm=class extends de{constructor(t,e){super(t),this.buffer=[],this.delayTime=e}dispose(){clearTimeout(this.timeoutId),super.dispose()}delay(t){this.timeoutId=setTimeout(()=>{let e=this.buffer.shift();if(e){let{time:r,data:o}=e;super.next(o),this.buffer.length&&this.delay(Number(this.buffer[0].time)-Number(r))}},t)}next(t){this.buffer.length||this.delay(this.delayTime),this.buffer.push({time:new Date,data:t})}complete(){this.timeoutId=setTimeout(()=>super.complete(),this.delayTime)}},KT=pe(wm,"delay"),Mm=class extends de{constructor(t,e){super(t),this.selector=e}error(t){this.dispose(),this.selector(t)(this.sink)}},xm=pe(Mm,"catchError");var eI=()=>i=>new Promise((t,e)=>{let r;new Ho(i,o=>r=o,e,()=>t(r))}),tI=()=>i=>{let t;return new ReadableStream({start(e){t=new Ho(i,e.enqueue.bind(e),e.error.bind(e),e.close.bind(e))},cancel(){t.dispose()}})},ke=(i=Ve,t=Ve,e=Ve)=>r=>new Ho(r,i,t,e),Pm=class extends de{constructor(t,e){super(t),e instanceof Function?this.next=r=>{e(r),t.next(r)}:(e.next&&(this.next=r=>{e.next(r),t.next(r)}),e.complete&&(this.complete=()=>{e.complete(),t.complete()}),e.error&&(this.error=r=>{e.error(r),t.error(r)}))}},Sa=pe(Pm,"tap"),km=class extends de{constructor(t,e){super(t),this.timeout=e,this.id=setTimeout(()=>this.error(new Ea(this.timeout)),this.timeout)}next(t){super.next(t),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},Lm=pe(km,"timeout"),rI=(i=1/0)=>t=>{if(t instanceof or){let e=Oe(r=>{let o=i,s=new de(r);s.error=n=>{o-- >0?s.subscribe(t):r.error(n)},s.sourceId=e.id,s.subscribe(t)},"retry",[i]);return e.source=t,it.pipe(e),e}else return e=>{let r=i,o=new de(e);o.error=s=>{r-- >0?t(o):e.error(s)},t(o)}};var Br=class Br extends ko{constructor(e,r,o){super({userId:r.userId,sdkAppId:e.sdkAppId,mediaType:o,room:e});this.room=e;this.user=r;u(this,"tinyId");u(this,"isRemote",!0);u(this,"jitterBufferDelay",0);u(this,"availableState");u(this,"remotePublishState");u(this,"_triggerCheckDecodeSubject",It(be(this,Br.STATE_SUBSCRIBE)));this.tinyId=r.tinyId,this.availableState=new ne(`${r.userId}-${this.mediaType}-available`,"remote-track-available"),this.remotePublishState=new ne(`${r.userId}-${this.mediaType}-remote-publish`,"remote-track-publish"),Se(im(be(this,ne.STATECHANGED),be(this.remotePublishState,ne.STATECHANGED)),Ji(()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing)),ke(p=>{this.availableState.state!==(p?ne.ON:ne.OFF)&&(this.availableState.state=p?ne.ON:ne.OFF),this.updatePlayingState(p)}));let s=Se(be(this.player,Qe.ERROR),yr(p=>p.code===MediaError.MEDIA_ERR_DECODE)),n=Se(Ta(5e3),yr(()=>this.ignoreDecodeError||!this.isSubscribed||!this.isPlayCalled||!this.stat.bytesReceived?!1:this.player.isPlaying||(this.kind===D.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)?(this.reportDecodeResult(!0),!1):!0)),d=Se(om(s,n),Je(be(this,ne.INIT)));Se(this._triggerCheckDecodeSubject,yr(()=>!this.ignoreDecodeError),mi(d),ke(p=>{this.reportDecodeResult(!1,p)}))}setMute(e){this.isRemotePublished&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.isRemotePublished&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}checkDecodeResult(){this._triggerCheckDecodeSubject.next(!0)}waitHasMediaTrack(){return new Promise(e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)})}get ignoreDecodeError(){var r,o;return(((o=(r=this.room)==null?void 0:r.networkQuality)==null?void 0:o.downlinkNetworkQuality)||0)>3||this.player.isInAutoPlayFailedState}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===Br.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===ne.ON}get isNeedPlay(){return this.isAvailable&&this.isPlayCalled}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}reportDecodeResult(e,r){let o=this.kind===D.AUDIO;Y[e?"addSuccessEvent":"addFailedEvent"]({key:o?504700:514702}),e||(Y.addEnum({key:o?504701:514703,value:Jn()}),Be.uploadEvent({log:`stat-decode-failed-${this.kind}-${qn()||bo()}`,userId:this.room.userId}),this._log.warn(`decode failed: isPlaying: ${this.player.isPlaying} ${this.kind===D.AUDIO?`audioLevel: ${this.getAudioLevel()}`:`framesDecoded: ${this.stat.framesDecoded>0}`}`),this.emit("decode-failed",{error:r}))}updatePlayingState(e){if(this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.isRemotePublished||!this.outMediaTrack)){this.log.info(`abort play, isSubscribed: ${this.isSubscribed} isAvailable: ${this.isRemotePublished} hasTrack: ${!!this.outMediaTrack} `);return}super.updatePlayingState(e)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.remotePublishState.state=this.isRemotePublished?ne.ON:ne.OFF}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};u(Br,"STATE_SUBSCRIBE","subscribe"),X([_f(5,1)],Br.prototype,"waitHasMediaTrack",1),X([qe(ne.INIT,Br.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),H.emit(L.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),hd(521716,!1)],Br.prototype,"subscribe",1),X([qe(Br.STATE_SUBSCRIBE,ne.INIT,{sync:!0,success(){this.log.info("unsubscribed"),H.emit(L.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],Br.prototype,"unsubscribe",1);var Ws=Br;var $o=class extends Ws{constructor(e,r){super(e,r,1);u(this,"volume",0);u(this,"mediaType",1);u(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.audioManager}get dbVolume(){return nd.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}decodeFrame(e){if(!this.manager)return e;let r=e;for(let o of this.manager.decodePipeline)if(o&&(r=o({frame:r,track:this}),!r))return;return r}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get isRemotePublished(){return this.user.muteState.audioAvailable}};var oI=[-1,-1,1,-1,-1,1,1,1],sI=[0,0,1,0,0,1,1,1];var Bt=class extends ne{constructor(e,r){super();this.context=e;u(this,"name");u(this,"input");u(this,"output");u(this,"texture");u(this,"ctx2d",null);u(this,"fbo");u(this,"width",0);u(this,"height",0);u(this,"x",0);u(this,"y",0);u(this,"program");u(this,"vertexShader");u(this,"fragmentShader");u(this,"totalFrames",0);u(this,"dropFrames",0);u(this,"matchInputSize",!0);u(this,"texCoordBuffer");u(this,"positionBuffer");u(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0});u(this,"cost",0);u(this,"_canvas",null);u(this,"_image");u(this,"log");if(this.context.on("disconnect",this.close,this),this.name=r.name,this.log=r.logger,this.matchInputSize=r.matchInputSize!==!1,this.width=r.width||e.width,this.height=r.height||e.height,this._image=r.image,e instanceof kt){e.ctx&&r.create2d&&(typeof OffscreenCanvas=="function"&&Yt!==16?this._canvas=new OffscreenCanvas(this.width,this.height):(this._canvas=document.createElement("canvas"),this._canvas.width=this.width,this._canvas.height=this.height),this.ctx2d=this._canvas.getContext("2d"),this._image=this._canvas);return}try{let o=e.ctx;this.texCoordBuffer=this.createBuffer(sI),this.positionBuffer=this.createBuffer(oI),r.createTexture!==!1&&(this.texture=o.createTexture(),this.useTexture(),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),o.pixelStorei(o.PACK_ALIGNMENT,1),o.pixelStorei(o.UNPACK_ALIGNMENT,1)),r.useFbo&&(this.fbo=o.createFramebuffer(),this.useBufferFrame(),this.useTexture(),o.texImage2D(o.TEXTURE_2D,0,o.RGBA,this.width,this.height,0,o.RGBA,o.UNSIGNED_BYTE,null),o.framebufferTexture2D(o.FRAMEBUFFER,o.COLOR_ATTACHMENT0,o.TEXTURE_2D,this.texture,0)),r.useDefaultProgram?this.program=e.defaultProgam:(r.vertexShaderSource||r.fragmentShaderSource)&&(this.vertexShader=r.vertexShaderSource?e.createShader(o.VERTEX_SHADER,r.vertexShaderSource):e.defaultVShader,this.fragmentShader=r.fragmentShaderSource?e.createShader(o.FRAGMENT_SHADER,r.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(o){this.context.destroy(new he({code:te.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${o.message||o}`}))}}get image(){return this._image}set image(e){this._image=e}createFramebuffer(e){let r=this.context.ctx,o=r.createFramebuffer();return r.bindFramebuffer(r.FRAMEBUFFER,o),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,e,0),o}connect(e,...r){return e.addInput(this,...r),this.output=e,e}addInput(e,...r){this.input=e,this.matchInputSize&&e.width&&e.height&&this.resize(e.width,e.height)}requestFrame(e){let r=Date.now();if(this.context instanceof Et&&this.render(e)||this.context instanceof kt&&this.render2d(e))this.totalFrames++;else return!1;return this.cost=Date.now()-r,!0}render2d(e){var r;return(r=this.input)!=null&&r.requestFrame(e)?this.draw2d(this.input.image,0,0,this.width,this.height):!1}update(e=0){var r;(r=this.output)==null||r.update(e)}disconnect(...e){var r;(r=this.output)==null||r.removeInput(this,...e),delete this.output}removeInput(e,...r){delete this.input}close(){var e,r;if(this.context.off("disconnect",this.close,this),(e=this.output)==null||e.removeInput(this),delete this.output,(r=this.input)==null||r.disconnect(),this.context instanceof Et){let o=this.context.ctx;o.deleteBuffer(this.texCoordBuffer),o.deleteBuffer(this.positionBuffer),this.fbo&&o.deleteFramebuffer(this.fbo),this.texture&&o.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&o.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&o.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&o.deleteProgram(this.program)}this._canvas&&(this._canvas.width=0,this._canvas.height=0,this.ctx2d=null),this.removeAllListeners()}useTexture(){this.useTextures(this.texture)}useInputTexture(){var e;this.useTextures((e=this.input)==null?void 0:e.texture)}useTextures(...e){let r=this.context.ctx;e.forEach((o,s)=>{o&&(r.activeTexture(r.TEXTURE0+s),r.bindTexture(r.TEXTURE_2D,o))})}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}createBuffer(e){let r=this.context.ctx,o=r.createBuffer();return r.bindBuffer(r.ARRAY_BUFFER,o),r.bufferData(r.ARRAY_BUFFER,new Float32Array(e),r.STATIC_DRAW),o}setTexBuffer(e){let r=this.context.ctx;r.bindBuffer(r.ARRAY_BUFFER,this.texCoordBuffer),r.bufferData(r.ARRAY_BUFFER,new Float32Array(e),r.STATIC_DRAW)}setPosBuffer(e){let r=this.context.ctx;r.bindBuffer(r.ARRAY_BUFFER,this.positionBuffer),r.bufferData(r.ARRAY_BUFFER,new Float32Array(e),r.STATIC_DRAW)}changeBufferData(e,r){let o=this.context.ctx;o.bindBuffer(o.ARRAY_BUFFER,e),o.bufferData(o.ARRAY_BUFFER,new Float32Array(r),o.STATIC_DRAW)}setAttributes(...e){let r=this.context.ctx;e.forEach((o,s)=>{r.enableVertexAttribArray(s),r.bindBuffer(r.ARRAY_BUFFER,o),r.vertexAttribPointer(s,2,r.FLOAT,!1,0,0)})}getVertexPoint(e,r){return[e/this.width*2-1,r/this.height*2-1]}layout2texCoords(e){return[...this.getVertexPoint(e.x,e.y),...this.getVertexPoint(e.x+e.width,e.y),...this.getVertexPoint(e.x,e.y+e.height),...this.getVertexPoint(e.x+e.width,e.y+e.height)]}resize(e,r){if(!(this.width===e&&this.height===r)){if(this.width=e,this.height=r,this._canvas&&(this._canvas.width=e,this._canvas.height=r),this.texture&&this.fbo){this.useTexture();let o=this.context.ctx;o.texImage2D(o.TEXTURE_2D,0,o.RGBA,e,r,0,o.RGBA,o.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(e,r)}}draw(e,r){this.setAttributes(e||this.positionBuffer,r||this.texCoordBuffer);let o=this.context.ctx;o.drawArrays(o.TRIANGLE_STRIP,0,4)}draw2d(e,r,o,s,n){return this.ctx2d&&e?(e instanceof ImageData?this.ctx2d.putImageData(e,r,o):(this.ctx2d.drawImage(e,r,o,s,n),typeof VideoFrame!="undefined"&&e instanceof VideoFrame&&e.close()),!0):!1}getInfo(){var _;let{totalFrames:e,x:r,y:o,width:s,height:n,name:d,cost:p}=this,m=Date.now(),g=(e-this.lastInfo.totalFrames)/((m-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:r,y:o,width:s,height:n,timestamp:m,fps:g,name:d,cost:p},ee({parent:(_=this.input)==null?void 0:_.getInfo()},this.lastInfo)}createTexture(e){let r=this.context.ctx,o=r.createTexture();return this.useTextures(o),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.pixelStorei(r.PACK_ALIGNMENT,1),r.pixelStorei(r.UNPACK_ALIGNMENT,1),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,r.RGBA,r.UNSIGNED_BYTE,e),o}};X([qe(ne.INIT,"connected",{sync:!0})],Bt.prototype,"connect",1),X([qe("connected",ne.INIT,{ignoreError:!0,sync:!0})],Bt.prototype,"disconnect",1),X([qe([],"closed",{sync:!0})],Bt.prototype,"close",1);var Df=Se(sm(250),Ji(()=>performance.now()),li()),Nf=i=>t=>{let e=0,r=performance.now();Se(Df,Ji(o=>(o-r)/i>>0),yr(o=>o!=e?(e=o,!0):!1))(t)},wd=i=>t=>{let e=performance.now();Se(Df,yd(r=>r-e<i),Ar(1))(t)};var aI=[0,1,1,1,0,0,1,0],Go=class extends Bt{constructor(e,r){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},r));u(this,"_intervalId",0);u(this,"_sequence",0);u(this,"checkGLError",!1);u(this,"checkVisibilityChange");e instanceof kt?this.ctx2d=e.ctx||null:e.available&&(r!=null&&r.mirrorUpAndDown)&&this.setTexBuffer(aI)}start(e){this.log.info(`${this.name} start render ${e} fps`),At.clearTask(this._intervalId),this._intervalId=At.run("intervalInWorker",()=>{if(e!==this.context.frameRate&&(At.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof Et){let o=this.context.ctx.getError();o&&this.context.destroy(new he({code:te.VIDEO_MANAGER_ERROR,extraCode:5,message:`${this.name} req ${this._sequence} render ${this.totalFrames} faild ${o}`}))}},{fps:this.context.frameRate})}render(e){var r;return(r=this.input)!=null&&r.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}addInput(e,...r){super.addInput(e,...r),this.start(this.context.frameRate)}update(e=0){if(this._intervalId&&(At.clearTask(this._intervalId),this._intervalId=0,e===1)){this.log.info(`${this.name} use requestVideoFrameCallback`);let r=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info(`${this.name} use timer`),document.removeEventListener("visibilitychange",r))};document.addEventListener("visibilitychange",r)}this.requestFrame(this._sequence++)}removeInput(e){super.removeInput(e),At.clearTask(this._intervalId)}resize(e,r){super.resize(e,r),this.context.setSize(e,r)}close(){super.close(),At.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},Gs=class extends Go{constructor(e,r){super(e,r);u(this,"_videoTrack");u(this,"_muteOb");u(this,"_closedOb",be(this,"closed"));u(this,"_subscription");u(this,"_canvasContainer");Number(Vi)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e._canvas.captureStream().getVideoTracks(),this._muteOb=be(this._videoTrack,"mute"),Se(be(this._videoTrack,"ended"),Je(this._closedOb),ke(()=>{this.context.destroy(new he({code:te.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){this._subscription=Se(this._muteOb,Je(this._closedOb),mi(wd(5e3)),ke(()=>{var e;(e=this._videoTrack)!=null&&e.muted&&this.context.destroy(new he({code:te.VIDEO_MANAGER_ERROR,extraCode:7,message:"video track muted"}))}))}disableCheckMute(){var e;(e=this._subscription)==null||e.dispose()}get videoTrack(){return this._videoTrack}putCanvasIntoDom(){!this.context._canvas||!this._canvasContainer||document.getElementById(this.context._canvas.id)||(this.log.info(`${this.name} put canvas to body`),document.body.appendChild(this._canvasContainer),this._canvasContainer.appendChild(this.context._canvas))}render(e){return this.putCanvasIntoDom(),super.render(e)}render2d(e){return this.putCanvasIntoDom(),super.render2d(e)}close(){var e,r;super.close(),(e=this._videoTrack)==null||e.stop(),delete this._videoTrack,(r=this._canvasContainer)==null||r.remove()}},Md=class extends Gs{render(t){var e;return!!((e=this.input)!=null&&e.requestFrame(t))}};var Od=class extends Gs{constructor(e,r,o){super(e,{name:"smallDestination",logger:o});this.resolution=r}resize(e,r){let o,s=e*r,n=this.resolution.width*this.resolution.height;this.log.info(`big res: ${e}*${r} small res: ${this.resolution.width}*${this.resolution.height} `),s>n?o=s/n:(this.log.warn(`Small stream resolution is not smaller than big stream, which is invalid. big: ${e} * ${r} small: ${this.resolution.width} * ${this.resolution.height}`),o=s/(160*120)),super.resize(e/Math.sqrt(o),r/Math.sqrt(o))}};var ya=class extends Bt{constructor(e,r){super(e,ee({name:"imageSource"},r));u(this,"_lastImage");u(this,"_totalFrames",0);u(this,"_autoResize",!1);u(this,"_canvasRendered");u(this,"_videoCallbackId",0);this._autoResize=(r==null?void 0:r.autoResize)!==!1,Yt===16&&(this._canvasRendered=It(),Se(this._canvasRendered,_a(this._image),zi(o=>o instanceof HTMLCanvasElement?be(o,"rendered"):Ia()),Je(be(this,"closed")),ke(()=>{this.update()})))}tryVideoFrameCallback(e){this._videoCallbackId&&e.cancelVideoFrameCallback(this._videoCallbackId),Oo()&&!document.hidden&&(this._videoCallbackId=e.requestVideoFrameCallback((r,o)=>{document.hidden||(this._totalFrames=o.presentedFrames,this.update(1))}))}_render(e,r){var d;let{width:o,height:s}=this,{image:n}=this;if(n instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(n),{videoWidth:o,videoHeight:s}=n,!o||!s)return!1;n.width=o,n.height=s}else if(n instanceof HTMLImageElement||n instanceof ImageData||n instanceof ImageBitmap){if({width:o,height:s}=n,n!==this._lastImage)this._lastImage=n;else if(o===this.width&&s===this.height)return!1}else n instanceof HTMLCanvasElement||n instanceof OffscreenCanvas?({width:o,height:s}=n,this._lastImage=n):typeof VideoFrame!="undefined"&&n instanceof VideoFrame&&({displayWidth:o,displayHeight:s}=n,(d=this._lastImage)==null||d.close(),this._lastImage=n);if(!this._autoResize)return!0;if(this.width===o&&this.height===s&&this.totalFrames){if(r){this.useTexture();let p=this.context.ctx;p.texSubImage2D(p.TEXTURE_2D,0,0,0,p.RGBA,p.UNSIGNED_BYTE,n)}}else{if(r){this.useTexture();let p=this.context.ctx;p.texImage2D(p.TEXTURE_2D,0,p.RGBA,p.RGBA,p.UNSIGNED_BYTE,n)}this.resize(o,s)}return!0}get image(){return this._image}set image(e){var r;(r=this._canvasRendered)==null||r.next(e),this._image=e}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},Aa=class extends ya{constructor(e,r,o){super(e,o);this._player=r;this.name="videoPlayerSource",Se(be(this._player,Qe.PLAYER_STATE_CHANGED),Je(be(this,"closed")),yr(({state:s})=>s==="PLAYING"),ke(()=>{this.tryVideoFrameCallback(this._player.element)}))}get image(){return this._player.element}},pi=class extends Aa{constructor(t,e,r){super(t,new Zt({id:r.name,track:e,muted:!0,container:null,objectFit:"contain",log:r.logger}),r),this.name="videoTrackSource",this._player.play()}replaceTrack(t){this._player.setTrack(t),this._player.play()}close(){super.close(),this._player.stop()}};var dI=`
32
32
  // \u9876\u70B9\u7740\u8272\u5668
33
33
  attribute vec4 a_position;
34
34
  attribute vec2 a_texCoord;
@@ -88,16 +88,16 @@ return ret;
88
88
  `,B=0;B<T-1;++B)v[B+1].deleteObject&&(ce+=" argType"+B+".deleteObject(arg"+B+`);
89
89
  `);C.isVoid||(ce+=` return retType.toWireType(destructors, rv);
90
90
  `),ce+=`};
91
- `,j.push(ce);var ye,le,ve=Ja(Function,j).apply(null,q);return ye=ve,le=ns.length,ns.push(ye),W=le,as[U]=W,W},f:()=>{K("")},c:mn,t:(T,E,v)=>x.copyWithin(T,E,E+v),s:T=>{x.length,K("OOM")},i:(T,E,v,C)=>{for(var U,W,j,q=0,Z=0;Z<v;Z++){var B=De[E>>2],ce=De[E+4>>2];E+=8;for(var Re=0;Re<ce;Re++)U=T,W=x[B+Re],j=void 0,j=ec[U],W===0||W===10?((U===1?_:b)(Xa(j,0)),j.length=0):j.push(W);q+=ce}return De[C>>2]=q,0}},mr=(function(){var T,E,v,C,U={a:tc};function W(j,q){var Z,B,ce=j.exports;return N=(k=ce).v,Z=N.buffer,o.HEAP8=P=new Int8Array(Z),o.HEAP16=J=new Int16Array(Z),o.HEAP32=Ne=new Int32Array(Z),o.HEAPU8=x=new Uint8Array(Z),o.HEAPU16=Q=new Uint16Array(Z),o.HEAPU32=De=new Uint32Array(Z),o.HEAPF32=me=new Float32Array(Z),o.HEAPF64=xe=new Float64Array(Z),Fe=k.z,B=k.w,tn.unshift(B),function(){if(vr--,o.monitorRunDependencies&&o.monitorRunDependencies(vr),vr==0&&(Yo!==null&&(clearInterval(Yo),Yo=null),Ei)){var Re=Ei;Ei=null,Re()}}(),ce}if(vr++,o.monitorRunDependencies&&o.monitorRunDependencies(vr),o.instantiateWasm)try{return o.instantiateWasm(U,W)}catch(j){b("Module.instantiateWasm callback failed with error: "+j),r(j)}(T=g,E=Wr,v=U,C=function(j){W(j.instance)},T||typeof WebAssembly.instantiateStreaming!="function"||no(E)||typeof fetch!="function"?_i(E,v,C):fetch(E,{credentials:"same-origin"}).then(j=>WebAssembly.instantiateStreaming(j,v).then(C,function(q){return b("wasm streaming compile failed: "+q),b("falling back to ArrayBuffer instantiation"),_i(E,v,C)}))).catch(r)}(),T=>(mr=k.x)(T)),Di=T=>(Di=k.y)(T),cs=T=>(cs=k.A)(T),rc=(o.__embind_initialize_bindings=()=>(o.__embind_initialize_bindings=k.B)(),T=>(rc=k.C)(T));o.dynCall_jiji=(T,E,v,C,U)=>(o.dynCall_jiji=k.D)(T,E,v,C,U);function ic(){function T(){wt||(wt=!0,o.calledRun=!0,Ks||(ao(tn),e(o),o.onRuntimeInitialized&&o.onRuntimeInitialized(),function(){if(o.postRun)for(typeof o.postRun=="function"&&(o.postRun=[o.postRun]);o.postRun.length;)E=o.postRun.shift(),rn.unshift(E);var E;ao(rn)}()))}vr>0||(function(){if(o.preRun)for(typeof o.preRun=="function"&&(o.preRun=[o.preRun]);o.preRun.length;)E=o.preRun.shift(),en.unshift(E);var E;ao(en)}(),vr>0||(o.setStatus?(o.setStatus("Running..."),setTimeout(function(){setTimeout(function(){o.setStatus("")},1),T()},1)):T()))}if(Ei=function T(){wt||ic(),wt||(Ei=T)},o.preInit)for(typeof o.preInit=="function"&&(o.preInit=[o.preInit]);o.preInit.length>0;)o.preInit.pop()();return ic(),t.ready}})();var MI="web.sdk.qcloud.com",OI=`https://${MI}/trtc/webrtc/v5/doc`,CM=`${OI}/zh-cn/`,Uf=(i=>(i[i.TRACE=0]="TRACE",i[i.DEBUG=1]="DEBUG",i[i.INFO=2]="INFO",i[i.WARN=3]="WARN",i[i.ERROR=4]="ERROR",i[i.NONE=5]="NONE",i))(Uf||{});var Fd={CANVAS:"canvas",AUDIO:"audio",VIDEO:"video",SCREEN:"screen",SMALL:"small",BIG:"big",AUXILIARY:"auxiliary",SMALL_VIDEO:"smallVideo",FACING_MODE_USER:"user",FACING_MODE_ENVIRONMENT:"environment",MUTE:"mute",UNMUTE:"unmute",ENDED:"ended",PLAYING:"playing",PAUSE:"pause",ERROR:"error",LOADEDDATA:"loadeddata",LOADEDMETADATA:"loadedmetadata",AUDIO_INPUT:"audioinput",VIDEO_INPUT:"videoinput",DETAIL:"detail",TEXT:"text",MAIN:"main",BACKUP:"backup",BANNED:"banned",KICK:"kick",USER_TIME_OUT:"user_time_out",ROOM_DISBAND:"room_disband",SEI_MESSAGE:"sei-message",ADD:"add",REMOVE:"remove",REPLACE:"replace",TRACK:"track",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",TRANSCEIVER_DIRECTION_SENDONLY:"sendonly",TRANSCEIVER_DIRECTION_RECVONLY:"recvonly",ENTER_PICTURE_IN_PICTURE:"enterpictureinpicture",LEAVE_PICTURE_IN_PICTURE:"leavepictureinpicture"},DM=Fd.MAIN,NM=Fd.AUXILIARY,wM=Fd.BIG,MM=Fd.SMALL;var OM=Object.keys(Uf);var xM=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{};function xf(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var{toString:PM}=Object.prototype,Vf=class Ff{constructor(t){this.core=t,br(this,"contextMap",new Map),br(this,"decodeProcessorMap",new WeakMap),this.addKVReportBeforeExitRoom=this.addKVReportBeforeExitRoom.bind(this),this.createDecoder=this.createDecoder.bind(this),this.core.innerEmitter.on("51",this.addKVReportBeforeExitRoom)}getAlias(){return"videoDecoder"}getGroup(t){return t!=null&&t.track?`${t.track.userId}${t.track.streamType}`:"*"}getName(){return Ff.Name}getValidateRule(t){return{type:this.core.enums.BASIC_TYPE.Object}}createDecoder(t,e){switch(t){case"wasm":return new wI(Ld(kd({},e),{wasmPath:`${this.core.assetsPath||"."}/videodec.wasm`}));case"webCodecs":return new Js;case"mse":throw new Error("mse decoder not supported yet");default:throw new Error("Unsupported decoder type")}}start(t){this.decodeProcessorMap.set(t.track,this.decode(t)),this.core.room.videoManager.addDecodeProcessor({processor:({frame:e,track:r})=>{var o;return((o=this.decodeProcessorMap.get(r))==null?void 0:o({frame:e,track:r}))||e},type:3})}decode(t){let{pipe:e,take:r,subscribe:o}=this.core.rx;return({frame:s,track:n})=>{if(n!==t.track||s.type==="empty")return s;if(this.contextMap.has(n))return this.contextMap.get(n).decode(s);let d=this.core.room.videoManager.createDecodeContext(Ld(kd({},t),{createDecoder:this.createDecoder}));return e(d.trackDoneOB,r(1),o(()=>{this.core.clearStarted(this,this.getGroup(t)),this.stop({track:n})})),this.contextMap.set(n,d),d.decode(s)}}stop(t){if(t!=null&&t.track){let e=this.contextMap.get(t.track);e&&(e.close("stop"),this.report(e,t.track),this.contextMap.delete(t.track))}else this.contextMap.forEach((e,r)=>{e.close("stop"),this.contextMap.delete(r)});this.contextMap.size===0&&this.core.room.videoManager.removeDecodeProcessor({type:3})}report(t,e){if(t.isReported)return;t.isReported=!0;let r=xf()-t.startPerformanceTime,{renderFreezeTotal:o,dataFreezeTotal:s}=this.getRemoteTrackFreezeDuration(e,t);r&&this.core.kvStatManager.addNumber({key:514850,value:Math.floor(o/r*100),split:1}),r&&this.core.kvStatManager.addNumber({key:514851,value:Math.floor(s/r*100),split:1}),t.inputFrameCount&&this.core.kvStatManager.addNumber({key:514852,value:Math.floor(t.decodedFrameCount/t.inputFrameCount*100),split:1})}addKVReportBeforeExitRoom({room:t}){t===this.core.room&&this.contextMap.forEach((e,r)=>{this.report(e,r)})}update(t){let e=this.contextMap.get(t.track);e&&(t.type!=="mock"?(e.close("update"),this.contextMap.set(t.track,this.core.room.videoManager.createDecodeContext(Ld(kd({},t),{createDecoder:this.createDecoder})))):e.mock(this.core.enums.DECODE_FAILED_ERROR_CODE.TEST))}getRemoteTrackFreezeDuration(t,e){let r=this.core.room.badCaseDetector.getRenderFreezeMap().get(`${t.userId}_${t.streamType}`),o=this.core.room.badCaseDetector.getDataFreezeMap().get(`${t.userId}_${t.streamType}`),s=0;r&&r.freezeTimeline.forEach(({startTime:d,endTime:p})=>{d>e.startPerformanceTime&&(s+=p===0?xf()-d:p-d)});let n=0;return o&&o.durationItemList.forEach(d=>{d.startTime>e.startPerformanceTime&&(n+=d.getDuration())}),{renderFreezeTotal:s,dataFreezeTotal:n}}destroy(){this.core.innerEmitter.off("51",this.addKVReportBeforeExitRoom)}};br(Vf,"Name","TRTCVideoDecoder");var Bm=Vf;var lg=Mi($i());function Hm({timesInSecond:i,maxSizeInSecond:t,getSize:e}){return Me((r,o)=>{let s=new WeakMap;return H.on(L.ROOM_DESTROY,({room:n})=>s.delete(n)),function(...n){let d=s.get(this);if(d||(d={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},s.set(this,d)),d.timestamp===0?d.timestamp=Date.now():Date.now()-d.timestamp>1e3&&(d.timestamp=Date.now(),d.callCountInSecond=0,d.totalSizeInSecond=0),e&&(d.totalSizeInSecond+=e(...n)),d.timestamp!==0&&Date.now()-d.timestamp<1e3&&(d.callCountInSecond>=i||d.totalSizeInSecond>t))throw new he({code:te.INVALID_OPERATION,message:dt({key:ct.CALL_FREQUENCY_LIMIT,data:{isTimes:d.callCountInSecond>=i,isSize:d.totalSizeInSecond>t,name:o,timesInSecond:i,maxSizeInSecond:t}})});d.callCountInSecond++,r.call(this,...n)}})}var xI="2025-04-17 10:05:35",$f=!0,Bf=function(){var i;$f&&($f=!1,$.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${Mr}/en/index.html`),console.info(`* Changelog: ${Mr}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),$.info("TRTC Web SDK Version:",rt),Tr||$.debug("Build Time:",xI),$.info("UA:",navigator.userAgent),$.info(`URL: ${location.href}${((i=self.frameElement)==null?void 0:i.tagName)==="IFRAME"?" in iframe":""}`),jn().then(t=>{t&&$.info(gr)}))};var nr={SCENE_LIVE:"live",SCENE_RTC:"rtc",ROLE_ANCHOR:"anchor",ROLE_AUDIENCE:"audience",STREAM_TYPE_MAIN:"main",STREAM_TYPE_SUB:"sub",AUDIO_PROFILE_STANDARD:"standard",AUDIO_PROFILE_STANDARD_STEREO:"standard-stereo",AUDIO_PROFILE_HIGH:"high",AUDIO_PROFILE_HIGH_STEREO:"high-stereo",QOS_PREFERENCE_SMOOTH:"smooth",QOS_PREFERENCE_CLEAR:"clear",SPEAKER:"Speakerphone",HEADSET:"Headset earpiece"};var ue={INVALID_PARAMETER:5e3,INVALID_OPERATION:5100,ENV_NOT_SUPPORTED:5200,DEVICE_ERROR:5300,SERVER_ERROR:5400,OPERATION_FAILED:5500,OPERATION_ABORT:5998,UNKNOWN_ERROR:5999},Rr=(O=>(O[O.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",O[O.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",O[O.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",O[O.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",O[O.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",O[O.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",O[O.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",O[O.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",O[O.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",O[O.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",O[O.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",O[O.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",O[O.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",O[O.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",O[O.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",O[O.INVALID_ROOM_ID_REQUIED=5015]="INVALID_ROOM_ID_REQUIED",O[O.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",O[O.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",O[O.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",O[O.INVALID_OPERATION=5100]="INVALID_OPERATION",O[O.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",O[O.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",O[O.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",O[O.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",O[O.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",O[O.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",O[O.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",O[O.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",O[O.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",O[O.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",O[O.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",O[O.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",O[O.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",O[O.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",O[O.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",O[O.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",O[O.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",O[O.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",O[O.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",O[O.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",O[O.DEVICE_ERROR=5300]="DEVICE_ERROR",O[O.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",O[O.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",O[O.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",O[O.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",O[O.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",O[O.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",O[O.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",O[O.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",O[O.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",O[O.SERVER_ERROR=5400]="SERVER_ERROR",O[O.NEED_TO_BUY=5401]="NEED_TO_BUY",O[O.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",O[O.OPERATION_FAILED=5500]="OPERATION_FAILED",O[O.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",O[O.REJOIN_FAILED=5502]="REJOIN_FAILED",O[O.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",O[O.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",O[O.VIDEO_DECODE_ERROR=5505]="VIDEO_DECODE_ERROR",O[O.OPERATION_ABORT=5998]="OPERATION_ABORT",O[O.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",O))(Rr||{});function Wf({code:i,params:t,enableDocLink:e=!1}){let r="",o,s=Rr[i];try{o=Hf[s]}catch(n){o=Hf.UNKNOWN_ERROR}return Xe(o)?r=o(t):we(o)&&(r=o),t.fnName&&!r.includes(t.fnName)&&(r[r.length-1]!=="."&&(r+="."),r+=` thrown from ${t.fnName}()`),e&&(r+=" doc:"),r}var Hf=Ee(ee({},qt),{INVALID_PARAMETER({fnName:i}){return`the parameters of the '${i}' you called does not meet the requirements, please check the API documentation.`},INVALID_PARAMETER_REQUIRED({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' is a required param when calling ${e}(), received: ${r}.`},INVALID_PARAMETER_TYPE({key:i,rule:t,fnName:e,value:r}){let o=`${i||t.name}`,s="";return Array.isArray(t.type)?s=t.type.join("|"):s=t.type,`'${o}' must be type of ${s} when calling ${e}(), received type: ${ht(r)}.`},INVALID_PARAMETER_EMPTY({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' cannot be '${r}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:i,rule:t,fnName:e,value:r}){let o=`${i||t.name}`,s=`${t.instanceOf.name||t.instanceOf}`;return`'${o}' must be instanceof ${s} when calling ${e}(), received type: ${ht(r)}.`},INVALID_PARAMETER_RANGE({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' must be one of ${t.values.join("|")} when calling ${e}(), received: ${r}.`},INVALID_PARAMETER_LESS_THAN_ZERO({key:i,rule:t,fnName:e}){return`'${i||t.name}' cannot be less than 0 when calling ${e}().`},INVALID_PARAMETER_MIN({key:i,rule:t,value:e}){return`the min value of ${i||t.name} is ${t.min}, received: ${e}.`},INVALID_PARAMETER_MAX({key:i,rule:t,value:e}){return`the max value of ${i||t.name} is ${t.max}, received: ${e}.`},INVALID_ELEMENT_ID({key:i,fnName:t}){return`'${i}' is not found in the document object when calling ${t}().`},INVALID_ELEMENT_ID_TYPE({key:i,fnName:t,type:e}){return`the element corresponding to '${i}' must be instanceof HTMLElement when calling ${t}(), received: ${e}.`},INVALID_STREAM_ID({key:i}){return`'${i}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},INVALID_ROOM_ID_STRING({key:i}){return`'${i}' must be a valid string.`},INVALID_ROOM_ID_INTEGER({key:i}){return`'${i}' must be an integer between [1, 4294967294].`},INVALID_ROOM_ID_INTEGER_STRING({key:i}){return`'${i}' must be an integer but go a string, use 'parseInt' to convert it or use 'strRoomId' instead.`},INVALID_ROOM_ID_REQUIED(){return"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required."},INVALID_STREAM_TYPE:({fnName:i})=>`'streamType' is required when 'userId' is not '*', calling ${i}()`,INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION({fnName:i}){return`the API '${i}' you called does not meet the requirements, please check the API documentation.`},INVALID_OPERATION_NOT_JOINED({fnName:i}){return`cannot ${i} because you are not enter room yet.`},INVALID_OPERATION_REMOTE_USER_NOT_EXIST({fnName:i,value:t}){return`cannot ${i} because remote user(userId: ${t.userId}) does not publishing stream.`},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST({fnName:i,value:t}){return`cannot ${i} because remote user(userId: ${t.userId}) does not publishing ${t.streamType} video.`},INVALID_OPERATION_REPEAT_CALL({fnName:i}){return`you are already ${i}(), cannot repeated call '${i}'.`},INVALID_OPERATION_NEED_VIDEO({fnName:i}){return`cannot call '${i}' because the camera is not turned on.`},INVALID_OPERATION_NEED_AUDIO({fnName:i}){return`cannot call '${i}' because the microphone is not turned on.`},INVALID_BUFFER_EMPTY:({key:i})=>`the buffer size of paramerter '${i}' cannot be empty`,INVALID_BUFFER_OVERSIZE:()=>"buffer size is over 1000 Bytes",INVALID_ROLE_AUDIENCE:()=>"role: 'audience' cannot call this api.",INVALID_NOT_ENABLE_SEI:()=>"you need to enable SEI in TRTC.create({ enableSEI: true })",INVALID_NEED_CALL_PUBLISHED:({fnName:i})=>`you need to call ${i}() after publish stream.`,ENV_NOT_SUPPORTED({fnName:i}){return`the current browser does not support the capability of the function '${i}' you are calling, please check the API documentation.`},NOT_SUPPORTED_WEBRTC:"the current browser does not support WebRTC capability, please check the SDK documentation.",NOT_SUPPORTED_H264_ENCODE:"this browser does not support H264 encode.",NOT_SUPPORTED_H264_DECODE:"this browser does not support H264 decode.",NOT_SUPPORTED_SCREEN_SHARE:"this browser does not support screen share, please check the browser version.",NOT_SUPPORTED_SMALL_VIDEO:"this browser does not support small video, please check the browser version.",NOT_SUPPORTED_SEI:"this browser does not support SEI, please check the browser version.",NOT_SUPPORTED_WEBGL:"this browser does not support WebGL, please check the browser version.",NOT_SUPPORTED_CHROME_VERSION({fnName:i}){return`cannot call ${i} because the browser version is too low, please upgrade to the latest version`},DEVICE_ERROR({fnName:i,error:t}){return`'${i}' got device exception${t?`, error: ${t.toString()}.`:"."}`},DEVICE_NOT_FOUND_ERROR({fnName:i,deviceType:t=qo(i),error:e}){return`NotFoundError, no ${t} detected, please check your device and the configuration on '${i}'${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_ALLOWED_ERROR({fnName:i,deviceType:t=qo(i),error:e}){return`NotAllowedError, you have disabled ${t} access, please allow the current application to use the ${t}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_READABLE_ERROR({fnName:i,deviceType:t=qo(i),error:e}){return`NotReadableError, the ${t} maybe in use by another APP, please check if the device is pre-occupied by another APP.`},DEVICE_OVERCONSTRAINED_ERROR({fnName:i,deviceType:t=qo(i),error:e}){return`OverconstrainedError, the device ID is incorrect, please check whether the device ID passed in is correct${e?`, error: ${e.toString()}.`:"."}`},DEVICE_INVALID_STATE_ERROR({fnName:i,deviceType:t=qo(i),error:e}){return`InvalidStateError, after the user clicks and interacts with the page, turn on the ${t}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_SECURITY_ERROR({fnName:i,deviceType:t=qo(i),error:e}){return`SecurityError, check whether the system security policy restricts the use of the ${t}, and it is recommended to turn on the ${t} after the user interacts with the page${e?`, error: ${e.toString()}.`:"."}`},DEVICE_ABORT_ERROR({fnName:i,deviceType:t=qo(i),error:e}){return`AbortError, an unknown exception in the system makes the device unusable, recommended to change the device or browser and re-check whether the device is normal${e?` error: ${e.toString()}.`:"."}`},CAMERA_RECOVER_FAILED({error:i}){return`camera recover capture failed ${(i==null?void 0:i.name)||""}: ${(i==null?void 0:i.originMessage)||(i==null?void 0:i.message)}`},MICROPHONE_RECOVER_FAILED({error:i}){return`microphone recover capture failed ${(i==null?void 0:i.name)||""}: ${(i==null?void 0:i.originMessage)||(i==null?void 0:i.message)}`},OPERATION_FAILED({fnName:i,error:t}){return`'${i}' failed, reason: ${t==null?void 0:t.toString()}`},FIREWALL_RESTRICTION(){return"media connection failure due to firewall restrictions, please try to change your network."},EVENT_HANDLER_ERROR({eventName:i}){return`an error was caught on trtc.on('${i}', handler), please check your code on 'handler'.`},VIDEO_CONTEXT_ERROR({reason:i,error:t}){return`video context error ${i} ${(t==null?void 0:t.name)||""} ${(t==null?void 0:t.message)||""}`},SERVER_ERROR({fnName:i,error:t}){return`'${i}' got server error: ${t==null?void 0:t.toString()}, please check the SDK documentation.`},NEED_TO_BUY({value:i,url:t}){return`You need to buy packages for ${i}. Refer to: ${t}`},ACCOUNT_NO_MONEY:({fnParams:i})=>`your TRTC account run out of credit, please recharge.${i.sdkAppId?` SDKAppId: ${i.sdkAppId}`:""}`,OPERATION_ABORT({fnName:i}){return`'${i}' abort`},UNKNOWN_ERROR({fnName:i,error:t}){return`'${i}' throw unknown exception${t?`, error: ${t.toString()}.`:"."}`}});function qo(i){if(!i)return"camera";let t=i.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var Wm=class i extends Error{constructor({code:e,extraCode:r,message:o="",messageParams:s,fnName:n="",originError:d}){var m;let p;o?p=o:p=Wf({code:e===ue.SERVER_ERROR?e:r||e,params:ee({fnName:n,error:d},s)});super(p);u(this,"name","RtcError");u(this,"code");u(this,"extraCode");u(this,"functionName");u(this,"message");u(this,"handler");u(this,"originError");this.name=Rr[e],this.code=e,this.extraCode=r,this.functionName=n,this.originError=d,this.message=p,this.extraCode===5302&&((m=this.originError)!=null&&m.message.includes("system"))&&(this.handler=()=>{let g={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},_={startLocalVideo:"webcam",startLocalAudio:"microphone"},b=document.createElement("a");Ao?b.href=`ms-settings:privacy-${_[this.functionName]}`:_r&&(b.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${g[this.functionName]}`),b.href.length>0&&b.click()})}static convertFrom(e,r,o){let s=e;if(e instanceof he){let{stack:n}=e,d={code:ue.UNKNOWN_ERROR,fnName:r,originError:e};switch(e.getCode()){case te.INVALID_PARAMETER:d.code=ue.INVALID_PARAMETER,d.message=e.message;break;case te.INVALID_OPERATION:d.code=ue.INVALID_OPERATION;break;case te.NOT_SUPPORTED:case te.NOT_SUPPORTED_H264:d.code=ue.ENV_NOT_SUPPORTED,e.getCode()===te.NOT_SUPPORTED_H264&&(d.extraCode=e.message.includes(qt.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case te.JOIN_ROOM_FAILED:d.messageParams={fnParams:o};case te.SERVER_TIMEOUT:case te.SWITCH_ROLE_FAILED:d.code=ue.SERVER_ERROR,d.extraCode=e.getExtraCode();break;case te.API_CALL_ABORTED:d.code=ue.OPERATION_ABORT;break;case te.DEVICE_NOT_FOUND:case te.DEVICE_AUTO_RECOVER_FAILED:case te.INITIALIZE_FAILED:d.code=5300,e.name&&(d.extraCode=PI(e.name));break;case te.UNKNOWN:break;default:d.code=ue.OPERATION_FAILED}s=new i(d),n&&(s.stack+=n.substr(n.indexOf(`
91
+ `,j.push(ce);var ye,le,ve=Ja(Function,j).apply(null,q);return ye=ve,le=ns.length,ns.push(ye),W=le,as[U]=W,W},f:()=>{K("")},c:mn,t:(T,E,v)=>x.copyWithin(T,E,E+v),s:T=>{x.length,K("OOM")},i:(T,E,v,C)=>{for(var U,W,j,q=0,Z=0;Z<v;Z++){var B=De[E>>2],ce=De[E+4>>2];E+=8;for(var Re=0;Re<ce;Re++)U=T,W=x[B+Re],j=void 0,j=ec[U],W===0||W===10?((U===1?_:b)(Xa(j,0)),j.length=0):j.push(W);q+=ce}return De[C>>2]=q,0}},mr=(function(){var T,E,v,C,U={a:tc};function W(j,q){var Z,B,ce=j.exports;return N=(k=ce).v,Z=N.buffer,o.HEAP8=P=new Int8Array(Z),o.HEAP16=J=new Int16Array(Z),o.HEAP32=Ne=new Int32Array(Z),o.HEAPU8=x=new Uint8Array(Z),o.HEAPU16=Q=new Uint16Array(Z),o.HEAPU32=De=new Uint32Array(Z),o.HEAPF32=me=new Float32Array(Z),o.HEAPF64=xe=new Float64Array(Z),Fe=k.z,B=k.w,tn.unshift(B),function(){if(vr--,o.monitorRunDependencies&&o.monitorRunDependencies(vr),vr==0&&(Yo!==null&&(clearInterval(Yo),Yo=null),Ei)){var Re=Ei;Ei=null,Re()}}(),ce}if(vr++,o.monitorRunDependencies&&o.monitorRunDependencies(vr),o.instantiateWasm)try{return o.instantiateWasm(U,W)}catch(j){b("Module.instantiateWasm callback failed with error: "+j),r(j)}(T=g,E=Wr,v=U,C=function(j){W(j.instance)},T||typeof WebAssembly.instantiateStreaming!="function"||no(E)||typeof fetch!="function"?_i(E,v,C):fetch(E,{credentials:"same-origin"}).then(j=>WebAssembly.instantiateStreaming(j,v).then(C,function(q){return b("wasm streaming compile failed: "+q),b("falling back to ArrayBuffer instantiation"),_i(E,v,C)}))).catch(r)}(),T=>(mr=k.x)(T)),Di=T=>(Di=k.y)(T),cs=T=>(cs=k.A)(T),rc=(o.__embind_initialize_bindings=()=>(o.__embind_initialize_bindings=k.B)(),T=>(rc=k.C)(T));o.dynCall_jiji=(T,E,v,C,U)=>(o.dynCall_jiji=k.D)(T,E,v,C,U);function ic(){function T(){wt||(wt=!0,o.calledRun=!0,Ks||(ao(tn),e(o),o.onRuntimeInitialized&&o.onRuntimeInitialized(),function(){if(o.postRun)for(typeof o.postRun=="function"&&(o.postRun=[o.postRun]);o.postRun.length;)E=o.postRun.shift(),rn.unshift(E);var E;ao(rn)}()))}vr>0||(function(){if(o.preRun)for(typeof o.preRun=="function"&&(o.preRun=[o.preRun]);o.preRun.length;)E=o.preRun.shift(),en.unshift(E);var E;ao(en)}(),vr>0||(o.setStatus?(o.setStatus("Running..."),setTimeout(function(){setTimeout(function(){o.setStatus("")},1),T()},1)):T()))}if(Ei=function T(){wt||ic(),wt||(Ei=T)},o.preInit)for(typeof o.preInit=="function"&&(o.preInit=[o.preInit]);o.preInit.length>0;)o.preInit.pop()();return ic(),t.ready}})();var MI="web.sdk.qcloud.com",OI=`https://${MI}/trtc/webrtc/v5/doc`,CM=`${OI}/zh-cn/`,Uf=(i=>(i[i.TRACE=0]="TRACE",i[i.DEBUG=1]="DEBUG",i[i.INFO=2]="INFO",i[i.WARN=3]="WARN",i[i.ERROR=4]="ERROR",i[i.NONE=5]="NONE",i))(Uf||{});var Fd={CANVAS:"canvas",AUDIO:"audio",VIDEO:"video",SCREEN:"screen",SMALL:"small",BIG:"big",AUXILIARY:"auxiliary",SMALL_VIDEO:"smallVideo",FACING_MODE_USER:"user",FACING_MODE_ENVIRONMENT:"environment",MUTE:"mute",UNMUTE:"unmute",ENDED:"ended",PLAYING:"playing",PAUSE:"pause",ERROR:"error",LOADEDDATA:"loadeddata",LOADEDMETADATA:"loadedmetadata",AUDIO_INPUT:"audioinput",VIDEO_INPUT:"videoinput",DETAIL:"detail",TEXT:"text",MAIN:"main",BACKUP:"backup",BANNED:"banned",KICK:"kick",USER_TIME_OUT:"user_time_out",ROOM_DISBAND:"room_disband",SEI_MESSAGE:"sei-message",ADD:"add",REMOVE:"remove",REPLACE:"replace",TRACK:"track",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",TRANSCEIVER_DIRECTION_SENDONLY:"sendonly",TRANSCEIVER_DIRECTION_RECVONLY:"recvonly",ENTER_PICTURE_IN_PICTURE:"enterpictureinpicture",LEAVE_PICTURE_IN_PICTURE:"leavepictureinpicture"},DM=Fd.MAIN,NM=Fd.AUXILIARY,wM=Fd.BIG,MM=Fd.SMALL;var OM=Object.keys(Uf);var xM=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{};function xf(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var{toString:PM}=Object.prototype,Vf=class Ff{constructor(t){this.core=t,br(this,"contextMap",new Map),br(this,"decodeProcessorMap",new WeakMap),this.addKVReportBeforeExitRoom=this.addKVReportBeforeExitRoom.bind(this),this.createDecoder=this.createDecoder.bind(this),this.core.innerEmitter.on("51",this.addKVReportBeforeExitRoom)}getAlias(){return"videoDecoder"}getGroup(t){return t!=null&&t.track?`${t.track.userId}${t.track.streamType}`:"*"}getName(){return Ff.Name}getValidateRule(t){return{type:this.core.enums.BASIC_TYPE.Object}}createDecoder(t,e){switch(t){case"wasm":return new wI(Ld(kd({},e),{wasmPath:`${this.core.assetsPath||"."}/videodec.wasm`}));case"webCodecs":return new Js;case"mse":throw new Error("mse decoder not supported yet");default:throw new Error("Unsupported decoder type")}}start(t){this.decodeProcessorMap.set(t.track,this.decode(t)),this.core.room.videoManager.addDecodeProcessor({processor:({frame:e,track:r})=>{var o;return((o=this.decodeProcessorMap.get(r))==null?void 0:o({frame:e,track:r}))||e},type:3})}decode(t){let{pipe:e,take:r,subscribe:o}=this.core.rx;return({frame:s,track:n})=>{if(n!==t.track||s.type==="empty")return s;if(this.contextMap.has(n))return this.contextMap.get(n).decode(s);let d=this.core.room.videoManager.createDecodeContext(Ld(kd({},t),{createDecoder:this.createDecoder}));return e(d.trackDoneOB,r(1),o(()=>{this.core.clearStarted(this,this.getGroup(t)),this.stop({track:n})})),this.contextMap.set(n,d),d.decode(s)}}stop(t){if(t!=null&&t.track){let e=this.contextMap.get(t.track);e&&(e.close("stop"),this.report(e,t.track),this.contextMap.delete(t.track))}else this.contextMap.forEach((e,r)=>{e.close("stop"),this.contextMap.delete(r)});this.contextMap.size===0&&this.core.room.videoManager.removeDecodeProcessor({type:3})}report(t,e){if(t.isReported)return;t.isReported=!0;let r=xf()-t.startPerformanceTime,{renderFreezeTotal:o,dataFreezeTotal:s}=this.getRemoteTrackFreezeDuration(e,t);r&&this.core.kvStatManager.addNumber({key:514850,value:Math.floor(o/r*100),split:1}),r&&this.core.kvStatManager.addNumber({key:514851,value:Math.floor(s/r*100),split:1}),t.inputFrameCount&&this.core.kvStatManager.addNumber({key:514852,value:Math.floor(t.decodedFrameCount/t.inputFrameCount*100),split:1})}addKVReportBeforeExitRoom({room:t}){t===this.core.room&&this.contextMap.forEach((e,r)=>{this.report(e,r)})}update(t){let e=this.contextMap.get(t.track);e&&(t.type!=="mock"?(e.close("update"),this.contextMap.set(t.track,this.core.room.videoManager.createDecodeContext(Ld(kd({},t),{createDecoder:this.createDecoder})))):e.mock(this.core.enums.DECODE_FAILED_ERROR_CODE.TEST))}getRemoteTrackFreezeDuration(t,e){let r=this.core.room.badCaseDetector.getRenderFreezeMap().get(`${t.userId}_${t.streamType}`),o=this.core.room.badCaseDetector.getDataFreezeMap().get(`${t.userId}_${t.streamType}`),s=0;r&&r.freezeTimeline.forEach(({startTime:d,endTime:p})=>{d>e.startPerformanceTime&&(s+=p===0?xf()-d:p-d)});let n=0;return o&&o.durationItemList.forEach(d=>{d.startTime>e.startPerformanceTime&&(n+=d.getDuration())}),{renderFreezeTotal:s,dataFreezeTotal:n}}destroy(){this.core.innerEmitter.off("51",this.addKVReportBeforeExitRoom)}};br(Vf,"Name","TRTCVideoDecoder");var Bm=Vf;var lg=Mi($i());function Hm({timesInSecond:i,maxSizeInSecond:t,getSize:e}){return Me((r,o)=>{let s=new WeakMap;return H.on(L.ROOM_DESTROY,({room:n})=>s.delete(n)),function(...n){let d=s.get(this);if(d||(d={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},s.set(this,d)),d.timestamp===0?d.timestamp=Date.now():Date.now()-d.timestamp>1e3&&(d.timestamp=Date.now(),d.callCountInSecond=0,d.totalSizeInSecond=0),e&&(d.totalSizeInSecond+=e(...n)),d.timestamp!==0&&Date.now()-d.timestamp<1e3&&(d.callCountInSecond>=i||d.totalSizeInSecond>t))throw new he({code:te.INVALID_OPERATION,message:dt({key:ct.CALL_FREQUENCY_LIMIT,data:{isTimes:d.callCountInSecond>=i,isSize:d.totalSizeInSecond>t,name:o,timesInSecond:i,maxSizeInSecond:t}})});d.callCountInSecond++,r.call(this,...n)}})}var xI="2025-04-17 15:08:43",$f=!0,Bf=function(){var i;$f&&($f=!1,$.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${Mr}/en/index.html`),console.info(`* Changelog: ${Mr}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),$.info("TRTC Web SDK Version:",rt),Tr||$.debug("Build Time:",xI),$.info("UA:",navigator.userAgent),$.info(`URL: ${location.href}${((i=self.frameElement)==null?void 0:i.tagName)==="IFRAME"?" in iframe":""}`),jn().then(t=>{t&&$.info(gr)}))};var nr={SCENE_LIVE:"live",SCENE_RTC:"rtc",ROLE_ANCHOR:"anchor",ROLE_AUDIENCE:"audience",STREAM_TYPE_MAIN:"main",STREAM_TYPE_SUB:"sub",AUDIO_PROFILE_STANDARD:"standard",AUDIO_PROFILE_STANDARD_STEREO:"standard-stereo",AUDIO_PROFILE_HIGH:"high",AUDIO_PROFILE_HIGH_STEREO:"high-stereo",QOS_PREFERENCE_SMOOTH:"smooth",QOS_PREFERENCE_CLEAR:"clear",SPEAKER:"Speakerphone",HEADSET:"Headset earpiece"};var ue={INVALID_PARAMETER:5e3,INVALID_OPERATION:5100,ENV_NOT_SUPPORTED:5200,DEVICE_ERROR:5300,SERVER_ERROR:5400,OPERATION_FAILED:5500,OPERATION_ABORT:5998,UNKNOWN_ERROR:5999},Rr=(O=>(O[O.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",O[O.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",O[O.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",O[O.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",O[O.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",O[O.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",O[O.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",O[O.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",O[O.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",O[O.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",O[O.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",O[O.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",O[O.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",O[O.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",O[O.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",O[O.INVALID_ROOM_ID_REQUIED=5015]="INVALID_ROOM_ID_REQUIED",O[O.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",O[O.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",O[O.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",O[O.INVALID_OPERATION=5100]="INVALID_OPERATION",O[O.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",O[O.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",O[O.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",O[O.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",O[O.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",O[O.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",O[O.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",O[O.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",O[O.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",O[O.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",O[O.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",O[O.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",O[O.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",O[O.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",O[O.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",O[O.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",O[O.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",O[O.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",O[O.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",O[O.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",O[O.DEVICE_ERROR=5300]="DEVICE_ERROR",O[O.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",O[O.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",O[O.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",O[O.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",O[O.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",O[O.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",O[O.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",O[O.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",O[O.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",O[O.SERVER_ERROR=5400]="SERVER_ERROR",O[O.NEED_TO_BUY=5401]="NEED_TO_BUY",O[O.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",O[O.OPERATION_FAILED=5500]="OPERATION_FAILED",O[O.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",O[O.REJOIN_FAILED=5502]="REJOIN_FAILED",O[O.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",O[O.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",O[O.VIDEO_DECODE_ERROR=5505]="VIDEO_DECODE_ERROR",O[O.OPERATION_ABORT=5998]="OPERATION_ABORT",O[O.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",O))(Rr||{});function Wf({code:i,params:t,enableDocLink:e=!1}){let r="",o,s=Rr[i];try{o=Hf[s]}catch(n){o=Hf.UNKNOWN_ERROR}return Xe(o)?r=o(t):we(o)&&(r=o),t.fnName&&!r.includes(t.fnName)&&(r[r.length-1]!=="."&&(r+="."),r+=` thrown from ${t.fnName}()`),e&&(r+=" doc:"),r}var Hf=Ee(ee({},qt),{INVALID_PARAMETER({fnName:i}){return`the parameters of the '${i}' you called does not meet the requirements, please check the API documentation.`},INVALID_PARAMETER_REQUIRED({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' is a required param when calling ${e}(), received: ${r}.`},INVALID_PARAMETER_TYPE({key:i,rule:t,fnName:e,value:r}){let o=`${i||t.name}`,s="";return Array.isArray(t.type)?s=t.type.join("|"):s=t.type,`'${o}' must be type of ${s} when calling ${e}(), received type: ${ht(r)}.`},INVALID_PARAMETER_EMPTY({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' cannot be '${r}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:i,rule:t,fnName:e,value:r}){let o=`${i||t.name}`,s=`${t.instanceOf.name||t.instanceOf}`;return`'${o}' must be instanceof ${s} when calling ${e}(), received type: ${ht(r)}.`},INVALID_PARAMETER_RANGE({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' must be one of ${t.values.join("|")} when calling ${e}(), received: ${r}.`},INVALID_PARAMETER_LESS_THAN_ZERO({key:i,rule:t,fnName:e}){return`'${i||t.name}' cannot be less than 0 when calling ${e}().`},INVALID_PARAMETER_MIN({key:i,rule:t,value:e}){return`the min value of ${i||t.name} is ${t.min}, received: ${e}.`},INVALID_PARAMETER_MAX({key:i,rule:t,value:e}){return`the max value of ${i||t.name} is ${t.max}, received: ${e}.`},INVALID_ELEMENT_ID({key:i,fnName:t}){return`'${i}' is not found in the document object when calling ${t}().`},INVALID_ELEMENT_ID_TYPE({key:i,fnName:t,type:e}){return`the element corresponding to '${i}' must be instanceof HTMLElement when calling ${t}(), received: ${e}.`},INVALID_STREAM_ID({key:i}){return`'${i}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},INVALID_ROOM_ID_STRING({key:i}){return`'${i}' must be a valid string.`},INVALID_ROOM_ID_INTEGER({key:i}){return`'${i}' must be an integer between [1, 4294967294].`},INVALID_ROOM_ID_INTEGER_STRING({key:i}){return`'${i}' must be an integer but go a string, use 'parseInt' to convert it or use 'strRoomId' instead.`},INVALID_ROOM_ID_REQUIED(){return"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required."},INVALID_STREAM_TYPE:({fnName:i})=>`'streamType' is required when 'userId' is not '*', calling ${i}()`,INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION({fnName:i}){return`the API '${i}' you called does not meet the requirements, please check the API documentation.`},INVALID_OPERATION_NOT_JOINED({fnName:i}){return`cannot ${i} because you are not enter room yet.`},INVALID_OPERATION_REMOTE_USER_NOT_EXIST({fnName:i,value:t}){return`cannot ${i} because remote user(userId: ${t.userId}) does not publishing stream.`},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST({fnName:i,value:t}){return`cannot ${i} because remote user(userId: ${t.userId}) does not publishing ${t.streamType} video.`},INVALID_OPERATION_REPEAT_CALL({fnName:i}){return`you are already ${i}(), cannot repeated call '${i}'.`},INVALID_OPERATION_NEED_VIDEO({fnName:i}){return`cannot call '${i}' because the camera is not turned on.`},INVALID_OPERATION_NEED_AUDIO({fnName:i}){return`cannot call '${i}' because the microphone is not turned on.`},INVALID_BUFFER_EMPTY:({key:i})=>`the buffer size of paramerter '${i}' cannot be empty`,INVALID_BUFFER_OVERSIZE:()=>"buffer size is over 1000 Bytes",INVALID_ROLE_AUDIENCE:()=>"role: 'audience' cannot call this api.",INVALID_NOT_ENABLE_SEI:()=>"you need to enable SEI in TRTC.create({ enableSEI: true })",INVALID_NEED_CALL_PUBLISHED:({fnName:i})=>`you need to call ${i}() after publish stream.`,ENV_NOT_SUPPORTED({fnName:i}){return`the current browser does not support the capability of the function '${i}' you are calling, please check the API documentation.`},NOT_SUPPORTED_WEBRTC:"the current browser does not support WebRTC capability, please check the SDK documentation.",NOT_SUPPORTED_H264_ENCODE:"this browser does not support H264 encode.",NOT_SUPPORTED_H264_DECODE:"this browser does not support H264 decode.",NOT_SUPPORTED_SCREEN_SHARE:"this browser does not support screen share, please check the browser version.",NOT_SUPPORTED_SMALL_VIDEO:"this browser does not support small video, please check the browser version.",NOT_SUPPORTED_SEI:"this browser does not support SEI, please check the browser version.",NOT_SUPPORTED_WEBGL:"this browser does not support WebGL, please check the browser version.",NOT_SUPPORTED_CHROME_VERSION({fnName:i}){return`cannot call ${i} because the browser version is too low, please upgrade to the latest version`},DEVICE_ERROR({fnName:i,error:t}){return`'${i}' got device exception${t?`, error: ${t.toString()}.`:"."}`},DEVICE_NOT_FOUND_ERROR({fnName:i,deviceType:t=qo(i),error:e}){return`NotFoundError, no ${t} detected, please check your device and the configuration on '${i}'${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_ALLOWED_ERROR({fnName:i,deviceType:t=qo(i),error:e}){return`NotAllowedError, you have disabled ${t} access, please allow the current application to use the ${t}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_READABLE_ERROR({fnName:i,deviceType:t=qo(i),error:e}){return`NotReadableError, the ${t} maybe in use by another APP, please check if the device is pre-occupied by another APP.`},DEVICE_OVERCONSTRAINED_ERROR({fnName:i,deviceType:t=qo(i),error:e}){return`OverconstrainedError, the device ID is incorrect, please check whether the device ID passed in is correct${e?`, error: ${e.toString()}.`:"."}`},DEVICE_INVALID_STATE_ERROR({fnName:i,deviceType:t=qo(i),error:e}){return`InvalidStateError, after the user clicks and interacts with the page, turn on the ${t}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_SECURITY_ERROR({fnName:i,deviceType:t=qo(i),error:e}){return`SecurityError, check whether the system security policy restricts the use of the ${t}, and it is recommended to turn on the ${t} after the user interacts with the page${e?`, error: ${e.toString()}.`:"."}`},DEVICE_ABORT_ERROR({fnName:i,deviceType:t=qo(i),error:e}){return`AbortError, an unknown exception in the system makes the device unusable, recommended to change the device or browser and re-check whether the device is normal${e?` error: ${e.toString()}.`:"."}`},CAMERA_RECOVER_FAILED({error:i}){return`camera recover capture failed ${(i==null?void 0:i.name)||""}: ${(i==null?void 0:i.originMessage)||(i==null?void 0:i.message)}`},MICROPHONE_RECOVER_FAILED({error:i}){return`microphone recover capture failed ${(i==null?void 0:i.name)||""}: ${(i==null?void 0:i.originMessage)||(i==null?void 0:i.message)}`},OPERATION_FAILED({fnName:i,error:t}){return`'${i}' failed, reason: ${t==null?void 0:t.toString()}`},FIREWALL_RESTRICTION(){return"media connection failure due to firewall restrictions, please try to change your network."},EVENT_HANDLER_ERROR({eventName:i}){return`an error was caught on trtc.on('${i}', handler), please check your code on 'handler'.`},VIDEO_CONTEXT_ERROR({reason:i,error:t}){return`video context error ${i} ${(t==null?void 0:t.name)||""} ${(t==null?void 0:t.message)||""}`},SERVER_ERROR({fnName:i,error:t}){return`'${i}' got server error: ${t==null?void 0:t.toString()}, please check the SDK documentation.`},NEED_TO_BUY({value:i,url:t}){return`You need to buy packages for ${i}. Refer to: ${t}`},ACCOUNT_NO_MONEY:({fnParams:i})=>`your TRTC account run out of credit, please recharge.${i.sdkAppId?` SDKAppId: ${i.sdkAppId}`:""}`,OPERATION_ABORT({fnName:i}){return`'${i}' abort`},UNKNOWN_ERROR({fnName:i,error:t}){return`'${i}' throw unknown exception${t?`, error: ${t.toString()}.`:"."}`}});function qo(i){if(!i)return"camera";let t=i.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var Wm=class i extends Error{constructor({code:e,extraCode:r,message:o="",messageParams:s,fnName:n="",originError:d}){var m;let p;o?p=o:p=Wf({code:e===ue.SERVER_ERROR?e:r||e,params:ee({fnName:n,error:d},s)});super(p);u(this,"name","RtcError");u(this,"code");u(this,"extraCode");u(this,"functionName");u(this,"message");u(this,"handler");u(this,"originError");this.name=Rr[e],this.code=e,this.extraCode=r,this.functionName=n,this.originError=d,this.message=p,this.extraCode===5302&&((m=this.originError)!=null&&m.message.includes("system"))&&(this.handler=()=>{let g={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},_={startLocalVideo:"webcam",startLocalAudio:"microphone"},b=document.createElement("a");Ao?b.href=`ms-settings:privacy-${_[this.functionName]}`:_r&&(b.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${g[this.functionName]}`),b.href.length>0&&b.click()})}static convertFrom(e,r,o){let s=e;if(e instanceof he){let{stack:n}=e,d={code:ue.UNKNOWN_ERROR,fnName:r,originError:e};switch(e.getCode()){case te.INVALID_PARAMETER:d.code=ue.INVALID_PARAMETER,d.message=e.message;break;case te.INVALID_OPERATION:d.code=ue.INVALID_OPERATION;break;case te.NOT_SUPPORTED:case te.NOT_SUPPORTED_H264:d.code=ue.ENV_NOT_SUPPORTED,e.getCode()===te.NOT_SUPPORTED_H264&&(d.extraCode=e.message.includes(qt.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case te.JOIN_ROOM_FAILED:d.messageParams={fnParams:o};case te.SERVER_TIMEOUT:case te.SWITCH_ROLE_FAILED:d.code=ue.SERVER_ERROR,d.extraCode=e.getExtraCode();break;case te.API_CALL_ABORTED:d.code=ue.OPERATION_ABORT;break;case te.DEVICE_NOT_FOUND:case te.DEVICE_AUTO_RECOVER_FAILED:case te.INITIALIZE_FAILED:d.code=5300,e.name&&(d.extraCode=PI(e.name));break;case te.UNKNOWN:break;default:d.code=ue.OPERATION_FAILED}s=new i(d),n&&(s.stack+=n.substr(n.indexOf(`
92
92
  `)))}else{if(e instanceof i)return e;s=new i({code:ue.UNKNOWN_ERROR,fnName:r,originError:e})}return s}};function PI(i){let t;switch(i){case"NotFoundError":t=5301;break;case"NotAllowedError":t=5302;break;case"NotReadableError":t=5303;break;case"OverconstrainedError":t=5304;break;case"InvalidStateError":t=5305;break;case"SecurityError":t=5306;break;case"AbortError":t=5307;break;default:t=5300}return t}var ae=Wm;var Gf={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}}},jf={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}}},zs={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(i,t,e){if(we(i)&&!document.getElementById(i))throw new ae({code:ue.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:t}})}},qf={name:"userId",required:!0,type:"string"},Jf={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[nr.AUDIO_PROFILE_STANDARD,nr.AUDIO_PROFILE_STANDARD_STEREO,nr.AUDIO_PROFILE_HIGH,nr.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function Ca(i,t){if(!i)throw new ae({code:ue.INVALID_OPERATION,extraCode:5101,fnName:t})}function zf(i,t,e){if(!i)throw new ae({code:ue.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:e}})}var GO={type:"number",notLessThanZero:!0},kI={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(i,t,e){if(this._room.isJoined)throw new ae({code:ue.INVALID_OPERATION,extraCode:5104,fnName:e});if(i.roomId){if(we(i.roomId))throw new ae({code:ue.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:t}});if(!(/^[1-9]\d*$/.test(String(i.roomId))&&i.roomId<4294967295))throw new ae({code:ue.INVALID_PARAMETER,extraCode:5013,fnName:e,messageParams:{key:t}})}else if(i.strRoomId){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(i.strRoomId))throw new ae({code:ue.INVALID_PARAMETER,extraCode:5012,fnName:e,messageParams:{key:t}})}else throw new ae({code:ue.INVALID_PARAMETER,extraCode:5015,fnName:e})},properties:{sdkAppId:{required:!0,type:"number",allowEmpty:!1},userId:{required:!0,type:"string",allowEmpty:!1},userSig:{required:!0,type:"string",allowEmpty:!1},scene:{type:"string",values:["live","rtc"]},role:{type:"string",values:["audience","anchor"]},roomId:{type:["string","number"]},strRoomId:{type:"string"},proxy:{type:["object","string"],properties:{websocketProxy:{type:"string"},turnServer:{type:["object","array"],properties:{url:{required:!0,type:"string"},username:{type:"string"},credential:{type:"string"},credentialType:{type:"string",values:["password"]}}},loggerProxy:{type:"string"},webtransportProxy:{type:"string"}}},enableAutoPlayDialog:{type:"boolean"},userDefineRecordId:{type:"string"},latencyLevel:{type:"number"},playoutDelay:{type:"object",properties:{min:{type:"number",min:0,max:1e3},max:{type:"number",min:0,max:1e4}}}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:zs,mute:{type:["boolean","string"]},publish:{type:"boolean"},option:Gf},validate(i){var t;if(!((t=i==null?void 0:i.option)!=null&&t.videoTrack)&&ai())throw new ae({code:ue.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:Ee(ee({},zs),{required:!1}),publish:{type:"boolean"},mute:{type:["boolean","string"]},option:Gf}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:Jf},validate(i){var t;if(!((t=i==null?void 0:i.option)!=null&&t.audioTrack)&&ai())throw new ae({code:ue.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:Jf}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:zs,publish:{type:"boolean"},option:jf},validate(i,t,e,r,o){var s;if(!((s=i==null?void 0:i.option)!=null&&s.videoTrack)){if(ai())throw new ae({code:ue.ENV_NOT_SUPPORTED,extraCode:5201});if(!ta())throw new ae({code:ue.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:zs,publish:{type:"boolean"},option:jf}},muteRemoteAudio:[qf,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[qf,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:zs,userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(i,t,e){Ca(this._room.isJoined,e);let r=this._room.remotePublishedUserMap.get(i.userId);if(zf(!!r,e,i),r&&(i.streamType==="main"&&!r.muteState.videoAvailable||i.streamType==="sub"&&!r.muteState.hasAuxiliary))throw new ae({code:ue.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:i}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:Ee(ee({},zs),{required:!1}),userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(i,t,e){Ca(this._room.isJoined,e);let r=this._room.remotePublishedUserMap.get(i.userId);if(zf(!!r,e,i),r&&(i.streamType==="main"&&!r.muteState.videoAvailable||i.streamType==="sub"&&!r.muteState.hasAuxiliary))throw new ae({code:ue.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:i}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(i,t,e){if(i.userId!=="*"&&V(i.streamType))throw new ae({code:ue.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(i,t,e){Ca(this._room.isJoining||this._room.isJoined,e)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(i,t,e,r){if(!sa)throw new ae({code:ue.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new ae({code:ue.INVALID_OPERATION,fnName:e,extraCode:5108});if(i.byteLength>1e3)throw new ae({code:ue.INVALID_PARAMETER,extraCode:5018,fnName:e});if(i.byteLength===0)throw new ae({code:ue.INVALID_PARAMETER,extraCode:5017,messageParams:{key:t},fnName:e});Ca(this._room.isJoined,e)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(i,t,e){if(!i&&!this._room.isMainStreamPublished||i&&!this._room.isAuxStreamPublished)throw new ae({code:ue.INVALID_OPERATION,extraCode:5109,messageParams:{key:t},fnName:e})}}}}],sendCustomMessage:{name:"message",required:!0,type:"object",properties:{cmdId:{type:"number",required:!0,min:1,max:10},data:{instanceOf:ArrayBuffer,required:!0,validate(i,t,e,r){if(i.byteLength>1e3)throw new ae({code:ue.INVALID_PARAMETER,extraCode:5018,fnName:e});if(i.byteLength===0)throw new ae({code:ue.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:t}})}}},validate(i,t,e){if(Ca(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new ae({code:ue.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:t}})}}},bt={TRTC:kI};var Lt=class extends Error{};function LI(i,t){let e=So(i);for(let r=0;r<t.length;r++)kr(e[r],t[r]);return e}function UI(i){this._resolve=Promise.resolve(i)}function VI(i){this._reject=Promise.reject(i)}var Yi=class Yi{constructor(t,e){this.instance=t;this.group=e;u(this,"started",!1);u(this,"ops",[]);u(this,"startSame",()=>!0);u(this,"mergeUpdate",LI);let r=Yi.instances.get(t);r?r.set(e,this):Yi.instances.set(t,new Map([[e,this]]))}static get(t,e){if(!e)return;let r=Yi.instances.get(t);return r&&r.get(e)||new Yi(t,e)}static gets(t,e){let r=Yi.instances.get(t),o=[];return r&&r.forEach((s,n)=>{e.test(n)&&o.push(s)}),o}action(t,e,r){let o=d=>{var p;return t===0?this.started=!0:t===3&&(this.started=!1),this.ops.shift(),(p=this.currentOp)==null||p.action(),d},s=d=>{var p,m;throw this.ops.shift(),t===0&&((p=this.currentOp)==null?void 0:p.type)===2&&this.ops.shift().reject(new Lt("start failed")),(m=this.currentOp)==null||m.action(),d},n={type:t,action:()=>e(...n.args).then(o,s),args:r,resolve:UI,reject:VI};try{switch(this.state){case 1:if(t===0)throw new Lt("already started");break;case 4:if(t===2)throw new Lt("not started");break;default:return this.cacheOp(n)}}catch(d){return Promise.reject(d)}return this.ops.push(n),n.promise=e(...n.args).then(o,s)}cacheOp(t){if(this.ops.length===1)switch(this.state){case 0:case 2:if(t.type===0)throw new Lt("already start");break;case 3:switch(t.type){case 2:throw new Lt("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new Lt("unknown state")}else switch(t.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let r=new Lt("keep stop");if(this.ops.slice(1).forEach(o=>o.reject(r)),this.ops=this.ops.slice(0,1),this.state===3)return this.currentOp.promise}break;case 2:switch(this.lastOpType){case 2:return this.lastOp.args=this.mergeUpdate(this.lastOp.args,t.args),this.lastOp.promise;case 3:throw new Lt("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new Lt("start not allowed after update");case 0:throw new Lt("duplicate start");case 3:if(this.startSame(this.currentOp.args,t.args))throw this.ops.pop().reject(new Lt("keep start")),new Lt("already start")}}t.promise=new Promise((r,o)=>{t._resolve?t._resolve.then(r):t.resolve=r,t._reject?t._reject.catch(o):t.reject=o});let{action:e}=t;return t.action=()=>e().then(t.resolve,t.reject),this.ops.push(t),t.promise}get lastOp(){return this.ops[this.ops.length-1]}get lastOpType(){return this.lastOp.type}get currentOp(){return this.ops[0]}get state(){return this.currentOp?this.currentOp.type:this.started?1:4}};u(Yi,"instances",new WeakMap);var fi=Yi;var $d=new WeakMap,Bd=(i,t)=>{if(t instanceof Lt){let{stack:e}=t;t=new ae({code:ue.OPERATION_ABORT,message:`${i} abort: ${t.message}`,fnName:i}),e&&(t.stack+=e.substr(e.indexOf(`
93
93
  `)))}throw t};function Zi(i,t){return Me((e,r)=>function(...o){let s=fi.get(this,typeof i=="string"?i:i.call(this,...o));return s?(t&&(s.startSame=t.bind(this)),s.action(0,e.bind(this),o).catch(Bd.bind(null,r))):e.apply(this,o)})}function Jo(i,t){let{merge:e,debounce:r}=t||{};return Me((o,s)=>function(...n){let d=fi.get(this,typeof i=="string"?i:i.call(this,...n));if(!d)return o.apply(this,n);if(e&&(d.mergeUpdate=e.bind(this)),r&&r.isNeedToDebounce.apply(this,n)){let{delay:p,getKey:m}=r;return new Promise((g,_)=>{var k,P;let b=(k=$d.get(this))==null?void 0:k.get(m(...n));if(b){let{timeoutId:x,resolve:J}=b;clearTimeout(x),J()}let N=setTimeout(()=>{if(d.state===3||d.state===4)return g();d.action(2,o.bind(this),n).catch(Bd.bind(null,s)).then(g,_)},p);$d.has(this)?(P=$d.get(this))==null||P.set(m(...n),{timeoutId:N,resolve:g}):$d.set(this,new Map([[m(...n),{timeoutId:N,resolve:g}]]))})}return d.action(2,o.bind(this),n).catch(Bd.bind(null,s))})}function Ki(i){return Me((t,e)=>function(...r){let o=typeof i=="function"?i.call(this,...r):i;if(o instanceof RegExp)return Promise.all(fi.gets(this,o).map(n=>n.action(3,()=>Promise.resolve(),r))).then(()=>t.call(this,...r));let s=fi.get(this,o);return s?s.action(3,t.bind(this),r).catch(Bd.bind(null,e)):t.apply(this,r)})}var se={ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",KICKED_OUT:"kicked-out",REMOTE_USER_ENTER:"remote-user-enter",REMOTE_USER_EXIT:"remote-user-exit",REMOTE_AUDIO_AVAILABLE:"remote-audio-available",REMOTE_AUDIO_UNAVAILABLE:"remote-audio-unavailable",REMOTE_VIDEO_AVAILABLE:"remote-video-available",REMOTE_VIDEO_UNAVAILABLE:"remote-video-unavailable",AUDIO_VOLUME:"audio-volume",AUDIO_FRAME:"audio-frame",NETWORK_QUALITY:"network-quality",CONNECTION_STATE_CHANGED:"connection-state-changed",AUDIO_PLAY_STATE_CHANGED:"audio-play-state-changed",VIDEO_PLAY_STATE_CHANGED:"video-play-state-changed",SCREEN_SHARE_STOPPED:"screen-share-stopped",DEVICE_CHANGED:"device-changed",PUBLISH_STATE_CHANGED:"publish-state-changed",TRACK:"track",STATISTICS:"statistics",SEI_MESSAGE:"sei-message",CUSTOM_MESSAGE:"custom-message",VIDEO_DECODE_DOWNGRADE_STATE_CHANGED:"video-decode-downgrade-state-changed",LAYER_DATA:"layerData",FIRST_VIDEO_FRAME:"first-video-frame"},Xf=new Set([se.ERROR,se.AUTOPLAY_FAILED,se.KICKED_OUT,se.REMOTE_USER_ENTER,se.REMOTE_USER_EXIT,se.REMOTE_AUDIO_AVAILABLE,se.REMOTE_AUDIO_UNAVAILABLE,se.REMOTE_VIDEO_AVAILABLE,se.REMOTE_VIDEO_UNAVAILABLE,se.CONNECTION_STATE_CHANGED,se.PUBLISH_STATE_CHANGED,se.SCREEN_SHARE_STOPPED,se.DEVICE_CHANGED,se.FIRST_VIDEO_FRAME]);function eo(i){return i==="sub"?"auxiliary":i==="auxiliary"?"sub":"main"}function Da(i){return i===nr.QOS_PREFERENCE_CLEAR?"detail":i===nr.QOS_PREFERENCE_SMOOTH?"motion":""}var jm={};Jr(jm,{bytes2ms:()=>Fp,convertObjectNumberToInt:()=>On,copyProperties:()=>Vp,deepClone:()=>So,deepMerge:()=>kr,delay:()=>xn,fibonacci:()=>yo,formatedTime:()=>gc,getConstructorName:()=>Nn,getContainerFromElement:()=>Jp,getEnv:()=>kp,getInternalVersion:()=>jp,getLoggerUrl:()=>Yr,getMuteStateFromFlag:()=>Mn,getNetworkType:()=>Cn,getNumNetworkType:()=>fc,getReconnectionTimeout:()=>Bp,getStringByteLength:()=>zp,getTurnServer:()=>qp,getUint32Version:()=>Tc,getValueType:()=>ht,getViewListFromView:()=>Es,glog:()=>Dn,ipv4ToUint32:()=>gs,isArray:()=>st,isAudioWorkletSupported:()=>Gp,isBoolean:()=>nt,isConstructor:()=>hs,isEmpty:()=>fs,isFunction:()=>Xe,isLangChinese:()=>fr,isMediaStreamTrack:()=>Hp,isNumber:()=>je,isObject:()=>Pr,isOverseaSdkAppId:()=>vn,isPlainObject:()=>Gt,isPortrait:()=>_c,isPromise:()=>xi,isRemoteTrack:()=>Wp,isString:()=>we,isUndefined:()=>V,loadImage:()=>_s,ms2bytes:()=>$p,ms2samples:()=>Hu,performanceNow:()=>_e,promiseAny:()=>wn,samples2ms:()=>Bu,setNetworkType:()=>Up,stringify:()=>ir,stringifyIncludeValue:()=>Ec,throttlePromise:()=>Ic});var zm={};Jr(zm,{ScheduleRequestType:()=>Yf,getAbilityConfig:()=>$I,getScheduleDomain:()=>Zf,isNeedToSchedule:()=>Hd,scheduleProxy:()=>ro,sendScheduleRequest:()=>Jm,setIsNeedToSchedule:()=>zo,setScheduleProxy:()=>Wd});var qm=null,Hd=!0;typeof document!="undefined"&&document.head.insertAdjacentHTML("beforeend",Object.values(Qr).map(i=>`<link rel="dns-prefetch" href="https://${i}">`).join(`\r
94
94
  `));function zo(i){nt(i)&&i!==Hd&&(Hd=i,$.info(`setIsNeedToSchedule ${i}`))}H.on("28",()=>zo(!0));H.on("63",()=>zo(!0));H.on("84",()=>zo(!0));H.on("201",i=>{i.state==="RECONNECTING"&&zo(!0)});H.on("202",i=>{i.state==="RECONNECTING"&&zo(!0)});function FI(i,t,e){let r={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let o=performance.getEntriesByType("resource"),s=to(i,"config",D.MAIN),n=to(i,"config",D.BACKUP);for(let d of o)if(d.startTime>=e&&(d.name===s||d.name===n)&&d.transferSize>0){let p=d.name===s?D.MAIN:D.BACKUP,m=Math.round(d.duration),g=Math.round(d.domainLookupStart-d.startTime),_=d.redirectStart>0?Math.round(d.redirectEnd-d.redirectStart):0,b=d.fetchStart>0?Math.round(d.domainLookupStart-d.fetchStart):0,N=Math.round(d.domainLookupEnd-d.domainLookupStart),k=Math.round(d.requestStart-d.secureConnectionStart),P=Math.round(d.secureConnectionStart-d.connectStart),x=Math.round(d.responseStart-d.requestStart),J=Math.round(d.responseEnd-d.responseStart),Q=[N,k,P,x,J];Be.uploadEvent({log:`stat-schedule-net:${m}(${g}(${_}->${b})->${Q.join("->")}) ${p}`,userId:t}),r=Ee(ee({},r),{totalCost:m,local:g,dns:N,tcp:P,tls:k,request:x,response:J});break}}catch(o){$.error("getScheduleDetailCost error",o)}return r}function Jm(m){return y(this,arguments,function*({userId:i,sdkAppId:t,useStringRoomId:e,roomId:r,userSig:o,version:s,frameWorkType:n,role:d,latencyLevel:p}){if(!Hd&&qm)return{isCached:!0,result:qm};let g={delta:0,count:[1,1],msg:[],detail:[]};try{let _=new FormData;_.append("userId",String(i)),_.append("sdkAppId",String(t)),_.append("isStrGroupId",String(e)),_.append("groupId",String(r)),_.append("sdkVersion",s),_.append("userSig",String(o)),d&&_.append("role",String(d)),p&&_.append("latencyLevel",String(p)),n&&_.append("frameWorkType",String(n));let b=_e(),N=yield HI(_,g,t);N.config&&(N.config.loggerDomain&&_o(N.config.loggerDomain),nt(N.config.scheduleCache)&&zo(!N.config.scheduleCache)),g.delta=_e()-b;let k=FI(Number(t),i,b);return qm=N,{isCached:!1,result:N,detailCost:k}}catch(_){let b=st(_)?_[0]:_,N=je(b.code)?b.code:0,k=`schedule failed${b.message?`: ${b.message}`:""}`,P=new he({code:te.SCHEDULE_FAILED,extraCode:N,message:dt({key:ct.JOIN_ROOM_FAILED,data:{error:k,code:N}})});throw $.error(k,N),P}})}var ro={main:"",backup:""};function Wd(i){st(i)?(ro.main=i[0],ro.backup=i[1]):ro.main=i}var Yf=(r=>(r.CONFIG="config",r.TRTC_AUTO_CONF="trtcAutoConf",r.AUDIO_AI_AUTH="audioAiAuth",r))(Yf||{});function to(i,t,e=D.MAIN,r=!1){return`https://${ro[e]||Zf(i,e,r)}/api/v1/${t}`}function $I(i,t,e){let r=to(i,t),o=to(i,t,D.BACKUP),s=new URLSearchParams(e).toString(),n=fetch(`${r}?${s}`).then(p=>p.json()),d=fetch(`${o}?${s}`).then(p=>p.json());return wn([n,d])}function Zf(i,t=D.MAIN,e=!1){let r;return vn(i)?e?r=t===D.MAIN?Qr.MAIN_OVERSEA_BACKUP:Qr.BACKUP_OVERSEA:r=t===D.MAIN?Qr.MAIN_OVERSEA:Qr.BACKUP_OVERSEA:r=t===D.MAIN?Qr.MAIN:Qr.BACKUP,r}function BI(i,t,e){return new Promise((r,o)=>{Zr({url:i,body:t,timeout:e.timeout,priority:"high"}).then(s=>{s.data.code===0?r(s.data.data):o({code:s.data.code,message:s.data.msg})}).catch(o)})}var Qf=(i,t)=>ki({retryFunction:BI,settings:{retries:3,timeout:0},onError:t,onRetrying:i});function HI(i,t,e){return new Promise((r,o)=>{let s=null;wn([Qf(n=>t.count[0]=n+1,({error:n,retry:d,retriedCount:p,retryFuncArgs:m})=>{t.msg[0]=n.message,s||(p>=1&&(m[0]=to(e,"config",D.MAIN,!0)),d())})(to(e,"config",D.MAIN),i,{get timeout(){return yo(2+t.count[0])*1e3}}),Qf(n=>t.count[1]=n+1,({error:n,retry:d,retriedCount:p,retryFuncArgs:m})=>{t.msg[1]=n.message,s||(p>=2&&(m[0]=to(e,"config",D.BACKUP,!0)),d())})(to(e,"config",D.BACKUP),i,{get timeout(){return yo(2+t.count[1])*1e3}})]).then(n=>{s=n,r(s)}).catch(o)})}var WI=i=>i.startsWith("data:application/octet-stream;base64,"),GI=i=>i.startsWith("file://"),Gd=class{constructor(){u(this,"_log");this._log=$.createLogger({id:"fd"})}download(t,e){return y(this,null,function*(){let{type:r="blob"}=e||{};t=t.replace(/(^|[^:])\/{2,}/g,"$1/");try{let o=_e(),s;if(Xe(fetch)?s=yield this.downloadWithFetch(t,r):s=yield this.downloadWithXHR(t,r),!s||!s.data)throw new Error("data is empty");let n=_e()-o;return this._log.info(`downloaded: ${t}, return type: ${r}, cost: ${n}ms`),Y.addSuccessEvent({key:522700,cost:_e()-o}),s.data}catch(o){throw this._log.error(`failed to download: ${t}, error: ${o}`),Y.addFailedEvent({key:522700,error:o}),o}})}downloadWithFetch(t,e){return y(this,null,function*(){this._log.info(`download with fetch: ${t}, return type: ${e}`);try{let r=yield fetch(t);if(!r.ok)throw new Error("network response was not ok");let o;return e==="arraybuffer"?o=yield r.arrayBuffer():o=yield r.blob(),{data:o}}catch(r){throw r}})}downloadWithXHR(t,e){return this._log.info(`download with xhr: ${t}, return type: ${e}`),new Promise((r,o)=>{let s=new XMLHttpRequest;s.open("GET",t,!0),s.responseType=e,s.onload=()=>{s.status===200||s.status===0&&s.response?r({data:s.response}):o(new Error("XHR failed"))},s.onerror=o,s.send(null)})}loadWasm(t,e){return y(this,null,function*(){this._log.info(`loadWasm ${t}, importObject: ${JSON.stringify(e)}`);let r=_e(),o=null,s=null;if(Xe(WebAssembly.instantiateStreaming)&&!WI(t)&&!GI(t)&&Xe(fetch))try{let n=fetch(t);o=(yield WebAssembly.instantiateStreaming(n,e)).instance}catch(n){s=n}if(!o)try{let n=yield this.download(t,{type:"arraybuffer"});o=(yield WebAssembly.instantiate(n,e)).instance}catch(n){s=n}if(o){let n=_e()-r;return this._log.info(`loadedWasm ${t}, cost: ${n}ms`),Y.addSuccessEvent({key:522701,cost:n}),o}throw this._log.error(`failed to loadWasm ${t}, error: ${s}`),Y.addFailedEvent({key:522701,error:s}),s})}};X([Hi({settings:{timeout:0,retries:3},onRetrying(t){this._log.warn(`download retrying: ${t}`)}})],Gd.prototype,"download",1);var Kf=new Gd;function eg({TRTC:i,room:t,errorModule:e,assetsPath:r}){return{TRTC:i,room:t,assetsPath:r,fileDownloader:Kf,innerEmitter:H,constants:$u,environment:ws,utils:jm,eventLogger:Be,log:this.room.getLogger(),loggerManager:$,errorModule:e,kvStatManager:Y,rtcDectection:Bi,trtc:this,rx:Um,enums:Sl,schedule:zm,clearStarted:(o,s)=>{let n=o.getAlias(),d=fi.instances.get(this);if(d)if(s){let p=d.get(n+s);if(!p)return;p.started=!1}else d.forEach((p,m)=>{m.startsWith(n)&&(p.started=!1)})},startGetPCM:ga,createAudioNode:ql}}var tg=(i,t)=>{let{emit:e}=i;return i.emit=(...r)=>{try{return e.apply(i,r)}catch(o){let s=dt({key:ct.CATCH_HANDLER_ERROR,data:{name:t,event:r[0]},addDocLink:!1});return $.warn(`${s}
95
95
 
96
- ${o.stack}`),!1}},i};var Xs=new WeakMap;function rg(i){let t=Xs.get(i);t&&(t.forEach(e=>clearTimeout(e)),Xs.delete(i))}function ig(i,t){return Me((e,r)=>function(...o){let s=Xs.get(this);s||(s=new Map,Xs.set(this,s));let n=t(...o),d=s.get(n);if(!d||d<=0){e.apply(this,o);let p=setTimeout(()=>{var m;(m=Xs.get(this))==null||m.delete(n)},i);s.set(n,p)}else{clearTimeout(d);let p=window.setTimeout(()=>{var m;e.apply(this,o),(m=Xs.get(this))==null||m.delete(n)},i);s.set(n,p)}})}var sg="trtc-sdk-v5",ng="5.10.0-wasm.3";function Ut(...i){return Me((t,e)=>function(...r){try{qd.call(this,i,r,e,this._name)}catch(o){return Promise.reject(o)}return t.apply(this,r)})}function Xm(...i){return Me((t,e)=>function(...r){try{qd.call(this,i,r,e,this._name)}catch(o){throw o}return t.apply(this,r)})}function qd(i,t,e,r){if(st(i))for(let o=0;o<i.length;o++)jd.call(this,{rule:i[o],value:t[o],key:i[o].name,fnName:e,className:r});else jd.call(this,{rule:i,value:t[0],key:i.name,fnName:e,className:r})}function jd({rule:i,value:t,key:e,fnName:r,className:o}){function s(p){return{code:ue.INVALID_PARAMETER,extraCode:p,fnName:r,messageParams:{key:e,rule:i,value:t}}}if(V(t)){if(i.required)throw new ae(s(5001));if(V(i.defaultValue)){Xe(i.validate)&&i.validate.call(this,t,e,r,o,this);return}t=i.defaultValue}if(Array.isArray(i.type)){let p=!1;for(let m=0;m<i.type.length;m++)i.type[m]===null&&t===null&&(p=!0),Xe(i.type[m])&&t instanceof i.type[m]&&(p=!0),we(i.type[m])&&ht(t)===i.type[m].toLowerCase()&&(p=!0);if(!p)throw new ae({code:ue.INVALID_PARAMETER,extraCode:5002,fnName:r,messageParams:{key:e,rule:{type:i.type.map(m=>hs(m)?Nn(m):we(m)?m:ht(m))},value:t}})}else if(!V(i.type)&&ht(t)!==i.type)throw new ae(s(5002));if(i.allowEmpty===!1){let p=je(t)&&(t===0||Number.isNaN(t)),m=we(t)&&t.trim()==="";if(p||m)throw new ae(s(5003))}if(i.notLessThanZero&&je(t)&&t<0)throw new ae(s(5006));if(!V(i.min)&&je(t)&&t<i.min)throw new ae(s(5007));if(!V(i.max)&&je(t)&&t>i.max)throw new ae(s(5008));if(we(i.instanceOf)){if(!t||t._name!==i.instanceOf)throw new ae(s(5004))}else if(Xe(i.instanceOf)&&!(t instanceof i.instanceOf))throw new ae(s(5004));if(Array.isArray(i.values)&&!i.values.includes(t))throw new ae(s(5005));let{properties:n}=i;Gt(n)&&Pr(t)&&Object.keys(n).forEach(p=>{jd.call(this,{rule:n[p],value:t&&t[p],key:`${p}`,fnName:r,className:o})});let{arrayItem:d}=i;Gt(d)&&st(t)&&t.forEach((p,m)=>{jd.call(this,{rule:d,value:p,key:`${e}[${m}]`,fnName:r,className:o})}),Xe(i.validate)&&i.validate.call(this,t,e,r,o,this)}function Ye(i={}){let{getRemoteId:t=()=>"",replaceArg:e,getKVReportKey:r,ignoreLog:o}=i;return Me((s,n)=>function(...d){var _;function p(b,N,k){if(k&&k.includes(b))return"hided";if(e){let P=e(...d);if(d[P.argIndex]===N)return P.value}if(N===d||b in d)return N;try{return N instanceof HTMLElement?`id: ${N.id} type:${ht(N)}`:(JSON.stringify(N),N)}catch(P){return`type:${ht(N)}`}}let m=this._log||$;if(o!=null&&o(...d))return s.apply(this,d);d.length>0?m.info(`${n}() ${JSON.stringify(d,(b,N)=>p(b,N,["userSig","privateMapKey"]))}`):m.info(`${n}()`);let g=r?r(...d):zc[n];try{let b=s.apply(this,d),N=_e();return xi(b)?b.then(k=>(m.info(`${n}() success ${t.call(this,...d)}`),Y.addSuccessEvent({key:g,cost:_e()-N}),k)).catch(k=>{var J;k=ae.convertFrom.call(this,k,n,d.length===1?d[0]:d);let P=k.extraCode||k.code,x=(J=k.message)!=null&&J.includes(P)?"":` code:${P}`;throw m.error(`${n}() failed ${t.call(this,...d)} ${k}${x} params: ${JSON.stringify(d,p)}`),Y.addFailedEvent({key:g,error:k}),k}):(Y.addSuccessEvent({key:g}),b)}catch(b){b=ae.convertFrom.call(this,b,n);let N=b.extraCode||b.code,k=(_=b.message)!=null&&_.includes(N)?"":` code:${N}`;throw m.error(`${n}() failed ${b}${k} params: ${JSON.stringify(d,p)}`),Y.addFailedEvent({key:g,error:b}),b}})}var Jd=i=>Me((t,e)=>function(r,o){return y(this,null,function*(){let s=this._plugins.get(r);if(!s)throw this._log.error(`plugin ${String(r)} is not found`),new ae({code:ue.OPERATION_ABORT,message:`plugin ${String(r)} is not found`,fnName:e});if(Xe(s.constructor.isSupported)&&!s.constructor.isSupported())throw this._log.error(`plugin ${String(r)} is not supported`),new ae({code:ue.ENV_NOT_SUPPORTED,message:`plugin ${String(r)} is not supported`,extraCode:5210,fnName:e});return qd.call(this,s.getValidateRule(i),[o],e,"TRTC"),t.call(this,s,o)})});var zd=0,Qm=class{constructor(t,e){u(this,"player");u(this,"publisher");u(this,"mixInput");this.mixInput=new Fs(e),t.url?(this.player=new Audio(t.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(t.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(t.track),this.mixInput.connect()}updateSettings(t){this.player&&(V(t.volume)||(this.volume=t.volume),V(t.loop)||(this.loop=t.loop),V(t.playbackRate)||(this.playbackRate=t.playbackRate))}updateListener(t){if(this.player){if(t.onDurationChange){let{onDurationChange:e}=t;this.player.ondurationchange=r=>{e(r.target.duration)}}if(t.onTimeUpdate){let e=t.onTimeUpdate,{player:r}=this;r.ontimeupdate=()=>{e(r.currentTime,r.duration)}}t.onEnded&&(this.player.onended=t.onEnded)}}reset(){this.seek(0),this.mixInput.connect()}seek(t){this.player&&(t<0&&t>this.player.duration||(this.player.currentTime=t,this.publisher.currentTime=t))}play(){var t,e;return(t=this.publisher)==null||t.play(),(e=this.player)==null?void 0:e.play()}pause(){var t,e;(t=this.player)==null||t.pause(),(e=this.publisher)==null||e.pause()}stop(){var t;(t=this.player)==null||t.pause(),this.mixInput.disconnect()}setOperation(t){t==="pause"&&this.pause(),t==="resume"&&(this.pause(),this.play()),t==="stop"&&(this.pause(),this.seek(0))}set volume(t){!this.player||!this.publisher||(this.player.volume=t,this.publisher.volume=t)}set loop(t){!this.player||!this.publisher||(this.player.loop=t,this.publisher.loop=t)}set playbackRate(t){!this.player||!this.publisher||(this.player.playbackRate=t,this.publisher.playbackRate=t)}};function Qs(i,t){if(t&&typeof t!="function")throw new ae({code:ue.INVALID_PARAMETER,message:`start audioMixer plugin: param ${i} should be a function.`})}var Hr=class Hr{constructor(t){this.core=t;u(this,"log");u(this,"mixedMusicMap",new Map);u(this,"cacheMusicMap",new Map);zd=zd+1,this.log=t.log.createChild({id:`${this.getAlias()}${zd}`}),this.log.info(`[audioMixer] created id=${this.getAlias()}${zd}`),this.core=t}getName(){return Hr.Name}getAlias(){return"ax"}getGroup(t){return t==null?void 0:t.id}getValidateRule(t){switch(t){case"start":return Hr.startValidateRule;case"update":return Hr.updateValidateRule;case"stop":return Hr.stopValidateRule}}start(t){return y(this,null,function*(){let{room:e}=this.core;this.log.info(`add music source, id: ${t.id} url: ${t.url}, track: ${t.track}`);let{id:r,url:o}=t;if(this.mixedMusicMap.has(r))return;let s=this.cacheMusicMap.get(r);s?t.url?s.reset():(s.mixInput.replaceSource(t.track),s.mixInput.connect()):(s=new Qm(t,e.audioManager),this.cacheMusicMap.set(r,s)),s.updateListener(t),s.updateSettings(t),yield s.play(),this.mixedMusicMap.set(r,s),this.log.info(`start mix audio track ${r} success.`),Y.addEnum({key:502700,value:3}),this.kvUpload(t)})}update(t){return y(this,null,function*(){let{id:e,operation:r,seekFrom:o,playbackRate:s}=t;this.log.info(`update music source, ${JSON.stringify(t)}`);let n=this.mixedMusicMap.get(e);if(!n){this.log.warn(`update music source failed, music id: ${e} not found.`);return}n.updateSettings(t),n.updateListener(t),V(r)||n.setOperation(r),V(o)||n.seek(o),this.kvUpload(t)})}stop(e){return y(this,arguments,function*({id:t}){var r;this.mixedMusicMap.has(t)&&(this.log.info(`remove music source, music id: ${t}`),(r=this.mixedMusicMap.get(t))==null||r.stop(),this.mixedMusicMap.delete(t)),t==="*"&&this.destroyAllMusic()})}kvUpload(t){let{track:e,loop:r,volume:o,playbackRate:s,operation:n,seekFrom:d,onTimeUpdate:p,onDurationChange:m,onEnded:g}=t;e&&Y.addCount({key:502711}),r&&Y.addCount({key:502703}),o&&Y.addCount({key:502704}),s&&Y.addCount({key:502705}),n&&Y.addCount({key:502706}),d&&Y.addCount({key:502707}),typeof p!="function"&&Y.addCount({key:502709}),typeof g!="function"&&Y.addCount({key:502710}),typeof m!="function"&&Y.addCount({key:502708})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((t,e)=>this.stop({id:e}))}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}};u(Hr,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(t,e,r){if(t.url&&t.url!=="*"){let o=t.url.split("?")[0],s=["mp3","ogg","wav","flac"],n=o.split(".").pop(),d=s.indexOf(n)>=0,p=o.startsWith("blob"),m=o.startsWith("data");if(!(d||p||m))throw new ae({code:ue.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:r})}if(!t.url&&!t.track)throw new ae({code:ue.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:r});Qs("onTimeUpdate",t.onTimeUpdate),Qs("onEnded",t.onEnded),Qs("onDurationChange",t.onDurationChange)}}),u(Hr,"updateValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},loop:{type:"boolean"},volume:{type:"number"},seekFrom:{type:"number"},operation:{type:"string",values:["pause","resume","stop"]}},validate(t,e,r){Qs("onTimeUpdate",t.onTimeUpdate),Qs("onEnded",t.onEnded),Qs("onDurationChange",t.onDurationChange)}}),u(Hr,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),u(Hr,"Name","AudioMixer");var Xd=Hr;var Qd=0,Ym,gi=class gi{constructor(t){this.core=t;u(this,"log");u(this,"audioContext",et("denoiser"));u(this,"workletNode");Qd=Qd+1,this.log=t.log.createChild({id:`${this.getAlias()}${Qd}`}),this.log.info(`[audioDenoiser] created id=${this.getAlias()}${Qd}`),t.assetsPath&&this.preload(`${t.assetsPath}/denoiser-wasm.js`).catch(e=>{})}static startValidateRule(t){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,r,o,s){if(!t.room.audioManager.hasAudioTrack)throw new ae({code:ue.INVALID_OPERATION,extraCode:5106,fnName:o})}}}preload(t){return Ym||(Ym=this.doPreload(t)),Ym}doPreload(t){return y(this,null,function*(){let e=yield this.core.fileDownloader.download(t,{type:"blob"}),r=URL.createObjectURL(e);try{yield Po(this.audioContext,r)}catch(o){throw this.log.error("load worklet failed",o),o}finally{URL.revokeObjectURL(r)}})}getName(){return gi.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(t){switch(t){case"start":return gi.startValidateRule(this.core);case"update":return gi.updateValidateRule;case"stop":return gi.stopValidateRule}}start(t){return y(this,null,function*(){let{room:e,schedule:r}=this.core;if(yield this.preload(`${t.assetsPath}/denoiser-wasm.js`),!this.workletNode){let o=String(Date.now()).slice(0,-3),{auth:s,sign:n,status:d,message:p}=yield jI(r,Ee(ee({},t),{timestamp:o}));if(!s)throw this.log.info(`RTCAIDenoiser: ${t.userId} auth result: ${s}. Message: ${p}`),new ae({code:ue.INVALID_PARAMETER,message:p});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(t.sdkAppId),userId:t.userId,timestamp:o,sign:n,status:d}}),this.workletNode.port.onmessage=m=>{var _;let{data:g}=m;if(g.type==="cost"){let b=(g==null?void 0:g.max)>20?"warn":(g==null?void 0:g.max)>10?"info":"debug";this.log[b](`avg cost: ${g.value} max: ${g==null?void 0:g.max}(${sc(new Date(g==null?void 0:g.maxCostTimestamp))}) hist: ${(_=g==null?void 0:g.hist)==null?void 0:_.join(" ")}`)}else g.type==="log"&&this.log[g.logLevel](`${g.value}`)}}this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(){return y(this,null,function*(){})}stop(){return y(this,null,function*(){if(!this.workletNode)return;let{room:t}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield t.audioManager.removeDenoiser(this.workletNode)})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};u(gi,"updateValidateRule",{type:"object"}),u(gi,"stopValidateRule",{type:"object"}),u(gi,"Name","AIDenoiser");var Yd=gi;function jI(s,n){return y(this,arguments,function*(i,{sdkAppId:t,userId:e,userSig:r,timestamp:o}){try{let{data:{errCode:d,errMsg:p,sign:m,status:g}}=yield i.getAbilityConfig(t,i.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:t,userId:e,userSig:r,timestamp:o});if(g==="1")return{auth:!0,sign:m,status:g,message:p};let _="Init RTCAIDenoiser failed.",b="";switch(d){case 1:b="Please check your params.";break;case 2:b="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:b="Server is invalid. Please contact our engineer. ";break;case 4:b="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:b="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:b="Your version is not supported.";break}return{auth:!1,status:g,message:p?`${_} Reason: ${p}. ${b}`:`${_}, ${b}`}}catch(d){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${d}`}}})}var ag=Mi($i(),1);var Zm=class extends ag.EventEmitter{constructor(){super();u(this,"observer");u(this,"state","nominal");this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return y(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!at&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){Be.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let r=this.stateNum,o=e[e.length-1];this.state=o.state,(this.stateNum>3||r>3)&&$.info(`${o.source}: ${o.state}`),this.emit("state-changed",{type:o.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(r){Be.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:r})}}},qI=new Zm,Km=qI;function JI([i,t]){let e=t.byteLength,r=parseInt(String(e/255),10),o=e%255,s=[];s.push(0,0,0,1,6,i);for(let d=0;d<r;d++)s.push(255);s.push(o);let n=new DataView(t);return s.push(...new Uint8Array(n.buffer)),s.push(128),new Uo(new DataView(new Uint8Array(s).buffer),!0)}function zI(i){return i.type==="empty"||i.data.byteLength===0}function XI(i){return i.getInt32(0)===1&&i.getInt8(4)===6}function QI(i){let t=0,e=0,r=new DataView(i);for(let o=0;o<i.byteLength;o++)switch(r.getUint8(o)){case 0:t++;break;case 1:(t===2||t===3)&&e++,t=0;break;default:t=0;break}return e}function ep({frame:i,seiMessageList:t}){if(!t||t.length===0||i.data.byteLength===0)return i;let r=9-QI(i.data);if(r<=0)return i;let o=t.splice(0,r).reverse().map(JI),s=o.reduce((g,_)=>g+_.dataView.byteLength,0),n=new ArrayBuffer(s+i.data.byteLength),d=new DataView(n),p=new DataView(i.data),m=0;for(let g=0;g<o.length;g++)for(let _=0;_<o[g].dataView.byteLength;_++)d.setInt8(m++,o[g].dataView.getInt8(_));for(let g=0;g<i.data.byteLength;g++)d.setInt8(m++,p.getInt8(g));return i.data=n,i}function tp({frame:i,onSEI:t}){try{let e=new DataView(i.data);if(zI(i)||!XI(e))return i;let r=[],o=0,s=-1,n=-1;for(let d=0;d<i.data.byteLength;d++){let p=e.getUint8(d);if(p===0)o++;else if(p===1){if(o===2||o===3){let m=d-o;if(s===-1?s=m:n===-1&&(n=m,r.push(new Uo(new DataView(e.buffer.slice(s,n)))),s=m,n=-1),!(e.getUint8(d+1)===6)){i.data=e.buffer.slice(m);break}}o=0}else o=0}t==null||t(r.reverse())}catch(e){}return i}var rp=0,Na=class Na{constructor(t){this.core=t;u(this,"log");u(this,"_seiMessageList",[]);u(this,"_smallSeiMessageList",[]);u(this,"_subStreamSeiMessageList",[]);rp++,this.log=t.log.createChild({id:`${this.getAlias()}${rp}`}),this.log.info(`[sei] created id=${this.getAlias()}${rp}`),this.core=t,this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode({frame:t,mediaType:e}){try{let r=e===8?this._smallSeiMessageList:e===2?this._subStreamSeiMessageList:this._seiMessageList;return ep({frame:t,seiMessageList:r})}catch(r){this.log.warn(r)}return t}decode({frame:t,track:e}){return tp({frame:t,onSEI:r=>{r.forEach(o=>{this.core.trtc.emit(se.SEI_MESSAGE,{seiPayloadType:o.seiPayloadType,data:o.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"})})}})}destroy(){this.log.debug("destory"),this.stop(),delete this.core}getValidateRule(t){switch(t){case"start":return{type:"object"};case"update":return{type:"object"};case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:oa?this.encode:ep,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:oa?this.decode:tp,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update({buffer:t,options:e}){var s;let r=[e.seiPayloadType,t],o=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(r):(this._seiMessageList.push(r),o&&this._smallSeiMessageList.push(r)),(s=this.core.room.scriptTransformWorker)==null||s.postMessage({type:"sei",data:r,isMain:!e.toSubStream,small:o})}getName(){return Na.Name}getAlias(){return"sei"}getGroup(){return"sei"}};u(Na,"autoStart",!0),u(Na,"Name","SEI");var Zd=Na;function ip({frame:i,onDump:t}){return t==null||t(),i}function op({frame:i,onDump:t}){return t==null||t(),i}var cg={"play() error: NotAllowedError:":{tips:i=>i.includes("main <video>")||i.includes("main <audio>")?"Remote stream auto play is restricted and playback fails":"Local stream playback failure, generally only occurs in Android WeChat devices, no need to handle",color:"red",class:"red"},"updateStream() try to recover local stream":{tips:"Device acquisition exception, automatic recovery is in progress"},"updateStream() recover local stream successfully":{tips:"Device acquisition exception, automatic recovery is successful"},"updateStream() failed to recover local stream":{tips:"Device acquisition exception, automatic recovery failed"},"main stream - video track is muted":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is muted":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is muted":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unable to provide media output":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is unable to provide media output":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is unable to provide media output":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unmuted":{tips:"Received enough playback video data"},"main stream - audio track is unmuted":{tips:"Received enough playback audio data"},"auxiliary stream - video track is unmuted":{tips:"Received enough playback screen sharing data"},"main stream - audio player track is ended":{tips:"Remote audio track stopped"},"main stream - video player track is ended":{tips:"Remote video track stopped"},"auxiliary stream - video player track is ended":{tips:"Received enough playback screen sharing data"},"stream - video track is muted":{tips:"Camera capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"stream - video track is unable to provide media output":{tips:"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked, and the customer needs to re-acquire. SDK v4.11.4+ will automatically resume acquisition without customer intervention",color:"orange"},"video track is unable to provide media output":{tips:i=>i.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"stream - audio track is muted":{tips:"Microphone capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"audio track is unable to provide media output":{tips:i=>i.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"Microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio track is unable to provide media output":{tips:"The microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"is adding audio track to current published local stream":{tips:"add audio track",color:"orange"},"is removing audio track from current published local stream":{tips:"remove audio track",color:"orange"},"is removing video track from current published local stream":{tips:"remove video track",color:"orange"},"is adding video track to current published local stream":{tips:"add video track",color:"orange"},"is replacing audio track to current published local main stream":{tips:"replace audio track",color:"orange"},"is replacing video track to current published local main stream":{tips:"replace video track",color:"orange"},"downlink network quality change":{tips:"Downstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"uplink network quality change":{tips:"Upstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"localStream mute video":{tips:"mute upstream video stream",color:"orange"},"localStream unmute video":{tips:"unmute upstream video stream",color:"orange"},"localStream mute audio":{tips:"mute upstream audio stream",color:"orange"},"localStream unmute audio":{tips:"unmute upstream audio stream",color:"orange"},"black detected":{tips:"Detect black screen, which means fps = 0. It is usually caused by network, and the network will be recovered after a while. If the network is normal but has not been restored, it is an abnormal situation."},'main stream start to play with options: {"muted":true}':{tips:"Play the remote stream in silent mode. Generally, the remote stream does not need to be played in silent mode. You need to confirm whether the parameters passed in the client stream.play API call are correct.",color:"orange"},"main stream - audio player is starting playing":{tips:"Remote stream audio playback success",color:"#0dd90d",class:"success"},"main stream - video player is starting playing":{tips:"Remote stream video playback success",color:"#0dd90d",class:"success"},"video player is playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"audio player is playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"stream - video player is starting playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"stream - audio player is starting playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"switch camera success":{tips:"Switch camera success",color:"#0dd90d",class:"success"},"switch microphone success":{tips:"Switch microphone success",color:"#0dd90d",class:"success"},gotStream:{tips:"Local stream capture success"},"local stream is published successfully":{tips:"Publish success",color:"#0dd90d",class:"success"},"encoderImplementation change to OpenH264":{tips:"Use software encoding"},"encoderImplementation change to ExternalEncoder":{tips:"Use hardware encoding"},"getUserMedia with constraints":{tips:"Start media (camera/microphone) capture"},"getDisplayMedia with constraints":{tips:"Start screen sharing capture"},"client-banned":{tips:"Kicked out of the room",color:"red",class:"red",textColor:"#fff"},user_timeout:{tips:"The backend is too long without receiving SDK heartbeat, which is usually caused by the JS thread being blocked for a long time. If the reproduction probability is high, the application browser Performance tool analyzes where the JS thread is blocked.",color:"red",class:"red",textColor:"#fff"},"schedule failed":{tips:"Signaling request failed, does not affect the normal room entry process, SDK will connect to the default signaling domain."},"updateStream() video flag is true, but no camera detected, set video to false":{tips:"When trying to resume camera acquisition, the camera acquisition is not resumed because it is detected that there is no camera.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to bandwidth":{tips:"bandwidth estimation is not enough to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to cpu":{tips:"cpu load is too high to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: hidden":{tips:"User page switched to backend, in mobile devices, this will cause the device to pause the capture, and it will be restored when the user switches backend to the frontend.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: visible":{tips:"User page switched to frontend",color:"orange",class:"orange",textColor:"#fff"},"main stream - audio player is paused":{tips:`The remote stream audio playback is paused, which usually has two possibilities:
96
+ ${o.stack}`),!1}},i};var Xs=new WeakMap;function rg(i){let t=Xs.get(i);t&&(t.forEach(e=>clearTimeout(e)),Xs.delete(i))}function ig(i,t){return Me((e,r)=>function(...o){let s=Xs.get(this);s||(s=new Map,Xs.set(this,s));let n=t(...o),d=s.get(n);if(!d||d<=0){e.apply(this,o);let p=setTimeout(()=>{var m;(m=Xs.get(this))==null||m.delete(n)},i);s.set(n,p)}else{clearTimeout(d);let p=window.setTimeout(()=>{var m;e.apply(this,o),(m=Xs.get(this))==null||m.delete(n)},i);s.set(n,p)}})}var sg="trtc-sdk-v5",ng="5.10.0-wasm.4";function Ut(...i){return Me((t,e)=>function(...r){try{qd.call(this,i,r,e,this._name)}catch(o){return Promise.reject(o)}return t.apply(this,r)})}function Xm(...i){return Me((t,e)=>function(...r){try{qd.call(this,i,r,e,this._name)}catch(o){throw o}return t.apply(this,r)})}function qd(i,t,e,r){if(st(i))for(let o=0;o<i.length;o++)jd.call(this,{rule:i[o],value:t[o],key:i[o].name,fnName:e,className:r});else jd.call(this,{rule:i,value:t[0],key:i.name,fnName:e,className:r})}function jd({rule:i,value:t,key:e,fnName:r,className:o}){function s(p){return{code:ue.INVALID_PARAMETER,extraCode:p,fnName:r,messageParams:{key:e,rule:i,value:t}}}if(V(t)){if(i.required)throw new ae(s(5001));if(V(i.defaultValue)){Xe(i.validate)&&i.validate.call(this,t,e,r,o,this);return}t=i.defaultValue}if(Array.isArray(i.type)){let p=!1;for(let m=0;m<i.type.length;m++)i.type[m]===null&&t===null&&(p=!0),Xe(i.type[m])&&t instanceof i.type[m]&&(p=!0),we(i.type[m])&&ht(t)===i.type[m].toLowerCase()&&(p=!0);if(!p)throw new ae({code:ue.INVALID_PARAMETER,extraCode:5002,fnName:r,messageParams:{key:e,rule:{type:i.type.map(m=>hs(m)?Nn(m):we(m)?m:ht(m))},value:t}})}else if(!V(i.type)&&ht(t)!==i.type)throw new ae(s(5002));if(i.allowEmpty===!1){let p=je(t)&&(t===0||Number.isNaN(t)),m=we(t)&&t.trim()==="";if(p||m)throw new ae(s(5003))}if(i.notLessThanZero&&je(t)&&t<0)throw new ae(s(5006));if(!V(i.min)&&je(t)&&t<i.min)throw new ae(s(5007));if(!V(i.max)&&je(t)&&t>i.max)throw new ae(s(5008));if(we(i.instanceOf)){if(!t||t._name!==i.instanceOf)throw new ae(s(5004))}else if(Xe(i.instanceOf)&&!(t instanceof i.instanceOf))throw new ae(s(5004));if(Array.isArray(i.values)&&!i.values.includes(t))throw new ae(s(5005));let{properties:n}=i;Gt(n)&&Pr(t)&&Object.keys(n).forEach(p=>{jd.call(this,{rule:n[p],value:t&&t[p],key:`${p}`,fnName:r,className:o})});let{arrayItem:d}=i;Gt(d)&&st(t)&&t.forEach((p,m)=>{jd.call(this,{rule:d,value:p,key:`${e}[${m}]`,fnName:r,className:o})}),Xe(i.validate)&&i.validate.call(this,t,e,r,o,this)}function Ye(i={}){let{getRemoteId:t=()=>"",replaceArg:e,getKVReportKey:r,ignoreLog:o}=i;return Me((s,n)=>function(...d){var _;function p(b,N,k){if(k&&k.includes(b))return"hided";if(e){let P=e(...d);if(d[P.argIndex]===N)return P.value}if(N===d||b in d)return N;try{return N instanceof HTMLElement?`id: ${N.id} type:${ht(N)}`:(JSON.stringify(N),N)}catch(P){return`type:${ht(N)}`}}let m=this._log||$;if(o!=null&&o(...d))return s.apply(this,d);d.length>0?m.info(`${n}() ${JSON.stringify(d,(b,N)=>p(b,N,["userSig","privateMapKey"]))}`):m.info(`${n}()`);let g=r?r(...d):zc[n];try{let b=s.apply(this,d),N=_e();return xi(b)?b.then(k=>(m.info(`${n}() success ${t.call(this,...d)}`),Y.addSuccessEvent({key:g,cost:_e()-N}),k)).catch(k=>{var J;k=ae.convertFrom.call(this,k,n,d.length===1?d[0]:d);let P=k.extraCode||k.code,x=(J=k.message)!=null&&J.includes(P)?"":` code:${P}`;throw m.error(`${n}() failed ${t.call(this,...d)} ${k}${x} params: ${JSON.stringify(d,p)}`),Y.addFailedEvent({key:g,error:k}),k}):(Y.addSuccessEvent({key:g}),b)}catch(b){b=ae.convertFrom.call(this,b,n);let N=b.extraCode||b.code,k=(_=b.message)!=null&&_.includes(N)?"":` code:${N}`;throw m.error(`${n}() failed ${b}${k} params: ${JSON.stringify(d,p)}`),Y.addFailedEvent({key:g,error:b}),b}})}var Jd=i=>Me((t,e)=>function(r,o){return y(this,null,function*(){let s=this._plugins.get(r);if(!s)throw this._log.error(`plugin ${String(r)} is not found`),new ae({code:ue.OPERATION_ABORT,message:`plugin ${String(r)} is not found`,fnName:e});if(Xe(s.constructor.isSupported)&&!s.constructor.isSupported())throw this._log.error(`plugin ${String(r)} is not supported`),new ae({code:ue.ENV_NOT_SUPPORTED,message:`plugin ${String(r)} is not supported`,extraCode:5210,fnName:e});return qd.call(this,s.getValidateRule(i),[o],e,"TRTC"),t.call(this,s,o)})});var zd=0,Qm=class{constructor(t,e){u(this,"player");u(this,"publisher");u(this,"mixInput");this.mixInput=new Fs(e),t.url?(this.player=new Audio(t.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(t.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(t.track),this.mixInput.connect()}updateSettings(t){this.player&&(V(t.volume)||(this.volume=t.volume),V(t.loop)||(this.loop=t.loop),V(t.playbackRate)||(this.playbackRate=t.playbackRate))}updateListener(t){if(this.player){if(t.onDurationChange){let{onDurationChange:e}=t;this.player.ondurationchange=r=>{e(r.target.duration)}}if(t.onTimeUpdate){let e=t.onTimeUpdate,{player:r}=this;r.ontimeupdate=()=>{e(r.currentTime,r.duration)}}t.onEnded&&(this.player.onended=t.onEnded)}}reset(){this.seek(0),this.mixInput.connect()}seek(t){this.player&&(t<0&&t>this.player.duration||(this.player.currentTime=t,this.publisher.currentTime=t))}play(){var t,e;return(t=this.publisher)==null||t.play(),(e=this.player)==null?void 0:e.play()}pause(){var t,e;(t=this.player)==null||t.pause(),(e=this.publisher)==null||e.pause()}stop(){var t;(t=this.player)==null||t.pause(),this.mixInput.disconnect()}setOperation(t){t==="pause"&&this.pause(),t==="resume"&&(this.pause(),this.play()),t==="stop"&&(this.pause(),this.seek(0))}set volume(t){!this.player||!this.publisher||(this.player.volume=t,this.publisher.volume=t)}set loop(t){!this.player||!this.publisher||(this.player.loop=t,this.publisher.loop=t)}set playbackRate(t){!this.player||!this.publisher||(this.player.playbackRate=t,this.publisher.playbackRate=t)}};function Qs(i,t){if(t&&typeof t!="function")throw new ae({code:ue.INVALID_PARAMETER,message:`start audioMixer plugin: param ${i} should be a function.`})}var Hr=class Hr{constructor(t){this.core=t;u(this,"log");u(this,"mixedMusicMap",new Map);u(this,"cacheMusicMap",new Map);zd=zd+1,this.log=t.log.createChild({id:`${this.getAlias()}${zd}`}),this.log.info(`[audioMixer] created id=${this.getAlias()}${zd}`),this.core=t}getName(){return Hr.Name}getAlias(){return"ax"}getGroup(t){return t==null?void 0:t.id}getValidateRule(t){switch(t){case"start":return Hr.startValidateRule;case"update":return Hr.updateValidateRule;case"stop":return Hr.stopValidateRule}}start(t){return y(this,null,function*(){let{room:e}=this.core;this.log.info(`add music source, id: ${t.id} url: ${t.url}, track: ${t.track}`);let{id:r,url:o}=t;if(this.mixedMusicMap.has(r))return;let s=this.cacheMusicMap.get(r);s?t.url?s.reset():(s.mixInput.replaceSource(t.track),s.mixInput.connect()):(s=new Qm(t,e.audioManager),this.cacheMusicMap.set(r,s)),s.updateListener(t),s.updateSettings(t),yield s.play(),this.mixedMusicMap.set(r,s),this.log.info(`start mix audio track ${r} success.`),Y.addEnum({key:502700,value:3}),this.kvUpload(t)})}update(t){return y(this,null,function*(){let{id:e,operation:r,seekFrom:o,playbackRate:s}=t;this.log.info(`update music source, ${JSON.stringify(t)}`);let n=this.mixedMusicMap.get(e);if(!n){this.log.warn(`update music source failed, music id: ${e} not found.`);return}n.updateSettings(t),n.updateListener(t),V(r)||n.setOperation(r),V(o)||n.seek(o),this.kvUpload(t)})}stop(e){return y(this,arguments,function*({id:t}){var r;this.mixedMusicMap.has(t)&&(this.log.info(`remove music source, music id: ${t}`),(r=this.mixedMusicMap.get(t))==null||r.stop(),this.mixedMusicMap.delete(t)),t==="*"&&this.destroyAllMusic()})}kvUpload(t){let{track:e,loop:r,volume:o,playbackRate:s,operation:n,seekFrom:d,onTimeUpdate:p,onDurationChange:m,onEnded:g}=t;e&&Y.addCount({key:502711}),r&&Y.addCount({key:502703}),o&&Y.addCount({key:502704}),s&&Y.addCount({key:502705}),n&&Y.addCount({key:502706}),d&&Y.addCount({key:502707}),typeof p!="function"&&Y.addCount({key:502709}),typeof g!="function"&&Y.addCount({key:502710}),typeof m!="function"&&Y.addCount({key:502708})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((t,e)=>this.stop({id:e}))}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}};u(Hr,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(t,e,r){if(t.url&&t.url!=="*"){let o=t.url.split("?")[0],s=["mp3","ogg","wav","flac"],n=o.split(".").pop(),d=s.indexOf(n)>=0,p=o.startsWith("blob"),m=o.startsWith("data");if(!(d||p||m))throw new ae({code:ue.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:r})}if(!t.url&&!t.track)throw new ae({code:ue.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:r});Qs("onTimeUpdate",t.onTimeUpdate),Qs("onEnded",t.onEnded),Qs("onDurationChange",t.onDurationChange)}}),u(Hr,"updateValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},loop:{type:"boolean"},volume:{type:"number"},seekFrom:{type:"number"},operation:{type:"string",values:["pause","resume","stop"]}},validate(t,e,r){Qs("onTimeUpdate",t.onTimeUpdate),Qs("onEnded",t.onEnded),Qs("onDurationChange",t.onDurationChange)}}),u(Hr,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),u(Hr,"Name","AudioMixer");var Xd=Hr;var Qd=0,Ym,gi=class gi{constructor(t){this.core=t;u(this,"log");u(this,"audioContext",et("denoiser"));u(this,"workletNode");Qd=Qd+1,this.log=t.log.createChild({id:`${this.getAlias()}${Qd}`}),this.log.info(`[audioDenoiser] created id=${this.getAlias()}${Qd}`),t.assetsPath&&this.preload(`${t.assetsPath}/denoiser-wasm.js`).catch(e=>{})}static startValidateRule(t){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,r,o,s){if(!t.room.audioManager.hasAudioTrack)throw new ae({code:ue.INVALID_OPERATION,extraCode:5106,fnName:o})}}}preload(t){return Ym||(Ym=this.doPreload(t)),Ym}doPreload(t){return y(this,null,function*(){let e=yield this.core.fileDownloader.download(t,{type:"blob"}),r=URL.createObjectURL(e);try{yield Po(this.audioContext,r)}catch(o){throw this.log.error("load worklet failed",o),o}finally{URL.revokeObjectURL(r)}})}getName(){return gi.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(t){switch(t){case"start":return gi.startValidateRule(this.core);case"update":return gi.updateValidateRule;case"stop":return gi.stopValidateRule}}start(t){return y(this,null,function*(){let{room:e,schedule:r}=this.core;if(yield this.preload(`${t.assetsPath}/denoiser-wasm.js`),!this.workletNode){let o=String(Date.now()).slice(0,-3),{auth:s,sign:n,status:d,message:p}=yield jI(r,Ee(ee({},t),{timestamp:o}));if(!s)throw this.log.info(`RTCAIDenoiser: ${t.userId} auth result: ${s}. Message: ${p}`),new ae({code:ue.INVALID_PARAMETER,message:p});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(t.sdkAppId),userId:t.userId,timestamp:o,sign:n,status:d}}),this.workletNode.port.onmessage=m=>{var _;let{data:g}=m;if(g.type==="cost"){let b=(g==null?void 0:g.max)>20?"warn":(g==null?void 0:g.max)>10?"info":"debug";this.log[b](`avg cost: ${g.value} max: ${g==null?void 0:g.max}(${sc(new Date(g==null?void 0:g.maxCostTimestamp))}) hist: ${(_=g==null?void 0:g.hist)==null?void 0:_.join(" ")}`)}else g.type==="log"&&this.log[g.logLevel](`${g.value}`)}}this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(){return y(this,null,function*(){})}stop(){return y(this,null,function*(){if(!this.workletNode)return;let{room:t}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield t.audioManager.removeDenoiser(this.workletNode)})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};u(gi,"updateValidateRule",{type:"object"}),u(gi,"stopValidateRule",{type:"object"}),u(gi,"Name","AIDenoiser");var Yd=gi;function jI(s,n){return y(this,arguments,function*(i,{sdkAppId:t,userId:e,userSig:r,timestamp:o}){try{let{data:{errCode:d,errMsg:p,sign:m,status:g}}=yield i.getAbilityConfig(t,i.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:t,userId:e,userSig:r,timestamp:o});if(g==="1")return{auth:!0,sign:m,status:g,message:p};let _="Init RTCAIDenoiser failed.",b="";switch(d){case 1:b="Please check your params.";break;case 2:b="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:b="Server is invalid. Please contact our engineer. ";break;case 4:b="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:b="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:b="Your version is not supported.";break}return{auth:!1,status:g,message:p?`${_} Reason: ${p}. ${b}`:`${_}, ${b}`}}catch(d){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${d}`}}})}var ag=Mi($i(),1);var Zm=class extends ag.EventEmitter{constructor(){super();u(this,"observer");u(this,"state","nominal");this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return y(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!at&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){Be.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let r=this.stateNum,o=e[e.length-1];this.state=o.state,(this.stateNum>3||r>3)&&$.info(`${o.source}: ${o.state}`),this.emit("state-changed",{type:o.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(r){Be.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:r})}}},qI=new Zm,Km=qI;function JI([i,t]){let e=t.byteLength,r=parseInt(String(e/255),10),o=e%255,s=[];s.push(0,0,0,1,6,i);for(let d=0;d<r;d++)s.push(255);s.push(o);let n=new DataView(t);return s.push(...new Uint8Array(n.buffer)),s.push(128),new Uo(new DataView(new Uint8Array(s).buffer),!0)}function zI(i){return i.type==="empty"||i.data.byteLength===0}function XI(i){return i.getInt32(0)===1&&i.getInt8(4)===6}function QI(i){let t=0,e=0,r=new DataView(i);for(let o=0;o<i.byteLength;o++)switch(r.getUint8(o)){case 0:t++;break;case 1:(t===2||t===3)&&e++,t=0;break;default:t=0;break}return e}function ep({frame:i,seiMessageList:t}){if(!t||t.length===0||i.data.byteLength===0)return i;let r=9-QI(i.data);if(r<=0)return i;let o=t.splice(0,r).reverse().map(JI),s=o.reduce((g,_)=>g+_.dataView.byteLength,0),n=new ArrayBuffer(s+i.data.byteLength),d=new DataView(n),p=new DataView(i.data),m=0;for(let g=0;g<o.length;g++)for(let _=0;_<o[g].dataView.byteLength;_++)d.setInt8(m++,o[g].dataView.getInt8(_));for(let g=0;g<i.data.byteLength;g++)d.setInt8(m++,p.getInt8(g));return i.data=n,i}function tp({frame:i,onSEI:t}){try{let e=new DataView(i.data);if(zI(i)||!XI(e))return i;let r=[],o=0,s=-1,n=-1;for(let d=0;d<i.data.byteLength;d++){let p=e.getUint8(d);if(p===0)o++;else if(p===1){if(o===2||o===3){let m=d-o;if(s===-1?s=m:n===-1&&(n=m,r.push(new Uo(new DataView(e.buffer.slice(s,n)))),s=m,n=-1),!(e.getUint8(d+1)===6)){i.data=e.buffer.slice(m);break}}o=0}else o=0}t==null||t(r.reverse())}catch(e){}return i}var rp=0,Na=class Na{constructor(t){this.core=t;u(this,"log");u(this,"_seiMessageList",[]);u(this,"_smallSeiMessageList",[]);u(this,"_subStreamSeiMessageList",[]);rp++,this.log=t.log.createChild({id:`${this.getAlias()}${rp}`}),this.log.info(`[sei] created id=${this.getAlias()}${rp}`),this.core=t,this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode({frame:t,mediaType:e}){try{let r=e===8?this._smallSeiMessageList:e===2?this._subStreamSeiMessageList:this._seiMessageList;return ep({frame:t,seiMessageList:r})}catch(r){this.log.warn(r)}return t}decode({frame:t,track:e}){return tp({frame:t,onSEI:r=>{r.forEach(o=>{this.core.trtc.emit(se.SEI_MESSAGE,{seiPayloadType:o.seiPayloadType,data:o.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"})})}})}destroy(){this.log.debug("destory"),this.stop(),delete this.core}getValidateRule(t){switch(t){case"start":return{type:"object"};case"update":return{type:"object"};case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:oa?this.encode:ep,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:oa?this.decode:tp,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update({buffer:t,options:e}){var s;let r=[e.seiPayloadType,t],o=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(r):(this._seiMessageList.push(r),o&&this._smallSeiMessageList.push(r)),(s=this.core.room.scriptTransformWorker)==null||s.postMessage({type:"sei",data:r,isMain:!e.toSubStream,small:o})}getName(){return Na.Name}getAlias(){return"sei"}getGroup(){return"sei"}};u(Na,"autoStart",!0),u(Na,"Name","SEI");var Zd=Na;function ip({frame:i,onDump:t}){return t==null||t(),i}function op({frame:i,onDump:t}){return t==null||t(),i}var cg={"play() error: NotAllowedError:":{tips:i=>i.includes("main <video>")||i.includes("main <audio>")?"Remote stream auto play is restricted and playback fails":"Local stream playback failure, generally only occurs in Android WeChat devices, no need to handle",color:"red",class:"red"},"updateStream() try to recover local stream":{tips:"Device acquisition exception, automatic recovery is in progress"},"updateStream() recover local stream successfully":{tips:"Device acquisition exception, automatic recovery is successful"},"updateStream() failed to recover local stream":{tips:"Device acquisition exception, automatic recovery failed"},"main stream - video track is muted":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is muted":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is muted":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unable to provide media output":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is unable to provide media output":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is unable to provide media output":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unmuted":{tips:"Received enough playback video data"},"main stream - audio track is unmuted":{tips:"Received enough playback audio data"},"auxiliary stream - video track is unmuted":{tips:"Received enough playback screen sharing data"},"main stream - audio player track is ended":{tips:"Remote audio track stopped"},"main stream - video player track is ended":{tips:"Remote video track stopped"},"auxiliary stream - video player track is ended":{tips:"Received enough playback screen sharing data"},"stream - video track is muted":{tips:"Camera capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"stream - video track is unable to provide media output":{tips:"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked, and the customer needs to re-acquire. SDK v4.11.4+ will automatically resume acquisition without customer intervention",color:"orange"},"video track is unable to provide media output":{tips:i=>i.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"stream - audio track is muted":{tips:"Microphone capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"audio track is unable to provide media output":{tips:i=>i.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"Microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio track is unable to provide media output":{tips:"The microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"is adding audio track to current published local stream":{tips:"add audio track",color:"orange"},"is removing audio track from current published local stream":{tips:"remove audio track",color:"orange"},"is removing video track from current published local stream":{tips:"remove video track",color:"orange"},"is adding video track to current published local stream":{tips:"add video track",color:"orange"},"is replacing audio track to current published local main stream":{tips:"replace audio track",color:"orange"},"is replacing video track to current published local main stream":{tips:"replace video track",color:"orange"},"downlink network quality change":{tips:"Downstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"uplink network quality change":{tips:"Upstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"localStream mute video":{tips:"mute upstream video stream",color:"orange"},"localStream unmute video":{tips:"unmute upstream video stream",color:"orange"},"localStream mute audio":{tips:"mute upstream audio stream",color:"orange"},"localStream unmute audio":{tips:"unmute upstream audio stream",color:"orange"},"black detected":{tips:"Detect black screen, which means fps = 0. It is usually caused by network, and the network will be recovered after a while. If the network is normal but has not been restored, it is an abnormal situation."},'main stream start to play with options: {"muted":true}':{tips:"Play the remote stream in silent mode. Generally, the remote stream does not need to be played in silent mode. You need to confirm whether the parameters passed in the client stream.play API call are correct.",color:"orange"},"main stream - audio player is starting playing":{tips:"Remote stream audio playback success",color:"#0dd90d",class:"success"},"main stream - video player is starting playing":{tips:"Remote stream video playback success",color:"#0dd90d",class:"success"},"video player is playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"audio player is playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"stream - video player is starting playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"stream - audio player is starting playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"switch camera success":{tips:"Switch camera success",color:"#0dd90d",class:"success"},"switch microphone success":{tips:"Switch microphone success",color:"#0dd90d",class:"success"},gotStream:{tips:"Local stream capture success"},"local stream is published successfully":{tips:"Publish success",color:"#0dd90d",class:"success"},"encoderImplementation change to OpenH264":{tips:"Use software encoding"},"encoderImplementation change to ExternalEncoder":{tips:"Use hardware encoding"},"getUserMedia with constraints":{tips:"Start media (camera/microphone) capture"},"getDisplayMedia with constraints":{tips:"Start screen sharing capture"},"client-banned":{tips:"Kicked out of the room",color:"red",class:"red",textColor:"#fff"},user_timeout:{tips:"The backend is too long without receiving SDK heartbeat, which is usually caused by the JS thread being blocked for a long time. If the reproduction probability is high, the application browser Performance tool analyzes where the JS thread is blocked.",color:"red",class:"red",textColor:"#fff"},"schedule failed":{tips:"Signaling request failed, does not affect the normal room entry process, SDK will connect to the default signaling domain."},"updateStream() video flag is true, but no camera detected, set video to false":{tips:"When trying to resume camera acquisition, the camera acquisition is not resumed because it is detected that there is no camera.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to bandwidth":{tips:"bandwidth estimation is not enough to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to cpu":{tips:"cpu load is too high to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: hidden":{tips:"User page switched to backend, in mobile devices, this will cause the device to pause the capture, and it will be restored when the user switches backend to the frontend.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: visible":{tips:"User page switched to frontend",color:"orange",class:"orange",textColor:"#fff"},"main stream - audio player is paused":{tips:`The remote stream audio playback is paused, which usually has two possibilities:
97
97
  1. The business side passes in the div tag container for playing audio and video to be removed by the business side from the DOM.
98
98
  2. If the user is in Chrome 70 and below, when the div container is moved, the playback will be paused.`,color:"orange",class:"orange",textColor:"#fff"},"main stream - video player is paused":{tips:`The remote stream video playback is paused, which usually has two possibilities:
99
99
  1. The business side passes in the div tag container for playing audio and video to be removed by the business side from the DOM.
100
- 2. If the user is in Chrome 70 and below, when the div container is moved, the playback will be paused.`,color:"orange",class:"orange",textColor:"#fff"},'"displaySurface":"window"':{tips:"Screen sharing captures the application window",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"monitor"':{tips:"Screen sharing captures the entire screen",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"browser"':{tips:"Screen sharing captures a certain tab page",color:"blue",class:"blue",textColor:"#fff"},updateMediaSettings:{tips:"The resolution and frame rate below are the actual resolution and frame rate captured",color:"blue",class:"blue",textColor:"#fff"},"main stream start to play with":{tips:"Call remoteStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"stream start to play with":{tips:"Call localStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"main setAudioVolume to 0":{tips:"Business side calls remoteStream.setAudioVolume(0) interface to set the playback volume to 0, which will cause the playback to be silent",color:"orange",class:"orange",textColor:"#fff"},"screen sharing was stopped because the video track is ended":{tips:"Screen sharing capture stopped, possible reasons: user clicks the stop button, the window/page shared by the user is closed, etc.",color:"orange",class:"orange",textColor:"#fff"},"Join() => joining room":{tips:"Call client.join interface",color:"blue",class:"blue",textColor:"#fff"},"publish() => publishing local stream":{tips:"Call client.publish interface",color:"blue",class:"blue",textColor:"#fff"},"subscribe() => subscribe to":{tips:"Call client.subscribe interface",color:"blue",class:"blue",textColor:"#fff"},"switchRole() => switch role":{tips:"Call client.switchRole interface",color:"blue",class:"blue",textColor:"#fff"}};["enterRoom","exitRoom","switchRole","destroy","startLocalAudio","updateLocalAudio","stopLocalAudio","startLocalVideo","updateLocalVideo","stopLocalVideo","startScreenShare","updateScreenShare","stopScreenShare","startRemoteVideo","updateRemoteVideo","stopRemoteVideo","muteRemoteAudio","setRemoteAudioVolume"].forEach(i=>{cg[`${i}()`]={tips:`Call trtc.${i}`,color:"blue",class:"blue",textColor:"#fff"}});var oP=Object.keys(cg);var YI=0,Kd,Ys=class Ys{constructor(t){this.core=t;u(this,"_core");u(this,"log");u(this,"dumpLocalVideoMap",{});u(this,"dumpRemoteVideoMap",{});u(this,"dialog");this._core=t,this.log=t.log.createChild({id:`${this.getAlias()}${++YI}`}),this.log.info("created")}getName(){return Ys.Name}getAlias(){return"dm"}getGroup(){return"dm"}getValidateRule(t){switch(t){case"start":return{name:"StartDebugOptions",required:!1};case"update":return{name:"UpdateDebugOptions",required:!1};case"stop":return{name:"StopDebugOptions",required:!1}}}start(){return y(this,null,function*(){var e;!new URLSearchParams(location.search).has("trtcDebug")&&((e=window.sessionStorage)==null?void 0:e.getItem("TRTC_ENABLE_DEBUG_PLUGIN"))!=="true"||(yield this.openDebugDiaLog(),this.addVideoProcessor())})}update(){}stop(){this.closeDebugDiaLog(),this.removeVideoProcessor()}destroy(){this.stop()}openDebugDiaLog(){return y(this,null,function*(){var t;try{if(Kd)yield Kd;else{let e=Date.now(),r=new URLSearchParams(location.search).get("trtcDebugDialogPath")||((t=window.sessionStorage)==null?void 0:t.getItem("TRTC_DEBUG_DIALOG_PATH"))||`https://unpkg.com/${sg}@${rt}/assets/debug-dialog.js`;Kd=this.loadScript(r),yield Kd,this.log.info(`download debug dialog script cost: ${Date.now()-e}ms`)}this.dialog=new TRTCDebugDialog(this._core,this.log,this.dumpLocalVideoMap,this.dumpRemoteVideoMap),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(e){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(e))}})}closeDebugDiaLog(){var t;(t=this.dialog)==null||t.closeDialog(),this.dialog=null}addVideoProcessor(){this._core.room.videoManager.addEncodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.encodeVideo.bind(this):ip,type:1}),this._core.room.videoManager.addDecodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.decodeVideo.bind(this):op,type:1})}removeVideoProcessor(){this._core.room.videoManager.removeEncodeProcessor({type:1}),this._core.room.videoManager.removeDecodeProcessor({type:1})}encodeVideo({frame:t,mediaType:e}){return ip({frame:t,onDump:()=>{if(!e)return;let r=e===2?"sub":"main",o=this.dumpLocalVideoMap[r];o&&(o.data.push(t.data),o.duration>0&&Date.now()-o.startTimestamp>o.duration*1e3&&o.onDumpEnd())}})}decodeVideo({frame:t,track:e}){return op({frame:t,onDump:()=>{if(!e)return;let r=this.dumpRemoteVideoMap[`${e.userId}-${e.streamType}`];r&&(r.data.push(t.data),r.duration>0&&Date.now()-r.startTimestamp>r.duration*1e3&&r.onDumpEnd())}})}loadScript(t){return new Promise((e,r)=>{this.log.info(`loading debug dialog from ${t}`);let o=document.createElement("script");o.type="text/javascript",o.onload=e,o.onerror=r,o.crossOrigin="anonymous",o.src=t,document.head.append?document.head.append(o):document.getElementsByTagName("head")[0].appendChild(o)})}};u(Ys,"Name","Debug"),u(Ys,"autoStart",!0),X([Hi({settings:{timeout:3e3,retries:3},onError(t,e,r){var o;(o=t==null?void 0:t.message)!=null&&o.includes("timeout")?e():r(t)}})],Ys.prototype,"loadScript",1);var eu=Ys;var dg=i=>{switch(i){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},tu=class{constructor(t,e,r){u(this,"trackDoneOB");u(this,"startOB");u(this,"stopOB");u(this,"inputFrameCount",0);u(this,"decodedFrameCount",0);u(this,"type","auto");u(this,"config");u(this,"decoder");u(this,"_decodeSink");let{kvStatManager:o,trtc:s}=t;this.config=r.config,this.trackDoneOB=be(e,ne.INIT),this.stopOB=It(this.trackDoneOB),this.startOB=It(),r.type==="auto"?this.type="webCodecs":this.type=r.type;let n=It(),d=p=>{let m=this.pipe(e);return n.next("STARTING"),e.log.info(`decoder type: ${this.type}`),Se(m,Je(this.stopOB),ke(()=>{},g=>{e.log.error(g),o.addFailedEvent({key:dg(this.type),error:g}),p>4?this.startOB.error(g):this.startOB.next(p+1)})),Se(m,Ar(1),xm(Ia))};Se(this.startOB,_a(0),zi(d),Je(this.stopOB),ke(()=>{e.player.setOutput(),n.next("STARTED")},p=>{n.next("FAILED")},()=>{o.addSuccessEvent({key:dg(this.type)}),o.addSuccessEvent({key:504702})}))}mock(t){this._decodeSink?this._decodeSink.error(t):this.startOB.next(0)}close(t){this.stopOB.next(t)}pipe(t){return li()(e=>y(this,null,function*(){this._decodeSink=e,e.defer(()=>{var o;(o=this.decoder)==null||o.close()});let{type:r}=this;try{switch(r){case"webCodecs":this.decoder=new AudioDecoder({error:o=>{t.log.error(o),e.error(4)},output:o=>{this.decodedFrameCount++,e.next(o),t.player.write(o)}});break;case"wasm":break}this.decoder.configure(this.config)}catch(o){t.log.error(o),e.error(r==="webCodecs"?2:6)}}))}decodeFrame(t){var e;this.inputFrameCount++,((e=this.decoder)==null?void 0:e.state)==="configured"&&this.decoder.decode(new EncodedAudioChunk({data:t.data,timestamp:t.timestamp,type:"key"}))}},ZI={type:"object"},wa=class wa{constructor(t){this.core=t;u(this,"log");u(this,"contextMap",new Map);u(this,"decodeProcessorMap",new WeakMap);this.log=t.log.createChild({id:`${this.getAlias()}`})}getAlias(){return wa.Name}getGroup(t){return t.track.userId+t.track.streamType}getName(){return wa.Name}getValidateRule(t){return ZI}start(t){let{track:e}=t;this.decodeProcessorMap.set(e,this.decode(t)),this.core.room.audioManager.addDecodeProcessor({processor:({frame:r,track:o})=>this.decodeProcessorMap.has(o)?this.decodeProcessorMap.get(o)({frame:r,track:o}):r,type:3})}decode(t){return({frame:e,track:r})=>{if(r!==t.track)return e;if(this.contextMap.has(r))return this.contextMap.get(r).decodeFrame(e);let o=new tu(this.core,r,t);return Se(o.trackDoneOB,Ar(1),ke(()=>{this.core.clearStarted(this,this.getGroup(t)),this.stop({track:r})})),this.contextMap.set(r,o),o.decodeFrame(e)}}stop({track:t}){let e=this.contextMap.get(t);e&&(e.close("stop"),this.contextMap.delete(t),this.contextMap.size===0&&this.core.room.audioManager.removeDecodeProcessor({type:3}))}update(t){let e=this.contextMap.get(t.track);if(e){if(t.type==="mock"){e.mock(10);return}e.close("update"),this.contextMap.set(t.track,new tu(this.core,t.track,t))}}};u(wa,"Name","TRTCAudioDecoder");var Ma=wa;var ug=0,Oa=new Set,Rt=null;Ou(ng);Ms.checkStorage();xl();var KI={RtcError:ae,ErrorCode:ue,ErrorCodeDictionary:Rr},fe=class fe extends lg.EventEmitter{constructor(e,r){super();u(this,"_room");u(this,"_eventListened",new Set);u(this,"_localVideoTrack",null);u(this,"_localAudioTrack",null);u(this,"_localScreenTrack",null);u(this,"_localScreenAudioTrack",null);u(this,"_localVideoConfig",null);u(this,"_localScreenConfig",null);u(this,"_localAudioConfig",null);u(this,"_remoteVideoConfigMap",new Map);u(this,"_remoteAudioConfigMap",new Map);u(this,"_remoteAudioVolumeMap",new Map);u(this,"_remoteAudioMuteMap",new Map);u(this,"_mediaTrackMap",new WeakMap);u(this,"_log",$.createLogger({id:`t${++ug}`}));u(this,"_plugins",new Map);u(this,"_networkQuality",null);u(this,"_speakerId");u(this,"_getPCMAbortCtrl");this._room=new e(ee({logger:this._log,frameWorkType:fe.frameWorkType},r)),this._room.videoDecodeFallbackType=r.videoDecodeFallback,this._log.info(`create() ${JSON.stringify(r,(o,s)=>o==="plugins"?s.map(n=>n.Name):s)}`),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(o){return this._room.audioManager.dump(o)}}}),r.plugins&&r.plugins.forEach(o=>{this._use(o,r.assetsPath)}),this._use(Xd,r.assetsPath),this._use(Yd,r.assetsPath),this._use(Ma,r.assetsPath||nc),this._use(eu),r.enableSEI&&sa&&this._use(Zd),this._room.on("audio-volume",o=>{!o.find(s=>s.userId==="")&&this._localAudioTrack&&o.push({userId:"",volume:Math.floor(this._localAudioTrack.getAudioLevel()*100)}),r.volumeType===1&&o.forEach(s=>{var d;let n=s.userId===""?this._localAudioTrack:(d=this.room.remotePublishedUserMap.get(s.userId))==null?void 0:d.remoteAudioTrack;n&&(s.volume=n.dbVolume)}),this.emit(se.AUDIO_VOLUME,{result:o.sort((s,n)=>n.volume-s.volume)})}),this._room.videoManager.on("error",o=>{this._log.error(new ae({code:ue.OPERATION_FAILED,extraCode:5504,message:o.message,originError:o}))}),this._listenEvents(),this._initActiveSpeaker(),tg(this,"trtc")}static create(e){}static _create(e,r){Bf();let o=new fe(e,r||{});return Oa.add(o),o}get room(){return this._room}_listenEvents(){xt(this,this._room).add("peer-join",e=>{let{userId:r}=e;this.emit(se.REMOTE_USER_ENTER,{userId:r})}).add("peer-leave",e=>{this.emit(se.REMOTE_USER_EXIT,{userId:e}),this._remoteAudioVolumeMap.delete(e)}).add("banned",e=>{this._exitRoom().finally(()=>{this.emit(se.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().finally(()=>{this.emit(se.ERROR,ae.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(se.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let r=Ee(ee({},e),{uplinkRTT:Math.min(e.uplinkRTT,bn),downlinkRTT:Math.min(e.downlinkRTT,bn)});this.emit(se.NETWORK_QUALITY,r)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(o=>{xt(o,o).add("player-state-changed",s=>{let n=Ee(ee({},s),{userId:e.userId});o.kind===D.VIDEO&&(n.streamType=eo(o.streamType)),this.emit(o.kind===D.AUDIO?se.AUDIO_PLAY_STATE_CHANGED:se.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",s=>{s.getCode()===te.PLAY_NOT_ALLOWED&&this.emit(se.AUTOPLAY_FAILED,{userId:o.userId,resume:()=>o.player.resume()})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(o=>{mt(o)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:r})=>{let{userId:o}=r,s=e.audioAvailable,n=e.videoAvailable,{audioAvailable:d,videoAvailable:p}=r;d||this._remoteAudioConfigMap.delete(o),p||this._remoteVideoConfigMap.delete(`${o}_main`),r.hasAuxiliary||this._remoteVideoConfigMap.delete(`${o}_sub`),n!==p&&(p?this._onVideoAvailable({userId:o,streamType:"main"}):this._onVideoUnavailable({userId:o,streamType:"main"}),this.emit(p?se.REMOTE_VIDEO_AVAILABLE:se.REMOTE_VIDEO_UNAVAILABLE,{userId:o,streamType:"main"})),s!==d&&(d?this._onAudioAvailable({userId:o}):this._onAudioUnavailable({userId:o,muteState:r}),this.emit(d?se.REMOTE_AUDIO_AVAILABLE:se.REMOTE_AUDIO_UNAVAILABLE,{userId:o})),e.hasAuxiliary!==r.hasAuxiliary&&(r.hasAuxiliary?this._onVideoAvailable({userId:o,streamType:"sub"}):this._onVideoUnavailable({userId:o,streamType:"sub"}),this.emit(r.hasAuxiliary?se.REMOTE_VIDEO_AVAILABLE:se.REMOTE_VIDEO_UNAVAILABLE,{userId:o,streamType:"sub"}))}).add("sei-message",e=>{this.emit(se.SEI_MESSAGE,Ee(ee({},e),{streamType:eo(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(se.ERROR,new ae({code:ue.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var s,n,d,p,m,g,_;let r={2:"big",3:"small",7:"sub"},o={rtt:Math.min(e.msg_up_stream_info.msg_network_status.uint32_rtt||((s=e.msg_down_stream_info[0])==null?void 0:s.msg_network_status.uint32_rtt)||((n=this._networkQuality)==null?void 0:n.uplinkRTT)||((d=this._networkQuality)==null?void 0:d.downlinkRTT)||0,bn),upLoss:((p=this._networkQuality)==null?void 0:p.uplinkLoss)||0,downLoss:((m=this._networkQuality)==null?void 0:m.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((g=e.msg_up_stream_info.msg_audio_status)==null?void 0:g.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((_=e.msg_up_stream_info.msg_audio_status)==null?void 0:_.uint32_audio_level)||0)/oi},video:e.msg_up_stream_info.msg_video_status.filter(b=>r[b.uint32_video_stream_type]).map(b=>({bitrate:(b.uint32_video_codec_bitrate||0)/1e3,width:b.uint32_video_width,height:b.uint32_video_height,frameRate:b.uint32_video_enc_fps,videoType:r[b.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(b=>({userId:b.msg_user_info.str_identifier,audio:{bitrate:(b.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(b.msg_audio_status.uint32_audio_level||0)/oi},video:b.msg_video_status.map(N=>({bitrate:(N.uint32_video_codec_bitrate||0)/1e3,width:N.uint32_video_width,height:N.uint32_video_height,frameRate:N.uint32_video_dec_fps,videoType:r[N.uint32_video_stream_type]}))}))};this.emit(se.STATISTICS,o)}).add("custom-message",e=>{this.emit(se.CUSTOM_MESSAGE,e)}).add("layerData",e=>this.emit(se.LAYER_DATA,e)).add("first-video-frame",e=>{this.emit(se.FIRST_VIDEO_FRAME,Ee(ee({},e),{streamType:eo(e.streamType)}))}),xt(this,Tt).add("audioInputAdded",e=>{this.emit(se.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(se.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(se.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(se.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>y(this,null,function*(){if(this.emit(se.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Rt&&Rt.deviceId===An){let r=(yield Wi()).find(o=>o.deviceId===An);r&&Rt.groupId!==r.groupId&&(Rt=r,this.emit(se.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}))}})).add("audioOutputRemoved",e=>y(this,null,function*(){this.emit(se.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let r=(yield Wi())[0];if(!r||!Rt||Rt.groupId===r.groupId)return;let o=Rt.deviceId===e.deviceId,s=Rt.deviceId===An&&Rt.deviceId===r.deviceId;(o||s)&&(Rt=r,this.emit(se.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}))}))}use(e){let r,o;"plugin"in e?(r=e.plugin,o=e.assetsPath):r=e,this._use(r,o||nc)}_use(e,r){if(this._plugins.get(e.Name)){this._log.warn("duplicate install plugin",e.Name);return}let s=new e(eg.call(this,{TRTC:fe,room:this._room,errorModule:KI,assetsPath:r}));this._plugins.set(e.Name,s),e.autoStart&&this.startPlugin(e.Name)}enterRoom(e){return y(this,null,function*(){var p,m;let{scene:r="rtc",enableAutoPlayDialog:o=!0,autoReceiveAudio:s=!0,autoReceiveVideo:n=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!we(e.proxy)&&e.proxy.turnServer&&((m=(p=this._room).setTurnServer)==null||m.call(p,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=o,this._room.autoReceiveAudio=s,this._room.autoReceiveVideo=n,nt(e.preferHW)&&(this._room.preferHW=e.preferHW),e.playoutDelay&&(this._room.playoutDelay=e.playoutDelay),e.jitterBufferDelay&&(this._room.jitterBufferDelay=e.jitterBufferDelay);let d={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:e.role==="audience"?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language,priority:e.priority,useVp8:e.useVp8,keepAlive:e.keepAlive};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(d,r,fe.frameWorkType),this._checkTrackToPublish(),Km.start()})}exitRoom(){return y(this,null,function*(){return yield this._exitRoom()})}switchRole(e,r){return y(this,null,function*(){r!=null&&r.privateMapKey&&(this._room.privateMapKey=r.privateMapKey),r!=null&&r.latencyLevel&&(this._room.latencyLevel=r.latencyLevel),yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){mt(this),this.removeAllListeners(),this._room.destroy(),Oa.delete(this),Oa.size===0&&Km.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),this._plugins.forEach(e=>{var r;return(r=e.destroy)==null?void 0:r.call(e)}),this._plugins.clear(),H.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return y(this,arguments,function*(e={publish:!0}){if(this._localAudioTrack){this._log.warn("local audio is already started");return}let{publish:r=!0,mute:o,option:s}=e,n=new ui(this._room.audioManager),d={},p={muted:!0};s&&(V(s.microphoneId)?V(s.audioTrack)||(d.customSource=s.audioTrack):d.deviceId=s.microphoneId,s&&je(s.captureVolume)&&n.setCaptureVolume(s.captureVolume),V(s.profile)||(we(s.profile)?cc[s.profile]&&n.setProfile(cc[s.profile]):n.setProfile(s.profile)),je(s.earMonitorVolume)&&(p.muted=!(s.earMonitorVolume>0),p.volume=s.earMonitorVolume),V(s.echoCancellation)||(n.profile.echoCancellation=s.echoCancellation),V(s.noiseSuppression)||(n.profile.noiseSuppression=s.noiseSuppression),V(s.autoGainControl)||(n.profile.autoGainControl=s.autoGainControl)),n.on("5",m=>{this.emit(se.ERROR,new ae({code:ue.DEVICE_ERROR,extraCode:5309,messageParams:{error:m}}))}),n.on("2",m=>{this.emit(se.DEVICE_CHANGED,{type:"microphone",action:"active",device:m})}),n.on("4",m=>{let g;m.error&&(g=ae.convertFrom(m.error)),this.emit(se.PUBLISH_STATE_CHANGED,Ee(ee({},m),{error:g}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId),yield n.capture(d),V(o)||n.setMute(o),xt(n,n).add("player-state-changed",m=>{this.emit(se.AUDIO_PLAY_STATE_CHANGED,Ee(ee({},m),{userId:""}))}),this.listeners(se.AUDIO_FRAME).length>0&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM(m=>{this.emit(fe.EVENT.AUDIO_FRAME,{data:m})})),this._getPCMAbortCtrl&&n.on("input-media-track-changed",()=>{this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("inputMediaTrackChanged"),this._getPCMAbortCtrl=this._room.audioManager.getPCM(m=>{this.emit(fe.EVENT.AUDIO_FRAME,{data:m})}))}),r&&this._room.isJoined&&this._room.publish(n).catch(()=>{}),this._localAudioTrack=n,this._localAudioConfig=Ee(ee({},e),{publish:r}),yield this._updateAudioPlayOption({playOption:p,track:n})})}updateLocalAudio(e){return y(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:r,mute:o,option:s}=e,n={};s&&(s.microphoneId?yield this._localAudioTrack.switchDevice(s.microphoneId):V(s.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(s.audioTrack)),V(s.captureVolume)||this._localAudioTrack.setCaptureVolume(s.captureVolume),V(s.earMonitorVolume)||(n.muted=!(s.earMonitorVolume>0),n.volume=s.earMonitorVolume),yield this._localAudioTrack.update3A(s)),this._room.isJoined&&!V(r)&&(r&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!r&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),V(o)||this._localAudioTrack.setMute(o),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),kr(this._localAudioConfig,e)})}stopLocalAudio(){return y(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),mt(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null,this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("stopLocalAudio"),delete this._getPCMAbortCtrl))})}startLocalVideo(){return y(this,arguments,function*(e={publish:!0,view:null}){if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:r,publish:o=!0,mute:s,option:n}=e,d=new Sr(this._room.videoManager),p={},m={};nt(n==null?void 0:n.avoidCrop)&&(d.avoidCrop=n.avoidCrop),n&&(n.cameraId?p.deviceId=n.cameraId:V(n.useFrontCamera)?V(n.videoTrack)||(p.customSource=n.videoTrack):p.facingMode=n.useFrontCamera?D.FACING_MODE_USER:D.FACING_MODE_ENVIRONMENT,n.qosPreference&&(p.contentHint=Da(n.qosPreference)),V(n.profile)||(we(n.profile)?Or[n.profile]&&d.setProfile(Or[n.profile]):d.setProfile(n.profile)),V(n.fillMode)||(m.objectFit=n.fillMode),V(n.mirror)||(m.mirror=n.mirror),V(n.small)||(ra()?we(n.small)?d.small=Or[n.small]:n.small===!0?d.small=Or["120p"]:d.small=n.small:this._log.warn("small stream is not supported"))),d.once("first-video-frame",g=>{this.emit(se.FIRST_VIDEO_FRAME,Ee(ee({},g),{streamType:eo(g.streamType)}))}),d.on("5",g=>{this.emit(se.ERROR,new ae({code:ue.DEVICE_ERROR,extraCode:5308,messageParams:{error:g}}))}),d.on("2",g=>{this.emit(se.DEVICE_CHANGED,{type:"camera",action:"active",device:g})}),d.on("4",g=>{let _;g.error&&(_=ae.convertFrom(g.error)),this.emit(se.PUBLISH_STATE_CHANGED,Ee(ee({},g),{error:_}))}),this._listenOutputTrackChanged(d),yield d.capture(p),V(s)||(yield d.setMute(s)),xt(d,d).add("player-state-changed",g=>{this.emit(se.VIDEO_PLAY_STATE_CHANGED,Ee(ee({},g),{userId:"",streamType:"main"}))}),o&&this._room.isJoined&&this._room.publish(d).catch(()=>{}),this._localVideoTrack=d,this._localVideoConfig=Ee(ee({},e),{view:r,publish:o}),yield this._updateVideoPlayOption({view:r,playOption:m,track:d})})}updateLocalVideo(e){return y(this,null,function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:r,publish:o,mute:s,option:n}=e,d={};if(n)if(V(n.profile)||(we(n.profile)?Or[n.profile]&&this._localVideoTrack.setProfile(Or[n.profile]):this._localVideoTrack.setProfile(n.profile),(!n.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(n.cameraId))&&V(n.useFrontCamera)&&this._localVideoTrack.applyProfile()),n.cameraId?yield this._localVideoTrack.switchDevice(n.cameraId):V(n.useFrontCamera)?V(n.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(n.videoTrack)):yield this._localVideoTrack.switchDevice(n.useFrontCamera?D.FACING_MODE_USER:D.FACING_MODE_ENVIRONMENT),V(n.fillMode)||(d.objectFit=n.fillMode),V(n.mirror)||(d.mirror=n.mirror),n.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(Da(n.qosPreference)),n.small){let p=!this._localVideoTrack.small;ra()?(n.small===!0?this._localVideoTrack.small=Or["120p"]:we(n.small)?this._localVideoTrack.small=Or[n.small]:this._localVideoTrack.small=n.small,this._room.videoManager.update(),p&&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&&!V(o)&&(o&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._localVideoConfig.publish&&!o&&this._room.unpublish(this._localVideoTrack).catch(()=>{})),V(s)||(yield this._localVideoTrack.setMute(s)),yield this._updateVideoPlayOption({view:r,playOption:d,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),kr(this._localVideoConfig,e)})}stopLocalVideo(){return y(this,null,function*(){this._localVideoTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),mt(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return y(this,arguments,function*(e={publish:!0,view:null}){if(this._localScreenTrack){this._log.warn("screen share is already started");return}let{view:r=null,publish:o=!0,option:s}=e,n=new ji(this._room.videoManager);n.on("4",_=>{let b;_.error&&(b=ae.convertFrom(_.error)),this.emit(se.PUBLISH_STATE_CHANGED,Ee(ee({},_),{error:b}))}),n.once("first-video-frame",_=>{this.emit(se.FIRST_VIDEO_FRAME,Ee(ee({},_),{streamType:eo(_.streamType)}))}),this._listenOutputTrackChanged(n),e.streamType==="main"&&(n.mediaType=4);let d=null,p={},m={};s&&(V(s.profile)||(we(s.profile)?dc[s.profile]&&n.setProfile(dc[s.profile]):n.setProfile(s.profile)),s.systemAudio&&(p.systemAudio=!0,p.echoCancellation=s.echoCancellation,p.noiseSuppression=s.noiseSuppression,p.autoGainControl=s.autoGainControl),V(s.fillMode)||(m.objectFit=s.fillMode),s.videoTrack&&(p.videoTrack=s.videoTrack),s.audioTrack&&(p.audioTrack=s.audioTrack),s.captureElement&&(p.captureElement=s.captureElement),s.preferDisplaySurface&&(p.preferDisplaySurface=s.preferDisplaySurface),s.qosPreference&&(p.contentHint=Da(s.qosPreference)));let g=yield n.capture(p);if(n.mediaTrack.addEventListener(D.ENDED,()=>{this._stopScreenShare(),this.emit(se.SCREEN_SHARE_STOPPED)}),g.getAudioTracks()[0]&&(d=new Fo(this._room.audioManager),yield d.setInputMediaStreamTrack(g.getAudioTracks()[0]),this._speakerId&&d.setAudioOutput(this._speakerId)),xt(n,n).add("player-state-changed",_=>{this.emit(se.VIDEO_PLAY_STATE_CHANGED,Ee(ee({},_),{userId:"",streamType:"sub"}))}),o&&this._room.isJoined){let _=[n];d&&_.push(d),this._room.publish(..._).catch(()=>{})}this._localScreenTrack=n,this._localScreenAudioTrack=d,this._localScreenConfig=Ee(ee({},e),{view:r,publish:o}),yield this._updateVideoPlayOption({view:r,playOption:m,track:n})})}updateScreenShare(e){return y(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:r,publish:o,option:s}=e,n={};if(s&&(V(s.fillMode)||(n.objectFit=s.fillMode),s.qosPreference)){let d=Da(s.qosPreference);this._localScreenTrack.setContentHint(d)}this._room.isJoined&&!V(o)&&(o&&!this._localScreenConfig.publish&&(this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch(()=>{})),this._localScreenConfig.publish&&!o&&(this._room.unpublish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.unpublish(this._localScreenAudioTrack).catch(()=>{}))),yield this._updateVideoPlayOption({view:r,playOption:n,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),kr(this._localScreenConfig,e)})}stopScreenShare(){return y(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return y(this,null,function*(){let{view:r,userId:o,streamType:s,option:n}=e,d=`${o}_${s}`;if(this._remoteVideoConfigMap.has(d)){this._log.warn(`remote video has already started. userId:${o}, streamType:${s}`);return}let p=this._room.remotePublishedUserMap.get(o);if(!p)return;let m={},g=s==="main"?p.remoteVideoTrack:p.remoteAuxiliaryTrack;this._listenOutputTrackChanged(g),n&&(V(n.fillMode)||(m.objectFit=n.fillMode),V(n.mirror)||(m.mirror=n.mirror),V(n.poster)||(m.poster=n.poster),m.canvasRender=n.canvasRender,s==="main"&&!V(n.small)&&(!p.remoteVideoTrack.isSubscribing&&!p.remoteVideoTrack.isSubscribed&&p.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,g.user))),yield this._room.subscribe(g),yield this._enableVideoDecodeFallback(g,s),yield this._updateVideoPlayOption({view:r,playOption:m,track:g}),this._emitTrackEvent(g),this._remoteVideoConfigMap.set(d,{config:e}),n&&!V(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:g,view:r,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:n==null?void 0:n.viewRoot})})}updateRemoteVideo(e){return y(this,null,function*(){var x,J;let{view:r,userId:o,streamType:s,option:n}=e,d=`${o}_${s}`,p=this._remoteVideoConfigMap.get(d);if(!p||!this._room.remotePublishedUserMap.has(o))return;let m={};n&&(V(n.fillMode)||(m.objectFit=n.fillMode),V(n.mirror)||(m.mirror=n.mirror));let g=null,_=this._room.remotePublishedUserMap.get(o);if(s==="main"&&(_!=null&&_.muteState.hasVideo)&&(g=_.remoteVideoTrack),s==="sub"&&(_!=null&&_.muteState.hasAuxiliary)&&(g=_.remoteAuxiliaryTrack),!g)return;let{config:b}=p;s==="main"&&n&&!V(n.small)&&this._room.changeType(n.small,g.user),yield this._updateVideoPlayOption({view:r,playOption:m,track:g,prevConfig:b}),kr(b,e);let N=V(n==null?void 0:n.receiveWhenViewVisible)?(x=b.option)==null?void 0:x.receiveWhenViewVisible:n.receiveWhenViewVisible,k=V(r)?b.view:r,P=V(n==null?void 0:n.viewRoot)?(J=b.option)==null?void 0:J.viewRoot:n.viewRoot;this._observeView({remoteTrack:g,view:k,receiveWhenViewVisible:N,viewRoot:P})})}stopRemoteVideo(e){return y(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,r=!0){return y(this,null,function*(){let o=[],s=this._room.remotePublishedUserMap.get(e.userId);if(s){let{muteState:d,remoteVideoTrack:p,remoteAuxiliaryTrack:m}=s;e.streamType==="main"&&(p.stop(),d.hasVideo&&o.push(p)),e.streamType==="sub"&&(m.stop(),d.hasAuxiliary&&o.push(m))}for(let d of o)r&&(yield this._room.unsubscribe(d),this._mediaTrackMap.delete(d.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,r){return y(this,null,function*(){this._remoteAudioMuteMap.set(e,r);try{if(e==="*")if(r)yield this._stopRemoteAudio({userId:e});else{let o=[...this._room.remotePublishedUserMap.values()];for(let s of o)s.muteState.hasAudio&&!this._remoteAudioConfigMap.has(s.userId)&&(yield this._startRemoteAudio({userId:s.userId}))}else r?yield this._stopRemoteAudio({userId:e}):this._remoteAudioConfigMap.has(e)||(yield this._startRemoteAudio({userId:e}))}catch(o){throw this._remoteAudioMuteMap.delete(e),o}})}setRemoteAudioVolume(e,r){if(e==="*"){let o=[...this._room.remotePublishedUserMap.values()];for(let s of o)this._remoteAudioVolumeMap.set(s.userId,r),s.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:r},track:s.remoteAudioTrack})}else if(e){let o=this._room.remotePublishedUserMap.get(e);this._remoteAudioVolumeMap.set(e,r),o&&o.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:r},track:o.remoteAudioTrack})}}startPlugin(e,r){return y(this,null,function*(){return e.start(r)})}updatePlugin(e,r){return y(this,null,function*(){return e.update(r)})}stopPlugin(e,r){return y(this,null,function*(){return e.stop(r)})}enableAudioVolumeEvaluation(e=2e3,r=!1){this._room.enableAudioVolumeEvaluation(e,r)}on(e,r,o){return this.listeners(e).includes(r)?this:(this._log.debug("on",e),super.on(e,r,o),this._eventListened.add(e),e===fe.EVENT.AUDIO_FRAME&&!this._getPCMAbortCtrl&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM(s=>{this.emit(fe.EVENT.AUDIO_FRAME,{data:s})}),this._localAudioTrack&&this._localAudioTrack.on("input-media-track-changed",()=>{this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("inputMediaTrackChanged"),this._getPCMAbortCtrl=this._room.audioManager.getPCM(s=>{this.emit(fe.EVENT.AUDIO_FRAME,{data:s})}))})),this)}emit(e,...r){try{Xf.has(e)&&this._log.debug(`emit ${e} ${JSON.stringify(r)}`)}catch(o){}return super.emit(e,...r)}off(e,r,o){var s,n;return this._log.debug("off",e),e==="*"?(this._eventListened.clear(),this.removeAllListeners(),(s=this._getPCMAbortCtrl)==null||s.abort("off"),delete this._getPCMAbortCtrl):(super.off(e,r,o),e===fe.EVENT.AUDIO_FRAME&&((n=this._getPCMAbortCtrl)==null||n.abort("off"),delete this._getPCMAbortCtrl)),this}getAudioTrack(e={userId:"",streamType:"main"}){let r,o=null,s="main",n=!1;if(we(e)?r=e:(r=e.userId,n=e.processed===!0,e.streamType&&(s=e.streamType)),r){let d=this._room.remotePublishedUserMap.get(r);d&&(o=d.remoteAudioTrack)}else o=s==="sub"?this._localScreenAudioTrack:this._localAudioTrack;return o?n&&o.outMediaTrack&&o.outMediaTrack!==o.mediaTrack?o.outMediaTrack.clone():o.mediaTrack:null}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:r="",streamType:o="main",processed:s=!1}=e,n=null;if(r==="")o==="main"&&this._localVideoTrack&&(n=this._localVideoTrack),o==="sub"&&this._localScreenTrack&&(n=this._localScreenTrack);else{let d=this._room.remotePublishedUserMap.get(r);d&&(n=o==="main"?d.remoteVideoTrack:d.remoteAuxiliaryTrack)}return n?s&&n.outMediaTrack&&n.outMediaTrack!==n.mediaTrack?n.outMediaTrack.clone():n.mediaTrack:null}getVideoSnapshot(e={}){let{userId:r,streamType:o="main"}=e;if(r){let s=this._room.remotePublishedUserMap.get(r);if(o==="main"&&(s!=null&&s.muteState.hasVideo))return s.remoteVideoTrack.getVideoFrame();if(o==="sub"&&(s!=null&&s.muteState.hasAuxiliary))return s.remoteAuxiliaryTrack.getVideoFrame()}else{if(o==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(o==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(e){var r,o;this._speakerId=e,(r=this._localAudioTrack)==null||r.setAudioOutput(e),(o=this._localScreenAudioTrack)==null||o.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(s=>s.remoteAudioTrack.setAudioOutput(e))}setCurrentSpeaker(e){return y(this,null,function*(){(yield Wi()).forEach(o=>{o.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(se.DEVICE_CHANGED,{type:"speaker",action:"active",device:o}),Rt=o)}),this._log.warn('the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: https://web.sdk.qcloud.com/trtc/webrtc/v5/doc/en/TRTC.html#.setCurrentSpeaker')})}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return y(this,null,function*(){let{userId:r}=e;if(this._remoteAudioConfigMap.has(r)){this._log.warn(`remote audio has already started. userId:${r}`);return}let o=this._room.remotePublishedUserMap.get(r);if(!o)return;let s={},n=o.remoteAudioTrack;this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId);try{let d=this._remoteAudioVolumeMap.get(r),p=je(d)?d:100;s.volume=p,this._remoteAudioConfigMap.set(r,e),yield this._room.subscribe(n),Se(be(n,"decode-failed"),Je(be(n,ne.INIT)),ke(()=>{this.startPlugin(Ma.Name,{track:n,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:s,track:n})}catch(d){throw this._remoteAudioConfigMap.delete(r),d}this._emitTrackEvent(n)})}_stopRemoteAudio(e,r=!0){return y(this,null,function*(){let o=this._room.remotePublishedUserMap.get(e.userId);o&&(o.remoteAudioTrack.stop(),o.muteState.hasAudio&&r&&(yield this._room.unsubscribe(o.remoteAudioTrack)),this._mediaTrackMap.delete(o.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete(`${e.userId}`)})}_enableVideoDecodeFallback(e,r){let o=this._room.videoDecodeFallbackType;if(!o||!this._plugins.has("TRTCVideoDecoder"))return;e.log.debug("remote video will fall back when decode failed",e.id);let s;Se(be(e,"decode-failed"),Je(be(e,ne.INIT)),Sa(()=>{this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:o})}),mi(be(e,"decode-downgrade-state-changed")),ke(n=>{s=n.state,this.emit(se.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,Ee(ee({},n),{streamType:r,userId:e.userId}))},n=>{e.log.error("fallback",n)},()=>{s==="STARTED"&&e.log.info("fallback complete")}))}_updateVideoPlayOption(n){return y(this,arguments,function*({view:e,playOption:r,track:o,prevConfig:s}){if(o.setMirror(r.mirror),V(e)&&s&&s.view&&!fs(r)){let d=Es(s.view);d.length>0&&(yield o.play(d,r))}if(!V(e)){let d=Es(e);d.length>0?yield o.play(d,r):o.stop()}})}_updateAudioPlayOption(s){return y(this,arguments,function*({playOption:e={},track:r,prevConfig:o}){if(!r.isPlayCalled)try{yield r.play(null,e)}catch(n){}V(e.muted)||r.setPlayerMute(e.muted),V(e.volume)||r.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,r=!0){let o=e.isRemote?e.userId:"";e.outMediaTrack&&(r&&this._mediaTrackMap.get(e.outMediaTrack)===o||(this._mediaTrackMap.set(e.outMediaTrack,o),this.emit(se.TRACK,{userId:o,streamType:eo(e.streamType),track:e.outMediaTrack,sourceTrack:e.mediaTrack})))}_checkTrackToPublish(){var r,o,s;let e=[];if((r=this._localAudioConfig)!=null&&r.publish&&this._localAudioTrack&&e.push(this._localAudioTrack),(o=this._localVideoConfig)!=null&&o.publish&&this._localVideoTrack&&e.push(this._localVideoTrack),(s=this._localScreenConfig)!=null&&s.publish&&(this._localScreenTrack&&e.push(this._localScreenTrack),this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack)),e.length!==0)return this._room.publish(...e).catch(()=>{})}_observeView({remoteTrack:e,view:r,receiveWhenViewVisible:o=!1,viewRoot:s}){if(V(r))return;let n=this._remoteVideoConfigMap.get(`${e.userId}_${eo(e.streamType)}`);if(!n)return;let d=n.observer||void 0;if(r===null||st(r)&&r.length===0||!o){d==null||d.disconnect(),e.isSubscribed||this._room.subscribe(e).catch(()=>{});return}let m=n.visibleViewMap||new Map,g=-1;(!d||d.root!==s)&&(d==null||d.disconnect(),m.clear(),d=new IntersectionObserver(b=>{b.forEach(N=>{m.set(N.target,N.isIntersecting)}),clearTimeout(g),g=window.setTimeout(()=>{let N=[...m.values()].find(k=>k);e.log.info(`view is${N?"":" not"} visible`),N?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:s}));let _=new Set(Es(r));m.forEach((b,N)=>{_.has(N)||(d.unobserve(N),m.delete(N))}),_.forEach(b=>{m.set(b,!0),d.observe(b)}),d.takeRecords().forEach(b=>{m.set(b.target,b.isIntersecting)}),n.visibleViewMap=m,n.observer=d}_exitRoom(){return y(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(e=>{this._stopRemoteAudio({userId:e}).catch()}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let r=e.includes("main")?"main":"sub",o=e.split(`_${r}`)[0];o&&this._stopRemoteVideo({userId:o,streamType:r}).catch()}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._remoteAudioVolumeMap.clear(),rg(this),this._room.remotePublishedUserMap.forEach(e=>{mt(e.remoteAudioTrack),mt(e.remoteVideoTrack),mt(e.remoteAuxiliaryTrack)})})}_stopScreenShare(){return y(this,null,function*(){var e;if(this._localScreenTrack){if(this._room.isJoined){let r=[this._localScreenTrack];this._localScreenAudioTrack&&r.push(this._localScreenAudioTrack),yield(e=this._room)==null?void 0:e.unpublish(...r).catch(()=>{})}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),mt(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_onLocalTrackCaptured({track:e}){e.kind==="audio"&&(!Rt||$s(Rt))&&(this._initActiveSpeaker(),H.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return y(this,null,function*(){if(Rt&&!$s(Rt))this.emit(se.DEVICE_CHANGED,{type:"speaker",action:"active",device:Rt});else{let e=yield Wi();e[0]&&!$s(e[0])?(Rt=e[0],this.emit(se.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):H.on("102",this._onLocalTrackCaptured,this)}})}_onAudioAvailable({userId:e}){let r=this._remoteAudioMuteMap.has(e)?this._remoteAudioMuteMap.get(e):this._remoteAudioMuteMap.get("*");(r===!1||this._room.autoReceiveAudio&&!r)&&this._doStartRemoteAudio({userId:e}).catch(()=>{})}_onVideoAvailable({userId:e,streamType:r}){if(!this._room.autoReceiveVideo)return;let o=this._room.remotePublishedUserMap.get(e);if(o){let s=r==="main"?o.remoteVideoTrack:o.remoteAuxiliaryTrack,n=[s];this._room.autoReceiveAudio&&o.remoteAudioTrack.isAvailable&&n.push(o.remoteAudioTrack),this._room.subscribe(...n).then(()=>{this._emitTrackEvent(s)}).catch(()=>{})}}_onAudioUnavailable({userId:e,muteState:r}){r.hasAudio&&r.audioMuted||this._stopRemoteAudio({userId:e},!1).catch(()=>{})}_onVideoUnavailable({userId:e,streamType:r}){this._stopRemoteVideo({userId:e,streamType:r},!1).catch(()=>{})}sendSEIMessage(e,r){var s;let o=this._plugins.get("SEI");o&&(o.update({buffer:e,options:Ee(ee({seiPayloadType:243},r),{small:!!((s=this._localVideoTrack)!=null&&s.small)})}),Y.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var r,o;(o=(r=this._room).sendCustomMessage)==null||o.call(r,e),Y.addCount({key:500001,useUV:!0})}static setLogLevel(e,r){$.setLogLevel(e),V(r)||(r?$.enableUploadLog():$.disableUploadLog())}static isSupported(){return Zc()}static getCameraList(e=!0){return er(e)}static getMicrophoneList(e=!0){return Jt(e)}static getSpeakerList(e=!0){return Wi(e)}static setCurrentSpeaker(e){return y(this,null,function*(){if(at&&(e===nr.SPEAKER||e===nr.HEADSET)){let o=yield fe.getMicrophoneList(),s="";if(o.forEach(n=>{n.label===e&&(s=n.deviceId)}),!s)return;Oa.forEach(n=>y(this,null,function*(){n._localAudioTrack&&(yield n.updateLocalAudio({option:{microphoneId:s}}))}));return}(yield Wi()).forEach(o=>{o.deviceId===e&&(Oa.forEach(s=>{s._setCurrentSpeaker(e),s.emit(se.DEVICE_CHANGED,{type:"speaker",action:"active",device:o})}),Rt=o)})})}static _addKVStat({type:e,key:r,value:o,base:s,useUV:n,version:d}){switch(d&&(Mo.version=d),e){case"count":Mo.addCount({key:r,useUV:n});break;case"enum":Mo.addEnum({key:r,value:o,useUV:n});break;case"number":Mo.addNumber({key:r,value:o,split:s});break}}};u(fe,"_loggerManager",$),u(fe,"EVENT",se),u(fe,"ERROR_CODE",ue),u(fe,"TYPE",nr),u(fe,"frameWorkType",30),X([Ye({replaceArg:e=>({argIndex:0,value:{name:"plugin"in e?e.plugin.Name:e.Name,assetsPath:"assetsPath"in e?e==null?void 0:e.assetsPath:"default"}})})],fe.prototype,"use",1),X([Ut(bt.TRTC.enterRoom),Zi("room",([e],[r])=>(e.roomId||e.strRoomId)===(r.roomId||r.strRoomId)&&e.userId===r.userId&&e.sdkAppId===r.sdkAppId),Me(e=>function(r){return this._log.setUserId(r.userId),this._log.setSdkAppId(r.sdkAppId),e.call(this,r)}),Ye()],fe.prototype,"enterRoom",1),X([Ye()],fe.prototype,"exitRoom",1),X([Ut(bt.TRTC.switchRole),Jo("room",{merge:(e,r)=>r}),Ye()],fe.prototype,"switchRole",1),X([Ye()],fe.prototype,"destroy",1),X([Ut(bt.TRTC.startLocalAudio),Zi("audio",([e],[r])=>{var o,s;return((o=e==null?void 0:e.option)==null?void 0:o.microphoneId)===((s=r==null?void 0:r.option)==null?void 0:s.microphoneId)}),Ye()],fe.prototype,"startLocalAudio",1),X([Ut(bt.TRTC.updateLocalAudio),Jo("audio",{debounce:{delay:200,getKey:()=>`${ug}-localAudio`,isNeedToDebounce:e=>{var r;return!V((r=e.option)==null?void 0:r.captureVolume)}}}),Ye()],fe.prototype,"updateLocalAudio",1),X([Ki("audio"),Ye()],fe.prototype,"stopLocalAudio",1),X([Ut(bt.TRTC.startLocalVideo),Zi("video",([e],[r])=>{var o,s;return((o=e==null?void 0:e.option)==null?void 0:o.cameraId)===((s=r==null?void 0:r.option)==null?void 0:s.cameraId)}),Ye()],fe.prototype,"startLocalVideo",1),X([Ut(bt.TRTC.updateLocalVideo),Jo("video"),Ye()],fe.prototype,"updateLocalVideo",1),X([Ki("video"),Ye()],fe.prototype,"stopLocalVideo",1),X([Ut(bt.TRTC.startScreenShare),Zi("screen",()=>!0),Ye()],fe.prototype,"startScreenShare",1),X([Ut(bt.TRTC.updateScreenShare),Jo("screen"),Ye()],fe.prototype,"updateScreenShare",1),X([Ye()],fe.prototype,"stopScreenShare",1),X([Ut(bt.TRTC.startRemoteVideo),Zi(e=>`v${e.userId}${e.streamType}`,()=>!0),Ye({getRemoteId:e=>`${e.userId}_${e.streamType}`})],fe.prototype,"startRemoteVideo",1),X([Ut(bt.TRTC.updateRemoteVideo),Jo(e=>`v${e.userId}${e.streamType}`),Ye({getRemoteId:e=>`${e.userId}_${e.streamType}`})],fe.prototype,"updateRemoteVideo",1),X([Ut(bt.TRTC.stopRemoteVideo),Me(e=>function(r){return y(this,null,function*(){if(r.userId==="*"){let o=[];return this._room.remotePublishedUserMap.forEach(s=>{this._remoteVideoConfigMap.has(`${s.userId}_main`)&&o.push(this.stopRemoteVideo({streamType:"main",userId:s.userId}).catch(()=>{})),this._remoteVideoConfigMap.has(`${s.userId}_sub`)&&o.push(this.stopRemoteVideo({streamType:"sub",userId:s.userId}).catch(()=>{}))}),Promise.all(o)}return e.call(this,r)})}),Ye({getRemoteId:e=>`${e.userId}_${e.streamType}`})],fe.prototype,"stopRemoteVideo",1),X([Ki(e=>`v${e.userId}${e.streamType}`)],fe.prototype,"_stopRemoteVideo",1),X([Ut(...bt.TRTC.muteRemoteAudio),Ye({getRemoteId:e=>e})],fe.prototype,"muteRemoteAudio",1),X([Xm(...bt.TRTC.setRemoteAudioVolume),ig(200,e=>e),Ye({getRemoteId:e=>e})],fe.prototype,"setRemoteAudioVolume",1),X([Jd("start"),Gi(e=>{var r;return(r=e.afterStart)==null?void 0:r.call(e)}),Zi((e,r)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(r)),Ye({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>bl[e.getName()],ignoreLog:e=>e.getName()==="Debug"})],fe.prototype,"startPlugin",1),X([Jd("update"),Jo((e,r)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(r)),Ye({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Rl[e.getName()]})],fe.prototype,"updatePlugin",1),X([Jd("stop"),Ki((e,r)=>{if(e.disableRandomCall)return null;let o=e.getGroup(r),s=e.getAlias();return o==="*"?new RegExp(`${s}.*`):s+o}),Ye({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>vl[e.getName()]})],fe.prototype,"stopPlugin",1),X([Xm(...bt.TRTC.enableAudioVolumeEvaluation)],fe.prototype,"enableAudioVolumeEvaluation",1),X([Ye()],fe.prototype,"getVideoSnapshot",1),X([Ye()],fe.prototype,"_setCurrentSpeaker",1),X([Zi(e=>`a${e.userId}`,()=>!0)],fe.prototype,"_startRemoteAudio",1),X([Me(e=>function(r){return y(this,null,function*(){return r.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(o=>this._stopRemoteAudio(Ee(ee({},r),{userId:o.userId})).catch(()=>{}))):e.call(this,r)})}),Ki(e=>`a${e.userId}`)],fe.prototype,"_stopRemoteAudio",1),X([Ki("room")],fe.prototype,"_exitRoom",1),X([Ki("screen")],fe.prototype,"_stopScreenShare",1),X([Ut(...bt.TRTC.sendSEIMessage),Hm({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...e)=>e[0].byteLength})],fe.prototype,"sendSEIMessage",1),X([Ut(bt.TRTC.sendCustomMessage),Hm({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],fe.prototype,"sendCustomMessage",1),X([Ut(bt.TRTC.create)],fe,"_create",1);var sp=fe,Zs=sp;var ru=class{constructor(t,e){u(this,"_flag");u(this,"terminalType");u(this,"userId");u(this,"tinyId");u(this,"role");u(this,"remoteAudioTrack");u(this,"remoteVideoTrack");u(this,"remoteAuxiliaryTrack");this.userId=e.userId||"",this.tinyId=e.tinyId||"",this.role=e.role||"audience",this.terminalType=e.terminalType,this.remoteAudioTrack=new $o(t,this),this.remoteVideoTrack=new Xi(t,this),this.remoteAuxiliaryTrack=new xd(t,this),this.flag=e.flag||0}get subscribeState(){let t={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(this.remoteVideoTrack.mediaType&8?t.smallVideo=!0:t.video=!0),this.remoteAudioTrack.isSubscribed&&(t.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(t.auxiliary=!0),t}get muteState(){return Mn(this.flag,this.userId)}get flag(){return this._flag}set flag(t){if(t===this._flag)return;let e,r=this.muteState;this._flag=t;let o=this.muteState;for(e in o)r[e]!=o[e]&&console.log(this.userId,e,r[e],"->",o[e]);this.remoteAudioTrack.onFlagChanged(),this.remoteVideoTrack.onFlagChanged(),this.remoteAuxiliaryTrack.onFlagChanged()}};var np=class{constructor(){u(this,"_set",new Set);H.on(L.LEAVE_SUCCESS,this.delete,this)}add({room:t,roomId:e}){if(t.scene==="rtc")return;let r=this.getKey(t.userId,e||t.roomId,t.sdkAppId,t.useStringRoomId);this._set.add(r)}delete({room:t,roomId:e}){if(t.scene==="rtc")return;let r=this.getKey(t.userId,t.roomId||e,t.sdkAppId,t.useStringRoomId);this._set.delete(r)}getKey(t,e,r,o){return`${r}_${e}_${t}_${o}`}isJoined({userId:t,roomId:e,sdkAppId:r,room:o}){return o.scene==="rtc"?!1:this._set.has(this.getKey(t,e,r,o.useStringRoomId))}};function eS(){return y(this,null,function*(){let i,t;try{let _=yield Jt();i=_&&_.length}catch(_){}try{let _=yield er();t=_&&_.length}catch(_){}let e={microphone:i,camera:t},{isH264EncodeSupported:r,isVp8EncodeSupported:o,isH264DecodeSupported:s,isVp8DecodeSupported:n}=this.checkSystemResult.detail,d=Bi.basis(),p={webRTC:d.isWebRTCSupported,getUserMedia:d.isGetUserMediaSupported,webSocket:d.isWebSocketsSupported,screenShare:d.isScreenShareSupported,webAudio:d.isWebAudioSupported,h264Encode:r,h264Decode:s,vp8Encode:o,vp8Decode:n},m={browser:d.browser,os:d.os,trtc:p,devices:e},g={isWebCodecSupported:d.isWebCodecSupported,isMediaSessionSupported:d.isMediaSessionSupported,isWebTransportSupported:d.isWebTransportSupported};Be.uploadEvent({log:`trtcstats-${JSON.stringify(m)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(m)}`),Be.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(g)}`,userId:this.userId})})}function mg(){return Me(i=>{let t=new np;return function(e,r,o){return y(this,null,function*(){let s=String(e.roomId||e.strRoomId);if(this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.userSig=e.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=r,e.privateMapKey=e.privateMapKey||"",this.isJoined)throw new he({code:te.INVALID_OPERATION,message:dt({key:ct.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:s,sdkAppId:this.sdkAppId,room:this}))throw new he({code:te.INVALID_OPERATION,message:dt({key:ct.REPEAT_JOIN,data:this.userId})});t.add({room:this,roomId:s}),this.role=e.role===21?"audience":"anchor",this._log.info(`Join() => joining room: ${s} useStringRoomId: ${this.useStringRoomId} scene: ${this.scene} role: ${this.role}`),H.emit(L.JOIN_START,{room:this,roomId:s,params:e});let n=Lr.getEnv();n||(n=zr.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(uc.OLD_CLOUD_LADDER)?n=zr.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(uc.WEBRTC)&&(n=zr.WEBRTC))),Be.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:s}),Bi.checkSystemRequirementsInternal().then(d=>{this.checkSystemResult=d,eS.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Lr.getEnv()&&(yield this.schedule(e,o));let d=yield i.call(this,e,r,o);return this.roomId=s,this._joinedTimestamp=Lr.performanceNow(),H.emit(L.JOIN_SUCCESS,{room:this}),o===30&&!e.component&&Be.uploadEvent({log:`stat-conv-${Number(Tr)}-${location.hostname}`,userId:this.userId}),d}catch(d){throw t.delete({room:this,roomId:s}),H.emit(L.JOIN_FAILED,{room:this,error:d}),d}})}})}var pg=()=>Me(i=>function(...t){return y(this,null,function*(){H.emit(L.LEAVE_START,{room:this}),yield i.call(this,...t),H.emit(L.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function hg(){return Me(i=>function(...t){return y(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(t=t.filter(r=>r.outMediaTrack&&r.state==="capture"),!t.length))return;H.emit("61",{room:this});let e=i.apply(this,t);return t.forEach(r=>r.publish(this,e)),e})})}function fg(){return Me(i=>function(...t){let e=i.apply(this,t);return t.forEach(r=>r.unpublish()),e})}function gg(){return Me(i=>function(...t){let e=i.apply(this,t);return t.forEach(r=>!r.isSubscribed&&r.subscribe(e)),e})}function tS({fn:i,context:t}){return function(...e){try{let r=i.apply(t,e);return xi(r)?r.catch(o=>$.error(`${i.name}() error observed ${o}`)):r}catch(r){$.error(`${i.name}() error observed ${r}`)}}}var iu=class{constructor(t){u(this,"_frameWorkType");u(this,"_component");u(this,"_language");u(this,"connectionType");u(this,"_room");u(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0});u(this,"_keyPrefix");u(this,"_log");u(this,"_intervalId");u(this,"_firstPublishedUserList");u(this,"_networkQuality");u(this,"_basicInfo");u(this,"_pathJoinRoom");u(this,"_pathLeaveRoom");u(this,"_pathMainVideoMap");u(this,"_pathMainAudioMap");u(this,"_pathAuxiliaryMap");u(this,"_remoteStreamStatMap");u(this,"_localStreamStat");u(this,"_eventMap",new Map);u(this,"_captureCostSum",0);u(this,"_captureCostCount",0);u(this,"isDestroyed",!1);this._frameWorkType=t.frameWorkType||30,this._component=t.component||0,this.connectionType=t.connectionType||1,this._language=t.language||0,this._room=t.room,this._keyPrefix="key_point",this._log=$.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(e=>{e.startsWith("handle")&&Xe(this[e])&&(this[e]=tS({fn:this[e],context:this}))}),this.initData(),this.installEvents()}initData(){this._firstPublishedUserList=[],this._networkQuality={totalUplinkRTT:0,totalUplinkLoss:0,count:0,totalDownlinkRTTAndLossMap:new Map},this._basicInfo={string_sdk_version:rt,uint32_os_type:15,string_device_name:"",string_http_user_agent:navigator.userAgent,string_os_version:"",uint32_avg_rtt:0,uint32_avg_up_loss:0,uint32_scene:this._room.scene==="live"?1:0,uint32_joining_duration:0,uint32_networkType:0,uint32_framework:this._frameWorkType,uint32_component:this._component,uint32_connection_type:this.connectionType,uint32_caller_coding_language:this._language,string_domain:location.hostname},this._pathJoinRoom={uint64_start_time:0,uint64_send_request_acc_ip_cmd_start_time:0,uint64_send_request_acc_ip_cmd_end_time:0,uint64_send_request_enter_room_cmd_start_time:0,uint64_send_request_enter_room_cmd_end_time:0,uint64_send_first_video_frame_time:0,uint64_recv_userlist_time:0,uint64_end_time:0,int32_send_request_acc_ip_cmd_ret:0,int32_send_request_enter_room_cmd_ret:0,int32_end_ret:0},this._pathLeaveRoom={uint64_start_time:0,uint64_send_request_exit_room_cmd_start_time:0,uint64_send_request_exit_room_cmd_end_time:0,uint64_end_time:0,int32_send_request_exit_room_cmd_ret:0,int32_end_ret:0},this._localStreamStat={totalVideoBitrate:0,totalVideoFPS:0,totalVideoHeight:0,totalVideoWidth:0,totalAudioLevel:0,videoCount:0,audioLevelCount:0,publishStartTime:0,statsToReport:{uint32_audio_capture_db:0,uint32_video_big_capture_fps:0,uint32_video_big_bitrate:0,uint32_video_big_resolution:0}},this._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,jn().then(t=>{this._basicInfo.string_os_version=bo(),t?this._basicInfo.string_device_name=t.mobile?t.model:this._basicInfo.string_os_version:this._basicInfo.string_device_name=this._basicInfo.string_os_version})}addEvent(t,e){return this._eventMap.set(t,e),H.on(t,e),this}installEvents(){this.handleUnload=this.handleUnload.bind(this),window.addEventListener("pagehide",this.handleUnload),this._room.once("banned",()=>this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})),this.addEvent(L.JOIN_START,this.handleJoinStart).addEvent(L.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(L.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(L.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(L.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(L.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(L.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(L.JOIN_FAILED,this.handleJoinFailed).addEvent(L.LEAVE_START,this.handleLeaveStart).addEvent(L.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(L.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(L.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(L.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(L.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(L.PUBLISH_START,this.handlePublishStart).addEvent(L.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(L.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(L.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(L.PLAY_TRACK_START,this.handlePlayStart).addEvent(L.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(L.PLAYER_STATE_CHANGED,({track:t,state:e,type:r})=>{!t.isRemote||!this.hitTest(t.room)||e==="PLAYING"&&(r===D.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))}).addEvent(L.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(L.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(L.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(L.REMOTE_PUBLISH_STATE_CHANGED,({room:t,prevMuteState:e,muteState:r})=>{if(!this.hitTest(t))return;let o=e.hasAudio||e.hasVideo||e.hasSmall,s=e.hasAuxiliary,n=r.hasAudio||r.hasVideo||r.hasSmall,d=r.hasAuxiliary;!o&&n&&this.handleRemoteStreamAdded(r.userId,"main"),!s&&d&&this.handleRemoteStreamAdded(r.userId,"auxiliary")}).addEvent(L.SINGLE_CONNECTION_STAT,({room:t,stat:e})=>{this.hitTest(t)&&(this._pathJoinRoom.int32_ice_cost=e.ice,this._pathJoinRoom.int32_dtls_cost=e.dtls,this._pathJoinRoom.int32_peer_connection_cost=e.peerConnection)})}uninstallEvents(){window.removeEventListener("pagehide",this.handleUnload),this._eventMap.forEach((t,e)=>H.off(e,t)),this._eventMap.clear()}destroy(){this.uninstallEvents(),At.clearTask(this._intervalId),this._pathJoinRoom.uint64_start_time===0&&(this._room=null),this.isDestroyed=!0}handleUnload(){this._room.isJoined&&this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})}handleJoinStart(t){this.hitTest(t.room)&&(this._pathJoinRoom.uint64_start_time===0&&(this._pathJoinRoom.uint64_start_time=Date.now()),t.params&&(V(t.params.frameWorkType)||(this._frameWorkType=t.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),V(t.params.component)||(this._component=t.params.component,this._basicInfo.uint32_component=this._component),V(t.params.language)||(this._language=t.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleJoinScheduleSuccess({room:t,detailCost:e}){if(this.hitTest(t)&&e){let{totalCost:r,local:o,dns:s,tcp:n,tls:d,request:p,response:m}=e;this._pathJoinRoom.int32_schedule_cost=r,this._pathJoinRoom.int32_schedule_local=o,this._pathJoinRoom.int32_schedule_dns=s,this._pathJoinRoom.int32_schedule_tcp=n,this._pathJoinRoom.int32_schedule_tls=d,this._pathJoinRoom.int32_schedule_request=p,this._pathJoinRoom.int32_schedule_response=m}}handleSignalConnectionStart({room:t}){this.hitTest(t)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time=Date.now())}handleSignalConnectionEnd({room:t,error:e}){this.hitTest(t)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time=Date.now(),e&&(this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret=e instanceof he?Number(e.getExtraCode()||e.getCode()):te.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}handleJoinSendCMD(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now())}handleJoinReceivedCMDResponce(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=t.code,t.code!==0&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}handleJoinSuccess(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_end_time===0&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=t.room.getSignalInfo())}handleJoinFailed({room:t,error:e}){this.hitTest(t)&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret===0&&(this._pathJoinRoom.int32_end_ret=e.code||this._pathJoinRoom.int32_send_request_enter_room_cmd_ret||this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret),setTimeout(()=>{this.report()}))}handleReceivedPublishUserList(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_recv_userlist_time===0&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=t.publishedUserList||[])}handleSendFirstVideoFrame({room:t}){this.hitTest(t)&&this._pathJoinRoom.uint64_send_first_video_frame_time===0&&this._pathJoinRoom.uint64_start_time!==0&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now())}handleLeaveStart(t){this.hitTest(t.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(t){this.hitTest(t.room)&&this._pathLeaveRoom.uint64_end_time===0&&(this._pathLeaveRoom.uint64_end_time=Date.now(),this._pathJoinRoom.uint64_end_time!==0?this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time:this._log.warn("pathJoinRoom endTime is 0"),this.report())}handleLeaveSendCMD(t){this.hitTest(t.room)&&(this._pathLeaveRoom.uint64_send_request_exit_room_cmd_start_time=Date.now(),this._pathLeaveRoom.uint64_send_request_exit_room_cmd_end_time=Date.now())}handleRemoteStreamAdded(t,e){var o;let r=`${t}_${e}`;if(!this._remoteStreamStatMap.has(r)){let s={userId:t,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:Ee(ee({},rS),{msg_user_info:new xa({userId:t,tinyId:(o=this._room.remotePublishedUserMap.get(t))==null?void 0:o.tinyId,role:20})})};s.statsToReport.uint32_stream_type=e==="main"?2:7,this._remoteStreamStatMap.set(r,s)}}handleSubscribeStart({room:t,remotePublishedUser:e,streamType:r,subscribeState:o}){if(!this.hitTest(t))return;let{userId:s,tinyId:n,role:d}=e,p=new xa({userId:s,tinyId:n,role:d==="anchor"?20:21}),m=Date.now(),g=`${s}_${r}`,_=this._remoteStreamStatMap.get(g);_&&_.subscribeStartTime===0&&(_.subscribeStartTime=m),r==="main"?(e.muteState.hasVideo&&(o.video||o.smallVideo)&&!this._pathMainVideoMap.has(g)&&this._pathMainVideoMap.set(g,{statsToReport:{msg_user_info:p,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:s,sendSubscribeCMDTime:m}),e.muteState.hasAudio&&o.audio&&!this._pathMainAudioMap.has(g)&&this._pathMainAudioMap.set(g,{statsToReport:{msg_user_info:p,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:s,sendSubscribeCMDTime:m})):e.muteState.hasAuxiliary&&o.auxiliary&&!this._pathAuxiliaryMap.has(g)&&this._pathAuxiliaryMap.set(g,{sendSubscribeCMDTime:m})}handleSubscribed({room:t,remotePublishedUser:e,streamType:r}){if(this.hitTest(t)){let o=`${e.userId}_${r}`,s=this._remoteStreamStatMap.get(o);s&&s.subscribedTime===0&&(s.subscribedTime=Date.now())}}handlePlayStart({track:t}){if(!t.isRemote||!this.hitTest(t.room))return;let e=`${t.userId}_${t.streamType}`,r=this._remoteStreamStatMap.get(e);(r==null?void 0:r.playStreamTime)===0&&(r.playStreamTime=Date.now())}handleVideoLoadedData({track:t}){if(!t.isRemote||!this.hitTest(t.room))return;let e=`${t.userId}_${t.streamType}`,r=this._pathMainVideoMap.get(e);r&&r.statsToReport.uint64_combine_first_frame_time===0&&(r.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(t){let e=`${t.userId}_${t.streamType}`,r=Date.now(),o=this._pathMainVideoMap.get(e),s=this._remoteStreamStatMap.get(e);if(s){let{statsToReport:n}=s;if(!n.uint32_video_render_first&&t.streamType==="main"?this.hasVideoFlag(t.userId):this.hasAuxFlag(t.userId)){let d=r-this._pathJoinRoom.uint64_start_time;n.uint32_video_render_first=d,Y.addNumber({key:516820,value:d})}}(o==null?void 0:o.statsToReport.uint64_render_first_frame_time)===0&&(o.statsToReport.uint64_render_first_frame_time=r)}handleAudioPlaying(t){let e=`${t.userId}_${t.streamType}`,r=this._pathMainAudioMap.get(e);r&&r.statsToReport.uint64_play_first_frame_time===0&&(r.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(t){this.hitTest(t.room)&&(this._networkQuality.totalUplinkLoss+=t.uplink.loss,this._networkQuality.totalUplinkRTT+=t.uplink.rtt,this._networkQuality.count++,t.downlinks.forEach(({rtt:e,loss:r,userId:o,videoDelay:s,audioDelay:n})=>{let d=this._networkQuality.totalDownlinkRTTAndLossMap.get(o);if(d)d.totalRTT+=e,d.totalLoss+=r,s&&(d.totalVideoDelay=(d.totalVideoDelay||0)+s,d.videoDelayCount=(d.videoDelayCount||0)+1),n&&(d.totalAudioDelay=(d.totalAudioDelay||0)+n,d.audioDelayCount=(d.audioDelayCount||0)+1),d.count++;else{let p,m,g,_;s&&(m=s,g=1),n&&(p=n,_=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(o,{totalRTT:e,totalLoss:r,count:1,totalAudioDelay:p,totalVideoDelay:m,audioDelayCount:_,videoDelayCount:g})}}))}handleHeartbeatStats(t){if(this.hitTest(t.room)){let{msg_device_info:e,msg_up_stream_info:r,msg_down_stream_info:o}=t.report;if(r.msg_video_status[0]){let{uint32_video_codec_bitrate:s,uint32_video_enc_fps:n,uint32_video_width:d,uint32_video_height:p}=r.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=s,this._localStreamStat.totalVideoFPS+=n,this._localStreamStat.totalVideoWidth+=d,this._localStreamStat.totalVideoHeight+=p,this._localStreamStat.videoCount++}if(r.msg_audio_status){let{uint32_audio_level:s}=r.msg_audio_status;Math.floor(s/oi*100)>0&&(this._localStreamStat.totalAudioLevel+=s/oi,this._localStreamStat.audioLevelCount++)}o.forEach(s=>{let{msg_user_info:n,msg_audio_status:d,msg_video_status:p}=s,m=n.str_identifier,g=this._room.remotePublishedUserMap.get(m);if(p.forEach(_=>{let b=_.uint32_video_stream_type===2,N=_.uint32_video_stream_type===7,k=`${m}_${b?"main":"auxiliary"}`,P=this._remoteStreamStatMap.get(k);if(P&&(b&&(g!=null&&g.remoteVideoTrack.isSubscribed)||N&&(g!=null&&g.remoteAuxiliaryTrack))){P.totalVideoFPS+=_.uint32_video_receive_fps,P.totalVideoBitrate+=_.uint32_video_codec_bitrate,P.videoCount++,P.statsToReport.uint32_video_width===0&&(P.statsToReport.uint32_video_width=_.uint32_video_width),P.statsToReport.uint32_video_height===0&&(P.statsToReport.uint32_video_height=_.uint32_video_height);let x=b?g.remoteVideoTrack:g.remoteAuxiliaryTrack;x.stat.jitterBufferDelay&&(P.videoJitterBufferDelay=x.stat.jitterBufferDelay),x.stat.framesReceived&&(P.statsToReport.uint32_video_consume_render_rate=Math.floor(x.stat.framesDecoded/x.stat.framesReceived*En(10,6)))}}),!fs(d)){let _=`${m}_main`,b=this._remoteStreamStatMap.get(_);this._remoteStreamStatMap.has(_)&&b&&g!=null&&g.remoteAudioTrack.isSubscribed&&(b.totalAudioBitrate+=d.uint32_audio_codec_bitrate,b.audioCount++,g.remoteAudioTrack.stat.jitterBufferDelay&&(b.audioJitterBufferDelay=g.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(d.uint32_audio_level/oi*100)>0&&(b.totalAudioLevel+=d.uint32_audio_level/oi,b.audioLevelCount++))}}),e.uint32_audio_capture_cost&&(this._captureCostSum+=e.uint32_audio_capture_cost,this._captureCostCount+=1,this._captureCostCount>=100&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0))}}handlePublishStart({room:t}){this.hitTest(t)&&this._localStreamStat.publishStartTime===0&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart({track:t}){t.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),t.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess({track:t}){t.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=0,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),t.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=0,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed({track:t,error:e}){let o={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[e.name]||(e instanceof he?e.getExtraCode()||e.getCode():te.UNKNOWN);t.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=o,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),t.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=o,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}hasVideoFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&ls)>=0}hasAudioFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&ms)>=0}hasAuxFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&yn)>=0}hitTest(t){return t===this._room}prepareReport(){if(this._captureCostCount>0&&!this._basicInfo.uint32_audio_capture_cost&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0),this._networkQuality.count>0&&(this._basicInfo.uint32_avg_rtt=Math.floor(this._networkQuality.totalUplinkRTT/this._networkQuality.count),this._basicInfo.uint32_avg_up_loss=Math.floor(this._networkQuality.totalUplinkLoss/this._networkQuality.count)),this._localStreamStat.videoCount>0){this._localStreamStat.statsToReport.uint32_video_big_capture_fps=Math.floor(this._localStreamStat.totalVideoFPS/this._localStreamStat.videoCount),this._localStreamStat.statsToReport.uint32_video_big_bitrate=Math.floor(this._localStreamStat.totalVideoBitrate/this._localStreamStat.videoCount);let t=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),e=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=t<<16|e}this._localStreamStat.audioLevelCount>0&&(this._localStreamStat.statsToReport.uint32_audio_capture_db=Math.floor(this._localStreamStat.totalAudioLevel/this._localStreamStat.audioLevelCount*100)),this._remoteStreamStatMap.forEach((t,e)=>{let{userId:r}=t,o=this._networkQuality.totalDownlinkRTTAndLossMap.get(r);if(o){let{totalLoss:g,count:_,audioDelayCount:b,videoDelayCount:N,totalAudioDelay:k,totalVideoDelay:P}=o;t.statsToReport.uint32_avg_down_loss=Math.floor(g/_),b&&k&&(t.statsToReport.uint32_audio_network_p2p_delay=Math.floor(k/b),t.audioJitterBufferDelay&&(t.statsToReport.uint32_p2p_delay=Math.floor(t.statsToReport.uint32_audio_network_p2p_delay+t.audioJitterBufferDelay))),N&&P&&(t.statsToReport.uint32_video_network_p2p_delay=Math.floor(P/N))}t.videoCount>0&&(t.statsToReport.uint32_video_avg_fps=Math.floor(t.totalVideoFPS/t.videoCount),t.statsToReport.uint32_video_avg_bitrate=Math.floor(t.totalVideoBitrate/t.videoCount)),t.audioCount>0&&(t.statsToReport.uint32_audio_recv_bitrate=t.statsToReport.uint32_audio_bitrate=Math.floor(t.totalAudioBitrate/t.audioCount)),t.audioLevelCount>0&&(t.statsToReport.uint32_audio_play_db=Math.floor(t.totalAudioLevel/t.audioLevelCount*100));let{callDurationCalculator:s}=this._room;s&&(t.statsToReport.uint32_audio_play_time=s.getDuration(e,D.AUDIO),t.statsToReport.uint32_video_play_time=s.getDuration(e,D.VIDEO)),t.statsToReport.uint32_video_render_first&&(t.statsToReport.uint32_video_render_first=Math.min(t.statsToReport.uint32_video_render_first,Xo));let{badCaseDetector:n}=this._room,{dataFreeze:d,count:p}=n.getDataFreezeDuration(e),{renderFreeze:m}=n.getRenderFreezeDuration(e);t.statsToReport.uint32_video_block_count=p,t.statsToReport.uint32_video_block_time=Math.min(d,t.statsToReport.uint32_video_play_time),t.statsToReport.uint32_video_external_block_time=Math.min(m,t.statsToReport.uint32_video_play_time),n.isBlackStream(e)&&t.statsToReport.uint32_video_avg_fps===0?t.statsToReport.uint32_video_black_screen_subjective=1:t.statsToReport.uint32_video_black_screen_subjective=0}),this._pathMainAudioMap.forEach((t,e)=>{if(!this.hasAudioFlag(t.userId)){this._pathMainAudioMap.delete(e);return}t.statsToReport.uint64_play_first_frame_time-t.statsToReport.uint64_start_enter_time>Xo&&(t.statsToReport.uint64_play_first_frame_time=t.statsToReport.uint64_start_enter_time+Xo)}),this._pathMainVideoMap.forEach((t,e)=>{if(!this.hasVideoFlag(t.userId)){this._pathMainVideoMap.delete(e);return}t.statsToReport.uint64_render_first_frame_time-t.statsToReport.uint64_start_enter_time>Xo&&(t.statsToReport.uint64_render_first_frame_time=t.statsToReport.uint64_start_enter_time+Xo)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>Xo&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+Xo)}getReportData(){this._basicInfo.uint32_networkType=fc();let t={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new xa({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:gs(this._signalInfo.relayIp),uint32_client_ip:gs(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*En(2,31)),msg_path_enter_room:this._pathJoinRoom,msg_path_exit_room:this._pathLeaveRoom,msg_path_recv_video:[...this._pathMainVideoMap.values()].map(e=>e.statsToReport),msg_quality_statistics:[...this._remoteStreamStatMap.values()].map(e=>e.statsToReport),str_room_name:String(this._room.roomId||0),msg_path_recv_audio:[...this._pathMainAudioMap.values()].map(e=>e.statsToReport),uint32_info_client_ip:gs(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,bytes_report_buf_from_0x1:this._signalInfo.endReportExtend};return On(t),t}report(){return y(this,null,function*(){try{this.prepareReport();let t=this.getReportData();yield this.upload(t),this.initData()}catch(t){this._log.warn(t)}finally{this.isDestroyed&&(this._room=null)}})}upload(t){return y(this,null,function*(){if(t.msg_path_enter_room.uint64_start_time===0)return;let e=Number(this._room.sdkAppId),r=yield Wu(t),o=r instanceof ArrayBuffer,s=`${Yr(e,Oi.KEY_POINT)}&gzip=${+o}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(s,r));let d=[this.uploadKVStat(Y),this.uploadKVStat(Mo)];n||d.push(Zr({url:s,body:r,priority:"low"})),yield Promise.all(d)})}setConnectionType(t){this.connectionType=t,this._basicInfo.uint32_connection_type=t}uploadKVStat(t){return y(this,null,function*(){let e=t.getReportData();if(e.stats_count.length===0&&e.stats_distribution.length===0)return;e.msg_sdk_basic_info=Ee(ee({},e.msg_sdk_basic_info),{bytes_device_name:this._basicInfo.string_device_name||"",bytes_os_version:this._basicInfo.string_os_version||"",uint32_framework:this._frameWorkType,uint32_network_type:this._basicInfo.uint32_networkType||0}),this._log.debug(e);let r=yield Wu(e),o=`${Yr(+this._room.sdkAppId,Oi.KV_STAT)}&gzip=${+(r instanceof ArrayBuffer)}`,s=!1;navigator.sendBeacon&&(s=navigator.sendBeacon(o,r)),s||Zr({url:o,body:r})})}};X([Hi({settings:{timeout:500,retries:3}})],iu.prototype,"upload",1);var Xo=5e3,rS={msg_user_info:null,uint32_video_avg_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_avg_bitrate:0,uint32_video_block_time:0,uint32_video_play_time:0,uint32_audio_block_time:0,uint32_audio_play_time:0,uint32_audio_play_db:0,uint32_avg_down_loss:0,uint32_stream_type:0,uint32_video_block_count:0,uint32_audio_block_count:0,uint32_audio_bitrate:0,uint32_video_black_screen_subjective:0,uint32_audio_recv_bitrate:0,uint32_video_external_block_time:0,uint32_video_consume_render_rate:0},xa=class{constructor(t){u(this,"str_identifier");u(this,"str_tinyid");u(this,"uint32_role");this.str_identifier=String(t.userId),this.str_tinyid=String(t.tinyId||0),this.uint32_role=t.role}},Eg=iu;var ap=class{constructor(){u(this,"_startTime");u(this,"_endTime");this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=_e())}stop(){this._endTime===0&&(this._endTime=_e())}getDuration(){return this._endTime===0?_e()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},ou=ap;var cp=class{constructor(t){u(this,"_room",null);u(this,"_durationMap");u(this,"_eventMap",new Map);this._room=t.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(L.REMOTE_TRACK_SUBSCRIBED,this.handleSubscribed).set(L.REMOTE_TRACK_UNSUBSCRIBED,this.handleUnsubscribed).set(L.REMOTE_PUBLISH_STATE_CHANGED,({room:t,prevMuteState:e,muteState:r})=>{var n;let{userId:o}=r;if(!this.hitTest(t))return;e.hasAudio&&!r.hasAudio&&this.stopDurationItem(`${o}_main`,D.AUDIO),e.hasVideo&&!r.hasVideo&&this.stopDurationItem(`${o}_main`,D.VIDEO),e.hasAuxiliary&&!r.hasAuxiliary&&this.stopDurationItem(`${o}_auxiliary`,D.VIDEO);let s=(n=this._room)==null?void 0:n.remotePublishedUserMap.get(o);s&&(!e.hasAudio&&r.hasAudio&&s.remoteAudioTrack.isSubscribed&&this.addDuractionItem(o,D.AUDIO,"main"),!e.hasVideo&&r.hasVideo&&s.remoteVideoTrack.isSubscribed&&this.addDuractionItem(o,D.VIDEO,"main"),!e.hasAuxiliary&&r.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(o,D.VIDEO,"auxiliary"))}),this._eventMap.forEach((t,e)=>H.on(e,t,this))}uninstallEvents(){this._eventMap.forEach((t,e)=>H.off(e,t,this)),this._eventMap.clear()}handleSubscribed({track:t}){if(!this.hitTest(t.room))return;let{userId:e,streamType:r,kind:o}=t;t.isSubscribed?this.addDuractionItem(e,o,r):this.stopDurationItem(`${e}_${r}`,o)}handleUnsubscribed({track:t}){this.hitTest(t.room)&&this.stopDurationItem(`${t.userId}_${t.streamType}`,t.kind)}isRecording(t){return t.findIndex(e=>e.endTime===0)>=0}addDuractionItem(t,e,r){let o=`${t}_${r}`,s=new ou,n=this._durationMap.get(o);n?this.isRecording(n[e])||n[e].push(s):this._durationMap.set(o,{userId:t,type:r,audio:e===D.AUDIO?[s]:[],video:e===D.AUDIO?[]:[s]})}stopDurationItem(t,e){if(this._durationMap.has(t)){let o=this._durationMap.get(t)[e].find(s=>s.endTime===0);o&&o.stop()}}hitTest(t){return this._room===t}getDuration(t,e){return this._durationMap.has(t)?this._durationMap.get(t)[e].reduce((o,s)=>o+s.getDuration(),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},_g=cp;var dp=class{constructor(t){u(this,"_room");u(this,"_renderFreezeMap",new Map);u(this,"_isVideoPlayingEventFiredMap",new Map);u(this,"_dataFreezeMap",new Map);u(this,"_monitorFreezeData",new Map);u(this,"_eventMap",new Map);this._room=t.room,this.installEvents()}getRenderFreezeMap(){return this._renderFreezeMap}getDataFreezeMap(){return this._dataFreezeMap}installEvents(){this._eventMap.set(L.LEAVE_SUCCESS,({room:t})=>{this.hitTest(t)&&this.stop()}).set(L.PLAY_TRACK_START,this.onPlayTrackStart).set(L.UNSUBSCRIBE_SUCCESS,({room:t,streamType:e,remotePublishedUser:r})=>{if(!this.hitTest(t))return;let{userId:o}=r,s=`${o}_${e}`;this.stopDataFreeze({key:s,userId:o,type:e})}).set(L.REMOTE_PUBLISH_STATE_CHANGED,({room:t,prevMuteState:e,muteState:r})=>{if(!this.hitTest(t))return;let{userId:o}=r;if(e.hasVideo&&!r.hasVideo){let s="main",n=`${r.userId}_${s}`;this.stopDataFreeze({key:n,userId:o,type:s})}if(e.hasAuxiliary&&!r.hasAuxiliary){let s="auxiliary",n=`${r.userId}_${s}`;this.stopDataFreeze({key:n,userId:o,type:s})}}).set(L.PLAYER_STATE_CHANGED,({track:t,state:e,reason:r,type:o})=>{if(!(!t.isRemote||!t.room||!this.hitTest(t.room)||o!==D.VIDEO)){if(e==="PLAYING"){let s=`${t.userId}_${t.streamType}`;this._isVideoPlayingEventFiredMap.set(s,!0)}r===D.MUTE?this.onVideoTrackMuted(t):r===D.UNMUTE&&this.onVideoTrackUnmuted(t)}}).set(L.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach((t,e)=>H.on(e,t,this))}uninstallEvents(){this._eventMap.forEach((t,e)=>H.off(e,t,this)),this._eventMap.clear()}stop(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}onVideoTrackMuted(t){if(!t.isSubscribed)return;let{userId:e,streamType:r}=t,o=`${e}_${r}`,s=this._dataFreezeMap.get(o),n=new ou;s?s.durationItemList.push(n):this._dataFreezeMap.set(o,{userId:e,type:r,durationItemList:[n],isFreezing(){let d=this.durationItemList[this.durationItemList.length-1];return d&&d.endTime===0}})}onVideoTrackUnmuted(t){if(!t.isSubscribed)return;let{userId:e,streamType:r}=t,o=`${e}_${r}`;this.stopDataFreeze({key:o,userId:e,type:r})}onHearBeatReport({room:t,report:e}){this.hitTest(t)&&e.msg_down_stream_info.forEach(r=>{let o=this._room.remotePublishedUserMap.get(r.msg_user_info.str_identifier);if(!o)return;let{userId:s,muteState:n}=o;r.msg_video_status.forEach(d=>{d.uint32_video_stream_type===2&&n.hasVideo&&!n.videoMuted&&o.remoteVideoTrack.isSubscribed&&this.handleRenderFreeze({userId:s,fps:d.uint32_video_dec_fps,type:"main"}),d.uint32_video_stream_type===7&&n.hasAuxiliary&&o.remoteAuxiliaryTrack.isSubscribed&&this.handleRenderFreeze({userId:s,fps:d.uint32_video_dec_fps,type:"auxiliary"})})})}stopDataFreeze({key:t,userId:e,type:r}){let o=this._dataFreezeMap.get(t);if(!o||!o.isFreezing())return;let s=o.durationItemList[o.durationItemList.length-1];s.stop();let n=s.getDuration();n>pc?this._monitorFreezeData.set(t,{userId:e,type:r,duration:n}):o.durationItemList.pop()}getTotalDuration(t){return t.reduce((e,r)=>{let o=r.getDuration();return e+Math.min(o,5e3)},0)}handleRenderFreeze(o){return y(this,arguments,function*({userId:t,fps:e,type:r}){let s=`${t}_${r}`,n=this._renderFreezeMap.get(s);if(e<=2){let d=_e();n&&!n.isFreeze&&(n.freezeTimeline.push({startTime:d,endTime:0}),n.isFreeze=!0),n||this._renderFreezeMap.set(s,{userId:t,type:r,isFreeze:!0,freezeTimeline:[{startTime:d,endTime:0}],renderFreezeTotal:0})}else if(n&&n.isFreeze){n.isFreeze=!1;let d=n.freezeTimeline.pop();if(d){d.endTime=_e();let p=d.endTime-d.startTime;n.freezeTimeline.push(d),n.renderFreezeTotal+=Math.min(5e3,p)}}})}onPlayTrackStart({track:t}){if(!t.isRemote||!this.hitTest(t.room)||t.kind!==D.VIDEO||!t.isRemotePublished)return;let e=`${t.userId}_${t.streamType}`;this._isVideoPlayingEventFiredMap.has(e)||this._isVideoPlayingEventFiredMap.set(e,!1)}getDataFreezeDuration(t){let e={dataFreeze:0,count:0},r=this._dataFreezeMap.get(t);if(r){if(r.isFreezing()){let o=r.durationItemList[r.durationItemList.length-1];o.stop(),o.getDuration()<pc&&r.durationItemList.pop()}e.dataFreeze=this.getTotalDuration(r.durationItemList),e.count=r.durationItemList.length}return e}getRenderFreezeDuration(t){let e=this._renderFreezeMap.get(t),r=0,o=0;if(e)if(!e.isFreeze)r=e.renderFreezeTotal;else{let s=_e(),n=e.freezeTimeline[e.freezeTimeline.length-1],d=s-n.startTime;r=e.renderFreezeTotal+Math.min(d,5e3),o=e.freezeTimeline.length}return{renderFreeze:r,count:o}}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(t){return this._isVideoPlayingEventFiredMap.has(t)?!this._isVideoPlayingEventFiredMap.get(t):!1}resetMonitor(){this._monitorFreezeData.clear()}hitTest(t){return t===this._room}destroy(){this.uninstallEvents()}},Tg=dp;var Sg=Mi($i(),1);var iS=[1,0,0,0,1,1,0,1],su=class extends Bt{constructor(t,e){if(super(t,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"mirror",logger:e}),t instanceof Et)try{this.setTexBuffer(iS)}catch(r){t.destroy(new he({code:te.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${r.message||r}`}))}}draw2d(t,e,r,o,s){if(this.ctx2d){this.ctx2d.save(),this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0);let n=super.draw2d(t,e,r,o,s);return this.ctx2d.restore(),n}return!1}render(t){var e;return(e=this.input)!=null&&e.requestFrame(t)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}};var up=class{constructor(t,e){this.node=t;this.layout=e;u(this,"positionBuffer")}get x(){return this.layout.x||this.node.x}get y(){return this.layout.y||this.node.y}get width(){return this.layout.width||this.node.width}get height(){return this.layout.height||this.node.height}get right(){return this.x+this.width}get bottom(){return this.y+this.height}},nu=class extends Bt{constructor(e,r){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:r});u(this,"inputs",[])}addInput(e,r){if(this.inputs[r.zIndex])throw new Error("input already exists");let o=new up(e,r);this.inputs[r.zIndex]=o}resize(e,r){let o=this.inputs.reduce((s,n)=>n?Object.assign(s,{width:Math.max(s.width,n.right),height:Math.max(s.height,n.bottom)}):s,{width:0,height:0});super.resize(o.width,o.height),this.context instanceof Et&&this.inputs.forEach(s=>{if(s){let n=this.layout2texCoords(s);s.positionBuffer?this.changeBufferData(s.positionBuffer,n):s.positionBuffer=this.createBuffer(n)}})}connect(e,...r){return super.connect(e,...r),this.resize(0,0),e}removeInput(e){this.inputs[this.inputs.findIndex(r=>(r==null?void 0:r.node)===e)]=void 0}render(e){let r=this.context.ctx;if(r.clearColor(0,0,0,0),!this.inputs.reduce((s,n)=>(!n||!n.node.requestFrame(e))&&s,!0)&&r){this.useProgram(),r.enable(r.BLEND),r.blendFunc(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let s=0;s<this.inputs.length;s++){let n=this.inputs[s];n&&(n.node.useTexture(),this.draw(n.positionBuffer))}return!0}return!1}render2d(e){if(!this.inputs.reduce((o,s)=>(!s||!s.node.requestFrame(e))&&o,!0)&&this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height);for(let o=0;o<this.inputs.length;o++){let s=this.inputs[o];s&&this.draw2d(s.node.image,s.x,s.y,s.width,s.height)}return!0}return!1}getInfo(){let{totalFrames:e,x:r,y:o,width:s,height:n,name:d}=this,p=Date.now(),m=(e-this.lastInfo.totalFrames)/((p-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:r,y:o,width:s,height:n,timestamp:p,fps:m,name:d},ee({parent:this.inputs.filter(g=>g).map(g=>g.node.getInfo())},this.lastInfo)}close(){super.close(),this.inputs.forEach(e=>{var r,o;if(e&&((r=e.node)==null||r.disconnect(),e.positionBuffer&&this.context instanceof Et))try{(o=this.context.ctx)==null||o.deleteBuffer(e.positionBuffer)}catch(s){}})}};var oS=`#version 300 es
100
+ 2. If the user is in Chrome 70 and below, when the div container is moved, the playback will be paused.`,color:"orange",class:"orange",textColor:"#fff"},'"displaySurface":"window"':{tips:"Screen sharing captures the application window",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"monitor"':{tips:"Screen sharing captures the entire screen",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"browser"':{tips:"Screen sharing captures a certain tab page",color:"blue",class:"blue",textColor:"#fff"},updateMediaSettings:{tips:"The resolution and frame rate below are the actual resolution and frame rate captured",color:"blue",class:"blue",textColor:"#fff"},"main stream start to play with":{tips:"Call remoteStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"stream start to play with":{tips:"Call localStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"main setAudioVolume to 0":{tips:"Business side calls remoteStream.setAudioVolume(0) interface to set the playback volume to 0, which will cause the playback to be silent",color:"orange",class:"orange",textColor:"#fff"},"screen sharing was stopped because the video track is ended":{tips:"Screen sharing capture stopped, possible reasons: user clicks the stop button, the window/page shared by the user is closed, etc.",color:"orange",class:"orange",textColor:"#fff"},"Join() => joining room":{tips:"Call client.join interface",color:"blue",class:"blue",textColor:"#fff"},"publish() => publishing local stream":{tips:"Call client.publish interface",color:"blue",class:"blue",textColor:"#fff"},"subscribe() => subscribe to":{tips:"Call client.subscribe interface",color:"blue",class:"blue",textColor:"#fff"},"switchRole() => switch role":{tips:"Call client.switchRole interface",color:"blue",class:"blue",textColor:"#fff"}};["enterRoom","exitRoom","switchRole","destroy","startLocalAudio","updateLocalAudio","stopLocalAudio","startLocalVideo","updateLocalVideo","stopLocalVideo","startScreenShare","updateScreenShare","stopScreenShare","startRemoteVideo","updateRemoteVideo","stopRemoteVideo","muteRemoteAudio","setRemoteAudioVolume"].forEach(i=>{cg[`${i}()`]={tips:`Call trtc.${i}`,color:"blue",class:"blue",textColor:"#fff"}});var oP=Object.keys(cg);var YI=0,Kd,Ys=class Ys{constructor(t){this.core=t;u(this,"_core");u(this,"log");u(this,"dumpLocalVideoMap",{});u(this,"dumpRemoteVideoMap",{});u(this,"dialog");this._core=t,this.log=t.log.createChild({id:`${this.getAlias()}${++YI}`}),this.log.info("created")}getName(){return Ys.Name}getAlias(){return"dm"}getGroup(){return"dm"}getValidateRule(t){switch(t){case"start":return{name:"StartDebugOptions",required:!1};case"update":return{name:"UpdateDebugOptions",required:!1};case"stop":return{name:"StopDebugOptions",required:!1}}}start(){return y(this,null,function*(){var e;!new URLSearchParams(location.search).has("trtcDebug")&&((e=window.sessionStorage)==null?void 0:e.getItem("TRTC_ENABLE_DEBUG_PLUGIN"))!=="true"||(yield this.openDebugDiaLog(),this.addVideoProcessor())})}update(){}stop(){this.closeDebugDiaLog(),this.removeVideoProcessor()}destroy(){this.stop()}openDebugDiaLog(){return y(this,null,function*(){var t;try{if(Kd)yield Kd;else{let e=Date.now(),r=new URLSearchParams(location.search).get("trtcDebugDialogPath")||((t=window.sessionStorage)==null?void 0:t.getItem("TRTC_DEBUG_DIALOG_PATH"))||`https://unpkg.com/${sg}@${rt}/assets/debug-dialog.js`;Kd=this.loadScript(r),yield Kd,this.log.info(`download debug dialog script cost: ${Date.now()-e}ms`)}this.dialog=new TRTCDebugDialog(this._core,this.log,this.dumpLocalVideoMap,this.dumpRemoteVideoMap),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(e){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(e))}})}closeDebugDiaLog(){var t;(t=this.dialog)==null||t.closeDialog(),this.dialog=null}addVideoProcessor(){this._core.room.videoManager.addEncodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.encodeVideo.bind(this):ip,type:1}),this._core.room.videoManager.addDecodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.decodeVideo.bind(this):op,type:1})}removeVideoProcessor(){this._core.room.videoManager.removeEncodeProcessor({type:1}),this._core.room.videoManager.removeDecodeProcessor({type:1})}encodeVideo({frame:t,mediaType:e}){return ip({frame:t,onDump:()=>{if(!e)return;let r=e===2?"sub":"main",o=this.dumpLocalVideoMap[r];o&&(o.data.push(t.data),o.duration>0&&Date.now()-o.startTimestamp>o.duration*1e3&&o.onDumpEnd())}})}decodeVideo({frame:t,track:e}){return op({frame:t,onDump:()=>{if(!e)return;let r=this.dumpRemoteVideoMap[`${e.userId}-${e.streamType}`];r&&(r.data.push(t.data),r.duration>0&&Date.now()-r.startTimestamp>r.duration*1e3&&r.onDumpEnd())}})}loadScript(t){return new Promise((e,r)=>{this.log.info(`loading debug dialog from ${t}`);let o=document.createElement("script");o.type="text/javascript",o.onload=e,o.onerror=r,o.crossOrigin="anonymous",o.src=t,document.head.append?document.head.append(o):document.getElementsByTagName("head")[0].appendChild(o)})}};u(Ys,"Name","Debug"),u(Ys,"autoStart",!0),X([Hi({settings:{timeout:3e3,retries:3},onError(t,e,r){var o;(o=t==null?void 0:t.message)!=null&&o.includes("timeout")?e():r(t)}})],Ys.prototype,"loadScript",1);var eu=Ys;var dg=i=>{switch(i){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},tu=class{constructor(t,e,r){u(this,"trackDoneOB");u(this,"startOB");u(this,"stopOB");u(this,"inputFrameCount",0);u(this,"decodedFrameCount",0);u(this,"type","auto");u(this,"config");u(this,"decoder");u(this,"_decodeSink");let{kvStatManager:o,trtc:s}=t;this.config=r.config,this.trackDoneOB=be(e,ne.INIT),this.stopOB=It(this.trackDoneOB),this.startOB=It(),r.type==="auto"?this.type="webCodecs":this.type=r.type;let n=It(),d=p=>{let m=this.pipe(e);return n.next("STARTING"),e.log.info(`decoder type: ${this.type}`),Se(m,Je(this.stopOB),ke(()=>{},g=>{e.log.error(g),o.addFailedEvent({key:dg(this.type),error:g}),p>4?this.startOB.error(g):this.startOB.next(p+1)})),Se(m,Ar(1),xm(Ia))};Se(this.startOB,_a(0),zi(d),Je(this.stopOB),ke(()=>{e.player.setOutput(),n.next("STARTED")},p=>{n.next("FAILED")},()=>{o.addSuccessEvent({key:dg(this.type)}),o.addSuccessEvent({key:504702})}))}mock(t){this._decodeSink?this._decodeSink.error(t):this.startOB.next(0)}close(t){this.stopOB.next(t)}pipe(t){return li()(e=>y(this,null,function*(){this._decodeSink=e,e.defer(()=>{var o;(o=this.decoder)==null||o.close()});let{type:r}=this;try{switch(r){case"webCodecs":this.decoder=new AudioDecoder({error:o=>{t.log.error(o),e.error(4)},output:o=>{this.decodedFrameCount++,e.next(o),t.player.write(o)}});break;case"wasm":break}this.decoder.configure(this.config)}catch(o){t.log.error(o),e.error(r==="webCodecs"?2:6)}}))}decodeFrame(t){var e;this.inputFrameCount++,((e=this.decoder)==null?void 0:e.state)==="configured"&&this.decoder.decode(new EncodedAudioChunk({data:t.data,timestamp:t.timestamp,type:"key"}))}},ZI={type:"object"},wa=class wa{constructor(t){this.core=t;u(this,"log");u(this,"contextMap",new Map);u(this,"decodeProcessorMap",new WeakMap);this.log=t.log.createChild({id:`${this.getAlias()}`})}getAlias(){return wa.Name}getGroup(t){return t.track.userId+t.track.streamType}getName(){return wa.Name}getValidateRule(t){return ZI}start(t){let{track:e}=t;this.decodeProcessorMap.set(e,this.decode(t)),this.core.room.audioManager.addDecodeProcessor({processor:({frame:r,track:o})=>this.decodeProcessorMap.has(o)?this.decodeProcessorMap.get(o)({frame:r,track:o}):r,type:3})}decode(t){return({frame:e,track:r})=>{if(r!==t.track)return e;if(this.contextMap.has(r))return this.contextMap.get(r).decodeFrame(e);let o=new tu(this.core,r,t);return Se(o.trackDoneOB,Ar(1),ke(()=>{this.core.clearStarted(this,this.getGroup(t)),this.stop({track:r})})),this.contextMap.set(r,o),o.decodeFrame(e)}}stop({track:t}){let e=this.contextMap.get(t);e&&(e.close("stop"),this.contextMap.delete(t),this.contextMap.size===0&&this.core.room.audioManager.removeDecodeProcessor({type:3}))}update(t){let e=this.contextMap.get(t.track);if(e){if(t.type==="mock"){e.mock(10);return}e.close("update"),this.contextMap.set(t.track,new tu(this.core,t.track,t))}}};u(wa,"Name","TRTCAudioDecoder");var Ma=wa;var ug=0,Oa=new Set,Rt=null;Ou(ng);Ms.checkStorage();xl();var KI={RtcError:ae,ErrorCode:ue,ErrorCodeDictionary:Rr},fe=class fe extends lg.EventEmitter{constructor(e,r){super();u(this,"_room");u(this,"_eventListened",new Set);u(this,"_localVideoTrack",null);u(this,"_localAudioTrack",null);u(this,"_localScreenTrack",null);u(this,"_localScreenAudioTrack",null);u(this,"_localVideoConfig",null);u(this,"_localScreenConfig",null);u(this,"_localAudioConfig",null);u(this,"_remoteVideoConfigMap",new Map);u(this,"_remoteAudioConfigMap",new Map);u(this,"_remoteAudioVolumeMap",new Map);u(this,"_remoteAudioMuteMap",new Map);u(this,"_mediaTrackMap",new WeakMap);u(this,"_log",$.createLogger({id:`t${++ug}`}));u(this,"_plugins",new Map);u(this,"_networkQuality",null);u(this,"_speakerId");u(this,"_getPCMAbortCtrl");this._room=new e(ee({logger:this._log,frameWorkType:fe.frameWorkType},r)),this._room.videoDecodeFallbackType=r.videoDecodeFallback,this._log.info(`create() ${JSON.stringify(r,(o,s)=>o==="plugins"?s.map(n=>n.Name):s)}`),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(o){return this._room.audioManager.dump(o)}}}),r.plugins&&r.plugins.forEach(o=>{this._use(o,r.assetsPath)}),this._use(Xd,r.assetsPath),this._use(Yd,r.assetsPath),this._use(Ma,r.assetsPath||nc),this._use(eu),r.enableSEI&&sa&&this._use(Zd),this._room.on("audio-volume",o=>{!o.find(s=>s.userId==="")&&this._localAudioTrack&&o.push({userId:"",volume:Math.floor(this._localAudioTrack.getAudioLevel()*100)}),r.volumeType===1&&o.forEach(s=>{var d;let n=s.userId===""?this._localAudioTrack:(d=this.room.remotePublishedUserMap.get(s.userId))==null?void 0:d.remoteAudioTrack;n&&(s.volume=n.dbVolume)}),this.emit(se.AUDIO_VOLUME,{result:o.sort((s,n)=>n.volume-s.volume)})}),this._room.videoManager.on("error",o=>{this._log.error(new ae({code:ue.OPERATION_FAILED,extraCode:5504,message:o.message,originError:o}))}),this._listenEvents(),this._initActiveSpeaker(),tg(this,"trtc")}static create(e){}static _create(e,r){Bf();let o=new fe(e,r||{});return Oa.add(o),o}get room(){return this._room}_listenEvents(){xt(this,this._room).add("peer-join",e=>{let{userId:r}=e;this.emit(se.REMOTE_USER_ENTER,{userId:r})}).add("peer-leave",e=>{this.emit(se.REMOTE_USER_EXIT,{userId:e}),this._remoteAudioVolumeMap.delete(e)}).add("banned",e=>{this._exitRoom().finally(()=>{this.emit(se.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().finally(()=>{this.emit(se.ERROR,ae.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(se.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let r=Ee(ee({},e),{uplinkRTT:Math.min(e.uplinkRTT,bn),downlinkRTT:Math.min(e.downlinkRTT,bn)});this.emit(se.NETWORK_QUALITY,r)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(o=>{xt(o,o).add("player-state-changed",s=>{let n=Ee(ee({},s),{userId:e.userId});o.kind===D.VIDEO&&(n.streamType=eo(o.streamType)),this.emit(o.kind===D.AUDIO?se.AUDIO_PLAY_STATE_CHANGED:se.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",s=>{s.getCode()===te.PLAY_NOT_ALLOWED&&this.emit(se.AUTOPLAY_FAILED,{userId:o.userId,resume:()=>o.player.resume()})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(o=>{mt(o)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:r})=>{let{userId:o}=r,s=e.audioAvailable,n=e.videoAvailable,{audioAvailable:d,videoAvailable:p}=r;d||this._remoteAudioConfigMap.delete(o),p||this._remoteVideoConfigMap.delete(`${o}_main`),r.hasAuxiliary||this._remoteVideoConfigMap.delete(`${o}_sub`),n!==p&&(p?this._onVideoAvailable({userId:o,streamType:"main"}):this._onVideoUnavailable({userId:o,streamType:"main"}),this.emit(p?se.REMOTE_VIDEO_AVAILABLE:se.REMOTE_VIDEO_UNAVAILABLE,{userId:o,streamType:"main"})),s!==d&&(d?this._onAudioAvailable({userId:o}):this._onAudioUnavailable({userId:o,muteState:r}),this.emit(d?se.REMOTE_AUDIO_AVAILABLE:se.REMOTE_AUDIO_UNAVAILABLE,{userId:o})),e.hasAuxiliary!==r.hasAuxiliary&&(r.hasAuxiliary?this._onVideoAvailable({userId:o,streamType:"sub"}):this._onVideoUnavailable({userId:o,streamType:"sub"}),this.emit(r.hasAuxiliary?se.REMOTE_VIDEO_AVAILABLE:se.REMOTE_VIDEO_UNAVAILABLE,{userId:o,streamType:"sub"}))}).add("sei-message",e=>{this.emit(se.SEI_MESSAGE,Ee(ee({},e),{streamType:eo(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(se.ERROR,new ae({code:ue.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var s,n,d,p,m,g,_;let r={2:"big",3:"small",7:"sub"},o={rtt:Math.min(e.msg_up_stream_info.msg_network_status.uint32_rtt||((s=e.msg_down_stream_info[0])==null?void 0:s.msg_network_status.uint32_rtt)||((n=this._networkQuality)==null?void 0:n.uplinkRTT)||((d=this._networkQuality)==null?void 0:d.downlinkRTT)||0,bn),upLoss:((p=this._networkQuality)==null?void 0:p.uplinkLoss)||0,downLoss:((m=this._networkQuality)==null?void 0:m.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((g=e.msg_up_stream_info.msg_audio_status)==null?void 0:g.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((_=e.msg_up_stream_info.msg_audio_status)==null?void 0:_.uint32_audio_level)||0)/oi},video:e.msg_up_stream_info.msg_video_status.filter(b=>r[b.uint32_video_stream_type]).map(b=>({bitrate:(b.uint32_video_codec_bitrate||0)/1e3,width:b.uint32_video_width,height:b.uint32_video_height,frameRate:b.uint32_video_enc_fps,videoType:r[b.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(b=>({userId:b.msg_user_info.str_identifier,audio:{bitrate:(b.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(b.msg_audio_status.uint32_audio_level||0)/oi},video:b.msg_video_status.map(N=>({bitrate:(N.uint32_video_codec_bitrate||0)/1e3,width:N.uint32_video_width,height:N.uint32_video_height,frameRate:N.uint32_video_dec_fps,videoType:r[N.uint32_video_stream_type]}))}))};this.emit(se.STATISTICS,o)}).add("custom-message",e=>{this.emit(se.CUSTOM_MESSAGE,e)}).add("layerData",e=>this.emit(se.LAYER_DATA,e)).add("first-video-frame",e=>{this.emit(se.FIRST_VIDEO_FRAME,Ee(ee({},e),{streamType:eo(e.streamType)}))}),xt(this,Tt).add("audioInputAdded",e=>{this.emit(se.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(se.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(se.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(se.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>y(this,null,function*(){if(this.emit(se.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Rt&&Rt.deviceId===An){let r=(yield Wi()).find(o=>o.deviceId===An);r&&Rt.groupId!==r.groupId&&(Rt=r,this.emit(se.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}))}})).add("audioOutputRemoved",e=>y(this,null,function*(){this.emit(se.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let r=(yield Wi())[0];if(!r||!Rt||Rt.groupId===r.groupId)return;let o=Rt.deviceId===e.deviceId,s=Rt.deviceId===An&&Rt.deviceId===r.deviceId;(o||s)&&(Rt=r,this.emit(se.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}))}))}use(e){let r,o;"plugin"in e?(r=e.plugin,o=e.assetsPath):r=e,this._use(r,o||nc)}_use(e,r){if(this._plugins.get(e.Name)){this._log.warn("duplicate install plugin",e.Name);return}let s=new e(eg.call(this,{TRTC:fe,room:this._room,errorModule:KI,assetsPath:r}));this._plugins.set(e.Name,s),e.autoStart&&this.startPlugin(e.Name)}enterRoom(e){return y(this,null,function*(){var p,m;let{scene:r="rtc",enableAutoPlayDialog:o=!0,autoReceiveAudio:s=!0,autoReceiveVideo:n=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!we(e.proxy)&&e.proxy.turnServer&&((m=(p=this._room).setTurnServer)==null||m.call(p,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=o,this._room.autoReceiveAudio=s,this._room.autoReceiveVideo=n,nt(e.preferHW)&&(this._room.preferHW=e.preferHW),e.playoutDelay&&(this._room.playoutDelay=e.playoutDelay),e.jitterBufferDelay&&(this._room.jitterBufferDelay=e.jitterBufferDelay);let d={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:e.role==="audience"?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language,priority:e.priority,useVp8:e.useVp8,keepAlive:e.keepAlive};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(d,r,fe.frameWorkType),this._checkTrackToPublish(),Km.start()})}exitRoom(){return y(this,null,function*(){return yield this._exitRoom()})}switchRole(e,r){return y(this,null,function*(){r!=null&&r.privateMapKey&&(this._room.privateMapKey=r.privateMapKey),r!=null&&r.latencyLevel&&(this._room.latencyLevel=r.latencyLevel),yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){mt(this),this.removeAllListeners(),this._room.destroy(),Oa.delete(this),Oa.size===0&&Km.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),this._plugins.forEach(e=>{var r;return(r=e.destroy)==null?void 0:r.call(e)}),this._plugins.clear(),H.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return y(this,arguments,function*(e={publish:!0}){if(this._localAudioTrack){this._log.warn("local audio is already started");return}let{publish:r=!0,mute:o,option:s}=e,n=new ui(this._room.audioManager),d={},p={muted:!0};s&&(V(s.microphoneId)?V(s.audioTrack)||(d.customSource=s.audioTrack):d.deviceId=s.microphoneId,s&&je(s.captureVolume)&&n.setCaptureVolume(s.captureVolume),V(s.profile)||(we(s.profile)?cc[s.profile]&&n.setProfile(cc[s.profile]):n.setProfile(s.profile)),je(s.earMonitorVolume)&&(p.muted=!(s.earMonitorVolume>0),p.volume=s.earMonitorVolume),V(s.echoCancellation)||(n.profile.echoCancellation=s.echoCancellation),V(s.noiseSuppression)||(n.profile.noiseSuppression=s.noiseSuppression),V(s.autoGainControl)||(n.profile.autoGainControl=s.autoGainControl)),n.on("5",m=>{this.emit(se.ERROR,new ae({code:ue.DEVICE_ERROR,extraCode:5309,messageParams:{error:m}}))}),n.on("2",m=>{this.emit(se.DEVICE_CHANGED,{type:"microphone",action:"active",device:m})}),n.on("4",m=>{let g;m.error&&(g=ae.convertFrom(m.error)),this.emit(se.PUBLISH_STATE_CHANGED,Ee(ee({},m),{error:g}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId),yield n.capture(d),V(o)||n.setMute(o),xt(n,n).add("player-state-changed",m=>{this.emit(se.AUDIO_PLAY_STATE_CHANGED,Ee(ee({},m),{userId:""}))}),this.listeners(se.AUDIO_FRAME).length>0&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM(m=>{this.emit(fe.EVENT.AUDIO_FRAME,{data:m})})),this._getPCMAbortCtrl&&n.on("input-media-track-changed",()=>{this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("inputMediaTrackChanged"),this._getPCMAbortCtrl=this._room.audioManager.getPCM(m=>{this.emit(fe.EVENT.AUDIO_FRAME,{data:m})}))}),r&&this._room.isJoined&&this._room.publish(n).catch(()=>{}),this._localAudioTrack=n,this._localAudioConfig=Ee(ee({},e),{publish:r}),yield this._updateAudioPlayOption({playOption:p,track:n})})}updateLocalAudio(e){return y(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:r,mute:o,option:s}=e,n={};s&&(s.microphoneId?yield this._localAudioTrack.switchDevice(s.microphoneId):V(s.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(s.audioTrack)),V(s.captureVolume)||this._localAudioTrack.setCaptureVolume(s.captureVolume),V(s.earMonitorVolume)||(n.muted=!(s.earMonitorVolume>0),n.volume=s.earMonitorVolume),yield this._localAudioTrack.update3A(s)),this._room.isJoined&&!V(r)&&(r&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!r&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),V(o)||this._localAudioTrack.setMute(o),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),kr(this._localAudioConfig,e)})}stopLocalAudio(){return y(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),mt(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null,this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("stopLocalAudio"),delete this._getPCMAbortCtrl))})}startLocalVideo(){return y(this,arguments,function*(e={publish:!0,view:null}){if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:r,publish:o=!0,mute:s,option:n}=e,d=new Sr(this._room.videoManager),p={},m={};nt(n==null?void 0:n.avoidCropping)&&(d.avoidCropping=n.avoidCropping),n&&(n.cameraId?p.deviceId=n.cameraId:V(n.useFrontCamera)?V(n.videoTrack)||(p.customSource=n.videoTrack):p.facingMode=n.useFrontCamera?D.FACING_MODE_USER:D.FACING_MODE_ENVIRONMENT,n.qosPreference&&(p.contentHint=Da(n.qosPreference)),V(n.profile)||(we(n.profile)?Or[n.profile]&&d.setProfile(Or[n.profile]):d.setProfile(n.profile)),V(n.fillMode)||(m.objectFit=n.fillMode),V(n.mirror)||(m.mirror=n.mirror),V(n.small)||(ra()?we(n.small)?d.small=Or[n.small]:n.small===!0?d.small=Or["120p"]:d.small=n.small:this._log.warn("small stream is not supported"))),d.once("first-video-frame",g=>{this.emit(se.FIRST_VIDEO_FRAME,Ee(ee({},g),{streamType:eo(g.streamType)}))}),d.on("5",g=>{this.emit(se.ERROR,new ae({code:ue.DEVICE_ERROR,extraCode:5308,messageParams:{error:g}}))}),d.on("2",g=>{this.emit(se.DEVICE_CHANGED,{type:"camera",action:"active",device:g})}),d.on("4",g=>{let _;g.error&&(_=ae.convertFrom(g.error)),this.emit(se.PUBLISH_STATE_CHANGED,Ee(ee({},g),{error:_}))}),this._listenOutputTrackChanged(d),yield d.capture(p),V(s)||(yield d.setMute(s)),xt(d,d).add("player-state-changed",g=>{this.emit(se.VIDEO_PLAY_STATE_CHANGED,Ee(ee({},g),{userId:"",streamType:"main"}))}),o&&this._room.isJoined&&this._room.publish(d).catch(()=>{}),this._localVideoTrack=d,this._localVideoConfig=Ee(ee({},e),{view:r,publish:o}),yield this._updateVideoPlayOption({view:r,playOption:m,track:d})})}updateLocalVideo(e){return y(this,null,function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:r,publish:o,mute:s,option:n}=e,d={};if(n)if(V(n.profile)||(we(n.profile)?Or[n.profile]&&this._localVideoTrack.setProfile(Or[n.profile]):this._localVideoTrack.setProfile(n.profile),(!n.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(n.cameraId))&&V(n.useFrontCamera)&&this._localVideoTrack.applyProfile()),n.cameraId?yield this._localVideoTrack.switchDevice(n.cameraId):V(n.useFrontCamera)?V(n.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(n.videoTrack)):yield this._localVideoTrack.switchDevice(n.useFrontCamera?D.FACING_MODE_USER:D.FACING_MODE_ENVIRONMENT),V(n.fillMode)||(d.objectFit=n.fillMode),V(n.mirror)||(d.mirror=n.mirror),n.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(Da(n.qosPreference)),n.small){let p=!this._localVideoTrack.small;ra()?(n.small===!0?this._localVideoTrack.small=Or["120p"]:we(n.small)?this._localVideoTrack.small=Or[n.small]:this._localVideoTrack.small=n.small,this._room.videoManager.update(),p&&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&&!V(o)&&(o&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._localVideoConfig.publish&&!o&&this._room.unpublish(this._localVideoTrack).catch(()=>{})),V(s)||(yield this._localVideoTrack.setMute(s)),yield this._updateVideoPlayOption({view:r,playOption:d,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),kr(this._localVideoConfig,e)})}stopLocalVideo(){return y(this,null,function*(){this._localVideoTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),mt(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return y(this,arguments,function*(e={publish:!0,view:null}){if(this._localScreenTrack){this._log.warn("screen share is already started");return}let{view:r=null,publish:o=!0,option:s}=e,n=new ji(this._room.videoManager);n.on("4",_=>{let b;_.error&&(b=ae.convertFrom(_.error)),this.emit(se.PUBLISH_STATE_CHANGED,Ee(ee({},_),{error:b}))}),n.once("first-video-frame",_=>{this.emit(se.FIRST_VIDEO_FRAME,Ee(ee({},_),{streamType:eo(_.streamType)}))}),this._listenOutputTrackChanged(n),e.streamType==="main"&&(n.mediaType=4);let d=null,p={},m={};s&&(V(s.profile)||(we(s.profile)?dc[s.profile]&&n.setProfile(dc[s.profile]):n.setProfile(s.profile)),s.systemAudio&&(p.systemAudio=!0,p.echoCancellation=s.echoCancellation,p.noiseSuppression=s.noiseSuppression,p.autoGainControl=s.autoGainControl),V(s.fillMode)||(m.objectFit=s.fillMode),s.videoTrack&&(p.videoTrack=s.videoTrack),s.audioTrack&&(p.audioTrack=s.audioTrack),s.captureElement&&(p.captureElement=s.captureElement),s.preferDisplaySurface&&(p.preferDisplaySurface=s.preferDisplaySurface),s.qosPreference&&(p.contentHint=Da(s.qosPreference)));let g=yield n.capture(p);if(n.mediaTrack.addEventListener(D.ENDED,()=>{this._stopScreenShare(),this.emit(se.SCREEN_SHARE_STOPPED)}),g.getAudioTracks()[0]&&(d=new Fo(this._room.audioManager),yield d.setInputMediaStreamTrack(g.getAudioTracks()[0]),this._speakerId&&d.setAudioOutput(this._speakerId)),xt(n,n).add("player-state-changed",_=>{this.emit(se.VIDEO_PLAY_STATE_CHANGED,Ee(ee({},_),{userId:"",streamType:"sub"}))}),o&&this._room.isJoined){let _=[n];d&&_.push(d),this._room.publish(..._).catch(()=>{})}this._localScreenTrack=n,this._localScreenAudioTrack=d,this._localScreenConfig=Ee(ee({},e),{view:r,publish:o}),yield this._updateVideoPlayOption({view:r,playOption:m,track:n})})}updateScreenShare(e){return y(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:r,publish:o,option:s}=e,n={};if(s&&(V(s.fillMode)||(n.objectFit=s.fillMode),s.qosPreference)){let d=Da(s.qosPreference);this._localScreenTrack.setContentHint(d)}this._room.isJoined&&!V(o)&&(o&&!this._localScreenConfig.publish&&(this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch(()=>{})),this._localScreenConfig.publish&&!o&&(this._room.unpublish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.unpublish(this._localScreenAudioTrack).catch(()=>{}))),yield this._updateVideoPlayOption({view:r,playOption:n,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),kr(this._localScreenConfig,e)})}stopScreenShare(){return y(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return y(this,null,function*(){let{view:r,userId:o,streamType:s,option:n}=e,d=`${o}_${s}`;if(this._remoteVideoConfigMap.has(d)){this._log.warn(`remote video has already started. userId:${o}, streamType:${s}`);return}let p=this._room.remotePublishedUserMap.get(o);if(!p)return;let m={},g=s==="main"?p.remoteVideoTrack:p.remoteAuxiliaryTrack;this._listenOutputTrackChanged(g),n&&(V(n.fillMode)||(m.objectFit=n.fillMode),V(n.mirror)||(m.mirror=n.mirror),V(n.poster)||(m.poster=n.poster),m.canvasRender=n.canvasRender,s==="main"&&!V(n.small)&&(!p.remoteVideoTrack.isSubscribing&&!p.remoteVideoTrack.isSubscribed&&p.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,g.user))),yield this._room.subscribe(g),yield this._enableVideoDecodeFallback(g,s),yield this._updateVideoPlayOption({view:r,playOption:m,track:g}),this._emitTrackEvent(g),this._remoteVideoConfigMap.set(d,{config:e}),n&&!V(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:g,view:r,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:n==null?void 0:n.viewRoot})})}updateRemoteVideo(e){return y(this,null,function*(){var x,J;let{view:r,userId:o,streamType:s,option:n}=e,d=`${o}_${s}`,p=this._remoteVideoConfigMap.get(d);if(!p||!this._room.remotePublishedUserMap.has(o))return;let m={};n&&(V(n.fillMode)||(m.objectFit=n.fillMode),V(n.mirror)||(m.mirror=n.mirror));let g=null,_=this._room.remotePublishedUserMap.get(o);if(s==="main"&&(_!=null&&_.muteState.hasVideo)&&(g=_.remoteVideoTrack),s==="sub"&&(_!=null&&_.muteState.hasAuxiliary)&&(g=_.remoteAuxiliaryTrack),!g)return;let{config:b}=p;s==="main"&&n&&!V(n.small)&&this._room.changeType(n.small,g.user),yield this._updateVideoPlayOption({view:r,playOption:m,track:g,prevConfig:b}),kr(b,e);let N=V(n==null?void 0:n.receiveWhenViewVisible)?(x=b.option)==null?void 0:x.receiveWhenViewVisible:n.receiveWhenViewVisible,k=V(r)?b.view:r,P=V(n==null?void 0:n.viewRoot)?(J=b.option)==null?void 0:J.viewRoot:n.viewRoot;this._observeView({remoteTrack:g,view:k,receiveWhenViewVisible:N,viewRoot:P})})}stopRemoteVideo(e){return y(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,r=!0){return y(this,null,function*(){let o=[],s=this._room.remotePublishedUserMap.get(e.userId);if(s){let{muteState:d,remoteVideoTrack:p,remoteAuxiliaryTrack:m}=s;e.streamType==="main"&&(p.stop(),d.hasVideo&&o.push(p)),e.streamType==="sub"&&(m.stop(),d.hasAuxiliary&&o.push(m))}for(let d of o)r&&(yield this._room.unsubscribe(d),this._mediaTrackMap.delete(d.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,r){return y(this,null,function*(){this._remoteAudioMuteMap.set(e,r);try{if(e==="*")if(r)yield this._stopRemoteAudio({userId:e});else{let o=[...this._room.remotePublishedUserMap.values()];for(let s of o)s.muteState.hasAudio&&!this._remoteAudioConfigMap.has(s.userId)&&(yield this._startRemoteAudio({userId:s.userId}))}else r?yield this._stopRemoteAudio({userId:e}):this._remoteAudioConfigMap.has(e)||(yield this._startRemoteAudio({userId:e}))}catch(o){throw this._remoteAudioMuteMap.delete(e),o}})}setRemoteAudioVolume(e,r){if(e==="*"){let o=[...this._room.remotePublishedUserMap.values()];for(let s of o)this._remoteAudioVolumeMap.set(s.userId,r),s.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:r},track:s.remoteAudioTrack})}else if(e){let o=this._room.remotePublishedUserMap.get(e);this._remoteAudioVolumeMap.set(e,r),o&&o.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:r},track:o.remoteAudioTrack})}}startPlugin(e,r){return y(this,null,function*(){return e.start(r)})}updatePlugin(e,r){return y(this,null,function*(){return e.update(r)})}stopPlugin(e,r){return y(this,null,function*(){return e.stop(r)})}enableAudioVolumeEvaluation(e=2e3,r=!1){this._room.enableAudioVolumeEvaluation(e,r)}on(e,r,o){return this.listeners(e).includes(r)?this:(this._log.debug("on",e),super.on(e,r,o),this._eventListened.add(e),e===fe.EVENT.AUDIO_FRAME&&!this._getPCMAbortCtrl&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM(s=>{this.emit(fe.EVENT.AUDIO_FRAME,{data:s})}),this._localAudioTrack&&this._localAudioTrack.on("input-media-track-changed",()=>{this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("inputMediaTrackChanged"),this._getPCMAbortCtrl=this._room.audioManager.getPCM(s=>{this.emit(fe.EVENT.AUDIO_FRAME,{data:s})}))})),this)}emit(e,...r){try{Xf.has(e)&&this._log.debug(`emit ${e} ${JSON.stringify(r)}`)}catch(o){}return super.emit(e,...r)}off(e,r,o){var s,n;return this._log.debug("off",e),e==="*"?(this._eventListened.clear(),this.removeAllListeners(),(s=this._getPCMAbortCtrl)==null||s.abort("off"),delete this._getPCMAbortCtrl):(super.off(e,r,o),e===fe.EVENT.AUDIO_FRAME&&((n=this._getPCMAbortCtrl)==null||n.abort("off"),delete this._getPCMAbortCtrl)),this}getAudioTrack(e={userId:"",streamType:"main"}){let r,o=null,s="main",n=!1;if(we(e)?r=e:(r=e.userId,n=e.processed===!0,e.streamType&&(s=e.streamType)),r){let d=this._room.remotePublishedUserMap.get(r);d&&(o=d.remoteAudioTrack)}else o=s==="sub"?this._localScreenAudioTrack:this._localAudioTrack;return o?n&&o.outMediaTrack&&o.outMediaTrack!==o.mediaTrack?o.outMediaTrack.clone():o.mediaTrack:null}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:r="",streamType:o="main",processed:s=!1}=e,n=null;if(r==="")o==="main"&&this._localVideoTrack&&(n=this._localVideoTrack),o==="sub"&&this._localScreenTrack&&(n=this._localScreenTrack);else{let d=this._room.remotePublishedUserMap.get(r);d&&(n=o==="main"?d.remoteVideoTrack:d.remoteAuxiliaryTrack)}return n?s&&n.outMediaTrack&&n.outMediaTrack!==n.mediaTrack?n.outMediaTrack.clone():n.mediaTrack:null}getVideoSnapshot(e={}){let{userId:r,streamType:o="main"}=e;if(r){let s=this._room.remotePublishedUserMap.get(r);if(o==="main"&&(s!=null&&s.muteState.hasVideo))return s.remoteVideoTrack.getVideoFrame();if(o==="sub"&&(s!=null&&s.muteState.hasAuxiliary))return s.remoteAuxiliaryTrack.getVideoFrame()}else{if(o==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(o==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(e){var r,o;this._speakerId=e,(r=this._localAudioTrack)==null||r.setAudioOutput(e),(o=this._localScreenAudioTrack)==null||o.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(s=>s.remoteAudioTrack.setAudioOutput(e))}setCurrentSpeaker(e){return y(this,null,function*(){(yield Wi()).forEach(o=>{o.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(se.DEVICE_CHANGED,{type:"speaker",action:"active",device:o}),Rt=o)}),this._log.warn('the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: https://web.sdk.qcloud.com/trtc/webrtc/v5/doc/en/TRTC.html#.setCurrentSpeaker')})}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return y(this,null,function*(){let{userId:r}=e;if(this._remoteAudioConfigMap.has(r)){this._log.warn(`remote audio has already started. userId:${r}`);return}let o=this._room.remotePublishedUserMap.get(r);if(!o)return;let s={},n=o.remoteAudioTrack;this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId);try{let d=this._remoteAudioVolumeMap.get(r),p=je(d)?d:100;s.volume=p,this._remoteAudioConfigMap.set(r,e),yield this._room.subscribe(n),Se(be(n,"decode-failed"),Je(be(n,ne.INIT)),ke(()=>{this.startPlugin(Ma.Name,{track:n,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:s,track:n})}catch(d){throw this._remoteAudioConfigMap.delete(r),d}this._emitTrackEvent(n)})}_stopRemoteAudio(e,r=!0){return y(this,null,function*(){let o=this._room.remotePublishedUserMap.get(e.userId);o&&(o.remoteAudioTrack.stop(),o.muteState.hasAudio&&r&&(yield this._room.unsubscribe(o.remoteAudioTrack)),this._mediaTrackMap.delete(o.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete(`${e.userId}`)})}_enableVideoDecodeFallback(e,r){let o=this._room.videoDecodeFallbackType;if(!o||!this._plugins.has("TRTCVideoDecoder"))return;e.log.debug("remote video will fall back when decode failed",e.id);let s;Se(be(e,"decode-failed"),Je(be(e,ne.INIT)),Sa(()=>{this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:o})}),mi(be(e,"decode-downgrade-state-changed")),ke(n=>{s=n.state,this.emit(se.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,Ee(ee({},n),{streamType:r,userId:e.userId}))},n=>{e.log.error("fallback",n)},()=>{s==="STARTED"&&e.log.info("fallback complete")}))}_updateVideoPlayOption(n){return y(this,arguments,function*({view:e,playOption:r,track:o,prevConfig:s}){if(o.setMirror(r.mirror),V(e)&&s&&s.view&&!fs(r)){let d=Es(s.view);d.length>0&&(yield o.play(d,r))}if(!V(e)){let d=Es(e);d.length>0?yield o.play(d,r):o.stop()}})}_updateAudioPlayOption(s){return y(this,arguments,function*({playOption:e={},track:r,prevConfig:o}){if(!r.isPlayCalled)try{yield r.play(null,e)}catch(n){}V(e.muted)||r.setPlayerMute(e.muted),V(e.volume)||r.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,r=!0){let o=e.isRemote?e.userId:"";e.outMediaTrack&&(r&&this._mediaTrackMap.get(e.outMediaTrack)===o||(this._mediaTrackMap.set(e.outMediaTrack,o),this.emit(se.TRACK,{userId:o,streamType:eo(e.streamType),track:e.outMediaTrack,sourceTrack:e.mediaTrack})))}_checkTrackToPublish(){var r,o,s;let e=[];if((r=this._localAudioConfig)!=null&&r.publish&&this._localAudioTrack&&e.push(this._localAudioTrack),(o=this._localVideoConfig)!=null&&o.publish&&this._localVideoTrack&&e.push(this._localVideoTrack),(s=this._localScreenConfig)!=null&&s.publish&&(this._localScreenTrack&&e.push(this._localScreenTrack),this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack)),e.length!==0)return this._room.publish(...e).catch(()=>{})}_observeView({remoteTrack:e,view:r,receiveWhenViewVisible:o=!1,viewRoot:s}){if(V(r))return;let n=this._remoteVideoConfigMap.get(`${e.userId}_${eo(e.streamType)}`);if(!n)return;let d=n.observer||void 0;if(r===null||st(r)&&r.length===0||!o){d==null||d.disconnect(),e.isSubscribed||this._room.subscribe(e).catch(()=>{});return}let m=n.visibleViewMap||new Map,g=-1;(!d||d.root!==s)&&(d==null||d.disconnect(),m.clear(),d=new IntersectionObserver(b=>{b.forEach(N=>{m.set(N.target,N.isIntersecting)}),clearTimeout(g),g=window.setTimeout(()=>{let N=[...m.values()].find(k=>k);e.log.info(`view is${N?"":" not"} visible`),N?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:s}));let _=new Set(Es(r));m.forEach((b,N)=>{_.has(N)||(d.unobserve(N),m.delete(N))}),_.forEach(b=>{m.set(b,!0),d.observe(b)}),d.takeRecords().forEach(b=>{m.set(b.target,b.isIntersecting)}),n.visibleViewMap=m,n.observer=d}_exitRoom(){return y(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(e=>{this._stopRemoteAudio({userId:e}).catch()}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let r=e.includes("main")?"main":"sub",o=e.split(`_${r}`)[0];o&&this._stopRemoteVideo({userId:o,streamType:r}).catch()}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._remoteAudioVolumeMap.clear(),rg(this),this._room.remotePublishedUserMap.forEach(e=>{mt(e.remoteAudioTrack),mt(e.remoteVideoTrack),mt(e.remoteAuxiliaryTrack)})})}_stopScreenShare(){return y(this,null,function*(){var e;if(this._localScreenTrack){if(this._room.isJoined){let r=[this._localScreenTrack];this._localScreenAudioTrack&&r.push(this._localScreenAudioTrack),yield(e=this._room)==null?void 0:e.unpublish(...r).catch(()=>{})}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),mt(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_onLocalTrackCaptured({track:e}){e.kind==="audio"&&(!Rt||$s(Rt))&&(this._initActiveSpeaker(),H.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return y(this,null,function*(){if(Rt&&!$s(Rt))this.emit(se.DEVICE_CHANGED,{type:"speaker",action:"active",device:Rt});else{let e=yield Wi();e[0]&&!$s(e[0])?(Rt=e[0],this.emit(se.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):H.on("102",this._onLocalTrackCaptured,this)}})}_onAudioAvailable({userId:e}){let r=this._remoteAudioMuteMap.has(e)?this._remoteAudioMuteMap.get(e):this._remoteAudioMuteMap.get("*");(r===!1||this._room.autoReceiveAudio&&!r)&&this._doStartRemoteAudio({userId:e}).catch(()=>{})}_onVideoAvailable({userId:e,streamType:r}){if(!this._room.autoReceiveVideo)return;let o=this._room.remotePublishedUserMap.get(e);if(o){let s=r==="main"?o.remoteVideoTrack:o.remoteAuxiliaryTrack,n=[s];this._room.autoReceiveAudio&&o.remoteAudioTrack.isAvailable&&n.push(o.remoteAudioTrack),this._room.subscribe(...n).then(()=>{this._emitTrackEvent(s)}).catch(()=>{})}}_onAudioUnavailable({userId:e,muteState:r}){r.hasAudio&&r.audioMuted||this._stopRemoteAudio({userId:e},!1).catch(()=>{})}_onVideoUnavailable({userId:e,streamType:r}){this._stopRemoteVideo({userId:e,streamType:r},!1).catch(()=>{})}sendSEIMessage(e,r){var s;let o=this._plugins.get("SEI");o&&(o.update({buffer:e,options:Ee(ee({seiPayloadType:243},r),{small:!!((s=this._localVideoTrack)!=null&&s.small)})}),Y.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var r,o;(o=(r=this._room).sendCustomMessage)==null||o.call(r,e),Y.addCount({key:500001,useUV:!0})}static setLogLevel(e,r){$.setLogLevel(e),V(r)||(r?$.enableUploadLog():$.disableUploadLog())}static isSupported(){return Zc()}static getCameraList(e=!0){return er(e)}static getMicrophoneList(e=!0){return Jt(e)}static getSpeakerList(e=!0){return Wi(e)}static setCurrentSpeaker(e){return y(this,null,function*(){if(at&&(e===nr.SPEAKER||e===nr.HEADSET)){let o=yield fe.getMicrophoneList(),s="";if(o.forEach(n=>{n.label===e&&(s=n.deviceId)}),!s)return;Oa.forEach(n=>y(this,null,function*(){n._localAudioTrack&&(yield n.updateLocalAudio({option:{microphoneId:s}}))}));return}(yield Wi()).forEach(o=>{o.deviceId===e&&(Oa.forEach(s=>{s._setCurrentSpeaker(e),s.emit(se.DEVICE_CHANGED,{type:"speaker",action:"active",device:o})}),Rt=o)})})}static _addKVStat({type:e,key:r,value:o,base:s,useUV:n,version:d}){switch(d&&(Mo.version=d),e){case"count":Mo.addCount({key:r,useUV:n});break;case"enum":Mo.addEnum({key:r,value:o,useUV:n});break;case"number":Mo.addNumber({key:r,value:o,split:s});break}}};u(fe,"_loggerManager",$),u(fe,"EVENT",se),u(fe,"ERROR_CODE",ue),u(fe,"TYPE",nr),u(fe,"frameWorkType",30),X([Ye({replaceArg:e=>({argIndex:0,value:{name:"plugin"in e?e.plugin.Name:e.Name,assetsPath:"assetsPath"in e?e==null?void 0:e.assetsPath:"default"}})})],fe.prototype,"use",1),X([Ut(bt.TRTC.enterRoom),Zi("room",([e],[r])=>(e.roomId||e.strRoomId)===(r.roomId||r.strRoomId)&&e.userId===r.userId&&e.sdkAppId===r.sdkAppId),Me(e=>function(r){return this._log.setUserId(r.userId),this._log.setSdkAppId(r.sdkAppId),e.call(this,r)}),Ye()],fe.prototype,"enterRoom",1),X([Ye()],fe.prototype,"exitRoom",1),X([Ut(bt.TRTC.switchRole),Jo("room",{merge:(e,r)=>r}),Ye()],fe.prototype,"switchRole",1),X([Ye()],fe.prototype,"destroy",1),X([Ut(bt.TRTC.startLocalAudio),Zi("audio",([e],[r])=>{var o,s;return((o=e==null?void 0:e.option)==null?void 0:o.microphoneId)===((s=r==null?void 0:r.option)==null?void 0:s.microphoneId)}),Ye()],fe.prototype,"startLocalAudio",1),X([Ut(bt.TRTC.updateLocalAudio),Jo("audio",{debounce:{delay:200,getKey:()=>`${ug}-localAudio`,isNeedToDebounce:e=>{var r;return!V((r=e.option)==null?void 0:r.captureVolume)}}}),Ye()],fe.prototype,"updateLocalAudio",1),X([Ki("audio"),Ye()],fe.prototype,"stopLocalAudio",1),X([Ut(bt.TRTC.startLocalVideo),Zi("video",([e],[r])=>{var o,s;return((o=e==null?void 0:e.option)==null?void 0:o.cameraId)===((s=r==null?void 0:r.option)==null?void 0:s.cameraId)}),Ye()],fe.prototype,"startLocalVideo",1),X([Ut(bt.TRTC.updateLocalVideo),Jo("video"),Ye()],fe.prototype,"updateLocalVideo",1),X([Ki("video"),Ye()],fe.prototype,"stopLocalVideo",1),X([Ut(bt.TRTC.startScreenShare),Zi("screen",()=>!0),Ye()],fe.prototype,"startScreenShare",1),X([Ut(bt.TRTC.updateScreenShare),Jo("screen"),Ye()],fe.prototype,"updateScreenShare",1),X([Ye()],fe.prototype,"stopScreenShare",1),X([Ut(bt.TRTC.startRemoteVideo),Zi(e=>`v${e.userId}${e.streamType}`,()=>!0),Ye({getRemoteId:e=>`${e.userId}_${e.streamType}`})],fe.prototype,"startRemoteVideo",1),X([Ut(bt.TRTC.updateRemoteVideo),Jo(e=>`v${e.userId}${e.streamType}`),Ye({getRemoteId:e=>`${e.userId}_${e.streamType}`})],fe.prototype,"updateRemoteVideo",1),X([Ut(bt.TRTC.stopRemoteVideo),Me(e=>function(r){return y(this,null,function*(){if(r.userId==="*"){let o=[];return this._room.remotePublishedUserMap.forEach(s=>{this._remoteVideoConfigMap.has(`${s.userId}_main`)&&o.push(this.stopRemoteVideo({streamType:"main",userId:s.userId}).catch(()=>{})),this._remoteVideoConfigMap.has(`${s.userId}_sub`)&&o.push(this.stopRemoteVideo({streamType:"sub",userId:s.userId}).catch(()=>{}))}),Promise.all(o)}return e.call(this,r)})}),Ye({getRemoteId:e=>`${e.userId}_${e.streamType}`})],fe.prototype,"stopRemoteVideo",1),X([Ki(e=>`v${e.userId}${e.streamType}`)],fe.prototype,"_stopRemoteVideo",1),X([Ut(...bt.TRTC.muteRemoteAudio),Ye({getRemoteId:e=>e})],fe.prototype,"muteRemoteAudio",1),X([Xm(...bt.TRTC.setRemoteAudioVolume),ig(200,e=>e),Ye({getRemoteId:e=>e})],fe.prototype,"setRemoteAudioVolume",1),X([Jd("start"),Gi(e=>{var r;return(r=e.afterStart)==null?void 0:r.call(e)}),Zi((e,r)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(r)),Ye({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>bl[e.getName()],ignoreLog:e=>e.getName()==="Debug"})],fe.prototype,"startPlugin",1),X([Jd("update"),Jo((e,r)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(r)),Ye({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Rl[e.getName()]})],fe.prototype,"updatePlugin",1),X([Jd("stop"),Ki((e,r)=>{if(e.disableRandomCall)return null;let o=e.getGroup(r),s=e.getAlias();return o==="*"?new RegExp(`${s}.*`):s+o}),Ye({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>vl[e.getName()]})],fe.prototype,"stopPlugin",1),X([Xm(...bt.TRTC.enableAudioVolumeEvaluation)],fe.prototype,"enableAudioVolumeEvaluation",1),X([Ye()],fe.prototype,"getVideoSnapshot",1),X([Ye()],fe.prototype,"_setCurrentSpeaker",1),X([Zi(e=>`a${e.userId}`,()=>!0)],fe.prototype,"_startRemoteAudio",1),X([Me(e=>function(r){return y(this,null,function*(){return r.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(o=>this._stopRemoteAudio(Ee(ee({},r),{userId:o.userId})).catch(()=>{}))):e.call(this,r)})}),Ki(e=>`a${e.userId}`)],fe.prototype,"_stopRemoteAudio",1),X([Ki("room")],fe.prototype,"_exitRoom",1),X([Ki("screen")],fe.prototype,"_stopScreenShare",1),X([Ut(...bt.TRTC.sendSEIMessage),Hm({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...e)=>e[0].byteLength})],fe.prototype,"sendSEIMessage",1),X([Ut(bt.TRTC.sendCustomMessage),Hm({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],fe.prototype,"sendCustomMessage",1),X([Ut(bt.TRTC.create)],fe,"_create",1);var sp=fe,Zs=sp;var ru=class{constructor(t,e){u(this,"_flag");u(this,"terminalType");u(this,"userId");u(this,"tinyId");u(this,"role");u(this,"remoteAudioTrack");u(this,"remoteVideoTrack");u(this,"remoteAuxiliaryTrack");this.userId=e.userId||"",this.tinyId=e.tinyId||"",this.role=e.role||"audience",this.terminalType=e.terminalType,this.remoteAudioTrack=new $o(t,this),this.remoteVideoTrack=new Xi(t,this),this.remoteAuxiliaryTrack=new xd(t,this),this.flag=e.flag||0}get subscribeState(){let t={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(this.remoteVideoTrack.mediaType&8?t.smallVideo=!0:t.video=!0),this.remoteAudioTrack.isSubscribed&&(t.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(t.auxiliary=!0),t}get muteState(){return Mn(this.flag,this.userId)}get flag(){return this._flag}set flag(t){if(t===this._flag)return;let e,r=this.muteState;this._flag=t;let o=this.muteState;for(e in o)r[e]!=o[e]&&console.log(this.userId,e,r[e],"->",o[e]);this.remoteAudioTrack.onFlagChanged(),this.remoteVideoTrack.onFlagChanged(),this.remoteAuxiliaryTrack.onFlagChanged()}};var np=class{constructor(){u(this,"_set",new Set);H.on(L.LEAVE_SUCCESS,this.delete,this)}add({room:t,roomId:e}){if(t.scene==="rtc")return;let r=this.getKey(t.userId,e||t.roomId,t.sdkAppId,t.useStringRoomId);this._set.add(r)}delete({room:t,roomId:e}){if(t.scene==="rtc")return;let r=this.getKey(t.userId,t.roomId||e,t.sdkAppId,t.useStringRoomId);this._set.delete(r)}getKey(t,e,r,o){return`${r}_${e}_${t}_${o}`}isJoined({userId:t,roomId:e,sdkAppId:r,room:o}){return o.scene==="rtc"?!1:this._set.has(this.getKey(t,e,r,o.useStringRoomId))}};function eS(){return y(this,null,function*(){let i,t;try{let _=yield Jt();i=_&&_.length}catch(_){}try{let _=yield er();t=_&&_.length}catch(_){}let e={microphone:i,camera:t},{isH264EncodeSupported:r,isVp8EncodeSupported:o,isH264DecodeSupported:s,isVp8DecodeSupported:n}=this.checkSystemResult.detail,d=Bi.basis(),p={webRTC:d.isWebRTCSupported,getUserMedia:d.isGetUserMediaSupported,webSocket:d.isWebSocketsSupported,screenShare:d.isScreenShareSupported,webAudio:d.isWebAudioSupported,h264Encode:r,h264Decode:s,vp8Encode:o,vp8Decode:n},m={browser:d.browser,os:d.os,trtc:p,devices:e},g={isWebCodecSupported:d.isWebCodecSupported,isMediaSessionSupported:d.isMediaSessionSupported,isWebTransportSupported:d.isWebTransportSupported};Be.uploadEvent({log:`trtcstats-${JSON.stringify(m)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(m)}`),Be.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(g)}`,userId:this.userId})})}function mg(){return Me(i=>{let t=new np;return function(e,r,o){return y(this,null,function*(){let s=String(e.roomId||e.strRoomId);if(this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.userSig=e.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=r,e.privateMapKey=e.privateMapKey||"",this.isJoined)throw new he({code:te.INVALID_OPERATION,message:dt({key:ct.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:s,sdkAppId:this.sdkAppId,room:this}))throw new he({code:te.INVALID_OPERATION,message:dt({key:ct.REPEAT_JOIN,data:this.userId})});t.add({room:this,roomId:s}),this.role=e.role===21?"audience":"anchor",this._log.info(`Join() => joining room: ${s} useStringRoomId: ${this.useStringRoomId} scene: ${this.scene} role: ${this.role}`),H.emit(L.JOIN_START,{room:this,roomId:s,params:e});let n=Lr.getEnv();n||(n=zr.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(uc.OLD_CLOUD_LADDER)?n=zr.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(uc.WEBRTC)&&(n=zr.WEBRTC))),Be.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:s}),Bi.checkSystemRequirementsInternal().then(d=>{this.checkSystemResult=d,eS.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Lr.getEnv()&&(yield this.schedule(e,o));let d=yield i.call(this,e,r,o);return this.roomId=s,this._joinedTimestamp=Lr.performanceNow(),H.emit(L.JOIN_SUCCESS,{room:this}),o===30&&!e.component&&Be.uploadEvent({log:`stat-conv-${Number(Tr)}-${location.hostname}`,userId:this.userId}),d}catch(d){throw t.delete({room:this,roomId:s}),H.emit(L.JOIN_FAILED,{room:this,error:d}),d}})}})}var pg=()=>Me(i=>function(...t){return y(this,null,function*(){H.emit(L.LEAVE_START,{room:this}),yield i.call(this,...t),H.emit(L.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function hg(){return Me(i=>function(...t){return y(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(t=t.filter(r=>r.outMediaTrack&&r.state==="capture"),!t.length))return;H.emit("61",{room:this});let e=i.apply(this,t);return t.forEach(r=>r.publish(this,e)),e})})}function fg(){return Me(i=>function(...t){let e=i.apply(this,t);return t.forEach(r=>r.unpublish()),e})}function gg(){return Me(i=>function(...t){let e=i.apply(this,t);return t.forEach(r=>!r.isSubscribed&&r.subscribe(e)),e})}function tS({fn:i,context:t}){return function(...e){try{let r=i.apply(t,e);return xi(r)?r.catch(o=>$.error(`${i.name}() error observed ${o}`)):r}catch(r){$.error(`${i.name}() error observed ${r}`)}}}var iu=class{constructor(t){u(this,"_frameWorkType");u(this,"_component");u(this,"_language");u(this,"connectionType");u(this,"_room");u(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0});u(this,"_keyPrefix");u(this,"_log");u(this,"_intervalId");u(this,"_firstPublishedUserList");u(this,"_networkQuality");u(this,"_basicInfo");u(this,"_pathJoinRoom");u(this,"_pathLeaveRoom");u(this,"_pathMainVideoMap");u(this,"_pathMainAudioMap");u(this,"_pathAuxiliaryMap");u(this,"_remoteStreamStatMap");u(this,"_localStreamStat");u(this,"_eventMap",new Map);u(this,"_captureCostSum",0);u(this,"_captureCostCount",0);u(this,"isDestroyed",!1);this._frameWorkType=t.frameWorkType||30,this._component=t.component||0,this.connectionType=t.connectionType||1,this._language=t.language||0,this._room=t.room,this._keyPrefix="key_point",this._log=$.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(e=>{e.startsWith("handle")&&Xe(this[e])&&(this[e]=tS({fn:this[e],context:this}))}),this.initData(),this.installEvents()}initData(){this._firstPublishedUserList=[],this._networkQuality={totalUplinkRTT:0,totalUplinkLoss:0,count:0,totalDownlinkRTTAndLossMap:new Map},this._basicInfo={string_sdk_version:rt,uint32_os_type:15,string_device_name:"",string_http_user_agent:navigator.userAgent,string_os_version:"",uint32_avg_rtt:0,uint32_avg_up_loss:0,uint32_scene:this._room.scene==="live"?1:0,uint32_joining_duration:0,uint32_networkType:0,uint32_framework:this._frameWorkType,uint32_component:this._component,uint32_connection_type:this.connectionType,uint32_caller_coding_language:this._language,string_domain:location.hostname},this._pathJoinRoom={uint64_start_time:0,uint64_send_request_acc_ip_cmd_start_time:0,uint64_send_request_acc_ip_cmd_end_time:0,uint64_send_request_enter_room_cmd_start_time:0,uint64_send_request_enter_room_cmd_end_time:0,uint64_send_first_video_frame_time:0,uint64_recv_userlist_time:0,uint64_end_time:0,int32_send_request_acc_ip_cmd_ret:0,int32_send_request_enter_room_cmd_ret:0,int32_end_ret:0},this._pathLeaveRoom={uint64_start_time:0,uint64_send_request_exit_room_cmd_start_time:0,uint64_send_request_exit_room_cmd_end_time:0,uint64_end_time:0,int32_send_request_exit_room_cmd_ret:0,int32_end_ret:0},this._localStreamStat={totalVideoBitrate:0,totalVideoFPS:0,totalVideoHeight:0,totalVideoWidth:0,totalAudioLevel:0,videoCount:0,audioLevelCount:0,publishStartTime:0,statsToReport:{uint32_audio_capture_db:0,uint32_video_big_capture_fps:0,uint32_video_big_bitrate:0,uint32_video_big_resolution:0}},this._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,jn().then(t=>{this._basicInfo.string_os_version=bo(),t?this._basicInfo.string_device_name=t.mobile?t.model:this._basicInfo.string_os_version:this._basicInfo.string_device_name=this._basicInfo.string_os_version})}addEvent(t,e){return this._eventMap.set(t,e),H.on(t,e),this}installEvents(){this.handleUnload=this.handleUnload.bind(this),window.addEventListener("pagehide",this.handleUnload),this._room.once("banned",()=>this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})),this.addEvent(L.JOIN_START,this.handleJoinStart).addEvent(L.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(L.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(L.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(L.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(L.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(L.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(L.JOIN_FAILED,this.handleJoinFailed).addEvent(L.LEAVE_START,this.handleLeaveStart).addEvent(L.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(L.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(L.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(L.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(L.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(L.PUBLISH_START,this.handlePublishStart).addEvent(L.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(L.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(L.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(L.PLAY_TRACK_START,this.handlePlayStart).addEvent(L.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(L.PLAYER_STATE_CHANGED,({track:t,state:e,type:r})=>{!t.isRemote||!this.hitTest(t.room)||e==="PLAYING"&&(r===D.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))}).addEvent(L.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(L.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(L.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(L.REMOTE_PUBLISH_STATE_CHANGED,({room:t,prevMuteState:e,muteState:r})=>{if(!this.hitTest(t))return;let o=e.hasAudio||e.hasVideo||e.hasSmall,s=e.hasAuxiliary,n=r.hasAudio||r.hasVideo||r.hasSmall,d=r.hasAuxiliary;!o&&n&&this.handleRemoteStreamAdded(r.userId,"main"),!s&&d&&this.handleRemoteStreamAdded(r.userId,"auxiliary")}).addEvent(L.SINGLE_CONNECTION_STAT,({room:t,stat:e})=>{this.hitTest(t)&&(this._pathJoinRoom.int32_ice_cost=e.ice,this._pathJoinRoom.int32_dtls_cost=e.dtls,this._pathJoinRoom.int32_peer_connection_cost=e.peerConnection)})}uninstallEvents(){window.removeEventListener("pagehide",this.handleUnload),this._eventMap.forEach((t,e)=>H.off(e,t)),this._eventMap.clear()}destroy(){this.uninstallEvents(),At.clearTask(this._intervalId),this._pathJoinRoom.uint64_start_time===0&&(this._room=null),this.isDestroyed=!0}handleUnload(){this._room.isJoined&&this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})}handleJoinStart(t){this.hitTest(t.room)&&(this._pathJoinRoom.uint64_start_time===0&&(this._pathJoinRoom.uint64_start_time=Date.now()),t.params&&(V(t.params.frameWorkType)||(this._frameWorkType=t.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),V(t.params.component)||(this._component=t.params.component,this._basicInfo.uint32_component=this._component),V(t.params.language)||(this._language=t.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleJoinScheduleSuccess({room:t,detailCost:e}){if(this.hitTest(t)&&e){let{totalCost:r,local:o,dns:s,tcp:n,tls:d,request:p,response:m}=e;this._pathJoinRoom.int32_schedule_cost=r,this._pathJoinRoom.int32_schedule_local=o,this._pathJoinRoom.int32_schedule_dns=s,this._pathJoinRoom.int32_schedule_tcp=n,this._pathJoinRoom.int32_schedule_tls=d,this._pathJoinRoom.int32_schedule_request=p,this._pathJoinRoom.int32_schedule_response=m}}handleSignalConnectionStart({room:t}){this.hitTest(t)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time=Date.now())}handleSignalConnectionEnd({room:t,error:e}){this.hitTest(t)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time=Date.now(),e&&(this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret=e instanceof he?Number(e.getExtraCode()||e.getCode()):te.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}handleJoinSendCMD(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now())}handleJoinReceivedCMDResponce(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=t.code,t.code!==0&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}handleJoinSuccess(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_end_time===0&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=t.room.getSignalInfo())}handleJoinFailed({room:t,error:e}){this.hitTest(t)&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret===0&&(this._pathJoinRoom.int32_end_ret=e.code||this._pathJoinRoom.int32_send_request_enter_room_cmd_ret||this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret),setTimeout(()=>{this.report()}))}handleReceivedPublishUserList(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_recv_userlist_time===0&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=t.publishedUserList||[])}handleSendFirstVideoFrame({room:t}){this.hitTest(t)&&this._pathJoinRoom.uint64_send_first_video_frame_time===0&&this._pathJoinRoom.uint64_start_time!==0&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now())}handleLeaveStart(t){this.hitTest(t.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(t){this.hitTest(t.room)&&this._pathLeaveRoom.uint64_end_time===0&&(this._pathLeaveRoom.uint64_end_time=Date.now(),this._pathJoinRoom.uint64_end_time!==0?this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time:this._log.warn("pathJoinRoom endTime is 0"),this.report())}handleLeaveSendCMD(t){this.hitTest(t.room)&&(this._pathLeaveRoom.uint64_send_request_exit_room_cmd_start_time=Date.now(),this._pathLeaveRoom.uint64_send_request_exit_room_cmd_end_time=Date.now())}handleRemoteStreamAdded(t,e){var o;let r=`${t}_${e}`;if(!this._remoteStreamStatMap.has(r)){let s={userId:t,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:Ee(ee({},rS),{msg_user_info:new xa({userId:t,tinyId:(o=this._room.remotePublishedUserMap.get(t))==null?void 0:o.tinyId,role:20})})};s.statsToReport.uint32_stream_type=e==="main"?2:7,this._remoteStreamStatMap.set(r,s)}}handleSubscribeStart({room:t,remotePublishedUser:e,streamType:r,subscribeState:o}){if(!this.hitTest(t))return;let{userId:s,tinyId:n,role:d}=e,p=new xa({userId:s,tinyId:n,role:d==="anchor"?20:21}),m=Date.now(),g=`${s}_${r}`,_=this._remoteStreamStatMap.get(g);_&&_.subscribeStartTime===0&&(_.subscribeStartTime=m),r==="main"?(e.muteState.hasVideo&&(o.video||o.smallVideo)&&!this._pathMainVideoMap.has(g)&&this._pathMainVideoMap.set(g,{statsToReport:{msg_user_info:p,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:s,sendSubscribeCMDTime:m}),e.muteState.hasAudio&&o.audio&&!this._pathMainAudioMap.has(g)&&this._pathMainAudioMap.set(g,{statsToReport:{msg_user_info:p,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:s,sendSubscribeCMDTime:m})):e.muteState.hasAuxiliary&&o.auxiliary&&!this._pathAuxiliaryMap.has(g)&&this._pathAuxiliaryMap.set(g,{sendSubscribeCMDTime:m})}handleSubscribed({room:t,remotePublishedUser:e,streamType:r}){if(this.hitTest(t)){let o=`${e.userId}_${r}`,s=this._remoteStreamStatMap.get(o);s&&s.subscribedTime===0&&(s.subscribedTime=Date.now())}}handlePlayStart({track:t}){if(!t.isRemote||!this.hitTest(t.room))return;let e=`${t.userId}_${t.streamType}`,r=this._remoteStreamStatMap.get(e);(r==null?void 0:r.playStreamTime)===0&&(r.playStreamTime=Date.now())}handleVideoLoadedData({track:t}){if(!t.isRemote||!this.hitTest(t.room))return;let e=`${t.userId}_${t.streamType}`,r=this._pathMainVideoMap.get(e);r&&r.statsToReport.uint64_combine_first_frame_time===0&&(r.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(t){let e=`${t.userId}_${t.streamType}`,r=Date.now(),o=this._pathMainVideoMap.get(e),s=this._remoteStreamStatMap.get(e);if(s){let{statsToReport:n}=s;if(!n.uint32_video_render_first&&t.streamType==="main"?this.hasVideoFlag(t.userId):this.hasAuxFlag(t.userId)){let d=r-this._pathJoinRoom.uint64_start_time;n.uint32_video_render_first=d,Y.addNumber({key:516820,value:d})}}(o==null?void 0:o.statsToReport.uint64_render_first_frame_time)===0&&(o.statsToReport.uint64_render_first_frame_time=r)}handleAudioPlaying(t){let e=`${t.userId}_${t.streamType}`,r=this._pathMainAudioMap.get(e);r&&r.statsToReport.uint64_play_first_frame_time===0&&(r.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(t){this.hitTest(t.room)&&(this._networkQuality.totalUplinkLoss+=t.uplink.loss,this._networkQuality.totalUplinkRTT+=t.uplink.rtt,this._networkQuality.count++,t.downlinks.forEach(({rtt:e,loss:r,userId:o,videoDelay:s,audioDelay:n})=>{let d=this._networkQuality.totalDownlinkRTTAndLossMap.get(o);if(d)d.totalRTT+=e,d.totalLoss+=r,s&&(d.totalVideoDelay=(d.totalVideoDelay||0)+s,d.videoDelayCount=(d.videoDelayCount||0)+1),n&&(d.totalAudioDelay=(d.totalAudioDelay||0)+n,d.audioDelayCount=(d.audioDelayCount||0)+1),d.count++;else{let p,m,g,_;s&&(m=s,g=1),n&&(p=n,_=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(o,{totalRTT:e,totalLoss:r,count:1,totalAudioDelay:p,totalVideoDelay:m,audioDelayCount:_,videoDelayCount:g})}}))}handleHeartbeatStats(t){if(this.hitTest(t.room)){let{msg_device_info:e,msg_up_stream_info:r,msg_down_stream_info:o}=t.report;if(r.msg_video_status[0]){let{uint32_video_codec_bitrate:s,uint32_video_enc_fps:n,uint32_video_width:d,uint32_video_height:p}=r.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=s,this._localStreamStat.totalVideoFPS+=n,this._localStreamStat.totalVideoWidth+=d,this._localStreamStat.totalVideoHeight+=p,this._localStreamStat.videoCount++}if(r.msg_audio_status){let{uint32_audio_level:s}=r.msg_audio_status;Math.floor(s/oi*100)>0&&(this._localStreamStat.totalAudioLevel+=s/oi,this._localStreamStat.audioLevelCount++)}o.forEach(s=>{let{msg_user_info:n,msg_audio_status:d,msg_video_status:p}=s,m=n.str_identifier,g=this._room.remotePublishedUserMap.get(m);if(p.forEach(_=>{let b=_.uint32_video_stream_type===2,N=_.uint32_video_stream_type===7,k=`${m}_${b?"main":"auxiliary"}`,P=this._remoteStreamStatMap.get(k);if(P&&(b&&(g!=null&&g.remoteVideoTrack.isSubscribed)||N&&(g!=null&&g.remoteAuxiliaryTrack))){P.totalVideoFPS+=_.uint32_video_receive_fps,P.totalVideoBitrate+=_.uint32_video_codec_bitrate,P.videoCount++,P.statsToReport.uint32_video_width===0&&(P.statsToReport.uint32_video_width=_.uint32_video_width),P.statsToReport.uint32_video_height===0&&(P.statsToReport.uint32_video_height=_.uint32_video_height);let x=b?g.remoteVideoTrack:g.remoteAuxiliaryTrack;x.stat.jitterBufferDelay&&(P.videoJitterBufferDelay=x.stat.jitterBufferDelay),x.stat.framesReceived&&(P.statsToReport.uint32_video_consume_render_rate=Math.floor(x.stat.framesDecoded/x.stat.framesReceived*En(10,6)))}}),!fs(d)){let _=`${m}_main`,b=this._remoteStreamStatMap.get(_);this._remoteStreamStatMap.has(_)&&b&&g!=null&&g.remoteAudioTrack.isSubscribed&&(b.totalAudioBitrate+=d.uint32_audio_codec_bitrate,b.audioCount++,g.remoteAudioTrack.stat.jitterBufferDelay&&(b.audioJitterBufferDelay=g.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(d.uint32_audio_level/oi*100)>0&&(b.totalAudioLevel+=d.uint32_audio_level/oi,b.audioLevelCount++))}}),e.uint32_audio_capture_cost&&(this._captureCostSum+=e.uint32_audio_capture_cost,this._captureCostCount+=1,this._captureCostCount>=100&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0))}}handlePublishStart({room:t}){this.hitTest(t)&&this._localStreamStat.publishStartTime===0&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart({track:t}){t.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),t.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess({track:t}){t.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=0,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),t.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=0,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed({track:t,error:e}){let o={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[e.name]||(e instanceof he?e.getExtraCode()||e.getCode():te.UNKNOWN);t.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=o,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),t.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=o,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}hasVideoFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&ls)>=0}hasAudioFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&ms)>=0}hasAuxFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&yn)>=0}hitTest(t){return t===this._room}prepareReport(){if(this._captureCostCount>0&&!this._basicInfo.uint32_audio_capture_cost&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0),this._networkQuality.count>0&&(this._basicInfo.uint32_avg_rtt=Math.floor(this._networkQuality.totalUplinkRTT/this._networkQuality.count),this._basicInfo.uint32_avg_up_loss=Math.floor(this._networkQuality.totalUplinkLoss/this._networkQuality.count)),this._localStreamStat.videoCount>0){this._localStreamStat.statsToReport.uint32_video_big_capture_fps=Math.floor(this._localStreamStat.totalVideoFPS/this._localStreamStat.videoCount),this._localStreamStat.statsToReport.uint32_video_big_bitrate=Math.floor(this._localStreamStat.totalVideoBitrate/this._localStreamStat.videoCount);let t=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),e=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=t<<16|e}this._localStreamStat.audioLevelCount>0&&(this._localStreamStat.statsToReport.uint32_audio_capture_db=Math.floor(this._localStreamStat.totalAudioLevel/this._localStreamStat.audioLevelCount*100)),this._remoteStreamStatMap.forEach((t,e)=>{let{userId:r}=t,o=this._networkQuality.totalDownlinkRTTAndLossMap.get(r);if(o){let{totalLoss:g,count:_,audioDelayCount:b,videoDelayCount:N,totalAudioDelay:k,totalVideoDelay:P}=o;t.statsToReport.uint32_avg_down_loss=Math.floor(g/_),b&&k&&(t.statsToReport.uint32_audio_network_p2p_delay=Math.floor(k/b),t.audioJitterBufferDelay&&(t.statsToReport.uint32_p2p_delay=Math.floor(t.statsToReport.uint32_audio_network_p2p_delay+t.audioJitterBufferDelay))),N&&P&&(t.statsToReport.uint32_video_network_p2p_delay=Math.floor(P/N))}t.videoCount>0&&(t.statsToReport.uint32_video_avg_fps=Math.floor(t.totalVideoFPS/t.videoCount),t.statsToReport.uint32_video_avg_bitrate=Math.floor(t.totalVideoBitrate/t.videoCount)),t.audioCount>0&&(t.statsToReport.uint32_audio_recv_bitrate=t.statsToReport.uint32_audio_bitrate=Math.floor(t.totalAudioBitrate/t.audioCount)),t.audioLevelCount>0&&(t.statsToReport.uint32_audio_play_db=Math.floor(t.totalAudioLevel/t.audioLevelCount*100));let{callDurationCalculator:s}=this._room;s&&(t.statsToReport.uint32_audio_play_time=s.getDuration(e,D.AUDIO),t.statsToReport.uint32_video_play_time=s.getDuration(e,D.VIDEO)),t.statsToReport.uint32_video_render_first&&(t.statsToReport.uint32_video_render_first=Math.min(t.statsToReport.uint32_video_render_first,Xo));let{badCaseDetector:n}=this._room,{dataFreeze:d,count:p}=n.getDataFreezeDuration(e),{renderFreeze:m}=n.getRenderFreezeDuration(e);t.statsToReport.uint32_video_block_count=p,t.statsToReport.uint32_video_block_time=Math.min(d,t.statsToReport.uint32_video_play_time),t.statsToReport.uint32_video_external_block_time=Math.min(m,t.statsToReport.uint32_video_play_time),n.isBlackStream(e)&&t.statsToReport.uint32_video_avg_fps===0?t.statsToReport.uint32_video_black_screen_subjective=1:t.statsToReport.uint32_video_black_screen_subjective=0}),this._pathMainAudioMap.forEach((t,e)=>{if(!this.hasAudioFlag(t.userId)){this._pathMainAudioMap.delete(e);return}t.statsToReport.uint64_play_first_frame_time-t.statsToReport.uint64_start_enter_time>Xo&&(t.statsToReport.uint64_play_first_frame_time=t.statsToReport.uint64_start_enter_time+Xo)}),this._pathMainVideoMap.forEach((t,e)=>{if(!this.hasVideoFlag(t.userId)){this._pathMainVideoMap.delete(e);return}t.statsToReport.uint64_render_first_frame_time-t.statsToReport.uint64_start_enter_time>Xo&&(t.statsToReport.uint64_render_first_frame_time=t.statsToReport.uint64_start_enter_time+Xo)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>Xo&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+Xo)}getReportData(){this._basicInfo.uint32_networkType=fc();let t={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new xa({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:gs(this._signalInfo.relayIp),uint32_client_ip:gs(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*En(2,31)),msg_path_enter_room:this._pathJoinRoom,msg_path_exit_room:this._pathLeaveRoom,msg_path_recv_video:[...this._pathMainVideoMap.values()].map(e=>e.statsToReport),msg_quality_statistics:[...this._remoteStreamStatMap.values()].map(e=>e.statsToReport),str_room_name:String(this._room.roomId||0),msg_path_recv_audio:[...this._pathMainAudioMap.values()].map(e=>e.statsToReport),uint32_info_client_ip:gs(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,bytes_report_buf_from_0x1:this._signalInfo.endReportExtend};return On(t),t}report(){return y(this,null,function*(){try{this.prepareReport();let t=this.getReportData();yield this.upload(t),this.initData()}catch(t){this._log.warn(t)}finally{this.isDestroyed&&(this._room=null)}})}upload(t){return y(this,null,function*(){if(t.msg_path_enter_room.uint64_start_time===0)return;let e=Number(this._room.sdkAppId),r=yield Wu(t),o=r instanceof ArrayBuffer,s=`${Yr(e,Oi.KEY_POINT)}&gzip=${+o}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(s,r));let d=[this.uploadKVStat(Y),this.uploadKVStat(Mo)];n||d.push(Zr({url:s,body:r,priority:"low"})),yield Promise.all(d)})}setConnectionType(t){this.connectionType=t,this._basicInfo.uint32_connection_type=t}uploadKVStat(t){return y(this,null,function*(){let e=t.getReportData();if(e.stats_count.length===0&&e.stats_distribution.length===0)return;e.msg_sdk_basic_info=Ee(ee({},e.msg_sdk_basic_info),{bytes_device_name:this._basicInfo.string_device_name||"",bytes_os_version:this._basicInfo.string_os_version||"",uint32_framework:this._frameWorkType,uint32_network_type:this._basicInfo.uint32_networkType||0}),this._log.debug(e);let r=yield Wu(e),o=`${Yr(+this._room.sdkAppId,Oi.KV_STAT)}&gzip=${+(r instanceof ArrayBuffer)}`,s=!1;navigator.sendBeacon&&(s=navigator.sendBeacon(o,r)),s||Zr({url:o,body:r})})}};X([Hi({settings:{timeout:500,retries:3}})],iu.prototype,"upload",1);var Xo=5e3,rS={msg_user_info:null,uint32_video_avg_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_avg_bitrate:0,uint32_video_block_time:0,uint32_video_play_time:0,uint32_audio_block_time:0,uint32_audio_play_time:0,uint32_audio_play_db:0,uint32_avg_down_loss:0,uint32_stream_type:0,uint32_video_block_count:0,uint32_audio_block_count:0,uint32_audio_bitrate:0,uint32_video_black_screen_subjective:0,uint32_audio_recv_bitrate:0,uint32_video_external_block_time:0,uint32_video_consume_render_rate:0},xa=class{constructor(t){u(this,"str_identifier");u(this,"str_tinyid");u(this,"uint32_role");this.str_identifier=String(t.userId),this.str_tinyid=String(t.tinyId||0),this.uint32_role=t.role}},Eg=iu;var ap=class{constructor(){u(this,"_startTime");u(this,"_endTime");this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=_e())}stop(){this._endTime===0&&(this._endTime=_e())}getDuration(){return this._endTime===0?_e()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},ou=ap;var cp=class{constructor(t){u(this,"_room",null);u(this,"_durationMap");u(this,"_eventMap",new Map);this._room=t.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(L.REMOTE_TRACK_SUBSCRIBED,this.handleSubscribed).set(L.REMOTE_TRACK_UNSUBSCRIBED,this.handleUnsubscribed).set(L.REMOTE_PUBLISH_STATE_CHANGED,({room:t,prevMuteState:e,muteState:r})=>{var n;let{userId:o}=r;if(!this.hitTest(t))return;e.hasAudio&&!r.hasAudio&&this.stopDurationItem(`${o}_main`,D.AUDIO),e.hasVideo&&!r.hasVideo&&this.stopDurationItem(`${o}_main`,D.VIDEO),e.hasAuxiliary&&!r.hasAuxiliary&&this.stopDurationItem(`${o}_auxiliary`,D.VIDEO);let s=(n=this._room)==null?void 0:n.remotePublishedUserMap.get(o);s&&(!e.hasAudio&&r.hasAudio&&s.remoteAudioTrack.isSubscribed&&this.addDuractionItem(o,D.AUDIO,"main"),!e.hasVideo&&r.hasVideo&&s.remoteVideoTrack.isSubscribed&&this.addDuractionItem(o,D.VIDEO,"main"),!e.hasAuxiliary&&r.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(o,D.VIDEO,"auxiliary"))}),this._eventMap.forEach((t,e)=>H.on(e,t,this))}uninstallEvents(){this._eventMap.forEach((t,e)=>H.off(e,t,this)),this._eventMap.clear()}handleSubscribed({track:t}){if(!this.hitTest(t.room))return;let{userId:e,streamType:r,kind:o}=t;t.isSubscribed?this.addDuractionItem(e,o,r):this.stopDurationItem(`${e}_${r}`,o)}handleUnsubscribed({track:t}){this.hitTest(t.room)&&this.stopDurationItem(`${t.userId}_${t.streamType}`,t.kind)}isRecording(t){return t.findIndex(e=>e.endTime===0)>=0}addDuractionItem(t,e,r){let o=`${t}_${r}`,s=new ou,n=this._durationMap.get(o);n?this.isRecording(n[e])||n[e].push(s):this._durationMap.set(o,{userId:t,type:r,audio:e===D.AUDIO?[s]:[],video:e===D.AUDIO?[]:[s]})}stopDurationItem(t,e){if(this._durationMap.has(t)){let o=this._durationMap.get(t)[e].find(s=>s.endTime===0);o&&o.stop()}}hitTest(t){return this._room===t}getDuration(t,e){return this._durationMap.has(t)?this._durationMap.get(t)[e].reduce((o,s)=>o+s.getDuration(),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},_g=cp;var dp=class{constructor(t){u(this,"_room");u(this,"_renderFreezeMap",new Map);u(this,"_isVideoPlayingEventFiredMap",new Map);u(this,"_dataFreezeMap",new Map);u(this,"_monitorFreezeData",new Map);u(this,"_eventMap",new Map);this._room=t.room,this.installEvents()}getRenderFreezeMap(){return this._renderFreezeMap}getDataFreezeMap(){return this._dataFreezeMap}installEvents(){this._eventMap.set(L.LEAVE_SUCCESS,({room:t})=>{this.hitTest(t)&&this.stop()}).set(L.PLAY_TRACK_START,this.onPlayTrackStart).set(L.UNSUBSCRIBE_SUCCESS,({room:t,streamType:e,remotePublishedUser:r})=>{if(!this.hitTest(t))return;let{userId:o}=r,s=`${o}_${e}`;this.stopDataFreeze({key:s,userId:o,type:e})}).set(L.REMOTE_PUBLISH_STATE_CHANGED,({room:t,prevMuteState:e,muteState:r})=>{if(!this.hitTest(t))return;let{userId:o}=r;if(e.hasVideo&&!r.hasVideo){let s="main",n=`${r.userId}_${s}`;this.stopDataFreeze({key:n,userId:o,type:s})}if(e.hasAuxiliary&&!r.hasAuxiliary){let s="auxiliary",n=`${r.userId}_${s}`;this.stopDataFreeze({key:n,userId:o,type:s})}}).set(L.PLAYER_STATE_CHANGED,({track:t,state:e,reason:r,type:o})=>{if(!(!t.isRemote||!t.room||!this.hitTest(t.room)||o!==D.VIDEO)){if(e==="PLAYING"){let s=`${t.userId}_${t.streamType}`;this._isVideoPlayingEventFiredMap.set(s,!0)}r===D.MUTE?this.onVideoTrackMuted(t):r===D.UNMUTE&&this.onVideoTrackUnmuted(t)}}).set(L.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach((t,e)=>H.on(e,t,this))}uninstallEvents(){this._eventMap.forEach((t,e)=>H.off(e,t,this)),this._eventMap.clear()}stop(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}onVideoTrackMuted(t){if(!t.isSubscribed)return;let{userId:e,streamType:r}=t,o=`${e}_${r}`,s=this._dataFreezeMap.get(o),n=new ou;s?s.durationItemList.push(n):this._dataFreezeMap.set(o,{userId:e,type:r,durationItemList:[n],isFreezing(){let d=this.durationItemList[this.durationItemList.length-1];return d&&d.endTime===0}})}onVideoTrackUnmuted(t){if(!t.isSubscribed)return;let{userId:e,streamType:r}=t,o=`${e}_${r}`;this.stopDataFreeze({key:o,userId:e,type:r})}onHearBeatReport({room:t,report:e}){this.hitTest(t)&&e.msg_down_stream_info.forEach(r=>{let o=this._room.remotePublishedUserMap.get(r.msg_user_info.str_identifier);if(!o)return;let{userId:s,muteState:n}=o;r.msg_video_status.forEach(d=>{d.uint32_video_stream_type===2&&n.hasVideo&&!n.videoMuted&&o.remoteVideoTrack.isSubscribed&&this.handleRenderFreeze({userId:s,fps:d.uint32_video_dec_fps,type:"main"}),d.uint32_video_stream_type===7&&n.hasAuxiliary&&o.remoteAuxiliaryTrack.isSubscribed&&this.handleRenderFreeze({userId:s,fps:d.uint32_video_dec_fps,type:"auxiliary"})})})}stopDataFreeze({key:t,userId:e,type:r}){let o=this._dataFreezeMap.get(t);if(!o||!o.isFreezing())return;let s=o.durationItemList[o.durationItemList.length-1];s.stop();let n=s.getDuration();n>pc?this._monitorFreezeData.set(t,{userId:e,type:r,duration:n}):o.durationItemList.pop()}getTotalDuration(t){return t.reduce((e,r)=>{let o=r.getDuration();return e+Math.min(o,5e3)},0)}handleRenderFreeze(o){return y(this,arguments,function*({userId:t,fps:e,type:r}){let s=`${t}_${r}`,n=this._renderFreezeMap.get(s);if(e<=2){let d=_e();n&&!n.isFreeze&&(n.freezeTimeline.push({startTime:d,endTime:0}),n.isFreeze=!0),n||this._renderFreezeMap.set(s,{userId:t,type:r,isFreeze:!0,freezeTimeline:[{startTime:d,endTime:0}],renderFreezeTotal:0})}else if(n&&n.isFreeze){n.isFreeze=!1;let d=n.freezeTimeline.pop();if(d){d.endTime=_e();let p=d.endTime-d.startTime;n.freezeTimeline.push(d),n.renderFreezeTotal+=Math.min(5e3,p)}}})}onPlayTrackStart({track:t}){if(!t.isRemote||!this.hitTest(t.room)||t.kind!==D.VIDEO||!t.isRemotePublished)return;let e=`${t.userId}_${t.streamType}`;this._isVideoPlayingEventFiredMap.has(e)||this._isVideoPlayingEventFiredMap.set(e,!1)}getDataFreezeDuration(t){let e={dataFreeze:0,count:0},r=this._dataFreezeMap.get(t);if(r){if(r.isFreezing()){let o=r.durationItemList[r.durationItemList.length-1];o.stop(),o.getDuration()<pc&&r.durationItemList.pop()}e.dataFreeze=this.getTotalDuration(r.durationItemList),e.count=r.durationItemList.length}return e}getRenderFreezeDuration(t){let e=this._renderFreezeMap.get(t),r=0,o=0;if(e)if(!e.isFreeze)r=e.renderFreezeTotal;else{let s=_e(),n=e.freezeTimeline[e.freezeTimeline.length-1],d=s-n.startTime;r=e.renderFreezeTotal+Math.min(d,5e3),o=e.freezeTimeline.length}return{renderFreeze:r,count:o}}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(t){return this._isVideoPlayingEventFiredMap.has(t)?!this._isVideoPlayingEventFiredMap.get(t):!1}resetMonitor(){this._monitorFreezeData.clear()}hitTest(t){return t===this._room}destroy(){this.uninstallEvents()}},Tg=dp;var Sg=Mi($i(),1);var iS=[1,0,0,0,1,1,0,1],su=class extends Bt{constructor(t,e){if(super(t,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"mirror",logger:e}),t instanceof Et)try{this.setTexBuffer(iS)}catch(r){t.destroy(new he({code:te.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${r.message||r}`}))}}draw2d(t,e,r,o,s){if(this.ctx2d){this.ctx2d.save(),this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0);let n=super.draw2d(t,e,r,o,s);return this.ctx2d.restore(),n}return!1}render(t){var e;return(e=this.input)!=null&&e.requestFrame(t)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}};var up=class{constructor(t,e){this.node=t;this.layout=e;u(this,"positionBuffer")}get x(){return this.layout.x||this.node.x}get y(){return this.layout.y||this.node.y}get width(){return this.layout.width||this.node.width}get height(){return this.layout.height||this.node.height}get right(){return this.x+this.width}get bottom(){return this.y+this.height}},nu=class extends Bt{constructor(e,r){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:r});u(this,"inputs",[])}addInput(e,r){if(this.inputs[r.zIndex])throw new Error("input already exists");let o=new up(e,r);this.inputs[r.zIndex]=o}resize(e,r){let o=this.inputs.reduce((s,n)=>n?Object.assign(s,{width:Math.max(s.width,n.right),height:Math.max(s.height,n.bottom)}):s,{width:0,height:0});super.resize(o.width,o.height),this.context instanceof Et&&this.inputs.forEach(s=>{if(s){let n=this.layout2texCoords(s);s.positionBuffer?this.changeBufferData(s.positionBuffer,n):s.positionBuffer=this.createBuffer(n)}})}connect(e,...r){return super.connect(e,...r),this.resize(0,0),e}removeInput(e){this.inputs[this.inputs.findIndex(r=>(r==null?void 0:r.node)===e)]=void 0}render(e){let r=this.context.ctx;if(r.clearColor(0,0,0,0),!this.inputs.reduce((s,n)=>(!n||!n.node.requestFrame(e))&&s,!0)&&r){this.useProgram(),r.enable(r.BLEND),r.blendFunc(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let s=0;s<this.inputs.length;s++){let n=this.inputs[s];n&&(n.node.useTexture(),this.draw(n.positionBuffer))}return!0}return!1}render2d(e){if(!this.inputs.reduce((o,s)=>(!s||!s.node.requestFrame(e))&&o,!0)&&this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height);for(let o=0;o<this.inputs.length;o++){let s=this.inputs[o];s&&this.draw2d(s.node.image,s.x,s.y,s.width,s.height)}return!0}return!1}getInfo(){let{totalFrames:e,x:r,y:o,width:s,height:n,name:d}=this,p=Date.now(),m=(e-this.lastInfo.totalFrames)/((p-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:r,y:o,width:s,height:n,timestamp:p,fps:m,name:d},ee({parent:this.inputs.filter(g=>g).map(g=>g.node.getInfo())},this.lastInfo)}close(){super.close(),this.inputs.forEach(e=>{var r,o;if(e&&((r=e.node)==null||r.disconnect(),e.positionBuffer&&this.context instanceof Et))try{(o=this.context.ctx)==null||o.deleteBuffer(e.positionBuffer)}catch(s){}})}};var oS=`#version 300 es
101
101
  in vec2 a_position;
102
102
  in vec2 a_texCoord;
103
103
  out vec2 v_texCoord;