trtc-sdk-v5 5.12.0-beta.7 → 5.12.0-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/cross-room/package.json +1 -1
- package/plugins/custom-encryption/package.json +1 -1
- package/plugins/device-detector/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/basic-beauty.esm.js +1 -1
- package/plugins/video-effect/basic-beauty/basic-beauty.umd.js +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/video-mixer/package.json +1 -1
- package/plugins/video-effect/virtual-background/package.json +1 -1
- package/plugins/video-effect/virtual-background/virtual-background.esm.js +1 -1
- package/plugins/video-effect/virtual-background/virtual-background.umd.js +1 -1
- package/plugins/video-effect/watermark/package.json +1 -1
- package/plugins/voice-changer/package.json +1 -1
- package/trtc.esm.js +3 -3
- package/trtc.js +1 -1
package/trtc.esm.js
CHANGED
|
@@ -49,13 +49,13 @@ uniform sampler2D u_texture;
|
|
|
49
49
|
|
|
50
50
|
void main() {
|
|
51
51
|
gl_FragColor = texture2D(u_texture, v_texCoord);
|
|
52
|
-
} `;var Yr=class extends ${constructor(e){super();d(this,"frameRate");d(this,"_canvas");d(this,"log");d(this,"hasAlpha",!1);d(this,"name");d(this,"error");this.name=e.name,this.log=e.logger.createChild({id:`vc-${this.name}`}),this.frameRate=e.frameRate}set width(e){this._canvas&&(this._canvas.width=e)}get width(){var e;return((e=this._canvas)==null?void 0:e.width)||0}set height(e){this._canvas&&(this._canvas.height=e)}get height(){var e;return((e=this._canvas)==null?void 0:e.height)||0}setSize(e,t){this._canvas&&(this._canvas.width=e,this._canvas.height=t)}createVideoTrackSource(e,t){return new Dt(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new Qo(this,e)}createVideoImageSource(e,t){return new gn(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new Tn(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}createTextSource(e,t){return new _c(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}};d(Yr,"_ids",0);var uE={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},Yo=class Yo extends Yr{constructor(){super(...arguments);d(this,"defaultProgam");d(this,"defaultVShader");d(this,"defaultFShader");d(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${Yr._ids++}`),this.ctx=this._canvas.getContext("webgl2",uE),!this.ctx)throw new N({code:I.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,dE),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,lE),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,b.addFailedEvent({key:512702,error:e})),this.disconnect(),this.log.info(`video context destroy${t}`?`: ${t}`:""),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),e}set width(e){var t;(t=this.ctx)==null||t.viewport(0,0,e,this.height),super.width=e}set height(e){var t;(t=this.ctx)==null||t.viewport(0,0,this.width,e),super.height=e}setSize(e,t){var r;(r=this.ctx)==null||r.viewport(0,0,e,t),super.setSize(e,t)}createShader(e,t){let r=this.ctx,s=r.createShader(e);return r.shaderSource(s,t),r.compileShader(s),s}createProgram(e,t){let r=this.ctx,s=r.createProgram();return r.attachShader(s,e),r.attachShader(s,t),r.linkProgram(s),r.getProgramParameter(s,r.LINK_STATUS)||this.log.error(r.getProgramInfoLog(s)),s}};d(Yo,"UNAVAILABLE","unavailable"),D([Te($.INIT,"created",{sync:!0,fail(e){this.log.error("video gl context create failed",e.cause),b.addFailedEvent({key:512700,error:e.cause||e})},success(){this.log.info("video context created use webgl"),b.addSuccessEvent({key:512700})}})],Yo.prototype,"create",1),D([Te("created",$.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(Yo.UNAVAILABLE,e),this.removeAllListeners()}})],Yo.prototype,"destroy",1);var Oe=Yo,Fe=class extends Yr{constructor(){super(...arguments);d(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${Yr._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!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,b.addFailedEvent({key:512703,error:e})),this.disconnect(),this.log.info(`video context destroy ${t?`: ${t}`:""}`),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners(),b.addSuccessEvent({key:512703})}};D([Te($.INIT,"created",{sync:!0,fail(e){this.log.error("video 2d context create failed",e.cause),b.addFailedEvent({key:512701,error:e.cause||e})},success(){this.log.info("video context created use 2d"),b.addSuccessEvent({key:512701})}})],Fe.prototype,"create",1),D([Te("created",$.INIT,{ignoreError:!0,sync:!0})],Fe.prototype,"destroy",1);function hE(o,i,e,t,r,s=!1){s&&([e,t]=[t,e]);let n={sWidth:o,sHeight:i,dWidth:e,dHeight:t,sx:0,sy:0,dx:0,dy:0};if(o===0||i===0)return n;switch(r){case void 0:case"fill":break;case"contain":{let a=Math.min(e/o,t/i);n.dWidth=o*a,n.dHeight=i*a,n.dx=(e-n.dWidth)/2,n.dy=(t-n.dHeight)/2;break}case"cover":{let a=Math.max(e/o,t/i),c=e/a,l=t/a;n.sx=(o-c)/2,n.sy=(i-l)/2,n.sWidth=c,n.sHeight=l;break}}return n}var Mu=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}},Zo=class extends Ye{constructor(e,t){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,matchInputSize:!1,logger:t});d(this,"inputs",[]);d(this,"backgroundColor","black")}addInput(e,t){let r=0,s=this.inputs.length;for(;r<s;){let a=Math.floor((r+s)/2);if(this.inputs[a].layout.zIndex<t.zIndex)r=a+1;else if(this.inputs[a].layout.zIndex>t.zIndex)s=a;else throw new Error(`input already exists at zIndex ${t.zIndex}`)}let n=new Mu(e,t);this.inputs.splice(r,0,n)}changeInputLayout(e,t){let r=this.inputs.findIndex(A=>A.node===e);if(r<0)return;let{x:s,y:n,width:a,height:c,zIndex:l,fillMode:u,rotation:h,hidden:m}=t;if(!E(l)&&this.inputs.some(A=>A.layout.zIndex===l&&A.node!==e))throw new Error(`input already exists at zIndex ${t.zIndex}`);let g=this.inputs[r];E(s)||(g.layout.x=s),E(n)||(g.layout.y=n),E(a)||(g.layout.width=a),E(c)||(g.layout.height=c),E(h)||(g.layout.rotation=h),E(m)||(g.layout.hidden=m),u&&(g.layout.fillMode=u),!E(l)&&l!==g.layout.zIndex&&(g.layout.zIndex=l,this.inputs.sort((A,_)=>A.layout.zIndex-_.layout.zIndex))}hasInput(e){return this.inputs.some(t=>t.node===e)}hasNoInput(){return this.inputs.length===0}resize(e,t){if(!this.matchInputSize){super.resize(e,t);return}let r=this.inputs.reduce((s,n)=>n?Object.assign(s,{width:Math.max(s.width,n.right),height:Math.max(s.height,n.bottom)}):s,{width:0,height:0});super.resize(r.width,r.height),this.context instanceof Oe&&this.inputs.forEach(s=>{if(s){let n=this.layout2texCoords(s);s.positionBuffer?this.changeBufferData(s.positionBuffer,n):s.positionBuffer=this.createBuffer(n)}})}connect(e,...t){return super.connect(e,...t),this.drawBackGround2d(this.backgroundColor),this.matchInputSize&&this.resize(0,0),e}removeInput(e){this.inputs=this.inputs.filter(t=>t.node!==e),this.inputs.length===0&&this.drawBackGround2d(this.backgroundColor)}render(e){let t=this.context.ctx;if(t.clearColor(0,0,0,0),this.inputs.reduce((s,n)=>n.node.requestFrame(e)||s,!1)&&t){this.useProgram(),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let s=0;s<this.inputs.length;s++){let n=this.inputs[s];n&&(n.node.useTexture(),this.draw(n.positionBuffer))}return!0}return!1}render2d(e){if(this.inputs.forEach(t=>t.node.requestFrame(e)),this.ctx2d){this.drawBackGround2d(this.backgroundColor);for(let t=0;t<this.inputs.length;t++){let r=this.inputs[t];if(r.hidden)continue;let s=hE(r.node.width,r.node.height,r.width,r.height,r.fillMode,dt(r.rotation));this.draw2d(r.node.image,r.x+s.dx,r.y+s.dy,s.dWidth,s.dHeight,s.sx,s.sy,s.sWidth,s.sHeight)}return!0}return!1}debugLayout(e,t,r,s,n=!1){this.ctx2d&&(n&&([r,s]=[s,r]),this.ctx2d.save(),this.ctx2d.strokeStyle="red",this.ctx2d.lineWidth=2,this.ctx2d.strokeRect(e,t,r,s),this.ctx2d.restore())}getInfo(){let{totalFrames:e,x:t,y:r,width:s,height:n,name:a}=this,c=Date.now(),l=(e-this.lastInfo.totalFrames)/((c-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:r,width:s,height:n,timestamp:c,fps:l,name:a},v({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 Oe)try{(t=this.context.ctx)==null||t.deleteBuffer(e.positionBuffer)}catch(r){}})}close(){super.close(),this.removeAllInputs()}};var mE=[1,0,0,0,1,1,0,1],Mt=class extends Ye{constructor(e,t,r,s){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),s&&(this.rotation=s),e instanceof Oe)try{this.setTexBuffer(mE)}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,s,n){if(this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height),this.ctx2d.save(),this.mirror&&(this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0)),this.rotation===90?(this.ctx2d.translate(s,0),this.ctx2d.rotate(Math.PI/2),this.ctx2d.scale(n/s,s/n)):this.rotation===180?(this.ctx2d.translate(this.width,this.height),this.ctx2d.rotate(Math.PI)):this.rotation===270&&(this.ctx2d.translate(0,n),this.ctx2d.rotate(3*Math.PI/2),this.ctx2d.scale(n/s,s/n));let a=super.draw2d(e,t,r,s,n);return this.ctx2d.restore(),a}return!1}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}};var Zr=class extends Qt{constructor(e,t=4){super(t,ot);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,"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.mixNode=new Zo(this.videoContext,this.log)}listenDeviceChange(){throw new Error("Method not implemented.")}enablePrintDetail(e=2e3){this._checkId=re.run("interval",()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:e})}create2dVideoContext(){this.videoContext?this.videoContext.destroy():this.videoContext=new Fe({frameRate:15,logger:this.log,name:"mix-ctx"}),this.videoContext.create({alpha:!1})}setFps(e){this.autoSetFps=!1,this.videoContext.frameRate=e;for(let t of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])t.shouldUpdate=!1;setTimeout(()=>{var t;return(t=this.destination)==null?void 0:t.start(this.videoContext.frameRate)},500)}setFpsAuto(){var s;if(!this.autoSetFps)return;for(let n of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])n.shouldUpdate=!1;let e=null,t=0,r=!0;for(let[n,a]of this.inputLocalVideoTracks)a.profile.frameRate>t&&(t=a.profile.frameRate,e=n);for(let[n,a]of this.inputLocalScreenTracks)a.profile.frameRate>t&&(t=a.profile.frameRate,e=n,r=!1);if(e!==null){let n=r?this.cameraNodeMap.get(e):this.screenNodeMap.get(e);n&&(n.shouldUpdate=!0,n.tryVideoFrameCallback()),this.log.info("set mix fps: ",t)}else(s=this.destination)==null||s.start(this.videoContext.frameRate),this.log.info("fallback to timer, fps: ",this.videoContext.frameRate)}setMixBackground(e){this.mixNode&&(this.mixNode.backgroundColor=e)}resizeMixCanvas(e,t){var r;(r=this.mixNode)==null||r.resize(e,t)}startMix(){return f(this,null,function*(){var e;if(!this.mixNode||!this.destination)throw new Error("can't mix without necessary conditions");this.mixNode.disconnect(),this.mixNode.connect(this.destination),ci&&this.player.setCanvas(this.videoContext._canvas),this.setOutputMediaStreamTrack(this.destination.videoTrack),(e=this.manager)==null||e.changeInput(this)})}addCameraSource(e,t,r){if(this.inputLocalVideoTracks.has(e)||this.cameraNodeMap.has(e))throw new Error(`There is already a cameraSource with the same ID: ${e}`);let{mediaTrack:s}=t;if(!s)throw new Error("no mediaTrack, add cameraSource failed");let n;Je===16&&s instanceof CanvasCaptureMediaStreamTrack?n=this.videoContext.createVideoImageSource(s.canvas,{name:"cameraCanvasSource",logger:this.log}):n=this.videoContext.createVideoTrackSource(s,"cameraNodeSource"),n.resize(t.settings.width,t.settings.height),n.shouldUpdate=!1,this._connectMix(n,r,"cover"),this.inputLocalVideoTracks.set(e,t),this.cameraNodeMap.set(e,n),this.setFpsAuto()}addScreenSource(e,t,r){if(this.inputLocalScreenTracks.has(e)||this.screenNodeMap.has(e))throw new Error(`There is already a screenSource with the same ID: ${e}`);let{mediaTrack:s}=t;if(!s)throw new Error("no mediaTrack, add cameraSource failed");let n=this.videoContext.createVideoTrackSource(s,"screenNodeSource");n.resize(t.settings.width,t.settings.height),n.shouldUpdate=!1,this._connectMix(n,r),this.inputLocalScreenTracks.set(e,t),this.screenNodeMap.set(e,n),this.setFpsAuto()}addTextSource(e){let{id:t,content:r="",font:s,color:n,layout:a}=e;if(this.textNodeMap.has(t))throw new Error(`There is already a textSource with the same ID: ${t}`);let c=this.videoContext.createTextSource({content:r,font:s,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 s=this.videoContext.createVideoImageSource(t,{autoResize:!1,logger:this.log});s.resize(t.width,t.height),this._connectMix(s,r),this.imageNodeMap.set(e,s)}addVideoSource(e,t,r){if(this.videoNodeMap.has(e))throw new Error(`There is already a videoSource with the same ID: ${e}`);let s=this.videoContext.createVideoImageSource(t,{autoResize:!1,logger:this.log});s.resize(t.videoWidth,t.videoHeight),s.shouldUpdate=!1,this._connectMix(s,r),this.videoNodeMap.set(e,s)}updateCameraSource(e,t,r=null,s){let n=this.cameraNodeMap.get(e);if(n){if(r){if(Je===16&&r instanceof CanvasCaptureMediaStreamTrack)if(n instanceof Dt){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 Dt)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)}s&&n.resize(s.width,s.height),(s||r)&&this.setFpsAuto(),this._changeMixLayout(n,t)}}updateScreenSource(e,t){let r=this.screenNodeMap.get(e);r&&this._changeMixLayout(r,t)}updateTextSource(e){let{id:t,content:r,font:s,color:n,layout:a}=e,c=this.textNodeMap.get(t);c&&(E(r)||(c.content=r),E(s)||(c.font=s),E(n)||(c.color=n),c.resize(a.width,a.height),this._changeMixLayout(c,a))}updateImageSource(e,t,r){let s=this.imageNodeMap.get(e);s&&(r&&(s.image=r,s.resize(r.width,r.height)),this._changeMixLayout(s,t))}updateVideoSource(e,t,r){let s=this.videoNodeMap.get(e);if(s){if(r){let n=s.image;n instanceof HTMLVideoElement&&this.stopVideoElement(n),s.image=r,s.resize(r.videoWidth,r.videoHeight)}this._changeMixLayout(s,t)}}_connectMix(e,t,r="contain"){if(!this.mixNode)return;let{mirror:s,rotation:n}=t;e.disconnect();let a=new Mt(this.videoContext,this.log,s,n);a=e.connect(a),dt(a.rotation)&&a.resize(e.height,e.width),t.fillMode||(t.fillMode=r),a.connect(this.mixNode,t)}_changeMixLayout(e,t){if(!this.mixNode)return;let{mirror:r,rotation:s}=t,n=e.output||e;n instanceof Mt&&(E(r)||(n.mirror=r),E(s)||(n.rotation=s),dt(n.rotation)?n.resize(e.height,e.width):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 Mt&&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 Mt&&r.output.close(),r.close(),this.screenNodeMap.delete(e)),this.checkAfterRemove(!0)}removeTextSource(e){let t=this.textNodeMap.get(e);t&&(t.output instanceof Mt&&t.output.close(),t.close(),this.textNodeMap.delete(e)),this.checkAfterRemove()}removeImageSource(e){let t=this.imageNodeMap.get(e);t&&(t.output instanceof Mt&&t.output.close(),t.close(),this.imageNodeMap.delete(e)),this.checkAfterRemove()}removeVideoSource(e){let t=this.videoNodeMap.get(e);t&&(t.output instanceof Mt&&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(),re.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();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 gc=$s();if(typeof navigator!="undefined"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:gc,exposeOrigin:!0,permittedOrigins:["*"]})}catch(o){}var pE=function(o){return f(this,null,function*(){let i=null,e=gE(o);y.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let t=yield navigator.mediaDevices.getDisplayMedia(e);o.systemAudio&&t.getAudioTracks().length===0&&(Oo&<<74||xe||ae)&&y.warn("Your browser not support capture system audio");let r=t.getVideoTracks()[0];if(r){if(o.frameRate)try{yield r.applyConstraints({frameRate:{min:o.frameRate,ideal:o.frameRate},width:o.width,height:o.height})}catch(s){y.warn(`screen applyConstraints failed: ${s}`)}o.captureElement&&(yield fE(r,o.captureElement))}if(o.audio){let s=_E(o);y.info(`getUserMedia with constraints: ${JSON.stringify(s)}`),i=yield navigator.mediaDevices.getUserMedia(s),t.addTrack(i.getAudioTracks()[0])}return t})};function fE(o,i){return f(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&ne(o.cropTo))try{if(!(((e=o.getCaptureHandle())==null?void 0:e.handle)===gc))return;let r=yield CropTarget.fromElement(i);yield o.cropTo(r)}catch(t){y.warn(`cropTo target failed ${t}`)}})}function _E(o){let i={echoCancellation:o.echoCancellation,autoGainControl:o.autoGainControl,noiseSuppression:o.noiseSuppression,sampleRate:o.sampleRate,channelCount:o.channelCount};return E(o.microphoneId)||(i.deviceId=o.microphoneId),{audio:i,video:!1}}function gE(o){let i={preferCurrentTab:o.preferDisplaySurface==="current-tab"||!!o.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:xe?{max:o.width}:{ideal:o.width,max:o.width},height:xe?{max:o.height}:{ideal:o.height,max:o.height},frameRate:o.frameRate,displaySurface:o.preferDisplaySurface||"monitor"};if(i.video=e,o.systemAudio){let{echoCancellation:t=!0,noiseSuppression:r=!1,autoGainControl:s=!1}=o;i.audio={echoCancellation:t,noiseSuppression:r,autoGainControl:s,sampleRate:48e3}}return i}var gp=pE;var Ze=class extends Be{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 gc===((t=(e=this.mediaTrack)==null?void 0:e.getCaptureHandle())==null?void 0:t.handle)}catch(r){return}}capture(u){return f(this,arguments,function*({systemAudio:e=!1,autoGainControl:t,echoCancellation:r,noiseSuppression:s,audioTrack:n,videoTrack:a,captureElement:c,preferDisplaySurface:l}){try{let h;return a||n?(h=new MediaStream,a&&h.addTrack(a),n&&h.addTrack(n)):(h=yield gp({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:t,echoCancellation:r,noiseSuppression:s,captureElement:c,preferDisplaySurface:l}),this.sourceTrack=h.getVideoTracks()[0]),yield this.setInputMediaStreamTrack(h.getVideoTracks()[0]),h}catch(h){throw this.log.error(`getDisplayMedia error observed ${h}`),h instanceof N?h:new N({code:I.INITIALIZE_FAILED,name:h.name,message:h.message})}})}switchDevice(e){return f(this,null,function*(){throw new Error("Method not implemented.")})}};D([st(function(e){this.setContentHint(e.contentHint||"detail")})],Ze.prototype,"capture",1);var Ii=class extends Ct{constructor(i){super(i),this._log.id=`s-${this._log.id}`}addAudioProcessor(i,e,t,r){this.pipeline.silentNode.setNode(t),this.pipeline.mixNode.setNode(e),this.pipeline.aec.setNode(r),this.enableTrackAEC(!1)}removeAudioProcessor(i,e,t,r){this.pipeline.aec.node===r&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode(),this.enableTrackAEC(!0))}};var TE='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}});',ku;function En(o,i=48e3,e=1,t){return f(this,null,function*(){let r=Ee("dump");ku||(ku=ji(r,URL.createObjectURL(new Blob([TE],{type:"application/javascript"})))),yield ku;let s=r.sampleRate,n=new AudioWorkletNode(r,"dumper",{numberOfInputs:o.length,numberOfOutputs:0,processorOptions:{sourceSampleRate:s,targetSampleRate:i}});return n.channelCountMode="explicit",n.channelCount=e,t&&n.port.postMessage({port:t},[t]),o.forEach((a,c)=>a.connect(n,0,c)),new ReadableStream({start(a){n.port.onmessage=c=>{a.enqueue(c.data)}},cancel(){o.forEach(a=>a.disconnect(n)),n.port.close()}})})}var Tc=class extends Ga{constructor(e){super();this.room=e;d(this,"_localAudioTrack");d(this,"_localScreenAudioTrack");d(this,"log",y.createLogger({id:"am"}));d(this,"denoiser");d(this,"voiceChanger");d(this,"mixChangedDebounce");d(this,"audioProcessor");d(this,"encodePipeline",[]);d(this,"decodePipeline",[]);d(this,"getPCMAbortCtrlMap",new Map);d(this,"audioFrameEventConfigMap",new Map);d(this,"audioReferenceMap",new Map);d(this,"isLocalAudioNeedAudioProcess",!1);d(this,"isScreenAudioNeedAudioProcess",!1);e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.installEvent()}get _localAudioPipline(){var e;return(e=this._localAudioTrack)==null?void 0:e.pipeline}get _localScreenAudioPipeline(){var e;return(e=this._localScreenAudioTrack)==null?void 0:e.pipeline}dump(e){var u,h;if(!this._localAudioTrack)return;let t=[],r=[];(u=this._localAudioPipline)!=null&&u.source.node&&(t.push(this._localAudioPipline.source.node),r.push("mic")),(h=this._localAudioPipline)!=null&&h.denoiser.node&&(t.push(this._localAudioPipline.denoiser.node),r.push("mic-processed")),this.mixWeight>1&&(t.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),r.push("mix")),this.log.info(`dump audio track ${r}, duration: ${e}`);let s=new AbortController,n=[],a=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),s.abort("timeout")},e*1e3),c=()=>{for(let m=0;m<r.length;m++){let g=URL.createObjectURL(new Blob(n[m])),A=document.createElement("a");A.href=g,A.download=`${r[m]}.pcm`,A.style.display="none",document.body.appendChild(A),A.click(),URL.revokeObjectURL(g),A.remove()}clearTimeout(a),s.abort("download")},l=En(t).then(m=>m.pipeTo(new WritableStream({write(g){g.forEach((A,_)=>n[_]=n[_]?n[_].concat(A[0]):[A[0]])}}),s).catch(g=>c));return{then:l.then.bind(l),download:c}}getPCM(e,t){var M,K,G;if(typeof WritableStream=="undefined"){this.log.warn("getPCM failed: browser not support WritableStream");return}let{enable:r,sampleRate:s=48e3,channelCount:n=1,port:a}=(t===""?this.audioFrameEventConfigMap.get(""):this.audioFrameEventConfigMap.get(t)||this.audioFrameEventConfigMap.get("*"))||{};if(!r)return;this.log.info(`getPCM ${t||"local"}`);let c=Math.floor(s*.04),l=new Float32Array(c),u=new Float32Array(c),h,m,g=0,A=new AbortController,_=t===""?(M=this._localAudioTrack)==null?void 0:M.mediaTrack:(G=(K=this.room)==null?void 0:K.remotePublishedUserMap.get(t))==null?void 0:G.remoteAudioTrack.mediaTrack;if(!_){this.log.info(`getPCM failed: ${t||"local"} has no audio track`);return}let T=Ee().createMediaStreamSource(new MediaStream([_]));return En([T],s,n,a).then(ee=>ee.pipeTo(new WritableStream({write(_e){_e[0][0]&&(g+_e[0][0].length>c?(l.set(_e[0][0].subarray(0,c-g),g),h=_e[0][0].subarray(c-g),_e[0][1]&&(u.set(_e[0][1].subarray(0,c-g),g),m=_e[0][1].subarray(c-g)),g+=c-g):(h&&(l.set(h,g),g+=h.length,h=void 0),m&&(u.set(m,g),m=void 0),l.set(_e[0][0],g),_e[0][1]&&u.set(_e[0][1],g),g+=_e[0][0].length),g>=c&&(g=0,e({userId:t,sampleRate:s,channelCount:n,data:n===1?l:[l,u]}),l=new Float32Array(c),u=new Float32Array(c)))}}),A).catch(_e=>this.log.warn(`stop getPCM reason:${_e}`))),A}get hasScreenAudioTrack(){return!E(this._localScreenAudioTrack)}get hasAudioTrack(){return!E(this._localAudioTrack)}changeInput(e){if(e instanceof Ii)return this._localScreenAudioTrack=e,this.isScreenAudioNeedAudioProcess&&this.audioProcessor&&(e.addAudioProcessor(...this.audioProcessor),this.audioReferenceMap.forEach((t,r)=>{e.mixAudioReference(t,r)})),e.pipeline.connect(),this.mixOnChange();if(e instanceof Ct)return this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),this.isLocalAudioNeedAudioProcess&&this.audioProcessor&&(e.addAudioProcessor(...this.audioProcessor),this.audioReferenceMap.forEach((t,r)=>{e.mixAudioReference(t,r)})),e.pipeline.connect(),this.mixOnChange();if(e instanceof Yt)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 Ii?delete this._localScreenAudioTrack:e instanceof Ct?delete this._localAudioTrack:e instanceof Yt}addDenoiser(e){var t;this.denoiser=e,(t=this._localAudioTrack)==null||t.addDenoiser(e)}addAudioProcessor(e,t,r,s){var n;this.audioProcessor=[e,t,r,s],this.isLocalAudioNeedAudioProcess&&this._localAudioTrack&&(this._localAudioTrack.addAudioProcessor(...this.audioProcessor),this.audioReferenceMap.forEach((a,c)=>{var l;(l=this._localAudioTrack)==null||l.mixAudioReference(a,c)})),this.isScreenAudioNeedAudioProcess&&this._localScreenAudioTrack&&((n=this._localScreenAudioTrack)==null||n.addAudioProcessor(...this.audioProcessor),this.audioReferenceMap.forEach((a,c)=>{var l;(l=this._localScreenAudioTrack)==null||l.mixAudioReference(a,c)}))}removeDenoiser(e){var t;delete this.denoiser,(t=this._localAudioTrack)==null||t.removeDenoiser(e)}addVoiceChanger(e,t){var r;this.voiceChanger=[e,t],(r=this._localAudioTrack)==null||r.pipeline.voiceChanger.setNode(e,t)}removeVoiceChanger(){var e;delete this.voiceChanger,(e=this._localAudioTrack)==null||e.pipeline.voiceChanger.deleteNode()}removeAudioProcessor(e,t,r,s){var n;delete this.audioProcessor,(n=this._localAudioTrack)==null||n.removeAudioProcessor(e,t,r,s)}destroy(){this.close(),this.audioReferenceMap.clear(),this.getPCMAbortCtrlMap.forEach(e=>e==null?void 0:e.abort("destroy")),this.getPCMAbortCtrlMap.clear(),this.audioFrameEventConfigMap.clear(),this.uninstallEvent()}addEncodeProcessor({processor:e,type:t}){var r;this.encodePipeline.includes(e)||(this.encodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}addDecodeProcessor({processor:e,type:t}){var r;this.decodePipeline.includes(e)||(this.decodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}handleLocalTrackStarted({room:e,userId:t}){var s;if(e!==this.room||this.getPCMAbortCtrlMap.get(t))return;let r=this.getPCM(n=>{var a;(a=this.room)==null||a.emit("audio-frame",n)},"");this.getPCMAbortCtrlMap.set(t,r),this.getPCMAbortCtrlMap.get(t)&&((s=this._localAudioTrack)==null||s.on("input-media-track-changed",()=>{let n=this.getPCMAbortCtrlMap.get(t);n&&(n.abort("inputMediaTrackChanged"),n=this.getPCM(a=>{var 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(s=>{var n;(n=this.room)==null||n.emit("audio-frame",s)},t);this.getPCMAbortCtrlMap.set(t,r)}}handleRemoteTrackStopped({room:e,userId:t}){if(e!==this.room)return;let r=this.getPCMAbortCtrlMap.get(t);r&&(r.abort("stopRemoteAudio"),this.getPCMAbortCtrlMap.delete(t))}installEvent(){S.on("113",this.handleLocalTrackStarted,this),S.on("114",this.handleLocalTrackStopped,this),S.on("115",this.handleRemoteTrackStarted,this),S.on("116",this.handleRemoteTrackStopped,this)}uninstallEvent(){S.off("113",this.handleLocalTrackStarted),S.off("114",this.handleLocalTrackStopped),S.off("115",this.handleRemoteTrackStarted),S.off("116",this.handleRemoteTrackStopped)}updateAudioReference({type:e,audioReference:t,refId:r,volume:s}){if(e==="add"){if(this.audioReferenceMap.get(r)||!t||(this.audioReferenceMap.set(r,t),!this.audioProcessor))return;this.mixAudioReference(t,r)}else if(e==="remove")this.audioReferenceMap.get(r)&&(this.audioReferenceMap.delete(r),this.unMixAudioReference(r));else if(e==="updateVolume"){if(!this.audioProcessor||E(s))return;this.setAudioReferenceVolume(r,s)}}};function Ec(o=30,i=2){return Y((e,t)=>function(...r){return new Promise((s,n)=>{let a=setTimeout(()=>{let c=new N({code:I.API_CALL_TIMEOUT,message:`checkPendingPromise ${t}() timeout ${o}s`});y.warn(c),i===2?n(c):i===1&&s()},o*1e3);e.apply(this,r).then(s,n).finally(()=>{clearTimeout(a)})})})}var Ai=class Ai extends Gr{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",nt(me(this,Ai.STATE_SUBSCRIBE)));this.tinyId=t.tinyId,this.availableState=new $(`${t.userId}-${this.mediaType}-available`,"remote-track-available"),this.remotePublishState=new $(`${t.userId}-${this.mediaType}-remote-publish`,"remote-track-publish"),ue(zl(me(this,$.STATECHANGED),me(this.remotePublishState,$.STATECHANGED)),_n(()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing)),be(c=>{this.availableState.state!==(c?$.ON:$.OFF)&&(this.availableState.state=c?$.ON:$.OFF),this.updatePlayingState(c)}));let s=ue(me(this.player,he.ERROR),Si(c=>c.code===MediaError.MEDIA_ERR_DECODE)),n=ue(pn(5e3),Si(()=>this.ignoreDecodeError||!this.isSubscribed||!this.isPlayCalled||!this.stat.bytesReceived?!1:this.player.isPlaying||(this.kind===p.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)?(this.reportDecodeResult(!0),!1):!0)),a=ue(Ql(s,n),He(me(this,$.INIT)));ue(this._triggerCheckDecodeSubject,Si(()=>!this.ignoreDecodeError),zr(a),be(c=>{this.reportDecodeResult(!1,c)}))}setMute(e){this.isRemotePublished&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.isRemotePublished&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}checkDecodeResult(){this._triggerCheckDecodeSubject.next(!0)}waitHasMediaTrack(){return new Promise(e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)})}get ignoreDecodeError(){var t,r;return(((r=(t=this.room)==null?void 0:t.networkQuality)==null?void 0:r.downlinkNetworkQuality)||0)>3||this.player.isInAutoPlayFailedState}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===Ai.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===$.ON}get isNeedPlay(){return this.isAvailable&&this.isPlayCalled}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}reportDecodeResult(e,t){var s,n;let r=this.kind===p.AUDIO;if(b[e?"addSuccessEvent":"addFailedEvent"]({key:r?504700:514702}),!r){let a=((s=this.room)==null?void 0:s.downlinkVideoCodec.toUpperCase())||"H264";b[e?"addSuccessEvent":"addFailedEvent"]({key:qs[`DECODE_${a}_RESULT`]}),e||this.log.warn(`${(n=this.room)==null?void 0:n.downlinkVideoCodec} decode failed`)}e||(b.addEnum({key:r?504701:514703,value:Hs()}),se.uploadEvent({log:`stat-decode-failed-${this.kind}-${Lr()||Hi()}`,userId:this.room.userId}),this._log.warn(`decode failed: isPlaying: ${this.player.isPlaying} ${this.kind===p.AUDIO?`audioLevel: ${this.getAudioLevel()}`:`framesDecoded: ${this.stat.framesDecoded>0}`}`),this.emit("decode-failed",{error:t}))}updatePlayingState(e){if(this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.isRemotePublished||!this.outMediaTrack)){this.log.info(`abort play, isSubscribed: ${this.isSubscribed} isAvailable: ${this.isRemotePublished} hasTrack: ${!!this.outMediaTrack} `);return}super.updatePlayingState(e)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.remotePublishState.state=this.isRemotePublished?$.ON:$.OFF}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};d(Ai,"STATE_SUBSCRIBE","subscribe"),D([Ec(5,1)],Ai.prototype,"waitHasMediaTrack",1),D([Te($.INIT,Ai.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),S.emit(C.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),pt(521716,!1)],Ai.prototype,"subscribe",1),D([Te(Ai.STATE_SUBSCRIBE,$.INIT,{sync:!0,success(){this.log.info("unsubscribed"),S.emit(C.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],Ai.prototype,"unsubscribe",1);var Ko=Ai;var Yt=class extends Ko{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 $r.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}decodeFrame(e){if(!this.manager)return e;let t=e;for(let r of this.manager.decodePipeline)if(r&&(t=r({frame:t,track:this}),!t))return;return t}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get isRemotePublished(){return this.user.muteState.audioAvailable}};function SE(o){return[15,30,45,60].reduce((e,t)=>Math.abs(t-o)<Math.abs(e-o)?t:e)}var Ci=class extends Ko{constructor(e,t,r=4){super(e,t,r);d(this,"mediaType",4);d(this,"source");d(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.videoManager,this.once("first-video-frame",s=>{this.room.emit("first-video-frame",s)})}play(e,t){return(de(t==null?void 0:t.canvasRender)?t.canvasRender:Je===17)&&!this.source&&this.useCanvasPlayer(),super.play(e,t).then(()=>{this.player.calculateStat()})}useCanvasPlayer(){if(this.log.info(`useCanvasPlayer(), has element:${!!this.player.element}`),!this.player.element)return;let e=new Fe({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});let t=new Qr(e,{name:"remotePlayer",logger:this.log});this.source=e.createVideoPlayerSource(this.player),this.source.connect(t),this.player.setCanvas(e._canvas),Hr()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let t=this.decodeFPS,r=SE(t);if(!q(t)||t<=0){this.log.debug(`updateCanvasPlayerFPS() ignore decoder: ${t} `);return}if(r===e.frameRate){this.log.debug(`updateCanvasPlayerFPS() ignore ClosestFPS ${r} == ${e.frameRate}`);return}this.log.info(`updateCanvasPlayerFPS() decoder: ${t}, closest: ${r}, current: ${e.frameRate}`),e.frameRate=r}get decodeFPS(){var n;let{msg_video_status:e}=((n=this.room.heartbeatReport)==null?void 0:n.msg_down_stream_info.find(a=>a.msg_user_info.str_identifier===this.userId))||{},t=this.mediaType===2?7:this.isSmall?3:2;if(!e||e.length===0)return 0;let r=e.find(a=>a.uint32_video_stream_type===t);return(r==null?void 0:r.uint32_video_dec_fps)||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),super.stop()}decodeFrame(e){if(!this.manager)return e;for(let t of this.manager.decodePipeline)if(t&&(e=t({frame:e,track:this}),!e))return;return e}get isBig(){return this.mediaType===4}get isSmall(){return this.mediaType===8}changeType(e){this.room.changeType(e,this.user)}get isRemotePublished(){return this.user.muteState.videoAvailable}setMirror(e){e==="publish"||e==="both"||super.setMirror(e)}onDecodeDowngradeStateChanged(e){this.emit("decode-downgrade-state-changed",e)}},es=class extends Ci{constructor(e,t){super(e,t,2);d(this,"mediaType",2);d(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}};var ts=new Map;S.on(C.JOIN_SUCCESS,({room:o})=>{Ae(o.userId,{eventId:32788})});S.on(C.LEAVE_START,({room:o})=>{Ae(o.userId,{eventId:32789})});S.on(C.LOCAL_TRACK_PUBLISHED,({track:o})=>{if(o.room){let i=32769;o.mediaType===4?i=32768:o.mediaType===2&&(i=32805),Ae(o.room.userId,{eventId:i})}});S.on(C.LOCAL_TRACK_UNPUBLISHED,({track:o})=>{if(o.room){let i=32771;o.mediaType===4?i=32770:o.mediaType===2&&(i=32806),Ae(o.room.userId,{eventId:i})}});S.on(C.TRACK_MUTED,({track:o})=>{o.room&&(o.kind===p.AUDIO?Ae(o.room.userId,{eventId:o.isRemote?32785:32772,remoteUserId:o.isRemote?o.userId:void 0}):Ae(o.room.userId,{eventId:o.isRemote?32784:32773,remoteUserId:o.isRemote?o.userId:void 0}))});S.on(C.TRACK_UNMUTED,({track:o})=>{o.room&&(o.kind===p.AUDIO?Ae(o.room.userId,{eventId:o.isRemote?32787:32774,remoteUserId:o.isRemote?o.userId:void 0}):Ae(o.room.userId,{eventId:o.isRemote?32786:32775,remoteUserId:o.isRemote?o.userId:void 0}))});S.on(C.REMOTE_TRACK_SUBSCRIBED,({track:o})=>{o.room&&(o.mediaType===1&&Ae(o.room.userId,{eventId:32777,remoteUserId:o.userId}),o.mediaType===4&&Ae(o.room.userId,{eventId:32776,remoteUserId:o.userId}),o.mediaType===8&&Ae(o.room.userId,{eventId:32803,remoteUserId:o.userId}))});S.on(C.REMOTE_TRACK_UNSUBSCRIBED,({track:o})=>{o.room&&(o.mediaType===1&&Ae(o.room.userId,{eventId:32779,remoteUserId:o.userId}),o.mediaType===4&&Ae(o.room.userId,{eventId:32778,remoteUserId:o.userId}),o.mediaType===8&&Ae(o.room.userId,{eventId:32804,remoteUserId:o.userId}))});S.on(C.SWITCH_DEVICE_SUCCESS,({track:o})=>{o.room&&Ae(o.room.userId,{eventId:o.kind===p.VIDEO?32780:32781})});S.on(C.LOCAL_TRACK_REPLACED,({track:o})=>{o.room&&Ae(o.room.userId,{eventId:o.kind===p.VIDEO?32782:32783})});S.on(C.SIGNAL_CONNECTION_STATE_CHANGED,({room:o,prevState:i,state:e})=>{let t;switch(e){case"CONNECTED":i==="RECONNECTING"?t=32795:t=32791;break;case"DISCONNECTED":i==="RECONNECTING"?t=32796:t=32790;break;case"RECONNECTING":t=32794;break}t&&Ae(o.userId,{eventId:t})});S.on(C.PEER_CONNECTION_STATE_CHANGED,({room:o,prevState:i,state:e,remoteUserId:t})=>{let r=!!t,s;switch(e){case"CONNECTED":i==="RECONNECTING"?s=r?32801:32798:s=r?32793:32792;break;case"DISCONNECTED":i==="RECONNECTING"&&(s=r?32802:32799);break;case"RECONNECTING":s=r?32800:32797;break}s&&Ae(o.userId,{eventId:s,remoteUserId:t})});S.on(C.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({implementation:o,userId:i,remoteUserId:e,codec:t,isHWCodec:r,prevImplementation:s,streamType:n})=>{let a=r?1:0;s||(a=r?3:2);let 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),Ae(i,l),b.addEnum({key:e?514701:513701,value:a}),b.addEnum({key:e?514700:513700,value:c})});S.on(C.LOCAL_TRACK_RECAPTURE,({track:o,error:i})=>{if(o.userId){let e={eventId:2003,param1:0};o.kind===p.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType=o.streamType==="auxiliary"?7:2,i&&(e.param1=8)),Ae(o.userId,e)}});function Ae(o,i){let e=w(v({},i),{timestamp:fs()});ts.has(o)?ts.get(o).push(e):ts.set(o,[e])}function Tp(o){if(ts.has(o)){let i=ts.get(o).map(e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,uint32_param1:e.param1,uint32_param2:e.param2,uint32_video_stream_type:e.streamType}));return ts.delete(o),i}return[]}function Ep(...o){return Y((i,e)=>function(...t){return IE.call(this,o,t,e,this._name),i.apply(this,t)})}function IE(o,i,e,t){try{if(Se(o))for(let r=0;r<o.length;r++)Sc.call(this,{rule:o[r],value:i[r],key:o[r].name,fnName:e,className:t});else Sc.call(this,{rule:o,value:i[0],key:o.name,fnName:e,className:t})}catch(r){throw y.error(r),r}}function Sc({rule:o,value:i,key:e,fnName:t,className:r}){if(E(i)){if(o.required)throw new N({code:I.INVALID_PARAMETER,message:P({key:L.INVALID_PARAMETER_REQUIRED,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(E(o.defaultValue))return;i=o.defaultValue}if(Array.isArray(o.type)){let a=!1;for(let c=0;c<o.type.length;c++)o.type[c]===null&&i===null&&(a=!0),ne(o.type[c])&&i instanceof o.type[c]&&(a=!0),te(o.type[c])&&Re(i)===o.type[c].toLowerCase()&&(a=!0);if(!a)throw new N({code:I.INVALID_PARAMETER,message:P({key:L.INVALID_PARAMETER_TYPE,data:{key:e,rule:{type:o.type.map(c=>Mr(c)?fo(c):te(c)?c:Re(c))},fnName:t,value:i},link:{className:r,fnName:t}})})}else if(!E(o.type)&&Re(i)!==o.type)throw new N({code:I.INVALID_PARAMETER,message:P({key:L.INVALID_PARAMETER_TYPE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(o.allowEmpty===!1){let a=q(i)&&(i===0||Number.isNaN(i)),c=te(i)&&i.trim()==="";if(a||c)throw new N({code:I.INVALID_PARAMETER,message:P({key:L.INVALID_PARAMETER_EMPTY,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})})}if(o.notLessThanZero&&q(i)&&i<0)throw new N({code:I.INVALID_PARAMETER,message:P({key:L.CANNOT_LESS_THAN_ZERO,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(!E(o.min)&&q(i)&&i<o.min)throw new N({code:I.INVALID_PARAMETER,message:P({key:L.INVALID_PARAMETER_MIN,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(!E(o.max)&&q(i)&&i>o.max)throw new N({code:I.INVALID_PARAMETER,message:P({key:L.INVALID_PARAMETER_MAX,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(te(o.instanceOf)){if(!i||i._name!==o.instanceOf)throw new N({code:I.INVALID_PARAMETER,message:P({key:L.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})})}else if(ne(o.instanceOf)&&!(i instanceof o.instanceOf))throw new N({code:I.INVALID_PARAMETER,message:P({key:L.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(o.values&&!o.values.includes(i))throw new N({code:I.INVALID_PARAMETER,message:P({key:L.INVALID_PARAMETER_RANGE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});let{properties:s}=o;ze(s)&&ft(i)&&Object.keys(s).forEach(a=>{Sc.call(this,{rule:s[a],value:i&&i[a],key:`${e}.${a}`,fnName:t,className:r})});let{arrayItem:n}=o;ze(n)&&Se(i)&&i.forEach((a,c)=>{Sc.call(this,{rule:n,value:a,key:`${e}[${c}]`,fnName:t,className:r})}),ne(o.validate)&&o.validate.call(this,i,e,t,r,this)}var Sp=Ge(tt(),1);var Ic=class extends Sp.EventEmitter{constructor(e,t,r="userId"){super();this.mySelfId=e;this._log=t;this.key=r;d(this,"userMap",new Map);d(this,"remotePublishedUserMap",new Map)}get hasRobotUser(){return!![...this.remotePublishedUserMap.values()].find(e=>e.isRobot)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:r,tinyId:s,role:n}=e;if(this.userMap.has(t))return;let a={userId:r,tinyId:s,role:n===20?"anchor":"audience"};this.userMap.set(t,a),this.emit("1",a)}deleteUser(e,t){let r=this.userMap.get(e);if(!r)return;let s=`peer leave [${e}]`;E(t)||(s+=`:${gd[t]}`),this._log.info(s);let n=this.remotePublishedUserMap.get(e);if(n){let a=n.muteState;n.flag=0,this.emit("5",n.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:a,muteState:n.muteState,flag:0})}this.userMap.delete(e),this.emit("2",r.userId)}setUserList(e){this.userMap.forEach(t=>{e.findIndex(r=>r[this.key]===t[this.key])<0&&this.deleteUser(t[this.key],0)}),e.forEach(t=>{!this.userMap.has(t[this.key])&&t[this.key]!==this.mySelfId&&this.addUser(t)})}addRemotePublishedUser(e){this.remotePublishedUserMap.has(e[this.key])||this.remotePublishedUserMap.set(e[this.key],e)}deleteRemotePublishedUser(e){this.remotePublishedUserMap.has(e)&&this.remotePublishedUserMap.delete(e)}setRemotePublishedUserList(e){this.remotePublishedUserMap.forEach(t=>{let r=t[this.key];if(e.findIndex(s=>s[this.key]===t[this.key])<0){this._log.info(`remote [${r}] unpublish`);let s=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(r),this.emit("6",{prevMuteState:s,muteState:t.muteState,flag:0})}}),e.forEach(t=>{var u;let r=t[this.key];if(r===this.mySelfId)return;let{flag:s,userId:n,tinyId:a}=t,c=xi(s,n),l=(u=this.remotePublishedUserMap.get(r))==null?void 0:u.muteState;if(l){let h=this.remotePublishedUserMap.get(r);h&&h.flag!==s&&(h.flag=s,this._log.info(`remote publish updated: ${JSON.stringify(h.muteState)}`),this.emit("6",{prevMuteState:l,muteState:c,flag:s}))}else this._log.info(`remote publish. state: ${JSON.stringify(c)}`),this.addUser({userId:n,tinyId:a,role:20}),this.emit("3",t),this.emit("6",{prevMuteState:xi(0,n),muteState:c,flag:s})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function Ou({timesInSecond:o,maxSizeInSecond:i,getSize:e}){return Y((t,r)=>{let s=new WeakMap;return S.on(C.ROOM_DESTROY,({room:n})=>s.delete(n)),function(...n){let a=s.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},s.set(this,a)),a.timestamp===0?a.timestamp=Date.now():Date.now()-a.timestamp>1e3&&(a.timestamp=Date.now(),a.callCountInSecond=0,a.totalSizeInSecond=0),e&&(a.totalSizeInSecond+=e(...n)),a.timestamp!==0&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=o||a.totalSizeInSecond>i))throw new N({code:I.INVALID_OPERATION,message:P({key:L.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=o,isSize:a.totalSizeInSecond>i,name:r,timesInSecond:o,maxSizeInSecond:i}})});a.callCountInSecond++,t.call(this,...n)}})}var AE="2025-07-22 14:45:11",Ip=!0,Ap=function(){var o;if(Ip){Ip=!1,y.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${ii}/en/index.html`),console.info(`* Changelog: ${ii}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),y.info("TRTC Web SDK Version:",we),Wt||y.debug("Build Time:",AE);let i=`UA: ${navigator.userAgent}
|
|
52
|
+
} `;var Yr=class extends ${constructor(e){super();d(this,"frameRate");d(this,"_canvas");d(this,"log");d(this,"hasAlpha",!1);d(this,"name");d(this,"error");this.name=e.name,this.log=e.logger.createChild({id:`vc-${this.name}`}),this.frameRate=e.frameRate}set width(e){this._canvas&&(this._canvas.width=e)}get width(){var e;return((e=this._canvas)==null?void 0:e.width)||0}set height(e){this._canvas&&(this._canvas.height=e)}get height(){var e;return((e=this._canvas)==null?void 0:e.height)||0}setSize(e,t){this._canvas&&(this._canvas.width=e,this._canvas.height=t)}createVideoTrackSource(e,t){return new Dt(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new Qo(this,e)}createVideoImageSource(e,t){return new gn(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new Tn(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}createTextSource(e,t){return new _c(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}};d(Yr,"_ids",0);var uE={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},Yo=class Yo extends Yr{constructor(){super(...arguments);d(this,"defaultProgam");d(this,"defaultVShader");d(this,"defaultFShader");d(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${Yr._ids++}`),this.ctx=this._canvas.getContext("webgl2",uE),!this.ctx)throw new N({code:I.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,dE),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,lE),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,b.addFailedEvent({key:512702,error:e})),this.disconnect(),this.log.info(`video context destroy${t}`?`: ${t}`:""),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),e}set width(e){var t;(t=this.ctx)==null||t.viewport(0,0,e,this.height),super.width=e}set height(e){var t;(t=this.ctx)==null||t.viewport(0,0,this.width,e),super.height=e}setSize(e,t){var r;(r=this.ctx)==null||r.viewport(0,0,e,t),super.setSize(e,t)}createShader(e,t){let r=this.ctx,s=r.createShader(e);return r.shaderSource(s,t),r.compileShader(s),s}createProgram(e,t){let r=this.ctx,s=r.createProgram();return r.attachShader(s,e),r.attachShader(s,t),r.linkProgram(s),r.getProgramParameter(s,r.LINK_STATUS)||this.log.error(r.getProgramInfoLog(s)),s}};d(Yo,"UNAVAILABLE","unavailable"),D([Te($.INIT,"created",{sync:!0,fail(e){this.log.error("video gl context create failed",e.cause),b.addFailedEvent({key:512700,error:e.cause||e})},success(){this.log.info("video context created use webgl"),b.addSuccessEvent({key:512700})}})],Yo.prototype,"create",1),D([Te("created",$.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(Yo.UNAVAILABLE,e),this.removeAllListeners()}})],Yo.prototype,"destroy",1);var Oe=Yo,Fe=class extends Yr{constructor(){super(...arguments);d(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${Yr._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!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,b.addFailedEvent({key:512703,error:e})),this.disconnect(),this.log.info(`video context destroy ${t?`: ${t}`:""}`),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners(),b.addSuccessEvent({key:512703})}};D([Te($.INIT,"created",{sync:!0,fail(e){this.log.error("video 2d context create failed",e.cause),b.addFailedEvent({key:512701,error:e.cause||e})},success(){this.log.info("video context created use 2d"),b.addSuccessEvent({key:512701})}})],Fe.prototype,"create",1),D([Te("created",$.INIT,{ignoreError:!0,sync:!0})],Fe.prototype,"destroy",1);function hE(o,i,e,t,r,s=!1){s&&([e,t]=[t,e]);let n={sWidth:o,sHeight:i,dWidth:e,dHeight:t,sx:0,sy:0,dx:0,dy:0};if(o===0||i===0)return n;switch(r){case void 0:case"fill":break;case"contain":{let a=Math.min(e/o,t/i);n.dWidth=o*a,n.dHeight=i*a,n.dx=(e-n.dWidth)/2,n.dy=(t-n.dHeight)/2;break}case"cover":{let a=Math.max(e/o,t/i),c=e/a,l=t/a;n.sx=(o-c)/2,n.sy=(i-l)/2,n.sWidth=c,n.sHeight=l;break}}return n}var Mu=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}},Zo=class extends Ye{constructor(e,t){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,matchInputSize:!1,logger:t});d(this,"inputs",[]);d(this,"backgroundColor","black")}addInput(e,t){let r=0,s=this.inputs.length;for(;r<s;){let a=Math.floor((r+s)/2);if(this.inputs[a].layout.zIndex<t.zIndex)r=a+1;else if(this.inputs[a].layout.zIndex>t.zIndex)s=a;else throw new Error(`input already exists at zIndex ${t.zIndex}`)}let n=new Mu(e,t);this.inputs.splice(r,0,n)}changeInputLayout(e,t){let r=this.inputs.findIndex(A=>A.node===e);if(r<0)return;let{x:s,y:n,width:a,height:c,zIndex:l,fillMode:u,rotation:h,hidden:m}=t;if(!E(l)&&this.inputs.some(A=>A.layout.zIndex===l&&A.node!==e))throw new Error(`input already exists at zIndex ${t.zIndex}`);let g=this.inputs[r];E(s)||(g.layout.x=s),E(n)||(g.layout.y=n),E(a)||(g.layout.width=a),E(c)||(g.layout.height=c),E(h)||(g.layout.rotation=h),E(m)||(g.layout.hidden=m),u&&(g.layout.fillMode=u),!E(l)&&l!==g.layout.zIndex&&(g.layout.zIndex=l,this.inputs.sort((A,_)=>A.layout.zIndex-_.layout.zIndex))}hasInput(e){return this.inputs.some(t=>t.node===e)}hasNoInput(){return this.inputs.length===0}resize(e,t){if(!this.matchInputSize){super.resize(e,t);return}let r=this.inputs.reduce((s,n)=>n?Object.assign(s,{width:Math.max(s.width,n.right),height:Math.max(s.height,n.bottom)}):s,{width:0,height:0});super.resize(r.width,r.height),this.context instanceof Oe&&this.inputs.forEach(s=>{if(s){let n=this.layout2texCoords(s);s.positionBuffer?this.changeBufferData(s.positionBuffer,n):s.positionBuffer=this.createBuffer(n)}})}connect(e,...t){return super.connect(e,...t),this.drawBackGround2d(this.backgroundColor),this.matchInputSize&&this.resize(0,0),e}removeInput(e){this.inputs=this.inputs.filter(t=>t.node!==e),this.inputs.length===0&&this.drawBackGround2d(this.backgroundColor)}render(e){let t=this.context.ctx;if(t.clearColor(0,0,0,0),this.inputs.reduce((s,n)=>n.node.requestFrame(e)||s,!1)&&t){this.useProgram(),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let s=0;s<this.inputs.length;s++){let n=this.inputs[s];n&&(n.node.useTexture(),this.draw(n.positionBuffer))}return!0}return!1}render2d(e){if(this.inputs.forEach(t=>t.node.requestFrame(e)),this.ctx2d){this.drawBackGround2d(this.backgroundColor);for(let t=0;t<this.inputs.length;t++){let r=this.inputs[t];if(r.hidden)continue;let s=hE(r.node.width,r.node.height,r.width,r.height,r.fillMode,dt(r.rotation));this.draw2d(r.node.image,r.x+s.dx,r.y+s.dy,s.dWidth,s.dHeight,s.sx,s.sy,s.sWidth,s.sHeight)}return!0}return!1}debugLayout(e,t,r,s,n=!1){this.ctx2d&&(n&&([r,s]=[s,r]),this.ctx2d.save(),this.ctx2d.strokeStyle="red",this.ctx2d.lineWidth=2,this.ctx2d.strokeRect(e,t,r,s),this.ctx2d.restore())}getInfo(){let{totalFrames:e,x:t,y:r,width:s,height:n,name:a}=this,c=Date.now(),l=(e-this.lastInfo.totalFrames)/((c-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:r,width:s,height:n,timestamp:c,fps:l,name:a},v({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 Oe)try{(t=this.context.ctx)==null||t.deleteBuffer(e.positionBuffer)}catch(r){}})}close(){super.close(),this.removeAllInputs()}};var mE=[1,0,0,0,1,1,0,1],Mt=class extends Ye{constructor(e,t,r,s){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),s&&(this.rotation=s),e instanceof Oe)try{this.setTexBuffer(mE)}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,s,n){if(this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height),this.ctx2d.save(),this.mirror&&(this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0)),this.rotation===90?(this.ctx2d.translate(s,0),this.ctx2d.rotate(Math.PI/2),this.ctx2d.scale(n/s,s/n)):this.rotation===180?(this.ctx2d.translate(this.width,this.height),this.ctx2d.rotate(Math.PI)):this.rotation===270&&(this.ctx2d.translate(0,n),this.ctx2d.rotate(3*Math.PI/2),this.ctx2d.scale(n/s,s/n));let a=super.draw2d(e,t,r,s,n);return this.ctx2d.restore(),a}return!1}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}};var Zr=class extends Qt{constructor(e,t=4){super(t,ot);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,"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.mixNode=new Zo(this.videoContext,this.log)}listenDeviceChange(){throw new Error("Method not implemented.")}enablePrintDetail(e=2e3){this._checkId=re.run("interval",()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:e})}create2dVideoContext(){this.videoContext?this.videoContext.destroy():this.videoContext=new Fe({frameRate:15,logger:this.log,name:"mix-ctx"}),this.videoContext.create({alpha:!1})}setFps(e){this.autoSetFps=!1,this.videoContext.frameRate=e;for(let t of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])t.shouldUpdate=!1;setTimeout(()=>{var t;return(t=this.destination)==null?void 0:t.start(this.videoContext.frameRate)},500)}setFpsAuto(){var s;if(!this.autoSetFps)return;for(let n of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])n.shouldUpdate=!1;let e=null,t=0,r=!0;for(let[n,a]of this.inputLocalVideoTracks)a.profile.frameRate>t&&(t=a.profile.frameRate,e=n);for(let[n,a]of this.inputLocalScreenTracks)a.profile.frameRate>t&&(t=a.profile.frameRate,e=n,r=!1);if(e!==null){let n=r?this.cameraNodeMap.get(e):this.screenNodeMap.get(e);n&&(n.shouldUpdate=!0,n.tryVideoFrameCallback()),this.log.info("set mix fps: ",t)}else(s=this.destination)==null||s.start(this.videoContext.frameRate),this.log.info("fallback to timer, fps: ",this.videoContext.frameRate)}setMixBackground(e){this.mixNode&&(this.mixNode.backgroundColor=e)}resizeMixCanvas(e,t){var r;(r=this.mixNode)==null||r.resize(e,t)}startMix(){return f(this,null,function*(){var e;if(!this.mixNode||!this.destination)throw new Error("can't mix without necessary conditions");this.mixNode.disconnect(),this.mixNode.connect(this.destination),ci&&this.player.setCanvas(this.videoContext._canvas),this.setOutputMediaStreamTrack(this.destination.videoTrack),(e=this.manager)==null||e.changeInput(this)})}addCameraSource(e,t,r){if(this.inputLocalVideoTracks.has(e)||this.cameraNodeMap.has(e))throw new Error(`There is already a cameraSource with the same ID: ${e}`);let{mediaTrack:s}=t;if(!s)throw new Error("no mediaTrack, add cameraSource failed");let n;Je===16&&s instanceof CanvasCaptureMediaStreamTrack?n=this.videoContext.createVideoImageSource(s.canvas,{name:"cameraCanvasSource",logger:this.log}):n=this.videoContext.createVideoTrackSource(s,"cameraNodeSource"),n.resize(t.settings.width,t.settings.height),n.shouldUpdate=!1,this._connectMix(n,r,"cover"),this.inputLocalVideoTracks.set(e,t),this.cameraNodeMap.set(e,n),this.setFpsAuto()}addScreenSource(e,t,r){if(this.inputLocalScreenTracks.has(e)||this.screenNodeMap.has(e))throw new Error(`There is already a screenSource with the same ID: ${e}`);let{mediaTrack:s}=t;if(!s)throw new Error("no mediaTrack, add cameraSource failed");let n=this.videoContext.createVideoTrackSource(s,"screenNodeSource");n.resize(t.settings.width,t.settings.height),n.shouldUpdate=!1,this._connectMix(n,r),this.inputLocalScreenTracks.set(e,t),this.screenNodeMap.set(e,n),this.setFpsAuto()}addTextSource(e){let{id:t,content:r="",font:s,color:n,layout:a}=e;if(this.textNodeMap.has(t))throw new Error(`There is already a textSource with the same ID: ${t}`);let c=this.videoContext.createTextSource({content:r,font:s,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 s=this.videoContext.createVideoImageSource(t,{autoResize:!1,logger:this.log});s.resize(t.width,t.height),this._connectMix(s,r),this.imageNodeMap.set(e,s)}addVideoSource(e,t,r){if(this.videoNodeMap.has(e))throw new Error(`There is already a videoSource with the same ID: ${e}`);let s=this.videoContext.createVideoImageSource(t,{autoResize:!1,logger:this.log});s.resize(t.videoWidth,t.videoHeight),s.shouldUpdate=!1,this._connectMix(s,r),this.videoNodeMap.set(e,s)}updateCameraSource(e,t,r=null,s){let n=this.cameraNodeMap.get(e);if(n){if(r){if(Je===16&&r instanceof CanvasCaptureMediaStreamTrack)if(n instanceof Dt){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 Dt)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)}s&&n.resize(s.width,s.height),(s||r)&&this.setFpsAuto(),this._changeMixLayout(n,t)}}updateScreenSource(e,t){let r=this.screenNodeMap.get(e);r&&this._changeMixLayout(r,t)}updateTextSource(e){let{id:t,content:r,font:s,color:n,layout:a}=e,c=this.textNodeMap.get(t);c&&(E(r)||(c.content=r),E(s)||(c.font=s),E(n)||(c.color=n),c.resize(a.width,a.height),this._changeMixLayout(c,a))}updateImageSource(e,t,r){let s=this.imageNodeMap.get(e);s&&(r&&(s.image=r,s.resize(r.width,r.height)),this._changeMixLayout(s,t))}updateVideoSource(e,t,r){let s=this.videoNodeMap.get(e);if(s){if(r){let n=s.image;n instanceof HTMLVideoElement&&this.stopVideoElement(n),s.image=r,s.resize(r.videoWidth,r.videoHeight)}this._changeMixLayout(s,t)}}_connectMix(e,t,r="contain"){if(!this.mixNode)return;let{mirror:s,rotation:n}=t;e.disconnect();let a=new Mt(this.videoContext,this.log,s,n);a=e.connect(a),dt(a.rotation)&&a.resize(e.height,e.width),t.fillMode||(t.fillMode=r),a.connect(this.mixNode,t)}_changeMixLayout(e,t){if(!this.mixNode)return;let{mirror:r,rotation:s}=t,n=e.output||e;n instanceof Mt&&(E(r)||(n.mirror=r),E(s)||(n.rotation=s),dt(n.rotation)?n.resize(e.height,e.width):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 Mt&&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 Mt&&r.output.close(),r.close(),this.screenNodeMap.delete(e)),this.checkAfterRemove(!0)}removeTextSource(e){let t=this.textNodeMap.get(e);t&&(t.output instanceof Mt&&t.output.close(),t.close(),this.textNodeMap.delete(e)),this.checkAfterRemove()}removeImageSource(e){let t=this.imageNodeMap.get(e);t&&(t.output instanceof Mt&&t.output.close(),t.close(),this.imageNodeMap.delete(e)),this.checkAfterRemove()}removeVideoSource(e){let t=this.videoNodeMap.get(e);t&&(t.output instanceof Mt&&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(),re.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();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 gc=$s();if(typeof navigator!="undefined"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:gc,exposeOrigin:!0,permittedOrigins:["*"]})}catch(o){}var pE=function(o){return f(this,null,function*(){let i=null,e=gE(o);y.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let t=yield navigator.mediaDevices.getDisplayMedia(e);o.systemAudio&&t.getAudioTracks().length===0&&(Oo&<<74||xe||ae)&&y.warn("Your browser not support capture system audio");let r=t.getVideoTracks()[0];if(r){if(o.frameRate)try{yield r.applyConstraints({frameRate:{min:o.frameRate,ideal:o.frameRate},width:o.width,height:o.height})}catch(s){y.warn(`screen applyConstraints failed: ${s}`)}o.captureElement&&(yield fE(r,o.captureElement))}if(o.audio){let s=_E(o);y.info(`getUserMedia with constraints: ${JSON.stringify(s)}`),i=yield navigator.mediaDevices.getUserMedia(s),t.addTrack(i.getAudioTracks()[0])}return t})};function fE(o,i){return f(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&ne(o.cropTo))try{if(!(((e=o.getCaptureHandle())==null?void 0:e.handle)===gc))return;let r=yield CropTarget.fromElement(i);yield o.cropTo(r)}catch(t){y.warn(`cropTo target failed ${t}`)}})}function _E(o){let i={echoCancellation:o.echoCancellation,autoGainControl:o.autoGainControl,noiseSuppression:o.noiseSuppression,sampleRate:o.sampleRate,channelCount:o.channelCount};return E(o.microphoneId)||(i.deviceId=o.microphoneId),{audio:i,video:!1}}function gE(o){let i={preferCurrentTab:o.preferDisplaySurface==="current-tab"||!!o.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:xe?{max:o.width}:{ideal:o.width,max:o.width},height:xe?{max:o.height}:{ideal:o.height,max:o.height},frameRate:o.frameRate,displaySurface:o.preferDisplaySurface||"monitor"};if(i.video=e,o.systemAudio){let{echoCancellation:t=!0,noiseSuppression:r=!1,autoGainControl:s=!1}=o;i.audio={echoCancellation:t,noiseSuppression:r,autoGainControl:s,sampleRate:48e3}}return i}var gp=pE;var Ze=class extends Be{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 gc===((t=(e=this.mediaTrack)==null?void 0:e.getCaptureHandle())==null?void 0:t.handle)}catch(r){return}}capture(u){return f(this,arguments,function*({systemAudio:e=!1,autoGainControl:t,echoCancellation:r,noiseSuppression:s,audioTrack:n,videoTrack:a,captureElement:c,preferDisplaySurface:l}){try{let h;return a||n?(h=new MediaStream,a&&h.addTrack(a),n&&h.addTrack(n)):(h=yield gp({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:t,echoCancellation:r,noiseSuppression:s,captureElement:c,preferDisplaySurface:l}),this.sourceTrack=h.getVideoTracks()[0]),yield this.setInputMediaStreamTrack(h.getVideoTracks()[0]),h}catch(h){throw this.log.error(`getDisplayMedia error observed ${h}`),h instanceof N?h:new N({code:I.INITIALIZE_FAILED,name:h.name,message:h.message})}})}switchDevice(e){return f(this,null,function*(){throw new Error("Method not implemented.")})}};D([st(function(e){this.setContentHint(e.contentHint||"detail")})],Ze.prototype,"capture",1);var Ii=class extends Ct{constructor(i){super(i),this._log.id=`s-${this._log.id}`}addAudioProcessor(i,e,t,r){this.pipeline.silentNode.setNode(t),this.pipeline.mixNode.setNode(e),this.pipeline.aec.setNode(r),this.enableTrackAEC(!1)}removeAudioProcessor(i,e,t,r){this.pipeline.aec.node===r&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode(),this.enableTrackAEC(!0))}};var TE='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}});',ku;function En(o,i=48e3,e=1,t){return f(this,null,function*(){let r=Ee("dump");ku||(ku=ji(r,URL.createObjectURL(new Blob([TE],{type:"application/javascript"})))),yield ku;let s=r.sampleRate,n=new AudioWorkletNode(r,"dumper",{numberOfInputs:o.length,numberOfOutputs:0,processorOptions:{sourceSampleRate:s,targetSampleRate:i}});return n.channelCountMode="explicit",n.channelCount=e,t&&n.port.postMessage({port:t},[t]),o.forEach((a,c)=>a.connect(n,0,c)),new ReadableStream({start(a){n.port.onmessage=c=>{a.enqueue(c.data)}},cancel(){o.forEach(a=>a.disconnect(n)),n.port.close()}})})}var Tc=class extends Ga{constructor(e){super();this.room=e;d(this,"_localAudioTrack");d(this,"_localScreenAudioTrack");d(this,"log",y.createLogger({id:"am"}));d(this,"denoiser");d(this,"voiceChanger");d(this,"mixChangedDebounce");d(this,"audioProcessor");d(this,"encodePipeline",[]);d(this,"decodePipeline",[]);d(this,"getPCMAbortCtrlMap",new Map);d(this,"audioFrameEventConfigMap",new Map);d(this,"audioReferenceMap",new Map);d(this,"isLocalAudioNeedAudioProcess",!1);d(this,"isScreenAudioNeedAudioProcess",!1);e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.installEvent()}get _localAudioPipline(){var e;return(e=this._localAudioTrack)==null?void 0:e.pipeline}get _localScreenAudioPipeline(){var e;return(e=this._localScreenAudioTrack)==null?void 0:e.pipeline}dump(e){var u,h;if(!this._localAudioTrack)return;let t=[],r=[];(u=this._localAudioPipline)!=null&&u.source.node&&(t.push(this._localAudioPipline.source.node),r.push("mic")),(h=this._localAudioPipline)!=null&&h.denoiser.node&&(t.push(this._localAudioPipline.denoiser.node),r.push("mic-processed")),this.mixWeight>1&&(t.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),r.push("mix")),this.log.info(`dump audio track ${r}, duration: ${e}`);let s=new AbortController,n=[],a=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),s.abort("timeout")},e*1e3),c=()=>{for(let m=0;m<r.length;m++){let g=URL.createObjectURL(new Blob(n[m])),A=document.createElement("a");A.href=g,A.download=`${r[m]}.pcm`,A.style.display="none",document.body.appendChild(A),A.click(),URL.revokeObjectURL(g),A.remove()}clearTimeout(a),s.abort("download")},l=En(t).then(m=>m.pipeTo(new WritableStream({write(g){g.forEach((A,_)=>n[_]=n[_]?n[_].concat(A[0]):[A[0]])}}),s).catch(g=>c));return{then:l.then.bind(l),download:c}}getPCM(e,t){var M,K,G;if(typeof WritableStream=="undefined"){this.log.warn("getPCM failed: browser not support WritableStream");return}let{enable:r,sampleRate:s=48e3,channelCount:n=1,port:a}=(t===""?this.audioFrameEventConfigMap.get(""):this.audioFrameEventConfigMap.get(t)||this.audioFrameEventConfigMap.get("*"))||{};if(!r)return;this.log.info(`getPCM ${t||"local"}`);let c=Math.floor(s*.04),l=new Float32Array(c),u=new Float32Array(c),h,m,g=0,A=new AbortController,_=t===""?(M=this._localAudioTrack)==null?void 0:M.mediaTrack:(G=(K=this.room)==null?void 0:K.remotePublishedUserMap.get(t))==null?void 0:G.remoteAudioTrack.mediaTrack;if(!_){this.log.info(`getPCM failed: ${t||"local"} has no audio track`);return}let T=Ee().createMediaStreamSource(new MediaStream([_]));return En([T],s,n,a).then(ee=>ee.pipeTo(new WritableStream({write(_e){_e[0][0]&&(g+_e[0][0].length>c?(l.set(_e[0][0].subarray(0,c-g),g),h=_e[0][0].subarray(c-g),_e[0][1]&&(u.set(_e[0][1].subarray(0,c-g),g),m=_e[0][1].subarray(c-g)),g+=c-g):(h&&(l.set(h,g),g+=h.length,h=void 0),m&&(u.set(m,g),m=void 0),l.set(_e[0][0],g),_e[0][1]&&u.set(_e[0][1],g),g+=_e[0][0].length),g>=c&&(g=0,e({userId:t,sampleRate:s,channelCount:n,data:n===1?l:[l,u]}),l=new Float32Array(c),u=new Float32Array(c)))}}),A).catch(_e=>this.log.warn(`stop getPCM reason:${_e}`))),A}get hasScreenAudioTrack(){return!E(this._localScreenAudioTrack)}get hasAudioTrack(){return!E(this._localAudioTrack)}changeInput(e){if(e instanceof Ii)return this._localScreenAudioTrack=e,this.isScreenAudioNeedAudioProcess&&this.audioProcessor&&(e.addAudioProcessor(...this.audioProcessor),this.audioReferenceMap.forEach((t,r)=>{e.mixAudioReference(t,r)})),e.pipeline.connect(),this.mixOnChange();if(e instanceof Ct)return this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),this.isLocalAudioNeedAudioProcess&&this.audioProcessor&&(e.addAudioProcessor(...this.audioProcessor),this.audioReferenceMap.forEach((t,r)=>{e.mixAudioReference(t,r)})),e.pipeline.connect(),this.mixOnChange();if(e instanceof Yt)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 Ii?delete this._localScreenAudioTrack:e instanceof Ct?delete this._localAudioTrack:e instanceof Yt}addDenoiser(e){var t;this.denoiser=e,(t=this._localAudioTrack)==null||t.addDenoiser(e)}addAudioProcessor(e,t,r,s){var n;this.audioProcessor=[e,t,r,s],this.isLocalAudioNeedAudioProcess&&this._localAudioTrack&&(this._localAudioTrack.addAudioProcessor(...this.audioProcessor),this.audioReferenceMap.forEach((a,c)=>{var l;(l=this._localAudioTrack)==null||l.mixAudioReference(a,c)})),this.isScreenAudioNeedAudioProcess&&this._localScreenAudioTrack&&((n=this._localScreenAudioTrack)==null||n.addAudioProcessor(...this.audioProcessor),this.audioReferenceMap.forEach((a,c)=>{var l;(l=this._localScreenAudioTrack)==null||l.mixAudioReference(a,c)}))}removeDenoiser(e){var t;delete this.denoiser,(t=this._localAudioTrack)==null||t.removeDenoiser(e)}addVoiceChanger(e,t){var r;this.voiceChanger=[e,t],(r=this._localAudioTrack)==null||r.pipeline.voiceChanger.setNode(e,t)}removeVoiceChanger(){var e;delete this.voiceChanger,(e=this._localAudioTrack)==null||e.pipeline.voiceChanger.deleteNode()}removeAudioProcessor(e,t,r,s){var n;delete this.audioProcessor,(n=this._localAudioTrack)==null||n.removeAudioProcessor(e,t,r,s)}destroy(){this.close(),this.audioReferenceMap.clear(),this.getPCMAbortCtrlMap.forEach(e=>e==null?void 0:e.abort("destroy")),this.getPCMAbortCtrlMap.clear(),this.audioFrameEventConfigMap.clear(),this.uninstallEvent()}addEncodeProcessor({processor:e,type:t}){var r;this.encodePipeline.includes(e)||(this.encodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}addDecodeProcessor({processor:e,type:t}){var r;this.decodePipeline.includes(e)||(this.decodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}handleLocalTrackStarted({room:e,userId:t}){var s;if(e!==this.room||this.getPCMAbortCtrlMap.get(t))return;let r=this.getPCM(n=>{var a;(a=this.room)==null||a.emit("audio-frame",n)},"");this.getPCMAbortCtrlMap.set(t,r),this.getPCMAbortCtrlMap.get(t)&&((s=this._localAudioTrack)==null||s.on("input-media-track-changed",()=>{let n=this.getPCMAbortCtrlMap.get(t);n&&(n.abort("inputMediaTrackChanged"),n=this.getPCM(a=>{var 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(s=>{var n;(n=this.room)==null||n.emit("audio-frame",s)},t);this.getPCMAbortCtrlMap.set(t,r)}}handleRemoteTrackStopped({room:e,userId:t}){if(e!==this.room)return;let r=this.getPCMAbortCtrlMap.get(t);r&&(r.abort("stopRemoteAudio"),this.getPCMAbortCtrlMap.delete(t))}installEvent(){S.on("113",this.handleLocalTrackStarted,this),S.on("114",this.handleLocalTrackStopped,this),S.on("115",this.handleRemoteTrackStarted,this),S.on("116",this.handleRemoteTrackStopped,this)}uninstallEvent(){S.off("113",this.handleLocalTrackStarted),S.off("114",this.handleLocalTrackStopped),S.off("115",this.handleRemoteTrackStarted),S.off("116",this.handleRemoteTrackStopped)}updateAudioReference({type:e,audioReference:t,refId:r,volume:s}){if(e==="add"){if(this.audioReferenceMap.get(r)||!t||(this.audioReferenceMap.set(r,t),!this.audioProcessor))return;this.mixAudioReference(t,r)}else if(e==="remove")this.audioReferenceMap.get(r)&&(this.audioReferenceMap.delete(r),this.unMixAudioReference(r));else if(e==="updateVolume"){if(!this.audioProcessor||E(s))return;this.setAudioReferenceVolume(r,s)}}};function Ec(o=30,i=2){return Y((e,t)=>function(...r){return new Promise((s,n)=>{let a=setTimeout(()=>{let c=new N({code:I.API_CALL_TIMEOUT,message:`checkPendingPromise ${t}() timeout ${o}s`});y.warn(c),i===2?n(c):i===1&&s()},o*1e3);e.apply(this,r).then(s,n).finally(()=>{clearTimeout(a)})})})}var Ai=class Ai extends Gr{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",nt(me(this,Ai.STATE_SUBSCRIBE)));this.tinyId=t.tinyId,this.availableState=new $(`${t.userId}-${this.mediaType}-available`,"remote-track-available"),this.remotePublishState=new $(`${t.userId}-${this.mediaType}-remote-publish`,"remote-track-publish"),ue(zl(me(this,$.STATECHANGED),me(this.remotePublishState,$.STATECHANGED)),_n(()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing)),be(c=>{this.availableState.state!==(c?$.ON:$.OFF)&&(this.availableState.state=c?$.ON:$.OFF),this.updatePlayingState(c)}));let s=ue(me(this.player,he.ERROR),Si(c=>c.code===MediaError.MEDIA_ERR_DECODE)),n=ue(pn(5e3),Si(()=>this.ignoreDecodeError||!this.isSubscribed||!this.isPlayCalled||!this.stat.bytesReceived?!1:this.player.isPlaying||(this.kind===p.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)?(this.reportDecodeResult(!0),!1):!0)),a=ue(Ql(s,n),He(me(this,$.INIT)));ue(this._triggerCheckDecodeSubject,Si(()=>!this.ignoreDecodeError),zr(a),be(c=>{this.reportDecodeResult(!1,c)}))}setMute(e){this.isRemotePublished&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.isRemotePublished&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}checkDecodeResult(){this._triggerCheckDecodeSubject.next(!0)}waitHasMediaTrack(){return new Promise(e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)})}get ignoreDecodeError(){var t,r;return(((r=(t=this.room)==null?void 0:t.networkQuality)==null?void 0:r.downlinkNetworkQuality)||0)>3||this.player.isInAutoPlayFailedState}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===Ai.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===$.ON}get isNeedPlay(){return this.isAvailable&&this.isPlayCalled}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}reportDecodeResult(e,t){var s,n;let r=this.kind===p.AUDIO;if(b[e?"addSuccessEvent":"addFailedEvent"]({key:r?504700:514702}),!r){let a=((s=this.room)==null?void 0:s.downlinkVideoCodec.toUpperCase())||"H264";b[e?"addSuccessEvent":"addFailedEvent"]({key:qs[`DECODE_${a}_RESULT`]}),e||this.log.warn(`${(n=this.room)==null?void 0:n.downlinkVideoCodec} decode failed`)}e||(b.addEnum({key:r?504701:514703,value:Hs()}),se.uploadEvent({log:`stat-decode-failed-${this.kind}-${Lr()||Hi()}`,userId:this.room.userId}),this._log.warn(`decode failed: isPlaying: ${this.player.isPlaying} ${this.kind===p.AUDIO?`audioLevel: ${this.getAudioLevel()}`:`framesDecoded: ${this.stat.framesDecoded>0}`}`),this.emit("decode-failed",{error:t}))}updatePlayingState(e){if(this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.isRemotePublished||!this.outMediaTrack)){this.log.info(`abort play, isSubscribed: ${this.isSubscribed} isAvailable: ${this.isRemotePublished} hasTrack: ${!!this.outMediaTrack} `);return}super.updatePlayingState(e)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.remotePublishState.state=this.isRemotePublished?$.ON:$.OFF}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};d(Ai,"STATE_SUBSCRIBE","subscribe"),D([Ec(5,1)],Ai.prototype,"waitHasMediaTrack",1),D([Te($.INIT,Ai.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),S.emit(C.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),pt(521716,!1)],Ai.prototype,"subscribe",1),D([Te(Ai.STATE_SUBSCRIBE,$.INIT,{sync:!0,success(){this.log.info("unsubscribed"),S.emit(C.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],Ai.prototype,"unsubscribe",1);var Ko=Ai;var Yt=class extends Ko{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 $r.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}decodeFrame(e){if(!this.manager)return e;let t=e;for(let r of this.manager.decodePipeline)if(r&&(t=r({frame:t,track:this}),!t))return;return t}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get isRemotePublished(){return this.user.muteState.audioAvailable}};function SE(o){return[15,30,45,60].reduce((e,t)=>Math.abs(t-o)<Math.abs(e-o)?t:e)}var Ci=class extends Ko{constructor(e,t,r=4){super(e,t,r);d(this,"mediaType",4);d(this,"source");d(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.videoManager,this.once("first-video-frame",s=>{this.room.emit("first-video-frame",s)})}play(e,t){return(de(t==null?void 0:t.canvasRender)?t.canvasRender:Je===17)&&!this.source&&this.useCanvasPlayer(),super.play(e,t).then(()=>{this.player.calculateStat()})}useCanvasPlayer(){if(this.log.info(`useCanvasPlayer(), has element:${!!this.player.element}`),!this.player.element)return;let e=new Fe({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});let t=new Qr(e,{name:"remotePlayer",logger:this.log});this.source=e.createVideoPlayerSource(this.player),this.source.connect(t),this.player.setCanvas(e._canvas),Hr()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let t=this.decodeFPS,r=SE(t);if(!q(t)||t<=0){this.log.debug(`updateCanvasPlayerFPS() ignore decoder: ${t} `);return}if(r===e.frameRate){this.log.debug(`updateCanvasPlayerFPS() ignore ClosestFPS ${r} == ${e.frameRate}`);return}this.log.info(`updateCanvasPlayerFPS() decoder: ${t}, closest: ${r}, current: ${e.frameRate}`),e.frameRate=r}get decodeFPS(){var n;let{msg_video_status:e}=((n=this.room.heartbeatReport)==null?void 0:n.msg_down_stream_info.find(a=>a.msg_user_info.str_identifier===this.userId))||{},t=this.mediaType===2?7:this.isSmall?3:2;if(!e||e.length===0)return 0;let r=e.find(a=>a.uint32_video_stream_type===t);return(r==null?void 0:r.uint32_video_dec_fps)||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),super.stop()}decodeFrame(e){if(!this.manager)return e;for(let t of this.manager.decodePipeline)if(t&&(e=t({frame:e,track:this}),!e))return;return e}get isBig(){return this.mediaType===4}get isSmall(){return this.mediaType===8}changeType(e){this.room.changeType(e,this.user)}get isRemotePublished(){return this.user.muteState.videoAvailable}setMirror(e){e==="publish"||e==="both"||super.setMirror(e)}onDecodeDowngradeStateChanged(e){this.emit("decode-downgrade-state-changed",e)}},es=class extends Ci{constructor(e,t){super(e,t,2);d(this,"mediaType",2);d(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}};var ts=new Map;S.on(C.JOIN_SUCCESS,({room:o})=>{Ae(o.userId,{eventId:32788})});S.on(C.LEAVE_START,({room:o})=>{Ae(o.userId,{eventId:32789})});S.on(C.LOCAL_TRACK_PUBLISHED,({track:o})=>{if(o.room){let i=32769;o.mediaType===4?i=32768:o.mediaType===2&&(i=32805),Ae(o.room.userId,{eventId:i})}});S.on(C.LOCAL_TRACK_UNPUBLISHED,({track:o})=>{if(o.room){let i=32771;o.mediaType===4?i=32770:o.mediaType===2&&(i=32806),Ae(o.room.userId,{eventId:i})}});S.on(C.TRACK_MUTED,({track:o})=>{o.room&&(o.kind===p.AUDIO?Ae(o.room.userId,{eventId:o.isRemote?32785:32772,remoteUserId:o.isRemote?o.userId:void 0}):Ae(o.room.userId,{eventId:o.isRemote?32784:32773,remoteUserId:o.isRemote?o.userId:void 0}))});S.on(C.TRACK_UNMUTED,({track:o})=>{o.room&&(o.kind===p.AUDIO?Ae(o.room.userId,{eventId:o.isRemote?32787:32774,remoteUserId:o.isRemote?o.userId:void 0}):Ae(o.room.userId,{eventId:o.isRemote?32786:32775,remoteUserId:o.isRemote?o.userId:void 0}))});S.on(C.REMOTE_TRACK_SUBSCRIBED,({track:o})=>{o.room&&(o.mediaType===1&&Ae(o.room.userId,{eventId:32777,remoteUserId:o.userId}),o.mediaType===4&&Ae(o.room.userId,{eventId:32776,remoteUserId:o.userId}),o.mediaType===8&&Ae(o.room.userId,{eventId:32803,remoteUserId:o.userId}))});S.on(C.REMOTE_TRACK_UNSUBSCRIBED,({track:o})=>{o.room&&(o.mediaType===1&&Ae(o.room.userId,{eventId:32779,remoteUserId:o.userId}),o.mediaType===4&&Ae(o.room.userId,{eventId:32778,remoteUserId:o.userId}),o.mediaType===8&&Ae(o.room.userId,{eventId:32804,remoteUserId:o.userId}))});S.on(C.SWITCH_DEVICE_SUCCESS,({track:o})=>{o.room&&Ae(o.room.userId,{eventId:o.kind===p.VIDEO?32780:32781})});S.on(C.LOCAL_TRACK_REPLACED,({track:o})=>{o.room&&Ae(o.room.userId,{eventId:o.kind===p.VIDEO?32782:32783})});S.on(C.SIGNAL_CONNECTION_STATE_CHANGED,({room:o,prevState:i,state:e})=>{let t;switch(e){case"CONNECTED":i==="RECONNECTING"?t=32795:t=32791;break;case"DISCONNECTED":i==="RECONNECTING"?t=32796:t=32790;break;case"RECONNECTING":t=32794;break}t&&Ae(o.userId,{eventId:t})});S.on(C.PEER_CONNECTION_STATE_CHANGED,({room:o,prevState:i,state:e,remoteUserId:t})=>{let r=!!t,s;switch(e){case"CONNECTED":i==="RECONNECTING"?s=r?32801:32798:s=r?32793:32792;break;case"DISCONNECTED":i==="RECONNECTING"&&(s=r?32802:32799);break;case"RECONNECTING":s=r?32800:32797;break}s&&Ae(o.userId,{eventId:s,remoteUserId:t})});S.on(C.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({implementation:o,userId:i,remoteUserId:e,codec:t,isHWCodec:r,prevImplementation:s,streamType:n})=>{let a=r?1:0;s||(a=r?3:2);let 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),Ae(i,l),b.addEnum({key:e?514701:513701,value:a}),b.addEnum({key:e?514700:513700,value:c})});S.on(C.LOCAL_TRACK_RECAPTURE,({track:o,error:i})=>{if(o.userId){let e={eventId:2003,param1:0};o.kind===p.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType=o.streamType==="auxiliary"?7:2,i&&(e.param1=8)),Ae(o.userId,e)}});function Ae(o,i){let e=w(v({},i),{timestamp:fs()});ts.has(o)?ts.get(o).push(e):ts.set(o,[e])}function Tp(o){if(ts.has(o)){let i=ts.get(o).map(e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,uint32_param1:e.param1,uint32_param2:e.param2,uint32_video_stream_type:e.streamType}));return ts.delete(o),i}return[]}function Ep(...o){return Y((i,e)=>function(...t){return IE.call(this,o,t,e,this._name),i.apply(this,t)})}function IE(o,i,e,t){try{if(Se(o))for(let r=0;r<o.length;r++)Sc.call(this,{rule:o[r],value:i[r],key:o[r].name,fnName:e,className:t});else Sc.call(this,{rule:o,value:i[0],key:o.name,fnName:e,className:t})}catch(r){throw y.error(r),r}}function Sc({rule:o,value:i,key:e,fnName:t,className:r}){if(E(i)){if(o.required)throw new N({code:I.INVALID_PARAMETER,message:P({key:L.INVALID_PARAMETER_REQUIRED,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(E(o.defaultValue))return;i=o.defaultValue}if(Array.isArray(o.type)){let a=!1;for(let c=0;c<o.type.length;c++)o.type[c]===null&&i===null&&(a=!0),ne(o.type[c])&&i instanceof o.type[c]&&(a=!0),te(o.type[c])&&Re(i)===o.type[c].toLowerCase()&&(a=!0);if(!a)throw new N({code:I.INVALID_PARAMETER,message:P({key:L.INVALID_PARAMETER_TYPE,data:{key:e,rule:{type:o.type.map(c=>Mr(c)?fo(c):te(c)?c:Re(c))},fnName:t,value:i},link:{className:r,fnName:t}})})}else if(!E(o.type)&&Re(i)!==o.type)throw new N({code:I.INVALID_PARAMETER,message:P({key:L.INVALID_PARAMETER_TYPE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(o.allowEmpty===!1){let a=q(i)&&(i===0||Number.isNaN(i)),c=te(i)&&i.trim()==="";if(a||c)throw new N({code:I.INVALID_PARAMETER,message:P({key:L.INVALID_PARAMETER_EMPTY,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})})}if(o.notLessThanZero&&q(i)&&i<0)throw new N({code:I.INVALID_PARAMETER,message:P({key:L.CANNOT_LESS_THAN_ZERO,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(!E(o.min)&&q(i)&&i<o.min)throw new N({code:I.INVALID_PARAMETER,message:P({key:L.INVALID_PARAMETER_MIN,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(!E(o.max)&&q(i)&&i>o.max)throw new N({code:I.INVALID_PARAMETER,message:P({key:L.INVALID_PARAMETER_MAX,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(te(o.instanceOf)){if(!i||i._name!==o.instanceOf)throw new N({code:I.INVALID_PARAMETER,message:P({key:L.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})})}else if(ne(o.instanceOf)&&!(i instanceof o.instanceOf))throw new N({code:I.INVALID_PARAMETER,message:P({key:L.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(o.values&&!o.values.includes(i))throw new N({code:I.INVALID_PARAMETER,message:P({key:L.INVALID_PARAMETER_RANGE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});let{properties:s}=o;ze(s)&&ft(i)&&Object.keys(s).forEach(a=>{Sc.call(this,{rule:s[a],value:i&&i[a],key:`${e}.${a}`,fnName:t,className:r})});let{arrayItem:n}=o;ze(n)&&Se(i)&&i.forEach((a,c)=>{Sc.call(this,{rule:n,value:a,key:`${e}[${c}]`,fnName:t,className:r})}),ne(o.validate)&&o.validate.call(this,i,e,t,r,this)}var Sp=Ge(tt(),1);var Ic=class extends Sp.EventEmitter{constructor(e,t,r="userId"){super();this.mySelfId=e;this._log=t;this.key=r;d(this,"userMap",new Map);d(this,"remotePublishedUserMap",new Map)}get hasRobotUser(){return!![...this.remotePublishedUserMap.values()].find(e=>e.isRobot)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:r,tinyId:s,role:n}=e;if(this.userMap.has(t))return;let a={userId:r,tinyId:s,role:n===20?"anchor":"audience"};this.userMap.set(t,a),this.emit("1",a)}deleteUser(e,t){let r=this.userMap.get(e);if(!r)return;let s=`peer leave [${e}]`;E(t)||(s+=`:${gd[t]}`),this._log.info(s);let n=this.remotePublishedUserMap.get(e);if(n){let a=n.muteState;n.flag=0,this.emit("5",n.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:a,muteState:n.muteState,flag:0})}this.userMap.delete(e),this.emit("2",r.userId)}setUserList(e){this.userMap.forEach(t=>{e.findIndex(r=>r[this.key]===t[this.key])<0&&this.deleteUser(t[this.key],0)}),e.forEach(t=>{!this.userMap.has(t[this.key])&&t[this.key]!==this.mySelfId&&this.addUser(t)})}addRemotePublishedUser(e){this.remotePublishedUserMap.has(e[this.key])||this.remotePublishedUserMap.set(e[this.key],e)}deleteRemotePublishedUser(e){this.remotePublishedUserMap.has(e)&&this.remotePublishedUserMap.delete(e)}setRemotePublishedUserList(e){this.remotePublishedUserMap.forEach(t=>{let r=t[this.key];if(e.findIndex(s=>s[this.key]===t[this.key])<0){this._log.info(`remote [${r}] unpublish`);let s=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(r),this.emit("6",{prevMuteState:s,muteState:t.muteState,flag:0})}}),e.forEach(t=>{var u;let r=t[this.key];if(r===this.mySelfId)return;let{flag:s,userId:n,tinyId:a}=t,c=xi(s,n),l=(u=this.remotePublishedUserMap.get(r))==null?void 0:u.muteState;if(l){let h=this.remotePublishedUserMap.get(r);h&&h.flag!==s&&(h.flag=s,this._log.info(`remote publish updated: ${JSON.stringify(h.muteState)}`),this.emit("6",{prevMuteState:l,muteState:c,flag:s}))}else this._log.info(`remote publish. state: ${JSON.stringify(c)}`),this.addUser({userId:n,tinyId:a,role:20}),this.emit("3",t),this.emit("6",{prevMuteState:xi(0,n),muteState:c,flag:s})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function Ou({timesInSecond:o,maxSizeInSecond:i,getSize:e}){return Y((t,r)=>{let s=new WeakMap;return S.on(C.ROOM_DESTROY,({room:n})=>s.delete(n)),function(...n){let a=s.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},s.set(this,a)),a.timestamp===0?a.timestamp=Date.now():Date.now()-a.timestamp>1e3&&(a.timestamp=Date.now(),a.callCountInSecond=0,a.totalSizeInSecond=0),e&&(a.totalSizeInSecond+=e(...n)),a.timestamp!==0&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=o||a.totalSizeInSecond>i))throw new N({code:I.INVALID_OPERATION,message:P({key:L.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=o,isSize:a.totalSizeInSecond>i,name:r,timesInSecond:o,maxSizeInSecond:i}})});a.callCountInSecond++,t.call(this,...n)}})}var AE="2025-07-22 21:24:37",Ip=!0,Ap=function(){var o;if(Ip){Ip=!1,y.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${ii}/en/index.html`),console.info(`* Changelog: ${ii}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),y.info("TRTC Web SDK Version:",we),Wt||y.debug("Build Time:",AE);let i=`UA: ${navigator.userAgent}
|
|
53
53
|
CPU core: ${navigator.hardwareConcurrency}, GPU: ${Yd()}`,e=navigator.deviceMemory;e&&(i+=`, minRAM: ${e}GB`),y.info(i),y.info(`URL: ${location.href}${((o=self.frameElement)==null?void 0:o.tagName)==="IFRAME"?" in iframe":""}`),xr().then(t=>{t&&y.info(Ft)})}};var kt={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},Ot=(R=>(R[R.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",R[R.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",R[R.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",R[R.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",R[R.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",R[R.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",R[R.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",R[R.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",R[R.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",R[R.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",R[R.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",R[R.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",R[R.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",R[R.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",R[R.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",R[R.INVALID_ROOM_ID_REQUIRED=5015]="INVALID_ROOM_ID_REQUIRED",R[R.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",R[R.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",R[R.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",R[R.INVALID_ROOM_ID_TYPE_MISMATCH=5019]="INVALID_ROOM_ID_TYPE_MISMATCH",R[R.INVALID_ROOM_ID_DUPLICATE=5020]="INVALID_ROOM_ID_DUPLICATE",R[R.INVALID_OPERATION=5100]="INVALID_OPERATION",R[R.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",R[R.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",R[R.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",R[R.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",R[R.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",R[R.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",R[R.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",R[R.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",R[R.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",R[R.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",R[R.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",R[R.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",R[R.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",R[R.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",R[R.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",R[R.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",R[R.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",R[R.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",R[R.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",R[R.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",R[R.DEVICE_ERROR=5300]="DEVICE_ERROR",R[R.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",R[R.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",R[R.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",R[R.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",R[R.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",R[R.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",R[R.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",R[R.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",R[R.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",R[R.SERVER_ERROR=5400]="SERVER_ERROR",R[R.NEED_TO_BUY=5401]="NEED_TO_BUY",R[R.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",R[R.OPERATION_FAILED=5500]="OPERATION_FAILED",R[R.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",R[R.REJOIN_FAILED=5502]="REJOIN_FAILED",R[R.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",R[R.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",R[R.VIDEO_ENCODE_FAILED=5505]="VIDEO_ENCODE_FAILED",R[R.AUDIO_ENCODE_FAILED=5506]="AUDIO_ENCODE_FAILED",R[R.VIDEO_DECODE_FAILED=5507]="VIDEO_DECODE_FAILED",R[R.AUDIO_DECODE_FAILED=5508]="AUDIO_DECODE_FAILED",R[R.OPERATION_ABORT=5998]="OPERATION_ABORT",R[R.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",R))(Ot||{});function Rp({code:o,params:i,enableDocLink:e=!1}){let t="",r,s=Ot[o];try{r=Cp[s]}catch(n){r=Cp.UNKNOWN_ERROR}return ne(r)?t=r(i):te(r)&&(t=r),i.fnName&&!t.includes(i.fnName)&&(t[t.length-1]!=="."&&(t+="."),t+=` thrown from ${i.fnName}()`),e&&(t+=" doc:"),t}var Cp=w(v({},Ve),{INVALID_PARAMETER({fnName:o}){return`the parameters of the '${o}' you called does not meet the requirements, please check the API documentation.`},INVALID_PARAMETER_REQUIRED({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' is a required param when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_TYPE({key:o,rule:i,fnName:e,value:t}){let r=`${o||i.name}`,s="";return Array.isArray(i.type)?s=i.type.join("|"):s=i.type,`'${r}' must be type of ${s} when calling ${e}(), received type: ${Re(t)}.`},INVALID_PARAMETER_EMPTY({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' cannot be '${t}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:o,rule:i,fnName:e,value:t}){let r=`${o||i.name}`,s=`${i.instanceOf.name||i.instanceOf}`;return`'${r}' must be instanceof ${s} when calling ${e}(), received type: ${Re(t)}.`},INVALID_PARAMETER_RANGE({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' must be one of ${i.values.join("|")} when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_LESS_THAN_ZERO({key:o,rule:i,fnName:e}){return`'${o||i.name}' cannot be less than 0 when calling ${e}().`},INVALID_PARAMETER_MIN({key:o,rule:i,value:e}){return`the min value of ${o||i.name} is ${i.min}, received: ${e}.`},INVALID_PARAMETER_MAX({key:o,rule:i,value:e}){return`the max value of ${o||i.name} is ${i.max}, received: ${e}.`},INVALID_ELEMENT_ID({key:o,fnName:i}){return`'${o}' is not found in the document object when calling ${i}().`},INVALID_ELEMENT_ID_TYPE({key:o,fnName:i,type:e}){return`the element corresponding to '${o}' must be instanceof HTMLElement when calling ${i}(), received: ${e}.`},INVALID_STREAM_ID({key:o}){return`'${o}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},INVALID_ROOM_ID_STRING({key:o}){return`'${o}' must be a valid string.`},INVALID_ROOM_ID_INTEGER({key:o}){return`'${o}' must be an integer between [1, 4294967294].`},INVALID_ROOM_ID_INTEGER_STRING({key:o}){return`'${o}' must be an integer but go a string, use 'parseInt' to convert it or use 'strRoomId' instead.`},INVALID_ROOM_ID_REQUIRED(){return"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required."},INVALID_ROOM_ID_TYPE_MISMATCH({key:o}){return`The type of target roomId must match the current roomId. Current room is using '${o}', but received '${o==="strRoomId"?"roomId":"strRoomId"}'.`},INVALID_ROOM_ID_DUPLICATE({key:o}){return`the target '${o}' must not be the same as the current '${o}'.`},INVALID_STREAM_TYPE:({fnName:o})=>`'streamType' is required when 'userId' is not '*', calling ${o}()`,INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION({fnName:o}){return`the API '${o}' you called does not meet the requirements, please check the API documentation.`},INVALID_OPERATION_NOT_JOINED({fnName:o}){return`cannot ${o} because you are not enter room yet.`},INVALID_OPERATION_REMOTE_USER_NOT_EXIST({fnName:o,value:i}){return`cannot ${o} because remote user(userId: ${i.userId}) does not publishing stream.`},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST({fnName:o,value:i}){return`cannot ${o} because remote user(userId: ${i.userId}) does not publishing ${i.streamType} video.`},INVALID_OPERATION_REPEAT_CALL({fnName:o}){return`you are already ${o}(), cannot repeated call '${o}'.`},INVALID_OPERATION_NEED_VIDEO({fnName:o}){return`cannot call '${o}' because the camera is not turned on.`},INVALID_OPERATION_NEED_AUDIO({fnName:o}){return`cannot call '${o}' because the microphone or screen share is not turned on.`},INVALID_BUFFER_EMPTY:({key:o})=>`the buffer size of paramerter '${o}' cannot be empty`,INVALID_BUFFER_OVERSIZE:()=>"buffer size is over 1000 Bytes",INVALID_ROLE_AUDIENCE:()=>"role: 'audience' cannot call this api.",INVALID_NOT_ENABLE_SEI:()=>"you need to enable SEI in TRTC.create({ enableSEI: true })",INVALID_NEED_CALL_PUBLISHED:({fnName:o})=>`you need to call ${o}() after publish stream.`,ENV_NOT_SUPPORTED({fnName:o}){return`the current browser does not support the capability of the function '${o}' you are calling, please check the API documentation.`},NOT_SUPPORTED_WEBRTC:"the current browser does not support WebRTC capability, please check the SDK documentation.",NOT_SUPPORTED_H264_ENCODE:"this browser does not support H264 encode.",NOT_SUPPORTED_H264_DECODE:"this browser does not support H264 decode.",NOT_SUPPORTED_SCREEN_SHARE:"this browser does not support screen share, please check the browser version.",NOT_SUPPORTED_SMALL_VIDEO:"this browser does not support small video, please check the browser version.",NOT_SUPPORTED_SEI:"this browser does not support SEI, please check the browser version.",NOT_SUPPORTED_WEBGL:"this browser does not support WebGL, please check the browser version.",NOT_SUPPORTED_CHROME_VERSION({fnName:o}){return`cannot call ${o} because the browser version is too low, please upgrade to the latest version`},DEVICE_ERROR({fnName:o,error:i}){return`'${o}' got device exception${i?`, error: ${i.toString()}.`:"."}`},DEVICE_NOT_FOUND_ERROR({fnName:o,deviceType:i=Kr(o),error:e}){return`NotFoundError, no ${i} detected, please check your device and the configuration on '${o}'${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_ALLOWED_ERROR({fnName:o,deviceType:i=Kr(o),error:e}){return`NotAllowedError, you have disabled ${i} access, please allow the current application to use the ${i}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_READABLE_ERROR({fnName:o,deviceType:i=Kr(o),error:e}){return`NotReadableError, the ${i} maybe in use by another APP, please check if the device is pre-occupied by another APP.`},DEVICE_OVERCONSTRAINED_ERROR({fnName:o,deviceType:i=Kr(o),error:e}){return`OverconstrainedError, the device ID is incorrect, please check whether the device ID passed in is correct${e?`, error: ${e.toString()}.`:"."}`},DEVICE_INVALID_STATE_ERROR({fnName:o,deviceType:i=Kr(o),error:e}){return`InvalidStateError, after the user clicks and interacts with the page, turn on the ${i}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_SECURITY_ERROR({fnName:o,deviceType:i=Kr(o),error:e}){return`SecurityError, check whether the system security policy restricts the use of the ${i}, and it is recommended to turn on the ${i} after the user interacts with the page${e?`, error: ${e.toString()}.`:"."}`},DEVICE_ABORT_ERROR({fnName:o,deviceType:i=Kr(o),error:e}){return`AbortError, an unknown exception in the system makes the device unusable, recommended to change the device or browser and re-check whether the device is normal${e?` error: ${e.toString()}.`:"."}`},CAMERA_RECOVER_FAILED({error:o}){return`camera recover capture failed ${(o==null?void 0:o.name)||""}: ${(o==null?void 0:o.originMessage)||(o==null?void 0:o.message)}`},MICROPHONE_RECOVER_FAILED({error:o}){return`microphone recover capture failed ${(o==null?void 0:o.name)||""}: ${(o==null?void 0:o.originMessage)||(o==null?void 0:o.message)}`},OPERATION_FAILED({fnName:o,error:i}){return`'${o}' failed, reason: ${i==null?void 0:i.toString()}`},FIREWALL_RESTRICTION(){return"media connection failure due to firewall restrictions, please try to change your network."},EVENT_HANDLER_ERROR({eventName:o}){return`an error was caught on trtc.on('${o}', handler), please check your code on 'handler'.`},VIDEO_CONTEXT_ERROR({reason:o,error:i}){return`video context error ${o} ${(i==null?void 0:i.name)||""} ${(i==null?void 0:i.message)||""}`},SERVER_ERROR({fnName:o,error:i}){return`'${o}' got server error: ${i==null?void 0:i.toString()}, please check the SDK documentation.`},NEED_TO_BUY({value:o,url:i}){return`You need to buy packages for ${o}. Refer to: ${i}`},ACCOUNT_NO_MONEY:({fnParams:o})=>`your TRTC account run out of credit, please recharge.${o.sdkAppId?` SDKAppId: ${o.sdkAppId}`:""}`,OPERATION_ABORT({fnName:o}){return`'${o}' abort`},UNKNOWN_ERROR({fnName:o,error:i}){return`'${o}' throw unknown exception${i?`, error: ${i.toString()}.`:"."}`}});function Kr(o){if(!o)return"camera";let i=o.toLowerCase();return i.includes("screen")?"screen share":i.includes("audio")?"microphone":"camera"}var wu=class o extends Error{constructor({code:e,extraCode:t,message:r="",messageParams:s,fnName:n="",originError:a}){var l;let c;r?c=r:c=Rp({code:e===U.SERVER_ERROR?e:t||e,params:v({fnName:n,error:a},s)});super(c);d(this,"name","RtcError");d(this,"code");d(this,"extraCode");d(this,"functionName");d(this,"message");d(this,"handler");d(this,"originError");this.name=Ot[e],this.code=e,this.extraCode=t,this.functionName=n,this.originError=a,this.message=c,this.extraCode===5302&&((l=this.originError)!=null&&l.message.includes("system"))&&(this.handler=()=>{let u={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},h={startLocalVideo:"webcam",startLocalAudio:"microphone"},m=document.createElement("a");wr?m.href=`ms-settings:privacy-${h[this.functionName]}`:Gt&&(m.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${u[this.functionName]}`),m.href.length>0&&m.click()})}static convertFrom(e,t,r){let s=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(Ve.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case I.JOIN_ROOM_FAILED:a.messageParams={fnParams:r};case I.SERVER_TIMEOUT:case I.SWITCH_ROLE_FAILED:case I.SWITCH_ROOM_FAILED:a.code=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=CE(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}s=new o(a),n&&(s.stack+=n.substr(n.indexOf(`
|
|
54
54
|
`)))}else{if(e instanceof o)return e;s=new o({code:U.UNKNOWN_ERROR,fnName:t,originError:e})}return s}};function CE(o){let i;switch(o){case"NotFoundError":i=5301;break;case"NotAllowedError":i=5302;break;case"NotReadableError":i=5303;break;case"OverconstrainedError":i=5304;break;case"InvalidStateError":i=5305;break;case"SecurityError":i=5306;break;case"AbortError":i=5307;break;default:i=5300}return i}var x=wu;function _r(o){return o==="sub"?"auxiliary":o==="auxiliary"?"sub":"main"}function Sn(o){return o===kt.QOS_PREFERENCE_CLEAR?"detail":o===kt.QOS_PREFERENCE_SMOOTH?"motion":""}function is(o,i){let e=i?dd:nr;return Ld(o)?v(v({},e),o):Lt[o]?Lt[o]:e}var yp={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}}},bp={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}}},rs={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(o,i,e){if(te(o)&&!document.getElementById(o))throw new x({code:U.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:i}})}},Np={name:"userId",required:!0,type:"string"},vp={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[kt.AUDIO_PROFILE_STANDARD,kt.AUDIO_PROFILE_STANDARD_STEREO,kt.AUDIO_PROFILE_HIGH,kt.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function os(o,i){if(!o)throw new x({code:U.INVALID_OPERATION,extraCode:5101,fnName:i})}function Dp(o,i,e){if(!o)throw new x({code:U.INVALID_OPERATION,extraCode:5102,fnName:i,messageParams:{value:e}})}function Mp(o,i,e){if(!(/^[1-9]\d*$/.test(String(o))&&o<4294967295))throw new x({code:U.INVALID_PARAMETER,extraCode:5013,fnName:i,messageParams:{key:e}})}function kp(o,i,e){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(o))throw new x({code:U.INVALID_PARAMETER,extraCode:5012,fnName:i,messageParams:{key:e}})}var UO={type:"number",notLessThanZero:!0},RE=(o,i)=>o.width*o.height>=i.width*i.height&&o.frameRate>=i.frameRate&&o.bitrate>=i.bitrate;function Op(o){var t;if(!((t=o==null?void 0:o.option)!=null&&t.small))return;if(!Pa()){y.warn("small stream is not supported"),delete o.option.small;return}let i=is(o.option.profile),e=is(o.option.small,!0);if(!RE(i,e)){y.warn(`small stream profile must be less than big stream profile. Big: ${JSON.stringify(i)}, Small: ${JSON.stringify(e)}`),delete o.option.small;return}}var yE={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(o,i,e){if(this._room.isJoined)throw new x({code:U.INVALID_OPERATION,extraCode:5104,fnName:e});if(o.roomId){if(te(o.roomId))throw new x({code:U.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:i}});Mp(o.roomId,e,i)}else if(o.strRoomId)kp(o.strRoomId,e,i);else throw new x({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:rs,mute:{type:["boolean","string"]},publish:{type:"boolean"},capture:{required:!1,type:"boolean"},option:yp},validate(o){var i,e;if(!((i=o==null?void 0:o.option)!=null&&i.videoTrack)&&Wi())throw new x({code:U.ENV_NOT_SUPPORTED,extraCode:5201});(e=o==null?void 0:o.option)!=null&&e.small&&Op(o)}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:w(v({},rs),{required:!1}),publish:{type:"boolean"},capture:{required:!1,type:"boolean"},mute:{type:["boolean","string"]},option:yp},validate(o){var i;(i=o==null?void 0:o.option)!=null&&i.small&&Op(o)}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:vp},validate(o){var i;if(!((i=o==null?void 0:o.option)!=null&&i.audioTrack)&&Wi())throw new x({code:U.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:vp}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:rs,publish:{type:"boolean"},option:bp},validate(o,i,e,t,r){var s;if(!((s=o==null?void 0:o.option)!=null&&s.videoTrack)){if(Wi())throw new x({code:U.ENV_NOT_SUPPORTED,extraCode:5201});if(!Xs())throw new x({code:U.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:rs,publish:{type:"boolean"},option:bp}},muteRemoteAudio:[Np,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[Np,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:rs,userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(o,i,e){os(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(o.userId);if(Dp(!!t,e,o),t&&(o.streamType==="main"&&!t.muteState.videoAvailable||o.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new x({code:U.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:o}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:w(v({},rs),{required:!1}),userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(o,i,e){os(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(o.userId);if(Dp(!!t,e,o),t&&(o.streamType==="main"&&!t.muteState.videoAvailable||o.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new x({code:U.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:o}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(o,i,e){if(o.userId!=="*"&&E(o.streamType))throw new x({code:U.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(o,i,e){os(this._room.isJoining||this._room.isJoined,e)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(o,i,e,t){if(!Ys)throw new x({code:U.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new x({code:U.INVALID_OPERATION,fnName:e,extraCode:5108});if(o.byteLength>1e3)throw new x({code:U.INVALID_PARAMETER,extraCode:5018,fnName:e});if(o.byteLength===0)throw new x({code:U.INVALID_PARAMETER,extraCode:5017,messageParams:{key:i},fnName:e});os(this._room.isJoined,e)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(o,i,e){if(!o&&!this._room.isMainStreamPublished||o&&!this._room.isAuxStreamPublished)throw new x({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(o,i,e,t){if(o.byteLength>1e3)throw new x({code:U.INVALID_PARAMETER,extraCode:5018,fnName:e});if(o.byteLength===0)throw new x({code:U.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:i}})}}},validate(o,i,e){if(os(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new x({code:U.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:i}})}},switchRoom:{name:"switchRoomConfig",type:"object",required:!0,validate(o,i,e){if(os(this._room.isJoined,e),this._room.useStringRoomId&&o.strRoomId===this._room.roomId||!this._room.useStringRoomId&&o.roomId===Number(this._room.roomId))throw new x({code:U.INVALID_PARAMETER,extraCode:5020,fnName:e,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(o.roomId&&this._room.useStringRoomId||!o.roomId&&o.strRoomId&&!this._room.useStringRoomId)throw new x({code:U.INVALID_PARAMETER,extraCode:5019,fnName:e,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(o.roomId)Mp(o.roomId,e,i);else if(o.strRoomId)kp(o.strRoomId,e,i);else throw new x({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}}}},Ue={TRTC:yE};var Ke=class extends Error{};function bE(o,i){let e=Nr(o);for(let t=0;t<i.length;t++)Bt(e[t],i[t]);return e}function NE(o){this._resolve=Promise.resolve(o)}function vE(o){this._reject=Promise.reject(o)}var gr=class gr{constructor(i,e){this.instance=i;this.group=e;d(this,"started",!1);d(this,"ops",[]);d(this,"startSame",()=>!0);d(this,"mergeUpdate",bE);let t=gr.instances.get(i);t?t.set(e,this):gr.instances.set(i,new Map([[e,this]]))}static get(i,e){if(!e)return;let t=gr.instances.get(i);return t&&t.get(e)||new gr(i,e)}static gets(i,e){let t=gr.instances.get(i),r=[];return t&&t.forEach((s,n)=>{e.test(n)&&r.push(s)}),r}action(i,e,t){let r=a=>{var c;return i===0?this.started=!0:i===3&&(this.started=!1),this.ops.shift(),(c=this.currentOp)==null||c.action(),a},s=a=>{var c,l;throw this.ops.shift(),i===0&&((c=this.currentOp)==null?void 0:c.type)===2&&this.ops.shift().reject(new Ke("start failed")),(l=this.currentOp)==null||l.action(),a},n={type:i,action:()=>e(...n.args).then(r,s),args:t,resolve:NE,reject:vE};try{switch(this.state){case 1:if(i===0)throw new Ke("already started");break;case 4:if(i===2)throw new Ke("not started");break;default:return this.cacheOp(n)}}catch(a){return Promise.reject(a)}return this.ops.push(n),n.promise=e(...n.args).then(r,s)}cacheOp(i){if(this.ops.length===1)switch(this.state){case 0:case 2:if(i.type===0)throw new Ke("already start");break;case 3:switch(i.type){case 2:throw new Ke("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new Ke("unknown state")}else switch(i.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let t=new Ke("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 Ke("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new Ke("start not allowed after update");case 0:throw new Ke("duplicate start");case 3:if(this.startSame(this.currentOp.args,i.args))throw this.ops.pop().reject(new Ke("keep start")),new Ke("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(gr,"instances",new WeakMap);var Zi=gr;var Ac=new WeakMap,Cc=(o,i)=>{if(i instanceof Ke){let{stack:e}=i;i=new x({code:U.OPERATION_ABORT,message:`${o} abort: ${i.message}`,fnName:o}),e&&(i.stack+=e.substr(e.indexOf(`
|
|
55
55
|
`)))}throw i};function Tr(o,i){return Y((e,t)=>function(...r){let s=Zi.get(this,typeof o=="string"?o:o.call(this,...r));return s?(i&&(s.startSame=i.bind(this)),s.action(0,e.bind(this),r).catch(Cc.bind(null,t))):e.apply(this,r)})}function eo(o,i){let{merge:e,debounce:t}=i||{};return Y((r,s)=>function(...n){let a=Zi.get(this,typeof o=="string"?o:o.call(this,...n));if(!a)return r.apply(this,n);if(e&&(a.mergeUpdate=e.bind(this)),t&&t.isNeedToDebounce.apply(this,n)){let{delay:c,getKey:l}=t;return new Promise((u,h)=>{var A,_;let m=(A=Ac.get(this))==null?void 0:A.get(l(...n));if(m){let{timeoutId:T,resolve:M}=m;clearTimeout(T),M()}let g=setTimeout(()=>{if(a.state===3||a.state===4)return u();a.action(2,r.bind(this),n).catch(Cc.bind(null,s)).then(u,h)},c);Ac.has(this)?(_=Ac.get(this))==null||_.set(l(...n),{timeoutId:g,resolve:u}):Ac.set(this,new Map([[l(...n),{timeoutId:g,resolve:u}]]))})}return a.action(2,r.bind(this),n).catch(Cc.bind(null,s))})}function Er(o){return Y((i,e)=>function(...t){let r=typeof o=="function"?o.call(this,...t):o;if(r instanceof RegExp)return Promise.all(Zi.gets(this,r).map(n=>n.action(3,()=>Promise.resolve(),t))).then(()=>i.call(this,...t));let s=Zi.get(this,r);return s?s.action(3,i.bind(this),t).catch(Cc.bind(null,e)):i.apply(this,t)})}var O={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"},wp=new Set([O.ERROR,O.AUTOPLAY_FAILED,O.KICKED_OUT,O.REMOTE_USER_ENTER,O.REMOTE_USER_EXIT,O.REMOTE_AUDIO_AVAILABLE,O.REMOTE_AUDIO_UNAVAILABLE,O.REMOTE_VIDEO_AVAILABLE,O.REMOTE_VIDEO_UNAVAILABLE,O.CONNECTION_STATE_CHANGED,O.PUBLISH_STATE_CHANGED,O.SCREEN_SHARE_STOPPED,O.DEVICE_CHANGED,O.FIRST_VIDEO_FRAME]);var Uu={};vi(Uu,{ScheduleRequestType:()=>Lp,getAbilityConfig:()=>ME,getScheduleDomain:()=>bc,isNeedToSchedule:()=>Rc,scheduleProxy:()=>Ri,sendScheduleRequest:()=>Pu,setIsNeedToSchedule:()=>Zt,setScheduleProxy:()=>yc});var Lu=null,Rc=!0;typeof document!="undefined"&&document.head.insertAdjacentHTML("beforeend",Object.values(ki).map(o=>`<link rel="dns-prefetch" href="https://${o}">`).join(`\r
|
|
56
56
|
`));function Zt(o){de(o)&&o!==Rc&&(Rc=o,y.info(`setIsNeedToSchedule ${o}`))}S.on("28",()=>Zt(!0));S.on("63",()=>Zt(!0));S.on("84",()=>Zt(!0));S.on("201",o=>{o.state==="RECONNECTING"&&Zt(!0)});S.on("202",o=>{o.state==="RECONNECTING"&&Zt(!0)});function DE(o,i,e){let t={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let r=performance.getEntriesByType("resource"),s=Sr(o,"config",p.MAIN),n=Sr(o,"config",p.BACKUP);for(let a of r)if(a.startTime>=e&&(a.name===s||a.name===n)&&a.transferSize>0){let c=a.name===s?p.MAIN:p.BACKUP,l=Math.round(a.duration),u=Math.round(a.domainLookupStart-a.startTime),h=a.redirectStart>0?Math.round(a.redirectEnd-a.redirectStart):0,m=a.fetchStart>0?Math.round(a.domainLookupStart-a.fetchStart):0,g=Math.round(a.domainLookupEnd-a.domainLookupStart),A=Math.round(a.requestStart-a.secureConnectionStart),_=Math.round(a.secureConnectionStart-a.connectStart),T=Math.round(a.responseStart-a.requestStart),M=Math.round(a.responseEnd-a.responseStart),K=[g,A,_,T,M];se.uploadEvent({log:`stat-schedule-net:${l}(${u}(${h}->${m})->${K.join("->")}) ${c}`,userId:i}),t=w(v({},t),{totalCost:l,local:u,dns:g,tcp:_,tls:A,request:T,response:M});break}}catch(r){y.error("getScheduleDetailCost error",r)}return t}function Pu(l){return f(this,arguments,function*({userId:o,sdkAppId:i,useStringRoomId:e,roomId:t,userSig:r,version:s,frameWorkType:n,role:a,latencyLevel:c}){if(!Rc&&Lu)return{isCached:!0,result:Lu};let u={delta:0,count:[1,1],msg:[],detail:[]};try{let h=new FormData;h.append("userId",String(o)),h.append("sdkAppId",String(i)),h.append("isStrGroupId",String(e)),h.append("groupId",String(t)),h.append("sdkVersion",s),h.append("userSig",String(r));let m=yield xr();m!=null&&m.model&&h.append("model",String(m==null?void 0:m.model)),a&&h.append("role",String(a)),c&&h.append("latencyLevel",String(c)),n&&h.append("frameWorkType",String(n));let g=B(),A=yield OE(h,u,i);A.config&&(A.config.loggerDomain&&Ar(A.config.loggerDomain),de(A.config.scheduleCache)&&Zt(!A.config.scheduleCache)),u.delta=B()-g;let _=DE(Number(i),o,g);return Lu=A,{isCached:!1,result:A,detailCost:_}}catch(h){let m=Se(h)?h[0]:h,g=q(m.code)?m.code:0,A=`schedule failed${m.message?`: ${m.message}`:""}`,_=new N({code:I.SCHEDULE_FAILED,extraCode:g,message:P({key:L.JOIN_ROOM_FAILED,data:{error:A,code:g}})});throw y.error(A,g),_}})}var Ri={main:"",backup:""};function yc(o){Se(o)?(Ri.main=o[0],Ri.backup=o[1]):Ri.main=o}var Lp=(t=>(t.CONFIG="config",t.TRTC_AUTO_CONF="trtcAutoConf",t.AUDIO_AI_AUTH="audioAiAuth",t))(Lp||{});function Sr(o,i,e=p.MAIN,t=!1){return`https://${Ri[e]||bc(o,e,t)}/api/v1/${i}`}function ME(o,i,e){let t=Sr(o,i),r=Sr(o,i,p.BACKUP),s=new URLSearchParams(e).toString(),n=fetch(`${t}?${s}`).then(c=>c.json()),a=fetch(`${r}?${s}`).then(c=>c.json());return kr([n,a])}function bc(o,i=p.MAIN,e=!1){let t;return Oi(o)?e?t=i===p.MAIN?ki.MAIN_OVERSEA_BACKUP:ki.BACKUP_OVERSEA:t=i===p.MAIN?ki.MAIN_OVERSEA:ki.BACKUP_OVERSEA:t=i===p.MAIN?ki.MAIN:ki.BACKUP,t}function kE(o,i,e){return new Promise((t,r)=>{Ui({url:o,body:i,timeout:e.timeout,priority:"high"}).then(s=>{s.data.code===0?t(s.data.data):r({code:s.data.code,message:s.data.msg})}).catch(r)})}var xp=(o,i)=>ni({retryFunction:kE,settings:{retries:3,timeout:0},onError:i,onRetrying:o});function OE(o,i,e){return new Promise((t,r)=>{let s=null;kr([xp(n=>i.count[0]=n+1,({error:n,retry:a,retriedCount:c,retryFuncArgs:l})=>{i.msg[0]=n.message,s||(c>=1&&(l[0]=Sr(e,"config",p.MAIN,!0)),a())})(Sr(e,"config",p.MAIN),o,{get timeout(){return Dr(2+i.count[0])*1e3}}),xp(n=>i.count[1]=n+1,({error:n,retry:a,retriedCount:c,retryFuncArgs:l})=>{i.msg[1]=n.message,s||(c>=2&&(l[0]=Sr(e,"config",p.BACKUP,!0)),a())})(Sr(e,"config",p.BACKUP),o,{get timeout(){return Dr(2+i.count[1])*1e3}})]).then(n=>{s=n,t(s)}).catch(r)})}var wE=o=>o.startsWith("data:application/octet-stream;base64,"),xE=o=>o.startsWith("file://"),In=class{constructor(){d(this,"_log");this._log=y.createLogger({id:"fd"})}download(i,e){return f(this,null,function*(){let{type:t="blob"}=e||{};i=ea(i);try{let r=B(),s;if(ne(fetch)?s=yield this.downloadWithFetch(i,t):s=yield this.downloadWithXHR(i,t),!s||!s.data)throw new Error("data is empty");let n=B()-r;return this._log.info(`downloaded: ${i}, return type: ${t}, cost: ${n}ms`),b.addSuccessEvent({key:522700,cost:B()-r}),s.data}catch(r){throw this._log.error(`failed to download: ${i}, error: ${r}`),b.addFailedEvent({key:522700,error:r}),r}})}downloadWithFetch(i,e){return f(this,null,function*(){this._log.info(`download with fetch: ${i}, return type: ${e}`);try{let t=yield fetch(i);if(!t.ok){let s=new Error(`network response was not ok: ${t.status}`);throw s.status=t.status,s}let r;return e==="arraybuffer"?r=yield t.arrayBuffer():r=yield t.blob(),{data:r}}catch(t){throw t}})}downloadWithXHR(i,e){return this._log.info(`download with xhr: ${i}, return type: ${e}`),new Promise((t,r)=>{let s=new XMLHttpRequest;s.open("GET",i,!0),s.responseType=e,s.onload=()=>{if(s.status===200||s.status===0&&s.response)t({data:s.response});else{let n=new Error(`XHR failed, status: ${s.status}`);n.status=s.status,r(n)}},s.onerror=r,s.send(null)})}loadWasm(i,e){return f(this,null,function*(){this._log.info(`loadWasm ${i}, importObject: ${JSON.stringify(e)}`);let t=B(),r=null,s=null;if(ne(WebAssembly.instantiateStreaming)&&!wE(i)&&!xE(i)&&ne(fetch))try{let n=fetch(i);r=(yield WebAssembly.instantiateStreaming(n,e)).instance}catch(n){s=n}if(!r)try{let n=yield this.download(i,{type:"arraybuffer"});r=(yield WebAssembly.instantiate(n,e)).instance}catch(n){s=n}if(r){let n=B()-t;return this._log.info(`loadedWasm ${i}, cost: ${n}ms`),b.addSuccessEvent({key:522701,cost:n}),r}throw this._log.error(`failed to loadWasm ${i}, error: ${s}`),b.addFailedEvent({key:522701,error:s}),s})}loadScript(i){this._log.info(`loadScript ${i}`);let e=B();return new Promise((t,r)=>{let s=document.createElement("script");s.type="text/javascript",s.onload=()=>{this._log.info(`loadedScript ${i}, cost: ${B()-e}ms`),b.addSuccessEvent({key:522702,cost:B()-e,split:1e3}),t(s)},s.onerror=n=>{this._log.error(`failed to loadScript ${i}, error: ${n}`),b.addFailedEvent({key:522702}),r(n)},s.crossOrigin="anonymous",s.src=i,document.head.append?document.head.append(s):document.getElementsByTagName("head")[0].appendChild(s)})}};D([St({settings:{timeout:0,retries:3},onError(i,e,t){var r;(i==null?void 0:i.status)===404||(r=i==null?void 0:i.message)!=null&&r.includes("404")?(this._log.warn("download 404, stop retry"),t(i)):e()},onRetrying(i){this._log.warn(`download retrying: ${i}`)}})],In.prototype,"download",1),D([St({settings:{timeout:3e3,retries:3},onRetrying(i){this._log.warn(`loadScript retrying: ${i}`)}})],In.prototype,"loadScript",1);var Vu=new In;function Pp({TRTC:o,room:i,errorModule:e,assetsPath:t}){return{TRTC:o,LocalMixVideoTrack:Zr,LocalVideoTrack:Be,LocalScreenTrack:Ze,room:i,assetsPath:t,fileDownloader:Vu,innerEmitter:S,constants:Td,environment:wo,utils:Gl,eventLogger:se,log:this.room.getLogger(),loggerManager:y,errorModule:e,kvStatManager:b,rtcDectection:pi,trtc:this,rx:Du,enums:ml,schedule:Uu,getDevices:Jo,initVisionTaskRegistry:(r,s="/mediapipe/vision.js")=>f(this,null,function*(){try{window.VisionTaskRegistry||(yield Vu.loadScript(`${r}/${s}`.replace(/([^:]\/)\/+/g,"$1"))),yield(yield window.VisionTaskRegistry.getInstance(r)).preloadModels([window.VisionTaskType.ImageSegmenter])}catch(n){throw new Error(`Virtual background assets not found. Please redeploy the assets of the npm package. ${n}`)}}),clearStarted:(r,s)=>{let n=r.getAlias(),a=Zi.instances.get(this);if(a)if(s){let c=a.get(n+s);if(!c)return;c.started=!1}else a.forEach((c,l)=>{l.startsWith(n)&&(c.started=!1)})},startGetPCM:En,createAudioNode:an}}var Up=(o,i)=>{let{emit:e}=o;return o.emit=(...t)=>{try{return e.apply(o,t)}catch(r){let s=P({key:L.CATCH_HANDLER_ERROR,data:{name:i,event:t[0]},addDocLink:!1});return y.warn(`${s}
|
|
57
57
|
|
|
58
|
-
${r.stack}`),!1}},o};var ss=new WeakMap;function Vp(o){let i=ss.get(o);i&&(i.forEach(e=>clearTimeout(e)),ss.delete(o))}function Bp(o,i){return Y((e,t)=>function(...r){let s=ss.get(this);s||(s=new Map,ss.set(this,s));let n=i(...r),a=s.get(n);if(!a||a<=0){e.apply(this,r);let c=setTimeout(()=>{var l;(l=ss.get(this))==null||l.delete(n)},o);s.set(n,c)}else{clearTimeout(a);let c=window.setTimeout(()=>{var l;e.apply(this,r),(l=ss.get(this))==null||l.delete(n)},o);s.set(n,c)}})}var Hp="trtc-sdk-v5",$p="5.12.0-beta.7";function qe(...o){return Y((i,e)=>function(...t){try{vc.call(this,o,t,e,this._name)}catch(r){return Promise.reject(r)}return i.apply(this,t)})}function Bu(...o){return Y((i,e)=>function(...t){try{vc.call(this,o,t,e,this._name)}catch(r){throw r}return i.apply(this,t)})}function vc(o,i,e,t){if(Se(o))for(let r=0;r<o.length;r++)Nc.call(this,{rule:o[r],value:i[r],key:o[r].name,fnName:e,className:t});else Nc.call(this,{rule:o,value:i[0],key:o.name,fnName:e,className:t})}function Nc({rule:o,value:i,key:e,fnName:t,className:r}){function s(c){return{code:U.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:o,value:i}}}if(E(i)){if(o.required)throw new x(s(5001));if(E(o.defaultValue)){ne(o.validate)&&o.validate.call(this,i,e,t,r,this);return}i=o.defaultValue}if(Array.isArray(o.type)){let c=!1;for(let l=0;l<o.type.length;l++)o.type[l]===null&&i===null&&(c=!0),ne(o.type[l])&&i instanceof o.type[l]&&(c=!0),te(o.type[l])&&Re(i)===o.type[l].toLowerCase()&&(c=!0);if(!c)throw new x({code:U.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:o.type.map(l=>Mr(l)?fo(l):te(l)?l:Re(l))},value:i}})}else if(!E(o.type)&&Re(i)!==o.type)throw new x(s(5002));if(o.allowEmpty===!1){let c=q(i)&&(i===0||Number.isNaN(i)),l=te(i)&&i.trim()==="";if(c||l)throw new x(s(5003))}if(o.notLessThanZero&&q(i)&&i<0)throw new x(s(5006));if(!E(o.min)&&q(i)&&i<o.min)throw new x(s(5007));if(!E(o.max)&&q(i)&&i>o.max)throw new x(s(5008));if(te(o.instanceOf)){if(!i||i._name!==o.instanceOf)throw new x(s(5004))}else if(ne(o.instanceOf)&&!(i instanceof o.instanceOf))throw new x(s(5004));if(Array.isArray(o.values)&&!o.values.includes(i))throw new x(s(5005));let{properties:n}=o;ze(n)&&ft(i)&&Object.keys(n).forEach(c=>{Nc.call(this,{rule:n[c],value:i&&i[c],key:`${c}`,fnName:t,className:r})});let{arrayItem:a}=o;ze(a)&&Se(i)&&i.forEach((c,l)=>{Nc.call(this,{rule:a,value:c,key:`${e}[${l}]`,fnName:t,className:r})}),ne(o.validate)&&o.validate.call(this,i,e,t,r,this)}function fe(o={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t,ignoreLog:r,ignoreErrorLog:s}=o;return Y((n,a)=>function(...c){var g,A,_;function l(T,M,K){if(K&&K.includes(T))return"hided";if(e){let G=e(...c);if(c[G.argIndex]===M)return G.value}if(M===c||T in c)return M;try{return M instanceof HTMLElement?`id: ${M.id} type:${Re(M)}`:M instanceof MediaStreamTrack?ta(M):(JSON.stringify(M),M)}catch(G){return`type:${Re(M)}`}}let u=this._log||y;if(r!=null&&r(...c))return n.apply(this,c);c.length>0?u.info(`${a}() ${JSON.stringify(c,(T,M)=>l(T,M,["userSig","privateMapKey"]))}`):u.info(`${a}()`);let h=t?t(...c):Da[a],m=(s==null?void 0:s(...c))||!1;try{let T=n.apply(this,c),M=B();if(lr(T)){let K=`${a.includes("Plugin")?`${((A=(g=c[0]).getName)==null?void 0:A.call(g))||""} `:" "}`;return T.then(G=>(u.info(`${a}() success ${K}${i.call(this,...c)}`),b.addSuccessEvent({key:h,cost:B()-M}),G)).catch(G=>{var J;G=x.convertFrom.call(this,G,a,c.length===1?c[0]:c);let ee=G.extraCode||G.code,_e=(J=G.message)!=null&&J.includes(ee)?"":` code:${ee}`;throw m||u.error(`${a}() failed ${K}${i.call(this,...c)} ${G}${_e} params: ${JSON.stringify(c,l)}`),b.addFailedEvent({key:h,error:G}),G})}return b.addSuccessEvent({key:h}),T}catch(T){T=x.convertFrom.call(this,T,a);let M=T.extraCode||T.code,K=(_=T.message)!=null&&_.includes(M)?"":` code:${M}`;throw m||u.error(`${a}() failed ${T}${K} params: ${JSON.stringify(c,l)}`),b.addFailedEvent({key:h,error:T}),T}})}var Dc=o=>Y((i,e)=>function(t,r){return f(this,null,function*(){let s=this._plugins.get(t);if(!s)throw this._log.error(`plugin ${String(t)} is not found`),new x({code:U.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});if(ne(s.constructor.isSupported)&&!s.constructor.isSupported())throw this._log.error(`plugin ${String(t)} is not supported`),new x({code:U.ENV_NOT_SUPPORTED,message:`plugin ${String(t)} is not supported`,extraCode:5210,fnName:e});return vc.call(this,s.getValidateRule(o),[r],e,"TRTC"),i.call(this,s,r)})});var Mc=0,Fu,Ki=class Ki{constructor(i){this.core=i;d(this,"log");d(this,"customAudioReferenceMap",new Map);d(this,"audioRefId",0);d(this,"audioContext",Ee());d(this,"localAudioWorkletNode");d(this,"screenAudioWorkletNode");d(this,"mixNode");d(this,"silentNode");Mc=Mc+1,this.log=i.log.createChild({id:`${this.getAlias()}${Mc}`}),this.log.info(`created id=${this.getAlias()}${Mc}`)}static getStartValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,t,r,s){if(!i.room.audioManager.hasAudioTrack&&!i.room.audioManager.hasScreenAudioTrack)throw new x({code:U.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return Fu||(Fu=this.doPreload(i)),Fu}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield ji(this.audioContext,t)}catch(r){this.log.error(`preload audioProcessor failed. ${r}`)}finally{URL.revokeObjectURL(t)}})}getName(){return Ki.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(i){switch(i){case"start":return Ki.getStartValidateRule(this.core);case"update":return Ki.updateValidateRule;case"stop":return Ki.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e}=this.core,{sdkAppId:t,userId:r,assetsPath:s=this.core.assetsPath,audioReference:n,processLevel:a,enableDump:c,isLocalAudioNeedAudioProcess:l=!0,isScreenAudioNeedAudioProcess:u=!0}=i;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=l,this.core.room.audioManager.isScreenAudioNeedAudioProcess=u,!s)throw new x({code:U.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(yield this.preload(`${s}/audioProcessor-wasm.js`),!this.localAudioWorkletNode||!this.screenAudioWorkletNode){let h=String(Date.now()).slice(0,-3),{auth:m,sign:g,status:A,message:_}=yield PE(w(v({},i),{timestamp:h}));if(!m)throw this.log.info(`audioProcessor: ${r} auth result: ${m}. Message: ${_}`),new x({code:U.INVALID_PARAMETER,message:_});this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",t,r,h,g,A,e),this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",t,r,h,g,A,e)}this.mixNode||(this.mixNode=this.audioContext.createGain(),this.mixNode.gain.value=1),this.silentNode||(this.silentNode=this.audioContext.createConstantSource(),this.silentNode.offset.setValueAtTime(0,this.audioContext.currentTime),this.silentNode.start()),this.localAudioWorkletNode.port.postMessage({type:"enable"}),this.screenAudioWorkletNode.port.postMessage({type:"enable"}),e.audioManager.addAudioProcessor(this.localAudioWorkletNode,this.mixNode,this.silentNode,this.screenAudioWorkletNode),E(n)||n.forEach(h=>{this.customAudioReferenceMap.set(h,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:h,refId:`o-${this.audioRefId++}`})}),E(a)||this.localAudioWorkletNode.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:a}}),E(c)||this.localAudioWorkletNode.port.postMessage({type:"dump",data:{enable:c}})})}update(i){return f(this,null,function*(){if(!this.localAudioWorkletNode||!this.screenAudioWorkletNode)return;let{audioReference:e,enableDump:t,processLevel:r}=i;E(e)||(this.customAudioReferenceMap.forEach((s,n)=>{this.customAudioReferenceMap.delete(n),this.core.room.audioManager.updateAudioReference({type:"remove",refId:s})}),e.forEach(s=>{this.customAudioReferenceMap.set(s,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:s,refId:`o-${this.audioRefId++}`})})),E(r)||this.localAudioWorkletNode.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:r}}),E(t)||(this.localAudioWorkletNode.port.postMessage({type:"dump",data:{enable:t}}),this.screenAudioWorkletNode.port.postMessage({type:"dump",data:{enable:t}}))})}stop(){return f(this,null,function*(){if(!this.localAudioWorkletNode||!this.mixNode||!this.silentNode||!this.screenAudioWorkletNode)return;let{room:i}=this.core;this.localAudioWorkletNode.port.postMessage({type:"disable"}),this.screenAudioWorkletNode.port.postMessage({type:"disable"}),yield i.audioManager.removeAudioProcessor(this.localAudioWorkletNode,this.mixNode,this.silentNode,this.screenAudioWorkletNode)})}destroy(){this.localAudioWorkletNode&&(this.localAudioWorkletNode.port.onmessage=null),this.screenAudioWorkletNode&&(this.screenAudioWorkletNode.port.onmessage=null)}initWorkletNode(i,e,t,r,s,n,a,c){i.port.postMessage({type:"init",data:{sdkAppId:String(t),userId:r,timestamp:s,sign:n,status:a}}),i.port.onmessage=l=>{var h;let{data:u}=l;switch(u.type){case"cost":let m=(u==null?void 0:u.value)>10?"info":"debug";this.log[m](`[${e}] avg cost: ${u.value} max: ${u==null?void 0:u.max}(${no(new Date(u==null?void 0:u.maxCostTimestamp))}) hist: ${(h=u==null?void 0:u.hist)==null?void 0:h.join(" ")}`);return;case"log":this.log[u.logLevel](`[${e}] ${u.value}`);return;case"dump":S.emit("265",{room:c,data:u.value,type:e==="localAudio"?"dump":"dump-screen-audio"});return}}}};d(Ki,"updateValidateRule",{type:"object"}),d(Ki,"stopValidateRule",{type:"object"}),d(Ki,"Name","AudioProcessor");var kc=Ki;function LE(o,i=p.MAIN){return`https://${Ri[i]||bc(o,i)}/api/v1/audioAiAuth`}function PE(r){return f(this,arguments,function*({sdkAppId:o,userId:i,userSig:e,timestamp:t}){let n=`${LE(o)}?sdkAppId=${o}&userId=${i}&userSig=${e}×tamp=${t}`,a=yield fetch(n),{data:{errCode:c,errMsg:l,sign:u,status:h}}=yield a.json();if(h==="1")return{auth:!0,sign:u,status:h,message:l};let m=Oi(o)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",g="Init RTCAudioProcessor failed.",A="";switch(c){case 1:A="Please check your params.";break;case 2:A=`You need to buy packages. Refer to: ${m}`;break;case 3:A="Server is invalid. Please contact our engineer. ";break;case 4:A=`Your packages is not active. Refer to: ${m}`;break;case 5:A=`Your packages is expired. Refer to: ${m}`;break;case 6:A="Your version is not supported.";break}return{auth:!1,status:h,message:l?`${g} Reason: ${l}. ${A}`:`${g}, ${A}`}})}var Oc=0,Hu=class{constructor(i,e){d(this,"player");d(this,"publisher");d(this,"mixInput");this.mixInput=new Wo(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)}}reset(){this.seek(0),this.mixInput.connect()}seek(i){this.player&&(i<0&&i>this.player.duration||(this.player.currentTime=i,this.publisher.currentTime=i))}play(){var i,e;return(i=this.publisher)==null||i.play(),(e=this.player)==null?void 0:e.play()}pause(){var i,e;(i=this.player)==null||i.pause(),(e=this.publisher)==null||e.pause()}stop(){var i;(i=this.player)==null||i.pause(),this.mixInput.disconnect()}setOperation(i){i==="pause"&&this.pause(),i==="resume"&&(this.pause(),this.play()),i==="stop"&&(this.pause(),this.seek(0))}set volume(i){!this.player||!this.publisher||(this.player.volume=i,this.publisher.volume=i)}set loop(i){!this.player||!this.publisher||(this.player.loop=i,this.publisher.loop=i)}set playbackRate(i){!this.player||!this.publisher||(this.player.playbackRate=i,this.publisher.playbackRate=i)}};function ns(o,i){if(i&&typeof i!="function")throw new x({code:U.INVALID_PARAMETER,message:`start audioMixer plugin: param ${o} should be a function.`})}var yi=class yi{constructor(i){this.core=i;d(this,"log");d(this,"mixedMusicMap",new Map);d(this,"cacheMusicMap",new Map);Oc=Oc+1,this.log=i.log.createChild({id:`${this.getAlias()}${Oc}`}),this.log.info(`created id=${this.getAlias()}${Oc}`)}getName(){return yi.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return yi.startValidateRule;case"update":return yi.updateValidateRule;case"stop":return yi.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e}=this.core;this.log.info(`add music source, id: ${i.id} url: ${i.url}, track: ${i.track}`);let{id:t,url:r}=i;if(this.mixedMusicMap.has(t))return;let s=this.cacheMusicMap.get(t);s?i.url?s.reset():(s.mixInput.replaceSource(i.track),s.mixInput.connect()):(s=new Hu(i,e.audioManager),this.cacheMusicMap.set(t,s)),s.updateListener(i),s.updateSettings(i),yield s.play(),this.mixedMusicMap.set(t,s),s.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"add",audioReference:s.mixInput.source.node,refId:`ax-${t}`}),this.log.info(`start mix audio track ${t} success.`),b.addEnum({key:502700,value:3}),this.kvUpload(i)})}update(i){return f(this,null,function*(){let{id:e,operation:t,seekFrom:r,playbackRate:s}=i;this.log.info(`update music source, ${JSON.stringify(i)}`);let n=this.mixedMusicMap.get(e);if(!n){this.log.warn(`update music source failed, music id: ${e} not found.`);return}n.updateSettings(i),n.updateListener(i),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:s,operation:n,seekFrom:a,onTimeUpdate:c,onDurationChange:l,onEnded:u}=i;e&&b.addCount({key:502711}),t&&b.addCount({key:502703}),r&&b.addCount({key:502704}),s&&b.addCount({key:502705}),n&&b.addCount({key:502706}),a&&b.addCount({key:502707}),typeof c!="function"&&b.addCount({key:502709}),typeof u!="function"&&b.addCount({key:502710}),typeof l!="function"&&b.addCount({key:502708})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((i,e)=>{i!=null&&i.mixInput.track&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:i.mixInput.track,refId:e}),this.stop({id:e})})}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}};d(yi,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(i,e,t){if(i.url&&i.url!=="*"){let r=i.url.split("?")[0],s=["mp3","ogg","wav","flac"],n=r.split(".").pop(),a=s.indexOf(n)>=0,c=r.startsWith("blob"),l=r.startsWith("data");if(!(a||c||l))throw new x({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 x({code:U.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});ns("onTimeUpdate",i.onTimeUpdate),ns("onEnded",i.onEnded),ns("onDurationChange",i.onDurationChange)}}),d(yi,"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){ns("onTimeUpdate",i.onTimeUpdate),ns("onEnded",i.onEnded),ns("onDurationChange",i.onDurationChange)}}),d(yi,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),d(yi,"Name","AudioMixer");var wc=yi;var xc=0,$u,er=class er{constructor(i){this.core=i;d(this,"log");d(this,"audioContext",Ee("denoiser"));d(this,"workletNode");xc=xc+1,this.log=i.log.createChild({id:`${this.getAlias()}${xc}`}),this.log.info(`created id=${this.getAlias()}${xc}`)}static startValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,t,r,s){if(!i.room.audioManager.hasAudioTrack)throw new x({code:U.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return $u||($u=this.doPreload(i)),$u}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield ji(this.audioContext,t)}catch(r){throw this.log.error("load worklet failed",r),r}finally{URL.revokeObjectURL(t)}})}getName(){return er.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(i){switch(i){case"start":return er.startValidateRule(this.core);case"update":return er.updateValidateRule;case"stop":return er.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 x({code:U.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(yield this.preload(`${r}/denoiser-wasm.js`),!this.workletNode){let s=String(Date.now()).slice(0,-3),{auth:n,sign:a,status:c,message:l}=yield VE(t,w(v({},i),{timestamp:s}));if(!n)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${n}. Message: ${l}`),new x({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:s,sign:a,status:c}}),this.workletNode.port.onmessage=u=>{var m;let{data:h}=u;if(h.type==="cost"){let g=(h==null?void 0:h.max)>20?"warn":(h==null?void 0:h.max)>10?"info":"debug";this.log[g](`avg cost: ${h.value} max: ${h==null?void 0:h.max}(${no(new Date(h==null?void 0:h.maxCostTimestamp))}) hist: ${(m=h==null?void 0:h.hist)==null?void 0:m.join(" ")}`)}else h.type==="log"&&this.log[h.logLevel](`${h.value}`)}}this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(){return f(this,null,function*(){})}stop(){return f(this,null,function*(){if(!this.workletNode)return;let{room:i}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield i.audioManager.removeDenoiser(this.workletNode)})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};d(er,"updateValidateRule",{type:"object"}),d(er,"stopValidateRule",{type:"object"}),d(er,"Name","AIDenoiser");var Lc=er;function VE(s,n){return f(this,arguments,function*(o,{sdkAppId:i,userId:e,userSig:t,timestamp:r}){try{let{data:{errCode:a,errMsg:c,sign:l,status:u}}=yield o.getAbilityConfig(i,o.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:i,userId:e,userSig:t,timestamp:r});if(u==="1")return{auth:!0,sign:l,status:u,message:c};let h=Oi(i)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",m="Init RTCAIDenoiser failed.",g="";switch(a){case 1:g="Please check your params.";break;case 2:g=`You need to buy packages. Refer to: ${h}`;break;case 3:g="Server is invalid. Please contact our engineer. ";break;case 4:g=`Your packages is not active. Refer to: ${h}`;break;case 5:g=`Your packages is expired. Refer to: ${h}`;break;case 6:g="Your version is not supported.";break}return{auth:!1,status:u,message:c?`${m} Reason: ${c}. ${g}`:`${m}, ${g}`}}catch(a){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${a}`}}})}var Wp=Ge(tt(),1);var Gu=class extends Wp.EventEmitter{constructor(){super();d(this,"observer");d(this,"state","nominal");this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return f(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!pe&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){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)&&y.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})}}},BE=new Gu,Wu=BE;function Ju([o,i]){let e=i.byteLength,t=parseInt(String(e/255),10),r=e%255,s=[];s.push(0,0,0,1,6,o);for(let a=0;a<t;a++)s.push(255);s.push(r);let n=new DataView(i);return s.push(...new Uint8Array(n.buffer)),s.push(128),new zi(new DataView(new Uint8Array(s).buffer),!0)}function qu(o){return o.type==="empty"||o.data.byteLength===0}function ju(o){return o.getInt32(0)===1&&o.getInt8(4)===6}function Xu(o){let i=0,e=0,t=new DataView(o);for(let r=0;r<o.byteLength;r++)switch(t.getUint8(r)){case 0:i++;break;case 1:(i===2||i===3)&&e++,i=0;break;default:i=0;break}return e}function zu({frame:o,seiMessageList:i}){if(!i||i.length===0||o.data.byteLength===0)return o;let t=9-Xu(o.data);if(t<=0)return o;let r=i.splice(0,t).reverse().map(Ju),s=r.reduce((u,h)=>u+h.dataView.byteLength,0),n=new ArrayBuffer(s+o.data.byteLength),a=new DataView(n),c=new DataView(o.data),l=0;for(let u=0;u<r.length;u++)for(let h=0;h<r[u].dataView.byteLength;h++)a.setInt8(l++,r[u].dataView.getInt8(h));for(let u=0;u<o.data.byteLength;u++)a.setInt8(l++,c.getInt8(u));return o.data=n,o}function Qu({frame:o,onSEI:i}){try{let e=new DataView(o.data);if(qu(o)||!ju(e))return o;let t=[],r=0,s=-1,n=-1;for(let a=0;a<o.data.byteLength;a++){let c=e.getUint8(a);if(c===0)r++;else if(c===1){if(r===2||r===3){let l=a-r;if(s===-1?s=l:n===-1&&(n=l,t.push(new zi(new DataView(e.buffer.slice(s,n)))),s=l,n=-1),!(e.getUint8(a+1)===6)){o.data=e.buffer.slice(l);break}}r=0}else r=0}i==null||i(t.reverse())}catch(e){}return o}var Yu=0,An=class An{constructor(i){this.core=i;d(this,"log");d(this,"_seiMessageList",[]);d(this,"_smallSeiMessageList",[]);d(this,"_subStreamSeiMessageList",[]);Yu++,this.log=i.log.createChild({id:`${this.getAlias()}${Yu}`}),this.log.info(`[sei] created id=${this.getAlias()}${Yu}`),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 zu({frame:i,seiMessageList:t})}catch(t){this.log.warn(t)}return i}decode({frame:i,track:e}){return Qu({frame:i,onSEI:t=>{t.forEach(r=>{this.core.trtc.emit(O.SEI_MESSAGE,{seiPayloadType:r.seiPayloadType,data:r.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"})})}})}destroy(){this.log.debug("destory"),this.stop(),delete this.core}getValidateRule(i){switch(i){case"start":return{type:"object"};case"update":return{type:"object"};case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:Ji?this.encode:zu,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:Ji?this.decode:Qu,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update({buffer:i,options:e}){var s;let t=[e.seiPayloadType,i],r=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(t):(this._seiMessageList.push(t),r&&this._smallSeiMessageList.push(t)),(s=this.core.room.scriptTransformWorker)==null||s.postMessage({type:"sei",data:t,isMain:!e.toSubStream,small:r})}getName(){return An.Name}getAlias(){return"sei"}getGroup(){return"sei"}};d(An,"autoStart",!0),d(An,"Name","SEI");var Pc=An;function Zu({frame:o,onDump:i}){return i==null||i(),o}function Ku({frame:o,onDump:i}){return i==null||i(),o}var Jp={"play() error: NotAllowedError:":{tips:o=>o.includes("main <video>")||o.includes("main <audio>")?"Remote stream auto play is restricted and playback fails":"Local stream playback failure, generally only occurs in Android WeChat devices, no need to handle",color:"red",class:"red"},"updateStream() try to recover local stream":{tips:"Device acquisition exception, automatic recovery is in progress"},"updateStream() recover local stream successfully":{tips:"Device acquisition exception, automatic recovery is successful"},"updateStream() failed to recover local stream":{tips:"Device acquisition exception, automatic recovery failed"},"main stream - video track is muted":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is muted":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is muted":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unable to provide media output":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is unable to provide media output":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is unable to provide media output":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unmuted":{tips:"Received enough playback video data"},"main stream - audio track is unmuted":{tips:"Received enough playback audio data"},"auxiliary stream - video track is unmuted":{tips:"Received enough playback screen sharing data"},"main stream - audio player track is ended":{tips:"Remote audio track stopped"},"main stream - video player track is ended":{tips:"Remote video track stopped"},"auxiliary stream - video player track is ended":{tips:"Received enough playback screen sharing data"},"stream - video track is muted":{tips:"Camera capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"stream - video track is unable to provide media output":{tips:"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked, and the customer needs to re-acquire. SDK v4.11.4+ will automatically resume acquisition without customer intervention",color:"orange"},"video track is unable to provide media output":{tips:o=>o.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"stream - audio track is muted":{tips:"Microphone capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"audio track is unable to provide media output":{tips:o=>o.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"Microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio track is unable to provide media output":{tips:"The microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"is adding audio track to current published local stream":{tips:"add audio track",color:"orange"},"is removing audio track from current published local stream":{tips:"remove audio track",color:"orange"},"is removing video track from current published local stream":{tips:"remove video track",color:"orange"},"is adding video track to current published local stream":{tips:"add video track",color:"orange"},"is replacing audio track to current published local main stream":{tips:"replace audio track",color:"orange"},"is replacing video track to current published local main stream":{tips:"replace video track",color:"orange"},"downlink network quality change":{tips:"Downstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"uplink network quality change":{tips:"Upstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"localStream mute video":{tips:"mute upstream video stream",color:"orange"},"localStream unmute video":{tips:"unmute upstream video stream",color:"orange"},"localStream mute audio":{tips:"mute upstream audio stream",color:"orange"},"localStream unmute audio":{tips:"unmute upstream audio stream",color:"orange"},"black detected":{tips:"Detect black screen, which means fps = 0. It is usually caused by network, and the network will be recovered after a while. If the network is normal but has not been restored, it is an abnormal situation."},'main stream start to play with options: {"muted":true}':{tips:"Play the remote stream in silent mode. Generally, the remote stream does not need to be played in silent mode. You need to confirm whether the parameters passed in the client stream.play API call are correct.",color:"orange"},"main stream - audio player is starting playing":{tips:"Remote stream audio playback success",color:"#0dd90d",class:"success"},"main stream - video player is starting playing":{tips:"Remote stream video playback success",color:"#0dd90d",class:"success"},"video player is playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"audio player is playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"stream - video player is starting playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"stream - audio player is starting playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"switch camera success":{tips:"Switch camera success",color:"#0dd90d",class:"success"},"switch microphone success":{tips:"Switch microphone success",color:"#0dd90d",class:"success"},gotStream:{tips:"Local stream capture success"},"local stream is published successfully":{tips:"Publish success",color:"#0dd90d",class:"success"},"encoderImplementation change to OpenH264":{tips:"Use software encoding"},"encoderImplementation change to ExternalEncoder":{tips:"Use hardware encoding"},"getUserMedia with constraints":{tips:"Start media (camera/microphone) capture"},"getDisplayMedia with constraints":{tips:"Start screen sharing capture"},"client-banned":{tips:"Kicked out of the room",color:"red",class:"red",textColor:"#fff"},user_timeout:{tips:"The backend is too long without receiving SDK heartbeat, which is usually caused by the JS thread being blocked for a long time. If the reproduction probability is high, the application browser Performance tool analyzes where the JS thread is blocked.",color:"red",class:"red",textColor:"#fff"},"schedule failed":{tips:"Signaling request failed, does not affect the normal room entry process, SDK will connect to the default signaling domain."},"updateStream() video flag is true, but no camera detected, set video to false":{tips:"When trying to resume camera acquisition, the camera acquisition is not resumed because it is detected that there is no camera.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to bandwidth":{tips:"bandwidth estimation is not enough to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to cpu":{tips:"cpu load is too high to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: hidden":{tips:"User page switched to backend, in mobile devices, this will cause the device to pause the capture, and it will be restored when the user switches backend to the frontend.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: visible":{tips:"User page switched to frontend",color:"orange",class:"orange",textColor:"#fff"},"main stream - audio player is paused":{tips:`The remote stream audio playback is paused, which usually has two possibilities:
|
|
58
|
+
${r.stack}`),!1}},o};var ss=new WeakMap;function Vp(o){let i=ss.get(o);i&&(i.forEach(e=>clearTimeout(e)),ss.delete(o))}function Bp(o,i){return Y((e,t)=>function(...r){let s=ss.get(this);s||(s=new Map,ss.set(this,s));let n=i(...r),a=s.get(n);if(!a||a<=0){e.apply(this,r);let c=setTimeout(()=>{var l;(l=ss.get(this))==null||l.delete(n)},o);s.set(n,c)}else{clearTimeout(a);let c=window.setTimeout(()=>{var l;e.apply(this,r),(l=ss.get(this))==null||l.delete(n)},o);s.set(n,c)}})}var Hp="trtc-sdk-v5",$p="5.12.0-beta.8";function qe(...o){return Y((i,e)=>function(...t){try{vc.call(this,o,t,e,this._name)}catch(r){return Promise.reject(r)}return i.apply(this,t)})}function Bu(...o){return Y((i,e)=>function(...t){try{vc.call(this,o,t,e,this._name)}catch(r){throw r}return i.apply(this,t)})}function vc(o,i,e,t){if(Se(o))for(let r=0;r<o.length;r++)Nc.call(this,{rule:o[r],value:i[r],key:o[r].name,fnName:e,className:t});else Nc.call(this,{rule:o,value:i[0],key:o.name,fnName:e,className:t})}function Nc({rule:o,value:i,key:e,fnName:t,className:r}){function s(c){return{code:U.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:o,value:i}}}if(E(i)){if(o.required)throw new x(s(5001));if(E(o.defaultValue)){ne(o.validate)&&o.validate.call(this,i,e,t,r,this);return}i=o.defaultValue}if(Array.isArray(o.type)){let c=!1;for(let l=0;l<o.type.length;l++)o.type[l]===null&&i===null&&(c=!0),ne(o.type[l])&&i instanceof o.type[l]&&(c=!0),te(o.type[l])&&Re(i)===o.type[l].toLowerCase()&&(c=!0);if(!c)throw new x({code:U.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:o.type.map(l=>Mr(l)?fo(l):te(l)?l:Re(l))},value:i}})}else if(!E(o.type)&&Re(i)!==o.type)throw new x(s(5002));if(o.allowEmpty===!1){let c=q(i)&&(i===0||Number.isNaN(i)),l=te(i)&&i.trim()==="";if(c||l)throw new x(s(5003))}if(o.notLessThanZero&&q(i)&&i<0)throw new x(s(5006));if(!E(o.min)&&q(i)&&i<o.min)throw new x(s(5007));if(!E(o.max)&&q(i)&&i>o.max)throw new x(s(5008));if(te(o.instanceOf)){if(!i||i._name!==o.instanceOf)throw new x(s(5004))}else if(ne(o.instanceOf)&&!(i instanceof o.instanceOf))throw new x(s(5004));if(Array.isArray(o.values)&&!o.values.includes(i))throw new x(s(5005));let{properties:n}=o;ze(n)&&ft(i)&&Object.keys(n).forEach(c=>{Nc.call(this,{rule:n[c],value:i&&i[c],key:`${c}`,fnName:t,className:r})});let{arrayItem:a}=o;ze(a)&&Se(i)&&i.forEach((c,l)=>{Nc.call(this,{rule:a,value:c,key:`${e}[${l}]`,fnName:t,className:r})}),ne(o.validate)&&o.validate.call(this,i,e,t,r,this)}function fe(o={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t,ignoreLog:r,ignoreErrorLog:s}=o;return Y((n,a)=>function(...c){var g,A,_;function l(T,M,K){if(K&&K.includes(T))return"hided";if(e){let G=e(...c);if(c[G.argIndex]===M)return G.value}if(M===c||T in c)return M;try{return M instanceof HTMLElement?`id: ${M.id} type:${Re(M)}`:M instanceof MediaStreamTrack?ta(M):(JSON.stringify(M),M)}catch(G){return`type:${Re(M)}`}}let u=this._log||y;if(r!=null&&r(...c))return n.apply(this,c);c.length>0?u.info(`${a}() ${JSON.stringify(c,(T,M)=>l(T,M,["userSig","privateMapKey"]))}`):u.info(`${a}()`);let h=t?t(...c):Da[a],m=(s==null?void 0:s(...c))||!1;try{let T=n.apply(this,c),M=B();if(lr(T)){let K=`${a.includes("Plugin")?`${((A=(g=c[0]).getName)==null?void 0:A.call(g))||""} `:" "}`;return T.then(G=>(u.info(`${a}() success ${K}${i.call(this,...c)}`),b.addSuccessEvent({key:h,cost:B()-M}),G)).catch(G=>{var J;G=x.convertFrom.call(this,G,a,c.length===1?c[0]:c);let ee=G.extraCode||G.code,_e=(J=G.message)!=null&&J.includes(ee)?"":` code:${ee}`;throw m||u.error(`${a}() failed ${K}${i.call(this,...c)} ${G}${_e} params: ${JSON.stringify(c,l)}`),b.addFailedEvent({key:h,error:G}),G})}return b.addSuccessEvent({key:h}),T}catch(T){T=x.convertFrom.call(this,T,a);let M=T.extraCode||T.code,K=(_=T.message)!=null&&_.includes(M)?"":` code:${M}`;throw m||u.error(`${a}() failed ${T}${K} params: ${JSON.stringify(c,l)}`),b.addFailedEvent({key:h,error:T}),T}})}var Dc=o=>Y((i,e)=>function(t,r){return f(this,null,function*(){let s=this._plugins.get(t);if(!s)throw this._log.error(`plugin ${String(t)} is not found`),new x({code:U.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});if(ne(s.constructor.isSupported)&&!s.constructor.isSupported())throw this._log.error(`plugin ${String(t)} is not supported`),new x({code:U.ENV_NOT_SUPPORTED,message:`plugin ${String(t)} is not supported`,extraCode:5210,fnName:e});return vc.call(this,s.getValidateRule(o),[r],e,"TRTC"),i.call(this,s,r)})});var Mc=0,Fu,Ki=class Ki{constructor(i){this.core=i;d(this,"log");d(this,"customAudioReferenceMap",new Map);d(this,"audioRefId",0);d(this,"audioContext",Ee());d(this,"localAudioWorkletNode");d(this,"screenAudioWorkletNode");d(this,"mixNode");d(this,"silentNode");Mc=Mc+1,this.log=i.log.createChild({id:`${this.getAlias()}${Mc}`}),this.log.info(`created id=${this.getAlias()}${Mc}`)}static getStartValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,t,r,s){if(!i.room.audioManager.hasAudioTrack&&!i.room.audioManager.hasScreenAudioTrack)throw new x({code:U.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return Fu||(Fu=this.doPreload(i)),Fu}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield ji(this.audioContext,t)}catch(r){this.log.error(`preload audioProcessor failed. ${r}`)}finally{URL.revokeObjectURL(t)}})}getName(){return Ki.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(i){switch(i){case"start":return Ki.getStartValidateRule(this.core);case"update":return Ki.updateValidateRule;case"stop":return Ki.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e}=this.core,{sdkAppId:t,userId:r,assetsPath:s=this.core.assetsPath,audioReference:n,processLevel:a,enableDump:c,isLocalAudioNeedAudioProcess:l=!0,isScreenAudioNeedAudioProcess:u=!0}=i;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=l,this.core.room.audioManager.isScreenAudioNeedAudioProcess=u,!s)throw new x({code:U.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(yield this.preload(`${s}/audioProcessor-wasm.js`),!this.localAudioWorkletNode||!this.screenAudioWorkletNode){let h=String(Date.now()).slice(0,-3),{auth:m,sign:g,status:A,message:_}=yield PE(w(v({},i),{timestamp:h}));if(!m)throw this.log.info(`audioProcessor: ${r} auth result: ${m}. Message: ${_}`),new x({code:U.INVALID_PARAMETER,message:_});this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",t,r,h,g,A,e),this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",t,r,h,g,A,e)}this.mixNode||(this.mixNode=this.audioContext.createGain(),this.mixNode.gain.value=1),this.silentNode||(this.silentNode=this.audioContext.createConstantSource(),this.silentNode.offset.setValueAtTime(0,this.audioContext.currentTime),this.silentNode.start()),this.localAudioWorkletNode.port.postMessage({type:"enable"}),this.screenAudioWorkletNode.port.postMessage({type:"enable"}),e.audioManager.addAudioProcessor(this.localAudioWorkletNode,this.mixNode,this.silentNode,this.screenAudioWorkletNode),E(n)||n.forEach(h=>{this.customAudioReferenceMap.set(h,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:h,refId:`o-${this.audioRefId++}`})}),E(a)||this.localAudioWorkletNode.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:a}}),E(c)||this.localAudioWorkletNode.port.postMessage({type:"dump",data:{enable:c}})})}update(i){return f(this,null,function*(){if(!this.localAudioWorkletNode||!this.screenAudioWorkletNode)return;let{audioReference:e,enableDump:t,processLevel:r}=i;E(e)||(this.customAudioReferenceMap.forEach((s,n)=>{this.customAudioReferenceMap.delete(n),this.core.room.audioManager.updateAudioReference({type:"remove",refId:s})}),e.forEach(s=>{this.customAudioReferenceMap.set(s,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:s,refId:`o-${this.audioRefId++}`})})),E(r)||this.localAudioWorkletNode.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:r}}),E(t)||(this.localAudioWorkletNode.port.postMessage({type:"dump",data:{enable:t}}),this.screenAudioWorkletNode.port.postMessage({type:"dump",data:{enable:t}}))})}stop(){return f(this,null,function*(){if(!this.localAudioWorkletNode||!this.mixNode||!this.silentNode||!this.screenAudioWorkletNode)return;let{room:i}=this.core;this.localAudioWorkletNode.port.postMessage({type:"disable"}),this.screenAudioWorkletNode.port.postMessage({type:"disable"}),yield i.audioManager.removeAudioProcessor(this.localAudioWorkletNode,this.mixNode,this.silentNode,this.screenAudioWorkletNode)})}destroy(){this.localAudioWorkletNode&&(this.localAudioWorkletNode.port.onmessage=null),this.screenAudioWorkletNode&&(this.screenAudioWorkletNode.port.onmessage=null)}initWorkletNode(i,e,t,r,s,n,a,c){i.port.postMessage({type:"init",data:{sdkAppId:String(t),userId:r,timestamp:s,sign:n,status:a}}),i.port.onmessage=l=>{var h;let{data:u}=l;switch(u.type){case"cost":let m=(u==null?void 0:u.value)>10?"info":"debug";this.log[m](`[${e}] avg cost: ${u.value} max: ${u==null?void 0:u.max}(${no(new Date(u==null?void 0:u.maxCostTimestamp))}) hist: ${(h=u==null?void 0:u.hist)==null?void 0:h.join(" ")}`);return;case"log":this.log[u.logLevel](`[${e}] ${u.value}`);return;case"dump":S.emit("265",{room:c,data:u.value,type:e==="localAudio"?"dump":"dump-screen-audio"});return}}}};d(Ki,"updateValidateRule",{type:"object"}),d(Ki,"stopValidateRule",{type:"object"}),d(Ki,"Name","AudioProcessor");var kc=Ki;function LE(o,i=p.MAIN){return`https://${Ri[i]||bc(o,i)}/api/v1/audioAiAuth`}function PE(r){return f(this,arguments,function*({sdkAppId:o,userId:i,userSig:e,timestamp:t}){let n=`${LE(o)}?sdkAppId=${o}&userId=${i}&userSig=${e}×tamp=${t}`,a=yield fetch(n),{data:{errCode:c,errMsg:l,sign:u,status:h}}=yield a.json();if(h==="1")return{auth:!0,sign:u,status:h,message:l};let m=Oi(o)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",g="Init RTCAudioProcessor failed.",A="";switch(c){case 1:A="Please check your params.";break;case 2:A=`You need to buy packages. Refer to: ${m}`;break;case 3:A="Server is invalid. Please contact our engineer. ";break;case 4:A=`Your packages is not active. Refer to: ${m}`;break;case 5:A=`Your packages is expired. Refer to: ${m}`;break;case 6:A="Your version is not supported.";break}return{auth:!1,status:h,message:l?`${g} Reason: ${l}. ${A}`:`${g}, ${A}`}})}var Oc=0,Hu=class{constructor(i,e){d(this,"player");d(this,"publisher");d(this,"mixInput");this.mixInput=new Wo(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)}}reset(){this.seek(0),this.mixInput.connect()}seek(i){this.player&&(i<0&&i>this.player.duration||(this.player.currentTime=i,this.publisher.currentTime=i))}play(){var i,e;return(i=this.publisher)==null||i.play(),(e=this.player)==null?void 0:e.play()}pause(){var i,e;(i=this.player)==null||i.pause(),(e=this.publisher)==null||e.pause()}stop(){var i;(i=this.player)==null||i.pause(),this.mixInput.disconnect()}setOperation(i){i==="pause"&&this.pause(),i==="resume"&&(this.pause(),this.play()),i==="stop"&&(this.pause(),this.seek(0))}set volume(i){!this.player||!this.publisher||(this.player.volume=i,this.publisher.volume=i)}set loop(i){!this.player||!this.publisher||(this.player.loop=i,this.publisher.loop=i)}set playbackRate(i){!this.player||!this.publisher||(this.player.playbackRate=i,this.publisher.playbackRate=i)}};function ns(o,i){if(i&&typeof i!="function")throw new x({code:U.INVALID_PARAMETER,message:`start audioMixer plugin: param ${o} should be a function.`})}var yi=class yi{constructor(i){this.core=i;d(this,"log");d(this,"mixedMusicMap",new Map);d(this,"cacheMusicMap",new Map);Oc=Oc+1,this.log=i.log.createChild({id:`${this.getAlias()}${Oc}`}),this.log.info(`created id=${this.getAlias()}${Oc}`)}getName(){return yi.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return yi.startValidateRule;case"update":return yi.updateValidateRule;case"stop":return yi.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e}=this.core;this.log.info(`add music source, id: ${i.id} url: ${i.url}, track: ${i.track}`);let{id:t,url:r}=i;if(this.mixedMusicMap.has(t))return;let s=this.cacheMusicMap.get(t);s?i.url?s.reset():(s.mixInput.replaceSource(i.track),s.mixInput.connect()):(s=new Hu(i,e.audioManager),this.cacheMusicMap.set(t,s)),s.updateListener(i),s.updateSettings(i),yield s.play(),this.mixedMusicMap.set(t,s),s.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"add",audioReference:s.mixInput.source.node,refId:`ax-${t}`}),this.log.info(`start mix audio track ${t} success.`),b.addEnum({key:502700,value:3}),this.kvUpload(i)})}update(i){return f(this,null,function*(){let{id:e,operation:t,seekFrom:r,playbackRate:s}=i;this.log.info(`update music source, ${JSON.stringify(i)}`);let n=this.mixedMusicMap.get(e);if(!n){this.log.warn(`update music source failed, music id: ${e} not found.`);return}n.updateSettings(i),n.updateListener(i),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:s,operation:n,seekFrom:a,onTimeUpdate:c,onDurationChange:l,onEnded:u}=i;e&&b.addCount({key:502711}),t&&b.addCount({key:502703}),r&&b.addCount({key:502704}),s&&b.addCount({key:502705}),n&&b.addCount({key:502706}),a&&b.addCount({key:502707}),typeof c!="function"&&b.addCount({key:502709}),typeof u!="function"&&b.addCount({key:502710}),typeof l!="function"&&b.addCount({key:502708})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((i,e)=>{i!=null&&i.mixInput.track&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:i.mixInput.track,refId:e}),this.stop({id:e})})}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}};d(yi,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(i,e,t){if(i.url&&i.url!=="*"){let r=i.url.split("?")[0],s=["mp3","ogg","wav","flac"],n=r.split(".").pop(),a=s.indexOf(n)>=0,c=r.startsWith("blob"),l=r.startsWith("data");if(!(a||c||l))throw new x({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 x({code:U.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});ns("onTimeUpdate",i.onTimeUpdate),ns("onEnded",i.onEnded),ns("onDurationChange",i.onDurationChange)}}),d(yi,"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){ns("onTimeUpdate",i.onTimeUpdate),ns("onEnded",i.onEnded),ns("onDurationChange",i.onDurationChange)}}),d(yi,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),d(yi,"Name","AudioMixer");var wc=yi;var xc=0,$u,er=class er{constructor(i){this.core=i;d(this,"log");d(this,"audioContext",Ee("denoiser"));d(this,"workletNode");xc=xc+1,this.log=i.log.createChild({id:`${this.getAlias()}${xc}`}),this.log.info(`created id=${this.getAlias()}${xc}`)}static startValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,t,r,s){if(!i.room.audioManager.hasAudioTrack)throw new x({code:U.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return $u||($u=this.doPreload(i)),$u}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield ji(this.audioContext,t)}catch(r){throw this.log.error("load worklet failed",r),r}finally{URL.revokeObjectURL(t)}})}getName(){return er.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(i){switch(i){case"start":return er.startValidateRule(this.core);case"update":return er.updateValidateRule;case"stop":return er.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 x({code:U.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(yield this.preload(`${r}/denoiser-wasm.js`),!this.workletNode){let s=String(Date.now()).slice(0,-3),{auth:n,sign:a,status:c,message:l}=yield VE(t,w(v({},i),{timestamp:s}));if(!n)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${n}. Message: ${l}`),new x({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:s,sign:a,status:c}}),this.workletNode.port.onmessage=u=>{var m;let{data:h}=u;if(h.type==="cost"){let g=(h==null?void 0:h.max)>20?"warn":(h==null?void 0:h.max)>10?"info":"debug";this.log[g](`avg cost: ${h.value} max: ${h==null?void 0:h.max}(${no(new Date(h==null?void 0:h.maxCostTimestamp))}) hist: ${(m=h==null?void 0:h.hist)==null?void 0:m.join(" ")}`)}else h.type==="log"&&this.log[h.logLevel](`${h.value}`)}}this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(){return f(this,null,function*(){})}stop(){return f(this,null,function*(){if(!this.workletNode)return;let{room:i}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield i.audioManager.removeDenoiser(this.workletNode)})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};d(er,"updateValidateRule",{type:"object"}),d(er,"stopValidateRule",{type:"object"}),d(er,"Name","AIDenoiser");var Lc=er;function VE(s,n){return f(this,arguments,function*(o,{sdkAppId:i,userId:e,userSig:t,timestamp:r}){try{let{data:{errCode:a,errMsg:c,sign:l,status:u}}=yield o.getAbilityConfig(i,o.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:i,userId:e,userSig:t,timestamp:r});if(u==="1")return{auth:!0,sign:l,status:u,message:c};let h=Oi(i)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",m="Init RTCAIDenoiser failed.",g="";switch(a){case 1:g="Please check your params.";break;case 2:g=`You need to buy packages. Refer to: ${h}`;break;case 3:g="Server is invalid. Please contact our engineer. ";break;case 4:g=`Your packages is not active. Refer to: ${h}`;break;case 5:g=`Your packages is expired. Refer to: ${h}`;break;case 6:g="Your version is not supported.";break}return{auth:!1,status:u,message:c?`${m} Reason: ${c}. ${g}`:`${m}, ${g}`}}catch(a){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${a}`}}})}var Wp=Ge(tt(),1);var Gu=class extends Wp.EventEmitter{constructor(){super();d(this,"observer");d(this,"state","nominal");this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return f(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!pe&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){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)&&y.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})}}},BE=new Gu,Wu=BE;function Ju([o,i]){let e=i.byteLength,t=parseInt(String(e/255),10),r=e%255,s=[];s.push(0,0,0,1,6,o);for(let a=0;a<t;a++)s.push(255);s.push(r);let n=new DataView(i);return s.push(...new Uint8Array(n.buffer)),s.push(128),new zi(new DataView(new Uint8Array(s).buffer),!0)}function qu(o){return o.type==="empty"||o.data.byteLength===0}function ju(o){return o.getInt32(0)===1&&o.getInt8(4)===6}function Xu(o){let i=0,e=0,t=new DataView(o);for(let r=0;r<o.byteLength;r++)switch(t.getUint8(r)){case 0:i++;break;case 1:(i===2||i===3)&&e++,i=0;break;default:i=0;break}return e}function zu({frame:o,seiMessageList:i}){if(!i||i.length===0||o.data.byteLength===0)return o;let t=9-Xu(o.data);if(t<=0)return o;let r=i.splice(0,t).reverse().map(Ju),s=r.reduce((u,h)=>u+h.dataView.byteLength,0),n=new ArrayBuffer(s+o.data.byteLength),a=new DataView(n),c=new DataView(o.data),l=0;for(let u=0;u<r.length;u++)for(let h=0;h<r[u].dataView.byteLength;h++)a.setInt8(l++,r[u].dataView.getInt8(h));for(let u=0;u<o.data.byteLength;u++)a.setInt8(l++,c.getInt8(u));return o.data=n,o}function Qu({frame:o,onSEI:i}){try{let e=new DataView(o.data);if(qu(o)||!ju(e))return o;let t=[],r=0,s=-1,n=-1;for(let a=0;a<o.data.byteLength;a++){let c=e.getUint8(a);if(c===0)r++;else if(c===1){if(r===2||r===3){let l=a-r;if(s===-1?s=l:n===-1&&(n=l,t.push(new zi(new DataView(e.buffer.slice(s,n)))),s=l,n=-1),!(e.getUint8(a+1)===6)){o.data=e.buffer.slice(l);break}}r=0}else r=0}i==null||i(t.reverse())}catch(e){}return o}var Yu=0,An=class An{constructor(i){this.core=i;d(this,"log");d(this,"_seiMessageList",[]);d(this,"_smallSeiMessageList",[]);d(this,"_subStreamSeiMessageList",[]);Yu++,this.log=i.log.createChild({id:`${this.getAlias()}${Yu}`}),this.log.info(`[sei] created id=${this.getAlias()}${Yu}`),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 zu({frame:i,seiMessageList:t})}catch(t){this.log.warn(t)}return i}decode({frame:i,track:e}){return Qu({frame:i,onSEI:t=>{t.forEach(r=>{this.core.trtc.emit(O.SEI_MESSAGE,{seiPayloadType:r.seiPayloadType,data:r.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"})})}})}destroy(){this.log.debug("destory"),this.stop(),delete this.core}getValidateRule(i){switch(i){case"start":return{type:"object"};case"update":return{type:"object"};case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:Ji?this.encode:zu,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:Ji?this.decode:Qu,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update({buffer:i,options:e}){var s;let t=[e.seiPayloadType,i],r=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(t):(this._seiMessageList.push(t),r&&this._smallSeiMessageList.push(t)),(s=this.core.room.scriptTransformWorker)==null||s.postMessage({type:"sei",data:t,isMain:!e.toSubStream,small:r})}getName(){return An.Name}getAlias(){return"sei"}getGroup(){return"sei"}};d(An,"autoStart",!0),d(An,"Name","SEI");var Pc=An;function Zu({frame:o,onDump:i}){return i==null||i(),o}function Ku({frame:o,onDump:i}){return i==null||i(),o}var Jp={"play() error: NotAllowedError:":{tips:o=>o.includes("main <video>")||o.includes("main <audio>")?"Remote stream auto play is restricted and playback fails":"Local stream playback failure, generally only occurs in Android WeChat devices, no need to handle",color:"red",class:"red"},"updateStream() try to recover local stream":{tips:"Device acquisition exception, automatic recovery is in progress"},"updateStream() recover local stream successfully":{tips:"Device acquisition exception, automatic recovery is successful"},"updateStream() failed to recover local stream":{tips:"Device acquisition exception, automatic recovery failed"},"main stream - video track is muted":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is muted":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is muted":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unable to provide media output":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is unable to provide media output":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is unable to provide media output":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unmuted":{tips:"Received enough playback video data"},"main stream - audio track is unmuted":{tips:"Received enough playback audio data"},"auxiliary stream - video track is unmuted":{tips:"Received enough playback screen sharing data"},"main stream - audio player track is ended":{tips:"Remote audio track stopped"},"main stream - video player track is ended":{tips:"Remote video track stopped"},"auxiliary stream - video player track is ended":{tips:"Received enough playback screen sharing data"},"stream - video track is muted":{tips:"Camera capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"stream - video track is unable to provide media output":{tips:"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked, and the customer needs to re-acquire. SDK v4.11.4+ will automatically resume acquisition without customer intervention",color:"orange"},"video track is unable to provide media output":{tips:o=>o.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"stream - audio track is muted":{tips:"Microphone capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"audio track is unable to provide media output":{tips:o=>o.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"Microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio track is unable to provide media output":{tips:"The microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"is adding audio track to current published local stream":{tips:"add audio track",color:"orange"},"is removing audio track from current published local stream":{tips:"remove audio track",color:"orange"},"is removing video track from current published local stream":{tips:"remove video track",color:"orange"},"is adding video track to current published local stream":{tips:"add video track",color:"orange"},"is replacing audio track to current published local main stream":{tips:"replace audio track",color:"orange"},"is replacing video track to current published local main stream":{tips:"replace video track",color:"orange"},"downlink network quality change":{tips:"Downstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"uplink network quality change":{tips:"Upstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"localStream mute video":{tips:"mute upstream video stream",color:"orange"},"localStream unmute video":{tips:"unmute upstream video stream",color:"orange"},"localStream mute audio":{tips:"mute upstream audio stream",color:"orange"},"localStream unmute audio":{tips:"unmute upstream audio stream",color:"orange"},"black detected":{tips:"Detect black screen, which means fps = 0. It is usually caused by network, and the network will be recovered after a while. If the network is normal but has not been restored, it is an abnormal situation."},'main stream start to play with options: {"muted":true}':{tips:"Play the remote stream in silent mode. Generally, the remote stream does not need to be played in silent mode. You need to confirm whether the parameters passed in the client stream.play API call are correct.",color:"orange"},"main stream - audio player is starting playing":{tips:"Remote stream audio playback success",color:"#0dd90d",class:"success"},"main stream - video player is starting playing":{tips:"Remote stream video playback success",color:"#0dd90d",class:"success"},"video player is playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"audio player is playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"stream - video player is starting playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"stream - audio player is starting playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"switch camera success":{tips:"Switch camera success",color:"#0dd90d",class:"success"},"switch microphone success":{tips:"Switch microphone success",color:"#0dd90d",class:"success"},gotStream:{tips:"Local stream capture success"},"local stream is published successfully":{tips:"Publish success",color:"#0dd90d",class:"success"},"encoderImplementation change to OpenH264":{tips:"Use software encoding"},"encoderImplementation change to ExternalEncoder":{tips:"Use hardware encoding"},"getUserMedia with constraints":{tips:"Start media (camera/microphone) capture"},"getDisplayMedia with constraints":{tips:"Start screen sharing capture"},"client-banned":{tips:"Kicked out of the room",color:"red",class:"red",textColor:"#fff"},user_timeout:{tips:"The backend is too long without receiving SDK heartbeat, which is usually caused by the JS thread being blocked for a long time. If the reproduction probability is high, the application browser Performance tool analyzes where the JS thread is blocked.",color:"red",class:"red",textColor:"#fff"},"schedule failed":{tips:"Signaling request failed, does not affect the normal room entry process, SDK will connect to the default signaling domain."},"updateStream() video flag is true, but no camera detected, set video to false":{tips:"When trying to resume camera acquisition, the camera acquisition is not resumed because it is detected that there is no camera.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to bandwidth":{tips:"bandwidth estimation is not enough to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to cpu":{tips:"cpu load is too high to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: hidden":{tips:"User page switched to backend, in mobile devices, this will cause the device to pause the capture, and it will be restored when the user switches backend to the frontend.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: visible":{tips:"User page switched to frontend",color:"orange",class:"orange",textColor:"#fff"},"main stream - audio player is paused":{tips:`The remote stream audio playback is paused, which usually has two possibilities:
|
|
59
59
|
1. The business side passes in the div tag container for playing audio and video to be removed by the business side from the DOM.
|
|
60
60
|
2. If the user is in Chrome 70 and below, when the div container is moved, the playback will be paused.`,color:"orange",class:"orange",textColor:"#fff"},"main stream - video player is paused":{tips:`The remote stream video playback is paused, which usually has two possibilities:
|
|
61
61
|
1. The business side passes in the div tag container for playing audio and video to be removed by the business side from the DOM.
|
|
@@ -83,7 +83,7 @@ in vec2 v_texCoord;
|
|
|
83
83
|
out vec4 outColor;
|
|
84
84
|
void main() {
|
|
85
85
|
outColor = vec4(texture(u_texture, v_texCoord).rgb, texture(mask, v_texCoord).a);
|
|
86
|
-
}`,jc=class extends Dt{constructor(e,t){super(e,t.input,{name:"vb",create2d:!1,useDefaultProgram:!1,useFbo:!1,createTexture:!0,width:t.width,height:t.height,logger:e.log});d(this,"_bgTexture");d(this,"_waterMarkTexture");d(this,"_lastMaskTexture");d(this,"_lastMaskFbo");d(this,"_textureValid",!1);d(this,"_selfieTextureValid",!1);d(this,"_selfieSegmentationHash");d(this,"wasm");d(this,"_prePrograme");d(this,"_segmentationMask");d(this,"_weixin",!1);d(this,"_centerFace");d(this,"_textureMatrixLocation");d(this,"_offsetMatrixLocation");d(this,"_enableFaceCentering",!1);d(this,"_mat4");d(this,"_onAbort");d(this,"_visionTaskRegistry");this.init(t).catch(r=>{e.log.error(r),e.destroy(new N({code:I.VIDEO_MANAGER_ERROR,extraCode:6,message:`init vb node error ${r.message||r}`}))})}init(e){return f(this,null,function*(){var n;let t=e.Wasm,r=this.context.ctx;if(e.mat4&&(this._mat4=e.mat4),this._enableFaceCentering=(n=e.enableFaceCentering)!=null?n:!1,this.wasm=new t.AllIn1(r),this.wasm.blurRadius=e.blurRadius||3,this.wasm.mirror=!!e.mirror,this.wasm.rotation=e.rotation||0,this.wasm.vbMode=e.bg==="blur"?1:e.bg instanceof HTMLImageElement?2:e.bg==="green"?3:0,this._onAbort=e.onAbort,e.waterMark){let{x:a,y:c,width:l,height:u}=e.waterMark;this.wasm.setWaterMark(a,c,l,u)}if(e.beautyParams){let{beauty:a,brightness:c,ruddy:l}=e.beautyParams;this.wasm.setBeauty(a,c,l,e==null?void 0:e.width,e==null?void 0:e.height)}this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),r.uniform1i(r.getUniformLocation(this.program,"mask"),1),e.bg instanceof HTMLImageElement&&(r.uniform1i(r.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(e.bg)),e.waterMark&&(r.uniform1i(r.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(e.waterMark.image));let s=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);if(this._textureMatrixLocation=r.getUniformLocation(this.program,"u_textureMatrix"),r.uniformMatrix4fv(this._textureMatrixLocation,!1,s),this._offsetMatrixLocation=r.getUniformLocation(this.program,"u_offsetMatrix"),r.uniformMatrix4fv(this._offsetMatrixLocation,!1,s),r.uniform1i(r.getUniformLocation(this.program,"lastMask"),4),this._weixin){let a=this.context.createShader(r.FRAGMENT_SHADER,sS),c=this.context.createShader(r.VERTEX_SHADER,oS);this._prePrograme=this.context.createProgram(c,a),r.useProgram(this._prePrograme),this.setAttributes(this.positionBuffer,this.texCoordBuffer),r.uniform1i(r.getUniformLocation(this._prePrograme,"mask"),1)}yield this.initVisionTasks(e)})}initVisionTasks(e){return f(this,null,function*(){if(e.bg){if(this._visionTaskRegistry=yield window.VisionTaskRegistry.getInstance(),!window.VisionTaskRegistry||!this._visionTaskRegistry||!this._visionTaskRegistry.visionWasm)throw new Error("Virtual background assets not found. Please redeploy the assets of the npm package.");if(this._visionTaskRegistry.video=this.image,this._selfieSegmentationHash=yield this._visionTaskRegistry.register(window.VisionTaskType.ImageSegmenter,{canvas:this.context._canvas}),!this._selfieSegmentationHash)throw new Error("Virtual background model not found. Please redeploy the assets of the npm package.");if(this._enableFaceCentering){this._visionTaskRegistry.models.has(window.VisionTaskType.FaceDetector)||(yield this._visionTaskRegistry.preloadModels([window.VisionTaskType.FaceDetector]));let t=yield this._visionTaskRegistry.register(window.VisionTaskType.FaceDetector);if(!t)return;this._centerFace=new qc(this.wasm.vbMode,t,this._visionTaskRegistry,this.context.log)}}})}onPredict(e){let t=this.context.ctx;this._weixin&&(this._lastMaskTexture||(this._lastMaskTexture=this.createTexture(this.image),this._lastMaskFbo=this.createFramebuffer(this._lastMaskTexture))),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),this.useTexture(),this.bindMaskTexture(e),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),this.useBufferFrame(),this._segmentationMask=e,this.totalFrames++,this.centerFace(),t.drawArrays(t.TRIANGLE_STRIP,0,4)}bindMaskTexture(e){let t=this.context.ctx;if(!e.confidenceMasks)return;let r=e.confidenceMasks[0].getAsWebGLTexture();t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,r),e.close()}onFirstFrame(){this.waitingFirstFrame=!1;let e=this.context.ctx;this.useTexture(),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,this.image)}render(e){let t=this.context.ctx,{image:r}=this;this.tryVideoFrameCallback();let{videoWidth:s,videoHeight:n}=r;if(
|
|
86
|
+
}`,jc=class extends Dt{constructor(e,t){super(e,t.input,{name:"vb",create2d:!1,useDefaultProgram:!1,useFbo:!1,createTexture:!0,width:t.width,height:t.height,logger:e.log});d(this,"_bgTexture");d(this,"_waterMarkTexture");d(this,"_lastMaskTexture");d(this,"_lastMaskFbo");d(this,"_textureValid",!1);d(this,"_selfieTextureValid",!1);d(this,"_selfieSegmentationHash");d(this,"wasm");d(this,"_prePrograme");d(this,"_segmentationMask");d(this,"_weixin",!1);d(this,"_centerFace");d(this,"_textureMatrixLocation");d(this,"_offsetMatrixLocation");d(this,"_enableFaceCentering",!1);d(this,"_mat4");d(this,"_onAbort");d(this,"_visionTaskRegistry");this.init(t).catch(r=>{e.log.error(r),e.destroy(new N({code:I.VIDEO_MANAGER_ERROR,extraCode:6,message:`init vb node error ${r.message||r}`}))})}init(e){return f(this,null,function*(){var n;let t=e.Wasm,r=this.context.ctx;if(e.mat4&&(this._mat4=e.mat4),this._enableFaceCentering=(n=e.enableFaceCentering)!=null?n:!1,this.wasm=new t.AllIn1(r),this.wasm.blurRadius=e.blurRadius||3,this.wasm.mirror=!!e.mirror,this.wasm.rotation=e.rotation||0,this.wasm.vbMode=e.bg==="blur"?1:e.bg instanceof HTMLImageElement?2:e.bg==="green"?3:0,this._onAbort=e.onAbort,e.waterMark){let{x:a,y:c,width:l,height:u}=e.waterMark;this.wasm.setWaterMark(a,c,l,u)}if(e.beautyParams){let{beauty:a,brightness:c,ruddy:l}=e.beautyParams;this.wasm.setBeauty(a,c,l,e==null?void 0:e.width,e==null?void 0:e.height)}this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),r.uniform1i(r.getUniformLocation(this.program,"mask"),1),e.bg instanceof HTMLImageElement&&(r.uniform1i(r.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(e.bg)),e.waterMark&&(r.uniform1i(r.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(e.waterMark.image));let s=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);if(this._textureMatrixLocation=r.getUniformLocation(this.program,"u_textureMatrix"),r.uniformMatrix4fv(this._textureMatrixLocation,!1,s),this._offsetMatrixLocation=r.getUniformLocation(this.program,"u_offsetMatrix"),r.uniformMatrix4fv(this._offsetMatrixLocation,!1,s),r.uniform1i(r.getUniformLocation(this.program,"lastMask"),4),this._weixin){let a=this.context.createShader(r.FRAGMENT_SHADER,sS),c=this.context.createShader(r.VERTEX_SHADER,oS);this._prePrograme=this.context.createProgram(c,a),r.useProgram(this._prePrograme),this.setAttributes(this.positionBuffer,this.texCoordBuffer),r.uniform1i(r.getUniformLocation(this._prePrograme,"mask"),1)}yield this.initVisionTasks(e)})}initVisionTasks(e){return f(this,null,function*(){if(e.bg){if(this._visionTaskRegistry=yield window.VisionTaskRegistry.getInstance(),!window.VisionTaskRegistry||!this._visionTaskRegistry||!this._visionTaskRegistry.visionWasm)throw new Error("Virtual background assets not found. Please redeploy the assets of the npm package.");if(this._visionTaskRegistry.video=this.image,this._selfieSegmentationHash=yield this._visionTaskRegistry.register(window.VisionTaskType.ImageSegmenter,{canvas:this.context._canvas}),!this._selfieSegmentationHash)throw new Error("Virtual background model not found. Please redeploy the assets of the npm package.");if(this._enableFaceCentering){this._visionTaskRegistry.models.has(window.VisionTaskType.FaceDetector)||(yield this._visionTaskRegistry.preloadModels([window.VisionTaskType.FaceDetector]));let t=yield this._visionTaskRegistry.register(window.VisionTaskType.FaceDetector);if(!t)return;this._centerFace=new qc(this.wasm.vbMode,t,this._visionTaskRegistry,this.context.log)}}})}onPredict(e){let t=this.context.ctx;this._weixin&&(this._lastMaskTexture||(this._lastMaskTexture=this.createTexture(this.image),this._lastMaskFbo=this.createFramebuffer(this._lastMaskTexture))),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),this.useTexture(),this.bindMaskTexture(e),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),this.useBufferFrame(),this._segmentationMask=e,this.totalFrames++,this.centerFace(),dt(this.wasm.rotation)&&this.resize(this.image.height,this.image.width),t.drawArrays(t.TRIANGLE_STRIP,0,4)}bindMaskTexture(e){let t=this.context.ctx;if(!e.confidenceMasks)return;let r=e.confidenceMasks[0].getAsWebGLTexture();t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,r),e.close()}onFirstFrame(){this.waitingFirstFrame=!1;let e=this.context.ctx;this.useTexture(),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,this.image)}render(e){let t=this.context.ctx,{image:r}=this;this.tryVideoFrameCallback();let{videoWidth:s,videoHeight:n}=r;if(s===0||n===0||!this.available)return!1;r.width=s,r.height=n;let a=!1;if(this.totalFrames)this.useTexture(),a=this._selfieTextureValid,this._selfieTextureValid=!0;else{if(this.program)this.useTexture();else return!1;a=this._textureValid,this._textureValid=!0}this.width!==s||this.height!==n||!a?(this.resize(s,n),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,r)):t.texSubImage2D(t.TEXTURE_2D,0,0,0,t.RGBA,t.UNSIGNED_BYTE,r),this._weixin&&(t.useProgram(this._prePrograme),this.useTexture(),this._segmentationMask&&(this.bindMaskTexture(this._segmentationMask),t.bindFramebuffer(t.FRAMEBUFFER,this._lastMaskFbo||null)),t.drawArrays(t.TRIANGLE_STRIP,0,4),this.useTexture(),this._segmentationMask?t.copyTexSubImage2D(t.TEXTURE_2D,0,0,0,0,0,s,n):t.copyTexImage2D(t.TEXTURE_2D,0,t.RGBA,0,0,s,n,0));try{if(this._selfieSegmentationHash&&this._visionTaskRegistry){let c=this._visionTaskRegistry.getResult(this._selfieSegmentationHash);this.onPredict(c)}}catch(c){this._onAbort&&this._onAbort(c)}return this.totalFrames||(t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),t.drawArrays(t.TRIANGLE_STRIP,0,4)),this._visionTaskRegistry&&this._visionTaskRegistry.resetHashResults(),!1}centerFace(){if(!this._centerFace||!this._enableFaceCentering)return;let e=this.context.ctx;this._centerFace.aspectRatio=e.canvas.width/e.canvas.height,this._centerFace.actionCentering(this.image);let{current:t,offset:r}=this._centerFace;if(t&&(this.wasm.vbMode===1&&this.drawImage(t.sx,t.sy,t.cropWidth,t.cropHeight),r&&this.wasm.vbMode===2)){if(!this._mat4)return;let s=this._mat4.create(),{scaleRatio:n=1,scaleOffsetX:a=0,scaleOffsetY:c=0}=t;this._mat4.fromTranslation(s,[-r.offsetX/e.canvas.width+a,c,0]),this._mat4.scale(s,s,[n,n,1]),e.uniformMatrix4fv(this._offsetMatrixLocation,!1,s)}}drawImage(e,t,r,s){let n=this.context.ctx;if(!this._mat4)return;let{width:a,height:c}=n.canvas,l=this._mat4.create();this._mat4.fromTranslation(l,[e/a,1-(t+s)/c,0]),this._mat4.scale(l,l,[r/a,s/c,1]),n.uniformMatrix4fv(this._textureMatrixLocation,!1,l)}close(){var t;super.close();let e=this.context.ctx;this._bgTexture&&e.deleteTexture(this._bgTexture),this._waterMarkTexture&&e.deleteTexture(this._waterMarkTexture),this._lastMaskTexture&&e.deleteTexture(this._lastMaskTexture),this._lastMaskFbo&&e.deleteFramebuffer(this._lastMaskFbo),this._prePrograme&&e.deleteProgram(this._prePrograme),(t=this.wasm)==null||t.close()}};var Xc=class extends Ye{constructor(e){super(e,{name:"yuv-source",useDefaultProgram:!1,create2d:!1,useFbo:!1,createTexture:!1,logger:e.log,fragmentShaderSource:`
|
|
87
87
|
precision highp float;
|
|
88
88
|
uniform sampler2D ySampler;
|
|
89
89
|
uniform sampler2D uSampler;
|