trtc-sdk-v5 5.11.0-beta.4 → 5.11.0-beta.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/trtc.esm.js CHANGED
@@ -30,7 +30,7 @@ ${t.stack}`)),this.sendRequest(yi(this._configs.sdkAppId,Ki.LOG),r)}sendRequest(
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=rl,r.innerText=`${kt()?"\u8BE6\u60C5 >":"Detail >"}`,r.onclick=this.onCollapseClick.bind(this);let o=i.content.firstChild,n=o.querySelector(`.${Ea}`);return n.appendChild(r),n.appendChild(t),n.appendChild(e),o}addDiaLog(){nl()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${vs}`).onclick=i=>i.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",C.info("show autoplay dialog"),re.uploadEvent({log:J_}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){C.warn("confirm clicked, try resume stream"),E.emit(A.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let i=this._dialogNode.querySelector(`.${rm}`);i.style.visibility=`${this._showDetail?"hidden":"visible"}`,i.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||re.uploadEvent({log:q_}),this._isCollapseClicked=!0}onQuestionClick(){window.open(am,"_blank"),this._isQuestionClicked||re.uploadEvent({log:j_}),this._isQuestionClicked=!0}},cm=sl;var ft=class extends di{constructor(e){super(e,p.VIDEO);d(this,"stat",{});d(this,"_calculateTimeout",-1);d(this,"viewMirror",!1);d(this,"objectFit");d(this,"container");d(this,"canvas");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(p.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,(t=this.container)==null||t.appendChild(this.elementToRender),this.bindElementEvents(),this.calculateStat()}get styleAttribute(){let e=`width: 100%; height: 100%; object-fit: ${this.objectFit};background-color: black;`;return this.viewMirror&&(e+="transform: scaleX(-1);"),e}setContainer(e){var 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(p.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(p.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent)}handleTrackEvent(e){var t;super.handleTrackEvent(e),e.type===p.MUTE&&((t=this.stat)!=null&&t.fps)&&(this.stat.fps=0)}handleElementEvent(e){var r,o;if(this.mode===2)return;super.handleElementEvent(e);let t=e.type;if(t===p.PAUSE&&(this.container&&document.getElementById(this.container.id)||this._log.warn(`${this.kind} player has been remove, element ID: ${(r=this.container)==null?void 0:r.id}`),this.container&&this.container!==document.getElementById(this.container.id)&&(this._pausedRetryCount=Ir,this._log.info(`view container ${(o=this.container)==null?void 0:o.id} is recreated`)),this._pausedRetryCount>0&&!nl()&&(this._log.info(`[${Ir-this._pausedRetryCount+1}/${Ir}] ${this.kind} player auto resume when paused`),this.resume(),this._pausedRetryCount--),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){let n=this.element.style.transform;t===p.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=n.replace("scaleX(-1)",""):t===p.LEAVE_PICTURE_IN_PICTURE&&!n.includes("scaleX")&&(this.element.style.transform=`${n} scaleX(-1)`)}}setCanvas(e,t=1){var r,o,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?((o=this.element)==null||o.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){this.element&&(this.element.poster=e)}stop(e=0){var t;super.stop(e),(t=this.canvas)==null||t.remove()}play(){return this.element?this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender):this.initializeElement(),this.mode===2?Promise.resolve():super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(ue.MEDIA_TRACK_CHANGED,e),e!==null&&(this.bindTrackEvents(),this.element&&this.mode!==2&&(this.element.srcObject=new MediaStream([e]),this.element.remove()),this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender)))}getVideoFrame(){if(this.canvas)return this.canvas.toDataURL("image/png");if(!this.element)return"";let e=document.createElement("canvas");return e.width=this.element.videoWidth,e.height=this.element.videoHeight,e.getContext("2d").drawImage(this.element,0,0),e.toDataURL("image/png")}getElement(){return this.element}calculateStat(){try{if(wr()&&this.element&&this._calculateTimeout<0){let e=0,t=null,r=(o,n)=>{this.stat.width=n.width,this.stat.height=n.height,t&&(this.stat.fps=Math.round((n.presentedFrames-t.presentedFrames)/(o-e)*1e3)),e=o,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 Bi(s,i){return f(this,null,function*(){if(!s.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield s.audioWorklet.addModule(i),C.info("worklet addModule success")}catch(e){throw C.info(`worklet addModule catch error. ${e.message}`),e}})}var Go;typeof AudioContext!="undefined"?Go=AudioContext:typeof webkitAudioContext!="undefined"?Go=webkitAudioContext:typeof mozAudioContext!="undefined"&&(Go=mozAudioContext);var Ht,dm=-1;lm();function lm(){try{if(Ht)return;Ht=new Go({sampleRate:48e3}),Ht.onstatechange=()=>{C.info(`context state: ${Ht.state}${Ht.state!=="running"?` visibilityState: ${document.visibilityState}`:""}`),Ds()},clearTimeout(dm)}catch(s){C.error(`initAudioContext failed: ${s} typeof AudioContextClass: ${typeof Go}`),dm=setTimeout(lm,1e3)}}var Ds=()=>{Ht.state==="suspended"?(Os(),document.addEventListener("click",Ds)):Ht.state==="interrupted"?Os():(document.removeEventListener("visibilitychange",Ds),document.removeEventListener("click",Ds))},al=0,cl=-1;function Os(){return new Promise((s,i)=>{if(Ht.state==="running")return s();Date.now()-al<1e3?(clearTimeout(cl),cl=setTimeout(()=>{al=Date.now(),Ht.resume().then(s,i)},1e3)):(clearTimeout(cl),al=Date.now(),Ht.resume().then(s,i))}).catch(s=>{C.warn(`context resume failed: ${s}`),document.addEventListener("visibilitychange",Ds)})}document.addEventListener("click",Ds);var Ee=s=>Ht;var De=class{constructor(i){this.name=i;d(this,"node");d(this,"node2");d(this,"pre",new Set);d(this,"next",new Set);d(this,"context");d(this,"connectedNodes",new Set);d(this,"nextInputChannelMap",new Map);d(this,"_channelCount",1)}get channelCount(){return this._channelCount}set channelCount(i){this._channelCount=i,this.setChannelCount(this.node,i),this.setChannelCount(this.node2,i),this.next.forEach(e=>e.channelCount=i)}setChannelCount(i,e){!i||i instanceof ScriptProcessorNode||(i.channelCountMode="explicit",i.channelCount=e||this.channelCount||1)}setContext(i){this.context=i,this.node&&i.addMixWeight()}removeContext(){var i;this.node&&((i=this.context)==null||i.reduceMixWeight()),delete this.context}replaceNode(i){var e;if(i!==this.node)try{this.node?this._disconnect():(e=this.context)==null||e.addMixWeight(),this.node=i,this.setChannelCount(this.node),this.preNodeReconnect(),this.reconnect()}catch(t){C.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(),b.addSuccessEvent({key:502701})}catch(r){C.error(r),b.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(),b.addSuccessEvent({key:502702})}catch(e){C.error(e),b.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}},Ia=class extends De{constructor(e=256){super();this.fftSize=e;d(this,"dataArray",new Uint8Array(0))}setNode(e){e.fftSize=this.fftSize,this.dataArray=new Uint8Array(e.frequencyBinCount),super.setNode(e)}getByteTimeDomainData(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),this.dataArray}get level(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),Math.max(...this.dataArray)/128-1}get timeDomainPathData(){let e=this.getByteTimeDomainData(),t=1,r=0,o=0,n=`M${r},${o}`;for(let a=0;a<e.length;a++)o=e[a]/128*100/2,n+=`L${r},${o}`,r+=t;return n}},Wo=class{constructor(){d(this,"source",new De);d(this,"gain",new De);d(this,"destination",new De)}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){this.source.replaceNode(Jo(i))}get track(){var i;return(i=this.stream)==null?void 0:i.getAudioTracks()[0]}get stream(){var i;return(i=this.destination.node)==null?void 0:i.stream}},Ms=class extends Wo{constructor(e){super();this.context=e;d(this,"aec",new De("aec"));d(this,"mixNode",new De("mixNode"));d(this,"silentNode",new De("silentNode"));d(this,"denoiser",new De("denoiser"));d(this,"voiceChanger",new De("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)}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}},Aa=class{constructor(){d(this,"audioContext",Ee("audio-mixer"));d(this,"destination",this.audioContext.createMediaStreamDestination());d(this,"inputs",new Set);d(this,"mixWeight",0);this.destination.channelCount=1}addMixWeight(i=1){this.mixWeight+=i,this.mixWeight-1===i+1>>1&&this.mixOnChange()}reduceMixWeight(i=1){this.addMixWeight(-i)}close(){this.inputs.forEach(i=>i.remove())}get mixTrack(){return this.destination.stream.getAudioTracks()[0]}},um=new WeakMap;function Jo(s){let i=um.get(s);if(i)return i;let e=Ee();if(s instanceof HTMLAudioElement)i=e.createMediaElementSource(s);else if(s instanceof MediaStreamTrack)i=e.createMediaStreamSource(new MediaStream([s]));else return s;return um.set(s,i),i}var _t=class _t{constructor(i){d(this,"_volume",0);d(this,"_volumeDb",0);d(this,"_log");d(this,"_scriptProcessorNode",null);d(this,"_audioWorkletNode",null);d(this,"_interval",200);d(this,"ready",this.preload());let{log:e}=i;this._log=e,E.on(A.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-_t.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!_t.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);';_t.workletReady=Bi(_t.audioContext,URL.createObjectURL(new Blob([i],{type:"application/javascript"})))}return _t.workletReady.then(()=>this.initAudioWorklet()).catch(i=>(this._log.error(`volumeMeter preload error: ${i}`),this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(_t.audioContext,"volume-meter");let i=!1;this._audioWorkletNode.port.onmessage=e=>{_t.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}`),re.logFailedEvent({userId:this._log.userId,eventType:st.LOAD_WORKLET,error:i}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=Ee("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=i=>{_t.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,E.off(A.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}getVolumeDb(){return Math.floor(this._volumeDb*100)}handleAudioLevelInterval(i){var t;let{interval:e}=i;this._interval=e,(t=this._audioWorkletNode)==null||t.port.postMessage({name:"setIntervalTime",intervalTime:e})}};d(_t,"lastMessageTime",0),d(_t,"audioContext",Ee("volume-meter")),d(_t,"workletReady");var Ra=_t,Ca=class extends De{constructor(e){super();d(this,"_volumeMeter");this._volumeMeter=new Ra(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()}}},Ur=Ra;var fm=$e(Ye(),1);var mm=s=>i=>i.deviceId===s;var qo=class{constructor(i,e="Input"){d(this,"kind");d(this,"type");d(this,"devices",[]);this.kind=i,this.type=e}update(i,e){let t=i.filter(r=>r.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);if(this.devices.length===1&&ks(this.devices[0])){this.devices=t;return}e&&(t.forEach(r=>{if(r.deviceId&&!this.devices.find(mm(r.deviceId))){let o=`${this.kind}${this.type}Added`;C.warn(`${o}: ${JSON.stringify(r)}`),e.emit(o,r)}}),this.devices.forEach(r=>{if(r.deviceId&&!t.find(mm(r.deviceId))){let o=`${this.kind}${this.type}Removed`;C.warn(`${o}: ${JSON.stringify(r)}`),e.emit(o,r)}})),this.devices=t}hasDevice(i){return!!this.devices.find(e=>e.deviceId===i)}},dl=class extends fm.EventEmitter{constructor(){super();d(this,"audioInputs",new qo(p.AUDIO));d(this,"videoInputs",new qo(p.VIDEO));d(this,"audioOutputs",new qo(p.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(){ya().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 ya(e);return this.audioInputs.update(t,this),this.videoInputs.update(t,this),this.audioOutputs.update(t,this),this})}},Le=io||ts?null:new dl;function ks(s){return s.deviceId===s.groupId&&s.groupId===""}function ya(){return f(this,arguments,function*(s=0){if(wi()||!ma())return[];let i=yield navigator.mediaDevices.enumerateDevices();if(s!==0){let e={audio:!1,video:!1};if(i.forEach(t=>{ks(t)&&(t.kind===p.AUDIO_INPUT?e.audio=!0:t.kind===p.VIDEO_INPUT&&(e.video=!0))}),s===2&&(e.audio=!1),s===1&&(e.video=!1),e.audio||e.video){let t;try{t=yield navigator.mediaDevices.getUserMedia(e),e.audio&&Os()}catch(r){C.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&&ll.add(`${e.deviceId}_${e.kind}`),e.getCapabilities&&(r.getCapabilities=()=>e.getCapabilities()),r})})}function nt(s=!1){return Le.update(s?1:0).then(i=>i.audioInputs.devices)}function gt(s=!1){return Le.update(s?2:0).then(i=>i.videoInputs.devices)}var pm=!1;function _m(){return f(this,null,function*(){try{pm||(pm=!0,C.info(`speakers:${(yield lr()).map(s=>` ${s.deviceId.slice(0,8)}: ${s.label}`)}`))}catch(s){}})}function lr(s=!1){return f(this,null,function*(){return(Ie||xe)&&(s=!1),Le.update(s?1:0).then(i=>i.audioOutputs.devices)})}var ll=new Set;function gm(s){if(s instanceof CanvasCaptureMediaStreamTrack||!(s instanceof MediaStreamTrack))return!1;let i=s.label.toLocaleLowerCase();if(i.includes("camera")||i.includes("webcam"))return!0;let t=`${((s==null?void 0:s.getSettings())||{}).deviceId}_${p.VIDEO_INPUT}`;return!!ll.has(t)}function Tm(s){if(s instanceof CanvasCaptureMediaStreamTrack||!(s instanceof MediaStreamTrack))return!1;let i=s.label.toLocaleLowerCase();if(i.includes("mic")||i.includes("\u9EA6\u514B\u98CE"))return!0;let t=`${((s==null?void 0:s.getSettings())||{}).deviceId}_${p.AUDIO_INPUT}`;return!!ll.has(t)}function ul(s,i){return f(this,null,function*(){let t=(yield nt()).find(r=>r.deviceId===Ar);return!i&&(t==null?void 0:t.groupId)===s||(t==null?void 0:t.groupId)===s&&t.label===i})}function Em(o){return f(this,arguments,function*({newDeviceId:s,oldDeviceId:i,oldGroupId:e,oldLabel:t,kind:r}){return s!==i?!1:r===p.AUDIO&&s===Ar?yield ul(e,t):!0})}var ba,hl=class extends Wo{constructor(e){super();this.log=e;d(this,"volumeMeter");d(this,"volumeDestination");d(this,"analyser",new Ia);this.volumeMeter=new Ca({log:this.log}),this.volumeDestination=new De,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},Na=class s extends di{constructor(e){super(e,p.AUDIO);d(this,"_outputDeviceId");d(this,"_volume",1);d(this,"_destination",Ee("player").createMediaStreamDestination());d(this,"pipeline");d(this,"volumeMeterMode","worklet");this.mode=0,this.pipeline=new hl(this._log)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(e){if((Kt==="15.2"||Kt==="15.3"||Kt==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}let r=ba||new Audio;r.setAttribute("autoplay","autoplay"),r.srcObject=this.getMediaStream(),r.muted=this.muted,this.element=r,q(e)&&(this.element.volume=Math.min(Math.max(e,0),1)),r===ba&&(ba=void 0),this.bindElementEvents()}play(e){return f(this,null,function*(){if(this.track)return this.pipeline.source.node||this.pipeline.replaceSource(this.track),this.element||this.initializeElement(e==null?void 0:e.volume),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),this.volumeMeterMode==="worklet"?this.pipeline.volumeMeter.init():this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(Ee("player").createAnalyser()),_m(),He(s.prototype,this,"play").call(this)})}stop(e=0){this.pipeline.destroy(),super.stop(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()}},va=class extends Na{setTrack(i){this.track!==i&&(this.unbindTrackEvents(),this.track=i,this.emit(ue.MEDIA_TRACK_CHANGED,i),i&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([i]))))}setVolume(i){this._volume=i,this.element&&(this.element.volume=i)}},Da=class extends Na{constructor(e){super(e);d(this,"_sourceElement");d(this,"_output",new De);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,o;((r=(t=this.element)==null?void 0:t.error)==null?void 0:r.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(ue.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([e]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e])),this.pipeline.source.channelCount=((o=e.getSettings())==null?void 0:o.channelCount)||1,this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){this._volume=e,this.useDestination?(this.pipeline.setVolume(e),this._log.info(`set pipeline volume: ${e}`)):e<=1?this.element?(this._log.info(`set element volume: ${e}`),this.element.volume=e):this._log.info("set element volume: no element"):Ie||(this._log.info(`start set pipeline volume: ${e}`),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),ve(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&&nr&&(ba=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}};var Vr=class extends H{constructor({userId:e,sdkAppId:t,mediaType:r,room:o,PlayerClass:n=r===1?Da:ft}){var a;super();d(this,"id",bo());d(this,"userId","");d(this,"isRemote");d(this,"mediaType");d(this,"room");d(this,"user");d(this,"_log");d(this,"_inputTrack");d(this,"_outputTrack");d(this,"isPlayCalled");d(this,"container",null);d(this,"player");d(this,"subVideoPlayerMap");d(this,"muted",!1);d(this,"abortCtrl");d(this,"objectFit","cover");d(this,"mirror");d(this,"rotation");d(this,"isScreen",!1);d(this,"manager");d(this,"trackSettings");d(this,"isFirstVideoFrameEmitted",!1);this.userId=e||"",this.mediaType=r,this._log=C.createLogger({id:`${this.kind[0]}t`,userId:(a=o||this.room)==null?void 0:a.userId,remoteUserId:this instanceof Fi?void 0:this.userId,sdkAppId:t,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof Fi}),this.player=new n({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log}),this.player.on(ue.PLAYER_STATE_CHANGED,c=>{E.emit(A.PLAYER_STATE_CHANGED,N({track:this},c)),this.emit("player-state-changed",c)}),this.kind===p.VIDEO&&(this.player.on(ue.LOADED_DATA,()=>{this.emitFirstVideoFrameEvent(ue.LOADED_DATA),E.emit(A.VIDEO_LOADED_DATA,{track:this})}),this.player.on(ue.LOADED_META_DATA,()=>{this.emitFirstVideoFrameEvent(ue.LOADED_META_DATA)}),this.player.on(ue.MEDIA_TRACK_CHANGED,c=>{var l;(l=this.subVideoPlayerMap)==null||l.forEach(u=>u.setTrack(c))})),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(ue.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||C}get kind(){return this.mediaType===1?p.AUDIO:p.VIDEO}get strMediaType(){return this.mediaType===4?p.VIDEO:this.mediaType===2?p.SCREEN:p.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=Se(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 ft&&(this.player.setObjectFit(this.objectFit),this.container!==r&&r&&(this.container=r,this.player.setContainer(r)),Se(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===p.VIDEO)&&this.setPlayerMute(!0),t&&!T(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof ft&&(this.player.setObjectFit(this.objectFit),t&&!T(t.poster)&&this.player.setPoster(t.poster)),this.isPlayCalled=!0,r&&(this.container=r,this.player instanceof ft&&this.player.setContainer(r)),E.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),Se(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(o){throw this.handleAutoPlayFailed(o),o}})}setMirror(e,t){if(this.isScreen||this.kind!==p.VIDEO||T(e)||e===this.mirror)return;this.mirror=e;let r=this.player;t&&(r=t);let o=this.manager;if(me(this.mirror)){r.setViewMirror(this.mirror),o&&(o.mirror=!1);return}switch(this.mirror){case"view":{o&&(o.mirror=!1),r.setViewMirror(!0);break}case"publish":{o&&(o.mirror=!0),r.setViewMirror(!0);break}case"both":o&&(o.mirror=!0),r.setViewMirror(!1)}}playSubContainer(e,t){return f(this,null,function*(){if(!this._outputTrack||this.kind===p.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((o,n)=>{var a;e.find(c=>n===c)||(o.stop(),(a=this.subVideoPlayerMap)==null||a.delete(n))});for(let[o,n]of e.entries()){let a=this.subVideoPlayerMap.get(n);a?t&&(T(t.objectFit)||a.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new ft({id:this.userId||this.id,track:this.playerMediaTrack,container:n,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:`vp-sub${o+1}`})}))}let r=[...this.subVideoPlayerMap.values()];for(let o of r)o.setViewMirror(this.player.mirror),yield o.play()})}setAudioOutput(e){return this.player.setSinkId(e)}setAudioVolume(e){this.player.setVolume(e)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var e;return((e=this.player)==null?void 0:e.getInternalAudioLevel())||0}stop(e=!1){this.isPlayCalled&&(this.isPlayCalled=!1,this.player&&(this.log.info(`stop ${this.kind} player`),this.player.stop(nd(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),E.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){qe(e,e).add(p.MUTE,this.onTrackMuted).add(p.UNMUTE,this.onTrackUnmuted).add(p.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===p.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){ve(e)}setInputMediaStreamTrack(e){var r;let t=this._inputTrack;if(e!==t)return this._inputTrack=e,this.trackSettings=(r=e.getSettings)==null?void 0:r.call(e),e.enabled=!this.muted,t&&this.uninstallTrackEvent(t),this.installTrackEvent(e),this.emit("input-media-track-changed",e||null,t||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var r;let t=this._outputTrack;e!==t&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",(r=e.getSettings)==null?void 0:r.call(e).deviceId,e.label),this._outputTrack=e,this._inputTrack&&(this._outputTrack.contentHint=this._inputTrack.contentHint,this._outputTrack.enabled=this._inputTrack.enabled),this.updatePlayingState(!!e),this.emit("output-media-track-changed",e))}setMediaType(e){this.mediaType=e}updatePlayingState(e){if(this.isPlayCalled){if(e){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped){this.player.play().catch(t=>this.handleAutoPlayFailed(t)),this.log.info(`playing state updated, play ${this.kind}`);return}}else if(!this.player.isStopped){this.player.stop(nd(this)?this.jitterBufferDelay:0),this.log.info(`playing state updated, stop ${this.kind}`);return}}this.log.debug(`updatePlayingState abort ${this.isPlayCalled} ${e} ${this.player.isStopped}`)}handleAutoPlayFailed(e){if(this.room&&this.room.enableAutoPlayDialog)new cm;else{let t=()=>{this.resume().then(()=>{document.removeEventListener("click",t,!0)})};document.addEventListener("click",t,!0)}this.emit("error",e)}getVideoFrame(){return this.player instanceof ft?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(e){var n,a,c;if(this.isFirstVideoFrameEmitted)return;let t=(n=this.mediaTrack)==null?void 0:n.getSettings(),r=(t==null?void 0:t.width)||((a=this.player.element)==null?void 0:a.videoWidth)||0,o=(t==null?void 0:t.height)||((c=this.player.element)==null?void 0:c.videoHeight)||0;e===ue.LOADED_META_DATA&&!r&&!o||(e===ue.LOADED_DATA&&!r&&!o&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,vi(this.rotation)&&([r,o]=[o,r]),this.emit("first-video-frame",{width:r,height:o,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`)}};v([Te([],H.INIT,{sync:!0})],Vr.prototype,"close",1);var z_=Object.prototype.hasOwnProperty,{toString:MR}=Object.prototype;function Q_(s){if(s==null)return!0;if(typeof s=="boolean")return!1;if(typeof s=="number")return s===0;if(typeof s=="string"||typeof s=="function"||Array.isArray(s))return s.length===0;if(s instanceof Error)return s.message==="";if(Je(s))switch(Object.prototype.toString.call(s)){case"[object File]":case"[object Map]":case"[object Set]":return s.size===0;case"[object Object]":{for(let i in s)if(z_.call(s,i))return!1;return!0}}return!1}var li=Q_;var Y_=function(s){return f(this,null,function*(){let i=K_(s);C.info(`getUserMedia with constraints: ${JSON.stringify(i)}`);let e=[],t=[],r=["label","deviceId","groupId"];i.audio&&(e=yield nt(),C.info(`microphones: ${St(e.map(o=>L(N({},o),{groupId:o.groupId.substring(0,8)})),{keysToInclude:r})}`)),i.video&&(t=yield gt(),C.info(`cameras: ${St(t,{keysToInclude:r})}`));try{let o=yield navigator.mediaDevices.getUserMedia(i);return Xd&&o.getTracks().forEach(n=>{C.info(`${n.kind} capabilities: ${St(n.getCapabilities(),{keysToInclude:kn})}`)}),i.audio&&Os(),o}catch(o){let{message:n}=o;throw o.name==="NotFoundError"&&(s.video&&t&&t.length===0&&(n=x({key:P.CAMERA_NOT_FOUND})),s.audio&&e&&e.length===0&&(n=x({key:P.MICROPHONE_NOT_FOUND}))),new y({code:I.INITIALIZE_FAILED,name:o.name,message:n,constraint:o.constraint})}})},Z_=Yt({retryFunction:Y_,settings:{retries:3,timeout:500},onError:({error:s,retry:i,reject:e,retryFuncArgs:t,retriedCount:r})=>{let o=r+1;s.name==="NotReadableError"||s.name==="OverconstrainedError"?(o===1?(t[0].video&&(t[0].maxResolution=!1,(!xe||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)):o===2?t[0].useDeviceIdOnly=!0:o===3&&!t[0].useExactDeviceId&&(t[0].useTrueAsConstraint=!0),i()):e(s),t[0].microphoneId&&Sm(t[0].microphoneId,!1),t[0].cameraId&&Sm(t[0].cameraId,!0)},onRetrying:s=>{C.warn(`getUserMedia NotReadableError observed, retrying [${s}/3]`)},onRetryFailed:s=>{re.logFailedEvent({eventType:st.GET_USER_MEDIA_RETRY,error:s})},onRetrySuccess:s=>{re.logSuccessEvent({eventType:st.GET_USER_MEDIA_RETRY}),re.uploadEvent({log:`stat-${st.GET_USER_MEDIA_RETRY}-success-${s}`})}});function Sm(s,i){return f(this,null,function*(){let t=(i?yield gt():yield nt()).find(r=>r.deviceId===s);t&&ne(t.getCapabilities)&&C.warn(St(t.getCapabilities(),{keysToInclude:kn}))})}function K_(s){return{audio:eg(s),video:tg(s)}}function eg(s){if(!s.audio)return!1;if(s.useTrueAsConstraint)return!0;let i={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:s.sampleRate};return!li(s.microphoneId)&&(i.deviceId=s.useExactDeviceId?{exact:s.microphoneId}:s.microphoneId,s.useDeviceIdOnly)?i:(q(s.channelCount)&&(i.channelCount=s.channelCount),me(s.echoCancellation)&&!s.echoCancellation&&(i.echoCancellation=!1),me(s.noiseSuppression)&&!s.noiseSuppression&&(i.noiseSuppression=!1),me(s.autoGainControl)&&!s.autoGainControl&&(i.autoGainControl=!1),li(i)?!0:i)}function tg(s){if(!s.video)return!1;if(s.useTrueAsConstraint)return!0;let{maxResolution:i=!0}=s,e={};return s.cameraId?e.deviceId=s.useExactDeviceId?{exact:s.cameraId}:s.cameraId:s.facingMode&&(e.facingMode=s.facingMode),s.useDeviceIdOnly&&!li(e)?e:(s.width&&(e.width={ideal:s.width},i&&!ae&&(e.width.max=s.width)),s.height&&(e.height={ideal:s.height},i&&!ae&&(e.height.max=s.height)),ae&&Ut&&s.width&&s.height&&s.width*s.height<352*288&&(e.width=s.width,e.height=s.height),s.frameRate&&(e.frameRate=s.frameRate),li(e)?!0:e)}var Im=Z_;function Oa(s){return Q((i,e)=>function(...t){return f(this,null,function*(){return yield s.apply(this,t),i.apply(this,t)})})}function et(s){return Q((i,e)=>function(...t){return f(this,null,function*(){let r=yield i.apply(this,t);return yield s.call(this,...t),r})})}function Ma(s){return Q((i,e)=>function(...t){return f(this,null,function*(){try{return yield i.apply(this,t)}catch(r){s.call(this,r)}})})}function Q(s){return function(i,e,t){return t.value=s(t.value,e),t}}var Am=(()=>{let s=!1,i=document.visibilityState;return()=>{document.visibilityState!==i&&C.info(`visibility change: ${document.visibilityState}`),!s&&(document.addEventListener("visibilitychange",()=>{C.info(`visibility change: ${document.visibilityState}`),i=document.visibilityState}),s=!0)}})();var ig=0,ka=class{constructor(){d(this,"log",C.createLogger({id:`fq${++ig}`}));d(this,"isRunning",!1);d(this,"queue",[])}get length(){return this.queue.length}get lastQueueItem(){return this.length===0?null:this.queue[this.length-1]}push(i,e=!1){var o,n;let t=N({},i),r=new Promise((a,c)=>{t.resolve=a,t.reject=c});return t.promise=r,e?this.length<=1?this.queue.push(t):(n=(o=this.lastQueueItem)==null?void 0:o.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:o}=this.queue[0];this.isRunning=!0,i.apply(t,e).then(r,o).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},jo=new WeakMap,Pa=new WeakMap;function Rt(s=!1){return function(i,e,t){let r=t.value;return t.value=function(...o){let n=jo.get(this)||new ka;return jo.set(this,n),n.push({fn:r,args:o,context:this},s)},t}}function Rm(s){return function(i,e,t){let r=t.value;return t.value=function(...o){let n=jo.get(this);if(n){let a=n.queue.filter((c,l)=>{if(l===0)return!0;let u=!0;return c.args.forEach(h=>{o.find(m=>m===h)||(u=!1)}),u?(c.reject(new y({code:I.API_CALL_ABORTED,message:s})),!1):!0});n.queue=a}return r.apply(this,o)},t}}function xa(s){return function(i,e,t){let r=t.value;return t.value=function(...o){var a,c,l;let n=[];return(c=(a=jo.get(this))==null?void 0:a.queue)==null||c.forEach(u=>n.push(u)),(l=Pa.get(this))==null||l.forEach(u=>u==null?void 0:u.queue.forEach(h=>n.push(h))),n.forEach(u=>{u.reject(new y({code:I.API_CALL_ABORTED,message:s}))}),jo.delete(this),Pa.delete(this),r.apply(this,o)},t}}function $i(s){return function(i,e,t){let r=t.value,o=n=>s(...n);return t.value=function(...n){let a=Pa.get(this)||new Map,c=a.get(o(n))||new ka;return a.set(o(n),c),Pa.set(this,a),c.push({fn:r,args:n,context:this})},t}}function at(s,i){return Q((e,t)=>function(...r){let o=s;try{let n=e.apply(this,r),a=w();return sr(n)?n.then(c=>(i?b.addSuccessEvent({key:o,cost:w()-a}):b.addSuccessEvent({key:o}),c)).catch(c=>{throw b.addFailedEvent({key:o,error:c}),c}):(b.addSuccessEvent({key:o}),n)}catch(n){throw b.addFailedEvent({key:o,error:n}),n}})}var Br=class Br extends Vr{constructor(e,t){super({mediaType:e,PlayerClass:t});d(this,"isRemote",!1);d(this,"deviceId");d(this,"groupId","");d(this,"label","");d(this,"sourceTrack");d(this,"_isRecapturing",!1);d(this,"_lastRecaptureTime",0);d(this,"_onMuteTimeoutId",-1);d(this,"_encodeCheckTimeoutId",-1);d(this,"profile")}get enableEncodeFrame(){return!1}get isPublishing(){return this.state.toString()==="publishing"}get isPublished(){return this.state==="publish"}encodeFrame(e,t){throw new Error("Method not implemented.")}installTrackEvent(e){qe(e,e).add(p.MUTE,this.onTrackMuted).add(p.UNMUTE,this.onTrackUnmuted).add(p.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===p.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){ve(e)}setStateToReady(){}capture(e){return f(this,null,function*(){var t;try{let r=w();E.emit(A.LOCAL_TRACK_CAPTURE_START,{track:this});let o;e.customSource?(o=new MediaStream,o.addTrack(e.customSource)):((t=this.mediaTrack)==null||t.stop(),o=yield Im(e));let n=o.getTracks()[0];return this.sourceTrack=n,yield this.setInputMediaStreamTrack(n),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),E.emit(A.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:w()-r}),o}catch(r){throw E.emit(A.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:r}),this.log.error(`getUserMedia error observed ${r}`),r}})}setOutputMediaStreamTrack(e){var t;if(super.setOutputMediaStreamTrack(e),this.setStateToReady(),this.isPublishing||this.isPublished)return(t=this.room)==null?void 0:t.replaceTrack(this)}publish(e,t){return this.room=e,this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),t}unpublish(){this.room&&this.room.localTracks.delete(this),E.emit(A.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return f(this,null,function*(){if(this.mediaTrack&&oi){let{deviceId:e,groupId:t}=this.mediaTrack.getSettings(),{label:r}=this.mediaTrack;(yield Em({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=r,t&&(this.groupId=t),ya().then(n=>{let a=n.find(c=>c.deviceId===e);a&&this.emit("2",a)}))}})}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(e=!1){return!(!this.deviceId||!this.mediaTrack||this.kind===p.AUDIO&&!Tm(this.mediaTrack)||this.kind===p.VIDEO&&!gm(this.mediaTrack)||this._isRecapturing||e&&Ut&&xe)}onTrackMuted(){if(super.onTrackMuted(),Am(),!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<ss){setTimeout(()=>this.onTrackMuted(),ss);return}this._onMuteTimeoutId=setTimeout(()=>f(this,null,function*(){var e;if((e=this.mediaTrack)!=null&&e.muted){if((Ie||pe)&&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(He(Br.prototype,this,"onTrackEnded").call(this),!!this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<ss){setTimeout(()=>this.onTrackEnded(),ss);return}this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e){return f(this,null,function*(){var r;if(this._isRecapturing||!this._inputTrack)return;this.log.warn("recapture trying"),(r=this._inputTrack)==null||r.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let t={useExactDeviceId:!0};if(e==="user"||e==="environment")t.facingMode=e;else{let o;(this.kind==="audio"?yield nt():yield gt()).find(a=>a.deviceId===e)&&(o=e),t.deviceId=o}return this.capture(t).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),E.emit(A.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(o=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${o.message}`),this.emit("5",o),E.emit(A.LOCAL_TRACK_RECAPTURE,{track:this,error:o})})})}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=(Xo.get(t)||0)+1;if(Xo.set(t,r),r>=3){let o=e?(yield gt()).find(n=>!Xo.has(n.deviceId)):(yield nt()).find(n=>!Xo.has(n.deviceId));o&&(this.log.warn(`${t} capture fail ${r} times, change new ${o.deviceId}`),t=o.deviceId)}}return t})}stopCapture(){var e;this._inputTrack&&(this._inputTrack.stop(),this.uninstallTrackEvent(this._inputTrack)),(e=this.manager)==null||e.removeInput(this)}close(){super.close(),this.stopCapture()}};v([Te(H.INIT,"ready",{ignoreError:!0,sync:!0})],Br.prototype,"setStateToReady",1),v([Rt()],Br.prototype,"capture",1),v([Te("ready","publish",{ignoreError:!0,success(){var t,r;this.room.localTracks.add(this),E.emit(A.LOCAL_TRACK_PUBLISHED,{track:this}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),!((((r=(t=this.room)==null?void 0:t.networkQuality)==null?void 0:r.uplinkNetworkQuality)||0)>3)&&(this._encodeCheckTimeoutId=setTimeout(()=>{var n,a;if(!((((a=(n=this.room)==null?void 0:n.networkQuality)==null?void 0:a.uplinkNetworkQuality)||0)>3)&&this.isPublished&&this.isMediaTrackActive){let c=this.kind===p.AUDIO,l=this.stat.bytesSent>0;b[l?"addSuccessEvent":"addFailedEvent"]({key:c?503700:513702}),l||(b.addEnum({key:c?503701:513703,value:yo()}),re.uploadEvent({log:`stat-encode-failed-${this.kind}-${Or()||Pi()}`,userId:this.userId}),this.log.warn("encode failed"),this.emit("6",this))}},5e3))},fail(e){let t="error";if(e.cause instanceof RTCError){let r=e.cause;r.message.includes("timeout")?t="timeout":r.code===I.API_CALL_ABORTED&&(t="api-call")}this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:t,error:e.cause||e})}}),at(521714,!1)],Br.prototype,"publish",1),v([Q(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)})}),Te([],"ready",{sync:!0})],Br.prototype,"unpublish",1);var Fi=Br,Xo=new Map;E.on(A.SWITCH_DEVICE_SUCCESS,s=>{s.track.deviceId&&Xo.delete(s.track.deviceId)});var Tt=class s extends Fi{constructor(e){super(1,va);d(this,"mediaType",1);d(this,"volume",0);d(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40});d(this,"playerMuted",!0);d(this,"pipeline");d(this,"earMonitorGainNode",new De);d(this,"_output",new De);d(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0});d(this,"mixedAudioReferenceMap",new Map);this.manager=e,this.pipeline=new Ms(e),this.pipeline.gain.pipeTo(this.earMonitorGainNode).pipeTo(this._output),this.pipeline.gain.pipeTo(this.player.pipeline.volumeMeter),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this)}get dbVolume(){return Ur.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}setInputMediaStreamTrack(e){return f(this,null,function*(){let t=this.trackSettings||{};b.addEnum({key:501701,value:t.channelCount||0,useUV:!1}),b.addEnum({key:501702,value:t.sampleRate||0,useUV:!1}),b.addEnum({key:502700,value:0});let{sampleRate:r,channelCount:o}=t;this._log.info(`local audio track input ${JSON.stringify({sampleRate:r,channelCount:o})}`),this.pipeline.source.channelCount=o||1,this.pipeline.replaceSource(e),yield He(s.prototype,this,"setInputMediaStreamTrack").call(this,e),this.updatePlayingState(!!e)})}capture({deviceId:e,customSource:t,useExactDeviceId:r=!0,retryWhenExactFailed:o=!0}){return super.capture({video:!1,audio:!0,microphoneId:e,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:r,retryWhenExactFailed:o,customSource:t})}switchDevice(e){return f(this,null,function*(){if(this.mediaTrack){if(this.deviceId===e)if(e===Ar){if(yield ul(this.groupId,this.label))return}else return;try{this.log.info(`switchDevice audio to: ${e}`),this.mediaTrack&&this.mediaTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0,retryWhenExactFailed:!1}),E.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(){Le&&!Le.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&Le.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return f(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current microphone is lost: ${JSON.stringify(e)}`),Ae(this.userId,{eventId:2003,param1:6,streamType:1});let t=yield nt();t[0]?this.recapture(t[0].deviceId):Le.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.log.warn(`microphone added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)}update3A(o){return f(this,arguments,function*({echoCancellation:e,noiseSuppression:t,autoGainControl:r}){let n=this.sourceTrack||this.mediaTrack;if(!n)return;let a=n.getConstraints(),c=!1;!T(e)&&e!==this.profile.echoCancellation&&(this.profile.echoCancellation=e,a.echoCancellation=e,c=!0),!T(t)&&t!==this.profile.noiseSuppression&&(this.profile.noiseSuppression=t,a.noiseSuppression=t,c=!0),!T(r)&&r!==this.profile.autoGainControl&&(this.profile.autoGainControl=r,a.autoGainControl=r,c=!0),c&&(ae||xe?yield n.applyConstraints(a).catch(l=>this._log.warn("update3A failed: ",l)):this.deviceId&&(yield this.recapture(this.deviceId)))})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&b.addEnum({key:502700,value:2})}setAudioVolume(e){super.setAudioVolume(0),Ie&&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&&!(xe||Ie))return this.update3A({echoCancellation:e})}addDenoiser(e){var t;if(lt<=92&&((t=this.trackSettings)==null?void 0:t.sampleRate)!==48e3){this._log.warn("denoiser only support sampleRate 48000 before chrome 93");return}b.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=Jo(e),o=new De,n=Ee().createGain();n.gain.value=1;let a=new De;o.pipeTo(a).pipeTo(this.pipeline.mixNode),o.setNode(r),a.setNode(n),this.mixedAudioReferenceMap.set(t,[o,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,o]=this.mixedAudioReferenceMap.get(e)||[];o!=null&&o.node&&(o.node.gain.value=t/100,this.log.info(`setAudioReferenceVolume() => ${e} ${o.node.gain.value}`))}addAudioProcessor(e,t,r,o){this.pipeline.silentNode.setNode(r),this.pipeline.mixNode.setNode(t),this.pipeline.aec.setNode(e),this.enableTrackAEC(!1)}removeDenoiser(e){this.pipeline.denoiser.node===e&&(this.pipeline.denoiser.deleteNode(),this.enableTrackANS(!0))}removeAudioProcessor(e,t,r,o){this.pipeline.aec.node===e&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode(),this.enableTrackAEC(!0))}close(){this.mixedAudioReferenceMap.forEach(([e,t])=>{e.deleteNode(),t.deleteNode()}),this.mixedAudioReferenceMap.clear(),this.pipeline.remove(),this.earMonitorGainNode.deleteNode(),this._output.deleteNode(),Le.off("audioInputAdded",this.handleMicrophoneAdded,this),Le.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}recapture(e){return f(this,null,function*(){try{yield He(s.prototype,this,"recapture").call(this,e)}catch(t){let r=(yield nt()).find(o=>o.deviceId!==e);if(r)yield He(s.prototype,this,"recapture").call(this,r.deviceId);else throw t}})}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduceRight((t,r)=>r?r({frame:t}):t,e):e}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}};var Hi=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 o=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=o}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 o=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=o}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 o=6;o<this.dataView.buffer.byteLength;o++){let n=this.dataView.getUint8(o);if(e++,n===255)i+=255;else{i+=n;break}}let t=new ArrayBuffer(i),r=new DataView(t);for(let o=0;o<t.byteLength;o++,e++)r.setInt8(o,this.dataView.getInt8(e));return r}};var La=class{constructor(){d(this,"_seiMessageList",[]);d(this,"_smallSeiMessageList",[]);d(this,"_seiPayloadType",243)}encodeSEINalu(i){let e=i.byteLength,t=parseInt(String(e/255),10),r=e%255,o=[];o.push(0,0,0,1,6,this._seiPayloadType);for(let a=0;a<t;a++)o.push(255);o.push(r);let n=new DataView(i);return o.push(...new Uint8Array(n.buffer)),o.push(128),new Hi(new DataView(new Uint8Array(o).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 o=0;o<i.byteLength;o++)switch(r.getUint8(o)){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 o=9-this.getNaluCount(i.data);if(o<=0)return 0;let n=t.splice(0,o).reverse().map(this.encodeSEINalu.bind(this)),a=n.reduce((m,g)=>m+g.dataView.byteLength,0),c=new ArrayBuffer(a+i.data.byteLength),l=new DataView(c),u=new DataView(i.data),h=0;for(let m=0;m<n.length;m++)for(let g=0;g<n[m].dataView.byteLength;g++)l.setInt8(h++,n[m].dataView.getInt8(g));for(let m=0;m<i.data.byteLength;m++)l.setInt8(h++,u.getInt8(m));return i.data=c,n.length}return 0}};var Fr=class Fr extends Fi{constructor(e,t=4){super(t,ft);d(this,"profile",N({},er));d(this,"avoidCropping",!1);d(this,"_scaleResolutionDownBy");d(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0});d(this,"small");d(this,"isNeedToSetBandwidth");d(this,"muteImage");d(this,"manager");d(this,"_seiCodec",new La);this.manager=e;let r=()=>{this.isAllowed2k4k(this.profile)?this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1}):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),this.setProfile(L(N({},this.profile),{width:1920,height:1080})),this.applyProfile())};this.on("input-media-track-changed",r),this.on("publish",r),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(!(!oi||!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"}setMute(e){return f(this,null,function*(){var t,r,o;if(ee(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}),this.muteImage=e,He(Fr.prototype,this,"setMute").call(this,!1)}else this.muteImage&&(yield(o=this.manager)==null?void 0:o.deleteWatermark("mute"),this.muteImage=void 0),He(Fr.prototype,this,"setMute").call(this,e)})}capture({deviceId:e,facingMode:t,useExactDeviceId:r=!0,customSource:o,retryWhenExactFailed:n=!0}){return super.capture({audio:!1,video:!0,facingMode:t||this.facingMode,cameraId:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:r,retryWhenExactFailed:n,customSource:o})}setProfile(e){let t=this.fallbackProfile(e);t.bitrate&&(this.isNeedToSetBandwidth=t.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile)?super.setProfile(t):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),super.setProfile(L(N({},this.profile),{width:1920,height:1080})))}applyProfile(){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,o=this.settings,n=o.height!==this.profile.height||o.width!==this.profile.width||o.frameRate!==this.profile.frameRate;if(n&&(ut===16&&this.deviceId?yield this.recapture(this.deviceId):(yield(a=this.sourceTrack||this.mediaTrack)==null?void 0:a.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}),this.manager&&this.manager.changeInput(this)),this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1})),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth){this.isNeedToSetBandwidth=!1;let{width:c=0,height:l=0}=(this.sourceTrack||this.mediaTrack).getSettings(),u=c*l;if(n&&u&&r&&u===r){this.log.warn("set bandwidth failed: resolution is not changed");return}return this.room.setBandWidth({bandwidth:this.profile.bitrate,type:p.VIDEO,videoType:p.BIG})}})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},t=this.sourceTrack||this.mediaTrack;return oi&&t&&Object.assign(e,t.getSettings()),e}get scaleResolutionDownBy(){return this._scaleResolutionDownBy?this._scaleResolutionDownBy:ls(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))return;let t={useExactDeviceId:!0,retryWhenExactFailed:!1};e==="user"||e==="environment"?t.facingMode=e:t.deviceId=e,this.mediaTrack.stop(),yield this.capture(t),E.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}})}updateSmallConfig(e){var r,o;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&&((o=this.room)==null||o.enableSmall(!0)),this.log.info("update small stream config success")}fallbackProfile(e,t=!1){let r=e.width>e.height,o=N({},e);return e.width*e.height<=160*120&&pe&&Ze&&(this.log.warn(`${t?"small ":""}resolution is ${e.width}*${e.height}, fallback to 240*180 for android chrome`),o.width=r?240:180,o.height=r?180:240,o.bitrate=Math.max(e.bitrate,150)),e.width*e.height>1280*720&&Sd&&(o.width=r?1280:720,o.height=r?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),!t&&this.avoidCropping&&(Ze||ae)&&!Ad()&&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}`)),o}stopSmall(){var e,t;this.small&&(delete this.small,(e=this.manager)==null||e.update(),(t=this.room)==null||t.enableSmall(!1))}listenDeviceChange(){Le&&!Le.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&Le.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return f(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current camera is lost: ${JSON.stringify(e)}`),Ae(this.userId,{eventId:2003,param1:7,streamType:2});let t=yield gt();t[0]?this.recapture(t[0].deviceId):Le.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return f(this,null,function*(){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((o,n)=>n?n({frame:o,mediaType:r}):o,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(){Le.off("videoInputAdded",this.handleCameraAdded,this),Le.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return f(this,null,function*(){try{yield He(Fr.prototype,this,"recapture").call(this,e)}catch(t){let r=(yield gt()).find(o=>o.deviceId!==e);if(r)yield He(Fr.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))}};v([et(function(e){this.setContentHint(e.contentHint||"motion")})],Fr.prototype,"capture",1);var je=Fr;var wa=bo();if(typeof navigator!="undefined"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:wa,exposeOrigin:!0,permittedOrigins:["*"]})}catch(s){}var ng=function(s){return f(this,null,function*(){let i=null,e=dg(s);C.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let t=yield navigator.mediaDevices.getDisplayMedia(e);s.systemAudio&&t.getAudioTracks().length===0&&(Is&&lt<74||xe||ae)&&C.warn("Your browser not support capture system audio");let r=t.getVideoTracks()[0];if(r){if(s.frameRate)try{yield r.applyConstraints({frameRate:{min:s.frameRate,ideal:s.frameRate},width:s.width,height:s.height})}catch(o){C.warn(`screen applyConstraints failed: ${o}`)}s.captureElement&&(yield ag(r,s.captureElement))}if(s.audio){let o=cg(s);C.info(`getUserMedia with constraints: ${JSON.stringify(o)}`),i=yield navigator.mediaDevices.getUserMedia(o),t.addTrack(i.getAudioTracks()[0])}return t})};function ag(s,i){return f(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&ne(s.cropTo))try{if(!(((e=s.getCaptureHandle())==null?void 0:e.handle)===wa))return;let r=yield CropTarget.fromElement(i);yield s.cropTo(r)}catch(t){C.warn(`cropTo target failed ${t}`)}})}function cg(s){let i={echoCancellation:s.echoCancellation,autoGainControl:s.autoGainControl,noiseSuppression:s.noiseSuppression,sampleRate:s.sampleRate,channelCount:s.channelCount};return T(s.microphoneId)||(i.deviceId=s.microphoneId),{audio:i,video:!1}}function dg(s){let i={preferCurrentTab:s.preferDisplaySurface==="current-tab"||!!s.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:xe?{max:s.width}:{ideal:s.width,max:s.width},height:xe?{max:s.height}:{ideal:s.height,max:s.height},frameRate:s.frameRate,displaySurface:s.preferDisplaySurface||"monitor"};if(i.video=e,s.systemAudio){let{echoCancellation:t=!0,noiseSuppression:r=!1,autoGainControl:o=!1}=s;i.audio={echoCancellation:t,noiseSuppression:r,autoGainControl:o,sampleRate:48e3}}return i}var ym=ng;var ct=class extends je{constructor(e){super(e,2);d(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600});d(this,"objectFit","contain");d(this,"isScreen",!0);this._log.id=`s-${this._log.id}`}get isShareCurrentTab(){var e,t;try{return wa===((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:o,audioTrack:n,videoTrack:a,captureElement:c,preferDisplaySurface:l}){try{let h;return a||n?(h=new MediaStream,a&&h.addTrack(a),n&&h.addTrack(n)):h=yield ym({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:t,echoCancellation:r,noiseSuppression:o,captureElement:c,preferDisplaySurface:l}),yield this.setInputMediaStreamTrack(h.getVideoTracks()[0]),h}catch(h){throw this.log.error(`getDisplayMedia error observed ${h}`),h instanceof y?h:new y({code:I.INITIALIZE_FAILED,name:h.name,message:h.message})}})}switchDevice(e){return f(this,null,function*(){throw new Error("Method not implemented.")})}};v([et(function(e){this.setContentHint(e.contentHint||"detail")})],ct.prototype,"capture",1);var hi=class extends Tt{constructor(i){super(i),this._log.id=`s-${this._log.id}`}addAudioProcessor(i,e,t,r){this.pipeline.silentNode.setNode(t),this.pipeline.mixNode.setNode(e),this.pipeline.aec.setNode(r),this.enableTrackAEC(!1)}removeAudioProcessor(i,e,t,r){this.pipeline.aec.node===r&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode(),this.enableTrackAEC(!0))}};var lg='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}});',ml;function zo(s,i=48e3,e=1,t){return f(this,null,function*(){let r=Ee("dump");ml||(ml=Bi(r,URL.createObjectURL(new Blob([lg],{type:"application/javascript"})))),yield ml;let o=r.sampleRate,n=new AudioWorkletNode(r,"dumper",{numberOfInputs:s.length,numberOfOutputs:0,processorOptions:{sourceSampleRate:o,targetSampleRate:i}});return n.channelCountMode="explicit",n.channelCount=e,t&&n.port.postMessage({port:t},[t]),s.forEach((a,c)=>a.connect(n,0,c)),new ReadableStream({start(a){n.port.onmessage=c=>{a.enqueue(c.data)}},cancel(){s.forEach(a=>a.disconnect(n)),n.port.close()}})})}var Ua=class extends Aa{constructor(e){super();this.room=e;d(this,"_localAudioTrack");d(this,"_localScreenAudioTrack");d(this,"log",C.createLogger({id:"am"}));d(this,"denoiser");d(this,"voiceChanger");d(this,"mixChangedDebounce");d(this,"audioProcessor");d(this,"encodePipeline",[]);d(this,"decodePipeline",[]);d(this,"getPCMAbortCtrlMap",new Map);d(this,"audioFrameEventConfigMap",new Map);d(this,"audioReferenceMap",new Map);d(this,"isLocalAudioNeedAudioProcess",!1);d(this,"isScreenAudioNeedAudioProcess",!1);e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.installEvent()}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 o=new AbortController,n=[],a=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),o.abort("timeout")},e*1e3),c=()=>{for(let m=0;m<r.length;m++){let g=URL.createObjectURL(new Blob(n[m])),D=document.createElement("a");D.href=g,D.download=`${r[m]}.pcm`,D.style.display="none",document.body.appendChild(D),D.click(),URL.revokeObjectURL(g),D.remove()}clearTimeout(a),o.abort("download")},l=zo(t).then(m=>m.pipeTo(new WritableStream({write(g){g.forEach((D,_)=>n[_]=n[_]?n[_].concat(D[0]):[D[0]])}}),o).catch(g=>c));return{then:l.then.bind(l),download:c}}getPCM(e,t){var O,K,G;if(T(WritableStream)){this.log.warn("getPCM failed: browser not support WritableStream");return}let{enable:r,sampleRate:o=48e3,channelCount:n=1,port:a}=(t===""?this.audioFrameEventConfigMap.get(""):this.audioFrameEventConfigMap.get(t)||this.audioFrameEventConfigMap.get("*"))||{};if(!r)return;this.log.info(`getPCM ${t||"local"}`);let c=Math.floor(o*.04),l=new Float32Array(c),u=new Float32Array(c),h,m,g=0,D=new AbortController,_=t===""?(O=this._localAudioTrack)==null?void 0:O.mediaTrack:(G=(K=this.room)==null?void 0:K.remotePublishedUserMap.get(t))==null?void 0:G.remoteAudioTrack.mediaTrack;if(!_){this.log.info(`getPCM failed: ${t||"local"} has no audio track`);return}let S=Ee().createMediaStreamSource(new MediaStream([_]));return zo([S],o,n,a).then(Z=>Z.pipeTo(new WritableStream({write(_e){_e[0][0]&&(g+_e[0][0].length>c?(l.set(_e[0][0].subarray(0,c-g),g),h=_e[0][0].subarray(c-g),_e[0][1]&&(u.set(_e[0][1].subarray(0,c-g),g),m=_e[0][1].subarray(c-g)),g+=c-g):(h&&(l.set(h,g),g+=h.length,h=void 0),m&&(u.set(m,g),m=void 0),l.set(_e[0][0],g),_e[0][1]&&u.set(_e[0][1],g),g+=_e[0][0].length),g>=c&&(g=0,e({userId:t,sampleRate:o,channelCount:n,data:n===1?l:[l,u]}),l=new Float32Array(c),u=new Float32Array(c)))}}),D).catch(_e=>this.log.warn(`stop getPCM reason:${_e}`))),D}get hasScreenAudioTrack(){return!T(this._localScreenAudioTrack)}get hasAudioTrack(){return!T(this._localAudioTrack)}changeInput(e){if(e instanceof hi)return this._localScreenAudioTrack=e,this.isScreenAudioNeedAudioProcess&&this.audioProcessor&&(e.addAudioProcessor(...this.audioProcessor),this.audioReferenceMap.forEach((t,r)=>{e.mixAudioReference(t,r)})),e.pipeline.connect(),this.mixOnChange();if(e instanceof Tt)return this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),this.isLocalAudioNeedAudioProcess&&this.audioProcessor&&(e.addAudioProcessor(...this.audioProcessor),this.audioReferenceMap.forEach((t,r)=>{e.mixAudioReference(t,r)})),e.pipeline.connect(),this.mixOnChange();if(e instanceof Gt)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 hi?delete this._localScreenAudioTrack:e instanceof Tt?delete this._localAudioTrack:e instanceof Gt}addDenoiser(e){var t;this.denoiser=e,(t=this._localAudioTrack)==null||t.addDenoiser(e)}addAudioProcessor(e,t,r,o){var n;this.audioProcessor=[e,t,r,o],this.isLocalAudioNeedAudioProcess&&this._localAudioTrack&&(this._localAudioTrack.addAudioProcessor(...this.audioProcessor),this.audioReferenceMap.forEach((a,c)=>{var l;(l=this._localAudioTrack)==null||l.mixAudioReference(a,c)})),this.isScreenAudioNeedAudioProcess&&this._localScreenAudioTrack&&((n=this._localScreenAudioTrack)==null||n.addAudioProcessor(...this.audioProcessor),this.audioReferenceMap.forEach((a,c)=>{var l;(l=this._localScreenAudioTrack)==null||l.mixAudioReference(a,c)}))}removeDenoiser(e){var t;delete this.denoiser,(t=this._localAudioTrack)==null||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,r,o){var n;delete this.audioProcessor,(n=this._localAudioTrack)==null||n.removeAudioProcessor(e,t,r,o)}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 o;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)&&((o=this._localAudioTrack)==null||o.on("input-media-track-changed",()=>{let n=this.getPCMAbortCtrlMap.get(t);n&&(n.abort("inputMediaTrackChanged"),n=this.getPCM(a=>{var c;(c=this.room)==null||c.emit("audio-frame",a)},""),this.getPCMAbortCtrlMap.set(t,n))}))}handleLocalTrackStopped({room:e,userId:t}){if(e!==this.room)return;let r=this.getPCMAbortCtrlMap.get(t);r&&(r.abort("stopLocalAudio"),this.getPCMAbortCtrlMap.delete(t))}handleRemoteTrackStarted({room:e,userId:t}){if(e===this.room&&!this.getPCMAbortCtrlMap.get(t)){let r=this.room.audioManager.getPCM(o=>{var n;(n=this.room)==null||n.emit("audio-frame",o)},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(){E.on("113",this.handleLocalTrackStarted,this),E.on("114",this.handleLocalTrackStopped,this),E.on("115",this.handleRemoteTrackStarted,this),E.on("116",this.handleRemoteTrackStopped,this)}uninstallEvent(){E.off("113",this.handleLocalTrackStarted),E.off("114",this.handleLocalTrackStopped),E.off("115",this.handleRemoteTrackStarted),E.off("116",this.handleRemoteTrackStopped)}updateAudioReference({type:e,audioReference:t,refId:r,volume:o}){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(o))return;this.setAudioReferenceVolume(r,o)}}};function Va(s=30,i=2){return Q((e,t)=>function(...r){return new Promise((o,n)=>{let a=setTimeout(()=>{let c=new y({code:I.API_CALL_TIMEOUT,message:`checkPendingPromise ${t}() timeout ${s}s`});C.warn(c),i===2?n(c):i===1&&o()},s*1e3);e.apply(this,r).then(o,n).finally(()=>{clearTimeout(a)})})})}var Zl={};Si(Zl,{Events:()=>Ce,Inspect:()=>Ct,LastSink:()=>$r,Sink:()=>W,Subscribe:()=>Hr,TimeoutError:()=>Qo,audit:()=>Jg,bindCallback:()=>Og,bindNodeCallback:()=>Mg,buffer:()=>Eg,bufferCount:()=>Tg,bufferTime:()=>lT,call:()=>bm,catchError:()=>Xl,combineLatest:()=>vm,concat:()=>mg,concatMap:()=>iT,concatMapTo:()=>rT,count:()=>xg,create:()=>ie,debounce:()=>qg,debounceTime:()=>jg,defer:()=>Dm,delay:()=>uT,deliver:()=>j,dispose:()=>Ba,elementAt:()=>Xg,empty:()=>Ko,every:()=>Kg,exhaustMap:()=>nT,exhaustMapTo:()=>aT,filter:()=>mi,find:()=>zg,findIndex:()=>Qg,first:()=>Yg,fromAnimationFrame:()=>vg,fromArray:()=>Ag,fromEvent:()=>he,fromEventPattern:()=>Rg,fromFetch:()=>Cg,fromIterable:()=>yg,fromPromise:()=>km,fromReadableStream:()=>Ng,fromReader:()=>bg,groupBy:()=>cT,identity:()=>ug,ignoreElements:()=>Vg,iif:()=>fg,inspect:()=>Nm,interval:()=>Sl,last:()=>Zg,map:()=>en,mapTo:()=>tT,max:()=>Lg,merge:()=>Tl,mergeMap:()=>sT,mergeMapTo:()=>oT,min:()=>wg,never:()=>kg,nothing:()=>de,of:()=>Ig,pairwise:()=>eT,pipe:()=>le,race:()=>El,range:()=>Dg,reduce:()=>Il,retry:()=>fT,scan:()=>jl,share:()=>Gi,shareReplay:()=>pg,skip:()=>Fg,skipUntil:()=>$g,skipWhile:()=>Wa,startWith:()=>Yo,subject:()=>tt,subscribe:()=>be,sum:()=>Ug,switchMap:()=>Ls,switchMapTo:()=>Wr,take:()=>Wi,takeLast:()=>Bg,takeUntil:()=>Be,takeWhile:()=>Pm,tap:()=>Yl,throttle:()=>Gg,throwError:()=>Pg,timeInterval:()=>dT,timeout:()=>pT,timer:()=>Zo,toPromise:()=>hT,toReadableStream:()=>mT,withLatestFrom:()=>gg,zip:()=>_g});function de(...s){}var bm=s=>s(),ug=s=>s;function Ba(){this.dispose()}var Nm=()=>typeof __FASTRX_DEVTOOLS__!="undefined",hg=1,Ct=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(i){let e=new pl(i,this,this.streamId++);return Ce.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},$r=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=de,this.error=de,this.next=de,this.dispose=de,this.subscribe=de,this.doDefer()}subscribe(i){return i instanceof Ct?i.subscribe(this):i(this),this}get bindSubscribe(){return i=>this.subscribe(i)}doDefer(){this.defers.forEach(bm),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}},W=class extends $r{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)}},Hr=class extends $r{constructor(i,e=de,t=de,r=de){if(super(),this._next=e,this._error=t,this._complete=r,this.then=de,i instanceof Ct){let o={toString:()=>"subscribe",id:0,source:i};this.defer(()=>{Ce.defer(o,0)}),Ce.create(o),Ce.pipe(o),this.sourceId=o.id,this.subscribe(i),Ce.subscribe({id:o.id,end:!0}),e==de?this._next=n=>Ce.next(o,0,n):this.next=n=>{Ce.next(o,0,n),e(n)},r==de?this._complete=()=>Ce.complete(o,0):this.complete=()=>{this.dispose(),Ce.complete(o,0),r()},t==de?this._error=n=>Ce.complete(o,0,n):this.error=n=>{this.dispose(),Ce.complete(o,0,n),t()}}else this.subscribe(i)}next(i){this._next(i)}complete(){this.dispose(),this._complete()}error(i){this.dispose(),this._error(i)}};function le(s,...i){return i.reduce((e,t)=>t(e),s)}function ie(s,i,e){if(Nm()){let t=Object.defineProperties(Object.setPrototypeOf(s,Ct.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}});Ce.create(t);for(let r=0;r<e.length;r++){let o=e[r];typeof o=="function"&&o instanceof Ct&&Ce.addSource(t,o)}return t}return s}function j(s,i){return function(...e){return t=>{if(t instanceof Ct){let r=ie(o=>{let n=new s(o,...e);n.sourceId=r.id,n.subscribe(t)},i,arguments);return r.source=t,Ce.pipe(r),r}else return r=>t(new s(r,...e))}}}function ur(s,i){window.postMessage({source:"fastrx-devtools-backend",payload:{event:s,payload:i}})}var pl=class extends W{constructor(i,e,t){super(i),this.source=e,this.id=t,this.sourceId=i.sourceId,this.defer(()=>{Ce.defer(this.source,this.id)})}next(i){Ce.next(this.source,this.id,i),this.sink.next(i)}complete(){Ce.complete(this.source,this.id),this.sink.complete()}error(i){Ce.complete(this.source,this.id,i),this.sink.error(i)}},Ce={addSource(s,i){ur("addSource",{id:s.id,name:s.toString(),source:{id:i.id,name:i.toString()}})},next(s,i,e){ur("next",{id:s.id,streamId:i,data:e&&e.toString()})},subscribe({id:s,end:i},e){ur("subscribe",{id:s,end:i,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(s,i,e){ur("complete",{id:s.id,streamId:i,err:e?e.toString():null})},defer(s,i){ur("defer",{id:s.id,streamId:i})},pipe(s){ur("pipe",{name:s.toString(),id:s.id,source:{id:s.source.id,name:s.source.toString()}})},update(s){ur("update",{id:s.id,name:s.toString()})},create(s){s.id||(s.id=hg++),ur("create",{name:s.toString(),id:s.id})}},Qo=class extends Error{constructor(i){super(`timeout after ${i}ms`),this.timeout=i}};var Fa=class extends $r{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 Gi(){return s=>{let i=new Fa(s);if(s instanceof Ct){let e=ie(t=>{i.add(t)},"share",arguments);return i.sourceId=e.id,e.source=s,Ce.pipe(e),e}return ie(i.add.bind(i),"share",arguments)}}function Tl(...s){return ie(i=>{let e=new W(i),t=s.length;e.complete=()=>{--t===0&&i.complete()},s.forEach(e.bindSubscribe)},"merge",arguments)}function El(...s){return ie(i=>{let e=new Map;s.forEach(t=>{let r=new W(i);e.set(t,r),r.complete=()=>{e.delete(t),e.size===0?i.complete():r.dispose()},r.next=o=>{e.delete(t),e.forEach(n=>n.dispose()),r.resetNext(),r.resetComplete(),r.next(o)}}),s.forEach(t=>e.get(t).subscribe(t))},"race",arguments)}function mg(...s){return ie(i=>{let e=0,t=s.length,r=new W(i);r.complete=()=>{e<t&&!r.disposed?(r.doDefer(),r.subscribe(s[e++])):i.complete()},r.complete()},"concat",arguments)}function pg(s){return i=>{let e=new Fa(i),t=[];return e.next=function(r){t.push(r),t.length>s&&t.shift(),this.sinks.forEach(o=>o.next(r))},ie(r=>{r.defer(()=>e.remove(r)),t.forEach(o=>r.next(o)),e.add(r)},"shareReplay",arguments)}}function fg(s,i,e){return ie(t=>s()?i(t):e(t),"iif",arguments)}function vm(...s){return ie(i=>{let e=s.length,t=e,r=e,o=new Array(e),n=()=>{--r===0&&i.complete()},a=(c,l)=>{let u=new W(i);u.next=h=>{--t===0?(u.next=m=>{o[l]=m,i.next(o)},u.next(h)):o[l]=h},u.complete=n,u.subscribe(c)};s.forEach(a)},"combineLatest",arguments)}function _g(...s){return ie(i=>{let e=s.length,t=e,r=new Array(e),o=()=>{--t===0&&i.complete()},n=(a,c)=>{let l=new W(i),u=[];r[c]=u,l.next=h=>{u.push(h),r.every(m=>m.length)&&i.next(r.map(m=>m.shift()))},l.complete=o,l.subscribe(a)};s.forEach(n)},"zip",arguments)}function Yo(...s){return i=>ie((e,t=0,r=s.length)=>{for(;t<r&&!e.disposed;)e.next(s[t++]);e.disposed||e.subscribe(i)},"startWith",arguments)}var fl=class extends W{constructor(i,...e){super(i);let t=new W(this.sink);t.next=r=>this.buffer=r,t.complete=de,t.subscribe(vm(...e))}next(i){this.buffer&&this.sink.next([i,...this.buffer])}},gg=j(fl,"withLatestFrom"),_l=class extends W{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()}},Tg=j(_l,"bufferCount"),gl=class extends W{constructor(i,e){super(i),this.buffer=[];let t=new W(i);t.next=r=>{i.next(this.buffer),this.buffer=[]},t.complete=de,t.subscribe(e)}next(i){this.buffer.push(i)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},Eg=j(gl,"buffer");var Sg=function(s,i,e,t){function r(o){return o instanceof e?o:new e(function(n){n(o)})}return new(e||(e=Promise))(function(o,n){function a(u){try{l(t.next(u))}catch(h){n(h)}}function c(u){try{l(t.throw(u))}catch(h){n(h)}}function l(u){u.done?o(u.value):r(u.value).then(a,c)}l((t=t.apply(s,i||[])).next())})};function tt(s){let i=arguments,e=Gi()(ie(t=>{e.next=r=>t.next(r),e.complete=()=>t.complete(),e.error=r=>t.error(r),s&&t.subscribe(s)},"subject",i));return e.next=de,e.complete=de,e.error=de,e}function Dm(s){return ie(i=>i.subscribe(s()),"defer",arguments)}var Om=s=>i=>{setTimeout(()=>s(i))},Mm=s=>Om(i=>{for(let e=0;!i.disposed&&e<s.length;e++)i.next(s[e]);i.complete()});function Ig(...s){return ie(Mm(s),"of",arguments)}function Ag(s){return ie(Mm(s),"fromArray",arguments)}function Sl(s){return ie(i=>{let e=0,t=setInterval(()=>i.next(e++),s);return i.defer(()=>{clearInterval(t)}),"interval"},"interval",arguments)}function Zo(s,i){return ie(e=>{let t=0,r=setTimeout(()=>{if(e.removeDefer(o),e.next(t++),i){let n=setInterval(()=>e.next(t++),i);e.defer(()=>{clearInterval(n)})}else e.complete()},s),o=()=>{clearTimeout(r)};e.defer(o)},"timer",arguments)}function $a(s,i){return e=>{let t=r=>e.next(r);e.defer(()=>i(t)),s(t)}}function Rg(s,i){return ie($a(s,i),"fromEventPattern",arguments)}function he(s,i){if("on"in s&&"off"in s)return ie($a(e=>s.on(i,e),e=>s.off(i,e)),"fromEvent",arguments);if("addListener"in s&&"removeListener"in s)return ie($a(e=>s.addListener(i,e),e=>s.removeListener(i,e)),"fromEvent",arguments);if("addEventListener"in s)return ie($a(e=>s.addEventListener(i,e),e=>s.removeEventListener(i,e)),"fromEvent",arguments);throw"target is not a EventDispachter"}function km(s){return ie(i=>{s.then(i.next.bind(i),i.error.bind(i))},"fromPromise",arguments)}function Cg(s,i){return ie(Dm(()=>km(fetch(s,i))),"fromFetch",arguments)}function yg(s){return ie(Om(i=>{try{for(let e of s){if(i.disposed)return;i.next(e)}i.complete()}catch(e){i.error(e)}}),"fromIterable",arguments)}function bg(s){let i=e=>Sg(this,void 0,void 0,function*(){if(e.disposed)return;let{done:t,value:r}=yield s.read();if(t){e.complete();return}else e.next(r),i(e)});return ie(e=>{i(e)},"fromReader",arguments)}function Ng(s){return ie(i=>{let e=new AbortController,t=e.signal;i.defer(()=>e.abort("cancelled")),s.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 vg(){return ie(s=>{let i=requestAnimationFrame(function e(t){s.disposed||(s.next(t),i=requestAnimationFrame(e))});s.defer(()=>cancelAnimationFrame(i))},"fromAnimationFrame",arguments)}function Dg(s,i){return ie((e,t=s,r=i+s)=>{for(;t<r&&!e.disposed;)e.next(t++);return e.complete(),"range"},"range",arguments)}function Og(s,i,...e){return ie(t=>{let r=e.concat(o=>(t.next(o),t.complete()));s.apply(i,r)},"bindCallback",arguments)}function Mg(s,i,...e){return ie(t=>{let r=e.concat((o,n)=>o?t.error(o):(t.next(n),t.complete()));s.apply(i,r)},"bindNodeCallback",arguments)}function kg(){return ie(()=>{},"never",arguments)}function Pg(s){return ie(i=>i.error(s),"throwError",arguments)}function Ko(){return ie(s=>s.complete(),"empty",arguments)}var Gr=class extends W{constructor(i,e,t){super(i),this.f=e;let r=()=>{this.sink.next(this.acc),this.sink.complete()};typeof t=="undefined"?this.next=o=>{this.acc=o,this.complete=r,this.resetNext()}:(this.acc=t,this.complete=r)}next(i){this.acc=this.f(this.acc,i)}},Il=j(Gr,"reduce"),xg=s=>j(Gr,"count")((i,e)=>s(e)?i+1:i,0),Lg=()=>j(Gr,"max")(Math.max),wg=()=>j(Gr,"min")(Math.min),Ug=()=>j(Gr,"sum")((s,i)=>s+i,0);var Al=class extends W{constructor(i,e,t){super(i),this.filter=e,this.thisArg=t}next(i){this.filter.call(this.thisArg,i)&&this.sink.next(i)}},mi=j(Al,"filter"),Rl=class extends W{next(i){}},Vg=j(Rl,"ignoreElements"),Cl=class extends W{constructor(i,e){super(i),this.count=e}next(i){this.sink.next(i),--this.count===0&&this.complete()}},Wi=j(Cl,"take"),yl=class extends W{constructor(i,e){super(i);let t=new W(i);t.next=()=>i.complete(),t.complete=Ba,t.subscribe(e)}},Be=j(yl,"takeUntil"),bl=class extends W{constructor(i,e){super(i),this.f=e}next(i){this.f(i)?this.sink.next(i):this.complete()}},Pm=j(bl,"takeWhile"),Bg=s=>Il((i,e)=>(i.push(e),i.length>s&&i.shift(),i),[]),Nl=class extends W{constructor(i,e){super(i),this.count=e}next(i){--this.count===0&&(this.next=super.next)}},Fg=j(Nl,"skip"),vl=class extends W{constructor(i,e){super(i),i.next=de;let t=new W(i);t.next=()=>{t.dispose(),i.resetNext()},t.complete=Ba,t.subscribe(e)}},$g=j(vl,"skipUntil"),Dl=class extends W{constructor(i,e){super(i),this.f=e}next(i){this.f(i)||(this.next=super.next,this.next(i))}},Wa=j(Dl,"skipWhile"),Hg={leading:!0,trailing:!1},Ol=class extends W{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)}},Ha=class extends W{constructor(i,e,t=Hg){super(i),this.durationSelector=e,this.config=t,this._throttle=new Ol(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=de,this._throttle.complete(),super.complete()}},Gg=j(Ha,"throttle"),Wg={leading:!1,trailing:!0},Jg=s=>j(Ha,"audit")(s,Wg),Ml=class extends W{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},Ga=class extends W{constructor(i,e){super(i),this.durationSelector=e,this._debounce=new Ml(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()}},qg=j(Ga,"debounce"),jg=s=>j(Ga,"debounceTime")(i=>Zo(s)),kl=class extends W{constructor(i,e,t){super(i),this.count=e,this.defaultValue=t}next(i){this.count--===0&&(this.defaultValue=i,this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("not enough elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},Xg=j(kl,"elementAt"),zg=s=>i=>Wi(1)(Wa(e=>!s(e))(i)),Pl=class extends W{constructor(i,e){super(i),this.f=e,this.i=0}next(i){this.f(i)?(this.sink.next(this.i++),this.complete()):++this.i}},Qg=j(Pl,"findIndex"),xl=class extends W{constructor(i,e,t){super(i),this.f=e,this.defaultValue=t,this.index=0}next(i){(!this.f||this.f(i,this.index++))&&(this.defaultValue=i,this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},Yg=j(xl,"first"),Ll=class extends W{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()}},Zg=j(Ll,"last"),wl=class extends W{constructor(i,e){super(i),this.predicate=e,this.index=0}next(i){this.predicate(i,this.index++)?this.result=!0:(this.result=!1,this.complete())}complete(){if(this.result===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.result);super.complete()}},Kg=j(wl,"every");var Ul=class extends W{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))}},jl=j(Ul,"scan"),Vl=class extends W{constructor(){super(...arguments),this.hasLast=!1}next(i){this.hasLast?this.sink.next([this.last,i]):this.hasLast=!0,this.last=i}},eT=j(Vl,"pairwise"),Ja=class extends W{constructor(i,e,t){super(i),this.mapper=e,this.thisArg=t}next(i){super.next(this.mapper.call(this.thisArg,i))}},en=j(Ja,"map"),tT=s=>j(Ja,"mapTo")(i=>s),Ps=class extends W{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()}},xs=class extends W{constructor(i,e,t){super(i),this.makeSource=e,this.combineResults=t,this.index=0}subInner(i,e){let t=this.currentSink=new e(this.sink,i,this);this.complete=this.tryComplete,t.complete=t.tryComplete,t.subscribe(this.makeSource(i,this.index++))}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},qa=class extends Ps{},ja=class extends xs{next(i){this.subInner(i,qa),this.next=e=>{this.currentSink.dispose(),this.subInner(e,qa)}}},Ls=j(ja,"switchMap");function Ya(s){return(i,e)=>s(()=>i,e)}var Wr=Ya(j(ja,"switchMapTo")),Bl=class extends Ps{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},Xa=class extends xs{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(),Bl),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},iT=j(Xa,"concatMap"),rT=Ya(j(Xa,"concatMapTo")),Fl=class extends Ps{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},za=class extends xs{constructor(){super(...arguments),this.inners=new Set}next(i){this.subInner(i,Fl),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(i=>i.resetComplete()):this.dispose()}},sT=j(za,"mergeMap"),oT=Ya(j(za,"mergeMapTo")),$l=class extends Ps{dispose(){this.context.resetNext(),super.dispose()}},Qa=class extends xs{next(i){this.next=de,this.subInner(i,$l)}},nT=j(Qa,"exhaustMap"),aT=Ya(j(Qa,"exhaustMapTo")),Hl=class extends W{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=tt(),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)}},cT=j(Hl,"groupBy"),Gl=class extends W{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}},dT=j(Gl,"timeInterval"),Wl=class extends W{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()}},lT=j(Wl,"bufferTime"),Jl=class extends W{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)}},uT=j(Jl,"delay"),ql=class extends W{constructor(i,e){super(i),this.selector=e}error(i){this.dispose(),this.selector(i)(this.sink)}},Xl=j(ql,"catchError");var hT=()=>s=>new Promise((i,e)=>{let t;new Hr(s,r=>t=r,e,()=>i(t))}),mT=()=>s=>{let i;return new ReadableStream({start(e){i=new Hr(s,e.enqueue.bind(e),e.error.bind(e),e.close.bind(e))},cancel(){i.dispose()}})},be=(s=de,i=de,e=de)=>t=>new Hr(t,s,i,e),zl=class extends W{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)}))}},Yl=j(zl,"tap"),Ql=class extends W{constructor(i,e){super(i),this.timeout=e,this.id=setTimeout(()=>this.error(new Qo(this.timeout)),this.timeout)}next(i){super.next(i),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},pT=j(Ql,"timeout"),fT=(s=1/0)=>i=>{if(i instanceof Ct){let e=ie(t=>{let r=s,o=new W(t);o.error=n=>{r-- >0?o.subscribe(i):t.error(n)},o.sourceId=e.id,o.subscribe(i)},"retry",[s]);return e.source=i,Ce.pipe(e),e}else return e=>{let t=s,r=new W(e);r.error=o=>{t-- >0?i(r):e.error(o)},i(r)}};var pi=class pi extends Vr{constructor(e,t,r){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:r,room:e});this.room=e;this.user=t;d(this,"tinyId");d(this,"isRemote",!0);d(this,"jitterBufferDelay",0);d(this,"availableState");d(this,"remotePublishState");d(this,"_triggerCheckDecodeSubject",tt(he(this,pi.STATE_SUBSCRIBE)));this.tinyId=t.tinyId,this.availableState=new H(`${t.userId}-${this.mediaType}-available`,"remote-track-available"),this.remotePublishState=new H(`${t.userId}-${this.mediaType}-remote-publish`,"remote-track-publish"),le(Tl(he(this,H.STATECHANGED),he(this.remotePublishState,H.STATECHANGED)),en(()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing)),be(c=>{this.availableState.state!==(c?H.ON:H.OFF)&&(this.availableState.state=c?H.ON:H.OFF),this.updatePlayingState(c)}));let o=le(he(this.player,ue.ERROR),mi(c=>c.code===MediaError.MEDIA_ERR_DECODE)),n=le(Zo(5e3),mi(()=>this.ignoreDecodeError||!this.isSubscribed||!this.isPlayCalled||!this.stat.bytesReceived?!1:this.player.isPlaying||(this.kind===p.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)?(this.reportDecodeResult(!0),!1):!0)),a=le(El(o,n),Be(he(this,H.INIT)));le(this._triggerCheckDecodeSubject,mi(()=>!this.ignoreDecodeError),Wr(a),be(c=>{this.reportDecodeResult(!1,c)}))}setMute(e){this.isRemotePublished&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.isRemotePublished&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}checkDecodeResult(){this._triggerCheckDecodeSubject.next(!0)}waitHasMediaTrack(){return new Promise(e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)})}get ignoreDecodeError(){var t,r;return(((r=(t=this.room)==null?void 0:t.networkQuality)==null?void 0:r.downlinkNetworkQuality)||0)>3||this.player.isInAutoPlayFailedState}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===pi.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===H.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){let r=this.kind===p.AUDIO;b[e?"addSuccessEvent":"addFailedEvent"]({key:r?504700:514702}),e||(b.addEnum({key:r?504701:514703,value:yo()}),re.uploadEvent({log:`stat-decode-failed-${this.kind}-${Or()||Pi()}`,userId:this.room.userId}),this._log.warn(`decode failed: isPlaying: ${this.player.isPlaying} ${this.kind===p.AUDIO?`audioLevel: ${this.getAudioLevel()}`:`framesDecoded: ${this.stat.framesDecoded>0}`}`),this.emit("decode-failed",{error:t}))}updatePlayingState(e){if(this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.isRemotePublished||!this.outMediaTrack)){this.log.info(`abort play, isSubscribed: ${this.isSubscribed} isAvailable: ${this.isRemotePublished} hasTrack: ${!!this.outMediaTrack} `);return}super.updatePlayingState(e)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.remotePublishState.state=this.isRemotePublished?H.ON:H.OFF}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};d(pi,"STATE_SUBSCRIBE","subscribe"),v([Va(5,1)],pi.prototype,"waitHasMediaTrack",1),v([Te(H.INIT,pi.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),E.emit(A.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),at(521716,!1)],pi.prototype,"subscribe",1),v([Te(pi.STATE_SUBSCRIBE,H.INIT,{sync:!0,success(){this.log.info("unsubscribed"),E.emit(A.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],pi.prototype,"unsubscribe",1);var ws=pi;var Gt=class extends ws{constructor(e,t){super(e,t,1);d(this,"volume",0);d(this,"mediaType",1);d(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.audioManager}get dbVolume(){return Ur.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}decodeFrame(e){if(!this.manager)return e;let t=e;for(let r of this.manager.decodePipeline)if(r&&(t=r({frame:t,track:this}),!t))return;return t}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get isRemotePublished(){return this.user.muteState.audioAvailable}};var gT=[-1,-1,1,-1,-1,1,1,1],TT=[0,0,1,0,0,1,1,1];var it=class extends H{constructor(e,t){super();this.context=e;d(this,"name");d(this,"input");d(this,"output");d(this,"texture");d(this,"ctx2d",null);d(this,"fbo");d(this,"width",0);d(this,"height",0);d(this,"x",0);d(this,"y",0);d(this,"program");d(this,"vertexShader");d(this,"fragmentShader");d(this,"totalFrames",0);d(this,"dropFrames",0);d(this,"matchInputSize",!0);d(this,"texCoordBuffer");d(this,"positionBuffer");d(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0});d(this,"cost",0);d(this,"_canvas",null);d(this,"_image");d(this,"log");if(this.context.on("disconnect",this.close,this),this.name=t.name,this.log=t.logger,this.matchInputSize=t.matchInputSize!==!1,this.width=t.width||e.width,this.height=t.height||e.height,this._image=t.image,e instanceof Xe){e.ctx&&t.create2d&&(typeof OffscreenCanvas=="function"&&ut!==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(TT),this.positionBuffer=this.createBuffer(gT),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.PACK_ALIGNMENT,1),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 y({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 ke&&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 ke){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,o)=>{r&&(t.activeTexture(t.TEXTURE0+o),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,o)=>{t.enableVertexAttribArray(o),t.bindBuffer(t.ARRAY_BUFFER,r),t.vertexAttribPointer(o,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,o,n){return this.ctx2d&&e?(e instanceof ImageData?this.ctx2d.putImageData(e,t,r):(this.ctx2d.drawImage(e,t,r,o,n),typeof VideoFrame!="undefined"&&e instanceof VideoFrame&&e.close()),!0):!1}getInfo(){var h;let{totalFrames:e,x:t,y:r,width:o,height:n,name:a,cost:c}=this,l=Date.now(),u=(e-this.lastInfo.totalFrames)/((l-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:r,width:o,height:n,timestamp:l,fps:u,name:a,cost:c},N({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.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),r}};v([Te(H.INIT,"connected",{sync:!0})],it.prototype,"connect",1),v([Te("connected",H.INIT,{ignoreError:!0,sync:!0})],it.prototype,"disconnect",1),v([Te([],"closed",{sync:!0})],it.prototype,"close",1);var ET=le(Sl(250),en(()=>performance.now()),Gi());var Lm=s=>i=>{let e=performance.now();le(ET,Wa(t=>t-e<s),Wi(1))(i)};var IT=[0,1,1,1,0,0,1,0],Jr=class extends it{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t));d(this,"_intervalId",0);d(this,"_sequence",0);d(this,"checkGLError",!1);d(this,"checkVisibilityChange");e instanceof Xe?this.ctx2d=e.ctx||null:e.available&&(t!=null&&t.mirrorUpAndDown)&&this.setTexBuffer(IT)}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 ke){let r=this.context.ctx.getError();r&&this.context.destroy(new y({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(),!0):!1}addInput(e,...t){super.addInput(e,...t),this.start(this.context.frameRate)}update(e=0){if(this._intervalId&&(oe.clearTask(this._intervalId),this._intervalId=0,e===1)){this.log.info(`${this.name} use requestVideoFrameCallback`);let t=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info(`${this.name} use timer`),document.removeEventListener("visibilitychange",t))};document.addEventListener("visibilitychange",t)}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)}},Us=class extends Jr{constructor(e,t){super(e,t);d(this,"_videoTrack");d(this,"_muteOb");d(this,"_closedOb",he(this,"closed"));d(this,"_subscription");d(this,"_canvasContainer");Number(Mi)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e._canvas.captureStream().getVideoTracks(),this._muteOb=he(this._videoTrack,"mute"),le(he(this._videoTrack,"ended"),Be(this._closedOb),be(()=>{this.context.destroy(new y({code:I.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){this._subscription=le(this._muteOb,Be(this._closedOb),Wr(Lm(5e3)),mi(()=>{var e;return!!((e=this._videoTrack)!=null&&e.muted)&&!document.hidden}),be(()=>{this.context.destroy(new y({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()}},Za=class extends Us{render(i){var e;return!!((e=this.input)!=null&&e.requestFrame(i))}};var Ka=class extends Us{constructor(e,t,r){super(e,{name:"smallDestination",logger:r});this.resolution=t}resize(e,t){let r,o=e*t,n=this.resolution.width*this.resolution.height;this.log.info(`big res: ${e}*${t} small res: ${this.resolution.width}*${this.resolution.height} `),o>n?r=o/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=o/(160*120)),super.resize(e/Math.sqrt(r),t/Math.sqrt(r))}};var tn=class extends it{constructor(e,t){super(e,N({name:"imageSource"},t));d(this,"_lastImage");d(this,"_totalFrames",0);d(this,"_autoResize",!1);d(this,"_canvasRendered");d(this,"_videoCallbackId",0);d(this,"waitingFirstFrame",!0);d(this,"shouldUpdate",!0);this._autoResize=(t==null?void 0:t.autoResize)!==!1,ut===16&&(this._canvasRendered=tt(),le(this._canvasRendered,Yo(this._image),Ls(r=>r instanceof HTMLCanvasElement?he(r,"rendered"):Ko()),Be(he(this,"closed")),be(()=>{this.update()})))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){if(!this.shouldUpdate)return;let e=this.image;this._videoCallbackId&&e.cancelVideoFrameCallback(this._videoCallbackId),wr()&&!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:o}=this,{image:n}=this;if(n instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(),{videoWidth:r,videoHeight:o}=n,!r||!o)return!1;n.width=r,n.height=o}else if(n instanceof HTMLImageElement||n instanceof ImageData||n instanceof ImageBitmap){if({width:r,height:o}=n,n!==this._lastImage)this._lastImage=n;else if(r===this.width&&o===this.height)return!1}else n instanceof HTMLCanvasElement||n instanceof OffscreenCanvas?({width:r,height:o}=n,this._lastImage=n):typeof VideoFrame!="undefined"&&n instanceof VideoFrame&&({displayWidth:r,displayHeight:o}=n,(a=this._lastImage)==null||a.close(),this._lastImage=n);if(!this._autoResize)return!0;if(this.width===r&&this.height===o&&this.totalFrames){if(t){this.useTexture();let c=this.context.ctx;c.texSubImage2D(c.TEXTURE_2D,0,0,0,c.RGBA,c.UNSIGNED_BYTE,n)}}else{if(t){this.useTexture();let c=this.context.ctx;c.texImage2D(c.TEXTURE_2D,0,c.RGBA,c.RGBA,c.UNSIGNED_BYTE,n)}this.resize(r,o)}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)}},rn=class extends tn{constructor(e,t,r){super(e,r);this._player=t;this.name="videoPlayerSource",le(he(this._player,ue.PLAYER_STATE_CHANGED),Be(he(this,"closed")),mi(({state:o})=>o==="PLAYING"),be(()=>{this.tryVideoFrameCallback()}))}get image(){return this._player.element}},Ji=class extends rn{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(i,e,t){super(i,new ft({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()}};var RT=`
33
+ `,t.onclick=this.onQuestionClick.bind(this);let r=document.createElement("div");r.className=rl,r.innerText=`${kt()?"\u8BE6\u60C5 >":"Detail >"}`,r.onclick=this.onCollapseClick.bind(this);let o=i.content.firstChild,n=o.querySelector(`.${Ea}`);return n.appendChild(r),n.appendChild(t),n.appendChild(e),o}addDiaLog(){nl()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${vs}`).onclick=i=>i.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",C.info("show autoplay dialog"),re.uploadEvent({log:J_}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){C.warn("confirm clicked, try resume stream"),E.emit(A.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let i=this._dialogNode.querySelector(`.${rm}`);i.style.visibility=`${this._showDetail?"hidden":"visible"}`,i.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||re.uploadEvent({log:q_}),this._isCollapseClicked=!0}onQuestionClick(){window.open(am,"_blank"),this._isQuestionClicked||re.uploadEvent({log:j_}),this._isQuestionClicked=!0}},cm=sl;var ft=class extends di{constructor(e){super(e,p.VIDEO);d(this,"stat",{});d(this,"_calculateTimeout",-1);d(this,"viewMirror",!1);d(this,"objectFit");d(this,"container");d(this,"canvas");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(p.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,(t=this.container)==null||t.appendChild(this.elementToRender),this.bindElementEvents(),this.calculateStat()}get styleAttribute(){let e=`width: 100%; height: 100%; object-fit: ${this.objectFit};background-color: black;`;return this.viewMirror&&(e+="transform: scaleX(-1);"),e}setContainer(e){var 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(p.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(p.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent)}handleTrackEvent(e){var t;super.handleTrackEvent(e),e.type===p.MUTE&&((t=this.stat)!=null&&t.fps)&&(this.stat.fps=0)}handleElementEvent(e){var r,o;if(this.mode===2)return;super.handleElementEvent(e);let t=e.type;if(t===p.PAUSE&&(this.container&&document.getElementById(this.container.id)||this._log.warn(`${this.kind} player has been remove, element ID: ${(r=this.container)==null?void 0:r.id}`),this.container&&this.container!==document.getElementById(this.container.id)&&(this._pausedRetryCount=Ir,this._log.info(`view container ${(o=this.container)==null?void 0:o.id} is recreated`)),this._pausedRetryCount>0&&!nl()&&(this._log.info(`[${Ir-this._pausedRetryCount+1}/${Ir}] ${this.kind} player auto resume when paused`),this.resume(),this._pausedRetryCount--),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){let n=this.element.style.transform;t===p.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=n.replace("scaleX(-1)",""):t===p.LEAVE_PICTURE_IN_PICTURE&&!n.includes("scaleX")&&(this.element.style.transform=`${n} scaleX(-1)`)}}setCanvas(e,t=1){var r,o,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?((o=this.element)==null||o.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){this.element&&(this.element.poster=e)}stop(e=0){var t;super.stop(e),(t=this.canvas)==null||t.remove()}play(){return this.element?this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender):this.initializeElement(),this.mode===2?Promise.resolve():super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(ue.MEDIA_TRACK_CHANGED,e),e!==null&&(this.bindTrackEvents(),this.element&&this.mode!==2&&(this.element.srcObject=new MediaStream([e]),this.element.remove()),this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender)))}getVideoFrame(){if(this.canvas)return this.canvas.toDataURL("image/png");if(!this.element)return"";let e=document.createElement("canvas");return e.width=this.element.videoWidth,e.height=this.element.videoHeight,e.getContext("2d").drawImage(this.element,0,0),e.toDataURL("image/png")}getElement(){return this.element}calculateStat(){try{if(wr()&&this.element&&this._calculateTimeout<0){let e=0,t=null,r=(o,n)=>{this.stat.width=n.width,this.stat.height=n.height,t&&(this.stat.fps=Math.round((n.presentedFrames-t.presentedFrames)/(o-e)*1e3)),e=o,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 Bi(s,i){return f(this,null,function*(){if(!s.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield s.audioWorklet.addModule(i),C.info("worklet addModule success")}catch(e){throw C.info(`worklet addModule catch error. ${e.message}`),e}})}var Go;typeof AudioContext!="undefined"?Go=AudioContext:typeof webkitAudioContext!="undefined"?Go=webkitAudioContext:typeof mozAudioContext!="undefined"&&(Go=mozAudioContext);var Ht,dm=-1;lm();function lm(){try{if(Ht)return;Ht=new Go({sampleRate:48e3}),Ht.onstatechange=()=>{C.info(`context state: ${Ht.state}${Ht.state!=="running"?` visibilityState: ${document.visibilityState}`:""}`),Ds()},clearTimeout(dm)}catch(s){C.error(`initAudioContext failed: ${s} typeof AudioContextClass: ${typeof Go}`),dm=setTimeout(lm,1e3)}}var Ds=()=>{Ht.state==="suspended"?(Os(),document.addEventListener("click",Ds)):Ht.state==="interrupted"?Os():(document.removeEventListener("visibilitychange",Ds),document.removeEventListener("click",Ds))},al=0,cl=-1;function Os(){return new Promise((s,i)=>{if(Ht.state==="running")return s();Date.now()-al<1e3?(clearTimeout(cl),cl=setTimeout(()=>{al=Date.now(),Ht.resume().then(s,i)},1e3)):(clearTimeout(cl),al=Date.now(),Ht.resume().then(s,i))}).catch(s=>{C.warn(`context resume failed: ${s}`),document.addEventListener("visibilitychange",Ds)})}document.addEventListener("click",Ds);var Ee=s=>Ht;var De=class{constructor(i){this.name=i;d(this,"node");d(this,"node2");d(this,"pre",new Set);d(this,"next",new Set);d(this,"context");d(this,"connectedNodes",new Set);d(this,"nextInputChannelMap",new Map);d(this,"_channelCount",1)}get channelCount(){return this._channelCount}set channelCount(i){this._channelCount=i,this.setChannelCount(this.node,i),this.setChannelCount(this.node2,i),this.next.forEach(e=>e.channelCount=i)}setChannelCount(i,e){!i||i instanceof ScriptProcessorNode||(i.channelCountMode="explicit",i.channelCount=e||this.channelCount||1)}setContext(i){this.context=i,this.node&&i.addMixWeight()}removeContext(){var i;this.node&&((i=this.context)==null||i.reduceMixWeight()),delete this.context}replaceNode(i){var e;if(i!==this.node)try{this.node?this._disconnect():(e=this.context)==null||e.addMixWeight(),this.node=i,this.setChannelCount(this.node),this.preNodeReconnect(),this.reconnect()}catch(t){C.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(),b.addSuccessEvent({key:502701})}catch(r){C.error(r),b.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(),b.addSuccessEvent({key:502702})}catch(e){C.error(e),b.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}},Ia=class extends De{constructor(e=256){super();this.fftSize=e;d(this,"dataArray",new Uint8Array(0))}setNode(e){e.fftSize=this.fftSize,this.dataArray=new Uint8Array(e.frequencyBinCount),super.setNode(e)}getByteTimeDomainData(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),this.dataArray}get level(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),Math.max(...this.dataArray)/128-1}get timeDomainPathData(){let e=this.getByteTimeDomainData(),t=1,r=0,o=0,n=`M${r},${o}`;for(let a=0;a<e.length;a++)o=e[a]/128*100/2,n+=`L${r},${o}`,r+=t;return n}},Wo=class{constructor(){d(this,"source",new De);d(this,"gain",new De);d(this,"destination",new De)}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){this.source.replaceNode(Jo(i))}get track(){var i;return(i=this.stream)==null?void 0:i.getAudioTracks()[0]}get stream(){var i;return(i=this.destination.node)==null?void 0:i.stream}},Ms=class extends Wo{constructor(e){super();this.context=e;d(this,"aec",new De("aec"));d(this,"mixNode",new De("mixNode"));d(this,"silentNode",new De("silentNode"));d(this,"denoiser",new De("denoiser"));d(this,"voiceChanger",new De("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)}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}},Aa=class{constructor(){d(this,"audioContext",Ee("audio-mixer"));d(this,"destination",this.audioContext.createMediaStreamDestination());d(this,"inputs",new Set);d(this,"mixWeight",0);this.destination.channelCount=1}addMixWeight(i=1){this.mixWeight+=i,this.mixWeight-1===i+1>>1&&this.mixOnChange()}reduceMixWeight(i=1){this.addMixWeight(-i)}close(){this.inputs.forEach(i=>i.remove())}get mixTrack(){return this.destination.stream.getAudioTracks()[0]}},um=new WeakMap;function Jo(s){let i=um.get(s);if(i)return i;let e=Ee();if(s instanceof HTMLAudioElement)i=e.createMediaElementSource(s);else if(s instanceof MediaStreamTrack)i=e.createMediaStreamSource(new MediaStream([s]));else return s;return um.set(s,i),i}var _t=class _t{constructor(i){d(this,"_volume",0);d(this,"_volumeDb",0);d(this,"_log");d(this,"_scriptProcessorNode",null);d(this,"_audioWorkletNode",null);d(this,"_interval",200);d(this,"ready",this.preload());let{log:e}=i;this._log=e,E.on(A.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-_t.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!_t.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);';_t.workletReady=Bi(_t.audioContext,URL.createObjectURL(new Blob([i],{type:"application/javascript"})))}return _t.workletReady.then(()=>this.initAudioWorklet()).catch(i=>(this._log.error(`volumeMeter preload error: ${i}`),this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(_t.audioContext,"volume-meter");let i=!1;this._audioWorkletNode.port.onmessage=e=>{_t.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}`),re.logFailedEvent({userId:this._log.userId,eventType:st.LOAD_WORKLET,error:i}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=Ee("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=i=>{_t.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,E.off(A.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}getVolumeDb(){return Math.floor(this._volumeDb*100)}handleAudioLevelInterval(i){var t;let{interval:e}=i;this._interval=e,(t=this._audioWorkletNode)==null||t.port.postMessage({name:"setIntervalTime",intervalTime:e})}};d(_t,"lastMessageTime",0),d(_t,"audioContext",Ee("volume-meter")),d(_t,"workletReady");var Ra=_t,Ca=class extends De{constructor(e){super();d(this,"_volumeMeter");this._volumeMeter=new Ra(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()}}},Ur=Ra;var fm=$e(Ye(),1);var mm=s=>i=>i.deviceId===s;var qo=class{constructor(i,e="Input"){d(this,"kind");d(this,"type");d(this,"devices",[]);this.kind=i,this.type=e}update(i,e){let t=i.filter(r=>r.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);if(this.devices.length===1&&ks(this.devices[0])){this.devices=t;return}e&&(t.forEach(r=>{if(r.deviceId&&!this.devices.find(mm(r.deviceId))){let o=`${this.kind}${this.type}Added`;C.warn(`${o}: ${JSON.stringify(r)}`),e.emit(o,r)}}),this.devices.forEach(r=>{if(r.deviceId&&!t.find(mm(r.deviceId))){let o=`${this.kind}${this.type}Removed`;C.warn(`${o}: ${JSON.stringify(r)}`),e.emit(o,r)}})),this.devices=t}hasDevice(i){return!!this.devices.find(e=>e.deviceId===i)}},dl=class extends fm.EventEmitter{constructor(){super();d(this,"audioInputs",new qo(p.AUDIO));d(this,"videoInputs",new qo(p.VIDEO));d(this,"audioOutputs",new qo(p.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(){ya().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 ya(e);return this.audioInputs.update(t,this),this.videoInputs.update(t,this),this.audioOutputs.update(t,this),this})}},Le=io||ts?null:new dl;function ks(s){return s.deviceId===s.groupId&&s.groupId===""}function ya(){return f(this,arguments,function*(s=0){if(wi()||!ma())return[];let i=yield navigator.mediaDevices.enumerateDevices();if(s!==0){let e={audio:!1,video:!1};if(i.forEach(t=>{ks(t)&&(t.kind===p.AUDIO_INPUT?e.audio=!0:t.kind===p.VIDEO_INPUT&&(e.video=!0))}),s===2&&(e.audio=!1),s===1&&(e.video=!1),e.audio||e.video){let t;try{t=yield navigator.mediaDevices.getUserMedia(e),e.audio&&Os()}catch(r){C.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&&ll.add(`${e.deviceId}_${e.kind}`),e.getCapabilities&&(r.getCapabilities=()=>e.getCapabilities()),r})})}function nt(s=!1){return Le.update(s?1:0).then(i=>i.audioInputs.devices)}function gt(s=!1){return Le.update(s?2:0).then(i=>i.videoInputs.devices)}var pm=!1;function _m(){return f(this,null,function*(){try{pm||(pm=!0,C.info(`speakers:${(yield lr()).map(s=>` ${s.deviceId.slice(0,8)}: ${s.label}`)}`))}catch(s){}})}function lr(s=!1){return f(this,null,function*(){return(Ie||xe)&&(s=!1),Le.update(s?1:0).then(i=>i.audioOutputs.devices)})}var ll=new Set;function gm(s){if(s instanceof CanvasCaptureMediaStreamTrack||!(s instanceof MediaStreamTrack))return!1;let i=s.label.toLocaleLowerCase();if(i.includes("camera")||i.includes("webcam"))return!0;let t=`${((s==null?void 0:s.getSettings())||{}).deviceId}_${p.VIDEO_INPUT}`;return!!ll.has(t)}function Tm(s){if(s instanceof CanvasCaptureMediaStreamTrack||!(s instanceof MediaStreamTrack))return!1;let i=s.label.toLocaleLowerCase();if(i.includes("mic")||i.includes("\u9EA6\u514B\u98CE"))return!0;let t=`${((s==null?void 0:s.getSettings())||{}).deviceId}_${p.AUDIO_INPUT}`;return!!ll.has(t)}function ul(s,i){return f(this,null,function*(){let t=(yield nt()).find(r=>r.deviceId===Ar);return!i&&(t==null?void 0:t.groupId)===s||(t==null?void 0:t.groupId)===s&&t.label===i})}function Em(o){return f(this,arguments,function*({newDeviceId:s,oldDeviceId:i,oldGroupId:e,oldLabel:t,kind:r}){return s!==i?!1:r===p.AUDIO&&s===Ar?yield ul(e,t):!0})}var ba,hl=class extends Wo{constructor(e){super();this.log=e;d(this,"volumeMeter");d(this,"volumeDestination");d(this,"analyser",new Ia);this.volumeMeter=new Ca({log:this.log}),this.volumeDestination=new De,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},Na=class s extends di{constructor(e){super(e,p.AUDIO);d(this,"_outputDeviceId");d(this,"_volume",1);d(this,"_destination",Ee("player").createMediaStreamDestination());d(this,"pipeline");d(this,"volumeMeterMode","worklet");this.mode=0,this.pipeline=new hl(this._log)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(e){if((Kt==="15.2"||Kt==="15.3"||Kt==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}let r=ba||new Audio;r.setAttribute("autoplay","autoplay"),r.srcObject=this.getMediaStream(),r.muted=this.muted,this.element=r,q(e)&&(this.element.volume=Math.min(Math.max(e,0),1)),r===ba&&(ba=void 0),this.bindElementEvents()}play(e){return f(this,null,function*(){if(this.track)return this.pipeline.source.node||this.pipeline.replaceSource(this.track),this.element||this.initializeElement(e==null?void 0:e.volume),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),this.volumeMeterMode==="worklet"?this.pipeline.volumeMeter.init():this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(Ee("player").createAnalyser()),_m(),He(s.prototype,this,"play").call(this)})}stop(e=0){this.pipeline.destroy(),super.stop(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()}},va=class extends Na{setTrack(i){this.track!==i&&(this.unbindTrackEvents(),this.track=i,this.emit(ue.MEDIA_TRACK_CHANGED,i),i&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([i]))))}setVolume(i){this._volume=i,this.element&&(this.element.volume=i)}},Da=class extends Na{constructor(e){super(e);d(this,"_sourceElement");d(this,"_output",new De);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,o;((r=(t=this.element)==null?void 0:t.error)==null?void 0:r.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(ue.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([e]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e])),this.pipeline.source.channelCount=((o=e.getSettings())==null?void 0:o.channelCount)||1,this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){this._volume=e,this.useDestination?(this.pipeline.setVolume(e),this._log.info(`set pipeline volume: ${e}`)):e<=1?this.element?(this._log.info(`set element volume: ${e}`),this.element.volume=e):this._log.info("set element volume: no element"):Ie||(this._log.info(`start set pipeline volume: ${e}`),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),ve(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&&nr&&(ba=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}};var Vr=class extends H{constructor({userId:e,sdkAppId:t,mediaType:r,room:o,PlayerClass:n=r===1?Da:ft}){var a;super();d(this,"id",bo());d(this,"userId","");d(this,"isRemote");d(this,"mediaType");d(this,"room");d(this,"user");d(this,"_log");d(this,"_inputTrack");d(this,"_outputTrack");d(this,"isPlayCalled");d(this,"container",null);d(this,"player");d(this,"subVideoPlayerMap");d(this,"muted",!1);d(this,"abortCtrl");d(this,"objectFit","cover");d(this,"mirror");d(this,"rotation");d(this,"isScreen",!1);d(this,"manager");d(this,"trackSettings");d(this,"isFirstVideoFrameEmitted",!1);this.userId=e||"",this.mediaType=r,this._log=C.createLogger({id:`${this.kind[0]}t`,userId:(a=o||this.room)==null?void 0:a.userId,remoteUserId:this instanceof Fi?void 0:this.userId,sdkAppId:t,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof Fi}),this.player=new n({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log}),this.player.on(ue.PLAYER_STATE_CHANGED,c=>{E.emit(A.PLAYER_STATE_CHANGED,N({track:this},c)),this.emit("player-state-changed",c)}),this.kind===p.VIDEO&&(this.player.on(ue.LOADED_DATA,()=>{this.emitFirstVideoFrameEvent(ue.LOADED_DATA),E.emit(A.VIDEO_LOADED_DATA,{track:this})}),this.player.on(ue.LOADED_META_DATA,()=>{this.emitFirstVideoFrameEvent(ue.LOADED_META_DATA)}),this.player.on(ue.MEDIA_TRACK_CHANGED,c=>{var l;(l=this.subVideoPlayerMap)==null||l.forEach(u=>u.setTrack(c))})),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(ue.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||C}get kind(){return this.mediaType===1?p.AUDIO:p.VIDEO}get strMediaType(){return this.mediaType===4?p.VIDEO:this.mediaType===2?p.SCREEN:p.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=Se(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 ft&&(this.player.setObjectFit(this.objectFit),this.container!==r&&r&&(this.container=r,this.player.setContainer(r)),Se(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===p.VIDEO)&&this.setPlayerMute(!0),t&&!T(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof ft&&(this.player.setObjectFit(this.objectFit),t&&!T(t.poster)&&this.player.setPoster(t.poster)),this.isPlayCalled=!0,r&&(this.container=r,this.player instanceof ft&&this.player.setContainer(r)),E.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),Se(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(o){throw this.handleAutoPlayFailed(o),o}})}setMirror(e,t){if(this.isScreen||this.kind!==p.VIDEO||T(e)||e===this.mirror)return;this.mirror=e;let r=this.player;t&&(r=t);let o=this.manager;if(me(this.mirror)){r.setViewMirror(this.mirror),o&&(o.mirror=!1);return}switch(this.mirror){case"view":{o&&(o.mirror=!1),r.setViewMirror(!0);break}case"publish":{o&&(o.mirror=!0),r.setViewMirror(!0);break}case"both":o&&(o.mirror=!0),r.setViewMirror(!1)}}playSubContainer(e,t){return f(this,null,function*(){if(!this._outputTrack||this.kind===p.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((o,n)=>{var a;e.find(c=>n===c)||(o.stop(),(a=this.subVideoPlayerMap)==null||a.delete(n))});for(let[o,n]of e.entries()){let a=this.subVideoPlayerMap.get(n);a?t&&(T(t.objectFit)||a.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new ft({id:this.userId||this.id,track:this.playerMediaTrack,container:n,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:`vp-sub${o+1}`})}))}let r=[...this.subVideoPlayerMap.values()];for(let o of r)o.setViewMirror(this.player.mirror),yield o.play()})}setAudioOutput(e){return this.player.setSinkId(e)}setAudioVolume(e){this.player.setVolume(e)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var e;return((e=this.player)==null?void 0:e.getInternalAudioLevel())||0}stop(e=!1){this.isPlayCalled&&(this.isPlayCalled=!1,this.player&&(this.log.info(`stop ${this.kind} player`),this.player.stop(nd(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),E.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){qe(e,e).add(p.MUTE,this.onTrackMuted).add(p.UNMUTE,this.onTrackUnmuted).add(p.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===p.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){ve(e)}setInputMediaStreamTrack(e){var r;let t=this._inputTrack;if(e!==t)return this._inputTrack=e,this.trackSettings=(r=e.getSettings)==null?void 0:r.call(e),e.enabled=!this.muted,t&&this.uninstallTrackEvent(t),this.installTrackEvent(e),this.emit("input-media-track-changed",e||null,t||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var r;let t=this._outputTrack;e!==t&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",(r=e.getSettings)==null?void 0:r.call(e).deviceId,e.label),this._outputTrack=e,this._inputTrack&&(this._outputTrack.contentHint=this._inputTrack.contentHint,this._outputTrack.enabled=this._inputTrack.enabled),this.updatePlayingState(!!e),this.emit("output-media-track-changed",e))}setMediaType(e){this.mediaType=e}updatePlayingState(e){if(this.isPlayCalled){if(e){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped){this.player.play().catch(t=>this.handleAutoPlayFailed(t)),this.log.info(`playing state updated, play ${this.kind}`);return}}else if(!this.player.isStopped){this.player.stop(nd(this)?this.jitterBufferDelay:0),this.log.info(`playing state updated, stop ${this.kind}`);return}}this.log.debug(`updatePlayingState abort ${this.isPlayCalled} ${e} ${this.player.isStopped}`)}handleAutoPlayFailed(e){if(this.room&&this.room.enableAutoPlayDialog)new cm;else{let t=()=>{this.resume().then(()=>{document.removeEventListener("click",t,!0)})};document.addEventListener("click",t,!0)}this.emit("error",e)}getVideoFrame(){return this.player instanceof ft?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(e){var n,a,c;if(this.isFirstVideoFrameEmitted)return;let t=(n=this.mediaTrack)==null?void 0:n.getSettings(),r=(t==null?void 0:t.width)||((a=this.player.element)==null?void 0:a.videoWidth)||0,o=(t==null?void 0:t.height)||((c=this.player.element)==null?void 0:c.videoHeight)||0;e===ue.LOADED_META_DATA&&!r&&!o||(e===ue.LOADED_DATA&&!r&&!o&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,vi(this.rotation)&&([r,o]=[o,r]),this.emit("first-video-frame",{width:r,height:o,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`)}};v([Te([],H.INIT,{sync:!0})],Vr.prototype,"close",1);var z_=Object.prototype.hasOwnProperty,{toString:MR}=Object.prototype;function Q_(s){if(s==null)return!0;if(typeof s=="boolean")return!1;if(typeof s=="number")return s===0;if(typeof s=="string"||typeof s=="function"||Array.isArray(s))return s.length===0;if(s instanceof Error)return s.message==="";if(Je(s))switch(Object.prototype.toString.call(s)){case"[object File]":case"[object Map]":case"[object Set]":return s.size===0;case"[object Object]":{for(let i in s)if(z_.call(s,i))return!1;return!0}}return!1}var li=Q_;var Y_=function(s){return f(this,null,function*(){let i=K_(s);C.info(`getUserMedia with constraints: ${JSON.stringify(i)}`);let e=[],t=[],r=["label","deviceId","groupId"];i.audio&&(e=yield nt(),C.info(`microphones: ${St(e.map(o=>L(N({},o),{groupId:o.groupId.substring(0,8)})),{keysToInclude:r})}`)),i.video&&(t=yield gt(),C.info(`cameras: ${St(t,{keysToInclude:r})}`));try{let o=yield navigator.mediaDevices.getUserMedia(i);return Xd&&o.getTracks().forEach(n=>{C.info(`${n.kind} capabilities: ${St(n.getCapabilities(),{keysToInclude:kn})}`)}),i.audio&&Os(),o}catch(o){let{message:n}=o;throw o.name==="NotFoundError"&&(s.video&&t&&t.length===0&&(n=x({key:P.CAMERA_NOT_FOUND})),s.audio&&e&&e.length===0&&(n=x({key:P.MICROPHONE_NOT_FOUND}))),new y({code:I.INITIALIZE_FAILED,name:o.name,message:n,constraint:o.constraint})}})},Z_=Yt({retryFunction:Y_,settings:{retries:3,timeout:500},onError:({error:s,retry:i,reject:e,retryFuncArgs:t,retriedCount:r})=>{let o=r+1;s.name==="NotReadableError"||s.name==="OverconstrainedError"?(o===1?(t[0].video&&(t[0].maxResolution=!1,(!xe||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)):o===2?t[0].useDeviceIdOnly=!0:o===3&&!t[0].useExactDeviceId&&(t[0].useTrueAsConstraint=!0),i()):e(s),t[0].microphoneId&&Sm(t[0].microphoneId,!1),t[0].cameraId&&Sm(t[0].cameraId,!0)},onRetrying:s=>{C.warn(`getUserMedia NotReadableError observed, retrying [${s}/3]`)},onRetryFailed:s=>{re.logFailedEvent({eventType:st.GET_USER_MEDIA_RETRY,error:s})},onRetrySuccess:s=>{re.logSuccessEvent({eventType:st.GET_USER_MEDIA_RETRY}),re.uploadEvent({log:`stat-${st.GET_USER_MEDIA_RETRY}-success-${s}`})}});function Sm(s,i){return f(this,null,function*(){let t=(i?yield gt():yield nt()).find(r=>r.deviceId===s);t&&ne(t.getCapabilities)&&C.warn(St(t.getCapabilities(),{keysToInclude:kn}))})}function K_(s){return{audio:eg(s),video:tg(s)}}function eg(s){if(!s.audio)return!1;if(s.useTrueAsConstraint)return!0;let i={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:s.sampleRate};return!li(s.microphoneId)&&(i.deviceId=s.useExactDeviceId?{exact:s.microphoneId}:s.microphoneId,s.useDeviceIdOnly)?i:(q(s.channelCount)&&(i.channelCount=s.channelCount),me(s.echoCancellation)&&!s.echoCancellation&&(i.echoCancellation=!1),me(s.noiseSuppression)&&!s.noiseSuppression&&(i.noiseSuppression=!1),me(s.autoGainControl)&&!s.autoGainControl&&(i.autoGainControl=!1),li(i)?!0:i)}function tg(s){if(!s.video)return!1;if(s.useTrueAsConstraint)return!0;let{maxResolution:i=!0}=s,e={};return s.cameraId?e.deviceId=s.useExactDeviceId?{exact:s.cameraId}:s.cameraId:s.facingMode&&(e.facingMode=s.facingMode),s.useDeviceIdOnly&&!li(e)?e:(s.width&&(e.width={ideal:s.width},i&&!ae&&(e.width.max=s.width)),s.height&&(e.height={ideal:s.height},i&&!ae&&(e.height.max=s.height)),ae&&Ut&&s.width&&s.height&&s.width*s.height<352*288&&(e.width=s.width,e.height=s.height),s.frameRate&&(e.frameRate=s.frameRate),li(e)?!0:e)}var Im=Z_;function Oa(s){return Q((i,e)=>function(...t){return f(this,null,function*(){return yield s.apply(this,t),i.apply(this,t)})})}function et(s){return Q((i,e)=>function(...t){return f(this,null,function*(){let r=yield i.apply(this,t);return yield s.call(this,...t),r})})}function Ma(s){return Q((i,e)=>function(...t){return f(this,null,function*(){try{return yield i.apply(this,t)}catch(r){s.call(this,r)}})})}function Q(s){return function(i,e,t){return t.value=s(t.value,e),t}}var Am=(()=>{let s=!1,i=document.visibilityState;return()=>{document.visibilityState!==i&&C.info(`visibility change: ${document.visibilityState}`),!s&&(document.addEventListener("visibilitychange",()=>{C.info(`visibility change: ${document.visibilityState}`),i=document.visibilityState}),s=!0)}})();var ig=0,ka=class{constructor(){d(this,"log",C.createLogger({id:`fq${++ig}`}));d(this,"isRunning",!1);d(this,"queue",[])}get length(){return this.queue.length}get lastQueueItem(){return this.length===0?null:this.queue[this.length-1]}push(i,e=!1){var o,n;let t=N({},i),r=new Promise((a,c)=>{t.resolve=a,t.reject=c});return t.promise=r,e?this.length<=1?this.queue.push(t):(n=(o=this.lastQueueItem)==null?void 0:o.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:o}=this.queue[0];this.isRunning=!0,i.apply(t,e).then(r,o).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},jo=new WeakMap,Pa=new WeakMap;function Rt(s=!1){return function(i,e,t){let r=t.value;return t.value=function(...o){let n=jo.get(this)||new ka;return jo.set(this,n),n.push({fn:r,args:o,context:this},s)},t}}function Rm(s){return function(i,e,t){let r=t.value;return t.value=function(...o){let n=jo.get(this);if(n){let a=n.queue.filter((c,l)=>{if(l===0)return!0;let u=!0;return c.args.forEach(h=>{o.find(m=>m===h)||(u=!1)}),u?(c.reject(new y({code:I.API_CALL_ABORTED,message:s})),!1):!0});n.queue=a}return r.apply(this,o)},t}}function xa(s){return function(i,e,t){let r=t.value;return t.value=function(...o){var a,c,l;let n=[];return(c=(a=jo.get(this))==null?void 0:a.queue)==null||c.forEach(u=>n.push(u)),(l=Pa.get(this))==null||l.forEach(u=>u==null?void 0:u.queue.forEach(h=>n.push(h))),n.forEach(u=>{u.reject(new y({code:I.API_CALL_ABORTED,message:s}))}),jo.delete(this),Pa.delete(this),r.apply(this,o)},t}}function $i(s){return function(i,e,t){let r=t.value,o=n=>s(...n);return t.value=function(...n){let a=Pa.get(this)||new Map,c=a.get(o(n))||new ka;return a.set(o(n),c),Pa.set(this,a),c.push({fn:r,args:n,context:this})},t}}function at(s,i){return Q((e,t)=>function(...r){let o=s;try{let n=e.apply(this,r),a=w();return sr(n)?n.then(c=>(i?b.addSuccessEvent({key:o,cost:w()-a}):b.addSuccessEvent({key:o}),c)).catch(c=>{throw b.addFailedEvent({key:o,error:c}),c}):(b.addSuccessEvent({key:o}),n)}catch(n){throw b.addFailedEvent({key:o,error:n}),n}})}var Br=class Br extends Vr{constructor(e,t){super({mediaType:e,PlayerClass:t});d(this,"isRemote",!1);d(this,"deviceId");d(this,"groupId","");d(this,"label","");d(this,"sourceTrack");d(this,"_isRecapturing",!1);d(this,"_lastRecaptureTime",0);d(this,"_onMuteTimeoutId",-1);d(this,"_encodeCheckTimeoutId",-1);d(this,"profile")}get enableEncodeFrame(){return!1}get isPublishing(){return this.state.toString()==="publishing"}get isPublished(){return this.state==="publish"}encodeFrame(e,t){throw new Error("Method not implemented.")}installTrackEvent(e){qe(e,e).add(p.MUTE,this.onTrackMuted).add(p.UNMUTE,this.onTrackUnmuted).add(p.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===p.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){ve(e)}setStateToReady(){}capture(e){return f(this,null,function*(){var t;try{let r=w();E.emit(A.LOCAL_TRACK_CAPTURE_START,{track:this});let o;e.customSource?(o=new MediaStream,o.addTrack(e.customSource)):((t=this.mediaTrack)==null||t.stop(),o=yield Im(e));let n=o.getTracks()[0];return this.sourceTrack=n,yield this.setInputMediaStreamTrack(n),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),E.emit(A.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:w()-r}),o}catch(r){throw E.emit(A.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:r}),this.log.error(`getUserMedia error observed ${r}`),r}})}setOutputMediaStreamTrack(e){var t;if(super.setOutputMediaStreamTrack(e),this.setStateToReady(),this.isPublishing||this.isPublished)return(t=this.room)==null?void 0:t.replaceTrack(this)}publish(e,t){return this.room=e,this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),t}unpublish(){this.room&&this.room.localTracks.delete(this),E.emit(A.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return f(this,null,function*(){if(this.mediaTrack&&oi){let{deviceId:e,groupId:t}=this.mediaTrack.getSettings(),{label:r}=this.mediaTrack;(yield Em({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=r,t&&(this.groupId=t),ya().then(n=>{let a=n.find(c=>c.deviceId===e);a&&this.emit("2",a)}))}})}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(e=!1){return!(!this.deviceId||!this.mediaTrack||this.kind===p.AUDIO&&!Tm(this.mediaTrack)||this.kind===p.VIDEO&&!gm(this.mediaTrack)||this._isRecapturing||e&&Ut&&xe)}onTrackMuted(){if(super.onTrackMuted(),Am(),!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<ss){setTimeout(()=>this.onTrackMuted(),ss);return}this._onMuteTimeoutId=setTimeout(()=>f(this,null,function*(){var e;if((e=this.mediaTrack)!=null&&e.muted){if((Ie||pe)&&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(He(Br.prototype,this,"onTrackEnded").call(this),!!this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<ss){setTimeout(()=>this.onTrackEnded(),ss);return}this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e){return f(this,null,function*(){var r;if(this._isRecapturing||!this._inputTrack)return;this.log.warn("recapture trying"),(r=this._inputTrack)==null||r.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let t={useExactDeviceId:!0};if(e==="user"||e==="environment")t.facingMode=e;else{let o;(this.kind==="audio"?yield nt():yield gt()).find(a=>a.deviceId===e)&&(o=e),t.deviceId=o}return this.capture(t).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),E.emit(A.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(o=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${o.message}`),this.emit("5",o),E.emit(A.LOCAL_TRACK_RECAPTURE,{track:this,error:o})})})}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=(Xo.get(t)||0)+1;if(Xo.set(t,r),r>=3){let o=e?(yield gt()).find(n=>!Xo.has(n.deviceId)):(yield nt()).find(n=>!Xo.has(n.deviceId));o&&(this.log.warn(`${t} capture fail ${r} times, change new ${o.deviceId}`),t=o.deviceId)}}return t})}stopCapture(){var e;this._inputTrack&&(this._inputTrack.stop(),this.uninstallTrackEvent(this._inputTrack)),(e=this.manager)==null||e.removeInput(this)}close(){super.close(),this.stopCapture()}};v([Te(H.INIT,"ready",{ignoreError:!0,sync:!0})],Br.prototype,"setStateToReady",1),v([Rt()],Br.prototype,"capture",1),v([Te("ready","publish",{ignoreError:!0,success(){var t,r;this.room.localTracks.add(this),E.emit(A.LOCAL_TRACK_PUBLISHED,{track:this}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),!((((r=(t=this.room)==null?void 0:t.networkQuality)==null?void 0:r.uplinkNetworkQuality)||0)>3)&&(this._encodeCheckTimeoutId=setTimeout(()=>{var n,a;if(!((((a=(n=this.room)==null?void 0:n.networkQuality)==null?void 0:a.uplinkNetworkQuality)||0)>3)&&this.isPublished&&this.isMediaTrackActive){let c=this.kind===p.AUDIO,l=this.stat.bytesSent>0;b[l?"addSuccessEvent":"addFailedEvent"]({key:c?503700:513702}),l||(b.addEnum({key:c?503701:513703,value:yo()}),re.uploadEvent({log:`stat-encode-failed-${this.kind}-${Or()||Pi()}`,userId:this.userId}),this.log.warn("encode failed"),this.emit("6",this))}},5e3))},fail(e){let t="error";if(e.cause instanceof RTCError){let r=e.cause;r.message.includes("timeout")?t="timeout":r.code===I.API_CALL_ABORTED&&(t="api-call")}this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:t,error:e.cause||e})}}),at(521714,!1)],Br.prototype,"publish",1),v([Q(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)})}),Te([],"ready",{sync:!0})],Br.prototype,"unpublish",1);var Fi=Br,Xo=new Map;E.on(A.SWITCH_DEVICE_SUCCESS,s=>{s.track.deviceId&&Xo.delete(s.track.deviceId)});var Tt=class s extends Fi{constructor(e){super(1,va);d(this,"mediaType",1);d(this,"volume",0);d(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40});d(this,"playerMuted",!0);d(this,"pipeline");d(this,"earMonitorGainNode",new De);d(this,"_output",new De);d(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0});d(this,"mixedAudioReferenceMap",new Map);this.manager=e,this.pipeline=new Ms(e),this.pipeline.gain.pipeTo(this.earMonitorGainNode).pipeTo(this._output),this.pipeline.gain.pipeTo(this.player.pipeline.volumeMeter),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this)}get dbVolume(){return Ur.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}setInputMediaStreamTrack(e){return f(this,null,function*(){let t=this.trackSettings||{};b.addEnum({key:501701,value:t.channelCount||0,useUV:!1}),b.addEnum({key:501702,value:t.sampleRate||0,useUV:!1}),b.addEnum({key:502700,value:0});let{sampleRate:r,channelCount:o}=t;this._log.info(`local audio track input ${JSON.stringify({sampleRate:r,channelCount:o})}`),this.pipeline.source.channelCount=o||1,this.pipeline.replaceSource(e),yield He(s.prototype,this,"setInputMediaStreamTrack").call(this,e),this.updatePlayingState(!!e)})}capture({deviceId:e,customSource:t,useExactDeviceId:r=!0,retryWhenExactFailed:o=!0}){return super.capture({video:!1,audio:!0,microphoneId:e,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:r,retryWhenExactFailed:o,customSource:t})}switchDevice(e){return f(this,null,function*(){if(this.mediaTrack){if(this.deviceId===e)if(e===Ar){if(yield ul(this.groupId,this.label))return}else return;try{this.log.info(`switchDevice audio to: ${e}`),this.mediaTrack&&this.mediaTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0,retryWhenExactFailed:!1}),E.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(){Le&&!Le.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&Le.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return f(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current microphone is lost: ${JSON.stringify(e)}`),Ae(this.userId,{eventId:2003,param1:6,streamType:1});let t=yield nt();t[0]?this.recapture(t[0].deviceId):Le.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.log.warn(`microphone added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)}update3A(o){return f(this,arguments,function*({echoCancellation:e,noiseSuppression:t,autoGainControl:r}){let n=this.sourceTrack||this.mediaTrack;if(!n)return;let a=n.getConstraints(),c=!1;!T(e)&&e!==this.profile.echoCancellation&&(this.profile.echoCancellation=e,a.echoCancellation=e,c=!0),!T(t)&&t!==this.profile.noiseSuppression&&(this.profile.noiseSuppression=t,a.noiseSuppression=t,c=!0),!T(r)&&r!==this.profile.autoGainControl&&(this.profile.autoGainControl=r,a.autoGainControl=r,c=!0),c&&(ae||xe?yield n.applyConstraints(a).catch(l=>this._log.warn("update3A failed: ",l)):this.deviceId&&(yield this.recapture(this.deviceId)))})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&b.addEnum({key:502700,value:2})}setAudioVolume(e){super.setAudioVolume(0),Ie&&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||xe||Ie)return;let t=this.sourceTrack.getConstraints();return t.echoCancellation=e,this.sourceTrack.applyConstraints(t).catch(r=>this._log.warn(`${e?"enable":"disable"} AEC failed `,r))}addDenoiser(e){var t;if(lt<=92&&((t=this.trackSettings)==null?void 0:t.sampleRate)!==48e3){this._log.warn("denoiser only support sampleRate 48000 before chrome 93");return}b.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=Jo(e),o=new De,n=Ee().createGain();n.gain.value=1;let a=new De;o.pipeTo(a).pipeTo(this.pipeline.mixNode),o.setNode(r),a.setNode(n),this.mixedAudioReferenceMap.set(t,[o,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,o]=this.mixedAudioReferenceMap.get(e)||[];o!=null&&o.node&&(o.node.gain.value=t/100,this.log.info(`setAudioReferenceVolume() => ${e} ${o.node.gain.value}`))}addAudioProcessor(e,t,r,o){this.pipeline.silentNode.setNode(r),this.pipeline.mixNode.setNode(t),this.pipeline.aec.setNode(e),this.enableTrackAEC(!1)}removeDenoiser(e){this.pipeline.denoiser.node===e&&(this.pipeline.denoiser.deleteNode(),this.enableTrackANS(!0))}removeAudioProcessor(e,t,r,o){this.pipeline.aec.node===e&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode(),this.enableTrackAEC(!0))}close(){this.mixedAudioReferenceMap.forEach(([e,t])=>{e.deleteNode(),t.deleteNode()}),this.mixedAudioReferenceMap.clear(),this.pipeline.remove(),this.earMonitorGainNode.deleteNode(),this._output.deleteNode(),Le.off("audioInputAdded",this.handleMicrophoneAdded,this),Le.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}recapture(e){return f(this,null,function*(){try{yield He(s.prototype,this,"recapture").call(this,e)}catch(t){let r=(yield nt()).find(o=>o.deviceId!==e);if(r)yield He(s.prototype,this,"recapture").call(this,r.deviceId);else throw t}})}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduceRight((t,r)=>r?r({frame:t}):t,e):e}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}};var Hi=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 o=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=o}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 o=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=o}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 o=6;o<this.dataView.buffer.byteLength;o++){let n=this.dataView.getUint8(o);if(e++,n===255)i+=255;else{i+=n;break}}let t=new ArrayBuffer(i),r=new DataView(t);for(let o=0;o<t.byteLength;o++,e++)r.setInt8(o,this.dataView.getInt8(e));return r}};var La=class{constructor(){d(this,"_seiMessageList",[]);d(this,"_smallSeiMessageList",[]);d(this,"_seiPayloadType",243)}encodeSEINalu(i){let e=i.byteLength,t=parseInt(String(e/255),10),r=e%255,o=[];o.push(0,0,0,1,6,this._seiPayloadType);for(let a=0;a<t;a++)o.push(255);o.push(r);let n=new DataView(i);return o.push(...new Uint8Array(n.buffer)),o.push(128),new Hi(new DataView(new Uint8Array(o).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 o=0;o<i.byteLength;o++)switch(r.getUint8(o)){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 o=9-this.getNaluCount(i.data);if(o<=0)return 0;let n=t.splice(0,o).reverse().map(this.encodeSEINalu.bind(this)),a=n.reduce((m,g)=>m+g.dataView.byteLength,0),c=new ArrayBuffer(a+i.data.byteLength),l=new DataView(c),u=new DataView(i.data),h=0;for(let m=0;m<n.length;m++)for(let g=0;g<n[m].dataView.byteLength;g++)l.setInt8(h++,n[m].dataView.getInt8(g));for(let m=0;m<i.data.byteLength;m++)l.setInt8(h++,u.getInt8(m));return i.data=c,n.length}return 0}};var Fr=class Fr extends Fi{constructor(e,t=4){super(t,ft);d(this,"profile",N({},er));d(this,"avoidCropping",!1);d(this,"_scaleResolutionDownBy");d(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0});d(this,"small");d(this,"isNeedToSetBandwidth");d(this,"muteImage");d(this,"manager");d(this,"_seiCodec",new La);this.manager=e;let r=()=>{this.isAllowed2k4k(this.profile)?this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1}):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),this.setProfile(L(N({},this.profile),{width:1920,height:1080})),this.applyProfile())};this.on("input-media-track-changed",r),this.on("publish",r),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(!(!oi||!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"}setMute(e){return f(this,null,function*(){var t,r,o;if(ee(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}),this.muteImage=e,He(Fr.prototype,this,"setMute").call(this,!1)}else this.muteImage&&(yield(o=this.manager)==null?void 0:o.deleteWatermark("mute"),this.muteImage=void 0),He(Fr.prototype,this,"setMute").call(this,e)})}capture({deviceId:e,facingMode:t,useExactDeviceId:r=!0,customSource:o,retryWhenExactFailed:n=!0}){return super.capture({audio:!1,video:!0,facingMode:t||this.facingMode,cameraId:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:r,retryWhenExactFailed:n,customSource:o})}setProfile(e){let t=this.fallbackProfile(e);t.bitrate&&(this.isNeedToSetBandwidth=t.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile)?super.setProfile(t):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),super.setProfile(L(N({},this.profile),{width:1920,height:1080})))}applyProfile(){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,o=this.settings,n=o.height!==this.profile.height||o.width!==this.profile.width||o.frameRate!==this.profile.frameRate;if(n&&(ut===16&&this.deviceId?yield this.recapture(this.deviceId):(yield(a=this.sourceTrack||this.mediaTrack)==null?void 0:a.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}),this.manager&&this.manager.changeInput(this)),this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1})),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth){this.isNeedToSetBandwidth=!1;let{width:c=0,height:l=0}=(this.sourceTrack||this.mediaTrack).getSettings(),u=c*l;if(n&&u&&r&&u===r){this.log.warn("set bandwidth failed: resolution is not changed");return}return this.room.setBandWidth({bandwidth:this.profile.bitrate,type:p.VIDEO,videoType:p.BIG})}})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},t=this.sourceTrack||this.mediaTrack;return oi&&t&&Object.assign(e,t.getSettings()),e}get scaleResolutionDownBy(){return this._scaleResolutionDownBy?this._scaleResolutionDownBy:ls(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))return;let t={useExactDeviceId:!0,retryWhenExactFailed:!1};e==="user"||e==="environment"?t.facingMode=e:t.deviceId=e,this.mediaTrack.stop(),yield this.capture(t),E.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}})}updateSmallConfig(e){var r,o;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&&((o=this.room)==null||o.enableSmall(!0)),this.log.info("update small stream config success")}fallbackProfile(e,t=!1){let r=e.width>e.height,o=N({},e);return e.width*e.height<=160*120&&pe&&Ze&&(this.log.warn(`${t?"small ":""}resolution is ${e.width}*${e.height}, fallback to 240*180 for android chrome`),o.width=r?240:180,o.height=r?180:240,o.bitrate=Math.max(e.bitrate,150)),e.width*e.height>1280*720&&Sd&&(o.width=r?1280:720,o.height=r?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),!t&&this.avoidCropping&&(Ze||ae)&&!Ad()&&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}`)),o}stopSmall(){var e,t;this.small&&(delete this.small,(e=this.manager)==null||e.update(),(t=this.room)==null||t.enableSmall(!1))}listenDeviceChange(){Le&&!Le.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&Le.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return f(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current camera is lost: ${JSON.stringify(e)}`),Ae(this.userId,{eventId:2003,param1:7,streamType:2});let t=yield gt();t[0]?this.recapture(t[0].deviceId):Le.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return f(this,null,function*(){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((o,n)=>n?n({frame:o,mediaType:r}):o,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(){Le.off("videoInputAdded",this.handleCameraAdded,this),Le.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return f(this,null,function*(){try{yield He(Fr.prototype,this,"recapture").call(this,e)}catch(t){let r=(yield gt()).find(o=>o.deviceId!==e);if(r)yield He(Fr.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))}};v([et(function(e){this.setContentHint(e.contentHint||"motion")})],Fr.prototype,"capture",1);var je=Fr;var wa=bo();if(typeof navigator!="undefined"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:wa,exposeOrigin:!0,permittedOrigins:["*"]})}catch(s){}var ng=function(s){return f(this,null,function*(){let i=null,e=dg(s);C.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let t=yield navigator.mediaDevices.getDisplayMedia(e);s.systemAudio&&t.getAudioTracks().length===0&&(Is&&lt<74||xe||ae)&&C.warn("Your browser not support capture system audio");let r=t.getVideoTracks()[0];if(r){if(s.frameRate)try{yield r.applyConstraints({frameRate:{min:s.frameRate,ideal:s.frameRate},width:s.width,height:s.height})}catch(o){C.warn(`screen applyConstraints failed: ${o}`)}s.captureElement&&(yield ag(r,s.captureElement))}if(s.audio){let o=cg(s);C.info(`getUserMedia with constraints: ${JSON.stringify(o)}`),i=yield navigator.mediaDevices.getUserMedia(o),t.addTrack(i.getAudioTracks()[0])}return t})};function ag(s,i){return f(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&ne(s.cropTo))try{if(!(((e=s.getCaptureHandle())==null?void 0:e.handle)===wa))return;let r=yield CropTarget.fromElement(i);yield s.cropTo(r)}catch(t){C.warn(`cropTo target failed ${t}`)}})}function cg(s){let i={echoCancellation:s.echoCancellation,autoGainControl:s.autoGainControl,noiseSuppression:s.noiseSuppression,sampleRate:s.sampleRate,channelCount:s.channelCount};return T(s.microphoneId)||(i.deviceId=s.microphoneId),{audio:i,video:!1}}function dg(s){let i={preferCurrentTab:s.preferDisplaySurface==="current-tab"||!!s.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:xe?{max:s.width}:{ideal:s.width,max:s.width},height:xe?{max:s.height}:{ideal:s.height,max:s.height},frameRate:s.frameRate,displaySurface:s.preferDisplaySurface||"monitor"};if(i.video=e,s.systemAudio){let{echoCancellation:t=!0,noiseSuppression:r=!1,autoGainControl:o=!1}=s;i.audio={echoCancellation:t,noiseSuppression:r,autoGainControl:o,sampleRate:48e3}}return i}var ym=ng;var ct=class extends je{constructor(e){super(e,2);d(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600});d(this,"objectFit","contain");d(this,"isScreen",!0);this._log.id=`s-${this._log.id}`}get isShareCurrentTab(){var e,t;try{return wa===((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:o,audioTrack:n,videoTrack:a,captureElement:c,preferDisplaySurface:l}){try{let h;return a||n?(h=new MediaStream,a&&h.addTrack(a),n&&h.addTrack(n)):h=yield ym({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:t,echoCancellation:r,noiseSuppression:o,captureElement:c,preferDisplaySurface:l}),yield this.setInputMediaStreamTrack(h.getVideoTracks()[0]),h}catch(h){throw this.log.error(`getDisplayMedia error observed ${h}`),h instanceof y?h:new y({code:I.INITIALIZE_FAILED,name:h.name,message:h.message})}})}switchDevice(e){return f(this,null,function*(){throw new Error("Method not implemented.")})}};v([et(function(e){this.setContentHint(e.contentHint||"detail")})],ct.prototype,"capture",1);var hi=class extends Tt{constructor(i){super(i),this._log.id=`s-${this._log.id}`}addAudioProcessor(i,e,t,r){this.pipeline.silentNode.setNode(t),this.pipeline.mixNode.setNode(e),this.pipeline.aec.setNode(r),this.enableTrackAEC(!1)}removeAudioProcessor(i,e,t,r){this.pipeline.aec.node===r&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode(),this.enableTrackAEC(!0))}};var lg='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}});',ml;function zo(s,i=48e3,e=1,t){return f(this,null,function*(){let r=Ee("dump");ml||(ml=Bi(r,URL.createObjectURL(new Blob([lg],{type:"application/javascript"})))),yield ml;let o=r.sampleRate,n=new AudioWorkletNode(r,"dumper",{numberOfInputs:s.length,numberOfOutputs:0,processorOptions:{sourceSampleRate:o,targetSampleRate:i}});return n.channelCountMode="explicit",n.channelCount=e,t&&n.port.postMessage({port:t},[t]),s.forEach((a,c)=>a.connect(n,0,c)),new ReadableStream({start(a){n.port.onmessage=c=>{a.enqueue(c.data)}},cancel(){s.forEach(a=>a.disconnect(n)),n.port.close()}})})}var Ua=class extends Aa{constructor(e){super();this.room=e;d(this,"_localAudioTrack");d(this,"_localScreenAudioTrack");d(this,"log",C.createLogger({id:"am"}));d(this,"denoiser");d(this,"voiceChanger");d(this,"mixChangedDebounce");d(this,"audioProcessor");d(this,"encodePipeline",[]);d(this,"decodePipeline",[]);d(this,"getPCMAbortCtrlMap",new Map);d(this,"audioFrameEventConfigMap",new Map);d(this,"audioReferenceMap",new Map);d(this,"isLocalAudioNeedAudioProcess",!1);d(this,"isScreenAudioNeedAudioProcess",!1);e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.installEvent()}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 o=new AbortController,n=[],a=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),o.abort("timeout")},e*1e3),c=()=>{for(let m=0;m<r.length;m++){let g=URL.createObjectURL(new Blob(n[m])),D=document.createElement("a");D.href=g,D.download=`${r[m]}.pcm`,D.style.display="none",document.body.appendChild(D),D.click(),URL.revokeObjectURL(g),D.remove()}clearTimeout(a),o.abort("download")},l=zo(t).then(m=>m.pipeTo(new WritableStream({write(g){g.forEach((D,_)=>n[_]=n[_]?n[_].concat(D[0]):[D[0]])}}),o).catch(g=>c));return{then:l.then.bind(l),download:c}}getPCM(e,t){var O,K,G;if(T(WritableStream)){this.log.warn("getPCM failed: browser not support WritableStream");return}let{enable:r,sampleRate:o=48e3,channelCount:n=1,port:a}=(t===""?this.audioFrameEventConfigMap.get(""):this.audioFrameEventConfigMap.get(t)||this.audioFrameEventConfigMap.get("*"))||{};if(!r)return;this.log.info(`getPCM ${t||"local"}`);let c=Math.floor(o*.04),l=new Float32Array(c),u=new Float32Array(c),h,m,g=0,D=new AbortController,_=t===""?(O=this._localAudioTrack)==null?void 0:O.mediaTrack:(G=(K=this.room)==null?void 0:K.remotePublishedUserMap.get(t))==null?void 0:G.remoteAudioTrack.mediaTrack;if(!_){this.log.info(`getPCM failed: ${t||"local"} has no audio track`);return}let S=Ee().createMediaStreamSource(new MediaStream([_]));return zo([S],o,n,a).then(Z=>Z.pipeTo(new WritableStream({write(_e){_e[0][0]&&(g+_e[0][0].length>c?(l.set(_e[0][0].subarray(0,c-g),g),h=_e[0][0].subarray(c-g),_e[0][1]&&(u.set(_e[0][1].subarray(0,c-g),g),m=_e[0][1].subarray(c-g)),g+=c-g):(h&&(l.set(h,g),g+=h.length,h=void 0),m&&(u.set(m,g),m=void 0),l.set(_e[0][0],g),_e[0][1]&&u.set(_e[0][1],g),g+=_e[0][0].length),g>=c&&(g=0,e({userId:t,sampleRate:o,channelCount:n,data:n===1?l:[l,u]}),l=new Float32Array(c),u=new Float32Array(c)))}}),D).catch(_e=>this.log.warn(`stop getPCM reason:${_e}`))),D}get hasScreenAudioTrack(){return!T(this._localScreenAudioTrack)}get hasAudioTrack(){return!T(this._localAudioTrack)}changeInput(e){if(e instanceof hi)return this._localScreenAudioTrack=e,this.isScreenAudioNeedAudioProcess&&this.audioProcessor&&(e.addAudioProcessor(...this.audioProcessor),this.audioReferenceMap.forEach((t,r)=>{e.mixAudioReference(t,r)})),e.pipeline.connect(),this.mixOnChange();if(e instanceof Tt)return this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),this.isLocalAudioNeedAudioProcess&&this.audioProcessor&&(e.addAudioProcessor(...this.audioProcessor),this.audioReferenceMap.forEach((t,r)=>{e.mixAudioReference(t,r)})),e.pipeline.connect(),this.mixOnChange();if(e instanceof Gt)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 hi?delete this._localScreenAudioTrack:e instanceof Tt?delete this._localAudioTrack:e instanceof Gt}addDenoiser(e){var t;this.denoiser=e,(t=this._localAudioTrack)==null||t.addDenoiser(e)}addAudioProcessor(e,t,r,o){var n;this.audioProcessor=[e,t,r,o],this.isLocalAudioNeedAudioProcess&&this._localAudioTrack&&(this._localAudioTrack.addAudioProcessor(...this.audioProcessor),this.audioReferenceMap.forEach((a,c)=>{var l;(l=this._localAudioTrack)==null||l.mixAudioReference(a,c)})),this.isScreenAudioNeedAudioProcess&&this._localScreenAudioTrack&&((n=this._localScreenAudioTrack)==null||n.addAudioProcessor(...this.audioProcessor),this.audioReferenceMap.forEach((a,c)=>{var l;(l=this._localScreenAudioTrack)==null||l.mixAudioReference(a,c)}))}removeDenoiser(e){var t;delete this.denoiser,(t=this._localAudioTrack)==null||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,r,o){var n;delete this.audioProcessor,(n=this._localAudioTrack)==null||n.removeAudioProcessor(e,t,r,o)}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 o;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)&&((o=this._localAudioTrack)==null||o.on("input-media-track-changed",()=>{let n=this.getPCMAbortCtrlMap.get(t);n&&(n.abort("inputMediaTrackChanged"),n=this.getPCM(a=>{var c;(c=this.room)==null||c.emit("audio-frame",a)},""),this.getPCMAbortCtrlMap.set(t,n))}))}handleLocalTrackStopped({room:e,userId:t}){if(e!==this.room)return;let r=this.getPCMAbortCtrlMap.get(t);r&&(r.abort("stopLocalAudio"),this.getPCMAbortCtrlMap.delete(t))}handleRemoteTrackStarted({room:e,userId:t}){if(e===this.room&&!this.getPCMAbortCtrlMap.get(t)){let r=this.room.audioManager.getPCM(o=>{var n;(n=this.room)==null||n.emit("audio-frame",o)},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(){E.on("113",this.handleLocalTrackStarted,this),E.on("114",this.handleLocalTrackStopped,this),E.on("115",this.handleRemoteTrackStarted,this),E.on("116",this.handleRemoteTrackStopped,this)}uninstallEvent(){E.off("113",this.handleLocalTrackStarted),E.off("114",this.handleLocalTrackStopped),E.off("115",this.handleRemoteTrackStarted),E.off("116",this.handleRemoteTrackStopped)}updateAudioReference({type:e,audioReference:t,refId:r,volume:o}){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(o))return;this.setAudioReferenceVolume(r,o)}}};function Va(s=30,i=2){return Q((e,t)=>function(...r){return new Promise((o,n)=>{let a=setTimeout(()=>{let c=new y({code:I.API_CALL_TIMEOUT,message:`checkPendingPromise ${t}() timeout ${s}s`});C.warn(c),i===2?n(c):i===1&&o()},s*1e3);e.apply(this,r).then(o,n).finally(()=>{clearTimeout(a)})})})}var Zl={};Si(Zl,{Events:()=>Ce,Inspect:()=>Ct,LastSink:()=>$r,Sink:()=>W,Subscribe:()=>Hr,TimeoutError:()=>Qo,audit:()=>Jg,bindCallback:()=>Og,bindNodeCallback:()=>Mg,buffer:()=>Eg,bufferCount:()=>Tg,bufferTime:()=>lT,call:()=>bm,catchError:()=>Xl,combineLatest:()=>vm,concat:()=>mg,concatMap:()=>iT,concatMapTo:()=>rT,count:()=>xg,create:()=>ie,debounce:()=>qg,debounceTime:()=>jg,defer:()=>Dm,delay:()=>uT,deliver:()=>j,dispose:()=>Ba,elementAt:()=>Xg,empty:()=>Ko,every:()=>Kg,exhaustMap:()=>nT,exhaustMapTo:()=>aT,filter:()=>mi,find:()=>zg,findIndex:()=>Qg,first:()=>Yg,fromAnimationFrame:()=>vg,fromArray:()=>Ag,fromEvent:()=>he,fromEventPattern:()=>Rg,fromFetch:()=>Cg,fromIterable:()=>yg,fromPromise:()=>km,fromReadableStream:()=>Ng,fromReader:()=>bg,groupBy:()=>cT,identity:()=>ug,ignoreElements:()=>Vg,iif:()=>fg,inspect:()=>Nm,interval:()=>Sl,last:()=>Zg,map:()=>en,mapTo:()=>tT,max:()=>Lg,merge:()=>Tl,mergeMap:()=>sT,mergeMapTo:()=>oT,min:()=>wg,never:()=>kg,nothing:()=>de,of:()=>Ig,pairwise:()=>eT,pipe:()=>le,race:()=>El,range:()=>Dg,reduce:()=>Il,retry:()=>fT,scan:()=>jl,share:()=>Gi,shareReplay:()=>pg,skip:()=>Fg,skipUntil:()=>$g,skipWhile:()=>Wa,startWith:()=>Yo,subject:()=>tt,subscribe:()=>be,sum:()=>Ug,switchMap:()=>Ls,switchMapTo:()=>Wr,take:()=>Wi,takeLast:()=>Bg,takeUntil:()=>Be,takeWhile:()=>Pm,tap:()=>Yl,throttle:()=>Gg,throwError:()=>Pg,timeInterval:()=>dT,timeout:()=>pT,timer:()=>Zo,toPromise:()=>hT,toReadableStream:()=>mT,withLatestFrom:()=>gg,zip:()=>_g});function de(...s){}var bm=s=>s(),ug=s=>s;function Ba(){this.dispose()}var Nm=()=>typeof __FASTRX_DEVTOOLS__!="undefined",hg=1,Ct=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(i){let e=new pl(i,this,this.streamId++);return Ce.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},$r=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=de,this.error=de,this.next=de,this.dispose=de,this.subscribe=de,this.doDefer()}subscribe(i){return i instanceof Ct?i.subscribe(this):i(this),this}get bindSubscribe(){return i=>this.subscribe(i)}doDefer(){this.defers.forEach(bm),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}},W=class extends $r{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)}},Hr=class extends $r{constructor(i,e=de,t=de,r=de){if(super(),this._next=e,this._error=t,this._complete=r,this.then=de,i instanceof Ct){let o={toString:()=>"subscribe",id:0,source:i};this.defer(()=>{Ce.defer(o,0)}),Ce.create(o),Ce.pipe(o),this.sourceId=o.id,this.subscribe(i),Ce.subscribe({id:o.id,end:!0}),e==de?this._next=n=>Ce.next(o,0,n):this.next=n=>{Ce.next(o,0,n),e(n)},r==de?this._complete=()=>Ce.complete(o,0):this.complete=()=>{this.dispose(),Ce.complete(o,0),r()},t==de?this._error=n=>Ce.complete(o,0,n):this.error=n=>{this.dispose(),Ce.complete(o,0,n),t()}}else this.subscribe(i)}next(i){this._next(i)}complete(){this.dispose(),this._complete()}error(i){this.dispose(),this._error(i)}};function le(s,...i){return i.reduce((e,t)=>t(e),s)}function ie(s,i,e){if(Nm()){let t=Object.defineProperties(Object.setPrototypeOf(s,Ct.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}});Ce.create(t);for(let r=0;r<e.length;r++){let o=e[r];typeof o=="function"&&o instanceof Ct&&Ce.addSource(t,o)}return t}return s}function j(s,i){return function(...e){return t=>{if(t instanceof Ct){let r=ie(o=>{let n=new s(o,...e);n.sourceId=r.id,n.subscribe(t)},i,arguments);return r.source=t,Ce.pipe(r),r}else return r=>t(new s(r,...e))}}}function ur(s,i){window.postMessage({source:"fastrx-devtools-backend",payload:{event:s,payload:i}})}var pl=class extends W{constructor(i,e,t){super(i),this.source=e,this.id=t,this.sourceId=i.sourceId,this.defer(()=>{Ce.defer(this.source,this.id)})}next(i){Ce.next(this.source,this.id,i),this.sink.next(i)}complete(){Ce.complete(this.source,this.id),this.sink.complete()}error(i){Ce.complete(this.source,this.id,i),this.sink.error(i)}},Ce={addSource(s,i){ur("addSource",{id:s.id,name:s.toString(),source:{id:i.id,name:i.toString()}})},next(s,i,e){ur("next",{id:s.id,streamId:i,data:e&&e.toString()})},subscribe({id:s,end:i},e){ur("subscribe",{id:s,end:i,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(s,i,e){ur("complete",{id:s.id,streamId:i,err:e?e.toString():null})},defer(s,i){ur("defer",{id:s.id,streamId:i})},pipe(s){ur("pipe",{name:s.toString(),id:s.id,source:{id:s.source.id,name:s.source.toString()}})},update(s){ur("update",{id:s.id,name:s.toString()})},create(s){s.id||(s.id=hg++),ur("create",{name:s.toString(),id:s.id})}},Qo=class extends Error{constructor(i){super(`timeout after ${i}ms`),this.timeout=i}};var Fa=class extends $r{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 Gi(){return s=>{let i=new Fa(s);if(s instanceof Ct){let e=ie(t=>{i.add(t)},"share",arguments);return i.sourceId=e.id,e.source=s,Ce.pipe(e),e}return ie(i.add.bind(i),"share",arguments)}}function Tl(...s){return ie(i=>{let e=new W(i),t=s.length;e.complete=()=>{--t===0&&i.complete()},s.forEach(e.bindSubscribe)},"merge",arguments)}function El(...s){return ie(i=>{let e=new Map;s.forEach(t=>{let r=new W(i);e.set(t,r),r.complete=()=>{e.delete(t),e.size===0?i.complete():r.dispose()},r.next=o=>{e.delete(t),e.forEach(n=>n.dispose()),r.resetNext(),r.resetComplete(),r.next(o)}}),s.forEach(t=>e.get(t).subscribe(t))},"race",arguments)}function mg(...s){return ie(i=>{let e=0,t=s.length,r=new W(i);r.complete=()=>{e<t&&!r.disposed?(r.doDefer(),r.subscribe(s[e++])):i.complete()},r.complete()},"concat",arguments)}function pg(s){return i=>{let e=new Fa(i),t=[];return e.next=function(r){t.push(r),t.length>s&&t.shift(),this.sinks.forEach(o=>o.next(r))},ie(r=>{r.defer(()=>e.remove(r)),t.forEach(o=>r.next(o)),e.add(r)},"shareReplay",arguments)}}function fg(s,i,e){return ie(t=>s()?i(t):e(t),"iif",arguments)}function vm(...s){return ie(i=>{let e=s.length,t=e,r=e,o=new Array(e),n=()=>{--r===0&&i.complete()},a=(c,l)=>{let u=new W(i);u.next=h=>{--t===0?(u.next=m=>{o[l]=m,i.next(o)},u.next(h)):o[l]=h},u.complete=n,u.subscribe(c)};s.forEach(a)},"combineLatest",arguments)}function _g(...s){return ie(i=>{let e=s.length,t=e,r=new Array(e),o=()=>{--t===0&&i.complete()},n=(a,c)=>{let l=new W(i),u=[];r[c]=u,l.next=h=>{u.push(h),r.every(m=>m.length)&&i.next(r.map(m=>m.shift()))},l.complete=o,l.subscribe(a)};s.forEach(n)},"zip",arguments)}function Yo(...s){return i=>ie((e,t=0,r=s.length)=>{for(;t<r&&!e.disposed;)e.next(s[t++]);e.disposed||e.subscribe(i)},"startWith",arguments)}var fl=class extends W{constructor(i,...e){super(i);let t=new W(this.sink);t.next=r=>this.buffer=r,t.complete=de,t.subscribe(vm(...e))}next(i){this.buffer&&this.sink.next([i,...this.buffer])}},gg=j(fl,"withLatestFrom"),_l=class extends W{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()}},Tg=j(_l,"bufferCount"),gl=class extends W{constructor(i,e){super(i),this.buffer=[];let t=new W(i);t.next=r=>{i.next(this.buffer),this.buffer=[]},t.complete=de,t.subscribe(e)}next(i){this.buffer.push(i)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},Eg=j(gl,"buffer");var Sg=function(s,i,e,t){function r(o){return o instanceof e?o:new e(function(n){n(o)})}return new(e||(e=Promise))(function(o,n){function a(u){try{l(t.next(u))}catch(h){n(h)}}function c(u){try{l(t.throw(u))}catch(h){n(h)}}function l(u){u.done?o(u.value):r(u.value).then(a,c)}l((t=t.apply(s,i||[])).next())})};function tt(s){let i=arguments,e=Gi()(ie(t=>{e.next=r=>t.next(r),e.complete=()=>t.complete(),e.error=r=>t.error(r),s&&t.subscribe(s)},"subject",i));return e.next=de,e.complete=de,e.error=de,e}function Dm(s){return ie(i=>i.subscribe(s()),"defer",arguments)}var Om=s=>i=>{setTimeout(()=>s(i))},Mm=s=>Om(i=>{for(let e=0;!i.disposed&&e<s.length;e++)i.next(s[e]);i.complete()});function Ig(...s){return ie(Mm(s),"of",arguments)}function Ag(s){return ie(Mm(s),"fromArray",arguments)}function Sl(s){return ie(i=>{let e=0,t=setInterval(()=>i.next(e++),s);return i.defer(()=>{clearInterval(t)}),"interval"},"interval",arguments)}function Zo(s,i){return ie(e=>{let t=0,r=setTimeout(()=>{if(e.removeDefer(o),e.next(t++),i){let n=setInterval(()=>e.next(t++),i);e.defer(()=>{clearInterval(n)})}else e.complete()},s),o=()=>{clearTimeout(r)};e.defer(o)},"timer",arguments)}function $a(s,i){return e=>{let t=r=>e.next(r);e.defer(()=>i(t)),s(t)}}function Rg(s,i){return ie($a(s,i),"fromEventPattern",arguments)}function he(s,i){if("on"in s&&"off"in s)return ie($a(e=>s.on(i,e),e=>s.off(i,e)),"fromEvent",arguments);if("addListener"in s&&"removeListener"in s)return ie($a(e=>s.addListener(i,e),e=>s.removeListener(i,e)),"fromEvent",arguments);if("addEventListener"in s)return ie($a(e=>s.addEventListener(i,e),e=>s.removeEventListener(i,e)),"fromEvent",arguments);throw"target is not a EventDispachter"}function km(s){return ie(i=>{s.then(i.next.bind(i),i.error.bind(i))},"fromPromise",arguments)}function Cg(s,i){return ie(Dm(()=>km(fetch(s,i))),"fromFetch",arguments)}function yg(s){return ie(Om(i=>{try{for(let e of s){if(i.disposed)return;i.next(e)}i.complete()}catch(e){i.error(e)}}),"fromIterable",arguments)}function bg(s){let i=e=>Sg(this,void 0,void 0,function*(){if(e.disposed)return;let{done:t,value:r}=yield s.read();if(t){e.complete();return}else e.next(r),i(e)});return ie(e=>{i(e)},"fromReader",arguments)}function Ng(s){return ie(i=>{let e=new AbortController,t=e.signal;i.defer(()=>e.abort("cancelled")),s.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 vg(){return ie(s=>{let i=requestAnimationFrame(function e(t){s.disposed||(s.next(t),i=requestAnimationFrame(e))});s.defer(()=>cancelAnimationFrame(i))},"fromAnimationFrame",arguments)}function Dg(s,i){return ie((e,t=s,r=i+s)=>{for(;t<r&&!e.disposed;)e.next(t++);return e.complete(),"range"},"range",arguments)}function Og(s,i,...e){return ie(t=>{let r=e.concat(o=>(t.next(o),t.complete()));s.apply(i,r)},"bindCallback",arguments)}function Mg(s,i,...e){return ie(t=>{let r=e.concat((o,n)=>o?t.error(o):(t.next(n),t.complete()));s.apply(i,r)},"bindNodeCallback",arguments)}function kg(){return ie(()=>{},"never",arguments)}function Pg(s){return ie(i=>i.error(s),"throwError",arguments)}function Ko(){return ie(s=>s.complete(),"empty",arguments)}var Gr=class extends W{constructor(i,e,t){super(i),this.f=e;let r=()=>{this.sink.next(this.acc),this.sink.complete()};typeof t=="undefined"?this.next=o=>{this.acc=o,this.complete=r,this.resetNext()}:(this.acc=t,this.complete=r)}next(i){this.acc=this.f(this.acc,i)}},Il=j(Gr,"reduce"),xg=s=>j(Gr,"count")((i,e)=>s(e)?i+1:i,0),Lg=()=>j(Gr,"max")(Math.max),wg=()=>j(Gr,"min")(Math.min),Ug=()=>j(Gr,"sum")((s,i)=>s+i,0);var Al=class extends W{constructor(i,e,t){super(i),this.filter=e,this.thisArg=t}next(i){this.filter.call(this.thisArg,i)&&this.sink.next(i)}},mi=j(Al,"filter"),Rl=class extends W{next(i){}},Vg=j(Rl,"ignoreElements"),Cl=class extends W{constructor(i,e){super(i),this.count=e}next(i){this.sink.next(i),--this.count===0&&this.complete()}},Wi=j(Cl,"take"),yl=class extends W{constructor(i,e){super(i);let t=new W(i);t.next=()=>i.complete(),t.complete=Ba,t.subscribe(e)}},Be=j(yl,"takeUntil"),bl=class extends W{constructor(i,e){super(i),this.f=e}next(i){this.f(i)?this.sink.next(i):this.complete()}},Pm=j(bl,"takeWhile"),Bg=s=>Il((i,e)=>(i.push(e),i.length>s&&i.shift(),i),[]),Nl=class extends W{constructor(i,e){super(i),this.count=e}next(i){--this.count===0&&(this.next=super.next)}},Fg=j(Nl,"skip"),vl=class extends W{constructor(i,e){super(i),i.next=de;let t=new W(i);t.next=()=>{t.dispose(),i.resetNext()},t.complete=Ba,t.subscribe(e)}},$g=j(vl,"skipUntil"),Dl=class extends W{constructor(i,e){super(i),this.f=e}next(i){this.f(i)||(this.next=super.next,this.next(i))}},Wa=j(Dl,"skipWhile"),Hg={leading:!0,trailing:!1},Ol=class extends W{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)}},Ha=class extends W{constructor(i,e,t=Hg){super(i),this.durationSelector=e,this.config=t,this._throttle=new Ol(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=de,this._throttle.complete(),super.complete()}},Gg=j(Ha,"throttle"),Wg={leading:!1,trailing:!0},Jg=s=>j(Ha,"audit")(s,Wg),Ml=class extends W{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},Ga=class extends W{constructor(i,e){super(i),this.durationSelector=e,this._debounce=new Ml(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()}},qg=j(Ga,"debounce"),jg=s=>j(Ga,"debounceTime")(i=>Zo(s)),kl=class extends W{constructor(i,e,t){super(i),this.count=e,this.defaultValue=t}next(i){this.count--===0&&(this.defaultValue=i,this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("not enough elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},Xg=j(kl,"elementAt"),zg=s=>i=>Wi(1)(Wa(e=>!s(e))(i)),Pl=class extends W{constructor(i,e){super(i),this.f=e,this.i=0}next(i){this.f(i)?(this.sink.next(this.i++),this.complete()):++this.i}},Qg=j(Pl,"findIndex"),xl=class extends W{constructor(i,e,t){super(i),this.f=e,this.defaultValue=t,this.index=0}next(i){(!this.f||this.f(i,this.index++))&&(this.defaultValue=i,this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},Yg=j(xl,"first"),Ll=class extends W{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()}},Zg=j(Ll,"last"),wl=class extends W{constructor(i,e){super(i),this.predicate=e,this.index=0}next(i){this.predicate(i,this.index++)?this.result=!0:(this.result=!1,this.complete())}complete(){if(this.result===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.result);super.complete()}},Kg=j(wl,"every");var Ul=class extends W{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))}},jl=j(Ul,"scan"),Vl=class extends W{constructor(){super(...arguments),this.hasLast=!1}next(i){this.hasLast?this.sink.next([this.last,i]):this.hasLast=!0,this.last=i}},eT=j(Vl,"pairwise"),Ja=class extends W{constructor(i,e,t){super(i),this.mapper=e,this.thisArg=t}next(i){super.next(this.mapper.call(this.thisArg,i))}},en=j(Ja,"map"),tT=s=>j(Ja,"mapTo")(i=>s),Ps=class extends W{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()}},xs=class extends W{constructor(i,e,t){super(i),this.makeSource=e,this.combineResults=t,this.index=0}subInner(i,e){let t=this.currentSink=new e(this.sink,i,this);this.complete=this.tryComplete,t.complete=t.tryComplete,t.subscribe(this.makeSource(i,this.index++))}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},qa=class extends Ps{},ja=class extends xs{next(i){this.subInner(i,qa),this.next=e=>{this.currentSink.dispose(),this.subInner(e,qa)}}},Ls=j(ja,"switchMap");function Ya(s){return(i,e)=>s(()=>i,e)}var Wr=Ya(j(ja,"switchMapTo")),Bl=class extends Ps{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},Xa=class extends xs{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(),Bl),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},iT=j(Xa,"concatMap"),rT=Ya(j(Xa,"concatMapTo")),Fl=class extends Ps{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},za=class extends xs{constructor(){super(...arguments),this.inners=new Set}next(i){this.subInner(i,Fl),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(i=>i.resetComplete()):this.dispose()}},sT=j(za,"mergeMap"),oT=Ya(j(za,"mergeMapTo")),$l=class extends Ps{dispose(){this.context.resetNext(),super.dispose()}},Qa=class extends xs{next(i){this.next=de,this.subInner(i,$l)}},nT=j(Qa,"exhaustMap"),aT=Ya(j(Qa,"exhaustMapTo")),Hl=class extends W{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=tt(),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)}},cT=j(Hl,"groupBy"),Gl=class extends W{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}},dT=j(Gl,"timeInterval"),Wl=class extends W{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()}},lT=j(Wl,"bufferTime"),Jl=class extends W{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)}},uT=j(Jl,"delay"),ql=class extends W{constructor(i,e){super(i),this.selector=e}error(i){this.dispose(),this.selector(i)(this.sink)}},Xl=j(ql,"catchError");var hT=()=>s=>new Promise((i,e)=>{let t;new Hr(s,r=>t=r,e,()=>i(t))}),mT=()=>s=>{let i;return new ReadableStream({start(e){i=new Hr(s,e.enqueue.bind(e),e.error.bind(e),e.close.bind(e))},cancel(){i.dispose()}})},be=(s=de,i=de,e=de)=>t=>new Hr(t,s,i,e),zl=class extends W{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)}))}},Yl=j(zl,"tap"),Ql=class extends W{constructor(i,e){super(i),this.timeout=e,this.id=setTimeout(()=>this.error(new Qo(this.timeout)),this.timeout)}next(i){super.next(i),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},pT=j(Ql,"timeout"),fT=(s=1/0)=>i=>{if(i instanceof Ct){let e=ie(t=>{let r=s,o=new W(t);o.error=n=>{r-- >0?o.subscribe(i):t.error(n)},o.sourceId=e.id,o.subscribe(i)},"retry",[s]);return e.source=i,Ce.pipe(e),e}else return e=>{let t=s,r=new W(e);r.error=o=>{t-- >0?i(r):e.error(o)},i(r)}};var pi=class pi extends Vr{constructor(e,t,r){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:r,room:e});this.room=e;this.user=t;d(this,"tinyId");d(this,"isRemote",!0);d(this,"jitterBufferDelay",0);d(this,"availableState");d(this,"remotePublishState");d(this,"_triggerCheckDecodeSubject",tt(he(this,pi.STATE_SUBSCRIBE)));this.tinyId=t.tinyId,this.availableState=new H(`${t.userId}-${this.mediaType}-available`,"remote-track-available"),this.remotePublishState=new H(`${t.userId}-${this.mediaType}-remote-publish`,"remote-track-publish"),le(Tl(he(this,H.STATECHANGED),he(this.remotePublishState,H.STATECHANGED)),en(()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing)),be(c=>{this.availableState.state!==(c?H.ON:H.OFF)&&(this.availableState.state=c?H.ON:H.OFF),this.updatePlayingState(c)}));let o=le(he(this.player,ue.ERROR),mi(c=>c.code===MediaError.MEDIA_ERR_DECODE)),n=le(Zo(5e3),mi(()=>this.ignoreDecodeError||!this.isSubscribed||!this.isPlayCalled||!this.stat.bytesReceived?!1:this.player.isPlaying||(this.kind===p.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)?(this.reportDecodeResult(!0),!1):!0)),a=le(El(o,n),Be(he(this,H.INIT)));le(this._triggerCheckDecodeSubject,mi(()=>!this.ignoreDecodeError),Wr(a),be(c=>{this.reportDecodeResult(!1,c)}))}setMute(e){this.isRemotePublished&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.isRemotePublished&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}checkDecodeResult(){this._triggerCheckDecodeSubject.next(!0)}waitHasMediaTrack(){return new Promise(e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)})}get ignoreDecodeError(){var t,r;return(((r=(t=this.room)==null?void 0:t.networkQuality)==null?void 0:r.downlinkNetworkQuality)||0)>3||this.player.isInAutoPlayFailedState}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===pi.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===H.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){let r=this.kind===p.AUDIO;b[e?"addSuccessEvent":"addFailedEvent"]({key:r?504700:514702}),e||(b.addEnum({key:r?504701:514703,value:yo()}),re.uploadEvent({log:`stat-decode-failed-${this.kind}-${Or()||Pi()}`,userId:this.room.userId}),this._log.warn(`decode failed: isPlaying: ${this.player.isPlaying} ${this.kind===p.AUDIO?`audioLevel: ${this.getAudioLevel()}`:`framesDecoded: ${this.stat.framesDecoded>0}`}`),this.emit("decode-failed",{error:t}))}updatePlayingState(e){if(this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.isRemotePublished||!this.outMediaTrack)){this.log.info(`abort play, isSubscribed: ${this.isSubscribed} isAvailable: ${this.isRemotePublished} hasTrack: ${!!this.outMediaTrack} `);return}super.updatePlayingState(e)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.remotePublishState.state=this.isRemotePublished?H.ON:H.OFF}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};d(pi,"STATE_SUBSCRIBE","subscribe"),v([Va(5,1)],pi.prototype,"waitHasMediaTrack",1),v([Te(H.INIT,pi.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),E.emit(A.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),at(521716,!1)],pi.prototype,"subscribe",1),v([Te(pi.STATE_SUBSCRIBE,H.INIT,{sync:!0,success(){this.log.info("unsubscribed"),E.emit(A.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],pi.prototype,"unsubscribe",1);var ws=pi;var Gt=class extends ws{constructor(e,t){super(e,t,1);d(this,"volume",0);d(this,"mediaType",1);d(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.audioManager}get dbVolume(){return Ur.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}decodeFrame(e){if(!this.manager)return e;let t=e;for(let r of this.manager.decodePipeline)if(r&&(t=r({frame:t,track:this}),!t))return;return t}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get isRemotePublished(){return this.user.muteState.audioAvailable}};var gT=[-1,-1,1,-1,-1,1,1,1],TT=[0,0,1,0,0,1,1,1];var it=class extends H{constructor(e,t){super();this.context=e;d(this,"name");d(this,"input");d(this,"output");d(this,"texture");d(this,"ctx2d",null);d(this,"fbo");d(this,"width",0);d(this,"height",0);d(this,"x",0);d(this,"y",0);d(this,"program");d(this,"vertexShader");d(this,"fragmentShader");d(this,"totalFrames",0);d(this,"dropFrames",0);d(this,"matchInputSize",!0);d(this,"texCoordBuffer");d(this,"positionBuffer");d(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0});d(this,"cost",0);d(this,"_canvas",null);d(this,"_image");d(this,"log");if(this.context.on("disconnect",this.close,this),this.name=t.name,this.log=t.logger,this.matchInputSize=t.matchInputSize!==!1,this.width=t.width||e.width,this.height=t.height||e.height,this._image=t.image,e instanceof Xe){e.ctx&&t.create2d&&(typeof OffscreenCanvas=="function"&&ut!==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(TT),this.positionBuffer=this.createBuffer(gT),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.PACK_ALIGNMENT,1),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 y({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 ke&&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 ke){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,o)=>{r&&(t.activeTexture(t.TEXTURE0+o),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,o)=>{t.enableVertexAttribArray(o),t.bindBuffer(t.ARRAY_BUFFER,r),t.vertexAttribPointer(o,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,o,n){return this.ctx2d&&e?(e instanceof ImageData?this.ctx2d.putImageData(e,t,r):(this.ctx2d.drawImage(e,t,r,o,n),typeof VideoFrame!="undefined"&&e instanceof VideoFrame&&e.close()),!0):!1}getInfo(){var h;let{totalFrames:e,x:t,y:r,width:o,height:n,name:a,cost:c}=this,l=Date.now(),u=(e-this.lastInfo.totalFrames)/((l-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:r,width:o,height:n,timestamp:l,fps:u,name:a,cost:c},N({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.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),r}};v([Te(H.INIT,"connected",{sync:!0})],it.prototype,"connect",1),v([Te("connected",H.INIT,{ignoreError:!0,sync:!0})],it.prototype,"disconnect",1),v([Te([],"closed",{sync:!0})],it.prototype,"close",1);var ET=le(Sl(250),en(()=>performance.now()),Gi());var Lm=s=>i=>{let e=performance.now();le(ET,Wa(t=>t-e<s),Wi(1))(i)};var IT=[0,1,1,1,0,0,1,0],Jr=class extends it{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t));d(this,"_intervalId",0);d(this,"_sequence",0);d(this,"checkGLError",!1);d(this,"checkVisibilityChange");e instanceof Xe?this.ctx2d=e.ctx||null:e.available&&(t!=null&&t.mirrorUpAndDown)&&this.setTexBuffer(IT)}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 ke){let r=this.context.ctx.getError();r&&this.context.destroy(new y({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(),!0):!1}addInput(e,...t){super.addInput(e,...t),this.start(this.context.frameRate)}update(e=0){if(this._intervalId&&(oe.clearTask(this._intervalId),this._intervalId=0,e===1)){this.log.info(`${this.name} use requestVideoFrameCallback`);let t=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info(`${this.name} use timer`),document.removeEventListener("visibilitychange",t))};document.addEventListener("visibilitychange",t)}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)}},Us=class extends Jr{constructor(e,t){super(e,t);d(this,"_videoTrack");d(this,"_muteOb");d(this,"_closedOb",he(this,"closed"));d(this,"_subscription");d(this,"_canvasContainer");Number(Mi)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e._canvas.captureStream().getVideoTracks(),this._muteOb=he(this._videoTrack,"mute"),le(he(this._videoTrack,"ended"),Be(this._closedOb),be(()=>{this.context.destroy(new y({code:I.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){this._subscription=le(this._muteOb,Be(this._closedOb),Wr(Lm(5e3)),mi(()=>{var e;return!!((e=this._videoTrack)!=null&&e.muted)&&!document.hidden}),be(()=>{this.context.destroy(new y({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()}},Za=class extends Us{render(i){var e;return!!((e=this.input)!=null&&e.requestFrame(i))}};var Ka=class extends Us{constructor(e,t,r){super(e,{name:"smallDestination",logger:r});this.resolution=t}resize(e,t){let r,o=e*t,n=this.resolution.width*this.resolution.height;this.log.info(`big res: ${e}*${t} small res: ${this.resolution.width}*${this.resolution.height} `),o>n?r=o/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=o/(160*120)),super.resize(e/Math.sqrt(r),t/Math.sqrt(r))}};var tn=class extends it{constructor(e,t){super(e,N({name:"imageSource"},t));d(this,"_lastImage");d(this,"_totalFrames",0);d(this,"_autoResize",!1);d(this,"_canvasRendered");d(this,"_videoCallbackId",0);d(this,"waitingFirstFrame",!0);d(this,"shouldUpdate",!0);this._autoResize=(t==null?void 0:t.autoResize)!==!1,ut===16&&(this._canvasRendered=tt(),le(this._canvasRendered,Yo(this._image),Ls(r=>r instanceof HTMLCanvasElement?he(r,"rendered"):Ko()),Be(he(this,"closed")),be(()=>{this.update()})))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){if(!this.shouldUpdate)return;let e=this.image;this._videoCallbackId&&e.cancelVideoFrameCallback(this._videoCallbackId),wr()&&!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:o}=this,{image:n}=this;if(n instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(),{videoWidth:r,videoHeight:o}=n,!r||!o)return!1;n.width=r,n.height=o}else if(n instanceof HTMLImageElement||n instanceof ImageData||n instanceof ImageBitmap){if({width:r,height:o}=n,n!==this._lastImage)this._lastImage=n;else if(r===this.width&&o===this.height)return!1}else n instanceof HTMLCanvasElement||n instanceof OffscreenCanvas?({width:r,height:o}=n,this._lastImage=n):typeof VideoFrame!="undefined"&&n instanceof VideoFrame&&({displayWidth:r,displayHeight:o}=n,(a=this._lastImage)==null||a.close(),this._lastImage=n);if(!this._autoResize)return!0;if(this.width===r&&this.height===o&&this.totalFrames){if(t){this.useTexture();let c=this.context.ctx;c.texSubImage2D(c.TEXTURE_2D,0,0,0,c.RGBA,c.UNSIGNED_BYTE,n)}}else{if(t){this.useTexture();let c=this.context.ctx;c.texImage2D(c.TEXTURE_2D,0,c.RGBA,c.RGBA,c.UNSIGNED_BYTE,n)}this.resize(r,o)}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)}},rn=class extends tn{constructor(e,t,r){super(e,r);this._player=t;this.name="videoPlayerSource",le(he(this._player,ue.PLAYER_STATE_CHANGED),Be(he(this,"closed")),mi(({state:o})=>o==="PLAYING"),be(()=>{this.tryVideoFrameCallback()}))}get image(){return this._player.element}},Ji=class extends rn{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(i,e,t){super(i,new ft({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()}};var RT=`
34
34
  // \u9876\u70B9\u7740\u8272\u5668
35
35
  attribute vec4 a_position;
36
36
  attribute vec2 a_texCoord;
@@ -48,13 +48,13 @@ uniform sampler2D u_texture;
48
48
 
49
49
  void main() {
50
50
  gl_FragColor = texture2D(u_texture, v_texCoord);
51
- } `;var qr=class extends H{constructor(e){super();d(this,"frameRate");d(this,"_canvas");d(this,"log");d(this,"hasAlpha",!1);d(this,"name");d(this,"error");this.name=e.name,this.log=e.logger.createChild({id:`vc-${this.name}`}),this.frameRate=e.frameRate}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 Ji(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new Us(this,e)}createVideoImageSource(e,t){return new tn(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new rn(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}};d(qr,"_ids",0);var yT={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},Vs=class Vs extends qr{constructor(){super(...arguments);d(this,"defaultProgam");d(this,"defaultVShader");d(this,"defaultFShader");d(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${qr._ids++}`),this.ctx=this._canvas.getContext("webgl2",yT),!this.ctx)throw new y({code:I.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,RT),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,CT),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new y({code:I.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})}destroy(e){let t="";return e&&(t=e.message,this.error=e,b.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}set height(e){var t;(t=this.ctx)==null||t.viewport(0,0,this.width,e),super.height=e}setSize(e,t){var r;(r=this.ctx)==null||r.viewport(0,0,e,t),super.setSize(e,t)}createShader(e,t){let r=this.ctx,o=r.createShader(e);return r.shaderSource(o,t),r.compileShader(o),o}createProgram(e,t){let r=this.ctx,o=r.createProgram();return r.attachShader(o,e),r.attachShader(o,t),r.linkProgram(o),r.getProgramParameter(o,r.LINK_STATUS)||this.log.error(r.getProgramInfoLog(o)),o}};d(Vs,"UNAVAILABLE","unavailable"),v([Te(H.INIT,"created",{sync:!0,fail(e){this.log.error("video gl context create failed",e.cause),b.addFailedEvent({key:512700,error:e.cause||e})},success(){this.log.info("video context created use webgl"),b.addSuccessEvent({key:512700})}})],Vs.prototype,"create",1),v([Te("created",H.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(Vs.UNAVAILABLE,e),this.removeAllListeners()}})],Vs.prototype,"destroy",1);var ke=Vs,Xe=class extends qr{constructor(){super(...arguments);d(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${qr._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new y({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,b.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(),b.addSuccessEvent({key:512703})}};v([Te(H.INIT,"created",{sync:!0,fail(e){this.log.error("video 2d context create failed",e.cause),b.addFailedEvent({key:512701,error:e.cause||e})},success(){this.log.info("video context created use 2d"),b.addSuccessEvent({key:512701})}})],Xe.prototype,"create",1),v([Te("created",H.INIT,{ignoreError:!0,sync:!0})],Xe.prototype,"destroy",1);function bT(s){return[15,30,45,60].reduce((e,t)=>Math.abs(t-s)<Math.abs(e-s)?t:e)}var fi=class extends ws{constructor(e,t,r=4){super(e,t,r);d(this,"mediaType",4);d(this,"source");d(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.videoManager,this.once("first-video-frame",o=>{this.room.emit("first-video-frame",o)})}play(e,t){return(me(t==null?void 0:t.canvasRender)?t.canvasRender:ut===17)&&!this.source&&this.useCanvasPlayer(),super.play(e,t).then(()=>{this.player.calculateStat()})}useCanvasPlayer(){if(this.log.info(`useCanvasPlayer(), has element:${!!this.player.element}`),!this.player.element)return;let e=new Xe({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});let t=new Jr(e,{name:"remotePlayer",logger:this.log});this.source=e.createVideoPlayerSource(this.player),this.source.connect(t),this.player.setCanvas(e._canvas),wr()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let t=this.decodeFPS,r=bT(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),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)}onDecodeDowngradeStateChanged(e){this.emit("decode-downgrade-state-changed",e)}},Bs=class extends fi{constructor(e,t){super(e,t,2);d(this,"mediaType",2);d(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}};var Fs=new Map;E.on(A.JOIN_SUCCESS,({room:s})=>{Ae(s.userId,{eventId:32788})});E.on(A.LEAVE_START,({room:s})=>{Ae(s.userId,{eventId:32789})});E.on(A.LOCAL_TRACK_PUBLISHED,({track:s})=>{if(s.room){let i=32769;s.mediaType===4?i=32768:s.mediaType===2&&(i=32805),Ae(s.room.userId,{eventId:i})}});E.on(A.LOCAL_TRACK_UNPUBLISHED,({track:s})=>{if(s.room){let i=32771;s.mediaType===4?i=32770:s.mediaType===2&&(i=32806),Ae(s.room.userId,{eventId:i})}});E.on(A.TRACK_MUTED,({track:s})=>{s.room&&(s.kind===p.AUDIO?Ae(s.room.userId,{eventId:s.isRemote?32785:32772,remoteUserId:s.isRemote?s.userId:void 0}):Ae(s.room.userId,{eventId:s.isRemote?32784:32773,remoteUserId:s.isRemote?s.userId:void 0}))});E.on(A.TRACK_UNMUTED,({track:s})=>{s.room&&(s.kind===p.AUDIO?Ae(s.room.userId,{eventId:s.isRemote?32787:32774,remoteUserId:s.isRemote?s.userId:void 0}):Ae(s.room.userId,{eventId:s.isRemote?32786:32775,remoteUserId:s.isRemote?s.userId:void 0}))});E.on(A.REMOTE_TRACK_SUBSCRIBED,({track:s})=>{s.room&&(s.mediaType===1&&Ae(s.room.userId,{eventId:32777,remoteUserId:s.userId}),s.mediaType===4&&Ae(s.room.userId,{eventId:32776,remoteUserId:s.userId}),s.mediaType===8&&Ae(s.room.userId,{eventId:32803,remoteUserId:s.userId}))});E.on(A.REMOTE_TRACK_UNSUBSCRIBED,({track:s})=>{s.room&&(s.mediaType===1&&Ae(s.room.userId,{eventId:32779,remoteUserId:s.userId}),s.mediaType===4&&Ae(s.room.userId,{eventId:32778,remoteUserId:s.userId}),s.mediaType===8&&Ae(s.room.userId,{eventId:32804,remoteUserId:s.userId}))});E.on(A.SWITCH_DEVICE_SUCCESS,({track:s})=>{s.room&&Ae(s.room.userId,{eventId:s.kind===p.VIDEO?32780:32781})});E.on(A.LOCAL_TRACK_REPLACED,({track:s})=>{s.room&&Ae(s.room.userId,{eventId:s.kind===p.VIDEO?32782:32783})});E.on(A.SIGNAL_CONNECTION_STATE_CHANGED,({room:s,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&&Ae(s.userId,{eventId:t})});E.on(A.PEER_CONNECTION_STATE_CHANGED,({room:s,prevState:i,state:e,remoteUserId:t})=>{let r=!!t,o;switch(e){case"CONNECTED":i==="RECONNECTING"?o=r?32801:32798:o=r?32793:32792;break;case"DISCONNECTED":i==="RECONNECTING"&&(o=r?32802:32799);break;case"RECONNECTING":o=r?32800:32797;break}o&&Ae(s.userId,{eventId:o,remoteUserId:t})});E.on(A.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({implementation:s,userId:i,remoteUserId:e,codec:t,isHWCodec:r,prevImplementation:o,streamType:n})=>{let a=r?1:0;o||(a=r?3:2);let c=t==="h264"?0:2,l={eventId:4004,param1:a,param2:c,streamType:n||2};e&&(l.remoteUserId=e,l.eventId=4005),Ae(i,l),b.addEnum({key:e?514701:513701,value:a}),b.addEnum({key:e?514700:513700,value:c})});E.on(A.LOCAL_TRACK_RECAPTURE,({track:s,error:i})=>{if(s.userId){let e={eventId:2003,param1:0};s.kind===p.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType=s.streamType==="auxiliary"?7:2,i&&(e.param1=8)),Ae(s.userId,e)}});function Ae(s,i){let e=L(N({},i),{timestamp:eo()});Fs.has(s)?Fs.get(s).push(e):Fs.set(s,[e])}function wm(s){if(Fs.has(s)){let i=Fs.get(s).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 Fs.delete(s),i}return[]}function Um(...s){return Q((i,e)=>function(...t){return NT.call(this,s,t,e,this._name),i.apply(this,t)})}function NT(s,i,e,t){try{if(Se(s))for(let r=0;r<s.length;r++)ec.call(this,{rule:s[r],value:i[r],key:s[r].name,fnName:e,className:t});else ec.call(this,{rule:s,value:i[0],key:s.name,fnName:e,className:t})}catch(r){throw C.error(r),r}}function ec({rule:s,value:i,key:e,fnName:t,className:r}){if(T(i)){if(s.required)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_REQUIRED,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(T(s.defaultValue))return;i=s.defaultValue}if(Array.isArray(s.type)){let a=!1;for(let c=0;c<s.type.length;c++)s.type[c]===null&&i===null&&(a=!0),ne(s.type[c])&&i instanceof s.type[c]&&(a=!0),ee(s.type[c])&&Re(i)===s.type[c].toLowerCase()&&(a=!0);if(!a)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_TYPE,data:{key:e,rule:{type:s.type.map(c=>br(c)?os(c):ee(c)?c:Re(c))},fnName:t,value:i},link:{className:r,fnName:t}})})}else if(!T(s.type)&&Re(i)!==s.type)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_TYPE,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(s.allowEmpty===!1){let a=q(i)&&(i===0||Number.isNaN(i)),c=ee(i)&&i.trim()==="";if(a||c)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_EMPTY,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})})}if(s.notLessThanZero&&q(i)&&i<0)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.CANNOT_LESS_THAN_ZERO,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(!T(s.min)&&q(i)&&i<s.min)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_MIN,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(!T(s.max)&&q(i)&&i>s.max)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_MAX,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(ee(s.instanceOf)){if(!i||i._name!==s.instanceOf)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})})}else if(ne(s.instanceOf)&&!(i instanceof s.instanceOf))throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(s.values&&!s.values.includes(i))throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_RANGE,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});let{properties:o}=s;Je(o)&&Mt(i)&&Object.keys(o).forEach(a=>{ec.call(this,{rule:o[a],value:i&&i[a],key:`${e}.${a}`,fnName:t,className:r})});let{arrayItem:n}=s;Je(n)&&Se(i)&&i.forEach((a,c)=>{ec.call(this,{rule:n,value:a,key:`${e}[${c}]`,fnName:t,className:r})}),ne(s.validate)&&s.validate.call(this,i,e,t,r,this)}var Vm=$e(Ye(),1);var tc=class extends Vm.EventEmitter{constructor(e,t,r="userId"){super();this.mySelfId=e;this._log=t;this.key=r;d(this,"userMap",new Map);d(this,"remotePublishedUserMap",new Map)}get hasRobotUser(){return!![...this.remotePublishedUserMap.values()].find(e=>e.isRobot)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:r,tinyId:o,role:n}=e;if(this.userMap.has(t))return;let a={userId:r,tinyId:o,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 o=`peer leave [${e}]`;T(t)||(o+=`:${Zc[t]}`),this._log.info(o);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(o=>o[this.key]===t[this.key])<0){this._log.info(`remote [${r}] unpublish`);let o=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(r),this.emit("6",{prevMuteState:o,muteState:t.muteState,flag:0})}}),e.forEach(t=>{var u;let r=t[this.key];if(r===this.mySelfId)return;let{flag:o,userId:n,tinyId:a}=t,c=bi(o,n),l=(u=this.remotePublishedUserMap.get(r))==null?void 0:u.muteState;if(l){let h=this.remotePublishedUserMap.get(r);h&&h.flag!==o&&(h.flag=o,this._log.info(`remote publish updated: ${JSON.stringify(h.muteState)}`),this.emit("6",{prevMuteState:l,muteState:c,flag:o}))}else this._log.info(`remote publish. state: ${JSON.stringify(c)}`),this.addUser({userId:n,tinyId:a,role:20}),this.emit("3",t),this.emit("6",{prevMuteState:bi(0,n),muteState:c,flag:o})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function eu({timesInSecond:s,maxSizeInSecond:i,getSize:e}){return Q((t,r)=>{let o=new WeakMap;return E.on(A.ROOM_DESTROY,({room:n})=>o.delete(n)),function(...n){let a=o.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},o.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>=s||a.totalSizeInSecond>i))throw new y({code:I.INVALID_OPERATION,message:x({key:P.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=s,isSize:a.totalSizeInSecond>i,name:r,timesInSecond:s,maxSizeInSecond:i}})});a.callCountInSecond++,t.call(this,...n)}})}var vT="2025-06-11 12:34:37",Bm=!0,Fm=function(){var s;if(Bm){Bm=!1,C.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${Xt}/en/index.html`),console.info(`* Changelog: ${Xt}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),C.info("TRTC Web SDK Version:",Pe),Vt||C.debug("Build Time:",vT);let i=`UA: ${navigator.userAgent}
51
+ } `;var qr=class extends H{constructor(e){super();d(this,"frameRate");d(this,"_canvas");d(this,"log");d(this,"hasAlpha",!1);d(this,"name");d(this,"error");this.name=e.name,this.log=e.logger.createChild({id:`vc-${this.name}`}),this.frameRate=e.frameRate}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 Ji(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new Us(this,e)}createVideoImageSource(e,t){return new tn(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new rn(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}};d(qr,"_ids",0);var yT={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},Vs=class Vs extends qr{constructor(){super(...arguments);d(this,"defaultProgam");d(this,"defaultVShader");d(this,"defaultFShader");d(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${qr._ids++}`),this.ctx=this._canvas.getContext("webgl2",yT),!this.ctx)throw new y({code:I.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,RT),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,CT),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new y({code:I.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})}destroy(e){let t="";return e&&(t=e.message,this.error=e,b.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}set height(e){var t;(t=this.ctx)==null||t.viewport(0,0,this.width,e),super.height=e}setSize(e,t){var r;(r=this.ctx)==null||r.viewport(0,0,e,t),super.setSize(e,t)}createShader(e,t){let r=this.ctx,o=r.createShader(e);return r.shaderSource(o,t),r.compileShader(o),o}createProgram(e,t){let r=this.ctx,o=r.createProgram();return r.attachShader(o,e),r.attachShader(o,t),r.linkProgram(o),r.getProgramParameter(o,r.LINK_STATUS)||this.log.error(r.getProgramInfoLog(o)),o}};d(Vs,"UNAVAILABLE","unavailable"),v([Te(H.INIT,"created",{sync:!0,fail(e){this.log.error("video gl context create failed",e.cause),b.addFailedEvent({key:512700,error:e.cause||e})},success(){this.log.info("video context created use webgl"),b.addSuccessEvent({key:512700})}})],Vs.prototype,"create",1),v([Te("created",H.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(Vs.UNAVAILABLE,e),this.removeAllListeners()}})],Vs.prototype,"destroy",1);var ke=Vs,Xe=class extends qr{constructor(){super(...arguments);d(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${qr._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new y({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,b.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(),b.addSuccessEvent({key:512703})}};v([Te(H.INIT,"created",{sync:!0,fail(e){this.log.error("video 2d context create failed",e.cause),b.addFailedEvent({key:512701,error:e.cause||e})},success(){this.log.info("video context created use 2d"),b.addSuccessEvent({key:512701})}})],Xe.prototype,"create",1),v([Te("created",H.INIT,{ignoreError:!0,sync:!0})],Xe.prototype,"destroy",1);function bT(s){return[15,30,45,60].reduce((e,t)=>Math.abs(t-s)<Math.abs(e-s)?t:e)}var fi=class extends ws{constructor(e,t,r=4){super(e,t,r);d(this,"mediaType",4);d(this,"source");d(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.videoManager,this.once("first-video-frame",o=>{this.room.emit("first-video-frame",o)})}play(e,t){return(me(t==null?void 0:t.canvasRender)?t.canvasRender:ut===17)&&!this.source&&this.useCanvasPlayer(),super.play(e,t).then(()=>{this.player.calculateStat()})}useCanvasPlayer(){if(this.log.info(`useCanvasPlayer(), has element:${!!this.player.element}`),!this.player.element)return;let e=new Xe({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});let t=new Jr(e,{name:"remotePlayer",logger:this.log});this.source=e.createVideoPlayerSource(this.player),this.source.connect(t),this.player.setCanvas(e._canvas),wr()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let t=this.decodeFPS,r=bT(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),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)}onDecodeDowngradeStateChanged(e){this.emit("decode-downgrade-state-changed",e)}},Bs=class extends fi{constructor(e,t){super(e,t,2);d(this,"mediaType",2);d(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}};var Fs=new Map;E.on(A.JOIN_SUCCESS,({room:s})=>{Ae(s.userId,{eventId:32788})});E.on(A.LEAVE_START,({room:s})=>{Ae(s.userId,{eventId:32789})});E.on(A.LOCAL_TRACK_PUBLISHED,({track:s})=>{if(s.room){let i=32769;s.mediaType===4?i=32768:s.mediaType===2&&(i=32805),Ae(s.room.userId,{eventId:i})}});E.on(A.LOCAL_TRACK_UNPUBLISHED,({track:s})=>{if(s.room){let i=32771;s.mediaType===4?i=32770:s.mediaType===2&&(i=32806),Ae(s.room.userId,{eventId:i})}});E.on(A.TRACK_MUTED,({track:s})=>{s.room&&(s.kind===p.AUDIO?Ae(s.room.userId,{eventId:s.isRemote?32785:32772,remoteUserId:s.isRemote?s.userId:void 0}):Ae(s.room.userId,{eventId:s.isRemote?32784:32773,remoteUserId:s.isRemote?s.userId:void 0}))});E.on(A.TRACK_UNMUTED,({track:s})=>{s.room&&(s.kind===p.AUDIO?Ae(s.room.userId,{eventId:s.isRemote?32787:32774,remoteUserId:s.isRemote?s.userId:void 0}):Ae(s.room.userId,{eventId:s.isRemote?32786:32775,remoteUserId:s.isRemote?s.userId:void 0}))});E.on(A.REMOTE_TRACK_SUBSCRIBED,({track:s})=>{s.room&&(s.mediaType===1&&Ae(s.room.userId,{eventId:32777,remoteUserId:s.userId}),s.mediaType===4&&Ae(s.room.userId,{eventId:32776,remoteUserId:s.userId}),s.mediaType===8&&Ae(s.room.userId,{eventId:32803,remoteUserId:s.userId}))});E.on(A.REMOTE_TRACK_UNSUBSCRIBED,({track:s})=>{s.room&&(s.mediaType===1&&Ae(s.room.userId,{eventId:32779,remoteUserId:s.userId}),s.mediaType===4&&Ae(s.room.userId,{eventId:32778,remoteUserId:s.userId}),s.mediaType===8&&Ae(s.room.userId,{eventId:32804,remoteUserId:s.userId}))});E.on(A.SWITCH_DEVICE_SUCCESS,({track:s})=>{s.room&&Ae(s.room.userId,{eventId:s.kind===p.VIDEO?32780:32781})});E.on(A.LOCAL_TRACK_REPLACED,({track:s})=>{s.room&&Ae(s.room.userId,{eventId:s.kind===p.VIDEO?32782:32783})});E.on(A.SIGNAL_CONNECTION_STATE_CHANGED,({room:s,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&&Ae(s.userId,{eventId:t})});E.on(A.PEER_CONNECTION_STATE_CHANGED,({room:s,prevState:i,state:e,remoteUserId:t})=>{let r=!!t,o;switch(e){case"CONNECTED":i==="RECONNECTING"?o=r?32801:32798:o=r?32793:32792;break;case"DISCONNECTED":i==="RECONNECTING"&&(o=r?32802:32799);break;case"RECONNECTING":o=r?32800:32797;break}o&&Ae(s.userId,{eventId:o,remoteUserId:t})});E.on(A.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({implementation:s,userId:i,remoteUserId:e,codec:t,isHWCodec:r,prevImplementation:o,streamType:n})=>{let a=r?1:0;o||(a=r?3:2);let c=t==="h264"?0:2,l={eventId:4004,param1:a,param2:c,streamType:n||2};e&&(l.remoteUserId=e,l.eventId=4005),Ae(i,l),b.addEnum({key:e?514701:513701,value:a}),b.addEnum({key:e?514700:513700,value:c})});E.on(A.LOCAL_TRACK_RECAPTURE,({track:s,error:i})=>{if(s.userId){let e={eventId:2003,param1:0};s.kind===p.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType=s.streamType==="auxiliary"?7:2,i&&(e.param1=8)),Ae(s.userId,e)}});function Ae(s,i){let e=L(N({},i),{timestamp:eo()});Fs.has(s)?Fs.get(s).push(e):Fs.set(s,[e])}function wm(s){if(Fs.has(s)){let i=Fs.get(s).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 Fs.delete(s),i}return[]}function Um(...s){return Q((i,e)=>function(...t){return NT.call(this,s,t,e,this._name),i.apply(this,t)})}function NT(s,i,e,t){try{if(Se(s))for(let r=0;r<s.length;r++)ec.call(this,{rule:s[r],value:i[r],key:s[r].name,fnName:e,className:t});else ec.call(this,{rule:s,value:i[0],key:s.name,fnName:e,className:t})}catch(r){throw C.error(r),r}}function ec({rule:s,value:i,key:e,fnName:t,className:r}){if(T(i)){if(s.required)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_REQUIRED,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(T(s.defaultValue))return;i=s.defaultValue}if(Array.isArray(s.type)){let a=!1;for(let c=0;c<s.type.length;c++)s.type[c]===null&&i===null&&(a=!0),ne(s.type[c])&&i instanceof s.type[c]&&(a=!0),ee(s.type[c])&&Re(i)===s.type[c].toLowerCase()&&(a=!0);if(!a)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_TYPE,data:{key:e,rule:{type:s.type.map(c=>br(c)?os(c):ee(c)?c:Re(c))},fnName:t,value:i},link:{className:r,fnName:t}})})}else if(!T(s.type)&&Re(i)!==s.type)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_TYPE,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(s.allowEmpty===!1){let a=q(i)&&(i===0||Number.isNaN(i)),c=ee(i)&&i.trim()==="";if(a||c)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_EMPTY,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})})}if(s.notLessThanZero&&q(i)&&i<0)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.CANNOT_LESS_THAN_ZERO,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(!T(s.min)&&q(i)&&i<s.min)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_MIN,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(!T(s.max)&&q(i)&&i>s.max)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_MAX,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(ee(s.instanceOf)){if(!i||i._name!==s.instanceOf)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})})}else if(ne(s.instanceOf)&&!(i instanceof s.instanceOf))throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(s.values&&!s.values.includes(i))throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_RANGE,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});let{properties:o}=s;Je(o)&&Mt(i)&&Object.keys(o).forEach(a=>{ec.call(this,{rule:o[a],value:i&&i[a],key:`${e}.${a}`,fnName:t,className:r})});let{arrayItem:n}=s;Je(n)&&Se(i)&&i.forEach((a,c)=>{ec.call(this,{rule:n,value:a,key:`${e}[${c}]`,fnName:t,className:r})}),ne(s.validate)&&s.validate.call(this,i,e,t,r,this)}var Vm=$e(Ye(),1);var tc=class extends Vm.EventEmitter{constructor(e,t,r="userId"){super();this.mySelfId=e;this._log=t;this.key=r;d(this,"userMap",new Map);d(this,"remotePublishedUserMap",new Map)}get hasRobotUser(){return!![...this.remotePublishedUserMap.values()].find(e=>e.isRobot)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:r,tinyId:o,role:n}=e;if(this.userMap.has(t))return;let a={userId:r,tinyId:o,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 o=`peer leave [${e}]`;T(t)||(o+=`:${Zc[t]}`),this._log.info(o);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(o=>o[this.key]===t[this.key])<0){this._log.info(`remote [${r}] unpublish`);let o=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(r),this.emit("6",{prevMuteState:o,muteState:t.muteState,flag:0})}}),e.forEach(t=>{var u;let r=t[this.key];if(r===this.mySelfId)return;let{flag:o,userId:n,tinyId:a}=t,c=bi(o,n),l=(u=this.remotePublishedUserMap.get(r))==null?void 0:u.muteState;if(l){let h=this.remotePublishedUserMap.get(r);h&&h.flag!==o&&(h.flag=o,this._log.info(`remote publish updated: ${JSON.stringify(h.muteState)}`),this.emit("6",{prevMuteState:l,muteState:c,flag:o}))}else this._log.info(`remote publish. state: ${JSON.stringify(c)}`),this.addUser({userId:n,tinyId:a,role:20}),this.emit("3",t),this.emit("6",{prevMuteState:bi(0,n),muteState:c,flag:o})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function eu({timesInSecond:s,maxSizeInSecond:i,getSize:e}){return Q((t,r)=>{let o=new WeakMap;return E.on(A.ROOM_DESTROY,({room:n})=>o.delete(n)),function(...n){let a=o.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},o.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>=s||a.totalSizeInSecond>i))throw new y({code:I.INVALID_OPERATION,message:x({key:P.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=s,isSize:a.totalSizeInSecond>i,name:r,timesInSecond:s,maxSizeInSecond:i}})});a.callCountInSecond++,t.call(this,...n)}})}var vT="2025-06-11 16:28:42",Bm=!0,Fm=function(){var s;if(Bm){Bm=!1,C.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${Xt}/en/index.html`),console.info(`* Changelog: ${Xt}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),C.info("TRTC Web SDK Version:",Pe),Vt||C.debug("Build Time:",vT);let i=`UA: ${navigator.userAgent}
52
52
  CPU core: ${navigator.hardwareConcurrency}, GPU: ${Rd()}`,e=navigator.deviceMemory;e&&(i+=`, minRAM: ${e}GB`),C.info(i),C.info(`URL: ${location.href}${((s=self.frameElement)==null?void 0:s.tagName)==="IFRAME"?" in iframe":""}`),Dr().then(t=>{t&&C.info(xt)})}};var yt={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 B={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},bt=(R=>(R[R.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",R[R.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",R[R.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",R[R.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",R[R.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",R[R.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",R[R.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",R[R.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",R[R.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",R[R.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",R[R.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",R[R.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",R[R.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",R[R.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",R[R.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",R[R.INVALID_ROOM_ID_REQUIRED=5015]="INVALID_ROOM_ID_REQUIRED",R[R.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",R[R.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",R[R.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",R[R.INVALID_ROOM_ID_TYPE_MISMATCH=5019]="INVALID_ROOM_ID_TYPE_MISMATCH",R[R.INVALID_ROOM_ID_DUPLICATE=5020]="INVALID_ROOM_ID_DUPLICATE",R[R.INVALID_OPERATION=5100]="INVALID_OPERATION",R[R.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",R[R.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",R[R.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",R[R.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",R[R.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",R[R.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",R[R.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",R[R.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",R[R.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",R[R.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",R[R.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",R[R.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",R[R.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",R[R.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",R[R.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",R[R.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",R[R.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",R[R.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",R[R.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",R[R.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",R[R.DEVICE_ERROR=5300]="DEVICE_ERROR",R[R.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",R[R.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",R[R.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",R[R.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",R[R.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",R[R.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",R[R.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",R[R.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",R[R.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",R[R.SERVER_ERROR=5400]="SERVER_ERROR",R[R.NEED_TO_BUY=5401]="NEED_TO_BUY",R[R.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",R[R.OPERATION_FAILED=5500]="OPERATION_FAILED",R[R.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",R[R.REJOIN_FAILED=5502]="REJOIN_FAILED",R[R.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",R[R.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",R[R.VIDEO_DECODE_ERROR=5505]="VIDEO_DECODE_ERROR",R[R.OPERATION_ABORT=5998]="OPERATION_ABORT",R[R.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",R))(bt||{});function Hm({code:s,params:i,enableDocLink:e=!1}){let t="",r,o=bt[s];try{r=$m[o]}catch(n){r=$m.UNKNOWN_ERROR}return ne(r)?t=r(i):ee(r)&&(t=r),i.fnName&&!t.includes(i.fnName)&&(t[t.length-1]!=="."&&(t+="."),t+=` thrown from ${i.fnName}()`),e&&(t+=" doc:"),t}var $m=L(N({},Ve),{INVALID_PARAMETER({fnName:s}){return`the parameters of the '${s}' you called does not meet the requirements, please check the API documentation.`},INVALID_PARAMETER_REQUIRED({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' is a required param when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_TYPE({key:s,rule:i,fnName:e,value:t}){let r=`${s||i.name}`,o="";return Array.isArray(i.type)?o=i.type.join("|"):o=i.type,`'${r}' must be type of ${o} when calling ${e}(), received type: ${Re(t)}.`},INVALID_PARAMETER_EMPTY({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' cannot be '${t}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:s,rule:i,fnName:e,value:t}){let r=`${s||i.name}`,o=`${i.instanceOf.name||i.instanceOf}`;return`'${r}' must be instanceof ${o} when calling ${e}(), received type: ${Re(t)}.`},INVALID_PARAMETER_RANGE({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' must be one of ${i.values.join("|")} when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_LESS_THAN_ZERO({key:s,rule:i,fnName:e}){return`'${s||i.name}' cannot be less than 0 when calling ${e}().`},INVALID_PARAMETER_MIN({key:s,rule:i,value:e}){return`the min value of ${s||i.name} is ${i.min}, received: ${e}.`},INVALID_PARAMETER_MAX({key:s,rule:i,value:e}){return`the max value of ${s||i.name} is ${i.max}, received: ${e}.`},INVALID_ELEMENT_ID({key:s,fnName:i}){return`'${s}' is not found in the document object when calling ${i}().`},INVALID_ELEMENT_ID_TYPE({key:s,fnName:i,type:e}){return`the element corresponding to '${s}' must be instanceof HTMLElement when calling ${i}(), received: ${e}.`},INVALID_STREAM_ID({key:s}){return`'${s}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},INVALID_ROOM_ID_STRING({key:s}){return`'${s}' must be a valid string.`},INVALID_ROOM_ID_INTEGER({key:s}){return`'${s}' must be an integer between [1, 4294967294].`},INVALID_ROOM_ID_INTEGER_STRING({key:s}){return`'${s}' 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:s}){return`The type of target roomId must match the current roomId. Current room is using '${s}', but received '${s==="strRoomId"?"roomId":"strRoomId"}'.`},INVALID_ROOM_ID_DUPLICATE({key:s}){return`the target '${s}' must not be the same as the current '${s}'.`},INVALID_STREAM_TYPE:({fnName:s})=>`'streamType' is required when 'userId' is not '*', calling ${s}()`,INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION({fnName:s}){return`the API '${s}' you called does not meet the requirements, please check the API documentation.`},INVALID_OPERATION_NOT_JOINED({fnName:s}){return`cannot ${s} because you are not enter room yet.`},INVALID_OPERATION_REMOTE_USER_NOT_EXIST({fnName:s,value:i}){return`cannot ${s} because remote user(userId: ${i.userId}) does not publishing stream.`},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST({fnName:s,value:i}){return`cannot ${s} because remote user(userId: ${i.userId}) does not publishing ${i.streamType} video.`},INVALID_OPERATION_REPEAT_CALL({fnName:s}){return`you are already ${s}(), cannot repeated call '${s}'.`},INVALID_OPERATION_NEED_VIDEO({fnName:s}){return`cannot call '${s}' because the camera is not turned on.`},INVALID_OPERATION_NEED_AUDIO({fnName:s}){return`cannot call '${s}' because the microphone or screen share is not turned on.`},INVALID_BUFFER_EMPTY:({key:s})=>`the buffer size of paramerter '${s}' 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:s})=>`you need to call ${s}() after publish stream.`,ENV_NOT_SUPPORTED({fnName:s}){return`the current browser does not support the capability of the function '${s}' 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:s}){return`cannot call ${s} because the browser version is too low, please upgrade to the latest version`},DEVICE_ERROR({fnName:s,error:i}){return`'${s}' got device exception${i?`, error: ${i.toString()}.`:"."}`},DEVICE_NOT_FOUND_ERROR({fnName:s,deviceType:i=jr(s),error:e}){return`NotFoundError, no ${i} detected, please check your device and the configuration on '${s}'${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_ALLOWED_ERROR({fnName:s,deviceType:i=jr(s),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:s,deviceType:i=jr(s),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:s,deviceType:i=jr(s),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:s,deviceType:i=jr(s),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:s,deviceType:i=jr(s),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:s,deviceType:i=jr(s),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:s}){return`camera recover capture failed ${(s==null?void 0:s.name)||""}: ${(s==null?void 0:s.originMessage)||(s==null?void 0:s.message)}`},MICROPHONE_RECOVER_FAILED({error:s}){return`microphone recover capture failed ${(s==null?void 0:s.name)||""}: ${(s==null?void 0:s.originMessage)||(s==null?void 0:s.message)}`},OPERATION_FAILED({fnName:s,error:i}){return`'${s}' 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:s}){return`an error was caught on trtc.on('${s}', handler), please check your code on 'handler'.`},VIDEO_CONTEXT_ERROR({reason:s,error:i}){return`video context error ${s} ${(i==null?void 0:i.name)||""} ${(i==null?void 0:i.message)||""}`},SERVER_ERROR({fnName:s,error:i}){return`'${s}' got server error: ${i==null?void 0:i.toString()}, please check the SDK documentation.`},NEED_TO_BUY({value:s,url:i}){return`You need to buy packages for ${s}. Refer to: ${i}`},ACCOUNT_NO_MONEY:({fnParams:s})=>`your TRTC account run out of credit, please recharge.${s.sdkAppId?` SDKAppId: ${s.sdkAppId}`:""}`,OPERATION_ABORT({fnName:s}){return`'${s}' abort`},UNKNOWN_ERROR({fnName:s,error:i}){return`'${s}' throw unknown exception${i?`, error: ${i.toString()}.`:"."}`}});function jr(s){if(!s)return"camera";let i=s.toLowerCase();return i.includes("screen")?"screen share":i.includes("audio")?"microphone":"camera"}var tu=class s extends Error{constructor({code:e,extraCode:t,message:r="",messageParams:o,fnName:n="",originError:a}){var l;let c;r?c=r:c=Hm({code:e===B.SERVER_ERROR?e:t||e,params:N({fnName:n,error:a},o)});super(c);d(this,"name","RtcError");d(this,"code");d(this,"extraCode");d(this,"functionName");d(this,"message");d(this,"handler");d(this,"originError");this.name=bt[e],this.code=e,this.extraCode=t,this.functionName=n,this.originError=a,this.message=c,this.extraCode===5302&&((l=this.originError)!=null&&l.message.includes("system"))&&(this.handler=()=>{let u={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},h={startLocalVideo:"webcam",startLocalAudio:"microphone"},m=document.createElement("a");vr?m.href=`ms-settings:privacy-${h[this.functionName]}`:Ut&&(m.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${u[this.functionName]}`),m.href.length>0&&m.click()})}static convertFrom(e,t,r){let o=e;if(e instanceof y){let{stack:n}=e,a={code:B.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case I.INVALID_PARAMETER:a.code=B.INVALID_PARAMETER,a.message=e.message;break;case I.INVALID_OPERATION:a.code=B.INVALID_OPERATION;break;case I.NOT_SUPPORTED:case I.NOT_SUPPORTED_H264:a.code=B.ENV_NOT_SUPPORTED,e.getCode()===I.NOT_SUPPORTED_H264&&(a.extraCode=e.message.includes(Ve.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=B.SERVER_ERROR,a.extraCode=e.getExtraCode();break;case I.API_CALL_ABORTED:a.code=B.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=DT(e.name));break;case I.UNKNOWN:break;default:a.code=B.OPERATION_FAILED}o=new s(a),n&&(o.stack+=n.substr(n.indexOf(`
53
53
  `)))}else{if(e instanceof s)return e;o=new s({code:B.UNKNOWN_ERROR,fnName:t,originError:e})}return o}};function DT(s){let i;switch(s){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 U=tu;function hr(s){return s==="sub"?"auxiliary":s==="auxiliary"?"sub":"main"}function sn(s){return s===yt.QOS_PREFERENCE_CLEAR?"detail":s===yt.QOS_PREFERENCE_SMOOTH?"motion":""}function $s(s,i){let e=i?Wc:er;return ad(s)?N(N({},e),s):Dt[s]?Dt[s]:e}var Gm={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}}},Wm={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}}},Hs={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(s,i,e){if(ee(s)&&!document.getElementById(s))throw new U({code:B.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:i}})}},Jm={name:"userId",required:!0,type:"string"},qm={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[yt.AUDIO_PROFILE_STANDARD,yt.AUDIO_PROFILE_STANDARD_STEREO,yt.AUDIO_PROFILE_HIGH,yt.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function Gs(s,i){if(!s)throw new U({code:B.INVALID_OPERATION,extraCode:5101,fnName:i})}function jm(s,i,e){if(!s)throw new U({code:B.INVALID_OPERATION,extraCode:5102,fnName:i,messageParams:{value:e}})}function Xm(s,i,e){if(!(/^[1-9]\d*$/.test(String(s))&&s<4294967295))throw new U({code:B.INVALID_PARAMETER,extraCode:5013,fnName:i,messageParams:{key:e}})}function zm(s,i,e){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(s))throw new U({code:B.INVALID_PARAMETER,extraCode:5012,fnName:i,messageParams:{key:e}})}var HO={type:"number",notLessThanZero:!0},OT=(s,i)=>s.width*s.height>=i.width*i.height&&s.frameRate>=i.frameRate&&s.bitrate>=i.bitrate;function Qm(s){var t;if(!((t=s==null?void 0:s.option)!=null&&t.small))return;if(!_a()){C.warn("small stream is not supported"),delete s.option.small;return}let i=$s(s.option.profile),e=$s(s.option.small,!0);if(!OT(i,e)){C.warn(`small stream profile must be less than big stream profile. Big: ${JSON.stringify(i)}, Small: ${JSON.stringify(e)}`),delete s.option.small;return}}var MT={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(s,i,e){if(this._room.isJoined)throw new U({code:B.INVALID_OPERATION,extraCode:5104,fnName:e});if(s.roomId){if(ee(s.roomId))throw new U({code:B.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:i}});Xm(s.roomId,e,i)}else if(s.strRoomId)zm(s.strRoomId,e,i);else throw new U({code:B.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:Hs,mute:{type:["boolean","string"]},publish:{type:"boolean"},capture:{required:!1,type:"boolean"},option:Gm},validate(s){var i,e;if(!((i=s==null?void 0:s.option)!=null&&i.videoTrack)&&wi())throw new U({code:B.ENV_NOT_SUPPORTED,extraCode:5201});(e=s==null?void 0:s.option)!=null&&e.small&&Qm(s)}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:L(N({},Hs),{required:!1}),publish:{type:"boolean"},capture:{required:!1,type:"boolean"},mute:{type:["boolean","string"]},option:Gm},validate(s){var i;(i=s==null?void 0:s.option)!=null&&i.small&&Qm(s)}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:qm},validate(s){var i;if(!((i=s==null?void 0:s.option)!=null&&i.audioTrack)&&wi())throw new U({code:B.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:qm}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:Hs,publish:{type:"boolean"},option:Wm},validate(s,i,e,t,r){var o;if(!((o=s==null?void 0:s.option)!=null&&o.videoTrack)){if(wi())throw new U({code:B.ENV_NOT_SUPPORTED,extraCode:5201});if(!Po())throw new U({code:B.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:Hs,publish:{type:"boolean"},option:Wm}},muteRemoteAudio:[Jm,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[Jm,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:Hs,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(s,i,e){Gs(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(s.userId);if(jm(!!t,e,s),t&&(s.streamType==="main"&&!t.muteState.videoAvailable||s.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new U({code:B.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:s}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:L(N({},Hs),{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(s,i,e){Gs(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(s.userId);if(jm(!!t,e,s),t&&(s.streamType==="main"&&!t.muteState.videoAvailable||s.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new U({code:B.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:s}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(s,i,e){if(s.userId!=="*"&&T(s.streamType))throw new U({code:B.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(s,i,e){Gs(this._room.isJoining||this._room.isJoined,e)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(s,i,e,t){if(!wo)throw new U({code:B.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new U({code:B.INVALID_OPERATION,fnName:e,extraCode:5108});if(s.byteLength>1e3)throw new U({code:B.INVALID_PARAMETER,extraCode:5018,fnName:e});if(s.byteLength===0)throw new U({code:B.INVALID_PARAMETER,extraCode:5017,messageParams:{key:i},fnName:e});Gs(this._room.isJoined,e)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(s,i,e){if(!s&&!this._room.isMainStreamPublished||s&&!this._room.isAuxStreamPublished)throw new U({code:B.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(s,i,e,t){if(s.byteLength>1e3)throw new U({code:B.INVALID_PARAMETER,extraCode:5018,fnName:e});if(s.byteLength===0)throw new U({code:B.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:i}})}}},validate(s,i,e){if(Gs(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new U({code:B.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:i}})}},switchRoom:{name:"switchRoomConfig",type:"object",required:!0,validate(s,i,e){if(Gs(this._room.isJoined,e),this._room.useStringRoomId&&s.strRoomId===this._room.roomId||!this._room.useStringRoomId&&s.roomId===Number(this._room.roomId))throw new U({code:B.INVALID_PARAMETER,extraCode:5020,fnName:e,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(s.roomId&&this._room.useStringRoomId||!s.roomId&&s.strRoomId&&!this._room.useStringRoomId)throw new U({code:B.INVALID_PARAMETER,extraCode:5019,fnName:e,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(s.roomId)Xm(s.roomId,e,i);else if(s.strRoomId)zm(s.strRoomId,e,i);else throw new U({code:B.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}}}},we={TRTC:MT};var ze=class extends Error{};function kT(s,i){let e=Rr(s);for(let t=0;t<i.length;t++)It(e[t],i[t]);return e}function PT(s){this._resolve=Promise.resolve(s)}function xT(s){this._reject=Promise.reject(s)}var mr=class mr{constructor(i,e){this.instance=i;this.group=e;d(this,"started",!1);d(this,"ops",[]);d(this,"startSame",()=>!0);d(this,"mergeUpdate",kT);let t=mr.instances.get(i);t?t.set(e,this):mr.instances.set(i,new Map([[e,this]]))}static get(i,e){if(!e)return;let t=mr.instances.get(i);return t&&t.get(e)||new mr(i,e)}static gets(i,e){let t=mr.instances.get(i),r=[];return t&&t.forEach((o,n)=>{e.test(n)&&r.push(o)}),r}action(i,e,t){let r=a=>{var c;return i===0?this.started=!0:i===3&&(this.started=!1),this.ops.shift(),(c=this.currentOp)==null||c.action(),a},o=a=>{var c,l;throw this.ops.shift(),i===0&&((c=this.currentOp)==null?void 0:c.type)===2&&this.ops.shift().reject(new ze("start failed")),(l=this.currentOp)==null||l.action(),a},n={type:i,action:()=>e(...n.args).then(r,o),args:t,resolve:PT,reject:xT};try{switch(this.state){case 1:if(i===0)throw new ze("already started");break;case 4:if(i===2)throw new ze("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,o)}cacheOp(i){if(this.ops.length===1)switch(this.state){case 0:case 2:if(i.type===0)throw new ze("already start");break;case 3:switch(i.type){case 2:throw new ze("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new ze("unknown state")}else switch(i.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let t=new ze("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 ze("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new ze("start not allowed after update");case 0:throw new ze("duplicate start");case 3:if(this.startSame(this.currentOp.args,i.args))throw this.ops.pop().reject(new ze("keep start")),new ze("already start")}}i.promise=new Promise((t,r)=>{i._resolve?i._resolve.then(t):i.resolve=t,i._reject?i._reject.catch(r):i.reject=r});let{action:e}=i;return i.action=()=>e().then(i.resolve,i.reject),this.ops.push(i),i.promise}get lastOp(){return this.ops[this.ops.length-1]}get lastOpType(){return this.lastOp.type}get currentOp(){return this.ops[0]}get state(){return this.currentOp?this.currentOp.type:this.started?1:4}};d(mr,"instances",new WeakMap);var qi=mr;var ic=new WeakMap,rc=(s,i)=>{if(i instanceof ze){let{stack:e}=i;i=new U({code:B.OPERATION_ABORT,message:`${s} abort: ${i.message}`,fnName:s}),e&&(i.stack+=e.substr(e.indexOf(`
54
54
  `)))}throw i};function pr(s,i){return Q((e,t)=>function(...r){let o=qi.get(this,typeof s=="string"?s:s.call(this,...r));return o?(i&&(o.startSame=i.bind(this)),o.action(0,e.bind(this),r).catch(rc.bind(null,t))):e.apply(this,r)})}function Xr(s,i){let{merge:e,debounce:t}=i||{};return Q((r,o)=>function(...n){let a=qi.get(this,typeof s=="string"?s:s.call(this,...n));if(!a)return r.apply(this,n);if(e&&(a.mergeUpdate=e.bind(this)),t&&t.isNeedToDebounce.apply(this,n)){let{delay:c,getKey:l}=t;return new Promise((u,h)=>{var D,_;let m=(D=ic.get(this))==null?void 0:D.get(l(...n));if(m){let{timeoutId:S,resolve:O}=m;clearTimeout(S),O()}let g=setTimeout(()=>{if(a.state===3||a.state===4)return u();a.action(2,r.bind(this),n).catch(rc.bind(null,o)).then(u,h)},c);ic.has(this)?(_=ic.get(this))==null||_.set(l(...n),{timeoutId:g,resolve:u}):ic.set(this,new Map([[l(...n),{timeoutId:g,resolve:u}]]))})}return a.action(2,r.bind(this),n).catch(rc.bind(null,o))})}function fr(s){return Q((i,e)=>function(...t){let r=typeof s=="function"?s.call(this,...t):s;if(r instanceof RegExp)return Promise.all(qi.gets(this,r).map(n=>n.action(3,()=>Promise.resolve(),t))).then(()=>i.call(this,...t));let o=qi.get(this,r);return o?o.action(3,i.bind(this),t).catch(rc.bind(null,e)):i.apply(this,t)})}var k={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"},Ym=new Set([k.ERROR,k.AUTOPLAY_FAILED,k.KICKED_OUT,k.REMOTE_USER_ENTER,k.REMOTE_USER_EXIT,k.REMOTE_AUDIO_AVAILABLE,k.REMOTE_AUDIO_UNAVAILABLE,k.REMOTE_VIDEO_AVAILABLE,k.REMOTE_VIDEO_UNAVAILABLE,k.CONNECTION_STATE_CHANGED,k.PUBLISH_STATE_CHANGED,k.SCREEN_SHARE_STOPPED,k.DEVICE_CHANGED,k.FIRST_VIDEO_FRAME]);var ru={};Si(ru,{bytes2ms:()=>nh,calculateScaleResolutionDownNumber:()=>ls,convertObjectNumberToInt:()=>ho,copyProperties:()=>oh,deepClone:()=>Rr,deepMerge:()=>It,delay:()=>Ni,fibonacci:()=>yr,formatedTime:()=>ph,getConstructorName:()=>os,getContainerFromElement:()=>mh,getEnv:()=>rh,getInternalVersion:()=>uh,getLoggerUrl:()=>yi,getMediaStreamTrackInfo:()=>Vn,getMuteStateFromFlag:()=>bi,getNetworkType:()=>ed,getNumNetworkType:()=>Cr,getReconnectionTimeout:()=>Pt,getStringByteLength:()=>uo,getTurnServer:()=>hh,getUint32Version:()=>Ln,getValueType:()=>Re,getViewListFromView:()=>cs,glog:()=>rd,ipv4ToUint32:()=>as,isArray:()=>Se,isAudioWorkletSupported:()=>lh,isBoolean:()=>me,isConstructor:()=>br,isEmpty:()=>ns,isFunction:()=>ne,isLangChinese:()=>kt,isMediaStreamTrack:()=>ch,isNumber:()=>q,isObject:()=>Mt,isOverseaSdkAppId:()=>Ci,isPlainObject:()=>Je,isPortrait:()=>sd,isPromise:()=>sr,isRemoteTrack:()=>dh,isRotate90Or270:()=>vi,isString:()=>ee,isUndefined:()=>T,loadImage:()=>ds,ms2bytes:()=>ah,ms2samples:()=>id,normalizeUrl:()=>Un,performanceNow:()=>w,promiseAny:()=>Nr,samples2ms:()=>td,setNetworkType:()=>Pn,stringify:()=>St,stringifyIncludeValue:()=>xn,throttlePromise:()=>wn});var nu={};Si(nu,{ScheduleRequestType:()=>Km,getAbilityConfig:()=>wT,getScheduleDomain:()=>nc,isNeedToSchedule:()=>sc,scheduleProxy:()=>_i,sendScheduleRequest:()=>ou,setIsNeedToSchedule:()=>Wt,setScheduleProxy:()=>oc});var su=null,sc=!0;typeof document!="undefined"&&document.head.insertAdjacentHTML("beforeend",Object.values(Ri).map(s=>`<link rel="dns-prefetch" href="https://${s}">`).join(`\r
55
55
  `));function Wt(s){me(s)&&s!==sc&&(sc=s,C.info(`setIsNeedToSchedule ${s}`))}E.on("28",()=>Wt(!0));E.on("63",()=>Wt(!0));E.on("84",()=>Wt(!0));E.on("201",s=>{s.state==="RECONNECTING"&&Wt(!0)});E.on("202",s=>{s.state==="RECONNECTING"&&Wt(!0)});function LT(s,i,e){let t={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let r=performance.getEntriesByType("resource"),o=_r(s,"config",p.MAIN),n=_r(s,"config",p.BACKUP);for(let a of r)if(a.startTime>=e&&(a.name===o||a.name===n)&&a.transferSize>0){let c=a.name===o?p.MAIN:p.BACKUP,l=Math.round(a.duration),u=Math.round(a.domainLookupStart-a.startTime),h=a.redirectStart>0?Math.round(a.redirectEnd-a.redirectStart):0,m=a.fetchStart>0?Math.round(a.domainLookupStart-a.fetchStart):0,g=Math.round(a.domainLookupEnd-a.domainLookupStart),D=Math.round(a.requestStart-a.secureConnectionStart),_=Math.round(a.secureConnectionStart-a.connectStart),S=Math.round(a.responseStart-a.requestStart),O=Math.round(a.responseEnd-a.responseStart),K=[g,D,_,S,O];re.uploadEvent({log:`stat-schedule-net:${l}(${u}(${h}->${m})->${K.join("->")}) ${c}`,userId:i}),t=L(N({},t),{totalCost:l,local:u,dns:g,tcp:_,tls:D,request:S,response:O});break}}catch(r){C.error("getScheduleDetailCost error",r)}return t}function ou(l){return f(this,arguments,function*({userId:s,sdkAppId:i,useStringRoomId:e,roomId:t,userSig:r,version:o,frameWorkType:n,role:a,latencyLevel:c}){if(!sc&&su)return{isCached:!0,result:su};let u={delta:0,count:[1,1],msg:[],detail:[]};try{let h=new FormData;h.append("userId",String(s)),h.append("sdkAppId",String(i)),h.append("isStrGroupId",String(e)),h.append("groupId",String(t)),h.append("sdkVersion",o),h.append("userSig",String(r));let m=yield Dr();m!=null&&m.model&&h.append("model",String(m==null?void 0:m.model)),a&&h.append("role",String(a)),c&&h.append("latencyLevel",String(c)),n&&h.append("frameWorkType",String(n));let g=w(),D=yield VT(h,u,i);D.config&&(D.config.loggerDomain&&Tr(D.config.loggerDomain),me(D.config.scheduleCache)&&Wt(!D.config.scheduleCache)),u.delta=w()-g;let _=LT(Number(i),s,g);return su=D,{isCached:!1,result:D,detailCost:_}}catch(h){let m=Se(h)?h[0]:h,g=q(m.code)?m.code:0,D=`schedule failed${m.message?`: ${m.message}`:""}`,_=new y({code:I.SCHEDULE_FAILED,extraCode:g,message:x({key:P.JOIN_ROOM_FAILED,data:{error:D,code:g}})});throw C.error(D,g),_}})}var _i={main:"",backup:""};function oc(s){Se(s)?(_i.main=s[0],_i.backup=s[1]):_i.main=s}var Km=(t=>(t.CONFIG="config",t.TRTC_AUTO_CONF="trtcAutoConf",t.AUDIO_AI_AUTH="audioAiAuth",t))(Km||{});function _r(s,i,e=p.MAIN,t=!1){return`https://${_i[e]||nc(s,e,t)}/api/v1/${i}`}function wT(s,i,e){let t=_r(s,i),r=_r(s,i,p.BACKUP),o=new URLSearchParams(e).toString(),n=fetch(`${t}?${o}`).then(c=>c.json()),a=fetch(`${r}?${o}`).then(c=>c.json());return Nr([n,a])}function nc(s,i=p.MAIN,e=!1){let t;return Ci(s)?e?t=i===p.MAIN?Ri.MAIN_OVERSEA_BACKUP:Ri.BACKUP_OVERSEA:t=i===p.MAIN?Ri.MAIN_OVERSEA:Ri.BACKUP_OVERSEA:t=i===p.MAIN?Ri.MAIN:Ri.BACKUP,t}function UT(s,i,e){return new Promise((t,r)=>{Di({url:s,body:i,timeout:e.timeout,priority:"high"}).then(o=>{o.data.code===0?t(o.data.data):r({code:o.data.code,message:o.data.msg})}).catch(r)})}var Zm=(s,i)=>Yt({retryFunction:UT,settings:{retries:3,timeout:0},onError:i,onRetrying:s});function VT(s,i,e){return new Promise((t,r)=>{let o=null;Nr([Zm(n=>i.count[0]=n+1,({error:n,retry:a,retriedCount:c,retryFuncArgs:l})=>{i.msg[0]=n.message,o||(c>=1&&(l[0]=_r(e,"config",p.MAIN,!0)),a())})(_r(e,"config",p.MAIN),s,{get timeout(){return yr(2+i.count[0])*1e3}}),Zm(n=>i.count[1]=n+1,({error:n,retry:a,retriedCount:c,retryFuncArgs:l})=>{i.msg[1]=n.message,o||(c>=2&&(l[0]=_r(e,"config",p.BACKUP,!0)),a())})(_r(e,"config",p.BACKUP),s,{get timeout(){return yr(2+i.count[1])*1e3}})]).then(n=>{o=n,t(o)}).catch(r)})}var BT=s=>s.startsWith("data:application/octet-stream;base64,"),FT=s=>s.startsWith("file://"),on=class{constructor(){d(this,"_log");this._log=C.createLogger({id:"fd"})}download(i,e){return f(this,null,function*(){let{type:t="blob"}=e||{};i=Un(i);try{let r=w(),o;if(ne(fetch)?o=yield this.downloadWithFetch(i,t):o=yield this.downloadWithXHR(i,t),!o||!o.data)throw new Error("data is empty");let n=w()-r;return this._log.info(`downloaded: ${i}, return type: ${t}, cost: ${n}ms`),b.addSuccessEvent({key:522700,cost:w()-r}),o.data}catch(r){throw this._log.error(`failed to download: ${i}, error: ${r}`),b.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 o=new Error(`network response was not ok: ${t.status}`);throw o.status=t.status,o}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 o=new XMLHttpRequest;o.open("GET",i,!0),o.responseType=e,o.onload=()=>{if(o.status===200||o.status===0&&o.response)t({data:o.response});else{let n=new Error(`XHR failed, status: ${o.status}`);n.status=o.status,r(n)}},o.onerror=r,o.send(null)})}loadWasm(i,e){return f(this,null,function*(){this._log.info(`loadWasm ${i}, importObject: ${JSON.stringify(e)}`);let t=w(),r=null,o=null;if(ne(WebAssembly.instantiateStreaming)&&!BT(i)&&!FT(i)&&ne(fetch))try{let n=fetch(i);r=(yield WebAssembly.instantiateStreaming(n,e)).instance}catch(n){o=n}if(!r)try{let n=yield this.download(i,{type:"arraybuffer"});r=(yield WebAssembly.instantiate(n,e)).instance}catch(n){o=n}if(r){let n=w()-t;return this._log.info(`loadedWasm ${i}, cost: ${n}ms`),b.addSuccessEvent({key:522701,cost:n}),r}throw this._log.error(`failed to loadWasm ${i}, error: ${o}`),b.addFailedEvent({key:522701,error:o}),o})}loadScript(i){this._log.info(`loadScript ${i}`);let e=w();return new Promise((t,r)=>{let o=document.createElement("script");o.type="text/javascript",o.onload=()=>{this._log.info(`loadedScript ${i}, cost: ${w()-e}ms`),b.addSuccessEvent({key:522702,cost:w()-e,split:1e3}),t(o)},o.onerror=n=>{this._log.error(`failed to loadScript ${i}, error: ${n}`),b.addFailedEvent({key:522702}),r(n)},o.crossOrigin="anonymous",o.src=i,document.head.append?document.head.append(o):document.getElementsByTagName("head")[0].appendChild(o)})}};v([pt({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}`)}})],on.prototype,"download",1),v([pt({settings:{timeout:3e3,retries:3},onRetrying(i){this._log.warn(`loadScript retrying: ${i}`)}})],on.prototype,"loadScript",1);var ep=new on;function tp({TRTC:s,room:i,errorModule:e,assetsPath:t}){return{TRTC:s,room:i,assetsPath:t,fileDownloader:ep,innerEmitter:E,constants:Kc,environment:As,utils:ru,eventLogger:re,log:this.room.getLogger(),loggerManager:C,errorModule:e,kvStatManager:b,rtcDectection:ni,trtc:this,rx:Zl,enums:Vd,schedule:nu,clearStarted:(r,o)=>{let n=r.getAlias(),a=qi.instances.get(this);if(a)if(o){let c=a.get(n+o);if(!c)return;c.started=!1}else a.forEach((c,l)=>{l.startsWith(n)&&(c.started=!1)})},startGetPCM:zo,createAudioNode:Jo}}var ip=(s,i)=>{let{emit:e}=s;return s.emit=(...t)=>{try{return e.apply(s,t)}catch(r){let o=x({key:P.CATCH_HANDLER_ERROR,data:{name:i,event:t[0]},addDocLink:!1});return C.warn(`${o}
56
56
 
57
- ${r.stack}`),!1}},s};var Ws=new WeakMap;function rp(s){let i=Ws.get(s);i&&(i.forEach(e=>clearTimeout(e)),Ws.delete(s))}function sp(s,i){return Q((e,t)=>function(...r){let o=Ws.get(this);o||(o=new Map,Ws.set(this,o));let n=i(...r),a=o.get(n);if(!a||a<=0){e.apply(this,r);let c=setTimeout(()=>{var l;(l=Ws.get(this))==null||l.delete(n)},s);o.set(n,c)}else{clearTimeout(a);let c=window.setTimeout(()=>{var l;e.apply(this,r),(l=Ws.get(this))==null||l.delete(n)},s);o.set(n,c)}})}var np="trtc-sdk-v5",ap="5.11.0-beta.4";function Ge(...s){return Q((i,e)=>function(...t){try{cc.call(this,s,t,e,this._name)}catch(r){return Promise.reject(r)}return i.apply(this,t)})}function au(...s){return Q((i,e)=>function(...t){try{cc.call(this,s,t,e,this._name)}catch(r){throw r}return i.apply(this,t)})}function cc(s,i,e,t){if(Se(s))for(let r=0;r<s.length;r++)ac.call(this,{rule:s[r],value:i[r],key:s[r].name,fnName:e,className:t});else ac.call(this,{rule:s,value:i[0],key:s.name,fnName:e,className:t})}function ac({rule:s,value:i,key:e,fnName:t,className:r}){function o(c){return{code:B.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:s,value:i}}}if(T(i)){if(s.required)throw new U(o(5001));if(T(s.defaultValue)){ne(s.validate)&&s.validate.call(this,i,e,t,r,this);return}i=s.defaultValue}if(Array.isArray(s.type)){let c=!1;for(let l=0;l<s.type.length;l++)s.type[l]===null&&i===null&&(c=!0),ne(s.type[l])&&i instanceof s.type[l]&&(c=!0),ee(s.type[l])&&Re(i)===s.type[l].toLowerCase()&&(c=!0);if(!c)throw new U({code:B.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:s.type.map(l=>br(l)?os(l):ee(l)?l:Re(l))},value:i}})}else if(!T(s.type)&&Re(i)!==s.type)throw new U(o(5002));if(s.allowEmpty===!1){let c=q(i)&&(i===0||Number.isNaN(i)),l=ee(i)&&i.trim()==="";if(c||l)throw new U(o(5003))}if(s.notLessThanZero&&q(i)&&i<0)throw new U(o(5006));if(!T(s.min)&&q(i)&&i<s.min)throw new U(o(5007));if(!T(s.max)&&q(i)&&i>s.max)throw new U(o(5008));if(ee(s.instanceOf)){if(!i||i._name!==s.instanceOf)throw new U(o(5004))}else if(ne(s.instanceOf)&&!(i instanceof s.instanceOf))throw new U(o(5004));if(Array.isArray(s.values)&&!s.values.includes(i))throw new U(o(5005));let{properties:n}=s;Je(n)&&Mt(i)&&Object.keys(n).forEach(c=>{ac.call(this,{rule:n[c],value:i&&i[c],key:`${c}`,fnName:t,className:r})});let{arrayItem:a}=s;Je(a)&&Se(i)&&i.forEach((c,l)=>{ac.call(this,{rule:a,value:c,key:`${e}[${l}]`,fnName:t,className:r})}),ne(s.validate)&&s.validate.call(this,i,e,t,r,this)}function fe(s={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t,ignoreLog:r,ignoreErrorLog:o}=s;return Q((n,a)=>function(...c){var g,D,_;function l(S,O,K){if(K&&K.includes(S))return"hided";if(e){let G=e(...c);if(c[G.argIndex]===O)return G.value}if(O===c||S in c)return O;try{return O instanceof HTMLElement?`id: ${O.id} type:${Re(O)}`:O instanceof MediaStreamTrack?Vn(O):(JSON.stringify(O),O)}catch(G){return`type:${Re(O)}`}}let u=this._log||C;if(r!=null&&r(...c))return n.apply(this,c);c.length>0?u.info(`${a}() ${JSON.stringify(c,(S,O)=>l(S,O,["userSig","privateMapKey"]))}`):u.info(`${a}()`);let h=t?t(...c):ua[a],m=(o==null?void 0:o(...c))||!1;try{let S=n.apply(this,c),O=w();if(sr(S)){let K=`${a.includes("Plugin")?`${((D=(g=c[0]).getName)==null?void 0:D.call(g))||""} `:" "}`;return S.then(G=>(u.info(`${a}() success ${K}${i.call(this,...c)}`),b.addSuccessEvent({key:h,cost:w()-O}),G)).catch(G=>{var J;G=U.convertFrom.call(this,G,a,c.length===1?c[0]:c);let Z=G.extraCode||G.code,_e=(J=G.message)!=null&&J.includes(Z)?"":` code:${Z}`;throw m||u.error(`${a}() failed ${K}${i.call(this,...c)} ${G}${_e} params: ${JSON.stringify(c,l)}`),b.addFailedEvent({key:h,error:G}),G})}return b.addSuccessEvent({key:h}),S}catch(S){S=U.convertFrom.call(this,S,a);let O=S.extraCode||S.code,K=(_=S.message)!=null&&_.includes(O)?"":` code:${O}`;throw m||u.error(`${a}() failed ${S}${K} params: ${JSON.stringify(c,l)}`),b.addFailedEvent({key:h,error:S}),S}})}var dc=s=>Q((i,e)=>function(t,r){return f(this,null,function*(){let o=this._plugins.get(t);if(!o)throw this._log.error(`plugin ${String(t)} is not found`),new U({code:B.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});if(ne(o.constructor.isSupported)&&!o.constructor.isSupported())throw this._log.error(`plugin ${String(t)} is not supported`),new U({code:B.ENV_NOT_SUPPORTED,message:`plugin ${String(t)} is not supported`,extraCode:5210,fnName:e});return cc.call(this,o.getValidateRule(s),[r],e,"TRTC"),i.call(this,o,r)})});var lc=0,cu,ji=class ji{constructor(i){this.core=i;d(this,"log");d(this,"customAudioReferenceMap",new Map);d(this,"audioRefId",0);d(this,"audioContext",Ee());d(this,"localAudioWorkletNode");d(this,"screenAudioWorkletNode");d(this,"mixNode");d(this,"silentNode");lc=lc+1,this.log=i.log.createChild({id:`${this.getAlias()}${lc}`}),this.log.info(`created id=${this.getAlias()}${lc}`),i.assetsPath&&this.preload(`${i.assetsPath}/audioProcessor-wasm.js`)}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,o){if(!i.room.audioManager.hasAudioTrack&&!i.room.audioManager.hasScreenAudioTrack)throw new U({code:B.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return cu||(cu=this.doPreload(i)),cu}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield Bi(this.audioContext,t)}catch(r){this.log.error(`preload audioProcessor failed. ${r}`)}finally{URL.revokeObjectURL(t)}})}getName(){return ji.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(i){switch(i){case"start":return ji.getStartValidateRule(this.core);case"update":return ji.updateValidateRule;case"stop":return ji.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e}=this.core,{sdkAppId:t,userId:r,assetsPath:o,audioReference:n,processLevel:a,enableDump:c,isLocalAudioNeedAudioProcess:l=!0,isScreenAudioNeedAudioProcess:u=!0}=i;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=l,this.core.room.audioManager.isScreenAudioNeedAudioProcess=u,yield this.preload(`${o}/audioProcessor-wasm.js`),!this.localAudioWorkletNode||!this.screenAudioWorkletNode){let h=String(Date.now()).slice(0,-3),{auth:m,sign:g,status:D,message:_}=yield HT(L(N({},i),{timestamp:h}));if(!m)throw this.log.info(`audioProcessor: ${r} auth result: ${m}. Message: ${_}`),new U({code:B.INVALID_PARAMETER,message:_});this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",t,r,h,g,D,e),this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",t,r,h,g,D,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()),this.localAudioWorkletNode.port.postMessage({type:"enable"}),this.screenAudioWorkletNode.port.postMessage({type:"enable"}),e.audioManager.addAudioProcessor(this.localAudioWorkletNode,this.mixNode,this.silentNode,this.screenAudioWorkletNode),T(n)||n.forEach(h=>{this.customAudioReferenceMap.set(h,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:h,refId:`o-${this.audioRefId++}`})}),T(a)||this.localAudioWorkletNode.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:a}}),T(c)||this.localAudioWorkletNode.port.postMessage({type:"dump",data:{enable:c}})})}update(i){return f(this,null,function*(){if(!this.localAudioWorkletNode||!this.screenAudioWorkletNode)return;let{audioReference:e,enableDump:t,processLevel:r}=i;T(e)||(this.customAudioReferenceMap.forEach((o,n)=>{this.customAudioReferenceMap.delete(n),this.core.room.audioManager.updateAudioReference({type:"remove",refId:o})}),e.forEach(o=>{this.customAudioReferenceMap.set(o,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:o,refId:`o-${this.audioRefId++}`})})),T(r)||this.localAudioWorkletNode.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:r}}),T(t)||(this.localAudioWorkletNode.port.postMessage({type:"dump",data:{enable:t}}),this.screenAudioWorkletNode.port.postMessage({type:"dump",data:{enable:t}}))})}stop(){return f(this,null,function*(){if(!this.localAudioWorkletNode||!this.mixNode||!this.silentNode||!this.screenAudioWorkletNode)return;let{room:i}=this.core;this.localAudioWorkletNode.port.postMessage({type:"disable"}),this.screenAudioWorkletNode.port.postMessage({type:"disable"}),yield i.audioManager.removeAudioProcessor(this.localAudioWorkletNode,this.mixNode,this.silentNode,this.screenAudioWorkletNode)})}destroy(){this.localAudioWorkletNode&&(this.localAudioWorkletNode.port.onmessage=null),this.screenAudioWorkletNode&&(this.screenAudioWorkletNode.port.onmessage=null)}initWorkletNode(i,e,t,r,o,n,a,c){i.port.postMessage({type:"init",data:{sdkAppId:String(t),userId:r,timestamp:o,sign:n,status:a}}),i.port.onmessage=l=>{var h;let{data:u}=l;switch(u.type){case"cost":let m=(u==null?void 0:u.value)>10?"info":"debug";this.log[m](`[${e}] avg cost: ${u.value} max: ${u==null?void 0:u.max}(${es(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}] ${u.value}`);return;case"dump":E.emit("265",{room:c,data:u.value,type:e==="localAudio"?"dump":"dump-screen-audio"});return}}}};d(ji,"updateValidateRule",{type:"object"}),d(ji,"stopValidateRule",{type:"object"}),d(ji,"Name","AudioProcessor");var uc=ji;function $T(s,i=p.MAIN){return`https://${_i[i]||nc(s,i)}/api/v1/audioAiAuth`}function HT(r){return f(this,arguments,function*({sdkAppId:s,userId:i,userSig:e,timestamp:t}){let n=`${$T(s)}?sdkAppId=${s}&userId=${i}&userSig=${e}&timestamp=${t}`,a=yield fetch(n),{data:{errCode:c,errMsg:l,sign:u,status:h}}=yield a.json();if(h==="1")return{auth:!0,sign:u,status:h,message:l};let m=Ci(s)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",g="Init RTCAudioProcessor failed.",D="";switch(c){case 1:D="Please check your params.";break;case 2:D=`You need to buy packages. Refer to: ${m}`;break;case 3:D="Server is invalid. Please contact our engineer. ";break;case 4:D=`Your packages is not active. Refer to: ${m}`;break;case 5:D=`Your packages is expired. Refer to: ${m}`;break;case 6:D="Your version is not supported.";break}return{auth:!1,status:h,message:l?`${g} Reason: ${l}. ${D}`:`${g}, ${D}`}})}var hc=0,du=class{constructor(i,e){d(this,"player");d(this,"publisher");d(this,"mixInput");this.mixInput=new Ms(e),i.url?(this.player=new Audio(i.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(i.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(i.track),this.mixInput.connect()}updateSettings(i){this.player&&(T(i.volume)||(this.volume=i.volume),T(i.loop)||(this.loop=i.loop),T(i.playbackRate)||(this.playbackRate=i.playbackRate))}updateListener(i){if(this.player){if(i.onDurationChange){let{onDurationChange:e}=i;this.player.ondurationchange=t=>{e(t.target.duration)}}if(i.onTimeUpdate){let e=i.onTimeUpdate,{player:t}=this;t.ontimeupdate=()=>{e(t.currentTime,t.duration)}}i.onEnded&&(this.player.onended=i.onEnded)}}reset(){this.seek(0),this.mixInput.connect()}seek(i){this.player&&(i<0&&i>this.player.duration||(this.player.currentTime=i,this.publisher.currentTime=i))}play(){var i,e;return(i=this.publisher)==null||i.play(),(e=this.player)==null?void 0:e.play()}pause(){var i,e;(i=this.player)==null||i.pause(),(e=this.publisher)==null||e.pause()}stop(){var i;(i=this.player)==null||i.pause(),this.mixInput.disconnect()}setOperation(i){i==="pause"&&this.pause(),i==="resume"&&(this.pause(),this.play()),i==="stop"&&(this.pause(),this.seek(0))}set volume(i){!this.player||!this.publisher||(this.player.volume=i,this.publisher.volume=i)}set loop(i){!this.player||!this.publisher||(this.player.loop=i,this.publisher.loop=i)}set playbackRate(i){!this.player||!this.publisher||(this.player.playbackRate=i,this.publisher.playbackRate=i)}};function Js(s,i){if(i&&typeof i!="function")throw new U({code:B.INVALID_PARAMETER,message:`start audioMixer plugin: param ${s} should be a function.`})}var gi=class gi{constructor(i){this.core=i;d(this,"log");d(this,"mixedMusicMap",new Map);d(this,"cacheMusicMap",new Map);hc=hc+1,this.log=i.log.createChild({id:`${this.getAlias()}${hc}`}),this.log.info(`created id=${this.getAlias()}${hc}`)}getName(){return gi.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return gi.startValidateRule;case"update":return gi.updateValidateRule;case"stop":return gi.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e}=this.core;this.log.info(`add music source, id: ${i.id} url: ${i.url}, track: ${i.track}`);let{id:t,url:r}=i;if(this.mixedMusicMap.has(t))return;let o=this.cacheMusicMap.get(t);o?i.url?o.reset():(o.mixInput.replaceSource(i.track),o.mixInput.connect()):(o=new du(i,e.audioManager),this.cacheMusicMap.set(t,o)),o.updateListener(i),o.updateSettings(i),yield o.play(),this.mixedMusicMap.set(t,o),o.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"add",audioReference:o.mixInput.source.node,refId:`ax-${t}`}),this.log.info(`start mix audio track ${t} success.`),b.addEnum({key:502700,value:3}),this.kvUpload(i)})}update(i){return f(this,null,function*(){let{id:e,operation:t,seekFrom:r,playbackRate:o}=i;this.log.info(`update music source, ${JSON.stringify(i)}`);let n=this.mixedMusicMap.get(e);if(!n){this.log.warn(`update music source failed, music id: ${e} not found.`);return}n.updateSettings(i),n.updateListener(i),T(t)||n.setOperation(t),T(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:o,operation:n,seekFrom:a,onTimeUpdate:c,onDurationChange:l,onEnded:u}=i;e&&b.addCount({key:502711}),t&&b.addCount({key:502703}),r&&b.addCount({key:502704}),o&&b.addCount({key:502705}),n&&b.addCount({key:502706}),a&&b.addCount({key:502707}),typeof c!="function"&&b.addCount({key:502709}),typeof u!="function"&&b.addCount({key:502710}),typeof l!="function"&&b.addCount({key:502708})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((i,e)=>{i!=null&&i.mixInput.track&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:i.mixInput.track,refId:e}),this.stop({id:e})})}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}};d(gi,"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],o=["mp3","ogg","wav","flac"],n=r.split(".").pop(),a=o.indexOf(n)>=0,c=r.startsWith("blob"),l=r.startsWith("data");if(!(a||c||l))throw new U({code:B.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new U({code:B.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});Js("onTimeUpdate",i.onTimeUpdate),Js("onEnded",i.onEnded),Js("onDurationChange",i.onDurationChange)}}),d(gi,"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){Js("onTimeUpdate",i.onTimeUpdate),Js("onEnded",i.onEnded),Js("onDurationChange",i.onDurationChange)}}),d(gi,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),d(gi,"Name","AudioMixer");var mc=gi;var pc=0,lu,Xi=class Xi{constructor(i){this.core=i;d(this,"log");d(this,"audioContext",Ee("denoiser"));d(this,"workletNode");pc=pc+1,this.log=i.log.createChild({id:`${this.getAlias()}${pc}`}),this.log.info(`created id=${this.getAlias()}${pc}`),i.assetsPath&&this.preload(`${i.assetsPath}/denoiser-wasm.js`).catch(e=>{})}static startValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,t,r,o){if(!i.room.audioManager.hasAudioTrack)throw new U({code:B.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return lu||(lu=this.doPreload(i)),lu}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield Bi(this.audioContext,t)}catch(r){throw this.log.error("load worklet failed",r),r}finally{URL.revokeObjectURL(t)}})}getName(){return Xi.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(i){switch(i){case"start":return Xi.startValidateRule(this.core);case"update":return Xi.updateValidateRule;case"stop":return Xi.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e,schedule:t}=this.core;if(i.assetsPath&&(yield this.preload(`${i.assetsPath}/denoiser-wasm.js`)),!this.workletNode){let r=String(Date.now()).slice(0,-3),{auth:o,sign:n,status:a,message:c}=yield WT(t,L(N({},i),{timestamp:r}));if(!o)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${o}. Message: ${c}`),new U({code:B.INVALID_PARAMETER,message:c});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:r,sign:n,status:a}}),this.workletNode.port.onmessage=l=>{var h;let{data:u}=l;if(u.type==="cost"){let m=(u==null?void 0:u.max)>20?"warn":(u==null?void 0:u.max)>10?"info":"debug";this.log[m](`avg cost: ${u.value} max: ${u==null?void 0:u.max}(${es(new Date(u==null?void 0:u.maxCostTimestamp))}) hist: ${(h=u==null?void 0:u.hist)==null?void 0:h.join(" ")}`)}else u.type==="log"&&this.log[u.logLevel](`${u.value}`)}}this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(){return f(this,null,function*(){})}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)})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};d(Xi,"updateValidateRule",{type:"object"}),d(Xi,"stopValidateRule",{type:"object"}),d(Xi,"Name","AIDenoiser");var fc=Xi;function WT(o,n){return f(this,arguments,function*(s,{sdkAppId:i,userId:e,userSig:t,timestamp:r}){try{let{data:{errCode:a,errMsg:c,sign:l,status:u}}=yield s.getAbilityConfig(i,s.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:i,userId:e,userSig:t,timestamp:r});if(u==="1")return{auth:!0,sign:l,status:u,message:c};let h=Ci(i)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",m="Init RTCAIDenoiser failed.",g="";switch(a){case 1:g="Please check your params.";break;case 2:g=`You need to buy packages. Refer to: ${h}`;break;case 3:g="Server is invalid. Please contact our engineer. ";break;case 4:g=`Your packages is not active. Refer to: ${h}`;break;case 5:g=`Your packages is expired. Refer to: ${h}`;break;case 6:g="Your version is not supported.";break}return{auth:!1,status:u,message:c?`${m} Reason: ${c}. ${g}`:`${m}, ${g}`}}catch(a){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${a}`}}})}var dp=$e(Ye(),1);var uu=class extends dp.EventEmitter{constructor(){super();d(this,"observer");d(this,"state","nominal");this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return f(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!pe&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){re.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)&&C.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){re.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},JT=new uu,hu=JT;function mu([s,i]){let e=i.byteLength,t=parseInt(String(e/255),10),r=e%255,o=[];o.push(0,0,0,1,6,s);for(let a=0;a<t;a++)o.push(255);o.push(r);let n=new DataView(i);return o.push(...new Uint8Array(n.buffer)),o.push(128),new Hi(new DataView(new Uint8Array(o).buffer),!0)}function pu(s){return s.type==="empty"||s.data.byteLength===0}function fu(s){return s.getInt32(0)===1&&s.getInt8(4)===6}function _u(s){let i=0,e=0,t=new DataView(s);for(let r=0;r<s.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 gu({frame:s,seiMessageList:i}){if(!i||i.length===0||s.data.byteLength===0)return s;let t=9-_u(s.data);if(t<=0)return s;let r=i.splice(0,t).reverse().map(mu),o=r.reduce((u,h)=>u+h.dataView.byteLength,0),n=new ArrayBuffer(o+s.data.byteLength),a=new DataView(n),c=new DataView(s.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<s.data.byteLength;u++)a.setInt8(l++,c.getInt8(u));return s.data=n,s}function Tu({frame:s,onSEI:i}){try{let e=new DataView(s.data);if(pu(s)||!fu(e))return s;let t=[],r=0,o=-1,n=-1;for(let a=0;a<s.data.byteLength;a++){let c=e.getUint8(a);if(c===0)r++;else if(c===1){if(r===2||r===3){let l=a-r;if(o===-1?o=l:n===-1&&(n=l,t.push(new Hi(new DataView(e.buffer.slice(o,n)))),o=l,n=-1),!(e.getUint8(a+1)===6)){s.data=e.buffer.slice(l);break}}r=0}else r=0}i==null||i(t.reverse())}catch(e){}return s}var Eu=0,nn=class nn{constructor(i){this.core=i;d(this,"log");d(this,"_seiMessageList",[]);d(this,"_smallSeiMessageList",[]);d(this,"_subStreamSeiMessageList",[]);Eu++,this.log=i.log.createChild({id:`${this.getAlias()}${Eu}`}),this.log.info(`[sei] created id=${this.getAlias()}${Eu}`),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 gu({frame:i,seiMessageList:t})}catch(t){this.log.warn(t)}return i}decode({frame:i,track:e}){return Tu({frame:i,onSEI:t=>{t.forEach(r=>{this.core.trtc.emit(k.SEI_MESSAGE,{seiPayloadType:r.seiPayloadType,data:r.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"})})}})}destroy(){this.log.debug("destory"),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:Ui?this.encode:gu,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:Ui?this.decode:Tu,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update({buffer:i,options:e}){var o;let t=[e.seiPayloadType,i],r=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(t):(this._seiMessageList.push(t),r&&this._smallSeiMessageList.push(t)),(o=this.core.room.scriptTransformWorker)==null||o.postMessage({type:"sei",data:t,isMain:!e.toSubStream,small:r})}getName(){return nn.Name}getAlias(){return"sei"}getGroup(){return"sei"}};d(nn,"autoStart",!0),d(nn,"Name","SEI");var _c=nn;function Su({frame:s,onDump:i}){return i==null||i(),s}function Iu({frame:s,onDump:i}){return i==null||i(),s}var lp={"play() error: NotAllowedError:":{tips:s=>s.includes("main <video>")||s.includes("main <audio>")?"Remote stream auto play is restricted and playback fails":"Local stream playback failure, generally only occurs in Android WeChat devices, no need to handle",color:"red",class:"red"},"updateStream() try to recover local stream":{tips:"Device acquisition exception, automatic recovery is in progress"},"updateStream() recover local stream successfully":{tips:"Device acquisition exception, automatic recovery is successful"},"updateStream() failed to recover local stream":{tips:"Device acquisition exception, automatic recovery failed"},"main stream - video track is muted":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is muted":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is muted":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unable to provide media output":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is unable to provide media output":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is unable to provide media output":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unmuted":{tips:"Received enough playback video data"},"main stream - audio track is unmuted":{tips:"Received enough playback audio data"},"auxiliary stream - video track is unmuted":{tips:"Received enough playback screen sharing data"},"main stream - audio player track is ended":{tips:"Remote audio track stopped"},"main stream - video player track is ended":{tips:"Remote video track stopped"},"auxiliary stream - video player track is ended":{tips:"Received enough playback screen sharing data"},"stream - video track is muted":{tips:"Camera capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"stream - video track is unable to provide media output":{tips:"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked, and the customer needs to re-acquire. SDK v4.11.4+ will automatically resume acquisition without customer intervention",color:"orange"},"video track is unable to provide media output":{tips:s=>s.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"stream - audio track is muted":{tips:"Microphone capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"audio track is unable to provide media output":{tips:s=>s.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"Microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio track is unable to provide media output":{tips:"The microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"is adding audio track to current published local stream":{tips:"add audio track",color:"orange"},"is removing audio track from current published local stream":{tips:"remove audio track",color:"orange"},"is removing video track from current published local stream":{tips:"remove video track",color:"orange"},"is adding video track to current published local stream":{tips:"add video track",color:"orange"},"is replacing audio track to current published local main stream":{tips:"replace audio track",color:"orange"},"is replacing video track to current published local main stream":{tips:"replace video track",color:"orange"},"downlink network quality change":{tips:"Downstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"uplink network quality change":{tips:"Upstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"localStream mute video":{tips:"mute upstream video stream",color:"orange"},"localStream unmute video":{tips:"unmute upstream video stream",color:"orange"},"localStream mute audio":{tips:"mute upstream audio stream",color:"orange"},"localStream unmute audio":{tips:"unmute upstream audio stream",color:"orange"},"black detected":{tips:"Detect black screen, which means fps = 0. It is usually caused by network, and the network will be recovered after a while. If the network is normal but has not been restored, it is an abnormal situation."},'main stream start to play with options: {"muted":true}':{tips:"Play the remote stream in silent mode. Generally, the remote stream does not need to be played in silent mode. You need to confirm whether the parameters passed in the client stream.play API call are correct.",color:"orange"},"main stream - audio player is starting playing":{tips:"Remote stream audio playback success",color:"#0dd90d",class:"success"},"main stream - video player is starting playing":{tips:"Remote stream video playback success",color:"#0dd90d",class:"success"},"video player is playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"audio player is playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"stream - video player is starting playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"stream - audio player is starting playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"switch camera success":{tips:"Switch camera success",color:"#0dd90d",class:"success"},"switch microphone success":{tips:"Switch microphone success",color:"#0dd90d",class:"success"},gotStream:{tips:"Local stream capture success"},"local stream is published successfully":{tips:"Publish success",color:"#0dd90d",class:"success"},"encoderImplementation change to OpenH264":{tips:"Use software encoding"},"encoderImplementation change to ExternalEncoder":{tips:"Use hardware encoding"},"getUserMedia with constraints":{tips:"Start media (camera/microphone) capture"},"getDisplayMedia with constraints":{tips:"Start screen sharing capture"},"client-banned":{tips:"Kicked out of the room",color:"red",class:"red",textColor:"#fff"},user_timeout:{tips:"The backend is too long without receiving SDK heartbeat, which is usually caused by the JS thread being blocked for a long time. If the reproduction probability is high, the application browser Performance tool analyzes where the JS thread is blocked.",color:"red",class:"red",textColor:"#fff"},"schedule failed":{tips:"Signaling request failed, does not affect the normal room entry process, SDK will connect to the default signaling domain."},"updateStream() video flag is true, but no camera detected, set video to false":{tips:"When trying to resume camera acquisition, the camera acquisition is not resumed because it is detected that there is no camera.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to bandwidth":{tips:"bandwidth estimation is not enough to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to cpu":{tips:"cpu load is too high to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: hidden":{tips:"User page switched to backend, in mobile devices, this will cause the device to pause the capture, and it will be restored when the user switches backend to the frontend.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: visible":{tips:"User page switched to frontend",color:"orange",class:"orange",textColor:"#fff"},"main stream - audio player is paused":{tips:`The remote stream audio playback is paused, which usually has two possibilities:
57
+ ${r.stack}`),!1}},s};var Ws=new WeakMap;function rp(s){let i=Ws.get(s);i&&(i.forEach(e=>clearTimeout(e)),Ws.delete(s))}function sp(s,i){return Q((e,t)=>function(...r){let o=Ws.get(this);o||(o=new Map,Ws.set(this,o));let n=i(...r),a=o.get(n);if(!a||a<=0){e.apply(this,r);let c=setTimeout(()=>{var l;(l=Ws.get(this))==null||l.delete(n)},s);o.set(n,c)}else{clearTimeout(a);let c=window.setTimeout(()=>{var l;e.apply(this,r),(l=Ws.get(this))==null||l.delete(n)},s);o.set(n,c)}})}var np="trtc-sdk-v5",ap="5.11.0-beta.6";function Ge(...s){return Q((i,e)=>function(...t){try{cc.call(this,s,t,e,this._name)}catch(r){return Promise.reject(r)}return i.apply(this,t)})}function au(...s){return Q((i,e)=>function(...t){try{cc.call(this,s,t,e,this._name)}catch(r){throw r}return i.apply(this,t)})}function cc(s,i,e,t){if(Se(s))for(let r=0;r<s.length;r++)ac.call(this,{rule:s[r],value:i[r],key:s[r].name,fnName:e,className:t});else ac.call(this,{rule:s,value:i[0],key:s.name,fnName:e,className:t})}function ac({rule:s,value:i,key:e,fnName:t,className:r}){function o(c){return{code:B.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:s,value:i}}}if(T(i)){if(s.required)throw new U(o(5001));if(T(s.defaultValue)){ne(s.validate)&&s.validate.call(this,i,e,t,r,this);return}i=s.defaultValue}if(Array.isArray(s.type)){let c=!1;for(let l=0;l<s.type.length;l++)s.type[l]===null&&i===null&&(c=!0),ne(s.type[l])&&i instanceof s.type[l]&&(c=!0),ee(s.type[l])&&Re(i)===s.type[l].toLowerCase()&&(c=!0);if(!c)throw new U({code:B.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:s.type.map(l=>br(l)?os(l):ee(l)?l:Re(l))},value:i}})}else if(!T(s.type)&&Re(i)!==s.type)throw new U(o(5002));if(s.allowEmpty===!1){let c=q(i)&&(i===0||Number.isNaN(i)),l=ee(i)&&i.trim()==="";if(c||l)throw new U(o(5003))}if(s.notLessThanZero&&q(i)&&i<0)throw new U(o(5006));if(!T(s.min)&&q(i)&&i<s.min)throw new U(o(5007));if(!T(s.max)&&q(i)&&i>s.max)throw new U(o(5008));if(ee(s.instanceOf)){if(!i||i._name!==s.instanceOf)throw new U(o(5004))}else if(ne(s.instanceOf)&&!(i instanceof s.instanceOf))throw new U(o(5004));if(Array.isArray(s.values)&&!s.values.includes(i))throw new U(o(5005));let{properties:n}=s;Je(n)&&Mt(i)&&Object.keys(n).forEach(c=>{ac.call(this,{rule:n[c],value:i&&i[c],key:`${c}`,fnName:t,className:r})});let{arrayItem:a}=s;Je(a)&&Se(i)&&i.forEach((c,l)=>{ac.call(this,{rule:a,value:c,key:`${e}[${l}]`,fnName:t,className:r})}),ne(s.validate)&&s.validate.call(this,i,e,t,r,this)}function fe(s={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t,ignoreLog:r,ignoreErrorLog:o}=s;return Q((n,a)=>function(...c){var g,D,_;function l(S,O,K){if(K&&K.includes(S))return"hided";if(e){let G=e(...c);if(c[G.argIndex]===O)return G.value}if(O===c||S in c)return O;try{return O instanceof HTMLElement?`id: ${O.id} type:${Re(O)}`:O instanceof MediaStreamTrack?Vn(O):(JSON.stringify(O),O)}catch(G){return`type:${Re(O)}`}}let u=this._log||C;if(r!=null&&r(...c))return n.apply(this,c);c.length>0?u.info(`${a}() ${JSON.stringify(c,(S,O)=>l(S,O,["userSig","privateMapKey"]))}`):u.info(`${a}()`);let h=t?t(...c):ua[a],m=(o==null?void 0:o(...c))||!1;try{let S=n.apply(this,c),O=w();if(sr(S)){let K=`${a.includes("Plugin")?`${((D=(g=c[0]).getName)==null?void 0:D.call(g))||""} `:" "}`;return S.then(G=>(u.info(`${a}() success ${K}${i.call(this,...c)}`),b.addSuccessEvent({key:h,cost:w()-O}),G)).catch(G=>{var J;G=U.convertFrom.call(this,G,a,c.length===1?c[0]:c);let Z=G.extraCode||G.code,_e=(J=G.message)!=null&&J.includes(Z)?"":` code:${Z}`;throw m||u.error(`${a}() failed ${K}${i.call(this,...c)} ${G}${_e} params: ${JSON.stringify(c,l)}`),b.addFailedEvent({key:h,error:G}),G})}return b.addSuccessEvent({key:h}),S}catch(S){S=U.convertFrom.call(this,S,a);let O=S.extraCode||S.code,K=(_=S.message)!=null&&_.includes(O)?"":` code:${O}`;throw m||u.error(`${a}() failed ${S}${K} params: ${JSON.stringify(c,l)}`),b.addFailedEvent({key:h,error:S}),S}})}var dc=s=>Q((i,e)=>function(t,r){return f(this,null,function*(){let o=this._plugins.get(t);if(!o)throw this._log.error(`plugin ${String(t)} is not found`),new U({code:B.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});if(ne(o.constructor.isSupported)&&!o.constructor.isSupported())throw this._log.error(`plugin ${String(t)} is not supported`),new U({code:B.ENV_NOT_SUPPORTED,message:`plugin ${String(t)} is not supported`,extraCode:5210,fnName:e});return cc.call(this,o.getValidateRule(s),[r],e,"TRTC"),i.call(this,o,r)})});var lc=0,cu,ji=class ji{constructor(i){this.core=i;d(this,"log");d(this,"customAudioReferenceMap",new Map);d(this,"audioRefId",0);d(this,"audioContext",Ee());d(this,"localAudioWorkletNode");d(this,"screenAudioWorkletNode");d(this,"mixNode");d(this,"silentNode");lc=lc+1,this.log=i.log.createChild({id:`${this.getAlias()}${lc}`}),this.log.info(`created id=${this.getAlias()}${lc}`),i.assetsPath&&this.preload(`${i.assetsPath}/audioProcessor-wasm.js`)}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,o){if(!i.room.audioManager.hasAudioTrack&&!i.room.audioManager.hasScreenAudioTrack)throw new U({code:B.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return cu||(cu=this.doPreload(i)),cu}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield Bi(this.audioContext,t)}catch(r){this.log.error(`preload audioProcessor failed. ${r}`)}finally{URL.revokeObjectURL(t)}})}getName(){return ji.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(i){switch(i){case"start":return ji.getStartValidateRule(this.core);case"update":return ji.updateValidateRule;case"stop":return ji.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e}=this.core,{sdkAppId:t,userId:r,assetsPath:o,audioReference:n,processLevel:a,enableDump:c,isLocalAudioNeedAudioProcess:l=!0,isScreenAudioNeedAudioProcess:u=!0}=i;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=l,this.core.room.audioManager.isScreenAudioNeedAudioProcess=u,yield this.preload(`${o}/audioProcessor-wasm.js`),!this.localAudioWorkletNode||!this.screenAudioWorkletNode){let h=String(Date.now()).slice(0,-3),{auth:m,sign:g,status:D,message:_}=yield HT(L(N({},i),{timestamp:h}));if(!m)throw this.log.info(`audioProcessor: ${r} auth result: ${m}. Message: ${_}`),new U({code:B.INVALID_PARAMETER,message:_});this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",t,r,h,g,D,e),this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",t,r,h,g,D,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()),this.localAudioWorkletNode.port.postMessage({type:"enable"}),this.screenAudioWorkletNode.port.postMessage({type:"enable"}),e.audioManager.addAudioProcessor(this.localAudioWorkletNode,this.mixNode,this.silentNode,this.screenAudioWorkletNode),T(n)||n.forEach(h=>{this.customAudioReferenceMap.set(h,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:h,refId:`o-${this.audioRefId++}`})}),T(a)||this.localAudioWorkletNode.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:a}}),T(c)||this.localAudioWorkletNode.port.postMessage({type:"dump",data:{enable:c}})})}update(i){return f(this,null,function*(){if(!this.localAudioWorkletNode||!this.screenAudioWorkletNode)return;let{audioReference:e,enableDump:t,processLevel:r}=i;T(e)||(this.customAudioReferenceMap.forEach((o,n)=>{this.customAudioReferenceMap.delete(n),this.core.room.audioManager.updateAudioReference({type:"remove",refId:o})}),e.forEach(o=>{this.customAudioReferenceMap.set(o,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:o,refId:`o-${this.audioRefId++}`})})),T(r)||this.localAudioWorkletNode.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:r}}),T(t)||(this.localAudioWorkletNode.port.postMessage({type:"dump",data:{enable:t}}),this.screenAudioWorkletNode.port.postMessage({type:"dump",data:{enable:t}}))})}stop(){return f(this,null,function*(){if(!this.localAudioWorkletNode||!this.mixNode||!this.silentNode||!this.screenAudioWorkletNode)return;let{room:i}=this.core;this.localAudioWorkletNode.port.postMessage({type:"disable"}),this.screenAudioWorkletNode.port.postMessage({type:"disable"}),yield i.audioManager.removeAudioProcessor(this.localAudioWorkletNode,this.mixNode,this.silentNode,this.screenAudioWorkletNode)})}destroy(){this.localAudioWorkletNode&&(this.localAudioWorkletNode.port.onmessage=null),this.screenAudioWorkletNode&&(this.screenAudioWorkletNode.port.onmessage=null)}initWorkletNode(i,e,t,r,o,n,a,c){i.port.postMessage({type:"init",data:{sdkAppId:String(t),userId:r,timestamp:o,sign:n,status:a}}),i.port.onmessage=l=>{var h;let{data:u}=l;switch(u.type){case"cost":let m=(u==null?void 0:u.value)>10?"info":"debug";this.log[m](`[${e}] avg cost: ${u.value} max: ${u==null?void 0:u.max}(${es(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}] ${u.value}`);return;case"dump":E.emit("265",{room:c,data:u.value,type:e==="localAudio"?"dump":"dump-screen-audio"});return}}}};d(ji,"updateValidateRule",{type:"object"}),d(ji,"stopValidateRule",{type:"object"}),d(ji,"Name","AudioProcessor");var uc=ji;function $T(s,i=p.MAIN){return`https://${_i[i]||nc(s,i)}/api/v1/audioAiAuth`}function HT(r){return f(this,arguments,function*({sdkAppId:s,userId:i,userSig:e,timestamp:t}){let n=`${$T(s)}?sdkAppId=${s}&userId=${i}&userSig=${e}&timestamp=${t}`,a=yield fetch(n),{data:{errCode:c,errMsg:l,sign:u,status:h}}=yield a.json();if(h==="1")return{auth:!0,sign:u,status:h,message:l};let m=Ci(s)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",g="Init RTCAudioProcessor failed.",D="";switch(c){case 1:D="Please check your params.";break;case 2:D=`You need to buy packages. Refer to: ${m}`;break;case 3:D="Server is invalid. Please contact our engineer. ";break;case 4:D=`Your packages is not active. Refer to: ${m}`;break;case 5:D=`Your packages is expired. Refer to: ${m}`;break;case 6:D="Your version is not supported.";break}return{auth:!1,status:h,message:l?`${g} Reason: ${l}. ${D}`:`${g}, ${D}`}})}var hc=0,du=class{constructor(i,e){d(this,"player");d(this,"publisher");d(this,"mixInput");this.mixInput=new Ms(e),i.url?(this.player=new Audio(i.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(i.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(i.track),this.mixInput.connect()}updateSettings(i){this.player&&(T(i.volume)||(this.volume=i.volume),T(i.loop)||(this.loop=i.loop),T(i.playbackRate)||(this.playbackRate=i.playbackRate))}updateListener(i){if(this.player){if(i.onDurationChange){let{onDurationChange:e}=i;this.player.ondurationchange=t=>{e(t.target.duration)}}if(i.onTimeUpdate){let e=i.onTimeUpdate,{player:t}=this;t.ontimeupdate=()=>{e(t.currentTime,t.duration)}}i.onEnded&&(this.player.onended=i.onEnded)}}reset(){this.seek(0),this.mixInput.connect()}seek(i){this.player&&(i<0&&i>this.player.duration||(this.player.currentTime=i,this.publisher.currentTime=i))}play(){var i,e;return(i=this.publisher)==null||i.play(),(e=this.player)==null?void 0:e.play()}pause(){var i,e;(i=this.player)==null||i.pause(),(e=this.publisher)==null||e.pause()}stop(){var i;(i=this.player)==null||i.pause(),this.mixInput.disconnect()}setOperation(i){i==="pause"&&this.pause(),i==="resume"&&(this.pause(),this.play()),i==="stop"&&(this.pause(),this.seek(0))}set volume(i){!this.player||!this.publisher||(this.player.volume=i,this.publisher.volume=i)}set loop(i){!this.player||!this.publisher||(this.player.loop=i,this.publisher.loop=i)}set playbackRate(i){!this.player||!this.publisher||(this.player.playbackRate=i,this.publisher.playbackRate=i)}};function Js(s,i){if(i&&typeof i!="function")throw new U({code:B.INVALID_PARAMETER,message:`start audioMixer plugin: param ${s} should be a function.`})}var gi=class gi{constructor(i){this.core=i;d(this,"log");d(this,"mixedMusicMap",new Map);d(this,"cacheMusicMap",new Map);hc=hc+1,this.log=i.log.createChild({id:`${this.getAlias()}${hc}`}),this.log.info(`created id=${this.getAlias()}${hc}`)}getName(){return gi.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return gi.startValidateRule;case"update":return gi.updateValidateRule;case"stop":return gi.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e}=this.core;this.log.info(`add music source, id: ${i.id} url: ${i.url}, track: ${i.track}`);let{id:t,url:r}=i;if(this.mixedMusicMap.has(t))return;let o=this.cacheMusicMap.get(t);o?i.url?o.reset():(o.mixInput.replaceSource(i.track),o.mixInput.connect()):(o=new du(i,e.audioManager),this.cacheMusicMap.set(t,o)),o.updateListener(i),o.updateSettings(i),yield o.play(),this.mixedMusicMap.set(t,o),o.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"add",audioReference:o.mixInput.source.node,refId:`ax-${t}`}),this.log.info(`start mix audio track ${t} success.`),b.addEnum({key:502700,value:3}),this.kvUpload(i)})}update(i){return f(this,null,function*(){let{id:e,operation:t,seekFrom:r,playbackRate:o}=i;this.log.info(`update music source, ${JSON.stringify(i)}`);let n=this.mixedMusicMap.get(e);if(!n){this.log.warn(`update music source failed, music id: ${e} not found.`);return}n.updateSettings(i),n.updateListener(i),T(t)||n.setOperation(t),T(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:o,operation:n,seekFrom:a,onTimeUpdate:c,onDurationChange:l,onEnded:u}=i;e&&b.addCount({key:502711}),t&&b.addCount({key:502703}),r&&b.addCount({key:502704}),o&&b.addCount({key:502705}),n&&b.addCount({key:502706}),a&&b.addCount({key:502707}),typeof c!="function"&&b.addCount({key:502709}),typeof u!="function"&&b.addCount({key:502710}),typeof l!="function"&&b.addCount({key:502708})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((i,e)=>{i!=null&&i.mixInput.track&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:i.mixInput.track,refId:e}),this.stop({id:e})})}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}};d(gi,"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],o=["mp3","ogg","wav","flac"],n=r.split(".").pop(),a=o.indexOf(n)>=0,c=r.startsWith("blob"),l=r.startsWith("data");if(!(a||c||l))throw new U({code:B.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new U({code:B.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});Js("onTimeUpdate",i.onTimeUpdate),Js("onEnded",i.onEnded),Js("onDurationChange",i.onDurationChange)}}),d(gi,"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){Js("onTimeUpdate",i.onTimeUpdate),Js("onEnded",i.onEnded),Js("onDurationChange",i.onDurationChange)}}),d(gi,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),d(gi,"Name","AudioMixer");var mc=gi;var pc=0,lu,Xi=class Xi{constructor(i){this.core=i;d(this,"log");d(this,"audioContext",Ee("denoiser"));d(this,"workletNode");pc=pc+1,this.log=i.log.createChild({id:`${this.getAlias()}${pc}`}),this.log.info(`created id=${this.getAlias()}${pc}`),i.assetsPath&&this.preload(`${i.assetsPath}/denoiser-wasm.js`).catch(e=>{})}static startValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,t,r,o){if(!i.room.audioManager.hasAudioTrack)throw new U({code:B.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return lu||(lu=this.doPreload(i)),lu}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield Bi(this.audioContext,t)}catch(r){throw this.log.error("load worklet failed",r),r}finally{URL.revokeObjectURL(t)}})}getName(){return Xi.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(i){switch(i){case"start":return Xi.startValidateRule(this.core);case"update":return Xi.updateValidateRule;case"stop":return Xi.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e,schedule:t}=this.core;if(i.assetsPath&&(yield this.preload(`${i.assetsPath}/denoiser-wasm.js`)),!this.workletNode){let r=String(Date.now()).slice(0,-3),{auth:o,sign:n,status:a,message:c}=yield WT(t,L(N({},i),{timestamp:r}));if(!o)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${o}. Message: ${c}`),new U({code:B.INVALID_PARAMETER,message:c});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:r,sign:n,status:a}}),this.workletNode.port.onmessage=l=>{var h;let{data:u}=l;if(u.type==="cost"){let m=(u==null?void 0:u.max)>20?"warn":(u==null?void 0:u.max)>10?"info":"debug";this.log[m](`avg cost: ${u.value} max: ${u==null?void 0:u.max}(${es(new Date(u==null?void 0:u.maxCostTimestamp))}) hist: ${(h=u==null?void 0:u.hist)==null?void 0:h.join(" ")}`)}else u.type==="log"&&this.log[u.logLevel](`${u.value}`)}}this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(){return f(this,null,function*(){})}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)})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};d(Xi,"updateValidateRule",{type:"object"}),d(Xi,"stopValidateRule",{type:"object"}),d(Xi,"Name","AIDenoiser");var fc=Xi;function WT(o,n){return f(this,arguments,function*(s,{sdkAppId:i,userId:e,userSig:t,timestamp:r}){try{let{data:{errCode:a,errMsg:c,sign:l,status:u}}=yield s.getAbilityConfig(i,s.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:i,userId:e,userSig:t,timestamp:r});if(u==="1")return{auth:!0,sign:l,status:u,message:c};let h=Ci(i)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",m="Init RTCAIDenoiser failed.",g="";switch(a){case 1:g="Please check your params.";break;case 2:g=`You need to buy packages. Refer to: ${h}`;break;case 3:g="Server is invalid. Please contact our engineer. ";break;case 4:g=`Your packages is not active. Refer to: ${h}`;break;case 5:g=`Your packages is expired. Refer to: ${h}`;break;case 6:g="Your version is not supported.";break}return{auth:!1,status:u,message:c?`${m} Reason: ${c}. ${g}`:`${m}, ${g}`}}catch(a){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${a}`}}})}var dp=$e(Ye(),1);var uu=class extends dp.EventEmitter{constructor(){super();d(this,"observer");d(this,"state","nominal");this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return f(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!pe&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){re.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)&&C.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){re.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},JT=new uu,hu=JT;function mu([s,i]){let e=i.byteLength,t=parseInt(String(e/255),10),r=e%255,o=[];o.push(0,0,0,1,6,s);for(let a=0;a<t;a++)o.push(255);o.push(r);let n=new DataView(i);return o.push(...new Uint8Array(n.buffer)),o.push(128),new Hi(new DataView(new Uint8Array(o).buffer),!0)}function pu(s){return s.type==="empty"||s.data.byteLength===0}function fu(s){return s.getInt32(0)===1&&s.getInt8(4)===6}function _u(s){let i=0,e=0,t=new DataView(s);for(let r=0;r<s.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 gu({frame:s,seiMessageList:i}){if(!i||i.length===0||s.data.byteLength===0)return s;let t=9-_u(s.data);if(t<=0)return s;let r=i.splice(0,t).reverse().map(mu),o=r.reduce((u,h)=>u+h.dataView.byteLength,0),n=new ArrayBuffer(o+s.data.byteLength),a=new DataView(n),c=new DataView(s.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<s.data.byteLength;u++)a.setInt8(l++,c.getInt8(u));return s.data=n,s}function Tu({frame:s,onSEI:i}){try{let e=new DataView(s.data);if(pu(s)||!fu(e))return s;let t=[],r=0,o=-1,n=-1;for(let a=0;a<s.data.byteLength;a++){let c=e.getUint8(a);if(c===0)r++;else if(c===1){if(r===2||r===3){let l=a-r;if(o===-1?o=l:n===-1&&(n=l,t.push(new Hi(new DataView(e.buffer.slice(o,n)))),o=l,n=-1),!(e.getUint8(a+1)===6)){s.data=e.buffer.slice(l);break}}r=0}else r=0}i==null||i(t.reverse())}catch(e){}return s}var Eu=0,nn=class nn{constructor(i){this.core=i;d(this,"log");d(this,"_seiMessageList",[]);d(this,"_smallSeiMessageList",[]);d(this,"_subStreamSeiMessageList",[]);Eu++,this.log=i.log.createChild({id:`${this.getAlias()}${Eu}`}),this.log.info(`[sei] created id=${this.getAlias()}${Eu}`),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 gu({frame:i,seiMessageList:t})}catch(t){this.log.warn(t)}return i}decode({frame:i,track:e}){return Tu({frame:i,onSEI:t=>{t.forEach(r=>{this.core.trtc.emit(k.SEI_MESSAGE,{seiPayloadType:r.seiPayloadType,data:r.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"})})}})}destroy(){this.log.debug("destory"),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:Ui?this.encode:gu,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:Ui?this.decode:Tu,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update({buffer:i,options:e}){var o;let t=[e.seiPayloadType,i],r=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(t):(this._seiMessageList.push(t),r&&this._smallSeiMessageList.push(t)),(o=this.core.room.scriptTransformWorker)==null||o.postMessage({type:"sei",data:t,isMain:!e.toSubStream,small:r})}getName(){return nn.Name}getAlias(){return"sei"}getGroup(){return"sei"}};d(nn,"autoStart",!0),d(nn,"Name","SEI");var _c=nn;function Su({frame:s,onDump:i}){return i==null||i(),s}function Iu({frame:s,onDump:i}){return i==null||i(),s}var lp={"play() error: NotAllowedError:":{tips:s=>s.includes("main <video>")||s.includes("main <audio>")?"Remote stream auto play is restricted and playback fails":"Local stream playback failure, generally only occurs in Android WeChat devices, no need to handle",color:"red",class:"red"},"updateStream() try to recover local stream":{tips:"Device acquisition exception, automatic recovery is in progress"},"updateStream() recover local stream successfully":{tips:"Device acquisition exception, automatic recovery is successful"},"updateStream() failed to recover local stream":{tips:"Device acquisition exception, automatic recovery failed"},"main stream - video track is muted":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is muted":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is muted":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unable to provide media output":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is unable to provide media output":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is unable to provide media output":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unmuted":{tips:"Received enough playback video data"},"main stream - audio track is unmuted":{tips:"Received enough playback audio data"},"auxiliary stream - video track is unmuted":{tips:"Received enough playback screen sharing data"},"main stream - audio player track is ended":{tips:"Remote audio track stopped"},"main stream - video player track is ended":{tips:"Remote video track stopped"},"auxiliary stream - video player track is ended":{tips:"Received enough playback screen sharing data"},"stream - video track is muted":{tips:"Camera capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"stream - video track is unable to provide media output":{tips:"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked, and the customer needs to re-acquire. SDK v4.11.4+ will automatically resume acquisition without customer intervention",color:"orange"},"video track is unable to provide media output":{tips:s=>s.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"stream - audio track is muted":{tips:"Microphone capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"audio track is unable to provide media output":{tips:s=>s.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"Microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio track is unable to provide media output":{tips:"The microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"is adding audio track to current published local stream":{tips:"add audio track",color:"orange"},"is removing audio track from current published local stream":{tips:"remove audio track",color:"orange"},"is removing video track from current published local stream":{tips:"remove video track",color:"orange"},"is adding video track to current published local stream":{tips:"add video track",color:"orange"},"is replacing audio track to current published local main stream":{tips:"replace audio track",color:"orange"},"is replacing video track to current published local main stream":{tips:"replace video track",color:"orange"},"downlink network quality change":{tips:"Downstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"uplink network quality change":{tips:"Upstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"localStream mute video":{tips:"mute upstream video stream",color:"orange"},"localStream unmute video":{tips:"unmute upstream video stream",color:"orange"},"localStream mute audio":{tips:"mute upstream audio stream",color:"orange"},"localStream unmute audio":{tips:"unmute upstream audio stream",color:"orange"},"black detected":{tips:"Detect black screen, which means fps = 0. It is usually caused by network, and the network will be recovered after a while. If the network is normal but has not been restored, it is an abnormal situation."},'main stream start to play with options: {"muted":true}':{tips:"Play the remote stream in silent mode. Generally, the remote stream does not need to be played in silent mode. You need to confirm whether the parameters passed in the client stream.play API call are correct.",color:"orange"},"main stream - audio player is starting playing":{tips:"Remote stream audio playback success",color:"#0dd90d",class:"success"},"main stream - video player is starting playing":{tips:"Remote stream video playback success",color:"#0dd90d",class:"success"},"video player is playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"audio player is playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"stream - video player is starting playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"stream - audio player is starting playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"switch camera success":{tips:"Switch camera success",color:"#0dd90d",class:"success"},"switch microphone success":{tips:"Switch microphone success",color:"#0dd90d",class:"success"},gotStream:{tips:"Local stream capture success"},"local stream is published successfully":{tips:"Publish success",color:"#0dd90d",class:"success"},"encoderImplementation change to OpenH264":{tips:"Use software encoding"},"encoderImplementation change to ExternalEncoder":{tips:"Use hardware encoding"},"getUserMedia with constraints":{tips:"Start media (camera/microphone) capture"},"getDisplayMedia with constraints":{tips:"Start screen sharing capture"},"client-banned":{tips:"Kicked out of the room",color:"red",class:"red",textColor:"#fff"},user_timeout:{tips:"The backend is too long without receiving SDK heartbeat, which is usually caused by the JS thread being blocked for a long time. If the reproduction probability is high, the application browser Performance tool analyzes where the JS thread is blocked.",color:"red",class:"red",textColor:"#fff"},"schedule failed":{tips:"Signaling request failed, does not affect the normal room entry process, SDK will connect to the default signaling domain."},"updateStream() video flag is true, but no camera detected, set video to false":{tips:"When trying to resume camera acquisition, the camera acquisition is not resumed because it is detected that there is no camera.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to bandwidth":{tips:"bandwidth estimation is not enough to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to cpu":{tips:"cpu load is too high to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: hidden":{tips:"User page switched to backend, in mobile devices, this will cause the device to pause the capture, and it will be restored when the user switches backend to the frontend.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: visible":{tips:"User page switched to frontend",color:"orange",class:"orange",textColor:"#fff"},"main stream - audio player is paused":{tips:`The remote stream audio playback is paused, which usually has two possibilities:
58
58
  1. The business side passes in the div tag container for playing audio and video to be removed by the business side from the DOM.
59
59
  2. If the user is in Chrome 70 and below, when the div container is moved, the playback will be paused.`,color:"orange",class:"orange",textColor:"#fff"},"main stream - video player is paused":{tips:`The remote stream video playback is paused, which usually has two possibilities:
60
60
  1. The business side passes in the div tag container for playing audio and video to be removed by the business side from the DOM.
@@ -118,4 +118,4 @@ offer: ${t==null?void 0:t.sdp}`),o}})}setIceServers(e){return f(this,null,functi
118
118
  next offer: ${this.filterSDPDirection(e==null?void 0:e.sdp)}`),this._log.warn(`current answer: ${this.filterSDPDirection((a=this._peerConnection.remoteDescription)==null?void 0:a.sdp)}
119
119
  next answer: ${this.filterSDPDirection(t)}`),this._log.warn(`offer: ${e==null?void 0:e.sdp}`),this._log.warn(`answer: ${t}`),this._log.warn(`transceivers: ${JSON.stringify(this._peerConnection.getTransceivers().map(({mid:l,currentDirection:u,direction:h,stopped:m})=>({mid:l,currentDirection:u,direction:h,stopped:m})))}`),this._log.warn(`parsedAnswer: ${JSON.stringify(this._parsedAnswer)}`),this._isSDPLogged=!0),this._updateSDPPromise=null,o(c)}})),this._updateSDPPromise}setTransceiverDirection(e,t){return f(this,null,function*(){if(!ae||!this._peerConnection||!this._parsedAnswer)return;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let r=this._peerConnection.getTransceivers();t.forEach(o=>{r[o].direction!==e&&(r[o].direction=e)});for(let o of t){let n=this._parsedAnswer.media[o].direction;e===te.INACTIVE&&n===te.RECVONLY&&(this._parsedAnswer.media[o].direction=e),e===te.SENDONLY&&n===te.INACTIVE&&(this._parsedAnswer.media[o].direction=te.RECVONLY)}yield this.updateSDP()})}filterSDPDirection(e=""){return ye(e).media.map(r=>r.direction)}setOffer(e){this._log.info("setting offer");let t=Jp(e.sdp,this.clientAbility,this._serverAbility);return this._log.debug(t),this._peerConnection.setLocalDescription({type:"offer",sdp:t})}setAnswer(e){return this._log.info("setting answer"),this._log.debug(e.sdp),this._peerConnection.setRemoteDescription(e)}switchVideoEncoder(e){return f(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let t=!1;this._parsedAnswer.media.forEach(r=>{var o;if(r.type===p.VIDEO){let n=this._serverAbility.video.codecs.find(a=>a.codec.toLowerCase()===e);n&&!((o=r.payloads)!=null&&o.includes(String(n.payload)))&&(r.fmtp=[],r.payloads="",r.rtp=[],r.rtcpFb=[],Zr(r,n),t=!0)}}),t&&(this._log.warn(`switch video encoder to ${e}`),yield this.updateSDP())})}useHWEncoder(e=!0,t){return f(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let r=!1,o=[];T(t)?o=this._parsedAnswer.media.slice(1,4):t===2?o.push(this._parsedAnswer.media[1]):t===3?o.push(this._parsedAnswer.media[2]):t===7&&o.push(this._parsedAnswer.media[3]),o.forEach(n=>{var a;if(n.type===p.VIDEO){let c;e&&this.is42001fSupported?c=this.clientAbility.video.codecs.find(l=>l.fmtp.includes("42001f")):e||(c=this._serverAbility.video.codecs.find(l=>l.codec.toLowerCase()===(this._serverAbility.useVp8?"vp8":"h264"))),c&&!((a=n.payloads)!=null&&a.includes(String(c.payload)))&&(n.fmtp=[],n.payloads="",n.rtp=[],n.rtcpFb=[],Zr(n,c),r=!0)}}),r&&(this._log.warn(`use ${e?"hw":"sw"} encoder`),yield this.updateSDP())})}sendDataChannelMessage(e){var t;(t=this._datachannel)==null||t.send(e)}reset(){var e;this._peerConnection&&(this._peerConnection.close(),this._peerConnection.removeEventListener("track",this._peerConnection._onaddstreampoly,this),this._peerConnection._onaddstreampoly=null,this._peerConnection=null),(e=this.clearWaitForConnectedPromise)==null||e.call(this),this._parsedAnswer=null,this.originOffer=null}close(){this._log.info("close pc"),this.removeRTCListener(),this.insertableStreamsAbortMap.forEach(e=>Qt(e.abort)&&e.abort("destroy")),this.insertableStreamsAbortMap.clear(),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners(),this._room.healthDetector.off("1",this.onBadHealth,this)}getReceiversByUserId(e){if(!this._peerConnection)return[];let t=this._peerConnection.getReceivers();return(this._downlinkMIDMap.get(e)||[]).map(r=>t[r])}get isUsingRelay(){return this._room.getIceTransportPolicy()==="relay"}detectTCPAndUDP({uplinkRTT:e,downlinkRTT:t}){var u;if(this.currentState!=="CONNECTED"||this._isRelayTried&&!this._room.forceRelay||this._room.getIceServers().length===0)return;let r=this._signalChannel.rtt,o=Math.max(e,t),{rttRatioThreshold:n,rttThreshold:a}=((u=this._room.scheduleResult.config)==null?void 0:u.useTurnTcpInfo)||{};if(!n||!a||!r||!o)return;let c=Math.floor(o/r),l=(this._isRelayTried||c>n)&&o>a;if(!l){this._rttOverCount=0;return}++this._rttOverCount<5||(this._log.warn(`detectTCPAndUDP ws-rtt: ${r} upRTT: ${e} downRTT: ${t} ratio: ${c} over-count: ${this._rttOverCount} isOver: ${l} isRelayTried: ${this._isRelayTried} force-relay: ${this._room.forceRelay}`),!this.isUsingRelay&&!this._isRelayTried?(this._isRelayTried=!0,this._rttOverCount=0,this.switchRelay(!0)):this._room.forceRelay&&this.switchRelay(!1))}switchRelay(e,t=!1){return f(this,null,function*(){if(this.isUsingRelay===e)return;let r=e?"relay":"udp",o=e?521709:521710;try{this._room.forceRelay=e,this._log.warn(`switchRelay ${r}`);let n=Date.now();yield this.doSwitchRelay(r),this._log.warn(`switchRelay ${r} success`),b.addSuccessEvent({key:o,cost:Date.now()-n})}catch(n){this._log.warn(`switchRelay ${r} failed`,n),b.addFailedEvent({key:o,error:n}),t?this._room.reJoin():yield this.switchRelay(!e,!0)}})}doSwitchRelay(e){return new Promise((t,r)=>{let o=setTimeout(()=>{this.stopReconnection(),r(new Error(`switch ${e} timeout`))},1e4);this.startReconnection().then(t,r).finally(()=>clearTimeout(o))})}removeRTCListener(){this._peerConnection&&(this._peerConnection.oniceconnectionstatechange=null,this._peerConnection.onconnectionstatechange=null,this._peerConnection.onsignalingstatechange=null,this._peerConnection.ontrack=null),this.dtlsTransport&&(this.dtlsTransport.onstatechange=null)}};v([xa("reconnect")],qt.prototype,"startReconnection",1),v([$i(e=>e.userId)],qt.prototype,"addDownlink",1),v([$i(e=>e)],qt.prototype,"removeDownlink",1),v([Rt(!0)],qt.prototype,"updateSDP",1),v([at(521712,!1)],qt.prototype,"setOffer",1),v([at(521713,!1)],qt.prototype,"setAnswer",1);var $u=class{constructor(i){d(this,"tag");d(this,"len");d(this,"data");let e=new DataView(i);this.tag=e.getUint16(),this.len=e.getUint16(2),this.data=new Uint8Array(i).slice(4,4+this.len).buffer}},Hu=class{constructor(i){d(this,"tinyId");d(this,"data");let e=new DataView(i),t=0,r=[];for(;t<e.byteLength;){let o=e.getUint16(t+2),n=new $u(new Uint8Array(i).slice(t,t+2+2+o).buffer);r.push(n),t+=4+o}r.forEach(o=>{o.tag===1?this.tinyId=new TextDecoder().decode(o.data):o.tag===2&&(this.data=o.data)})}},Yp=new Set;function Et(){let s=Math.floor(Math.random()*4294967296);return Yp.has(s)?Et():(Yp.add(s),s)}var tf=$e(Ye());var Kr=class extends tf.default{constructor(e){super();d(this,"userId");d(this,"tinyId");d(this,"_sdpSemantics");d(this,"_isUplink");d(this,"_room");d(this,"_log");d(this,"_currentState","DISCONNECTED");d(this,"_prevTime",-1);d(this,"_blackSmallVideoDetectionId");this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=C.createLogger({id:"n",userId:this._room.userId,remoteUserId:this._isUplink?void 0:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink})}get _peerConnection(){var e;return((e=this.singlePC)==null?void 0:e.getPeerConnection())||null}get singlePC(){return this._room.singlePC}get _signalChannel(){return this._room.signalChannel}close(e){this._log.info("close connection"),this.emit("closed",e)}emitConnectionStateChangedEvent(e){return e===this._currentState?!1:(E.emit(A.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:e,remoteUserId:this._isUplink?void 0:this.userId}),this.emit("connection-state-changed",{prevState:this._currentState,state:e}),this._currentState=e,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}getCurrentState(){return this._currentState}get isH264(){var e,t;return!!((t=(e=this._peerConnection)==null?void 0:e.remoteDescription)!=null&&t.sdp.includes("H264"))}};var Gu=class{constructor(){d(this,"worker");d(this,"callbacks",new Map);d(this,"_log");d(this,"sleep",{});d(this,"heartbeatListenerCleaner",new Map);d(this,"userIdMap",new Map);this._log=C.createLogger({id:"bvd"})}getWorker(){if(!this.worker){let i=`
120
120
  const tracks=new Map;let canvas,ctx;const log=(...t)=>postMessage({type:"log",message:"[worker] "+t.join(" ")});function startDetection(e,t,a){if(!tracks.has(e)){const c={reader:a.getReader(),blackCount:0,timeoutId:null,intervalId:null};tracks.set(e,c),c.timeoutId=setTimeout(()=>stopDetection(e,"timeout"),t),c.intervalId=setInterval(async()=>{try{await isFrameBlack(e)?(c.blackCount++,postMessage({type:"blackCount",trackId:e,count:c.blackCount}),3<=c.blackCount&&(postMessage({type:"black",trackId:e}),stopDetection(e,"black"))):c.blackCount=0}catch(t){log("check black video error:",t.message),stopDetection(e,"error")}},1e3)}}function stopDetection(t,e){var a=tracks.get(t);a&&(a.timeoutId&&clearTimeout(a.timeoutId),a.intervalId&&clearInterval(a.intervalId),a.reader&&a.reader.cancel(),tracks.delete(t),postMessage({type:e,trackId:t}))}async function isFrameBlack(t){t=tracks.get(t);if(!t)return!1;var t=t.reader,{done:t,value:e}=await t.read();if(!e||t)return!1;canvas||(canvas=new OffscreenCanvas(e.codedWidth,e.codedHeight),ctx=canvas.getContext("2d",{willReadFrequently:!0})),canvas.width===e.codedWidth&&canvas.height===e.codedHeight||(canvas.width=e.codedWidth,canvas.height=e.codedHeight,ctx=canvas.getContext("2d",{willReadFrequently:!0})),ctx.drawImage(e,0,0,canvas.width,canvas.height);t=getFrameBlackRatio(ctx.getImageData(0,0,canvas.width,canvas.height));return e.close(),1===t}function getFrameBlackRatio(t){var e=t.data;let a=0;for(let t=0;t<100;t++){var c=4*Math.floor(Math.random()*(e.length/4)),[c,r,n,o]=[e[c],e[1+c],e[2+c],e[3+c]];0<o&&0===c&&0===r&&0===n&&a++}return a/100}self.onmessage=t=>{var{type:t,trackId:e,timeout:a,readable:c}=t.data;"addTrack"===t&&startDetection(e,a,c),"removeTrack"===t&&stopDetection(e)};
121
- `,e=new Blob([i],{type:"application/javascript"}),t=URL.createObjectURL(e);this.worker=new Worker(t),URL.revokeObjectURL(t),this.worker.onerror=r=>this._log.warn("worker error:",r.message,r.filename||"unknown",r.lineno||"unknown"),this.worker.onmessage=r=>{var l;let{type:o,trackId:n,message:a,count:c}=r.data;if(o==="black")(l=this.callbacks.get(n))==null||l();else if(o==="log")this._log.warn(a);else if(o==="blackCount"){let u=this.userIdMap.get(n);this._log.warn(`${u||n} black count: ${c}`)}}}return this.worker}start({track:i,isUplink:e,room:t,userId:r,onBlack:o}){if(this._log.debug("start detect black video",i.id),!ko()||!o||!i||T(Worker))return;let n=a=>{var l,u,h,m;let c;if(e)c=(u=(l=a.msg_up_stream_info)==null?void 0:l.msg_video_status)==null?void 0:u.filter(g=>g.uint32_video_stream_type===3)[0];else{let g=(h=a.msg_down_stream_info)==null?void 0:h.filter(D=>{var _;return((_=D.msg_user_info)==null?void 0:_.str_identifier)===r})[0];c=(m=g==null?void 0:g.msg_video_status)==null?void 0:m.filter(D=>D.uint32_video_stream_type===3)[0]}if(c){let g=(c.uint32_video_codec_bitrate||0)/1e3;if(this.sleep[i.id]&&this.sleep[i.id]>0){this.sleep[i.id]-=1;return}g>0&&g<10&&(this.sleep[i.id]=30,this._log.debug("track bitrate",g,"start check"),this.checkOnce(i,30*1e3))}};return t.on("heartbeat-report",n),this.heartbeatListenerCleaner.set(i.id,()=>t.off("heartbeat-report",n)),this.callbacks.set(i.id,o),this.userIdMap.set(i.id,r),i.id}checkOnce(i,e){try{let t=this.getWorker();if(!t)throw new Error("Worker not available");let r=new MediaStreamTrackProcessor({track:i});t.postMessage({type:"addTrack",trackId:i.id,timeout:e,readable:r.readable},[r.readable])}catch(t){this._log.warn("check error:",t),this.stop(i.id)}}stop(i){if(i){this.worker&&this.worker.postMessage({type:"removeTrack",trackId:i}),this.callbacks.delete(i),delete this.sleep[i];let e=this.heartbeatListenerCleaner.get(i);e&&e(),this.heartbeatListenerCleaner.delete(i),this.userIdMap.delete(i)}}destroy(){this.callbacks.forEach((i,e)=>this.stop(e)),this.worker&&(this.worker.terminate(),this.worker=null)}},Yi=new Gu;var Tn=class extends Kr{constructor(e){super(L(N({},e),{isUplink:!0}));d(this,"localMainAudioTrack",null);d(this,"localMainVideoTrack",null);d(this,"localAuxAudioTrack",null);d(this,"localAuxVideoTrack",null);d(this,"_isPublishingAux",!1);d(this,"_publishingLocalAudioTrack");d(this,"_publishingLocalVideoTrack");d(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});d(this,"_flag",0);d(this,"_checkPublishStateTimeoutId",-1);this.initialize()}get videoCodec(){var e;return((e=this.singlePC)==null?void 0:e.videoCodec)||"h264"}get ssrc(){if(!this.singlePC)return{audio:0,video:0,videoRtx:0,small:0,smallRtx:0,auxiliary:0,auxiliaryRtx:0};let{audioSsrc:e,bigVideoSsrc:t,bigVideoRtxSsrc:r,smallVideoSsrc:o,smallVideoRtxSsrc:n,auxVideoSsrc:a,auxVideoRtxSsrc:c}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:r||0,small:o||0,smallRtx:n||0,auxiliary:a||0,auxiliaryRtx:c||0}}get flag(){return this._flag}set flag(e){this._flag!==e&&(this._flag=e,this.checkPublishState())}checkPublishState(e=!1){if(!e&&this._checkPublishStateTimeoutId>0)return;let{publishState:t,serverPublishState:r}=this,o=Object.keys(t).find(n=>t[n]!==r[n]);if(o)if(e)this._log.warn(`publish state not matched, ${o} local:${t[o]} server:${r[o]} ${Pi()} ${Or()}`),b.addCount({key:521e3});else{this._checkPublishStateTimeoutId=oe.run("timeout",()=>this.checkPublishState(!0),{delay:10*1e3,count:1});return}oe.clearTask(this._checkPublishStateTimeoutId),this._checkPublishStateTimeoutId=-1}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}get publishState(){var t,r,o,n;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(si()?(e.audio=!!((t=a[0])!=null&&t.track),e.bigVideo=!!((r=a[1])!=null&&r.track),e.smallVideo=!!((o=a[2])!=null&&o.track),e.auxVideo=!!((n=a[3])!=null&&n.track)):a.forEach(c=>{c.track&&(c.track.kind===p.AUDIO?e.audio=!0:(e.bigVideo=!0,this._room.videoManager.hasSmall&&(e.smallVideo=!0)))}))}return e}get publishingState(){let{publishState:e}=this,t=N({},e);return this._publishingLocalAudioTrack&&(t.audio=!0),this._publishingLocalVideoTrack&&(this._isPublishingAux?t.auxVideo=!0:(t.bigVideo=!0,this._publishingLocalVideoTrack.small&&(t.smallVideo=!0))),t}get serverPublishState(){return{audio:!!(this.flag&ir),bigVideo:!!(this.flag&tr),smallVideo:!!(this.flag&so),auxVideo:!!(this.flag&Er)}}get muteState(){var e,t,r;return{audio:!!((e=this.localMainAudioTrack)!=null&&e.muted),bigVideo:!!((t=this.localMainVideoTrack)!=null&&t.muted),auxVideo:!!((r=this.localAuxVideoTrack)!=null&&r.muted)}}initialize(){this.installEvents()}close(e){var r;let t=((r=this._peerConnection)==null?void 0:r.getSenders())||[];for(let o of t)o.replaceTrack(null);super.close(e),this.uninstallEvents(),this.uninstallTrackMuteEvents(this.localMainAudioTrack,this.localMainVideoTrack,this.localAuxVideoTrack),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),this.installSPCEvents()}installSPCEvents(){var e,t;(e=this.singlePC)!=null&&e.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||(t=this.singlePC)==null||t.on("spc-reconnected",this.onSinglePCReconnected,this)}uninstallSPCEvents(){var e;(e=this.singlePC)==null||e.off("spc-reconnected",this.onSinglePCReconnected,this)}uninstallEvents(){this.off("connection-state-changed",this.handleConnectionStateChange,this),this.uninstallSPCEvents()}emitConnectionStateChangedEvent(e,t){var n,a,c;let r=this._currentState,o=super.emitConnectionStateChangedEvent(e);return o&&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}),(c=this._publishingLocalVideoTrack)==null||c.emit("connection-state-changed",{prevState:r,state:e}))),o}onVideoEncodeFailed(e){var t;e&&e.isMediaTrackActive&&this.videoCodec==="h264"&&(this._log.warn("h264 encoder not working"),(t=this.singlePC)!=null&&t.isVP8EncodeSupported&&(this._log.warn("switch to vp8"),this.singlePC.switchVideoEncoder("vp8")))}publish(o){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:r}){var l,u,h,m,g,D,_;if(!this.singlePC)return;this.installEvents(),yield this.singlePC.waitForPeerConnectionConnected();let{publishState:n,muteState:a}=this;if(e&&(this._publishingLocalAudioTrack=e,n.audio=!0,a.audio=e.muted),t){if(!this.singlePC.isH264EncodeSupported&&!this.singlePC.isVP8EncodeSupported)throw new y({code:I.NOT_SUPPORTED_H264,message:x({key:P.NOT_SUPPORTED_H264ENCODE})});this.singlePC.isUsingH264&&!this.singlePC.isH264EncodeSupported&&this.singlePC.isVP8EncodeSupported&&(this._log.warn("h264 encoder not supported"),yield this.singlePC.switchVideoEncoder("vp8")),pe&&Ss()===115&&t.profile.width*t.profile.height<=640*360&&(this._log.warn(`fallback video to defaultBigVideoProfile: ${JSON.stringify(er)}`),t.setProfile(er),yield t.applyProfile()),this._publishingLocalVideoTrack=t,r?(n.auxVideo=!0,a.auxVideo=t.muted):(n.bigVideo=!0,a.bigVideo=t.muted)}this._isPublishingAux=r;let c;if(t&&!r&&t.small&&(c=this._room.videoManager.smallTrack,n.smallVideo=!0),yield this._signalChannel.sendWaitForResponseWithRetry({command:Y.SPC_PUBLISH,responseCommand:F.SPC_PUBLISH_RESULT,data:L(N({},this.singlePC.uplinkSSRC),{state:n,muteState:a}),retries:3}),yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:c,isAuxiliary:r}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,t){this[r?"localAuxVideoTrack":"localMainVideoTrack"]=t,yield this.singlePC.setDegradationPreference(this._peerConnection.getSenders()[r?3:1],t.contentHint,t.streamType);let{scaleResolutionDownBy:S}=t;yield this.singlePC.setScaleResolutionDownBy(this._peerConnection.getSenders()[r?3:1],S,t.streamType)}e&&(this[r?"localAuxAudioTrack":"localMainAudioTrack"]=e),yield this.singlePC.setBandwidth({audio:((l=this.localMainAudioTrack)==null?void 0:l.profile.bitrate)||((u=this.localAuxAudioTrack)==null?void 0:u.profile.bitrate),bigVideo:(h=this.localMainVideoTrack)==null?void 0:h.profile.bitrate,smallVideo:(g=(m=this.localMainVideoTrack)==null?void 0:m.small)==null?void 0:g.bitrate,auxVideo:(D=this.localAuxVideoTrack)==null?void 0:D.profile.bitrate}),this.sendMediaSettings(),this.installTrackMuteEvents(e,t),(this._room.preferHW||(_=this._room.scheduleResult.config)!=null&&_.preferHW)&&t&&t.profile.width*t.profile.height>=1280*720&&this.singlePC.useHWEncoder(!0,r?7:2)})}publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:r,isAuxiliary:o}){if(!mt())return;this._log.info("publish by transceiver");let n=t==null?void 0:t.outMediaTrack,a=e==null?void 0:e.outMediaTrack,c=this._peerConnection.getTransceivers(),l=[],u=[],h=(g,D,_)=>{var O;let S=c[D].sender.replaceTrack(_);u.push(D),(O=this.singlePC)!=null&&O.enableInsertableStreams&&S.then(()=>this.createEncodedStreams(c[D].sender,g)),this.initSenderTransform(c[D].sender,g),l.push(S)};a&&h(e.mediaType,0,a),n&&h(t.mediaType,o?3:1,n),t!=null&&t.small&&l.push(this.publishSmall(this._room.videoManager.smallMode,t));let m=this.singlePC.setTransceiverDirection(te.SENDONLY,u);return l.push(m),Promise.all(l)}getTrackByMediaType(e){switch(e){case 1:return this.localMainAudioTrack||this._publishingLocalAudioTrack;case 4:case 8:return this.localMainVideoTrack||this._publishingLocalVideoTrack;case 2:return this.localAuxVideoTrack||this._publishingLocalVideoTrack;default:return null}}createEncodedStreams(e,t){var a,c;if(this.singlePC.insertableStreamsAbortMap.has(e))return;let r=e.createEncodedStreams(),o=new AbortController;(a=this.singlePC)==null||a.addAbortController(e,o),((c=this.getTrackByMediaType(t))!=null&&c.enableEncodeFrame?r.readable.pipeThrough(new TransformStream({transform:(l,u)=>{var m;let h=this.getTrackByMediaType(t);u.enqueue((m=this.singlePC)!=null&&m.isUsingH264&&h?h.encodeFrame(l,t===8):l)}}),o):r.readable).pipeTo(r.writable,o).catch(l=>{this._log.debug("encoded stream error",l),l!=="destory"&&this._log.warn(l)})}initSenderTransform(e,t){if(!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker||!Ns)return;let r=t!==2,o=t===8;e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!1,isAudio:t===1,isMain:r,isSmall:o}))}enableSmall(e){return f(this,null,function*(){e?yield this.publishSmall(this._room.videoManager.smallMode):yield this.unpublishSmall()})}publishSmall(r){return f(this,arguments,function*(e,t=this.localMainVideoTrack){var l;if(!this.singlePC)return;let o=this._peerConnection.getTransceivers(),{sender:n}=o[2],a=yield this.doPublishSmall(e,t),c=e==="canvas"?524700:524701;if(b.addSuccessEvent({key:c}),!a){b.addFailedEvent({key:c,error:10001});return}(l=this.singlePC)!=null&&l.enableInsertableStreams&&this.createEncodedStreams(n,8),this.initSenderTransform(n,8),yield this.singlePC.setTransceiverDirection(te.SENDONLY,[2]),this.updateMediaSettings(),yield this.doPublishChange(),this._blackSmallVideoDetectionId=Yi.start({track:n.track,room:this._room,isUplink:!0,userId:this.userId,onBlack:()=>{this._log.warn("small video is black");let u=e==="canvas"?524700:524701;b.addFailedEvent({key:u,error:10002}),Yi.stop(this._blackSmallVideoDetectionId)}})})}doPublishSmall(r){return f(this,arguments,function*(e,t=this.localMainVideoTrack){if(!this.singlePC)return null;this._log.info("publish small",e);let o=this._peerConnection.getTransceivers(),{sender:n}=o[2];if(e==="canvas"&&this._room.videoManager.smallTrack)return yield n.replaceTrack(this._room.videoManager.smallTrack),"canvas";if(e==="api"&&(t!=null&&t.outMediaTrack)&&(t!=null&&t.small)){yield n.replaceTrack(t==null?void 0:t.outMediaTrack);let a=n.getParameters(),c=ls(t==null?void 0:t.profile,t==null?void 0:t.small);return this._log.info("small scaleResolutionDownBy",c),a.encodings[0].scaleResolutionDownBy=c,n.setParameters(a),"api"}return this._log.warn(`small track can not be enabled, smallMode: ${this._room.videoManager.smallMode}, smallTrack: ${!!this._room.videoManager.smallTrack}, bigVideoTrack: ${!!(t!=null&&t.outMediaTrack)}`),null})}unpublishSmall(){return f(this,null,function*(){if(!this.singlePC)return;this._log.info("unpublish small"),yield this._peerConnection.getTransceivers()[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(te.INACTIVE,[2]),this.updateMediaSettings(),yield this.doPublishChange(),Yi.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0})}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}){var l;yield(l=this.singlePC)==null?void 0:l.waitForPeerConnectionConnected();let o=t&&t===this.localAuxVideoTrack,n=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),c=[];e&&(o?this.localAuxAudioTrack=null:this.localMainAudioTrack=null,!this.localMainAudioTrack&&!this.localAuxAudioTrack&&(yield a[0].replaceTrack(null),c.push(0))),n&&(o?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=L(N({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),c.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=L(N({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),c.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.singlePC.setTransceiverDirection(te.INACTIVE,c),yield this.doPublishChange(!1)):yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),t==null||t.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return f(this,null,function*(){let t={state:this.publishingState,constraintConfig:this._mediaSettings},r=yield this._signalChannel.sendWaitForResponseWithRetry({command:Y.PUBLISH_STATE_CHANGE,data:t,responseCommand:F.PUBLISH_STATE_CHANGE_RESULT,enableLog:e,retries:3});this.checkPublishResultCode(r.data.code,r.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:Y.UNPUBLISH,commandDesc:"unpublish",responseCommand:F.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===I.API_CALL_TIMEOUT)return Promise.resolve();throw t})}updateMediaSettings(){var o;this._mediaSettings.videoCodec=((o=this.singlePC)==null?void 0:o.videoCodec)||"h264";let e=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:t,localAuxVideoTrack:r}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?r=this._publishingLocalVideoTrack:t=this._publishingLocalVideoTrack),oi){if(e&&e.outMediaTrack){let n=e.outMediaTrack.getSettings();this._mediaSettings.audioChannel=n.channelCount||1,this._mediaSettings.audioBps=e.profile.bitrate*1e3,this._mediaSettings.audioFs=n.sampleRate||0}if(t&&t.outMediaTrack){let n=t.outMediaTrack.getSettings(),{scaleResolutionDownBy:a}=t;this._mediaSettings.videoWidth=n.width/a||0,this._mediaSettings.videoHeight=n.height/a||0,this._mediaSettings.videoFps=n.frameRate||0,this._mediaSettings.videoBps=t.profile.bitrate*1e3,t.small&&(this._mediaSettings.smallVideoWidth=t.small.width,this._mediaSettings.smallVideoHeight=t.small.height,this._mediaSettings.smallVideoFps=t.small.frameRate,this._mediaSettings.smallVideoBps=t.small.bitrate*1e3)}if(r&&r.outMediaTrack){let n=r.outMediaTrack.getSettings(),{scaleResolutionDownBy:a}=r;this._mediaSettings.auxVideoWidth=n.width/a||0,this._mediaSettings.auxVideoHeight=n.height/a||0,this._mediaSettings.auxVideoFps=n.frameRate||0,this._mediaSettings.auxVideoBps=r.profile.bitrate*1e3}}else e&&e.outMediaTrack&&(this._mediaSettings.audioChannel=e.profile.channelCount,this._mediaSettings.audioBps=e.profile.bitrate*1e3,this._mediaSettings.audioFs=e.profile.sampleRate),t&&t.outMediaTrack&&(this._mediaSettings.videoWidth=t.profile.width,this._mediaSettings.videoHeight=t.profile.height,this._mediaSettings.videoFps=t.profile.frameRate,this._mediaSettings.videoBps=t.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:Y.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:F.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?p.AUXILIARY:p.MAIN} stream`),si()&&(yield this.addTrackByTransceiver(e,t))})}addTrackByTransceiver(e,t){return f(this,null,function*(){var o;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===p.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),n===1&&((o=this.localMainVideoTrack)!=null&&o.small)&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===te.INACTIVE&&(yield this.singlePC.setTransceiverDirection(te.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}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?p.AUXILIARY:p.MAIN} stream`),si()&&(yield this.removeTrackByTransceiver(e,t))})}removeTrackByTransceiver(e,t){return f(this,null,function*(){if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===p.AUDIO)yield r[0].sender.replaceTrack(null);else{let o=t?3:1;yield r[o].sender.replaceTrack(null),o===1&&this._room.videoManager.hasSmall&&(yield r[2].sender.replaceTrack(null)),yield this.singlePC.setTransceiverDirection(te.INACTIVE,[o])}this.updateMediaSettings(),yield this.doPublishChange()})}replaceTrack(e){return f(this,null,function*(){var n;let t=(n=this._peerConnection)==null?void 0:n.getSenders(),r=e.outMediaTrack||e.mediaTrack;if(!t||t.length===0||!r||t.find(a=>a.track===r))return!1;let o=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info(`is replacing ${r.kind} track ${r.id} ${r.label} on ${o?p.AUXILIARY:p.MAIN} stream`),r.kind===p.AUDIO&&t[0]&&(yield t[0].replaceTrack(r)),r.kind===p.VIDEO&&(!o&&t[1]&&(yield t[1].replaceTrack(r)),o&&t[3]&&(yield t[3].replaceTrack(r))),!0})}setBandwidth(o){return f(this,arguments,function*({bandwidth:e,type:t,videoType:r}){if(this.singlePC){let n={};t===p.AUDIO?n.audio=e:r==="big"?n.bigVideo=e:r==="small"?n.smallVideo=e:n.auxVideo=e,yield this.singlePC.setBandwidth(n)}})}sendMutedFlag(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info(`send muted state: ${JSON.stringify(this.muteState)}`),this._signalChannel.sendWaitForResponseWithRetry({command:Y.UPDATE_MUTE_STAT,responseCommand:F.MUTE_RESULT,data:this.muteState,retries:3}).catch(()=>{}))}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&E.emit(A.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(e=p.VIDEO){if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===p.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===p.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===p.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===p.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===Sr?(this._log.error(Ve.NOT_SUPPORTED_H264ENCODE),new y({code:I.NOT_SUPPORTED_H264,message:x({key:P.NOT_SUPPORTED_H264ENCODE})})):new y({code:I.UNKNOWN,message:x({key:P.SIGNAL_RESPONSE_FAILED,data:{signalResponse:F.PUBLISH_RESULT,code:e,message:t}})})}onSinglePCReconnected(){return f(this,null,function*(){this.isMainStreamPublished&&(this._log.warn("republish main stream"),yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(this._log.warn("republish aux stream"),yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0}))})}};v([et(function({localVideoTrack:e}){e==null||e.once("6",this.onVideoEncodeFailed,this)})],Tn.prototype,"publish",1),v([et(function({localVideoTrack:e}){e==null||e.off("6",this.onVideoEncodeFailed,this)})],Tn.prototype,"unpublish",1);var Wu=Tn;function rf(s){return Object.keys(s).filter(i=>s[i])}var Ys=class extends Kr{constructor(e){super(L(N({},e),{isUplink:!1}));d(this,"_flag",0);d(this,"isRobot",!1);d(this,"role","anchor");d(this,"remoteAudioTrack");d(this,"remoteVideoTrack");d(this,"remoteAuxiliaryTrack");d(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0});d(this,"jitterBufferTimeoutId",-1);this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=new Gt(this._room,this),this.remoteVideoTrack=new fi(this._room,this),this.remoteAuxiliaryTrack=new Bs(this._room,this),this.initialize()}get videoCodec(){var e;return((e=this.singlePC)==null?void 0:e.downlinkVideoCodec)||"h264"}get subscribeState(){return{audio:this.remoteAudioTrack.isSubscribed||this.remoteAudioTrack.isSubscribing,video:this.remoteVideoTrack.isBig&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),smallVideo:this.remoteVideoTrack.isSmall&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),auxiliary:this.remoteAuxiliaryTrack.isSubscribed||this.remoteAuxiliaryTrack.isSubscribing}}get muteState(){return bi(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,r,o;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(r=this.remoteVideoTrack)==null||r.onFlagChanged(),(o=this.remoteAuxiliaryTrack)==null||o.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===p.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){clearTimeout(this.jitterBufferTimeoutId),super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents(),this.removeDownlink()}installEvents(){this.singlePC&&(this.listeners("track").includes(this.onTrack)||this.singlePC.on("track",this.onTrack,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||this.singlePC.on("spc-reconnected",this.onSinglePCReconnected,this))}uninstallEvents(){this.singlePC&&(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this))}emitConnectionStateChangedEvent(e){var o,n;let t=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&t!==e&&((o=this.remoteVideoTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),r}onTrack(e){var u,h;let t=e.streams[0],{track:r,receiver:o}=e;if(!t.id.includes(this.tinyId))return;let a=t.id.includes("aux")?"auxiliary":"main";this._log.debug(`ontrack ${a} ${r.kind}`);let c=p.AUDIO;r.kind===p.VIDEO&&(c=a===p.MAIN?p.VIDEO:p.AUXILIARY);let l=this.remoteAudioTrack;c===p.VIDEO?l=this.remoteVideoTrack:c===p.AUXILIARY&&(l=this.remoteAuxiliaryTrack),(u=this.singlePC)==null||u.receiverRemoteTrackMap.set(o,l),(h=this.singlePC)!=null&&h.scriptTransformWorker&&this.initReceiverTransform(o,a,r.kind===p.AUDIO),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(o),l.setInputMediaStreamTrack(r)}createEncodedStreams(e){if(!this.singlePC.insertableStreamsAbortMap.has(e)){let t=e.createEncodedStreams(),r=new AbortController,o={abortController:r,enqueue:n=>{var c,l;let a=(c=this.singlePC)==null?void 0:c.receiverRemoteTrackMap.get(e);return!a||a.kind==="video"&&!((l=this.singlePC)!=null&&l.isUsingH264)?n:a.decodeFrame(n)}};t.readable.pipeThrough(new TransformStream({transform:(n,a)=>{let c=o.enqueue(n);c&&a.enqueue(c)}})).pipeTo(t.writable,r).catch(n=>{n!=="destory"&&this._log.warn(n)}),this.singlePC.addAbortController(e,r)}}initReceiverTransform(e,t,r){!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker||e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!0,isAudio:r,userId:this.userId,streamType:t}))}subscribe(e,t){return f(this,null,function*(){var r;try{let o=!0;if(this._log.info(`subscribe ${t} ${rf(e)}`),this.hasSSRC){let n="subscribe_change";Object.values(e).find(a=>a===!0)||(n="unsubscribe"),yield this.sendSubscription(n,e)}else{if((r=this.singlePC)!=null&&r.autoSubscribedUserMap.size){let n=this.singlePC.autoSubscribedUserMap.get(this.userId);if(n){this.singlePC.autoSubscribedUserMap.delete(this.userId);let a=this.singlePC.autoSubscribedSsrcGroups[n.groupIndex];a&&(this.ssrc={audio:a.audioSsrc,video:a.bigVideoSsrc,videoRtx:a.bigVideoRtxSsrc,auxiliary:a.auxVideoSsrc,auxiliaryRtx:a.auxVideoRtxSsrc},o=!1)}}yield this.doSubscribe(e,o),this.checkTrackEnded(e)}if(e.smallVideo){let{user:n,mediaTrack:a}=this.remoteVideoTrack;b.addSuccessEvent({key:524702}),this._blackSmallVideoDetectionId=Yi.start({track:a,isUplink:!1,room:this._room,userId:this.userId,onBlack:()=>{this._log.warn("small video is black, auto change to big"),this._room.changeType(!1,n),b.addFailedEvent({key:524702}),Yi.stop(this._blackSmallVideoDetectionId)}})}else Yi.stop(this._blackSmallVideoDetectionId)}catch(o){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${o.message} ${JSON.stringify(this.muteState)}`),new y({code:I.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):o}})}checkTrackEnded(e){var t,r,o;if((e.audio&&((t=this.remoteAudioTrack.mediaTrack)==null?void 0:t.readyState)==="ended"||e.video&&((r=this.remoteVideoTrack.mediaTrack)==null?void 0:r.readyState)==="ended"||e.auxiliary&&((o=this.remoteAuxiliaryTrack.mediaTrack)==null?void 0:o.readState)==="ended")&&this.singlePC&&!this.singlePC.isReconnecting){if(this._log.warn("remote track ended start spc reconnect"),Ze&&lt<92)return;this.singlePC.startReconnection()}}unsubscribe(r){return f(this,arguments,function*({remoteTracks:e,streamType:t}){var a;if(t==="main"&&!this.isMainStreamSubscribed||t==="auxiliary"&&!this.isAuxStreamSubscribed){this._log.info(`${t} stream already unsubscribed`);return}let o=N({},this.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:o.audio=!1;break;case 4:o.video=!1;break;case 8:o.smallVideo=!1;break;case 2:o.auxiliary=!1;break;default:break}});let n="subscribe_change";Object.values(o).find(c=>c===!0)||(n="unsubscribe"),this._log.info(`${n==="unsubscribe"?n:"subscribe"} ${t} [${rf(o)}]`),n==="unsubscribe"&&((a=this.singlePC)==null||a.removeDownlinkQueue.add(this.tinyId)),yield this.sendSubscription(n,o),t==="main"&&(Yi.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0),n==="unsubscribe"&&(yield this.removeDownlink())})}sendSubscription(e,t=this.subscribeState){let r={srcTinyId:this.tinyId,srcUserId:this.userId},o=Y.UNSUBSCRIBE,n=F.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(r={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},o=Y.SUBSCRIBE_CHANGE,n=F.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponseWithRetry({command:o,data:r,responseCommand:n,timeout:1e4,retries:3}).then(({data:a})=>{if(a.code!==0){let c=new y({code:a.code,message:x({key:P.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(c),c}})}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}setDelay({audioDelay:e,videoDelay:t}){this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=t}onSinglePCReconnected(){return f(this,null,function*(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary)&&(this._log.warn(`resubscribe ${JSON.stringify(this.subscribeState)}`),yield this.doSubscribe(this.subscribeState),this.remoteAudioTrack.checkDecodeResult(),this.remoteVideoTrack.checkDecodeResult(),this.remoteAuxiliaryTrack.checkDecodeResult())})}get hasSSRC(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}doSubscribe(){return f(this,arguments,function*(e=this.subscribeState,t=!0){if(this.singlePC){this.singlePC.addDownlinkQueue.add(this.tinyId),yield this.singlePC.waitForPeerConnectionConnected();try{if(t||!this.hasSSRC){let r={audioSsrc:Et(),bigVideoSsrc:Et(),bigVideoRtxSsrc:Et(),auxVideoSsrc:Et(),auxVideoRtxSsrc:Et()},{audioSsrc:o,bigVideoSsrc:n,bigVideoRtxSsrc:a,auxVideoSsrc:c,auxVideoRtxSsrc:l}=r;this.ssrc={audio:o,video:n,videoRtx:a,auxiliary:c,auxiliaryRtx:l},this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc});try{let u=yield this._signalChannel.sendWaitForResponseWithRetry({command:Y.SPC_SUBSCRIBE,responseCommand:F.SPC_SUBSCRIBE_RESULT,data:{srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo,customData:!1,ssrc:r},retries:3,retryTimeout:0});if(u.data.code!==0&&u.data.code!==-10036)throw new y({code:u.data.code,message:u.data.message})}catch(u){throw yield this.removeDownlink(),u}return}this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc})}finally{if(!ga)return;let{main:r,aux:o}=this._room.jitterBufferDelay||{},{jitterDelay:n=r,jitterDelayAux:a=o}=this._room.scheduleResult.config||{};(q(n)||q(a))&&this.setJitterBufferDelay({mainDelay:n,auxDelay:a})}}})}removeDownlink(){return f(this,null,function*(){if(!this.singlePC)return;this.ssrc={audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0},this.singlePC.removeDownlinkQueue.delete(this.tinyId);let e=this._room.scheduleResult.config;(e!=null&&e.jitterDelay||e!=null&&e.jitterDelayAux)&&this.setJitterBufferDelay({mainDelay:0,auxDelay:0}),yield this.singlePC.removeDownlink(this.userId)})}setJitterBufferDelay({mainDelay:e,auxDelay:t}){if(!ga||!this.singlePC||!this._peerConnection||Oi(e)&&Oi(t))return Promise.resolve();this._log.info(`set jitterBuffer main: ${e} aux: ${t}`);let r=this.singlePC.getReceiversByUserId(this.userId);return q(e)&&(this.remoteAudioTrack.jitterBufferDelay=e,this.remoteVideoTrack.jitterBufferDelay=e),q(t)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=t,Oi(e)&&(this.remoteAudioTrack.jitterBufferDelay=t)),new Promise(o=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:o})})}doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:o}){try{if(e===0&&t===0)return r.forEach(a=>a.jitterBufferTarget=0),o();if(r.forEach(a=>{var h;let c=a.track===this.remoteAuxiliaryTrack.outMediaTrack||Oi(e)&&a.track===this.remoteAudioTrack.outMediaTrack;if(c&&Oi(t)||!c&&Oi(e))return;let l=c?t||0:e,u=(a.jitterBufferTarget||0)+100;u>l||(a.jitterBufferTarget=u,this._log.debug(`set ${c?"aux ":""}${(h=a==null?void 0:a.track)==null?void 0:h.kind} jitterBuffer delay ${u} -> ${l}`))}),!r.find(a=>{let c=a.track===this.remoteAuxiliaryTrack.outMediaTrack?t||0:e;return a.jitterBufferTarget<c}))return this._log.info(`set jitterBuffer main: ${e} aux: ${t} done`),o();this.jitterBufferTimeoutId=setTimeout(()=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:o})},1e3)}catch(n){this._log.warn(`set jitterBuffer delay error: ${n}`),clearTimeout(this.jitterBufferTimeoutId),o()}}get audioReceiver(){var e;return((e=this.singlePC)==null?void 0:e.getReceiversByUserId(this.userId)[0])||null}};v([Rt(),Q(e=>function(...t){return new Promise((r,o)=>{let n=a=>{this.off("closed",n),o(new y({code:I.API_CALL_ABORTED,message:x({key:P.CONNECTION_ABORTED,data:a})}))};this.on("closed",n),e.apply(this,t).then(r,o).finally(()=>{this.off("closed",n)})})})],Ys.prototype,"subscribe",1),v([Rt()],Ys.prototype,"unsubscribe",1),v([$i(()=>"jitter")],Ys.prototype,"setJitterBufferDelay",1);var sf=Ys;function of(){return Q(s=>function(...i){return f(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(i=i.filter(t=>t.outMediaTrack&&t.state==="ready"),!i.length))return;E.emit("61",{room:this});let e=s.apply(this,i);return i.forEach(t=>t.publish(this,e)),e})})}function nf(){return Q(s=>function(...i){let e=s.apply(this,i);return i.forEach(t=>t.unpublish()),e})}var af=$e(Ye());function yE(){return Math.floor(Math.random()*16383)}var xc=class xc extends af.EventEmitter{constructor(e,t){super();this.room=e;this.signalChannel=t;d(this,"log");d(this,"cmdIdSeqMap",new Map);d(this,"messageMap",new Map);this.log=C.createLogger({id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),t.on(F.RECEIVE_CUSTOM_MSG,this.onReceiveMsg),this.room.on("peer-leave",r=>{[...this.messageMap.keys()].forEach(o=>{o.split("_").slice(0,-1).join("_")===r&&this.messageMap.delete(o)})})}send({cmdId:e,data:t}){let r=this.cmdIdSeqMap.get(e)||yE(),o={cmdId:e,msg:btoa(String.fromCharCode(...new Uint8Array(t))),ordered:!0,reliable:!0,streamSeq:r};this.cmdIdSeqMap.set(e,r+1),this.signalChannel.send(Y.SEND_CUSTOM_MSG,o),this.log.debug(`send custom msg: ${JSON.stringify(o)}`)}onReceiveMsg(e){let{data:t}=e.data,r=this.room.tinyIdToUserIdMap.get(t.srcTinyId);if(r){let o={userId:r,cmdId:t.cmdId,seq:t.streamSeq,data:Uint8Array.from(atob(t.msg),n=>n.charCodeAt(0)).buffer};if(t.ordered){let n=`${r}_${o.cmdId}`,a=this.messageMap.get(n);if(!a||a.lastSeq===0)a||(a={lastSeq:0,cachedMessageMap:new Map},this.messageMap.set(n,a),setTimeout(()=>this.emitMessage(o,!0),100)),a.cachedMessageMap.set(o.seq,{message:o});else if(Math.abs(a.lastSeq-o.seq)>xc.SEQ_INTERVAL)this.messageMap.set(n,{lastSeq:o.seq,cachedMessageMap:new Map}),this.emitMessage(o);else if(o.seq>a.lastSeq){if(o.seq===a.lastSeq+1)this.emitMessage(o);else if(!a.cachedMessageMap.has(o.seq)){let c=setTimeout(()=>this.emitMessage(o,!0),5e3);a.cachedMessageMap.set(o.seq,{message:o,timeoutId:c})}}else this.log.debug(`drop message ${o.userId}-${o.cmdId}-${o.seq}`)}else this.emit("message",o)}else{this.log.warn(`receive msg from unknown user, wait peer-join tinyId: ${t.srcTinyId}`);let o=n=>{n.tinyId===t.srcTinyId&&(this.room.off("peer-join",o),this.onReceiveMsg(e))};this.room.on("peer-join",o),Ni(2e3).then(()=>this.room.off("peer-join",o))}}emitMessage(e,t=!1){var a;let r=this.messageMap.get(`${e.userId}_${e.cmdId}`),o=e;if(r){if(t){let c=[...r.cachedMessageMap.values()].sort((l,u)=>l.message.seq-u.message.seq);c[0]&&(o=c[0].message)}r.lastSeq!==0&&o.seq-r.lastSeq>1&&this.log.debug(`msg lost userId: ${o.userId} seq: ${r.lastSeq} -> ${o.seq}`),r.lastSeq=o.seq,clearTimeout((a=r.cachedMessageMap.get(o.seq))==null?void 0:a.timeoutId),r.cachedMessageMap.delete(o.seq)}this.log.debug(`receive custom msg: ${JSON.stringify(o)}`),this.emit("message",o);let n=r==null?void 0:r.cachedMessageMap.get(o.seq+1);n&&this.emitMessage(n.message)}};d(xc,"SEQ_INTERVAL",300);var Pc=xc;var{isString:cf,isUndefined:gr,getNetworkType:bE,isEmpty:En}=dt,jt=class extends Mc{constructor(e){super(e);d(this,"_businessInfo");d(this,"userManager");d(this,"_version");d(this,"_heartbeat",-1);d(this,"_lastHeartBeatTime",-1);d(this,"_stats");d(this,"_joinTimeout",-1);d(this,"_firstPublishedList",null);d(this,"_joinReject",null);d(this,"_isRelayChanged",!1);d(this,"sdpSemantics");d(this,"signalChannel",null);d(this,"uplinkConnection",null);d(this,"singlePC",null);d(this,"enableSPC",bs);d(this,"_changeBigSmallRecords",new Map);d(this,"networkQuality");d(this,"_iceTransportPolicy");d(this,"forceRelay",!1);d(this,"_turnServers",[]);d(this,"_iceServersFromJoin");d(this,"_syncUserListInterval",-1);d(this,"_smallStreamConfig",{bitrate:100,frameRate:15,height:120,width:160});d(this,"enableSEI",!1);d(this,"_enableAudioVolumeEvaluation",!1);d(this,"_audioVolumeIntervalId",0);d(this,"_enableMultiAuxStream",!1);d(this,"_pureAudioPushMode",!1);d(this,"_customMessageManager");d(this,"preferHW",!1);d(this,"healthDetector");d(this,"playoutDelay");d(this,"jitterBufferDelay");d(this,"_updateAudioLevelTaskId",-1);this._stats=new pn(this,this._log),this.userManager=new tc(this.userId,this._log),this._version=Pe,this.sdpSemantics=is,gr(e.sdpSemantics)?ni.isUnifiedPlanDefault()&&(this.sdpSemantics=rr):this.sdpSemantics=e.sdpSemantics,this._log.info(`sdpSemantics: ${this.sdpSemantics}, netType: ${bE()}`),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=gr(e.enableMultiAuxStream)?!1:e.enableMultiAuxStream,this.enableSEI=e.enableSEI&&bs,!gr(e.enableSPC)&&bs&&(this.enableSPC=e.enableSPC),this.preferHW=!!e.preferHW,this._initBusinessInfo(e),this.healthDetector=new jp(this)}get isMainStreamPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.isMainStreamPublished)}get isMainAudioPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.localMainAudioTrack)}get isAuxStreamPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.isAuxStreamPublished)}get hasAuxStream(){return[...this.remotePublishedUserMap.values()].findIndex(e=>e.muteState.hasAuxiliary)>=0}get userMap(){return this.userManager.userMap}get remotePublishedUserMap(){return this.userManager.remotePublishedUserMap}get tinyIdToUserIdMap(){return new Map([...this.userMap.values()].map(e=>[e.tinyId,e.userId]))}join(e,t,r){return f(this,null,function*(){return this.userManager.mySelfId=this.userId,this.userManager.on("1",o=>{this.emit("peer-join",o)}),this.userManager.on("2",o=>{this.closeDownLinkConnection(o,"remote user exitRoom"),this.emit("peer-leave",o)}),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",n=>{var o=Xu(n,[]);E.emit(A.REMOTE_PUBLISH_STATE_CHANGED,N({room:this},o)),this.emit("remote-publish-state-changed",N({},o))}),this.joinParams=e,new Promise((o,n)=>f(this,null,function*(){var a,c;this._joinReject=n;try{this.checkDestroy();try{yield Promise.all([this.initialize(),this.initSinglePC()])}catch(u){if(u instanceof y&&u.code===I.SPC_INITIALIZED_FAILED)(a=this.signalChannel)==null||a.destroy(),yield this.initialize();else return n(u)}let l=w();yield this.doJoin(e,(c=this.singlePC)==null?void 0:c.clientAbility),b.addSuccessEvent({key:521708,cost:w()-l}),o(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(l){b.addFailedEvent({key:521708,error:l}),n(l)}this._joinReject=null}))})}initSinglePC(){return f(this,null,function*(){if(!(!this.enableSPC||this.singlePC)){this.singlePC=new qt({signalChannel:this.signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.on("sei-message",e=>this.emit("sei-message",e)),this.singlePC.on("dump",e=>this.emit("dump",e)),this.singlePC.once("error",()=>this.fallbackToMPC());try{return yield this.singlePC.initialize()}catch(e){throw this.fallbackToMPC(),new y({code:I.SPC_INITIALIZED_FAILED,message:e==null?void 0:e.message})}}})}doJoin(e,t){return new Promise((r,o)=>f(this,null,function*(){var c,l,u;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this.signalChannel.once(Ne.SETUP_FAILED,h=>{this.clearJoinTimeout(),E.emit(A.JOIN_SIGNAL_CONNECTION_END,{room:this,error:h}),o(h)}),me((l=(c=this.scheduleResult)==null?void 0:c.config)==null?void 0:l.singlePC)&&bs&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2),t&&this.playoutDelay&&(t.playoutDelay=this.playoutDelay);let n={roomId:String(e.roomId||e.strRoomId),useStringRoomId:this.useStringRoomId,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel,trtcRole:e.role,trtcScene:this.scene==="live"?2:1,sdpSemantics:this.sdpSemantics,version:this._version,ua:navigator&&navigator.userAgent||"",terminalType:Cd(),netType:Cr(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig,receiveMix:!0};this._log.debug(`join room signal data: ${JSON.stringify(n)}`);let a=5e3;(u=this.scheduleResult.config)!=null&&u.enterRoomTimeout&&this.scheduleResult.config.enterRoomTimeout>=1&&(a=this.scheduleResult.config.enterRoomTimeout*1e3),this._joinTimeout=window.setTimeout(()=>{o(new y({code:I.JOIN_ROOM_FAILED,message:x({key:P.JOIN_ROOM_TIMEOUT})}))},a),E.emit(A.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?Y.SPC_JOIN_ROOM:Y.JOIN_ROOM,n),this.signalChannel.once(F.JOIN_ROOM_RESULT,h=>f(this,null,function*(){this.clearJoinTimeout();let{code:m,message:g,data:D,tinyId:_}=h.data;E.emit(A.JOIN_RECEIVED_CMD_RES,{room:this,code:m}),m===0?(this._log.info("Join room success, start heartbeat"),_&&(this.tinyId=_),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=D.publishers,this._iceServersFromJoin=D.iceServer?[D.iceServer]:[],this.singlePC&&this.singlePC.setIceServers(this.getIceServers()).then(()=>{var S;(S=this.singlePC)==null||S.connect(L(N({},D.ability),{useVp8:D.ability.useVp8||!!e.useVp8})).catch(()=>{})}),r()):(this._log.error(`Join room failed result: ${m} error: ${g}`),o(new y({code:I.JOIN_ROOM_FAILED,extraCode:m,message:x({key:P.JOIN_ROOM_FAILED,data:{error:g,code:m}})})))}))}))}reJoin(){return f(this,null,function*(){if(!this.isJoined){this._log.warn("reJoin abort");return}try{this._log.warn(`reJoin pending: ${this.joinParams.roomId}`);let e,t=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,t.push(this.initSinglePC().then(r=>(e=r,r)))),this.signalChannel&&(this.signalChannel.close(),t.push(this.signalChannel.connect())),yield Promise.all(t),yield this.doJoin(L(N({},this.joinParams),{role:this.role==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),e),this._log.warn("reJoin success"),re.logSuccessEvent({userId:this.userId,eventType:st.REJOIN}),this.singlePC){let r=o=>{var n;o.state==="CONNECTED"&&((n=this.singlePC)==null||n.off(Ti.CONNECTION_STATE_CHANGED,r),this.uplinkConnection instanceof Wu&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach(a=>{a.installEvents(),a.onSinglePCReconnected()}))};this.singlePC.on(Ti.CONNECTION_STATE_CHANGED,r),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof mn&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(e){this._log.warn(`reJoin fail ${e}`),this.reset(),re.logFailedEvent({userId:this.userId,eventType:st.REJOIN,error:e}),this.emit("error",new y({code:I.JOIN_ROOM_FAILED,message:x({key:P.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}})}initialize(){return f(this,null,function*(){let{mainUrl:e,backupUrl:t}=this.getSignalChannelUrl(),r=this.signalChannel||Sp(this.userId),o=!!(r&&r.isConnected&&r.keepAlive&&r.room===this),n;return Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(n=this.scheduleResult.domains[0]),this._log.info(`${o?"reuse":"setup"} signal channel`),o?(r.url=e,r.backupUrl=t,r.room=this,this.signalChannel=r):(r&&r.close(),this.signalChannel=new qs({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:e,backupUrl:t,room:this,signalDomainWhenUnifiedProxy:this.proxy_unified?n:void 0}),this._customMessageManager=new Pc(this,this.signalChannel),this._customMessageManager.on("message",a=>{this.emit("custom-message",a)})),this.networkQuality||(this.networkQuality=new Qs({signalChannel:this.signalChannel,room:this}),this.networkQuality.on(Qs.EVENT_NETWORK_QUALITY,a=>{var c;this.emit("network-quality",a),(c=this.singlePC)==null||c.detectTCPAndUDP(a)})),qe(this,this.signalChannel).add(Ne.CONNECTION_STATE_CHANGED,a=>{E.emit(A.SIGNAL_CONNECTION_STATE_CHANGED,N({room:this},a)),this.emit("signal-connection-state-changed",a)}).add(Ne.RECONNECT_FAILED,a=>{this.reset(),this.emit("error",a)}).add(F.PEER_JOIN,a=>{let{srcTinyId:c,userId:l,role:u}=a.data.data;this.userManager.addUser({userId:l,tinyId:c,role:u})}).add(F.PEER_LEAVE,a=>{let{userId:c,reason:l=0}=a.data.data;this.userManager.deleteUser(c,l)}).add(F.UPDATE_REMOTE_MUTE_STAT,a=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=10*1e3&&this.doHeartbeat(),this.onPublishedUserList(a.data)}).add(F.CLIENT_BANNED,a=>{let c=a.data.data,{reason:l}=c;if(re.uploadEvent({log:`stat-banned:${l}`,userId:this.userId}),l==="user_time_out"){this._log.warn(`${l} last heart beat time: ${this._lastHeartBeatTime} interval: ${Date.now()-this._lastHeartBeatTime}, visibility: ${document.visibilityState}`),this.reJoin();return}this._log[l==="kick"?"error":"info"](`user was banned because of [${l}]`),this.reset(),this.emit("banned",{reason:l})}).add(F.SEND_SWITCH_ROOM_SUBED_REQ,a=>{if(!this.singlePC)return;let{subList:c}=a.data.data;c.forEach(l=>{this.singlePC.autoSubscribedUserMap.set(l.userId,l)})}),this.signalChannel.once(Ne.SETUP_SUCCESS,a=>{this.tinyId=a.signalInfo.tinyId,E.emit(A.JOIN_SIGNAL_CONNECTION_END,{room:this})}),E.emit(A.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),o&&E.emit(A.JOIN_SIGNAL_CONNECTION_END,{room:this}),o})}setSignalChannel(e){this.signalChannel=e,e||ve(this)}leave(){return f(this,null,function*(){var e;try{yield this.doHeartbeat()}catch(t){}this._log.info("leave() => leaving room"),E.emit(A.LEAVE_SEND_CMD,{room:this}),(e=this.signalChannel)==null||e.send(Y.LEAVE_ROOM)})}clearNetworkQuality(){this.networkQuality&&(this.networkQuality.stop(),delete this.networkQuality)}closeConnections(){this.remotePublishedUserMap.forEach(e=>{this.closeDownLinkConnection(e.userId,"you exitRoom")})}clearJoinTimeout(){clearTimeout(this._joinTimeout),this._joinTimeout=-1}startHeartbeat(){this._heartbeat===-1&&(this._heartbeat=oe.run("ric",this.doHeartbeat.bind(this),{delay:2e3}))}stopHeartbeat(){this._heartbeat!==-1&&(this._log.info("stopHeartbeat"),oe.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return f(this,null,function*(){var n;let e=this.badCaseDetector.getMonitorFreeze(),t=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:e});this.badCaseDetector.resetMonitor();let r=(n=this.signalChannel)!=null&&n.isConnected?wm(this.userId):[],o=L(N({str_sdk_version:to,uint64_datetime:new Date().getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_event_msg:r,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},t),{msg_device_info:N({uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:Cr()},t.msg_device_info)});if(this.heartbeatReport=o,E.emit(A.HEARTBEAT_REPORT,{room:this,report:o}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(Y.ON_QUALITY_REPORT,o);let a=Date.now();this._lastHeartBeatTime>0&&a-this._lastHeartBeatTime>1e4&&this._log.warn(`heartbeat took ${a-this._lastHeartBeatTime}`),this._lastHeartBeatTime=a,this.signalChannel.isOnline||(this._log.warn("signal channel is not online"),this.signalChannel.startReconnection())}this.emit("heartbeat-report",L(N({},o),{bytes_sent:this._stats.totalBytesSent+this.signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this.signalChannel.bytesReceived}))}!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)})}onPublishedUserList(e){if(!this.isJoined)return;let t=e.data.userList.filter(r=>r.flag!==Jc).map(({userId:r,srcTinyId:o,flag:n})=>{r===this.userId&&this.uplinkConnection&&(this.uplinkConnection.flag=n);let a=this.remotePublishedUserMap.get(r);return a&&this.checkSubscribeBigSmallVideo(a),{userId:r,tinyId:o,flag:n}});e.data.mixRobotList.forEach(({userId:r,srcTinyId:o,flag:n,mixUserList:a})=>{t.unshift({userId:r,tinyId:o,flag:n,isRobot:!0,mixUserList:a})}),E.emit(A.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:t}),this.userManager.setRemotePublishedUserList(t)}closeUplink(e="you unpublished"){this.uplinkConnection&&(this.localTracks.size>0&&this.uplinkConnection.doUnpublish(),this.uplinkConnection.close(e),this.uplinkConnection instanceof mn&&(this.uplinkConnection=null)),this.localTracks.forEach(t=>t.unpublish()),this.localTracks.clear()}createDownlinkConnection({userId:e,tinyId:t,flag:r,isRobot:o}){let n=new(this.singlePC?sf:ku)({userId:e,tinyId:t,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:r,isRobot:o});this.userManager.addRemotePublishedUser(n),this.installDownlinkEvents(n,e),this.emit("remote-published",n)}closeDownLinkConnection(e,t="remote user unpublished"){let r=this.remotePublishedUserMap.get(e);r&&(r.close(t),this.emit("remote-unpublished",r))}installDownlinkEvents(e,t){e.on("error",r=>{let o=r.getCode();o!==I.ICE_TRANSPORT_ERROR&&(o===I.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",r))}),e.on("connection-state-changed",r=>{this.emit("media-connection-state-changed",L(N({},r),{userId:e.userId}))}),e.on("firewall-restriction",()=>{this.emit("firewall-restriction")})}startSyncUserListInterval(){this._syncUserListInterval===-1&&(this._syncUserListInterval=oe.run("ric",this.syncUserList.bind(this)))}stopSyncUserListInterval(){oe.clearTask(this._syncUserListInterval),this._syncUserListInterval=-1}syncUserList(){return this.getUserList().then(e=>{this.userManager.setUserList(e)}).catch(e=>{this._log.debug(`sync user list failed: ${e}`)})}getUserList(){var e;return(e=this.signalChannel)!=null&&e.isConnected?this.signalChannel.sendWaitForResponse({command:Y.GET_USER_LIST,responseCommand:F.USER_LIST_RES,enableLog:!1,timeout:2e3}).then(({data:t})=>{let{code:r,message:o}=t;if(r===0)return(t.data&&t.data.userList||[]).map(({userId:a,srcTinyId:c,role:l})=>({userId:a,tinyId:c,role:l}));throw x({key:P.SIGNAL_RESPONSE_FAILED,data:{signalResponse:F.USER_LIST_RES,code:r,message:o}})}):Promise.reject("not connected")}getAllConnections(){let e=[...this.remotePublishedUserMap.values()];return this.uplinkConnection&&e.push(this.uplinkConnection),e}isRelayMaybeFailed(){if(this.signalChannel&&!this.signalChannel.isOnline||!bu)return!1;if(this.singlePC)return this.singlePC.reconnectionCount>6;let e=this.getAllConnections();if(e.length===0)return!1;for(let t=0;t<e.length;t++)if(e[t].getReconnectionCount()<6)return!1;return!0}checkConnectionsToReconnect(){var e;this.singlePC?((e=this.singlePC.getPeerConnection())==null?void 0:e.connectionState)===ge.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach(r=>{if(r instanceof rt&&!r.getIsReconnecting()){let o=r.getPeerConnection();o&&o.connectionState===ge.CLOSED&&(this._log.warn(`[${r.getUserId()}] pc is closed but not reconnect`),r.startReconnection())}})}fallbackToMPC(){return f(this,null,function*(){var e;if(this._log.warn("fallback to multi pc"),re.uploadEvent({log:"stat-fallback",userId:this.userId}),this.enableSPC=!1,(e=this.singlePC)==null||e.close(),this.singlePC=null,this.isJoined&&(yield this.reJoin()),this.uplinkConnection){let t=this.uplinkConnection;this.uplinkConnection=new mn({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),t.isMainStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:t.localMainAudioTrack,localVideoTrack:t.localMainVideoTrack,isAuxiliary:!1})),t.isAuxStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:t.localAuxAudioTrack,localVideoTrack:t.localAuxVideoTrack,isAuxiliary:!0})),t.close()}for(let t of[...this.remotePublishedUserMap.values()]){let r=new ku({userId:t.userId,tinyId:t.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:t.flag,remoteAudioTrack:t.remoteAudioTrack,remoteVideoTrack:t.remoteVideoTrack,remoteAuxiliaryTrack:t.remoteAuxiliaryTrack});this.installDownlinkEvents(r,t.userId),this.remotePublishedUserMap.set(t.userId,r),t.isMainStreamSubscribed&&(yield r.subscribe(t.subscribeState,"main")),t.isAuxStreamSubscribed&&(yield r.subscribe(t.subscribeState,"auxiliary"))}})}destroy(){this.isDestroyed||(this.signalChannel&&(this._log.info("destroying SignalChannel"),this.signalChannel.close(),this.signalChannel=null),super.destroy(),this._joinReject&&(this._joinReject(new y({code:I.INVALID_OPERATION,message:x({key:P.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners(),this.healthDetector.destroy(),oe.clearTask(this._audioVolumeIntervalId))}switchRole(e){return f(this,null,function*(){this.role!==e&&(e==="audience"&&this.uplinkConnection&&this.closeUplink("you switch role to audience"),yield this.doSwitchRole(e))})}doSwitchRole(e){let t={command:Y.SWITCH_ROLE,data:{role:e==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:F.SWITCH_ROLE_RES,retries:1};return this._log.info(`switchRole signal data: ${JSON.stringify(t.data)}`),this.signalChannel.sendWaitForResponseWithRetry(t).then(r=>{let{code:o,message:n}=r.data;if(o!==0)throw new y({code:I.SWITCH_ROLE_FAILED,message:x({key:P.SWITCH_ROLE_FAILED,data:{message:n,code:o}})});this.role=e}).catch(r=>{throw r instanceof y&&r.getCode()===I.API_CALL_TIMEOUT&&(r=new y({code:I.SWITCH_ROLE_FAILED,message:x({key:P.SWITCH_ROLE_TIMEOUT})})),this._log.error(r),r})}publish(...e){return f(this,null,function*(){let t={},r={};e.forEach(c=>{c instanceof Tt&&(c instanceof hi?r.audio=c:t.audio=c),c instanceof je&&(c instanceof ct&&c.mediaType===2?r.video=c:t.video=c)});let o=En(t),n=En(r);(!o||!n)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new Wu({userId:this.userId,tinyId:this.tinyId,room:this}):this.uplinkConnection=new mn({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),this.uplinkConnection.on("connection-state-changed",c=>{this.emit("media-connection-state-changed",L(N({},c),{userId:this.userId}))}),this.uplinkConnection.on("firewall-restriction",()=>{this.emit("firewall-restriction")}),this.uplinkConnection.on("error",c=>{let l=c.getCode();l!==I.ICE_TRANSPORT_ERROR&&(l===I.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",c))}));let a=e.map(c=>c.kind).join(",");o||(this._log.info(`publish() => main ${a}`),yield this.uplinkConnection.publish({localAudioTrack:t.audio,localVideoTrack:t.video,isAuxiliary:!1}),this._log.info("main is published")),n||(this._log.info(`publish() => aux ${a}`),yield this.uplinkConnection.publish({localAudioTrack:r.audio,localVideoTrack:r.video,isAuxiliary:!0}),this._log.info("aux is published"))})}unpublish(...e){return f(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||!this.isMainStreamPublished&&!this.isAuxStreamPublished||!this.uplinkConnection)return;let t={},r={};e.forEach(o=>{!o.mediaTrack||!o.isPublished||(o instanceof Tt&&(o instanceof hi?r.audio=o:t.audio=o),o instanceof je&&(o instanceof ct&&o.mediaType===2?r.video=o:t.video=o))});try{let o=e.map(n=>n.kind).join(",");En(t)||(this._log.info(`unpublish() => main ${o}`),yield this.uplinkConnection.unpublish({localAudioTrack:t.audio,localVideoTrack:t.video})),En(r)||(this._log.info(`unpublish() => aux ${o}`),yield this.uplinkConnection.unpublish({localAudioTrack:r.audio,localVideoTrack:r.video}))}catch(o){}this.localTracks.size===0&&this.closeUplink("you unpublished")})}addTrack(e){if(!this.uplinkConnection||!e.mediaTrack)return Promise.resolve();let t=this.uplinkConnection.addTrack(e);return e.publish(this,t),t}removeTrack(e){return!this.uplinkConnection||!e.mediaTrack?Promise.resolve():this.uplinkConnection.removeTrack(e).then(t=>(e.unpublish(),t))}replaceTrack(e){return!this.uplinkConnection||!e.mediaTrack||!qd()?Promise.resolve():this.uplinkConnection.replaceTrack(e).then(t=>{t&&E.emit(A.LOCAL_TRACK_REPLACED,{track:e})})}setBandWidth(e){return f(this,null,function*(){this.uplinkConnection&&(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())})}enableSmall(e){return f(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:p.VIDEO,videoType:p.SMALL,bandwidth:this.uplinkConnection.localMainVideoTrack.small.bitrate})),yield this.uplinkConnection.enableSmall(e)})}subscribe(...e){return f(this,null,function*(){if(e=e.filter(n=>!n.isSubscribed),e.length===0)return;let{userId:t}=e[0],r=this.remotePublishedUserMap.get(t);if(!r)return;let o=e.find(n=>n.mediaType===2)?"auxiliary":"main";try{let n=N({},r.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:n.audio=!0;break;case 4:n.video=!0;break;case 8:n.smallVideo=!0;break;case 2:n.auxiliary=!0;break}});let a=this._changeBigSmallRecords.get(t);a&&a.options.smallVideo&&r.muteState.hasSmall&&n.video&&(n.video=!1,n.smallVideo=!0),E.emit(A.SUBSCRIBE_START,{room:this,streamType:o,remotePublishedUser:r,subscribeState:n}),this._log.info(`subscribe() => ${t} ${o} [${Rc(n)}] prev: [${Rc(r.subscribeState)}]`),yield r.subscribe(n,o),this._log.info(`subscribe ${t} ${o} done`);for(let c of e)c.mediaTrack||(yield c.waitHasMediaTrack());E.emit(A.SUBSCRIBE_SUCCESS,{room:this,streamType:o,remotePublishedUser:r})}catch(n){let a=n instanceof y?n.getCode():I.UNKNOWN,c=n;throw n instanceof y?a===I.REMOTE_STREAM_NOT_EXIST&&(c=new y({code:I.API_CALL_ABORTED,message:x({key:P.API_CALL_ABORTED,data:{message:n.message,userId:t,streamType:o}})}),this._log.warn(c)):(c=new y({code:a,message:x({key:P.SUBSCRIBE_FAILED,data:{message:n.message,userId:t,streamType:o}})}),this._log.error(c)),c}})}unsubscribe(...e){return f(this,null,function*(){let{userId:t}=e[0],r=this.remotePublishedUserMap.get(t);if(!r)return;let o=e.find(n=>n.mediaType===2)?"auxiliary":"main";this._log.info(`unsubscribe() => ${t} ${o}`);try{yield r.unsubscribe({remoteTracks:e,streamType:o})}catch(n){this._log.warn(`unsubscribe() => failed ${n}`)}e.forEach(n=>{n.unsubscribe(),n.mediaType===8&&n.setMediaType(4)}),E.emit(A.UNSUBSCRIBE_SUCCESS,{room:this,streamType:o,remotePublishedUser:r})})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAudioVolumeEvaluation(e=2e3,t){if(e<=0){this._enableAudioVolumeEvaluation=!1,oe.clearTask(this._audioVolumeIntervalId);return}e=Math.floor(Math.max(e,100)),E.emit(A.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&oe.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=oe.run("intervalInWorker",()=>{var o;Ur.isRunning?this.stopUpdateAudioLevelFromSenderStat():this.updateAudioLevelFromSenderStat(e,t);let r=[];(o=this.remotePublishedUserMap)==null||o.forEach(n=>{if(n.muteState.hasAudio){!Ur.isRunning&&n.muteState.audioAvailable&&n.remoteAudioTrack.isSubscribed?this.updateDownlinkAudioLevelFromReceiver(n):n.remoteAudioTrack.volume=0;let a=Math.floor(n.remoteAudioTrack.getAudioLevel()*100);r.push({userId:n.userId,volume:a})}}),this.emit("audio-volume",r)},{delay:e,backgroundTask:t})}updateAudioLevelFromSenderStat(e,t){return f(this,null,function*(){var n;if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack||this._updateAudioLevelTaskId!==-1)return;let r=(n=this.uplinkConnection.getPeerConnection())==null?void 0:n.getSenders()[0];if(!r)return;let o=Math.max(e,500);this._log.warn(`updateAudioLevelFromSenderStat ${o}`),this._updateAudioLevelTaskId=oe.run("intervalInWorker",()=>f(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack){this.stopUpdateAudioLevelFromSenderStat();return}let a=yield r.getStats();if(this._updateAudioLevelTaskId<0)return;let{localMainAudioTrack:c}=this.uplinkConnection;a.forEach(l=>{l.type==="media-source"&&l.audioLevel&&(c.volume=l.audioLevel)})}),{delay:o,backgroundTask:t})})}stopUpdateAudioLevelFromSenderStat(){var e;this._updateAudioLevelTaskId!==-1&&(this._log.warn("stopUpdateAudioLevelFromSenderStat"),oe.clearTask(this._updateAudioLevelTaskId),this._updateAudioLevelTaskId=-1,(e=this.uplinkConnection)!=null&&e.localMainAudioTrack&&(this.uplinkConnection.localMainAudioTrack.volume=0))}updateDownlinkAudioLevelFromReceiver(e){var o;let{audioReceiver:t}=e;if(!jd||!t)return;let r=(o=t.getSynchronizationSources()[0])==null?void 0:o.audioLevel;q(r)?e.remoteAudioTrack.volume=Math.min(r*2,1):t.getStats().then(n=>{n.forEach(a=>{a.type==="inbound-rtp"&&q(a.audioLevel)&&(e.remoteAudioTrack.volume=a.audioLevel)})})}getLocalAudioStats(){return f(this,null,function*(){var t;let e={};return e[this.userId]={bytesSent:0,packetsSent:0,audioLevel:0},(t=this.uplinkConnection)!=null&&t.localMainAudioTrack&&(e[this.userId]=this.uplinkConnection.localMainAudioTrack.stat),e})}getLocalVideoStats(){return f(this,null,function*(){var t,r;let e={};return e[this.userId]=((r=(t=this.uplinkConnection)==null?void 0:t.localMainVideoTrack)==null?void 0:r.stat)||{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0},e})}getTransportStats(){return f(this,null,function*(){let e={rtt:0,downlinksRTT:{}};if(this.uplinkConnection){let t=yield this._stats.getSenderStats(this.uplinkConnection);e.rtt=t.rtt}for(let[,t]of this.remotePublishedUserMap){let r=yield this._stats.getReceiverStats(t);e.downlinksRTT[r.userId]=r.rtt}return e})}getRemoteVideoStats(e){return f(this,null,function*(){let t={};for(let[r,o]of this.remotePublishedUserMap)e==="main"&&o.muteState.hasVideo&&(t[r]=o.remoteVideoTrack.stat),e==="auxiliary"&&o.muteState.hasAuxiliary&&(t[r]=o.remoteAuxiliaryTrack.stat);return t})}getRemoteAudioStats(){return f(this,null,function*(){let e={};for(let[t,r]of this.remotePublishedUserMap)r.muteState.hasAudio&&(e[t]=r.remoteAudioTrack.stat);return e})}setTurnServer(e,t){this._log.info(`set turn server: ${JSON.stringify(e)} ${t||""}`);let r=[];Array.isArray(e)?e.forEach(o=>r.push(dt.getTurnServer(o))):dt.isPlainObject(e)&&r.push(dt.getTurnServer(e)),this._turnServers=r,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:Y.START_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:F.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:Y.STOP_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:F.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"})}sendStartPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?Y.START_PUBLISH_TENCENT_CDN:Y.START_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?F.START_PUBLISH_TENCENT_CDN_RES:F.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"})}sendStopPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?Y.STOP_PUBLISH_TENCENT_CDN:Y.STOP_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?F.STOP_PUBLISH_TENCENT_CDN_RES:F.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}sendStartPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Y.START_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:F.START_PUBLISH_CDN_STREAM_RES,commandDesc:"startPublishCDNStream"})}sendUpdatePushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Y.UPDATE_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:F.UPDATE_PUBLISH_CDN_STREAM_RES,commandDesc:"updatePublishCDNStream"})}sendStopPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Y.STOP_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:F.STOP_PUBLISH_CDN_STREAM_RES,commandDesc:"stopPublishCDNStream"})}sendAbilityStatus(e){var t;(t=this.signalChannel)==null||t.sendWaitForResponse({command:Y.ABILITY_STATUS_REPORT,data:e,timeout:5e3,responseCommand:F.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch(r=>{})}getIceServers(e){var t,r;return this._turnServers.length>0?this._turnServers:(t=this.scheduleResult.iceServers)!=null&&t.length?this.scheduleResult.iceServers:e!=null&&e.length?e:(r=this._iceServersFromJoin)!=null&&r.length?this._iceServersFromJoin:[]}getIceTransportPolicy(){return this.forceRelay?"relay":this._iceTransportPolicy||this.scheduleResult.iceTransportPolicy||"all"}getLogger(){return this._log}enableAIVoice(){throw new Error("Method not implemented.")}getSignalChannelUrl(){let e={mainUrl:"",backupUrl:""},t=dt.getEnv();return t?(e.mainUrl=`wss://${t}.rtc.qq.com`,e.backupUrl=e.mainUrl):this.proxy_ws?(e.mainUrl=this.proxy_ws,e.backupUrl=e.mainUrl):this.proxy_unified?(e.mainUrl=`wss://${this.proxy_unified}`,e.backupUrl=e.mainUrl):Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(e.mainUrl=`wss://${this.scheduleResult.domains[0]}`,e.backupUrl=e.mainUrl,this.scheduleResult.domains[1]&&(e.backupUrl=`wss://${this.scheduleResult.domains[1]}`)),e}getSignalInfo(){var e;return((e=this.signalChannel)==null?void 0:e.getSignalInfo())||{clientIp:"",relayIp:""}}reset(e=!1){this.stopSyncUserListInterval(),this.stopHeartbeat(),this.closeConnections(),this.clearNetworkQuality(),this.closeUplink("you exitRoom"),this.signalChannel&&(e&&this.signalChannel.keepAlive&&this.signalChannel.isConnected?this.signalChannel.stopKeepAliveIn(3600):(this.signalChannel.close(),this.setSignalChannel(null))),this._stats.reset(),this.userManager.clear(),this.userManager.removeAllListeners(),this.singlePC&&(this.singlePC.close(),this.singlePC=null),this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}}checkSubscribeBigSmallVideo(e){return f(this,null,function*(){let{subscribeState:t,userId:r,muteState:{hasSmall:o,hasVideo:n}}=e;if(!o&&!n||!t.video&&!t.smallVideo)return;let a=this._changeBigSmallRecords.get(r);if(!a||a.isSubscribing||a.reSubscribeCount<=0)return;let{options:c,reSubscribeCount:l}=a;if(c.video&&t.video||c.smallVideo&&t.smallVideo&&o)return;let u={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:c.video,smallVideo:c.smallVideo};try{if(!o&&u.smallVideo&&(u.video=!0,u.smallVideo=!1),u.smallVideo===t.smallVideo&&u.video===t.video)return;a.isSubscribing=!0,a.reSubscribeCount=l-1,yield e.subscribe(u,"main"),e.remoteVideoTrack.setMediaType(u.smallVideo?8:4),this._log.info(`change [${r}] to ${u.smallVideo?"small":"big"} video successfully. count ${rs-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount=rs}catch(h){this._log.info(`change [${r}] to ${u.smallVideo?"small":"big"} video failed. count ${rs-a.reSubscribeCount}. reason: ${h}`),a.isSubscribing=!1,a.reSubscribeCount===0&&this._changeBigSmallRecords.delete(r)}})}changeType(e,t){let o={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:rs};this._changeBigSmallRecords.set(t.userId,o),this._log.info(`set [${t.userId}] video prefer type: ${e?"small":"big"}`),this.emit("subscribe-small-video-changed",{userId:t.userId,isSmall:e});let n=this.remotePublishedUserMap.get(t.userId);n&&this.checkSubscribeBigSmallVideo(n)}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(e){this._businessInfo=e.businessInfo;let t={};if(cf(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!gr(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PURE_AUDIO})});this._pureAudioPushMode=e.pureAudioPushMode,t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.pure_audio_push_mod=this._pureAudioPushMode}if(!gr(e.userDefineRecordId)){let r=/^[A-Za-z0-9_-]{1,64}$/gi;if(e.userDefineRecordId.match(r)===null)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!gr(e.userDefinePushArgs))if(cf(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256)t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_push_args=e.userDefinePushArgs;else throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_USER_DEFINE_PUSH_ARGS})});En(t)||(this._businessInfo=JSON.stringify(t))}sendCustomMessage(e){var t;(t=this._customMessageManager)==null||t.send(e)}enableInsertableStreams(){return f(this,null,function*(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&Ui)return this.singlePC.enableInsertableStreams=!0,yield this.singlePC.waitForPeerConnectionConnected(),yield this.singlePC.startReconnection()})}sendSignalMessage(e){var t;return this.signalChannel?(t=this.signalChannel)==null?void 0:t.sendWaitForResponseWithRetry(e):Promise.reject(new y({code:I.INVALID_OPERATION,message:"not join"}))}get enableCodecPipeline(){return this.videoManager.encodePipeline.length>0||this.videoManager.decodePipeline.length>0||this.audioManager.encodePipeline.length>0||this.audioManager.decodePipeline.length>0}get scriptTransformWorker(){var e;return(e=this.singlePC)==null?void 0:e.scriptTransformWorker}switchRoom(e){return f(this,null,function*(){var D,_;if(!this.signalChannel)return;let{roomId:t,strRoomId:r,userSig:o,privateMapKey:n}=e,a=((D=this.scheduleResult.config)==null?void 0:D.autoSubscribeCount)||(e==null?void 0:e.autoSubscribeCount)||1,c=String(this.useStringRoomId?r:t),l=[];for(let S=0;S<a;S++)l.push({audioSsrc:Et(),bigVideoSsrc:Et(),bigVideoRtxSsrc:Et(),auxVideoSsrc:Et(),auxVideoRtxSsrc:Et()});let u={currRoomId:this.roomId,targetRoomId:c,useStringRoomId:this.useStringRoomId,ability:(_=this.singlePC)==null?void 0:_.clientAbility,userSig:o!=null?o:this.userSig,privateMapKey:n!=null?n:this.privateMapKey,subscribe:l};this.singlePC&&(this.singlePC.autoSubscribedSsrcGroups=l,this.singlePC.autoSubscribedUserMap.clear()),E.emit(A.SWITCH_ROOM_START,{room:this});let h=yield this.signalChannel.sendWaitForResponse({command:Y.SWITCH_ROOM,responseCommand:F.SEND_SWITCH_ROOM_RES,data:u}),{code:m,message:g}=h.data;if(m===0){let S=this.roomId;this.roomId=this.useStringRoomId?r:String(t),gr(o)||(this.userSig=o),gr(n)||(this.privateMapKey=n),E.emit(A.SWITCH_ROOM_SUCCESS,{room:this,currentRoomId:S,targetRoomId:c})}else{this._log.error(`switch room failed. result: ${m} error: ${g}`),this.singlePC&&(this.singlePC.autoSubscribedSsrcGroups=[]);let S=new y({code:I.SWITCH_ROOM_FAILED,extraCode:m,message:g});throw E.emit(A.SWITCH_ROOM_FAILED,{room:this,error:S}),S}})}isSwitchRoomSupported(){var t;let e="unable to use switchRoom API, fallback to exitRoom and enterRoom.";return((t=this.scheduleResult.config)==null?void 0:t.switchRoom)!==!0?(this._log.warn(`${e} Reason: this sdkAppId is not supported, please contact us [https://trtc.io/contact] to enable it.`),!1):this.scene!=="live"?(this._log.warn(`${e} Reason: the scene is not 'live'.`),!1):this.role!=="audience"?(this._log.warn(`${e} Reason: the role is not 'audience'.`),!1):this.singlePC?!0:(this._log.warn(`${e} Reason: is not using single peerConnection.`),!1)}};v([Te(["left",H.INIT],"joined"),pt({settings:{retries:1,timeout:0},onRetrying(e){this._log.warn(`join retry ${e}`)},onRetryFailed(e){this._log.error("join failed",e)},onError(e,t){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),Wt(!0),this.reset(),t()):this.signalChannel&&this.signalChannel.isConnected&&this.signalChannel.keepAlive?(this._log.warn("is using keepAlive ws, retry join"),this.signalChannel.close(),this.reset(),t()):(this.reset(),t())}}),fp()],jt.prototype,"join",1),v([Te("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),_p(),xa("leave room"),Ho({fnName:"publish",validateArgs:!1}),Ho({fnName:"unsubscribe",validateArgs:!1})],jt.prototype,"leave",1),v([Rt(),of(),pt({settings:{retries:Ai,timeout:e=>Pt(e)},onError(e,t,r){var o;(o=e.message)!=null&&o.includes("timeout")?(this._log.warn("publish timeout"),t()):(this._log.error(`publish failed: ${e}`),r(e),E.emit(A.PUBLISH_FAILED,{room:this}))}})],jt.prototype,"publish",1),v([Ho({fnName:"publish"}),Rm("api-call"),Rt(),nf(),et(function(){var e,t;this.localTracks.size===0&&dr()&&((t=(e=this.singlePC)==null?void 0:e.getPeerConnection())==null||t.getSenders().forEach(r=>r.track&&r.replaceTrack(null)))})],jt.prototype,"unpublish",1),v([Ma(e=>{if(e.code!==I.API_CALL_ABORTED)throw e}),$i(e=>e.userId)],jt.prototype,"replaceTrack",1),v([$i((...e)=>e[0].userId),Va(),gp(),pt({settings:{retries:Ai,timeout:e=>Pt(e)},onError(e,t,r,o){e.message.includes("timeout")?(this._log.warn("subscribe timeout"),t()):(this._log.error(`subscribe failed: ${e}`),r(e),E.emit(A.SUBSCRIBE_FAILED,{room:this,remoteTracks:o}))}})],jt.prototype,"subscribe",1),v([Ho({fnName:"subscribe",callback(...e){this.singlePC||e.forEach(t=>{let r=this.remotePublishedUserMap.get(t.userId);r&&!r.isMainStreamSubscribed&&!r.isAuxStreamSubscribed&&r.close("you unsubscribed")})}}),$i((...e)=>e[0].userId)],jt.prototype,"unsubscribe",1);un.create=un._create.bind(un,jt);var cH=un;export{cH as default};
121
+ `,e=new Blob([i],{type:"application/javascript"}),t=URL.createObjectURL(e);this.worker=new Worker(t),URL.revokeObjectURL(t),this.worker.onerror=r=>this._log.warn("worker error:",r.message,r.filename||"unknown",r.lineno||"unknown"),this.worker.onmessage=r=>{var l;let{type:o,trackId:n,message:a,count:c}=r.data;if(o==="black")(l=this.callbacks.get(n))==null||l();else if(o==="log")this._log.warn(a);else if(o==="blackCount"){let u=this.userIdMap.get(n);this._log.warn(`${u||n} black count: ${c}`)}}}return this.worker}start({track:i,isUplink:e,room:t,userId:r,onBlack:o}){if(this._log.debug("start detect black video",i.id),!ko()||!o||!i||T(Worker))return;let n=a=>{var l,u,h,m;let c;if(e)c=(u=(l=a.msg_up_stream_info)==null?void 0:l.msg_video_status)==null?void 0:u.filter(g=>g.uint32_video_stream_type===3)[0];else{let g=(h=a.msg_down_stream_info)==null?void 0:h.filter(D=>{var _;return((_=D.msg_user_info)==null?void 0:_.str_identifier)===r})[0];c=(m=g==null?void 0:g.msg_video_status)==null?void 0:m.filter(D=>D.uint32_video_stream_type===3)[0]}if(c){let g=(c.uint32_video_codec_bitrate||0)/1e3;if(this.sleep[i.id]&&this.sleep[i.id]>0){this.sleep[i.id]-=1;return}g>0&&g<10&&(this.sleep[i.id]=30,this._log.debug("track bitrate",g,"start check"),this.checkOnce(i,30*1e3))}};return t.on("heartbeat-report",n),this.heartbeatListenerCleaner.set(i.id,()=>t.off("heartbeat-report",n)),this.callbacks.set(i.id,o),this.userIdMap.set(i.id,r),i.id}checkOnce(i,e){try{let t=this.getWorker();if(!t)throw new Error("Worker not available");let r=new MediaStreamTrackProcessor({track:i});t.postMessage({type:"addTrack",trackId:i.id,timeout:e,readable:r.readable},[r.readable])}catch(t){this._log.warn("check error:",t),this.stop(i.id)}}stop(i){if(i){this.worker&&this.worker.postMessage({type:"removeTrack",trackId:i}),this.callbacks.delete(i),delete this.sleep[i];let e=this.heartbeatListenerCleaner.get(i);e&&e(),this.heartbeatListenerCleaner.delete(i),this.userIdMap.delete(i)}}destroy(){this.callbacks.forEach((i,e)=>this.stop(e)),this.worker&&(this.worker.terminate(),this.worker=null)}},Yi=new Gu;var Tn=class extends Kr{constructor(e){super(L(N({},e),{isUplink:!0}));d(this,"localMainAudioTrack",null);d(this,"localMainVideoTrack",null);d(this,"localAuxAudioTrack",null);d(this,"localAuxVideoTrack",null);d(this,"_isPublishingAux",!1);d(this,"_publishingLocalAudioTrack");d(this,"_publishingLocalVideoTrack");d(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});d(this,"_flag",0);d(this,"_checkPublishStateTimeoutId",-1);this.initialize()}get videoCodec(){var e;return((e=this.singlePC)==null?void 0:e.videoCodec)||"h264"}get ssrc(){if(!this.singlePC)return{audio:0,video:0,videoRtx:0,small:0,smallRtx:0,auxiliary:0,auxiliaryRtx:0};let{audioSsrc:e,bigVideoSsrc:t,bigVideoRtxSsrc:r,smallVideoSsrc:o,smallVideoRtxSsrc:n,auxVideoSsrc:a,auxVideoRtxSsrc:c}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:r||0,small:o||0,smallRtx:n||0,auxiliary:a||0,auxiliaryRtx:c||0}}get flag(){return this._flag}set flag(e){this._flag!==e&&(this._flag=e,this.checkPublishState())}checkPublishState(e=!1){if(!e&&this._checkPublishStateTimeoutId>0)return;let{publishState:t,serverPublishState:r}=this,o=Object.keys(t).find(n=>t[n]!==r[n]);if(o)if(e)this._log.warn(`publish state not matched, ${o} local:${t[o]} server:${r[o]} ${Pi()} ${Or()}`),b.addCount({key:521e3});else{this._checkPublishStateTimeoutId=oe.run("timeout",()=>this.checkPublishState(!0),{delay:10*1e3,count:1});return}oe.clearTask(this._checkPublishStateTimeoutId),this._checkPublishStateTimeoutId=-1}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}get publishState(){var t,r,o,n;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(si()?(e.audio=!!((t=a[0])!=null&&t.track),e.bigVideo=!!((r=a[1])!=null&&r.track),e.smallVideo=!!((o=a[2])!=null&&o.track),e.auxVideo=!!((n=a[3])!=null&&n.track)):a.forEach(c=>{c.track&&(c.track.kind===p.AUDIO?e.audio=!0:(e.bigVideo=!0,this._room.videoManager.hasSmall&&(e.smallVideo=!0)))}))}return e}get publishingState(){let{publishState:e}=this,t=N({},e);return this._publishingLocalAudioTrack&&(t.audio=!0),this._publishingLocalVideoTrack&&(this._isPublishingAux?t.auxVideo=!0:(t.bigVideo=!0,this._publishingLocalVideoTrack.small&&(t.smallVideo=!0))),t}get serverPublishState(){return{audio:!!(this.flag&ir),bigVideo:!!(this.flag&tr),smallVideo:!!(this.flag&so),auxVideo:!!(this.flag&Er)}}get muteState(){var e,t,r;return{audio:!!((e=this.localMainAudioTrack)!=null&&e.muted),bigVideo:!!((t=this.localMainVideoTrack)!=null&&t.muted),auxVideo:!!((r=this.localAuxVideoTrack)!=null&&r.muted)}}initialize(){this.installEvents()}close(e){var r;let t=((r=this._peerConnection)==null?void 0:r.getSenders())||[];for(let o of t)o.replaceTrack(null);super.close(e),this.uninstallEvents(),this.uninstallTrackMuteEvents(this.localMainAudioTrack,this.localMainVideoTrack,this.localAuxVideoTrack),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),this.installSPCEvents()}installSPCEvents(){var e,t;(e=this.singlePC)!=null&&e.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||(t=this.singlePC)==null||t.on("spc-reconnected",this.onSinglePCReconnected,this)}uninstallSPCEvents(){var e;(e=this.singlePC)==null||e.off("spc-reconnected",this.onSinglePCReconnected,this)}uninstallEvents(){this.off("connection-state-changed",this.handleConnectionStateChange,this),this.uninstallSPCEvents()}emitConnectionStateChangedEvent(e,t){var n,a,c;let r=this._currentState,o=super.emitConnectionStateChangedEvent(e);return o&&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}),(c=this._publishingLocalVideoTrack)==null||c.emit("connection-state-changed",{prevState:r,state:e}))),o}onVideoEncodeFailed(e){var t;e&&e.isMediaTrackActive&&this.videoCodec==="h264"&&(this._log.warn("h264 encoder not working"),(t=this.singlePC)!=null&&t.isVP8EncodeSupported&&(this._log.warn("switch to vp8"),this.singlePC.switchVideoEncoder("vp8")))}publish(o){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:r}){var l,u,h,m,g,D,_;if(!this.singlePC)return;this.installEvents(),yield this.singlePC.waitForPeerConnectionConnected();let{publishState:n,muteState:a}=this;if(e&&(this._publishingLocalAudioTrack=e,n.audio=!0,a.audio=e.muted),t){if(!this.singlePC.isH264EncodeSupported&&!this.singlePC.isVP8EncodeSupported)throw new y({code:I.NOT_SUPPORTED_H264,message:x({key:P.NOT_SUPPORTED_H264ENCODE})});this.singlePC.isUsingH264&&!this.singlePC.isH264EncodeSupported&&this.singlePC.isVP8EncodeSupported&&(this._log.warn("h264 encoder not supported"),yield this.singlePC.switchVideoEncoder("vp8")),pe&&Ss()===115&&t.profile.width*t.profile.height<=640*360&&(this._log.warn(`fallback video to defaultBigVideoProfile: ${JSON.stringify(er)}`),t.setProfile(er),yield t.applyProfile()),this._publishingLocalVideoTrack=t,r?(n.auxVideo=!0,a.auxVideo=t.muted):(n.bigVideo=!0,a.bigVideo=t.muted)}this._isPublishingAux=r;let c;if(t&&!r&&t.small&&(c=this._room.videoManager.smallTrack,n.smallVideo=!0),yield this._signalChannel.sendWaitForResponseWithRetry({command:Y.SPC_PUBLISH,responseCommand:F.SPC_PUBLISH_RESULT,data:L(N({},this.singlePC.uplinkSSRC),{state:n,muteState:a}),retries:3}),yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:c,isAuxiliary:r}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,t){this[r?"localAuxVideoTrack":"localMainVideoTrack"]=t,yield this.singlePC.setDegradationPreference(this._peerConnection.getSenders()[r?3:1],t.contentHint,t.streamType);let{scaleResolutionDownBy:S}=t;yield this.singlePC.setScaleResolutionDownBy(this._peerConnection.getSenders()[r?3:1],S,t.streamType)}e&&(this[r?"localAuxAudioTrack":"localMainAudioTrack"]=e),yield this.singlePC.setBandwidth({audio:((l=this.localMainAudioTrack)==null?void 0:l.profile.bitrate)||((u=this.localAuxAudioTrack)==null?void 0:u.profile.bitrate),bigVideo:(h=this.localMainVideoTrack)==null?void 0:h.profile.bitrate,smallVideo:(g=(m=this.localMainVideoTrack)==null?void 0:m.small)==null?void 0:g.bitrate,auxVideo:(D=this.localAuxVideoTrack)==null?void 0:D.profile.bitrate}),this.sendMediaSettings(),this.installTrackMuteEvents(e,t),(this._room.preferHW||(_=this._room.scheduleResult.config)!=null&&_.preferHW)&&t&&t.profile.width*t.profile.height>=1280*720&&this.singlePC.useHWEncoder(!0,r?7:2)})}publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:r,isAuxiliary:o}){if(!mt())return;this._log.info("publish by transceiver");let n=t==null?void 0:t.outMediaTrack,a=e==null?void 0:e.outMediaTrack,c=this._peerConnection.getTransceivers(),l=[],u=[],h=(g,D,_)=>{var O;let S=c[D].sender.replaceTrack(_);u.push(D),(O=this.singlePC)!=null&&O.enableInsertableStreams&&S.then(()=>this.createEncodedStreams(c[D].sender,g)),this.initSenderTransform(c[D].sender,g),l.push(S)};a&&h(e.mediaType,0,a),n&&h(t.mediaType,o?3:1,n),t!=null&&t.small&&l.push(this.publishSmall(this._room.videoManager.smallMode,t));let m=this.singlePC.setTransceiverDirection(te.SENDONLY,u);return l.push(m),Promise.all(l)}getTrackByMediaType(e){switch(e){case 1:return this.localMainAudioTrack||this._publishingLocalAudioTrack;case 4:case 8:return this.localMainVideoTrack||this._publishingLocalVideoTrack;case 2:return this.localAuxVideoTrack||this._publishingLocalVideoTrack;default:return null}}createEncodedStreams(e,t){var a,c;if(this.singlePC.insertableStreamsAbortMap.has(e))return;let r=e.createEncodedStreams(),o=new AbortController;(a=this.singlePC)==null||a.addAbortController(e,o),((c=this.getTrackByMediaType(t))!=null&&c.enableEncodeFrame?r.readable.pipeThrough(new TransformStream({transform:(l,u)=>{var m;let h=this.getTrackByMediaType(t);u.enqueue((m=this.singlePC)!=null&&m.isUsingH264&&h?h.encodeFrame(l,t===8):l)}}),o):r.readable).pipeTo(r.writable,o).catch(l=>{this._log.debug("encoded stream error",l),l!=="destory"&&this._log.warn(l)})}initSenderTransform(e,t){if(!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker||!Ns)return;let r=t!==2,o=t===8;e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!1,isAudio:t===1,isMain:r,isSmall:o}))}enableSmall(e){return f(this,null,function*(){e?yield this.publishSmall(this._room.videoManager.smallMode):yield this.unpublishSmall()})}publishSmall(r){return f(this,arguments,function*(e,t=this.localMainVideoTrack){var l;if(!this.singlePC)return;let o=this._peerConnection.getTransceivers(),{sender:n}=o[2],a=yield this.doPublishSmall(e,t),c=e==="canvas"?524700:524701;if(b.addSuccessEvent({key:c}),!a){b.addFailedEvent({key:c,error:10001});return}(l=this.singlePC)!=null&&l.enableInsertableStreams&&this.createEncodedStreams(n,8),this.initSenderTransform(n,8),yield this.singlePC.setTransceiverDirection(te.SENDONLY,[2]),this.updateMediaSettings(),yield this.doPublishChange(),this._blackSmallVideoDetectionId=Yi.start({track:n.track,room:this._room,isUplink:!0,userId:this.userId,onBlack:()=>{this._log.warn("small video is black");let u=e==="canvas"?524700:524701;b.addFailedEvent({key:u,error:10002}),Yi.stop(this._blackSmallVideoDetectionId)}})})}doPublishSmall(r){return f(this,arguments,function*(e,t=this.localMainVideoTrack){if(!this.singlePC)return null;this._log.info("publish small",e);let o=this._peerConnection.getTransceivers(),{sender:n}=o[2];if(e==="canvas"&&this._room.videoManager.smallTrack)return yield n.replaceTrack(this._room.videoManager.smallTrack),"canvas";if(e==="api"&&(t!=null&&t.outMediaTrack)&&(t!=null&&t.small)){yield n.replaceTrack(t==null?void 0:t.outMediaTrack);let a=n.getParameters(),c=ls(t==null?void 0:t.profile,t==null?void 0:t.small);return this._log.info("small scaleResolutionDownBy",c),a.encodings[0].scaleResolutionDownBy=c,n.setParameters(a),"api"}return this._log.warn(`small track can not be enabled, smallMode: ${this._room.videoManager.smallMode}, smallTrack: ${!!this._room.videoManager.smallTrack}, bigVideoTrack: ${!!(t!=null&&t.outMediaTrack)}`),null})}unpublishSmall(){return f(this,null,function*(){if(!this.singlePC)return;this._log.info("unpublish small"),yield this._peerConnection.getTransceivers()[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(te.INACTIVE,[2]),this.updateMediaSettings(),yield this.doPublishChange(),Yi.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0})}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}){var l;yield(l=this.singlePC)==null?void 0:l.waitForPeerConnectionConnected();let o=t&&t===this.localAuxVideoTrack,n=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),c=[];e&&(o?this.localAuxAudioTrack=null:this.localMainAudioTrack=null,!this.localMainAudioTrack&&!this.localAuxAudioTrack&&(yield a[0].replaceTrack(null),c.push(0))),n&&(o?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=L(N({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),c.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=L(N({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),c.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.singlePC.setTransceiverDirection(te.INACTIVE,c),yield this.doPublishChange(!1)):yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),t==null||t.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return f(this,null,function*(){let t={state:this.publishingState,constraintConfig:this._mediaSettings},r=yield this._signalChannel.sendWaitForResponseWithRetry({command:Y.PUBLISH_STATE_CHANGE,data:t,responseCommand:F.PUBLISH_STATE_CHANGE_RESULT,enableLog:e,retries:3});this.checkPublishResultCode(r.data.code,r.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:Y.UNPUBLISH,commandDesc:"unpublish",responseCommand:F.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===I.API_CALL_TIMEOUT)return Promise.resolve();throw t})}updateMediaSettings(){var o;this._mediaSettings.videoCodec=((o=this.singlePC)==null?void 0:o.videoCodec)||"h264";let e=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:t,localAuxVideoTrack:r}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?r=this._publishingLocalVideoTrack:t=this._publishingLocalVideoTrack),oi){if(e&&e.outMediaTrack){let n=e.outMediaTrack.getSettings();this._mediaSettings.audioChannel=n.channelCount||1,this._mediaSettings.audioBps=e.profile.bitrate*1e3,this._mediaSettings.audioFs=n.sampleRate||0}if(t&&t.outMediaTrack){let n=t.outMediaTrack.getSettings(),{scaleResolutionDownBy:a}=t;this._mediaSettings.videoWidth=n.width/a||0,this._mediaSettings.videoHeight=n.height/a||0,this._mediaSettings.videoFps=n.frameRate||0,this._mediaSettings.videoBps=t.profile.bitrate*1e3,t.small&&(this._mediaSettings.smallVideoWidth=t.small.width,this._mediaSettings.smallVideoHeight=t.small.height,this._mediaSettings.smallVideoFps=t.small.frameRate,this._mediaSettings.smallVideoBps=t.small.bitrate*1e3)}if(r&&r.outMediaTrack){let n=r.outMediaTrack.getSettings(),{scaleResolutionDownBy:a}=r;this._mediaSettings.auxVideoWidth=n.width/a||0,this._mediaSettings.auxVideoHeight=n.height/a||0,this._mediaSettings.auxVideoFps=n.frameRate||0,this._mediaSettings.auxVideoBps=r.profile.bitrate*1e3}}else e&&e.outMediaTrack&&(this._mediaSettings.audioChannel=e.profile.channelCount,this._mediaSettings.audioBps=e.profile.bitrate*1e3,this._mediaSettings.audioFs=e.profile.sampleRate),t&&t.outMediaTrack&&(this._mediaSettings.videoWidth=t.profile.width,this._mediaSettings.videoHeight=t.profile.height,this._mediaSettings.videoFps=t.profile.frameRate,this._mediaSettings.videoBps=t.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:Y.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:F.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?p.AUXILIARY:p.MAIN} stream`),si()&&(yield this.addTrackByTransceiver(e,t))})}addTrackByTransceiver(e,t){return f(this,null,function*(){var o;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===p.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),n===1&&((o=this.localMainVideoTrack)!=null&&o.small)&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===te.INACTIVE&&(yield this.singlePC.setTransceiverDirection(te.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}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?p.AUXILIARY:p.MAIN} stream`),si()&&(yield this.removeTrackByTransceiver(e,t))})}removeTrackByTransceiver(e,t){return f(this,null,function*(){if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===p.AUDIO)yield r[0].sender.replaceTrack(null);else{let o=t?3:1;yield r[o].sender.replaceTrack(null),o===1&&this._room.videoManager.hasSmall&&(yield r[2].sender.replaceTrack(null)),yield this.singlePC.setTransceiverDirection(te.INACTIVE,[o])}this.updateMediaSettings(),yield this.doPublishChange()})}replaceTrack(e){return f(this,null,function*(){var n;let t=(n=this._peerConnection)==null?void 0:n.getSenders(),r=e.outMediaTrack||e.mediaTrack;if(!t||t.length===0||!r||t.find(a=>a.track===r))return!1;let o=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info(`is replacing ${r.kind} track ${r.id} ${r.label} on ${o?p.AUXILIARY:p.MAIN} stream`),r.kind===p.AUDIO&&t[0]&&(yield t[0].replaceTrack(r)),r.kind===p.VIDEO&&(!o&&t[1]&&(yield t[1].replaceTrack(r)),o&&t[3]&&(yield t[3].replaceTrack(r))),!0})}setBandwidth(o){return f(this,arguments,function*({bandwidth:e,type:t,videoType:r}){if(this.singlePC){let n={};t===p.AUDIO?n.audio=e:r==="big"?n.bigVideo=e:r==="small"?n.smallVideo=e:n.auxVideo=e,yield this.singlePC.setBandwidth(n)}})}sendMutedFlag(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info(`send muted state: ${JSON.stringify(this.muteState)}`),this._signalChannel.sendWaitForResponseWithRetry({command:Y.UPDATE_MUTE_STAT,responseCommand:F.MUTE_RESULT,data:this.muteState,retries:3}).catch(()=>{}))}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&E.emit(A.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(e=p.VIDEO){if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===p.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===p.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===p.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===p.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===Sr?(this._log.error(Ve.NOT_SUPPORTED_H264ENCODE),new y({code:I.NOT_SUPPORTED_H264,message:x({key:P.NOT_SUPPORTED_H264ENCODE})})):new y({code:I.UNKNOWN,message:x({key:P.SIGNAL_RESPONSE_FAILED,data:{signalResponse:F.PUBLISH_RESULT,code:e,message:t}})})}onSinglePCReconnected(){return f(this,null,function*(){this.isMainStreamPublished&&(this._log.warn("republish main stream"),yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(this._log.warn("republish aux stream"),yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0}))})}};v([et(function({localVideoTrack:e}){e==null||e.once("6",this.onVideoEncodeFailed,this)})],Tn.prototype,"publish",1),v([et(function({localVideoTrack:e}){e==null||e.off("6",this.onVideoEncodeFailed,this)})],Tn.prototype,"unpublish",1);var Wu=Tn;function rf(s){return Object.keys(s).filter(i=>s[i])}var Ys=class extends Kr{constructor(e){super(L(N({},e),{isUplink:!1}));d(this,"_flag",0);d(this,"isRobot",!1);d(this,"role","anchor");d(this,"remoteAudioTrack");d(this,"remoteVideoTrack");d(this,"remoteAuxiliaryTrack");d(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0});d(this,"jitterBufferTimeoutId",-1);this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=new Gt(this._room,this),this.remoteVideoTrack=new fi(this._room,this),this.remoteAuxiliaryTrack=new Bs(this._room,this),this.initialize()}get videoCodec(){var e;return((e=this.singlePC)==null?void 0:e.downlinkVideoCodec)||"h264"}get subscribeState(){return{audio:this.remoteAudioTrack.isSubscribed||this.remoteAudioTrack.isSubscribing,video:this.remoteVideoTrack.isBig&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),smallVideo:this.remoteVideoTrack.isSmall&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),auxiliary:this.remoteAuxiliaryTrack.isSubscribed||this.remoteAuxiliaryTrack.isSubscribing}}get muteState(){return bi(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,r,o;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(r=this.remoteVideoTrack)==null||r.onFlagChanged(),(o=this.remoteAuxiliaryTrack)==null||o.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===p.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){clearTimeout(this.jitterBufferTimeoutId),super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents(),this.removeDownlink()}installEvents(){this.singlePC&&(this.listeners("track").includes(this.onTrack)||this.singlePC.on("track",this.onTrack,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||this.singlePC.on("spc-reconnected",this.onSinglePCReconnected,this))}uninstallEvents(){this.singlePC&&(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this))}emitConnectionStateChangedEvent(e){var o,n;let t=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&t!==e&&((o=this.remoteVideoTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),r}onTrack(e){var u,h;let t=e.streams[0],{track:r,receiver:o}=e;if(!t.id.includes(this.tinyId))return;let a=t.id.includes("aux")?"auxiliary":"main";this._log.debug(`ontrack ${a} ${r.kind}`);let c=p.AUDIO;r.kind===p.VIDEO&&(c=a===p.MAIN?p.VIDEO:p.AUXILIARY);let l=this.remoteAudioTrack;c===p.VIDEO?l=this.remoteVideoTrack:c===p.AUXILIARY&&(l=this.remoteAuxiliaryTrack),(u=this.singlePC)==null||u.receiverRemoteTrackMap.set(o,l),(h=this.singlePC)!=null&&h.scriptTransformWorker&&this.initReceiverTransform(o,a,r.kind===p.AUDIO),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(o),l.setInputMediaStreamTrack(r)}createEncodedStreams(e){if(!this.singlePC.insertableStreamsAbortMap.has(e)){let t=e.createEncodedStreams(),r=new AbortController,o={abortController:r,enqueue:n=>{var c,l;let a=(c=this.singlePC)==null?void 0:c.receiverRemoteTrackMap.get(e);return!a||a.kind==="video"&&!((l=this.singlePC)!=null&&l.isUsingH264)?n:a.decodeFrame(n)}};t.readable.pipeThrough(new TransformStream({transform:(n,a)=>{let c=o.enqueue(n);c&&a.enqueue(c)}})).pipeTo(t.writable,r).catch(n=>{n!=="destory"&&this._log.warn(n)}),this.singlePC.addAbortController(e,r)}}initReceiverTransform(e,t,r){!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker||e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!0,isAudio:r,userId:this.userId,streamType:t}))}subscribe(e,t){return f(this,null,function*(){var r;try{let o=!0;if(this._log.info(`subscribe ${t} ${rf(e)}`),this.hasSSRC){let n="subscribe_change";Object.values(e).find(a=>a===!0)||(n="unsubscribe"),yield this.sendSubscription(n,e)}else{if((r=this.singlePC)!=null&&r.autoSubscribedUserMap.size){let n=this.singlePC.autoSubscribedUserMap.get(this.userId);if(n){this.singlePC.autoSubscribedUserMap.delete(this.userId);let a=this.singlePC.autoSubscribedSsrcGroups[n.groupIndex];a&&(this.ssrc={audio:a.audioSsrc,video:a.bigVideoSsrc,videoRtx:a.bigVideoRtxSsrc,auxiliary:a.auxVideoSsrc,auxiliaryRtx:a.auxVideoRtxSsrc},o=!1)}}yield this.doSubscribe(e,o),this.checkTrackEnded(e)}if(e.smallVideo){let{user:n,mediaTrack:a}=this.remoteVideoTrack;b.addSuccessEvent({key:524702}),this._blackSmallVideoDetectionId=Yi.start({track:a,isUplink:!1,room:this._room,userId:this.userId,onBlack:()=>{this._log.warn("small video is black, auto change to big"),this._room.changeType(!1,n),b.addFailedEvent({key:524702}),Yi.stop(this._blackSmallVideoDetectionId)}})}else Yi.stop(this._blackSmallVideoDetectionId)}catch(o){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${o.message} ${JSON.stringify(this.muteState)}`),new y({code:I.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):o}})}checkTrackEnded(e){var t,r,o;if((e.audio&&((t=this.remoteAudioTrack.mediaTrack)==null?void 0:t.readyState)==="ended"||e.video&&((r=this.remoteVideoTrack.mediaTrack)==null?void 0:r.readyState)==="ended"||e.auxiliary&&((o=this.remoteAuxiliaryTrack.mediaTrack)==null?void 0:o.readState)==="ended")&&this.singlePC&&!this.singlePC.isReconnecting){if(this._log.warn("remote track ended start spc reconnect"),Ze&&lt<92)return;this.singlePC.startReconnection()}}unsubscribe(r){return f(this,arguments,function*({remoteTracks:e,streamType:t}){var a;if(t==="main"&&!this.isMainStreamSubscribed||t==="auxiliary"&&!this.isAuxStreamSubscribed){this._log.info(`${t} stream already unsubscribed`);return}let o=N({},this.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:o.audio=!1;break;case 4:o.video=!1;break;case 8:o.smallVideo=!1;break;case 2:o.auxiliary=!1;break;default:break}});let n="subscribe_change";Object.values(o).find(c=>c===!0)||(n="unsubscribe"),this._log.info(`${n==="unsubscribe"?n:"subscribe"} ${t} [${rf(o)}]`),n==="unsubscribe"&&((a=this.singlePC)==null||a.removeDownlinkQueue.add(this.tinyId)),yield this.sendSubscription(n,o),t==="main"&&(Yi.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0),n==="unsubscribe"&&(yield this.removeDownlink())})}sendSubscription(e,t=this.subscribeState){let r={srcTinyId:this.tinyId,srcUserId:this.userId},o=Y.UNSUBSCRIBE,n=F.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(r={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},o=Y.SUBSCRIBE_CHANGE,n=F.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponseWithRetry({command:o,data:r,responseCommand:n,timeout:1e4,retries:3}).then(({data:a})=>{if(a.code!==0){let c=new y({code:a.code,message:x({key:P.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(c),c}})}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}setDelay({audioDelay:e,videoDelay:t}){this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=t}onSinglePCReconnected(){return f(this,null,function*(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary)&&(this._log.warn(`resubscribe ${JSON.stringify(this.subscribeState)}`),yield this.doSubscribe(this.subscribeState),this.remoteAudioTrack.checkDecodeResult(),this.remoteVideoTrack.checkDecodeResult(),this.remoteAuxiliaryTrack.checkDecodeResult())})}get hasSSRC(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}doSubscribe(){return f(this,arguments,function*(e=this.subscribeState,t=!0){if(this.singlePC){this.singlePC.addDownlinkQueue.add(this.tinyId),yield this.singlePC.waitForPeerConnectionConnected();try{if(t||!this.hasSSRC){let r={audioSsrc:Et(),bigVideoSsrc:Et(),bigVideoRtxSsrc:Et(),auxVideoSsrc:Et(),auxVideoRtxSsrc:Et()},{audioSsrc:o,bigVideoSsrc:n,bigVideoRtxSsrc:a,auxVideoSsrc:c,auxVideoRtxSsrc:l}=r;this.ssrc={audio:o,video:n,videoRtx:a,auxiliary:c,auxiliaryRtx:l},this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc});try{let u=yield this._signalChannel.sendWaitForResponseWithRetry({command:Y.SPC_SUBSCRIBE,responseCommand:F.SPC_SUBSCRIBE_RESULT,data:{srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo,customData:!1,ssrc:r},retries:3,retryTimeout:0});if(u.data.code!==0&&u.data.code!==-10036)throw new y({code:u.data.code,message:u.data.message})}catch(u){throw yield this.removeDownlink(),u}return}this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc})}finally{if(!ga)return;let{main:r,aux:o}=this._room.jitterBufferDelay||{},{jitterDelay:n=r,jitterDelayAux:a=o}=this._room.scheduleResult.config||{};(q(n)||q(a))&&this.setJitterBufferDelay({mainDelay:n,auxDelay:a})}}})}removeDownlink(){return f(this,null,function*(){if(!this.singlePC)return;this.ssrc={audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0},this.singlePC.removeDownlinkQueue.delete(this.tinyId);let e=this._room.scheduleResult.config;(e!=null&&e.jitterDelay||e!=null&&e.jitterDelayAux)&&this.setJitterBufferDelay({mainDelay:0,auxDelay:0}),yield this.singlePC.removeDownlink(this.userId)})}setJitterBufferDelay({mainDelay:e,auxDelay:t}){if(!ga||!this.singlePC||!this._peerConnection||Oi(e)&&Oi(t))return Promise.resolve();this._log.info(`set jitterBuffer main: ${e} aux: ${t}`);let r=this.singlePC.getReceiversByUserId(this.userId);return q(e)&&(this.remoteAudioTrack.jitterBufferDelay=e,this.remoteVideoTrack.jitterBufferDelay=e),q(t)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=t,Oi(e)&&(this.remoteAudioTrack.jitterBufferDelay=t)),new Promise(o=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:o})})}doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:o}){try{if(e===0&&t===0)return r.forEach(a=>a.jitterBufferTarget=0),o();if(r.forEach(a=>{var h;let c=a.track===this.remoteAuxiliaryTrack.outMediaTrack||Oi(e)&&a.track===this.remoteAudioTrack.outMediaTrack;if(c&&Oi(t)||!c&&Oi(e))return;let l=c?t||0:e,u=(a.jitterBufferTarget||0)+100;u>l||(a.jitterBufferTarget=u,this._log.debug(`set ${c?"aux ":""}${(h=a==null?void 0:a.track)==null?void 0:h.kind} jitterBuffer delay ${u} -> ${l}`))}),!r.find(a=>{let c=a.track===this.remoteAuxiliaryTrack.outMediaTrack?t||0:e;return a.jitterBufferTarget<c}))return this._log.info(`set jitterBuffer main: ${e} aux: ${t} done`),o();this.jitterBufferTimeoutId=setTimeout(()=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:o})},1e3)}catch(n){this._log.warn(`set jitterBuffer delay error: ${n}`),clearTimeout(this.jitterBufferTimeoutId),o()}}get audioReceiver(){var e;return((e=this.singlePC)==null?void 0:e.getReceiversByUserId(this.userId)[0])||null}};v([Rt(),Q(e=>function(...t){return new Promise((r,o)=>{let n=a=>{this.off("closed",n),o(new y({code:I.API_CALL_ABORTED,message:x({key:P.CONNECTION_ABORTED,data:a})}))};this.on("closed",n),e.apply(this,t).then(r,o).finally(()=>{this.off("closed",n)})})})],Ys.prototype,"subscribe",1),v([Rt()],Ys.prototype,"unsubscribe",1),v([$i(()=>"jitter")],Ys.prototype,"setJitterBufferDelay",1);var sf=Ys;function of(){return Q(s=>function(...i){return f(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(i=i.filter(t=>t.outMediaTrack&&t.state==="ready"),!i.length))return;E.emit("61",{room:this});let e=s.apply(this,i);return i.forEach(t=>t.publish(this,e)),e})})}function nf(){return Q(s=>function(...i){let e=s.apply(this,i);return i.forEach(t=>t.unpublish()),e})}var af=$e(Ye());function yE(){return Math.floor(Math.random()*16383)}var xc=class xc extends af.EventEmitter{constructor(e,t){super();this.room=e;this.signalChannel=t;d(this,"log");d(this,"cmdIdSeqMap",new Map);d(this,"messageMap",new Map);this.log=C.createLogger({id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),t.on(F.RECEIVE_CUSTOM_MSG,this.onReceiveMsg),this.room.on("peer-leave",r=>{[...this.messageMap.keys()].forEach(o=>{o.split("_").slice(0,-1).join("_")===r&&this.messageMap.delete(o)})})}send({cmdId:e,data:t}){let r=this.cmdIdSeqMap.get(e)||yE(),o={cmdId:e,msg:btoa(String.fromCharCode(...new Uint8Array(t))),ordered:!0,reliable:!0,streamSeq:r};this.cmdIdSeqMap.set(e,r+1),this.signalChannel.send(Y.SEND_CUSTOM_MSG,o),this.log.debug(`send custom msg: ${JSON.stringify(o)}`)}onReceiveMsg(e){let{data:t}=e.data,r=this.room.tinyIdToUserIdMap.get(t.srcTinyId);if(r){let o={userId:r,cmdId:t.cmdId,seq:t.streamSeq,data:Uint8Array.from(atob(t.msg),n=>n.charCodeAt(0)).buffer};if(t.ordered){let n=`${r}_${o.cmdId}`,a=this.messageMap.get(n);if(!a||a.lastSeq===0)a||(a={lastSeq:0,cachedMessageMap:new Map},this.messageMap.set(n,a),setTimeout(()=>this.emitMessage(o,!0),100)),a.cachedMessageMap.set(o.seq,{message:o});else if(Math.abs(a.lastSeq-o.seq)>xc.SEQ_INTERVAL)this.messageMap.set(n,{lastSeq:o.seq,cachedMessageMap:new Map}),this.emitMessage(o);else if(o.seq>a.lastSeq){if(o.seq===a.lastSeq+1)this.emitMessage(o);else if(!a.cachedMessageMap.has(o.seq)){let c=setTimeout(()=>this.emitMessage(o,!0),5e3);a.cachedMessageMap.set(o.seq,{message:o,timeoutId:c})}}else this.log.debug(`drop message ${o.userId}-${o.cmdId}-${o.seq}`)}else this.emit("message",o)}else{this.log.warn(`receive msg from unknown user, wait peer-join tinyId: ${t.srcTinyId}`);let o=n=>{n.tinyId===t.srcTinyId&&(this.room.off("peer-join",o),this.onReceiveMsg(e))};this.room.on("peer-join",o),Ni(2e3).then(()=>this.room.off("peer-join",o))}}emitMessage(e,t=!1){var a;let r=this.messageMap.get(`${e.userId}_${e.cmdId}`),o=e;if(r){if(t){let c=[...r.cachedMessageMap.values()].sort((l,u)=>l.message.seq-u.message.seq);c[0]&&(o=c[0].message)}r.lastSeq!==0&&o.seq-r.lastSeq>1&&this.log.debug(`msg lost userId: ${o.userId} seq: ${r.lastSeq} -> ${o.seq}`),r.lastSeq=o.seq,clearTimeout((a=r.cachedMessageMap.get(o.seq))==null?void 0:a.timeoutId),r.cachedMessageMap.delete(o.seq)}this.log.debug(`receive custom msg: ${JSON.stringify(o)}`),this.emit("message",o);let n=r==null?void 0:r.cachedMessageMap.get(o.seq+1);n&&this.emitMessage(n.message)}};d(xc,"SEQ_INTERVAL",300);var Pc=xc;var{isString:cf,isUndefined:gr,getNetworkType:bE,isEmpty:En}=dt,jt=class extends Mc{constructor(e){super(e);d(this,"_businessInfo");d(this,"userManager");d(this,"_version");d(this,"_heartbeat",-1);d(this,"_lastHeartBeatTime",-1);d(this,"_stats");d(this,"_joinTimeout",-1);d(this,"_firstPublishedList",null);d(this,"_joinReject",null);d(this,"_isRelayChanged",!1);d(this,"sdpSemantics");d(this,"signalChannel",null);d(this,"uplinkConnection",null);d(this,"singlePC",null);d(this,"enableSPC",bs);d(this,"_changeBigSmallRecords",new Map);d(this,"networkQuality");d(this,"_iceTransportPolicy");d(this,"forceRelay",!1);d(this,"_turnServers",[]);d(this,"_iceServersFromJoin");d(this,"_syncUserListInterval",-1);d(this,"_smallStreamConfig",{bitrate:100,frameRate:15,height:120,width:160});d(this,"enableSEI",!1);d(this,"_enableAudioVolumeEvaluation",!1);d(this,"_audioVolumeIntervalId",0);d(this,"_enableMultiAuxStream",!1);d(this,"_pureAudioPushMode",!1);d(this,"_customMessageManager");d(this,"preferHW",!1);d(this,"healthDetector");d(this,"playoutDelay");d(this,"jitterBufferDelay");d(this,"_updateAudioLevelTaskId",-1);this._stats=new pn(this,this._log),this.userManager=new tc(this.userId,this._log),this._version=Pe,this.sdpSemantics=is,gr(e.sdpSemantics)?ni.isUnifiedPlanDefault()&&(this.sdpSemantics=rr):this.sdpSemantics=e.sdpSemantics,this._log.info(`sdpSemantics: ${this.sdpSemantics}, netType: ${bE()}`),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=gr(e.enableMultiAuxStream)?!1:e.enableMultiAuxStream,this.enableSEI=e.enableSEI&&bs,!gr(e.enableSPC)&&bs&&(this.enableSPC=e.enableSPC),this.preferHW=!!e.preferHW,this._initBusinessInfo(e),this.healthDetector=new jp(this)}get isMainStreamPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.isMainStreamPublished)}get isMainAudioPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.localMainAudioTrack)}get isAuxStreamPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.isAuxStreamPublished)}get hasAuxStream(){return[...this.remotePublishedUserMap.values()].findIndex(e=>e.muteState.hasAuxiliary)>=0}get userMap(){return this.userManager.userMap}get remotePublishedUserMap(){return this.userManager.remotePublishedUserMap}get tinyIdToUserIdMap(){return new Map([...this.userMap.values()].map(e=>[e.tinyId,e.userId]))}join(e,t,r){return f(this,null,function*(){return this.userManager.mySelfId=this.userId,this.userManager.on("1",o=>{this.emit("peer-join",o)}),this.userManager.on("2",o=>{this.closeDownLinkConnection(o,"remote user exitRoom"),this.emit("peer-leave",o)}),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",n=>{var o=Xu(n,[]);E.emit(A.REMOTE_PUBLISH_STATE_CHANGED,N({room:this},o)),this.emit("remote-publish-state-changed",N({},o))}),this.joinParams=e,new Promise((o,n)=>f(this,null,function*(){var a,c;this._joinReject=n;try{this.checkDestroy();try{yield Promise.all([this.initialize(),this.initSinglePC()])}catch(u){if(u instanceof y&&u.code===I.SPC_INITIALIZED_FAILED)(a=this.signalChannel)==null||a.destroy(),yield this.initialize();else return n(u)}let l=w();yield this.doJoin(e,(c=this.singlePC)==null?void 0:c.clientAbility),b.addSuccessEvent({key:521708,cost:w()-l}),o(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(l){b.addFailedEvent({key:521708,error:l}),n(l)}this._joinReject=null}))})}initSinglePC(){return f(this,null,function*(){if(!(!this.enableSPC||this.singlePC)){this.singlePC=new qt({signalChannel:this.signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.on("sei-message",e=>this.emit("sei-message",e)),this.singlePC.on("dump",e=>this.emit("dump",e)),this.singlePC.once("error",()=>this.fallbackToMPC());try{return yield this.singlePC.initialize()}catch(e){throw this.fallbackToMPC(),new y({code:I.SPC_INITIALIZED_FAILED,message:e==null?void 0:e.message})}}})}doJoin(e,t){return new Promise((r,o)=>f(this,null,function*(){var c,l,u;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this.signalChannel.once(Ne.SETUP_FAILED,h=>{this.clearJoinTimeout(),E.emit(A.JOIN_SIGNAL_CONNECTION_END,{room:this,error:h}),o(h)}),me((l=(c=this.scheduleResult)==null?void 0:c.config)==null?void 0:l.singlePC)&&bs&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2),t&&this.playoutDelay&&(t.playoutDelay=this.playoutDelay);let n={roomId:String(e.roomId||e.strRoomId),useStringRoomId:this.useStringRoomId,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel,trtcRole:e.role,trtcScene:this.scene==="live"?2:1,sdpSemantics:this.sdpSemantics,version:this._version,ua:navigator&&navigator.userAgent||"",terminalType:Cd(),netType:Cr(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig,receiveMix:!0};this._log.debug(`join room signal data: ${JSON.stringify(n)}`);let a=5e3;(u=this.scheduleResult.config)!=null&&u.enterRoomTimeout&&this.scheduleResult.config.enterRoomTimeout>=1&&(a=this.scheduleResult.config.enterRoomTimeout*1e3),this._joinTimeout=window.setTimeout(()=>{o(new y({code:I.JOIN_ROOM_FAILED,message:x({key:P.JOIN_ROOM_TIMEOUT})}))},a),E.emit(A.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?Y.SPC_JOIN_ROOM:Y.JOIN_ROOM,n),this.signalChannel.once(F.JOIN_ROOM_RESULT,h=>f(this,null,function*(){this.clearJoinTimeout();let{code:m,message:g,data:D,tinyId:_}=h.data;E.emit(A.JOIN_RECEIVED_CMD_RES,{room:this,code:m}),m===0?(this._log.info("Join room success, start heartbeat"),_&&(this.tinyId=_),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=D.publishers,this._iceServersFromJoin=D.iceServer?[D.iceServer]:[],this.singlePC&&this.singlePC.setIceServers(this.getIceServers()).then(()=>{var S;(S=this.singlePC)==null||S.connect(L(N({},D.ability),{useVp8:D.ability.useVp8||!!e.useVp8})).catch(()=>{})}),r()):(this._log.error(`Join room failed result: ${m} error: ${g}`),o(new y({code:I.JOIN_ROOM_FAILED,extraCode:m,message:x({key:P.JOIN_ROOM_FAILED,data:{error:g,code:m}})})))}))}))}reJoin(){return f(this,null,function*(){if(!this.isJoined){this._log.warn("reJoin abort");return}try{this._log.warn(`reJoin pending: ${this.joinParams.roomId}`);let e,t=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,t.push(this.initSinglePC().then(r=>(e=r,r)))),this.signalChannel&&(this.signalChannel.close(),t.push(this.signalChannel.connect())),yield Promise.all(t),yield this.doJoin(L(N({},this.joinParams),{role:this.role==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),e),this._log.warn("reJoin success"),re.logSuccessEvent({userId:this.userId,eventType:st.REJOIN}),this.singlePC){let r=o=>{var n;o.state==="CONNECTED"&&((n=this.singlePC)==null||n.off(Ti.CONNECTION_STATE_CHANGED,r),this.uplinkConnection instanceof Wu&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach(a=>{a.installEvents(),a.onSinglePCReconnected()}))};this.singlePC.on(Ti.CONNECTION_STATE_CHANGED,r),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof mn&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(e){this._log.warn(`reJoin fail ${e}`),this.reset(),re.logFailedEvent({userId:this.userId,eventType:st.REJOIN,error:e}),this.emit("error",new y({code:I.JOIN_ROOM_FAILED,message:x({key:P.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}})}initialize(){return f(this,null,function*(){let{mainUrl:e,backupUrl:t}=this.getSignalChannelUrl(),r=this.signalChannel||Sp(this.userId),o=!!(r&&r.isConnected&&r.keepAlive&&r.userId===this.userId),n;return Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(n=this.scheduleResult.domains[0]),this._log.info(`${o?"reuse":"setup"} signal channel`),o?(r.url=e,r.backupUrl=t,r.room=this,this.signalChannel=r):(r&&r.close(),this.signalChannel=new qs({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:e,backupUrl:t,room:this,signalDomainWhenUnifiedProxy:this.proxy_unified?n:void 0}),this._customMessageManager=new Pc(this,this.signalChannel),this._customMessageManager.on("message",a=>{this.emit("custom-message",a)})),this.networkQuality||(this.networkQuality=new Qs({signalChannel:this.signalChannel,room:this}),this.networkQuality.on(Qs.EVENT_NETWORK_QUALITY,a=>{var c;this.emit("network-quality",a),(c=this.singlePC)==null||c.detectTCPAndUDP(a)})),qe(this,this.signalChannel).add(Ne.CONNECTION_STATE_CHANGED,a=>{E.emit(A.SIGNAL_CONNECTION_STATE_CHANGED,N({room:this},a)),this.emit("signal-connection-state-changed",a)}).add(Ne.RECONNECT_FAILED,a=>{this.reset(),this.emit("error",a)}).add(F.PEER_JOIN,a=>{let{srcTinyId:c,userId:l,role:u}=a.data.data;this.userManager.addUser({userId:l,tinyId:c,role:u})}).add(F.PEER_LEAVE,a=>{let{userId:c,reason:l=0}=a.data.data;this.userManager.deleteUser(c,l)}).add(F.UPDATE_REMOTE_MUTE_STAT,a=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=10*1e3&&this.doHeartbeat(),this.onPublishedUserList(a.data)}).add(F.CLIENT_BANNED,a=>{let c=a.data.data,{reason:l}=c;if(re.uploadEvent({log:`stat-banned:${l}`,userId:this.userId}),l==="user_time_out"){this._log.warn(`${l} last heart beat time: ${this._lastHeartBeatTime} interval: ${Date.now()-this._lastHeartBeatTime}, visibility: ${document.visibilityState}`),this.reJoin();return}this._log[l==="kick"?"error":"info"](`user was banned because of [${l}]`),this.reset(),this.emit("banned",{reason:l})}).add(F.SEND_SWITCH_ROOM_SUBED_REQ,a=>{if(!this.singlePC)return;let{subList:c}=a.data.data;c.forEach(l=>{this.singlePC.autoSubscribedUserMap.set(l.userId,l)})}),this.signalChannel.once(Ne.SETUP_SUCCESS,a=>{this.tinyId=a.signalInfo.tinyId,E.emit(A.JOIN_SIGNAL_CONNECTION_END,{room:this})}),E.emit(A.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),o&&E.emit(A.JOIN_SIGNAL_CONNECTION_END,{room:this}),o})}setSignalChannel(e){this.signalChannel=e,e||ve(this)}leave(){return f(this,null,function*(){var e;try{yield this.doHeartbeat()}catch(t){}this._log.info("leave() => leaving room"),E.emit(A.LEAVE_SEND_CMD,{room:this}),(e=this.signalChannel)==null||e.send(Y.LEAVE_ROOM)})}clearNetworkQuality(){this.networkQuality&&(this.networkQuality.stop(),delete this.networkQuality)}closeConnections(){this.remotePublishedUserMap.forEach(e=>{this.closeDownLinkConnection(e.userId,"you exitRoom")})}clearJoinTimeout(){clearTimeout(this._joinTimeout),this._joinTimeout=-1}startHeartbeat(){this._heartbeat===-1&&(this._heartbeat=oe.run("ric",this.doHeartbeat.bind(this),{delay:2e3}))}stopHeartbeat(){this._heartbeat!==-1&&(this._log.info("stopHeartbeat"),oe.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return f(this,null,function*(){var n;let e=this.badCaseDetector.getMonitorFreeze(),t=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:e});this.badCaseDetector.resetMonitor();let r=(n=this.signalChannel)!=null&&n.isConnected?wm(this.userId):[],o=L(N({str_sdk_version:to,uint64_datetime:new Date().getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_event_msg:r,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},t),{msg_device_info:N({uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:Cr()},t.msg_device_info)});if(this.heartbeatReport=o,E.emit(A.HEARTBEAT_REPORT,{room:this,report:o}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(Y.ON_QUALITY_REPORT,o);let a=Date.now();this._lastHeartBeatTime>0&&a-this._lastHeartBeatTime>1e4&&this._log.warn(`heartbeat took ${a-this._lastHeartBeatTime}`),this._lastHeartBeatTime=a,this.signalChannel.isOnline||(this._log.warn("signal channel is not online"),this.signalChannel.startReconnection())}this.emit("heartbeat-report",L(N({},o),{bytes_sent:this._stats.totalBytesSent+this.signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this.signalChannel.bytesReceived}))}!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)})}onPublishedUserList(e){if(!this.isJoined)return;let t=e.data.userList.filter(r=>r.flag!==Jc).map(({userId:r,srcTinyId:o,flag:n})=>{r===this.userId&&this.uplinkConnection&&(this.uplinkConnection.flag=n);let a=this.remotePublishedUserMap.get(r);return a&&this.checkSubscribeBigSmallVideo(a),{userId:r,tinyId:o,flag:n}});e.data.mixRobotList.forEach(({userId:r,srcTinyId:o,flag:n,mixUserList:a})=>{t.unshift({userId:r,tinyId:o,flag:n,isRobot:!0,mixUserList:a})}),E.emit(A.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:t}),this.userManager.setRemotePublishedUserList(t)}closeUplink(e="you unpublished"){this.uplinkConnection&&(this.localTracks.size>0&&this.uplinkConnection.doUnpublish(),this.uplinkConnection.close(e),this.uplinkConnection instanceof mn&&(this.uplinkConnection=null)),this.localTracks.forEach(t=>t.unpublish()),this.localTracks.clear()}createDownlinkConnection({userId:e,tinyId:t,flag:r,isRobot:o}){let n=new(this.singlePC?sf:ku)({userId:e,tinyId:t,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:r,isRobot:o});this.userManager.addRemotePublishedUser(n),this.installDownlinkEvents(n,e),this.emit("remote-published",n)}closeDownLinkConnection(e,t="remote user unpublished"){let r=this.remotePublishedUserMap.get(e);r&&(r.close(t),this.emit("remote-unpublished",r))}installDownlinkEvents(e,t){e.on("error",r=>{let o=r.getCode();o!==I.ICE_TRANSPORT_ERROR&&(o===I.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",r))}),e.on("connection-state-changed",r=>{this.emit("media-connection-state-changed",L(N({},r),{userId:e.userId}))}),e.on("firewall-restriction",()=>{this.emit("firewall-restriction")})}startSyncUserListInterval(){this._syncUserListInterval===-1&&(this._syncUserListInterval=oe.run("ric",this.syncUserList.bind(this)))}stopSyncUserListInterval(){oe.clearTask(this._syncUserListInterval),this._syncUserListInterval=-1}syncUserList(){return this.getUserList().then(e=>{this.userManager.setUserList(e)}).catch(e=>{this._log.debug(`sync user list failed: ${e}`)})}getUserList(){var e;return(e=this.signalChannel)!=null&&e.isConnected?this.signalChannel.sendWaitForResponse({command:Y.GET_USER_LIST,responseCommand:F.USER_LIST_RES,enableLog:!1,timeout:2e3}).then(({data:t})=>{let{code:r,message:o}=t;if(r===0)return(t.data&&t.data.userList||[]).map(({userId:a,srcTinyId:c,role:l})=>({userId:a,tinyId:c,role:l}));throw x({key:P.SIGNAL_RESPONSE_FAILED,data:{signalResponse:F.USER_LIST_RES,code:r,message:o}})}):Promise.reject("not connected")}getAllConnections(){let e=[...this.remotePublishedUserMap.values()];return this.uplinkConnection&&e.push(this.uplinkConnection),e}isRelayMaybeFailed(){if(this.signalChannel&&!this.signalChannel.isOnline||!bu)return!1;if(this.singlePC)return this.singlePC.reconnectionCount>6;let e=this.getAllConnections();if(e.length===0)return!1;for(let t=0;t<e.length;t++)if(e[t].getReconnectionCount()<6)return!1;return!0}checkConnectionsToReconnect(){var e;this.singlePC?((e=this.singlePC.getPeerConnection())==null?void 0:e.connectionState)===ge.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach(r=>{if(r instanceof rt&&!r.getIsReconnecting()){let o=r.getPeerConnection();o&&o.connectionState===ge.CLOSED&&(this._log.warn(`[${r.getUserId()}] pc is closed but not reconnect`),r.startReconnection())}})}fallbackToMPC(){return f(this,null,function*(){var e;if(this._log.warn("fallback to multi pc"),re.uploadEvent({log:"stat-fallback",userId:this.userId}),this.enableSPC=!1,(e=this.singlePC)==null||e.close(),this.singlePC=null,this.isJoined&&(yield this.reJoin()),this.uplinkConnection){let t=this.uplinkConnection;this.uplinkConnection=new mn({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),t.isMainStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:t.localMainAudioTrack,localVideoTrack:t.localMainVideoTrack,isAuxiliary:!1})),t.isAuxStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:t.localAuxAudioTrack,localVideoTrack:t.localAuxVideoTrack,isAuxiliary:!0})),t.close()}for(let t of[...this.remotePublishedUserMap.values()]){let r=new ku({userId:t.userId,tinyId:t.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:t.flag,remoteAudioTrack:t.remoteAudioTrack,remoteVideoTrack:t.remoteVideoTrack,remoteAuxiliaryTrack:t.remoteAuxiliaryTrack});this.installDownlinkEvents(r,t.userId),this.remotePublishedUserMap.set(t.userId,r),t.isMainStreamSubscribed&&(yield r.subscribe(t.subscribeState,"main")),t.isAuxStreamSubscribed&&(yield r.subscribe(t.subscribeState,"auxiliary"))}})}destroy(){this.isDestroyed||(this.signalChannel&&(this._log.info("destroying SignalChannel"),this.signalChannel.close(),this.signalChannel=null),super.destroy(),this._joinReject&&(this._joinReject(new y({code:I.INVALID_OPERATION,message:x({key:P.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners(),this.healthDetector.destroy(),oe.clearTask(this._audioVolumeIntervalId))}switchRole(e){return f(this,null,function*(){this.role!==e&&(e==="audience"&&this.uplinkConnection&&this.closeUplink("you switch role to audience"),yield this.doSwitchRole(e))})}doSwitchRole(e){let t={command:Y.SWITCH_ROLE,data:{role:e==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:F.SWITCH_ROLE_RES,retries:1};return this._log.info(`switchRole signal data: ${JSON.stringify(t.data)}`),this.signalChannel.sendWaitForResponseWithRetry(t).then(r=>{let{code:o,message:n}=r.data;if(o!==0)throw new y({code:I.SWITCH_ROLE_FAILED,message:x({key:P.SWITCH_ROLE_FAILED,data:{message:n,code:o}})});this.role=e}).catch(r=>{throw r instanceof y&&r.getCode()===I.API_CALL_TIMEOUT&&(r=new y({code:I.SWITCH_ROLE_FAILED,message:x({key:P.SWITCH_ROLE_TIMEOUT})})),this._log.error(r),r})}publish(...e){return f(this,null,function*(){let t={},r={};e.forEach(c=>{c instanceof Tt&&(c instanceof hi?r.audio=c:t.audio=c),c instanceof je&&(c instanceof ct&&c.mediaType===2?r.video=c:t.video=c)});let o=En(t),n=En(r);(!o||!n)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new Wu({userId:this.userId,tinyId:this.tinyId,room:this}):this.uplinkConnection=new mn({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),this.uplinkConnection.on("connection-state-changed",c=>{this.emit("media-connection-state-changed",L(N({},c),{userId:this.userId}))}),this.uplinkConnection.on("firewall-restriction",()=>{this.emit("firewall-restriction")}),this.uplinkConnection.on("error",c=>{let l=c.getCode();l!==I.ICE_TRANSPORT_ERROR&&(l===I.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",c))}));let a=e.map(c=>c.kind).join(",");o||(this._log.info(`publish() => main ${a}`),yield this.uplinkConnection.publish({localAudioTrack:t.audio,localVideoTrack:t.video,isAuxiliary:!1}),this._log.info("main is published")),n||(this._log.info(`publish() => aux ${a}`),yield this.uplinkConnection.publish({localAudioTrack:r.audio,localVideoTrack:r.video,isAuxiliary:!0}),this._log.info("aux is published"))})}unpublish(...e){return f(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||!this.isMainStreamPublished&&!this.isAuxStreamPublished||!this.uplinkConnection)return;let t={},r={};e.forEach(o=>{!o.mediaTrack||!o.isPublished||(o instanceof Tt&&(o instanceof hi?r.audio=o:t.audio=o),o instanceof je&&(o instanceof ct&&o.mediaType===2?r.video=o:t.video=o))});try{let o=e.map(n=>n.kind).join(",");En(t)||(this._log.info(`unpublish() => main ${o}`),yield this.uplinkConnection.unpublish({localAudioTrack:t.audio,localVideoTrack:t.video})),En(r)||(this._log.info(`unpublish() => aux ${o}`),yield this.uplinkConnection.unpublish({localAudioTrack:r.audio,localVideoTrack:r.video}))}catch(o){}this.localTracks.size===0&&this.closeUplink("you unpublished")})}addTrack(e){if(!this.uplinkConnection||!e.mediaTrack)return Promise.resolve();let t=this.uplinkConnection.addTrack(e);return e.publish(this,t),t}removeTrack(e){return!this.uplinkConnection||!e.mediaTrack?Promise.resolve():this.uplinkConnection.removeTrack(e).then(t=>(e.unpublish(),t))}replaceTrack(e){return!this.uplinkConnection||!e.mediaTrack||!qd()?Promise.resolve():this.uplinkConnection.replaceTrack(e).then(t=>{t&&E.emit(A.LOCAL_TRACK_REPLACED,{track:e})})}setBandWidth(e){return f(this,null,function*(){this.uplinkConnection&&(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())})}enableSmall(e){return f(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:p.VIDEO,videoType:p.SMALL,bandwidth:this.uplinkConnection.localMainVideoTrack.small.bitrate})),yield this.uplinkConnection.enableSmall(e)})}subscribe(...e){return f(this,null,function*(){if(e=e.filter(n=>!n.isSubscribed),e.length===0)return;let{userId:t}=e[0],r=this.remotePublishedUserMap.get(t);if(!r)return;let o=e.find(n=>n.mediaType===2)?"auxiliary":"main";try{let n=N({},r.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:n.audio=!0;break;case 4:n.video=!0;break;case 8:n.smallVideo=!0;break;case 2:n.auxiliary=!0;break}});let a=this._changeBigSmallRecords.get(t);a&&a.options.smallVideo&&r.muteState.hasSmall&&n.video&&(n.video=!1,n.smallVideo=!0),E.emit(A.SUBSCRIBE_START,{room:this,streamType:o,remotePublishedUser:r,subscribeState:n}),this._log.info(`subscribe() => ${t} ${o} [${Rc(n)}] prev: [${Rc(r.subscribeState)}]`),yield r.subscribe(n,o),this._log.info(`subscribe ${t} ${o} done`);for(let c of e)c.mediaTrack||(yield c.waitHasMediaTrack());E.emit(A.SUBSCRIBE_SUCCESS,{room:this,streamType:o,remotePublishedUser:r})}catch(n){let a=n instanceof y?n.getCode():I.UNKNOWN,c=n;throw n instanceof y?a===I.REMOTE_STREAM_NOT_EXIST&&(c=new y({code:I.API_CALL_ABORTED,message:x({key:P.API_CALL_ABORTED,data:{message:n.message,userId:t,streamType:o}})}),this._log.warn(c)):(c=new y({code:a,message:x({key:P.SUBSCRIBE_FAILED,data:{message:n.message,userId:t,streamType:o}})}),this._log.error(c)),c}})}unsubscribe(...e){return f(this,null,function*(){let{userId:t}=e[0],r=this.remotePublishedUserMap.get(t);if(!r)return;let o=e.find(n=>n.mediaType===2)?"auxiliary":"main";this._log.info(`unsubscribe() => ${t} ${o}`);try{yield r.unsubscribe({remoteTracks:e,streamType:o})}catch(n){this._log.warn(`unsubscribe() => failed ${n}`)}e.forEach(n=>{n.unsubscribe(),n.mediaType===8&&n.setMediaType(4)}),E.emit(A.UNSUBSCRIBE_SUCCESS,{room:this,streamType:o,remotePublishedUser:r})})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAudioVolumeEvaluation(e=2e3,t){if(e<=0){this._enableAudioVolumeEvaluation=!1,oe.clearTask(this._audioVolumeIntervalId);return}e=Math.floor(Math.max(e,100)),E.emit(A.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&oe.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=oe.run("intervalInWorker",()=>{var o;Ur.isRunning?this.stopUpdateAudioLevelFromSenderStat():this.updateAudioLevelFromSenderStat(e,t);let r=[];(o=this.remotePublishedUserMap)==null||o.forEach(n=>{if(n.muteState.hasAudio){!Ur.isRunning&&n.muteState.audioAvailable&&n.remoteAudioTrack.isSubscribed?this.updateDownlinkAudioLevelFromReceiver(n):n.remoteAudioTrack.volume=0;let a=Math.floor(n.remoteAudioTrack.getAudioLevel()*100);r.push({userId:n.userId,volume:a})}}),this.emit("audio-volume",r)},{delay:e,backgroundTask:t})}updateAudioLevelFromSenderStat(e,t){return f(this,null,function*(){var n;if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack||this._updateAudioLevelTaskId!==-1)return;let r=(n=this.uplinkConnection.getPeerConnection())==null?void 0:n.getSenders()[0];if(!r)return;let o=Math.max(e,500);this._log.warn(`updateAudioLevelFromSenderStat ${o}`),this._updateAudioLevelTaskId=oe.run("intervalInWorker",()=>f(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack){this.stopUpdateAudioLevelFromSenderStat();return}let a=yield r.getStats();if(this._updateAudioLevelTaskId<0)return;let{localMainAudioTrack:c}=this.uplinkConnection;a.forEach(l=>{l.type==="media-source"&&l.audioLevel&&(c.volume=l.audioLevel)})}),{delay:o,backgroundTask:t})})}stopUpdateAudioLevelFromSenderStat(){var e;this._updateAudioLevelTaskId!==-1&&(this._log.warn("stopUpdateAudioLevelFromSenderStat"),oe.clearTask(this._updateAudioLevelTaskId),this._updateAudioLevelTaskId=-1,(e=this.uplinkConnection)!=null&&e.localMainAudioTrack&&(this.uplinkConnection.localMainAudioTrack.volume=0))}updateDownlinkAudioLevelFromReceiver(e){var o;let{audioReceiver:t}=e;if(!jd||!t)return;let r=(o=t.getSynchronizationSources()[0])==null?void 0:o.audioLevel;q(r)?e.remoteAudioTrack.volume=Math.min(r*2,1):t.getStats().then(n=>{n.forEach(a=>{a.type==="inbound-rtp"&&q(a.audioLevel)&&(e.remoteAudioTrack.volume=a.audioLevel)})})}getLocalAudioStats(){return f(this,null,function*(){var t;let e={};return e[this.userId]={bytesSent:0,packetsSent:0,audioLevel:0},(t=this.uplinkConnection)!=null&&t.localMainAudioTrack&&(e[this.userId]=this.uplinkConnection.localMainAudioTrack.stat),e})}getLocalVideoStats(){return f(this,null,function*(){var t,r;let e={};return e[this.userId]=((r=(t=this.uplinkConnection)==null?void 0:t.localMainVideoTrack)==null?void 0:r.stat)||{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0},e})}getTransportStats(){return f(this,null,function*(){let e={rtt:0,downlinksRTT:{}};if(this.uplinkConnection){let t=yield this._stats.getSenderStats(this.uplinkConnection);e.rtt=t.rtt}for(let[,t]of this.remotePublishedUserMap){let r=yield this._stats.getReceiverStats(t);e.downlinksRTT[r.userId]=r.rtt}return e})}getRemoteVideoStats(e){return f(this,null,function*(){let t={};for(let[r,o]of this.remotePublishedUserMap)e==="main"&&o.muteState.hasVideo&&(t[r]=o.remoteVideoTrack.stat),e==="auxiliary"&&o.muteState.hasAuxiliary&&(t[r]=o.remoteAuxiliaryTrack.stat);return t})}getRemoteAudioStats(){return f(this,null,function*(){let e={};for(let[t,r]of this.remotePublishedUserMap)r.muteState.hasAudio&&(e[t]=r.remoteAudioTrack.stat);return e})}setTurnServer(e,t){this._log.info(`set turn server: ${JSON.stringify(e)} ${t||""}`);let r=[];Array.isArray(e)?e.forEach(o=>r.push(dt.getTurnServer(o))):dt.isPlainObject(e)&&r.push(dt.getTurnServer(e)),this._turnServers=r,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:Y.START_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:F.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:Y.STOP_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:F.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"})}sendStartPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?Y.START_PUBLISH_TENCENT_CDN:Y.START_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?F.START_PUBLISH_TENCENT_CDN_RES:F.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"})}sendStopPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?Y.STOP_PUBLISH_TENCENT_CDN:Y.STOP_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?F.STOP_PUBLISH_TENCENT_CDN_RES:F.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}sendStartPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Y.START_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:F.START_PUBLISH_CDN_STREAM_RES,commandDesc:"startPublishCDNStream"})}sendUpdatePushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Y.UPDATE_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:F.UPDATE_PUBLISH_CDN_STREAM_RES,commandDesc:"updatePublishCDNStream"})}sendStopPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Y.STOP_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:F.STOP_PUBLISH_CDN_STREAM_RES,commandDesc:"stopPublishCDNStream"})}sendAbilityStatus(e){var t;(t=this.signalChannel)==null||t.sendWaitForResponse({command:Y.ABILITY_STATUS_REPORT,data:e,timeout:5e3,responseCommand:F.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch(r=>{})}getIceServers(e){var t,r;return this._turnServers.length>0?this._turnServers:(t=this.scheduleResult.iceServers)!=null&&t.length?this.scheduleResult.iceServers:e!=null&&e.length?e:(r=this._iceServersFromJoin)!=null&&r.length?this._iceServersFromJoin:[]}getIceTransportPolicy(){return this.forceRelay?"relay":this._iceTransportPolicy||this.scheduleResult.iceTransportPolicy||"all"}getLogger(){return this._log}enableAIVoice(){throw new Error("Method not implemented.")}getSignalChannelUrl(){let e={mainUrl:"",backupUrl:""},t=dt.getEnv();return t?(e.mainUrl=`wss://${t}.rtc.qq.com`,e.backupUrl=e.mainUrl):this.proxy_ws?(e.mainUrl=this.proxy_ws,e.backupUrl=e.mainUrl):this.proxy_unified?(e.mainUrl=`wss://${this.proxy_unified}`,e.backupUrl=e.mainUrl):Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(e.mainUrl=`wss://${this.scheduleResult.domains[0]}`,e.backupUrl=e.mainUrl,this.scheduleResult.domains[1]&&(e.backupUrl=`wss://${this.scheduleResult.domains[1]}`)),e}getSignalInfo(){var e;return((e=this.signalChannel)==null?void 0:e.getSignalInfo())||{clientIp:"",relayIp:""}}reset(e=!1){this.stopSyncUserListInterval(),this.stopHeartbeat(),this.closeConnections(),this.clearNetworkQuality(),this.closeUplink("you exitRoom"),this.signalChannel&&(e&&this.signalChannel.keepAlive&&this.signalChannel.isConnected?this.signalChannel.stopKeepAliveIn(3600):(this.signalChannel.close(),this.setSignalChannel(null))),this._stats.reset(),this.userManager.clear(),this.userManager.removeAllListeners(),this.singlePC&&(this.singlePC.close(),this.singlePC=null),this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}}checkSubscribeBigSmallVideo(e){return f(this,null,function*(){let{subscribeState:t,userId:r,muteState:{hasSmall:o,hasVideo:n}}=e;if(!o&&!n||!t.video&&!t.smallVideo)return;let a=this._changeBigSmallRecords.get(r);if(!a||a.isSubscribing||a.reSubscribeCount<=0)return;let{options:c,reSubscribeCount:l}=a;if(c.video&&t.video||c.smallVideo&&t.smallVideo&&o)return;let u={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:c.video,smallVideo:c.smallVideo};try{if(!o&&u.smallVideo&&(u.video=!0,u.smallVideo=!1),u.smallVideo===t.smallVideo&&u.video===t.video)return;a.isSubscribing=!0,a.reSubscribeCount=l-1,yield e.subscribe(u,"main"),e.remoteVideoTrack.setMediaType(u.smallVideo?8:4),this._log.info(`change [${r}] to ${u.smallVideo?"small":"big"} video successfully. count ${rs-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount=rs}catch(h){this._log.info(`change [${r}] to ${u.smallVideo?"small":"big"} video failed. count ${rs-a.reSubscribeCount}. reason: ${h}`),a.isSubscribing=!1,a.reSubscribeCount===0&&this._changeBigSmallRecords.delete(r)}})}changeType(e,t){let o={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:rs};this._changeBigSmallRecords.set(t.userId,o),this._log.info(`set [${t.userId}] video prefer type: ${e?"small":"big"}`),this.emit("subscribe-small-video-changed",{userId:t.userId,isSmall:e});let n=this.remotePublishedUserMap.get(t.userId);n&&this.checkSubscribeBigSmallVideo(n)}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(e){this._businessInfo=e.businessInfo;let t={};if(cf(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!gr(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PURE_AUDIO})});this._pureAudioPushMode=e.pureAudioPushMode,t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.pure_audio_push_mod=this._pureAudioPushMode}if(!gr(e.userDefineRecordId)){let r=/^[A-Za-z0-9_-]{1,64}$/gi;if(e.userDefineRecordId.match(r)===null)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!gr(e.userDefinePushArgs))if(cf(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256)t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_push_args=e.userDefinePushArgs;else throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_USER_DEFINE_PUSH_ARGS})});En(t)||(this._businessInfo=JSON.stringify(t))}sendCustomMessage(e){var t;(t=this._customMessageManager)==null||t.send(e)}enableInsertableStreams(){return f(this,null,function*(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&Ui)return this.singlePC.enableInsertableStreams=!0,yield this.singlePC.waitForPeerConnectionConnected(),yield this.singlePC.startReconnection()})}sendSignalMessage(e){var t;return this.signalChannel?(t=this.signalChannel)==null?void 0:t.sendWaitForResponseWithRetry(e):Promise.reject(new y({code:I.INVALID_OPERATION,message:"not join"}))}get enableCodecPipeline(){return this.videoManager.encodePipeline.length>0||this.videoManager.decodePipeline.length>0||this.audioManager.encodePipeline.length>0||this.audioManager.decodePipeline.length>0}get scriptTransformWorker(){var e;return(e=this.singlePC)==null?void 0:e.scriptTransformWorker}switchRoom(e){return f(this,null,function*(){var D,_;if(!this.signalChannel)return;let{roomId:t,strRoomId:r,userSig:o,privateMapKey:n}=e,a=((D=this.scheduleResult.config)==null?void 0:D.autoSubscribeCount)||(e==null?void 0:e.autoSubscribeCount)||1,c=String(this.useStringRoomId?r:t),l=[];for(let S=0;S<a;S++)l.push({audioSsrc:Et(),bigVideoSsrc:Et(),bigVideoRtxSsrc:Et(),auxVideoSsrc:Et(),auxVideoRtxSsrc:Et()});let u={currRoomId:this.roomId,targetRoomId:c,useStringRoomId:this.useStringRoomId,ability:(_=this.singlePC)==null?void 0:_.clientAbility,userSig:o!=null?o:this.userSig,privateMapKey:n!=null?n:this.privateMapKey,subscribe:l};this.singlePC&&(this.singlePC.autoSubscribedSsrcGroups=l,this.singlePC.autoSubscribedUserMap.clear()),E.emit(A.SWITCH_ROOM_START,{room:this});let h=yield this.signalChannel.sendWaitForResponse({command:Y.SWITCH_ROOM,responseCommand:F.SEND_SWITCH_ROOM_RES,data:u}),{code:m,message:g}=h.data;if(m===0){let S=this.roomId;this.roomId=this.useStringRoomId?r:String(t),gr(o)||(this.userSig=o),gr(n)||(this.privateMapKey=n),E.emit(A.SWITCH_ROOM_SUCCESS,{room:this,currentRoomId:S,targetRoomId:c})}else{this._log.error(`switch room failed. result: ${m} error: ${g}`),this.singlePC&&(this.singlePC.autoSubscribedSsrcGroups=[]);let S=new y({code:I.SWITCH_ROOM_FAILED,extraCode:m,message:g});throw E.emit(A.SWITCH_ROOM_FAILED,{room:this,error:S}),S}})}isSwitchRoomSupported(){var t;let e="unable to use switchRoom API, fallback to exitRoom and enterRoom.";return((t=this.scheduleResult.config)==null?void 0:t.switchRoom)!==!0?(this._log.warn(`${e} Reason: this sdkAppId is not supported, please contact us [https://trtc.io/contact] to enable it.`),!1):this.scene!=="live"?(this._log.warn(`${e} Reason: the scene is not 'live'.`),!1):this.role!=="audience"?(this._log.warn(`${e} Reason: the role is not 'audience'.`),!1):this.singlePC?!0:(this._log.warn(`${e} Reason: is not using single peerConnection.`),!1)}};v([Te(["left",H.INIT],"joined"),pt({settings:{retries:1,timeout:0},onRetrying(e){this._log.warn(`join retry ${e}`)},onRetryFailed(e){this._log.error("join failed",e)},onError(e,t){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),Wt(!0),this.reset(),t()):this.signalChannel&&this.signalChannel.isConnected&&this.signalChannel.keepAlive?(this._log.warn("is using keepAlive ws, retry join"),this.signalChannel.close(),this.reset(),t()):(this.reset(),t())}}),fp()],jt.prototype,"join",1),v([Te("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),_p(),xa("leave room"),Ho({fnName:"publish",validateArgs:!1}),Ho({fnName:"unsubscribe",validateArgs:!1})],jt.prototype,"leave",1),v([Rt(),of(),pt({settings:{retries:Ai,timeout:e=>Pt(e)},onError(e,t,r){var o;(o=e.message)!=null&&o.includes("timeout")?(this._log.warn("publish timeout"),t()):(this._log.error(`publish failed: ${e}`),r(e),E.emit(A.PUBLISH_FAILED,{room:this}))}})],jt.prototype,"publish",1),v([Ho({fnName:"publish"}),Rm("api-call"),Rt(),nf(),et(function(){var e,t;this.localTracks.size===0&&dr()&&((t=(e=this.singlePC)==null?void 0:e.getPeerConnection())==null||t.getSenders().forEach(r=>r.track&&r.replaceTrack(null)))})],jt.prototype,"unpublish",1),v([Ma(e=>{if(e.code!==I.API_CALL_ABORTED)throw e}),$i(e=>e.userId)],jt.prototype,"replaceTrack",1),v([$i((...e)=>e[0].userId),Va(),gp(),pt({settings:{retries:Ai,timeout:e=>Pt(e)},onError(e,t,r,o){e.message.includes("timeout")?(this._log.warn("subscribe timeout"),t()):(this._log.error(`subscribe failed: ${e}`),r(e),E.emit(A.SUBSCRIBE_FAILED,{room:this,remoteTracks:o}))}})],jt.prototype,"subscribe",1),v([Ho({fnName:"subscribe",callback(...e){this.singlePC||e.forEach(t=>{let r=this.remotePublishedUserMap.get(t.userId);r&&!r.isMainStreamSubscribed&&!r.isAuxStreamSubscribed&&r.close("you unsubscribed")})}}),$i((...e)=>e[0].userId)],jt.prototype,"unsubscribe",1);un.create=un._create.bind(un,jt);var cH=un;export{cH as default};