trtc-sdk-v5 5.15.1-beta.6 → 5.15.1-beta.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/plugins/cdn-streaming/package.json +1 -1
- package/plugins/chorus/package.json +1 -1
- package/plugins/cross-room/package.json +1 -1
- package/plugins/custom-encryption/package.json +1 -1
- package/plugins/device-detector/package.json +1 -1
- package/plugins/lebplayer/package.json +1 -1
- package/plugins/realtime-transcriber/package.json +1 -1
- package/plugins/small-stream-auto-switcher/package.json +1 -1
- package/plugins/video-decoder/package.json +1 -1
- package/plugins/video-effect/basic-beauty/package.json +1 -1
- package/plugins/video-effect/beauty/package.json +1 -1
- package/plugins/video-effect/face-detection/package.json +1 -1
- package/plugins/video-effect/video-mixer/package.json +1 -1
- package/plugins/video-effect/virtual-background/package.json +1 -1
- package/plugins/video-effect/watermark/package.json +1 -1
- package/plugins/voice-changer/package.json +1 -1
- package/trtc.esm.js +2 -2
- package/trtc.js +1 -1
package/trtc.esm.js
CHANGED
|
@@ -49,7 +49,7 @@ uniform sampler2D u_texture;
|
|
|
49
49
|
|
|
50
50
|
void main() {
|
|
51
51
|
gl_FragColor = texture2D(u_texture, v_texCoord);
|
|
52
|
-
} `;var Rs=class extends Y{constructor(e){super();d(this,"frameRate");d(this,"_canvas");d(this,"log");d(this,"hasAlpha",!1);d(this,"name");d(this,"error");this.name=e.name,this.log=e.logger.createChild({id:`vc-${this.name}`}),this.frameRate=e.frameRate}get canvas(){return this._canvas}set width(e){this._canvas&&(this._canvas.width=e)}get width(){var e;return((e=this._canvas)==null?void 0:e.width)||0}set height(e){this._canvas&&(this._canvas.height=e)}get height(){var e;return((e=this._canvas)==null?void 0:e.height)||0}setSize(e,t){this._canvas&&(this._canvas.width=e,this._canvas.height=t)}createVideoTrackSource(e,t){return new zt(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new No(this,e)}createVideoImageSource(e,t){return new ra(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new sa(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}createTextSource(e,t){return new gd(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}};d(Rs,"_ids",0);var Do=class Do extends Rs{constructor(){super(...arguments);d(this,"defaultProgam");d(this,"defaultVShader");d(this,"defaultFShader");d(this,"ctx");d(this,"_canvas2d")}get canvas(){return this._canvas2d||this._canvas}create(e=!1){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${Rs._ids++}`),e&&(this._canvas2d=document.createElement("canvas")),this.ctx=this._canvas.getContext("webgl2",yl),!this.ctx)throw new N({code:I.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,US),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,VS),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new N({code:I.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})}destroy(e){let t="";return e&&(t=e.message,this.error=e,y.addFailedEvent({key:512702,error:e})),this.disconnect(),this.log.info(`video context destroy${t}`?`: ${t}`:""),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),e}set width(e){var t;(t=this.ctx)==null||t.viewport(0,0,e,this.height),super.width=e,this._canvas2d&&(this._canvas2d.width=e)}set height(e){var t;(t=this.ctx)==null||t.viewport(0,0,this.width,e),super.height=e,this._canvas2d&&(this._canvas2d.height=e)}setSize(e,t){var r;(r=this.ctx)==null||r.viewport(0,0,e,t),super.setSize(e,t),this._canvas2d&&(this._canvas2d.width=e,this._canvas2d.height=t)}createShader(e,t){let r=this.ctx,o=r.createShader(e);return r.shaderSource(o,t),r.compileShader(o),o}createProgram(e,t){let r=this.ctx,o=r.createProgram();return r.attachShader(o,e),r.attachShader(o,t),r.linkProgram(o),r.getProgramParameter(o,r.LINK_STATUS)||this.log.error(r.getProgramInfoLog(o)),o}};d(Do,"UNAVAILABLE","unavailable"),O([ve(Y.INIT,"created",{sync:!0,fail(e){this.log.error("video gl context create failed",e.cause),y.addFailedEvent({key:512700,error:e.cause||e})},success(){this.log.info("video context created use webgl"),y.addSuccessEvent({key:512700})}})],Do.prototype,"create",1),O([ve("created",Y.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(Do.UNAVAILABLE,e),this.removeAllListeners()}})],Do.prototype,"destroy",1);var $e=Do,Qe=class extends Rs{constructor(){super(...arguments);d(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${Rs._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:e.alpha,willReadFrequently:e.willReadFrequently}),!this.ctx)throw new N({code:I.VIDEO_MANAGER_ERROR,extraCode:2,message:"2d context not supported"});this._canvas.addEventListener("contextlost",()=>{this.log.error("2d context lost")}),this._canvas.addEventListener("contextrestored",()=>{this.log.warn("2d context restored")})}destroy(e){let t="";e&&(t=e.message,this.error=e,y.addFailedEvent({key:512703,error:e})),this.disconnect(),this.log.info(`video context destroy ${t?`: ${t}`:""}`),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners(),y.addSuccessEvent({key:512703})}};O([ve(Y.INIT,"created",{sync:!0,fail(e){this.log.error("video 2d context create failed",e.cause),y.addFailedEvent({key:512701,error:e.cause||e})},success(){this.log.info("video context created use 2d"),y.addSuccessEvent({key:512701})}})],Qe.prototype,"create",1),O([ve("created",Y.INIT,{ignoreError:!0,sync:!0})],Qe.prototype,"destroy",1);function FS(s,i,e,t,r,o=!1){o&&([e,t]=[t,e]);let n={sWidth:s,sHeight:i,dWidth:e,dHeight:t,sx:0,sy:0,dx:0,dy:0};if(s===0||i===0)return n;switch(r){case void 0:case"fill":break;case"contain":{let a=Math.min(e/s,t/i);n.dWidth=s*a,n.dHeight=i*a,n.dx=(e-n.dWidth)/2,n.dy=(t-n.dHeight)/2;break}case"cover":{let a=Math.max(e/s,t/i),c=e/a,l=t/a;n.sx=(s-c)/2,n.sy=(i-l)/2,n.sWidth=c,n.sHeight=l;break}}return n}var $h=class{constructor(i,e){this.node=i;this.layout=e;d(this,"positionBuffer")}get x(){return this.layout.x||this.node.x}get y(){return this.layout.y||this.node.y}get width(){return this.layout.width||this.node.width}get height(){return this.layout.height||this.node.height}get right(){return this.x+this.width}get bottom(){return this.y+this.height}get fillMode(){return this.layout.fillMode}get rotation(){return this.layout.rotation}get hidden(){return!!this.layout.hidden}},Mo=class extends we{constructor(e,t){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:t});d(this,"inputs",[]);d(this,"backgroundColor","black")}addInput(e,t){let r=0,o=this.inputs.length;for(;r<o;){let a=Math.floor((r+o)/2);if(this.inputs[a].layout.zIndex<t.zIndex)r=a+1;else if(this.inputs[a].layout.zIndex>t.zIndex)o=a;else throw new Error(`input already exists at zIndex ${t.zIndex}`)}let n=new $h(e,t);this.inputs.splice(r,0,n)}changeInputLayout(e,t){let r=this.inputs.findIndex(T=>T.node===e);if(r<0)return;let{x:o,y:n,width:a,height:c,zIndex:l,fillMode:u,rotation:m,hidden:p}=t;if(!E(l)&&this.inputs.some(T=>T.layout.zIndex===l&&T.node!==e))throw new Error(`input already exists at zIndex ${t.zIndex}`);let h=this.inputs[r];E(o)||(h.layout.x=o),E(n)||(h.layout.y=n),E(a)||(h.layout.width=a),E(c)||(h.layout.height=c),E(m)||(h.layout.rotation=m),E(p)||(h.layout.hidden=p),u&&(h.layout.fillMode=u),!E(l)&&l!==h.layout.zIndex&&(h.layout.zIndex=l,this.inputs.sort((T,g)=>T.layout.zIndex-g.layout.zIndex))}hasInput(e){return this.inputs.some(t=>t.node===e)}hasNoInput(){return this.inputs.length===0}resize(e,t){if(!this.matchInputSize){super.resize(e,t);return}let r=this.inputs.reduce((o,n)=>n?Object.assign(o,{width:Math.max(o.width,n.right),height:Math.max(o.height,n.bottom)}):o,{width:0,height:0});super.resize(r.width,r.height),this.context instanceof $e&&this.inputs.forEach(o=>{if(o){let n=this.layout2texCoords(o);o.positionBuffer?this.changeBufferData(o.positionBuffer,n):o.positionBuffer=this.createBuffer(n)}})}connect(e,...t){return super.connect(e,...t),this.drawBackGround2d(this.backgroundColor),this.matchInputSize&&this.resize(0,0),e}removeInput(e){this.inputs=this.inputs.filter(t=>t.node!==e),this.inputs.length===0&&this.drawBackGround2d(this.backgroundColor)}render(e){let t=this.context.ctx;if(t.clearColor(0,0,0,0),this.inputs.reduce((o,n)=>n.node.requestFrame(e)||o,!1)&&t){this.useProgram(),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let o=0;o<this.inputs.length;o++){let n=this.inputs[o];n&&(n.node.useTexture(),this.draw(n.positionBuffer))}return!0}return!1}render2d(e){if(this.inputs.forEach(t=>t.node.requestFrame(e)),this.ctx2d){this.drawBackGround2d(this.backgroundColor);for(let t=0;t<this.inputs.length;t++){let r=this.inputs[t];if(r.hidden)continue;let o=FS(r.node.width,r.node.height,r.width,r.height,r.fillMode,Nt(r.rotation));this.draw2d(r.node.image,r.x+o.dx,r.y+o.dy,o.dWidth,o.dHeight,o.sx,o.sy,o.sWidth,o.sHeight)}return!0}return!1}debugLayout(e,t,r,o,n=!1){this.ctx2d&&(n&&([r,o]=[o,r]),this.ctx2d.save(),this.ctx2d.strokeStyle="red",this.ctx2d.lineWidth=2,this.ctx2d.strokeRect(e,t,r,o),this.ctx2d.restore())}getInfo(){let{totalFrames:e,x:t,y:r,width:o,height:n,name:a}=this,c=Date.now(),l=(e-this.lastInfo.totalFrames)/((c-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:r,width:o,height:n,timestamp:c,fps:l,name:a},M({parent:this.inputs.filter(u=>u).map(u=>u.node.getInfo())},this.lastInfo)}removeAllInputs(){this.inputs.forEach(e=>{var t;if(e.node.disconnect(),e.positionBuffer&&this.context instanceof $e)try{(t=this.context.ctx)==null||t.deleteBuffer(e.positionBuffer)}catch(r){}})}close(){super.close(),this.removeAllInputs()}};var BS=[1,0,0,0,1,1,0,1],Qt=class extends we{constructor(e,t,r,o){super(e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"transform",logger:t});d(this,"mirror",!1);d(this,"rotation",0);if(r&&(this.mirror=r),o&&(this.rotation=o),e instanceof $e)try{this.setTexBuffer(BS)}catch(n){e.destroy(new N({code:I.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${n.message||n}`}))}}draw2d(e,t,r,o,n){if(this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height),this.ctx2d.save(),this.mirror&&(this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0)),this.rotation===90?(this.ctx2d.translate(o,0),this.ctx2d.rotate(Math.PI/2),this.ctx2d.scale(n/o,o/n)):this.rotation===180?(this.ctx2d.translate(this.width,this.height),this.ctx2d.rotate(Math.PI)):this.rotation===270&&(this.ctx2d.translate(0,n),this.ctx2d.rotate(3*Math.PI/2),this.ctx2d.scale(n/o,o/n));let a=super.draw2d(e,t,r,o,n);return this.ctx2d.restore(),a}return!1}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}resize(e,t){Nt(this.rotation)&&([e,t]=[t,e]),super.resize(e,t)}};var Cs=class extends Ei{constructor(e,t=4){super(t,rt);d(this,"inputLocalVideoTracks",new Map);d(this,"inputLocalScreenTracks",new Map);d(this,"cameraNodeMap",new Map);d(this,"screenNodeMap",new Map);d(this,"textNodeMap",new Map);d(this,"imageNodeMap",new Map);d(this,"videoNodeMap",new Map);d(this,"endedIds",new Set);d(this,"videoContext");d(this,"mixNode");d(this,"destination");d(this,"manager");d(this,"stat");d(this,"_checkId",0);d(this,"autoSetFps",!0);this.manager=e,this.log.id+="mix",this.create2dVideoContext(),this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log}),this.destination.on(we.RENDER,r=>{this.emit("render",r)}),this.mixNode=new Mo(this.videoContext,this.log),this.mixNode.matchInputSize=!1}listenDeviceChange(){throw new Error("Method not implemented.")}enablePrintDetail(e=2e3){this._checkId=ce.run("interval",()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:e})}create2dVideoContext(){this.videoContext?this.videoContext.destroy():this.videoContext=new Qe({frameRate:15,logger:this.log,name:"mix-ctx"}),this.videoContext.create({alpha:!1})}setFps(e){this.autoSetFps=!1,this.videoContext.frameRate=e;for(let t of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])t.shouldUpdate=!1;setTimeout(()=>{var t;return(t=this.destination)==null?void 0:t.start(this.videoContext.frameRate)},500)}setFpsAuto(){var o;if(!this.autoSetFps)return;for(let n of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])n.shouldUpdate=!1;let e=null,t=0,r=!0;for(let[n,a]of this.inputLocalVideoTracks)if(a.profile.frameRate>t){if(this.endedIds.has(n)){let c=this.cameraNodeMap.get(n);c&&c.image.cancelVideoFrameCallback(c.videoCallbackId);continue}t=a.profile.frameRate,e=n}for(let[n,a]of this.inputLocalScreenTracks)if(a.profile.frameRate>t){if(this.endedIds.has(n)){let c=this.screenNodeMap.get(n);c&&c.image.cancelVideoFrameCallback(c.videoCallbackId);continue}t=a.profile.frameRate,e=n,r=!1}if(e!==null){let n=r?this.cameraNodeMap.get(e):this.screenNodeMap.get(e);n&&(n.shouldUpdate=!0,n.tryVideoFrameCallback()),this.log.info("set mix fps: ",t)}else(o=this.destination)==null||o.start(this.videoContext.frameRate),this.log.info("fallback to timer, fps: ",this.videoContext.frameRate)}setMixBackground(e){this.mixNode&&(this.mixNode.backgroundColor=e)}resizeMixCanvas(e,t){var r;(r=this.mixNode)==null||r.resize(e,t)}startMix(){return f(this,null,function*(){var e;if(!this.mixNode||!this.destination)throw new Error("can't mix without necessary conditions");this.mixNode.disconnect(),this.mixNode.connect(this.destination),Gt&&this.player.setCanvas(this.videoContext._canvas),this.setOutputMediaStreamTrack(this.destination.videoTrack),(e=this.manager)==null||e.changeInput(this)})}addCameraSource(e,t,r){if(this.inputLocalVideoTracks.has(e)||this.cameraNodeMap.has(e))throw new Error(`There is already a cameraSource with the same ID: ${e}`);let{mediaTrack:o}=t;if(!o)throw new Error("no mediaTrack, add cameraSource failed");t.recaptureMode=1,it(this,Ne).add("videoInputRemoved",a=>{a.deviceId===t.deviceId&&(this.endedIds.add(e),this.setFpsAuto())}),t.on("output-media-track-changed",()=>{this.endedIds.delete(e),this.updateCameraSource(e,r,t.mediaTrack)});let n;qe===16&&o instanceof CanvasCaptureMediaStreamTrack?n=this.videoContext.createVideoImageSource(o.canvas,{name:"cameraCanvasSource",logger:this.log}):n=this.videoContext.createVideoTrackSource(o,"cameraNodeSource"),n.resize(t.settings.width,t.settings.height),n.shouldUpdate=!1,this._connectMix(n,r,"cover"),this.inputLocalVideoTracks.set(e,t),this.cameraNodeMap.set(e,n),this.setFpsAuto()}addScreenSource(e,t,r){if(this.inputLocalScreenTracks.has(e)||this.screenNodeMap.has(e))throw new Error(`There is already a screenSource with the same ID: ${e}`);let{mediaTrack:o}=t;if(!o)throw new Error("no mediaTrack, add screenSource failed");t.on("output-media-track-changed",()=>{this.updateScreenSource(e,r,t.mediaTrack)});let n=this.videoContext.createVideoTrackSource(o,"screenNodeSource");n.resize(t.settings.width,t.settings.height),n.shouldUpdate=!1,this._connectMix(n,r),this.inputLocalScreenTracks.set(e,t),this.screenNodeMap.set(e,n),this.setFpsAuto()}addTextSource(e){let{id:t,content:r="",font:o,color:n,layout:a}=e;if(this.textNodeMap.has(t))throw new Error(`There is already a textSource with the same ID: ${t}`);let c=this.videoContext.createTextSource({content:r,font:o,color:n});c.resize(a.width,a.height),this._connectMix(c,a),this.textNodeMap.set(t,c)}addImageSource(e,t,r){if(this.imageNodeMap.has(e))throw new Error(`There is already a imageSource with the same ID: ${e}`);let o=this.videoContext.createVideoImageSource(t,{autoResize:!1,logger:this.log});o.resize(t.width,t.height),this._connectMix(o,r),this.imageNodeMap.set(e,o)}addVideoSource(e,t,r){if(this.videoNodeMap.has(e))throw new Error(`There is already a videoSource with the same ID: ${e}`);let o=this.videoContext.createVideoImageSource(t,{autoResize:!1,logger:this.log});o.resize(t.videoWidth,t.videoHeight),o.shouldUpdate=!1,this._connectMix(o,r),this.videoNodeMap.set(e,o)}updateCameraSource(e,t,r=null,o){let n=this.cameraNodeMap.get(e);if(n){if(r){if(qe===16&&r instanceof CanvasCaptureMediaStreamTrack)if(n instanceof zt){let l=n.output;n.close(),n=this.videoContext.createVideoImageSource(r.canvas,{name:"cameraCanvasSource",logger:this.log}),n.connect(l),this.cameraNodeMap.set(e,n)}else n.image=r.canvas;else if(n instanceof zt)n.replaceTrack(r);else{let l=n.output;n.close(),n=this.videoContext.createVideoTrackSource(r,"cameraNodeSource"),n.connect(l),this.cameraNodeMap.set(e,n)}let{width:a,height:c}=r.getSettings();a&&c&&n.resize(a,c)}o&&n.resize(o.width,o.height),(o||r)&&this.setFpsAuto(),this._changeMixLayout(n,t)}}updateScreenSource(e,t,r=null){let o=this.screenNodeMap.get(e);o&&(r&&o.replaceTrack(r),this._changeMixLayout(o,t))}updateTextSource(e){let{id:t,content:r,font:o,color:n,layout:a}=e,c=this.textNodeMap.get(t);c&&(E(r)||(c.content=r),E(o)||(c.font=o),E(n)||(c.color=n),c.resize(a.width,a.height),this._changeMixLayout(c,a))}updateImageSource(e,t,r){let o=this.imageNodeMap.get(e);o&&(r&&(o.image=r,o.resize(r.width,r.height)),this._changeMixLayout(o,t))}updateVideoSource(e,t,r){let o=this.videoNodeMap.get(e);if(o){if(r){let n=o.image;n instanceof HTMLVideoElement&&this.stopVideoElement(n),o.image=r,o.resize(r.videoWidth,r.videoHeight)}this._changeMixLayout(o,t)}}_connectMix(e,t,r="contain"){if(!this.mixNode)return;let{mirror:o,rotation:n}=t;e.disconnect();let a=new Qt(this.videoContext,this.log,o,n);a=e.connect(a),t.fillMode||(t.fillMode=r),a.connect(this.mixNode,t)}_changeMixLayout(e,t){if(!this.mixNode)return;let{mirror:r,rotation:o}=t,n=e.output||e;n instanceof Qt&&(E(r)||(n.mirror=r),E(o)||(n.rotation=o),n.resize(e.width,e.height)),this.mixNode.changeInputLayout(n,t)}removeCameraSource(e){let t=this.inputLocalVideoTracks.get(e);if(!t)return;t.close(),this.inputLocalVideoTracks.delete(e);let r=this.cameraNodeMap.get(e);r&&(r.output instanceof Qt&&r.output.close(),r.close(),this.cameraNodeMap.delete(e)),this.checkAfterRemove(!0)}removeScreenSource(e){let t=this.inputLocalScreenTracks.get(e);if(!t)return;t.close(),this.inputLocalScreenTracks.delete(e);let r=this.screenNodeMap.get(e);r&&(r.output instanceof Qt&&r.output.close(),r.close(),this.screenNodeMap.delete(e)),this.checkAfterRemove(!0)}removeTextSource(e){let t=this.textNodeMap.get(e);t&&(t.output instanceof Qt&&t.output.close(),t.close(),this.textNodeMap.delete(e)),this.checkAfterRemove()}removeImageSource(e){let t=this.imageNodeMap.get(e);t&&(t.output instanceof Qt&&t.output.close(),t.close(),this.imageNodeMap.delete(e)),this.checkAfterRemove()}removeVideoSource(e){let t=this.videoNodeMap.get(e);t&&(t.output instanceof Qt&&t.output.close(),t.image instanceof HTMLVideoElement&&this.stopVideoElement(t.image),t.close(),this.videoNodeMap.delete(e)),this.checkAfterRemove()}checkAfterRemove(e=!1){e&&this.setFpsAuto()}stopVideoElement(e){e.pause(),e.src="",e.srcObject=null,e.remove()}close(){var e;super.close(),ce.clearTask(this._checkId),(e=this.videoContext)==null||e.destroy(),delete this.mixNode,delete this.destination;for(let t of[...this.inputLocalVideoTracks.values(),...this.inputLocalScreenTracks.values()])t.close();this.inputLocalVideoTracks.clear(),this.inputLocalScreenTracks.clear(),this.cameraNodeMap.clear(),this.screenNodeMap.clear(),this.textNodeMap.clear(),this.imageNodeMap.clear(),Fe(this);for(let t of this.videoNodeMap.values())t.image instanceof HTMLVideoElement&&this.stopVideoElement(t.image);this.videoNodeMap.clear(),this.log.info("localMixVideoTrack close, stop mix")}};var Td=Cn();if(typeof navigator!="undefined"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:Td,exposeOrigin:!0,permittedOrigins:["*"]})}catch(s){}var HS=function(s){return f(this,null,function*(){let i=null,e=GS(s);C.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let t=yield navigator.mediaDevices.getDisplayMedia(e);s.systemAudio&&t.getAudioTracks().length===0&&(ao&&et<74||ye||re)&&C.warn("Your browser not support capture system audio");let r=t.getVideoTracks()[0];if(r){if(s.frameRate)try{yield r.applyConstraints({frameRate:{min:s.frameRate,ideal:s.frameRate},width:s.width,height:s.height})}catch(o){C.warn(`screen applyConstraints failed: ${o}`)}s.captureElement&&(yield $S(r,s.captureElement))}if(s.audio){let o=WS(s);C.info(`getUserMedia with constraints: ${JSON.stringify(o)}`),i=yield navigator.mediaDevices.getUserMedia(o),t.addTrack(i.getAudioTracks()[0])}return t})};function $S(s,i){return f(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&me(s.cropTo))try{if(!(((e=s.getCaptureHandle())==null?void 0:e.handle)===Td))return;let r=yield CropTarget.fromElement(i);yield s.cropTo(r)}catch(t){C.warn(`cropTo target failed ${t}`)}})}function WS(s){let i={echoCancellation:s.echoCancellation,autoGainControl:s.autoGainControl,noiseSuppression:s.noiseSuppression,sampleRate:s.sampleRate,channelCount:s.channelCount};return E(s.microphoneId)||(i.deviceId=s.microphoneId),{audio:i,video:!1}}function GS(s){let i={preferCurrentTab:s.preferDisplaySurface==="current-tab"||!!s.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:ye?{max:s.width}:{ideal:s.width,max:s.width},height:ye?{max:s.height}:{ideal:s.height,max:s.height},frameRate:s.frameRate,displaySurface:s.preferDisplaySurface||"monitor"};if(i.video=e,s.systemAudio){let{echoCancellation:t=!0,noiseSuppression:r=!1,autoGainControl:o=!1}=s;i.audio={echoCancellation:t,noiseSuppression:r,autoGainControl:o,sampleRate:48e3}}return i}var Uf=HS;var xt=class extends ze{constructor(e){super(e,2);d(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600});d(this,"objectFit","contain");d(this,"isScreen",!0);this._log.id=`s-${this._log.id}`}get isShareCurrentTab(){var e,t;try{return Td===((t=(e=this.mediaTrack)==null?void 0:e.getCaptureHandle())==null?void 0:t.handle)}catch(r){return}}capture(u){return f(this,arguments,function*({systemAudio:e=!1,autoGainControl:t,echoCancellation:r,noiseSuppression:o,audioTrack:n,videoTrack:a,captureElement:c,preferDisplaySurface:l}){try{let m=x(),p;return a||n?(p=new MediaStream,a&&p.addTrack(a),n&&p.addTrack(n)):(p=yield Uf({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:t,echoCancellation:r,noiseSuppression:o,captureElement:c,preferDisplaySurface:l}),this.sourceTrack=p.getVideoTracks()[0]),yield this.setInputMediaStreamTrack(p.getVideoTracks()[0]),S.emit(A.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:x()-m}),p}catch(m){throw this.log.error(`getDisplayMedia error observed ${m}`),m instanceof N?m:new N({code:I.INITIALIZE_FAILED,name:m.name,message:m.message})}})}switchDevice(e){return f(this,null,function*(){throw new Error("Method not implemented.")})}};O([Ct(function(e){this.setContentHint(e.contentHint||"detail")})],xt.prototype,"capture",1);var ys=class extends wt{constructor(i){super(i),this._log.id=`s-${this._log.id}`,this.isScreen=!0}addAudioProcessor(i,e,t){this.pipeline.silentNode.setNode(t),this.pipeline.mixNode.setNode(e),this.pipeline.aec.setNode(i),this.enableTrackAEC(!1)}removeAudioProcessor(i){this.pipeline.aec.node===i&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode(),this.enableTrackAEC(!0))}};var JS='registerProcessor("dumper",class extends AudioWorkletProcessor{constructor(e){super(),this.sourceSampleRate=e.processorOptions.sourceSampleRate||48e3,this.targetSampleRate=e.processorOptions.targetSampleRate||48e3,this.port.onmessage=e=>{this.port2=e.data.port}}process(e){return(this.port2||this.port).postMessage(this.resampleAll(e,this.sourceSampleRate,this.targetSampleRate)),!0}resampleAll(r,s,a){if(s===a)return r;var o=[];for(let t=0;t<r.length;t++){o[t]=[];for(let e=0;e<r[t].length;e++)o[t][e]=this.resample(r[t][e],s,a)}return o}resample(t,e,r){if(e===r)return t;var s=Math.round(t.length*(this.targetSampleRate/this.sourceSampleRate)),a=new Float32Array(s),o=(t.length-1)/(s-1);a[0]=t[0];for(let e=1;e<s-1;e++){var l=e*o,p=Math.floor(l),h=Math.ceil(l);a[e]=t[p]+(t[h]-t[p])*(l-p)}return a[s-1]=t[t.length-1],a}});',Wh;function oa(s,i=48e3,e=1,t){return f(this,null,function*(){let r=Ae("dump");Wh||(Wh=sr(r,URL.createObjectURL(new Blob([JS],{type:"application/javascript"})))),yield Wh;let o=r.sampleRate,n=new AudioWorkletNode(r,"dumper",{numberOfInputs:s.length,numberOfOutputs:0,processorOptions:{sourceSampleRate:o,targetSampleRate:i}});return n.channelCountMode="explicit",n.channelCount=e,t&&n.port.postMessage({port:t},[t]),s.forEach((a,c)=>a.connect(n,0,c)),new ReadableStream({start(a){n.port.onmessage=c=>{a.enqueue(c.data)}},cancel(){s.forEach(a=>a.disconnect(n)),n.port.close()}})})}var Ed=class extends Gc{constructor(e){super();this.room=e;d(this,"_localAudioTrack");d(this,"_localScreenAudioTrack");d(this,"log");d(this,"denoiser");d(this,"voiceChanger");d(this,"mixChangedDebounce");d(this,"audioProcessor");d(this,"encodePipeline",[]);d(this,"decodePipeline",[]);d(this,"getPCMAbortCtrlMap",new Map);d(this,"audioFrameEventConfigMap",new Map);d(this,"audioReferenceMap",new Map);d(this,"isLocalAudioNeedAudioProcess",!1);d(this,"isScreenAudioNeedAudioProcess",!1);this.log=C.createLogger({parent:e==null?void 0:e.getLogger(),id:"am",userId:e==null?void 0:e.userId,sdkAppId:e==null?void 0:e.sdkAppId}),this.installEvent()}get localAudioTrack(){return this._localAudioTrack}get _localAudioPipline(){var e;return(e=this._localAudioTrack)==null?void 0:e.pipeline}get _localScreenAudioPipeline(){var e;return(e=this._localScreenAudioTrack)==null?void 0:e.pipeline}dump(e){var u,m;if(!this._localAudioTrack)return;let t=[],r=[];(u=this._localAudioPipline)!=null&&u.source.node&&(t.push(this._localAudioPipline.source.node),r.push("mic")),(m=this._localAudioPipline)!=null&&m.denoiser.node&&(t.push(this._localAudioPipline.denoiser.node),r.push("mic-processed")),this.mixWeight>1&&(t.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),r.push("mix")),this.log.info(`dump audio track ${r}, duration: ${e}`);let o=new AbortController,n=[],a=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),o.abort("timeout")},e*1e3),c=()=>{for(let p=0;p<r.length;p++){let h=URL.createObjectURL(new Blob(n[p])),T=document.createElement("a");T.href=h,T.download=`${r[p]}.pcm`,T.style.display="none",document.body.appendChild(T),T.click(),URL.revokeObjectURL(h),T.remove()}clearTimeout(a),o.abort("download")},l=oa(t).then(p=>p.pipeTo(new WritableStream({write(h){h.forEach((T,g)=>n[g]=n[g]?n[g].concat(T[0]):[T[0]])}}),o).catch(h=>c));return{then:l.then.bind(l),download:c}}getPCM(e,t){var D,j,V;if(typeof WritableStream=="undefined"){this.log.warn("getPCM failed: browser not support WritableStream");return}let{enable:r,sampleRate:o=48e3,channelCount:n=1,port:a}=(t===""?this.audioFrameEventConfigMap.get(""):this.audioFrameEventConfigMap.get(t)||this.audioFrameEventConfigMap.get("*"))||{};if(!r)return;this.log.info(`getPCM ${t||"local"}`);let c=Math.floor(o*.04),l=new Float32Array(c),u=new Float32Array(c),m,p,h=0,T=new AbortController,g=t===""?(D=this._localAudioTrack)==null?void 0:D.mediaTrack:(V=(j=this.room)==null?void 0:j.remotePublishedUserMap.get(t))==null?void 0:V.remoteAudioTrack.mediaTrack;if(!g){this.log.info(`getPCM failed: ${t||"local"} has no audio track`);return}let R=Ae().createMediaStreamSource(new MediaStream([g]));return oa([R],o,n,a).then(ae=>ae.pipeTo(new WritableStream({write(b){b[0][0]&&(h+b[0][0].length>c?(l.set(b[0][0].subarray(0,c-h),h),m=b[0][0].subarray(c-h),b[0][1]&&(u.set(b[0][1].subarray(0,c-h),h),p=b[0][1].subarray(c-h)),h+=c-h):(m&&(l.set(m,h),h+=m.length,m=void 0),p&&(u.set(p,h),p=void 0),l.set(b[0][0],h),b[0][1]&&u.set(b[0][1],h),h+=b[0][0].length),h>=c&&(h=0,e({userId:t,sampleRate:o,channelCount:n,data:n===1?l:[l,u]}),l=new Float32Array(c),u=new Float32Array(c)))}}),T).catch(b=>this.log.warn(`stop getPCM reason:${b}`))),T}get hasScreenAudioTrack(){return!E(this._localScreenAudioTrack)}get hasAudioTrack(){return!E(this._localAudioTrack)}changeInput(e){var t,r;if(e instanceof ys)return this._localScreenAudioTrack=e,this.isScreenAudioNeedAudioProcess&&((t=this.audioProcessor)!=null&&t.screenAudioWorkletNode)&&(e.addAudioProcessor(this.audioProcessor.screenAudioWorkletNode,this.audioProcessor.mixNode,this.audioProcessor.silentNode),this.audioReferenceMap.forEach((o,n)=>{e.mixAudioReference(o,n)})),e.pipeline.connect(),this.mixOnChange();if(e instanceof wt)return this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),this.isLocalAudioNeedAudioProcess&&((r=this.audioProcessor)!=null&&r.localAudioWorkletNode)&&(e.addAudioProcessor(this.audioProcessor.localAudioWorkletNode,this.audioProcessor.mixNode,this.audioProcessor.silentNode),this.audioReferenceMap.forEach((o,n)=>{e.mixAudioReference(o,n)})),e.pipeline.connect(),this.mixOnChange();if(e instanceof Ai)return e.setOutputMediaStreamTrack(e.mediaTrack)}mixAudioReference(e,t){var r;(r=this._localAudioTrack)==null||r.mixAudioReference(e,t)}unMixAudioReference(e){var t;(t=this._localAudioTrack)==null||t.unMixAudioReference(e)}setAudioReferenceVolume(e,t){var r;(r=this._localAudioTrack)==null||r.setAudioReferenceVolume(e,t)}mixOnChange(){return this.mixChangedDebounce||(this.mixChangedDebounce=Promise.resolve().then(()=>{var e,t;return delete this.mixChangedDebounce,Promise.all([(e=this._localAudioTrack)==null?void 0:e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),(t=this._localScreenAudioTrack)==null?void 0:t.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)])})),this.mixChangedDebounce}removeInput(e){e instanceof ys?delete this._localScreenAudioTrack:e instanceof wt?delete this._localAudioTrack:e instanceof Ai}addDenoiser(e){var t;this.denoiser=e,(t=this._localAudioTrack)==null||t.addDenoiser(e)}addAudioProcessor(e,t,r,o){var n;this.audioProcessor={localAudioWorkletNode:r,mixNode:e,silentNode:t,screenAudioWorkletNode:o},this.isLocalAudioNeedAudioProcess&&this._localAudioTrack&&r&&(this._localAudioTrack.addAudioProcessor(r,e,t),this.audioReferenceMap.forEach((a,c)=>{var l;(l=this._localAudioTrack)==null||l.mixAudioReference(a,c)})),this.isScreenAudioNeedAudioProcess&&this._localScreenAudioTrack&&o&&((n=this._localScreenAudioTrack)==null||n.addAudioProcessor(o,e,t),this.audioReferenceMap.forEach((a,c)=>{var l;(l=this._localScreenAudioTrack)==null||l.mixAudioReference(a,c)}))}removeDenoiser(e){var t;return delete this.denoiser,(t=this._localAudioTrack)==null?void 0:t.removeDenoiser(e)}addVoiceChanger(e,t){var r;this.voiceChanger=[e,t],(r=this._localAudioTrack)==null||r.pipeline.voiceChanger.setNode(e,t)}removeVoiceChanger(){var e;delete this.voiceChanger,(e=this._localAudioTrack)==null||e.pipeline.voiceChanger.deleteNode()}removeAudioProcessor(e,t){var r,o;delete this.audioProcessor,(r=this._localAudioTrack)==null||r.removeAudioProcessor(e),(o=this._localScreenAudioTrack)==null||o.removeAudioProcessor(t)}destroy(){this.close(),this.audioReferenceMap.clear(),this.getPCMAbortCtrlMap.forEach(e=>e==null?void 0:e.abort("destroy")),this.getPCMAbortCtrlMap.clear(),this.audioFrameEventConfigMap.clear(),this.uninstallEvent()}addEncodeProcessor({processor:e,type:t}){var r;this.encodePipeline.includes(e)||(this.encodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}addDecodeProcessor({processor:e,type:t}){var r;this.decodePipeline.includes(e)||(this.decodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}handleLocalTrackStarted({room:e,userId:t}){var o;if(e!==this.room||this.getPCMAbortCtrlMap.get(t))return;let r=this.getPCM(n=>{var a;(a=this.room)==null||a.emit("audio-frame",n)},"");this.getPCMAbortCtrlMap.set(t,r),this.getPCMAbortCtrlMap.get(t)&&((o=this._localAudioTrack)==null||o.on("input-media-track-changed",()=>{let n=this.getPCMAbortCtrlMap.get(t);n&&(n.abort("inputMediaTrackChanged"),n=this.getPCM(a=>{var c;(c=this.room)==null||c.emit("audio-frame",a)},""),this.getPCMAbortCtrlMap.set(t,n))}))}handleLocalTrackStopped({room:e,userId:t}){if(e!==this.room)return;let r=this.getPCMAbortCtrlMap.get(t);r&&(r.abort("stopLocalAudio"),this.getPCMAbortCtrlMap.delete(t))}handleRemoteTrackStarted({room:e,userId:t}){if(e===this.room&&!this.getPCMAbortCtrlMap.get(t)){let r=this.room.audioManager.getPCM(o=>{var n;(n=this.room)==null||n.emit("audio-frame",o)},t);this.getPCMAbortCtrlMap.set(t,r)}}handleRemoteTrackStopped({room:e,userId:t}){if(e!==this.room)return;let r=this.getPCMAbortCtrlMap.get(t);r&&(r.abort("stopRemoteAudio"),this.getPCMAbortCtrlMap.delete(t))}installEvent(){S.on("113",this.handleLocalTrackStarted,this),S.on("114",this.handleLocalTrackStopped,this),S.on("115",this.handleRemoteTrackStarted,this),S.on("116",this.handleRemoteTrackStopped,this)}uninstallEvent(){S.off("113",this.handleLocalTrackStarted),S.off("114",this.handleLocalTrackStopped),S.off("115",this.handleRemoteTrackStarted),S.off("116",this.handleRemoteTrackStopped)}updateAudioReference({type:e,audioReference:t,refId:r,volume:o}){if(e==="add"){if(this.audioReferenceMap.get(r)||!t||(this.audioReferenceMap.set(r,t),!this.audioProcessor))return;this.mixAudioReference(t,r)}else if(e==="remove")this.audioReferenceMap.get(r)&&(this.audioReferenceMap.delete(r),this.unMixAudioReference(r));else if(e==="updateVolume"){if(!this.audioProcessor||E(o))return;this.setAudioReferenceVolume(r,o)}}};function bs(s=30,i=2){return K((e,t)=>function(...r){return new Promise((o,n)=>{let a=setTimeout(()=>{let c=new N({code:I.API_CALL_TIMEOUT,message:`checkPendingPromise ${t}() timeout ${s}s`});(this.log||this._log||C).warn(c),i===2?n(c):i===1&&o()},s*1e3);this._checkPendingPromiseSet||(this._checkPendingPromiseSet=new Set),this._checkPendingPromiseSet.add(a),e.apply(this,r).then(o,n).finally(()=>{clearTimeout(a),this._checkPendingPromiseSet&&a&&this._checkPendingPromiseSet.delete(a)})})})}function Vf(){return K((s,i)=>function(...e){return this._checkPendingPromiseSet&&(this._checkPendingPromiseSet.forEach(t=>clearTimeout(t)),this._checkPendingPromiseSet.clear()),s.apply(this,e)})}var xi=class xi extends ps{constructor(e,t,r){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:r,room:e});this.room=e;this.user=t;d(this,"tinyId");d(this,"isRemote",!0);d(this,"jitterBufferDelay",0);d(this,"availableState");d(this,"remotePublishState");d(this,"_triggerCheckDecodeSubject",ot(ue(this,xi.STATE_SUBSCRIBE)));d(this,"ignoreUpdatePlayingState");this.tinyId=t.tinyId,this.availableState=new Y(`${t.userId}-${this.mediaType}-available`,"remote-track-available"),this.remotePublishState=new Y(`${t.userId}-${this.mediaType}-remote-publish`,"remote-track-publish"),he(Qn(ue(this,Y.STATECHANGED),ue(this.remotePublishState,Y.STATECHANGED)),ea(()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing)),Se(c=>{this.availableState.state!==(c?Y.ON:Y.OFF)&&(this.availableState.state=c?Y.ON:Y.OFF),!(this.isRemotePublished&&this.ignoreUpdatePlayingState)&&this.updatePlayingState(c)}));let o=he(ue(this.player,G.ERROR),Xt(c=>c.code===MediaError.MEDIA_ERR_DECODE)),n=he(Zn(5e3),Xt(()=>this.ignoreDecodeError||!this.isSubscribed||!this.isPlayCalled||!this.stat.bytesReceived||!this.isRemotePublished?!1:this.player.isPlaying||(this.kind===_.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)?(this.reportDecodeResult(!0),!1):!0)),a=he(rh(o,n),Le(ue(this,Y.INIT)));he(this._triggerCheckDecodeSubject,Xt(()=>!this.ignoreDecodeError),Ss(a),Se(c=>{this.reportDecodeResult(!1,c)}))}setMute(e){this.isRemotePublished&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.isRemotePublished&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}checkDecodeResult(){this._triggerCheckDecodeSubject.next(!0)}waitHasMediaTrack(){return new Promise(e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)})}get ignoreDecodeError(){var t,r,o,n;return((n=(o=(r=(t=this.room)==null?void 0:t.networkQuality)==null?void 0:r.hadRecentBadDownlink)==null?void 0:o.call(r,2))!=null?n:!1)||this.player.isInAutoPlayFailedState}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===xi.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===Y.ON}get isNeedPlay(){return this.isAvailable&&this.isPlayCalled}subscribe(e){return e}unsubscribe(){this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}reportDecodeResult(e,t){var o,n;let r=this.kind===_.AUDIO;if(y[e?"addSuccessEvent":"addFailedEvent"]({key:r?504700:514702}),!r){let a=((o=this.room)==null?void 0:o.downlinkVideoCodec.toUpperCase())||"H264";y[e?"addSuccessEvent":"addFailedEvent"]({key:mo[`DECODE_${a}_RESULT`]}),e||this.log.warn(`${(n=this.room)==null?void 0:n.downlinkVideoCodec} decode failed`)}e||(y.addEnum({key:r?504701:514703,value:as()}),se.uploadEvent({log:`stat-decode-failed-${this.kind}-${Dt()||Mt()}`,userId:this.room.userId}),this._log.warn(`decode failed: isPlaying: ${this.player.isPlaying} ${this.kind===_.AUDIO?`audioLevel: ${this.getAudioLevel()}`:`framesDecoded: ${this.stat.framesDecoded>0}`}`),this.emit("decode-failed",{error:t}))}updatePlayingState(e){if(this.player.isPlayCalled&&this.player.setTrack(this.playerMediaTrack),this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.isRemotePublished||!this.outMediaTrack)){this.log.info(`abort play, isSubscribed: ${this.isSubscribed} isAvailable: ${this.isRemotePublished} hasTrack: ${!!this.outMediaTrack} `);return}super.updatePlayingState(e)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.remotePublishState.state=this.isRemotePublished?Y.ON:Y.OFF,this.emit("remote-publish-changed",this.isRemotePublished)}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};d(xi,"STATE_SUBSCRIBE","subscribe"),O([bs(5,1)],xi.prototype,"waitHasMediaTrack",1),O([ve(Y.INIT,xi.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),S.emit(A.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),yt(521716,!1)],xi.prototype,"subscribe",1),O([ve(xi.STATE_SUBSCRIBE,Y.INIT,{sync:!0,success(){this.log.info("unsubscribed"),S.emit(A.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],xi.prototype,"unsubscribe",1);var Oo=xi;var Ai=class extends Oo{constructor(e,t){super(e,t,1);d(this,"volume",0);d(this,"mediaType",1);d(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.audioManager}get dbVolume(){return ms.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}onPlayerError(e){this.enableDecodeFrame&&(this._log.warn("use audio decoder"),this.room.enableInsertableStreams())}get enableDecodeFrame(){var e,t;return this.manager?this.manager.decodePipeline.some(r=>r)||((t=(e=this.player.element)==null?void 0:e.error)==null?void 0:t.code)===MediaError.MEDIA_ERR_DECODE&&Vc().AudioDecoder&&gi:!1}get enableDecryptFrame(){return this.manager&&!!this.manager.decodePipeline[0]}decodeFrame(e){if(!this.manager)return e;let t=e;for(let[r,o]of this.manager.decodePipeline.entries()){if(!o)continue;let n={frame:e,track:this};if(r===1&&this.isAvailable&&this.room.role==="audience"&&(n.onAudioFrameNTPTime=({ntp:a,frame:c,hasLeavingTag:l})=>{this.emit("audio-frame-with-ntp",{ntp:a,frame:c,hasLeavingTag:l})}),t=o(n),!t)return}return t}getAudioLevel(){if(!this.isAvailable)return 0;let e=this.volume||super.getAudioLevel();return e>1?1:e}getInternalAudioLevel(){return this.isAvailable?super.getInternalAudioLevel():0}get isRemotePublished(){return this.user.muteState.audioAvailable}};var Sd=class extends we{constructor(e,t,r,o,n){super(e,{useDefaultProgram:!0,useFbo:!0,name:"alpha",create2d:!0,logger:t});this.setContainer=o;d(this,"initStat",{alphaStitchingType:1});d(this,"end",ot());d(this,"minSize",320);d(this,"maxSize",1280);d(this,"draggable",!1);d(this,"startDragX",0);d(this,"startDragY",0);d(this,"left",0);d(this,"top",0);d(this,"baseWidth",320);d(this,"baseRatio");d(this,"container");this.initStat=n,this.draggable=r,this.bindDragEvents(),y.addEnum({key:515700,value:1}),this.draggable&&y.addEnum({key:515700,value:11})}bindDragEvents(){let e=this.context._canvas;if(e)if(this.draggable){let t=Le(this.end);he(ue(e,"mousedown"),ta(this.startDrag.bind(this)),Vr(()=>he(ue(window,"mousemove"),Le(ue(window,"mouseup")))),t,Se(this.doDrag.bind(this))),he(ue(e,"dblclick"),t,Se(this.resetPosition.bind(this))),he(ue(e,"wheel"),t,Se(this.handleZoom.bind(this))),this.renderCanvas()}else{if(!this.container)return;this.container.style.removeProperty("left"),this.container.style.removeProperty("top"),this.end.next()}}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}startDrag(e){e.preventDefault(),e.button===0&&(this.startDragX=e.clientX-this.left,this.startDragY=e.clientY-this.top)}renderCanvas(){let{container:e}=this;e||this.setContainer(),!(!e||!this.baseRatio||!this.draggable)&&(e.style.setProperty("width",`${this.baseWidth}px`),e.style.setProperty("height",`${this.baseWidth/this.baseRatio}px`),e.style.setProperty("position","fixed"),e.style.setProperty("left",`${this.left}px`),e.style.setProperty("top",`${this.top}px`))}doDrag(e){e.preventDefault(),this.left=e.clientX-this.startDragX,this.top=e.clientY-this.startDragY,this.renderCanvas()}handleZoom(e){e.preventDefault();let t=.1,r=e.deltaY,o=this.context._canvas;o&&(this.baseWidth||(this.baseWidth=o.offsetWidth),r<0?this.baseWidth=Math.min(this.baseWidth*(1+t),this.maxSize):this.baseWidth=Math.max(this.baseWidth*(1-t),this.minSize),this.renderCanvas())}resetPosition(){this.left=0,this.top=0,this.renderCanvas()}onRatioReset(){this.renderCanvas()}draw2d(e,t,r,o,n){var h;let{ctx2d:a}=this,c=this.context._canvas;if(!a||!c)return!1;let l=super.draw2d(e,t,r,o,n),u=a.getImageData(0,0,o,n),{data:m}=u,p=!1;if(this.initStat.alphaStitchingType===1){let T=Math.floor(o/2);for(let g=0;g<n;g++)for(let R=0;R<T;R++){let D=(g*o+R)*4,j=R+T,V=(g*o+j)*4,ae=m[V];m[V+3]=0;let b=ae>=100;m[D+3]=b?255:0}p=super.draw2d(u,0,0,0,0,T,n),c.width=T}else if(this.initStat.alphaStitchingType===2){let T=Math.floor(n/2);for(let g=0;g<T;g++)for(let R=0;R<o;R++){let D=(g*o+R)*4,V=((g+T)*o+R)*4,ae=m[V];m[V+3]=0;let b=ae>=100;m[D+3]=b?255:0}p=super.draw2d(u,0,0,0,0,o,T),c.height=T}return(h=this.context.ctx)==null||h.clearRect(0,0,o,n),l&&p}close(){this.baseRatio=void 0,this.end.next(),this.end.complete()}};function XS(s){return[15,30,45,60].reduce((e,t)=>Math.abs(t-s)<Math.abs(e-s)?t:e)}var Ui=class extends Oo{constructor(e,t,r=4){super(e,t,r);d(this,"mediaType",4);d(this,"source");d(this,"shouldRenderAlpha",!1);d(this,"alphaNode");d(this,"shouldBeDraggable",!0);d(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0,keyFramesDecoded:0});d(this,"_keyFrameCountLogged",!1);d(this,"_keyFrameStartTimestamp",0);d(this,"_keyFrameStartCount",0);d(this,"_keyFrameIntervals",[]);d(this,"_prevKeyFrameTimestamp",0);this.manager=e.videoManager,this.on("first-video-frame",o=>{this.room.emit("first-video-frame",o)})}isAlphaSei(e){if(this.userId!==e.userId||e.seiPayloadType!==50)return!1;let t=new Uint8Array(e.data);return t.length%3!==0||t[0]!==0||t[1]!==1?!1:t}play(e,t){return t!=null&&t.canvasRender&&!this.source&&this.useCanvasPlayer(),super.play(e,t).then(()=>{this.player.calculateStat(),S.emit("156",{track:this,player:this.player})})}updateAlphaRenderInfo(e){let t=this.isAlphaSei(e);if(t)if(!this.alphaNode)this.shouldRenderAlpha=!0,this.player.shouldRenderAlpha=!0,this.useCanvasPlayer(t[2]);else{let r=t[2];if(this.alphaNode.baseRatio&&this.alphaNode.initStat.alphaStitchingType===r)return;this.alphaNode.initStat={alphaStitchingType:r};let o=this.player.getElement();if(o){let n=o.videoWidth/o.videoHeight;n&&(this.alphaNode.baseRatio=n*(r===1?.5:2),this.alphaNode.onRatioReset())}this.player.canvas&&(this.player.canvas.id=this.generateAlphaCanvasName(r))}}generateAlphaCanvasName(e){let t="alpha",r=Nn[e];return`${t}_${r}_${this.userId}`}useCanvasPlayer(e){if(this.log.info(`useCanvasPlayer(), has element:${!!this.player.element}`),!this.player.element)return;let t=new Qe({frameRate:15,logger:this.log,name:this.shouldRenderAlpha&&e?this.generateAlphaCanvasName(e):this.userId});t.create({alpha:this.shouldRenderAlpha,willReadFrequently:this.shouldRenderAlpha});let r=new As(t,{name:"remotePlayer",logger:this.log});if(this.source=t.createVideoPlayerSource(this.player),this.player.setCanvas(t._canvas),this.shouldRenderAlpha&&e){let o=()=>{!this.player.container||!this.alphaNode||(this.alphaNode.container=this.player.container,this.alphaNode.renderCanvas())},n=new Sd(t,this.log,this.shouldBeDraggable,o,{alphaStitchingType:e});this.source.connect(n),n.connect(r),this.alphaNode=n}else this.source.connect(r);ir()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,t),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let t=this.decodeFPS,r=XS(t);if(!te(t)||t<=0){this.log.debug(`updateCanvasPlayerFPS() ignore decoder: ${t} `);return}if(r===e.frameRate){this.log.debug(`updateCanvasPlayerFPS() ignore ClosestFPS ${r} == ${e.frameRate}`);return}this.log.info(`updateCanvasPlayerFPS() decoder: ${t}, closest: ${r}, current: ${e.frameRate}`),e.frameRate=r}get decodeFPS(){var n;let{msg_video_status:e}=((n=this.room.heartbeatReport)==null?void 0:n.msg_down_stream_info.find(a=>a.msg_user_info.str_identifier===this.userId))||{},t=this.mediaType===2?7:this.isSmall?3:2;if(!e||e.length===0)return 0;let r=e.find(a=>a.uint32_video_stream_type===t);return(r==null?void 0:r.uint32_video_dec_fps)||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),S.emit("157",{track:this,player:this.player}),this.alphaNode&&this.alphaNode.close(),super.stop()}decodeFrame(e){if(!this.manager)return e;for(let t of this.manager.decodePipeline)if(t&&(e=t({frame:e,track:this}),!e))return;return e}get isBig(){return this.mediaType===4}get isSmall(){return this.mediaType===8}changeType(e){this.room.changeType(e,this.user)}get isRemotePublished(){return this.user.muteState.videoAvailable}setMirror(e){e==="publish"||e==="both"||super.setMirror(e)}setDraggable(e){this.shouldBeDraggable=e,this.alphaNode&&(this.alphaNode.draggable=e,this.alphaNode.bindDragEvents())}onDecodeDowngradeStateChanged(e){this.emit("decode-downgrade-state-changed",e)}updateKeyFramesDecoded(e){let t=this.stat.keyFramesDecoded||0;if(this.stat.keyFramesDecoded=e,this._keyFrameCountLogged)return;let r=Date.now();if(!this._keyFrameStartTimestamp){this._keyFrameStartTimestamp=r,this._keyFrameStartCount=e,this._prevKeyFrameTimestamp=r;return}if(this._prevKeyFrameTimestamp&&e>t){let n=e-t,c=(r-this._prevKeyFrameTimestamp)/1e3/n;this._keyFrameIntervals.push(c)}this._prevKeyFrameTimestamp=r;let o=r-this._keyFrameStartTimestamp;if(o>=16e3){let n=e-this._keyFrameStartCount,a=n>0?o/1e3/n:0,c=`${n} keyframes in 16s ${a} [${this._keyFrameIntervals.map(u=>u.toFixed(1)).join(",")}] keyFramesDecoded ${e}`,l=a<=2.5?"debug":"info";this.log[l](c),this._keyFrameCountLogged=!0}}},Po=class extends Ui{constructor(e,t){super(e,t,2);d(this,"mediaType",2);d(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}};var ko=new Map;S.on(A.JOIN_SUCCESS,({room:s})=>{Me(s.userId,{eventId:32788})});S.on(A.LEAVE_START,({room:s})=>{Me(s.userId,{eventId:32789})});S.on(A.LOCAL_TRACK_PUBLISHED,({track:s})=>{if(s.room){let i=32769;s.mediaType===4?i=32768:s.mediaType===2&&(i=32805),Me(s.room.userId,{eventId:i})}});S.on(A.LOCAL_TRACK_UNPUBLISHED,({track:s})=>{if(s.room){let i=32771;s.mediaType===4?i=32770:s.mediaType===2&&(i=32806),Me(s.room.userId,{eventId:i})}});S.on(A.TRACK_MUTED,({track:s})=>{s.room&&(s.kind===_.AUDIO?Me(s.room.userId,{eventId:s.isRemote?32785:32772,remoteUserId:s.isRemote?s.userId:void 0}):Me(s.room.userId,{eventId:s.isRemote?32784:32773,remoteUserId:s.isRemote?s.userId:void 0}))});S.on(A.TRACK_UNMUTED,({track:s})=>{s.room&&(s.kind===_.AUDIO?Me(s.room.userId,{eventId:s.isRemote?32787:32774,remoteUserId:s.isRemote?s.userId:void 0}):Me(s.room.userId,{eventId:s.isRemote?32786:32775,remoteUserId:s.isRemote?s.userId:void 0}))});S.on(A.REMOTE_TRACK_SUBSCRIBED,({track:s})=>{s.room&&(s.mediaType===1&&Me(s.room.userId,{eventId:32777,remoteUserId:s.userId}),s.mediaType===4&&Me(s.room.userId,{eventId:32776,remoteUserId:s.userId}),s.mediaType===8&&Me(s.room.userId,{eventId:32803,remoteUserId:s.userId}))});S.on(A.REMOTE_TRACK_UNSUBSCRIBED,({track:s})=>{s.room&&(s.mediaType===1&&Me(s.room.userId,{eventId:32779,remoteUserId:s.userId}),s.mediaType===4&&Me(s.room.userId,{eventId:32778,remoteUserId:s.userId}),s.mediaType===8&&Me(s.room.userId,{eventId:32804,remoteUserId:s.userId}))});S.on(A.SWITCH_DEVICE_SUCCESS,({track:s})=>{s.room&&Me(s.room.userId,{eventId:s.kind===_.VIDEO?32780:32781})});S.on(A.LOCAL_TRACK_REPLACED,({track:s})=>{s.room&&Me(s.room.userId,{eventId:s.kind===_.VIDEO?32782:32783})});S.on(A.SIGNAL_CONNECTION_STATE_CHANGED,({room:s,prevState:i,state:e})=>{let t;switch(e){case"CONNECTED":i==="RECONNECTING"?t=32795:t=32791;break;case"DISCONNECTED":i==="RECONNECTING"?t=32796:t=32790;break;case"RECONNECTING":t=32794;break}t&&Me(s.userId,{eventId:t})});S.on(A.PEER_CONNECTION_STATE_CHANGED,({room:s,prevState:i,state:e,remoteUserId:t})=>{let r=!!t,o;switch(e){case"CONNECTED":i==="RECONNECTING"?o=r?32801:32798:o=r?32793:32792;break;case"DISCONNECTED":i==="RECONNECTING"&&(o=r?32802:32799);break;case"RECONNECTING":o=r?32800:32797;break}o&&Me(s.userId,{eventId:o,remoteUserId:t})});S.on(A.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({implementation:s,userId:i,remoteUserId:e,codec:t,isHWCodec:r,prevImplementation:o,streamType:n})=>{let a=r?1:0;o||(a=r?3:2);let c={H264:0,H265:1,VP8:2}[t.toUpperCase()],l={eventId:4004,param1:a,param2:c,streamType:n||2};e&&(l.remoteUserId=e,l.eventId=4005),Me(i,l),y.addEnum({key:e?514701:513701,value:a}),y.addEnum({key:e?514700:513700,value:c})});S.on(A.LOCAL_TRACK_RECAPTURE,({track:s,error:i})=>{if(s.userId){let e={eventId:2003,param1:0};s.kind===_.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType=s.streamType==="auxiliary"?7:2,i&&(e.param1=8)),Me(s.userId,e)}});function Me(s,i){let e=L(M({},i),{timestamp:Wi()});ko.has(s)?ko.get(s).push(e):ko.set(s,[e])}function Ff(s){if(ko.has(s)){let i=ko.get(s).map(e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,uint32_param1:e.param1,uint32_param2:e.param2,uint32_video_stream_type:e.streamType}));return ko.delete(s),i}return[]}function Bf(...s){return K((i,e)=>function(...t){return zS.call(this,s,t,e,this._name),i.apply(this,t)})}function zS(s,i,e,t){try{if(Ie(s))for(let r=0;r<s.length;r++)Id.call(this,{rule:s[r],value:i[r],key:s[r].name,fnName:e,className:t});else Id.call(this,{rule:s,value:i[0],key:s.name,fnName:e,className:t})}catch(r){throw C.error(r),r}}function Id({rule:s,value:i,key:e,fnName:t,className:r}){if(E(i)){if(s.required)throw new N({code:I.INVALID_PARAMETER,message:W({key:H.INVALID_PARAMETER_REQUIRED,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(E(s.defaultValue))return;i=s.defaultValue}if(Array.isArray(s.type)){let a=!1;for(let c=0;c<s.type.length;c++)s.type[c]===null&&i===null&&(a=!0),me(s.type[c])&&i instanceof s.type[c]&&(a=!0),ne(s.type[c])&&Pe(i)===s.type[c].toLowerCase()&&(a=!0);if(!a)throw new N({code:I.INVALID_PARAMETER,message:W({key:H.INVALID_PARAMETER_TYPE,data:{key:e,rule:{type:s.type.map(c=>es(c)?Js(c):ne(c)?c:Pe(c))},fnName:t,value:i},link:{className:r,fnName:t}})})}else if(!E(s.type)&&Pe(i)!==s.type)throw new N({code:I.INVALID_PARAMETER,message:W({key:H.INVALID_PARAMETER_TYPE,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(s.allowEmpty===!1){let a=te(i)&&(i===0||Number.isNaN(i)),c=ne(i)&&i.trim()==="";if(a||c)throw new N({code:I.INVALID_PARAMETER,message:W({key:H.INVALID_PARAMETER_EMPTY,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})})}if(s.notLessThanZero&&te(i)&&i<0)throw new N({code:I.INVALID_PARAMETER,message:W({key:H.CANNOT_LESS_THAN_ZERO,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(!E(s.min)&&te(i)&&i<s.min)throw new N({code:I.INVALID_PARAMETER,message:W({key:H.INVALID_PARAMETER_MIN,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(!E(s.max)&&te(i)&&i>s.max)throw new N({code:I.INVALID_PARAMETER,message:W({key:H.INVALID_PARAMETER_MAX,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(ne(s.instanceOf)){if(!i||i._name!==s.instanceOf)throw new N({code:I.INVALID_PARAMETER,message:W({key:H.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})})}else if(me(s.instanceOf)&&!(i instanceof s.instanceOf))throw new N({code:I.INVALID_PARAMETER,message:W({key:H.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(s.values&&!s.values.includes(i))throw new N({code:I.INVALID_PARAMETER,message:W({key:H.INVALID_PARAMETER_RANGE,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});let{properties:o}=s;dt(o)&&vt(i)&&Object.keys(o).forEach(a=>{Id.call(this,{rule:o[a],value:i&&i[a],key:`${e}.${a}`,fnName:t,className:r})});let{arrayItem:n}=s;dt(n)&&Ie(i)&&i.forEach((a,c)=>{Id.call(this,{rule:n,value:a,key:`${e}[${c}]`,fnName:t,className:r})}),me(s.validate)&&s.validate.call(this,i,e,t,r,this)}var Hf=We(Ze(),1);var Ad=class extends Hf.EventEmitter{constructor(e,t,r="userId"){super();this.mySelfId=e;this._log=t;this.key=r;d(this,"userMap",new Map);d(this,"remotePublishedUserMap",new Map);d(this,"asrRobotUserMap",new Map)}get hasRobotUser(){return!![...this.remotePublishedUserMap.values()].find(e=>e.isRobot)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:r,tinyId:o,role:n,fromType:a}=e;if(a===Hs){this.addAsrRobotUser(e);return}if(this.userMap.has(t))return;let c={userId:r,tinyId:o,role:n===20?"anchor":"audience"};this.userMap.set(t,c),this.emit("1",c)}addAsrRobotUser(e){let t=e[this.key],{userId:r,tinyId:o,role:n}=e;if(this.asrRobotUserMap.has(t))return;let a={userId:r,tinyId:o,role:n===20?"anchor":"audience"};this.asrRobotUserMap.set(t,a),this.emit("8",a)}deleteUser(e,t){let r=this.userMap.get(e);if(!r)return;if(this.asrRobotUserMap.has(e)){this.deleteAsrRobotUser(e);return}let n=`peer leave [${e}]`;E(t)||(n+=`:${Cl[t]}`),this._log.info(n);let a=this.remotePublishedUserMap.get(e);if(a){let c=a.muteState;a.flag=0,this.emit("5",a.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:c,muteState:a.muteState,flag:0})}this.userMap.delete(e),this.emit("2",{userId:r.userId,reason:t})}deleteAsrRobotUser(e){if(!this.asrRobotUserMap.has(e))return;let t=this.asrRobotUserMap.get(e);t&&(this.asrRobotUserMap.delete(e),this.emit("9",t))}setUserList(e){this.userMap.forEach(t=>{e.findIndex(r=>r[this.key]===t[this.key])<0&&this.deleteUser(t[this.key],0)}),e.forEach(t=>{!this.userMap.has(t[this.key])&&t[this.key]!==this.mySelfId&&this.addUser(t)})}addRemotePublishedUser(e){this.remotePublishedUserMap.has(e[this.key])||this.remotePublishedUserMap.set(e[this.key],e)}deleteRemotePublishedUser(e){this.remotePublishedUserMap.has(e)&&this.remotePublishedUserMap.delete(e)}setRemotePublishedUserList(e){this.remotePublishedUserMap.forEach(t=>{let r=t[this.key];if(e.findIndex(o=>o[this.key]===t[this.key])<0){this._log.info(`remote [${r}] unpublish`);let o=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(r),this.emit("6",{prevMuteState:o,muteState:t.muteState,flag:0})}}),e.forEach(t=>{var m;let r=t[this.key];if(r===this.mySelfId){this.emit("7",t);return}let{flag:o,userId:n,tinyId:a,fromType:c}=t,l=oi(o,n),u=(m=this.remotePublishedUserMap.get(r))==null?void 0:m.muteState;if(u){let p=this.remotePublishedUserMap.get(r);p&&p.flag!==o&&(p.flag=o,this._log.info(`remote publish updated: ${JSON.stringify(p.muteState)}`),this.emit("6",{prevMuteState:u,muteState:l,flag:o}))}else this._log.info(`remote publish. state: ${JSON.stringify(l)}`),this.addUser({userId:n,tinyId:a,role:20,fromType:c}),this.emit("3",t),this.emit("6",{prevMuteState:oi(0,n),muteState:l,flag:o})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};var $f=We(Ze(),1);var Lo=class extends $f.default{constructor(){super(...arguments);d(this,"_connectionTimeoutCount",0);d(this,"_isFirewallRestrictionEventEmitted",!1)}increaseTimeoutCount(){this._connectionTimeoutCount+=1,this.checkAndEmitFirewallRestriction()}resetTimeoutCount(){this._connectionTimeoutCount=0}checkAndEmitFirewallRestriction(){this._connectionTimeoutCount>=3&&!this._isFirewallRestrictionEventEmitted&&(this._isFirewallRestrictionEventEmitted=!0,this.emit("firewall-restriction"))}destroy(){this._connectionTimeoutCount=0,this._isFirewallRestrictionEventEmitted=!1,this.removeAllListeners()}};function Gh({timesInSecond:s,maxSizeInSecond:i,getSize:e}){return K((t,r)=>{let o=new WeakMap;return S.on(A.ROOM_DESTROY,({room:n})=>o.delete(n)),function(...n){let a=o.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},o.set(this,a)),a.timestamp===0?a.timestamp=Date.now():Date.now()-a.timestamp>1e3&&(a.timestamp=Date.now(),a.callCountInSecond=0,a.totalSizeInSecond=0),e&&(a.totalSizeInSecond+=e(...n)),a.timestamp!==0&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=s||a.totalSizeInSecond>i))throw new N({code:I.INVALID_OPERATION,message:W({key:H.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=s,isSize:a.totalSizeInSecond>i,name:r,timesInSecond:s,maxSizeInSecond:i}})});a.callCountInSecond++,t.call(this,...n)}})}var YS="2026-01-20 21:59:01",Wf=!0,Gf=function(){var s;if(Wf){Wf=!1,C.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${gt}/en/index.html`),console.info(`* Changelog: ${gt}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),C.info("TRTC Web SDK Version:",Ge),hi||C.debug("Build Time:",YS);let i=`UA: ${navigator.userAgent}
|
|
52
|
+
} `;var Rs=class extends Y{constructor(e){super();d(this,"frameRate");d(this,"_canvas");d(this,"log");d(this,"hasAlpha",!1);d(this,"name");d(this,"error");this.name=e.name,this.log=e.logger.createChild({id:`vc-${this.name}`}),this.frameRate=e.frameRate}get canvas(){return this._canvas}set width(e){this._canvas&&(this._canvas.width=e)}get width(){var e;return((e=this._canvas)==null?void 0:e.width)||0}set height(e){this._canvas&&(this._canvas.height=e)}get height(){var e;return((e=this._canvas)==null?void 0:e.height)||0}setSize(e,t){this._canvas&&(this._canvas.width=e,this._canvas.height=t)}createVideoTrackSource(e,t){return new zt(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new No(this,e)}createVideoImageSource(e,t){return new ra(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new sa(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}createTextSource(e,t){return new gd(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}};d(Rs,"_ids",0);var Do=class Do extends Rs{constructor(){super(...arguments);d(this,"defaultProgam");d(this,"defaultVShader");d(this,"defaultFShader");d(this,"ctx");d(this,"_canvas2d")}get canvas(){return this._canvas2d||this._canvas}create(e=!1){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${Rs._ids++}`),e&&(this._canvas2d=document.createElement("canvas")),this.ctx=this._canvas.getContext("webgl2",yl),!this.ctx)throw new N({code:I.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,US),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,VS),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new N({code:I.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})}destroy(e){let t="";return e&&(t=e.message,this.error=e,y.addFailedEvent({key:512702,error:e})),this.disconnect(),this.log.info(`video context destroy${t}`?`: ${t}`:""),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),e}set width(e){var t;(t=this.ctx)==null||t.viewport(0,0,e,this.height),super.width=e,this._canvas2d&&(this._canvas2d.width=e)}set height(e){var t;(t=this.ctx)==null||t.viewport(0,0,this.width,e),super.height=e,this._canvas2d&&(this._canvas2d.height=e)}setSize(e,t){var r;(r=this.ctx)==null||r.viewport(0,0,e,t),super.setSize(e,t),this._canvas2d&&(this._canvas2d.width=e,this._canvas2d.height=t)}createShader(e,t){let r=this.ctx,o=r.createShader(e);return r.shaderSource(o,t),r.compileShader(o),o}createProgram(e,t){let r=this.ctx,o=r.createProgram();return r.attachShader(o,e),r.attachShader(o,t),r.linkProgram(o),r.getProgramParameter(o,r.LINK_STATUS)||this.log.error(r.getProgramInfoLog(o)),o}};d(Do,"UNAVAILABLE","unavailable"),O([ve(Y.INIT,"created",{sync:!0,fail(e){this.log.error("video gl context create failed",e.cause),y.addFailedEvent({key:512700,error:e.cause||e})},success(){this.log.info("video context created use webgl"),y.addSuccessEvent({key:512700})}})],Do.prototype,"create",1),O([ve("created",Y.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(Do.UNAVAILABLE,e),this.removeAllListeners()}})],Do.prototype,"destroy",1);var $e=Do,Qe=class extends Rs{constructor(){super(...arguments);d(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${Rs._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:e.alpha,willReadFrequently:e.willReadFrequently}),!this.ctx)throw new N({code:I.VIDEO_MANAGER_ERROR,extraCode:2,message:"2d context not supported"});this._canvas.addEventListener("contextlost",()=>{this.log.error("2d context lost")}),this._canvas.addEventListener("contextrestored",()=>{this.log.warn("2d context restored")})}destroy(e){let t="";e&&(t=e.message,this.error=e,y.addFailedEvent({key:512703,error:e})),this.disconnect(),this.log.info(`video context destroy ${t?`: ${t}`:""}`),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners(),y.addSuccessEvent({key:512703})}};O([ve(Y.INIT,"created",{sync:!0,fail(e){this.log.error("video 2d context create failed",e.cause),y.addFailedEvent({key:512701,error:e.cause||e})},success(){this.log.info("video context created use 2d"),y.addSuccessEvent({key:512701})}})],Qe.prototype,"create",1),O([ve("created",Y.INIT,{ignoreError:!0,sync:!0})],Qe.prototype,"destroy",1);function FS(s,i,e,t,r,o=!1){o&&([e,t]=[t,e]);let n={sWidth:s,sHeight:i,dWidth:e,dHeight:t,sx:0,sy:0,dx:0,dy:0};if(s===0||i===0)return n;switch(r){case void 0:case"fill":break;case"contain":{let a=Math.min(e/s,t/i);n.dWidth=s*a,n.dHeight=i*a,n.dx=(e-n.dWidth)/2,n.dy=(t-n.dHeight)/2;break}case"cover":{let a=Math.max(e/s,t/i),c=e/a,l=t/a;n.sx=(s-c)/2,n.sy=(i-l)/2,n.sWidth=c,n.sHeight=l;break}}return n}var $h=class{constructor(i,e){this.node=i;this.layout=e;d(this,"positionBuffer")}get x(){return this.layout.x||this.node.x}get y(){return this.layout.y||this.node.y}get width(){return this.layout.width||this.node.width}get height(){return this.layout.height||this.node.height}get right(){return this.x+this.width}get bottom(){return this.y+this.height}get fillMode(){return this.layout.fillMode}get rotation(){return this.layout.rotation}get hidden(){return!!this.layout.hidden}},Mo=class extends we{constructor(e,t){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:t});d(this,"inputs",[]);d(this,"backgroundColor","black")}addInput(e,t){let r=0,o=this.inputs.length;for(;r<o;){let a=Math.floor((r+o)/2);if(this.inputs[a].layout.zIndex<t.zIndex)r=a+1;else if(this.inputs[a].layout.zIndex>t.zIndex)o=a;else throw new Error(`input already exists at zIndex ${t.zIndex}`)}let n=new $h(e,t);this.inputs.splice(r,0,n)}changeInputLayout(e,t){let r=this.inputs.findIndex(T=>T.node===e);if(r<0)return;let{x:o,y:n,width:a,height:c,zIndex:l,fillMode:u,rotation:m,hidden:p}=t;if(!E(l)&&this.inputs.some(T=>T.layout.zIndex===l&&T.node!==e))throw new Error(`input already exists at zIndex ${t.zIndex}`);let h=this.inputs[r];E(o)||(h.layout.x=o),E(n)||(h.layout.y=n),E(a)||(h.layout.width=a),E(c)||(h.layout.height=c),E(m)||(h.layout.rotation=m),E(p)||(h.layout.hidden=p),u&&(h.layout.fillMode=u),!E(l)&&l!==h.layout.zIndex&&(h.layout.zIndex=l,this.inputs.sort((T,g)=>T.layout.zIndex-g.layout.zIndex))}hasInput(e){return this.inputs.some(t=>t.node===e)}hasNoInput(){return this.inputs.length===0}resize(e,t){if(!this.matchInputSize){super.resize(e,t);return}let r=this.inputs.reduce((o,n)=>n?Object.assign(o,{width:Math.max(o.width,n.right),height:Math.max(o.height,n.bottom)}):o,{width:0,height:0});super.resize(r.width,r.height),this.context instanceof $e&&this.inputs.forEach(o=>{if(o){let n=this.layout2texCoords(o);o.positionBuffer?this.changeBufferData(o.positionBuffer,n):o.positionBuffer=this.createBuffer(n)}})}connect(e,...t){return super.connect(e,...t),this.drawBackGround2d(this.backgroundColor),this.matchInputSize&&this.resize(0,0),e}removeInput(e){this.inputs=this.inputs.filter(t=>t.node!==e),this.inputs.length===0&&this.drawBackGround2d(this.backgroundColor)}render(e){let t=this.context.ctx;if(t.clearColor(0,0,0,0),this.inputs.reduce((o,n)=>n.node.requestFrame(e)||o,!1)&&t){this.useProgram(),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let o=0;o<this.inputs.length;o++){let n=this.inputs[o];n&&(n.node.useTexture(),this.draw(n.positionBuffer))}return!0}return!1}render2d(e){if(this.inputs.forEach(t=>t.node.requestFrame(e)),this.ctx2d){this.drawBackGround2d(this.backgroundColor);for(let t=0;t<this.inputs.length;t++){let r=this.inputs[t];if(r.hidden)continue;let o=FS(r.node.width,r.node.height,r.width,r.height,r.fillMode,Nt(r.rotation));this.draw2d(r.node.image,r.x+o.dx,r.y+o.dy,o.dWidth,o.dHeight,o.sx,o.sy,o.sWidth,o.sHeight)}return!0}return!1}debugLayout(e,t,r,o,n=!1){this.ctx2d&&(n&&([r,o]=[o,r]),this.ctx2d.save(),this.ctx2d.strokeStyle="red",this.ctx2d.lineWidth=2,this.ctx2d.strokeRect(e,t,r,o),this.ctx2d.restore())}getInfo(){let{totalFrames:e,x:t,y:r,width:o,height:n,name:a}=this,c=Date.now(),l=(e-this.lastInfo.totalFrames)/((c-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:r,width:o,height:n,timestamp:c,fps:l,name:a},M({parent:this.inputs.filter(u=>u).map(u=>u.node.getInfo())},this.lastInfo)}removeAllInputs(){this.inputs.forEach(e=>{var t;if(e.node.disconnect(),e.positionBuffer&&this.context instanceof $e)try{(t=this.context.ctx)==null||t.deleteBuffer(e.positionBuffer)}catch(r){}})}close(){super.close(),this.removeAllInputs()}};var BS=[1,0,0,0,1,1,0,1],Qt=class extends we{constructor(e,t,r,o){super(e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"transform",logger:t});d(this,"mirror",!1);d(this,"rotation",0);if(r&&(this.mirror=r),o&&(this.rotation=o),e instanceof $e)try{this.setTexBuffer(BS)}catch(n){e.destroy(new N({code:I.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${n.message||n}`}))}}draw2d(e,t,r,o,n){if(this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height),this.ctx2d.save(),this.mirror&&(this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0)),this.rotation===90?(this.ctx2d.translate(o,0),this.ctx2d.rotate(Math.PI/2),this.ctx2d.scale(n/o,o/n)):this.rotation===180?(this.ctx2d.translate(this.width,this.height),this.ctx2d.rotate(Math.PI)):this.rotation===270&&(this.ctx2d.translate(0,n),this.ctx2d.rotate(3*Math.PI/2),this.ctx2d.scale(n/o,o/n));let a=super.draw2d(e,t,r,o,n);return this.ctx2d.restore(),a}return!1}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}resize(e,t){Nt(this.rotation)&&([e,t]=[t,e]),super.resize(e,t)}};var Cs=class extends Ei{constructor(e,t=4){super(t,rt);d(this,"inputLocalVideoTracks",new Map);d(this,"inputLocalScreenTracks",new Map);d(this,"cameraNodeMap",new Map);d(this,"screenNodeMap",new Map);d(this,"textNodeMap",new Map);d(this,"imageNodeMap",new Map);d(this,"videoNodeMap",new Map);d(this,"endedIds",new Set);d(this,"videoContext");d(this,"mixNode");d(this,"destination");d(this,"manager");d(this,"stat");d(this,"_checkId",0);d(this,"autoSetFps",!0);this.manager=e,this.log.id+="mix",this.create2dVideoContext(),this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log}),this.destination.on(we.RENDER,r=>{this.emit("render",r)}),this.mixNode=new Mo(this.videoContext,this.log),this.mixNode.matchInputSize=!1}listenDeviceChange(){throw new Error("Method not implemented.")}enablePrintDetail(e=2e3){this._checkId=ce.run("interval",()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:e})}create2dVideoContext(){this.videoContext?this.videoContext.destroy():this.videoContext=new Qe({frameRate:15,logger:this.log,name:"mix-ctx"}),this.videoContext.create({alpha:!1})}setFps(e){this.autoSetFps=!1,this.videoContext.frameRate=e;for(let t of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])t.shouldUpdate=!1;setTimeout(()=>{var t;return(t=this.destination)==null?void 0:t.start(this.videoContext.frameRate)},500)}setFpsAuto(){var o;if(!this.autoSetFps)return;for(let n of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])n.shouldUpdate=!1;let e=null,t=0,r=!0;for(let[n,a]of this.inputLocalVideoTracks)if(a.profile.frameRate>t){if(this.endedIds.has(n)){let c=this.cameraNodeMap.get(n);c&&c.image.cancelVideoFrameCallback(c.videoCallbackId);continue}t=a.profile.frameRate,e=n}for(let[n,a]of this.inputLocalScreenTracks)if(a.profile.frameRate>t){if(this.endedIds.has(n)){let c=this.screenNodeMap.get(n);c&&c.image.cancelVideoFrameCallback(c.videoCallbackId);continue}t=a.profile.frameRate,e=n,r=!1}if(e!==null){let n=r?this.cameraNodeMap.get(e):this.screenNodeMap.get(e);n&&(n.shouldUpdate=!0,n.tryVideoFrameCallback()),this.log.info("set mix fps: ",t)}else(o=this.destination)==null||o.start(this.videoContext.frameRate),this.log.info("fallback to timer, fps: ",this.videoContext.frameRate)}setMixBackground(e){this.mixNode&&(this.mixNode.backgroundColor=e)}resizeMixCanvas(e,t){var r;(r=this.mixNode)==null||r.resize(e,t)}startMix(){return f(this,null,function*(){var e;if(!this.mixNode||!this.destination)throw new Error("can't mix without necessary conditions");this.mixNode.disconnect(),this.mixNode.connect(this.destination),Gt&&this.player.setCanvas(this.videoContext._canvas),this.setOutputMediaStreamTrack(this.destination.videoTrack),(e=this.manager)==null||e.changeInput(this)})}addCameraSource(e,t,r){if(this.inputLocalVideoTracks.has(e)||this.cameraNodeMap.has(e))throw new Error(`There is already a cameraSource with the same ID: ${e}`);let{mediaTrack:o}=t;if(!o)throw new Error("no mediaTrack, add cameraSource failed");t.recaptureMode=1,it(this,Ne).add("videoInputRemoved",a=>{a.deviceId===t.deviceId&&(this.endedIds.add(e),this.setFpsAuto())}),t.on("output-media-track-changed",()=>{this.endedIds.delete(e),this.updateCameraSource(e,r,t.mediaTrack)});let n;qe===16&&o instanceof CanvasCaptureMediaStreamTrack?n=this.videoContext.createVideoImageSource(o.canvas,{name:"cameraCanvasSource",logger:this.log}):n=this.videoContext.createVideoTrackSource(o,"cameraNodeSource"),n.resize(t.settings.width,t.settings.height),n.shouldUpdate=!1,this._connectMix(n,r,"cover"),this.inputLocalVideoTracks.set(e,t),this.cameraNodeMap.set(e,n),this.setFpsAuto()}addScreenSource(e,t,r){if(this.inputLocalScreenTracks.has(e)||this.screenNodeMap.has(e))throw new Error(`There is already a screenSource with the same ID: ${e}`);let{mediaTrack:o}=t;if(!o)throw new Error("no mediaTrack, add screenSource failed");t.on("output-media-track-changed",()=>{this.updateScreenSource(e,r,t.mediaTrack)});let n=this.videoContext.createVideoTrackSource(o,"screenNodeSource");n.resize(t.settings.width,t.settings.height),n.shouldUpdate=!1,this._connectMix(n,r),this.inputLocalScreenTracks.set(e,t),this.screenNodeMap.set(e,n),this.setFpsAuto()}addTextSource(e){let{id:t,content:r="",font:o,color:n,layout:a}=e;if(this.textNodeMap.has(t))throw new Error(`There is already a textSource with the same ID: ${t}`);let c=this.videoContext.createTextSource({content:r,font:o,color:n});c.resize(a.width,a.height),this._connectMix(c,a),this.textNodeMap.set(t,c)}addImageSource(e,t,r){if(this.imageNodeMap.has(e))throw new Error(`There is already a imageSource with the same ID: ${e}`);let o=this.videoContext.createVideoImageSource(t,{autoResize:!1,logger:this.log});o.resize(t.width,t.height),this._connectMix(o,r),this.imageNodeMap.set(e,o)}addVideoSource(e,t,r){if(this.videoNodeMap.has(e))throw new Error(`There is already a videoSource with the same ID: ${e}`);let o=this.videoContext.createVideoImageSource(t,{autoResize:!1,logger:this.log});o.resize(t.videoWidth,t.videoHeight),o.shouldUpdate=!1,this._connectMix(o,r),this.videoNodeMap.set(e,o)}updateCameraSource(e,t,r=null,o){let n=this.cameraNodeMap.get(e);if(n){if(r){if(qe===16&&r instanceof CanvasCaptureMediaStreamTrack)if(n instanceof zt){let l=n.output;n.close(),n=this.videoContext.createVideoImageSource(r.canvas,{name:"cameraCanvasSource",logger:this.log}),n.connect(l),this.cameraNodeMap.set(e,n)}else n.image=r.canvas;else if(n instanceof zt)n.replaceTrack(r);else{let l=n.output;n.close(),n=this.videoContext.createVideoTrackSource(r,"cameraNodeSource"),n.connect(l),this.cameraNodeMap.set(e,n)}let{width:a,height:c}=r.getSettings();a&&c&&n.resize(a,c)}o&&n.resize(o.width,o.height),(o||r)&&this.setFpsAuto(),this._changeMixLayout(n,t)}}updateScreenSource(e,t,r=null){let o=this.screenNodeMap.get(e);o&&(r&&o.replaceTrack(r),this._changeMixLayout(o,t))}updateTextSource(e){let{id:t,content:r,font:o,color:n,layout:a}=e,c=this.textNodeMap.get(t);c&&(E(r)||(c.content=r),E(o)||(c.font=o),E(n)||(c.color=n),c.resize(a.width,a.height),this._changeMixLayout(c,a))}updateImageSource(e,t,r){let o=this.imageNodeMap.get(e);o&&(r&&(o.image=r,o.resize(r.width,r.height)),this._changeMixLayout(o,t))}updateVideoSource(e,t,r){let o=this.videoNodeMap.get(e);if(o){if(r){let n=o.image;n instanceof HTMLVideoElement&&this.stopVideoElement(n),o.image=r,o.resize(r.videoWidth,r.videoHeight)}this._changeMixLayout(o,t)}}_connectMix(e,t,r="contain"){if(!this.mixNode)return;let{mirror:o,rotation:n}=t;e.disconnect();let a=new Qt(this.videoContext,this.log,o,n);a=e.connect(a),t.fillMode||(t.fillMode=r),a.connect(this.mixNode,t)}_changeMixLayout(e,t){if(!this.mixNode)return;let{mirror:r,rotation:o}=t,n=e.output||e;n instanceof Qt&&(E(r)||(n.mirror=r),E(o)||(n.rotation=o),n.resize(e.width,e.height)),this.mixNode.changeInputLayout(n,t)}removeCameraSource(e){let t=this.inputLocalVideoTracks.get(e);if(!t)return;t.close(),this.inputLocalVideoTracks.delete(e);let r=this.cameraNodeMap.get(e);r&&(r.output instanceof Qt&&r.output.close(),r.close(),this.cameraNodeMap.delete(e)),this.checkAfterRemove(!0)}removeScreenSource(e){let t=this.inputLocalScreenTracks.get(e);if(!t)return;t.close(),this.inputLocalScreenTracks.delete(e);let r=this.screenNodeMap.get(e);r&&(r.output instanceof Qt&&r.output.close(),r.close(),this.screenNodeMap.delete(e)),this.checkAfterRemove(!0)}removeTextSource(e){let t=this.textNodeMap.get(e);t&&(t.output instanceof Qt&&t.output.close(),t.close(),this.textNodeMap.delete(e)),this.checkAfterRemove()}removeImageSource(e){let t=this.imageNodeMap.get(e);t&&(t.output instanceof Qt&&t.output.close(),t.close(),this.imageNodeMap.delete(e)),this.checkAfterRemove()}removeVideoSource(e){let t=this.videoNodeMap.get(e);t&&(t.output instanceof Qt&&t.output.close(),t.image instanceof HTMLVideoElement&&this.stopVideoElement(t.image),t.close(),this.videoNodeMap.delete(e)),this.checkAfterRemove()}checkAfterRemove(e=!1){e&&this.setFpsAuto()}stopVideoElement(e){e.pause(),e.src="",e.srcObject=null,e.remove()}close(){var e;super.close(),ce.clearTask(this._checkId),(e=this.videoContext)==null||e.destroy(),delete this.mixNode,delete this.destination;for(let t of[...this.inputLocalVideoTracks.values(),...this.inputLocalScreenTracks.values()])t.close();this.inputLocalVideoTracks.clear(),this.inputLocalScreenTracks.clear(),this.cameraNodeMap.clear(),this.screenNodeMap.clear(),this.textNodeMap.clear(),this.imageNodeMap.clear(),Fe(this);for(let t of this.videoNodeMap.values())t.image instanceof HTMLVideoElement&&this.stopVideoElement(t.image);this.videoNodeMap.clear(),this.log.info("localMixVideoTrack close, stop mix")}};var Td=Cn();if(typeof navigator!="undefined"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:Td,exposeOrigin:!0,permittedOrigins:["*"]})}catch(s){}var HS=function(s){return f(this,null,function*(){let i=null,e=GS(s);C.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let t=yield navigator.mediaDevices.getDisplayMedia(e);s.systemAudio&&t.getAudioTracks().length===0&&(ao&&et<74||ye||re)&&C.warn("Your browser not support capture system audio");let r=t.getVideoTracks()[0];if(r){if(s.frameRate)try{yield r.applyConstraints({frameRate:{min:s.frameRate,ideal:s.frameRate},width:s.width,height:s.height})}catch(o){C.warn(`screen applyConstraints failed: ${o}`)}s.captureElement&&(yield $S(r,s.captureElement))}if(s.audio){let o=WS(s);C.info(`getUserMedia with constraints: ${JSON.stringify(o)}`),i=yield navigator.mediaDevices.getUserMedia(o),t.addTrack(i.getAudioTracks()[0])}return t})};function $S(s,i){return f(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&me(s.cropTo))try{if(!(((e=s.getCaptureHandle())==null?void 0:e.handle)===Td))return;let r=yield CropTarget.fromElement(i);yield s.cropTo(r)}catch(t){C.warn(`cropTo target failed ${t}`)}})}function WS(s){let i={echoCancellation:s.echoCancellation,autoGainControl:s.autoGainControl,noiseSuppression:s.noiseSuppression,sampleRate:s.sampleRate,channelCount:s.channelCount};return E(s.microphoneId)||(i.deviceId=s.microphoneId),{audio:i,video:!1}}function GS(s){let i={preferCurrentTab:s.preferDisplaySurface==="current-tab"||!!s.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:ye?{max:s.width}:{ideal:s.width,max:s.width},height:ye?{max:s.height}:{ideal:s.height,max:s.height},frameRate:s.frameRate,displaySurface:s.preferDisplaySurface||"monitor"};if(i.video=e,s.systemAudio){let{echoCancellation:t=!0,noiseSuppression:r=!1,autoGainControl:o=!1}=s;i.audio={echoCancellation:t,noiseSuppression:r,autoGainControl:o,sampleRate:48e3}}return i}var Uf=HS;var xt=class extends ze{constructor(e){super(e,2);d(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600});d(this,"objectFit","contain");d(this,"isScreen",!0);this._log.id=`s-${this._log.id}`}get isShareCurrentTab(){var e,t;try{return Td===((t=(e=this.mediaTrack)==null?void 0:e.getCaptureHandle())==null?void 0:t.handle)}catch(r){return}}capture(u){return f(this,arguments,function*({systemAudio:e=!1,autoGainControl:t,echoCancellation:r,noiseSuppression:o,audioTrack:n,videoTrack:a,captureElement:c,preferDisplaySurface:l}){try{let m=x(),p;return a||n?(p=new MediaStream,a&&p.addTrack(a),n&&p.addTrack(n)):(p=yield Uf({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:t,echoCancellation:r,noiseSuppression:o,captureElement:c,preferDisplaySurface:l}),this.sourceTrack=p.getVideoTracks()[0]),yield this.setInputMediaStreamTrack(p.getVideoTracks()[0]),S.emit(A.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:x()-m}),p}catch(m){throw this.log.error(`getDisplayMedia error observed ${m}`),m instanceof N?m:new N({code:I.INITIALIZE_FAILED,name:m.name,message:m.message})}})}switchDevice(e){return f(this,null,function*(){throw new Error("Method not implemented.")})}};O([Ct(function(e){this.setContentHint(e.contentHint||"detail")})],xt.prototype,"capture",1);var ys=class extends wt{constructor(i){super(i),this._log.id=`s-${this._log.id}`,this.isScreen=!0}addAudioProcessor(i,e,t){this.pipeline.silentNode.setNode(t),this.pipeline.mixNode.setNode(e),this.pipeline.aec.setNode(i),this.enableTrackAEC(!1)}removeAudioProcessor(i){this.pipeline.aec.node===i&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode(),this.enableTrackAEC(!0))}};var JS='registerProcessor("dumper",class extends AudioWorkletProcessor{constructor(e){super(),this.sourceSampleRate=e.processorOptions.sourceSampleRate||48e3,this.targetSampleRate=e.processorOptions.targetSampleRate||48e3,this.port.onmessage=e=>{this.port2=e.data.port}}process(e){return(this.port2||this.port).postMessage(this.resampleAll(e,this.sourceSampleRate,this.targetSampleRate)),!0}resampleAll(r,s,a){if(s===a)return r;var o=[];for(let t=0;t<r.length;t++){o[t]=[];for(let e=0;e<r[t].length;e++)o[t][e]=this.resample(r[t][e],s,a)}return o}resample(t,e,r){if(e===r)return t;var s=Math.round(t.length*(this.targetSampleRate/this.sourceSampleRate)),a=new Float32Array(s),o=(t.length-1)/(s-1);a[0]=t[0];for(let e=1;e<s-1;e++){var l=e*o,p=Math.floor(l),h=Math.ceil(l);a[e]=t[p]+(t[h]-t[p])*(l-p)}return a[s-1]=t[t.length-1],a}});',Wh;function oa(s,i=48e3,e=1,t){return f(this,null,function*(){let r=Ae("dump");Wh||(Wh=sr(r,URL.createObjectURL(new Blob([JS],{type:"application/javascript"})))),yield Wh;let o=r.sampleRate,n=new AudioWorkletNode(r,"dumper",{numberOfInputs:s.length,numberOfOutputs:0,processorOptions:{sourceSampleRate:o,targetSampleRate:i}});return n.channelCountMode="explicit",n.channelCount=e,t&&n.port.postMessage({port:t},[t]),s.forEach((a,c)=>a.connect(n,0,c)),new ReadableStream({start(a){n.port.onmessage=c=>{a.enqueue(c.data)}},cancel(){s.forEach(a=>a.disconnect(n)),n.port.close()}})})}var Ed=class extends Gc{constructor(e){super();this.room=e;d(this,"_localAudioTrack");d(this,"_localScreenAudioTrack");d(this,"log");d(this,"denoiser");d(this,"voiceChanger");d(this,"mixChangedDebounce");d(this,"audioProcessor");d(this,"encodePipeline",[]);d(this,"decodePipeline",[]);d(this,"getPCMAbortCtrlMap",new Map);d(this,"audioFrameEventConfigMap",new Map);d(this,"audioReferenceMap",new Map);d(this,"isLocalAudioNeedAudioProcess",!1);d(this,"isScreenAudioNeedAudioProcess",!1);this.log=C.createLogger({parent:e==null?void 0:e.getLogger(),id:"am",userId:e==null?void 0:e.userId,sdkAppId:e==null?void 0:e.sdkAppId}),this.installEvent()}get localAudioTrack(){return this._localAudioTrack}get _localAudioPipline(){var e;return(e=this._localAudioTrack)==null?void 0:e.pipeline}get _localScreenAudioPipeline(){var e;return(e=this._localScreenAudioTrack)==null?void 0:e.pipeline}dump(e){var u,m;if(!this._localAudioTrack)return;let t=[],r=[];(u=this._localAudioPipline)!=null&&u.source.node&&(t.push(this._localAudioPipline.source.node),r.push("mic")),(m=this._localAudioPipline)!=null&&m.denoiser.node&&(t.push(this._localAudioPipline.denoiser.node),r.push("mic-processed")),this.mixWeight>1&&(t.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),r.push("mix")),this.log.info(`dump audio track ${r}, duration: ${e}`);let o=new AbortController,n=[],a=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),o.abort("timeout")},e*1e3),c=()=>{for(let p=0;p<r.length;p++){let h=URL.createObjectURL(new Blob(n[p])),T=document.createElement("a");T.href=h,T.download=`${r[p]}.pcm`,T.style.display="none",document.body.appendChild(T),T.click(),URL.revokeObjectURL(h),T.remove()}clearTimeout(a),o.abort("download")},l=oa(t).then(p=>p.pipeTo(new WritableStream({write(h){h.forEach((T,g)=>n[g]=n[g]?n[g].concat(T[0]):[T[0]])}}),o).catch(h=>c));return{then:l.then.bind(l),download:c}}getPCM(e,t){var D,j,V;if(typeof WritableStream=="undefined"){this.log.warn("getPCM failed: browser not support WritableStream");return}let{enable:r,sampleRate:o=48e3,channelCount:n=1,port:a}=(t===""?this.audioFrameEventConfigMap.get(""):this.audioFrameEventConfigMap.get(t)||this.audioFrameEventConfigMap.get("*"))||{};if(!r)return;this.log.info(`getPCM ${t||"local"}`);let c=Math.floor(o*.04),l=new Float32Array(c),u=new Float32Array(c),m,p,h=0,T=new AbortController,g=t===""?(D=this._localAudioTrack)==null?void 0:D.mediaTrack:(V=(j=this.room)==null?void 0:j.remotePublishedUserMap.get(t))==null?void 0:V.remoteAudioTrack.mediaTrack;if(!g){this.log.info(`getPCM failed: ${t||"local"} has no audio track`);return}let R=Ae().createMediaStreamSource(new MediaStream([g]));return oa([R],o,n,a).then(ae=>ae.pipeTo(new WritableStream({write(b){b[0][0]&&(h+b[0][0].length>c?(l.set(b[0][0].subarray(0,c-h),h),m=b[0][0].subarray(c-h),b[0][1]&&(u.set(b[0][1].subarray(0,c-h),h),p=b[0][1].subarray(c-h)),h+=c-h):(m&&(l.set(m,h),h+=m.length,m=void 0),p&&(u.set(p,h),p=void 0),l.set(b[0][0],h),b[0][1]&&u.set(b[0][1],h),h+=b[0][0].length),h>=c&&(h=0,e({userId:t,sampleRate:o,channelCount:n,data:n===1?l:[l,u]}),l=new Float32Array(c),u=new Float32Array(c)))}}),T).catch(b=>this.log.warn(`stop getPCM reason:${b}`))),T}get hasScreenAudioTrack(){return!E(this._localScreenAudioTrack)}get hasAudioTrack(){return!E(this._localAudioTrack)}changeInput(e){var t,r;if(e instanceof ys)return this._localScreenAudioTrack=e,this.isScreenAudioNeedAudioProcess&&((t=this.audioProcessor)!=null&&t.screenAudioWorkletNode)&&(e.addAudioProcessor(this.audioProcessor.screenAudioWorkletNode,this.audioProcessor.mixNode,this.audioProcessor.silentNode),this.audioReferenceMap.forEach((o,n)=>{e.mixAudioReference(o,n)})),e.pipeline.connect(),this.mixOnChange();if(e instanceof wt)return this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),this.isLocalAudioNeedAudioProcess&&((r=this.audioProcessor)!=null&&r.localAudioWorkletNode)&&(e.addAudioProcessor(this.audioProcessor.localAudioWorkletNode,this.audioProcessor.mixNode,this.audioProcessor.silentNode),this.audioReferenceMap.forEach((o,n)=>{e.mixAudioReference(o,n)})),e.pipeline.connect(),this.mixOnChange();if(e instanceof Ai)return e.setOutputMediaStreamTrack(e.mediaTrack)}mixAudioReference(e,t){var r;(r=this._localAudioTrack)==null||r.mixAudioReference(e,t)}unMixAudioReference(e){var t;(t=this._localAudioTrack)==null||t.unMixAudioReference(e)}setAudioReferenceVolume(e,t){var r;(r=this._localAudioTrack)==null||r.setAudioReferenceVolume(e,t)}mixOnChange(){return this.mixChangedDebounce||(this.mixChangedDebounce=Promise.resolve().then(()=>{var e,t;return delete this.mixChangedDebounce,Promise.all([(e=this._localAudioTrack)==null?void 0:e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),(t=this._localScreenAudioTrack)==null?void 0:t.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)])})),this.mixChangedDebounce}removeInput(e){e instanceof ys?delete this._localScreenAudioTrack:e instanceof wt?delete this._localAudioTrack:e instanceof Ai}addDenoiser(e){var t;this.denoiser=e,(t=this._localAudioTrack)==null||t.addDenoiser(e)}addAudioProcessor(e,t,r,o){var n;this.audioProcessor={localAudioWorkletNode:r,mixNode:e,silentNode:t,screenAudioWorkletNode:o},this.isLocalAudioNeedAudioProcess&&this._localAudioTrack&&r&&(this._localAudioTrack.addAudioProcessor(r,e,t),this.audioReferenceMap.forEach((a,c)=>{var l;(l=this._localAudioTrack)==null||l.mixAudioReference(a,c)})),this.isScreenAudioNeedAudioProcess&&this._localScreenAudioTrack&&o&&((n=this._localScreenAudioTrack)==null||n.addAudioProcessor(o,e,t),this.audioReferenceMap.forEach((a,c)=>{var l;(l=this._localScreenAudioTrack)==null||l.mixAudioReference(a,c)}))}removeDenoiser(e){var t;return delete this.denoiser,(t=this._localAudioTrack)==null?void 0:t.removeDenoiser(e)}addVoiceChanger(e,t){var r;this.voiceChanger=[e,t],(r=this._localAudioTrack)==null||r.pipeline.voiceChanger.setNode(e,t)}removeVoiceChanger(){var e;delete this.voiceChanger,(e=this._localAudioTrack)==null||e.pipeline.voiceChanger.deleteNode()}removeAudioProcessor(e,t){var r,o;delete this.audioProcessor,(r=this._localAudioTrack)==null||r.removeAudioProcessor(e),(o=this._localScreenAudioTrack)==null||o.removeAudioProcessor(t)}destroy(){this.close(),this.audioReferenceMap.clear(),this.getPCMAbortCtrlMap.forEach(e=>e==null?void 0:e.abort("destroy")),this.getPCMAbortCtrlMap.clear(),this.audioFrameEventConfigMap.clear(),this.uninstallEvent()}addEncodeProcessor({processor:e,type:t}){var r;this.encodePipeline.includes(e)||(this.encodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}addDecodeProcessor({processor:e,type:t}){var r;this.decodePipeline.includes(e)||(this.decodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}handleLocalTrackStarted({room:e,userId:t}){var o;if(e!==this.room||this.getPCMAbortCtrlMap.get(t))return;let r=this.getPCM(n=>{var a;(a=this.room)==null||a.emit("audio-frame",n)},"");this.getPCMAbortCtrlMap.set(t,r),this.getPCMAbortCtrlMap.get(t)&&((o=this._localAudioTrack)==null||o.on("input-media-track-changed",()=>{let n=this.getPCMAbortCtrlMap.get(t);n&&(n.abort("inputMediaTrackChanged"),n=this.getPCM(a=>{var c;(c=this.room)==null||c.emit("audio-frame",a)},""),this.getPCMAbortCtrlMap.set(t,n))}))}handleLocalTrackStopped({room:e,userId:t}){if(e!==this.room)return;let r=this.getPCMAbortCtrlMap.get(t);r&&(r.abort("stopLocalAudio"),this.getPCMAbortCtrlMap.delete(t))}handleRemoteTrackStarted({room:e,userId:t}){if(e===this.room&&!this.getPCMAbortCtrlMap.get(t)){let r=this.room.audioManager.getPCM(o=>{var n;(n=this.room)==null||n.emit("audio-frame",o)},t);this.getPCMAbortCtrlMap.set(t,r)}}handleRemoteTrackStopped({room:e,userId:t}){if(e!==this.room)return;let r=this.getPCMAbortCtrlMap.get(t);r&&(r.abort("stopRemoteAudio"),this.getPCMAbortCtrlMap.delete(t))}installEvent(){S.on("113",this.handleLocalTrackStarted,this),S.on("114",this.handleLocalTrackStopped,this),S.on("115",this.handleRemoteTrackStarted,this),S.on("116",this.handleRemoteTrackStopped,this)}uninstallEvent(){S.off("113",this.handleLocalTrackStarted),S.off("114",this.handleLocalTrackStopped),S.off("115",this.handleRemoteTrackStarted),S.off("116",this.handleRemoteTrackStopped)}updateAudioReference({type:e,audioReference:t,refId:r,volume:o}){if(e==="add"){if(this.audioReferenceMap.get(r)||!t||(this.audioReferenceMap.set(r,t),!this.audioProcessor))return;this.mixAudioReference(t,r)}else if(e==="remove")this.audioReferenceMap.get(r)&&(this.audioReferenceMap.delete(r),this.unMixAudioReference(r));else if(e==="updateVolume"){if(!this.audioProcessor||E(o))return;this.setAudioReferenceVolume(r,o)}}};function bs(s=30,i=2){return K((e,t)=>function(...r){return new Promise((o,n)=>{let a=setTimeout(()=>{let c=new N({code:I.API_CALL_TIMEOUT,message:`checkPendingPromise ${t}() timeout ${s}s`});(this.log||this._log||C).warn(c),i===2?n(c):i===1&&o()},s*1e3);this._checkPendingPromiseSet||(this._checkPendingPromiseSet=new Set),this._checkPendingPromiseSet.add(a),e.apply(this,r).then(o,n).finally(()=>{clearTimeout(a),this._checkPendingPromiseSet&&a&&this._checkPendingPromiseSet.delete(a)})})})}function Vf(){return K((s,i)=>function(...e){return this._checkPendingPromiseSet&&(this._checkPendingPromiseSet.forEach(t=>clearTimeout(t)),this._checkPendingPromiseSet.clear()),s.apply(this,e)})}var xi=class xi extends ps{constructor(e,t,r){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:r,room:e});this.room=e;this.user=t;d(this,"tinyId");d(this,"isRemote",!0);d(this,"jitterBufferDelay",0);d(this,"availableState");d(this,"remotePublishState");d(this,"_triggerCheckDecodeSubject",ot(ue(this,xi.STATE_SUBSCRIBE)));d(this,"ignoreUpdatePlayingState");this.tinyId=t.tinyId,this.availableState=new Y(`${t.userId}-${this.mediaType}-available`,"remote-track-available"),this.remotePublishState=new Y(`${t.userId}-${this.mediaType}-remote-publish`,"remote-track-publish"),he(Qn(ue(this,Y.STATECHANGED),ue(this.remotePublishState,Y.STATECHANGED)),ea(()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing)),Se(c=>{this.availableState.state!==(c?Y.ON:Y.OFF)&&(this.availableState.state=c?Y.ON:Y.OFF),!(this.isRemotePublished&&this.ignoreUpdatePlayingState)&&this.updatePlayingState(c)}));let o=he(ue(this.player,G.ERROR),Xt(c=>c.code===MediaError.MEDIA_ERR_DECODE)),n=he(Zn(5e3),Xt(()=>this.ignoreDecodeError||!this.isSubscribed||!this.isPlayCalled||!this.stat.bytesReceived||!this.isRemotePublished?!1:this.player.isPlaying||(this.kind===_.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)?(this.reportDecodeResult(!0),!1):!0)),a=he(rh(o,n),Le(ue(this,Y.INIT)));he(this._triggerCheckDecodeSubject,Xt(()=>!this.ignoreDecodeError),Ss(a),Se(c=>{this.reportDecodeResult(!1,c)}))}setMute(e){this.isRemotePublished&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.isRemotePublished&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}checkDecodeResult(){this._triggerCheckDecodeSubject.next(!0)}waitHasMediaTrack(){return new Promise(e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)})}get ignoreDecodeError(){var t,r,o,n;return((n=(o=(r=(t=this.room)==null?void 0:t.networkQuality)==null?void 0:r.hadRecentBadDownlink)==null?void 0:o.call(r,2))!=null?n:!1)||this.player.isInAutoPlayFailedState}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===xi.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===Y.ON}get isNeedPlay(){return this.isAvailable&&this.isPlayCalled}subscribe(e){return e}unsubscribe(){this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}reportDecodeResult(e,t){var o,n;let r=this.kind===_.AUDIO;if(y[e?"addSuccessEvent":"addFailedEvent"]({key:r?504700:514702}),!r){let a=((o=this.room)==null?void 0:o.downlinkVideoCodec.toUpperCase())||"H264";y[e?"addSuccessEvent":"addFailedEvent"]({key:mo[`DECODE_${a}_RESULT`]}),e||this.log.warn(`${(n=this.room)==null?void 0:n.downlinkVideoCodec} decode failed`)}e||(y.addEnum({key:r?504701:514703,value:as()}),se.uploadEvent({log:`stat-decode-failed-${this.kind}-${Dt()||Mt()}`,userId:this.room.userId}),this._log.warn(`decode failed: isPlaying: ${this.player.isPlaying} ${this.kind===_.AUDIO?`audioLevel: ${this.getAudioLevel()}`:`framesDecoded: ${this.stat.framesDecoded>0}`}`),this.emit("decode-failed",{error:t}))}updatePlayingState(e){if(this.player.isPlayCalled&&this.player.setTrack(this.playerMediaTrack),this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.isRemotePublished||!this.outMediaTrack)){this.log.info(`abort play, isSubscribed: ${this.isSubscribed} isAvailable: ${this.isRemotePublished} hasTrack: ${!!this.outMediaTrack} `);return}super.updatePlayingState(e)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.remotePublishState.state=this.isRemotePublished?Y.ON:Y.OFF,this.emit("remote-publish-changed",this.isRemotePublished)}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};d(xi,"STATE_SUBSCRIBE","subscribe"),O([bs(5,1)],xi.prototype,"waitHasMediaTrack",1),O([ve(Y.INIT,xi.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),S.emit(A.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),yt(521716,!1)],xi.prototype,"subscribe",1),O([ve(xi.STATE_SUBSCRIBE,Y.INIT,{sync:!0,success(){this.log.info("unsubscribed"),S.emit(A.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],xi.prototype,"unsubscribe",1);var Oo=xi;var Ai=class extends Oo{constructor(e,t){super(e,t,1);d(this,"volume",0);d(this,"mediaType",1);d(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.audioManager}get dbVolume(){return ms.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}onPlayerError(e){this.enableDecodeFrame&&(this._log.warn("use audio decoder"),this.room.enableInsertableStreams())}get enableDecodeFrame(){var e,t;return this.manager?this.manager.decodePipeline.some(r=>r)||((t=(e=this.player.element)==null?void 0:e.error)==null?void 0:t.code)===MediaError.MEDIA_ERR_DECODE&&Vc().AudioDecoder&&gi:!1}get enableDecryptFrame(){return this.manager&&!!this.manager.decodePipeline[0]}decodeFrame(e){if(!this.manager)return e;let t=e;for(let[r,o]of this.manager.decodePipeline.entries()){if(!o)continue;let n={frame:e,track:this};if(r===1&&this.isAvailable&&this.room.role==="audience"&&(n.onAudioFrameNTPTime=({ntp:a,frame:c,hasLeavingTag:l})=>{this.emit("audio-frame-with-ntp",{ntp:a,frame:c,hasLeavingTag:l})}),t=o(n),!t)return}return t}getAudioLevel(){if(!this.isAvailable)return 0;let e=this.volume||super.getAudioLevel();return e>1?1:e}getInternalAudioLevel(){return this.isAvailable?super.getInternalAudioLevel():0}get isRemotePublished(){return this.user.muteState.audioAvailable}};var Sd=class extends we{constructor(e,t,r,o,n){super(e,{useDefaultProgram:!0,useFbo:!0,name:"alpha",create2d:!0,logger:t});this.setContainer=o;d(this,"initStat",{alphaStitchingType:1});d(this,"end",ot());d(this,"minSize",320);d(this,"maxSize",1280);d(this,"draggable",!1);d(this,"startDragX",0);d(this,"startDragY",0);d(this,"left",0);d(this,"top",0);d(this,"baseWidth",320);d(this,"baseRatio");d(this,"container");this.initStat=n,this.draggable=r,this.bindDragEvents(),y.addEnum({key:515700,value:1}),this.draggable&&y.addEnum({key:515700,value:11})}bindDragEvents(){let e=this.context._canvas;if(e)if(this.draggable){let t=Le(this.end);he(ue(e,"mousedown"),ta(this.startDrag.bind(this)),Vr(()=>he(ue(window,"mousemove"),Le(ue(window,"mouseup")))),t,Se(this.doDrag.bind(this))),he(ue(e,"dblclick"),t,Se(this.resetPosition.bind(this))),he(ue(e,"wheel"),t,Se(this.handleZoom.bind(this))),this.renderCanvas()}else{if(!this.container)return;this.container.style.removeProperty("left"),this.container.style.removeProperty("top"),this.end.next()}}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}startDrag(e){e.preventDefault(),e.button===0&&(this.startDragX=e.clientX-this.left,this.startDragY=e.clientY-this.top)}renderCanvas(){let{container:e}=this;e||this.setContainer(),!(!e||!this.baseRatio||!this.draggable)&&(e.style.setProperty("width",`${this.baseWidth}px`),e.style.setProperty("height",`${this.baseWidth/this.baseRatio}px`),e.style.setProperty("position","fixed"),e.style.setProperty("left",`${this.left}px`),e.style.setProperty("top",`${this.top}px`))}doDrag(e){e.preventDefault(),this.left=e.clientX-this.startDragX,this.top=e.clientY-this.startDragY,this.renderCanvas()}handleZoom(e){e.preventDefault();let t=.1,r=e.deltaY,o=this.context._canvas;o&&(this.baseWidth||(this.baseWidth=o.offsetWidth),r<0?this.baseWidth=Math.min(this.baseWidth*(1+t),this.maxSize):this.baseWidth=Math.max(this.baseWidth*(1-t),this.minSize),this.renderCanvas())}resetPosition(){this.left=0,this.top=0,this.renderCanvas()}onRatioReset(){this.renderCanvas()}draw2d(e,t,r,o,n){var h;let{ctx2d:a}=this,c=this.context._canvas;if(!a||!c)return!1;let l=super.draw2d(e,t,r,o,n),u=a.getImageData(0,0,o,n),{data:m}=u,p=!1;if(this.initStat.alphaStitchingType===1){let T=Math.floor(o/2);for(let g=0;g<n;g++)for(let R=0;R<T;R++){let D=(g*o+R)*4,j=R+T,V=(g*o+j)*4,ae=m[V];m[V+3]=0;let b=ae>=100;m[D+3]=b?255:0}p=super.draw2d(u,0,0,0,0,T,n),c.width=T}else if(this.initStat.alphaStitchingType===2){let T=Math.floor(n/2);for(let g=0;g<T;g++)for(let R=0;R<o;R++){let D=(g*o+R)*4,V=((g+T)*o+R)*4,ae=m[V];m[V+3]=0;let b=ae>=100;m[D+3]=b?255:0}p=super.draw2d(u,0,0,0,0,o,T),c.height=T}return(h=this.context.ctx)==null||h.clearRect(0,0,o,n),l&&p}close(){this.baseRatio=void 0,this.end.next(),this.end.complete()}};function XS(s){return[15,30,45,60].reduce((e,t)=>Math.abs(t-s)<Math.abs(e-s)?t:e)}var Ui=class extends Oo{constructor(e,t,r=4){super(e,t,r);d(this,"mediaType",4);d(this,"source");d(this,"shouldRenderAlpha",!1);d(this,"alphaNode");d(this,"shouldBeDraggable",!0);d(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0,keyFramesDecoded:0});d(this,"_keyFrameCountLogged",!1);d(this,"_keyFrameStartTimestamp",0);d(this,"_keyFrameStartCount",0);d(this,"_keyFrameIntervals",[]);d(this,"_prevKeyFrameTimestamp",0);this.manager=e.videoManager,this.on("first-video-frame",o=>{this.room.emit("first-video-frame",o)})}isAlphaSei(e){if(this.userId!==e.userId||e.seiPayloadType!==50)return!1;let t=new Uint8Array(e.data);return t.length%3!==0||t[0]!==0||t[1]!==1?!1:t}play(e,t){return t!=null&&t.canvasRender&&!this.source&&this.useCanvasPlayer(),super.play(e,t).then(()=>{this.player.calculateStat(),S.emit("156",{track:this,player:this.player})})}updateAlphaRenderInfo(e){let t=this.isAlphaSei(e);if(t)if(!this.alphaNode)this.shouldRenderAlpha=!0,this.player.shouldRenderAlpha=!0,this.useCanvasPlayer(t[2]);else{let r=t[2];if(this.alphaNode.baseRatio&&this.alphaNode.initStat.alphaStitchingType===r)return;this.alphaNode.initStat={alphaStitchingType:r};let o=this.player.getElement();if(o){let n=o.videoWidth/o.videoHeight;n&&(this.alphaNode.baseRatio=n*(r===1?.5:2),this.alphaNode.onRatioReset())}this.player.canvas&&(this.player.canvas.id=this.generateAlphaCanvasName(r))}}generateAlphaCanvasName(e){let t="alpha",r=Nn[e];return`${t}_${r}_${this.userId}`}useCanvasPlayer(e){if(this.log.info(`useCanvasPlayer(), has element:${!!this.player.element}`),!this.player.element)return;let t=new Qe({frameRate:15,logger:this.log,name:this.shouldRenderAlpha&&e?this.generateAlphaCanvasName(e):this.userId});t.create({alpha:this.shouldRenderAlpha,willReadFrequently:this.shouldRenderAlpha});let r=new As(t,{name:"remotePlayer",logger:this.log});if(this.source=t.createVideoPlayerSource(this.player),this.player.setCanvas(t._canvas),this.shouldRenderAlpha&&e){let o=()=>{!this.player.container||!this.alphaNode||(this.alphaNode.container=this.player.container,this.alphaNode.renderCanvas())},n=new Sd(t,this.log,this.shouldBeDraggable,o,{alphaStitchingType:e});this.source.connect(n),n.connect(r),this.alphaNode=n}else this.source.connect(r);ir()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,t),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let t=this.decodeFPS,r=XS(t);if(!te(t)||t<=0){this.log.debug(`updateCanvasPlayerFPS() ignore decoder: ${t} `);return}if(r===e.frameRate){this.log.debug(`updateCanvasPlayerFPS() ignore ClosestFPS ${r} == ${e.frameRate}`);return}this.log.info(`updateCanvasPlayerFPS() decoder: ${t}, closest: ${r}, current: ${e.frameRate}`),e.frameRate=r}get decodeFPS(){var n;let{msg_video_status:e}=((n=this.room.heartbeatReport)==null?void 0:n.msg_down_stream_info.find(a=>a.msg_user_info.str_identifier===this.userId))||{},t=this.mediaType===2?7:this.isSmall?3:2;if(!e||e.length===0)return 0;let r=e.find(a=>a.uint32_video_stream_type===t);return(r==null?void 0:r.uint32_video_dec_fps)||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),S.emit("157",{track:this,player:this.player}),this.alphaNode&&this.alphaNode.close(),super.stop()}decodeFrame(e){if(!this.manager)return e;for(let t of this.manager.decodePipeline)if(t&&(e=t({frame:e,track:this}),!e))return;return e}get isBig(){return this.mediaType===4}get isSmall(){return this.mediaType===8}changeType(e){this.room.changeType(e,this.user)}get isRemotePublished(){return this.user.muteState.videoAvailable}setMirror(e){e==="publish"||e==="both"||super.setMirror(e)}setDraggable(e){this.shouldBeDraggable=e,this.alphaNode&&(this.alphaNode.draggable=e,this.alphaNode.bindDragEvents())}onDecodeDowngradeStateChanged(e){this.emit("decode-downgrade-state-changed",e)}updateKeyFramesDecoded(e){let t=this.stat.keyFramesDecoded||0;if(this.stat.keyFramesDecoded=e,this._keyFrameCountLogged)return;let r=Date.now();if(!this._keyFrameStartTimestamp){this._keyFrameStartTimestamp=r,this._keyFrameStartCount=e,this._prevKeyFrameTimestamp=r;return}if(this._prevKeyFrameTimestamp&&e>t){let n=e-t,c=(r-this._prevKeyFrameTimestamp)/1e3/n;this._keyFrameIntervals.push(c)}this._prevKeyFrameTimestamp=r;let o=r-this._keyFrameStartTimestamp;if(o>=16e3){let n=e-this._keyFrameStartCount,a=n>0?o/1e3/n:0,c=`${n} keyframes in 16s ${a} [${this._keyFrameIntervals.map(u=>u.toFixed(1)).join(",")}] keyFramesDecoded ${e}`,l=a<=2.5?"debug":"info";this.log[l](c),this._keyFrameCountLogged=!0}}},Po=class extends Ui{constructor(e,t){super(e,t,2);d(this,"mediaType",2);d(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}};var ko=new Map;S.on(A.JOIN_SUCCESS,({room:s})=>{Me(s.userId,{eventId:32788})});S.on(A.LEAVE_START,({room:s})=>{Me(s.userId,{eventId:32789})});S.on(A.LOCAL_TRACK_PUBLISHED,({track:s})=>{if(s.room){let i=32769;s.mediaType===4?i=32768:s.mediaType===2&&(i=32805),Me(s.room.userId,{eventId:i})}});S.on(A.LOCAL_TRACK_UNPUBLISHED,({track:s})=>{if(s.room){let i=32771;s.mediaType===4?i=32770:s.mediaType===2&&(i=32806),Me(s.room.userId,{eventId:i})}});S.on(A.TRACK_MUTED,({track:s})=>{s.room&&(s.kind===_.AUDIO?Me(s.room.userId,{eventId:s.isRemote?32785:32772,remoteUserId:s.isRemote?s.userId:void 0}):Me(s.room.userId,{eventId:s.isRemote?32784:32773,remoteUserId:s.isRemote?s.userId:void 0}))});S.on(A.TRACK_UNMUTED,({track:s})=>{s.room&&(s.kind===_.AUDIO?Me(s.room.userId,{eventId:s.isRemote?32787:32774,remoteUserId:s.isRemote?s.userId:void 0}):Me(s.room.userId,{eventId:s.isRemote?32786:32775,remoteUserId:s.isRemote?s.userId:void 0}))});S.on(A.REMOTE_TRACK_SUBSCRIBED,({track:s})=>{s.room&&(s.mediaType===1&&Me(s.room.userId,{eventId:32777,remoteUserId:s.userId}),s.mediaType===4&&Me(s.room.userId,{eventId:32776,remoteUserId:s.userId}),s.mediaType===8&&Me(s.room.userId,{eventId:32803,remoteUserId:s.userId}))});S.on(A.REMOTE_TRACK_UNSUBSCRIBED,({track:s})=>{s.room&&(s.mediaType===1&&Me(s.room.userId,{eventId:32779,remoteUserId:s.userId}),s.mediaType===4&&Me(s.room.userId,{eventId:32778,remoteUserId:s.userId}),s.mediaType===8&&Me(s.room.userId,{eventId:32804,remoteUserId:s.userId}))});S.on(A.SWITCH_DEVICE_SUCCESS,({track:s})=>{s.room&&Me(s.room.userId,{eventId:s.kind===_.VIDEO?32780:32781})});S.on(A.LOCAL_TRACK_REPLACED,({track:s})=>{s.room&&Me(s.room.userId,{eventId:s.kind===_.VIDEO?32782:32783})});S.on(A.SIGNAL_CONNECTION_STATE_CHANGED,({room:s,prevState:i,state:e})=>{let t;switch(e){case"CONNECTED":i==="RECONNECTING"?t=32795:t=32791;break;case"DISCONNECTED":i==="RECONNECTING"?t=32796:t=32790;break;case"RECONNECTING":t=32794;break}t&&Me(s.userId,{eventId:t})});S.on(A.PEER_CONNECTION_STATE_CHANGED,({room:s,prevState:i,state:e,remoteUserId:t})=>{let r=!!t,o;switch(e){case"CONNECTED":i==="RECONNECTING"?o=r?32801:32798:o=r?32793:32792;break;case"DISCONNECTED":i==="RECONNECTING"&&(o=r?32802:32799);break;case"RECONNECTING":o=r?32800:32797;break}o&&Me(s.userId,{eventId:o,remoteUserId:t})});S.on(A.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({implementation:s,userId:i,remoteUserId:e,codec:t,isHWCodec:r,prevImplementation:o,streamType:n})=>{let a=r?1:0;o||(a=r?3:2);let c={H264:0,H265:1,VP8:2}[t.toUpperCase()],l={eventId:4004,param1:a,param2:c,streamType:n||2};e&&(l.remoteUserId=e,l.eventId=4005),Me(i,l),y.addEnum({key:e?514701:513701,value:a}),y.addEnum({key:e?514700:513700,value:c})});S.on(A.LOCAL_TRACK_RECAPTURE,({track:s,error:i})=>{if(s.userId){let e={eventId:2003,param1:0};s.kind===_.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType=s.streamType==="auxiliary"?7:2,i&&(e.param1=8)),Me(s.userId,e)}});function Me(s,i){let e=L(M({},i),{timestamp:Wi()});ko.has(s)?ko.get(s).push(e):ko.set(s,[e])}function Ff(s){if(ko.has(s)){let i=ko.get(s).map(e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,uint32_param1:e.param1,uint32_param2:e.param2,uint32_video_stream_type:e.streamType}));return ko.delete(s),i}return[]}function Bf(...s){return K((i,e)=>function(...t){return zS.call(this,s,t,e,this._name),i.apply(this,t)})}function zS(s,i,e,t){try{if(Ie(s))for(let r=0;r<s.length;r++)Id.call(this,{rule:s[r],value:i[r],key:s[r].name,fnName:e,className:t});else Id.call(this,{rule:s,value:i[0],key:s.name,fnName:e,className:t})}catch(r){throw C.error(r),r}}function Id({rule:s,value:i,key:e,fnName:t,className:r}){if(E(i)){if(s.required)throw new N({code:I.INVALID_PARAMETER,message:W({key:H.INVALID_PARAMETER_REQUIRED,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(E(s.defaultValue))return;i=s.defaultValue}if(Array.isArray(s.type)){let a=!1;for(let c=0;c<s.type.length;c++)s.type[c]===null&&i===null&&(a=!0),me(s.type[c])&&i instanceof s.type[c]&&(a=!0),ne(s.type[c])&&Pe(i)===s.type[c].toLowerCase()&&(a=!0);if(!a)throw new N({code:I.INVALID_PARAMETER,message:W({key:H.INVALID_PARAMETER_TYPE,data:{key:e,rule:{type:s.type.map(c=>es(c)?Js(c):ne(c)?c:Pe(c))},fnName:t,value:i},link:{className:r,fnName:t}})})}else if(!E(s.type)&&Pe(i)!==s.type)throw new N({code:I.INVALID_PARAMETER,message:W({key:H.INVALID_PARAMETER_TYPE,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(s.allowEmpty===!1){let a=te(i)&&(i===0||Number.isNaN(i)),c=ne(i)&&i.trim()==="";if(a||c)throw new N({code:I.INVALID_PARAMETER,message:W({key:H.INVALID_PARAMETER_EMPTY,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})})}if(s.notLessThanZero&&te(i)&&i<0)throw new N({code:I.INVALID_PARAMETER,message:W({key:H.CANNOT_LESS_THAN_ZERO,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(!E(s.min)&&te(i)&&i<s.min)throw new N({code:I.INVALID_PARAMETER,message:W({key:H.INVALID_PARAMETER_MIN,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(!E(s.max)&&te(i)&&i>s.max)throw new N({code:I.INVALID_PARAMETER,message:W({key:H.INVALID_PARAMETER_MAX,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(ne(s.instanceOf)){if(!i||i._name!==s.instanceOf)throw new N({code:I.INVALID_PARAMETER,message:W({key:H.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})})}else if(me(s.instanceOf)&&!(i instanceof s.instanceOf))throw new N({code:I.INVALID_PARAMETER,message:W({key:H.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(s.values&&!s.values.includes(i))throw new N({code:I.INVALID_PARAMETER,message:W({key:H.INVALID_PARAMETER_RANGE,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});let{properties:o}=s;dt(o)&&vt(i)&&Object.keys(o).forEach(a=>{Id.call(this,{rule:o[a],value:i&&i[a],key:`${e}.${a}`,fnName:t,className:r})});let{arrayItem:n}=s;dt(n)&&Ie(i)&&i.forEach((a,c)=>{Id.call(this,{rule:n,value:a,key:`${e}[${c}]`,fnName:t,className:r})}),me(s.validate)&&s.validate.call(this,i,e,t,r,this)}var Hf=We(Ze(),1);var Ad=class extends Hf.EventEmitter{constructor(e,t,r="userId"){super();this.mySelfId=e;this._log=t;this.key=r;d(this,"userMap",new Map);d(this,"remotePublishedUserMap",new Map);d(this,"asrRobotUserMap",new Map)}get hasRobotUser(){return!![...this.remotePublishedUserMap.values()].find(e=>e.isRobot)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:r,tinyId:o,role:n,fromType:a}=e;if(a===Hs){this.addAsrRobotUser(e);return}if(this.userMap.has(t))return;let c={userId:r,tinyId:o,role:n===20?"anchor":"audience"};this.userMap.set(t,c),this.emit("1",c)}addAsrRobotUser(e){let t=e[this.key],{userId:r,tinyId:o,role:n}=e;if(this.asrRobotUserMap.has(t))return;let a={userId:r,tinyId:o,role:n===20?"anchor":"audience"};this.asrRobotUserMap.set(t,a),this.emit("8",a)}deleteUser(e,t){let r=this.userMap.get(e);if(!r)return;if(this.asrRobotUserMap.has(e)){this.deleteAsrRobotUser(e);return}let n=`peer leave [${e}]`;E(t)||(n+=`:${Cl[t]}`),this._log.info(n);let a=this.remotePublishedUserMap.get(e);if(a){let c=a.muteState;a.flag=0,this.emit("5",a.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:c,muteState:a.muteState,flag:0})}this.userMap.delete(e),this.emit("2",{userId:r.userId,reason:t})}deleteAsrRobotUser(e){if(!this.asrRobotUserMap.has(e))return;let t=this.asrRobotUserMap.get(e);t&&(this.asrRobotUserMap.delete(e),this.emit("9",t))}setUserList(e){this.userMap.forEach(t=>{e.findIndex(r=>r[this.key]===t[this.key])<0&&this.deleteUser(t[this.key],0)}),e.forEach(t=>{!this.userMap.has(t[this.key])&&t[this.key]!==this.mySelfId&&this.addUser(t)})}addRemotePublishedUser(e){this.remotePublishedUserMap.has(e[this.key])||this.remotePublishedUserMap.set(e[this.key],e)}deleteRemotePublishedUser(e){this.remotePublishedUserMap.has(e)&&this.remotePublishedUserMap.delete(e)}setRemotePublishedUserList(e){this.remotePublishedUserMap.forEach(t=>{let r=t[this.key];if(e.findIndex(o=>o[this.key]===t[this.key])<0){this._log.info(`remote [${r}] unpublish`);let o=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(r),this.emit("6",{prevMuteState:o,muteState:t.muteState,flag:0})}}),e.forEach(t=>{var m;let r=t[this.key];if(r===this.mySelfId){this.emit("7",t);return}let{flag:o,userId:n,tinyId:a,fromType:c}=t,l=oi(o,n),u=(m=this.remotePublishedUserMap.get(r))==null?void 0:m.muteState;if(u){let p=this.remotePublishedUserMap.get(r);p&&p.flag!==o&&(p.flag=o,this._log.info(`remote publish updated: ${JSON.stringify(p.muteState)}`),this.emit("6",{prevMuteState:u,muteState:l,flag:o}))}else this._log.info(`remote publish. state: ${JSON.stringify(l)}`),this.addUser({userId:n,tinyId:a,role:20,fromType:c}),this.emit("3",t),this.emit("6",{prevMuteState:oi(0,n),muteState:l,flag:o})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};var $f=We(Ze(),1);var Lo=class extends $f.default{constructor(){super(...arguments);d(this,"_connectionTimeoutCount",0);d(this,"_isFirewallRestrictionEventEmitted",!1)}increaseTimeoutCount(){this._connectionTimeoutCount+=1,this.checkAndEmitFirewallRestriction()}resetTimeoutCount(){this._connectionTimeoutCount=0}checkAndEmitFirewallRestriction(){this._connectionTimeoutCount>=3&&!this._isFirewallRestrictionEventEmitted&&(this._isFirewallRestrictionEventEmitted=!0,this.emit("firewall-restriction"))}destroy(){this._connectionTimeoutCount=0,this._isFirewallRestrictionEventEmitted=!1,this.removeAllListeners()}};function Gh({timesInSecond:s,maxSizeInSecond:i,getSize:e}){return K((t,r)=>{let o=new WeakMap;return S.on(A.ROOM_DESTROY,({room:n})=>o.delete(n)),function(...n){let a=o.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},o.set(this,a)),a.timestamp===0?a.timestamp=Date.now():Date.now()-a.timestamp>1e3&&(a.timestamp=Date.now(),a.callCountInSecond=0,a.totalSizeInSecond=0),e&&(a.totalSizeInSecond+=e(...n)),a.timestamp!==0&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=s||a.totalSizeInSecond>i))throw new N({code:I.INVALID_OPERATION,message:W({key:H.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=s,isSize:a.totalSizeInSecond>i,name:r,timesInSecond:s,maxSizeInSecond:i}})});a.callCountInSecond++,t.call(this,...n)}})}var YS="2026-01-22 11:54:22",Wf=!0,Gf=function(){var s;if(Wf){Wf=!1,C.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${gt}/en/index.html`),console.info(`* Changelog: ${gt}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),C.info("TRTC Web SDK Version:",Ge),hi||C.debug("Build Time:",YS);let i=`UA: ${navigator.userAgent}
|
|
53
53
|
CPU core: ${navigator.hardwareConcurrency}, GPU: ${vr()}`;if(Te&&window.screen&&(window.screen.width||window.screen.height)){let t=`${window.screen.width}x${window.screen.height}@${window.devicePixelRatio}`;i+=`, screen: ${t}`}let e=navigator.deviceMemory;e&&(i+=`, minRAM: ${e}GB`),C.info(i),C.info(`URL: ${location.href}${((s=self.frameElement)==null?void 0:s.tagName)==="IFRAME"?" in iframe":""}`),ns().then(t=>{t&&C.info(ai)})}};var vs={SCENE_LIVE:"live",SCENE_RTC:"rtc",ROLE_ANCHOR:"anchor",ROLE_AUDIENCE:"audience",STREAM_TYPE_MAIN:"main",STREAM_TYPE_SUB:"sub",AUDIO_PROFILE_STANDARD:"standard",AUDIO_PROFILE_STANDARD_STEREO:"standard-stereo",AUDIO_PROFILE_HIGH:"high",AUDIO_PROFILE_HIGH_STEREO:"high-stereo",QOS_PREFERENCE_SMOOTH:"smooth",QOS_PREFERENCE_CLEAR:"clear",SPEAKER:"Speakerphone",HEADSET:"Headset earpiece"};var U={INVALID_PARAMETER:5e3,INVALID_OPERATION:5100,ENV_NOT_SUPPORTED:5200,DEVICE_ERROR:5300,SERVER_ERROR:5400,OPERATION_FAILED:5500,OPERATION_ABORT:5998,UNKNOWN_ERROR:5999},Ut=(v=>(v[v.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",v[v.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",v[v.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",v[v.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",v[v.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",v[v.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",v[v.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",v[v.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",v[v.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",v[v.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",v[v.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",v[v.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",v[v.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",v[v.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",v[v.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",v[v.INVALID_ROOM_ID_REQUIRED=5015]="INVALID_ROOM_ID_REQUIRED",v[v.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",v[v.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",v[v.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",v[v.INVALID_ROOM_ID_TYPE_MISMATCH=5019]="INVALID_ROOM_ID_TYPE_MISMATCH",v[v.INVALID_ROOM_ID_DUPLICATE=5020]="INVALID_ROOM_ID_DUPLICATE",v[v.INVALID_OPERATION=5100]="INVALID_OPERATION",v[v.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",v[v.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",v[v.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",v[v.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",v[v.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",v[v.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",v[v.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",v[v.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",v[v.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",v[v.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",v[v.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",v[v.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",v[v.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",v[v.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",v[v.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",v[v.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",v[v.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",v[v.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",v[v.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",v[v.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",v[v.DEVICE_ERROR=5300]="DEVICE_ERROR",v[v.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",v[v.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",v[v.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",v[v.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",v[v.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",v[v.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",v[v.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",v[v.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",v[v.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",v[v.NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX=5310]="NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX",v[v.SERVER_ERROR=5400]="SERVER_ERROR",v[v.NEED_TO_BUY=5401]="NEED_TO_BUY",v[v.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",v[v.OPERATION_FAILED=5500]="OPERATION_FAILED",v[v.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",v[v.REJOIN_FAILED=5502]="REJOIN_FAILED",v[v.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",v[v.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",v[v.VIDEO_ENCODE_FAILED=5505]="VIDEO_ENCODE_FAILED",v[v.AUDIO_ENCODE_FAILED=5506]="AUDIO_ENCODE_FAILED",v[v.VIDEO_DECODE_FAILED=5507]="VIDEO_DECODE_FAILED",v[v.AUDIO_DECODE_FAILED=5508]="AUDIO_DECODE_FAILED",v[v.OPERATION_ABORT=5998]="OPERATION_ABORT",v[v.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",v))(Ut||{});function jf({code:s,params:i,enableDocLink:e=!1}){let t="",r,o=Ut[s];try{r=Jf[o]}catch(n){r=Jf.UNKNOWN_ERROR}return me(r)?t=r(i):ne(r)&&(t=r),i.fnName&&!t.includes(i.fnName)&&(t[t.length-1]!=="."&&(t+="."),t+=` thrown from ${i.fnName}()`),e&&(t+=" doc:"),t}var Jf=L(M({},Xe),{INVALID_PARAMETER({fnName:s}){return`the parameters of the '${s}' you called does not meet the requirements, please check the API documentation.`},INVALID_PARAMETER_REQUIRED({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' is a required param when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_TYPE({key:s,rule:i,fnName:e,value:t}){let r=`${s||i.name}`,o="";return Array.isArray(i.type)?o=i.type.join("|"):o=i.type,`'${r}' must be type of ${o} when calling ${e}(), received type: ${Pe(t)}.`},INVALID_PARAMETER_EMPTY({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' cannot be '${t}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:s,rule:i,fnName:e,value:t}){let r=`${s||i.name}`,o=`${i.instanceOf.name||i.instanceOf}`;return`'${r}' must be instanceof ${o} when calling ${e}(), received type: ${Pe(t)}.`},INVALID_PARAMETER_RANGE({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' must be one of ${i.values.join("|")} when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_LESS_THAN_ZERO({key:s,rule:i,fnName:e}){return`'${s||i.name}' cannot be less than 0 when calling ${e}().`},INVALID_PARAMETER_MIN({key:s,rule:i,value:e}){return`the min value of ${s||i.name} is ${i.min}, received: ${e}.`},INVALID_PARAMETER_MAX({key:s,rule:i,value:e}){return`the max value of ${s||i.name} is ${i.max}, received: ${e}.`},INVALID_ELEMENT_ID({key:s,fnName:i}){return`'${s}' is not found in the document object when calling ${i}().`},INVALID_ELEMENT_ID_TYPE({key:s,fnName:i,type:e}){return`the element corresponding to '${s}' must be instanceof HTMLElement when calling ${i}(), received: ${e}.`},INVALID_STREAM_ID({key:s}){return`'${s}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},INVALID_ROOM_ID_STRING({key:s}){return`'${s}' must be a valid string.`},INVALID_ROOM_ID_INTEGER({key:s}){return`'${s}' must be an integer between [1, 4294967294].`},INVALID_ROOM_ID_INTEGER_STRING({key:s}){return`'${s}' must be an integer but go a string, use 'parseInt' to convert it or use 'strRoomId' instead.`},INVALID_ROOM_ID_REQUIRED(){return"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required."},INVALID_ROOM_ID_TYPE_MISMATCH({key:s}){return`The type of target roomId must match the current roomId. Current room is using '${s}', but received '${s==="strRoomId"?"roomId":"strRoomId"}'.`},INVALID_ROOM_ID_DUPLICATE({key:s}){return`the target '${s}' must not be the same as the current '${s}'.`},INVALID_STREAM_TYPE:({fnName:s})=>`'streamType' is required when 'userId' is not '*', calling ${s}()`,INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION({fnName:s}){return`the API '${s}' you called does not meet the requirements, please check the API documentation.`},INVALID_OPERATION_NOT_JOINED({fnName:s}){return`cannot ${s} because you are not enter room yet.`},INVALID_OPERATION_REMOTE_USER_NOT_EXIST({fnName:s,value:i}){return`cannot ${s} because remote user(userId: ${i.userId}) does not publishing stream.`},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST({fnName:s,value:i}){return`cannot ${s} because remote user(userId: ${i.userId}) does not publishing ${i.streamType} video.`},INVALID_OPERATION_REPEAT_CALL({fnName:s}){return`you are already ${s}(), cannot repeated call '${s}'.`},INVALID_OPERATION_NEED_VIDEO({fnName:s}){return`cannot call '${s}' because the camera is not turned on.`},INVALID_OPERATION_NEED_AUDIO({fnName:s}){return`cannot call '${s}' because the microphone or screen share is not turned on.`},INVALID_BUFFER_EMPTY:({key:s})=>`the buffer size of paramerter '${s}' cannot be empty`,INVALID_BUFFER_OVERSIZE:()=>"buffer size is over 1000 Bytes",INVALID_ROLE_AUDIENCE:()=>"role: 'audience' cannot call this api.",INVALID_NOT_ENABLE_SEI:()=>"you need to enable SEI in TRTC.create({ enableSEI: true })",INVALID_NEED_CALL_PUBLISHED:({fnName:s})=>`you need to call ${s}() after publish stream.`,ENV_NOT_SUPPORTED({fnName:s}){return`the current browser does not support the capability of the function '${s}' you are calling, please check the API documentation.`},NOT_SUPPORTED_WEBRTC:"the current browser does not support WebRTC capability, please check the SDK documentation.",NOT_SUPPORTED_H264_ENCODE:"this browser does not support H264 encode.",NOT_SUPPORTED_H264_DECODE:"this browser does not support H264 decode.",NOT_SUPPORTED_SCREEN_SHARE:"this browser does not support screen share, please check the browser version.",NOT_SUPPORTED_SMALL_VIDEO:"this browser does not support small video, please check the browser version.",NOT_SUPPORTED_SEI:"this browser does not support SEI, please check the browser version.",NOT_SUPPORTED_WEBGL:"this browser does not support WebGL, please check the browser version.",NOT_SUPPORTED_CHROME_VERSION({fnName:s}){return`cannot call ${s} because the browser version is too low, please upgrade to the latest version`},DEVICE_ERROR({fnName:s,error:i}){return`'${s}' got device exception${i?`, error: ${i.toString()}.`:"."}`},DEVICE_NOT_FOUND_ERROR({fnName:s,deviceType:i=Ns(s),error:e}){return`NotFoundError, no ${i} detected, please check your device and the configuration on '${s}'${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_ALLOWED_ERROR({fnName:s,deviceType:i=Ns(s),error:e}){return`NotAllowedError, you have disabled ${i} access, please allow the current application to use the ${i}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_READABLE_ERROR({fnName:s,deviceType:i=Ns(s),error:e}){return`NotReadableError, the ${i} maybe in use by another APP, please check if the device is pre-occupied by another APP.`},DEVICE_OVERCONSTRAINED_ERROR({fnName:s,deviceType:i=Ns(s),error:e}){return`OverconstrainedError, the device ID is incorrect, please check whether the device ID passed in is correct${e?`, error: ${e.toString()}.`:"."}`},DEVICE_INVALID_STATE_ERROR({fnName:s,deviceType:i=Ns(s),error:e}){return`InvalidStateError, after the user clicks and interacts with the page, turn on the ${i}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_SECURITY_ERROR({fnName:s,deviceType:i=Ns(s),error:e}){return`SecurityError, check whether the system security policy restricts the use of the ${i}, and it is recommended to turn on the ${i} after the user interacts with the page${e?`, error: ${e.toString()}.`:"."}`},DEVICE_ABORT_ERROR({fnName:s,deviceType:i=Ns(s),error:e}){return`AbortError, an unknown exception in the system makes the device unusable, recommended to change the device or browser and re-check whether the device is normal${e?` error: ${e.toString()}.`:"."}`},CAMERA_RECOVER_FAILED({error:s}){return`camera recover capture failed ${(s==null?void 0:s.name)||""}: ${(s==null?void 0:s.originMessage)||(s==null?void 0:s.message)}`},MICROPHONE_RECOVER_FAILED({error:s}){return`microphone recover capture failed ${(s==null?void 0:s.name)||""}: ${(s==null?void 0:s.originMessage)||(s==null?void 0:s.message)}`},OPERATION_FAILED({fnName:s,error:i}){return`'${s}' failed, reason: ${i==null?void 0:i.toString()}`},FIREWALL_RESTRICTION(){return"media connection failure due to firewall restrictions, please try to change your network."},EVENT_HANDLER_ERROR({eventName:s}){return`an error was caught on trtc.on('${s}', handler), please check your code on 'handler'.`},VIDEO_CONTEXT_ERROR({reason:s,error:i}){return`video context error ${s} ${(i==null?void 0:i.name)||""} ${(i==null?void 0:i.message)||""}`},SERVER_ERROR({fnName:s,error:i}){return`'${s}' got server error: ${i==null?void 0:i.toString()}, please check the SDK documentation.`},NEED_TO_BUY({value:s,url:i}){return`You need to buy packages for ${s}. Refer to: ${i}`},ACCOUNT_NO_MONEY:({fnParams:s})=>`your TRTC account run out of credit, please recharge.${s.sdkAppId?` SDKAppId: ${s.sdkAppId}`:""}`,OPERATION_ABORT({fnName:s}){return`'${s}' abort`},UNKNOWN_ERROR({fnName:s,error:i}){return`'${s}' throw unknown exception${i?`, error: ${i.toString()}.`:"."}`}});function Ns(s){if(!s)return"camera";let i=s.toLowerCase();return i.includes("screen")?"screen share":i.includes("audio")?"microphone":"camera"}var Jh=class s extends Error{constructor({code:e,extraCode:t,message:r="",messageParams:o,fnName:n="",originError:a,data:c}){var u;let l;r?l=r:l=jf({code:e===U.SERVER_ERROR?e:t||e,params:M({fnName:n,error:a},o)});super(l);d(this,"name","RtcError");d(this,"code");d(this,"extraCode");d(this,"functionName");d(this,"message");d(this,"data");d(this,"handler");d(this,"originError");this.name=Ut[e],this.code=e,this.extraCode=t,this.functionName=n,this.originError=a,this.message=l,this.data=c,this.extraCode===5302&&((u=this.originError)!=null&&u.message.includes("system"))&&(this.handler=()=>{let m={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},p={startLocalVideo:"webcam",startLocalAudio:"microphone"},h=document.createElement("a");ss?h.href=`ms-settings:privacy-${p[this.functionName]}`:ui&&(h.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${m[this.functionName]}`),h.href.length>0&&h.click()})}static convertFrom(e,t,r){let o=e;if(e instanceof N){let{stack:n}=e,a={code:U.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case I.INVALID_PARAMETER:a.code=U.INVALID_PARAMETER,a.message=e.message;break;case I.INVALID_OPERATION:a.code=U.INVALID_OPERATION;break;case I.NOT_SUPPORTED:case I.NOT_SUPPORTED_H264:a.code=U.ENV_NOT_SUPPORTED,e.getCode()===I.NOT_SUPPORTED_H264&&(a.extraCode=e.message.includes(Xe.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case I.JOIN_ROOM_FAILED:a.messageParams={fnParams:r};case I.SERVER_TIMEOUT:case I.SWITCH_ROLE_FAILED:case I.SWITCH_ROOM_FAILED:a.code=U.SERVER_ERROR,a.extraCode=e.getExtraCode();break;case I.API_CALL_ABORTED:a.code=U.OPERATION_ABORT;break;case I.DEVICE_NOT_FOUND:case I.DEVICE_AUTO_RECOVER_FAILED:case I.INITIALIZE_FAILED:a.code=5300,e.name&&(a.extraCode=ZS(e.name));break;case I.VIDEO_ENCODE_FAILED:a.extraCode=5505;case I.AUDIO_ENCODE_FAILED:a.extraCode=5506,a.code=U.OPERATION_FAILED;break;case I.UNKNOWN:break;default:a.code=U.OPERATION_FAILED}o=new s(a),n&&(o.stack+=n.substr(n.indexOf(`
|
|
54
54
|
`)))}else{if(e instanceof s)return e;o=new s({code:U.UNKNOWN_ERROR,fnName:t,originError:e})}return o}};function ZS(s){let i;switch(s){case"NotFoundError":i=5301;break;case"NotAllowedError":i=5302;break;case"NotReadableError":i=5303;break;case"OverconstrainedError":i=5304;break;case"InvalidStateError":i=5305;break;case"SecurityError":i=5306;break;case"AbortError":i=5307;break;default:i=5300}return i}var B=Jh;function bt(s){return s==="sub"?"auxiliary":s==="auxiliary"?"sub":"main"}function na(s){return s===vs.QOS_PREFERENCE_CLEAR?"detail":s===vs.QOS_PREFERENCE_SMOOTH?"motion":""}function wo(s,i){let e=i?fl:Er;return $l(s)?M(M({},e),s):ti[s]?ti[s]:e}var qf={type:"object",properties:{cameraId:{type:"string"},useFrontCamera:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:["string","boolean"],values:[!0,!1,"view","publish","both"]},small:{type:["string","object","boolean"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack}}},Xf={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}}},xo={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(s,i,e){if(ne(s)&&!document.getElementById(s))throw new B({code:U.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:i}})}},zf={name:"userId",required:!0,type:"string"},Qf={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{type:["string","object"],properties:{bitrate:{type:"number"},channelCount:{type:"number"}}},echoCancellation:{values:[!0,!1,"remote-only","all"]},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function Uo(s,i){if(!s)throw new B({code:U.INVALID_OPERATION,extraCode:5101,fnName:i})}function Yf(s,i,e){if(!s)throw new B({code:U.INVALID_OPERATION,extraCode:5102,fnName:i,messageParams:{value:e}})}function Zf(s,i,e){if(!(/^[1-9]\d*$/.test(String(s))&&s<4294967295))throw new B({code:U.INVALID_PARAMETER,extraCode:5013,fnName:i,messageParams:{key:e}})}function Kf(s,i,e){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(s))throw new B({code:U.INVALID_PARAMETER,extraCode:5012,fnName:i,messageParams:{key:e}})}var Aw={type:"number",notLessThanZero:!0},KS=(s,i)=>s.width*s.height>=i.width*i.height&&s.frameRate>=i.frameRate&&s.bitrate>=i.bitrate;function e_(s){var t;if(!((t=s==null?void 0:s.option)!=null&&t.small))return;if(!Uc()){C.warn("small stream is not supported"),delete s.option.small;return}let i=wo(s.option.profile),e=wo(s.option.small,!0);if(!KS(i,e)){C.warn(`small stream profile must be less than big stream profile. Big: ${JSON.stringify(i)}, Small: ${JSON.stringify(e)}`),delete s.option.small;return}}var eI={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(s,i,e){if(this._room.isJoined)throw new B({code:U.INVALID_OPERATION,extraCode:5104,fnName:e});if(s.roomId){if(ne(s.roomId))throw new B({code:U.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:i}});Zf(s.roomId,e,i)}else if(s.strRoomId)Kf(s.strRoomId,e,i);else throw new B({code:U.INVALID_PARAMETER,extraCode:5015,fnName:e})},properties:{sdkAppId:{required:!0,type:"number",allowEmpty:!1},userId:{required:!0,type:"string",allowEmpty:!1},userSig:{required:!0,type:"string",allowEmpty:!1},scene:{type:"string",values:["live","rtc"]},role:{type:"string",values:["audience","anchor"]},roomId:{type:["string","number"]},strRoomId:{type:"string"},proxy:{type:["object","string"],properties:{websocketProxy:{type:"string"},turnServer:{type:["object","array"],properties:{url:{required:!0,type:"string"},username:{type:"string"},credential:{type:"string"},credentialType:{type:"string",values:["password"]}}},loggerProxy:{type:"string"},webtransportProxy:{type:"string"}}},enableAutoPlayDialog:{type:"boolean"},userDefineRecordId:{type:"string"},latencyLevel:{type:"number"},playoutDelay:{type:"object",properties:{min:{type:"number",min:0,max:1e3},max:{type:"number",min:0,max:1e4}}}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:xo,mute:{type:["boolean","string"]},publish:{type:"boolean"},capture:{required:!1,type:"boolean"},option:qf},validate(s){var i,e;if(!((i=s==null?void 0:s.option)!=null&&i.videoTrack)&&tr())throw new B({code:U.ENV_NOT_SUPPORTED,extraCode:5201});(e=s==null?void 0:s.option)!=null&&e.small&&e_(s)}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:L(M({},xo),{required:!1}),publish:{type:"boolean"},capture:{required:!1,type:"boolean"},mute:{type:["boolean","string"]},option:qf},validate(s){var i;(i=s==null?void 0:s.option)!=null&&i.small&&e_(s)}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},mute:{type:["boolean","string"],values:[!0,!1,"microphone"]},muteKeepVolumeDetection:{type:"boolean"},option:Qf},validate(s){var i;if(!((i=s==null?void 0:s.option)!=null&&i.audioTrack)&&tr())throw new B({code:U.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:["boolean","string"],values:[!0,!1,"microphone"]},muteKeepVolumeDetection:{type:"boolean"},option:Qf}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:xo,publish:{type:"boolean"},option:Xf},validate(s,i,e,t,r){var o;if(!((o=s==null?void 0:s.option)!=null&&o.videoTrack)){if(tr())throw new B({code:U.ENV_NOT_SUPPORTED,extraCode:5201});if(!Pn())throw new B({code:U.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:xo,publish:{type:"boolean"},option:Xf}},muteRemoteAudio:[zf,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[zf,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:xo,userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(s,i,e){Uo(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(s.userId);if(Yf(!!t,e,s),t&&(s.streamType==="main"&&!t.muteState.videoAvailable||s.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new B({code:U.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:s}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:L(M({},xo),{required:!1}),userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(s,i,e){Uo(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(s.userId);if(Yf(!!t,e,s),t){if(s.streamType==="main"&&!t.muteState.videoAvailable||s.streamType==="sub"&&!t.muteState.hasAuxiliary)throw new B({code:U.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:s}});if(s.option){let r=s.streamType==="main"?t.remoteVideoTrack:t.remoteAuxiliaryTrack;if((s.option.pictureInPicture||s.option.fullScreen||s.option.fullScreen)&&(!r.isSubscribed||!r.player.isPlaying))throw new B({code:U.INVALID_OPERATION,message:"cannot set pictureInPicture or fullScreen when remote video is not playing"})}}}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(s,i,e){if(s.userId!=="*"&&E(s.streamType))throw new B({code:U.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(s,i,e){Uo(this._room.isJoining||this._room.isJoined,e)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(s,i,e,t){if(!wn)throw new B({code:U.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new B({code:U.INVALID_OPERATION,fnName:e,extraCode:5108});if(s.byteLength>1e3)throw new B({code:U.INVALID_PARAMETER,extraCode:5018,fnName:e});if(s.byteLength===0)throw new B({code:U.INVALID_PARAMETER,extraCode:5017,messageParams:{key:i},fnName:e});Uo(this._room.isJoined,e)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(s,i,e){if(!s&&!this._room.isMainStreamPublished||s&&!this._room.isAuxStreamPublished)throw new B({code:U.INVALID_OPERATION,extraCode:5109,messageParams:{key:i},fnName:e})}}}}],sendCustomMessage:{name:"message",required:!0,type:"object",properties:{cmdId:{type:"number",required:!0,min:1,max:10},data:{instanceOf:ArrayBuffer,required:!0,validate(s,i,e,t){if(s.byteLength>1e3)throw new B({code:U.INVALID_PARAMETER,extraCode:5018,fnName:e});if(s.byteLength===0)throw new B({code:U.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:i}})}}},validate(s,i,e){if(Uo(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new B({code:U.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:i}})}},switchRoom:{name:"switchRoomConfig",type:"object",required:!0,validate(s,i,e){if(Uo(this._room.isJoined,e),this._room.useStringRoomId&&s.strRoomId===this._room.roomId||!this._room.useStringRoomId&&s.roomId===Number(this._room.roomId))throw new B({code:U.INVALID_PARAMETER,extraCode:5020,fnName:e,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(s.roomId&&this._room.useStringRoomId||!s.roomId&&s.strRoomId&&!this._room.useStringRoomId)throw new B({code:U.INVALID_PARAMETER,extraCode:5019,fnName:e,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(s.roomId)Zf(s.roomId,e,i);else if(s.strRoomId)Kf(s.strRoomId,e,i);else throw new B({code:U.INVALID_PARAMETER,extraCode:5015,fnName:e})},properties:{roomId:{type:"number"},strRoomId:{type:"string"},privateMapKey:{type:"string"},userSig:{type:"string",required:!0},autoSubscribeCount:{type:"number",min:0,max:50}}},_switchPlaybackQuality:{name:"SwitchToQualityOptions",required:!0,type:["string","object"],properties:{quality:{type:"string"},streamList:{type:"array",arrayItem:{type:"object",properties:{name:{type:"string",required:!0},userId:{type:"string",required:!0},streamType:{type:"string",values:["main","sub"]}}}}}}},je={TRTC:eI};var ht=class extends Error{};function tI(s,i){let e=Yr(s);for(let t=0;t<i.length;t++)ni(e[t],i[t]);return e}function iI(s){this._resolve=Promise.resolve(s)}function rI(s){this._reject=Promise.reject(s)}var Hr=class Hr{constructor(i,e){this.instance=i;this.group=e;d(this,"started",!1);d(this,"ops",[]);d(this,"startSame",()=>!0);d(this,"mergeUpdate",tI);let t=Hr.instances.get(i);t?t.set(e,this):Hr.instances.set(i,new Map([[e,this]]))}static get(i,e){if(!e)return;let t=Hr.instances.get(i);return t&&t.get(e)||new Hr(i,e)}static gets(i,e){let t=Hr.instances.get(i),r=[];return t&&t.forEach((o,n)=>{e.test(n)&&r.push(o)}),r}action(i,e,t){let r=a=>{var c;return i===0?this.started=!0:i===3&&(this.started=!1),this.ops.shift(),(c=this.currentOp)==null||c.action(),a},o=a=>{var c,l;throw this.ops.shift(),i===0&&((c=this.currentOp)==null?void 0:c.type)===2&&this.ops.shift().reject(new ht("start failed")),(l=this.currentOp)==null||l.action(),a},n={type:i,action:()=>e(...n.args).then(r,o),args:t,resolve:iI,reject:rI};try{switch(this.state){case 1:if(i===0)throw new ht("already started");break;case 4:if(i===2)throw new ht("not started");break;default:return this.cacheOp(n)}}catch(a){return Promise.reject(a)}return this.ops.push(n),n.promise=e(...n.args).then(r,o)}cacheOp(i){if(this.ops.length===1)switch(this.state){case 0:case 2:if(i.type===0)throw new ht("already start");break;case 3:switch(i.type){case 2:throw new ht("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new ht("unknown state")}else switch(i.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let t=new ht("keep stop");if(this.ops.slice(1).forEach(r=>r.reject(t)),this.ops=this.ops.slice(0,1),this.state===3)return this.currentOp.promise}break;case 2:switch(this.lastOpType){case 2:return this.lastOp.args=this.mergeUpdate(this.lastOp.args,i.args),this.lastOp.promise;case 3:throw new ht("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new ht("start not allowed after update");case 0:throw new ht("duplicate start");case 3:if(this.startSame(this.currentOp.args,i.args))throw this.ops.pop().reject(new ht("keep start")),new ht("already start")}}i.promise=new Promise((t,r)=>{i._resolve?i._resolve.then(t):i.resolve=t,i._reject?i._reject.catch(r):i.reject=r});let{action:e}=i;return i.action=()=>e().then(i.resolve,i.reject),this.ops.push(i),i.promise}get lastOp(){return this.ops[this.ops.length-1]}get lastOpType(){return this.lastOp.type}get currentOp(){return this.ops[0]}get state(){return this.currentOp?this.currentOp.type:this.started?1:4}};d(Hr,"instances",new WeakMap);var dr=Hr;var Cd=new WeakMap,yd=(s,i)=>{if(i instanceof ht){let{stack:e}=i;i=new B({code:U.OPERATION_ABORT,message:`${s} abort: ${i.message}`,fnName:s}),e&&(i.stack+=e.substr(e.indexOf(`
|
|
55
55
|
`)))}throw i};function $r(s,i){return K((e,t)=>function(...r){let o=dr.get(this,typeof s=="string"?s:s.call(this,...r));return o?(i&&(o.startSame=i.bind(this)),o.action(0,e.bind(this),r).catch(yd.bind(null,t))):e.apply(this,r)})}function Ds(s,i){let{merge:e,debounce:t}=i||{};return K((r,o)=>function(...n){let a=dr.get(this,typeof s=="string"?s:s.call(this,...n));if(!a)return r.apply(this,n);if(e&&(a.mergeUpdate=e.bind(this)),t&&t.isNeedToDebounce.apply(this,n)){let{delay:c,getKey:l}=t;return new Promise((u,m)=>{var T,g;let p=(T=Cd.get(this))==null?void 0:T.get(l(...n));if(p){let{timeoutId:R,resolve:D}=p;clearTimeout(R),D()}let h=setTimeout(()=>{if(a.state===3||a.state===4)return u();a.action(2,r.bind(this),n).catch(yd.bind(null,o)).then(u,m)},c);Cd.has(this)?(g=Cd.get(this))==null||g.set(l(...n),{timeoutId:h,resolve:u}):Cd.set(this,new Map([[l(...n),{timeoutId:h,resolve:u}]]))})}return a.action(2,r.bind(this),n).catch(yd.bind(null,o))})}function Wr(s){return K((i,e)=>function(...t){let r=typeof s=="function"?s.call(this,...t):s;if(r instanceof RegExp)return Promise.all(dr.gets(this,r).map(n=>n.action(3,()=>Promise.resolve(),t))).then(()=>i.call(this,...t));let o=dr.get(this,r);return o?o.action(3,i.bind(this),t).catch(yd.bind(null,e)):i.apply(this,t)})}function Gr(){return function(s,i,e){return s.prototype[i]=function(){let t=this._log||console,r=`"${i}" is a static method. Use TRTC.${i}() instead. See: ${gt}/en/TRTC.html#.${i}`;t.warn(r)},e}}var w={ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",KICKED_OUT:"kicked-out",REMOTE_USER_ENTER:"remote-user-enter",REMOTE_USER_EXIT:"remote-user-exit",REMOTE_AUDIO_AVAILABLE:"remote-audio-available",REMOTE_AUDIO_UNAVAILABLE:"remote-audio-unavailable",REMOTE_VIDEO_AVAILABLE:"remote-video-available",REMOTE_VIDEO_UNAVAILABLE:"remote-video-unavailable",AUDIO_VOLUME:"audio-volume",AUDIO_FRAME:"audio-frame",NETWORK_QUALITY:"network-quality",CONNECTION_STATE_CHANGED:"connection-state-changed",AUDIO_PLAY_STATE_CHANGED:"audio-play-state-changed",VIDEO_PLAY_STATE_CHANGED:"video-play-state-changed",SCREEN_SHARE_STOPPED:"screen-share-stopped",DEVICE_CHANGED:"device-changed",PUBLISH_STATE_CHANGED:"publish-state-changed",TRACK:"track",STATISTICS:"statistics",SEI_MESSAGE:"sei-message",CUSTOM_MESSAGE:"custom-message",VIDEO_DECODE_DOWNGRADE_STATE_CHANGED:"video-decode-downgrade-state-changed",LAYER_DATA:"layerData",FIRST_VIDEO_FRAME:"first-video-frame",PERMISSION_STATE_CHANGE:"permission-state-change",VIDEO_SIZE_CHANGED:"video-size-changed",REALTIME_TRANSCRIBER_MESSAGE:"realtime-transcriber-message",REALTIME_TRANSCRIBER_STATE_CHANGED:"realtime-transcriber-state-changed",PICTURE_IN_PICTURE_STATE_CHANGED:"picture-in-picture-state-changed",FULL_SCREEN_STATE_CHANGED:"full-screen-state-changed"},t_=new Set([w.AUDIO_VOLUME,w.AUDIO_FRAME,w.NETWORK_QUALITY,w.STATISTICS,w.SEI_MESSAGE,w.CUSTOM_MESSAGE,w.LAYER_DATA]);var qh={};$i(qh,{ScheduleRequestType:()=>s_,getAbilityConfig:()=>cI,getScheduleDomain:()=>Md,isNeedToSchedule:()=>aa,scheduleProxy:()=>Ri,sendScheduleRequest:()=>jh,setIsNeedToSchedule:()=>Vt,setScheduleProxy:()=>Dd});var bd=null,Nd=0,r_=2*3600*1e3,vd="trtc_schedule_cache",aa=!0;typeof document!="undefined"&&document.head.insertAdjacentHTML("beforeend",Object.values(ji).map(s=>`<link rel="dns-prefetch" href="https://${s}">`).join(`\r
|
|
@@ -61,7 +61,7 @@ CPU core: ${navigator.hardwareConcurrency}, GPU: ${vr()}`;if(Te&&window.screen&&
|
|
|
61
61
|
${e.map(l=>l.toString()).join(`
|
|
62
62
|
`)};(${t})();${r}})()`,n=new Blob([o],{type:"text/javascript"}),a=URL.createObjectURL(n),c=new Worker(a);return URL.revokeObjectURL(a),c}var lr=class{constructor(i){d(this,"audioPlayer");d(this,"videoPlayer");d(this,"log");this.audioPlayer=i.audioPlayer,this.videoPlayer=i.videoPlayer,this.log=i.log.createChild({id:"pip"}),this.videoPlayer.on(G.USER_RESUME_IN_PIP_OR_FULL_SCREEN,this.handleUserResumeInPIPOrFullScreen,this),this.videoPlayer.on(G.USER_PAUSE_IN_PIP_OR_FULL_SCREEN,this.handleUserPauseInPIPOrFullScreen,this),this.videoPlayer.on(G.ENTER_PICTURE_IN_PICTURE,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.on(G.ENTER_FULL_SCREEN,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.on(G.LEAVE_PICTURE_IN_PICTURE,this.handleLeavePIP,this),this.videoPlayer.on(G.LEAVE_FULL_SCREEN,this.handleLeaveFullScreen,this),this.videoPlayer.on(G.VOLUME_CHANGE,this.handleVolumeChange,this)}handleUserResumeInPIPOrFullScreen(){this.audioPlayer.isPaused&&(this.log.warn(`resume audio in ${this.videoPlayer.isPictureInPicture()?"pip":"fullscreen"}`),this.audioPlayer.doResume()),fe&&br&&this.videoPlayer.resetSrcObjectToReplay()}handleUserPauseInPIPOrFullScreen(){this.audioPlayer.isPaused||(this.log.warn(`pause audio in ${this.videoPlayer.isPictureInPicture()?"pip":"fullscreen"}`),this.audioPlayer.doPause())}handleEnterPIPOrFullScreen(){this.videoPlayer.element&&this.audioPlayer.muted!==this.videoPlayer.element.muted&&(this.log.warn(`sync video muted to ${this.audioPlayer.muted} when enter ${this.videoPlayer.isPictureInPicture()?"pip":"fullscreen"}`),this.videoPlayer.element.muted=this.audioPlayer.muted)}handleLeavePIP(){this.audioPlayer.isPaused&&!this.audioPlayer.isPausedByUserCall&&(this.log.warn("resume after leave pip"),this.audioPlayer.doResume()),this.videoPlayer.isPaused&&!this.videoPlayer.isPausedByUserCall&&(this.log.warn("resume video after leave pip"),this.videoPlayer.doResume())}handleLeaveFullScreen(){this.audioPlayer.isPaused&&!this.audioPlayer.isPausedByUserCall&&(this.log.warn("resume audio after leave fullscreen"),this.audioPlayer.doResume()),this.videoPlayer.isPaused&&!this.videoPlayer.isPausedByUserCall&&(this.log.warn("resume video after leave fullscreen"),fe&&br?this.videoPlayer.resetSrcObjectToReplay():this.videoPlayer.doResume())}handleVolumeChange(i){i.muted!==void 0&&this.audioPlayer.muted!==i.muted&&(this.log.warn(`sync audio muted to ${i.muted} in ${this.videoPlayer.isPictureInPicture()?"pip":"fullscreen"}`),this.audioPlayer.setMuted(i.muted))}destroy(){this.videoPlayer.off(G.USER_RESUME_IN_PIP_OR_FULL_SCREEN,this.handleUserResumeInPIPOrFullScreen,this),this.videoPlayer.off(G.USER_PAUSE_IN_PIP_OR_FULL_SCREEN,this.handleUserPauseInPIPOrFullScreen,this),this.videoPlayer.off(G.ENTER_PICTURE_IN_PICTURE,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.off(G.ENTER_FULL_SCREEN,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.off(G.LEAVE_PICTURE_IN_PICTURE,this.handleLeavePIP,this),this.videoPlayer.off(G.LEAVE_FULL_SCREEN,this.handleLeaveFullScreen,this),this.videoPlayer.off(G.VOLUME_CHANGE,this.handleVolumeChange,this)}};var a_=!1,c_;function d_({TRTC:s,room:i,errorModule:e,assetsPath:t}){return{TRTC:s,LocalMixVideoTrack:Cs,LocalVideoTrack:ze,LocalScreenTrack:xt,room:i,assetsPath:t,fileDownloader:da,innerEmitter:S,INNER_EVENT:A,constants:bl,environment:co,utils:Bh,eventLogger:se,log:this.room.getLogger(),loggerManager:C,errorModule:e,kvStatManager:y,rtcDectection:Pi,trtc:this,rx:Vh,enums:Tu,schedule:qh,getDevices:Io,initVisionTaskRegistry:(r,o,n="/mediapipe/vision.js")=>f(this,null,function*(){!window.VisionTaskRegistry&&!a_&&(a_=!0,c_=da.loadScript(`${r}/${n}`.replace(/([^:]\/)\/+/g,"$1"))),yield c_,yield(yield window.VisionTaskRegistry.getInstance(r)).preloadModels(o)}),audioContext:Ae(),deviceDetector:Ne,AudioPlayer:Ro,RemoteAudioPlayer:Co,VideoPlayer:rt,showAutoPlayDialog:go,Timer:ce,clearStarted:(r,o)=>{let n=r.getAlias(),a=dr.instances.get(this);if(a)if(o){let c=a.get(n+o);if(!c)return;c.started=!1}else a.forEach((c,l)=>{l.startsWith(n)&&(c.started=!1)})},startGetPCM:oa,createAudioNode:So,getNetworkTimeOffset:Vm,validateSourceNode:()=>{var r;if(re&&!((r=this.room.audioManager._localAudioPipline)!=null&&r.source.node))throw new B({code:U.DEVICE_ERROR,extraCode:5310,message:"The audio processing plugin cannot be used due to the microphone's sampling rate is not 48KHz in Firefox. Please switch to another browser such as Chrome."})},createScriptTransformWorker:Od,AVPlayerStateSyncManager:lr,PlayerEvent:G}}var l_=(s,i)=>{let{emit:e}=s;return s.emit=(...t)=>{try{return e.apply(s,t)}catch(r){let o=W({key:H.CATCH_HANDLER_ERROR,data:{name:i,event:t[0]},addDocLink:!1});return C.warn(`${o}
|
|
63
63
|
|
|
64
|
-
${r.stack}`),!1}},s};var Vo=new WeakMap;function u_(s){let i=Vo.get(s);i&&(i.forEach(e=>clearTimeout(e)),Vo.delete(s))}function h_(s,i){return K((e,t)=>function(...r){let o=Vo.get(this);o||(o=new Map,Vo.set(this,o));let n=i(...r),a=o.get(n);if(!a||a<=0){e.apply(this,r);let c=setTimeout(()=>{var l;(l=Vo.get(this))==null||l.delete(n)},s);o.set(n,c)}else{clearTimeout(a);let c=window.setTimeout(()=>{var l;e.apply(this,r),(l=Vo.get(this))==null||l.delete(n)},s);o.set(n,c)}})}var p_="trtc-sdk-v5",em="5.15.1-beta.6";function nt(...s){return K((i,e)=>function(...t){try{kd.call(this,s,t,e,this._name)}catch(r){return Promise.reject(r)}return i.apply(this,t)})}function tm(...s){return K((i,e)=>function(...t){try{kd.call(this,s,t,e,this._name)}catch(r){throw r}return i.apply(this,t)})}function kd(s,i,e,t){if(Ie(s))for(let r=0;r<s.length;r++)Pd.call(this,{rule:s[r],value:i[r],key:s[r].name,fnName:e,className:t});else Pd.call(this,{rule:s,value:i[0],key:s.name,fnName:e,className:t})}function Pd({rule:s,value:i,key:e,fnName:t,className:r}){function o(c){return{code:U.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:s,value:i}}}if(E(i)){if(s.required)throw new B(o(5001));if(E(s.defaultValue)){me(s.validate)&&s.validate.call(this,i,e,t,r,this);return}i=s.defaultValue}if(Array.isArray(s.type)){let c=!1;for(let l=0;l<s.type.length;l++)s.type[l]===null&&i===null&&(c=!0),me(s.type[l])&&i instanceof s.type[l]&&(c=!0),ne(s.type[l])&&Pe(i)===s.type[l].toLowerCase()&&(c=!0);if(!c)throw new B({code:U.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:s.type.map(l=>es(l)?Js(l):ne(l)?l:Pe(l))},value:i}})}else if(!E(s.type)&&Pe(i)!==s.type)throw new B(o(5002));if(s.allowEmpty===!1){let c=te(i)&&(i===0||Number.isNaN(i)),l=ne(i)&&i.trim()==="";if(c||l)throw new B(o(5003))}if(s.notLessThanZero&&te(i)&&i<0)throw new B(o(5006));if(!E(s.min)&&te(i)&&i<s.min)throw new B(o(5007));if(!E(s.max)&&te(i)&&i>s.max)throw new B(o(5008));if(ne(s.instanceOf)){if(!i||i._name!==s.instanceOf)throw new B(o(5004))}else if(me(s.instanceOf)&&!(i instanceof s.instanceOf))throw new B(o(5004));if(Array.isArray(s.values)&&!s.values.includes(i))throw new B(o(5005));let{properties:n}=s;dt(n)&&vt(i)&&Object.keys(n).forEach(c=>{Pd.call(this,{rule:n[c],value:i&&i[c],key:`${c}`,fnName:t,className:r})});let{arrayItem:a}=s;dt(a)&&Ie(i)&&i.forEach((c,l)=>{Pd.call(this,{rule:a,value:c,key:`${e}[${l}]`,fnName:t,className:r})}),me(s.validate)&&s.validate.call(this,i,e,t,r,this)}var mI=0;function Re(s={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t,ignoreLog:r,ignoreErrorLog:o}=s;return K((n,a)=>function(...c){var T,g,R;function l(D,j,V){if(V&&V.includes(D))return"hided";if(e){let ae=e(...c);if(c[ae.argIndex]===j)return ae.value}if(j===c||D in c)return j;try{return j instanceof HTMLElement?`id: ${j.id} type:${Pe(j)}`:j instanceof MediaStreamTrack?Xa(j):(JSON.stringify(j),j)}catch(ae){return`type:${Pe(j)}`}}let u=(this==null?void 0:this._log)||C,m=++mI;if(r!=null&&r(...c))return n.apply(this,c);c.length>0?u.info(`${a}() ${m} ${JSON.stringify(c,(D,j)=>l(D,j,["userSig","privateMapKey"]))}`):u.info(`${a}() ${m}`);let p=t?t(...c):Mc[a],h=(o==null?void 0:o(...c))||!1;try{let D=n.apply(this,c),j=x();if(Rr(D)){let V=`${a.includes("Plugin")?`${((g=(T=c[0]).getName)==null?void 0:g.call(T))||""} `:" "}`;return D.then(ae=>(u.info(`${a}() success ${m} ${V}${i.call(this,...c)}`),y.addSuccessEvent({key:p,cost:x()-j}),ae)).catch(ae=>{var ge;ae=B.convertFrom.call(this,ae,a,c.length===1?c[0]:c);let b=ae.extraCode||ae.code,$=(ge=ae.message)!=null&&ge.includes(b)?"":` code:${b}`,P=(ae==null?void 0:ae.code)===U.OPERATION_ABORT;throw h||u[P?"warn":"error"](`${a}() failed ${m} ${V}${i.call(this,...c)} ${ae}${$} params: ${JSON.stringify(c,l)}`),y.addFailedEvent({key:p,error:ae}),ae})}return y.addSuccessEvent({key:p}),D}catch(D){D=B.convertFrom.call(this,D,a);let j=D.extraCode||D.code,V=(R=D.message)!=null&&R.includes(j)?"":` code:${j}`,ae=(D==null?void 0:D.code)===U.OPERATION_ABORT;throw h||u[ae?"warn":"error"](`${a}() failed ${m} ${D}${V} params: ${JSON.stringify(c,l)}`),y.addFailedEvent({key:p,error:D}),D}})}var Ld=s=>K((i,e)=>function(t,r){return f(this,null,function*(){let o=this._plugins.get(t);if(!o)throw this._log.error(`plugin ${String(t)} is not found`),new B({code:U.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});if(me(o.constructor.isSupported)&&!o.constructor.isSupported())throw this._log.error(`plugin ${String(t)} is not supported`),new B({code:U.ENV_NOT_SUPPORTED,message:`plugin ${String(t)} is not supported`,extraCode:5210,fnName:e});return kd.call(this,o.getValidateRule(s),[r],e,"TRTC"),i.call(this,o,r)})});var wd=0,im,ur=class ur{constructor(i){this.core=i;d(this,"log");d(this,"customAudioReferenceMap",new Map);d(this,"audioRefId",0);d(this,"audioContext",Ae());d(this,"localAudioWorkletNode");d(this,"screenAudioWorkletNode");d(this,"mixNode");d(this,"silentNode");wd=wd+1,this.log=i.log.createChild({id:`${this.getAlias()}${wd}`}),this.log.info(`created id=${this.getAlias()}${wd}`),this.installEvent()}static getStartValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,t,r,o){if(!i.room.audioManager.hasAudioTrack&&!i.room.audioManager.hasScreenAudioTrack)throw new B({code:U.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return im||(im=this.doPreload(i)),im}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield sr(this.audioContext,t)}catch(r){this.log.error(`preload audioProcessor failed. ${r}`)}finally{URL.revokeObjectURL(t)}})}getName(){return ur.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(i){switch(i){case"start":return ur.getStartValidateRule(this.core);case"update":return ur.updateValidateRule;case"stop":return ur.stopValidateRule}}start(i){return f(this,null,function*(){var p,h,T,g;let{room:e}=this.core,{sdkAppId:t,userId:r,userSig:o,assetsPath:n=this.core.assetsPath,audioReference:a,processLevel:c,enableDump:l,isLocalAudioNeedAudioProcess:u=!0,isScreenAudioNeedAudioProcess:m=!1}=i;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=u,this.core.room.audioManager.isScreenAudioNeedAudioProcess=m,!n)throw new B({code:U.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload(`${n}/audioProcessor-wasm.js`),u&&!this.localAudioWorkletNode){let{sign:R,status:D,timestamp:j}=yield this.getAuthData(t,r,o);this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",t,r,j,R,D,e)}if(m&&!this.screenAudioWorkletNode){let{sign:R,status:D,timestamp:j}=yield this.getAuthData(t,r,o);this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",t,r,j,R,D,e)}this.mixNode||(this.mixNode=this.audioContext.createGain(),this.mixNode.gain.value=1),this.silentNode||(this.silentNode=this.audioContext.createConstantSource(),this.silentNode.offset.setValueAtTime(0,this.audioContext.currentTime),this.silentNode.start()),(p=this.localAudioWorkletNode)==null||p.port.postMessage({type:"enable"}),(h=this.screenAudioWorkletNode)==null||h.port.postMessage({type:"enable"}),e.audioManager.addAudioProcessor(this.mixNode,this.silentNode,this.localAudioWorkletNode,this.screenAudioWorkletNode),E(a)||a.forEach(R=>{this.customAudioReferenceMap.set(R,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:R,refId:`o-${this.audioRefId++}`})}),E(c)||(T=this.localAudioWorkletNode)==null||T.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:c}}),E(l)||(g=this.localAudioWorkletNode)==null||g.port.postMessage({type:"dump",data:{enable:l}})})}update(i){return f(this,null,function*(){var o,n,a;let{audioReference:e,enableDump:t,processLevel:r}=i;E(e)||(this.customAudioReferenceMap.forEach((c,l)=>{this.customAudioReferenceMap.delete(l),this.core.room.audioManager.updateAudioReference({type:"remove",refId:c})}),e.forEach(c=>{this.customAudioReferenceMap.set(c,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:c,refId:`o-${this.audioRefId++}`})})),E(r)||(o=this.localAudioWorkletNode)==null||o.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:r}}),E(t)||((n=this.localAudioWorkletNode)==null||n.port.postMessage({type:"dump",data:{enable:t}}),(a=this.screenAudioWorkletNode)==null||a.port.postMessage({type:"dump",data:{enable:t}}))})}stop(){return f(this,null,function*(){var e,t;let{room:i}=this.core;(e=this.localAudioWorkletNode)==null||e.port.postMessage({type:"disable"}),(t=this.screenAudioWorkletNode)==null||t.port.postMessage({type:"disable"}),yield i.audioManager.removeAudioProcessor(this.localAudioWorkletNode,this.screenAudioWorkletNode)})}destroy(){this.localAudioWorkletNode&&(this.localAudioWorkletNode.port.onmessage=null),this.screenAudioWorkletNode&&(this.screenAudioWorkletNode.port.onmessage=null),this.uninstallEvent()}getAuthData(i,e,t){return f(this,null,function*(){let r=String(Date.now()).slice(0,-3),{auth:o,sign:n,status:a,message:c}=yield fI({sdkAppId:i,userSig:t,userId:e,timestamp:r});if(!o)throw this.log.info(`audioProcessor: ${e} auth result: ${o}. Message: ${c}`),new B({code:U.INVALID_PARAMETER,message:c});return{sign:n,status:a,timestamp:r}})}initWorkletNode(i,e,t,r,o,n,a,c){i.port.postMessage({type:"init",data:{sdkAppId:String(t),userId:r,timestamp:o,sign:n,status:a}}),i.port.onmessage=l=>{var m;let{data:u}=l;switch(u.type){case"cost":let p=(u==null?void 0:u.value)>10?"info":"debug";this.log[p](`${e==="localAudio"?"":`[${e}] `}avg cost: ${u.value} max: ${u==null?void 0:u.max}(${xs(new Date(u==null?void 0:u.maxCostTimestamp))}) hist: ${(m=u==null?void 0:u.hist)==null?void 0:m.join(" ")}`);return;case"log":this.log[u.logLevel](`${e==="localAudio"?"":`[${e}] `}${u.value}`);return;case"dump":S.emit("265",{room:c,data:u.value,type:e==="localAudio"?"dump":"dump-screen-audio"});return;case"detectEcho":this.log.warn(`${e==="localAudio"?"":`[${e}] `}detect echo: ${os()?Dt():Mt()}`);return}}}handleLocalAudioStarted(i){return f(this,null,function*(){var e;if(!(!this.hitTest(i.room)||((e=this.core.room.scheduleResult.config)==null?void 0:e.audioProcessor)!==!0))try{yield this.core.trtc.startPlugin("AudioProcessor",{sdkAppId:this.core.room.sdkAppId,userId:this.core.room.userId,userSig:this.core.room.userSig}),this.log.warn("audio processor auto start success")}catch(t){this.log.warn(`audio processor auto start failed, error: ${t}`)}})}handleLocalAudioStopped(i){return f(this,null,function*(){var e;!this.hitTest(i.room)||((e=this.core.room.scheduleResult.config)==null?void 0:e.audioProcessor)!==!0||(yield this.core.trtc.stopPlugin("AudioProcessor"))})}installEvent(){this.core.innerEmitter.on("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.on("114",this.handleLocalAudioStopped,this)}uninstallEvent(){this.core.innerEmitter.off("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.off("114",this.handleLocalAudioStopped,this)}hitTest(i){return i===this.core.room}};d(ur,"updateValidateRule",{type:"object"}),d(ur,"stopValidateRule",{type:"object"}),d(ur,"Name","AudioProcessor");var xd=ur;function pI(s,i=_.MAIN){return`https://${Ri[i]||Md(s,i)}/api/v1/audioAiAuth`}function fI(r){return f(this,arguments,function*({sdkAppId:s,userId:i,userSig:e,timestamp:t}){let n=`${pI(s)}?sdkAppId=${s}&userId=${i}&userSig=${e}×tamp=${t}`,a=yield fetch(n),{data:{errCode:c,errMsg:l,sign:u,status:m}}=yield a.json();if(m==="1")return{auth:!0,sign:u,status:m,message:l};let p=$t(s)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",h="Init RTCAudioProcessor failed.",T="";switch(c){case 1:T="Please check your params.";break;case 2:T=`You need to buy packages. Refer to: ${p}`;break;case 3:T="Server is invalid. Please contact our engineer. ";break;case 4:T=`Your packages is not active. Refer to: ${p}`;break;case 5:T=`Your packages is expired. Refer to: ${p}`;break;case 6:T="Your version is not supported.";break}return{auth:!1,status:m,message:l?`${h} Reason: ${l}. ${T}`:`${h}, ${T}`}})}var Ud=0,rm=class{constructor(i,e){d(this,"audioObjectURL");d(this,"player");d(this,"publisher");d(this,"mixInput");this.mixInput=new Eo(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&&(E(i.volume)||(this.volume=i.volume),E(i.loop)||(this.loop=i.loop),E(i.playbackRate)||(this.playbackRate=i.playbackRate))}updateListener(i){if(this.player){if(i.onDurationChange){let{onDurationChange:e}=i;this.player.ondurationchange=t=>{e(t.target.duration)}}if(i.onTimeUpdate){let e=i.onTimeUpdate,{player:t}=this;t.ontimeupdate=()=>{e(t.currentTime,t.duration)}}i.onEnded&&(this.player.onended=i.onEnded)}}reload(i){return f(this,null,function*(){if(i.url){let e=yield da.download(i.url,{retries:3,type:"blob"});this.audioObjectURL&&URL.revokeObjectURL(this.audioObjectURL),this.audioObjectURL=URL.createObjectURL(e),this.player&&this.publisher?(this.player.src=this.audioObjectURL,this.publisher.src=this.audioObjectURL):(this.player=new Audio(this.audioObjectURL),this.player.crossOrigin="anonymous",this.publisher=new Audio(this.audioObjectURL),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher),this.updateListener(i),this.updateSettings(i))}else this.mixInput.replaceSource(i.track)})}reset(){this.seek(0),this.mixInput.connect()}seek(i){this.player&&(i<0&&i>this.player.duration||(this.player.currentTime=i,this.publisher.currentTime=i))}play(){var i,e;return Promise.all([(i=this.player)==null?void 0:i.play(),(e=this.publisher)==null?void 0:e.play()])}pause(){var i,e;(i=this.player)==null||i.pause(),(e=this.publisher)==null||e.pause()}stop(){var i;(i=this.player)==null||i.pause(),this.mixInput.disconnect()}setOperation(i){i==="pause"&&this.pause(),i==="resume"&&(this.pause(),this.play()),i==="stop"&&(this.pause(),this.seek(0))}set volume(i){!this.player||!this.publisher||(this.player.volume=i,this.publisher.volume=i)}set loop(i){!this.player||!this.publisher||(this.player.loop=i,this.publisher.loop=i)}set playbackRate(i){!this.player||!this.publisher||(this.player.playbackRate=i,this.publisher.playbackRate=i)}};function Fo(s,i){if(i&&typeof i!="function")throw new B({code:U.INVALID_PARAMETER,message:`start audioMixer plugin: param ${s} should be a function.`})}var Vi=class Vi{constructor(i){this.core=i;d(this,"log");d(this,"mixedMusicMap",new Map);d(this,"cacheMusicMap",new Map);Ud=Ud+1,this.log=i.log.createChild({id:`${this.getAlias()}${Ud}`}),this.log.info(`created id=${this.getAlias()}${Ud}`)}getName(){return Vi.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return Vi.startValidateRule;case"update":return Vi.updateValidateRule;case"stop":return Vi.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e}=this.core;this.core.validateSourceNode(),this.log.info(`add music source, id: ${i.id} url: ${i.url}, track: ${i.track}`);let{id:t,url:r}=i;if(this.mixedMusicMap.has(t))return;let o=this.cacheMusicMap.get(t);o?i.url?o.reset():(o.mixInput.replaceSource(i.track),o.mixInput.connect()):(o=new rm(i,e.audioManager),this.cacheMusicMap.set(t,o)),o.updateListener(i),o.updateSettings(i);try{yield o.play()}catch(n){yield this.handleAutoPlayFailed(o,i,n)}this.mixedMusicMap.set(t,o),o.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"add",audioReference:o.mixInput.source.node,refId:`ax-${t}`}),this.log.info(`start mix audio track ${t} success.`),y.addEnum({key:502700,value:3}),this.kvUpload(i)})}handleAutoPlayFailed(i,e,t){return f(this,null,function*(){if(t.name==="NotSupportedError")this.log.error(`play failed, try to reload source. error: ${t}`),yield i.reload(e),yield i.play();else if(t.name==="NotAllowedError")if(this.core.room.enableAutoPlayDialog){let r=()=>{var o;(o=i.play())==null||o.finally(()=>{S.off("154",r,this)})};S.on("154",r,this),go()}else this.core.trtc.emit(w.AUTOPLAY_FAILED,{userId:"",mediaType:"audio",resume:()=>f(this,null,function*(){return i.play()})});else throw t})}update(i){return f(this,null,function*(){let{id:e,operation:t,seekFrom:r,playbackRate: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),E(t)||n.setOperation(t),E(r)||n.seek(r),this.kvUpload(i)})}stop(e){return f(this,arguments,function*({id:i}){if(this.mixedMusicMap.has(i)){this.log.info(`remove music source, music id: ${i}`);let t=this.mixedMusicMap.get(i);t!=null&&t.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:t.mixInput.source.node,refId:`ax-${i}`}),t==null||t.stop(),this.mixedMusicMap.delete(i)}i==="*"&&this.destroyAllMusic()})}kvUpload(i){let{track:e,loop:t,volume:r,playbackRate:o,operation:n,seekFrom:a,onTimeUpdate:c,onDurationChange:l,onEnded:u}=i;e&&y.addCount({key:502009}),t&&y.addCount({key:502001}),r&&y.addCount({key:502002}),o&&y.addCount({key:502003}),n&&y.addCount({key:502004}),a&&y.addCount({key:502005}),typeof c!="function"&&y.addCount({key:502007}),typeof u!="function"&&y.addCount({key:502008}),typeof l!="function"&&y.addCount({key:502006})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((i,e)=>{i!=null&&i.mixInput.track&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:i.mixInput.track,refId:e}),this.stop({id:e})})}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}};d(Vi,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(i,e,t){if(i.url&&i.url!=="*"){let r=i.url.split("?")[0],o=["mp3","ogg","wav","flac"],n=r.split(".").pop(),a=o.indexOf(n)>=0,c=r.startsWith("blob"),l=r.startsWith("data");if(!(a||c||l))throw new B({code:U.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new B({code:U.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});Fo("onTimeUpdate",i.onTimeUpdate),Fo("onEnded",i.onEnded),Fo("onDurationChange",i.onDurationChange)}}),d(Vi,"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){Fo("onTimeUpdate",i.onTimeUpdate),Fo("onEnded",i.onEnded),Fo("onDurationChange",i.onDurationChange)}}),d(Vi,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),d(Vi,"Name","AudioMixer");var Vd=Vi;var Fd=0,sm,hr=class hr{constructor(i){this.core=i;d(this,"log");d(this,"audioContext",Ae("denoiser"));d(this,"workletNode");d(this,"config",{enableFarFieldReduce:!1,farFieldReduceThreshold:.5});Fd=Fd+1,this.log=i.log.createChild({id:`${this.getAlias()}${Fd}`}),this.log.info(`created id=${this.getAlias()}${Fd}`)}static startValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0},mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}},validate(e,t,r,o){if(!i.room.audioManager.hasAudioTrack)throw new B({code:U.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return sm||(sm=this.doPreload(i)),sm}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield sr(this.audioContext,t)}catch(r){throw this.log.error("load worklet failed",r),r}finally{URL.revokeObjectURL(t)}})}getName(){return hr.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser"}getValidateRule(i){switch(i){case"start":return hr.startValidateRule(this.core);case"update":return hr.updateValidateRule;case"stop":return hr.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e,schedule:t}=this.core,{assetsPath:r=this.core.assetsPath}=i;if(!r)throw new B({code:U.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload(`${r}/denoiser-wasm${Pu()?"":"-nosimd"}.js`),!this.workletNode){let o=String(Date.now()).slice(0,-3),{auth:n,sign:a,status:c,message:l}=yield gI(t,L(M({},i),{timestamp:o}));if(!n)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${n}. Message: ${l}`),new B({code:U.INVALID_PARAMETER,message:l});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(i.sdkAppId),userId:i.userId,timestamp:o,sign:a,status:c}}),this.workletNode.port.onmessage=u=>{var p;let{data:m}=u;if(m.type==="cost"){let h=(m==null?void 0:m.max)>20?"warn":(m==null?void 0:m.max)>10?"info":"debug";this.log[h](`avg cost: ${m.value} max: ${m==null?void 0:m.max}(${xs(new Date(m==null?void 0:m.maxCostTimestamp))}) hist: ${(p=m==null?void 0:m.hist)==null?void 0:p.join(" ")}`)}else m.type==="log"&&this.log[m.logLevel](`${m.value}`)}}this.updateConfig(i),this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(i){return f(this,null,function*(){this.updateConfig(i)})}stop(){return f(this,null,function*(){if(!this.workletNode)return;let{room:i}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield i.audioManager.removeDenoiser(this.workletNode)})}updateConfig(i){if(!this.workletNode)return;let e=!1;E(i.mode)||(i.mode===0?this.config.enableFarFieldReduce=!1:i.mode===1&&(this.config.enableFarFieldReduce=!0),e=!0),E(i.farFieldReduceThreshold)||(this.config.farFieldReduceThreshold=i.farFieldReduceThreshold,e=!0),e&&this.workletNode.port.postMessage({type:"setConfig",data:this.config})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};d(hr,"updateValidateRule",{type:"object",properties:{mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}}}),d(hr,"stopValidateRule",{type:"object"}),d(hr,"Name","AIDenoiser");var Bd=hr;function gI(o,n){return f(this,arguments,function*(s,{sdkAppId:i,userId:e,userSig:t,timestamp:r}){try{let{data:{errCode:a,errMsg:c,sign:l,status:u}}=yield s.getAbilityConfig(i,s.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:i,userId:e,userSig:t,timestamp:r});if(u==="1")return{auth:!0,sign:l,status:u,message:c};let m=$t(i)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",p="Init RTCAIDenoiser failed.",h="";switch(a){case 1:h="Please check your params.";break;case 2:h=`You need to buy packages. Refer to: ${m}`;break;case 3:h="Server is invalid. Please contact our engineer. ";break;case 4:h=`Your packages is not active. Refer to: ${m}`;break;case 5:h=`Your packages is expired. Refer to: ${m}`;break;case 6:h="Your version is not supported.";break}return{auth:!1,status:u,message:c?`${p} Reason: ${c}. ${h}`:`${p}, ${h}`}}catch(a){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${a}`}}})}var __=We(Ze(),1);var om=class extends __.EventEmitter{constructor(){super();d(this,"observer");d(this,"state","nominal");this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return f(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!fe&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){se.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let t=this.stateNum,r=e[e.length-1];this.state=r.state,(this.stateNum>3||t>3)&&C.info(`${r.source}: ${r.state}`),this.emit("state-changed",{type:r.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(t){se.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},TI=new om,nm=TI;var am=0,la=class la{constructor(i){this.core=i;d(this,"log");d(this,"_seiMessageList",[]);d(this,"_smallSeiMessageList",[]);d(this,"_subStreamSeiMessageList",[]);am++,this.log=i.log.createChild({id:`${this.getAlias()}${am}`}),this.log.info(`[sei] created id=${this.getAlias()}${am}`),this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode({frame:i,mediaType:e}){try{let t=e===8?this._smallSeiMessageList:e===2?this._subStreamSeiMessageList:this._seiMessageList;return Zh({frame:i,seiMessageList:t})}catch(t){this.log.warn(t)}return i}decode({frame:i,track:e}){return Kh({frame:i,onSEI:t=>{t.forEach(r=>{e!=null&&e.userId?this.core.trtc.emit(w.SEI_MESSAGE,{seiPayloadType:r.seiPayloadType,data:r.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"}):this.core.innerEmitter.emit(this.core.INNER_EVENT.SEI_MESSAGE,{room:this.core.room,nalu:r})})}})}destroy(){this.log.debug("destroy"),this.stop(),delete this.core}getValidateRule(i){switch(i){case"start":return{type:"object"};case"update":return{type:"object"};case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:gi?this.encode:Zh,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:gi?this.decode:Kh,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update({buffer:i,options:e}){var o;let t=[e.seiPayloadType,i],r=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(t):(this._seiMessageList.push(t),r&&this._smallSeiMessageList.push(t)),(o=this.core.room.scriptTransformWorker)==null||o.postMessage({type:"sei",data:t,isMain:!e.toSubStream,small:r})}getName(){return la.Name}getAlias(){return"sei"}getGroup(){return"sei"}};d(la,"autoStart",!0),d(la,"Name","SEI");var Hd=la;var EI=0,$d,ua=class ua{constructor(i){this.core=i;d(this,"_core");d(this,"log");d(this,"dialog");this._core=i,this.log=i.log.createChild({id:`${this.getAlias()}${++EI}`}),this.log.info("created")}getName(){return ua.Name}getAlias(){return"dm"}getGroup(){return"dm"}getValidateRule(i){switch(i){case"start":return{name:"StartDebugOptions",required:!1};case"update":return{name:"UpdateDebugOptions",required:!1};case"stop":return{name:"StopDebugOptions",required:!1}}}start(){return f(this,null,function*(){var e;!new URLSearchParams(location.search).has("trtcDebug")&&((e=window.sessionStorage)==null?void 0:e.getItem("TRTC_ENABLE_DEBUG_PLUGIN"))!=="true"||(yield this.openDebugDiaLog())})}update(e){return f(this,arguments,function*({visible:i}){i?yield this.openDebugDiaLog():this.closeDebugDiaLog()})}stop(){this.closeDebugDiaLog()}destroy(){this.stop()}openDebugDiaLog(){return f(this,null,function*(){var i;if(!this.dialog)try{if($d)yield $d;else{let e=new URLSearchParams(location.search).get("trtcDebugDialogPath")||((i=window.sessionStorage)==null?void 0:i.getItem("TRTC_DEBUG_DIALOG_PATH"))||`https://unpkg.com/${p_}@${Ge}/assets/debug-dialog.js`;$d=this._core.fileDownloader.loadScript(e),yield $d}this.dialog=new TRTCDebugDialog(this._core,this.log),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(e){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(e))}})}closeDebugDiaLog(){this.dialog&&(this.dialog.closeDialog(),this.dialog=null)}};d(ua,"Name","Debug"),d(ua,"autoStart",!0);var Wd=ua;var g_=s=>{switch(s){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},Gd=class{constructor(i,e,t){d(this,"trackDoneOB");d(this,"startOB");d(this,"stopOB");d(this,"inputFrameCount",0);d(this,"decodedFrameCount",0);d(this,"type","auto");d(this,"config");d(this,"decoder");d(this,"_decodeSink");let{kvStatManager:r,trtc:o}=i;this.config=t.config,this.trackDoneOB=ue(e,Y.INIT),this.stopOB=ot(),this.startOB=ot(),t.type==="auto"?this.type="webCodecs":this.type=t.type;let n=ot(),a=c=>{let l=this.pipe(e);return n.next("STARTING"),e.log.info(`decoder type: ${this.type}`),he(l,Le(this.stopOB),Se(()=>{},u=>{e.log.error(u),r.addFailedEvent({key:g_(this.type),error:u}),c>4?this.startOB.error(u):this.startOB.next(c+1)})),he(l,ar(1),wh(Kn))};he(this.startOB,Yn(0),Vr(a),Le(this.stopOB),Se(()=>{e.player.setOutput(),n.next("STARTED")},c=>{n.next("FAILED")},()=>{r.addSuccessEvent({key:g_(this.type)}),r.addSuccessEvent({key:504702})}))}mock(i){this._decodeSink?this._decodeSink.error(i):this.startOB.next(0)}close(i){this.stopOB.next(i)}pipe(i){return nr()(e=>f(this,null,function*(){this._decodeSink=e,e.defer(()=>{var r;(r=this.decoder)==null||r.close()});let{type:t}=this;try{switch(t){case"webCodecs":this.decoder=new AudioDecoder({error:r=>{i.log.error(r),e.error(4)},output:r=>{this.decodedFrameCount++,e.next(r),i.player.write(r)}});break;case"wasm":break}this.decoder.configure(this.config)}catch(r){i.log.error(r),e.error(t==="webCodecs"?2:6)}}))}decodeFrame(i){var e;this.inputFrameCount++,((e=this.decoder)==null?void 0:e.state)==="configured"&&this.decoder.decode(new EncodedAudioChunk({data:i.data,timestamp:i.timestamp,type:"key"}))}},SI={type:"object"},ha=class ha{constructor(i){this.core=i;d(this,"log");d(this,"contextMap",new Map);d(this,"decodeProcessorMap",new WeakMap);this.log=i.log.createChild({id:`${this.getAlias()}`})}getAlias(){return ha.Name}getGroup(i){return i.track.userId+i.track.streamType}getName(){return ha.Name}getValidateRule(i){return SI}start(i){let{track:e}=i;this.decodeProcessorMap.set(e,this.decode(i)),this.core.room.audioManager.addDecodeProcessor({processor:({frame:t,track:r})=>this.decodeProcessorMap.has(r)?this.decodeProcessorMap.get(r)({frame:t,track:r}):t,type:3})}decode(i){return({frame:e,track:t})=>{if(t!==i.track)return e;if(this.contextMap.has(t))return this.contextMap.get(t).decodeFrame(e);let r=new Gd(this.core,t,i);return he(r.trackDoneOB,ar(1),Se(()=>{this.core.clearStarted(this,this.getGroup(i)),this.stop({track:t})})),this.contextMap.set(t,r),r.decodeFrame(e)}}stop({track:i}){let e=this.contextMap.get(i);e&&(e.close("stop"),this.contextMap.delete(i),this.contextMap.size===0&&this.core.room.audioManager.removeDecodeProcessor({type:3}))}update(i){let e=this.contextMap.get(i.track);if(e){if(i.type==="mock"){e.mock(10);return}e.close("update"),this.contextMap.set(i.track,new Gd(this.core,i.track,i))}}};d(ha,"Name","TRTCAudioDecoder");var ma=ha;var Jd=class{constructor(){d(this,"log");this.log=C.createLogger({id:"exp"})}call(i,e){return f(this,null,function*(){return me(this[i])?this[i](e):Promise.reject(new N({code:I.INVALID_PARAMETER,message:W({key:H.API_NOT_EXIST,data:{name:i}})}))})}enableAudioFrameEvent(i){return f(this,null,function*(){let{trtcInstance:e,enable:t,userId:r,sampleRate:o=48e3,channelCount:n=1,port:a}=i,{audioManager:c}=e.room,{getPCMAbortCtrlMap:l,audioFrameEventConfigMap:u}=c;if(u.set(r,{enable:t,sampleRate:o,channelCount:n,port:a}),t)if(r==="*")e.room.remotePublishedUserMap.forEach(m=>{if(m.remoteAudioTrack.isAvailable){if(l.get(m.userId))return;let p=c.getPCM(h=>{e.emit(w.AUDIO_FRAME,h)},m.userId);l.set(m.userId,p)}});else{if(l.get(r))return;let m=c.getPCM(p=>{e.emit(w.AUDIO_FRAME,p)},r);l.set(r,m)}else if(r==="*")e.room.remotePublishedUserMap.forEach(m=>{if(m.remoteAudioTrack.isSubscribed){let{userId:p}=m,h=l.get(p);h==null||h.abort("disable"),l.delete(p)}});else{let m=l.get(r);m==null||m.abort("disable"),l.delete(r)}})}resumeRemotePlayer(i){return f(this,null,function*(){if(i.userId==="*"){let t=[];return i.trtcInstance.room.remotePublishedUserMap.forEach(r=>{let{remoteAudioTrack:o,remoteVideoTrack:n,remoteAuxiliaryTrack:a}=r;i.streamType?i.streamType==="main"?(o.isAvailable&&t.push(o.player.resume()),n.isAvailable&&t.push(n.player.resume())):a.isAvailable&&t.push(a.player.resume()):(o.isAvailable&&t.push(o.player.resume()),n.isAvailable&&t.push(n.player.resume()),a.isAvailable&&t.push(a.player.resume()))}),Promise.all(t)}let e=i.trtcInstance.room.remotePublishedUserMap.get(i.userId);if(e)return i.streamType==="main"?Promise.all([e.remoteAudioTrack.player.resume(),e.remoteVideoTrack.player.resume()]):e.remoteAuxiliaryTrack.player.resume()})}pauseRemotePlayer(i){if(i.userId==="*")i.trtcInstance.room.remotePublishedUserMap.forEach(e=>{let{remoteAudioTrack:t,remoteVideoTrack:r,remoteAuxiliaryTrack:o}=e;i.streamType?i.streamType==="main"?(t.isAvailable&&t.player.pause(),r.isAvailable&&r.player.pause(!1)):o.isAvailable&&o.player.pause(!1):(t.isAvailable&&t.player.pause(),r.isAvailable&&r.player.pause(!1),o.isAvailable&&o.player.pause(!1))});else{let e=i.trtcInstance.room.remotePublishedUserMap.get(i.userId);e&&(i.streamType==="main"?(e.remoteAudioTrack.player.pause(),e.remoteVideoTrack.player.pause(!1)):e.remoteAuxiliaryTrack.player.pause(!1))}}requestPictureInPicture(i){let e=[...i.trtcInstance.room.remotePublishedUserMap.values()].find(t=>t.remoteVideoTrack.isAvailable);return e?i.enable?e.remoteVideoTrack.player.enterPictureInPicture():e.remoteVideoTrack.player.exitPictureInPicture():Promise.reject(new N({code:I.INVALID_OPERATION,message:"no available remote video"}))}requestFullScreen(i){let e=[...i.trtcInstance.room.remotePublishedUserMap.values()].find(t=>t.remoteVideoTrack.isAvailable);return e?i.enable?e.remoteVideoTrack.player.enterFullscreen():e.remoteVideoTrack.player.exitFullscreen():Promise.reject(new N({code:I.INVALID_OPERATION,message:"no available remote video"}))}getCurrentPlayingStream(i){var t,r,o,n;let e=i;if(e._currentLiveUserId){let a=(t=e._currentLiveStreamType)!=null?t:"main",c=(r=e._remoteVideoConfigMap.get(`${e._currentLiveUserId}_${a}`))==null?void 0:r.config;if(c)return{userId:e._currentLiveUserId,streamType:a,config:c}}for(let[a,c]of i.room.remotePublishedUserMap){if(c.remoteVideoTrack.isPlayCalled){let l=(o=e._remoteVideoConfigMap.get(`${a}_main`))==null?void 0:o.config;if(l)return{userId:a,streamType:"main",config:l}}if(c.remoteAuxiliaryTrack.isPlayCalled){let l=(n=e._remoteVideoConfigMap.get(`${a}_sub`))==null?void 0:n.config;if(l)return{userId:a,streamType:"sub",config:l}}}return null}switchPlaybackQuality(i){return f(this,null,function*(){var l;let{trtcInstance:e,streamList:t,quality:r}=i,o=e;if(t&&t.length>0&&(o._playbackQualityList=t.map(u=>{var m;return L(M({},u),{streamType:(m=u.streamType)!=null?m:"main"})})),r==="auto"||!r)return;if(!o._playbackQualityList||o._playbackQualityList.length<=0){this.log.warn("switchPlaybackQuality: streamList is empty, please call with streamList first");return}let n=o._playbackQualityList.find(u=>u.name===r);if(!n){this.log.warn(`switchPlaybackQuality: quality "${r}" not found in streamList`);return}let a=this.getCurrentPlayingStream(e);if(this.log.info(`currentPlaying userId: ${a==null?void 0:a.userId}, streamType: ${a==null?void 0:a.streamType}`),!a)return;let c=(l=n.streamType)!=null?l:"main";yield e.startRemoteVideo(L(M({},a.config),{userId:n.userId,streamType:c,option:L(M({},a.config.option),{isLiveStream:!0})})),yield e.stopRemoteVideo(M({},a.config)),o._currentLiveUserId=n.userId,o._currentLiveStreamType=c})}};O([Bf({name:"options",type:"object",required:!0,properties:{enable:{required:!0,type:"boolean"},userId:{required:!0,type:"string"},sampleRate:{type:"number",values:[8e3,16e3,32e3,44100,48e3]},channelCount:{type:"number",values:[1,2]},port:{type:"messageport"}}})],Jd.prototype,"enableAudioFrameEvent",1);var T_=new Jd;var E_=We(Ze(),1);var cm=class extends E_.EventEmitter{constructor(){super();d(this,"states",{});d(this,"permissionChangeHandler");d(this,"log");this.log=C.createLogger({id:"pm"}),this.permissionChangeHandler=()=>{var e,t;this.emit("permission-state-change",{camera:(e=this.states.camera)==null?void 0:e.state,microphone:(t=this.states.microphone)==null?void 0:t.state})}}request(e){return f(this,null,function*(){if(this.log.info(`request ${e.join(", ")}`),e.length===0)return Promise.resolve();(yield navigator.mediaDevices.getUserMedia({video:e.includes("camera"),audio:e.includes("microphone")})).getTracks().forEach(r=>r.stop())})}get(e){return f(this,null,function*(){try{return this.states[e]||(this.states[e]=yield navigator.permissions.query({name:e}),this.states[e].addEventListener("change",this.permissionChangeHandler)),this.log.info(`get ${e} permission state: ${this.states[e].state}`),this.states[e].state}catch(t){return this.log.error(`get ${e} permission failed, error: ${t instanceof Error?t.message:t}`),null}})}destroy(){Object.values(this.states).forEach(e=>{e==null||e.removeEventListener("change",this.permissionChangeHandler)}),this.states={}}},pa=new cm;var S_=0,fa=new Set,Ye=null;ul(em);lo.checkStorage();var z=class z extends I_.EventEmitter{constructor(e,t){super();d(this,"_room");d(this,"_eventListened",new Set);d(this,"_localVideoTrack",null);d(this,"_localAudioTrack",null);d(this,"_localScreenTrack",null);d(this,"_localScreenAudioTrack",null);d(this,"_localVideoConfig",null);d(this,"_localScreenConfig",null);d(this,"_localAudioConfig",null);d(this,"_remoteVideoConfigMap",new Map);d(this,"_remoteAudioConfigMap",new Map);d(this,"_remoteAudioVolumeMap",new Map);d(this,"_remoteAudioMuteMap",new Map);d(this,"_mediaTrackMap",new WeakMap);d(this,"_log",C.createLogger({id:`t${++S_}`}));d(this,"_plugins",new Map);d(this,"_networkQuality",null);d(this,"_speakerId");d(this,"enterRoomParams");d(this,"_enableAutoSwitchWhenRecapturing",!0);d(this,"_autoSubscribeDataChannel",!1);d(this,"_playbackQualityList",[]);d(this,"_currentLiveUserId");d(this,"_currentLiveStreamType","main");this._room=new e(M({logger:this._log,frameWorkType:z.frameWorkType},t)),this._room.videoDecodeFallbackType=t.videoDecodeFallback,pe(t.enableAutoSwitchWhenRecapturing)&&(this._enableAutoSwitchWhenRecapturing=t.enableAutoSwitchWhenRecapturing),this._log.info(`create() ${JSON.stringify(t,(r,o)=>r==="plugins"?o.map(n=>n.Name):o)}`),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(r){return this._room.audioManager.dump(r)}}}),t.plugins&&t.plugins.forEach(r=>{this._use(r,t.assetsPath)}),this._use(Vd,t.assetsPath),this._use(xd,t.assetsPath),this._use(Bd,t.assetsPath),this._use(ma,t.assetsPath),this._use(Wd),t.enableSEI&&wn&&this._use(Hd),this._room.on("audio-volume",r=>{var o,n;!r.find(a=>a.userId==="")&&this._localAudioTrack&&r.push({userId:"",volume:Math.floor(((o=this._localAudioTrack.getInternalAudioLevelAfter3A())!=null?o:this._localAudioTrack.getAudioLevel())*100),floatVolume:(n=this._localAudioTrack.getInternalAudioLevelAfter3A())!=null?n:this._localAudioTrack.getInternalAudioLevel()}),t.volumeType===1&&r.forEach(a=>{var l;let c=a.userId===""?this._localAudioTrack:(l=this.room.remotePublishedUserMap.get(a.userId))==null?void 0:l.remoteAudioTrack;c&&(a.volume=c.dbVolume)}),t.enableDbVolume&&r.forEach(a=>{var l;let c=a.userId===""?this._localAudioTrack:(l=this.room.remotePublishedUserMap.get(a.userId))==null?void 0:l.remoteAudioTrack;c&&(a.volume=c.dbVolume)}),this.emit(w.AUDIO_VOLUME,{result:r.sort((a,c)=>c.volume-a.volume)})}),this._room.videoManager.on("error",r=>{this._log.error(new B({code:U.OPERATION_FAILED,extraCode:5504,message:r.message,originError:r}))}),this._listenEvents(),this._initActiveSpeaker(),l_(this,"trtc")}static create(e){}static _create(e,t){Gf();let r=new z(e,t||{});return fa.add(r),r.__v_skip=!0,r}get room(){return this._room}_listenEvents(){it(this,this._room).add("peer-join",e=>{let{userId:t}=e;this.emit(w.REMOTE_USER_ENTER,{userId:t})}).add("peer-leave",({userId:e,reason:t})=>{this.emit(w.REMOTE_USER_EXIT,{userId:e,reason:t})}).add("banned",e=>{Vt(!0),this._exitRoom().finally(()=>{this.emit(w.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().finally(()=>{this.emit(w.ERROR,B.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(w.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let t=L(M({},e),{uplinkRTT:Math.min(e.uplinkRTT,on),downlinkRTT:Math.min(e.downlinkRTT,on)});this.emit(w.NETWORK_QUALITY,t)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(r=>{it(r,r).add("player-state-changed",o=>{let n=L(M({},o),{userId:e.userId});r.kind===_.VIDEO&&(n.streamType=bt(r.streamType)),this.emit(r.kind===_.AUDIO?w.AUDIO_PLAY_STATE_CHANGED:w.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",o=>{o.getCode()===I.PLAY_NOT_ALLOWED&&this.emit(w.AUTOPLAY_FAILED,{userId:r.userId,mediaType:r.strMediaType,resume:()=>r.player.resume()})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(r=>{Fe(r)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:t})=>{let{userId:r}=t,o=e.audioAvailable,n=e.videoAvailable,{audioAvailable:a,videoAvailable:c}=t;a||this._remoteAudioConfigMap.delete(r),c||this._removeRemoteVideoConfig(r,"main"),t.hasAuxiliary||this._removeRemoteVideoConfig(r,"sub"),n!==c&&(c?this._onVideoAvailable({userId:r,streamType:"main"}):this._onVideoUnavailable({userId:r,streamType:"main"}),this.emit(c?w.REMOTE_VIDEO_AVAILABLE:w.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"main"})),o!==a&&(a?this._onAudioAvailable({userId:r}):this._onAudioUnavailable({userId:r,muteState:t}),this.emit(a?w.REMOTE_AUDIO_AVAILABLE:w.REMOTE_AUDIO_UNAVAILABLE,{userId:r})),e.hasAuxiliary!==t.hasAuxiliary&&(t.hasAuxiliary?this._onVideoAvailable({userId:r,streamType:"sub"}):this._onVideoUnavailable({userId:r,streamType:"sub"}),this.emit(t.hasAuxiliary?w.REMOTE_VIDEO_AVAILABLE:w.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"sub"})),e.hasDatachannel!==t.hasDatachannel&&t.hasDatachannel&&this._onDataChannelAvailable()}).add("sei-message",e=>{this.emit(w.SEI_MESSAGE,L(M({},e),{streamType:bt(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(w.ERROR,new B({code:U.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var o,n,a,c,l,u,m;let t={2:"big",3:"small",7:"sub"},r={rtt:Math.min(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,on),upLoss:((c=this._networkQuality)==null?void 0:c.uplinkLoss)||0,downLoss:((l=this._networkQuality)==null?void 0:l.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((u=e.msg_up_stream_info.msg_audio_status)==null?void 0:u.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((m=e.msg_up_stream_info.msg_audio_status)==null?void 0:m.uint32_audio_level)||0)/Pt},video:e.msg_up_stream_info.msg_video_status.filter(p=>t[p.uint32_video_stream_type]).map(p=>({bitrate:(p.uint32_video_codec_bitrate||0)/1e3,width:p.uint32_video_width,height:p.uint32_video_height,frameRate:p.uint32_video_enc_fps,videoType:t[p.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(p=>({userId:p.msg_user_info.str_identifier,audio:{bitrate:(p.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(p.msg_audio_status.uint32_audio_level||0)/Pt,point2pointDelay:(p.msg_audio_status.uint32_audio_p2p_delay||0)+(p.msg_audio_status.uint32_audio_cache_ms||0),jitterBufferDelay:p.msg_audio_status.uint32_audio_cache_ms||0},video:p.msg_video_status.map(h=>({bitrate:(h.uint32_video_codec_bitrate||0)/1e3,width:h.uint32_video_width,height:h.uint32_video_height,frameRate:h.uint32_video_dec_fps,videoType:t[h.uint32_video_stream_type],point2pointDelay:(h.uint32_video_p2p_delay||0)+(h.uint32_video_cache_ms||0),jitterBufferDelay:h.uint32_video_cache_ms||0,codec:h.uint32_video_codec}))}))};this.emit(w.STATISTICS,r)}).add("custom-message",e=>{this.emit(w.CUSTOM_MESSAGE,e)}).add("layerData",e=>this.emit(w.LAYER_DATA,e)).add("first-video-frame",e=>{this.emit(w.FIRST_VIDEO_FRAME,L(M({},e),{streamType:bt(e.streamType)}))}).add("audio-frame",e=>{this.emit(w.AUDIO_FRAME,e)}).add("data-channel-message",e=>{var o,n,a,c,l;let{data:t}=e;if(t.sender==="")return;let r={segmentId:(o=t.payload)==null?void 0:o.roundid,speakerUserId:t.sender,sourceText:(n=t.payload)==null?void 0:n.text,translationTexts:(a=t.payload)==null?void 0:a.translate_msg,timestamp:(c=t.payload)==null?void 0:c.start_utc_ms,isCompleted:(l=t.payload)==null?void 0:l.end,robotId:t.robotid};r.sourceText!==""&&this.emit(w.REALTIME_TRANSCRIBER_MESSAGE,r)}).add("asr-robot-peer-join",e=>{this.emit(w.REALTIME_TRANSCRIBER_STATE_CHANGED,{state:"started",roomId:this.room.roomId,transcriberRobotId:e.userId})}).add("asr-robot-peer-leave",e=>{this.emit(w.REALTIME_TRANSCRIBER_STATE_CHANGED,{state:"stopped",roomId:this.room.roomId,transcriberRobotId:e.userId})}),it(this,Ne).add("audioInputAdded",e=>{this.emit(w.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(w.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(w.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(w.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>f(this,null,function*(){if(this.emit(w.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Ye&&Ye.deviceId===sn){let t=(yield xr()).find(r=>r.deviceId===sn);t&&Ye.groupId!==t.groupId&&(Ye=t,this.emit(w.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}})).add("audioOutputRemoved",e=>f(this,null,function*(){this.emit(w.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield xr())[0];if(!t||!Ye||Ye.groupId===t.groupId)return;let r=Ye.deviceId===e.deviceId,o=Ye.deviceId===sn&&Ye.deviceId===t.deviceId;(r||o)&&(Ye=t,this.emit(w.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))})),it(this,pa).add("permission-state-change",e=>{this.emit(w.PERMISSION_STATE_CHANGE,e)}),this.room.enableSEI&&this.on(w.SEI_MESSAGE,e=>{var r;let t=(r=this.room.remotePublishedUserMap.get(e.userId))==null?void 0:r.remoteVideoTrack;t&&t.updateAlphaRenderInfo(e)})}getNetworkTime(){return Wi()}use(e){let t,r;return"plugin"in e?(t=e.plugin,r=e.assetsPath):t=e,t.Name==="Chorus"&&(this.room.enableChorus=!0),this._use(t,r)}_use(e,t){let r=this._plugins.get(e.Name);if(r)return this._log.warn("duplicate install plugin",e.Name),r;let o=new e(d_.call(this,{TRTC:z,room:this._room,assetsPath:t,errorModule:{RtcError:B,ErrorCode:U,CoreErrorCode:I,ErrorCodeDictionary:Ut}}));return this._plugins.set(e.Name,o),o.__v_skip=!0,e.autoStart&&this.startPlugin(e.Name),o}enterRoom(e){return f(this,null,function*(){var c,l;this.enterRoomParams=e;let{scene:t="rtc",enableAutoPlayDialog:r=!0,autoReceiveAudio:o=!0,autoReceiveVideo:n=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!ne(e.proxy)&&e.proxy.turnServer&&((l=(c=this._room).setTurnServer)==null||l.call(c,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=r,this._room.autoReceiveAudio=o,this._room.autoReceiveVideo=n,pe(e.preferHW)&&(this._room.preferHW=e.preferHW),e.playoutDelay&&(this._room.playoutDelay=e.playoutDelay),e.jitterBufferDelay&&(this._room.jitterBufferDelay=e.jitterBufferDelay);let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:e.role==="audience"?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,enableDataChannel:this._plugins.has("RealtimeTranscriber"),frameWorkType:e.frameWorkType,component:e.component,language:e.language,priority:e.priority,useVp8:e.useVp8,useH265:e.useH265||!1,keepAlive:e.keepAlive};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(a,t,z.frameWorkType),this._checkTrackToPublish(),nm.start()})}exitRoom(){return f(this,null,function*(){return yield this._exitRoom()})}switchRoom(e){return f(this,null,function*(){if(this.room.isSwitchRoomSupported())try{this._clearRemoteTracks(),yield this._room.switchRoom(e)}catch(t){if(t instanceof Qo&&(t.code===I.API_CALL_TIMEOUT||t.code===I.SWITCH_ROOM_FAILED))this._log.warn(`switchRoom ${t.code===I.API_CALL_TIMEOUT?"timeout":"failed"}, fallback to exitRoom() and enterRoom()`),yield this._rejoinRoom(e);else throw t}else yield this._rejoinRoom(e)})}_rejoinRoom(e){return f(this,null,function*(){yield this.exitRoom();let t=M(M({},this.enterRoomParams),e);yield this.enterRoom(t)})}_clearRemoteTracks(){new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(e=>{this._stopRemoteAudio({userId:e}).catch(()=>{})}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let t=e.includes("main")?"main":"sub",r=e.split(`_${t}`)[0];r&&this._stopRemoteVideo({userId:r,streamType:t}).catch(()=>{})}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),u_(this),this._room.remotePublishedUserMap.forEach(e=>{Fe(e.remoteAudioTrack),Fe(e.remoteVideoTrack),Fe(e.remoteAuxiliaryTrack)})}switchRole(e,t){return f(this,null,function*(){t!=null&&t.privateMapKey&&(this._room.privateMapKey=t.privateMapKey),t!=null&&t.latencyLevel&&(this._room.latencyLevel=t.latencyLevel),yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){this._plugins.forEach(e=>{var t;return(t=e.destroy)==null?void 0:t.call(e)}),this._plugins.clear(),Fe(this),this.removeAllListeners(),this._room.destroy(),fa.delete(this),fa.size===0&&nm.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),S.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return f(this,arguments,function*(e={publish:!0}){if(this._localAudioTrack){this._log.warn("local audio is already started");return}let{publish:t=!0,mute:r,muteKeepVolumeDetection:o,option:n}=e,a=new wt(this._room.audioManager),c={},l={muted:!0};n&&(E(n.microphoneId)?E(n.audioTrack)||(c.customSource=n.audioTrack):c.deviceId=n.microphoneId,n&&te(n.captureVolume)&&a.setCaptureVolume(n.captureVolume),E(n.profile)||(ne(n.profile)?Pa[n.profile]&&a.setProfile(Pa[n.profile]):a.setProfile(n.profile)),te(n.earMonitorVolume)&&(l.muted=!(n.earMonitorVolume>0),l.volume=n.earMonitorVolume),E(n.echoCancellation)||(a.profile.echoCancellation=n.echoCancellation),E(n.noiseSuppression)||(a.profile.noiseSuppression=n.noiseSuppression),E(n.autoGainControl)||(a.profile.autoGainControl=n.autoGainControl),pe(this._enableAutoSwitchWhenRecapturing)&&(a.enableAutoSwitchWhenRecapturing=this._enableAutoSwitchWhenRecapturing)),a.on("5",u=>{this.emit(w.ERROR,new B({code:U.DEVICE_ERROR,extraCode:5309,messageParams:{error:u}}))}),a.on("2",u=>{this.emit(w.DEVICE_CHANGED,{type:"microphone",action:"active",device:u})}),a.on("4",u=>{let m;u.error&&(m=B.convertFrom(u.error)),this.emit(w.PUBLISH_STATE_CHANGED,L(M({},u),{error:m}))}),a.on("6",()=>{}),this._listenOutputTrackChanged(a),this._speakerId&&a.setAudioOutput(this._speakerId),yield a.capture(c),E(r)||a.setMute(r,o),it(a,a).add("player-state-changed",u=>{this.emit(w.AUDIO_PLAY_STATE_CHANGED,L(M({},u),{userId:""}))}),t&&this._room.isJoined&&this._room.publish(a).catch(()=>{}),this._localAudioTrack=a,this._room.capturedLocalMainAudioTrack=a,this._localAudioConfig=L(M({},e),{publish:t}),yield this._updateAudioPlayOption({playOption:l,track:a}),S.emit("113",{userId:"",room:this.room})})}updateLocalAudio(e){return f(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:r,muteKeepVolumeDetection:o,option:n}=e,a={};n&&(n.microphoneId?yield this._localAudioTrack.switchDevice(n.microphoneId):E(n.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(n.audioTrack)),E(n.captureVolume)||this._localAudioTrack.setCaptureVolume(n.captureVolume),E(n.earMonitorVolume)||(a.muted=!(n.earMonitorVolume>0),a.volume=n.earMonitorVolume),yield this._localAudioTrack.update3A(n)),this._room.isJoined&&!E(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),E(r)||this._localAudioTrack.setMute(r,o),yield this._updateAudioPlayOption({playOption:a,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),ni(this._localAudioConfig,e)})}stopLocalAudio(){return f(this,null,function*(){this._localAudioTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),S.emit("114",{userId:"",room:this.room}),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),Fe(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null,delete this._room.capturedLocalMainAudioTrack)})}startLocalVideo(){return f(this,arguments,function*(e={publish:!0,view:null,capture:!0}){var p,h;if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:t,publish:r=!0,capture:o=!0,mute:n,option:a}=e,c=r,l=new ze(this._room.videoManager),u={},m={};a&&(pe(a.avoidCropping)&&(l.avoidCropping=a.avoidCropping),a.cameraId?u.deviceId=a.cameraId:E(a.useFrontCamera)?E(a.videoTrack)||(u.customSource=a.videoTrack):u.facingMode=a.useFrontCamera?_.FACING_MODE_USER:_.FACING_MODE_ENVIRONMENT,E(a.retryWhenExactFailed)||(u.retryWhenExactFailed=a.retryWhenExactFailed),a.qosPreference&&(u.contentHint=na(a.qosPreference)),E(a.profile)||(ne(a.profile)?ti[a.profile]&&l.setProfile(ti[a.profile]):l.setProfile(a.profile)),E(a.fillMode)||(m.objectFit=a.fillMode),E(a.mirror)||(m.mirror=a.mirror),E(a.small)||(E(a.smallMode)||(this._room.smallMode=a.smallMode),pe(a.small)&&a.small===!1?l.stopSmall():l.updateSmallConfig(wo(a.small,!0))),E(a.rotation)||l.setRotation(a.rotation),pe(this._enableAutoSwitchWhenRecapturing)&&(l.enableAutoSwitchWhenRecapturing=this._enableAutoSwitchWhenRecapturing)),l.once("first-video-frame",T=>{this.emit(w.FIRST_VIDEO_FRAME,L(M({},T),{streamType:bt(T.streamType)}))}),l.on("5",T=>{this.emit(w.ERROR,new B({code:U.DEVICE_ERROR,extraCode:5308,messageParams:{error:T}}))}),l.on("2",T=>{this.emit(w.DEVICE_CHANGED,{type:"camera",action:"active",device:T})}),l.on("4",T=>{let g;T.error&&(g=B.convertFrom(T.error)),this.emit(w.PUBLISH_STATE_CHANGED,L(M({},T),{error:g}))}),l.on("6",()=>{}),this._listenOutputTrackChanged(l),o?yield l.capture(u):(p=l.manager)==null||p.changeInput(l),E(n)||(yield l.setMute(n)),it(l,l).add("player-state-changed",T=>{this.emit(w.VIDEO_PLAY_STATE_CHANGED,L(M({},T),{userId:"",streamType:"main"}))}).add("video-size-changed",T=>{this.emit(w.VIDEO_SIZE_CHANGED,L(M({},T),{streamType:bt(T.streamType)}))}),c&&this._room.isJoined&&(this._localScreenTrack&&((h=this._localScreenConfig)==null?void 0:h.publish)&&this._localScreenConfig.streamType==="main"?(c=!1,this._log.warn("main stream is already published, local video track will not publish")):this._room.publish(l).catch(()=>{})),this._localVideoTrack=l,this._room.capturedLocalMainVideoTrack=l,this._localVideoConfig=L(M({},e),{view:t,publish:c,capture:o}),yield this._updateVideoPlayOption({view:t,playOption:m,track:l})})}updateLocalVideo(e){return f(this,null,function*(){var m,p,h,T;if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:r=!0,mute:o,capture:n,option:a,forcePublish:c=!1}=e,l=r||c,u={};if(this._localVideoConfig.capture)n!==!1?a!=null&&a.cameraId?yield this._localVideoTrack.switchDevice(a==null?void 0:a.cameraId):E(a==null?void 0:a.useFrontCamera)?E(a==null?void 0:a.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(a==null?void 0:a.videoTrack)):yield this._localVideoTrack.switchDevice(a!=null&&a.useFrontCamera?_.FACING_MODE_USER:_.FACING_MODE_ENVIRONMENT):this._localVideoTrack.stopCapture();else if(n){let g={};g.deviceId=(a==null?void 0:a.cameraId)||((m=this._localVideoConfig.option)==null?void 0:m.cameraId),g.facingMode=a!=null&&a.useFrontCamera||(p=this._localVideoConfig.option)!=null&&p.useFrontCamera?_.FACING_MODE_USER:_.FACING_MODE_ENVIRONMENT,g.customSource=(a==null?void 0:a.videoTrack)||((h=this._localVideoConfig.option)==null?void 0:h.videoTrack),yield this._localVideoTrack.capture(g)}a&&(E(a.profile)||(ne(a.profile)?ti[a.profile]&&this._localVideoTrack.setProfile(ti[a.profile]):this._localVideoTrack.setProfile(a.profile),(!a.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(a.cameraId))&&E(a.useFrontCamera)&&(yield this._localVideoTrack.applyProfile())),E(a.fillMode)||(u.objectFit=a.fillMode),E(a.mirror)||(u.mirror=a.mirror),E(a.rotation)||this._localVideoTrack.setRotation(a.rotation),a.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(na(a.qosPreference)),E(a.small)||(pe(a.small)&&!a.small?this._localVideoTrack.stopSmall():this._localVideoTrack.updateSmallConfig(wo(a.small,!0)))),this._room.isJoined&&E(l)&&this._localVideoConfig.publish&&n&&!this._localVideoConfig.capture&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._room.isJoined&&((l!=null?l:this._localVideoConfig.publish)||c?!(this._localScreenTrack&&((T=this._localScreenConfig)==null?void 0:T.publish)&&this._localScreenConfig.streamType==="main")||c?this._room.publish(this._localVideoTrack).catch(()=>{}):(l=!1,this._log.warn("main stream is already published, local video track will not publish")):this._room.unpublish(this._localVideoTrack).catch(()=>{})),E(o)||(yield this._localVideoTrack.setMute(o)),yield this._updateVideoPlayOption({view:t,playOption:u,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),ni(this._localVideoConfig,L(M({},e),{publish:l}))})}stopLocalVideo(){return f(this,null,function*(){var e;this._localVideoTrack&&(this._room.isJoined&&((e=this._localVideoConfig)!=null&&e.publish)&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),Fe(this._localVideoTrack),this._localVideoTrack=null,delete this._room.capturedLocalMainVideoTrack,this._localVideoConfig=null)})}startScreenShare(){return f(this,arguments,function*(e={publish:!0,view:null}){var h,T,g;if(this._localScreenTrack){this._log.warn("screen share is already started");return}let{view:t=null,publish:r=!0,muteSystemAudio:o,option:n}=e,a=r,c=new xt(this._room.videoManager);c.on("4",R=>{let D;R.error&&(D=B.convertFrom(R.error)),this.emit(w.PUBLISH_STATE_CHANGED,L(M({},R),{error:D}))}),c.once("first-video-frame",R=>{this.emit(w.FIRST_VIDEO_FRAME,L(M({},R),{streamType:bt(R.streamType)}))}),this._listenOutputTrackChanged(c),e.streamType==="main"&&(c.mediaType=4);let l=null,u={},m={};n&&(E(n.profile)||(ne(n.profile)?ka[n.profile]&&c.setProfile(ka[n.profile]):c.setProfile(n.profile)),n.systemAudio&&(u.systemAudio=!0,u.echoCancellation=n.echoCancellation,u.noiseSuppression=n.noiseSuppression,u.autoGainControl=n.autoGainControl),E(n.fillMode)||(m.objectFit=n.fillMode),n.videoTrack&&(u.videoTrack=n.videoTrack),n.audioTrack&&(u.audioTrack=n.audioTrack),n.captureElement&&(u.captureElement=n.captureElement),n.preferDisplaySurface&&(u.preferDisplaySurface=n.preferDisplaySurface),n.qosPreference&&(u.contentHint=na(n.qosPreference)));let p=yield c.capture(u);if(c.mediaTrack.addEventListener(_.ENDED,()=>{this._stopScreenShare(),this.emit(w.SCREEN_SHARE_STOPPED)}),p.getAudioTracks()[0]){l=new ys(this._room.audioManager);let R=p.getAudioTracks()[0];(h=e.option)!=null&&h.systemAudio&&!((T=e.option)!=null&&T.audioTrack)&&(l.sourceTrack=R),yield l.setInputMediaStreamTrack(R),pe(o)&&l.mediaTrack&&(l.mediaTrack.enabled=!o),this._speakerId&&l.setAudioOutput(this._speakerId)}if(it(c,c).add("player-state-changed",R=>{this.emit(w.VIDEO_PLAY_STATE_CHANGED,L(M({},R),{userId:"",streamType:"sub"}))}),a&&this._room.isJoined){let R=this._localVideoTrack&&((g=this._localVideoConfig)==null?void 0:g.publish);!(e.streamType==="main"&&R)?this._room.publish(c).catch(()=>{}):(a=!1,this._log.warn("main stream is already published, screen share main will not publish")),l&&(this._checkScreenAudioEchoCancellation(c,l),this._room.publish(l).catch(()=>{}))}this._localScreenTrack=c,this._room.capturedLocalAuxVideoTrack=c,this._localScreenAudioTrack=l,this._localScreenConfig=L(M({},e),{view:t,publish:a}),yield this._updateVideoPlayOption({view:t,playOption:m,track:c})})}updateScreenShare(e){return f(this,null,function*(){var l,u;if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:r,muteSystemAudio:o,option:n}=e,a=r,c={};if(n){if(E(n.fillMode)||(c.objectFit=n.fillMode),n.qosPreference){let m=na(n.qosPreference);this._localScreenTrack.setContentHint(m)}n.videoTrack&&this._localScreenTrack.setInputMediaStreamTrack(n.videoTrack),n.audioTrack&&this._localScreenAudioTrack&&this._localScreenAudioTrack.setInputMediaStreamTrack(n.audioTrack)}if(this._room.isJoined&&!E(a)){if(a&&!this._localScreenConfig.publish){let m=this._localVideoTrack&&((l=this._localVideoConfig)==null?void 0:l.publish);!(this._localScreenConfig.streamType==="main"&&m)?this._room.publish(this._localScreenTrack).catch(()=>{}):(a=!1,this._log.warn("main stream is already published, screen share main will not publish")),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch(()=>{})}if(this._localScreenConfig.publish&&!a){let m=[this._localScreenTrack];this._localScreenAudioTrack&&m.push(this._localScreenAudioTrack),m.forEach(p=>this._room.unpublish(p).catch(()=>{}))}}(u=this._localScreenAudioTrack)!=null&&u.mediaTrack&&pe(o)&&(this._localScreenAudioTrack.mediaTrack.enabled=!o),yield this._updateVideoPlayOption({view:t,playOption:c,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),ni(this._localScreenConfig,L(M({},e),{publish:a}))})}stopScreenShare(){return f(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return f(this,null,function*(){let{view:t,userId:r,streamType:o,option:n}=e,a=`${r}_${o}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${r}, streamType:${o}`);return}let c=this._room.remotePublishedUserMap.get(r);if(!c)return;let l={},u=o==="main"?c.remoteVideoTrack:c.remoteAuxiliaryTrack,m=this._bindRemoteVideoTrackEvents(u);this._listenOutputTrackChanged(u),n&&(E(n.fillMode)||(l.objectFit=n.fillMode),E(n.mirror)||(l.mirror=n.mirror),E(n.poster)||(l.poster=n.poster),l.canvasRender=n.canvasRender,o==="main"&&!E(n.small)&&(!c.remoteVideoTrack.isSubscribing&&!c.remoteVideoTrack.isSubscribed&&c.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,u.user)),E(n.draggable)||u.setDraggable(n.draggable)),l.isLiveStream=!!this._playbackQualityList.find(p=>p.userId===r&&p.streamType===o),yield this._room.subscribe(u),yield this._enableVideoDecodeFallback(u,o),yield this._updateVideoPlayOption({view:t,playOption:l,track:u}),this._emitTrackEvent(u),this._remoteVideoConfigMap.set(a,{config:e,handlers:m}),n&&!E(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:u,view:t,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:n==null?void 0:n.viewRoot}),l.isLiveStream&&(this._currentLiveUserId=r,this._currentLiveStreamType=o)})}updateRemoteVideo(e){return f(this,null,function*(){var D,j;let{view:t,userId:r,streamType:o,option:n,mute:a}=e,c=`${r}_${o}`,l=this._remoteVideoConfigMap.get(c);if(!l||!this._room.remotePublishedUserMap.has(r))return;let u={};n&&(E(n.fillMode)||(u.objectFit=n.fillMode),E(n.mirror)||(u.mirror=n.mirror));let m=null,p=this._room.remotePublishedUserMap.get(r);if(o==="main"&&(p!=null&&p.muteState.hasVideo)&&(m=p.remoteVideoTrack),o==="sub"&&(p!=null&&p.muteState.hasAuxiliary)&&(m=p.remoteAuxiliaryTrack),!m)return;let{config:h}=l;o==="main"&&n&&!E(n.small)&&this._room.changeType(n.small,m.user),n&&!E(n.draggable)&&m.setDraggable(n.draggable),n&&(pe(n.pictureInPicture)&&(n.pictureInPicture?yield m.player.enterPictureInPicture():yield m.player.exitPictureInPicture()),pe(n.fullScreen)&&(n.fullScreen?yield m.player.enterFullscreen():yield m.player.exitFullscreen())),pe(a)&&(m.ignoreUpdatePlayingState=!0,a?(yield m.player.pause(),yield this.room.unsubscribe(m)):(yield this.room.subscribe(m),yield m.player.resume(!0))),yield this._updateVideoPlayOption({view:t,playOption:u,track:m,prevConfig:h}),ni(h,e);let T=E(n==null?void 0:n.receiveWhenViewVisible)?(D=h.option)==null?void 0:D.receiveWhenViewVisible:n.receiveWhenViewVisible,g=E(t)?h.view:t,R=E(n==null?void 0:n.viewRoot)?(j=h.option)==null?void 0:j.viewRoot:n.viewRoot;this._observeView({remoteTrack:m,view:g,receiveWhenViewVisible:T,viewRoot:R})})}stopRemoteVideo(e){return f(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,t=!0){return f(this,null,function*(){let r=[],o=this._room.remotePublishedUserMap.get(e.userId);if(o){let{muteState:n,remoteVideoTrack:a,remoteAuxiliaryTrack:c}=o;e.streamType==="main"&&(a.stop(),n.hasVideo&&r.push(a)),e.streamType==="sub"&&(c.stop(),n.hasAuxiliary&&r.push(c))}for(let n of r)t&&(delete n.ignoreUpdatePlayingState,yield this._room.unsubscribe(n),this._mediaTrackMap.delete(n.outMediaTrack));this._removeRemoteVideoConfig(e.userId,e.streamType)})}_removeRemoteVideoConfig(e,t){let r=`${e}_${t}`,o=this._remoteVideoConfigMap.get(r);if(o&&(o.observer&&o.observer.disconnect(),o.handlers)){let n=this._room.remotePublishedUserMap.get(e);if(n){let a=t==="main"?n.remoteVideoTrack:n.remoteAuxiliaryTrack;this._unbindRemoteVideoTrackEvents(a,o.handlers)}}this._remoteVideoConfigMap.delete(r)}_bindRemoteVideoTrackEvents(e){let t={onEnterPIP:()=>f(this,null,function*(){yield e.player.enterPIPPromise,this.emit(w.PICTURE_IN_PICTURE_STATE_CHANGED,{streamType:bt(e.streamType),userId:e.userId,isPictureInPicture:!0,pictureInPictureWindow:e.player.pipWindow})}),onLeavePIP:()=>{this.emit(w.PICTURE_IN_PICTURE_STATE_CHANGED,{streamType:bt(e.streamType),userId:e.userId,isPictureInPicture:!1})},onEnterFullScreen:()=>{this.emit(w.FULL_SCREEN_STATE_CHANGED,{streamType:bt(e.streamType),userId:e.userId,isFullScreen:!0})},onLeaveFullScreen:()=>{this.emit(w.FULL_SCREEN_STATE_CHANGED,{streamType:bt(e.streamType),userId:e.userId,isFullScreen:!1})},onDecodeFailed:()=>{this.emit(w.ERROR,new B({code:U.OPERATION_FAILED,extraCode:5507,message:"video decode failed"}))},onVideoSizeChanged:r=>{this.emit(w.VIDEO_SIZE_CHANGED,L(M({},r),{streamType:bt(r.streamType)}))}};return e.player.on(G.ENTER_PICTURE_IN_PICTURE,t.onEnterPIP),e.player.on(G.LEAVE_PICTURE_IN_PICTURE,t.onLeavePIP),e.player.on(G.ENTER_FULL_SCREEN,t.onEnterFullScreen),e.player.on(G.LEAVE_FULL_SCREEN,t.onLeaveFullScreen),e.on("decode-failed",t.onDecodeFailed),e.on("video-size-changed",t.onVideoSizeChanged),t}_unbindRemoteVideoTrackEvents(e,t){e.player.off(G.ENTER_PICTURE_IN_PICTURE,t.onEnterPIP),e.player.off(G.LEAVE_PICTURE_IN_PICTURE,t.onLeavePIP),e.player.off(G.ENTER_FULL_SCREEN,t.onEnterFullScreen),e.player.off(G.LEAVE_FULL_SCREEN,t.onLeaveFullScreen),e.off("decode-failed",t.onDecodeFailed),e.off("video-size-changed",t.onVideoSizeChanged)}muteRemoteAudio(e,t){return f(this,null,function*(){this._remoteAudioMuteMap.set(e,t);try{if(e==="*")if(t)yield this._stopRemoteAudio({userId:e});else{let r=[...this._room.remotePublishedUserMap.values()];for(let o of r)o.muteState.hasAudio&&!this._remoteAudioConfigMap.has(o.userId)&&this.room.isJoined&&(yield this._startRemoteAudio({userId:o.userId}))}else t?yield this._stopRemoteAudio({userId:e}):!this._remoteAudioConfigMap.has(e)&&this.room.isJoined&&(yield this._startRemoteAudio({userId:e}))}catch(r){throw r.code!==U.OPERATION_ABORT&&this._remoteAudioMuteMap.delete(e),r}})}setRemoteAudioVolume(e,t){if(e==="*"){this._remoteAudioVolumeMap.set("*",t),this._remoteAudioVolumeMap.forEach((o,n)=>this._remoteAudioVolumeMap.set(n,t));let r=[...this._room.remotePublishedUserMap.values()];for(let o of r)this._remoteAudioVolumeMap.set(o.userId,t),o.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:o.remoteAudioTrack})}else if(e){let r=this._room.remotePublishedUserMap.get(e);this._remoteAudioVolumeMap.set(e,t),r&&r.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:r.remoteAudioTrack})}}startPlugin(e,t){return f(this,null,function*(){return e.start(t)})}updatePlugin(e,t){return f(this,null,function*(){return e.update(t)})}stopPlugin(e,t){return f(this,null,function*(){return e.stop(t)})}enableAudioVolumeEvaluation(e=2e3,t=!1){this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,r){if(this.listeners(e).includes(t))return this;if(this._log.debug("on",e),super.on(e,t,r),this._eventListened.add(e),this.listeners(w.AUDIO_FRAME).length>0){let{audioFrameEventConfigMap:o}=this.room.audioManager;o.get("")||o.set("",{enable:!0}),this._localAudioTrack&&this.room.audioManager.handleLocalTrackStarted({userId:"",room:this.room})}return e==="realtime-transcriber-message"&&this._room.subscribeDataChannel(),this}emit(e,...t){try{t_.has(e)||this._log.debug(`emit ${e} ${JSON.stringify(t)}`)}catch(r){}return super.emit(e,...t)}off(e,t,r){if(this._log.debug("off",e),e==="*"?(this._eventListened.clear(),this.removeAllListeners()):super.off(e,t,r),(e==="realtime-transcriber-message"||e==="*")&&this.listeners("realtime-transcriber-message").length===0&&this._room.unsubscribeDataChannel(),(e===z.EVENT.AUDIO_FRAME||e==="*")&&this.listeners(z.EVENT.AUDIO_FRAME).length===0){let{getPCMAbortCtrlMap:o}=this.room.audioManager;o.forEach(n=>{n==null||n.abort("off")}),o.clear()}return this}getAudioTrack(e={userId:"",streamType:"main"}){let t,r=null,o="main",n=!1;if(ne(e)?t=e:(t=e.userId,n=e.processed===!0,e.streamType&&(o=e.streamType)),t){let a=this._room.remotePublishedUserMap.get(t);a&&(r=a.remoteAudioTrack)}else r=o==="sub"?this._localScreenAudioTrack:this._localAudioTrack;return r?n&&r.outMediaTrack&&r.outMediaTrack!==r.mediaTrack?r.outMediaTrack.clone():r.mediaTrack:null}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:t="",streamType:r="main",processed:o=!1}=e,n=null;if(t==="")r==="main"&&this._localVideoTrack&&(n=this._localVideoTrack),r==="sub"&&this._localScreenTrack&&(n=this._localScreenTrack);else{let a=this._room.remotePublishedUserMap.get(t);a&&(n=r==="main"?a.remoteVideoTrack:a.remoteAuxiliaryTrack)}return n?o&&n.outMediaTrack&&n.outMediaTrack!==n.mediaTrack?n.outMediaTrack.clone():n.mediaTrack:null}getVideoSnapshot(e={}){let{userId:t,streamType:r="main"}=e;if(t){let o=this._room.remotePublishedUserMap.get(t);if(r==="main"&&(o!=null&&o.muteState.hasVideo))return o.remoteVideoTrack.getVideoFrame();if(r==="sub"&&(o!=null&&o.muteState.hasAuxiliary))return o.remoteAuxiliaryTrack.getVideoFrame()}else{if(r==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(r==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(e){var t,r;this._speakerId=e,(t=this._localAudioTrack)==null||t.setAudioOutput(e),(r=this._localScreenAudioTrack)==null||r.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(o=>o.remoteAudioTrack.setAudioOutput(e))}setCurrentSpeaker(e){return f(this,null,function*(){(yield xr()).forEach(r=>{r.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(w.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}),Ye=r)}),this._log.warn(`the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: ${gt}/en/TRTC.html#.setCurrentSpeaker`)})}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return f(this,null,function*(){var a;let{userId:t}=e;if(this._remoteAudioConfigMap.has(t)){this._log.warn(`remote audio has already started. userId:${t}`);return}let r=this._room.remotePublishedUserMap.get(t);if(!r)return;let o={},n=r.remoteAudioTrack;n.on("decode-failed",c=>{this.emit(w.ERROR,new B({code:U.OPERATION_FAILED,extraCode:5508,message:"audio decode failed"}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId);try{let c=(a=this._remoteAudioVolumeMap.get(t))!=null?a:this._remoteAudioVolumeMap.get("*"),l=te(c)?c:100;o.volume=l,this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(n),he(ue(n,"decode-failed"),Le(ue(n,Y.INIT)),Se(()=>{this.startPlugin(ma.Name,{track:n,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:o,track:n}),S.emit("115",{userId:t,room:this.room}),n.outMediaTrack&&this.room.audioManager.updateAudioReference({type:"add",audioReference:n.outMediaTrack,refId:`ra-${t}`})}catch(c){throw this._remoteAudioConfigMap.delete(t),c}this._emitTrackEvent(n)})}_stopRemoteAudio(e,t=!0){return f(this,null,function*(){let r=this._room.remotePublishedUserMap.get(e.userId);r&&(r.remoteAudioTrack.stop(),r.muteState.hasAudio&&t&&(yield this._room.unsubscribe(r.remoteAudioTrack)),this._mediaTrackMap.delete(r.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete(`${e.userId}`),S.emit("116",{userId:e.userId,room:this.room}),this.room.audioManager.updateAudioReference({type:"remove",refId:`ra-${e.userId}`})})}_enableVideoDecodeFallback(e,t){let r=this._room.videoDecodeFallbackType;if(!r||!this._plugins.has("TRTCVideoDecoder"))return;e.log.debug("remote video will fall back when decode failed",e.id);let o;he(ue(e,"decode-failed"),Le(ue(e,Y.INIT)),ta(()=>{this._room.downlinkVideoCodec!=="h265"&&this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:r})}),Ss(ue(e,"decode-downgrade-state-changed")),Se(n=>{o=n.state,this.emit(w.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,L(M({},n),{streamType:t,userId:e.userId}))},n=>{e.log.error("fallback",n)},()=>{o==="STARTED"&&e.log.info("fallback complete")}))}_updateVideoPlayOption(n){return f(this,arguments,function*({view:e,playOption:t,track:r,prevConfig:o}){if(r.setMirror(t.mirror),E(e)&&o&&o.view&&!js(t)){let a=Xs(o.view);a.length>0&&(yield r.play(a,t))}if(!E(e)){let a=Xs(e);a.length>0?yield r.play(a,t):r.stop()}})}_updateAudioPlayOption(o){return f(this,arguments,function*({playOption:e={},track:t,prevConfig:r}){if(!t.isPlayCalled)try{yield t.play(null,e)}catch(n){}if(E(e.muted)||t.setPlayerMute(e.muted),E(e.volume)||t.setAudioVolume(e.volume/100),t instanceof wt&&t.mediaTrack){let n=e.muted===!1&&!E(e.volume)&&e.volume>0?"add":"remove";this.room.audioManager.updateAudioReference({type:n,audioReference:t.mediaTrack,refId:"em"})}else if(t instanceof Ai){let n=e.muted?0:e.volume;if(E(n))return;this.room.audioManager.updateAudioReference({type:"updateVolume",refId:`ra-${t.userId}`,volume:e.volume})}})}_listenOutputTrackChanged(e){e.listeners("output-media-track-changed").length===0&&e.on("output-media-track-changed",()=>this._emitTrackEvent(e,!1))}_emitTrackEvent(e,t=!0){let r=e.isRemote?e.userId:"";e.outMediaTrack&&(t&&this._mediaTrackMap.get(e.outMediaTrack)===r||(this._mediaTrackMap.set(e.outMediaTrack,r),this.emit(w.TRACK,{userId:r,streamType:bt(e.streamType),track:e.outMediaTrack,sourceTrack:e.mediaTrack})))}_checkTrackToPublish(){var t,r,o;let e=[];if((t=this._localAudioConfig)!=null&&t.publish&&this._localAudioTrack&&e.push(this._localAudioTrack),(r=this._localVideoConfig)!=null&&r.publish&&this._localVideoTrack&&e.push(this._localVideoTrack),(o=this._localScreenConfig)!=null&&o.publish&&(this._localScreenTrack&&e.push(this._localScreenTrack),this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack),this._checkScreenAudioEchoCancellation(this._localScreenTrack,this._localScreenAudioTrack)),e.length!==0)return Promise.all(e.map(n=>this._room.publish(n).catch(()=>{})))}_observeView({remoteTrack:e,view:t,receiveWhenViewVisible:r,viewRoot:o}){if(E(t)||E(r))return;let n=this._remoteVideoConfigMap.get(`${e.userId}_${bt(e.streamType)}`);if(!n)return;let a=n.observer||void 0;if(t===null||Ie(t)&&t.length===0||!r){a==null||a.disconnect(),e.isSubscribed||(this._log.info("_observeView observer disconnect, resubscribe",e.userId,e.strMediaType),this._room.subscribe(e).catch(()=>{}));return}let l=n.visibleViewMap||new Map,u=-1;(!a||a.root!==o)&&(a==null||a.disconnect(),l.clear(),a=new IntersectionObserver(p=>{p.forEach(h=>{l.set(h.target,h.isIntersecting),e.log.info(`view ${h.target.id} is${h.isIntersecting?"":" not"} visible`)}),clearTimeout(u),u=window.setTimeout(()=>{[...l.values()].find(T=>T)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:o}));let m=new Set(Xs(t));l.forEach((p,h)=>{m.has(h)||(a.unobserve(h),l.delete(h))}),m.forEach(p=>{l.set(p,!0),a.observe(p)}),a.takeRecords().forEach(p=>{l.set(p.target,p.isIntersecting)}),n.visibleViewMap=l,n.observer=a}_exitRoom(){return f(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),this._clearRemoteTracks()})}_stopScreenShare(){return f(this,null,function*(){var e,t;if(this._localScreenTrack){if(this._room.isJoined){let r=[];(e=this._localScreenConfig)!=null&&e.publish&&r.push(this._localScreenTrack),this._localScreenAudioTrack&&r.push(this._localScreenAudioTrack),yield Promise.all(r.map(o=>this._room.unpublish(o).catch(()=>{})))}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(((t=this._localScreenAudioTrack.trackSettings)==null?void 0:t.echoCancellation)===!1&&this.stopPlugin("AudioProcessor"),this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),Fe(this._localScreenTrack),this._localScreenTrack=null,delete this._room.capturedLocalAuxVideoTrack,this._localScreenConfig=null}})}_checkScreenAudioEchoCancellation(e,t){return f(this,null,function*(){var o,n;if(!e||!t)return;let r=(o=e.trackSettings)==null?void 0:o.displaySurface;if(((n=t.trackSettings)==null?void 0:n.echoCancellation)===!1&&(r==="monitor"||r==="browser"&&e.isShareCurrentTab)){this._log.warn("echoCancellation of screen audio track is disable. Try starting audioProcessor plugin");try{yield this.startPlugin("AudioProcessor",{sdkAppId:Number(this.room.sdkAppId),userId:this._room.userId,userSig:this.room.userSig,isScreenAudioNeedAudioProcess:!0,isLocalAudioNeedAudioProcess:!1})}catch(a){this._log.warn("start audioProcessor plugin failed: ",a)}}})}_onLocalTrackCaptured({track:e}){e.kind==="audio"&&(!Ye||Ao(Ye))&&(this._initActiveSpeaker(),S.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return f(this,null,function*(){if(Ye&&!Ao(Ye))this.emit(w.DEVICE_CHANGED,{type:"speaker",action:"active",device:Ye});else{let e=yield xr();e[0]&&!Ao(e[0])?(Ye=e[0],this.emit(w.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):S.on("102",this._onLocalTrackCaptured,this)}})}_onAudioAvailable({userId:e}){let t=this._remoteAudioMuteMap.has(e)?this._remoteAudioMuteMap.get(e):this._remoteAudioMuteMap.get("*");(t===!1||this._room.autoReceiveAudio&&!t)&&this._doStartRemoteAudio({userId:e}).catch(()=>{})}_onVideoAvailable({userId:e,streamType:t}){if(!this._room.autoReceiveVideo)return;let r=this._room.remotePublishedUserMap.get(e);if(r){let o=t==="main"?r.remoteVideoTrack:r.remoteAuxiliaryTrack,n=[o];this._room.autoReceiveAudio&&r.remoteAudioTrack.isAvailable&&n.push(r.remoteAudioTrack),this._room.subscribe(...n).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(()=>{})}_onDataChannelAvailable(){if(this.listeners("realtime-transcriber-message").length>0)return this._room.subscribeDataChannel()}sendSEIMessage(e,t){var o;let r=this._plugins.get("SEI");r&&(r.update({buffer:e,options:L(M({seiPayloadType:243},t),{small:!!((o=this._localVideoTrack)!=null&&o.small)})}),y.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,r;(r=(t=this._room).sendCustomMessage)==null||r.call(t,e),y.addCount({key:500001,useUV:!0})}callExperimentalAPI(e,t){return f(this,null,function*(){return this._log.info(`callExperimentalAPI(${e}, ${JSON.stringify(t)})`),T_.call(e,M({trtcInstance:this},t))})}static setLogLevel(e,t){C.setLogLevel(e),E(t)||(t?C.enableUploadLog():C.disableUploadLog())}static isSupported(){return wc(z.frameWorkType)}static getPermissions(r){return f(this,arguments,function*({request:e=!0,types:t=["camera","microphone"]}){e&&(yield pa.request(t).catch(a=>{var c;return C.error(`getPermissions request failed, error: ${(c=a==null?void 0:a.message)!=null?c:a}`)}));let[o,n]=yield Promise.all([pa.get("camera"),pa.get("microphone")]);return{camera:o,microphone:n}})}static getCameraList(e=!0){return Rt(e)}static getMicrophoneList(e=!0){return At(e)}static getSpeakerList(e=!0){return xr(e)}static setCurrentSpeaker(e){return f(this,null,function*(){if(fe&&(e===vs.SPEAKER||e===vs.HEADSET)){let r=yield z.getMicrophoneList(),o="";if(r.forEach(n=>{n.label===e&&(o=n.deviceId)}),!o)return;fa.forEach(n=>f(null,null,function*(){n._localAudioTrack&&(yield n.updateLocalAudio({option:{microphoneId:o}}))}));return}(yield xr()).forEach(r=>{r.deviceId===e&&(fa.forEach(o=>{o._setCurrentSpeaker(e),o.emit(w.DEVICE_CHANGED,{type:"speaker",action:"active",device:r})}),Ye=r)})})}static _addKVStat({type:e,key:t,value:r,base:o,useUV:n,version:a,max:c}){switch(a&&(us.version=a),e){case"count":us.addCount({key:t,useUV:n});break;case"enum":us.addEnum({key:t,value:r,useUV:n});break;case"number":us.addNumber({key:t,value:r,split:o,max:c});break}}get localVideoTrack(){return this._localVideoTrack}get localScreenTrack(){return this._localScreenTrack}get localScreenAudioTrack(){return this._localScreenAudioTrack}};d(z,"VERSION",em),d(z,"_loggerManager",C),d(z,"EVENT",w),d(z,"ERROR_CODE",U),d(z,"TYPE",vs),d(z,"frameWorkType",30),O([Re({replaceArg:e=>({argIndex:0,value:{name:"plugin"in e?e.plugin.Name:e.Name,assetsPath:"assetsPath"in e?e==null?void 0:e.assetsPath:"default"}})})],z.prototype,"use",1),O([nt(je.TRTC.enterRoom),$r("room",([e],[t])=>(e.roomId||e.strRoomId)===(t.roomId||t.strRoomId)&&e.userId===t.userId&&e.sdkAppId===t.sdkAppId),K(e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)}),Re()],z.prototype,"enterRoom",1),O([Re()],z.prototype,"exitRoom",1),O([nt(je.TRTC.switchRoom),Re(),or()],z.prototype,"switchRoom",1),O([nt(je.TRTC.switchRole),Ds("room",{merge:(e,t)=>t}),Re()],z.prototype,"switchRole",1),O([Re()],z.prototype,"destroy",1),O([nt(je.TRTC.startLocalAudio),$r("audio",([e],[t])=>{var r,o;return((r=e==null?void 0:e.option)==null?void 0:r.microphoneId)===((o=t==null?void 0:t.option)==null?void 0:o.microphoneId)}),Re()],z.prototype,"startLocalAudio",1),O([nt(je.TRTC.updateLocalAudio),Ds("audio",{debounce:{delay:200,getKey:()=>`${S_}-localAudio`,isNeedToDebounce:e=>{var t;return!E((t=e.option)==null?void 0:t.captureVolume)}}}),Re()],z.prototype,"updateLocalAudio",1),O([Wr("audio"),Re()],z.prototype,"stopLocalAudio",1),O([nt(je.TRTC.startLocalVideo),$r("video",([e],[t])=>{var r,o;return((r=e==null?void 0:e.option)==null?void 0:r.cameraId)===((o=t==null?void 0:t.option)==null?void 0:o.cameraId)}),Re()],z.prototype,"startLocalVideo",1),O([nt(je.TRTC.updateLocalVideo),Ds("video"),Re()],z.prototype,"updateLocalVideo",1),O([Wr("video"),Re()],z.prototype,"stopLocalVideo",1),O([nt(je.TRTC.startScreenShare),$r("screen",()=>!0),Re()],z.prototype,"startScreenShare",1),O([nt(je.TRTC.updateScreenShare),Ds("screen"),Re()],z.prototype,"updateScreenShare",1),O([Re()],z.prototype,"stopScreenShare",1),O([nt(je.TRTC.startRemoteVideo),$r(e=>`v${e.userId}${e.streamType}`,()=>!0),Re({getRemoteId:e=>`${e.userId}_${e.streamType}`})],z.prototype,"startRemoteVideo",1),O([nt(je.TRTC.updateRemoteVideo),Ds(e=>`v${e.userId}${e.streamType}`),Re({getRemoteId:e=>`${e.userId}_${e.streamType}`})],z.prototype,"updateRemoteVideo",1),O([nt(je.TRTC.stopRemoteVideo),K(e=>function(t){return f(this,null,function*(){if(t.userId==="*"){let r=[];return this._room.remotePublishedUserMap.forEach(o=>{this._remoteVideoConfigMap.has(`${o.userId}_main`)&&r.push(this.stopRemoteVideo({streamType:"main",userId:o.userId}).catch(()=>{})),this._remoteVideoConfigMap.has(`${o.userId}_sub`)&&r.push(this.stopRemoteVideo({streamType:"sub",userId:o.userId}).catch(()=>{}))}),Promise.all(r)}return e.call(this,t)})}),Re({getRemoteId:e=>`${e.userId}_${e.streamType}`})],z.prototype,"stopRemoteVideo",1),O([Wr(e=>`v${e.userId}${e.streamType}`)],z.prototype,"_stopRemoteVideo",1),O([nt(...je.TRTC.muteRemoteAudio),Re({getRemoteId:e=>e})],z.prototype,"muteRemoteAudio",1),O([tm(...je.TRTC.setRemoteAudioVolume),h_(200,e=>e),Re({getRemoteId:e=>e})],z.prototype,"setRemoteAudioVolume",1),O([Ld("start"),Ct(e=>{var t;return(t=e.afterStart)==null?void 0:t.call(e)}),$r((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t)),Re({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Su[e.getName()],ignoreLog:e=>e.getName()==="Debug",ignoreErrorLog:e=>e.getName()==="AudioProcessor"})],z.prototype,"startPlugin",1),O([Ld("update"),Ds((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t),{merge:(e,t)=>(ni(e[1],t[1]),e)}),Re({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Iu[e.getName()]})],z.prototype,"updatePlugin",1),O([Ld("stop"),Wr((e,t)=>{if(e.disableRandomCall)return null;let r=e.getGroup(t),o=e.getAlias();return r==="*"?new RegExp(`${o}.*`):o+r}),Re({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Au[e.getName()]})],z.prototype,"stopPlugin",1),O([tm(...je.TRTC.enableAudioVolumeEvaluation)],z.prototype,"enableAudioVolumeEvaluation",1),O([Re()],z.prototype,"getVideoSnapshot",1),O([Re()],z.prototype,"_setCurrentSpeaker",1),O([$r(e=>`a${e.userId}`,()=>!0)],z.prototype,"_startRemoteAudio",1),O([K(e=>function(t){return f(this,null,function*(){return t.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(r=>this._stopRemoteAudio(L(M({},t),{userId:r.userId})).catch(()=>{}))):e.call(this,t)})}),Wr(e=>`a${e.userId}`)],z.prototype,"_stopRemoteAudio",1),O([Wr("room")],z.prototype,"_exitRoom",1),O([Wr("screen")],z.prototype,"_stopScreenShare",1),O([nt(...je.TRTC.sendSEIMessage),Gh({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...e)=>e[0].byteLength})],z.prototype,"sendSEIMessage",1),O([nt(je.TRTC.sendCustomMessage),Gh({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],z.prototype,"sendCustomMessage",1),O([Gr()],z,"create",1),O([nt(je.TRTC.create)],z,"_create",1),O([Gr()],z,"setLogLevel",1),O([Gr()],z,"isSupported",1),O([Gr(),Re()],z,"getPermissions",1),O([Gr()],z,"getCameraList",1),O([Gr()],z,"getMicrophoneList",1),O([Gr()],z,"getSpeakerList",1);var dm=z,_a=dm;var lm=class{constructor(){d(this,"_set",new Set);S.on(A.LEAVE_SUCCESS,this.delete,this),S.on(A.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess,this)}add({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,e||i.roomId,i.sdkAppId,i.useStringRoomId);this._set.add(t)}delete({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,i.roomId||e,i.sdkAppId,i.useStringRoomId);this._set.delete(t)}getKey(i,e,t,r){return`${t}_${e}_${i}_${r}`}isJoined({userId:i,roomId:e,sdkAppId:t,room:r}){return r.scene==="rtc"?!1:this._set.has(this.getKey(i,e,t,r.useStringRoomId))}handleSwitchRoomSuccess({room:i,currentRoomId:e,targetRoomId:t}){i.scene!=="rtc"&&(this._set.delete(this.getKey(i.userId,e,i.sdkAppId,i.useStringRoomId)),this._set.add(this.getKey(i.userId,t,i.sdkAppId,i.useStringRoomId)))}};function II(){return f(this,null,function*(){let s,i;try{let h=yield At();s=h&&h.length}catch(h){}try{let h=yield Rt();i=h&&h.length}catch(h){}let e={microphone:s,camera:i},{isH264EncodeSupported:t,isVp8EncodeSupported:r,isH264DecodeSupported:o,isVp8DecodeSupported:n,isH265EncodeSupported:a,isH265DecodeSupported:c}=this.checkSystemResult.detail,l=Pi.basis(),u={webRTC:l.isWebRTCSupported,getUserMedia:l.isGetUserMediaSupported,webSocket:l.isWebSocketsSupported,screenShare:l.isScreenShareSupported,webAudio:l.isWebAudioSupported,h264Encode:t,h264Decode:o,vp8Encode:r,vp8Decode:n,h265Encode:a,h265Decode:c},m={browser:l.browser,os:l.os,trtc:u,devices:e},p={isWebCodecSupported:l.isWebCodecSupported,isMediaSessionSupported:l.isMediaSessionSupported,isWebTransportSupported:l.isWebTransportSupported};se.uploadEvent({log:`trtcstats-${JSON.stringify(m)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(m)}`),se.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(p)}`,userId:this.userId}),Lu()})}function A_(){return K(s=>{let i=new lm;return function(e,t,r){return f(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 N({code:I.INVALID_OPERATION,message:W({key:H.INVALID_JOIN})});if(this.checkDestroy(),i.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this}))throw new N({code:I.INVALID_OPERATION,message:W({key:H.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}`),S.emit(A.JOIN_START,{room:this,roomId:o,params:e});let n=Et.getEnv();n||(n=Gi.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(La.OLD_CLOUD_LADDER)?n=Gi.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(La.WEBRTC)&&(n=Gi.WEBRTC))),se.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),Pi.checkSystemRequirementsInternal(r).then(a=>{this.checkSystemResult=a,II.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Et.getEnv()&&(yield this.schedule(e,r));let a=yield s.call(this,e,t,r);return this.roomId=o,this._joinedTimestamp=Et.performanceNow(),S.emit(A.JOIN_SUCCESS,{room:this}),r===30&&!e.component&&se.uploadEvent({log:`stat-conv-${Number(hi)}-${location.hostname}`,userId:this.userId}),a}catch(a){throw i.delete({room:this,roomId:o}),S.emit(A.JOIN_FAILED,{room:this,error:a}),a}})}})}var R_=()=>K(s=>function(...i){return f(this,null,function*(){S.emit(A.LEAVE_START,{room:this}),yield s.call(this,...i),S.emit(A.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function C_(){return K(s=>function(...i){let e=s.apply(this,i);return i.forEach(t=>!t.isSubscribed&&t.subscribe(e)),e})}var v_=We(Ze());var Ce={SETUP_SUCCESS:"1",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",RECONNECT_FAILED:"4",SETUP_FAILED:"5",DISCONNECTED:"6",CLOSE:"7",ONLINE:"8"};var Yt={CLIENT_BANNED:9,CHANNEL_SETUP_RESULT:19,CHANNEL_RECONNECT_RESULT:514,JOIN_ROOM_RESULT:20,PEER_JOIN:4134,PEER_LEAVE:4135,STREAM_ADDED:16,STREAM_REMOVED:18,UPLINK_NETWORK_STATS:22,UPDATE_REMOTE_MUTE_STAT:23,PUBLISH_RESULT:4098,PUBLISH_STATE_CHANGE_RESULT:4112,UNPUBLISH_RESULT:4100,SUBSCRIBE_RESULT:4102,UNSUBSCRIBE_RESULT:4104,SUBSCRIBE_CHANGE_RESULT:4106,MUTE_RESULT:4108,UPDATE_OFFER_RESULT:4128,START_PUBLISH_TENCENT_CDN_RES:1286,STOP_PUBLISH_TENCENT_CDN_RES:1288,START_PUBLISH_GIVEN_CDN_RES:777,STOP_PUBLISH_GIVEN_CDN_RES:779,START_MIX_TRANSCODE_RES:781,STOP_MIX_TRANSCODE_RES:783,START_PUBLISH_CDN_STREAM_RES:8196,UPDATE_PUBLISH_CDN_STREAM_RES:8198,STOP_PUBLISH_CDN_STREAM_RES:8200,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772,REBUILD_PEER_CONNECTION_RES:4150,SPC_PUBLISH_RESULT:4146,SPC_SUBSCRIBE_RESULT:4156,ABILITY_STATUS_REPORT_RESULT:4158,SERVER_FIRST_PACKAGE_RECEIVED:5e3,RECEIVE_CUSTOM_MSG:4140,FALLBACK_CODEC:66,SEND_SWITCH_ROOM_RES:4160,SEND_SWITCH_ROOM_SUBED_REQ:4161,UPDATE_NETWORK_TIME_RESULT:5001,CUSTOM_CMD_RES:8220},y_=[Yt.UPDATE_REMOTE_MUTE_STAT,Yt.UPLINK_NETWORK_STATS,Yt.USER_LIST_RES,Yt.MUTE_RESULT,Yt.SERVER_FIRST_PACKAGE_RECEIVED,Yt.RECEIVE_CUSTOM_MSG,Yt.UPDATE_NETWORK_TIME_RESULT],q={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",START_PUBLISH_CDN_STREAM_RES:"start-publish-cdn-stream-res",UPDATE_PUBLISH_CDN_STREAM_RES:"update-publish-cdn-stream-res",STOP_PUBLISH_CDN_STREAM_RES:"stop-publish-cdn-stream-res",USER_LIST_RES:"user-list-res",SWITCH_ROLE_RES:"switch_role_res",MUTE_RESULT:"mute-result",UPDATE_CONSTRAINT_CONFIG_RES:"update-contraint-config-res",REBUILD_PEER_CONNECTION_RES:"rebuild-pc-res",SPC_PUBLISH_RESULT:"spc-publish-result",SPC_SUBSCRIBE_RESULT:"spc-subscribe-result",ABILITY_STATUS_REPORT_RESULT:"ability-status-report",SERVER_FIRST_PACKAGE_RECEIVED:"first-pkg-received",RECEIVE_CUSTOM_MSG:"receive-custom-msg",FALLBACK_CODEC:"fallback-codec",SEND_SWITCH_ROOM_RES:"send-switch-room-res",SEND_SWITCH_ROOM_SUBED_REQ:"send-switch-room-subed-res",UPDATE_NETWORK_TIME_RESULT:"update_network_time_result",CUSTOM_CMD_RES:"custom-cmd-res"},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",START_PUBLISH_CDN_STREAM:"start_publish_cdn_stream",UPDATE_PUBLISH_CDN_STREAM:"update_publish_cdn_stream",STOP_PUBLISH_CDN_STREAM:"stop_publish_cdn_stream",GET_USER_LIST:"get_user_list",SWITCH_ROLE:"change_role",UPDATE_CONSTRAINT_CONFIG:"update_constraint_config",REBUILD_PEER_CONNECTION:"rebuild_pc",READY_TO_RECEIVE_DATA:"ready_to_receive",SPC_JOIN_ROOM:"join/v2",SPC_PUBLISH:"publish/v2",SPC_SUBSCRIBE:"subscribe/v3",ABILITY_STATUS_REPORT:"ability_status_report",RECONNECT_WS:"reconnect",SEND_CUSTOM_MSG:"channel_msg",SWITCH_ROOM:"switch_room",UPDATE_NETWORK_TIME:"update_network_time",CUSTOM_CMD:"abstract_cmd"},b_=new Set([Q.PUBLISH,Q.PUBLISH_CHANGE,Q.PUBLISH_STATE_CHANGE,Q.UNPUBLISH,Q.SUBSCRIBE,Q.SUBSCRIBE_CHANGE,Q.UNSUBSCRIBE,Q.SPC_PUBLISH,Q.SPC_SUBSCRIBE]);var jd=new Set;function N_(s){let i=[...jd.values()].find(e=>e.room.userId===s&&!e.room.isJoined);return i||null}var RI=["autoTest","relayInnerIp","relayOuterIp","mcd","newRelay","clientIp"],CI=0,Bo=class extends v_.default{constructor(e){var r,o,n;super();d(this,"room");d(this,"sdkAppId");d(this,"userId");d(this,"userSig");d(this,"url");d(this,"backupUrl");d(this,"destroyed",!1);d(this,"_socketInUse");d(this,"_socket");d(this,"_backupSocket");d(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,bakRelayIps:[],reportToken:void 0});d(this,"_currentState","DISCONNECTED");d(this,"_isReconnecting",!1);d(this,"_seq",0);d(this,"_log");d(this,"_lastMessageTime",-1);d(this,"_connectStartTime",-1);d(this,"_stopConnectRetry");d(this,"_isFirstConnect",!0);d(this,"bytesSent",0);d(this,"bytesReceived",0);d(this,"keepAlive",!1);d(this,"signalDomainWhenUnifiedProxy");d(this,"stopKeepAliveTimeout");d(this,"rtt",0);this.room=e.room,this.sdkAppId=e.sdkAppId,this.userId=e.userId,this.userSig=e.userSig,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy;let t=((o=(r=this.room.scheduleResult)==null?void 0:r.config)==null?void 0:o.keepAliveClient)||0;(n=this.room.joinParams)!=null&&n.keepAlive&&!t&&(t=1),t-jd.size>0&&this.room.enableSPC&&(this.keepAlive=!0,jd.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=C.createLogger({parent:this.room.getLogger(),id:`ws${++CI}`,userId:this.userId,sdkAppId:this.sdkAppId}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get race(){return this.room.enableSPC&&!this.room.proxy_ws}get urlParam(){let e=`?sdkAppId=${encodeURIComponent(this.sdkAppId)}&userId=${encodeURIComponent(this.userId)}&userSig=${encodeURIComponent(this.userSig)}&keepAlive=${encodeURIComponent(Number(this.keepAlive))}`;this.signalDomainWhenUnifiedProxy&&(e+=`&signalDomain=${encodeURIComponent(this.signalDomainWhenUnifiedProxy)}`);let t=new URLSearchParams(location.search);return RI.forEach(r=>{let o=t.get(`trtc_${r}`);o&&(e+=`&${r}=${encodeURIComponent(o)}`)}),this.race?`${e}&race=1`:e}get _urlWithParam(){return`${this.url}${this.race?"/v2/ws":""}${this.urlParam}`}get _backupUrlWithParam(){return`${this.backupUrl}${this.race?"/v2/ws":""}${this.urlParam}`}get isConnected(){return this._currentState==="CONNECTED"}get isConnecting(){return this._currentState==="CONNECTING"}get isOnline(){return this._currentState==="CONNECTED"&&Date.now()-this._lastMessageTime<12*1e3}connect(){return f(this,arguments,function*(e=10*1e3){if(this.isConnected)return Promise.resolve();this._log.info(`connect to [${this.url}, ${this.backupUrl}] ${this.race?"race":""}${e?` timeout: ${e}`:""} keepAlive: ${Number(this.keepAlive)}`),this.emitConnectionStateChanged("CONNECTING"),this._connectStartTime=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 ts(t),this.unbindAndCloseSocket(this._socketInUse===this._socket?_.BACKUP:_.MAIN),this._isFirstConnect&&(y.addSuccessEvent({key:521720}),this._isFirstConnect=!1),this.emitConnectionStateChanged("CONNECTED")})}connectWS({url:e,timeout:t,isMain:r}){let o=new WebSocket(e);this.bindSocket(o),r?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(r?_.MAIN:_.BACKUP),c(new N({code:I.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===_.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(t){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(t){}this._backupSocket=null}}onclose(e){e.target===this._socketInUse&&(this._log.warn(`${e.target===this._socket?"main":"backup"} is closed code:${e.code} ${e.reason}`),this.emitConnectionStateChanged("DISCONNECTED"),(!e.wasClean||e.code!==1e3)&&this.startReconnection(),this.room.isJoining&&this.emit(Ce.SETUP_FAILED,new N({code:I.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onclose"})))}onerror(e){this._log.error(`${e.target===this._socket?"main":"backup"} error observed`),this.emitConnectionStateChanged("DISCONNECTED"),e.target===this._socketInUse&&(this.unbindAndCloseSocket(_.MAIN),this.unbindAndCloseSocket(_.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(Ce.SETUP_FAILED,new N({code:I.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(e){if(!this.isConnected)return;let{isOnline:t}=this;this._lastMessageTime=Date.now(),t||this.emit(Ce.ONLINE),this.bytesReceived+=cn(e.data);let r=JSON.parse(e.data),{cmd:o,data:n}=r,a=Object.values(Yt),l=Object.keys(Yt)[a.indexOf(o)],u=q[l]||o;switch(y_.includes(o)||(this._log.debug(`received ${o} msg: ${e.data}`),u&&this._log.info(`Received event: [ ${u} ]`)),o){case Yt.CHANNEL_SETUP_RESULT:{if(r.code===0)this._signalInfo.clientIp=n.clientIp,this._signalInfo.signalIp=n.signalInnerIp,n.svrTime&&ba(n.svrTime-new Date().getTime()),this._log.info(`ChannelSetup Success ${x()-this._connectStartTime}`),y.addSuccessEvent({key:521701,cost:x()-this._connectStartTime}),this._connectStartTime=-1,this.room.firewallDetector.resetTimeoutCount(),this.emit(Ce.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let m=new N({code:I.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:r.code,message:W({key:H.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:r.code,errorMsg:r.message}})});this._log.error(`${r.code}, ${r.message}`),this.close(),y.addFailedEvent({key:521701,error:m}),this.emit(Ce.SETUP_FAILED,m)}break}case Yt.JOIN_ROOM_RESULT:{r.code===0&&(this._signalInfo.relayIp=n.relayOuterIp,this._signalInfo.relayInnerIp=n.relayInnerIp,this._signalInfo.bakRelayIps=n.bakRelayIps,this._signalInfo.relayPort=n.relayPort,this._signalInfo.tinyId=r.tinyId,this._signalInfo.endReportExtend=n.endReportExtend,this._signalInfo.reportToken=n.reportToken,this._log.info(`signalIp:${this._signalInfo.signalIp} clientIp:${this._signalInfo.clientIp} relayIp: ${this._signalInfo.relayIp}`)),this.emit(u,{data:r});break}default:this.emit(String(u),{data:r});break}}reGetSignalChannelUrl(){return f(this,null,function*(){try{if(!this.room.joinParams)return;Vt(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(e){}})}startReconnection(){if(!this._socketInUse)return;this._socketInUse.onclose=null,this._socketInUse.close(4011);let e=this._socketInUse===this._socket;this.unbindAndCloseSocket(e?_.MAIN:_.BACKUP),this._socketInUse=null,this.emitConnectionStateChanged("DISCONNECTED"),this.reconnect()}reconnect(){return f(this,null,function*(){if(!this._isReconnecting){if(!this.room.isJoined&&this.keepAlive){this.close();return}this._isReconnecting=!0;try{this._log.warn("reconnect"),yield this.connect();let{roomId:e,useStringRoomId:t}=this.room,{relayIp:r,relayInnerIp:o,relayPort:n}=this._signalInfo,{data:a}=yield this.sendWaitForResponse({command:Q.RECONNECT_WS,data:{roomId:e,useStringRoomId:t,relayInnerIp:o,relayOuterIp:r,relayPort:n},responseCommand:q.CHANNEL_RECONNECT_RESULT});a.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),y.addSuccessEvent({key:521702,cost:x()-this._connectStartTime}),this._connectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(y.addFailedEvent({key:521702,error:a.code}),this._log.warn(`reconnect failed, ${a.code} ${a.message}`),this.room.reJoin())}catch(e){this._log.error(e),this.room.reJoin()}}})}send(e,t={}){if(this.isConnected&&!this.room.isLeft){let r={cmd:e,data:t,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},o=JSON.stringify(r);return this._socketInUse.send(o),b_.has(e)&&this._log.info("send",e,t),this.bytesSent+=cn(o),r.seq}}sendWaitForResponse({command:e,data:t,timeout:r=5e3,responseCommand:o,commandDesc:n,enableLog:a=!0,addReceiveTime:c=!1}){return new Promise((l,u)=>{let m=()=>{clearTimeout(p),u(new N({code:I.API_CALL_ABORTED,message:`${e} aborted due to connection closed`}))};this.once(Ce.CLOSE,m);let p=setTimeout(()=>{this.off(o,h),this.off(Ce.CLOSE,m);let g=new N({code:I.API_CALL_TIMEOUT,message:W({key:H.API_CALL_TIMEOUT,data:{commandDesc:n,command:e}})});a&&this._log.warn(g),u(g)},r),h=g=>{g.data.seq===T&&(clearTimeout(p),this.off(o,h),this.off(Ce.CLOSE,m),c&&(g.data.receiveTime=Date.now()),l(g))};this.on(o,h);let T=this.send(e,t)})}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:r,retries:o=0,retryTimeout:n=0}=e;return Ni({retryFunction:this.sendWaitForResponse,onError:({retry:a,reject:c,error:l})=>{!this.room.isJoined||this.destroyed||l.code===I.API_CALL_ABORTED?c(l):this.isOnline?a():(this._log.warn(`retry ${r} when connected`),this.once(Ce.ONLINE,a))},onRetrying:a=>{this._log.warn(`${t||r} 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"),clearTimeout(this.stopKeepAliveTimeout),jd.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,bakRelayIps:[],endReportExtend:void 0,reportToken:void 0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(_.MAIN),this.unbindAndCloseSocket(_.BACKUP),this.emitConnectionStateChanged("DISCONNECTED"),this.emit(Ce.CLOSE)}destroy(){this.close(),this.destroyed=!0}getBackupRelayIpPair(){var t;let e=(t=this._signalInfo.bakRelayIps)==null?void 0:t.shift();return e&&(e.relayPort=e.relayPort||this._signalInfo.relayPort),e}clearBakRelayIps(){this._signalInfo.bakRelayIps=[]}stopKeepAliveIn(e=3600){if(this.keepAlive){this._log.info(`stopKeepAlive in ${e}s`),this.stopKeepAliveTimeout=setTimeout(()=>{this.keepAlive=!1,this._log.info(`close due to not used ${e}s`),this.close(),this.off(q.JOIN_ROOM_RESULT,t)},e*1e3);let t=r=>{r.data.code===0&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(q.JOIN_ROOM_RESULT,t))};this.on(q.JOIN_ROOM_RESULT,t)}}emitConnectionStateChanged(e){if(e===this._currentState)return;this._log.info(`${this._currentState} -> ${e}`);let t={prevState:this._currentState,state:e};e==="CONNECTING"&&(t.isReconnecting=this._isReconnecting),this.emit(Ce.CONNECTION_STATE_CHANGED,t),this._currentState=e,e==="CONNECTED"?this.emit(Ce.CONNECTED):e==="DISCONNECTED"&&this.emit(Ce.DISCONNECTED)}};O([kt({settings:{retries:1/0,timeout:2e3},onError(e,t){!this.room.isDestroyed&&!this.destroyed&&(this._isFirstConnect&&(y.addFailedEvent({key:521720,error:e}),this._isFirstConnect=!1),this.room.firewallDetector.increaseTimeoutCount(),t())},onRetrying(e,t){this._log.warn(`retrying to connect ${e}`),e>=3&&e%3===0&&this.reGetSignalChannelUrl(),t&&(this._stopConnectRetry=t,(this.room.isDestroyed||this.destroyed)&&t())}})],Bo.prototype,"connect",1);var D_=We(Ze());var um=!1,_t=class{constructor(i){d(this,"userId");d(this,"tinyId");d(this,"_sdpSemantics");d(this,"_isUplink");d(this,"_room");d(this,"_log");d(this,"_signalChannel");d(this,"_isErrorObserved",!1);d(this,"_waitForPeerConnectionConnectedPromise");d(this,"_waitForPeerConnectionConnectedPromiseReject",null);d(this,"_peerConnection",null);d(this,"_emitter",new D_.default);d(this,"_currentState","DISCONNECTED");d(this,"_isReconnecting",!1);d(this,"_reconnectionCount",0);d(this,"_reconnectionTimer",-1);d(this,"_isFirstConnection",!0);d(this,"_prevTime",-1);d(this,"_localAddress");d(this,"_remoteAddress");d(this,"isDestoyed",!1);this.userId=i.userId,this.tinyId=i.tinyId,this._room=i.room,this._sdpSemantics=i.room.sdpSemantics,this._isUplink=i.isUplink,this._log=i.room.getLogger().createChild({id:"n-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=i.signalChannel}beforeConnect(){this._prevTime<0&&(this._prevTime=x())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,y.addSuccessEvent({key:521705,cost:Math.min(x()-this._prevTime,30*1e3)})):this._isReconnecting&&y.addSuccessEvent({key:521706,cost:x()-this._prevTime}),this._prevTime=-1}catch(i){throw this._isFirstConnection?(this._isFirstConnection=!1,y.addFailedEvent({key:521705,error:i})):this._isReconnecting&&this._reconnectionCount>=3&&y.addFailedEvent({key:521706,error:i}),i}}initialize(){let i={iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"};this._peerConnection=new RTCPeerConnection(i),this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this)}close(i){this._log.info("close connection"),this._emitter.emit("closed",i),this._isReconnecting&&this.stopReconnection(),this.closePeerConnection()}destroy(){this.isDestoyed=!0}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 N({code:I.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return ii;let i=null;if(this._isUplink){if(!Pr()||this._peerConnection.getSenders().length===0)return ii;i=this._peerConnection.getSenders()[0].transport}else{if(!hs()||this._peerConnection.getReceivers().length===0)return ii;i=this._peerConnection.getReceivers()[0].transport}return i?i.state:ii}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===be.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),i.target.connectionState===be.FAILED||i.target.connectionState===be.CLOSED){let r=`connection ${i.target.connectionState}. ICE Transport state: ${e}, DTLS Transport state: ${t}`,o=new N({message:r,code:I.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",o)}(i.target.connectionState===be.CONNECTED||i.target.connectionState===be.COMPLETED)&&(this.logSelectedCandidate(),se.logSuccessEvent({userId:this._room.userId,eventType:Oe.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(i){return i===this._currentState?!1:(i==="CONNECTED"&&(this._room.firewallDetector.resetTimeoutCount(),um=!0),S.emit(A.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:i,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:i}),this._currentState=i,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}logSelectedCandidate(){return f(this,null,function*(){if(!this._peerConnection)return;let i=yield this._peerConnection.getStats();for(let[,e]of i)if(Or(e)){let t=i.get(e.localCandidateId),r=i.get(e.remoteCandidateId);t&&(this._log.info(`local candidate: ${t.candidateType} ${t.protocol}:${t.ip||t.address}:${t.port} ${t.networkType||""} ${t.candidateType==="relay"?`relayProtocol:${t.relayProtocol}`:""}`),this._localAddress=`${t.ip||t.address}:${t.port}`),r&&(this._log.info(`remote candidate: ${r.candidateType} ${r.protocol}:${r.ip||r.address}:${r.port}`),this._remoteAddress=`${r.protocol}:${r.ip||r.address}`);break}})}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise?this._waitForPeerConnectionConnectedPromise:(this._waitForPeerConnectionConnectedPromise=new Promise((i,e)=>{if(this._currentState==="CONNECTED")return i();this._waitForPeerConnectionConnectedPromiseReject=e;let t=a=>{a.state==="CONNECTED"&&(clearTimeout(n),o(),i())},r=({room:a})=>{a===this._room&&(clearTimeout(n),o(),e(new N({code:I.API_CALL_ABORTED,message:W({key:H.CONNECTION_ABORTED,data:"leave room"})})))},o=()=>{S.off(A.LEAVE_SUCCESS,r,this),this._emitter.off("connection-state-changed",t,this)},n=setTimeout(()=>{o();let a=new N({code:I.API_CALL_TIMEOUT,message:"connection timeout"});this._room.firewallDetector.increaseTimeoutCount(),e(a)},rn);S.on(A.LEAVE_SUCCESS,r,this),this._emitter.on("connection-state-changed",t,this)}),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally(()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null}),this._waitForPeerConnectionConnectedPromise)}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(Ce.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=Ji()){this._log.warn(`SDK has tried reconnect for ${this._reconnectionCount} times, but all failed, please check your network`),this.stopReconnection();let i=new N({code:this._isUplink?I.UPLINK_RECONNECTION_FAILED:I.DOWNLINK_RECONNECTION_FAILED,message:W({key:this._isUplink?H.UPLINK_RECONNECTION_FAILED:H.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(Ce.CONNECTED,this.reconnect,this),-1)}on(i,e,t){this._emitter.on(i,e,t)}off(i,e,t){this._emitter.off(i,e,t)}getIsReconnecting(){return this._isReconnecting}get isH264(){var i,e;return!!((e=(i=this._peerConnection)==null?void 0:i.remoteDescription)!=null&&e.sdp.includes("H264"))}setOffer(i){var e;return(e=this._peerConnection)==null?void 0:e.setLocalDescription(i)}setAnswer(i){var e;return(e=this._peerConnection)==null?void 0:e.setRemoteDescription(i)}};O([yt(521712,!1)],_t.prototype,"setOffer",1),O([yt(521713,!1)],_t.prototype,"setAnswer",1);var fm=We(pm());var De=function(s){return fm.default.parse(s)},Zt=function(s){return fm.default.write(s)},U_=function(s){let i=De(s);return i.media.forEach(e=>{e.type===_.AUDIO&&e.fmtp.forEach(t=>{t.config+=";sprop-stereo=1;stereo=1"})}),Zt(i)};function V_(s){let i=De(s);return i.media.forEach(e=>{var t,r;if(e.type===_.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 l=c.match(/apt=(\d+)/);l&&l[1]&&o.has(Number(l[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=(r=e.payloads)==null?void 0:r.split(" ").filter(a=>!o.has(Number(a))).join(" ")}}),Zt(i)}function qd(s){return Object.keys(s).filter(i=>s[i])}var $o=class $o extends _t{constructor(e){super(L(M({},e),{isUplink:!1}));d(this,"_flag",0);d(this,"isRobot",!1);d(this,"role","anchor");d(this,"remoteAudioTrack");d(this,"remoteVideoTrack");d(this,"remoteAuxiliaryTrack");d(this,"avPlayerStateSyncManager");d(this,"ssrc",{audio:0,video:0,auxiliary:0});d(this,"_isSDPExchanging",!1);d(this,"_videoCodec");d(this,"fromType");this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=e.remoteAudioTrack||new Ai(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new Ui(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new Po(this._room,this),this.avPlayerStateSyncManager=new lr({log:this._log,audioPlayer:this.remoteAudioTrack.player,videoPlayer:this.remoteVideoTrack.player})}get videoCodec(){var t,r;let e=(r=(t=this._peerConnection)==null?void 0:t.remoteDescription)==null?void 0:r.sdp;return e?e.includes("H264")?"h264":"vp8":this._videoCodec||"h264"}set videoCodec(e){this._videoCodec=e}get subscribeState(){let e={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(this.remoteVideoTrack.mediaType&8?e.smallVideo=!0:e.video=!0),this.remoteAudioTrack.isSubscribed&&(e.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(e.auxiliary=!0),e}get muteState(){return oi(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,r,o;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(r=this.remoteVideoTrack)==null||r.onFlagChanged(),(o=this.remoteAuxiliaryTrack)==null||o.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===_.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.avPlayerStateSyncManager.destroy(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var o,n;let t=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&t!==e&&((o=this.remoteVideoTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),r}onTrack(e){let t=e.streams[0],{track:r}=e,o=t.id===tn?_.MAIN:_.AUXILIARY;this._log.debug(`ontrack ${o} ${r.kind}`);let n=_.AUDIO;r.kind===_.VIDEO&&(n=o===_.MAIN?_.VIDEO:_.AUXILIARY);let a=this.remoteAudioTrack;n===_.VIDEO?a=this.remoteVideoTrack:n===_.AUXILIARY&&(a=this.remoteAuxiliaryTrack),a.setInputMediaStreamTrack(r)}addRRTRLine(e){let t=e.split(`\r
|
|
64
|
+
${r.stack}`),!1}},s};var Vo=new WeakMap;function u_(s){let i=Vo.get(s);i&&(i.forEach(e=>clearTimeout(e)),Vo.delete(s))}function h_(s,i){return K((e,t)=>function(...r){let o=Vo.get(this);o||(o=new Map,Vo.set(this,o));let n=i(...r),a=o.get(n);if(!a||a<=0){e.apply(this,r);let c=setTimeout(()=>{var l;(l=Vo.get(this))==null||l.delete(n)},s);o.set(n,c)}else{clearTimeout(a);let c=window.setTimeout(()=>{var l;e.apply(this,r),(l=Vo.get(this))==null||l.delete(n)},s);o.set(n,c)}})}var p_="trtc-sdk-v5",em="5.15.1-beta.8";function nt(...s){return K((i,e)=>function(...t){try{kd.call(this,s,t,e,this._name)}catch(r){return Promise.reject(r)}return i.apply(this,t)})}function tm(...s){return K((i,e)=>function(...t){try{kd.call(this,s,t,e,this._name)}catch(r){throw r}return i.apply(this,t)})}function kd(s,i,e,t){if(Ie(s))for(let r=0;r<s.length;r++)Pd.call(this,{rule:s[r],value:i[r],key:s[r].name,fnName:e,className:t});else Pd.call(this,{rule:s,value:i[0],key:s.name,fnName:e,className:t})}function Pd({rule:s,value:i,key:e,fnName:t,className:r}){function o(c){return{code:U.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:s,value:i}}}if(E(i)){if(s.required)throw new B(o(5001));if(E(s.defaultValue)){me(s.validate)&&s.validate.call(this,i,e,t,r,this);return}i=s.defaultValue}if(Array.isArray(s.type)){let c=!1;for(let l=0;l<s.type.length;l++)s.type[l]===null&&i===null&&(c=!0),me(s.type[l])&&i instanceof s.type[l]&&(c=!0),ne(s.type[l])&&Pe(i)===s.type[l].toLowerCase()&&(c=!0);if(!c)throw new B({code:U.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:s.type.map(l=>es(l)?Js(l):ne(l)?l:Pe(l))},value:i}})}else if(!E(s.type)&&Pe(i)!==s.type)throw new B(o(5002));if(s.allowEmpty===!1){let c=te(i)&&(i===0||Number.isNaN(i)),l=ne(i)&&i.trim()==="";if(c||l)throw new B(o(5003))}if(s.notLessThanZero&&te(i)&&i<0)throw new B(o(5006));if(!E(s.min)&&te(i)&&i<s.min)throw new B(o(5007));if(!E(s.max)&&te(i)&&i>s.max)throw new B(o(5008));if(ne(s.instanceOf)){if(!i||i._name!==s.instanceOf)throw new B(o(5004))}else if(me(s.instanceOf)&&!(i instanceof s.instanceOf))throw new B(o(5004));if(Array.isArray(s.values)&&!s.values.includes(i))throw new B(o(5005));let{properties:n}=s;dt(n)&&vt(i)&&Object.keys(n).forEach(c=>{Pd.call(this,{rule:n[c],value:i&&i[c],key:`${c}`,fnName:t,className:r})});let{arrayItem:a}=s;dt(a)&&Ie(i)&&i.forEach((c,l)=>{Pd.call(this,{rule:a,value:c,key:`${e}[${l}]`,fnName:t,className:r})}),me(s.validate)&&s.validate.call(this,i,e,t,r,this)}var mI=0;function Re(s={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t,ignoreLog:r,ignoreErrorLog:o}=s;return K((n,a)=>function(...c){var T,g,R;function l(D,j,V){if(V&&V.includes(D))return"hided";if(e){let ae=e(...c);if(c[ae.argIndex]===j)return ae.value}if(j===c||D in c)return j;try{return j instanceof HTMLElement?`id: ${j.id} type:${Pe(j)}`:j instanceof MediaStreamTrack?Xa(j):(JSON.stringify(j),j)}catch(ae){return`type:${Pe(j)}`}}let u=(this==null?void 0:this._log)||C,m=++mI;if(r!=null&&r(...c))return n.apply(this,c);c.length>0?u.info(`${a}() ${m} ${JSON.stringify(c,(D,j)=>l(D,j,["userSig","privateMapKey"]))}`):u.info(`${a}() ${m}`);let p=t?t(...c):Mc[a],h=(o==null?void 0:o(...c))||!1;try{let D=n.apply(this,c),j=x();if(Rr(D)){let V=`${a.includes("Plugin")?`${((g=(T=c[0]).getName)==null?void 0:g.call(T))||""} `:" "}`;return D.then(ae=>(u.info(`${a}() success ${m} ${V}${i.call(this,...c)}`),y.addSuccessEvent({key:p,cost:x()-j}),ae)).catch(ae=>{var ge;ae=B.convertFrom.call(this,ae,a,c.length===1?c[0]:c);let b=ae.extraCode||ae.code,$=(ge=ae.message)!=null&&ge.includes(b)?"":` code:${b}`,P=(ae==null?void 0:ae.code)===U.OPERATION_ABORT;throw h||u[P?"warn":"error"](`${a}() failed ${m} ${V}${i.call(this,...c)} ${ae}${$} params: ${JSON.stringify(c,l)}`),y.addFailedEvent({key:p,error:ae}),ae})}return y.addSuccessEvent({key:p}),D}catch(D){D=B.convertFrom.call(this,D,a);let j=D.extraCode||D.code,V=(R=D.message)!=null&&R.includes(j)?"":` code:${j}`,ae=(D==null?void 0:D.code)===U.OPERATION_ABORT;throw h||u[ae?"warn":"error"](`${a}() failed ${m} ${D}${V} params: ${JSON.stringify(c,l)}`),y.addFailedEvent({key:p,error:D}),D}})}var Ld=s=>K((i,e)=>function(t,r){return f(this,null,function*(){let o=this._plugins.get(t);if(!o)throw this._log.error(`plugin ${String(t)} is not found`),new B({code:U.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});if(me(o.constructor.isSupported)&&!o.constructor.isSupported())throw this._log.error(`plugin ${String(t)} is not supported`),new B({code:U.ENV_NOT_SUPPORTED,message:`plugin ${String(t)} is not supported`,extraCode:5210,fnName:e});return kd.call(this,o.getValidateRule(s),[r],e,"TRTC"),i.call(this,o,r)})});var wd=0,im,ur=class ur{constructor(i){this.core=i;d(this,"log");d(this,"customAudioReferenceMap",new Map);d(this,"audioRefId",0);d(this,"audioContext",Ae());d(this,"localAudioWorkletNode");d(this,"screenAudioWorkletNode");d(this,"mixNode");d(this,"silentNode");wd=wd+1,this.log=i.log.createChild({id:`${this.getAlias()}${wd}`}),this.log.info(`created id=${this.getAlias()}${wd}`),this.installEvent()}static getStartValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,t,r,o){if(!i.room.audioManager.hasAudioTrack&&!i.room.audioManager.hasScreenAudioTrack)throw new B({code:U.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return im||(im=this.doPreload(i)),im}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield sr(this.audioContext,t)}catch(r){this.log.error(`preload audioProcessor failed. ${r}`)}finally{URL.revokeObjectURL(t)}})}getName(){return ur.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(i){switch(i){case"start":return ur.getStartValidateRule(this.core);case"update":return ur.updateValidateRule;case"stop":return ur.stopValidateRule}}start(i){return f(this,null,function*(){var p,h,T,g;let{room:e}=this.core,{sdkAppId:t,userId:r,userSig:o,assetsPath:n=this.core.assetsPath,audioReference:a,processLevel:c,enableDump:l,isLocalAudioNeedAudioProcess:u=!0,isScreenAudioNeedAudioProcess:m=!1}=i;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=u,this.core.room.audioManager.isScreenAudioNeedAudioProcess=m,!n)throw new B({code:U.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload(`${n}/audioProcessor-wasm.js`),u&&!this.localAudioWorkletNode){let{sign:R,status:D,timestamp:j}=yield this.getAuthData(t,r,o);this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",t,r,j,R,D,e)}if(m&&!this.screenAudioWorkletNode){let{sign:R,status:D,timestamp:j}=yield this.getAuthData(t,r,o);this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",t,r,j,R,D,e)}this.mixNode||(this.mixNode=this.audioContext.createGain(),this.mixNode.gain.value=1),this.silentNode||(this.silentNode=this.audioContext.createConstantSource(),this.silentNode.offset.setValueAtTime(0,this.audioContext.currentTime),this.silentNode.start()),(p=this.localAudioWorkletNode)==null||p.port.postMessage({type:"enable"}),(h=this.screenAudioWorkletNode)==null||h.port.postMessage({type:"enable"}),e.audioManager.addAudioProcessor(this.mixNode,this.silentNode,this.localAudioWorkletNode,this.screenAudioWorkletNode),E(a)||a.forEach(R=>{this.customAudioReferenceMap.set(R,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:R,refId:`o-${this.audioRefId++}`})}),E(c)||(T=this.localAudioWorkletNode)==null||T.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:c}}),E(l)||(g=this.localAudioWorkletNode)==null||g.port.postMessage({type:"dump",data:{enable:l}})})}update(i){return f(this,null,function*(){var o,n,a;let{audioReference:e,enableDump:t,processLevel:r}=i;E(e)||(this.customAudioReferenceMap.forEach((c,l)=>{this.customAudioReferenceMap.delete(l),this.core.room.audioManager.updateAudioReference({type:"remove",refId:c})}),e.forEach(c=>{this.customAudioReferenceMap.set(c,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:c,refId:`o-${this.audioRefId++}`})})),E(r)||(o=this.localAudioWorkletNode)==null||o.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:r}}),E(t)||((n=this.localAudioWorkletNode)==null||n.port.postMessage({type:"dump",data:{enable:t}}),(a=this.screenAudioWorkletNode)==null||a.port.postMessage({type:"dump",data:{enable:t}}))})}stop(){return f(this,null,function*(){var e,t;let{room:i}=this.core;(e=this.localAudioWorkletNode)==null||e.port.postMessage({type:"disable"}),(t=this.screenAudioWorkletNode)==null||t.port.postMessage({type:"disable"}),yield i.audioManager.removeAudioProcessor(this.localAudioWorkletNode,this.screenAudioWorkletNode)})}destroy(){this.localAudioWorkletNode&&(this.localAudioWorkletNode.port.onmessage=null),this.screenAudioWorkletNode&&(this.screenAudioWorkletNode.port.onmessage=null),this.uninstallEvent()}getAuthData(i,e,t){return f(this,null,function*(){let r=String(Date.now()).slice(0,-3),{auth:o,sign:n,status:a,message:c}=yield fI({sdkAppId:i,userSig:t,userId:e,timestamp:r});if(!o)throw this.log.info(`audioProcessor: ${e} auth result: ${o}. Message: ${c}`),new B({code:U.INVALID_PARAMETER,message:c});return{sign:n,status:a,timestamp:r}})}initWorkletNode(i,e,t,r,o,n,a,c){i.port.postMessage({type:"init",data:{sdkAppId:String(t),userId:r,timestamp:o,sign:n,status:a}}),i.port.onmessage=l=>{var m;let{data:u}=l;switch(u.type){case"cost":let p=(u==null?void 0:u.value)>10?"info":"debug";this.log[p](`${e==="localAudio"?"":`[${e}] `}avg cost: ${u.value} max: ${u==null?void 0:u.max}(${xs(new Date(u==null?void 0:u.maxCostTimestamp))}) hist: ${(m=u==null?void 0:u.hist)==null?void 0:m.join(" ")}`);return;case"log":this.log[u.logLevel](`${e==="localAudio"?"":`[${e}] `}${u.value}`);return;case"dump":S.emit("265",{room:c,data:u.value,type:e==="localAudio"?"dump":"dump-screen-audio"});return;case"detectEcho":this.log.warn(`${e==="localAudio"?"":`[${e}] `}detect echo: ${os()?Dt():Mt()}`);return}}}handleLocalAudioStarted(i){return f(this,null,function*(){var e;if(!(!this.hitTest(i.room)||((e=this.core.room.scheduleResult.config)==null?void 0:e.audioProcessor)!==!0))try{yield this.core.trtc.startPlugin("AudioProcessor",{sdkAppId:this.core.room.sdkAppId,userId:this.core.room.userId,userSig:this.core.room.userSig}),this.log.warn("audio processor auto start success")}catch(t){this.log.warn(`audio processor auto start failed, error: ${t}`)}})}handleLocalAudioStopped(i){return f(this,null,function*(){var e;!this.hitTest(i.room)||((e=this.core.room.scheduleResult.config)==null?void 0:e.audioProcessor)!==!0||(yield this.core.trtc.stopPlugin("AudioProcessor"))})}installEvent(){this.core.innerEmitter.on("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.on("114",this.handleLocalAudioStopped,this)}uninstallEvent(){this.core.innerEmitter.off("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.off("114",this.handleLocalAudioStopped,this)}hitTest(i){return i===this.core.room}};d(ur,"updateValidateRule",{type:"object"}),d(ur,"stopValidateRule",{type:"object"}),d(ur,"Name","AudioProcessor");var xd=ur;function pI(s,i=_.MAIN){return`https://${Ri[i]||Md(s,i)}/api/v1/audioAiAuth`}function fI(r){return f(this,arguments,function*({sdkAppId:s,userId:i,userSig:e,timestamp:t}){let n=`${pI(s)}?sdkAppId=${s}&userId=${i}&userSig=${e}×tamp=${t}`,a=yield fetch(n),{data:{errCode:c,errMsg:l,sign:u,status:m}}=yield a.json();if(m==="1")return{auth:!0,sign:u,status:m,message:l};let p=$t(s)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",h="Init RTCAudioProcessor failed.",T="";switch(c){case 1:T="Please check your params.";break;case 2:T=`You need to buy packages. Refer to: ${p}`;break;case 3:T="Server is invalid. Please contact our engineer. ";break;case 4:T=`Your packages is not active. Refer to: ${p}`;break;case 5:T=`Your packages is expired. Refer to: ${p}`;break;case 6:T="Your version is not supported.";break}return{auth:!1,status:m,message:l?`${h} Reason: ${l}. ${T}`:`${h}, ${T}`}})}var Ud=0,rm=class{constructor(i,e){d(this,"audioObjectURL");d(this,"player");d(this,"publisher");d(this,"mixInput");this.mixInput=new Eo(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&&(E(i.volume)||(this.volume=i.volume),E(i.loop)||(this.loop=i.loop),E(i.playbackRate)||(this.playbackRate=i.playbackRate))}updateListener(i){if(this.player){if(i.onDurationChange){let{onDurationChange:e}=i;this.player.ondurationchange=t=>{e(t.target.duration)}}if(i.onTimeUpdate){let e=i.onTimeUpdate,{player:t}=this;t.ontimeupdate=()=>{e(t.currentTime,t.duration)}}i.onEnded&&(this.player.onended=i.onEnded)}}reload(i){return f(this,null,function*(){if(i.url){let e=yield da.download(i.url,{retries:3,type:"blob"});this.audioObjectURL&&URL.revokeObjectURL(this.audioObjectURL),this.audioObjectURL=URL.createObjectURL(e),this.player&&this.publisher?(this.player.src=this.audioObjectURL,this.publisher.src=this.audioObjectURL):(this.player=new Audio(this.audioObjectURL),this.player.crossOrigin="anonymous",this.publisher=new Audio(this.audioObjectURL),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher),this.updateListener(i),this.updateSettings(i))}else this.mixInput.replaceSource(i.track)})}reset(){this.seek(0),this.mixInput.connect()}seek(i){this.player&&(i<0&&i>this.player.duration||(this.player.currentTime=i,this.publisher.currentTime=i))}play(){var i,e;return Promise.all([(i=this.player)==null?void 0:i.play(),(e=this.publisher)==null?void 0:e.play()])}pause(){var i,e;(i=this.player)==null||i.pause(),(e=this.publisher)==null||e.pause()}stop(){var i;(i=this.player)==null||i.pause(),this.mixInput.disconnect()}setOperation(i){i==="pause"&&this.pause(),i==="resume"&&(this.pause(),this.play()),i==="stop"&&(this.pause(),this.seek(0))}set volume(i){!this.player||!this.publisher||(this.player.volume=i,this.publisher.volume=i)}set loop(i){!this.player||!this.publisher||(this.player.loop=i,this.publisher.loop=i)}set playbackRate(i){!this.player||!this.publisher||(this.player.playbackRate=i,this.publisher.playbackRate=i)}};function Fo(s,i){if(i&&typeof i!="function")throw new B({code:U.INVALID_PARAMETER,message:`start audioMixer plugin: param ${s} should be a function.`})}var Vi=class Vi{constructor(i){this.core=i;d(this,"log");d(this,"mixedMusicMap",new Map);d(this,"cacheMusicMap",new Map);Ud=Ud+1,this.log=i.log.createChild({id:`${this.getAlias()}${Ud}`}),this.log.info(`created id=${this.getAlias()}${Ud}`)}getName(){return Vi.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return Vi.startValidateRule;case"update":return Vi.updateValidateRule;case"stop":return Vi.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e}=this.core;this.core.validateSourceNode(),this.log.info(`add music source, id: ${i.id} url: ${i.url}, track: ${i.track}`);let{id:t,url:r}=i;if(this.mixedMusicMap.has(t))return;let o=this.cacheMusicMap.get(t);o?i.url?o.reset():(o.mixInput.replaceSource(i.track),o.mixInput.connect()):(o=new rm(i,e.audioManager),this.cacheMusicMap.set(t,o)),o.updateListener(i),o.updateSettings(i);try{yield o.play()}catch(n){yield this.handleAutoPlayFailed(o,i,n)}this.mixedMusicMap.set(t,o),o.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"add",audioReference:o.mixInput.source.node,refId:`ax-${t}`}),this.log.info(`start mix audio track ${t} success.`),y.addEnum({key:502700,value:3}),this.kvUpload(i)})}handleAutoPlayFailed(i,e,t){return f(this,null,function*(){if(t.name==="NotSupportedError")this.log.error(`play failed, try to reload source. error: ${t}`),yield i.reload(e),yield i.play();else if(t.name==="NotAllowedError")if(this.core.room.enableAutoPlayDialog){let r=()=>{var o;(o=i.play())==null||o.finally(()=>{S.off("154",r,this)})};S.on("154",r,this),go()}else this.core.trtc.emit(w.AUTOPLAY_FAILED,{userId:"",mediaType:"audio",resume:()=>f(this,null,function*(){return i.play()})});else throw t})}update(i){return f(this,null,function*(){let{id:e,operation:t,seekFrom:r,playbackRate: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),E(t)||n.setOperation(t),E(r)||n.seek(r),this.kvUpload(i)})}stop(e){return f(this,arguments,function*({id:i}){if(this.mixedMusicMap.has(i)){this.log.info(`remove music source, music id: ${i}`);let t=this.mixedMusicMap.get(i);t!=null&&t.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:t.mixInput.source.node,refId:`ax-${i}`}),t==null||t.stop(),this.mixedMusicMap.delete(i)}i==="*"&&this.destroyAllMusic()})}kvUpload(i){let{track:e,loop:t,volume:r,playbackRate:o,operation:n,seekFrom:a,onTimeUpdate:c,onDurationChange:l,onEnded:u}=i;e&&y.addCount({key:502009}),t&&y.addCount({key:502001}),r&&y.addCount({key:502002}),o&&y.addCount({key:502003}),n&&y.addCount({key:502004}),a&&y.addCount({key:502005}),typeof c!="function"&&y.addCount({key:502007}),typeof u!="function"&&y.addCount({key:502008}),typeof l!="function"&&y.addCount({key:502006})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((i,e)=>{i!=null&&i.mixInput.track&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:i.mixInput.track,refId:e}),this.stop({id:e})})}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}};d(Vi,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(i,e,t){if(i.url&&i.url!=="*"){let r=i.url.split("?")[0],o=["mp3","ogg","wav","flac"],n=r.split(".").pop(),a=o.indexOf(n)>=0,c=r.startsWith("blob"),l=r.startsWith("data");if(!(a||c||l))throw new B({code:U.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new B({code:U.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});Fo("onTimeUpdate",i.onTimeUpdate),Fo("onEnded",i.onEnded),Fo("onDurationChange",i.onDurationChange)}}),d(Vi,"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){Fo("onTimeUpdate",i.onTimeUpdate),Fo("onEnded",i.onEnded),Fo("onDurationChange",i.onDurationChange)}}),d(Vi,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),d(Vi,"Name","AudioMixer");var Vd=Vi;var Fd=0,sm,hr=class hr{constructor(i){this.core=i;d(this,"log");d(this,"audioContext",Ae("denoiser"));d(this,"workletNode");d(this,"config",{enableFarFieldReduce:!1,farFieldReduceThreshold:.5});Fd=Fd+1,this.log=i.log.createChild({id:`${this.getAlias()}${Fd}`}),this.log.info(`created id=${this.getAlias()}${Fd}`)}static startValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0},mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}},validate(e,t,r,o){if(!i.room.audioManager.hasAudioTrack)throw new B({code:U.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return sm||(sm=this.doPreload(i)),sm}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield sr(this.audioContext,t)}catch(r){throw this.log.error("load worklet failed",r),r}finally{URL.revokeObjectURL(t)}})}getName(){return hr.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser"}getValidateRule(i){switch(i){case"start":return hr.startValidateRule(this.core);case"update":return hr.updateValidateRule;case"stop":return hr.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e,schedule:t}=this.core,{assetsPath:r=this.core.assetsPath}=i;if(!r)throw new B({code:U.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload(`${r}/denoiser-wasm${Pu()?"":"-nosimd"}.js`),!this.workletNode){let o=String(Date.now()).slice(0,-3),{auth:n,sign:a,status:c,message:l}=yield gI(t,L(M({},i),{timestamp:o}));if(!n)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${n}. Message: ${l}`),new B({code:U.INVALID_PARAMETER,message:l});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(i.sdkAppId),userId:i.userId,timestamp:o,sign:a,status:c}}),this.workletNode.port.onmessage=u=>{var p;let{data:m}=u;if(m.type==="cost"){let h=(m==null?void 0:m.max)>20?"warn":(m==null?void 0:m.max)>10?"info":"debug";this.log[h](`avg cost: ${m.value} max: ${m==null?void 0:m.max}(${xs(new Date(m==null?void 0:m.maxCostTimestamp))}) hist: ${(p=m==null?void 0:m.hist)==null?void 0:p.join(" ")}`)}else m.type==="log"&&this.log[m.logLevel](`${m.value}`)}}this.updateConfig(i),this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(i){return f(this,null,function*(){this.updateConfig(i)})}stop(){return f(this,null,function*(){if(!this.workletNode)return;let{room:i}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield i.audioManager.removeDenoiser(this.workletNode)})}updateConfig(i){if(!this.workletNode)return;let e=!1;E(i.mode)||(i.mode===0?this.config.enableFarFieldReduce=!1:i.mode===1&&(this.config.enableFarFieldReduce=!0),e=!0),E(i.farFieldReduceThreshold)||(this.config.farFieldReduceThreshold=i.farFieldReduceThreshold,e=!0),e&&this.workletNode.port.postMessage({type:"setConfig",data:this.config})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};d(hr,"updateValidateRule",{type:"object",properties:{mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}}}),d(hr,"stopValidateRule",{type:"object"}),d(hr,"Name","AIDenoiser");var Bd=hr;function gI(o,n){return f(this,arguments,function*(s,{sdkAppId:i,userId:e,userSig:t,timestamp:r}){try{let{data:{errCode:a,errMsg:c,sign:l,status:u}}=yield s.getAbilityConfig(i,s.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:i,userId:e,userSig:t,timestamp:r});if(u==="1")return{auth:!0,sign:l,status:u,message:c};let m=$t(i)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",p="Init RTCAIDenoiser failed.",h="";switch(a){case 1:h="Please check your params.";break;case 2:h=`You need to buy packages. Refer to: ${m}`;break;case 3:h="Server is invalid. Please contact our engineer. ";break;case 4:h=`Your packages is not active. Refer to: ${m}`;break;case 5:h=`Your packages is expired. Refer to: ${m}`;break;case 6:h="Your version is not supported.";break}return{auth:!1,status:u,message:c?`${p} Reason: ${c}. ${h}`:`${p}, ${h}`}}catch(a){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${a}`}}})}var __=We(Ze(),1);var om=class extends __.EventEmitter{constructor(){super();d(this,"observer");d(this,"state","nominal");this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return f(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!fe&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){se.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let t=this.stateNum,r=e[e.length-1];this.state=r.state,(this.stateNum>3||t>3)&&C.info(`${r.source}: ${r.state}`),this.emit("state-changed",{type:r.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(t){se.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},TI=new om,nm=TI;var am=0,la=class la{constructor(i){this.core=i;d(this,"log");d(this,"_seiMessageList",[]);d(this,"_smallSeiMessageList",[]);d(this,"_subStreamSeiMessageList",[]);am++,this.log=i.log.createChild({id:`${this.getAlias()}${am}`}),this.log.info(`[sei] created id=${this.getAlias()}${am}`),this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode({frame:i,mediaType:e}){try{let t=e===8?this._smallSeiMessageList:e===2?this._subStreamSeiMessageList:this._seiMessageList;return Zh({frame:i,seiMessageList:t})}catch(t){this.log.warn(t)}return i}decode({frame:i,track:e}){return Kh({frame:i,onSEI:t=>{t.forEach(r=>{e!=null&&e.userId?this.core.trtc.emit(w.SEI_MESSAGE,{seiPayloadType:r.seiPayloadType,data:r.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"}):this.core.innerEmitter.emit(this.core.INNER_EVENT.SEI_MESSAGE,{room:this.core.room,nalu:r})})}})}destroy(){this.log.debug("destroy"),this.stop(),delete this.core}getValidateRule(i){switch(i){case"start":return{type:"object"};case"update":return{type:"object"};case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:gi?this.encode:Zh,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:gi?this.decode:Kh,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update({buffer:i,options:e}){var o;let t=[e.seiPayloadType,i],r=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(t):(this._seiMessageList.push(t),r&&this._smallSeiMessageList.push(t)),(o=this.core.room.scriptTransformWorker)==null||o.postMessage({type:"sei",data:t,isMain:!e.toSubStream,small:r})}getName(){return la.Name}getAlias(){return"sei"}getGroup(){return"sei"}};d(la,"autoStart",!0),d(la,"Name","SEI");var Hd=la;var EI=0,$d,ua=class ua{constructor(i){this.core=i;d(this,"_core");d(this,"log");d(this,"dialog");this._core=i,this.log=i.log.createChild({id:`${this.getAlias()}${++EI}`}),this.log.info("created")}getName(){return ua.Name}getAlias(){return"dm"}getGroup(){return"dm"}getValidateRule(i){switch(i){case"start":return{name:"StartDebugOptions",required:!1};case"update":return{name:"UpdateDebugOptions",required:!1};case"stop":return{name:"StopDebugOptions",required:!1}}}start(){return f(this,null,function*(){var e;!new URLSearchParams(location.search).has("trtcDebug")&&((e=window.sessionStorage)==null?void 0:e.getItem("TRTC_ENABLE_DEBUG_PLUGIN"))!=="true"||(yield this.openDebugDiaLog())})}update(e){return f(this,arguments,function*({visible:i}){i?yield this.openDebugDiaLog():this.closeDebugDiaLog()})}stop(){this.closeDebugDiaLog()}destroy(){this.stop()}openDebugDiaLog(){return f(this,null,function*(){var i;if(!this.dialog)try{if($d)yield $d;else{let e=new URLSearchParams(location.search).get("trtcDebugDialogPath")||((i=window.sessionStorage)==null?void 0:i.getItem("TRTC_DEBUG_DIALOG_PATH"))||`https://unpkg.com/${p_}@${Ge}/assets/debug-dialog.js`;$d=this._core.fileDownloader.loadScript(e),yield $d}this.dialog=new TRTCDebugDialog(this._core,this.log),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(e){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(e))}})}closeDebugDiaLog(){this.dialog&&(this.dialog.closeDialog(),this.dialog=null)}};d(ua,"Name","Debug"),d(ua,"autoStart",!0);var Wd=ua;var g_=s=>{switch(s){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},Gd=class{constructor(i,e,t){d(this,"trackDoneOB");d(this,"startOB");d(this,"stopOB");d(this,"inputFrameCount",0);d(this,"decodedFrameCount",0);d(this,"type","auto");d(this,"config");d(this,"decoder");d(this,"_decodeSink");let{kvStatManager:r,trtc:o}=i;this.config=t.config,this.trackDoneOB=ue(e,Y.INIT),this.stopOB=ot(),this.startOB=ot(),t.type==="auto"?this.type="webCodecs":this.type=t.type;let n=ot(),a=c=>{let l=this.pipe(e);return n.next("STARTING"),e.log.info(`decoder type: ${this.type}`),he(l,Le(this.stopOB),Se(()=>{},u=>{e.log.error(u),r.addFailedEvent({key:g_(this.type),error:u}),c>4?this.startOB.error(u):this.startOB.next(c+1)})),he(l,ar(1),wh(Kn))};he(this.startOB,Yn(0),Vr(a),Le(this.stopOB),Se(()=>{e.player.setOutput(),n.next("STARTED")},c=>{n.next("FAILED")},()=>{r.addSuccessEvent({key:g_(this.type)}),r.addSuccessEvent({key:504702})}))}mock(i){this._decodeSink?this._decodeSink.error(i):this.startOB.next(0)}close(i){this.stopOB.next(i)}pipe(i){return nr()(e=>f(this,null,function*(){this._decodeSink=e,e.defer(()=>{var r;(r=this.decoder)==null||r.close()});let{type:t}=this;try{switch(t){case"webCodecs":this.decoder=new AudioDecoder({error:r=>{i.log.error(r),e.error(4)},output:r=>{this.decodedFrameCount++,e.next(r),i.player.write(r)}});break;case"wasm":break}this.decoder.configure(this.config)}catch(r){i.log.error(r),e.error(t==="webCodecs"?2:6)}}))}decodeFrame(i){var e;this.inputFrameCount++,((e=this.decoder)==null?void 0:e.state)==="configured"&&this.decoder.decode(new EncodedAudioChunk({data:i.data,timestamp:i.timestamp,type:"key"}))}},SI={type:"object"},ha=class ha{constructor(i){this.core=i;d(this,"log");d(this,"contextMap",new Map);d(this,"decodeProcessorMap",new WeakMap);this.log=i.log.createChild({id:`${this.getAlias()}`})}getAlias(){return ha.Name}getGroup(i){return i.track.userId+i.track.streamType}getName(){return ha.Name}getValidateRule(i){return SI}start(i){let{track:e}=i;this.decodeProcessorMap.set(e,this.decode(i)),this.core.room.audioManager.addDecodeProcessor({processor:({frame:t,track:r})=>this.decodeProcessorMap.has(r)?this.decodeProcessorMap.get(r)({frame:t,track:r}):t,type:3})}decode(i){return({frame:e,track:t})=>{if(t!==i.track)return e;if(this.contextMap.has(t))return this.contextMap.get(t).decodeFrame(e);let r=new Gd(this.core,t,i);return he(r.trackDoneOB,ar(1),Se(()=>{this.core.clearStarted(this,this.getGroup(i)),this.stop({track:t})})),this.contextMap.set(t,r),r.decodeFrame(e)}}stop({track:i}){let e=this.contextMap.get(i);e&&(e.close("stop"),this.contextMap.delete(i),this.contextMap.size===0&&this.core.room.audioManager.removeDecodeProcessor({type:3}))}update(i){let e=this.contextMap.get(i.track);if(e){if(i.type==="mock"){e.mock(10);return}e.close("update"),this.contextMap.set(i.track,new Gd(this.core,i.track,i))}}};d(ha,"Name","TRTCAudioDecoder");var ma=ha;var Jd=class{constructor(){d(this,"log");this.log=C.createLogger({id:"exp"})}call(i,e){return f(this,null,function*(){return me(this[i])?this[i](e):Promise.reject(new N({code:I.INVALID_PARAMETER,message:W({key:H.API_NOT_EXIST,data:{name:i}})}))})}enableAudioFrameEvent(i){return f(this,null,function*(){let{trtcInstance:e,enable:t,userId:r,sampleRate:o=48e3,channelCount:n=1,port:a}=i,{audioManager:c}=e.room,{getPCMAbortCtrlMap:l,audioFrameEventConfigMap:u}=c;if(u.set(r,{enable:t,sampleRate:o,channelCount:n,port:a}),t)if(r==="*")e.room.remotePublishedUserMap.forEach(m=>{if(m.remoteAudioTrack.isAvailable){if(l.get(m.userId))return;let p=c.getPCM(h=>{e.emit(w.AUDIO_FRAME,h)},m.userId);l.set(m.userId,p)}});else{if(l.get(r))return;let m=c.getPCM(p=>{e.emit(w.AUDIO_FRAME,p)},r);l.set(r,m)}else if(r==="*")e.room.remotePublishedUserMap.forEach(m=>{if(m.remoteAudioTrack.isSubscribed){let{userId:p}=m,h=l.get(p);h==null||h.abort("disable"),l.delete(p)}});else{let m=l.get(r);m==null||m.abort("disable"),l.delete(r)}})}resumeRemotePlayer(i){return f(this,null,function*(){if(i.userId==="*"){let t=[];return i.trtcInstance.room.remotePublishedUserMap.forEach(r=>{let{remoteAudioTrack:o,remoteVideoTrack:n,remoteAuxiliaryTrack:a}=r;i.streamType?i.streamType==="main"?(o.isAvailable&&t.push(o.player.resume()),n.isAvailable&&t.push(n.player.resume())):a.isAvailable&&t.push(a.player.resume()):(o.isAvailable&&t.push(o.player.resume()),n.isAvailable&&t.push(n.player.resume()),a.isAvailable&&t.push(a.player.resume()))}),Promise.all(t)}let e=i.trtcInstance.room.remotePublishedUserMap.get(i.userId);if(e)return i.streamType==="main"?Promise.all([e.remoteAudioTrack.player.resume(),e.remoteVideoTrack.player.resume()]):e.remoteAuxiliaryTrack.player.resume()})}pauseRemotePlayer(i){if(i.userId==="*")i.trtcInstance.room.remotePublishedUserMap.forEach(e=>{let{remoteAudioTrack:t,remoteVideoTrack:r,remoteAuxiliaryTrack:o}=e;i.streamType?i.streamType==="main"?(t.isAvailable&&t.player.pause(),r.isAvailable&&r.player.pause(!1)):o.isAvailable&&o.player.pause(!1):(t.isAvailable&&t.player.pause(),r.isAvailable&&r.player.pause(!1),o.isAvailable&&o.player.pause(!1))});else{let e=i.trtcInstance.room.remotePublishedUserMap.get(i.userId);e&&(i.streamType==="main"?(e.remoteAudioTrack.player.pause(),e.remoteVideoTrack.player.pause(!1)):e.remoteAuxiliaryTrack.player.pause(!1))}}requestPictureInPicture(i){let e=[...i.trtcInstance.room.remotePublishedUserMap.values()].find(t=>t.remoteVideoTrack.isAvailable);return e?i.enable?e.remoteVideoTrack.player.enterPictureInPicture():e.remoteVideoTrack.player.exitPictureInPicture():Promise.reject(new N({code:I.INVALID_OPERATION,message:"no available remote video"}))}requestFullScreen(i){let e=[...i.trtcInstance.room.remotePublishedUserMap.values()].find(t=>t.remoteVideoTrack.isAvailable);return e?i.enable?e.remoteVideoTrack.player.enterFullscreen():e.remoteVideoTrack.player.exitFullscreen():Promise.reject(new N({code:I.INVALID_OPERATION,message:"no available remote video"}))}getCurrentPlayingStream(i){var t,r,o,n;let e=i;if(e._currentLiveUserId){let a=(t=e._currentLiveStreamType)!=null?t:"main",c=(r=e._remoteVideoConfigMap.get(`${e._currentLiveUserId}_${a}`))==null?void 0:r.config;if(c)return{userId:e._currentLiveUserId,streamType:a,config:c}}for(let[a,c]of i.room.remotePublishedUserMap){if(c.remoteVideoTrack.isPlayCalled){let l=(o=e._remoteVideoConfigMap.get(`${a}_main`))==null?void 0:o.config;if(l)return{userId:a,streamType:"main",config:l}}if(c.remoteAuxiliaryTrack.isPlayCalled){let l=(n=e._remoteVideoConfigMap.get(`${a}_sub`))==null?void 0:n.config;if(l)return{userId:a,streamType:"sub",config:l}}}return null}switchPlaybackQuality(i){return f(this,null,function*(){var l;let{trtcInstance:e,streamList:t,quality:r}=i,o=e;if(t&&t.length>0&&(o._playbackQualityList=t.map(u=>{var m;return L(M({},u),{streamType:(m=u.streamType)!=null?m:"main"})})),r==="auto"||!r)return;if(!o._playbackQualityList||o._playbackQualityList.length<=0){this.log.warn("switchPlaybackQuality: streamList is empty, please call with streamList first");return}let n=o._playbackQualityList.find(u=>u.name===r);if(!n){this.log.warn(`switchPlaybackQuality: quality "${r}" not found in streamList`);return}let a=this.getCurrentPlayingStream(e);if(this.log.info(`currentPlaying userId: ${a==null?void 0:a.userId}, streamType: ${a==null?void 0:a.streamType}`),!a)return;let c=(l=n.streamType)!=null?l:"main";yield e.startRemoteVideo(L(M({},a.config),{userId:n.userId,streamType:c,option:L(M({},a.config.option),{isLiveStream:!0})})),yield e.stopRemoteVideo(M({},a.config)),o._currentLiveUserId=n.userId,o._currentLiveStreamType=c})}};O([Bf({name:"options",type:"object",required:!0,properties:{enable:{required:!0,type:"boolean"},userId:{required:!0,type:"string"},sampleRate:{type:"number",values:[8e3,16e3,32e3,44100,48e3]},channelCount:{type:"number",values:[1,2]},port:{type:"messageport"}}})],Jd.prototype,"enableAudioFrameEvent",1);var T_=new Jd;var E_=We(Ze(),1);var cm=class extends E_.EventEmitter{constructor(){super();d(this,"states",{});d(this,"permissionChangeHandler");d(this,"log");this.log=C.createLogger({id:"pm"}),this.permissionChangeHandler=()=>{var e,t;this.emit("permission-state-change",{camera:(e=this.states.camera)==null?void 0:e.state,microphone:(t=this.states.microphone)==null?void 0:t.state})}}request(e){return f(this,null,function*(){if(this.log.info(`request ${e.join(", ")}`),e.length===0)return Promise.resolve();(yield navigator.mediaDevices.getUserMedia({video:e.includes("camera"),audio:e.includes("microphone")})).getTracks().forEach(r=>r.stop())})}get(e){return f(this,null,function*(){try{return this.states[e]||(this.states[e]=yield navigator.permissions.query({name:e}),this.states[e].addEventListener("change",this.permissionChangeHandler)),this.log.info(`get ${e} permission state: ${this.states[e].state}`),this.states[e].state}catch(t){return this.log.error(`get ${e} permission failed, error: ${t instanceof Error?t.message:t}`),null}})}destroy(){Object.values(this.states).forEach(e=>{e==null||e.removeEventListener("change",this.permissionChangeHandler)}),this.states={}}},pa=new cm;var S_=0,fa=new Set,Ye=null;ul(em);lo.checkStorage();var z=class z extends I_.EventEmitter{constructor(e,t){super();d(this,"_room");d(this,"_eventListened",new Set);d(this,"_localVideoTrack",null);d(this,"_localAudioTrack",null);d(this,"_localScreenTrack",null);d(this,"_localScreenAudioTrack",null);d(this,"_localVideoConfig",null);d(this,"_localScreenConfig",null);d(this,"_localAudioConfig",null);d(this,"_remoteVideoConfigMap",new Map);d(this,"_remoteAudioConfigMap",new Map);d(this,"_remoteAudioVolumeMap",new Map);d(this,"_remoteAudioMuteMap",new Map);d(this,"_mediaTrackMap",new WeakMap);d(this,"_log",C.createLogger({id:`t${++S_}`}));d(this,"_plugins",new Map);d(this,"_networkQuality",null);d(this,"_speakerId");d(this,"enterRoomParams");d(this,"_enableAutoSwitchWhenRecapturing",!0);d(this,"_autoSubscribeDataChannel",!1);d(this,"_playbackQualityList",[]);d(this,"_currentLiveUserId");d(this,"_currentLiveStreamType","main");this._room=new e(M({logger:this._log,frameWorkType:z.frameWorkType},t)),this._room.videoDecodeFallbackType=t.videoDecodeFallback,pe(t.enableAutoSwitchWhenRecapturing)&&(this._enableAutoSwitchWhenRecapturing=t.enableAutoSwitchWhenRecapturing),this._log.info(`create() ${JSON.stringify(t,(r,o)=>r==="plugins"?o.map(n=>n.Name):o)}`),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(r){return this._room.audioManager.dump(r)}}}),t.plugins&&t.plugins.forEach(r=>{this._use(r,t.assetsPath)}),this._use(Vd,t.assetsPath),this._use(xd,t.assetsPath),this._use(Bd,t.assetsPath),this._use(ma,t.assetsPath),this._use(Wd),t.enableSEI&&wn&&this._use(Hd),this._room.on("audio-volume",r=>{var o,n;!r.find(a=>a.userId==="")&&this._localAudioTrack&&r.push({userId:"",volume:Math.floor(((o=this._localAudioTrack.getInternalAudioLevelAfter3A())!=null?o:this._localAudioTrack.getAudioLevel())*100),floatVolume:(n=this._localAudioTrack.getInternalAudioLevelAfter3A())!=null?n:this._localAudioTrack.getInternalAudioLevel()}),t.volumeType===1&&r.forEach(a=>{var l;let c=a.userId===""?this._localAudioTrack:(l=this.room.remotePublishedUserMap.get(a.userId))==null?void 0:l.remoteAudioTrack;c&&(a.volume=c.dbVolume)}),t.enableDbVolume&&r.forEach(a=>{var l;let c=a.userId===""?this._localAudioTrack:(l=this.room.remotePublishedUserMap.get(a.userId))==null?void 0:l.remoteAudioTrack;c&&(a.volume=c.dbVolume)}),this.emit(w.AUDIO_VOLUME,{result:r.sort((a,c)=>c.volume-a.volume)})}),this._room.videoManager.on("error",r=>{this._log.error(new B({code:U.OPERATION_FAILED,extraCode:5504,message:r.message,originError:r}))}),this._listenEvents(),this._initActiveSpeaker(),l_(this,"trtc")}static create(e){}static _create(e,t){Gf();let r=new z(e,t||{});return fa.add(r),r.__v_skip=!0,r}get room(){return this._room}_listenEvents(){it(this,this._room).add("peer-join",e=>{let{userId:t}=e;this.emit(w.REMOTE_USER_ENTER,{userId:t})}).add("peer-leave",({userId:e,reason:t})=>{this.emit(w.REMOTE_USER_EXIT,{userId:e,reason:t})}).add("banned",e=>{Vt(!0),this._exitRoom().finally(()=>{this.emit(w.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().finally(()=>{this.emit(w.ERROR,B.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(w.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let t=L(M({},e),{uplinkRTT:Math.min(e.uplinkRTT,on),downlinkRTT:Math.min(e.downlinkRTT,on)});this.emit(w.NETWORK_QUALITY,t)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(r=>{it(r,r).add("player-state-changed",o=>{let n=L(M({},o),{userId:e.userId});r.kind===_.VIDEO&&(n.streamType=bt(r.streamType)),this.emit(r.kind===_.AUDIO?w.AUDIO_PLAY_STATE_CHANGED:w.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",o=>{o.getCode()===I.PLAY_NOT_ALLOWED&&this.emit(w.AUTOPLAY_FAILED,{userId:r.userId,mediaType:r.strMediaType,resume:()=>r.player.resume()})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(r=>{Fe(r)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:t})=>{let{userId:r}=t,o=e.audioAvailable,n=e.videoAvailable,{audioAvailable:a,videoAvailable:c}=t;a||this._remoteAudioConfigMap.delete(r),c||this._removeRemoteVideoConfig(r,"main"),t.hasAuxiliary||this._removeRemoteVideoConfig(r,"sub"),n!==c&&(c?this._onVideoAvailable({userId:r,streamType:"main"}):this._onVideoUnavailable({userId:r,streamType:"main"}),this.emit(c?w.REMOTE_VIDEO_AVAILABLE:w.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"main"})),o!==a&&(a?this._onAudioAvailable({userId:r}):this._onAudioUnavailable({userId:r,muteState:t}),this.emit(a?w.REMOTE_AUDIO_AVAILABLE:w.REMOTE_AUDIO_UNAVAILABLE,{userId:r})),e.hasAuxiliary!==t.hasAuxiliary&&(t.hasAuxiliary?this._onVideoAvailable({userId:r,streamType:"sub"}):this._onVideoUnavailable({userId:r,streamType:"sub"}),this.emit(t.hasAuxiliary?w.REMOTE_VIDEO_AVAILABLE:w.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"sub"})),e.hasDatachannel!==t.hasDatachannel&&t.hasDatachannel&&this._onDataChannelAvailable()}).add("sei-message",e=>{this.emit(w.SEI_MESSAGE,L(M({},e),{streamType:bt(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(w.ERROR,new B({code:U.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var o,n,a,c,l,u,m;let t={2:"big",3:"small",7:"sub"},r={rtt:Math.min(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,on),upLoss:((c=this._networkQuality)==null?void 0:c.uplinkLoss)||0,downLoss:((l=this._networkQuality)==null?void 0:l.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((u=e.msg_up_stream_info.msg_audio_status)==null?void 0:u.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((m=e.msg_up_stream_info.msg_audio_status)==null?void 0:m.uint32_audio_level)||0)/Pt},video:e.msg_up_stream_info.msg_video_status.filter(p=>t[p.uint32_video_stream_type]).map(p=>({bitrate:(p.uint32_video_codec_bitrate||0)/1e3,width:p.uint32_video_width,height:p.uint32_video_height,frameRate:p.uint32_video_enc_fps,videoType:t[p.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(p=>({userId:p.msg_user_info.str_identifier,audio:{bitrate:(p.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(p.msg_audio_status.uint32_audio_level||0)/Pt,point2pointDelay:(p.msg_audio_status.uint32_audio_p2p_delay||0)+(p.msg_audio_status.uint32_audio_cache_ms||0),jitterBufferDelay:p.msg_audio_status.uint32_audio_cache_ms||0},video:p.msg_video_status.map(h=>({bitrate:(h.uint32_video_codec_bitrate||0)/1e3,width:h.uint32_video_width,height:h.uint32_video_height,frameRate:h.uint32_video_dec_fps,videoType:t[h.uint32_video_stream_type],point2pointDelay:(h.uint32_video_p2p_delay||0)+(h.uint32_video_cache_ms||0),jitterBufferDelay:h.uint32_video_cache_ms||0,codec:h.uint32_video_codec}))}))};this.emit(w.STATISTICS,r)}).add("custom-message",e=>{this.emit(w.CUSTOM_MESSAGE,e)}).add("layerData",e=>this.emit(w.LAYER_DATA,e)).add("first-video-frame",e=>{this.emit(w.FIRST_VIDEO_FRAME,L(M({},e),{streamType:bt(e.streamType)}))}).add("audio-frame",e=>{this.emit(w.AUDIO_FRAME,e)}).add("data-channel-message",e=>{var o,n,a,c,l;let{data:t}=e;if(t.sender==="")return;let r={segmentId:(o=t.payload)==null?void 0:o.roundid,speakerUserId:t.sender,sourceText:(n=t.payload)==null?void 0:n.text,translationTexts:(a=t.payload)==null?void 0:a.translate_msg,timestamp:(c=t.payload)==null?void 0:c.start_utc_ms,isCompleted:(l=t.payload)==null?void 0:l.end,robotId:t.robotid};r.sourceText!==""&&this.emit(w.REALTIME_TRANSCRIBER_MESSAGE,r)}).add("asr-robot-peer-join",e=>{this.emit(w.REALTIME_TRANSCRIBER_STATE_CHANGED,{state:"started",roomId:this.room.roomId,transcriberRobotId:e.userId})}).add("asr-robot-peer-leave",e=>{this.emit(w.REALTIME_TRANSCRIBER_STATE_CHANGED,{state:"stopped",roomId:this.room.roomId,transcriberRobotId:e.userId})}),it(this,Ne).add("audioInputAdded",e=>{this.emit(w.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(w.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(w.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(w.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>f(this,null,function*(){if(this.emit(w.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Ye&&Ye.deviceId===sn){let t=(yield xr()).find(r=>r.deviceId===sn);t&&Ye.groupId!==t.groupId&&(Ye=t,this.emit(w.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}})).add("audioOutputRemoved",e=>f(this,null,function*(){this.emit(w.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield xr())[0];if(!t||!Ye||Ye.groupId===t.groupId)return;let r=Ye.deviceId===e.deviceId,o=Ye.deviceId===sn&&Ye.deviceId===t.deviceId;(r||o)&&(Ye=t,this.emit(w.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))})),it(this,pa).add("permission-state-change",e=>{this.emit(w.PERMISSION_STATE_CHANGE,e)}),this.room.enableSEI&&this.on(w.SEI_MESSAGE,e=>{var r;let t=(r=this.room.remotePublishedUserMap.get(e.userId))==null?void 0:r.remoteVideoTrack;t&&t.updateAlphaRenderInfo(e)})}getNetworkTime(){return Wi()}use(e){let t,r;return"plugin"in e?(t=e.plugin,r=e.assetsPath):t=e,t.Name==="Chorus"&&(this.room.enableChorus=!0),this._use(t,r)}_use(e,t){let r=this._plugins.get(e.Name);if(r)return this._log.warn("duplicate install plugin",e.Name),r;let o=new e(d_.call(this,{TRTC:z,room:this._room,assetsPath:t,errorModule:{RtcError:B,ErrorCode:U,CoreErrorCode:I,ErrorCodeDictionary:Ut}}));return this._plugins.set(e.Name,o),o.__v_skip=!0,e.autoStart&&this.startPlugin(e.Name),o}enterRoom(e){return f(this,null,function*(){var c,l;this.enterRoomParams=e;let{scene:t="rtc",enableAutoPlayDialog:r=!0,autoReceiveAudio:o=!0,autoReceiveVideo:n=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!ne(e.proxy)&&e.proxy.turnServer&&((l=(c=this._room).setTurnServer)==null||l.call(c,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=r,this._room.autoReceiveAudio=o,this._room.autoReceiveVideo=n,pe(e.preferHW)&&(this._room.preferHW=e.preferHW),e.playoutDelay&&(this._room.playoutDelay=e.playoutDelay),e.jitterBufferDelay&&(this._room.jitterBufferDelay=e.jitterBufferDelay);let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:e.role==="audience"?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,enableDataChannel:this._plugins.has("RealtimeTranscriber"),frameWorkType:e.frameWorkType,component:e.component,language:e.language,priority:e.priority,useVp8:e.useVp8,useH265:e.useH265||!1,keepAlive:e.keepAlive};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(a,t,z.frameWorkType),this._checkTrackToPublish(),nm.start()})}exitRoom(){return f(this,null,function*(){return yield this._exitRoom()})}switchRoom(e){return f(this,null,function*(){if(this.room.isSwitchRoomSupported())try{this._clearRemoteTracks(),yield this._room.switchRoom(e)}catch(t){if(t instanceof Qo&&(t.code===I.API_CALL_TIMEOUT||t.code===I.SWITCH_ROOM_FAILED))this._log.warn(`switchRoom ${t.code===I.API_CALL_TIMEOUT?"timeout":"failed"}, fallback to exitRoom() and enterRoom()`),yield this._rejoinRoom(e);else throw t}else yield this._rejoinRoom(e)})}_rejoinRoom(e){return f(this,null,function*(){yield this.exitRoom();let t=M(M({},this.enterRoomParams),e);yield this.enterRoom(t)})}_clearRemoteTracks(){new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(e=>{this._stopRemoteAudio({userId:e}).catch(()=>{})}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let t=e.includes("main")?"main":"sub",r=e.split(`_${t}`)[0];r&&this._stopRemoteVideo({userId:r,streamType:t}).catch(()=>{})}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),u_(this),this._room.remotePublishedUserMap.forEach(e=>{Fe(e.remoteAudioTrack),Fe(e.remoteVideoTrack),Fe(e.remoteAuxiliaryTrack)})}switchRole(e,t){return f(this,null,function*(){t!=null&&t.privateMapKey&&(this._room.privateMapKey=t.privateMapKey),t!=null&&t.latencyLevel&&(this._room.latencyLevel=t.latencyLevel),yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){this._plugins.forEach(e=>{var t;return(t=e.destroy)==null?void 0:t.call(e)}),this._plugins.clear(),Fe(this),this.removeAllListeners(),this._room.destroy(),fa.delete(this),fa.size===0&&nm.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),S.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return f(this,arguments,function*(e={publish:!0}){if(this._localAudioTrack){this._log.warn("local audio is already started");return}let{publish:t=!0,mute:r,muteKeepVolumeDetection:o,option:n}=e,a=new wt(this._room.audioManager),c={},l={muted:!0};n&&(E(n.microphoneId)?E(n.audioTrack)||(c.customSource=n.audioTrack):c.deviceId=n.microphoneId,n&&te(n.captureVolume)&&a.setCaptureVolume(n.captureVolume),E(n.profile)||(ne(n.profile)?Pa[n.profile]&&a.setProfile(Pa[n.profile]):a.setProfile(n.profile)),te(n.earMonitorVolume)&&(l.muted=!(n.earMonitorVolume>0),l.volume=n.earMonitorVolume),E(n.echoCancellation)||(a.profile.echoCancellation=n.echoCancellation),E(n.noiseSuppression)||(a.profile.noiseSuppression=n.noiseSuppression),E(n.autoGainControl)||(a.profile.autoGainControl=n.autoGainControl),pe(this._enableAutoSwitchWhenRecapturing)&&(a.enableAutoSwitchWhenRecapturing=this._enableAutoSwitchWhenRecapturing)),a.on("5",u=>{this.emit(w.ERROR,new B({code:U.DEVICE_ERROR,extraCode:5309,messageParams:{error:u}}))}),a.on("2",u=>{this.emit(w.DEVICE_CHANGED,{type:"microphone",action:"active",device:u})}),a.on("4",u=>{let m;u.error&&(m=B.convertFrom(u.error)),this.emit(w.PUBLISH_STATE_CHANGED,L(M({},u),{error:m}))}),a.on("6",()=>{}),this._listenOutputTrackChanged(a),this._speakerId&&a.setAudioOutput(this._speakerId),yield a.capture(c),E(r)||a.setMute(r,o),it(a,a).add("player-state-changed",u=>{this.emit(w.AUDIO_PLAY_STATE_CHANGED,L(M({},u),{userId:""}))}),t&&this._room.isJoined&&this._room.publish(a).catch(()=>{}),this._localAudioTrack=a,this._room.capturedLocalMainAudioTrack=a,this._localAudioConfig=L(M({},e),{publish:t}),yield this._updateAudioPlayOption({playOption:l,track:a}),S.emit("113",{userId:"",room:this.room})})}updateLocalAudio(e){return f(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:r,muteKeepVolumeDetection:o,option:n}=e,a={};n&&(n.microphoneId?yield this._localAudioTrack.switchDevice(n.microphoneId):E(n.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(n.audioTrack)),E(n.captureVolume)||this._localAudioTrack.setCaptureVolume(n.captureVolume),E(n.earMonitorVolume)||(a.muted=!(n.earMonitorVolume>0),a.volume=n.earMonitorVolume),yield this._localAudioTrack.update3A(n)),this._room.isJoined&&!E(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),E(r)||this._localAudioTrack.setMute(r,o),yield this._updateAudioPlayOption({playOption:a,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),ni(this._localAudioConfig,e)})}stopLocalAudio(){return f(this,null,function*(){this._localAudioTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),S.emit("114",{userId:"",room:this.room}),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),Fe(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null,delete this._room.capturedLocalMainAudioTrack)})}startLocalVideo(){return f(this,arguments,function*(e={publish:!0,view:null,capture:!0}){var p,h;if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:t,publish:r=!0,capture:o=!0,mute:n,option:a}=e,c=r,l=new ze(this._room.videoManager),u={},m={};a&&(pe(a.avoidCropping)&&(l.avoidCropping=a.avoidCropping),a.cameraId?u.deviceId=a.cameraId:E(a.useFrontCamera)?E(a.videoTrack)||(u.customSource=a.videoTrack):u.facingMode=a.useFrontCamera?_.FACING_MODE_USER:_.FACING_MODE_ENVIRONMENT,E(a.retryWhenExactFailed)||(u.retryWhenExactFailed=a.retryWhenExactFailed),a.qosPreference&&(u.contentHint=na(a.qosPreference)),E(a.profile)||(ne(a.profile)?ti[a.profile]&&l.setProfile(ti[a.profile]):l.setProfile(a.profile)),E(a.fillMode)||(m.objectFit=a.fillMode),E(a.mirror)||(m.mirror=a.mirror),E(a.small)||(E(a.smallMode)||(this._room.smallMode=a.smallMode),pe(a.small)&&a.small===!1?l.stopSmall():l.updateSmallConfig(wo(a.small,!0))),E(a.rotation)||l.setRotation(a.rotation),pe(this._enableAutoSwitchWhenRecapturing)&&(l.enableAutoSwitchWhenRecapturing=this._enableAutoSwitchWhenRecapturing)),l.once("first-video-frame",T=>{this.emit(w.FIRST_VIDEO_FRAME,L(M({},T),{streamType:bt(T.streamType)}))}),l.on("5",T=>{this.emit(w.ERROR,new B({code:U.DEVICE_ERROR,extraCode:5308,messageParams:{error:T}}))}),l.on("2",T=>{this.emit(w.DEVICE_CHANGED,{type:"camera",action:"active",device:T})}),l.on("4",T=>{let g;T.error&&(g=B.convertFrom(T.error)),this.emit(w.PUBLISH_STATE_CHANGED,L(M({},T),{error:g}))}),l.on("6",()=>{}),this._listenOutputTrackChanged(l),o?yield l.capture(u):(p=l.manager)==null||p.changeInput(l),E(n)||(yield l.setMute(n)),it(l,l).add("player-state-changed",T=>{this.emit(w.VIDEO_PLAY_STATE_CHANGED,L(M({},T),{userId:"",streamType:"main"}))}).add("video-size-changed",T=>{this.emit(w.VIDEO_SIZE_CHANGED,L(M({},T),{streamType:bt(T.streamType)}))}),c&&this._room.isJoined&&(this._localScreenTrack&&((h=this._localScreenConfig)==null?void 0:h.publish)&&this._localScreenConfig.streamType==="main"?(c=!1,this._log.warn("main stream is already published, local video track will not publish")):this._room.publish(l).catch(()=>{})),this._localVideoTrack=l,this._room.capturedLocalMainVideoTrack=l,this._localVideoConfig=L(M({},e),{view:t,publish:c,capture:o}),yield this._updateVideoPlayOption({view:t,playOption:m,track:l})})}updateLocalVideo(e){return f(this,null,function*(){var m,p,h,T;if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:r=!0,mute:o,capture:n,option:a,forcePublish:c=!1}=e,l=r||c,u={};if(this._localVideoConfig.capture)n!==!1?a!=null&&a.cameraId?yield this._localVideoTrack.switchDevice(a==null?void 0:a.cameraId):E(a==null?void 0:a.useFrontCamera)?E(a==null?void 0:a.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(a==null?void 0:a.videoTrack)):yield this._localVideoTrack.switchDevice(a!=null&&a.useFrontCamera?_.FACING_MODE_USER:_.FACING_MODE_ENVIRONMENT):this._localVideoTrack.stopCapture();else if(n){let g={};g.deviceId=(a==null?void 0:a.cameraId)||((m=this._localVideoConfig.option)==null?void 0:m.cameraId),g.facingMode=a!=null&&a.useFrontCamera||(p=this._localVideoConfig.option)!=null&&p.useFrontCamera?_.FACING_MODE_USER:_.FACING_MODE_ENVIRONMENT,g.customSource=(a==null?void 0:a.videoTrack)||((h=this._localVideoConfig.option)==null?void 0:h.videoTrack),yield this._localVideoTrack.capture(g)}a&&(E(a.profile)||(ne(a.profile)?ti[a.profile]&&this._localVideoTrack.setProfile(ti[a.profile]):this._localVideoTrack.setProfile(a.profile),(!a.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(a.cameraId||a.useFrontCamera?_.FACING_MODE_USER:_.FACING_MODE_ENVIRONMENT))&&(yield this._localVideoTrack.applyProfile())),E(a.fillMode)||(u.objectFit=a.fillMode),E(a.mirror)||(u.mirror=a.mirror),E(a.rotation)||this._localVideoTrack.setRotation(a.rotation),a.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(na(a.qosPreference)),E(a.small)||(pe(a.small)&&!a.small?this._localVideoTrack.stopSmall():this._localVideoTrack.updateSmallConfig(wo(a.small,!0)))),this._room.isJoined&&E(l)&&this._localVideoConfig.publish&&n&&!this._localVideoConfig.capture&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._room.isJoined&&((l!=null?l:this._localVideoConfig.publish)||c?!(this._localScreenTrack&&((T=this._localScreenConfig)==null?void 0:T.publish)&&this._localScreenConfig.streamType==="main")||c?this._room.publish(this._localVideoTrack).catch(()=>{}):(l=!1,this._log.warn("main stream is already published, local video track will not publish")):this._room.unpublish(this._localVideoTrack).catch(()=>{})),E(o)||(yield this._localVideoTrack.setMute(o)),yield this._updateVideoPlayOption({view:t,playOption:u,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),ni(this._localVideoConfig,L(M({},e),{publish:l}))})}stopLocalVideo(){return f(this,null,function*(){var e;this._localVideoTrack&&(this._room.isJoined&&((e=this._localVideoConfig)!=null&&e.publish)&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),Fe(this._localVideoTrack),this._localVideoTrack=null,delete this._room.capturedLocalMainVideoTrack,this._localVideoConfig=null)})}startScreenShare(){return f(this,arguments,function*(e={publish:!0,view:null}){var h,T,g;if(this._localScreenTrack){this._log.warn("screen share is already started");return}let{view:t=null,publish:r=!0,muteSystemAudio:o,option:n}=e,a=r,c=new xt(this._room.videoManager);c.on("4",R=>{let D;R.error&&(D=B.convertFrom(R.error)),this.emit(w.PUBLISH_STATE_CHANGED,L(M({},R),{error:D}))}),c.once("first-video-frame",R=>{this.emit(w.FIRST_VIDEO_FRAME,L(M({},R),{streamType:bt(R.streamType)}))}),this._listenOutputTrackChanged(c),e.streamType==="main"&&(c.mediaType=4);let l=null,u={},m={};n&&(E(n.profile)||(ne(n.profile)?ka[n.profile]&&c.setProfile(ka[n.profile]):c.setProfile(n.profile)),n.systemAudio&&(u.systemAudio=!0,u.echoCancellation=n.echoCancellation,u.noiseSuppression=n.noiseSuppression,u.autoGainControl=n.autoGainControl),E(n.fillMode)||(m.objectFit=n.fillMode),n.videoTrack&&(u.videoTrack=n.videoTrack),n.audioTrack&&(u.audioTrack=n.audioTrack),n.captureElement&&(u.captureElement=n.captureElement),n.preferDisplaySurface&&(u.preferDisplaySurface=n.preferDisplaySurface),n.qosPreference&&(u.contentHint=na(n.qosPreference)));let p=yield c.capture(u);if(c.mediaTrack.addEventListener(_.ENDED,()=>{this._stopScreenShare(),this.emit(w.SCREEN_SHARE_STOPPED)}),p.getAudioTracks()[0]){l=new ys(this._room.audioManager);let R=p.getAudioTracks()[0];(h=e.option)!=null&&h.systemAudio&&!((T=e.option)!=null&&T.audioTrack)&&(l.sourceTrack=R),yield l.setInputMediaStreamTrack(R),pe(o)&&l.mediaTrack&&(l.mediaTrack.enabled=!o),this._speakerId&&l.setAudioOutput(this._speakerId)}if(it(c,c).add("player-state-changed",R=>{this.emit(w.VIDEO_PLAY_STATE_CHANGED,L(M({},R),{userId:"",streamType:"sub"}))}),a&&this._room.isJoined){let R=this._localVideoTrack&&((g=this._localVideoConfig)==null?void 0:g.publish);!(e.streamType==="main"&&R)?this._room.publish(c).catch(()=>{}):(a=!1,this._log.warn("main stream is already published, screen share main will not publish")),l&&(this._checkScreenAudioEchoCancellation(c,l),this._room.publish(l).catch(()=>{}))}this._localScreenTrack=c,this._room.capturedLocalAuxVideoTrack=c,this._localScreenAudioTrack=l,this._localScreenConfig=L(M({},e),{view:t,publish:a}),yield this._updateVideoPlayOption({view:t,playOption:m,track:c})})}updateScreenShare(e){return f(this,null,function*(){var l,u;if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:r,muteSystemAudio:o,option:n}=e,a=r,c={};if(n){if(E(n.fillMode)||(c.objectFit=n.fillMode),n.qosPreference){let m=na(n.qosPreference);this._localScreenTrack.setContentHint(m)}n.videoTrack&&this._localScreenTrack.setInputMediaStreamTrack(n.videoTrack),n.audioTrack&&this._localScreenAudioTrack&&this._localScreenAudioTrack.setInputMediaStreamTrack(n.audioTrack)}if(this._room.isJoined&&!E(a)){if(a&&!this._localScreenConfig.publish){let m=this._localVideoTrack&&((l=this._localVideoConfig)==null?void 0:l.publish);!(this._localScreenConfig.streamType==="main"&&m)?this._room.publish(this._localScreenTrack).catch(()=>{}):(a=!1,this._log.warn("main stream is already published, screen share main will not publish")),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch(()=>{})}if(this._localScreenConfig.publish&&!a){let m=[this._localScreenTrack];this._localScreenAudioTrack&&m.push(this._localScreenAudioTrack),m.forEach(p=>this._room.unpublish(p).catch(()=>{}))}}(u=this._localScreenAudioTrack)!=null&&u.mediaTrack&&pe(o)&&(this._localScreenAudioTrack.mediaTrack.enabled=!o),yield this._updateVideoPlayOption({view:t,playOption:c,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),ni(this._localScreenConfig,L(M({},e),{publish:a}))})}stopScreenShare(){return f(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return f(this,null,function*(){let{view:t,userId:r,streamType:o,option:n}=e,a=`${r}_${o}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${r}, streamType:${o}`);return}let c=this._room.remotePublishedUserMap.get(r);if(!c)return;let l={},u=o==="main"?c.remoteVideoTrack:c.remoteAuxiliaryTrack,m=this._bindRemoteVideoTrackEvents(u);this._listenOutputTrackChanged(u),n&&(E(n.fillMode)||(l.objectFit=n.fillMode),E(n.mirror)||(l.mirror=n.mirror),E(n.poster)||(l.poster=n.poster),l.canvasRender=n.canvasRender,o==="main"&&!E(n.small)&&(!c.remoteVideoTrack.isSubscribing&&!c.remoteVideoTrack.isSubscribed&&c.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,u.user)),E(n.draggable)||u.setDraggable(n.draggable)),l.isLiveStream=!!this._playbackQualityList.find(p=>p.userId===r&&p.streamType===o),yield this._room.subscribe(u),yield this._enableVideoDecodeFallback(u,o),yield this._updateVideoPlayOption({view:t,playOption:l,track:u}),this._emitTrackEvent(u),this._remoteVideoConfigMap.set(a,{config:e,handlers:m}),n&&!E(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:u,view:t,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:n==null?void 0:n.viewRoot}),l.isLiveStream&&(this._currentLiveUserId=r,this._currentLiveStreamType=o)})}updateRemoteVideo(e){return f(this,null,function*(){var D,j;let{view:t,userId:r,streamType:o,option:n,mute:a}=e,c=`${r}_${o}`,l=this._remoteVideoConfigMap.get(c);if(!l||!this._room.remotePublishedUserMap.has(r))return;let u={};n&&(E(n.fillMode)||(u.objectFit=n.fillMode),E(n.mirror)||(u.mirror=n.mirror));let m=null,p=this._room.remotePublishedUserMap.get(r);if(o==="main"&&(p!=null&&p.muteState.hasVideo)&&(m=p.remoteVideoTrack),o==="sub"&&(p!=null&&p.muteState.hasAuxiliary)&&(m=p.remoteAuxiliaryTrack),!m)return;let{config:h}=l;o==="main"&&n&&!E(n.small)&&this._room.changeType(n.small,m.user),n&&!E(n.draggable)&&m.setDraggable(n.draggable),n&&(pe(n.pictureInPicture)&&(n.pictureInPicture?yield m.player.enterPictureInPicture():yield m.player.exitPictureInPicture()),pe(n.fullScreen)&&(n.fullScreen?yield m.player.enterFullscreen():yield m.player.exitFullscreen())),pe(a)&&(m.ignoreUpdatePlayingState=!0,a?(yield m.player.pause(),yield this.room.unsubscribe(m)):(yield this.room.subscribe(m),yield m.player.resume(!0))),yield this._updateVideoPlayOption({view:t,playOption:u,track:m,prevConfig:h}),ni(h,e);let T=E(n==null?void 0:n.receiveWhenViewVisible)?(D=h.option)==null?void 0:D.receiveWhenViewVisible:n.receiveWhenViewVisible,g=E(t)?h.view:t,R=E(n==null?void 0:n.viewRoot)?(j=h.option)==null?void 0:j.viewRoot:n.viewRoot;this._observeView({remoteTrack:m,view:g,receiveWhenViewVisible:T,viewRoot:R})})}stopRemoteVideo(e){return f(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,t=!0){return f(this,null,function*(){let r=[],o=this._room.remotePublishedUserMap.get(e.userId);if(o){let{muteState:n,remoteVideoTrack:a,remoteAuxiliaryTrack:c}=o;e.streamType==="main"&&(a.stop(),n.hasVideo&&r.push(a)),e.streamType==="sub"&&(c.stop(),n.hasAuxiliary&&r.push(c))}for(let n of r)t&&(delete n.ignoreUpdatePlayingState,yield this._room.unsubscribe(n),this._mediaTrackMap.delete(n.outMediaTrack));this._removeRemoteVideoConfig(e.userId,e.streamType)})}_removeRemoteVideoConfig(e,t){let r=`${e}_${t}`,o=this._remoteVideoConfigMap.get(r);if(o&&(o.observer&&o.observer.disconnect(),o.handlers)){let n=this._room.remotePublishedUserMap.get(e);if(n){let a=t==="main"?n.remoteVideoTrack:n.remoteAuxiliaryTrack;this._unbindRemoteVideoTrackEvents(a,o.handlers)}}this._remoteVideoConfigMap.delete(r)}_bindRemoteVideoTrackEvents(e){let t={onEnterPIP:()=>f(this,null,function*(){yield e.player.enterPIPPromise,this.emit(w.PICTURE_IN_PICTURE_STATE_CHANGED,{streamType:bt(e.streamType),userId:e.userId,isPictureInPicture:!0,pictureInPictureWindow:e.player.pipWindow})}),onLeavePIP:()=>{this.emit(w.PICTURE_IN_PICTURE_STATE_CHANGED,{streamType:bt(e.streamType),userId:e.userId,isPictureInPicture:!1})},onEnterFullScreen:()=>{this.emit(w.FULL_SCREEN_STATE_CHANGED,{streamType:bt(e.streamType),userId:e.userId,isFullScreen:!0})},onLeaveFullScreen:()=>{this.emit(w.FULL_SCREEN_STATE_CHANGED,{streamType:bt(e.streamType),userId:e.userId,isFullScreen:!1})},onDecodeFailed:()=>{this.emit(w.ERROR,new B({code:U.OPERATION_FAILED,extraCode:5507,message:"video decode failed"}))},onVideoSizeChanged:r=>{this.emit(w.VIDEO_SIZE_CHANGED,L(M({},r),{streamType:bt(r.streamType)}))}};return e.player.on(G.ENTER_PICTURE_IN_PICTURE,t.onEnterPIP),e.player.on(G.LEAVE_PICTURE_IN_PICTURE,t.onLeavePIP),e.player.on(G.ENTER_FULL_SCREEN,t.onEnterFullScreen),e.player.on(G.LEAVE_FULL_SCREEN,t.onLeaveFullScreen),e.on("decode-failed",t.onDecodeFailed),e.on("video-size-changed",t.onVideoSizeChanged),t}_unbindRemoteVideoTrackEvents(e,t){e.player.off(G.ENTER_PICTURE_IN_PICTURE,t.onEnterPIP),e.player.off(G.LEAVE_PICTURE_IN_PICTURE,t.onLeavePIP),e.player.off(G.ENTER_FULL_SCREEN,t.onEnterFullScreen),e.player.off(G.LEAVE_FULL_SCREEN,t.onLeaveFullScreen),e.off("decode-failed",t.onDecodeFailed),e.off("video-size-changed",t.onVideoSizeChanged)}muteRemoteAudio(e,t){return f(this,null,function*(){this._remoteAudioMuteMap.set(e,t);try{if(e==="*")if(t)yield this._stopRemoteAudio({userId:e});else{let r=[...this._room.remotePublishedUserMap.values()];for(let o of r)o.muteState.hasAudio&&!this._remoteAudioConfigMap.has(o.userId)&&this.room.isJoined&&(yield this._startRemoteAudio({userId:o.userId}))}else t?yield this._stopRemoteAudio({userId:e}):!this._remoteAudioConfigMap.has(e)&&this.room.isJoined&&(yield this._startRemoteAudio({userId:e}))}catch(r){throw r.code!==U.OPERATION_ABORT&&this._remoteAudioMuteMap.delete(e),r}})}setRemoteAudioVolume(e,t){if(e==="*"){this._remoteAudioVolumeMap.set("*",t),this._remoteAudioVolumeMap.forEach((o,n)=>this._remoteAudioVolumeMap.set(n,t));let r=[...this._room.remotePublishedUserMap.values()];for(let o of r)this._remoteAudioVolumeMap.set(o.userId,t),o.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:o.remoteAudioTrack})}else if(e){let r=this._room.remotePublishedUserMap.get(e);this._remoteAudioVolumeMap.set(e,t),r&&r.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:r.remoteAudioTrack})}}startPlugin(e,t){return f(this,null,function*(){return e.start(t)})}updatePlugin(e,t){return f(this,null,function*(){return e.update(t)})}stopPlugin(e,t){return f(this,null,function*(){return e.stop(t)})}enableAudioVolumeEvaluation(e=2e3,t=!1){this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,r){if(this.listeners(e).includes(t))return this;if(this._log.debug("on",e),super.on(e,t,r),this._eventListened.add(e),this.listeners(w.AUDIO_FRAME).length>0){let{audioFrameEventConfigMap:o}=this.room.audioManager;o.get("")||o.set("",{enable:!0}),this._localAudioTrack&&this.room.audioManager.handleLocalTrackStarted({userId:"",room:this.room})}return e==="realtime-transcriber-message"&&this._room.subscribeDataChannel(),this}emit(e,...t){try{t_.has(e)||this._log.debug(`emit ${e} ${JSON.stringify(t)}`)}catch(r){}return super.emit(e,...t)}off(e,t,r){if(this._log.debug("off",e),e==="*"?(this._eventListened.clear(),this.removeAllListeners()):super.off(e,t,r),(e==="realtime-transcriber-message"||e==="*")&&this.listeners("realtime-transcriber-message").length===0&&this._room.unsubscribeDataChannel(),(e===z.EVENT.AUDIO_FRAME||e==="*")&&this.listeners(z.EVENT.AUDIO_FRAME).length===0){let{getPCMAbortCtrlMap:o}=this.room.audioManager;o.forEach(n=>{n==null||n.abort("off")}),o.clear()}return this}getAudioTrack(e={userId:"",streamType:"main"}){let t,r=null,o="main",n=!1;if(ne(e)?t=e:(t=e.userId,n=e.processed===!0,e.streamType&&(o=e.streamType)),t){let a=this._room.remotePublishedUserMap.get(t);a&&(r=a.remoteAudioTrack)}else r=o==="sub"?this._localScreenAudioTrack:this._localAudioTrack;return r?n&&r.outMediaTrack&&r.outMediaTrack!==r.mediaTrack?r.outMediaTrack.clone():r.mediaTrack:null}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:t="",streamType:r="main",processed:o=!1}=e,n=null;if(t==="")r==="main"&&this._localVideoTrack&&(n=this._localVideoTrack),r==="sub"&&this._localScreenTrack&&(n=this._localScreenTrack);else{let a=this._room.remotePublishedUserMap.get(t);a&&(n=r==="main"?a.remoteVideoTrack:a.remoteAuxiliaryTrack)}return n?o&&n.outMediaTrack&&n.outMediaTrack!==n.mediaTrack?n.outMediaTrack.clone():n.mediaTrack:null}getVideoSnapshot(e={}){let{userId:t,streamType:r="main"}=e;if(t){let o=this._room.remotePublishedUserMap.get(t);if(r==="main"&&(o!=null&&o.muteState.hasVideo))return o.remoteVideoTrack.getVideoFrame();if(r==="sub"&&(o!=null&&o.muteState.hasAuxiliary))return o.remoteAuxiliaryTrack.getVideoFrame()}else{if(r==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(r==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(e){var t,r;this._speakerId=e,(t=this._localAudioTrack)==null||t.setAudioOutput(e),(r=this._localScreenAudioTrack)==null||r.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(o=>o.remoteAudioTrack.setAudioOutput(e))}setCurrentSpeaker(e){return f(this,null,function*(){(yield xr()).forEach(r=>{r.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(w.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}),Ye=r)}),this._log.warn(`the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: ${gt}/en/TRTC.html#.setCurrentSpeaker`)})}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return f(this,null,function*(){var a;let{userId:t}=e;if(this._remoteAudioConfigMap.has(t)){this._log.warn(`remote audio has already started. userId:${t}`);return}let r=this._room.remotePublishedUserMap.get(t);if(!r)return;let o={},n=r.remoteAudioTrack;n.on("decode-failed",c=>{this.emit(w.ERROR,new B({code:U.OPERATION_FAILED,extraCode:5508,message:"audio decode failed"}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId);try{let c=(a=this._remoteAudioVolumeMap.get(t))!=null?a:this._remoteAudioVolumeMap.get("*"),l=te(c)?c:100;o.volume=l,this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(n),he(ue(n,"decode-failed"),Le(ue(n,Y.INIT)),Se(()=>{this.startPlugin(ma.Name,{track:n,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:o,track:n}),S.emit("115",{userId:t,room:this.room}),n.outMediaTrack&&this.room.audioManager.updateAudioReference({type:"add",audioReference:n.outMediaTrack,refId:`ra-${t}`})}catch(c){throw this._remoteAudioConfigMap.delete(t),c}this._emitTrackEvent(n)})}_stopRemoteAudio(e,t=!0){return f(this,null,function*(){let r=this._room.remotePublishedUserMap.get(e.userId);r&&(r.remoteAudioTrack.stop(),r.muteState.hasAudio&&t&&(yield this._room.unsubscribe(r.remoteAudioTrack)),this._mediaTrackMap.delete(r.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete(`${e.userId}`),S.emit("116",{userId:e.userId,room:this.room}),this.room.audioManager.updateAudioReference({type:"remove",refId:`ra-${e.userId}`})})}_enableVideoDecodeFallback(e,t){let r=this._room.videoDecodeFallbackType;if(!r||!this._plugins.has("TRTCVideoDecoder"))return;e.log.debug("remote video will fall back when decode failed",e.id);let o;he(ue(e,"decode-failed"),Le(ue(e,Y.INIT)),ta(()=>{this._room.downlinkVideoCodec!=="h265"&&this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:r})}),Ss(ue(e,"decode-downgrade-state-changed")),Se(n=>{o=n.state,this.emit(w.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,L(M({},n),{streamType:t,userId:e.userId}))},n=>{e.log.error("fallback",n)},()=>{o==="STARTED"&&e.log.info("fallback complete")}))}_updateVideoPlayOption(n){return f(this,arguments,function*({view:e,playOption:t,track:r,prevConfig:o}){if(r.setMirror(t.mirror),E(e)&&o&&o.view&&!js(t)){let a=Xs(o.view);a.length>0&&(yield r.play(a,t))}if(!E(e)){let a=Xs(e);a.length>0?yield r.play(a,t):r.stop()}})}_updateAudioPlayOption(o){return f(this,arguments,function*({playOption:e={},track:t,prevConfig:r}){if(!t.isPlayCalled)try{yield t.play(null,e)}catch(n){}if(E(e.muted)||t.setPlayerMute(e.muted),E(e.volume)||t.setAudioVolume(e.volume/100),t instanceof wt&&t.mediaTrack){let n=e.muted===!1&&!E(e.volume)&&e.volume>0?"add":"remove";this.room.audioManager.updateAudioReference({type:n,audioReference:t.mediaTrack,refId:"em"})}else if(t instanceof Ai){let n=e.muted?0:e.volume;if(E(n))return;this.room.audioManager.updateAudioReference({type:"updateVolume",refId:`ra-${t.userId}`,volume:e.volume})}})}_listenOutputTrackChanged(e){e.listeners("output-media-track-changed").length===0&&e.on("output-media-track-changed",()=>this._emitTrackEvent(e,!1))}_emitTrackEvent(e,t=!0){let r=e.isRemote?e.userId:"";e.outMediaTrack&&(t&&this._mediaTrackMap.get(e.outMediaTrack)===r||(this._mediaTrackMap.set(e.outMediaTrack,r),this.emit(w.TRACK,{userId:r,streamType:bt(e.streamType),track:e.outMediaTrack,sourceTrack:e.mediaTrack})))}_checkTrackToPublish(){var t,r,o;let e=[];if((t=this._localAudioConfig)!=null&&t.publish&&this._localAudioTrack&&e.push(this._localAudioTrack),(r=this._localVideoConfig)!=null&&r.publish&&this._localVideoTrack&&e.push(this._localVideoTrack),(o=this._localScreenConfig)!=null&&o.publish&&(this._localScreenTrack&&e.push(this._localScreenTrack),this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack),this._checkScreenAudioEchoCancellation(this._localScreenTrack,this._localScreenAudioTrack)),e.length!==0)return Promise.all(e.map(n=>this._room.publish(n).catch(()=>{})))}_observeView({remoteTrack:e,view:t,receiveWhenViewVisible:r,viewRoot:o}){if(E(t)||E(r))return;let n=this._remoteVideoConfigMap.get(`${e.userId}_${bt(e.streamType)}`);if(!n)return;let a=n.observer||void 0;if(t===null||Ie(t)&&t.length===0||!r){a==null||a.disconnect(),e.isSubscribed||(this._log.info("_observeView observer disconnect, resubscribe",e.userId,e.strMediaType),this._room.subscribe(e).catch(()=>{}));return}let l=n.visibleViewMap||new Map,u=-1;(!a||a.root!==o)&&(a==null||a.disconnect(),l.clear(),a=new IntersectionObserver(p=>{p.forEach(h=>{l.set(h.target,h.isIntersecting),e.log.info(`view ${h.target.id} is${h.isIntersecting?"":" not"} visible`)}),clearTimeout(u),u=window.setTimeout(()=>{[...l.values()].find(T=>T)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:o}));let m=new Set(Xs(t));l.forEach((p,h)=>{m.has(h)||(a.unobserve(h),l.delete(h))}),m.forEach(p=>{l.set(p,!0),a.observe(p)}),a.takeRecords().forEach(p=>{l.set(p.target,p.isIntersecting)}),n.visibleViewMap=l,n.observer=a}_exitRoom(){return f(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),this._clearRemoteTracks()})}_stopScreenShare(){return f(this,null,function*(){var e,t;if(this._localScreenTrack){if(this._room.isJoined){let r=[];(e=this._localScreenConfig)!=null&&e.publish&&r.push(this._localScreenTrack),this._localScreenAudioTrack&&r.push(this._localScreenAudioTrack),yield Promise.all(r.map(o=>this._room.unpublish(o).catch(()=>{})))}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(((t=this._localScreenAudioTrack.trackSettings)==null?void 0:t.echoCancellation)===!1&&this.stopPlugin("AudioProcessor"),this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),Fe(this._localScreenTrack),this._localScreenTrack=null,delete this._room.capturedLocalAuxVideoTrack,this._localScreenConfig=null}})}_checkScreenAudioEchoCancellation(e,t){return f(this,null,function*(){var o,n;if(!e||!t)return;let r=(o=e.trackSettings)==null?void 0:o.displaySurface;if(((n=t.trackSettings)==null?void 0:n.echoCancellation)===!1&&(r==="monitor"||r==="browser"&&e.isShareCurrentTab)){this._log.warn("echoCancellation of screen audio track is disable. Try starting audioProcessor plugin");try{yield this.startPlugin("AudioProcessor",{sdkAppId:Number(this.room.sdkAppId),userId:this._room.userId,userSig:this.room.userSig,isScreenAudioNeedAudioProcess:!0,isLocalAudioNeedAudioProcess:!1})}catch(a){this._log.warn("start audioProcessor plugin failed: ",a)}}})}_onLocalTrackCaptured({track:e}){e.kind==="audio"&&(!Ye||Ao(Ye))&&(this._initActiveSpeaker(),S.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return f(this,null,function*(){if(Ye&&!Ao(Ye))this.emit(w.DEVICE_CHANGED,{type:"speaker",action:"active",device:Ye});else{let e=yield xr();e[0]&&!Ao(e[0])?(Ye=e[0],this.emit(w.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):S.on("102",this._onLocalTrackCaptured,this)}})}_onAudioAvailable({userId:e}){let t=this._remoteAudioMuteMap.has(e)?this._remoteAudioMuteMap.get(e):this._remoteAudioMuteMap.get("*");(t===!1||this._room.autoReceiveAudio&&!t)&&this._doStartRemoteAudio({userId:e}).catch(()=>{})}_onVideoAvailable({userId:e,streamType:t}){if(!this._room.autoReceiveVideo)return;let r=this._room.remotePublishedUserMap.get(e);if(r){let o=t==="main"?r.remoteVideoTrack:r.remoteAuxiliaryTrack,n=[o];this._room.autoReceiveAudio&&r.remoteAudioTrack.isAvailable&&n.push(r.remoteAudioTrack),this._room.subscribe(...n).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(()=>{})}_onDataChannelAvailable(){if(this.listeners("realtime-transcriber-message").length>0)return this._room.subscribeDataChannel()}sendSEIMessage(e,t){var o;let r=this._plugins.get("SEI");r&&(r.update({buffer:e,options:L(M({seiPayloadType:243},t),{small:!!((o=this._localVideoTrack)!=null&&o.small)})}),y.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,r;(r=(t=this._room).sendCustomMessage)==null||r.call(t,e),y.addCount({key:500001,useUV:!0})}callExperimentalAPI(e,t){return f(this,null,function*(){return this._log.info(`callExperimentalAPI(${e}, ${JSON.stringify(t)})`),T_.call(e,M({trtcInstance:this},t))})}static setLogLevel(e,t){C.setLogLevel(e),E(t)||(t?C.enableUploadLog():C.disableUploadLog())}static isSupported(){return wc(z.frameWorkType)}static getPermissions(r){return f(this,arguments,function*({request:e=!0,types:t=["camera","microphone"]}){e&&(yield pa.request(t).catch(a=>{var c;return C.error(`getPermissions request failed, error: ${(c=a==null?void 0:a.message)!=null?c:a}`)}));let[o,n]=yield Promise.all([pa.get("camera"),pa.get("microphone")]);return{camera:o,microphone:n}})}static getCameraList(e=!0){return Rt(e)}static getMicrophoneList(e=!0){return At(e)}static getSpeakerList(e=!0){return xr(e)}static setCurrentSpeaker(e){return f(this,null,function*(){if(fe&&(e===vs.SPEAKER||e===vs.HEADSET)){let r=yield z.getMicrophoneList(),o="";if(r.forEach(n=>{n.label===e&&(o=n.deviceId)}),!o)return;fa.forEach(n=>f(null,null,function*(){n._localAudioTrack&&(yield n.updateLocalAudio({option:{microphoneId:o}}))}));return}(yield xr()).forEach(r=>{r.deviceId===e&&(fa.forEach(o=>{o._setCurrentSpeaker(e),o.emit(w.DEVICE_CHANGED,{type:"speaker",action:"active",device:r})}),Ye=r)})})}static _addKVStat({type:e,key:t,value:r,base:o,useUV:n,version:a,max:c}){switch(a&&(us.version=a),e){case"count":us.addCount({key:t,useUV:n});break;case"enum":us.addEnum({key:t,value:r,useUV:n});break;case"number":us.addNumber({key:t,value:r,split:o,max:c});break}}get localVideoTrack(){return this._localVideoTrack}get localScreenTrack(){return this._localScreenTrack}get localScreenAudioTrack(){return this._localScreenAudioTrack}};d(z,"VERSION",em),d(z,"_loggerManager",C),d(z,"EVENT",w),d(z,"ERROR_CODE",U),d(z,"TYPE",vs),d(z,"frameWorkType",30),O([Re({replaceArg:e=>({argIndex:0,value:{name:"plugin"in e?e.plugin.Name:e.Name,assetsPath:"assetsPath"in e?e==null?void 0:e.assetsPath:"default"}})})],z.prototype,"use",1),O([nt(je.TRTC.enterRoom),$r("room",([e],[t])=>(e.roomId||e.strRoomId)===(t.roomId||t.strRoomId)&&e.userId===t.userId&&e.sdkAppId===t.sdkAppId),K(e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)}),Re()],z.prototype,"enterRoom",1),O([Re()],z.prototype,"exitRoom",1),O([nt(je.TRTC.switchRoom),Re(),or()],z.prototype,"switchRoom",1),O([nt(je.TRTC.switchRole),Ds("room",{merge:(e,t)=>t}),Re()],z.prototype,"switchRole",1),O([Re()],z.prototype,"destroy",1),O([nt(je.TRTC.startLocalAudio),$r("audio",([e],[t])=>{var r,o;return((r=e==null?void 0:e.option)==null?void 0:r.microphoneId)===((o=t==null?void 0:t.option)==null?void 0:o.microphoneId)}),Re()],z.prototype,"startLocalAudio",1),O([nt(je.TRTC.updateLocalAudio),Ds("audio",{debounce:{delay:200,getKey:()=>`${S_}-localAudio`,isNeedToDebounce:e=>{var t;return!E((t=e.option)==null?void 0:t.captureVolume)}}}),Re()],z.prototype,"updateLocalAudio",1),O([Wr("audio"),Re()],z.prototype,"stopLocalAudio",1),O([nt(je.TRTC.startLocalVideo),$r("video",([e],[t])=>{var r,o;return((r=e==null?void 0:e.option)==null?void 0:r.cameraId)===((o=t==null?void 0:t.option)==null?void 0:o.cameraId)}),Re()],z.prototype,"startLocalVideo",1),O([nt(je.TRTC.updateLocalVideo),Ds("video"),Re()],z.prototype,"updateLocalVideo",1),O([Wr("video"),Re()],z.prototype,"stopLocalVideo",1),O([nt(je.TRTC.startScreenShare),$r("screen",()=>!0),Re()],z.prototype,"startScreenShare",1),O([nt(je.TRTC.updateScreenShare),Ds("screen"),Re()],z.prototype,"updateScreenShare",1),O([Re()],z.prototype,"stopScreenShare",1),O([nt(je.TRTC.startRemoteVideo),$r(e=>`v${e.userId}${e.streamType}`,()=>!0),Re({getRemoteId:e=>`${e.userId}_${e.streamType}`})],z.prototype,"startRemoteVideo",1),O([nt(je.TRTC.updateRemoteVideo),Ds(e=>`v${e.userId}${e.streamType}`),Re({getRemoteId:e=>`${e.userId}_${e.streamType}`})],z.prototype,"updateRemoteVideo",1),O([nt(je.TRTC.stopRemoteVideo),K(e=>function(t){return f(this,null,function*(){if(t.userId==="*"){let r=[];return this._room.remotePublishedUserMap.forEach(o=>{this._remoteVideoConfigMap.has(`${o.userId}_main`)&&r.push(this.stopRemoteVideo({streamType:"main",userId:o.userId}).catch(()=>{})),this._remoteVideoConfigMap.has(`${o.userId}_sub`)&&r.push(this.stopRemoteVideo({streamType:"sub",userId:o.userId}).catch(()=>{}))}),Promise.all(r)}return e.call(this,t)})}),Re({getRemoteId:e=>`${e.userId}_${e.streamType}`})],z.prototype,"stopRemoteVideo",1),O([Wr(e=>`v${e.userId}${e.streamType}`)],z.prototype,"_stopRemoteVideo",1),O([nt(...je.TRTC.muteRemoteAudio),Re({getRemoteId:e=>e})],z.prototype,"muteRemoteAudio",1),O([tm(...je.TRTC.setRemoteAudioVolume),h_(200,e=>e),Re({getRemoteId:e=>e})],z.prototype,"setRemoteAudioVolume",1),O([Ld("start"),Ct(e=>{var t;return(t=e.afterStart)==null?void 0:t.call(e)}),$r((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t)),Re({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Su[e.getName()],ignoreLog:e=>e.getName()==="Debug",ignoreErrorLog:e=>e.getName()==="AudioProcessor"})],z.prototype,"startPlugin",1),O([Ld("update"),Ds((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t),{merge:(e,t)=>(ni(e[1],t[1]),e)}),Re({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Iu[e.getName()]})],z.prototype,"updatePlugin",1),O([Ld("stop"),Wr((e,t)=>{if(e.disableRandomCall)return null;let r=e.getGroup(t),o=e.getAlias();return r==="*"?new RegExp(`${o}.*`):o+r}),Re({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Au[e.getName()]})],z.prototype,"stopPlugin",1),O([tm(...je.TRTC.enableAudioVolumeEvaluation)],z.prototype,"enableAudioVolumeEvaluation",1),O([Re()],z.prototype,"getVideoSnapshot",1),O([Re()],z.prototype,"_setCurrentSpeaker",1),O([$r(e=>`a${e.userId}`,()=>!0)],z.prototype,"_startRemoteAudio",1),O([K(e=>function(t){return f(this,null,function*(){return t.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(r=>this._stopRemoteAudio(L(M({},t),{userId:r.userId})).catch(()=>{}))):e.call(this,t)})}),Wr(e=>`a${e.userId}`)],z.prototype,"_stopRemoteAudio",1),O([Wr("room")],z.prototype,"_exitRoom",1),O([Wr("screen")],z.prototype,"_stopScreenShare",1),O([nt(...je.TRTC.sendSEIMessage),Gh({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...e)=>e[0].byteLength})],z.prototype,"sendSEIMessage",1),O([nt(je.TRTC.sendCustomMessage),Gh({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],z.prototype,"sendCustomMessage",1),O([Gr()],z,"create",1),O([nt(je.TRTC.create)],z,"_create",1),O([Gr()],z,"setLogLevel",1),O([Gr()],z,"isSupported",1),O([Gr(),Re()],z,"getPermissions",1),O([Gr()],z,"getCameraList",1),O([Gr()],z,"getMicrophoneList",1),O([Gr()],z,"getSpeakerList",1);var dm=z,_a=dm;var lm=class{constructor(){d(this,"_set",new Set);S.on(A.LEAVE_SUCCESS,this.delete,this),S.on(A.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess,this)}add({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,e||i.roomId,i.sdkAppId,i.useStringRoomId);this._set.add(t)}delete({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,i.roomId||e,i.sdkAppId,i.useStringRoomId);this._set.delete(t)}getKey(i,e,t,r){return`${t}_${e}_${i}_${r}`}isJoined({userId:i,roomId:e,sdkAppId:t,room:r}){return r.scene==="rtc"?!1:this._set.has(this.getKey(i,e,t,r.useStringRoomId))}handleSwitchRoomSuccess({room:i,currentRoomId:e,targetRoomId:t}){i.scene!=="rtc"&&(this._set.delete(this.getKey(i.userId,e,i.sdkAppId,i.useStringRoomId)),this._set.add(this.getKey(i.userId,t,i.sdkAppId,i.useStringRoomId)))}};function II(){return f(this,null,function*(){let s,i;try{let h=yield At();s=h&&h.length}catch(h){}try{let h=yield Rt();i=h&&h.length}catch(h){}let e={microphone:s,camera:i},{isH264EncodeSupported:t,isVp8EncodeSupported:r,isH264DecodeSupported:o,isVp8DecodeSupported:n,isH265EncodeSupported:a,isH265DecodeSupported:c}=this.checkSystemResult.detail,l=Pi.basis(),u={webRTC:l.isWebRTCSupported,getUserMedia:l.isGetUserMediaSupported,webSocket:l.isWebSocketsSupported,screenShare:l.isScreenShareSupported,webAudio:l.isWebAudioSupported,h264Encode:t,h264Decode:o,vp8Encode:r,vp8Decode:n,h265Encode:a,h265Decode:c},m={browser:l.browser,os:l.os,trtc:u,devices:e},p={isWebCodecSupported:l.isWebCodecSupported,isMediaSessionSupported:l.isMediaSessionSupported,isWebTransportSupported:l.isWebTransportSupported};se.uploadEvent({log:`trtcstats-${JSON.stringify(m)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(m)}`),se.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(p)}`,userId:this.userId}),Lu()})}function A_(){return K(s=>{let i=new lm;return function(e,t,r){return f(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 N({code:I.INVALID_OPERATION,message:W({key:H.INVALID_JOIN})});if(this.checkDestroy(),i.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this}))throw new N({code:I.INVALID_OPERATION,message:W({key:H.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}`),S.emit(A.JOIN_START,{room:this,roomId:o,params:e});let n=Et.getEnv();n||(n=Gi.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(La.OLD_CLOUD_LADDER)?n=Gi.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(La.WEBRTC)&&(n=Gi.WEBRTC))),se.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),Pi.checkSystemRequirementsInternal(r).then(a=>{this.checkSystemResult=a,II.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Et.getEnv()&&(yield this.schedule(e,r));let a=yield s.call(this,e,t,r);return this.roomId=o,this._joinedTimestamp=Et.performanceNow(),S.emit(A.JOIN_SUCCESS,{room:this}),r===30&&!e.component&&se.uploadEvent({log:`stat-conv-${Number(hi)}-${location.hostname}`,userId:this.userId}),a}catch(a){throw i.delete({room:this,roomId:o}),S.emit(A.JOIN_FAILED,{room:this,error:a}),a}})}})}var R_=()=>K(s=>function(...i){return f(this,null,function*(){S.emit(A.LEAVE_START,{room:this}),yield s.call(this,...i),S.emit(A.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function C_(){return K(s=>function(...i){let e=s.apply(this,i);return i.forEach(t=>!t.isSubscribed&&t.subscribe(e)),e})}var v_=We(Ze());var Ce={SETUP_SUCCESS:"1",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",RECONNECT_FAILED:"4",SETUP_FAILED:"5",DISCONNECTED:"6",CLOSE:"7",ONLINE:"8"};var Yt={CLIENT_BANNED:9,CHANNEL_SETUP_RESULT:19,CHANNEL_RECONNECT_RESULT:514,JOIN_ROOM_RESULT:20,PEER_JOIN:4134,PEER_LEAVE:4135,STREAM_ADDED:16,STREAM_REMOVED:18,UPLINK_NETWORK_STATS:22,UPDATE_REMOTE_MUTE_STAT:23,PUBLISH_RESULT:4098,PUBLISH_STATE_CHANGE_RESULT:4112,UNPUBLISH_RESULT:4100,SUBSCRIBE_RESULT:4102,UNSUBSCRIBE_RESULT:4104,SUBSCRIBE_CHANGE_RESULT:4106,MUTE_RESULT:4108,UPDATE_OFFER_RESULT:4128,START_PUBLISH_TENCENT_CDN_RES:1286,STOP_PUBLISH_TENCENT_CDN_RES:1288,START_PUBLISH_GIVEN_CDN_RES:777,STOP_PUBLISH_GIVEN_CDN_RES:779,START_MIX_TRANSCODE_RES:781,STOP_MIX_TRANSCODE_RES:783,START_PUBLISH_CDN_STREAM_RES:8196,UPDATE_PUBLISH_CDN_STREAM_RES:8198,STOP_PUBLISH_CDN_STREAM_RES:8200,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772,REBUILD_PEER_CONNECTION_RES:4150,SPC_PUBLISH_RESULT:4146,SPC_SUBSCRIBE_RESULT:4156,ABILITY_STATUS_REPORT_RESULT:4158,SERVER_FIRST_PACKAGE_RECEIVED:5e3,RECEIVE_CUSTOM_MSG:4140,FALLBACK_CODEC:66,SEND_SWITCH_ROOM_RES:4160,SEND_SWITCH_ROOM_SUBED_REQ:4161,UPDATE_NETWORK_TIME_RESULT:5001,CUSTOM_CMD_RES:8220},y_=[Yt.UPDATE_REMOTE_MUTE_STAT,Yt.UPLINK_NETWORK_STATS,Yt.USER_LIST_RES,Yt.MUTE_RESULT,Yt.SERVER_FIRST_PACKAGE_RECEIVED,Yt.RECEIVE_CUSTOM_MSG,Yt.UPDATE_NETWORK_TIME_RESULT],q={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",START_PUBLISH_CDN_STREAM_RES:"start-publish-cdn-stream-res",UPDATE_PUBLISH_CDN_STREAM_RES:"update-publish-cdn-stream-res",STOP_PUBLISH_CDN_STREAM_RES:"stop-publish-cdn-stream-res",USER_LIST_RES:"user-list-res",SWITCH_ROLE_RES:"switch_role_res",MUTE_RESULT:"mute-result",UPDATE_CONSTRAINT_CONFIG_RES:"update-contraint-config-res",REBUILD_PEER_CONNECTION_RES:"rebuild-pc-res",SPC_PUBLISH_RESULT:"spc-publish-result",SPC_SUBSCRIBE_RESULT:"spc-subscribe-result",ABILITY_STATUS_REPORT_RESULT:"ability-status-report",SERVER_FIRST_PACKAGE_RECEIVED:"first-pkg-received",RECEIVE_CUSTOM_MSG:"receive-custom-msg",FALLBACK_CODEC:"fallback-codec",SEND_SWITCH_ROOM_RES:"send-switch-room-res",SEND_SWITCH_ROOM_SUBED_REQ:"send-switch-room-subed-res",UPDATE_NETWORK_TIME_RESULT:"update_network_time_result",CUSTOM_CMD_RES:"custom-cmd-res"},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",START_PUBLISH_CDN_STREAM:"start_publish_cdn_stream",UPDATE_PUBLISH_CDN_STREAM:"update_publish_cdn_stream",STOP_PUBLISH_CDN_STREAM:"stop_publish_cdn_stream",GET_USER_LIST:"get_user_list",SWITCH_ROLE:"change_role",UPDATE_CONSTRAINT_CONFIG:"update_constraint_config",REBUILD_PEER_CONNECTION:"rebuild_pc",READY_TO_RECEIVE_DATA:"ready_to_receive",SPC_JOIN_ROOM:"join/v2",SPC_PUBLISH:"publish/v2",SPC_SUBSCRIBE:"subscribe/v3",ABILITY_STATUS_REPORT:"ability_status_report",RECONNECT_WS:"reconnect",SEND_CUSTOM_MSG:"channel_msg",SWITCH_ROOM:"switch_room",UPDATE_NETWORK_TIME:"update_network_time",CUSTOM_CMD:"abstract_cmd"},b_=new Set([Q.PUBLISH,Q.PUBLISH_CHANGE,Q.PUBLISH_STATE_CHANGE,Q.UNPUBLISH,Q.SUBSCRIBE,Q.SUBSCRIBE_CHANGE,Q.UNSUBSCRIBE,Q.SPC_PUBLISH,Q.SPC_SUBSCRIBE]);var jd=new Set;function N_(s){let i=[...jd.values()].find(e=>e.room.userId===s&&!e.room.isJoined);return i||null}var RI=["autoTest","relayInnerIp","relayOuterIp","mcd","newRelay","clientIp"],CI=0,Bo=class extends v_.default{constructor(e){var r,o,n;super();d(this,"room");d(this,"sdkAppId");d(this,"userId");d(this,"userSig");d(this,"url");d(this,"backupUrl");d(this,"destroyed",!1);d(this,"_socketInUse");d(this,"_socket");d(this,"_backupSocket");d(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,bakRelayIps:[],reportToken:void 0});d(this,"_currentState","DISCONNECTED");d(this,"_isReconnecting",!1);d(this,"_seq",0);d(this,"_log");d(this,"_lastMessageTime",-1);d(this,"_connectStartTime",-1);d(this,"_stopConnectRetry");d(this,"_isFirstConnect",!0);d(this,"bytesSent",0);d(this,"bytesReceived",0);d(this,"keepAlive",!1);d(this,"signalDomainWhenUnifiedProxy");d(this,"stopKeepAliveTimeout");d(this,"rtt",0);this.room=e.room,this.sdkAppId=e.sdkAppId,this.userId=e.userId,this.userSig=e.userSig,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy;let t=((o=(r=this.room.scheduleResult)==null?void 0:r.config)==null?void 0:o.keepAliveClient)||0;(n=this.room.joinParams)!=null&&n.keepAlive&&!t&&(t=1),t-jd.size>0&&this.room.enableSPC&&(this.keepAlive=!0,jd.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=C.createLogger({parent:this.room.getLogger(),id:`ws${++CI}`,userId:this.userId,sdkAppId:this.sdkAppId}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get race(){return this.room.enableSPC&&!this.room.proxy_ws}get urlParam(){let e=`?sdkAppId=${encodeURIComponent(this.sdkAppId)}&userId=${encodeURIComponent(this.userId)}&userSig=${encodeURIComponent(this.userSig)}&keepAlive=${encodeURIComponent(Number(this.keepAlive))}`;this.signalDomainWhenUnifiedProxy&&(e+=`&signalDomain=${encodeURIComponent(this.signalDomainWhenUnifiedProxy)}`);let t=new URLSearchParams(location.search);return RI.forEach(r=>{let o=t.get(`trtc_${r}`);o&&(e+=`&${r}=${encodeURIComponent(o)}`)}),this.race?`${e}&race=1`:e}get _urlWithParam(){return`${this.url}${this.race?"/v2/ws":""}${this.urlParam}`}get _backupUrlWithParam(){return`${this.backupUrl}${this.race?"/v2/ws":""}${this.urlParam}`}get isConnected(){return this._currentState==="CONNECTED"}get isConnecting(){return this._currentState==="CONNECTING"}get isOnline(){return this._currentState==="CONNECTED"&&Date.now()-this._lastMessageTime<12*1e3}connect(){return f(this,arguments,function*(e=10*1e3){if(this.isConnected)return Promise.resolve();this._log.info(`connect to [${this.url}, ${this.backupUrl}] ${this.race?"race":""}${e?` timeout: ${e}`:""} keepAlive: ${Number(this.keepAlive)}`),this.emitConnectionStateChanged("CONNECTING"),this._connectStartTime=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 ts(t),this.unbindAndCloseSocket(this._socketInUse===this._socket?_.BACKUP:_.MAIN),this._isFirstConnect&&(y.addSuccessEvent({key:521720}),this._isFirstConnect=!1),this.emitConnectionStateChanged("CONNECTED")})}connectWS({url:e,timeout:t,isMain:r}){let o=new WebSocket(e);this.bindSocket(o),r?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(r?_.MAIN:_.BACKUP),c(new N({code:I.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===_.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(t){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(t){}this._backupSocket=null}}onclose(e){e.target===this._socketInUse&&(this._log.warn(`${e.target===this._socket?"main":"backup"} is closed code:${e.code} ${e.reason}`),this.emitConnectionStateChanged("DISCONNECTED"),(!e.wasClean||e.code!==1e3)&&this.startReconnection(),this.room.isJoining&&this.emit(Ce.SETUP_FAILED,new N({code:I.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onclose"})))}onerror(e){this._log.error(`${e.target===this._socket?"main":"backup"} error observed`),this.emitConnectionStateChanged("DISCONNECTED"),e.target===this._socketInUse&&(this.unbindAndCloseSocket(_.MAIN),this.unbindAndCloseSocket(_.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(Ce.SETUP_FAILED,new N({code:I.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(e){if(!this.isConnected)return;let{isOnline:t}=this;this._lastMessageTime=Date.now(),t||this.emit(Ce.ONLINE),this.bytesReceived+=cn(e.data);let r=JSON.parse(e.data),{cmd:o,data:n}=r,a=Object.values(Yt),l=Object.keys(Yt)[a.indexOf(o)],u=q[l]||o;switch(y_.includes(o)||(this._log.debug(`received ${o} msg: ${e.data}`),u&&this._log.info(`Received event: [ ${u} ]`)),o){case Yt.CHANNEL_SETUP_RESULT:{if(r.code===0)this._signalInfo.clientIp=n.clientIp,this._signalInfo.signalIp=n.signalInnerIp,n.svrTime&&ba(n.svrTime-new Date().getTime()),this._log.info(`ChannelSetup Success ${x()-this._connectStartTime}`),y.addSuccessEvent({key:521701,cost:x()-this._connectStartTime}),this._connectStartTime=-1,this.room.firewallDetector.resetTimeoutCount(),this.emit(Ce.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let m=new N({code:I.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:r.code,message:W({key:H.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:r.code,errorMsg:r.message}})});this._log.error(`${r.code}, ${r.message}`),this.close(),y.addFailedEvent({key:521701,error:m}),this.emit(Ce.SETUP_FAILED,m)}break}case Yt.JOIN_ROOM_RESULT:{r.code===0&&(this._signalInfo.relayIp=n.relayOuterIp,this._signalInfo.relayInnerIp=n.relayInnerIp,this._signalInfo.bakRelayIps=n.bakRelayIps,this._signalInfo.relayPort=n.relayPort,this._signalInfo.tinyId=r.tinyId,this._signalInfo.endReportExtend=n.endReportExtend,this._signalInfo.reportToken=n.reportToken,this._log.info(`signalIp:${this._signalInfo.signalIp} clientIp:${this._signalInfo.clientIp} relayIp: ${this._signalInfo.relayIp}`)),this.emit(u,{data:r});break}default:this.emit(String(u),{data:r});break}}reGetSignalChannelUrl(){return f(this,null,function*(){try{if(!this.room.joinParams)return;Vt(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(e){}})}startReconnection(){if(!this._socketInUse)return;this._socketInUse.onclose=null,this._socketInUse.close(4011);let e=this._socketInUse===this._socket;this.unbindAndCloseSocket(e?_.MAIN:_.BACKUP),this._socketInUse=null,this.emitConnectionStateChanged("DISCONNECTED"),this.reconnect()}reconnect(){return f(this,null,function*(){if(!this._isReconnecting){if(!this.room.isJoined&&this.keepAlive){this.close();return}this._isReconnecting=!0;try{this._log.warn("reconnect"),yield this.connect();let{roomId:e,useStringRoomId:t}=this.room,{relayIp:r,relayInnerIp:o,relayPort:n}=this._signalInfo,{data:a}=yield this.sendWaitForResponse({command:Q.RECONNECT_WS,data:{roomId:e,useStringRoomId:t,relayInnerIp:o,relayOuterIp:r,relayPort:n},responseCommand:q.CHANNEL_RECONNECT_RESULT});a.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),y.addSuccessEvent({key:521702,cost:x()-this._connectStartTime}),this._connectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(y.addFailedEvent({key:521702,error:a.code}),this._log.warn(`reconnect failed, ${a.code} ${a.message}`),this.room.reJoin())}catch(e){this._log.error(e),this.room.reJoin()}}})}send(e,t={}){if(this.isConnected&&!this.room.isLeft){let r={cmd:e,data:t,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},o=JSON.stringify(r);return this._socketInUse.send(o),b_.has(e)&&this._log.info("send",e,t),this.bytesSent+=cn(o),r.seq}}sendWaitForResponse({command:e,data:t,timeout:r=5e3,responseCommand:o,commandDesc:n,enableLog:a=!0,addReceiveTime:c=!1}){return new Promise((l,u)=>{let m=()=>{clearTimeout(p),u(new N({code:I.API_CALL_ABORTED,message:`${e} aborted due to connection closed`}))};this.once(Ce.CLOSE,m);let p=setTimeout(()=>{this.off(o,h),this.off(Ce.CLOSE,m);let g=new N({code:I.API_CALL_TIMEOUT,message:W({key:H.API_CALL_TIMEOUT,data:{commandDesc:n,command:e}})});a&&this._log.warn(g),u(g)},r),h=g=>{g.data.seq===T&&(clearTimeout(p),this.off(o,h),this.off(Ce.CLOSE,m),c&&(g.data.receiveTime=Date.now()),l(g))};this.on(o,h);let T=this.send(e,t)})}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:r,retries:o=0,retryTimeout:n=0}=e;return Ni({retryFunction:this.sendWaitForResponse,onError:({retry:a,reject:c,error:l})=>{!this.room.isJoined||this.destroyed||l.code===I.API_CALL_ABORTED?c(l):this.isOnline?a():(this._log.warn(`retry ${r} when connected`),this.once(Ce.ONLINE,a))},onRetrying:a=>{this._log.warn(`${t||r} 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"),clearTimeout(this.stopKeepAliveTimeout),jd.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,bakRelayIps:[],endReportExtend:void 0,reportToken:void 0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(_.MAIN),this.unbindAndCloseSocket(_.BACKUP),this.emitConnectionStateChanged("DISCONNECTED"),this.emit(Ce.CLOSE)}destroy(){this.close(),this.destroyed=!0}getBackupRelayIpPair(){var t;let e=(t=this._signalInfo.bakRelayIps)==null?void 0:t.shift();return e&&(e.relayPort=e.relayPort||this._signalInfo.relayPort),e}clearBakRelayIps(){this._signalInfo.bakRelayIps=[]}stopKeepAliveIn(e=3600){if(this.keepAlive){this._log.info(`stopKeepAlive in ${e}s`),this.stopKeepAliveTimeout=setTimeout(()=>{this.keepAlive=!1,this._log.info(`close due to not used ${e}s`),this.close(),this.off(q.JOIN_ROOM_RESULT,t)},e*1e3);let t=r=>{r.data.code===0&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(q.JOIN_ROOM_RESULT,t))};this.on(q.JOIN_ROOM_RESULT,t)}}emitConnectionStateChanged(e){if(e===this._currentState)return;this._log.info(`${this._currentState} -> ${e}`);let t={prevState:this._currentState,state:e};e==="CONNECTING"&&(t.isReconnecting=this._isReconnecting),this.emit(Ce.CONNECTION_STATE_CHANGED,t),this._currentState=e,e==="CONNECTED"?this.emit(Ce.CONNECTED):e==="DISCONNECTED"&&this.emit(Ce.DISCONNECTED)}};O([kt({settings:{retries:1/0,timeout:2e3},onError(e,t){!this.room.isDestroyed&&!this.destroyed&&(this._isFirstConnect&&(y.addFailedEvent({key:521720,error:e}),this._isFirstConnect=!1),this.room.firewallDetector.increaseTimeoutCount(),t())},onRetrying(e,t){this._log.warn(`retrying to connect ${e}`),e>=3&&e%3===0&&this.reGetSignalChannelUrl(),t&&(this._stopConnectRetry=t,(this.room.isDestroyed||this.destroyed)&&t())}})],Bo.prototype,"connect",1);var D_=We(Ze());var um=!1,_t=class{constructor(i){d(this,"userId");d(this,"tinyId");d(this,"_sdpSemantics");d(this,"_isUplink");d(this,"_room");d(this,"_log");d(this,"_signalChannel");d(this,"_isErrorObserved",!1);d(this,"_waitForPeerConnectionConnectedPromise");d(this,"_waitForPeerConnectionConnectedPromiseReject",null);d(this,"_peerConnection",null);d(this,"_emitter",new D_.default);d(this,"_currentState","DISCONNECTED");d(this,"_isReconnecting",!1);d(this,"_reconnectionCount",0);d(this,"_reconnectionTimer",-1);d(this,"_isFirstConnection",!0);d(this,"_prevTime",-1);d(this,"_localAddress");d(this,"_remoteAddress");d(this,"isDestoyed",!1);this.userId=i.userId,this.tinyId=i.tinyId,this._room=i.room,this._sdpSemantics=i.room.sdpSemantics,this._isUplink=i.isUplink,this._log=i.room.getLogger().createChild({id:"n-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=i.signalChannel}beforeConnect(){this._prevTime<0&&(this._prevTime=x())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,y.addSuccessEvent({key:521705,cost:Math.min(x()-this._prevTime,30*1e3)})):this._isReconnecting&&y.addSuccessEvent({key:521706,cost:x()-this._prevTime}),this._prevTime=-1}catch(i){throw this._isFirstConnection?(this._isFirstConnection=!1,y.addFailedEvent({key:521705,error:i})):this._isReconnecting&&this._reconnectionCount>=3&&y.addFailedEvent({key:521706,error:i}),i}}initialize(){let i={iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"};this._peerConnection=new RTCPeerConnection(i),this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this)}close(i){this._log.info("close connection"),this._emitter.emit("closed",i),this._isReconnecting&&this.stopReconnection(),this.closePeerConnection()}destroy(){this.isDestoyed=!0}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 N({code:I.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return ii;let i=null;if(this._isUplink){if(!Pr()||this._peerConnection.getSenders().length===0)return ii;i=this._peerConnection.getSenders()[0].transport}else{if(!hs()||this._peerConnection.getReceivers().length===0)return ii;i=this._peerConnection.getReceivers()[0].transport}return i?i.state:ii}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===be.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),i.target.connectionState===be.FAILED||i.target.connectionState===be.CLOSED){let r=`connection ${i.target.connectionState}. ICE Transport state: ${e}, DTLS Transport state: ${t}`,o=new N({message:r,code:I.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",o)}(i.target.connectionState===be.CONNECTED||i.target.connectionState===be.COMPLETED)&&(this.logSelectedCandidate(),se.logSuccessEvent({userId:this._room.userId,eventType:Oe.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(i){return i===this._currentState?!1:(i==="CONNECTED"&&(this._room.firewallDetector.resetTimeoutCount(),um=!0),S.emit(A.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:i,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:i}),this._currentState=i,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}logSelectedCandidate(){return f(this,null,function*(){if(!this._peerConnection)return;let i=yield this._peerConnection.getStats();for(let[,e]of i)if(Or(e)){let t=i.get(e.localCandidateId),r=i.get(e.remoteCandidateId);t&&(this._log.info(`local candidate: ${t.candidateType} ${t.protocol}:${t.ip||t.address}:${t.port} ${t.networkType||""} ${t.candidateType==="relay"?`relayProtocol:${t.relayProtocol}`:""}`),this._localAddress=`${t.ip||t.address}:${t.port}`),r&&(this._log.info(`remote candidate: ${r.candidateType} ${r.protocol}:${r.ip||r.address}:${r.port}`),this._remoteAddress=`${r.protocol}:${r.ip||r.address}`);break}})}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise?this._waitForPeerConnectionConnectedPromise:(this._waitForPeerConnectionConnectedPromise=new Promise((i,e)=>{if(this._currentState==="CONNECTED")return i();this._waitForPeerConnectionConnectedPromiseReject=e;let t=a=>{a.state==="CONNECTED"&&(clearTimeout(n),o(),i())},r=({room:a})=>{a===this._room&&(clearTimeout(n),o(),e(new N({code:I.API_CALL_ABORTED,message:W({key:H.CONNECTION_ABORTED,data:"leave room"})})))},o=()=>{S.off(A.LEAVE_SUCCESS,r,this),this._emitter.off("connection-state-changed",t,this)},n=setTimeout(()=>{o();let a=new N({code:I.API_CALL_TIMEOUT,message:"connection timeout"});this._room.firewallDetector.increaseTimeoutCount(),e(a)},rn);S.on(A.LEAVE_SUCCESS,r,this),this._emitter.on("connection-state-changed",t,this)}),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally(()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null}),this._waitForPeerConnectionConnectedPromise)}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(Ce.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=Ji()){this._log.warn(`SDK has tried reconnect for ${this._reconnectionCount} times, but all failed, please check your network`),this.stopReconnection();let i=new N({code:this._isUplink?I.UPLINK_RECONNECTION_FAILED:I.DOWNLINK_RECONNECTION_FAILED,message:W({key:this._isUplink?H.UPLINK_RECONNECTION_FAILED:H.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(Ce.CONNECTED,this.reconnect,this),-1)}on(i,e,t){this._emitter.on(i,e,t)}off(i,e,t){this._emitter.off(i,e,t)}getIsReconnecting(){return this._isReconnecting}get isH264(){var i,e;return!!((e=(i=this._peerConnection)==null?void 0:i.remoteDescription)!=null&&e.sdp.includes("H264"))}setOffer(i){var e;return(e=this._peerConnection)==null?void 0:e.setLocalDescription(i)}setAnswer(i){var e;return(e=this._peerConnection)==null?void 0:e.setRemoteDescription(i)}};O([yt(521712,!1)],_t.prototype,"setOffer",1),O([yt(521713,!1)],_t.prototype,"setAnswer",1);var fm=We(pm());var De=function(s){return fm.default.parse(s)},Zt=function(s){return fm.default.write(s)},U_=function(s){let i=De(s);return i.media.forEach(e=>{e.type===_.AUDIO&&e.fmtp.forEach(t=>{t.config+=";sprop-stereo=1;stereo=1"})}),Zt(i)};function V_(s){let i=De(s);return i.media.forEach(e=>{var t,r;if(e.type===_.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 l=c.match(/apt=(\d+)/);l&&l[1]&&o.has(Number(l[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=(r=e.payloads)==null?void 0:r.split(" ").filter(a=>!o.has(Number(a))).join(" ")}}),Zt(i)}function qd(s){return Object.keys(s).filter(i=>s[i])}var $o=class $o extends _t{constructor(e){super(L(M({},e),{isUplink:!1}));d(this,"_flag",0);d(this,"isRobot",!1);d(this,"role","anchor");d(this,"remoteAudioTrack");d(this,"remoteVideoTrack");d(this,"remoteAuxiliaryTrack");d(this,"avPlayerStateSyncManager");d(this,"ssrc",{audio:0,video:0,auxiliary:0});d(this,"_isSDPExchanging",!1);d(this,"_videoCodec");d(this,"fromType");this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=e.remoteAudioTrack||new Ai(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new Ui(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new Po(this._room,this),this.avPlayerStateSyncManager=new lr({log:this._log,audioPlayer:this.remoteAudioTrack.player,videoPlayer:this.remoteVideoTrack.player})}get videoCodec(){var t,r;let e=(r=(t=this._peerConnection)==null?void 0:t.remoteDescription)==null?void 0:r.sdp;return e?e.includes("H264")?"h264":"vp8":this._videoCodec||"h264"}set videoCodec(e){this._videoCodec=e}get subscribeState(){let e={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(this.remoteVideoTrack.mediaType&8?e.smallVideo=!0:e.video=!0),this.remoteAudioTrack.isSubscribed&&(e.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(e.auxiliary=!0),e}get muteState(){return oi(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,r,o;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(r=this.remoteVideoTrack)==null||r.onFlagChanged(),(o=this.remoteAuxiliaryTrack)==null||o.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===_.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.avPlayerStateSyncManager.destroy(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var o,n;let t=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&t!==e&&((o=this.remoteVideoTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),r}onTrack(e){let t=e.streams[0],{track:r}=e,o=t.id===tn?_.MAIN:_.AUXILIARY;this._log.debug(`ontrack ${o} ${r.kind}`);let n=_.AUDIO;r.kind===_.VIDEO&&(n=o===_.MAIN?_.VIDEO:_.AUXILIARY);let a=this.remoteAudioTrack;n===_.VIDEO?a=this.remoteVideoTrack:n===_.AUXILIARY&&(a=this.remoteAuxiliaryTrack),a.setInputMediaStreamTrack(r)}addRRTRLine(e){let t=e.split(`\r
|
|
65
65
|
`),r=new Map;t.forEach((n,a)=>{/^a=rtcp-fb:/.test(n)&&t[a+1]&&!/^a=rtcp-fb:/.test(t[a+1])&&r.set(a+1,`${n.match(/^a=rtcp-fb:\d+/)[0]} rrtr`)});let o=[...r];for(let n=0;n<o.length;n++){let[a,c]=o[n];t.splice(a+n,0,c)}return t.join(`\r
|
|
66
66
|
`)}addSPSDescription(e){let t=De(e);return t.media.forEach(r=>{r.type===_.VIDEO&&r.fmtp.forEach(o=>{o.config+=";sps-pps-idr-in-keyframe=1"})}),Zt(t)}removeSDESDescription(e){let t=["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"],r=De(e);return r.media.forEach(o=>{o.ext&&(o.ext=o.ext.filter(n=>!t.includes(n.uri)))}),Zt(r)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return f(this,null,function*(){var r,o;try{if((((r=this._peerConnection)==null?void 0:r.connectionState)===be.NEW||((o=this._peerConnection)==null?void 0:o.connectionState)===be.CONNECTING)&&(yield this.waitForPeerConnectionConnected()),this.isSubscriptionStateNotChanged(e)){this._peerConnection||(this.initialize(),yield this.connect(e));return}if(this._log.info(`subscribe ${t} ${JSON.stringify(e)}`),this._peerConnection||this._isSDPExchanging){let n="subscribe_change";Object.values(e).find(a=>a===!0)||(n="unsubscribe"),yield this.sendSubscription(n,e)}else this.initialize(),yield this.connect(e)}catch(n){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${n.message} ${JSON.stringify(this.muteState)}`),new N({code:I.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):n}})}unsubscribe(r){return f(this,arguments,function*({remoteTracks:e,streamType:t}){if(this._currentState==="CONNECTED"&&(t==="main"&&!this.isMainStreamSubscribed||t==="auxiliary"&&!this.isAuxStreamSubscribed)){this._log.info(`${t} stream already unsubscribed`);return}let o=M({},this.subscribeState);e.forEach(a=>{switch(a.mediaType){case 1:o.audio=!1;break;case 4:o.video=!1;break;case 8:o.smallVideo=!1;break;case 2:o.auxiliary=!1;break;default:break}});let n="subscribe_change";Object.values(o).find(a=>a===!0)||(n="unsubscribe"),this._log.info(`${n==="unsubscribe"?n:"subscribe"} ${t} [${qd(o)}]`),yield this.sendSubscription(n,o),n==="unsubscribe"&&(this.closePeerConnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"))})}unsubscribeDataChannel(){return f(this,null,function*(){})}sendSubscription(e,t=this.subscribeState){let r={srcTinyId:this.tinyId,srcUserId:this.userId},o=Q.UNSUBSCRIBE,n=q.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(r={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},o=Q.SUBSCRIBE_CHANGE,n=q.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:o,data:r,responseCommand:n,timeout:1e4}).then(({data:a})=>{if(a.code!==0){let c=new N({code:a.code,message:W({key:H.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(c),c}})}connect(){return f(this,arguments,function*(e=this.subscribeState){try{yield this.exchangeSDP(e),yield this.waitForPeerConnectionConnected()}catch(t){throw this.closePeerConnection(!0),t}})}exchangeSDP(e){return f(this,null,function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info("createOffer success, sending offer");let{type:t,sdp:r}=this._peerConnection.localDescription,o={type:t,sdp:r,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},n=yield this._signalChannel.sendWaitForResponse({command:Q.SUBSCRIBE,commandDesc:"exchange sdp",data:o,responseCommand:q.SUBSCRIBE_RESULT,timeout:Rl});if(!this._peerConnection){let a=new N({code:I.INVALID_OPERATION,message:W({key:H.CONNECTION_CLOSED})});throw this._log.warn(a),a}yield this.onSubscribeResult(n),this._isSDPExchanging=!1}catch(t){throw this._isSDPExchanging=!1,t}})}createOffer(){return f(this,null,function*(){let e={voiceActivityDetection:!1};It()&&this._sdpSemantics===Ar?(this._peerConnection.addTransceiver(_.AUDIO,{direction:de.RECVONLY}),this._peerConnection.addTransceiver(_.VIDEO,{direction:de.RECVONLY}),this._peerConnection.addTransceiver(_.VIDEO,{direction:de.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:r}=yield Lc();r||(this._log.warn("remove h264 desc from sdp"),t.sdp=V_(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=U_(t.sdp),this._sdpSemantics===Ar&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this.setOffer(t)})}onSubscribeResult(e){return f(this,null,function*(){let{code:t,message:r=""}=e&&e.data||{},{type:o,sdp:n}=e&&e.data&&e.data.data||{};if(t===zr)throw new N({code:I.NOT_SUPPORTED_H264,message:W({key:H.NOT_SUPPORTED_H264DECODE})});try{if(t!==0)throw new N({code:t,message:W({key:H.EXCHANGE_SDP_FAILED,data:{errMsg:r}})});this._log.debug(`accept remote answer: ${n}`),yield this.setAnswer({type:o,sdp:n}),this.updateSSRC(n)}catch(a){throw this._log.error(a),a}})}updateSSRC(e){try{De(e).media.forEach(r=>{if(r.ssrcs)if(r.type===_.AUDIO){let o=r.ssrcs.find(n=>{var a;return(a=n.value)==null?void 0:a.includes(tn)});o&&(this.ssrc.audio=Number(o.id))}else{let o=r.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(tn)}),n=r.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(Tl)});o&&(this.ssrc.video=Number(o.id)),n&&(this.ssrc.auxiliary=Number(n.id))}})}catch(t){}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return f(this,null,function*(){if(!(Ue($o.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch(t){let r=si(this._reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${r/1e3}s`),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},r)}})}getIsReconnecting(){return this._isReconnecting}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}getCurrentState(){return this._currentState}setDelay({audioDelay:e,videoDelay:t}){this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=t}get audioReceiver(){var e;return((e=this._peerConnection)==null?void 0:e.getReceivers()[0])||null}};O([K(e=>function(...t){return new Promise((r,o)=>{let n=a=>{this._emitter.off("closed",n),o(new N({code:I.API_CALL_ABORTED,message:W({key:H.CONNECTION_ABORTED,data:a})}))};this._emitter.on("closed",n),e.apply(this,t).then(r,o).finally(()=>{this._emitter.off("closed",n)})})})],$o.prototype,"subscribe",1),O([yt(521717,!1)],$o.prototype,"unsubscribe",1),O([Ct(_t.prototype.afterConnect),Xc(_t.prototype.beforeConnect)],$o.prototype,"connect",1);var _m=$o,gm=_m;var B_={voiceActivityDetection:!1},Wo=class Wo extends _t{constructor(e){super(L(M({},e),{isUplink:!0}));d(this,"localMainAudioTrack",null);d(this,"localMainVideoTrack",null);d(this,"localAuxAudioTrack",null);d(this,"localAuxVideoTrack",null);d(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0});d(this,"_isPublishingAux",!1);d(this,"_publishingLocalAudioTrack");d(this,"_publishingLocalVideoTrack");d(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0});d(this,"flag",0)}get videoCodec(){return this._mediaSettings.videoCodec.toLowerCase()||"h264"}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}initialize(){super.initialize(),this.installEvents()}reset(){this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this.uninstallEvents()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this._emitter.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this._emitter.on("connection-state-changed",this.handleConnectionStateChange,this)}uninstallEvents(){this._emitter.off("connection-state-changed",this.handleConnectionStateChange,this)}emitConnectionStateChangedEvent(e,t){var n,a,c;let r=this._currentState,o=super.emitConnectionStateChangedEvent(e);return o&&r!==e&&(t?t.emit("connection-state-changed",{prevState:r,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:r,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:r,state:e}),(c=this._publishingLocalVideoTrack)==null||c.emit("connection-state-changed",{prevState:r,state:e}))),o}publish(o){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:r}){this._peerConnection||this.initialize(),e&&(this._publishingLocalAudioTrack=e),t&&(this._publishingLocalVideoTrack=t),this._isPublishingAux=r;let n;t&&!r&&t.small&&(n=this._room.videoManager.smallTrack),this.sendMediaSettings(),It()?yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:n,isAuxiliary:r}):yield this.publishByAddTrack({localAudioTrack:e,localVideoTrack:t,smallTrack:n}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,r?(t&&(this.localAuxVideoTrack=t),e&&(this.localAuxAudioTrack=e)):(t&&(this.localMainVideoTrack=t),e&&(this.localMainAudioTrack=e)),this.installTrackMuteEvents(e,t),this.sendMutedFlag()})}publishByTransceiver(n){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:r,isAuxiliary:o}){this._log.info("publish by transceiver");let a=new MediaStream,c=t==null?void 0:t.outMediaTrack,l=e==null?void 0:e.outMediaTrack;l&&a.addTrack(l),c&&a.addTrack(c);let u=this._peerConnection.getTransceivers();if(u.length===0)this._peerConnection.addTransceiver(l||_.AUDIO,{direction:de.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(o?_.VIDEO:c||_.VIDEO,{direction:de.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(r||_.VIDEO,{direction:de.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(o?c||_.VIDEO:_.VIDEO,{direction:de.SENDONLY,streams:[a]}),yield this.connect();else{let m=[];if(l&&(u[0].sender.track||m.push(0),yield u[0].sender.replaceTrack(l),yield this.setBandwidth({bandwidth:(e==null?void 0:e.profile.bitrate)||40,type:_.AUDIO})),c){let p=o?3:1;yield u[p].sender.replaceTrack(c),yield this.setBandwidth({bandwidth:t.profile.bitrate,type:_.VIDEO,videoType:o?_.AUXILIARY:_.BIG}),m.push(p),r&&(yield u[2].sender.replaceTrack(r),yield this.setBandwidth({bandwidth:t.small.bitrate,type:_.VIDEO,videoType:_.SMALL}),m.push(2))}yield this.setTransceiverDirection(de.SENDONLY,m),yield this.doPublishChange(),t==null||t.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),t==null||t.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"})}})}publishByAddTrack(o){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:r}){this._log.info("publish by addtrack");let n=t==null?void 0:t.outMediaTrack,a=e==null?void 0:e.outMediaTrack;if(this._peerConnection&&this._peerConnection.connectionState!=="new"){e&&a&&(yield this.addTrack(e)),n&&(yield this.addTrack(t));return}let c=new MediaStream;if(a&&c.addTrack(a),n&&c.addTrack(n),a&&this._peerConnection.addTrack(a,c),n&&(this._peerConnection.addTrack(n,c),r)){let l=new MediaStream;l.addTrack(r),this._peerConnection.addTrack(r,l)}yield this.connect()})}enableSmall(e){return f(this,null,function*(){let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.setTransceiverDirection(de.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(de.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()})}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(r){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){if(!kr()){if(e&&e.outMediaTrack&&!t&&this.localMainVideoTrack){yield this.removeTrack(e),this.localMainAudioTrack=null;return}if(t&&t.outMediaTrack&&!e&&this.localMainAudioTrack){yield this.removeTrack(t),this.localMainVideoTrack=null;return}yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),this.emitConnectionStateChangedEvent("DISCONNECTED",t);return}let o=t&&t===this.localAuxVideoTrack,n=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),c=[];e&&(o?this.localAuxAudioTrack=null:this.localMainAudioTrack=null,!this.localAuxAudioTrack&&!this.localMainAudioTrack&&(yield a[0].replaceTrack(null),c.push(0))),n&&(o?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=L(M({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),c.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=L(M({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),c.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.setTransceiverDirection(de.INACTIVE,c),yield this.doPublishChange(!1)):yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),t==null||t.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return f(this,null,function*(){let t={state:this._room.publishState,constraintConfig:this._mediaSettings},r=yield this._signalChannel.sendWaitForResponse({command:Q.PUBLISH_STATE_CHANGE,data:t,responseCommand:q.PUBLISH_STATE_CHANGE_RESULT,enableLog:e});this.checkPublishResultCode(r.data.code,r.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:Q.UNPUBLISH,commandDesc:"unpublish",responseCommand:q.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===I.API_CALL_TIMEOUT)return Promise.resolve();throw t})}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let r=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:o,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:o=this._publishingLocalVideoTrack),Oi){if(r&&r.outMediaTrack){let a=r.outMediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=r.profile.bitrate*1e3,this._mediaSettings.audioFs=a.sampleRate||0}if(o&&o.outMediaTrack){let a=o.outMediaTrack.getSettings();this._mediaSettings.videoWidth=a.width||0,this._mediaSettings.videoHeight=a.height||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=o.profile.bitrate*1e3,o.small&&(this._mediaSettings.smallVideoWidth=o.small.width,this._mediaSettings.smallVideoHeight=o.small.height,this._mediaSettings.smallVideoFps=o.small.frameRate,this._mediaSettings.smallVideoBps=o.small.bitrate*1e3)}if(n&&n.outMediaTrack){let a=n.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=a.width||0,this._mediaSettings.auxVideoHeight=a.height||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=n.profile.bitrate*1e3}}else r&&r.outMediaTrack&&(this._mediaSettings.audioChannel=r.profile.channelCount,this._mediaSettings.audioBps=r.profile.bitrate*1e3,this._mediaSettings.audioFs=r.profile.sampleRate),o&&o.outMediaTrack&&(this._mediaSettings.videoWidth=o.profile.width,this._mediaSettings.videoHeight=o.profile.height,this._mediaSettings.videoFps=o.profile.frameRate,this._mediaSettings.videoBps=o.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:Q.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:q.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return f(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is adding ${e.kind} track to current published local ${t?_.AUXILIARY:_.MAIN} stream`),It()?yield this.addTrackByTransceiver(e,t):yield this.addTrackBySender(e)})}addTrackByTransceiver(e,t){return f(this,null,function*(){var o;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===_.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),n===1&&((o=this.localMainVideoTrack)!=null&&o.small)&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===de.INACTIVE&&(yield this.setTransceiverDirection(de.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}addTrackBySender(e){return f(this,null,function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;kr()&&this._peerConnection.getTransceivers().findIndex(o=>o.direction==="stopped")>=0&&(this._log.warn("transceiver is stopping, negotiate sdp first"),yield this.updateOffer("remove",t));let r=this._peerConnection.getSenders().find(o=>o.track&&o.track.kind===t.kind);if(r&&r.track){this._log.warn("sender already exists, remove sender first");let o=r.track;this.removeSender(r),yield this.updateOffer("remove",o)}if(t&&this._peerConnection.addTrack(t,new MediaStream([t])),t.kind===_.VIDEO&&e instanceof ze&&e.small){let o=new MediaStream,{smallTrack:n}=this._room.videoManager;o.addTrack(n),this._peerConnection.addTrack(n,o)}yield this.updateOffer("add",t)})}isNeedToResetOfferOrder(){if(this._sdpSemantics===Vs||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=De(e);for(let r=0;r<t.media.length;r++)if(Number(t.media[r].mid)===0&&t.media[r].type===_.VIDEO)return!0;return!1}removeSender(e){let t=null;kr()&&(t=this._peerConnection.getTransceivers().find(r=>r.sender&&r.sender.track===e.track)),this._peerConnection.removeTrack(e),t&&me(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return f(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${t?_.AUXILIARY:_.MAIN} stream`),It()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)})}removeTrackByTransceiver(e,t){return f(this,null,function*(){if(!e.outMediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===_.AUDIO)yield r[0].sender.replaceTrack(null);else{let o=t?3:1;yield r[o].sender.replaceTrack(null),o===1&&e.small&&(yield r[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(de.INACTIVE,[o])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,t){return f(this,null,function*(){if(!re)return;let r=!1,o=!1;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let n=this._peerConnection.getTransceivers();if(t.forEach(l=>{n[l].direction!==e&&(n[l].direction=e,r=!0)}),r){this._log.info("updating offer");let l=yield this._peerConnection.createOffer();yield this.setOffer(l)}let a=-1,c=this._peerConnection.remoteDescription.sdp.split(`\r
|
|
67
67
|
`).map(l=>{if(l.match(new RegExp(`a=(${de.INACTIVE}|${de.RECVONLY}|${de.SENDONLY})`))&&a++,t.includes(a)){if(e===de.INACTIVE&&l.includes(`a=${de.RECVONLY}`))return o=!0,`a=${e}`;if(e===de.SENDONLY&&l.includes(`a=${de.INACTIVE}`))return o=!0,`a=${de.RECVONLY}`}return l}).join(`\r
|