trtc-sdk-v5 5.11.0-beta.4 → 5.11.0-beta.5
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/video-mixer/package.json +1 -1
- package/plugins/video-effect/virtual-background/package.json +1 -1
- package/plugins/video-effect/watermark/package.json +1 -1
- package/plugins/voice-changer/package.json +1 -1
- package/trtc.esm.js +3 -3
- package/trtc.js +1 -1
package/trtc.esm.js
CHANGED
|
@@ -48,13 +48,13 @@ uniform sampler2D u_texture;
|
|
|
48
48
|
|
|
49
49
|
void main() {
|
|
50
50
|
gl_FragColor = texture2D(u_texture, v_texCoord);
|
|
51
|
-
} `;var qr=class extends H{constructor(e){super();d(this,"frameRate");d(this,"_canvas");d(this,"log");d(this,"hasAlpha",!1);d(this,"name");d(this,"error");this.name=e.name,this.log=e.logger.createChild({id:`vc-${this.name}`}),this.frameRate=e.frameRate}set width(e){this._canvas&&(this._canvas.width=e)}get width(){var e;return((e=this._canvas)==null?void 0:e.width)||0}set height(e){this._canvas&&(this._canvas.height=e)}get height(){var e;return((e=this._canvas)==null?void 0:e.height)||0}setSize(e,t){this._canvas&&(this._canvas.width=e,this._canvas.height=t)}createVideoTrackSource(e,t){return new Ji(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new Us(this,e)}createVideoImageSource(e,t){return new tn(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new rn(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}};d(qr,"_ids",0);var yT={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},Vs=class Vs extends qr{constructor(){super(...arguments);d(this,"defaultProgam");d(this,"defaultVShader");d(this,"defaultFShader");d(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${qr._ids++}`),this.ctx=this._canvas.getContext("webgl2",yT),!this.ctx)throw new y({code:I.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,RT),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,CT),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new y({code:I.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})}destroy(e){let t="";return e&&(t=e.message,this.error=e,b.addFailedEvent({key:512702,error:e})),this.disconnect(),this.log.info(`video context destroy${t}`?`: ${t}`:""),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),e}set width(e){var t;(t=this.ctx)==null||t.viewport(0,0,e,this.height),super.width=e}set height(e){var t;(t=this.ctx)==null||t.viewport(0,0,this.width,e),super.height=e}setSize(e,t){var r;(r=this.ctx)==null||r.viewport(0,0,e,t),super.setSize(e,t)}createShader(e,t){let r=this.ctx,o=r.createShader(e);return r.shaderSource(o,t),r.compileShader(o),o}createProgram(e,t){let r=this.ctx,o=r.createProgram();return r.attachShader(o,e),r.attachShader(o,t),r.linkProgram(o),r.getProgramParameter(o,r.LINK_STATUS)||this.log.error(r.getProgramInfoLog(o)),o}};d(Vs,"UNAVAILABLE","unavailable"),v([Te(H.INIT,"created",{sync:!0,fail(e){this.log.error("video gl context create failed",e.cause),b.addFailedEvent({key:512700,error:e.cause||e})},success(){this.log.info("video context created use webgl"),b.addSuccessEvent({key:512700})}})],Vs.prototype,"create",1),v([Te("created",H.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(Vs.UNAVAILABLE,e),this.removeAllListeners()}})],Vs.prototype,"destroy",1);var ke=Vs,Xe=class extends qr{constructor(){super(...arguments);d(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${qr._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new y({code:I.VIDEO_MANAGER_ERROR,extraCode:2,message:"2d context not supported"});this._canvas.addEventListener("contextlost",()=>{this.log.error("2d context lost")}),this._canvas.addEventListener("contextrestored",()=>{this.log.warn("2d context restored")})}destroy(e){let t="";e&&(t=e.message,this.error=e,b.addFailedEvent({key:512703,error:e})),this.disconnect(),this.log.info(`video context destroy ${t?`: ${t}`:""}`),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners(),b.addSuccessEvent({key:512703})}};v([Te(H.INIT,"created",{sync:!0,fail(e){this.log.error("video 2d context create failed",e.cause),b.addFailedEvent({key:512701,error:e.cause||e})},success(){this.log.info("video context created use 2d"),b.addSuccessEvent({key:512701})}})],Xe.prototype,"create",1),v([Te("created",H.INIT,{ignoreError:!0,sync:!0})],Xe.prototype,"destroy",1);function bT(s){return[15,30,45,60].reduce((e,t)=>Math.abs(t-s)<Math.abs(e-s)?t:e)}var fi=class extends ws{constructor(e,t,r=4){super(e,t,r);d(this,"mediaType",4);d(this,"source");d(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.videoManager,this.once("first-video-frame",o=>{this.room.emit("first-video-frame",o)})}play(e,t){return(me(t==null?void 0:t.canvasRender)?t.canvasRender:ut===17)&&!this.source&&this.useCanvasPlayer(),super.play(e,t).then(()=>{this.player.calculateStat()})}useCanvasPlayer(){if(this.log.info(`useCanvasPlayer(), has element:${!!this.player.element}`),!this.player.element)return;let e=new Xe({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});let t=new Jr(e,{name:"remotePlayer",logger:this.log});this.source=e.createVideoPlayerSource(this.player),this.source.connect(t),this.player.setCanvas(e._canvas),wr()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let t=this.decodeFPS,r=bT(t);if(!q(t)||t<=0){this.log.debug(`updateCanvasPlayerFPS() ignore decoder: ${t} `);return}if(r===e.frameRate){this.log.debug(`updateCanvasPlayerFPS() ignore ClosestFPS ${r} == ${e.frameRate}`);return}this.log.info(`updateCanvasPlayerFPS() decoder: ${t}, closest: ${r}, current: ${e.frameRate}`),e.frameRate=r}get decodeFPS(){var n;let{msg_video_status:e}=((n=this.room.heartbeatReport)==null?void 0:n.msg_down_stream_info.find(a=>a.msg_user_info.str_identifier===this.userId))||{},t=this.mediaType===2?7:this.isSmall?3:2;if(!e||e.length===0)return 0;let r=e.find(a=>a.uint32_video_stream_type===t);return(r==null?void 0:r.uint32_video_dec_fps)||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),super.stop()}decodeFrame(e){if(!this.manager)return e;for(let t of this.manager.decodePipeline)if(t&&(e=t({frame:e,track:this}),!e))return;return e}get isBig(){return this.mediaType===4}get isSmall(){return this.mediaType===8}changeType(e){this.room.changeType(e,this.user)}get isRemotePublished(){return this.user.muteState.videoAvailable}setMirror(e){e==="publish"||e==="both"||super.setMirror(e)}onDecodeDowngradeStateChanged(e){this.emit("decode-downgrade-state-changed",e)}},Bs=class extends fi{constructor(e,t){super(e,t,2);d(this,"mediaType",2);d(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}};var Fs=new Map;E.on(A.JOIN_SUCCESS,({room:s})=>{Ae(s.userId,{eventId:32788})});E.on(A.LEAVE_START,({room:s})=>{Ae(s.userId,{eventId:32789})});E.on(A.LOCAL_TRACK_PUBLISHED,({track:s})=>{if(s.room){let i=32769;s.mediaType===4?i=32768:s.mediaType===2&&(i=32805),Ae(s.room.userId,{eventId:i})}});E.on(A.LOCAL_TRACK_UNPUBLISHED,({track:s})=>{if(s.room){let i=32771;s.mediaType===4?i=32770:s.mediaType===2&&(i=32806),Ae(s.room.userId,{eventId:i})}});E.on(A.TRACK_MUTED,({track:s})=>{s.room&&(s.kind===p.AUDIO?Ae(s.room.userId,{eventId:s.isRemote?32785:32772,remoteUserId:s.isRemote?s.userId:void 0}):Ae(s.room.userId,{eventId:s.isRemote?32784:32773,remoteUserId:s.isRemote?s.userId:void 0}))});E.on(A.TRACK_UNMUTED,({track:s})=>{s.room&&(s.kind===p.AUDIO?Ae(s.room.userId,{eventId:s.isRemote?32787:32774,remoteUserId:s.isRemote?s.userId:void 0}):Ae(s.room.userId,{eventId:s.isRemote?32786:32775,remoteUserId:s.isRemote?s.userId:void 0}))});E.on(A.REMOTE_TRACK_SUBSCRIBED,({track:s})=>{s.room&&(s.mediaType===1&&Ae(s.room.userId,{eventId:32777,remoteUserId:s.userId}),s.mediaType===4&&Ae(s.room.userId,{eventId:32776,remoteUserId:s.userId}),s.mediaType===8&&Ae(s.room.userId,{eventId:32803,remoteUserId:s.userId}))});E.on(A.REMOTE_TRACK_UNSUBSCRIBED,({track:s})=>{s.room&&(s.mediaType===1&&Ae(s.room.userId,{eventId:32779,remoteUserId:s.userId}),s.mediaType===4&&Ae(s.room.userId,{eventId:32778,remoteUserId:s.userId}),s.mediaType===8&&Ae(s.room.userId,{eventId:32804,remoteUserId:s.userId}))});E.on(A.SWITCH_DEVICE_SUCCESS,({track:s})=>{s.room&&Ae(s.room.userId,{eventId:s.kind===p.VIDEO?32780:32781})});E.on(A.LOCAL_TRACK_REPLACED,({track:s})=>{s.room&&Ae(s.room.userId,{eventId:s.kind===p.VIDEO?32782:32783})});E.on(A.SIGNAL_CONNECTION_STATE_CHANGED,({room:s,prevState:i,state:e})=>{let t;switch(e){case"CONNECTED":i==="RECONNECTING"?t=32795:t=32791;break;case"DISCONNECTED":i==="RECONNECTING"?t=32796:t=32790;break;case"RECONNECTING":t=32794;break}t&&Ae(s.userId,{eventId:t})});E.on(A.PEER_CONNECTION_STATE_CHANGED,({room:s,prevState:i,state:e,remoteUserId:t})=>{let r=!!t,o;switch(e){case"CONNECTED":i==="RECONNECTING"?o=r?32801:32798:o=r?32793:32792;break;case"DISCONNECTED":i==="RECONNECTING"&&(o=r?32802:32799);break;case"RECONNECTING":o=r?32800:32797;break}o&&Ae(s.userId,{eventId:o,remoteUserId:t})});E.on(A.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({implementation:s,userId:i,remoteUserId:e,codec:t,isHWCodec:r,prevImplementation:o,streamType:n})=>{let a=r?1:0;o||(a=r?3:2);let c=t==="h264"?0:2,l={eventId:4004,param1:a,param2:c,streamType:n||2};e&&(l.remoteUserId=e,l.eventId=4005),Ae(i,l),b.addEnum({key:e?514701:513701,value:a}),b.addEnum({key:e?514700:513700,value:c})});E.on(A.LOCAL_TRACK_RECAPTURE,({track:s,error:i})=>{if(s.userId){let e={eventId:2003,param1:0};s.kind===p.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType=s.streamType==="auxiliary"?7:2,i&&(e.param1=8)),Ae(s.userId,e)}});function Ae(s,i){let e=L(N({},i),{timestamp:eo()});Fs.has(s)?Fs.get(s).push(e):Fs.set(s,[e])}function wm(s){if(Fs.has(s)){let i=Fs.get(s).map(e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,uint32_param1:e.param1,uint32_param2:e.param2,uint32_video_stream_type:e.streamType}));return Fs.delete(s),i}return[]}function Um(...s){return Q((i,e)=>function(...t){return NT.call(this,s,t,e,this._name),i.apply(this,t)})}function NT(s,i,e,t){try{if(Se(s))for(let r=0;r<s.length;r++)ec.call(this,{rule:s[r],value:i[r],key:s[r].name,fnName:e,className:t});else ec.call(this,{rule:s,value:i[0],key:s.name,fnName:e,className:t})}catch(r){throw C.error(r),r}}function ec({rule:s,value:i,key:e,fnName:t,className:r}){if(T(i)){if(s.required)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_REQUIRED,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(T(s.defaultValue))return;i=s.defaultValue}if(Array.isArray(s.type)){let a=!1;for(let c=0;c<s.type.length;c++)s.type[c]===null&&i===null&&(a=!0),ne(s.type[c])&&i instanceof s.type[c]&&(a=!0),ee(s.type[c])&&Re(i)===s.type[c].toLowerCase()&&(a=!0);if(!a)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_TYPE,data:{key:e,rule:{type:s.type.map(c=>br(c)?os(c):ee(c)?c:Re(c))},fnName:t,value:i},link:{className:r,fnName:t}})})}else if(!T(s.type)&&Re(i)!==s.type)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_TYPE,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(s.allowEmpty===!1){let a=q(i)&&(i===0||Number.isNaN(i)),c=ee(i)&&i.trim()==="";if(a||c)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_EMPTY,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})})}if(s.notLessThanZero&&q(i)&&i<0)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.CANNOT_LESS_THAN_ZERO,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(!T(s.min)&&q(i)&&i<s.min)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_MIN,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(!T(s.max)&&q(i)&&i>s.max)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_MAX,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(ee(s.instanceOf)){if(!i||i._name!==s.instanceOf)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})})}else if(ne(s.instanceOf)&&!(i instanceof s.instanceOf))throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(s.values&&!s.values.includes(i))throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_RANGE,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});let{properties:o}=s;Je(o)&&Mt(i)&&Object.keys(o).forEach(a=>{ec.call(this,{rule:o[a],value:i&&i[a],key:`${e}.${a}`,fnName:t,className:r})});let{arrayItem:n}=s;Je(n)&&Se(i)&&i.forEach((a,c)=>{ec.call(this,{rule:n,value:a,key:`${e}[${c}]`,fnName:t,className:r})}),ne(s.validate)&&s.validate.call(this,i,e,t,r,this)}var Vm=$e(Ye(),1);var tc=class extends Vm.EventEmitter{constructor(e,t,r="userId"){super();this.mySelfId=e;this._log=t;this.key=r;d(this,"userMap",new Map);d(this,"remotePublishedUserMap",new Map)}get hasRobotUser(){return!![...this.remotePublishedUserMap.values()].find(e=>e.isRobot)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:r,tinyId:o,role:n}=e;if(this.userMap.has(t))return;let a={userId:r,tinyId:o,role:n===20?"anchor":"audience"};this.userMap.set(t,a),this.emit("1",a)}deleteUser(e,t){let r=this.userMap.get(e);if(!r)return;let o=`peer leave [${e}]`;T(t)||(o+=`:${Zc[t]}`),this._log.info(o);let n=this.remotePublishedUserMap.get(e);if(n){let a=n.muteState;n.flag=0,this.emit("5",n.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:a,muteState:n.muteState,flag:0})}this.userMap.delete(e),this.emit("2",r.userId)}setUserList(e){this.userMap.forEach(t=>{e.findIndex(r=>r[this.key]===t[this.key])<0&&this.deleteUser(t[this.key],0)}),e.forEach(t=>{!this.userMap.has(t[this.key])&&t[this.key]!==this.mySelfId&&this.addUser(t)})}addRemotePublishedUser(e){this.remotePublishedUserMap.has(e[this.key])||this.remotePublishedUserMap.set(e[this.key],e)}deleteRemotePublishedUser(e){this.remotePublishedUserMap.has(e)&&this.remotePublishedUserMap.delete(e)}setRemotePublishedUserList(e){this.remotePublishedUserMap.forEach(t=>{let r=t[this.key];if(e.findIndex(o=>o[this.key]===t[this.key])<0){this._log.info(`remote [${r}] unpublish`);let o=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(r),this.emit("6",{prevMuteState:o,muteState:t.muteState,flag:0})}}),e.forEach(t=>{var u;let r=t[this.key];if(r===this.mySelfId)return;let{flag:o,userId:n,tinyId:a}=t,c=bi(o,n),l=(u=this.remotePublishedUserMap.get(r))==null?void 0:u.muteState;if(l){let h=this.remotePublishedUserMap.get(r);h&&h.flag!==o&&(h.flag=o,this._log.info(`remote publish updated: ${JSON.stringify(h.muteState)}`),this.emit("6",{prevMuteState:l,muteState:c,flag:o}))}else this._log.info(`remote publish. state: ${JSON.stringify(c)}`),this.addUser({userId:n,tinyId:a,role:20}),this.emit("3",t),this.emit("6",{prevMuteState:bi(0,n),muteState:c,flag:o})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function eu({timesInSecond:s,maxSizeInSecond:i,getSize:e}){return Q((t,r)=>{let o=new WeakMap;return E.on(A.ROOM_DESTROY,({room:n})=>o.delete(n)),function(...n){let a=o.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},o.set(this,a)),a.timestamp===0?a.timestamp=Date.now():Date.now()-a.timestamp>1e3&&(a.timestamp=Date.now(),a.callCountInSecond=0,a.totalSizeInSecond=0),e&&(a.totalSizeInSecond+=e(...n)),a.timestamp!==0&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=s||a.totalSizeInSecond>i))throw new y({code:I.INVALID_OPERATION,message:x({key:P.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=s,isSize:a.totalSizeInSecond>i,name:r,timesInSecond:s,maxSizeInSecond:i}})});a.callCountInSecond++,t.call(this,...n)}})}var vT="2025-06-11 12:34:37",Bm=!0,Fm=function(){var s;if(Bm){Bm=!1,C.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${Xt}/en/index.html`),console.info(`* Changelog: ${Xt}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),C.info("TRTC Web SDK Version:",Pe),Vt||C.debug("Build Time:",vT);let i=`UA: ${navigator.userAgent}
|
|
51
|
+
} `;var qr=class extends H{constructor(e){super();d(this,"frameRate");d(this,"_canvas");d(this,"log");d(this,"hasAlpha",!1);d(this,"name");d(this,"error");this.name=e.name,this.log=e.logger.createChild({id:`vc-${this.name}`}),this.frameRate=e.frameRate}set width(e){this._canvas&&(this._canvas.width=e)}get width(){var e;return((e=this._canvas)==null?void 0:e.width)||0}set height(e){this._canvas&&(this._canvas.height=e)}get height(){var e;return((e=this._canvas)==null?void 0:e.height)||0}setSize(e,t){this._canvas&&(this._canvas.width=e,this._canvas.height=t)}createVideoTrackSource(e,t){return new Ji(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new Us(this,e)}createVideoImageSource(e,t){return new tn(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new rn(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}};d(qr,"_ids",0);var yT={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},Vs=class Vs extends qr{constructor(){super(...arguments);d(this,"defaultProgam");d(this,"defaultVShader");d(this,"defaultFShader");d(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${qr._ids++}`),this.ctx=this._canvas.getContext("webgl2",yT),!this.ctx)throw new y({code:I.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,RT),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,CT),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new y({code:I.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})}destroy(e){let t="";return e&&(t=e.message,this.error=e,b.addFailedEvent({key:512702,error:e})),this.disconnect(),this.log.info(`video context destroy${t}`?`: ${t}`:""),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),e}set width(e){var t;(t=this.ctx)==null||t.viewport(0,0,e,this.height),super.width=e}set height(e){var t;(t=this.ctx)==null||t.viewport(0,0,this.width,e),super.height=e}setSize(e,t){var r;(r=this.ctx)==null||r.viewport(0,0,e,t),super.setSize(e,t)}createShader(e,t){let r=this.ctx,o=r.createShader(e);return r.shaderSource(o,t),r.compileShader(o),o}createProgram(e,t){let r=this.ctx,o=r.createProgram();return r.attachShader(o,e),r.attachShader(o,t),r.linkProgram(o),r.getProgramParameter(o,r.LINK_STATUS)||this.log.error(r.getProgramInfoLog(o)),o}};d(Vs,"UNAVAILABLE","unavailable"),v([Te(H.INIT,"created",{sync:!0,fail(e){this.log.error("video gl context create failed",e.cause),b.addFailedEvent({key:512700,error:e.cause||e})},success(){this.log.info("video context created use webgl"),b.addSuccessEvent({key:512700})}})],Vs.prototype,"create",1),v([Te("created",H.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(Vs.UNAVAILABLE,e),this.removeAllListeners()}})],Vs.prototype,"destroy",1);var ke=Vs,Xe=class extends qr{constructor(){super(...arguments);d(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${qr._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new y({code:I.VIDEO_MANAGER_ERROR,extraCode:2,message:"2d context not supported"});this._canvas.addEventListener("contextlost",()=>{this.log.error("2d context lost")}),this._canvas.addEventListener("contextrestored",()=>{this.log.warn("2d context restored")})}destroy(e){let t="";e&&(t=e.message,this.error=e,b.addFailedEvent({key:512703,error:e})),this.disconnect(),this.log.info(`video context destroy ${t?`: ${t}`:""}`),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners(),b.addSuccessEvent({key:512703})}};v([Te(H.INIT,"created",{sync:!0,fail(e){this.log.error("video 2d context create failed",e.cause),b.addFailedEvent({key:512701,error:e.cause||e})},success(){this.log.info("video context created use 2d"),b.addSuccessEvent({key:512701})}})],Xe.prototype,"create",1),v([Te("created",H.INIT,{ignoreError:!0,sync:!0})],Xe.prototype,"destroy",1);function bT(s){return[15,30,45,60].reduce((e,t)=>Math.abs(t-s)<Math.abs(e-s)?t:e)}var fi=class extends ws{constructor(e,t,r=4){super(e,t,r);d(this,"mediaType",4);d(this,"source");d(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.videoManager,this.once("first-video-frame",o=>{this.room.emit("first-video-frame",o)})}play(e,t){return(me(t==null?void 0:t.canvasRender)?t.canvasRender:ut===17)&&!this.source&&this.useCanvasPlayer(),super.play(e,t).then(()=>{this.player.calculateStat()})}useCanvasPlayer(){if(this.log.info(`useCanvasPlayer(), has element:${!!this.player.element}`),!this.player.element)return;let e=new Xe({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});let t=new Jr(e,{name:"remotePlayer",logger:this.log});this.source=e.createVideoPlayerSource(this.player),this.source.connect(t),this.player.setCanvas(e._canvas),wr()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let t=this.decodeFPS,r=bT(t);if(!q(t)||t<=0){this.log.debug(`updateCanvasPlayerFPS() ignore decoder: ${t} `);return}if(r===e.frameRate){this.log.debug(`updateCanvasPlayerFPS() ignore ClosestFPS ${r} == ${e.frameRate}`);return}this.log.info(`updateCanvasPlayerFPS() decoder: ${t}, closest: ${r}, current: ${e.frameRate}`),e.frameRate=r}get decodeFPS(){var n;let{msg_video_status:e}=((n=this.room.heartbeatReport)==null?void 0:n.msg_down_stream_info.find(a=>a.msg_user_info.str_identifier===this.userId))||{},t=this.mediaType===2?7:this.isSmall?3:2;if(!e||e.length===0)return 0;let r=e.find(a=>a.uint32_video_stream_type===t);return(r==null?void 0:r.uint32_video_dec_fps)||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),super.stop()}decodeFrame(e){if(!this.manager)return e;for(let t of this.manager.decodePipeline)if(t&&(e=t({frame:e,track:this}),!e))return;return e}get isBig(){return this.mediaType===4}get isSmall(){return this.mediaType===8}changeType(e){this.room.changeType(e,this.user)}get isRemotePublished(){return this.user.muteState.videoAvailable}setMirror(e){e==="publish"||e==="both"||super.setMirror(e)}onDecodeDowngradeStateChanged(e){this.emit("decode-downgrade-state-changed",e)}},Bs=class extends fi{constructor(e,t){super(e,t,2);d(this,"mediaType",2);d(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}};var Fs=new Map;E.on(A.JOIN_SUCCESS,({room:s})=>{Ae(s.userId,{eventId:32788})});E.on(A.LEAVE_START,({room:s})=>{Ae(s.userId,{eventId:32789})});E.on(A.LOCAL_TRACK_PUBLISHED,({track:s})=>{if(s.room){let i=32769;s.mediaType===4?i=32768:s.mediaType===2&&(i=32805),Ae(s.room.userId,{eventId:i})}});E.on(A.LOCAL_TRACK_UNPUBLISHED,({track:s})=>{if(s.room){let i=32771;s.mediaType===4?i=32770:s.mediaType===2&&(i=32806),Ae(s.room.userId,{eventId:i})}});E.on(A.TRACK_MUTED,({track:s})=>{s.room&&(s.kind===p.AUDIO?Ae(s.room.userId,{eventId:s.isRemote?32785:32772,remoteUserId:s.isRemote?s.userId:void 0}):Ae(s.room.userId,{eventId:s.isRemote?32784:32773,remoteUserId:s.isRemote?s.userId:void 0}))});E.on(A.TRACK_UNMUTED,({track:s})=>{s.room&&(s.kind===p.AUDIO?Ae(s.room.userId,{eventId:s.isRemote?32787:32774,remoteUserId:s.isRemote?s.userId:void 0}):Ae(s.room.userId,{eventId:s.isRemote?32786:32775,remoteUserId:s.isRemote?s.userId:void 0}))});E.on(A.REMOTE_TRACK_SUBSCRIBED,({track:s})=>{s.room&&(s.mediaType===1&&Ae(s.room.userId,{eventId:32777,remoteUserId:s.userId}),s.mediaType===4&&Ae(s.room.userId,{eventId:32776,remoteUserId:s.userId}),s.mediaType===8&&Ae(s.room.userId,{eventId:32803,remoteUserId:s.userId}))});E.on(A.REMOTE_TRACK_UNSUBSCRIBED,({track:s})=>{s.room&&(s.mediaType===1&&Ae(s.room.userId,{eventId:32779,remoteUserId:s.userId}),s.mediaType===4&&Ae(s.room.userId,{eventId:32778,remoteUserId:s.userId}),s.mediaType===8&&Ae(s.room.userId,{eventId:32804,remoteUserId:s.userId}))});E.on(A.SWITCH_DEVICE_SUCCESS,({track:s})=>{s.room&&Ae(s.room.userId,{eventId:s.kind===p.VIDEO?32780:32781})});E.on(A.LOCAL_TRACK_REPLACED,({track:s})=>{s.room&&Ae(s.room.userId,{eventId:s.kind===p.VIDEO?32782:32783})});E.on(A.SIGNAL_CONNECTION_STATE_CHANGED,({room:s,prevState:i,state:e})=>{let t;switch(e){case"CONNECTED":i==="RECONNECTING"?t=32795:t=32791;break;case"DISCONNECTED":i==="RECONNECTING"?t=32796:t=32790;break;case"RECONNECTING":t=32794;break}t&&Ae(s.userId,{eventId:t})});E.on(A.PEER_CONNECTION_STATE_CHANGED,({room:s,prevState:i,state:e,remoteUserId:t})=>{let r=!!t,o;switch(e){case"CONNECTED":i==="RECONNECTING"?o=r?32801:32798:o=r?32793:32792;break;case"DISCONNECTED":i==="RECONNECTING"&&(o=r?32802:32799);break;case"RECONNECTING":o=r?32800:32797;break}o&&Ae(s.userId,{eventId:o,remoteUserId:t})});E.on(A.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({implementation:s,userId:i,remoteUserId:e,codec:t,isHWCodec:r,prevImplementation:o,streamType:n})=>{let a=r?1:0;o||(a=r?3:2);let c=t==="h264"?0:2,l={eventId:4004,param1:a,param2:c,streamType:n||2};e&&(l.remoteUserId=e,l.eventId=4005),Ae(i,l),b.addEnum({key:e?514701:513701,value:a}),b.addEnum({key:e?514700:513700,value:c})});E.on(A.LOCAL_TRACK_RECAPTURE,({track:s,error:i})=>{if(s.userId){let e={eventId:2003,param1:0};s.kind===p.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType=s.streamType==="auxiliary"?7:2,i&&(e.param1=8)),Ae(s.userId,e)}});function Ae(s,i){let e=L(N({},i),{timestamp:eo()});Fs.has(s)?Fs.get(s).push(e):Fs.set(s,[e])}function wm(s){if(Fs.has(s)){let i=Fs.get(s).map(e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,uint32_param1:e.param1,uint32_param2:e.param2,uint32_video_stream_type:e.streamType}));return Fs.delete(s),i}return[]}function Um(...s){return Q((i,e)=>function(...t){return NT.call(this,s,t,e,this._name),i.apply(this,t)})}function NT(s,i,e,t){try{if(Se(s))for(let r=0;r<s.length;r++)ec.call(this,{rule:s[r],value:i[r],key:s[r].name,fnName:e,className:t});else ec.call(this,{rule:s,value:i[0],key:s.name,fnName:e,className:t})}catch(r){throw C.error(r),r}}function ec({rule:s,value:i,key:e,fnName:t,className:r}){if(T(i)){if(s.required)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_REQUIRED,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(T(s.defaultValue))return;i=s.defaultValue}if(Array.isArray(s.type)){let a=!1;for(let c=0;c<s.type.length;c++)s.type[c]===null&&i===null&&(a=!0),ne(s.type[c])&&i instanceof s.type[c]&&(a=!0),ee(s.type[c])&&Re(i)===s.type[c].toLowerCase()&&(a=!0);if(!a)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_TYPE,data:{key:e,rule:{type:s.type.map(c=>br(c)?os(c):ee(c)?c:Re(c))},fnName:t,value:i},link:{className:r,fnName:t}})})}else if(!T(s.type)&&Re(i)!==s.type)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_TYPE,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(s.allowEmpty===!1){let a=q(i)&&(i===0||Number.isNaN(i)),c=ee(i)&&i.trim()==="";if(a||c)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_EMPTY,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})})}if(s.notLessThanZero&&q(i)&&i<0)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.CANNOT_LESS_THAN_ZERO,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(!T(s.min)&&q(i)&&i<s.min)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_MIN,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(!T(s.max)&&q(i)&&i>s.max)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_MAX,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(ee(s.instanceOf)){if(!i||i._name!==s.instanceOf)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})})}else if(ne(s.instanceOf)&&!(i instanceof s.instanceOf))throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});if(s.values&&!s.values.includes(i))throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PARAMETER_RANGE,data:{key:e,rule:s,fnName:t,value:i},link:{className:r,fnName:t}})});let{properties:o}=s;Je(o)&&Mt(i)&&Object.keys(o).forEach(a=>{ec.call(this,{rule:o[a],value:i&&i[a],key:`${e}.${a}`,fnName:t,className:r})});let{arrayItem:n}=s;Je(n)&&Se(i)&&i.forEach((a,c)=>{ec.call(this,{rule:n,value:a,key:`${e}[${c}]`,fnName:t,className:r})}),ne(s.validate)&&s.validate.call(this,i,e,t,r,this)}var Vm=$e(Ye(),1);var tc=class extends Vm.EventEmitter{constructor(e,t,r="userId"){super();this.mySelfId=e;this._log=t;this.key=r;d(this,"userMap",new Map);d(this,"remotePublishedUserMap",new Map)}get hasRobotUser(){return!![...this.remotePublishedUserMap.values()].find(e=>e.isRobot)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:r,tinyId:o,role:n}=e;if(this.userMap.has(t))return;let a={userId:r,tinyId:o,role:n===20?"anchor":"audience"};this.userMap.set(t,a),this.emit("1",a)}deleteUser(e,t){let r=this.userMap.get(e);if(!r)return;let o=`peer leave [${e}]`;T(t)||(o+=`:${Zc[t]}`),this._log.info(o);let n=this.remotePublishedUserMap.get(e);if(n){let a=n.muteState;n.flag=0,this.emit("5",n.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:a,muteState:n.muteState,flag:0})}this.userMap.delete(e),this.emit("2",r.userId)}setUserList(e){this.userMap.forEach(t=>{e.findIndex(r=>r[this.key]===t[this.key])<0&&this.deleteUser(t[this.key],0)}),e.forEach(t=>{!this.userMap.has(t[this.key])&&t[this.key]!==this.mySelfId&&this.addUser(t)})}addRemotePublishedUser(e){this.remotePublishedUserMap.has(e[this.key])||this.remotePublishedUserMap.set(e[this.key],e)}deleteRemotePublishedUser(e){this.remotePublishedUserMap.has(e)&&this.remotePublishedUserMap.delete(e)}setRemotePublishedUserList(e){this.remotePublishedUserMap.forEach(t=>{let r=t[this.key];if(e.findIndex(o=>o[this.key]===t[this.key])<0){this._log.info(`remote [${r}] unpublish`);let o=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(r),this.emit("6",{prevMuteState:o,muteState:t.muteState,flag:0})}}),e.forEach(t=>{var u;let r=t[this.key];if(r===this.mySelfId)return;let{flag:o,userId:n,tinyId:a}=t,c=bi(o,n),l=(u=this.remotePublishedUserMap.get(r))==null?void 0:u.muteState;if(l){let h=this.remotePublishedUserMap.get(r);h&&h.flag!==o&&(h.flag=o,this._log.info(`remote publish updated: ${JSON.stringify(h.muteState)}`),this.emit("6",{prevMuteState:l,muteState:c,flag:o}))}else this._log.info(`remote publish. state: ${JSON.stringify(c)}`),this.addUser({userId:n,tinyId:a,role:20}),this.emit("3",t),this.emit("6",{prevMuteState:bi(0,n),muteState:c,flag:o})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function eu({timesInSecond:s,maxSizeInSecond:i,getSize:e}){return Q((t,r)=>{let o=new WeakMap;return E.on(A.ROOM_DESTROY,({room:n})=>o.delete(n)),function(...n){let a=o.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},o.set(this,a)),a.timestamp===0?a.timestamp=Date.now():Date.now()-a.timestamp>1e3&&(a.timestamp=Date.now(),a.callCountInSecond=0,a.totalSizeInSecond=0),e&&(a.totalSizeInSecond+=e(...n)),a.timestamp!==0&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=s||a.totalSizeInSecond>i))throw new y({code:I.INVALID_OPERATION,message:x({key:P.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=s,isSize:a.totalSizeInSecond>i,name:r,timesInSecond:s,maxSizeInSecond:i}})});a.callCountInSecond++,t.call(this,...n)}})}var vT="2025-06-11 15:49:23",Bm=!0,Fm=function(){var s;if(Bm){Bm=!1,C.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${Xt}/en/index.html`),console.info(`* Changelog: ${Xt}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),C.info("TRTC Web SDK Version:",Pe),Vt||C.debug("Build Time:",vT);let i=`UA: ${navigator.userAgent}
|
|
52
52
|
CPU core: ${navigator.hardwareConcurrency}, GPU: ${Rd()}`,e=navigator.deviceMemory;e&&(i+=`, minRAM: ${e}GB`),C.info(i),C.info(`URL: ${location.href}${((s=self.frameElement)==null?void 0:s.tagName)==="IFRAME"?" in iframe":""}`),Dr().then(t=>{t&&C.info(xt)})}};var yt={SCENE_LIVE:"live",SCENE_RTC:"rtc",ROLE_ANCHOR:"anchor",ROLE_AUDIENCE:"audience",STREAM_TYPE_MAIN:"main",STREAM_TYPE_SUB:"sub",AUDIO_PROFILE_STANDARD:"standard",AUDIO_PROFILE_STANDARD_STEREO:"standard-stereo",AUDIO_PROFILE_HIGH:"high",AUDIO_PROFILE_HIGH_STEREO:"high-stereo",QOS_PREFERENCE_SMOOTH:"smooth",QOS_PREFERENCE_CLEAR:"clear",SPEAKER:"Speakerphone",HEADSET:"Headset earpiece"};var B={INVALID_PARAMETER:5e3,INVALID_OPERATION:5100,ENV_NOT_SUPPORTED:5200,DEVICE_ERROR:5300,SERVER_ERROR:5400,OPERATION_FAILED:5500,OPERATION_ABORT:5998,UNKNOWN_ERROR:5999},bt=(R=>(R[R.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",R[R.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",R[R.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",R[R.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",R[R.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",R[R.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",R[R.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",R[R.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",R[R.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",R[R.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",R[R.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",R[R.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",R[R.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",R[R.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",R[R.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",R[R.INVALID_ROOM_ID_REQUIRED=5015]="INVALID_ROOM_ID_REQUIRED",R[R.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",R[R.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",R[R.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",R[R.INVALID_ROOM_ID_TYPE_MISMATCH=5019]="INVALID_ROOM_ID_TYPE_MISMATCH",R[R.INVALID_ROOM_ID_DUPLICATE=5020]="INVALID_ROOM_ID_DUPLICATE",R[R.INVALID_OPERATION=5100]="INVALID_OPERATION",R[R.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",R[R.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",R[R.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",R[R.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",R[R.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",R[R.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",R[R.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",R[R.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",R[R.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",R[R.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",R[R.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",R[R.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",R[R.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",R[R.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",R[R.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",R[R.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",R[R.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",R[R.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",R[R.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",R[R.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",R[R.DEVICE_ERROR=5300]="DEVICE_ERROR",R[R.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",R[R.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",R[R.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",R[R.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",R[R.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",R[R.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",R[R.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",R[R.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",R[R.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",R[R.SERVER_ERROR=5400]="SERVER_ERROR",R[R.NEED_TO_BUY=5401]="NEED_TO_BUY",R[R.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",R[R.OPERATION_FAILED=5500]="OPERATION_FAILED",R[R.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",R[R.REJOIN_FAILED=5502]="REJOIN_FAILED",R[R.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",R[R.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",R[R.VIDEO_DECODE_ERROR=5505]="VIDEO_DECODE_ERROR",R[R.OPERATION_ABORT=5998]="OPERATION_ABORT",R[R.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",R))(bt||{});function Hm({code:s,params:i,enableDocLink:e=!1}){let t="",r,o=bt[s];try{r=$m[o]}catch(n){r=$m.UNKNOWN_ERROR}return ne(r)?t=r(i):ee(r)&&(t=r),i.fnName&&!t.includes(i.fnName)&&(t[t.length-1]!=="."&&(t+="."),t+=` thrown from ${i.fnName}()`),e&&(t+=" doc:"),t}var $m=L(N({},Ve),{INVALID_PARAMETER({fnName:s}){return`the parameters of the '${s}' you called does not meet the requirements, please check the API documentation.`},INVALID_PARAMETER_REQUIRED({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' is a required param when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_TYPE({key:s,rule:i,fnName:e,value:t}){let r=`${s||i.name}`,o="";return Array.isArray(i.type)?o=i.type.join("|"):o=i.type,`'${r}' must be type of ${o} when calling ${e}(), received type: ${Re(t)}.`},INVALID_PARAMETER_EMPTY({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' cannot be '${t}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:s,rule:i,fnName:e,value:t}){let r=`${s||i.name}`,o=`${i.instanceOf.name||i.instanceOf}`;return`'${r}' must be instanceof ${o} when calling ${e}(), received type: ${Re(t)}.`},INVALID_PARAMETER_RANGE({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' must be one of ${i.values.join("|")} when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_LESS_THAN_ZERO({key:s,rule:i,fnName:e}){return`'${s||i.name}' cannot be less than 0 when calling ${e}().`},INVALID_PARAMETER_MIN({key:s,rule:i,value:e}){return`the min value of ${s||i.name} is ${i.min}, received: ${e}.`},INVALID_PARAMETER_MAX({key:s,rule:i,value:e}){return`the max value of ${s||i.name} is ${i.max}, received: ${e}.`},INVALID_ELEMENT_ID({key:s,fnName:i}){return`'${s}' is not found in the document object when calling ${i}().`},INVALID_ELEMENT_ID_TYPE({key:s,fnName:i,type:e}){return`the element corresponding to '${s}' must be instanceof HTMLElement when calling ${i}(), received: ${e}.`},INVALID_STREAM_ID({key:s}){return`'${s}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},INVALID_ROOM_ID_STRING({key:s}){return`'${s}' must be a valid string.`},INVALID_ROOM_ID_INTEGER({key:s}){return`'${s}' must be an integer between [1, 4294967294].`},INVALID_ROOM_ID_INTEGER_STRING({key:s}){return`'${s}' must be an integer but go a string, use 'parseInt' to convert it or use 'strRoomId' instead.`},INVALID_ROOM_ID_REQUIRED(){return"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required."},INVALID_ROOM_ID_TYPE_MISMATCH({key:s}){return`The type of target roomId must match the current roomId. Current room is using '${s}', but received '${s==="strRoomId"?"roomId":"strRoomId"}'.`},INVALID_ROOM_ID_DUPLICATE({key:s}){return`the target '${s}' must not be the same as the current '${s}'.`},INVALID_STREAM_TYPE:({fnName:s})=>`'streamType' is required when 'userId' is not '*', calling ${s}()`,INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION({fnName:s}){return`the API '${s}' you called does not meet the requirements, please check the API documentation.`},INVALID_OPERATION_NOT_JOINED({fnName:s}){return`cannot ${s} because you are not enter room yet.`},INVALID_OPERATION_REMOTE_USER_NOT_EXIST({fnName:s,value:i}){return`cannot ${s} because remote user(userId: ${i.userId}) does not publishing stream.`},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST({fnName:s,value:i}){return`cannot ${s} because remote user(userId: ${i.userId}) does not publishing ${i.streamType} video.`},INVALID_OPERATION_REPEAT_CALL({fnName:s}){return`you are already ${s}(), cannot repeated call '${s}'.`},INVALID_OPERATION_NEED_VIDEO({fnName:s}){return`cannot call '${s}' because the camera is not turned on.`},INVALID_OPERATION_NEED_AUDIO({fnName:s}){return`cannot call '${s}' because the microphone or screen share is not turned on.`},INVALID_BUFFER_EMPTY:({key:s})=>`the buffer size of paramerter '${s}' cannot be empty`,INVALID_BUFFER_OVERSIZE:()=>"buffer size is over 1000 Bytes",INVALID_ROLE_AUDIENCE:()=>"role: 'audience' cannot call this api.",INVALID_NOT_ENABLE_SEI:()=>"you need to enable SEI in TRTC.create({ enableSEI: true })",INVALID_NEED_CALL_PUBLISHED:({fnName:s})=>`you need to call ${s}() after publish stream.`,ENV_NOT_SUPPORTED({fnName:s}){return`the current browser does not support the capability of the function '${s}' you are calling, please check the API documentation.`},NOT_SUPPORTED_WEBRTC:"the current browser does not support WebRTC capability, please check the SDK documentation.",NOT_SUPPORTED_H264_ENCODE:"this browser does not support H264 encode.",NOT_SUPPORTED_H264_DECODE:"this browser does not support H264 decode.",NOT_SUPPORTED_SCREEN_SHARE:"this browser does not support screen share, please check the browser version.",NOT_SUPPORTED_SMALL_VIDEO:"this browser does not support small video, please check the browser version.",NOT_SUPPORTED_SEI:"this browser does not support SEI, please check the browser version.",NOT_SUPPORTED_WEBGL:"this browser does not support WebGL, please check the browser version.",NOT_SUPPORTED_CHROME_VERSION({fnName:s}){return`cannot call ${s} because the browser version is too low, please upgrade to the latest version`},DEVICE_ERROR({fnName:s,error:i}){return`'${s}' got device exception${i?`, error: ${i.toString()}.`:"."}`},DEVICE_NOT_FOUND_ERROR({fnName:s,deviceType:i=jr(s),error:e}){return`NotFoundError, no ${i} detected, please check your device and the configuration on '${s}'${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_ALLOWED_ERROR({fnName:s,deviceType:i=jr(s),error:e}){return`NotAllowedError, you have disabled ${i} access, please allow the current application to use the ${i}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_READABLE_ERROR({fnName:s,deviceType:i=jr(s),error:e}){return`NotReadableError, the ${i} maybe in use by another APP, please check if the device is pre-occupied by another APP.`},DEVICE_OVERCONSTRAINED_ERROR({fnName:s,deviceType:i=jr(s),error:e}){return`OverconstrainedError, the device ID is incorrect, please check whether the device ID passed in is correct${e?`, error: ${e.toString()}.`:"."}`},DEVICE_INVALID_STATE_ERROR({fnName:s,deviceType:i=jr(s),error:e}){return`InvalidStateError, after the user clicks and interacts with the page, turn on the ${i}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_SECURITY_ERROR({fnName:s,deviceType:i=jr(s),error:e}){return`SecurityError, check whether the system security policy restricts the use of the ${i}, and it is recommended to turn on the ${i} after the user interacts with the page${e?`, error: ${e.toString()}.`:"."}`},DEVICE_ABORT_ERROR({fnName:s,deviceType:i=jr(s),error:e}){return`AbortError, an unknown exception in the system makes the device unusable, recommended to change the device or browser and re-check whether the device is normal${e?` error: ${e.toString()}.`:"."}`},CAMERA_RECOVER_FAILED({error:s}){return`camera recover capture failed ${(s==null?void 0:s.name)||""}: ${(s==null?void 0:s.originMessage)||(s==null?void 0:s.message)}`},MICROPHONE_RECOVER_FAILED({error:s}){return`microphone recover capture failed ${(s==null?void 0:s.name)||""}: ${(s==null?void 0:s.originMessage)||(s==null?void 0:s.message)}`},OPERATION_FAILED({fnName:s,error:i}){return`'${s}' failed, reason: ${i==null?void 0:i.toString()}`},FIREWALL_RESTRICTION(){return"media connection failure due to firewall restrictions, please try to change your network."},EVENT_HANDLER_ERROR({eventName:s}){return`an error was caught on trtc.on('${s}', handler), please check your code on 'handler'.`},VIDEO_CONTEXT_ERROR({reason:s,error:i}){return`video context error ${s} ${(i==null?void 0:i.name)||""} ${(i==null?void 0:i.message)||""}`},SERVER_ERROR({fnName:s,error:i}){return`'${s}' got server error: ${i==null?void 0:i.toString()}, please check the SDK documentation.`},NEED_TO_BUY({value:s,url:i}){return`You need to buy packages for ${s}. Refer to: ${i}`},ACCOUNT_NO_MONEY:({fnParams:s})=>`your TRTC account run out of credit, please recharge.${s.sdkAppId?` SDKAppId: ${s.sdkAppId}`:""}`,OPERATION_ABORT({fnName:s}){return`'${s}' abort`},UNKNOWN_ERROR({fnName:s,error:i}){return`'${s}' throw unknown exception${i?`, error: ${i.toString()}.`:"."}`}});function jr(s){if(!s)return"camera";let i=s.toLowerCase();return i.includes("screen")?"screen share":i.includes("audio")?"microphone":"camera"}var tu=class s extends Error{constructor({code:e,extraCode:t,message:r="",messageParams:o,fnName:n="",originError:a}){var l;let c;r?c=r:c=Hm({code:e===B.SERVER_ERROR?e:t||e,params:N({fnName:n,error:a},o)});super(c);d(this,"name","RtcError");d(this,"code");d(this,"extraCode");d(this,"functionName");d(this,"message");d(this,"handler");d(this,"originError");this.name=bt[e],this.code=e,this.extraCode=t,this.functionName=n,this.originError=a,this.message=c,this.extraCode===5302&&((l=this.originError)!=null&&l.message.includes("system"))&&(this.handler=()=>{let u={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},h={startLocalVideo:"webcam",startLocalAudio:"microphone"},m=document.createElement("a");vr?m.href=`ms-settings:privacy-${h[this.functionName]}`:Ut&&(m.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${u[this.functionName]}`),m.href.length>0&&m.click()})}static convertFrom(e,t,r){let o=e;if(e instanceof y){let{stack:n}=e,a={code:B.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case I.INVALID_PARAMETER:a.code=B.INVALID_PARAMETER,a.message=e.message;break;case I.INVALID_OPERATION:a.code=B.INVALID_OPERATION;break;case I.NOT_SUPPORTED:case I.NOT_SUPPORTED_H264:a.code=B.ENV_NOT_SUPPORTED,e.getCode()===I.NOT_SUPPORTED_H264&&(a.extraCode=e.message.includes(Ve.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case I.JOIN_ROOM_FAILED:a.messageParams={fnParams:r};case I.SERVER_TIMEOUT:case I.SWITCH_ROLE_FAILED:case I.SWITCH_ROOM_FAILED:a.code=B.SERVER_ERROR,a.extraCode=e.getExtraCode();break;case I.API_CALL_ABORTED:a.code=B.OPERATION_ABORT;break;case I.DEVICE_NOT_FOUND:case I.DEVICE_AUTO_RECOVER_FAILED:case I.INITIALIZE_FAILED:a.code=5300,e.name&&(a.extraCode=DT(e.name));break;case I.UNKNOWN:break;default:a.code=B.OPERATION_FAILED}o=new s(a),n&&(o.stack+=n.substr(n.indexOf(`
|
|
53
53
|
`)))}else{if(e instanceof s)return e;o=new s({code:B.UNKNOWN_ERROR,fnName:t,originError:e})}return o}};function DT(s){let i;switch(s){case"NotFoundError":i=5301;break;case"NotAllowedError":i=5302;break;case"NotReadableError":i=5303;break;case"OverconstrainedError":i=5304;break;case"InvalidStateError":i=5305;break;case"SecurityError":i=5306;break;case"AbortError":i=5307;break;default:i=5300}return i}var U=tu;function hr(s){return s==="sub"?"auxiliary":s==="auxiliary"?"sub":"main"}function sn(s){return s===yt.QOS_PREFERENCE_CLEAR?"detail":s===yt.QOS_PREFERENCE_SMOOTH?"motion":""}function $s(s,i){let e=i?Wc:er;return ad(s)?N(N({},e),s):Dt[s]?Dt[s]:e}var Gm={type:"object",properties:{cameraId:{type:"string"},useFrontCamera:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:["string","boolean"],values:[!0,!1,"view","publish","both"]},small:{type:["string","object","boolean"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack}}},Wm={type:"object",properties:{systemAudio:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},profile:{type:["string","object"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack},audioTrack:{instanceOf:MediaStreamTrack}}},Hs={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(s,i,e){if(ee(s)&&!document.getElementById(s))throw new U({code:B.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:i}})}},Jm={name:"userId",required:!0,type:"string"},qm={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[yt.AUDIO_PROFILE_STANDARD,yt.AUDIO_PROFILE_STANDARD_STEREO,yt.AUDIO_PROFILE_HIGH,yt.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function Gs(s,i){if(!s)throw new U({code:B.INVALID_OPERATION,extraCode:5101,fnName:i})}function jm(s,i,e){if(!s)throw new U({code:B.INVALID_OPERATION,extraCode:5102,fnName:i,messageParams:{value:e}})}function Xm(s,i,e){if(!(/^[1-9]\d*$/.test(String(s))&&s<4294967295))throw new U({code:B.INVALID_PARAMETER,extraCode:5013,fnName:i,messageParams:{key:e}})}function zm(s,i,e){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(s))throw new U({code:B.INVALID_PARAMETER,extraCode:5012,fnName:i,messageParams:{key:e}})}var HO={type:"number",notLessThanZero:!0},OT=(s,i)=>s.width*s.height>=i.width*i.height&&s.frameRate>=i.frameRate&&s.bitrate>=i.bitrate;function Qm(s){var t;if(!((t=s==null?void 0:s.option)!=null&&t.small))return;if(!_a()){C.warn("small stream is not supported"),delete s.option.small;return}let i=$s(s.option.profile),e=$s(s.option.small,!0);if(!OT(i,e)){C.warn(`small stream profile must be less than big stream profile. Big: ${JSON.stringify(i)}, Small: ${JSON.stringify(e)}`),delete s.option.small;return}}var MT={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(s,i,e){if(this._room.isJoined)throw new U({code:B.INVALID_OPERATION,extraCode:5104,fnName:e});if(s.roomId){if(ee(s.roomId))throw new U({code:B.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:i}});Xm(s.roomId,e,i)}else if(s.strRoomId)zm(s.strRoomId,e,i);else throw new U({code:B.INVALID_PARAMETER,extraCode:5015,fnName:e})},properties:{sdkAppId:{required:!0,type:"number",allowEmpty:!1},userId:{required:!0,type:"string",allowEmpty:!1},userSig:{required:!0,type:"string",allowEmpty:!1},scene:{type:"string",values:["live","rtc"]},role:{type:"string",values:["audience","anchor"]},roomId:{type:["string","number"]},strRoomId:{type:"string"},proxy:{type:["object","string"],properties:{websocketProxy:{type:"string"},turnServer:{type:["object","array"],properties:{url:{required:!0,type:"string"},username:{type:"string"},credential:{type:"string"},credentialType:{type:"string",values:["password"]}}},loggerProxy:{type:"string"},webtransportProxy:{type:"string"}}},enableAutoPlayDialog:{type:"boolean"},userDefineRecordId:{type:"string"},latencyLevel:{type:"number"},playoutDelay:{type:"object",properties:{min:{type:"number",min:0,max:1e3},max:{type:"number",min:0,max:1e4}}}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:Hs,mute:{type:["boolean","string"]},publish:{type:"boolean"},capture:{required:!1,type:"boolean"},option:Gm},validate(s){var i,e;if(!((i=s==null?void 0:s.option)!=null&&i.videoTrack)&&wi())throw new U({code:B.ENV_NOT_SUPPORTED,extraCode:5201});(e=s==null?void 0:s.option)!=null&&e.small&&Qm(s)}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:L(N({},Hs),{required:!1}),publish:{type:"boolean"},capture:{required:!1,type:"boolean"},mute:{type:["boolean","string"]},option:Gm},validate(s){var i;(i=s==null?void 0:s.option)!=null&&i.small&&Qm(s)}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:qm},validate(s){var i;if(!((i=s==null?void 0:s.option)!=null&&i.audioTrack)&&wi())throw new U({code:B.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:qm}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:Hs,publish:{type:"boolean"},option:Wm},validate(s,i,e,t,r){var o;if(!((o=s==null?void 0:s.option)!=null&&o.videoTrack)){if(wi())throw new U({code:B.ENV_NOT_SUPPORTED,extraCode:5201});if(!Po())throw new U({code:B.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:Hs,publish:{type:"boolean"},option:Wm}},muteRemoteAudio:[Jm,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[Jm,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:Hs,userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(s,i,e){Gs(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(s.userId);if(jm(!!t,e,s),t&&(s.streamType==="main"&&!t.muteState.videoAvailable||s.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new U({code:B.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:s}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:L(N({},Hs),{required:!1}),userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(s,i,e){Gs(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(s.userId);if(jm(!!t,e,s),t&&(s.streamType==="main"&&!t.muteState.videoAvailable||s.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new U({code:B.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:s}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(s,i,e){if(s.userId!=="*"&&T(s.streamType))throw new U({code:B.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(s,i,e){Gs(this._room.isJoining||this._room.isJoined,e)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(s,i,e,t){if(!wo)throw new U({code:B.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new U({code:B.INVALID_OPERATION,fnName:e,extraCode:5108});if(s.byteLength>1e3)throw new U({code:B.INVALID_PARAMETER,extraCode:5018,fnName:e});if(s.byteLength===0)throw new U({code:B.INVALID_PARAMETER,extraCode:5017,messageParams:{key:i},fnName:e});Gs(this._room.isJoined,e)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(s,i,e){if(!s&&!this._room.isMainStreamPublished||s&&!this._room.isAuxStreamPublished)throw new U({code:B.INVALID_OPERATION,extraCode:5109,messageParams:{key:i},fnName:e})}}}}],sendCustomMessage:{name:"message",required:!0,type:"object",properties:{cmdId:{type:"number",required:!0,min:1,max:10},data:{instanceOf:ArrayBuffer,required:!0,validate(s,i,e,t){if(s.byteLength>1e3)throw new U({code:B.INVALID_PARAMETER,extraCode:5018,fnName:e});if(s.byteLength===0)throw new U({code:B.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:i}})}}},validate(s,i,e){if(Gs(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new U({code:B.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:i}})}},switchRoom:{name:"switchRoomConfig",type:"object",required:!0,validate(s,i,e){if(Gs(this._room.isJoined,e),this._room.useStringRoomId&&s.strRoomId===this._room.roomId||!this._room.useStringRoomId&&s.roomId===Number(this._room.roomId))throw new U({code:B.INVALID_PARAMETER,extraCode:5020,fnName:e,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(s.roomId&&this._room.useStringRoomId||!s.roomId&&s.strRoomId&&!this._room.useStringRoomId)throw new U({code:B.INVALID_PARAMETER,extraCode:5019,fnName:e,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(s.roomId)Xm(s.roomId,e,i);else if(s.strRoomId)zm(s.strRoomId,e,i);else throw new U({code:B.INVALID_PARAMETER,extraCode:5015,fnName:e})},properties:{roomId:{type:"number"},strRoomId:{type:"string"},privateMapKey:{type:"string"},userSig:{type:"string",required:!0},autoSubscribeCount:{type:"number",min:0,max:50}}}},we={TRTC:MT};var ze=class extends Error{};function kT(s,i){let e=Rr(s);for(let t=0;t<i.length;t++)It(e[t],i[t]);return e}function PT(s){this._resolve=Promise.resolve(s)}function xT(s){this._reject=Promise.reject(s)}var mr=class mr{constructor(i,e){this.instance=i;this.group=e;d(this,"started",!1);d(this,"ops",[]);d(this,"startSame",()=>!0);d(this,"mergeUpdate",kT);let t=mr.instances.get(i);t?t.set(e,this):mr.instances.set(i,new Map([[e,this]]))}static get(i,e){if(!e)return;let t=mr.instances.get(i);return t&&t.get(e)||new mr(i,e)}static gets(i,e){let t=mr.instances.get(i),r=[];return t&&t.forEach((o,n)=>{e.test(n)&&r.push(o)}),r}action(i,e,t){let r=a=>{var c;return i===0?this.started=!0:i===3&&(this.started=!1),this.ops.shift(),(c=this.currentOp)==null||c.action(),a},o=a=>{var c,l;throw this.ops.shift(),i===0&&((c=this.currentOp)==null?void 0:c.type)===2&&this.ops.shift().reject(new ze("start failed")),(l=this.currentOp)==null||l.action(),a},n={type:i,action:()=>e(...n.args).then(r,o),args:t,resolve:PT,reject:xT};try{switch(this.state){case 1:if(i===0)throw new ze("already started");break;case 4:if(i===2)throw new ze("not started");break;default:return this.cacheOp(n)}}catch(a){return Promise.reject(a)}return this.ops.push(n),n.promise=e(...n.args).then(r,o)}cacheOp(i){if(this.ops.length===1)switch(this.state){case 0:case 2:if(i.type===0)throw new ze("already start");break;case 3:switch(i.type){case 2:throw new ze("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new ze("unknown state")}else switch(i.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let t=new ze("keep stop");if(this.ops.slice(1).forEach(r=>r.reject(t)),this.ops=this.ops.slice(0,1),this.state===3)return this.currentOp.promise}break;case 2:switch(this.lastOpType){case 2:return this.lastOp.args=this.mergeUpdate(this.lastOp.args,i.args),this.lastOp.promise;case 3:throw new ze("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new ze("start not allowed after update");case 0:throw new ze("duplicate start");case 3:if(this.startSame(this.currentOp.args,i.args))throw this.ops.pop().reject(new ze("keep start")),new ze("already start")}}i.promise=new Promise((t,r)=>{i._resolve?i._resolve.then(t):i.resolve=t,i._reject?i._reject.catch(r):i.reject=r});let{action:e}=i;return i.action=()=>e().then(i.resolve,i.reject),this.ops.push(i),i.promise}get lastOp(){return this.ops[this.ops.length-1]}get lastOpType(){return this.lastOp.type}get currentOp(){return this.ops[0]}get state(){return this.currentOp?this.currentOp.type:this.started?1:4}};d(mr,"instances",new WeakMap);var qi=mr;var ic=new WeakMap,rc=(s,i)=>{if(i instanceof ze){let{stack:e}=i;i=new U({code:B.OPERATION_ABORT,message:`${s} abort: ${i.message}`,fnName:s}),e&&(i.stack+=e.substr(e.indexOf(`
|
|
54
54
|
`)))}throw i};function pr(s,i){return Q((e,t)=>function(...r){let o=qi.get(this,typeof s=="string"?s:s.call(this,...r));return o?(i&&(o.startSame=i.bind(this)),o.action(0,e.bind(this),r).catch(rc.bind(null,t))):e.apply(this,r)})}function Xr(s,i){let{merge:e,debounce:t}=i||{};return Q((r,o)=>function(...n){let a=qi.get(this,typeof s=="string"?s:s.call(this,...n));if(!a)return r.apply(this,n);if(e&&(a.mergeUpdate=e.bind(this)),t&&t.isNeedToDebounce.apply(this,n)){let{delay:c,getKey:l}=t;return new Promise((u,h)=>{var D,_;let m=(D=ic.get(this))==null?void 0:D.get(l(...n));if(m){let{timeoutId:S,resolve:O}=m;clearTimeout(S),O()}let g=setTimeout(()=>{if(a.state===3||a.state===4)return u();a.action(2,r.bind(this),n).catch(rc.bind(null,o)).then(u,h)},c);ic.has(this)?(_=ic.get(this))==null||_.set(l(...n),{timeoutId:g,resolve:u}):ic.set(this,new Map([[l(...n),{timeoutId:g,resolve:u}]]))})}return a.action(2,r.bind(this),n).catch(rc.bind(null,o))})}function fr(s){return Q((i,e)=>function(...t){let r=typeof s=="function"?s.call(this,...t):s;if(r instanceof RegExp)return Promise.all(qi.gets(this,r).map(n=>n.action(3,()=>Promise.resolve(),t))).then(()=>i.call(this,...t));let o=qi.get(this,r);return o?o.action(3,i.bind(this),t).catch(rc.bind(null,e)):i.apply(this,t)})}var k={ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",KICKED_OUT:"kicked-out",REMOTE_USER_ENTER:"remote-user-enter",REMOTE_USER_EXIT:"remote-user-exit",REMOTE_AUDIO_AVAILABLE:"remote-audio-available",REMOTE_AUDIO_UNAVAILABLE:"remote-audio-unavailable",REMOTE_VIDEO_AVAILABLE:"remote-video-available",REMOTE_VIDEO_UNAVAILABLE:"remote-video-unavailable",AUDIO_VOLUME:"audio-volume",AUDIO_FRAME:"audio-frame",NETWORK_QUALITY:"network-quality",CONNECTION_STATE_CHANGED:"connection-state-changed",AUDIO_PLAY_STATE_CHANGED:"audio-play-state-changed",VIDEO_PLAY_STATE_CHANGED:"video-play-state-changed",SCREEN_SHARE_STOPPED:"screen-share-stopped",DEVICE_CHANGED:"device-changed",PUBLISH_STATE_CHANGED:"publish-state-changed",TRACK:"track",STATISTICS:"statistics",SEI_MESSAGE:"sei-message",CUSTOM_MESSAGE:"custom-message",VIDEO_DECODE_DOWNGRADE_STATE_CHANGED:"video-decode-downgrade-state-changed",LAYER_DATA:"layerData",FIRST_VIDEO_FRAME:"first-video-frame"},Ym=new Set([k.ERROR,k.AUTOPLAY_FAILED,k.KICKED_OUT,k.REMOTE_USER_ENTER,k.REMOTE_USER_EXIT,k.REMOTE_AUDIO_AVAILABLE,k.REMOTE_AUDIO_UNAVAILABLE,k.REMOTE_VIDEO_AVAILABLE,k.REMOTE_VIDEO_UNAVAILABLE,k.CONNECTION_STATE_CHANGED,k.PUBLISH_STATE_CHANGED,k.SCREEN_SHARE_STOPPED,k.DEVICE_CHANGED,k.FIRST_VIDEO_FRAME]);var ru={};Si(ru,{bytes2ms:()=>nh,calculateScaleResolutionDownNumber:()=>ls,convertObjectNumberToInt:()=>ho,copyProperties:()=>oh,deepClone:()=>Rr,deepMerge:()=>It,delay:()=>Ni,fibonacci:()=>yr,formatedTime:()=>ph,getConstructorName:()=>os,getContainerFromElement:()=>mh,getEnv:()=>rh,getInternalVersion:()=>uh,getLoggerUrl:()=>yi,getMediaStreamTrackInfo:()=>Vn,getMuteStateFromFlag:()=>bi,getNetworkType:()=>ed,getNumNetworkType:()=>Cr,getReconnectionTimeout:()=>Pt,getStringByteLength:()=>uo,getTurnServer:()=>hh,getUint32Version:()=>Ln,getValueType:()=>Re,getViewListFromView:()=>cs,glog:()=>rd,ipv4ToUint32:()=>as,isArray:()=>Se,isAudioWorkletSupported:()=>lh,isBoolean:()=>me,isConstructor:()=>br,isEmpty:()=>ns,isFunction:()=>ne,isLangChinese:()=>kt,isMediaStreamTrack:()=>ch,isNumber:()=>q,isObject:()=>Mt,isOverseaSdkAppId:()=>Ci,isPlainObject:()=>Je,isPortrait:()=>sd,isPromise:()=>sr,isRemoteTrack:()=>dh,isRotate90Or270:()=>vi,isString:()=>ee,isUndefined:()=>T,loadImage:()=>ds,ms2bytes:()=>ah,ms2samples:()=>id,normalizeUrl:()=>Un,performanceNow:()=>w,promiseAny:()=>Nr,samples2ms:()=>td,setNetworkType:()=>Pn,stringify:()=>St,stringifyIncludeValue:()=>xn,throttlePromise:()=>wn});var nu={};Si(nu,{ScheduleRequestType:()=>Km,getAbilityConfig:()=>wT,getScheduleDomain:()=>nc,isNeedToSchedule:()=>sc,scheduleProxy:()=>_i,sendScheduleRequest:()=>ou,setIsNeedToSchedule:()=>Wt,setScheduleProxy:()=>oc});var su=null,sc=!0;typeof document!="undefined"&&document.head.insertAdjacentHTML("beforeend",Object.values(Ri).map(s=>`<link rel="dns-prefetch" href="https://${s}">`).join(`\r
|
|
55
55
|
`));function Wt(s){me(s)&&s!==sc&&(sc=s,C.info(`setIsNeedToSchedule ${s}`))}E.on("28",()=>Wt(!0));E.on("63",()=>Wt(!0));E.on("84",()=>Wt(!0));E.on("201",s=>{s.state==="RECONNECTING"&&Wt(!0)});E.on("202",s=>{s.state==="RECONNECTING"&&Wt(!0)});function LT(s,i,e){let t={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let r=performance.getEntriesByType("resource"),o=_r(s,"config",p.MAIN),n=_r(s,"config",p.BACKUP);for(let a of r)if(a.startTime>=e&&(a.name===o||a.name===n)&&a.transferSize>0){let c=a.name===o?p.MAIN:p.BACKUP,l=Math.round(a.duration),u=Math.round(a.domainLookupStart-a.startTime),h=a.redirectStart>0?Math.round(a.redirectEnd-a.redirectStart):0,m=a.fetchStart>0?Math.round(a.domainLookupStart-a.fetchStart):0,g=Math.round(a.domainLookupEnd-a.domainLookupStart),D=Math.round(a.requestStart-a.secureConnectionStart),_=Math.round(a.secureConnectionStart-a.connectStart),S=Math.round(a.responseStart-a.requestStart),O=Math.round(a.responseEnd-a.responseStart),K=[g,D,_,S,O];re.uploadEvent({log:`stat-schedule-net:${l}(${u}(${h}->${m})->${K.join("->")}) ${c}`,userId:i}),t=L(N({},t),{totalCost:l,local:u,dns:g,tcp:_,tls:D,request:S,response:O});break}}catch(r){C.error("getScheduleDetailCost error",r)}return t}function ou(l){return f(this,arguments,function*({userId:s,sdkAppId:i,useStringRoomId:e,roomId:t,userSig:r,version:o,frameWorkType:n,role:a,latencyLevel:c}){if(!sc&&su)return{isCached:!0,result:su};let u={delta:0,count:[1,1],msg:[],detail:[]};try{let h=new FormData;h.append("userId",String(s)),h.append("sdkAppId",String(i)),h.append("isStrGroupId",String(e)),h.append("groupId",String(t)),h.append("sdkVersion",o),h.append("userSig",String(r));let m=yield Dr();m!=null&&m.model&&h.append("model",String(m==null?void 0:m.model)),a&&h.append("role",String(a)),c&&h.append("latencyLevel",String(c)),n&&h.append("frameWorkType",String(n));let g=w(),D=yield VT(h,u,i);D.config&&(D.config.loggerDomain&&Tr(D.config.loggerDomain),me(D.config.scheduleCache)&&Wt(!D.config.scheduleCache)),u.delta=w()-g;let _=LT(Number(i),s,g);return su=D,{isCached:!1,result:D,detailCost:_}}catch(h){let m=Se(h)?h[0]:h,g=q(m.code)?m.code:0,D=`schedule failed${m.message?`: ${m.message}`:""}`,_=new y({code:I.SCHEDULE_FAILED,extraCode:g,message:x({key:P.JOIN_ROOM_FAILED,data:{error:D,code:g}})});throw C.error(D,g),_}})}var _i={main:"",backup:""};function oc(s){Se(s)?(_i.main=s[0],_i.backup=s[1]):_i.main=s}var Km=(t=>(t.CONFIG="config",t.TRTC_AUTO_CONF="trtcAutoConf",t.AUDIO_AI_AUTH="audioAiAuth",t))(Km||{});function _r(s,i,e=p.MAIN,t=!1){return`https://${_i[e]||nc(s,e,t)}/api/v1/${i}`}function wT(s,i,e){let t=_r(s,i),r=_r(s,i,p.BACKUP),o=new URLSearchParams(e).toString(),n=fetch(`${t}?${o}`).then(c=>c.json()),a=fetch(`${r}?${o}`).then(c=>c.json());return Nr([n,a])}function nc(s,i=p.MAIN,e=!1){let t;return Ci(s)?e?t=i===p.MAIN?Ri.MAIN_OVERSEA_BACKUP:Ri.BACKUP_OVERSEA:t=i===p.MAIN?Ri.MAIN_OVERSEA:Ri.BACKUP_OVERSEA:t=i===p.MAIN?Ri.MAIN:Ri.BACKUP,t}function UT(s,i,e){return new Promise((t,r)=>{Di({url:s,body:i,timeout:e.timeout,priority:"high"}).then(o=>{o.data.code===0?t(o.data.data):r({code:o.data.code,message:o.data.msg})}).catch(r)})}var Zm=(s,i)=>Yt({retryFunction:UT,settings:{retries:3,timeout:0},onError:i,onRetrying:s});function VT(s,i,e){return new Promise((t,r)=>{let o=null;Nr([Zm(n=>i.count[0]=n+1,({error:n,retry:a,retriedCount:c,retryFuncArgs:l})=>{i.msg[0]=n.message,o||(c>=1&&(l[0]=_r(e,"config",p.MAIN,!0)),a())})(_r(e,"config",p.MAIN),s,{get timeout(){return yr(2+i.count[0])*1e3}}),Zm(n=>i.count[1]=n+1,({error:n,retry:a,retriedCount:c,retryFuncArgs:l})=>{i.msg[1]=n.message,o||(c>=2&&(l[0]=_r(e,"config",p.BACKUP,!0)),a())})(_r(e,"config",p.BACKUP),s,{get timeout(){return yr(2+i.count[1])*1e3}})]).then(n=>{o=n,t(o)}).catch(r)})}var BT=s=>s.startsWith("data:application/octet-stream;base64,"),FT=s=>s.startsWith("file://"),on=class{constructor(){d(this,"_log");this._log=C.createLogger({id:"fd"})}download(i,e){return f(this,null,function*(){let{type:t="blob"}=e||{};i=Un(i);try{let r=w(),o;if(ne(fetch)?o=yield this.downloadWithFetch(i,t):o=yield this.downloadWithXHR(i,t),!o||!o.data)throw new Error("data is empty");let n=w()-r;return this._log.info(`downloaded: ${i}, return type: ${t}, cost: ${n}ms`),b.addSuccessEvent({key:522700,cost:w()-r}),o.data}catch(r){throw this._log.error(`failed to download: ${i}, error: ${r}`),b.addFailedEvent({key:522700,error:r}),r}})}downloadWithFetch(i,e){return f(this,null,function*(){this._log.info(`download with fetch: ${i}, return type: ${e}`);try{let t=yield fetch(i);if(!t.ok){let o=new Error(`network response was not ok: ${t.status}`);throw o.status=t.status,o}let r;return e==="arraybuffer"?r=yield t.arrayBuffer():r=yield t.blob(),{data:r}}catch(t){throw t}})}downloadWithXHR(i,e){return this._log.info(`download with xhr: ${i}, return type: ${e}`),new Promise((t,r)=>{let o=new XMLHttpRequest;o.open("GET",i,!0),o.responseType=e,o.onload=()=>{if(o.status===200||o.status===0&&o.response)t({data:o.response});else{let n=new Error(`XHR failed, status: ${o.status}`);n.status=o.status,r(n)}},o.onerror=r,o.send(null)})}loadWasm(i,e){return f(this,null,function*(){this._log.info(`loadWasm ${i}, importObject: ${JSON.stringify(e)}`);let t=w(),r=null,o=null;if(ne(WebAssembly.instantiateStreaming)&&!BT(i)&&!FT(i)&&ne(fetch))try{let n=fetch(i);r=(yield WebAssembly.instantiateStreaming(n,e)).instance}catch(n){o=n}if(!r)try{let n=yield this.download(i,{type:"arraybuffer"});r=(yield WebAssembly.instantiate(n,e)).instance}catch(n){o=n}if(r){let n=w()-t;return this._log.info(`loadedWasm ${i}, cost: ${n}ms`),b.addSuccessEvent({key:522701,cost:n}),r}throw this._log.error(`failed to loadWasm ${i}, error: ${o}`),b.addFailedEvent({key:522701,error:o}),o})}loadScript(i){this._log.info(`loadScript ${i}`);let e=w();return new Promise((t,r)=>{let o=document.createElement("script");o.type="text/javascript",o.onload=()=>{this._log.info(`loadedScript ${i}, cost: ${w()-e}ms`),b.addSuccessEvent({key:522702,cost:w()-e,split:1e3}),t(o)},o.onerror=n=>{this._log.error(`failed to loadScript ${i}, error: ${n}`),b.addFailedEvent({key:522702}),r(n)},o.crossOrigin="anonymous",o.src=i,document.head.append?document.head.append(o):document.getElementsByTagName("head")[0].appendChild(o)})}};v([pt({settings:{timeout:0,retries:3},onError(i,e,t){var r;(i==null?void 0:i.status)===404||(r=i==null?void 0:i.message)!=null&&r.includes("404")?(this._log.warn("download 404, stop retry"),t(i)):e()},onRetrying(i){this._log.warn(`download retrying: ${i}`)}})],on.prototype,"download",1),v([pt({settings:{timeout:3e3,retries:3},onRetrying(i){this._log.warn(`loadScript retrying: ${i}`)}})],on.prototype,"loadScript",1);var ep=new on;function tp({TRTC:s,room:i,errorModule:e,assetsPath:t}){return{TRTC:s,room:i,assetsPath:t,fileDownloader:ep,innerEmitter:E,constants:Kc,environment:As,utils:ru,eventLogger:re,log:this.room.getLogger(),loggerManager:C,errorModule:e,kvStatManager:b,rtcDectection:ni,trtc:this,rx:Zl,enums:Vd,schedule:nu,clearStarted:(r,o)=>{let n=r.getAlias(),a=qi.instances.get(this);if(a)if(o){let c=a.get(n+o);if(!c)return;c.started=!1}else a.forEach((c,l)=>{l.startsWith(n)&&(c.started=!1)})},startGetPCM:zo,createAudioNode:Jo}}var ip=(s,i)=>{let{emit:e}=s;return s.emit=(...t)=>{try{return e.apply(s,t)}catch(r){let o=x({key:P.CATCH_HANDLER_ERROR,data:{name:i,event:t[0]},addDocLink:!1});return C.warn(`${o}
|
|
56
56
|
|
|
57
|
-
${r.stack}`),!1}},s};var Ws=new WeakMap;function rp(s){let i=Ws.get(s);i&&(i.forEach(e=>clearTimeout(e)),Ws.delete(s))}function sp(s,i){return Q((e,t)=>function(...r){let o=Ws.get(this);o||(o=new Map,Ws.set(this,o));let n=i(...r),a=o.get(n);if(!a||a<=0){e.apply(this,r);let c=setTimeout(()=>{var l;(l=Ws.get(this))==null||l.delete(n)},s);o.set(n,c)}else{clearTimeout(a);let c=window.setTimeout(()=>{var l;e.apply(this,r),(l=Ws.get(this))==null||l.delete(n)},s);o.set(n,c)}})}var np="trtc-sdk-v5",ap="5.11.0-beta.4";function Ge(...s){return Q((i,e)=>function(...t){try{cc.call(this,s,t,e,this._name)}catch(r){return Promise.reject(r)}return i.apply(this,t)})}function au(...s){return Q((i,e)=>function(...t){try{cc.call(this,s,t,e,this._name)}catch(r){throw r}return i.apply(this,t)})}function cc(s,i,e,t){if(Se(s))for(let r=0;r<s.length;r++)ac.call(this,{rule:s[r],value:i[r],key:s[r].name,fnName:e,className:t});else ac.call(this,{rule:s,value:i[0],key:s.name,fnName:e,className:t})}function ac({rule:s,value:i,key:e,fnName:t,className:r}){function o(c){return{code:B.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:s,value:i}}}if(T(i)){if(s.required)throw new U(o(5001));if(T(s.defaultValue)){ne(s.validate)&&s.validate.call(this,i,e,t,r,this);return}i=s.defaultValue}if(Array.isArray(s.type)){let c=!1;for(let l=0;l<s.type.length;l++)s.type[l]===null&&i===null&&(c=!0),ne(s.type[l])&&i instanceof s.type[l]&&(c=!0),ee(s.type[l])&&Re(i)===s.type[l].toLowerCase()&&(c=!0);if(!c)throw new U({code:B.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:s.type.map(l=>br(l)?os(l):ee(l)?l:Re(l))},value:i}})}else if(!T(s.type)&&Re(i)!==s.type)throw new U(o(5002));if(s.allowEmpty===!1){let c=q(i)&&(i===0||Number.isNaN(i)),l=ee(i)&&i.trim()==="";if(c||l)throw new U(o(5003))}if(s.notLessThanZero&&q(i)&&i<0)throw new U(o(5006));if(!T(s.min)&&q(i)&&i<s.min)throw new U(o(5007));if(!T(s.max)&&q(i)&&i>s.max)throw new U(o(5008));if(ee(s.instanceOf)){if(!i||i._name!==s.instanceOf)throw new U(o(5004))}else if(ne(s.instanceOf)&&!(i instanceof s.instanceOf))throw new U(o(5004));if(Array.isArray(s.values)&&!s.values.includes(i))throw new U(o(5005));let{properties:n}=s;Je(n)&&Mt(i)&&Object.keys(n).forEach(c=>{ac.call(this,{rule:n[c],value:i&&i[c],key:`${c}`,fnName:t,className:r})});let{arrayItem:a}=s;Je(a)&&Se(i)&&i.forEach((c,l)=>{ac.call(this,{rule:a,value:c,key:`${e}[${l}]`,fnName:t,className:r})}),ne(s.validate)&&s.validate.call(this,i,e,t,r,this)}function fe(s={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t,ignoreLog:r,ignoreErrorLog:o}=s;return Q((n,a)=>function(...c){var g,D,_;function l(S,O,K){if(K&&K.includes(S))return"hided";if(e){let G=e(...c);if(c[G.argIndex]===O)return G.value}if(O===c||S in c)return O;try{return O instanceof HTMLElement?`id: ${O.id} type:${Re(O)}`:O instanceof MediaStreamTrack?Vn(O):(JSON.stringify(O),O)}catch(G){return`type:${Re(O)}`}}let u=this._log||C;if(r!=null&&r(...c))return n.apply(this,c);c.length>0?u.info(`${a}() ${JSON.stringify(c,(S,O)=>l(S,O,["userSig","privateMapKey"]))}`):u.info(`${a}()`);let h=t?t(...c):ua[a],m=(o==null?void 0:o(...c))||!1;try{let S=n.apply(this,c),O=w();if(sr(S)){let K=`${a.includes("Plugin")?`${((D=(g=c[0]).getName)==null?void 0:D.call(g))||""} `:" "}`;return S.then(G=>(u.info(`${a}() success ${K}${i.call(this,...c)}`),b.addSuccessEvent({key:h,cost:w()-O}),G)).catch(G=>{var J;G=U.convertFrom.call(this,G,a,c.length===1?c[0]:c);let Z=G.extraCode||G.code,_e=(J=G.message)!=null&&J.includes(Z)?"":` code:${Z}`;throw m||u.error(`${a}() failed ${K}${i.call(this,...c)} ${G}${_e} params: ${JSON.stringify(c,l)}`),b.addFailedEvent({key:h,error:G}),G})}return b.addSuccessEvent({key:h}),S}catch(S){S=U.convertFrom.call(this,S,a);let O=S.extraCode||S.code,K=(_=S.message)!=null&&_.includes(O)?"":` code:${O}`;throw m||u.error(`${a}() failed ${S}${K} params: ${JSON.stringify(c,l)}`),b.addFailedEvent({key:h,error:S}),S}})}var dc=s=>Q((i,e)=>function(t,r){return f(this,null,function*(){let o=this._plugins.get(t);if(!o)throw this._log.error(`plugin ${String(t)} is not found`),new U({code:B.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});if(ne(o.constructor.isSupported)&&!o.constructor.isSupported())throw this._log.error(`plugin ${String(t)} is not supported`),new U({code:B.ENV_NOT_SUPPORTED,message:`plugin ${String(t)} is not supported`,extraCode:5210,fnName:e});return cc.call(this,o.getValidateRule(s),[r],e,"TRTC"),i.call(this,o,r)})});var lc=0,cu,ji=class ji{constructor(i){this.core=i;d(this,"log");d(this,"customAudioReferenceMap",new Map);d(this,"audioRefId",0);d(this,"audioContext",Ee());d(this,"localAudioWorkletNode");d(this,"screenAudioWorkletNode");d(this,"mixNode");d(this,"silentNode");lc=lc+1,this.log=i.log.createChild({id:`${this.getAlias()}${lc}`}),this.log.info(`created id=${this.getAlias()}${lc}`),i.assetsPath&&this.preload(`${i.assetsPath}/audioProcessor-wasm.js`)}static getStartValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,t,r,o){if(!i.room.audioManager.hasAudioTrack&&!i.room.audioManager.hasScreenAudioTrack)throw new U({code:B.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return cu||(cu=this.doPreload(i)),cu}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield Bi(this.audioContext,t)}catch(r){this.log.error(`preload audioProcessor failed. ${r}`)}finally{URL.revokeObjectURL(t)}})}getName(){return ji.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(i){switch(i){case"start":return ji.getStartValidateRule(this.core);case"update":return ji.updateValidateRule;case"stop":return ji.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e}=this.core,{sdkAppId:t,userId:r,assetsPath:o,audioReference:n,processLevel:a,enableDump:c,isLocalAudioNeedAudioProcess:l=!0,isScreenAudioNeedAudioProcess:u=!0}=i;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=l,this.core.room.audioManager.isScreenAudioNeedAudioProcess=u,yield this.preload(`${o}/audioProcessor-wasm.js`),!this.localAudioWorkletNode||!this.screenAudioWorkletNode){let h=String(Date.now()).slice(0,-3),{auth:m,sign:g,status:D,message:_}=yield HT(L(N({},i),{timestamp:h}));if(!m)throw this.log.info(`audioProcessor: ${r} auth result: ${m}. Message: ${_}`),new U({code:B.INVALID_PARAMETER,message:_});this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",t,r,h,g,D,e),this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",t,r,h,g,D,e)}this.mixNode||(this.mixNode=this.audioContext.createGain(),this.mixNode.gain.value=1),this.silentNode||(this.silentNode=this.audioContext.createConstantSource(),this.silentNode.offset.setValueAtTime(0,this.audioContext.currentTime),this.silentNode.start()),this.localAudioWorkletNode.port.postMessage({type:"enable"}),this.screenAudioWorkletNode.port.postMessage({type:"enable"}),e.audioManager.addAudioProcessor(this.localAudioWorkletNode,this.mixNode,this.silentNode,this.screenAudioWorkletNode),T(n)||n.forEach(h=>{this.customAudioReferenceMap.set(h,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:h,refId:`o-${this.audioRefId++}`})}),T(a)||this.localAudioWorkletNode.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:a}}),T(c)||this.localAudioWorkletNode.port.postMessage({type:"dump",data:{enable:c}})})}update(i){return f(this,null,function*(){if(!this.localAudioWorkletNode||!this.screenAudioWorkletNode)return;let{audioReference:e,enableDump:t,processLevel:r}=i;T(e)||(this.customAudioReferenceMap.forEach((o,n)=>{this.customAudioReferenceMap.delete(n),this.core.room.audioManager.updateAudioReference({type:"remove",refId:o})}),e.forEach(o=>{this.customAudioReferenceMap.set(o,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:o,refId:`o-${this.audioRefId++}`})})),T(r)||this.localAudioWorkletNode.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:r}}),T(t)||(this.localAudioWorkletNode.port.postMessage({type:"dump",data:{enable:t}}),this.screenAudioWorkletNode.port.postMessage({type:"dump",data:{enable:t}}))})}stop(){return f(this,null,function*(){if(!this.localAudioWorkletNode||!this.mixNode||!this.silentNode||!this.screenAudioWorkletNode)return;let{room:i}=this.core;this.localAudioWorkletNode.port.postMessage({type:"disable"}),this.screenAudioWorkletNode.port.postMessage({type:"disable"}),yield i.audioManager.removeAudioProcessor(this.localAudioWorkletNode,this.mixNode,this.silentNode,this.screenAudioWorkletNode)})}destroy(){this.localAudioWorkletNode&&(this.localAudioWorkletNode.port.onmessage=null),this.screenAudioWorkletNode&&(this.screenAudioWorkletNode.port.onmessage=null)}initWorkletNode(i,e,t,r,o,n,a,c){i.port.postMessage({type:"init",data:{sdkAppId:String(t),userId:r,timestamp:o,sign:n,status:a}}),i.port.onmessage=l=>{var h;let{data:u}=l;switch(u.type){case"cost":let m=(u==null?void 0:u.value)>10?"info":"debug";this.log[m](`[${e}] avg cost: ${u.value} max: ${u==null?void 0:u.max}(${es(new Date(u==null?void 0:u.maxCostTimestamp))}) hist: ${(h=u==null?void 0:u.hist)==null?void 0:h.join(" ")}`);return;case"log":this.log[u.logLevel](`[${e}] ${u.value}`);return;case"dump":E.emit("265",{room:c,data:u.value,type:e==="localAudio"?"dump":"dump-screen-audio"});return}}}};d(ji,"updateValidateRule",{type:"object"}),d(ji,"stopValidateRule",{type:"object"}),d(ji,"Name","AudioProcessor");var uc=ji;function $T(s,i=p.MAIN){return`https://${_i[i]||nc(s,i)}/api/v1/audioAiAuth`}function HT(r){return f(this,arguments,function*({sdkAppId:s,userId:i,userSig:e,timestamp:t}){let n=`${$T(s)}?sdkAppId=${s}&userId=${i}&userSig=${e}×tamp=${t}`,a=yield fetch(n),{data:{errCode:c,errMsg:l,sign:u,status:h}}=yield a.json();if(h==="1")return{auth:!0,sign:u,status:h,message:l};let m=Ci(s)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",g="Init RTCAudioProcessor failed.",D="";switch(c){case 1:D="Please check your params.";break;case 2:D=`You need to buy packages. Refer to: ${m}`;break;case 3:D="Server is invalid. Please contact our engineer. ";break;case 4:D=`Your packages is not active. Refer to: ${m}`;break;case 5:D=`Your packages is expired. Refer to: ${m}`;break;case 6:D="Your version is not supported.";break}return{auth:!1,status:h,message:l?`${g} Reason: ${l}. ${D}`:`${g}, ${D}`}})}var hc=0,du=class{constructor(i,e){d(this,"player");d(this,"publisher");d(this,"mixInput");this.mixInput=new Ms(e),i.url?(this.player=new Audio(i.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(i.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(i.track),this.mixInput.connect()}updateSettings(i){this.player&&(T(i.volume)||(this.volume=i.volume),T(i.loop)||(this.loop=i.loop),T(i.playbackRate)||(this.playbackRate=i.playbackRate))}updateListener(i){if(this.player){if(i.onDurationChange){let{onDurationChange:e}=i;this.player.ondurationchange=t=>{e(t.target.duration)}}if(i.onTimeUpdate){let e=i.onTimeUpdate,{player:t}=this;t.ontimeupdate=()=>{e(t.currentTime,t.duration)}}i.onEnded&&(this.player.onended=i.onEnded)}}reset(){this.seek(0),this.mixInput.connect()}seek(i){this.player&&(i<0&&i>this.player.duration||(this.player.currentTime=i,this.publisher.currentTime=i))}play(){var i,e;return(i=this.publisher)==null||i.play(),(e=this.player)==null?void 0:e.play()}pause(){var i,e;(i=this.player)==null||i.pause(),(e=this.publisher)==null||e.pause()}stop(){var i;(i=this.player)==null||i.pause(),this.mixInput.disconnect()}setOperation(i){i==="pause"&&this.pause(),i==="resume"&&(this.pause(),this.play()),i==="stop"&&(this.pause(),this.seek(0))}set volume(i){!this.player||!this.publisher||(this.player.volume=i,this.publisher.volume=i)}set loop(i){!this.player||!this.publisher||(this.player.loop=i,this.publisher.loop=i)}set playbackRate(i){!this.player||!this.publisher||(this.player.playbackRate=i,this.publisher.playbackRate=i)}};function Js(s,i){if(i&&typeof i!="function")throw new U({code:B.INVALID_PARAMETER,message:`start audioMixer plugin: param ${s} should be a function.`})}var gi=class gi{constructor(i){this.core=i;d(this,"log");d(this,"mixedMusicMap",new Map);d(this,"cacheMusicMap",new Map);hc=hc+1,this.log=i.log.createChild({id:`${this.getAlias()}${hc}`}),this.log.info(`created id=${this.getAlias()}${hc}`)}getName(){return gi.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return gi.startValidateRule;case"update":return gi.updateValidateRule;case"stop":return gi.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e}=this.core;this.log.info(`add music source, id: ${i.id} url: ${i.url}, track: ${i.track}`);let{id:t,url:r}=i;if(this.mixedMusicMap.has(t))return;let o=this.cacheMusicMap.get(t);o?i.url?o.reset():(o.mixInput.replaceSource(i.track),o.mixInput.connect()):(o=new du(i,e.audioManager),this.cacheMusicMap.set(t,o)),o.updateListener(i),o.updateSettings(i),yield o.play(),this.mixedMusicMap.set(t,o),o.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"add",audioReference:o.mixInput.source.node,refId:`ax-${t}`}),this.log.info(`start mix audio track ${t} success.`),b.addEnum({key:502700,value:3}),this.kvUpload(i)})}update(i){return f(this,null,function*(){let{id:e,operation:t,seekFrom:r,playbackRate:o}=i;this.log.info(`update music source, ${JSON.stringify(i)}`);let n=this.mixedMusicMap.get(e);if(!n){this.log.warn(`update music source failed, music id: ${e} not found.`);return}n.updateSettings(i),n.updateListener(i),T(t)||n.setOperation(t),T(r)||n.seek(r),this.kvUpload(i)})}stop(e){return f(this,arguments,function*({id:i}){if(this.mixedMusicMap.has(i)){this.log.info(`remove music source, music id: ${i}`);let t=this.mixedMusicMap.get(i);t!=null&&t.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:t.mixInput.source.node,refId:`ax-${i}`}),t==null||t.stop(),this.mixedMusicMap.delete(i)}i==="*"&&this.destroyAllMusic()})}kvUpload(i){let{track:e,loop:t,volume:r,playbackRate:o,operation:n,seekFrom:a,onTimeUpdate:c,onDurationChange:l,onEnded:u}=i;e&&b.addCount({key:502711}),t&&b.addCount({key:502703}),r&&b.addCount({key:502704}),o&&b.addCount({key:502705}),n&&b.addCount({key:502706}),a&&b.addCount({key:502707}),typeof c!="function"&&b.addCount({key:502709}),typeof u!="function"&&b.addCount({key:502710}),typeof l!="function"&&b.addCount({key:502708})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((i,e)=>{i!=null&&i.mixInput.track&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:i.mixInput.track,refId:e}),this.stop({id:e})})}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}};d(gi,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(i,e,t){if(i.url&&i.url!=="*"){let r=i.url.split("?")[0],o=["mp3","ogg","wav","flac"],n=r.split(".").pop(),a=o.indexOf(n)>=0,c=r.startsWith("blob"),l=r.startsWith("data");if(!(a||c||l))throw new U({code:B.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new U({code:B.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});Js("onTimeUpdate",i.onTimeUpdate),Js("onEnded",i.onEnded),Js("onDurationChange",i.onDurationChange)}}),d(gi,"updateValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},loop:{type:"boolean"},volume:{type:"number"},seekFrom:{type:"number"},operation:{type:"string",values:["pause","resume","stop"]}},validate(i,e,t){Js("onTimeUpdate",i.onTimeUpdate),Js("onEnded",i.onEnded),Js("onDurationChange",i.onDurationChange)}}),d(gi,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),d(gi,"Name","AudioMixer");var mc=gi;var pc=0,lu,Xi=class Xi{constructor(i){this.core=i;d(this,"log");d(this,"audioContext",Ee("denoiser"));d(this,"workletNode");pc=pc+1,this.log=i.log.createChild({id:`${this.getAlias()}${pc}`}),this.log.info(`created id=${this.getAlias()}${pc}`),i.assetsPath&&this.preload(`${i.assetsPath}/denoiser-wasm.js`).catch(e=>{})}static startValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,t,r,o){if(!i.room.audioManager.hasAudioTrack)throw new U({code:B.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return lu||(lu=this.doPreload(i)),lu}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield Bi(this.audioContext,t)}catch(r){throw this.log.error("load worklet failed",r),r}finally{URL.revokeObjectURL(t)}})}getName(){return Xi.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(i){switch(i){case"start":return Xi.startValidateRule(this.core);case"update":return Xi.updateValidateRule;case"stop":return Xi.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e,schedule:t}=this.core;if(i.assetsPath&&(yield this.preload(`${i.assetsPath}/denoiser-wasm.js`)),!this.workletNode){let r=String(Date.now()).slice(0,-3),{auth:o,sign:n,status:a,message:c}=yield WT(t,L(N({},i),{timestamp:r}));if(!o)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${o}. Message: ${c}`),new U({code:B.INVALID_PARAMETER,message:c});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(i.sdkAppId),userId:i.userId,timestamp:r,sign:n,status:a}}),this.workletNode.port.onmessage=l=>{var h;let{data:u}=l;if(u.type==="cost"){let m=(u==null?void 0:u.max)>20?"warn":(u==null?void 0:u.max)>10?"info":"debug";this.log[m](`avg cost: ${u.value} max: ${u==null?void 0:u.max}(${es(new Date(u==null?void 0:u.maxCostTimestamp))}) hist: ${(h=u==null?void 0:u.hist)==null?void 0:h.join(" ")}`)}else u.type==="log"&&this.log[u.logLevel](`${u.value}`)}}this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(){return f(this,null,function*(){})}stop(){return f(this,null,function*(){if(!this.workletNode)return;let{room:i}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield i.audioManager.removeDenoiser(this.workletNode)})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};d(Xi,"updateValidateRule",{type:"object"}),d(Xi,"stopValidateRule",{type:"object"}),d(Xi,"Name","AIDenoiser");var fc=Xi;function WT(o,n){return f(this,arguments,function*(s,{sdkAppId:i,userId:e,userSig:t,timestamp:r}){try{let{data:{errCode:a,errMsg:c,sign:l,status:u}}=yield s.getAbilityConfig(i,s.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:i,userId:e,userSig:t,timestamp:r});if(u==="1")return{auth:!0,sign:l,status:u,message:c};let h=Ci(i)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",m="Init RTCAIDenoiser failed.",g="";switch(a){case 1:g="Please check your params.";break;case 2:g=`You need to buy packages. Refer to: ${h}`;break;case 3:g="Server is invalid. Please contact our engineer. ";break;case 4:g=`Your packages is not active. Refer to: ${h}`;break;case 5:g=`Your packages is expired. Refer to: ${h}`;break;case 6:g="Your version is not supported.";break}return{auth:!1,status:u,message:c?`${m} Reason: ${c}. ${g}`:`${m}, ${g}`}}catch(a){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${a}`}}})}var dp=$e(Ye(),1);var uu=class extends dp.EventEmitter{constructor(){super();d(this,"observer");d(this,"state","nominal");this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return f(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!pe&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){re.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let t=this.stateNum,r=e[e.length-1];this.state=r.state,(this.stateNum>3||t>3)&&C.info(`${r.source}: ${r.state}`),this.emit("state-changed",{type:r.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(t){re.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},JT=new uu,hu=JT;function mu([s,i]){let e=i.byteLength,t=parseInt(String(e/255),10),r=e%255,o=[];o.push(0,0,0,1,6,s);for(let a=0;a<t;a++)o.push(255);o.push(r);let n=new DataView(i);return o.push(...new Uint8Array(n.buffer)),o.push(128),new Hi(new DataView(new Uint8Array(o).buffer),!0)}function pu(s){return s.type==="empty"||s.data.byteLength===0}function fu(s){return s.getInt32(0)===1&&s.getInt8(4)===6}function _u(s){let i=0,e=0,t=new DataView(s);for(let r=0;r<s.byteLength;r++)switch(t.getUint8(r)){case 0:i++;break;case 1:(i===2||i===3)&&e++,i=0;break;default:i=0;break}return e}function gu({frame:s,seiMessageList:i}){if(!i||i.length===0||s.data.byteLength===0)return s;let t=9-_u(s.data);if(t<=0)return s;let r=i.splice(0,t).reverse().map(mu),o=r.reduce((u,h)=>u+h.dataView.byteLength,0),n=new ArrayBuffer(o+s.data.byteLength),a=new DataView(n),c=new DataView(s.data),l=0;for(let u=0;u<r.length;u++)for(let h=0;h<r[u].dataView.byteLength;h++)a.setInt8(l++,r[u].dataView.getInt8(h));for(let u=0;u<s.data.byteLength;u++)a.setInt8(l++,c.getInt8(u));return s.data=n,s}function Tu({frame:s,onSEI:i}){try{let e=new DataView(s.data);if(pu(s)||!fu(e))return s;let t=[],r=0,o=-1,n=-1;for(let a=0;a<s.data.byteLength;a++){let c=e.getUint8(a);if(c===0)r++;else if(c===1){if(r===2||r===3){let l=a-r;if(o===-1?o=l:n===-1&&(n=l,t.push(new Hi(new DataView(e.buffer.slice(o,n)))),o=l,n=-1),!(e.getUint8(a+1)===6)){s.data=e.buffer.slice(l);break}}r=0}else r=0}i==null||i(t.reverse())}catch(e){}return s}var Eu=0,nn=class nn{constructor(i){this.core=i;d(this,"log");d(this,"_seiMessageList",[]);d(this,"_smallSeiMessageList",[]);d(this,"_subStreamSeiMessageList",[]);Eu++,this.log=i.log.createChild({id:`${this.getAlias()}${Eu}`}),this.log.info(`[sei] created id=${this.getAlias()}${Eu}`),this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode({frame:i,mediaType:e}){try{let t=e===8?this._smallSeiMessageList:e===2?this._subStreamSeiMessageList:this._seiMessageList;return gu({frame:i,seiMessageList:t})}catch(t){this.log.warn(t)}return i}decode({frame:i,track:e}){return Tu({frame:i,onSEI:t=>{t.forEach(r=>{this.core.trtc.emit(k.SEI_MESSAGE,{seiPayloadType:r.seiPayloadType,data:r.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"})})}})}destroy(){this.log.debug("destory"),this.stop(),delete this.core}getValidateRule(i){switch(i){case"start":return{type:"object"};case"update":return{type:"object"};case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:Ui?this.encode:gu,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:Ui?this.decode:Tu,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update({buffer:i,options:e}){var o;let t=[e.seiPayloadType,i],r=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(t):(this._seiMessageList.push(t),r&&this._smallSeiMessageList.push(t)),(o=this.core.room.scriptTransformWorker)==null||o.postMessage({type:"sei",data:t,isMain:!e.toSubStream,small:r})}getName(){return nn.Name}getAlias(){return"sei"}getGroup(){return"sei"}};d(nn,"autoStart",!0),d(nn,"Name","SEI");var _c=nn;function Su({frame:s,onDump:i}){return i==null||i(),s}function Iu({frame:s,onDump:i}){return i==null||i(),s}var lp={"play() error: NotAllowedError:":{tips:s=>s.includes("main <video>")||s.includes("main <audio>")?"Remote stream auto play is restricted and playback fails":"Local stream playback failure, generally only occurs in Android WeChat devices, no need to handle",color:"red",class:"red"},"updateStream() try to recover local stream":{tips:"Device acquisition exception, automatic recovery is in progress"},"updateStream() recover local stream successfully":{tips:"Device acquisition exception, automatic recovery is successful"},"updateStream() failed to recover local stream":{tips:"Device acquisition exception, automatic recovery failed"},"main stream - video track is muted":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is muted":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is muted":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unable to provide media output":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is unable to provide media output":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is unable to provide media output":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unmuted":{tips:"Received enough playback video data"},"main stream - audio track is unmuted":{tips:"Received enough playback audio data"},"auxiliary stream - video track is unmuted":{tips:"Received enough playback screen sharing data"},"main stream - audio player track is ended":{tips:"Remote audio track stopped"},"main stream - video player track is ended":{tips:"Remote video track stopped"},"auxiliary stream - video player track is ended":{tips:"Received enough playback screen sharing data"},"stream - video track is muted":{tips:"Camera capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"stream - video track is unable to provide media output":{tips:"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked, and the customer needs to re-acquire. SDK v4.11.4+ will automatically resume acquisition without customer intervention",color:"orange"},"video track is unable to provide media output":{tips:s=>s.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"stream - audio track is muted":{tips:"Microphone capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"audio track is unable to provide media output":{tips:s=>s.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"Microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio track is unable to provide media output":{tips:"The microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"is adding audio track to current published local stream":{tips:"add audio track",color:"orange"},"is removing audio track from current published local stream":{tips:"remove audio track",color:"orange"},"is removing video track from current published local stream":{tips:"remove video track",color:"orange"},"is adding video track to current published local stream":{tips:"add video track",color:"orange"},"is replacing audio track to current published local main stream":{tips:"replace audio track",color:"orange"},"is replacing video track to current published local main stream":{tips:"replace video track",color:"orange"},"downlink network quality change":{tips:"Downstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"uplink network quality change":{tips:"Upstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"localStream mute video":{tips:"mute upstream video stream",color:"orange"},"localStream unmute video":{tips:"unmute upstream video stream",color:"orange"},"localStream mute audio":{tips:"mute upstream audio stream",color:"orange"},"localStream unmute audio":{tips:"unmute upstream audio stream",color:"orange"},"black detected":{tips:"Detect black screen, which means fps = 0. It is usually caused by network, and the network will be recovered after a while. If the network is normal but has not been restored, it is an abnormal situation."},'main stream start to play with options: {"muted":true}':{tips:"Play the remote stream in silent mode. Generally, the remote stream does not need to be played in silent mode. You need to confirm whether the parameters passed in the client stream.play API call are correct.",color:"orange"},"main stream - audio player is starting playing":{tips:"Remote stream audio playback success",color:"#0dd90d",class:"success"},"main stream - video player is starting playing":{tips:"Remote stream video playback success",color:"#0dd90d",class:"success"},"video player is playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"audio player is playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"stream - video player is starting playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"stream - audio player is starting playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"switch camera success":{tips:"Switch camera success",color:"#0dd90d",class:"success"},"switch microphone success":{tips:"Switch microphone success",color:"#0dd90d",class:"success"},gotStream:{tips:"Local stream capture success"},"local stream is published successfully":{tips:"Publish success",color:"#0dd90d",class:"success"},"encoderImplementation change to OpenH264":{tips:"Use software encoding"},"encoderImplementation change to ExternalEncoder":{tips:"Use hardware encoding"},"getUserMedia with constraints":{tips:"Start media (camera/microphone) capture"},"getDisplayMedia with constraints":{tips:"Start screen sharing capture"},"client-banned":{tips:"Kicked out of the room",color:"red",class:"red",textColor:"#fff"},user_timeout:{tips:"The backend is too long without receiving SDK heartbeat, which is usually caused by the JS thread being blocked for a long time. If the reproduction probability is high, the application browser Performance tool analyzes where the JS thread is blocked.",color:"red",class:"red",textColor:"#fff"},"schedule failed":{tips:"Signaling request failed, does not affect the normal room entry process, SDK will connect to the default signaling domain."},"updateStream() video flag is true, but no camera detected, set video to false":{tips:"When trying to resume camera acquisition, the camera acquisition is not resumed because it is detected that there is no camera.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to bandwidth":{tips:"bandwidth estimation is not enough to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to cpu":{tips:"cpu load is too high to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: hidden":{tips:"User page switched to backend, in mobile devices, this will cause the device to pause the capture, and it will be restored when the user switches backend to the frontend.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: visible":{tips:"User page switched to frontend",color:"orange",class:"orange",textColor:"#fff"},"main stream - audio player is paused":{tips:`The remote stream audio playback is paused, which usually has two possibilities:
|
|
57
|
+
${r.stack}`),!1}},s};var Ws=new WeakMap;function rp(s){let i=Ws.get(s);i&&(i.forEach(e=>clearTimeout(e)),Ws.delete(s))}function sp(s,i){return Q((e,t)=>function(...r){let o=Ws.get(this);o||(o=new Map,Ws.set(this,o));let n=i(...r),a=o.get(n);if(!a||a<=0){e.apply(this,r);let c=setTimeout(()=>{var l;(l=Ws.get(this))==null||l.delete(n)},s);o.set(n,c)}else{clearTimeout(a);let c=window.setTimeout(()=>{var l;e.apply(this,r),(l=Ws.get(this))==null||l.delete(n)},s);o.set(n,c)}})}var np="trtc-sdk-v5",ap="5.11.0-beta.5";function Ge(...s){return Q((i,e)=>function(...t){try{cc.call(this,s,t,e,this._name)}catch(r){return Promise.reject(r)}return i.apply(this,t)})}function au(...s){return Q((i,e)=>function(...t){try{cc.call(this,s,t,e,this._name)}catch(r){throw r}return i.apply(this,t)})}function cc(s,i,e,t){if(Se(s))for(let r=0;r<s.length;r++)ac.call(this,{rule:s[r],value:i[r],key:s[r].name,fnName:e,className:t});else ac.call(this,{rule:s,value:i[0],key:s.name,fnName:e,className:t})}function ac({rule:s,value:i,key:e,fnName:t,className:r}){function o(c){return{code:B.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:s,value:i}}}if(T(i)){if(s.required)throw new U(o(5001));if(T(s.defaultValue)){ne(s.validate)&&s.validate.call(this,i,e,t,r,this);return}i=s.defaultValue}if(Array.isArray(s.type)){let c=!1;for(let l=0;l<s.type.length;l++)s.type[l]===null&&i===null&&(c=!0),ne(s.type[l])&&i instanceof s.type[l]&&(c=!0),ee(s.type[l])&&Re(i)===s.type[l].toLowerCase()&&(c=!0);if(!c)throw new U({code:B.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:s.type.map(l=>br(l)?os(l):ee(l)?l:Re(l))},value:i}})}else if(!T(s.type)&&Re(i)!==s.type)throw new U(o(5002));if(s.allowEmpty===!1){let c=q(i)&&(i===0||Number.isNaN(i)),l=ee(i)&&i.trim()==="";if(c||l)throw new U(o(5003))}if(s.notLessThanZero&&q(i)&&i<0)throw new U(o(5006));if(!T(s.min)&&q(i)&&i<s.min)throw new U(o(5007));if(!T(s.max)&&q(i)&&i>s.max)throw new U(o(5008));if(ee(s.instanceOf)){if(!i||i._name!==s.instanceOf)throw new U(o(5004))}else if(ne(s.instanceOf)&&!(i instanceof s.instanceOf))throw new U(o(5004));if(Array.isArray(s.values)&&!s.values.includes(i))throw new U(o(5005));let{properties:n}=s;Je(n)&&Mt(i)&&Object.keys(n).forEach(c=>{ac.call(this,{rule:n[c],value:i&&i[c],key:`${c}`,fnName:t,className:r})});let{arrayItem:a}=s;Je(a)&&Se(i)&&i.forEach((c,l)=>{ac.call(this,{rule:a,value:c,key:`${e}[${l}]`,fnName:t,className:r})}),ne(s.validate)&&s.validate.call(this,i,e,t,r,this)}function fe(s={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t,ignoreLog:r,ignoreErrorLog:o}=s;return Q((n,a)=>function(...c){var g,D,_;function l(S,O,K){if(K&&K.includes(S))return"hided";if(e){let G=e(...c);if(c[G.argIndex]===O)return G.value}if(O===c||S in c)return O;try{return O instanceof HTMLElement?`id: ${O.id} type:${Re(O)}`:O instanceof MediaStreamTrack?Vn(O):(JSON.stringify(O),O)}catch(G){return`type:${Re(O)}`}}let u=this._log||C;if(r!=null&&r(...c))return n.apply(this,c);c.length>0?u.info(`${a}() ${JSON.stringify(c,(S,O)=>l(S,O,["userSig","privateMapKey"]))}`):u.info(`${a}()`);let h=t?t(...c):ua[a],m=(o==null?void 0:o(...c))||!1;try{let S=n.apply(this,c),O=w();if(sr(S)){let K=`${a.includes("Plugin")?`${((D=(g=c[0]).getName)==null?void 0:D.call(g))||""} `:" "}`;return S.then(G=>(u.info(`${a}() success ${K}${i.call(this,...c)}`),b.addSuccessEvent({key:h,cost:w()-O}),G)).catch(G=>{var J;G=U.convertFrom.call(this,G,a,c.length===1?c[0]:c);let Z=G.extraCode||G.code,_e=(J=G.message)!=null&&J.includes(Z)?"":` code:${Z}`;throw m||u.error(`${a}() failed ${K}${i.call(this,...c)} ${G}${_e} params: ${JSON.stringify(c,l)}`),b.addFailedEvent({key:h,error:G}),G})}return b.addSuccessEvent({key:h}),S}catch(S){S=U.convertFrom.call(this,S,a);let O=S.extraCode||S.code,K=(_=S.message)!=null&&_.includes(O)?"":` code:${O}`;throw m||u.error(`${a}() failed ${S}${K} params: ${JSON.stringify(c,l)}`),b.addFailedEvent({key:h,error:S}),S}})}var dc=s=>Q((i,e)=>function(t,r){return f(this,null,function*(){let o=this._plugins.get(t);if(!o)throw this._log.error(`plugin ${String(t)} is not found`),new U({code:B.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});if(ne(o.constructor.isSupported)&&!o.constructor.isSupported())throw this._log.error(`plugin ${String(t)} is not supported`),new U({code:B.ENV_NOT_SUPPORTED,message:`plugin ${String(t)} is not supported`,extraCode:5210,fnName:e});return cc.call(this,o.getValidateRule(s),[r],e,"TRTC"),i.call(this,o,r)})});var lc=0,cu,ji=class ji{constructor(i){this.core=i;d(this,"log");d(this,"customAudioReferenceMap",new Map);d(this,"audioRefId",0);d(this,"audioContext",Ee());d(this,"localAudioWorkletNode");d(this,"screenAudioWorkletNode");d(this,"mixNode");d(this,"silentNode");lc=lc+1,this.log=i.log.createChild({id:`${this.getAlias()}${lc}`}),this.log.info(`created id=${this.getAlias()}${lc}`),i.assetsPath&&this.preload(`${i.assetsPath}/audioProcessor-wasm.js`)}static getStartValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,t,r,o){if(!i.room.audioManager.hasAudioTrack&&!i.room.audioManager.hasScreenAudioTrack)throw new U({code:B.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return cu||(cu=this.doPreload(i)),cu}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield Bi(this.audioContext,t)}catch(r){this.log.error(`preload audioProcessor failed. ${r}`)}finally{URL.revokeObjectURL(t)}})}getName(){return ji.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(i){switch(i){case"start":return ji.getStartValidateRule(this.core);case"update":return ji.updateValidateRule;case"stop":return ji.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e}=this.core,{sdkAppId:t,userId:r,assetsPath:o,audioReference:n,processLevel:a,enableDump:c,isLocalAudioNeedAudioProcess:l=!0,isScreenAudioNeedAudioProcess:u=!0}=i;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=l,this.core.room.audioManager.isScreenAudioNeedAudioProcess=u,yield this.preload(`${o}/audioProcessor-wasm.js`),!this.localAudioWorkletNode||!this.screenAudioWorkletNode){let h=String(Date.now()).slice(0,-3),{auth:m,sign:g,status:D,message:_}=yield HT(L(N({},i),{timestamp:h}));if(!m)throw this.log.info(`audioProcessor: ${r} auth result: ${m}. Message: ${_}`),new U({code:B.INVALID_PARAMETER,message:_});this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",t,r,h,g,D,e),this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",t,r,h,g,D,e)}this.mixNode||(this.mixNode=this.audioContext.createGain(),this.mixNode.gain.value=1),this.silentNode||(this.silentNode=this.audioContext.createConstantSource(),this.silentNode.offset.setValueAtTime(0,this.audioContext.currentTime),this.silentNode.start()),this.localAudioWorkletNode.port.postMessage({type:"enable"}),this.screenAudioWorkletNode.port.postMessage({type:"enable"}),e.audioManager.addAudioProcessor(this.localAudioWorkletNode,this.mixNode,this.silentNode,this.screenAudioWorkletNode),T(n)||n.forEach(h=>{this.customAudioReferenceMap.set(h,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:h,refId:`o-${this.audioRefId++}`})}),T(a)||this.localAudioWorkletNode.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:a}}),T(c)||this.localAudioWorkletNode.port.postMessage({type:"dump",data:{enable:c}})})}update(i){return f(this,null,function*(){if(!this.localAudioWorkletNode||!this.screenAudioWorkletNode)return;let{audioReference:e,enableDump:t,processLevel:r}=i;T(e)||(this.customAudioReferenceMap.forEach((o,n)=>{this.customAudioReferenceMap.delete(n),this.core.room.audioManager.updateAudioReference({type:"remove",refId:o})}),e.forEach(o=>{this.customAudioReferenceMap.set(o,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:o,refId:`o-${this.audioRefId++}`})})),T(r)||this.localAudioWorkletNode.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:r}}),T(t)||(this.localAudioWorkletNode.port.postMessage({type:"dump",data:{enable:t}}),this.screenAudioWorkletNode.port.postMessage({type:"dump",data:{enable:t}}))})}stop(){return f(this,null,function*(){if(!this.localAudioWorkletNode||!this.mixNode||!this.silentNode||!this.screenAudioWorkletNode)return;let{room:i}=this.core;this.localAudioWorkletNode.port.postMessage({type:"disable"}),this.screenAudioWorkletNode.port.postMessage({type:"disable"}),yield i.audioManager.removeAudioProcessor(this.localAudioWorkletNode,this.mixNode,this.silentNode,this.screenAudioWorkletNode)})}destroy(){this.localAudioWorkletNode&&(this.localAudioWorkletNode.port.onmessage=null),this.screenAudioWorkletNode&&(this.screenAudioWorkletNode.port.onmessage=null)}initWorkletNode(i,e,t,r,o,n,a,c){i.port.postMessage({type:"init",data:{sdkAppId:String(t),userId:r,timestamp:o,sign:n,status:a}}),i.port.onmessage=l=>{var h;let{data:u}=l;switch(u.type){case"cost":let m=(u==null?void 0:u.value)>10?"info":"debug";this.log[m](`[${e}] avg cost: ${u.value} max: ${u==null?void 0:u.max}(${es(new Date(u==null?void 0:u.maxCostTimestamp))}) hist: ${(h=u==null?void 0:u.hist)==null?void 0:h.join(" ")}`);return;case"log":this.log[u.logLevel](`[${e}] ${u.value}`);return;case"dump":E.emit("265",{room:c,data:u.value,type:e==="localAudio"?"dump":"dump-screen-audio"});return}}}};d(ji,"updateValidateRule",{type:"object"}),d(ji,"stopValidateRule",{type:"object"}),d(ji,"Name","AudioProcessor");var uc=ji;function $T(s,i=p.MAIN){return`https://${_i[i]||nc(s,i)}/api/v1/audioAiAuth`}function HT(r){return f(this,arguments,function*({sdkAppId:s,userId:i,userSig:e,timestamp:t}){let n=`${$T(s)}?sdkAppId=${s}&userId=${i}&userSig=${e}×tamp=${t}`,a=yield fetch(n),{data:{errCode:c,errMsg:l,sign:u,status:h}}=yield a.json();if(h==="1")return{auth:!0,sign:u,status:h,message:l};let m=Ci(s)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",g="Init RTCAudioProcessor failed.",D="";switch(c){case 1:D="Please check your params.";break;case 2:D=`You need to buy packages. Refer to: ${m}`;break;case 3:D="Server is invalid. Please contact our engineer. ";break;case 4:D=`Your packages is not active. Refer to: ${m}`;break;case 5:D=`Your packages is expired. Refer to: ${m}`;break;case 6:D="Your version is not supported.";break}return{auth:!1,status:h,message:l?`${g} Reason: ${l}. ${D}`:`${g}, ${D}`}})}var hc=0,du=class{constructor(i,e){d(this,"player");d(this,"publisher");d(this,"mixInput");this.mixInput=new Ms(e),i.url?(this.player=new Audio(i.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(i.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(i.track),this.mixInput.connect()}updateSettings(i){this.player&&(T(i.volume)||(this.volume=i.volume),T(i.loop)||(this.loop=i.loop),T(i.playbackRate)||(this.playbackRate=i.playbackRate))}updateListener(i){if(this.player){if(i.onDurationChange){let{onDurationChange:e}=i;this.player.ondurationchange=t=>{e(t.target.duration)}}if(i.onTimeUpdate){let e=i.onTimeUpdate,{player:t}=this;t.ontimeupdate=()=>{e(t.currentTime,t.duration)}}i.onEnded&&(this.player.onended=i.onEnded)}}reset(){this.seek(0),this.mixInput.connect()}seek(i){this.player&&(i<0&&i>this.player.duration||(this.player.currentTime=i,this.publisher.currentTime=i))}play(){var i,e;return(i=this.publisher)==null||i.play(),(e=this.player)==null?void 0:e.play()}pause(){var i,e;(i=this.player)==null||i.pause(),(e=this.publisher)==null||e.pause()}stop(){var i;(i=this.player)==null||i.pause(),this.mixInput.disconnect()}setOperation(i){i==="pause"&&this.pause(),i==="resume"&&(this.pause(),this.play()),i==="stop"&&(this.pause(),this.seek(0))}set volume(i){!this.player||!this.publisher||(this.player.volume=i,this.publisher.volume=i)}set loop(i){!this.player||!this.publisher||(this.player.loop=i,this.publisher.loop=i)}set playbackRate(i){!this.player||!this.publisher||(this.player.playbackRate=i,this.publisher.playbackRate=i)}};function Js(s,i){if(i&&typeof i!="function")throw new U({code:B.INVALID_PARAMETER,message:`start audioMixer plugin: param ${s} should be a function.`})}var gi=class gi{constructor(i){this.core=i;d(this,"log");d(this,"mixedMusicMap",new Map);d(this,"cacheMusicMap",new Map);hc=hc+1,this.log=i.log.createChild({id:`${this.getAlias()}${hc}`}),this.log.info(`created id=${this.getAlias()}${hc}`)}getName(){return gi.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return gi.startValidateRule;case"update":return gi.updateValidateRule;case"stop":return gi.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e}=this.core;this.log.info(`add music source, id: ${i.id} url: ${i.url}, track: ${i.track}`);let{id:t,url:r}=i;if(this.mixedMusicMap.has(t))return;let o=this.cacheMusicMap.get(t);o?i.url?o.reset():(o.mixInput.replaceSource(i.track),o.mixInput.connect()):(o=new du(i,e.audioManager),this.cacheMusicMap.set(t,o)),o.updateListener(i),o.updateSettings(i),yield o.play(),this.mixedMusicMap.set(t,o),o.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"add",audioReference:o.mixInput.source.node,refId:`ax-${t}`}),this.log.info(`start mix audio track ${t} success.`),b.addEnum({key:502700,value:3}),this.kvUpload(i)})}update(i){return f(this,null,function*(){let{id:e,operation:t,seekFrom:r,playbackRate:o}=i;this.log.info(`update music source, ${JSON.stringify(i)}`);let n=this.mixedMusicMap.get(e);if(!n){this.log.warn(`update music source failed, music id: ${e} not found.`);return}n.updateSettings(i),n.updateListener(i),T(t)||n.setOperation(t),T(r)||n.seek(r),this.kvUpload(i)})}stop(e){return f(this,arguments,function*({id:i}){if(this.mixedMusicMap.has(i)){this.log.info(`remove music source, music id: ${i}`);let t=this.mixedMusicMap.get(i);t!=null&&t.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:t.mixInput.source.node,refId:`ax-${i}`}),t==null||t.stop(),this.mixedMusicMap.delete(i)}i==="*"&&this.destroyAllMusic()})}kvUpload(i){let{track:e,loop:t,volume:r,playbackRate:o,operation:n,seekFrom:a,onTimeUpdate:c,onDurationChange:l,onEnded:u}=i;e&&b.addCount({key:502711}),t&&b.addCount({key:502703}),r&&b.addCount({key:502704}),o&&b.addCount({key:502705}),n&&b.addCount({key:502706}),a&&b.addCount({key:502707}),typeof c!="function"&&b.addCount({key:502709}),typeof u!="function"&&b.addCount({key:502710}),typeof l!="function"&&b.addCount({key:502708})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((i,e)=>{i!=null&&i.mixInput.track&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:i.mixInput.track,refId:e}),this.stop({id:e})})}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}};d(gi,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(i,e,t){if(i.url&&i.url!=="*"){let r=i.url.split("?")[0],o=["mp3","ogg","wav","flac"],n=r.split(".").pop(),a=o.indexOf(n)>=0,c=r.startsWith("blob"),l=r.startsWith("data");if(!(a||c||l))throw new U({code:B.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new U({code:B.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});Js("onTimeUpdate",i.onTimeUpdate),Js("onEnded",i.onEnded),Js("onDurationChange",i.onDurationChange)}}),d(gi,"updateValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},loop:{type:"boolean"},volume:{type:"number"},seekFrom:{type:"number"},operation:{type:"string",values:["pause","resume","stop"]}},validate(i,e,t){Js("onTimeUpdate",i.onTimeUpdate),Js("onEnded",i.onEnded),Js("onDurationChange",i.onDurationChange)}}),d(gi,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),d(gi,"Name","AudioMixer");var mc=gi;var pc=0,lu,Xi=class Xi{constructor(i){this.core=i;d(this,"log");d(this,"audioContext",Ee("denoiser"));d(this,"workletNode");pc=pc+1,this.log=i.log.createChild({id:`${this.getAlias()}${pc}`}),this.log.info(`created id=${this.getAlias()}${pc}`),i.assetsPath&&this.preload(`${i.assetsPath}/denoiser-wasm.js`).catch(e=>{})}static startValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,t,r,o){if(!i.room.audioManager.hasAudioTrack)throw new U({code:B.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return lu||(lu=this.doPreload(i)),lu}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield Bi(this.audioContext,t)}catch(r){throw this.log.error("load worklet failed",r),r}finally{URL.revokeObjectURL(t)}})}getName(){return Xi.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(i){switch(i){case"start":return Xi.startValidateRule(this.core);case"update":return Xi.updateValidateRule;case"stop":return Xi.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e,schedule:t}=this.core;if(i.assetsPath&&(yield this.preload(`${i.assetsPath}/denoiser-wasm.js`)),!this.workletNode){let r=String(Date.now()).slice(0,-3),{auth:o,sign:n,status:a,message:c}=yield WT(t,L(N({},i),{timestamp:r}));if(!o)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${o}. Message: ${c}`),new U({code:B.INVALID_PARAMETER,message:c});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(i.sdkAppId),userId:i.userId,timestamp:r,sign:n,status:a}}),this.workletNode.port.onmessage=l=>{var h;let{data:u}=l;if(u.type==="cost"){let m=(u==null?void 0:u.max)>20?"warn":(u==null?void 0:u.max)>10?"info":"debug";this.log[m](`avg cost: ${u.value} max: ${u==null?void 0:u.max}(${es(new Date(u==null?void 0:u.maxCostTimestamp))}) hist: ${(h=u==null?void 0:u.hist)==null?void 0:h.join(" ")}`)}else u.type==="log"&&this.log[u.logLevel](`${u.value}`)}}this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(){return f(this,null,function*(){})}stop(){return f(this,null,function*(){if(!this.workletNode)return;let{room:i}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield i.audioManager.removeDenoiser(this.workletNode)})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};d(Xi,"updateValidateRule",{type:"object"}),d(Xi,"stopValidateRule",{type:"object"}),d(Xi,"Name","AIDenoiser");var fc=Xi;function WT(o,n){return f(this,arguments,function*(s,{sdkAppId:i,userId:e,userSig:t,timestamp:r}){try{let{data:{errCode:a,errMsg:c,sign:l,status:u}}=yield s.getAbilityConfig(i,s.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:i,userId:e,userSig:t,timestamp:r});if(u==="1")return{auth:!0,sign:l,status:u,message:c};let h=Ci(i)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",m="Init RTCAIDenoiser failed.",g="";switch(a){case 1:g="Please check your params.";break;case 2:g=`You need to buy packages. Refer to: ${h}`;break;case 3:g="Server is invalid. Please contact our engineer. ";break;case 4:g=`Your packages is not active. Refer to: ${h}`;break;case 5:g=`Your packages is expired. Refer to: ${h}`;break;case 6:g="Your version is not supported.";break}return{auth:!1,status:u,message:c?`${m} Reason: ${c}. ${g}`:`${m}, ${g}`}}catch(a){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${a}`}}})}var dp=$e(Ye(),1);var uu=class extends dp.EventEmitter{constructor(){super();d(this,"observer");d(this,"state","nominal");this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return f(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!pe&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){re.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let t=this.stateNum,r=e[e.length-1];this.state=r.state,(this.stateNum>3||t>3)&&C.info(`${r.source}: ${r.state}`),this.emit("state-changed",{type:r.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(t){re.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},JT=new uu,hu=JT;function mu([s,i]){let e=i.byteLength,t=parseInt(String(e/255),10),r=e%255,o=[];o.push(0,0,0,1,6,s);for(let a=0;a<t;a++)o.push(255);o.push(r);let n=new DataView(i);return o.push(...new Uint8Array(n.buffer)),o.push(128),new Hi(new DataView(new Uint8Array(o).buffer),!0)}function pu(s){return s.type==="empty"||s.data.byteLength===0}function fu(s){return s.getInt32(0)===1&&s.getInt8(4)===6}function _u(s){let i=0,e=0,t=new DataView(s);for(let r=0;r<s.byteLength;r++)switch(t.getUint8(r)){case 0:i++;break;case 1:(i===2||i===3)&&e++,i=0;break;default:i=0;break}return e}function gu({frame:s,seiMessageList:i}){if(!i||i.length===0||s.data.byteLength===0)return s;let t=9-_u(s.data);if(t<=0)return s;let r=i.splice(0,t).reverse().map(mu),o=r.reduce((u,h)=>u+h.dataView.byteLength,0),n=new ArrayBuffer(o+s.data.byteLength),a=new DataView(n),c=new DataView(s.data),l=0;for(let u=0;u<r.length;u++)for(let h=0;h<r[u].dataView.byteLength;h++)a.setInt8(l++,r[u].dataView.getInt8(h));for(let u=0;u<s.data.byteLength;u++)a.setInt8(l++,c.getInt8(u));return s.data=n,s}function Tu({frame:s,onSEI:i}){try{let e=new DataView(s.data);if(pu(s)||!fu(e))return s;let t=[],r=0,o=-1,n=-1;for(let a=0;a<s.data.byteLength;a++){let c=e.getUint8(a);if(c===0)r++;else if(c===1){if(r===2||r===3){let l=a-r;if(o===-1?o=l:n===-1&&(n=l,t.push(new Hi(new DataView(e.buffer.slice(o,n)))),o=l,n=-1),!(e.getUint8(a+1)===6)){s.data=e.buffer.slice(l);break}}r=0}else r=0}i==null||i(t.reverse())}catch(e){}return s}var Eu=0,nn=class nn{constructor(i){this.core=i;d(this,"log");d(this,"_seiMessageList",[]);d(this,"_smallSeiMessageList",[]);d(this,"_subStreamSeiMessageList",[]);Eu++,this.log=i.log.createChild({id:`${this.getAlias()}${Eu}`}),this.log.info(`[sei] created id=${this.getAlias()}${Eu}`),this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode({frame:i,mediaType:e}){try{let t=e===8?this._smallSeiMessageList:e===2?this._subStreamSeiMessageList:this._seiMessageList;return gu({frame:i,seiMessageList:t})}catch(t){this.log.warn(t)}return i}decode({frame:i,track:e}){return Tu({frame:i,onSEI:t=>{t.forEach(r=>{this.core.trtc.emit(k.SEI_MESSAGE,{seiPayloadType:r.seiPayloadType,data:r.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"})})}})}destroy(){this.log.debug("destory"),this.stop(),delete this.core}getValidateRule(i){switch(i){case"start":return{type:"object"};case"update":return{type:"object"};case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:Ui?this.encode:gu,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:Ui?this.decode:Tu,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update({buffer:i,options:e}){var o;let t=[e.seiPayloadType,i],r=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(t):(this._seiMessageList.push(t),r&&this._smallSeiMessageList.push(t)),(o=this.core.room.scriptTransformWorker)==null||o.postMessage({type:"sei",data:t,isMain:!e.toSubStream,small:r})}getName(){return nn.Name}getAlias(){return"sei"}getGroup(){return"sei"}};d(nn,"autoStart",!0),d(nn,"Name","SEI");var _c=nn;function Su({frame:s,onDump:i}){return i==null||i(),s}function Iu({frame:s,onDump:i}){return i==null||i(),s}var lp={"play() error: NotAllowedError:":{tips:s=>s.includes("main <video>")||s.includes("main <audio>")?"Remote stream auto play is restricted and playback fails":"Local stream playback failure, generally only occurs in Android WeChat devices, no need to handle",color:"red",class:"red"},"updateStream() try to recover local stream":{tips:"Device acquisition exception, automatic recovery is in progress"},"updateStream() recover local stream successfully":{tips:"Device acquisition exception, automatic recovery is successful"},"updateStream() failed to recover local stream":{tips:"Device acquisition exception, automatic recovery failed"},"main stream - video track is muted":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is muted":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is muted":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unable to provide media output":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is unable to provide media output":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is unable to provide media output":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unmuted":{tips:"Received enough playback video data"},"main stream - audio track is unmuted":{tips:"Received enough playback audio data"},"auxiliary stream - video track is unmuted":{tips:"Received enough playback screen sharing data"},"main stream - audio player track is ended":{tips:"Remote audio track stopped"},"main stream - video player track is ended":{tips:"Remote video track stopped"},"auxiliary stream - video player track is ended":{tips:"Received enough playback screen sharing data"},"stream - video track is muted":{tips:"Camera capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"stream - video track is unable to provide media output":{tips:"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked, and the customer needs to re-acquire. SDK v4.11.4+ will automatically resume acquisition without customer intervention",color:"orange"},"video track is unable to provide media output":{tips:s=>s.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"stream - audio track is muted":{tips:"Microphone capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"audio track is unable to provide media output":{tips:s=>s.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"Microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio track is unable to provide media output":{tips:"The microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"is adding audio track to current published local stream":{tips:"add audio track",color:"orange"},"is removing audio track from current published local stream":{tips:"remove audio track",color:"orange"},"is removing video track from current published local stream":{tips:"remove video track",color:"orange"},"is adding video track to current published local stream":{tips:"add video track",color:"orange"},"is replacing audio track to current published local main stream":{tips:"replace audio track",color:"orange"},"is replacing video track to current published local main stream":{tips:"replace video track",color:"orange"},"downlink network quality change":{tips:"Downstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"uplink network quality change":{tips:"Upstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"localStream mute video":{tips:"mute upstream video stream",color:"orange"},"localStream unmute video":{tips:"unmute upstream video stream",color:"orange"},"localStream mute audio":{tips:"mute upstream audio stream",color:"orange"},"localStream unmute audio":{tips:"unmute upstream audio stream",color:"orange"},"black detected":{tips:"Detect black screen, which means fps = 0. It is usually caused by network, and the network will be recovered after a while. If the network is normal but has not been restored, it is an abnormal situation."},'main stream start to play with options: {"muted":true}':{tips:"Play the remote stream in silent mode. Generally, the remote stream does not need to be played in silent mode. You need to confirm whether the parameters passed in the client stream.play API call are correct.",color:"orange"},"main stream - audio player is starting playing":{tips:"Remote stream audio playback success",color:"#0dd90d",class:"success"},"main stream - video player is starting playing":{tips:"Remote stream video playback success",color:"#0dd90d",class:"success"},"video player is playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"audio player is playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"stream - video player is starting playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"stream - audio player is starting playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"switch camera success":{tips:"Switch camera success",color:"#0dd90d",class:"success"},"switch microphone success":{tips:"Switch microphone success",color:"#0dd90d",class:"success"},gotStream:{tips:"Local stream capture success"},"local stream is published successfully":{tips:"Publish success",color:"#0dd90d",class:"success"},"encoderImplementation change to OpenH264":{tips:"Use software encoding"},"encoderImplementation change to ExternalEncoder":{tips:"Use hardware encoding"},"getUserMedia with constraints":{tips:"Start media (camera/microphone) capture"},"getDisplayMedia with constraints":{tips:"Start screen sharing capture"},"client-banned":{tips:"Kicked out of the room",color:"red",class:"red",textColor:"#fff"},user_timeout:{tips:"The backend is too long without receiving SDK heartbeat, which is usually caused by the JS thread being blocked for a long time. If the reproduction probability is high, the application browser Performance tool analyzes where the JS thread is blocked.",color:"red",class:"red",textColor:"#fff"},"schedule failed":{tips:"Signaling request failed, does not affect the normal room entry process, SDK will connect to the default signaling domain."},"updateStream() video flag is true, but no camera detected, set video to false":{tips:"When trying to resume camera acquisition, the camera acquisition is not resumed because it is detected that there is no camera.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to bandwidth":{tips:"bandwidth estimation is not enough to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to cpu":{tips:"cpu load is too high to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: hidden":{tips:"User page switched to backend, in mobile devices, this will cause the device to pause the capture, and it will be restored when the user switches backend to the frontend.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: visible":{tips:"User page switched to frontend",color:"orange",class:"orange",textColor:"#fff"},"main stream - audio player is paused":{tips:`The remote stream audio playback is paused, which usually has two possibilities:
|
|
58
58
|
1. The business side passes in the div tag container for playing audio and video to be removed by the business side from the DOM.
|
|
59
59
|
2. If the user is in Chrome 70 and below, when the div container is moved, the playback will be paused.`,color:"orange",class:"orange",textColor:"#fff"},"main stream - video player is paused":{tips:`The remote stream video playback is paused, which usually has two possibilities:
|
|
60
60
|
1. The business side passes in the div tag container for playing audio and video to be removed by the business side from the DOM.
|
|
@@ -118,4 +118,4 @@ offer: ${t==null?void 0:t.sdp}`),o}})}setIceServers(e){return f(this,null,functi
|
|
|
118
118
|
next offer: ${this.filterSDPDirection(e==null?void 0:e.sdp)}`),this._log.warn(`current answer: ${this.filterSDPDirection((a=this._peerConnection.remoteDescription)==null?void 0:a.sdp)}
|
|
119
119
|
next answer: ${this.filterSDPDirection(t)}`),this._log.warn(`offer: ${e==null?void 0:e.sdp}`),this._log.warn(`answer: ${t}`),this._log.warn(`transceivers: ${JSON.stringify(this._peerConnection.getTransceivers().map(({mid:l,currentDirection:u,direction:h,stopped:m})=>({mid:l,currentDirection:u,direction:h,stopped:m})))}`),this._log.warn(`parsedAnswer: ${JSON.stringify(this._parsedAnswer)}`),this._isSDPLogged=!0),this._updateSDPPromise=null,o(c)}})),this._updateSDPPromise}setTransceiverDirection(e,t){return f(this,null,function*(){if(!ae||!this._peerConnection||!this._parsedAnswer)return;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let r=this._peerConnection.getTransceivers();t.forEach(o=>{r[o].direction!==e&&(r[o].direction=e)});for(let o of t){let n=this._parsedAnswer.media[o].direction;e===te.INACTIVE&&n===te.RECVONLY&&(this._parsedAnswer.media[o].direction=e),e===te.SENDONLY&&n===te.INACTIVE&&(this._parsedAnswer.media[o].direction=te.RECVONLY)}yield this.updateSDP()})}filterSDPDirection(e=""){return ye(e).media.map(r=>r.direction)}setOffer(e){this._log.info("setting offer");let t=Jp(e.sdp,this.clientAbility,this._serverAbility);return this._log.debug(t),this._peerConnection.setLocalDescription({type:"offer",sdp:t})}setAnswer(e){return this._log.info("setting answer"),this._log.debug(e.sdp),this._peerConnection.setRemoteDescription(e)}switchVideoEncoder(e){return f(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let t=!1;this._parsedAnswer.media.forEach(r=>{var o;if(r.type===p.VIDEO){let n=this._serverAbility.video.codecs.find(a=>a.codec.toLowerCase()===e);n&&!((o=r.payloads)!=null&&o.includes(String(n.payload)))&&(r.fmtp=[],r.payloads="",r.rtp=[],r.rtcpFb=[],Zr(r,n),t=!0)}}),t&&(this._log.warn(`switch video encoder to ${e}`),yield this.updateSDP())})}useHWEncoder(e=!0,t){return f(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let r=!1,o=[];T(t)?o=this._parsedAnswer.media.slice(1,4):t===2?o.push(this._parsedAnswer.media[1]):t===3?o.push(this._parsedAnswer.media[2]):t===7&&o.push(this._parsedAnswer.media[3]),o.forEach(n=>{var a;if(n.type===p.VIDEO){let c;e&&this.is42001fSupported?c=this.clientAbility.video.codecs.find(l=>l.fmtp.includes("42001f")):e||(c=this._serverAbility.video.codecs.find(l=>l.codec.toLowerCase()===(this._serverAbility.useVp8?"vp8":"h264"))),c&&!((a=n.payloads)!=null&&a.includes(String(c.payload)))&&(n.fmtp=[],n.payloads="",n.rtp=[],n.rtcpFb=[],Zr(n,c),r=!0)}}),r&&(this._log.warn(`use ${e?"hw":"sw"} encoder`),yield this.updateSDP())})}sendDataChannelMessage(e){var t;(t=this._datachannel)==null||t.send(e)}reset(){var e;this._peerConnection&&(this._peerConnection.close(),this._peerConnection.removeEventListener("track",this._peerConnection._onaddstreampoly,this),this._peerConnection._onaddstreampoly=null,this._peerConnection=null),(e=this.clearWaitForConnectedPromise)==null||e.call(this),this._parsedAnswer=null,this.originOffer=null}close(){this._log.info("close pc"),this.removeRTCListener(),this.insertableStreamsAbortMap.forEach(e=>Qt(e.abort)&&e.abort("destroy")),this.insertableStreamsAbortMap.clear(),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners(),this._room.healthDetector.off("1",this.onBadHealth,this)}getReceiversByUserId(e){if(!this._peerConnection)return[];let t=this._peerConnection.getReceivers();return(this._downlinkMIDMap.get(e)||[]).map(r=>t[r])}get isUsingRelay(){return this._room.getIceTransportPolicy()==="relay"}detectTCPAndUDP({uplinkRTT:e,downlinkRTT:t}){var u;if(this.currentState!=="CONNECTED"||this._isRelayTried&&!this._room.forceRelay||this._room.getIceServers().length===0)return;let r=this._signalChannel.rtt,o=Math.max(e,t),{rttRatioThreshold:n,rttThreshold:a}=((u=this._room.scheduleResult.config)==null?void 0:u.useTurnTcpInfo)||{};if(!n||!a||!r||!o)return;let c=Math.floor(o/r),l=(this._isRelayTried||c>n)&&o>a;if(!l){this._rttOverCount=0;return}++this._rttOverCount<5||(this._log.warn(`detectTCPAndUDP ws-rtt: ${r} upRTT: ${e} downRTT: ${t} ratio: ${c} over-count: ${this._rttOverCount} isOver: ${l} isRelayTried: ${this._isRelayTried} force-relay: ${this._room.forceRelay}`),!this.isUsingRelay&&!this._isRelayTried?(this._isRelayTried=!0,this._rttOverCount=0,this.switchRelay(!0)):this._room.forceRelay&&this.switchRelay(!1))}switchRelay(e,t=!1){return f(this,null,function*(){if(this.isUsingRelay===e)return;let r=e?"relay":"udp",o=e?521709:521710;try{this._room.forceRelay=e,this._log.warn(`switchRelay ${r}`);let n=Date.now();yield this.doSwitchRelay(r),this._log.warn(`switchRelay ${r} success`),b.addSuccessEvent({key:o,cost:Date.now()-n})}catch(n){this._log.warn(`switchRelay ${r} failed`,n),b.addFailedEvent({key:o,error:n}),t?this._room.reJoin():yield this.switchRelay(!e,!0)}})}doSwitchRelay(e){return new Promise((t,r)=>{let o=setTimeout(()=>{this.stopReconnection(),r(new Error(`switch ${e} timeout`))},1e4);this.startReconnection().then(t,r).finally(()=>clearTimeout(o))})}removeRTCListener(){this._peerConnection&&(this._peerConnection.oniceconnectionstatechange=null,this._peerConnection.onconnectionstatechange=null,this._peerConnection.onsignalingstatechange=null,this._peerConnection.ontrack=null),this.dtlsTransport&&(this.dtlsTransport.onstatechange=null)}};v([xa("reconnect")],qt.prototype,"startReconnection",1),v([$i(e=>e.userId)],qt.prototype,"addDownlink",1),v([$i(e=>e)],qt.prototype,"removeDownlink",1),v([Rt(!0)],qt.prototype,"updateSDP",1),v([at(521712,!1)],qt.prototype,"setOffer",1),v([at(521713,!1)],qt.prototype,"setAnswer",1);var $u=class{constructor(i){d(this,"tag");d(this,"len");d(this,"data");let e=new DataView(i);this.tag=e.getUint16(),this.len=e.getUint16(2),this.data=new Uint8Array(i).slice(4,4+this.len).buffer}},Hu=class{constructor(i){d(this,"tinyId");d(this,"data");let e=new DataView(i),t=0,r=[];for(;t<e.byteLength;){let o=e.getUint16(t+2),n=new $u(new Uint8Array(i).slice(t,t+2+2+o).buffer);r.push(n),t+=4+o}r.forEach(o=>{o.tag===1?this.tinyId=new TextDecoder().decode(o.data):o.tag===2&&(this.data=o.data)})}},Yp=new Set;function Et(){let s=Math.floor(Math.random()*4294967296);return Yp.has(s)?Et():(Yp.add(s),s)}var tf=$e(Ye());var Kr=class extends tf.default{constructor(e){super();d(this,"userId");d(this,"tinyId");d(this,"_sdpSemantics");d(this,"_isUplink");d(this,"_room");d(this,"_log");d(this,"_currentState","DISCONNECTED");d(this,"_prevTime",-1);d(this,"_blackSmallVideoDetectionId");this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=C.createLogger({id:"n",userId:this._room.userId,remoteUserId:this._isUplink?void 0:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink})}get _peerConnection(){var e;return((e=this.singlePC)==null?void 0:e.getPeerConnection())||null}get singlePC(){return this._room.singlePC}get _signalChannel(){return this._room.signalChannel}close(e){this._log.info("close connection"),this.emit("closed",e)}emitConnectionStateChangedEvent(e){return e===this._currentState?!1:(E.emit(A.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:e,remoteUserId:this._isUplink?void 0:this.userId}),this.emit("connection-state-changed",{prevState:this._currentState,state:e}),this._currentState=e,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}getCurrentState(){return this._currentState}get isH264(){var e,t;return!!((t=(e=this._peerConnection)==null?void 0:e.remoteDescription)!=null&&t.sdp.includes("H264"))}};var Gu=class{constructor(){d(this,"worker");d(this,"callbacks",new Map);d(this,"_log");d(this,"sleep",{});d(this,"heartbeatListenerCleaner",new Map);d(this,"userIdMap",new Map);this._log=C.createLogger({id:"bvd"})}getWorker(){if(!this.worker){let i=`
|
|
120
120
|
const tracks=new Map;let canvas,ctx;const log=(...t)=>postMessage({type:"log",message:"[worker] "+t.join(" ")});function startDetection(e,t,a){if(!tracks.has(e)){const c={reader:a.getReader(),blackCount:0,timeoutId:null,intervalId:null};tracks.set(e,c),c.timeoutId=setTimeout(()=>stopDetection(e,"timeout"),t),c.intervalId=setInterval(async()=>{try{await isFrameBlack(e)?(c.blackCount++,postMessage({type:"blackCount",trackId:e,count:c.blackCount}),3<=c.blackCount&&(postMessage({type:"black",trackId:e}),stopDetection(e,"black"))):c.blackCount=0}catch(t){log("check black video error:",t.message),stopDetection(e,"error")}},1e3)}}function stopDetection(t,e){var a=tracks.get(t);a&&(a.timeoutId&&clearTimeout(a.timeoutId),a.intervalId&&clearInterval(a.intervalId),a.reader&&a.reader.cancel(),tracks.delete(t),postMessage({type:e,trackId:t}))}async function isFrameBlack(t){t=tracks.get(t);if(!t)return!1;var t=t.reader,{done:t,value:e}=await t.read();if(!e||t)return!1;canvas||(canvas=new OffscreenCanvas(e.codedWidth,e.codedHeight),ctx=canvas.getContext("2d",{willReadFrequently:!0})),canvas.width===e.codedWidth&&canvas.height===e.codedHeight||(canvas.width=e.codedWidth,canvas.height=e.codedHeight,ctx=canvas.getContext("2d",{willReadFrequently:!0})),ctx.drawImage(e,0,0,canvas.width,canvas.height);t=getFrameBlackRatio(ctx.getImageData(0,0,canvas.width,canvas.height));return e.close(),1===t}function getFrameBlackRatio(t){var e=t.data;let a=0;for(let t=0;t<100;t++){var c=4*Math.floor(Math.random()*(e.length/4)),[c,r,n,o]=[e[c],e[1+c],e[2+c],e[3+c]];0<o&&0===c&&0===r&&0===n&&a++}return a/100}self.onmessage=t=>{var{type:t,trackId:e,timeout:a,readable:c}=t.data;"addTrack"===t&&startDetection(e,a,c),"removeTrack"===t&&stopDetection(e)};
|
|
121
|
-
`,e=new Blob([i],{type:"application/javascript"}),t=URL.createObjectURL(e);this.worker=new Worker(t),URL.revokeObjectURL(t),this.worker.onerror=r=>this._log.warn("worker error:",r.message,r.filename||"unknown",r.lineno||"unknown"),this.worker.onmessage=r=>{var l;let{type:o,trackId:n,message:a,count:c}=r.data;if(o==="black")(l=this.callbacks.get(n))==null||l();else if(o==="log")this._log.warn(a);else if(o==="blackCount"){let u=this.userIdMap.get(n);this._log.warn(`${u||n} black count: ${c}`)}}}return this.worker}start({track:i,isUplink:e,room:t,userId:r,onBlack:o}){if(this._log.debug("start detect black video",i.id),!ko()||!o||!i||T(Worker))return;let n=a=>{var l,u,h,m;let c;if(e)c=(u=(l=a.msg_up_stream_info)==null?void 0:l.msg_video_status)==null?void 0:u.filter(g=>g.uint32_video_stream_type===3)[0];else{let g=(h=a.msg_down_stream_info)==null?void 0:h.filter(D=>{var _;return((_=D.msg_user_info)==null?void 0:_.str_identifier)===r})[0];c=(m=g==null?void 0:g.msg_video_status)==null?void 0:m.filter(D=>D.uint32_video_stream_type===3)[0]}if(c){let g=(c.uint32_video_codec_bitrate||0)/1e3;if(this.sleep[i.id]&&this.sleep[i.id]>0){this.sleep[i.id]-=1;return}g>0&&g<10&&(this.sleep[i.id]=30,this._log.debug("track bitrate",g,"start check"),this.checkOnce(i,30*1e3))}};return t.on("heartbeat-report",n),this.heartbeatListenerCleaner.set(i.id,()=>t.off("heartbeat-report",n)),this.callbacks.set(i.id,o),this.userIdMap.set(i.id,r),i.id}checkOnce(i,e){try{let t=this.getWorker();if(!t)throw new Error("Worker not available");let r=new MediaStreamTrackProcessor({track:i});t.postMessage({type:"addTrack",trackId:i.id,timeout:e,readable:r.readable},[r.readable])}catch(t){this._log.warn("check error:",t),this.stop(i.id)}}stop(i){if(i){this.worker&&this.worker.postMessage({type:"removeTrack",trackId:i}),this.callbacks.delete(i),delete this.sleep[i];let e=this.heartbeatListenerCleaner.get(i);e&&e(),this.heartbeatListenerCleaner.delete(i),this.userIdMap.delete(i)}}destroy(){this.callbacks.forEach((i,e)=>this.stop(e)),this.worker&&(this.worker.terminate(),this.worker=null)}},Yi=new Gu;var Tn=class extends Kr{constructor(e){super(L(N({},e),{isUplink:!0}));d(this,"localMainAudioTrack",null);d(this,"localMainVideoTrack",null);d(this,"localAuxAudioTrack",null);d(this,"localAuxVideoTrack",null);d(this,"_isPublishingAux",!1);d(this,"_publishingLocalAudioTrack");d(this,"_publishingLocalVideoTrack");d(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0});d(this,"_flag",0);d(this,"_checkPublishStateTimeoutId",-1);this.initialize()}get videoCodec(){var e;return((e=this.singlePC)==null?void 0:e.videoCodec)||"h264"}get ssrc(){if(!this.singlePC)return{audio:0,video:0,videoRtx:0,small:0,smallRtx:0,auxiliary:0,auxiliaryRtx:0};let{audioSsrc:e,bigVideoSsrc:t,bigVideoRtxSsrc:r,smallVideoSsrc:o,smallVideoRtxSsrc:n,auxVideoSsrc:a,auxVideoRtxSsrc:c}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:r||0,small:o||0,smallRtx:n||0,auxiliary:a||0,auxiliaryRtx:c||0}}get flag(){return this._flag}set flag(e){this._flag!==e&&(this._flag=e,this.checkPublishState())}checkPublishState(e=!1){if(!e&&this._checkPublishStateTimeoutId>0)return;let{publishState:t,serverPublishState:r}=this,o=Object.keys(t).find(n=>t[n]!==r[n]);if(o)if(e)this._log.warn(`publish state not matched, ${o} local:${t[o]} server:${r[o]} ${Pi()} ${Or()}`),b.addCount({key:521e3});else{this._checkPublishStateTimeoutId=oe.run("timeout",()=>this.checkPublishState(!0),{delay:10*1e3,count:1});return}oe.clearTask(this._checkPublishStateTimeoutId),this._checkPublishStateTimeoutId=-1}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}get publishState(){var t,r,o,n;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(si()?(e.audio=!!((t=a[0])!=null&&t.track),e.bigVideo=!!((r=a[1])!=null&&r.track),e.smallVideo=!!((o=a[2])!=null&&o.track),e.auxVideo=!!((n=a[3])!=null&&n.track)):a.forEach(c=>{c.track&&(c.track.kind===p.AUDIO?e.audio=!0:(e.bigVideo=!0,this._room.videoManager.hasSmall&&(e.smallVideo=!0)))}))}return e}get publishingState(){let{publishState:e}=this,t=N({},e);return this._publishingLocalAudioTrack&&(t.audio=!0),this._publishingLocalVideoTrack&&(this._isPublishingAux?t.auxVideo=!0:(t.bigVideo=!0,this._publishingLocalVideoTrack.small&&(t.smallVideo=!0))),t}get serverPublishState(){return{audio:!!(this.flag&ir),bigVideo:!!(this.flag&tr),smallVideo:!!(this.flag&so),auxVideo:!!(this.flag&Er)}}get muteState(){var e,t,r;return{audio:!!((e=this.localMainAudioTrack)!=null&&e.muted),bigVideo:!!((t=this.localMainVideoTrack)!=null&&t.muted),auxVideo:!!((r=this.localAuxVideoTrack)!=null&&r.muted)}}initialize(){this.installEvents()}close(e){var r;let t=((r=this._peerConnection)==null?void 0:r.getSenders())||[];for(let o of t)o.replaceTrack(null);super.close(e),this.uninstallEvents(),this.uninstallTrackMuteEvents(this.localMainAudioTrack,this.localMainVideoTrack,this.localAuxVideoTrack),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),this.installSPCEvents()}installSPCEvents(){var e,t;(e=this.singlePC)!=null&&e.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||(t=this.singlePC)==null||t.on("spc-reconnected",this.onSinglePCReconnected,this)}uninstallSPCEvents(){var e;(e=this.singlePC)==null||e.off("spc-reconnected",this.onSinglePCReconnected,this)}uninstallEvents(){this.off("connection-state-changed",this.handleConnectionStateChange,this),this.uninstallSPCEvents()}emitConnectionStateChangedEvent(e,t){var n,a,c;let r=this._currentState,o=super.emitConnectionStateChangedEvent(e);return o&&r!==e&&(t?t.emit("connection-state-changed",{prevState:r,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:r,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:r,state:e}),(c=this._publishingLocalVideoTrack)==null||c.emit("connection-state-changed",{prevState:r,state:e}))),o}onVideoEncodeFailed(e){var t;e&&e.isMediaTrackActive&&this.videoCodec==="h264"&&(this._log.warn("h264 encoder not working"),(t=this.singlePC)!=null&&t.isVP8EncodeSupported&&(this._log.warn("switch to vp8"),this.singlePC.switchVideoEncoder("vp8")))}publish(o){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:r}){var l,u,h,m,g,D,_;if(!this.singlePC)return;this.installEvents(),yield this.singlePC.waitForPeerConnectionConnected();let{publishState:n,muteState:a}=this;if(e&&(this._publishingLocalAudioTrack=e,n.audio=!0,a.audio=e.muted),t){if(!this.singlePC.isH264EncodeSupported&&!this.singlePC.isVP8EncodeSupported)throw new y({code:I.NOT_SUPPORTED_H264,message:x({key:P.NOT_SUPPORTED_H264ENCODE})});this.singlePC.isUsingH264&&!this.singlePC.isH264EncodeSupported&&this.singlePC.isVP8EncodeSupported&&(this._log.warn("h264 encoder not supported"),yield this.singlePC.switchVideoEncoder("vp8")),pe&&Ss()===115&&t.profile.width*t.profile.height<=640*360&&(this._log.warn(`fallback video to defaultBigVideoProfile: ${JSON.stringify(er)}`),t.setProfile(er),yield t.applyProfile()),this._publishingLocalVideoTrack=t,r?(n.auxVideo=!0,a.auxVideo=t.muted):(n.bigVideo=!0,a.bigVideo=t.muted)}this._isPublishingAux=r;let c;if(t&&!r&&t.small&&(c=this._room.videoManager.smallTrack,n.smallVideo=!0),yield this._signalChannel.sendWaitForResponseWithRetry({command:Y.SPC_PUBLISH,responseCommand:F.SPC_PUBLISH_RESULT,data:L(N({},this.singlePC.uplinkSSRC),{state:n,muteState:a}),retries:3}),yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:c,isAuxiliary:r}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,t){this[r?"localAuxVideoTrack":"localMainVideoTrack"]=t,yield this.singlePC.setDegradationPreference(this._peerConnection.getSenders()[r?3:1],t.contentHint,t.streamType);let{scaleResolutionDownBy:S}=t;yield this.singlePC.setScaleResolutionDownBy(this._peerConnection.getSenders()[r?3:1],S,t.streamType)}e&&(this[r?"localAuxAudioTrack":"localMainAudioTrack"]=e),yield this.singlePC.setBandwidth({audio:((l=this.localMainAudioTrack)==null?void 0:l.profile.bitrate)||((u=this.localAuxAudioTrack)==null?void 0:u.profile.bitrate),bigVideo:(h=this.localMainVideoTrack)==null?void 0:h.profile.bitrate,smallVideo:(g=(m=this.localMainVideoTrack)==null?void 0:m.small)==null?void 0:g.bitrate,auxVideo:(D=this.localAuxVideoTrack)==null?void 0:D.profile.bitrate}),this.sendMediaSettings(),this.installTrackMuteEvents(e,t),(this._room.preferHW||(_=this._room.scheduleResult.config)!=null&&_.preferHW)&&t&&t.profile.width*t.profile.height>=1280*720&&this.singlePC.useHWEncoder(!0,r?7:2)})}publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:r,isAuxiliary:o}){if(!mt())return;this._log.info("publish by transceiver");let n=t==null?void 0:t.outMediaTrack,a=e==null?void 0:e.outMediaTrack,c=this._peerConnection.getTransceivers(),l=[],u=[],h=(g,D,_)=>{var O;let S=c[D].sender.replaceTrack(_);u.push(D),(O=this.singlePC)!=null&&O.enableInsertableStreams&&S.then(()=>this.createEncodedStreams(c[D].sender,g)),this.initSenderTransform(c[D].sender,g),l.push(S)};a&&h(e.mediaType,0,a),n&&h(t.mediaType,o?3:1,n),t!=null&&t.small&&l.push(this.publishSmall(this._room.videoManager.smallMode,t));let m=this.singlePC.setTransceiverDirection(te.SENDONLY,u);return l.push(m),Promise.all(l)}getTrackByMediaType(e){switch(e){case 1:return this.localMainAudioTrack||this._publishingLocalAudioTrack;case 4:case 8:return this.localMainVideoTrack||this._publishingLocalVideoTrack;case 2:return this.localAuxVideoTrack||this._publishingLocalVideoTrack;default:return null}}createEncodedStreams(e,t){var a,c;if(this.singlePC.insertableStreamsAbortMap.has(e))return;let r=e.createEncodedStreams(),o=new AbortController;(a=this.singlePC)==null||a.addAbortController(e,o),((c=this.getTrackByMediaType(t))!=null&&c.enableEncodeFrame?r.readable.pipeThrough(new TransformStream({transform:(l,u)=>{var m;let h=this.getTrackByMediaType(t);u.enqueue((m=this.singlePC)!=null&&m.isUsingH264&&h?h.encodeFrame(l,t===8):l)}}),o):r.readable).pipeTo(r.writable,o).catch(l=>{this._log.debug("encoded stream error",l),l!=="destory"&&this._log.warn(l)})}initSenderTransform(e,t){if(!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker||!Ns)return;let r=t!==2,o=t===8;e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!1,isAudio:t===1,isMain:r,isSmall:o}))}enableSmall(e){return f(this,null,function*(){e?yield this.publishSmall(this._room.videoManager.smallMode):yield this.unpublishSmall()})}publishSmall(r){return f(this,arguments,function*(e,t=this.localMainVideoTrack){var l;if(!this.singlePC)return;let o=this._peerConnection.getTransceivers(),{sender:n}=o[2],a=yield this.doPublishSmall(e,t),c=e==="canvas"?524700:524701;if(b.addSuccessEvent({key:c}),!a){b.addFailedEvent({key:c,error:10001});return}(l=this.singlePC)!=null&&l.enableInsertableStreams&&this.createEncodedStreams(n,8),this.initSenderTransform(n,8),yield this.singlePC.setTransceiverDirection(te.SENDONLY,[2]),this.updateMediaSettings(),yield this.doPublishChange(),this._blackSmallVideoDetectionId=Yi.start({track:n.track,room:this._room,isUplink:!0,userId:this.userId,onBlack:()=>{this._log.warn("small video is black");let u=e==="canvas"?524700:524701;b.addFailedEvent({key:u,error:10002}),Yi.stop(this._blackSmallVideoDetectionId)}})})}doPublishSmall(r){return f(this,arguments,function*(e,t=this.localMainVideoTrack){if(!this.singlePC)return null;this._log.info("publish small",e);let o=this._peerConnection.getTransceivers(),{sender:n}=o[2];if(e==="canvas"&&this._room.videoManager.smallTrack)return yield n.replaceTrack(this._room.videoManager.smallTrack),"canvas";if(e==="api"&&(t!=null&&t.outMediaTrack)&&(t!=null&&t.small)){yield n.replaceTrack(t==null?void 0:t.outMediaTrack);let a=n.getParameters(),c=ls(t==null?void 0:t.profile,t==null?void 0:t.small);return this._log.info("small scaleResolutionDownBy",c),a.encodings[0].scaleResolutionDownBy=c,n.setParameters(a),"api"}return this._log.warn(`small track can not be enabled, smallMode: ${this._room.videoManager.smallMode}, smallTrack: ${!!this._room.videoManager.smallTrack}, bigVideoTrack: ${!!(t!=null&&t.outMediaTrack)}`),null})}unpublishSmall(){return f(this,null,function*(){if(!this.singlePC)return;this._log.info("unpublish small"),yield this._peerConnection.getTransceivers()[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(te.INACTIVE,[2]),this.updateMediaSettings(),yield this.doPublishChange(),Yi.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0})}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(r){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){var l;yield(l=this.singlePC)==null?void 0:l.waitForPeerConnectionConnected();let o=t&&t===this.localAuxVideoTrack,n=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),c=[];e&&(o?this.localAuxAudioTrack=null:this.localMainAudioTrack=null,!this.localMainAudioTrack&&!this.localAuxAudioTrack&&(yield a[0].replaceTrack(null),c.push(0))),n&&(o?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=L(N({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),c.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=L(N({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),c.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.singlePC.setTransceiverDirection(te.INACTIVE,c),yield this.doPublishChange(!1)):yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),t==null||t.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return f(this,null,function*(){let t={state:this.publishingState,constraintConfig:this._mediaSettings},r=yield this._signalChannel.sendWaitForResponseWithRetry({command:Y.PUBLISH_STATE_CHANGE,data:t,responseCommand:F.PUBLISH_STATE_CHANGE_RESULT,enableLog:e,retries:3});this.checkPublishResultCode(r.data.code,r.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:Y.UNPUBLISH,commandDesc:"unpublish",responseCommand:F.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===I.API_CALL_TIMEOUT)return Promise.resolve();throw t})}updateMediaSettings(){var o;this._mediaSettings.videoCodec=((o=this.singlePC)==null?void 0:o.videoCodec)||"h264";let e=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:t,localAuxVideoTrack:r}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?r=this._publishingLocalVideoTrack:t=this._publishingLocalVideoTrack),oi){if(e&&e.outMediaTrack){let n=e.outMediaTrack.getSettings();this._mediaSettings.audioChannel=n.channelCount||1,this._mediaSettings.audioBps=e.profile.bitrate*1e3,this._mediaSettings.audioFs=n.sampleRate||0}if(t&&t.outMediaTrack){let n=t.outMediaTrack.getSettings(),{scaleResolutionDownBy:a}=t;this._mediaSettings.videoWidth=n.width/a||0,this._mediaSettings.videoHeight=n.height/a||0,this._mediaSettings.videoFps=n.frameRate||0,this._mediaSettings.videoBps=t.profile.bitrate*1e3,t.small&&(this._mediaSettings.smallVideoWidth=t.small.width,this._mediaSettings.smallVideoHeight=t.small.height,this._mediaSettings.smallVideoFps=t.small.frameRate,this._mediaSettings.smallVideoBps=t.small.bitrate*1e3)}if(r&&r.outMediaTrack){let n=r.outMediaTrack.getSettings(),{scaleResolutionDownBy:a}=r;this._mediaSettings.auxVideoWidth=n.width/a||0,this._mediaSettings.auxVideoHeight=n.height/a||0,this._mediaSettings.auxVideoFps=n.frameRate||0,this._mediaSettings.auxVideoBps=r.profile.bitrate*1e3}}else e&&e.outMediaTrack&&(this._mediaSettings.audioChannel=e.profile.channelCount,this._mediaSettings.audioBps=e.profile.bitrate*1e3,this._mediaSettings.audioFs=e.profile.sampleRate),t&&t.outMediaTrack&&(this._mediaSettings.videoWidth=t.profile.width,this._mediaSettings.videoHeight=t.profile.height,this._mediaSettings.videoFps=t.profile.frameRate,this._mediaSettings.videoBps=t.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:Y.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:F.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return f(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is adding ${e.kind} track to current published local ${t?p.AUXILIARY:p.MAIN} stream`),si()&&(yield this.addTrackByTransceiver(e,t))})}addTrackByTransceiver(e,t){return f(this,null,function*(){var o;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===p.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),n===1&&((o=this.localMainVideoTrack)!=null&&o.small)&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===te.INACTIVE&&(yield this.singlePC.setTransceiverDirection(te.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}removeTrack(e){return f(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${t?p.AUXILIARY:p.MAIN} stream`),si()&&(yield this.removeTrackByTransceiver(e,t))})}removeTrackByTransceiver(e,t){return f(this,null,function*(){if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===p.AUDIO)yield r[0].sender.replaceTrack(null);else{let o=t?3:1;yield r[o].sender.replaceTrack(null),o===1&&this._room.videoManager.hasSmall&&(yield r[2].sender.replaceTrack(null)),yield this.singlePC.setTransceiverDirection(te.INACTIVE,[o])}this.updateMediaSettings(),yield this.doPublishChange()})}replaceTrack(e){return f(this,null,function*(){var n;let t=(n=this._peerConnection)==null?void 0:n.getSenders(),r=e.outMediaTrack||e.mediaTrack;if(!t||t.length===0||!r||t.find(a=>a.track===r))return!1;let o=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info(`is replacing ${r.kind} track ${r.id} ${r.label} on ${o?p.AUXILIARY:p.MAIN} stream`),r.kind===p.AUDIO&&t[0]&&(yield t[0].replaceTrack(r)),r.kind===p.VIDEO&&(!o&&t[1]&&(yield t[1].replaceTrack(r)),o&&t[3]&&(yield t[3].replaceTrack(r))),!0})}setBandwidth(o){return f(this,arguments,function*({bandwidth:e,type:t,videoType:r}){if(this.singlePC){let n={};t===p.AUDIO?n.audio=e:r==="big"?n.bigVideo=e:r==="small"?n.smallVideo=e:n.auxVideo=e,yield this.singlePC.setBandwidth(n)}})}sendMutedFlag(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info(`send muted state: ${JSON.stringify(this.muteState)}`),this._signalChannel.sendWaitForResponseWithRetry({command:Y.UPDATE_MUTE_STAT,responseCommand:F.MUTE_RESULT,data:this.muteState,retries:3}).catch(()=>{}))}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&E.emit(A.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(e=p.VIDEO){if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===p.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===p.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===p.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===p.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===Sr?(this._log.error(Ve.NOT_SUPPORTED_H264ENCODE),new y({code:I.NOT_SUPPORTED_H264,message:x({key:P.NOT_SUPPORTED_H264ENCODE})})):new y({code:I.UNKNOWN,message:x({key:P.SIGNAL_RESPONSE_FAILED,data:{signalResponse:F.PUBLISH_RESULT,code:e,message:t}})})}onSinglePCReconnected(){return f(this,null,function*(){this.isMainStreamPublished&&(this._log.warn("republish main stream"),yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(this._log.warn("republish aux stream"),yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0}))})}};v([et(function({localVideoTrack:e}){e==null||e.once("6",this.onVideoEncodeFailed,this)})],Tn.prototype,"publish",1),v([et(function({localVideoTrack:e}){e==null||e.off("6",this.onVideoEncodeFailed,this)})],Tn.prototype,"unpublish",1);var Wu=Tn;function rf(s){return Object.keys(s).filter(i=>s[i])}var Ys=class extends Kr{constructor(e){super(L(N({},e),{isUplink:!1}));d(this,"_flag",0);d(this,"isRobot",!1);d(this,"role","anchor");d(this,"remoteAudioTrack");d(this,"remoteVideoTrack");d(this,"remoteAuxiliaryTrack");d(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0});d(this,"jitterBufferTimeoutId",-1);this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=new Gt(this._room,this),this.remoteVideoTrack=new fi(this._room,this),this.remoteAuxiliaryTrack=new Bs(this._room,this),this.initialize()}get videoCodec(){var e;return((e=this.singlePC)==null?void 0:e.downlinkVideoCodec)||"h264"}get subscribeState(){return{audio:this.remoteAudioTrack.isSubscribed||this.remoteAudioTrack.isSubscribing,video:this.remoteVideoTrack.isBig&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),smallVideo:this.remoteVideoTrack.isSmall&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),auxiliary:this.remoteAuxiliaryTrack.isSubscribed||this.remoteAuxiliaryTrack.isSubscribing}}get muteState(){return bi(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,r,o;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(r=this.remoteVideoTrack)==null||r.onFlagChanged(),(o=this.remoteAuxiliaryTrack)==null||o.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===p.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){clearTimeout(this.jitterBufferTimeoutId),super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents(),this.removeDownlink()}installEvents(){this.singlePC&&(this.listeners("track").includes(this.onTrack)||this.singlePC.on("track",this.onTrack,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||this.singlePC.on("spc-reconnected",this.onSinglePCReconnected,this))}uninstallEvents(){this.singlePC&&(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this))}emitConnectionStateChangedEvent(e){var o,n;let t=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&t!==e&&((o=this.remoteVideoTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),r}onTrack(e){var u,h;let t=e.streams[0],{track:r,receiver:o}=e;if(!t.id.includes(this.tinyId))return;let a=t.id.includes("aux")?"auxiliary":"main";this._log.debug(`ontrack ${a} ${r.kind}`);let c=p.AUDIO;r.kind===p.VIDEO&&(c=a===p.MAIN?p.VIDEO:p.AUXILIARY);let l=this.remoteAudioTrack;c===p.VIDEO?l=this.remoteVideoTrack:c===p.AUXILIARY&&(l=this.remoteAuxiliaryTrack),(u=this.singlePC)==null||u.receiverRemoteTrackMap.set(o,l),(h=this.singlePC)!=null&&h.scriptTransformWorker&&this.initReceiverTransform(o,a,r.kind===p.AUDIO),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(o),l.setInputMediaStreamTrack(r)}createEncodedStreams(e){if(!this.singlePC.insertableStreamsAbortMap.has(e)){let t=e.createEncodedStreams(),r=new AbortController,o={abortController:r,enqueue:n=>{var c,l;let a=(c=this.singlePC)==null?void 0:c.receiverRemoteTrackMap.get(e);return!a||a.kind==="video"&&!((l=this.singlePC)!=null&&l.isUsingH264)?n:a.decodeFrame(n)}};t.readable.pipeThrough(new TransformStream({transform:(n,a)=>{let c=o.enqueue(n);c&&a.enqueue(c)}})).pipeTo(t.writable,r).catch(n=>{n!=="destory"&&this._log.warn(n)}),this.singlePC.addAbortController(e,r)}}initReceiverTransform(e,t,r){!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker||e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!0,isAudio:r,userId:this.userId,streamType:t}))}subscribe(e,t){return f(this,null,function*(){var r;try{let o=!0;if(this._log.info(`subscribe ${t} ${rf(e)}`),this.hasSSRC){let n="subscribe_change";Object.values(e).find(a=>a===!0)||(n="unsubscribe"),yield this.sendSubscription(n,e)}else{if((r=this.singlePC)!=null&&r.autoSubscribedUserMap.size){let n=this.singlePC.autoSubscribedUserMap.get(this.userId);if(n){this.singlePC.autoSubscribedUserMap.delete(this.userId);let a=this.singlePC.autoSubscribedSsrcGroups[n.groupIndex];a&&(this.ssrc={audio:a.audioSsrc,video:a.bigVideoSsrc,videoRtx:a.bigVideoRtxSsrc,auxiliary:a.auxVideoSsrc,auxiliaryRtx:a.auxVideoRtxSsrc},o=!1)}}yield this.doSubscribe(e,o),this.checkTrackEnded(e)}if(e.smallVideo){let{user:n,mediaTrack:a}=this.remoteVideoTrack;b.addSuccessEvent({key:524702}),this._blackSmallVideoDetectionId=Yi.start({track:a,isUplink:!1,room:this._room,userId:this.userId,onBlack:()=>{this._log.warn("small video is black, auto change to big"),this._room.changeType(!1,n),b.addFailedEvent({key:524702}),Yi.stop(this._blackSmallVideoDetectionId)}})}else Yi.stop(this._blackSmallVideoDetectionId)}catch(o){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${o.message} ${JSON.stringify(this.muteState)}`),new y({code:I.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):o}})}checkTrackEnded(e){var t,r,o;if((e.audio&&((t=this.remoteAudioTrack.mediaTrack)==null?void 0:t.readyState)==="ended"||e.video&&((r=this.remoteVideoTrack.mediaTrack)==null?void 0:r.readyState)==="ended"||e.auxiliary&&((o=this.remoteAuxiliaryTrack.mediaTrack)==null?void 0:o.readState)==="ended")&&this.singlePC&&!this.singlePC.isReconnecting){if(this._log.warn("remote track ended start spc reconnect"),Ze&<<92)return;this.singlePC.startReconnection()}}unsubscribe(r){return f(this,arguments,function*({remoteTracks:e,streamType:t}){var a;if(t==="main"&&!this.isMainStreamSubscribed||t==="auxiliary"&&!this.isAuxStreamSubscribed){this._log.info(`${t} stream already unsubscribed`);return}let o=N({},this.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:o.audio=!1;break;case 4:o.video=!1;break;case 8:o.smallVideo=!1;break;case 2:o.auxiliary=!1;break;default:break}});let n="subscribe_change";Object.values(o).find(c=>c===!0)||(n="unsubscribe"),this._log.info(`${n==="unsubscribe"?n:"subscribe"} ${t} [${rf(o)}]`),n==="unsubscribe"&&((a=this.singlePC)==null||a.removeDownlinkQueue.add(this.tinyId)),yield this.sendSubscription(n,o),t==="main"&&(Yi.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0),n==="unsubscribe"&&(yield this.removeDownlink())})}sendSubscription(e,t=this.subscribeState){let r={srcTinyId:this.tinyId,srcUserId:this.userId},o=Y.UNSUBSCRIBE,n=F.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(r={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},o=Y.SUBSCRIBE_CHANGE,n=F.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponseWithRetry({command:o,data:r,responseCommand:n,timeout:1e4,retries:3}).then(({data:a})=>{if(a.code!==0){let c=new y({code:a.code,message:x({key:P.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(c),c}})}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}setDelay({audioDelay:e,videoDelay:t}){this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=t}onSinglePCReconnected(){return f(this,null,function*(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary)&&(this._log.warn(`resubscribe ${JSON.stringify(this.subscribeState)}`),yield this.doSubscribe(this.subscribeState),this.remoteAudioTrack.checkDecodeResult(),this.remoteVideoTrack.checkDecodeResult(),this.remoteAuxiliaryTrack.checkDecodeResult())})}get hasSSRC(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}doSubscribe(){return f(this,arguments,function*(e=this.subscribeState,t=!0){if(this.singlePC){this.singlePC.addDownlinkQueue.add(this.tinyId),yield this.singlePC.waitForPeerConnectionConnected();try{if(t||!this.hasSSRC){let r={audioSsrc:Et(),bigVideoSsrc:Et(),bigVideoRtxSsrc:Et(),auxVideoSsrc:Et(),auxVideoRtxSsrc:Et()},{audioSsrc:o,bigVideoSsrc:n,bigVideoRtxSsrc:a,auxVideoSsrc:c,auxVideoRtxSsrc:l}=r;this.ssrc={audio:o,video:n,videoRtx:a,auxiliary:c,auxiliaryRtx:l},this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc});try{let u=yield this._signalChannel.sendWaitForResponseWithRetry({command:Y.SPC_SUBSCRIBE,responseCommand:F.SPC_SUBSCRIBE_RESULT,data:{srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo,customData:!1,ssrc:r},retries:3,retryTimeout:0});if(u.data.code!==0&&u.data.code!==-10036)throw new y({code:u.data.code,message:u.data.message})}catch(u){throw yield this.removeDownlink(),u}return}this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc})}finally{if(!ga)return;let{main:r,aux:o}=this._room.jitterBufferDelay||{},{jitterDelay:n=r,jitterDelayAux:a=o}=this._room.scheduleResult.config||{};(q(n)||q(a))&&this.setJitterBufferDelay({mainDelay:n,auxDelay:a})}}})}removeDownlink(){return f(this,null,function*(){if(!this.singlePC)return;this.ssrc={audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0},this.singlePC.removeDownlinkQueue.delete(this.tinyId);let e=this._room.scheduleResult.config;(e!=null&&e.jitterDelay||e!=null&&e.jitterDelayAux)&&this.setJitterBufferDelay({mainDelay:0,auxDelay:0}),yield this.singlePC.removeDownlink(this.userId)})}setJitterBufferDelay({mainDelay:e,auxDelay:t}){if(!ga||!this.singlePC||!this._peerConnection||Oi(e)&&Oi(t))return Promise.resolve();this._log.info(`set jitterBuffer main: ${e} aux: ${t}`);let r=this.singlePC.getReceiversByUserId(this.userId);return q(e)&&(this.remoteAudioTrack.jitterBufferDelay=e,this.remoteVideoTrack.jitterBufferDelay=e),q(t)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=t,Oi(e)&&(this.remoteAudioTrack.jitterBufferDelay=t)),new Promise(o=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:o})})}doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:o}){try{if(e===0&&t===0)return r.forEach(a=>a.jitterBufferTarget=0),o();if(r.forEach(a=>{var h;let c=a.track===this.remoteAuxiliaryTrack.outMediaTrack||Oi(e)&&a.track===this.remoteAudioTrack.outMediaTrack;if(c&&Oi(t)||!c&&Oi(e))return;let l=c?t||0:e,u=(a.jitterBufferTarget||0)+100;u>l||(a.jitterBufferTarget=u,this._log.debug(`set ${c?"aux ":""}${(h=a==null?void 0:a.track)==null?void 0:h.kind} jitterBuffer delay ${u} -> ${l}`))}),!r.find(a=>{let c=a.track===this.remoteAuxiliaryTrack.outMediaTrack?t||0:e;return a.jitterBufferTarget<c}))return this._log.info(`set jitterBuffer main: ${e} aux: ${t} done`),o();this.jitterBufferTimeoutId=setTimeout(()=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:o})},1e3)}catch(n){this._log.warn(`set jitterBuffer delay error: ${n}`),clearTimeout(this.jitterBufferTimeoutId),o()}}get audioReceiver(){var e;return((e=this.singlePC)==null?void 0:e.getReceiversByUserId(this.userId)[0])||null}};v([Rt(),Q(e=>function(...t){return new Promise((r,o)=>{let n=a=>{this.off("closed",n),o(new y({code:I.API_CALL_ABORTED,message:x({key:P.CONNECTION_ABORTED,data:a})}))};this.on("closed",n),e.apply(this,t).then(r,o).finally(()=>{this.off("closed",n)})})})],Ys.prototype,"subscribe",1),v([Rt()],Ys.prototype,"unsubscribe",1),v([$i(()=>"jitter")],Ys.prototype,"setJitterBufferDelay",1);var sf=Ys;function of(){return Q(s=>function(...i){return f(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(i=i.filter(t=>t.outMediaTrack&&t.state==="ready"),!i.length))return;E.emit("61",{room:this});let e=s.apply(this,i);return i.forEach(t=>t.publish(this,e)),e})})}function nf(){return Q(s=>function(...i){let e=s.apply(this,i);return i.forEach(t=>t.unpublish()),e})}var af=$e(Ye());function yE(){return Math.floor(Math.random()*16383)}var xc=class xc extends af.EventEmitter{constructor(e,t){super();this.room=e;this.signalChannel=t;d(this,"log");d(this,"cmdIdSeqMap",new Map);d(this,"messageMap",new Map);this.log=C.createLogger({id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),t.on(F.RECEIVE_CUSTOM_MSG,this.onReceiveMsg),this.room.on("peer-leave",r=>{[...this.messageMap.keys()].forEach(o=>{o.split("_").slice(0,-1).join("_")===r&&this.messageMap.delete(o)})})}send({cmdId:e,data:t}){let r=this.cmdIdSeqMap.get(e)||yE(),o={cmdId:e,msg:btoa(String.fromCharCode(...new Uint8Array(t))),ordered:!0,reliable:!0,streamSeq:r};this.cmdIdSeqMap.set(e,r+1),this.signalChannel.send(Y.SEND_CUSTOM_MSG,o),this.log.debug(`send custom msg: ${JSON.stringify(o)}`)}onReceiveMsg(e){let{data:t}=e.data,r=this.room.tinyIdToUserIdMap.get(t.srcTinyId);if(r){let o={userId:r,cmdId:t.cmdId,seq:t.streamSeq,data:Uint8Array.from(atob(t.msg),n=>n.charCodeAt(0)).buffer};if(t.ordered){let n=`${r}_${o.cmdId}`,a=this.messageMap.get(n);if(!a||a.lastSeq===0)a||(a={lastSeq:0,cachedMessageMap:new Map},this.messageMap.set(n,a),setTimeout(()=>this.emitMessage(o,!0),100)),a.cachedMessageMap.set(o.seq,{message:o});else if(Math.abs(a.lastSeq-o.seq)>xc.SEQ_INTERVAL)this.messageMap.set(n,{lastSeq:o.seq,cachedMessageMap:new Map}),this.emitMessage(o);else if(o.seq>a.lastSeq){if(o.seq===a.lastSeq+1)this.emitMessage(o);else if(!a.cachedMessageMap.has(o.seq)){let c=setTimeout(()=>this.emitMessage(o,!0),5e3);a.cachedMessageMap.set(o.seq,{message:o,timeoutId:c})}}else this.log.debug(`drop message ${o.userId}-${o.cmdId}-${o.seq}`)}else this.emit("message",o)}else{this.log.warn(`receive msg from unknown user, wait peer-join tinyId: ${t.srcTinyId}`);let o=n=>{n.tinyId===t.srcTinyId&&(this.room.off("peer-join",o),this.onReceiveMsg(e))};this.room.on("peer-join",o),Ni(2e3).then(()=>this.room.off("peer-join",o))}}emitMessage(e,t=!1){var a;let r=this.messageMap.get(`${e.userId}_${e.cmdId}`),o=e;if(r){if(t){let c=[...r.cachedMessageMap.values()].sort((l,u)=>l.message.seq-u.message.seq);c[0]&&(o=c[0].message)}r.lastSeq!==0&&o.seq-r.lastSeq>1&&this.log.debug(`msg lost userId: ${o.userId} seq: ${r.lastSeq} -> ${o.seq}`),r.lastSeq=o.seq,clearTimeout((a=r.cachedMessageMap.get(o.seq))==null?void 0:a.timeoutId),r.cachedMessageMap.delete(o.seq)}this.log.debug(`receive custom msg: ${JSON.stringify(o)}`),this.emit("message",o);let n=r==null?void 0:r.cachedMessageMap.get(o.seq+1);n&&this.emitMessage(n.message)}};d(xc,"SEQ_INTERVAL",300);var Pc=xc;var{isString:cf,isUndefined:gr,getNetworkType:bE,isEmpty:En}=dt,jt=class extends Mc{constructor(e){super(e);d(this,"_businessInfo");d(this,"userManager");d(this,"_version");d(this,"_heartbeat",-1);d(this,"_lastHeartBeatTime",-1);d(this,"_stats");d(this,"_joinTimeout",-1);d(this,"_firstPublishedList",null);d(this,"_joinReject",null);d(this,"_isRelayChanged",!1);d(this,"sdpSemantics");d(this,"signalChannel",null);d(this,"uplinkConnection",null);d(this,"singlePC",null);d(this,"enableSPC",bs);d(this,"_changeBigSmallRecords",new Map);d(this,"networkQuality");d(this,"_iceTransportPolicy");d(this,"forceRelay",!1);d(this,"_turnServers",[]);d(this,"_iceServersFromJoin");d(this,"_syncUserListInterval",-1);d(this,"_smallStreamConfig",{bitrate:100,frameRate:15,height:120,width:160});d(this,"enableSEI",!1);d(this,"_enableAudioVolumeEvaluation",!1);d(this,"_audioVolumeIntervalId",0);d(this,"_enableMultiAuxStream",!1);d(this,"_pureAudioPushMode",!1);d(this,"_customMessageManager");d(this,"preferHW",!1);d(this,"healthDetector");d(this,"playoutDelay");d(this,"jitterBufferDelay");d(this,"_updateAudioLevelTaskId",-1);this._stats=new pn(this,this._log),this.userManager=new tc(this.userId,this._log),this._version=Pe,this.sdpSemantics=is,gr(e.sdpSemantics)?ni.isUnifiedPlanDefault()&&(this.sdpSemantics=rr):this.sdpSemantics=e.sdpSemantics,this._log.info(`sdpSemantics: ${this.sdpSemantics}, netType: ${bE()}`),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=gr(e.enableMultiAuxStream)?!1:e.enableMultiAuxStream,this.enableSEI=e.enableSEI&&bs,!gr(e.enableSPC)&&bs&&(this.enableSPC=e.enableSPC),this.preferHW=!!e.preferHW,this._initBusinessInfo(e),this.healthDetector=new jp(this)}get isMainStreamPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.isMainStreamPublished)}get isMainAudioPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.localMainAudioTrack)}get isAuxStreamPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.isAuxStreamPublished)}get hasAuxStream(){return[...this.remotePublishedUserMap.values()].findIndex(e=>e.muteState.hasAuxiliary)>=0}get userMap(){return this.userManager.userMap}get remotePublishedUserMap(){return this.userManager.remotePublishedUserMap}get tinyIdToUserIdMap(){return new Map([...this.userMap.values()].map(e=>[e.tinyId,e.userId]))}join(e,t,r){return f(this,null,function*(){return this.userManager.mySelfId=this.userId,this.userManager.on("1",o=>{this.emit("peer-join",o)}),this.userManager.on("2",o=>{this.closeDownLinkConnection(o,"remote user exitRoom"),this.emit("peer-leave",o)}),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",n=>{var o=Xu(n,[]);E.emit(A.REMOTE_PUBLISH_STATE_CHANGED,N({room:this},o)),this.emit("remote-publish-state-changed",N({},o))}),this.joinParams=e,new Promise((o,n)=>f(this,null,function*(){var a,c;this._joinReject=n;try{this.checkDestroy();try{yield Promise.all([this.initialize(),this.initSinglePC()])}catch(u){if(u instanceof y&&u.code===I.SPC_INITIALIZED_FAILED)(a=this.signalChannel)==null||a.destroy(),yield this.initialize();else return n(u)}let l=w();yield this.doJoin(e,(c=this.singlePC)==null?void 0:c.clientAbility),b.addSuccessEvent({key:521708,cost:w()-l}),o(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(l){b.addFailedEvent({key:521708,error:l}),n(l)}this._joinReject=null}))})}initSinglePC(){return f(this,null,function*(){if(!(!this.enableSPC||this.singlePC)){this.singlePC=new qt({signalChannel:this.signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.on("sei-message",e=>this.emit("sei-message",e)),this.singlePC.on("dump",e=>this.emit("dump",e)),this.singlePC.once("error",()=>this.fallbackToMPC());try{return yield this.singlePC.initialize()}catch(e){throw this.fallbackToMPC(),new y({code:I.SPC_INITIALIZED_FAILED,message:e==null?void 0:e.message})}}})}doJoin(e,t){return new Promise((r,o)=>f(this,null,function*(){var c,l,u;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this.signalChannel.once(Ne.SETUP_FAILED,h=>{this.clearJoinTimeout(),E.emit(A.JOIN_SIGNAL_CONNECTION_END,{room:this,error:h}),o(h)}),me((l=(c=this.scheduleResult)==null?void 0:c.config)==null?void 0:l.singlePC)&&bs&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2),t&&this.playoutDelay&&(t.playoutDelay=this.playoutDelay);let n={roomId:String(e.roomId||e.strRoomId),useStringRoomId:this.useStringRoomId,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel,trtcRole:e.role,trtcScene:this.scene==="live"?2:1,sdpSemantics:this.sdpSemantics,version:this._version,ua:navigator&&navigator.userAgent||"",terminalType:Cd(),netType:Cr(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig,receiveMix:!0};this._log.debug(`join room signal data: ${JSON.stringify(n)}`);let a=5e3;(u=this.scheduleResult.config)!=null&&u.enterRoomTimeout&&this.scheduleResult.config.enterRoomTimeout>=1&&(a=this.scheduleResult.config.enterRoomTimeout*1e3),this._joinTimeout=window.setTimeout(()=>{o(new y({code:I.JOIN_ROOM_FAILED,message:x({key:P.JOIN_ROOM_TIMEOUT})}))},a),E.emit(A.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?Y.SPC_JOIN_ROOM:Y.JOIN_ROOM,n),this.signalChannel.once(F.JOIN_ROOM_RESULT,h=>f(this,null,function*(){this.clearJoinTimeout();let{code:m,message:g,data:D,tinyId:_}=h.data;E.emit(A.JOIN_RECEIVED_CMD_RES,{room:this,code:m}),m===0?(this._log.info("Join room success, start heartbeat"),_&&(this.tinyId=_),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=D.publishers,this._iceServersFromJoin=D.iceServer?[D.iceServer]:[],this.singlePC&&this.singlePC.setIceServers(this.getIceServers()).then(()=>{var S;(S=this.singlePC)==null||S.connect(L(N({},D.ability),{useVp8:D.ability.useVp8||!!e.useVp8})).catch(()=>{})}),r()):(this._log.error(`Join room failed result: ${m} error: ${g}`),o(new y({code:I.JOIN_ROOM_FAILED,extraCode:m,message:x({key:P.JOIN_ROOM_FAILED,data:{error:g,code:m}})})))}))}))}reJoin(){return f(this,null,function*(){if(!this.isJoined){this._log.warn("reJoin abort");return}try{this._log.warn(`reJoin pending: ${this.joinParams.roomId}`);let e,t=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,t.push(this.initSinglePC().then(r=>(e=r,r)))),this.signalChannel&&(this.signalChannel.close(),t.push(this.signalChannel.connect())),yield Promise.all(t),yield this.doJoin(L(N({},this.joinParams),{role:this.role==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),e),this._log.warn("reJoin success"),re.logSuccessEvent({userId:this.userId,eventType:st.REJOIN}),this.singlePC){let r=o=>{var n;o.state==="CONNECTED"&&((n=this.singlePC)==null||n.off(Ti.CONNECTION_STATE_CHANGED,r),this.uplinkConnection instanceof Wu&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach(a=>{a.installEvents(),a.onSinglePCReconnected()}))};this.singlePC.on(Ti.CONNECTION_STATE_CHANGED,r),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof mn&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(e){this._log.warn(`reJoin fail ${e}`),this.reset(),re.logFailedEvent({userId:this.userId,eventType:st.REJOIN,error:e}),this.emit("error",new y({code:I.JOIN_ROOM_FAILED,message:x({key:P.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}})}initialize(){return f(this,null,function*(){let{mainUrl:e,backupUrl:t}=this.getSignalChannelUrl(),r=this.signalChannel||Sp(this.userId),o=!!(r&&r.isConnected&&r.keepAlive&&r.room===this),n;return Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(n=this.scheduleResult.domains[0]),this._log.info(`${o?"reuse":"setup"} signal channel`),o?(r.url=e,r.backupUrl=t,r.room=this,this.signalChannel=r):(r&&r.close(),this.signalChannel=new qs({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:e,backupUrl:t,room:this,signalDomainWhenUnifiedProxy:this.proxy_unified?n:void 0}),this._customMessageManager=new Pc(this,this.signalChannel),this._customMessageManager.on("message",a=>{this.emit("custom-message",a)})),this.networkQuality||(this.networkQuality=new Qs({signalChannel:this.signalChannel,room:this}),this.networkQuality.on(Qs.EVENT_NETWORK_QUALITY,a=>{var c;this.emit("network-quality",a),(c=this.singlePC)==null||c.detectTCPAndUDP(a)})),qe(this,this.signalChannel).add(Ne.CONNECTION_STATE_CHANGED,a=>{E.emit(A.SIGNAL_CONNECTION_STATE_CHANGED,N({room:this},a)),this.emit("signal-connection-state-changed",a)}).add(Ne.RECONNECT_FAILED,a=>{this.reset(),this.emit("error",a)}).add(F.PEER_JOIN,a=>{let{srcTinyId:c,userId:l,role:u}=a.data.data;this.userManager.addUser({userId:l,tinyId:c,role:u})}).add(F.PEER_LEAVE,a=>{let{userId:c,reason:l=0}=a.data.data;this.userManager.deleteUser(c,l)}).add(F.UPDATE_REMOTE_MUTE_STAT,a=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=10*1e3&&this.doHeartbeat(),this.onPublishedUserList(a.data)}).add(F.CLIENT_BANNED,a=>{let c=a.data.data,{reason:l}=c;if(re.uploadEvent({log:`stat-banned:${l}`,userId:this.userId}),l==="user_time_out"){this._log.warn(`${l} last heart beat time: ${this._lastHeartBeatTime} interval: ${Date.now()-this._lastHeartBeatTime}, visibility: ${document.visibilityState}`),this.reJoin();return}this._log[l==="kick"?"error":"info"](`user was banned because of [${l}]`),this.reset(),this.emit("banned",{reason:l})}).add(F.SEND_SWITCH_ROOM_SUBED_REQ,a=>{if(!this.singlePC)return;let{subList:c}=a.data.data;c.forEach(l=>{this.singlePC.autoSubscribedUserMap.set(l.userId,l)})}),this.signalChannel.once(Ne.SETUP_SUCCESS,a=>{this.tinyId=a.signalInfo.tinyId,E.emit(A.JOIN_SIGNAL_CONNECTION_END,{room:this})}),E.emit(A.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),o&&E.emit(A.JOIN_SIGNAL_CONNECTION_END,{room:this}),o})}setSignalChannel(e){this.signalChannel=e,e||ve(this)}leave(){return f(this,null,function*(){var e;try{yield this.doHeartbeat()}catch(t){}this._log.info("leave() => leaving room"),E.emit(A.LEAVE_SEND_CMD,{room:this}),(e=this.signalChannel)==null||e.send(Y.LEAVE_ROOM)})}clearNetworkQuality(){this.networkQuality&&(this.networkQuality.stop(),delete this.networkQuality)}closeConnections(){this.remotePublishedUserMap.forEach(e=>{this.closeDownLinkConnection(e.userId,"you exitRoom")})}clearJoinTimeout(){clearTimeout(this._joinTimeout),this._joinTimeout=-1}startHeartbeat(){this._heartbeat===-1&&(this._heartbeat=oe.run("ric",this.doHeartbeat.bind(this),{delay:2e3}))}stopHeartbeat(){this._heartbeat!==-1&&(this._log.info("stopHeartbeat"),oe.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return f(this,null,function*(){var n;let e=this.badCaseDetector.getMonitorFreeze(),t=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:e});this.badCaseDetector.resetMonitor();let r=(n=this.signalChannel)!=null&&n.isConnected?wm(this.userId):[],o=L(N({str_sdk_version:to,uint64_datetime:new Date().getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_event_msg:r,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},t),{msg_device_info:N({uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:Cr()},t.msg_device_info)});if(this.heartbeatReport=o,E.emit(A.HEARTBEAT_REPORT,{room:this,report:o}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(Y.ON_QUALITY_REPORT,o);let a=Date.now();this._lastHeartBeatTime>0&&a-this._lastHeartBeatTime>1e4&&this._log.warn(`heartbeat took ${a-this._lastHeartBeatTime}`),this._lastHeartBeatTime=a,this.signalChannel.isOnline||(this._log.warn("signal channel is not online"),this.signalChannel.startReconnection())}this.emit("heartbeat-report",L(N({},o),{bytes_sent:this._stats.totalBytesSent+this.signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this.signalChannel.bytesReceived}))}!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)})}onPublishedUserList(e){if(!this.isJoined)return;let t=e.data.userList.filter(r=>r.flag!==Jc).map(({userId:r,srcTinyId:o,flag:n})=>{r===this.userId&&this.uplinkConnection&&(this.uplinkConnection.flag=n);let a=this.remotePublishedUserMap.get(r);return a&&this.checkSubscribeBigSmallVideo(a),{userId:r,tinyId:o,flag:n}});e.data.mixRobotList.forEach(({userId:r,srcTinyId:o,flag:n,mixUserList:a})=>{t.unshift({userId:r,tinyId:o,flag:n,isRobot:!0,mixUserList:a})}),E.emit(A.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:t}),this.userManager.setRemotePublishedUserList(t)}closeUplink(e="you unpublished"){this.uplinkConnection&&(this.localTracks.size>0&&this.uplinkConnection.doUnpublish(),this.uplinkConnection.close(e),this.uplinkConnection instanceof mn&&(this.uplinkConnection=null)),this.localTracks.forEach(t=>t.unpublish()),this.localTracks.clear()}createDownlinkConnection({userId:e,tinyId:t,flag:r,isRobot:o}){let n=new(this.singlePC?sf:ku)({userId:e,tinyId:t,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:r,isRobot:o});this.userManager.addRemotePublishedUser(n),this.installDownlinkEvents(n,e),this.emit("remote-published",n)}closeDownLinkConnection(e,t="remote user unpublished"){let r=this.remotePublishedUserMap.get(e);r&&(r.close(t),this.emit("remote-unpublished",r))}installDownlinkEvents(e,t){e.on("error",r=>{let o=r.getCode();o!==I.ICE_TRANSPORT_ERROR&&(o===I.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",r))}),e.on("connection-state-changed",r=>{this.emit("media-connection-state-changed",L(N({},r),{userId:e.userId}))}),e.on("firewall-restriction",()=>{this.emit("firewall-restriction")})}startSyncUserListInterval(){this._syncUserListInterval===-1&&(this._syncUserListInterval=oe.run("ric",this.syncUserList.bind(this)))}stopSyncUserListInterval(){oe.clearTask(this._syncUserListInterval),this._syncUserListInterval=-1}syncUserList(){return this.getUserList().then(e=>{this.userManager.setUserList(e)}).catch(e=>{this._log.debug(`sync user list failed: ${e}`)})}getUserList(){var e;return(e=this.signalChannel)!=null&&e.isConnected?this.signalChannel.sendWaitForResponse({command:Y.GET_USER_LIST,responseCommand:F.USER_LIST_RES,enableLog:!1,timeout:2e3}).then(({data:t})=>{let{code:r,message:o}=t;if(r===0)return(t.data&&t.data.userList||[]).map(({userId:a,srcTinyId:c,role:l})=>({userId:a,tinyId:c,role:l}));throw x({key:P.SIGNAL_RESPONSE_FAILED,data:{signalResponse:F.USER_LIST_RES,code:r,message:o}})}):Promise.reject("not connected")}getAllConnections(){let e=[...this.remotePublishedUserMap.values()];return this.uplinkConnection&&e.push(this.uplinkConnection),e}isRelayMaybeFailed(){if(this.signalChannel&&!this.signalChannel.isOnline||!bu)return!1;if(this.singlePC)return this.singlePC.reconnectionCount>6;let e=this.getAllConnections();if(e.length===0)return!1;for(let t=0;t<e.length;t++)if(e[t].getReconnectionCount()<6)return!1;return!0}checkConnectionsToReconnect(){var e;this.singlePC?((e=this.singlePC.getPeerConnection())==null?void 0:e.connectionState)===ge.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach(r=>{if(r instanceof rt&&!r.getIsReconnecting()){let o=r.getPeerConnection();o&&o.connectionState===ge.CLOSED&&(this._log.warn(`[${r.getUserId()}] pc is closed but not reconnect`),r.startReconnection())}})}fallbackToMPC(){return f(this,null,function*(){var e;if(this._log.warn("fallback to multi pc"),re.uploadEvent({log:"stat-fallback",userId:this.userId}),this.enableSPC=!1,(e=this.singlePC)==null||e.close(),this.singlePC=null,this.isJoined&&(yield this.reJoin()),this.uplinkConnection){let t=this.uplinkConnection;this.uplinkConnection=new mn({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),t.isMainStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:t.localMainAudioTrack,localVideoTrack:t.localMainVideoTrack,isAuxiliary:!1})),t.isAuxStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:t.localAuxAudioTrack,localVideoTrack:t.localAuxVideoTrack,isAuxiliary:!0})),t.close()}for(let t of[...this.remotePublishedUserMap.values()]){let r=new ku({userId:t.userId,tinyId:t.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:t.flag,remoteAudioTrack:t.remoteAudioTrack,remoteVideoTrack:t.remoteVideoTrack,remoteAuxiliaryTrack:t.remoteAuxiliaryTrack});this.installDownlinkEvents(r,t.userId),this.remotePublishedUserMap.set(t.userId,r),t.isMainStreamSubscribed&&(yield r.subscribe(t.subscribeState,"main")),t.isAuxStreamSubscribed&&(yield r.subscribe(t.subscribeState,"auxiliary"))}})}destroy(){this.isDestroyed||(this.signalChannel&&(this._log.info("destroying SignalChannel"),this.signalChannel.close(),this.signalChannel=null),super.destroy(),this._joinReject&&(this._joinReject(new y({code:I.INVALID_OPERATION,message:x({key:P.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners(),this.healthDetector.destroy(),oe.clearTask(this._audioVolumeIntervalId))}switchRole(e){return f(this,null,function*(){this.role!==e&&(e==="audience"&&this.uplinkConnection&&this.closeUplink("you switch role to audience"),yield this.doSwitchRole(e))})}doSwitchRole(e){let t={command:Y.SWITCH_ROLE,data:{role:e==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:F.SWITCH_ROLE_RES,retries:1};return this._log.info(`switchRole signal data: ${JSON.stringify(t.data)}`),this.signalChannel.sendWaitForResponseWithRetry(t).then(r=>{let{code:o,message:n}=r.data;if(o!==0)throw new y({code:I.SWITCH_ROLE_FAILED,message:x({key:P.SWITCH_ROLE_FAILED,data:{message:n,code:o}})});this.role=e}).catch(r=>{throw r instanceof y&&r.getCode()===I.API_CALL_TIMEOUT&&(r=new y({code:I.SWITCH_ROLE_FAILED,message:x({key:P.SWITCH_ROLE_TIMEOUT})})),this._log.error(r),r})}publish(...e){return f(this,null,function*(){let t={},r={};e.forEach(c=>{c instanceof Tt&&(c instanceof hi?r.audio=c:t.audio=c),c instanceof je&&(c instanceof ct&&c.mediaType===2?r.video=c:t.video=c)});let o=En(t),n=En(r);(!o||!n)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new Wu({userId:this.userId,tinyId:this.tinyId,room:this}):this.uplinkConnection=new mn({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),this.uplinkConnection.on("connection-state-changed",c=>{this.emit("media-connection-state-changed",L(N({},c),{userId:this.userId}))}),this.uplinkConnection.on("firewall-restriction",()=>{this.emit("firewall-restriction")}),this.uplinkConnection.on("error",c=>{let l=c.getCode();l!==I.ICE_TRANSPORT_ERROR&&(l===I.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",c))}));let a=e.map(c=>c.kind).join(",");o||(this._log.info(`publish() => main ${a}`),yield this.uplinkConnection.publish({localAudioTrack:t.audio,localVideoTrack:t.video,isAuxiliary:!1}),this._log.info("main is published")),n||(this._log.info(`publish() => aux ${a}`),yield this.uplinkConnection.publish({localAudioTrack:r.audio,localVideoTrack:r.video,isAuxiliary:!0}),this._log.info("aux is published"))})}unpublish(...e){return f(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||!this.isMainStreamPublished&&!this.isAuxStreamPublished||!this.uplinkConnection)return;let t={},r={};e.forEach(o=>{!o.mediaTrack||!o.isPublished||(o instanceof Tt&&(o instanceof hi?r.audio=o:t.audio=o),o instanceof je&&(o instanceof ct&&o.mediaType===2?r.video=o:t.video=o))});try{let o=e.map(n=>n.kind).join(",");En(t)||(this._log.info(`unpublish() => main ${o}`),yield this.uplinkConnection.unpublish({localAudioTrack:t.audio,localVideoTrack:t.video})),En(r)||(this._log.info(`unpublish() => aux ${o}`),yield this.uplinkConnection.unpublish({localAudioTrack:r.audio,localVideoTrack:r.video}))}catch(o){}this.localTracks.size===0&&this.closeUplink("you unpublished")})}addTrack(e){if(!this.uplinkConnection||!e.mediaTrack)return Promise.resolve();let t=this.uplinkConnection.addTrack(e);return e.publish(this,t),t}removeTrack(e){return!this.uplinkConnection||!e.mediaTrack?Promise.resolve():this.uplinkConnection.removeTrack(e).then(t=>(e.unpublish(),t))}replaceTrack(e){return!this.uplinkConnection||!e.mediaTrack||!qd()?Promise.resolve():this.uplinkConnection.replaceTrack(e).then(t=>{t&&E.emit(A.LOCAL_TRACK_REPLACED,{track:e})})}setBandWidth(e){return f(this,null,function*(){this.uplinkConnection&&(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())})}enableSmall(e){return f(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:p.VIDEO,videoType:p.SMALL,bandwidth:this.uplinkConnection.localMainVideoTrack.small.bitrate})),yield this.uplinkConnection.enableSmall(e)})}subscribe(...e){return f(this,null,function*(){if(e=e.filter(n=>!n.isSubscribed),e.length===0)return;let{userId:t}=e[0],r=this.remotePublishedUserMap.get(t);if(!r)return;let o=e.find(n=>n.mediaType===2)?"auxiliary":"main";try{let n=N({},r.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:n.audio=!0;break;case 4:n.video=!0;break;case 8:n.smallVideo=!0;break;case 2:n.auxiliary=!0;break}});let a=this._changeBigSmallRecords.get(t);a&&a.options.smallVideo&&r.muteState.hasSmall&&n.video&&(n.video=!1,n.smallVideo=!0),E.emit(A.SUBSCRIBE_START,{room:this,streamType:o,remotePublishedUser:r,subscribeState:n}),this._log.info(`subscribe() => ${t} ${o} [${Rc(n)}] prev: [${Rc(r.subscribeState)}]`),yield r.subscribe(n,o),this._log.info(`subscribe ${t} ${o} done`);for(let c of e)c.mediaTrack||(yield c.waitHasMediaTrack());E.emit(A.SUBSCRIBE_SUCCESS,{room:this,streamType:o,remotePublishedUser:r})}catch(n){let a=n instanceof y?n.getCode():I.UNKNOWN,c=n;throw n instanceof y?a===I.REMOTE_STREAM_NOT_EXIST&&(c=new y({code:I.API_CALL_ABORTED,message:x({key:P.API_CALL_ABORTED,data:{message:n.message,userId:t,streamType:o}})}),this._log.warn(c)):(c=new y({code:a,message:x({key:P.SUBSCRIBE_FAILED,data:{message:n.message,userId:t,streamType:o}})}),this._log.error(c)),c}})}unsubscribe(...e){return f(this,null,function*(){let{userId:t}=e[0],r=this.remotePublishedUserMap.get(t);if(!r)return;let o=e.find(n=>n.mediaType===2)?"auxiliary":"main";this._log.info(`unsubscribe() => ${t} ${o}`);try{yield r.unsubscribe({remoteTracks:e,streamType:o})}catch(n){this._log.warn(`unsubscribe() => failed ${n}`)}e.forEach(n=>{n.unsubscribe(),n.mediaType===8&&n.setMediaType(4)}),E.emit(A.UNSUBSCRIBE_SUCCESS,{room:this,streamType:o,remotePublishedUser:r})})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAudioVolumeEvaluation(e=2e3,t){if(e<=0){this._enableAudioVolumeEvaluation=!1,oe.clearTask(this._audioVolumeIntervalId);return}e=Math.floor(Math.max(e,100)),E.emit(A.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&oe.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=oe.run("intervalInWorker",()=>{var o;Ur.isRunning?this.stopUpdateAudioLevelFromSenderStat():this.updateAudioLevelFromSenderStat(e,t);let r=[];(o=this.remotePublishedUserMap)==null||o.forEach(n=>{if(n.muteState.hasAudio){!Ur.isRunning&&n.muteState.audioAvailable&&n.remoteAudioTrack.isSubscribed?this.updateDownlinkAudioLevelFromReceiver(n):n.remoteAudioTrack.volume=0;let a=Math.floor(n.remoteAudioTrack.getAudioLevel()*100);r.push({userId:n.userId,volume:a})}}),this.emit("audio-volume",r)},{delay:e,backgroundTask:t})}updateAudioLevelFromSenderStat(e,t){return f(this,null,function*(){var n;if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack||this._updateAudioLevelTaskId!==-1)return;let r=(n=this.uplinkConnection.getPeerConnection())==null?void 0:n.getSenders()[0];if(!r)return;let o=Math.max(e,500);this._log.warn(`updateAudioLevelFromSenderStat ${o}`),this._updateAudioLevelTaskId=oe.run("intervalInWorker",()=>f(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack){this.stopUpdateAudioLevelFromSenderStat();return}let a=yield r.getStats();if(this._updateAudioLevelTaskId<0)return;let{localMainAudioTrack:c}=this.uplinkConnection;a.forEach(l=>{l.type==="media-source"&&l.audioLevel&&(c.volume=l.audioLevel)})}),{delay:o,backgroundTask:t})})}stopUpdateAudioLevelFromSenderStat(){var e;this._updateAudioLevelTaskId!==-1&&(this._log.warn("stopUpdateAudioLevelFromSenderStat"),oe.clearTask(this._updateAudioLevelTaskId),this._updateAudioLevelTaskId=-1,(e=this.uplinkConnection)!=null&&e.localMainAudioTrack&&(this.uplinkConnection.localMainAudioTrack.volume=0))}updateDownlinkAudioLevelFromReceiver(e){var o;let{audioReceiver:t}=e;if(!jd||!t)return;let r=(o=t.getSynchronizationSources()[0])==null?void 0:o.audioLevel;q(r)?e.remoteAudioTrack.volume=Math.min(r*2,1):t.getStats().then(n=>{n.forEach(a=>{a.type==="inbound-rtp"&&q(a.audioLevel)&&(e.remoteAudioTrack.volume=a.audioLevel)})})}getLocalAudioStats(){return f(this,null,function*(){var t;let e={};return e[this.userId]={bytesSent:0,packetsSent:0,audioLevel:0},(t=this.uplinkConnection)!=null&&t.localMainAudioTrack&&(e[this.userId]=this.uplinkConnection.localMainAudioTrack.stat),e})}getLocalVideoStats(){return f(this,null,function*(){var t,r;let e={};return e[this.userId]=((r=(t=this.uplinkConnection)==null?void 0:t.localMainVideoTrack)==null?void 0:r.stat)||{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0},e})}getTransportStats(){return f(this,null,function*(){let e={rtt:0,downlinksRTT:{}};if(this.uplinkConnection){let t=yield this._stats.getSenderStats(this.uplinkConnection);e.rtt=t.rtt}for(let[,t]of this.remotePublishedUserMap){let r=yield this._stats.getReceiverStats(t);e.downlinksRTT[r.userId]=r.rtt}return e})}getRemoteVideoStats(e){return f(this,null,function*(){let t={};for(let[r,o]of this.remotePublishedUserMap)e==="main"&&o.muteState.hasVideo&&(t[r]=o.remoteVideoTrack.stat),e==="auxiliary"&&o.muteState.hasAuxiliary&&(t[r]=o.remoteAuxiliaryTrack.stat);return t})}getRemoteAudioStats(){return f(this,null,function*(){let e={};for(let[t,r]of this.remotePublishedUserMap)r.muteState.hasAudio&&(e[t]=r.remoteAudioTrack.stat);return e})}setTurnServer(e,t){this._log.info(`set turn server: ${JSON.stringify(e)} ${t||""}`);let r=[];Array.isArray(e)?e.forEach(o=>r.push(dt.getTurnServer(o))):dt.isPlainObject(e)&&r.push(dt.getTurnServer(e)),this._turnServers=r,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:Y.START_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:F.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:Y.STOP_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:F.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"})}sendStartPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?Y.START_PUBLISH_TENCENT_CDN:Y.START_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?F.START_PUBLISH_TENCENT_CDN_RES:F.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"})}sendStopPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?Y.STOP_PUBLISH_TENCENT_CDN:Y.STOP_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?F.STOP_PUBLISH_TENCENT_CDN_RES:F.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}sendStartPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Y.START_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:F.START_PUBLISH_CDN_STREAM_RES,commandDesc:"startPublishCDNStream"})}sendUpdatePushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Y.UPDATE_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:F.UPDATE_PUBLISH_CDN_STREAM_RES,commandDesc:"updatePublishCDNStream"})}sendStopPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Y.STOP_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:F.STOP_PUBLISH_CDN_STREAM_RES,commandDesc:"stopPublishCDNStream"})}sendAbilityStatus(e){var t;(t=this.signalChannel)==null||t.sendWaitForResponse({command:Y.ABILITY_STATUS_REPORT,data:e,timeout:5e3,responseCommand:F.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch(r=>{})}getIceServers(e){var t,r;return this._turnServers.length>0?this._turnServers:(t=this.scheduleResult.iceServers)!=null&&t.length?this.scheduleResult.iceServers:e!=null&&e.length?e:(r=this._iceServersFromJoin)!=null&&r.length?this._iceServersFromJoin:[]}getIceTransportPolicy(){return this.forceRelay?"relay":this._iceTransportPolicy||this.scheduleResult.iceTransportPolicy||"all"}getLogger(){return this._log}enableAIVoice(){throw new Error("Method not implemented.")}getSignalChannelUrl(){let e={mainUrl:"",backupUrl:""},t=dt.getEnv();return t?(e.mainUrl=`wss://${t}.rtc.qq.com`,e.backupUrl=e.mainUrl):this.proxy_ws?(e.mainUrl=this.proxy_ws,e.backupUrl=e.mainUrl):this.proxy_unified?(e.mainUrl=`wss://${this.proxy_unified}`,e.backupUrl=e.mainUrl):Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(e.mainUrl=`wss://${this.scheduleResult.domains[0]}`,e.backupUrl=e.mainUrl,this.scheduleResult.domains[1]&&(e.backupUrl=`wss://${this.scheduleResult.domains[1]}`)),e}getSignalInfo(){var e;return((e=this.signalChannel)==null?void 0:e.getSignalInfo())||{clientIp:"",relayIp:""}}reset(e=!1){this.stopSyncUserListInterval(),this.stopHeartbeat(),this.closeConnections(),this.clearNetworkQuality(),this.closeUplink("you exitRoom"),this.signalChannel&&(e&&this.signalChannel.keepAlive&&this.signalChannel.isConnected?this.signalChannel.stopKeepAliveIn(3600):(this.signalChannel.close(),this.setSignalChannel(null))),this._stats.reset(),this.userManager.clear(),this.userManager.removeAllListeners(),this.singlePC&&(this.singlePC.close(),this.singlePC=null),this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}}checkSubscribeBigSmallVideo(e){return f(this,null,function*(){let{subscribeState:t,userId:r,muteState:{hasSmall:o,hasVideo:n}}=e;if(!o&&!n||!t.video&&!t.smallVideo)return;let a=this._changeBigSmallRecords.get(r);if(!a||a.isSubscribing||a.reSubscribeCount<=0)return;let{options:c,reSubscribeCount:l}=a;if(c.video&&t.video||c.smallVideo&&t.smallVideo&&o)return;let u={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:c.video,smallVideo:c.smallVideo};try{if(!o&&u.smallVideo&&(u.video=!0,u.smallVideo=!1),u.smallVideo===t.smallVideo&&u.video===t.video)return;a.isSubscribing=!0,a.reSubscribeCount=l-1,yield e.subscribe(u,"main"),e.remoteVideoTrack.setMediaType(u.smallVideo?8:4),this._log.info(`change [${r}] to ${u.smallVideo?"small":"big"} video successfully. count ${rs-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount=rs}catch(h){this._log.info(`change [${r}] to ${u.smallVideo?"small":"big"} video failed. count ${rs-a.reSubscribeCount}. reason: ${h}`),a.isSubscribing=!1,a.reSubscribeCount===0&&this._changeBigSmallRecords.delete(r)}})}changeType(e,t){let o={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:rs};this._changeBigSmallRecords.set(t.userId,o),this._log.info(`set [${t.userId}] video prefer type: ${e?"small":"big"}`),this.emit("subscribe-small-video-changed",{userId:t.userId,isSmall:e});let n=this.remotePublishedUserMap.get(t.userId);n&&this.checkSubscribeBigSmallVideo(n)}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(e){this._businessInfo=e.businessInfo;let t={};if(cf(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!gr(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PURE_AUDIO})});this._pureAudioPushMode=e.pureAudioPushMode,t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.pure_audio_push_mod=this._pureAudioPushMode}if(!gr(e.userDefineRecordId)){let r=/^[A-Za-z0-9_-]{1,64}$/gi;if(e.userDefineRecordId.match(r)===null)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!gr(e.userDefinePushArgs))if(cf(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256)t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_push_args=e.userDefinePushArgs;else throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_USER_DEFINE_PUSH_ARGS})});En(t)||(this._businessInfo=JSON.stringify(t))}sendCustomMessage(e){var t;(t=this._customMessageManager)==null||t.send(e)}enableInsertableStreams(){return f(this,null,function*(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&Ui)return this.singlePC.enableInsertableStreams=!0,yield this.singlePC.waitForPeerConnectionConnected(),yield this.singlePC.startReconnection()})}sendSignalMessage(e){var t;return this.signalChannel?(t=this.signalChannel)==null?void 0:t.sendWaitForResponseWithRetry(e):Promise.reject(new y({code:I.INVALID_OPERATION,message:"not join"}))}get enableCodecPipeline(){return this.videoManager.encodePipeline.length>0||this.videoManager.decodePipeline.length>0||this.audioManager.encodePipeline.length>0||this.audioManager.decodePipeline.length>0}get scriptTransformWorker(){var e;return(e=this.singlePC)==null?void 0:e.scriptTransformWorker}switchRoom(e){return f(this,null,function*(){var D,_;if(!this.signalChannel)return;let{roomId:t,strRoomId:r,userSig:o,privateMapKey:n}=e,a=((D=this.scheduleResult.config)==null?void 0:D.autoSubscribeCount)||(e==null?void 0:e.autoSubscribeCount)||1,c=String(this.useStringRoomId?r:t),l=[];for(let S=0;S<a;S++)l.push({audioSsrc:Et(),bigVideoSsrc:Et(),bigVideoRtxSsrc:Et(),auxVideoSsrc:Et(),auxVideoRtxSsrc:Et()});let u={currRoomId:this.roomId,targetRoomId:c,useStringRoomId:this.useStringRoomId,ability:(_=this.singlePC)==null?void 0:_.clientAbility,userSig:o!=null?o:this.userSig,privateMapKey:n!=null?n:this.privateMapKey,subscribe:l};this.singlePC&&(this.singlePC.autoSubscribedSsrcGroups=l,this.singlePC.autoSubscribedUserMap.clear()),E.emit(A.SWITCH_ROOM_START,{room:this});let h=yield this.signalChannel.sendWaitForResponse({command:Y.SWITCH_ROOM,responseCommand:F.SEND_SWITCH_ROOM_RES,data:u}),{code:m,message:g}=h.data;if(m===0){let S=this.roomId;this.roomId=this.useStringRoomId?r:String(t),gr(o)||(this.userSig=o),gr(n)||(this.privateMapKey=n),E.emit(A.SWITCH_ROOM_SUCCESS,{room:this,currentRoomId:S,targetRoomId:c})}else{this._log.error(`switch room failed. result: ${m} error: ${g}`),this.singlePC&&(this.singlePC.autoSubscribedSsrcGroups=[]);let S=new y({code:I.SWITCH_ROOM_FAILED,extraCode:m,message:g});throw E.emit(A.SWITCH_ROOM_FAILED,{room:this,error:S}),S}})}isSwitchRoomSupported(){var t;let e="unable to use switchRoom API, fallback to exitRoom and enterRoom.";return((t=this.scheduleResult.config)==null?void 0:t.switchRoom)!==!0?(this._log.warn(`${e} Reason: this sdkAppId is not supported, please contact us [https://trtc.io/contact] to enable it.`),!1):this.scene!=="live"?(this._log.warn(`${e} Reason: the scene is not 'live'.`),!1):this.role!=="audience"?(this._log.warn(`${e} Reason: the role is not 'audience'.`),!1):this.singlePC?!0:(this._log.warn(`${e} Reason: is not using single peerConnection.`),!1)}};v([Te(["left",H.INIT],"joined"),pt({settings:{retries:1,timeout:0},onRetrying(e){this._log.warn(`join retry ${e}`)},onRetryFailed(e){this._log.error("join failed",e)},onError(e,t){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),Wt(!0),this.reset(),t()):this.signalChannel&&this.signalChannel.isConnected&&this.signalChannel.keepAlive?(this._log.warn("is using keepAlive ws, retry join"),this.signalChannel.close(),this.reset(),t()):(this.reset(),t())}}),fp()],jt.prototype,"join",1),v([Te("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),_p(),xa("leave room"),Ho({fnName:"publish",validateArgs:!1}),Ho({fnName:"unsubscribe",validateArgs:!1})],jt.prototype,"leave",1),v([Rt(),of(),pt({settings:{retries:Ai,timeout:e=>Pt(e)},onError(e,t,r){var o;(o=e.message)!=null&&o.includes("timeout")?(this._log.warn("publish timeout"),t()):(this._log.error(`publish failed: ${e}`),r(e),E.emit(A.PUBLISH_FAILED,{room:this}))}})],jt.prototype,"publish",1),v([Ho({fnName:"publish"}),Rm("api-call"),Rt(),nf(),et(function(){var e,t;this.localTracks.size===0&&dr()&&((t=(e=this.singlePC)==null?void 0:e.getPeerConnection())==null||t.getSenders().forEach(r=>r.track&&r.replaceTrack(null)))})],jt.prototype,"unpublish",1),v([Ma(e=>{if(e.code!==I.API_CALL_ABORTED)throw e}),$i(e=>e.userId)],jt.prototype,"replaceTrack",1),v([$i((...e)=>e[0].userId),Va(),gp(),pt({settings:{retries:Ai,timeout:e=>Pt(e)},onError(e,t,r,o){e.message.includes("timeout")?(this._log.warn("subscribe timeout"),t()):(this._log.error(`subscribe failed: ${e}`),r(e),E.emit(A.SUBSCRIBE_FAILED,{room:this,remoteTracks:o}))}})],jt.prototype,"subscribe",1),v([Ho({fnName:"subscribe",callback(...e){this.singlePC||e.forEach(t=>{let r=this.remotePublishedUserMap.get(t.userId);r&&!r.isMainStreamSubscribed&&!r.isAuxStreamSubscribed&&r.close("you unsubscribed")})}}),$i((...e)=>e[0].userId)],jt.prototype,"unsubscribe",1);un.create=un._create.bind(un,jt);var cH=un;export{cH as default};
|
|
121
|
+
`,e=new Blob([i],{type:"application/javascript"}),t=URL.createObjectURL(e);this.worker=new Worker(t),URL.revokeObjectURL(t),this.worker.onerror=r=>this._log.warn("worker error:",r.message,r.filename||"unknown",r.lineno||"unknown"),this.worker.onmessage=r=>{var l;let{type:o,trackId:n,message:a,count:c}=r.data;if(o==="black")(l=this.callbacks.get(n))==null||l();else if(o==="log")this._log.warn(a);else if(o==="blackCount"){let u=this.userIdMap.get(n);this._log.warn(`${u||n} black count: ${c}`)}}}return this.worker}start({track:i,isUplink:e,room:t,userId:r,onBlack:o}){if(this._log.debug("start detect black video",i.id),!ko()||!o||!i||T(Worker))return;let n=a=>{var l,u,h,m;let c;if(e)c=(u=(l=a.msg_up_stream_info)==null?void 0:l.msg_video_status)==null?void 0:u.filter(g=>g.uint32_video_stream_type===3)[0];else{let g=(h=a.msg_down_stream_info)==null?void 0:h.filter(D=>{var _;return((_=D.msg_user_info)==null?void 0:_.str_identifier)===r})[0];c=(m=g==null?void 0:g.msg_video_status)==null?void 0:m.filter(D=>D.uint32_video_stream_type===3)[0]}if(c){let g=(c.uint32_video_codec_bitrate||0)/1e3;if(this.sleep[i.id]&&this.sleep[i.id]>0){this.sleep[i.id]-=1;return}g>0&&g<10&&(this.sleep[i.id]=30,this._log.debug("track bitrate",g,"start check"),this.checkOnce(i,30*1e3))}};return t.on("heartbeat-report",n),this.heartbeatListenerCleaner.set(i.id,()=>t.off("heartbeat-report",n)),this.callbacks.set(i.id,o),this.userIdMap.set(i.id,r),i.id}checkOnce(i,e){try{let t=this.getWorker();if(!t)throw new Error("Worker not available");let r=new MediaStreamTrackProcessor({track:i});t.postMessage({type:"addTrack",trackId:i.id,timeout:e,readable:r.readable},[r.readable])}catch(t){this._log.warn("check error:",t),this.stop(i.id)}}stop(i){if(i){this.worker&&this.worker.postMessage({type:"removeTrack",trackId:i}),this.callbacks.delete(i),delete this.sleep[i];let e=this.heartbeatListenerCleaner.get(i);e&&e(),this.heartbeatListenerCleaner.delete(i),this.userIdMap.delete(i)}}destroy(){this.callbacks.forEach((i,e)=>this.stop(e)),this.worker&&(this.worker.terminate(),this.worker=null)}},Yi=new Gu;var Tn=class extends Kr{constructor(e){super(L(N({},e),{isUplink:!0}));d(this,"localMainAudioTrack",null);d(this,"localMainVideoTrack",null);d(this,"localAuxAudioTrack",null);d(this,"localAuxVideoTrack",null);d(this,"_isPublishingAux",!1);d(this,"_publishingLocalAudioTrack");d(this,"_publishingLocalVideoTrack");d(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0});d(this,"_flag",0);d(this,"_checkPublishStateTimeoutId",-1);this.initialize()}get videoCodec(){var e;return((e=this.singlePC)==null?void 0:e.videoCodec)||"h264"}get ssrc(){if(!this.singlePC)return{audio:0,video:0,videoRtx:0,small:0,smallRtx:0,auxiliary:0,auxiliaryRtx:0};let{audioSsrc:e,bigVideoSsrc:t,bigVideoRtxSsrc:r,smallVideoSsrc:o,smallVideoRtxSsrc:n,auxVideoSsrc:a,auxVideoRtxSsrc:c}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:r||0,small:o||0,smallRtx:n||0,auxiliary:a||0,auxiliaryRtx:c||0}}get flag(){return this._flag}set flag(e){this._flag!==e&&(this._flag=e,this.checkPublishState())}checkPublishState(e=!1){if(!e&&this._checkPublishStateTimeoutId>0)return;let{publishState:t,serverPublishState:r}=this,o=Object.keys(t).find(n=>t[n]!==r[n]);if(o)if(e)this._log.warn(`publish state not matched, ${o} local:${t[o]} server:${r[o]} ${Pi()} ${Or()}`),b.addCount({key:521e3});else{this._checkPublishStateTimeoutId=oe.run("timeout",()=>this.checkPublishState(!0),{delay:10*1e3,count:1});return}oe.clearTask(this._checkPublishStateTimeoutId),this._checkPublishStateTimeoutId=-1}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}get publishState(){var t,r,o,n;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(si()?(e.audio=!!((t=a[0])!=null&&t.track),e.bigVideo=!!((r=a[1])!=null&&r.track),e.smallVideo=!!((o=a[2])!=null&&o.track),e.auxVideo=!!((n=a[3])!=null&&n.track)):a.forEach(c=>{c.track&&(c.track.kind===p.AUDIO?e.audio=!0:(e.bigVideo=!0,this._room.videoManager.hasSmall&&(e.smallVideo=!0)))}))}return e}get publishingState(){let{publishState:e}=this,t=N({},e);return this._publishingLocalAudioTrack&&(t.audio=!0),this._publishingLocalVideoTrack&&(this._isPublishingAux?t.auxVideo=!0:(t.bigVideo=!0,this._publishingLocalVideoTrack.small&&(t.smallVideo=!0))),t}get serverPublishState(){return{audio:!!(this.flag&ir),bigVideo:!!(this.flag&tr),smallVideo:!!(this.flag&so),auxVideo:!!(this.flag&Er)}}get muteState(){var e,t,r;return{audio:!!((e=this.localMainAudioTrack)!=null&&e.muted),bigVideo:!!((t=this.localMainVideoTrack)!=null&&t.muted),auxVideo:!!((r=this.localAuxVideoTrack)!=null&&r.muted)}}initialize(){this.installEvents()}close(e){var r;let t=((r=this._peerConnection)==null?void 0:r.getSenders())||[];for(let o of t)o.replaceTrack(null);super.close(e),this.uninstallEvents(),this.uninstallTrackMuteEvents(this.localMainAudioTrack,this.localMainVideoTrack,this.localAuxVideoTrack),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),this.installSPCEvents()}installSPCEvents(){var e,t;(e=this.singlePC)!=null&&e.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||(t=this.singlePC)==null||t.on("spc-reconnected",this.onSinglePCReconnected,this)}uninstallSPCEvents(){var e;(e=this.singlePC)==null||e.off("spc-reconnected",this.onSinglePCReconnected,this)}uninstallEvents(){this.off("connection-state-changed",this.handleConnectionStateChange,this),this.uninstallSPCEvents()}emitConnectionStateChangedEvent(e,t){var n,a,c;let r=this._currentState,o=super.emitConnectionStateChangedEvent(e);return o&&r!==e&&(t?t.emit("connection-state-changed",{prevState:r,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:r,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:r,state:e}),(c=this._publishingLocalVideoTrack)==null||c.emit("connection-state-changed",{prevState:r,state:e}))),o}onVideoEncodeFailed(e){var t;e&&e.isMediaTrackActive&&this.videoCodec==="h264"&&(this._log.warn("h264 encoder not working"),(t=this.singlePC)!=null&&t.isVP8EncodeSupported&&(this._log.warn("switch to vp8"),this.singlePC.switchVideoEncoder("vp8")))}publish(o){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:r}){var l,u,h,m,g,D,_;if(!this.singlePC)return;this.installEvents(),yield this.singlePC.waitForPeerConnectionConnected();let{publishState:n,muteState:a}=this;if(e&&(this._publishingLocalAudioTrack=e,n.audio=!0,a.audio=e.muted),t){if(!this.singlePC.isH264EncodeSupported&&!this.singlePC.isVP8EncodeSupported)throw new y({code:I.NOT_SUPPORTED_H264,message:x({key:P.NOT_SUPPORTED_H264ENCODE})});this.singlePC.isUsingH264&&!this.singlePC.isH264EncodeSupported&&this.singlePC.isVP8EncodeSupported&&(this._log.warn("h264 encoder not supported"),yield this.singlePC.switchVideoEncoder("vp8")),pe&&Ss()===115&&t.profile.width*t.profile.height<=640*360&&(this._log.warn(`fallback video to defaultBigVideoProfile: ${JSON.stringify(er)}`),t.setProfile(er),yield t.applyProfile()),this._publishingLocalVideoTrack=t,r?(n.auxVideo=!0,a.auxVideo=t.muted):(n.bigVideo=!0,a.bigVideo=t.muted)}this._isPublishingAux=r;let c;if(t&&!r&&t.small&&(c=this._room.videoManager.smallTrack,n.smallVideo=!0),yield this._signalChannel.sendWaitForResponseWithRetry({command:Y.SPC_PUBLISH,responseCommand:F.SPC_PUBLISH_RESULT,data:L(N({},this.singlePC.uplinkSSRC),{state:n,muteState:a}),retries:3}),yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:c,isAuxiliary:r}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,t){this[r?"localAuxVideoTrack":"localMainVideoTrack"]=t,yield this.singlePC.setDegradationPreference(this._peerConnection.getSenders()[r?3:1],t.contentHint,t.streamType);let{scaleResolutionDownBy:S}=t;yield this.singlePC.setScaleResolutionDownBy(this._peerConnection.getSenders()[r?3:1],S,t.streamType)}e&&(this[r?"localAuxAudioTrack":"localMainAudioTrack"]=e),yield this.singlePC.setBandwidth({audio:((l=this.localMainAudioTrack)==null?void 0:l.profile.bitrate)||((u=this.localAuxAudioTrack)==null?void 0:u.profile.bitrate),bigVideo:(h=this.localMainVideoTrack)==null?void 0:h.profile.bitrate,smallVideo:(g=(m=this.localMainVideoTrack)==null?void 0:m.small)==null?void 0:g.bitrate,auxVideo:(D=this.localAuxVideoTrack)==null?void 0:D.profile.bitrate}),this.sendMediaSettings(),this.installTrackMuteEvents(e,t),(this._room.preferHW||(_=this._room.scheduleResult.config)!=null&&_.preferHW)&&t&&t.profile.width*t.profile.height>=1280*720&&this.singlePC.useHWEncoder(!0,r?7:2)})}publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:r,isAuxiliary:o}){if(!mt())return;this._log.info("publish by transceiver");let n=t==null?void 0:t.outMediaTrack,a=e==null?void 0:e.outMediaTrack,c=this._peerConnection.getTransceivers(),l=[],u=[],h=(g,D,_)=>{var O;let S=c[D].sender.replaceTrack(_);u.push(D),(O=this.singlePC)!=null&&O.enableInsertableStreams&&S.then(()=>this.createEncodedStreams(c[D].sender,g)),this.initSenderTransform(c[D].sender,g),l.push(S)};a&&h(e.mediaType,0,a),n&&h(t.mediaType,o?3:1,n),t!=null&&t.small&&l.push(this.publishSmall(this._room.videoManager.smallMode,t));let m=this.singlePC.setTransceiverDirection(te.SENDONLY,u);return l.push(m),Promise.all(l)}getTrackByMediaType(e){switch(e){case 1:return this.localMainAudioTrack||this._publishingLocalAudioTrack;case 4:case 8:return this.localMainVideoTrack||this._publishingLocalVideoTrack;case 2:return this.localAuxVideoTrack||this._publishingLocalVideoTrack;default:return null}}createEncodedStreams(e,t){var a,c;if(this.singlePC.insertableStreamsAbortMap.has(e))return;let r=e.createEncodedStreams(),o=new AbortController;(a=this.singlePC)==null||a.addAbortController(e,o),((c=this.getTrackByMediaType(t))!=null&&c.enableEncodeFrame?r.readable.pipeThrough(new TransformStream({transform:(l,u)=>{var m;let h=this.getTrackByMediaType(t);u.enqueue((m=this.singlePC)!=null&&m.isUsingH264&&h?h.encodeFrame(l,t===8):l)}}),o):r.readable).pipeTo(r.writable,o).catch(l=>{this._log.debug("encoded stream error",l),l!=="destory"&&this._log.warn(l)})}initSenderTransform(e,t){if(!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker||!Ns)return;let r=t!==2,o=t===8;e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!1,isAudio:t===1,isMain:r,isSmall:o}))}enableSmall(e){return f(this,null,function*(){e?yield this.publishSmall(this._room.videoManager.smallMode):yield this.unpublishSmall()})}publishSmall(r){return f(this,arguments,function*(e,t=this.localMainVideoTrack){var l;if(!this.singlePC)return;let o=this._peerConnection.getTransceivers(),{sender:n}=o[2],a=yield this.doPublishSmall(e,t),c=e==="canvas"?524700:524701;if(b.addSuccessEvent({key:c}),!a){b.addFailedEvent({key:c,error:10001});return}(l=this.singlePC)!=null&&l.enableInsertableStreams&&this.createEncodedStreams(n,8),this.initSenderTransform(n,8),yield this.singlePC.setTransceiverDirection(te.SENDONLY,[2]),this.updateMediaSettings(),yield this.doPublishChange(),this._blackSmallVideoDetectionId=Yi.start({track:n.track,room:this._room,isUplink:!0,userId:this.userId,onBlack:()=>{this._log.warn("small video is black");let u=e==="canvas"?524700:524701;b.addFailedEvent({key:u,error:10002}),Yi.stop(this._blackSmallVideoDetectionId)}})})}doPublishSmall(r){return f(this,arguments,function*(e,t=this.localMainVideoTrack){if(!this.singlePC)return null;this._log.info("publish small",e);let o=this._peerConnection.getTransceivers(),{sender:n}=o[2];if(e==="canvas"&&this._room.videoManager.smallTrack)return yield n.replaceTrack(this._room.videoManager.smallTrack),"canvas";if(e==="api"&&(t!=null&&t.outMediaTrack)&&(t!=null&&t.small)){yield n.replaceTrack(t==null?void 0:t.outMediaTrack);let a=n.getParameters(),c=ls(t==null?void 0:t.profile,t==null?void 0:t.small);return this._log.info("small scaleResolutionDownBy",c),a.encodings[0].scaleResolutionDownBy=c,n.setParameters(a),"api"}return this._log.warn(`small track can not be enabled, smallMode: ${this._room.videoManager.smallMode}, smallTrack: ${!!this._room.videoManager.smallTrack}, bigVideoTrack: ${!!(t!=null&&t.outMediaTrack)}`),null})}unpublishSmall(){return f(this,null,function*(){if(!this.singlePC)return;this._log.info("unpublish small"),yield this._peerConnection.getTransceivers()[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(te.INACTIVE,[2]),this.updateMediaSettings(),yield this.doPublishChange(),Yi.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0})}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(r){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){var l;yield(l=this.singlePC)==null?void 0:l.waitForPeerConnectionConnected();let o=t&&t===this.localAuxVideoTrack,n=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),c=[];e&&(o?this.localAuxAudioTrack=null:this.localMainAudioTrack=null,!this.localMainAudioTrack&&!this.localAuxAudioTrack&&(yield a[0].replaceTrack(null),c.push(0))),n&&(o?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=L(N({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),c.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=L(N({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),c.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.singlePC.setTransceiverDirection(te.INACTIVE,c),yield this.doPublishChange(!1)):yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),t==null||t.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return f(this,null,function*(){let t={state:this.publishingState,constraintConfig:this._mediaSettings},r=yield this._signalChannel.sendWaitForResponseWithRetry({command:Y.PUBLISH_STATE_CHANGE,data:t,responseCommand:F.PUBLISH_STATE_CHANGE_RESULT,enableLog:e,retries:3});this.checkPublishResultCode(r.data.code,r.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:Y.UNPUBLISH,commandDesc:"unpublish",responseCommand:F.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===I.API_CALL_TIMEOUT)return Promise.resolve();throw t})}updateMediaSettings(){var o;this._mediaSettings.videoCodec=((o=this.singlePC)==null?void 0:o.videoCodec)||"h264";let e=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:t,localAuxVideoTrack:r}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?r=this._publishingLocalVideoTrack:t=this._publishingLocalVideoTrack),oi){if(e&&e.outMediaTrack){let n=e.outMediaTrack.getSettings();this._mediaSettings.audioChannel=n.channelCount||1,this._mediaSettings.audioBps=e.profile.bitrate*1e3,this._mediaSettings.audioFs=n.sampleRate||0}if(t&&t.outMediaTrack){let n=t.outMediaTrack.getSettings(),{scaleResolutionDownBy:a}=t;this._mediaSettings.videoWidth=n.width/a||0,this._mediaSettings.videoHeight=n.height/a||0,this._mediaSettings.videoFps=n.frameRate||0,this._mediaSettings.videoBps=t.profile.bitrate*1e3,t.small&&(this._mediaSettings.smallVideoWidth=t.small.width,this._mediaSettings.smallVideoHeight=t.small.height,this._mediaSettings.smallVideoFps=t.small.frameRate,this._mediaSettings.smallVideoBps=t.small.bitrate*1e3)}if(r&&r.outMediaTrack){let n=r.outMediaTrack.getSettings(),{scaleResolutionDownBy:a}=r;this._mediaSettings.auxVideoWidth=n.width/a||0,this._mediaSettings.auxVideoHeight=n.height/a||0,this._mediaSettings.auxVideoFps=n.frameRate||0,this._mediaSettings.auxVideoBps=r.profile.bitrate*1e3}}else e&&e.outMediaTrack&&(this._mediaSettings.audioChannel=e.profile.channelCount,this._mediaSettings.audioBps=e.profile.bitrate*1e3,this._mediaSettings.audioFs=e.profile.sampleRate),t&&t.outMediaTrack&&(this._mediaSettings.videoWidth=t.profile.width,this._mediaSettings.videoHeight=t.profile.height,this._mediaSettings.videoFps=t.profile.frameRate,this._mediaSettings.videoBps=t.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:Y.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:F.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return f(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is adding ${e.kind} track to current published local ${t?p.AUXILIARY:p.MAIN} stream`),si()&&(yield this.addTrackByTransceiver(e,t))})}addTrackByTransceiver(e,t){return f(this,null,function*(){var o;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===p.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),n===1&&((o=this.localMainVideoTrack)!=null&&o.small)&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===te.INACTIVE&&(yield this.singlePC.setTransceiverDirection(te.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}removeTrack(e){return f(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${t?p.AUXILIARY:p.MAIN} stream`),si()&&(yield this.removeTrackByTransceiver(e,t))})}removeTrackByTransceiver(e,t){return f(this,null,function*(){if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===p.AUDIO)yield r[0].sender.replaceTrack(null);else{let o=t?3:1;yield r[o].sender.replaceTrack(null),o===1&&this._room.videoManager.hasSmall&&(yield r[2].sender.replaceTrack(null)),yield this.singlePC.setTransceiverDirection(te.INACTIVE,[o])}this.updateMediaSettings(),yield this.doPublishChange()})}replaceTrack(e){return f(this,null,function*(){var n;let t=(n=this._peerConnection)==null?void 0:n.getSenders(),r=e.outMediaTrack||e.mediaTrack;if(!t||t.length===0||!r||t.find(a=>a.track===r))return!1;let o=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info(`is replacing ${r.kind} track ${r.id} ${r.label} on ${o?p.AUXILIARY:p.MAIN} stream`),r.kind===p.AUDIO&&t[0]&&(yield t[0].replaceTrack(r)),r.kind===p.VIDEO&&(!o&&t[1]&&(yield t[1].replaceTrack(r)),o&&t[3]&&(yield t[3].replaceTrack(r))),!0})}setBandwidth(o){return f(this,arguments,function*({bandwidth:e,type:t,videoType:r}){if(this.singlePC){let n={};t===p.AUDIO?n.audio=e:r==="big"?n.bigVideo=e:r==="small"?n.smallVideo=e:n.auxVideo=e,yield this.singlePC.setBandwidth(n)}})}sendMutedFlag(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info(`send muted state: ${JSON.stringify(this.muteState)}`),this._signalChannel.sendWaitForResponseWithRetry({command:Y.UPDATE_MUTE_STAT,responseCommand:F.MUTE_RESULT,data:this.muteState,retries:3}).catch(()=>{}))}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&E.emit(A.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(e=p.VIDEO){if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===p.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===p.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===p.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===p.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===Sr?(this._log.error(Ve.NOT_SUPPORTED_H264ENCODE),new y({code:I.NOT_SUPPORTED_H264,message:x({key:P.NOT_SUPPORTED_H264ENCODE})})):new y({code:I.UNKNOWN,message:x({key:P.SIGNAL_RESPONSE_FAILED,data:{signalResponse:F.PUBLISH_RESULT,code:e,message:t}})})}onSinglePCReconnected(){return f(this,null,function*(){this.isMainStreamPublished&&(this._log.warn("republish main stream"),yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(this._log.warn("republish aux stream"),yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0}))})}};v([et(function({localVideoTrack:e}){e==null||e.once("6",this.onVideoEncodeFailed,this)})],Tn.prototype,"publish",1),v([et(function({localVideoTrack:e}){e==null||e.off("6",this.onVideoEncodeFailed,this)})],Tn.prototype,"unpublish",1);var Wu=Tn;function rf(s){return Object.keys(s).filter(i=>s[i])}var Ys=class extends Kr{constructor(e){super(L(N({},e),{isUplink:!1}));d(this,"_flag",0);d(this,"isRobot",!1);d(this,"role","anchor");d(this,"remoteAudioTrack");d(this,"remoteVideoTrack");d(this,"remoteAuxiliaryTrack");d(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0});d(this,"jitterBufferTimeoutId",-1);this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=new Gt(this._room,this),this.remoteVideoTrack=new fi(this._room,this),this.remoteAuxiliaryTrack=new Bs(this._room,this),this.initialize()}get videoCodec(){var e;return((e=this.singlePC)==null?void 0:e.downlinkVideoCodec)||"h264"}get subscribeState(){return{audio:this.remoteAudioTrack.isSubscribed||this.remoteAudioTrack.isSubscribing,video:this.remoteVideoTrack.isBig&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),smallVideo:this.remoteVideoTrack.isSmall&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),auxiliary:this.remoteAuxiliaryTrack.isSubscribed||this.remoteAuxiliaryTrack.isSubscribing}}get muteState(){return bi(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,r,o;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(r=this.remoteVideoTrack)==null||r.onFlagChanged(),(o=this.remoteAuxiliaryTrack)==null||o.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===p.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){clearTimeout(this.jitterBufferTimeoutId),super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents(),this.removeDownlink()}installEvents(){this.singlePC&&(this.listeners("track").includes(this.onTrack)||this.singlePC.on("track",this.onTrack,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||this.singlePC.on("spc-reconnected",this.onSinglePCReconnected,this))}uninstallEvents(){this.singlePC&&(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this))}emitConnectionStateChangedEvent(e){var o,n;let t=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&t!==e&&((o=this.remoteVideoTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),r}onTrack(e){var u,h;let t=e.streams[0],{track:r,receiver:o}=e;if(!t.id.includes(this.tinyId))return;let a=t.id.includes("aux")?"auxiliary":"main";this._log.debug(`ontrack ${a} ${r.kind}`);let c=p.AUDIO;r.kind===p.VIDEO&&(c=a===p.MAIN?p.VIDEO:p.AUXILIARY);let l=this.remoteAudioTrack;c===p.VIDEO?l=this.remoteVideoTrack:c===p.AUXILIARY&&(l=this.remoteAuxiliaryTrack),(u=this.singlePC)==null||u.receiverRemoteTrackMap.set(o,l),(h=this.singlePC)!=null&&h.scriptTransformWorker&&this.initReceiverTransform(o,a,r.kind===p.AUDIO),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(o),l.setInputMediaStreamTrack(r)}createEncodedStreams(e){if(!this.singlePC.insertableStreamsAbortMap.has(e)){let t=e.createEncodedStreams(),r=new AbortController,o={abortController:r,enqueue:n=>{var c,l;let a=(c=this.singlePC)==null?void 0:c.receiverRemoteTrackMap.get(e);return!a||a.kind==="video"&&!((l=this.singlePC)!=null&&l.isUsingH264)?n:a.decodeFrame(n)}};t.readable.pipeThrough(new TransformStream({transform:(n,a)=>{let c=o.enqueue(n);c&&a.enqueue(c)}})).pipeTo(t.writable,r).catch(n=>{n!=="destory"&&this._log.warn(n)}),this.singlePC.addAbortController(e,r)}}initReceiverTransform(e,t,r){!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker||e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!0,isAudio:r,userId:this.userId,streamType:t}))}subscribe(e,t){return f(this,null,function*(){var r;try{let o=!0;if(this._log.info(`subscribe ${t} ${rf(e)}`),this.hasSSRC){let n="subscribe_change";Object.values(e).find(a=>a===!0)||(n="unsubscribe"),yield this.sendSubscription(n,e)}else{if((r=this.singlePC)!=null&&r.autoSubscribedUserMap.size){let n=this.singlePC.autoSubscribedUserMap.get(this.userId);if(n){this.singlePC.autoSubscribedUserMap.delete(this.userId);let a=this.singlePC.autoSubscribedSsrcGroups[n.groupIndex];a&&(this.ssrc={audio:a.audioSsrc,video:a.bigVideoSsrc,videoRtx:a.bigVideoRtxSsrc,auxiliary:a.auxVideoSsrc,auxiliaryRtx:a.auxVideoRtxSsrc},o=!1)}}yield this.doSubscribe(e,o),this.checkTrackEnded(e)}if(e.smallVideo){let{user:n,mediaTrack:a}=this.remoteVideoTrack;b.addSuccessEvent({key:524702}),this._blackSmallVideoDetectionId=Yi.start({track:a,isUplink:!1,room:this._room,userId:this.userId,onBlack:()=>{this._log.warn("small video is black, auto change to big"),this._room.changeType(!1,n),b.addFailedEvent({key:524702}),Yi.stop(this._blackSmallVideoDetectionId)}})}else Yi.stop(this._blackSmallVideoDetectionId)}catch(o){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${o.message} ${JSON.stringify(this.muteState)}`),new y({code:I.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):o}})}checkTrackEnded(e){var t,r,o;if((e.audio&&((t=this.remoteAudioTrack.mediaTrack)==null?void 0:t.readyState)==="ended"||e.video&&((r=this.remoteVideoTrack.mediaTrack)==null?void 0:r.readyState)==="ended"||e.auxiliary&&((o=this.remoteAuxiliaryTrack.mediaTrack)==null?void 0:o.readState)==="ended")&&this.singlePC&&!this.singlePC.isReconnecting){if(this._log.warn("remote track ended start spc reconnect"),Ze&<<92)return;this.singlePC.startReconnection()}}unsubscribe(r){return f(this,arguments,function*({remoteTracks:e,streamType:t}){var a;if(t==="main"&&!this.isMainStreamSubscribed||t==="auxiliary"&&!this.isAuxStreamSubscribed){this._log.info(`${t} stream already unsubscribed`);return}let o=N({},this.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:o.audio=!1;break;case 4:o.video=!1;break;case 8:o.smallVideo=!1;break;case 2:o.auxiliary=!1;break;default:break}});let n="subscribe_change";Object.values(o).find(c=>c===!0)||(n="unsubscribe"),this._log.info(`${n==="unsubscribe"?n:"subscribe"} ${t} [${rf(o)}]`),n==="unsubscribe"&&((a=this.singlePC)==null||a.removeDownlinkQueue.add(this.tinyId)),yield this.sendSubscription(n,o),t==="main"&&(Yi.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0),n==="unsubscribe"&&(yield this.removeDownlink())})}sendSubscription(e,t=this.subscribeState){let r={srcTinyId:this.tinyId,srcUserId:this.userId},o=Y.UNSUBSCRIBE,n=F.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(r={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},o=Y.SUBSCRIBE_CHANGE,n=F.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponseWithRetry({command:o,data:r,responseCommand:n,timeout:1e4,retries:3}).then(({data:a})=>{if(a.code!==0){let c=new y({code:a.code,message:x({key:P.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(c),c}})}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}setDelay({audioDelay:e,videoDelay:t}){this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=t}onSinglePCReconnected(){return f(this,null,function*(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary)&&(this._log.warn(`resubscribe ${JSON.stringify(this.subscribeState)}`),yield this.doSubscribe(this.subscribeState),this.remoteAudioTrack.checkDecodeResult(),this.remoteVideoTrack.checkDecodeResult(),this.remoteAuxiliaryTrack.checkDecodeResult())})}get hasSSRC(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}doSubscribe(){return f(this,arguments,function*(e=this.subscribeState,t=!0){if(this.singlePC){this.singlePC.addDownlinkQueue.add(this.tinyId),yield this.singlePC.waitForPeerConnectionConnected();try{if(t||!this.hasSSRC){let r={audioSsrc:Et(),bigVideoSsrc:Et(),bigVideoRtxSsrc:Et(),auxVideoSsrc:Et(),auxVideoRtxSsrc:Et()},{audioSsrc:o,bigVideoSsrc:n,bigVideoRtxSsrc:a,auxVideoSsrc:c,auxVideoRtxSsrc:l}=r;this.ssrc={audio:o,video:n,videoRtx:a,auxiliary:c,auxiliaryRtx:l},this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc});try{let u=yield this._signalChannel.sendWaitForResponseWithRetry({command:Y.SPC_SUBSCRIBE,responseCommand:F.SPC_SUBSCRIBE_RESULT,data:{srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo,customData:!1,ssrc:r},retries:3,retryTimeout:0});if(u.data.code!==0&&u.data.code!==-10036)throw new y({code:u.data.code,message:u.data.message})}catch(u){throw yield this.removeDownlink(),u}return}this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc})}finally{if(!ga)return;let{main:r,aux:o}=this._room.jitterBufferDelay||{},{jitterDelay:n=r,jitterDelayAux:a=o}=this._room.scheduleResult.config||{};(q(n)||q(a))&&this.setJitterBufferDelay({mainDelay:n,auxDelay:a})}}})}removeDownlink(){return f(this,null,function*(){if(!this.singlePC)return;this.ssrc={audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0},this.singlePC.removeDownlinkQueue.delete(this.tinyId);let e=this._room.scheduleResult.config;(e!=null&&e.jitterDelay||e!=null&&e.jitterDelayAux)&&this.setJitterBufferDelay({mainDelay:0,auxDelay:0}),yield this.singlePC.removeDownlink(this.userId)})}setJitterBufferDelay({mainDelay:e,auxDelay:t}){if(!ga||!this.singlePC||!this._peerConnection||Oi(e)&&Oi(t))return Promise.resolve();this._log.info(`set jitterBuffer main: ${e} aux: ${t}`);let r=this.singlePC.getReceiversByUserId(this.userId);return q(e)&&(this.remoteAudioTrack.jitterBufferDelay=e,this.remoteVideoTrack.jitterBufferDelay=e),q(t)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=t,Oi(e)&&(this.remoteAudioTrack.jitterBufferDelay=t)),new Promise(o=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:o})})}doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:o}){try{if(e===0&&t===0)return r.forEach(a=>a.jitterBufferTarget=0),o();if(r.forEach(a=>{var h;let c=a.track===this.remoteAuxiliaryTrack.outMediaTrack||Oi(e)&&a.track===this.remoteAudioTrack.outMediaTrack;if(c&&Oi(t)||!c&&Oi(e))return;let l=c?t||0:e,u=(a.jitterBufferTarget||0)+100;u>l||(a.jitterBufferTarget=u,this._log.debug(`set ${c?"aux ":""}${(h=a==null?void 0:a.track)==null?void 0:h.kind} jitterBuffer delay ${u} -> ${l}`))}),!r.find(a=>{let c=a.track===this.remoteAuxiliaryTrack.outMediaTrack?t||0:e;return a.jitterBufferTarget<c}))return this._log.info(`set jitterBuffer main: ${e} aux: ${t} done`),o();this.jitterBufferTimeoutId=setTimeout(()=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:o})},1e3)}catch(n){this._log.warn(`set jitterBuffer delay error: ${n}`),clearTimeout(this.jitterBufferTimeoutId),o()}}get audioReceiver(){var e;return((e=this.singlePC)==null?void 0:e.getReceiversByUserId(this.userId)[0])||null}};v([Rt(),Q(e=>function(...t){return new Promise((r,o)=>{let n=a=>{this.off("closed",n),o(new y({code:I.API_CALL_ABORTED,message:x({key:P.CONNECTION_ABORTED,data:a})}))};this.on("closed",n),e.apply(this,t).then(r,o).finally(()=>{this.off("closed",n)})})})],Ys.prototype,"subscribe",1),v([Rt()],Ys.prototype,"unsubscribe",1),v([$i(()=>"jitter")],Ys.prototype,"setJitterBufferDelay",1);var sf=Ys;function of(){return Q(s=>function(...i){return f(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(i=i.filter(t=>t.outMediaTrack&&t.state==="ready"),!i.length))return;E.emit("61",{room:this});let e=s.apply(this,i);return i.forEach(t=>t.publish(this,e)),e})})}function nf(){return Q(s=>function(...i){let e=s.apply(this,i);return i.forEach(t=>t.unpublish()),e})}var af=$e(Ye());function yE(){return Math.floor(Math.random()*16383)}var xc=class xc extends af.EventEmitter{constructor(e,t){super();this.room=e;this.signalChannel=t;d(this,"log");d(this,"cmdIdSeqMap",new Map);d(this,"messageMap",new Map);this.log=C.createLogger({id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),t.on(F.RECEIVE_CUSTOM_MSG,this.onReceiveMsg),this.room.on("peer-leave",r=>{[...this.messageMap.keys()].forEach(o=>{o.split("_").slice(0,-1).join("_")===r&&this.messageMap.delete(o)})})}send({cmdId:e,data:t}){let r=this.cmdIdSeqMap.get(e)||yE(),o={cmdId:e,msg:btoa(String.fromCharCode(...new Uint8Array(t))),ordered:!0,reliable:!0,streamSeq:r};this.cmdIdSeqMap.set(e,r+1),this.signalChannel.send(Y.SEND_CUSTOM_MSG,o),this.log.debug(`send custom msg: ${JSON.stringify(o)}`)}onReceiveMsg(e){let{data:t}=e.data,r=this.room.tinyIdToUserIdMap.get(t.srcTinyId);if(r){let o={userId:r,cmdId:t.cmdId,seq:t.streamSeq,data:Uint8Array.from(atob(t.msg),n=>n.charCodeAt(0)).buffer};if(t.ordered){let n=`${r}_${o.cmdId}`,a=this.messageMap.get(n);if(!a||a.lastSeq===0)a||(a={lastSeq:0,cachedMessageMap:new Map},this.messageMap.set(n,a),setTimeout(()=>this.emitMessage(o,!0),100)),a.cachedMessageMap.set(o.seq,{message:o});else if(Math.abs(a.lastSeq-o.seq)>xc.SEQ_INTERVAL)this.messageMap.set(n,{lastSeq:o.seq,cachedMessageMap:new Map}),this.emitMessage(o);else if(o.seq>a.lastSeq){if(o.seq===a.lastSeq+1)this.emitMessage(o);else if(!a.cachedMessageMap.has(o.seq)){let c=setTimeout(()=>this.emitMessage(o,!0),5e3);a.cachedMessageMap.set(o.seq,{message:o,timeoutId:c})}}else this.log.debug(`drop message ${o.userId}-${o.cmdId}-${o.seq}`)}else this.emit("message",o)}else{this.log.warn(`receive msg from unknown user, wait peer-join tinyId: ${t.srcTinyId}`);let o=n=>{n.tinyId===t.srcTinyId&&(this.room.off("peer-join",o),this.onReceiveMsg(e))};this.room.on("peer-join",o),Ni(2e3).then(()=>this.room.off("peer-join",o))}}emitMessage(e,t=!1){var a;let r=this.messageMap.get(`${e.userId}_${e.cmdId}`),o=e;if(r){if(t){let c=[...r.cachedMessageMap.values()].sort((l,u)=>l.message.seq-u.message.seq);c[0]&&(o=c[0].message)}r.lastSeq!==0&&o.seq-r.lastSeq>1&&this.log.debug(`msg lost userId: ${o.userId} seq: ${r.lastSeq} -> ${o.seq}`),r.lastSeq=o.seq,clearTimeout((a=r.cachedMessageMap.get(o.seq))==null?void 0:a.timeoutId),r.cachedMessageMap.delete(o.seq)}this.log.debug(`receive custom msg: ${JSON.stringify(o)}`),this.emit("message",o);let n=r==null?void 0:r.cachedMessageMap.get(o.seq+1);n&&this.emitMessage(n.message)}};d(xc,"SEQ_INTERVAL",300);var Pc=xc;var{isString:cf,isUndefined:gr,getNetworkType:bE,isEmpty:En}=dt,jt=class extends Mc{constructor(e){super(e);d(this,"_businessInfo");d(this,"userManager");d(this,"_version");d(this,"_heartbeat",-1);d(this,"_lastHeartBeatTime",-1);d(this,"_stats");d(this,"_joinTimeout",-1);d(this,"_firstPublishedList",null);d(this,"_joinReject",null);d(this,"_isRelayChanged",!1);d(this,"sdpSemantics");d(this,"signalChannel",null);d(this,"uplinkConnection",null);d(this,"singlePC",null);d(this,"enableSPC",bs);d(this,"_changeBigSmallRecords",new Map);d(this,"networkQuality");d(this,"_iceTransportPolicy");d(this,"forceRelay",!1);d(this,"_turnServers",[]);d(this,"_iceServersFromJoin");d(this,"_syncUserListInterval",-1);d(this,"_smallStreamConfig",{bitrate:100,frameRate:15,height:120,width:160});d(this,"enableSEI",!1);d(this,"_enableAudioVolumeEvaluation",!1);d(this,"_audioVolumeIntervalId",0);d(this,"_enableMultiAuxStream",!1);d(this,"_pureAudioPushMode",!1);d(this,"_customMessageManager");d(this,"preferHW",!1);d(this,"healthDetector");d(this,"playoutDelay");d(this,"jitterBufferDelay");d(this,"_updateAudioLevelTaskId",-1);this._stats=new pn(this,this._log),this.userManager=new tc(this.userId,this._log),this._version=Pe,this.sdpSemantics=is,gr(e.sdpSemantics)?ni.isUnifiedPlanDefault()&&(this.sdpSemantics=rr):this.sdpSemantics=e.sdpSemantics,this._log.info(`sdpSemantics: ${this.sdpSemantics}, netType: ${bE()}`),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=gr(e.enableMultiAuxStream)?!1:e.enableMultiAuxStream,this.enableSEI=e.enableSEI&&bs,!gr(e.enableSPC)&&bs&&(this.enableSPC=e.enableSPC),this.preferHW=!!e.preferHW,this._initBusinessInfo(e),this.healthDetector=new jp(this)}get isMainStreamPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.isMainStreamPublished)}get isMainAudioPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.localMainAudioTrack)}get isAuxStreamPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.isAuxStreamPublished)}get hasAuxStream(){return[...this.remotePublishedUserMap.values()].findIndex(e=>e.muteState.hasAuxiliary)>=0}get userMap(){return this.userManager.userMap}get remotePublishedUserMap(){return this.userManager.remotePublishedUserMap}get tinyIdToUserIdMap(){return new Map([...this.userMap.values()].map(e=>[e.tinyId,e.userId]))}join(e,t,r){return f(this,null,function*(){return this.userManager.mySelfId=this.userId,this.userManager.on("1",o=>{this.emit("peer-join",o)}),this.userManager.on("2",o=>{this.closeDownLinkConnection(o,"remote user exitRoom"),this.emit("peer-leave",o)}),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",n=>{var o=Xu(n,[]);E.emit(A.REMOTE_PUBLISH_STATE_CHANGED,N({room:this},o)),this.emit("remote-publish-state-changed",N({},o))}),this.joinParams=e,new Promise((o,n)=>f(this,null,function*(){var a,c;this._joinReject=n;try{this.checkDestroy();try{yield Promise.all([this.initialize(),this.initSinglePC()])}catch(u){if(u instanceof y&&u.code===I.SPC_INITIALIZED_FAILED)(a=this.signalChannel)==null||a.destroy(),yield this.initialize();else return n(u)}let l=w();yield this.doJoin(e,(c=this.singlePC)==null?void 0:c.clientAbility),b.addSuccessEvent({key:521708,cost:w()-l}),o(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(l){b.addFailedEvent({key:521708,error:l}),n(l)}this._joinReject=null}))})}initSinglePC(){return f(this,null,function*(){if(!(!this.enableSPC||this.singlePC)){this.singlePC=new qt({signalChannel:this.signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.on("sei-message",e=>this.emit("sei-message",e)),this.singlePC.on("dump",e=>this.emit("dump",e)),this.singlePC.once("error",()=>this.fallbackToMPC());try{return yield this.singlePC.initialize()}catch(e){throw this.fallbackToMPC(),new y({code:I.SPC_INITIALIZED_FAILED,message:e==null?void 0:e.message})}}})}doJoin(e,t){return new Promise((r,o)=>f(this,null,function*(){var c,l,u;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this.signalChannel.once(Ne.SETUP_FAILED,h=>{this.clearJoinTimeout(),E.emit(A.JOIN_SIGNAL_CONNECTION_END,{room:this,error:h}),o(h)}),me((l=(c=this.scheduleResult)==null?void 0:c.config)==null?void 0:l.singlePC)&&bs&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2),t&&this.playoutDelay&&(t.playoutDelay=this.playoutDelay);let n={roomId:String(e.roomId||e.strRoomId),useStringRoomId:this.useStringRoomId,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel,trtcRole:e.role,trtcScene:this.scene==="live"?2:1,sdpSemantics:this.sdpSemantics,version:this._version,ua:navigator&&navigator.userAgent||"",terminalType:Cd(),netType:Cr(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig,receiveMix:!0};this._log.debug(`join room signal data: ${JSON.stringify(n)}`);let a=5e3;(u=this.scheduleResult.config)!=null&&u.enterRoomTimeout&&this.scheduleResult.config.enterRoomTimeout>=1&&(a=this.scheduleResult.config.enterRoomTimeout*1e3),this._joinTimeout=window.setTimeout(()=>{o(new y({code:I.JOIN_ROOM_FAILED,message:x({key:P.JOIN_ROOM_TIMEOUT})}))},a),E.emit(A.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?Y.SPC_JOIN_ROOM:Y.JOIN_ROOM,n),this.signalChannel.once(F.JOIN_ROOM_RESULT,h=>f(this,null,function*(){this.clearJoinTimeout();let{code:m,message:g,data:D,tinyId:_}=h.data;E.emit(A.JOIN_RECEIVED_CMD_RES,{room:this,code:m}),m===0?(this._log.info("Join room success, start heartbeat"),_&&(this.tinyId=_),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=D.publishers,this._iceServersFromJoin=D.iceServer?[D.iceServer]:[],this.singlePC&&this.singlePC.setIceServers(this.getIceServers()).then(()=>{var S;(S=this.singlePC)==null||S.connect(L(N({},D.ability),{useVp8:D.ability.useVp8||!!e.useVp8})).catch(()=>{})}),r()):(this._log.error(`Join room failed result: ${m} error: ${g}`),o(new y({code:I.JOIN_ROOM_FAILED,extraCode:m,message:x({key:P.JOIN_ROOM_FAILED,data:{error:g,code:m}})})))}))}))}reJoin(){return f(this,null,function*(){if(!this.isJoined){this._log.warn("reJoin abort");return}try{this._log.warn(`reJoin pending: ${this.joinParams.roomId}`);let e,t=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,t.push(this.initSinglePC().then(r=>(e=r,r)))),this.signalChannel&&(this.signalChannel.close(),t.push(this.signalChannel.connect())),yield Promise.all(t),yield this.doJoin(L(N({},this.joinParams),{role:this.role==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),e),this._log.warn("reJoin success"),re.logSuccessEvent({userId:this.userId,eventType:st.REJOIN}),this.singlePC){let r=o=>{var n;o.state==="CONNECTED"&&((n=this.singlePC)==null||n.off(Ti.CONNECTION_STATE_CHANGED,r),this.uplinkConnection instanceof Wu&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach(a=>{a.installEvents(),a.onSinglePCReconnected()}))};this.singlePC.on(Ti.CONNECTION_STATE_CHANGED,r),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof mn&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(e){this._log.warn(`reJoin fail ${e}`),this.reset(),re.logFailedEvent({userId:this.userId,eventType:st.REJOIN,error:e}),this.emit("error",new y({code:I.JOIN_ROOM_FAILED,message:x({key:P.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}})}initialize(){return f(this,null,function*(){let{mainUrl:e,backupUrl:t}=this.getSignalChannelUrl(),r=this.signalChannel||Sp(this.userId),o=!!(r&&r.isConnected&&r.keepAlive&&r.userId===this.userId&&r.room===this),n;return Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(n=this.scheduleResult.domains[0]),this._log.info(`${o?"reuse":"setup"} signal channel`),o?(r.url=e,r.backupUrl=t,r.room=this,this.signalChannel=r):(r&&r.close(),this.signalChannel=new qs({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:e,backupUrl:t,room:this,signalDomainWhenUnifiedProxy:this.proxy_unified?n:void 0}),this._customMessageManager=new Pc(this,this.signalChannel),this._customMessageManager.on("message",a=>{this.emit("custom-message",a)})),this.networkQuality||(this.networkQuality=new Qs({signalChannel:this.signalChannel,room:this}),this.networkQuality.on(Qs.EVENT_NETWORK_QUALITY,a=>{var c;this.emit("network-quality",a),(c=this.singlePC)==null||c.detectTCPAndUDP(a)})),qe(this,this.signalChannel).add(Ne.CONNECTION_STATE_CHANGED,a=>{E.emit(A.SIGNAL_CONNECTION_STATE_CHANGED,N({room:this},a)),this.emit("signal-connection-state-changed",a)}).add(Ne.RECONNECT_FAILED,a=>{this.reset(),this.emit("error",a)}).add(F.PEER_JOIN,a=>{let{srcTinyId:c,userId:l,role:u}=a.data.data;this.userManager.addUser({userId:l,tinyId:c,role:u})}).add(F.PEER_LEAVE,a=>{let{userId:c,reason:l=0}=a.data.data;this.userManager.deleteUser(c,l)}).add(F.UPDATE_REMOTE_MUTE_STAT,a=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=10*1e3&&this.doHeartbeat(),this.onPublishedUserList(a.data)}).add(F.CLIENT_BANNED,a=>{let c=a.data.data,{reason:l}=c;if(re.uploadEvent({log:`stat-banned:${l}`,userId:this.userId}),l==="user_time_out"){this._log.warn(`${l} last heart beat time: ${this._lastHeartBeatTime} interval: ${Date.now()-this._lastHeartBeatTime}, visibility: ${document.visibilityState}`),this.reJoin();return}this._log[l==="kick"?"error":"info"](`user was banned because of [${l}]`),this.reset(),this.emit("banned",{reason:l})}).add(F.SEND_SWITCH_ROOM_SUBED_REQ,a=>{if(!this.singlePC)return;let{subList:c}=a.data.data;c.forEach(l=>{this.singlePC.autoSubscribedUserMap.set(l.userId,l)})}),this.signalChannel.once(Ne.SETUP_SUCCESS,a=>{this.tinyId=a.signalInfo.tinyId,E.emit(A.JOIN_SIGNAL_CONNECTION_END,{room:this})}),E.emit(A.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),o&&E.emit(A.JOIN_SIGNAL_CONNECTION_END,{room:this}),o})}setSignalChannel(e){this.signalChannel=e,e||ve(this)}leave(){return f(this,null,function*(){var e;try{yield this.doHeartbeat()}catch(t){}this._log.info("leave() => leaving room"),E.emit(A.LEAVE_SEND_CMD,{room:this}),(e=this.signalChannel)==null||e.send(Y.LEAVE_ROOM)})}clearNetworkQuality(){this.networkQuality&&(this.networkQuality.stop(),delete this.networkQuality)}closeConnections(){this.remotePublishedUserMap.forEach(e=>{this.closeDownLinkConnection(e.userId,"you exitRoom")})}clearJoinTimeout(){clearTimeout(this._joinTimeout),this._joinTimeout=-1}startHeartbeat(){this._heartbeat===-1&&(this._heartbeat=oe.run("ric",this.doHeartbeat.bind(this),{delay:2e3}))}stopHeartbeat(){this._heartbeat!==-1&&(this._log.info("stopHeartbeat"),oe.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return f(this,null,function*(){var n;let e=this.badCaseDetector.getMonitorFreeze(),t=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:e});this.badCaseDetector.resetMonitor();let r=(n=this.signalChannel)!=null&&n.isConnected?wm(this.userId):[],o=L(N({str_sdk_version:to,uint64_datetime:new Date().getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_event_msg:r,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},t),{msg_device_info:N({uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:Cr()},t.msg_device_info)});if(this.heartbeatReport=o,E.emit(A.HEARTBEAT_REPORT,{room:this,report:o}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(Y.ON_QUALITY_REPORT,o);let a=Date.now();this._lastHeartBeatTime>0&&a-this._lastHeartBeatTime>1e4&&this._log.warn(`heartbeat took ${a-this._lastHeartBeatTime}`),this._lastHeartBeatTime=a,this.signalChannel.isOnline||(this._log.warn("signal channel is not online"),this.signalChannel.startReconnection())}this.emit("heartbeat-report",L(N({},o),{bytes_sent:this._stats.totalBytesSent+this.signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this.signalChannel.bytesReceived}))}!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)})}onPublishedUserList(e){if(!this.isJoined)return;let t=e.data.userList.filter(r=>r.flag!==Jc).map(({userId:r,srcTinyId:o,flag:n})=>{r===this.userId&&this.uplinkConnection&&(this.uplinkConnection.flag=n);let a=this.remotePublishedUserMap.get(r);return a&&this.checkSubscribeBigSmallVideo(a),{userId:r,tinyId:o,flag:n}});e.data.mixRobotList.forEach(({userId:r,srcTinyId:o,flag:n,mixUserList:a})=>{t.unshift({userId:r,tinyId:o,flag:n,isRobot:!0,mixUserList:a})}),E.emit(A.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:t}),this.userManager.setRemotePublishedUserList(t)}closeUplink(e="you unpublished"){this.uplinkConnection&&(this.localTracks.size>0&&this.uplinkConnection.doUnpublish(),this.uplinkConnection.close(e),this.uplinkConnection instanceof mn&&(this.uplinkConnection=null)),this.localTracks.forEach(t=>t.unpublish()),this.localTracks.clear()}createDownlinkConnection({userId:e,tinyId:t,flag:r,isRobot:o}){let n=new(this.singlePC?sf:ku)({userId:e,tinyId:t,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:r,isRobot:o});this.userManager.addRemotePublishedUser(n),this.installDownlinkEvents(n,e),this.emit("remote-published",n)}closeDownLinkConnection(e,t="remote user unpublished"){let r=this.remotePublishedUserMap.get(e);r&&(r.close(t),this.emit("remote-unpublished",r))}installDownlinkEvents(e,t){e.on("error",r=>{let o=r.getCode();o!==I.ICE_TRANSPORT_ERROR&&(o===I.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",r))}),e.on("connection-state-changed",r=>{this.emit("media-connection-state-changed",L(N({},r),{userId:e.userId}))}),e.on("firewall-restriction",()=>{this.emit("firewall-restriction")})}startSyncUserListInterval(){this._syncUserListInterval===-1&&(this._syncUserListInterval=oe.run("ric",this.syncUserList.bind(this)))}stopSyncUserListInterval(){oe.clearTask(this._syncUserListInterval),this._syncUserListInterval=-1}syncUserList(){return this.getUserList().then(e=>{this.userManager.setUserList(e)}).catch(e=>{this._log.debug(`sync user list failed: ${e}`)})}getUserList(){var e;return(e=this.signalChannel)!=null&&e.isConnected?this.signalChannel.sendWaitForResponse({command:Y.GET_USER_LIST,responseCommand:F.USER_LIST_RES,enableLog:!1,timeout:2e3}).then(({data:t})=>{let{code:r,message:o}=t;if(r===0)return(t.data&&t.data.userList||[]).map(({userId:a,srcTinyId:c,role:l})=>({userId:a,tinyId:c,role:l}));throw x({key:P.SIGNAL_RESPONSE_FAILED,data:{signalResponse:F.USER_LIST_RES,code:r,message:o}})}):Promise.reject("not connected")}getAllConnections(){let e=[...this.remotePublishedUserMap.values()];return this.uplinkConnection&&e.push(this.uplinkConnection),e}isRelayMaybeFailed(){if(this.signalChannel&&!this.signalChannel.isOnline||!bu)return!1;if(this.singlePC)return this.singlePC.reconnectionCount>6;let e=this.getAllConnections();if(e.length===0)return!1;for(let t=0;t<e.length;t++)if(e[t].getReconnectionCount()<6)return!1;return!0}checkConnectionsToReconnect(){var e;this.singlePC?((e=this.singlePC.getPeerConnection())==null?void 0:e.connectionState)===ge.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach(r=>{if(r instanceof rt&&!r.getIsReconnecting()){let o=r.getPeerConnection();o&&o.connectionState===ge.CLOSED&&(this._log.warn(`[${r.getUserId()}] pc is closed but not reconnect`),r.startReconnection())}})}fallbackToMPC(){return f(this,null,function*(){var e;if(this._log.warn("fallback to multi pc"),re.uploadEvent({log:"stat-fallback",userId:this.userId}),this.enableSPC=!1,(e=this.singlePC)==null||e.close(),this.singlePC=null,this.isJoined&&(yield this.reJoin()),this.uplinkConnection){let t=this.uplinkConnection;this.uplinkConnection=new mn({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),t.isMainStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:t.localMainAudioTrack,localVideoTrack:t.localMainVideoTrack,isAuxiliary:!1})),t.isAuxStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:t.localAuxAudioTrack,localVideoTrack:t.localAuxVideoTrack,isAuxiliary:!0})),t.close()}for(let t of[...this.remotePublishedUserMap.values()]){let r=new ku({userId:t.userId,tinyId:t.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:t.flag,remoteAudioTrack:t.remoteAudioTrack,remoteVideoTrack:t.remoteVideoTrack,remoteAuxiliaryTrack:t.remoteAuxiliaryTrack});this.installDownlinkEvents(r,t.userId),this.remotePublishedUserMap.set(t.userId,r),t.isMainStreamSubscribed&&(yield r.subscribe(t.subscribeState,"main")),t.isAuxStreamSubscribed&&(yield r.subscribe(t.subscribeState,"auxiliary"))}})}destroy(){this.isDestroyed||(this.signalChannel&&(this._log.info("destroying SignalChannel"),this.signalChannel.close(),this.signalChannel=null),super.destroy(),this._joinReject&&(this._joinReject(new y({code:I.INVALID_OPERATION,message:x({key:P.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners(),this.healthDetector.destroy(),oe.clearTask(this._audioVolumeIntervalId))}switchRole(e){return f(this,null,function*(){this.role!==e&&(e==="audience"&&this.uplinkConnection&&this.closeUplink("you switch role to audience"),yield this.doSwitchRole(e))})}doSwitchRole(e){let t={command:Y.SWITCH_ROLE,data:{role:e==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:F.SWITCH_ROLE_RES,retries:1};return this._log.info(`switchRole signal data: ${JSON.stringify(t.data)}`),this.signalChannel.sendWaitForResponseWithRetry(t).then(r=>{let{code:o,message:n}=r.data;if(o!==0)throw new y({code:I.SWITCH_ROLE_FAILED,message:x({key:P.SWITCH_ROLE_FAILED,data:{message:n,code:o}})});this.role=e}).catch(r=>{throw r instanceof y&&r.getCode()===I.API_CALL_TIMEOUT&&(r=new y({code:I.SWITCH_ROLE_FAILED,message:x({key:P.SWITCH_ROLE_TIMEOUT})})),this._log.error(r),r})}publish(...e){return f(this,null,function*(){let t={},r={};e.forEach(c=>{c instanceof Tt&&(c instanceof hi?r.audio=c:t.audio=c),c instanceof je&&(c instanceof ct&&c.mediaType===2?r.video=c:t.video=c)});let o=En(t),n=En(r);(!o||!n)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new Wu({userId:this.userId,tinyId:this.tinyId,room:this}):this.uplinkConnection=new mn({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),this.uplinkConnection.on("connection-state-changed",c=>{this.emit("media-connection-state-changed",L(N({},c),{userId:this.userId}))}),this.uplinkConnection.on("firewall-restriction",()=>{this.emit("firewall-restriction")}),this.uplinkConnection.on("error",c=>{let l=c.getCode();l!==I.ICE_TRANSPORT_ERROR&&(l===I.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",c))}));let a=e.map(c=>c.kind).join(",");o||(this._log.info(`publish() => main ${a}`),yield this.uplinkConnection.publish({localAudioTrack:t.audio,localVideoTrack:t.video,isAuxiliary:!1}),this._log.info("main is published")),n||(this._log.info(`publish() => aux ${a}`),yield this.uplinkConnection.publish({localAudioTrack:r.audio,localVideoTrack:r.video,isAuxiliary:!0}),this._log.info("aux is published"))})}unpublish(...e){return f(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||!this.isMainStreamPublished&&!this.isAuxStreamPublished||!this.uplinkConnection)return;let t={},r={};e.forEach(o=>{!o.mediaTrack||!o.isPublished||(o instanceof Tt&&(o instanceof hi?r.audio=o:t.audio=o),o instanceof je&&(o instanceof ct&&o.mediaType===2?r.video=o:t.video=o))});try{let o=e.map(n=>n.kind).join(",");En(t)||(this._log.info(`unpublish() => main ${o}`),yield this.uplinkConnection.unpublish({localAudioTrack:t.audio,localVideoTrack:t.video})),En(r)||(this._log.info(`unpublish() => aux ${o}`),yield this.uplinkConnection.unpublish({localAudioTrack:r.audio,localVideoTrack:r.video}))}catch(o){}this.localTracks.size===0&&this.closeUplink("you unpublished")})}addTrack(e){if(!this.uplinkConnection||!e.mediaTrack)return Promise.resolve();let t=this.uplinkConnection.addTrack(e);return e.publish(this,t),t}removeTrack(e){return!this.uplinkConnection||!e.mediaTrack?Promise.resolve():this.uplinkConnection.removeTrack(e).then(t=>(e.unpublish(),t))}replaceTrack(e){return!this.uplinkConnection||!e.mediaTrack||!qd()?Promise.resolve():this.uplinkConnection.replaceTrack(e).then(t=>{t&&E.emit(A.LOCAL_TRACK_REPLACED,{track:e})})}setBandWidth(e){return f(this,null,function*(){this.uplinkConnection&&(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())})}enableSmall(e){return f(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:p.VIDEO,videoType:p.SMALL,bandwidth:this.uplinkConnection.localMainVideoTrack.small.bitrate})),yield this.uplinkConnection.enableSmall(e)})}subscribe(...e){return f(this,null,function*(){if(e=e.filter(n=>!n.isSubscribed),e.length===0)return;let{userId:t}=e[0],r=this.remotePublishedUserMap.get(t);if(!r)return;let o=e.find(n=>n.mediaType===2)?"auxiliary":"main";try{let n=N({},r.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:n.audio=!0;break;case 4:n.video=!0;break;case 8:n.smallVideo=!0;break;case 2:n.auxiliary=!0;break}});let a=this._changeBigSmallRecords.get(t);a&&a.options.smallVideo&&r.muteState.hasSmall&&n.video&&(n.video=!1,n.smallVideo=!0),E.emit(A.SUBSCRIBE_START,{room:this,streamType:o,remotePublishedUser:r,subscribeState:n}),this._log.info(`subscribe() => ${t} ${o} [${Rc(n)}] prev: [${Rc(r.subscribeState)}]`),yield r.subscribe(n,o),this._log.info(`subscribe ${t} ${o} done`);for(let c of e)c.mediaTrack||(yield c.waitHasMediaTrack());E.emit(A.SUBSCRIBE_SUCCESS,{room:this,streamType:o,remotePublishedUser:r})}catch(n){let a=n instanceof y?n.getCode():I.UNKNOWN,c=n;throw n instanceof y?a===I.REMOTE_STREAM_NOT_EXIST&&(c=new y({code:I.API_CALL_ABORTED,message:x({key:P.API_CALL_ABORTED,data:{message:n.message,userId:t,streamType:o}})}),this._log.warn(c)):(c=new y({code:a,message:x({key:P.SUBSCRIBE_FAILED,data:{message:n.message,userId:t,streamType:o}})}),this._log.error(c)),c}})}unsubscribe(...e){return f(this,null,function*(){let{userId:t}=e[0],r=this.remotePublishedUserMap.get(t);if(!r)return;let o=e.find(n=>n.mediaType===2)?"auxiliary":"main";this._log.info(`unsubscribe() => ${t} ${o}`);try{yield r.unsubscribe({remoteTracks:e,streamType:o})}catch(n){this._log.warn(`unsubscribe() => failed ${n}`)}e.forEach(n=>{n.unsubscribe(),n.mediaType===8&&n.setMediaType(4)}),E.emit(A.UNSUBSCRIBE_SUCCESS,{room:this,streamType:o,remotePublishedUser:r})})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAudioVolumeEvaluation(e=2e3,t){if(e<=0){this._enableAudioVolumeEvaluation=!1,oe.clearTask(this._audioVolumeIntervalId);return}e=Math.floor(Math.max(e,100)),E.emit(A.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&oe.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=oe.run("intervalInWorker",()=>{var o;Ur.isRunning?this.stopUpdateAudioLevelFromSenderStat():this.updateAudioLevelFromSenderStat(e,t);let r=[];(o=this.remotePublishedUserMap)==null||o.forEach(n=>{if(n.muteState.hasAudio){!Ur.isRunning&&n.muteState.audioAvailable&&n.remoteAudioTrack.isSubscribed?this.updateDownlinkAudioLevelFromReceiver(n):n.remoteAudioTrack.volume=0;let a=Math.floor(n.remoteAudioTrack.getAudioLevel()*100);r.push({userId:n.userId,volume:a})}}),this.emit("audio-volume",r)},{delay:e,backgroundTask:t})}updateAudioLevelFromSenderStat(e,t){return f(this,null,function*(){var n;if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack||this._updateAudioLevelTaskId!==-1)return;let r=(n=this.uplinkConnection.getPeerConnection())==null?void 0:n.getSenders()[0];if(!r)return;let o=Math.max(e,500);this._log.warn(`updateAudioLevelFromSenderStat ${o}`),this._updateAudioLevelTaskId=oe.run("intervalInWorker",()=>f(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack){this.stopUpdateAudioLevelFromSenderStat();return}let a=yield r.getStats();if(this._updateAudioLevelTaskId<0)return;let{localMainAudioTrack:c}=this.uplinkConnection;a.forEach(l=>{l.type==="media-source"&&l.audioLevel&&(c.volume=l.audioLevel)})}),{delay:o,backgroundTask:t})})}stopUpdateAudioLevelFromSenderStat(){var e;this._updateAudioLevelTaskId!==-1&&(this._log.warn("stopUpdateAudioLevelFromSenderStat"),oe.clearTask(this._updateAudioLevelTaskId),this._updateAudioLevelTaskId=-1,(e=this.uplinkConnection)!=null&&e.localMainAudioTrack&&(this.uplinkConnection.localMainAudioTrack.volume=0))}updateDownlinkAudioLevelFromReceiver(e){var o;let{audioReceiver:t}=e;if(!jd||!t)return;let r=(o=t.getSynchronizationSources()[0])==null?void 0:o.audioLevel;q(r)?e.remoteAudioTrack.volume=Math.min(r*2,1):t.getStats().then(n=>{n.forEach(a=>{a.type==="inbound-rtp"&&q(a.audioLevel)&&(e.remoteAudioTrack.volume=a.audioLevel)})})}getLocalAudioStats(){return f(this,null,function*(){var t;let e={};return e[this.userId]={bytesSent:0,packetsSent:0,audioLevel:0},(t=this.uplinkConnection)!=null&&t.localMainAudioTrack&&(e[this.userId]=this.uplinkConnection.localMainAudioTrack.stat),e})}getLocalVideoStats(){return f(this,null,function*(){var t,r;let e={};return e[this.userId]=((r=(t=this.uplinkConnection)==null?void 0:t.localMainVideoTrack)==null?void 0:r.stat)||{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0},e})}getTransportStats(){return f(this,null,function*(){let e={rtt:0,downlinksRTT:{}};if(this.uplinkConnection){let t=yield this._stats.getSenderStats(this.uplinkConnection);e.rtt=t.rtt}for(let[,t]of this.remotePublishedUserMap){let r=yield this._stats.getReceiverStats(t);e.downlinksRTT[r.userId]=r.rtt}return e})}getRemoteVideoStats(e){return f(this,null,function*(){let t={};for(let[r,o]of this.remotePublishedUserMap)e==="main"&&o.muteState.hasVideo&&(t[r]=o.remoteVideoTrack.stat),e==="auxiliary"&&o.muteState.hasAuxiliary&&(t[r]=o.remoteAuxiliaryTrack.stat);return t})}getRemoteAudioStats(){return f(this,null,function*(){let e={};for(let[t,r]of this.remotePublishedUserMap)r.muteState.hasAudio&&(e[t]=r.remoteAudioTrack.stat);return e})}setTurnServer(e,t){this._log.info(`set turn server: ${JSON.stringify(e)} ${t||""}`);let r=[];Array.isArray(e)?e.forEach(o=>r.push(dt.getTurnServer(o))):dt.isPlainObject(e)&&r.push(dt.getTurnServer(e)),this._turnServers=r,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:Y.START_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:F.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:Y.STOP_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:F.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"})}sendStartPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?Y.START_PUBLISH_TENCENT_CDN:Y.START_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?F.START_PUBLISH_TENCENT_CDN_RES:F.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"})}sendStopPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?Y.STOP_PUBLISH_TENCENT_CDN:Y.STOP_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?F.STOP_PUBLISH_TENCENT_CDN_RES:F.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}sendStartPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Y.START_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:F.START_PUBLISH_CDN_STREAM_RES,commandDesc:"startPublishCDNStream"})}sendUpdatePushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Y.UPDATE_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:F.UPDATE_PUBLISH_CDN_STREAM_RES,commandDesc:"updatePublishCDNStream"})}sendStopPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Y.STOP_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:F.STOP_PUBLISH_CDN_STREAM_RES,commandDesc:"stopPublishCDNStream"})}sendAbilityStatus(e){var t;(t=this.signalChannel)==null||t.sendWaitForResponse({command:Y.ABILITY_STATUS_REPORT,data:e,timeout:5e3,responseCommand:F.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch(r=>{})}getIceServers(e){var t,r;return this._turnServers.length>0?this._turnServers:(t=this.scheduleResult.iceServers)!=null&&t.length?this.scheduleResult.iceServers:e!=null&&e.length?e:(r=this._iceServersFromJoin)!=null&&r.length?this._iceServersFromJoin:[]}getIceTransportPolicy(){return this.forceRelay?"relay":this._iceTransportPolicy||this.scheduleResult.iceTransportPolicy||"all"}getLogger(){return this._log}enableAIVoice(){throw new Error("Method not implemented.")}getSignalChannelUrl(){let e={mainUrl:"",backupUrl:""},t=dt.getEnv();return t?(e.mainUrl=`wss://${t}.rtc.qq.com`,e.backupUrl=e.mainUrl):this.proxy_ws?(e.mainUrl=this.proxy_ws,e.backupUrl=e.mainUrl):this.proxy_unified?(e.mainUrl=`wss://${this.proxy_unified}`,e.backupUrl=e.mainUrl):Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(e.mainUrl=`wss://${this.scheduleResult.domains[0]}`,e.backupUrl=e.mainUrl,this.scheduleResult.domains[1]&&(e.backupUrl=`wss://${this.scheduleResult.domains[1]}`)),e}getSignalInfo(){var e;return((e=this.signalChannel)==null?void 0:e.getSignalInfo())||{clientIp:"",relayIp:""}}reset(e=!1){this.stopSyncUserListInterval(),this.stopHeartbeat(),this.closeConnections(),this.clearNetworkQuality(),this.closeUplink("you exitRoom"),this.signalChannel&&(e&&this.signalChannel.keepAlive&&this.signalChannel.isConnected?this.signalChannel.stopKeepAliveIn(3600):(this.signalChannel.close(),this.setSignalChannel(null))),this._stats.reset(),this.userManager.clear(),this.userManager.removeAllListeners(),this.singlePC&&(this.singlePC.close(),this.singlePC=null),this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}}checkSubscribeBigSmallVideo(e){return f(this,null,function*(){let{subscribeState:t,userId:r,muteState:{hasSmall:o,hasVideo:n}}=e;if(!o&&!n||!t.video&&!t.smallVideo)return;let a=this._changeBigSmallRecords.get(r);if(!a||a.isSubscribing||a.reSubscribeCount<=0)return;let{options:c,reSubscribeCount:l}=a;if(c.video&&t.video||c.smallVideo&&t.smallVideo&&o)return;let u={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:c.video,smallVideo:c.smallVideo};try{if(!o&&u.smallVideo&&(u.video=!0,u.smallVideo=!1),u.smallVideo===t.smallVideo&&u.video===t.video)return;a.isSubscribing=!0,a.reSubscribeCount=l-1,yield e.subscribe(u,"main"),e.remoteVideoTrack.setMediaType(u.smallVideo?8:4),this._log.info(`change [${r}] to ${u.smallVideo?"small":"big"} video successfully. count ${rs-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount=rs}catch(h){this._log.info(`change [${r}] to ${u.smallVideo?"small":"big"} video failed. count ${rs-a.reSubscribeCount}. reason: ${h}`),a.isSubscribing=!1,a.reSubscribeCount===0&&this._changeBigSmallRecords.delete(r)}})}changeType(e,t){let o={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:rs};this._changeBigSmallRecords.set(t.userId,o),this._log.info(`set [${t.userId}] video prefer type: ${e?"small":"big"}`),this.emit("subscribe-small-video-changed",{userId:t.userId,isSmall:e});let n=this.remotePublishedUserMap.get(t.userId);n&&this.checkSubscribeBigSmallVideo(n)}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(e){this._businessInfo=e.businessInfo;let t={};if(cf(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!gr(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_PURE_AUDIO})});this._pureAudioPushMode=e.pureAudioPushMode,t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.pure_audio_push_mod=this._pureAudioPushMode}if(!gr(e.userDefineRecordId)){let r=/^[A-Za-z0-9_-]{1,64}$/gi;if(e.userDefineRecordId.match(r)===null)throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!gr(e.userDefinePushArgs))if(cf(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256)t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_push_args=e.userDefinePushArgs;else throw new y({code:I.INVALID_PARAMETER,message:x({key:P.INVALID_USER_DEFINE_PUSH_ARGS})});En(t)||(this._businessInfo=JSON.stringify(t))}sendCustomMessage(e){var t;(t=this._customMessageManager)==null||t.send(e)}enableInsertableStreams(){return f(this,null,function*(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&Ui)return this.singlePC.enableInsertableStreams=!0,yield this.singlePC.waitForPeerConnectionConnected(),yield this.singlePC.startReconnection()})}sendSignalMessage(e){var t;return this.signalChannel?(t=this.signalChannel)==null?void 0:t.sendWaitForResponseWithRetry(e):Promise.reject(new y({code:I.INVALID_OPERATION,message:"not join"}))}get enableCodecPipeline(){return this.videoManager.encodePipeline.length>0||this.videoManager.decodePipeline.length>0||this.audioManager.encodePipeline.length>0||this.audioManager.decodePipeline.length>0}get scriptTransformWorker(){var e;return(e=this.singlePC)==null?void 0:e.scriptTransformWorker}switchRoom(e){return f(this,null,function*(){var D,_;if(!this.signalChannel)return;let{roomId:t,strRoomId:r,userSig:o,privateMapKey:n}=e,a=((D=this.scheduleResult.config)==null?void 0:D.autoSubscribeCount)||(e==null?void 0:e.autoSubscribeCount)||1,c=String(this.useStringRoomId?r:t),l=[];for(let S=0;S<a;S++)l.push({audioSsrc:Et(),bigVideoSsrc:Et(),bigVideoRtxSsrc:Et(),auxVideoSsrc:Et(),auxVideoRtxSsrc:Et()});let u={currRoomId:this.roomId,targetRoomId:c,useStringRoomId:this.useStringRoomId,ability:(_=this.singlePC)==null?void 0:_.clientAbility,userSig:o!=null?o:this.userSig,privateMapKey:n!=null?n:this.privateMapKey,subscribe:l};this.singlePC&&(this.singlePC.autoSubscribedSsrcGroups=l,this.singlePC.autoSubscribedUserMap.clear()),E.emit(A.SWITCH_ROOM_START,{room:this});let h=yield this.signalChannel.sendWaitForResponse({command:Y.SWITCH_ROOM,responseCommand:F.SEND_SWITCH_ROOM_RES,data:u}),{code:m,message:g}=h.data;if(m===0){let S=this.roomId;this.roomId=this.useStringRoomId?r:String(t),gr(o)||(this.userSig=o),gr(n)||(this.privateMapKey=n),E.emit(A.SWITCH_ROOM_SUCCESS,{room:this,currentRoomId:S,targetRoomId:c})}else{this._log.error(`switch room failed. result: ${m} error: ${g}`),this.singlePC&&(this.singlePC.autoSubscribedSsrcGroups=[]);let S=new y({code:I.SWITCH_ROOM_FAILED,extraCode:m,message:g});throw E.emit(A.SWITCH_ROOM_FAILED,{room:this,error:S}),S}})}isSwitchRoomSupported(){var t;let e="unable to use switchRoom API, fallback to exitRoom and enterRoom.";return((t=this.scheduleResult.config)==null?void 0:t.switchRoom)!==!0?(this._log.warn(`${e} Reason: this sdkAppId is not supported, please contact us [https://trtc.io/contact] to enable it.`),!1):this.scene!=="live"?(this._log.warn(`${e} Reason: the scene is not 'live'.`),!1):this.role!=="audience"?(this._log.warn(`${e} Reason: the role is not 'audience'.`),!1):this.singlePC?!0:(this._log.warn(`${e} Reason: is not using single peerConnection.`),!1)}};v([Te(["left",H.INIT],"joined"),pt({settings:{retries:1,timeout:0},onRetrying(e){this._log.warn(`join retry ${e}`)},onRetryFailed(e){this._log.error("join failed",e)},onError(e,t){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),Wt(!0),this.reset(),t()):this.signalChannel&&this.signalChannel.isConnected&&this.signalChannel.keepAlive?(this._log.warn("is using keepAlive ws, retry join"),this.signalChannel.close(),this.reset(),t()):(this.reset(),t())}}),fp()],jt.prototype,"join",1),v([Te("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),_p(),xa("leave room"),Ho({fnName:"publish",validateArgs:!1}),Ho({fnName:"unsubscribe",validateArgs:!1})],jt.prototype,"leave",1),v([Rt(),of(),pt({settings:{retries:Ai,timeout:e=>Pt(e)},onError(e,t,r){var o;(o=e.message)!=null&&o.includes("timeout")?(this._log.warn("publish timeout"),t()):(this._log.error(`publish failed: ${e}`),r(e),E.emit(A.PUBLISH_FAILED,{room:this}))}})],jt.prototype,"publish",1),v([Ho({fnName:"publish"}),Rm("api-call"),Rt(),nf(),et(function(){var e,t;this.localTracks.size===0&&dr()&&((t=(e=this.singlePC)==null?void 0:e.getPeerConnection())==null||t.getSenders().forEach(r=>r.track&&r.replaceTrack(null)))})],jt.prototype,"unpublish",1),v([Ma(e=>{if(e.code!==I.API_CALL_ABORTED)throw e}),$i(e=>e.userId)],jt.prototype,"replaceTrack",1),v([$i((...e)=>e[0].userId),Va(),gp(),pt({settings:{retries:Ai,timeout:e=>Pt(e)},onError(e,t,r,o){e.message.includes("timeout")?(this._log.warn("subscribe timeout"),t()):(this._log.error(`subscribe failed: ${e}`),r(e),E.emit(A.SUBSCRIBE_FAILED,{room:this,remoteTracks:o}))}})],jt.prototype,"subscribe",1),v([Ho({fnName:"subscribe",callback(...e){this.singlePC||e.forEach(t=>{let r=this.remotePublishedUserMap.get(t.userId);r&&!r.isMainStreamSubscribed&&!r.isAuxStreamSubscribed&&r.close("you unsubscribed")})}}),$i((...e)=>e[0].userId)],jt.prototype,"unsubscribe",1);un.create=un._create.bind(un,jt);var cH=un;export{cH as default};
|