trtc-sdk-v5 5.8.1 → 5.8.2-beta.1

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
@@ -40,7 +40,7 @@ let sum=0;let rms;for(let i=0;i<firstChannel.length;++i){sum+=firstChannel[i]*fi
40
40
  rms=Math.sqrt(sum/firstChannel.length);this.volume=Math.max(rms,this.volume*0.95);this.tick-=firstChannel.length;if(this.tick<0){this.tick+=(this.intervalTime/1000)*sampleRate;this.port.postMessage({volume:this.volume,cacheLen:cl,outputLen:l});}
41
41
  return true;}}
42
42
  registerProcessor("volume-meter",VolumeMeter);
43
- `,Ji=class{constructor(i){u(this,"_volume",0);u(this,"_log");u(this,"_scriptProcessorNode",null);u(this,"_audioWorkletNode",null);u(this,"_interval",200);u(this,"ready",this.preload());let{log:e}=i;this._log=e,g.on(E.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){return Ji.workletReady||(Ji.workletReady=Gi(Ji.audioContext,URL.createObjectURL(new Blob([Mp],{type:"application/javascript"})))),Ji.workletReady.then(()=>this.initAudioWorklet()).catch(()=>this.initScriptProcessor())}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(Ji.audioContext,"volume-meter");let i=!1;this._audioWorkletNode.port.onmessage=e=>{this._volume=e.data.volume||0,!i&&e.data.cacheLen&&e.data.outputLen&&(this._log.warn("worklet play success"),i=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(i){Z.logFailedEvent({userId:this._log.userId,eventType:Ve.LOAD_WORKLET,error:i}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=qe("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=i=>{let e=i.inputBuffer.getChannelData(0),t=0;for(let s=0;s<e.length;++s)t+=e[s]*e[s];this._volume=Math.sqrt(t/e.length)||0}}catch(i){this._log.error(`volumeMeter init script processor error: ${i}`)}}destroy(){this._scriptProcessorNode&&(this._scriptProcessorNode.onaudioprocess=null),this._audioWorkletNode&&(this._audioWorkletNode.port.postMessage({name:"stop"}),this._audioWorkletNode.port.onmessage=null),this._audioWorkletNode=null,this._scriptProcessorNode=null,g.off(E.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}handleAudioLevelInterval(i){var t;let{interval:e}=i;this._interval=e,(t=this._audioWorkletNode)==null||t.port.postMessage({name:"setIntervalTime",intervalTime:e})}},Ws=Ji;u(Ws,"audioContext",qe("volume-meter")),u(Ws,"workletReady");var fn=class extends Et{constructor(e){super();u(this,"_volumeMeter");this._volumeMeter=new Ws(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return _(this,null,function*(){yield this._volumeMeter.preload(),this.setNode(this._volumeMeter.node)})}getCalculatedVolume(){return this._volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this._volumeMeter.getInternalAudioLevel()}write(e){if(this.node){let t=e.allocationSize({planeIndex:0}),s=new Float32Array(t>>2);e.copyTo(s,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:s},[s.buffer]),e.close()}}};var el=Se(Ne(),1);var Ku=r=>i=>i.deviceId===r;var Js=class{constructor(i,e="Input"){u(this,"kind");u(this,"type");u(this,"devices",[]);this.kind=i,this.type=e}update(i,e){let t=i.filter(s=>s.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);if(this.devices.length===1&&Lr(this.devices[0])){this.devices=t;return}e&&(t.forEach(s=>{if(s.deviceId&&!this.devices.find(Ku(s.deviceId))){let o=`${this.kind}${this.type}Added`;I.warn(`${o}: ${JSON.stringify(s)}`),e.emit(o,s)}}),this.devices.forEach(s=>{if(s.deviceId&&!t.find(Ku(s.deviceId))){let o=`${this.kind}${this.type}Removed`;I.warn(`${o}: ${JSON.stringify(s)}`),e.emit(o,s)}})),this.devices=t}hasDevice(i){return!!this.devices.find(e=>e.deviceId===i)}},_c=class extends el.EventEmitter{constructor(){super();u(this,"audioInputs",new Js(h.AUDIO));u(this,"videoInputs",new Js(h.VIDEO));u(this,"audioOutputs",new Js(h.AUDIO,"Output"));this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||re.run(Vi,()=>{this.update()},{delay:1e4}))}init(){En().then(e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)})}update(){return _(this,arguments,function*(e=0){let t=yield En(e);return this.audioInputs.update(t,this),this.videoInputs.update(t,this),this.audioOutputs.update(t,this),this})}},ge=rs||cr?null:new _c;function Lr(r){return r.deviceId===r.groupId&&r.groupId===""}function En(){return _(this,arguments,function*(r=0){if(ii()||!rn())return[];let i=yield navigator.mediaDevices.enumerateDevices();if(r!==0){let e={audio:!1,video:!1};if(i.forEach(t=>{Lr(t)&&(t.kind===h.AUDIO_INPUT?e.audio=!0:t.kind===h.VIDEO_INPUT&&(e.video=!0))}),r===2&&(e.audio=!1),r===1&&(e.video=!1),e.audio||e.video){let t;try{t=yield navigator.mediaDevices.getUserMedia(e)}catch(s){I.debug("capture before getDevices failed: ",s)}i=yield navigator.mediaDevices.enumerateDevices(),t==null||t.getTracks().forEach(s=>s.stop())}}return i.map((e,t)=>{let s={kind:e.kind,deviceId:e.deviceId,groupId:e.groupId,label:e.label||`${e.kind}_${t}`};return e.deviceId.length>0&&fc.add(`${e.deviceId}_${e.kind}`),e.getCapabilities&&(s.getCapabilities=()=>e.getCapabilities()),s})})}function Be(r=!1){return ge.update(r?1:0).then(i=>i.audioInputs.devices)}function Xe(r=!1){return ge.update(r?2:0).then(i=>i.videoInputs.devices)}var Zu=!1;function tl(){return _(this,null,function*(){try{Zu||(Zu=!0,I.info(`speakers:${(yield ji()).map(r=>` ${r.deviceId.slice(0,8)}: ${r.label}`)}`))}catch(r){}})}function ji(r=!1){return _(this,null,function*(){return ge.update(r?1:0).then(i=>i.audioOutputs.devices)})}var fc=new Set;function il(r){if(r instanceof CanvasCaptureMediaStreamTrack||!(r instanceof MediaStreamTrack))return!1;let i=r.label.toLocaleLowerCase();if(i.includes("camera")||i.includes("webcam"))return!0;let t=`${((r==null?void 0:r.getSettings())||{}).deviceId}_${h.VIDEO_INPUT}`;return!!fc.has(t)}function rl(r){if(r instanceof CanvasCaptureMediaStreamTrack||!(r instanceof MediaStreamTrack))return!1;let i=r.label.toLocaleLowerCase();if(i.includes("mic")||i.includes("\u9EA6\u514B\u98CE"))return!0;let t=`${((r==null?void 0:r.getSettings())||{}).deviceId}_${h.AUDIO_INPUT}`;return!!fc.has(t)}function Ec(r,i){return _(this,null,function*(){let t=(yield Be()).find(s=>s.deviceId===wi);return(t==null?void 0:t.groupId)===r&&t.label===i})}function sl(o){return _(this,arguments,function*({newDeviceId:r,oldDeviceId:i,oldGroupId:e,oldLabel:t,kind:s}){return r!==i?!1:s===h.AUDIO&&r===wi?yield Ec(e,t):!0})}var gn,gc=class extends Gs{constructor(e){super();this.log=e;u(this,"volumeMeter");u(this,"volumeDestination");u(this,"analyser",new pn);this.volumeMeter=new fn({log:this.log}),this.volumeDestination=new Et,this.volumeMeter.pipeTo(this.volumeDestination)}destory(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},xr=class extends Vt{constructor(e){super(e,h.AUDIO);u(this,"_outputDeviceId");u(this,"_volume",1);u(this,"_destination",qe("player").createMediaStreamDestination());u(this,"pipeline");u(this,"volumeMeterMode","worklet");this.pipeline=new gc(this._log)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(){if((Ti==="15.2"||Ti==="15.3"||Ti==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}let t=gn||new Audio;t.setAttribute("autoplay","autoplay"),t.srcObject=this.getMediaStream(),t.muted=this.muted,this.element=t,t===gn&&(gn=void 0),this.bindElementEvents()}play(){return _(this,null,function*(){if(!!this.track)return this.pipeline.source.node||this.pipeline.replaceSource(this.track),this.element||this.initializeElement(),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),this.volumeMeterMode==="worklet"?this.pipeline.volumeMeter.init():this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(qe("player").createAnalyser()),this.setVolume(this._volume),tl(),Ie(xr.prototype,this,"play").call(this)})}stop(e=0){this.pipeline.destory(),super.stop(e)}setSinkId(e){return _(this,null,function*(){var t,s;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield(s=(t=this.element).setSinkId)==null?void 0:s.call(t,e))})}get useDestination(){return!!this.pipeline.stream}setLoop(e){!this.element||(this.element.loop=e)}getAudioLevel(){return this.pipeline.volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this.pipeline.volumeMeter.getInternalAudioLevel()}},Tn=class extends xr{constructor(i){super(i),this.pipeline.source.pipeTo(this.pipeline.volumeMeter,this.pipeline.destination)}setTrack(i){var e;this.track!==i&&(this.unbindTrackEvents(),this.track=i,this.emit(ve.MEDIA_TRACK_CHANGED,i),i?(this.bindTrackEvents(),this.pipeline.source.channelCount=((e=i.getSettings())==null?void 0:e.channelCount)||1,this.pipeline.replaceSource(i),!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([i]))):this.pipeline.source.deleteNode())}setSourceNode(i){!i||this.pipeline.source.node===i||(this.pipeline.replaceSource(i),i instanceof MediaStreamAudioSourceNode?this.pipeline.destination.setNode(this._destination):this.pipeline.destination.deleteNode(),this.element&&(this.element.srcObject=this.getMediaStream(),this.element.play().catch(()=>{}),this.setVolume(this._volume)))}setVolume(i){this._volume=i,this.element&&(this.element.volume=i)}},Sn=class extends xr{constructor(e){super(e);u(this,"_sourceElement");this.pipeline.source.pipeTo(this.pipeline.gain.pipeTo(this.pipeline.volumeMeter,this.pipeline.destination))}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var t,s,o;((s=(t=this.element)==null?void 0:t.error)==null?void 0:s.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(ve.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._log.info("set element volume: no element"),this.element&&(this.element.volume=e)):(this._log.info(`start set pipeline volume: ${e}`),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),me(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play()))}stop(e=0){this.pipeline.destory();let t=this._sourceElement||this.element;t&&Ir&&(gn=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}};var qi=class extends F{constructor({userId:e,sdkAppId:t,mediaType:s,room:o,PlayerClass:n=s===1?Sn:je}){var a;super();u(this,"id",Ms());u(this,"userId","");u(this,"isRemote");u(this,"mediaType");u(this,"room");u(this,"user");u(this,"_log");u(this,"_inputTrack");u(this,"_outputTrack");u(this,"isPlayCalled");u(this,"container",null);u(this,"player");u(this,"subVideoPlayerMap");u(this,"muted",!1);u(this,"abortCtrl");u(this,"objectFit","cover");u(this,"mirror");u(this,"isScreen",!1);u(this,"manager");u(this,"trackSettings");u(this,"onPlayerError");this.userId=e||"",this.mediaType=s,this._log=I.createLogger({id:`${this.kind[0]}t`,userId:(a=o||this.room)==null?void 0:a.userId,remoteUserId:this instanceof Qe?void 0:this.userId,sdkAppId:t,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof Qe}),this.player=new n({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log}),this.player.on(ve.PLAYER_STATE_CHANGED,c=>{g.emit(E.PLAYER_STATE_CHANGED,N({track:this},c)),this.emit("player-state-changed",c)}),this.kind===h.VIDEO&&(this.player.on(ve.LOADED_DATA,()=>{g.emit(E.VIDEO_LOADED_DATA,{track:this})}),this.player.on(ve.MEDIA_TRACK_CHANGED,c=>{var d;(d=this.subVideoPlayerMap)==null||d.forEach(l=>l.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(ve.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||I}get kind(){return this.mediaType===1?h.AUDIO:h.VIDEO}get strMediaType(){return this.mediaType===4?h.VIDEO:this.mediaType===2?h.SCREEN:h.AUDIO}get streamType(){return(this.mediaType&2)===0?"main":"auxiliary"}get isMediaTrackActive(){return this.mediaTrack?!this.mediaTrack.muted&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled:!1}play(e,t){return _(this,null,function*(){let s=he(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 je&&(this.player.setObjectFit(this.objectFit),this.container!==s&&s&&(this.container=s,this.player.setContainer(s)),he(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===h.VIDEO)&&this.setPlayerMute(!0),t&&!T(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof je&&this.player.setObjectFit(this.objectFit),this.isPlayCalled=!0,s&&(this.container=s,this.player instanceof je&&this.player.setContainer(s)),g.emit(E.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(),he(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(o){throw this.handleAutoPlayFailed(),this.emit("error",o),o}})}setMirror(e,t){if(this.isScreen||this.kind!==h.VIDEO||T(e)||e===this.mirror)return;this.mirror=e;let s=this.player;t&&(s=t);let o=this.manager;if(de(this.mirror)){s.setViewMirror(this.mirror),o&&(o.mirror=!1);return}switch(this.mirror){case"view":{o&&(o.mirror=!1),s.setViewMirror(!0);break}case"publish":{o&&(o.mirror=!0),s.setViewMirror(!0);break}case"both":o&&(o.mirror=!0),s.setViewMirror(!1)}}playSubContainer(e,t){return _(this,null,function*(){if(!this._outputTrack||this.kind===h.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 je({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 s=[...this.subVideoPlayerMap.values()];for(let o of s)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(){!this.isPlayCalled||(this.isPlayCalled=!1,this.player&&(this.log.info(`stop ${this.kind} player`),this.player.stop(_t(this)?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(e=>{e.stop()}),this.container=null)}resume(){return _(this,null,function*(){var e;!this.isPlayCalled||(yield(e=this.player)==null?void 0:e.resume())})}close(){this.log.info("close"),this.isPlayCalled&&this.stop()}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),g.emit(e?E.TRACK_MUTED:E.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){De(e,e).add(h.MUTE,this.onTrackMuted).add(h.UNMUTE,this.onTrackUnmuted).add(h.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===h.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){me(e)}setInputMediaStreamTrack(e){var s;let t=this._inputTrack;if(e!==t)return this._inputTrack=e,this.trackSettings=(s=e.getSettings)==null?void 0:s.call(e),e.enabled=!this.muted,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 s;let t=this._outputTrack;e!==t&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",(s=e.getSettings)==null?void 0:s.call(e).deviceId,e.label),this._outputTrack=e,this.updatePlayingState(!!e),this.emit("output-media-track-changed",e))}setMediaType(e){this.mediaType=e}updatePlayingState(e){if(this.isPlayCalled){if(e){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped){this.player.play().catch(()=>this.handleAutoPlayFailed()),this.log.info(`playing state updated, play ${this.kind}`);return}}else if(!this.player.isStopped){this.player.stop(_t(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(){if(this.room&&this.room.enableAutoPlayDialog)new Qu;else{let e=()=>{this.resume().then(()=>{document.removeEventListener("click",e,!0)})};document.addEventListener("click",e,!0)}}getVideoFrame(){return this.player instanceof je?this.player.getVideoFrame():""}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`)}};y([ue([],F.INIT,{sync:!0})],qi.prototype,"close",1);var kp=Object.prototype.hasOwnProperty,{toString:BT}=Object.prototype;function Lp(r){if(r==null)return!0;if(typeof r=="boolean")return!1;if(typeof r=="number")return r===0;if(typeof r=="string"||typeof r=="function"||Array.isArray(r))return r.length===0;if(r instanceof Error)return r.message==="";if(Je(r))switch(Object.prototype.toString.call(r)){case"[object File]":case"[object Map]":case"[object Set]":return r.size===0;case"[object Object]":{for(let i in r)if(kp.call(r,i))return!1;return!0}}return!1}var Bt=Lp;var xp=function(r){return _(this,null,function*(){let i=wp(r);I.info(`getUserMedia with constraints: ${JSON.stringify(i)}`);let e=[],t=[],s=["label","deviceId"];i.audio&&(e=yield Be(),I.info(`microphones: ${pt(e,{keysToInclude:s})}`)),i.video&&(t=yield Xe(),I.info(`cameras: ${pt(t,{keysToInclude:s})}`));try{let o=yield navigator.mediaDevices.getUserMedia(i);return ic&&o.getTracks().forEach(n=>{I.info(`${n.kind} capabilities: ${pt(n.getCapabilities(),{keysToInclude:Oo})}`)}),o}catch(o){let{message:n}=o;throw o.name==="NotFoundError"&&(r.video&&t&&t.length===0&&(n=L({key:M.CAMERA_NOT_FOUND})),r.audio&&e&&e.length===0&&(n=L({key:M.MICROPHONE_NOT_FOUND}))),new b({code:A.INITIALIZE_FAILED,name:o.name,message:n,constraint:o.constraint})}})},Pp=vt({retryFunction:xp,settings:{retries:3,timeout:500},onError:({error:r,retry:i,reject:e,retryFuncArgs:t,retriedCount:s})=>{let o=s+1;r.name==="NotReadableError"||r.name==="OverconstrainedError"?(o===1?t[0].video&&(t[0].maxResolution=!1,(!Ue||t[0].width*t[0].height<=1920*1080)&&t[0].frameRate&&(t[0].frameRate=t[0].frameRate>10?10:5)):o===2?t[0].useDeviceIdOnly=!0:o===3&&!t[0].useExactDeviceId&&(t[0].useTrueAsConstraint=!0),i()):e(r),t[0].microphoneId&&ol(t[0].microphoneId,!1),t[0].cameraId&&ol(t[0].cameraId,!0)},onRetrying:r=>{I.warn(`getUserMedia NotReadableError observed, retrying [${r}/3]`)},onRetryFailed:r=>{Z.logFailedEvent({eventType:Ve.GET_USER_MEDIA_RETRY,error:r})},onRetrySuccess:r=>{Z.logSuccessEvent({eventType:Ve.GET_USER_MEDIA_RETRY}),Z.uploadEvent({log:`stat-${Ve.GET_USER_MEDIA_RETRY}-success-${r}`})}});function ol(r,i){return _(this,null,function*(){let t=(i?yield Xe():yield Be()).find(s=>s.deviceId===r);t&&W(t.getCapabilities)&&I.warn(pt(t.getCapabilities(),{keysToInclude:Oo}))})}function wp(r){return{audio:Vp(r),video:Up(r)}}function Vp(r){if(!r.audio)return!1;if(r.useTrueAsConstraint)return!0;let i={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:r.sampleRate};return!Bt(r.microphoneId)&&(i.deviceId=r.useExactDeviceId?{exact:r.microphoneId}:r.microphoneId,r.useDeviceIdOnly)?i:(ee(r.channelCount)&&(i.channelCount=r.channelCount),de(r.echoCancellation)&&!r.echoCancellation&&(i.echoCancellation=!1),de(r.noiseSuppression)&&!r.noiseSuppression&&(i.noiseSuppression=!1),de(r.autoGainControl)&&!r.autoGainControl&&(i.autoGainControl=!1),Bt(i)?!0:i)}function Up(r){if(!r.video)return!1;if(r.useTrueAsConstraint)return!0;let{maxResolution:i=!0}=r,e={};return r.cameraId?e.deviceId=r.useExactDeviceId?{exact:r.cameraId}:r.cameraId:r.facingMode&&(e.facingMode=r.facingMode),r.useDeviceIdOnly&&!Bt(e)?e:(r.width&&(e.width={ideal:r.width},i&&!ie&&(e.width.max=r.width)),r.height&&(e.height={ideal:r.height},i&&!ie&&(e.height.max=r.height)),ie&&bt&&r.width&&r.height&&r.width*r.height<352*288&&(e.width=r.width,e.height=r.height),r.frameRate&&(e.frameRate=r.frameRate),Bt(e)?!0:e)}var nl=Pp;function In(r){return J((i,e)=>function(...t){return _(this,null,function*(){return yield r.apply(this,t),i.apply(this,t)})})}function gt(r){return J((i,e)=>function(...t){return _(this,null,function*(){let s=yield i.apply(this,t);return yield r.call(this,...t),s})})}function J(r){return function(i,e,t){return t.value=r(t.value,e),t}}var al=(()=>{let r=!1,i=document.visibilityState;return()=>{document.visibilityState!==i&&I.info(`visibility change: ${document.visibilityState}`),!r&&(document.addEventListener("visibilitychange",()=>{I.info(`visibility change: ${document.visibilityState}`),i=document.visibilityState}),r=!0)}})();var Bp=0,An=class{constructor(){this.log=I.createLogger({id:`fq${++Bp}`});this.isRunning=!1;this.queue=[]}get length(){return this.queue.length}get lastQueueItem(){return this.length===0?null:this.queue[this.length-1]}push(i,e=!1){var o,n;let t=N({},i),s=new Promise((a,c)=>{t.resolve=a,t.reject=c});return t.promise=s,e?this.length<=1?this.queue.push(t):(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(),s}shift(){let i=this.queue.shift();return this.log.debug(`shift ${this.length}`),i}callNext(){if(this.isRunning||this.length===0)return;this.log.debug("callNext ",this.length);let{fn:i,args:e,context:t,resolve:s,reject:o}=this.queue[0];this.isRunning=!0,i.apply(t,e).then(s,o).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},qs=new WeakMap,Cn=new WeakMap;function $t(r=!1){return function(i,e,t){let s=t.value;return t.value=function(...o){let n=qs.get(this)||new An;return qs.set(this,n),n.push({fn:s,args:o,context:this},r)},t}}function cl(r){return function(i,e,t){let s=t.value;return t.value=function(...o){let n=qs.get(this);if(n){let a=n.queue.filter((c,d)=>{if(d===0)return!0;let l=!0;return c.args.forEach(p=>{o.find(m=>m===p)||(l=!1)}),l?(c.reject(new b({code:A.API_CALL_ABORTED,message:r})),!1):!0});n.queue=a}return s.apply(this,o)},t}}function Rn(r){return function(i,e,t){let s=t.value;return t.value=function(...o){var a,c,d;let n=[];return(c=(a=qs.get(this))==null?void 0:a.queue)==null||c.forEach(l=>n.push(l)),(d=Cn.get(this))==null||d.forEach(l=>l==null?void 0:l.queue.forEach(p=>n.push(p))),n.forEach(l=>{l.reject(new b({code:A.API_CALL_ABORTED,message:r}))}),qs.delete(this),Cn.delete(this),s.apply(this,o)},t}}function si(r){return function(i,e,t){let s=t.value,o=n=>r(...n);return t.value=function(...n){let a=Cn.get(this)||new Map,c=a.get(o(n))||new An;return a.set(o(n),c),Cn.set(this,a),c.push({fn:s,args:n,context:this})},t}}var Tc=class extends qi{constructor(e,t){super({mediaType:e,PlayerClass:t});u(this,"isRemote",!1);u(this,"deviceId");u(this,"groupId","");u(this,"label","");u(this,"_isRecapturing",!1);u(this,"_lastRecaptureTime",0);u(this,"_onMuteTimeoutId",-1);u(this,"_encodeCheckTimeoutId",-1);u(this,"profile")}get enableEncodeFrame(){return!1}get isPublished(){return this.state==="publish"}encodeFrame(e,t){throw new Error("Method not implemented.")}installTrackEvent(e){De(e,e).add(h.MUTE,this.onTrackMuted).add(h.UNMUTE,this.onTrackUnmuted).add(h.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===h.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){me(e)}setStateToCapture(){}capture(e){return _(this,null,function*(){var t;try{let s=x();g.emit(E.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 nl(e));let n=o.getTracks()[0];return yield this.setInputMediaStreamTrack(n),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),g.emit(E.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:x()-s}),o}catch(s){throw g.emit(E.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:s}),this.log.error(`getUserMedia error observed ${s}`),s}})}setInputMediaStreamTrack(e){return this.state===F.INIT&&this.setStateToCapture(),super.setInputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var t;return super.setOutputMediaStreamTrack(e),(t=this.room)==null?void 0:t.replaceTrack(this)}publish(e,t){return this.room=e,this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),t}unpublish(){this.room&&this.room.localTracks.delete(this),g.emit(E.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return _(this,null,function*(){if(this.mediaTrack&&xt){let{deviceId:e,groupId:t}=this.mediaTrack.getSettings(),{label:s}=this.mediaTrack;(yield sl({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=s,t&&(this.groupId=t),En().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===h.AUDIO&&!rl(this.mediaTrack)||this.kind===h.VIDEO&&!il(this.mediaTrack)||this._isRecapturing||e&&bt&&Ue)}onTrackMuted(){if(super.onTrackMuted(),al(),!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<lr){setTimeout(()=>this.onTrackMuted(),lr);return}this._onMuteTimeoutId=setTimeout(()=>_(this,null,function*(){var e;if((e=this.mediaTrack)!=null&&e.muted){if((We||pe)&&document.visibilityState!=="visible")return;this.recapture(yield this.getRecoverCaptureDeviceId())}}),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return _(this,null,function*(){if(Ie(Tc.prototype,this,"onTrackEnded").call(this),!!this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<lr){setTimeout(()=>this.onTrackEnded(),lr);return}this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e){return _(this,null,function*(){var s;if(this._isRecapturing||!this._inputTrack)return;this.log.warn("recapture trying"),(s=this._inputTrack)==null||s.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let t={useExactDeviceId:!0};if(e==="user"||e==="environment")t.facingMode=e;else{let o;(this.kind==="audio"?yield Be():yield Xe()).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}),g.emit(E.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(o=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${o.message}`),this.emit("5",o),g.emit(E.LOCAL_TRACK_RECAPTURE,{track:this,error:o})})})}getRecoverCaptureDeviceId(){return _(this,null,function*(){let e=this instanceof le;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let s=(Xs.get(t)||0)+1;if(Xs.set(t,s),s>=3){let o=e?(yield Xe()).find(n=>!Xs.has(n.deviceId)):(yield Be()).find(n=>!Xs.has(n.deviceId));o&&(this.log.warn(`${t} capture fail ${s} times, change new ${o.deviceId}`),t=o.deviceId)}}return t})}close(){var e;super.close(),this._inputTrack&&(this._inputTrack.stop(),this.uninstallTrackEvent(this._inputTrack)),(e=this.manager)==null||e.removeInput(this)}},Qe=Tc;y([ue(F.INIT,"capture",{ignoreError:!0,sync:!0})],Qe.prototype,"setStateToCapture",1),y([$t()],Qe.prototype,"capture",1),y([ue("capture","publish",{ignoreError:!0,success(){this.room.localTracks.add(this),g.emit(E.LOCAL_TRACK_PUBLISHED,{track:this}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),this._encodeCheckTimeoutId=setTimeout(()=>{if(this.isPublished&&this.isMediaTrackActive){let r=this.stat.bytesSent>0;D[r?"addSuccessEvent":"addFailedEvent"]({key:this.kind===h.AUDIO?503700:513702}),r||(this.log.warn("encode failed"),this.emit("6",this))}},5e3)},fail(r){let i="error",e=r.cause;e.message.includes("timeout")?i="timeout":e.code===A.API_CALL_ABORTED&&(i="api-call"),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:i,error:e})}})],Qe.prototype,"publish",1),y([J(r=>function(){return _(this,null,function*(){let i=this.state==="publish"?"started":"starting";r.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:i,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)})}),ue([],"capture",{sync:!0})],Qe.prototype,"unpublish",1);var Xs=new Map;g.on(E.SWITCH_DEVICE_SUCCESS,r=>{r.track.deviceId&&Xs.delete(r.track.deviceId)});var Oe=class extends Qe{constructor(e){super(1,Tn);u(this,"mediaType",1);u(this,"volume",0);u(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40});u(this,"playerMuted",!0);u(this,"pipeline");u(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0});this.manager=e,this.pipeline=new kr(e),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this)}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}get playerMediaTrack(){return this.mediaTrack}setInputMediaStreamTrack(e){return _(this,null,function*(){yield Ie(Oe.prototype,this,"setInputMediaStreamTrack").call(this,e);let t=this.trackSettings||{};D.addEnum({key:501701,value:t.channelCount||0,useUV:!1}),D.addEnum({key:501702,value:t.sampleRate||0,useUV:!1}),D.addEnum({key:502700,value:0});let{sampleRate:s,channelCount:o}=t;this._log.info(`local audio track input ${JSON.stringify({sampleRate:s,channelCount:o})}`),this.pipeline.source.channelCount=o||1,this.pipeline.replaceSource(e),this.updatePlayingState(!!e)})}capture({deviceId:e,customSource:t,useExactDeviceId:s=!1}){return super.capture({video:!1,audio:!0,microphoneId:e,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:s,customSource:t})}switchDevice(e){return _(this,null,function*(){if(!!this.mediaTrack){if(this.deviceId===e)if(e===wi){if(yield Ec(this.groupId,this.label))return}else return;try{this.log.info(`switchDevice audio to: ${e}`),this.mediaTrack&&this.mediaTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0}),this.room&&(yield this.room.replaceTrack(this)),g.emit(E.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(){ge&&!ge.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&ge.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return _(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 Be();t[0]?this.recapture(t[0].deviceId):ge.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.log.warn(`microphone added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)}update3A(o){return _(this,arguments,function*({echoCancellation:e,noiseSuppression:t,autoGainControl:s}){let n=!1;!T(e)&&e!==this.profile.echoCancellation&&(this.profile.echoCancellation=e,n=!0),!T(t)&&t!==this.profile.noiseSuppression&&(this.profile.noiseSuppression=t,n=!0),!T(s)&&s!==this.profile.autoGainControl&&(this.profile.autoGainControl=s,n=!0),n&&this.deviceId&&(yield this.recapture(this.deviceId))})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&D.addEnum({key:502700,value:2}),this.resetPlayerSource()}enableTrackANS(e){if(!this._inputTrack)return;let t=this._inputTrack.getConstraints();return t.noiseSuppression=e,this._inputTrack.applyConstraints(t).catch(s=>this._log.warn(`${e?"enable":"disable"} ANS failed `,s))}addDenoiser(e){var t;if(ht<=92&&((t=this.trackSettings)==null?void 0:t.sampleRate)!==48e3){this._log.warn("denoiser only support sampleRate 48000 before chrome 93");return}D.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.resetPlayerSource(),this.enableTrackANS(!1)}removeDenoiser(e){this.pipeline.denoiser.node===e&&(this.pipeline.denoiser.deleteNode(),this.resetPlayerSource(),this.enableTrackANS(!0))}resetPlayerSource(){this.player.setSourceNode(this.pipeline.gain.node||this.pipeline.denoiser.node||this.pipeline.source.node)}close(){this.pipeline.remove(),ge.off("audioInputAdded",this.handleMicrophoneAdded,this),ge.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}recapture(e){return _(this,null,function*(){try{yield Ie(Oe.prototype,this,"recapture").call(this,e)}catch(t){let s=(yield Be()).find(o=>o.deviceId!==e);if(s)yield Ie(Oe.prototype,this,"recapture").call(this,s.deviceId);else throw t}})}};var Ni=class{constructor(i,e=!1){this.dataView=i;this.isSEI&&(e?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let i=this.seiPayloadStartIndex,e=this.dataView.byteLength-2,t=[],s=0;for(let n=i;n<=e;n++){let a=this.dataView.getInt8(n);switch(a){case 0:case 1:case 2:case 3:s===2&&(t.push(3),s=0),a==0?s++:s=0,t.push(a);break;default:s=0,t.push(a);break}}t.push(this.dataView.getInt8(this.dataView.byteLength-1));let 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=[],s=0;for(let n=i;n<=e;n++)switch(this.dataView.getInt8(n)){case 0:s++,t.push(this.dataView.getInt8(n));break;case 3:s!==2&&t.push(this.dataView.getInt8(n)),s=0;break;default:t.push(this.dataView.getInt8(n)),s=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),s=new DataView(t);for(let o=0;o<t.byteLength;o++,e++)s.setInt8(o,this.dataView.getInt8(e));return s}};var yn=class{constructor(){u(this,"_seiMessageList",[]);u(this,"_smallSeiMessageList",[]);u(this,"_seiPayloadType",243)}encodeSEINalu(i){let e=i.byteLength,t=parseInt(String(e/255),10),s=e%255,o=[];o.push(0,0,0,1,6,this._seiPayloadType);for(let a=0;a<t;a++)o.push(255);o.push(s);let n=new DataView(i);return o.push(...new Uint8Array(n.buffer)),o.push(128),new Ni(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)}getNaluCount(i){let e=0,t=0,s=new DataView(i);for(let o=0;o<i.byteLength;o++)switch(s.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 s=this.getNaluCount(i.data),o=9-s;if(o<=0)return 0;let n=t.splice(0,o).reverse().map(this.encodeSEINalu.bind(this)),a=n.reduce((m,f)=>m+f.dataView.byteLength,0),c=new ArrayBuffer(a+i.data.byteLength),d=new DataView(c),l=new DataView(i.data),p=0;for(let m=0;m<n.length;m++)for(let f=0;f<n[m].dataView.byteLength;f++)d.setInt8(p++,n[m].dataView.getInt8(f));for(let m=0;m<i.data.byteLength;m++)d.setInt8(p++,l.getInt8(m));return i.data=c,n.length}return 0}};var le=class extends Qe{constructor(e,t=4){super(t,je);u(this,"profile",{width:640,height:480,frameRate:15,bitrate:500});u(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0});u(this,"small");u(this,"isNeedToSetBandwidth");u(this,"muteImage");u(this,"manager");u(this,"_seiCodec",new yn);u(this,"pipeline",[]);this.manager=e;let s=()=>{this.isAllowed2k4k(this.profile)?this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1}):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),this.setProfile(P(N({},this.profile),{width:1920,height:1080})),this.applyProfile())};this.on("input-media-track-changed",s),this.on("publish",s),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(!(!xt||!this.mediaTrack))return this.mediaTrack.getSettings().facingMode}get isQosClearFirst(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)==="detail"}setMute(e){return _(this,null,function*(){var t,s,o;if(Y(e)){if(this.muteImage===e)return;yield(t=this.manager)==null?void 0:t.deleteWatermark("mute"),yield(s=this.manager)==null?void 0:s.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:e}),this.muteImage=e,Ie(le.prototype,this,"setMute").call(this,!1)}else yield(o=this.manager)==null?void 0:o.deleteWatermark("mute"),this.muteImage=void 0,Ie(le.prototype,this,"setMute").call(this,e)})}capture({deviceId:e,facingMode:t,useExactDeviceId:s=!1,customSource:o}){return super.capture({audio:!1,video:!0,facingMode:t||this.facingMode,cameraId:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:s,customSource:o})}setProfile(e){let t=N({},e),s=t.width>t.height;t.width*t.height<=160*120&&pe&&Pe&&(this.log.warn(`resolution is ${t.width}*${t.height}, fallback to 240*180`),t.width=s?240:180,t.height=s?180:240,t.bitrate=Math.max(t.bitrate,150)),t.width*t.height>1280*720&&Pa&&(t.width=s?1280:720,t.height=s?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),t.bitrate&&(this.isNeedToSetBandwidth=t.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile)?super.setProfile(t):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),super.setProfile(P(N({},this.profile),{width:1920,height:1080})))}applyProfile(){var s;if(!this.mediaTrack)return;let e=this.settings;if(e.height!==this.profile.height||e.width!==this.profile.width||e.frameRate!==this.profile.frameRate)return(s=this.mediaTrack)==null?void 0:s.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}).then(()=>{if(this.manager&&this.manager.changeInput(this),this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1}),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth)return this.isNeedToSetBandwidth=!1,this.room.setBandWidth({bandwidth:this.profile.bitrate,type:h.VIDEO,videoType:h.BIG})})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate};return xt&&this.mediaTrack&&Object.assign(e,this.mediaTrack.getSettings()),e}get scaleResolutionDownBy(){let{settings:e}=this;return e.width===this.profile.width&&e.height===this.profile.height?1:Ja()&&this.profile.width>this.profile.height&&e.height>e.width?Math.max(e.width/this.profile.height,e.height/this.profile.width,1):Math.max(e.width/this.profile.width,e.height/this.profile.height,1)}isAllowed2k4k(e){var t;return!this.room||!this.room.scheduleResult||this.isScreen||e.height*e.width<2560*1440?!0:((t=this.room.scheduleResult.trtcAutoConf)==null?void 0:t["2k4k"])===1}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}switchDevice(e){return _(this,null,function*(){try{if(!this.isNeedToSwitchDevice(e))return;let t={useExactDeviceId:!0};e==="user"||e==="environment"?t.facingMode=e:t.deviceId=e,this.mediaTrack.stop(),yield this.capture(t),g.emit(E.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(t){throw this.log.error(`switch camera failed ${t}`),this.deviceId&&this.recapture(this.deviceId),t}})}listenDeviceChange(){ge&&!ge.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&ge.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return _(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 Xe();t[0]?this.recapture(t[0].deviceId):ge.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return _(this,null,function*(){this.log.warn(`camera added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)})}encodeFrame(e,t){let s=t?8:this.mediaType;return this.pipeline.reduce((o,n)=>n?n(o,s):o,e)}get enableEncodeFrame(){return this.pipeline.some(e=>e)}play(e,t){return _(this,null,function*(){return T(this.mirror)&&!this.isScreen&&this.setMirror("view"),Ie(le.prototype,this,"play").call(this,e,t)})}close(){ge.off("videoInputAdded",this.handleCameraAdded,this),ge.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return _(this,null,function*(){try{yield Ie(le.prototype,this,"recapture").call(this,e)}catch(t){let s=(yield Xe()).find(o=>o.deviceId!==e);if(s)yield Ie(le.prototype,this,"recapture").call(this,s.deviceId);else throw t}})}};var hl=Ms();if(navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:hl,exposeOrigin:!0,permittedOrigins:["*"]})}catch(r){}var Wp=function(r){return _(this,null,function*(){let i=null,e=qp(r);I.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let t=yield navigator.mediaDevices.getDisplayMedia(e);r.systemAudio&&t.getAudioTracks().length===0&&(Sr&&ht<74||Ue||ie)&&I.warn("Your browser not support capture system audio");let s=t.getVideoTracks()[0];if(s){if(r.frameRate)try{yield s.applyConstraints({frameRate:{min:r.frameRate,ideal:r.frameRate},width:r.width,height:r.height})}catch(o){I.warn(`screen applyConstraints failed: ${o}`)}r.captureElement&&(yield Jp(s,r.captureElement))}if(r.audio){let o=jp(r);I.info(`getUserMedia with constraints: ${JSON.stringify(o)}`),i=yield navigator.mediaDevices.getUserMedia(o),t.addTrack(i.getAudioTracks()[0])}return t})};function Jp(r,i){return _(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&W(r.cropTo))try{if(!(((e=r.getCaptureHandle())==null?void 0:e.handle)===hl))return;let s=yield CropTarget.fromElement(i);yield r.cropTo(s)}catch(t){I.warn(`cropTo target failed ${t}`)}})}function jp(r){let i={echoCancellation:r.echoCancellation,autoGainControl:r.autoGainControl,noiseSuppression:r.noiseSuppression,sampleRate:r.sampleRate,channelCount:r.channelCount};return T(r.microphoneId)||(i.deviceId=r.microphoneId),{audio:i,video:!1}}function qp(r){let i={preferCurrentTab:r.preferDisplaySurface==="current-tab"||!!r.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:Ue?{max:r.width}:{ideal:r.width,max:r.width},height:Ue?{max:r.height}:{ideal:r.height,max:r.height},frameRate:r.frameRate,displaySurface:r.preferDisplaySurface||"monitor"};if(i.video=e,r.systemAudio){let{echoCancellation:t=!0,noiseSuppression:s=!1,autoGainControl:o=!1}=r;i.audio={echoCancellation:t,noiseSuppression:s,autoGainControl:o,sampleRate:48e3}}return i}var ml=Wp;var ze=class extends le{constructor(e){super(e,2);u(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600});u(this,"objectFit","contain");u(this,"isScreen",!0);this._log.id=`s-${this._log.id}`}capture(l){return _(this,arguments,function*({systemAudio:e=!1,autoGainControl:t,echoCancellation:s,noiseSuppression:o,audioTrack:n,videoTrack:a,captureElement:c,preferDisplaySurface:d}){try{let p;return a||n?(p=new MediaStream,a&&p.addTrack(a),n&&p.addTrack(n)):p=yield ml({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:t,echoCancellation:s,noiseSuppression:o,captureElement:c,preferDisplaySurface:d}),yield this.setInputMediaStreamTrack(p.getVideoTracks()[0]),p}catch(p){throw this.log.error(`getDisplayMedia error observed ${p}`),p instanceof b?p:new b({code:A.INITIALIZE_FAILED,name:p.name,message:p.message})}})}switchDevice(e){return _(this,null,function*(){throw new Error("Method not implemented.")})}};var Ft=class extends Oe{constructor(i){super(i),this._log.id=`s-${this._log.id}`}};var Xp="registerProcessor('dumper', class extends AudioWorkletProcessor {process(inputs) {this.port.postMessage(inputs);return true;}});",Sc;function pl(r){return _(this,null,function*(){let i=qe("dump");Sc||(Sc=Gi(i,URL.createObjectURL(new Blob([Xp],{type:"application/javascript"})))),yield Sc;let e=new AudioWorkletNode(i,"dumper",{numberOfInputs:r.length,numberOfOutputs:0});return r.forEach((t,s)=>t.connect(e,0,s)),new ReadableStream({start(t){e.port.onmessage=s=>{t.enqueue(s.data)}},cancel(){r.forEach(t=>t.disconnect(e)),e.port.close()}})})}var bn=class extends _n{constructor(e){super();this.room=e;u(this,"_localAudioTrack");u(this,"_localScreenAudioTrack");u(this,"log",I.createLogger({id:"am"}));u(this,"denoiser");e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId))}get _localAudioPipline(){var e;return(e=this._localAudioTrack)==null?void 0:e.pipeline}dump(e){var l,p;if(!this._localAudioTrack)return;let t=[],s=[];(l=this._localAudioPipline)!=null&&l.source.node&&(t.push(this._localAudioPipline.source.node),s.push("mic")),(p=this._localAudioPipline)!=null&&p.denoiser.node&&(t.push(this._localAudioPipline.denoiser.node),s.push("mic-processed")),this.mixWeight>1&&(t.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),s.push("mix")),this.log.info(`dump audio track ${s}, duration: ${e}`);let 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<s.length;m++){let f=URL.createObjectURL(new Blob(n[m])),R=document.createElement("a");R.href=f,R.download=`${s[m]}.pcm`,R.style.display="none",document.body.appendChild(R),R.click(),URL.revokeObjectURL(f),R.remove()}clearTimeout(a),o.abort("download")},d=pl(t).then(m=>m.pipeTo(new WritableStream({write(f){f.forEach((R,C)=>n[C]=n[C]?n[C].concat(R[0]):[R[0]])}}),o).catch(f=>c));return{then:d.then.bind(d),download:c}}get hasScreenAudioTrack(){return this._localScreenAudioTrack!==null}get hasAudioTrack(){return this._localAudioTrack!==null}changeInput(e){if(e instanceof Ft)this._localScreenAudioTrack=e,e.pipeline.connect(),this.mixOnChange();else if(e instanceof Oe)this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),e.pipeline.connect(),this.mixOnChange();else if(e instanceof oi)return e.setOutputMediaStreamTrack(e.mediaTrack)}mixOnChange(){var e,t;(e=this._localAudioTrack)==null||e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),(t=this._localScreenAudioTrack)==null||t.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)}removeInput(e){e instanceof Ft?delete this._localScreenAudioTrack:e instanceof Oe?delete this._localAudioTrack:e instanceof oi}addDenoiser(e){var t;this.denoiser=e,(t=this._localAudioTrack)==null||t.addDenoiser(e)}removeDenoiser(e){var t;delete this.denoiser,(t=this._localAudioTrack)==null||t.removeDenoiser(e)}destroy(){this.close()}};function Nn(r=30,i=2){return J((e,t)=>function(...s){return new Promise((o,n)=>{let a=setTimeout(()=>{let c=new b({code:A.API_CALL_TIMEOUT,message:`checkPendingPromise ${t}() timeout ${r}s`});I.warn(c),i===2?n(c):i===1&&o()},r*1e3);e.apply(this,s).then(o,n).finally(()=>{clearTimeout(a)})})})}var Ic=class extends qi{constructor(e,t,s){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:s,room:e});this.room=e;this.user=t;u(this,"tinyId");u(this,"isRemote",!0);u(this,"jitterBufferDelay",0);u(this,"_decodeCheckTimeoutId",-1);this.tinyId=t.tinyId}setMute(e){this.hasFlag&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.hasFlag&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}waitHasMediaTrack(){return new Promise(e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)})}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===Ic.STATE_SUBSCRIBE}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}updatePlayingState(e){if(this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.hasFlag||!this.outMediaTrack)){this.log.info(`abort play, isSubscribed: ${this.isSubscribed} hasFlag: ${this.hasFlag} hasTrack: ${!!this.outMediaTrack} `);return}super.updatePlayingState(e)}}onFlagChanged(){this.updatePlayingState(this.hasFlag)}onTrackMuted(){this.hasFlag&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackMuted()}onTrackUnmuted(){this.hasFlag&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackUnmuted()}onTrackEnded(){this.hasFlag&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackEnded()}},rt=Ic;u(rt,"STATE_SUBSCRIBE","subscribe"),y([Nn(5,1)],rt.prototype,"waitHasMediaTrack",1),y([ue(F.INIT,rt.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),g.emit(E.REMOTE_TRACK_SUBSCRIBED,{track:this}),this.updatePlayingState(!0),this._decodeCheckTimeoutId=setTimeout(()=>{if(this.isSubscribed&&this.isPlayCalled&&this.stat.bytesReceived>0){let r=this.player.isPlaying||(this.kind===h.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0);D[r?"addSuccessEvent":"addFailedEvent"]({key:this.kind===h.AUDIO?504700:514702}),r||this._log.warn(`decode failed: isPlaying: ${this.player.isPlaying} ${this.kind===h.AUDIO?`audioLevel: ${this.getAudioLevel()}`:`framesDecoded: ${this.stat.framesDecoded>0}`} )`)}},5e3)},ignoreError:!0})],rt.prototype,"subscribe",1),y([ue(rt.STATE_SUBSCRIBE,F.INIT,{sync:!0,success(){this.log.info("unsubscribed"),this.updatePlayingState(!1),g.emit(E.REMOTE_TRACK_UNSUBSCRIBED,{track:this}),clearTimeout(this._decodeCheckTimeoutId)}})],rt.prototype,"unsubscribe",1);var oi=class extends rt{constructor(e,t){super(e,t,1);u(this,"volume",0);u(this,"mediaType",1);u(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0});u(this,"audioDecoder");this.manager=e.audioManager}onPlayerError(e){if(this.enableDecodeFrame){this.room.enableInsertableStreams();let t=new AudioDecoder({error:s=>this._log.error(s),output:s=>{this.player.write(s)}});t.configure({codec:"opus",sampleRate:48e3,numberOfChannels:1}),this._log.info(`audioDecoder state:${t.state}`),this.audioDecoder=t}}get enableDecodeFrame(){var e,t;return((t=(e=this.player.element)==null?void 0:e.error)==null?void 0:t.code)===MediaError.MEDIA_ERR_DECODE&&Fi&&nn().AudioDecoder}decodeFrame(e){var t;return((t=this.audioDecoder)==null?void 0:t.state)==="configured"&&this.audioDecoder.decode(new EncodedAudioChunk({data:e.data,timestamp:e.timestamp,type:"key"})),e}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get hasFlag(){return this.user.muteState.hasAudio}isFlagChanged(e){let t=e.hasAudio&&!e.audioMuted;return this.hasFlag||(this.volume=0),this.hasFlag!==t}};var zp=[-1,-1,1,-1,-1,1,1,1],Yp=[0,0,1,0,0,1,1,1],Ye=class extends F{constructor(e,t){super();this.context=e;u(this,"name");u(this,"input");u(this,"output");u(this,"texture");u(this,"ctx2d",null);u(this,"fbo");u(this,"width",0);u(this,"height",0);u(this,"x",0);u(this,"y",0);u(this,"program");u(this,"vertexShader");u(this,"fragmentShader");u(this,"totalFrames",0);u(this,"dropFrames",0);u(this,"matchInputSize",!0);u(this,"texCoordBuffer");u(this,"positionBuffer");u(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0});u(this,"cost",0);u(this,"_canvas",null);u(this,"_image");if(this.context.on("disconnect",this.close,this),this.name=t.name,this.matchInputSize=t.matchInputSize!==!1,this.width=t.width||e.width,this.height=t.height||e.height,this._image=t.image,e instanceof Fe){if(e.ctx&&t.create2d){let s=document.createElement("canvas"),o=typeof s.transferControlToOffscreen=="function"?s.transferControlToOffscreen():s;o.width=this.width,o.height=this.height,this.ctx2d=o.getContext("2d"),this._image=o,this._canvas=o}return}try{let s=e.ctx;this.texCoordBuffer=this.createBuffer(Yp),this.positionBuffer=this.createBuffer(zp),t.createTexture!==!1&&(this.texture=s.createTexture(),this.useTexture(),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),s.pixelStorei(s.PACK_ALIGNMENT,1),s.pixelStorei(s.UNPACK_ALIGNMENT,1)),t.useFbo&&(this.fbo=s.createFramebuffer(),this.useBufferFrame(),this.useTexture(),s.texImage2D(s.TEXTURE_2D,0,s.RGBA,this.width,this.height,0,s.RGBA,s.UNSIGNED_BYTE,null),s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,this.texture,0)),t.useDefaultProgram?this.program=e.defaultProgam:(t.vertexShaderSource||t.fragmentShaderSource)&&(this.vertexShader=t.vertexShaderSource?e.createShader(s.VERTEX_SHADER,t.vertexShaderSource):e.defaultVShader,this.fragmentShader=t.fragmentShaderSource?e.createShader(s.FRAGMENT_SHADER,t.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(s){this.context.destroy(s)}}get image(){return this._image}set image(e){this._image=e}createFramebuffer(e){let t=this.context.ctx,s=t.createFramebuffer();return t.bindFramebuffer(t.FRAMEBUFFER,s),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0),s}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 ye&&this.render(e)||this.context instanceof Fe&&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}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 ye){let s=this.context.ctx;s.deleteBuffer(this.texCoordBuffer),s.deleteBuffer(this.positionBuffer),this.fbo&&s.deleteFramebuffer(this.fbo),this.texture&&s.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&s.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&s.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&s.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((s,o)=>{s&&(t.activeTexture(t.TEXTURE0+o),t.bindTexture(t.TEXTURE_2D,s))})}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,s=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,s),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW),s}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 s=this.context.ctx;s.bindBuffer(s.ARRAY_BUFFER,e),s.bufferData(s.ARRAY_BUFFER,new Float32Array(t),s.STATIC_DRAW)}setAttributes(...e){let t=this.context.ctx;e.forEach((s,o)=>{t.enableVertexAttribArray(o),t.bindBuffer(t.ARRAY_BUFFER,s),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 s=this.context.ctx;s.texImage2D(s.TEXTURE_2D,0,s.RGBA,e,t,0,s.RGBA,s.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 s=this.context.ctx;s.drawArrays(s.TRIANGLE_STRIP,0,4)}draw2d(e,t,s,o,n){return this.ctx2d&&e?(e instanceof ImageData?this.ctx2d.putImageData(e,t,s):this.ctx2d.drawImage(e,t,s,o,n),!0):!1}getInfo(){var p;let{totalFrames:e,x:t,y:s,width:o,height:n,name:a,cost:c}=this,d=Date.now(),l=(e-this.lastInfo.totalFrames)/((d-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:s,width:o,height:n,timestamp:d,fps:l,name:a,cost:c},N({parent:(p=this.input)==null?void 0:p.getInfo()},this.lastInfo)}createTexture(e){let t=this.context.ctx,s=t.createTexture();return this.useTextures(s),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),s}};y([ue(F.INIT,"connected",{sync:!0})],Ye.prototype,"connect",1),y([ue("connected",F.INIT,{ignoreError:!0,sync:!0})],Ye.prototype,"disconnect",1),y([ue([],"closed",{sync:!0})],Ye.prototype,"close",1);var Kp=[0,1,1,1,0,0,1,0],Qs=class extends Ye{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t));u(this,"_intervalId",0);u(this,"_sequence",0);u(this,"checkGLError",!1);e instanceof Fe?this.ctx2d=e.ctx:e.available&&(t==null?void 0:t.mirrorUpAndDown)&&this.setTexBuffer(Kp)}start(e){this._intervalId=re.run("intervalInWorker",()=>{if(e!==this.context.frameRate&&(re.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof ye){let s=this.context.ctx.getError();s&&this.context.destroy(new Error(`${this.name} req ${this._sequence} render ${this.totalFrames} faild ${s}`))}},{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)}removeInput(e){super.removeInput(e),re.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}},Pr=class extends Qs{constructor(e,t){super(e,t);u(this,"_videoTrack");u(this,"_canvasContainer");Number(gi)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e._canvas.captureStream().getVideoTracks();let s=o=>{var c;let n=()=>{var d;return(d=this._videoTrack)==null?void 0:d.removeEventListener(o,a)},a=()=>{n(),this.context.destroy(new Error(`video track ${o}`))};this.once("closed",n),(c=this._videoTrack)==null||c.addEventListener(o,a)};e instanceof ye&&s("mute"),s("ended")}get videoTrack(){return this._videoTrack}putCanvasIntoDom(){!this.context._canvas||!this._canvasContainer||document.getElementById(this.context._canvas.id)||(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()}},vn=class extends Pr{render(i){var e;return!!((e=this.input)!=null&&e.requestFrame(i))}};var Dn=class extends Pr{constructor(e,t){super(e,{name:"smallDestination"});this.resolution=t}resize(e,t){let s,o=e*t,n=this.resolution.width*this.resolution.height;I.info(`big res: ${e}*${t} small res: ${this.resolution.width}*${this.resolution.height} `),o>n?s=o/n:(I.warn(`Small stream resolution is not smaller than big stream, which is invalid. big: ${e} * ${t} small: ${this.resolution.width} * ${this.resolution.height}`),s=o/(160*120)),super.resize(e/Math.sqrt(s),t/Math.sqrt(s))}};var zs=class extends Ye{constructor(e,t){super(e,N({name:"imageSource"},t));u(this,"_lastImage");u(this,"_totalFrames",0);u(this,"_autoResize",!1);this._autoResize=(t==null?void 0:t.autoResize)!==!1}_render(e,t){var n,a;let{width:s,height:o}=this;if(this.image instanceof HTMLVideoElement){if(W(this.image.getVideoPlaybackQuality)&&Pe){let d=this.image.getVideoPlaybackQuality().totalVideoFrames;if(((a=(n=this.image.srcObject)==null?void 0:n.getVideoTracks()[0])==null?void 0:a.muted)===!0||this._totalFrames===d)return!1;this._totalFrames=d,this.dropFrames=this._totalFrames-this.totalFrames}if({videoWidth:s,videoHeight:o}=this.image,!s||!o)return!1;this.image.width=s,this.image.height=o}else if(this.image instanceof HTMLImageElement||this.image instanceof ImageData||this.image instanceof ImageBitmap){if({width:s,height:o}=this.image,this.image!==this._lastImage)this._lastImage=this.image;else if(s===this.width&&o===this.height)return!1}else(this.image instanceof HTMLCanvasElement||this.image instanceof OffscreenCanvas)&&({width:s,height:o}=this.image,this._lastImage=this.image);if(!this._autoResize)return!0;if(this.width===s&&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,this.image)}}else{if(t){this.useTexture();let c=this.context.ctx;c.texImage2D(c.TEXTURE_2D,0,c.RGBA,c.RGBA,c.UNSIGNED_BYTE,this.image)}this.resize(s,o)}return!0}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},Ys=class extends zs{constructor(e,t,s){super(e,s);this._player=t;this.name="videoPlayerSource"}get image(){return this._player.element}},wr=class extends Ys{constructor(i,e,t){super(i,new je({id:t.name,track:e,muted:!0,container:null,objectFit:"contain",log:t.logger}),t),this.name="videoTrackSource",this._player.play()}get image(){return this._player.element}replaceTrack(i){this._player.setTrack(i),this._player.play()}close(){super.close(),this._player.stop()}};var Zp=`
43
+ `,Ji=class{constructor(i){u(this,"_volume",0);u(this,"_log");u(this,"_scriptProcessorNode",null);u(this,"_audioWorkletNode",null);u(this,"_interval",200);u(this,"ready",this.preload());let{log:e}=i;this._log=e,g.on(E.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){return Ji.workletReady||(Ji.workletReady=Gi(Ji.audioContext,URL.createObjectURL(new Blob([Mp],{type:"application/javascript"})))),Ji.workletReady.then(()=>this.initAudioWorklet()).catch(()=>this.initScriptProcessor())}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(Ji.audioContext,"volume-meter");let i=!1;this._audioWorkletNode.port.onmessage=e=>{this._volume=e.data.volume||0,!i&&e.data.cacheLen&&e.data.outputLen&&(this._log.warn("worklet play success"),i=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(i){Z.logFailedEvent({userId:this._log.userId,eventType:Ve.LOAD_WORKLET,error:i}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=qe("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=i=>{let e=i.inputBuffer.getChannelData(0),t=0;for(let s=0;s<e.length;++s)t+=e[s]*e[s];this._volume=Math.sqrt(t/e.length)||0}}catch(i){this._log.error(`volumeMeter init script processor error: ${i}`)}}destroy(){this._scriptProcessorNode&&(this._scriptProcessorNode.onaudioprocess=null),this._audioWorkletNode&&(this._audioWorkletNode.port.postMessage({name:"stop"}),this._audioWorkletNode.port.onmessage=null),this._audioWorkletNode=null,this._scriptProcessorNode=null,g.off(E.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}handleAudioLevelInterval(i){var t;let{interval:e}=i;this._interval=e,(t=this._audioWorkletNode)==null||t.port.postMessage({name:"setIntervalTime",intervalTime:e})}},Ws=Ji;u(Ws,"audioContext",qe("volume-meter")),u(Ws,"workletReady");var fn=class extends Et{constructor(e){super();u(this,"_volumeMeter");this._volumeMeter=new Ws(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return _(this,null,function*(){yield this._volumeMeter.preload(),this.setNode(this._volumeMeter.node)})}getCalculatedVolume(){return this._volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this._volumeMeter.getInternalAudioLevel()}write(e){if(this.node){let t=e.allocationSize({planeIndex:0}),s=new Float32Array(t>>2);e.copyTo(s,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:s},[s.buffer]),e.close()}}};var el=Se(Ne(),1);var Ku=r=>i=>i.deviceId===r;var Js=class{constructor(i,e="Input"){u(this,"kind");u(this,"type");u(this,"devices",[]);this.kind=i,this.type=e}update(i,e){let t=i.filter(s=>s.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);if(this.devices.length===1&&Lr(this.devices[0])){this.devices=t;return}e&&(t.forEach(s=>{if(s.deviceId&&!this.devices.find(Ku(s.deviceId))){let o=`${this.kind}${this.type}Added`;I.warn(`${o}: ${JSON.stringify(s)}`),e.emit(o,s)}}),this.devices.forEach(s=>{if(s.deviceId&&!t.find(Ku(s.deviceId))){let o=`${this.kind}${this.type}Removed`;I.warn(`${o}: ${JSON.stringify(s)}`),e.emit(o,s)}})),this.devices=t}hasDevice(i){return!!this.devices.find(e=>e.deviceId===i)}},_c=class extends el.EventEmitter{constructor(){super();u(this,"audioInputs",new Js(h.AUDIO));u(this,"videoInputs",new Js(h.VIDEO));u(this,"audioOutputs",new Js(h.AUDIO,"Output"));this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||re.run(Vi,()=>{this.update()},{delay:1e4}))}init(){En().then(e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)})}update(){return _(this,arguments,function*(e=0){let t=yield En(e);return this.audioInputs.update(t,this),this.videoInputs.update(t,this),this.audioOutputs.update(t,this),this})}},ge=rs||cr?null:new _c;function Lr(r){return r.deviceId===r.groupId&&r.groupId===""}function En(){return _(this,arguments,function*(r=0){if(ii()||!rn())return[];let i=yield navigator.mediaDevices.enumerateDevices();if(r!==0){let e={audio:!1,video:!1};if(i.forEach(t=>{Lr(t)&&(t.kind===h.AUDIO_INPUT?e.audio=!0:t.kind===h.VIDEO_INPUT&&(e.video=!0))}),r===2&&(e.audio=!1),r===1&&(e.video=!1),e.audio||e.video){let t;try{t=yield navigator.mediaDevices.getUserMedia(e)}catch(s){I.debug("capture before getDevices failed: ",s)}i=yield navigator.mediaDevices.enumerateDevices(),t==null||t.getTracks().forEach(s=>s.stop())}}return i.map((e,t)=>{let s={kind:e.kind,deviceId:e.deviceId,groupId:e.groupId,label:e.label||`${e.kind}_${t}`};return e.deviceId.length>0&&fc.add(`${e.deviceId}_${e.kind}`),e.getCapabilities&&(s.getCapabilities=()=>e.getCapabilities()),s})})}function Be(r=!1){return ge.update(r?1:0).then(i=>i.audioInputs.devices)}function Xe(r=!1){return ge.update(r?2:0).then(i=>i.videoInputs.devices)}var Zu=!1;function tl(){return _(this,null,function*(){try{Zu||(Zu=!0,I.info(`speakers:${(yield ji()).map(r=>` ${r.deviceId.slice(0,8)}: ${r.label}`)}`))}catch(r){}})}function ji(r=!1){return _(this,null,function*(){return ge.update(r?1:0).then(i=>i.audioOutputs.devices)})}var fc=new Set;function il(r){if(r instanceof CanvasCaptureMediaStreamTrack||!(r instanceof MediaStreamTrack))return!1;let i=r.label.toLocaleLowerCase();if(i.includes("camera")||i.includes("webcam"))return!0;let t=`${((r==null?void 0:r.getSettings())||{}).deviceId}_${h.VIDEO_INPUT}`;return!!fc.has(t)}function rl(r){if(r instanceof CanvasCaptureMediaStreamTrack||!(r instanceof MediaStreamTrack))return!1;let i=r.label.toLocaleLowerCase();if(i.includes("mic")||i.includes("\u9EA6\u514B\u98CE"))return!0;let t=`${((r==null?void 0:r.getSettings())||{}).deviceId}_${h.AUDIO_INPUT}`;return!!fc.has(t)}function Ec(r,i){return _(this,null,function*(){let t=(yield Be()).find(s=>s.deviceId===wi);return(t==null?void 0:t.groupId)===r&&t.label===i})}function sl(o){return _(this,arguments,function*({newDeviceId:r,oldDeviceId:i,oldGroupId:e,oldLabel:t,kind:s}){return r!==i?!1:s===h.AUDIO&&r===wi?yield Ec(e,t):!0})}var gn,gc=class extends Gs{constructor(e){super();this.log=e;u(this,"volumeMeter");u(this,"volumeDestination");u(this,"analyser",new pn);this.volumeMeter=new fn({log:this.log}),this.volumeDestination=new Et,this.volumeMeter.pipeTo(this.volumeDestination)}destory(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},xr=class extends Vt{constructor(e){super(e,h.AUDIO);u(this,"_outputDeviceId");u(this,"_volume",1);u(this,"_destination",qe("player").createMediaStreamDestination());u(this,"pipeline");u(this,"volumeMeterMode","worklet");this.pipeline=new gc(this._log)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(){if((Ti==="15.2"||Ti==="15.3"||Ti==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}let t=gn||new Audio;t.setAttribute("autoplay","autoplay"),t.srcObject=this.getMediaStream(),t.muted=this.muted,this.element=t,t===gn&&(gn=void 0),this.bindElementEvents()}play(){return _(this,null,function*(){if(!!this.track)return this.pipeline.source.node||this.pipeline.replaceSource(this.track),this.element||this.initializeElement(),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),this.volumeMeterMode==="worklet"?this.pipeline.volumeMeter.init():this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(qe("player").createAnalyser()),this.setVolume(this._volume),tl(),Ie(xr.prototype,this,"play").call(this)})}stop(e=0){this.pipeline.destory(),super.stop(e)}setSinkId(e){return _(this,null,function*(){var t,s;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield(s=(t=this.element).setSinkId)==null?void 0:s.call(t,e))})}get useDestination(){return!!this.pipeline.stream}setLoop(e){!this.element||(this.element.loop=e)}getAudioLevel(){return this.pipeline.volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this.pipeline.volumeMeter.getInternalAudioLevel()}},Tn=class extends xr{constructor(i){super(i),this.pipeline.source.pipeTo(this.pipeline.volumeMeter,this.pipeline.destination)}setTrack(i){var e;this.track!==i&&(this.unbindTrackEvents(),this.track=i,this.emit(ve.MEDIA_TRACK_CHANGED,i),i?(this.bindTrackEvents(),this.pipeline.source.channelCount=((e=i.getSettings())==null?void 0:e.channelCount)||1,this.pipeline.replaceSource(i),!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([i]))):this.pipeline.source.deleteNode())}setSourceNode(i){!i||this.pipeline.source.node===i||(this.pipeline.replaceSource(i),i instanceof MediaStreamAudioSourceNode?this.pipeline.destination.setNode(this._destination):this.pipeline.destination.deleteNode(),this.element&&(this.element.srcObject=this.getMediaStream(),this.element.play().catch(()=>{}),this.setVolume(this._volume)))}setVolume(i){this._volume=i,this.element&&(this.element.volume=i)}},Sn=class extends xr{constructor(e){super(e);u(this,"_sourceElement");this.pipeline.source.pipeTo(this.pipeline.gain.pipeTo(this.pipeline.volumeMeter,this.pipeline.destination))}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var t,s,o;((s=(t=this.element)==null?void 0:t.error)==null?void 0:s.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(ve.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._log.info("set element volume: no element"),this.element&&(this.element.volume=e)):(this._log.info(`start set pipeline volume: ${e}`),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),me(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play()))}stop(e=0){this.pipeline.destory();let t=this._sourceElement||this.element;t&&Ir&&(gn=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}};var qi=class extends F{constructor({userId:e,sdkAppId:t,mediaType:s,room:o,PlayerClass:n=s===1?Sn:je}){var a;super();u(this,"id",Ms());u(this,"userId","");u(this,"isRemote");u(this,"mediaType");u(this,"room");u(this,"user");u(this,"_log");u(this,"_inputTrack");u(this,"_outputTrack");u(this,"isPlayCalled");u(this,"container",null);u(this,"player");u(this,"subVideoPlayerMap");u(this,"muted",!1);u(this,"abortCtrl");u(this,"objectFit","cover");u(this,"mirror");u(this,"isScreen",!1);u(this,"manager");u(this,"trackSettings");u(this,"onPlayerError");this.userId=e||"",this.mediaType=s,this._log=I.createLogger({id:`${this.kind[0]}t`,userId:(a=o||this.room)==null?void 0:a.userId,remoteUserId:this instanceof Qe?void 0:this.userId,sdkAppId:t,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof Qe}),this.player=new n({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log}),this.player.on(ve.PLAYER_STATE_CHANGED,c=>{g.emit(E.PLAYER_STATE_CHANGED,N({track:this},c)),this.emit("player-state-changed",c)}),this.kind===h.VIDEO&&(this.player.on(ve.LOADED_DATA,()=>{g.emit(E.VIDEO_LOADED_DATA,{track:this})}),this.player.on(ve.MEDIA_TRACK_CHANGED,c=>{var d;(d=this.subVideoPlayerMap)==null||d.forEach(l=>l.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(ve.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||I}get kind(){return this.mediaType===1?h.AUDIO:h.VIDEO}get strMediaType(){return this.mediaType===4?h.VIDEO:this.mediaType===2?h.SCREEN:h.AUDIO}get streamType(){return(this.mediaType&2)===0?"main":"auxiliary"}get isMediaTrackActive(){return this.mediaTrack?!this.mediaTrack.muted&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled:!1}play(e,t){return _(this,null,function*(){let s=he(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 je&&(this.player.setObjectFit(this.objectFit),this.container!==s&&s&&(this.container=s,this.player.setContainer(s)),he(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===h.VIDEO)&&this.setPlayerMute(!0),t&&!T(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof je&&this.player.setObjectFit(this.objectFit),this.isPlayCalled=!0,s&&(this.container=s,this.player instanceof je&&this.player.setContainer(s)),g.emit(E.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(),he(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(o){throw this.handleAutoPlayFailed(),this.emit("error",o),o}})}setMirror(e,t){if(this.isScreen||this.kind!==h.VIDEO||T(e)||e===this.mirror)return;this.mirror=e;let s=this.player;t&&(s=t);let o=this.manager;if(de(this.mirror)){s.setViewMirror(this.mirror),o&&(o.mirror=!1);return}switch(this.mirror){case"view":{o&&(o.mirror=!1),s.setViewMirror(!0);break}case"publish":{o&&(o.mirror=!0),s.setViewMirror(!0);break}case"both":o&&(o.mirror=!0),s.setViewMirror(!1)}}playSubContainer(e,t){return _(this,null,function*(){if(!this._outputTrack||this.kind===h.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 je({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 s=[...this.subVideoPlayerMap.values()];for(let o of s)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(){!this.isPlayCalled||(this.isPlayCalled=!1,this.player&&(this.log.info(`stop ${this.kind} player`),this.player.stop(_t(this)?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(e=>{e.stop()}),this.container=null)}resume(){return _(this,null,function*(){var e;!this.isPlayCalled||(yield(e=this.player)==null?void 0:e.resume())})}close(){this.log.info("close"),this.isPlayCalled&&this.stop()}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),g.emit(e?E.TRACK_MUTED:E.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){De(e,e).add(h.MUTE,this.onTrackMuted).add(h.UNMUTE,this.onTrackUnmuted).add(h.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===h.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){me(e)}setInputMediaStreamTrack(e){var s;let t=this._inputTrack;if(e!==t)return this._inputTrack=e,this.trackSettings=(s=e.getSettings)==null?void 0:s.call(e),e.enabled=!this.muted,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 s;let t=this._outputTrack;e!==t&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",(s=e.getSettings)==null?void 0:s.call(e).deviceId,e.label),this._outputTrack=e,this.updatePlayingState(!!e),this.emit("output-media-track-changed",e))}setMediaType(e){this.mediaType=e}updatePlayingState(e){if(this.isPlayCalled){if(e){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped){this.player.play().catch(()=>this.handleAutoPlayFailed()),this.log.info(`playing state updated, play ${this.kind}`);return}}else if(!this.player.isStopped){this.player.stop(_t(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(){if(this.room&&this.room.enableAutoPlayDialog)new Qu;else{let e=()=>{this.resume().then(()=>{document.removeEventListener("click",e,!0)})};document.addEventListener("click",e,!0)}}getVideoFrame(){return this.player instanceof je?this.player.getVideoFrame():""}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`)}};y([ue([],F.INIT,{sync:!0})],qi.prototype,"close",1);var kp=Object.prototype.hasOwnProperty,{toString:BT}=Object.prototype;function Lp(r){if(r==null)return!0;if(typeof r=="boolean")return!1;if(typeof r=="number")return r===0;if(typeof r=="string"||typeof r=="function"||Array.isArray(r))return r.length===0;if(r instanceof Error)return r.message==="";if(Je(r))switch(Object.prototype.toString.call(r)){case"[object File]":case"[object Map]":case"[object Set]":return r.size===0;case"[object Object]":{for(let i in r)if(kp.call(r,i))return!1;return!0}}return!1}var Bt=Lp;var xp=function(r){return _(this,null,function*(){let i=wp(r);I.info(`getUserMedia with constraints: ${JSON.stringify(i)}`);let e=[],t=[],s=["label","deviceId"];i.audio&&(e=yield Be(),I.info(`microphones: ${pt(e,{keysToInclude:s})}`)),i.video&&(t=yield Xe(),I.info(`cameras: ${pt(t,{keysToInclude:s})}`));try{let o=yield navigator.mediaDevices.getUserMedia(i);return ic&&o.getTracks().forEach(n=>{I.info(`${n.kind} capabilities: ${pt(n.getCapabilities(),{keysToInclude:Oo})}`)}),o}catch(o){let{message:n}=o;throw o.name==="NotFoundError"&&(r.video&&t&&t.length===0&&(n=L({key:M.CAMERA_NOT_FOUND})),r.audio&&e&&e.length===0&&(n=L({key:M.MICROPHONE_NOT_FOUND}))),new b({code:A.INITIALIZE_FAILED,name:o.name,message:n,constraint:o.constraint})}})},Pp=vt({retryFunction:xp,settings:{retries:3,timeout:500},onError:({error:r,retry:i,reject:e,retryFuncArgs:t,retriedCount:s})=>{let o=s+1;r.name==="NotReadableError"||r.name==="OverconstrainedError"?(o===1?t[0].video&&(t[0].maxResolution=!1,(!Ue||t[0].width*t[0].height<=1920*1080)&&t[0].frameRate&&(t[0].frameRate=t[0].frameRate>10?10:5)):o===2?t[0].useDeviceIdOnly=!0:o===3&&!t[0].useExactDeviceId&&(t[0].useTrueAsConstraint=!0),i()):e(r),t[0].microphoneId&&ol(t[0].microphoneId,!1),t[0].cameraId&&ol(t[0].cameraId,!0)},onRetrying:r=>{I.warn(`getUserMedia NotReadableError observed, retrying [${r}/3]`)},onRetryFailed:r=>{Z.logFailedEvent({eventType:Ve.GET_USER_MEDIA_RETRY,error:r})},onRetrySuccess:r=>{Z.logSuccessEvent({eventType:Ve.GET_USER_MEDIA_RETRY}),Z.uploadEvent({log:`stat-${Ve.GET_USER_MEDIA_RETRY}-success-${r}`})}});function ol(r,i){return _(this,null,function*(){let t=(i?yield Xe():yield Be()).find(s=>s.deviceId===r);t&&W(t.getCapabilities)&&I.warn(pt(t.getCapabilities(),{keysToInclude:Oo}))})}function wp(r){return{audio:Vp(r),video:Up(r)}}function Vp(r){if(!r.audio)return!1;if(r.useTrueAsConstraint)return!0;let i={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:r.sampleRate};return!Bt(r.microphoneId)&&(i.deviceId=r.useExactDeviceId?{exact:r.microphoneId}:r.microphoneId,r.useDeviceIdOnly)?i:(ee(r.channelCount)&&(i.channelCount=r.channelCount),de(r.echoCancellation)&&!r.echoCancellation&&(i.echoCancellation=!1),de(r.noiseSuppression)&&!r.noiseSuppression&&(i.noiseSuppression=!1),de(r.autoGainControl)&&!r.autoGainControl&&(i.autoGainControl=!1),Bt(i)?!0:i)}function Up(r){if(!r.video)return!1;if(r.useTrueAsConstraint)return!0;let{maxResolution:i=!0}=r,e={};return r.cameraId?e.deviceId=r.useExactDeviceId?{exact:r.cameraId}:r.cameraId:r.facingMode&&(e.facingMode=r.facingMode),r.useDeviceIdOnly&&!Bt(e)?e:(r.width&&(e.width={ideal:r.width},i&&!ie&&(e.width.max=r.width)),r.height&&(e.height={ideal:r.height},i&&!ie&&(e.height.max=r.height)),ie&&bt&&r.width&&r.height&&r.width*r.height<352*288&&(e.width=r.width,e.height=r.height),r.frameRate&&(e.frameRate=r.frameRate),Bt(e)?!0:e)}var nl=Pp;function In(r){return J((i,e)=>function(...t){return _(this,null,function*(){return yield r.apply(this,t),i.apply(this,t)})})}function gt(r){return J((i,e)=>function(...t){return _(this,null,function*(){let s=yield i.apply(this,t);return yield r.call(this,...t),s})})}function J(r){return function(i,e,t){return t.value=r(t.value,e),t}}var al=(()=>{let r=!1,i=document.visibilityState;return()=>{document.visibilityState!==i&&I.info(`visibility change: ${document.visibilityState}`),!r&&(document.addEventListener("visibilitychange",()=>{I.info(`visibility change: ${document.visibilityState}`),i=document.visibilityState}),r=!0)}})();var Bp=0,An=class{constructor(){this.log=I.createLogger({id:`fq${++Bp}`});this.isRunning=!1;this.queue=[]}get length(){return this.queue.length}get lastQueueItem(){return this.length===0?null:this.queue[this.length-1]}push(i,e=!1){var o,n;let t=N({},i),s=new Promise((a,c)=>{t.resolve=a,t.reject=c});return t.promise=s,e?this.length<=1?this.queue.push(t):(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(),s}shift(){let i=this.queue.shift();return this.log.debug(`shift ${this.length}`),i}callNext(){if(this.isRunning||this.length===0)return;this.log.debug("callNext ",this.length);let{fn:i,args:e,context:t,resolve:s,reject:o}=this.queue[0];this.isRunning=!0,i.apply(t,e).then(s,o).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},qs=new WeakMap,Cn=new WeakMap;function $t(r=!1){return function(i,e,t){let s=t.value;return t.value=function(...o){let n=qs.get(this)||new An;return qs.set(this,n),n.push({fn:s,args:o,context:this},r)},t}}function cl(r){return function(i,e,t){let s=t.value;return t.value=function(...o){let n=qs.get(this);if(n){let a=n.queue.filter((c,d)=>{if(d===0)return!0;let l=!0;return c.args.forEach(p=>{o.find(m=>m===p)||(l=!1)}),l?(c.reject(new b({code:A.API_CALL_ABORTED,message:r})),!1):!0});n.queue=a}return s.apply(this,o)},t}}function Rn(r){return function(i,e,t){let s=t.value;return t.value=function(...o){var a,c,d;let n=[];return(c=(a=qs.get(this))==null?void 0:a.queue)==null||c.forEach(l=>n.push(l)),(d=Cn.get(this))==null||d.forEach(l=>l==null?void 0:l.queue.forEach(p=>n.push(p))),n.forEach(l=>{l.reject(new b({code:A.API_CALL_ABORTED,message:r}))}),qs.delete(this),Cn.delete(this),s.apply(this,o)},t}}function si(r){return function(i,e,t){let s=t.value,o=n=>r(...n);return t.value=function(...n){let a=Cn.get(this)||new Map,c=a.get(o(n))||new An;return a.set(o(n),c),Cn.set(this,a),c.push({fn:s,args:n,context:this})},t}}var Tc=class extends qi{constructor(e,t){super({mediaType:e,PlayerClass:t});u(this,"isRemote",!1);u(this,"deviceId");u(this,"groupId","");u(this,"label","");u(this,"_isRecapturing",!1);u(this,"_lastRecaptureTime",0);u(this,"_onMuteTimeoutId",-1);u(this,"_encodeCheckTimeoutId",-1);u(this,"profile")}get enableEncodeFrame(){return!1}get isPublished(){return this.state==="publish"}encodeFrame(e,t){throw new Error("Method not implemented.")}installTrackEvent(e){De(e,e).add(h.MUTE,this.onTrackMuted).add(h.UNMUTE,this.onTrackUnmuted).add(h.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===h.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){me(e)}setStateToCapture(){}capture(e){return _(this,null,function*(){var t;try{let s=x();g.emit(E.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 nl(e));let n=o.getTracks()[0];return yield this.setInputMediaStreamTrack(n),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),g.emit(E.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:x()-s}),o}catch(s){throw g.emit(E.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:s}),this.log.error(`getUserMedia error observed ${s}`),s}})}setInputMediaStreamTrack(e){return this.state===F.INIT&&this.setStateToCapture(),super.setInputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var t;if(super.setOutputMediaStreamTrack(e),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),g.emit(E.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return _(this,null,function*(){if(this.mediaTrack&&xt){let{deviceId:e,groupId:t}=this.mediaTrack.getSettings(),{label:s}=this.mediaTrack;(yield sl({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=s,t&&(this.groupId=t),En().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===h.AUDIO&&!rl(this.mediaTrack)||this.kind===h.VIDEO&&!il(this.mediaTrack)||this._isRecapturing||e&&bt&&Ue)}onTrackMuted(){if(super.onTrackMuted(),al(),!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<lr){setTimeout(()=>this.onTrackMuted(),lr);return}this._onMuteTimeoutId=setTimeout(()=>_(this,null,function*(){var e;if((e=this.mediaTrack)!=null&&e.muted){if((We||pe)&&document.visibilityState!=="visible")return;this.recapture(yield this.getRecoverCaptureDeviceId())}}),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return _(this,null,function*(){if(Ie(Tc.prototype,this,"onTrackEnded").call(this),!!this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<lr){setTimeout(()=>this.onTrackEnded(),lr);return}this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e){return _(this,null,function*(){var s;if(this._isRecapturing||!this._inputTrack)return;this.log.warn("recapture trying"),(s=this._inputTrack)==null||s.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let t={useExactDeviceId:!0};if(e==="user"||e==="environment")t.facingMode=e;else{let o;(this.kind==="audio"?yield Be():yield Xe()).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}),g.emit(E.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(o=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${o.message}`),this.emit("5",o),g.emit(E.LOCAL_TRACK_RECAPTURE,{track:this,error:o})})})}getRecoverCaptureDeviceId(){return _(this,null,function*(){let e=this instanceof le;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let s=(Xs.get(t)||0)+1;if(Xs.set(t,s),s>=3){let o=e?(yield Xe()).find(n=>!Xs.has(n.deviceId)):(yield Be()).find(n=>!Xs.has(n.deviceId));o&&(this.log.warn(`${t} capture fail ${s} times, change new ${o.deviceId}`),t=o.deviceId)}}return t})}close(){var e;super.close(),this._inputTrack&&(this._inputTrack.stop(),this.uninstallTrackEvent(this._inputTrack)),(e=this.manager)==null||e.removeInput(this)}},Qe=Tc;y([ue(F.INIT,"capture",{ignoreError:!0,sync:!0})],Qe.prototype,"setStateToCapture",1),y([$t()],Qe.prototype,"capture",1),y([ue("capture","publish",{ignoreError:!0,success(){this.room.localTracks.add(this),g.emit(E.LOCAL_TRACK_PUBLISHED,{track:this}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),this._encodeCheckTimeoutId=setTimeout(()=>{if(this.isPublished&&this.isMediaTrackActive){let r=this.stat.bytesSent>0;D[r?"addSuccessEvent":"addFailedEvent"]({key:this.kind===h.AUDIO?503700:513702}),r||(this.log.warn("encode failed"),this.emit("6",this))}},5e3)},fail(r){let i="error",e=r.cause;e.message.includes("timeout")?i="timeout":e.code===A.API_CALL_ABORTED&&(i="api-call"),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:i,error:e})}})],Qe.prototype,"publish",1),y([J(r=>function(){return _(this,null,function*(){let i=this.state==="publish"?"started":"starting";r.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:i,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)})}),ue([],"capture",{sync:!0})],Qe.prototype,"unpublish",1);var Xs=new Map;g.on(E.SWITCH_DEVICE_SUCCESS,r=>{r.track.deviceId&&Xs.delete(r.track.deviceId)});var Oe=class extends Qe{constructor(e){super(1,Tn);u(this,"mediaType",1);u(this,"volume",0);u(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40});u(this,"playerMuted",!0);u(this,"pipeline");u(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0});this.manager=e,this.pipeline=new kr(e),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this)}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}get playerMediaTrack(){return this.mediaTrack}setInputMediaStreamTrack(e){return _(this,null,function*(){yield Ie(Oe.prototype,this,"setInputMediaStreamTrack").call(this,e);let t=this.trackSettings||{};D.addEnum({key:501701,value:t.channelCount||0,useUV:!1}),D.addEnum({key:501702,value:t.sampleRate||0,useUV:!1}),D.addEnum({key:502700,value:0});let{sampleRate:s,channelCount:o}=t;this._log.info(`local audio track input ${JSON.stringify({sampleRate:s,channelCount:o})}`),this.pipeline.source.channelCount=o||1,this.pipeline.replaceSource(e),this.updatePlayingState(!!e)})}capture({deviceId:e,customSource:t,useExactDeviceId:s=!1}){return super.capture({video:!1,audio:!0,microphoneId:e,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:s,customSource:t})}switchDevice(e){return _(this,null,function*(){if(!!this.mediaTrack){if(this.deviceId===e)if(e===wi){if(yield Ec(this.groupId,this.label))return}else return;try{this.log.info(`switchDevice audio to: ${e}`),this.mediaTrack&&this.mediaTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0}),this.room&&(yield this.room.replaceTrack(this)),g.emit(E.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(){ge&&!ge.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&ge.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return _(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 Be();t[0]?this.recapture(t[0].deviceId):ge.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.log.warn(`microphone added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)}update3A(o){return _(this,arguments,function*({echoCancellation:e,noiseSuppression:t,autoGainControl:s}){let n=!1;!T(e)&&e!==this.profile.echoCancellation&&(this.profile.echoCancellation=e,n=!0),!T(t)&&t!==this.profile.noiseSuppression&&(this.profile.noiseSuppression=t,n=!0),!T(s)&&s!==this.profile.autoGainControl&&(this.profile.autoGainControl=s,n=!0),n&&this.deviceId&&(yield this.recapture(this.deviceId))})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&D.addEnum({key:502700,value:2}),this.resetPlayerSource()}enableTrackANS(e){if(!this._inputTrack)return;let t=this._inputTrack.getConstraints();return t.noiseSuppression=e,this._inputTrack.applyConstraints(t).catch(s=>this._log.warn(`${e?"enable":"disable"} ANS failed `,s))}addDenoiser(e){var t;if(ht<=92&&((t=this.trackSettings)==null?void 0:t.sampleRate)!==48e3){this._log.warn("denoiser only support sampleRate 48000 before chrome 93");return}D.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.resetPlayerSource(),this.enableTrackANS(!1)}removeDenoiser(e){this.pipeline.denoiser.node===e&&(this.pipeline.denoiser.deleteNode(),this.resetPlayerSource(),this.enableTrackANS(!0))}resetPlayerSource(){this.player.setSourceNode(this.pipeline.gain.node||this.pipeline.denoiser.node||this.pipeline.source.node)}close(){this.pipeline.remove(),ge.off("audioInputAdded",this.handleMicrophoneAdded,this),ge.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}recapture(e){return _(this,null,function*(){try{yield Ie(Oe.prototype,this,"recapture").call(this,e)}catch(t){let s=(yield Be()).find(o=>o.deviceId!==e);if(s)yield Ie(Oe.prototype,this,"recapture").call(this,s.deviceId);else throw t}})}};var Ni=class{constructor(i,e=!1){this.dataView=i;this.isSEI&&(e?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let i=this.seiPayloadStartIndex,e=this.dataView.byteLength-2,t=[],s=0;for(let n=i;n<=e;n++){let a=this.dataView.getInt8(n);switch(a){case 0:case 1:case 2:case 3:s===2&&(t.push(3),s=0),a==0?s++:s=0,t.push(a);break;default:s=0,t.push(a);break}}t.push(this.dataView.getInt8(this.dataView.byteLength-1));let 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=[],s=0;for(let n=i;n<=e;n++)switch(this.dataView.getInt8(n)){case 0:s++,t.push(this.dataView.getInt8(n));break;case 3:s!==2&&t.push(this.dataView.getInt8(n)),s=0;break;default:t.push(this.dataView.getInt8(n)),s=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),s=new DataView(t);for(let o=0;o<t.byteLength;o++,e++)s.setInt8(o,this.dataView.getInt8(e));return s}};var yn=class{constructor(){u(this,"_seiMessageList",[]);u(this,"_smallSeiMessageList",[]);u(this,"_seiPayloadType",243)}encodeSEINalu(i){let e=i.byteLength,t=parseInt(String(e/255),10),s=e%255,o=[];o.push(0,0,0,1,6,this._seiPayloadType);for(let a=0;a<t;a++)o.push(255);o.push(s);let n=new DataView(i);return o.push(...new Uint8Array(n.buffer)),o.push(128),new Ni(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)}getNaluCount(i){let e=0,t=0,s=new DataView(i);for(let o=0;o<i.byteLength;o++)switch(s.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 s=this.getNaluCount(i.data),o=9-s;if(o<=0)return 0;let n=t.splice(0,o).reverse().map(this.encodeSEINalu.bind(this)),a=n.reduce((m,f)=>m+f.dataView.byteLength,0),c=new ArrayBuffer(a+i.data.byteLength),d=new DataView(c),l=new DataView(i.data),p=0;for(let m=0;m<n.length;m++)for(let f=0;f<n[m].dataView.byteLength;f++)d.setInt8(p++,n[m].dataView.getInt8(f));for(let m=0;m<i.data.byteLength;m++)d.setInt8(p++,l.getInt8(m));return i.data=c,n.length}return 0}};var le=class extends Qe{constructor(e,t=4){super(t,je);u(this,"profile",{width:640,height:480,frameRate:15,bitrate:500});u(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0});u(this,"small");u(this,"isNeedToSetBandwidth");u(this,"muteImage");u(this,"manager");u(this,"_seiCodec",new yn);u(this,"pipeline",[]);this.manager=e;let s=()=>{this.isAllowed2k4k(this.profile)?this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1}):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),this.setProfile(P(N({},this.profile),{width:1920,height:1080})),this.applyProfile())};this.on("input-media-track-changed",s),this.on("publish",s),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(!(!xt||!this.mediaTrack))return this.mediaTrack.getSettings().facingMode}get isQosClearFirst(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)==="detail"}setMute(e){return _(this,null,function*(){var t,s,o;if(Y(e)){if(this.muteImage===e)return;yield(t=this.manager)==null?void 0:t.deleteWatermark("mute"),yield(s=this.manager)==null?void 0:s.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:e}),this.muteImage=e,Ie(le.prototype,this,"setMute").call(this,!1)}else yield(o=this.manager)==null?void 0:o.deleteWatermark("mute"),this.muteImage=void 0,Ie(le.prototype,this,"setMute").call(this,e)})}capture({deviceId:e,facingMode:t,useExactDeviceId:s=!1,customSource:o}){return super.capture({audio:!1,video:!0,facingMode:t||this.facingMode,cameraId:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:s,customSource:o})}setProfile(e){let t=N({},e),s=t.width>t.height;t.width*t.height<=160*120&&pe&&Pe&&(this.log.warn(`resolution is ${t.width}*${t.height}, fallback to 240*180`),t.width=s?240:180,t.height=s?180:240,t.bitrate=Math.max(t.bitrate,150)),t.width*t.height>1280*720&&Pa&&(t.width=s?1280:720,t.height=s?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),t.bitrate&&(this.isNeedToSetBandwidth=t.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile)?super.setProfile(t):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),super.setProfile(P(N({},this.profile),{width:1920,height:1080})))}applyProfile(){var s;if(!this.mediaTrack)return;let e=this.settings;if(e.height!==this.profile.height||e.width!==this.profile.width||e.frameRate!==this.profile.frameRate)return(s=this.mediaTrack)==null?void 0:s.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}).then(()=>{if(this.manager&&this.manager.changeInput(this),this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1}),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth)return this.isNeedToSetBandwidth=!1,this.room.setBandWidth({bandwidth:this.profile.bitrate,type:h.VIDEO,videoType:h.BIG})})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate};return xt&&this.mediaTrack&&Object.assign(e,this.mediaTrack.getSettings()),e}get scaleResolutionDownBy(){let{settings:e}=this;return e.width===this.profile.width&&e.height===this.profile.height?1:Ja()&&this.profile.width>this.profile.height&&e.height>e.width?Math.max(e.width/this.profile.height,e.height/this.profile.width,1):Math.max(e.width/this.profile.width,e.height/this.profile.height,1)}isAllowed2k4k(e){var t;return!this.room||!this.room.scheduleResult||this.isScreen||e.height*e.width<2560*1440?!0:((t=this.room.scheduleResult.trtcAutoConf)==null?void 0:t["2k4k"])===1}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}switchDevice(e){return _(this,null,function*(){try{if(!this.isNeedToSwitchDevice(e))return;let t={useExactDeviceId:!0};e==="user"||e==="environment"?t.facingMode=e:t.deviceId=e,this.mediaTrack.stop(),yield this.capture(t),g.emit(E.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(t){throw this.log.error(`switch camera failed ${t}`),this.deviceId&&this.recapture(this.deviceId),t}})}listenDeviceChange(){ge&&!ge.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&ge.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return _(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 Xe();t[0]?this.recapture(t[0].deviceId):ge.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return _(this,null,function*(){this.log.warn(`camera added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)})}encodeFrame(e,t){let s=t?8:this.mediaType;return this.pipeline.reduce((o,n)=>n?n(o,s):o,e)}get enableEncodeFrame(){return this.pipeline.some(e=>e)}play(e,t){return _(this,null,function*(){return T(this.mirror)&&!this.isScreen&&this.setMirror("view"),Ie(le.prototype,this,"play").call(this,e,t)})}close(){ge.off("videoInputAdded",this.handleCameraAdded,this),ge.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return _(this,null,function*(){try{yield Ie(le.prototype,this,"recapture").call(this,e)}catch(t){let s=(yield Xe()).find(o=>o.deviceId!==e);if(s)yield Ie(le.prototype,this,"recapture").call(this,s.deviceId);else throw t}})}};var hl=Ms();if(navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:hl,exposeOrigin:!0,permittedOrigins:["*"]})}catch(r){}var Wp=function(r){return _(this,null,function*(){let i=null,e=qp(r);I.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let t=yield navigator.mediaDevices.getDisplayMedia(e);r.systemAudio&&t.getAudioTracks().length===0&&(Sr&&ht<74||Ue||ie)&&I.warn("Your browser not support capture system audio");let s=t.getVideoTracks()[0];if(s){if(r.frameRate)try{yield s.applyConstraints({frameRate:{min:r.frameRate,ideal:r.frameRate},width:r.width,height:r.height})}catch(o){I.warn(`screen applyConstraints failed: ${o}`)}r.captureElement&&(yield Jp(s,r.captureElement))}if(r.audio){let o=jp(r);I.info(`getUserMedia with constraints: ${JSON.stringify(o)}`),i=yield navigator.mediaDevices.getUserMedia(o),t.addTrack(i.getAudioTracks()[0])}return t})};function Jp(r,i){return _(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&W(r.cropTo))try{if(!(((e=r.getCaptureHandle())==null?void 0:e.handle)===hl))return;let s=yield CropTarget.fromElement(i);yield r.cropTo(s)}catch(t){I.warn(`cropTo target failed ${t}`)}})}function jp(r){let i={echoCancellation:r.echoCancellation,autoGainControl:r.autoGainControl,noiseSuppression:r.noiseSuppression,sampleRate:r.sampleRate,channelCount:r.channelCount};return T(r.microphoneId)||(i.deviceId=r.microphoneId),{audio:i,video:!1}}function qp(r){let i={preferCurrentTab:r.preferDisplaySurface==="current-tab"||!!r.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:Ue?{max:r.width}:{ideal:r.width,max:r.width},height:Ue?{max:r.height}:{ideal:r.height,max:r.height},frameRate:r.frameRate,displaySurface:r.preferDisplaySurface||"monitor"};if(i.video=e,r.systemAudio){let{echoCancellation:t=!0,noiseSuppression:s=!1,autoGainControl:o=!1}=r;i.audio={echoCancellation:t,noiseSuppression:s,autoGainControl:o,sampleRate:48e3}}return i}var ml=Wp;var ze=class extends le{constructor(e){super(e,2);u(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600});u(this,"objectFit","contain");u(this,"isScreen",!0);this._log.id=`s-${this._log.id}`}capture(l){return _(this,arguments,function*({systemAudio:e=!1,autoGainControl:t,echoCancellation:s,noiseSuppression:o,audioTrack:n,videoTrack:a,captureElement:c,preferDisplaySurface:d}){try{let p;return a||n?(p=new MediaStream,a&&p.addTrack(a),n&&p.addTrack(n)):p=yield ml({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:t,echoCancellation:s,noiseSuppression:o,captureElement:c,preferDisplaySurface:d}),yield this.setInputMediaStreamTrack(p.getVideoTracks()[0]),p}catch(p){throw this.log.error(`getDisplayMedia error observed ${p}`),p instanceof b?p:new b({code:A.INITIALIZE_FAILED,name:p.name,message:p.message})}})}switchDevice(e){return _(this,null,function*(){throw new Error("Method not implemented.")})}};var Ft=class extends Oe{constructor(i){super(i),this._log.id=`s-${this._log.id}`}};var Xp="registerProcessor('dumper', class extends AudioWorkletProcessor {process(inputs) {this.port.postMessage(inputs);return true;}});",Sc;function pl(r){return _(this,null,function*(){let i=qe("dump");Sc||(Sc=Gi(i,URL.createObjectURL(new Blob([Xp],{type:"application/javascript"})))),yield Sc;let e=new AudioWorkletNode(i,"dumper",{numberOfInputs:r.length,numberOfOutputs:0});return r.forEach((t,s)=>t.connect(e,0,s)),new ReadableStream({start(t){e.port.onmessage=s=>{t.enqueue(s.data)}},cancel(){r.forEach(t=>t.disconnect(e)),e.port.close()}})})}var bn=class extends _n{constructor(e){super();this.room=e;u(this,"_localAudioTrack");u(this,"_localScreenAudioTrack");u(this,"log",I.createLogger({id:"am"}));u(this,"denoiser");e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId))}get _localAudioPipline(){var e;return(e=this._localAudioTrack)==null?void 0:e.pipeline}dump(e){var l,p;if(!this._localAudioTrack)return;let t=[],s=[];(l=this._localAudioPipline)!=null&&l.source.node&&(t.push(this._localAudioPipline.source.node),s.push("mic")),(p=this._localAudioPipline)!=null&&p.denoiser.node&&(t.push(this._localAudioPipline.denoiser.node),s.push("mic-processed")),this.mixWeight>1&&(t.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),s.push("mix")),this.log.info(`dump audio track ${s}, duration: ${e}`);let 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<s.length;m++){let f=URL.createObjectURL(new Blob(n[m])),R=document.createElement("a");R.href=f,R.download=`${s[m]}.pcm`,R.style.display="none",document.body.appendChild(R),R.click(),URL.revokeObjectURL(f),R.remove()}clearTimeout(a),o.abort("download")},d=pl(t).then(m=>m.pipeTo(new WritableStream({write(f){f.forEach((R,C)=>n[C]=n[C]?n[C].concat(R[0]):[R[0]])}}),o).catch(f=>c));return{then:d.then.bind(d),download:c}}get hasScreenAudioTrack(){return this._localScreenAudioTrack!==null}get hasAudioTrack(){return this._localAudioTrack!==null}changeInput(e){if(e instanceof Ft)this._localScreenAudioTrack=e,e.pipeline.connect(),this.mixOnChange();else if(e instanceof Oe)this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),e.pipeline.connect(),this.mixOnChange();else if(e instanceof oi)return e.setOutputMediaStreamTrack(e.mediaTrack)}mixOnChange(){var e,t;(e=this._localAudioTrack)==null||e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),(t=this._localScreenAudioTrack)==null||t.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)}removeInput(e){e instanceof Ft?delete this._localScreenAudioTrack:e instanceof Oe?delete this._localAudioTrack:e instanceof oi}addDenoiser(e){var t;this.denoiser=e,(t=this._localAudioTrack)==null||t.addDenoiser(e)}removeDenoiser(e){var t;delete this.denoiser,(t=this._localAudioTrack)==null||t.removeDenoiser(e)}destroy(){this.close()}};function Nn(r=30,i=2){return J((e,t)=>function(...s){return new Promise((o,n)=>{let a=setTimeout(()=>{let c=new b({code:A.API_CALL_TIMEOUT,message:`checkPendingPromise ${t}() timeout ${r}s`});I.warn(c),i===2?n(c):i===1&&o()},r*1e3);e.apply(this,s).then(o,n).finally(()=>{clearTimeout(a)})})})}var Ic=class extends qi{constructor(e,t,s){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:s,room:e});this.room=e;this.user=t;u(this,"tinyId");u(this,"isRemote",!0);u(this,"jitterBufferDelay",0);u(this,"_decodeCheckTimeoutId",-1);this.tinyId=t.tinyId}setMute(e){this.hasFlag&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.hasFlag&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}waitHasMediaTrack(){return new Promise(e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)})}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===Ic.STATE_SUBSCRIBE}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}updatePlayingState(e){if(this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.hasFlag||!this.outMediaTrack)){this.log.info(`abort play, isSubscribed: ${this.isSubscribed} hasFlag: ${this.hasFlag} hasTrack: ${!!this.outMediaTrack} `);return}super.updatePlayingState(e)}}onFlagChanged(){this.updatePlayingState(this.hasFlag)}onTrackMuted(){this.hasFlag&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackMuted()}onTrackUnmuted(){this.hasFlag&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackUnmuted()}onTrackEnded(){this.hasFlag&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackEnded()}},rt=Ic;u(rt,"STATE_SUBSCRIBE","subscribe"),y([Nn(5,1)],rt.prototype,"waitHasMediaTrack",1),y([ue(F.INIT,rt.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),g.emit(E.REMOTE_TRACK_SUBSCRIBED,{track:this}),this.updatePlayingState(!0),this._decodeCheckTimeoutId=setTimeout(()=>{if(this.isSubscribed&&this.isPlayCalled&&this.stat.bytesReceived>0){let r=this.player.isPlaying||(this.kind===h.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0);D[r?"addSuccessEvent":"addFailedEvent"]({key:this.kind===h.AUDIO?504700:514702}),r||this._log.warn(`decode failed: isPlaying: ${this.player.isPlaying} ${this.kind===h.AUDIO?`audioLevel: ${this.getAudioLevel()}`:`framesDecoded: ${this.stat.framesDecoded>0}`} )`)}},5e3)},ignoreError:!0})],rt.prototype,"subscribe",1),y([ue(rt.STATE_SUBSCRIBE,F.INIT,{sync:!0,success(){this.log.info("unsubscribed"),this.updatePlayingState(!1),g.emit(E.REMOTE_TRACK_UNSUBSCRIBED,{track:this}),clearTimeout(this._decodeCheckTimeoutId)}})],rt.prototype,"unsubscribe",1);var oi=class extends rt{constructor(e,t){super(e,t,1);u(this,"volume",0);u(this,"mediaType",1);u(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0});u(this,"audioDecoder");this.manager=e.audioManager}onPlayerError(e){if(this.enableDecodeFrame){this.room.enableInsertableStreams();let t=new AudioDecoder({error:s=>this._log.error(s),output:s=>{this.player.write(s)}});t.configure({codec:"opus",sampleRate:48e3,numberOfChannels:1}),this._log.info(`audioDecoder state:${t.state}`),this.audioDecoder=t}}get enableDecodeFrame(){var e,t;return((t=(e=this.player.element)==null?void 0:e.error)==null?void 0:t.code)===MediaError.MEDIA_ERR_DECODE&&Fi&&nn().AudioDecoder}decodeFrame(e){var t;return((t=this.audioDecoder)==null?void 0:t.state)==="configured"&&this.audioDecoder.decode(new EncodedAudioChunk({data:e.data,timestamp:e.timestamp,type:"key"})),e}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get hasFlag(){return this.user.muteState.hasAudio}isFlagChanged(e){let t=e.hasAudio&&!e.audioMuted;return this.hasFlag||(this.volume=0),this.hasFlag!==t}};var zp=[-1,-1,1,-1,-1,1,1,1],Yp=[0,0,1,0,0,1,1,1],Ye=class extends F{constructor(e,t){super();this.context=e;u(this,"name");u(this,"input");u(this,"output");u(this,"texture");u(this,"ctx2d",null);u(this,"fbo");u(this,"width",0);u(this,"height",0);u(this,"x",0);u(this,"y",0);u(this,"program");u(this,"vertexShader");u(this,"fragmentShader");u(this,"totalFrames",0);u(this,"dropFrames",0);u(this,"matchInputSize",!0);u(this,"texCoordBuffer");u(this,"positionBuffer");u(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0});u(this,"cost",0);u(this,"_canvas",null);u(this,"_image");if(this.context.on("disconnect",this.close,this),this.name=t.name,this.matchInputSize=t.matchInputSize!==!1,this.width=t.width||e.width,this.height=t.height||e.height,this._image=t.image,e instanceof Fe){if(e.ctx&&t.create2d){let s=document.createElement("canvas"),o=typeof s.transferControlToOffscreen=="function"?s.transferControlToOffscreen():s;o.width=this.width,o.height=this.height,this.ctx2d=o.getContext("2d"),this._image=o,this._canvas=o}return}try{let s=e.ctx;this.texCoordBuffer=this.createBuffer(Yp),this.positionBuffer=this.createBuffer(zp),t.createTexture!==!1&&(this.texture=s.createTexture(),this.useTexture(),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),s.pixelStorei(s.PACK_ALIGNMENT,1),s.pixelStorei(s.UNPACK_ALIGNMENT,1)),t.useFbo&&(this.fbo=s.createFramebuffer(),this.useBufferFrame(),this.useTexture(),s.texImage2D(s.TEXTURE_2D,0,s.RGBA,this.width,this.height,0,s.RGBA,s.UNSIGNED_BYTE,null),s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,this.texture,0)),t.useDefaultProgram?this.program=e.defaultProgam:(t.vertexShaderSource||t.fragmentShaderSource)&&(this.vertexShader=t.vertexShaderSource?e.createShader(s.VERTEX_SHADER,t.vertexShaderSource):e.defaultVShader,this.fragmentShader=t.fragmentShaderSource?e.createShader(s.FRAGMENT_SHADER,t.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(s){this.context.destroy(s)}}get image(){return this._image}set image(e){this._image=e}createFramebuffer(e){let t=this.context.ctx,s=t.createFramebuffer();return t.bindFramebuffer(t.FRAMEBUFFER,s),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0),s}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 ye&&this.render(e)||this.context instanceof Fe&&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}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 ye){let s=this.context.ctx;s.deleteBuffer(this.texCoordBuffer),s.deleteBuffer(this.positionBuffer),this.fbo&&s.deleteFramebuffer(this.fbo),this.texture&&s.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&s.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&s.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&s.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((s,o)=>{s&&(t.activeTexture(t.TEXTURE0+o),t.bindTexture(t.TEXTURE_2D,s))})}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,s=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,s),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW),s}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 s=this.context.ctx;s.bindBuffer(s.ARRAY_BUFFER,e),s.bufferData(s.ARRAY_BUFFER,new Float32Array(t),s.STATIC_DRAW)}setAttributes(...e){let t=this.context.ctx;e.forEach((s,o)=>{t.enableVertexAttribArray(o),t.bindBuffer(t.ARRAY_BUFFER,s),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 s=this.context.ctx;s.texImage2D(s.TEXTURE_2D,0,s.RGBA,e,t,0,s.RGBA,s.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 s=this.context.ctx;s.drawArrays(s.TRIANGLE_STRIP,0,4)}draw2d(e,t,s,o,n){return this.ctx2d&&e?(e instanceof ImageData?this.ctx2d.putImageData(e,t,s):this.ctx2d.drawImage(e,t,s,o,n),!0):!1}getInfo(){var p;let{totalFrames:e,x:t,y:s,width:o,height:n,name:a,cost:c}=this,d=Date.now(),l=(e-this.lastInfo.totalFrames)/((d-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:s,width:o,height:n,timestamp:d,fps:l,name:a,cost:c},N({parent:(p=this.input)==null?void 0:p.getInfo()},this.lastInfo)}createTexture(e){let t=this.context.ctx,s=t.createTexture();return this.useTextures(s),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),s}};y([ue(F.INIT,"connected",{sync:!0})],Ye.prototype,"connect",1),y([ue("connected",F.INIT,{ignoreError:!0,sync:!0})],Ye.prototype,"disconnect",1),y([ue([],"closed",{sync:!0})],Ye.prototype,"close",1);var Kp=[0,1,1,1,0,0,1,0],Qs=class extends Ye{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t));u(this,"_intervalId",0);u(this,"_sequence",0);u(this,"checkGLError",!1);e instanceof Fe?this.ctx2d=e.ctx:e.available&&(t==null?void 0:t.mirrorUpAndDown)&&this.setTexBuffer(Kp)}start(e){this._intervalId=re.run("intervalInWorker",()=>{if(e!==this.context.frameRate&&(re.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof ye){let s=this.context.ctx.getError();s&&this.context.destroy(new Error(`${this.name} req ${this._sequence} render ${this.totalFrames} faild ${s}`))}},{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)}removeInput(e){super.removeInput(e),re.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}},Pr=class extends Qs{constructor(e,t){super(e,t);u(this,"_videoTrack");u(this,"_canvasContainer");Number(gi)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e._canvas.captureStream().getVideoTracks();let s=o=>{var c;let n=()=>{var d;return(d=this._videoTrack)==null?void 0:d.removeEventListener(o,a)},a=()=>{n(),this.context.destroy(new Error(`video track ${o}`))};this.once("closed",n),(c=this._videoTrack)==null||c.addEventListener(o,a)};e instanceof ye&&s("mute"),s("ended")}get videoTrack(){return this._videoTrack}putCanvasIntoDom(){!this.context._canvas||!this._canvasContainer||document.getElementById(this.context._canvas.id)||(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()}},vn=class extends Pr{render(i){var e;return!!((e=this.input)!=null&&e.requestFrame(i))}};var Dn=class extends Pr{constructor(e,t){super(e,{name:"smallDestination"});this.resolution=t}resize(e,t){let s,o=e*t,n=this.resolution.width*this.resolution.height;I.info(`big res: ${e}*${t} small res: ${this.resolution.width}*${this.resolution.height} `),o>n?s=o/n:(I.warn(`Small stream resolution is not smaller than big stream, which is invalid. big: ${e} * ${t} small: ${this.resolution.width} * ${this.resolution.height}`),s=o/(160*120)),super.resize(e/Math.sqrt(s),t/Math.sqrt(s))}};var zs=class extends Ye{constructor(e,t){super(e,N({name:"imageSource"},t));u(this,"_lastImage");u(this,"_totalFrames",0);u(this,"_autoResize",!1);this._autoResize=(t==null?void 0:t.autoResize)!==!1}_render(e,t){var n,a;let{width:s,height:o}=this;if(this.image instanceof HTMLVideoElement){if(W(this.image.getVideoPlaybackQuality)&&Pe){let d=this.image.getVideoPlaybackQuality().totalVideoFrames;if(((a=(n=this.image.srcObject)==null?void 0:n.getVideoTracks()[0])==null?void 0:a.muted)===!0||this._totalFrames===d)return!1;this._totalFrames=d,this.dropFrames=this._totalFrames-this.totalFrames}if({videoWidth:s,videoHeight:o}=this.image,!s||!o)return!1;this.image.width=s,this.image.height=o}else if(this.image instanceof HTMLImageElement||this.image instanceof ImageData||this.image instanceof ImageBitmap){if({width:s,height:o}=this.image,this.image!==this._lastImage)this._lastImage=this.image;else if(s===this.width&&o===this.height)return!1}else(this.image instanceof HTMLCanvasElement||this.image instanceof OffscreenCanvas)&&({width:s,height:o}=this.image,this._lastImage=this.image);if(!this._autoResize)return!0;if(this.width===s&&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,this.image)}}else{if(t){this.useTexture();let c=this.context.ctx;c.texImage2D(c.TEXTURE_2D,0,c.RGBA,c.RGBA,c.UNSIGNED_BYTE,this.image)}this.resize(s,o)}return!0}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},Ys=class extends zs{constructor(e,t,s){super(e,s);this._player=t;this.name="videoPlayerSource"}get image(){return this._player.element}},wr=class extends Ys{constructor(i,e,t){super(i,new je({id:t.name,track:e,muted:!0,container:null,objectFit:"contain",log:t.logger}),t),this.name="videoTrackSource",this._player.play()}get image(){return this._player.element}replaceTrack(i){this._player.setTrack(i),this._player.play()}close(){super.close(),this._player.stop()}};var Zp=`
44
44
  // \u9876\u70B9\u7740\u8272\u5668
45
45
  attribute vec4 a_position;
46
46
  attribute vec2 a_texCoord;
@@ -62,7 +62,7 @@ void main() {
62
62
  `)))}else{if(e instanceof zi)return e;o=new zi({code:w.UNKNOWN_ERROR,fnName:t,originError:e})}return o}};function p_(r){let i;switch(r){case"NotFoundError":i=5301;break;case"NotAllowedError":i=5302;break;case"NotReadableError":i=5303;break;case"OverconstrainedError":i=5304;break;case"InvalidStateError":i=5305;break;case"SecurityError":i=5306;break;case"AbortError":i=5307;break;default:i=5300}return i}var k=zi;var Rl={type:"object",properties:{cameraId:{type:"string"},useFrontCamera:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:["string","boolean"],values:[!0,!1,"view","publish","both"]},small:{properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack}}},yl={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}}},Fr={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(r,i,e){if(Y(r)&&!document.getElementById(r))throw new k({code:w.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:i}})}},bl={name:"userId",required:!0,type:"string"},Nl={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[st.AUDIO_PROFILE_STANDARD,st.AUDIO_PROFILE_STANDARD_STEREO,st.AUDIO_PROFILE_HIGH,st.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function eo(r,i){if(!r)throw new k({code:w.INVALID_OPERATION,extraCode:5101,fnName:i})}function vl(r,i,e){if(!r)throw new k({code:w.INVALID_OPERATION,extraCode:5102,fnName:i,messageParams:{value:e}})}var qy={type:"number",notLessThanZero:!0},__={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(r,i,e){if(this._room.isJoined)throw new k({code:w.INVALID_OPERATION,extraCode:5104,fnName:e});if(r.roomId){if(Y(r.roomId))throw new k({code:w.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:i}});if(!(/^[1-9]\d*$/.test(String(r.roomId))&&r.roomId<4294967295))throw new k({code:w.INVALID_PARAMETER,extraCode:5013,fnName:e,messageParams:{key:i}})}else if(r.strRoomId){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(r.strRoomId))throw new k({code:w.INVALID_PARAMETER,extraCode:5012,fnName:e,messageParams:{key:i}})}else throw new k({code:w.INVALID_PARAMETER,extraCode:5015,fnName:e})},properties:{sdkAppId:{required:!0,type:"number",allowEmpty:!1},userId:{required:!0,type:"string",allowEmpty:!1},userSig:{required:!0,type:"string",allowEmpty:!1},scene:{type:"string",values:["live","rtc"]},role:{type:"string",values:["audience","anchor"]},roomId:{type:["string","number"]},strRoomId:{type:"string"},proxy:{type:["object","string"],properties:{websocketProxy:{type:"string"},turnServer:{type:["object","array"],properties:{url:{required:!0,type:"string"},username:{type:"string"},credential:{type:"string"},credentialType:{type:"string",values:["password"]}}},loggerProxy:{type:"string"},webtransportProxy:{type:"string"}}},enableAutoPlayDialog:{type:"boolean"},userDefineRecordId:{type:"string"},latencyLevel:{type:"number"}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:Fr,mute:{type:["boolean","string"]},publish:{type:"boolean"},option:Rl},validate(r){var i;if(!((i=r==null?void 0:r.option)!=null&&i.videoTrack)&&ii())throw new k({code:w.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:P(N({},Fr),{required:!1}),publish:{type:"boolean"},mute:{type:["boolean","string"]},option:Rl}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:Nl},validate(r){var i;if(!((i=r==null?void 0:r.option)!=null&&i.audioTrack)&&ii())throw new k({code:w.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:Nl}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:Fr,publish:{type:"boolean"},option:yl},validate(r,i,e,t,s){var o;if(!((o=r==null?void 0:r.option)!=null&&o.videoTrack)&&ii())throw new k({code:w.ENV_NOT_SUPPORTED,extraCode:5201});if(!Ls())throw new k({code:w.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:Fr,publish:{type:"boolean"},option:yl}},muteRemoteAudio:[bl,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[bl,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:Fr,userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(r,i,e){eo(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(r.userId);if(vl(!!t,e,r),t&&(r.streamType==="main"&&!t.muteState.videoAvailable||r.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new k({code:w.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:r}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:P(N({},Fr),{required:!1}),userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(r,i,e){eo(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(r.userId);if(vl(!!t,e,r),t&&(r.streamType==="main"&&!t.muteState.videoAvailable||r.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new k({code:w.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:r}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(r,i,e){if(r.userId!=="*"&&T(r.streamType))throw new k({code:w.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(r,i,e){eo(this._room.isJoining||this._room.isJoined,e)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(r,i,e,t){if(!Fi)throw new k({code:w.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new k({code:w.INVALID_OPERATION,fnName:e,extraCode:5108});if(r.byteLength>1e3)throw new k({code:w.INVALID_PARAMETER,extraCode:5018,fnName:e});if(r.byteLength===0)throw new k({code:w.INVALID_PARAMETER,extraCode:5017,messageParams:{key:i},fnName:e});eo(this._room.isJoined,e)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(r,i,e){if(!r&&!this._room.isMainStreamPublished||r&&!this._room.isAuxStreamPublished)throw new k({code:w.INVALID_OPERATION,extraCode:5109,messageParams:{key:i},fnName:e})}}}}],sendCustomMessage:{name:"message",required:!0,type:"object",properties:{cmdId:{type:"number",required:!0,min:1,max:10},data:{instanceOf:ArrayBuffer,required:!0,validate(r,i,e,t){if(r.byteLength>1e3)throw new k({code:w.INVALID_PARAMETER,extraCode:5018,fnName:e});if(r.byteLength===0)throw new k({code:w.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:i}})}}},validate(r,i,e){if(eo(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new k({code:w.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:i}})}}},Ce={TRTC:__};var Me=class extends Error{};function f_(r,i){let e=yr(r);for(let t=0;t<i.length;t++)Kt(e[t],i[t]);return e}function E_(r){this._resolve=Promise.resolve(r)}function g_(r){this._reject=Promise.reject(r)}var Yi=class{constructor(i,e){this.instance=i;this.group=e;this.started=!1;this.ops=[];this.startSame=()=>!0;this.mergeUpdate=f_;let t=Yi.instances.get(i);t?t.set(e,this):Yi.instances.set(i,new Map([[e,this]]))}static get(i,e){if(!e)return;let t=Yi.instances.get(i);return t&&t.get(e)||new Yi(i,e)}static gets(i,e){let t=Yi.instances.get(i),s=[];return t&&t.forEach((o,n)=>{e.test(n)&&s.push(o)}),s}action(i,e,t){let s=a=>{var c;return i===0?this.started=!0:i===3&&(this.started=!1),this.ops.shift(),(c=this.currentOp)==null||c.action(),a},o=a=>{var c,d;throw this.ops.shift(),i===0&&((c=this.currentOp)==null?void 0:c.type)===2&&this.ops.shift().reject(new Me("start failed")),(d=this.currentOp)==null||d.action(),a},n={type:i,action:()=>e(...n.args).then(s,o),args:t,resolve:E_,reject:g_};try{switch(this.state){case 1:if(i===0)throw new Me("already started");break;case 4:if(i===2)throw new Me("not started");break;default:return this.cacheOp(n)}}catch(a){return Promise.reject(a)}return this.ops.push(n),n.promise=e(...n.args).then(s,o)}cacheOp(i){if(this.ops.length===1)switch(this.state){case 0:case 2:if(i.type===0)throw new Me("already start");break;case 3:switch(i.type){case 2:throw new Me("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new Me("unknown state")}else switch(i.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let t=new Me("keep stop");if(this.ops.slice(1).forEach(s=>s.reject(t)),this.ops=this.ops.slice(0,1),this.state===3)return this.currentOp.promise}break;case 2:switch(this.lastOpType){case 2:return this.lastOp.args=this.mergeUpdate(this.lastOp.args,i.args),this.lastOp.promise;case 3:throw new Me("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new Me("start not allowed after update");case 0:throw new Me("duplicate start");case 3:if(this.startSame(this.currentOp.args,i.args))throw this.ops.pop().reject(new Me("keep start")),new Me("already start")}}i.promise=new Promise((t,s)=>{i._resolve?i._resolve.then(t):i.resolve=t,i._reject?i._reject.catch(s):i.reject=s});let{action:e}=i;return i.action=()=>e().then(i.resolve,i.reject),this.ops.push(i),i.promise}get lastOp(){return this.ops[this.ops.length-1]}get lastOpType(){return this.lastOp.type}get currentOp(){return this.ops[0]}get state(){return this.currentOp?this.currentOp.type:this.started?1:4}},Ht=Yi;Ht.instances=new WeakMap;var Fn=new WeakMap,Hn=(r,i)=>{if(i instanceof Me){let{stack:e}=i;i=new k({code:w.OPERATION_ABORT,message:`${r} abort: ${i.message}`,fnName:r}),e&&(i.stack+=e.substr(e.indexOf(`
63
63
  `)))}throw i};function Di(r,i){return J((e,t)=>function(...s){let o=Ht.get(this,typeof r=="string"?r:r.call(this,...s));return o?(i&&(o.startSame=i.bind(this)),o.action(0,e.bind(this),s).catch(Hn.bind(null,t))):e.apply(this,s)})}function Ki(r,i){let{merge:e,debounce:t}=i||{};return J((s,o)=>function(...n){let a=Ht.get(this,typeof r=="string"?r:r.call(this,...n));if(!a)return s.apply(this,n);if(e&&(a.mergeUpdate=e.bind(this)),t&&t.isNeedToDebounce.apply(this,n)){let{delay:c,getKey:d}=t;return new Promise((l,p)=>{var R,C;let m=(R=Fn.get(this))==null?void 0:R.get(d(...n));if(m){let{timeoutId:v,resolve:U}=m;clearTimeout(v),U()}let f=setTimeout(()=>{if(a.state===3||a.state===4)return l();a.action(2,s.bind(this),n).catch(Hn.bind(null,o)).then(l,p)},c);Fn.has(this)?(C=Fn.get(this))==null||C.set(d(...n),{timeoutId:f,resolve:l}):Fn.set(this,new Map([[d(...n),{timeoutId:f,resolve:l}]]))})}return a.action(2,s.bind(this),n).catch(Hn.bind(null,o))})}function Oi(r){return J((i,e)=>function(...t){let s=typeof r=="function"?r.call(this,...t):r;if(s instanceof RegExp)return Promise.all(Ht.gets(this,s).map(n=>n.action(3,()=>Promise.resolve(),t))).then(()=>i.call(this,...t));let o=Ht.get(this,s);return o?o.action(3,i.bind(this),t).catch(Hn.bind(null,e)):i.apply(this,t)})}var $={ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",KICKED_OUT:"kicked-out",REMOTE_USER_ENTER:"remote-user-enter",REMOTE_USER_EXIT:"remote-user-exit",REMOTE_AUDIO_AVAILABLE:"remote-audio-available",REMOTE_AUDIO_UNAVAILABLE:"remote-audio-unavailable",REMOTE_VIDEO_AVAILABLE:"remote-video-available",REMOTE_VIDEO_UNAVAILABLE:"remote-video-unavailable",AUDIO_VOLUME:"audio-volume",NETWORK_QUALITY:"network-quality",CONNECTION_STATE_CHANGED:"connection-state-changed",AUDIO_PLAY_STATE_CHANGED:"audio-play-state-changed",VIDEO_PLAY_STATE_CHANGED:"video-play-state-changed",SCREEN_SHARE_STOPPED:"screen-share-stopped",DEVICE_CHANGED:"device-changed",PUBLISH_STATE_CHANGED:"publish-state-changed",TRACK:"track",STATISTICS:"statistics",SEI_MESSAGE:"sei-message",CUSTOM_MESSAGE:"custom-message"};function Zi(r){return r==="sub"?"auxiliary":r==="auxiliary"?"sub":"main"}function er(r){return r===st.QOS_PREFERENCE_CLEAR?"detail":r===st.QOS_PREFERENCE_SMOOTH?"motion":""}var T_=r=>r.startsWith("data:application/octet-stream;base64,"),S_=r=>r.startsWith("file://"),Gn=class{constructor(){u(this,"_log");this._log=I.createLogger({id:"fd"})}download(i,e){return _(this,null,function*(){let{type:t="blob"}=e||{};try{let s=x(),o;if(W(fetch)?o=yield this.downloadWithFetch(i,t):o=yield this.downloadWithXHR(i,t),!o||!o.data)throw new Error("data is empty");let n=x()-s;return this._log.info(`downloaded: ${i}, return type: ${t}, cost: ${n}ms`),D.addSuccessEvent({key:522700,cost:x()-s}),o.data}catch(s){throw this._log.error(`failed to download: ${i}, error: ${s}`),D.addFailedEvent({key:522700,error:s}),s}})}downloadWithFetch(i,e){return _(this,null,function*(){this._log.info(`download with fetch: ${i}, return type: ${e}`);try{let t=yield fetch(i);if(!t.ok)throw new Error("network response was not ok");let s;return e==="arraybuffer"?s=yield t.arrayBuffer():s=yield t.blob(),{data:s}}catch(t){throw t}})}downloadWithXHR(i,e){return this._log.info(`download with xhr: ${i}, return type: ${e}`),new Promise((t,s)=>{let o=new XMLHttpRequest;o.open("GET",i,!0),o.responseType=e,o.onload=()=>{o.status===200||o.status===0&&o.response?t({data:o.response}):s(new Error("XHR failed"))},o.onerror=s,o.send(null)})}loadWasm(i,e){return _(this,null,function*(){this._log.info(`loadWasm ${i}, importObject: ${JSON.stringify(e)}`);let t=x(),s=null,o=null;if(W(WebAssembly.instantiateStreaming)&&!T_(i)&&!S_(i)&&W(fetch))try{let n=fetch(i);s=(yield WebAssembly.instantiateStreaming(n,e)).instance}catch(n){o=n}if(!s)try{let n=yield this.download(i,{type:"arraybuffer"});s=(yield WebAssembly.instantiate(n,e)).instance}catch(n){o=n}if(s){let n=x()-t;return this._log.info(`loadedWasm ${i}, cost: ${n}ms`),D.addSuccessEvent({key:522701,cost:n}),s}throw this._log.error(`failed to loadWasm ${i}, error: ${o}`),D.addFailedEvent({key:522701,error:o}),o})}};y([it({settings:{timeout:0,retries:3},onRetrying(r){this._log.warn(`download retrying: ${r}`)}})],Gn.prototype,"download",1);var Dl=new Gn;function Ol({TRTC:r,room:i,errorModule:e,assetsPath:t}){return{TRTC:r,room:i,assetsPath:t,fileDownloader:Dl,innerEmitter:g,constants:Ra,environment:Ar,utils:we,eventLogger:Z,log:this.room.getLogger(),loggerManager:I,errorModule:e,kvStatManager:D,rtcDectection:ft,trtc:this,clearStarted:(s,o)=>{let n=s.getAlias(),a=Ht.instances.get(this);if(!!a)if(o){let c=a.get(n+o);if(!c)return;c.started=!1}else a.forEach((c,d)=>{d.startsWith(n)&&(c.started=!1)})}}}var Ml=(r,i)=>{let{emit:e}=r;return r.emit=(...t)=>{try{return e.apply(r,t)}catch(s){let o=L({key:M.CATCH_HANDLER_ERROR,data:{name:i,event:t[0]},addDocLink:!1});return I.warn(`${o}
64
64
 
65
- ${s.stack}`),!1}},r};var Wn=new WeakMap;function kl(r,i){return J((e,t)=>function(...s){var a,c;let o=(a=Wn.get(this))==null?void 0:a.get(i(...s));o&&o>0&&clearTimeout(o);let n=window.setTimeout(()=>{e.apply(this,s)},r);Wn.has(this)?(c=Wn.get(this))==null||c.set(i(...s),n):Wn.set(this,new Map([[i(...s),n]]))})}var Ll="5.8.1";function ke(...r){return J((i,e)=>function(...t){try{jn.call(this,r,t,e,this._name)}catch(s){return Promise.reject(s)}return i.apply(this,t)})}function dd(...r){return J((i,e)=>function(...t){try{jn.call(this,r,t,e,this._name)}catch(s){throw s}return i.apply(this,t)})}function jn(r,i,e,t){if(he(r))for(let s=0;s<r.length;s++)Jn.call(this,{rule:r[s],value:i[s],key:r[s].name,fnName:e,className:t});else Jn.call(this,{rule:r,value:i[0],key:r.name,fnName:e,className:t})}function Jn({rule:r,value:i,key:e,fnName:t,className:s}){function o(c){return{code:w.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:r,value:i}}}if(T(i)){if(r.required)throw new k(o(5001));if(T(r.defaultValue)){W(r.validate)&&r.validate.call(this,i,e,t,s,this);return}i=r.defaultValue}if(Array.isArray(r.type)){let c=!1;for(let d=0;d<r.type.length;d++)r.type[d]===null&&i===null&&(c=!0),W(r.type[d])&&i instanceof r.type[d]&&(c=!0),Y(r.type[d])&&fe(i)===r.type[d].toLowerCase()&&(c=!0);if(!c)throw new k({code:w.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:r.type.map(d=>Ns(d)?zo(d):Y(d)?d:fe(d))},value:i}})}else if(!T(r.type)&&fe(i)!==r.type)throw new k(o(5002));if(r.allowEmpty===!1){let c=ee(i)&&(i===0||Number.isNaN(i)),d=Y(i)&&i.trim()==="";if(c||d)throw new k(o(5003))}if(r.notLessThanZero&&ee(i)&&i<0)throw new k(o(5006));if(!T(r.min)&&ee(i)&&i<r.min)throw new k(o(5007));if(!T(r.max)&&ee(i)&&i>r.max)throw new k(o(5008));if(Y(r.instanceOf)){if(!i||i._name!==r.instanceOf)throw new k(o(5004))}else if(W(r.instanceOf)&&!(i instanceof r.instanceOf))throw new k(o(5004));if(Array.isArray(r.values)&&!r.values.includes(i))throw new k(o(5005));let{properties:n}=r;Je(n)&&mt(i)&&Object.keys(n).forEach(c=>{Jn.call(this,{rule:n[c],value:i&&i[c],key:`${c}`,fnName:t,className:s})});let{arrayItem:a}=r;Je(a)&&he(i)&&i.forEach((c,d)=>{Jn.call(this,{rule:a,value:c,key:`${e}[${d}]`,fnName:t,className:s})}),W(r.validate)&&r.validate.call(this,i,e,t,s,this)}function oe(r={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t}=r;return J((s,o)=>function(...n){function a(l,p,m){if(m&&m.includes(l))return"hided";if(e){let f=e(...n);if(n[f.argIndex]===p)return f.value}if(p===n||l in n)return p;try{return p instanceof HTMLElement?`id: ${p.id} type:${fe(p)}`:(JSON.stringify(p),p)}catch(f){return`type:${fe(p)}`}}let c=this._log||I;n.length>0?c.info(`${o}() ${JSON.stringify(n,(l,p)=>a(l,p,["userSig","privateMapKey"]))}`):c.info(`${o}()`);let d=t?t(...n):un[o];try{let l=s.apply(this,n),p=x();return bs(l)?l.then(m=>(c.info(`${o}() success ${i.call(this,...n)}`),D.addSuccessEvent({key:d,cost:x()-p}),m)).catch(m=>{throw m=k.convertFrom.call(this,m,o,n.length===1?n[0]:n),c.error(`${o}() failed ${i.call(this,...n)} ${m} params: ${JSON.stringify(n,a)}`),D.addFailedEvent({key:d,error:m}),m}):(D.addSuccessEvent({key:d}),l)}catch(l){throw l=k.convertFrom.call(this,l,o),c.error(`${o}() failed ${l} params: ${JSON.stringify(n,a)}`),D.addFailedEvent({key:d,error:l}),l}})}var qn=r=>J((i,e)=>function(t,s){return _(this,null,function*(){let o=this._plugins.get(t);if(!o)throw this._log.error(`plugin ${String(t)} is not found`),new k({code:w.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});if(W(o.constructor.isSupported)&&!o.constructor.isSupported())throw this._log.error(`plugin ${String(t)} is not supported`),new k({code:w.ENV_NOT_SUPPORTED,message:`plugin ${String(t)} is not supported`,extraCode:5210,fnName:e});return jn.call(this,o.getValidateRule(r),[s],e,"TRTC"),i.call(this,o,s)})});var Xn=0,ud=class{constructor(i,e){u(this,"player");u(this,"publisher");u(this,"mixInput");this.mixInput=new kr(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 Hr(r,i){if(i&&typeof i!="function")throw new k({code:w.INVALID_PARAMETER,message:`start audioMixer plugin: param ${r} should be a function.`})}var Gr=class{constructor(i){this.core=i;u(this,"log");u(this,"mixedMusicMap",new Map);u(this,"cacheMusicMap",new Map);Xn=Xn+1,this.log=i.log.createChild({id:`${this.getAlias()}${Xn}`}),this.log.info(`[audioMixer] created id=${this.getAlias()}${Xn}`),this.core=i}getName(){return Gr.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return Gr.startValidateRule;case"update":return Gr.updateValidateRule;case"stop":return Gr.stopValidateRule}}start(i){return _(this,null,function*(){let{room:e}=this.core;this.log.info(`add music source, id: ${i.id} url: ${i.url}, track: ${i.track}`);let{id:t,url:s}=i;if(this.mixedMusicMap.has(t))return;let o=this.cacheMusicMap.get(t);o?i.url?o.reset():(o.mixInput.replaceSource(i.track),o.mixInput.connect()):(o=new ud(i,e.audioManager),this.cacheMusicMap.set(t,o)),o.updateListener(i),o.updateSettings(i),yield o.play(),this.mixedMusicMap.set(t,o),this.log.info(`start mix audio track ${t} success.`),D.addEnum({key:502700,value:3}),this.kvUpload(i)})}update(i){return _(this,null,function*(){let{id:e,operation:t,seekFrom:s,playbackRate:o}=i;this.log.info(`update music source, ${JSON.stringify(i)}`);let n=this.mixedMusicMap.get(e);if(!n){this.log.warn(`update music source failed, music id: ${e} not found.`);return}n.updateSettings(i),n.updateListener(i),T(t)||n.setOperation(t),T(s)||n.seek(s),this.kvUpload(i)})}stop(e){return _(this,arguments,function*({id:i}){var t;this.mixedMusicMap.has(i)&&(this.log.info(`remove music source, music id: ${i}`),(t=this.mixedMusicMap.get(i))==null||t.stop(),this.mixedMusicMap.delete(i)),i==="*"&&this.destroyAllMusic()})}kvUpload(i){let{track:e,loop:t,volume:s,playbackRate:o,operation:n,seekFrom:a,onTimeUpdate:c,onDurationChange:d,onEnded:l}=i;e&&D.addCount({key:502711}),t&&D.addCount({key:502703}),s&&D.addCount({key:502704}),o&&D.addCount({key:502705}),n&&D.addCount({key:502706}),a&&D.addCount({key:502707}),typeof c!="function"&&D.addCount({key:502709}),typeof l!="function"&&D.addCount({key:502710}),typeof d!="function"&&D.addCount({key:502708})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((i,e)=>this.stop({id:e}))}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}},Mi=Gr;u(Mi,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(i,e,t){if(i.url&&i.url!=="*"){let s=i.url.split("?")[0],o=["mp3","ogg","wav","flac"],n=s.split(".").pop(),a=o.indexOf(n)>=0,c=s.startsWith("blob"),d=s.startsWith("data");if(!(a||c||d))throw new k({code:w.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new k({code:w.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});Hr("onTimeUpdate",i.onTimeUpdate),Hr("onEnded",i.onEnded),Hr("onDurationChange",i.onDurationChange)}}),u(Mi,"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){Hr("onTimeUpdate",i.onTimeUpdate),Hr("onEnded",i.onEnded),Hr("onDurationChange",i.onDurationChange)}}),u(Mi,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),u(Mi,"Name","AudioMixer");var A_=r=>(r=Number(r),r>0&&r<14e8),Qn=0,ld,Wr=class{constructor(i){this.core=i;u(this,"log");u(this,"audioContext",qe("denoiser"));u(this,"workletNode");Qn=Qn+1,this.log=i.log.createChild({id:`${this.getAlias()}${Qn}`}),this.log.info(`[audioDenoiser] created id=${this.getAlias()}${Qn}`),i.assetsPath&&this.preload(`${i.assetsPath}/denoiser-wasm.js`)}static startValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,t,s,o){if(!i.room.audioManager.hasAudioTrack)throw new k({code:w.INVALID_OPERATION,extraCode:5106,fnName:s})}}}preload(i){return ld||(ld=this.doPreload(i)),ld}doPreload(i){return _(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield Gi(this.audioContext,t)}finally{URL.revokeObjectURL(t)}})}getName(){return Wr.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(i){switch(i){case"start":return Wr.startValidateRule(this.core);case"update":return Wr.updateValidateRule;case"stop":return Wr.stopValidateRule}}start(i){return _(this,null,function*(){let{room:e}=this.core;if(yield this.preload(`${i.assetsPath}/denoiser-wasm.js`),!this.workletNode){let t=String(Date.now()).slice(0,-3),{auth:s,sign:o,status:n,message:a}=yield R_(P(N({},i),{timestamp:t}));if(!s)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${s}. Message: ${a}`),new k({code:w.INVALID_PARAMETER,message:a});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(i.sdkAppId),userId:i.userId,timestamp:t,sign:o,status:n}}),this.workletNode.port.onmessage=c=>{let{data:d}=c;d.type==="cost"&&this.log.debug(`[RTCAIDenoiser] ${d.value}`)}}this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(){return _(this,null,function*(){})}stop(){return _(this,null,function*(){if(!this.workletNode)return;let{room:i}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield i.audioManager.removeDenoiser(this.workletNode)})}destroy(){}},tr=Wr;u(tr,"updateValidateRule",{type:"object"}),u(tr,"stopValidateRule",{type:"object"}),u(tr,"Name","AIDenoiser");var xl={MAIN:"schedule.cloud-rtc.com",MAIN_OVERSEA:"schedule.rtc.tencentcloud.com"};function C_(r){let i;return A_(r)?i=xl.MAIN_OVERSEA:i=xl.MAIN,i}function R_(s){return _(this,arguments,function*({sdkAppId:r,userId:i,userSig:e,timestamp:t}){let n=`https://${C_(r)}/api/v1/audioAiAuth?sdkAppId=${r}&userId=${i}&userSig=${e}&timestamp=${t}`,a=yield fetch(n),{data:{errCode:c,errMsg:d,sign:l,status:p}}=yield a.json();if(p==="1")return{auth:!0,sign:l,status:p,message:d};let m="Init RTCAIDenoiser failed.",f="";switch(c){case 1:f="Please check your params.";break;case 2:f="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:f="Server is invalid. Please contact our engineer. ";break;case 4:f="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:f="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:f="Your version is not supported.";break}return{auth:!1,status:p,message:d?`${m} Reason: ${d}. ${f}`:`${m}, ${f}`}})}var Pl=Se(Ne(),1);var hd=class extends Pl.EventEmitter{constructor(){super();this.state="nominal";this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return _(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!pe&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){Z.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let t=this.stateNum,s=e[e.length-1];this.state=s.state,(this.stateNum>3||t>3)&&I.info(`${s.source}: ${s.state}`),this.emit("state-changed",{type:s.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(t){Z.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},y_=new hd,md=y_;var pd=0,Ed=class{constructor(i){this.core=i;u(this,"log");u(this,"_seiMessageList",[]);u(this,"_smallSeiMessageList",[]);u(this,"_subStreamSeiMessageList",[]);u(this,"_seiWorker");pd++,this.log=i.log.createChild({id:`${this.getAlias()}${pd}`}),this.log.info(`[sei] created id=${this.getAlias()}${pd}`),this.core=i}encode(i,e){try{let t=e===8?this._smallSeiMessageList:e===2?this._subStreamSeiMessageList:this._seiMessageList,s=_d(i,t);s&&this.log.debug(`${s} sei sent`)}catch(t){this.log.warn(t)}return i}decode(i,e){return fd(i).forEach(t=>{this.core.trtc.emit($.SEI_MESSAGE,{seiPayloadType:t.seiPayloadType,data:t.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"})}),i}destroy(){}getValidateRule(i){switch(i){case"start":return{type:"object"};case"update":return{type:"object"};case"stop":return{type:"object"}}}start(i){yi?(this._seiWorker=b_(),this._seiWorker.onmessage=e=>{this.core.trtc.emit($.SEI_MESSAGE,P(N({},e.data),{streamType:Zi(e.data.streamType)}))},this._seiWorker.onerror=e=>{this.log.error("seiWorker error: ",e.message)},this.core.room.videoManager.enableSEI({seiWorker:this._seiWorker})):this.core.room.videoManager.enableSEI({encoder:this.encode.bind(this),decoder:this.decode.bind(this)})}stop(i){this.core.room.videoManager.disableSEI()}update({buffer:i,options:e}){var o;let t=[e.seiPayloadType,i],s=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(t):(this._seiMessageList.push(t),s&&this._smallSeiMessageList.push(t)),this.core.innerEmitter.emit("265",{room:this.core.room,data:t,isMain:!e.toSubStream}),(o=this._seiWorker)==null||o.postMessage({message:t,isMain:!e.toSubStream,small:s})}getName(){return Ed.Name}getAlias(){return"sei"}getGroup(){return"sei"}},to=Ed;u(to,"Name","SEI");function Ul([r,i]){let e=i.byteLength,t=parseInt(String(e/255),10),s=e%255,o=[];o.push(0,0,0,1,6,r);for(let a=0;a<t;a++)o.push(255);o.push(s);let n=new DataView(i);return o.push(...new Uint8Array(n.buffer)),o.push(128),new Ni(new DataView(new Uint8Array(o).buffer),!0)}function Bl(r){return r.type==="empty"||r.data.byteLength===0}function $l(r){return r.getInt32(0)===1&&r.getInt8(4)===6}function Fl(r){let i=0,e=0,t=new DataView(r);for(let s=0;s<r.byteLength;s++)switch(t.getUint8(s)){case 0:i++;break;case 1:(i===2||i===3)&&e++,i=0;break;default:i=0;break}return e}function _d(r,i){if(i.length>0&&r.data.byteLength>0){let e=Fl(r.data),t=9-e;if(t<=0)return 0;let s=i.splice(0,t).reverse().map(Ul),o=s.reduce((l,p)=>l+p.dataView.byteLength,0),n=new ArrayBuffer(o+r.data.byteLength),a=new DataView(n),c=new DataView(r.data),d=0;for(let l=0;l<s.length;l++)for(let p=0;p<s[l].dataView.byteLength;p++)a.setInt8(d++,s[l].dataView.getInt8(p));for(let l=0;l<r.data.byteLength;l++)a.setInt8(d++,c.getInt8(l));return r.data=n,s.length}return 0}function fd(r){try{let i=new DataView(r.data);if(Bl(r)||!$l(i))return[];let e=[],t=0,s=-1,o=-1;for(let n=0;n<r.data.byteLength;n++){let a=i.getUint8(n);if(a===0)t++;else if(a===1){if(t===2||t===3){let c=n-t;if(s===-1?s=c:o===-1&&(o=c,e.push(new Ni(new DataView(i.buffer.slice(s,o)))),s=c,o=-1),!(i.getUint8(n+1)===6)){r.data=i.buffer.slice(c);break}}t=0}else t=0}return e.reverse()}catch(i){return[]}}function wl(r){return new TransformStream({transform(i,e){_d(i,r),e.enqueue(i)}})}function Vl(r,i){return new TransformStream({transform(e,t){fd(e).forEach(s=>{self.postMessage({seiPayloadType:s.seiPayloadType,data:s.seiPayload.buffer,userId:r,streamType:i})}),t.enqueue(e)}})}function b_(){let r=[Ni],i=[Fl,Bl,$l,Ul,_d,fd,wl,Vl],e=()=>{let a=[],c=[],d=[];self.onmessage=l=>{l.data.isMain?(a.push(l.data.message),l.data.small&&d.push(l.data.message)):c.push(l.data.message)},self.onrtctransform=l=>{let{options:p}=l.transformer,m=p.isReceiver?Vl(p.userId,p.streamType):wl(p.isMain?p.small?d:a:c);l.transformer.readable.pipeThrough(m).pipeTo(l.transformer.writable)}},t=`(()=>{${r.map(a=>`const ${a.name}=(()=>${a.toString()})()`).join(`
65
+ ${s.stack}`),!1}},r};var Wn=new WeakMap;function kl(r,i){return J((e,t)=>function(...s){var a,c;let o=(a=Wn.get(this))==null?void 0:a.get(i(...s));o&&o>0&&clearTimeout(o);let n=window.setTimeout(()=>{e.apply(this,s)},r);Wn.has(this)?(c=Wn.get(this))==null||c.set(i(...s),n):Wn.set(this,new Map([[i(...s),n]]))})}var Ll="5.8.2-beta.1";function ke(...r){return J((i,e)=>function(...t){try{jn.call(this,r,t,e,this._name)}catch(s){return Promise.reject(s)}return i.apply(this,t)})}function dd(...r){return J((i,e)=>function(...t){try{jn.call(this,r,t,e,this._name)}catch(s){throw s}return i.apply(this,t)})}function jn(r,i,e,t){if(he(r))for(let s=0;s<r.length;s++)Jn.call(this,{rule:r[s],value:i[s],key:r[s].name,fnName:e,className:t});else Jn.call(this,{rule:r,value:i[0],key:r.name,fnName:e,className:t})}function Jn({rule:r,value:i,key:e,fnName:t,className:s}){function o(c){return{code:w.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:r,value:i}}}if(T(i)){if(r.required)throw new k(o(5001));if(T(r.defaultValue)){W(r.validate)&&r.validate.call(this,i,e,t,s,this);return}i=r.defaultValue}if(Array.isArray(r.type)){let c=!1;for(let d=0;d<r.type.length;d++)r.type[d]===null&&i===null&&(c=!0),W(r.type[d])&&i instanceof r.type[d]&&(c=!0),Y(r.type[d])&&fe(i)===r.type[d].toLowerCase()&&(c=!0);if(!c)throw new k({code:w.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:r.type.map(d=>Ns(d)?zo(d):Y(d)?d:fe(d))},value:i}})}else if(!T(r.type)&&fe(i)!==r.type)throw new k(o(5002));if(r.allowEmpty===!1){let c=ee(i)&&(i===0||Number.isNaN(i)),d=Y(i)&&i.trim()==="";if(c||d)throw new k(o(5003))}if(r.notLessThanZero&&ee(i)&&i<0)throw new k(o(5006));if(!T(r.min)&&ee(i)&&i<r.min)throw new k(o(5007));if(!T(r.max)&&ee(i)&&i>r.max)throw new k(o(5008));if(Y(r.instanceOf)){if(!i||i._name!==r.instanceOf)throw new k(o(5004))}else if(W(r.instanceOf)&&!(i instanceof r.instanceOf))throw new k(o(5004));if(Array.isArray(r.values)&&!r.values.includes(i))throw new k(o(5005));let{properties:n}=r;Je(n)&&mt(i)&&Object.keys(n).forEach(c=>{Jn.call(this,{rule:n[c],value:i&&i[c],key:`${c}`,fnName:t,className:s})});let{arrayItem:a}=r;Je(a)&&he(i)&&i.forEach((c,d)=>{Jn.call(this,{rule:a,value:c,key:`${e}[${d}]`,fnName:t,className:s})}),W(r.validate)&&r.validate.call(this,i,e,t,s,this)}function oe(r={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t}=r;return J((s,o)=>function(...n){function a(l,p,m){if(m&&m.includes(l))return"hided";if(e){let f=e(...n);if(n[f.argIndex]===p)return f.value}if(p===n||l in n)return p;try{return p instanceof HTMLElement?`id: ${p.id} type:${fe(p)}`:(JSON.stringify(p),p)}catch(f){return`type:${fe(p)}`}}let c=this._log||I;n.length>0?c.info(`${o}() ${JSON.stringify(n,(l,p)=>a(l,p,["userSig","privateMapKey"]))}`):c.info(`${o}()`);let d=t?t(...n):un[o];try{let l=s.apply(this,n),p=x();return bs(l)?l.then(m=>(c.info(`${o}() success ${i.call(this,...n)}`),D.addSuccessEvent({key:d,cost:x()-p}),m)).catch(m=>{throw m=k.convertFrom.call(this,m,o,n.length===1?n[0]:n),c.error(`${o}() failed ${i.call(this,...n)} ${m} params: ${JSON.stringify(n,a)}`),D.addFailedEvent({key:d,error:m}),m}):(D.addSuccessEvent({key:d}),l)}catch(l){throw l=k.convertFrom.call(this,l,o),c.error(`${o}() failed ${l} params: ${JSON.stringify(n,a)}`),D.addFailedEvent({key:d,error:l}),l}})}var qn=r=>J((i,e)=>function(t,s){return _(this,null,function*(){let o=this._plugins.get(t);if(!o)throw this._log.error(`plugin ${String(t)} is not found`),new k({code:w.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});if(W(o.constructor.isSupported)&&!o.constructor.isSupported())throw this._log.error(`plugin ${String(t)} is not supported`),new k({code:w.ENV_NOT_SUPPORTED,message:`plugin ${String(t)} is not supported`,extraCode:5210,fnName:e});return jn.call(this,o.getValidateRule(r),[s],e,"TRTC"),i.call(this,o,s)})});var Xn=0,ud=class{constructor(i,e){u(this,"player");u(this,"publisher");u(this,"mixInput");this.mixInput=new kr(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 Hr(r,i){if(i&&typeof i!="function")throw new k({code:w.INVALID_PARAMETER,message:`start audioMixer plugin: param ${r} should be a function.`})}var Gr=class{constructor(i){this.core=i;u(this,"log");u(this,"mixedMusicMap",new Map);u(this,"cacheMusicMap",new Map);Xn=Xn+1,this.log=i.log.createChild({id:`${this.getAlias()}${Xn}`}),this.log.info(`[audioMixer] created id=${this.getAlias()}${Xn}`),this.core=i}getName(){return Gr.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return Gr.startValidateRule;case"update":return Gr.updateValidateRule;case"stop":return Gr.stopValidateRule}}start(i){return _(this,null,function*(){let{room:e}=this.core;this.log.info(`add music source, id: ${i.id} url: ${i.url}, track: ${i.track}`);let{id:t,url:s}=i;if(this.mixedMusicMap.has(t))return;let o=this.cacheMusicMap.get(t);o?i.url?o.reset():(o.mixInput.replaceSource(i.track),o.mixInput.connect()):(o=new ud(i,e.audioManager),this.cacheMusicMap.set(t,o)),o.updateListener(i),o.updateSettings(i),yield o.play(),this.mixedMusicMap.set(t,o),this.log.info(`start mix audio track ${t} success.`),D.addEnum({key:502700,value:3}),this.kvUpload(i)})}update(i){return _(this,null,function*(){let{id:e,operation:t,seekFrom:s,playbackRate:o}=i;this.log.info(`update music source, ${JSON.stringify(i)}`);let n=this.mixedMusicMap.get(e);if(!n){this.log.warn(`update music source failed, music id: ${e} not found.`);return}n.updateSettings(i),n.updateListener(i),T(t)||n.setOperation(t),T(s)||n.seek(s),this.kvUpload(i)})}stop(e){return _(this,arguments,function*({id:i}){var t;this.mixedMusicMap.has(i)&&(this.log.info(`remove music source, music id: ${i}`),(t=this.mixedMusicMap.get(i))==null||t.stop(),this.mixedMusicMap.delete(i)),i==="*"&&this.destroyAllMusic()})}kvUpload(i){let{track:e,loop:t,volume:s,playbackRate:o,operation:n,seekFrom:a,onTimeUpdate:c,onDurationChange:d,onEnded:l}=i;e&&D.addCount({key:502711}),t&&D.addCount({key:502703}),s&&D.addCount({key:502704}),o&&D.addCount({key:502705}),n&&D.addCount({key:502706}),a&&D.addCount({key:502707}),typeof c!="function"&&D.addCount({key:502709}),typeof l!="function"&&D.addCount({key:502710}),typeof d!="function"&&D.addCount({key:502708})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((i,e)=>this.stop({id:e}))}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}},Mi=Gr;u(Mi,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(i,e,t){if(i.url&&i.url!=="*"){let s=i.url.split("?")[0],o=["mp3","ogg","wav","flac"],n=s.split(".").pop(),a=o.indexOf(n)>=0,c=s.startsWith("blob"),d=s.startsWith("data");if(!(a||c||d))throw new k({code:w.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new k({code:w.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});Hr("onTimeUpdate",i.onTimeUpdate),Hr("onEnded",i.onEnded),Hr("onDurationChange",i.onDurationChange)}}),u(Mi,"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){Hr("onTimeUpdate",i.onTimeUpdate),Hr("onEnded",i.onEnded),Hr("onDurationChange",i.onDurationChange)}}),u(Mi,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),u(Mi,"Name","AudioMixer");var A_=r=>(r=Number(r),r>0&&r<14e8),Qn=0,ld,Wr=class{constructor(i){this.core=i;u(this,"log");u(this,"audioContext",qe("denoiser"));u(this,"workletNode");Qn=Qn+1,this.log=i.log.createChild({id:`${this.getAlias()}${Qn}`}),this.log.info(`[audioDenoiser] created id=${this.getAlias()}${Qn}`),i.assetsPath&&this.preload(`${i.assetsPath}/denoiser-wasm.js`)}static startValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,t,s,o){if(!i.room.audioManager.hasAudioTrack)throw new k({code:w.INVALID_OPERATION,extraCode:5106,fnName:s})}}}preload(i){return ld||(ld=this.doPreload(i)),ld}doPreload(i){return _(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield Gi(this.audioContext,t)}finally{URL.revokeObjectURL(t)}})}getName(){return Wr.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(i){switch(i){case"start":return Wr.startValidateRule(this.core);case"update":return Wr.updateValidateRule;case"stop":return Wr.stopValidateRule}}start(i){return _(this,null,function*(){let{room:e}=this.core;if(yield this.preload(`${i.assetsPath}/denoiser-wasm.js`),!this.workletNode){let t=String(Date.now()).slice(0,-3),{auth:s,sign:o,status:n,message:a}=yield R_(P(N({},i),{timestamp:t}));if(!s)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${s}. Message: ${a}`),new k({code:w.INVALID_PARAMETER,message:a});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(i.sdkAppId),userId:i.userId,timestamp:t,sign:o,status:n}}),this.workletNode.port.onmessage=c=>{let{data:d}=c;d.type==="cost"&&this.log.debug(`[RTCAIDenoiser] ${d.value}`)}}this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(){return _(this,null,function*(){})}stop(){return _(this,null,function*(){if(!this.workletNode)return;let{room:i}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield i.audioManager.removeDenoiser(this.workletNode)})}destroy(){}},tr=Wr;u(tr,"updateValidateRule",{type:"object"}),u(tr,"stopValidateRule",{type:"object"}),u(tr,"Name","AIDenoiser");var xl={MAIN:"schedule.cloud-rtc.com",MAIN_OVERSEA:"schedule.rtc.tencentcloud.com"};function C_(r){let i;return A_(r)?i=xl.MAIN_OVERSEA:i=xl.MAIN,i}function R_(s){return _(this,arguments,function*({sdkAppId:r,userId:i,userSig:e,timestamp:t}){let n=`https://${C_(r)}/api/v1/audioAiAuth?sdkAppId=${r}&userId=${i}&userSig=${e}&timestamp=${t}`,a=yield fetch(n),{data:{errCode:c,errMsg:d,sign:l,status:p}}=yield a.json();if(p==="1")return{auth:!0,sign:l,status:p,message:d};let m="Init RTCAIDenoiser failed.",f="";switch(c){case 1:f="Please check your params.";break;case 2:f="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:f="Server is invalid. Please contact our engineer. ";break;case 4:f="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:f="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:f="Your version is not supported.";break}return{auth:!1,status:p,message:d?`${m} Reason: ${d}. ${f}`:`${m}, ${f}`}})}var Pl=Se(Ne(),1);var hd=class extends Pl.EventEmitter{constructor(){super();this.state="nominal";this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return _(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!pe&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){Z.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let t=this.stateNum,s=e[e.length-1];this.state=s.state,(this.stateNum>3||t>3)&&I.info(`${s.source}: ${s.state}`),this.emit("state-changed",{type:s.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(t){Z.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},y_=new hd,md=y_;var pd=0,Ed=class{constructor(i){this.core=i;u(this,"log");u(this,"_seiMessageList",[]);u(this,"_smallSeiMessageList",[]);u(this,"_subStreamSeiMessageList",[]);u(this,"_seiWorker");pd++,this.log=i.log.createChild({id:`${this.getAlias()}${pd}`}),this.log.info(`[sei] created id=${this.getAlias()}${pd}`),this.core=i}encode(i,e){try{let t=e===8?this._smallSeiMessageList:e===2?this._subStreamSeiMessageList:this._seiMessageList,s=_d(i,t);s&&this.log.debug(`${s} sei sent`)}catch(t){this.log.warn(t)}return i}decode(i,e){return fd(i).forEach(t=>{this.core.trtc.emit($.SEI_MESSAGE,{seiPayloadType:t.seiPayloadType,data:t.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"})}),i}destroy(){}getValidateRule(i){switch(i){case"start":return{type:"object"};case"update":return{type:"object"};case"stop":return{type:"object"}}}start(i){yi?(this._seiWorker=b_(),this._seiWorker.onmessage=e=>{this.core.trtc.emit($.SEI_MESSAGE,P(N({},e.data),{streamType:Zi(e.data.streamType)}))},this._seiWorker.onerror=e=>{this.log.error("seiWorker error: ",e.message)},this.core.room.videoManager.enableSEI({seiWorker:this._seiWorker})):this.core.room.videoManager.enableSEI({encoder:this.encode.bind(this),decoder:this.decode.bind(this)})}stop(i){this.core.room.videoManager.disableSEI()}update({buffer:i,options:e}){var o;let t=[e.seiPayloadType,i],s=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(t):(this._seiMessageList.push(t),s&&this._smallSeiMessageList.push(t)),this.core.innerEmitter.emit("265",{room:this.core.room,data:t,isMain:!e.toSubStream}),(o=this._seiWorker)==null||o.postMessage({message:t,isMain:!e.toSubStream,small:s})}getName(){return Ed.Name}getAlias(){return"sei"}getGroup(){return"sei"}},to=Ed;u(to,"Name","SEI");function Ul([r,i]){let e=i.byteLength,t=parseInt(String(e/255),10),s=e%255,o=[];o.push(0,0,0,1,6,r);for(let a=0;a<t;a++)o.push(255);o.push(s);let n=new DataView(i);return o.push(...new Uint8Array(n.buffer)),o.push(128),new Ni(new DataView(new Uint8Array(o).buffer),!0)}function Bl(r){return r.type==="empty"||r.data.byteLength===0}function $l(r){return r.getInt32(0)===1&&r.getInt8(4)===6}function Fl(r){let i=0,e=0,t=new DataView(r);for(let s=0;s<r.byteLength;s++)switch(t.getUint8(s)){case 0:i++;break;case 1:(i===2||i===3)&&e++,i=0;break;default:i=0;break}return e}function _d(r,i){if(i.length>0&&r.data.byteLength>0){let e=Fl(r.data),t=9-e;if(t<=0)return 0;let s=i.splice(0,t).reverse().map(Ul),o=s.reduce((l,p)=>l+p.dataView.byteLength,0),n=new ArrayBuffer(o+r.data.byteLength),a=new DataView(n),c=new DataView(r.data),d=0;for(let l=0;l<s.length;l++)for(let p=0;p<s[l].dataView.byteLength;p++)a.setInt8(d++,s[l].dataView.getInt8(p));for(let l=0;l<r.data.byteLength;l++)a.setInt8(d++,c.getInt8(l));return r.data=n,s.length}return 0}function fd(r){try{let i=new DataView(r.data);if(Bl(r)||!$l(i))return[];let e=[],t=0,s=-1,o=-1;for(let n=0;n<r.data.byteLength;n++){let a=i.getUint8(n);if(a===0)t++;else if(a===1){if(t===2||t===3){let c=n-t;if(s===-1?s=c:o===-1&&(o=c,e.push(new Ni(new DataView(i.buffer.slice(s,o)))),s=c,o=-1),!(i.getUint8(n+1)===6)){r.data=i.buffer.slice(c);break}}t=0}else t=0}return e.reverse()}catch(i){return[]}}function wl(r){return new TransformStream({transform(i,e){_d(i,r),e.enqueue(i)}})}function Vl(r,i){return new TransformStream({transform(e,t){fd(e).forEach(s=>{self.postMessage({seiPayloadType:s.seiPayloadType,data:s.seiPayload.buffer,userId:r,streamType:i})}),t.enqueue(e)}})}function b_(){let r=[Ni],i=[Fl,Bl,$l,Ul,_d,fd,wl,Vl],e=()=>{let a=[],c=[],d=[];self.onmessage=l=>{l.data.isMain?(a.push(l.data.message),l.data.small&&d.push(l.data.message)):c.push(l.data.message)},self.onrtctransform=l=>{let{options:p}=l.transformer,m=p.isReceiver?Vl(p.userId,p.streamType):wl(p.isMain?p.small?d:a:c);l.transformer.readable.pipeThrough(m).pipeTo(l.transformer.writable)}},t=`(()=>{${r.map(a=>`const ${a.name}=(()=>${a.toString()})()`).join(`
66
66
  `)}
67
67
  ${i.map(a=>a.toString()).join(`
68
68
  `)};(${e})()})()`,s=new Blob([t],{type:"text/javascript"}),o=URL.createObjectURL(s),n=new Worker(o);return URL.revokeObjectURL(o),n}var Hl=0,zn=new Set,Le=null;ha(Ll);var N_={RtcError:k,ErrorCode:w,ErrorCodeDictionary:It},Jr=class extends Gl.EventEmitter{constructor(e,t){super();u(this,"_room");u(this,"_eventListened",new Set);u(this,"_localVideoTrack",null);u(this,"_localAudioTrack",null);u(this,"_localScreenTrack",null);u(this,"_localScreenAudioTrack",null);u(this,"_localVideoConfig",null);u(this,"_localScreenConfig",null);u(this,"_localAudioConfig",null);u(this,"_remoteVideoConfigMap",new Map);u(this,"_remoteAudioConfigMap",new Map);u(this,"_remoteAudioMuteMap",new Map);u(this,"_mediaTrackMap",new WeakMap);u(this,"_log",I.createLogger({id:`t${++Hl}`}));u(this,"_plugins",new Map);u(this,"_networkQuality",null);u(this,"_speakerId");this._room=new e(N({logger:this._log,frameWorkType:Jr.frameWorkType},t)),this._log.debug(`TRTC.create() ${JSON.stringify(t,(s,o)=>s==="plugins"?o.map(n=>n.Name):o)}`),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(s){return this._room.audioManager.dump(s)}}}),t.plugins&&t.plugins.forEach(s=>{this._use(s,t.assetsPath)}),this._use(Mi,t.assetsPath),this._use(tr,t.assetsPath),t.enableSEI&&Fi&&(this._use(to),this.startPlugin("SEI")),this._room.on("audio-volume",s=>{!s.find(o=>o.userId==="")&&this._localAudioTrack&&s.push({userId:"",volume:Math.floor(this._localAudioTrack.getAudioLevel()*100)}),this.emit($.AUDIO_VOLUME,{result:s.sort((o,n)=>n.volume-o.volume)})}),this._room.videoManager.on("error",({reason:s,error:o})=>{this._log.error(new k({code:w.OPERATION_FAILED,extraCode:5504,messageParams:{reason:s,error:o}}))}),this._listenEvents(),this._initActiveSpeaker(),Ml(this,"trtc")}static create(e){}static _create(e,t){Il();let s=new Jr(e,t||{});return zn.add(s),s}get room(){return this._room}_listenEvents(){De(this,this._room).add("peer-join",e=>{let{userId:t}=e;this.emit($.REMOTE_USER_ENTER,{userId:t})}).add("peer-leave",e=>{this.emit($.REMOTE_USER_EXIT,{userId:e})}).add("banned",e=>{this._exitRoom().then(()=>{this.emit($.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().then(()=>{this.emit($.ERROR,k.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit($.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e,this.emit($.NETWORK_QUALITY,e)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(s=>{De(s,s).add("player-state-changed",o=>{let n=P(N({},o),{userId:e.userId});s.kind===h.VIDEO&&(n.streamType=Zi(s.streamType)),this.emit(s.kind===h.AUDIO?$.AUDIO_PLAY_STATE_CHANGED:$.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",o=>{o.getCode()===A.PLAY_NOT_ALLOWED&&this.emit($.AUTOPLAY_FAILED,{userId:s.userId})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(s=>{me(s)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:t})=>{let{userId:s}=t,o=e.audioAvailable,n=e.videoAvailable,{audioAvailable:a,videoAvailable:c}=t;a||this._remoteAudioConfigMap.delete(s),c||this._remoteVideoConfigMap.delete(`${s}_${"main"}`),t.hasAuxiliary||this._remoteVideoConfigMap.delete(`${s}_${"sub"}`),o!==a&&(this.emit(a?$.REMOTE_AUDIO_AVAILABLE:$.REMOTE_AUDIO_UNAVAILABLE,{userId:s}),a?this._onAudioAvailable({userId:s}):this._onAudioUnavailable({userId:s,muteState:t})),n!==c&&(this.emit(c?$.REMOTE_VIDEO_AVAILABLE:$.REMOTE_VIDEO_UNAVAILABLE,{userId:s,streamType:"main"}),c?this._onVideoAvailable({userId:s,streamType:"main"}):this._onVideoUnavailable({userId:s,streamType:"main"})),e.hasAuxiliary!==t.hasAuxiliary&&(this.emit(t.hasAuxiliary?$.REMOTE_VIDEO_AVAILABLE:$.REMOTE_VIDEO_UNAVAILABLE,{userId:s,streamType:"sub"}),t.hasAuxiliary?this._onVideoAvailable({userId:s,streamType:"sub"}):this._onVideoUnavailable({userId:s,streamType:"sub"}))}).add("sei-message",e=>{this.emit($.SEI_MESSAGE,P(N({},e),{streamType:Zi(e.streamType)}))}).add("firewall-restriction",()=>{this.emit($.ERROR,new k({code:w.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var o,n,a,c,d,l,p;let t={2:"big",3:"small",7:"sub"},s={rtt:e.msg_up_stream_info.msg_network_status.uint32_rtt||((o=e.msg_down_stream_info[0])==null?void 0:o.msg_network_status.uint32_rtt)||((n=this._networkQuality)==null?void 0:n.uplinkRTT)||((a=this._networkQuality)==null?void 0:a.downlinkRTT)||0,upLoss:((c=this._networkQuality)==null?void 0:c.uplinkLoss)||0,downLoss:((d=this._networkQuality)==null?void 0:d.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((l=e.msg_up_stream_info.msg_audio_status)==null?void 0:l.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((p=e.msg_up_stream_info.msg_audio_status)==null?void 0:p.uint32_audio_level)||0)/ct},video:e.msg_up_stream_info.msg_video_status.filter(m=>t[m.uint32_video_stream_type]).map(m=>({bitrate:(m.uint32_video_codec_bitrate||0)/1e3,width:m.uint32_video_width,height:m.uint32_video_height,frameRate:m.uint32_video_enc_fps,videoType:t[m.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(m=>({userId:m.msg_user_info.str_identifier,audio:{bitrate:(m.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(m.msg_audio_status.uint32_audio_level||0)/ct},video:m.msg_video_status.map(f=>({bitrate:(f.uint32_video_codec_bitrate||0)/1e3,width:f.uint32_video_width,height:f.uint32_video_height,frameRate:f.uint32_video_dec_fps,videoType:t[f.uint32_video_stream_type]}))}))};this.emit($.STATISTICS,s)}).add("custom-message",e=>{this.emit($.CUSTOM_MESSAGE,e)}),De(this,ge).add("audioInputAdded",e=>{this.emit($.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit($.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit($.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit($.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>_(this,null,function*(){if(this.emit($.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Le&&Le.deviceId===cs){let t=(yield ji()).find(s=>s.deviceId===cs);t&&Le.groupId!==t.groupId&&(Le=t,this.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}})).add("audioOutputRemoved",e=>_(this,null,function*(){this.emit($.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield ji())[0];t&&Le&&(Le.deviceId===e.deviceId||Le.deviceId===cs&&Le.groupId!==t.groupId)&&(Le=t,this.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}))}use(e){let t,s;"plugin"in e?(t=e.plugin,s=e.assetsPath):t=e,this._use(t,s||"https://web.sdk.qcloud.com/trtc/webrtc/v5/assets/")}_use(e,t){if(this._plugins.get(e.Name)){this._log.warn("duplicate install plugin",e.Name);return}let o=new e(Ol.call(this,{TRTC:Jr,room:this._room,errorModule:N_,assetsPath:t}));this._plugins.set(e.Name,o),e.autoStart&&(this.startPlugin(e.Name),this._log.info("auto start plugin",e.Name))}enterRoom(e){return _(this,null,function*(){var c,d;let{scene:t="rtc",enableAutoPlayDialog:s=!0,autoReceiveAudio:o=!0,autoReceiveVideo:n=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!Y(e.proxy)&&e.proxy.turnServer&&((d=(c=this._room).setTurnServer)==null||d.call(c,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=s,this._room.autoReceiveAudio=o,this._room.autoReceiveVideo=n,de(e.preferHW)&&(this._room.preferHW=e.preferHW);let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:e.role==="audience"?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(a,t,Jr.frameWorkType),this._checkTrackToPublish(),md.start()})}exitRoom(){return _(this,null,function*(){return yield this._exitRoom()})}switchRole(e,t){return _(this,null,function*(){t!=null&&t.privateMapKey&&(this._room.privateMapKey=t.privateMapKey),t!=null&&t.latencyLevel&&(this._room.latencyLevel=t.latencyLevel),yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){me(this),this.removeAllListeners(),this._room.destroy(),zn.delete(this),zn.size===0&&md.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),this._plugins.forEach(e=>{var t;return(t=e.destroy)==null?void 0:t.call(e)})}startLocalAudio(){return _(this,arguments,function*(e={publish:!0}){if(this._localAudioTrack){this._log.warn("local audio is already started");return}let{publish:t=!0,mute:s,option:o}=e,n=new Oe(this._room.audioManager),a={},c={muted:!0};o&&(T(o.microphoneId)?T(o.audioTrack)||(a.customSource=o.audioTrack):a.deviceId=o.microphoneId,o&&ee(o.captureVolume)&&n.setCaptureVolume(o.captureVolume),T(o.profile)||(Y(o.profile)?Ro[o.profile]&&n.setProfile(Ro[o.profile]):n.setProfile(o.profile)),ee(o.earMonitorVolume)&&(c.muted=!(o.earMonitorVolume>0),c.volume=o.earMonitorVolume),T(o.echoCancellation)||(n.profile.echoCancellation=o.echoCancellation),T(o.noiseSuppression)||(n.profile.noiseSuppression=o.noiseSuppression),T(o.autoGainControl)||(n.profile.autoGainControl=o.autoGainControl)),n.on("5",d=>{this.emit($.ERROR,new k({code:w.DEVICE_ERROR,extraCode:5309,messageParams:{error:d}}))}),n.on("2",d=>{this.emit($.DEVICE_CHANGED,{type:"microphone",action:"active",device:d})}),n.on("4",d=>{let l;d.error&&(l=k.convertFrom(d.error)),this.emit($.PUBLISH_STATE_CHANGED,P(N({},d),{error:l}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId),yield n.capture(a),T(s)||n.setMute(s),De(n,n).add("player-state-changed",d=>{this.emit($.AUDIO_PLAY_STATE_CHANGED,P(N({},d),{userId:""}))}),t&&this._room.isJoined&&this._room.publish(n).catch(()=>{}),this._localAudioTrack=n,this._localAudioConfig=P(N({},e),{publish:t}),yield this._updateAudioPlayOption({playOption:c,track:n})})}updateLocalAudio(e){return _(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:s,option:o}=e,n={};o&&(o.microphoneId?yield this._localAudioTrack.switchDevice(o.microphoneId):T(o.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(o.audioTrack)),T(o.captureVolume)||this._localAudioTrack.setCaptureVolume(o.captureVolume),T(o.earMonitorVolume)||(n.muted=!(o.earMonitorVolume>0),n.volume=o.earMonitorVolume),yield this._localAudioTrack.update3A(o)),this._room.isJoined&&!T(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),T(s)||this._localAudioTrack.setMute(s),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),Kt(this._localAudioConfig,e)})}stopLocalAudio(){return _(this,null,function*(){!this._localAudioTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),me(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)})}startLocalVideo(){return _(this,arguments,function*(e={publish:!0,view:null}){if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:t,publish:s=!0,mute:o,option:n}=e,a=new le(this._room.videoManager),c={},d={};if(n&&(n.cameraId?c.deviceId=n.cameraId:T(n.useFrontCamera)?T(n.videoTrack)||(c.customSource=n.videoTrack):c.facingMode=n.useFrontCamera?h.FACING_MODE_USER:h.FACING_MODE_ENVIRONMENT,T(n.profile)||(Y(n.profile)?Ze[n.profile]&&a.setProfile(Ze[n.profile]):a.setProfile(n.profile)),T(n.fillMode)||(d.objectFit=n.fillMode),T(n.mirror)||(d.mirror=n.mirror),T(n.small)||(xs()?Y(n.small)?a.small=Ze[n.small]:n.small===!0?a.small=Ze["120p"]:a.small=n.small:this._log.warn("small stream is not supported"))),a.on("5",l=>{this.emit($.ERROR,new k({code:w.DEVICE_ERROR,extraCode:5308,messageParams:{error:l}}))}),a.on("2",l=>{this.emit($.DEVICE_CHANGED,{type:"camera",action:"active",device:l})}),a.on("4",l=>{let p;l.error&&(p=k.convertFrom(l.error)),this.emit($.PUBLISH_STATE_CHANGED,P(N({},l),{error:p}))}),this._listenOutputTrackChanged(a),yield a.capture(c),T(o)||(yield a.setMute(o)),a.mediaTrack)if(n!=null&&n.qosPreference){let l=er(n.qosPreference);a.mediaTrack.contentHint=l}else n!=null&&n.videoTrack||(a.mediaTrack.contentHint=er(st.QOS_PREFERENCE_SMOOTH));De(a,a).add("player-state-changed",l=>{this.emit($.VIDEO_PLAY_STATE_CHANGED,P(N({},l),{userId:"",streamType:"main"}))}),s&&this._room.isJoined&&this._room.publish(a).catch(()=>{}),this._localVideoTrack=a,this._localVideoConfig=P(N({},e),{view:t,publish:s}),yield this._updateVideoPlayOption({view:t,playOption:d,track:a})})}updateLocalVideo(e){return _(this,null,function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:s,mute:o,option:n}=e,a={};if(n){if(T(n.profile)||(Y(n.profile)?Ze[n.profile]&&this._localVideoTrack.setProfile(Ze[n.profile]):this._localVideoTrack.setProfile(n.profile),(!n.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(n.cameraId))&&T(n.useFrontCamera)&&this._localVideoTrack.applyProfile()),n.cameraId?yield this._localVideoTrack.switchDevice(n.cameraId):T(n.useFrontCamera)?T(n.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(n.videoTrack)):yield this._localVideoTrack.switchDevice(n.useFrontCamera?h.FACING_MODE_USER:h.FACING_MODE_ENVIRONMENT),T(n.fillMode)||(a.objectFit=n.fillMode),T(n.mirror)||(a.mirror=n.mirror),n.qosPreference&&this._localVideoTrack.mediaTrack){let c=er(n.qosPreference);this._localVideoTrack.mediaTrack.contentHint=c}if(n.small){let c=!this._localVideoTrack.small;xs()?(n.small===!0?this._localVideoTrack.small=Ze["120p"]:Y(n.small)?this._localVideoTrack.small=Ze[n.small]:this._localVideoTrack.small=n.small,this._room.videoManager.update(),c&&this._room.enableSmall(!0)):this._log.warn("small stream is not supported")}else n.small===!1&&this._localVideoTrack.small&&(delete this._localVideoTrack.small,this._room.videoManager.update(),this._room.enableSmall(!1))}this._room.isJoined&&!T(s)&&(s&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._localVideoConfig.publish&&!s&&this._room.unpublish(this._localVideoTrack).catch(()=>{})),T(o)||(yield this._localVideoTrack.setMute(o)),yield this._updateVideoPlayOption({view:t,playOption:a,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),Kt(this._localVideoConfig,e)})}stopLocalVideo(){return _(this,null,function*(){!this._localVideoTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),me(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return _(this,arguments,function*(e={publish:!0,view:null}){if(this._localScreenTrack){this._log.warn("screen share is already started");return}let{view:t=null,publish:s=!0,option:o}=e,n=new ze(this._room.videoManager);n.on("4",p=>{let m;p.error&&(m=k.convertFrom(p.error)),this.emit($.PUBLISH_STATE_CHANGED,P(N({},p),{error:m}))}),this._listenOutputTrackChanged(n);let a=null,c={},d={};o&&(T(o.profile)||(Y(o.profile)?yo[o.profile]&&n.setProfile(yo[o.profile]):n.setProfile(o.profile)),o.systemAudio&&(c.systemAudio=!0,c.echoCancellation=o.echoCancellation,c.noiseSuppression=o.noiseSuppression,c.autoGainControl=o.autoGainControl),T(o.fillMode)||(d.objectFit=o.fillMode),o.videoTrack&&(c.videoTrack=o.videoTrack),o.audioTrack&&(c.audioTrack=o.audioTrack),o.captureElement&&(c.captureElement=o.captureElement),o.preferDisplaySurface&&(c.preferDisplaySurface=o.preferDisplaySurface));let l=yield n.capture(c);if(o!=null&&o.qosPreference){let p=er(o.qosPreference);n.mediaTrack.contentHint=p}else o!=null&&o.videoTrack||(n.mediaTrack.contentHint=er(st.QOS_PREFERENCE_CLEAR));if(n.mediaTrack.addEventListener(h.ENDED,()=>{this._stopScreenShare(),this.emit($.SCREEN_SHARE_STOPPED)}),l.getAudioTracks()[0]&&(a=new Ft(this._room.audioManager),a.setInputMediaStreamTrack(l.getAudioTracks()[0]),this._speakerId&&a.setAudioOutput(this._speakerId)),De(n,n).add("player-state-changed",p=>{this.emit($.VIDEO_PLAY_STATE_CHANGED,P(N({},p),{userId:"",streamType:"sub"}))}),s&&this._room.isJoined){let p=[n];a&&p.push(a),this._room.publish(...p).catch(()=>{})}this._localScreenTrack=n,this._localScreenAudioTrack=a,this._localScreenConfig=P(N({},e),{view:t,publish:s}),yield this._updateVideoPlayOption({view:t,playOption:d,track:n})})}updateScreenShare(e){return _(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:s,option:o}=e,n={};if(o&&(T(o.fillMode)||(n.objectFit=o.fillMode),o.qosPreference)){let a=er(o.qosPreference);this._localScreenTrack.mediaTrack.contentHint=a}this._room.isJoined&&!T(s)&&(s&&!this._localScreenConfig.publish&&(this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch(()=>{})),this._localScreenConfig.publish&&!s&&(this._room.unpublish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.unpublish(this._localScreenAudioTrack).catch(()=>{}))),yield this._updateVideoPlayOption({view:t,playOption:n,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),Kt(this._localScreenConfig,e)})}stopScreenShare(){return _(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return _(this,null,function*(){let{view:t,userId:s,streamType:o,option:n}=e,a=`${s}_${o}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${s}, streamType:${o}`);return}let c=this._room.remotePublishedUserMap.get(s);if(!c)return;let d={},l=o==="main"?c.remoteVideoTrack:c.remoteAuxiliaryTrack;this._listenOutputTrackChanged(l),n&&(T(n.fillMode)||(d.objectFit=n.fillMode),T(n.mirror)||(d.mirror=n.mirror),d.canvasRender=n.canvasRender,o==="main"&&!T(n.small)&&(c.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,l.user))),yield this._room.subscribe(l),yield this._updateVideoPlayOption({view:t,playOption:d,track:l}),this._emitTrackEvent(l),this._remoteVideoConfigMap.set(a,{config:e}),n&&!T(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:l,view:t,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:n==null?void 0:n.viewRoot})})}updateRemoteVideo(e){return _(this,null,function*(){var v,U;let{view:t,userId:s,streamType:o,option:n}=e,a=`${s}_${o}`,c=this._remoteVideoConfigMap.get(a);if(!c||!this._room.remotePublishedUserMap.has(s))return;let d={};n&&(T(n.fillMode)||(d.objectFit=n.fillMode),T(n.mirror)||(d.mirror=n.mirror));let l=null,p=this._room.remotePublishedUserMap.get(s);if(o==="main"&&(p==null?void 0:p.muteState.hasVideo)&&(l=p.remoteVideoTrack),o==="sub"&&(p==null?void 0:p.muteState.hasAuxiliary)&&(l=p.remoteAuxiliaryTrack),!l)return;let{config:m}=c;o==="main"&&n&&!T(n.small)&&this._room.changeType(n.small,l.user),yield this._updateVideoPlayOption({view:t,playOption:d,track:l,prevConfig:m}),Kt(m,e);let f=T(n==null?void 0:n.receiveWhenViewVisible)?(v=m.option)==null?void 0:v.receiveWhenViewVisible:n.receiveWhenViewVisible,R=T(t)?m.view:t,C=T(n==null?void 0:n.viewRoot)?(U=m.option)==null?void 0:U.viewRoot:n.viewRoot;this._observeView({remoteTrack:l,view:R,receiveWhenViewVisible:f,viewRoot:C})})}stopRemoteVideo(e){return _(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,t=!0){return _(this,null,function*(){let s=[],o=this._room.remotePublishedUserMap.get(e.userId);if(o){let{muteState:a,remoteVideoTrack:c,remoteAuxiliaryTrack:d}=o;e.streamType==="main"&&(c.stop(),a.hasVideo&&s.push(c)),e.streamType==="sub"&&(d.stop(),a.hasAuxiliary&&s.push(d))}for(let a of s)t&&(yield this._room.unsubscribe(a),this._mediaTrackMap.get(a.outMediaTrack)===a.userId&&this._mediaTrackMap.delete(a.outMediaTrack));let n=this._remoteVideoConfigMap.get(`${e.userId}_${e.streamType}`);n&&n.observer&&n.observer.disconnect(),this._remoteVideoConfigMap.delete(`${e.userId}_${e.streamType}`)})}muteRemoteAudio(e,t){return _(this,null,function*(){if(e==="*")if(t)yield this._stopRemoteAudio({userId:e});else{let s=[...this._room.remotePublishedUserMap.values()];for(let o of s)o.muteState.hasAudio&&!this._remoteAudioConfigMap.has(o.userId)&&(yield this._startRemoteAudio({userId:o.userId}))}else t?yield this._stopRemoteAudio({userId:e}):this._remoteAudioConfigMap.has(e)||(yield this._startRemoteAudio({userId:e}));this._remoteAudioMuteMap.set(e,t)})}setRemoteAudioVolume(e,t){if(e==="*"){let s=[...this._room.remotePublishedUserMap.values()];for(let o of s)this._updateAudioPlayOption({playOption:{volume:t},track:o.remoteAudioTrack})}else if(e){let s=this._room.remotePublishedUserMap.get(e);s&&this._updateAudioPlayOption({playOption:{volume:t},track:s.remoteAudioTrack})}}startPlugin(e,t){return _(this,null,function*(){return e.start(t)})}updatePlugin(e,t){return _(this,null,function*(){return e.update(t)})}stopPlugin(e,t){return _(this,null,function*(){return e.stop(t)})}enableAudioVolumeEvaluation(e=2e3,t=!1){this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,s){return this.listeners(e).includes(t)?this:(this._log.debug("on",e),super.on(e,t,s),this._eventListened.add(e),this)}off(e,t,s){return this._log.debug("off",e),e==="*"?(this._eventListened.clear(),this.removeAllListeners()):super.off(e,t,s),this}getAudioTrack(e={userId:"",streamType:"main"}){var o,n;let t,s="main";if(Y(e)?t=e:(t=e.userId,e.streamType&&(s=e.streamType)),t){let a=this._room.remotePublishedUserMap.get(t);if(a)return a.remoteAudioTrack.mediaTrack}else return s==="sub"?((o=this._localScreenAudioTrack)==null?void 0:o.mediaTrack)||null:((n=this._localAudioTrack)==null?void 0:n.mediaTrack)||null;return null}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:t="",streamType:s="main"}=e;if(t===""){if(s==="main"&&this._localVideoTrack)return this._localVideoTrack.mediaTrack;if(s==="sub"&&this._localScreenTrack)return this._localScreenTrack.mediaTrack}else{let o=this._room.remotePublishedUserMap.get(t);if(o)return s==="main"?o.remoteVideoTrack.mediaTrack:o.remoteAuxiliaryTrack.mediaTrack}return null}getVideoSnapshot(e={}){let{userId:t,streamType:s="main"}=e;if(t){let o=this._room.remotePublishedUserMap.get(t);if(s==="main"&&(o==null?void 0:o.muteState.hasVideo))return o.remoteVideoTrack.getVideoFrame();if(s==="sub"&&(o==null?void 0:o.muteState.hasAuxiliary))return o.remoteAuxiliaryTrack.getVideoFrame()}else{if(s==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(s==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}setCurrentSpeaker(e){var t,s;this._speakerId=e,(t=this._localAudioTrack)==null||t.setAudioOutput(e),(s=this._localScreenAudioTrack)==null||s.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(o=>o.remoteAudioTrack.setAudioOutput(e))}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return _(this,null,function*(){let{userId:t,option:s}=e;if(this._remoteAudioConfigMap.has(t)){this._log.warn(`remote audio has already started. userId:${t}`);return}let o=this._room.remotePublishedUserMap.get(t);if(!o)return;let n={};s&&(T(s.volume)||(n.volume=s.volume));let a=o.remoteAudioTrack;this._listenOutputTrackChanged(a),this._speakerId&&a.setAudioOutput(this._speakerId);try{this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(a),yield this._updateAudioPlayOption({playOption:n,track:a})}catch(c){throw this._remoteAudioConfigMap.delete(t),c}this._emitTrackEvent(a)})}_stopRemoteAudio(e,t=!0){return _(this,null,function*(){let s=this._room.remotePublishedUserMap.get(e.userId);s&&(s.remoteAudioTrack.stop(),s.muteState.hasAudio&&t&&(yield this._room.unsubscribe(s.remoteAudioTrack)),this._mediaTrackMap.get(s.remoteAudioTrack.outMediaTrack)===e.userId&&this._mediaTrackMap.delete(s.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete(`${e.userId}`)})}_updateVideoPlayOption(n){return _(this,arguments,function*({view:e,playOption:t,track:s,prevConfig:o}){if(s.setMirror(t.mirror),T(e)&&o&&o.view&&!Ga(t)){let a=Ds(o.view);a.length>0&&(yield s.play(a,t))}if(!T(e)){let a=Ds(e);a.length>0?yield s.play(a,t):s.stop()}})}_updateAudioPlayOption(o){return _(this,arguments,function*({playOption:e={},track:t,prevConfig:s}){if(!t.isPlayCalled)try{yield t.play(null,e)}catch(n){}T(e.muted)||t.setPlayerMute(e.muted),T(e.volume)||t.setAudioVolume(e.volume/100)})}_listenOutputTrackChanged(e){e.listeners("output-media-track-changed").length===0&&e.on("output-media-track-changed",()=>this._emitTrackEvent(e,!1))}_emitTrackEvent(e,t=!0){let s=e.isRemote?e.userId:"";!e.outMediaTrack||t&&this._mediaTrackMap.get(e.outMediaTrack)===s||(this._mediaTrackMap.set(e.outMediaTrack,s),this.emit($.TRACK,{userId:s,streamType:Zi(e.streamType),track:e.outMediaTrack}))}_checkTrackToPublish(){var t,s,o;let e=[];if(((t=this._localAudioConfig)==null?void 0:t.publish)&&this._localAudioTrack&&e.push(this._localAudioTrack),((s=this._localVideoConfig)==null?void 0:s.publish)&&this._localVideoTrack&&e.push(this._localVideoTrack),(o=this._localScreenConfig)!=null&&o.publish&&(this._localScreenTrack&&e.push(this._localScreenTrack),this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack)),e.length!==0)return this._room.publish(...e).catch(()=>{})}_observeView({remoteTrack:e,view:t,receiveWhenViewVisible:s=!1,viewRoot:o}){if(T(t))return;let n=this._remoteVideoConfigMap.get(`${e.userId}_${Zi(e.streamType)}`);if(!n)return;let a=n.observer||void 0;if(t===null||he(t)&&t.length===0||!s){a==null||a.disconnect(),e.isSubscribed||this._room.subscribe(e).catch(()=>{});return}let d=n.visibleViewMap||new Map,l=-1;(!a||a.root!==o)&&(a==null||a.disconnect(),d.clear(),a=new IntersectionObserver(m=>{m.forEach(f=>{d.set(f.target,f.isIntersecting)}),clearTimeout(l),l=window.setTimeout(()=>{[...d.values()].find(R=>R)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:o}));let p=new Set(Ds(t));d.forEach((m,f)=>{p.has(f)||(a.unobserve(f),d.delete(f))}),p.forEach(m=>{d.set(m,!0),a.observe(m)}),a.takeRecords().forEach(m=>{d.set(m.target,m.isIntersecting)}),n.visibleViewMap=d,n.observer=a}_exitRoom(){return _(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(e=>{this._stopRemoteAudio({userId:e}).catch()}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let t=e.includes("main")?"main":"sub",s=e.split(`_${t}`)[0];s&&this._stopRemoteVideo({userId:s,streamType:t}).catch()}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._room.remotePublishedUserMap.forEach(e=>{me(e.remoteAudioTrack),me(e.remoteVideoTrack),me(e.remoteAuxiliaryTrack)})})}_stopScreenShare(){return _(this,null,function*(){var e;if(!!this._localScreenTrack){if(this._room.isJoined){let t=[this._localScreenTrack];this._localScreenAudioTrack&&t.push(this._localScreenAudioTrack),yield(e=this._room)==null?void 0:e.unpublish(...t).catch(()=>{})}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),me(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_initActiveSpeaker(){return _(this,null,function*(){if(Le&&!Lr(Le))this.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:Le});else{let e=yield ji();if(e[0]&&!Lr(e[0]))Le=e[0],this.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]});else{let t=({track:s})=>{s.kind==="audio"&&(!Le||Lr(Le))&&(this._initActiveSpeaker(),g.off("102",this._initActiveSpeaker))};g.on("102",t)}}})}_onAudioAvailable({userId:e}){let t=this._remoteAudioMuteMap.has(e)?this._remoteAudioMuteMap.get(e):this._remoteAudioMuteMap.get("*");(t===!1||this._room.autoReceiveAudio&&!t)&&this._doStartRemoteAudio({userId:e}).catch(()=>{})}_onVideoAvailable({userId:e,streamType:t}){if(!this._room.autoReceiveVideo)return;let s=this._room.remotePublishedUserMap.get(e);if(s){let o=t==="main"?s.remoteVideoTrack:s.remoteAuxiliaryTrack;this._room.subscribe(o).then(()=>{this._emitTrackEvent(o)}).catch(()=>{})}}_onAudioUnavailable({userId:e,muteState:t}){t.hasAudio&&t.audioMuted||this._stopRemoteAudio({userId:e},!1).catch(()=>{})}_onVideoUnavailable({userId:e,streamType:t}){this._stopRemoteVideo({userId:e,streamType:t},!1).catch(()=>{})}sendSEIMessage(e,t){var o;let s=this._plugins.get("SEI");s&&(s.update({buffer:e,options:P(N({seiPayloadType:243},t),{small:!!((o=this._localVideoTrack)!=null&&o.small)})}),D.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,s;(s=(t=this._room).sendCustomMessage)==null||s.call(t,e),D.addCount({key:500001,useUV:!0})}static setLogLevel(e,t){I.setLogLevel(e),T(t)||(t?I.enableUploadLog():I.disableUploadLog())}static isSupported(){return on()}static getCameraList(e=!0){return Xe(e)}static getMicrophoneList(e=!0){return Be(e)}static getSpeakerList(e=!0){return ji(e)}static setCurrentSpeaker(e){return _(this,null,function*(){(yield ji()).forEach(s=>{s.deviceId===e&&(zn.forEach(o=>{o.setCurrentSpeaker(e),o.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:s})}),Le=s)})})}static _addKVStat({type:e,key:t,value:s,base:o,useUV:n,version:a}){switch(a&&(Hi.version=a),e){case"count":Hi.addCount({key:t,useUV:n});break;case"enum":Hi.addEnum({key:t,value:s,useUV:n});break;case"number":Hi.addNumber({key:t,value:s,split:o});break}}},Q=Jr;u(Q,"_loggerManager",I),u(Q,"EVENT",$),u(Q,"ERROR_CODE",w),u(Q,"TYPE",st),u(Q,"frameWorkType",30),y([oe({replaceArg:r=>({argIndex:0,value:{name:"plugin"in r?r.plugin.Name:r.Name,assetsPath:"assetsPath"in r?r==null?void 0:r.assetsPath:"default"}})})],Q.prototype,"use",1),y([ke(Ce.TRTC.enterRoom),Di("room",([r],[i])=>(r.roomId||r.strRoomId)===(i.roomId||i.strRoomId)&&r.userId===i.userId&&r.sdkAppId===i.sdkAppId),J(r=>function(i){return this._log.setUserId(i.userId),this._log.setSdkAppId(i.sdkAppId),r.call(this,i)}),oe()],Q.prototype,"enterRoom",1),y([oe()],Q.prototype,"exitRoom",1),y([ke(Ce.TRTC.switchRole),Ki("room",{merge:(r,i)=>i}),oe()],Q.prototype,"switchRole",1),y([oe()],Q.prototype,"destroy",1),y([ke(Ce.TRTC.startLocalAudio),Di("audio",([r],[i])=>{var e,t;return((e=r==null?void 0:r.option)==null?void 0:e.microphoneId)===((t=i==null?void 0:i.option)==null?void 0:t.microphoneId)}),oe()],Q.prototype,"startLocalAudio",1),y([ke(Ce.TRTC.updateLocalAudio),Ki("audio",{debounce:{delay:200,getKey:()=>`${Hl}-localAudio`,isNeedToDebounce:r=>{var i;return!T((i=r.option)==null?void 0:i.captureVolume)}}}),oe()],Q.prototype,"updateLocalAudio",1),y([Oi("audio"),oe()],Q.prototype,"stopLocalAudio",1),y([ke(Ce.TRTC.startLocalVideo),Di("video",([r],[i])=>{var e,t;return((e=r==null?void 0:r.option)==null?void 0:e.cameraId)===((t=i==null?void 0:i.option)==null?void 0:t.cameraId)}),oe()],Q.prototype,"startLocalVideo",1),y([ke(Ce.TRTC.updateLocalVideo),Ki("video"),oe()],Q.prototype,"updateLocalVideo",1),y([Oi("video"),oe()],Q.prototype,"stopLocalVideo",1),y([ke(Ce.TRTC.startScreenShare),Di("screen",()=>!0),oe()],Q.prototype,"startScreenShare",1),y([ke(Ce.TRTC.updateScreenShare),Ki("screen"),oe()],Q.prototype,"updateScreenShare",1),y([oe()],Q.prototype,"stopScreenShare",1),y([ke(Ce.TRTC.startRemoteVideo),Di(r=>`v${r.userId}${r.streamType}`,()=>!0),oe({getRemoteId:r=>`${r.userId}_${r.streamType}`})],Q.prototype,"startRemoteVideo",1),y([ke(Ce.TRTC.updateRemoteVideo),Ki(r=>`v${r.userId}${r.streamType}`),oe({getRemoteId:r=>`${r.userId}_${r.streamType}`})],Q.prototype,"updateRemoteVideo",1),y([ke(Ce.TRTC.stopRemoteVideo),J(r=>function(i){return _(this,null,function*(){if(i.userId==="*"){let e=[];return this._room.remotePublishedUserMap.forEach(t=>{this._remoteVideoConfigMap.has(`${t.userId}_${"main"}`)&&e.push(this.stopRemoteVideo({streamType:"main",userId:t.userId}).catch(()=>{})),this._remoteVideoConfigMap.has(`${t.userId}_${"sub"}`)&&e.push(this.stopRemoteVideo({streamType:"sub",userId:t.userId}).catch(()=>{}))}),Promise.all(e)}return r.call(this,i)})}),oe({getRemoteId:r=>`${r.userId}_${r.streamType}`})],Q.prototype,"stopRemoteVideo",1),y([Oi(r=>`v${r.userId}${r.streamType}`)],Q.prototype,"_stopRemoteVideo",1),y([ke(...Ce.TRTC.muteRemoteAudio),oe({getRemoteId:r=>r})],Q.prototype,"muteRemoteAudio",1),y([dd(...Ce.TRTC.setRemoteAudioVolume),kl(200,r=>r),oe({getRemoteId:r=>r})],Q.prototype,"setRemoteAudioVolume",1),y([qn("start"),gt(r=>{var i;return(i=r.afterStart)==null?void 0:i.call(r)}),Di((r,i)=>r.getAlias()+r.getGroup(i)),oe({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>oc[r.getName()]})],Q.prototype,"startPlugin",1),y([qn("update"),Ki((r,i)=>r.getAlias()+r.getGroup(i)),oe({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>nc[r.getName()]})],Q.prototype,"updatePlugin",1),y([qn("stop"),Oi((r,i)=>{let e=r.getGroup(i),t=r.getAlias();return e==="*"?new RegExp(`${t}.*`):t+e}),oe({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>ac[r.getName()]})],Q.prototype,"stopPlugin",1),y([dd(...Ce.TRTC.enableAudioVolumeEvaluation)],Q.prototype,"enableAudioVolumeEvaluation",1),y([oe()],Q.prototype,"getVideoSnapshot",1),y([oe()],Q.prototype,"setCurrentSpeaker",1),y([Di(r=>`a${r.userId}`,()=>!0)],Q.prototype,"_startRemoteAudio",1),y([J(r=>function(i){return _(this,null,function*(){return i.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(e=>this._stopRemoteAudio(P(N({},i),{userId:e.userId})).catch(()=>{}))):r.call(this,i)})}),Oi(r=>`a${r.userId}`)],Q.prototype,"_stopRemoteAudio",1),y([Oi("room")],Q.prototype,"_exitRoom",1),y([Oi("screen")],Q.prototype,"_stopScreenShare",1),y([ke(...Ce.TRTC.sendSEIMessage),nd({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...r)=>r[0].byteLength})],Q.prototype,"sendSEIMessage",1),y([ke(Ce.TRTC.sendCustomMessage),nd({timesInSecond:30,maxSizeInSecond:8e3,getSize:r=>r.data.byteLength})],Q.prototype,"sendCustomMessage",1),y([ke(Ce.TRTC.create)],Q,"_create",1);var io=Q;var gd=class{constructor(){this._set=new Set;g.on(E.LEAVE_SUCCESS,this.delete,this)}add({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,e||i.roomId,i.sdkAppId,i.useStringRoomId);this._set.add(t)}delete({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,i.roomId||e,i.sdkAppId,i.useStringRoomId);this._set.delete(t)}getKey(i,e,t,s){return`${t}_${e}_${i}_${s}`}isJoined({userId:i,roomId:e,sdkAppId:t,room:s}){return s.scene==="rtc"?!1:this._set.has(this.getKey(i,e,t,s.useStringRoomId))}};function v_(){return _(this,null,function*(){let r,i;try{let p=yield Be();r=p&&p.length}catch(p){}try{let p=yield Xe();i=p&&p.length}catch(p){}let e={microphone:r,camera:i},{isH264EncodeSupported:t,isVp8EncodeSupported:s,isH264DecodeSupported:o,isVp8DecodeSupported:n}=this.checkSystemResult.detail,a=ft.basis(),c={webRTC:a.isWebRTCSupported,getUserMedia:a.isGetUserMediaSupported,webSocket:a.isWebSocketsSupported,screenShare:a.isScreenShareSupported,webAudio:a.isWebAudioSupported,h264Encode:t,h264Decode:o,vp8Encode:s,vp8Decode:n},d={browser:a.browser,os:a.os,trtc:c,devices:e},l={isWebCodecSupported:a.isWebCodecSupported,isMediaSessionSupported:a.isMediaSessionSupported,isWebTransportSupported:a.isWebTransportSupported};Z.uploadEvent({log:`trtcstats-${JSON.stringify(d)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(d)}`),Z.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(l)}`,userId:this.userId})})}function Wl(){return J(r=>{let i=new gd;return function(e,t,s){return _(this,null,function*(){let o=String(e.roomId||e.strRoomId);if(this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.userSig=e.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=t,e.privateMapKey=e.privateMapKey||"",this.isJoined)throw new b({code:A.INVALID_OPERATION,message:L({key:M.INVALID_JOIN})});if(this.checkDestroy(),i.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this}))throw new b({code:A.INVALID_OPERATION,message:L({key:M.REPEAT_JOIN,data:this.userId})});i.add({room:this,roomId:o}),this.role=e.role===21?"audience":"anchor",this._log.info(`Join() => joining room: ${o} useStringRoomId: ${this.useStringRoomId} scene: ${this.scene} role: ${this.role}`),g.emit(E.JOIN_START,{room:this,roomId:o,params:e}),this.checkSystemResult=yield ft.checkSystemRequirementsInternal(),this.checkDestroy();let n=we.getEnv();n||(n=jt.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(bo.OLD_CLOUD_LADDER)?n=jt.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(bo.WEBRTC)&&(n=jt.WEBRTC))),Z.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),v_.call(this);let{isH264EncodeSupported:a,isVp8EncodeSupported:c}=this.checkSystemResult.detail;if(!ft.isWebRTCSupported()||!a&&!c)throw new b({code:A.NOT_SUPPORTED,message:L({key:M.NOT_SUPPORTED_WEBRTC})});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!we.getEnv()&&(yield this.schedule(e,s));let d=yield r.call(this,e,t,s);return this.roomId=o,this._joinedTimestamp=we.performanceNow(),g.emit(E.JOIN_SUCCESS,{room:this}),s===30&&!e.component&&Z.uploadEvent({log:`stat-conv-${Number(zt)}-${location.hostname}`,userId:this.userId}),d}catch(d){throw i.delete({room:this,roomId:o}),g.emit(E.JOIN_FAILED,{room:this,error:d}),d}})}})}var Jl=()=>J(r=>function(...i){return _(this,null,function*(){g.emit(E.LEAVE_START,{room:this}),yield r.call(this),g.emit(E.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function jl(){return J(r=>function(...i){let e=r.apply(this,i);return i.forEach(t=>!t.isSubscribed&&t.subscribe(e)),e})}var Xl=Se(Ne());var _e={SETUP_SUCCESS:"1",SETUP_FAILED:"5",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",DISCONNECTED:"5",RECONNECT_FAILED:"4"};var Gt={CLIENT_BANNED:9,CHANNEL_SETUP_RESULT:19,CHANNEL_RECONNECT_RESULT:514,JOIN_ROOM_RESULT:20,PEER_JOIN:4134,PEER_LEAVE:4135,STREAM_ADDED:16,STREAM_REMOVED:18,UPLINK_NETWORK_STATS:22,UPDATE_REMOTE_MUTE_STAT:23,PUBLISH_RESULT:4098,PUBLISH_STATE_CHANGE_RESULT:4112,UNPUBLISH_RESULT:4100,SUBSCRIBE_RESULT:4102,UNSUBSCRIBE_RESULT:4104,SUBSCRIBE_CHANGE_RESULT:4106,MUTE_RESULT:4108,UPDATE_OFFER_RESULT:4128,START_PUBLISH_TENCENT_CDN_RES:1286,STOP_PUBLISH_TENCENT_CDN_RES:1288,START_PUBLISH_GIVEN_CDN_RES:777,STOP_PUBLISH_GIVEN_CDN_RES:779,START_MIX_TRANSCODE_RES:781,STOP_MIX_TRANSCODE_RES:783,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772,REBUILD_PEER_CONNECTION_RES:4150,SPC_PUBLISH_RESULT:4146,SPC_SUBSCRIBE_RESULT:4156,ABILITY_STATUS_REPORT_RESULT:4158,SERVER_FIRST_PACKAGE_RECEIVED:5e3,RECEIVE_CUSTOM_MSG:4140},ql=[Gt.UPDATE_REMOTE_MUTE_STAT,Gt.UPLINK_NETWORK_STATS,Gt.USER_LIST_RES,Gt.MUTE_RESULT,Gt.SERVER_FIRST_PACKAGE_RECEIVED],V={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",USER_LIST_RES:"user-list-res",SWITCH_ROLE_RES:"switch_role_res",MUTE_RESULT:"mute-result",UPDATE_CONSTRAINT_CONFIG_RES:"update-contraint-config-res",REBUILD_PEER_CONNECTION_RES:"rebuild-pc-res",SPC_PUBLISH_RESULT:"spc-publish-result",SPC_SUBSCRIBE_RESULT:"spc-subscribe-result",ABILITY_STATUS_REPORT_RESULT:"ability-status-report",SERVER_FIRST_PACKAGE_RECEIVED:"first-pkg-received",RECEIVE_CUSTOM_MSG:"receive-custom-msg"},q={PUBLISH_CHANGE:"publish_change",JOIN_ROOM:"join",LEAVE_ROOM:"leave",ON_QUALITY_REPORT:"quality_report",UPDATE_MUTE_STAT:"mute_uplink",PUBLISH:"publish",PUBLISH_STATE_CHANGE:"publish_state_change",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",RECEIVE_DATA_USER_LIST:"receive_data_userlist",UNSUBSCRIBE:"unsubscribe",SUBSCRIBE_CHANGE:"subscribe_change",START_PUBLISH_TENCENT_CDN:"start_publishing",STOP_PUBLISH_TENCENT_CDN:"stop_publishing",START_PUBLISH_GIVEN_CDN:"start_push_user_cdn",STOP_PUBLISH_GIVEN_CDN:"stop_push_user_cdn",START_MIX_TRANSCODE:"start_mcu_mix",STOP_MIX_TRANSCODE:"stop_mcu_mix",GET_USER_LIST:"get_user_list",SWITCH_ROLE:"change_role",UPDATE_CONSTRAINT_CONFIG:"update_constraint_config",REBUILD_PEER_CONNECTION:"rebuild_pc",READY_TO_RECEIVE_DATA:"ready_to_receive",SPC_JOIN_ROOM:"join/v2",SPC_PUBLISH:"publish/v2",SPC_SUBSCRIBE:"subscribe/v3",ABILITY_STATUS_REPORT:"ability_status_report",RECONNECT_WS:"reconnect",SEND_CUSTOM_MSG:"channel_msg"};var Yn=new Set;function Ql(r){let i=[...Yn.values()].find(e=>e.room.userId===r&&!e.room.isJoined);return i||null}var jr=class extends Xl.default{constructor(e){var s,o;super();u(this,"room");u(this,"url");u(this,"backupUrl");u(this,"race");u(this,"destroyed",!1);u(this,"_socketInUse");u(this,"_socket");u(this,"_backupSocket");u(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0});u(this,"_currentState","DISCONNECTED");u(this,"_isReconnecting",!1);u(this,"_seq",0);u(this,"_log");u(this,"_lastMessageTime",-1);u(this,"_connnectStartTime",-1);u(this,"_stopConnectRetry");u(this,"bytesSent",0);u(this,"bytesReceived",0);u(this,"keepAlive",!1);u(this,"signalDomainWhenUnifiedProxy");this.room=e.room,this.race=T(e.race)?!0:e.race,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy,(((o=(s=this.room.scheduleResult)==null?void 0:s.config)==null?void 0:o.keepAliveClient)||0)-Yn.size>0&&this.room.enableSPC&&(this.keepAlive=!0,Yn.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=I.createLogger({id:"ws",userId:this.userId,sdkAppId:this.sdkAppId}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get urlParam(){let e=`?sdkAppId=${encodeURIComponent(this.sdkAppId)}&userId=${encodeURIComponent(this.userId)}&userSig=${encodeURIComponent(this.userSig)}&keepAlive=${encodeURIComponent(Number(this.keepAlive))}`;return this.signalDomainWhenUnifiedProxy&&(e+=`&signalDomain=${encodeURIComponent(this.signalDomainWhenUnifiedProxy)}`),this.race?`${e}&race=1`:e}get _urlWithParam(){return`${this.url}${this.race?"/v2/ws":""}${this.urlParam}`}get _backupUrlWithParam(){return`${this.backupUrl}${this.race?"/v2/ws":""}${this.urlParam}`}get isConnected(){return this._currentState==="CONNECTED"}get isConnecting(){return this._currentState==="CONNECTING"}get sdkAppId(){return this.room.sdkAppId}get userId(){return this.room.userId}get userSig(){return this.room.userSig}get isOnline(){return this._currentState==="CONNECTED"&&Date.now()-this._lastMessageTime<12*1e3}connect(){return _(this,arguments,function*(e=10*1e3){if(this.isConnected)return Promise.resolve();this._log.info(`connect to [${this.url}, ${this.backupUrl}]${e?` timeout: ${e}`:""} keepAlive: ${Number(this.keepAlive)}`),this.emitConnectionStateChanged("CONNECTING"),this._connnectStartTime=x();let t=[this.connectWS({url:this._urlWithParam,isMain:!0,timeout:e})];this.race&&this._backupUrlWithParam!==this._urlWithParam&&t.push(this.connectWS({url:this._backupUrlWithParam,isMain:!1,timeout:e})),this._socketInUse=yield Rs(t),this.unbindAndCloseSocket(this._socketInUse===this._socket?h.BACKUP:h.MAIN),this.emitConnectionStateChanged("CONNECTED")})}connectWS({url:e,timeout:t,isMain:s}){let o=new WebSocket(e);this.bindSocket(o),s?this._socket=o:this._backupSocket=o;let n=-1;return new Promise((a,c)=>{o.onclose=c,o.onerror=c,o.onopen=()=>a(o),t&&(n=setTimeout(()=>{this.unbindAndCloseSocket(s?h.MAIN:h.BACKUP),c(new b({code:A.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))},t))}).finally(()=>{o.onclose=null,o.onerror=null,o.onopen=null,clearTimeout(n)})}bindSocket(e){e.addEventListener("close",this.onclose),e.addEventListener("error",this.onerror),e.addEventListener("message",this.onmessage)}unbindSocket(e){e.removeEventListener("close",this.onclose),e.removeEventListener("error",this.onerror),e.removeEventListener("message",this.onmessage)}unbindAndCloseSocket(e){if(e===h.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(t){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(t){}this._backupSocket=null}}onclose(e){if(e.target===this._socketInUse&&(this._log.warn(`${e.target===this._socket?"main":"backup"} is closed code:${e.code} ${e.reason}`),this.emitConnectionStateChanged("DISCONNECTED"),!e.wasClean||e.code!==1e3)){this._socketInUse.onclose=null,this._socketInUse.close(4011);let t=this._socketInUse===this._socket;this.unbindAndCloseSocket(t?h.MAIN:h.BACKUP),this._socketInUse=null,this.reconnect()}}onerror(e){this._log.error(`${e.target===this._socket?"main":"backup"} error observed`),this.emitConnectionStateChanged("DISCONNECTED"),e.target===this._socketInUse&&(this.unbindAndCloseSocket(h.MAIN),this.unbindAndCloseSocket(h.BACKUP),this._socketInUse=null,this.reconnect())}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=Yo(e.data);let t=JSON.parse(e.data),{cmd:s,data:o}=t,n=Object.values(Gt),c=Object.keys(Gt)[n.indexOf(s)],d=V[c]||s;switch(ql.includes(s)||(this._log.debug(`received ${s} msg: ${e.data}`),d&&this._log.info(`Received event: [ ${d} ]`)),s){case Gt.CHANNEL_SETUP_RESULT:{if(t.code===0)this._signalInfo.clientIp=o.clientIp,this._signalInfo.signalIp=o.signalInnerIp,o.svrTime&&Qd(o.svrTime),this._log.info("ChannelSetup Success"),D.addSuccessEvent({key:521701,cost:x()-this._connnectStartTime}),this._connnectStartTime=-1,this.emit(_e.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let l=new b({code:A.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:L({key:M.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error(`${t.code}, ${t.message}`),this.close(),D.addFailedEvent({key:521701,error:l}),this.emit(_e.SETUP_FAILED,l)}break}case Gt.JOIN_ROOM_RESULT:{t.code===0&&(this._signalInfo.relayIp=o.relayOuterIp,this._signalInfo.relayInnerIp=o.relayInnerIp,this._signalInfo.relayPort=o.relayPort,this._signalInfo.tinyId=t.tinyId,this._log.info(`signalIp:${this._signalInfo.signalIp} clientIp:${this._signalInfo.clientIp} relayIp: ${this._signalInfo.relayIp}`)),this.emit(d,{data:t});break}default:this.emit(String(d),{data:t});break}}reGetSignalChannelUrl(){return _(this,null,function*(){try{if(!this.room.joinParams)return;Mt(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(e){}})}reconnect(){return _(this,null,function*(){if(!this._isReconnecting){if(!this.room.isJoined&&this.keepAlive){this.close();return}this._isReconnecting=!0;try{this._log.warn("reconnect"),yield this.connect();let{roomId:e,useStringRoomId:t}=this.room,{relayIp:s,relayInnerIp:o,relayPort:n}=this._signalInfo,{data:a}=yield this.sendWaitForResponse({command:q.RECONNECT_WS,data:{roomId:e,useStringRoomId:t,relayInnerIp:o,relayOuterIp:s,relayPort:n},responseCommand:V.CHANNEL_RECONNECT_RESULT});a.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),D.addSuccessEvent({key:521702,cost:x()-this._connnectStartTime}),this._connnectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(D.addFailedEvent({key:521702,error:a.code}),this._log.warn(`reconnect failed, ${a.code} ${a.message}`),this.room.reJoin())}catch(e){this._log.error(e),this.room.reJoin()}}})}send(e,t={}){if(this.isConnected&&!this.room.isLeft){let s={cmd:e,data:t,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},o=JSON.stringify(s);return this._socketInUse.send(o),this.bytesSent+=Yo(o),s.seq}}sendWaitForResponse({command:e,data:t,timeout:s=5e3,responseCommand:o,commandDesc:n,enableLog:a=!0}){return new Promise((c,d)=>{let l=setTimeout(()=>{this.off(o,p);let f=new b({code:A.API_CALL_TIMEOUT,message:L({key:M.API_CALL_TIMEOUT,data:{commandDesc:n,command:e}})});a&&this._log.warn(f),d(f)},s),p=f=>{f.data.seq===m&&(clearTimeout(l),this.off(o,p),c(f))};this.on(o,p);let m=this.send(e,t)})}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:s,retries:o=0,retryTimeout:n=0}=e;return vt({retryFunction:this.sendWaitForResponse,onError:({retry:a})=>{this.isOnline?a():(this._log.warn(`retry ${s} when connected`),this.once(_e.CONNECTED,a))},onRetrying:a=>{this._log.warn(`${t||s} timeout observed, retrying [${a}/${o}]`)},settings:{retries:o,timeout:n},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),Yn.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(h.MAIN),this.unbindAndCloseSocket(h.BACKUP),this.emitConnectionStateChanged("DISCONNECTED")}destroy(){this.close(),this.destroyed=!0}stopKeepAliveIn(e=3600){if(this.keepAlive){this._log.info(`stopKeepAlive in ${e}s`);let t=setTimeout(()=>{this.keepAlive=!1,this._log.info(`close due to not used ${e}s`),this.close(),this.off(V.JOIN_ROOM_RESULT,s)},e*1e3),s=o=>{o.data.code===0&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(t),this.off(V.JOIN_ROOM_RESULT,s))};this.on(V.JOIN_ROOM_RESULT,s)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info(`${this._currentState} -> ${e}`),this.emit(_e.CONNECTION_STATE_CHANGED,{prevState:this._currentState,state:e}),this._currentState=e,e==="CONNECTED"?this.emit(_e.CONNECTED):e==="DISCONNECTED"&&this.emit(_e.DISCONNECTED))}};y([it({settings:{retries:1/0,timeout:2e3},onError(r,i){!this.room.isDestroyed&&!this.destroyed&&i()},onRetrying(r,i){this._log.warn(`retrying to connect ${r}`),r>=3&&r%3===0&&this.reGetSignalChannelUrl(),i&&(this._stopConnectRetry=i,(this.room.isDestroyed||this.destroyed)&&i())}})],jr.prototype,"connect",1);var zl=Se(Ne());var Td=0,Sd=!1,Kn=new Set,O_=r=>Td>2&&!Sd&&Kn.size===0&&r,Id=!1,Ke=class{constructor(i){u(this,"userId");u(this,"tinyId");u(this,"_sdpSemantics");u(this,"_isUplink");u(this,"_room");u(this,"_log");u(this,"_signalChannel");u(this,"_isErrorObserved",!1);u(this,"_waitForPeerConnectionConnectedPromise");u(this,"_waitForPeerConnectionConnectedPromiseReject",null);u(this,"_peerConnection",null);u(this,"_emitter",new zl.default);u(this,"_currentState","DISCONNECTED");u(this,"_isReconnecting",!1);u(this,"_reconnectionCount",0);u(this,"_reconnectionTimer",-1);u(this,"_isFirstConnection",!0);u(this,"_prevTime",-1);u(this,"_localAddress");u(this,"_remoteAddress");this.userId=i.userId,this.tinyId=i.tinyId,this._room=i.room,this._sdpSemantics=i.room.sdpSemantics,this._isUplink=i.isUplink,this._log=I.createLogger({id:"n-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=i.signalChannel}beforeConnect(){this._prevTime<0&&(this._prevTime=x())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,D.addSuccessEvent({key:521705,cost:Math.min(x()-this._prevTime,30*1e3)})):this._isReconnecting&&D.addSuccessEvent({key:521706,cost:x()-this._prevTime}),this._prevTime=-1}catch(i){throw this._isFirstConnection?(this._isFirstConnection=!1,D.addFailedEvent({key:521705,error:i})):this._isReconnecting&&this._reconnectionCount>=3&&D.addFailedEvent({key:521706,error:i}),i}}initialize(){let i={iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"};this._peerConnection=new RTCPeerConnection(i),this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this)}close(i){this._log.info("close connection"),this._emitter.emit("closed",i),this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),Kn.delete(this)}closePeerConnection(i=!1){this._peerConnection&&(this._log.info("close pc"),this._peerConnection.onconnectionstatechange=null,this._peerConnection.close(),this._peerConnection=null,i&&this.emitConnectionStateChangedEvent("DISCONNECTED")),this._waitForPeerConnectionConnectedPromiseReject&&this._waitForPeerConnectionConnectedPromiseReject(new b({code:A.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return nt;let i=null;if(this._isUplink){if(!Ri()||this._peerConnection.getSenders().length===0)return nt;i=this._peerConnection.getSenders()[0].transport}else{if(!$i()||this._peerConnection.getReceivers().length===0)return nt;i=this._peerConnection.getReceivers()[0].transport}return i?i.state:nt}onConnectionStateChange(i){let e=this._peerConnection.iceConnectionState,t=this.getDTLSTransportState();if(this._log.info(`connectionState: ${i.target.connectionState}, ICE: ${e}, DTLS: ${t}`),i.target.connectionState===se.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),i.target.connectionState===se.FAILED||i.target.connectionState===se.CLOSED){let s=`connection ${i.target.connectionState}. ICE Transport state: ${e}, DTLS Transport state: ${t}`,o=new b({message:s,code:A.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",o)}(i.target.connectionState===se.CONNECTED||i.target.connectionState===se.COMPLETED)&&(this.logSelectedCandidate(),Z.logSuccessEvent({userId:this._room.userId,eventType:Ve.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(i){return i===this._currentState?!1:(i==="CONNECTED"?(Td=0,Sd=!1,Id=!0,Kn.add(this)):Kn.delete(this),g.emit(E.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:i,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:i}),this._currentState=i,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}logSelectedCandidate(){return _(this,null,function*(){if(!this._peerConnection)return;let i=yield this._peerConnection.getStats();for(let[,e]of i)if(Ci(e)){let t=i.get(e.localCandidateId),s=i.get(e.remoteCandidateId);t&&(this._log.info(`local candidate: ${t.candidateType} ${t.protocol}:${t.ip||t.address}:${t.port} ${t.networkType||""} ${t.candidateType==="relay"?`relayProtocol:${t.relayProtocol}`:""}`),this._localAddress=`${t.ip||t.address}:${t.port}`),s&&(this._log.info(`remote candidate: ${s.candidateType} ${s.protocol}:${s.ip||s.address}:${s.port}`),this._remoteAddress=`${s.protocol}:${s.ip||s.address}`);break}})}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise?this._waitForPeerConnectionConnectedPromise:(this._waitForPeerConnectionConnectedPromise=new Promise((i,e)=>{if(this._currentState==="CONNECTED")return i();this._waitForPeerConnectionConnectedPromiseReject=e;let t=a=>{a.state==="CONNECTED"&&(clearTimeout(n),o(),i())},s=({room:a})=>{a===this._room&&(clearTimeout(n),o(),e(new b({code:A.API_CALL_ABORTED,message:L({key:M.CONNECTION_ABORTED,data:"leave room"})})))},o=()=>{g.off(E.LEAVE_SUCCESS,s,this),this._emitter.off("connection-state-changed",t,this)},n=setTimeout(()=>{o();let a=new b({code:A.API_CALL_TIMEOUT,message:"connection timeout"});Td+=1,O_(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),Sd=!0,this._emitter.emit("firewall-restriction")),e(a)},as);g.on(E.LEAVE_SUCCESS,s,this),this._emitter.on("connection-state-changed",t,this)}),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally(()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null}),this._waitForPeerConnectionConnectedPromise)}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(_e.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=qt()){this._log.warn(`SDK has tried reconnect for ${this._reconnectionCount} times, but all failed, please check your network`),this.stopReconnection();let i=new b({code:this._isUplink?A.UPLINK_RECONNECTION_FAILED:A.DOWNLINK_RECONNECTION_FAILED,message:L({key:this._isUplink?M.UPLINK_RECONNECTION_FAILED:M.DOWNLINK_RECONNECTION_FAILED})});return this.emitConnectionStateChangedEvent("DISCONNECTED"),this._emitter.emit("error",i),-1}return this._signalChannel.isConnected?(this._reconnectionCount+=1,this._log.warn(`reconnect() trying [${this._reconnectionCount}]`),1):(this._log.warn("reconnect() signal channel is not connected, suspend reconnection until signal is connected"),this._signalChannel.once(_e.CONNECTED,this.reconnect,this),-1)}on(i,e,t){this._emitter.on(i,e,t)}off(i,e,t){this._emitter.off(i,e,t)}getIsReconnecting(){return this._isReconnecting}get isH264(){var i,e;return!!((e=(i=this._peerConnection)==null?void 0:i.remoteDescription)!=null&&e.sdp.includes("H264"))}};var yd=Se(Rd());var ce=function(r){return yd.default.parse(r)},He=function(r){return yd.default.write(r)},sh=function(r){let i=ce(r);return i.media.forEach(e=>{e.type===h.AUDIO&&e.fmtp.forEach(t=>{t.config+=";sprop-stereo=1;stereo=1"})}),He(i)};function oh(r){let i=ce(r);return i.media.forEach(e=>{var t,s;if(e.type===h.VIDEO){let o=new Set;e.rtp.forEach(({payload:a,codec:c})=>c==="H264"&&o.add(a)),e.fmtp.forEach(({payload:a,config:c})=>{let d=c.match(/apt=(\d+)/);d&&d[1]&&o.has(Number(d[1]))&&o.add(a)});let n=({payload:a})=>!o.has(a);e.rtp=e.rtp.filter(n),e.rtcpFb=(t=e.rtcpFb)==null?void 0:t.filter(n),e.fmtp=e.fmtp.filter(n),e.payloads=(s=e.payloads)==null?void 0:s.split(" ").filter(a=>!o.has(Number(a))).join(" ")}}),He(i)}function Zn(r){return Object.keys(r).filter(i=>r[i])}var Nd=class extends Ke{constructor(e){super(P(N({},e),{isUplink:!1}));u(this,"_flag",0);u(this,"role","anchor");u(this,"remoteAudioTrack");u(this,"remoteVideoTrack");u(this,"remoteAuxiliaryTrack");u(this,"ssrc",{audio:0,video:0,auxiliary:0});u(this,"_isSDPExchanging",!1);this.flag=e.flag,this.remoteAudioTrack=e.remoteAudioTrack||new oi(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new Tt(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new Vr(this._room,this)}get videoCodec(){var t,s;let e=(s=(t=this._peerConnection)==null?void 0:t.remoteDescription)==null?void 0:s.sdp;return e?e.includes("H264")?"h264":"vp8":"h264"}get subscribeState(){let e={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(this.remoteVideoTrack.mediaType&8?e.smallVideo=!0:e.video=!0),this.remoteAudioTrack.isSubscribed&&(e.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(e.auxiliary=!0),e}get muteState(){return Ai(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,s,o;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(s=this.remoteVideoTrack)==null||s.onFlagChanged(),(o=this.remoteAuxiliaryTrack)==null||o.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===h.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var o,n;let t=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&t!==e&&((o=this.remoteVideoTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),s}onTrack(e){let t=e.streams[0],{track:s}=e,o=t.id===ns?h.MAIN:h.AUXILIARY;this._log.debug(`ontrack ${o} ${s.kind}`);let n=h.AUDIO;s.kind===h.VIDEO&&(n=o===h.MAIN?h.VIDEO:h.AUXILIARY);let a=this.remoteAudioTrack;n===h.VIDEO?a=this.remoteVideoTrack:n===h.AUXILIARY&&(a=this.remoteAuxiliaryTrack),a.setInputMediaStreamTrack(s)}addRRTRLine(e){let t=e.split(`\r