trtc-sdk-v5 5.10.2-beta.16 → 5.10.2-beta.17
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/package.json +1 -1
- package/plugins/video-effect/beauty/package.json +1 -1
- package/plugins/video-effect/virtual-background/package.json +1 -1
- package/plugins/video-effect/watermark/package.json +1 -1
- package/plugins/voice-changer/package.json +1 -1
- package/trtc.esm.js +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 Ls=class extends ge{constructor(e){super();c(this,"frameRate");c(this,"_canvas");c(this,"log");c(this,"hasAlpha",!1);c(this,"name");c(this,"error");this.name=e.name,this.log=e.logger.createChild({id:`vc-${this.name}`}),this.frameRate=e.frameRate}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 kr(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new vo(this,e)}createVideoImageSource(e,t){return new Kn(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new ea(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}};c(Ls,"_ids",0);var YT={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},No=class No extends Ls{constructor(){super(...arguments);c(this,"defaultProgam");c(this,"defaultVShader");c(this,"defaultFShader");c(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${Ls._ids++}`),this.ctx=this._canvas.getContext("webgl2",YT),!this.ctx)throw new X({code:H.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,XT),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,QT),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new X({code:H.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})}destroy(e){let t="";return e&&(t=e.message,this.error=e,Q.addFailedEvent({key:512702,error:e})),this.disconnect(),this.log.info(`video context destroy${t}`?`: ${t}`:""),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),e}set width(e){var t;(t=this.ctx)==null||t.viewport(0,0,e,this.height),super.width=e}set height(e){var t;(t=this.ctx)==null||t.viewport(0,0,this.width,e),super.height=e}setSize(e,t){var r;(r=this.ctx)==null||r.viewport(0,0,e,t),super.setSize(e,t)}createShader(e,t){let r=this.ctx,o=r.createShader(e);return r.shaderSource(o,t),r.compileShader(o),o}createProgram(e,t){let r=this.ctx,o=r.createProgram();return r.attachShader(o,e),r.attachShader(o,t),r.linkProgram(o),r.getProgramParameter(o,r.LINK_STATUS)||this.log.error(r.getProgramInfoLog(o)),o}};c(No,"UNAVAILABLE","unavailable"),J([qe(ge.INIT,"created",{sync:!0,fail(e){this.log.error("video gl context create failed",e.cause),Q.addFailedEvent({key:512700,error:e.cause||e})},success(){this.log.info("video context created use webgl"),Q.addSuccessEvent({key:512700})}})],No.prototype,"create",1),J([qe("created",ge.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(No.UNAVAILABLE,e),this.removeAllListeners()}})],No.prototype,"destroy",1);var mt=No,Dt=class extends Ls{constructor(){super(...arguments);c(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${Ls._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new X({code:H.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,Q.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(),Q.addSuccessEvent({key:512703})}};J([qe(ge.INIT,"created",{sync:!0,fail(e){this.log.error("video 2d context create failed",e.cause),Q.addFailedEvent({key:512701,error:e.cause||e})},success(){this.log.info("video context created use 2d"),Q.addSuccessEvent({key:512701})}})],Dt.prototype,"create",1),J([qe("created",ge.INIT,{ignoreError:!0,sync:!0})],Dt.prototype,"destroy",1);function ZT(s){return[15,30,45,60].reduce((e,t)=>Math.abs(t-s)<Math.abs(e-s)?t:e)}var er=class extends bo{constructor(e,t,r=4){super(e,t,r);c(this,"mediaType",4);c(this,"source");c(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.videoManager,this.once("first-video-frame",o=>{this.room.emit("first-video-frame",o)})}play(e,t){return(Qe(t==null?void 0:t.canvasRender)?t.canvasRender:Xt===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 Dt({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});let t=new xs(e,{name:"remotePlayer",logger:this.log});this.source=e.createVideoPlayerSource(this.player),this.source.connect(t),this.player.setCanvas(e._canvas),ys()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let t=this.decodeFPS,r=ZT(t);if(!De(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)}},Do=class extends er{constructor(e,t){super(e,t,2);c(this,"mediaType",2);c(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}};var ko=new Map;x.on(B.JOIN_SUCCESS,({room:s})=>{Ze(s.userId,{eventId:32788})});x.on(B.LEAVE_START,({room:s})=>{Ze(s.userId,{eventId:32789})});x.on(B.LOCAL_TRACK_PUBLISHED,({track:s})=>{if(s.room){let i=32769;s.mediaType===4?i=32768:s.mediaType===2&&(i=32805),Ze(s.room.userId,{eventId:i})}});x.on(B.LOCAL_TRACK_UNPUBLISHED,({track:s})=>{if(s.room){let i=32771;s.mediaType===4?i=32770:s.mediaType===2&&(i=32806),Ze(s.room.userId,{eventId:i})}});x.on(B.TRACK_MUTED,({track:s})=>{s.room&&(s.kind===S.AUDIO?Ze(s.room.userId,{eventId:s.isRemote?32785:32772,remoteUserId:s.isRemote?s.userId:void 0}):Ze(s.room.userId,{eventId:s.isRemote?32784:32773,remoteUserId:s.isRemote?s.userId:void 0}))});x.on(B.TRACK_UNMUTED,({track:s})=>{s.room&&(s.kind===S.AUDIO?Ze(s.room.userId,{eventId:s.isRemote?32787:32774,remoteUserId:s.isRemote?s.userId:void 0}):Ze(s.room.userId,{eventId:s.isRemote?32786:32775,remoteUserId:s.isRemote?s.userId:void 0}))});x.on(B.REMOTE_TRACK_SUBSCRIBED,({track:s})=>{s.room&&(s.mediaType===1&&Ze(s.room.userId,{eventId:32777,remoteUserId:s.userId}),s.mediaType===4&&Ze(s.room.userId,{eventId:32776,remoteUserId:s.userId}),s.mediaType===8&&Ze(s.room.userId,{eventId:32803,remoteUserId:s.userId}))});x.on(B.REMOTE_TRACK_UNSUBSCRIBED,({track:s})=>{s.room&&(s.mediaType===1&&Ze(s.room.userId,{eventId:32779,remoteUserId:s.userId}),s.mediaType===4&&Ze(s.room.userId,{eventId:32778,remoteUserId:s.userId}),s.mediaType===8&&Ze(s.room.userId,{eventId:32804,remoteUserId:s.userId}))});x.on(B.SWITCH_DEVICE_SUCCESS,({track:s})=>{s.room&&Ze(s.room.userId,{eventId:s.kind===S.VIDEO?32780:32781})});x.on(B.LOCAL_TRACK_REPLACED,({track:s})=>{s.room&&Ze(s.room.userId,{eventId:s.kind===S.VIDEO?32782:32783})});x.on(B.SIGNAL_CONNECTION_STATE_CHANGED,({room:s,prevState:i,state:e})=>{let t;switch(e){case"CONNECTED":i==="RECONNECTING"?t=32795:t=32791;break;case"DISCONNECTED":i==="RECONNECTING"?t=32796:t=32790;break;case"RECONNECTING":t=32794;break}t&&Ze(s.userId,{eventId:t})});x.on(B.PEER_CONNECTION_STATE_CHANGED,({room:s,prevState:i,state:e,remoteUserId:t})=>{let r=!!t,o;switch(e){case"CONNECTED":i==="RECONNECTING"?o=r?32801:32798:o=r?32793:32792;break;case"DISCONNECTED":i==="RECONNECTING"&&(o=r?32802:32799);break;case"RECONNECTING":o=r?32800:32797;break}o&&Ze(s.userId,{eventId:o,remoteUserId:t})});x.on(B.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({implementation:s,userId:i,remoteUserId:e,codec:t,isHWCodec:r,prevImplementation:o,streamType:n})=>{let a=r?1:0;o||(a=r?3:2);let d=t==="h264"?0:2,l={eventId:4004,param1:a,param2:d,streamType:n||2};e&&(l.remoteUserId=e,l.eventId=4005),Ze(i,l),Q.addEnum({key:e?514701:513701,value:a}),Q.addEnum({key:e?514700:513700,value:d})});x.on(B.LOCAL_TRACK_RECAPTURE,({track:s,error:i})=>{if(s.userId){let e={eventId:2003,param1:0};s.kind===S.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType=s.streamType==="auxiliary"?7:2,i&&(e.param1=8)),Ze(s.userId,e)}});function Ze(s,i){let e=de(Z({},i),{timestamp:Zo()});ko.has(s)?ko.get(s).push(e):ko.set(s,[e])}function rf(s){if(ko.has(s)){let i=ko.get(s).map(e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,uint32_param1:e.param1,uint32_param2:e.param2,uint32_video_stream_type:e.streamType}));return ko.delete(s),i}return[]}var sf=gt(Mt(),1);var rc=class extends sf.EventEmitter{constructor(e,t,r="userId"){super();this.mySelfId=e;this._log=t;this.key=r;c(this,"userMap",new Map);c(this,"remotePublishedUserMap",new Map)}get hasRobotUser(){return!![...this.remotePublishedUserMap.values()].find(e=>e.isRobot)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:r,tinyId:o,role:n}=e;if(this.userMap.has(t))return;let a={userId:r,tinyId:o,role:n===20?"anchor":"audience"};this.userMap.set(t,a),this.emit("1",a)}deleteUser(e,t){let r=this.userMap.get(e);if(!r)return;let o=`peer leave [${e}]`;M(t)||(o+=`:${cl[t]}`),this._log.info(o);let n=this.remotePublishedUserMap.get(e);if(n){let a=n.muteState;n.flag=0,this.emit("5",n.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:a,muteState:n.muteState,flag:0})}this.userMap.delete(e),this.emit("2",r.userId)}setUserList(e){this.userMap.forEach(t=>{e.findIndex(r=>r[this.key]===t[this.key])<0&&this.deleteUser(t[this.key],0)}),e.forEach(t=>{!this.userMap.has(t[this.key])&&t[this.key]!==this.mySelfId&&this.addUser(t)})}addRemotePublishedUser(e){this.remotePublishedUserMap.has(e[this.key])||this.remotePublishedUserMap.set(e[this.key],e)}deleteRemotePublishedUser(e){this.remotePublishedUserMap.has(e)&&this.remotePublishedUserMap.delete(e)}setRemotePublishedUserList(e){this.remotePublishedUserMap.forEach(t=>{let r=t[this.key];if(e.findIndex(o=>o[this.key]===t[this.key])<0){this._log.info(`remote [${r}] unpublish`);let o=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(r),this.emit("6",{prevMuteState:o,muteState:t.muteState,flag:0})}}),e.forEach(t=>{var h;let r=t[this.key];if(r===this.mySelfId)return;let{flag:o,userId:n,tinyId:a}=t,d=ur(o,n),l=(h=this.remotePublishedUserMap.get(r))==null?void 0:h.muteState;if(l){let u=this.remotePublishedUserMap.get(r);u&&u.flag!==o&&(u.flag=o,this._log.info(`remote publish updated: ${JSON.stringify(u.muteState)}`),this.emit("6",{prevMuteState:l,muteState:d,flag:o}))}else this._log.info(`remote publish. state: ${JSON.stringify(d)}`),this.addUser({userId:n,tinyId:a,role:20}),this.emit("3",t),this.emit("6",{prevMuteState:ur(0,n),muteState:d,flag:o})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function lh({timesInSecond:s,maxSizeInSecond:i,getSize:e}){return be((t,r)=>{let o=new WeakMap;return x.on(B.ROOM_DESTROY,({room:n})=>o.delete(n)),function(...n){let a=o.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},o.set(this,a)),a.timestamp===0?a.timestamp=Date.now():Date.now()-a.timestamp>1e3&&(a.timestamp=Date.now(),a.callCountInSecond=0,a.totalSizeInSecond=0),e&&(a.totalSizeInSecond+=e(...n)),a.timestamp!==0&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=s||a.totalSizeInSecond>i))throw new X({code:H.INVALID_OPERATION,message:pe({key:me.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=s,isSize:a.totalSizeInSecond>i,name:r,timesInSecond:s,maxSizeInSecond:i}})});a.callCountInSecond++,t.call(this,...n)}})}var KT="2025-06-06 15:06:22",of=!0,nf=function(){var s;if(of){of=!1,z.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${wi}/en/index.html`),console.info(`* Changelog: ${wi}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),z.info("TRTC Web SDK Version:",Rt),Ti||z.debug("Build Time:",KT);let i=`UA: ${navigator.userAgent}
|
|
52
|
+
} `;var Ls=class extends ge{constructor(e){super();c(this,"frameRate");c(this,"_canvas");c(this,"log");c(this,"hasAlpha",!1);c(this,"name");c(this,"error");this.name=e.name,this.log=e.logger.createChild({id:`vc-${this.name}`}),this.frameRate=e.frameRate}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 kr(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new vo(this,e)}createVideoImageSource(e,t){return new Kn(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new ea(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}};c(Ls,"_ids",0);var YT={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},No=class No extends Ls{constructor(){super(...arguments);c(this,"defaultProgam");c(this,"defaultVShader");c(this,"defaultFShader");c(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${Ls._ids++}`),this.ctx=this._canvas.getContext("webgl2",YT),!this.ctx)throw new X({code:H.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,XT),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,QT),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new X({code:H.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})}destroy(e){let t="";return e&&(t=e.message,this.error=e,Q.addFailedEvent({key:512702,error:e})),this.disconnect(),this.log.info(`video context destroy${t}`?`: ${t}`:""),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),e}set width(e){var t;(t=this.ctx)==null||t.viewport(0,0,e,this.height),super.width=e}set height(e){var t;(t=this.ctx)==null||t.viewport(0,0,this.width,e),super.height=e}setSize(e,t){var r;(r=this.ctx)==null||r.viewport(0,0,e,t),super.setSize(e,t)}createShader(e,t){let r=this.ctx,o=r.createShader(e);return r.shaderSource(o,t),r.compileShader(o),o}createProgram(e,t){let r=this.ctx,o=r.createProgram();return r.attachShader(o,e),r.attachShader(o,t),r.linkProgram(o),r.getProgramParameter(o,r.LINK_STATUS)||this.log.error(r.getProgramInfoLog(o)),o}};c(No,"UNAVAILABLE","unavailable"),J([qe(ge.INIT,"created",{sync:!0,fail(e){this.log.error("video gl context create failed",e.cause),Q.addFailedEvent({key:512700,error:e.cause||e})},success(){this.log.info("video context created use webgl"),Q.addSuccessEvent({key:512700})}})],No.prototype,"create",1),J([qe("created",ge.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(No.UNAVAILABLE,e),this.removeAllListeners()}})],No.prototype,"destroy",1);var mt=No,Dt=class extends Ls{constructor(){super(...arguments);c(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${Ls._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new X({code:H.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,Q.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(),Q.addSuccessEvent({key:512703})}};J([qe(ge.INIT,"created",{sync:!0,fail(e){this.log.error("video 2d context create failed",e.cause),Q.addFailedEvent({key:512701,error:e.cause||e})},success(){this.log.info("video context created use 2d"),Q.addSuccessEvent({key:512701})}})],Dt.prototype,"create",1),J([qe("created",ge.INIT,{ignoreError:!0,sync:!0})],Dt.prototype,"destroy",1);function ZT(s){return[15,30,45,60].reduce((e,t)=>Math.abs(t-s)<Math.abs(e-s)?t:e)}var er=class extends bo{constructor(e,t,r=4){super(e,t,r);c(this,"mediaType",4);c(this,"source");c(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.videoManager,this.once("first-video-frame",o=>{this.room.emit("first-video-frame",o)})}play(e,t){return(Qe(t==null?void 0:t.canvasRender)?t.canvasRender:Xt===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 Dt({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});let t=new xs(e,{name:"remotePlayer",logger:this.log});this.source=e.createVideoPlayerSource(this.player),this.source.connect(t),this.player.setCanvas(e._canvas),ys()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let t=this.decodeFPS,r=ZT(t);if(!De(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)}},Do=class extends er{constructor(e,t){super(e,t,2);c(this,"mediaType",2);c(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}};var ko=new Map;x.on(B.JOIN_SUCCESS,({room:s})=>{Ze(s.userId,{eventId:32788})});x.on(B.LEAVE_START,({room:s})=>{Ze(s.userId,{eventId:32789})});x.on(B.LOCAL_TRACK_PUBLISHED,({track:s})=>{if(s.room){let i=32769;s.mediaType===4?i=32768:s.mediaType===2&&(i=32805),Ze(s.room.userId,{eventId:i})}});x.on(B.LOCAL_TRACK_UNPUBLISHED,({track:s})=>{if(s.room){let i=32771;s.mediaType===4?i=32770:s.mediaType===2&&(i=32806),Ze(s.room.userId,{eventId:i})}});x.on(B.TRACK_MUTED,({track:s})=>{s.room&&(s.kind===S.AUDIO?Ze(s.room.userId,{eventId:s.isRemote?32785:32772,remoteUserId:s.isRemote?s.userId:void 0}):Ze(s.room.userId,{eventId:s.isRemote?32784:32773,remoteUserId:s.isRemote?s.userId:void 0}))});x.on(B.TRACK_UNMUTED,({track:s})=>{s.room&&(s.kind===S.AUDIO?Ze(s.room.userId,{eventId:s.isRemote?32787:32774,remoteUserId:s.isRemote?s.userId:void 0}):Ze(s.room.userId,{eventId:s.isRemote?32786:32775,remoteUserId:s.isRemote?s.userId:void 0}))});x.on(B.REMOTE_TRACK_SUBSCRIBED,({track:s})=>{s.room&&(s.mediaType===1&&Ze(s.room.userId,{eventId:32777,remoteUserId:s.userId}),s.mediaType===4&&Ze(s.room.userId,{eventId:32776,remoteUserId:s.userId}),s.mediaType===8&&Ze(s.room.userId,{eventId:32803,remoteUserId:s.userId}))});x.on(B.REMOTE_TRACK_UNSUBSCRIBED,({track:s})=>{s.room&&(s.mediaType===1&&Ze(s.room.userId,{eventId:32779,remoteUserId:s.userId}),s.mediaType===4&&Ze(s.room.userId,{eventId:32778,remoteUserId:s.userId}),s.mediaType===8&&Ze(s.room.userId,{eventId:32804,remoteUserId:s.userId}))});x.on(B.SWITCH_DEVICE_SUCCESS,({track:s})=>{s.room&&Ze(s.room.userId,{eventId:s.kind===S.VIDEO?32780:32781})});x.on(B.LOCAL_TRACK_REPLACED,({track:s})=>{s.room&&Ze(s.room.userId,{eventId:s.kind===S.VIDEO?32782:32783})});x.on(B.SIGNAL_CONNECTION_STATE_CHANGED,({room:s,prevState:i,state:e})=>{let t;switch(e){case"CONNECTED":i==="RECONNECTING"?t=32795:t=32791;break;case"DISCONNECTED":i==="RECONNECTING"?t=32796:t=32790;break;case"RECONNECTING":t=32794;break}t&&Ze(s.userId,{eventId:t})});x.on(B.PEER_CONNECTION_STATE_CHANGED,({room:s,prevState:i,state:e,remoteUserId:t})=>{let r=!!t,o;switch(e){case"CONNECTED":i==="RECONNECTING"?o=r?32801:32798:o=r?32793:32792;break;case"DISCONNECTED":i==="RECONNECTING"&&(o=r?32802:32799);break;case"RECONNECTING":o=r?32800:32797;break}o&&Ze(s.userId,{eventId:o,remoteUserId:t})});x.on(B.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({implementation:s,userId:i,remoteUserId:e,codec:t,isHWCodec:r,prevImplementation:o,streamType:n})=>{let a=r?1:0;o||(a=r?3:2);let d=t==="h264"?0:2,l={eventId:4004,param1:a,param2:d,streamType:n||2};e&&(l.remoteUserId=e,l.eventId=4005),Ze(i,l),Q.addEnum({key:e?514701:513701,value:a}),Q.addEnum({key:e?514700:513700,value:d})});x.on(B.LOCAL_TRACK_RECAPTURE,({track:s,error:i})=>{if(s.userId){let e={eventId:2003,param1:0};s.kind===S.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType=s.streamType==="auxiliary"?7:2,i&&(e.param1=8)),Ze(s.userId,e)}});function Ze(s,i){let e=de(Z({},i),{timestamp:Zo()});ko.has(s)?ko.get(s).push(e):ko.set(s,[e])}function rf(s){if(ko.has(s)){let i=ko.get(s).map(e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,uint32_param1:e.param1,uint32_param2:e.param2,uint32_video_stream_type:e.streamType}));return ko.delete(s),i}return[]}var sf=gt(Mt(),1);var rc=class extends sf.EventEmitter{constructor(e,t,r="userId"){super();this.mySelfId=e;this._log=t;this.key=r;c(this,"userMap",new Map);c(this,"remotePublishedUserMap",new Map)}get hasRobotUser(){return!![...this.remotePublishedUserMap.values()].find(e=>e.isRobot)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:r,tinyId:o,role:n}=e;if(this.userMap.has(t))return;let a={userId:r,tinyId:o,role:n===20?"anchor":"audience"};this.userMap.set(t,a),this.emit("1",a)}deleteUser(e,t){let r=this.userMap.get(e);if(!r)return;let o=`peer leave [${e}]`;M(t)||(o+=`:${cl[t]}`),this._log.info(o);let n=this.remotePublishedUserMap.get(e);if(n){let a=n.muteState;n.flag=0,this.emit("5",n.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:a,muteState:n.muteState,flag:0})}this.userMap.delete(e),this.emit("2",r.userId)}setUserList(e){this.userMap.forEach(t=>{e.findIndex(r=>r[this.key]===t[this.key])<0&&this.deleteUser(t[this.key],0)}),e.forEach(t=>{!this.userMap.has(t[this.key])&&t[this.key]!==this.mySelfId&&this.addUser(t)})}addRemotePublishedUser(e){this.remotePublishedUserMap.has(e[this.key])||this.remotePublishedUserMap.set(e[this.key],e)}deleteRemotePublishedUser(e){this.remotePublishedUserMap.has(e)&&this.remotePublishedUserMap.delete(e)}setRemotePublishedUserList(e){this.remotePublishedUserMap.forEach(t=>{let r=t[this.key];if(e.findIndex(o=>o[this.key]===t[this.key])<0){this._log.info(`remote [${r}] unpublish`);let o=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(r),this.emit("6",{prevMuteState:o,muteState:t.muteState,flag:0})}}),e.forEach(t=>{var h;let r=t[this.key];if(r===this.mySelfId)return;let{flag:o,userId:n,tinyId:a}=t,d=ur(o,n),l=(h=this.remotePublishedUserMap.get(r))==null?void 0:h.muteState;if(l){let u=this.remotePublishedUserMap.get(r);u&&u.flag!==o&&(u.flag=o,this._log.info(`remote publish updated: ${JSON.stringify(u.muteState)}`),this.emit("6",{prevMuteState:l,muteState:d,flag:o}))}else this._log.info(`remote publish. state: ${JSON.stringify(d)}`),this.addUser({userId:n,tinyId:a,role:20}),this.emit("3",t),this.emit("6",{prevMuteState:ur(0,n),muteState:d,flag:o})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function lh({timesInSecond:s,maxSizeInSecond:i,getSize:e}){return be((t,r)=>{let o=new WeakMap;return x.on(B.ROOM_DESTROY,({room:n})=>o.delete(n)),function(...n){let a=o.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},o.set(this,a)),a.timestamp===0?a.timestamp=Date.now():Date.now()-a.timestamp>1e3&&(a.timestamp=Date.now(),a.callCountInSecond=0,a.totalSizeInSecond=0),e&&(a.totalSizeInSecond+=e(...n)),a.timestamp!==0&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=s||a.totalSizeInSecond>i))throw new X({code:H.INVALID_OPERATION,message:pe({key:me.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=s,isSize:a.totalSizeInSecond>i,name:r,timesInSecond:s,maxSizeInSecond:i}})});a.callCountInSecond++,t.call(this,...n)}})}var KT="2025-06-06 16:19:30",of=!0,nf=function(){var s;if(of){of=!1,z.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${wi}/en/index.html`),console.info(`* Changelog: ${wi}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),z.info("TRTC Web SDK Version:",Rt),Ti||z.debug("Build Time:",KT);let i=`UA: ${navigator.userAgent}
|
|
53
53
|
CPU core: ${navigator.hardwareConcurrency}, GPU: ${wl()}`,e=navigator.deviceMemory;e&&(i+=`, minRAM: ${e}GB`),z.info(i),z.info(`URL: ${location.href}${((s=self.frameElement)==null?void 0:s.tagName)==="IFRAME"?" in iframe":""}`),Es().then(t=>{t&&z.info(fi)})}};var ci={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 fe={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},Ri=(U=>(U[U.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",U[U.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",U[U.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",U[U.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",U[U.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",U[U.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",U[U.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",U[U.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",U[U.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",U[U.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",U[U.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",U[U.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",U[U.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",U[U.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",U[U.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",U[U.INVALID_ROOM_ID_REQUIED=5015]="INVALID_ROOM_ID_REQUIED",U[U.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",U[U.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",U[U.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",U[U.INVALID_OPERATION=5100]="INVALID_OPERATION",U[U.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",U[U.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",U[U.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",U[U.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",U[U.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",U[U.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",U[U.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",U[U.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",U[U.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",U[U.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",U[U.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",U[U.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",U[U.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",U[U.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",U[U.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",U[U.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",U[U.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",U[U.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",U[U.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",U[U.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",U[U.DEVICE_ERROR=5300]="DEVICE_ERROR",U[U.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",U[U.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",U[U.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",U[U.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",U[U.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",U[U.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",U[U.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",U[U.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",U[U.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",U[U.SERVER_ERROR=5400]="SERVER_ERROR",U[U.NEED_TO_BUY=5401]="NEED_TO_BUY",U[U.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",U[U.OPERATION_FAILED=5500]="OPERATION_FAILED",U[U.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",U[U.REJOIN_FAILED=5502]="REJOIN_FAILED",U[U.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",U[U.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",U[U.VIDEO_DECODE_ERROR=5505]="VIDEO_DECODE_ERROR",U[U.OPERATION_ABORT=5998]="OPERATION_ABORT",U[U.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",U))(Ri||{});function df({code:s,params:i,enableDocLink:e=!1}){let t="",r,o=Ri[s];try{r=af[o]}catch(n){r=af.UNKNOWN_ERROR}return Fe(r)?t=r(i):Oe(r)&&(t=r),i.fnName&&!t.includes(i.fnName)&&(t[t.length-1]!=="."&&(t+="."),t+=` thrown from ${i.fnName}()`),e&&(t+=" doc:"),t}var af=de(Z({},Tt),{INVALID_PARAMETER({fnName:s}){return`the parameters of the '${s}' you called does not meet the requirements, please check the API documentation.`},INVALID_PARAMETER_REQUIRED({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' is a required param when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_TYPE({key:s,rule:i,fnName:e,value:t}){let r=`${s||i.name}`,o="";return Array.isArray(i.type)?o=i.type.join("|"):o=i.type,`'${r}' must be type of ${o} when calling ${e}(), received type: ${lt(t)}.`},INVALID_PARAMETER_EMPTY({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' cannot be '${t}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:s,rule:i,fnName:e,value:t}){let r=`${s||i.name}`,o=`${i.instanceOf.name||i.instanceOf}`;return`'${r}' must be instanceof ${o} when calling ${e}(), received type: ${lt(t)}.`},INVALID_PARAMETER_RANGE({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' must be one of ${i.values.join("|")} when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_LESS_THAN_ZERO({key:s,rule:i,fnName:e}){return`'${s||i.name}' cannot be less than 0 when calling ${e}().`},INVALID_PARAMETER_MIN({key:s,rule:i,value:e}){return`the min value of ${s||i.name} is ${i.min}, received: ${e}.`},INVALID_PARAMETER_MAX({key:s,rule:i,value:e}){return`the max value of ${s||i.name} is ${i.max}, received: ${e}.`},INVALID_ELEMENT_ID({key:s,fnName:i}){return`'${s}' is not found in the document object when calling ${i}().`},INVALID_ELEMENT_ID_TYPE({key:s,fnName:i,type:e}){return`the element corresponding to '${s}' must be instanceof HTMLElement when calling ${i}(), received: ${e}.`},INVALID_STREAM_ID({key:s}){return`'${s}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},INVALID_ROOM_ID_STRING({key:s}){return`'${s}' must be a valid string.`},INVALID_ROOM_ID_INTEGER({key:s}){return`'${s}' must be an integer between [1, 4294967294].`},INVALID_ROOM_ID_INTEGER_STRING({key:s}){return`'${s}' must be an integer but go a string, use 'parseInt' to convert it or use 'strRoomId' instead.`},INVALID_ROOM_ID_REQUIED(){return"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required."},INVALID_STREAM_TYPE:({fnName:s})=>`'streamType' is required when 'userId' is not '*', calling ${s}()`,INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION({fnName:s}){return`the API '${s}' you called does not meet the requirements, please check the API documentation.`},INVALID_OPERATION_NOT_JOINED({fnName:s}){return`cannot ${s} because you are not enter room yet.`},INVALID_OPERATION_REMOTE_USER_NOT_EXIST({fnName:s,value:i}){return`cannot ${s} because remote user(userId: ${i.userId}) does not publishing stream.`},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST({fnName:s,value:i}){return`cannot ${s} because remote user(userId: ${i.userId}) does not publishing ${i.streamType} video.`},INVALID_OPERATION_REPEAT_CALL({fnName:s}){return`you are already ${s}(), cannot repeated call '${s}'.`},INVALID_OPERATION_NEED_VIDEO({fnName:s}){return`cannot call '${s}' because the camera is not turned on.`},INVALID_OPERATION_NEED_AUDIO({fnName:s}){return`cannot call '${s}' because the microphone is not turned on.`},INVALID_BUFFER_EMPTY:({key:s})=>`the buffer size of paramerter '${s}' cannot be empty`,INVALID_BUFFER_OVERSIZE:()=>"buffer size is over 1000 Bytes",INVALID_ROLE_AUDIENCE:()=>"role: 'audience' cannot call this api.",INVALID_NOT_ENABLE_SEI:()=>"you need to enable SEI in TRTC.create({ enableSEI: true })",INVALID_NEED_CALL_PUBLISHED:({fnName:s})=>`you need to call ${s}() after publish stream.`,ENV_NOT_SUPPORTED({fnName:s}){return`the current browser does not support the capability of the function '${s}' you are calling, please check the API documentation.`},NOT_SUPPORTED_WEBRTC:"the current browser does not support WebRTC capability, please check the SDK documentation.",NOT_SUPPORTED_H264_ENCODE:"this browser does not support H264 encode.",NOT_SUPPORTED_H264_DECODE:"this browser does not support H264 decode.",NOT_SUPPORTED_SCREEN_SHARE:"this browser does not support screen share, please check the browser version.",NOT_SUPPORTED_SMALL_VIDEO:"this browser does not support small video, please check the browser version.",NOT_SUPPORTED_SEI:"this browser does not support SEI, please check the browser version.",NOT_SUPPORTED_WEBGL:"this browser does not support WebGL, please check the browser version.",NOT_SUPPORTED_CHROME_VERSION({fnName:s}){return`cannot call ${s} because the browser version is too low, please upgrade to the latest version`},DEVICE_ERROR({fnName:s,error:i}){return`'${s}' got device exception${i?`, error: ${i.toString()}.`:"."}`},DEVICE_NOT_FOUND_ERROR({fnName:s,deviceType:i=Ps(s),error:e}){return`NotFoundError, no ${i} detected, please check your device and the configuration on '${s}'${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_ALLOWED_ERROR({fnName:s,deviceType:i=Ps(s),error:e}){return`NotAllowedError, you have disabled ${i} access, please allow the current application to use the ${i}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_READABLE_ERROR({fnName:s,deviceType:i=Ps(s),error:e}){return`NotReadableError, the ${i} maybe in use by another APP, please check if the device is pre-occupied by another APP.`},DEVICE_OVERCONSTRAINED_ERROR({fnName:s,deviceType:i=Ps(s),error:e}){return`OverconstrainedError, the device ID is incorrect, please check whether the device ID passed in is correct${e?`, error: ${e.toString()}.`:"."}`},DEVICE_INVALID_STATE_ERROR({fnName:s,deviceType:i=Ps(s),error:e}){return`InvalidStateError, after the user clicks and interacts with the page, turn on the ${i}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_SECURITY_ERROR({fnName:s,deviceType:i=Ps(s),error:e}){return`SecurityError, check whether the system security policy restricts the use of the ${i}, and it is recommended to turn on the ${i} after the user interacts with the page${e?`, error: ${e.toString()}.`:"."}`},DEVICE_ABORT_ERROR({fnName:s,deviceType:i=Ps(s),error:e}){return`AbortError, an unknown exception in the system makes the device unusable, recommended to change the device or browser and re-check whether the device is normal${e?` error: ${e.toString()}.`:"."}`},CAMERA_RECOVER_FAILED({error:s}){return`camera recover capture failed ${(s==null?void 0:s.name)||""}: ${(s==null?void 0:s.originMessage)||(s==null?void 0:s.message)}`},MICROPHONE_RECOVER_FAILED({error:s}){return`microphone recover capture failed ${(s==null?void 0:s.name)||""}: ${(s==null?void 0:s.originMessage)||(s==null?void 0:s.message)}`},OPERATION_FAILED({fnName:s,error:i}){return`'${s}' failed, reason: ${i==null?void 0:i.toString()}`},FIREWALL_RESTRICTION(){return"media connection failure due to firewall restrictions, please try to change your network."},EVENT_HANDLER_ERROR({eventName:s}){return`an error was caught on trtc.on('${s}', handler), please check your code on 'handler'.`},VIDEO_CONTEXT_ERROR({reason:s,error:i}){return`video context error ${s} ${(i==null?void 0:i.name)||""} ${(i==null?void 0:i.message)||""}`},SERVER_ERROR({fnName:s,error:i}){return`'${s}' got server error: ${i==null?void 0:i.toString()}, please check the SDK documentation.`},NEED_TO_BUY({value:s,url:i}){return`You need to buy packages for ${s}. Refer to: ${i}`},ACCOUNT_NO_MONEY:({fnParams:s})=>`your TRTC account run out of credit, please recharge.${s.sdkAppId?` SDKAppId: ${s.sdkAppId}`:""}`,OPERATION_ABORT({fnName:s}){return`'${s}' abort`},UNKNOWN_ERROR({fnName:s,error:i}){return`'${s}' throw unknown exception${i?`, error: ${i.toString()}.`:"."}`}});function Ps(s){if(!s)return"camera";let i=s.toLowerCase();return i.includes("screen")?"screen share":i.includes("audio")?"microphone":"camera"}var uh=class s extends Error{constructor({code:e,extraCode:t,message:r="",messageParams:o,fnName:n="",originError:a}){var l;let d;r?d=r:d=df({code:e===fe.SERVER_ERROR?e:t||e,params:Z({fnName:n,error:a},o)});super(d);c(this,"name","RtcError");c(this,"code");c(this,"extraCode");c(this,"functionName");c(this,"message");c(this,"handler");c(this,"originError");this.name=Ri[e],this.code=e,this.extraCode=t,this.functionName=n,this.originError=a,this.message=d,this.extraCode===5302&&((l=this.originError)!=null&&l.message.includes("system"))&&(this.handler=()=>{let h={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},u={startLocalVideo:"webcam",startLocalAudio:"microphone"},m=document.createElement("a");gs?m.href=`ms-settings:privacy-${u[this.functionName]}`:Ei&&(m.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${h[this.functionName]}`),m.href.length>0&&m.click()})}static convertFrom(e,t,r){let o=e;if(e instanceof X){let{stack:n}=e,a={code:fe.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case H.INVALID_PARAMETER:a.code=fe.INVALID_PARAMETER,a.message=e.message;break;case H.INVALID_OPERATION:a.code=fe.INVALID_OPERATION;break;case H.NOT_SUPPORTED:case H.NOT_SUPPORTED_H264:a.code=fe.ENV_NOT_SUPPORTED,e.getCode()===H.NOT_SUPPORTED_H264&&(a.extraCode=e.message.includes(Tt.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case H.JOIN_ROOM_FAILED:a.messageParams={fnParams:r};case H.SERVER_TIMEOUT:case H.SWITCH_ROLE_FAILED:a.code=fe.SERVER_ERROR,a.extraCode=e.getExtraCode();break;case H.API_CALL_ABORTED:a.code=fe.OPERATION_ABORT;break;case H.DEVICE_NOT_FOUND:case H.DEVICE_AUTO_RECOVER_FAILED:case H.INITIALIZE_FAILED:a.code=5300,e.name&&(a.extraCode=eS(e.name));break;case H.UNKNOWN:break;default:a.code=fe.OPERATION_FAILED}o=new s(a),n&&(o.stack+=n.substr(n.indexOf(`
|
|
54
54
|
`)))}else{if(e instanceof s)return e;o=new s({code:fe.UNKNOWN_ERROR,fnName:t,originError:e})}return o}};function eS(s){let i;switch(s){case"NotFoundError":i=5301;break;case"NotAllowedError":i=5302;break;case"NotReadableError":i=5303;break;case"OverconstrainedError":i=5304;break;case"InvalidStateError":i=5305;break;case"SecurityError":i=5306;break;case"AbortError":i=5307;break;default:i=5300}return i}var ue=uh;var cf={type:"object",properties:{cameraId:{type:"string"},useFrontCamera:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:["string","boolean"],values:[!0,!1,"view","publish","both"]},small:{properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack}}},lf={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}}},Oo={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(s,i,e){if(Oe(s)&&!document.getElementById(s))throw new ue({code:fe.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:i}})}},uf={name:"userId",required:!0,type:"string"},hf={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[ci.AUDIO_PROFILE_STANDARD,ci.AUDIO_PROFILE_STANDARD_STEREO,ci.AUDIO_PROFILE_HIGH,ci.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function ta(s,i){if(!s)throw new ue({code:fe.INVALID_OPERATION,extraCode:5101,fnName:i})}function mf(s,i,e){if(!s)throw new ue({code:fe.INVALID_OPERATION,extraCode:5102,fnName:i,messageParams:{value:e}})}var t0={type:"number",notLessThanZero:!0},tS={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(s,i,e){if(this._room.isJoined)throw new ue({code:fe.INVALID_OPERATION,extraCode:5104,fnName:e});if(s.roomId){if(Oe(s.roomId))throw new ue({code:fe.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:i}});if(!(/^[1-9]\d*$/.test(String(s.roomId))&&s.roomId<4294967295))throw new ue({code:fe.INVALID_PARAMETER,extraCode:5013,fnName:e,messageParams:{key:i}})}else if(s.strRoomId){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(s.strRoomId))throw new ue({code:fe.INVALID_PARAMETER,extraCode:5012,fnName:e,messageParams:{key:i}})}else throw new ue({code:fe.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:Oo,mute:{type:["boolean","string"]},publish:{type:"boolean"},option:cf},validate(s){var i;if(!((i=s==null?void 0:s.option)!=null&&i.videoTrack)&&Ir())throw new ue({code:fe.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:de(Z({},Oo),{required:!1}),publish:{type:"boolean"},mute:{type:["boolean","string"]},option:cf}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:hf},validate(s){var i;if(!((i=s==null?void 0:s.option)!=null&&i.audioTrack)&&Ir())throw new ue({code:fe.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:hf}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:Oo,publish:{type:"boolean"},option:lf},validate(s,i,e,t,r){var o;if(!((o=s==null?void 0:s.option)!=null&&o.videoTrack)){if(Ir())throw new ue({code:fe.ENV_NOT_SUPPORTED,extraCode:5201});if(!kn())throw new ue({code:fe.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:Oo,publish:{type:"boolean"},option:lf}},muteRemoteAudio:[uf,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[uf,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:Oo,userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(s,i,e){ta(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(s.userId);if(mf(!!t,e,s),t&&(s.streamType==="main"&&!t.muteState.videoAvailable||s.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new ue({code:fe.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:s}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:de(Z({},Oo),{required:!1}),userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(s,i,e){ta(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(s.userId);if(mf(!!t,e,s),t&&(s.streamType==="main"&&!t.muteState.videoAvailable||s.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new ue({code:fe.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:s}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(s,i,e){if(s.userId!=="*"&&M(s.streamType))throw new ue({code:fe.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(s,i,e){ta(this._room.isJoining||this._room.isJoined,e)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(s,i,e,t){if(!xn)throw new ue({code:fe.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new ue({code:fe.INVALID_OPERATION,fnName:e,extraCode:5108});if(s.byteLength>1e3)throw new ue({code:fe.INVALID_PARAMETER,extraCode:5018,fnName:e});if(s.byteLength===0)throw new ue({code:fe.INVALID_PARAMETER,extraCode:5017,messageParams:{key:i},fnName:e});ta(this._room.isJoined,e)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(s,i,e){if(!s&&!this._room.isMainStreamPublished||s&&!this._room.isAuxStreamPublished)throw new ue({code:fe.INVALID_OPERATION,extraCode:5109,messageParams:{key:i},fnName:e})}}}}],sendCustomMessage:{name:"message",required:!0,type:"object",properties:{cmdId:{type:"number",required:!0,min:1,max:10},data:{instanceOf:ArrayBuffer,required:!0,validate(s,i,e,t){if(s.byteLength>1e3)throw new ue({code:fe.INVALID_PARAMETER,extraCode:5018,fnName:e});if(s.byteLength===0)throw new ue({code:fe.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:i}})}}},validate(s,i,e){if(ta(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new ue({code:fe.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:i}})}}},It={TRTC:tS};var kt=class extends Error{};function iS(s,i){let e=hs(s);for(let t=0;t<i.length;t++)Li(e[t],i[t]);return e}function rS(s){this._resolve=Promise.resolve(s)}function sS(s){this._reject=Promise.reject(s)}var Kr=class Kr{constructor(i,e){this.instance=i;this.group=e;c(this,"started",!1);c(this,"ops",[]);c(this,"startSame",()=>!0);c(this,"mergeUpdate",iS);let t=Kr.instances.get(i);t?t.set(e,this):Kr.instances.set(i,new Map([[e,this]]))}static get(i,e){if(!e)return;let t=Kr.instances.get(i);return t&&t.get(e)||new Kr(i,e)}static gets(i,e){let t=Kr.instances.get(i),r=[];return t&&t.forEach((o,n)=>{e.test(n)&&r.push(o)}),r}action(i,e,t){let r=a=>{var d;return i===0?this.started=!0:i===3&&(this.started=!1),this.ops.shift(),(d=this.currentOp)==null||d.action(),a},o=a=>{var d,l;throw this.ops.shift(),i===0&&((d=this.currentOp)==null?void 0:d.type)===2&&this.ops.shift().reject(new kt("start failed")),(l=this.currentOp)==null||l.action(),a},n={type:i,action:()=>e(...n.args).then(r,o),args:t,resolve:rS,reject:sS};try{switch(this.state){case 1:if(i===0)throw new kt("already started");break;case 4:if(i===2)throw new kt("not started");break;default:return this.cacheOp(n)}}catch(a){return Promise.reject(a)}return this.ops.push(n),n.promise=e(...n.args).then(r,o)}cacheOp(i){if(this.ops.length===1)switch(this.state){case 0:case 2:if(i.type===0)throw new kt("already start");break;case 3:switch(i.type){case 2:throw new kt("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new kt("unknown state")}else switch(i.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let t=new kt("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 kt("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new kt("start not allowed after update");case 0:throw new kt("duplicate start");case 3:if(this.startSame(this.currentOp.args,i.args))throw this.ops.pop().reject(new kt("keep start")),new kt("already start")}}i.promise=new Promise((t,r)=>{i._resolve?i._resolve.then(t):i.resolve=t,i._reject?i._reject.catch(r):i.reject=r});let{action:e}=i;return i.action=()=>e().then(i.resolve,i.reject),this.ops.push(i),i.promise}get lastOp(){return this.ops[this.ops.length-1]}get lastOpType(){return this.lastOp.type}get currentOp(){return this.ops[0]}get state(){return this.currentOp?this.currentOp.type:this.started?1:4}};c(Kr,"instances",new WeakMap);var Or=Kr;var sc=new WeakMap,oc=(s,i)=>{if(i instanceof kt){let{stack:e}=i;i=new ue({code:fe.OPERATION_ABORT,message:`${s} abort: ${i.message}`,fnName:s}),e&&(i.stack+=e.substr(e.indexOf(`
|
|
55
55
|
`)))}throw i};function es(s,i){return be((e,t)=>function(...r){let o=Or.get(this,typeof s=="string"?s:s.call(this,...r));return o?(i&&(o.startSame=i.bind(this)),o.action(0,e.bind(this),r).catch(oc.bind(null,t))):e.apply(this,r)})}function Us(s,i){let{merge:e,debounce:t}=i||{};return be((r,o)=>function(...n){let a=Or.get(this,typeof s=="string"?s:s.call(this,...n));if(!a)return r.apply(this,n);if(e&&(a.mergeUpdate=e.bind(this)),t&&t.isNeedToDebounce.apply(this,n)){let{delay:d,getKey:l}=t;return new Promise((h,u)=>{var g,f;let m=(g=sc.get(this))==null?void 0:g.get(l(...n));if(m){let{timeoutId:T,resolve:I}=m;clearTimeout(T),I()}let p=setTimeout(()=>{if(a.state===3||a.state===4)return h();a.action(2,r.bind(this),n).catch(oc.bind(null,o)).then(h,u)},d);sc.has(this)?(f=sc.get(this))==null||f.set(l(...n),{timeoutId:p,resolve:h}):sc.set(this,new Map([[l(...n),{timeoutId:p,resolve:h}]]))})}return a.action(2,r.bind(this),n).catch(oc.bind(null,o))})}function ts(s){return be((i,e)=>function(...t){let r=typeof s=="function"?s.call(this,...t):s;if(r instanceof RegExp)return Promise.all(Or.gets(this,r).map(n=>n.action(3,()=>Promise.resolve(),t))).then(()=>i.call(this,...t));let o=Or.get(this,r);return o?o.action(3,i.bind(this),t).catch(oc.bind(null,e)):i.apply(this,t)})}var ne={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"},pf=new Set([ne.ERROR,ne.AUTOPLAY_FAILED,ne.KICKED_OUT,ne.REMOTE_USER_ENTER,ne.REMOTE_USER_EXIT,ne.REMOTE_AUDIO_AVAILABLE,ne.REMOTE_AUDIO_UNAVAILABLE,ne.REMOTE_VIDEO_AVAILABLE,ne.REMOTE_VIDEO_UNAVAILABLE,ne.CONNECTION_STATE_CHANGED,ne.PUBLISH_STATE_CHANGED,ne.SCREEN_SHARE_STOPPED,ne.DEVICE_CHANGED,ne.FIRST_VIDEO_FRAME]);function is(s){return s==="sub"?"auxiliary":s==="auxiliary"?"sub":"main"}function ia(s){return s===ci.QOS_PREFERENCE_CLEAR?"detail":s===ci.QOS_PREFERENCE_SMOOTH?"motion":""}var mh={};nr(mh,{bytes2ms:()=>ym,convertObjectNumberToInt:()=>un,copyProperties:()=>Rm,deepClone:()=>hs,deepMerge:()=>Li,delay:()=>hr,fibonacci:()=>fs,formatedTime:()=>Mm,getConstructorName:()=>cn,getContainerFromElement:()=>wm,getEnv:()=>Am,getInternalVersion:()=>km,getLoggerUrl:()=>lr,getMediaStreamTrackInfo:()=>Ha,getMuteStateFromFlag:()=>ur,getNetworkType:()=>ul,getNumNetworkType:()=>ps,getReconnectionTimeout:()=>pi,getStringByteLength:()=>ln,getTurnServer:()=>Om,getUint32Version:()=>Ba,getValueType:()=>lt,getViewListFromView:()=>Ks,glog:()=>pl,ipv4ToUint32:()=>Zs,isArray:()=>tt,isAudioWorkletSupported:()=>Dm,isBoolean:()=>Qe,isConstructor:()=>Qs,isEmpty:()=>Ys,isFunction:()=>Fe,isLangChinese:()=>mi,isMediaStreamTrack:()=>vm,isNumber:()=>De,isObject:()=>xi,isOverseaSdkAppId:()=>ms,isPlainObject:()=>Ht,isPortrait:()=>Va,isPromise:()=>Wr,isRemoteTrack:()=>Nm,isString:()=>Oe,isUndefined:()=>M,loadImage:()=>eo,ms2bytes:()=>bm,ms2samples:()=>ml,normalizeUrl:()=>Fa,performanceNow:()=>le,promiseAny:()=>_s,samples2ms:()=>hl,setNetworkType:()=>Pa,stringify:()=>oi,stringifyIncludeValue:()=>Ua,throttlePromise:()=>$a});var _h={};nr(_h,{ScheduleRequestType:()=>_f,getAbilityConfig:()=>nS,getScheduleDomain:()=>dc,isNeedToSchedule:()=>nc,scheduleProxy:()=>tr,sendScheduleRequest:()=>fh,setIsNeedToSchedule:()=>yi,setScheduleProxy:()=>ac});var ph=null,nc=!0;typeof document!="undefined"&&document.head.insertAdjacentHTML("beforeend",Object.values(cr).map(s=>`<link rel="dns-prefetch" href="https://${s}">`).join(`\r
|
|
56
56
|
`));function yi(s){Qe(s)&&s!==nc&&(nc=s,z.info(`setIsNeedToSchedule ${s}`))}x.on("28",()=>yi(!0));x.on("63",()=>yi(!0));x.on("84",()=>yi(!0));x.on("201",s=>{s.state==="RECONNECTING"&&yi(!0)});x.on("202",s=>{s.state==="RECONNECTING"&&yi(!0)});function oS(s,i,e){let t={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let r=performance.getEntriesByType("resource"),o=rs(s,"config",S.MAIN),n=rs(s,"config",S.BACKUP);for(let a of r)if(a.startTime>=e&&(a.name===o||a.name===n)&&a.transferSize>0){let d=a.name===o?S.MAIN:S.BACKUP,l=Math.round(a.duration),h=Math.round(a.domainLookupStart-a.startTime),u=a.redirectStart>0?Math.round(a.redirectEnd-a.redirectStart):0,m=a.fetchStart>0?Math.round(a.domainLookupStart-a.fetchStart):0,p=Math.round(a.domainLookupEnd-a.domainLookupStart),g=Math.round(a.requestStart-a.secureConnectionStart),f=Math.round(a.secureConnectionStart-a.connectStart),T=Math.round(a.responseStart-a.requestStart),I=Math.round(a.responseEnd-a.responseStart),v=[p,g,f,T,I];Me.uploadEvent({log:`stat-schedule-net:${l}(${h}(${u}->${m})->${v.join("->")}) ${d}`,userId:i}),t=de(Z({},t),{totalCost:l,local:h,dns:p,tcp:f,tls:g,request:T,response:I});break}}catch(r){z.error("getScheduleDetailCost error",r)}return t}function fh(l){return A(this,arguments,function*({userId:s,sdkAppId:i,useStringRoomId:e,roomId:t,userSig:r,version:o,frameWorkType:n,role:a,latencyLevel:d}){if(!nc&&ph)return{isCached:!0,result:ph};let h={delta:0,count:[1,1],msg:[],detail:[]};try{let u=new FormData;u.append("userId",String(s)),u.append("sdkAppId",String(i)),u.append("isStrGroupId",String(e)),u.append("groupId",String(t)),u.append("sdkVersion",o),u.append("userSig",String(r));let m=yield Es();m!=null&&m.model&&u.append("model",String(m==null?void 0:m.model)),a&&u.append("role",String(a)),d&&u.append("latencyLevel",String(d)),n&&u.append("frameWorkType",String(n));let p=le(),g=yield dS(u,h,i);g.config&&(g.config.loggerDomain&&as(g.config.loggerDomain),Qe(g.config.scheduleCache)&&yi(!g.config.scheduleCache)),h.delta=le()-p;let f=oS(Number(i),s,p);return ph=g,{isCached:!1,result:g,detailCost:f}}catch(u){let m=tt(u)?u[0]:u,p=De(m.code)?m.code:0,g=`schedule failed${m.message?`: ${m.message}`:""}`,f=new X({code:H.SCHEDULE_FAILED,extraCode:p,message:pe({key:me.JOIN_ROOM_FAILED,data:{error:g,code:p}})});throw z.error(g,p),f}})}var tr={main:"",backup:""};function ac(s){tt(s)?(tr.main=s[0],tr.backup=s[1]):tr.main=s}var _f=(t=>(t.CONFIG="config",t.TRTC_AUTO_CONF="trtcAutoConf",t.AUDIO_AI_AUTH="audioAiAuth",t))(_f||{});function rs(s,i,e=S.MAIN,t=!1){return`https://${tr[e]||dc(s,e,t)}/api/v1/${i}`}function nS(s,i,e){let t=rs(s,i),r=rs(s,i,S.BACKUP),o=new URLSearchParams(e).toString(),n=fetch(`${t}?${o}`).then(d=>d.json()),a=fetch(`${r}?${o}`).then(d=>d.json());return _s([n,a])}function dc(s,i=S.MAIN,e=!1){let t;return ms(s)?e?t=i===S.MAIN?cr.MAIN_OVERSEA_BACKUP:cr.BACKUP_OVERSEA:t=i===S.MAIN?cr.MAIN_OVERSEA:cr.BACKUP_OVERSEA:t=i===S.MAIN?cr.MAIN:cr.BACKUP,t}function aS(s,i,e){return new Promise((t,r)=>{mr({url:s,body:i,timeout:e.timeout,priority:"high"}).then(o=>{o.data.code===0?t(o.data.data):r({code:o.data.code,message:o.data.msg})}).catch(r)})}var ff=(s,i)=>Ui({retryFunction:aS,settings:{retries:3,timeout:0},onError:i,onRetrying:s});function dS(s,i,e){return new Promise((t,r)=>{let o=null;_s([ff(n=>i.count[0]=n+1,({error:n,retry:a,retriedCount:d,retryFuncArgs:l})=>{i.msg[0]=n.message,o||(d>=1&&(l[0]=rs(e,"config",S.MAIN,!0)),a())})(rs(e,"config",S.MAIN),s,{get timeout(){return fs(2+i.count[0])*1e3}}),ff(n=>i.count[1]=n+1,({error:n,retry:a,retriedCount:d,retryFuncArgs:l})=>{i.msg[1]=n.message,o||(d>=2&&(l[0]=rs(e,"config",S.BACKUP,!0)),a())})(rs(e,"config",S.BACKUP),s,{get timeout(){return fs(2+i.count[1])*1e3}})]).then(n=>{o=n,t(o)}).catch(r)})}var cS=s=>s.startsWith("data:application/octet-stream;base64,"),lS=s=>s.startsWith("file://"),cc=class{constructor(){c(this,"_log");this._log=z.createLogger({id:"fd"})}download(i,e){return A(this,null,function*(){let{type:t="blob"}=e||{};i=Fa(i);try{let r=le(),o;if(Fe(fetch)?o=yield this.downloadWithFetch(i,t):o=yield this.downloadWithXHR(i,t),!o||!o.data)throw new Error("data is empty");let n=le()-r;return this._log.info(`downloaded: ${i}, return type: ${t}, cost: ${n}ms`),Q.addSuccessEvent({key:522700,cost:le()-r}),o.data}catch(r){throw this._log.error(`failed to download: ${i}, error: ${r}`),Q.addFailedEvent({key:522700,error:r}),r}})}downloadWithFetch(i,e){return A(this,null,function*(){this._log.info(`download with fetch: ${i}, return type: ${e}`);try{let t=yield fetch(i);if(!t.ok)throw new Error("network response was not ok");let r;return e==="arraybuffer"?r=yield t.arrayBuffer():r=yield t.blob(),{data:r}}catch(t){throw t}})}downloadWithXHR(i,e){return this._log.info(`download with xhr: ${i}, return type: ${e}`),new Promise((t,r)=>{let o=new XMLHttpRequest;o.open("GET",i,!0),o.responseType=e,o.onload=()=>{o.status===200||o.status===0&&o.response?t({data:o.response}):r(new Error("XHR failed"))},o.onerror=r,o.send(null)})}loadWasm(i,e){return A(this,null,function*(){this._log.info(`loadWasm ${i}, importObject: ${JSON.stringify(e)}`);let t=le(),r=null,o=null;if(Fe(WebAssembly.instantiateStreaming)&&!cS(i)&&!lS(i)&&Fe(fetch))try{let n=fetch(i);r=(yield WebAssembly.instantiateStreaming(n,e)).instance}catch(n){o=n}if(!r)try{let n=yield this.download(i,{type:"arraybuffer"});r=(yield WebAssembly.instantiate(n,e)).instance}catch(n){o=n}if(r){let n=le()-t;return this._log.info(`loadedWasm ${i}, cost: ${n}ms`),Q.addSuccessEvent({key:522701,cost:n}),r}throw this._log.error(`failed to loadWasm ${i}, error: ${o}`),Q.addFailedEvent({key:522701,error:o}),o})}};J([Gt({settings:{timeout:0,retries:3},onRetrying(i){this._log.warn(`download retrying: ${i}`)}})],cc.prototype,"download",1);var gf=new cc;function Ef({TRTC:s,room:i,errorModule:e,assetsPath:t}){return{TRTC:s,room:i,assetsPath:t,fileDownloader:gf,innerEmitter:x,constants:ll,environment:mo,utils:mh,eventLogger:Me,log:this.room.getLogger(),loggerManager:z,errorModule:e,kvStatManager:Q,rtcDectection:Wi,trtc:this,rx:dh,enums:Jl,schedule:_h,clearStarted:(r,o)=>{let n=r.getAlias(),a=Or.instances.get(this);if(a)if(o){let d=a.get(n+o);if(!d)return;d.started=!1}else a.forEach((d,l)=>{l.startsWith(n)&&(d.started=!1)})},startGetPCM:Jn,createAudioNode:Gn}}var Tf=(s,i)=>{let{emit:e}=s;return s.emit=(...t)=>{try{return e.apply(s,t)}catch(r){let o=pe({key:me.CATCH_HANDLER_ERROR,data:{name:i,event:t[0]},addDocLink:!1});return z.warn(`${o}
|
|
57
57
|
|
|
58
|
-
${r.stack}`),!1}},s};var wo=new WeakMap;function Sf(s){let i=wo.get(s);i&&(i.forEach(e=>clearTimeout(e)),wo.delete(s))}function ra(s,i){return be((e,t)=>function(...r){let o=wo.get(this);o||(o=new Map,wo.set(this,o));let n=i(...r),a=o.get(n);if(!a||a<=0){e.apply(this,r);let d=setTimeout(()=>{var l;(l=wo.get(this))==null||l.delete(n)},s);o.set(n,d)}else{clearTimeout(a);let d=window.setTimeout(()=>{var l;e.apply(this,r),(l=wo.get(this))==null||l.delete(n)},s);o.set(n,d)}})}var If="5.10.2-beta.16";function Ot(...s){return be((i,e)=>function(...t){try{uc.call(this,s,t,e,this._name)}catch(r){return Promise.reject(r)}return i.apply(this,t)})}function gh(...s){return be((i,e)=>function(...t){try{uc.call(this,s,t,e,this._name)}catch(r){throw r}return i.apply(this,t)})}function uc(s,i,e,t){if(tt(s))for(let r=0;r<s.length;r++)lc.call(this,{rule:s[r],value:i[r],key:s[r].name,fnName:e,className:t});else lc.call(this,{rule:s,value:i[0],key:s.name,fnName:e,className:t})}function lc({rule:s,value:i,key:e,fnName:t,className:r}){function o(d){return{code:fe.INVALID_PARAMETER,extraCode:d,fnName:t,messageParams:{key:e,rule:s,value:i}}}if(M(i)){if(s.required)throw new ue(o(5001));if(M(s.defaultValue)){Fe(s.validate)&&s.validate.call(this,i,e,t,r,this);return}i=s.defaultValue}if(Array.isArray(s.type)){let d=!1;for(let l=0;l<s.type.length;l++)s.type[l]===null&&i===null&&(d=!0),Fe(s.type[l])&&i instanceof s.type[l]&&(d=!0),Oe(s.type[l])&<(i)===s.type[l].toLowerCase()&&(d=!0);if(!d)throw new ue({code:fe.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:s.type.map(l=>Qs(l)?cn(l):Oe(l)?l:lt(l))},value:i}})}else if(!M(s.type)&<(i)!==s.type)throw new ue(o(5002));if(s.allowEmpty===!1){let d=De(i)&&(i===0||Number.isNaN(i)),l=Oe(i)&&i.trim()==="";if(d||l)throw new ue(o(5003))}if(s.notLessThanZero&&De(i)&&i<0)throw new ue(o(5006));if(!M(s.min)&&De(i)&&i<s.min)throw new ue(o(5007));if(!M(s.max)&&De(i)&&i>s.max)throw new ue(o(5008));if(Oe(s.instanceOf)){if(!i||i._name!==s.instanceOf)throw new ue(o(5004))}else if(Fe(s.instanceOf)&&!(i instanceof s.instanceOf))throw new ue(o(5004));if(Array.isArray(s.values)&&!s.values.includes(i))throw new ue(o(5005));let{properties:n}=s;Ht(n)&&xi(i)&&Object.keys(n).forEach(d=>{lc.call(this,{rule:n[d],value:i&&i[d],key:`${d}`,fnName:t,className:r})});let{arrayItem:a}=s;Ht(a)&&tt(i)&&i.forEach((d,l)=>{lc.call(this,{rule:a,value:d,key:`${e}[${l}]`,fnName:t,className:r})}),Fe(s.validate)&&s.validate.call(this,i,e,t,r,this)}function Xe(s={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t,ignoreLog:r}=s;return be((o,n)=>function(...a){var u;function d(m,p,g){if(g&&g.includes(m))return"hided";if(e){let f=e(...a);if(a[f.argIndex]===p)return f.value}if(p===a||m in a)return p;try{return p instanceof HTMLElement?`id: ${p.id} type:${lt(p)}`:p instanceof MediaStreamTrack?Ha(p):(JSON.stringify(p),p)}catch(f){return`type:${lt(p)}`}}let l=this._log||z;if(r!=null&&r(...a))return o.apply(this,a);a.length>0?l.info(`${n}() ${JSON.stringify(a,(m,p)=>d(m,p,["userSig","privateMapKey"]))}`):l.info(`${n}()`);let h=t?t(...a):fd[n];try{let m=o.apply(this,a),p=le();return Wr(m)?m.then(g=>(l.info(`${n}() success ${i.call(this,...a)}`),Q.addSuccessEvent({key:h,cost:le()-p}),g)).catch(g=>{var I;g=ue.convertFrom.call(this,g,n,a.length===1?a[0]:a);let f=g.extraCode||g.code,T=(I=g.message)!=null&&I.includes(f)?"":` code:${f}`;throw l.error(`${n}() failed ${i.call(this,...a)} ${g}${T} params: ${JSON.stringify(a,d)}`),Q.addFailedEvent({key:h,error:g}),g}):(Q.addSuccessEvent({key:h}),m)}catch(m){m=ue.convertFrom.call(this,m,n);let p=m.extraCode||m.code,g=(u=m.message)!=null&&u.includes(p)?"":` code:${p}`;throw l.error(`${n}() failed ${m}${g} params: ${JSON.stringify(a,d)}`),Q.addFailedEvent({key:h,error:m}),m}})}var hc=s=>be((i,e)=>function(t,r){return A(this,null,function*(){let o=this._plugins.get(t);if(!o)throw this._log.error(`plugin ${String(t)} is not found`),new ue({code:fe.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});if(Fe(o.constructor.isSupported)&&!o.constructor.isSupported())throw this._log.error(`plugin ${String(t)} is not supported`),new ue({code:fe.ENV_NOT_SUPPORTED,message:`plugin ${String(t)} is not supported`,extraCode:5210,fnName:e});return uc.call(this,o.getValidateRule(s),[r],e,"TRTC"),i.call(this,o,r)})});var mc=0,Eh,wr=class wr{constructor(i){this.core=i;c(this,"log");c(this,"customAudioReferenceMap",new Map);c(this,"audioRefId",0);c(this,"audioContext",dt());c(this,"localAudioWorkletNode");c(this,"screenAudioWorkletNode");c(this,"mixNode");c(this,"mixNodeConnector");c(this,"muteNode");c(this,"muteNodeConnector");mc=mc+1,this.log=i.log.createChild({id:`${this.getAlias()}${mc}`}),this.log.info(`created id=${this.getAlias()}${mc}`),i.assetsPath&&this.preload(`${i.assetsPath}/audioProcessor-wasm.js`)}static startValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,t,r,o){}}}preload(i){return Eh||(Eh=this.doPreload(i)),Eh}doPreload(i){return A(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield Rr(this.audioContext,t)}catch(r){this.log.error(`preload audioProcessor failed. ${r}`)}finally{URL.revokeObjectURL(t)}})}getName(){return wr.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(i){switch(i){case"start":return wr.startValidateRule(this.core);case"update":return wr.updateValidateRule;case"stop":return wr.stopValidateRule}}start(i){return A(this,null,function*(){let{room:e}=this.core,{sdkAppId:t,userId:r,assetsPath:o,audioReference:n,processLevel:a,enableDump:d,isLocalAudioNeedAudioProcess:l=!0,isScreenAudioNeedAudioProcess:h=!0}=i;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=l,this.core.room.audioManager.isScreenAudioNeedAudioProcess=h,yield this.preload(`${o}/audioProcessor-wasm.js`),!this.localAudioWorkletNode||!this.screenAudioWorkletNode){let u=String(Date.now()).slice(0,-3),{auth:m,sign:p,status:g,message:f}=yield mS(de(Z({},i),{timestamp:u}));if(!m)throw this.log.info(`audioProcessor: ${r} auth result: ${m}. Message: ${f}`),new ue({code:fe.INVALID_PARAMETER,message:f});this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.localAudioWorkletNode.port.postMessage({type:"init",data:{sdkAppId:String(t),userId:r,timestamp:u,sign:p,status:g}}),this.localAudioWorkletNode.port.onmessage=T=>{var v;let{data:I}=T;switch(I.type){case"cost":let b=(I==null?void 0:I.value)>20?"warn":(I==null?void 0:I.value)>10?"info":"debug";this.log[b](`avg cost: ${I.value} max: ${I==null?void 0:I.max}(${ns(new Date(I==null?void 0:I.maxCostTimestamp))}) hist: ${(v=I==null?void 0:I.hist)==null?void 0:v.join(" ")}`);return;case"log":this.log[I.logLevel](`${I.value}`);return;case"dump":x.emit("265",{room:e,data:I.value,type:"dump"});return}},this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.screenAudioWorkletNode.port.postMessage({type:"init",data:{sdkAppId:String(t),userId:r,timestamp:u,sign:p,status:g}}),this.screenAudioWorkletNode.port.onmessage=T=>{var v;let{data:I}=T;switch(I.type){case"cost":let b=(I==null?void 0:I.value)>20?"warn":(I==null?void 0:I.value)>10?"info":"debug";this.log[b](`[dump-screen-audio] avg cost: ${I.value} max: ${I==null?void 0:I.max}(${ns(new Date(I==null?void 0:I.maxCostTimestamp))}) hist: ${(v=I==null?void 0:I.hist)==null?void 0:v.join(" ")}`);return;case"log":this.log[I.logLevel](`[dump-screen-audio] ${I.value}`);return;case"dump":x.emit("265",{room:e,data:I.value,type:"dump-screen-audio"});return}}}this.mixNode||(this.mixNode=this.audioContext.createGain(),this.mixNode.gain.value=1),this.muteNode||(this.muteNode=this.audioContext.createConstantSource(),this.muteNode.offset.setValueAtTime(0,this.audioContext.currentTime),this.muteNode.start()),this.localAudioWorkletNode.port.postMessage({type:"enable"}),this.screenAudioWorkletNode.port.postMessage({type:"enable"}),e.audioManager.addAudioProcessor(this.localAudioWorkletNode,this.mixNode,this.muteNode,this.screenAudioWorkletNode),M(n)||n.forEach(u=>{this.customAudioReferenceMap.set(u,`o-${this.audioRefId++}`),x.emit("266",{room:this.core.room,type:"add",audioReference:u,refId:`o-${this.audioRefId++}`})}),M(a)||this.localAudioWorkletNode.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:a}}),M(d)||this.localAudioWorkletNode.port.postMessage({type:"dump",data:{enable:d}})})}update(i){return A(this,null,function*(){if(!this.localAudioWorkletNode||!this.screenAudioWorkletNode)return;let{audioReference:e,enableDump:t,processLevel:r}=i;M(e)||(this.customAudioReferenceMap.forEach((o,n)=>{this.customAudioReferenceMap.delete(n),x.emit("266",{room:this.core.room,type:"remove",refId:o})}),e.forEach(o=>{this.customAudioReferenceMap.set(o,`o-${this.audioRefId++}`),x.emit("266",{room:this.core.room,type:"add",audioReference:o,refId:`o-${this.audioRefId++}`})})),M(r)||this.localAudioWorkletNode.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:r}}),M(t)||(this.localAudioWorkletNode.port.postMessage({type:"dump",data:{enable:t}}),this.screenAudioWorkletNode.port.postMessage({type:"dump",data:{enable:t}}))})}stop(){return A(this,null,function*(){if(!this.localAudioWorkletNode||!this.mixNode||!this.muteNode||!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.muteNode,this.screenAudioWorkletNode)})}destroy(){this.localAudioWorkletNode&&(this.localAudioWorkletNode.port.onmessage=null),this.screenAudioWorkletNode&&(this.screenAudioWorkletNode.port.onmessage=null)}};c(wr,"updateValidateRule",{type:"object"}),c(wr,"stopValidateRule",{type:"object"}),c(wr,"Name","AudioProcessor");var pc=wr;function hS(s,i=S.MAIN){return`https://${tr[i]||dc(s,i)}/api/v1/audioAiAuth`}function mS(r){return A(this,arguments,function*({sdkAppId:s,userId:i,userSig:e,timestamp:t}){let n=`${hS(s)}?sdkAppId=${s}&userId=${i}&userSig=${e}×tamp=${t}`,a=yield fetch(n),{data:{errCode:d,errMsg:l,sign:h,status:u}}=yield a.json();if(u==="1")return{auth:!0,sign:h,status:u,message:l};let m=ms(s)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",p="Init RTCAudioProcessor failed.",g="";switch(d){case 1:g="Please check your params.";break;case 2:g=`You need to buy packages. Refer to: ${m}`;break;case 3:g="Server is invalid. Please contact our engineer. ";break;case 4:g=`Your packages is not active. Refer to: ${m}`;break;case 5:g=`Your packages is expired. Refer to: ${m}`;break;case 6:g="Your version is not supported.";break}return{auth:!1,status:u,message:l?`${p} Reason: ${l}. ${g}`:`${p}, ${g}`}})}var fc=0,Th=class{constructor(i,e){c(this,"player");c(this,"publisher");c(this,"mixInput");this.mixInput=new Io(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&&(M(i.volume)||(this.volume=i.volume),M(i.loop)||(this.loop=i.loop),M(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 Mo(s,i){if(i&&typeof i!="function")throw new ue({code:fe.INVALID_PARAMETER,message:`start audioMixer plugin: param ${s} should be a function.`})}var ir=class ir{constructor(i){this.core=i;c(this,"log");c(this,"mixedMusicMap",new Map);c(this,"cacheMusicMap",new Map);fc=fc+1,this.log=i.log.createChild({id:`${this.getAlias()}${fc}`}),this.log.info(`created id=${this.getAlias()}${fc}`)}getName(){return ir.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return ir.startValidateRule;case"update":return ir.updateValidateRule;case"stop":return ir.stopValidateRule}}start(i){return A(this,null,function*(){let{room:e}=this.core;this.log.info(`add music source, id: ${i.id} url: ${i.url}, track: ${i.track}`);let{id:t,url:r}=i;if(this.mixedMusicMap.has(t))return;let o=this.cacheMusicMap.get(t);o?i.url?o.reset():(o.mixInput.replaceSource(i.track),o.mixInput.connect()):(o=new Th(i,e.audioManager),this.cacheMusicMap.set(t,o)),o.updateListener(i),o.updateSettings(i),yield o.play(),this.mixedMusicMap.set(t,o),o.mixInput.source.node&&x.emit("266",{room:this.core.room,type:"add",audioReference:o.mixInput.source.node,refId:`ax-${t}`}),this.log.info(`start mix audio track ${t} success.`),Q.addEnum({key:502700,value:3}),this.kvUpload(i)})}update(i){return A(this,null,function*(){let{id:e,operation:t,seekFrom:r,playbackRate:o}=i;this.log.info(`update music source, ${JSON.stringify(i)}`);let n=this.mixedMusicMap.get(e);if(!n){this.log.warn(`update music source failed, music id: ${e} not found.`);return}n.updateSettings(i),n.updateListener(i),M(t)||n.setOperation(t),M(r)||n.seek(r),this.kvUpload(i)})}stop(e){return A(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&&x.emit("266",{room:this.core.room,type:"remove",audioReference:t.mixInput.source.node,refId:`ax-${i}`}),t==null||t.stop(),this.mixedMusicMap.delete(i)}i==="*"&&this.destroyAllMusic()})}kvUpload(i){let{track:e,loop:t,volume:r,playbackRate:o,operation:n,seekFrom:a,onTimeUpdate:d,onDurationChange:l,onEnded:h}=i;e&&Q.addCount({key:502711}),t&&Q.addCount({key:502703}),r&&Q.addCount({key:502704}),o&&Q.addCount({key:502705}),n&&Q.addCount({key:502706}),a&&Q.addCount({key:502707}),typeof d!="function"&&Q.addCount({key:502709}),typeof h!="function"&&Q.addCount({key:502710}),typeof l!="function"&&Q.addCount({key:502708})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((i,e)=>{i!=null&&i.mixInput.track&&x.emit("266",{room:this.core.room,type:"remove",audioReference:i.mixInput.track,refId:e}),this.stop({id:e})})}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}};c(ir,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(i,e,t){if(i.url&&i.url!=="*"){let r=i.url.split("?")[0],o=["mp3","ogg","wav","flac"],n=r.split(".").pop(),a=o.indexOf(n)>=0,d=r.startsWith("blob"),l=r.startsWith("data");if(!(a||d||l))throw new ue({code:fe.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new ue({code:fe.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});Mo("onTimeUpdate",i.onTimeUpdate),Mo("onEnded",i.onEnded),Mo("onDurationChange",i.onDurationChange)}}),c(ir,"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){Mo("onTimeUpdate",i.onTimeUpdate),Mo("onEnded",i.onEnded),Mo("onDurationChange",i.onDurationChange)}}),c(ir,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),c(ir,"Name","AudioMixer");var _c=ir;var gc=0,Sh,Mr=class Mr{constructor(i){this.core=i;c(this,"log");c(this,"audioContext",dt("denoiser"));c(this,"workletNode");gc=gc+1,this.log=i.log.createChild({id:`${this.getAlias()}${gc}`}),this.log.info(`created id=${this.getAlias()}${gc}`),i.assetsPath&&this.preload(`${i.assetsPath}/denoiser-wasm.js`).catch(e=>{})}static startValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,t,r,o){if(!i.room.audioManager.hasAudioTrack)throw new ue({code:fe.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return Sh||(Sh=this.doPreload(i)),Sh}doPreload(i){return A(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield Rr(this.audioContext,t)}catch(r){throw this.log.error("load worklet failed",r),r}finally{URL.revokeObjectURL(t)}})}getName(){return Mr.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(i){switch(i){case"start":return Mr.startValidateRule(this.core);case"update":return Mr.updateValidateRule;case"stop":return Mr.stopValidateRule}}start(i){return A(this,null,function*(){let{room:e,schedule:t}=this.core;if(yield this.preload(`${i.assetsPath}/denoiser-wasm.js`),!this.workletNode){let r=String(Date.now()).slice(0,-3),{auth:o,sign:n,status:a,message:d}=yield fS(t,de(Z({},i),{timestamp:r}));if(!o)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${o}. Message: ${d}`),new ue({code:fe.INVALID_PARAMETER,message:d});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(i.sdkAppId),userId:i.userId,timestamp:r,sign:n,status:a}}),this.workletNode.port.onmessage=l=>{var u;let{data:h}=l;if(h.type==="cost"){let m=(h==null?void 0:h.max)>20?"warn":(h==null?void 0:h.max)>10?"info":"debug";this.log[m](`avg cost: ${h.value} max: ${h==null?void 0:h.max}(${ns(new Date(h==null?void 0:h.maxCostTimestamp))}) hist: ${(u=h==null?void 0:h.hist)==null?void 0:u.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 A(this,null,function*(){})}stop(){return A(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)}};c(Mr,"updateValidateRule",{type:"object"}),c(Mr,"stopValidateRule",{type:"object"}),c(Mr,"Name","AIDenoiser");var Ec=Mr;function fS(o,n){return A(this,arguments,function*(s,{sdkAppId:i,userId:e,userSig:t,timestamp:r}){try{let{data:{errCode:a,errMsg:d,sign:l,status:h}}=yield s.getAbilityConfig(i,s.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:i,userId:e,userSig:t,timestamp:r});if(h==="1")return{auth:!0,sign:l,status:h,message:d};let u="Init RTCAIDenoiser failed.",m="";switch(a){case 1:m="Please check your params.";break;case 2:m="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:m="Server is invalid. Please contact our engineer. ";break;case 4:m="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:m="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:m="Your version is not supported.";break}return{auth:!1,status:h,message:d?`${u} Reason: ${d}. ${m}`:`${u}, ${m}`}}catch(a){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${a}`}}})}var Af=gt(Mt(),1);var Ih=class extends Af.EventEmitter{constructor(){super();c(this,"observer");c(this,"state","nominal");this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return A(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!ze&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){Me.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)&&z.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){Me.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},_S=new Ih,Ah=_S;function Ch([s,i]){let e=i.byteLength,t=parseInt(String(e/255),10),r=e%255,o=[];o.push(0,0,0,1,6,s);for(let a=0;a<t;a++)o.push(255);o.push(r);let n=new DataView(i);return o.push(...new Uint8Array(n.buffer)),o.push(128),new vr(new DataView(new Uint8Array(o).buffer),!0)}function Rh(s){return s.type==="empty"||s.data.byteLength===0}function yh(s){return s.getInt32(0)===1&&s.getInt8(4)===6}function bh(s){let i=0,e=0,t=new DataView(s);for(let r=0;r<s.byteLength;r++)switch(t.getUint8(r)){case 0:i++;break;case 1:(i===2||i===3)&&e++,i=0;break;default:i=0;break}return e}function vh({frame:s,seiMessageList:i}){if(!i||i.length===0||s.data.byteLength===0)return s;let t=9-bh(s.data);if(t<=0)return s;let r=i.splice(0,t).reverse().map(Ch),o=r.reduce((h,u)=>h+u.dataView.byteLength,0),n=new ArrayBuffer(o+s.data.byteLength),a=new DataView(n),d=new DataView(s.data),l=0;for(let h=0;h<r.length;h++)for(let u=0;u<r[h].dataView.byteLength;u++)a.setInt8(l++,r[h].dataView.getInt8(u));for(let h=0;h<s.data.byteLength;h++)a.setInt8(l++,d.getInt8(h));return s.data=n,s}function Nh({frame:s,onSEI:i}){try{let e=new DataView(s.data);if(Rh(s)||!yh(e))return s;let t=[],r=0,o=-1,n=-1;for(let a=0;a<s.data.byteLength;a++){let d=e.getUint8(a);if(d===0)r++;else if(d===1){if(r===2||r===3){let l=a-r;if(o===-1?o=l:n===-1&&(n=l,t.push(new vr(new DataView(e.buffer.slice(o,n)))),o=l,n=-1),!(e.getUint8(a+1)===6)){s.data=e.buffer.slice(l);break}}r=0}else r=0}i==null||i(t.reverse())}catch(e){}return s}var Dh=0,sa=class sa{constructor(i){this.core=i;c(this,"log");c(this,"_seiMessageList",[]);c(this,"_smallSeiMessageList",[]);c(this,"_subStreamSeiMessageList",[]);Dh++,this.log=i.log.createChild({id:`${this.getAlias()}${Dh}`}),this.log.info(`[sei] created id=${this.getAlias()}${Dh}`),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 vh({frame:i,seiMessageList:t})}catch(t){this.log.warn(t)}return i}decode({frame:i,track:e}){return Nh({frame:i,onSEI:t=>{t.forEach(r=>{this.core.trtc.emit(ne.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:Ar?this.encode:vh,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:Ar?this.decode:Nh,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update({buffer:i,options:e}){var o;let t=[e.seiPayloadType,i],r=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(t):(this._seiMessageList.push(t),r&&this._smallSeiMessageList.push(t)),(o=this.core.room.scriptTransformWorker)==null||o.postMessage({type:"sei",data:t,isMain:!e.toSubStream,small:r})}getName(){return sa.Name}getAlias(){return"sei"}getGroup(){return"sei"}};c(sa,"autoStart",!0),c(sa,"Name","SEI");var Tc=sa;function kh({frame:s,onDump:i}){return i==null||i(),s}function Oh({frame:s,onDump:i}){return i==null||i(),s}var Cf=()=>{let s=window.navigator&&window.navigator.userAgent||"",i=/iPad/i.test(s)||/iPhone/i.test(s),e=/Android/i.test(s);return i||e},Re={LOG_BUTTON:"Log",NETWORK_BUTTON:"Network",DUMP_BUTTON:"Dump",DUMPING_BUTTON:"Dumping",END_BUTTON:"End",UPLOAD_BUTTON:"Upload Log",EXPORT_BUTTON:"Export Log",HIDE_BUTTON:"Hide",GO_BOTTOM:"goBottom",BACK_TOP:"backTop",CLEAR_LOG:"Clear Log",UPLINK:"Uplink",DOWNLINK:"Downlink",NO_DATA:"No Data",BASIC:"Basic",DURATION:"Duration",VIDEO:"Video",AUDIO:"Audio",SCREEN:"Screen"},Rf=s=>s.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d").replace(">",">").replace(">","<"),ss={"play() error: NotAllowedError:":{tips:s=>s.includes("main <video>")||s.includes("main <audio>")?"Remote stream auto play is restricted and playback fails":"Local stream playback failure, generally only occurs in Android WeChat devices, no need to handle",color:"red",class:"red"},"updateStream() try to recover local stream":{tips:"Device acquisition exception, automatic recovery is in progress"},"updateStream() recover local stream successfully":{tips:"Device acquisition exception, automatic recovery is successful"},"updateStream() failed to recover local stream":{tips:"Device acquisition exception, automatic recovery failed"},"main stream - video track is muted":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is muted":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is muted":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unable to provide media output":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is unable to provide media output":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is unable to provide media output":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unmuted":{tips:"Received enough playback video data"},"main stream - audio track is unmuted":{tips:"Received enough playback audio data"},"auxiliary stream - video track is unmuted":{tips:"Received enough playback screen sharing data"},"main stream - audio player track is ended":{tips:"Remote audio track stopped"},"main stream - video player track is ended":{tips:"Remote video track stopped"},"auxiliary stream - video player track is ended":{tips:"Received enough playback screen sharing data"},"stream - video track is muted":{tips:"Camera capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"stream - video track is unable to provide media output":{tips:"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked, and the customer needs to re-acquire. SDK v4.11.4+ will automatically resume acquisition without customer intervention",color:"orange"},"video track is unable to provide media output":{tips:s=>s.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"stream - audio track is muted":{tips:"Microphone capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"audio track is unable to provide media output":{tips:s=>s.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"Microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio track is unable to provide media output":{tips:"The microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"is adding audio track to current published local stream":{tips:"add audio track",color:"orange"},"is removing audio track from current published local stream":{tips:"remove audio track",color:"orange"},"is removing video track from current published local stream":{tips:"remove video track",color:"orange"},"is adding video track to current published local stream":{tips:"add video track",color:"orange"},"is replacing audio track to current published local main stream":{tips:"replace audio track",color:"orange"},"is replacing video track to current published local main stream":{tips:"replace video track",color:"orange"},"downlink network quality change":{tips:"Downstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"uplink network quality change":{tips:"Upstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"localStream mute video":{tips:"mute upstream video stream",color:"orange"},"localStream unmute video":{tips:"unmute upstream video stream",color:"orange"},"localStream mute audio":{tips:"mute upstream audio stream",color:"orange"},"localStream unmute audio":{tips:"unmute upstream audio stream",color:"orange"},"black detected":{tips:"Detect black screen, which means fps = 0. It is usually caused by network, and the network will be recovered after a while. If the network is normal but has not been restored, it is an abnormal situation."},'main stream start to play with options: {"muted":true}':{tips:"Play the remote stream in silent mode. Generally, the remote stream does not need to be played in silent mode. You need to confirm whether the parameters passed in the client stream.play API call are correct.",color:"orange"},"main stream - audio player is starting playing":{tips:"Remote stream audio playback success",color:"#0dd90d",class:"success"},"main stream - video player is starting playing":{tips:"Remote stream video playback success",color:"#0dd90d",class:"success"},"video player is playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"audio player is playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"stream - video player is starting playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"stream - audio player is starting playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"switch camera success":{tips:"Switch camera success",color:"#0dd90d",class:"success"},"switch microphone success":{tips:"Switch microphone success",color:"#0dd90d",class:"success"},gotStream:{tips:"Local stream capture success"},"local stream is published successfully":{tips:"Publish success",color:"#0dd90d",class:"success"},"encoderImplementation change to OpenH264":{tips:"Use software encoding"},"encoderImplementation change to ExternalEncoder":{tips:"Use hardware encoding"},"getUserMedia with constraints":{tips:"Start media (camera/microphone) capture"},"getDisplayMedia with constraints":{tips:"Start screen sharing capture"},"client-banned":{tips:"Kicked out of the room",color:"red",class:"red",textColor:"#fff"},user_timeout:{tips:"The backend is too long without receiving SDK heartbeat, which is usually caused by the JS thread being blocked for a long time. If the reproduction probability is high, the application browser Performance tool analyzes where the JS thread is blocked.",color:"red",class:"red",textColor:"#fff"},"schedule failed":{tips:"Signaling request failed, does not affect the normal room entry process, SDK will connect to the default signaling domain."},"updateStream() video flag is true, but no camera detected, set video to false":{tips:"When trying to resume camera acquisition, the camera acquisition is not resumed because it is detected that there is no camera.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to bandwidth":{tips:"bandwidth estimation is not enough to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to cpu":{tips:"cpu load is too high to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: hidden":{tips:"User page switched to backend, in mobile devices, this will cause the device to pause the capture, and it will be restored when the user switches backend to the frontend.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: visible":{tips:"User page switched to frontend",color:"orange",class:"orange",textColor:"#fff"},"main stream - audio player is paused":{tips:`The remote stream audio playback is paused, which usually has two possibilities:
|
|
58
|
+
${r.stack}`),!1}},s};var wo=new WeakMap;function Sf(s){let i=wo.get(s);i&&(i.forEach(e=>clearTimeout(e)),wo.delete(s))}function ra(s,i){return be((e,t)=>function(...r){let o=wo.get(this);o||(o=new Map,wo.set(this,o));let n=i(...r),a=o.get(n);if(!a||a<=0){e.apply(this,r);let d=setTimeout(()=>{var l;(l=wo.get(this))==null||l.delete(n)},s);o.set(n,d)}else{clearTimeout(a);let d=window.setTimeout(()=>{var l;e.apply(this,r),(l=wo.get(this))==null||l.delete(n)},s);o.set(n,d)}})}var If="5.10.2-beta.17";function Ot(...s){return be((i,e)=>function(...t){try{uc.call(this,s,t,e,this._name)}catch(r){return Promise.reject(r)}return i.apply(this,t)})}function gh(...s){return be((i,e)=>function(...t){try{uc.call(this,s,t,e,this._name)}catch(r){throw r}return i.apply(this,t)})}function uc(s,i,e,t){if(tt(s))for(let r=0;r<s.length;r++)lc.call(this,{rule:s[r],value:i[r],key:s[r].name,fnName:e,className:t});else lc.call(this,{rule:s,value:i[0],key:s.name,fnName:e,className:t})}function lc({rule:s,value:i,key:e,fnName:t,className:r}){function o(d){return{code:fe.INVALID_PARAMETER,extraCode:d,fnName:t,messageParams:{key:e,rule:s,value:i}}}if(M(i)){if(s.required)throw new ue(o(5001));if(M(s.defaultValue)){Fe(s.validate)&&s.validate.call(this,i,e,t,r,this);return}i=s.defaultValue}if(Array.isArray(s.type)){let d=!1;for(let l=0;l<s.type.length;l++)s.type[l]===null&&i===null&&(d=!0),Fe(s.type[l])&&i instanceof s.type[l]&&(d=!0),Oe(s.type[l])&<(i)===s.type[l].toLowerCase()&&(d=!0);if(!d)throw new ue({code:fe.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:s.type.map(l=>Qs(l)?cn(l):Oe(l)?l:lt(l))},value:i}})}else if(!M(s.type)&<(i)!==s.type)throw new ue(o(5002));if(s.allowEmpty===!1){let d=De(i)&&(i===0||Number.isNaN(i)),l=Oe(i)&&i.trim()==="";if(d||l)throw new ue(o(5003))}if(s.notLessThanZero&&De(i)&&i<0)throw new ue(o(5006));if(!M(s.min)&&De(i)&&i<s.min)throw new ue(o(5007));if(!M(s.max)&&De(i)&&i>s.max)throw new ue(o(5008));if(Oe(s.instanceOf)){if(!i||i._name!==s.instanceOf)throw new ue(o(5004))}else if(Fe(s.instanceOf)&&!(i instanceof s.instanceOf))throw new ue(o(5004));if(Array.isArray(s.values)&&!s.values.includes(i))throw new ue(o(5005));let{properties:n}=s;Ht(n)&&xi(i)&&Object.keys(n).forEach(d=>{lc.call(this,{rule:n[d],value:i&&i[d],key:`${d}`,fnName:t,className:r})});let{arrayItem:a}=s;Ht(a)&&tt(i)&&i.forEach((d,l)=>{lc.call(this,{rule:a,value:d,key:`${e}[${l}]`,fnName:t,className:r})}),Fe(s.validate)&&s.validate.call(this,i,e,t,r,this)}function Xe(s={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t,ignoreLog:r}=s;return be((o,n)=>function(...a){var u;function d(m,p,g){if(g&&g.includes(m))return"hided";if(e){let f=e(...a);if(a[f.argIndex]===p)return f.value}if(p===a||m in a)return p;try{return p instanceof HTMLElement?`id: ${p.id} type:${lt(p)}`:p instanceof MediaStreamTrack?Ha(p):(JSON.stringify(p),p)}catch(f){return`type:${lt(p)}`}}let l=this._log||z;if(r!=null&&r(...a))return o.apply(this,a);a.length>0?l.info(`${n}() ${JSON.stringify(a,(m,p)=>d(m,p,["userSig","privateMapKey"]))}`):l.info(`${n}()`);let h=t?t(...a):fd[n];try{let m=o.apply(this,a),p=le();return Wr(m)?m.then(g=>(l.info(`${n}() success ${i.call(this,...a)}`),Q.addSuccessEvent({key:h,cost:le()-p}),g)).catch(g=>{var I;g=ue.convertFrom.call(this,g,n,a.length===1?a[0]:a);let f=g.extraCode||g.code,T=(I=g.message)!=null&&I.includes(f)?"":` code:${f}`;throw l.error(`${n}() failed ${i.call(this,...a)} ${g}${T} params: ${JSON.stringify(a,d)}`),Q.addFailedEvent({key:h,error:g}),g}):(Q.addSuccessEvent({key:h}),m)}catch(m){m=ue.convertFrom.call(this,m,n);let p=m.extraCode||m.code,g=(u=m.message)!=null&&u.includes(p)?"":` code:${p}`;throw l.error(`${n}() failed ${m}${g} params: ${JSON.stringify(a,d)}`),Q.addFailedEvent({key:h,error:m}),m}})}var hc=s=>be((i,e)=>function(t,r){return A(this,null,function*(){let o=this._plugins.get(t);if(!o)throw this._log.error(`plugin ${String(t)} is not found`),new ue({code:fe.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});if(Fe(o.constructor.isSupported)&&!o.constructor.isSupported())throw this._log.error(`plugin ${String(t)} is not supported`),new ue({code:fe.ENV_NOT_SUPPORTED,message:`plugin ${String(t)} is not supported`,extraCode:5210,fnName:e});return uc.call(this,o.getValidateRule(s),[r],e,"TRTC"),i.call(this,o,r)})});var mc=0,Eh,wr=class wr{constructor(i){this.core=i;c(this,"log");c(this,"customAudioReferenceMap",new Map);c(this,"audioRefId",0);c(this,"audioContext",dt());c(this,"localAudioWorkletNode");c(this,"screenAudioWorkletNode");c(this,"mixNode");c(this,"mixNodeConnector");c(this,"muteNode");c(this,"muteNodeConnector");mc=mc+1,this.log=i.log.createChild({id:`${this.getAlias()}${mc}`}),this.log.info(`created id=${this.getAlias()}${mc}`),i.assetsPath&&this.preload(`${i.assetsPath}/audioProcessor-wasm.js`)}static startValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,t,r,o){}}}preload(i){return Eh||(Eh=this.doPreload(i)),Eh}doPreload(i){return A(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield Rr(this.audioContext,t)}catch(r){this.log.error(`preload audioProcessor failed. ${r}`)}finally{URL.revokeObjectURL(t)}})}getName(){return wr.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(i){switch(i){case"start":return wr.startValidateRule(this.core);case"update":return wr.updateValidateRule;case"stop":return wr.stopValidateRule}}start(i){return A(this,null,function*(){let{room:e}=this.core,{sdkAppId:t,userId:r,assetsPath:o,audioReference:n,processLevel:a,enableDump:d,isLocalAudioNeedAudioProcess:l=!0,isScreenAudioNeedAudioProcess:h=!0}=i;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=l,this.core.room.audioManager.isScreenAudioNeedAudioProcess=h,yield this.preload(`${o}/audioProcessor-wasm.js`),!this.localAudioWorkletNode||!this.screenAudioWorkletNode){let u=String(Date.now()).slice(0,-3),{auth:m,sign:p,status:g,message:f}=yield mS(de(Z({},i),{timestamp:u}));if(!m)throw this.log.info(`audioProcessor: ${r} auth result: ${m}. Message: ${f}`),new ue({code:fe.INVALID_PARAMETER,message:f});this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.localAudioWorkletNode.port.postMessage({type:"init",data:{sdkAppId:String(t),userId:r,timestamp:u,sign:p,status:g}}),this.localAudioWorkletNode.port.onmessage=T=>{var v;let{data:I}=T;switch(I.type){case"cost":let b=(I==null?void 0:I.value)>20?"warn":(I==null?void 0:I.value)>10?"info":"debug";this.log[b](`avg cost: ${I.value} max: ${I==null?void 0:I.max}(${ns(new Date(I==null?void 0:I.maxCostTimestamp))}) hist: ${(v=I==null?void 0:I.hist)==null?void 0:v.join(" ")}`);return;case"log":this.log[I.logLevel](`${I.value}`);return;case"dump":x.emit("265",{room:e,data:I.value,type:"dump"});return}},this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.screenAudioWorkletNode.port.postMessage({type:"init",data:{sdkAppId:String(t),userId:r,timestamp:u,sign:p,status:g}}),this.screenAudioWorkletNode.port.onmessage=T=>{var v;let{data:I}=T;switch(I.type){case"cost":let b=(I==null?void 0:I.value)>20?"warn":(I==null?void 0:I.value)>10?"info":"debug";this.log[b](`[dump-screen-audio] avg cost: ${I.value} max: ${I==null?void 0:I.max}(${ns(new Date(I==null?void 0:I.maxCostTimestamp))}) hist: ${(v=I==null?void 0:I.hist)==null?void 0:v.join(" ")}`);return;case"log":this.log[I.logLevel](`[dump-screen-audio] ${I.value}`);return;case"dump":x.emit("265",{room:e,data:I.value,type:"dump-screen-audio"});return}}}this.mixNode||(this.mixNode=this.audioContext.createGain(),this.mixNode.gain.value=1),this.muteNode||(this.muteNode=this.audioContext.createConstantSource(),this.muteNode.offset.setValueAtTime(0,this.audioContext.currentTime),this.muteNode.start()),this.localAudioWorkletNode.port.postMessage({type:"enable"}),this.screenAudioWorkletNode.port.postMessage({type:"enable"}),e.audioManager.addAudioProcessor(this.localAudioWorkletNode,this.mixNode,this.muteNode,this.screenAudioWorkletNode),M(n)||n.forEach(u=>{this.customAudioReferenceMap.set(u,`o-${this.audioRefId++}`),x.emit("266",{room:this.core.room,type:"add",audioReference:u,refId:`o-${this.audioRefId++}`})}),M(a)||this.localAudioWorkletNode.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:a}}),M(d)||this.localAudioWorkletNode.port.postMessage({type:"dump",data:{enable:d}})})}update(i){return A(this,null,function*(){if(!this.localAudioWorkletNode||!this.screenAudioWorkletNode)return;let{audioReference:e,enableDump:t,processLevel:r}=i;M(e)||(this.customAudioReferenceMap.forEach((o,n)=>{this.customAudioReferenceMap.delete(n),x.emit("266",{room:this.core.room,type:"remove",refId:o})}),e.forEach(o=>{this.customAudioReferenceMap.set(o,`o-${this.audioRefId++}`),x.emit("266",{room:this.core.room,type:"add",audioReference:o,refId:`o-${this.audioRefId++}`})})),M(r)||this.localAudioWorkletNode.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:r}}),M(t)||(this.localAudioWorkletNode.port.postMessage({type:"dump",data:{enable:t}}),this.screenAudioWorkletNode.port.postMessage({type:"dump",data:{enable:t}}))})}stop(){return A(this,null,function*(){if(!this.localAudioWorkletNode||!this.mixNode||!this.muteNode||!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.muteNode,this.screenAudioWorkletNode)})}destroy(){this.localAudioWorkletNode&&(this.localAudioWorkletNode.port.onmessage=null),this.screenAudioWorkletNode&&(this.screenAudioWorkletNode.port.onmessage=null)}};c(wr,"updateValidateRule",{type:"object"}),c(wr,"stopValidateRule",{type:"object"}),c(wr,"Name","AudioProcessor");var pc=wr;function hS(s,i=S.MAIN){return`https://${tr[i]||dc(s,i)}/api/v1/audioAiAuth`}function mS(r){return A(this,arguments,function*({sdkAppId:s,userId:i,userSig:e,timestamp:t}){let n=`${hS(s)}?sdkAppId=${s}&userId=${i}&userSig=${e}×tamp=${t}`,a=yield fetch(n),{data:{errCode:d,errMsg:l,sign:h,status:u}}=yield a.json();if(u==="1")return{auth:!0,sign:h,status:u,message:l};let m=ms(s)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",p="Init RTCAudioProcessor failed.",g="";switch(d){case 1:g="Please check your params.";break;case 2:g=`You need to buy packages. Refer to: ${m}`;break;case 3:g="Server is invalid. Please contact our engineer. ";break;case 4:g=`Your packages is not active. Refer to: ${m}`;break;case 5:g=`Your packages is expired. Refer to: ${m}`;break;case 6:g="Your version is not supported.";break}return{auth:!1,status:u,message:l?`${p} Reason: ${l}. ${g}`:`${p}, ${g}`}})}var fc=0,Th=class{constructor(i,e){c(this,"player");c(this,"publisher");c(this,"mixInput");this.mixInput=new Io(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&&(M(i.volume)||(this.volume=i.volume),M(i.loop)||(this.loop=i.loop),M(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 Mo(s,i){if(i&&typeof i!="function")throw new ue({code:fe.INVALID_PARAMETER,message:`start audioMixer plugin: param ${s} should be a function.`})}var ir=class ir{constructor(i){this.core=i;c(this,"log");c(this,"mixedMusicMap",new Map);c(this,"cacheMusicMap",new Map);fc=fc+1,this.log=i.log.createChild({id:`${this.getAlias()}${fc}`}),this.log.info(`created id=${this.getAlias()}${fc}`)}getName(){return ir.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return ir.startValidateRule;case"update":return ir.updateValidateRule;case"stop":return ir.stopValidateRule}}start(i){return A(this,null,function*(){let{room:e}=this.core;this.log.info(`add music source, id: ${i.id} url: ${i.url}, track: ${i.track}`);let{id:t,url:r}=i;if(this.mixedMusicMap.has(t))return;let o=this.cacheMusicMap.get(t);o?i.url?o.reset():(o.mixInput.replaceSource(i.track),o.mixInput.connect()):(o=new Th(i,e.audioManager),this.cacheMusicMap.set(t,o)),o.updateListener(i),o.updateSettings(i),yield o.play(),this.mixedMusicMap.set(t,o),o.mixInput.source.node&&x.emit("266",{room:this.core.room,type:"add",audioReference:o.mixInput.source.node,refId:`ax-${t}`}),this.log.info(`start mix audio track ${t} success.`),Q.addEnum({key:502700,value:3}),this.kvUpload(i)})}update(i){return A(this,null,function*(){let{id:e,operation:t,seekFrom:r,playbackRate:o}=i;this.log.info(`update music source, ${JSON.stringify(i)}`);let n=this.mixedMusicMap.get(e);if(!n){this.log.warn(`update music source failed, music id: ${e} not found.`);return}n.updateSettings(i),n.updateListener(i),M(t)||n.setOperation(t),M(r)||n.seek(r),this.kvUpload(i)})}stop(e){return A(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&&x.emit("266",{room:this.core.room,type:"remove",audioReference:t.mixInput.source.node,refId:`ax-${i}`}),t==null||t.stop(),this.mixedMusicMap.delete(i)}i==="*"&&this.destroyAllMusic()})}kvUpload(i){let{track:e,loop:t,volume:r,playbackRate:o,operation:n,seekFrom:a,onTimeUpdate:d,onDurationChange:l,onEnded:h}=i;e&&Q.addCount({key:502711}),t&&Q.addCount({key:502703}),r&&Q.addCount({key:502704}),o&&Q.addCount({key:502705}),n&&Q.addCount({key:502706}),a&&Q.addCount({key:502707}),typeof d!="function"&&Q.addCount({key:502709}),typeof h!="function"&&Q.addCount({key:502710}),typeof l!="function"&&Q.addCount({key:502708})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((i,e)=>{i!=null&&i.mixInput.track&&x.emit("266",{room:this.core.room,type:"remove",audioReference:i.mixInput.track,refId:e}),this.stop({id:e})})}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}};c(ir,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(i,e,t){if(i.url&&i.url!=="*"){let r=i.url.split("?")[0],o=["mp3","ogg","wav","flac"],n=r.split(".").pop(),a=o.indexOf(n)>=0,d=r.startsWith("blob"),l=r.startsWith("data");if(!(a||d||l))throw new ue({code:fe.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new ue({code:fe.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});Mo("onTimeUpdate",i.onTimeUpdate),Mo("onEnded",i.onEnded),Mo("onDurationChange",i.onDurationChange)}}),c(ir,"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){Mo("onTimeUpdate",i.onTimeUpdate),Mo("onEnded",i.onEnded),Mo("onDurationChange",i.onDurationChange)}}),c(ir,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),c(ir,"Name","AudioMixer");var _c=ir;var gc=0,Sh,Mr=class Mr{constructor(i){this.core=i;c(this,"log");c(this,"audioContext",dt("denoiser"));c(this,"workletNode");gc=gc+1,this.log=i.log.createChild({id:`${this.getAlias()}${gc}`}),this.log.info(`created id=${this.getAlias()}${gc}`),i.assetsPath&&this.preload(`${i.assetsPath}/denoiser-wasm.js`).catch(e=>{})}static startValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,t,r,o){if(!i.room.audioManager.hasAudioTrack)throw new ue({code:fe.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return Sh||(Sh=this.doPreload(i)),Sh}doPreload(i){return A(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield Rr(this.audioContext,t)}catch(r){throw this.log.error("load worklet failed",r),r}finally{URL.revokeObjectURL(t)}})}getName(){return Mr.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(i){switch(i){case"start":return Mr.startValidateRule(this.core);case"update":return Mr.updateValidateRule;case"stop":return Mr.stopValidateRule}}start(i){return A(this,null,function*(){let{room:e,schedule:t}=this.core;if(yield this.preload(`${i.assetsPath}/denoiser-wasm.js`),!this.workletNode){let r=String(Date.now()).slice(0,-3),{auth:o,sign:n,status:a,message:d}=yield fS(t,de(Z({},i),{timestamp:r}));if(!o)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${o}. Message: ${d}`),new ue({code:fe.INVALID_PARAMETER,message:d});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(i.sdkAppId),userId:i.userId,timestamp:r,sign:n,status:a}}),this.workletNode.port.onmessage=l=>{var u;let{data:h}=l;if(h.type==="cost"){let m=(h==null?void 0:h.max)>20?"warn":(h==null?void 0:h.max)>10?"info":"debug";this.log[m](`avg cost: ${h.value} max: ${h==null?void 0:h.max}(${ns(new Date(h==null?void 0:h.maxCostTimestamp))}) hist: ${(u=h==null?void 0:h.hist)==null?void 0:u.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 A(this,null,function*(){})}stop(){return A(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)}};c(Mr,"updateValidateRule",{type:"object"}),c(Mr,"stopValidateRule",{type:"object"}),c(Mr,"Name","AIDenoiser");var Ec=Mr;function fS(o,n){return A(this,arguments,function*(s,{sdkAppId:i,userId:e,userSig:t,timestamp:r}){try{let{data:{errCode:a,errMsg:d,sign:l,status:h}}=yield s.getAbilityConfig(i,s.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:i,userId:e,userSig:t,timestamp:r});if(h==="1")return{auth:!0,sign:l,status:h,message:d};let u="Init RTCAIDenoiser failed.",m="";switch(a){case 1:m="Please check your params.";break;case 2:m="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:m="Server is invalid. Please contact our engineer. ";break;case 4:m="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:m="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:m="Your version is not supported.";break}return{auth:!1,status:h,message:d?`${u} Reason: ${d}. ${m}`:`${u}, ${m}`}}catch(a){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${a}`}}})}var Af=gt(Mt(),1);var Ih=class extends Af.EventEmitter{constructor(){super();c(this,"observer");c(this,"state","nominal");this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return A(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!ze&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){Me.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)&&z.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){Me.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},_S=new Ih,Ah=_S;function Ch([s,i]){let e=i.byteLength,t=parseInt(String(e/255),10),r=e%255,o=[];o.push(0,0,0,1,6,s);for(let a=0;a<t;a++)o.push(255);o.push(r);let n=new DataView(i);return o.push(...new Uint8Array(n.buffer)),o.push(128),new vr(new DataView(new Uint8Array(o).buffer),!0)}function Rh(s){return s.type==="empty"||s.data.byteLength===0}function yh(s){return s.getInt32(0)===1&&s.getInt8(4)===6}function bh(s){let i=0,e=0,t=new DataView(s);for(let r=0;r<s.byteLength;r++)switch(t.getUint8(r)){case 0:i++;break;case 1:(i===2||i===3)&&e++,i=0;break;default:i=0;break}return e}function vh({frame:s,seiMessageList:i}){if(!i||i.length===0||s.data.byteLength===0)return s;let t=9-bh(s.data);if(t<=0)return s;let r=i.splice(0,t).reverse().map(Ch),o=r.reduce((h,u)=>h+u.dataView.byteLength,0),n=new ArrayBuffer(o+s.data.byteLength),a=new DataView(n),d=new DataView(s.data),l=0;for(let h=0;h<r.length;h++)for(let u=0;u<r[h].dataView.byteLength;u++)a.setInt8(l++,r[h].dataView.getInt8(u));for(let h=0;h<s.data.byteLength;h++)a.setInt8(l++,d.getInt8(h));return s.data=n,s}function Nh({frame:s,onSEI:i}){try{let e=new DataView(s.data);if(Rh(s)||!yh(e))return s;let t=[],r=0,o=-1,n=-1;for(let a=0;a<s.data.byteLength;a++){let d=e.getUint8(a);if(d===0)r++;else if(d===1){if(r===2||r===3){let l=a-r;if(o===-1?o=l:n===-1&&(n=l,t.push(new vr(new DataView(e.buffer.slice(o,n)))),o=l,n=-1),!(e.getUint8(a+1)===6)){s.data=e.buffer.slice(l);break}}r=0}else r=0}i==null||i(t.reverse())}catch(e){}return s}var Dh=0,sa=class sa{constructor(i){this.core=i;c(this,"log");c(this,"_seiMessageList",[]);c(this,"_smallSeiMessageList",[]);c(this,"_subStreamSeiMessageList",[]);Dh++,this.log=i.log.createChild({id:`${this.getAlias()}${Dh}`}),this.log.info(`[sei] created id=${this.getAlias()}${Dh}`),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 vh({frame:i,seiMessageList:t})}catch(t){this.log.warn(t)}return i}decode({frame:i,track:e}){return Nh({frame:i,onSEI:t=>{t.forEach(r=>{this.core.trtc.emit(ne.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:Ar?this.encode:vh,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:Ar?this.decode:Nh,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update({buffer:i,options:e}){var o;let t=[e.seiPayloadType,i],r=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(t):(this._seiMessageList.push(t),r&&this._smallSeiMessageList.push(t)),(o=this.core.room.scriptTransformWorker)==null||o.postMessage({type:"sei",data:t,isMain:!e.toSubStream,small:r})}getName(){return sa.Name}getAlias(){return"sei"}getGroup(){return"sei"}};c(sa,"autoStart",!0),c(sa,"Name","SEI");var Tc=sa;function kh({frame:s,onDump:i}){return i==null||i(),s}function Oh({frame:s,onDump:i}){return i==null||i(),s}var Cf=()=>{let s=window.navigator&&window.navigator.userAgent||"",i=/iPad/i.test(s)||/iPhone/i.test(s),e=/Android/i.test(s);return i||e},Re={LOG_BUTTON:"Log",NETWORK_BUTTON:"Network",DUMP_BUTTON:"Dump",DUMPING_BUTTON:"Dumping",END_BUTTON:"End",UPLOAD_BUTTON:"Upload Log",EXPORT_BUTTON:"Export Log",HIDE_BUTTON:"Hide",GO_BOTTOM:"goBottom",BACK_TOP:"backTop",CLEAR_LOG:"Clear Log",UPLINK:"Uplink",DOWNLINK:"Downlink",NO_DATA:"No Data",BASIC:"Basic",DURATION:"Duration",VIDEO:"Video",AUDIO:"Audio",SCREEN:"Screen"},Rf=s=>s.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d").replace(">",">").replace(">","<"),ss={"play() error: NotAllowedError:":{tips:s=>s.includes("main <video>")||s.includes("main <audio>")?"Remote stream auto play is restricted and playback fails":"Local stream playback failure, generally only occurs in Android WeChat devices, no need to handle",color:"red",class:"red"},"updateStream() try to recover local stream":{tips:"Device acquisition exception, automatic recovery is in progress"},"updateStream() recover local stream successfully":{tips:"Device acquisition exception, automatic recovery is successful"},"updateStream() failed to recover local stream":{tips:"Device acquisition exception, automatic recovery failed"},"main stream - video track is muted":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is muted":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is muted":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unable to provide media output":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is unable to provide media output":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is unable to provide media output":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unmuted":{tips:"Received enough playback video data"},"main stream - audio track is unmuted":{tips:"Received enough playback audio data"},"auxiliary stream - video track is unmuted":{tips:"Received enough playback screen sharing data"},"main stream - audio player track is ended":{tips:"Remote audio track stopped"},"main stream - video player track is ended":{tips:"Remote video track stopped"},"auxiliary stream - video player track is ended":{tips:"Received enough playback screen sharing data"},"stream - video track is muted":{tips:"Camera capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"stream - video track is unable to provide media output":{tips:"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked, and the customer needs to re-acquire. SDK v4.11.4+ will automatically resume acquisition without customer intervention",color:"orange"},"video track is unable to provide media output":{tips:s=>s.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"stream - audio track is muted":{tips:"Microphone capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"audio track is unable to provide media output":{tips:s=>s.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"Microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio track is unable to provide media output":{tips:"The microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"is adding audio track to current published local stream":{tips:"add audio track",color:"orange"},"is removing audio track from current published local stream":{tips:"remove audio track",color:"orange"},"is removing video track from current published local stream":{tips:"remove video track",color:"orange"},"is adding video track to current published local stream":{tips:"add video track",color:"orange"},"is replacing audio track to current published local main stream":{tips:"replace audio track",color:"orange"},"is replacing video track to current published local main stream":{tips:"replace video track",color:"orange"},"downlink network quality change":{tips:"Downstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"uplink network quality change":{tips:"Upstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"localStream mute video":{tips:"mute upstream video stream",color:"orange"},"localStream unmute video":{tips:"unmute upstream video stream",color:"orange"},"localStream mute audio":{tips:"mute upstream audio stream",color:"orange"},"localStream unmute audio":{tips:"unmute upstream audio stream",color:"orange"},"black detected":{tips:"Detect black screen, which means fps = 0. It is usually caused by network, and the network will be recovered after a while. If the network is normal but has not been restored, it is an abnormal situation."},'main stream start to play with options: {"muted":true}':{tips:"Play the remote stream in silent mode. Generally, the remote stream does not need to be played in silent mode. You need to confirm whether the parameters passed in the client stream.play API call are correct.",color:"orange"},"main stream - audio player is starting playing":{tips:"Remote stream audio playback success",color:"#0dd90d",class:"success"},"main stream - video player is starting playing":{tips:"Remote stream video playback success",color:"#0dd90d",class:"success"},"video player is playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"audio player is playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"stream - video player is starting playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"stream - audio player is starting playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"switch camera success":{tips:"Switch camera success",color:"#0dd90d",class:"success"},"switch microphone success":{tips:"Switch microphone success",color:"#0dd90d",class:"success"},gotStream:{tips:"Local stream capture success"},"local stream is published successfully":{tips:"Publish success",color:"#0dd90d",class:"success"},"encoderImplementation change to OpenH264":{tips:"Use software encoding"},"encoderImplementation change to ExternalEncoder":{tips:"Use hardware encoding"},"getUserMedia with constraints":{tips:"Start media (camera/microphone) capture"},"getDisplayMedia with constraints":{tips:"Start screen sharing capture"},"client-banned":{tips:"Kicked out of the room",color:"red",class:"red",textColor:"#fff"},user_timeout:{tips:"The backend is too long without receiving SDK heartbeat, which is usually caused by the JS thread being blocked for a long time. If the reproduction probability is high, the application browser Performance tool analyzes where the JS thread is blocked.",color:"red",class:"red",textColor:"#fff"},"schedule failed":{tips:"Signaling request failed, does not affect the normal room entry process, SDK will connect to the default signaling domain."},"updateStream() video flag is true, but no camera detected, set video to false":{tips:"When trying to resume camera acquisition, the camera acquisition is not resumed because it is detected that there is no camera.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to bandwidth":{tips:"bandwidth estimation is not enough to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to cpu":{tips:"cpu load is too high to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: hidden":{tips:"User page switched to backend, in mobile devices, this will cause the device to pause the capture, and it will be restored when the user switches backend to the frontend.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: visible":{tips:"User page switched to frontend",color:"orange",class:"orange",textColor:"#fff"},"main stream - audio player is paused":{tips:`The remote stream audio playback is paused, which usually has two possibilities:
|
|
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.
|
|
@@ -70,7 +70,7 @@ ${r.stack}`),!1}},s};var wo=new WeakMap;function Sf(s){let i=wo.get(s);i&&(i.for
|
|
|
70
70
|
<span class="tooltiptext tooltip-top">${n}</span>
|
|
71
71
|
</span>`)}}),i.innerHTML=r}getCurrentTime(){let i=new Date,e=this.pad(i.getHours()),t=this.pad(i.getMinutes()),r=this.pad(i.getSeconds());return`${e}:${t}:${r}`}dumpVideo(i,e,t,r){let o=Date.now(),n=this.formatStartDumpTime(o),a=[],d=`${e}_${r}_${i}`,l=()=>{if(a.length===0){this.addInfoToBanner(Po,`[${d}] dump failed. Reason: data is empty`);return}let u;i==="main"?u="video":i==="auxiliary"&&(u="screen");let m=URL.createObjectURL(new Blob(a)),p=document.createElement("a"),g=e==="local"?`local_${u}_${n}.h264`:`remote-${r}_${u}_${n}.h264`;p.href=m,p.download=g,p.style.display="none",document.body.appendChild(p),p.click(),URL.revokeObjectURL(m),p.remove(),this.addInfoToBanner(xr,`[${d}] dump success. File name is: ${g}`)},h;if(e==="local"){if(!this.hasLocalTrack(i,"video"))return{};h=()=>{delete this.dumpLocalVideoMap[i==="auxiliary"?"sub":"main"]},this.dumpLocalVideoMap[i==="auxiliary"?"sub":"main"]={startTimestamp:o,data:a,duration:t,onDumpEnd:h}}if(e==="remote"&&r){if(h=()=>{delete this.dumpRemoteVideoMap[`${r}-${i}`]},this.dumpRemoteVideoMap[`${r}-${i}`])return this.addInfoToBanner(wf,`[${d}] dump already exists.`),{};this.dumpRemoteVideoMap[`${r}-${i}`]={startTimestamp:o,data:a,duration:t,onDumpEnd:h}}return{download:l,onDumpEnd:h}}hasLocalTrack(i,e){for(let t of this._core.room.localTracks)if(t.streamType===i&&t.kind===e)return!0;return!1}dumpAudio(i,e,t){var q,$,te;let r=null,o=[],n=[],a=[],d=[],l=[],h=[],u=[],m=new AbortController,p=Date.now(),g=this.formatStartDumpTime(p),f=this._core.room.audioManager._localAudioPipline,T=this._core.room.audioManager._localScreenAudioPipeline,I,v,b=({data:se})=>{a[0]=a[0]?a[0].concat(se):[se]},w=({room:se,data:y,type:G})=>{if(this.hitTest(se)){if(G==="dump"){if(d[0]=d[0]?d[0].concat(y.captureInput):y.captureInput,d[1]=d[1]?d[1].concat(y.playInput):y.playInput,!I)I=y.startTime,v=y.startTime;else{let j=y.startTime-I,Ce=y.endTime-y.startTime;if(j>30||Ce>30){let ee=function(he){if(typeof he!="number"||he<0)return"0\u6BEB\u79D2";let V=[],P=Math.floor(he/6e4),_e=he%6e4;P>0&&V.push(`${P}\u5206`);let ae=Math.floor(_e/1e3);return _e%=1e3,(ae>0||V.length)&&V.push(`${ae}\u79D2`),(_e>0||!V.length)&&V.push(`${_e}\u6BEB\u79D2`),V.join("")};var E=ee;let O=y.startTime-v,Ne=I-v;u.push(`${y.startTime} ${ee(O)}~${ee(Ne)} ${j} ${Ce}`)}I=y.startTime}h.push(y.startTime)}G==="dump-screen-audio"&&(l[0]=l[0]?l[0].concat(y.captureInput):y.captureInput,l[1]=l[1]?l[1].concat(y.playInput):y.playInput)}};if(i==="local"){let{sampleRate:se}=this._core.room.audioManager.audioContext;if(!this._core.room.audioManager.hasAudioTrack&&!this._core.room.audioManager.hasScreenAudioTrack)return{};if(f!=null&&f.source.node&&(o.push(f.source.node),n.push(`local_audio_raw_capture-${se}-${f.source.node.channelCount}`)),((q=f==null?void 0:f.audioProcessor)!=null&&q.node||T!=null&&T.audioProcessor.node)&&(this._core.trtc.updatePlugin("AudioProcessor",{enableDump:!0}),this._core.innerEmitter.on("265",w),($=f==null?void 0:f.audioProcessor)!=null&&$.node&&(o.push(f.audioProcessor.node),n.push(`local_audio_audioProcessor_processed-${se}-${f.audioProcessor.node.channelCount}`)),T!=null&&T.audioProcessor.node&&(o.push(T.audioProcessor.node),n.push(`screen_audio_audioProcessor_processed-${se}-${T.audioProcessor.node.channelCount}`))),f!=null&&f.denoiser.node&&(o.push(f.denoiser.node),n.push(`local_audio_denoiser_processed-${se}-${f.denoiser.node.channelCount}`)),this._core.room.audioManager.mixWeight>1&&(f!=null&&f.stream)){let y=this._core.room.audioManager.audioContext.createMediaStreamSource(f.stream);y.channelCount=1,o.push(y),n.push(`local_audio_destination-${se}-${y.channelCount}`)}}else if(i==="remote"&&t!==void 0){let se=(te=this._core.room.remotePublishedUserMap.get(t))==null?void 0:te.remoteAudioTrack;if(!(se!=null&&se.mediaTrack))return{};let y=this._core.createAudioNode(se.mediaTrack);o.push(y),n.push(`remote_${t}`)}let N=()=>A(this,null,function*(){var j,Ce,O,Ne,ee;let se=new Mf.default;for(let he=0;he<n.length;he++)se.file(`${n[he]}.pcm`,new Blob(a[he]));if((j=d==null?void 0:d[0])!=null&&j.length&&se.file("audioProcessor_input_capture.pcm",new Blob(d[0])),(Ce=d==null?void 0:d[1])!=null&&Ce.length&&se.file("audioProcessor_input_playback.pcm",new Blob(d[1])),(O=l==null?void 0:l[0])!=null&&O.length&&se.file("audioProcessor_screen_audio_input_capture.pcm",new Blob(l[0])),(Ne=l==null?void 0:l[1])!=null&&Ne.length&&se.file("audioProcessor_screen_audio_input_playback.pcm",new Blob(l[1])),h!=null&&h.length){let he=h.reduce((V,P)=>`${V}
|
|
72
72
|
${P}`);se.file("audioProcessor_handle_timestamp.txt",new Blob([he]))}if(u!=null&&u.length){let he=u.reduce((V,P)=>`${V}
|
|
73
|
-
${P}`);se.file("audioProcessor_big_gap_data.txt",new Blob([he]))}let y=yield se.generateAsync({type:"blob"}),G=URL.createObjectURL(y),E=document.createElement("a");E.href=G,E.download=`${i}-audio-${g}.zip`,E.style.display="none",document.body.appendChild(E),E.click(),URL.revokeObjectURL(G),E.remove(),this.addInfoToBanner(xr,`Dump success, file name is: ${i}-${g}.zip`),this._core.trtc.off(ne.AUDIO_FRAME,b),this._core.innerEmitter.off("265",w),((ee=f==null?void 0:f.audioProcessor)!=null&&ee.node||T!=null&&T.audioProcessor.node)&&this._core.trtc.updatePlugin("AudioProcessor",{enableDump:!1}),r&&clearTimeout(r),m.abort("download")});return e>0&&(r=Number(setTimeout(()=>{m.abort("timeout")},e*1e3))),o.length>0&&this._core.startGetPCM(o).then(se=>se.pipeTo(new WritableStream({write(y){y.forEach((G,E)=>{a[E]=a[E]?a[E].concat(G[0]):[G[0]]})}}),m).catch(()=>N)),{download:N,onDumpEnd:()=>{m.abort("timeout")}}}formatStartDumpTime(i){let e=new Date(i),t=e.getFullYear(),r=this.pad(e.getMonth()+1),o=this.pad(e.getDate()),n=this.pad(e.getHours()),a=this.pad(e.getMinutes()),d=this.pad(e.getSeconds()),l=-e.getTimezoneOffset(),h=Math.floor(Math.abs(l)/60),u=Math.abs(l)%60,m=l>=0?"+":"-";return`${t}-${r}-${o}T${n}-${a}-${d}${m}${this.pad(h)}-${this.pad(u)}`}};J([ra(300,()=>"export")],da.prototype,"onExportClick",1),J([ra(300,()=>"upload")],da.prototype,"onUploadClick",1);var Ff=da;var gS=0;var Uo=class Uo{constructor(i){this.core=i;c(this,"_core");c(this,"log");c(this,"dumpLocalVideoMap",{});c(this,"dumpRemoteVideoMap",{});c(this,"dialog");this._core=i,this.log=i.log.createChild({id:`${this.getAlias()}${++gS}`}),this.log.info("created")}getName(){return Uo.Name}getAlias(){return"dm"}getGroup(){return"dm"}getValidateRule(i){switch(i){case"start":return{name:"StartDebugOptions",required:!1};case"update":return{name:"UpdateDebugOptions",required:!1};case"stop":return{name:"StopDebugOptions",required:!1}}}start(){return A(this,null,function*(){var e;!new URLSearchParams(location.search).has("trtcDebug")&&((e=window.sessionStorage)==null?void 0:e.getItem("TRTC_ENABLE_DEBUG_PLUGIN"))!=="true"||(yield this.openDebugDiaLog(),this.addVideoProcessor())})}update(e){return A(this,arguments,function*({forceOpen:i}){M(i)&&(i?(yield this.openDebugDiaLog(),this.addVideoProcessor()):(this.closeDebugDiaLog(),this.removeVideoProcessor()))})}stop(){this.closeDebugDiaLog(),this.removeVideoProcessor()}destroy(){this.stop()}openDebugDiaLog(){return A(this,null,function*(){if(!this.dialog)try{this.dialog=new Ff(this._core,this.log,this.dumpLocalVideoMap,this.dumpRemoteVideoMap),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(i){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(i))}})}closeDebugDiaLog(){this.dialog&&(this.dialog.closeDialog(),this.dialog=null)}addVideoProcessor(){this._core.room.videoManager.addEncodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.encodeVideo.bind(this):kh,type:1}),this._core.room.videoManager.addDecodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.decodeVideo.bind(this):Oh,type:1})}removeVideoProcessor(){this._core.room.videoManager.removeEncodeProcessor({type:1}),this._core.room.videoManager.removeDecodeProcessor({type:1})}encodeVideo({frame:i,mediaType:e}){return kh({frame:i,onDump:()=>{if(!e)return;let t=e===2?"sub":"main",r=this.dumpLocalVideoMap[t];r&&(r.data.push(i.data.slice(0)),r.duration>0&&Date.now()-r.startTimestamp>r.duration*1e3&&r.onDumpEnd())}})}decodeVideo({frame:i,track:e}){return Oh({frame:i,onDump:()=>{if(!e)return;let t=this.dumpRemoteVideoMap[`${e.userId}-${e.streamType}`];t&&(t.data.push(i.data.slice(0)),t.duration>0&&Date.now()-t.startTimestamp>t.duration*1e3&&t.onDumpEnd())}})}loadScript(i){return new Promise((e,t)=>{this.log.info(`loading debug dialog from ${i}`);let r=document.createElement("script");r.type="text/javascript",r.onload=e,r.onerror=t,r.crossOrigin="anonymous",r.src=i,document.head.append?document.head.append(r):document.getElementsByTagName("head")[0].appendChild(r)})}};c(Uo,"Name","Debug"),c(Uo,"autoStart",!0),J([Gt({settings:{timeout:3e3,retries:3},onError(i,e,t){var r;(r=i==null?void 0:i.message)!=null&&r.includes("timeout")?e():t(i)}})],Uo.prototype,"loadScript",1);var kc=Uo;var Hf=s=>{switch(s){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},Oc=class{constructor(i,e,t){c(this,"trackDoneOB");c(this,"startOB");c(this,"stopOB");c(this,"inputFrameCount",0);c(this,"decodedFrameCount",0);c(this,"type","auto");c(this,"config");c(this,"decoder");c(this,"_decodeSink");let{kvStatManager:r,trtc:o}=i;this.config=t.config,this.trackDoneOB=We(e,ge.INIT),this.stopOB=Vt(),this.startOB=Vt(),t.type==="auto"?this.type="webCodecs":this.type=t.type;let n=Vt(),a=d=>{let l=this.pipe(e);return n.next("STARTING"),e.log.info(`decoder type: ${this.type}`),He(l,St(this.stopOB),it(()=>{},h=>{e.log.error(h),r.addFailedEvent({key:Hf(this.type),error:h}),d>4?this.startOB.error(h):this.startOB.next(d+1)})),He(l,Dr(1),sh(Yn))};He(this.startOB,Xn(0),yo(a),St(this.stopOB),it(()=>{e.player.setOutput(),n.next("STARTED")},d=>{n.next("FAILED")},()=>{r.addSuccessEvent({key:Hf(this.type)}),r.addSuccessEvent({key:504702})}))}mock(i){this._decodeSink?this._decodeSink.error(i):this.startOB.next(0)}close(i){this.stopOB.next(i)}pipe(i){return Nr()(e=>A(this,null,function*(){this._decodeSink=e,e.defer(()=>{var r;(r=this.decoder)==null||r.close()});let{type:t}=this;try{switch(t){case"webCodecs":this.decoder=new AudioDecoder({error:r=>{i.log.error(r),e.error(4)},output:r=>{this.decodedFrameCount++,e.next(r),i.player.write(r)}});break;case"wasm":break}this.decoder.configure(this.config)}catch(r){i.log.error(r),e.error(t==="webCodecs"?2:6)}}))}decodeFrame(i){var e;this.inputFrameCount++,((e=this.decoder)==null?void 0:e.state)==="configured"&&this.decoder.decode(new EncodedAudioChunk({data:i.data,timestamp:i.timestamp,type:"key"}))}},ES={type:"object"},la=class la{constructor(i){this.core=i;c(this,"log");c(this,"contextMap",new Map);c(this,"decodeProcessorMap",new WeakMap);this.log=i.log.createChild({id:`${this.getAlias()}`})}getAlias(){return la.Name}getGroup(i){return i.track.userId+i.track.streamType}getName(){return la.Name}getValidateRule(i){return ES}start(i){let{track:e}=i;this.decodeProcessorMap.set(e,this.decode(i)),this.core.room.audioManager.addDecodeProcessor({processor:({frame:t,track:r})=>this.decodeProcessorMap.has(r)?this.decodeProcessorMap.get(r)({frame:t,track:r}):t,type:3})}decode(i){return({frame:e,track:t})=>{if(t!==i.track)return e;if(this.contextMap.has(t))return this.contextMap.get(t).decodeFrame(e);let r=new Oc(this.core,t,i);return He(r.trackDoneOB,Dr(1),it(()=>{this.core.clearStarted(this,this.getGroup(i)),this.stop({track:t})})),this.contextMap.set(t,r),r.decodeFrame(e)}}stop({track:i}){let e=this.contextMap.get(i);e&&(e.close("stop"),this.contextMap.delete(i),this.contextMap.size===0&&this.core.room.audioManager.removeDecodeProcessor({type:3}))}update(i){let e=this.contextMap.get(i.track);if(e){if(i.type==="mock"){e.mock(10);return}e.close("update"),this.contextMap.set(i.track,new Oc(this.core,i.track,i))}}};c(la,"Name","TRTCAudioDecoder");var ua=la;var Gf=0,ha=new Set,At=null;Zc(If);po.checkStorage();nu();var TS={RtcError:ue,ErrorCode:fe,ErrorCodeDictionary:Ri},Ie=class Ie extends Wf.EventEmitter{constructor(e,t){super();c(this,"_room");c(this,"_eventListened",new Set);c(this,"_localVideoTrack",null);c(this,"_localAudioTrack",null);c(this,"_localScreenTrack",null);c(this,"_localScreenAudioTrack",null);c(this,"_localVideoConfig",null);c(this,"_localScreenConfig",null);c(this,"_localAudioConfig",null);c(this,"_remoteVideoConfigMap",new Map);c(this,"_remoteAudioConfigMap",new Map);c(this,"_remoteAudioVolumeMap",new Map);c(this,"_remoteAudioMuteMap",new Map);c(this,"_mediaTrackMap",new WeakMap);c(this,"_log",z.createLogger({id:`t${++Gf}`}));c(this,"_plugins",new Map);c(this,"_networkQuality",null);c(this,"_speakerId");c(this,"_getPCMAbortCtrl");this._room=new e(Z({logger:this._log,frameWorkType:Ie.frameWorkType},t)),this._room.videoDecodeFallbackType=t.videoDecodeFallback,this._log.info(`create() ${JSON.stringify(t,(r,o)=>r==="plugins"?o.map(n=>n.Name):o)}`),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(r){return this._room.audioManager.dump(r)}}}),t.plugins&&t.plugins.forEach(r=>{this._use(r,t.assetsPath)}),this._use(_c,t.assetsPath),this._use(pc,t.assetsPath),this._use(Ec,t.assetsPath),this._use(ua,t.assetsPath||ba),this._use(kc),t.enableSEI&&xn&&this._use(Tc),this._room.on("audio-volume",r=>{!r.find(o=>o.userId==="")&&this._localAudioTrack&&r.push({userId:"",volume:Math.floor(this._localAudioTrack.getAudioLevel()*100)}),t.volumeType===1&&r.forEach(o=>{var a;let n=o.userId===""?this._localAudioTrack:(a=this.room.remotePublishedUserMap.get(o.userId))==null?void 0:a.remoteAudioTrack;n&&(o.volume=n.dbVolume)}),this.emit(ne.AUDIO_VOLUME,{result:r.sort((o,n)=>n.volume-o.volume)})}),this._room.videoManager.on("error",r=>{this._log.error(new ue({code:fe.OPERATION_FAILED,extraCode:5504,message:r.message,originError:r}))}),this._listenEvents(),this._initActiveSpeaker(),Tf(this,"trtc")}static create(e){}static _create(e,t){nf();let r=new Ie(e,t||{});return ha.add(r),r}get room(){return this._room}_listenEvents(){vt(this,this._room).add("peer-join",e=>{let{userId:t}=e;this.emit(ne.REMOTE_USER_ENTER,{userId:t})}).add("peer-leave",e=>{this.emit(ne.REMOTE_USER_EXIT,{userId:e}),this._remoteAudioVolumeMap.delete(e)}).add("banned",e=>{this._exitRoom().finally(()=>{this.emit(ne.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().finally(()=>{this.emit(ne.ERROR,ue.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(ne.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let t=de(Z({},e),{uplinkRTT:Math.min(e.uplinkRTT,an),downlinkRTT:Math.min(e.downlinkRTT,an)});this.emit(ne.NETWORK_QUALITY,t)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(r=>{vt(r,r).add("player-state-changed",o=>{let n=de(Z({},o),{userId:e.userId});r.kind===S.VIDEO&&(n.streamType=is(r.streamType)),this.emit(r.kind===S.AUDIO?ne.AUDIO_PLAY_STATE_CHANGED:ne.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",o=>{o.getCode()===H.PLAY_NOT_ALLOWED&&this.emit(ne.AUTOPLAY_FAILED,{userId:r.userId,resume:()=>r.player.resume()})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(r=>{at(r)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:t})=>{let{userId:r}=t,o=e.audioAvailable,n=e.videoAvailable,{audioAvailable:a,videoAvailable:d}=t;a||this._remoteAudioConfigMap.delete(r),d||this._removeRemoteVideoConfig(r,"main"),t.hasAuxiliary||this._removeRemoteVideoConfig(r,"sub"),n!==d&&(d?this._onVideoAvailable({userId:r,streamType:"main"}):this._onVideoUnavailable({userId:r,streamType:"main"}),this.emit(d?ne.REMOTE_VIDEO_AVAILABLE:ne.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"main"})),o!==a&&(a?this._onAudioAvailable({userId:r}):this._onAudioUnavailable({userId:r,muteState:t}),this.emit(a?ne.REMOTE_AUDIO_AVAILABLE:ne.REMOTE_AUDIO_UNAVAILABLE,{userId:r})),e.hasAuxiliary!==t.hasAuxiliary&&(t.hasAuxiliary?this._onVideoAvailable({userId:r,streamType:"sub"}):this._onVideoUnavailable({userId:r,streamType:"sub"}),this.emit(t.hasAuxiliary?ne.REMOTE_VIDEO_AVAILABLE:ne.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"sub"}))}).add("sei-message",e=>{this.emit(ne.SEI_MESSAGE,de(Z({},e),{streamType:is(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(ne.ERROR,new ue({code:fe.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var o,n,a,d,l,h,u;let t={2:"big",3:"small",7:"sub"},r={rtt:Math.min(e.msg_up_stream_info.msg_network_status.uint32_rtt||((o=e.msg_down_stream_info[0])==null?void 0:o.msg_network_status.uint32_rtt)||((n=this._networkQuality)==null?void 0:n.uplinkRTT)||((a=this._networkQuality)==null?void 0:a.downlinkRTT)||0,an),upLoss:((d=this._networkQuality)==null?void 0:d.uplinkLoss)||0,downLoss:((l=this._networkQuality)==null?void 0:l.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((h=e.msg_up_stream_info.msg_audio_status)==null?void 0:h.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((u=e.msg_up_stream_info.msg_audio_status)==null?void 0:u.uint32_audio_level)||0)/ai},video:e.msg_up_stream_info.msg_video_status.filter(m=>t[m.uint32_video_stream_type]).map(m=>({bitrate:(m.uint32_video_codec_bitrate||0)/1e3,width:m.uint32_video_width,height:m.uint32_video_height,frameRate:m.uint32_video_enc_fps,videoType:t[m.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(m=>({userId:m.msg_user_info.str_identifier,audio:{bitrate:(m.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(m.msg_audio_status.uint32_audio_level||0)/ai},video:m.msg_video_status.map(p=>({bitrate:(p.uint32_video_codec_bitrate||0)/1e3,width:p.uint32_video_width,height:p.uint32_video_height,frameRate:p.uint32_video_dec_fps,videoType:t[p.uint32_video_stream_type]}))}))};this.emit(ne.STATISTICS,r)}).add("custom-message",e=>{this.emit(ne.CUSTOM_MESSAGE,e)}).add("layerData",e=>this.emit(ne.LAYER_DATA,e)).add("first-video-frame",e=>{this.emit(ne.FIRST_VIDEO_FRAME,de(Z({},e),{streamType:is(e.streamType)}))}),vt(this,ft).add("audioInputAdded",e=>{this.emit(ne.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(ne.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(ne.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(ne.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>A(this,null,function*(){if(this.emit(ne.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),At&&At.deviceId===nn){let t=(yield Yr()).find(r=>r.deviceId===nn);t&&At.groupId!==t.groupId&&(At=t,this.emit(ne.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}})).add("audioOutputRemoved",e=>A(this,null,function*(){this.emit(ne.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield Yr())[0];if(!t||!At||At.groupId===t.groupId)return;let r=At.deviceId===e.deviceId,o=At.deviceId===nn&&At.deviceId===t.deviceId;(r||o)&&(At=t,this.emit(ne.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}))}use(e){let t,r;"plugin"in e?(t=e.plugin,r=e.assetsPath):t=e,this._use(t,r||ba)}_use(e,t){if(this._plugins.get(e.Name)){this._log.warn("duplicate install plugin",e.Name);return}let o=new e(Ef.call(this,{TRTC:Ie,room:this._room,errorModule:TS,assetsPath:t}));this._plugins.set(e.Name,o),e.autoStart&&this.startPlugin(e.Name)}enterRoom(e){return A(this,null,function*(){var d,l;let{scene:t="rtc",enableAutoPlayDialog:r=!0,autoReceiveAudio:o=!0,autoReceiveVideo:n=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!Oe(e.proxy)&&e.proxy.turnServer&&((l=(d=this._room).setTurnServer)==null||l.call(d,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=r,this._room.autoReceiveAudio=o,this._room.autoReceiveVideo=n,Qe(e.preferHW)&&(this._room.preferHW=e.preferHW),e.playoutDelay&&(this._room.playoutDelay=e.playoutDelay),e.jitterBufferDelay&&(this._room.jitterBufferDelay=e.jitterBufferDelay);let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:e.role==="audience"?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language,priority:e.priority,useVp8:e.useVp8,keepAlive:e.keepAlive};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(a,t,Ie.frameWorkType),this._checkTrackToPublish(),Ah.start()})}exitRoom(){return A(this,null,function*(){return yield this._exitRoom()})}switchRole(e,t){return A(this,null,function*(){t!=null&&t.privateMapKey&&(this._room.privateMapKey=t.privateMapKey),t!=null&&t.latencyLevel&&(this._room.latencyLevel=t.latencyLevel),yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){at(this),this.removeAllListeners(),this._room.destroy(),ha.delete(this),ha.size===0&&Ah.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),this._plugins.forEach(e=>{var t;return(t=e.destroy)==null?void 0:t.call(e)}),this._plugins.clear(),x.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return A(this,arguments,function*(e={publish:!0}){if(this._localAudioTrack){this._log.warn("local audio is already started");return}let{publish:t=!0,mute:r,option:o}=e,n=new ti(this._room.audioManager),a={},d={muted:!0};o&&(M(o.microphoneId)?M(o.audioTrack)||(a.customSource=o.audioTrack):a.deviceId=o.microphoneId,o&&De(o.captureVolume)&&n.setCaptureVolume(o.captureVolume),M(o.profile)||(Oe(o.profile)?Da[o.profile]&&n.setProfile(Da[o.profile]):n.setProfile(o.profile)),De(o.earMonitorVolume)&&(d.muted=!(o.earMonitorVolume>0),d.volume=o.earMonitorVolume),M(o.echoCancellation)||(n.profile.echoCancellation=o.echoCancellation),M(o.noiseSuppression)||(n.profile.noiseSuppression=o.noiseSuppression),M(o.autoGainControl)||(n.profile.autoGainControl=o.autoGainControl)),n.on("5",l=>{this.emit(ne.ERROR,new ue({code:fe.DEVICE_ERROR,extraCode:5309,messageParams:{error:l}}))}),n.on("2",l=>{this.emit(ne.DEVICE_CHANGED,{type:"microphone",action:"active",device:l})}),n.on("4",l=>{let h;l.error&&(h=ue.convertFrom(l.error)),this.emit(ne.PUBLISH_STATE_CHANGED,de(Z({},l),{error:h}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId),yield n.capture(a),M(r)||n.setMute(r),vt(n,n).add("player-state-changed",l=>{this.emit(ne.AUDIO_PLAY_STATE_CHANGED,de(Z({},l),{userId:""}))}),this.listeners(ne.AUDIO_FRAME).length>0&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM(l=>{this.emit(Ie.EVENT.AUDIO_FRAME,{data:l})})),this._getPCMAbortCtrl&&n.on("input-media-track-changed",()=>{this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("inputMediaTrackChanged"),this._getPCMAbortCtrl=this._room.audioManager.getPCM(l=>{this.emit(Ie.EVENT.AUDIO_FRAME,{data:l})}))}),t&&this._room.isJoined&&this._room.publish(n).catch(()=>{}),this._localAudioTrack=n,this._localAudioConfig=de(Z({},e),{publish:t}),yield this._updateAudioPlayOption({playOption:d,track:n})})}updateLocalAudio(e){return A(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:r,option:o}=e,n={};o&&(o.microphoneId?yield this._localAudioTrack.switchDevice(o.microphoneId):M(o.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(o.audioTrack)),M(o.captureVolume)||this._localAudioTrack.setCaptureVolume(o.captureVolume),M(o.earMonitorVolume)||(n.muted=!(o.earMonitorVolume>0),n.volume=o.earMonitorVolume),yield this._localAudioTrack.update3A(o)),this._room.isJoined&&!M(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),M(r)||this._localAudioTrack.setMute(r),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),Li(this._localAudioConfig,e)})}stopLocalAudio(){return A(this,null,function*(){this._localAudioTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),at(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null,this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("stopLocalAudio"),delete this._getPCMAbortCtrl))})}startLocalVideo(){return A(this,arguments,function*(e={publish:!0,view:null}){if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:t,publish:r=!0,mute:o,option:n}=e,a=new Nt(this._room.videoManager),d={},l={};Qe(n==null?void 0:n.avoidCropping)&&(a.avoidCropping=n.avoidCropping),n&&(n.cameraId?d.deviceId=n.cameraId:M(n.useFrontCamera)?M(n.videoTrack)||(d.customSource=n.videoTrack):d.facingMode=n.useFrontCamera?S.FACING_MODE_USER:S.FACING_MODE_ENVIRONMENT,n.qosPreference&&(d.contentHint=ia(n.qosPreference)),M(n.profile)||(Oe(n.profile)?si[n.profile]&&a.setProfile(si[n.profile]):a.setProfile(n.profile)),M(n.fillMode)||(l.objectFit=n.fillMode),M(n.mirror)||(l.mirror=n.mirror),M(n.small)||(On()?Oe(n.small)?a.small=si[n.small]:n.small===!0?a.small=si["120p"]:a.small=n.small:this._log.warn("small stream is not supported"))),a.once("first-video-frame",h=>{this.emit(ne.FIRST_VIDEO_FRAME,de(Z({},h),{streamType:is(h.streamType)}))}),a.on("5",h=>{this.emit(ne.ERROR,new ue({code:fe.DEVICE_ERROR,extraCode:5308,messageParams:{error:h}}))}),a.on("2",h=>{this.emit(ne.DEVICE_CHANGED,{type:"camera",action:"active",device:h})}),a.on("4",h=>{let u;h.error&&(u=ue.convertFrom(h.error)),this.emit(ne.PUBLISH_STATE_CHANGED,de(Z({},h),{error:u}))}),this._listenOutputTrackChanged(a),yield a.capture(d),M(o)||(yield a.setMute(o)),vt(a,a).add("player-state-changed",h=>{this.emit(ne.VIDEO_PLAY_STATE_CHANGED,de(Z({},h),{userId:"",streamType:"main"}))}),r&&this._room.isJoined&&this._room.publish(a).catch(()=>{}),this._localVideoTrack=a,this._localVideoConfig=de(Z({},e),{view:t,publish:r}),yield this._updateVideoPlayOption({view:t,playOption:l,track:a})})}updateLocalVideo(e){return A(this,null,function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:r,mute:o,option:n}=e,a={};if(n)if(M(n.profile)||(Oe(n.profile)?si[n.profile]&&this._localVideoTrack.setProfile(si[n.profile]):this._localVideoTrack.setProfile(n.profile),(!n.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(n.cameraId))&&M(n.useFrontCamera)&&(yield this._localVideoTrack.applyProfile())),n.cameraId?yield this._localVideoTrack.switchDevice(n.cameraId):M(n.useFrontCamera)?M(n.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(n.videoTrack)):yield this._localVideoTrack.switchDevice(n.useFrontCamera?S.FACING_MODE_USER:S.FACING_MODE_ENVIRONMENT),M(n.fillMode)||(a.objectFit=n.fillMode),M(n.mirror)||(a.mirror=n.mirror),n.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(ia(n.qosPreference)),n.small){let d=!this._localVideoTrack.small;On()?(n.small===!0?this._localVideoTrack.small=si["120p"]:Oe(n.small)?this._localVideoTrack.small=si[n.small]:this._localVideoTrack.small=n.small,this._room.videoManager.update(),d&&this._room.enableSmall(!0)):this._log.warn("small stream is not supported")}else n.small===!1&&this._localVideoTrack.small&&(delete this._localVideoTrack.small,this._room.videoManager.update(),this._room.enableSmall(!1));this._room.isJoined&&!M(r)&&(r&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._localVideoConfig.publish&&!r&&this._room.unpublish(this._localVideoTrack).catch(()=>{})),M(o)||(yield this._localVideoTrack.setMute(o)),yield this._updateVideoPlayOption({view:t,playOption:a,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),Li(this._localVideoConfig,e)})}stopLocalVideo(){return A(this,null,function*(){this._localVideoTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),at(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return A(this,arguments,function*(e={publish:!0,view:null}){var u;if(this._localScreenTrack){this._log.warn("screen share is already started");return}let{view:t=null,publish:r=!0,option:o}=e,n=new jt(this._room.videoManager);n.on("4",m=>{let p;m.error&&(p=ue.convertFrom(m.error)),this.emit(ne.PUBLISH_STATE_CHANGED,de(Z({},m),{error:p}))}),n.once("first-video-frame",m=>{this.emit(ne.FIRST_VIDEO_FRAME,de(Z({},m),{streamType:is(m.streamType)}))}),this._listenOutputTrackChanged(n),e.streamType==="main"&&(n.mediaType=4);let a=null,d={},l={};o&&(M(o.profile)||(Oe(o.profile)?ka[o.profile]&&n.setProfile(ka[o.profile]):n.setProfile(o.profile)),o.systemAudio&&(d.systemAudio=!0,d.echoCancellation=o.echoCancellation,d.noiseSuppression=o.noiseSuppression,d.autoGainControl=o.autoGainControl),M(o.fillMode)||(l.objectFit=o.fillMode),o.videoTrack&&(d.videoTrack=o.videoTrack),o.audioTrack&&(d.audioTrack=o.audioTrack),o.captureElement&&(d.captureElement=o.captureElement),o.preferDisplaySurface&&(d.preferDisplaySurface=o.preferDisplaySurface),o.qosPreference&&(d.contentHint=ia(o.qosPreference)));let h=yield n.capture(d);if(n.mediaTrack.addEventListener(S.ENDED,()=>{this._stopScreenShare(),this.emit(ne.SCREEN_SHARE_STOPPED)}),h.getAudioTracks()[0]&&(a=new Yi(this._room.audioManager),yield a.setInputMediaStreamTrack(h.getAudioTracks()[0]),this._speakerId&&a.setAudioOutput(this._speakerId)),vt(n,n).add("player-state-changed",m=>{this.emit(ne.VIDEO_PLAY_STATE_CHANGED,de(Z({},m),{userId:"",streamType:"sub"}))}),r&&this._room.isJoined){let m=[n];if(a){m.push(a);let{echoCancellation:p}=((u=a.mediaTrack)==null?void 0:u.getSettings())||{};if(p===!1){this._log.warn("echoCancellation of screen audio track is disable, try to open audioProcessor plugin");try{this.startPlugin("AudioProcessor",{sdkAppId:Number(this.room.sdkAppId),userId:this._room.userId,userSig:this.room.userSig,screenAudio:!0,localAudio:!1})}catch(g){this._log.warn("start audioProcessor plugin failed: ",g)}}}this._room.publish(...m).catch(()=>{})}this._localScreenTrack=n,this._localScreenAudioTrack=a,this._localScreenConfig=de(Z({},e),{view:t,publish:r}),yield this._updateVideoPlayOption({view:t,playOption:l,track:n})})}updateScreenShare(e){return A(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:r,option:o}=e,n={};if(o&&(M(o.fillMode)||(n.objectFit=o.fillMode),o.qosPreference)){let a=ia(o.qosPreference);this._localScreenTrack.setContentHint(a)}this._room.isJoined&&!M(r)&&(r&&!this._localScreenConfig.publish&&(this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch(()=>{})),this._localScreenConfig.publish&&!r&&(this._room.unpublish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.unpublish(this._localScreenAudioTrack).catch(()=>{}))),yield this._updateVideoPlayOption({view:t,playOption:n,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),Li(this._localScreenConfig,e)})}stopScreenShare(){return A(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return A(this,null,function*(){let{view:t,userId:r,streamType:o,option:n}=e,a=`${r}_${o}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${r}, streamType:${o}`);return}let d=this._room.remotePublishedUserMap.get(r);if(!d)return;let l={},h=o==="main"?d.remoteVideoTrack:d.remoteAuxiliaryTrack;this._listenOutputTrackChanged(h),n&&(M(n.fillMode)||(l.objectFit=n.fillMode),M(n.mirror)||(l.mirror=n.mirror),M(n.poster)||(l.poster=n.poster),l.canvasRender=n.canvasRender,o==="main"&&!M(n.small)&&(!d.remoteVideoTrack.isSubscribing&&!d.remoteVideoTrack.isSubscribed&&d.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,h.user))),yield this._room.subscribe(h),yield this._enableVideoDecodeFallback(h,o),yield this._updateVideoPlayOption({view:t,playOption:l,track:h}),this._emitTrackEvent(h),this._remoteVideoConfigMap.set(a,{config:e}),n&&!M(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:h,view:t,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:n==null?void 0:n.viewRoot})})}updateRemoteVideo(e){return A(this,null,function*(){var T,I;let{view:t,userId:r,streamType:o,option:n}=e,a=`${r}_${o}`,d=this._remoteVideoConfigMap.get(a);if(!d||!this._room.remotePublishedUserMap.has(r))return;let l={};n&&(M(n.fillMode)||(l.objectFit=n.fillMode),M(n.mirror)||(l.mirror=n.mirror));let h=null,u=this._room.remotePublishedUserMap.get(r);if(o==="main"&&(u!=null&&u.muteState.hasVideo)&&(h=u.remoteVideoTrack),o==="sub"&&(u!=null&&u.muteState.hasAuxiliary)&&(h=u.remoteAuxiliaryTrack),!h)return;let{config:m}=d;o==="main"&&n&&!M(n.small)&&this._room.changeType(n.small,h.user),yield this._updateVideoPlayOption({view:t,playOption:l,track:h,prevConfig:m}),Li(m,e);let p=M(n==null?void 0:n.receiveWhenViewVisible)?(T=m.option)==null?void 0:T.receiveWhenViewVisible:n.receiveWhenViewVisible,g=M(t)?m.view:t,f=M(n==null?void 0:n.viewRoot)?(I=m.option)==null?void 0:I.viewRoot:n.viewRoot;this._observeView({remoteTrack:h,view:g,receiveWhenViewVisible:p,viewRoot:f})})}stopRemoteVideo(e){return A(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,t=!0){return A(this,null,function*(){let r=[],o=this._room.remotePublishedUserMap.get(e.userId);if(o){let{muteState:n,remoteVideoTrack:a,remoteAuxiliaryTrack:d}=o;e.streamType==="main"&&(a.stop(),n.hasVideo&&r.push(a)),e.streamType==="sub"&&(d.stop(),n.hasAuxiliary&&r.push(d))}for(let n of r)t&&(yield this._room.unsubscribe(n),this._mediaTrackMap.delete(n.outMediaTrack));this._removeRemoteVideoConfig(e.userId,e.streamType)})}_removeRemoteVideoConfig(e,t){let r=`${e}_${t}`,o=this._remoteVideoConfigMap.get(r);o&&o.observer&&o.observer.disconnect(),this._remoteVideoConfigMap.delete(r)}muteRemoteAudio(e,t){return A(this,null,function*(){this._remoteAudioMuteMap.set(e,t);try{if(e==="*")if(t)yield this._stopRemoteAudio({userId:e});else{let r=[...this._room.remotePublishedUserMap.values()];for(let o of r)o.muteState.hasAudio&&!this._remoteAudioConfigMap.has(o.userId)&&(yield this._startRemoteAudio({userId:o.userId}))}else t?yield this._stopRemoteAudio({userId:e}):this._remoteAudioConfigMap.has(e)||(yield this._startRemoteAudio({userId:e}))}catch(r){throw this._remoteAudioMuteMap.delete(e),r}})}setRemoteAudioVolume(e,t){if(e==="*"){let r=[...this._room.remotePublishedUserMap.values()];for(let o of r)this._remoteAudioVolumeMap.set(o.userId,t),o.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:o.remoteAudioTrack})}else if(e){let r=this._room.remotePublishedUserMap.get(e);this._remoteAudioVolumeMap.set(e,t),r&&r.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:r.remoteAudioTrack})}}startPlugin(e,t){return A(this,null,function*(){return e.start(t)})}updatePlugin(e,t){return A(this,null,function*(){return e.update(t)})}stopPlugin(e,t){return A(this,null,function*(){return e.stop(t)})}enableAudioVolumeEvaluation(e=2e3,t=!1){this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,r){return this.listeners(e).includes(t)?this:(this._log.debug("on",e),super.on(e,t,r),this._eventListened.add(e),e===Ie.EVENT.AUDIO_FRAME&&!this._getPCMAbortCtrl&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM(o=>{this.emit(Ie.EVENT.AUDIO_FRAME,{data:o})}),this._localAudioTrack&&this._localAudioTrack.on("input-media-track-changed",()=>{this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("inputMediaTrackChanged"),this._getPCMAbortCtrl=this._room.audioManager.getPCM(o=>{this.emit(Ie.EVENT.AUDIO_FRAME,{data:o})}))})),this)}emit(e,...t){try{pf.has(e)&&this._log.debug(`emit ${e} ${JSON.stringify(t)}`)}catch(r){}return super.emit(e,...t)}off(e,t,r){var o,n;return this._log.debug("off",e),e==="*"?(this._eventListened.clear(),this.removeAllListeners(),(o=this._getPCMAbortCtrl)==null||o.abort("off"),delete this._getPCMAbortCtrl):(super.off(e,t,r),e===Ie.EVENT.AUDIO_FRAME&&((n=this._getPCMAbortCtrl)==null||n.abort("off"),delete this._getPCMAbortCtrl)),this}getAudioTrack(e={userId:"",streamType:"main"}){let t,r=null,o="main",n=!1;if(Oe(e)?t=e:(t=e.userId,n=e.processed===!0,e.streamType&&(o=e.streamType)),t){let a=this._room.remotePublishedUserMap.get(t);a&&(r=a.remoteAudioTrack)}else r=o==="sub"?this._localScreenAudioTrack:this._localAudioTrack;return r?n&&r.outMediaTrack&&r.outMediaTrack!==r.mediaTrack?r.outMediaTrack.clone():r.mediaTrack:null}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:t="",streamType:r="main",processed:o=!1}=e,n=null;if(t==="")r==="main"&&this._localVideoTrack&&(n=this._localVideoTrack),r==="sub"&&this._localScreenTrack&&(n=this._localScreenTrack);else{let a=this._room.remotePublishedUserMap.get(t);a&&(n=r==="main"?a.remoteVideoTrack:a.remoteAuxiliaryTrack)}return n?o&&n.outMediaTrack&&n.outMediaTrack!==n.mediaTrack?n.outMediaTrack.clone():n.mediaTrack:null}getVideoSnapshot(e={}){let{userId:t,streamType:r="main"}=e;if(t){let o=this._room.remotePublishedUserMap.get(t);if(r==="main"&&(o!=null&&o.muteState.hasVideo))return o.remoteVideoTrack.getVideoFrame();if(r==="sub"&&(o!=null&&o.muteState.hasAuxiliary))return o.remoteAuxiliaryTrack.getVideoFrame()}else{if(r==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(r==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(e){var t,r;this._speakerId=e,(t=this._localAudioTrack)==null||t.setAudioOutput(e),(r=this._localScreenAudioTrack)==null||r.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(o=>o.remoteAudioTrack.setAudioOutput(e))}setCurrentSpeaker(e){return A(this,null,function*(){(yield Yr()).forEach(r=>{r.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(ne.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}),At=r)}),this._log.warn('the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: https://web.sdk.qcloud.com/trtc/webrtc/v5/doc/en/TRTC.html#.setCurrentSpeaker')})}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return A(this,null,function*(){let{userId:t}=e;if(this._remoteAudioConfigMap.has(t)){this._log.warn(`remote audio has already started. userId:${t}`);return}let r=this._room.remotePublishedUserMap.get(t);if(!r)return;let o={},n=r.remoteAudioTrack;this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId);try{let a=this._remoteAudioVolumeMap.get(t),d=De(a)?a:100;o.volume=d,this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(n),He(We(n,"decode-failed"),St(We(n,ge.INIT)),it(()=>{this.startPlugin(ua.Name,{track:n,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:o,track:n}),n.outMediaTrack&&x.emit("266",{room:this.room,type:"add",audioReference:n.outMediaTrack,refId:`ra-${t}`})}catch(a){throw this._remoteAudioConfigMap.delete(t),a}this._emitTrackEvent(n)})}_stopRemoteAudio(e,t=!0){return A(this,null,function*(){let r=this._room.remotePublishedUserMap.get(e.userId);r&&(r.remoteAudioTrack.stop(),r.muteState.hasAudio&&t&&(yield this._room.unsubscribe(r.remoteAudioTrack)),this._mediaTrackMap.delete(r.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete(`${e.userId}`),x.emit("266",{room:this.room,type:"remove",refId:`ra-${e.userId}`})})}_enableVideoDecodeFallback(e,t){let r=this._room.videoDecodeFallbackType;if(!r||!this._plugins.has("TRTCVideoDecoder"))return;e.log.debug("remote video will fall back when decode failed",e.id);let o;He(We(e,"decode-failed"),St(We(e,ge.INIT)),ah(()=>{this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:r})}),Ms(We(e,"decode-downgrade-state-changed")),it(n=>{o=n.state,this.emit(ne.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,de(Z({},n),{streamType:t,userId:e.userId}))},n=>{e.log.error("fallback",n)},()=>{o==="STARTED"&&e.log.info("fallback complete")}))}_updateVideoPlayOption(n){return A(this,arguments,function*({view:e,playOption:t,track:r,prevConfig:o}){if(r.setMirror(t.mirror),M(e)&&o&&o.view&&!Ys(t)){let a=Ks(o.view);a.length>0&&(yield r.play(a,t))}if(!M(e)){let a=Ks(e);a.length>0?yield r.play(a,t):r.stop()}})}_updateAudioPlayOption(o){return A(this,arguments,function*({playOption:e={},track:t,prevConfig:r}){if(!t.isPlayCalled)try{yield t.play(null,e)}catch(n){}if(M(e.muted)||t.setPlayerMute(e.muted),M(e.volume)||t.setAudioVolume(e.volume/100),t instanceof ti&&t.mediaTrack){let n=e.muted===!1&&!M(e.volume)&&e.volume>0?"add":"remove";x.emit("266",{room:this.room,type:n,audioReference:t.mediaTrack,refId:"em"})}else if(t instanceof Ci){let n=e.muted?0:e.volume;if(M(n))return;x.emit("266",{room:this.room,type:"update_volume",refId:`ra-${t.userId}`,volume:e.volume})}})}_listenOutputTrackChanged(e){e.listeners("output-media-track-changed").length===0&&e.on("output-media-track-changed",()=>this._emitTrackEvent(e,!1))}_emitTrackEvent(e,t=!0){let r=e.isRemote?e.userId:"";e.outMediaTrack&&(t&&this._mediaTrackMap.get(e.outMediaTrack)===r||(this._mediaTrackMap.set(e.outMediaTrack,r),this.emit(ne.TRACK,{userId:r,streamType:is(e.streamType),track:e.outMediaTrack,sourceTrack:e.mediaTrack})))}_checkTrackToPublish(){var t,r,o,n;let e=[];if((t=this._localAudioConfig)!=null&&t.publish&&this._localAudioTrack&&e.push(this._localAudioTrack),(r=this._localVideoConfig)!=null&&r.publish&&this._localVideoTrack&&e.push(this._localVideoTrack),(o=this._localScreenConfig)!=null&&o.publish&&(this._localScreenTrack&&e.push(this._localScreenTrack),this._localScreenAudioTrack)){e.push(this._localScreenAudioTrack);let{echoCancellation:a}=((n=this._localScreenAudioTrack.mediaTrack)==null?void 0:n.getSettings())||{};if(a===!1){this._log.warn("echoCancellation of screen audio track is disable, try to open audioProcessor plugin");try{this.startPlugin("AudioProcessor",{sdkAppId:Number(this.room.sdkAppId),userId:this._room.userId,userSig:this.room.userSig,screenAudio:!0,localAudio:!1})}catch(d){this._log.warn("start audioProcessor plugin failed: ",d)}}}if(e.length!==0)return this._room.publish(...e).catch(()=>{})}_observeView({remoteTrack:e,view:t,receiveWhenViewVisible:r=!1,viewRoot:o}){if(M(t))return;let n=this._remoteVideoConfigMap.get(`${e.userId}_${is(e.streamType)}`);if(!n)return;let a=n.observer||void 0;if(t===null||tt(t)&&t.length===0||!r){a==null||a.disconnect(),e.isSubscribed||this._room.subscribe(e).catch(()=>{});return}let l=n.visibleViewMap||new Map,h=-1;(!a||a.root!==o)&&(a==null||a.disconnect(),l.clear(),a=new IntersectionObserver(m=>{m.forEach(p=>{l.set(p.target,p.isIntersecting),e.log.info(`view ${p.target.id} is${p.isIntersecting?"":" not"} visible`)}),clearTimeout(h),h=window.setTimeout(()=>{[...l.values()].find(g=>g)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:o}));let u=new Set(Ks(t));l.forEach((m,p)=>{u.has(p)||(a.unobserve(p),l.delete(p))}),u.forEach(m=>{l.set(m,!0),a.observe(m)}),a.takeRecords().forEach(m=>{l.set(m.target,m.isIntersecting)}),n.visibleViewMap=l,n.observer=a}_exitRoom(){return A(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(e=>{this._stopRemoteAudio({userId:e}).catch()}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let t=e.includes("main")?"main":"sub",r=e.split(`_${t}`)[0];r&&this._stopRemoteVideo({userId:r,streamType:t}).catch()}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._remoteAudioVolumeMap.clear(),Sf(this),this._room.remotePublishedUserMap.forEach(e=>{at(e.remoteAudioTrack),at(e.remoteVideoTrack),at(e.remoteAuxiliaryTrack)})})}_stopScreenShare(){return A(this,null,function*(){var e;if(this._localScreenTrack){if(this._room.isJoined){let t=[this._localScreenTrack];this._localScreenAudioTrack&&t.push(this._localScreenAudioTrack),yield(e=this._room)==null?void 0:e.unpublish(...t).catch(()=>{})}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),at(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_onLocalTrackCaptured({track:e}){e.kind==="audio"&&(!At||Ao(At))&&(this._initActiveSpeaker(),x.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return A(this,null,function*(){if(At&&!Ao(At))this.emit(ne.DEVICE_CHANGED,{type:"speaker",action:"active",device:At});else{let e=yield Yr();e[0]&&!Ao(e[0])?(At=e[0],this.emit(ne.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):x.on("102",this._onLocalTrackCaptured,this)}})}_onAudioAvailable({userId:e}){let t=this._remoteAudioMuteMap.has(e)?this._remoteAudioMuteMap.get(e):this._remoteAudioMuteMap.get("*");(t===!1||this._room.autoReceiveAudio&&!t)&&this._doStartRemoteAudio({userId:e}).catch(()=>{})}_onVideoAvailable({userId:e,streamType:t}){if(!this._room.autoReceiveVideo)return;let r=this._room.remotePublishedUserMap.get(e);if(r){let o=t==="main"?r.remoteVideoTrack:r.remoteAuxiliaryTrack,n=[o];this._room.autoReceiveAudio&&r.remoteAudioTrack.isAvailable&&n.push(r.remoteAudioTrack),this._room.subscribe(...n).then(()=>{this._emitTrackEvent(o)}).catch(()=>{})}}_onAudioUnavailable({userId:e,muteState:t}){t.hasAudio&&t.audioMuted||this._stopRemoteAudio({userId:e},!1).catch(()=>{})}_onVideoUnavailable({userId:e,streamType:t}){this._stopRemoteVideo({userId:e,streamType:t},!1).catch(()=>{})}sendSEIMessage(e,t){var o;let r=this._plugins.get("SEI");r&&(r.update({buffer:e,options:de(Z({seiPayloadType:243},t),{small:!!((o=this._localVideoTrack)!=null&&o.small)})}),Q.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,r;(r=(t=this._room).sendCustomMessage)==null||r.call(t,e),Q.addCount({key:500001,useUV:!0})}static setLogLevel(e,t){z.setLogLevel(e),M(t)||(t?z.enableUploadLog():z.disableUploadLog())}static isSupported(){return Td()}static getCameraList(e=!0){return ei(e)}static getMicrophoneList(e=!0){return Wt(e)}static getSpeakerList(e=!0){return Yr(e)}static setCurrentSpeaker(e){return A(this,null,function*(){if(ze&&(e===ci.SPEAKER||e===ci.HEADSET)){let r=yield Ie.getMicrophoneList(),o="";if(r.forEach(n=>{n.label===e&&(o=n.deviceId)}),!o)return;ha.forEach(n=>A(this,null,function*(){n._localAudioTrack&&(yield n.updateLocalAudio({option:{microphoneId:o}}))}));return}(yield Yr()).forEach(r=>{r.deviceId===e&&(ha.forEach(o=>{o._setCurrentSpeaker(e),o.emit(ne.DEVICE_CHANGED,{type:"speaker",action:"active",device:r})}),At=r)})})}static _addKVStat({type:e,key:t,value:r,base:o,useUV:n,version:a}){switch(a&&(Cs.version=a),e){case"count":Cs.addCount({key:t,useUV:n});break;case"enum":Cs.addEnum({key:t,value:r,useUV:n});break;case"number":Cs.addNumber({key:t,value:r,split:o});break}}};c(Ie,"_loggerManager",z),c(Ie,"EVENT",ne),c(Ie,"ERROR_CODE",fe),c(Ie,"TYPE",ci),c(Ie,"frameWorkType",30),J([Xe({replaceArg:e=>({argIndex:0,value:{name:"plugin"in e?e.plugin.Name:e.Name,assetsPath:"assetsPath"in e?e==null?void 0:e.assetsPath:"default"}})})],Ie.prototype,"use",1),J([Ot(It.TRTC.enterRoom),es("room",([e],[t])=>(e.roomId||e.strRoomId)===(t.roomId||t.strRoomId)&&e.userId===t.userId&&e.sdkAppId===t.sdkAppId),be(e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)}),Xe()],Ie.prototype,"enterRoom",1),J([Xe()],Ie.prototype,"exitRoom",1),J([Ot(It.TRTC.switchRole),Us("room",{merge:(e,t)=>t}),Xe()],Ie.prototype,"switchRole",1),J([Xe()],Ie.prototype,"destroy",1),J([Ot(It.TRTC.startLocalAudio),es("audio",([e],[t])=>{var r,o;return((r=e==null?void 0:e.option)==null?void 0:r.microphoneId)===((o=t==null?void 0:t.option)==null?void 0:o.microphoneId)}),Xe()],Ie.prototype,"startLocalAudio",1),J([Ot(It.TRTC.updateLocalAudio),Us("audio",{debounce:{delay:200,getKey:()=>`${Gf}-localAudio`,isNeedToDebounce:e=>{var t;return!M((t=e.option)==null?void 0:t.captureVolume)}}}),Xe()],Ie.prototype,"updateLocalAudio",1),J([ts("audio"),Xe()],Ie.prototype,"stopLocalAudio",1),J([Ot(It.TRTC.startLocalVideo),es("video",([e],[t])=>{var r,o;return((r=e==null?void 0:e.option)==null?void 0:r.cameraId)===((o=t==null?void 0:t.option)==null?void 0:o.cameraId)}),Xe()],Ie.prototype,"startLocalVideo",1),J([Ot(It.TRTC.updateLocalVideo),Us("video"),Xe()],Ie.prototype,"updateLocalVideo",1),J([ts("video"),Xe()],Ie.prototype,"stopLocalVideo",1),J([Ot(It.TRTC.startScreenShare),es("screen",()=>!0),Xe()],Ie.prototype,"startScreenShare",1),J([Ot(It.TRTC.updateScreenShare),Us("screen"),Xe()],Ie.prototype,"updateScreenShare",1),J([Xe()],Ie.prototype,"stopScreenShare",1),J([Ot(It.TRTC.startRemoteVideo),es(e=>`v${e.userId}${e.streamType}`,()=>!0),Xe({getRemoteId:e=>`${e.userId}_${e.streamType}`})],Ie.prototype,"startRemoteVideo",1),J([Ot(It.TRTC.updateRemoteVideo),Us(e=>`v${e.userId}${e.streamType}`),Xe({getRemoteId:e=>`${e.userId}_${e.streamType}`})],Ie.prototype,"updateRemoteVideo",1),J([Ot(It.TRTC.stopRemoteVideo),be(e=>function(t){return A(this,null,function*(){if(t.userId==="*"){let r=[];return this._room.remotePublishedUserMap.forEach(o=>{this._remoteVideoConfigMap.has(`${o.userId}_main`)&&r.push(this.stopRemoteVideo({streamType:"main",userId:o.userId}).catch(()=>{})),this._remoteVideoConfigMap.has(`${o.userId}_sub`)&&r.push(this.stopRemoteVideo({streamType:"sub",userId:o.userId}).catch(()=>{}))}),Promise.all(r)}return e.call(this,t)})}),Xe({getRemoteId:e=>`${e.userId}_${e.streamType}`})],Ie.prototype,"stopRemoteVideo",1),J([ts(e=>`v${e.userId}${e.streamType}`)],Ie.prototype,"_stopRemoteVideo",1),J([Ot(...It.TRTC.muteRemoteAudio),Xe({getRemoteId:e=>e})],Ie.prototype,"muteRemoteAudio",1),J([gh(...It.TRTC.setRemoteAudioVolume),ra(200,e=>e),Xe({getRemoteId:e=>e})],Ie.prototype,"setRemoteAudioVolume",1),J([hc("start"),Ut(e=>{var t;return(t=e.afterStart)==null?void 0:t.call(e)}),es((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t)),Xe({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Xl[e.getName()],ignoreLog:e=>e.getName()==="Debug"})],Ie.prototype,"startPlugin",1),J([hc("update"),Us((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t)),Xe({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Ql[e.getName()]})],Ie.prototype,"updatePlugin",1),J([hc("stop"),ts((e,t)=>{if(e.disableRandomCall)return null;let r=e.getGroup(t),o=e.getAlias();return r==="*"?new RegExp(`${o}.*`):o+r}),Xe({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Yl[e.getName()]})],Ie.prototype,"stopPlugin",1),J([gh(...It.TRTC.enableAudioVolumeEvaluation)],Ie.prototype,"enableAudioVolumeEvaluation",1),J([Xe()],Ie.prototype,"getVideoSnapshot",1),J([Xe()],Ie.prototype,"_setCurrentSpeaker",1),J([es(e=>`a${e.userId}`,()=>!0)],Ie.prototype,"_startRemoteAudio",1),J([be(e=>function(t){return A(this,null,function*(){return t.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(r=>this._stopRemoteAudio(de(Z({},t),{userId:r.userId})).catch(()=>{}))):e.call(this,t)})}),ts(e=>`a${e.userId}`)],Ie.prototype,"_stopRemoteAudio",1),J([ts("room")],Ie.prototype,"_exitRoom",1),J([ts("screen")],Ie.prototype,"_stopScreenShare",1),J([Ot(...It.TRTC.sendSEIMessage),lh({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...e)=>e[0].byteLength})],Ie.prototype,"sendSEIMessage",1),J([Ot(It.TRTC.sendCustomMessage),lh({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],Ie.prototype,"sendCustomMessage",1),J([Ot(It.TRTC.create)],Ie,"_create",1);var $h=Ie,ma=$h;var Fh=class{constructor(){c(this,"_set",new Set);x.on(B.LEAVE_SUCCESS,this.delete,this)}add({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,e||i.roomId,i.sdkAppId,i.useStringRoomId);this._set.add(t)}delete({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,i.roomId||e,i.sdkAppId,i.useStringRoomId);this._set.delete(t)}getKey(i,e,t,r){return`${t}_${e}_${i}_${r}`}isJoined({userId:i,roomId:e,sdkAppId:t,room:r}){return r.scene==="rtc"?!1:this._set.has(this.getKey(i,e,t,r.useStringRoomId))}};function SS(){return A(this,null,function*(){let s,i;try{let u=yield Wt();s=u&&u.length}catch(u){}try{let u=yield ei();i=u&&u.length}catch(u){}let e={microphone:s,camera:i},{isH264EncodeSupported:t,isVp8EncodeSupported:r,isH264DecodeSupported:o,isVp8DecodeSupported:n}=this.checkSystemResult.detail,a=Wi.basis(),d={webRTC:a.isWebRTCSupported,getUserMedia:a.isGetUserMediaSupported,webSocket:a.isWebSocketsSupported,screenShare:a.isScreenShareSupported,webAudio:a.isWebAudioSupported,h264Encode:t,h264Decode:o,vp8Encode:r,vp8Decode:n},l={browser:a.browser,os:a.os,trtc:d,devices:e},h={isWebCodecSupported:a.isWebCodecSupported,isMediaSessionSupported:a.isMediaSessionSupported,isWebTransportSupported:a.isWebTransportSupported};Me.uploadEvent({log:`trtcstats-${JSON.stringify(l)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(l)}`),Me.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(h)}`,userId:this.userId})})}function zf(){return be(s=>{let i=new Fh;return function(e,t,r){return A(this,null,function*(){let o=String(e.roomId||e.strRoomId);if(this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.userSig=e.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=t,e.privateMapKey=e.privateMapKey||"",this.isJoined)throw new X({code:H.INVALID_OPERATION,message:pe({key:me.INVALID_JOIN})});if(this.checkDestroy(),i.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this}))throw new X({code:H.INVALID_OPERATION,message:pe({key:me.REPEAT_JOIN,data:this.userId})});i.add({room:this,roomId:o}),this.role=e.role===21?"audience":"anchor",this._log.info(`Join() => joining room: ${o} useStringRoomId: ${this.useStringRoomId} scene: ${this.scene} role: ${this.role}`),x.emit(B.JOIN_START,{room:this,roomId:o,params:e});let n=Jt.getEnv();n||(n=ar.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(Oa.OLD_CLOUD_LADDER)?n=ar.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(Oa.WEBRTC)&&(n=ar.WEBRTC))),Me.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),Wi.checkSystemRequirementsInternal().then(a=>{this.checkSystemResult=a,SS.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Jt.getEnv()&&(yield this.schedule(e,r));let a=yield s.call(this,e,t,r);return this.roomId=o,this._joinedTimestamp=Jt.performanceNow(),x.emit(B.JOIN_SUCCESS,{room:this}),r===30&&!e.component&&Me.uploadEvent({log:`stat-conv-${Number(Ti)}-${location.hostname}`,userId:this.userId}),a}catch(a){throw i.delete({room:this,roomId:o}),x.emit(B.JOIN_FAILED,{room:this,error:a}),a}})}})}var jf=()=>be(s=>function(...i){return A(this,null,function*(){x.emit(B.LEAVE_START,{room:this}),yield s.call(this,...i),x.emit(B.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function Jf(){return be(s=>function(...i){let e=s.apply(this,i);return i.forEach(t=>!t.isSubscribed&&t.subscribe(e)),e})}var Xf=gt(Mt());var rt={SETUP_SUCCESS:"1",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",RECONNECT_FAILED:"4",SETUP_FAILED:"5",DISCONNECTED:"6"};var bi={CLIENT_BANNED:9,CHANNEL_SETUP_RESULT:19,CHANNEL_RECONNECT_RESULT:514,JOIN_ROOM_RESULT:20,PEER_JOIN:4134,PEER_LEAVE:4135,STREAM_ADDED:16,STREAM_REMOVED:18,UPLINK_NETWORK_STATS:22,UPDATE_REMOTE_MUTE_STAT:23,PUBLISH_RESULT:4098,PUBLISH_STATE_CHANGE_RESULT:4112,UNPUBLISH_RESULT:4100,SUBSCRIBE_RESULT:4102,UNSUBSCRIBE_RESULT:4104,SUBSCRIBE_CHANGE_RESULT:4106,MUTE_RESULT:4108,UPDATE_OFFER_RESULT:4128,START_PUBLISH_TENCENT_CDN_RES:1286,STOP_PUBLISH_TENCENT_CDN_RES:1288,START_PUBLISH_GIVEN_CDN_RES:777,STOP_PUBLISH_GIVEN_CDN_RES:779,START_MIX_TRANSCODE_RES:781,STOP_MIX_TRANSCODE_RES:783,START_PUBLISH_CDN_STREAM_RES:8196,UPDATE_PUBLISH_CDN_STREAM_RES:8198,STOP_PUBLISH_CDN_STREAM_RES:8200,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772,REBUILD_PEER_CONNECTION_RES:4150,SPC_PUBLISH_RESULT:4146,SPC_SUBSCRIBE_RESULT:4156,ABILITY_STATUS_REPORT_RESULT:4158,SERVER_FIRST_PACKAGE_RECEIVED:5e3,RECEIVE_CUSTOM_MSG:4140},qf=[bi.UPDATE_REMOTE_MUTE_STAT,bi.UPLINK_NETWORK_STATS,bi.USER_LIST_RES,bi.MUTE_RESULT,bi.SERVER_FIRST_PACKAGE_RECEIVED,bi.RECEIVE_CUSTOM_MSG],Ee={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",START_PUBLISH_CDN_STREAM_RES:"start-publish-cdn-stream-res",UPDATE_PUBLISH_CDN_STREAM_RES:"update-publish-cdn-stream-res",STOP_PUBLISH_CDN_STREAM_RES:"stop-publish-cdn-stream-res",USER_LIST_RES:"user-list-res",SWITCH_ROLE_RES:"switch_role_res",MUTE_RESULT:"mute-result",UPDATE_CONSTRAINT_CONFIG_RES:"update-contraint-config-res",REBUILD_PEER_CONNECTION_RES:"rebuild-pc-res",SPC_PUBLISH_RESULT:"spc-publish-result",SPC_SUBSCRIBE_RESULT:"spc-subscribe-result",ABILITY_STATUS_REPORT_RESULT:"ability-status-report",SERVER_FIRST_PACKAGE_RECEIVED:"first-pkg-received",RECEIVE_CUSTOM_MSG:"receive-custom-msg"},ve={PUBLISH_CHANGE:"publish_change",JOIN_ROOM:"join",LEAVE_ROOM:"leave",ON_QUALITY_REPORT:"quality_report",UPDATE_MUTE_STAT:"mute_uplink",PUBLISH:"publish",PUBLISH_STATE_CHANGE:"publish_state_change",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",RECEIVE_DATA_USER_LIST:"receive_data_userlist",UNSUBSCRIBE:"unsubscribe",SUBSCRIBE_CHANGE:"subscribe_change",START_PUBLISH_TENCENT_CDN:"start_publishing",STOP_PUBLISH_TENCENT_CDN:"stop_publishing",START_PUBLISH_GIVEN_CDN:"start_push_user_cdn",STOP_PUBLISH_GIVEN_CDN:"stop_push_user_cdn",START_MIX_TRANSCODE:"start_mcu_mix",STOP_MIX_TRANSCODE:"stop_mcu_mix",START_PUBLISH_CDN_STREAM:"start_publish_cdn_stream",UPDATE_PUBLISH_CDN_STREAM:"update_publish_cdn_stream",STOP_PUBLISH_CDN_STREAM:"stop_publish_cdn_stream",GET_USER_LIST:"get_user_list",SWITCH_ROLE:"change_role",UPDATE_CONSTRAINT_CONFIG:"update_constraint_config",REBUILD_PEER_CONNECTION:"rebuild_pc",READY_TO_RECEIVE_DATA:"ready_to_receive",SPC_JOIN_ROOM:"join/v2",SPC_PUBLISH:"publish/v2",SPC_SUBSCRIBE:"subscribe/v3",ABILITY_STATUS_REPORT:"ability_status_report",RECONNECT_WS:"reconnect",SEND_CUSTOM_MSG:"channel_msg"};var wc=new Set;function Qf(s){let i=[...wc.values()].find(e=>e.room.userId===s&&!e.room.isJoined);return i||null}var Vo=class extends Xf.default{constructor(e){var r,o,n;super();c(this,"room");c(this,"sdkAppId");c(this,"userId");c(this,"userSig");c(this,"url");c(this,"backupUrl");c(this,"destroyed",!1);c(this,"_socketInUse");c(this,"_socket");c(this,"_backupSocket");c(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,bakRelayIps:[]});c(this,"_currentState","DISCONNECTED");c(this,"_isReconnecting",!1);c(this,"_seq",0);c(this,"_log");c(this,"_lastMessageTime",-1);c(this,"_connectStartTime",-1);c(this,"_stopConnectRetry");c(this,"bytesSent",0);c(this,"bytesReceived",0);c(this,"keepAlive",!1);c(this,"signalDomainWhenUnifiedProxy");c(this,"stopKeepAliveTimeout");c(this,"rtt",0);this.room=e.room,this.sdkAppId=e.sdkAppId,this.userId=e.userId,this.userSig=e.userSig,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy;let t=((o=(r=this.room.scheduleResult)==null?void 0:r.config)==null?void 0:o.keepAliveClient)||0;(n=this.room.joinParams)!=null&&n.keepAlive&&!t&&(t=1),t-wc.size>0&&this.room.enableSPC&&(this.keepAlive=!0,wc.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=z.createLogger({id:"ws",userId:this.userId,sdkAppId:this.sdkAppId}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get race(){return this.room.enableSPC&&!this.room.proxy_ws}get urlParam(){let e=`?sdkAppId=${encodeURIComponent(this.sdkAppId)}&userId=${encodeURIComponent(this.userId)}&userSig=${encodeURIComponent(this.userSig)}&keepAlive=${encodeURIComponent(Number(this.keepAlive))}`;this.signalDomainWhenUnifiedProxy&&(e+=`&signalDomain=${encodeURIComponent(this.signalDomainWhenUnifiedProxy)}`);let t=new URLSearchParams(location.search).get("clientIp");return t&&(e+=`&clientIp=${t}`),this.race?`${e}&race=1`:e}get _urlWithParam(){return`${this.url}${this.race?"/v2/ws":""}${this.urlParam}`}get _backupUrlWithParam(){return`${this.backupUrl}${this.race?"/v2/ws":""}${this.urlParam}`}get isConnected(){return this._currentState==="CONNECTED"}get isConnecting(){return this._currentState==="CONNECTING"}get isOnline(){return this._currentState==="CONNECTED"&&Date.now()-this._lastMessageTime<12*1e3}connect(){return A(this,arguments,function*(e=10*1e3){if(this.isConnected)return Promise.resolve();this._log.info(`connect to [${this.url}, ${this.backupUrl}] ${this.race?"race":""}${e?` timeout: ${e}`:""} keepAlive: ${Number(this.keepAlive)}`),this.emitConnectionStateChanged("CONNECTING"),this._connectStartTime=le();let t=[this.connectWS({url:this._urlWithParam,isMain:!0,timeout:e})];this.race&&this._backupUrlWithParam!==this._urlWithParam&&t.push(this.connectWS({url:this._backupUrlWithParam,isMain:!1,timeout:e})),this._socketInUse=yield _s(t),this.unbindAndCloseSocket(this._socketInUse===this._socket?S.BACKUP:S.MAIN),this.emitConnectionStateChanged("CONNECTED")})}connectWS({url:e,timeout:t,isMain:r}){let o=new WebSocket(e);this.bindSocket(o),r?this._socket=o:this._backupSocket=o;let n=-1;return new Promise((a,d)=>{o.onclose=d,o.onerror=d,o.onopen=()=>a(o),t&&(n=setTimeout(()=>{this.unbindAndCloseSocket(r?S.MAIN:S.BACKUP),d(new X({code:H.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))},t))}).finally(()=>{o.onclose=null,o.onerror=null,o.onopen=null,clearTimeout(n)})}bindSocket(e){e.addEventListener("close",this.onclose),e.addEventListener("error",this.onerror),e.addEventListener("message",this.onmessage)}unbindSocket(e){e.removeEventListener("close",this.onclose),e.removeEventListener("error",this.onerror),e.removeEventListener("message",this.onmessage)}unbindAndCloseSocket(e){if(e===S.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(t){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(t){}this._backupSocket=null}}onclose(e){e.target===this._socketInUse&&(this._log.warn(`${e.target===this._socket?"main":"backup"} is closed code:${e.code} ${e.reason}`),this.emitConnectionStateChanged("DISCONNECTED"),(!e.wasClean||e.code!==1e3)&&this.startReconnection(),this.room.isJoining&&this.emit(rt.SETUP_FAILED,new X({code:H.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onclose"})))}onerror(e){this._log.error(`${e.target===this._socket?"main":"backup"} error observed`),this.emitConnectionStateChanged("DISCONNECTED"),e.target===this._socketInUse&&(this.unbindAndCloseSocket(S.MAIN),this.unbindAndCloseSocket(S.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(rt.SETUP_FAILED,new X({code:H.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=ln(e.data);let t=JSON.parse(e.data),{cmd:r,data:o}=t,n=Object.values(bi),d=Object.keys(bi)[n.indexOf(r)],l=Ee[d]||r;switch(qf.includes(r)||(this._log.debug(`received ${r} msg: ${e.data}`),l&&this._log.info(`Received event: [ ${l} ]`)),r){case bi.CHANNEL_SETUP_RESULT:{if(t.code===0)this._signalInfo.clientIp=o.clientIp,this._signalInfo.signalIp=o.signalInnerIp,o.svrTime&&gm(o.svrTime),this._log.info(`ChannelSetup Success ${le()-this._connectStartTime}`),Q.addSuccessEvent({key:521701,cost:le()-this._connectStartTime}),this._connectStartTime=-1,this.emit(rt.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let h=new X({code:H.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:pe({key:me.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error(`${t.code}, ${t.message}`),this.close(),Q.addFailedEvent({key:521701,error:h}),this.emit(rt.SETUP_FAILED,h)}break}case bi.JOIN_ROOM_RESULT:{t.code===0&&(this._signalInfo.relayIp=o.relayOuterIp,this._signalInfo.relayInnerIp=o.relayInnerIp,this._signalInfo.bakRelayIps=o.bakRelayIps,this._signalInfo.relayPort=o.relayPort,this._signalInfo.tinyId=t.tinyId,this._signalInfo.endReportExtend=o.endReportExtend,this._log.info(`signalIp:${this._signalInfo.signalIp} clientIp:${this._signalInfo.clientIp} relayIp: ${this._signalInfo.relayIp}`)),this.emit(l,{data:t});break}default:this.emit(String(l),{data:t});break}}reGetSignalChannelUrl(){return A(this,null,function*(){try{if(!this.room.joinParams)return;yi(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(e){}})}startReconnection(){if(!this._socketInUse)return;this._socketInUse.onclose=null,this._socketInUse.close(4011);let e=this._socketInUse===this._socket;this.unbindAndCloseSocket(e?S.MAIN:S.BACKUP),this._socketInUse=null,this.emitConnectionStateChanged("DISCONNECTED"),this.reconnect()}reconnect(){return A(this,null,function*(){if(!this._isReconnecting){if(!this.room.isJoined&&this.keepAlive){this.close();return}this._isReconnecting=!0;try{this._log.warn("reconnect"),yield this.connect();let{roomId:e,useStringRoomId:t}=this.room,{relayIp:r,relayInnerIp:o,relayPort:n}=this._signalInfo,{data:a}=yield this.sendWaitForResponse({command:ve.RECONNECT_WS,data:{roomId:e,useStringRoomId:t,relayInnerIp:o,relayOuterIp:r,relayPort:n},responseCommand:Ee.CHANNEL_RECONNECT_RESULT});a.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),Q.addSuccessEvent({key:521702,cost:le()-this._connectStartTime}),this._connectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(Q.addFailedEvent({key:521702,error:a.code}),this._log.warn(`reconnect failed, ${a.code} ${a.message}`),this.room.reJoin())}catch(e){this._log.error(e),this.room.reJoin()}}})}send(e,t={}){if(this.isConnected&&!this.room.isLeft){let r={cmd:e,data:t,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},o=JSON.stringify(r);return this._socketInUse.send(o),this.bytesSent+=ln(o),r.seq}}sendWaitForResponse({command:e,data:t,timeout:r=5e3,responseCommand:o,commandDesc:n,enableLog:a=!0,addReceiveTime:d=!1}){return new Promise((l,h)=>{let u=setTimeout(()=>{this.off(o,p);let f=new X({code:H.API_CALL_TIMEOUT,message:pe({key:me.API_CALL_TIMEOUT,data:{commandDesc:n,command:e}})});a&&this._log.warn(f),h(f)},r),m=Date.now(),p=f=>{f.data.seq===g&&(clearTimeout(u),this.off(o,p),d&&(f.data.receiveTime=Date.now()),l(f))};this.on(o,p);let g=this.send(e,t)})}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:r,retries:o=0,retryTimeout:n=0}=e;return Ui({retryFunction:this.sendWaitForResponse,onError:({retry:a})=>{this.isOnline?a():(this._log.warn(`retry ${r} when connected`),this.once(rt.CONNECTED,a))},onRetrying:a=>{this._log.warn(`${t||r} timeout observed, retrying [${a}/${o}]`)},settings:{retries:o,timeout:n},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),clearTimeout(this.stopKeepAliveTimeout),wc.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,bakRelayIps:[],endReportExtend:void 0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(S.MAIN),this.unbindAndCloseSocket(S.BACKUP),this.emitConnectionStateChanged("DISCONNECTED")}destroy(){this.close(),this.destroyed=!0}getBackupRelayIpPair(){var t;let e=(t=this._signalInfo.bakRelayIps)==null?void 0:t.shift();return e&&(e.relayPort=e.relayPort||this._signalInfo.relayPort),e}clearBakRelayIps(){this._signalInfo.bakRelayIps=[]}stopKeepAliveIn(e=3600){if(this.keepAlive){this._log.info(`stopKeepAlive in ${e}s`),this.stopKeepAliveTimeout=setTimeout(()=>{this.keepAlive=!1,this._log.info(`close due to not used ${e}s`),this.close(),this.off(Ee.JOIN_ROOM_RESULT,t)},e*1e3);let t=r=>{r.data.code===0&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(Ee.JOIN_ROOM_RESULT,t))};this.on(Ee.JOIN_ROOM_RESULT,t)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info(`${this._currentState} -> ${e}`),this.emit(rt.CONNECTION_STATE_CHANGED,{prevState:this._currentState,state:e}),this._currentState=e,e==="CONNECTED"?this.emit(rt.CONNECTED):e==="DISCONNECTED"&&this.emit(rt.DISCONNECTED))}};J([Gt({settings:{retries:1/0,timeout:2e3},onError(e,t){!this.room.isDestroyed&&!this.destroyed&&t()},onRetrying(e,t){this._log.warn(`retrying to connect ${e}`),e>=3&&e%3===0&&this.reGetSignalChannelUrl(),t&&(this._stopConnectRetry=t,(this.room.isDestroyed||this.destroyed)&&t())}})],Vo.prototype,"connect",1);var Yf=gt(Mt());var Hh=0,Gh=!1,Mc=new Set,AS=s=>Hh>2&&!Gh&&Mc.size===0&&s,Wh=!1,$t=class{constructor(i){c(this,"userId");c(this,"tinyId");c(this,"_sdpSemantics");c(this,"_isUplink");c(this,"_room");c(this,"_log");c(this,"_signalChannel");c(this,"_isErrorObserved",!1);c(this,"_waitForPeerConnectionConnectedPromise");c(this,"_waitForPeerConnectionConnectedPromiseReject",null);c(this,"_peerConnection",null);c(this,"_emitter",new Yf.default);c(this,"_currentState","DISCONNECTED");c(this,"_isReconnecting",!1);c(this,"_reconnectionCount",0);c(this,"_reconnectionTimer",-1);c(this,"_isFirstConnection",!0);c(this,"_prevTime",-1);c(this,"_localAddress");c(this,"_remoteAddress");this.userId=i.userId,this.tinyId=i.tinyId,this._room=i.room,this._sdpSemantics=i.room.sdpSemantics,this._isUplink=i.isUplink,this._log=z.createLogger({id:"n-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=i.signalChannel}beforeConnect(){this._prevTime<0&&(this._prevTime=le())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,Q.addSuccessEvent({key:521705,cost:Math.min(le()-this._prevTime,30*1e3)})):this._isReconnecting&&Q.addSuccessEvent({key:521706,cost:le()-this._prevTime}),this._prevTime=-1}catch(i){throw this._isFirstConnection?(this._isFirstConnection=!1,Q.addFailedEvent({key:521705,error:i})):this._isReconnecting&&this._reconnectionCount>=3&&Q.addFailedEvent({key:521706,error:i}),i}}initialize(){let i={iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"};this._peerConnection=new RTCPeerConnection(i),this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this)}close(i){this._log.info("close connection"),this._emitter.emit("closed",i),this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),Mc.delete(this)}closePeerConnection(i=!1){this._peerConnection&&(this._log.info("close pc"),this._peerConnection.onconnectionstatechange=null,this._peerConnection.close(),this._peerConnection=null,i&&this.emitConnectionStateChangedEvent("DISCONNECTED")),this._waitForPeerConnectionConnectedPromiseReject&&this._waitForPeerConnectionConnectedPromiseReject(new X({code:H.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return hi;let i=null;if(this._isUplink){if(!Qr()||this._peerConnection.getSenders().length===0)return hi;i=this._peerConnection.getSenders()[0].transport}else{if(!Rs()||this._peerConnection.getReceivers().length===0)return hi;i=this._peerConnection.getReceivers()[0].transport}return i?i.state:hi}onConnectionStateChange(i){let e=this._peerConnection.iceConnectionState,t=this.getDTLSTransportState();if(this._log.info(`connectionState: ${i.target.connectionState}, ICE: ${e}, DTLS: ${t}`),i.target.connectionState===Je.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),i.target.connectionState===Je.FAILED||i.target.connectionState===Je.CLOSED){let r=`connection ${i.target.connectionState}. ICE Transport state: ${e}, DTLS Transport state: ${t}`,o=new X({message:r,code:H.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",o)}(i.target.connectionState===Je.CONNECTED||i.target.connectionState===Je.COMPLETED)&&(this.logSelectedCandidate(),Me.logSuccessEvent({userId:this._room.userId,eventType:Ft.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(i){return i===this._currentState?!1:(i==="CONNECTED"?(Hh=0,Gh=!1,Wh=!0,Mc.add(this)):Mc.delete(this),x.emit(B.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:i,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:i}),this._currentState=i,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}logSelectedCandidate(){return A(this,null,function*(){if(!this._peerConnection)return;let i=yield this._peerConnection.getStats();for(let[,e]of i)if(Xr(e)){let t=i.get(e.localCandidateId),r=i.get(e.remoteCandidateId);t&&(this._log.info(`local candidate: ${t.candidateType} ${t.protocol}:${t.ip||t.address}:${t.port} ${t.networkType||""} ${t.candidateType==="relay"?`relayProtocol:${t.relayProtocol}`:""}`),this._localAddress=`${t.ip||t.address}:${t.port}`),r&&(this._log.info(`remote candidate: ${r.candidateType} ${r.protocol}:${r.ip||r.address}:${r.port}`),this._remoteAddress=`${r.protocol}:${r.ip||r.address}`);break}})}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise?this._waitForPeerConnectionConnectedPromise:(this._waitForPeerConnectionConnectedPromise=new Promise((i,e)=>{if(this._currentState==="CONNECTED")return i();this._waitForPeerConnectionConnectedPromiseReject=e;let t=a=>{a.state==="CONNECTED"&&(clearTimeout(n),o(),i())},r=({room:a})=>{a===this._room&&(clearTimeout(n),o(),e(new X({code:H.API_CALL_ABORTED,message:pe({key:me.CONNECTION_ABORTED,data:"leave room"})})))},o=()=>{x.off(B.LEAVE_SUCCESS,r,this),this._emitter.off("connection-state-changed",t,this)},n=setTimeout(()=>{o();let a=new X({code:H.API_CALL_TIMEOUT,message:"connection timeout"});Hh+=1,AS(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),Gh=!0,this._emitter.emit("firewall-restriction")),e(a)},on);x.on(B.LEAVE_SUCCESS,r,this),this._emitter.on("connection-state-changed",t,this)}),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally(()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null}),this._waitForPeerConnectionConnectedPromise)}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(rt.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=dr()){this._log.warn(`SDK has tried reconnect for ${this._reconnectionCount} times, but all failed, please check your network`),this.stopReconnection();let i=new X({code:this._isUplink?H.UPLINK_RECONNECTION_FAILED:H.DOWNLINK_RECONNECTION_FAILED,message:pe({key:this._isUplink?me.UPLINK_RECONNECTION_FAILED:me.DOWNLINK_RECONNECTION_FAILED})});return this.emitConnectionStateChangedEvent("DISCONNECTED"),this._emitter.emit("error",i),-1}return this._signalChannel.isConnected?(this._reconnectionCount+=1,this._log.warn(`reconnect() trying [${this._reconnectionCount}]`),1):(this._log.warn("reconnect() signal channel is not connected, suspend reconnection until signal is connected"),this._signalChannel.once(rt.CONNECTED,this.reconnect,this),-1)}on(i,e,t){this._emitter.on(i,e,t)}off(i,e,t){this._emitter.off(i,e,t)}getIsReconnecting(){return this._isReconnecting}get isH264(){var i,e;return!!((e=(i=this._peerConnection)==null?void 0:i.remoteDescription)!=null&&e.sdp.includes("H264"))}setOffer(i){var e;return(e=this._peerConnection)==null?void 0:e.setLocalDescription(i)}setAnswer(i){var e;return(e=this._peerConnection)==null?void 0:e.setRemoteDescription(i)}};J([zt(521712,!1)],$t.prototype,"setOffer",1),J([zt(521713,!1)],$t.prototype,"setAnswer",1);var qh=gt(Jh());var et=function(s){return qh.default.parse(s)},li=function(s){return qh.default.write(s)},o_=function(s){let i=et(s);return i.media.forEach(e=>{e.type===S.AUDIO&&e.fmtp.forEach(t=>{t.config+=";sprop-stereo=1;stereo=1"})}),li(i)};function n_(s){let i=et(s);return i.media.forEach(e=>{var t,r;if(e.type===S.VIDEO){let o=new Set;e.rtp.forEach(({payload:a,codec:d})=>d==="H264"&&o.add(a)),e.fmtp.forEach(({payload:a,config:d})=>{let l=d.match(/apt=(\d+)/);l&&l[1]&&o.has(Number(l[1]))&&o.add(a)});let n=({payload:a})=>!o.has(a);e.rtp=e.rtp.filter(n),e.rtcpFb=(t=e.rtcpFb)==null?void 0:t.filter(n),e.fmtp=e.fmtp.filter(n),e.payloads=(r=e.payloads)==null?void 0:r.split(" ").filter(a=>!o.has(Number(a))).join(" ")}}),li(i)}function xc(s){return Object.keys(s).filter(i=>s[i])}var $o=class $o extends $t{constructor(e){super(de(Z({},e),{isUplink:!1}));c(this,"_flag",0);c(this,"isRobot",!1);c(this,"role","anchor");c(this,"remoteAudioTrack");c(this,"remoteVideoTrack");c(this,"remoteAuxiliaryTrack");c(this,"ssrc",{audio:0,video:0,auxiliary:0});c(this,"_isSDPExchanging",!1);this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=e.remoteAudioTrack||new Ci(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new er(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new Do(this._room,this)}get videoCodec(){var t,r;let e=(r=(t=this._peerConnection)==null?void 0:t.remoteDescription)==null?void 0:r.sdp;return e?e.includes("H264")?"h264":"vp8":"h264"}get subscribeState(){let e={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(this.remoteVideoTrack.mediaType&8?e.smallVideo=!0:e.video=!0),this.remoteAudioTrack.isSubscribed&&(e.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(e.auxiliary=!0),e}get muteState(){return ur(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,r,o;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(r=this.remoteVideoTrack)==null||r.onFlagChanged(),(o=this.remoteAuxiliaryTrack)==null||o.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===S.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var o,n;let t=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&t!==e&&((o=this.remoteVideoTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),r}onTrack(e){let t=e.streams[0],{track:r}=e,o=t.id===sn?S.MAIN:S.AUXILIARY;this._log.debug(`ontrack ${o} ${r.kind}`);let n=S.AUDIO;r.kind===S.VIDEO&&(n=o===S.MAIN?S.VIDEO:S.AUXILIARY);let a=this.remoteAudioTrack;n===S.VIDEO?a=this.remoteVideoTrack:n===S.AUXILIARY&&(a=this.remoteAuxiliaryTrack),a.setInputMediaStreamTrack(r)}addRRTRLine(e){let t=e.split(`\r
|
|
73
|
+
${P}`);se.file("audioProcessor_big_gap_data.txt",new Blob([he]))}let y=yield se.generateAsync({type:"blob"}),G=URL.createObjectURL(y),E=document.createElement("a");E.href=G,E.download=`${i}-audio-${g}.zip`,E.style.display="none",document.body.appendChild(E),E.click(),URL.revokeObjectURL(G),E.remove(),this.addInfoToBanner(xr,`Dump success, file name is: ${i}-${g}.zip`),this._core.trtc.off(ne.AUDIO_FRAME,b),this._core.innerEmitter.off("265",w),((ee=f==null?void 0:f.audioProcessor)!=null&&ee.node||T!=null&&T.audioProcessor.node)&&this._core.trtc.updatePlugin("AudioProcessor",{enableDump:!1}),r&&clearTimeout(r),m.abort("download")});return e>0&&(r=Number(setTimeout(()=>{m.abort("timeout")},e*1e3))),o.length>0&&this._core.startGetPCM(o).then(se=>se.pipeTo(new WritableStream({write(y){y.forEach((G,E)=>{a[E]=a[E]?a[E].concat(G[0]):[G[0]]})}}),m).catch(()=>N)),{download:N,onDumpEnd:()=>{m.abort("timeout")}}}formatStartDumpTime(i){let e=new Date(i),t=e.getFullYear(),r=this.pad(e.getMonth()+1),o=this.pad(e.getDate()),n=this.pad(e.getHours()),a=this.pad(e.getMinutes()),d=this.pad(e.getSeconds()),l=-e.getTimezoneOffset(),h=Math.floor(Math.abs(l)/60),u=Math.abs(l)%60,m=l>=0?"+":"-";return`${t}-${r}-${o}T${n}-${a}-${d}${m}${this.pad(h)}-${this.pad(u)}`}};J([ra(300,()=>"export")],da.prototype,"onExportClick",1),J([ra(300,()=>"upload")],da.prototype,"onUploadClick",1);var Ff=da;var gS=0;var Uo=class Uo{constructor(i){this.core=i;c(this,"_core");c(this,"log");c(this,"dumpLocalVideoMap",{});c(this,"dumpRemoteVideoMap",{});c(this,"dialog");this._core=i,this.log=i.log.createChild({id:`${this.getAlias()}${++gS}`}),this.log.info("created")}getName(){return Uo.Name}getAlias(){return"dm"}getGroup(){return"dm"}getValidateRule(i){switch(i){case"start":return{name:"StartDebugOptions",required:!1};case"update":return{name:"UpdateDebugOptions",required:!1};case"stop":return{name:"StopDebugOptions",required:!1}}}start(){return A(this,null,function*(){var e;!new URLSearchParams(location.search).has("trtcDebug")&&((e=window.sessionStorage)==null?void 0:e.getItem("TRTC_ENABLE_DEBUG_PLUGIN"))!=="true"||(yield this.openDebugDiaLog(),this.addVideoProcessor())})}update(e){return A(this,arguments,function*({forceOpen:i}){M(i)&&(i?(yield this.openDebugDiaLog(),this.addVideoProcessor()):(this.closeDebugDiaLog(),this.removeVideoProcessor()))})}stop(){this.closeDebugDiaLog(),this.removeVideoProcessor()}destroy(){this.stop()}openDebugDiaLog(){return A(this,null,function*(){if(!this.dialog)try{this.dialog=new Ff(this._core,this.log,this.dumpLocalVideoMap,this.dumpRemoteVideoMap),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(i){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(i))}})}closeDebugDiaLog(){this.dialog&&(this.dialog.closeDialog(),this.dialog=null)}addVideoProcessor(){this._core.room.videoManager.addEncodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.encodeVideo.bind(this):kh,type:1}),this._core.room.videoManager.addDecodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.decodeVideo.bind(this):Oh,type:1})}removeVideoProcessor(){this._core.room.videoManager.removeEncodeProcessor({type:1}),this._core.room.videoManager.removeDecodeProcessor({type:1})}encodeVideo({frame:i,mediaType:e}){return kh({frame:i,onDump:()=>{if(!e)return;let t=e===2?"sub":"main",r=this.dumpLocalVideoMap[t];r&&(r.data.push(i.data.slice(0)),r.duration>0&&Date.now()-r.startTimestamp>r.duration*1e3&&r.onDumpEnd())}})}decodeVideo({frame:i,track:e}){return Oh({frame:i,onDump:()=>{if(!e)return;let t=this.dumpRemoteVideoMap[`${e.userId}-${e.streamType}`];t&&(t.data.push(i.data.slice(0)),t.duration>0&&Date.now()-t.startTimestamp>t.duration*1e3&&t.onDumpEnd())}})}loadScript(i){return new Promise((e,t)=>{this.log.info(`loading debug dialog from ${i}`);let r=document.createElement("script");r.type="text/javascript",r.onload=e,r.onerror=t,r.crossOrigin="anonymous",r.src=i,document.head.append?document.head.append(r):document.getElementsByTagName("head")[0].appendChild(r)})}};c(Uo,"Name","Debug"),c(Uo,"autoStart",!0),J([Gt({settings:{timeout:3e3,retries:3},onError(i,e,t){var r;(r=i==null?void 0:i.message)!=null&&r.includes("timeout")?e():t(i)}})],Uo.prototype,"loadScript",1);var kc=Uo;var Hf=s=>{switch(s){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},Oc=class{constructor(i,e,t){c(this,"trackDoneOB");c(this,"startOB");c(this,"stopOB");c(this,"inputFrameCount",0);c(this,"decodedFrameCount",0);c(this,"type","auto");c(this,"config");c(this,"decoder");c(this,"_decodeSink");let{kvStatManager:r,trtc:o}=i;this.config=t.config,this.trackDoneOB=We(e,ge.INIT),this.stopOB=Vt(),this.startOB=Vt(),t.type==="auto"?this.type="webCodecs":this.type=t.type;let n=Vt(),a=d=>{let l=this.pipe(e);return n.next("STARTING"),e.log.info(`decoder type: ${this.type}`),He(l,St(this.stopOB),it(()=>{},h=>{e.log.error(h),r.addFailedEvent({key:Hf(this.type),error:h}),d>4?this.startOB.error(h):this.startOB.next(d+1)})),He(l,Dr(1),sh(Yn))};He(this.startOB,Xn(0),yo(a),St(this.stopOB),it(()=>{e.player.setOutput(),n.next("STARTED")},d=>{n.next("FAILED")},()=>{r.addSuccessEvent({key:Hf(this.type)}),r.addSuccessEvent({key:504702})}))}mock(i){this._decodeSink?this._decodeSink.error(i):this.startOB.next(0)}close(i){this.stopOB.next(i)}pipe(i){return Nr()(e=>A(this,null,function*(){this._decodeSink=e,e.defer(()=>{var r;(r=this.decoder)==null||r.close()});let{type:t}=this;try{switch(t){case"webCodecs":this.decoder=new AudioDecoder({error:r=>{i.log.error(r),e.error(4)},output:r=>{this.decodedFrameCount++,e.next(r),i.player.write(r)}});break;case"wasm":break}this.decoder.configure(this.config)}catch(r){i.log.error(r),e.error(t==="webCodecs"?2:6)}}))}decodeFrame(i){var e;this.inputFrameCount++,((e=this.decoder)==null?void 0:e.state)==="configured"&&this.decoder.decode(new EncodedAudioChunk({data:i.data,timestamp:i.timestamp,type:"key"}))}},ES={type:"object"},la=class la{constructor(i){this.core=i;c(this,"log");c(this,"contextMap",new Map);c(this,"decodeProcessorMap",new WeakMap);this.log=i.log.createChild({id:`${this.getAlias()}`})}getAlias(){return la.Name}getGroup(i){return i.track.userId+i.track.streamType}getName(){return la.Name}getValidateRule(i){return ES}start(i){let{track:e}=i;this.decodeProcessorMap.set(e,this.decode(i)),this.core.room.audioManager.addDecodeProcessor({processor:({frame:t,track:r})=>this.decodeProcessorMap.has(r)?this.decodeProcessorMap.get(r)({frame:t,track:r}):t,type:3})}decode(i){return({frame:e,track:t})=>{if(t!==i.track)return e;if(this.contextMap.has(t))return this.contextMap.get(t).decodeFrame(e);let r=new Oc(this.core,t,i);return He(r.trackDoneOB,Dr(1),it(()=>{this.core.clearStarted(this,this.getGroup(i)),this.stop({track:t})})),this.contextMap.set(t,r),r.decodeFrame(e)}}stop({track:i}){let e=this.contextMap.get(i);e&&(e.close("stop"),this.contextMap.delete(i),this.contextMap.size===0&&this.core.room.audioManager.removeDecodeProcessor({type:3}))}update(i){let e=this.contextMap.get(i.track);if(e){if(i.type==="mock"){e.mock(10);return}e.close("update"),this.contextMap.set(i.track,new Oc(this.core,i.track,i))}}};c(la,"Name","TRTCAudioDecoder");var ua=la;var Gf=0,ha=new Set,At=null;Zc(If);po.checkStorage();nu();var TS={RtcError:ue,ErrorCode:fe,ErrorCodeDictionary:Ri},Ie=class Ie extends Wf.EventEmitter{constructor(e,t){super();c(this,"_room");c(this,"_eventListened",new Set);c(this,"_localVideoTrack",null);c(this,"_localAudioTrack",null);c(this,"_localScreenTrack",null);c(this,"_localScreenAudioTrack",null);c(this,"_localVideoConfig",null);c(this,"_localScreenConfig",null);c(this,"_localAudioConfig",null);c(this,"_remoteVideoConfigMap",new Map);c(this,"_remoteAudioConfigMap",new Map);c(this,"_remoteAudioVolumeMap",new Map);c(this,"_remoteAudioMuteMap",new Map);c(this,"_mediaTrackMap",new WeakMap);c(this,"_log",z.createLogger({id:`t${++Gf}`}));c(this,"_plugins",new Map);c(this,"_networkQuality",null);c(this,"_speakerId");c(this,"_getPCMAbortCtrl");this._room=new e(Z({logger:this._log,frameWorkType:Ie.frameWorkType},t)),this._room.videoDecodeFallbackType=t.videoDecodeFallback,this._log.info(`create() ${JSON.stringify(t,(r,o)=>r==="plugins"?o.map(n=>n.Name):o)}`),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(r){return this._room.audioManager.dump(r)}}}),t.plugins&&t.plugins.forEach(r=>{this._use(r,t.assetsPath)}),this._use(_c,t.assetsPath),this._use(pc,t.assetsPath),this._use(Ec,t.assetsPath),this._use(ua,t.assetsPath||ba),this._use(kc),t.enableSEI&&xn&&this._use(Tc),this._room.on("audio-volume",r=>{!r.find(o=>o.userId==="")&&this._localAudioTrack&&r.push({userId:"",volume:Math.floor(this._localAudioTrack.getAudioLevel()*100)}),t.volumeType===1&&r.forEach(o=>{var a;let n=o.userId===""?this._localAudioTrack:(a=this.room.remotePublishedUserMap.get(o.userId))==null?void 0:a.remoteAudioTrack;n&&(o.volume=n.dbVolume)}),this.emit(ne.AUDIO_VOLUME,{result:r.sort((o,n)=>n.volume-o.volume)})}),this._room.videoManager.on("error",r=>{this._log.error(new ue({code:fe.OPERATION_FAILED,extraCode:5504,message:r.message,originError:r}))}),this._listenEvents(),this._initActiveSpeaker(),Tf(this,"trtc")}static create(e){}static _create(e,t){nf();let r=new Ie(e,t||{});return ha.add(r),r}get room(){return this._room}_listenEvents(){vt(this,this._room).add("peer-join",e=>{let{userId:t}=e;this.emit(ne.REMOTE_USER_ENTER,{userId:t})}).add("peer-leave",e=>{this.emit(ne.REMOTE_USER_EXIT,{userId:e}),this._remoteAudioVolumeMap.delete(e)}).add("banned",e=>{this._exitRoom().finally(()=>{this.emit(ne.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().finally(()=>{this.emit(ne.ERROR,ue.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(ne.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let t=de(Z({},e),{uplinkRTT:Math.min(e.uplinkRTT,an),downlinkRTT:Math.min(e.downlinkRTT,an)});this.emit(ne.NETWORK_QUALITY,t)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(r=>{vt(r,r).add("player-state-changed",o=>{let n=de(Z({},o),{userId:e.userId});r.kind===S.VIDEO&&(n.streamType=is(r.streamType)),this.emit(r.kind===S.AUDIO?ne.AUDIO_PLAY_STATE_CHANGED:ne.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",o=>{o.getCode()===H.PLAY_NOT_ALLOWED&&this.emit(ne.AUTOPLAY_FAILED,{userId:r.userId,resume:()=>r.player.resume()})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(r=>{at(r)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:t})=>{let{userId:r}=t,o=e.audioAvailable,n=e.videoAvailable,{audioAvailable:a,videoAvailable:d}=t;a||this._remoteAudioConfigMap.delete(r),d||this._removeRemoteVideoConfig(r,"main"),t.hasAuxiliary||this._removeRemoteVideoConfig(r,"sub"),n!==d&&(d?this._onVideoAvailable({userId:r,streamType:"main"}):this._onVideoUnavailable({userId:r,streamType:"main"}),this.emit(d?ne.REMOTE_VIDEO_AVAILABLE:ne.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"main"})),o!==a&&(a?this._onAudioAvailable({userId:r}):this._onAudioUnavailable({userId:r,muteState:t}),this.emit(a?ne.REMOTE_AUDIO_AVAILABLE:ne.REMOTE_AUDIO_UNAVAILABLE,{userId:r})),e.hasAuxiliary!==t.hasAuxiliary&&(t.hasAuxiliary?this._onVideoAvailable({userId:r,streamType:"sub"}):this._onVideoUnavailable({userId:r,streamType:"sub"}),this.emit(t.hasAuxiliary?ne.REMOTE_VIDEO_AVAILABLE:ne.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"sub"}))}).add("sei-message",e=>{this.emit(ne.SEI_MESSAGE,de(Z({},e),{streamType:is(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(ne.ERROR,new ue({code:fe.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var o,n,a,d,l,h,u;let t={2:"big",3:"small",7:"sub"},r={rtt:Math.min(e.msg_up_stream_info.msg_network_status.uint32_rtt||((o=e.msg_down_stream_info[0])==null?void 0:o.msg_network_status.uint32_rtt)||((n=this._networkQuality)==null?void 0:n.uplinkRTT)||((a=this._networkQuality)==null?void 0:a.downlinkRTT)||0,an),upLoss:((d=this._networkQuality)==null?void 0:d.uplinkLoss)||0,downLoss:((l=this._networkQuality)==null?void 0:l.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((h=e.msg_up_stream_info.msg_audio_status)==null?void 0:h.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((u=e.msg_up_stream_info.msg_audio_status)==null?void 0:u.uint32_audio_level)||0)/ai},video:e.msg_up_stream_info.msg_video_status.filter(m=>t[m.uint32_video_stream_type]).map(m=>({bitrate:(m.uint32_video_codec_bitrate||0)/1e3,width:m.uint32_video_width,height:m.uint32_video_height,frameRate:m.uint32_video_enc_fps,videoType:t[m.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(m=>({userId:m.msg_user_info.str_identifier,audio:{bitrate:(m.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(m.msg_audio_status.uint32_audio_level||0)/ai},video:m.msg_video_status.map(p=>({bitrate:(p.uint32_video_codec_bitrate||0)/1e3,width:p.uint32_video_width,height:p.uint32_video_height,frameRate:p.uint32_video_dec_fps,videoType:t[p.uint32_video_stream_type]}))}))};this.emit(ne.STATISTICS,r)}).add("custom-message",e=>{this.emit(ne.CUSTOM_MESSAGE,e)}).add("layerData",e=>this.emit(ne.LAYER_DATA,e)).add("first-video-frame",e=>{this.emit(ne.FIRST_VIDEO_FRAME,de(Z({},e),{streamType:is(e.streamType)}))}),vt(this,ft).add("audioInputAdded",e=>{this.emit(ne.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(ne.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(ne.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(ne.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>A(this,null,function*(){if(this.emit(ne.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),At&&At.deviceId===nn){let t=(yield Yr()).find(r=>r.deviceId===nn);t&&At.groupId!==t.groupId&&(At=t,this.emit(ne.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}})).add("audioOutputRemoved",e=>A(this,null,function*(){this.emit(ne.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield Yr())[0];if(!t||!At||At.groupId===t.groupId)return;let r=At.deviceId===e.deviceId,o=At.deviceId===nn&&At.deviceId===t.deviceId;(r||o)&&(At=t,this.emit(ne.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}))}use(e){let t,r;"plugin"in e?(t=e.plugin,r=e.assetsPath):t=e,this._use(t,r||ba)}_use(e,t){if(this._plugins.get(e.Name)){this._log.warn("duplicate install plugin",e.Name);return}let o=new e(Ef.call(this,{TRTC:Ie,room:this._room,errorModule:TS,assetsPath:t}));this._plugins.set(e.Name,o),e.autoStart&&this.startPlugin(e.Name)}enterRoom(e){return A(this,null,function*(){var d,l;let{scene:t="rtc",enableAutoPlayDialog:r=!0,autoReceiveAudio:o=!0,autoReceiveVideo:n=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!Oe(e.proxy)&&e.proxy.turnServer&&((l=(d=this._room).setTurnServer)==null||l.call(d,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=r,this._room.autoReceiveAudio=o,this._room.autoReceiveVideo=n,Qe(e.preferHW)&&(this._room.preferHW=e.preferHW),e.playoutDelay&&(this._room.playoutDelay=e.playoutDelay),e.jitterBufferDelay&&(this._room.jitterBufferDelay=e.jitterBufferDelay);let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:e.role==="audience"?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language,priority:e.priority,useVp8:e.useVp8,keepAlive:e.keepAlive};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(a,t,Ie.frameWorkType),this._checkTrackToPublish(),Ah.start()})}exitRoom(){return A(this,null,function*(){return yield this._exitRoom()})}switchRole(e,t){return A(this,null,function*(){t!=null&&t.privateMapKey&&(this._room.privateMapKey=t.privateMapKey),t!=null&&t.latencyLevel&&(this._room.latencyLevel=t.latencyLevel),yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){at(this),this.removeAllListeners(),this._room.destroy(),ha.delete(this),ha.size===0&&Ah.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),this._plugins.forEach(e=>{var t;return(t=e.destroy)==null?void 0:t.call(e)}),this._plugins.clear(),x.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return A(this,arguments,function*(e={publish:!0}){if(this._localAudioTrack){this._log.warn("local audio is already started");return}let{publish:t=!0,mute:r,option:o}=e,n=new ti(this._room.audioManager),a={},d={muted:!0};o&&(M(o.microphoneId)?M(o.audioTrack)||(a.customSource=o.audioTrack):a.deviceId=o.microphoneId,o&&De(o.captureVolume)&&n.setCaptureVolume(o.captureVolume),M(o.profile)||(Oe(o.profile)?Da[o.profile]&&n.setProfile(Da[o.profile]):n.setProfile(o.profile)),De(o.earMonitorVolume)&&(d.muted=!(o.earMonitorVolume>0),d.volume=o.earMonitorVolume),M(o.echoCancellation)||(n.profile.echoCancellation=o.echoCancellation),M(o.noiseSuppression)||(n.profile.noiseSuppression=o.noiseSuppression),M(o.autoGainControl)||(n.profile.autoGainControl=o.autoGainControl)),n.on("5",l=>{this.emit(ne.ERROR,new ue({code:fe.DEVICE_ERROR,extraCode:5309,messageParams:{error:l}}))}),n.on("2",l=>{this.emit(ne.DEVICE_CHANGED,{type:"microphone",action:"active",device:l})}),n.on("4",l=>{let h;l.error&&(h=ue.convertFrom(l.error)),this.emit(ne.PUBLISH_STATE_CHANGED,de(Z({},l),{error:h}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId),yield n.capture(a),M(r)||n.setMute(r),vt(n,n).add("player-state-changed",l=>{this.emit(ne.AUDIO_PLAY_STATE_CHANGED,de(Z({},l),{userId:""}))}),this.listeners(ne.AUDIO_FRAME).length>0&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM(l=>{this.emit(Ie.EVENT.AUDIO_FRAME,{data:l})})),this._getPCMAbortCtrl&&n.on("input-media-track-changed",()=>{this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("inputMediaTrackChanged"),this._getPCMAbortCtrl=this._room.audioManager.getPCM(l=>{this.emit(Ie.EVENT.AUDIO_FRAME,{data:l})}))}),t&&this._room.isJoined&&this._room.publish(n).catch(()=>{}),this._localAudioTrack=n,this._localAudioConfig=de(Z({},e),{publish:t}),yield this._updateAudioPlayOption({playOption:d,track:n})})}updateLocalAudio(e){return A(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:r,option:o}=e,n={};o&&(o.microphoneId?yield this._localAudioTrack.switchDevice(o.microphoneId):M(o.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(o.audioTrack)),M(o.captureVolume)||this._localAudioTrack.setCaptureVolume(o.captureVolume),M(o.earMonitorVolume)||(n.muted=!(o.earMonitorVolume>0),n.volume=o.earMonitorVolume),yield this._localAudioTrack.update3A(o)),this._room.isJoined&&!M(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),M(r)||this._localAudioTrack.setMute(r),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),Li(this._localAudioConfig,e)})}stopLocalAudio(){return A(this,null,function*(){this._localAudioTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),at(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null,this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("stopLocalAudio"),delete this._getPCMAbortCtrl))})}startLocalVideo(){return A(this,arguments,function*(e={publish:!0,view:null}){if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:t,publish:r=!0,mute:o,option:n}=e,a=new Nt(this._room.videoManager),d={},l={};Qe(n==null?void 0:n.avoidCropping)&&(a.avoidCropping=n.avoidCropping),n&&(n.cameraId?d.deviceId=n.cameraId:M(n.useFrontCamera)?M(n.videoTrack)||(d.customSource=n.videoTrack):d.facingMode=n.useFrontCamera?S.FACING_MODE_USER:S.FACING_MODE_ENVIRONMENT,n.qosPreference&&(d.contentHint=ia(n.qosPreference)),M(n.profile)||(Oe(n.profile)?si[n.profile]&&a.setProfile(si[n.profile]):a.setProfile(n.profile)),M(n.fillMode)||(l.objectFit=n.fillMode),M(n.mirror)||(l.mirror=n.mirror),M(n.small)||(On()?Oe(n.small)?a.small=si[n.small]:n.small===!0?a.small=si["120p"]:a.small=n.small:this._log.warn("small stream is not supported"))),a.once("first-video-frame",h=>{this.emit(ne.FIRST_VIDEO_FRAME,de(Z({},h),{streamType:is(h.streamType)}))}),a.on("5",h=>{this.emit(ne.ERROR,new ue({code:fe.DEVICE_ERROR,extraCode:5308,messageParams:{error:h}}))}),a.on("2",h=>{this.emit(ne.DEVICE_CHANGED,{type:"camera",action:"active",device:h})}),a.on("4",h=>{let u;h.error&&(u=ue.convertFrom(h.error)),this.emit(ne.PUBLISH_STATE_CHANGED,de(Z({},h),{error:u}))}),this._listenOutputTrackChanged(a),yield a.capture(d),M(o)||(yield a.setMute(o)),vt(a,a).add("player-state-changed",h=>{this.emit(ne.VIDEO_PLAY_STATE_CHANGED,de(Z({},h),{userId:"",streamType:"main"}))}),r&&this._room.isJoined&&this._room.publish(a).catch(()=>{}),this._localVideoTrack=a,this._localVideoConfig=de(Z({},e),{view:t,publish:r}),yield this._updateVideoPlayOption({view:t,playOption:l,track:a})})}updateLocalVideo(e){return A(this,null,function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:r,mute:o,option:n}=e,a={};if(n)if(M(n.profile)||(Oe(n.profile)?si[n.profile]&&this._localVideoTrack.setProfile(si[n.profile]):this._localVideoTrack.setProfile(n.profile),(!n.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(n.cameraId))&&M(n.useFrontCamera)&&(yield this._localVideoTrack.applyProfile())),n.cameraId?yield this._localVideoTrack.switchDevice(n.cameraId):M(n.useFrontCamera)?M(n.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(n.videoTrack)):yield this._localVideoTrack.switchDevice(n.useFrontCamera?S.FACING_MODE_USER:S.FACING_MODE_ENVIRONMENT),M(n.fillMode)||(a.objectFit=n.fillMode),M(n.mirror)||(a.mirror=n.mirror),n.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(ia(n.qosPreference)),n.small){let d=!this._localVideoTrack.small;On()?(n.small===!0?this._localVideoTrack.small=si["120p"]:Oe(n.small)?this._localVideoTrack.small=si[n.small]:this._localVideoTrack.small=n.small,this._room.videoManager.update(),d&&this._room.enableSmall(!0)):this._log.warn("small stream is not supported")}else n.small===!1&&this._localVideoTrack.small&&(delete this._localVideoTrack.small,this._room.videoManager.update(),this._room.enableSmall(!1));this._room.isJoined&&!M(r)&&(r&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._localVideoConfig.publish&&!r&&this._room.unpublish(this._localVideoTrack).catch(()=>{})),M(o)||(yield this._localVideoTrack.setMute(o)),yield this._updateVideoPlayOption({view:t,playOption:a,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),Li(this._localVideoConfig,e)})}stopLocalVideo(){return A(this,null,function*(){this._localVideoTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),at(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return A(this,arguments,function*(e={publish:!0,view:null}){var u;if(this._localScreenTrack){this._log.warn("screen share is already started");return}let{view:t=null,publish:r=!0,option:o}=e,n=new jt(this._room.videoManager);n.on("4",m=>{let p;m.error&&(p=ue.convertFrom(m.error)),this.emit(ne.PUBLISH_STATE_CHANGED,de(Z({},m),{error:p}))}),n.once("first-video-frame",m=>{this.emit(ne.FIRST_VIDEO_FRAME,de(Z({},m),{streamType:is(m.streamType)}))}),this._listenOutputTrackChanged(n),e.streamType==="main"&&(n.mediaType=4);let a=null,d={},l={};o&&(M(o.profile)||(Oe(o.profile)?ka[o.profile]&&n.setProfile(ka[o.profile]):n.setProfile(o.profile)),o.systemAudio&&(d.systemAudio=!0,d.echoCancellation=o.echoCancellation,d.noiseSuppression=o.noiseSuppression,d.autoGainControl=o.autoGainControl),M(o.fillMode)||(l.objectFit=o.fillMode),o.videoTrack&&(d.videoTrack=o.videoTrack),o.audioTrack&&(d.audioTrack=o.audioTrack),o.captureElement&&(d.captureElement=o.captureElement),o.preferDisplaySurface&&(d.preferDisplaySurface=o.preferDisplaySurface),o.qosPreference&&(d.contentHint=ia(o.qosPreference)));let h=yield n.capture(d);if(n.mediaTrack.addEventListener(S.ENDED,()=>{this._stopScreenShare(),this.emit(ne.SCREEN_SHARE_STOPPED)}),h.getAudioTracks()[0]&&(a=new Yi(this._room.audioManager),yield a.setInputMediaStreamTrack(h.getAudioTracks()[0]),this._speakerId&&a.setAudioOutput(this._speakerId)),vt(n,n).add("player-state-changed",m=>{this.emit(ne.VIDEO_PLAY_STATE_CHANGED,de(Z({},m),{userId:"",streamType:"sub"}))}),r&&this._room.isJoined){let m=[n];if(a&&(m.push(a),((u=a.trackSettings)==null?void 0:u.echoCancellation)===!1)){this._log.warn("echoCancellation of screen audio track is disable, try to open audioProcessor plugin");try{this.startPlugin("AudioProcessor",{sdkAppId:Number(this.room.sdkAppId),userId:this._room.userId,userSig:this.room.userSig,isScreenAudioNeedAudioProcess:!0,isLocalAudioNeedAudioProcess:!1})}catch(p){this._log.warn("start audioProcessor plugin failed: ",p)}}this._room.publish(...m).catch(()=>{})}this._localScreenTrack=n,this._localScreenAudioTrack=a,this._localScreenConfig=de(Z({},e),{view:t,publish:r}),yield this._updateVideoPlayOption({view:t,playOption:l,track:n})})}updateScreenShare(e){return A(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:r,option:o}=e,n={};if(o&&(M(o.fillMode)||(n.objectFit=o.fillMode),o.qosPreference)){let a=ia(o.qosPreference);this._localScreenTrack.setContentHint(a)}this._room.isJoined&&!M(r)&&(r&&!this._localScreenConfig.publish&&(this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch(()=>{})),this._localScreenConfig.publish&&!r&&(this._room.unpublish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.unpublish(this._localScreenAudioTrack).catch(()=>{}))),yield this._updateVideoPlayOption({view:t,playOption:n,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),Li(this._localScreenConfig,e)})}stopScreenShare(){return A(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return A(this,null,function*(){let{view:t,userId:r,streamType:o,option:n}=e,a=`${r}_${o}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${r}, streamType:${o}`);return}let d=this._room.remotePublishedUserMap.get(r);if(!d)return;let l={},h=o==="main"?d.remoteVideoTrack:d.remoteAuxiliaryTrack;this._listenOutputTrackChanged(h),n&&(M(n.fillMode)||(l.objectFit=n.fillMode),M(n.mirror)||(l.mirror=n.mirror),M(n.poster)||(l.poster=n.poster),l.canvasRender=n.canvasRender,o==="main"&&!M(n.small)&&(!d.remoteVideoTrack.isSubscribing&&!d.remoteVideoTrack.isSubscribed&&d.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,h.user))),yield this._room.subscribe(h),yield this._enableVideoDecodeFallback(h,o),yield this._updateVideoPlayOption({view:t,playOption:l,track:h}),this._emitTrackEvent(h),this._remoteVideoConfigMap.set(a,{config:e}),n&&!M(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:h,view:t,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:n==null?void 0:n.viewRoot})})}updateRemoteVideo(e){return A(this,null,function*(){var T,I;let{view:t,userId:r,streamType:o,option:n}=e,a=`${r}_${o}`,d=this._remoteVideoConfigMap.get(a);if(!d||!this._room.remotePublishedUserMap.has(r))return;let l={};n&&(M(n.fillMode)||(l.objectFit=n.fillMode),M(n.mirror)||(l.mirror=n.mirror));let h=null,u=this._room.remotePublishedUserMap.get(r);if(o==="main"&&(u!=null&&u.muteState.hasVideo)&&(h=u.remoteVideoTrack),o==="sub"&&(u!=null&&u.muteState.hasAuxiliary)&&(h=u.remoteAuxiliaryTrack),!h)return;let{config:m}=d;o==="main"&&n&&!M(n.small)&&this._room.changeType(n.small,h.user),yield this._updateVideoPlayOption({view:t,playOption:l,track:h,prevConfig:m}),Li(m,e);let p=M(n==null?void 0:n.receiveWhenViewVisible)?(T=m.option)==null?void 0:T.receiveWhenViewVisible:n.receiveWhenViewVisible,g=M(t)?m.view:t,f=M(n==null?void 0:n.viewRoot)?(I=m.option)==null?void 0:I.viewRoot:n.viewRoot;this._observeView({remoteTrack:h,view:g,receiveWhenViewVisible:p,viewRoot:f})})}stopRemoteVideo(e){return A(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,t=!0){return A(this,null,function*(){let r=[],o=this._room.remotePublishedUserMap.get(e.userId);if(o){let{muteState:n,remoteVideoTrack:a,remoteAuxiliaryTrack:d}=o;e.streamType==="main"&&(a.stop(),n.hasVideo&&r.push(a)),e.streamType==="sub"&&(d.stop(),n.hasAuxiliary&&r.push(d))}for(let n of r)t&&(yield this._room.unsubscribe(n),this._mediaTrackMap.delete(n.outMediaTrack));this._removeRemoteVideoConfig(e.userId,e.streamType)})}_removeRemoteVideoConfig(e,t){let r=`${e}_${t}`,o=this._remoteVideoConfigMap.get(r);o&&o.observer&&o.observer.disconnect(),this._remoteVideoConfigMap.delete(r)}muteRemoteAudio(e,t){return A(this,null,function*(){this._remoteAudioMuteMap.set(e,t);try{if(e==="*")if(t)yield this._stopRemoteAudio({userId:e});else{let r=[...this._room.remotePublishedUserMap.values()];for(let o of r)o.muteState.hasAudio&&!this._remoteAudioConfigMap.has(o.userId)&&(yield this._startRemoteAudio({userId:o.userId}))}else t?yield this._stopRemoteAudio({userId:e}):this._remoteAudioConfigMap.has(e)||(yield this._startRemoteAudio({userId:e}))}catch(r){throw this._remoteAudioMuteMap.delete(e),r}})}setRemoteAudioVolume(e,t){if(e==="*"){let r=[...this._room.remotePublishedUserMap.values()];for(let o of r)this._remoteAudioVolumeMap.set(o.userId,t),o.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:o.remoteAudioTrack})}else if(e){let r=this._room.remotePublishedUserMap.get(e);this._remoteAudioVolumeMap.set(e,t),r&&r.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:r.remoteAudioTrack})}}startPlugin(e,t){return A(this,null,function*(){return e.start(t)})}updatePlugin(e,t){return A(this,null,function*(){return e.update(t)})}stopPlugin(e,t){return A(this,null,function*(){return e.stop(t)})}enableAudioVolumeEvaluation(e=2e3,t=!1){this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,r){return this.listeners(e).includes(t)?this:(this._log.debug("on",e),super.on(e,t,r),this._eventListened.add(e),e===Ie.EVENT.AUDIO_FRAME&&!this._getPCMAbortCtrl&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM(o=>{this.emit(Ie.EVENT.AUDIO_FRAME,{data:o})}),this._localAudioTrack&&this._localAudioTrack.on("input-media-track-changed",()=>{this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("inputMediaTrackChanged"),this._getPCMAbortCtrl=this._room.audioManager.getPCM(o=>{this.emit(Ie.EVENT.AUDIO_FRAME,{data:o})}))})),this)}emit(e,...t){try{pf.has(e)&&this._log.debug(`emit ${e} ${JSON.stringify(t)}`)}catch(r){}return super.emit(e,...t)}off(e,t,r){var o,n;return this._log.debug("off",e),e==="*"?(this._eventListened.clear(),this.removeAllListeners(),(o=this._getPCMAbortCtrl)==null||o.abort("off"),delete this._getPCMAbortCtrl):(super.off(e,t,r),e===Ie.EVENT.AUDIO_FRAME&&((n=this._getPCMAbortCtrl)==null||n.abort("off"),delete this._getPCMAbortCtrl)),this}getAudioTrack(e={userId:"",streamType:"main"}){let t,r=null,o="main",n=!1;if(Oe(e)?t=e:(t=e.userId,n=e.processed===!0,e.streamType&&(o=e.streamType)),t){let a=this._room.remotePublishedUserMap.get(t);a&&(r=a.remoteAudioTrack)}else r=o==="sub"?this._localScreenAudioTrack:this._localAudioTrack;return r?n&&r.outMediaTrack&&r.outMediaTrack!==r.mediaTrack?r.outMediaTrack.clone():r.mediaTrack:null}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:t="",streamType:r="main",processed:o=!1}=e,n=null;if(t==="")r==="main"&&this._localVideoTrack&&(n=this._localVideoTrack),r==="sub"&&this._localScreenTrack&&(n=this._localScreenTrack);else{let a=this._room.remotePublishedUserMap.get(t);a&&(n=r==="main"?a.remoteVideoTrack:a.remoteAuxiliaryTrack)}return n?o&&n.outMediaTrack&&n.outMediaTrack!==n.mediaTrack?n.outMediaTrack.clone():n.mediaTrack:null}getVideoSnapshot(e={}){let{userId:t,streamType:r="main"}=e;if(t){let o=this._room.remotePublishedUserMap.get(t);if(r==="main"&&(o!=null&&o.muteState.hasVideo))return o.remoteVideoTrack.getVideoFrame();if(r==="sub"&&(o!=null&&o.muteState.hasAuxiliary))return o.remoteAuxiliaryTrack.getVideoFrame()}else{if(r==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(r==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(e){var t,r;this._speakerId=e,(t=this._localAudioTrack)==null||t.setAudioOutput(e),(r=this._localScreenAudioTrack)==null||r.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(o=>o.remoteAudioTrack.setAudioOutput(e))}setCurrentSpeaker(e){return A(this,null,function*(){(yield Yr()).forEach(r=>{r.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(ne.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}),At=r)}),this._log.warn('the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: https://web.sdk.qcloud.com/trtc/webrtc/v5/doc/en/TRTC.html#.setCurrentSpeaker')})}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return A(this,null,function*(){let{userId:t}=e;if(this._remoteAudioConfigMap.has(t)){this._log.warn(`remote audio has already started. userId:${t}`);return}let r=this._room.remotePublishedUserMap.get(t);if(!r)return;let o={},n=r.remoteAudioTrack;this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId);try{let a=this._remoteAudioVolumeMap.get(t),d=De(a)?a:100;o.volume=d,this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(n),He(We(n,"decode-failed"),St(We(n,ge.INIT)),it(()=>{this.startPlugin(ua.Name,{track:n,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:o,track:n}),n.outMediaTrack&&x.emit("266",{room:this.room,type:"add",audioReference:n.outMediaTrack,refId:`ra-${t}`})}catch(a){throw this._remoteAudioConfigMap.delete(t),a}this._emitTrackEvent(n)})}_stopRemoteAudio(e,t=!0){return A(this,null,function*(){let r=this._room.remotePublishedUserMap.get(e.userId);r&&(r.remoteAudioTrack.stop(),r.muteState.hasAudio&&t&&(yield this._room.unsubscribe(r.remoteAudioTrack)),this._mediaTrackMap.delete(r.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete(`${e.userId}`),x.emit("266",{room:this.room,type:"remove",refId:`ra-${e.userId}`})})}_enableVideoDecodeFallback(e,t){let r=this._room.videoDecodeFallbackType;if(!r||!this._plugins.has("TRTCVideoDecoder"))return;e.log.debug("remote video will fall back when decode failed",e.id);let o;He(We(e,"decode-failed"),St(We(e,ge.INIT)),ah(()=>{this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:r})}),Ms(We(e,"decode-downgrade-state-changed")),it(n=>{o=n.state,this.emit(ne.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,de(Z({},n),{streamType:t,userId:e.userId}))},n=>{e.log.error("fallback",n)},()=>{o==="STARTED"&&e.log.info("fallback complete")}))}_updateVideoPlayOption(n){return A(this,arguments,function*({view:e,playOption:t,track:r,prevConfig:o}){if(r.setMirror(t.mirror),M(e)&&o&&o.view&&!Ys(t)){let a=Ks(o.view);a.length>0&&(yield r.play(a,t))}if(!M(e)){let a=Ks(e);a.length>0?yield r.play(a,t):r.stop()}})}_updateAudioPlayOption(o){return A(this,arguments,function*({playOption:e={},track:t,prevConfig:r}){if(!t.isPlayCalled)try{yield t.play(null,e)}catch(n){}if(M(e.muted)||t.setPlayerMute(e.muted),M(e.volume)||t.setAudioVolume(e.volume/100),t instanceof ti&&t.mediaTrack){let n=e.muted===!1&&!M(e.volume)&&e.volume>0?"add":"remove";x.emit("266",{room:this.room,type:n,audioReference:t.mediaTrack,refId:"em"})}else if(t instanceof Ci){let n=e.muted?0:e.volume;if(M(n))return;x.emit("266",{room:this.room,type:"update_volume",refId:`ra-${t.userId}`,volume:e.volume})}})}_listenOutputTrackChanged(e){e.listeners("output-media-track-changed").length===0&&e.on("output-media-track-changed",()=>this._emitTrackEvent(e,!1))}_emitTrackEvent(e,t=!0){let r=e.isRemote?e.userId:"";e.outMediaTrack&&(t&&this._mediaTrackMap.get(e.outMediaTrack)===r||(this._mediaTrackMap.set(e.outMediaTrack,r),this.emit(ne.TRACK,{userId:r,streamType:is(e.streamType),track:e.outMediaTrack,sourceTrack:e.mediaTrack})))}_checkTrackToPublish(){var t,r,o,n;let e=[];if((t=this._localAudioConfig)!=null&&t.publish&&this._localAudioTrack&&e.push(this._localAudioTrack),(r=this._localVideoConfig)!=null&&r.publish&&this._localVideoTrack&&e.push(this._localVideoTrack),(o=this._localScreenConfig)!=null&&o.publish&&(this._localScreenTrack&&e.push(this._localScreenTrack),this._localScreenAudioTrack&&(e.push(this._localScreenAudioTrack),((n=this._localScreenAudioTrack.trackSettings)==null?void 0:n.echoCancellation)===!1))){this._log.warn("echoCancellation of screen audio track is disable, try to open audioProcessor plugin");try{this.startPlugin("AudioProcessor",{sdkAppId:Number(this.room.sdkAppId),userId:this._room.userId,userSig:this.room.userSig,isScreenAudioNeedAudioProcess:!0,isLocalAudioNeedAudioProcess:!1})}catch(a){this._log.warn("start audioProcessor plugin failed: ",a)}}if(e.length!==0)return this._room.publish(...e).catch(()=>{})}_observeView({remoteTrack:e,view:t,receiveWhenViewVisible:r=!1,viewRoot:o}){if(M(t))return;let n=this._remoteVideoConfigMap.get(`${e.userId}_${is(e.streamType)}`);if(!n)return;let a=n.observer||void 0;if(t===null||tt(t)&&t.length===0||!r){a==null||a.disconnect(),e.isSubscribed||this._room.subscribe(e).catch(()=>{});return}let l=n.visibleViewMap||new Map,h=-1;(!a||a.root!==o)&&(a==null||a.disconnect(),l.clear(),a=new IntersectionObserver(m=>{m.forEach(p=>{l.set(p.target,p.isIntersecting),e.log.info(`view ${p.target.id} is${p.isIntersecting?"":" not"} visible`)}),clearTimeout(h),h=window.setTimeout(()=>{[...l.values()].find(g=>g)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:o}));let u=new Set(Ks(t));l.forEach((m,p)=>{u.has(p)||(a.unobserve(p),l.delete(p))}),u.forEach(m=>{l.set(m,!0),a.observe(m)}),a.takeRecords().forEach(m=>{l.set(m.target,m.isIntersecting)}),n.visibleViewMap=l,n.observer=a}_exitRoom(){return A(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(e=>{this._stopRemoteAudio({userId:e}).catch()}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let t=e.includes("main")?"main":"sub",r=e.split(`_${t}`)[0];r&&this._stopRemoteVideo({userId:r,streamType:t}).catch()}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._remoteAudioVolumeMap.clear(),Sf(this),this._room.remotePublishedUserMap.forEach(e=>{at(e.remoteAudioTrack),at(e.remoteVideoTrack),at(e.remoteAuxiliaryTrack)})})}_stopScreenShare(){return A(this,null,function*(){var e,t;if(this._localScreenTrack){if(this._room.isJoined){let r=[this._localScreenTrack];this._localScreenAudioTrack&&r.push(this._localScreenAudioTrack),yield(e=this._room)==null?void 0:e.unpublish(...r).catch(()=>{})}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(((t=this._localScreenAudioTrack.trackSettings)==null?void 0:t.echoCancellation)===!1&&this.stopPlugin("AudioProcessor"),this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),at(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_onLocalTrackCaptured({track:e}){e.kind==="audio"&&(!At||Ao(At))&&(this._initActiveSpeaker(),x.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return A(this,null,function*(){if(At&&!Ao(At))this.emit(ne.DEVICE_CHANGED,{type:"speaker",action:"active",device:At});else{let e=yield Yr();e[0]&&!Ao(e[0])?(At=e[0],this.emit(ne.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):x.on("102",this._onLocalTrackCaptured,this)}})}_onAudioAvailable({userId:e}){let t=this._remoteAudioMuteMap.has(e)?this._remoteAudioMuteMap.get(e):this._remoteAudioMuteMap.get("*");(t===!1||this._room.autoReceiveAudio&&!t)&&this._doStartRemoteAudio({userId:e}).catch(()=>{})}_onVideoAvailable({userId:e,streamType:t}){if(!this._room.autoReceiveVideo)return;let r=this._room.remotePublishedUserMap.get(e);if(r){let o=t==="main"?r.remoteVideoTrack:r.remoteAuxiliaryTrack,n=[o];this._room.autoReceiveAudio&&r.remoteAudioTrack.isAvailable&&n.push(r.remoteAudioTrack),this._room.subscribe(...n).then(()=>{this._emitTrackEvent(o)}).catch(()=>{})}}_onAudioUnavailable({userId:e,muteState:t}){t.hasAudio&&t.audioMuted||this._stopRemoteAudio({userId:e},!1).catch(()=>{})}_onVideoUnavailable({userId:e,streamType:t}){this._stopRemoteVideo({userId:e,streamType:t},!1).catch(()=>{})}sendSEIMessage(e,t){var o;let r=this._plugins.get("SEI");r&&(r.update({buffer:e,options:de(Z({seiPayloadType:243},t),{small:!!((o=this._localVideoTrack)!=null&&o.small)})}),Q.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,r;(r=(t=this._room).sendCustomMessage)==null||r.call(t,e),Q.addCount({key:500001,useUV:!0})}static setLogLevel(e,t){z.setLogLevel(e),M(t)||(t?z.enableUploadLog():z.disableUploadLog())}static isSupported(){return Td()}static getCameraList(e=!0){return ei(e)}static getMicrophoneList(e=!0){return Wt(e)}static getSpeakerList(e=!0){return Yr(e)}static setCurrentSpeaker(e){return A(this,null,function*(){if(ze&&(e===ci.SPEAKER||e===ci.HEADSET)){let r=yield Ie.getMicrophoneList(),o="";if(r.forEach(n=>{n.label===e&&(o=n.deviceId)}),!o)return;ha.forEach(n=>A(this,null,function*(){n._localAudioTrack&&(yield n.updateLocalAudio({option:{microphoneId:o}}))}));return}(yield Yr()).forEach(r=>{r.deviceId===e&&(ha.forEach(o=>{o._setCurrentSpeaker(e),o.emit(ne.DEVICE_CHANGED,{type:"speaker",action:"active",device:r})}),At=r)})})}static _addKVStat({type:e,key:t,value:r,base:o,useUV:n,version:a}){switch(a&&(Cs.version=a),e){case"count":Cs.addCount({key:t,useUV:n});break;case"enum":Cs.addEnum({key:t,value:r,useUV:n});break;case"number":Cs.addNumber({key:t,value:r,split:o});break}}};c(Ie,"_loggerManager",z),c(Ie,"EVENT",ne),c(Ie,"ERROR_CODE",fe),c(Ie,"TYPE",ci),c(Ie,"frameWorkType",30),J([Xe({replaceArg:e=>({argIndex:0,value:{name:"plugin"in e?e.plugin.Name:e.Name,assetsPath:"assetsPath"in e?e==null?void 0:e.assetsPath:"default"}})})],Ie.prototype,"use",1),J([Ot(It.TRTC.enterRoom),es("room",([e],[t])=>(e.roomId||e.strRoomId)===(t.roomId||t.strRoomId)&&e.userId===t.userId&&e.sdkAppId===t.sdkAppId),be(e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)}),Xe()],Ie.prototype,"enterRoom",1),J([Xe()],Ie.prototype,"exitRoom",1),J([Ot(It.TRTC.switchRole),Us("room",{merge:(e,t)=>t}),Xe()],Ie.prototype,"switchRole",1),J([Xe()],Ie.prototype,"destroy",1),J([Ot(It.TRTC.startLocalAudio),es("audio",([e],[t])=>{var r,o;return((r=e==null?void 0:e.option)==null?void 0:r.microphoneId)===((o=t==null?void 0:t.option)==null?void 0:o.microphoneId)}),Xe()],Ie.prototype,"startLocalAudio",1),J([Ot(It.TRTC.updateLocalAudio),Us("audio",{debounce:{delay:200,getKey:()=>`${Gf}-localAudio`,isNeedToDebounce:e=>{var t;return!M((t=e.option)==null?void 0:t.captureVolume)}}}),Xe()],Ie.prototype,"updateLocalAudio",1),J([ts("audio"),Xe()],Ie.prototype,"stopLocalAudio",1),J([Ot(It.TRTC.startLocalVideo),es("video",([e],[t])=>{var r,o;return((r=e==null?void 0:e.option)==null?void 0:r.cameraId)===((o=t==null?void 0:t.option)==null?void 0:o.cameraId)}),Xe()],Ie.prototype,"startLocalVideo",1),J([Ot(It.TRTC.updateLocalVideo),Us("video"),Xe()],Ie.prototype,"updateLocalVideo",1),J([ts("video"),Xe()],Ie.prototype,"stopLocalVideo",1),J([Ot(It.TRTC.startScreenShare),es("screen",()=>!0),Xe()],Ie.prototype,"startScreenShare",1),J([Ot(It.TRTC.updateScreenShare),Us("screen"),Xe()],Ie.prototype,"updateScreenShare",1),J([Xe()],Ie.prototype,"stopScreenShare",1),J([Ot(It.TRTC.startRemoteVideo),es(e=>`v${e.userId}${e.streamType}`,()=>!0),Xe({getRemoteId:e=>`${e.userId}_${e.streamType}`})],Ie.prototype,"startRemoteVideo",1),J([Ot(It.TRTC.updateRemoteVideo),Us(e=>`v${e.userId}${e.streamType}`),Xe({getRemoteId:e=>`${e.userId}_${e.streamType}`})],Ie.prototype,"updateRemoteVideo",1),J([Ot(It.TRTC.stopRemoteVideo),be(e=>function(t){return A(this,null,function*(){if(t.userId==="*"){let r=[];return this._room.remotePublishedUserMap.forEach(o=>{this._remoteVideoConfigMap.has(`${o.userId}_main`)&&r.push(this.stopRemoteVideo({streamType:"main",userId:o.userId}).catch(()=>{})),this._remoteVideoConfigMap.has(`${o.userId}_sub`)&&r.push(this.stopRemoteVideo({streamType:"sub",userId:o.userId}).catch(()=>{}))}),Promise.all(r)}return e.call(this,t)})}),Xe({getRemoteId:e=>`${e.userId}_${e.streamType}`})],Ie.prototype,"stopRemoteVideo",1),J([ts(e=>`v${e.userId}${e.streamType}`)],Ie.prototype,"_stopRemoteVideo",1),J([Ot(...It.TRTC.muteRemoteAudio),Xe({getRemoteId:e=>e})],Ie.prototype,"muteRemoteAudio",1),J([gh(...It.TRTC.setRemoteAudioVolume),ra(200,e=>e),Xe({getRemoteId:e=>e})],Ie.prototype,"setRemoteAudioVolume",1),J([hc("start"),Ut(e=>{var t;return(t=e.afterStart)==null?void 0:t.call(e)}),es((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t)),Xe({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Xl[e.getName()],ignoreLog:e=>e.getName()==="Debug"})],Ie.prototype,"startPlugin",1),J([hc("update"),Us((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t)),Xe({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Ql[e.getName()]})],Ie.prototype,"updatePlugin",1),J([hc("stop"),ts((e,t)=>{if(e.disableRandomCall)return null;let r=e.getGroup(t),o=e.getAlias();return r==="*"?new RegExp(`${o}.*`):o+r}),Xe({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Yl[e.getName()]})],Ie.prototype,"stopPlugin",1),J([gh(...It.TRTC.enableAudioVolumeEvaluation)],Ie.prototype,"enableAudioVolumeEvaluation",1),J([Xe()],Ie.prototype,"getVideoSnapshot",1),J([Xe()],Ie.prototype,"_setCurrentSpeaker",1),J([es(e=>`a${e.userId}`,()=>!0)],Ie.prototype,"_startRemoteAudio",1),J([be(e=>function(t){return A(this,null,function*(){return t.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(r=>this._stopRemoteAudio(de(Z({},t),{userId:r.userId})).catch(()=>{}))):e.call(this,t)})}),ts(e=>`a${e.userId}`)],Ie.prototype,"_stopRemoteAudio",1),J([ts("room")],Ie.prototype,"_exitRoom",1),J([ts("screen")],Ie.prototype,"_stopScreenShare",1),J([Ot(...It.TRTC.sendSEIMessage),lh({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...e)=>e[0].byteLength})],Ie.prototype,"sendSEIMessage",1),J([Ot(It.TRTC.sendCustomMessage),lh({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],Ie.prototype,"sendCustomMessage",1),J([Ot(It.TRTC.create)],Ie,"_create",1);var $h=Ie,ma=$h;var Fh=class{constructor(){c(this,"_set",new Set);x.on(B.LEAVE_SUCCESS,this.delete,this)}add({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,e||i.roomId,i.sdkAppId,i.useStringRoomId);this._set.add(t)}delete({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,i.roomId||e,i.sdkAppId,i.useStringRoomId);this._set.delete(t)}getKey(i,e,t,r){return`${t}_${e}_${i}_${r}`}isJoined({userId:i,roomId:e,sdkAppId:t,room:r}){return r.scene==="rtc"?!1:this._set.has(this.getKey(i,e,t,r.useStringRoomId))}};function SS(){return A(this,null,function*(){let s,i;try{let u=yield Wt();s=u&&u.length}catch(u){}try{let u=yield ei();i=u&&u.length}catch(u){}let e={microphone:s,camera:i},{isH264EncodeSupported:t,isVp8EncodeSupported:r,isH264DecodeSupported:o,isVp8DecodeSupported:n}=this.checkSystemResult.detail,a=Wi.basis(),d={webRTC:a.isWebRTCSupported,getUserMedia:a.isGetUserMediaSupported,webSocket:a.isWebSocketsSupported,screenShare:a.isScreenShareSupported,webAudio:a.isWebAudioSupported,h264Encode:t,h264Decode:o,vp8Encode:r,vp8Decode:n},l={browser:a.browser,os:a.os,trtc:d,devices:e},h={isWebCodecSupported:a.isWebCodecSupported,isMediaSessionSupported:a.isMediaSessionSupported,isWebTransportSupported:a.isWebTransportSupported};Me.uploadEvent({log:`trtcstats-${JSON.stringify(l)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(l)}`),Me.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(h)}`,userId:this.userId})})}function zf(){return be(s=>{let i=new Fh;return function(e,t,r){return A(this,null,function*(){let o=String(e.roomId||e.strRoomId);if(this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.userSig=e.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=t,e.privateMapKey=e.privateMapKey||"",this.isJoined)throw new X({code:H.INVALID_OPERATION,message:pe({key:me.INVALID_JOIN})});if(this.checkDestroy(),i.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this}))throw new X({code:H.INVALID_OPERATION,message:pe({key:me.REPEAT_JOIN,data:this.userId})});i.add({room:this,roomId:o}),this.role=e.role===21?"audience":"anchor",this._log.info(`Join() => joining room: ${o} useStringRoomId: ${this.useStringRoomId} scene: ${this.scene} role: ${this.role}`),x.emit(B.JOIN_START,{room:this,roomId:o,params:e});let n=Jt.getEnv();n||(n=ar.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(Oa.OLD_CLOUD_LADDER)?n=ar.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(Oa.WEBRTC)&&(n=ar.WEBRTC))),Me.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),Wi.checkSystemRequirementsInternal().then(a=>{this.checkSystemResult=a,SS.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Jt.getEnv()&&(yield this.schedule(e,r));let a=yield s.call(this,e,t,r);return this.roomId=o,this._joinedTimestamp=Jt.performanceNow(),x.emit(B.JOIN_SUCCESS,{room:this}),r===30&&!e.component&&Me.uploadEvent({log:`stat-conv-${Number(Ti)}-${location.hostname}`,userId:this.userId}),a}catch(a){throw i.delete({room:this,roomId:o}),x.emit(B.JOIN_FAILED,{room:this,error:a}),a}})}})}var jf=()=>be(s=>function(...i){return A(this,null,function*(){x.emit(B.LEAVE_START,{room:this}),yield s.call(this,...i),x.emit(B.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function Jf(){return be(s=>function(...i){let e=s.apply(this,i);return i.forEach(t=>!t.isSubscribed&&t.subscribe(e)),e})}var Xf=gt(Mt());var rt={SETUP_SUCCESS:"1",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",RECONNECT_FAILED:"4",SETUP_FAILED:"5",DISCONNECTED:"6"};var bi={CLIENT_BANNED:9,CHANNEL_SETUP_RESULT:19,CHANNEL_RECONNECT_RESULT:514,JOIN_ROOM_RESULT:20,PEER_JOIN:4134,PEER_LEAVE:4135,STREAM_ADDED:16,STREAM_REMOVED:18,UPLINK_NETWORK_STATS:22,UPDATE_REMOTE_MUTE_STAT:23,PUBLISH_RESULT:4098,PUBLISH_STATE_CHANGE_RESULT:4112,UNPUBLISH_RESULT:4100,SUBSCRIBE_RESULT:4102,UNSUBSCRIBE_RESULT:4104,SUBSCRIBE_CHANGE_RESULT:4106,MUTE_RESULT:4108,UPDATE_OFFER_RESULT:4128,START_PUBLISH_TENCENT_CDN_RES:1286,STOP_PUBLISH_TENCENT_CDN_RES:1288,START_PUBLISH_GIVEN_CDN_RES:777,STOP_PUBLISH_GIVEN_CDN_RES:779,START_MIX_TRANSCODE_RES:781,STOP_MIX_TRANSCODE_RES:783,START_PUBLISH_CDN_STREAM_RES:8196,UPDATE_PUBLISH_CDN_STREAM_RES:8198,STOP_PUBLISH_CDN_STREAM_RES:8200,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772,REBUILD_PEER_CONNECTION_RES:4150,SPC_PUBLISH_RESULT:4146,SPC_SUBSCRIBE_RESULT:4156,ABILITY_STATUS_REPORT_RESULT:4158,SERVER_FIRST_PACKAGE_RECEIVED:5e3,RECEIVE_CUSTOM_MSG:4140},qf=[bi.UPDATE_REMOTE_MUTE_STAT,bi.UPLINK_NETWORK_STATS,bi.USER_LIST_RES,bi.MUTE_RESULT,bi.SERVER_FIRST_PACKAGE_RECEIVED,bi.RECEIVE_CUSTOM_MSG],Ee={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",START_PUBLISH_CDN_STREAM_RES:"start-publish-cdn-stream-res",UPDATE_PUBLISH_CDN_STREAM_RES:"update-publish-cdn-stream-res",STOP_PUBLISH_CDN_STREAM_RES:"stop-publish-cdn-stream-res",USER_LIST_RES:"user-list-res",SWITCH_ROLE_RES:"switch_role_res",MUTE_RESULT:"mute-result",UPDATE_CONSTRAINT_CONFIG_RES:"update-contraint-config-res",REBUILD_PEER_CONNECTION_RES:"rebuild-pc-res",SPC_PUBLISH_RESULT:"spc-publish-result",SPC_SUBSCRIBE_RESULT:"spc-subscribe-result",ABILITY_STATUS_REPORT_RESULT:"ability-status-report",SERVER_FIRST_PACKAGE_RECEIVED:"first-pkg-received",RECEIVE_CUSTOM_MSG:"receive-custom-msg"},ve={PUBLISH_CHANGE:"publish_change",JOIN_ROOM:"join",LEAVE_ROOM:"leave",ON_QUALITY_REPORT:"quality_report",UPDATE_MUTE_STAT:"mute_uplink",PUBLISH:"publish",PUBLISH_STATE_CHANGE:"publish_state_change",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",RECEIVE_DATA_USER_LIST:"receive_data_userlist",UNSUBSCRIBE:"unsubscribe",SUBSCRIBE_CHANGE:"subscribe_change",START_PUBLISH_TENCENT_CDN:"start_publishing",STOP_PUBLISH_TENCENT_CDN:"stop_publishing",START_PUBLISH_GIVEN_CDN:"start_push_user_cdn",STOP_PUBLISH_GIVEN_CDN:"stop_push_user_cdn",START_MIX_TRANSCODE:"start_mcu_mix",STOP_MIX_TRANSCODE:"stop_mcu_mix",START_PUBLISH_CDN_STREAM:"start_publish_cdn_stream",UPDATE_PUBLISH_CDN_STREAM:"update_publish_cdn_stream",STOP_PUBLISH_CDN_STREAM:"stop_publish_cdn_stream",GET_USER_LIST:"get_user_list",SWITCH_ROLE:"change_role",UPDATE_CONSTRAINT_CONFIG:"update_constraint_config",REBUILD_PEER_CONNECTION:"rebuild_pc",READY_TO_RECEIVE_DATA:"ready_to_receive",SPC_JOIN_ROOM:"join/v2",SPC_PUBLISH:"publish/v2",SPC_SUBSCRIBE:"subscribe/v3",ABILITY_STATUS_REPORT:"ability_status_report",RECONNECT_WS:"reconnect",SEND_CUSTOM_MSG:"channel_msg"};var wc=new Set;function Qf(s){let i=[...wc.values()].find(e=>e.room.userId===s&&!e.room.isJoined);return i||null}var Vo=class extends Xf.default{constructor(e){var r,o,n;super();c(this,"room");c(this,"sdkAppId");c(this,"userId");c(this,"userSig");c(this,"url");c(this,"backupUrl");c(this,"destroyed",!1);c(this,"_socketInUse");c(this,"_socket");c(this,"_backupSocket");c(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,bakRelayIps:[]});c(this,"_currentState","DISCONNECTED");c(this,"_isReconnecting",!1);c(this,"_seq",0);c(this,"_log");c(this,"_lastMessageTime",-1);c(this,"_connectStartTime",-1);c(this,"_stopConnectRetry");c(this,"bytesSent",0);c(this,"bytesReceived",0);c(this,"keepAlive",!1);c(this,"signalDomainWhenUnifiedProxy");c(this,"stopKeepAliveTimeout");c(this,"rtt",0);this.room=e.room,this.sdkAppId=e.sdkAppId,this.userId=e.userId,this.userSig=e.userSig,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy;let t=((o=(r=this.room.scheduleResult)==null?void 0:r.config)==null?void 0:o.keepAliveClient)||0;(n=this.room.joinParams)!=null&&n.keepAlive&&!t&&(t=1),t-wc.size>0&&this.room.enableSPC&&(this.keepAlive=!0,wc.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=z.createLogger({id:"ws",userId:this.userId,sdkAppId:this.sdkAppId}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get race(){return this.room.enableSPC&&!this.room.proxy_ws}get urlParam(){let e=`?sdkAppId=${encodeURIComponent(this.sdkAppId)}&userId=${encodeURIComponent(this.userId)}&userSig=${encodeURIComponent(this.userSig)}&keepAlive=${encodeURIComponent(Number(this.keepAlive))}`;this.signalDomainWhenUnifiedProxy&&(e+=`&signalDomain=${encodeURIComponent(this.signalDomainWhenUnifiedProxy)}`);let t=new URLSearchParams(location.search).get("clientIp");return t&&(e+=`&clientIp=${t}`),this.race?`${e}&race=1`:e}get _urlWithParam(){return`${this.url}${this.race?"/v2/ws":""}${this.urlParam}`}get _backupUrlWithParam(){return`${this.backupUrl}${this.race?"/v2/ws":""}${this.urlParam}`}get isConnected(){return this._currentState==="CONNECTED"}get isConnecting(){return this._currentState==="CONNECTING"}get isOnline(){return this._currentState==="CONNECTED"&&Date.now()-this._lastMessageTime<12*1e3}connect(){return A(this,arguments,function*(e=10*1e3){if(this.isConnected)return Promise.resolve();this._log.info(`connect to [${this.url}, ${this.backupUrl}] ${this.race?"race":""}${e?` timeout: ${e}`:""} keepAlive: ${Number(this.keepAlive)}`),this.emitConnectionStateChanged("CONNECTING"),this._connectStartTime=le();let t=[this.connectWS({url:this._urlWithParam,isMain:!0,timeout:e})];this.race&&this._backupUrlWithParam!==this._urlWithParam&&t.push(this.connectWS({url:this._backupUrlWithParam,isMain:!1,timeout:e})),this._socketInUse=yield _s(t),this.unbindAndCloseSocket(this._socketInUse===this._socket?S.BACKUP:S.MAIN),this.emitConnectionStateChanged("CONNECTED")})}connectWS({url:e,timeout:t,isMain:r}){let o=new WebSocket(e);this.bindSocket(o),r?this._socket=o:this._backupSocket=o;let n=-1;return new Promise((a,d)=>{o.onclose=d,o.onerror=d,o.onopen=()=>a(o),t&&(n=setTimeout(()=>{this.unbindAndCloseSocket(r?S.MAIN:S.BACKUP),d(new X({code:H.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))},t))}).finally(()=>{o.onclose=null,o.onerror=null,o.onopen=null,clearTimeout(n)})}bindSocket(e){e.addEventListener("close",this.onclose),e.addEventListener("error",this.onerror),e.addEventListener("message",this.onmessage)}unbindSocket(e){e.removeEventListener("close",this.onclose),e.removeEventListener("error",this.onerror),e.removeEventListener("message",this.onmessage)}unbindAndCloseSocket(e){if(e===S.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(t){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(t){}this._backupSocket=null}}onclose(e){e.target===this._socketInUse&&(this._log.warn(`${e.target===this._socket?"main":"backup"} is closed code:${e.code} ${e.reason}`),this.emitConnectionStateChanged("DISCONNECTED"),(!e.wasClean||e.code!==1e3)&&this.startReconnection(),this.room.isJoining&&this.emit(rt.SETUP_FAILED,new X({code:H.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onclose"})))}onerror(e){this._log.error(`${e.target===this._socket?"main":"backup"} error observed`),this.emitConnectionStateChanged("DISCONNECTED"),e.target===this._socketInUse&&(this.unbindAndCloseSocket(S.MAIN),this.unbindAndCloseSocket(S.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(rt.SETUP_FAILED,new X({code:H.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=ln(e.data);let t=JSON.parse(e.data),{cmd:r,data:o}=t,n=Object.values(bi),d=Object.keys(bi)[n.indexOf(r)],l=Ee[d]||r;switch(qf.includes(r)||(this._log.debug(`received ${r} msg: ${e.data}`),l&&this._log.info(`Received event: [ ${l} ]`)),r){case bi.CHANNEL_SETUP_RESULT:{if(t.code===0)this._signalInfo.clientIp=o.clientIp,this._signalInfo.signalIp=o.signalInnerIp,o.svrTime&&gm(o.svrTime),this._log.info(`ChannelSetup Success ${le()-this._connectStartTime}`),Q.addSuccessEvent({key:521701,cost:le()-this._connectStartTime}),this._connectStartTime=-1,this.emit(rt.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let h=new X({code:H.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:pe({key:me.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error(`${t.code}, ${t.message}`),this.close(),Q.addFailedEvent({key:521701,error:h}),this.emit(rt.SETUP_FAILED,h)}break}case bi.JOIN_ROOM_RESULT:{t.code===0&&(this._signalInfo.relayIp=o.relayOuterIp,this._signalInfo.relayInnerIp=o.relayInnerIp,this._signalInfo.bakRelayIps=o.bakRelayIps,this._signalInfo.relayPort=o.relayPort,this._signalInfo.tinyId=t.tinyId,this._signalInfo.endReportExtend=o.endReportExtend,this._log.info(`signalIp:${this._signalInfo.signalIp} clientIp:${this._signalInfo.clientIp} relayIp: ${this._signalInfo.relayIp}`)),this.emit(l,{data:t});break}default:this.emit(String(l),{data:t});break}}reGetSignalChannelUrl(){return A(this,null,function*(){try{if(!this.room.joinParams)return;yi(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(e){}})}startReconnection(){if(!this._socketInUse)return;this._socketInUse.onclose=null,this._socketInUse.close(4011);let e=this._socketInUse===this._socket;this.unbindAndCloseSocket(e?S.MAIN:S.BACKUP),this._socketInUse=null,this.emitConnectionStateChanged("DISCONNECTED"),this.reconnect()}reconnect(){return A(this,null,function*(){if(!this._isReconnecting){if(!this.room.isJoined&&this.keepAlive){this.close();return}this._isReconnecting=!0;try{this._log.warn("reconnect"),yield this.connect();let{roomId:e,useStringRoomId:t}=this.room,{relayIp:r,relayInnerIp:o,relayPort:n}=this._signalInfo,{data:a}=yield this.sendWaitForResponse({command:ve.RECONNECT_WS,data:{roomId:e,useStringRoomId:t,relayInnerIp:o,relayOuterIp:r,relayPort:n},responseCommand:Ee.CHANNEL_RECONNECT_RESULT});a.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),Q.addSuccessEvent({key:521702,cost:le()-this._connectStartTime}),this._connectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(Q.addFailedEvent({key:521702,error:a.code}),this._log.warn(`reconnect failed, ${a.code} ${a.message}`),this.room.reJoin())}catch(e){this._log.error(e),this.room.reJoin()}}})}send(e,t={}){if(this.isConnected&&!this.room.isLeft){let r={cmd:e,data:t,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},o=JSON.stringify(r);return this._socketInUse.send(o),this.bytesSent+=ln(o),r.seq}}sendWaitForResponse({command:e,data:t,timeout:r=5e3,responseCommand:o,commandDesc:n,enableLog:a=!0,addReceiveTime:d=!1}){return new Promise((l,h)=>{let u=setTimeout(()=>{this.off(o,p);let f=new X({code:H.API_CALL_TIMEOUT,message:pe({key:me.API_CALL_TIMEOUT,data:{commandDesc:n,command:e}})});a&&this._log.warn(f),h(f)},r),m=Date.now(),p=f=>{f.data.seq===g&&(clearTimeout(u),this.off(o,p),d&&(f.data.receiveTime=Date.now()),l(f))};this.on(o,p);let g=this.send(e,t)})}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:r,retries:o=0,retryTimeout:n=0}=e;return Ui({retryFunction:this.sendWaitForResponse,onError:({retry:a})=>{this.isOnline?a():(this._log.warn(`retry ${r} when connected`),this.once(rt.CONNECTED,a))},onRetrying:a=>{this._log.warn(`${t||r} timeout observed, retrying [${a}/${o}]`)},settings:{retries:o,timeout:n},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),clearTimeout(this.stopKeepAliveTimeout),wc.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,bakRelayIps:[],endReportExtend:void 0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(S.MAIN),this.unbindAndCloseSocket(S.BACKUP),this.emitConnectionStateChanged("DISCONNECTED")}destroy(){this.close(),this.destroyed=!0}getBackupRelayIpPair(){var t;let e=(t=this._signalInfo.bakRelayIps)==null?void 0:t.shift();return e&&(e.relayPort=e.relayPort||this._signalInfo.relayPort),e}clearBakRelayIps(){this._signalInfo.bakRelayIps=[]}stopKeepAliveIn(e=3600){if(this.keepAlive){this._log.info(`stopKeepAlive in ${e}s`),this.stopKeepAliveTimeout=setTimeout(()=>{this.keepAlive=!1,this._log.info(`close due to not used ${e}s`),this.close(),this.off(Ee.JOIN_ROOM_RESULT,t)},e*1e3);let t=r=>{r.data.code===0&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(Ee.JOIN_ROOM_RESULT,t))};this.on(Ee.JOIN_ROOM_RESULT,t)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info(`${this._currentState} -> ${e}`),this.emit(rt.CONNECTION_STATE_CHANGED,{prevState:this._currentState,state:e}),this._currentState=e,e==="CONNECTED"?this.emit(rt.CONNECTED):e==="DISCONNECTED"&&this.emit(rt.DISCONNECTED))}};J([Gt({settings:{retries:1/0,timeout:2e3},onError(e,t){!this.room.isDestroyed&&!this.destroyed&&t()},onRetrying(e,t){this._log.warn(`retrying to connect ${e}`),e>=3&&e%3===0&&this.reGetSignalChannelUrl(),t&&(this._stopConnectRetry=t,(this.room.isDestroyed||this.destroyed)&&t())}})],Vo.prototype,"connect",1);var Yf=gt(Mt());var Hh=0,Gh=!1,Mc=new Set,AS=s=>Hh>2&&!Gh&&Mc.size===0&&s,Wh=!1,$t=class{constructor(i){c(this,"userId");c(this,"tinyId");c(this,"_sdpSemantics");c(this,"_isUplink");c(this,"_room");c(this,"_log");c(this,"_signalChannel");c(this,"_isErrorObserved",!1);c(this,"_waitForPeerConnectionConnectedPromise");c(this,"_waitForPeerConnectionConnectedPromiseReject",null);c(this,"_peerConnection",null);c(this,"_emitter",new Yf.default);c(this,"_currentState","DISCONNECTED");c(this,"_isReconnecting",!1);c(this,"_reconnectionCount",0);c(this,"_reconnectionTimer",-1);c(this,"_isFirstConnection",!0);c(this,"_prevTime",-1);c(this,"_localAddress");c(this,"_remoteAddress");this.userId=i.userId,this.tinyId=i.tinyId,this._room=i.room,this._sdpSemantics=i.room.sdpSemantics,this._isUplink=i.isUplink,this._log=z.createLogger({id:"n-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=i.signalChannel}beforeConnect(){this._prevTime<0&&(this._prevTime=le())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,Q.addSuccessEvent({key:521705,cost:Math.min(le()-this._prevTime,30*1e3)})):this._isReconnecting&&Q.addSuccessEvent({key:521706,cost:le()-this._prevTime}),this._prevTime=-1}catch(i){throw this._isFirstConnection?(this._isFirstConnection=!1,Q.addFailedEvent({key:521705,error:i})):this._isReconnecting&&this._reconnectionCount>=3&&Q.addFailedEvent({key:521706,error:i}),i}}initialize(){let i={iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"};this._peerConnection=new RTCPeerConnection(i),this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this)}close(i){this._log.info("close connection"),this._emitter.emit("closed",i),this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),Mc.delete(this)}closePeerConnection(i=!1){this._peerConnection&&(this._log.info("close pc"),this._peerConnection.onconnectionstatechange=null,this._peerConnection.close(),this._peerConnection=null,i&&this.emitConnectionStateChangedEvent("DISCONNECTED")),this._waitForPeerConnectionConnectedPromiseReject&&this._waitForPeerConnectionConnectedPromiseReject(new X({code:H.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return hi;let i=null;if(this._isUplink){if(!Qr()||this._peerConnection.getSenders().length===0)return hi;i=this._peerConnection.getSenders()[0].transport}else{if(!Rs()||this._peerConnection.getReceivers().length===0)return hi;i=this._peerConnection.getReceivers()[0].transport}return i?i.state:hi}onConnectionStateChange(i){let e=this._peerConnection.iceConnectionState,t=this.getDTLSTransportState();if(this._log.info(`connectionState: ${i.target.connectionState}, ICE: ${e}, DTLS: ${t}`),i.target.connectionState===Je.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),i.target.connectionState===Je.FAILED||i.target.connectionState===Je.CLOSED){let r=`connection ${i.target.connectionState}. ICE Transport state: ${e}, DTLS Transport state: ${t}`,o=new X({message:r,code:H.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",o)}(i.target.connectionState===Je.CONNECTED||i.target.connectionState===Je.COMPLETED)&&(this.logSelectedCandidate(),Me.logSuccessEvent({userId:this._room.userId,eventType:Ft.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(i){return i===this._currentState?!1:(i==="CONNECTED"?(Hh=0,Gh=!1,Wh=!0,Mc.add(this)):Mc.delete(this),x.emit(B.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:i,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:i}),this._currentState=i,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}logSelectedCandidate(){return A(this,null,function*(){if(!this._peerConnection)return;let i=yield this._peerConnection.getStats();for(let[,e]of i)if(Xr(e)){let t=i.get(e.localCandidateId),r=i.get(e.remoteCandidateId);t&&(this._log.info(`local candidate: ${t.candidateType} ${t.protocol}:${t.ip||t.address}:${t.port} ${t.networkType||""} ${t.candidateType==="relay"?`relayProtocol:${t.relayProtocol}`:""}`),this._localAddress=`${t.ip||t.address}:${t.port}`),r&&(this._log.info(`remote candidate: ${r.candidateType} ${r.protocol}:${r.ip||r.address}:${r.port}`),this._remoteAddress=`${r.protocol}:${r.ip||r.address}`);break}})}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise?this._waitForPeerConnectionConnectedPromise:(this._waitForPeerConnectionConnectedPromise=new Promise((i,e)=>{if(this._currentState==="CONNECTED")return i();this._waitForPeerConnectionConnectedPromiseReject=e;let t=a=>{a.state==="CONNECTED"&&(clearTimeout(n),o(),i())},r=({room:a})=>{a===this._room&&(clearTimeout(n),o(),e(new X({code:H.API_CALL_ABORTED,message:pe({key:me.CONNECTION_ABORTED,data:"leave room"})})))},o=()=>{x.off(B.LEAVE_SUCCESS,r,this),this._emitter.off("connection-state-changed",t,this)},n=setTimeout(()=>{o();let a=new X({code:H.API_CALL_TIMEOUT,message:"connection timeout"});Hh+=1,AS(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),Gh=!0,this._emitter.emit("firewall-restriction")),e(a)},on);x.on(B.LEAVE_SUCCESS,r,this),this._emitter.on("connection-state-changed",t,this)}),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally(()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null}),this._waitForPeerConnectionConnectedPromise)}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(rt.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=dr()){this._log.warn(`SDK has tried reconnect for ${this._reconnectionCount} times, but all failed, please check your network`),this.stopReconnection();let i=new X({code:this._isUplink?H.UPLINK_RECONNECTION_FAILED:H.DOWNLINK_RECONNECTION_FAILED,message:pe({key:this._isUplink?me.UPLINK_RECONNECTION_FAILED:me.DOWNLINK_RECONNECTION_FAILED})});return this.emitConnectionStateChangedEvent("DISCONNECTED"),this._emitter.emit("error",i),-1}return this._signalChannel.isConnected?(this._reconnectionCount+=1,this._log.warn(`reconnect() trying [${this._reconnectionCount}]`),1):(this._log.warn("reconnect() signal channel is not connected, suspend reconnection until signal is connected"),this._signalChannel.once(rt.CONNECTED,this.reconnect,this),-1)}on(i,e,t){this._emitter.on(i,e,t)}off(i,e,t){this._emitter.off(i,e,t)}getIsReconnecting(){return this._isReconnecting}get isH264(){var i,e;return!!((e=(i=this._peerConnection)==null?void 0:i.remoteDescription)!=null&&e.sdp.includes("H264"))}setOffer(i){var e;return(e=this._peerConnection)==null?void 0:e.setLocalDescription(i)}setAnswer(i){var e;return(e=this._peerConnection)==null?void 0:e.setRemoteDescription(i)}};J([zt(521712,!1)],$t.prototype,"setOffer",1),J([zt(521713,!1)],$t.prototype,"setAnswer",1);var qh=gt(Jh());var et=function(s){return qh.default.parse(s)},li=function(s){return qh.default.write(s)},o_=function(s){let i=et(s);return i.media.forEach(e=>{e.type===S.AUDIO&&e.fmtp.forEach(t=>{t.config+=";sprop-stereo=1;stereo=1"})}),li(i)};function n_(s){let i=et(s);return i.media.forEach(e=>{var t,r;if(e.type===S.VIDEO){let o=new Set;e.rtp.forEach(({payload:a,codec:d})=>d==="H264"&&o.add(a)),e.fmtp.forEach(({payload:a,config:d})=>{let l=d.match(/apt=(\d+)/);l&&l[1]&&o.has(Number(l[1]))&&o.add(a)});let n=({payload:a})=>!o.has(a);e.rtp=e.rtp.filter(n),e.rtcpFb=(t=e.rtcpFb)==null?void 0:t.filter(n),e.fmtp=e.fmtp.filter(n),e.payloads=(r=e.payloads)==null?void 0:r.split(" ").filter(a=>!o.has(Number(a))).join(" ")}}),li(i)}function xc(s){return Object.keys(s).filter(i=>s[i])}var $o=class $o extends $t{constructor(e){super(de(Z({},e),{isUplink:!1}));c(this,"_flag",0);c(this,"isRobot",!1);c(this,"role","anchor");c(this,"remoteAudioTrack");c(this,"remoteVideoTrack");c(this,"remoteAuxiliaryTrack");c(this,"ssrc",{audio:0,video:0,auxiliary:0});c(this,"_isSDPExchanging",!1);this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=e.remoteAudioTrack||new Ci(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new er(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new Do(this._room,this)}get videoCodec(){var t,r;let e=(r=(t=this._peerConnection)==null?void 0:t.remoteDescription)==null?void 0:r.sdp;return e?e.includes("H264")?"h264":"vp8":"h264"}get subscribeState(){let e={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(this.remoteVideoTrack.mediaType&8?e.smallVideo=!0:e.video=!0),this.remoteAudioTrack.isSubscribed&&(e.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(e.auxiliary=!0),e}get muteState(){return ur(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,r,o;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(r=this.remoteVideoTrack)==null||r.onFlagChanged(),(o=this.remoteAuxiliaryTrack)==null||o.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===S.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var o,n;let t=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&t!==e&&((o=this.remoteVideoTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),r}onTrack(e){let t=e.streams[0],{track:r}=e,o=t.id===sn?S.MAIN:S.AUXILIARY;this._log.debug(`ontrack ${o} ${r.kind}`);let n=S.AUDIO;r.kind===S.VIDEO&&(n=o===S.MAIN?S.VIDEO:S.AUXILIARY);let a=this.remoteAudioTrack;n===S.VIDEO?a=this.remoteVideoTrack:n===S.AUXILIARY&&(a=this.remoteAuxiliaryTrack),a.setInputMediaStreamTrack(r)}addRRTRLine(e){let t=e.split(`\r
|
|
74
74
|
`),r=new Map;t.forEach((n,a)=>{/^a=rtcp-fb:/.test(n)&&t[a+1]&&!/^a=rtcp-fb:/.test(t[a+1])&&r.set(a+1,`${n.match(/^a=rtcp-fb:\d+/)[0]} rrtr`)});let o=[...r];for(let n=0;n<o.length;n++){let[a,d]=o[n];t.splice(a+n,0,d)}return t.join(`\r
|
|
75
75
|
`)}addSPSDescription(e){let t=et(e);return t.media.forEach(r=>{r.type===S.VIDEO&&r.fmtp.forEach(o=>{o.config+=";sps-pps-idr-in-keyframe=1"})}),li(t)}removeSDESDescription(e){let t=["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"],r=et(e);return r.media.forEach(o=>{o.ext&&(o.ext=o.ext.filter(n=>!t.includes(n.uri)))}),li(r)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return A(this,null,function*(){var r,o;try{if((((r=this._peerConnection)==null?void 0:r.connectionState)===Je.NEW||((o=this._peerConnection)==null?void 0:o.connectionState)===Je.CONNECTING)&&(yield this.waitForPeerConnectionConnected()),this.isSubscriptionStateNotChanged(e)){this._peerConnection||(this.initialize(),yield this.connect(e));return}if(this._log.info(`subscribe ${t} ${JSON.stringify(e)}`),this._peerConnection||this._isSDPExchanging){let n="subscribe_change";Object.values(e).find(a=>a===!0)||(n="unsubscribe"),yield this.sendSubscription(n,e)}else this.initialize(),yield this.connect(e)}catch(n){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${n.message} ${JSON.stringify(this.muteState)}`),new X({code:H.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):n}})}unsubscribe(r){return A(this,arguments,function*({remoteTracks:e,streamType:t}){if(this._currentState==="CONNECTED"&&(t==="main"&&!this.isMainStreamSubscribed||t==="auxiliary"&&!this.isAuxStreamSubscribed)){this._log.info(`${t} stream already unsubscribed`);return}let o=Z({},this.subscribeState);e.forEach(a=>{switch(a.mediaType){case 1:o.audio=!1;break;case 4:o.video=!1;break;case 8:o.smallVideo=!1;break;case 2:o.auxiliary=!1;break;default:break}});let n="subscribe_change";Object.values(o).find(a=>a===!0)||(n="unsubscribe"),this._log.info(`${n==="unsubscribe"?n:"subscribe"} ${t} [${xc(o)}]`),yield this.sendSubscription(n,o),n==="unsubscribe"&&(this.closePeerConnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"))})}sendSubscription(e,t=this.subscribeState){let r={srcTinyId:this.tinyId,srcUserId:this.userId},o=ve.UNSUBSCRIBE,n=Ee.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(r={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},o=ve.SUBSCRIBE_CHANGE,n=Ee.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:o,data:r,responseCommand:n,timeout:1e4}).then(({data:a})=>{if(a.code!==0){let d=new X({code:a.code,message:pe({key:me.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(d),d}})}connect(){return A(this,arguments,function*(e=this.subscribeState){try{yield this.exchangeSDP(e),yield this.waitForPeerConnectionConnected()}catch(t){throw this.closePeerConnection(!0),t}})}exchangeSDP(e){return A(this,null,function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info("createOffer success, sending offer");let{type:t,sdp:r}=this._peerConnection.localDescription,o={type:t,sdp:r,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},n=yield this._signalChannel.sendWaitForResponse({command:ve.SUBSCRIBE,commandDesc:"exchange sdp",data:o,responseCommand:Ee.SUBSCRIBE_RESULT,timeout:dl});if(!this._peerConnection){let a=new X({code:H.INVALID_OPERATION,message:pe({key:me.CONNECTION_CLOSED})});throw this._log.warn(a),a}yield this.onSubscribeResult(n),this._isSDPExchanging=!1}catch(t){throw this._isSDPExchanging=!1,t}})}createOffer(){return A(this,null,function*(){let e={voiceActivityDetection:!1};Yt()&&this._sdpSemantics===Gr?(this._peerConnection.addTransceiver(S.AUDIO,{direction:ke.RECVONLY}),this._peerConnection.addTransceiver(S.VIDEO,{direction:ke.RECVONLY}),this._peerConnection.addTransceiver(S.VIDEO,{direction:ke.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:r}=yield Ed();r||(this._log.warn("remove h264 desc from sdp"),t.sdp=n_(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=o_(t.sdp),this._sdpSemantics===Gr&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this.setOffer(t)})}onSubscribeResult(e){return A(this,null,function*(){let{code:t,message:r=""}=e&&e.data||{},{type:o,sdp:n}=e&&e.data&&e.data.data||{};if(t===cs)throw new X({code:H.NOT_SUPPORTED_H264,message:pe({key:me.NOT_SUPPORTED_H264DECODE})});try{if(t!==0)throw new X({code:t,message:pe({key:me.EXCHANGE_SDP_FAILED,data:{errMsg:r}})});this._log.debug(`accept remote answer: ${n}`),yield this.setAnswer({type:o,sdp:n}),this.updateSSRC(n)}catch(a){throw this._log.error(a),a}})}updateSSRC(e){try{et(e).media.forEach(r=>{if(r.ssrcs)if(r.type===S.AUDIO){let o=r.ssrcs.find(n=>{var a;return(a=n.value)==null?void 0:a.includes(sn)});o&&(this.ssrc.audio=Number(o.id))}else{let o=r.ssrcs.find(a=>{var d;return(d=a.value)==null?void 0:d.includes(sn)}),n=r.ssrcs.find(a=>{var d;return(d=a.value)==null?void 0:d.includes(rl)});o&&(this.ssrc.video=Number(o.id)),n&&(this.ssrc.auxiliary=Number(n.id))}})}catch(t){}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return A(this,null,function*(){if(!(Ct($o.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch(t){let r=pi(this._reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${r/1e3}s`),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},r)}})}getIsReconnecting(){return this._isReconnecting}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}getCurrentState(){return this._currentState}setDelay({audioDelay:e,videoDelay:t}){this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=t}get audioReceiver(){var e;return((e=this._peerConnection)==null?void 0:e.getReceivers()[0])||null}};J([be(e=>function(...t){return new Promise((r,o)=>{let n=a=>{this._emitter.off("closed",n),o(new X({code:H.API_CALL_ABORTED,message:pe({key:me.CONNECTION_ABORTED,data:a})}))};this._emitter.on("closed",n),e.apply(this,t).then(r,o).finally(()=>{this._emitter.off("closed",n)})})})],$o.prototype,"subscribe",1),J([zt(521717,!1)],$o.prototype,"unsubscribe",1),J([Ut($t.prototype.afterConnect),xd($t.prototype.beforeConnect)],$o.prototype,"connect",1);var Xh=$o,Qh=Xh;var d_={voiceActivityDetection:!1},Fo=class Fo extends $t{constructor(e){super(de(Z({},e),{isUplink:!0}));c(this,"localMainAudioTrack",null);c(this,"localMainVideoTrack",null);c(this,"localAuxAudioTrack",null);c(this,"localAuxVideoTrack",null);c(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0});c(this,"_isPublishingAux",!1);c(this,"_publishingLocalAudioTrack");c(this,"_publishingLocalVideoTrack");c(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0});c(this,"flag",0)}get videoCodec(){return this._mediaSettings.videoCodec.toLowerCase()||"h264"}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}get publishState(){var t,r,o,n;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(Hi()?(e.audio=!!((t=a[0])!=null&&t.track),e.bigVideo=!!((r=a[1])!=null&&r.track),e.smallVideo=!!((o=a[2])!=null&&o.track),e.auxVideo=!!((n=a[3])!=null&&n.track)):a.forEach(d=>{d.track&&(d.track.kind===S.AUDIO?e.audio=!0:(e.bigVideo=!0,this._room.videoManager.hasSmall&&(e.smallVideo=!0)))}))}return e}initialize(){super.initialize(),this.installEvents()}reset(){this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this.uninstallEvents()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this._emitter.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this._emitter.on("connection-state-changed",this.handleConnectionStateChange,this)}uninstallEvents(){this._emitter.off("connection-state-changed",this.handleConnectionStateChange,this)}emitConnectionStateChangedEvent(e,t){var n,a,d;let r=this._currentState,o=super.emitConnectionStateChangedEvent(e);return o&&r!==e&&(t?t.emit("connection-state-changed",{prevState:r,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:r,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:r,state:e}),(d=this._publishingLocalVideoTrack)==null||d.emit("connection-state-changed",{prevState:r,state:e}))),o}publish(o){return A(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:r}){this._peerConnection||this.initialize(),e&&(this._publishingLocalAudioTrack=e),t&&(this._publishingLocalVideoTrack=t),this._isPublishingAux=r;let n;t&&!r&&t.small&&(n=this._room.videoManager.smallTrack),this.sendMediaSettings(),Yt()?yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:n,isAuxiliary:r}):yield this.publishByAddTrack({localAudioTrack:e,localVideoTrack:t,smallTrack:n}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,r?(t&&(this.localAuxVideoTrack=t),e&&(this.localAuxAudioTrack=e)):(t&&(this.localMainVideoTrack=t),e&&(this.localMainAudioTrack=e)),this.installTrackMuteEvents(e,t),this.sendMutedFlag()})}publishByTransceiver(n){return A(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:r,isAuxiliary:o}){this._log.info("publish by transceiver");let a=new MediaStream,d=t==null?void 0:t.outMediaTrack,l=e==null?void 0:e.outMediaTrack;l&&a.addTrack(l),d&&a.addTrack(d);let h=this._peerConnection.getTransceivers();if(h.length===0)this._peerConnection.addTransceiver(l||S.AUDIO,{direction:ke.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(o?S.VIDEO:d||S.VIDEO,{direction:ke.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(r||S.VIDEO,{direction:ke.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(o?d||S.VIDEO:S.VIDEO,{direction:ke.SENDONLY,streams:[a]}),yield this.connect();else{let u=[];if(l&&(h[0].sender.track||u.push(0),yield h[0].sender.replaceTrack(l),yield this.setBandwidth({bandwidth:(e==null?void 0:e.profile.bitrate)||40,type:S.AUDIO})),d){let m=o?3:1;yield h[m].sender.replaceTrack(d),yield this.setBandwidth({bandwidth:t.profile.bitrate,type:S.VIDEO,videoType:o?S.AUXILIARY:S.BIG}),u.push(m),r&&(yield h[2].sender.replaceTrack(r),yield this.setBandwidth({bandwidth:t.small.bitrate,type:S.VIDEO,videoType:S.SMALL}),u.push(2))}yield this.setTransceiverDirection(ke.SENDONLY,u),yield this.doPublishChange(),t==null||t.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),t==null||t.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"})}})}publishByAddTrack(o){return A(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:r}){this._log.info("publish by addtrack");let n=t==null?void 0:t.outMediaTrack,a=e==null?void 0:e.outMediaTrack;if(this._peerConnection&&this._peerConnection.connectionState!=="new"){e&&a&&(yield this.addTrack(e)),n&&(yield this.addTrack(t));return}let d=new MediaStream;if(a&&d.addTrack(a),n&&d.addTrack(n),a&&this._peerConnection.addTrack(a,d),n&&(this._peerConnection.addTrack(n,d),r)){let l=new MediaStream;l.addTrack(r),this._peerConnection.addTrack(r,l)}yield this.connect()})}enableSmall(e){return A(this,null,function*(){let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.setTransceiverDirection(ke.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(ke.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()})}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(r){return A(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){if(!Hi()){if(e&&e.outMediaTrack&&!t&&this.localMainVideoTrack){yield this.removeTrack(e),this.localMainAudioTrack=null;return}if(t&&t.outMediaTrack&&!e&&this.localMainAudioTrack){yield this.removeTrack(t),this.localMainVideoTrack=null;return}yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),this.emitConnectionStateChangedEvent("DISCONNECTED",t);return}let o=t&&t===this.localAuxVideoTrack,n=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),d=[];e&&(o?this.localAuxAudioTrack=null:this.localMainAudioTrack=null,!this.localAuxAudioTrack&&!this.localMainAudioTrack&&(yield a[0].replaceTrack(null),d.push(0))),n&&(o?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=de(Z({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),d.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=de(Z({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),d.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.setTransceiverDirection(ke.INACTIVE,d),yield this.doPublishChange(!1)):yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),t==null||t.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return A(this,null,function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},r=yield this._signalChannel.sendWaitForResponse({command:ve.PUBLISH_STATE_CHANGE,data:t,responseCommand:Ee.PUBLISH_STATE_CHANGE_RESULT,enableLog:e});this.checkPublishResultCode(r.data.code,r.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:ve.UNPUBLISH,commandDesc:"unpublish",responseCommand:Ee.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===H.API_CALL_TIMEOUT)return Promise.resolve();throw t})}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let r=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:o,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:o=this._publishingLocalVideoTrack),Gi){if(r&&r.outMediaTrack){let a=r.outMediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=r.profile.bitrate*1e3,this._mediaSettings.audioFs=a.sampleRate||0}if(o&&o.outMediaTrack){let a=o.outMediaTrack.getSettings();this._mediaSettings.videoWidth=a.width||0,this._mediaSettings.videoHeight=a.height||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=o.profile.bitrate*1e3,o.small&&(this._mediaSettings.smallVideoWidth=o.small.width,this._mediaSettings.smallVideoHeight=o.small.height,this._mediaSettings.smallVideoFps=o.small.frameRate,this._mediaSettings.smallVideoBps=o.small.bitrate*1e3)}if(n&&n.outMediaTrack){let a=n.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=a.width||0,this._mediaSettings.auxVideoHeight=a.height||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=n.profile.bitrate*1e3}}else r&&r.outMediaTrack&&(this._mediaSettings.audioChannel=r.profile.channelCount,this._mediaSettings.audioBps=r.profile.bitrate*1e3,this._mediaSettings.audioFs=r.profile.sampleRate),o&&o.outMediaTrack&&(this._mediaSettings.videoWidth=o.profile.width,this._mediaSettings.videoHeight=o.profile.height,this._mediaSettings.videoFps=o.profile.frameRate,this._mediaSettings.videoBps=o.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:ve.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:Ee.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return A(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is adding ${e.kind} track to current published local ${t?S.AUXILIARY:S.MAIN} stream`),Yt()?yield this.addTrackByTransceiver(e,t):yield this.addTrackBySender(e)})}addTrackByTransceiver(e,t){return A(this,null,function*(){var o;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===S.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),n===1&&((o=this.localMainVideoTrack)!=null&&o.small)&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===ke.INACTIVE&&(yield this.setTransceiverDirection(ke.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}addTrackBySender(e){return A(this,null,function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;Hi()&&this._peerConnection.getTransceivers().findIndex(o=>o.direction==="stopped")>=0&&(this._log.warn("transceiver is stopping, negotiate sdp first"),yield this.updateOffer("remove",t));let r=this._peerConnection.getSenders().find(o=>o.track&&o.track.kind===t.kind);if(r&&r.track){this._log.warn("sender already exists, remove sender first");let o=r.track;this.removeSender(r),yield this.updateOffer("remove",o)}if(t&&this._peerConnection.addTrack(t,new MediaStream([t])),t.kind===S.VIDEO&&e instanceof Nt&&e.small){let o=new MediaStream,{smallTrack:n}=this._room.videoManager;o.addTrack(n),this._peerConnection.addTrack(n,o)}yield this.updateOffer("add",t)})}isNeedToResetOfferOrder(){if(this._sdpSemantics===Js||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=et(e);for(let r=0;r<t.media.length;r++)if(Number(t.media[r].mid)===0&&t.media[r].type===S.VIDEO)return!0;return!1}removeSender(e){let t=null;Hi()&&(t=this._peerConnection.getTransceivers().find(r=>r.sender&&r.sender.track===e.track)),this._peerConnection.removeTrack(e),t&&Fe(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return A(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${t?S.AUXILIARY:S.MAIN} stream`),Yt()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)})}removeTrackByTransceiver(e,t){return A(this,null,function*(){if(!e.outMediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===S.AUDIO)yield r[0].sender.replaceTrack(null);else{let o=t?3:1;yield r[o].sender.replaceTrack(null),o===1&&e.small&&(yield r[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(ke.INACTIVE,[o])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,t){return A(this,null,function*(){if(!Ue)return;let r=!1,o=!1;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let n=this._peerConnection.getTransceivers();if(t.forEach(l=>{n[l].direction!==e&&(n[l].direction=e,r=!0)}),r){this._log.info("updating offer");let l=yield this._peerConnection.createOffer();yield this.setOffer(l)}let a=-1,d=this._peerConnection.remoteDescription.sdp.split(`\r
|
|
76
76
|
`).map(l=>{if(l.match(new RegExp(`a=(${ke.INACTIVE}|${ke.RECVONLY}|${ke.SENDONLY})`))&&a++,t.includes(a)){if(e===ke.INACTIVE&&l.includes(`a=${ke.RECVONLY}`))return o=!0,`a=${e}`;if(e===ke.SENDONLY&&l.includes(`a=${ke.INACTIVE}`))return o=!0,`a=${ke.RECVONLY}`}return l}).join(`\r
|