trtc-sdk-v5 5.15.0-beta.19 → 5.15.0-beta.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/debug-dialog.js +1 -1
- package/package.json +1 -1
- package/trtc.esm.js +3 -3
- package/trtc.js +1 -1
package/trtc.esm.js
CHANGED
|
@@ -30,7 +30,7 @@ ${t.stack}`));let s=Ir.enable?qi(r,2002,Number(this._configs.sdkAppId)):JSON.str
|
|
|
30
30
|
<path d="m512 960c-247.04 0-448-200.96-448-448s200.96-448 448-448 448 200.96 448 448-200.96 448-448 448zm0-831.71c-211.58 0-383.71 172.13-383.71 383.71 0 211.55 172.13 383.71 383.71 383.71 211.55 0 383.71-172.16 383.71-383.71 0-211.58-172.16-383.71-383.71-383.71z" p-id="2032"/>
|
|
31
31
|
<path d="m512 673.7c-17.665 0-32.001-14.336-32.001-31.999v-54.112c0-52.353 40-92.352 75.328-127.65 25.887-25.92 52.672-52.672 52.672-74.017 0-53.343-43.072-96.735-95.999-96.735-53.823 0-95.999 41.536-95.999 94.559 0 17.665-14.336 31.999-32.001 31.999s-32.001-14.336-32.001-31.999c0-87.424 71.775-158.56 160-158.56s160 72.095 160 160.74c0 47.904-36.32 84.192-71.424 119.3-27.84 27.776-56.576 56.512-56.576 82.336v54.112c0 17.665-14.336 32.032-32.001 32.032z" p-id="2033"/>
|
|
32
32
|
</svg>
|
|
33
|
-
`,t.onclick=this.onQuestionClick.bind(this);let r=document.createElement("div");r.className=Tu,r.innerText=`${Yt()?"\u8BE6\u60C5 >":"Detail >"}`,r.onclick=this.onCollapseClick.bind(this);let s=i.content.firstChild,n=s.querySelector(`.${Id}`);return n.appendChild(r),n.appendChild(t),n.appendChild(e),s}addDiaLog(){br()||(Eu=!0,this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${yn}`).onclick=i=>i.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",R.info("show autoplay dialog"),se.uploadEvent({log:BT}))}deleteDialog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null,Eu=!1)}onConfirm(){R.warn("confirm clicked, try resume stream"),S.emit(A.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDialog()}onCollapseClick(){let i=this._dialogNode.querySelector(`.${Pp}`);i.style.visibility=`${this._showDetail?"hidden":"visible"}`,i.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||se.uploadEvent({log:HT}),this._isCollapseClicked=!0}onQuestionClick(){window.open(Up,"_blank"),this._isQuestionClicked||se.uploadEvent({log:$T}),this._isQuestionClicked=!0}},bn=null;function ns(){bn||(bn=new Su)}function Vp(){bn&&(bn.deleteDialog(),bn=null)}var pt=class o extends fi{constructor(e){super(e,_.VIDEO);c(this,"stat",{});c(this,"_calculateTimeout",-1);c(this,"viewMirror",!1);c(this,"objectFit");c(this,"container");c(this,"canvas");c(this,"shouldRenderAlpha",!1);c(this,"_preSize",{width:0,height:0});c(this,"posterImg");this.mode=e.canvas?1:0,this.container=e.container,this.canvas=e.canvas,T(e.viewMirror)||(this.viewMirror=e.viewMirror),T(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}get isPlaying(){var e;return this._state!=="PLAYING"||this.element&&this.element.paused?!1:((e=this.track)==null?void 0:e.readyState)==="live"&&!this.track.muted}initializeElement(){var t;let e=document.createElement(_.VIDEO);this.track&&this.mode!==2&&(e.srcObject=new MediaStream([this.track])),e.muted=!0,e.setAttribute("id",`video_${this.id}`),e.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),e.setAttribute("autoplay","autoplay"),e.setAttribute("playsinline","playsinline"),this.element=e,_e&&(e.poster="noposter"),(t=this.container)==null||t.appendChild(this.elementToRender),this.bindElementEvents(),this.calculateStat()}get styleAttribute(){let e=`width: 100%; height: 100%; object-fit: ${this.objectFit};${this.shouldRenderAlpha?"":"background-color: black"};`;return this.viewMirror&&(e+="transform: scaleX(-1);"),e}setContainer(e){var t;this.container=e,this.track&&this.elementToRender&&((t=this.container)==null||t.appendChild(this.elementToRender))}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),e&&e.add(_.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(_.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent).add(_.RESIZE,this.handleElementEvent)}handleTrackEvent(e){var t;return e.type===_.MUTE&&((t=this.stat)!=null&&t.fps)&&(this.stat.fps=0),super.handleTrackEvent(e)}handleElementEvent(e){var r,s,n,a,d,l;if(this.mode===2)return;super.handleElementEvent(e);let t=e.type;if(t===_.PAUSE&&(this.container&&!this.container.isConnected&&(this._log.warn(`${this.kind} player has been remove, element ID: ${this.container.id}`),Ke(500).then(()=>{var u;(u=this.container)!=null&&u.isConnected&&(this._pausedRetryCount=$r,this._log.info(`view container ${this.container.id} is in dom, reset pausedRetryCount`))})),this._pausedRetryCount>0&&!br()&&!this._isPausedByUserCall&&(this._log.info(`[${$r-this._pausedRetryCount+1}/${$r}] ${this.kind} player auto resume when paused`),this.doResume(),this._pausedRetryCount--),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){let u=this.element.style.transform;t===_.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=u.replace("scaleX(-1)",""):t===_.LEAVE_PICTURE_IN_PICTURE&&!u.includes("scaleX")&&(this.element.style.transform=`${u} scaleX(-1)`)}t===_.RESIZE&&(this._preSize.height!==((r=this.element)==null?void 0:r.videoHeight)||this._preSize.width!==((s=this.element)==null?void 0:s.videoWidth))&&(this._log.info(`video size changed to ${(n=this.element)==null?void 0:n.videoWidth}x${(a=this.element)==null?void 0:a.videoHeight}`),this._preSize.height=((d=this.element)==null?void 0:d.videoHeight)||0,this._preSize.width=((l=this.element)==null?void 0:l.videoWidth)||0,this.emit(he.RESIZE,{newWidth:this._preSize.width,newHeight:this._preSize.height}))}setCanvas(e,t=1){var r,s,n,a;this.canvas!==e&&((r=this.canvas)==null||r.remove(),e==null||e.setAttribute("style",this.styleAttribute),this.canvas=e,this.mode=e?t:0,this.mode===2&&this.setTrack(e.captureStream().getVideoTracks()[0]),e?((s=this.element)==null||s.remove(),(n=this.container)==null||n.appendChild(e)):this.element&&((a=this.container)==null||a.appendChild(this.element)))}setAttr(e){let t=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},e);t.style=Object.assign({width:"100%",height:"100%"},t.style),super.setAttr(t)}get mirror(){return this.viewMirror}setRect(e,t){this.elementToRender&&(this.elementToRender.style.width=`${e}px`,this.elementToRender.style.height=`${t}px`)}setViewMirror(e){this.elementToRender&&(this.elementToRender.style.transform=e?"scaleX(-1)":""),this.viewMirror=e}setObjectFit(e){this.elementToRender&&(this.elementToRender.style.objectFit=`${e}`),this.objectFit=e}setPoster(e,t=!1){return new Promise(r=>{if(this.element)if(this._log.info("setPoster",e.slice(0,10)),this.element.poster=e,t&&(Re||ee)){if(e==="")this.removePosterImg();else if(!this.posterImg){let s=document.createElement("img");s.src=e,s.style=`position:absolute;top:0;left:0;${this.styleAttribute}`,s.onload=()=>f(this,null,function*(){var n;s.decode&&(yield s.decode()),this.posterImg=s,(n=this.container)==null||n.appendChild(s),r()})}}else r()})}removePosterImg(){this.posterImg&&(this.posterImg.remove(),URL.revokeObjectURL(this.posterImg.src),delete this.posterImg)}pause(){return f(this,null,function*(){return(Ve&&$e>=128||ee||Re)&&(yield this.setPoster(this.getVideoFrame(),!0)),Le(o.prototype,this,"pause").call(this)})}resume(){return this.posterImg&&this.setPoster("",!0),super.resume()}stop(e=0){var t;super.stop(e),(t=this.canvas)==null||t.remove(),this.removePosterImg()}play(){return this.element?this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender):this.initializeElement(),this.mode===2?Promise.resolve():super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(he.MEDIA_TRACK_CHANGED,e),e!==null&&(this.bindTrackEvents(),this.element&&this.mode!==2&&(this.element.srcObject=new MediaStream([e]),this.element.remove()),this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender)))}getVideoFrame(){if(this.canvas)return this.canvas.toDataURL("image/png");if(!this.element)return"";let e=document.createElement("canvas");return e.width=this.element.videoWidth,e.height=this.element.videoHeight,e.getContext("2d").drawImage(this.element,0,0),e.toDataURL("image/png")}getElement(){return this.element}calculateStat(){try{if(Ki()&&this.element&&this._calculateTimeout<0){let e=0,t=null,r=(s,n)=>{this.stat.width=n.width,this.stat.height=n.height,t&&(this.stat.fps=Math.round((n.presentedFrames-t.presentedFrames)/(s-e)*1e3)),e=s,t=n,this._calculateTimeout=-1,this.element&&(this._calculateTimeout=setTimeout(()=>{var a;return(a=this.element)==null?void 0:a.requestVideoFrameCallback(r)},2e3))};this.element.requestVideoFrameCallback(r)}}catch(e){this._log.warn("init stat failed",e)}}};function tr(o,i){return f(this,null,function*(){if(!o.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield o.audioWorklet.addModule(i),R.info("worklet addModule success")}catch(e){throw R.info(`worklet addModule catch error. ${e.message}`),e}})}var Nn;typeof AudioContext!="undefined"?Nn=AudioContext:typeof webkitAudioContext!="undefined"?Nn=webkitAudioContext:typeof mozAudioContext!="undefined"&&(Nn=mozAudioContext);var yu=1500,it,Fp=-1,Cd=0,vn=-1,Ru=!1,Bp=0,Hp=-1,$p=-1;Wp();function Wp(){try{if(it)return;it=new Nn({sampleRate:48e3}),it.onstatechange=()=>{R.info(`context state: ${it.state}${it.state!=="running"?` visibilityState: ${document.visibilityState}`:""}`),as()},clearTimeout(Fp)}catch(o){R.error(`initAudioContext failed: ${o} typeof AudioContextClass: ${typeof Nn}`),Fp=setTimeout(Wp,1e3)}}var as=()=>{it.state==="suspended"?(Cd=V(),GT(),Nr(),document.addEventListener("click",as)):it.state==="interrupted"?Nr():(Cd&&(y.addNumber({key:507800,value:V()-Cd,split:[0,500,1e3,1500,2e3,3e3,4e3,5e3,1e4,3e4],max:6e4}),Cd=0),JT(),document.removeEventListener("visibilitychange",as),document.removeEventListener("click",as))},Au=0,Cu=-1;function Nr(){return new Promise((o,i)=>{if(it.state==="running")return o();Date.now()-Au<1e3?(clearTimeout(Cu),Cu=setTimeout(()=>{Au=Date.now(),it.resume().then(o,i)},1e3)):(clearTimeout(Cu),Au=Date.now(),it.resume().then(o,i))}).catch(o=>{R.warn(`context resume failed: ${o}`),document.addEventListener("visibilitychange",as)})}document.addEventListener("click",as);function GT(){vn===-1&&(vn=setTimeout(()=>{it.state==="suspended"&&(Ru=!0,S.emit("155",{isSuspended:!0}))},yu))}function JT(){vn!==-1&&(clearTimeout(vn),vn=-1,Ru&&(Ru=!1,S.emit("155",{isSuspended:!1})))}function Gp(){if(!ge||$p!==-1)return;let o=()=>{V()-Bp<500||(it&&it.state==="running"&&it.currentTime===Hp&&(R.warn("context is fake running, auto resume"),it.suspend().catch(i=>{R.warn(`context suspend failed: ${i}`)})),Hp=it.currentTime,Bp=V())};$p=setInterval(()=>{o()},2e3),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&o()})}var Ee=o=>it;var Ue=class{constructor(i){this.name=i;c(this,"node");c(this,"node2");c(this,"pre",new Set);c(this,"next",new Set);c(this,"context");c(this,"connectedNodes",new Set);c(this,"nextInputChannelMap",new Map);c(this,"_channelCount",1)}get channelCount(){return this._channelCount}set channelCount(i){this._channelCount=i,this.setChannelCount(this.node,i),this.setChannelCount(this.node2,i),this.next.forEach(e=>e.channelCount=i)}setChannelCount(i,e){!i||i instanceof ScriptProcessorNode||(i.channelCountMode="explicit",i.channelCount=e||this.channelCount||1)}setContext(i){this.context=i,this.node&&i.addMixWeight()}removeContext(){var i;this.node&&((i=this.context)==null||i.reduceMixWeight()),delete this.context}replaceNode(i){var e;if(i!==this.node)try{this.node?this._disconnect():(e=this.context)==null||e.addMixWeight(),this.node=i,this.setChannelCount(this.node),this.preNodeReconnect(),this.reconnect()}catch(t){R.error(t)}}setNode(i,e){var t;if(!this.node)try{(t=this.context)==null||t.addMixWeight(),this.node=i,this.setChannelCount(this.node),e&&(this.node2=e,this.setChannelCount(this.node2)),this.preNodeReconnect(),this.reconnect(),y.addSuccessEvent({key:502701})}catch(r){R.error(r),y.addFailedEvent({key:502701,error:r})}}deleteNode(){var i;if(this.node)try{this._disconnect(),delete this.node,delete this.node2,(i=this.context)==null||i.reduceMixWeight(),this.preNodeReconnect(),y.addSuccessEvent({key:502702})}catch(e){R.error(e),y.addFailedEvent({key:502702,error:e})}}preNodeReconnect(){this.pre.forEach(i=>{i.node?i.reconnect():i.preNodeReconnect()})}connectNext(i){this.next.forEach(e=>{let t=this.nextInputChannelMap.get(e);i._connect(e.node,t)||e.connectNext(i)})}_connect(i,e=0){return!this.node||!i?!1:((this.node2||this.node).connect(i,0,e),this.connectedNodes.add(i),!0)}_disconnect(){this.connectedNodes.forEach(i=>{var e;return(e=this.node2||this.node)==null?void 0:e.disconnect(i)}),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(i,e=0){return this.next.add(i),i.pre.add(this),this.nextInputChannelMap.set(i,e),i}},Rd=class extends Ue{constructor(e=256){super();this.fftSize=e;c(this,"dataArray",new Uint8Array(0))}setNode(e){e.fftSize=this.fftSize,this.dataArray=new Uint8Array(e.frequencyBinCount),super.setNode(e)}getByteTimeDomainData(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),this.dataArray}get level(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),Math.max(...this.dataArray)/128-1}get timeDomainPathData(){let e=this.getByteTimeDomainData(),t=1,r=0,s=0,n=`M${r},${s}`;for(let a=0;a<e.length;a++)s=e[a]/128*100/2,n+=`L${r},${s}`,r+=t;return n}},Dn=class{constructor(){c(this,"source",new Ue);c(this,"gain",new Ue);c(this,"destination",new Ue)}get volume(){var i;return((i=this.gain.node)==null?void 0:i.gain.value)||1}setVolume(i){if(i===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(Ee().createGain()),this.gain.node.gain.value=i}replaceSource(i){let e=Mn(i);e&&this.source.replaceNode(e)}get track(){var i;return(i=this.stream)==null?void 0:i.getAudioTracks()[0]}get stream(){var i;return(i=this.destination.node)==null?void 0:i.stream}},ds=class extends Dn{constructor(e){super();this.context=e;c(this,"aec",new Ue("aec"));c(this,"mixNode",new Ue("mixNode"));c(this,"silentNode",new Ue("silentNode"));c(this,"denoiser",new Ue("denoiser"));c(this,"voiceChanger",new Ue("voiceChanger"));this.source.pipeTo(this.aec).pipeTo(this.denoiser).pipeTo(this.voiceChanger).pipeTo(this.gain).pipeTo(this.destination),this.silentNode.pipeTo(this.mixNode).pipeTo(this.aec,1)}get isProcessEnabled(){return this.aec.node||this.denoiser.node||this.voiceChanger.node||this.gain.node}connect(){this.context.inputs.has(this)||(this.destination.setNode(this.context.destination),this.source.setContext(this.context),this.aec.setContext(this.context),this.silentNode.setContext(this.context),this.mixNode.setContext(this.context),this.denoiser.setContext(this.context),this.voiceChanger.setContext(this.context),this.gain.setContext(this.context),this.context.inputs.add(this))}disconnect(){this.context.inputs.has(this)&&(this.destination.deleteNode(),this.source.removeContext(),this.aec.removeContext(),this.silentNode.removeContext(),this.mixNode.removeContext(),this.denoiser.removeContext(),this.voiceChanger.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.aec.deleteNode(),this.silentNode.deleteNode(),this.mixNode.deleteNode(),this.denoiser.deleteNode(),this.voiceChanger.deleteNode(),this.source.deleteNode(),this.disconnect()}setVolume(e){if(e===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(this.context.audioContext.createGain()),this.gain.node.gain.value=e}},yd=class{constructor(){c(this,"audioContext",Ee("audio-mixer"));c(this,"destination",this.audioContext.createMediaStreamDestination());c(this,"inputs",new Set);c(this,"mixWeight",0);this.destination.channelCount=1}addMixWeight(i=1){this.mixWeight+=i,this.mixWeight-1===i+1>>1&&this.mixOnChange()}reduceMixWeight(i=1){this.addMixWeight(-i)}close(){this.inputs.forEach(i=>i.remove())}get mixTrack(){return this.destination.stream.getAudioTracks()[0]}},Jp=new WeakMap;function Mn(o){try{let i=Jp.get(o);if(i)return i;let e=Ee();if(o instanceof HTMLAudioElement)i=e.createMediaElementSource(o);else if(o instanceof MediaStreamTrack)i=e.createMediaStreamSource(new MediaStream([o]));else return o;return Jp.set(o,i),i}catch(i){if(ee&&i instanceof Error&&i.name==="NotSupportedError")R.warn(i);else throw i}}var Ot=class Ot{constructor(i){c(this,"_volume",0);c(this,"_volumeDb",0);c(this,"_log");c(this,"_scriptProcessorNode",null);c(this,"_audioWorkletNode",null);c(this,"_interval",200);c(this,"ready",this.preload());let{log:e}=i;this._log=e,S.on(A.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-Ot.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!Ot.workletReady){let i='class VolumeMeterWorklet extends AudioWorkletProcessor{constructor(){super(),this.volume=0,this.intervalTime=200,this.tick=200,this.isStop=!1,this.cache=[],this.sentFirstInfo1=!1,this.unmute=!1,this.port.onmessage=t=>{var e=t.data;switch(e.name){case"chunk":this.cache.push(...e.data),this.sentFirstInfo1||(this.port.postMessage({cl:e.data.length}),this.sentFirstInfo1=!0);break;case"setIntervalTime":this.intervalTime=e.intervalTime;break;case"unmute":this.unmute=!0;break;case"stop":this.isStop=!0}}}process(t,s){t=t[0],s=s[0];if(t||s){if(this.isStop)return!1;var i=s&&s[0]?s[0].length:0,h=this.cache.length,a=(i<h?(s[0].set(this.cache.slice(0,i)),this.cache=this.cache.slice(i)):this.unmute&&s[0].set(t[0]),(i<h?s:t)[0]);if(a){let e=0;for(let t=0;t<a.length;++t)e=Math.max(Math.abs(a[t]),e);s=a.reduce((t,e)=>t+e*e,0)/a.length;this.volume=e,this.tick-=a.length,this.tick<0&&(this.tick+=this.intervalTime/1e3*sampleRate,this.port.postMessage({volume:this.volume,volumeDb:Math.max(10*Math.log10(s)+100,0)/100,cacheLen:h,outputLen:i}))}}return!0}}registerProcessor("volume-meter",VolumeMeterWorklet);';Ot.workletReady=tr(Ot.audioContext,URL.createObjectURL(new Blob([i],{type:"application/javascript"})))}return Ot.workletReady.then(()=>this.initAudioWorklet()).catch(i=>(this._log.error(`volumeMeter preload error: ${i}`),this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(Ot.audioContext,"volume-meter");let i=!1;this._audioWorkletNode.port.onmessage=e=>{Ot.lastMessageTime=Date.now(),this._volume=e.data.volume||0,this._volumeDb=e.data.volumeDb||0,!i&&e.data.cacheLen&&e.data.outputLen&&(this._log.warn("worklet play success"),i=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(i){this._log.error(`volumeMeter init audio worklet error: ${i}`),se.logFailedEvent({userId:this._log.userId,eventType:Ze.LOAD_WORKLET,error:i}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=Ee("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=i=>{Ot.lastMessageTime=Date.now();let e=i.inputBuffer.getChannelData(0),t=0;for(let r=0;r<e.length;++r)t+=e[r]*e[r];this._volume=Math.sqrt(t/e.length)||0}}catch(i){this._log.error(`volumeMeter init script processor error: ${i}`)}}destroy(){this._scriptProcessorNode&&(this._scriptProcessorNode.onaudioprocess=null),this._audioWorkletNode&&(this._audioWorkletNode.port.postMessage({name:"stop"}),this._audioWorkletNode.port.onmessage=null),this._audioWorkletNode=null,this._scriptProcessorNode=null,S.off(A.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}getVolumeDb(){return Math.floor(this._volumeDb*100)}handleAudioLevelInterval(i){var t;let{interval:e}=i;this._interval=e,(t=this._audioWorkletNode)==null||t.port.postMessage({name:"setIntervalTime",intervalTime:e})}};c(Ot,"lastMessageTime",0),c(Ot,"audioContext",Ee("volume-meter")),c(Ot,"workletReady");var bd=Ot,On=class extends Ue{constructor(e){super();c(this,"_volumeMeter");this._volumeMeter=new bd(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return f(this,null,function*(){yield this._volumeMeter.preload(),this.setNode(this._volumeMeter.node)})}getCalculatedVolume(){return this._volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this._volumeMeter.getInternalAudioLevel()}getVolumeDb(){return this._volumeMeter.getVolumeDb()}write(e){if(this.node){let t=e.allocationSize({planeIndex:0}),r=new Float32Array(t>>2);e.copyTo(r,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:r},[r.buffer]),e.close()}}},so=bd;var zp=Je(nt(),1);var jp=o=>i=>i.deviceId===o;var kn=class{constructor(i,e){c(this,"kind");c(this,"type");c(this,"devices",[]);this.kind=i,this.type=e}update(i,e){let t=i.filter(r=>r.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);if(this.devices.length===1&&ls(this.devices[0])){this.devices=t;return}e&&(t.forEach(r=>{if(r.deviceId&&!this.devices.find(jp(r.deviceId))){let s=`${this.kind}${this.type}Added`;R.warn(`${s}: ${JSON.stringify(r)}`),e.emit(s,r)}}),this.devices.forEach(r=>{if(r.deviceId&&!t.find(jp(r.deviceId))){let s=`${this.kind}${this.type}Removed`;R.warn(`${s}: ${JSON.stringify(r)}`),e.emit(s,r)}})),this.devices=t}hasDevice(i){return!!this.devices.find(e=>e.deviceId===i)}},bu=class extends zp.EventEmitter{constructor(){super();c(this,"audioInputs",new kn(_.AUDIO,"Input"));c(this,"videoInputs",new kn(_.VIDEO,"Input"));c(this,"audioOutputs",new kn(_.AUDIO,"Output"));this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||oe.run("interval",()=>{this.update()},{delay:1e4}))}init(){cs().then(e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)})}update(){return f(this,arguments,function*(e=0){let t=yield cs(e);return this.audioInputs.update(t,this),this.videoInputs.update(t,this),this.audioOutputs.update(t,this),this})}hasBlueTooth(){var t;if(((t=Ee())==null?void 0:t.outputLatency)*1e3>150)return!0;let e=["bluetooth","air","wireless","bt","tws","buds","headset","headphone"];return this.audioOutputs.devices.some(r=>e.some(s=>r.label.toLowerCase().includes(s)))||this.audioInputs.devices.some(r=>e.some(s=>r.label.toLowerCase().includes(s)))}},be=xs||Do?null:new bu;function ls(o){return o.deviceId===o.groupId&&o.groupId===""}function cs(){return f(this,arguments,function*(o=0){if(Zi()||!md())return[];let i=yield navigator.mediaDevices.enumerateDevices();if(o!==0){let e={audio:!1,video:!1};if(i.forEach(t=>{ls(t)&&(t.kind===_.AUDIO_INPUT?e.audio=!0:t.kind===_.VIDEO_INPUT&&(e.video=!0))}),o===2&&(e.audio=!1),o===1&&(e.video=!1),e.audio||e.video){let t;try{t=yield navigator.mediaDevices.getUserMedia(e),e.audio&&Nr()}catch(r){R.debug("capture before getDevices failed: ",r)}i=yield navigator.mediaDevices.enumerateDevices(),t==null||t.getTracks().forEach(r=>r.stop())}}return i.map((e,t)=>{let r={kind:e.kind,deviceId:e.deviceId,groupId:e.groupId,label:e.label||`${e.kind}_${t}`};return e.deviceId.length>0&&Nu.add(`${e.deviceId}_${e.kind}`),e.getCapabilities&&(r.getCapabilities=()=>e.getCapabilities()),r})})}function It(o=!1){return be.update(o?1:0).then(i=>i.audioInputs.devices)}function At(o=!1){return be.update(o?2:0).then(i=>i.videoInputs.devices)}var Xp=!1;function Qp(){return f(this,null,function*(){try{Xp||(Xp=!0,R.info(`speakers:${(yield vr()).map(o=>` ${o.deviceId.slice(0,8)}: ${o.label}`)}`))}catch(o){}})}function vr(o=!1){return f(this,null,function*(){return(ge||Re)&&(o=!1),be.update(o?1:0).then(i=>i.audioOutputs.devices)})}var Nu=new Set;function Yp(o){if(o instanceof CanvasCaptureMediaStreamTrack||!(o instanceof MediaStreamTrack))return!1;let i=o.label.toLocaleLowerCase();if(i.includes("camera")||i.includes("webcam"))return!0;let t=`${((o==null?void 0:o.getSettings())||{}).deviceId}_${_.VIDEO_INPUT}`;return!!Nu.has(t)}function Zp(o){if(o instanceof CanvasCaptureMediaStreamTrack||!(o instanceof MediaStreamTrack))return!1;let i=o.label.toLocaleLowerCase();if(i.includes("mic")||i.includes("\u9EA6\u514B\u98CE"))return!0;let t=`${((o==null?void 0:o.getSettings())||{}).deviceId}_${_.AUDIO_INPUT}`;return!!Nu.has(t)}function vu(o,i){return f(this,null,function*(){let t=(yield It()).find(r=>r.deviceId===Wr);return!i&&(t==null?void 0:t.groupId)===o||(t==null?void 0:t.groupId)===o&&t.label===i})}function Kp(s){return f(this,arguments,function*({newDeviceId:o,oldDeviceId:i,oldGroupId:e,oldLabel:t,kind:r}){return o!==i?!1:r===_.AUDIO&&o===Wr?yield vu(e,t):!0})}var Nd,Du=class extends Dn{constructor(e){super();this.log=e;c(this,"volumeMeter");c(this,"volumeMeterAfter3A");c(this,"volumeDestination");c(this,"analyser",new Rd);this.volumeMeter=new On({log:this.log}),this.volumeMeterAfter3A=new On({log:this.log}),this.volumeDestination=new Ue,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},us=class o extends fi{constructor(e){super(e,_.AUDIO);c(this,"_outputDeviceId");c(this,"_volume",1);c(this,"_destination",Ee("player").createMediaStreamDestination());c(this,"pipeline");c(this,"volumeMeterMode","worklet");c(this,"enableVolumeControlInIOS");this.enableVolumeControlInIOS=e.enableVolumeControlInIOS,this.mode=0,e.url&&(this.url=e.url),this.pipeline=new Du(this._log)}setTrack(e){}get duration(){var e;return Math.floor((((e=this.element)==null?void 0:e.duration)||0)*1e3)}get currentTime(){var e;return Math.floor((((e=this.element)==null?void 0:e.currentTime)||0)*1e3)}set currentTime(e){this.element&&(this.element.currentTime=e/1e3)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(e){if(this._log.info("initializeElement"),(ht==="15.2"||ht==="15.3"||ht==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}(ri||oi)&&ht==="18.7"&&this.bindAutoPlayEvent();let r=Nd||new Audio;r.setAttribute("autoplay","autoplay"),r.srcObject=this.getMediaStream(),this._log.info("initializeElement set srcObject"),r.muted=this.muted,this.url&&(r.crossOrigin="anonymous",r.src=this.url),this.element=r,Q(e)&&(this.element.volume=Math.min(Math.max(e,0),1)),r===Nd&&(Nd=void 0),this.options.enableTimeupdateEvent&&(this.element.ontimeupdate=()=>this.emit(he.TIME_UPDATE,this.currentTime)),this.bindElementEvents()}play(e){return f(this,null,function*(){if(!(!this.track&&!this.url))return!this.pipeline.source.node&&this.track&&this.pipeline.replaceSource(this.track),this.element||this.initializeElement(e==null?void 0:e.volume),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),this.volumeMeterMode==="worklet"?(this.pipeline.volumeMeter.init(),this.pipeline.volumeMeterAfter3A.init()):this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(Ee("player").createAnalyser()),Qp(),Le(o.prototype,this,"play").call(this)})}stop(e=0){this.pipeline.destroy(),super.stop(e)}setVolume(e){this._volume=e,this.element&&(this.element.volume=e)}setSinkId(e){return f(this,null,function*(){var t,r;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield(r=(t=this.element).setSinkId)==null?void 0:r.call(t,e))})}get useDestination(){return!!this.pipeline.stream}setLoop(e){this.element&&(this.element.loop=e)}getAudioLevel(){return this.pipeline.volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this.pipeline.volumeMeter.getInternalAudioLevel()}getInternalAudioLevelAfter3A(){return this.pipeline.volumeMeterAfter3A.getInternalAudioLevel()}},vd=class extends us{setTrack(i){this.track!==i&&(this.unbindTrackEvents(),this.track=i,this.emit(he.MEDIA_TRACK_CHANGED,i),i&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([i]))))}},Dd=class extends us{constructor(e){super(e);c(this,"_sourceElement");c(this,"_output",new Ue);this.pipeline.source.pipeTo(this.pipeline.gain),this.pipeline.gain.pipeTo(this.pipeline.volumeMeter).pipeTo(this._output),this.pipeline.gain.pipeTo(this.pipeline.destination)}setOutput(){this.mode=1,this._output.setNode(Ee("player").destination)}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var t,r,s;this._log.info("RemoteAudioPlayer set Track",e),((r=(t=this.element)==null?void 0:t.error)==null?void 0:r.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(he.MEDIA_TRACK_CHANGED,e.kind),e?(this.bindTrackEvents(),this._sourceElement?(this._log.info("RemoteAudioPlayer set Track for _sourceElement"),this._sourceElement.srcObject=new MediaStream([e])):!this.useDestination&&this.element&&(this._log.info("RemoteAudioPlayer set Track for element"),this.element.srcObject=new MediaStream([e])),this.pipeline.source.channelCount=((s=e.getSettings())==null?void 0:s.channelCount)||1,this._log.info("RemoteAudioPlayer set channelCount end"),this.pipeline.replaceSource(e),this._log.info("RemoteAudioPlayer this.pipeline.replaceSource end")):this.pipeline.source.deleteNode())}setVolume(e){if(this._volume=e,this.useDestination)this.pipeline.setVolume(e),this._log.info(`set pipeline volume: ${e}`);else if(e<=1&&!ge)this.element?(this._log.info(`set element volume: ${e}`),this.element.volume=e):this._log.info("set element volume: no element");else{if(ge)if(this.enableVolumeControlInIOS)Gp();else return;if(ee&&!this.pipeline.source.node){this._log.warn("set pipeline volume failed: no source node");return}this._log.info(`start set pipeline volume: ${e}`),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),we(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play())}}stop(e=0){this.pipeline.destroy();let t=this._sourceElement||this.element;t&&Ft&&(Nd=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}};var no=class extends j{constructor({userId:e,sdkAppId:t,mediaType:r,room:s,PlayerClass:n=r===1?Dd:pt}){var a;super();c(this,"id",an());c(this,"userId","");c(this,"isRemote");c(this,"mediaType");c(this,"room");c(this,"user");c(this,"_log");c(this,"_inputTrack");c(this,"_outputTrack");c(this,"isPlayCalled");c(this,"container",null);c(this,"player");c(this,"subVideoPlayerMap");c(this,"muted",!1);c(this,"abortCtrl");c(this,"objectFit","cover");c(this,"mirror");c(this,"rotation");c(this,"isScreen",!1);c(this,"manager");c(this,"trackSettings");c(this,"isFirstVideoFrameEmitted",!1);this.userId=e||"",this.mediaType=r,this._log=R.createLogger({parent:s==null?void 0:s.getLogger(),id:`${this.kind[0]}t`,userId:(a=s||this.room)==null?void 0:a.userId,remoteUserId:this instanceof _i?void 0:this.userId,sdkAppId:t,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof _i}),this.player=new n({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log,enableVolumeControlInIOS:s==null?void 0:s.enableVolumeControlInIOS}),this.player.on(he.PLAYER_STATE_CHANGED,d=>{if(S.emit(A.PLAYER_STATE_CHANGED,M({track:this},d)),this.emit("player-state-changed",d),d.state==="PLAYING"&&this.room){let l=!0;for(let{remoteAudioTrack:u,remoteVideoTrack:h,remoteAuxiliaryTrack:p}of[...this.room.remotePublishedUserMap.values()])if(u.isAvailable&&!u.player.isPlaying||h.isAvailable&&!h.player.isPlaying||p.isAvailable&&!p.player.isPlaying){l=!1;break}l&&br()&&Vp()}}),this.kind===_.VIDEO&&(this.player.on(he.LOADED_DATA,()=>{this.emitFirstVideoFrameEvent(he.LOADED_DATA),S.emit(A.VIDEO_LOADED_DATA,{track:this})}),this.player.on(he.LOADED_META_DATA,()=>{this.emitFirstVideoFrameEvent(he.LOADED_META_DATA)}),this.player.on(he.MEDIA_TRACK_CHANGED,d=>{var l;(l=this.subVideoPlayerMap)==null||l.forEach(u=>u.setTrack(d))}),this.player.on(he.RESIZE,d=>{this.emitFirstVideoFrameEvent(he.RESIZE),this.emit("video-size-changed",M({userId:this.userId,streamType:this.mediaType===2?"auxiliary":"main"},d))})),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(he.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||R}get kind(){return this.mediaType===1?_.AUDIO:_.VIDEO}get isAudio(){return this.kind===_.AUDIO}get strMediaType(){return this.mediaType===4?_.VIDEO:this.mediaType===2?_.SCREEN:_.AUDIO}get streamType(){return(this.mediaType&2)===0?"main":"auxiliary"}get isMediaTrackActive(){return this.mediaTrack?!this.mediaTrack.muted&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled:!1}play(e,t){return f(this,null,function*(){let r=Ae(e)?e[0]:e;if(this.isPlayCalled){this.log.info(`play update options: ${JSON.stringify(t)}`),t&&!T(t.muted)&&this.setPlayerMute(t.muted),t&&!T(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof pt&&(this.player.setObjectFit(this.objectFit),this.container!==r&&r&&(this.container=r,this.player.setContainer(r)),Ae(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t)));return}if(t&&!T(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===_.VIDEO)&&this.setPlayerMute(!0),t&&!T(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof pt&&(this.player.setObjectFit(this.objectFit),t&&!T(t.poster)&&this.player.setPoster(t.poster)),this.isPlayCalled=!0,r&&(this.container=r,this.player instanceof pt&&this.player.setContainer(r)),S.emit(A.PLAY_TRACK_START,{track:this}),!this._outputTrack){this.log.info("play has not mediaTrack, abort");return}this._log.info(`play with options: ${JSON.stringify(t)}`);try{this.player.setTrack(this.playerMediaTrack),yield this.player.play(t),Ae(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(s){throw this.handleAutoPlayFailed(s),s}})}setMirror(e,t){if(this.isScreen||this.kind!==_.VIDEO||T(e)||e===this.mirror)return;this.mirror=e;let r=this.player;t&&(r=t);let s=this.manager;if(ue(this.mirror)){r.setViewMirror(this.mirror),!this.isRemote&&s&&(s.mirror=!1);return}switch(this.mirror){case"view":{s&&(s.mirror=!1),r.setViewMirror(!0);break}case"publish":{s&&(s.mirror=!0),r.setViewMirror(!0);break}case"both":s&&(s.mirror=!0),r.setViewMirror(!1)}}playSubContainer(e,t){return f(this,null,function*(){if(!this._outputTrack||this.kind===_.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((s,n)=>{var a;e.find(d=>n===d)||(s.stop(),(a=this.subVideoPlayerMap)==null||a.delete(n))});for(let[s,n]of e.entries()){let a=this.subVideoPlayerMap.get(n);a?t&&(T(t.objectFit)||a.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new pt({id:this.userId||this.id,track:this.playerMediaTrack,container:n,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:`vp-sub${s+1}`})}))}let r=[...this.subVideoPlayerMap.values()];for(let s of r)s.setViewMirror(this.player.mirror),yield s.play()})}setAudioOutput(e){return this.player.setSinkId(e)}setAudioVolume(e){this.player.setVolume(e)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var e;return((e=this.player)==null?void 0:e.getInternalAudioLevel())||0}stop(e=!1){this.isPlayCalled&&(this.isPlayCalled=!1,this.isFirstVideoFrameEmitted=!1,this.player&&(this.log.info(`stop ${this.kind} player`),this.player.stop(La(this)&&!e?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(t=>{t.stop()}),this.container=null)}resume(){return f(this,null,function*(){var e;this.isPlayCalled&&(yield(e=this.player)==null?void 0:e.resume())})}close(){this.log.info("close"),this.isPlayCalled&&this.stop(!0)}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),S.emit(e?A.TRACK_MUTED:A.TRACK_UNMUTED,{track:this})}setPlayerMute(e){this.player.setMuted(e)}get mediaTrack(){return this._inputTrack||null}get outMediaTrack(){return this._outputTrack||null}get playerMediaTrack(){return this.outMediaTrack}installTrackEvent(e){tt(e,e).add(_.MUTE,this.onTrackMuted).add(_.UNMUTE,this.onTrackUnmuted).add(_.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===_.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){we(e)}setInputMediaStreamTrack(e){var r;let t=this._inputTrack;if(e!==t)return this._inputTrack=e,this.trackSettings=(r=e.getSettings)==null?void 0:r.call(e),e.enabled=!this.muted,t&&this.uninstallTrackEvent(t),this.installTrackEvent(e),this.emit("input-media-track-changed",e||null,t||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var r;let t=this._outputTrack;e!==t&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",(r=e.getSettings)==null?void 0:r.call(e).deviceId,e.label),this._outputTrack=e,this._inputTrack&&(this._outputTrack.contentHint=this._inputTrack.contentHint,this._outputTrack.enabled=this._inputTrack.enabled),this.updatePlayingState(!!e),this.emit("output-media-track-changed",e))}setMediaType(e){this.mediaType=e}updatePlayingState(e){var t,r;if(this.isPlayCalled){if(e){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped){this.player.play().catch(s=>this.handleAutoPlayFailed(s)),this.log.info(`playing state updated, play ${this.kind}`);return}}else if(!this.player.isStopped){if(La(this)&&this.isAudio&&((t=this.user)!=null&&t.muteState.hasAudio)&&((r=this.user)!=null&&r.muteState.audioMuted))return;this.player.stop(La(this)?this.jitterBufferDelay:0),this.log.info(`playing state updated, stop ${this.kind}`);return}}this.log.debug(`updatePlayingState abort ${this.isPlayCalled} ${e} ${this.player.isStopped}`)}handleAutoPlayFailed(e){return f(this,null,function*(){var r;this.log.warn("handleAutoPlayFailed",e);let t=()=>{this.resume().then(()=>{document.removeEventListener("click",t,!0)})};if(this.room&&this.room.enableAutoPlayDialog){if((ri||oi)&&(yield Ke(100),(r=this.player)!=null&&r.isPlaying))return;ns()}else document.addEventListener("click",t,!0);S.once(A.LOCAL_TRACK_CAPTURE_SUCCESS,({track:s})=>{s.kind==="audio"&&br()&&!this.player.isPlaying&&this.isRemote&&this.isAvailable&&t()}),this.emit("error",e)})}getVideoFrame(){return this.player instanceof pt?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(e){var n,a,d;if(this.isFirstVideoFrameEmitted)return;let t=(n=this.mediaTrack)==null?void 0:n.getSettings(),r=(t==null?void 0:t.width)||((a=this.player.element)==null?void 0:a.videoWidth)||0,s=(t==null?void 0:t.height)||((d=this.player.element)==null?void 0:d.videoHeight)||0;e===he.RESIZE&&!r&&!s||e===he.LOADED_META_DATA&&!r&&!s||(e===he.LOADED_DATA&&!r&&!s&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,bt(this.rotation)&&([r,s]=[s,r]),this.emit("first-video-frame",{width:r,height:s,streamType:this.streamType,userId:this.isRemote?this.userId:""}))}onTrackMuted(){this._log.warn(`${this.kind} track is unable to provide media output`)}onTrackUnmuted(){this._log.info(`${this.kind} track is able to provide media output`)}onTrackEnded(){this._log.warn(`${this.kind} track ended`)}};D([ye([],j.INIT,{sync:!0})],no.prototype,"close",1);var qT=Object.prototype.hasOwnProperty,{toString:yb}=Object.prototype;function jT(o){if(o==null)return!0;if(typeof o=="boolean")return!1;if(typeof o=="number")return o===0;if(typeof o=="string"||typeof o=="function"||Array.isArray(o))return o.length===0;if(o instanceof Error)return o.message==="";if(dt(o))switch(Object.prototype.toString.call(o)){case"[object File]":case"[object Map]":case"[object Set]":return o.size===0;case"[object Object]":{for(let i in o)if(qT.call(o,i))return!1;return!0}}return!1}var gi=jT;var XT=function(o){return f(this,null,function*(){let i=QT(o);R.info(`getUserMedia with constraints: ${JSON.stringify(i)}`);let e=[],t=[],r=["label","deviceId","groupId"];if(i.audio&&(e=yield It(),R.info(`microphones: ${gt(e.map(s=>w(M({},s),{groupId:s.groupId.substring(0,8)})),{keysToInclude:r})}`)),i.video&&(t=yield At(),R.info(`cameras: ${gt(t,{keysToInclude:r})}`),!ue(i.video)&&i.video.facingMode==="user"&&!i.video.deviceId)){let n=t.filter(a=>!a.label.includes("infrared")).find(a=>a.label.includes("facing front"));n&&(i.video.deviceId=n.deviceId,R.info(`exclude infrared camera: ${JSON.stringify(i)}`))}try{let s=yield navigator.mediaDevices.getUserMedia(i);return nu&&s.getTracks().forEach(n=>{var d;let a=n.getCapabilities();R.info(`${n.kind} capabilities: ${gt(a,{keysToInclude:Sa})}`),!T(o.echoCancellation)&&((d=a.echoCancellation)==null?void 0:d.indexOf(o.echoCancellation))===-1&&R.warn(`Invalid argument for 'echoCancellation'. Expected one of [${JSON.stringify(a.echoCancellation)}], but received '${o.echoCancellation}'`)}),i.audio&&Nr(),s}catch(s){let{message:n}=s;throw s.name==="NotFoundError"&&(o.video&&t&&t.length===0&&(n=$({key:B.CAMERA_NOT_FOUND})),o.audio&&e&&e.length===0&&(n=$({key:B.MICROPHONE_NOT_FOUND}))),new v({code:I.INITIALIZE_FAILED,name:s.name,message:n,constraint:s.constraint})}})},zT=Ri({retryFunction:XT,settings:{retries:3,timeout:500},onError:({error:o,retry:i,reject:e,retryFuncArgs:t,retriedCount:r})=>{let s=r+1;o.name==="NotReadableError"||o.name==="OverconstrainedError"||o.name==="AbortError"?(s===1?(t[0].video&&(t[0].maxResolution=!1,(!Re||t[0].width*t[0].height<=1920*1080)&&t[0].frameRate&&(t[0].frameRate=t[0].frameRate>10?10:5)),t[0].retryWhenExactFailed&&t[0].useExactDeviceId&&(t[0].useExactDeviceId=!1)):s===2?t[0].useDeviceIdOnly=!0:s===3&&!t[0].useExactDeviceId&&(t[0].useTrueAsConstraint=!0),i()):e(o),t[0].microphoneId&&ef(t[0].microphoneId,!1),t[0].cameraId&&ef(t[0].cameraId,!0)},onRetrying:o=>{R.warn(`getUserMedia NotReadableError observed, retrying [${o}/3]`)},onRetryFailed:o=>{se.logFailedEvent({eventType:Ze.GET_USER_MEDIA_RETRY,error:o})},onRetrySuccess:o=>{se.logSuccessEvent({eventType:Ze.GET_USER_MEDIA_RETRY}),se.uploadEvent({log:`stat-${Ze.GET_USER_MEDIA_RETRY}-success-${o}`})}});function ef(o,i){return f(this,null,function*(){let t=(i?yield At():yield It()).find(r=>r.deviceId===o);t&&le(t.getCapabilities)&&R.warn(gt(t.getCapabilities(),{keysToInclude:Sa}))})}function QT(o){return{audio:YT(o),video:ZT(o)}}function YT(o){if(!o.audio)return!1;if(o.useTrueAsConstraint)return!0;let i={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:o.sampleRate};return!gi(o.microphoneId)&&(i.deviceId=o.useExactDeviceId?{exact:o.microphoneId}:o.microphoneId,o.useDeviceIdOnly)?i:(Q(o.channelCount)&&(i.channelCount=o.channelCount),(ue(o.echoCancellation)||o.echoCancellation==="remote-only"||o.echoCancellation==="all")&&(i.echoCancellation=o.echoCancellation),ue(o.noiseSuppression)&&!o.noiseSuppression&&(i.noiseSuppression=!1),ue(o.autoGainControl)&&!o.autoGainControl&&(i.autoGainControl=!1),gi(i)?!0:i)}function ZT(o){if(!o.video)return!1;if(o.useTrueAsConstraint)return!0;let{maxResolution:i=!0}=o,e={};return o.cameraId?e.deviceId=o.useExactDeviceId?{exact:o.cameraId}:o.cameraId:o.facingMode&&(e.facingMode=o.facingMode),o.useDeviceIdOnly&&!gi(e)?e:(o.width&&(e.width={ideal:o.width},i&&!ee&&(e.width.max=o.width)),o.height&&(e.height={ideal:o.height},i&&!ee&&(e.height.max=o.height)),ee&&si&&o.width&&o.height&&o.width*o.height<352*288&&(e.width=o.width,e.height=o.height),o.frameRate&&(e.frameRate=o.frameRate),gi(e)?!0:e)}var tf=zT;function Md(o){return Y((i,e)=>function(...t){return f(this,null,function*(){return yield o.apply(this,t),i.apply(this,t)})})}function Ct(o){return Y((i,e)=>function(...t){return f(this,null,function*(){let r=yield i.apply(this,t);return yield o.call(this,...t),r})})}function Od(o){return Y((i,e)=>function(...t){return f(this,null,function*(){try{return yield i.apply(this,t)}catch(r){o.call(this,r)}})})}function Y(o){return function(i,e,t){return t.value=o(t.value,e),t}}var rf=(()=>{let o=!1,i=document.visibilityState;return()=>{document.visibilityState!==i&&R.info(`visibility change: ${document.visibilityState}`),!o&&(document.addEventListener("visibilitychange",()=>{R.info(`visibility change: ${document.visibilityState}`),i=document.visibilityState}),o=!0)}})();var KT=0,kd=class{constructor(){c(this,"log",R.createLogger({id:`fq${++KT}`}));c(this,"isRunning",!1);c(this,"queue",[])}get length(){return this.queue.length}get lastQueueItem(){return this.length===0?null:this.queue[this.length-1]}push(i,e=!1){var s,n;let t=M({},i),r=new Promise((a,d)=>{t.resolve=a,t.reject=d});return t.promise=r,e?this.length<=1?this.queue.push(t):(n=(s=this.lastQueueItem)==null?void 0:s.promise)==null||n.then(t.resolve,t.reject):this.queue.push(t),this.log.debug(`push ${this.length}`),this.isRunning||this.callNext(),r}shift(){let i=this.queue.shift();return this.log.debug(`shift ${this.length}`),i}callNext(){if(this.isRunning||this.length===0)return;this.log.debug("callNext ",this.length);let{fn:i,args:e,context:t,resolve:r,reject:s}=this.queue[0];this.isRunning=!0,i.apply(t,e).then(r,s).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},Pd=new WeakMap,Ld=new WeakMap;function ir(o=!1){return function(i,e,t){let r=t.value;return t.value=function(...s){let n=Pd.get(this)||new kd;return Pd.set(this,n),n.push({fn:r,args:s,context:this},o)},t}}function xd(o){return function(i,e,t){let r=t.value;return t.value=function(...s){var a,d,l;let n=[];return(d=(a=Pd.get(this))==null?void 0:a.queue)==null||d.forEach(u=>n.push(u)),(l=Ld.get(this))==null||l.forEach(u=>u==null?void 0:u.queue.forEach(h=>n.push(h))),n.forEach(u=>{u.reject(new v({code:I.API_CALL_ABORTED,message:o}))}),Pd.delete(this),Ld.delete(this),r.apply(this,s)},t}}function Ti(o){return function(i,e,t){let r=t.value,s=n=>o(...n);return t.value=function(...n){let a=Ld.get(this)||new Map,d=a.get(s(n))||new kd;return a.set(s(n),d),Ld.set(this,a),d.push({fn:r,args:n,context:this})},t}}function Rt(o,i){return Y((e,t)=>function(...r){let s=o;try{let n=e.apply(this,r),a=V();return Tr(n)?n.then(d=>(i?y.addSuccessEvent({key:s,cost:V()-a}):y.addSuccessEvent({key:s}),d)).catch(d=>{throw y.addFailedEvent({key:s,error:d}),d}):(y.addSuccessEvent({key:s}),n)}catch(n){throw y.addFailedEvent({key:s,error:n}),n}})}var fh={};Bi(fh,{Events:()=>Oe,Inspect:()=>Ht,LastSink:()=>ao,Sink:()=>X,Subscribe:()=>co,TimeoutError:()=>Pn,audit:()=>wE,bindCallback:()=>IE,bindNodeCallback:()=>AE,buffer:()=>dE,bufferCount:()=>aE,bufferTime:()=>tS,call:()=>of,catchError:()=>hh,combineLatest:()=>nf,concat:()=>iE,concatMap:()=>jE,concatMapTo:()=>XE,count:()=>yE,create:()=>ae,debounce:()=>UE,debounceTime:()=>VE,defer:()=>af,delay:()=>iS,deliver:()=>z,dispose:()=>wd,elementAt:()=>FE,empty:()=>Un,every:()=>GE,exhaustMap:()=>YE,exhaustMapTo:()=>ZE,expand:()=>rS,filter:()=>$t,find:()=>BE,findIndex:()=>HE,first:()=>$E,fromAnimationFrame:()=>EE,fromArray:()=>mE,fromEvent:()=>de,fromEventPattern:()=>pE,fromFetch:()=>fE,fromIterable:()=>_E,fromPromise:()=>lf,fromReadableStream:()=>TE,fromReader:()=>gE,groupBy:()=>KE,identity:()=>eE,ignoreElements:()=>DE,iif:()=>oE,inspect:()=>sf,interval:()=>wu,last:()=>WE,map:()=>Vn,mapTo:()=>qE,max:()=>bE,merge:()=>Ln,mergeMap:()=>zE,mergeMapTo:()=>QE,min:()=>NE,never:()=>CE,nothing:()=>pe,of:()=>hE,pairwise:()=>JE,pipe:()=>ce,race:()=>Lu,range:()=>SE,reduce:()=>Uu,retry:()=>aS,scan:()=>uh,setAsapScheduler:()=>uE,share:()=>rr,shareReplay:()=>rE,skip:()=>OE,skipUntil:()=>kE,skipWhile:()=>Hd,startWith:()=>xn,subject:()=>rt,subscribe:()=>Te,sum:()=>vE,switchMap:()=>Mr,switchMapTo:()=>mo,take:()=>or,takeLast:()=>ME,takeUntil:()=>ke,takeWhile:()=>uf,tap:()=>Fn,throttle:()=>LE,throwError:()=>RE,timeInterval:()=>eS,timeout:()=>nS,timer:()=>wn,toPromise:()=>oS,toReadableStream:()=>sS,withLatestFrom:()=>nE,zip:()=>sE});function pe(...o){}var of=o=>o(),eE=o=>o;function wd(){this.dispose()}var sf=()=>typeof __FASTRX_DEVTOOLS__!="undefined",tE=1,Ht=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(i){let e=new Mu(i,this,this.streamId++);return Oe.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},ao=class{constructor(){this.defers=new Set,this.disposed=!1}next(i){}complete(){this.dispose()}error(i){this.dispose()}get bindDispose(){return()=>this.dispose()}dispose(){this.disposed=!0,this.complete=pe,this.error=pe,this.next=pe,this.dispose=pe,this.subscribe=pe,this.doDefer()}subscribe(i){return i instanceof Ht?i.subscribe(this):i(this),this}get bindSubscribe(){return i=>this.subscribe(i)}doDefer(){this.defers.forEach(of),this.defers.clear()}defer(i){this.defers.add(i)}removeDefer(i){this.defers.delete(i)}reset(){this.disposed=!1,delete this.complete,delete this.next,delete this.dispose,delete this.next,delete this.subscribe}resetNext(){delete this.next}resetComplete(){delete this.complete}resetError(){delete this.error}},X=class extends ao{constructor(i){super(),this.sink=i,i.defer(this.bindDispose)}next(i){this.sink.next(i)}complete(){this.sink.complete()}error(i){this.sink.error(i)}},co=class extends ao{constructor(i,e=pe,t=pe,r=pe){if(super(),this._next=e,this._error=t,this._complete=r,this.then=pe,i instanceof Ht){let s={toString:()=>"subscribe",id:0,source:i};this.defer(()=>{Oe.defer(s,0)}),Oe.create(s),Oe.pipe(s),this.sourceId=s.id,this.subscribe(i),Oe.subscribe({id:s.id,end:!0}),e==pe?this._next=n=>Oe.next(s,0,n):this.next=n=>{Oe.next(s,0,n),e(n)},r==pe?this._complete=()=>Oe.complete(s,0):this.complete=()=>{this.dispose(),Oe.complete(s,0),r()},t==pe?this._error=n=>Oe.complete(s,0,n):this.error=n=>{this.dispose(),Oe.complete(s,0,n),t(n)}}else this.subscribe(i)}next(i){this._next(i)}complete(){this.dispose(),this._complete()}error(i){this.dispose(),this._error(i)}};function ce(o,...i){return i.reduce((e,t)=>t(e),o)}function ae(o,i,e){if(sf()){let t=Object.defineProperties(Object.setPrototypeOf(o,Ht.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:i,writable:!0,configurable:!0},args:{value:e,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});Oe.create(t);for(let r=0;r<e.length;r++){let s=e[r];typeof s=="function"&&s instanceof Ht&&Oe.addSource(t,s)}return t}return o}function z(o,i){return function(...e){return t=>{if(t instanceof Ht){let r=ae(s=>{let n=new o(s,...e);n.sourceId=r.id,n.subscribe(t)},i,arguments);return r.source=t,Oe.pipe(r),r}else return r=>t(new o(r,...e))}}}function Dr(o,i){window.postMessage({source:"fastrx-devtools-backend",payload:{event:o,payload:i}})}var Mu=class extends X{constructor(i,e,t){super(i),this.source=e,this.id=t,this.sourceId=i.sourceId,this.defer(()=>{Oe.defer(this.source,this.id)})}next(i){Oe.next(this.source,this.id,i),this.sink.next(i)}complete(){Oe.complete(this.source,this.id),this.sink.complete()}error(i){Oe.complete(this.source,this.id,i),this.sink.error(i)}},Oe={addSource(o,i){Dr("addSource",{id:o.id,name:o.toString(),source:{id:i.id,name:i.toString()}})},next(o,i,e){Dr("next",{id:o.id,streamId:i,data:e&&e.toString()})},subscribe({id:o,end:i},e){Dr("subscribe",{id:o,end:i,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(o,i,e){Dr("complete",{id:o.id,streamId:i,err:e?e.toString():null})},defer(o,i){Dr("defer",{id:o.id,streamId:i})},pipe(o){Dr("pipe",{name:o.toString(),id:o.id,source:{id:o.source.id,name:o.source.toString()}})},update(o){Dr("update",{id:o.id,name:o.toString()})},create(o){o.id||(o.id=tE++),Dr("create",{name:o.toString(),id:o.id})}},Pn=class extends Error{constructor(i){super(`timeout after ${i}ms`),this.timeout=i}};var Ud=class extends ao{constructor(i){super(),this.source=i,this.sinks=new Set}add(i){i.defer(()=>this.remove(i)),this.sinks.add(i).size===1&&(this.reset(),this.subscribe(this.source))}remove(i){this.sinks.delete(i),this.sinks.size===0&&this.dispose()}next(i){this.sinks.forEach(e=>e.next(i))}complete(){this.sinks.forEach(i=>i.complete()),this.sinks.clear()}error(i){this.sinks.forEach(e=>e.error(i)),this.sinks.clear()}};function rr(){return o=>{let i=new Ud(o);if(o instanceof Ht){let e=ae(t=>{i.add(t)},"share",arguments);return i.sourceId=e.id,e.source=o,Oe.pipe(e),e}return ae(i.add.bind(i),"share",arguments)}}function Ln(...o){return ae(i=>{let e=new X(i),t=o.length;e.complete=()=>{--t===0&&i.complete()},o.forEach(e.bindSubscribe)},"merge",arguments)}function Lu(...o){return ae(i=>{let e=new Map;o.forEach(t=>{let r=new X(i);e.set(t,r),r.complete=()=>{e.delete(t),e.size===0?i.complete():r.dispose()},r.next=s=>{e.delete(t),e.forEach(n=>n.dispose()),r.resetNext(),r.resetComplete(),r.next(s)}}),o.forEach(t=>e.get(t).subscribe(t))},"race",arguments)}function iE(...o){return ae(i=>{let e=0,t=o.length,r=new X(i);r.complete=()=>{e<t&&!r.disposed?(r.doDefer(),r.subscribe(o[e++])):i.complete()},r.complete()},"concat",arguments)}function rE(o){return i=>{let e=new Ud(i),t=[];return e.next=function(r){t.push(r),t.length>o&&t.shift(),this.sinks.forEach(s=>s.next(r))},ae(r=>{r.defer(()=>e.remove(r)),t.forEach(s=>r.next(s)),e.add(r)},"shareReplay",arguments)}}function oE(o,i,e){return ae(t=>o()?i(t):e(t),"iif",arguments)}function nf(...o){return ae(i=>{let e=o.length,t=e,r=e,s=new Array(e),n=()=>{--r===0&&i.complete()},a=(d,l)=>{let u=new X(i);u.next=h=>{t--,u.next=p=>{s[l]=p,t===0&&i.next(s)},u.next(h)},u.complete=n,u.subscribe(d)};o.forEach(a)},"combineLatest",arguments)}function sE(...o){return ae(i=>{let e=o.length,t=e,r=new Array(e),s=()=>{--t===0&&i.complete()},n=(a,d)=>{let l=new X(i),u=[];r[d]=u,l.next=h=>{u.push(h),r.every(p=>p.length)&&i.next(r.map(p=>p.shift()))},l.complete=s,l.subscribe(a)};o.forEach(n)},"zip",arguments)}function xn(...o){return i=>ae((e,t=0,r=o.length)=>{for(;t<r&&!e.disposed;)e.next(o[t++]);e.disposed||e.subscribe(i)},"startWith",arguments)}var Ou=class extends X{constructor(i,...e){super(i);let t=new X(this.sink);t.next=r=>this.buffer=r,t.complete=pe,t.subscribe(nf(...e))}next(i){this.buffer&&this.sink.next([i,...this.buffer])}},nE=z(Ou,"withLatestFrom"),ku=class extends X{constructor(i,e,t){super(i),this.bufferSize=e,this.startBufferEvery=t,this.buffer=[],this.count=0,this.startBufferEvery&&(this.buffers=[[]])}next(i){this.startBufferEvery?(this.count++===this.startBufferEvery&&(this.buffers.push([]),this.count=1),this.buffers.forEach(e=>{e.push(i)}),this.buffers[0].length===this.bufferSize&&this.sink.next(this.buffers.shift())):(this.buffer.push(i),this.buffer.length===this.bufferSize&&(this.sink.next(this.buffer),this.buffer=[]))}complete(){this.buffer.length?this.sink.next(this.buffer):this.buffers.length&&this.buffers.forEach(i=>this.sink.next(i)),super.complete()}},aE=z(ku,"bufferCount"),Pu=class extends X{constructor(i,e){super(i),this.buffer=[];let t=new X(i);t.next=r=>{i.next(this.buffer),this.buffer=[]},t.complete=pe,t.subscribe(e)}next(i){this.buffer.push(i)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},dE=z(Pu,"buffer");var cE=function(o,i,e,t){function r(s){return s instanceof e?s:new e(function(n){n(s)})}return new(e||(e=Promise))(function(s,n){function a(u){try{l(t.next(u))}catch(h){n(h)}}function d(u){try{l(t.throw(u))}catch(h){n(h)}}function l(u){u.done?s(u.value):r(u.value).then(a,d)}l((t=t.apply(o,i||[])).next())})};function rt(o){let i=arguments,e=rr()(ae(t=>{e.next=r=>t.next(r),e.complete=()=>t.complete(),e.error=r=>t.error(r),o&&t.subscribe(o)},"subject",i));return e.next=pe,e.complete=pe,e.error=pe,e}function af(o){return ae(i=>i.subscribe(o()),"defer",arguments)}var hs={promise:o=>{Promise.resolve().then(o)},setImmediate:typeof setImmediate!="undefined"?o=>setImmediate(o):null,setTimeout:o=>setTimeout(o,0)},lE=()=>typeof Promise!="undefined"?hs.promise:hs.setImmediate?hs.setImmediate:hs.setTimeout,xu=lE(),df=o=>i=>{xu(()=>o(i))},uE=o=>{typeof o=="function"?xu=o:hs[o]&&(xu=hs[o])};var cf=o=>df(i=>{for(let e=0;!i.disposed&&e<o.length;e++)i.next(o[e]);i.complete()});function hE(...o){return ae(cf(o),"of",arguments)}function mE(o){return ae(cf(o),"fromArray",arguments)}function wu(o){return ae(i=>{let e=0,t=setInterval(()=>i.next(e++),o);return i.defer(()=>{clearInterval(t)}),"interval"},"interval",arguments)}function wn(o,i){return ae(e=>{let t=0,r=setTimeout(()=>{if(e.removeDefer(s),e.next(t++),i){let n=setInterval(()=>e.next(t++),i);e.defer(()=>{clearInterval(n)})}else e.complete()},o),s=()=>clearTimeout(r);e.defer(s)},"timer",arguments)}function Vd(o,i){return e=>{let t=r=>e.next(r);e.defer(()=>i(t)),o(t)}}function pE(o,i){return ae(Vd(o,i),"fromEventPattern",arguments)}function de(o,i){if("on"in o&&"off"in o)return ae(Vd(e=>o.on(i,e),e=>o.off(i,e)),"fromEvent",arguments);if("addListener"in o&&"removeListener"in o)return ae(Vd(e=>o.addListener(i,e),e=>o.removeListener(i,e)),"fromEvent",arguments);if("addEventListener"in o)return ae(Vd(e=>o.addEventListener(i,e),e=>o.removeEventListener(i,e)),"fromEvent",arguments);throw"target is not a EventDispachter"}function lf(o){return ae(i=>{o.then(i.next.bind(i),i.error.bind(i))},"fromPromise",arguments)}function fE(o,i){return ae(af(()=>lf(fetch(o,i))),"fromFetch",arguments)}function _E(o){return ae(df(i=>{try{for(let e of o){if(i.disposed)return;i.next(e)}i.complete()}catch(e){i.error(e)}}),"fromIterable",arguments)}function gE(o){let i=e=>cE(this,void 0,void 0,function*(){if(e.disposed)return;let{done:t,value:r}=yield o.read();if(t){e.complete();return}else e.next(r),i(e)});return ae(e=>{i(e)},"fromReader",arguments)}function TE(o){return ae(i=>{let e=new AbortController,t=e.signal;i.defer(()=>e.abort("cancelled")),o.pipeTo(new WritableStream({write(r){i.next(r)},close(){i.complete()},abort(r){i.error(r)}}),{signal:t}).then(()=>i.complete(),r=>i.error(r))},"fromReadableStream",arguments)}function EE(){return ae(o=>{let i=requestAnimationFrame(function e(t){o.disposed||(o.next(t),i=requestAnimationFrame(e))});o.defer(()=>cancelAnimationFrame(i))},"fromAnimationFrame",arguments)}function SE(o,i){return ae((e,t=o,r=i+o)=>{for(;t<r&&!e.disposed;)e.next(t++);return e.complete(),"range"},"range",arguments)}function IE(o,i,...e){return ae(t=>{let r=e.concat(s=>(t.next(s),t.complete()));o.apply(i,r)},"bindCallback",arguments)}function AE(o,i,...e){return ae(t=>{let r=e.concat((s,n)=>s?t.error(s):(t.next(n),t.complete()));o.apply(i,r)},"bindNodeCallback",arguments)}function CE(){return ae(()=>{},"never",arguments)}function RE(o){return ae(i=>i.error(o),"throwError",arguments)}function Un(){return ae(o=>o.complete(),"empty",arguments)}var lo=class extends X{constructor(i,e,t){super(i),this.f=e;let r=()=>{this.sink.next(this.acc),this.sink.complete()};typeof t=="undefined"?this.next=s=>{this.acc=s,this.complete=r,this.resetNext()}:(this.acc=t,this.complete=r)}next(i){this.acc=this.f(this.acc,i)}},Uu=z(lo,"reduce"),yE=o=>z(lo,"count")((i,e)=>o(e)?i+1:i,0),bE=()=>z(lo,"max")(Math.max),NE=()=>z(lo,"min")(Math.min),vE=()=>z(lo,"sum")((o,i)=>o+i,0);var Vu=class extends X{constructor(i,e,t){super(i),this.filter=e,this.thisArg=t}next(i){this.filter.call(this.thisArg,i)&&this.sink.next(i)}},$t=z(Vu,"filter"),Fu=class extends X{next(i){}},DE=z(Fu,"ignoreElements"),Bu=class extends X{constructor(i,e){super(i),this.count=e}next(i){this.sink.next(i),--this.count===0&&(this.doDefer(),this.complete())}},or=z(Bu,"take"),Hu=class extends X{constructor(i,e){super(i);let t=new X(i);t.next=()=>{t.doDefer(),i.complete()},t.complete=wd,t.subscribe(e)}},ke=z(Hu,"takeUntil"),$u=class extends X{constructor(i,e){super(i),this.f=e}next(i){this.f(i)?this.sink.next(i):(this.doDefer(),this.complete())}},uf=z($u,"takeWhile"),ME=o=>Uu((i,e)=>(i.push(e),i.length>o&&i.shift(),i),[]),Wu=class extends X{constructor(i,e){super(i),this.count=e}next(i){--this.count===0&&(this.next=super.next)}},OE=z(Wu,"skip"),Gu=class extends X{constructor(i,e){super(i),i.next=pe;let t=new X(i);t.next=()=>{t.doDefer(),i.resetNext()},t.complete=wd,t.subscribe(e)}},kE=z(Gu,"skipUntil"),Ju=class extends X{constructor(i,e){super(i),this.f=e}next(i){this.f(i)||(this.next=super.next,this.next(i))}},Hd=z(Ju,"skipWhile"),PE={leading:!0,trailing:!1},qu=class extends X{constructor(i,e,t){super(i),this.durationSelector=e,this.trailing=t}cacheValue(i){this.last=i,this.disposed&&this.throttle(i)}send(i){this.sink.next(i),this.throttle(i)}throttle(i){this.reset(),this.subscribe(this.durationSelector(i))}next(){this.complete()}complete(){this.dispose(),this.trailing&&this.send(this.last)}},Fd=class extends X{constructor(i,e,t=PE){super(i),this.durationSelector=e,this.config=t,this._throttle=new qu(this.sink,this.durationSelector,this.config.trailing),this._throttle.dispose()}next(i){this._throttle.disposed&&this.config.leading?this._throttle.send(i):this._throttle.cacheValue(i)}complete(){this._throttle.throttle=pe,this._throttle.complete(),super.complete()}},LE=z(Fd,"throttle"),xE={leading:!1,trailing:!0},wE=o=>z(Fd,"audit")(o,xE),ju=class extends X{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},Bd=class extends X{constructor(i,e){super(i),this.durationSelector=e,this._debounce=new ju(this.sink),this._debounce.dispose()}next(i){this._debounce.dispose(),this._debounce.reset(),this._debounce.last=i,this._debounce.subscribe(this.durationSelector(i))}complete(){this._debounce.complete(),super.complete()}},UE=z(Bd,"debounce"),VE=o=>z(Bd,"debounceTime")(i=>wn(o)),Xu=class extends X{constructor(i,e,t){super(i),this.count=e,this.defaultValue=t}next(i){this.count--===0&&(this.defaultValue=i,this.doDefer(),this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("not enough elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},FE=z(Xu,"elementAt"),BE=o=>i=>or(1)(Hd(e=>!o(e))(i)),zu=class extends X{constructor(i,e){super(i),this.f=e,this.i=0}next(i){this.f(i)?(this.sink.next(this.i++),this.doDefer(),this.complete()):++this.i}},HE=z(zu,"findIndex"),Qu=class extends X{constructor(i,e,t){super(i),this.f=e,this.defaultValue=t,this.index=0}next(i){(!this.f||this.f(i,this.index++))&&(this.defaultValue=i,this.doDefer(),this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},$E=z(Qu,"first"),Yu=class extends X{constructor(i,e,t){super(i),this.f=e,this.defaultValue=t,this.index=0}next(i){(!this.f||this.f(i,this.index++))&&(this.defaultValue=i)}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},WE=z(Yu,"last"),Zu=class extends X{constructor(i,e){super(i),this.predicate=e,this.index=0}next(i){this.predicate(i,this.index++)?this.result=!0:(this.result=!1,this.doDefer(),this.complete())}complete(){if(this.result===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.result);super.complete()}},GE=z(Zu,"every");var Ku=class extends X{constructor(i,e,t){super(i),this.f=e,typeof t=="undefined"?this.next=r=>{this.acc=r,this.resetNext(),this.sink.next(this.acc)}:this.acc=t}next(i){this.sink.next(this.acc=this.f(this.acc,i))}},uh=z(Ku,"scan"),eh=class extends X{constructor(){super(...arguments),this.hasLast=!1}next(i){this.hasLast?this.sink.next([this.last,i]):this.hasLast=!0,this.last=i}},JE=z(eh,"pairwise"),$d=class extends X{constructor(i,e,t){super(i),this.mapper=e,this.thisArg=t}next(i){super.next(this.mapper.call(this.thisArg,i))}},Vn=z($d,"map"),qE=o=>z($d,"mapTo")(i=>o),uo=class extends X{constructor(i,e,t){super(i),this.data=e,this.context=t}next(i){let e=this.context.combineResults;e?this.sink.next(e(this.data,i)):this.sink.next(i)}tryComplete(){this.context.resetComplete(),this.dispose()}},ho=class o extends X{constructor(i,e,t){super(i),this.makeSource=e,this.combineResults=t,this.index=0}subInner(i,e){let t=this.currentSink=new e(this.sink,i,this);this.complete===o.prototype.complete&&(this.complete=this.tryComplete),t.complete=t.tryComplete,t.subscribe(this.makeSource(i,this.index++))}complete(){this.sink.complete()}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},Wd=class extends uo{},Gd=class extends ho{next(i){this.subInner(i,Wd),this.next=e=>{this.currentSink.dispose(),this.subInner(e,Wd)}}},Mr=z(Gd,"switchMap");function Xd(o){return(i,e)=>o(()=>i,e)}var mo=Xd(z(Gd,"switchMapTo")),th=class extends uo{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},Jd=class extends ho{constructor(){super(...arguments),this.sources=[],this.next2=this.sources.push.bind(this.sources)}next(i){this.next2(i),this.subNext()}subNext(){this.next=this.next2,this.subInner(this.sources.shift(),th),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},jE=z(Jd,"concatMap"),XE=Xd(z(Jd,"concatMapTo")),ih=class extends uo{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},qd=class extends ho{constructor(){super(...arguments),this.inners=new Set}next(i){this.subInner(i,ih),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(i=>i.resetComplete()):this.dispose()}},zE=z(qd,"mergeMap"),QE=Xd(z(qd,"mergeMapTo")),rh=class extends uo{dispose(){this.context.resetNext(),super.dispose()}},jd=class extends ho{next(i){this.next=pe,this.subInner(i,rh)}},YE=z(jd,"exhaustMap"),ZE=Xd(z(jd,"exhaustMapTo")),oh=class extends X{constructor(i,e){super(i),this.f=e,this.groups=new Map}next(i){let e=this.f(i),t=this.groups.get(e);typeof t=="undefined"&&(t=rt(),t.key=e,this.groups.set(e,t),super.next(t)),t.next(i)}complete(){this.groups.forEach(i=>i.complete()),super.complete()}error(i){this.groups.forEach(e=>e.error(i)),super.error(i)}},KE=z(oh,"groupBy"),sh=class extends X{constructor(){super(...arguments),this.start=new Date}next(i){this.sink.next({value:i,interval:Number(new Date)-Number(this.start)}),this.start=new Date}},eS=z(sh,"timeInterval"),nh=class extends X{constructor(i,e){super(i),this.miniseconds=e,this.buffer=[],this.id=setInterval(()=>{this.sink.next(this.buffer.concat()),this.buffer.length=0},this.miniseconds)}next(i){this.buffer.push(i)}complete(){this.sink.next(this.buffer),super.complete()}dispose(){clearInterval(this.id),super.dispose()}},tS=z(nh,"bufferTime"),ah=class extends X{constructor(i,e){super(i),this.buffer=[],this.delayTime=e}dispose(){clearTimeout(this.timeoutId),super.dispose()}delay(i){this.timeoutId=setTimeout(()=>{let e=this.buffer.shift();if(e){let{time:t,data:r}=e;super.next(r),this.buffer.length&&this.delay(Number(this.buffer[0].time)-Number(t))}},i)}next(i){this.buffer.length||this.delay(this.delayTime),this.buffer.push({time:new Date,data:i})}complete(){this.timeoutId=setTimeout(()=>super.complete(),this.delayTime)}},iS=z(ah,"delay"),dh=class extends X{constructor(i,e){super(i),this.selector=e}error(i){this.dispose(),this.selector(i)(this.sink)}},hh=z(dh,"catchError"),ch=class extends uo{tryComplete(){let i=this.context.inners.delete(this);super.dispose(),i&&this.context.checkComplete()}next(i){this.sink.next(i),this.context.expandValue(i)}},lh=class extends ho{constructor(i,e){super(i,e),this.project=e,this.inners=new Set,this.sourceCompleted=!1}next(i){this.sink.next(i),this.expandValue(i)}expandValue(i){let e=new ch(this.sink,i,this);this.currentSink=e,this.complete=this.tryComplete,e.complete=e.tryComplete,this.inners.add(e),e.subscribe(this.makeSource(i,this.index++))}complete(){this.sourceCompleted=!0,this.checkComplete()}checkComplete(){this.sourceCompleted&&this.inners.size===0&&(this.resetComplete(),super.complete())}tryComplete(){this.sourceCompleted=!0,this.checkComplete()}},rS=z(lh,"expand");var oS=()=>o=>new Promise((i,e)=>{let t;new co(o,r=>t=r,e,()=>i(t))}),sS=()=>o=>{let i;return new ReadableStream({start(e){i=new co(o,e.enqueue.bind(e),e.error.bind(e),e.close.bind(e))},cancel(){i.dispose()}})},Te=(o=pe,i=pe,e=pe)=>t=>new co(t,o,i,e),mh=class extends X{constructor(i,e){super(i),e instanceof Function?this.next=t=>{e(t),i.next(t)}:(e.next&&(this.next=t=>{e.next(t),i.next(t)}),e.complete&&(this.complete=()=>{e.complete(),i.complete()}),e.error&&(this.error=t=>{e.error(t),i.error(t)}))}},Fn=z(mh,"tap"),ph=class extends X{constructor(i,e){super(i),this.timeout=e,this.id=setTimeout(()=>this.error(new Pn(this.timeout)),this.timeout)}next(i){super.next(i),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},nS=z(ph,"timeout"),aS=(o=1/0)=>i=>{if(i instanceof Ht){let e=ae(t=>{let r=o,s=new X(t);s.error=n=>{r-- >0?s.subscribe(i):t.error(n)},s.sourceId=e.id,s.subscribe(i)},"retry",[o]);return e.source=i,Oe.pipe(e),e}else return e=>{let t=o,r=new X(e);r.error=s=>{t-- >0?i(r):e.error(s)},i(r)}};var ms=(e=>(e[e.AUTO_SWITCH_NEW_DEVICE=0]="AUTO_SWITCH_NEW_DEVICE",e[e.WAIT_CURRENT_DEVICE=1]="WAIT_CURRENT_DEVICE",e))(ms||{}),po=class po extends no{constructor(e,t){super({mediaType:e,PlayerClass:t});c(this,"isRemote",!1);c(this,"deviceId");c(this,"groupId","");c(this,"label","");c(this,"sourceTrack");c(this,"enableAutoSwitchWhenRecapturing",!0);c(this,"_isRecapturing",!1);c(this,"_lastRecaptureTime",0);c(this,"_onMuteTimeoutId",-1);c(this,"_encodeCheckTimeoutId",-1);c(this,"recaptureMode",0);c(this,"profile");c(this,"retryEncodeFailed")}get enableEncodeFrame(){return!1}get isPublishing(){return this.state.toString()==="publishing"}get isPublished(){return this.state==="publish"}get isUseCustomSource(){return this.sourceTrack&&this.mediaTrack&&this.sourceTrack!==this.mediaTrack}encodeFrame(e,t){throw new Error("Method not implemented.")}installTrackEvent(e){e.addEventListener(_.MUTE,this.onTrackMuted),e.addEventListener(_.UNMUTE,this.onTrackUnmuted),e.addEventListener(_.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===_.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){e.removeEventListener(_.MUTE,this.onTrackMuted),e.removeEventListener(_.UNMUTE,this.onTrackUnmuted),e.removeEventListener(_.ENDED,this.onTrackEnded)}setStateToReady(){}capture(e,t=!1){return f(this,null,function*(){var s;let r=this.sourceTrack;try{let n=V();S.emit(A.LOCAL_TRACK_CAPTURE_START,{track:this});let a;e.customSource?(a=new MediaStream,a.addTrack(e.customSource)):(t||(s=this.sourceTrack)==null||s.stop(),a=yield tf(e));let d=a.getTracks()[0];return yield this.setInputMediaStreamTrack(d),e.customSource||(this.sourceTrack=d,this.updateDeviceIdInUse(),this.listenDeviceChange()),S.emit(A.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:V()-n}),a}catch(n){throw S.emit(A.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:n}),this.log.error(`getUserMedia error observed ${n}`),n}finally{t&&(r==null||r.stop())}})}setOutputMediaStreamTrack(e){var t;if(super.setOutputMediaStreamTrack(e),this.setStateToReady(),this.isPublishing||this.isPublished)return(t=this.room)==null?void 0:t.replaceTrack(this)}get hasFlag(){var t,r;let e=Kt(((t=this.room)==null?void 0:t.localPublishFlag)||0,((r=this.room)==null?void 0:r.userId)||"");return this.mediaType===4&&e.hasVideo||this.mediaType===1&&e.hasAudio||this.mediaType===2&&e.hasAuxiliary}publish(e,t){return f(this,null,function*(){return this.room=e,this.room.localTracks.add(this),this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.bindParent(e.getLogger()),yield t,this._checkPublishFlag(e)})}_checkPublishFlag(e){return new Promise((t,r)=>f(this,null,function*(){var l,u,h,p;let s=()=>r(new v({code:I.API_CALL_ABORTED,message:"publish aborted"}));if(this.hasFlag||this.muted?t():((this.state===j.INIT||this.state==="ready")&&s(),ce(de(e,"local-publish-flag-changed"),$t(()=>this.hasFlag),ke(Ln(de(this,j.INIT),de(this,"ready"))),Te(t,r,s))),(((u=(l=this.room)==null?void 0:l.networkQuality)==null?void 0:u.uplinkNetworkQuality)||0)>3)return t();let a=e.heartbeatCount,d=((p=(h=this.mediaTrack)==null?void 0:h.stats)==null?void 0:p.totalFrames)||0;this._encodeCheckTimeoutId=setTimeout(()=>f(this,null,function*(){var g,E,C,P,re,L,Qe;if((((E=(g=this.room)==null?void 0:g.networkQuality)==null?void 0:E.uplinkNetworkQuality)||0)>3||e.heartbeatCount-a<3)return t();if((this.isPublished||this.isPublishing)&&this.isMediaTrackActive){if((C=this.mediaTrack)!=null&&C.stats){let O=this.mediaTrack.stats.totalFrames||0;O-d===0&&this.log.warn("capture totalFrames is 0 during encode check, totalFrames",O)}let N=this.kind===_.AUDIO,k=this.stat.bytesSent>0;if(y[k?"addSuccessEvent":"addFailedEvent"]({key:N?503700:513702}),!N){let O=((re=(P=this.room)==null?void 0:P.videoCodec)==null?void 0:re.toUpperCase())||"H264",Ne={H264:513704,H265:513705,VP8:513706}[O];Ne&&y[k?"addSuccessEvent":"addFailedEvent"]({key:Ne})}if(!k){if(y.addEnum({key:N?503701:513703,value:Zr()}),se.uploadEvent({log:`stat-encode-failed-${this.kind}-${ai()||di()}`,userId:this.userId}),this.log.warn(N?"encode failed":`${(Qe=(L=this.room)==null?void 0:L.videoCodec)==null?void 0:Qe.toUpperCase()} encode failed`),this.retryEncodeFailed&&(this.log.warn("retry encode"),yield this.retryEncodeFailed(this),this.stat.bytesSent>0||this.hasFlag||(yield Ke(5e3),this.stat.bytesSent>0||this.hasFlag)))return t();this.emit("6",this),r(new v({message:`${this.strMediaType} encode failed`,code:N?I.AUDIO_ENCODE_FAILED:I.VIDEO_ENCODE_FAILED}))}}}),1e4)}))}unpublish(){this.room&&this.room.localTracks.delete(this),this.log.info("unpublish"),S.emit(A.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return f(this,null,function*(){if(this.sourceTrack&&Ni){let{deviceId:e,groupId:t}=this.sourceTrack.getSettings(),{label:r}=this.sourceTrack;(yield Kp({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=r,t&&(this.groupId=t),cs().then(n=>{let a=n.find(d=>{let l=d.deviceId===e;return t&&(l=l&&d.groupId===t),l});a&&this.emit("2",a)}))}})}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(e=!1){return!(!this.deviceId||!this.sourceTrack||this.kind===_.AUDIO&&!Zp(this.sourceTrack)||this.kind===_.VIDEO&&!Yp(this.sourceTrack)||this._isRecapturing||e&&si&&Re)}onTrackMuted(){if(super.onTrackMuted(),rf(),!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<ko){setTimeout(()=>this.onTrackMuted(),ko);return}this._onMuteTimeoutId=setTimeout(()=>f(this,null,function*(){var e;if((e=this.sourceTrack)!=null&&e.muted){if((ge||_e)&&document.visibilityState!=="visible")return;this.recapture(yield this.getRecoverCaptureDeviceId())}}),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return f(this,null,function*(){if(Le(po.prototype,this,"onTrackEnded").call(this),!!this.isNeedToRecapture()&&this.recaptureMode===0){if(Date.now()-this._lastRecaptureTime<ko){setTimeout(()=>this.onTrackEnded(),ko);return}this.emit("7"),this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e,t=!1){return f(this,null,function*(){var n;if(this._isRecapturing||!this.sourceTrack)return;this.log.warn("recapture trying");let r=this.sourceTrack;t||(n=this.sourceTrack)==null||n.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let s={useExactDeviceId:!0};if(e==="user"||e==="environment")s.facingMode=e;else{let a;(this.kind==="audio"?yield It():yield At()).find(l=>l.deviceId===e)&&(a=e),s.deviceId=a}return this.capture(s,t).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),S.emit(A.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(a=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${a.message}`),this.emit("5",a),S.emit(A.LOCAL_TRACK_RECAPTURE,{track:this,error:a})}).finally(()=>{t&&(r==null||r.stop())})})}getRecoverCaptureDeviceId(){return f(this,null,function*(){let e=this instanceof je;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let r=(Bn.get(t)||0)+1;if(Bn.set(t,r),r>=3&&this.enableAutoSwitchWhenRecapturing){let s=e?(yield At()).find(n=>!Bn.has(n.deviceId)):(yield It()).find(n=>!Bn.has(n.deviceId));s&&(this.log.warn(`${t} capture fail ${r} times, change new ${s.deviceId}`),t=s.deviceId)}}return t})}stopCapture(){var e;this.sourceTrack&&(this.sourceTrack.stop(),this.uninstallTrackEvent(this.sourceTrack)),this._inputTrack&&this.uninstallTrackEvent(this._inputTrack),(e=this.manager)==null||e.removeInput(this)}close(){super.close(),this.stopCapture()}};D([ye(j.INIT,"ready",{ignoreError:!0,sync:!0})],po.prototype,"setStateToReady",1),D([ir()],po.prototype,"capture",1),D([ye("ready","publish",{ignoreError:!0,success(){S.emit(A.LOCAL_TRACK_PUBLISHED,{track:this,room:this.room}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),this.log.info("published")},fail(e){var n;(n=this.room)==null||n.localTracks.delete(this);let t="error",r=e instanceof v?e:e.cause instanceof v?e.cause:e,s=!1;r instanceof v&&(r.message.includes("timeout")?t="timeout":r.code===I.API_CALL_ABORTED&&(s=!0,t="api-call")),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:t,error:r}),this.log[s?"info":"error"]("publish failed",r)}}),Rt(521714,!1)],po.prototype,"publish",1),D([Y(e=>function(){return f(this,null,function*(){let t=this.state==="publish"?"started":"starting";e.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:t,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)})}),ye([],"ready",{sync:!0})],po.prototype,"unpublish",1);var _i=po,Bn=new Map;S.on(A.SWITCH_DEVICE_SUCCESS,o=>{o.track.deviceId&&Bn.delete(o.track.deviceId)});var kt=class o extends _i{constructor(e){super(1,vd);c(this,"mediaType",1);c(this,"volume",0);c(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40});c(this,"playerMuted",!0);c(this,"pipeline");c(this,"earMonitorGainNode",new Ue);c(this,"_output",new Ue);c(this,"codecPipeline",[]);c(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0});c(this,"mixedAudioReferenceMap",new Map);c(this,"isAudioContextLongSuspended",!1);c(this,"after3aSilenceStartTime",0);this.manager=e,this.pipeline=new ds(e),this.pipeline.source.pipeTo(this.player.pipeline.volumeMeter),this.pipeline.gain.pipeTo(this.earMonitorGainNode).pipeTo(this._output),this.pipeline.gain.pipeTo(this.player.pipeline.volumeMeterAfter3A),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this),S.on(A.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this)}get dbVolume(){return so.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}getInternalAudioLevelAfter3A(){if(this.pipeline.isProcessEnabled)return this.player.getInternalAudioLevelAfter3A()}updateAfter3aSilenceStartTime(e){T(e)||(e===0&&!this.after3aSilenceStartTime?this.after3aSilenceStartTime=V():e>0&&(this.after3aSilenceStartTime=0))}setInputMediaStreamTrack(e){return f(this,null,function*(){let t=this.trackSettings||{};y.addEnum({key:501701,value:t.channelCount||0,useUV:!1}),y.addEnum({key:501702,value:t.sampleRate||0,useUV:!1}),y.addEnum({key:502700,value:0});let{sampleRate:r,channelCount:s}=t;this._log.info(`local audio track input ${JSON.stringify({sampleRate:r,channelCount:s})}`),this.pipeline.source.channelCount=s||1,this.pipeline.replaceSource(e),yield Le(o.prototype,this,"setInputMediaStreamTrack").call(this,e),this.updatePlayingState(!!e)})}capture(a){return f(this,arguments,function*({deviceId:e,customSource:t,useExactDeviceId:r=!0,retryWhenExactFailed:s},n=!1){let d=yield Le(o.prototype,this,"capture").call(this,{video:!1,audio:!0,microphoneId:e,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:r,retryWhenExactFailed:s,customSource:t},n);return Nr(),d})}switchDevice(e){return f(this,null,function*(){if(this.mediaTrack){if(this.deviceId===e&&!this.isUseCustomSource)if(e===Wr){if(yield vu(this.groupId,this.label))return}else return;try{this.log.info(`switchDevice audio to: ${e}`),this.sourceTrack&&this.sourceTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0,retryWhenExactFailed:!1}),S.emit(A.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(t){throw this.log.error(`switch microphone failed ${t}`),this.deviceId&&this.recapture(this.deviceId),t}}})}listenDeviceChange(){be&&!be.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&be.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return f(this,null,function*(){if(e.deviceId===this.deviceId){let t=this.recaptureMode===1;if(this.log.warn(`RecaptureMode: ${ms[this.recaptureMode]}. Current microphone is lost: ${JSON.stringify(e)}`),this.recaptureMode===0){ve(this.userId,{eventId:2003,param1:6,streamType:1});let r=yield It();r[0]?this.recapture(r[0].deviceId):t=!0}t&&be.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.recaptureMode===1&&e.deviceId!==this.deviceId||(be.off("audioInputAdded",this.handleMicrophoneAdded,this),this.log.warn(`microphone added: ${JSON.stringify(e)}`),this.recapture(e.deviceId))}update3A(s){return f(this,arguments,function*({echoCancellation:e,noiseSuppression:t,autoGainControl:r}){let n=this.sourceTrack||this.mediaTrack;if(!n)return;let a=n.getConstraints(),d=!1;!T(e)&&e!==this.profile.echoCancellation&&(this.profile.echoCancellation=e,a.echoCancellation=e,d=!0),!T(t)&&t!==this.profile.noiseSuppression&&(this.profile.noiseSuppression=t,a.noiseSuppression=t,d=!0),!T(r)&&r!==this.profile.autoGainControl&&(this.profile.autoGainControl=r,a.autoGainControl=r,d=!0),d&&(ee||Re?yield n.applyConstraints(a).catch(l=>this._log.warn("update3A failed: ",l)):this.deviceId&&(yield this.recapture(this.deviceId,!0)))})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&y.addEnum({key:502700,value:2})}setAudioVolume(e){super.setAudioVolume(0),ge&&this.player.setMuted(!0),this.earMonitorGainNode.node||(this.earMonitorGainNode.setNode(Ee().createGain()),this._output.setNode(Ee().destination)),this.earMonitorGainNode.node.gain.value=e}enableTrackANS(e){return this.update3A({noiseSuppression:e})}enableTrackAEC(e){if(this.sourceTrack&&!(Re||ge))return this.update3A({echoCancellation:e})}addDenoiser(e){var t;if($e<=92&&((t=this.trackSettings)==null?void 0:t.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)}mixAudioReference(e,t){if(this.mixedAudioReferenceMap.has(t))return;this.log.info(`mixAudioReference() => ${t}`);let r=Mn(e);if(!r)return;let s=new Ue,n=Ee().createGain();n.gain.value=1;let a=new Ue;s.pipeTo(a).pipeTo(this.pipeline.mixNode),s.setNode(r),a.setNode(n),this.mixedAudioReferenceMap.set(t,[s,a])}unMixAudioReference(e){let[t,r]=this.mixedAudioReferenceMap.get(e)||[];t&&(this.log.info(`unMixAudioReference() => ${e}`),t.deleteNode(),r==null||r.deleteNode(),this.mixedAudioReferenceMap.delete(e))}setAudioReferenceVolume(e,t){let[r,s]=this.mixedAudioReferenceMap.get(e)||[];s!=null&&s.node&&(s.node.gain.value=t/100,this.log.info(`setAudioReferenceVolume() => ${e} ${s.node.gain.value}`))}addAudioProcessor(e,t,r){this.pipeline.silentNode.setNode(r),this.pipeline.mixNode.setNode(t),this.pipeline.aec.setNode(e)}removeDenoiser(e){if(this.pipeline.denoiser.node===e)return this.pipeline.denoiser.deleteNode(),this.enableTrackANS(!0)}removeAudioProcessor(e){this.pipeline.aec.node===e&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode())}close(){this.mixedAudioReferenceMap.forEach(([e,t])=>{e.deleteNode(),t.deleteNode()}),this.mixedAudioReferenceMap.clear(),this.pipeline.remove(),this.earMonitorGainNode.deleteNode(),this._output.deleteNode(),be.off("audioInputAdded",this.handleMicrophoneAdded,this),be.off("audioInputRemoved",this.handleMicrophoneRemoved,this),S.off(A.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this),super.close()}recapture(e,t=!1){return f(this,null,function*(){try{yield Le(o.prototype,this,"recapture").call(this,e,t)}catch(r){let s=(yield It()).find(n=>n.deviceId!==e);if(s)yield Le(o.prototype,this,"recapture").call(this,s.deviceId);else throw r}})}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduceRight((t,r)=>r?r({frame:t,ntp:Hi()}):t,e):e}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}get enableEncryptFrame(){return this.manager&&!!this.manager.encodePipeline[0]}handleAudioContextLongSuspended({isSuspended:e}){if(this.pipeline.isProcessEnabled)if(e){this.isAudioContextLongSuspended=!0,this.log.warn(`context has suspended for ${yu/1e3} seconds, change to source audio${Ft?"":", non-Safari"}`);let t=this.sourceTrack||this.mediaTrack;t&&this.setOutputMediaStreamTrack(t)}else this.isAudioContextLongSuspended=!1,this.log.warn("context has resumed, change to processed audio"),this.pipeline.track&&this.setOutputMediaStreamTrack(this.pipeline.track)}setOutputMediaStreamTrack(e){if(this.isAudioContextLongSuspended){let t=this.sourceTrack||this.mediaTrack;t&&(e=t)}super.setOutputMediaStreamTrack(e)}};var sr=class{constructor(i,e=!1){this.dataView=i;this.isSEI&&(e?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let i=this.seiPayloadStartIndex,e=this.dataView.byteLength-2,t=[],r=0;for(let n=i;n<=e;n++){let a=this.dataView.getInt8(n);switch(a){case 0:case 1:case 2:case 3:r===2&&(t.push(3),r=0),a==0?r++:r=0,t.push(a);break;default:r=0,t.push(a);break}}t.push(this.dataView.getInt8(this.dataView.byteLength-1));let s=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=s}removePreventionByte(){let i=this.seiPayloadStartIndex,e=this.dataView.byteLength-1,t=[],r=0;for(let n=i;n<=e;n++)switch(this.dataView.getInt8(n)){case 0:r++,t.push(this.dataView.getInt8(n));break;case 3:r!==2&&t.push(this.dataView.getInt8(n)),r=0;break;default:t.push(this.dataView.getInt8(n)),r=0;break}let s=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=s}get isSEI(){return this.dataView.getUint8(4)===6}get seiPayloadStartIndex(){let i=6;for(let e=6;e<this.dataView.buffer.byteLength&&(i++,this.dataView.getUint8(e)===255);e++);return i}get seiPayloadType(){return this.isSEI?this.dataView.getUint8(5):null}get seiPayload(){if(!this.isSEI)return null;let i=0,e=6;for(let s=6;s<this.dataView.buffer.byteLength;s++){let n=this.dataView.getUint8(s);if(e++,n===255)i+=255;else{i+=n;break}}let t=new ArrayBuffer(i),r=new DataView(t);for(let s=0;s<t.byteLength;s++,e++)r.setInt8(s,this.dataView.getInt8(e));return r}};var zd=class{constructor(){c(this,"_seiMessageList",[]);c(this,"_smallSeiMessageList",[]);c(this,"_seiPayloadType",243)}encodeSEINalu(i){let e=i.byteLength,t=parseInt(String(e/255),10),r=e%255,s=[];s.push(0,0,0,1,6,this._seiPayloadType);for(let a=0;a<t;a++)s.push(255);s.push(r);let n=new DataView(i);return s.push(...new Uint8Array(n.buffer)),s.push(128),new sr(new DataView(new Uint8Array(s).buffer),!0)}sendSEI(i,e){e!=null&&e.seiPayloadType&&(this._seiPayloadType=e.seiPayloadType),this._seiMessageList.push(i),e!=null&&e.small&&this._smallSeiMessageList.push(i)}isEmpty(){return!this._seiMessageList.length}getNaluCount(i){let e=0,t=0,r=new DataView(i);for(let s=0;s<i.byteLength;s++)switch(r.getUint8(s)){case 0:e++;break;case 1:(e===2||e===3)&&t++,e=0;break;default:e=0;break}return t}encode(i,e){let t=e?this._smallSeiMessageList:this._seiMessageList;if(t.length>0&&i.data.byteLength>0){let s=9-this.getNaluCount(i.data);if(s<=0)return 0;let n=t.splice(0,s).reverse().map(this.encodeSEINalu.bind(this)),a=n.reduce((p,m)=>p+m.dataView.byteLength,0),d=new ArrayBuffer(a+i.data.byteLength),l=new DataView(d),u=new DataView(i.data),h=0;for(let p=0;p<n.length;p++)for(let m=0;m<n[p].dataView.byteLength;m++)l.setInt8(h++,n[p].dataView.getInt8(m));for(let p=0;p<i.data.byteLength;p++)l.setInt8(h++,u.getInt8(p));return i.data=d,n.length}return 0}};var Or=class Or extends _i{constructor(e,t=4){super(t,pt);c(this,"profile",M({},pr));c(this,"avoidCropping",!1);c(this,"_scaleResolutionDownBy");c(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0,framesCaptured:0});c(this,"small");c(this,"isNeedToSetBandwidth");c(this,"muteImage");c(this,"manager");c(this,"_seiCodec",new zd);this.manager=e;let r=()=>{var s;if(this.isAllowed2k4k(this.profile))this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1});else{let n=Ut(((s=this.room)==null?void 0:s.sdkAppId)||0)?ua:la;this.log.warn(`Resolution is reset to 1080p, need to upgrade ability here ${n}`),this.setProfile(w(M({},this.profile),{width:1920,height:1080})),this.applyProfile()}};this.on("input-media-track-changed",r),this.on("publish",r),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(!(!Ni||!this.mediaTrack))return this.mediaTrack.getSettings().facingMode}get contentHint(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)||""}get isQosClearFirst(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)==="detail"}get hasSmall(){var e;return!!((e=this.manager)!=null&&e.hasSmall)}setMute(e){return f(this,null,function*(){var t,r,s;if(ie(e)){if(this.muteImage===e)return;yield(t=this.manager)==null?void 0:t.deleteWatermark("mute"),yield(r=this.manager)==null?void 0:r.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:e,fillVideo:!0}),this.muteImage=e,Le(Or.prototype,this,"setMute").call(this,!1)}else this.muteImage&&(yield(s=this.manager)==null?void 0:s.deleteWatermark("mute"),this.muteImage=void 0),Le(Or.prototype,this,"setMute").call(this,e)})}capture(a){return f(this,arguments,function*({deviceId:e,facingMode:t,useExactDeviceId:r=!0,customSource:s,retryWhenExactFailed:n=!0}){let d={audio:!1,video:!0,facingMode:t||this.facingMode,cameraId:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:r,retryWhenExactFailed:n,customSource:s};if(d.facingMode==="environment"){let l=yield this.getDeviceIdWhenUsingBackCamera();l&&(d.cameraId=l)}return Le(Or.prototype,this,"capture").call(this,d)})}setProfile(e){var r;let t=this.fallbackProfile(e);if(t.bitrate&&(this.isNeedToSetBandwidth=t.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile))super.setProfile(t);else{let s=Ut(((r=this.room)==null?void 0:r.sdkAppId)||0)?ua:la;this.log.warn(`Resolution is reset to 1080p, need to upgrade ability here ${s}`),super.setProfile(w(M({},this.profile),{width:1920,height:1080}))}}applyProfile(){return f(this,null,function*(){var a;if(!this.mediaTrack)return;let{width:e=0,height:t=0}=(this.sourceTrack||this.mediaTrack).getSettings(),r=e*t,s=this.settings,n=s.height!==this.profile.height||s.width!==this.profile.width||s.frameRate!==this.profile.frameRate;if(n&&(et===16&&this.deviceId?yield this.recapture(this.deviceId):(yield(a=this.sourceTrack||this.mediaTrack)==null?void 0:a.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}),this.manager&&this.manager.changeInput(this)),this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1})),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth){this.isNeedToSetBandwidth=!1;let{width:d=0,height:l=0}=(this.sourceTrack||this.mediaTrack).getSettings(),u=d*l;if(n&&u&&r&&u===r){this.log.warn("set bandwidth failed: resolution is not changed");return}return this.room.setBandWidth({bandwidth:this.profile.bitrate,type:_.VIDEO,videoType:_.BIG})}})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},t=this.sourceTrack||this.mediaTrack;return Ni&&t&&Object.assign(e,t.getSettings()),e}get scaleResolutionDownBy(){return this._scaleResolutionDownBy?this._scaleResolutionDownBy:Ho(this.settings,this.profile)}isAllowed2k4k(e){var t;return!this.room||!this.room.scheduleResult||this.isScreen||e.height*e.width<2560*1440?!0:((t=this.room.scheduleResult.trtcAutoConf)==null?void 0:t["2k4k"])===1}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}switchDevice(e){return f(this,null,function*(){try{if(!this.isNeedToSwitchDevice(e)&&!this.isUseCustomSource)return;let t={useExactDeviceId:!0,retryWhenExactFailed:!1};e==="user"||e==="environment"?t.facingMode=e:t.deviceId=e,this.sourceTrack&&this.sourceTrack.stop(),yield this.capture(t),S.emit(A.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(t){throw this.log.error(`switch camera failed ${t}`),this.deviceId&&this.recapture(this.deviceId),t}})}getDeviceIdWhenUsingBackCamera(){return f(this,null,function*(){let e;try{if(tn&&!Qo&&au){let r=(yield At(!0)).map(n=>{var a;return w(M({},n),{capabilities:(a=n.getCapabilities)==null?void 0:a.call(n)})}).filter(n=>{var a,d;return(d=(a=n.capabilities)==null?void 0:a.facingMode)==null?void 0:d.includes("environment")}),s=r[0];r.forEach(n=>{var u,h,p,m;let{capabilities:a}=n,d=(u=a.width)!=null&&u.max&&((h=a.height)!=null&&h.max)?a.width.max*a.height.max:0,l=(p=s.capabilities.width)!=null&&p.max&&((m=s.capabilities.height)!=null&&m.max)?s.capabilities.width.max*s.capabilities.height.max:0;d>l&&(s=n)}),s!=null&&s.capabilities&&(this._log.info("use max resolution back camera",s),e=s.deviceId)}}catch(t){this._log.warn("get max res camera failed",t)}return e})}updateSmallConfig(e){var r,s;this._log.info(`update small stream config: ${JSON.stringify(e)}`);let t=!this.small;this.small=this.fallbackProfile(e,!0),(r=this.manager)==null||r.update(),t&&((s=this.room)==null||s.enableSmall(!0)),this.log.info("update small stream config success")}fallbackProfile(e,t=!1){let r=e.width>e.height,s=M({},e);return e.width*e.height<=160*120&&_e&&Ve&&(this.log.warn(`${t?"small ":""}resolution is ${e.width}*${e.height}, fallback to 240*180 for android chrome`),s.width=r?240:180,s.height=r?180:240,s.bitrate=Math.max(e.bitrate,150)),e.width*e.height>1280*720&&vl&&(s.width=r?1280:720,s.height=r?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),sn(ht,"14.3")&&bl(ht,"14.0",!0)&&this.on("7",()=>{let n=this.profile.width>this.profile.height;this.profile.width*this.profile.height>640*480?(this.profile.width=n?640:480,this.profile.height=n?480:640,this.log.warn("reduce the resolution to 480p on iOS 14.0 ~ 14.2")):this.profile.width*this.profile.height>640*360&&(this.profile.width=n?640:360,this.profile.height=n?360:640,this.log.warn("reduce the resolution to 360p on iOS 14.0 ~ 14.2"))}),!t&&this.avoidCropping&&(Ve||ee)&&!nn()&&e.width*e.height<=640*360&&e.width/e.height===16/9&&(this._scaleResolutionDownBy=1280/e.width,e.width=1280,e.height=720,this.log.warn(`capture 720p, scale: ${this._scaleResolutionDownBy}`)),s}stopSmall(){var e,t;this.small&&(delete this.small,(e=this.manager)==null||e.update(),(t=this.room)==null||t.enableSmall(!1))}listenDeviceChange(){be&&!be.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&be.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return f(this,null,function*(){if(e.deviceId===this.deviceId){let t=this.recaptureMode===1;if(this.log.warn(`RecaptureMode: ${ms[this.recaptureMode]}. Current camera is lost: ${JSON.stringify(e)}`),this.recaptureMode===0){ve(this.userId,{eventId:2003,param1:7,streamType:2});let r=yield At();r[0]?this.recapture(r[0].deviceId):t=!0}t&&be.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return f(this,null,function*(){this.recaptureMode===1&&e.deviceId!==this.deviceId||(be.off("videoInputAdded",this.handleCameraAdded,this),this.log.warn(`camera added: ${JSON.stringify(e)}`),this.recapture(e.deviceId))})}encodeFrame(e,t){if(!this.manager)return e;let r=t?8:this.mediaType;return this.manager.encodePipeline.reduceRight((s,n)=>n?n({frame:s,mediaType:r}):s,e)}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}play(e,t){return T(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,t)}close(){be.off("videoInputAdded",this.handleCameraAdded,this),be.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return f(this,null,function*(){try{yield Le(Or.prototype,this,"recapture").call(this,e)}catch(t){let r=(yield At()).find(s=>s.deviceId!==e);if(r)yield Le(Or.prototype,this,"recapture").call(this,r.deviceId);else throw t}})}setContentHint(e){this.mediaTrack&&"contentHint"in this.mediaTrack&&(this.mediaTrack.contentHint!==e&&(this.log.info(`setContentHint ${e}`),this.mediaTrack.contentHint=e),this.outMediaTrack&&this.outMediaTrack.contentHint!==e&&(this.outMediaTrack.contentHint=e))}setRotation(e){this.manager&&(this.isScreen||T(e)||e!==this.rotation&&(this.rotation=e,this.manager.rotation=e))}};D([Ct(function(e){this.setContentHint(e.contentHint||"motion")})],Or.prototype,"capture",1);var je=Or;var gh={};Bi(gh,{REPORT_TYPE:()=>$o,buildSSOPackage:()=>qi,bytes2ms:()=>bm,calculateScaleResolutionDownNumber:()=>Ho,concatArrayBuffers:()=>Oa,convertObjectNumberToInt:()=>Js,copyProperties:()=>ym,deepClone:()=>Gr,deepCloneBasic:()=>Ra,deepMerge:()=>ei,delay:()=>Ke,fibonacci:()=>qr,formatedTime:()=>xm,getConstructorName:()=>wo,getContainerFromElement:()=>Lm,getEnv:()=>Am,getFirst16Bits:()=>Um,getInternalVersion:()=>km,getLast16Bits:()=>ka,getLoggerUrl:()=>Ji,getMediaStreamTrackInfo:()=>Ma,getMuteStateFromFlag:()=>Kt,getNetworkType:()=>ya,getNumNetworkType:()=>Jr,getReconnectionTimeout:()=>Zt,getStringByteLength:()=>Gs,getTurnServer:()=>Pm,getUint32Version:()=>Na,getValueType:()=>Me,getViewListFromView:()=>Fo,glog:()=>pl,ipv4ToUint32:()=>Vo,isArray:()=>Ae,isAudioWorkletSupported:()=>Mm,isBoolean:()=>ue,isConstructor:()=>jr,isEmpty:()=>Uo,isFunction:()=>le,isLangChinese:()=>Yt,isMediaStreamTrack:()=>vm,isNumber:()=>Q,isObject:()=>yt,isOverseaSdkAppId:()=>Ut,isPlainObject:()=>dt,isPortrait:()=>fl,isPromise:()=>Tr,isRemoteTrack:()=>Dm,isRotate90Or270:()=>bt,isSetSinkIdSupported:()=>Om,isString:()=>ie,isUndefined:()=>T,loadImage:()=>Bo,loadVideo:()=>wm,ms2bytes:()=>Nm,ms2samples:()=>ml,normalizeUrl:()=>Da,performanceNow:()=>V,promiseAny:()=>Xr,samples2ms:()=>hl,setNetworkTypeFromWebRTC:()=>ba,stringify:()=>gt,stringifyIncludeValue:()=>Ws,throttlePromise:()=>va});var lS=[-1,-1,1,-1,-1,1,1,1],uS=[0,0,1,0,0,1,1,1];var kr=class kr extends j{constructor(e,t){super();this.context=e;c(this,"name");c(this,"input");c(this,"output");c(this,"texture");c(this,"ctx2d",null);c(this,"fbo");c(this,"width",0);c(this,"height",0);c(this,"x",0);c(this,"y",0);c(this,"program");c(this,"vertexShader");c(this,"fragmentShader");c(this,"totalFrames",0);c(this,"dropFrames",0);c(this,"matchInputSize",!0);c(this,"texCoordBuffer");c(this,"positionBuffer");c(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0});c(this,"cost",0);c(this,"_canvas",null);c(this,"_image");c(this,"log");if(this.context.on("disconnect",this.close,this),this.name=t.name,this.log=t.logger,this.matchInputSize=t.matchInputSize!==!1,this.width=t.width||e.width,this.height=t.height||e.height,this._image=t.image,e instanceof Xe){e.ctx&&t.create2d&&(typeof OffscreenCanvas=="function"&&et!==16?this._canvas=new OffscreenCanvas(this.width,this.height):(this._canvas=document.createElement("canvas"),this._canvas.width=this.width,this._canvas.height=this.height),this.ctx2d=this._canvas.getContext("2d"),this._image=this._canvas);return}try{let r=e.ctx;this.texCoordBuffer=this.createBuffer(uS),this.positionBuffer=this.createBuffer(lS),t.createTexture!==!1&&(this.texture=r.createTexture(),this.useTexture(),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.pixelStorei(r.UNPACK_ALIGNMENT,1)),t.useFbo&&(this.fbo=r.createFramebuffer(),this.useBufferFrame(),this.useTexture(),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,this.width,this.height,0,r.RGBA,r.UNSIGNED_BYTE,null),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,this.texture,0)),t.useDefaultProgram?this.program=e.defaultProgam:(t.vertexShaderSource||t.fragmentShaderSource)&&(this.vertexShader=t.vertexShaderSource?e.createShader(r.VERTEX_SHADER,t.vertexShaderSource):e.defaultVShader,this.fragmentShader=t.fragmentShaderSource?e.createShader(r.FRAGMENT_SHADER,t.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(r){this.context.destroy(new v({code:I.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${r.message||r}`}))}}get image(){return this._image}set image(e){this._image=e}createFramebuffer(e){let t=this.context.ctx,r=t.createFramebuffer();return t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0),r}connect(e,...t){return e.addInput(this,...t),this.output=e,e}addInput(e,...t){this.input=e,this.matchInputSize&&e.width&&e.height&&this.resize(e.width,e.height)}requestFrame(e){let t=Date.now();if(this.context instanceof Be&&this.render(e)||this.context instanceof Xe&&this.render2d(e))this.totalFrames++;else return!1;return this.cost=Date.now()-t,!0}render2d(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?this.draw2d(this.input.image,0,0,this.width,this.height):!1}update(e=0){var t;(t=this.output)==null||t.update(e)}disconnect(...e){var t;(t=this.output)==null||t.removeInput(this,...e),delete this.output}removeInput(e,...t){delete this.input}close(){var e,t;if(this.context.off("disconnect",this.close,this),(e=this.output)==null||e.removeInput(this),delete this.output,(t=this.input)==null||t.disconnect(),this.context instanceof Be){let r=this.context.ctx;r.deleteBuffer(this.texCoordBuffer),r.deleteBuffer(this.positionBuffer),this.fbo&&r.deleteFramebuffer(this.fbo),this.texture&&r.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&r.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&r.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&r.deleteProgram(this.program)}this._canvas&&(this._canvas.width=0,this._canvas.height=0,this.ctx2d=null),this.removeAllListeners()}useTexture(){this.useTextures(this.texture)}useInputTexture(){var e;this.useTextures((e=this.input)==null?void 0:e.texture)}useTextures(...e){let t=this.context.ctx;e.forEach((r,s)=>{r&&(t.activeTexture(t.TEXTURE0+s),t.bindTexture(t.TEXTURE_2D,r))})}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}createBuffer(e){let t=this.context.ctx,r=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,r),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW),r}setTexBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}setPosBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}changeBufferData(e,t){let r=this.context.ctx;r.bindBuffer(r.ARRAY_BUFFER,e),r.bufferData(r.ARRAY_BUFFER,new Float32Array(t),r.STATIC_DRAW)}setAttributes(...e){let t=this.context.ctx;e.forEach((r,s)=>{t.enableVertexAttribArray(s),t.bindBuffer(t.ARRAY_BUFFER,r),t.vertexAttribPointer(s,2,t.FLOAT,!1,0,0)})}getVertexPoint(e,t){return[e/this.width*2-1,t/this.height*2-1]}layout2texCoords(e){return[...this.getVertexPoint(e.x,e.y),...this.getVertexPoint(e.x+e.width,e.y),...this.getVertexPoint(e.x,e.y+e.height),...this.getVertexPoint(e.x+e.width,e.y+e.height)]}resize(e,t){if(!(this.width===e&&this.height===t)){if(this.width=e,this.height=t,this._canvas&&(this._canvas.width=e,this._canvas.height=t),this.texture&&this.fbo){this.useTexture();let r=this.context.ctx;r.texImage2D(r.TEXTURE_2D,0,r.RGBA,e,t,0,r.RGBA,r.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(e,t)}}draw(e,t){this.setAttributes(e||this.positionBuffer,t||this.texCoordBuffer);let r=this.context.ctx;r.drawArrays(r.TRIANGLE_STRIP,0,4)}draw2d(e,t,r,s,n,a,d,l,u){let h=!T(a)&&!T(d)&&!T(l)&&!T(u);return this.ctx2d&&e?(e instanceof ImageData?(h?this.ctx2d.putImageData(e,t,r,a,d,l,u):this.ctx2d.putImageData(e,t,r),this.emit(kr.RENDER,this.ctx2d.canvas)):(h?this.ctx2d.drawImage(e,a,d,l,u,t,r,s,n):this.ctx2d.drawImage(e,t,r,s,n),this.emit(kr.RENDER,e)),typeof VideoFrame!="undefined"&&e instanceof VideoFrame&&e.close(),!0):!1}drawBackGround2d(e){this.ctx2d&&(this.ctx2d.save(),this.ctx2d.fillStyle=e,this.ctx2d.fillRect(0,0,this.width,this.height),this.ctx2d.restore())}getInfo(){var h;let{totalFrames:e,x:t,y:r,width:s,height:n,name:a,cost:d}=this,l=Date.now(),u=(e-this.lastInfo.totalFrames)/((l-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:r,width:s,height:n,timestamp:l,fps:u,name:a,cost:d},M({parent:(h=this.input)==null?void 0:h.getInfo()},this.lastInfo)}createTexture(e){let t=this.context.ctx,r=t.createTexture();return this.useTextures(r),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.pixelStorei(t.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),r}};c(kr,"RENDER","render"),D([ye(j.INIT,"connected",{sync:!0})],kr.prototype,"connect",1),D([ye("connected",j.INIT,{ignoreError:!0,sync:!0})],kr.prototype,"disconnect",1),D([ye([],"closed",{sync:!0})],kr.prototype,"close",1);var Pe=kr;var hS=ce(wu(250),Vn(()=>performance.now()),rr());var hf=o=>i=>{let e=performance.now();ce(hS,Hd(t=>t-e<o),or(1))(i)};var pS=[0,1,1,1,0,0,1,0],fo=class extends Pe{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t));c(this,"_intervalId",0);c(this,"_sequence",0);c(this,"checkGLError",!1);c(this,"checkVisibilityChange");e instanceof Xe?this.ctx2d=e.ctx||null:e.available&&(t!=null&&t.mirrorUpAndDown)&&this.setTexBuffer(pS)}start(e){this.log.info(`${this.name} start render ${e} fps`),oe.clearTask(this._intervalId),this._intervalId=oe.run("intervalInWorker",()=>{if(e!==this.context.frameRate&&(oe.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof Be){let r=this.context.ctx.getError();r&&this.context.destroy(new v({code:I.VIDEO_MANAGER_ERROR,extraCode:5,message:`${this.name} req ${this._sequence} render ${this.totalFrames} faild ${r}`}))}},{fps:this.context.frameRate})}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),this.emit(Pe.RENDER,this.context._canvas),!0):!1}addInput(e,...t){super.addInput(e,...t),this.start(this.context.frameRate)}update(e=0){this.state!=="closed"&&(this._intervalId&&(oe.clearTask(this._intervalId),this._intervalId=0,e===1&&(this.log.info(`${this.name} use requestVideoFrameCallback`),this.checkVisibilityChange=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info(`${this.name} use timer`),document.removeEventListener("visibilitychange",this.checkVisibilityChange))},document.addEventListener("visibilitychange",this.checkVisibilityChange))),this.requestFrame(this._sequence++))}removeInput(e){super.removeInput(e),oe.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}close(){super.close(),oe.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},ps=class extends fo{constructor(e,t){super(e,t);c(this,"_videoTrack");c(this,"_muteOb");c(this,"_closedOb",de(this,"closed"));c(this,"_subscription");c(this,"_canvasContainer");Number(Xi)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e.canvas.captureStream().getVideoTracks(),this._muteOb=de(this._videoTrack,"mute"),ce(de(this._videoTrack,"ended"),ke(this._closedOb),Te(()=>{this.context.destroy(new v({code:I.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){this._subscription=ce(this._muteOb,ke(this._closedOb),mo(hf(5e3)),$t(()=>{var e;return!!((e=this._videoTrack)!=null&&e.muted)&&!document.hidden}),Te(()=>{this.context.destroy(new v({code:I.VIDEO_MANAGER_ERROR,extraCode:7,message:"video track muted"}))}))}disableCheckMute(){var e;(e=this._subscription)==null||e.dispose()}get videoTrack(){return this._videoTrack}putCanvasIntoDom(){!this.context._canvas||!this._canvasContainer||document.getElementById(this.context._canvas.id)||(this.log.info(`${this.name} put canvas to body`),document.body.appendChild(this._canvasContainer),this._canvasContainer.appendChild(this.context._canvas))}render(e){return this.putCanvasIntoDom(),super.render(e)}render2d(e){return this.putCanvasIntoDom(),super.render2d(e)}close(){var e,t;super.close(),(e=this._videoTrack)==null||e.stop(),delete this._videoTrack,(t=this._canvasContainer)==null||t.remove()}},Qd=class extends ps{render(i){var t;let e=!!((t=this.input)!=null&&t.requestFrame(i));if(this.context._canvas2d){let r=this.context._canvas2d.getContext("2d");r.clearRect(0,0,this.context._canvas2d.width,this.context._canvas2d.height),r.drawImage(this.context._canvas,0,0,this.context._canvas2d.width,this.context._canvas2d.height),this.emit(Pe.RENDER,this.context._canvas2d)}else this.emit(Pe.RENDER,this.context._canvas);return e}};var Yd=class extends ps{constructor(e,t,r){super(e,{name:"smallDestination",logger:r});this.resolution=t}resize(e,t){let r,s=e*t,n=this.resolution.width*this.resolution.height;this.log.info(`big res: ${e}*${t} small res: ${this.resolution.width}*${this.resolution.height} `),s>n?r=s/n:(this.log.warn(`Small stream resolution is not smaller than big stream, which is invalid. big: ${e} * ${t} small: ${this.resolution.width} * ${this.resolution.height}`),r=s/(160*120)),super.resize(e/Math.sqrt(r),t/Math.sqrt(r))}};var Hn=class extends Pe{constructor(e,t){super(e,M({name:"imageSource"},t));c(this,"_lastImage");c(this,"_totalFrames",0);c(this,"_autoResize",!1);c(this,"_canvasRendered");c(this,"videoCallbackId",0);c(this,"waitingFirstFrame",!0);c(this,"shouldUpdate",!0);this._autoResize=(t==null?void 0:t.autoResize)!==!1,et===16&&(this._canvasRendered=rt(),ce(this._canvasRendered,xn(this._image),Mr(r=>r instanceof HTMLCanvasElement?de(r,"rendered"):Un()),ke(de(this,"closed")),Te(()=>{this.update()})))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){if(!this.shouldUpdate)return;let e=this.image;this.videoCallbackId&&e.cancelVideoFrameCallback(this.videoCallbackId),Ki()&&!document.hidden&&(this.videoCallbackId=e.requestVideoFrameCallback((t,r)=>{this.waitingFirstFrame&&this.onFirstFrame(),document.hidden||(this._totalFrames=r.presentedFrames,this.update(1))}))}_render(e,t){var a;let{width:r,height:s}=this,{image:n}=this;if(n instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(),{videoWidth:r,videoHeight:s}=n,!r||!s)return!1;n.width=r,n.height=s}else if(n instanceof HTMLImageElement||n instanceof ImageData||n instanceof ImageBitmap){if({width:r,height:s}=n,n!==this._lastImage)this._lastImage=n;else if(r===this.width&&s===this.height)return!0}else n instanceof HTMLCanvasElement||n instanceof OffscreenCanvas?({width:r,height:s}=n,this._lastImage=n):typeof VideoFrame!="undefined"&&n instanceof VideoFrame&&({displayWidth:r,displayHeight:s}=n,(a=this._lastImage)==null||a.close(),this._lastImage=n);if(!this._autoResize)return!0;if(this.width===r&&this.height===s&&this.totalFrames){if(t){this.useTexture();let d=this.context.ctx;d.texSubImage2D(d.TEXTURE_2D,0,0,0,d.RGBA,d.UNSIGNED_BYTE,n)}}else{if(t){this.useTexture();let d=this.context.ctx;d.texImage2D(d.TEXTURE_2D,0,d.RGBA,d.RGBA,d.UNSIGNED_BYTE,n)}this.resize(r,s)}return!0}get image(){return this._image}set image(e){var t;(t=this._canvasRendered)==null||t.next(e),this._image=e}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},$n=class extends Hn{constructor(e,t,r){super(e,r);this._player=t;this.name="videoPlayerSource",ce(de(this._player,he.PLAYER_STATE_CHANGED),ke(de(this,"closed")),$t(({state:s})=>s==="PLAYING"),Te(()=>{this.tryVideoFrameCallback()}))}get image(){return this._player.element}},Wt=class extends $n{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(i,e,t){super(i,new pt({id:t.name,track:e,muted:!0,container:null,objectFit:"contain",log:t.logger}),t),this.name="videoTrackSource",this._player.play()}replaceTrack(i){this.waitingFirstFrame=!0,this._player.setTrack(i),this._player.play()}close(){super.close(),this._player.stop()}},Zd=class extends Pe{constructor(e,t,r){super(e,w(M({name:"textSource"},r),{create2d:!0}));c(this,"hasChange",!0);c(this,"content","");this.ctx2d.textBaseline="top",this.content=t.content||"",t.font&&(this.font=t.font),t.color&&(this.color=t.color)}set font(e){this.ctx2d&&(this.ctx2d.font=e,this.hasChange=!0)}get font(){var e;return((e=this.ctx2d)==null?void 0:e.font)||""}set color(e){this.ctx2d&&(this.ctx2d.fillStyle=e,this.hasChange=!0)}get color(){var e;return((e=this.ctx2d)==null?void 0:e.fillStyle)||""}render2d(e){return this.ctx2d&&this.hasChange?(this.ctx2d.clearRect(0,0,this.width,this.height),this.drawMultilineText(0,0),this.hasChange=!1,!0):!1}render(e){return!1}resize(e,t){if(!this.ctx2d)return;let{color:r,font:s}=this;super.resize(e,t),this.color=r,this.font=s}drawMultilineText(e=0,t=0,r=1.2){if(!this.ctx2d)return;let s=this.ctx2d.measureText(this.content);t+=s.fontBoundingBoxAscent||s.actualBoundingBoxAscent||0;let n=this.font.match(/(\d+)px/),d=(n?parseInt(n[1],10):16)*r,l=this.content.split(`
|
|
33
|
+
`,t.onclick=this.onQuestionClick.bind(this);let r=document.createElement("div");r.className=Tu,r.innerText=`${Yt()?"\u8BE6\u60C5 >":"Detail >"}`,r.onclick=this.onCollapseClick.bind(this);let s=i.content.firstChild,n=s.querySelector(`.${Id}`);return n.appendChild(r),n.appendChild(t),n.appendChild(e),s}addDiaLog(){br()||(Eu=!0,this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${yn}`).onclick=i=>i.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",R.info("show autoplay dialog"),se.uploadEvent({log:BT}))}deleteDialog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null,Eu=!1),bn=null}onConfirm(){R.warn("confirm clicked, try resume stream"),S.emit(A.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDialog()}onCollapseClick(){let i=this._dialogNode.querySelector(`.${Pp}`);i.style.visibility=`${this._showDetail?"hidden":"visible"}`,i.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||se.uploadEvent({log:HT}),this._isCollapseClicked=!0}onQuestionClick(){window.open(Up,"_blank"),this._isQuestionClicked||se.uploadEvent({log:$T}),this._isQuestionClicked=!0}},bn=null;function ns(){bn||(bn=new Su)}function Vp(){bn&&bn.deleteDialog()}var pt=class o extends fi{constructor(e){super(e,_.VIDEO);c(this,"stat",{});c(this,"_calculateTimeout",-1);c(this,"viewMirror",!1);c(this,"objectFit");c(this,"container");c(this,"canvas");c(this,"shouldRenderAlpha",!1);c(this,"_preSize",{width:0,height:0});c(this,"posterImg");this.mode=e.canvas?1:0,this.container=e.container,this.canvas=e.canvas,T(e.viewMirror)||(this.viewMirror=e.viewMirror),T(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}get isPlaying(){var e;return this._state!=="PLAYING"||this.element&&this.element.paused?!1:((e=this.track)==null?void 0:e.readyState)==="live"&&!this.track.muted}initializeElement(){var t;let e=document.createElement(_.VIDEO);this.track&&this.mode!==2&&(e.srcObject=new MediaStream([this.track])),e.muted=!0,e.setAttribute("id",`video_${this.id}`),e.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),e.setAttribute("autoplay","autoplay"),e.setAttribute("playsinline","playsinline"),this.element=e,_e&&(e.poster="noposter"),(t=this.container)==null||t.appendChild(this.elementToRender),this.bindElementEvents(),this.calculateStat()}get styleAttribute(){let e=`width: 100%; height: 100%; object-fit: ${this.objectFit};${this.shouldRenderAlpha?"":"background-color: black"};`;return this.viewMirror&&(e+="transform: scaleX(-1);"),e}setContainer(e){var t;this.container=e,this.track&&this.elementToRender&&((t=this.container)==null||t.appendChild(this.elementToRender))}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),e&&e.add(_.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(_.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent).add(_.RESIZE,this.handleElementEvent)}handleTrackEvent(e){var t;return e.type===_.MUTE&&((t=this.stat)!=null&&t.fps)&&(this.stat.fps=0),super.handleTrackEvent(e)}handleElementEvent(e){var r,s,n,a,d,l;if(this.mode===2)return;super.handleElementEvent(e);let t=e.type;if(t===_.PAUSE&&(this.container&&!this.container.isConnected&&(this._log.warn(`${this.kind} player has been remove, element ID: ${this.container.id}`),Ke(500).then(()=>{var u;(u=this.container)!=null&&u.isConnected&&(this._pausedRetryCount=$r,this._log.info(`view container ${this.container.id} is in dom, reset pausedRetryCount`))})),this._pausedRetryCount>0&&!br()&&!this._isPausedByUserCall&&(this._log.info(`[${$r-this._pausedRetryCount+1}/${$r}] ${this.kind} player auto resume when paused`),this.doResume(),this._pausedRetryCount--),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){let u=this.element.style.transform;t===_.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=u.replace("scaleX(-1)",""):t===_.LEAVE_PICTURE_IN_PICTURE&&!u.includes("scaleX")&&(this.element.style.transform=`${u} scaleX(-1)`)}t===_.RESIZE&&(this._preSize.height!==((r=this.element)==null?void 0:r.videoHeight)||this._preSize.width!==((s=this.element)==null?void 0:s.videoWidth))&&(this._log.info(`video size changed to ${(n=this.element)==null?void 0:n.videoWidth}x${(a=this.element)==null?void 0:a.videoHeight}`),this._preSize.height=((d=this.element)==null?void 0:d.videoHeight)||0,this._preSize.width=((l=this.element)==null?void 0:l.videoWidth)||0,this.emit(he.RESIZE,{newWidth:this._preSize.width,newHeight:this._preSize.height}))}setCanvas(e,t=1){var r,s,n,a;this.canvas!==e&&((r=this.canvas)==null||r.remove(),e==null||e.setAttribute("style",this.styleAttribute),this.canvas=e,this.mode=e?t:0,this.mode===2&&this.setTrack(e.captureStream().getVideoTracks()[0]),e?((s=this.element)==null||s.remove(),(n=this.container)==null||n.appendChild(e)):this.element&&((a=this.container)==null||a.appendChild(this.element)))}setAttr(e){let t=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},e);t.style=Object.assign({width:"100%",height:"100%"},t.style),super.setAttr(t)}get mirror(){return this.viewMirror}setRect(e,t){this.elementToRender&&(this.elementToRender.style.width=`${e}px`,this.elementToRender.style.height=`${t}px`)}setViewMirror(e){this.elementToRender&&(this.elementToRender.style.transform=e?"scaleX(-1)":""),this.viewMirror=e}setObjectFit(e){this.elementToRender&&(this.elementToRender.style.objectFit=`${e}`),this.objectFit=e}setPoster(e,t=!1){return new Promise(r=>{if(this.element)if(this._log.info("setPoster",e.slice(0,10)),this.element.poster=e,t&&(Re||ee)){if(e==="")this.removePosterImg();else if(!this.posterImg){let s=document.createElement("img");s.src=e,s.style=`position:absolute;top:0;left:0;${this.styleAttribute}`,s.onload=()=>f(this,null,function*(){var n;s.decode&&(yield s.decode()),this.posterImg=s,(n=this.container)==null||n.appendChild(s),r()})}}else r()})}removePosterImg(){this.posterImg&&(this.posterImg.remove(),URL.revokeObjectURL(this.posterImg.src),delete this.posterImg)}pause(){return f(this,null,function*(){return(Ve&&$e>=128||ee||Re)&&(yield this.setPoster(this.getVideoFrame(),!0)),Le(o.prototype,this,"pause").call(this)})}resume(){return this.posterImg&&this.setPoster("",!0),super.resume()}stop(e=0){var t;super.stop(e),(t=this.canvas)==null||t.remove(),this.removePosterImg()}play(){return this.element?this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender):this.initializeElement(),this.mode===2?Promise.resolve():super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(he.MEDIA_TRACK_CHANGED,e),e!==null&&(this.bindTrackEvents(),this.element&&this.mode!==2&&(this.element.srcObject=new MediaStream([e]),this.element.remove()),this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender)))}getVideoFrame(){if(this.canvas)return this.canvas.toDataURL("image/png");if(!this.element)return"";let e=document.createElement("canvas");return e.width=this.element.videoWidth,e.height=this.element.videoHeight,e.getContext("2d").drawImage(this.element,0,0),e.toDataURL("image/png")}getElement(){return this.element}calculateStat(){try{if(Ki()&&this.element&&this._calculateTimeout<0){let e=0,t=null,r=(s,n)=>{this.stat.width=n.width,this.stat.height=n.height,t&&(this.stat.fps=Math.round((n.presentedFrames-t.presentedFrames)/(s-e)*1e3)),e=s,t=n,this._calculateTimeout=-1,this.element&&(this._calculateTimeout=setTimeout(()=>{var a;return(a=this.element)==null?void 0:a.requestVideoFrameCallback(r)},2e3))};this.element.requestVideoFrameCallback(r)}}catch(e){this._log.warn("init stat failed",e)}}};function tr(o,i){return f(this,null,function*(){if(!o.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield o.audioWorklet.addModule(i),R.info("worklet addModule success")}catch(e){throw R.info(`worklet addModule catch error. ${e.message}`),e}})}var Nn;typeof AudioContext!="undefined"?Nn=AudioContext:typeof webkitAudioContext!="undefined"?Nn=webkitAudioContext:typeof mozAudioContext!="undefined"&&(Nn=mozAudioContext);var yu=1500,it,Fp=-1,Cd=0,vn=-1,Ru=!1,Bp=0,Hp=-1,$p=-1;Wp();function Wp(){try{if(it)return;it=new Nn({sampleRate:48e3}),it.onstatechange=()=>{R.info(`context state: ${it.state}${it.state!=="running"?` visibilityState: ${document.visibilityState}`:""}`),as()},clearTimeout(Fp)}catch(o){R.error(`initAudioContext failed: ${o} typeof AudioContextClass: ${typeof Nn}`),Fp=setTimeout(Wp,1e3)}}var as=()=>{it.state==="suspended"?(Cd=V(),GT(),Nr(),document.addEventListener("click",as)):it.state==="interrupted"?Nr():(Cd&&(y.addNumber({key:507800,value:V()-Cd,split:[0,500,1e3,1500,2e3,3e3,4e3,5e3,1e4,3e4],max:6e4}),Cd=0),JT(),document.removeEventListener("visibilitychange",as),document.removeEventListener("click",as))},Au=0,Cu=-1;function Nr(){return new Promise((o,i)=>{if(it.state==="running")return o();Date.now()-Au<1e3?(clearTimeout(Cu),Cu=setTimeout(()=>{Au=Date.now(),it.resume().then(o,i)},1e3)):(clearTimeout(Cu),Au=Date.now(),it.resume().then(o,i))}).catch(o=>{R.warn(`context resume failed: ${o}`),document.addEventListener("visibilitychange",as)})}document.addEventListener("click",as);function GT(){vn===-1&&(vn=setTimeout(()=>{it.state==="suspended"&&(Ru=!0,S.emit("155",{isSuspended:!0}))},yu))}function JT(){vn!==-1&&(clearTimeout(vn),vn=-1,Ru&&(Ru=!1,S.emit("155",{isSuspended:!1})))}function Gp(){if(!ge||$p!==-1)return;let o=()=>{V()-Bp<500||(it&&it.state==="running"&&it.currentTime===Hp&&(R.warn("context is fake running, auto resume"),it.suspend().catch(i=>{R.warn(`context suspend failed: ${i}`)})),Hp=it.currentTime,Bp=V())};$p=setInterval(()=>{o()},2e3),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&o()})}var Ee=o=>it;var Ue=class{constructor(i){this.name=i;c(this,"node");c(this,"node2");c(this,"pre",new Set);c(this,"next",new Set);c(this,"context");c(this,"connectedNodes",new Set);c(this,"nextInputChannelMap",new Map);c(this,"_channelCount",1)}get channelCount(){return this._channelCount}set channelCount(i){this._channelCount=i,this.setChannelCount(this.node,i),this.setChannelCount(this.node2,i),this.next.forEach(e=>e.channelCount=i)}setChannelCount(i,e){!i||i instanceof ScriptProcessorNode||(i.channelCountMode="explicit",i.channelCount=e||this.channelCount||1)}setContext(i){this.context=i,this.node&&i.addMixWeight()}removeContext(){var i;this.node&&((i=this.context)==null||i.reduceMixWeight()),delete this.context}replaceNode(i){var e;if(i!==this.node)try{this.node?this._disconnect():(e=this.context)==null||e.addMixWeight(),this.node=i,this.setChannelCount(this.node),this.preNodeReconnect(),this.reconnect()}catch(t){R.error(t)}}setNode(i,e){var t;if(!this.node)try{(t=this.context)==null||t.addMixWeight(),this.node=i,this.setChannelCount(this.node),e&&(this.node2=e,this.setChannelCount(this.node2)),this.preNodeReconnect(),this.reconnect(),y.addSuccessEvent({key:502701})}catch(r){R.error(r),y.addFailedEvent({key:502701,error:r})}}deleteNode(){var i;if(this.node)try{this._disconnect(),delete this.node,delete this.node2,(i=this.context)==null||i.reduceMixWeight(),this.preNodeReconnect(),y.addSuccessEvent({key:502702})}catch(e){R.error(e),y.addFailedEvent({key:502702,error:e})}}preNodeReconnect(){this.pre.forEach(i=>{i.node?i.reconnect():i.preNodeReconnect()})}connectNext(i){this.next.forEach(e=>{let t=this.nextInputChannelMap.get(e);i._connect(e.node,t)||e.connectNext(i)})}_connect(i,e=0){return!this.node||!i?!1:((this.node2||this.node).connect(i,0,e),this.connectedNodes.add(i),!0)}_disconnect(){this.connectedNodes.forEach(i=>{var e;return(e=this.node2||this.node)==null?void 0:e.disconnect(i)}),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(i,e=0){return this.next.add(i),i.pre.add(this),this.nextInputChannelMap.set(i,e),i}},Rd=class extends Ue{constructor(e=256){super();this.fftSize=e;c(this,"dataArray",new Uint8Array(0))}setNode(e){e.fftSize=this.fftSize,this.dataArray=new Uint8Array(e.frequencyBinCount),super.setNode(e)}getByteTimeDomainData(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),this.dataArray}get level(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),Math.max(...this.dataArray)/128-1}get timeDomainPathData(){let e=this.getByteTimeDomainData(),t=1,r=0,s=0,n=`M${r},${s}`;for(let a=0;a<e.length;a++)s=e[a]/128*100/2,n+=`L${r},${s}`,r+=t;return n}},Dn=class{constructor(){c(this,"source",new Ue);c(this,"gain",new Ue);c(this,"destination",new Ue)}get volume(){var i;return((i=this.gain.node)==null?void 0:i.gain.value)||1}setVolume(i){if(i===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(Ee().createGain()),this.gain.node.gain.value=i}replaceSource(i){let e=Mn(i);e&&this.source.replaceNode(e)}get track(){var i;return(i=this.stream)==null?void 0:i.getAudioTracks()[0]}get stream(){var i;return(i=this.destination.node)==null?void 0:i.stream}},ds=class extends Dn{constructor(e){super();this.context=e;c(this,"aec",new Ue("aec"));c(this,"mixNode",new Ue("mixNode"));c(this,"silentNode",new Ue("silentNode"));c(this,"denoiser",new Ue("denoiser"));c(this,"voiceChanger",new Ue("voiceChanger"));this.source.pipeTo(this.aec).pipeTo(this.denoiser).pipeTo(this.voiceChanger).pipeTo(this.gain).pipeTo(this.destination),this.silentNode.pipeTo(this.mixNode).pipeTo(this.aec,1)}get isProcessEnabled(){return this.aec.node||this.denoiser.node||this.voiceChanger.node||this.gain.node}connect(){this.context.inputs.has(this)||(this.destination.setNode(this.context.destination),this.source.setContext(this.context),this.aec.setContext(this.context),this.silentNode.setContext(this.context),this.mixNode.setContext(this.context),this.denoiser.setContext(this.context),this.voiceChanger.setContext(this.context),this.gain.setContext(this.context),this.context.inputs.add(this))}disconnect(){this.context.inputs.has(this)&&(this.destination.deleteNode(),this.source.removeContext(),this.aec.removeContext(),this.silentNode.removeContext(),this.mixNode.removeContext(),this.denoiser.removeContext(),this.voiceChanger.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.aec.deleteNode(),this.silentNode.deleteNode(),this.mixNode.deleteNode(),this.denoiser.deleteNode(),this.voiceChanger.deleteNode(),this.source.deleteNode(),this.disconnect()}setVolume(e){if(e===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(this.context.audioContext.createGain()),this.gain.node.gain.value=e}},yd=class{constructor(){c(this,"audioContext",Ee("audio-mixer"));c(this,"destination",this.audioContext.createMediaStreamDestination());c(this,"inputs",new Set);c(this,"mixWeight",0);this.destination.channelCount=1}addMixWeight(i=1){this.mixWeight+=i,this.mixWeight-1===i+1>>1&&this.mixOnChange()}reduceMixWeight(i=1){this.addMixWeight(-i)}close(){this.inputs.forEach(i=>i.remove())}get mixTrack(){return this.destination.stream.getAudioTracks()[0]}},Jp=new WeakMap;function Mn(o){try{let i=Jp.get(o);if(i)return i;let e=Ee();if(o instanceof HTMLAudioElement)i=e.createMediaElementSource(o);else if(o instanceof MediaStreamTrack)i=e.createMediaStreamSource(new MediaStream([o]));else return o;return Jp.set(o,i),i}catch(i){if(ee&&i instanceof Error&&i.name==="NotSupportedError")R.warn(i);else throw i}}var Ot=class Ot{constructor(i){c(this,"_volume",0);c(this,"_volumeDb",0);c(this,"_log");c(this,"_scriptProcessorNode",null);c(this,"_audioWorkletNode",null);c(this,"_interval",200);c(this,"ready",this.preload());let{log:e}=i;this._log=e,S.on(A.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-Ot.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!Ot.workletReady){let i='class VolumeMeterWorklet extends AudioWorkletProcessor{constructor(){super(),this.volume=0,this.intervalTime=200,this.tick=200,this.isStop=!1,this.cache=[],this.sentFirstInfo1=!1,this.unmute=!1,this.port.onmessage=t=>{var e=t.data;switch(e.name){case"chunk":this.cache.push(...e.data),this.sentFirstInfo1||(this.port.postMessage({cl:e.data.length}),this.sentFirstInfo1=!0);break;case"setIntervalTime":this.intervalTime=e.intervalTime;break;case"unmute":this.unmute=!0;break;case"stop":this.isStop=!0}}}process(t,s){t=t[0],s=s[0];if(t||s){if(this.isStop)return!1;var i=s&&s[0]?s[0].length:0,h=this.cache.length,a=(i<h?(s[0].set(this.cache.slice(0,i)),this.cache=this.cache.slice(i)):this.unmute&&s[0].set(t[0]),(i<h?s:t)[0]);if(a){let e=0;for(let t=0;t<a.length;++t)e=Math.max(Math.abs(a[t]),e);s=a.reduce((t,e)=>t+e*e,0)/a.length;this.volume=e,this.tick-=a.length,this.tick<0&&(this.tick+=this.intervalTime/1e3*sampleRate,this.port.postMessage({volume:this.volume,volumeDb:Math.max(10*Math.log10(s)+100,0)/100,cacheLen:h,outputLen:i}))}}return!0}}registerProcessor("volume-meter",VolumeMeterWorklet);';Ot.workletReady=tr(Ot.audioContext,URL.createObjectURL(new Blob([i],{type:"application/javascript"})))}return Ot.workletReady.then(()=>this.initAudioWorklet()).catch(i=>(this._log.error(`volumeMeter preload error: ${i}`),this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(Ot.audioContext,"volume-meter");let i=!1;this._audioWorkletNode.port.onmessage=e=>{Ot.lastMessageTime=Date.now(),this._volume=e.data.volume||0,this._volumeDb=e.data.volumeDb||0,!i&&e.data.cacheLen&&e.data.outputLen&&(this._log.warn("worklet play success"),i=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(i){this._log.error(`volumeMeter init audio worklet error: ${i}`),se.logFailedEvent({userId:this._log.userId,eventType:Ze.LOAD_WORKLET,error:i}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=Ee("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=i=>{Ot.lastMessageTime=Date.now();let e=i.inputBuffer.getChannelData(0),t=0;for(let r=0;r<e.length;++r)t+=e[r]*e[r];this._volume=Math.sqrt(t/e.length)||0}}catch(i){this._log.error(`volumeMeter init script processor error: ${i}`)}}destroy(){this._scriptProcessorNode&&(this._scriptProcessorNode.onaudioprocess=null),this._audioWorkletNode&&(this._audioWorkletNode.port.postMessage({name:"stop"}),this._audioWorkletNode.port.onmessage=null),this._audioWorkletNode=null,this._scriptProcessorNode=null,S.off(A.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}getVolumeDb(){return Math.floor(this._volumeDb*100)}handleAudioLevelInterval(i){var t;let{interval:e}=i;this._interval=e,(t=this._audioWorkletNode)==null||t.port.postMessage({name:"setIntervalTime",intervalTime:e})}};c(Ot,"lastMessageTime",0),c(Ot,"audioContext",Ee("volume-meter")),c(Ot,"workletReady");var bd=Ot,On=class extends Ue{constructor(e){super();c(this,"_volumeMeter");this._volumeMeter=new bd(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return f(this,null,function*(){yield this._volumeMeter.preload(),this.setNode(this._volumeMeter.node)})}getCalculatedVolume(){return this._volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this._volumeMeter.getInternalAudioLevel()}getVolumeDb(){return this._volumeMeter.getVolumeDb()}write(e){if(this.node){let t=e.allocationSize({planeIndex:0}),r=new Float32Array(t>>2);e.copyTo(r,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:r},[r.buffer]),e.close()}}},so=bd;var zp=Je(nt(),1);var jp=o=>i=>i.deviceId===o;var kn=class{constructor(i,e){c(this,"kind");c(this,"type");c(this,"devices",[]);this.kind=i,this.type=e}update(i,e){let t=i.filter(r=>r.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);if(this.devices.length===1&&ls(this.devices[0])){this.devices=t;return}e&&(t.forEach(r=>{if(r.deviceId&&!this.devices.find(jp(r.deviceId))){let s=`${this.kind}${this.type}Added`;R.warn(`${s}: ${JSON.stringify(r)}`),e.emit(s,r)}}),this.devices.forEach(r=>{if(r.deviceId&&!t.find(jp(r.deviceId))){let s=`${this.kind}${this.type}Removed`;R.warn(`${s}: ${JSON.stringify(r)}`),e.emit(s,r)}})),this.devices=t}hasDevice(i){return!!this.devices.find(e=>e.deviceId===i)}},bu=class extends zp.EventEmitter{constructor(){super();c(this,"audioInputs",new kn(_.AUDIO,"Input"));c(this,"videoInputs",new kn(_.VIDEO,"Input"));c(this,"audioOutputs",new kn(_.AUDIO,"Output"));this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||oe.run("interval",()=>{this.update()},{delay:1e4}))}init(){cs().then(e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)})}update(){return f(this,arguments,function*(e=0){let t=yield cs(e);return this.audioInputs.update(t,this),this.videoInputs.update(t,this),this.audioOutputs.update(t,this),this})}hasBlueTooth(){var t;if(((t=Ee())==null?void 0:t.outputLatency)*1e3>150)return!0;let e=["bluetooth","air","wireless","bt","tws","buds","headset","headphone"];return this.audioOutputs.devices.some(r=>e.some(s=>r.label.toLowerCase().includes(s)))||this.audioInputs.devices.some(r=>e.some(s=>r.label.toLowerCase().includes(s)))}},be=xs||Do?null:new bu;function ls(o){return o.deviceId===o.groupId&&o.groupId===""}function cs(){return f(this,arguments,function*(o=0){if(Zi()||!md())return[];let i=yield navigator.mediaDevices.enumerateDevices();if(o!==0){let e={audio:!1,video:!1};if(i.forEach(t=>{ls(t)&&(t.kind===_.AUDIO_INPUT?e.audio=!0:t.kind===_.VIDEO_INPUT&&(e.video=!0))}),o===2&&(e.audio=!1),o===1&&(e.video=!1),e.audio||e.video){let t;try{t=yield navigator.mediaDevices.getUserMedia(e),e.audio&&Nr()}catch(r){R.debug("capture before getDevices failed: ",r)}i=yield navigator.mediaDevices.enumerateDevices(),t==null||t.getTracks().forEach(r=>r.stop())}}return i.map((e,t)=>{let r={kind:e.kind,deviceId:e.deviceId,groupId:e.groupId,label:e.label||`${e.kind}_${t}`};return e.deviceId.length>0&&Nu.add(`${e.deviceId}_${e.kind}`),e.getCapabilities&&(r.getCapabilities=()=>e.getCapabilities()),r})})}function It(o=!1){return be.update(o?1:0).then(i=>i.audioInputs.devices)}function At(o=!1){return be.update(o?2:0).then(i=>i.videoInputs.devices)}var Xp=!1;function Qp(){return f(this,null,function*(){try{Xp||(Xp=!0,R.info(`speakers:${(yield vr()).map(o=>` ${o.deviceId.slice(0,8)}: ${o.label}`)}`))}catch(o){}})}function vr(o=!1){return f(this,null,function*(){return(ge||Re)&&(o=!1),be.update(o?1:0).then(i=>i.audioOutputs.devices)})}var Nu=new Set;function Yp(o){if(o instanceof CanvasCaptureMediaStreamTrack||!(o instanceof MediaStreamTrack))return!1;let i=o.label.toLocaleLowerCase();if(i.includes("camera")||i.includes("webcam"))return!0;let t=`${((o==null?void 0:o.getSettings())||{}).deviceId}_${_.VIDEO_INPUT}`;return!!Nu.has(t)}function Zp(o){if(o instanceof CanvasCaptureMediaStreamTrack||!(o instanceof MediaStreamTrack))return!1;let i=o.label.toLocaleLowerCase();if(i.includes("mic")||i.includes("\u9EA6\u514B\u98CE"))return!0;let t=`${((o==null?void 0:o.getSettings())||{}).deviceId}_${_.AUDIO_INPUT}`;return!!Nu.has(t)}function vu(o,i){return f(this,null,function*(){let t=(yield It()).find(r=>r.deviceId===Wr);return!i&&(t==null?void 0:t.groupId)===o||(t==null?void 0:t.groupId)===o&&t.label===i})}function Kp(s){return f(this,arguments,function*({newDeviceId:o,oldDeviceId:i,oldGroupId:e,oldLabel:t,kind:r}){return o!==i?!1:r===_.AUDIO&&o===Wr?yield vu(e,t):!0})}var Nd,Du=class extends Dn{constructor(e){super();this.log=e;c(this,"volumeMeter");c(this,"volumeMeterAfter3A");c(this,"volumeDestination");c(this,"analyser",new Rd);this.volumeMeter=new On({log:this.log}),this.volumeMeterAfter3A=new On({log:this.log}),this.volumeDestination=new Ue,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},us=class o extends fi{constructor(e){super(e,_.AUDIO);c(this,"_outputDeviceId");c(this,"_volume",1);c(this,"_destination",Ee("player").createMediaStreamDestination());c(this,"pipeline");c(this,"volumeMeterMode","worklet");c(this,"enableVolumeControlInIOS");this.enableVolumeControlInIOS=e.enableVolumeControlInIOS,this.mode=0,e.url&&(this.url=e.url),this.pipeline=new Du(this._log)}setTrack(e){}get duration(){var e;return Math.floor((((e=this.element)==null?void 0:e.duration)||0)*1e3)}get currentTime(){var e;return Math.floor((((e=this.element)==null?void 0:e.currentTime)||0)*1e3)}set currentTime(e){this.element&&(this.element.currentTime=e/1e3)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(e){if((ht==="15.2"||ht==="15.3"||ht==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}(ri||oi)&&ht>="18.7"&&this.bindAutoPlayEvent();let r=Nd||new Audio;r.setAttribute("autoplay","autoplay"),r.srcObject=this.getMediaStream(),r.muted=this.muted,this.url&&(r.crossOrigin="anonymous",r.src=this.url),this.element=r,Q(e)&&(this.element.volume=Math.min(Math.max(e,0),1)),r===Nd&&(Nd=void 0),this.options.enableTimeupdateEvent&&(this.element.ontimeupdate=()=>this.emit(he.TIME_UPDATE,this.currentTime)),this.bindElementEvents(),this._log.info("initializeElement success")}play(e){return f(this,null,function*(){if(!(!this.track&&!this.url))return!this.pipeline.source.node&&this.track&&this.pipeline.replaceSource(this.track),this.element||this.initializeElement(e==null?void 0:e.volume),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),this.volumeMeterMode==="worklet"?(this.pipeline.volumeMeter.init(),this.pipeline.volumeMeterAfter3A.init(),this._log.info("volumeMeter init success")):this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(Ee("player").createAnalyser()),Qp(),Le(o.prototype,this,"play").call(this)})}stop(e=0){this.pipeline.destroy(),super.stop(e)}setVolume(e){this._volume=e,this.element&&(this.element.volume=e)}setSinkId(e){return f(this,null,function*(){var t,r;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield(r=(t=this.element).setSinkId)==null?void 0:r.call(t,e))})}get useDestination(){return!!this.pipeline.stream}setLoop(e){this.element&&(this.element.loop=e)}getAudioLevel(){return this.pipeline.volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this.pipeline.volumeMeter.getInternalAudioLevel()}getInternalAudioLevelAfter3A(){return this.pipeline.volumeMeterAfter3A.getInternalAudioLevel()}},vd=class extends us{setTrack(i){this.track!==i&&(this.unbindTrackEvents(),this.track=i,this.emit(he.MEDIA_TRACK_CHANGED,i),i&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([i]))))}},Dd=class extends us{constructor(e){super(e);c(this,"_sourceElement");c(this,"_output",new Ue);this.pipeline.source.pipeTo(this.pipeline.gain),this.pipeline.gain.pipeTo(this.pipeline.volumeMeter).pipeTo(this._output),this.pipeline.gain.pipeTo(this.pipeline.destination)}setOutput(){this.mode=1,this._output.setNode(Ee("player").destination)}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var t,r,s;((r=(t=this.element)==null?void 0:t.error)==null?void 0:r.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(he.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([e]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e])),this.pipeline.source.channelCount=((s=e.getSettings())==null?void 0:s.channelCount)||1,this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){if(this._volume=e,this.useDestination)this.pipeline.setVolume(e),this._log.info(`set pipeline volume: ${e}`);else if(e<=1&&!ge)this.element?(this._log.info(`set element volume: ${e}`),this.element.volume=e):this._log.info("set element volume: no element");else{if(ge)if(this.enableVolumeControlInIOS)Gp();else return;if(ee&&!this.pipeline.source.node){this._log.warn("set pipeline volume failed: no source node");return}this._log.info(`start set pipeline volume: ${e}`),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),we(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play())}}stop(e=0){this.pipeline.destroy();let t=this._sourceElement||this.element;t&&Ft&&(Nd=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}};var no=class extends j{constructor({userId:e,sdkAppId:t,mediaType:r,room:s,PlayerClass:n=r===1?Dd:pt}){var a;super();c(this,"id",an());c(this,"userId","");c(this,"isRemote");c(this,"mediaType");c(this,"room");c(this,"user");c(this,"_log");c(this,"_inputTrack");c(this,"_outputTrack");c(this,"isPlayCalled");c(this,"container",null);c(this,"player");c(this,"subVideoPlayerMap");c(this,"muted",!1);c(this,"abortCtrl");c(this,"objectFit","cover");c(this,"mirror");c(this,"rotation");c(this,"isScreen",!1);c(this,"manager");c(this,"trackSettings");c(this,"isFirstVideoFrameEmitted",!1);this.userId=e||"",this.mediaType=r,this._log=R.createLogger({parent:s==null?void 0:s.getLogger(),id:`${this.kind[0]}t`,userId:(a=s||this.room)==null?void 0:a.userId,remoteUserId:this instanceof _i?void 0:this.userId,sdkAppId:t,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof _i}),this.player=new n({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log,enableVolumeControlInIOS:s==null?void 0:s.enableVolumeControlInIOS}),this.player.on(he.PLAYER_STATE_CHANGED,d=>{if(S.emit(A.PLAYER_STATE_CHANGED,M({track:this},d)),this.emit("player-state-changed",d),d.state==="PLAYING"&&this.room){let l=!0;for(let{remoteAudioTrack:u,remoteVideoTrack:h,remoteAuxiliaryTrack:p}of[...this.room.remotePublishedUserMap.values()])if(u.isAvailable&&!u.player.isPlaying||h.isAvailable&&!h.player.isPlaying||p.isAvailable&&!p.player.isPlaying){l=!1;break}l&&br()&&Vp()}}),this.kind===_.VIDEO&&(this.player.on(he.LOADED_DATA,()=>{this.emitFirstVideoFrameEvent(he.LOADED_DATA),S.emit(A.VIDEO_LOADED_DATA,{track:this})}),this.player.on(he.LOADED_META_DATA,()=>{this.emitFirstVideoFrameEvent(he.LOADED_META_DATA)}),this.player.on(he.MEDIA_TRACK_CHANGED,d=>{var l;(l=this.subVideoPlayerMap)==null||l.forEach(u=>u.setTrack(d))}),this.player.on(he.RESIZE,d=>{this.emitFirstVideoFrameEvent(he.RESIZE),this.emit("video-size-changed",M({userId:this.userId,streamType:this.mediaType===2?"auxiliary":"main"},d))})),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(he.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||R}get kind(){return this.mediaType===1?_.AUDIO:_.VIDEO}get isAudio(){return this.kind===_.AUDIO}get strMediaType(){return this.mediaType===4?_.VIDEO:this.mediaType===2?_.SCREEN:_.AUDIO}get streamType(){return(this.mediaType&2)===0?"main":"auxiliary"}get isMediaTrackActive(){return this.mediaTrack?!this.mediaTrack.muted&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled:!1}play(e,t){return f(this,null,function*(){let r=Ae(e)?e[0]:e;if(this.isPlayCalled){this.log.info(`play update options: ${JSON.stringify(t)}`),t&&!T(t.muted)&&this.setPlayerMute(t.muted),t&&!T(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof pt&&(this.player.setObjectFit(this.objectFit),this.container!==r&&r&&(this.container=r,this.player.setContainer(r)),Ae(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t)));return}if(t&&!T(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===_.VIDEO)&&this.setPlayerMute(!0),t&&!T(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof pt&&(this.player.setObjectFit(this.objectFit),t&&!T(t.poster)&&this.player.setPoster(t.poster)),this.isPlayCalled=!0,r&&(this.container=r,this.player instanceof pt&&this.player.setContainer(r)),S.emit(A.PLAY_TRACK_START,{track:this}),!this._outputTrack){this.log.info("play has not mediaTrack, abort");return}this._log.info(`play with options: ${JSON.stringify(t)}`);try{this.player.setTrack(this.playerMediaTrack),yield this.player.play(t),Ae(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(s){throw this.handleAutoPlayFailed(s),s}})}setMirror(e,t){if(this.isScreen||this.kind!==_.VIDEO||T(e)||e===this.mirror)return;this.mirror=e;let r=this.player;t&&(r=t);let s=this.manager;if(ue(this.mirror)){r.setViewMirror(this.mirror),!this.isRemote&&s&&(s.mirror=!1);return}switch(this.mirror){case"view":{s&&(s.mirror=!1),r.setViewMirror(!0);break}case"publish":{s&&(s.mirror=!0),r.setViewMirror(!0);break}case"both":s&&(s.mirror=!0),r.setViewMirror(!1)}}playSubContainer(e,t){return f(this,null,function*(){if(!this._outputTrack||this.kind===_.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((s,n)=>{var a;e.find(d=>n===d)||(s.stop(),(a=this.subVideoPlayerMap)==null||a.delete(n))});for(let[s,n]of e.entries()){let a=this.subVideoPlayerMap.get(n);a?t&&(T(t.objectFit)||a.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new pt({id:this.userId||this.id,track:this.playerMediaTrack,container:n,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:`vp-sub${s+1}`})}))}let r=[...this.subVideoPlayerMap.values()];for(let s of r)s.setViewMirror(this.player.mirror),yield s.play()})}setAudioOutput(e){return this.player.setSinkId(e)}setAudioVolume(e){this.player.setVolume(e)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var e;return((e=this.player)==null?void 0:e.getInternalAudioLevel())||0}stop(e=!1){this.isPlayCalled&&(this.isPlayCalled=!1,this.isFirstVideoFrameEmitted=!1,this.player&&(this.log.info(`stop ${this.kind} player`),this.player.stop(La(this)&&!e?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(t=>{t.stop()}),this.container=null)}resume(){return f(this,null,function*(){var e;this.isPlayCalled&&(yield(e=this.player)==null?void 0:e.resume())})}close(){this.log.info("close"),this.isPlayCalled&&this.stop(!0)}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),S.emit(e?A.TRACK_MUTED:A.TRACK_UNMUTED,{track:this})}setPlayerMute(e){this.player.setMuted(e)}get mediaTrack(){return this._inputTrack||null}get outMediaTrack(){return this._outputTrack||null}get playerMediaTrack(){return this.outMediaTrack}installTrackEvent(e){tt(e,e).add(_.MUTE,this.onTrackMuted).add(_.UNMUTE,this.onTrackUnmuted).add(_.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===_.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){we(e)}setInputMediaStreamTrack(e){var r;let t=this._inputTrack;if(e!==t)return this._inputTrack=e,this.trackSettings=(r=e.getSettings)==null?void 0:r.call(e),e.enabled=!this.muted,t&&this.uninstallTrackEvent(t),this.installTrackEvent(e),this.emit("input-media-track-changed",e||null,t||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var r;let t=this._outputTrack;e!==t&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",(r=e.getSettings)==null?void 0:r.call(e).deviceId,e.label),this._outputTrack=e,this._inputTrack&&(this._outputTrack.contentHint=this._inputTrack.contentHint,this._outputTrack.enabled=this._inputTrack.enabled),this.updatePlayingState(!!e),this.emit("output-media-track-changed",e))}setMediaType(e){this.mediaType=e}updatePlayingState(e){var t,r;if(this.isPlayCalled){if(e){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped){this.player.play().catch(s=>this.handleAutoPlayFailed(s)),this.log.info(`playing state updated, play ${this.kind}`);return}}else if(!this.player.isStopped){if(La(this)&&this.isAudio&&((t=this.user)!=null&&t.muteState.hasAudio)&&((r=this.user)!=null&&r.muteState.audioMuted))return;this.player.stop(La(this)?this.jitterBufferDelay:0),this.log.info(`playing state updated, stop ${this.kind}`);return}}this.log.debug(`updatePlayingState abort ${this.isPlayCalled} ${e} ${this.player.isStopped}`)}handleAutoPlayFailed(e){return f(this,null,function*(){var r;this.log.warn("handleAutoPlayFailed",e);let t=()=>{this.resume().then(()=>{document.removeEventListener("click",t,!0)})};if(this.room&&this.room.enableAutoPlayDialog){if((ri||oi)&&(yield Ke(100),(r=this.player)!=null&&r.isPlaying))return;ns()}else document.addEventListener("click",t,!0);S.once(A.LOCAL_TRACK_CAPTURE_SUCCESS,({track:s})=>{s.kind==="audio"&&br()&&!this.player.isPlaying&&this.isRemote&&this.isAvailable&&t()}),this.emit("error",e)})}getVideoFrame(){return this.player instanceof pt?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(e){var n,a,d;if(this.isFirstVideoFrameEmitted)return;let t=(n=this.mediaTrack)==null?void 0:n.getSettings(),r=(t==null?void 0:t.width)||((a=this.player.element)==null?void 0:a.videoWidth)||0,s=(t==null?void 0:t.height)||((d=this.player.element)==null?void 0:d.videoHeight)||0;e===he.RESIZE&&!r&&!s||e===he.LOADED_META_DATA&&!r&&!s||(e===he.LOADED_DATA&&!r&&!s&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,bt(this.rotation)&&([r,s]=[s,r]),this.emit("first-video-frame",{width:r,height:s,streamType:this.streamType,userId:this.isRemote?this.userId:""}))}onTrackMuted(){this._log.warn(`${this.kind} track is unable to provide media output`)}onTrackUnmuted(){this._log.info(`${this.kind} track is able to provide media output`)}onTrackEnded(){this._log.warn(`${this.kind} track ended`)}};D([ye([],j.INIT,{sync:!0})],no.prototype,"close",1);var qT=Object.prototype.hasOwnProperty,{toString:yb}=Object.prototype;function jT(o){if(o==null)return!0;if(typeof o=="boolean")return!1;if(typeof o=="number")return o===0;if(typeof o=="string"||typeof o=="function"||Array.isArray(o))return o.length===0;if(o instanceof Error)return o.message==="";if(dt(o))switch(Object.prototype.toString.call(o)){case"[object File]":case"[object Map]":case"[object Set]":return o.size===0;case"[object Object]":{for(let i in o)if(qT.call(o,i))return!1;return!0}}return!1}var gi=jT;var XT=function(o){return f(this,null,function*(){let i=QT(o);R.info(`getUserMedia with constraints: ${JSON.stringify(i)}`);let e=[],t=[],r=["label","deviceId","groupId"];if(i.audio&&(e=yield It(),R.info(`microphones: ${gt(e.map(s=>w(M({},s),{groupId:s.groupId.substring(0,8)})),{keysToInclude:r})}`)),i.video&&(t=yield At(),R.info(`cameras: ${gt(t,{keysToInclude:r})}`),!ue(i.video)&&i.video.facingMode==="user"&&!i.video.deviceId)){let n=t.filter(a=>!a.label.includes("infrared")).find(a=>a.label.includes("facing front"));n&&(i.video.deviceId=n.deviceId,R.info(`exclude infrared camera: ${JSON.stringify(i)}`))}try{let s=yield navigator.mediaDevices.getUserMedia(i);return nu&&s.getTracks().forEach(n=>{var d;let a=n.getCapabilities();R.info(`${n.kind} capabilities: ${gt(a,{keysToInclude:Sa})}`),!T(o.echoCancellation)&&((d=a.echoCancellation)==null?void 0:d.indexOf(o.echoCancellation))===-1&&R.warn(`Invalid argument for 'echoCancellation'. Expected one of [${JSON.stringify(a.echoCancellation)}], but received '${o.echoCancellation}'`)}),i.audio&&Nr(),s}catch(s){let{message:n}=s;throw s.name==="NotFoundError"&&(o.video&&t&&t.length===0&&(n=$({key:B.CAMERA_NOT_FOUND})),o.audio&&e&&e.length===0&&(n=$({key:B.MICROPHONE_NOT_FOUND}))),new v({code:I.INITIALIZE_FAILED,name:s.name,message:n,constraint:s.constraint})}})},zT=Ri({retryFunction:XT,settings:{retries:3,timeout:500},onError:({error:o,retry:i,reject:e,retryFuncArgs:t,retriedCount:r})=>{let s=r+1;o.name==="NotReadableError"||o.name==="OverconstrainedError"||o.name==="AbortError"?(s===1?(t[0].video&&(t[0].maxResolution=!1,(!Re||t[0].width*t[0].height<=1920*1080)&&t[0].frameRate&&(t[0].frameRate=t[0].frameRate>10?10:5)),t[0].retryWhenExactFailed&&t[0].useExactDeviceId&&(t[0].useExactDeviceId=!1)):s===2?t[0].useDeviceIdOnly=!0:s===3&&!t[0].useExactDeviceId&&(t[0].useTrueAsConstraint=!0),i()):e(o),t[0].microphoneId&&ef(t[0].microphoneId,!1),t[0].cameraId&&ef(t[0].cameraId,!0)},onRetrying:o=>{R.warn(`getUserMedia NotReadableError observed, retrying [${o}/3]`)},onRetryFailed:o=>{se.logFailedEvent({eventType:Ze.GET_USER_MEDIA_RETRY,error:o})},onRetrySuccess:o=>{se.logSuccessEvent({eventType:Ze.GET_USER_MEDIA_RETRY}),se.uploadEvent({log:`stat-${Ze.GET_USER_MEDIA_RETRY}-success-${o}`})}});function ef(o,i){return f(this,null,function*(){let t=(i?yield At():yield It()).find(r=>r.deviceId===o);t&&le(t.getCapabilities)&&R.warn(gt(t.getCapabilities(),{keysToInclude:Sa}))})}function QT(o){return{audio:YT(o),video:ZT(o)}}function YT(o){if(!o.audio)return!1;if(o.useTrueAsConstraint)return!0;let i={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:o.sampleRate};return!gi(o.microphoneId)&&(i.deviceId=o.useExactDeviceId?{exact:o.microphoneId}:o.microphoneId,o.useDeviceIdOnly)?i:(Q(o.channelCount)&&(i.channelCount=o.channelCount),(ue(o.echoCancellation)||o.echoCancellation==="remote-only"||o.echoCancellation==="all")&&(i.echoCancellation=o.echoCancellation),ue(o.noiseSuppression)&&!o.noiseSuppression&&(i.noiseSuppression=!1),ue(o.autoGainControl)&&!o.autoGainControl&&(i.autoGainControl=!1),gi(i)?!0:i)}function ZT(o){if(!o.video)return!1;if(o.useTrueAsConstraint)return!0;let{maxResolution:i=!0}=o,e={};return o.cameraId?e.deviceId=o.useExactDeviceId?{exact:o.cameraId}:o.cameraId:o.facingMode&&(e.facingMode=o.facingMode),o.useDeviceIdOnly&&!gi(e)?e:(o.width&&(e.width={ideal:o.width},i&&!ee&&(e.width.max=o.width)),o.height&&(e.height={ideal:o.height},i&&!ee&&(e.height.max=o.height)),ee&&si&&o.width&&o.height&&o.width*o.height<352*288&&(e.width=o.width,e.height=o.height),o.frameRate&&(e.frameRate=o.frameRate),gi(e)?!0:e)}var tf=zT;function Md(o){return Y((i,e)=>function(...t){return f(this,null,function*(){return yield o.apply(this,t),i.apply(this,t)})})}function Ct(o){return Y((i,e)=>function(...t){return f(this,null,function*(){let r=yield i.apply(this,t);return yield o.call(this,...t),r})})}function Od(o){return Y((i,e)=>function(...t){return f(this,null,function*(){try{return yield i.apply(this,t)}catch(r){o.call(this,r)}})})}function Y(o){return function(i,e,t){return t.value=o(t.value,e),t}}var rf=(()=>{let o=!1,i=document.visibilityState;return()=>{document.visibilityState!==i&&R.info(`visibility change: ${document.visibilityState}`),!o&&(document.addEventListener("visibilitychange",()=>{R.info(`visibility change: ${document.visibilityState}`),i=document.visibilityState}),o=!0)}})();var KT=0,kd=class{constructor(){c(this,"log",R.createLogger({id:`fq${++KT}`}));c(this,"isRunning",!1);c(this,"queue",[])}get length(){return this.queue.length}get lastQueueItem(){return this.length===0?null:this.queue[this.length-1]}push(i,e=!1){var s,n;let t=M({},i),r=new Promise((a,d)=>{t.resolve=a,t.reject=d});return t.promise=r,e?this.length<=1?this.queue.push(t):(n=(s=this.lastQueueItem)==null?void 0:s.promise)==null||n.then(t.resolve,t.reject):this.queue.push(t),this.log.debug(`push ${this.length}`),this.isRunning||this.callNext(),r}shift(){let i=this.queue.shift();return this.log.debug(`shift ${this.length}`),i}callNext(){if(this.isRunning||this.length===0)return;this.log.debug("callNext ",this.length);let{fn:i,args:e,context:t,resolve:r,reject:s}=this.queue[0];this.isRunning=!0,i.apply(t,e).then(r,s).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},Pd=new WeakMap,Ld=new WeakMap;function ir(o=!1){return function(i,e,t){let r=t.value;return t.value=function(...s){let n=Pd.get(this)||new kd;return Pd.set(this,n),n.push({fn:r,args:s,context:this},o)},t}}function xd(o){return function(i,e,t){let r=t.value;return t.value=function(...s){var a,d,l;let n=[];return(d=(a=Pd.get(this))==null?void 0:a.queue)==null||d.forEach(u=>n.push(u)),(l=Ld.get(this))==null||l.forEach(u=>u==null?void 0:u.queue.forEach(h=>n.push(h))),n.forEach(u=>{u.reject(new v({code:I.API_CALL_ABORTED,message:o}))}),Pd.delete(this),Ld.delete(this),r.apply(this,s)},t}}function Ti(o){return function(i,e,t){let r=t.value,s=n=>o(...n);return t.value=function(...n){let a=Ld.get(this)||new Map,d=a.get(s(n))||new kd;return a.set(s(n),d),Ld.set(this,a),d.push({fn:r,args:n,context:this})},t}}function Rt(o,i){return Y((e,t)=>function(...r){let s=o;try{let n=e.apply(this,r),a=V();return Tr(n)?n.then(d=>(i?y.addSuccessEvent({key:s,cost:V()-a}):y.addSuccessEvent({key:s}),d)).catch(d=>{throw y.addFailedEvent({key:s,error:d}),d}):(y.addSuccessEvent({key:s}),n)}catch(n){throw y.addFailedEvent({key:s,error:n}),n}})}var fh={};Bi(fh,{Events:()=>Oe,Inspect:()=>Ht,LastSink:()=>ao,Sink:()=>X,Subscribe:()=>co,TimeoutError:()=>Pn,audit:()=>wE,bindCallback:()=>IE,bindNodeCallback:()=>AE,buffer:()=>dE,bufferCount:()=>aE,bufferTime:()=>tS,call:()=>of,catchError:()=>hh,combineLatest:()=>nf,concat:()=>iE,concatMap:()=>jE,concatMapTo:()=>XE,count:()=>yE,create:()=>ae,debounce:()=>UE,debounceTime:()=>VE,defer:()=>af,delay:()=>iS,deliver:()=>z,dispose:()=>wd,elementAt:()=>FE,empty:()=>Un,every:()=>GE,exhaustMap:()=>YE,exhaustMapTo:()=>ZE,expand:()=>rS,filter:()=>$t,find:()=>BE,findIndex:()=>HE,first:()=>$E,fromAnimationFrame:()=>EE,fromArray:()=>mE,fromEvent:()=>de,fromEventPattern:()=>pE,fromFetch:()=>fE,fromIterable:()=>_E,fromPromise:()=>lf,fromReadableStream:()=>TE,fromReader:()=>gE,groupBy:()=>KE,identity:()=>eE,ignoreElements:()=>DE,iif:()=>oE,inspect:()=>sf,interval:()=>wu,last:()=>WE,map:()=>Vn,mapTo:()=>qE,max:()=>bE,merge:()=>Ln,mergeMap:()=>zE,mergeMapTo:()=>QE,min:()=>NE,never:()=>CE,nothing:()=>pe,of:()=>hE,pairwise:()=>JE,pipe:()=>ce,race:()=>Lu,range:()=>SE,reduce:()=>Uu,retry:()=>aS,scan:()=>uh,setAsapScheduler:()=>uE,share:()=>rr,shareReplay:()=>rE,skip:()=>OE,skipUntil:()=>kE,skipWhile:()=>Hd,startWith:()=>xn,subject:()=>rt,subscribe:()=>Te,sum:()=>vE,switchMap:()=>Mr,switchMapTo:()=>mo,take:()=>or,takeLast:()=>ME,takeUntil:()=>ke,takeWhile:()=>uf,tap:()=>Fn,throttle:()=>LE,throwError:()=>RE,timeInterval:()=>eS,timeout:()=>nS,timer:()=>wn,toPromise:()=>oS,toReadableStream:()=>sS,withLatestFrom:()=>nE,zip:()=>sE});function pe(...o){}var of=o=>o(),eE=o=>o;function wd(){this.dispose()}var sf=()=>typeof __FASTRX_DEVTOOLS__!="undefined",tE=1,Ht=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(i){let e=new Mu(i,this,this.streamId++);return Oe.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},ao=class{constructor(){this.defers=new Set,this.disposed=!1}next(i){}complete(){this.dispose()}error(i){this.dispose()}get bindDispose(){return()=>this.dispose()}dispose(){this.disposed=!0,this.complete=pe,this.error=pe,this.next=pe,this.dispose=pe,this.subscribe=pe,this.doDefer()}subscribe(i){return i instanceof Ht?i.subscribe(this):i(this),this}get bindSubscribe(){return i=>this.subscribe(i)}doDefer(){this.defers.forEach(of),this.defers.clear()}defer(i){this.defers.add(i)}removeDefer(i){this.defers.delete(i)}reset(){this.disposed=!1,delete this.complete,delete this.next,delete this.dispose,delete this.next,delete this.subscribe}resetNext(){delete this.next}resetComplete(){delete this.complete}resetError(){delete this.error}},X=class extends ao{constructor(i){super(),this.sink=i,i.defer(this.bindDispose)}next(i){this.sink.next(i)}complete(){this.sink.complete()}error(i){this.sink.error(i)}},co=class extends ao{constructor(i,e=pe,t=pe,r=pe){if(super(),this._next=e,this._error=t,this._complete=r,this.then=pe,i instanceof Ht){let s={toString:()=>"subscribe",id:0,source:i};this.defer(()=>{Oe.defer(s,0)}),Oe.create(s),Oe.pipe(s),this.sourceId=s.id,this.subscribe(i),Oe.subscribe({id:s.id,end:!0}),e==pe?this._next=n=>Oe.next(s,0,n):this.next=n=>{Oe.next(s,0,n),e(n)},r==pe?this._complete=()=>Oe.complete(s,0):this.complete=()=>{this.dispose(),Oe.complete(s,0),r()},t==pe?this._error=n=>Oe.complete(s,0,n):this.error=n=>{this.dispose(),Oe.complete(s,0,n),t(n)}}else this.subscribe(i)}next(i){this._next(i)}complete(){this.dispose(),this._complete()}error(i){this.dispose(),this._error(i)}};function ce(o,...i){return i.reduce((e,t)=>t(e),o)}function ae(o,i,e){if(sf()){let t=Object.defineProperties(Object.setPrototypeOf(o,Ht.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:i,writable:!0,configurable:!0},args:{value:e,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});Oe.create(t);for(let r=0;r<e.length;r++){let s=e[r];typeof s=="function"&&s instanceof Ht&&Oe.addSource(t,s)}return t}return o}function z(o,i){return function(...e){return t=>{if(t instanceof Ht){let r=ae(s=>{let n=new o(s,...e);n.sourceId=r.id,n.subscribe(t)},i,arguments);return r.source=t,Oe.pipe(r),r}else return r=>t(new o(r,...e))}}}function Dr(o,i){window.postMessage({source:"fastrx-devtools-backend",payload:{event:o,payload:i}})}var Mu=class extends X{constructor(i,e,t){super(i),this.source=e,this.id=t,this.sourceId=i.sourceId,this.defer(()=>{Oe.defer(this.source,this.id)})}next(i){Oe.next(this.source,this.id,i),this.sink.next(i)}complete(){Oe.complete(this.source,this.id),this.sink.complete()}error(i){Oe.complete(this.source,this.id,i),this.sink.error(i)}},Oe={addSource(o,i){Dr("addSource",{id:o.id,name:o.toString(),source:{id:i.id,name:i.toString()}})},next(o,i,e){Dr("next",{id:o.id,streamId:i,data:e&&e.toString()})},subscribe({id:o,end:i},e){Dr("subscribe",{id:o,end:i,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(o,i,e){Dr("complete",{id:o.id,streamId:i,err:e?e.toString():null})},defer(o,i){Dr("defer",{id:o.id,streamId:i})},pipe(o){Dr("pipe",{name:o.toString(),id:o.id,source:{id:o.source.id,name:o.source.toString()}})},update(o){Dr("update",{id:o.id,name:o.toString()})},create(o){o.id||(o.id=tE++),Dr("create",{name:o.toString(),id:o.id})}},Pn=class extends Error{constructor(i){super(`timeout after ${i}ms`),this.timeout=i}};var Ud=class extends ao{constructor(i){super(),this.source=i,this.sinks=new Set}add(i){i.defer(()=>this.remove(i)),this.sinks.add(i).size===1&&(this.reset(),this.subscribe(this.source))}remove(i){this.sinks.delete(i),this.sinks.size===0&&this.dispose()}next(i){this.sinks.forEach(e=>e.next(i))}complete(){this.sinks.forEach(i=>i.complete()),this.sinks.clear()}error(i){this.sinks.forEach(e=>e.error(i)),this.sinks.clear()}};function rr(){return o=>{let i=new Ud(o);if(o instanceof Ht){let e=ae(t=>{i.add(t)},"share",arguments);return i.sourceId=e.id,e.source=o,Oe.pipe(e),e}return ae(i.add.bind(i),"share",arguments)}}function Ln(...o){return ae(i=>{let e=new X(i),t=o.length;e.complete=()=>{--t===0&&i.complete()},o.forEach(e.bindSubscribe)},"merge",arguments)}function Lu(...o){return ae(i=>{let e=new Map;o.forEach(t=>{let r=new X(i);e.set(t,r),r.complete=()=>{e.delete(t),e.size===0?i.complete():r.dispose()},r.next=s=>{e.delete(t),e.forEach(n=>n.dispose()),r.resetNext(),r.resetComplete(),r.next(s)}}),o.forEach(t=>e.get(t).subscribe(t))},"race",arguments)}function iE(...o){return ae(i=>{let e=0,t=o.length,r=new X(i);r.complete=()=>{e<t&&!r.disposed?(r.doDefer(),r.subscribe(o[e++])):i.complete()},r.complete()},"concat",arguments)}function rE(o){return i=>{let e=new Ud(i),t=[];return e.next=function(r){t.push(r),t.length>o&&t.shift(),this.sinks.forEach(s=>s.next(r))},ae(r=>{r.defer(()=>e.remove(r)),t.forEach(s=>r.next(s)),e.add(r)},"shareReplay",arguments)}}function oE(o,i,e){return ae(t=>o()?i(t):e(t),"iif",arguments)}function nf(...o){return ae(i=>{let e=o.length,t=e,r=e,s=new Array(e),n=()=>{--r===0&&i.complete()},a=(d,l)=>{let u=new X(i);u.next=h=>{t--,u.next=p=>{s[l]=p,t===0&&i.next(s)},u.next(h)},u.complete=n,u.subscribe(d)};o.forEach(a)},"combineLatest",arguments)}function sE(...o){return ae(i=>{let e=o.length,t=e,r=new Array(e),s=()=>{--t===0&&i.complete()},n=(a,d)=>{let l=new X(i),u=[];r[d]=u,l.next=h=>{u.push(h),r.every(p=>p.length)&&i.next(r.map(p=>p.shift()))},l.complete=s,l.subscribe(a)};o.forEach(n)},"zip",arguments)}function xn(...o){return i=>ae((e,t=0,r=o.length)=>{for(;t<r&&!e.disposed;)e.next(o[t++]);e.disposed||e.subscribe(i)},"startWith",arguments)}var Ou=class extends X{constructor(i,...e){super(i);let t=new X(this.sink);t.next=r=>this.buffer=r,t.complete=pe,t.subscribe(nf(...e))}next(i){this.buffer&&this.sink.next([i,...this.buffer])}},nE=z(Ou,"withLatestFrom"),ku=class extends X{constructor(i,e,t){super(i),this.bufferSize=e,this.startBufferEvery=t,this.buffer=[],this.count=0,this.startBufferEvery&&(this.buffers=[[]])}next(i){this.startBufferEvery?(this.count++===this.startBufferEvery&&(this.buffers.push([]),this.count=1),this.buffers.forEach(e=>{e.push(i)}),this.buffers[0].length===this.bufferSize&&this.sink.next(this.buffers.shift())):(this.buffer.push(i),this.buffer.length===this.bufferSize&&(this.sink.next(this.buffer),this.buffer=[]))}complete(){this.buffer.length?this.sink.next(this.buffer):this.buffers.length&&this.buffers.forEach(i=>this.sink.next(i)),super.complete()}},aE=z(ku,"bufferCount"),Pu=class extends X{constructor(i,e){super(i),this.buffer=[];let t=new X(i);t.next=r=>{i.next(this.buffer),this.buffer=[]},t.complete=pe,t.subscribe(e)}next(i){this.buffer.push(i)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},dE=z(Pu,"buffer");var cE=function(o,i,e,t){function r(s){return s instanceof e?s:new e(function(n){n(s)})}return new(e||(e=Promise))(function(s,n){function a(u){try{l(t.next(u))}catch(h){n(h)}}function d(u){try{l(t.throw(u))}catch(h){n(h)}}function l(u){u.done?s(u.value):r(u.value).then(a,d)}l((t=t.apply(o,i||[])).next())})};function rt(o){let i=arguments,e=rr()(ae(t=>{e.next=r=>t.next(r),e.complete=()=>t.complete(),e.error=r=>t.error(r),o&&t.subscribe(o)},"subject",i));return e.next=pe,e.complete=pe,e.error=pe,e}function af(o){return ae(i=>i.subscribe(o()),"defer",arguments)}var hs={promise:o=>{Promise.resolve().then(o)},setImmediate:typeof setImmediate!="undefined"?o=>setImmediate(o):null,setTimeout:o=>setTimeout(o,0)},lE=()=>typeof Promise!="undefined"?hs.promise:hs.setImmediate?hs.setImmediate:hs.setTimeout,xu=lE(),df=o=>i=>{xu(()=>o(i))},uE=o=>{typeof o=="function"?xu=o:hs[o]&&(xu=hs[o])};var cf=o=>df(i=>{for(let e=0;!i.disposed&&e<o.length;e++)i.next(o[e]);i.complete()});function hE(...o){return ae(cf(o),"of",arguments)}function mE(o){return ae(cf(o),"fromArray",arguments)}function wu(o){return ae(i=>{let e=0,t=setInterval(()=>i.next(e++),o);return i.defer(()=>{clearInterval(t)}),"interval"},"interval",arguments)}function wn(o,i){return ae(e=>{let t=0,r=setTimeout(()=>{if(e.removeDefer(s),e.next(t++),i){let n=setInterval(()=>e.next(t++),i);e.defer(()=>{clearInterval(n)})}else e.complete()},o),s=()=>clearTimeout(r);e.defer(s)},"timer",arguments)}function Vd(o,i){return e=>{let t=r=>e.next(r);e.defer(()=>i(t)),o(t)}}function pE(o,i){return ae(Vd(o,i),"fromEventPattern",arguments)}function de(o,i){if("on"in o&&"off"in o)return ae(Vd(e=>o.on(i,e),e=>o.off(i,e)),"fromEvent",arguments);if("addListener"in o&&"removeListener"in o)return ae(Vd(e=>o.addListener(i,e),e=>o.removeListener(i,e)),"fromEvent",arguments);if("addEventListener"in o)return ae(Vd(e=>o.addEventListener(i,e),e=>o.removeEventListener(i,e)),"fromEvent",arguments);throw"target is not a EventDispachter"}function lf(o){return ae(i=>{o.then(i.next.bind(i),i.error.bind(i))},"fromPromise",arguments)}function fE(o,i){return ae(af(()=>lf(fetch(o,i))),"fromFetch",arguments)}function _E(o){return ae(df(i=>{try{for(let e of o){if(i.disposed)return;i.next(e)}i.complete()}catch(e){i.error(e)}}),"fromIterable",arguments)}function gE(o){let i=e=>cE(this,void 0,void 0,function*(){if(e.disposed)return;let{done:t,value:r}=yield o.read();if(t){e.complete();return}else e.next(r),i(e)});return ae(e=>{i(e)},"fromReader",arguments)}function TE(o){return ae(i=>{let e=new AbortController,t=e.signal;i.defer(()=>e.abort("cancelled")),o.pipeTo(new WritableStream({write(r){i.next(r)},close(){i.complete()},abort(r){i.error(r)}}),{signal:t}).then(()=>i.complete(),r=>i.error(r))},"fromReadableStream",arguments)}function EE(){return ae(o=>{let i=requestAnimationFrame(function e(t){o.disposed||(o.next(t),i=requestAnimationFrame(e))});o.defer(()=>cancelAnimationFrame(i))},"fromAnimationFrame",arguments)}function SE(o,i){return ae((e,t=o,r=i+o)=>{for(;t<r&&!e.disposed;)e.next(t++);return e.complete(),"range"},"range",arguments)}function IE(o,i,...e){return ae(t=>{let r=e.concat(s=>(t.next(s),t.complete()));o.apply(i,r)},"bindCallback",arguments)}function AE(o,i,...e){return ae(t=>{let r=e.concat((s,n)=>s?t.error(s):(t.next(n),t.complete()));o.apply(i,r)},"bindNodeCallback",arguments)}function CE(){return ae(()=>{},"never",arguments)}function RE(o){return ae(i=>i.error(o),"throwError",arguments)}function Un(){return ae(o=>o.complete(),"empty",arguments)}var lo=class extends X{constructor(i,e,t){super(i),this.f=e;let r=()=>{this.sink.next(this.acc),this.sink.complete()};typeof t=="undefined"?this.next=s=>{this.acc=s,this.complete=r,this.resetNext()}:(this.acc=t,this.complete=r)}next(i){this.acc=this.f(this.acc,i)}},Uu=z(lo,"reduce"),yE=o=>z(lo,"count")((i,e)=>o(e)?i+1:i,0),bE=()=>z(lo,"max")(Math.max),NE=()=>z(lo,"min")(Math.min),vE=()=>z(lo,"sum")((o,i)=>o+i,0);var Vu=class extends X{constructor(i,e,t){super(i),this.filter=e,this.thisArg=t}next(i){this.filter.call(this.thisArg,i)&&this.sink.next(i)}},$t=z(Vu,"filter"),Fu=class extends X{next(i){}},DE=z(Fu,"ignoreElements"),Bu=class extends X{constructor(i,e){super(i),this.count=e}next(i){this.sink.next(i),--this.count===0&&(this.doDefer(),this.complete())}},or=z(Bu,"take"),Hu=class extends X{constructor(i,e){super(i);let t=new X(i);t.next=()=>{t.doDefer(),i.complete()},t.complete=wd,t.subscribe(e)}},ke=z(Hu,"takeUntil"),$u=class extends X{constructor(i,e){super(i),this.f=e}next(i){this.f(i)?this.sink.next(i):(this.doDefer(),this.complete())}},uf=z($u,"takeWhile"),ME=o=>Uu((i,e)=>(i.push(e),i.length>o&&i.shift(),i),[]),Wu=class extends X{constructor(i,e){super(i),this.count=e}next(i){--this.count===0&&(this.next=super.next)}},OE=z(Wu,"skip"),Gu=class extends X{constructor(i,e){super(i),i.next=pe;let t=new X(i);t.next=()=>{t.doDefer(),i.resetNext()},t.complete=wd,t.subscribe(e)}},kE=z(Gu,"skipUntil"),Ju=class extends X{constructor(i,e){super(i),this.f=e}next(i){this.f(i)||(this.next=super.next,this.next(i))}},Hd=z(Ju,"skipWhile"),PE={leading:!0,trailing:!1},qu=class extends X{constructor(i,e,t){super(i),this.durationSelector=e,this.trailing=t}cacheValue(i){this.last=i,this.disposed&&this.throttle(i)}send(i){this.sink.next(i),this.throttle(i)}throttle(i){this.reset(),this.subscribe(this.durationSelector(i))}next(){this.complete()}complete(){this.dispose(),this.trailing&&this.send(this.last)}},Fd=class extends X{constructor(i,e,t=PE){super(i),this.durationSelector=e,this.config=t,this._throttle=new qu(this.sink,this.durationSelector,this.config.trailing),this._throttle.dispose()}next(i){this._throttle.disposed&&this.config.leading?this._throttle.send(i):this._throttle.cacheValue(i)}complete(){this._throttle.throttle=pe,this._throttle.complete(),super.complete()}},LE=z(Fd,"throttle"),xE={leading:!1,trailing:!0},wE=o=>z(Fd,"audit")(o,xE),ju=class extends X{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},Bd=class extends X{constructor(i,e){super(i),this.durationSelector=e,this._debounce=new ju(this.sink),this._debounce.dispose()}next(i){this._debounce.dispose(),this._debounce.reset(),this._debounce.last=i,this._debounce.subscribe(this.durationSelector(i))}complete(){this._debounce.complete(),super.complete()}},UE=z(Bd,"debounce"),VE=o=>z(Bd,"debounceTime")(i=>wn(o)),Xu=class extends X{constructor(i,e,t){super(i),this.count=e,this.defaultValue=t}next(i){this.count--===0&&(this.defaultValue=i,this.doDefer(),this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("not enough elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},FE=z(Xu,"elementAt"),BE=o=>i=>or(1)(Hd(e=>!o(e))(i)),zu=class extends X{constructor(i,e){super(i),this.f=e,this.i=0}next(i){this.f(i)?(this.sink.next(this.i++),this.doDefer(),this.complete()):++this.i}},HE=z(zu,"findIndex"),Qu=class extends X{constructor(i,e,t){super(i),this.f=e,this.defaultValue=t,this.index=0}next(i){(!this.f||this.f(i,this.index++))&&(this.defaultValue=i,this.doDefer(),this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},$E=z(Qu,"first"),Yu=class extends X{constructor(i,e,t){super(i),this.f=e,this.defaultValue=t,this.index=0}next(i){(!this.f||this.f(i,this.index++))&&(this.defaultValue=i)}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},WE=z(Yu,"last"),Zu=class extends X{constructor(i,e){super(i),this.predicate=e,this.index=0}next(i){this.predicate(i,this.index++)?this.result=!0:(this.result=!1,this.doDefer(),this.complete())}complete(){if(this.result===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.result);super.complete()}},GE=z(Zu,"every");var Ku=class extends X{constructor(i,e,t){super(i),this.f=e,typeof t=="undefined"?this.next=r=>{this.acc=r,this.resetNext(),this.sink.next(this.acc)}:this.acc=t}next(i){this.sink.next(this.acc=this.f(this.acc,i))}},uh=z(Ku,"scan"),eh=class extends X{constructor(){super(...arguments),this.hasLast=!1}next(i){this.hasLast?this.sink.next([this.last,i]):this.hasLast=!0,this.last=i}},JE=z(eh,"pairwise"),$d=class extends X{constructor(i,e,t){super(i),this.mapper=e,this.thisArg=t}next(i){super.next(this.mapper.call(this.thisArg,i))}},Vn=z($d,"map"),qE=o=>z($d,"mapTo")(i=>o),uo=class extends X{constructor(i,e,t){super(i),this.data=e,this.context=t}next(i){let e=this.context.combineResults;e?this.sink.next(e(this.data,i)):this.sink.next(i)}tryComplete(){this.context.resetComplete(),this.dispose()}},ho=class o extends X{constructor(i,e,t){super(i),this.makeSource=e,this.combineResults=t,this.index=0}subInner(i,e){let t=this.currentSink=new e(this.sink,i,this);this.complete===o.prototype.complete&&(this.complete=this.tryComplete),t.complete=t.tryComplete,t.subscribe(this.makeSource(i,this.index++))}complete(){this.sink.complete()}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},Wd=class extends uo{},Gd=class extends ho{next(i){this.subInner(i,Wd),this.next=e=>{this.currentSink.dispose(),this.subInner(e,Wd)}}},Mr=z(Gd,"switchMap");function Xd(o){return(i,e)=>o(()=>i,e)}var mo=Xd(z(Gd,"switchMapTo")),th=class extends uo{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},Jd=class extends ho{constructor(){super(...arguments),this.sources=[],this.next2=this.sources.push.bind(this.sources)}next(i){this.next2(i),this.subNext()}subNext(){this.next=this.next2,this.subInner(this.sources.shift(),th),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},jE=z(Jd,"concatMap"),XE=Xd(z(Jd,"concatMapTo")),ih=class extends uo{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},qd=class extends ho{constructor(){super(...arguments),this.inners=new Set}next(i){this.subInner(i,ih),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(i=>i.resetComplete()):this.dispose()}},zE=z(qd,"mergeMap"),QE=Xd(z(qd,"mergeMapTo")),rh=class extends uo{dispose(){this.context.resetNext(),super.dispose()}},jd=class extends ho{next(i){this.next=pe,this.subInner(i,rh)}},YE=z(jd,"exhaustMap"),ZE=Xd(z(jd,"exhaustMapTo")),oh=class extends X{constructor(i,e){super(i),this.f=e,this.groups=new Map}next(i){let e=this.f(i),t=this.groups.get(e);typeof t=="undefined"&&(t=rt(),t.key=e,this.groups.set(e,t),super.next(t)),t.next(i)}complete(){this.groups.forEach(i=>i.complete()),super.complete()}error(i){this.groups.forEach(e=>e.error(i)),super.error(i)}},KE=z(oh,"groupBy"),sh=class extends X{constructor(){super(...arguments),this.start=new Date}next(i){this.sink.next({value:i,interval:Number(new Date)-Number(this.start)}),this.start=new Date}},eS=z(sh,"timeInterval"),nh=class extends X{constructor(i,e){super(i),this.miniseconds=e,this.buffer=[],this.id=setInterval(()=>{this.sink.next(this.buffer.concat()),this.buffer.length=0},this.miniseconds)}next(i){this.buffer.push(i)}complete(){this.sink.next(this.buffer),super.complete()}dispose(){clearInterval(this.id),super.dispose()}},tS=z(nh,"bufferTime"),ah=class extends X{constructor(i,e){super(i),this.buffer=[],this.delayTime=e}dispose(){clearTimeout(this.timeoutId),super.dispose()}delay(i){this.timeoutId=setTimeout(()=>{let e=this.buffer.shift();if(e){let{time:t,data:r}=e;super.next(r),this.buffer.length&&this.delay(Number(this.buffer[0].time)-Number(t))}},i)}next(i){this.buffer.length||this.delay(this.delayTime),this.buffer.push({time:new Date,data:i})}complete(){this.timeoutId=setTimeout(()=>super.complete(),this.delayTime)}},iS=z(ah,"delay"),dh=class extends X{constructor(i,e){super(i),this.selector=e}error(i){this.dispose(),this.selector(i)(this.sink)}},hh=z(dh,"catchError"),ch=class extends uo{tryComplete(){let i=this.context.inners.delete(this);super.dispose(),i&&this.context.checkComplete()}next(i){this.sink.next(i),this.context.expandValue(i)}},lh=class extends ho{constructor(i,e){super(i,e),this.project=e,this.inners=new Set,this.sourceCompleted=!1}next(i){this.sink.next(i),this.expandValue(i)}expandValue(i){let e=new ch(this.sink,i,this);this.currentSink=e,this.complete=this.tryComplete,e.complete=e.tryComplete,this.inners.add(e),e.subscribe(this.makeSource(i,this.index++))}complete(){this.sourceCompleted=!0,this.checkComplete()}checkComplete(){this.sourceCompleted&&this.inners.size===0&&(this.resetComplete(),super.complete())}tryComplete(){this.sourceCompleted=!0,this.checkComplete()}},rS=z(lh,"expand");var oS=()=>o=>new Promise((i,e)=>{let t;new co(o,r=>t=r,e,()=>i(t))}),sS=()=>o=>{let i;return new ReadableStream({start(e){i=new co(o,e.enqueue.bind(e),e.error.bind(e),e.close.bind(e))},cancel(){i.dispose()}})},Te=(o=pe,i=pe,e=pe)=>t=>new co(t,o,i,e),mh=class extends X{constructor(i,e){super(i),e instanceof Function?this.next=t=>{e(t),i.next(t)}:(e.next&&(this.next=t=>{e.next(t),i.next(t)}),e.complete&&(this.complete=()=>{e.complete(),i.complete()}),e.error&&(this.error=t=>{e.error(t),i.error(t)}))}},Fn=z(mh,"tap"),ph=class extends X{constructor(i,e){super(i),this.timeout=e,this.id=setTimeout(()=>this.error(new Pn(this.timeout)),this.timeout)}next(i){super.next(i),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},nS=z(ph,"timeout"),aS=(o=1/0)=>i=>{if(i instanceof Ht){let e=ae(t=>{let r=o,s=new X(t);s.error=n=>{r-- >0?s.subscribe(i):t.error(n)},s.sourceId=e.id,s.subscribe(i)},"retry",[o]);return e.source=i,Oe.pipe(e),e}else return e=>{let t=o,r=new X(e);r.error=s=>{t-- >0?i(r):e.error(s)},i(r)}};var ms=(e=>(e[e.AUTO_SWITCH_NEW_DEVICE=0]="AUTO_SWITCH_NEW_DEVICE",e[e.WAIT_CURRENT_DEVICE=1]="WAIT_CURRENT_DEVICE",e))(ms||{}),po=class po extends no{constructor(e,t){super({mediaType:e,PlayerClass:t});c(this,"isRemote",!1);c(this,"deviceId");c(this,"groupId","");c(this,"label","");c(this,"sourceTrack");c(this,"enableAutoSwitchWhenRecapturing",!0);c(this,"_isRecapturing",!1);c(this,"_lastRecaptureTime",0);c(this,"_onMuteTimeoutId",-1);c(this,"_encodeCheckTimeoutId",-1);c(this,"recaptureMode",0);c(this,"profile");c(this,"retryEncodeFailed")}get enableEncodeFrame(){return!1}get isPublishing(){return this.state.toString()==="publishing"}get isPublished(){return this.state==="publish"}get isUseCustomSource(){return this.sourceTrack&&this.mediaTrack&&this.sourceTrack!==this.mediaTrack}encodeFrame(e,t){throw new Error("Method not implemented.")}installTrackEvent(e){e.addEventListener(_.MUTE,this.onTrackMuted),e.addEventListener(_.UNMUTE,this.onTrackUnmuted),e.addEventListener(_.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===_.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){e.removeEventListener(_.MUTE,this.onTrackMuted),e.removeEventListener(_.UNMUTE,this.onTrackUnmuted),e.removeEventListener(_.ENDED,this.onTrackEnded)}setStateToReady(){}capture(e,t=!1){return f(this,null,function*(){var s;let r=this.sourceTrack;try{let n=V();S.emit(A.LOCAL_TRACK_CAPTURE_START,{track:this});let a;e.customSource?(a=new MediaStream,a.addTrack(e.customSource)):(t||(s=this.sourceTrack)==null||s.stop(),a=yield tf(e));let d=a.getTracks()[0];return yield this.setInputMediaStreamTrack(d),e.customSource||(this.sourceTrack=d,this.updateDeviceIdInUse(),this.listenDeviceChange()),S.emit(A.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:V()-n}),a}catch(n){throw S.emit(A.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:n}),this.log.error(`getUserMedia error observed ${n}`),n}finally{t&&(r==null||r.stop())}})}setOutputMediaStreamTrack(e){var t;if(super.setOutputMediaStreamTrack(e),this.setStateToReady(),this.isPublishing||this.isPublished)return(t=this.room)==null?void 0:t.replaceTrack(this)}get hasFlag(){var t,r;let e=Kt(((t=this.room)==null?void 0:t.localPublishFlag)||0,((r=this.room)==null?void 0:r.userId)||"");return this.mediaType===4&&e.hasVideo||this.mediaType===1&&e.hasAudio||this.mediaType===2&&e.hasAuxiliary}publish(e,t){return f(this,null,function*(){return this.room=e,this.room.localTracks.add(this),this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.bindParent(e.getLogger()),yield t,this._checkPublishFlag(e)})}_checkPublishFlag(e){return new Promise((t,r)=>f(this,null,function*(){var l,u,h,p;let s=()=>r(new v({code:I.API_CALL_ABORTED,message:"publish aborted"}));if(this.hasFlag||this.muted?t():((this.state===j.INIT||this.state==="ready")&&s(),ce(de(e,"local-publish-flag-changed"),$t(()=>this.hasFlag),ke(Ln(de(this,j.INIT),de(this,"ready"))),Te(t,r,s))),(((u=(l=this.room)==null?void 0:l.networkQuality)==null?void 0:u.uplinkNetworkQuality)||0)>3)return t();let a=e.heartbeatCount,d=((p=(h=this.mediaTrack)==null?void 0:h.stats)==null?void 0:p.totalFrames)||0;this._encodeCheckTimeoutId=setTimeout(()=>f(this,null,function*(){var g,E,C,P,re,L,Qe;if((((E=(g=this.room)==null?void 0:g.networkQuality)==null?void 0:E.uplinkNetworkQuality)||0)>3||e.heartbeatCount-a<3)return t();if((this.isPublished||this.isPublishing)&&this.isMediaTrackActive){if((C=this.mediaTrack)!=null&&C.stats){let O=this.mediaTrack.stats.totalFrames||0;O-d===0&&this.log.warn("capture totalFrames is 0 during encode check, totalFrames",O)}let N=this.kind===_.AUDIO,k=this.stat.bytesSent>0;if(y[k?"addSuccessEvent":"addFailedEvent"]({key:N?503700:513702}),!N){let O=((re=(P=this.room)==null?void 0:P.videoCodec)==null?void 0:re.toUpperCase())||"H264",Ne={H264:513704,H265:513705,VP8:513706}[O];Ne&&y[k?"addSuccessEvent":"addFailedEvent"]({key:Ne})}if(!k){if(y.addEnum({key:N?503701:513703,value:Zr()}),se.uploadEvent({log:`stat-encode-failed-${this.kind}-${ai()||di()}`,userId:this.userId}),this.log.warn(N?"encode failed":`${(Qe=(L=this.room)==null?void 0:L.videoCodec)==null?void 0:Qe.toUpperCase()} encode failed`),this.retryEncodeFailed&&(this.log.warn("retry encode"),yield this.retryEncodeFailed(this),this.stat.bytesSent>0||this.hasFlag||(yield Ke(5e3),this.stat.bytesSent>0||this.hasFlag)))return t();this.emit("6",this),r(new v({message:`${this.strMediaType} encode failed`,code:N?I.AUDIO_ENCODE_FAILED:I.VIDEO_ENCODE_FAILED}))}}}),1e4)}))}unpublish(){this.room&&this.room.localTracks.delete(this),this.log.info("unpublish"),S.emit(A.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return f(this,null,function*(){if(this.sourceTrack&&Ni){let{deviceId:e,groupId:t}=this.sourceTrack.getSettings(),{label:r}=this.sourceTrack;(yield Kp({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=r,t&&(this.groupId=t),cs().then(n=>{let a=n.find(d=>{let l=d.deviceId===e;return t&&(l=l&&d.groupId===t),l});a&&this.emit("2",a)}))}})}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(e=!1){return!(!this.deviceId||!this.sourceTrack||this.kind===_.AUDIO&&!Zp(this.sourceTrack)||this.kind===_.VIDEO&&!Yp(this.sourceTrack)||this._isRecapturing||e&&si&&Re)}onTrackMuted(){if(super.onTrackMuted(),rf(),!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<ko){setTimeout(()=>this.onTrackMuted(),ko);return}this._onMuteTimeoutId=setTimeout(()=>f(this,null,function*(){var e;if((e=this.sourceTrack)!=null&&e.muted){if((ge||_e)&&document.visibilityState!=="visible")return;this.recapture(yield this.getRecoverCaptureDeviceId())}}),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return f(this,null,function*(){if(Le(po.prototype,this,"onTrackEnded").call(this),!!this.isNeedToRecapture()&&this.recaptureMode===0){if(Date.now()-this._lastRecaptureTime<ko){setTimeout(()=>this.onTrackEnded(),ko);return}this.emit("7"),this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e,t=!1){return f(this,null,function*(){var n;if(this._isRecapturing||!this.sourceTrack)return;this.log.warn("recapture trying");let r=this.sourceTrack;t||(n=this.sourceTrack)==null||n.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let s={useExactDeviceId:!0};if(e==="user"||e==="environment")s.facingMode=e;else{let a;(this.kind==="audio"?yield It():yield At()).find(l=>l.deviceId===e)&&(a=e),s.deviceId=a}return this.capture(s,t).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),S.emit(A.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(a=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${a.message}`),this.emit("5",a),S.emit(A.LOCAL_TRACK_RECAPTURE,{track:this,error:a})}).finally(()=>{t&&(r==null||r.stop())})})}getRecoverCaptureDeviceId(){return f(this,null,function*(){let e=this instanceof je;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let r=(Bn.get(t)||0)+1;if(Bn.set(t,r),r>=3&&this.enableAutoSwitchWhenRecapturing){let s=e?(yield At()).find(n=>!Bn.has(n.deviceId)):(yield It()).find(n=>!Bn.has(n.deviceId));s&&(this.log.warn(`${t} capture fail ${r} times, change new ${s.deviceId}`),t=s.deviceId)}}return t})}stopCapture(){var e;this.sourceTrack&&(this.sourceTrack.stop(),this.uninstallTrackEvent(this.sourceTrack)),this._inputTrack&&this.uninstallTrackEvent(this._inputTrack),(e=this.manager)==null||e.removeInput(this)}close(){super.close(),this.stopCapture()}};D([ye(j.INIT,"ready",{ignoreError:!0,sync:!0})],po.prototype,"setStateToReady",1),D([ir()],po.prototype,"capture",1),D([ye("ready","publish",{ignoreError:!0,success(){S.emit(A.LOCAL_TRACK_PUBLISHED,{track:this,room:this.room}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),this.log.info("published")},fail(e){var n;(n=this.room)==null||n.localTracks.delete(this);let t="error",r=e instanceof v?e:e.cause instanceof v?e.cause:e,s=!1;r instanceof v&&(r.message.includes("timeout")?t="timeout":r.code===I.API_CALL_ABORTED&&(s=!0,t="api-call")),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:t,error:r}),this.log[s?"info":"error"]("publish failed",r)}}),Rt(521714,!1)],po.prototype,"publish",1),D([Y(e=>function(){return f(this,null,function*(){let t=this.state==="publish"?"started":"starting";e.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:t,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)})}),ye([],"ready",{sync:!0})],po.prototype,"unpublish",1);var _i=po,Bn=new Map;S.on(A.SWITCH_DEVICE_SUCCESS,o=>{o.track.deviceId&&Bn.delete(o.track.deviceId)});var kt=class o extends _i{constructor(e){super(1,vd);c(this,"mediaType",1);c(this,"volume",0);c(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40});c(this,"playerMuted",!0);c(this,"pipeline");c(this,"earMonitorGainNode",new Ue);c(this,"_output",new Ue);c(this,"codecPipeline",[]);c(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0});c(this,"mixedAudioReferenceMap",new Map);c(this,"isAudioContextLongSuspended",!1);c(this,"after3aSilenceStartTime",0);this.manager=e,this.pipeline=new ds(e),this.pipeline.source.pipeTo(this.player.pipeline.volumeMeter),this.pipeline.gain.pipeTo(this.earMonitorGainNode).pipeTo(this._output),this.pipeline.gain.pipeTo(this.player.pipeline.volumeMeterAfter3A),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this),S.on(A.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this)}get dbVolume(){return so.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}getInternalAudioLevelAfter3A(){if(this.pipeline.isProcessEnabled)return this.player.getInternalAudioLevelAfter3A()}updateAfter3aSilenceStartTime(e){T(e)||(e===0&&!this.after3aSilenceStartTime?this.after3aSilenceStartTime=V():e>0&&(this.after3aSilenceStartTime=0))}setInputMediaStreamTrack(e){return f(this,null,function*(){let t=this.trackSettings||{};y.addEnum({key:501701,value:t.channelCount||0,useUV:!1}),y.addEnum({key:501702,value:t.sampleRate||0,useUV:!1}),y.addEnum({key:502700,value:0});let{sampleRate:r,channelCount:s}=t;this._log.info(`local audio track input ${JSON.stringify({sampleRate:r,channelCount:s})}`),this.pipeline.source.channelCount=s||1,this.pipeline.replaceSource(e),yield Le(o.prototype,this,"setInputMediaStreamTrack").call(this,e),this.updatePlayingState(!!e)})}capture(a){return f(this,arguments,function*({deviceId:e,customSource:t,useExactDeviceId:r=!0,retryWhenExactFailed:s},n=!1){let d=yield Le(o.prototype,this,"capture").call(this,{video:!1,audio:!0,microphoneId:e,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:r,retryWhenExactFailed:s,customSource:t},n);return Nr(),d})}switchDevice(e){return f(this,null,function*(){if(this.mediaTrack){if(this.deviceId===e&&!this.isUseCustomSource)if(e===Wr){if(yield vu(this.groupId,this.label))return}else return;try{this.log.info(`switchDevice audio to: ${e}`),this.sourceTrack&&this.sourceTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0,retryWhenExactFailed:!1}),S.emit(A.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(t){throw this.log.error(`switch microphone failed ${t}`),this.deviceId&&this.recapture(this.deviceId),t}}})}listenDeviceChange(){be&&!be.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&be.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return f(this,null,function*(){if(e.deviceId===this.deviceId){let t=this.recaptureMode===1;if(this.log.warn(`RecaptureMode: ${ms[this.recaptureMode]}. Current microphone is lost: ${JSON.stringify(e)}`),this.recaptureMode===0){ve(this.userId,{eventId:2003,param1:6,streamType:1});let r=yield It();r[0]?this.recapture(r[0].deviceId):t=!0}t&&be.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.recaptureMode===1&&e.deviceId!==this.deviceId||(be.off("audioInputAdded",this.handleMicrophoneAdded,this),this.log.warn(`microphone added: ${JSON.stringify(e)}`),this.recapture(e.deviceId))}update3A(s){return f(this,arguments,function*({echoCancellation:e,noiseSuppression:t,autoGainControl:r}){let n=this.sourceTrack||this.mediaTrack;if(!n)return;let a=n.getConstraints(),d=!1;!T(e)&&e!==this.profile.echoCancellation&&(this.profile.echoCancellation=e,a.echoCancellation=e,d=!0),!T(t)&&t!==this.profile.noiseSuppression&&(this.profile.noiseSuppression=t,a.noiseSuppression=t,d=!0),!T(r)&&r!==this.profile.autoGainControl&&(this.profile.autoGainControl=r,a.autoGainControl=r,d=!0),d&&(ee||Re?yield n.applyConstraints(a).catch(l=>this._log.warn("update3A failed: ",l)):this.deviceId&&(yield this.recapture(this.deviceId,!0)))})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&y.addEnum({key:502700,value:2})}setAudioVolume(e){super.setAudioVolume(0),ge&&this.player.setMuted(!0),this.earMonitorGainNode.node||(this.earMonitorGainNode.setNode(Ee().createGain()),this._output.setNode(Ee().destination)),this.earMonitorGainNode.node.gain.value=e}enableTrackANS(e){return this.update3A({noiseSuppression:e})}enableTrackAEC(e){if(this.sourceTrack&&!(Re||ge))return this.update3A({echoCancellation:e})}addDenoiser(e){var t;if($e<=92&&((t=this.trackSettings)==null?void 0:t.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)}mixAudioReference(e,t){if(this.mixedAudioReferenceMap.has(t))return;this.log.info(`mixAudioReference() => ${t}`);let r=Mn(e);if(!r)return;let s=new Ue,n=Ee().createGain();n.gain.value=1;let a=new Ue;s.pipeTo(a).pipeTo(this.pipeline.mixNode),s.setNode(r),a.setNode(n),this.mixedAudioReferenceMap.set(t,[s,a])}unMixAudioReference(e){let[t,r]=this.mixedAudioReferenceMap.get(e)||[];t&&(this.log.info(`unMixAudioReference() => ${e}`),t.deleteNode(),r==null||r.deleteNode(),this.mixedAudioReferenceMap.delete(e))}setAudioReferenceVolume(e,t){let[r,s]=this.mixedAudioReferenceMap.get(e)||[];s!=null&&s.node&&(s.node.gain.value=t/100,this.log.info(`setAudioReferenceVolume() => ${e} ${s.node.gain.value}`))}addAudioProcessor(e,t,r){this.pipeline.silentNode.setNode(r),this.pipeline.mixNode.setNode(t),this.pipeline.aec.setNode(e)}removeDenoiser(e){if(this.pipeline.denoiser.node===e)return this.pipeline.denoiser.deleteNode(),this.enableTrackANS(!0)}removeAudioProcessor(e){this.pipeline.aec.node===e&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode())}close(){this.mixedAudioReferenceMap.forEach(([e,t])=>{e.deleteNode(),t.deleteNode()}),this.mixedAudioReferenceMap.clear(),this.pipeline.remove(),this.earMonitorGainNode.deleteNode(),this._output.deleteNode(),be.off("audioInputAdded",this.handleMicrophoneAdded,this),be.off("audioInputRemoved",this.handleMicrophoneRemoved,this),S.off(A.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this),super.close()}recapture(e,t=!1){return f(this,null,function*(){try{yield Le(o.prototype,this,"recapture").call(this,e,t)}catch(r){let s=(yield It()).find(n=>n.deviceId!==e);if(s)yield Le(o.prototype,this,"recapture").call(this,s.deviceId);else throw r}})}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduceRight((t,r)=>r?r({frame:t,ntp:Hi()}):t,e):e}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}get enableEncryptFrame(){return this.manager&&!!this.manager.encodePipeline[0]}handleAudioContextLongSuspended({isSuspended:e}){if(this.pipeline.isProcessEnabled)if(e){this.isAudioContextLongSuspended=!0,this.log.warn(`context has suspended for ${yu/1e3} seconds, change to source audio${Ft?"":", non-Safari"}`);let t=this.sourceTrack||this.mediaTrack;t&&this.setOutputMediaStreamTrack(t)}else this.isAudioContextLongSuspended=!1,this.log.warn("context has resumed, change to processed audio"),this.pipeline.track&&this.setOutputMediaStreamTrack(this.pipeline.track)}setOutputMediaStreamTrack(e){if(this.isAudioContextLongSuspended){let t=this.sourceTrack||this.mediaTrack;t&&(e=t)}super.setOutputMediaStreamTrack(e)}};var sr=class{constructor(i,e=!1){this.dataView=i;this.isSEI&&(e?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let i=this.seiPayloadStartIndex,e=this.dataView.byteLength-2,t=[],r=0;for(let n=i;n<=e;n++){let a=this.dataView.getInt8(n);switch(a){case 0:case 1:case 2:case 3:r===2&&(t.push(3),r=0),a==0?r++:r=0,t.push(a);break;default:r=0,t.push(a);break}}t.push(this.dataView.getInt8(this.dataView.byteLength-1));let s=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=s}removePreventionByte(){let i=this.seiPayloadStartIndex,e=this.dataView.byteLength-1,t=[],r=0;for(let n=i;n<=e;n++)switch(this.dataView.getInt8(n)){case 0:r++,t.push(this.dataView.getInt8(n));break;case 3:r!==2&&t.push(this.dataView.getInt8(n)),r=0;break;default:t.push(this.dataView.getInt8(n)),r=0;break}let s=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=s}get isSEI(){return this.dataView.getUint8(4)===6}get seiPayloadStartIndex(){let i=6;for(let e=6;e<this.dataView.buffer.byteLength&&(i++,this.dataView.getUint8(e)===255);e++);return i}get seiPayloadType(){return this.isSEI?this.dataView.getUint8(5):null}get seiPayload(){if(!this.isSEI)return null;let i=0,e=6;for(let s=6;s<this.dataView.buffer.byteLength;s++){let n=this.dataView.getUint8(s);if(e++,n===255)i+=255;else{i+=n;break}}let t=new ArrayBuffer(i),r=new DataView(t);for(let s=0;s<t.byteLength;s++,e++)r.setInt8(s,this.dataView.getInt8(e));return r}};var zd=class{constructor(){c(this,"_seiMessageList",[]);c(this,"_smallSeiMessageList",[]);c(this,"_seiPayloadType",243)}encodeSEINalu(i){let e=i.byteLength,t=parseInt(String(e/255),10),r=e%255,s=[];s.push(0,0,0,1,6,this._seiPayloadType);for(let a=0;a<t;a++)s.push(255);s.push(r);let n=new DataView(i);return s.push(...new Uint8Array(n.buffer)),s.push(128),new sr(new DataView(new Uint8Array(s).buffer),!0)}sendSEI(i,e){e!=null&&e.seiPayloadType&&(this._seiPayloadType=e.seiPayloadType),this._seiMessageList.push(i),e!=null&&e.small&&this._smallSeiMessageList.push(i)}isEmpty(){return!this._seiMessageList.length}getNaluCount(i){let e=0,t=0,r=new DataView(i);for(let s=0;s<i.byteLength;s++)switch(r.getUint8(s)){case 0:e++;break;case 1:(e===2||e===3)&&t++,e=0;break;default:e=0;break}return t}encode(i,e){let t=e?this._smallSeiMessageList:this._seiMessageList;if(t.length>0&&i.data.byteLength>0){let s=9-this.getNaluCount(i.data);if(s<=0)return 0;let n=t.splice(0,s).reverse().map(this.encodeSEINalu.bind(this)),a=n.reduce((p,m)=>p+m.dataView.byteLength,0),d=new ArrayBuffer(a+i.data.byteLength),l=new DataView(d),u=new DataView(i.data),h=0;for(let p=0;p<n.length;p++)for(let m=0;m<n[p].dataView.byteLength;m++)l.setInt8(h++,n[p].dataView.getInt8(m));for(let p=0;p<i.data.byteLength;p++)l.setInt8(h++,u.getInt8(p));return i.data=d,n.length}return 0}};var Or=class Or extends _i{constructor(e,t=4){super(t,pt);c(this,"profile",M({},pr));c(this,"avoidCropping",!1);c(this,"_scaleResolutionDownBy");c(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0,framesCaptured:0});c(this,"small");c(this,"isNeedToSetBandwidth");c(this,"muteImage");c(this,"manager");c(this,"_seiCodec",new zd);this.manager=e;let r=()=>{var s;if(this.isAllowed2k4k(this.profile))this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1});else{let n=Ut(((s=this.room)==null?void 0:s.sdkAppId)||0)?ua:la;this.log.warn(`Resolution is reset to 1080p, need to upgrade ability here ${n}`),this.setProfile(w(M({},this.profile),{width:1920,height:1080})),this.applyProfile()}};this.on("input-media-track-changed",r),this.on("publish",r),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(!(!Ni||!this.mediaTrack))return this.mediaTrack.getSettings().facingMode}get contentHint(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)||""}get isQosClearFirst(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)==="detail"}get hasSmall(){var e;return!!((e=this.manager)!=null&&e.hasSmall)}setMute(e){return f(this,null,function*(){var t,r,s;if(ie(e)){if(this.muteImage===e)return;yield(t=this.manager)==null?void 0:t.deleteWatermark("mute"),yield(r=this.manager)==null?void 0:r.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:e,fillVideo:!0}),this.muteImage=e,Le(Or.prototype,this,"setMute").call(this,!1)}else this.muteImage&&(yield(s=this.manager)==null?void 0:s.deleteWatermark("mute"),this.muteImage=void 0),Le(Or.prototype,this,"setMute").call(this,e)})}capture(a){return f(this,arguments,function*({deviceId:e,facingMode:t,useExactDeviceId:r=!0,customSource:s,retryWhenExactFailed:n=!0}){let d={audio:!1,video:!0,facingMode:t||this.facingMode,cameraId:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:r,retryWhenExactFailed:n,customSource:s};if(d.facingMode==="environment"){let l=yield this.getDeviceIdWhenUsingBackCamera();l&&(d.cameraId=l)}return Le(Or.prototype,this,"capture").call(this,d)})}setProfile(e){var r;let t=this.fallbackProfile(e);if(t.bitrate&&(this.isNeedToSetBandwidth=t.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile))super.setProfile(t);else{let s=Ut(((r=this.room)==null?void 0:r.sdkAppId)||0)?ua:la;this.log.warn(`Resolution is reset to 1080p, need to upgrade ability here ${s}`),super.setProfile(w(M({},this.profile),{width:1920,height:1080}))}}applyProfile(){return f(this,null,function*(){var a;if(!this.mediaTrack)return;let{width:e=0,height:t=0}=(this.sourceTrack||this.mediaTrack).getSettings(),r=e*t,s=this.settings,n=s.height!==this.profile.height||s.width!==this.profile.width||s.frameRate!==this.profile.frameRate;if(n&&(et===16&&this.deviceId?yield this.recapture(this.deviceId):(yield(a=this.sourceTrack||this.mediaTrack)==null?void 0:a.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}),this.manager&&this.manager.changeInput(this)),this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1})),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth){this.isNeedToSetBandwidth=!1;let{width:d=0,height:l=0}=(this.sourceTrack||this.mediaTrack).getSettings(),u=d*l;if(n&&u&&r&&u===r){this.log.warn("set bandwidth failed: resolution is not changed");return}return this.room.setBandWidth({bandwidth:this.profile.bitrate,type:_.VIDEO,videoType:_.BIG})}})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},t=this.sourceTrack||this.mediaTrack;return Ni&&t&&Object.assign(e,t.getSettings()),e}get scaleResolutionDownBy(){return this._scaleResolutionDownBy?this._scaleResolutionDownBy:Ho(this.settings,this.profile)}isAllowed2k4k(e){var t;return!this.room||!this.room.scheduleResult||this.isScreen||e.height*e.width<2560*1440?!0:((t=this.room.scheduleResult.trtcAutoConf)==null?void 0:t["2k4k"])===1}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}switchDevice(e){return f(this,null,function*(){try{if(!this.isNeedToSwitchDevice(e)&&!this.isUseCustomSource)return;let t={useExactDeviceId:!0,retryWhenExactFailed:!1};e==="user"||e==="environment"?t.facingMode=e:t.deviceId=e,this.sourceTrack&&this.sourceTrack.stop(),yield this.capture(t),S.emit(A.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(t){throw this.log.error(`switch camera failed ${t}`),this.deviceId&&this.recapture(this.deviceId),t}})}getDeviceIdWhenUsingBackCamera(){return f(this,null,function*(){let e;try{if(tn&&!Qo&&au){let r=(yield At(!0)).map(n=>{var a;return w(M({},n),{capabilities:(a=n.getCapabilities)==null?void 0:a.call(n)})}).filter(n=>{var a,d;return(d=(a=n.capabilities)==null?void 0:a.facingMode)==null?void 0:d.includes("environment")}),s=r[0];r.forEach(n=>{var u,h,p,m;let{capabilities:a}=n,d=(u=a.width)!=null&&u.max&&((h=a.height)!=null&&h.max)?a.width.max*a.height.max:0,l=(p=s.capabilities.width)!=null&&p.max&&((m=s.capabilities.height)!=null&&m.max)?s.capabilities.width.max*s.capabilities.height.max:0;d>l&&(s=n)}),s!=null&&s.capabilities&&(this._log.info("use max resolution back camera",s),e=s.deviceId)}}catch(t){this._log.warn("get max res camera failed",t)}return e})}updateSmallConfig(e){return f(this,null,function*(){var r,s;this._log.info(`update small stream config: ${JSON.stringify(e)}`);let t=!this.small;this.small=this.fallbackProfile(e,!0),yield(r=this.manager)==null?void 0:r.update(),t&&(yield(s=this.room)==null?void 0:s.enableSmall(!0)),this.log.info("update small stream config success")})}fallbackProfile(e,t=!1){let r=e.width>e.height,s=M({},e);return e.width*e.height<=160*120&&_e&&Ve&&(this.log.warn(`${t?"small ":""}resolution is ${e.width}*${e.height}, fallback to 240*180 for android chrome`),s.width=r?240:180,s.height=r?180:240,s.bitrate=Math.max(e.bitrate,150)),e.width*e.height>1280*720&&vl&&(s.width=r?1280:720,s.height=r?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),sn(ht,"14.3")&&bl(ht,"14.0",!0)&&this.on("7",()=>{let n=this.profile.width>this.profile.height;this.profile.width*this.profile.height>640*480?(this.profile.width=n?640:480,this.profile.height=n?480:640,this.log.warn("reduce the resolution to 480p on iOS 14.0 ~ 14.2")):this.profile.width*this.profile.height>640*360&&(this.profile.width=n?640:360,this.profile.height=n?360:640,this.log.warn("reduce the resolution to 360p on iOS 14.0 ~ 14.2"))}),!t&&this.avoidCropping&&(Ve||ee)&&!nn()&&e.width*e.height<=640*360&&e.width/e.height===16/9&&(this._scaleResolutionDownBy=1280/e.width,e.width=1280,e.height=720,this.log.warn(`capture 720p, scale: ${this._scaleResolutionDownBy}`)),s}stopSmall(){var e,t;this.small&&(delete this.small,(e=this.manager)==null||e.update(),(t=this.room)==null||t.enableSmall(!1))}listenDeviceChange(){be&&!be.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&be.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return f(this,null,function*(){if(e.deviceId===this.deviceId){let t=this.recaptureMode===1;if(this.log.warn(`RecaptureMode: ${ms[this.recaptureMode]}. Current camera is lost: ${JSON.stringify(e)}`),this.recaptureMode===0){ve(this.userId,{eventId:2003,param1:7,streamType:2});let r=yield At();r[0]?this.recapture(r[0].deviceId):t=!0}t&&be.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return f(this,null,function*(){this.recaptureMode===1&&e.deviceId!==this.deviceId||(be.off("videoInputAdded",this.handleCameraAdded,this),this.log.warn(`camera added: ${JSON.stringify(e)}`),this.recapture(e.deviceId))})}encodeFrame(e,t){if(!this.manager)return e;let r=t?8:this.mediaType;return this.manager.encodePipeline.reduceRight((s,n)=>n?n({frame:s,mediaType:r}):s,e)}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}play(e,t){return T(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,t)}close(){be.off("videoInputAdded",this.handleCameraAdded,this),be.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return f(this,null,function*(){try{yield Le(Or.prototype,this,"recapture").call(this,e)}catch(t){let r=(yield At()).find(s=>s.deviceId!==e);if(r)yield Le(Or.prototype,this,"recapture").call(this,r.deviceId);else throw t}})}setContentHint(e){this.mediaTrack&&"contentHint"in this.mediaTrack&&(this.mediaTrack.contentHint!==e&&(this.log.info(`setContentHint ${e}`),this.mediaTrack.contentHint=e),this.outMediaTrack&&this.outMediaTrack.contentHint!==e&&(this.outMediaTrack.contentHint=e))}setRotation(e){this.manager&&(this.isScreen||T(e)||e!==this.rotation&&(this.rotation=e,this.manager.rotation=e))}};D([Ct(function(e){this.setContentHint(e.contentHint||"motion")})],Or.prototype,"capture",1);var je=Or;var gh={};Bi(gh,{REPORT_TYPE:()=>$o,buildSSOPackage:()=>qi,bytes2ms:()=>bm,calculateScaleResolutionDownNumber:()=>Ho,concatArrayBuffers:()=>Oa,convertObjectNumberToInt:()=>Js,copyProperties:()=>ym,deepClone:()=>Gr,deepCloneBasic:()=>Ra,deepMerge:()=>ei,delay:()=>Ke,fibonacci:()=>qr,formatedTime:()=>xm,getConstructorName:()=>wo,getContainerFromElement:()=>Lm,getEnv:()=>Am,getFirst16Bits:()=>Um,getInternalVersion:()=>km,getLast16Bits:()=>ka,getLoggerUrl:()=>Ji,getMediaStreamTrackInfo:()=>Ma,getMuteStateFromFlag:()=>Kt,getNetworkType:()=>ya,getNumNetworkType:()=>Jr,getReconnectionTimeout:()=>Zt,getStringByteLength:()=>Gs,getTurnServer:()=>Pm,getUint32Version:()=>Na,getValueType:()=>Me,getViewListFromView:()=>Fo,glog:()=>pl,ipv4ToUint32:()=>Vo,isArray:()=>Ae,isAudioWorkletSupported:()=>Mm,isBoolean:()=>ue,isConstructor:()=>jr,isEmpty:()=>Uo,isFunction:()=>le,isLangChinese:()=>Yt,isMediaStreamTrack:()=>vm,isNumber:()=>Q,isObject:()=>yt,isOverseaSdkAppId:()=>Ut,isPlainObject:()=>dt,isPortrait:()=>fl,isPromise:()=>Tr,isRemoteTrack:()=>Dm,isRotate90Or270:()=>bt,isSetSinkIdSupported:()=>Om,isString:()=>ie,isUndefined:()=>T,loadImage:()=>Bo,loadVideo:()=>wm,ms2bytes:()=>Nm,ms2samples:()=>ml,normalizeUrl:()=>Da,performanceNow:()=>V,promiseAny:()=>Xr,samples2ms:()=>hl,setNetworkTypeFromWebRTC:()=>ba,stringify:()=>gt,stringifyIncludeValue:()=>Ws,throttlePromise:()=>va});var lS=[-1,-1,1,-1,-1,1,1,1],uS=[0,0,1,0,0,1,1,1];var kr=class kr extends j{constructor(e,t){super();this.context=e;c(this,"name");c(this,"input");c(this,"output");c(this,"texture");c(this,"ctx2d",null);c(this,"fbo");c(this,"width",0);c(this,"height",0);c(this,"x",0);c(this,"y",0);c(this,"program");c(this,"vertexShader");c(this,"fragmentShader");c(this,"totalFrames",0);c(this,"dropFrames",0);c(this,"matchInputSize",!0);c(this,"texCoordBuffer");c(this,"positionBuffer");c(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0});c(this,"cost",0);c(this,"_canvas",null);c(this,"_image");c(this,"log");if(this.context.on("disconnect",this.close,this),this.name=t.name,this.log=t.logger,this.matchInputSize=t.matchInputSize!==!1,this.width=t.width||e.width,this.height=t.height||e.height,this._image=t.image,e instanceof Xe){e.ctx&&t.create2d&&(typeof OffscreenCanvas=="function"&&et!==16?this._canvas=new OffscreenCanvas(this.width,this.height):(this._canvas=document.createElement("canvas"),this._canvas.width=this.width,this._canvas.height=this.height),this.ctx2d=this._canvas.getContext("2d"),this._image=this._canvas);return}try{let r=e.ctx;this.texCoordBuffer=this.createBuffer(uS),this.positionBuffer=this.createBuffer(lS),t.createTexture!==!1&&(this.texture=r.createTexture(),this.useTexture(),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.pixelStorei(r.UNPACK_ALIGNMENT,1)),t.useFbo&&(this.fbo=r.createFramebuffer(),this.useBufferFrame(),this.useTexture(),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,this.width,this.height,0,r.RGBA,r.UNSIGNED_BYTE,null),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,this.texture,0)),t.useDefaultProgram?this.program=e.defaultProgam:(t.vertexShaderSource||t.fragmentShaderSource)&&(this.vertexShader=t.vertexShaderSource?e.createShader(r.VERTEX_SHADER,t.vertexShaderSource):e.defaultVShader,this.fragmentShader=t.fragmentShaderSource?e.createShader(r.FRAGMENT_SHADER,t.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(r){this.context.destroy(new v({code:I.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${r.message||r}`}))}}get image(){return this._image}set image(e){this._image=e}createFramebuffer(e){let t=this.context.ctx,r=t.createFramebuffer();return t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0),r}connect(e,...t){return e.addInput(this,...t),this.output=e,e}addInput(e,...t){this.input=e,this.matchInputSize&&e.width&&e.height&&this.resize(e.width,e.height)}requestFrame(e){let t=Date.now();if(this.context instanceof Be&&this.render(e)||this.context instanceof Xe&&this.render2d(e))this.totalFrames++;else return!1;return this.cost=Date.now()-t,!0}render2d(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?this.draw2d(this.input.image,0,0,this.width,this.height):!1}update(e=0){var t;(t=this.output)==null||t.update(e)}disconnect(...e){var t;(t=this.output)==null||t.removeInput(this,...e),delete this.output}removeInput(e,...t){delete this.input}close(){var e,t;if(this.context.off("disconnect",this.close,this),(e=this.output)==null||e.removeInput(this),delete this.output,(t=this.input)==null||t.disconnect(),this.context instanceof Be){let r=this.context.ctx;r.deleteBuffer(this.texCoordBuffer),r.deleteBuffer(this.positionBuffer),this.fbo&&r.deleteFramebuffer(this.fbo),this.texture&&r.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&r.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&r.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&r.deleteProgram(this.program)}this._canvas&&(this._canvas.width=0,this._canvas.height=0,this.ctx2d=null),this.removeAllListeners()}useTexture(){this.useTextures(this.texture)}useInputTexture(){var e;this.useTextures((e=this.input)==null?void 0:e.texture)}useTextures(...e){let t=this.context.ctx;e.forEach((r,s)=>{r&&(t.activeTexture(t.TEXTURE0+s),t.bindTexture(t.TEXTURE_2D,r))})}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}createBuffer(e){let t=this.context.ctx,r=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,r),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW),r}setTexBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}setPosBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}changeBufferData(e,t){let r=this.context.ctx;r.bindBuffer(r.ARRAY_BUFFER,e),r.bufferData(r.ARRAY_BUFFER,new Float32Array(t),r.STATIC_DRAW)}setAttributes(...e){let t=this.context.ctx;e.forEach((r,s)=>{t.enableVertexAttribArray(s),t.bindBuffer(t.ARRAY_BUFFER,r),t.vertexAttribPointer(s,2,t.FLOAT,!1,0,0)})}getVertexPoint(e,t){return[e/this.width*2-1,t/this.height*2-1]}layout2texCoords(e){return[...this.getVertexPoint(e.x,e.y),...this.getVertexPoint(e.x+e.width,e.y),...this.getVertexPoint(e.x,e.y+e.height),...this.getVertexPoint(e.x+e.width,e.y+e.height)]}resize(e,t){if(!(this.width===e&&this.height===t)){if(this.width=e,this.height=t,this._canvas&&(this._canvas.width=e,this._canvas.height=t),this.texture&&this.fbo){this.useTexture();let r=this.context.ctx;r.texImage2D(r.TEXTURE_2D,0,r.RGBA,e,t,0,r.RGBA,r.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(e,t)}}draw(e,t){this.setAttributes(e||this.positionBuffer,t||this.texCoordBuffer);let r=this.context.ctx;r.drawArrays(r.TRIANGLE_STRIP,0,4)}draw2d(e,t,r,s,n,a,d,l,u){let h=!T(a)&&!T(d)&&!T(l)&&!T(u);return this.ctx2d&&e?(e instanceof ImageData?(h?this.ctx2d.putImageData(e,t,r,a,d,l,u):this.ctx2d.putImageData(e,t,r),this.emit(kr.RENDER,this.ctx2d.canvas)):(h?this.ctx2d.drawImage(e,a,d,l,u,t,r,s,n):this.ctx2d.drawImage(e,t,r,s,n),this.emit(kr.RENDER,e)),typeof VideoFrame!="undefined"&&e instanceof VideoFrame&&e.close(),!0):!1}drawBackGround2d(e){this.ctx2d&&(this.ctx2d.save(),this.ctx2d.fillStyle=e,this.ctx2d.fillRect(0,0,this.width,this.height),this.ctx2d.restore())}getInfo(){var h;let{totalFrames:e,x:t,y:r,width:s,height:n,name:a,cost:d}=this,l=Date.now(),u=(e-this.lastInfo.totalFrames)/((l-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:r,width:s,height:n,timestamp:l,fps:u,name:a,cost:d},M({parent:(h=this.input)==null?void 0:h.getInfo()},this.lastInfo)}createTexture(e){let t=this.context.ctx,r=t.createTexture();return this.useTextures(r),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.pixelStorei(t.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),r}};c(kr,"RENDER","render"),D([ye(j.INIT,"connected",{sync:!0})],kr.prototype,"connect",1),D([ye("connected",j.INIT,{ignoreError:!0,sync:!0})],kr.prototype,"disconnect",1),D([ye([],"closed",{sync:!0})],kr.prototype,"close",1);var Pe=kr;var hS=ce(wu(250),Vn(()=>performance.now()),rr());var hf=o=>i=>{let e=performance.now();ce(hS,Hd(t=>t-e<o),or(1))(i)};var pS=[0,1,1,1,0,0,1,0],fo=class extends Pe{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t));c(this,"_intervalId",0);c(this,"_sequence",0);c(this,"checkGLError",!1);c(this,"checkVisibilityChange");e instanceof Xe?this.ctx2d=e.ctx||null:e.available&&(t!=null&&t.mirrorUpAndDown)&&this.setTexBuffer(pS)}start(e){this.log.info(`${this.name} start render ${e} fps`),oe.clearTask(this._intervalId),this._intervalId=oe.run("intervalInWorker",()=>{if(e!==this.context.frameRate&&(oe.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof Be){let r=this.context.ctx.getError();r&&this.context.destroy(new v({code:I.VIDEO_MANAGER_ERROR,extraCode:5,message:`${this.name} req ${this._sequence} render ${this.totalFrames} faild ${r}`}))}},{fps:this.context.frameRate})}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),this.emit(Pe.RENDER,this.context._canvas),!0):!1}addInput(e,...t){super.addInput(e,...t),this.start(this.context.frameRate)}update(e=0){this.state!=="closed"&&(this._intervalId&&(oe.clearTask(this._intervalId),this._intervalId=0,e===1&&(this.log.info(`${this.name} use requestVideoFrameCallback`),this.checkVisibilityChange=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info(`${this.name} use timer`),document.removeEventListener("visibilitychange",this.checkVisibilityChange))},document.addEventListener("visibilitychange",this.checkVisibilityChange))),this.requestFrame(this._sequence++))}removeInput(e){super.removeInput(e),oe.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}close(){super.close(),oe.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},ps=class extends fo{constructor(e,t){super(e,t);c(this,"_videoTrack");c(this,"_muteOb");c(this,"_closedOb",de(this,"closed"));c(this,"_subscription");c(this,"_canvasContainer");Number(Xi)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e.canvas.captureStream().getVideoTracks(),this._muteOb=de(this._videoTrack,"mute"),ce(de(this._videoTrack,"ended"),ke(this._closedOb),Te(()=>{this.context.destroy(new v({code:I.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){this._subscription=ce(this._muteOb,ke(this._closedOb),mo(hf(5e3)),$t(()=>{var e;return!!((e=this._videoTrack)!=null&&e.muted)&&!document.hidden}),Te(()=>{this.context.destroy(new v({code:I.VIDEO_MANAGER_ERROR,extraCode:7,message:"video track muted"}))}))}disableCheckMute(){var e;(e=this._subscription)==null||e.dispose()}get videoTrack(){return this._videoTrack}putCanvasIntoDom(){!this.context._canvas||!this._canvasContainer||document.getElementById(this.context._canvas.id)||(this.log.info(`${this.name} put canvas to body`),document.body.appendChild(this._canvasContainer),this._canvasContainer.appendChild(this.context._canvas))}render(e){return this.putCanvasIntoDom(),super.render(e)}render2d(e){return this.putCanvasIntoDom(),super.render2d(e)}close(){var e,t;super.close(),(e=this._videoTrack)==null||e.stop(),delete this._videoTrack,(t=this._canvasContainer)==null||t.remove()}},Qd=class extends ps{render(i){var t;let e=!!((t=this.input)!=null&&t.requestFrame(i));if(this.context._canvas2d){let r=this.context._canvas2d.getContext("2d");r.clearRect(0,0,this.context._canvas2d.width,this.context._canvas2d.height),r.drawImage(this.context._canvas,0,0,this.context._canvas2d.width,this.context._canvas2d.height),this.emit(Pe.RENDER,this.context._canvas2d)}else this.emit(Pe.RENDER,this.context._canvas);return e}};var Yd=class extends ps{constructor(e,t,r){super(e,{name:"smallDestination",logger:r});this.resolution=t}resize(e,t){let r,s=e*t,n=this.resolution.width*this.resolution.height;this.log.info(`big res: ${e}*${t} small res: ${this.resolution.width}*${this.resolution.height} `),s>n?r=s/n:(this.log.warn(`Small stream resolution is not smaller than big stream, which is invalid. big: ${e} * ${t} small: ${this.resolution.width} * ${this.resolution.height}`),r=s/(160*120)),super.resize(e/Math.sqrt(r),t/Math.sqrt(r))}};var Hn=class extends Pe{constructor(e,t){super(e,M({name:"imageSource"},t));c(this,"_lastImage");c(this,"_totalFrames",0);c(this,"_autoResize",!1);c(this,"_canvasRendered");c(this,"videoCallbackId",0);c(this,"waitingFirstFrame",!0);c(this,"shouldUpdate",!0);this._autoResize=(t==null?void 0:t.autoResize)!==!1,et===16&&(this._canvasRendered=rt(),ce(this._canvasRendered,xn(this._image),Mr(r=>r instanceof HTMLCanvasElement?de(r,"rendered"):Un()),ke(de(this,"closed")),Te(()=>{this.update()})))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){if(!this.shouldUpdate)return;let e=this.image;this.videoCallbackId&&e.cancelVideoFrameCallback(this.videoCallbackId),Ki()&&!document.hidden&&(this.videoCallbackId=e.requestVideoFrameCallback((t,r)=>{this.waitingFirstFrame&&this.onFirstFrame(),document.hidden||(this._totalFrames=r.presentedFrames,this.update(1))}))}_render(e,t){var a;let{width:r,height:s}=this,{image:n}=this;if(n instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(),{videoWidth:r,videoHeight:s}=n,!r||!s)return!1;n.width=r,n.height=s}else if(n instanceof HTMLImageElement||n instanceof ImageData||n instanceof ImageBitmap){if({width:r,height:s}=n,n!==this._lastImage)this._lastImage=n;else if(r===this.width&&s===this.height)return!0}else n instanceof HTMLCanvasElement||n instanceof OffscreenCanvas?({width:r,height:s}=n,this._lastImage=n):typeof VideoFrame!="undefined"&&n instanceof VideoFrame&&({displayWidth:r,displayHeight:s}=n,(a=this._lastImage)==null||a.close(),this._lastImage=n);if(!this._autoResize)return!0;if(this.width===r&&this.height===s&&this.totalFrames){if(t){this.useTexture();let d=this.context.ctx;d.texSubImage2D(d.TEXTURE_2D,0,0,0,d.RGBA,d.UNSIGNED_BYTE,n)}}else{if(t){this.useTexture();let d=this.context.ctx;d.texImage2D(d.TEXTURE_2D,0,d.RGBA,d.RGBA,d.UNSIGNED_BYTE,n)}this.resize(r,s)}return!0}get image(){return this._image}set image(e){var t;(t=this._canvasRendered)==null||t.next(e),this._image=e}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},$n=class extends Hn{constructor(e,t,r){super(e,r);this._player=t;this.name="videoPlayerSource",ce(de(this._player,he.PLAYER_STATE_CHANGED),ke(de(this,"closed")),$t(({state:s})=>s==="PLAYING"),Te(()=>{this.tryVideoFrameCallback()}))}get image(){return this._player.element}},Wt=class extends $n{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(i,e,t){super(i,new pt({id:t.name,track:e,muted:!0,container:null,objectFit:"contain",log:t.logger}),t),this.name="videoTrackSource",this._player.play()}replaceTrack(i){this.waitingFirstFrame=!0,this._player.setTrack(i),this._player.play()}close(){super.close(),this._player.stop()}},Zd=class extends Pe{constructor(e,t,r){super(e,w(M({name:"textSource"},r),{create2d:!0}));c(this,"hasChange",!0);c(this,"content","");this.ctx2d.textBaseline="top",this.content=t.content||"",t.font&&(this.font=t.font),t.color&&(this.color=t.color)}set font(e){this.ctx2d&&(this.ctx2d.font=e,this.hasChange=!0)}get font(){var e;return((e=this.ctx2d)==null?void 0:e.font)||""}set color(e){this.ctx2d&&(this.ctx2d.fillStyle=e,this.hasChange=!0)}get color(){var e;return((e=this.ctx2d)==null?void 0:e.fillStyle)||""}render2d(e){return this.ctx2d&&this.hasChange?(this.ctx2d.clearRect(0,0,this.width,this.height),this.drawMultilineText(0,0),this.hasChange=!1,!0):!1}render(e){return!1}resize(e,t){if(!this.ctx2d)return;let{color:r,font:s}=this;super.resize(e,t),this.color=r,this.font=s}drawMultilineText(e=0,t=0,r=1.2){if(!this.ctx2d)return;let s=this.ctx2d.measureText(this.content);t+=s.fontBoundingBoxAscent||s.actualBoundingBoxAscent||0;let n=this.font.match(/(\d+)px/),d=(n?parseInt(n[1],10):16)*r,l=this.content.split(`
|
|
34
34
|
`);for(let u=0;u<l.length;u++)this.ctx2d.fillText(l[u],e,t+u*d)}};var _S=`
|
|
35
35
|
// \u9876\u70B9\u7740\u8272\u5668
|
|
36
36
|
attribute vec4 a_position;
|
|
@@ -49,13 +49,13 @@ uniform sampler2D u_texture;
|
|
|
49
49
|
|
|
50
50
|
void main() {
|
|
51
51
|
gl_FragColor = texture2D(u_texture, v_texCoord);
|
|
52
|
-
} `;var _o=class extends j{constructor(e){super();c(this,"frameRate");c(this,"_canvas");c(this,"log");c(this,"hasAlpha",!1);c(this,"name");c(this,"error");this.name=e.name,this.log=e.logger.createChild({id:`vc-${this.name}`}),this.frameRate=e.frameRate}get canvas(){return this._canvas}set width(e){this._canvas&&(this._canvas.width=e)}get width(){var e;return((e=this._canvas)==null?void 0:e.width)||0}set height(e){this._canvas&&(this._canvas.height=e)}get height(){var e;return((e=this._canvas)==null?void 0:e.height)||0}setSize(e,t){this._canvas&&(this._canvas.width=e,this._canvas.height=t)}createVideoTrackSource(e,t){return new Wt(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new ps(this,e)}createVideoImageSource(e,t){return new Hn(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new $n(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}createTextSource(e,t){return new Zd(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}};c(_o,"_ids",0);var TS={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},fs=class fs extends _o{constructor(){super(...arguments);c(this,"defaultProgam");c(this,"defaultVShader");c(this,"defaultFShader");c(this,"ctx");c(this,"_canvas2d")}get canvas(){return this._canvas2d||this._canvas}create(e=!1){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${_o._ids++}`),e&&(this._canvas2d=document.createElement("canvas")),this.ctx=this._canvas.getContext("webgl2",TS),!this.ctx)throw new v({code:I.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,_S),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,gS),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new v({code:I.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})}destroy(e){let t="";return e&&(t=e.message,this.error=e,y.addFailedEvent({key:512702,error:e})),this.disconnect(),this.log.info(`video context destroy${t}`?`: ${t}`:""),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),e}set width(e){var t;(t=this.ctx)==null||t.viewport(0,0,e,this.height),super.width=e,this._canvas2d&&(this._canvas2d.width=e)}set height(e){var t;(t=this.ctx)==null||t.viewport(0,0,this.width,e),super.height=e,this._canvas2d&&(this._canvas2d.height=e)}setSize(e,t){var r;(r=this.ctx)==null||r.viewport(0,0,e,t),super.setSize(e,t),this._canvas2d&&(this._canvas2d.width=e,this._canvas2d.height=t)}createShader(e,t){let r=this.ctx,s=r.createShader(e);return r.shaderSource(s,t),r.compileShader(s),s}createProgram(e,t){let r=this.ctx,s=r.createProgram();return r.attachShader(s,e),r.attachShader(s,t),r.linkProgram(s),r.getProgramParameter(s,r.LINK_STATUS)||this.log.error(r.getProgramInfoLog(s)),s}};c(fs,"UNAVAILABLE","unavailable"),D([ye(j.INIT,"created",{sync:!0,fail(e){this.log.error("video gl context create failed",e.cause),y.addFailedEvent({key:512700,error:e.cause||e})},success(){this.log.info("video context created use webgl"),y.addSuccessEvent({key:512700})}})],fs.prototype,"create",1),D([ye("created",j.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(fs.UNAVAILABLE,e),this.removeAllListeners()}})],fs.prototype,"destroy",1);var Be=fs,Xe=class extends _o{constructor(){super(...arguments);c(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${_o._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:e.alpha,willReadFrequently:e.willReadFrequently}),!this.ctx)throw new v({code:I.VIDEO_MANAGER_ERROR,extraCode:2,message:"2d context not supported"});this._canvas.addEventListener("contextlost",()=>{this.log.error("2d context lost")}),this._canvas.addEventListener("contextrestored",()=>{this.log.warn("2d context restored")})}destroy(e){let t="";e&&(t=e.message,this.error=e,y.addFailedEvent({key:512703,error:e})),this.disconnect(),this.log.info(`video context destroy ${t?`: ${t}`:""}`),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners(),y.addSuccessEvent({key:512703})}};D([ye(j.INIT,"created",{sync:!0,fail(e){this.log.error("video 2d context create failed",e.cause),y.addFailedEvent({key:512701,error:e.cause||e})},success(){this.log.info("video context created use 2d"),y.addSuccessEvent({key:512701})}})],Xe.prototype,"create",1),D([ye("created",j.INIT,{ignoreError:!0,sync:!0})],Xe.prototype,"destroy",1);function ES(o,i,e,t,r,s=!1){s&&([e,t]=[t,e]);let n={sWidth:o,sHeight:i,dWidth:e,dHeight:t,sx:0,sy:0,dx:0,dy:0};if(o===0||i===0)return n;switch(r){case void 0:case"fill":break;case"contain":{let a=Math.min(e/o,t/i);n.dWidth=o*a,n.dHeight=i*a,n.dx=(e-n.dWidth)/2,n.dy=(t-n.dHeight)/2;break}case"cover":{let a=Math.max(e/o,t/i),d=e/a,l=t/a;n.sx=(o-d)/2,n.sy=(i-l)/2,n.sWidth=d,n.sHeight=l;break}}return n}var Eh=class{constructor(i,e){this.node=i;this.layout=e;c(this,"positionBuffer")}get x(){return this.layout.x||this.node.x}get y(){return this.layout.y||this.node.y}get width(){return this.layout.width||this.node.width}get height(){return this.layout.height||this.node.height}get right(){return this.x+this.width}get bottom(){return this.y+this.height}get fillMode(){return this.layout.fillMode}get rotation(){return this.layout.rotation}get hidden(){return!!this.layout.hidden}},_s=class extends Pe{constructor(e,t){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:t});c(this,"inputs",[]);c(this,"backgroundColor","black")}addInput(e,t){let r=0,s=this.inputs.length;for(;r<s;){let a=Math.floor((r+s)/2);if(this.inputs[a].layout.zIndex<t.zIndex)r=a+1;else if(this.inputs[a].layout.zIndex>t.zIndex)s=a;else throw new Error(`input already exists at zIndex ${t.zIndex}`)}let n=new Eh(e,t);this.inputs.splice(r,0,n)}changeInputLayout(e,t){let r=this.inputs.findIndex(g=>g.node===e);if(r<0)return;let{x:s,y:n,width:a,height:d,zIndex:l,fillMode:u,rotation:h,hidden:p}=t;if(!T(l)&&this.inputs.some(g=>g.layout.zIndex===l&&g.node!==e))throw new Error(`input already exists at zIndex ${t.zIndex}`);let m=this.inputs[r];T(s)||(m.layout.x=s),T(n)||(m.layout.y=n),T(a)||(m.layout.width=a),T(d)||(m.layout.height=d),T(h)||(m.layout.rotation=h),T(p)||(m.layout.hidden=p),u&&(m.layout.fillMode=u),!T(l)&&l!==m.layout.zIndex&&(m.layout.zIndex=l,this.inputs.sort((g,E)=>g.layout.zIndex-E.layout.zIndex))}hasInput(e){return this.inputs.some(t=>t.node===e)}hasNoInput(){return this.inputs.length===0}resize(e,t){if(!this.matchInputSize){super.resize(e,t);return}let r=this.inputs.reduce((s,n)=>n?Object.assign(s,{width:Math.max(s.width,n.right),height:Math.max(s.height,n.bottom)}):s,{width:0,height:0});super.resize(r.width,r.height),this.context instanceof Be&&this.inputs.forEach(s=>{if(s){let n=this.layout2texCoords(s);s.positionBuffer?this.changeBufferData(s.positionBuffer,n):s.positionBuffer=this.createBuffer(n)}})}connect(e,...t){return super.connect(e,...t),this.drawBackGround2d(this.backgroundColor),this.matchInputSize&&this.resize(0,0),e}removeInput(e){this.inputs=this.inputs.filter(t=>t.node!==e),this.inputs.length===0&&this.drawBackGround2d(this.backgroundColor)}render(e){let t=this.context.ctx;if(t.clearColor(0,0,0,0),this.inputs.reduce((s,n)=>n.node.requestFrame(e)||s,!1)&&t){this.useProgram(),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let s=0;s<this.inputs.length;s++){let n=this.inputs[s];n&&(n.node.useTexture(),this.draw(n.positionBuffer))}return!0}return!1}render2d(e){if(this.inputs.forEach(t=>t.node.requestFrame(e)),this.ctx2d){this.drawBackGround2d(this.backgroundColor);for(let t=0;t<this.inputs.length;t++){let r=this.inputs[t];if(r.hidden)continue;let s=ES(r.node.width,r.node.height,r.width,r.height,r.fillMode,bt(r.rotation));this.draw2d(r.node.image,r.x+s.dx,r.y+s.dy,s.dWidth,s.dHeight,s.sx,s.sy,s.sWidth,s.sHeight)}return!0}return!1}debugLayout(e,t,r,s,n=!1){this.ctx2d&&(n&&([r,s]=[s,r]),this.ctx2d.save(),this.ctx2d.strokeStyle="red",this.ctx2d.lineWidth=2,this.ctx2d.strokeRect(e,t,r,s),this.ctx2d.restore())}getInfo(){let{totalFrames:e,x:t,y:r,width:s,height:n,name:a}=this,d=Date.now(),l=(e-this.lastInfo.totalFrames)/((d-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:r,width:s,height:n,timestamp:d,fps:l,name:a},M({parent:this.inputs.filter(u=>u).map(u=>u.node.getInfo())},this.lastInfo)}removeAllInputs(){this.inputs.forEach(e=>{var t;if(e.node.disconnect(),e.positionBuffer&&this.context instanceof Be)try{(t=this.context.ctx)==null||t.deleteBuffer(e.positionBuffer)}catch(r){}})}close(){super.close(),this.removeAllInputs()}};var SS=[1,0,0,0,1,1,0,1],Gt=class extends Pe{constructor(e,t,r,s){super(e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"transform",logger:t});c(this,"mirror",!1);c(this,"rotation",0);if(r&&(this.mirror=r),s&&(this.rotation=s),e instanceof Be)try{this.setTexBuffer(SS)}catch(n){e.destroy(new v({code:I.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${n.message||n}`}))}}draw2d(e,t,r,s,n){if(this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height),this.ctx2d.save(),this.mirror&&(this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0)),this.rotation===90?(this.ctx2d.translate(s,0),this.ctx2d.rotate(Math.PI/2),this.ctx2d.scale(n/s,s/n)):this.rotation===180?(this.ctx2d.translate(this.width,this.height),this.ctx2d.rotate(Math.PI)):this.rotation===270&&(this.ctx2d.translate(0,n),this.ctx2d.rotate(3*Math.PI/2),this.ctx2d.scale(n/s,s/n));let a=super.draw2d(e,t,r,s,n);return this.ctx2d.restore(),a}return!1}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}resize(e,t){bt(this.rotation)&&([e,t]=[t,e]),super.resize(e,t)}};var go=class extends _i{constructor(e,t=4){super(t,pt);c(this,"inputLocalVideoTracks",new Map);c(this,"inputLocalScreenTracks",new Map);c(this,"cameraNodeMap",new Map);c(this,"screenNodeMap",new Map);c(this,"textNodeMap",new Map);c(this,"imageNodeMap",new Map);c(this,"videoNodeMap",new Map);c(this,"endedIds",new Set);c(this,"videoContext");c(this,"mixNode");c(this,"destination");c(this,"manager");c(this,"stat");c(this,"_checkId",0);c(this,"autoSetFps",!0);this.manager=e,this.log.id+="mix",this.create2dVideoContext(),this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log}),this.destination.on(Pe.RENDER,r=>{this.emit("render",r)}),this.mixNode=new _s(this.videoContext,this.log),this.mixNode.matchInputSize=!1}listenDeviceChange(){throw new Error("Method not implemented.")}enablePrintDetail(e=2e3){this._checkId=oe.run("interval",()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:e})}create2dVideoContext(){this.videoContext?this.videoContext.destroy():this.videoContext=new Xe({frameRate:15,logger:this.log,name:"mix-ctx"}),this.videoContext.create({alpha:!1})}setFps(e){this.autoSetFps=!1,this.videoContext.frameRate=e;for(let t of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])t.shouldUpdate=!1;setTimeout(()=>{var t;return(t=this.destination)==null?void 0:t.start(this.videoContext.frameRate)},500)}setFpsAuto(){var s;if(!this.autoSetFps)return;for(let n of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])n.shouldUpdate=!1;let e=null,t=0,r=!0;for(let[n,a]of this.inputLocalVideoTracks)if(a.profile.frameRate>t){if(this.endedIds.has(n)){let d=this.cameraNodeMap.get(n);d&&d.image.cancelVideoFrameCallback(d.videoCallbackId);continue}t=a.profile.frameRate,e=n}for(let[n,a]of this.inputLocalScreenTracks)if(a.profile.frameRate>t){if(this.endedIds.has(n)){let d=this.screenNodeMap.get(n);d&&d.image.cancelVideoFrameCallback(d.videoCallbackId);continue}t=a.profile.frameRate,e=n,r=!1}if(e!==null){let n=r?this.cameraNodeMap.get(e):this.screenNodeMap.get(e);n&&(n.shouldUpdate=!0,n.tryVideoFrameCallback()),this.log.info("set mix fps: ",t)}else(s=this.destination)==null||s.start(this.videoContext.frameRate),this.log.info("fallback to timer, fps: ",this.videoContext.frameRate)}setMixBackground(e){this.mixNode&&(this.mixNode.backgroundColor=e)}resizeMixCanvas(e,t){var r;(r=this.mixNode)==null||r.resize(e,t)}startMix(){return f(this,null,function*(){var e;if(!this.mixNode||!this.destination)throw new Error("can't mix without necessary conditions");this.mixNode.disconnect(),this.mixNode.connect(this.destination),Ft&&this.player.setCanvas(this.videoContext._canvas),this.setOutputMediaStreamTrack(this.destination.videoTrack),(e=this.manager)==null||e.changeInput(this)})}addCameraSource(e,t,r){if(this.inputLocalVideoTracks.has(e)||this.cameraNodeMap.has(e))throw new Error(`There is already a cameraSource with the same ID: ${e}`);let{mediaTrack:s}=t;if(!s)throw new Error("no mediaTrack, add cameraSource failed");t.recaptureMode=1,tt(this,be).add("videoInputRemoved",a=>{a.deviceId===t.deviceId&&(this.endedIds.add(e),this.setFpsAuto())}),t.on("output-media-track-changed",()=>{this.endedIds.delete(e),this.updateCameraSource(e,r,t.mediaTrack)});let n;et===16&&s instanceof CanvasCaptureMediaStreamTrack?n=this.videoContext.createVideoImageSource(s.canvas,{name:"cameraCanvasSource",logger:this.log}):n=this.videoContext.createVideoTrackSource(s,"cameraNodeSource"),n.resize(t.settings.width,t.settings.height),n.shouldUpdate=!1,this._connectMix(n,r,"cover"),this.inputLocalVideoTracks.set(e,t),this.cameraNodeMap.set(e,n),this.setFpsAuto()}addScreenSource(e,t,r){if(this.inputLocalScreenTracks.has(e)||this.screenNodeMap.has(e))throw new Error(`There is already a screenSource with the same ID: ${e}`);let{mediaTrack:s}=t;if(!s)throw new Error("no mediaTrack, add cameraSource failed");let n=this.videoContext.createVideoTrackSource(s,"screenNodeSource");n.resize(t.settings.width,t.settings.height),n.shouldUpdate=!1,this._connectMix(n,r),this.inputLocalScreenTracks.set(e,t),this.screenNodeMap.set(e,n),this.setFpsAuto()}addTextSource(e){let{id:t,content:r="",font:s,color:n,layout:a}=e;if(this.textNodeMap.has(t))throw new Error(`There is already a textSource with the same ID: ${t}`);let d=this.videoContext.createTextSource({content:r,font:s,color:n});d.resize(a.width,a.height),this._connectMix(d,a),this.textNodeMap.set(t,d)}addImageSource(e,t,r){if(this.imageNodeMap.has(e))throw new Error(`There is already a imageSource with the same ID: ${e}`);let s=this.videoContext.createVideoImageSource(t,{autoResize:!1,logger:this.log});s.resize(t.width,t.height),this._connectMix(s,r),this.imageNodeMap.set(e,s)}addVideoSource(e,t,r){if(this.videoNodeMap.has(e))throw new Error(`There is already a videoSource with the same ID: ${e}`);let s=this.videoContext.createVideoImageSource(t,{autoResize:!1,logger:this.log});s.resize(t.videoWidth,t.videoHeight),s.shouldUpdate=!1,this._connectMix(s,r),this.videoNodeMap.set(e,s)}updateCameraSource(e,t,r=null,s){let n=this.cameraNodeMap.get(e);if(n){if(r){if(et===16&&r instanceof CanvasCaptureMediaStreamTrack)if(n instanceof Wt){let l=n.output;n.close(),n=this.videoContext.createVideoImageSource(r.canvas,{name:"cameraCanvasSource",logger:this.log}),n.connect(l),this.cameraNodeMap.set(e,n)}else n.image=r.canvas;else if(n instanceof Wt)n.replaceTrack(r);else{let l=n.output;n.close(),n=this.videoContext.createVideoTrackSource(r,"cameraNodeSource"),n.connect(l),this.cameraNodeMap.set(e,n)}let{width:a,height:d}=r.getSettings();a&&d&&n.resize(a,d)}s&&n.resize(s.width,s.height),(s||r)&&this.setFpsAuto(),this._changeMixLayout(n,t)}}updateScreenSource(e,t){let r=this.screenNodeMap.get(e);r&&this._changeMixLayout(r,t)}updateTextSource(e){let{id:t,content:r,font:s,color:n,layout:a}=e,d=this.textNodeMap.get(t);d&&(T(r)||(d.content=r),T(s)||(d.font=s),T(n)||(d.color=n),d.resize(a.width,a.height),this._changeMixLayout(d,a))}updateImageSource(e,t,r){let s=this.imageNodeMap.get(e);s&&(r&&(s.image=r,s.resize(r.width,r.height)),this._changeMixLayout(s,t))}updateVideoSource(e,t,r){let s=this.videoNodeMap.get(e);if(s){if(r){let n=s.image;n instanceof HTMLVideoElement&&this.stopVideoElement(n),s.image=r,s.resize(r.videoWidth,r.videoHeight)}this._changeMixLayout(s,t)}}_connectMix(e,t,r="contain"){if(!this.mixNode)return;let{mirror:s,rotation:n}=t;e.disconnect();let a=new Gt(this.videoContext,this.log,s,n);a=e.connect(a),t.fillMode||(t.fillMode=r),a.connect(this.mixNode,t)}_changeMixLayout(e,t){if(!this.mixNode)return;let{mirror:r,rotation:s}=t,n=e.output||e;n instanceof Gt&&(T(r)||(n.mirror=r),T(s)||(n.rotation=s),n.resize(e.width,e.height)),this.mixNode.changeInputLayout(n,t)}removeCameraSource(e){let t=this.inputLocalVideoTracks.get(e);if(!t)return;t.close(),this.inputLocalVideoTracks.delete(e);let r=this.cameraNodeMap.get(e);r&&(r.output instanceof Gt&&r.output.close(),r.close(),this.cameraNodeMap.delete(e)),this.checkAfterRemove(!0)}removeScreenSource(e){let t=this.inputLocalScreenTracks.get(e);if(!t)return;t.close(),this.inputLocalScreenTracks.delete(e);let r=this.screenNodeMap.get(e);r&&(r.output instanceof Gt&&r.output.close(),r.close(),this.screenNodeMap.delete(e)),this.checkAfterRemove(!0)}removeTextSource(e){let t=this.textNodeMap.get(e);t&&(t.output instanceof Gt&&t.output.close(),t.close(),this.textNodeMap.delete(e)),this.checkAfterRemove()}removeImageSource(e){let t=this.imageNodeMap.get(e);t&&(t.output instanceof Gt&&t.output.close(),t.close(),this.imageNodeMap.delete(e)),this.checkAfterRemove()}removeVideoSource(e){let t=this.videoNodeMap.get(e);t&&(t.output instanceof Gt&&t.output.close(),t.image instanceof HTMLVideoElement&&this.stopVideoElement(t.image),t.close(),this.videoNodeMap.delete(e)),this.checkAfterRemove()}checkAfterRemove(e=!1){e&&this.setFpsAuto()}stopVideoElement(e){e.pause(),e.src="",e.srcObject=null,e.remove()}close(){var e;super.close(),oe.clearTask(this._checkId),(e=this.videoContext)==null||e.destroy(),delete this.mixNode,delete this.destination;for(let t of[...this.inputLocalVideoTracks.values(),...this.inputLocalScreenTracks.values()])t.close();this.inputLocalVideoTracks.clear(),this.inputLocalScreenTracks.clear(),this.cameraNodeMap.clear(),this.screenNodeMap.clear(),this.textNodeMap.clear(),this.imageNodeMap.clear(),we(this);for(let t of this.videoNodeMap.values())t.image instanceof HTMLVideoElement&&this.stopVideoElement(t.image);this.videoNodeMap.clear(),this.log.info("localMixVideoTrack close, stop mix")}};var Kd=an();if(typeof navigator!="undefined"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:Kd,exposeOrigin:!0,permittedOrigins:["*"]})}catch(o){}var IS=function(o){return f(this,null,function*(){let i=null,e=RS(o);R.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let t=yield navigator.mediaDevices.getDisplayMedia(e);o.systemAudio&&t.getAudioTracks().length===0&&(Zo&&$e<74||Re||ee)&&R.warn("Your browser not support capture system audio");let r=t.getVideoTracks()[0];if(r){if(o.frameRate)try{yield r.applyConstraints({frameRate:{min:o.frameRate,ideal:o.frameRate},width:o.width,height:o.height})}catch(s){R.warn(`screen applyConstraints failed: ${s}`)}o.captureElement&&(yield AS(r,o.captureElement))}if(o.audio){let s=CS(o);R.info(`getUserMedia with constraints: ${JSON.stringify(s)}`),i=yield navigator.mediaDevices.getUserMedia(s),t.addTrack(i.getAudioTracks()[0])}return t})};function AS(o,i){return f(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&le(o.cropTo))try{if(!(((e=o.getCaptureHandle())==null?void 0:e.handle)===Kd))return;let r=yield CropTarget.fromElement(i);yield o.cropTo(r)}catch(t){R.warn(`cropTo target failed ${t}`)}})}function CS(o){let i={echoCancellation:o.echoCancellation,autoGainControl:o.autoGainControl,noiseSuppression:o.noiseSuppression,sampleRate:o.sampleRate,channelCount:o.channelCount};return T(o.microphoneId)||(i.deviceId=o.microphoneId),{audio:i,video:!1}}function RS(o){let i={preferCurrentTab:o.preferDisplaySurface==="current-tab"||!!o.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:Re?{max:o.width}:{ideal:o.width,max:o.width},height:Re?{max:o.height}:{ideal:o.height,max:o.height},frameRate:o.frameRate,displaySurface:o.preferDisplaySurface||"monitor"};if(i.video=e,o.systemAudio){let{echoCancellation:t=!0,noiseSuppression:r=!1,autoGainControl:s=!1}=o;i.audio={echoCancellation:t,noiseSuppression:r,autoGainControl:s,sampleRate:48e3}}return i}var mf=IS;var Pt=class extends je{constructor(e){super(e,2);c(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600});c(this,"objectFit","contain");c(this,"isScreen",!0);this._log.id=`s-${this._log.id}`}get isShareCurrentTab(){var e,t;try{return Kd===((t=(e=this.mediaTrack)==null?void 0:e.getCaptureHandle())==null?void 0:t.handle)}catch(r){return}}capture(u){return f(this,arguments,function*({systemAudio:e=!1,autoGainControl:t,echoCancellation:r,noiseSuppression:s,audioTrack:n,videoTrack:a,captureElement:d,preferDisplaySurface:l}){try{let h;return a||n?(h=new MediaStream,a&&h.addTrack(a),n&&h.addTrack(n)):(h=yield mf({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:t,echoCancellation:r,noiseSuppression:s,captureElement:d,preferDisplaySurface:l}),this.sourceTrack=h.getVideoTracks()[0]),yield this.setInputMediaStreamTrack(h.getVideoTracks()[0]),h}catch(h){throw this.log.error(`getDisplayMedia error observed ${h}`),h instanceof v?h:new v({code:I.INITIALIZE_FAILED,name:h.name,message:h.message})}})}switchDevice(e){return f(this,null,function*(){throw new Error("Method not implemented.")})}};D([Ct(function(e){this.setContentHint(e.contentHint||"detail")})],Pt.prototype,"capture",1);var To=class extends kt{constructor(i){super(i),this._log.id=`s-${this._log.id}`,this.isScreen=!0}addAudioProcessor(i,e,t){this.pipeline.silentNode.setNode(t),this.pipeline.mixNode.setNode(e),this.pipeline.aec.setNode(i),this.enableTrackAEC(!1)}removeAudioProcessor(i){this.pipeline.aec.node===i&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode(),this.enableTrackAEC(!0))}};var yS='registerProcessor("dumper",class extends AudioWorkletProcessor{constructor(e){super(),this.sourceSampleRate=e.processorOptions.sourceSampleRate||48e3,this.targetSampleRate=e.processorOptions.targetSampleRate||48e3,this.port.onmessage=e=>{this.port2=e.data.port}}process(e){return(this.port2||this.port).postMessage(this.resampleAll(e,this.sourceSampleRate,this.targetSampleRate)),!0}resampleAll(r,s,a){if(s===a)return r;var o=[];for(let t=0;t<r.length;t++){o[t]=[];for(let e=0;e<r[t].length;e++)o[t][e]=this.resample(r[t][e],s,a)}return o}resample(t,e,r){if(e===r)return t;var s=Math.round(t.length*(this.targetSampleRate/this.sourceSampleRate)),a=new Float32Array(s),o=(t.length-1)/(s-1);a[0]=t[0];for(let e=1;e<s-1;e++){var l=e*o,p=Math.floor(l),h=Math.ceil(l);a[e]=t[p]+(t[h]-t[p])*(l-p)}return a[s-1]=t[t.length-1],a}});',Sh;function Wn(o,i=48e3,e=1,t){return f(this,null,function*(){let r=Ee("dump");Sh||(Sh=tr(r,URL.createObjectURL(new Blob([yS],{type:"application/javascript"})))),yield Sh;let s=r.sampleRate,n=new AudioWorkletNode(r,"dumper",{numberOfInputs:o.length,numberOfOutputs:0,processorOptions:{sourceSampleRate:s,targetSampleRate:i}});return n.channelCountMode="explicit",n.channelCount=e,t&&n.port.postMessage({port:t},[t]),o.forEach((a,d)=>a.connect(n,0,d)),new ReadableStream({start(a){n.port.onmessage=d=>{a.enqueue(d.data)}},cancel(){o.forEach(a=>a.disconnect(n)),n.port.close()}})})}var ec=class extends yd{constructor(e){super();this.room=e;c(this,"_localAudioTrack");c(this,"_localScreenAudioTrack");c(this,"log");c(this,"denoiser");c(this,"voiceChanger");c(this,"mixChangedDebounce");c(this,"audioProcessor");c(this,"encodePipeline",[]);c(this,"decodePipeline",[]);c(this,"getPCMAbortCtrlMap",new Map);c(this,"audioFrameEventConfigMap",new Map);c(this,"audioReferenceMap",new Map);c(this,"isLocalAudioNeedAudioProcess",!1);c(this,"isScreenAudioNeedAudioProcess",!1);this.log=R.createLogger({parent:e==null?void 0:e.getLogger(),id:"am",userId:e==null?void 0:e.userId,sdkAppId:e==null?void 0:e.sdkAppId}),this.installEvent()}get localAudioTrack(){return this._localAudioTrack}get _localAudioPipline(){var e;return(e=this._localAudioTrack)==null?void 0:e.pipeline}get _localScreenAudioPipeline(){var e;return(e=this._localScreenAudioTrack)==null?void 0:e.pipeline}dump(e){var u,h;if(!this._localAudioTrack)return;let t=[],r=[];(u=this._localAudioPipline)!=null&&u.source.node&&(t.push(this._localAudioPipline.source.node),r.push("mic")),(h=this._localAudioPipline)!=null&&h.denoiser.node&&(t.push(this._localAudioPipline.denoiser.node),r.push("mic-processed")),this.mixWeight>1&&(t.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),r.push("mix")),this.log.info(`dump audio track ${r}, duration: ${e}`);let s=new AbortController,n=[],a=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),s.abort("timeout")},e*1e3),d=()=>{for(let p=0;p<r.length;p++){let m=URL.createObjectURL(new Blob(n[p])),g=document.createElement("a");g.href=m,g.download=`${r[p]}.pcm`,g.style.display="none",document.body.appendChild(g),g.click(),URL.revokeObjectURL(m),g.remove()}clearTimeout(a),s.abort("download")},l=Wn(t).then(p=>p.pipeTo(new WritableStream({write(m){m.forEach((g,E)=>n[E]=n[E]?n[E].concat(g[0]):[g[0]])}}),s).catch(m=>d));return{then:l.then.bind(l),download:d}}getPCM(e,t){var P,re,L;if(typeof WritableStream=="undefined"){this.log.warn("getPCM failed: browser not support WritableStream");return}let{enable:r,sampleRate:s=48e3,channelCount:n=1,port:a}=(t===""?this.audioFrameEventConfigMap.get(""):this.audioFrameEventConfigMap.get(t)||this.audioFrameEventConfigMap.get("*"))||{};if(!r)return;this.log.info(`getPCM ${t||"local"}`);let d=Math.floor(s*.04),l=new Float32Array(d),u=new Float32Array(d),h,p,m=0,g=new AbortController,E=t===""?(P=this._localAudioTrack)==null?void 0:P.mediaTrack:(L=(re=this.room)==null?void 0:re.remotePublishedUserMap.get(t))==null?void 0:L.remoteAudioTrack.mediaTrack;if(!E){this.log.info(`getPCM failed: ${t||"local"} has no audio track`);return}let C=Ee().createMediaStreamSource(new MediaStream([E]));return Wn([C],s,n,a).then(Qe=>Qe.pipeTo(new WritableStream({write(N){N[0][0]&&(m+N[0][0].length>d?(l.set(N[0][0].subarray(0,d-m),m),h=N[0][0].subarray(d-m),N[0][1]&&(u.set(N[0][1].subarray(0,d-m),m),p=N[0][1].subarray(d-m)),m+=d-m):(h&&(l.set(h,m),m+=h.length,h=void 0),p&&(u.set(p,m),p=void 0),l.set(N[0][0],m),N[0][1]&&u.set(N[0][1],m),m+=N[0][0].length),m>=d&&(m=0,e({userId:t,sampleRate:s,channelCount:n,data:n===1?l:[l,u]}),l=new Float32Array(d),u=new Float32Array(d)))}}),g).catch(N=>this.log.warn(`stop getPCM reason:${N}`))),g}get hasScreenAudioTrack(){return!T(this._localScreenAudioTrack)}get hasAudioTrack(){return!T(this._localAudioTrack)}changeInput(e){var t,r;if(e instanceof To)return this._localScreenAudioTrack=e,this.isScreenAudioNeedAudioProcess&&((t=this.audioProcessor)!=null&&t.screenAudioWorkletNode)&&(e.addAudioProcessor(this.audioProcessor.screenAudioWorkletNode,this.audioProcessor.mixNode,this.audioProcessor.silentNode),this.audioReferenceMap.forEach((s,n)=>{e.mixAudioReference(s,n)})),e.pipeline.connect(),this.mixOnChange();if(e instanceof kt)return this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),this.isLocalAudioNeedAudioProcess&&((r=this.audioProcessor)!=null&&r.localAudioWorkletNode)&&(e.addAudioProcessor(this.audioProcessor.localAudioWorkletNode,this.audioProcessor.mixNode,this.audioProcessor.silentNode),this.audioReferenceMap.forEach((s,n)=>{e.mixAudioReference(s,n)})),e.pipeline.connect(),this.mixOnChange();if(e instanceof Ei)return e.setOutputMediaStreamTrack(e.mediaTrack)}mixAudioReference(e,t){var r;(r=this._localAudioTrack)==null||r.mixAudioReference(e,t)}unMixAudioReference(e){var t;(t=this._localAudioTrack)==null||t.unMixAudioReference(e)}setAudioReferenceVolume(e,t){var r;(r=this._localAudioTrack)==null||r.setAudioReferenceVolume(e,t)}mixOnChange(){return this.mixChangedDebounce||(this.mixChangedDebounce=Promise.resolve().then(()=>{var e,t;return delete this.mixChangedDebounce,Promise.all([(e=this._localAudioTrack)==null?void 0:e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),(t=this._localScreenAudioTrack)==null?void 0:t.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)])})),this.mixChangedDebounce}removeInput(e){e instanceof To?delete this._localScreenAudioTrack:e instanceof kt?delete this._localAudioTrack:e instanceof Ei}addDenoiser(e){var t;this.denoiser=e,(t=this._localAudioTrack)==null||t.addDenoiser(e)}addAudioProcessor(e,t,r,s){var n;this.audioProcessor={localAudioWorkletNode:r,mixNode:e,silentNode:t,screenAudioWorkletNode:s},this.isLocalAudioNeedAudioProcess&&this._localAudioTrack&&r&&(this._localAudioTrack.addAudioProcessor(r,e,t),this.audioReferenceMap.forEach((a,d)=>{var l;(l=this._localAudioTrack)==null||l.mixAudioReference(a,d)})),this.isScreenAudioNeedAudioProcess&&this._localScreenAudioTrack&&s&&((n=this._localScreenAudioTrack)==null||n.addAudioProcessor(s,e,t),this.audioReferenceMap.forEach((a,d)=>{var l;(l=this._localScreenAudioTrack)==null||l.mixAudioReference(a,d)}))}removeDenoiser(e){var t;return delete this.denoiser,(t=this._localAudioTrack)==null?void 0:t.removeDenoiser(e)}addVoiceChanger(e,t){var r;this.voiceChanger=[e,t],(r=this._localAudioTrack)==null||r.pipeline.voiceChanger.setNode(e,t)}removeVoiceChanger(){var e;delete this.voiceChanger,(e=this._localAudioTrack)==null||e.pipeline.voiceChanger.deleteNode()}removeAudioProcessor(e,t){var r,s;delete this.audioProcessor,(r=this._localAudioTrack)==null||r.removeAudioProcessor(e),(s=this._localScreenAudioTrack)==null||s.removeAudioProcessor(t)}destroy(){this.close(),this.audioReferenceMap.clear(),this.getPCMAbortCtrlMap.forEach(e=>e==null?void 0:e.abort("destroy")),this.getPCMAbortCtrlMap.clear(),this.audioFrameEventConfigMap.clear(),this.uninstallEvent()}addEncodeProcessor({processor:e,type:t}){var r;this.encodePipeline.includes(e)||(this.encodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}addDecodeProcessor({processor:e,type:t}){var r;this.decodePipeline.includes(e)||(this.decodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}handleLocalTrackStarted({room:e,userId:t}){var s;if(e!==this.room||this.getPCMAbortCtrlMap.get(t))return;let r=this.getPCM(n=>{var a;(a=this.room)==null||a.emit("audio-frame",n)},"");this.getPCMAbortCtrlMap.set(t,r),this.getPCMAbortCtrlMap.get(t)&&((s=this._localAudioTrack)==null||s.on("input-media-track-changed",()=>{let n=this.getPCMAbortCtrlMap.get(t);n&&(n.abort("inputMediaTrackChanged"),n=this.getPCM(a=>{var d;(d=this.room)==null||d.emit("audio-frame",a)},""),this.getPCMAbortCtrlMap.set(t,n))}))}handleLocalTrackStopped({room:e,userId:t}){if(e!==this.room)return;let r=this.getPCMAbortCtrlMap.get(t);r&&(r.abort("stopLocalAudio"),this.getPCMAbortCtrlMap.delete(t))}handleRemoteTrackStarted({room:e,userId:t}){if(e===this.room&&!this.getPCMAbortCtrlMap.get(t)){let r=this.room.audioManager.getPCM(s=>{var n;(n=this.room)==null||n.emit("audio-frame",s)},t);this.getPCMAbortCtrlMap.set(t,r)}}handleRemoteTrackStopped({room:e,userId:t}){if(e!==this.room)return;let r=this.getPCMAbortCtrlMap.get(t);r&&(r.abort("stopRemoteAudio"),this.getPCMAbortCtrlMap.delete(t))}installEvent(){S.on("113",this.handleLocalTrackStarted,this),S.on("114",this.handleLocalTrackStopped,this),S.on("115",this.handleRemoteTrackStarted,this),S.on("116",this.handleRemoteTrackStopped,this)}uninstallEvent(){S.off("113",this.handleLocalTrackStarted),S.off("114",this.handleLocalTrackStopped),S.off("115",this.handleRemoteTrackStarted),S.off("116",this.handleRemoteTrackStopped)}updateAudioReference({type:e,audioReference:t,refId:r,volume:s}){if(e==="add"){if(this.audioReferenceMap.get(r)||!t||(this.audioReferenceMap.set(r,t),!this.audioProcessor))return;this.mixAudioReference(t,r)}else if(e==="remove")this.audioReferenceMap.get(r)&&(this.audioReferenceMap.delete(r),this.unMixAudioReference(r));else if(e==="updateVolume"){if(!this.audioProcessor||T(s))return;this.setAudioReferenceVolume(r,s)}}};function Eo(o=30,i=2){return Y((e,t)=>function(...r){return new Promise((s,n)=>{let a=setTimeout(()=>{let d=new v({code:I.API_CALL_TIMEOUT,message:`checkPendingPromise ${t}() timeout ${o}s`});(this.log||this._log||R).warn(d),i===2?n(d):i===1&&s()},o*1e3);this._checkPendingPromiseSet||(this._checkPendingPromiseSet=new Set),this._checkPendingPromiseSet.add(a),e.apply(this,r).then(s,n).finally(()=>{clearTimeout(a),this._checkPendingPromiseSet&&a&&this._checkPendingPromiseSet.delete(a)})})})}function pf(){return Y((o,i)=>function(...e){return this._checkPendingPromiseSet&&(this._checkPendingPromiseSet.forEach(t=>clearTimeout(t)),this._checkPendingPromiseSet.clear()),o.apply(this,e)})}var ki=class ki extends no{constructor(e,t,r){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:r,room:e});this.room=e;this.user=t;c(this,"tinyId");c(this,"isRemote",!0);c(this,"jitterBufferDelay",0);c(this,"availableState");c(this,"remotePublishState");c(this,"_triggerCheckDecodeSubject",rt(de(this,ki.STATE_SUBSCRIBE)));c(this,"ignoreUpdatePlayingState");this.tinyId=t.tinyId,this.availableState=new j(`${t.userId}-${this.mediaType}-available`,"remote-track-available"),this.remotePublishState=new j(`${t.userId}-${this.mediaType}-remote-publish`,"remote-track-publish"),ce(Ln(de(this,j.STATECHANGED),de(this.remotePublishState,j.STATECHANGED)),Vn(()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing)),Te(d=>{this.availableState.state!==(d?j.ON:j.OFF)&&(this.availableState.state=d?j.ON:j.OFF),!(this.isRemotePublished&&this.ignoreUpdatePlayingState)&&this.updatePlayingState(d)}));let s=ce(de(this.player,he.ERROR),$t(d=>d.code===MediaError.MEDIA_ERR_DECODE)),n=ce(wn(5e3),$t(()=>this.ignoreDecodeError||!this.isSubscribed||!this.isPlayCalled||!this.stat.bytesReceived?!1:this.player.isPlaying||(this.kind===_.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)?(this.reportDecodeResult(!0),!1):!0)),a=ce(Lu(s,n),ke(de(this,j.INIT)));ce(this._triggerCheckDecodeSubject,$t(()=>!this.ignoreDecodeError),mo(a),Te(d=>{this.reportDecodeResult(!1,d)}))}setMute(e){this.isRemotePublished&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.isRemotePublished&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}checkDecodeResult(){this._triggerCheckDecodeSubject.next(!0)}waitHasMediaTrack(){return new Promise(e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)})}get ignoreDecodeError(){var t,r;return(((r=(t=this.room)==null?void 0:t.networkQuality)==null?void 0:r.downlinkNetworkQuality)||0)>3||this.player.isInAutoPlayFailedState}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===ki.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===j.ON}get isNeedPlay(){return this.isAvailable&&this.isPlayCalled}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}reportDecodeResult(e,t){var s,n;let r=this.kind===_.AUDIO;if(y[e?"addSuccessEvent":"addFailedEvent"]({key:r?504700:514702}),!r){let a=((s=this.room)==null?void 0:s.downlinkVideoCodec.toUpperCase())||"H264";y[e?"addSuccessEvent":"addFailedEvent"]({key:rs[`DECODE_${a}_RESULT`]}),e||this.log.warn(`${(n=this.room)==null?void 0:n.downlinkVideoCodec} decode failed`)}e||(y.addEnum({key:r?504701:514703,value:Zr()}),se.uploadEvent({log:`stat-decode-failed-${this.kind}-${ai()||di()}`,userId:this.room.userId}),this._log.warn(`decode failed: isPlaying: ${this.player.isPlaying} ${this.kind===_.AUDIO?`audioLevel: ${this.getAudioLevel()}`:`framesDecoded: ${this.stat.framesDecoded>0}`}`),this.emit("decode-failed",{error:t}))}updatePlayingState(e){if(this.player.isPlayCalled&&this.player.setTrack(this.playerMediaTrack),this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.isRemotePublished||!this.outMediaTrack)){this.log.info(`abort play, isSubscribed: ${this.isSubscribed} isAvailable: ${this.isRemotePublished} hasTrack: ${!!this.outMediaTrack} `);return}super.updatePlayingState(e)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.remotePublishState.state=this.isRemotePublished?j.ON:j.OFF,this.emit("remote-publish-changed",this.isRemotePublished)}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};c(ki,"STATE_SUBSCRIBE","subscribe"),D([Eo(5,1)],ki.prototype,"waitHasMediaTrack",1),D([ye(j.INIT,ki.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),S.emit(A.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),Rt(521716,!1)],ki.prototype,"subscribe",1),D([ye(ki.STATE_SUBSCRIBE,j.INIT,{sync:!0,success(){this.log.info("unsubscribed"),S.emit(A.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],ki.prototype,"unsubscribe",1);var gs=ki;var Ei=class extends gs{constructor(e,t){super(e,t,1);c(this,"volume",0);c(this,"mediaType",1);c(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.audioManager}get dbVolume(){return so.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}onPlayerError(e){this.enableDecodeFrame&&(this._log.warn("use audio decoder"),this.room.enableInsertableStreams())}get enableDecodeFrame(){var e,t;return this.manager?this.manager.decodePipeline.some(r=>r)||((t=(e=this.player.element)==null?void 0:e.error)==null?void 0:t.code)===MediaError.MEDIA_ERR_DECODE&&Td().AudioDecoder&&pi:!1}get enableDecryptFrame(){return this.manager&&!!this.manager.decodePipeline[0]}decodeFrame(e){if(!this.manager)return e;let t=e;for(let[r,s]of this.manager.decodePipeline.entries()){if(!s)continue;let n={frame:e,track:this};if(r===1&&this.isAvailable&&this.room.role==="audience"&&(n.onAudioFrameNTPTime=({ntp:a,frame:d,hasLeavingTag:l})=>{this.emit("audio-frame-with-ntp",{ntp:a,frame:d,hasLeavingTag:l})}),t=s(n),!t)return}return t}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get isRemotePublished(){return this.user.muteState.audioAvailable}};var tc=class extends Pe{constructor(e,t,r,s,n){super(e,{useDefaultProgram:!0,useFbo:!0,name:"alpha",create2d:!0,logger:t});this.setContainer=s;c(this,"initStat",{alphaStitchingType:1});c(this,"end",rt());c(this,"minSize",320);c(this,"maxSize",1280);c(this,"draggable",!1);c(this,"startDragX",0);c(this,"startDragY",0);c(this,"left",0);c(this,"top",0);c(this,"baseWidth",320);c(this,"baseRatio");c(this,"container");this.initStat=n,this.draggable=r,this.bindDragEvents(),y.addEnum({key:515700,value:1}),this.draggable&&y.addEnum({key:515700,value:11})}bindDragEvents(){let e=this.context._canvas;if(e)if(this.draggable){let t=ke(this.end);ce(de(e,"mousedown"),Fn(this.startDrag.bind(this)),Mr(()=>ce(de(window,"mousemove"),ke(de(window,"mouseup")))),t,Te(this.doDrag.bind(this))),ce(de(e,"dblclick"),t,Te(this.resetPosition.bind(this))),ce(de(e,"wheel"),t,Te(this.handleZoom.bind(this))),this.renderCanvas()}else{if(!this.container)return;this.container.style.removeProperty("left"),this.container.style.removeProperty("top"),this.end.next()}}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}startDrag(e){e.preventDefault(),e.button===0&&(this.startDragX=e.clientX-this.left,this.startDragY=e.clientY-this.top)}renderCanvas(){let{container:e}=this;e||this.setContainer(),!(!e||!this.baseRatio||!this.draggable)&&(e.style.setProperty("width",`${this.baseWidth}px`),e.style.setProperty("height",`${this.baseWidth/this.baseRatio}px`),e.style.setProperty("position","fixed"),e.style.setProperty("left",`${this.left}px`),e.style.setProperty("top",`${this.top}px`))}doDrag(e){e.preventDefault(),this.left=e.clientX-this.startDragX,this.top=e.clientY-this.startDragY,this.renderCanvas()}handleZoom(e){e.preventDefault();let t=.1,r=e.deltaY,s=this.context._canvas;s&&(this.baseWidth||(this.baseWidth=s.offsetWidth),r<0?this.baseWidth=Math.min(this.baseWidth*(1+t),this.maxSize):this.baseWidth=Math.max(this.baseWidth*(1-t),this.minSize),this.renderCanvas())}resetPosition(){this.left=0,this.top=0,this.renderCanvas()}onRatioReset(){this.renderCanvas()}draw2d(e,t,r,s,n){var m;let{ctx2d:a}=this,d=this.context._canvas;if(!a||!d)return!1;let l=super.draw2d(e,t,r,s,n),u=a.getImageData(0,0,s,n),{data:h}=u,p=!1;if(this.initStat.alphaStitchingType===1){let g=Math.floor(s/2);for(let E=0;E<n;E++)for(let C=0;C<g;C++){let P=(E*s+C)*4,re=C+g,L=(E*s+re)*4,Qe=h[L];h[L+3]=0;let N=Qe>=100;h[P+3]=N?255:0}p=super.draw2d(u,0,0,0,0,g,n),d.width=g}else if(this.initStat.alphaStitchingType===2){let g=Math.floor(n/2);for(let E=0;E<g;E++)for(let C=0;C<s;C++){let P=(E*s+C)*4,L=((E+g)*s+C)*4,Qe=h[L];h[L+3]=0;let N=Qe>=100;h[P+3]=N?255:0}p=super.draw2d(u,0,0,0,0,s,g),d.height=g}return(m=this.context.ctx)==null||m.clearRect(0,0,s,n),l&&p}close(){this.baseRatio=void 0,this.end.next(),this.end.complete()}};function vS(o){return[15,30,45,60].reduce((e,t)=>Math.abs(t-o)<Math.abs(e-o)?t:e)}var Pi=class extends gs{constructor(e,t,r=4){super(e,t,r);c(this,"mediaType",4);c(this,"source");c(this,"shouldRenderAlpha",!1);c(this,"alphaNode");c(this,"shouldBeDraggable",!0);c(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.videoManager,this.on("first-video-frame",s=>{this.room.emit("first-video-frame",s)})}isAlphaSei(e){if(this.userId!==e.userId||e.seiPayloadType!==50)return!1;let t=new Uint8Array(e.data);return t.length%3!==0||t[0]!==0||t[1]!==1?!1:t}play(e,t){return(ue(t==null?void 0:t.canvasRender)?t.canvasRender:et===17)&&!this.source&&this.useCanvasPlayer(),super.play(e,t).then(()=>{this.player.calculateStat(),S.emit("156",{track:this,player:this.player})})}updateAlphaRenderInfo(e){let t=this.isAlphaSei(e);if(t)if(!this.alphaNode)this.shouldRenderAlpha=!0,this.player.shouldRenderAlpha=!0,this.useCanvasPlayer(t[2]);else{let r=t[2];if(this.alphaNode.baseRatio&&this.alphaNode.initStat.alphaStitchingType===r)return;this.alphaNode.initStat={alphaStitchingType:r};let s=this.player.getElement();if(s){let n=s.videoWidth/s.videoHeight;n&&(this.alphaNode.baseRatio=n*(r===1?.5:2),this.alphaNode.onRatioReset())}this.player.canvas&&(this.player.canvas.id=this.generateAlphaCanvasName(r))}}generateAlphaCanvasName(e){let t="alpha",r=un[e];return`${t}_${r}_${this.userId}`}useCanvasPlayer(e){if(this.log.info(`useCanvasPlayer(), has element:${!!this.player.element}`),!this.player.element)return;let t=new Xe({frameRate:15,logger:this.log,name:this.shouldRenderAlpha&&e?this.generateAlphaCanvasName(e):this.userId});t.create({alpha:this.shouldRenderAlpha,willReadFrequently:this.shouldRenderAlpha});let r=new fo(t,{name:"remotePlayer",logger:this.log});if(this.source=t.createVideoPlayerSource(this.player),this.player.setCanvas(t._canvas),this.shouldRenderAlpha&&e){let s=()=>{!this.player.container||!this.alphaNode||(this.alphaNode.container=this.player.container,this.alphaNode.renderCanvas())},n=new tc(t,this.log,this.shouldBeDraggable,s,{alphaStitchingType:e});this.source.connect(n),n.connect(r),this.alphaNode=n}else this.source.connect(r);Ki()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,t),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let t=this.decodeFPS,r=vS(t);if(!Q(t)||t<=0){this.log.debug(`updateCanvasPlayerFPS() ignore decoder: ${t} `);return}if(r===e.frameRate){this.log.debug(`updateCanvasPlayerFPS() ignore ClosestFPS ${r} == ${e.frameRate}`);return}this.log.info(`updateCanvasPlayerFPS() decoder: ${t}, closest: ${r}, current: ${e.frameRate}`),e.frameRate=r}get decodeFPS(){var n;let{msg_video_status:e}=((n=this.room.heartbeatReport)==null?void 0:n.msg_down_stream_info.find(a=>a.msg_user_info.str_identifier===this.userId))||{},t=this.mediaType===2?7:this.isSmall?3:2;if(!e||e.length===0)return 0;let r=e.find(a=>a.uint32_video_stream_type===t);return(r==null?void 0:r.uint32_video_dec_fps)||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),S.emit("157",{track:this,player:this.player}),this.alphaNode&&this.alphaNode.close(),super.stop()}decodeFrame(e){if(!this.manager)return e;for(let t of this.manager.decodePipeline)if(t&&(e=t({frame:e,track:this}),!e))return;return e}get isBig(){return this.mediaType===4}get isSmall(){return this.mediaType===8}changeType(e){this.room.changeType(e,this.user)}get isRemotePublished(){return this.user.muteState.videoAvailable}setMirror(e){e==="publish"||e==="both"||super.setMirror(e)}setDraggable(e){this.shouldBeDraggable=e,this.alphaNode&&(this.alphaNode.draggable=e,this.alphaNode.bindDragEvents())}onDecodeDowngradeStateChanged(e){this.emit("decode-downgrade-state-changed",e)}},Ts=class extends Pi{constructor(e,t){super(e,t,2);c(this,"mediaType",2);c(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}};var Es=new Map;S.on(A.JOIN_SUCCESS,({room:o})=>{ve(o.userId,{eventId:32788})});S.on(A.LEAVE_START,({room:o})=>{ve(o.userId,{eventId:32789})});S.on(A.LOCAL_TRACK_PUBLISHED,({track:o})=>{if(o.room){let i=32769;o.mediaType===4?i=32768:o.mediaType===2&&(i=32805),ve(o.room.userId,{eventId:i})}});S.on(A.LOCAL_TRACK_UNPUBLISHED,({track:o})=>{if(o.room){let i=32771;o.mediaType===4?i=32770:o.mediaType===2&&(i=32806),ve(o.room.userId,{eventId:i})}});S.on(A.TRACK_MUTED,({track:o})=>{o.room&&(o.kind===_.AUDIO?ve(o.room.userId,{eventId:o.isRemote?32785:32772,remoteUserId:o.isRemote?o.userId:void 0}):ve(o.room.userId,{eventId:o.isRemote?32784:32773,remoteUserId:o.isRemote?o.userId:void 0}))});S.on(A.TRACK_UNMUTED,({track:o})=>{o.room&&(o.kind===_.AUDIO?ve(o.room.userId,{eventId:o.isRemote?32787:32774,remoteUserId:o.isRemote?o.userId:void 0}):ve(o.room.userId,{eventId:o.isRemote?32786:32775,remoteUserId:o.isRemote?o.userId:void 0}))});S.on(A.REMOTE_TRACK_SUBSCRIBED,({track:o})=>{o.room&&(o.mediaType===1&&ve(o.room.userId,{eventId:32777,remoteUserId:o.userId}),o.mediaType===4&&ve(o.room.userId,{eventId:32776,remoteUserId:o.userId}),o.mediaType===8&&ve(o.room.userId,{eventId:32803,remoteUserId:o.userId}))});S.on(A.REMOTE_TRACK_UNSUBSCRIBED,({track:o})=>{o.room&&(o.mediaType===1&&ve(o.room.userId,{eventId:32779,remoteUserId:o.userId}),o.mediaType===4&&ve(o.room.userId,{eventId:32778,remoteUserId:o.userId}),o.mediaType===8&&ve(o.room.userId,{eventId:32804,remoteUserId:o.userId}))});S.on(A.SWITCH_DEVICE_SUCCESS,({track:o})=>{o.room&&ve(o.room.userId,{eventId:o.kind===_.VIDEO?32780:32781})});S.on(A.LOCAL_TRACK_REPLACED,({track:o})=>{o.room&&ve(o.room.userId,{eventId:o.kind===_.VIDEO?32782:32783})});S.on(A.SIGNAL_CONNECTION_STATE_CHANGED,({room:o,prevState:i,state:e})=>{let t;switch(e){case"CONNECTED":i==="RECONNECTING"?t=32795:t=32791;break;case"DISCONNECTED":i==="RECONNECTING"?t=32796:t=32790;break;case"RECONNECTING":t=32794;break}t&&ve(o.userId,{eventId:t})});S.on(A.PEER_CONNECTION_STATE_CHANGED,({room:o,prevState:i,state:e,remoteUserId:t})=>{let r=!!t,s;switch(e){case"CONNECTED":i==="RECONNECTING"?s=r?32801:32798:s=r?32793:32792;break;case"DISCONNECTED":i==="RECONNECTING"&&(s=r?32802:32799);break;case"RECONNECTING":s=r?32800:32797;break}s&&ve(o.userId,{eventId:s,remoteUserId:t})});S.on(A.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({implementation:o,userId:i,remoteUserId:e,codec:t,isHWCodec:r,prevImplementation:s,streamType:n})=>{let a=r?1:0;s||(a=r?3:2);let d={H264:0,H265:1,VP8:2}[t.toUpperCase()],l={eventId:4004,param1:a,param2:d,streamType:n||2};e&&(l.remoteUserId=e,l.eventId=4005),ve(i,l),y.addEnum({key:e?514701:513701,value:a}),y.addEnum({key:e?514700:513700,value:d})});S.on(A.LOCAL_TRACK_RECAPTURE,({track:o,error:i})=>{if(o.userId){let e={eventId:2003,param1:0};o.kind===_.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType=o.streamType==="auxiliary"?7:2,i&&(e.param1=8)),ve(o.userId,e)}});function ve(o,i){let e=w(M({},i),{timestamp:Hi()});Es.has(o)?Es.get(o).push(e):Es.set(o,[e])}function ff(o){if(Es.has(o)){let i=Es.get(o).map(e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,uint32_param1:e.param1,uint32_param2:e.param2,uint32_video_stream_type:e.streamType}));return Es.delete(o),i}return[]}function _f(...o){return Y((i,e)=>function(...t){return DS.call(this,o,t,e,this._name),i.apply(this,t)})}function DS(o,i,e,t){try{if(Ae(o))for(let r=0;r<o.length;r++)ic.call(this,{rule:o[r],value:i[r],key:o[r].name,fnName:e,className:t});else ic.call(this,{rule:o,value:i[0],key:o.name,fnName:e,className:t})}catch(r){throw R.error(r),r}}function ic({rule:o,value:i,key:e,fnName:t,className:r}){if(T(i)){if(o.required)throw new v({code:I.INVALID_PARAMETER,message:$({key:B.INVALID_PARAMETER_REQUIRED,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(T(o.defaultValue))return;i=o.defaultValue}if(Array.isArray(o.type)){let a=!1;for(let d=0;d<o.type.length;d++)o.type[d]===null&&i===null&&(a=!0),le(o.type[d])&&i instanceof o.type[d]&&(a=!0),ie(o.type[d])&&Me(i)===o.type[d].toLowerCase()&&(a=!0);if(!a)throw new v({code:I.INVALID_PARAMETER,message:$({key:B.INVALID_PARAMETER_TYPE,data:{key:e,rule:{type:o.type.map(d=>jr(d)?wo(d):ie(d)?d:Me(d))},fnName:t,value:i},link:{className:r,fnName:t}})})}else if(!T(o.type)&&Me(i)!==o.type)throw new v({code:I.INVALID_PARAMETER,message:$({key:B.INVALID_PARAMETER_TYPE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(o.allowEmpty===!1){let a=Q(i)&&(i===0||Number.isNaN(i)),d=ie(i)&&i.trim()==="";if(a||d)throw new v({code:I.INVALID_PARAMETER,message:$({key:B.INVALID_PARAMETER_EMPTY,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})})}if(o.notLessThanZero&&Q(i)&&i<0)throw new v({code:I.INVALID_PARAMETER,message:$({key:B.CANNOT_LESS_THAN_ZERO,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(!T(o.min)&&Q(i)&&i<o.min)throw new v({code:I.INVALID_PARAMETER,message:$({key:B.INVALID_PARAMETER_MIN,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(!T(o.max)&&Q(i)&&i>o.max)throw new v({code:I.INVALID_PARAMETER,message:$({key:B.INVALID_PARAMETER_MAX,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(ie(o.instanceOf)){if(!i||i._name!==o.instanceOf)throw new v({code:I.INVALID_PARAMETER,message:$({key:B.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})})}else if(le(o.instanceOf)&&!(i instanceof o.instanceOf))throw new v({code:I.INVALID_PARAMETER,message:$({key:B.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(o.values&&!o.values.includes(i))throw new v({code:I.INVALID_PARAMETER,message:$({key:B.INVALID_PARAMETER_RANGE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});let{properties:s}=o;dt(s)&&yt(i)&&Object.keys(s).forEach(a=>{ic.call(this,{rule:s[a],value:i&&i[a],key:`${e}.${a}`,fnName:t,className:r})});let{arrayItem:n}=o;dt(n)&&Ae(i)&&i.forEach((a,d)=>{ic.call(this,{rule:n,value:a,key:`${e}[${d}]`,fnName:t,className:r})}),le(o.validate)&&o.validate.call(this,i,e,t,r,this)}var gf=Je(nt(),1);var rc=class extends gf.EventEmitter{constructor(e,t,r="userId"){super();this.mySelfId=e;this._log=t;this.key=r;c(this,"userMap",new Map);c(this,"remotePublishedUserMap",new Map)}get hasRobotUser(){return!![...this.remotePublishedUserMap.values()].find(e=>e.isRobot)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:r,tinyId:s,role:n}=e;if(this.userMap.has(t))return;let a={userId:r,tinyId:s,role:n===20?"anchor":"audience"};this.userMap.set(t,a),this.emit("1",a)}deleteUser(e,t){let r=this.userMap.get(e);if(!r)return;let s=`peer leave [${e}]`;T(t)||(s+=`:${tl[t]}`),this._log.info(s);let n=this.remotePublishedUserMap.get(e);if(n){let a=n.muteState;n.flag=0,this.emit("5",n.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:a,muteState:n.muteState,flag:0})}this.userMap.delete(e),this.emit("2",r.userId)}setUserList(e){this.userMap.forEach(t=>{e.findIndex(r=>r[this.key]===t[this.key])<0&&this.deleteUser(t[this.key],0)}),e.forEach(t=>{!this.userMap.has(t[this.key])&&t[this.key]!==this.mySelfId&&this.addUser(t)})}addRemotePublishedUser(e){this.remotePublishedUserMap.has(e[this.key])||this.remotePublishedUserMap.set(e[this.key],e)}deleteRemotePublishedUser(e){this.remotePublishedUserMap.has(e)&&this.remotePublishedUserMap.delete(e)}setRemotePublishedUserList(e){this.remotePublishedUserMap.forEach(t=>{let r=t[this.key];if(e.findIndex(s=>s[this.key]===t[this.key])<0){this._log.info(`remote [${r}] unpublish`);let s=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(r),this.emit("6",{prevMuteState:s,muteState:t.muteState,flag:0})}}),e.forEach(t=>{var u;let r=t[this.key];if(r===this.mySelfId){this.emit("7",t);return}let{flag:s,userId:n,tinyId:a}=t,d=Kt(s,n),l=(u=this.remotePublishedUserMap.get(r))==null?void 0:u.muteState;if(l){let h=this.remotePublishedUserMap.get(r);h&&h.flag!==s&&(h.flag=s,this._log.info(`remote publish updated: ${JSON.stringify(h.muteState)}`),this.emit("6",{prevMuteState:l,muteState:d,flag:s}))}else this._log.info(`remote publish. state: ${JSON.stringify(d)}`),this.addUser({userId:n,tinyId:a,role:20}),this.emit("3",t),this.emit("6",{prevMuteState:Kt(0,n),muteState:d,flag:s})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function Ih({timesInSecond:o,maxSizeInSecond:i,getSize:e}){return Y((t,r)=>{let s=new WeakMap;return S.on(A.ROOM_DESTROY,({room:n})=>s.delete(n)),function(...n){let a=s.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},s.set(this,a)),a.timestamp===0?a.timestamp=Date.now():Date.now()-a.timestamp>1e3&&(a.timestamp=Date.now(),a.callCountInSecond=0,a.totalSizeInSecond=0),e&&(a.totalSizeInSecond+=e(...n)),a.timestamp!==0&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=o||a.totalSizeInSecond>i))throw new v({code:I.INVALID_OPERATION,message:$({key:B.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=o,isSize:a.totalSizeInSecond>i,name:r,timesInSecond:o,maxSizeInSecond:i}})});a.callCountInSecond++,t.call(this,...n)}})}var MS="2025-12-18 10:33:59",Tf=!0,Ef=function(){var o;if(Tf){Tf=!1,R.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${_t}/en/index.html`),console.info(`* Changelog: ${_t}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),R.info("TRTC Web SDK Version:",He),ni||R.debug("Build Time:",MS);let i=`UA: ${navigator.userAgent}
|
|
52
|
+
} `;var _o=class extends j{constructor(e){super();c(this,"frameRate");c(this,"_canvas");c(this,"log");c(this,"hasAlpha",!1);c(this,"name");c(this,"error");this.name=e.name,this.log=e.logger.createChild({id:`vc-${this.name}`}),this.frameRate=e.frameRate}get canvas(){return this._canvas}set width(e){this._canvas&&(this._canvas.width=e)}get width(){var e;return((e=this._canvas)==null?void 0:e.width)||0}set height(e){this._canvas&&(this._canvas.height=e)}get height(){var e;return((e=this._canvas)==null?void 0:e.height)||0}setSize(e,t){this._canvas&&(this._canvas.width=e,this._canvas.height=t)}createVideoTrackSource(e,t){return new Wt(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new ps(this,e)}createVideoImageSource(e,t){return new Hn(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new $n(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}createTextSource(e,t){return new Zd(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}};c(_o,"_ids",0);var TS={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},fs=class fs extends _o{constructor(){super(...arguments);c(this,"defaultProgam");c(this,"defaultVShader");c(this,"defaultFShader");c(this,"ctx");c(this,"_canvas2d")}get canvas(){return this._canvas2d||this._canvas}create(e=!1){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${_o._ids++}`),e&&(this._canvas2d=document.createElement("canvas")),this.ctx=this._canvas.getContext("webgl2",TS),!this.ctx)throw new v({code:I.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,_S),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,gS),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new v({code:I.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})}destroy(e){let t="";return e&&(t=e.message,this.error=e,y.addFailedEvent({key:512702,error:e})),this.disconnect(),this.log.info(`video context destroy${t}`?`: ${t}`:""),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),e}set width(e){var t;(t=this.ctx)==null||t.viewport(0,0,e,this.height),super.width=e,this._canvas2d&&(this._canvas2d.width=e)}set height(e){var t;(t=this.ctx)==null||t.viewport(0,0,this.width,e),super.height=e,this._canvas2d&&(this._canvas2d.height=e)}setSize(e,t){var r;(r=this.ctx)==null||r.viewport(0,0,e,t),super.setSize(e,t),this._canvas2d&&(this._canvas2d.width=e,this._canvas2d.height=t)}createShader(e,t){let r=this.ctx,s=r.createShader(e);return r.shaderSource(s,t),r.compileShader(s),s}createProgram(e,t){let r=this.ctx,s=r.createProgram();return r.attachShader(s,e),r.attachShader(s,t),r.linkProgram(s),r.getProgramParameter(s,r.LINK_STATUS)||this.log.error(r.getProgramInfoLog(s)),s}};c(fs,"UNAVAILABLE","unavailable"),D([ye(j.INIT,"created",{sync:!0,fail(e){this.log.error("video gl context create failed",e.cause),y.addFailedEvent({key:512700,error:e.cause||e})},success(){this.log.info("video context created use webgl"),y.addSuccessEvent({key:512700})}})],fs.prototype,"create",1),D([ye("created",j.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(fs.UNAVAILABLE,e),this.removeAllListeners()}})],fs.prototype,"destroy",1);var Be=fs,Xe=class extends _o{constructor(){super(...arguments);c(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${_o._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:e.alpha,willReadFrequently:e.willReadFrequently}),!this.ctx)throw new v({code:I.VIDEO_MANAGER_ERROR,extraCode:2,message:"2d context not supported"});this._canvas.addEventListener("contextlost",()=>{this.log.error("2d context lost")}),this._canvas.addEventListener("contextrestored",()=>{this.log.warn("2d context restored")})}destroy(e){let t="";e&&(t=e.message,this.error=e,y.addFailedEvent({key:512703,error:e})),this.disconnect(),this.log.info(`video context destroy ${t?`: ${t}`:""}`),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners(),y.addSuccessEvent({key:512703})}};D([ye(j.INIT,"created",{sync:!0,fail(e){this.log.error("video 2d context create failed",e.cause),y.addFailedEvent({key:512701,error:e.cause||e})},success(){this.log.info("video context created use 2d"),y.addSuccessEvent({key:512701})}})],Xe.prototype,"create",1),D([ye("created",j.INIT,{ignoreError:!0,sync:!0})],Xe.prototype,"destroy",1);function ES(o,i,e,t,r,s=!1){s&&([e,t]=[t,e]);let n={sWidth:o,sHeight:i,dWidth:e,dHeight:t,sx:0,sy:0,dx:0,dy:0};if(o===0||i===0)return n;switch(r){case void 0:case"fill":break;case"contain":{let a=Math.min(e/o,t/i);n.dWidth=o*a,n.dHeight=i*a,n.dx=(e-n.dWidth)/2,n.dy=(t-n.dHeight)/2;break}case"cover":{let a=Math.max(e/o,t/i),d=e/a,l=t/a;n.sx=(o-d)/2,n.sy=(i-l)/2,n.sWidth=d,n.sHeight=l;break}}return n}var Eh=class{constructor(i,e){this.node=i;this.layout=e;c(this,"positionBuffer")}get x(){return this.layout.x||this.node.x}get y(){return this.layout.y||this.node.y}get width(){return this.layout.width||this.node.width}get height(){return this.layout.height||this.node.height}get right(){return this.x+this.width}get bottom(){return this.y+this.height}get fillMode(){return this.layout.fillMode}get rotation(){return this.layout.rotation}get hidden(){return!!this.layout.hidden}},_s=class extends Pe{constructor(e,t){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:t});c(this,"inputs",[]);c(this,"backgroundColor","black")}addInput(e,t){let r=0,s=this.inputs.length;for(;r<s;){let a=Math.floor((r+s)/2);if(this.inputs[a].layout.zIndex<t.zIndex)r=a+1;else if(this.inputs[a].layout.zIndex>t.zIndex)s=a;else throw new Error(`input already exists at zIndex ${t.zIndex}`)}let n=new Eh(e,t);this.inputs.splice(r,0,n)}changeInputLayout(e,t){let r=this.inputs.findIndex(g=>g.node===e);if(r<0)return;let{x:s,y:n,width:a,height:d,zIndex:l,fillMode:u,rotation:h,hidden:p}=t;if(!T(l)&&this.inputs.some(g=>g.layout.zIndex===l&&g.node!==e))throw new Error(`input already exists at zIndex ${t.zIndex}`);let m=this.inputs[r];T(s)||(m.layout.x=s),T(n)||(m.layout.y=n),T(a)||(m.layout.width=a),T(d)||(m.layout.height=d),T(h)||(m.layout.rotation=h),T(p)||(m.layout.hidden=p),u&&(m.layout.fillMode=u),!T(l)&&l!==m.layout.zIndex&&(m.layout.zIndex=l,this.inputs.sort((g,E)=>g.layout.zIndex-E.layout.zIndex))}hasInput(e){return this.inputs.some(t=>t.node===e)}hasNoInput(){return this.inputs.length===0}resize(e,t){if(!this.matchInputSize){super.resize(e,t);return}let r=this.inputs.reduce((s,n)=>n?Object.assign(s,{width:Math.max(s.width,n.right),height:Math.max(s.height,n.bottom)}):s,{width:0,height:0});super.resize(r.width,r.height),this.context instanceof Be&&this.inputs.forEach(s=>{if(s){let n=this.layout2texCoords(s);s.positionBuffer?this.changeBufferData(s.positionBuffer,n):s.positionBuffer=this.createBuffer(n)}})}connect(e,...t){return super.connect(e,...t),this.drawBackGround2d(this.backgroundColor),this.matchInputSize&&this.resize(0,0),e}removeInput(e){this.inputs=this.inputs.filter(t=>t.node!==e),this.inputs.length===0&&this.drawBackGround2d(this.backgroundColor)}render(e){let t=this.context.ctx;if(t.clearColor(0,0,0,0),this.inputs.reduce((s,n)=>n.node.requestFrame(e)||s,!1)&&t){this.useProgram(),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let s=0;s<this.inputs.length;s++){let n=this.inputs[s];n&&(n.node.useTexture(),this.draw(n.positionBuffer))}return!0}return!1}render2d(e){if(this.inputs.forEach(t=>t.node.requestFrame(e)),this.ctx2d){this.drawBackGround2d(this.backgroundColor);for(let t=0;t<this.inputs.length;t++){let r=this.inputs[t];if(r.hidden)continue;let s=ES(r.node.width,r.node.height,r.width,r.height,r.fillMode,bt(r.rotation));this.draw2d(r.node.image,r.x+s.dx,r.y+s.dy,s.dWidth,s.dHeight,s.sx,s.sy,s.sWidth,s.sHeight)}return!0}return!1}debugLayout(e,t,r,s,n=!1){this.ctx2d&&(n&&([r,s]=[s,r]),this.ctx2d.save(),this.ctx2d.strokeStyle="red",this.ctx2d.lineWidth=2,this.ctx2d.strokeRect(e,t,r,s),this.ctx2d.restore())}getInfo(){let{totalFrames:e,x:t,y:r,width:s,height:n,name:a}=this,d=Date.now(),l=(e-this.lastInfo.totalFrames)/((d-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:r,width:s,height:n,timestamp:d,fps:l,name:a},M({parent:this.inputs.filter(u=>u).map(u=>u.node.getInfo())},this.lastInfo)}removeAllInputs(){this.inputs.forEach(e=>{var t;if(e.node.disconnect(),e.positionBuffer&&this.context instanceof Be)try{(t=this.context.ctx)==null||t.deleteBuffer(e.positionBuffer)}catch(r){}})}close(){super.close(),this.removeAllInputs()}};var SS=[1,0,0,0,1,1,0,1],Gt=class extends Pe{constructor(e,t,r,s){super(e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"transform",logger:t});c(this,"mirror",!1);c(this,"rotation",0);if(r&&(this.mirror=r),s&&(this.rotation=s),e instanceof Be)try{this.setTexBuffer(SS)}catch(n){e.destroy(new v({code:I.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${n.message||n}`}))}}draw2d(e,t,r,s,n){if(this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height),this.ctx2d.save(),this.mirror&&(this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0)),this.rotation===90?(this.ctx2d.translate(s,0),this.ctx2d.rotate(Math.PI/2),this.ctx2d.scale(n/s,s/n)):this.rotation===180?(this.ctx2d.translate(this.width,this.height),this.ctx2d.rotate(Math.PI)):this.rotation===270&&(this.ctx2d.translate(0,n),this.ctx2d.rotate(3*Math.PI/2),this.ctx2d.scale(n/s,s/n));let a=super.draw2d(e,t,r,s,n);return this.ctx2d.restore(),a}return!1}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}resize(e,t){bt(this.rotation)&&([e,t]=[t,e]),super.resize(e,t)}};var go=class extends _i{constructor(e,t=4){super(t,pt);c(this,"inputLocalVideoTracks",new Map);c(this,"inputLocalScreenTracks",new Map);c(this,"cameraNodeMap",new Map);c(this,"screenNodeMap",new Map);c(this,"textNodeMap",new Map);c(this,"imageNodeMap",new Map);c(this,"videoNodeMap",new Map);c(this,"endedIds",new Set);c(this,"videoContext");c(this,"mixNode");c(this,"destination");c(this,"manager");c(this,"stat");c(this,"_checkId",0);c(this,"autoSetFps",!0);this.manager=e,this.log.id+="mix",this.create2dVideoContext(),this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log}),this.destination.on(Pe.RENDER,r=>{this.emit("render",r)}),this.mixNode=new _s(this.videoContext,this.log),this.mixNode.matchInputSize=!1}listenDeviceChange(){throw new Error("Method not implemented.")}enablePrintDetail(e=2e3){this._checkId=oe.run("interval",()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:e})}create2dVideoContext(){this.videoContext?this.videoContext.destroy():this.videoContext=new Xe({frameRate:15,logger:this.log,name:"mix-ctx"}),this.videoContext.create({alpha:!1})}setFps(e){this.autoSetFps=!1,this.videoContext.frameRate=e;for(let t of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])t.shouldUpdate=!1;setTimeout(()=>{var t;return(t=this.destination)==null?void 0:t.start(this.videoContext.frameRate)},500)}setFpsAuto(){var s;if(!this.autoSetFps)return;for(let n of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])n.shouldUpdate=!1;let e=null,t=0,r=!0;for(let[n,a]of this.inputLocalVideoTracks)if(a.profile.frameRate>t){if(this.endedIds.has(n)){let d=this.cameraNodeMap.get(n);d&&d.image.cancelVideoFrameCallback(d.videoCallbackId);continue}t=a.profile.frameRate,e=n}for(let[n,a]of this.inputLocalScreenTracks)if(a.profile.frameRate>t){if(this.endedIds.has(n)){let d=this.screenNodeMap.get(n);d&&d.image.cancelVideoFrameCallback(d.videoCallbackId);continue}t=a.profile.frameRate,e=n,r=!1}if(e!==null){let n=r?this.cameraNodeMap.get(e):this.screenNodeMap.get(e);n&&(n.shouldUpdate=!0,n.tryVideoFrameCallback()),this.log.info("set mix fps: ",t)}else(s=this.destination)==null||s.start(this.videoContext.frameRate),this.log.info("fallback to timer, fps: ",this.videoContext.frameRate)}setMixBackground(e){this.mixNode&&(this.mixNode.backgroundColor=e)}resizeMixCanvas(e,t){var r;(r=this.mixNode)==null||r.resize(e,t)}startMix(){return f(this,null,function*(){var e;if(!this.mixNode||!this.destination)throw new Error("can't mix without necessary conditions");this.mixNode.disconnect(),this.mixNode.connect(this.destination),Ft&&this.player.setCanvas(this.videoContext._canvas),this.setOutputMediaStreamTrack(this.destination.videoTrack),(e=this.manager)==null||e.changeInput(this)})}addCameraSource(e,t,r){if(this.inputLocalVideoTracks.has(e)||this.cameraNodeMap.has(e))throw new Error(`There is already a cameraSource with the same ID: ${e}`);let{mediaTrack:s}=t;if(!s)throw new Error("no mediaTrack, add cameraSource failed");t.recaptureMode=1,tt(this,be).add("videoInputRemoved",a=>{a.deviceId===t.deviceId&&(this.endedIds.add(e),this.setFpsAuto())}),t.on("output-media-track-changed",()=>{this.endedIds.delete(e),this.updateCameraSource(e,r,t.mediaTrack)});let n;et===16&&s instanceof CanvasCaptureMediaStreamTrack?n=this.videoContext.createVideoImageSource(s.canvas,{name:"cameraCanvasSource",logger:this.log}):n=this.videoContext.createVideoTrackSource(s,"cameraNodeSource"),n.resize(t.settings.width,t.settings.height),n.shouldUpdate=!1,this._connectMix(n,r,"cover"),this.inputLocalVideoTracks.set(e,t),this.cameraNodeMap.set(e,n),this.setFpsAuto()}addScreenSource(e,t,r){if(this.inputLocalScreenTracks.has(e)||this.screenNodeMap.has(e))throw new Error(`There is already a screenSource with the same ID: ${e}`);let{mediaTrack:s}=t;if(!s)throw new Error("no mediaTrack, add cameraSource failed");let n=this.videoContext.createVideoTrackSource(s,"screenNodeSource");n.resize(t.settings.width,t.settings.height),n.shouldUpdate=!1,this._connectMix(n,r),this.inputLocalScreenTracks.set(e,t),this.screenNodeMap.set(e,n),this.setFpsAuto()}addTextSource(e){let{id:t,content:r="",font:s,color:n,layout:a}=e;if(this.textNodeMap.has(t))throw new Error(`There is already a textSource with the same ID: ${t}`);let d=this.videoContext.createTextSource({content:r,font:s,color:n});d.resize(a.width,a.height),this._connectMix(d,a),this.textNodeMap.set(t,d)}addImageSource(e,t,r){if(this.imageNodeMap.has(e))throw new Error(`There is already a imageSource with the same ID: ${e}`);let s=this.videoContext.createVideoImageSource(t,{autoResize:!1,logger:this.log});s.resize(t.width,t.height),this._connectMix(s,r),this.imageNodeMap.set(e,s)}addVideoSource(e,t,r){if(this.videoNodeMap.has(e))throw new Error(`There is already a videoSource with the same ID: ${e}`);let s=this.videoContext.createVideoImageSource(t,{autoResize:!1,logger:this.log});s.resize(t.videoWidth,t.videoHeight),s.shouldUpdate=!1,this._connectMix(s,r),this.videoNodeMap.set(e,s)}updateCameraSource(e,t,r=null,s){let n=this.cameraNodeMap.get(e);if(n){if(r){if(et===16&&r instanceof CanvasCaptureMediaStreamTrack)if(n instanceof Wt){let l=n.output;n.close(),n=this.videoContext.createVideoImageSource(r.canvas,{name:"cameraCanvasSource",logger:this.log}),n.connect(l),this.cameraNodeMap.set(e,n)}else n.image=r.canvas;else if(n instanceof Wt)n.replaceTrack(r);else{let l=n.output;n.close(),n=this.videoContext.createVideoTrackSource(r,"cameraNodeSource"),n.connect(l),this.cameraNodeMap.set(e,n)}let{width:a,height:d}=r.getSettings();a&&d&&n.resize(a,d)}s&&n.resize(s.width,s.height),(s||r)&&this.setFpsAuto(),this._changeMixLayout(n,t)}}updateScreenSource(e,t){let r=this.screenNodeMap.get(e);r&&this._changeMixLayout(r,t)}updateTextSource(e){let{id:t,content:r,font:s,color:n,layout:a}=e,d=this.textNodeMap.get(t);d&&(T(r)||(d.content=r),T(s)||(d.font=s),T(n)||(d.color=n),d.resize(a.width,a.height),this._changeMixLayout(d,a))}updateImageSource(e,t,r){let s=this.imageNodeMap.get(e);s&&(r&&(s.image=r,s.resize(r.width,r.height)),this._changeMixLayout(s,t))}updateVideoSource(e,t,r){let s=this.videoNodeMap.get(e);if(s){if(r){let n=s.image;n instanceof HTMLVideoElement&&this.stopVideoElement(n),s.image=r,s.resize(r.videoWidth,r.videoHeight)}this._changeMixLayout(s,t)}}_connectMix(e,t,r="contain"){if(!this.mixNode)return;let{mirror:s,rotation:n}=t;e.disconnect();let a=new Gt(this.videoContext,this.log,s,n);a=e.connect(a),t.fillMode||(t.fillMode=r),a.connect(this.mixNode,t)}_changeMixLayout(e,t){if(!this.mixNode)return;let{mirror:r,rotation:s}=t,n=e.output||e;n instanceof Gt&&(T(r)||(n.mirror=r),T(s)||(n.rotation=s),n.resize(e.width,e.height)),this.mixNode.changeInputLayout(n,t)}removeCameraSource(e){let t=this.inputLocalVideoTracks.get(e);if(!t)return;t.close(),this.inputLocalVideoTracks.delete(e);let r=this.cameraNodeMap.get(e);r&&(r.output instanceof Gt&&r.output.close(),r.close(),this.cameraNodeMap.delete(e)),this.checkAfterRemove(!0)}removeScreenSource(e){let t=this.inputLocalScreenTracks.get(e);if(!t)return;t.close(),this.inputLocalScreenTracks.delete(e);let r=this.screenNodeMap.get(e);r&&(r.output instanceof Gt&&r.output.close(),r.close(),this.screenNodeMap.delete(e)),this.checkAfterRemove(!0)}removeTextSource(e){let t=this.textNodeMap.get(e);t&&(t.output instanceof Gt&&t.output.close(),t.close(),this.textNodeMap.delete(e)),this.checkAfterRemove()}removeImageSource(e){let t=this.imageNodeMap.get(e);t&&(t.output instanceof Gt&&t.output.close(),t.close(),this.imageNodeMap.delete(e)),this.checkAfterRemove()}removeVideoSource(e){let t=this.videoNodeMap.get(e);t&&(t.output instanceof Gt&&t.output.close(),t.image instanceof HTMLVideoElement&&this.stopVideoElement(t.image),t.close(),this.videoNodeMap.delete(e)),this.checkAfterRemove()}checkAfterRemove(e=!1){e&&this.setFpsAuto()}stopVideoElement(e){e.pause(),e.src="",e.srcObject=null,e.remove()}close(){var e;super.close(),oe.clearTask(this._checkId),(e=this.videoContext)==null||e.destroy(),delete this.mixNode,delete this.destination;for(let t of[...this.inputLocalVideoTracks.values(),...this.inputLocalScreenTracks.values()])t.close();this.inputLocalVideoTracks.clear(),this.inputLocalScreenTracks.clear(),this.cameraNodeMap.clear(),this.screenNodeMap.clear(),this.textNodeMap.clear(),this.imageNodeMap.clear(),we(this);for(let t of this.videoNodeMap.values())t.image instanceof HTMLVideoElement&&this.stopVideoElement(t.image);this.videoNodeMap.clear(),this.log.info("localMixVideoTrack close, stop mix")}};var Kd=an();if(typeof navigator!="undefined"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:Kd,exposeOrigin:!0,permittedOrigins:["*"]})}catch(o){}var IS=function(o){return f(this,null,function*(){let i=null,e=RS(o);R.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let t=yield navigator.mediaDevices.getDisplayMedia(e);o.systemAudio&&t.getAudioTracks().length===0&&(Zo&&$e<74||Re||ee)&&R.warn("Your browser not support capture system audio");let r=t.getVideoTracks()[0];if(r){if(o.frameRate)try{yield r.applyConstraints({frameRate:{min:o.frameRate,ideal:o.frameRate},width:o.width,height:o.height})}catch(s){R.warn(`screen applyConstraints failed: ${s}`)}o.captureElement&&(yield AS(r,o.captureElement))}if(o.audio){let s=CS(o);R.info(`getUserMedia with constraints: ${JSON.stringify(s)}`),i=yield navigator.mediaDevices.getUserMedia(s),t.addTrack(i.getAudioTracks()[0])}return t})};function AS(o,i){return f(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&le(o.cropTo))try{if(!(((e=o.getCaptureHandle())==null?void 0:e.handle)===Kd))return;let r=yield CropTarget.fromElement(i);yield o.cropTo(r)}catch(t){R.warn(`cropTo target failed ${t}`)}})}function CS(o){let i={echoCancellation:o.echoCancellation,autoGainControl:o.autoGainControl,noiseSuppression:o.noiseSuppression,sampleRate:o.sampleRate,channelCount:o.channelCount};return T(o.microphoneId)||(i.deviceId=o.microphoneId),{audio:i,video:!1}}function RS(o){let i={preferCurrentTab:o.preferDisplaySurface==="current-tab"||!!o.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:Re?{max:o.width}:{ideal:o.width,max:o.width},height:Re?{max:o.height}:{ideal:o.height,max:o.height},frameRate:o.frameRate,displaySurface:o.preferDisplaySurface||"monitor"};if(i.video=e,o.systemAudio){let{echoCancellation:t=!0,noiseSuppression:r=!1,autoGainControl:s=!1}=o;i.audio={echoCancellation:t,noiseSuppression:r,autoGainControl:s,sampleRate:48e3}}return i}var mf=IS;var Pt=class extends je{constructor(e){super(e,2);c(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600});c(this,"objectFit","contain");c(this,"isScreen",!0);this._log.id=`s-${this._log.id}`}get isShareCurrentTab(){var e,t;try{return Kd===((t=(e=this.mediaTrack)==null?void 0:e.getCaptureHandle())==null?void 0:t.handle)}catch(r){return}}capture(u){return f(this,arguments,function*({systemAudio:e=!1,autoGainControl:t,echoCancellation:r,noiseSuppression:s,audioTrack:n,videoTrack:a,captureElement:d,preferDisplaySurface:l}){try{let h;return a||n?(h=new MediaStream,a&&h.addTrack(a),n&&h.addTrack(n)):(h=yield mf({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:t,echoCancellation:r,noiseSuppression:s,captureElement:d,preferDisplaySurface:l}),this.sourceTrack=h.getVideoTracks()[0]),yield this.setInputMediaStreamTrack(h.getVideoTracks()[0]),h}catch(h){throw this.log.error(`getDisplayMedia error observed ${h}`),h instanceof v?h:new v({code:I.INITIALIZE_FAILED,name:h.name,message:h.message})}})}switchDevice(e){return f(this,null,function*(){throw new Error("Method not implemented.")})}};D([Ct(function(e){this.setContentHint(e.contentHint||"detail")})],Pt.prototype,"capture",1);var To=class extends kt{constructor(i){super(i),this._log.id=`s-${this._log.id}`,this.isScreen=!0}addAudioProcessor(i,e,t){this.pipeline.silentNode.setNode(t),this.pipeline.mixNode.setNode(e),this.pipeline.aec.setNode(i),this.enableTrackAEC(!1)}removeAudioProcessor(i){this.pipeline.aec.node===i&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode(),this.enableTrackAEC(!0))}};var yS='registerProcessor("dumper",class extends AudioWorkletProcessor{constructor(e){super(),this.sourceSampleRate=e.processorOptions.sourceSampleRate||48e3,this.targetSampleRate=e.processorOptions.targetSampleRate||48e3,this.port.onmessage=e=>{this.port2=e.data.port}}process(e){return(this.port2||this.port).postMessage(this.resampleAll(e,this.sourceSampleRate,this.targetSampleRate)),!0}resampleAll(r,s,a){if(s===a)return r;var o=[];for(let t=0;t<r.length;t++){o[t]=[];for(let e=0;e<r[t].length;e++)o[t][e]=this.resample(r[t][e],s,a)}return o}resample(t,e,r){if(e===r)return t;var s=Math.round(t.length*(this.targetSampleRate/this.sourceSampleRate)),a=new Float32Array(s),o=(t.length-1)/(s-1);a[0]=t[0];for(let e=1;e<s-1;e++){var l=e*o,p=Math.floor(l),h=Math.ceil(l);a[e]=t[p]+(t[h]-t[p])*(l-p)}return a[s-1]=t[t.length-1],a}});',Sh;function Wn(o,i=48e3,e=1,t){return f(this,null,function*(){let r=Ee("dump");Sh||(Sh=tr(r,URL.createObjectURL(new Blob([yS],{type:"application/javascript"})))),yield Sh;let s=r.sampleRate,n=new AudioWorkletNode(r,"dumper",{numberOfInputs:o.length,numberOfOutputs:0,processorOptions:{sourceSampleRate:s,targetSampleRate:i}});return n.channelCountMode="explicit",n.channelCount=e,t&&n.port.postMessage({port:t},[t]),o.forEach((a,d)=>a.connect(n,0,d)),new ReadableStream({start(a){n.port.onmessage=d=>{a.enqueue(d.data)}},cancel(){o.forEach(a=>a.disconnect(n)),n.port.close()}})})}var ec=class extends yd{constructor(e){super();this.room=e;c(this,"_localAudioTrack");c(this,"_localScreenAudioTrack");c(this,"log");c(this,"denoiser");c(this,"voiceChanger");c(this,"mixChangedDebounce");c(this,"audioProcessor");c(this,"encodePipeline",[]);c(this,"decodePipeline",[]);c(this,"getPCMAbortCtrlMap",new Map);c(this,"audioFrameEventConfigMap",new Map);c(this,"audioReferenceMap",new Map);c(this,"isLocalAudioNeedAudioProcess",!1);c(this,"isScreenAudioNeedAudioProcess",!1);this.log=R.createLogger({parent:e==null?void 0:e.getLogger(),id:"am",userId:e==null?void 0:e.userId,sdkAppId:e==null?void 0:e.sdkAppId}),this.installEvent()}get localAudioTrack(){return this._localAudioTrack}get _localAudioPipline(){var e;return(e=this._localAudioTrack)==null?void 0:e.pipeline}get _localScreenAudioPipeline(){var e;return(e=this._localScreenAudioTrack)==null?void 0:e.pipeline}dump(e){var u,h;if(!this._localAudioTrack)return;let t=[],r=[];(u=this._localAudioPipline)!=null&&u.source.node&&(t.push(this._localAudioPipline.source.node),r.push("mic")),(h=this._localAudioPipline)!=null&&h.denoiser.node&&(t.push(this._localAudioPipline.denoiser.node),r.push("mic-processed")),this.mixWeight>1&&(t.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),r.push("mix")),this.log.info(`dump audio track ${r}, duration: ${e}`);let s=new AbortController,n=[],a=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),s.abort("timeout")},e*1e3),d=()=>{for(let p=0;p<r.length;p++){let m=URL.createObjectURL(new Blob(n[p])),g=document.createElement("a");g.href=m,g.download=`${r[p]}.pcm`,g.style.display="none",document.body.appendChild(g),g.click(),URL.revokeObjectURL(m),g.remove()}clearTimeout(a),s.abort("download")},l=Wn(t).then(p=>p.pipeTo(new WritableStream({write(m){m.forEach((g,E)=>n[E]=n[E]?n[E].concat(g[0]):[g[0]])}}),s).catch(m=>d));return{then:l.then.bind(l),download:d}}getPCM(e,t){var P,re,L;if(typeof WritableStream=="undefined"){this.log.warn("getPCM failed: browser not support WritableStream");return}let{enable:r,sampleRate:s=48e3,channelCount:n=1,port:a}=(t===""?this.audioFrameEventConfigMap.get(""):this.audioFrameEventConfigMap.get(t)||this.audioFrameEventConfigMap.get("*"))||{};if(!r)return;this.log.info(`getPCM ${t||"local"}`);let d=Math.floor(s*.04),l=new Float32Array(d),u=new Float32Array(d),h,p,m=0,g=new AbortController,E=t===""?(P=this._localAudioTrack)==null?void 0:P.mediaTrack:(L=(re=this.room)==null?void 0:re.remotePublishedUserMap.get(t))==null?void 0:L.remoteAudioTrack.mediaTrack;if(!E){this.log.info(`getPCM failed: ${t||"local"} has no audio track`);return}let C=Ee().createMediaStreamSource(new MediaStream([E]));return Wn([C],s,n,a).then(Qe=>Qe.pipeTo(new WritableStream({write(N){N[0][0]&&(m+N[0][0].length>d?(l.set(N[0][0].subarray(0,d-m),m),h=N[0][0].subarray(d-m),N[0][1]&&(u.set(N[0][1].subarray(0,d-m),m),p=N[0][1].subarray(d-m)),m+=d-m):(h&&(l.set(h,m),m+=h.length,h=void 0),p&&(u.set(p,m),p=void 0),l.set(N[0][0],m),N[0][1]&&u.set(N[0][1],m),m+=N[0][0].length),m>=d&&(m=0,e({userId:t,sampleRate:s,channelCount:n,data:n===1?l:[l,u]}),l=new Float32Array(d),u=new Float32Array(d)))}}),g).catch(N=>this.log.warn(`stop getPCM reason:${N}`))),g}get hasScreenAudioTrack(){return!T(this._localScreenAudioTrack)}get hasAudioTrack(){return!T(this._localAudioTrack)}changeInput(e){var t,r;if(e instanceof To)return this._localScreenAudioTrack=e,this.isScreenAudioNeedAudioProcess&&((t=this.audioProcessor)!=null&&t.screenAudioWorkletNode)&&(e.addAudioProcessor(this.audioProcessor.screenAudioWorkletNode,this.audioProcessor.mixNode,this.audioProcessor.silentNode),this.audioReferenceMap.forEach((s,n)=>{e.mixAudioReference(s,n)})),e.pipeline.connect(),this.mixOnChange();if(e instanceof kt)return this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),this.isLocalAudioNeedAudioProcess&&((r=this.audioProcessor)!=null&&r.localAudioWorkletNode)&&(e.addAudioProcessor(this.audioProcessor.localAudioWorkletNode,this.audioProcessor.mixNode,this.audioProcessor.silentNode),this.audioReferenceMap.forEach((s,n)=>{e.mixAudioReference(s,n)})),e.pipeline.connect(),this.mixOnChange();if(e instanceof Ei)return e.setOutputMediaStreamTrack(e.mediaTrack)}mixAudioReference(e,t){var r;(r=this._localAudioTrack)==null||r.mixAudioReference(e,t)}unMixAudioReference(e){var t;(t=this._localAudioTrack)==null||t.unMixAudioReference(e)}setAudioReferenceVolume(e,t){var r;(r=this._localAudioTrack)==null||r.setAudioReferenceVolume(e,t)}mixOnChange(){return this.mixChangedDebounce||(this.mixChangedDebounce=Promise.resolve().then(()=>{var e,t;return delete this.mixChangedDebounce,Promise.all([(e=this._localAudioTrack)==null?void 0:e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),(t=this._localScreenAudioTrack)==null?void 0:t.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)])})),this.mixChangedDebounce}removeInput(e){e instanceof To?delete this._localScreenAudioTrack:e instanceof kt?delete this._localAudioTrack:e instanceof Ei}addDenoiser(e){var t;this.denoiser=e,(t=this._localAudioTrack)==null||t.addDenoiser(e)}addAudioProcessor(e,t,r,s){var n;this.audioProcessor={localAudioWorkletNode:r,mixNode:e,silentNode:t,screenAudioWorkletNode:s},this.isLocalAudioNeedAudioProcess&&this._localAudioTrack&&r&&(this._localAudioTrack.addAudioProcessor(r,e,t),this.audioReferenceMap.forEach((a,d)=>{var l;(l=this._localAudioTrack)==null||l.mixAudioReference(a,d)})),this.isScreenAudioNeedAudioProcess&&this._localScreenAudioTrack&&s&&((n=this._localScreenAudioTrack)==null||n.addAudioProcessor(s,e,t),this.audioReferenceMap.forEach((a,d)=>{var l;(l=this._localScreenAudioTrack)==null||l.mixAudioReference(a,d)}))}removeDenoiser(e){var t;return delete this.denoiser,(t=this._localAudioTrack)==null?void 0:t.removeDenoiser(e)}addVoiceChanger(e,t){var r;this.voiceChanger=[e,t],(r=this._localAudioTrack)==null||r.pipeline.voiceChanger.setNode(e,t)}removeVoiceChanger(){var e;delete this.voiceChanger,(e=this._localAudioTrack)==null||e.pipeline.voiceChanger.deleteNode()}removeAudioProcessor(e,t){var r,s;delete this.audioProcessor,(r=this._localAudioTrack)==null||r.removeAudioProcessor(e),(s=this._localScreenAudioTrack)==null||s.removeAudioProcessor(t)}destroy(){this.close(),this.audioReferenceMap.clear(),this.getPCMAbortCtrlMap.forEach(e=>e==null?void 0:e.abort("destroy")),this.getPCMAbortCtrlMap.clear(),this.audioFrameEventConfigMap.clear(),this.uninstallEvent()}addEncodeProcessor({processor:e,type:t}){var r;this.encodePipeline.includes(e)||(this.encodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}addDecodeProcessor({processor:e,type:t}){var r;this.decodePipeline.includes(e)||(this.decodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}handleLocalTrackStarted({room:e,userId:t}){var s;if(e!==this.room||this.getPCMAbortCtrlMap.get(t))return;let r=this.getPCM(n=>{var a;(a=this.room)==null||a.emit("audio-frame",n)},"");this.getPCMAbortCtrlMap.set(t,r),this.getPCMAbortCtrlMap.get(t)&&((s=this._localAudioTrack)==null||s.on("input-media-track-changed",()=>{let n=this.getPCMAbortCtrlMap.get(t);n&&(n.abort("inputMediaTrackChanged"),n=this.getPCM(a=>{var d;(d=this.room)==null||d.emit("audio-frame",a)},""),this.getPCMAbortCtrlMap.set(t,n))}))}handleLocalTrackStopped({room:e,userId:t}){if(e!==this.room)return;let r=this.getPCMAbortCtrlMap.get(t);r&&(r.abort("stopLocalAudio"),this.getPCMAbortCtrlMap.delete(t))}handleRemoteTrackStarted({room:e,userId:t}){if(e===this.room&&!this.getPCMAbortCtrlMap.get(t)){let r=this.room.audioManager.getPCM(s=>{var n;(n=this.room)==null||n.emit("audio-frame",s)},t);this.getPCMAbortCtrlMap.set(t,r)}}handleRemoteTrackStopped({room:e,userId:t}){if(e!==this.room)return;let r=this.getPCMAbortCtrlMap.get(t);r&&(r.abort("stopRemoteAudio"),this.getPCMAbortCtrlMap.delete(t))}installEvent(){S.on("113",this.handleLocalTrackStarted,this),S.on("114",this.handleLocalTrackStopped,this),S.on("115",this.handleRemoteTrackStarted,this),S.on("116",this.handleRemoteTrackStopped,this)}uninstallEvent(){S.off("113",this.handleLocalTrackStarted),S.off("114",this.handleLocalTrackStopped),S.off("115",this.handleRemoteTrackStarted),S.off("116",this.handleRemoteTrackStopped)}updateAudioReference({type:e,audioReference:t,refId:r,volume:s}){if(e==="add"){if(this.audioReferenceMap.get(r)||!t||(this.audioReferenceMap.set(r,t),!this.audioProcessor))return;this.mixAudioReference(t,r)}else if(e==="remove")this.audioReferenceMap.get(r)&&(this.audioReferenceMap.delete(r),this.unMixAudioReference(r));else if(e==="updateVolume"){if(!this.audioProcessor||T(s))return;this.setAudioReferenceVolume(r,s)}}};function Eo(o=30,i=2){return Y((e,t)=>function(...r){return new Promise((s,n)=>{let a=setTimeout(()=>{let d=new v({code:I.API_CALL_TIMEOUT,message:`checkPendingPromise ${t}() timeout ${o}s`});(this.log||this._log||R).warn(d),i===2?n(d):i===1&&s()},o*1e3);this._checkPendingPromiseSet||(this._checkPendingPromiseSet=new Set),this._checkPendingPromiseSet.add(a),e.apply(this,r).then(s,n).finally(()=>{clearTimeout(a),this._checkPendingPromiseSet&&a&&this._checkPendingPromiseSet.delete(a)})})})}function pf(){return Y((o,i)=>function(...e){return this._checkPendingPromiseSet&&(this._checkPendingPromiseSet.forEach(t=>clearTimeout(t)),this._checkPendingPromiseSet.clear()),o.apply(this,e)})}var ki=class ki extends no{constructor(e,t,r){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:r,room:e});this.room=e;this.user=t;c(this,"tinyId");c(this,"isRemote",!0);c(this,"jitterBufferDelay",0);c(this,"availableState");c(this,"remotePublishState");c(this,"_triggerCheckDecodeSubject",rt(de(this,ki.STATE_SUBSCRIBE)));c(this,"ignoreUpdatePlayingState");this.tinyId=t.tinyId,this.availableState=new j(`${t.userId}-${this.mediaType}-available`,"remote-track-available"),this.remotePublishState=new j(`${t.userId}-${this.mediaType}-remote-publish`,"remote-track-publish"),ce(Ln(de(this,j.STATECHANGED),de(this.remotePublishState,j.STATECHANGED)),Vn(()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing)),Te(d=>{this.availableState.state!==(d?j.ON:j.OFF)&&(this.availableState.state=d?j.ON:j.OFF),!(this.isRemotePublished&&this.ignoreUpdatePlayingState)&&this.updatePlayingState(d)}));let s=ce(de(this.player,he.ERROR),$t(d=>d.code===MediaError.MEDIA_ERR_DECODE)),n=ce(wn(5e3),$t(()=>this.ignoreDecodeError||!this.isSubscribed||!this.isPlayCalled||!this.stat.bytesReceived?!1:this.player.isPlaying||(this.kind===_.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)?(this.reportDecodeResult(!0),!1):!0)),a=ce(Lu(s,n),ke(de(this,j.INIT)));ce(this._triggerCheckDecodeSubject,$t(()=>!this.ignoreDecodeError),mo(a),Te(d=>{this.reportDecodeResult(!1,d)}))}setMute(e){this.isRemotePublished&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.isRemotePublished&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}checkDecodeResult(){this._triggerCheckDecodeSubject.next(!0)}waitHasMediaTrack(){return new Promise(e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)})}get ignoreDecodeError(){var t,r;return(((r=(t=this.room)==null?void 0:t.networkQuality)==null?void 0:r.downlinkNetworkQuality)||0)>3||this.player.isInAutoPlayFailedState}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===ki.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===j.ON}get isNeedPlay(){return this.isAvailable&&this.isPlayCalled}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}reportDecodeResult(e,t){var s,n;let r=this.kind===_.AUDIO;if(y[e?"addSuccessEvent":"addFailedEvent"]({key:r?504700:514702}),!r){let a=((s=this.room)==null?void 0:s.downlinkVideoCodec.toUpperCase())||"H264";y[e?"addSuccessEvent":"addFailedEvent"]({key:rs[`DECODE_${a}_RESULT`]}),e||this.log.warn(`${(n=this.room)==null?void 0:n.downlinkVideoCodec} decode failed`)}e||(y.addEnum({key:r?504701:514703,value:Zr()}),se.uploadEvent({log:`stat-decode-failed-${this.kind}-${ai()||di()}`,userId:this.room.userId}),this._log.warn(`decode failed: isPlaying: ${this.player.isPlaying} ${this.kind===_.AUDIO?`audioLevel: ${this.getAudioLevel()}`:`framesDecoded: ${this.stat.framesDecoded>0}`}`),this.emit("decode-failed",{error:t}))}updatePlayingState(e){if(this.player.isPlayCalled&&this.player.setTrack(this.playerMediaTrack),this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.isRemotePublished||!this.outMediaTrack)){this.log.info(`abort play, isSubscribed: ${this.isSubscribed} isAvailable: ${this.isRemotePublished} hasTrack: ${!!this.outMediaTrack} `);return}super.updatePlayingState(e)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.remotePublishState.state=this.isRemotePublished?j.ON:j.OFF,this.emit("remote-publish-changed",this.isRemotePublished)}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};c(ki,"STATE_SUBSCRIBE","subscribe"),D([Eo(5,1)],ki.prototype,"waitHasMediaTrack",1),D([ye(j.INIT,ki.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),S.emit(A.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),Rt(521716,!1)],ki.prototype,"subscribe",1),D([ye(ki.STATE_SUBSCRIBE,j.INIT,{sync:!0,success(){this.log.info("unsubscribed"),S.emit(A.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],ki.prototype,"unsubscribe",1);var gs=ki;var Ei=class extends gs{constructor(e,t){super(e,t,1);c(this,"volume",0);c(this,"mediaType",1);c(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.audioManager}get dbVolume(){return so.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}onPlayerError(e){this.enableDecodeFrame&&(this._log.warn("use audio decoder"),this.room.enableInsertableStreams())}get enableDecodeFrame(){var e,t;return this.manager?this.manager.decodePipeline.some(r=>r)||((t=(e=this.player.element)==null?void 0:e.error)==null?void 0:t.code)===MediaError.MEDIA_ERR_DECODE&&Td().AudioDecoder&&pi:!1}get enableDecryptFrame(){return this.manager&&!!this.manager.decodePipeline[0]}decodeFrame(e){if(!this.manager)return e;let t=e;for(let[r,s]of this.manager.decodePipeline.entries()){if(!s)continue;let n={frame:e,track:this};if(r===1&&this.isAvailable&&this.room.role==="audience"&&(n.onAudioFrameNTPTime=({ntp:a,frame:d,hasLeavingTag:l})=>{this.emit("audio-frame-with-ntp",{ntp:a,frame:d,hasLeavingTag:l})}),t=s(n),!t)return}return t}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get isRemotePublished(){return this.user.muteState.audioAvailable}};var tc=class extends Pe{constructor(e,t,r,s,n){super(e,{useDefaultProgram:!0,useFbo:!0,name:"alpha",create2d:!0,logger:t});this.setContainer=s;c(this,"initStat",{alphaStitchingType:1});c(this,"end",rt());c(this,"minSize",320);c(this,"maxSize",1280);c(this,"draggable",!1);c(this,"startDragX",0);c(this,"startDragY",0);c(this,"left",0);c(this,"top",0);c(this,"baseWidth",320);c(this,"baseRatio");c(this,"container");this.initStat=n,this.draggable=r,this.bindDragEvents(),y.addEnum({key:515700,value:1}),this.draggable&&y.addEnum({key:515700,value:11})}bindDragEvents(){let e=this.context._canvas;if(e)if(this.draggable){let t=ke(this.end);ce(de(e,"mousedown"),Fn(this.startDrag.bind(this)),Mr(()=>ce(de(window,"mousemove"),ke(de(window,"mouseup")))),t,Te(this.doDrag.bind(this))),ce(de(e,"dblclick"),t,Te(this.resetPosition.bind(this))),ce(de(e,"wheel"),t,Te(this.handleZoom.bind(this))),this.renderCanvas()}else{if(!this.container)return;this.container.style.removeProperty("left"),this.container.style.removeProperty("top"),this.end.next()}}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}startDrag(e){e.preventDefault(),e.button===0&&(this.startDragX=e.clientX-this.left,this.startDragY=e.clientY-this.top)}renderCanvas(){let{container:e}=this;e||this.setContainer(),!(!e||!this.baseRatio||!this.draggable)&&(e.style.setProperty("width",`${this.baseWidth}px`),e.style.setProperty("height",`${this.baseWidth/this.baseRatio}px`),e.style.setProperty("position","fixed"),e.style.setProperty("left",`${this.left}px`),e.style.setProperty("top",`${this.top}px`))}doDrag(e){e.preventDefault(),this.left=e.clientX-this.startDragX,this.top=e.clientY-this.startDragY,this.renderCanvas()}handleZoom(e){e.preventDefault();let t=.1,r=e.deltaY,s=this.context._canvas;s&&(this.baseWidth||(this.baseWidth=s.offsetWidth),r<0?this.baseWidth=Math.min(this.baseWidth*(1+t),this.maxSize):this.baseWidth=Math.max(this.baseWidth*(1-t),this.minSize),this.renderCanvas())}resetPosition(){this.left=0,this.top=0,this.renderCanvas()}onRatioReset(){this.renderCanvas()}draw2d(e,t,r,s,n){var m;let{ctx2d:a}=this,d=this.context._canvas;if(!a||!d)return!1;let l=super.draw2d(e,t,r,s,n),u=a.getImageData(0,0,s,n),{data:h}=u,p=!1;if(this.initStat.alphaStitchingType===1){let g=Math.floor(s/2);for(let E=0;E<n;E++)for(let C=0;C<g;C++){let P=(E*s+C)*4,re=C+g,L=(E*s+re)*4,Qe=h[L];h[L+3]=0;let N=Qe>=100;h[P+3]=N?255:0}p=super.draw2d(u,0,0,0,0,g,n),d.width=g}else if(this.initStat.alphaStitchingType===2){let g=Math.floor(n/2);for(let E=0;E<g;E++)for(let C=0;C<s;C++){let P=(E*s+C)*4,L=((E+g)*s+C)*4,Qe=h[L];h[L+3]=0;let N=Qe>=100;h[P+3]=N?255:0}p=super.draw2d(u,0,0,0,0,s,g),d.height=g}return(m=this.context.ctx)==null||m.clearRect(0,0,s,n),l&&p}close(){this.baseRatio=void 0,this.end.next(),this.end.complete()}};function vS(o){return[15,30,45,60].reduce((e,t)=>Math.abs(t-o)<Math.abs(e-o)?t:e)}var Pi=class extends gs{constructor(e,t,r=4){super(e,t,r);c(this,"mediaType",4);c(this,"source");c(this,"shouldRenderAlpha",!1);c(this,"alphaNode");c(this,"shouldBeDraggable",!0);c(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.videoManager,this.on("first-video-frame",s=>{this.room.emit("first-video-frame",s)})}isAlphaSei(e){if(this.userId!==e.userId||e.seiPayloadType!==50)return!1;let t=new Uint8Array(e.data);return t.length%3!==0||t[0]!==0||t[1]!==1?!1:t}play(e,t){return(ue(t==null?void 0:t.canvasRender)?t.canvasRender:et===17)&&!this.source&&this.useCanvasPlayer(),super.play(e,t).then(()=>{this.player.calculateStat(),S.emit("156",{track:this,player:this.player})})}updateAlphaRenderInfo(e){let t=this.isAlphaSei(e);if(t)if(!this.alphaNode)this.shouldRenderAlpha=!0,this.player.shouldRenderAlpha=!0,this.useCanvasPlayer(t[2]);else{let r=t[2];if(this.alphaNode.baseRatio&&this.alphaNode.initStat.alphaStitchingType===r)return;this.alphaNode.initStat={alphaStitchingType:r};let s=this.player.getElement();if(s){let n=s.videoWidth/s.videoHeight;n&&(this.alphaNode.baseRatio=n*(r===1?.5:2),this.alphaNode.onRatioReset())}this.player.canvas&&(this.player.canvas.id=this.generateAlphaCanvasName(r))}}generateAlphaCanvasName(e){let t="alpha",r=un[e];return`${t}_${r}_${this.userId}`}useCanvasPlayer(e){if(this.log.info(`useCanvasPlayer(), has element:${!!this.player.element}`),!this.player.element)return;let t=new Xe({frameRate:15,logger:this.log,name:this.shouldRenderAlpha&&e?this.generateAlphaCanvasName(e):this.userId});t.create({alpha:this.shouldRenderAlpha,willReadFrequently:this.shouldRenderAlpha});let r=new fo(t,{name:"remotePlayer",logger:this.log});if(this.source=t.createVideoPlayerSource(this.player),this.player.setCanvas(t._canvas),this.shouldRenderAlpha&&e){let s=()=>{!this.player.container||!this.alphaNode||(this.alphaNode.container=this.player.container,this.alphaNode.renderCanvas())},n=new tc(t,this.log,this.shouldBeDraggable,s,{alphaStitchingType:e});this.source.connect(n),n.connect(r),this.alphaNode=n}else this.source.connect(r);Ki()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,t),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let t=this.decodeFPS,r=vS(t);if(!Q(t)||t<=0){this.log.debug(`updateCanvasPlayerFPS() ignore decoder: ${t} `);return}if(r===e.frameRate){this.log.debug(`updateCanvasPlayerFPS() ignore ClosestFPS ${r} == ${e.frameRate}`);return}this.log.info(`updateCanvasPlayerFPS() decoder: ${t}, closest: ${r}, current: ${e.frameRate}`),e.frameRate=r}get decodeFPS(){var n;let{msg_video_status:e}=((n=this.room.heartbeatReport)==null?void 0:n.msg_down_stream_info.find(a=>a.msg_user_info.str_identifier===this.userId))||{},t=this.mediaType===2?7:this.isSmall?3:2;if(!e||e.length===0)return 0;let r=e.find(a=>a.uint32_video_stream_type===t);return(r==null?void 0:r.uint32_video_dec_fps)||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),S.emit("157",{track:this,player:this.player}),this.alphaNode&&this.alphaNode.close(),super.stop()}decodeFrame(e){if(!this.manager)return e;for(let t of this.manager.decodePipeline)if(t&&(e=t({frame:e,track:this}),!e))return;return e}get isBig(){return this.mediaType===4}get isSmall(){return this.mediaType===8}changeType(e){this.room.changeType(e,this.user)}get isRemotePublished(){return this.user.muteState.videoAvailable}setMirror(e){e==="publish"||e==="both"||super.setMirror(e)}setDraggable(e){this.shouldBeDraggable=e,this.alphaNode&&(this.alphaNode.draggable=e,this.alphaNode.bindDragEvents())}onDecodeDowngradeStateChanged(e){this.emit("decode-downgrade-state-changed",e)}},Ts=class extends Pi{constructor(e,t){super(e,t,2);c(this,"mediaType",2);c(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}};var Es=new Map;S.on(A.JOIN_SUCCESS,({room:o})=>{ve(o.userId,{eventId:32788})});S.on(A.LEAVE_START,({room:o})=>{ve(o.userId,{eventId:32789})});S.on(A.LOCAL_TRACK_PUBLISHED,({track:o})=>{if(o.room){let i=32769;o.mediaType===4?i=32768:o.mediaType===2&&(i=32805),ve(o.room.userId,{eventId:i})}});S.on(A.LOCAL_TRACK_UNPUBLISHED,({track:o})=>{if(o.room){let i=32771;o.mediaType===4?i=32770:o.mediaType===2&&(i=32806),ve(o.room.userId,{eventId:i})}});S.on(A.TRACK_MUTED,({track:o})=>{o.room&&(o.kind===_.AUDIO?ve(o.room.userId,{eventId:o.isRemote?32785:32772,remoteUserId:o.isRemote?o.userId:void 0}):ve(o.room.userId,{eventId:o.isRemote?32784:32773,remoteUserId:o.isRemote?o.userId:void 0}))});S.on(A.TRACK_UNMUTED,({track:o})=>{o.room&&(o.kind===_.AUDIO?ve(o.room.userId,{eventId:o.isRemote?32787:32774,remoteUserId:o.isRemote?o.userId:void 0}):ve(o.room.userId,{eventId:o.isRemote?32786:32775,remoteUserId:o.isRemote?o.userId:void 0}))});S.on(A.REMOTE_TRACK_SUBSCRIBED,({track:o})=>{o.room&&(o.mediaType===1&&ve(o.room.userId,{eventId:32777,remoteUserId:o.userId}),o.mediaType===4&&ve(o.room.userId,{eventId:32776,remoteUserId:o.userId}),o.mediaType===8&&ve(o.room.userId,{eventId:32803,remoteUserId:o.userId}))});S.on(A.REMOTE_TRACK_UNSUBSCRIBED,({track:o})=>{o.room&&(o.mediaType===1&&ve(o.room.userId,{eventId:32779,remoteUserId:o.userId}),o.mediaType===4&&ve(o.room.userId,{eventId:32778,remoteUserId:o.userId}),o.mediaType===8&&ve(o.room.userId,{eventId:32804,remoteUserId:o.userId}))});S.on(A.SWITCH_DEVICE_SUCCESS,({track:o})=>{o.room&&ve(o.room.userId,{eventId:o.kind===_.VIDEO?32780:32781})});S.on(A.LOCAL_TRACK_REPLACED,({track:o})=>{o.room&&ve(o.room.userId,{eventId:o.kind===_.VIDEO?32782:32783})});S.on(A.SIGNAL_CONNECTION_STATE_CHANGED,({room:o,prevState:i,state:e})=>{let t;switch(e){case"CONNECTED":i==="RECONNECTING"?t=32795:t=32791;break;case"DISCONNECTED":i==="RECONNECTING"?t=32796:t=32790;break;case"RECONNECTING":t=32794;break}t&&ve(o.userId,{eventId:t})});S.on(A.PEER_CONNECTION_STATE_CHANGED,({room:o,prevState:i,state:e,remoteUserId:t})=>{let r=!!t,s;switch(e){case"CONNECTED":i==="RECONNECTING"?s=r?32801:32798:s=r?32793:32792;break;case"DISCONNECTED":i==="RECONNECTING"&&(s=r?32802:32799);break;case"RECONNECTING":s=r?32800:32797;break}s&&ve(o.userId,{eventId:s,remoteUserId:t})});S.on(A.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({implementation:o,userId:i,remoteUserId:e,codec:t,isHWCodec:r,prevImplementation:s,streamType:n})=>{let a=r?1:0;s||(a=r?3:2);let d={H264:0,H265:1,VP8:2}[t.toUpperCase()],l={eventId:4004,param1:a,param2:d,streamType:n||2};e&&(l.remoteUserId=e,l.eventId=4005),ve(i,l),y.addEnum({key:e?514701:513701,value:a}),y.addEnum({key:e?514700:513700,value:d})});S.on(A.LOCAL_TRACK_RECAPTURE,({track:o,error:i})=>{if(o.userId){let e={eventId:2003,param1:0};o.kind===_.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType=o.streamType==="auxiliary"?7:2,i&&(e.param1=8)),ve(o.userId,e)}});function ve(o,i){let e=w(M({},i),{timestamp:Hi()});Es.has(o)?Es.get(o).push(e):Es.set(o,[e])}function ff(o){if(Es.has(o)){let i=Es.get(o).map(e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,uint32_param1:e.param1,uint32_param2:e.param2,uint32_video_stream_type:e.streamType}));return Es.delete(o),i}return[]}function _f(...o){return Y((i,e)=>function(...t){return DS.call(this,o,t,e,this._name),i.apply(this,t)})}function DS(o,i,e,t){try{if(Ae(o))for(let r=0;r<o.length;r++)ic.call(this,{rule:o[r],value:i[r],key:o[r].name,fnName:e,className:t});else ic.call(this,{rule:o,value:i[0],key:o.name,fnName:e,className:t})}catch(r){throw R.error(r),r}}function ic({rule:o,value:i,key:e,fnName:t,className:r}){if(T(i)){if(o.required)throw new v({code:I.INVALID_PARAMETER,message:$({key:B.INVALID_PARAMETER_REQUIRED,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(T(o.defaultValue))return;i=o.defaultValue}if(Array.isArray(o.type)){let a=!1;for(let d=0;d<o.type.length;d++)o.type[d]===null&&i===null&&(a=!0),le(o.type[d])&&i instanceof o.type[d]&&(a=!0),ie(o.type[d])&&Me(i)===o.type[d].toLowerCase()&&(a=!0);if(!a)throw new v({code:I.INVALID_PARAMETER,message:$({key:B.INVALID_PARAMETER_TYPE,data:{key:e,rule:{type:o.type.map(d=>jr(d)?wo(d):ie(d)?d:Me(d))},fnName:t,value:i},link:{className:r,fnName:t}})})}else if(!T(o.type)&&Me(i)!==o.type)throw new v({code:I.INVALID_PARAMETER,message:$({key:B.INVALID_PARAMETER_TYPE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(o.allowEmpty===!1){let a=Q(i)&&(i===0||Number.isNaN(i)),d=ie(i)&&i.trim()==="";if(a||d)throw new v({code:I.INVALID_PARAMETER,message:$({key:B.INVALID_PARAMETER_EMPTY,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})})}if(o.notLessThanZero&&Q(i)&&i<0)throw new v({code:I.INVALID_PARAMETER,message:$({key:B.CANNOT_LESS_THAN_ZERO,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(!T(o.min)&&Q(i)&&i<o.min)throw new v({code:I.INVALID_PARAMETER,message:$({key:B.INVALID_PARAMETER_MIN,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(!T(o.max)&&Q(i)&&i>o.max)throw new v({code:I.INVALID_PARAMETER,message:$({key:B.INVALID_PARAMETER_MAX,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(ie(o.instanceOf)){if(!i||i._name!==o.instanceOf)throw new v({code:I.INVALID_PARAMETER,message:$({key:B.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})})}else if(le(o.instanceOf)&&!(i instanceof o.instanceOf))throw new v({code:I.INVALID_PARAMETER,message:$({key:B.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(o.values&&!o.values.includes(i))throw new v({code:I.INVALID_PARAMETER,message:$({key:B.INVALID_PARAMETER_RANGE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});let{properties:s}=o;dt(s)&&yt(i)&&Object.keys(s).forEach(a=>{ic.call(this,{rule:s[a],value:i&&i[a],key:`${e}.${a}`,fnName:t,className:r})});let{arrayItem:n}=o;dt(n)&&Ae(i)&&i.forEach((a,d)=>{ic.call(this,{rule:n,value:a,key:`${e}[${d}]`,fnName:t,className:r})}),le(o.validate)&&o.validate.call(this,i,e,t,r,this)}var gf=Je(nt(),1);var rc=class extends gf.EventEmitter{constructor(e,t,r="userId"){super();this.mySelfId=e;this._log=t;this.key=r;c(this,"userMap",new Map);c(this,"remotePublishedUserMap",new Map)}get hasRobotUser(){return!![...this.remotePublishedUserMap.values()].find(e=>e.isRobot)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:r,tinyId:s,role:n}=e;if(this.userMap.has(t))return;let a={userId:r,tinyId:s,role:n===20?"anchor":"audience"};this.userMap.set(t,a),this.emit("1",a)}deleteUser(e,t){let r=this.userMap.get(e);if(!r)return;let s=`peer leave [${e}]`;T(t)||(s+=`:${tl[t]}`),this._log.info(s);let n=this.remotePublishedUserMap.get(e);if(n){let a=n.muteState;n.flag=0,this.emit("5",n.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:a,muteState:n.muteState,flag:0})}this.userMap.delete(e),this.emit("2",r.userId)}setUserList(e){this.userMap.forEach(t=>{e.findIndex(r=>r[this.key]===t[this.key])<0&&this.deleteUser(t[this.key],0)}),e.forEach(t=>{!this.userMap.has(t[this.key])&&t[this.key]!==this.mySelfId&&this.addUser(t)})}addRemotePublishedUser(e){this.remotePublishedUserMap.has(e[this.key])||this.remotePublishedUserMap.set(e[this.key],e)}deleteRemotePublishedUser(e){this.remotePublishedUserMap.has(e)&&this.remotePublishedUserMap.delete(e)}setRemotePublishedUserList(e){this.remotePublishedUserMap.forEach(t=>{let r=t[this.key];if(e.findIndex(s=>s[this.key]===t[this.key])<0){this._log.info(`remote [${r}] unpublish`);let s=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(r),this.emit("6",{prevMuteState:s,muteState:t.muteState,flag:0})}}),e.forEach(t=>{var u;let r=t[this.key];if(r===this.mySelfId){this.emit("7",t);return}let{flag:s,userId:n,tinyId:a}=t,d=Kt(s,n),l=(u=this.remotePublishedUserMap.get(r))==null?void 0:u.muteState;if(l){let h=this.remotePublishedUserMap.get(r);h&&h.flag!==s&&(h.flag=s,this._log.info(`remote publish updated: ${JSON.stringify(h.muteState)}`),this.emit("6",{prevMuteState:l,muteState:d,flag:s}))}else this._log.info(`remote publish. state: ${JSON.stringify(d)}`),this.addUser({userId:n,tinyId:a,role:20}),this.emit("3",t),this.emit("6",{prevMuteState:Kt(0,n),muteState:d,flag:s})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function Ih({timesInSecond:o,maxSizeInSecond:i,getSize:e}){return Y((t,r)=>{let s=new WeakMap;return S.on(A.ROOM_DESTROY,({room:n})=>s.delete(n)),function(...n){let a=s.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},s.set(this,a)),a.timestamp===0?a.timestamp=Date.now():Date.now()-a.timestamp>1e3&&(a.timestamp=Date.now(),a.callCountInSecond=0,a.totalSizeInSecond=0),e&&(a.totalSizeInSecond+=e(...n)),a.timestamp!==0&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=o||a.totalSizeInSecond>i))throw new v({code:I.INVALID_OPERATION,message:$({key:B.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=o,isSize:a.totalSizeInSecond>i,name:r,timesInSecond:o,maxSizeInSecond:i}})});a.callCountInSecond++,t.call(this,...n)}})}var MS="2025-12-18 14:33:09",Tf=!0,Ef=function(){var o;if(Tf){Tf=!1,R.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${_t}/en/index.html`),console.info(`* Changelog: ${_t}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),R.info("TRTC Web SDK Version:",He),ni||R.debug("Build Time:",MS);let i=`UA: ${navigator.userAgent}
|
|
53
53
|
CPU core: ${navigator.hardwareConcurrency}, GPU: ${Ml()}`,e=navigator.deviceMemory;e&&(i+=`, minRAM: ${e}GB`),R.info(i),R.info(`URL: ${location.href}${((o=self.frameElement)==null?void 0:o.tagName)==="IFRAME"?" in iframe":""}`),Yr().then(t=>{t&&R.info(ti)})}};var So={SCENE_LIVE:"live",SCENE_RTC:"rtc",ROLE_ANCHOR:"anchor",ROLE_AUDIENCE:"audience",STREAM_TYPE_MAIN:"main",STREAM_TYPE_SUB:"sub",AUDIO_PROFILE_STANDARD:"standard",AUDIO_PROFILE_STANDARD_STEREO:"standard-stereo",AUDIO_PROFILE_HIGH:"high",AUDIO_PROFILE_HIGH_STEREO:"high-stereo",QOS_PREFERENCE_SMOOTH:"smooth",QOS_PREFERENCE_CLEAR:"clear",SPEAKER:"Speakerphone",HEADSET:"Headset earpiece"};var W={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},Lt=(b=>(b[b.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",b[b.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",b[b.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",b[b.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",b[b.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",b[b.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",b[b.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",b[b.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",b[b.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",b[b.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",b[b.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",b[b.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",b[b.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",b[b.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",b[b.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",b[b.INVALID_ROOM_ID_REQUIRED=5015]="INVALID_ROOM_ID_REQUIRED",b[b.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",b[b.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",b[b.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",b[b.INVALID_ROOM_ID_TYPE_MISMATCH=5019]="INVALID_ROOM_ID_TYPE_MISMATCH",b[b.INVALID_ROOM_ID_DUPLICATE=5020]="INVALID_ROOM_ID_DUPLICATE",b[b.INVALID_OPERATION=5100]="INVALID_OPERATION",b[b.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",b[b.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",b[b.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",b[b.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",b[b.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",b[b.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",b[b.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",b[b.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",b[b.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",b[b.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",b[b.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",b[b.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",b[b.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",b[b.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",b[b.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",b[b.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",b[b.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",b[b.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",b[b.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",b[b.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",b[b.DEVICE_ERROR=5300]="DEVICE_ERROR",b[b.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",b[b.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",b[b.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",b[b.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",b[b.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",b[b.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",b[b.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",b[b.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",b[b.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",b[b.NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX=5310]="NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX",b[b.SERVER_ERROR=5400]="SERVER_ERROR",b[b.NEED_TO_BUY=5401]="NEED_TO_BUY",b[b.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",b[b.OPERATION_FAILED=5500]="OPERATION_FAILED",b[b.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",b[b.REJOIN_FAILED=5502]="REJOIN_FAILED",b[b.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",b[b.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",b[b.VIDEO_ENCODE_FAILED=5505]="VIDEO_ENCODE_FAILED",b[b.AUDIO_ENCODE_FAILED=5506]="AUDIO_ENCODE_FAILED",b[b.VIDEO_DECODE_FAILED=5507]="VIDEO_DECODE_FAILED",b[b.AUDIO_DECODE_FAILED=5508]="AUDIO_DECODE_FAILED",b[b.OPERATION_ABORT=5998]="OPERATION_ABORT",b[b.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",b))(Lt||{});function If({code:o,params:i,enableDocLink:e=!1}){let t="",r,s=Lt[o];try{r=Sf[s]}catch(n){r=Sf.UNKNOWN_ERROR}return le(r)?t=r(i):ie(r)&&(t=r),i.fnName&&!t.includes(i.fnName)&&(t[t.length-1]!=="."&&(t+="."),t+=` thrown from ${i.fnName}()`),e&&(t+=" doc:"),t}var Sf=w(M({},qe),{INVALID_PARAMETER({fnName:o}){return`the parameters of the '${o}' you called does not meet the requirements, please check the API documentation.`},INVALID_PARAMETER_REQUIRED({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' is a required param when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_TYPE({key:o,rule:i,fnName:e,value:t}){let r=`${o||i.name}`,s="";return Array.isArray(i.type)?s=i.type.join("|"):s=i.type,`'${r}' must be type of ${s} when calling ${e}(), received type: ${Me(t)}.`},INVALID_PARAMETER_EMPTY({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' cannot be '${t}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:o,rule:i,fnName:e,value:t}){let r=`${o||i.name}`,s=`${i.instanceOf.name||i.instanceOf}`;return`'${r}' must be instanceof ${s} when calling ${e}(), received type: ${Me(t)}.`},INVALID_PARAMETER_RANGE({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' must be one of ${i.values.join("|")} when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_LESS_THAN_ZERO({key:o,rule:i,fnName:e}){return`'${o||i.name}' cannot be less than 0 when calling ${e}().`},INVALID_PARAMETER_MIN({key:o,rule:i,value:e}){return`the min value of ${o||i.name} is ${i.min}, received: ${e}.`},INVALID_PARAMETER_MAX({key:o,rule:i,value:e}){return`the max value of ${o||i.name} is ${i.max}, received: ${e}.`},INVALID_ELEMENT_ID({key:o,fnName:i}){return`'${o}' is not found in the document object when calling ${i}().`},INVALID_ELEMENT_ID_TYPE({key:o,fnName:i,type:e}){return`the element corresponding to '${o}' must be instanceof HTMLElement when calling ${i}(), received: ${e}.`},INVALID_STREAM_ID({key:o}){return`'${o}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},INVALID_ROOM_ID_STRING({key:o}){return`'${o}' must be a valid string.`},INVALID_ROOM_ID_INTEGER({key:o}){return`'${o}' must be an integer between [1, 4294967294].`},INVALID_ROOM_ID_INTEGER_STRING({key:o}){return`'${o}' must be an integer but go a string, use 'parseInt' to convert it or use 'strRoomId' instead.`},INVALID_ROOM_ID_REQUIRED(){return"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required."},INVALID_ROOM_ID_TYPE_MISMATCH({key:o}){return`The type of target roomId must match the current roomId. Current room is using '${o}', but received '${o==="strRoomId"?"roomId":"strRoomId"}'.`},INVALID_ROOM_ID_DUPLICATE({key:o}){return`the target '${o}' must not be the same as the current '${o}'.`},INVALID_STREAM_TYPE:({fnName:o})=>`'streamType' is required when 'userId' is not '*', calling ${o}()`,INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION({fnName:o}){return`the API '${o}' you called does not meet the requirements, please check the API documentation.`},INVALID_OPERATION_NOT_JOINED({fnName:o}){return`cannot ${o} because you are not enter room yet.`},INVALID_OPERATION_REMOTE_USER_NOT_EXIST({fnName:o,value:i}){return`cannot ${o} because remote user(userId: ${i.userId}) does not publishing stream.`},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST({fnName:o,value:i}){return`cannot ${o} because remote user(userId: ${i.userId}) does not publishing ${i.streamType} video.`},INVALID_OPERATION_REPEAT_CALL({fnName:o}){return`you are already ${o}(), cannot repeated call '${o}'.`},INVALID_OPERATION_NEED_VIDEO({fnName:o}){return`cannot call '${o}' because the camera is not turned on.`},INVALID_OPERATION_NEED_AUDIO({fnName:o}){return`cannot call '${o}' because the microphone or screen share is not turned on.`},INVALID_BUFFER_EMPTY:({key:o})=>`the buffer size of paramerter '${o}' cannot be empty`,INVALID_BUFFER_OVERSIZE:()=>"buffer size is over 1000 Bytes",INVALID_ROLE_AUDIENCE:()=>"role: 'audience' cannot call this api.",INVALID_NOT_ENABLE_SEI:()=>"you need to enable SEI in TRTC.create({ enableSEI: true })",INVALID_NEED_CALL_PUBLISHED:({fnName:o})=>`you need to call ${o}() after publish stream.`,ENV_NOT_SUPPORTED({fnName:o}){return`the current browser does not support the capability of the function '${o}' you are calling, please check the API documentation.`},NOT_SUPPORTED_WEBRTC:"the current browser does not support WebRTC capability, please check the SDK documentation.",NOT_SUPPORTED_H264_ENCODE:"this browser does not support H264 encode.",NOT_SUPPORTED_H264_DECODE:"this browser does not support H264 decode.",NOT_SUPPORTED_SCREEN_SHARE:"this browser does not support screen share, please check the browser version.",NOT_SUPPORTED_SMALL_VIDEO:"this browser does not support small video, please check the browser version.",NOT_SUPPORTED_SEI:"this browser does not support SEI, please check the browser version.",NOT_SUPPORTED_WEBGL:"this browser does not support WebGL, please check the browser version.",NOT_SUPPORTED_CHROME_VERSION({fnName:o}){return`cannot call ${o} because the browser version is too low, please upgrade to the latest version`},DEVICE_ERROR({fnName:o,error:i}){return`'${o}' got device exception${i?`, error: ${i.toString()}.`:"."}`},DEVICE_NOT_FOUND_ERROR({fnName:o,deviceType:i=Io(o),error:e}){return`NotFoundError, no ${i} detected, please check your device and the configuration on '${o}'${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_ALLOWED_ERROR({fnName:o,deviceType:i=Io(o),error:e}){return`NotAllowedError, you have disabled ${i} access, please allow the current application to use the ${i}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_READABLE_ERROR({fnName:o,deviceType:i=Io(o),error:e}){return`NotReadableError, the ${i} maybe in use by another APP, please check if the device is pre-occupied by another APP.`},DEVICE_OVERCONSTRAINED_ERROR({fnName:o,deviceType:i=Io(o),error:e}){return`OverconstrainedError, the device ID is incorrect, please check whether the device ID passed in is correct${e?`, error: ${e.toString()}.`:"."}`},DEVICE_INVALID_STATE_ERROR({fnName:o,deviceType:i=Io(o),error:e}){return`InvalidStateError, after the user clicks and interacts with the page, turn on the ${i}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_SECURITY_ERROR({fnName:o,deviceType:i=Io(o),error:e}){return`SecurityError, check whether the system security policy restricts the use of the ${i}, and it is recommended to turn on the ${i} after the user interacts with the page${e?`, error: ${e.toString()}.`:"."}`},DEVICE_ABORT_ERROR({fnName:o,deviceType:i=Io(o),error:e}){return`AbortError, an unknown exception in the system makes the device unusable, recommended to change the device or browser and re-check whether the device is normal${e?` error: ${e.toString()}.`:"."}`},CAMERA_RECOVER_FAILED({error:o}){return`camera recover capture failed ${(o==null?void 0:o.name)||""}: ${(o==null?void 0:o.originMessage)||(o==null?void 0:o.message)}`},MICROPHONE_RECOVER_FAILED({error:o}){return`microphone recover capture failed ${(o==null?void 0:o.name)||""}: ${(o==null?void 0:o.originMessage)||(o==null?void 0:o.message)}`},OPERATION_FAILED({fnName:o,error:i}){return`'${o}' failed, reason: ${i==null?void 0:i.toString()}`},FIREWALL_RESTRICTION(){return"media connection failure due to firewall restrictions, please try to change your network."},EVENT_HANDLER_ERROR({eventName:o}){return`an error was caught on trtc.on('${o}', handler), please check your code on 'handler'.`},VIDEO_CONTEXT_ERROR({reason:o,error:i}){return`video context error ${o} ${(i==null?void 0:i.name)||""} ${(i==null?void 0:i.message)||""}`},SERVER_ERROR({fnName:o,error:i}){return`'${o}' got server error: ${i==null?void 0:i.toString()}, please check the SDK documentation.`},NEED_TO_BUY({value:o,url:i}){return`You need to buy packages for ${o}. Refer to: ${i}`},ACCOUNT_NO_MONEY:({fnParams:o})=>`your TRTC account run out of credit, please recharge.${o.sdkAppId?` SDKAppId: ${o.sdkAppId}`:""}`,OPERATION_ABORT({fnName:o}){return`'${o}' abort`},UNKNOWN_ERROR({fnName:o,error:i}){return`'${o}' throw unknown exception${i?`, error: ${i.toString()}.`:"."}`}});function Io(o){if(!o)return"camera";let i=o.toLowerCase();return i.includes("screen")?"screen share":i.includes("audio")?"microphone":"camera"}var Ah=class o extends Error{constructor({code:e,extraCode:t,message:r="",messageParams:s,fnName:n="",originError:a,data:d}){var u;let l;r?l=r:l=If({code:e===W.SERVER_ERROR?e:t||e,params:M({fnName:n,error:a},s)});super(l);c(this,"name","RtcError");c(this,"code");c(this,"extraCode");c(this,"functionName");c(this,"message");c(this,"data");c(this,"handler");c(this,"originError");this.name=Lt[e],this.code=e,this.extraCode=t,this.functionName=n,this.originError=a,this.message=l,this.data=d,this.extraCode===5302&&((u=this.originError)!=null&&u.message.includes("system"))&&(this.handler=()=>{let h={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},p={startLocalVideo:"webcam",startLocalAudio:"microphone"},m=document.createElement("a");Qr?m.href=`ms-settings:privacy-${p[this.functionName]}`:si&&(m.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${h[this.functionName]}`),m.href.length>0&&m.click()})}static convertFrom(e,t,r){let s=e;if(e instanceof v){let{stack:n}=e,a={code:W.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case I.INVALID_PARAMETER:a.code=W.INVALID_PARAMETER,a.message=e.message;break;case I.INVALID_OPERATION:a.code=W.INVALID_OPERATION;break;case I.NOT_SUPPORTED:case I.NOT_SUPPORTED_H264:a.code=W.ENV_NOT_SUPPORTED,e.getCode()===I.NOT_SUPPORTED_H264&&(a.extraCode=e.message.includes(qe.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case I.JOIN_ROOM_FAILED:a.messageParams={fnParams:r};case I.SERVER_TIMEOUT:case I.SWITCH_ROLE_FAILED:case I.SWITCH_ROOM_FAILED:a.code=W.SERVER_ERROR,a.extraCode=e.getExtraCode();break;case I.API_CALL_ABORTED:a.code=W.OPERATION_ABORT;break;case I.DEVICE_NOT_FOUND:case I.DEVICE_AUTO_RECOVER_FAILED:case I.INITIALIZE_FAILED:a.code=5300,e.name&&(a.extraCode=OS(e.name));break;case I.VIDEO_ENCODE_FAILED:a.extraCode=5505;case I.AUDIO_ENCODE_FAILED:a.extraCode=5506,a.code=W.OPERATION_FAILED;break;case I.UNKNOWN:break;default:a.code=W.OPERATION_FAILED}s=new o(a),n&&(s.stack+=n.substr(n.indexOf(`
|
|
54
54
|
`)))}else{if(e instanceof o)return e;s=new o({code:W.UNKNOWN_ERROR,fnName:t,originError:e})}return s}};function OS(o){let i;switch(o){case"NotFoundError":i=5301;break;case"NotAllowedError":i=5302;break;case"NotReadableError":i=5303;break;case"OverconstrainedError":i=5304;break;case"InvalidStateError":i=5305;break;case"SecurityError":i=5306;break;case"AbortError":i=5307;break;default:i=5300}return i}var F=Ah;function Li(o){return o==="sub"?"auxiliary":o==="auxiliary"?"sub":"main"}function Gn(o){return o===So.QOS_PREFERENCE_CLEAR?"detail":o===So.QOS_PREFERENCE_SMOOTH?"motion":""}function Ss(o,i){let e=i?jc:pr;return Tl(o)?M(M({},e),o):zt[o]?zt[o]:e}var Af={type:"object",properties:{cameraId:{type:"string"},useFrontCamera:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:["string","boolean"],values:[!0,!1,"view","publish","both"]},small:{type:["string","object","boolean"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack}}},Cf={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}}},Is={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(o,i,e){if(ie(o)&&!document.getElementById(o))throw new F({code:W.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:i}})}},Rf={name:"userId",required:!0,type:"string"},yf={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{type:["string","object"],properties:{bitrate:{type:"number"},channelCount:{type:"number"}}},echoCancellation:{values:[!0,!1,"remote-only","all"]},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function As(o,i){if(!o)throw new F({code:W.INVALID_OPERATION,extraCode:5101,fnName:i})}function bf(o,i,e){if(!o)throw new F({code:W.INVALID_OPERATION,extraCode:5102,fnName:i,messageParams:{value:e}})}function Nf(o,i,e){if(!(/^[1-9]\d*$/.test(String(o))&&o<4294967295))throw new F({code:W.INVALID_PARAMETER,extraCode:5013,fnName:i,messageParams:{key:e}})}function vf(o,i,e){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(o))throw new F({code:W.INVALID_PARAMETER,extraCode:5012,fnName:i,messageParams:{key:e}})}var FL={type:"number",notLessThanZero:!0},kS=(o,i)=>o.width*o.height>=i.width*i.height&&o.frameRate>=i.frameRate&&o.bitrate>=i.bitrate;function Df(o){var t;if(!((t=o==null?void 0:o.option)!=null&&t.small))return;if(!gd()){R.warn("small stream is not supported"),delete o.option.small;return}let i=Ss(o.option.profile),e=Ss(o.option.small,!0);if(!kS(i,e)){R.warn(`small stream profile must be less than big stream profile. Big: ${JSON.stringify(i)}, Small: ${JSON.stringify(e)}`),delete o.option.small;return}}var PS={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(o,i,e){if(this._room.isJoined)throw new F({code:W.INVALID_OPERATION,extraCode:5104,fnName:e});if(o.roomId){if(ie(o.roomId))throw new F({code:W.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:i}});Nf(o.roomId,e,i)}else if(o.strRoomId)vf(o.strRoomId,e,i);else throw new F({code:W.INVALID_PARAMETER,extraCode:5015,fnName:e})},properties:{sdkAppId:{required:!0,type:"number",allowEmpty:!1},userId:{required:!0,type:"string",allowEmpty:!1},userSig:{required:!0,type:"string",allowEmpty:!1},scene:{type:"string",values:["live","rtc"]},role:{type:"string",values:["audience","anchor"]},roomId:{type:["string","number"]},strRoomId:{type:"string"},proxy:{type:["object","string"],properties:{websocketProxy:{type:"string"},turnServer:{type:["object","array"],properties:{url:{required:!0,type:"string"},username:{type:"string"},credential:{type:"string"},credentialType:{type:"string",values:["password"]}}},loggerProxy:{type:"string"},webtransportProxy:{type:"string"}}},enableAutoPlayDialog:{type:"boolean"},userDefineRecordId:{type:"string"},latencyLevel:{type:"number"},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:Is,mute:{type:["boolean","string"]},publish:{type:"boolean"},capture:{required:!1,type:"boolean"},option:Af},validate(o){var i,e;if(!((i=o==null?void 0:o.option)!=null&&i.videoTrack)&&Zi())throw new F({code:W.ENV_NOT_SUPPORTED,extraCode:5201});(e=o==null?void 0:o.option)!=null&&e.small&&Df(o)}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:w(M({},Is),{required:!1}),publish:{type:"boolean"},capture:{required:!1,type:"boolean"},mute:{type:["boolean","string"]},option:Af},validate(o){var i;(i=o==null?void 0:o.option)!=null&&i.small&&Df(o)}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:yf},validate(o){var i;if(!((i=o==null?void 0:o.option)!=null&&i.audioTrack)&&Zi())throw new F({code:W.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:yf}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:Is,publish:{type:"boolean"},option:Cf},validate(o,i,e,t,r){var s;if(!((s=o==null?void 0:o.option)!=null&&s.videoTrack)){if(Zi())throw new F({code:W.ENV_NOT_SUPPORTED,extraCode:5201});if(!fn())throw new F({code:W.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:Is,publish:{type:"boolean"},option:Cf}},muteRemoteAudio:[Rf,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[Rf,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:Is,userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(o,i,e){As(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(o.userId);if(bf(!!t,e,o),t&&(o.streamType==="main"&&!t.muteState.videoAvailable||o.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new F({code:W.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:o}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:w(M({},Is),{required:!1}),userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(o,i,e){As(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(o.userId);if(bf(!!t,e,o),t&&(o.streamType==="main"&&!t.muteState.videoAvailable||o.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new F({code:W.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:o}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(o,i,e){if(o.userId!=="*"&&T(o.streamType))throw new F({code:W.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(o,i,e){As(this._room.isJoining||this._room.isJoined,e)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(o,i,e,t){if(!Tn)throw new F({code:W.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new F({code:W.INVALID_OPERATION,fnName:e,extraCode:5108});if(o.byteLength>1e3)throw new F({code:W.INVALID_PARAMETER,extraCode:5018,fnName:e});if(o.byteLength===0)throw new F({code:W.INVALID_PARAMETER,extraCode:5017,messageParams:{key:i},fnName:e});As(this._room.isJoined,e)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(o,i,e){if(!o&&!this._room.isMainStreamPublished||o&&!this._room.isAuxStreamPublished)throw new F({code:W.INVALID_OPERATION,extraCode:5109,messageParams:{key:i},fnName:e})}}}}],sendCustomMessage:{name:"message",required:!0,type:"object",properties:{cmdId:{type:"number",required:!0,min:1,max:10},data:{instanceOf:ArrayBuffer,required:!0,validate(o,i,e,t){if(o.byteLength>1e3)throw new F({code:W.INVALID_PARAMETER,extraCode:5018,fnName:e});if(o.byteLength===0)throw new F({code:W.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:i}})}}},validate(o,i,e){if(As(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new F({code:W.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:i}})}},switchRoom:{name:"switchRoomConfig",type:"object",required:!0,validate(o,i,e){if(As(this._room.isJoined,e),this._room.useStringRoomId&&o.strRoomId===this._room.roomId||!this._room.useStringRoomId&&o.roomId===Number(this._room.roomId))throw new F({code:W.INVALID_PARAMETER,extraCode:5020,fnName:e,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(o.roomId&&this._room.useStringRoomId||!o.roomId&&o.strRoomId&&!this._room.useStringRoomId)throw new F({code:W.INVALID_PARAMETER,extraCode:5019,fnName:e,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(o.roomId)Nf(o.roomId,e,i);else if(o.strRoomId)vf(o.strRoomId,e,i);else throw new F({code:W.INVALID_PARAMETER,extraCode:5015,fnName:e})},properties:{roomId:{type:"number"},strRoomId:{type:"string"},privateMapKey:{type:"string"},userSig:{type:"string",required:!0},autoSubscribeCount:{type:"number",min:0,max:50}}}},Ge={TRTC:PS};var lt=class extends Error{};function LS(o,i){let e=Gr(o);for(let t=0;t<i.length;t++)ei(e[t],i[t]);return e}function xS(o){this._resolve=Promise.resolve(o)}function wS(o){this._reject=Promise.reject(o)}var Pr=class Pr{constructor(i,e){this.instance=i;this.group=e;c(this,"started",!1);c(this,"ops",[]);c(this,"startSame",()=>!0);c(this,"mergeUpdate",LS);let t=Pr.instances.get(i);t?t.set(e,this):Pr.instances.set(i,new Map([[e,this]]))}static get(i,e){if(!e)return;let t=Pr.instances.get(i);return t&&t.get(e)||new Pr(i,e)}static gets(i,e){let t=Pr.instances.get(i),r=[];return t&&t.forEach((s,n)=>{e.test(n)&&r.push(s)}),r}action(i,e,t){let r=a=>{var d;return i===0?this.started=!0:i===3&&(this.started=!1),this.ops.shift(),(d=this.currentOp)==null||d.action(),a},s=a=>{var d,l;throw this.ops.shift(),i===0&&((d=this.currentOp)==null?void 0:d.type)===2&&this.ops.shift().reject(new lt("start failed")),(l=this.currentOp)==null||l.action(),a},n={type:i,action:()=>e(...n.args).then(r,s),args:t,resolve:xS,reject:wS};try{switch(this.state){case 1:if(i===0)throw new lt("already started");break;case 4:if(i===2)throw new lt("not started");break;default:return this.cacheOp(n)}}catch(a){return Promise.reject(a)}return this.ops.push(n),n.promise=e(...n.args).then(r,s)}cacheOp(i){if(this.ops.length===1)switch(this.state){case 0:case 2:if(i.type===0)throw new lt("already start");break;case 3:switch(i.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(i.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let t=new lt("keep stop");if(this.ops.slice(1).forEach(r=>r.reject(t)),this.ops=this.ops.slice(0,1),this.state===3)return this.currentOp.promise}break;case 2:switch(this.lastOpType){case 2:return this.lastOp.args=this.mergeUpdate(this.lastOp.args,i.args),this.lastOp.promise;case 3:throw new 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,i.args))throw this.ops.pop().reject(new lt("keep start")),new lt("already start")}}i.promise=new Promise((t,r)=>{i._resolve?i._resolve.then(t):i.resolve=t,i._reject?i._reject.catch(r):i.reject=r});let{action:e}=i;return i.action=()=>e().then(i.resolve,i.reject),this.ops.push(i),i.promise}get lastOp(){return this.ops[this.ops.length-1]}get lastOpType(){return this.lastOp.type}get currentOp(){return this.ops[0]}get state(){return this.currentOp?this.currentOp.type:this.started?1:4}};c(Pr,"instances",new WeakMap);var nr=Pr;var sc=new WeakMap,nc=(o,i)=>{if(i instanceof lt){let{stack:e}=i;i=new F({code:W.OPERATION_ABORT,message:`${o} abort: ${i.message}`,fnName:o}),e&&(i.stack+=e.substr(e.indexOf(`
|
|
55
55
|
`)))}throw i};function Lr(o,i){return Y((e,t)=>function(...r){let s=nr.get(this,typeof o=="string"?o:o.call(this,...r));return s?(i&&(s.startSame=i.bind(this)),s.action(0,e.bind(this),r).catch(nc.bind(null,t))):e.apply(this,r)})}function Ao(o,i){let{merge:e,debounce:t}=i||{};return Y((r,s)=>function(...n){let a=nr.get(this,typeof o=="string"?o:o.call(this,...n));if(!a)return r.apply(this,n);if(e&&(a.mergeUpdate=e.bind(this)),t&&t.isNeedToDebounce.apply(this,n)){let{delay:d,getKey:l}=t;return new Promise((u,h)=>{var g,E;let p=(g=sc.get(this))==null?void 0:g.get(l(...n));if(p){let{timeoutId:C,resolve:P}=p;clearTimeout(C),P()}let m=setTimeout(()=>{if(a.state===3||a.state===4)return u();a.action(2,r.bind(this),n).catch(nc.bind(null,s)).then(u,h)},d);sc.has(this)?(E=sc.get(this))==null||E.set(l(...n),{timeoutId:m,resolve:u}):sc.set(this,new Map([[l(...n),{timeoutId:m,resolve:u}]]))})}return a.action(2,r.bind(this),n).catch(nc.bind(null,s))})}function xr(o){return Y((i,e)=>function(...t){let r=typeof o=="function"?o.call(this,...t):o;if(r instanceof RegExp)return Promise.all(nr.gets(this,r).map(n=>n.action(3,()=>Promise.resolve(),t))).then(()=>i.call(this,...t));let s=nr.get(this,r);return s?s.action(3,i.bind(this),t).catch(nc.bind(null,e)):i.apply(this,t)})}function wr(){return function(o,i,e){return o.prototype[i]=function(){let t=this._log||console,r=`"${i}" is a static method. Use TRTC.${i}() instead. See: ${_t}/en/TRTC.html#.${i}`;t.warn(r)},e}}var U={ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",KICKED_OUT:"kicked-out",REMOTE_USER_ENTER:"remote-user-enter",REMOTE_USER_EXIT:"remote-user-exit",REMOTE_AUDIO_AVAILABLE:"remote-audio-available",REMOTE_AUDIO_UNAVAILABLE:"remote-audio-unavailable",REMOTE_VIDEO_AVAILABLE:"remote-video-available",REMOTE_VIDEO_UNAVAILABLE:"remote-video-unavailable",AUDIO_VOLUME:"audio-volume",AUDIO_FRAME:"audio-frame",NETWORK_QUALITY:"network-quality",CONNECTION_STATE_CHANGED:"connection-state-changed",AUDIO_PLAY_STATE_CHANGED:"audio-play-state-changed",VIDEO_PLAY_STATE_CHANGED:"video-play-state-changed",SCREEN_SHARE_STOPPED:"screen-share-stopped",DEVICE_CHANGED:"device-changed",PUBLISH_STATE_CHANGED:"publish-state-changed",TRACK:"track",STATISTICS:"statistics",SEI_MESSAGE:"sei-message",CUSTOM_MESSAGE:"custom-message",VIDEO_DECODE_DOWNGRADE_STATE_CHANGED:"video-decode-downgrade-state-changed",LAYER_DATA:"layerData",FIRST_VIDEO_FRAME:"first-video-frame",PERMISSION_STATE_CHANGE:"permission-state-change",VIDEO_SIZE_CHANGED:"video-size-changed"},Mf=new Set([U.AUDIO_VOLUME,U.AUDIO_FRAME,U.NETWORK_QUALITY,U.STATISTICS,U.SEI_MESSAGE,U.CUSTOM_MESSAGE,U.LAYER_DATA]);var yh={};Bi(yh,{ScheduleRequestType:()=>Pf,getAbilityConfig:()=>FS,getScheduleDomain:()=>cc,isNeedToSchedule:()=>ac,scheduleProxy:()=>xi,sendScheduleRequest:()=>Rh,setIsNeedToSchedule:()=>xt,setScheduleProxy:()=>dc});var Ch=null,kf=0,US=48*3600*1e3,ac=!0;typeof document!="undefined"&&document.head.insertAdjacentHTML("beforeend",Object.values(Gi).map(o=>`<link rel="dns-prefetch" href="https://${o}">`).join(`\r
|
|
56
56
|
`));function xt(o){ue(o)&&o!==ac&&(ac=o,R.info(`setIsNeedToSchedule ${o}`),o||(kf=Date.now()+US))}S.on("28",()=>xt(!0));S.on("63",()=>xt(!0));S.on("84",()=>xt(!0));S.on("201",o=>{o.state==="RECONNECTING"&&xt(!0)});S.on("202",o=>{o.state==="RECONNECTING"&&xt(!0)});function VS(o,i,e){let t={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let r=performance.getEntriesByType("resource"),s=Ur(o,"config",_.MAIN),n=Ur(o,"config",_.BACKUP);for(let a of r)if(a.startTime>=e&&(a.name===s||a.name===n)&&a.transferSize>0){let d=a.name===s?_.MAIN:_.BACKUP,l=Math.round(a.duration),u=Math.round(a.domainLookupStart-a.startTime),h=a.redirectStart>0?Math.round(a.redirectEnd-a.redirectStart):0,p=a.fetchStart>0?Math.round(a.domainLookupStart-a.fetchStart):0,m=Math.round(a.domainLookupEnd-a.domainLookupStart),g=Math.round(a.requestStart-a.secureConnectionStart),E=Math.round(a.secureConnectionStart-a.connectStart),C=Math.round(a.responseStart-a.requestStart),P=Math.round(a.responseEnd-a.responseStart),re=[m,g,E,C,P];se.uploadEvent({log:`stat-schedule-net:${l}(${u}(${h}->${p})->${re.join("->")}) ${d}`,userId:i}),t=w(M({},t),{totalCost:l,local:u,dns:m,tcp:E,tls:g,request:C,response:P});break}}catch(r){R.error("getScheduleDetailCost error",r)}return t}function Rh(l){return f(this,arguments,function*({userId:o,sdkAppId:i,useStringRoomId:e,roomId:t,userSig:r,version:s,frameWorkType:n,role:a,latencyLevel:d}){var h;if(!ac&&Ch&&kf>Date.now())return{isCached:!0,result:Ch};let u={delta:0,count:[1,1],msg:[],detail:[]};try{let p=new FormData;p.append("userId",String(o)),p.append("sdkAppId",String(i)),p.append("isStrGroupId",String(e)),p.append("groupId",String(t)),p.append("sdkVersion",s),p.append("userSig",String(r));let m=((h=yield Yr())==null?void 0:h.model)||ed();m&&p.append("model",m);let g=di();g&&p.append("osString",g),a&&p.append("role",String(a)),d&&p.append("latencyLevel",String(d)),n&&p.append("frameWorkType",String(n));let E=V(),C=yield HS(p,u,i);C.config&&(C.config.loggerDomain&&Fr(C.config.loggerDomain),ue(C.config.scheduleCache)&&xt(!C.config.scheduleCache)),u.delta=V()-E;let P=VS(Number(i),o,E);return Ch=C,{isCached:!1,result:C,detailCost:P}}catch(p){let m=Ae(p)?p[0]:p,g=Q(m.code)?m.code:0,E=`schedule failed${m.message?`: ${m.message}`:""}`,C=new v({code:I.SCHEDULE_FAILED,extraCode:g,message:$({key:B.JOIN_ROOM_FAILED,data:{error:E,code:g}})});throw R.error(E,g),C}})}var xi={main:"",backup:""};function dc(o){Ae(o)?(xi.main=o[0],xi.backup=o[1]):xi.main=o}var Pf=(t=>(t.CONFIG="config",t.TRTC_AUTO_CONF="trtcAutoConf",t.AUDIO_AI_AUTH="audioAiAuth",t))(Pf||{});function Ur(o,i,e=_.MAIN,t=!1){return`https://${xi[e]||cc(o,e,t)}/api/v1/${i}`}function FS(o,i,e){let t=Ur(o,i),r=Ur(o,i,_.BACKUP),s=new URLSearchParams(e).toString(),n=fetch(`${t}?${s}`).then(d=>d.json()),a=fetch(`${r}?${s}`).then(d=>d.json());return Xr([n,a])}function cc(o,i=_.MAIN,e=!1){let t;return Ut(o)?e?t=i===_.MAIN?Gi.MAIN_OVERSEA_BACKUP:Gi.BACKUP_OVERSEA:t=i===_.MAIN?Gi.MAIN_OVERSEA:Gi.BACKUP_OVERSEA:t=i===_.MAIN?Gi.MAIN:Gi.BACKUP,t}function BS(o,i,e){return new Promise((t,r)=>{ji({url:o,body:i,timeout:e.timeout,priority:"high"}).then(s=>{s.data.code===0?t(s.data.data):r({code:s.data.code,message:s.data.msg})}).catch(r)})}var Of=(o,i)=>Ri({retryFunction:BS,settings:{retries:3,timeout:0},onError:i,onRetrying:o});function HS(o,i,e){return new Promise((t,r)=>{let s=null;Xr([Of(n=>i.count[0]=n+1,({error:n,retry:a,retriedCount:d,retryFuncArgs:l})=>{i.msg[0]=n.message,s||(d>=1&&(l[0]=Ur(e,"config",_.MAIN,!0)),a())})(Ur(e,"config",_.MAIN),o,{get timeout(){return qr(2+i.count[0])*1e3}}),Of(n=>i.count[1]=n+1,({error:n,retry:a,retriedCount:d,retryFuncArgs:l})=>{i.msg[1]=n.message,s||(d>=2&&(l[0]=Ur(e,"config",_.BACKUP,!0)),a())})(Ur(e,"config",_.BACKUP),o,{get timeout(){return qr(2+i.count[1])*1e3}})]).then(n=>{s=n,t(s)}).catch(r)})}var $S=o=>o.startsWith("data:application/octet-stream;base64,"),WS=o=>o.startsWith("file://"),Jn=class{constructor(){c(this,"_log");this._log=R.createLogger({id:"fd"})}download(i,e){return f(this,null,function*(){let{type:t="blob"}=e||{};i=Da(i);try{let r=V(),s;if(le(fetch)?s=yield this.downloadWithFetch(i,t):s=yield this.downloadWithXHR(i,t),!s||!s.data)throw new Error("data is empty");let n=V()-r;return this._log.info(`downloaded: ${i}, return type: ${t}, cost: ${n}ms`),y.addSuccessEvent({key:522700,cost:V()-r}),s.data}catch(r){throw this._log.error(`failed to download: ${i}, error: ${r}`),y.addFailedEvent({key:522700,error:r}),r}})}downloadWithFetch(i,e){return f(this,null,function*(){this._log.info(`download with fetch: ${i}, return type: ${e}`);try{let t=yield fetch(i);if(!t.ok){let s=new Error(`network response was not ok: ${t.status}`);throw s.status=t.status,s}let r;return e==="arraybuffer"?r=yield t.arrayBuffer():r=yield t.blob(),{data:r}}catch(t){throw t}})}downloadWithXHR(i,e){return this._log.info(`download with xhr: ${i}, return type: ${e}`),new Promise((t,r)=>{let s=new XMLHttpRequest;s.open("GET",i,!0),s.responseType=e,s.onload=()=>{if(s.status===200||s.status===0&&s.response)t({data:s.response});else{let n=new Error(`XHR failed, status: ${s.status}`);n.status=s.status,r(n)}},s.onerror=r,s.send(null)})}loadWasm(i,e){return f(this,null,function*(){this._log.info(`loadWasm ${i}, importObject: ${JSON.stringify(e)}`);let t=V(),r=null,s=null;if(le(WebAssembly.instantiateStreaming)&&!$S(i)&&!WS(i)&&le(fetch))try{let n=fetch(i);r=(yield WebAssembly.instantiateStreaming(n,e)).instance}catch(n){s=n}if(!r)try{let n=yield this.download(i,{type:"arraybuffer"});r=(yield WebAssembly.instantiate(n,e)).instance}catch(n){s=n}if(r){let n=V()-t;return this._log.info(`loadedWasm ${i}, cost: ${n}ms`),y.addSuccessEvent({key:522701,cost:n}),r}throw this._log.error(`failed to loadWasm ${i}, error: ${s}`),y.addFailedEvent({key:522701,error:s}),s})}loadScript(i){this._log.info(`loadScript ${i}`);let e=V();return new Promise((t,r)=>{let s=document.createElement("script");s.type="text/javascript",s.onload=()=>{this._log.info(`loadedScript ${i}, cost: ${V()-e}ms`),y.addSuccessEvent({key:522702,cost:V()-e,split:1e3}),t(s)},s.onerror=n=>{this._log.error(`failed to loadScript ${i}, error: ${(n==null?void 0:n.message)||JSON.stringify(n)}`),y.addFailedEvent({key:522702}),r(n)},s.crossOrigin="anonymous",s.src=i,document.head.append?document.head.append(s):document.getElementsByTagName("head")[0].appendChild(s)})}};D([Mt({settings:{timeout:0,retries:3},onError(i,e,t){var r;(i==null?void 0:i.status)===404||(r=i==null?void 0:i.message)!=null&&r.includes("404")?(this._log.warn("download 404, stop retry"),t(i)):e()},onRetrying(i){this._log.warn(`download retrying: ${i}`)}})],Jn.prototype,"download",1),D([Mt({settings:{timeout:3e3,retries:3},onRetrying(i){this._log.warn(`loadScript retrying: ${i}`)}})],Jn.prototype,"loadScript",1);var qn=new Jn;var Lf=!1,xf;function wf({TRTC:o,room:i,errorModule:e,assetsPath:t}){return{TRTC:o,LocalMixVideoTrack:go,LocalVideoTrack:je,LocalScreenTrack:Pt,room:i,assetsPath:t,fileDownloader:qn,innerEmitter:S,INNER_EVENT:A,constants:il,environment:Ko,utils:gh,eventLogger:se,log:this.room.getLogger(),loggerManager:R,errorModule:e,kvStatManager:y,rtcDectection:vi,trtc:this,rx:fh,enums:zl,schedule:yh,getDevices:cs,initVisionTaskRegistry:(r,s,n="/mediapipe/vision.js")=>f(this,null,function*(){!window.VisionTaskRegistry&&!Lf&&(Lf=!0,xf=qn.loadScript(`${r}/${n}`.replace(/([^:]\/)\/+/g,"$1"))),yield xf,yield(yield window.VisionTaskRegistry.getInstance(r)).preloadModels(s)}),audioContext:Ee(),deviceDetector:be,AudioPlayer:us,showAutoPlayDialog:ns,Timer:oe,clearStarted:(r,s)=>{let n=r.getAlias(),a=nr.instances.get(this);if(a)if(s){let d=a.get(n+s);if(!d)return;d.started=!1}else a.forEach((d,l)=>{l.startsWith(n)&&(d.started=!1)})},startGetPCM:Wn,createAudioNode:Mn,getNetworkTimeOffset:fm,validateSourceNode:()=>{var r;if(ee&&!((r=this.room.audioManager._localAudioPipline)!=null&&r.source.node))throw new F({code:W.DEVICE_ERROR,extraCode:5310,message:"The audio processing plugin cannot be used due to the microphone's sampling rate is not 48KHz in Firefox. Please switch to another browser such as Chrome."})}}}var Uf=(o,i)=>{let{emit:e}=o;return o.emit=(...t)=>{try{return e.apply(o,t)}catch(r){let s=$({key:B.CATCH_HANDLER_ERROR,data:{name:i,event:t[0]},addDocLink:!1});return R.warn(`${s}
|
|
57
57
|
|
|
58
|
-
${r.stack}`),!1}},o};var Cs=new WeakMap;function Vf(o){let i=Cs.get(o);i&&(i.forEach(e=>clearTimeout(e)),Cs.delete(o))}function Ff(o,i){return Y((e,t)=>function(...r){let s=Cs.get(this);s||(s=new Map,Cs.set(this,s));let n=i(...r),a=s.get(n);if(!a||a<=0){e.apply(this,r);let d=setTimeout(()=>{var l;(l=Cs.get(this))==null||l.delete(n)},o);s.set(n,d)}else{clearTimeout(a);let d=window.setTimeout(()=>{var l;e.apply(this,r),(l=Cs.get(this))==null||l.delete(n)},o);s.set(n,d)}})}var Hf="trtc-sdk-v5",bh="5.15.0-beta.19";function ot(...o){return Y((i,e)=>function(...t){try{uc.call(this,o,t,e,this._name)}catch(r){return Promise.reject(r)}return i.apply(this,t)})}function Nh(...o){return Y((i,e)=>function(...t){try{uc.call(this,o,t,e,this._name)}catch(r){throw r}return i.apply(this,t)})}function uc(o,i,e,t){if(Ae(o))for(let r=0;r<o.length;r++)lc.call(this,{rule:o[r],value:i[r],key:o[r].name,fnName:e,className:t});else lc.call(this,{rule:o,value:i[0],key:o.name,fnName:e,className:t})}function lc({rule:o,value:i,key:e,fnName:t,className:r}){function s(d){return{code:W.INVALID_PARAMETER,extraCode:d,fnName:t,messageParams:{key:e,rule:o,value:i}}}if(T(i)){if(o.required)throw new F(s(5001));if(T(o.defaultValue)){le(o.validate)&&o.validate.call(this,i,e,t,r,this);return}i=o.defaultValue}if(Array.isArray(o.type)){let d=!1;for(let l=0;l<o.type.length;l++)o.type[l]===null&&i===null&&(d=!0),le(o.type[l])&&i instanceof o.type[l]&&(d=!0),ie(o.type[l])&&Me(i)===o.type[l].toLowerCase()&&(d=!0);if(!d)throw new F({code:W.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:o.type.map(l=>jr(l)?wo(l):ie(l)?l:Me(l))},value:i}})}else if(!T(o.type)&&Me(i)!==o.type)throw new F(s(5002));if(o.allowEmpty===!1){let d=Q(i)&&(i===0||Number.isNaN(i)),l=ie(i)&&i.trim()==="";if(d||l)throw new F(s(5003))}if(o.notLessThanZero&&Q(i)&&i<0)throw new F(s(5006));if(!T(o.min)&&Q(i)&&i<o.min)throw new F(s(5007));if(!T(o.max)&&Q(i)&&i>o.max)throw new F(s(5008));if(ie(o.instanceOf)){if(!i||i._name!==o.instanceOf)throw new F(s(5004))}else if(le(o.instanceOf)&&!(i instanceof o.instanceOf))throw new F(s(5004));if(Array.isArray(o.values)&&!o.values.includes(i))throw new F(s(5005));let{properties:n}=o;dt(n)&&yt(i)&&Object.keys(n).forEach(d=>{lc.call(this,{rule:n[d],value:i&&i[d],key:`${d}`,fnName:t,className:r})});let{arrayItem:a}=o;dt(a)&&Ae(i)&&i.forEach((d,l)=>{lc.call(this,{rule:a,value:d,key:`${e}[${l}]`,fnName:t,className:r})}),le(o.validate)&&o.validate.call(this,i,e,t,r,this)}function Se(o={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t,ignoreLog:r,ignoreErrorLog:s}=o;return Y((n,a)=>function(...d){var m,g,E;function l(C,P,re){if(re&&re.includes(C))return"hided";if(e){let L=e(...d);if(d[L.argIndex]===P)return L.value}if(P===d||C in d)return P;try{return P instanceof HTMLElement?`id: ${P.id} type:${Me(P)}`:P instanceof MediaStreamTrack?Ma(P):(JSON.stringify(P),P)}catch(L){return`type:${Me(P)}`}}let u=(this==null?void 0:this._log)||R;if(r!=null&&r(...d))return n.apply(this,d);d.length>0?u.info(`${a}() ${JSON.stringify(d,(C,P)=>l(C,P,["userSig","privateMapKey"]))}`):u.info(`${a}()`);let h=t?t(...d):ld[a],p=(s==null?void 0:s(...d))||!1;try{let C=n.apply(this,d),P=V();if(Tr(C)){let re=`${a.includes("Plugin")?`${((g=(m=d[0]).getName)==null?void 0:g.call(m))||""} `:" "}`;return C.then(L=>(u.info(`${a}() success ${re}${i.call(this,...d)}`),y.addSuccessEvent({key:h,cost:V()-P}),L)).catch(L=>{var k;L=F.convertFrom.call(this,L,a,d.length===1?d[0]:d);let Qe=L.extraCode||L.code,N=(k=L.message)!=null&&k.includes(Qe)?"":` code:${Qe}`;throw p||u.error(`${a}() failed ${re}${i.call(this,...d)} ${L}${N} params: ${JSON.stringify(d,l)}`),y.addFailedEvent({key:h,error:L}),L})}return y.addSuccessEvent({key:h}),C}catch(C){C=F.convertFrom.call(this,C,a);let P=C.extraCode||C.code,re=(E=C.message)!=null&&E.includes(P)?"":` code:${P}`;throw p||u.error(`${a}() failed ${C}${re} params: ${JSON.stringify(d,l)}`),y.addFailedEvent({key:h,error:C}),C}})}var hc=o=>Y((i,e)=>function(t,r){return f(this,null,function*(){let s=this._plugins.get(t);if(!s)throw this._log.error(`plugin ${String(t)} is not found`),new F({code:W.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});if(le(s.constructor.isSupported)&&!s.constructor.isSupported())throw this._log.error(`plugin ${String(t)} is not supported`),new F({code:W.ENV_NOT_SUPPORTED,message:`plugin ${String(t)} is not supported`,extraCode:5210,fnName:e});return uc.call(this,s.getValidateRule(o),[r],e,"TRTC"),i.call(this,s,r)})});var mc=0,vh,ar=class ar{constructor(i){this.core=i;c(this,"log");c(this,"customAudioReferenceMap",new Map);c(this,"audioRefId",0);c(this,"audioContext",Ee());c(this,"localAudioWorkletNode");c(this,"screenAudioWorkletNode");c(this,"mixNode");c(this,"silentNode");mc=mc+1,this.log=i.log.createChild({id:`${this.getAlias()}${mc}`}),this.log.info(`created id=${this.getAlias()}${mc}`),this.installEvent()}static getStartValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,t,r,s){if(!i.room.audioManager.hasAudioTrack&&!i.room.audioManager.hasScreenAudioTrack)throw new F({code:W.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return vh||(vh=this.doPreload(i)),vh}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield tr(this.audioContext,t)}catch(r){this.log.error(`preload audioProcessor failed. ${r}`)}finally{URL.revokeObjectURL(t)}})}getName(){return ar.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(i){switch(i){case"start":return ar.getStartValidateRule(this.core);case"update":return ar.updateValidateRule;case"stop":return ar.stopValidateRule}}start(i){return f(this,null,function*(){var p,m,g,E;let{room:e}=this.core,{sdkAppId:t,userId:r,userSig:s,assetsPath:n=this.core.assetsPath,audioReference:a,processLevel:d,enableDump:l,isLocalAudioNeedAudioProcess:u=!0,isScreenAudioNeedAudioProcess:h=!1}=i;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=u,this.core.room.audioManager.isScreenAudioNeedAudioProcess=h,!n)throw new F({code:W.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload(`${n}/audioProcessor-wasm.js`),u&&!this.localAudioWorkletNode){let{sign:C,status:P,timestamp:re}=yield this.getAuthData(t,r,s);this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",t,r,re,C,P,e)}if(h&&!this.screenAudioWorkletNode){let{sign:C,status:P,timestamp:re}=yield this.getAuthData(t,r,s);this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",t,r,re,C,P,e)}this.mixNode||(this.mixNode=this.audioContext.createGain(),this.mixNode.gain.value=1),this.silentNode||(this.silentNode=this.audioContext.createConstantSource(),this.silentNode.offset.setValueAtTime(0,this.audioContext.currentTime),this.silentNode.start()),(p=this.localAudioWorkletNode)==null||p.port.postMessage({type:"enable"}),(m=this.screenAudioWorkletNode)==null||m.port.postMessage({type:"enable"}),e.audioManager.addAudioProcessor(this.mixNode,this.silentNode,this.localAudioWorkletNode,this.screenAudioWorkletNode),T(a)||a.forEach(C=>{this.customAudioReferenceMap.set(C,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:C,refId:`o-${this.audioRefId++}`})}),T(d)||(g=this.localAudioWorkletNode)==null||g.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:d}}),T(l)||(E=this.localAudioWorkletNode)==null||E.port.postMessage({type:"dump",data:{enable:l}})})}update(i){return f(this,null,function*(){var s,n,a;let{audioReference:e,enableDump:t,processLevel:r}=i;T(e)||(this.customAudioReferenceMap.forEach((d,l)=>{this.customAudioReferenceMap.delete(l),this.core.room.audioManager.updateAudioReference({type:"remove",refId:d})}),e.forEach(d=>{this.customAudioReferenceMap.set(d,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:d,refId:`o-${this.audioRefId++}`})})),T(r)||(s=this.localAudioWorkletNode)==null||s.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:r}}),T(t)||((n=this.localAudioWorkletNode)==null||n.port.postMessage({type:"dump",data:{enable:t}}),(a=this.screenAudioWorkletNode)==null||a.port.postMessage({type:"dump",data:{enable:t}}))})}stop(){return f(this,null,function*(){var e,t;let{room:i}=this.core;(e=this.localAudioWorkletNode)==null||e.port.postMessage({type:"disable"}),(t=this.screenAudioWorkletNode)==null||t.port.postMessage({type:"disable"}),yield i.audioManager.removeAudioProcessor(this.localAudioWorkletNode,this.screenAudioWorkletNode)})}destroy(){this.localAudioWorkletNode&&(this.localAudioWorkletNode.port.onmessage=null),this.screenAudioWorkletNode&&(this.screenAudioWorkletNode.port.onmessage=null),this.uninstallEvent()}getAuthData(i,e,t){return f(this,null,function*(){let r=String(Date.now()).slice(0,-3),{auth:s,sign:n,status:a,message:d}=yield JS({sdkAppId:i,userSig:t,userId:e,timestamp:r});if(!s)throw this.log.info(`audioProcessor: ${e} auth result: ${s}. Message: ${d}`),new F({code:W.INVALID_PARAMETER,message:d});return{sign:n,status:a,timestamp:r}})}initWorkletNode(i,e,t,r,s,n,a,d){i.port.postMessage({type:"init",data:{sdkAppId:String(t),userId:r,timestamp:s,sign:n,status:a}}),i.port.onmessage=l=>{var h;let{data:u}=l;switch(u.type){case"cost":let p=(u==null?void 0:u.value)>10?"info":"debug";this.log[p](`${e==="localAudio"?"":`[${e}] `}avg cost: ${u.value} max: ${u==null?void 0:u.max}(${vo(new Date(u==null?void 0:u.maxCostTimestamp))}) hist: ${(h=u==null?void 0:u.hist)==null?void 0:h.join(" ")}`);return;case"log":this.log[u.logLevel](`${e==="localAudio"?"":`[${e}] `}${u.value}`);return;case"dump":S.emit("265",{room:d,data:u.value,type:e==="localAudio"?"dump":"dump-screen-audio"});return}}}handleLocalAudioStarted(i){return f(this,null,function*(){var e;if(!(!this.hitTest(i.room)||((e=this.core.room.scheduleResult.config)==null?void 0:e.audioProcessor)!==!0))try{yield this.core.trtc.startPlugin("AudioProcessor",{sdkAppId:this.core.room.sdkAppId,userId:this.core.room.userId,userSig:this.core.room.userSig}),this.log.warn("audio processor auto start success")}catch(t){this.log.warn(`audio processor auto start failed, error: ${t}`)}})}handleLocalAudioStopped(i){return f(this,null,function*(){var e;!this.hitTest(i.room)||((e=this.core.room.scheduleResult.config)==null?void 0:e.audioProcessor)!==!0||(yield this.core.trtc.stopPlugin("AudioProcessor"))})}installEvent(){this.core.innerEmitter.on("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.on("114",this.handleLocalAudioStopped,this)}uninstallEvent(){this.core.innerEmitter.off("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.off("114",this.handleLocalAudioStopped,this)}hitTest(i){return i===this.core.room}};c(ar,"updateValidateRule",{type:"object"}),c(ar,"stopValidateRule",{type:"object"}),c(ar,"Name","AudioProcessor");var pc=ar;function GS(o,i=_.MAIN){return`https://${xi[i]||cc(o,i)}/api/v1/audioAiAuth`}function JS(r){return f(this,arguments,function*({sdkAppId:o,userId:i,userSig:e,timestamp:t}){let n=`${GS(o)}?sdkAppId=${o}&userId=${i}&userSig=${e}×tamp=${t}`,a=yield fetch(n),{data:{errCode:d,errMsg:l,sign:u,status:h}}=yield a.json();if(h==="1")return{auth:!0,sign:u,status:h,message:l};let p=Ut(o)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",m="Init RTCAudioProcessor failed.",g="";switch(d){case 1:g="Please check your params.";break;case 2:g=`You need to buy packages. Refer to: ${p}`;break;case 3:g="Server is invalid. Please contact our engineer. ";break;case 4:g=`Your packages is not active. Refer to: ${p}`;break;case 5:g=`Your packages is expired. Refer to: ${p}`;break;case 6:g="Your version is not supported.";break}return{auth:!1,status:h,message:l?`${m} Reason: ${l}. ${g}`:`${m}, ${g}`}})}var fc=0,Dh=class{constructor(i,e){c(this,"audioObjectURL");c(this,"player");c(this,"publisher");c(this,"mixInput");this.mixInput=new ds(e),i.url?(this.player=new Audio(i.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(i.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(i.track),this.mixInput.connect()}updateSettings(i){this.player&&(T(i.volume)||(this.volume=i.volume),T(i.loop)||(this.loop=i.loop),T(i.playbackRate)||(this.playbackRate=i.playbackRate))}updateListener(i){if(this.player){if(i.onDurationChange){let{onDurationChange:e}=i;this.player.ondurationchange=t=>{e(t.target.duration)}}if(i.onTimeUpdate){let e=i.onTimeUpdate,{player:t}=this;t.ontimeupdate=()=>{e(t.currentTime,t.duration)}}i.onEnded&&(this.player.onended=i.onEnded)}}reload(i){return f(this,null,function*(){if(i.url){let e=yield qn.download(i.url,{retries:3,type:"blob"});this.audioObjectURL&&URL.revokeObjectURL(this.audioObjectURL),this.audioObjectURL=URL.createObjectURL(e),this.player&&this.publisher?(this.player.src=this.audioObjectURL,this.publisher.src=this.audioObjectURL):(this.player=new Audio(this.audioObjectURL),this.player.crossOrigin="anonymous",this.publisher=new Audio(this.audioObjectURL),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher),this.updateListener(i),this.updateSettings(i))}else this.mixInput.replaceSource(i.track)})}reset(){this.seek(0),this.mixInput.connect()}seek(i){this.player&&(i<0&&i>this.player.duration||(this.player.currentTime=i,this.publisher.currentTime=i))}play(){var i,e;return Promise.all([(i=this.player)==null?void 0:i.play(),(e=this.publisher)==null?void 0:e.play()])}pause(){var i,e;(i=this.player)==null||i.pause(),(e=this.publisher)==null||e.pause()}stop(){var i;(i=this.player)==null||i.pause(),this.mixInput.disconnect()}setOperation(i){i==="pause"&&this.pause(),i==="resume"&&(this.pause(),this.play()),i==="stop"&&(this.pause(),this.seek(0))}set volume(i){!this.player||!this.publisher||(this.player.volume=i,this.publisher.volume=i)}set loop(i){!this.player||!this.publisher||(this.player.loop=i,this.publisher.loop=i)}set playbackRate(i){!this.player||!this.publisher||(this.player.playbackRate=i,this.publisher.playbackRate=i)}};function Rs(o,i){if(i&&typeof i!="function")throw new F({code:W.INVALID_PARAMETER,message:`start audioMixer plugin: param ${o} should be a function.`})}var wi=class wi{constructor(i){this.core=i;c(this,"log");c(this,"mixedMusicMap",new Map);c(this,"cacheMusicMap",new Map);fc=fc+1,this.log=i.log.createChild({id:`${this.getAlias()}${fc}`}),this.log.info(`created id=${this.getAlias()}${fc}`)}getName(){return wi.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return wi.startValidateRule;case"update":return wi.updateValidateRule;case"stop":return wi.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e}=this.core;this.core.validateSourceNode(),this.log.info(`add music source, id: ${i.id} url: ${i.url}, track: ${i.track}`);let{id:t,url:r}=i;if(this.mixedMusicMap.has(t))return;let s=this.cacheMusicMap.get(t);s?i.url?s.reset():(s.mixInput.replaceSource(i.track),s.mixInput.connect()):(s=new Dh(i,e.audioManager),this.cacheMusicMap.set(t,s)),s.updateListener(i),s.updateSettings(i);try{yield s.play()}catch(n){yield this.handleAutoPlayFailed(s,i,n)}this.mixedMusicMap.set(t,s),s.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"add",audioReference:s.mixInput.source.node,refId:`ax-${t}`}),this.log.info(`start mix audio track ${t} success.`),y.addEnum({key:502700,value:3}),this.kvUpload(i)})}handleAutoPlayFailed(i,e,t){return f(this,null,function*(){if(t.name==="NotSupportedError")this.log.error(`play failed, try to reload source. error: ${t}`),yield i.reload(e),yield i.play();else if(t.name==="NotAllowedError")if(this.core.room.enableAutoPlayDialog){let r=()=>{var s;(s=i.play())==null||s.finally(()=>{S.off("154",r,this)})};S.on("154",r,this),ns()}else this.core.trtc.emit(U.AUTOPLAY_FAILED,{userId:"",mediaType:"audio",resume:()=>f(this,null,function*(){return i.play()})});else throw t})}update(i){return f(this,null,function*(){let{id:e,operation:t,seekFrom:r,playbackRate:s}=i;this.log.info(`update music source, ${JSON.stringify(i)}`);let n=this.mixedMusicMap.get(e);if(!n){this.log.warn(`update music source failed, music id: ${e} not found.`);return}n.updateSettings(i),n.updateListener(i),T(t)||n.setOperation(t),T(r)||n.seek(r),this.kvUpload(i)})}stop(e){return f(this,arguments,function*({id:i}){if(this.mixedMusicMap.has(i)){this.log.info(`remove music source, music id: ${i}`);let t=this.mixedMusicMap.get(i);t!=null&&t.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:t.mixInput.source.node,refId:`ax-${i}`}),t==null||t.stop(),this.mixedMusicMap.delete(i)}i==="*"&&this.destroyAllMusic()})}kvUpload(i){let{track:e,loop:t,volume:r,playbackRate:s,operation:n,seekFrom:a,onTimeUpdate:d,onDurationChange:l,onEnded:u}=i;e&&y.addCount({key:502009}),t&&y.addCount({key:502001}),r&&y.addCount({key:502002}),s&&y.addCount({key:502003}),n&&y.addCount({key:502004}),a&&y.addCount({key:502005}),typeof d!="function"&&y.addCount({key:502007}),typeof u!="function"&&y.addCount({key:502008}),typeof l!="function"&&y.addCount({key:502006})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((i,e)=>{i!=null&&i.mixInput.track&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:i.mixInput.track,refId:e}),this.stop({id:e})})}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}};c(wi,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(i,e,t){if(i.url&&i.url!=="*"){let r=i.url.split("?")[0],s=["mp3","ogg","wav","flac"],n=r.split(".").pop(),a=s.indexOf(n)>=0,d=r.startsWith("blob"),l=r.startsWith("data");if(!(a||d||l))throw new F({code:W.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new F({code:W.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});Rs("onTimeUpdate",i.onTimeUpdate),Rs("onEnded",i.onEnded),Rs("onDurationChange",i.onDurationChange)}}),c(wi,"updateValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},loop:{type:"boolean"},volume:{type:"number"},seekFrom:{type:"number"},operation:{type:"string",values:["pause","resume","stop"]}},validate(i,e,t){Rs("onTimeUpdate",i.onTimeUpdate),Rs("onEnded",i.onEnded),Rs("onDurationChange",i.onDurationChange)}}),c(wi,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),c(wi,"Name","AudioMixer");var _c=wi;var gc=0,Mh,dr=class dr{constructor(i){this.core=i;c(this,"log");c(this,"audioContext",Ee("denoiser"));c(this,"workletNode");c(this,"config",{enableFarFieldReduce:!1,farFieldReduceThreshold:.5});gc=gc+1,this.log=i.log.createChild({id:`${this.getAlias()}${gc}`}),this.log.info(`created id=${this.getAlias()}${gc}`)}static startValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0},mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}},validate(e,t,r,s){if(!i.room.audioManager.hasAudioTrack)throw new F({code:W.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return Mh||(Mh=this.doPreload(i)),Mh}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield tr(this.audioContext,t)}catch(r){throw this.log.error("load worklet failed",r),r}finally{URL.revokeObjectURL(t)}})}getName(){return dr.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser"}getValidateRule(i){switch(i){case"start":return dr.startValidateRule(this.core);case"update":return dr.updateValidateRule;case"stop":return dr.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e,schedule:t}=this.core,{assetsPath:r=this.core.assetsPath}=i;if(!r)throw new F({code:W.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload(`${r}/denoiser-wasm${cu()?"":"-nosimd"}.js`),!this.workletNode){let s=String(Date.now()).slice(0,-3),{auth:n,sign:a,status:d,message:l}=yield jS(t,w(M({},i),{timestamp:s}));if(!n)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${n}. Message: ${l}`),new F({code:W.INVALID_PARAMETER,message:l});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(i.sdkAppId),userId:i.userId,timestamp:s,sign:a,status:d}}),this.workletNode.port.onmessage=u=>{var p;let{data:h}=u;if(h.type==="cost"){let m=(h==null?void 0:h.max)>20?"warn":(h==null?void 0:h.max)>10?"info":"debug";this.log[m](`avg cost: ${h.value} max: ${h==null?void 0:h.max}(${vo(new Date(h==null?void 0:h.maxCostTimestamp))}) hist: ${(p=h==null?void 0:h.hist)==null?void 0:p.join(" ")}`)}else h.type==="log"&&this.log[h.logLevel](`${h.value}`)}}this.updateConfig(i),this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(i){return f(this,null,function*(){this.updateConfig(i)})}stop(){return f(this,null,function*(){if(!this.workletNode)return;let{room:i}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield i.audioManager.removeDenoiser(this.workletNode)})}updateConfig(i){if(!this.workletNode)return;let e=!1;T(i.mode)||(i.mode===0?this.config.enableFarFieldReduce=!1:i.mode===1&&(this.config.enableFarFieldReduce=!0),e=!0),T(i.farFieldReduceThreshold)||(this.config.farFieldReduceThreshold=i.farFieldReduceThreshold,e=!0),e&&this.workletNode.port.postMessage({type:"setConfig",data:this.config})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};c(dr,"updateValidateRule",{type:"object",properties:{mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}}}),c(dr,"stopValidateRule",{type:"object"}),c(dr,"Name","AIDenoiser");var Tc=dr;function jS(s,n){return f(this,arguments,function*(o,{sdkAppId:i,userId:e,userSig:t,timestamp:r}){try{let{data:{errCode:a,errMsg:d,sign:l,status:u}}=yield o.getAbilityConfig(i,o.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:i,userId:e,userSig:t,timestamp:r});if(u==="1")return{auth:!0,sign:l,status:u,message:d};let h=Ut(i)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",p="Init RTCAIDenoiser failed.",m="";switch(a){case 1:m="Please check your params.";break;case 2:m=`You need to buy packages. Refer to: ${h}`;break;case 3:m="Server is invalid. Please contact our engineer. ";break;case 4:m=`Your packages is not active. Refer to: ${h}`;break;case 5:m=`Your packages is expired. Refer to: ${h}`;break;case 6:m="Your version is not supported.";break}return{auth:!1,status:u,message:d?`${p} Reason: ${d}. ${m}`:`${p}, ${m}`}}catch(a){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${a}`}}})}var Wf=Je(nt(),1);var Oh=class extends Wf.EventEmitter{constructor(){super();c(this,"observer");c(this,"state","nominal");this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return f(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!_e&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){se.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let t=this.stateNum,r=e[e.length-1];this.state=r.state,(this.stateNum>3||t>3)&&R.info(`${r.source}: ${r.state}`),this.emit("state-changed",{type:r.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(t){se.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},XS=new Oh,kh=XS;function Ph([o,i]){let e=i.byteLength,t=parseInt(String(e/255),10),r=e%255,s=[];s.push(0,0,0,1,6,o);for(let a=0;a<t;a++)s.push(255);s.push(r);let n=new DataView(i);return s.push(...new Uint8Array(n.buffer)),s.push(128),new sr(new DataView(new Uint8Array(s).buffer),!0)}function Lh(o){return o.type==="empty"||o.data.byteLength===0}function xh(o){return o.getInt32(0)===1&&o.getInt8(4)===6}function wh(o){let i=0,e=0,t=new DataView(o);for(let r=0;r<o.byteLength;r++)switch(t.getUint8(r)){case 0:i++;break;case 1:(i===2||i===3)&&e++,i=0;break;default:i=0;break}return e}function Uh({frame:o,seiMessageList:i}){if(!i||i.length===0||o.data.byteLength===0)return o;let t=9-wh(o.data);if(t<=0)return o;let r=i.splice(0,t).reverse().map(Ph),s=r.reduce((u,h)=>u+h.dataView.byteLength,0),n=new ArrayBuffer(s+o.data.byteLength),a=new DataView(n),d=new DataView(o.data),l=0;for(let u=0;u<r.length;u++)for(let h=0;h<r[u].dataView.byteLength;h++)a.setInt8(l++,r[u].dataView.getInt8(h));for(let u=0;u<o.data.byteLength;u++)a.setInt8(l++,d.getInt8(u));return o.data=n,o}function Vh({frame:o,onSEI:i}){try{let e=new DataView(o.data);if(Lh(o)||!xh(e))return o;let t=[],r=0,s=-1,n=-1;for(let a=0;a<o.data.byteLength;a++){let d=e.getUint8(a);if(d===0)r++;else if(d===1){if(r===2||r===3){let l=a-r;if(s===-1?s=l:n===-1&&(n=l,t.push(new sr(new DataView(e.buffer.slice(s,n)))),s=l,n=-1),!(e.getUint8(a+1)===6)){o.data=e.buffer.slice(l);break}}r=0}else r=0}i==null||i(t.reverse())}catch(e){}return o}var Fh=0,jn=class jn{constructor(i){this.core=i;c(this,"log");c(this,"_seiMessageList",[]);c(this,"_smallSeiMessageList",[]);c(this,"_subStreamSeiMessageList",[]);Fh++,this.log=i.log.createChild({id:`${this.getAlias()}${Fh}`}),this.log.info(`[sei] created id=${this.getAlias()}${Fh}`),this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode({frame:i,mediaType:e}){try{let t=e===8?this._smallSeiMessageList:e===2?this._subStreamSeiMessageList:this._seiMessageList;return Uh({frame:i,seiMessageList:t})}catch(t){this.log.warn(t)}return i}decode({frame:i,track:e}){return Vh({frame:i,onSEI:t=>{t.forEach(r=>{this.core.trtc.emit(U.SEI_MESSAGE,{seiPayloadType:r.seiPayloadType,data:r.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"})})}})}destroy(){this.log.debug("destroy"),this.stop(),delete this.core}getValidateRule(i){switch(i){case"start":return{type:"object"};case"update":return{type:"object"};case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:pi?this.encode:Uh,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:pi?this.decode:Vh,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update({buffer:i,options:e}){var s;let t=[e.seiPayloadType,i],r=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(t):(this._seiMessageList.push(t),r&&this._smallSeiMessageList.push(t)),(s=this.core.room.scriptTransformWorker)==null||s.postMessage({type:"sei",data:t,isMain:!e.toSubStream,small:r})}getName(){return jn.Name}getAlias(){return"sei"}getGroup(){return"sei"}};c(jn,"autoStart",!0),c(jn,"Name","SEI");var Ec=jn;var zS=0,Sc,Xn=class Xn{constructor(i){this.core=i;c(this,"_core");c(this,"log");c(this,"dialog");this._core=i,this.log=i.log.createChild({id:`${this.getAlias()}${++zS}`}),this.log.info("created")}getName(){return Xn.Name}getAlias(){return"dm"}getGroup(){return"dm"}getValidateRule(i){switch(i){case"start":return{name:"StartDebugOptions",required:!1};case"update":return{name:"UpdateDebugOptions",required:!1};case"stop":return{name:"StopDebugOptions",required:!1}}}start(){return f(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())})}update(e){return f(this,arguments,function*({visible:i}){i?yield this.openDebugDiaLog():this.closeDebugDiaLog()})}stop(){this.closeDebugDiaLog()}destroy(){this.stop()}openDebugDiaLog(){return f(this,null,function*(){var i;if(!this.dialog)try{if(Sc)yield Sc;else{let e=new URLSearchParams(location.search).get("trtcDebugDialogPath")||((i=window.sessionStorage)==null?void 0:i.getItem("TRTC_DEBUG_DIALOG_PATH"))||`https://unpkg.com/${Hf}@${He}/assets/debug-dialog.js`;Sc=this._core.fileDownloader.loadScript(e),yield Sc}this.dialog=new TRTCDebugDialog(this._core,this.log),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(){this.dialog&&(this.dialog.closeDialog(),this.dialog=null)}};c(Xn,"Name","Debug"),c(Xn,"autoStart",!0);var Ic=Xn;var Gf=o=>{switch(o){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},Ac=class{constructor(i,e,t){c(this,"trackDoneOB");c(this,"startOB");c(this,"stopOB");c(this,"inputFrameCount",0);c(this,"decodedFrameCount",0);c(this,"type","auto");c(this,"config");c(this,"decoder");c(this,"_decodeSink");let{kvStatManager:r,trtc:s}=i;this.config=t.config,this.trackDoneOB=de(e,j.INIT),this.stopOB=rt(),this.startOB=rt(),t.type==="auto"?this.type="webCodecs":this.type=t.type;let n=rt(),a=d=>{let l=this.pipe(e);return n.next("STARTING"),e.log.info(`decoder type: ${this.type}`),ce(l,ke(this.stopOB),Te(()=>{},u=>{e.log.error(u),r.addFailedEvent({key:Gf(this.type),error:u}),d>4?this.startOB.error(u):this.startOB.next(d+1)})),ce(l,or(1),hh(Un))};ce(this.startOB,xn(0),Mr(a),ke(this.stopOB),Te(()=>{e.player.setOutput(),n.next("STARTED")},d=>{n.next("FAILED")},()=>{r.addSuccessEvent({key:Gf(this.type)}),r.addSuccessEvent({key:504702})}))}mock(i){this._decodeSink?this._decodeSink.error(i):this.startOB.next(0)}close(i){this.stopOB.next(i)}pipe(i){return rr()(e=>f(this,null,function*(){this._decodeSink=e,e.defer(()=>{var r;(r=this.decoder)==null||r.close()});let{type:t}=this;try{switch(t){case"webCodecs":this.decoder=new AudioDecoder({error:r=>{i.log.error(r),e.error(4)},output:r=>{this.decodedFrameCount++,e.next(r),i.player.write(r)}});break;case"wasm":break}this.decoder.configure(this.config)}catch(r){i.log.error(r),e.error(t==="webCodecs"?2:6)}}))}decodeFrame(i){var e;this.inputFrameCount++,((e=this.decoder)==null?void 0:e.state)==="configured"&&this.decoder.decode(new EncodedAudioChunk({data:i.data,timestamp:i.timestamp,type:"key"}))}},QS={type:"object"},zn=class zn{constructor(i){this.core=i;c(this,"log");c(this,"contextMap",new Map);c(this,"decodeProcessorMap",new WeakMap);this.log=i.log.createChild({id:`${this.getAlias()}`})}getAlias(){return zn.Name}getGroup(i){return i.track.userId+i.track.streamType}getName(){return zn.Name}getValidateRule(i){return QS}start(i){let{track:e}=i;this.decodeProcessorMap.set(e,this.decode(i)),this.core.room.audioManager.addDecodeProcessor({processor:({frame:t,track:r})=>this.decodeProcessorMap.has(r)?this.decodeProcessorMap.get(r)({frame:t,track:r}):t,type:3})}decode(i){return({frame:e,track:t})=>{if(t!==i.track)return e;if(this.contextMap.has(t))return this.contextMap.get(t).decodeFrame(e);let r=new Ac(this.core,t,i);return ce(r.trackDoneOB,or(1),Te(()=>{this.core.clearStarted(this,this.getGroup(i)),this.stop({track:t})})),this.contextMap.set(t,r),r.decodeFrame(e)}}stop({track:i}){let e=this.contextMap.get(i);e&&(e.close("stop"),this.contextMap.delete(i),this.contextMap.size===0&&this.core.room.audioManager.removeDecodeProcessor({type:3}))}update(i){let e=this.contextMap.get(i.track);if(e){if(i.type==="mock"){e.mock(10);return}e.close("update"),this.contextMap.set(i.track,new Ac(this.core,i.track,i))}}};c(zn,"Name","TRTCAudioDecoder");var Qn=zn;var Cc=class{constructor(){c(this,"log");this.log=R.createLogger({id:"exp"})}call(i,e){return f(this,null,function*(){return le(this[i])?this[i](e):Promise.reject(new v({code:I.INVALID_PARAMETER,message:$({key:B.API_NOT_EXIST,data:{name:i}})}))})}enableAudioFrameEvent(i){return f(this,null,function*(){let{trtcInstance:e,enable:t,userId:r,sampleRate:s=48e3,channelCount:n=1,port:a}=i,{audioManager:d}=e.room,{getPCMAbortCtrlMap:l,audioFrameEventConfigMap:u}=d;if(u.set(r,{enable:t,sampleRate:s,channelCount:n,port:a}),t)if(r==="*")e.room.remotePublishedUserMap.forEach(h=>{if(h.remoteAudioTrack.isAvailable){if(l.get(h.userId))return;let p=d.getPCM(m=>{e.emit(U.AUDIO_FRAME,m)},h.userId);l.set(h.userId,p)}});else{if(l.get(r))return;let h=d.getPCM(p=>{e.emit(U.AUDIO_FRAME,p)},r);l.set(r,h)}else if(r==="*")e.room.remotePublishedUserMap.forEach(h=>{if(h.remoteAudioTrack.isSubscribed){let{userId:p}=h,m=l.get(p);m==null||m.abort("disable"),l.delete(p)}});else{let h=l.get(r);h==null||h.abort("disable"),l.delete(r)}})}resumeRemotePlayer(i){return f(this,null,function*(){if(i.userId==="*"){let t=[];return i.trtcInstance.room.remotePublishedUserMap.forEach(r=>{let{remoteAudioTrack:s,remoteVideoTrack:n,remoteAuxiliaryTrack:a}=r;i.streamType?i.streamType==="main"?(s.isAvailable&&t.push(s.player.resume()),n.isAvailable&&t.push(n.player.resume())):a.isAvailable&&t.push(a.player.resume()):(s.isAvailable&&t.push(s.player.resume()),n.isAvailable&&t.push(n.player.resume()),a.isAvailable&&t.push(a.player.resume()))}),Promise.all(t)}let e=i.trtcInstance.room.remotePublishedUserMap.get(i.userId);if(e)return i.streamType==="main"?Promise.all([e.remoteAudioTrack.player.resume(),e.remoteVideoTrack.player.resume()]):e.remoteAuxiliaryTrack.player.resume()})}pauseRemotePlayer(i){if(i.userId==="*")i.trtcInstance.room.remotePublishedUserMap.forEach(e=>{let{remoteAudioTrack:t,remoteVideoTrack:r,remoteAuxiliaryTrack:s}=e;i.streamType?i.streamType==="main"?(t.isAvailable&&t.player.pause(),r.isAvailable&&r.player.pause()):s.isAvailable&&s.player.pause():(t.isAvailable&&t.player.pause(),r.isAvailable&&r.player.pause(),s.isAvailable&&s.player.pause())});else{let e=i.trtcInstance.room.remotePublishedUserMap.get(i.userId);e&&(i.streamType==="main"?(e.remoteAudioTrack.player.pause(),e.remoteVideoTrack.player.pause()):e.remoteAuxiliaryTrack.player.pause())}}};D([_f({name:"options",type:"object",required:!0,properties:{enable:{required:!0,type:"boolean"},userId:{required:!0,type:"string"},sampleRate:{type:"number",values:[8e3,16e3,32e3,44100,48e3]},channelCount:{type:"number",values:[1,2]},port:{type:"messageport"}}})],Cc.prototype,"enableAudioFrameEvent",1);var Jf=new Cc;var qf=Je(nt(),1);var Bh=class extends qf.EventEmitter{constructor(){super();c(this,"states",{});c(this,"permissionChangeHandler");c(this,"log");this.log=R.createLogger({id:"pm"}),this.permissionChangeHandler=()=>{var e,t;this.emit("permission-state-change",{camera:(e=this.states.camera)==null?void 0:e.state,microphone:(t=this.states.microphone)==null?void 0:t.state})}}request(e){return f(this,null,function*(){if(this.log.info(`request ${e.join(", ")}`),e.length===0)return Promise.resolve();(yield navigator.mediaDevices.getUserMedia({video:e.includes("camera"),audio:e.includes("microphone")})).getTracks().forEach(r=>r.stop())})}get(e){return f(this,null,function*(){try{return this.states[e]||(this.states[e]=yield navigator.permissions.query({name:e}),this.states[e].addEventListener("change",this.permissionChangeHandler)),this.log.info(`get ${e} permission state: ${this.states[e].state}`),this.states[e].state}catch(t){return this.log.error(`get ${e} permission failed, error: ${t instanceof Error?t.message:t}`),null}})}destroy(){Object.values(this.states).forEach(e=>{e==null||e.removeEventListener("change",this.permissionChangeHandler)}),this.states={}}},Yn=new Bh;var jf=0,Zn=new Set,ze=null;Wc(bh);es.checkStorage();var q=class q extends Xf.EventEmitter{constructor(e,t){super();c(this,"_room");c(this,"_eventListened",new Set);c(this,"_localVideoTrack",null);c(this,"_localAudioTrack",null);c(this,"_localScreenTrack",null);c(this,"_localScreenAudioTrack",null);c(this,"_localVideoConfig",null);c(this,"_localScreenConfig",null);c(this,"_localAudioConfig",null);c(this,"_remoteVideoConfigMap",new Map);c(this,"_remoteAudioConfigMap",new Map);c(this,"_remoteAudioVolumeMap",new Map);c(this,"_remoteAudioMuteMap",new Map);c(this,"_mediaTrackMap",new WeakMap);c(this,"_log",R.createLogger({id:`t${++jf}`}));c(this,"_plugins",new Map);c(this,"_networkQuality",null);c(this,"_speakerId");c(this,"enterRoomParams");c(this,"_enableAutoSwitchWhenRecapturing",!0);this._room=new e(M({logger:this._log,frameWorkType:q.frameWorkType},t)),this._room.videoDecodeFallbackType=t.videoDecodeFallback,ue(t.enableAutoSwitchWhenRecapturing)&&(this._enableAutoSwitchWhenRecapturing=t.enableAutoSwitchWhenRecapturing),this._log.info(`create() ${JSON.stringify(t,(r,s)=>r==="plugins"?s.map(n=>n.Name):s)}`),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(r){return this._room.audioManager.dump(r)}}}),t.plugins&&t.plugins.forEach(r=>{this._use(r,t.assetsPath)}),this._use(_c,t.assetsPath),this._use(pc,t.assetsPath),this._use(Tc,t.assetsPath),this._use(Qn,t.assetsPath),this._use(Ic),t.enableSEI&&Tn&&this._use(Ec),this._room.on("audio-volume",r=>{var s,n;!r.find(a=>a.userId==="")&&this._localAudioTrack&&r.push({userId:"",volume:Math.floor(((s=this._localAudioTrack.getInternalAudioLevelAfter3A())!=null?s:this._localAudioTrack.getAudioLevel())*100),floatVolume:(n=this._localAudioTrack.getInternalAudioLevelAfter3A())!=null?n:this._localAudioTrack.getInternalAudioLevel()}),t.volumeType===1&&r.forEach(a=>{var l;let d=a.userId===""?this._localAudioTrack:(l=this.room.remotePublishedUserMap.get(a.userId))==null?void 0:l.remoteAudioTrack;d&&(a.volume=d.dbVolume)}),t.enableDbVolume&&r.forEach(a=>{var l;let d=a.userId===""?this._localAudioTrack:(l=this.room.remotePublishedUserMap.get(a.userId))==null?void 0:l.remoteAudioTrack;d&&(a.volume=d.dbVolume)}),this.emit(U.AUDIO_VOLUME,{result:r.sort((a,d)=>d.volume-a.volume)})}),this._room.videoManager.on("error",r=>{this._log.error(new F({code:W.OPERATION_FAILED,extraCode:5504,message:r.message,originError:r}))}),this._listenEvents(),this._initActiveSpeaker(),Uf(this,"trtc")}static create(e){}static _create(e,t){Ef();let r=new q(e,t||{});return Zn.add(r),r.__v_skip=!0,r}get room(){return this._room}_listenEvents(){tt(this,this._room).add("peer-join",e=>{let{userId:t}=e;this.emit(U.REMOTE_USER_ENTER,{userId:t})}).add("peer-leave",e=>{this.emit(U.REMOTE_USER_EXIT,{userId:e})}).add("banned",e=>{xt(!0),this._exitRoom().finally(()=>{this.emit(U.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().finally(()=>{this.emit(U.ERROR,F.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(U.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let t=w(M({},e),{uplinkRTT:Math.min(e.uplinkRTT,Hs),downlinkRTT:Math.min(e.downlinkRTT,Hs)});this.emit(U.NETWORK_QUALITY,t)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(r=>{tt(r,r).add("player-state-changed",s=>{let n=w(M({},s),{userId:e.userId});r.kind===_.VIDEO&&(n.streamType=Li(r.streamType)),this.emit(r.kind===_.AUDIO?U.AUDIO_PLAY_STATE_CHANGED:U.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",s=>{s.getCode()===I.PLAY_NOT_ALLOWED&&this.emit(U.AUTOPLAY_FAILED,{userId:r.userId,mediaType:r.strMediaType,resume:()=>r.player.resume()})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(r=>{we(r)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:t})=>{let{userId:r}=t,s=e.audioAvailable,n=e.videoAvailable,{audioAvailable:a,videoAvailable:d}=t;a||this._remoteAudioConfigMap.delete(r),d||this._removeRemoteVideoConfig(r,"main"),t.hasAuxiliary||this._removeRemoteVideoConfig(r,"sub"),n!==d&&(d?this._onVideoAvailable({userId:r,streamType:"main"}):this._onVideoUnavailable({userId:r,streamType:"main"}),this.emit(d?U.REMOTE_VIDEO_AVAILABLE:U.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"main"})),s!==a&&(a?this._onAudioAvailable({userId:r}):this._onAudioUnavailable({userId:r,muteState:t}),this.emit(a?U.REMOTE_AUDIO_AVAILABLE:U.REMOTE_AUDIO_UNAVAILABLE,{userId:r})),e.hasAuxiliary!==t.hasAuxiliary&&(t.hasAuxiliary?this._onVideoAvailable({userId:r,streamType:"sub"}):this._onVideoUnavailable({userId:r,streamType:"sub"}),this.emit(t.hasAuxiliary?U.REMOTE_VIDEO_AVAILABLE:U.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"sub"}))}).add("sei-message",e=>{this.emit(U.SEI_MESSAGE,w(M({},e),{streamType:Li(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(U.ERROR,new F({code:W.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var s,n,a,d,l,u,h;let t={2:"big",3:"small",7:"sub"},r={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)||((a=this._networkQuality)==null?void 0:a.downlinkRTT)||0,Hs),upLoss:((d=this._networkQuality)==null?void 0:d.uplinkLoss)||0,downLoss:((l=this._networkQuality)==null?void 0:l.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((u=e.msg_up_stream_info.msg_audio_status)==null?void 0:u.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((h=e.msg_up_stream_info.msg_audio_status)==null?void 0:h.uint32_audio_level)||0)/Dt},video:e.msg_up_stream_info.msg_video_status.filter(p=>t[p.uint32_video_stream_type]).map(p=>({bitrate:(p.uint32_video_codec_bitrate||0)/1e3,width:p.uint32_video_width,height:p.uint32_video_height,frameRate:p.uint32_video_enc_fps,videoType:t[p.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(p=>({userId:p.msg_user_info.str_identifier,audio:{bitrate:(p.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(p.msg_audio_status.uint32_audio_level||0)/Dt,point2pointDelay:(p.msg_audio_status.uint32_audio_p2p_delay||0)+(p.msg_audio_status.uint32_audio_cache_ms||0),jitterBufferDelay:p.msg_audio_status.uint32_audio_cache_ms||0},video:p.msg_video_status.map(m=>({bitrate:(m.uint32_video_codec_bitrate||0)/1e3,width:m.uint32_video_width,height:m.uint32_video_height,frameRate:m.uint32_video_dec_fps,videoType:t[m.uint32_video_stream_type],point2pointDelay:(m.uint32_video_p2p_delay||0)+(m.uint32_video_cache_ms||0),jitterBufferDelay:m.uint32_video_cache_ms||0,codec:m.uint32_video_codec}))}))};this.emit(U.STATISTICS,r)}).add("custom-message",e=>{this.emit(U.CUSTOM_MESSAGE,e)}).add("layerData",e=>this.emit(U.LAYER_DATA,e)).add("first-video-frame",e=>{this.emit(U.FIRST_VIDEO_FRAME,w(M({},e),{streamType:Li(e.streamType)}))}).add("audio-frame",e=>{this.emit(U.AUDIO_FRAME,e)}),tt(this,be).add("audioInputAdded",e=>{this.emit(U.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(U.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(U.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(U.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>f(this,null,function*(){if(this.emit(U.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),ze&&ze.deviceId===Bs){let t=(yield vr()).find(r=>r.deviceId===Bs);t&&ze.groupId!==t.groupId&&(ze=t,this.emit(U.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}})).add("audioOutputRemoved",e=>f(this,null,function*(){this.emit(U.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield vr())[0];if(!t||!ze||ze.groupId===t.groupId)return;let r=ze.deviceId===e.deviceId,s=ze.deviceId===Bs&&ze.deviceId===t.deviceId;(r||s)&&(ze=t,this.emit(U.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))})),tt(this,Yn).add("permission-state-change",e=>{this.emit(U.PERMISSION_STATE_CHANGE,e)}),this.room.enableSEI&&this.on(U.SEI_MESSAGE,e=>{var r;let t=(r=this.room.remotePublishedUserMap.get(e.userId))==null?void 0:r.remoteVideoTrack;t&&t.updateAlphaRenderInfo(e)})}getNetworkTime(){return Hi()}use(e){let t,r;return"plugin"in e?(t=e.plugin,r=e.assetsPath):t=e,t.Name==="Chorus"&&(this.room.enableChorus=!0),this._use(t,r)}_use(e,t){let r=this._plugins.get(e.Name);if(r)return this._log.warn("duplicate install plugin",e.Name),r;let s=new e(wf.call(this,{TRTC:q,room:this._room,assetsPath:t,errorModule:{RtcError:F,ErrorCode:W,CoreErrorCode:I,ErrorCodeDictionary:Lt}}));return this._plugins.set(e.Name,s),s.__v_skip=!0,e.autoStart&&this.startPlugin(e.Name),s}enterRoom(e){return f(this,null,function*(){var d,l;this.enterRoomParams=e;let{scene:t="rtc",enableAutoPlayDialog:r=!0,autoReceiveAudio:s=!0,autoReceiveVideo:n=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!ie(e.proxy)&&e.proxy.turnServer&&((l=(d=this._room).setTurnServer)==null||l.call(d,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=r,this._room.autoReceiveAudio=s,this._room.autoReceiveVideo=n,ue(e.preferHW)&&(this._room.preferHW=e.preferHW),e.playoutDelay&&(this._room.playoutDelay=e.playoutDelay),e.jitterBufferDelay&&(this._room.jitterBufferDelay=e.jitterBufferDelay);let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:e.role==="audience"?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language,priority:e.priority,useVp8:e.useVp8,useH265:e.useH265||!1,keepAlive:e.keepAlive};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(a,t,q.frameWorkType),this._checkTrackToPublish(),kh.start()})}exitRoom(){return f(this,null,function*(){return yield this._exitRoom()})}switchRoom(e){return f(this,null,function*(){if(this.room.isSwitchRoomSupported())try{this._clearRemoteTracks(),yield this._room.switchRoom(e)}catch(t){if(t instanceof Ps&&(t.code===I.API_CALL_TIMEOUT||t.code===I.SWITCH_ROOM_FAILED))this._log.warn(`switchRoom ${t.code===I.API_CALL_TIMEOUT?"timeout":"failed"}, fallback to exitRoom() and enterRoom()`),yield this._rejoinRoom(e);else throw t}else yield this._rejoinRoom(e)})}_rejoinRoom(e){return f(this,null,function*(){yield this.exitRoom();let t=M(M({},this.enterRoomParams),e);yield this.enterRoom(t)})}_clearRemoteTracks(){new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(e=>{this._stopRemoteAudio({userId:e}).catch(()=>{})}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let t=e.includes("main")?"main":"sub",r=e.split(`_${t}`)[0];r&&this._stopRemoteVideo({userId:r,streamType:t}).catch(()=>{})}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),Vf(this),this._room.remotePublishedUserMap.forEach(e=>{we(e.remoteAudioTrack),we(e.remoteVideoTrack),we(e.remoteAuxiliaryTrack)})}switchRole(e,t){return f(this,null,function*(){t!=null&&t.privateMapKey&&(this._room.privateMapKey=t.privateMapKey),t!=null&&t.latencyLevel&&(this._room.latencyLevel=t.latencyLevel),yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){this._plugins.forEach(e=>{var t;return(t=e.destroy)==null?void 0:t.call(e)}),this._plugins.clear(),we(this),this.removeAllListeners(),this._room.destroy(),Zn.delete(this),Zn.size===0&&kh.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),S.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return f(this,arguments,function*(e={publish:!0}){if(this._localAudioTrack){this._log.warn("local audio is already started");return}let{publish:t=!0,mute:r,option:s}=e,n=new kt(this._room.audioManager),a={},d={muted:!0};s&&(T(s.microphoneId)?T(s.audioTrack)||(a.customSource=s.audioTrack):a.deviceId=s.microphoneId,s&&Q(s.captureVolume)&&n.setCaptureVolume(s.captureVolume),T(s.profile)||(ie(s.profile)?pa[s.profile]&&n.setProfile(pa[s.profile]):n.setProfile(s.profile)),Q(s.earMonitorVolume)&&(d.muted=!(s.earMonitorVolume>0),d.volume=s.earMonitorVolume),T(s.echoCancellation)||(n.profile.echoCancellation=s.echoCancellation),T(s.noiseSuppression)||(n.profile.noiseSuppression=s.noiseSuppression),T(s.autoGainControl)||(n.profile.autoGainControl=s.autoGainControl),ue(this._enableAutoSwitchWhenRecapturing)&&(n.enableAutoSwitchWhenRecapturing=this._enableAutoSwitchWhenRecapturing)),n.on("5",l=>{this.emit(U.ERROR,new F({code:W.DEVICE_ERROR,extraCode:5309,messageParams:{error:l}}))}),n.on("2",l=>{this.emit(U.DEVICE_CHANGED,{type:"microphone",action:"active",device:l})}),n.on("4",l=>{let u;l.error&&(u=F.convertFrom(l.error)),this.emit(U.PUBLISH_STATE_CHANGED,w(M({},l),{error:u}))}),n.on("6",()=>{}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId),yield n.capture(a),T(r)||n.setMute(r),tt(n,n).add("player-state-changed",l=>{this.emit(U.AUDIO_PLAY_STATE_CHANGED,w(M({},l),{userId:""}))}),t&&this._room.isJoined&&this._room.publish(n).catch(()=>{}),this._localAudioTrack=n,this._localAudioConfig=w(M({},e),{publish:t}),yield this._updateAudioPlayOption({playOption:d,track:n}),S.emit("113",{userId:"",room:this.room})})}updateLocalAudio(e){return f(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:r,option:s}=e,n={};s&&(s.microphoneId?yield this._localAudioTrack.switchDevice(s.microphoneId):T(s.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(s.audioTrack)),T(s.captureVolume)||this._localAudioTrack.setCaptureVolume(s.captureVolume),T(s.earMonitorVolume)||(n.muted=!(s.earMonitorVolume>0),n.volume=s.earMonitorVolume),yield this._localAudioTrack.update3A(s)),this._room.isJoined&&!T(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),T(r)||this._localAudioTrack.setMute(r),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),ei(this._localAudioConfig,e)})}stopLocalAudio(){return f(this,null,function*(){this._localAudioTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),S.emit("114",{userId:"",room:this.room}),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),we(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)})}startLocalVideo(){return f(this,arguments,function*(e={publish:!0,view:null,capture:!0}){var h;if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:t,publish:r=!0,capture:s=!0,mute:n,option:a}=e,d=new je(this._room.videoManager),l={},u={};a&&(ue(a.avoidCropping)&&(d.avoidCropping=a.avoidCropping),a.cameraId?l.deviceId=a.cameraId:T(a.useFrontCamera)?T(a.videoTrack)||(l.customSource=a.videoTrack):l.facingMode=a.useFrontCamera?_.FACING_MODE_USER:_.FACING_MODE_ENVIRONMENT,T(a.retryWhenExactFailed)||(l.retryWhenExactFailed=a.retryWhenExactFailed),a.qosPreference&&(l.contentHint=Gn(a.qosPreference)),T(a.profile)||(ie(a.profile)?zt[a.profile]&&d.setProfile(zt[a.profile]):d.setProfile(a.profile)),T(a.fillMode)||(u.objectFit=a.fillMode),T(a.mirror)||(u.mirror=a.mirror),T(a.small)||(T(a.smallMode)||(this._room.smallMode=a.smallMode),ue(a.small)&&a.small===!1?d.stopSmall():d.updateSmallConfig(Ss(a.small,!0))),T(a.rotation)||d.setRotation(a.rotation),ue(this._enableAutoSwitchWhenRecapturing)&&(d.enableAutoSwitchWhenRecapturing=this._enableAutoSwitchWhenRecapturing)),d.once("first-video-frame",p=>{this.emit(U.FIRST_VIDEO_FRAME,w(M({},p),{streamType:Li(p.streamType)}))}),d.on("5",p=>{this.emit(U.ERROR,new F({code:W.DEVICE_ERROR,extraCode:5308,messageParams:{error:p}}))}),d.on("2",p=>{this.emit(U.DEVICE_CHANGED,{type:"camera",action:"active",device:p})}),d.on("4",p=>{let m;p.error&&(m=F.convertFrom(p.error)),this.emit(U.PUBLISH_STATE_CHANGED,w(M({},p),{error:m}))}),d.on("6",()=>{}),this._listenOutputTrackChanged(d),s?yield d.capture(l):(h=d.manager)==null||h.changeInput(d),T(n)||(yield d.setMute(n)),tt(d,d).add("player-state-changed",p=>{this.emit(U.VIDEO_PLAY_STATE_CHANGED,w(M({},p),{userId:"",streamType:"main"}))}).add("video-size-changed",p=>{this.emit(U.VIDEO_SIZE_CHANGED,w(M({},p),{streamType:Li(p.streamType)}))}),r&&this._room.isJoined&&this._room.publish(d).catch(()=>{}),this._localVideoTrack=d,this._localVideoConfig=w(M({},e),{view:t,publish:r,capture:s}),yield this._updateVideoPlayOption({view:t,playOption:u,track:d})})}updateLocalVideo(e){return f(this,null,function*(){var l,u,h;if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:r,mute:s,capture:n,option:a}=e,d={};if(this._localVideoConfig.capture)n!==!1?a!=null&&a.cameraId?yield this._localVideoTrack.switchDevice(a==null?void 0:a.cameraId):T(a==null?void 0:a.useFrontCamera)?T(a==null?void 0:a.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(a==null?void 0:a.videoTrack)):yield this._localVideoTrack.switchDevice(a!=null&&a.useFrontCamera?_.FACING_MODE_USER:_.FACING_MODE_ENVIRONMENT):this._localVideoTrack.stopCapture();else if(n){let p={};p.deviceId=(a==null?void 0:a.cameraId)||((l=this._localVideoConfig.option)==null?void 0:l.cameraId),p.facingMode=a!=null&&a.useFrontCamera||(u=this._localVideoConfig.option)!=null&&u.useFrontCamera?_.FACING_MODE_USER:_.FACING_MODE_ENVIRONMENT,p.customSource=(a==null?void 0:a.videoTrack)||((h=this._localVideoConfig.option)==null?void 0:h.videoTrack),yield this._localVideoTrack.capture(p)}a&&(T(a.profile)||(ie(a.profile)?zt[a.profile]&&this._localVideoTrack.setProfile(zt[a.profile]):this._localVideoTrack.setProfile(a.profile),(!a.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(a.cameraId))&&T(a.useFrontCamera)&&(yield this._localVideoTrack.applyProfile())),T(a.fillMode)||(d.objectFit=a.fillMode),T(a.mirror)||(d.mirror=a.mirror),T(a.rotation)||this._localVideoTrack.setRotation(a.rotation),a.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(Gn(a.qosPreference)),T(a.small)||(ue(a.small)&&!a.small?this._localVideoTrack.stopSmall():this._localVideoTrack.updateSmallConfig(Ss(a.small,!0)))),this._room.isJoined&&T(r)&&this._localVideoConfig.publish&&n&&!this._localVideoConfig.capture&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._room.isJoined&&((r!=null?r:this._localVideoConfig.publish)?this._room.publish(this._localVideoTrack).catch(()=>{}):this._room.unpublish(this._localVideoTrack).catch(()=>{})),T(s)||(yield this._localVideoTrack.setMute(s)),yield this._updateVideoPlayOption({view:t,playOption:d,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),ei(this._localVideoConfig,e)})}stopLocalVideo(){return f(this,null,function*(){this._localVideoTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),we(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return f(this,arguments,function*(e={publish:!0,view:null}){var p,m;if(this._localScreenTrack){this._log.warn("screen share is already started");return}let{view:t=null,publish:r=!0,muteSystemAudio:s,option:n}=e,a=new Pt(this._room.videoManager);a.on("4",g=>{let E;g.error&&(E=F.convertFrom(g.error)),this.emit(U.PUBLISH_STATE_CHANGED,w(M({},g),{error:E}))}),a.once("first-video-frame",g=>{this.emit(U.FIRST_VIDEO_FRAME,w(M({},g),{streamType:Li(g.streamType)}))}),this._listenOutputTrackChanged(a),e.streamType==="main"&&(a.mediaType=4);let d=null,l={},u={};n&&(T(n.profile)||(ie(n.profile)?fa[n.profile]&&a.setProfile(fa[n.profile]):a.setProfile(n.profile)),n.systemAudio&&(l.systemAudio=!0,l.echoCancellation=n.echoCancellation,l.noiseSuppression=n.noiseSuppression,l.autoGainControl=n.autoGainControl),T(n.fillMode)||(u.objectFit=n.fillMode),n.videoTrack&&(l.videoTrack=n.videoTrack),n.audioTrack&&(l.audioTrack=n.audioTrack),n.captureElement&&(l.captureElement=n.captureElement),n.preferDisplaySurface&&(l.preferDisplaySurface=n.preferDisplaySurface),n.qosPreference&&(l.contentHint=Gn(n.qosPreference)));let h=yield a.capture(l);if(a.mediaTrack.addEventListener(_.ENDED,()=>{this._stopScreenShare(),this.emit(U.SCREEN_SHARE_STOPPED)}),h.getAudioTracks()[0]){d=new To(this._room.audioManager);let g=h.getAudioTracks()[0];(p=e.option)!=null&&p.systemAudio&&!((m=e.option)!=null&&m.audioTrack)&&(d.sourceTrack=g),yield d.setInputMediaStreamTrack(g),ue(s)&&d.mediaTrack&&(d.mediaTrack.enabled=!s),this._speakerId&&d.setAudioOutput(this._speakerId)}if(tt(a,a).add("player-state-changed",g=>{this.emit(U.VIDEO_PLAY_STATE_CHANGED,w(M({},g),{userId:"",streamType:"sub"}))}),r&&this._room.isJoined){let g=[a];d&&(g.push(d),this._checkScreenAudioEchoCancellation(a,d)),g.forEach(E=>this._room.publish(E).catch(()=>{}))}this._localScreenTrack=a,this._localScreenAudioTrack=d,this._localScreenConfig=w(M({},e),{view:t,publish:r}),yield this._updateVideoPlayOption({view:t,playOption:u,track:a})})}updateScreenShare(e){return f(this,null,function*(){var d;if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:r,muteSystemAudio:s,option:n}=e,a={};if(n&&(T(n.fillMode)||(a.objectFit=n.fillMode),n.qosPreference)){let l=Gn(n.qosPreference);this._localScreenTrack.setContentHint(l)}if(this._room.isJoined&&!T(r)){if(r&&!this._localScreenConfig.publish){let l=[this._localScreenTrack];this._localScreenAudioTrack&&l.push(this._localScreenAudioTrack),l.forEach(u=>this._room.publish(u).catch(()=>{}))}if(this._localScreenConfig.publish&&!r){let l=[this._localScreenTrack];this._localScreenAudioTrack&&l.push(this._localScreenAudioTrack),l.forEach(u=>this._room.unpublish(u).catch(()=>{}))}}(d=this._localScreenAudioTrack)!=null&&d.mediaTrack&&ue(s)&&(this._localScreenAudioTrack.mediaTrack.enabled=!s),yield this._updateVideoPlayOption({view:t,playOption:a,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),ei(this._localScreenConfig,e)})}stopScreenShare(){return f(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return f(this,null,function*(){let{view:t,userId:r,streamType:s,option:n}=e,a=`${r}_${s}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${r}, streamType:${s}`);return}let d=this._room.remotePublishedUserMap.get(r);if(!d)return;let l={},u=s==="main"?d.remoteVideoTrack:d.remoteAuxiliaryTrack;u.on("decode-failed",h=>{this.emit(U.ERROR,new F({code:W.OPERATION_FAILED,extraCode:5507,message:"video decode failed"}))}),u.on("video-size-changed",h=>{this.emit(U.VIDEO_SIZE_CHANGED,w(M({},h),{streamType:Li(h.streamType)}))}),this._listenOutputTrackChanged(u),n&&(T(n.fillMode)||(l.objectFit=n.fillMode),T(n.mirror)||(l.mirror=n.mirror),T(n.poster)||(l.poster=n.poster),l.canvasRender=n.canvasRender,s==="main"&&!T(n.small)&&(!d.remoteVideoTrack.isSubscribing&&!d.remoteVideoTrack.isSubscribed&&d.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,u.user)),T(n.draggable)||u.setDraggable(n.draggable)),yield this._room.subscribe(u),yield this._enableVideoDecodeFallback(u,s),yield this._updateVideoPlayOption({view:t,playOption:l,track:u}),this._emitTrackEvent(u),this._remoteVideoConfigMap.set(a,{config:e}),n&&!T(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:u,view:t,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:n==null?void 0:n.viewRoot})})}updateRemoteVideo(e){return f(this,null,function*(){var P,re;let{view:t,userId:r,streamType:s,option:n,mute:a}=e,d=`${r}_${s}`,l=this._remoteVideoConfigMap.get(d);if(!l||!this._room.remotePublishedUserMap.has(r))return;let u={};n&&(T(n.fillMode)||(u.objectFit=n.fillMode),T(n.mirror)||(u.mirror=n.mirror));let h=null,p=this._room.remotePublishedUserMap.get(r);if(s==="main"&&(p!=null&&p.muteState.hasVideo)&&(h=p.remoteVideoTrack),s==="sub"&&(p!=null&&p.muteState.hasAuxiliary)&&(h=p.remoteAuxiliaryTrack),!h)return;let{config:m}=l;s==="main"&&n&&!T(n.small)&&this._room.changeType(n.small,h.user),n&&!T(n.draggable)&&h.setDraggable(n.draggable),ue(a)&&(h.ignoreUpdatePlayingState=!0,a?(yield h.player.pause(),yield this.room.unsubscribe(h)):(yield this.room.subscribe(h),yield h.player.resume())),yield this._updateVideoPlayOption({view:t,playOption:u,track:h,prevConfig:m}),ei(m,e);let g=T(n==null?void 0:n.receiveWhenViewVisible)?(P=m.option)==null?void 0:P.receiveWhenViewVisible:n.receiveWhenViewVisible,E=T(t)?m.view:t,C=T(n==null?void 0:n.viewRoot)?(re=m.option)==null?void 0:re.viewRoot:n.viewRoot;this._observeView({remoteTrack:h,view:E,receiveWhenViewVisible:g,viewRoot:C})})}stopRemoteVideo(e){return f(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,t=!0){return f(this,null,function*(){let r=[],s=this._room.remotePublishedUserMap.get(e.userId);if(s){let{muteState:n,remoteVideoTrack:a,remoteAuxiliaryTrack:d}=s;e.streamType==="main"&&(a.stop(),n.hasVideo&&r.push(a)),e.streamType==="sub"&&(d.stop(),n.hasAuxiliary&&r.push(d))}for(let n of r)t&&(delete n.ignoreUpdatePlayingState,yield this._room.unsubscribe(n),this._mediaTrackMap.delete(n.outMediaTrack));this._removeRemoteVideoConfig(e.userId,e.streamType)})}_removeRemoteVideoConfig(e,t){let r=`${e}_${t}`,s=this._remoteVideoConfigMap.get(r);s&&s.observer&&s.observer.disconnect(),this._remoteVideoConfigMap.delete(r)}muteRemoteAudio(e,t){return f(this,null,function*(){this._remoteAudioMuteMap.set(e,t);try{if(e==="*")if(t)yield this._stopRemoteAudio({userId:e});else{let r=[...this._room.remotePublishedUserMap.values()];for(let s of r)s.muteState.hasAudio&&!this._remoteAudioConfigMap.has(s.userId)&&(yield this._startRemoteAudio({userId:s.userId}))}else t?yield this._stopRemoteAudio({userId:e}):this._remoteAudioConfigMap.has(e)||(yield this._startRemoteAudio({userId:e}))}catch(r){throw r.code!==W.OPERATION_ABORT&&this._remoteAudioMuteMap.delete(e),r}})}setRemoteAudioVolume(e,t){if(e==="*"){this._remoteAudioVolumeMap.set("*",t),this._remoteAudioVolumeMap.forEach((s,n)=>this._remoteAudioVolumeMap.set(n,t));let r=[...this._room.remotePublishedUserMap.values()];for(let s of r)this._remoteAudioVolumeMap.set(s.userId,t),s.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:s.remoteAudioTrack})}else if(e){let r=this._room.remotePublishedUserMap.get(e);this._remoteAudioVolumeMap.set(e,t),r&&r.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:r.remoteAudioTrack})}}startPlugin(e,t){return f(this,null,function*(){return e.start(t)})}updatePlugin(e,t){return f(this,null,function*(){return e.update(t)})}stopPlugin(e,t){return f(this,null,function*(){return e.stop(t)})}enableAudioVolumeEvaluation(e=2e3,t=!1){this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,r){if(this.listeners(e).includes(t))return this;if(this._log.debug("on",e),super.on(e,t,r),this._eventListened.add(e),this.listeners(U.AUDIO_FRAME).length>0){let{audioFrameEventConfigMap:s}=this.room.audioManager;s.get("")||s.set("",{enable:!0}),this._localAudioTrack&&this.room.audioManager.handleLocalTrackStarted({userId:"",room:this.room})}return this}emit(e,...t){try{Mf.has(e)||this._log.debug(`emit ${e} ${JSON.stringify(t)}`)}catch(r){}return super.emit(e,...t)}off(e,t,r){if(this._log.debug("off",e),e==="*"?(this._eventListened.clear(),this.removeAllListeners()):super.off(e,t,r),(e===q.EVENT.AUDIO_FRAME||e==="*")&&this.listeners(q.EVENT.AUDIO_FRAME).length===0){let{getPCMAbortCtrlMap:s}=this.room.audioManager;s.forEach(n=>{n==null||n.abort("off")}),s.clear()}return this}getAudioTrack(e={userId:"",streamType:"main"}){let t,r=null,s="main",n=!1;if(ie(e)?t=e:(t=e.userId,n=e.processed===!0,e.streamType&&(s=e.streamType)),t){let a=this._room.remotePublishedUserMap.get(t);a&&(r=a.remoteAudioTrack)}else r=s==="sub"?this._localScreenAudioTrack:this._localAudioTrack;return r?n&&r.outMediaTrack&&r.outMediaTrack!==r.mediaTrack?r.outMediaTrack.clone():r.mediaTrack:null}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:t="",streamType:r="main",processed:s=!1}=e,n=null;if(t==="")r==="main"&&this._localVideoTrack&&(n=this._localVideoTrack),r==="sub"&&this._localScreenTrack&&(n=this._localScreenTrack);else{let a=this._room.remotePublishedUserMap.get(t);a&&(n=r==="main"?a.remoteVideoTrack:a.remoteAuxiliaryTrack)}return n?s&&n.outMediaTrack&&n.outMediaTrack!==n.mediaTrack?n.outMediaTrack.clone():n.mediaTrack:null}getVideoSnapshot(e={}){let{userId:t,streamType:r="main"}=e;if(t){let s=this._room.remotePublishedUserMap.get(t);if(r==="main"&&(s!=null&&s.muteState.hasVideo))return s.remoteVideoTrack.getVideoFrame();if(r==="sub"&&(s!=null&&s.muteState.hasAuxiliary))return s.remoteAuxiliaryTrack.getVideoFrame()}else{if(r==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(r==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(e){var t,r;this._speakerId=e,(t=this._localAudioTrack)==null||t.setAudioOutput(e),(r=this._localScreenAudioTrack)==null||r.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(s=>s.remoteAudioTrack.setAudioOutput(e))}setCurrentSpeaker(e){return f(this,null,function*(){(yield vr()).forEach(r=>{r.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(U.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}),ze=r)}),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: ${_t}/en/TRTC.html#.setCurrentSpeaker`)})}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return f(this,null,function*(){var a;let{userId:t}=e;if(this._remoteAudioConfigMap.has(t)){this._log.warn(`remote audio has already started. userId:${t}`);return}let r=this._room.remotePublishedUserMap.get(t);if(!r)return;let s={},n=r.remoteAudioTrack;n.on("decode-failed",d=>{this.emit(U.ERROR,new F({code:W.OPERATION_FAILED,extraCode:5508,message:"audio decode failed"}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId);try{let d=(a=this._remoteAudioVolumeMap.get(t))!=null?a:this._remoteAudioVolumeMap.get("*"),l=Q(d)?d:100;s.volume=l,this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(n),ce(de(n,"decode-failed"),ke(de(n,j.INIT)),Te(()=>{this.startPlugin(Qn.Name,{track:n,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:s,track:n}),S.emit("115",{userId:t,room:this.room}),n.outMediaTrack&&this.room.audioManager.updateAudioReference({type:"add",audioReference:n.outMediaTrack,refId:`ra-${t}`})}catch(d){throw this._remoteAudioConfigMap.delete(t),d}this._emitTrackEvent(n)})}_stopRemoteAudio(e,t=!0){return f(this,null,function*(){let r=this._room.remotePublishedUserMap.get(e.userId);r&&(r.remoteAudioTrack.stop(),r.muteState.hasAudio&&t&&(yield this._room.unsubscribe(r.remoteAudioTrack)),this._mediaTrackMap.delete(r.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete(`${e.userId}`),S.emit("116",{userId:e.userId,room:this.room}),this.room.audioManager.updateAudioReference({type:"remove",refId:`ra-${e.userId}`})})}_enableVideoDecodeFallback(e,t){let r=this._room.videoDecodeFallbackType;if(!r||!this._plugins.has("TRTCVideoDecoder"))return;e.log.debug("remote video will fall back when decode failed",e.id);let s;ce(de(e,"decode-failed"),ke(de(e,j.INIT)),Fn(()=>{this._room.downlinkVideoCodec!=="h265"&&this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:r})}),mo(de(e,"decode-downgrade-state-changed")),Te(n=>{s=n.state,this.emit(U.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,w(M({},n),{streamType:t,userId:e.userId}))},n=>{e.log.error("fallback",n)},()=>{s==="STARTED"&&e.log.info("fallback complete")}))}_updateVideoPlayOption(n){return f(this,arguments,function*({view:e,playOption:t,track:r,prevConfig:s}){if(r.setMirror(t.mirror),T(e)&&s&&s.view&&!Uo(t)){let a=Fo(s.view);a.length>0&&(yield r.play(a,t))}if(!T(e)){let a=Fo(e);a.length>0?yield r.play(a,t):r.stop()}})}_updateAudioPlayOption(s){return f(this,arguments,function*({playOption:e={},track:t,prevConfig:r}){if(!t.isPlayCalled)try{yield t.play(null,e)}catch(n){}if(T(e.muted)||t.setPlayerMute(e.muted),T(e.volume)||t.setAudioVolume(e.volume/100),t instanceof kt&&t.mediaTrack){let n=e.muted===!1&&!T(e.volume)&&e.volume>0?"add":"remove";this.room.audioManager.updateAudioReference({type:n,audioReference:t.mediaTrack,refId:"em"})}else if(t instanceof Ei){let n=e.muted?0:e.volume;if(T(n))return;this.room.audioManager.updateAudioReference({type:"updateVolume",refId:`ra-${t.userId}`,volume:e.volume})}})}_listenOutputTrackChanged(e){e.listeners("output-media-track-changed").length===0&&e.on("output-media-track-changed",()=>this._emitTrackEvent(e,!1))}_emitTrackEvent(e,t=!0){let r=e.isRemote?e.userId:"";e.outMediaTrack&&(t&&this._mediaTrackMap.get(e.outMediaTrack)===r||(this._mediaTrackMap.set(e.outMediaTrack,r),this.emit(U.TRACK,{userId:r,streamType:Li(e.streamType),track:e.outMediaTrack,sourceTrack:e.mediaTrack})))}_checkTrackToPublish(){var t,r,s;let e=[];if((t=this._localAudioConfig)!=null&&t.publish&&this._localAudioTrack&&e.push(this._localAudioTrack),(r=this._localVideoConfig)!=null&&r.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),this._checkScreenAudioEchoCancellation(this._localScreenTrack,this._localScreenAudioTrack)),e.length!==0)return Promise.all(e.map(n=>this._room.publish(n).catch(()=>{})))}_observeView({remoteTrack:e,view:t,receiveWhenViewVisible:r,viewRoot:s}){if(T(t)||T(r))return;let n=this._remoteVideoConfigMap.get(`${e.userId}_${Li(e.streamType)}`);if(!n)return;let a=n.observer||void 0;if(t===null||Ae(t)&&t.length===0||!r){a==null||a.disconnect(),e.isSubscribed||(this._log.info("_observeView observer disconnect, resubscribe",e.userId,e.strMediaType),this._room.subscribe(e).catch(()=>{}));return}let l=n.visibleViewMap||new Map,u=-1;(!a||a.root!==s)&&(a==null||a.disconnect(),l.clear(),a=new IntersectionObserver(p=>{p.forEach(m=>{l.set(m.target,m.isIntersecting),e.log.info(`view ${m.target.id} is${m.isIntersecting?"":" not"} visible`)}),clearTimeout(u),u=window.setTimeout(()=>{[...l.values()].find(g=>g)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:s}));let h=new Set(Fo(t));l.forEach((p,m)=>{h.has(m)||(a.unobserve(m),l.delete(m))}),h.forEach(p=>{l.set(p,!0),a.observe(p)}),a.takeRecords().forEach(p=>{l.set(p.target,p.isIntersecting)}),n.visibleViewMap=l,n.observer=a}_exitRoom(){return f(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),this._clearRemoteTracks()})}_stopScreenShare(){return f(this,null,function*(){var e;if(this._localScreenTrack){if(this._room.isJoined){let t=[this._localScreenTrack];this._localScreenAudioTrack&&t.push(this._localScreenAudioTrack),yield Promise.all(t.map(r=>this._room.unpublish(r).catch(()=>{})))}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(((e=this._localScreenAudioTrack.trackSettings)==null?void 0:e.echoCancellation)===!1&&this.stopPlugin("AudioProcessor"),this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),we(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_checkScreenAudioEchoCancellation(e,t){return f(this,null,function*(){var s,n;if(!e||!t)return;let r=(s=e.trackSettings)==null?void 0:s.displaySurface;if(((n=t.trackSettings)==null?void 0:n.echoCancellation)===!1&&(r==="monitor"||r==="browser"&&e.isShareCurrentTab)){this._log.warn("echoCancellation of screen audio track is disable. Try starting audioProcessor plugin");try{yield this.startPlugin("AudioProcessor",{sdkAppId:Number(this.room.sdkAppId),userId:this._room.userId,userSig:this.room.userSig,isScreenAudioNeedAudioProcess:!0,isLocalAudioNeedAudioProcess:!1})}catch(a){this._log.warn("start audioProcessor plugin failed: ",a)}}})}_onLocalTrackCaptured({track:e}){e.kind==="audio"&&(!ze||ls(ze))&&(this._initActiveSpeaker(),S.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return f(this,null,function*(){if(ze&&!ls(ze))this.emit(U.DEVICE_CHANGED,{type:"speaker",action:"active",device:ze});else{let e=yield vr();e[0]&&!ls(e[0])?(ze=e[0],this.emit(U.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):S.on("102",this._onLocalTrackCaptured,this)}})}_onAudioAvailable({userId:e}){let t=this._remoteAudioMuteMap.has(e)?this._remoteAudioMuteMap.get(e):this._remoteAudioMuteMap.get("*");(t===!1||this._room.autoReceiveAudio&&!t)&&this._doStartRemoteAudio({userId:e}).catch(()=>{})}_onVideoAvailable({userId:e,streamType:t}){if(!this._room.autoReceiveVideo)return;let r=this._room.remotePublishedUserMap.get(e);if(r){let s=t==="main"?r.remoteVideoTrack:r.remoteAuxiliaryTrack,n=[s];this._room.autoReceiveAudio&&r.remoteAudioTrack.isAvailable&&n.push(r.remoteAudioTrack),this._room.subscribe(...n).then(()=>{this._emitTrackEvent(s)}).catch(()=>{})}}_onAudioUnavailable({userId:e,muteState:t}){t.hasAudio&&t.audioMuted||this._stopRemoteAudio({userId:e},!1).catch(()=>{})}_onVideoUnavailable({userId:e,streamType:t}){this._stopRemoteVideo({userId:e,streamType:t},!1).catch(()=>{})}sendSEIMessage(e,t){var s;let r=this._plugins.get("SEI");r&&(r.update({buffer:e,options:w(M({seiPayloadType:243},t),{small:!!((s=this._localVideoTrack)!=null&&s.small)})}),y.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,r;(r=(t=this._room).sendCustomMessage)==null||r.call(t,e),y.addCount({key:500001,useUV:!0})}callExperimentalAPI(e,t){return f(this,null,function*(){return this._log.info(`callExperimentalAPI(${e}, ${JSON.stringify(t)})`),Jf.call(e,M({trtcInstance:this},t))})}static setLogLevel(e,t){R.setLogLevel(e),T(t)||(t?R.enableUploadLog():R.disableUploadLog())}static isSupported(){return fd(q.frameWorkType)}static getPermissions(r){return f(this,arguments,function*({request:e=!0,types:t=["camera","microphone"]}){e&&(yield Yn.request(t).catch(a=>{var d;return R.error(`getPermissions request failed, error: ${(d=a==null?void 0:a.message)!=null?d:a}`)}));let[s,n]=yield Promise.all([Yn.get("camera"),Yn.get("microphone")]);return{camera:s,microphone:n}})}static getCameraList(e=!0){return At(e)}static getMicrophoneList(e=!0){return It(e)}static getSpeakerList(e=!0){return vr(e)}static setCurrentSpeaker(e){return f(this,null,function*(){if(_e&&(e===So.SPEAKER||e===So.HEADSET)){let r=yield q.getMicrophoneList(),s="";if(r.forEach(n=>{n.label===e&&(s=n.deviceId)}),!s)return;Zn.forEach(n=>f(this,null,function*(){n._localAudioTrack&&(yield n.updateLocalAudio({option:{microphoneId:s}}))}));return}(yield vr()).forEach(r=>{r.deviceId===e&&(Zn.forEach(s=>{s._setCurrentSpeaker(e),s.emit(U.DEVICE_CHANGED,{type:"speaker",action:"active",device:r})}),ze=r)})})}static _addKVStat({type:e,key:t,value:r,base:s,useUV:n,version:a,max:d}){switch(a&&(ro.version=a),e){case"count":ro.addCount({key:t,useUV:n});break;case"enum":ro.addEnum({key:t,value:r,useUV:n});break;case"number":ro.addNumber({key:t,value:r,split:s,max:d});break}}};c(q,"VERSION",bh),c(q,"_loggerManager",R),c(q,"EVENT",U),c(q,"ERROR_CODE",W),c(q,"TYPE",So),c(q,"frameWorkType",30),D([Se({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"}})})],q.prototype,"use",1),D([ot(Ge.TRTC.enterRoom),Lr("room",([e],[t])=>(e.roomId||e.strRoomId)===(t.roomId||t.strRoomId)&&e.userId===t.userId&&e.sdkAppId===t.sdkAppId),Y(e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)}),Se()],q.prototype,"enterRoom",1),D([Se()],q.prototype,"exitRoom",1),D([ot(Ge.TRTC.switchRoom),Se(),ir()],q.prototype,"switchRoom",1),D([ot(Ge.TRTC.switchRole),Ao("room",{merge:(e,t)=>t}),Se()],q.prototype,"switchRole",1),D([Se()],q.prototype,"destroy",1),D([ot(Ge.TRTC.startLocalAudio),Lr("audio",([e],[t])=>{var r,s;return((r=e==null?void 0:e.option)==null?void 0:r.microphoneId)===((s=t==null?void 0:t.option)==null?void 0:s.microphoneId)}),Se()],q.prototype,"startLocalAudio",1),D([ot(Ge.TRTC.updateLocalAudio),Ao("audio",{debounce:{delay:200,getKey:()=>`${jf}-localAudio`,isNeedToDebounce:e=>{var t;return!T((t=e.option)==null?void 0:t.captureVolume)}}}),Se()],q.prototype,"updateLocalAudio",1),D([xr("audio"),Se()],q.prototype,"stopLocalAudio",1),D([ot(Ge.TRTC.startLocalVideo),Lr("video",([e],[t])=>{var r,s;return((r=e==null?void 0:e.option)==null?void 0:r.cameraId)===((s=t==null?void 0:t.option)==null?void 0:s.cameraId)}),Se()],q.prototype,"startLocalVideo",1),D([ot(Ge.TRTC.updateLocalVideo),Ao("video"),Se()],q.prototype,"updateLocalVideo",1),D([xr("video"),Se()],q.prototype,"stopLocalVideo",1),D([ot(Ge.TRTC.startScreenShare),Lr("screen",()=>!0),Se()],q.prototype,"startScreenShare",1),D([ot(Ge.TRTC.updateScreenShare),Ao("screen"),Se()],q.prototype,"updateScreenShare",1),D([Se()],q.prototype,"stopScreenShare",1),D([ot(Ge.TRTC.startRemoteVideo),Lr(e=>`v${e.userId}${e.streamType}`,()=>!0),Se({getRemoteId:e=>`${e.userId}_${e.streamType}`})],q.prototype,"startRemoteVideo",1),D([ot(Ge.TRTC.updateRemoteVideo),Ao(e=>`v${e.userId}${e.streamType}`),Se({getRemoteId:e=>`${e.userId}_${e.streamType}`})],q.prototype,"updateRemoteVideo",1),D([ot(Ge.TRTC.stopRemoteVideo),Y(e=>function(t){return f(this,null,function*(){if(t.userId==="*"){let r=[];return this._room.remotePublishedUserMap.forEach(s=>{this._remoteVideoConfigMap.has(`${s.userId}_main`)&&r.push(this.stopRemoteVideo({streamType:"main",userId:s.userId}).catch(()=>{})),this._remoteVideoConfigMap.has(`${s.userId}_sub`)&&r.push(this.stopRemoteVideo({streamType:"sub",userId:s.userId}).catch(()=>{}))}),Promise.all(r)}return e.call(this,t)})}),Se({getRemoteId:e=>`${e.userId}_${e.streamType}`})],q.prototype,"stopRemoteVideo",1),D([xr(e=>`v${e.userId}${e.streamType}`)],q.prototype,"_stopRemoteVideo",1),D([ot(...Ge.TRTC.muteRemoteAudio),Se({getRemoteId:e=>e})],q.prototype,"muteRemoteAudio",1),D([Nh(...Ge.TRTC.setRemoteAudioVolume),Ff(200,e=>e),Se({getRemoteId:e=>e})],q.prototype,"setRemoteAudioVolume",1),D([hc("start"),Ct(e=>{var t;return(t=e.afterStart)==null?void 0:t.call(e)}),Lr((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t)),Se({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Yl[e.getName()],ignoreLog:e=>e.getName()==="Debug",ignoreErrorLog:e=>e.getName()==="AudioProcessor"})],q.prototype,"startPlugin",1),D([hc("update"),Ao((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t),{merge:(e,t)=>(ei(e[1],t[1]),e)}),Se({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Zl[e.getName()]})],q.prototype,"updatePlugin",1),D([hc("stop"),xr((e,t)=>{if(e.disableRandomCall)return null;let r=e.getGroup(t),s=e.getAlias();return r==="*"?new RegExp(`${s}.*`):s+r}),Se({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Kl[e.getName()]})],q.prototype,"stopPlugin",1),D([Nh(...Ge.TRTC.enableAudioVolumeEvaluation)],q.prototype,"enableAudioVolumeEvaluation",1),D([Se()],q.prototype,"getVideoSnapshot",1),D([Se()],q.prototype,"_setCurrentSpeaker",1),D([Lr(e=>`a${e.userId}`,()=>!0)],q.prototype,"_startRemoteAudio",1),D([Y(e=>function(t){return f(this,null,function*(){return t.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(r=>this._stopRemoteAudio(w(M({},t),{userId:r.userId})).catch(()=>{}))):e.call(this,t)})}),xr(e=>`a${e.userId}`)],q.prototype,"_stopRemoteAudio",1),D([xr("room")],q.prototype,"_exitRoom",1),D([xr("screen")],q.prototype,"_stopScreenShare",1),D([ot(...Ge.TRTC.sendSEIMessage),Ih({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...e)=>e[0].byteLength})],q.prototype,"sendSEIMessage",1),D([ot(Ge.TRTC.sendCustomMessage),Ih({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],q.prototype,"sendCustomMessage",1),D([wr()],q,"create",1),D([ot(Ge.TRTC.create)],q,"_create",1),D([wr()],q,"setLogLevel",1),D([wr()],q,"isSupported",1),D([wr(),Se()],q,"getPermissions",1),D([wr()],q,"getCameraList",1),D([wr()],q,"getMicrophoneList",1),D([wr()],q,"getSpeakerList",1);var Hh=q,Kn=Hh;var $h=class{constructor(){c(this,"_set",new Set);S.on(A.LEAVE_SUCCESS,this.delete,this),S.on(A.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess,this)}add({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,e||i.roomId,i.sdkAppId,i.useStringRoomId);this._set.add(t)}delete({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,i.roomId||e,i.sdkAppId,i.useStringRoomId);this._set.delete(t)}getKey(i,e,t,r){return`${t}_${e}_${i}_${r}`}isJoined({userId:i,roomId:e,sdkAppId:t,room:r}){return r.scene==="rtc"?!1:this._set.has(this.getKey(i,e,t,r.useStringRoomId))}handleSwitchRoomSuccess({room:i,currentRoomId:e,targetRoomId:t}){i.scene!=="rtc"&&(this._set.delete(this.getKey(i.userId,e,i.sdkAppId,i.useStringRoomId)),this._set.add(this.getKey(i.userId,t,i.sdkAppId,i.useStringRoomId)))}};function YS(){return f(this,null,function*(){let o,i;try{let m=yield It();o=m&&m.length}catch(m){}try{let m=yield At();i=m&&m.length}catch(m){}let e={microphone:o,camera:i},{isH264EncodeSupported:t,isVp8EncodeSupported:r,isH264DecodeSupported:s,isVp8DecodeSupported:n,isH265EncodeSupported:a,isH265DecodeSupported:d}=this.checkSystemResult.detail,l=vi.basis(),u={webRTC:l.isWebRTCSupported,getUserMedia:l.isGetUserMediaSupported,webSocket:l.isWebSocketsSupported,screenShare:l.isScreenShareSupported,webAudio:l.isWebAudioSupported,h264Encode:t,h264Decode:s,vp8Encode:r,vp8Decode:n,h265Encode:a,h265Decode:d},h={browser:l.browser,os:l.os,trtc:u,devices:e},p={isWebCodecSupported:l.isWebCodecSupported,isMediaSessionSupported:l.isMediaSessionSupported,isWebTransportSupported:l.isWebTransportSupported};se.uploadEvent({log:`trtcstats-${JSON.stringify(h)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(h)}`),se.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(p)}`,userId:this.userId}),uu()})}function zf(){return Y(o=>{let i=new $h;return function(e,t,r){return f(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=t,e.privateMapKey=e.privateMapKey||"",this.isJoined)throw new v({code:I.INVALID_OPERATION,message:$({key:B.INVALID_JOIN})});if(this.checkDestroy(),i.isJoined({userId:this.userId,roomId:s,sdkAppId:this.sdkAppId,room:this}))throw new v({code:I.INVALID_OPERATION,message:$({key:B.REPEAT_JOIN,data:this.userId})});i.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}`),S.emit(A.JOIN_START,{room:this,roomId:s,params:e});let n=Nt.getEnv();n||(n=$i.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(_a.OLD_CLOUD_LADDER)?n=$i.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(_a.WEBRTC)&&(n=$i.WEBRTC))),se.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:s}),vi.checkSystemRequirementsInternal(r).then(a=>{this.checkSystemResult=a,YS.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Nt.getEnv()&&(yield this.schedule(e,r));let a=yield o.call(this,e,t,r);return this.roomId=s,this._joinedTimestamp=Nt.performanceNow(),S.emit(A.JOIN_SUCCESS,{room:this}),r===30&&!e.component&&se.uploadEvent({log:`stat-conv-${Number(ni)}-${location.hostname}`,userId:this.userId}),a}catch(a){throw i.delete({room:this,roomId:s}),S.emit(A.JOIN_FAILED,{room:this,error:a}),a}})}})}var Qf=()=>Y(o=>function(...i){return f(this,null,function*(){S.emit(A.LEAVE_START,{room:this}),yield o.call(this,...i),S.emit(A.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function Yf(){return Y(o=>function(...i){let e=o.apply(this,i);return i.forEach(t=>!t.isSubscribed&&t.subscribe(e)),e})}var Kf=Je(nt());var Ie={SETUP_SUCCESS:"1",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",RECONNECT_FAILED:"4",SETUP_FAILED:"5",DISCONNECTED:"6",CLOSE:"7",ONLINE:"8"};var Jt={CLIENT_BANNED:9,CHANNEL_SETUP_RESULT:19,CHANNEL_RECONNECT_RESULT:514,JOIN_ROOM_RESULT:20,PEER_JOIN:4134,PEER_LEAVE:4135,STREAM_ADDED:16,STREAM_REMOVED:18,UPLINK_NETWORK_STATS:22,UPDATE_REMOTE_MUTE_STAT:23,PUBLISH_RESULT:4098,PUBLISH_STATE_CHANGE_RESULT:4112,UNPUBLISH_RESULT:4100,SUBSCRIBE_RESULT:4102,UNSUBSCRIBE_RESULT:4104,SUBSCRIBE_CHANGE_RESULT:4106,MUTE_RESULT:4108,UPDATE_OFFER_RESULT:4128,START_PUBLISH_TENCENT_CDN_RES:1286,STOP_PUBLISH_TENCENT_CDN_RES:1288,START_PUBLISH_GIVEN_CDN_RES:777,STOP_PUBLISH_GIVEN_CDN_RES:779,START_MIX_TRANSCODE_RES:781,STOP_MIX_TRANSCODE_RES:783,START_PUBLISH_CDN_STREAM_RES:8196,UPDATE_PUBLISH_CDN_STREAM_RES:8198,STOP_PUBLISH_CDN_STREAM_RES:8200,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772,REBUILD_PEER_CONNECTION_RES:4150,SPC_PUBLISH_RESULT:4146,SPC_SUBSCRIBE_RESULT:4156,ABILITY_STATUS_REPORT_RESULT:4158,SERVER_FIRST_PACKAGE_RECEIVED:5e3,RECEIVE_CUSTOM_MSG:4140,FALLBACK_CODEC:66,SEND_SWITCH_ROOM_RES:4160,SEND_SWITCH_ROOM_SUBED_REQ:4161,UPDATE_NETWORK_TIME_RESULT:5001,CUSTOM_CMD_RES:8220},Zf=[Jt.UPDATE_REMOTE_MUTE_STAT,Jt.UPLINK_NETWORK_STATS,Jt.USER_LIST_RES,Jt.MUTE_RESULT,Jt.SERVER_FIRST_PACKAGE_RECEIVED,Jt.RECEIVE_CUSTOM_MSG,Jt.UPDATE_NETWORK_TIME_RESULT],J={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",START_PUBLISH_CDN_STREAM_RES:"start-publish-cdn-stream-res",UPDATE_PUBLISH_CDN_STREAM_RES:"update-publish-cdn-stream-res",STOP_PUBLISH_CDN_STREAM_RES:"stop-publish-cdn-stream-res",USER_LIST_RES:"user-list-res",SWITCH_ROLE_RES:"switch_role_res",MUTE_RESULT:"mute-result",UPDATE_CONSTRAINT_CONFIG_RES:"update-contraint-config-res",REBUILD_PEER_CONNECTION_RES:"rebuild-pc-res",SPC_PUBLISH_RESULT:"spc-publish-result",SPC_SUBSCRIBE_RESULT:"spc-subscribe-result",ABILITY_STATUS_REPORT_RESULT:"ability-status-report",SERVER_FIRST_PACKAGE_RECEIVED:"first-pkg-received",RECEIVE_CUSTOM_MSG:"receive-custom-msg",FALLBACK_CODEC:"fallback-codec",SEND_SWITCH_ROOM_RES:"send-switch-room-res",SEND_SWITCH_ROOM_SUBED_REQ:"send-switch-room-subed-res",UPDATE_NETWORK_TIME_RESULT:"update_network_time_result",CUSTOM_CMD_RES:"custom-cmd-res"},Z={PUBLISH_CHANGE:"publish_change",JOIN_ROOM:"join",LEAVE_ROOM:"leave",ON_QUALITY_REPORT:"quality_report",UPDATE_MUTE_STAT:"mute_uplink",PUBLISH:"publish",PUBLISH_STATE_CHANGE:"publish_state_change",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",RECEIVE_DATA_USER_LIST:"receive_data_userlist",UNSUBSCRIBE:"unsubscribe",SUBSCRIBE_CHANGE:"subscribe_change",START_PUBLISH_TENCENT_CDN:"start_publishing",STOP_PUBLISH_TENCENT_CDN:"stop_publishing",START_PUBLISH_GIVEN_CDN:"start_push_user_cdn",STOP_PUBLISH_GIVEN_CDN:"stop_push_user_cdn",START_MIX_TRANSCODE:"start_mcu_mix",STOP_MIX_TRANSCODE:"stop_mcu_mix",START_PUBLISH_CDN_STREAM:"start_publish_cdn_stream",UPDATE_PUBLISH_CDN_STREAM:"update_publish_cdn_stream",STOP_PUBLISH_CDN_STREAM:"stop_publish_cdn_stream",GET_USER_LIST:"get_user_list",SWITCH_ROLE:"change_role",UPDATE_CONSTRAINT_CONFIG:"update_constraint_config",REBUILD_PEER_CONNECTION:"rebuild_pc",READY_TO_RECEIVE_DATA:"ready_to_receive",SPC_JOIN_ROOM:"join/v2",SPC_PUBLISH:"publish/v2",SPC_SUBSCRIBE:"subscribe/v3",ABILITY_STATUS_REPORT:"ability_status_report",RECONNECT_WS:"reconnect",SEND_CUSTOM_MSG:"channel_msg",SWITCH_ROOM:"switch_room",UPDATE_NETWORK_TIME:"update_network_time",CUSTOM_CMD:"abstract_cmd"};var Rc=new Set;function e_(o){let i=[...Rc.values()].find(e=>e.room.userId===o&&!e.room.isJoined);return i||null}var KS=["autoTest","relayInnerIp","relayOuterIp","mcd","newRelay","clientIp"],ys=class extends Kf.default{constructor(e){var r,s,n;super();c(this,"room");c(this,"sdkAppId");c(this,"userId");c(this,"userSig");c(this,"url");c(this,"backupUrl");c(this,"destroyed",!1);c(this,"_socketInUse");c(this,"_socket");c(this,"_backupSocket");c(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,bakRelayIps:[],reportToken:void 0});c(this,"_currentState","DISCONNECTED");c(this,"_isReconnecting",!1);c(this,"_seq",0);c(this,"_log");c(this,"_lastMessageTime",-1);c(this,"_connectStartTime",-1);c(this,"_stopConnectRetry");c(this,"_isFirstConnect",!0);c(this,"bytesSent",0);c(this,"bytesReceived",0);c(this,"keepAlive",!1);c(this,"signalDomainWhenUnifiedProxy");c(this,"stopKeepAliveTimeout");c(this,"rtt",0);this.room=e.room,this.sdkAppId=e.sdkAppId,this.userId=e.userId,this.userSig=e.userSig,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy;let t=((s=(r=this.room.scheduleResult)==null?void 0:r.config)==null?void 0:s.keepAliveClient)||0;(n=this.room.joinParams)!=null&&n.keepAlive&&!t&&(t=1),t-Rc.size>0&&this.room.enableSPC&&(this.keepAlive=!0,Rc.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=R.createLogger({parent:this.room.getLogger(),id:"ws",userId:this.userId,sdkAppId:this.sdkAppId}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get race(){return this.room.enableSPC&&!this.room.proxy_ws}get urlParam(){let e=`?sdkAppId=${encodeURIComponent(this.sdkAppId)}&userId=${encodeURIComponent(this.userId)}&userSig=${encodeURIComponent(this.userSig)}&keepAlive=${encodeURIComponent(Number(this.keepAlive))}`;this.signalDomainWhenUnifiedProxy&&(e+=`&signalDomain=${encodeURIComponent(this.signalDomainWhenUnifiedProxy)}`);let t=new URLSearchParams(location.search);return KS.forEach(r=>{let s=t.get(`trtc_${r}`);s&&(e+=`&${r}=${encodeURIComponent(s)}`)}),this.race?`${e}&race=1`:e}get _urlWithParam(){return`${this.url}${this.race?"/v2/ws":""}${this.urlParam}`}get _backupUrlWithParam(){return`${this.backupUrl}${this.race?"/v2/ws":""}${this.urlParam}`}get isConnected(){return this._currentState==="CONNECTED"}get isConnecting(){return this._currentState==="CONNECTING"}get isOnline(){return this._currentState==="CONNECTED"&&Date.now()-this._lastMessageTime<12*1e3}connect(){return f(this,arguments,function*(e=10*1e3){if(this.isConnected)return Promise.resolve();this._log.info(`connect to [${this.url}, ${this.backupUrl}] ${this.race?"race":""}${e?` timeout: ${e}`:""} keepAlive: ${Number(this.keepAlive)}`),this.emitConnectionStateChanged("CONNECTING"),this._connectStartTime=V();let t=[this.connectWS({url:this._urlWithParam,isMain:!0,timeout:e})];this.race&&this._backupUrlWithParam!==this._urlWithParam&&t.push(this.connectWS({url:this._backupUrlWithParam,isMain:!1,timeout:e})),this._socketInUse=yield Xr(t),this.unbindAndCloseSocket(this._socketInUse===this._socket?_.BACKUP:_.MAIN),this._isFirstConnect&&(y.addSuccessEvent({key:521720}),this._isFirstConnect=!1),this.emitConnectionStateChanged("CONNECTED")})}connectWS({url:e,timeout:t,isMain:r}){let s=new WebSocket(e);this.bindSocket(s),r?this._socket=s:this._backupSocket=s;let n=-1;return new Promise((a,d)=>{s.onclose=d,s.onerror=d,s.onopen=()=>a(s),t&&(n=setTimeout(()=>{this.unbindAndCloseSocket(r?_.MAIN:_.BACKUP),d(new v({code:I.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))},t))}).finally(()=>{s.onclose=null,s.onerror=null,s.onopen=null,clearTimeout(n)})}bindSocket(e){e.addEventListener("close",this.onclose),e.addEventListener("error",this.onerror),e.addEventListener("message",this.onmessage)}unbindSocket(e){e.removeEventListener("close",this.onclose),e.removeEventListener("error",this.onerror),e.removeEventListener("message",this.onmessage)}unbindAndCloseSocket(e){if(e===_.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(t){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(t){}this._backupSocket=null}}onclose(e){e.target===this._socketInUse&&(this._log.warn(`${e.target===this._socket?"main":"backup"} is closed code:${e.code} ${e.reason}`),this.emitConnectionStateChanged("DISCONNECTED"),(!e.wasClean||e.code!==1e3)&&this.startReconnection(),this.room.isJoining&&this.emit(Ie.SETUP_FAILED,new v({code:I.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onclose"})))}onerror(e){this._log.error(`${e.target===this._socket?"main":"backup"} error observed`),this.emitConnectionStateChanged("DISCONNECTED"),e.target===this._socketInUse&&(this.unbindAndCloseSocket(_.MAIN),this.unbindAndCloseSocket(_.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(Ie.SETUP_FAILED,new v({code:I.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(e){if(!this.isConnected)return;let{isOnline:t}=this;this._lastMessageTime=Date.now(),t||this.emit(Ie.ONLINE),this.bytesReceived+=Gs(e.data);let r=JSON.parse(e.data),{cmd:s,data:n}=r,a=Object.values(Jt),l=Object.keys(Jt)[a.indexOf(s)],u=J[l]||s;switch(Zf.includes(s)||(this._log.debug(`received ${s} msg: ${e.data}`),u&&this._log.info(`Received event: [ ${u} ]`)),s){case Jt.CHANNEL_SETUP_RESULT:{if(r.code===0)this._signalInfo.clientIp=n.clientIp,this._signalInfo.signalIp=n.signalInnerIp,n.svrTime&&da(n.svrTime-new Date().getTime()),this._log.info(`ChannelSetup Success ${V()-this._connectStartTime}`),y.addSuccessEvent({key:521701,cost:V()-this._connectStartTime}),this._connectStartTime=-1,this.emit(Ie.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let h=new v({code:I.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:r.code,message:$({key:B.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:r.code,errorMsg:r.message}})});this._log.error(`${r.code}, ${r.message}`),this.close(),y.addFailedEvent({key:521701,error:h}),this.emit(Ie.SETUP_FAILED,h)}break}case Jt.JOIN_ROOM_RESULT:{r.code===0&&(this._signalInfo.relayIp=n.relayOuterIp,this._signalInfo.relayInnerIp=n.relayInnerIp,this._signalInfo.bakRelayIps=n.bakRelayIps,this._signalInfo.relayPort=n.relayPort,this._signalInfo.tinyId=r.tinyId,this._signalInfo.endReportExtend=n.endReportExtend,this._signalInfo.reportToken=n.reportToken,this._log.info(`signalIp:${this._signalInfo.signalIp} clientIp:${this._signalInfo.clientIp} relayIp: ${this._signalInfo.relayIp}`)),this.emit(u,{data:r});break}default:this.emit(String(u),{data:r});break}}reGetSignalChannelUrl(){return f(this,null,function*(){try{if(!this.room.joinParams)return;xt(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(e){}})}startReconnection(){if(!this._socketInUse)return;this._socketInUse.onclose=null,this._socketInUse.close(4011);let e=this._socketInUse===this._socket;this.unbindAndCloseSocket(e?_.MAIN:_.BACKUP),this._socketInUse=null,this.emitConnectionStateChanged("DISCONNECTED"),this.reconnect()}reconnect(){return f(this,null,function*(){if(!this._isReconnecting){if(!this.room.isJoined&&this.keepAlive){this.close();return}this._isReconnecting=!0;try{this._log.warn("reconnect"),yield this.connect();let{roomId:e,useStringRoomId:t}=this.room,{relayIp:r,relayInnerIp:s,relayPort:n}=this._signalInfo,{data:a}=yield this.sendWaitForResponse({command:Z.RECONNECT_WS,data:{roomId:e,useStringRoomId:t,relayInnerIp:s,relayOuterIp:r,relayPort:n},responseCommand:J.CHANNEL_RECONNECT_RESULT});a.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),y.addSuccessEvent({key:521702,cost:V()-this._connectStartTime}),this._connectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(y.addFailedEvent({key:521702,error:a.code}),this._log.warn(`reconnect failed, ${a.code} ${a.message}`),this.room.reJoin())}catch(e){this._log.error(e),this.room.reJoin()}}})}send(e,t={}){if(this.isConnected&&!this.room.isLeft){let r={cmd:e,data:t,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},s=JSON.stringify(r);return this._socketInUse.send(s),this.bytesSent+=Gs(s),r.seq}}sendWaitForResponse({command:e,data:t,timeout:r=5e3,responseCommand:s,commandDesc:n,enableLog:a=!0,addReceiveTime:d=!1}){return new Promise((l,u)=>{let h=()=>{clearTimeout(p),u(new v({code:I.API_CALL_ABORTED,message:`${e} aborted due to connection closed`}))};this.once(Ie.CLOSE,h);let p=setTimeout(()=>{this.off(s,m),this.off(Ie.CLOSE,h);let E=new v({code:I.API_CALL_TIMEOUT,message:$({key:B.API_CALL_TIMEOUT,data:{commandDesc:n,command:e}})});a&&this._log.warn(E),u(E)},r),m=E=>{E.data.seq===g&&(clearTimeout(p),this.off(s,m),this.off(Ie.CLOSE,h),d&&(E.data.receiveTime=Date.now()),l(E))};this.on(s,m);let g=this.send(e,t)})}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:r,retries:s=0,retryTimeout:n=0}=e;return Ri({retryFunction:this.sendWaitForResponse,onError:({retry:a,reject:d,error:l})=>{!this.room.isJoined||this.destroyed||l.code===I.API_CALL_ABORTED?d(l):this.isOnline?a():(this._log.warn(`retry ${r} when connected`),this.once(Ie.ONLINE,a))},onRetrying:a=>{this._log.warn(`${t||r} timeout observed, retrying [${a}/${s}]`)},settings:{retries:s,timeout:n},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),clearTimeout(this.stopKeepAliveTimeout),Rc.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,bakRelayIps:[],endReportExtend:void 0,reportToken:void 0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(_.MAIN),this.unbindAndCloseSocket(_.BACKUP),this.emitConnectionStateChanged("DISCONNECTED"),this.emit(Ie.CLOSE)}destroy(){this.close(),this.destroyed=!0}getBackupRelayIpPair(){var t;let e=(t=this._signalInfo.bakRelayIps)==null?void 0:t.shift();return e&&(e.relayPort=e.relayPort||this._signalInfo.relayPort),e}clearBakRelayIps(){this._signalInfo.bakRelayIps=[]}stopKeepAliveIn(e=3600){if(this.keepAlive){this._log.info(`stopKeepAlive in ${e}s`),this.stopKeepAliveTimeout=setTimeout(()=>{this.keepAlive=!1,this._log.info(`close due to not used ${e}s`),this.close(),this.off(J.JOIN_ROOM_RESULT,t)},e*1e3);let t=r=>{r.data.code===0&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(J.JOIN_ROOM_RESULT,t))};this.on(J.JOIN_ROOM_RESULT,t)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info(`${this._currentState} -> ${e}`),this.emit(Ie.CONNECTION_STATE_CHANGED,{prevState:this._currentState,state:e}),this._currentState=e,e==="CONNECTED"?this.emit(Ie.CONNECTED):e==="DISCONNECTED"&&this.emit(Ie.DISCONNECTED))}};D([Mt({settings:{retries:1/0,timeout:2e3},onError(e,t){!this.room.isDestroyed&&!this.destroyed&&(this._isFirstConnect&&(y.addFailedEvent({key:521720,error:e}),this._isFirstConnect=!1),t())},onRetrying(e,t){this._log.warn(`retrying to connect ${e}`),e>=3&&e%3===0&&this.reGetSignalChannelUrl(),t&&(this._stopConnectRetry=t,(this.room.isDestroyed||this.destroyed)&&t())}})],ys.prototype,"connect",1);var t_=Je(nt());var Wh=0,Gh=!1,yc=new Set,eI=o=>Wh>2&&!Gh&&yc.size===0&&o,Jh=!1,ft=class{constructor(i){c(this,"userId");c(this,"tinyId");c(this,"_sdpSemantics");c(this,"_isUplink");c(this,"_room");c(this,"_log");c(this,"_signalChannel");c(this,"_isErrorObserved",!1);c(this,"_waitForPeerConnectionConnectedPromise");c(this,"_waitForPeerConnectionConnectedPromiseReject",null);c(this,"_peerConnection",null);c(this,"_emitter",new t_.default);c(this,"_currentState","DISCONNECTED");c(this,"_isReconnecting",!1);c(this,"_reconnectionCount",0);c(this,"_reconnectionTimer",-1);c(this,"_isFirstConnection",!0);c(this,"_prevTime",-1);c(this,"_localAddress");c(this,"_remoteAddress");this.userId=i.userId,this.tinyId=i.tinyId,this._room=i.room,this._sdpSemantics=i.room.sdpSemantics,this._isUplink=i.isUplink,this._log=i.room.getLogger().createChild({id:"n-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=i.signalChannel}beforeConnect(){this._prevTime<0&&(this._prevTime=V())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,y.addSuccessEvent({key:521705,cost:Math.min(V()-this._prevTime,30*1e3)})):this._isReconnecting&&y.addSuccessEvent({key:521706,cost:V()-this._prevTime}),this._prevTime=-1}catch(i){throw this._isFirstConnection?(this._isFirstConnection=!1,y.addFailedEvent({key:521705,error:i})):this._isReconnecting&&this._reconnectionCount>=3&&y.addFailedEvent({key:521706,error:i}),i}}initialize(){let i={iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"};this._peerConnection=new RTCPeerConnection(i),this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this)}close(i){this._log.info("close connection"),this._emitter.emit("closed",i),this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),yc.delete(this)}closePeerConnection(i=!1){this._peerConnection&&(this._log.info("close pc"),this._peerConnection.onconnectionstatechange=null,this._peerConnection.close(),this._peerConnection=null,i&&this.emitConnectionStateChangedEvent("DISCONNECTED")),this._waitForPeerConnectionConnectedPromiseReject&&this._waitForPeerConnectionConnectedPromiseReject(new v({code:I.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return Qt;let i=null;if(this._isUplink){if(!Rr()||this._peerConnection.getSenders().length===0)return Qt;i=this._peerConnection.getSenders()[0].transport}else{if(!oo()||this._peerConnection.getReceivers().length===0)return Qt;i=this._peerConnection.getReceivers()[0].transport}return i?i.state:Qt}onConnectionStateChange(i){let e=this._peerConnection.iceConnectionState,t=this.getDTLSTransportState();if(this._log.info(`connectionState: ${i.target.connectionState}, ICE: ${e}, DTLS: ${t}`),i.target.connectionState===Ce.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),i.target.connectionState===Ce.FAILED||i.target.connectionState===Ce.CLOSED){let r=`connection ${i.target.connectionState}. ICE Transport state: ${e}, DTLS Transport state: ${t}`,s=new v({message:r,code:I.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",s)}(i.target.connectionState===Ce.CONNECTED||i.target.connectionState===Ce.COMPLETED)&&(this.logSelectedCandidate(),se.logSuccessEvent({userId:this._room.userId,eventType:Ze.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(i){return i===this._currentState?!1:(i==="CONNECTED"?(Wh=0,Gh=!1,Jh=!0,yc.add(this)):yc.delete(this),S.emit(A.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:i,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:i}),this._currentState=i,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}logSelectedCandidate(){return f(this,null,function*(){if(!this._peerConnection)return;let i=yield this._peerConnection.getStats();for(let[,e]of i)if(Cr(e)){let t=i.get(e.localCandidateId),r=i.get(e.remoteCandidateId);t&&(this._log.info(`local candidate: ${t.candidateType} ${t.protocol}:${t.ip||t.address}:${t.port} ${t.networkType||""} ${t.candidateType==="relay"?`relayProtocol:${t.relayProtocol}`:""}`),this._localAddress=`${t.ip||t.address}:${t.port}`),r&&(this._log.info(`remote candidate: ${r.candidateType} ${r.protocol}:${r.ip||r.address}:${r.port}`),this._remoteAddress=`${r.protocol}:${r.ip||r.address}`);break}})}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise?this._waitForPeerConnectionConnectedPromise:(this._waitForPeerConnectionConnectedPromise=new Promise((i,e)=>{if(this._currentState==="CONNECTED")return i();this._waitForPeerConnectionConnectedPromiseReject=e;let t=a=>{a.state==="CONNECTED"&&(clearTimeout(n),s(),i())},r=({room:a})=>{a===this._room&&(clearTimeout(n),s(),e(new v({code:I.API_CALL_ABORTED,message:$({key:B.CONNECTION_ABORTED,data:"leave room"})})))},s=()=>{S.off(A.LEAVE_SUCCESS,r,this),this._emitter.off("connection-state-changed",t,this)},n=setTimeout(()=>{s();let a=new v({code:I.API_CALL_TIMEOUT,message:"connection timeout"});Wh+=1,eI(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),Gh=!0,this._emitter.emit("firewall-restriction")),e(a)},Fs);S.on(A.LEAVE_SUCCESS,r,this),this._emitter.on("connection-state-changed",t,this)}),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally(()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null}),this._waitForPeerConnectionConnectedPromise)}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(Ie.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=Wi()){this._log.warn(`SDK has tried reconnect for ${this._reconnectionCount} times, but all failed, please check your network`),this.stopReconnection();let i=new v({code:this._isUplink?I.UPLINK_RECONNECTION_FAILED:I.DOWNLINK_RECONNECTION_FAILED,message:$({key:this._isUplink?B.UPLINK_RECONNECTION_FAILED:B.DOWNLINK_RECONNECTION_FAILED})});return this.emitConnectionStateChangedEvent("DISCONNECTED"),this._emitter.emit("error",i),-1}return this._signalChannel.isConnected?(this._reconnectionCount+=1,this._log.warn(`reconnect() trying [${this._reconnectionCount}]`),1):(this._log.warn("reconnect() signal channel is not connected, suspend reconnection until signal is connected"),this._signalChannel.once(Ie.CONNECTED,this.reconnect,this),-1)}on(i,e,t){this._emitter.on(i,e,t)}off(i,e,t){this._emitter.off(i,e,t)}getIsReconnecting(){return this._isReconnecting}get isH264(){var i,e;return!!((e=(i=this._peerConnection)==null?void 0:i.remoteDescription)!=null&&e.sdp.includes("H264"))}setOffer(i){var e;return(e=this._peerConnection)==null?void 0:e.setLocalDescription(i)}setAnswer(i){var e;return(e=this._peerConnection)==null?void 0:e.setRemoteDescription(i)}};D([Rt(521712,!1)],ft.prototype,"setOffer",1),D([Rt(521713,!1)],ft.prototype,"setAnswer",1);var zh=Je(Xh());var De=function(o){return zh.default.parse(o)},qt=function(o){return zh.default.write(o)},c_=function(o){let i=De(o);return i.media.forEach(e=>{e.type===_.AUDIO&&e.fmtp.forEach(t=>{t.config+=";sprop-stereo=1;stereo=1"})}),qt(i)};function l_(o){let i=De(o);return i.media.forEach(e=>{var t,r;if(e.type===_.VIDEO){let s=new Set;e.rtp.forEach(({payload:a,codec:d})=>d==="H264"&&s.add(a)),e.fmtp.forEach(({payload:a,config:d})=>{let l=d.match(/apt=(\d+)/);l&&l[1]&&s.has(Number(l[1]))&&s.add(a)});let n=({payload:a})=>!s.has(a);e.rtp=e.rtp.filter(n),e.rtcpFb=(t=e.rtcpFb)==null?void 0:t.filter(n),e.fmtp=e.fmtp.filter(n),e.payloads=(r=e.payloads)==null?void 0:r.split(" ").filter(a=>!s.has(Number(a))).join(" ")}}),qt(i)}function bc(o){return Object.keys(o).filter(i=>o[i])}var Ns=class Ns extends ft{constructor(e){super(w(M({},e),{isUplink:!1}));c(this,"_flag",0);c(this,"isRobot",!1);c(this,"role","anchor");c(this,"remoteAudioTrack");c(this,"remoteVideoTrack");c(this,"remoteAuxiliaryTrack");c(this,"ssrc",{audio:0,video:0,auxiliary:0});c(this,"_isSDPExchanging",!1);c(this,"_videoCodec");this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=e.remoteAudioTrack||new Ei(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new Pi(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new Ts(this._room,this)}get videoCodec(){var t,r;let e=(r=(t=this._peerConnection)==null?void 0:t.remoteDescription)==null?void 0:r.sdp;return e?e.includes("H264")?"h264":"vp8":this._videoCodec||"h264"}set videoCodec(e){this._videoCodec=e}get subscribeState(){let e={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(this.remoteVideoTrack.mediaType&8?e.smallVideo=!0:e.video=!0),this.remoteAudioTrack.isSubscribed&&(e.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(e.auxiliary=!0),e}get muteState(){return Kt(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,r,s;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(r=this.remoteVideoTrack)==null||r.onFlagChanged(),(s=this.remoteAuxiliaryTrack)==null||s.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===_.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var s,n;let t=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&t!==e&&((s=this.remoteVideoTrack)==null||s.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),r}onTrack(e){let t=e.streams[0],{track:r}=e,s=t.id===Vs?_.MAIN:_.AUXILIARY;this._log.debug(`ontrack ${s} ${r.kind}`);let n=_.AUDIO;r.kind===_.VIDEO&&(n=s===_.MAIN?_.VIDEO:_.AUXILIARY);let a=this.remoteAudioTrack;n===_.VIDEO?a=this.remoteVideoTrack:n===_.AUXILIARY&&(a=this.remoteAuxiliaryTrack),a.setInputMediaStreamTrack(r)}addRRTRLine(e){let t=e.split(`\r
|
|
58
|
+
${r.stack}`),!1}},o};var Cs=new WeakMap;function Vf(o){let i=Cs.get(o);i&&(i.forEach(e=>clearTimeout(e)),Cs.delete(o))}function Ff(o,i){return Y((e,t)=>function(...r){let s=Cs.get(this);s||(s=new Map,Cs.set(this,s));let n=i(...r),a=s.get(n);if(!a||a<=0){e.apply(this,r);let d=setTimeout(()=>{var l;(l=Cs.get(this))==null||l.delete(n)},o);s.set(n,d)}else{clearTimeout(a);let d=window.setTimeout(()=>{var l;e.apply(this,r),(l=Cs.get(this))==null||l.delete(n)},o);s.set(n,d)}})}var Hf="trtc-sdk-v5",bh="5.15.0-beta.20";function ot(...o){return Y((i,e)=>function(...t){try{uc.call(this,o,t,e,this._name)}catch(r){return Promise.reject(r)}return i.apply(this,t)})}function Nh(...o){return Y((i,e)=>function(...t){try{uc.call(this,o,t,e,this._name)}catch(r){throw r}return i.apply(this,t)})}function uc(o,i,e,t){if(Ae(o))for(let r=0;r<o.length;r++)lc.call(this,{rule:o[r],value:i[r],key:o[r].name,fnName:e,className:t});else lc.call(this,{rule:o,value:i[0],key:o.name,fnName:e,className:t})}function lc({rule:o,value:i,key:e,fnName:t,className:r}){function s(d){return{code:W.INVALID_PARAMETER,extraCode:d,fnName:t,messageParams:{key:e,rule:o,value:i}}}if(T(i)){if(o.required)throw new F(s(5001));if(T(o.defaultValue)){le(o.validate)&&o.validate.call(this,i,e,t,r,this);return}i=o.defaultValue}if(Array.isArray(o.type)){let d=!1;for(let l=0;l<o.type.length;l++)o.type[l]===null&&i===null&&(d=!0),le(o.type[l])&&i instanceof o.type[l]&&(d=!0),ie(o.type[l])&&Me(i)===o.type[l].toLowerCase()&&(d=!0);if(!d)throw new F({code:W.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:o.type.map(l=>jr(l)?wo(l):ie(l)?l:Me(l))},value:i}})}else if(!T(o.type)&&Me(i)!==o.type)throw new F(s(5002));if(o.allowEmpty===!1){let d=Q(i)&&(i===0||Number.isNaN(i)),l=ie(i)&&i.trim()==="";if(d||l)throw new F(s(5003))}if(o.notLessThanZero&&Q(i)&&i<0)throw new F(s(5006));if(!T(o.min)&&Q(i)&&i<o.min)throw new F(s(5007));if(!T(o.max)&&Q(i)&&i>o.max)throw new F(s(5008));if(ie(o.instanceOf)){if(!i||i._name!==o.instanceOf)throw new F(s(5004))}else if(le(o.instanceOf)&&!(i instanceof o.instanceOf))throw new F(s(5004));if(Array.isArray(o.values)&&!o.values.includes(i))throw new F(s(5005));let{properties:n}=o;dt(n)&&yt(i)&&Object.keys(n).forEach(d=>{lc.call(this,{rule:n[d],value:i&&i[d],key:`${d}`,fnName:t,className:r})});let{arrayItem:a}=o;dt(a)&&Ae(i)&&i.forEach((d,l)=>{lc.call(this,{rule:a,value:d,key:`${e}[${l}]`,fnName:t,className:r})}),le(o.validate)&&o.validate.call(this,i,e,t,r,this)}function Se(o={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t,ignoreLog:r,ignoreErrorLog:s}=o;return Y((n,a)=>function(...d){var m,g,E;function l(C,P,re){if(re&&re.includes(C))return"hided";if(e){let L=e(...d);if(d[L.argIndex]===P)return L.value}if(P===d||C in d)return P;try{return P instanceof HTMLElement?`id: ${P.id} type:${Me(P)}`:P instanceof MediaStreamTrack?Ma(P):(JSON.stringify(P),P)}catch(L){return`type:${Me(P)}`}}let u=(this==null?void 0:this._log)||R;if(r!=null&&r(...d))return n.apply(this,d);d.length>0?u.info(`${a}() ${JSON.stringify(d,(C,P)=>l(C,P,["userSig","privateMapKey"]))}`):u.info(`${a}()`);let h=t?t(...d):ld[a],p=(s==null?void 0:s(...d))||!1;try{let C=n.apply(this,d),P=V();if(Tr(C)){let re=`${a.includes("Plugin")?`${((g=(m=d[0]).getName)==null?void 0:g.call(m))||""} `:" "}`;return C.then(L=>(u.info(`${a}() success ${re}${i.call(this,...d)}`),y.addSuccessEvent({key:h,cost:V()-P}),L)).catch(L=>{var k;L=F.convertFrom.call(this,L,a,d.length===1?d[0]:d);let Qe=L.extraCode||L.code,N=(k=L.message)!=null&&k.includes(Qe)?"":` code:${Qe}`;throw p||u.error(`${a}() failed ${re}${i.call(this,...d)} ${L}${N} params: ${JSON.stringify(d,l)}`),y.addFailedEvent({key:h,error:L}),L})}return y.addSuccessEvent({key:h}),C}catch(C){C=F.convertFrom.call(this,C,a);let P=C.extraCode||C.code,re=(E=C.message)!=null&&E.includes(P)?"":` code:${P}`;throw p||u.error(`${a}() failed ${C}${re} params: ${JSON.stringify(d,l)}`),y.addFailedEvent({key:h,error:C}),C}})}var hc=o=>Y((i,e)=>function(t,r){return f(this,null,function*(){let s=this._plugins.get(t);if(!s)throw this._log.error(`plugin ${String(t)} is not found`),new F({code:W.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});if(le(s.constructor.isSupported)&&!s.constructor.isSupported())throw this._log.error(`plugin ${String(t)} is not supported`),new F({code:W.ENV_NOT_SUPPORTED,message:`plugin ${String(t)} is not supported`,extraCode:5210,fnName:e});return uc.call(this,s.getValidateRule(o),[r],e,"TRTC"),i.call(this,s,r)})});var mc=0,vh,ar=class ar{constructor(i){this.core=i;c(this,"log");c(this,"customAudioReferenceMap",new Map);c(this,"audioRefId",0);c(this,"audioContext",Ee());c(this,"localAudioWorkletNode");c(this,"screenAudioWorkletNode");c(this,"mixNode");c(this,"silentNode");mc=mc+1,this.log=i.log.createChild({id:`${this.getAlias()}${mc}`}),this.log.info(`created id=${this.getAlias()}${mc}`),this.installEvent()}static getStartValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,t,r,s){if(!i.room.audioManager.hasAudioTrack&&!i.room.audioManager.hasScreenAudioTrack)throw new F({code:W.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return vh||(vh=this.doPreload(i)),vh}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield tr(this.audioContext,t)}catch(r){this.log.error(`preload audioProcessor failed. ${r}`)}finally{URL.revokeObjectURL(t)}})}getName(){return ar.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(i){switch(i){case"start":return ar.getStartValidateRule(this.core);case"update":return ar.updateValidateRule;case"stop":return ar.stopValidateRule}}start(i){return f(this,null,function*(){var p,m,g,E;let{room:e}=this.core,{sdkAppId:t,userId:r,userSig:s,assetsPath:n=this.core.assetsPath,audioReference:a,processLevel:d,enableDump:l,isLocalAudioNeedAudioProcess:u=!0,isScreenAudioNeedAudioProcess:h=!1}=i;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=u,this.core.room.audioManager.isScreenAudioNeedAudioProcess=h,!n)throw new F({code:W.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload(`${n}/audioProcessor-wasm.js`),u&&!this.localAudioWorkletNode){let{sign:C,status:P,timestamp:re}=yield this.getAuthData(t,r,s);this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",t,r,re,C,P,e)}if(h&&!this.screenAudioWorkletNode){let{sign:C,status:P,timestamp:re}=yield this.getAuthData(t,r,s);this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",t,r,re,C,P,e)}this.mixNode||(this.mixNode=this.audioContext.createGain(),this.mixNode.gain.value=1),this.silentNode||(this.silentNode=this.audioContext.createConstantSource(),this.silentNode.offset.setValueAtTime(0,this.audioContext.currentTime),this.silentNode.start()),(p=this.localAudioWorkletNode)==null||p.port.postMessage({type:"enable"}),(m=this.screenAudioWorkletNode)==null||m.port.postMessage({type:"enable"}),e.audioManager.addAudioProcessor(this.mixNode,this.silentNode,this.localAudioWorkletNode,this.screenAudioWorkletNode),T(a)||a.forEach(C=>{this.customAudioReferenceMap.set(C,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:C,refId:`o-${this.audioRefId++}`})}),T(d)||(g=this.localAudioWorkletNode)==null||g.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:d}}),T(l)||(E=this.localAudioWorkletNode)==null||E.port.postMessage({type:"dump",data:{enable:l}})})}update(i){return f(this,null,function*(){var s,n,a;let{audioReference:e,enableDump:t,processLevel:r}=i;T(e)||(this.customAudioReferenceMap.forEach((d,l)=>{this.customAudioReferenceMap.delete(l),this.core.room.audioManager.updateAudioReference({type:"remove",refId:d})}),e.forEach(d=>{this.customAudioReferenceMap.set(d,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:d,refId:`o-${this.audioRefId++}`})})),T(r)||(s=this.localAudioWorkletNode)==null||s.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:r}}),T(t)||((n=this.localAudioWorkletNode)==null||n.port.postMessage({type:"dump",data:{enable:t}}),(a=this.screenAudioWorkletNode)==null||a.port.postMessage({type:"dump",data:{enable:t}}))})}stop(){return f(this,null,function*(){var e,t;let{room:i}=this.core;(e=this.localAudioWorkletNode)==null||e.port.postMessage({type:"disable"}),(t=this.screenAudioWorkletNode)==null||t.port.postMessage({type:"disable"}),yield i.audioManager.removeAudioProcessor(this.localAudioWorkletNode,this.screenAudioWorkletNode)})}destroy(){this.localAudioWorkletNode&&(this.localAudioWorkletNode.port.onmessage=null),this.screenAudioWorkletNode&&(this.screenAudioWorkletNode.port.onmessage=null),this.uninstallEvent()}getAuthData(i,e,t){return f(this,null,function*(){let r=String(Date.now()).slice(0,-3),{auth:s,sign:n,status:a,message:d}=yield JS({sdkAppId:i,userSig:t,userId:e,timestamp:r});if(!s)throw this.log.info(`audioProcessor: ${e} auth result: ${s}. Message: ${d}`),new F({code:W.INVALID_PARAMETER,message:d});return{sign:n,status:a,timestamp:r}})}initWorkletNode(i,e,t,r,s,n,a,d){i.port.postMessage({type:"init",data:{sdkAppId:String(t),userId:r,timestamp:s,sign:n,status:a}}),i.port.onmessage=l=>{var h;let{data:u}=l;switch(u.type){case"cost":let p=(u==null?void 0:u.value)>10?"info":"debug";this.log[p](`${e==="localAudio"?"":`[${e}] `}avg cost: ${u.value} max: ${u==null?void 0:u.max}(${vo(new Date(u==null?void 0:u.maxCostTimestamp))}) hist: ${(h=u==null?void 0:u.hist)==null?void 0:h.join(" ")}`);return;case"log":this.log[u.logLevel](`${e==="localAudio"?"":`[${e}] `}${u.value}`);return;case"dump":S.emit("265",{room:d,data:u.value,type:e==="localAudio"?"dump":"dump-screen-audio"});return}}}handleLocalAudioStarted(i){return f(this,null,function*(){var e;if(!(!this.hitTest(i.room)||((e=this.core.room.scheduleResult.config)==null?void 0:e.audioProcessor)!==!0))try{yield this.core.trtc.startPlugin("AudioProcessor",{sdkAppId:this.core.room.sdkAppId,userId:this.core.room.userId,userSig:this.core.room.userSig}),this.log.warn("audio processor auto start success")}catch(t){this.log.warn(`audio processor auto start failed, error: ${t}`)}})}handleLocalAudioStopped(i){return f(this,null,function*(){var e;!this.hitTest(i.room)||((e=this.core.room.scheduleResult.config)==null?void 0:e.audioProcessor)!==!0||(yield this.core.trtc.stopPlugin("AudioProcessor"))})}installEvent(){this.core.innerEmitter.on("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.on("114",this.handleLocalAudioStopped,this)}uninstallEvent(){this.core.innerEmitter.off("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.off("114",this.handleLocalAudioStopped,this)}hitTest(i){return i===this.core.room}};c(ar,"updateValidateRule",{type:"object"}),c(ar,"stopValidateRule",{type:"object"}),c(ar,"Name","AudioProcessor");var pc=ar;function GS(o,i=_.MAIN){return`https://${xi[i]||cc(o,i)}/api/v1/audioAiAuth`}function JS(r){return f(this,arguments,function*({sdkAppId:o,userId:i,userSig:e,timestamp:t}){let n=`${GS(o)}?sdkAppId=${o}&userId=${i}&userSig=${e}×tamp=${t}`,a=yield fetch(n),{data:{errCode:d,errMsg:l,sign:u,status:h}}=yield a.json();if(h==="1")return{auth:!0,sign:u,status:h,message:l};let p=Ut(o)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",m="Init RTCAudioProcessor failed.",g="";switch(d){case 1:g="Please check your params.";break;case 2:g=`You need to buy packages. Refer to: ${p}`;break;case 3:g="Server is invalid. Please contact our engineer. ";break;case 4:g=`Your packages is not active. Refer to: ${p}`;break;case 5:g=`Your packages is expired. Refer to: ${p}`;break;case 6:g="Your version is not supported.";break}return{auth:!1,status:h,message:l?`${m} Reason: ${l}. ${g}`:`${m}, ${g}`}})}var fc=0,Dh=class{constructor(i,e){c(this,"audioObjectURL");c(this,"player");c(this,"publisher");c(this,"mixInput");this.mixInput=new ds(e),i.url?(this.player=new Audio(i.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(i.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(i.track),this.mixInput.connect()}updateSettings(i){this.player&&(T(i.volume)||(this.volume=i.volume),T(i.loop)||(this.loop=i.loop),T(i.playbackRate)||(this.playbackRate=i.playbackRate))}updateListener(i){if(this.player){if(i.onDurationChange){let{onDurationChange:e}=i;this.player.ondurationchange=t=>{e(t.target.duration)}}if(i.onTimeUpdate){let e=i.onTimeUpdate,{player:t}=this;t.ontimeupdate=()=>{e(t.currentTime,t.duration)}}i.onEnded&&(this.player.onended=i.onEnded)}}reload(i){return f(this,null,function*(){if(i.url){let e=yield qn.download(i.url,{retries:3,type:"blob"});this.audioObjectURL&&URL.revokeObjectURL(this.audioObjectURL),this.audioObjectURL=URL.createObjectURL(e),this.player&&this.publisher?(this.player.src=this.audioObjectURL,this.publisher.src=this.audioObjectURL):(this.player=new Audio(this.audioObjectURL),this.player.crossOrigin="anonymous",this.publisher=new Audio(this.audioObjectURL),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher),this.updateListener(i),this.updateSettings(i))}else this.mixInput.replaceSource(i.track)})}reset(){this.seek(0),this.mixInput.connect()}seek(i){this.player&&(i<0&&i>this.player.duration||(this.player.currentTime=i,this.publisher.currentTime=i))}play(){var i,e;return Promise.all([(i=this.player)==null?void 0:i.play(),(e=this.publisher)==null?void 0:e.play()])}pause(){var i,e;(i=this.player)==null||i.pause(),(e=this.publisher)==null||e.pause()}stop(){var i;(i=this.player)==null||i.pause(),this.mixInput.disconnect()}setOperation(i){i==="pause"&&this.pause(),i==="resume"&&(this.pause(),this.play()),i==="stop"&&(this.pause(),this.seek(0))}set volume(i){!this.player||!this.publisher||(this.player.volume=i,this.publisher.volume=i)}set loop(i){!this.player||!this.publisher||(this.player.loop=i,this.publisher.loop=i)}set playbackRate(i){!this.player||!this.publisher||(this.player.playbackRate=i,this.publisher.playbackRate=i)}};function Rs(o,i){if(i&&typeof i!="function")throw new F({code:W.INVALID_PARAMETER,message:`start audioMixer plugin: param ${o} should be a function.`})}var wi=class wi{constructor(i){this.core=i;c(this,"log");c(this,"mixedMusicMap",new Map);c(this,"cacheMusicMap",new Map);fc=fc+1,this.log=i.log.createChild({id:`${this.getAlias()}${fc}`}),this.log.info(`created id=${this.getAlias()}${fc}`)}getName(){return wi.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return wi.startValidateRule;case"update":return wi.updateValidateRule;case"stop":return wi.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e}=this.core;this.core.validateSourceNode(),this.log.info(`add music source, id: ${i.id} url: ${i.url}, track: ${i.track}`);let{id:t,url:r}=i;if(this.mixedMusicMap.has(t))return;let s=this.cacheMusicMap.get(t);s?i.url?s.reset():(s.mixInput.replaceSource(i.track),s.mixInput.connect()):(s=new Dh(i,e.audioManager),this.cacheMusicMap.set(t,s)),s.updateListener(i),s.updateSettings(i);try{yield s.play()}catch(n){yield this.handleAutoPlayFailed(s,i,n)}this.mixedMusicMap.set(t,s),s.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"add",audioReference:s.mixInput.source.node,refId:`ax-${t}`}),this.log.info(`start mix audio track ${t} success.`),y.addEnum({key:502700,value:3}),this.kvUpload(i)})}handleAutoPlayFailed(i,e,t){return f(this,null,function*(){if(t.name==="NotSupportedError")this.log.error(`play failed, try to reload source. error: ${t}`),yield i.reload(e),yield i.play();else if(t.name==="NotAllowedError")if(this.core.room.enableAutoPlayDialog){let r=()=>{var s;(s=i.play())==null||s.finally(()=>{S.off("154",r,this)})};S.on("154",r,this),ns()}else this.core.trtc.emit(U.AUTOPLAY_FAILED,{userId:"",mediaType:"audio",resume:()=>f(this,null,function*(){return i.play()})});else throw t})}update(i){return f(this,null,function*(){let{id:e,operation:t,seekFrom:r,playbackRate:s}=i;this.log.info(`update music source, ${JSON.stringify(i)}`);let n=this.mixedMusicMap.get(e);if(!n){this.log.warn(`update music source failed, music id: ${e} not found.`);return}n.updateSettings(i),n.updateListener(i),T(t)||n.setOperation(t),T(r)||n.seek(r),this.kvUpload(i)})}stop(e){return f(this,arguments,function*({id:i}){if(this.mixedMusicMap.has(i)){this.log.info(`remove music source, music id: ${i}`);let t=this.mixedMusicMap.get(i);t!=null&&t.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:t.mixInput.source.node,refId:`ax-${i}`}),t==null||t.stop(),this.mixedMusicMap.delete(i)}i==="*"&&this.destroyAllMusic()})}kvUpload(i){let{track:e,loop:t,volume:r,playbackRate:s,operation:n,seekFrom:a,onTimeUpdate:d,onDurationChange:l,onEnded:u}=i;e&&y.addCount({key:502009}),t&&y.addCount({key:502001}),r&&y.addCount({key:502002}),s&&y.addCount({key:502003}),n&&y.addCount({key:502004}),a&&y.addCount({key:502005}),typeof d!="function"&&y.addCount({key:502007}),typeof u!="function"&&y.addCount({key:502008}),typeof l!="function"&&y.addCount({key:502006})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((i,e)=>{i!=null&&i.mixInput.track&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:i.mixInput.track,refId:e}),this.stop({id:e})})}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}};c(wi,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(i,e,t){if(i.url&&i.url!=="*"){let r=i.url.split("?")[0],s=["mp3","ogg","wav","flac"],n=r.split(".").pop(),a=s.indexOf(n)>=0,d=r.startsWith("blob"),l=r.startsWith("data");if(!(a||d||l))throw new F({code:W.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new F({code:W.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});Rs("onTimeUpdate",i.onTimeUpdate),Rs("onEnded",i.onEnded),Rs("onDurationChange",i.onDurationChange)}}),c(wi,"updateValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},loop:{type:"boolean"},volume:{type:"number"},seekFrom:{type:"number"},operation:{type:"string",values:["pause","resume","stop"]}},validate(i,e,t){Rs("onTimeUpdate",i.onTimeUpdate),Rs("onEnded",i.onEnded),Rs("onDurationChange",i.onDurationChange)}}),c(wi,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),c(wi,"Name","AudioMixer");var _c=wi;var gc=0,Mh,dr=class dr{constructor(i){this.core=i;c(this,"log");c(this,"audioContext",Ee("denoiser"));c(this,"workletNode");c(this,"config",{enableFarFieldReduce:!1,farFieldReduceThreshold:.5});gc=gc+1,this.log=i.log.createChild({id:`${this.getAlias()}${gc}`}),this.log.info(`created id=${this.getAlias()}${gc}`)}static startValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0},mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}},validate(e,t,r,s){if(!i.room.audioManager.hasAudioTrack)throw new F({code:W.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return Mh||(Mh=this.doPreload(i)),Mh}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield tr(this.audioContext,t)}catch(r){throw this.log.error("load worklet failed",r),r}finally{URL.revokeObjectURL(t)}})}getName(){return dr.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser"}getValidateRule(i){switch(i){case"start":return dr.startValidateRule(this.core);case"update":return dr.updateValidateRule;case"stop":return dr.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e,schedule:t}=this.core,{assetsPath:r=this.core.assetsPath}=i;if(!r)throw new F({code:W.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload(`${r}/denoiser-wasm${cu()?"":"-nosimd"}.js`),!this.workletNode){let s=String(Date.now()).slice(0,-3),{auth:n,sign:a,status:d,message:l}=yield jS(t,w(M({},i),{timestamp:s}));if(!n)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${n}. Message: ${l}`),new F({code:W.INVALID_PARAMETER,message:l});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(i.sdkAppId),userId:i.userId,timestamp:s,sign:a,status:d}}),this.workletNode.port.onmessage=u=>{var p;let{data:h}=u;if(h.type==="cost"){let m=(h==null?void 0:h.max)>20?"warn":(h==null?void 0:h.max)>10?"info":"debug";this.log[m](`avg cost: ${h.value} max: ${h==null?void 0:h.max}(${vo(new Date(h==null?void 0:h.maxCostTimestamp))}) hist: ${(p=h==null?void 0:h.hist)==null?void 0:p.join(" ")}`)}else h.type==="log"&&this.log[h.logLevel](`${h.value}`)}}this.updateConfig(i),this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(i){return f(this,null,function*(){this.updateConfig(i)})}stop(){return f(this,null,function*(){if(!this.workletNode)return;let{room:i}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield i.audioManager.removeDenoiser(this.workletNode)})}updateConfig(i){if(!this.workletNode)return;let e=!1;T(i.mode)||(i.mode===0?this.config.enableFarFieldReduce=!1:i.mode===1&&(this.config.enableFarFieldReduce=!0),e=!0),T(i.farFieldReduceThreshold)||(this.config.farFieldReduceThreshold=i.farFieldReduceThreshold,e=!0),e&&this.workletNode.port.postMessage({type:"setConfig",data:this.config})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};c(dr,"updateValidateRule",{type:"object",properties:{mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}}}),c(dr,"stopValidateRule",{type:"object"}),c(dr,"Name","AIDenoiser");var Tc=dr;function jS(s,n){return f(this,arguments,function*(o,{sdkAppId:i,userId:e,userSig:t,timestamp:r}){try{let{data:{errCode:a,errMsg:d,sign:l,status:u}}=yield o.getAbilityConfig(i,o.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:i,userId:e,userSig:t,timestamp:r});if(u==="1")return{auth:!0,sign:l,status:u,message:d};let h=Ut(i)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",p="Init RTCAIDenoiser failed.",m="";switch(a){case 1:m="Please check your params.";break;case 2:m=`You need to buy packages. Refer to: ${h}`;break;case 3:m="Server is invalid. Please contact our engineer. ";break;case 4:m=`Your packages is not active. Refer to: ${h}`;break;case 5:m=`Your packages is expired. Refer to: ${h}`;break;case 6:m="Your version is not supported.";break}return{auth:!1,status:u,message:d?`${p} Reason: ${d}. ${m}`:`${p}, ${m}`}}catch(a){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${a}`}}})}var Wf=Je(nt(),1);var Oh=class extends Wf.EventEmitter{constructor(){super();c(this,"observer");c(this,"state","nominal");this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return f(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!_e&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){se.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let t=this.stateNum,r=e[e.length-1];this.state=r.state,(this.stateNum>3||t>3)&&R.info(`${r.source}: ${r.state}`),this.emit("state-changed",{type:r.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(t){se.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},XS=new Oh,kh=XS;function Ph([o,i]){let e=i.byteLength,t=parseInt(String(e/255),10),r=e%255,s=[];s.push(0,0,0,1,6,o);for(let a=0;a<t;a++)s.push(255);s.push(r);let n=new DataView(i);return s.push(...new Uint8Array(n.buffer)),s.push(128),new sr(new DataView(new Uint8Array(s).buffer),!0)}function Lh(o){return o.type==="empty"||o.data.byteLength===0}function xh(o){return o.getInt32(0)===1&&o.getInt8(4)===6}function wh(o){let i=0,e=0,t=new DataView(o);for(let r=0;r<o.byteLength;r++)switch(t.getUint8(r)){case 0:i++;break;case 1:(i===2||i===3)&&e++,i=0;break;default:i=0;break}return e}function Uh({frame:o,seiMessageList:i}){if(!i||i.length===0||o.data.byteLength===0)return o;let t=9-wh(o.data);if(t<=0)return o;let r=i.splice(0,t).reverse().map(Ph),s=r.reduce((u,h)=>u+h.dataView.byteLength,0),n=new ArrayBuffer(s+o.data.byteLength),a=new DataView(n),d=new DataView(o.data),l=0;for(let u=0;u<r.length;u++)for(let h=0;h<r[u].dataView.byteLength;h++)a.setInt8(l++,r[u].dataView.getInt8(h));for(let u=0;u<o.data.byteLength;u++)a.setInt8(l++,d.getInt8(u));return o.data=n,o}function Vh({frame:o,onSEI:i}){try{let e=new DataView(o.data);if(Lh(o)||!xh(e))return o;let t=[],r=0,s=-1,n=-1;for(let a=0;a<o.data.byteLength;a++){let d=e.getUint8(a);if(d===0)r++;else if(d===1){if(r===2||r===3){let l=a-r;if(s===-1?s=l:n===-1&&(n=l,t.push(new sr(new DataView(e.buffer.slice(s,n)))),s=l,n=-1),!(e.getUint8(a+1)===6)){o.data=e.buffer.slice(l);break}}r=0}else r=0}i==null||i(t.reverse())}catch(e){}return o}var Fh=0,jn=class jn{constructor(i){this.core=i;c(this,"log");c(this,"_seiMessageList",[]);c(this,"_smallSeiMessageList",[]);c(this,"_subStreamSeiMessageList",[]);Fh++,this.log=i.log.createChild({id:`${this.getAlias()}${Fh}`}),this.log.info(`[sei] created id=${this.getAlias()}${Fh}`),this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode({frame:i,mediaType:e}){try{let t=e===8?this._smallSeiMessageList:e===2?this._subStreamSeiMessageList:this._seiMessageList;return Uh({frame:i,seiMessageList:t})}catch(t){this.log.warn(t)}return i}decode({frame:i,track:e}){return Vh({frame:i,onSEI:t=>{t.forEach(r=>{this.core.trtc.emit(U.SEI_MESSAGE,{seiPayloadType:r.seiPayloadType,data:r.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"})})}})}destroy(){this.log.debug("destroy"),this.stop(),delete this.core}getValidateRule(i){switch(i){case"start":return{type:"object"};case"update":return{type:"object"};case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:pi?this.encode:Uh,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:pi?this.decode:Vh,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update({buffer:i,options:e}){var s;let t=[e.seiPayloadType,i],r=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(t):(this._seiMessageList.push(t),r&&this._smallSeiMessageList.push(t)),(s=this.core.room.scriptTransformWorker)==null||s.postMessage({type:"sei",data:t,isMain:!e.toSubStream,small:r})}getName(){return jn.Name}getAlias(){return"sei"}getGroup(){return"sei"}};c(jn,"autoStart",!0),c(jn,"Name","SEI");var Ec=jn;var zS=0,Sc,Xn=class Xn{constructor(i){this.core=i;c(this,"_core");c(this,"log");c(this,"dialog");this._core=i,this.log=i.log.createChild({id:`${this.getAlias()}${++zS}`}),this.log.info("created")}getName(){return Xn.Name}getAlias(){return"dm"}getGroup(){return"dm"}getValidateRule(i){switch(i){case"start":return{name:"StartDebugOptions",required:!1};case"update":return{name:"UpdateDebugOptions",required:!1};case"stop":return{name:"StopDebugOptions",required:!1}}}start(){return f(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())})}update(e){return f(this,arguments,function*({visible:i}){i?yield this.openDebugDiaLog():this.closeDebugDiaLog()})}stop(){this.closeDebugDiaLog()}destroy(){this.stop()}openDebugDiaLog(){return f(this,null,function*(){var i;if(!this.dialog)try{if(Sc)yield Sc;else{let e=new URLSearchParams(location.search).get("trtcDebugDialogPath")||((i=window.sessionStorage)==null?void 0:i.getItem("TRTC_DEBUG_DIALOG_PATH"))||`https://unpkg.com/${Hf}@${He}/assets/debug-dialog.js`;Sc=this._core.fileDownloader.loadScript(e),yield Sc}this.dialog=new TRTCDebugDialog(this._core,this.log),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(){this.dialog&&(this.dialog.closeDialog(),this.dialog=null)}};c(Xn,"Name","Debug"),c(Xn,"autoStart",!0);var Ic=Xn;var Gf=o=>{switch(o){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},Ac=class{constructor(i,e,t){c(this,"trackDoneOB");c(this,"startOB");c(this,"stopOB");c(this,"inputFrameCount",0);c(this,"decodedFrameCount",0);c(this,"type","auto");c(this,"config");c(this,"decoder");c(this,"_decodeSink");let{kvStatManager:r,trtc:s}=i;this.config=t.config,this.trackDoneOB=de(e,j.INIT),this.stopOB=rt(),this.startOB=rt(),t.type==="auto"?this.type="webCodecs":this.type=t.type;let n=rt(),a=d=>{let l=this.pipe(e);return n.next("STARTING"),e.log.info(`decoder type: ${this.type}`),ce(l,ke(this.stopOB),Te(()=>{},u=>{e.log.error(u),r.addFailedEvent({key:Gf(this.type),error:u}),d>4?this.startOB.error(u):this.startOB.next(d+1)})),ce(l,or(1),hh(Un))};ce(this.startOB,xn(0),Mr(a),ke(this.stopOB),Te(()=>{e.player.setOutput(),n.next("STARTED")},d=>{n.next("FAILED")},()=>{r.addSuccessEvent({key:Gf(this.type)}),r.addSuccessEvent({key:504702})}))}mock(i){this._decodeSink?this._decodeSink.error(i):this.startOB.next(0)}close(i){this.stopOB.next(i)}pipe(i){return rr()(e=>f(this,null,function*(){this._decodeSink=e,e.defer(()=>{var r;(r=this.decoder)==null||r.close()});let{type:t}=this;try{switch(t){case"webCodecs":this.decoder=new AudioDecoder({error:r=>{i.log.error(r),e.error(4)},output:r=>{this.decodedFrameCount++,e.next(r),i.player.write(r)}});break;case"wasm":break}this.decoder.configure(this.config)}catch(r){i.log.error(r),e.error(t==="webCodecs"?2:6)}}))}decodeFrame(i){var e;this.inputFrameCount++,((e=this.decoder)==null?void 0:e.state)==="configured"&&this.decoder.decode(new EncodedAudioChunk({data:i.data,timestamp:i.timestamp,type:"key"}))}},QS={type:"object"},zn=class zn{constructor(i){this.core=i;c(this,"log");c(this,"contextMap",new Map);c(this,"decodeProcessorMap",new WeakMap);this.log=i.log.createChild({id:`${this.getAlias()}`})}getAlias(){return zn.Name}getGroup(i){return i.track.userId+i.track.streamType}getName(){return zn.Name}getValidateRule(i){return QS}start(i){let{track:e}=i;this.decodeProcessorMap.set(e,this.decode(i)),this.core.room.audioManager.addDecodeProcessor({processor:({frame:t,track:r})=>this.decodeProcessorMap.has(r)?this.decodeProcessorMap.get(r)({frame:t,track:r}):t,type:3})}decode(i){return({frame:e,track:t})=>{if(t!==i.track)return e;if(this.contextMap.has(t))return this.contextMap.get(t).decodeFrame(e);let r=new Ac(this.core,t,i);return ce(r.trackDoneOB,or(1),Te(()=>{this.core.clearStarted(this,this.getGroup(i)),this.stop({track:t})})),this.contextMap.set(t,r),r.decodeFrame(e)}}stop({track:i}){let e=this.contextMap.get(i);e&&(e.close("stop"),this.contextMap.delete(i),this.contextMap.size===0&&this.core.room.audioManager.removeDecodeProcessor({type:3}))}update(i){let e=this.contextMap.get(i.track);if(e){if(i.type==="mock"){e.mock(10);return}e.close("update"),this.contextMap.set(i.track,new Ac(this.core,i.track,i))}}};c(zn,"Name","TRTCAudioDecoder");var Qn=zn;var Cc=class{constructor(){c(this,"log");this.log=R.createLogger({id:"exp"})}call(i,e){return f(this,null,function*(){return le(this[i])?this[i](e):Promise.reject(new v({code:I.INVALID_PARAMETER,message:$({key:B.API_NOT_EXIST,data:{name:i}})}))})}enableAudioFrameEvent(i){return f(this,null,function*(){let{trtcInstance:e,enable:t,userId:r,sampleRate:s=48e3,channelCount:n=1,port:a}=i,{audioManager:d}=e.room,{getPCMAbortCtrlMap:l,audioFrameEventConfigMap:u}=d;if(u.set(r,{enable:t,sampleRate:s,channelCount:n,port:a}),t)if(r==="*")e.room.remotePublishedUserMap.forEach(h=>{if(h.remoteAudioTrack.isAvailable){if(l.get(h.userId))return;let p=d.getPCM(m=>{e.emit(U.AUDIO_FRAME,m)},h.userId);l.set(h.userId,p)}});else{if(l.get(r))return;let h=d.getPCM(p=>{e.emit(U.AUDIO_FRAME,p)},r);l.set(r,h)}else if(r==="*")e.room.remotePublishedUserMap.forEach(h=>{if(h.remoteAudioTrack.isSubscribed){let{userId:p}=h,m=l.get(p);m==null||m.abort("disable"),l.delete(p)}});else{let h=l.get(r);h==null||h.abort("disable"),l.delete(r)}})}resumeRemotePlayer(i){return f(this,null,function*(){if(i.userId==="*"){let t=[];return i.trtcInstance.room.remotePublishedUserMap.forEach(r=>{let{remoteAudioTrack:s,remoteVideoTrack:n,remoteAuxiliaryTrack:a}=r;i.streamType?i.streamType==="main"?(s.isAvailable&&t.push(s.player.resume()),n.isAvailable&&t.push(n.player.resume())):a.isAvailable&&t.push(a.player.resume()):(s.isAvailable&&t.push(s.player.resume()),n.isAvailable&&t.push(n.player.resume()),a.isAvailable&&t.push(a.player.resume()))}),Promise.all(t)}let e=i.trtcInstance.room.remotePublishedUserMap.get(i.userId);if(e)return i.streamType==="main"?Promise.all([e.remoteAudioTrack.player.resume(),e.remoteVideoTrack.player.resume()]):e.remoteAuxiliaryTrack.player.resume()})}pauseRemotePlayer(i){if(i.userId==="*")i.trtcInstance.room.remotePublishedUserMap.forEach(e=>{let{remoteAudioTrack:t,remoteVideoTrack:r,remoteAuxiliaryTrack:s}=e;i.streamType?i.streamType==="main"?(t.isAvailable&&t.player.pause(),r.isAvailable&&r.player.pause()):s.isAvailable&&s.player.pause():(t.isAvailable&&t.player.pause(),r.isAvailable&&r.player.pause(),s.isAvailable&&s.player.pause())});else{let e=i.trtcInstance.room.remotePublishedUserMap.get(i.userId);e&&(i.streamType==="main"?(e.remoteAudioTrack.player.pause(),e.remoteVideoTrack.player.pause()):e.remoteAuxiliaryTrack.player.pause())}}};D([_f({name:"options",type:"object",required:!0,properties:{enable:{required:!0,type:"boolean"},userId:{required:!0,type:"string"},sampleRate:{type:"number",values:[8e3,16e3,32e3,44100,48e3]},channelCount:{type:"number",values:[1,2]},port:{type:"messageport"}}})],Cc.prototype,"enableAudioFrameEvent",1);var Jf=new Cc;var qf=Je(nt(),1);var Bh=class extends qf.EventEmitter{constructor(){super();c(this,"states",{});c(this,"permissionChangeHandler");c(this,"log");this.log=R.createLogger({id:"pm"}),this.permissionChangeHandler=()=>{var e,t;this.emit("permission-state-change",{camera:(e=this.states.camera)==null?void 0:e.state,microphone:(t=this.states.microphone)==null?void 0:t.state})}}request(e){return f(this,null,function*(){if(this.log.info(`request ${e.join(", ")}`),e.length===0)return Promise.resolve();(yield navigator.mediaDevices.getUserMedia({video:e.includes("camera"),audio:e.includes("microphone")})).getTracks().forEach(r=>r.stop())})}get(e){return f(this,null,function*(){try{return this.states[e]||(this.states[e]=yield navigator.permissions.query({name:e}),this.states[e].addEventListener("change",this.permissionChangeHandler)),this.log.info(`get ${e} permission state: ${this.states[e].state}`),this.states[e].state}catch(t){return this.log.error(`get ${e} permission failed, error: ${t instanceof Error?t.message:t}`),null}})}destroy(){Object.values(this.states).forEach(e=>{e==null||e.removeEventListener("change",this.permissionChangeHandler)}),this.states={}}},Yn=new Bh;var jf=0,Zn=new Set,ze=null;Wc(bh);es.checkStorage();var q=class q extends Xf.EventEmitter{constructor(e,t){super();c(this,"_room");c(this,"_eventListened",new Set);c(this,"_localVideoTrack",null);c(this,"_localAudioTrack",null);c(this,"_localScreenTrack",null);c(this,"_localScreenAudioTrack",null);c(this,"_localVideoConfig",null);c(this,"_localScreenConfig",null);c(this,"_localAudioConfig",null);c(this,"_remoteVideoConfigMap",new Map);c(this,"_remoteAudioConfigMap",new Map);c(this,"_remoteAudioVolumeMap",new Map);c(this,"_remoteAudioMuteMap",new Map);c(this,"_mediaTrackMap",new WeakMap);c(this,"_log",R.createLogger({id:`t${++jf}`}));c(this,"_plugins",new Map);c(this,"_networkQuality",null);c(this,"_speakerId");c(this,"enterRoomParams");c(this,"_enableAutoSwitchWhenRecapturing",!0);this._room=new e(M({logger:this._log,frameWorkType:q.frameWorkType},t)),this._room.videoDecodeFallbackType=t.videoDecodeFallback,ue(t.enableAutoSwitchWhenRecapturing)&&(this._enableAutoSwitchWhenRecapturing=t.enableAutoSwitchWhenRecapturing),this._log.info(`create() ${JSON.stringify(t,(r,s)=>r==="plugins"?s.map(n=>n.Name):s)}`),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(r){return this._room.audioManager.dump(r)}}}),t.plugins&&t.plugins.forEach(r=>{this._use(r,t.assetsPath)}),this._use(_c,t.assetsPath),this._use(pc,t.assetsPath),this._use(Tc,t.assetsPath),this._use(Qn,t.assetsPath),this._use(Ic),t.enableSEI&&Tn&&this._use(Ec),this._room.on("audio-volume",r=>{var s,n;!r.find(a=>a.userId==="")&&this._localAudioTrack&&r.push({userId:"",volume:Math.floor(((s=this._localAudioTrack.getInternalAudioLevelAfter3A())!=null?s:this._localAudioTrack.getAudioLevel())*100),floatVolume:(n=this._localAudioTrack.getInternalAudioLevelAfter3A())!=null?n:this._localAudioTrack.getInternalAudioLevel()}),t.volumeType===1&&r.forEach(a=>{var l;let d=a.userId===""?this._localAudioTrack:(l=this.room.remotePublishedUserMap.get(a.userId))==null?void 0:l.remoteAudioTrack;d&&(a.volume=d.dbVolume)}),t.enableDbVolume&&r.forEach(a=>{var l;let d=a.userId===""?this._localAudioTrack:(l=this.room.remotePublishedUserMap.get(a.userId))==null?void 0:l.remoteAudioTrack;d&&(a.volume=d.dbVolume)}),this.emit(U.AUDIO_VOLUME,{result:r.sort((a,d)=>d.volume-a.volume)})}),this._room.videoManager.on("error",r=>{this._log.error(new F({code:W.OPERATION_FAILED,extraCode:5504,message:r.message,originError:r}))}),this._listenEvents(),this._initActiveSpeaker(),Uf(this,"trtc")}static create(e){}static _create(e,t){Ef();let r=new q(e,t||{});return Zn.add(r),r.__v_skip=!0,r}get room(){return this._room}_listenEvents(){tt(this,this._room).add("peer-join",e=>{let{userId:t}=e;this.emit(U.REMOTE_USER_ENTER,{userId:t})}).add("peer-leave",e=>{this.emit(U.REMOTE_USER_EXIT,{userId:e})}).add("banned",e=>{xt(!0),this._exitRoom().finally(()=>{this.emit(U.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().finally(()=>{this.emit(U.ERROR,F.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(U.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let t=w(M({},e),{uplinkRTT:Math.min(e.uplinkRTT,Hs),downlinkRTT:Math.min(e.downlinkRTT,Hs)});this.emit(U.NETWORK_QUALITY,t)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(r=>{tt(r,r).add("player-state-changed",s=>{let n=w(M({},s),{userId:e.userId});r.kind===_.VIDEO&&(n.streamType=Li(r.streamType)),this.emit(r.kind===_.AUDIO?U.AUDIO_PLAY_STATE_CHANGED:U.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",s=>{s.getCode()===I.PLAY_NOT_ALLOWED&&this.emit(U.AUTOPLAY_FAILED,{userId:r.userId,mediaType:r.strMediaType,resume:()=>r.player.resume()})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(r=>{we(r)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:t})=>{let{userId:r}=t,s=e.audioAvailable,n=e.videoAvailable,{audioAvailable:a,videoAvailable:d}=t;a||this._remoteAudioConfigMap.delete(r),d||this._removeRemoteVideoConfig(r,"main"),t.hasAuxiliary||this._removeRemoteVideoConfig(r,"sub"),n!==d&&(d?this._onVideoAvailable({userId:r,streamType:"main"}):this._onVideoUnavailable({userId:r,streamType:"main"}),this.emit(d?U.REMOTE_VIDEO_AVAILABLE:U.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"main"})),s!==a&&(a?this._onAudioAvailable({userId:r}):this._onAudioUnavailable({userId:r,muteState:t}),this.emit(a?U.REMOTE_AUDIO_AVAILABLE:U.REMOTE_AUDIO_UNAVAILABLE,{userId:r})),e.hasAuxiliary!==t.hasAuxiliary&&(t.hasAuxiliary?this._onVideoAvailable({userId:r,streamType:"sub"}):this._onVideoUnavailable({userId:r,streamType:"sub"}),this.emit(t.hasAuxiliary?U.REMOTE_VIDEO_AVAILABLE:U.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"sub"}))}).add("sei-message",e=>{this.emit(U.SEI_MESSAGE,w(M({},e),{streamType:Li(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(U.ERROR,new F({code:W.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var s,n,a,d,l,u,h;let t={2:"big",3:"small",7:"sub"},r={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)||((a=this._networkQuality)==null?void 0:a.downlinkRTT)||0,Hs),upLoss:((d=this._networkQuality)==null?void 0:d.uplinkLoss)||0,downLoss:((l=this._networkQuality)==null?void 0:l.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((u=e.msg_up_stream_info.msg_audio_status)==null?void 0:u.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((h=e.msg_up_stream_info.msg_audio_status)==null?void 0:h.uint32_audio_level)||0)/Dt},video:e.msg_up_stream_info.msg_video_status.filter(p=>t[p.uint32_video_stream_type]).map(p=>({bitrate:(p.uint32_video_codec_bitrate||0)/1e3,width:p.uint32_video_width,height:p.uint32_video_height,frameRate:p.uint32_video_enc_fps,videoType:t[p.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(p=>({userId:p.msg_user_info.str_identifier,audio:{bitrate:(p.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(p.msg_audio_status.uint32_audio_level||0)/Dt,point2pointDelay:(p.msg_audio_status.uint32_audio_p2p_delay||0)+(p.msg_audio_status.uint32_audio_cache_ms||0),jitterBufferDelay:p.msg_audio_status.uint32_audio_cache_ms||0},video:p.msg_video_status.map(m=>({bitrate:(m.uint32_video_codec_bitrate||0)/1e3,width:m.uint32_video_width,height:m.uint32_video_height,frameRate:m.uint32_video_dec_fps,videoType:t[m.uint32_video_stream_type],point2pointDelay:(m.uint32_video_p2p_delay||0)+(m.uint32_video_cache_ms||0),jitterBufferDelay:m.uint32_video_cache_ms||0,codec:m.uint32_video_codec}))}))};this.emit(U.STATISTICS,r)}).add("custom-message",e=>{this.emit(U.CUSTOM_MESSAGE,e)}).add("layerData",e=>this.emit(U.LAYER_DATA,e)).add("first-video-frame",e=>{this.emit(U.FIRST_VIDEO_FRAME,w(M({},e),{streamType:Li(e.streamType)}))}).add("audio-frame",e=>{this.emit(U.AUDIO_FRAME,e)}),tt(this,be).add("audioInputAdded",e=>{this.emit(U.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(U.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(U.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(U.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>f(this,null,function*(){if(this.emit(U.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),ze&&ze.deviceId===Bs){let t=(yield vr()).find(r=>r.deviceId===Bs);t&&ze.groupId!==t.groupId&&(ze=t,this.emit(U.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}})).add("audioOutputRemoved",e=>f(this,null,function*(){this.emit(U.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield vr())[0];if(!t||!ze||ze.groupId===t.groupId)return;let r=ze.deviceId===e.deviceId,s=ze.deviceId===Bs&&ze.deviceId===t.deviceId;(r||s)&&(ze=t,this.emit(U.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))})),tt(this,Yn).add("permission-state-change",e=>{this.emit(U.PERMISSION_STATE_CHANGE,e)}),this.room.enableSEI&&this.on(U.SEI_MESSAGE,e=>{var r;let t=(r=this.room.remotePublishedUserMap.get(e.userId))==null?void 0:r.remoteVideoTrack;t&&t.updateAlphaRenderInfo(e)})}getNetworkTime(){return Hi()}use(e){let t,r;return"plugin"in e?(t=e.plugin,r=e.assetsPath):t=e,t.Name==="Chorus"&&(this.room.enableChorus=!0),this._use(t,r)}_use(e,t){let r=this._plugins.get(e.Name);if(r)return this._log.warn("duplicate install plugin",e.Name),r;let s=new e(wf.call(this,{TRTC:q,room:this._room,assetsPath:t,errorModule:{RtcError:F,ErrorCode:W,CoreErrorCode:I,ErrorCodeDictionary:Lt}}));return this._plugins.set(e.Name,s),s.__v_skip=!0,e.autoStart&&this.startPlugin(e.Name),s}enterRoom(e){return f(this,null,function*(){var d,l;this.enterRoomParams=e;let{scene:t="rtc",enableAutoPlayDialog:r=!0,autoReceiveAudio:s=!0,autoReceiveVideo:n=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!ie(e.proxy)&&e.proxy.turnServer&&((l=(d=this._room).setTurnServer)==null||l.call(d,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=r,this._room.autoReceiveAudio=s,this._room.autoReceiveVideo=n,ue(e.preferHW)&&(this._room.preferHW=e.preferHW),e.playoutDelay&&(this._room.playoutDelay=e.playoutDelay),e.jitterBufferDelay&&(this._room.jitterBufferDelay=e.jitterBufferDelay);let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:e.role==="audience"?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language,priority:e.priority,useVp8:e.useVp8,useH265:e.useH265||!1,keepAlive:e.keepAlive};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(a,t,q.frameWorkType),this._checkTrackToPublish(),kh.start()})}exitRoom(){return f(this,null,function*(){return yield this._exitRoom()})}switchRoom(e){return f(this,null,function*(){if(this.room.isSwitchRoomSupported())try{this._clearRemoteTracks(),yield this._room.switchRoom(e)}catch(t){if(t instanceof Ps&&(t.code===I.API_CALL_TIMEOUT||t.code===I.SWITCH_ROOM_FAILED))this._log.warn(`switchRoom ${t.code===I.API_CALL_TIMEOUT?"timeout":"failed"}, fallback to exitRoom() and enterRoom()`),yield this._rejoinRoom(e);else throw t}else yield this._rejoinRoom(e)})}_rejoinRoom(e){return f(this,null,function*(){yield this.exitRoom();let t=M(M({},this.enterRoomParams),e);yield this.enterRoom(t)})}_clearRemoteTracks(){new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(e=>{this._stopRemoteAudio({userId:e}).catch(()=>{})}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let t=e.includes("main")?"main":"sub",r=e.split(`_${t}`)[0];r&&this._stopRemoteVideo({userId:r,streamType:t}).catch(()=>{})}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),Vf(this),this._room.remotePublishedUserMap.forEach(e=>{we(e.remoteAudioTrack),we(e.remoteVideoTrack),we(e.remoteAuxiliaryTrack)})}switchRole(e,t){return f(this,null,function*(){t!=null&&t.privateMapKey&&(this._room.privateMapKey=t.privateMapKey),t!=null&&t.latencyLevel&&(this._room.latencyLevel=t.latencyLevel),yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){this._plugins.forEach(e=>{var t;return(t=e.destroy)==null?void 0:t.call(e)}),this._plugins.clear(),we(this),this.removeAllListeners(),this._room.destroy(),Zn.delete(this),Zn.size===0&&kh.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),S.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return f(this,arguments,function*(e={publish:!0}){if(this._localAudioTrack){this._log.warn("local audio is already started");return}let{publish:t=!0,mute:r,option:s}=e,n=new kt(this._room.audioManager),a={},d={muted:!0};s&&(T(s.microphoneId)?T(s.audioTrack)||(a.customSource=s.audioTrack):a.deviceId=s.microphoneId,s&&Q(s.captureVolume)&&n.setCaptureVolume(s.captureVolume),T(s.profile)||(ie(s.profile)?pa[s.profile]&&n.setProfile(pa[s.profile]):n.setProfile(s.profile)),Q(s.earMonitorVolume)&&(d.muted=!(s.earMonitorVolume>0),d.volume=s.earMonitorVolume),T(s.echoCancellation)||(n.profile.echoCancellation=s.echoCancellation),T(s.noiseSuppression)||(n.profile.noiseSuppression=s.noiseSuppression),T(s.autoGainControl)||(n.profile.autoGainControl=s.autoGainControl),ue(this._enableAutoSwitchWhenRecapturing)&&(n.enableAutoSwitchWhenRecapturing=this._enableAutoSwitchWhenRecapturing)),n.on("5",l=>{this.emit(U.ERROR,new F({code:W.DEVICE_ERROR,extraCode:5309,messageParams:{error:l}}))}),n.on("2",l=>{this.emit(U.DEVICE_CHANGED,{type:"microphone",action:"active",device:l})}),n.on("4",l=>{let u;l.error&&(u=F.convertFrom(l.error)),this.emit(U.PUBLISH_STATE_CHANGED,w(M({},l),{error:u}))}),n.on("6",()=>{}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId),yield n.capture(a),T(r)||n.setMute(r),tt(n,n).add("player-state-changed",l=>{this.emit(U.AUDIO_PLAY_STATE_CHANGED,w(M({},l),{userId:""}))}),t&&this._room.isJoined&&this._room.publish(n).catch(()=>{}),this._localAudioTrack=n,this._localAudioConfig=w(M({},e),{publish:t}),yield this._updateAudioPlayOption({playOption:d,track:n}),S.emit("113",{userId:"",room:this.room})})}updateLocalAudio(e){return f(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:r,option:s}=e,n={};s&&(s.microphoneId?yield this._localAudioTrack.switchDevice(s.microphoneId):T(s.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(s.audioTrack)),T(s.captureVolume)||this._localAudioTrack.setCaptureVolume(s.captureVolume),T(s.earMonitorVolume)||(n.muted=!(s.earMonitorVolume>0),n.volume=s.earMonitorVolume),yield this._localAudioTrack.update3A(s)),this._room.isJoined&&!T(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),T(r)||this._localAudioTrack.setMute(r),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),ei(this._localAudioConfig,e)})}stopLocalAudio(){return f(this,null,function*(){this._localAudioTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),S.emit("114",{userId:"",room:this.room}),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),we(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)})}startLocalVideo(){return f(this,arguments,function*(e={publish:!0,view:null,capture:!0}){var h;if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:t,publish:r=!0,capture:s=!0,mute:n,option:a}=e,d=new je(this._room.videoManager),l={},u={};a&&(ue(a.avoidCropping)&&(d.avoidCropping=a.avoidCropping),a.cameraId?l.deviceId=a.cameraId:T(a.useFrontCamera)?T(a.videoTrack)||(l.customSource=a.videoTrack):l.facingMode=a.useFrontCamera?_.FACING_MODE_USER:_.FACING_MODE_ENVIRONMENT,T(a.retryWhenExactFailed)||(l.retryWhenExactFailed=a.retryWhenExactFailed),a.qosPreference&&(l.contentHint=Gn(a.qosPreference)),T(a.profile)||(ie(a.profile)?zt[a.profile]&&d.setProfile(zt[a.profile]):d.setProfile(a.profile)),T(a.fillMode)||(u.objectFit=a.fillMode),T(a.mirror)||(u.mirror=a.mirror),T(a.small)||(T(a.smallMode)||(this._room.smallMode=a.smallMode),ue(a.small)&&a.small===!1?d.stopSmall():d.updateSmallConfig(Ss(a.small,!0))),T(a.rotation)||d.setRotation(a.rotation),ue(this._enableAutoSwitchWhenRecapturing)&&(d.enableAutoSwitchWhenRecapturing=this._enableAutoSwitchWhenRecapturing)),d.once("first-video-frame",p=>{this.emit(U.FIRST_VIDEO_FRAME,w(M({},p),{streamType:Li(p.streamType)}))}),d.on("5",p=>{this.emit(U.ERROR,new F({code:W.DEVICE_ERROR,extraCode:5308,messageParams:{error:p}}))}),d.on("2",p=>{this.emit(U.DEVICE_CHANGED,{type:"camera",action:"active",device:p})}),d.on("4",p=>{let m;p.error&&(m=F.convertFrom(p.error)),this.emit(U.PUBLISH_STATE_CHANGED,w(M({},p),{error:m}))}),d.on("6",()=>{}),this._listenOutputTrackChanged(d),s?yield d.capture(l):(h=d.manager)==null||h.changeInput(d),T(n)||(yield d.setMute(n)),tt(d,d).add("player-state-changed",p=>{this.emit(U.VIDEO_PLAY_STATE_CHANGED,w(M({},p),{userId:"",streamType:"main"}))}).add("video-size-changed",p=>{this.emit(U.VIDEO_SIZE_CHANGED,w(M({},p),{streamType:Li(p.streamType)}))}),r&&this._room.isJoined&&this._room.publish(d).catch(()=>{}),this._localVideoTrack=d,this._localVideoConfig=w(M({},e),{view:t,publish:r,capture:s}),yield this._updateVideoPlayOption({view:t,playOption:u,track:d})})}updateLocalVideo(e){return f(this,null,function*(){var l,u,h;if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:r,mute:s,capture:n,option:a}=e,d={};if(this._localVideoConfig.capture)n!==!1?a!=null&&a.cameraId?yield this._localVideoTrack.switchDevice(a==null?void 0:a.cameraId):T(a==null?void 0:a.useFrontCamera)?T(a==null?void 0:a.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(a==null?void 0:a.videoTrack)):yield this._localVideoTrack.switchDevice(a!=null&&a.useFrontCamera?_.FACING_MODE_USER:_.FACING_MODE_ENVIRONMENT):this._localVideoTrack.stopCapture();else if(n){let p={};p.deviceId=(a==null?void 0:a.cameraId)||((l=this._localVideoConfig.option)==null?void 0:l.cameraId),p.facingMode=a!=null&&a.useFrontCamera||(u=this._localVideoConfig.option)!=null&&u.useFrontCamera?_.FACING_MODE_USER:_.FACING_MODE_ENVIRONMENT,p.customSource=(a==null?void 0:a.videoTrack)||((h=this._localVideoConfig.option)==null?void 0:h.videoTrack),yield this._localVideoTrack.capture(p)}a&&(T(a.profile)||(ie(a.profile)?zt[a.profile]&&this._localVideoTrack.setProfile(zt[a.profile]):this._localVideoTrack.setProfile(a.profile),(!a.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(a.cameraId))&&T(a.useFrontCamera)&&(yield this._localVideoTrack.applyProfile())),T(a.fillMode)||(d.objectFit=a.fillMode),T(a.mirror)||(d.mirror=a.mirror),T(a.rotation)||this._localVideoTrack.setRotation(a.rotation),a.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(Gn(a.qosPreference)),T(a.small)||(ue(a.small)&&!a.small?this._localVideoTrack.stopSmall():this._localVideoTrack.updateSmallConfig(Ss(a.small,!0)))),this._room.isJoined&&T(r)&&this._localVideoConfig.publish&&n&&!this._localVideoConfig.capture&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._room.isJoined&&((r!=null?r:this._localVideoConfig.publish)?this._room.publish(this._localVideoTrack).catch(()=>{}):this._room.unpublish(this._localVideoTrack).catch(()=>{})),T(s)||(yield this._localVideoTrack.setMute(s)),yield this._updateVideoPlayOption({view:t,playOption:d,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),ei(this._localVideoConfig,e)})}stopLocalVideo(){return f(this,null,function*(){this._localVideoTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),we(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return f(this,arguments,function*(e={publish:!0,view:null}){var p,m;if(this._localScreenTrack){this._log.warn("screen share is already started");return}let{view:t=null,publish:r=!0,muteSystemAudio:s,option:n}=e,a=new Pt(this._room.videoManager);a.on("4",g=>{let E;g.error&&(E=F.convertFrom(g.error)),this.emit(U.PUBLISH_STATE_CHANGED,w(M({},g),{error:E}))}),a.once("first-video-frame",g=>{this.emit(U.FIRST_VIDEO_FRAME,w(M({},g),{streamType:Li(g.streamType)}))}),this._listenOutputTrackChanged(a),e.streamType==="main"&&(a.mediaType=4);let d=null,l={},u={};n&&(T(n.profile)||(ie(n.profile)?fa[n.profile]&&a.setProfile(fa[n.profile]):a.setProfile(n.profile)),n.systemAudio&&(l.systemAudio=!0,l.echoCancellation=n.echoCancellation,l.noiseSuppression=n.noiseSuppression,l.autoGainControl=n.autoGainControl),T(n.fillMode)||(u.objectFit=n.fillMode),n.videoTrack&&(l.videoTrack=n.videoTrack),n.audioTrack&&(l.audioTrack=n.audioTrack),n.captureElement&&(l.captureElement=n.captureElement),n.preferDisplaySurface&&(l.preferDisplaySurface=n.preferDisplaySurface),n.qosPreference&&(l.contentHint=Gn(n.qosPreference)));let h=yield a.capture(l);if(a.mediaTrack.addEventListener(_.ENDED,()=>{this._stopScreenShare(),this.emit(U.SCREEN_SHARE_STOPPED)}),h.getAudioTracks()[0]){d=new To(this._room.audioManager);let g=h.getAudioTracks()[0];(p=e.option)!=null&&p.systemAudio&&!((m=e.option)!=null&&m.audioTrack)&&(d.sourceTrack=g),yield d.setInputMediaStreamTrack(g),ue(s)&&d.mediaTrack&&(d.mediaTrack.enabled=!s),this._speakerId&&d.setAudioOutput(this._speakerId)}if(tt(a,a).add("player-state-changed",g=>{this.emit(U.VIDEO_PLAY_STATE_CHANGED,w(M({},g),{userId:"",streamType:"sub"}))}),r&&this._room.isJoined){let g=[a];d&&(g.push(d),this._checkScreenAudioEchoCancellation(a,d)),g.forEach(E=>this._room.publish(E).catch(()=>{}))}this._localScreenTrack=a,this._localScreenAudioTrack=d,this._localScreenConfig=w(M({},e),{view:t,publish:r}),yield this._updateVideoPlayOption({view:t,playOption:u,track:a})})}updateScreenShare(e){return f(this,null,function*(){var d;if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:r,muteSystemAudio:s,option:n}=e,a={};if(n&&(T(n.fillMode)||(a.objectFit=n.fillMode),n.qosPreference)){let l=Gn(n.qosPreference);this._localScreenTrack.setContentHint(l)}if(this._room.isJoined&&!T(r)){if(r&&!this._localScreenConfig.publish){let l=[this._localScreenTrack];this._localScreenAudioTrack&&l.push(this._localScreenAudioTrack),l.forEach(u=>this._room.publish(u).catch(()=>{}))}if(this._localScreenConfig.publish&&!r){let l=[this._localScreenTrack];this._localScreenAudioTrack&&l.push(this._localScreenAudioTrack),l.forEach(u=>this._room.unpublish(u).catch(()=>{}))}}(d=this._localScreenAudioTrack)!=null&&d.mediaTrack&&ue(s)&&(this._localScreenAudioTrack.mediaTrack.enabled=!s),yield this._updateVideoPlayOption({view:t,playOption:a,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),ei(this._localScreenConfig,e)})}stopScreenShare(){return f(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return f(this,null,function*(){let{view:t,userId:r,streamType:s,option:n}=e,a=`${r}_${s}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${r}, streamType:${s}`);return}let d=this._room.remotePublishedUserMap.get(r);if(!d)return;let l={},u=s==="main"?d.remoteVideoTrack:d.remoteAuxiliaryTrack;u.on("decode-failed",h=>{this.emit(U.ERROR,new F({code:W.OPERATION_FAILED,extraCode:5507,message:"video decode failed"}))}),u.on("video-size-changed",h=>{this.emit(U.VIDEO_SIZE_CHANGED,w(M({},h),{streamType:Li(h.streamType)}))}),this._listenOutputTrackChanged(u),n&&(T(n.fillMode)||(l.objectFit=n.fillMode),T(n.mirror)||(l.mirror=n.mirror),T(n.poster)||(l.poster=n.poster),l.canvasRender=n.canvasRender,s==="main"&&!T(n.small)&&(!d.remoteVideoTrack.isSubscribing&&!d.remoteVideoTrack.isSubscribed&&d.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,u.user)),T(n.draggable)||u.setDraggable(n.draggable)),yield this._room.subscribe(u),yield this._enableVideoDecodeFallback(u,s),yield this._updateVideoPlayOption({view:t,playOption:l,track:u}),this._emitTrackEvent(u),this._remoteVideoConfigMap.set(a,{config:e}),n&&!T(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:u,view:t,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:n==null?void 0:n.viewRoot})})}updateRemoteVideo(e){return f(this,null,function*(){var P,re;let{view:t,userId:r,streamType:s,option:n,mute:a}=e,d=`${r}_${s}`,l=this._remoteVideoConfigMap.get(d);if(!l||!this._room.remotePublishedUserMap.has(r))return;let u={};n&&(T(n.fillMode)||(u.objectFit=n.fillMode),T(n.mirror)||(u.mirror=n.mirror));let h=null,p=this._room.remotePublishedUserMap.get(r);if(s==="main"&&(p!=null&&p.muteState.hasVideo)&&(h=p.remoteVideoTrack),s==="sub"&&(p!=null&&p.muteState.hasAuxiliary)&&(h=p.remoteAuxiliaryTrack),!h)return;let{config:m}=l;s==="main"&&n&&!T(n.small)&&this._room.changeType(n.small,h.user),n&&!T(n.draggable)&&h.setDraggable(n.draggable),ue(a)&&(h.ignoreUpdatePlayingState=!0,a?(yield h.player.pause(),yield this.room.unsubscribe(h)):(yield this.room.subscribe(h),yield h.player.resume())),yield this._updateVideoPlayOption({view:t,playOption:u,track:h,prevConfig:m}),ei(m,e);let g=T(n==null?void 0:n.receiveWhenViewVisible)?(P=m.option)==null?void 0:P.receiveWhenViewVisible:n.receiveWhenViewVisible,E=T(t)?m.view:t,C=T(n==null?void 0:n.viewRoot)?(re=m.option)==null?void 0:re.viewRoot:n.viewRoot;this._observeView({remoteTrack:h,view:E,receiveWhenViewVisible:g,viewRoot:C})})}stopRemoteVideo(e){return f(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,t=!0){return f(this,null,function*(){let r=[],s=this._room.remotePublishedUserMap.get(e.userId);if(s){let{muteState:n,remoteVideoTrack:a,remoteAuxiliaryTrack:d}=s;e.streamType==="main"&&(a.stop(),n.hasVideo&&r.push(a)),e.streamType==="sub"&&(d.stop(),n.hasAuxiliary&&r.push(d))}for(let n of r)t&&(delete n.ignoreUpdatePlayingState,yield this._room.unsubscribe(n),this._mediaTrackMap.delete(n.outMediaTrack));this._removeRemoteVideoConfig(e.userId,e.streamType)})}_removeRemoteVideoConfig(e,t){let r=`${e}_${t}`,s=this._remoteVideoConfigMap.get(r);s&&s.observer&&s.observer.disconnect(),this._remoteVideoConfigMap.delete(r)}muteRemoteAudio(e,t){return f(this,null,function*(){this._remoteAudioMuteMap.set(e,t);try{if(e==="*")if(t)yield this._stopRemoteAudio({userId:e});else{let r=[...this._room.remotePublishedUserMap.values()];for(let s of r)s.muteState.hasAudio&&!this._remoteAudioConfigMap.has(s.userId)&&(yield this._startRemoteAudio({userId:s.userId}))}else t?yield this._stopRemoteAudio({userId:e}):this._remoteAudioConfigMap.has(e)||(yield this._startRemoteAudio({userId:e}))}catch(r){throw r.code!==W.OPERATION_ABORT&&this._remoteAudioMuteMap.delete(e),r}})}setRemoteAudioVolume(e,t){if(e==="*"){this._remoteAudioVolumeMap.set("*",t),this._remoteAudioVolumeMap.forEach((s,n)=>this._remoteAudioVolumeMap.set(n,t));let r=[...this._room.remotePublishedUserMap.values()];for(let s of r)this._remoteAudioVolumeMap.set(s.userId,t),s.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:s.remoteAudioTrack})}else if(e){let r=this._room.remotePublishedUserMap.get(e);this._remoteAudioVolumeMap.set(e,t),r&&r.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:r.remoteAudioTrack})}}startPlugin(e,t){return f(this,null,function*(){return e.start(t)})}updatePlugin(e,t){return f(this,null,function*(){return e.update(t)})}stopPlugin(e,t){return f(this,null,function*(){return e.stop(t)})}enableAudioVolumeEvaluation(e=2e3,t=!1){this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,r){if(this.listeners(e).includes(t))return this;if(this._log.debug("on",e),super.on(e,t,r),this._eventListened.add(e),this.listeners(U.AUDIO_FRAME).length>0){let{audioFrameEventConfigMap:s}=this.room.audioManager;s.get("")||s.set("",{enable:!0}),this._localAudioTrack&&this.room.audioManager.handleLocalTrackStarted({userId:"",room:this.room})}return this}emit(e,...t){try{Mf.has(e)||this._log.debug(`emit ${e} ${JSON.stringify(t)}`)}catch(r){}return super.emit(e,...t)}off(e,t,r){if(this._log.debug("off",e),e==="*"?(this._eventListened.clear(),this.removeAllListeners()):super.off(e,t,r),(e===q.EVENT.AUDIO_FRAME||e==="*")&&this.listeners(q.EVENT.AUDIO_FRAME).length===0){let{getPCMAbortCtrlMap:s}=this.room.audioManager;s.forEach(n=>{n==null||n.abort("off")}),s.clear()}return this}getAudioTrack(e={userId:"",streamType:"main"}){let t,r=null,s="main",n=!1;if(ie(e)?t=e:(t=e.userId,n=e.processed===!0,e.streamType&&(s=e.streamType)),t){let a=this._room.remotePublishedUserMap.get(t);a&&(r=a.remoteAudioTrack)}else r=s==="sub"?this._localScreenAudioTrack:this._localAudioTrack;return r?n&&r.outMediaTrack&&r.outMediaTrack!==r.mediaTrack?r.outMediaTrack.clone():r.mediaTrack:null}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:t="",streamType:r="main",processed:s=!1}=e,n=null;if(t==="")r==="main"&&this._localVideoTrack&&(n=this._localVideoTrack),r==="sub"&&this._localScreenTrack&&(n=this._localScreenTrack);else{let a=this._room.remotePublishedUserMap.get(t);a&&(n=r==="main"?a.remoteVideoTrack:a.remoteAuxiliaryTrack)}return n?s&&n.outMediaTrack&&n.outMediaTrack!==n.mediaTrack?n.outMediaTrack.clone():n.mediaTrack:null}getVideoSnapshot(e={}){let{userId:t,streamType:r="main"}=e;if(t){let s=this._room.remotePublishedUserMap.get(t);if(r==="main"&&(s!=null&&s.muteState.hasVideo))return s.remoteVideoTrack.getVideoFrame();if(r==="sub"&&(s!=null&&s.muteState.hasAuxiliary))return s.remoteAuxiliaryTrack.getVideoFrame()}else{if(r==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(r==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(e){var t,r;this._speakerId=e,(t=this._localAudioTrack)==null||t.setAudioOutput(e),(r=this._localScreenAudioTrack)==null||r.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(s=>s.remoteAudioTrack.setAudioOutput(e))}setCurrentSpeaker(e){return f(this,null,function*(){(yield vr()).forEach(r=>{r.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(U.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}),ze=r)}),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: ${_t}/en/TRTC.html#.setCurrentSpeaker`)})}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return f(this,null,function*(){var a;let{userId:t}=e;if(this._remoteAudioConfigMap.has(t)){this._log.warn(`remote audio has already started. userId:${t}`);return}let r=this._room.remotePublishedUserMap.get(t);if(!r)return;let s={},n=r.remoteAudioTrack;n.on("decode-failed",d=>{this.emit(U.ERROR,new F({code:W.OPERATION_FAILED,extraCode:5508,message:"audio decode failed"}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId);try{let d=(a=this._remoteAudioVolumeMap.get(t))!=null?a:this._remoteAudioVolumeMap.get("*"),l=Q(d)?d:100;s.volume=l,this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(n),ce(de(n,"decode-failed"),ke(de(n,j.INIT)),Te(()=>{this.startPlugin(Qn.Name,{track:n,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:s,track:n}),S.emit("115",{userId:t,room:this.room}),n.outMediaTrack&&this.room.audioManager.updateAudioReference({type:"add",audioReference:n.outMediaTrack,refId:`ra-${t}`})}catch(d){throw this._remoteAudioConfigMap.delete(t),d}this._emitTrackEvent(n)})}_stopRemoteAudio(e,t=!0){return f(this,null,function*(){let r=this._room.remotePublishedUserMap.get(e.userId);r&&(r.remoteAudioTrack.stop(),r.muteState.hasAudio&&t&&(yield this._room.unsubscribe(r.remoteAudioTrack)),this._mediaTrackMap.delete(r.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete(`${e.userId}`),S.emit("116",{userId:e.userId,room:this.room}),this.room.audioManager.updateAudioReference({type:"remove",refId:`ra-${e.userId}`})})}_enableVideoDecodeFallback(e,t){let r=this._room.videoDecodeFallbackType;if(!r||!this._plugins.has("TRTCVideoDecoder"))return;e.log.debug("remote video will fall back when decode failed",e.id);let s;ce(de(e,"decode-failed"),ke(de(e,j.INIT)),Fn(()=>{this._room.downlinkVideoCodec!=="h265"&&this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:r})}),mo(de(e,"decode-downgrade-state-changed")),Te(n=>{s=n.state,this.emit(U.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,w(M({},n),{streamType:t,userId:e.userId}))},n=>{e.log.error("fallback",n)},()=>{s==="STARTED"&&e.log.info("fallback complete")}))}_updateVideoPlayOption(n){return f(this,arguments,function*({view:e,playOption:t,track:r,prevConfig:s}){if(r.setMirror(t.mirror),T(e)&&s&&s.view&&!Uo(t)){let a=Fo(s.view);a.length>0&&(yield r.play(a,t))}if(!T(e)){let a=Fo(e);a.length>0?yield r.play(a,t):r.stop()}})}_updateAudioPlayOption(s){return f(this,arguments,function*({playOption:e={},track:t,prevConfig:r}){if(!t.isPlayCalled)try{yield t.play(null,e)}catch(n){}if(T(e.muted)||t.setPlayerMute(e.muted),T(e.volume)||t.setAudioVolume(e.volume/100),t instanceof kt&&t.mediaTrack){let n=e.muted===!1&&!T(e.volume)&&e.volume>0?"add":"remove";this.room.audioManager.updateAudioReference({type:n,audioReference:t.mediaTrack,refId:"em"})}else if(t instanceof Ei){let n=e.muted?0:e.volume;if(T(n))return;this.room.audioManager.updateAudioReference({type:"updateVolume",refId:`ra-${t.userId}`,volume:e.volume})}})}_listenOutputTrackChanged(e){e.listeners("output-media-track-changed").length===0&&e.on("output-media-track-changed",()=>this._emitTrackEvent(e,!1))}_emitTrackEvent(e,t=!0){let r=e.isRemote?e.userId:"";e.outMediaTrack&&(t&&this._mediaTrackMap.get(e.outMediaTrack)===r||(this._mediaTrackMap.set(e.outMediaTrack,r),this.emit(U.TRACK,{userId:r,streamType:Li(e.streamType),track:e.outMediaTrack,sourceTrack:e.mediaTrack})))}_checkTrackToPublish(){var t,r,s;let e=[];if((t=this._localAudioConfig)!=null&&t.publish&&this._localAudioTrack&&e.push(this._localAudioTrack),(r=this._localVideoConfig)!=null&&r.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),this._checkScreenAudioEchoCancellation(this._localScreenTrack,this._localScreenAudioTrack)),e.length!==0)return Promise.all(e.map(n=>this._room.publish(n).catch(()=>{})))}_observeView({remoteTrack:e,view:t,receiveWhenViewVisible:r,viewRoot:s}){if(T(t)||T(r))return;let n=this._remoteVideoConfigMap.get(`${e.userId}_${Li(e.streamType)}`);if(!n)return;let a=n.observer||void 0;if(t===null||Ae(t)&&t.length===0||!r){a==null||a.disconnect(),e.isSubscribed||(this._log.info("_observeView observer disconnect, resubscribe",e.userId,e.strMediaType),this._room.subscribe(e).catch(()=>{}));return}let l=n.visibleViewMap||new Map,u=-1;(!a||a.root!==s)&&(a==null||a.disconnect(),l.clear(),a=new IntersectionObserver(p=>{p.forEach(m=>{l.set(m.target,m.isIntersecting),e.log.info(`view ${m.target.id} is${m.isIntersecting?"":" not"} visible`)}),clearTimeout(u),u=window.setTimeout(()=>{[...l.values()].find(g=>g)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:s}));let h=new Set(Fo(t));l.forEach((p,m)=>{h.has(m)||(a.unobserve(m),l.delete(m))}),h.forEach(p=>{l.set(p,!0),a.observe(p)}),a.takeRecords().forEach(p=>{l.set(p.target,p.isIntersecting)}),n.visibleViewMap=l,n.observer=a}_exitRoom(){return f(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),this._clearRemoteTracks()})}_stopScreenShare(){return f(this,null,function*(){var e;if(this._localScreenTrack){if(this._room.isJoined){let t=[this._localScreenTrack];this._localScreenAudioTrack&&t.push(this._localScreenAudioTrack),yield Promise.all(t.map(r=>this._room.unpublish(r).catch(()=>{})))}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(((e=this._localScreenAudioTrack.trackSettings)==null?void 0:e.echoCancellation)===!1&&this.stopPlugin("AudioProcessor"),this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),we(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_checkScreenAudioEchoCancellation(e,t){return f(this,null,function*(){var s,n;if(!e||!t)return;let r=(s=e.trackSettings)==null?void 0:s.displaySurface;if(((n=t.trackSettings)==null?void 0:n.echoCancellation)===!1&&(r==="monitor"||r==="browser"&&e.isShareCurrentTab)){this._log.warn("echoCancellation of screen audio track is disable. Try starting audioProcessor plugin");try{yield this.startPlugin("AudioProcessor",{sdkAppId:Number(this.room.sdkAppId),userId:this._room.userId,userSig:this.room.userSig,isScreenAudioNeedAudioProcess:!0,isLocalAudioNeedAudioProcess:!1})}catch(a){this._log.warn("start audioProcessor plugin failed: ",a)}}})}_onLocalTrackCaptured({track:e}){e.kind==="audio"&&(!ze||ls(ze))&&(this._initActiveSpeaker(),S.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return f(this,null,function*(){if(ze&&!ls(ze))this.emit(U.DEVICE_CHANGED,{type:"speaker",action:"active",device:ze});else{let e=yield vr();e[0]&&!ls(e[0])?(ze=e[0],this.emit(U.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):S.on("102",this._onLocalTrackCaptured,this)}})}_onAudioAvailable({userId:e}){let t=this._remoteAudioMuteMap.has(e)?this._remoteAudioMuteMap.get(e):this._remoteAudioMuteMap.get("*");(t===!1||this._room.autoReceiveAudio&&!t)&&this._doStartRemoteAudio({userId:e}).catch(()=>{})}_onVideoAvailable({userId:e,streamType:t}){if(!this._room.autoReceiveVideo)return;let r=this._room.remotePublishedUserMap.get(e);if(r){let s=t==="main"?r.remoteVideoTrack:r.remoteAuxiliaryTrack,n=[s];this._room.autoReceiveAudio&&r.remoteAudioTrack.isAvailable&&n.push(r.remoteAudioTrack),this._room.subscribe(...n).then(()=>{this._emitTrackEvent(s)}).catch(()=>{})}}_onAudioUnavailable({userId:e,muteState:t}){t.hasAudio&&t.audioMuted||this._stopRemoteAudio({userId:e},!1).catch(()=>{})}_onVideoUnavailable({userId:e,streamType:t}){this._stopRemoteVideo({userId:e,streamType:t},!1).catch(()=>{})}sendSEIMessage(e,t){var s;let r=this._plugins.get("SEI");r&&(r.update({buffer:e,options:w(M({seiPayloadType:243},t),{small:!!((s=this._localVideoTrack)!=null&&s.small)})}),y.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,r;(r=(t=this._room).sendCustomMessage)==null||r.call(t,e),y.addCount({key:500001,useUV:!0})}callExperimentalAPI(e,t){return f(this,null,function*(){return this._log.info(`callExperimentalAPI(${e}, ${JSON.stringify(t)})`),Jf.call(e,M({trtcInstance:this},t))})}static setLogLevel(e,t){R.setLogLevel(e),T(t)||(t?R.enableUploadLog():R.disableUploadLog())}static isSupported(){return fd(q.frameWorkType)}static getPermissions(r){return f(this,arguments,function*({request:e=!0,types:t=["camera","microphone"]}){e&&(yield Yn.request(t).catch(a=>{var d;return R.error(`getPermissions request failed, error: ${(d=a==null?void 0:a.message)!=null?d:a}`)}));let[s,n]=yield Promise.all([Yn.get("camera"),Yn.get("microphone")]);return{camera:s,microphone:n}})}static getCameraList(e=!0){return At(e)}static getMicrophoneList(e=!0){return It(e)}static getSpeakerList(e=!0){return vr(e)}static setCurrentSpeaker(e){return f(this,null,function*(){if(_e&&(e===So.SPEAKER||e===So.HEADSET)){let r=yield q.getMicrophoneList(),s="";if(r.forEach(n=>{n.label===e&&(s=n.deviceId)}),!s)return;Zn.forEach(n=>f(this,null,function*(){n._localAudioTrack&&(yield n.updateLocalAudio({option:{microphoneId:s}}))}));return}(yield vr()).forEach(r=>{r.deviceId===e&&(Zn.forEach(s=>{s._setCurrentSpeaker(e),s.emit(U.DEVICE_CHANGED,{type:"speaker",action:"active",device:r})}),ze=r)})})}static _addKVStat({type:e,key:t,value:r,base:s,useUV:n,version:a,max:d}){switch(a&&(ro.version=a),e){case"count":ro.addCount({key:t,useUV:n});break;case"enum":ro.addEnum({key:t,value:r,useUV:n});break;case"number":ro.addNumber({key:t,value:r,split:s,max:d});break}}};c(q,"VERSION",bh),c(q,"_loggerManager",R),c(q,"EVENT",U),c(q,"ERROR_CODE",W),c(q,"TYPE",So),c(q,"frameWorkType",30),D([Se({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"}})})],q.prototype,"use",1),D([ot(Ge.TRTC.enterRoom),Lr("room",([e],[t])=>(e.roomId||e.strRoomId)===(t.roomId||t.strRoomId)&&e.userId===t.userId&&e.sdkAppId===t.sdkAppId),Y(e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)}),Se()],q.prototype,"enterRoom",1),D([Se()],q.prototype,"exitRoom",1),D([ot(Ge.TRTC.switchRoom),Se(),ir()],q.prototype,"switchRoom",1),D([ot(Ge.TRTC.switchRole),Ao("room",{merge:(e,t)=>t}),Se()],q.prototype,"switchRole",1),D([Se()],q.prototype,"destroy",1),D([ot(Ge.TRTC.startLocalAudio),Lr("audio",([e],[t])=>{var r,s;return((r=e==null?void 0:e.option)==null?void 0:r.microphoneId)===((s=t==null?void 0:t.option)==null?void 0:s.microphoneId)}),Se()],q.prototype,"startLocalAudio",1),D([ot(Ge.TRTC.updateLocalAudio),Ao("audio",{debounce:{delay:200,getKey:()=>`${jf}-localAudio`,isNeedToDebounce:e=>{var t;return!T((t=e.option)==null?void 0:t.captureVolume)}}}),Se()],q.prototype,"updateLocalAudio",1),D([xr("audio"),Se()],q.prototype,"stopLocalAudio",1),D([ot(Ge.TRTC.startLocalVideo),Lr("video",([e],[t])=>{var r,s;return((r=e==null?void 0:e.option)==null?void 0:r.cameraId)===((s=t==null?void 0:t.option)==null?void 0:s.cameraId)}),Se()],q.prototype,"startLocalVideo",1),D([ot(Ge.TRTC.updateLocalVideo),Ao("video"),Se()],q.prototype,"updateLocalVideo",1),D([xr("video"),Se()],q.prototype,"stopLocalVideo",1),D([ot(Ge.TRTC.startScreenShare),Lr("screen",()=>!0),Se()],q.prototype,"startScreenShare",1),D([ot(Ge.TRTC.updateScreenShare),Ao("screen"),Se()],q.prototype,"updateScreenShare",1),D([Se()],q.prototype,"stopScreenShare",1),D([ot(Ge.TRTC.startRemoteVideo),Lr(e=>`v${e.userId}${e.streamType}`,()=>!0),Se({getRemoteId:e=>`${e.userId}_${e.streamType}`})],q.prototype,"startRemoteVideo",1),D([ot(Ge.TRTC.updateRemoteVideo),Ao(e=>`v${e.userId}${e.streamType}`),Se({getRemoteId:e=>`${e.userId}_${e.streamType}`})],q.prototype,"updateRemoteVideo",1),D([ot(Ge.TRTC.stopRemoteVideo),Y(e=>function(t){return f(this,null,function*(){if(t.userId==="*"){let r=[];return this._room.remotePublishedUserMap.forEach(s=>{this._remoteVideoConfigMap.has(`${s.userId}_main`)&&r.push(this.stopRemoteVideo({streamType:"main",userId:s.userId}).catch(()=>{})),this._remoteVideoConfigMap.has(`${s.userId}_sub`)&&r.push(this.stopRemoteVideo({streamType:"sub",userId:s.userId}).catch(()=>{}))}),Promise.all(r)}return e.call(this,t)})}),Se({getRemoteId:e=>`${e.userId}_${e.streamType}`})],q.prototype,"stopRemoteVideo",1),D([xr(e=>`v${e.userId}${e.streamType}`)],q.prototype,"_stopRemoteVideo",1),D([ot(...Ge.TRTC.muteRemoteAudio),Se({getRemoteId:e=>e})],q.prototype,"muteRemoteAudio",1),D([Nh(...Ge.TRTC.setRemoteAudioVolume),Ff(200,e=>e),Se({getRemoteId:e=>e})],q.prototype,"setRemoteAudioVolume",1),D([hc("start"),Ct(e=>{var t;return(t=e.afterStart)==null?void 0:t.call(e)}),Lr((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t)),Se({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Yl[e.getName()],ignoreLog:e=>e.getName()==="Debug",ignoreErrorLog:e=>e.getName()==="AudioProcessor"})],q.prototype,"startPlugin",1),D([hc("update"),Ao((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t),{merge:(e,t)=>(ei(e[1],t[1]),e)}),Se({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Zl[e.getName()]})],q.prototype,"updatePlugin",1),D([hc("stop"),xr((e,t)=>{if(e.disableRandomCall)return null;let r=e.getGroup(t),s=e.getAlias();return r==="*"?new RegExp(`${s}.*`):s+r}),Se({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Kl[e.getName()]})],q.prototype,"stopPlugin",1),D([Nh(...Ge.TRTC.enableAudioVolumeEvaluation)],q.prototype,"enableAudioVolumeEvaluation",1),D([Se()],q.prototype,"getVideoSnapshot",1),D([Se()],q.prototype,"_setCurrentSpeaker",1),D([Lr(e=>`a${e.userId}`,()=>!0)],q.prototype,"_startRemoteAudio",1),D([Y(e=>function(t){return f(this,null,function*(){return t.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(r=>this._stopRemoteAudio(w(M({},t),{userId:r.userId})).catch(()=>{}))):e.call(this,t)})}),xr(e=>`a${e.userId}`)],q.prototype,"_stopRemoteAudio",1),D([xr("room")],q.prototype,"_exitRoom",1),D([xr("screen")],q.prototype,"_stopScreenShare",1),D([ot(...Ge.TRTC.sendSEIMessage),Ih({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...e)=>e[0].byteLength})],q.prototype,"sendSEIMessage",1),D([ot(Ge.TRTC.sendCustomMessage),Ih({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],q.prototype,"sendCustomMessage",1),D([wr()],q,"create",1),D([ot(Ge.TRTC.create)],q,"_create",1),D([wr()],q,"setLogLevel",1),D([wr()],q,"isSupported",1),D([wr(),Se()],q,"getPermissions",1),D([wr()],q,"getCameraList",1),D([wr()],q,"getMicrophoneList",1),D([wr()],q,"getSpeakerList",1);var Hh=q,Kn=Hh;var $h=class{constructor(){c(this,"_set",new Set);S.on(A.LEAVE_SUCCESS,this.delete,this),S.on(A.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess,this)}add({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,e||i.roomId,i.sdkAppId,i.useStringRoomId);this._set.add(t)}delete({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,i.roomId||e,i.sdkAppId,i.useStringRoomId);this._set.delete(t)}getKey(i,e,t,r){return`${t}_${e}_${i}_${r}`}isJoined({userId:i,roomId:e,sdkAppId:t,room:r}){return r.scene==="rtc"?!1:this._set.has(this.getKey(i,e,t,r.useStringRoomId))}handleSwitchRoomSuccess({room:i,currentRoomId:e,targetRoomId:t}){i.scene!=="rtc"&&(this._set.delete(this.getKey(i.userId,e,i.sdkAppId,i.useStringRoomId)),this._set.add(this.getKey(i.userId,t,i.sdkAppId,i.useStringRoomId)))}};function YS(){return f(this,null,function*(){let o,i;try{let m=yield It();o=m&&m.length}catch(m){}try{let m=yield At();i=m&&m.length}catch(m){}let e={microphone:o,camera:i},{isH264EncodeSupported:t,isVp8EncodeSupported:r,isH264DecodeSupported:s,isVp8DecodeSupported:n,isH265EncodeSupported:a,isH265DecodeSupported:d}=this.checkSystemResult.detail,l=vi.basis(),u={webRTC:l.isWebRTCSupported,getUserMedia:l.isGetUserMediaSupported,webSocket:l.isWebSocketsSupported,screenShare:l.isScreenShareSupported,webAudio:l.isWebAudioSupported,h264Encode:t,h264Decode:s,vp8Encode:r,vp8Decode:n,h265Encode:a,h265Decode:d},h={browser:l.browser,os:l.os,trtc:u,devices:e},p={isWebCodecSupported:l.isWebCodecSupported,isMediaSessionSupported:l.isMediaSessionSupported,isWebTransportSupported:l.isWebTransportSupported};se.uploadEvent({log:`trtcstats-${JSON.stringify(h)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(h)}`),se.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(p)}`,userId:this.userId}),uu()})}function zf(){return Y(o=>{let i=new $h;return function(e,t,r){return f(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=t,e.privateMapKey=e.privateMapKey||"",this.isJoined)throw new v({code:I.INVALID_OPERATION,message:$({key:B.INVALID_JOIN})});if(this.checkDestroy(),i.isJoined({userId:this.userId,roomId:s,sdkAppId:this.sdkAppId,room:this}))throw new v({code:I.INVALID_OPERATION,message:$({key:B.REPEAT_JOIN,data:this.userId})});i.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}`),S.emit(A.JOIN_START,{room:this,roomId:s,params:e});let n=Nt.getEnv();n||(n=$i.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(_a.OLD_CLOUD_LADDER)?n=$i.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(_a.WEBRTC)&&(n=$i.WEBRTC))),se.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:s}),vi.checkSystemRequirementsInternal(r).then(a=>{this.checkSystemResult=a,YS.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Nt.getEnv()&&(yield this.schedule(e,r));let a=yield o.call(this,e,t,r);return this.roomId=s,this._joinedTimestamp=Nt.performanceNow(),S.emit(A.JOIN_SUCCESS,{room:this}),r===30&&!e.component&&se.uploadEvent({log:`stat-conv-${Number(ni)}-${location.hostname}`,userId:this.userId}),a}catch(a){throw i.delete({room:this,roomId:s}),S.emit(A.JOIN_FAILED,{room:this,error:a}),a}})}})}var Qf=()=>Y(o=>function(...i){return f(this,null,function*(){S.emit(A.LEAVE_START,{room:this}),yield o.call(this,...i),S.emit(A.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function Yf(){return Y(o=>function(...i){let e=o.apply(this,i);return i.forEach(t=>!t.isSubscribed&&t.subscribe(e)),e})}var Kf=Je(nt());var Ie={SETUP_SUCCESS:"1",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",RECONNECT_FAILED:"4",SETUP_FAILED:"5",DISCONNECTED:"6",CLOSE:"7",ONLINE:"8"};var Jt={CLIENT_BANNED:9,CHANNEL_SETUP_RESULT:19,CHANNEL_RECONNECT_RESULT:514,JOIN_ROOM_RESULT:20,PEER_JOIN:4134,PEER_LEAVE:4135,STREAM_ADDED:16,STREAM_REMOVED:18,UPLINK_NETWORK_STATS:22,UPDATE_REMOTE_MUTE_STAT:23,PUBLISH_RESULT:4098,PUBLISH_STATE_CHANGE_RESULT:4112,UNPUBLISH_RESULT:4100,SUBSCRIBE_RESULT:4102,UNSUBSCRIBE_RESULT:4104,SUBSCRIBE_CHANGE_RESULT:4106,MUTE_RESULT:4108,UPDATE_OFFER_RESULT:4128,START_PUBLISH_TENCENT_CDN_RES:1286,STOP_PUBLISH_TENCENT_CDN_RES:1288,START_PUBLISH_GIVEN_CDN_RES:777,STOP_PUBLISH_GIVEN_CDN_RES:779,START_MIX_TRANSCODE_RES:781,STOP_MIX_TRANSCODE_RES:783,START_PUBLISH_CDN_STREAM_RES:8196,UPDATE_PUBLISH_CDN_STREAM_RES:8198,STOP_PUBLISH_CDN_STREAM_RES:8200,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772,REBUILD_PEER_CONNECTION_RES:4150,SPC_PUBLISH_RESULT:4146,SPC_SUBSCRIBE_RESULT:4156,ABILITY_STATUS_REPORT_RESULT:4158,SERVER_FIRST_PACKAGE_RECEIVED:5e3,RECEIVE_CUSTOM_MSG:4140,FALLBACK_CODEC:66,SEND_SWITCH_ROOM_RES:4160,SEND_SWITCH_ROOM_SUBED_REQ:4161,UPDATE_NETWORK_TIME_RESULT:5001,CUSTOM_CMD_RES:8220},Zf=[Jt.UPDATE_REMOTE_MUTE_STAT,Jt.UPLINK_NETWORK_STATS,Jt.USER_LIST_RES,Jt.MUTE_RESULT,Jt.SERVER_FIRST_PACKAGE_RECEIVED,Jt.RECEIVE_CUSTOM_MSG,Jt.UPDATE_NETWORK_TIME_RESULT],J={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",START_PUBLISH_CDN_STREAM_RES:"start-publish-cdn-stream-res",UPDATE_PUBLISH_CDN_STREAM_RES:"update-publish-cdn-stream-res",STOP_PUBLISH_CDN_STREAM_RES:"stop-publish-cdn-stream-res",USER_LIST_RES:"user-list-res",SWITCH_ROLE_RES:"switch_role_res",MUTE_RESULT:"mute-result",UPDATE_CONSTRAINT_CONFIG_RES:"update-contraint-config-res",REBUILD_PEER_CONNECTION_RES:"rebuild-pc-res",SPC_PUBLISH_RESULT:"spc-publish-result",SPC_SUBSCRIBE_RESULT:"spc-subscribe-result",ABILITY_STATUS_REPORT_RESULT:"ability-status-report",SERVER_FIRST_PACKAGE_RECEIVED:"first-pkg-received",RECEIVE_CUSTOM_MSG:"receive-custom-msg",FALLBACK_CODEC:"fallback-codec",SEND_SWITCH_ROOM_RES:"send-switch-room-res",SEND_SWITCH_ROOM_SUBED_REQ:"send-switch-room-subed-res",UPDATE_NETWORK_TIME_RESULT:"update_network_time_result",CUSTOM_CMD_RES:"custom-cmd-res"},Z={PUBLISH_CHANGE:"publish_change",JOIN_ROOM:"join",LEAVE_ROOM:"leave",ON_QUALITY_REPORT:"quality_report",UPDATE_MUTE_STAT:"mute_uplink",PUBLISH:"publish",PUBLISH_STATE_CHANGE:"publish_state_change",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",RECEIVE_DATA_USER_LIST:"receive_data_userlist",UNSUBSCRIBE:"unsubscribe",SUBSCRIBE_CHANGE:"subscribe_change",START_PUBLISH_TENCENT_CDN:"start_publishing",STOP_PUBLISH_TENCENT_CDN:"stop_publishing",START_PUBLISH_GIVEN_CDN:"start_push_user_cdn",STOP_PUBLISH_GIVEN_CDN:"stop_push_user_cdn",START_MIX_TRANSCODE:"start_mcu_mix",STOP_MIX_TRANSCODE:"stop_mcu_mix",START_PUBLISH_CDN_STREAM:"start_publish_cdn_stream",UPDATE_PUBLISH_CDN_STREAM:"update_publish_cdn_stream",STOP_PUBLISH_CDN_STREAM:"stop_publish_cdn_stream",GET_USER_LIST:"get_user_list",SWITCH_ROLE:"change_role",UPDATE_CONSTRAINT_CONFIG:"update_constraint_config",REBUILD_PEER_CONNECTION:"rebuild_pc",READY_TO_RECEIVE_DATA:"ready_to_receive",SPC_JOIN_ROOM:"join/v2",SPC_PUBLISH:"publish/v2",SPC_SUBSCRIBE:"subscribe/v3",ABILITY_STATUS_REPORT:"ability_status_report",RECONNECT_WS:"reconnect",SEND_CUSTOM_MSG:"channel_msg",SWITCH_ROOM:"switch_room",UPDATE_NETWORK_TIME:"update_network_time",CUSTOM_CMD:"abstract_cmd"};var Rc=new Set;function e_(o){let i=[...Rc.values()].find(e=>e.room.userId===o&&!e.room.isJoined);return i||null}var KS=["autoTest","relayInnerIp","relayOuterIp","mcd","newRelay","clientIp"],ys=class extends Kf.default{constructor(e){var r,s,n;super();c(this,"room");c(this,"sdkAppId");c(this,"userId");c(this,"userSig");c(this,"url");c(this,"backupUrl");c(this,"destroyed",!1);c(this,"_socketInUse");c(this,"_socket");c(this,"_backupSocket");c(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,bakRelayIps:[],reportToken:void 0});c(this,"_currentState","DISCONNECTED");c(this,"_isReconnecting",!1);c(this,"_seq",0);c(this,"_log");c(this,"_lastMessageTime",-1);c(this,"_connectStartTime",-1);c(this,"_stopConnectRetry");c(this,"_isFirstConnect",!0);c(this,"bytesSent",0);c(this,"bytesReceived",0);c(this,"keepAlive",!1);c(this,"signalDomainWhenUnifiedProxy");c(this,"stopKeepAliveTimeout");c(this,"rtt",0);this.room=e.room,this.sdkAppId=e.sdkAppId,this.userId=e.userId,this.userSig=e.userSig,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy;let t=((s=(r=this.room.scheduleResult)==null?void 0:r.config)==null?void 0:s.keepAliveClient)||0;(n=this.room.joinParams)!=null&&n.keepAlive&&!t&&(t=1),t-Rc.size>0&&this.room.enableSPC&&(this.keepAlive=!0,Rc.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=R.createLogger({parent:this.room.getLogger(),id:"ws",userId:this.userId,sdkAppId:this.sdkAppId}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get race(){return this.room.enableSPC&&!this.room.proxy_ws}get urlParam(){let e=`?sdkAppId=${encodeURIComponent(this.sdkAppId)}&userId=${encodeURIComponent(this.userId)}&userSig=${encodeURIComponent(this.userSig)}&keepAlive=${encodeURIComponent(Number(this.keepAlive))}`;this.signalDomainWhenUnifiedProxy&&(e+=`&signalDomain=${encodeURIComponent(this.signalDomainWhenUnifiedProxy)}`);let t=new URLSearchParams(location.search);return KS.forEach(r=>{let s=t.get(`trtc_${r}`);s&&(e+=`&${r}=${encodeURIComponent(s)}`)}),this.race?`${e}&race=1`:e}get _urlWithParam(){return`${this.url}${this.race?"/v2/ws":""}${this.urlParam}`}get _backupUrlWithParam(){return`${this.backupUrl}${this.race?"/v2/ws":""}${this.urlParam}`}get isConnected(){return this._currentState==="CONNECTED"}get isConnecting(){return this._currentState==="CONNECTING"}get isOnline(){return this._currentState==="CONNECTED"&&Date.now()-this._lastMessageTime<12*1e3}connect(){return f(this,arguments,function*(e=10*1e3){if(this.isConnected)return Promise.resolve();this._log.info(`connect to [${this.url}, ${this.backupUrl}] ${this.race?"race":""}${e?` timeout: ${e}`:""} keepAlive: ${Number(this.keepAlive)}`),this.emitConnectionStateChanged("CONNECTING"),this._connectStartTime=V();let t=[this.connectWS({url:this._urlWithParam,isMain:!0,timeout:e})];this.race&&this._backupUrlWithParam!==this._urlWithParam&&t.push(this.connectWS({url:this._backupUrlWithParam,isMain:!1,timeout:e})),this._socketInUse=yield Xr(t),this.unbindAndCloseSocket(this._socketInUse===this._socket?_.BACKUP:_.MAIN),this._isFirstConnect&&(y.addSuccessEvent({key:521720}),this._isFirstConnect=!1),this.emitConnectionStateChanged("CONNECTED")})}connectWS({url:e,timeout:t,isMain:r}){let s=new WebSocket(e);this.bindSocket(s),r?this._socket=s:this._backupSocket=s;let n=-1;return new Promise((a,d)=>{s.onclose=d,s.onerror=d,s.onopen=()=>a(s),t&&(n=setTimeout(()=>{this.unbindAndCloseSocket(r?_.MAIN:_.BACKUP),d(new v({code:I.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))},t))}).finally(()=>{s.onclose=null,s.onerror=null,s.onopen=null,clearTimeout(n)})}bindSocket(e){e.addEventListener("close",this.onclose),e.addEventListener("error",this.onerror),e.addEventListener("message",this.onmessage)}unbindSocket(e){e.removeEventListener("close",this.onclose),e.removeEventListener("error",this.onerror),e.removeEventListener("message",this.onmessage)}unbindAndCloseSocket(e){if(e===_.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(t){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(t){}this._backupSocket=null}}onclose(e){e.target===this._socketInUse&&(this._log.warn(`${e.target===this._socket?"main":"backup"} is closed code:${e.code} ${e.reason}`),this.emitConnectionStateChanged("DISCONNECTED"),(!e.wasClean||e.code!==1e3)&&this.startReconnection(),this.room.isJoining&&this.emit(Ie.SETUP_FAILED,new v({code:I.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onclose"})))}onerror(e){this._log.error(`${e.target===this._socket?"main":"backup"} error observed`),this.emitConnectionStateChanged("DISCONNECTED"),e.target===this._socketInUse&&(this.unbindAndCloseSocket(_.MAIN),this.unbindAndCloseSocket(_.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(Ie.SETUP_FAILED,new v({code:I.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(e){if(!this.isConnected)return;let{isOnline:t}=this;this._lastMessageTime=Date.now(),t||this.emit(Ie.ONLINE),this.bytesReceived+=Gs(e.data);let r=JSON.parse(e.data),{cmd:s,data:n}=r,a=Object.values(Jt),l=Object.keys(Jt)[a.indexOf(s)],u=J[l]||s;switch(Zf.includes(s)||(this._log.debug(`received ${s} msg: ${e.data}`),u&&this._log.info(`Received event: [ ${u} ]`)),s){case Jt.CHANNEL_SETUP_RESULT:{if(r.code===0)this._signalInfo.clientIp=n.clientIp,this._signalInfo.signalIp=n.signalInnerIp,n.svrTime&&da(n.svrTime-new Date().getTime()),this._log.info(`ChannelSetup Success ${V()-this._connectStartTime}`),y.addSuccessEvent({key:521701,cost:V()-this._connectStartTime}),this._connectStartTime=-1,this.emit(Ie.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let h=new v({code:I.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:r.code,message:$({key:B.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:r.code,errorMsg:r.message}})});this._log.error(`${r.code}, ${r.message}`),this.close(),y.addFailedEvent({key:521701,error:h}),this.emit(Ie.SETUP_FAILED,h)}break}case Jt.JOIN_ROOM_RESULT:{r.code===0&&(this._signalInfo.relayIp=n.relayOuterIp,this._signalInfo.relayInnerIp=n.relayInnerIp,this._signalInfo.bakRelayIps=n.bakRelayIps,this._signalInfo.relayPort=n.relayPort,this._signalInfo.tinyId=r.tinyId,this._signalInfo.endReportExtend=n.endReportExtend,this._signalInfo.reportToken=n.reportToken,this._log.info(`signalIp:${this._signalInfo.signalIp} clientIp:${this._signalInfo.clientIp} relayIp: ${this._signalInfo.relayIp}`)),this.emit(u,{data:r});break}default:this.emit(String(u),{data:r});break}}reGetSignalChannelUrl(){return f(this,null,function*(){try{if(!this.room.joinParams)return;xt(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(e){}})}startReconnection(){if(!this._socketInUse)return;this._socketInUse.onclose=null,this._socketInUse.close(4011);let e=this._socketInUse===this._socket;this.unbindAndCloseSocket(e?_.MAIN:_.BACKUP),this._socketInUse=null,this.emitConnectionStateChanged("DISCONNECTED"),this.reconnect()}reconnect(){return f(this,null,function*(){if(!this._isReconnecting){if(!this.room.isJoined&&this.keepAlive){this.close();return}this._isReconnecting=!0;try{this._log.warn("reconnect"),yield this.connect();let{roomId:e,useStringRoomId:t}=this.room,{relayIp:r,relayInnerIp:s,relayPort:n}=this._signalInfo,{data:a}=yield this.sendWaitForResponse({command:Z.RECONNECT_WS,data:{roomId:e,useStringRoomId:t,relayInnerIp:s,relayOuterIp:r,relayPort:n},responseCommand:J.CHANNEL_RECONNECT_RESULT});a.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),y.addSuccessEvent({key:521702,cost:V()-this._connectStartTime}),this._connectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(y.addFailedEvent({key:521702,error:a.code}),this._log.warn(`reconnect failed, ${a.code} ${a.message}`),this.room.reJoin())}catch(e){this._log.error(e),this.room.reJoin()}}})}send(e,t={}){if(this.isConnected&&!this.room.isLeft){let r={cmd:e,data:t,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},s=JSON.stringify(r);return this._socketInUse.send(s),this.bytesSent+=Gs(s),r.seq}}sendWaitForResponse({command:e,data:t,timeout:r=5e3,responseCommand:s,commandDesc:n,enableLog:a=!0,addReceiveTime:d=!1}){return new Promise((l,u)=>{let h=()=>{clearTimeout(p),u(new v({code:I.API_CALL_ABORTED,message:`${e} aborted due to connection closed`}))};this.once(Ie.CLOSE,h);let p=setTimeout(()=>{this.off(s,m),this.off(Ie.CLOSE,h);let E=new v({code:I.API_CALL_TIMEOUT,message:$({key:B.API_CALL_TIMEOUT,data:{commandDesc:n,command:e}})});a&&this._log.warn(E),u(E)},r),m=E=>{E.data.seq===g&&(clearTimeout(p),this.off(s,m),this.off(Ie.CLOSE,h),d&&(E.data.receiveTime=Date.now()),l(E))};this.on(s,m);let g=this.send(e,t)})}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:r,retries:s=0,retryTimeout:n=0}=e;return Ri({retryFunction:this.sendWaitForResponse,onError:({retry:a,reject:d,error:l})=>{!this.room.isJoined||this.destroyed||l.code===I.API_CALL_ABORTED?d(l):this.isOnline?a():(this._log.warn(`retry ${r} when connected`),this.once(Ie.ONLINE,a))},onRetrying:a=>{this._log.warn(`${t||r} timeout observed, retrying [${a}/${s}]`)},settings:{retries:s,timeout:n},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),clearTimeout(this.stopKeepAliveTimeout),Rc.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,bakRelayIps:[],endReportExtend:void 0,reportToken:void 0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(_.MAIN),this.unbindAndCloseSocket(_.BACKUP),this.emitConnectionStateChanged("DISCONNECTED"),this.emit(Ie.CLOSE)}destroy(){this.close(),this.destroyed=!0}getBackupRelayIpPair(){var t;let e=(t=this._signalInfo.bakRelayIps)==null?void 0:t.shift();return e&&(e.relayPort=e.relayPort||this._signalInfo.relayPort),e}clearBakRelayIps(){this._signalInfo.bakRelayIps=[]}stopKeepAliveIn(e=3600){if(this.keepAlive){this._log.info(`stopKeepAlive in ${e}s`),this.stopKeepAliveTimeout=setTimeout(()=>{this.keepAlive=!1,this._log.info(`close due to not used ${e}s`),this.close(),this.off(J.JOIN_ROOM_RESULT,t)},e*1e3);let t=r=>{r.data.code===0&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(J.JOIN_ROOM_RESULT,t))};this.on(J.JOIN_ROOM_RESULT,t)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info(`${this._currentState} -> ${e}`),this.emit(Ie.CONNECTION_STATE_CHANGED,{prevState:this._currentState,state:e}),this._currentState=e,e==="CONNECTED"?this.emit(Ie.CONNECTED):e==="DISCONNECTED"&&this.emit(Ie.DISCONNECTED))}};D([Mt({settings:{retries:1/0,timeout:2e3},onError(e,t){!this.room.isDestroyed&&!this.destroyed&&(this._isFirstConnect&&(y.addFailedEvent({key:521720,error:e}),this._isFirstConnect=!1),t())},onRetrying(e,t){this._log.warn(`retrying to connect ${e}`),e>=3&&e%3===0&&this.reGetSignalChannelUrl(),t&&(this._stopConnectRetry=t,(this.room.isDestroyed||this.destroyed)&&t())}})],ys.prototype,"connect",1);var t_=Je(nt());var Wh=0,Gh=!1,yc=new Set,eI=o=>Wh>2&&!Gh&&yc.size===0&&o,Jh=!1,ft=class{constructor(i){c(this,"userId");c(this,"tinyId");c(this,"_sdpSemantics");c(this,"_isUplink");c(this,"_room");c(this,"_log");c(this,"_signalChannel");c(this,"_isErrorObserved",!1);c(this,"_waitForPeerConnectionConnectedPromise");c(this,"_waitForPeerConnectionConnectedPromiseReject",null);c(this,"_peerConnection",null);c(this,"_emitter",new t_.default);c(this,"_currentState","DISCONNECTED");c(this,"_isReconnecting",!1);c(this,"_reconnectionCount",0);c(this,"_reconnectionTimer",-1);c(this,"_isFirstConnection",!0);c(this,"_prevTime",-1);c(this,"_localAddress");c(this,"_remoteAddress");this.userId=i.userId,this.tinyId=i.tinyId,this._room=i.room,this._sdpSemantics=i.room.sdpSemantics,this._isUplink=i.isUplink,this._log=i.room.getLogger().createChild({id:"n-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=i.signalChannel}beforeConnect(){this._prevTime<0&&(this._prevTime=V())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,y.addSuccessEvent({key:521705,cost:Math.min(V()-this._prevTime,30*1e3)})):this._isReconnecting&&y.addSuccessEvent({key:521706,cost:V()-this._prevTime}),this._prevTime=-1}catch(i){throw this._isFirstConnection?(this._isFirstConnection=!1,y.addFailedEvent({key:521705,error:i})):this._isReconnecting&&this._reconnectionCount>=3&&y.addFailedEvent({key:521706,error:i}),i}}initialize(){let i={iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"};this._peerConnection=new RTCPeerConnection(i),this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this)}close(i){this._log.info("close connection"),this._emitter.emit("closed",i),this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),yc.delete(this)}closePeerConnection(i=!1){this._peerConnection&&(this._log.info("close pc"),this._peerConnection.onconnectionstatechange=null,this._peerConnection.close(),this._peerConnection=null,i&&this.emitConnectionStateChangedEvent("DISCONNECTED")),this._waitForPeerConnectionConnectedPromiseReject&&this._waitForPeerConnectionConnectedPromiseReject(new v({code:I.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return Qt;let i=null;if(this._isUplink){if(!Rr()||this._peerConnection.getSenders().length===0)return Qt;i=this._peerConnection.getSenders()[0].transport}else{if(!oo()||this._peerConnection.getReceivers().length===0)return Qt;i=this._peerConnection.getReceivers()[0].transport}return i?i.state:Qt}onConnectionStateChange(i){let e=this._peerConnection.iceConnectionState,t=this.getDTLSTransportState();if(this._log.info(`connectionState: ${i.target.connectionState}, ICE: ${e}, DTLS: ${t}`),i.target.connectionState===Ce.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),i.target.connectionState===Ce.FAILED||i.target.connectionState===Ce.CLOSED){let r=`connection ${i.target.connectionState}. ICE Transport state: ${e}, DTLS Transport state: ${t}`,s=new v({message:r,code:I.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",s)}(i.target.connectionState===Ce.CONNECTED||i.target.connectionState===Ce.COMPLETED)&&(this.logSelectedCandidate(),se.logSuccessEvent({userId:this._room.userId,eventType:Ze.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(i){return i===this._currentState?!1:(i==="CONNECTED"?(Wh=0,Gh=!1,Jh=!0,yc.add(this)):yc.delete(this),S.emit(A.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:i,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:i}),this._currentState=i,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}logSelectedCandidate(){return f(this,null,function*(){if(!this._peerConnection)return;let i=yield this._peerConnection.getStats();for(let[,e]of i)if(Cr(e)){let t=i.get(e.localCandidateId),r=i.get(e.remoteCandidateId);t&&(this._log.info(`local candidate: ${t.candidateType} ${t.protocol}:${t.ip||t.address}:${t.port} ${t.networkType||""} ${t.candidateType==="relay"?`relayProtocol:${t.relayProtocol}`:""}`),this._localAddress=`${t.ip||t.address}:${t.port}`),r&&(this._log.info(`remote candidate: ${r.candidateType} ${r.protocol}:${r.ip||r.address}:${r.port}`),this._remoteAddress=`${r.protocol}:${r.ip||r.address}`);break}})}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise?this._waitForPeerConnectionConnectedPromise:(this._waitForPeerConnectionConnectedPromise=new Promise((i,e)=>{if(this._currentState==="CONNECTED")return i();this._waitForPeerConnectionConnectedPromiseReject=e;let t=a=>{a.state==="CONNECTED"&&(clearTimeout(n),s(),i())},r=({room:a})=>{a===this._room&&(clearTimeout(n),s(),e(new v({code:I.API_CALL_ABORTED,message:$({key:B.CONNECTION_ABORTED,data:"leave room"})})))},s=()=>{S.off(A.LEAVE_SUCCESS,r,this),this._emitter.off("connection-state-changed",t,this)},n=setTimeout(()=>{s();let a=new v({code:I.API_CALL_TIMEOUT,message:"connection timeout"});Wh+=1,eI(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),Gh=!0,this._emitter.emit("firewall-restriction")),e(a)},Fs);S.on(A.LEAVE_SUCCESS,r,this),this._emitter.on("connection-state-changed",t,this)}),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally(()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null}),this._waitForPeerConnectionConnectedPromise)}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(Ie.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=Wi()){this._log.warn(`SDK has tried reconnect for ${this._reconnectionCount} times, but all failed, please check your network`),this.stopReconnection();let i=new v({code:this._isUplink?I.UPLINK_RECONNECTION_FAILED:I.DOWNLINK_RECONNECTION_FAILED,message:$({key:this._isUplink?B.UPLINK_RECONNECTION_FAILED:B.DOWNLINK_RECONNECTION_FAILED})});return this.emitConnectionStateChangedEvent("DISCONNECTED"),this._emitter.emit("error",i),-1}return this._signalChannel.isConnected?(this._reconnectionCount+=1,this._log.warn(`reconnect() trying [${this._reconnectionCount}]`),1):(this._log.warn("reconnect() signal channel is not connected, suspend reconnection until signal is connected"),this._signalChannel.once(Ie.CONNECTED,this.reconnect,this),-1)}on(i,e,t){this._emitter.on(i,e,t)}off(i,e,t){this._emitter.off(i,e,t)}getIsReconnecting(){return this._isReconnecting}get isH264(){var i,e;return!!((e=(i=this._peerConnection)==null?void 0:i.remoteDescription)!=null&&e.sdp.includes("H264"))}setOffer(i){var e;return(e=this._peerConnection)==null?void 0:e.setLocalDescription(i)}setAnswer(i){var e;return(e=this._peerConnection)==null?void 0:e.setRemoteDescription(i)}};D([Rt(521712,!1)],ft.prototype,"setOffer",1),D([Rt(521713,!1)],ft.prototype,"setAnswer",1);var zh=Je(Xh());var De=function(o){return zh.default.parse(o)},qt=function(o){return zh.default.write(o)},c_=function(o){let i=De(o);return i.media.forEach(e=>{e.type===_.AUDIO&&e.fmtp.forEach(t=>{t.config+=";sprop-stereo=1;stereo=1"})}),qt(i)};function l_(o){let i=De(o);return i.media.forEach(e=>{var t,r;if(e.type===_.VIDEO){let s=new Set;e.rtp.forEach(({payload:a,codec:d})=>d==="H264"&&s.add(a)),e.fmtp.forEach(({payload:a,config:d})=>{let l=d.match(/apt=(\d+)/);l&&l[1]&&s.has(Number(l[1]))&&s.add(a)});let n=({payload:a})=>!s.has(a);e.rtp=e.rtp.filter(n),e.rtcpFb=(t=e.rtcpFb)==null?void 0:t.filter(n),e.fmtp=e.fmtp.filter(n),e.payloads=(r=e.payloads)==null?void 0:r.split(" ").filter(a=>!s.has(Number(a))).join(" ")}}),qt(i)}function bc(o){return Object.keys(o).filter(i=>o[i])}var Ns=class Ns extends ft{constructor(e){super(w(M({},e),{isUplink:!1}));c(this,"_flag",0);c(this,"isRobot",!1);c(this,"role","anchor");c(this,"remoteAudioTrack");c(this,"remoteVideoTrack");c(this,"remoteAuxiliaryTrack");c(this,"ssrc",{audio:0,video:0,auxiliary:0});c(this,"_isSDPExchanging",!1);c(this,"_videoCodec");this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=e.remoteAudioTrack||new Ei(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new Pi(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new Ts(this._room,this)}get videoCodec(){var t,r;let e=(r=(t=this._peerConnection)==null?void 0:t.remoteDescription)==null?void 0:r.sdp;return e?e.includes("H264")?"h264":"vp8":this._videoCodec||"h264"}set videoCodec(e){this._videoCodec=e}get subscribeState(){let e={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(this.remoteVideoTrack.mediaType&8?e.smallVideo=!0:e.video=!0),this.remoteAudioTrack.isSubscribed&&(e.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(e.auxiliary=!0),e}get muteState(){return Kt(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,r,s;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(r=this.remoteVideoTrack)==null||r.onFlagChanged(),(s=this.remoteAuxiliaryTrack)==null||s.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===_.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var s,n;let t=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&t!==e&&((s=this.remoteVideoTrack)==null||s.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),r}onTrack(e){let t=e.streams[0],{track:r}=e,s=t.id===Vs?_.MAIN:_.AUXILIARY;this._log.debug(`ontrack ${s} ${r.kind}`);let n=_.AUDIO;r.kind===_.VIDEO&&(n=s===_.MAIN?_.VIDEO:_.AUXILIARY);let a=this.remoteAudioTrack;n===_.VIDEO?a=this.remoteVideoTrack:n===_.AUXILIARY&&(a=this.remoteAuxiliaryTrack),a.setInputMediaStreamTrack(r)}addRRTRLine(e){let t=e.split(`\r
|
|
59
59
|
`),r=new Map;t.forEach((n,a)=>{/^a=rtcp-fb:/.test(n)&&t[a+1]&&!/^a=rtcp-fb:/.test(t[a+1])&&r.set(a+1,`${n.match(/^a=rtcp-fb:\d+/)[0]} rrtr`)});let s=[...r];for(let n=0;n<s.length;n++){let[a,d]=s[n];t.splice(a+n,0,d)}return t.join(`\r
|
|
60
60
|
`)}addSPSDescription(e){let t=De(e);return t.media.forEach(r=>{r.type===_.VIDEO&&r.fmtp.forEach(s=>{s.config+=";sps-pps-idr-in-keyframe=1"})}),qt(t)}removeSDESDescription(e){let t=["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"],r=De(e);return r.media.forEach(s=>{s.ext&&(s.ext=s.ext.filter(n=>!t.includes(n.uri)))}),qt(r)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return f(this,null,function*(){var r,s;try{if((((r=this._peerConnection)==null?void 0:r.connectionState)===Ce.NEW||((s=this._peerConnection)==null?void 0:s.connectionState)===Ce.CONNECTING)&&(yield this.waitForPeerConnectionConnected()),this.isSubscriptionStateNotChanged(e)){this._peerConnection||(this.initialize(),yield this.connect(e));return}if(this._log.info(`subscribe ${t} ${JSON.stringify(e)}`),this._peerConnection||this._isSDPExchanging){let n="subscribe_change";Object.values(e).find(a=>a===!0)||(n="unsubscribe"),yield this.sendSubscription(n,e)}else this.initialize(),yield this.connect(e)}catch(n){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${n.message} ${JSON.stringify(this.muteState)}`),new v({code:I.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):n}})}unsubscribe(r){return f(this,arguments,function*({remoteTracks:e,streamType:t}){if(this._currentState==="CONNECTED"&&(t==="main"&&!this.isMainStreamSubscribed||t==="auxiliary"&&!this.isAuxStreamSubscribed)){this._log.info(`${t} stream already unsubscribed`);return}let s=M({},this.subscribeState);e.forEach(a=>{switch(a.mediaType){case 1:s.audio=!1;break;case 4:s.video=!1;break;case 8:s.smallVideo=!1;break;case 2:s.auxiliary=!1;break;default:break}});let n="subscribe_change";Object.values(s).find(a=>a===!0)||(n="unsubscribe"),this._log.info(`${n==="unsubscribe"?n:"subscribe"} ${t} [${bc(s)}]`),yield this.sendSubscription(n,s),n==="unsubscribe"&&(this.closePeerConnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"))})}sendSubscription(e,t=this.subscribeState){let r={srcTinyId:this.tinyId,srcUserId:this.userId},s=Z.UNSUBSCRIBE,n=J.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(r={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},s=Z.SUBSCRIBE_CHANGE,n=J.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:s,data:r,responseCommand:n,timeout:1e4}).then(({data:a})=>{if(a.code!==0){let d=new v({code:a.code,message:$({key:B.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(d),d}})}connect(){return f(this,arguments,function*(e=this.subscribeState){try{yield this.exchangeSDP(e),yield this.waitForPeerConnectionConnected()}catch(t){throw this.closePeerConnection(!0),t}})}exchangeSDP(e){return f(this,null,function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info("createOffer success, sending offer");let{type:t,sdp:r}=this._peerConnection.localDescription,s={type:t,sdp:r,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},n=yield this._signalChannel.sendWaitForResponse({command:Z.SUBSCRIBE,commandDesc:"exchange sdp",data:s,responseCommand:J.SUBSCRIBE_RESULT,timeout:el});if(!this._peerConnection){let a=new v({code:I.INVALID_OPERATION,message:$({key:B.CONNECTION_CLOSED})});throw this._log.warn(a),a}yield this.onSubscribeResult(n),this._isSDPExchanging=!1}catch(t){throw this._isSDPExchanging=!1,t}})}createOffer(){return f(this,null,function*(){let e={voiceActivityDetection:!1};St()&&this._sdpSemantics===gr?(this._peerConnection.addTransceiver(_.AUDIO,{direction:ne.RECVONLY}),this._peerConnection.addTransceiver(_.VIDEO,{direction:ne.RECVONLY}),this._peerConnection.addTransceiver(_.VIDEO,{direction:ne.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:r}=yield pd();r||(this._log.warn("remove h264 desc from sdp"),t.sdp=l_(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=c_(t.sdp),this._sdpSemantics===gr&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this.setOffer(t)})}onSubscribeResult(e){return f(this,null,function*(){let{code:t,message:r=""}=e&&e.data||{},{type:s,sdp:n}=e&&e.data&&e.data.data||{};if(t===Hr)throw new v({code:I.NOT_SUPPORTED_H264,message:$({key:B.NOT_SUPPORTED_H264DECODE})});try{if(t!==0)throw new v({code:t,message:$({key:B.EXCHANGE_SDP_FAILED,data:{errMsg:r}})});this._log.debug(`accept remote answer: ${n}`),yield this.setAnswer({type:s,sdp:n}),this.updateSSRC(n)}catch(a){throw this._log.error(a),a}})}updateSSRC(e){try{De(e).media.forEach(r=>{if(r.ssrcs)if(r.type===_.AUDIO){let s=r.ssrcs.find(n=>{var a;return(a=n.value)==null?void 0:a.includes(Vs)});s&&(this.ssrc.audio=Number(s.id))}else{let s=r.ssrcs.find(a=>{var d;return(d=a.value)==null?void 0:d.includes(Vs)}),n=r.ssrcs.find(a=>{var d;return(d=a.value)==null?void 0:d.includes(zc)});s&&(this.ssrc.video=Number(s.id)),n&&(this.ssrc.auxiliary=Number(n.id))}})}catch(t){}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return f(this,null,function*(){if(!(Le(Ns.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch(t){let r=Zt(this._reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${r/1e3}s`),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},r)}})}getIsReconnecting(){return this._isReconnecting}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}getCurrentState(){return this._currentState}setDelay({audioDelay:e,videoDelay:t}){this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=t}get audioReceiver(){var e;return((e=this._peerConnection)==null?void 0:e.getReceivers()[0])||null}};D([Y(e=>function(...t){return new Promise((r,s)=>{let n=a=>{this._emitter.off("closed",n),s(new v({code:I.API_CALL_ABORTED,message:$({key:B.CONNECTION_ABORTED,data:a})}))};this._emitter.on("closed",n),e.apply(this,t).then(r,s).finally(()=>{this._emitter.off("closed",n)})})})],Ns.prototype,"subscribe",1),D([Rt(521717,!1)],Ns.prototype,"unsubscribe",1),D([Ct(ft.prototype.afterConnect),Md(ft.prototype.beforeConnect)],Ns.prototype,"connect",1);var Qh=Ns,Yh=Qh;var h_={voiceActivityDetection:!1},vs=class vs extends ft{constructor(e){super(w(M({},e),{isUplink:!0}));c(this,"localMainAudioTrack",null);c(this,"localMainVideoTrack",null);c(this,"localAuxAudioTrack",null);c(this,"localAuxVideoTrack",null);c(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0});c(this,"_isPublishingAux",!1);c(this,"_publishingLocalAudioTrack");c(this,"_publishingLocalVideoTrack");c(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0});c(this,"flag",0)}get videoCodec(){return this._mediaSettings.videoCodec.toLowerCase()||"h264"}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}initialize(){super.initialize(),this.installEvents()}reset(){this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this.uninstallEvents()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this._emitter.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this._emitter.on("connection-state-changed",this.handleConnectionStateChange,this)}uninstallEvents(){this._emitter.off("connection-state-changed",this.handleConnectionStateChange,this)}emitConnectionStateChangedEvent(e,t){var n,a,d;let r=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&r!==e&&(t?t.emit("connection-state-changed",{prevState:r,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:r,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:r,state:e}),(d=this._publishingLocalVideoTrack)==null||d.emit("connection-state-changed",{prevState:r,state:e}))),s}publish(s){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:r}){this._peerConnection||this.initialize(),e&&(this._publishingLocalAudioTrack=e),t&&(this._publishingLocalVideoTrack=t),this._isPublishingAux=r;let n;t&&!r&&t.small&&(n=this._room.videoManager.smallTrack),this.sendMediaSettings(),St()?yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:n,isAuxiliary:r}):yield this.publishByAddTrack({localAudioTrack:e,localVideoTrack:t,smallTrack:n}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,r?(t&&(this.localAuxVideoTrack=t),e&&(this.localAuxAudioTrack=e)):(t&&(this.localMainVideoTrack=t),e&&(this.localMainAudioTrack=e)),this.installTrackMuteEvents(e,t),this.sendMutedFlag()})}publishByTransceiver(n){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:r,isAuxiliary:s}){this._log.info("publish by transceiver");let a=new MediaStream,d=t==null?void 0:t.outMediaTrack,l=e==null?void 0:e.outMediaTrack;l&&a.addTrack(l),d&&a.addTrack(d);let u=this._peerConnection.getTransceivers();if(u.length===0)this._peerConnection.addTransceiver(l||_.AUDIO,{direction:ne.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(s?_.VIDEO:d||_.VIDEO,{direction:ne.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(r||_.VIDEO,{direction:ne.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(s?d||_.VIDEO:_.VIDEO,{direction:ne.SENDONLY,streams:[a]}),yield this.connect();else{let h=[];if(l&&(u[0].sender.track||h.push(0),yield u[0].sender.replaceTrack(l),yield this.setBandwidth({bandwidth:(e==null?void 0:e.profile.bitrate)||40,type:_.AUDIO})),d){let p=s?3:1;yield u[p].sender.replaceTrack(d),yield this.setBandwidth({bandwidth:t.profile.bitrate,type:_.VIDEO,videoType:s?_.AUXILIARY:_.BIG}),h.push(p),r&&(yield u[2].sender.replaceTrack(r),yield this.setBandwidth({bandwidth:t.small.bitrate,type:_.VIDEO,videoType:_.SMALL}),h.push(2))}yield this.setTransceiverDirection(ne.SENDONLY,h),yield this.doPublishChange(),t==null||t.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),t==null||t.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"})}})}publishByAddTrack(s){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:r}){this._log.info("publish by addtrack");let n=t==null?void 0:t.outMediaTrack,a=e==null?void 0:e.outMediaTrack;if(this._peerConnection&&this._peerConnection.connectionState!=="new"){e&&a&&(yield this.addTrack(e)),n&&(yield this.addTrack(t));return}let d=new MediaStream;if(a&&d.addTrack(a),n&&d.addTrack(n),a&&this._peerConnection.addTrack(a,d),n&&(this._peerConnection.addTrack(n,d),r)){let l=new MediaStream;l.addTrack(r),this._peerConnection.addTrack(r,l)}yield this.connect()})}enableSmall(e){return f(this,null,function*(){let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.setTransceiverDirection(ne.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(ne.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()})}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(r){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){if(!yr()){if(e&&e.outMediaTrack&&!t&&this.localMainVideoTrack){yield this.removeTrack(e),this.localMainAudioTrack=null;return}if(t&&t.outMediaTrack&&!e&&this.localMainAudioTrack){yield this.removeTrack(t),this.localMainVideoTrack=null;return}yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),this.emitConnectionStateChangedEvent("DISCONNECTED",t);return}let s=t&&t===this.localAuxVideoTrack,n=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),d=[];e&&(s?this.localAuxAudioTrack=null:this.localMainAudioTrack=null,!this.localAuxAudioTrack&&!this.localMainAudioTrack&&(yield a[0].replaceTrack(null),d.push(0))),n&&(s?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=w(M({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),d.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=w(M({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),d.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.setTransceiverDirection(ne.INACTIVE,d),yield this.doPublishChange(!1)):yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),t==null||t.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return f(this,null,function*(){let t={state:this._room.publishState,constraintConfig:this._mediaSettings},r=yield this._signalChannel.sendWaitForResponse({command:Z.PUBLISH_STATE_CHANGE,data:t,responseCommand:J.PUBLISH_STATE_CHANGE_RESULT,enableLog:e});this.checkPublishResultCode(r.data.code,r.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:Z.UNPUBLISH,commandDesc:"unpublish",responseCommand:J.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===I.API_CALL_TIMEOUT)return Promise.resolve();throw t})}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let r=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:s,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:s=this._publishingLocalVideoTrack),Ni){if(r&&r.outMediaTrack){let a=r.outMediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=r.profile.bitrate*1e3,this._mediaSettings.audioFs=a.sampleRate||0}if(s&&s.outMediaTrack){let a=s.outMediaTrack.getSettings();this._mediaSettings.videoWidth=a.width||0,this._mediaSettings.videoHeight=a.height||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=s.profile.bitrate*1e3,s.small&&(this._mediaSettings.smallVideoWidth=s.small.width,this._mediaSettings.smallVideoHeight=s.small.height,this._mediaSettings.smallVideoFps=s.small.frameRate,this._mediaSettings.smallVideoBps=s.small.bitrate*1e3)}if(n&&n.outMediaTrack){let a=n.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=a.width||0,this._mediaSettings.auxVideoHeight=a.height||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=n.profile.bitrate*1e3}}else r&&r.outMediaTrack&&(this._mediaSettings.audioChannel=r.profile.channelCount,this._mediaSettings.audioBps=r.profile.bitrate*1e3,this._mediaSettings.audioFs=r.profile.sampleRate),s&&s.outMediaTrack&&(this._mediaSettings.videoWidth=s.profile.width,this._mediaSettings.videoHeight=s.profile.height,this._mediaSettings.videoFps=s.profile.frameRate,this._mediaSettings.videoBps=s.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:Z.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:J.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return f(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is adding ${e.kind} track to current published local ${t?_.AUXILIARY:_.MAIN} stream`),St()?yield this.addTrackByTransceiver(e,t):yield this.addTrackBySender(e)})}addTrackByTransceiver(e,t){return f(this,null,function*(){var s;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===_.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),n===1&&((s=this.localMainVideoTrack)!=null&&s.small)&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===ne.INACTIVE&&(yield this.setTransceiverDirection(ne.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}addTrackBySender(e){return f(this,null,function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;yr()&&this._peerConnection.getTransceivers().findIndex(s=>s.direction==="stopped")>=0&&(this._log.warn("transceiver is stopping, negotiate sdp first"),yield this.updateOffer("remove",t));let r=this._peerConnection.getSenders().find(s=>s.track&&s.track.kind===t.kind);if(r&&r.track){this._log.warn("sender already exists, remove sender first");let s=r.track;this.removeSender(r),yield this.updateOffer("remove",s)}if(t&&this._peerConnection.addTrack(t,new MediaStream([t])),t.kind===_.VIDEO&&e instanceof je&&e.small){let s=new MediaStream,{smallTrack:n}=this._room.videoManager;s.addTrack(n),this._peerConnection.addTrack(n,s)}yield this.updateOffer("add",t)})}isNeedToResetOfferOrder(){if(this._sdpSemantics===Mo||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=De(e);for(let r=0;r<t.media.length;r++)if(Number(t.media[r].mid)===0&&t.media[r].type===_.VIDEO)return!0;return!1}removeSender(e){let t=null;yr()&&(t=this._peerConnection.getTransceivers().find(r=>r.sender&&r.sender.track===e.track)),this._peerConnection.removeTrack(e),t&&le(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return f(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${t?_.AUXILIARY:_.MAIN} stream`),St()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)})}removeTrackByTransceiver(e,t){return f(this,null,function*(){if(!e.outMediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===_.AUDIO)yield r[0].sender.replaceTrack(null);else{let s=t?3:1;yield r[s].sender.replaceTrack(null),s===1&&e.small&&(yield r[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(ne.INACTIVE,[s])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,t){return f(this,null,function*(){if(!ee)return;let r=!1,s=!1;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let n=this._peerConnection.getTransceivers();if(t.forEach(l=>{n[l].direction!==e&&(n[l].direction=e,r=!0)}),r){this._log.info("updating offer");let l=yield this._peerConnection.createOffer();yield this.setOffer(l)}let a=-1,d=this._peerConnection.remoteDescription.sdp.split(`\r
|
|
61
61
|
`).map(l=>{if(l.match(new RegExp(`a=(${ne.INACTIVE}|${ne.RECVONLY}|${ne.SENDONLY})`))&&a++,t.includes(a)){if(e===ne.INACTIVE&&l.includes(`a=${ne.RECVONLY}`))return s=!0,`a=${e}`;if(e===ne.SENDONLY&&l.includes(`a=${ne.INACTIVE}`))return s=!0,`a=${ne.RECVONLY}`}return l}).join(`\r
|