trtc-sdk-v5 5.8.7-beta.6 → 5.8.7-beta.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/trtc.esm.js CHANGED
@@ -51,7 +51,7 @@ void main() {
51
51
  `)))}else{if(e instanceof mr)return e;o=new mr({code:U.UNKNOWN_ERROR,fnName:t,originError:e})}return o}};function o_(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 P=mr;var uh={type:"object",properties:{cameraId:{type:"string"},useFrontCamera:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:["string","boolean"],values:[!0,!1,"view","publish","both"]},small:{properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack}}},hh={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}}},ns={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(s,i,e){if(z(s)&&!document.getElementById(s))throw new P({code:U.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:i}})}},mh={name:"userId",required:!0,type:"string"},ph={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[ut.AUDIO_PROFILE_STANDARD,ut.AUDIO_PROFILE_STANDARD_STEREO,ut.AUDIO_PROFILE_HIGH,ut.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function No(s,i){if(!s)throw new P({code:U.INVALID_OPERATION,extraCode:5101,fnName:i})}function fh(s,i,e){if(!s)throw new P({code:U.INVALID_OPERATION,extraCode:5102,fnName:i,messageParams:{value:e}})}var mN={type:"number",notLessThanZero:!0},n_={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 P({code:U.INVALID_OPERATION,extraCode:5104,fnName:e});if(s.roomId){if(z(s.roomId))throw new P({code:U.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:i}});if(!(/^[1-9]\d*$/.test(String(s.roomId))&&s.roomId<4294967295))throw new P({code:U.INVALID_PARAMETER,extraCode:5013,fnName:e,messageParams:{key:i}})}else if(s.strRoomId){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(s.strRoomId))throw new P({code:U.INVALID_PARAMETER,extraCode:5012,fnName:e,messageParams:{key:i}})}else throw new P({code:U.INVALID_PARAMETER,extraCode:5015,fnName:e})},properties:{sdkAppId:{required:!0,type:"number",allowEmpty:!1},userId:{required:!0,type:"string",allowEmpty:!1},userSig:{required:!0,type:"string",allowEmpty:!1},scene:{type:"string",values:["live","rtc"]},role:{type:"string",values:["audience","anchor"]},roomId:{type:["string","number"]},strRoomId:{type:"string"},proxy:{type:["object","string"],properties:{websocketProxy:{type:"string"},turnServer:{type:["object","array"],properties:{url:{required:!0,type:"string"},username:{type:"string"},credential:{type:"string"},credentialType:{type:"string",values:["password"]}}},loggerProxy:{type:"string"},webtransportProxy:{type:"string"}}},enableAutoPlayDialog:{type:"boolean"},userDefineRecordId:{type:"string"},latencyLevel:{type:"number"}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:ns,mute:{type:["boolean","string"]},publish:{type:"boolean"},option:uh},validate(s){var i;if(!((i=s==null?void 0:s.option)!=null&&i.videoTrack)&&Ei())throw new P({code:U.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:L(v({},ns),{required:!1}),publish:{type:"boolean"},mute:{type:["boolean","string"]},option:uh}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:ph},validate(s){var i;if(!((i=s==null?void 0:s.option)!=null&&i.audioTrack)&&Ei())throw new P({code:U.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:ph}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:ns,publish:{type:"boolean"},option:hh},validate(s,i,e,t,r){var o;if(!((o=s==null?void 0:s.option)!=null&&o.videoTrack)&&Ei())throw new P({code:U.ENV_NOT_SUPPORTED,extraCode:5201});if(!eo())throw new P({code:U.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:ns,publish:{type:"boolean"},option:hh}},muteRemoteAudio:[mh,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[mh,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:ns,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){No(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(s.userId);if(fh(!!t,e,s),t&&(s.streamType==="main"&&!t.muteState.videoAvailable||s.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new P({code:U.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:s}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:L(v({},ns),{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){No(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(s.userId);if(fh(!!t,e,s),t&&(s.streamType==="main"&&!t.muteState.videoAvailable||s.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new P({code:U.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!=="*"&&E(s.streamType))throw new P({code:U.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(s,i,e){No(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(!so)throw new P({code:U.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new P({code:U.INVALID_OPERATION,fnName:e,extraCode:5108});if(s.byteLength>1e3)throw new P({code:U.INVALID_PARAMETER,extraCode:5018,fnName:e});if(s.byteLength===0)throw new P({code:U.INVALID_PARAMETER,extraCode:5017,messageParams:{key:i},fnName:e});No(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 P({code:U.INVALID_OPERATION,extraCode:5109,messageParams:{key:i},fnName:e})}}}}],sendCustomMessage:{name:"message",required:!0,type:"object",properties:{cmdId:{type:"number",required:!0,min:1,max:10},data:{instanceOf:ArrayBuffer,required:!0,validate(s,i,e,t){if(s.byteLength>1e3)throw new P({code:U.INVALID_PARAMETER,extraCode:5018,fnName:e});if(s.byteLength===0)throw new P({code:U.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:i}})}}},validate(s,i,e){if(No(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new P({code:U.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:i}})}}},Ne={TRTC:n_};var we=class extends Error{};function a_(s,i){let e=Hr(s);for(let t=0;t<i.length;t++)fi(e[t],i[t]);return e}function c_(s){this._resolve=Promise.resolve(s)}function d_(s){this._reject=Promise.reject(s)}var pr=class{constructor(i,e){this.instance=i;this.group=e;this.started=!1;this.ops=[];this.startSame=()=>!0;this.mergeUpdate=a_;let t=pr.instances.get(i);t?t.set(e,this):pr.instances.set(i,new Map([[e,this]]))}static get(i,e){if(!e)return;let t=pr.instances.get(i);return t&&t.get(e)||new pr(i,e)}static gets(i,e){let t=pr.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,d;throw this.ops.shift(),i===0&&((c=this.currentOp)==null?void 0:c.type)===2&&this.ops.shift().reject(new we("start failed")),(d=this.currentOp)==null||d.action(),a},n={type:i,action:()=>e(...n.args).then(r,o),args:t,resolve:c_,reject:d_};try{switch(this.state){case 1:if(i===0)throw new we("already started");break;case 4:if(i===2)throw new we("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 we("already start");break;case 3:switch(i.type){case 2:throw new we("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new we("unknown state")}else switch(i.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let t=new we("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 we("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new we("start not allowed after update");case 0:throw new we("duplicate start");case 3:if(this.startSame(this.currentOp.args,i.args))throw this.ops.pop().reject(new we("keep start")),new we("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}},ti=pr;ti.instances=new WeakMap;var ha=new WeakMap,ma=(s,i)=>{if(i instanceof we){let{stack:e}=i;i=new P({code:U.OPERATION_ABORT,message:`${s} abort: ${i.message}`,fnName:s}),e&&(i.stack+=e.substr(e.indexOf(`
52
52
  `)))}throw i};function ji(s,i){return G((e,t)=>function(...r){let o=ti.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(ma.bind(null,t))):e.apply(this,r)})}function fr(s,i){let{merge:e,debounce:t}=i||{};return G((r,o)=>function(...n){let a=ti.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:d}=t;return new Promise((h,u)=>{var I,C;let p=(I=ha.get(this))==null?void 0:I.get(d(...n));if(p){let{timeoutId:D,resolve:B}=p;clearTimeout(D),B()}let _=setTimeout(()=>{if(a.state===3||a.state===4)return h();a.action(2,r.bind(this),n).catch(ma.bind(null,o)).then(h,u)},c);ha.has(this)?(C=ha.get(this))==null||C.set(d(...n),{timeoutId:_,resolve:h}):ha.set(this,new Map([[d(...n),{timeoutId:_,resolve:h}]]))})}return a.action(2,r.bind(this),n).catch(ma.bind(null,o))})}function qi(s){return G((i,e)=>function(...t){let r=typeof s=="function"?s.call(this,...t):s;if(r instanceof RegExp)return Promise.all(ti.gets(this,r).map(n=>n.action(3,()=>Promise.resolve(),t))).then(()=>i.call(this,...t));let o=ti.get(this,r);return o?o.action(3,i.bind(this),t).catch(ma.bind(null,e)):i.apply(this,t)})}var M={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"},_h=new Set([M.ERROR,M.AUTOPLAY_FAILED,M.KICKED_OUT,M.REMOTE_USER_ENTER,M.REMOTE_USER_EXIT,M.REMOTE_AUDIO_AVAILABLE,M.REMOTE_AUDIO_UNAVAILABLE,M.REMOTE_VIDEO_AVAILABLE,M.REMOTE_VIDEO_UNAVAILABLE,M.CONNECTION_STATE_CHANGED,M.PUBLISH_STATE_CHANGED,M.SCREEN_SHARE_STOPPED,M.DEVICE_CHANGED]);function vo(s){return s==="sub"?"auxiliary":s==="auxiliary"?"sub":"main"}function _r(s){return s===ut.QOS_PREFERENCE_CLEAR?"detail":s===ut.QOS_PREFERENCE_SMOOTH?"motion":""}var l_=s=>s.startsWith("data:application/octet-stream;base64,"),u_=s=>s.startsWith("file://"),pa=class{constructor(){l(this,"_log");this._log=R.createLogger({id:"fd"})}download(i,e){return f(this,null,function*(){let{type:t="blob"}=e||{};try{let r=k(),o;if(te(fetch)?o=yield this.downloadWithFetch(i,t):o=yield this.downloadWithXHR(i,t),!o||!o.data)throw new Error("data is empty");let n=k()-r;return this._log.info(`downloaded: ${i}, return type: ${t}, cost: ${n}ms`),N.addSuccessEvent({key:522700,cost:k()-r}),o.data}catch(r){throw this._log.error(`failed to download: ${i}, error: ${r}`),N.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)throw new Error("network response was not ok");let r;return e==="arraybuffer"?r=yield t.arrayBuffer():r=yield t.blob(),{data:r}}catch(t){throw t}})}downloadWithXHR(i,e){return this._log.info(`download with xhr: ${i}, return type: ${e}`),new Promise((t,r)=>{let o=new XMLHttpRequest;o.open("GET",i,!0),o.responseType=e,o.onload=()=>{o.status===200||o.status===0&&o.response?t({data:o.response}):r(new Error("XHR failed"))},o.onerror=r,o.send(null)})}loadWasm(i,e){return f(this,null,function*(){this._log.info(`loadWasm ${i}, importObject: ${JSON.stringify(e)}`);let t=k(),r=null,o=null;if(te(WebAssembly.instantiateStreaming)&&!l_(i)&&!u_(i)&&te(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=k()-t;return this._log.info(`loadedWasm ${i}, cost: ${n}ms`),N.addSuccessEvent({key:522701,cost:n}),r}throw this._log.error(`failed to loadWasm ${i}, error: ${o}`),N.addFailedEvent({key:522701,error:o}),o})}};b([je({settings:{timeout:0,retries:3},onRetrying(s){this._log.warn(`download retrying: ${s}`)}})],pa.prototype,"download",1);var gh=new pa;function Eh({TRTC:s,room:i,errorModule:e,assetsPath:t}){return{TRTC:s,room:i,assetsPath:t,fileDownloader:gh,innerEmitter:T,constants:Ka,environment:Br,utils:Be,eventLogger:Y,log:this.room.getLogger(),loggerManager:R,errorModule:e,kvStatManager:N,rtcDectection:Wt,trtc:this,clearStarted:(r,o)=>{let n=r.getAlias(),a=ti.instances.get(this);if(!!a)if(o){let c=a.get(n+o);if(!c)return;c.started=!1}else a.forEach((c,d)=>{d.startsWith(n)&&(c.started=!1)})},startGetPCM:To,createAudioNode:qc}}var Th=(s,i)=>{let{emit:e}=s;return s.emit=(...t)=>{try{return e.apply(s,t)}catch(r){let o=w({key:x.CATCH_HANDLER_ERROR,data:{name:i,event:t[0]},addDocLink:!1});return R.warn(`${o}
53
53
 
54
- ${r.stack}`),!1}},s};var as=new WeakMap;function Sh(s){let i=as.get(s);i&&(i.forEach(e=>clearTimeout(e)),as.delete(s))}function Ih(s,i){return G((e,t)=>function(...r){let o=as.get(this);o||(o=new Map,as.set(this,o));let n=i(...r),a=o.get(n);if(!a||a<=0){e.apply(this,r);let c=setTimeout(()=>{var d;(d=as.get(this))==null||d.delete(n)},s);o.set(n,c)}else{clearTimeout(a);let c=window.setTimeout(()=>{var d;e.apply(this,r),(d=as.get(this))==null||d.delete(n)},s);o.set(n,c)}})}var Ah="5.8.7-beta.6";function Ue(...s){return G((i,e)=>function(...t){try{_a.call(this,s,t,e,this._name)}catch(r){return Promise.reject(r)}return i.apply(this,t)})}function Wd(...s){return G((i,e)=>function(...t){try{_a.call(this,s,t,e,this._name)}catch(r){throw r}return i.apply(this,t)})}function _a(s,i,e,t){if(_e(s))for(let r=0;r<s.length;r++)fa.call(this,{rule:s[r],value:i[r],key:s[r].name,fnName:e,className:t});else fa.call(this,{rule:s,value:i[0],key:s.name,fnName:e,className:t})}function fa({rule:s,value:i,key:e,fnName:t,className:r}){function o(c){return{code:U.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:s,value:i}}}if(E(i)){if(s.required)throw new P(o(5001));if(E(s.defaultValue)){te(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 d=0;d<s.type.length;d++)s.type[d]===null&&i===null&&(c=!0),te(s.type[d])&&i instanceof s.type[d]&&(c=!0),z(s.type[d])&&Ae(i)===s.type[d].toLowerCase()&&(c=!0);if(!c)throw new P({code:U.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:s.type.map(d=>Xs(d)?An(d):z(d)?d:Ae(d))},value:i}})}else if(!E(s.type)&&Ae(i)!==s.type)throw new P(o(5002));if(s.allowEmpty===!1){let c=K(i)&&(i===0||Number.isNaN(i)),d=z(i)&&i.trim()==="";if(c||d)throw new P(o(5003))}if(s.notLessThanZero&&K(i)&&i<0)throw new P(o(5006));if(!E(s.min)&&K(i)&&i<s.min)throw new P(o(5007));if(!E(s.max)&&K(i)&&i>s.max)throw new P(o(5008));if(z(s.instanceOf)){if(!i||i._name!==s.instanceOf)throw new P(o(5004))}else if(te(s.instanceOf)&&!(i instanceof s.instanceOf))throw new P(o(5004));if(Array.isArray(s.values)&&!s.values.includes(i))throw new P(o(5005));let{properties:n}=s;Ze(n)&&Ct(i)&&Object.keys(n).forEach(c=>{fa.call(this,{rule:n[c],value:i&&i[c],key:`${c}`,fnName:t,className:r})});let{arrayItem:a}=s;Ze(a)&&_e(i)&&i.forEach((c,d)=>{fa.call(this,{rule:a,value:c,key:`${e}[${d}]`,fnName:t,className:r})}),te(s.validate)&&s.validate.call(this,i,e,t,r,this)}function ae(s={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t,ignoreLog:r}=s;return G((o,n)=>function(...a){var u;function c(p,_,I){if(I&&I.includes(p))return"hided";if(e){let C=e(...a);if(a[C.argIndex]===_)return C.value}if(_===a||p in a)return _;try{return _ instanceof HTMLElement?`id: ${_.id} type:${Ae(_)}`:(JSON.stringify(_),_)}catch(C){return`type:${Ae(_)}`}}let d=this._log||R;if(r!=null&&r(...a))return o.apply(this,a);a.length>0?d.info(`${n}() ${JSON.stringify(a,(p,_)=>c(p,_,["userSig","privateMapKey"]))}`):d.info(`${n}()`);let h=t?t(...a):vn[n];try{let p=o.apply(this,a),_=k();return sr(p)?p.then(I=>(d.info(`${n}() success ${i.call(this,...a)}`),N.addSuccessEvent({key:h,cost:k()-_}),I)).catch(I=>{var B;I=P.convertFrom.call(this,I,n,a.length===1?a[0]:a);let C=I.extraCode||I.code,D=(B=I.message)!=null&&B.includes(C)?"":` code:${C}`;throw d.error(`${n}() failed ${i.call(this,...a)} ${I}${D} params: ${JSON.stringify(a,c)}`),N.addFailedEvent({key:h,error:I}),I}):(N.addSuccessEvent({key:h}),p)}catch(p){p=P.convertFrom.call(this,p,n);let _=p.extraCode||p.code,I=(u=p.message)!=null&&u.includes(_)?"":` code:${_}`;throw d.error(`${n}() failed ${p}${I} params: ${JSON.stringify(a,c)}`),N.addFailedEvent({key:h,error:p}),p}})}var ga=s=>G((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 P({code:U.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});if(te(o.constructor.isSupported)&&!o.constructor.isSupported())throw this._log.error(`plugin ${String(t)} is not supported`),new P({code:U.ENV_NOT_SUPPORTED,message:`plugin ${String(t)} is not supported`,extraCode:5210,fnName:e});return _a.call(this,o.getValidateRule(s),[r],e,"TRTC"),i.call(this,o,r)})});var Ea=0,Jd=class{constructor(i,e){l(this,"player");l(this,"publisher");l(this,"mixInput");this.mixInput=new Qr(e),i.url?(this.player=new Audio(i.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(i.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(i.track),this.mixInput.connect()}updateSettings(i){!this.player||(E(i.volume)||(this.volume=i.volume),E(i.loop)||(this.loop=i.loop),E(i.playbackRate)||(this.playbackRate=i.playbackRate))}updateListener(i){if(!!this.player){if(i.onDurationChange){let{onDurationChange:e}=i;this.player.ondurationchange=t=>{e(t.target.duration)}}if(i.onTimeUpdate){let e=i.onTimeUpdate,{player:t}=this;t.ontimeupdate=()=>{e(t.currentTime,t.duration)}}i.onEnded&&(this.player.onended=i.onEnded)}}reset(){this.seek(0),this.mixInput.connect()}seek(i){!this.player||i<0&&i>this.player.duration||(this.player.currentTime=i,this.publisher.currentTime=i)}play(){var i,e;return(i=this.publisher)==null||i.play(),(e=this.player)==null?void 0:e.play()}pause(){var i,e;(i=this.player)==null||i.pause(),(e=this.publisher)==null||e.pause()}stop(){var i;(i=this.player)==null||i.pause(),this.mixInput.disconnect()}setOperation(i){i==="pause"&&this.pause(),i==="resume"&&(this.pause(),this.play()),i==="stop"&&(this.pause(),this.seek(0))}set volume(i){!this.player||!this.publisher||(this.player.volume=i,this.publisher.volume=i)}set loop(i){!this.player||!this.publisher||(this.player.loop=i,this.publisher.loop=i)}set playbackRate(i){!this.player||!this.publisher||(this.player.playbackRate=i,this.publisher.playbackRate=i)}};function cs(s,i){if(i&&typeof i!="function")throw new P({code:U.INVALID_PARAMETER,message:`start audioMixer plugin: param ${s} should be a function.`})}var ds=class{constructor(i){this.core=i;l(this,"log");l(this,"mixedMusicMap",new Map);l(this,"cacheMusicMap",new Map);Ea=Ea+1,this.log=i.log.createChild({id:`${this.getAlias()}${Ea}`}),this.log.info(`[audioMixer] created id=${this.getAlias()}${Ea}`),this.core=i}getName(){return ds.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return ds.startValidateRule;case"update":return ds.updateValidateRule;case"stop":return ds.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 Jd(i,e.audioManager),this.cacheMusicMap.set(t,o)),o.updateListener(i),o.updateSettings(i),yield o.play(),this.mixedMusicMap.set(t,o),this.log.info(`start mix audio track ${t} success.`),N.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),E(t)||n.setOperation(t),E(r)||n.seek(r),this.kvUpload(i)})}stop(e){return f(this,arguments,function*({id:i}){var t;this.mixedMusicMap.has(i)&&(this.log.info(`remove music source, music id: ${i}`),(t=this.mixedMusicMap.get(i))==null||t.stop(),this.mixedMusicMap.delete(i)),i==="*"&&this.destroyAllMusic()})}kvUpload(i){let{track:e,loop:t,volume:r,playbackRate:o,operation:n,seekFrom:a,onTimeUpdate:c,onDurationChange:d,onEnded:h}=i;e&&N.addCount({key:502711}),t&&N.addCount({key:502703}),r&&N.addCount({key:502704}),o&&N.addCount({key:502705}),n&&N.addCount({key:502706}),a&&N.addCount({key:502707}),typeof c!="function"&&N.addCount({key:502709}),typeof h!="function"&&N.addCount({key:502710}),typeof d!="function"&&N.addCount({key:502708})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((i,e)=>this.stop({id:e}))}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}},Xi=ds;l(Xi,"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"),d=r.startsWith("data");if(!(a||c||d))throw new P({code:U.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new P({code:U.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});cs("onTimeUpdate",i.onTimeUpdate),cs("onEnded",i.onEnded),cs("onDurationChange",i.onDurationChange)}}),l(Xi,"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){cs("onTimeUpdate",i.onTimeUpdate),cs("onEnded",i.onEnded),cs("onDurationChange",i.onDurationChange)}}),l(Xi,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),l(Xi,"Name","AudioMixer");var Ta=0,jd,ls=class{constructor(i){this.core=i;l(this,"log");l(this,"audioContext",qe("denoiser"));l(this,"workletNode");Ta=Ta+1,this.log=i.log.createChild({id:`${this.getAlias()}${Ta}`}),this.log.info(`[audioDenoiser] created id=${this.getAlias()}${Ta}`),i.assetsPath&&this.preload(`${i.assetsPath}/denoiser-wasm.js`)}static startValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,t,r,o){if(!i.room.audioManager.hasAudioTrack)throw new P({code:U.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return jd||(jd=this.doPreload(i)),jd}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield dr(this.audioContext,t)}finally{URL.revokeObjectURL(t)}})}getName(){return ls.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(i){switch(i){case"start":return ls.startValidateRule(this.core);case"update":return ls.updateValidateRule;case"stop":return ls.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e}=this.core;if(yield this.preload(`${i.assetsPath}/denoiser-wasm.js`),!this.workletNode){let t=String(Date.now()).slice(0,-3),{auth:r,sign:o,status:n,message:a}=yield p_(L(v({},i),{timestamp:t}));if(!r)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${r}. Message: ${a}`),new P({code:U.INVALID_PARAMETER,message:a});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(i.sdkAppId),userId:i.userId,timestamp:t,sign:o,status:n}}),this.workletNode.port.onmessage=c=>{let{data:d}=c;d.type==="cost"&&this.log.debug(`[RTCAIDenoiser] ${d.value}`)}}this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(){return 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)}},gr=ls;l(gr,"updateValidateRule",{type:"object"}),l(gr,"stopValidateRule",{type:"object"}),l(gr,"Name","AIDenoiser");function m_(s,i=m.MAIN){return`https://${Vt[i]||Sn(s,i)}/api/v1/audioAiAuth`}function p_(r){return f(this,arguments,function*({sdkAppId:s,userId:i,userSig:e,timestamp:t}){let n=`${m_(s)}?sdkAppId=${s}&userId=${i}&userSig=${e}&timestamp=${t}`,a=yield fetch(n),{data:{errCode:c,errMsg:d,sign:h,status:u}}=yield a.json();if(u==="1")return{auth:!0,sign:h,status:u,message:d};let p="Init RTCAIDenoiser failed.",_="";switch(c){case 1:_="Please check your params.";break;case 2:_="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:_="Server is invalid. Please contact our engineer. ";break;case 4:_="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:_="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:_="Your version is not supported.";break}return{auth:!1,status:u,message:d?`${p} Reason: ${d}. ${_}`:`${p}, ${_}`}})}var Ch=Se(De(),1);var qd=class extends Ch.EventEmitter{constructor(){super();this.state="nominal";this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return f(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!fe&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){Y.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)&&R.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){Y.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},f_=new qd,Xd=f_;function Qd([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 Ri(new DataView(new Uint8Array(o).buffer),!0)}function zd(s){return s.type==="empty"||s.data.byteLength===0}function Yd(s){return s.getInt32(0)===1&&s.getInt8(4)===6}function Kd(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 Zd({frame:s,seiMessageList:i}){if(!i||i.length===0||s.data.byteLength===0)return s;let e=Kd(s.data),t=9-e;if(t<=0)return s;let r=i.splice(0,t).reverse().map(Qd),o=r.reduce((h,u)=>h+u.dataView.byteLength,0),n=new ArrayBuffer(o+s.data.byteLength),a=new DataView(n),c=new DataView(s.data),d=0;for(let h=0;h<r.length;h++)for(let u=0;u<r[h].dataView.byteLength;u++)a.setInt8(d++,r[h].dataView.getInt8(u));for(let h=0;h<s.data.byteLength;h++)a.setInt8(d++,c.getInt8(h));return s.data=n,s}function el({frame:s,onSEI:i}){try{let e=new DataView(s.data);if(zd(s)||!Yd(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 d=a-r;if(o===-1?o=d:n===-1&&(n=d,t.push(new Ri(new DataView(e.buffer.slice(o,n)))),o=d,n=-1),!(e.getUint8(a+1)===6)){s.data=e.buffer.slice(d);break}}r=0}else r=0}i==null||i(t.reverse())}catch(e){}return s}var tl=0,il=class{constructor(i){this.core=i;l(this,"log");l(this,"_seiMessageList",[]);l(this,"_smallSeiMessageList",[]);l(this,"_subStreamSeiMessageList",[]);tl++,this.log=i.log.createChild({id:`${this.getAlias()}${tl}`}),this.log.info(`[sei] created id=${this.getAlias()}${tl}`),this.core=i,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 Zd({frame:i,seiMessageList:t})}catch(t){this.log.warn(t)}return i}decode({frame:i,track:e}){return el({frame:i,onSEI:t=>{t.forEach(r=>{this.core.trtc.emit(M.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:Ti?this.encode:Zd,type:1}),this.core.room.videoManager.addDecodeProcessor({processor:Ti?this.decode:el,type:1})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:1}),this.core.room.videoManager.removeDecodeProcessor({type:1})}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 il.Name}getAlias(){return"sei"}getGroup(){return"sei"}},us=il;l(us,"autoStart",!0),l(us,"Name","SEI");var g_=0,Sa,rl=class{constructor(i){this.core=i;l(this,"_core");l(this,"log");l(this,"dumpLocalVideoMap",{});l(this,"dumpRemoteVideoMap",{});l(this,"dialog");this._core=i,this.log=i.log.createChild({id:`${this.getAlias()}${++g_}`}),this.log.info("created")}getName(){return rl.Name}getAlias(){return"dm"}getGroup(){return"dm"}getValidateRule(i){switch(i){case"start":return{name:"StartDebugOptions",required:!1};case"update":return{name:"UpdateDebugOptions",required:!1};case"stop":return{name:"StopDebugOptions",required:!1}}}start(){return f(this,null,function*(){!new URLSearchParams(location.search).has("trtcDebug")||(yield this.openDebugDiaLog(),this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED&&this.addVideoProcessor())})}update(){}stop(){this.closeDebugDiaLog(),this.removeVideoProcessor()}destroy(){this.stop()}openDebugDiaLog(){return f(this,null,function*(){try{if(Sa)yield Sa;else{let i=Date.now();Sa=this.loadScript(`https://web.sdk.qcloud.com/trtc/webrtc/assets/debug/debug-dialog@${Ie}.js`),yield Sa,this.log.info(`download debug dialog script cost: ${Date.now()-i}ms`)}this.dialog=new TRTCDebugDialog(this._core,this.log,this.dumpLocalVideoMap,this.dumpRemoteVideoMap),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(i){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(i))}})}closeDebugDiaLog(){var i;(i=this.dialog)==null||i.closeDialog(),this.dialog=null}addVideoProcessor(){this._core.room.videoManager.addEncodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.encodeVideo.bind(this):this.encodeVideoDump,type:2}),this._core.room.videoManager.addDecodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.decodeVideo.bind(this):this.decodeVideoDump,type:2})}removeVideoProcessor(){this._core.room.videoManager.removeEncodeProcessor({type:2}),this._core.room.videoManager.removeDecodeProcessor({type:2})}encodeVideo({frame:i,mediaType:e}){return this.encodeVideoDump({frame:i,onDump:()=>{if(!e)return;let t=e===2?"sub":"main",r=this.dumpLocalVideoMap[t];r&&(r.data.push(i.data),r.duration>0&&Date.now()-r.startTimestamp>r.duration*1e3&&r.onDumpEnd())}})}decodeVideo({frame:i,track:e}){return this.decodeVideoDump({frame:i,onDump:()=>{if(!e)return;let t=this.dumpRemoteVideoMap[`${e.userId}-${e.streamType}`];t&&(t.data.push(i.data),t.duration>0&&Date.now()-t.startTimestamp>t.duration*1e3&&t.onDumpEnd())}})}encodeVideoDump({frame:i,onDump:e}){return e==null||e(),i}decodeVideoDump({frame:i,onDump:e}){return e==null||e(),i}loadScript(i){return new Promise((e,t)=>{this.log.info(`loading debug dialog from ${i}`);let r=document.createElement("script");r.type="text/javascript",r.onload=e,r.onerror=t,r.crossOrigin="anonymous",r.src=i,document.head.append?document.head.append(r):document.getElementsByTagName("head")[0].appendChild(r)})}},Er=rl;l(Er,"Name","Debug"),l(Er,"autoStart",!0),b([je({settings:{timeout:3e3,retries:3},onError(s,i,e){var t;(t=s==null?void 0:s.message)!=null&&t.includes("timeout")?i():e(s)}})],Er.prototype,"loadScript",1);var bh=Se(De(),1);var Rh=Symbol("instance"),dD=Symbol("abortCtrl"),lD=Symbol("cacheResult");var yh=new Map;var E_=(()=>typeof window!="undefined"&&window.__AFSM__?(e,t)=>{window.dispatchEvent(new CustomEvent(e,{detail:t}))}:typeof importScripts!="undefined"?(e,t)=>{postMessage({type:e,payload:t})}:()=>{})();function T_(s,i){let e=this._state;this._state=s;let t=s.toString();s&&this.emit(t,e),this.emit(oe.STATECHANGED,s,e,i),this.updateDevTools({value:s,old:e,err:i instanceof Error?i.message:String(i)})}var oe=class extends bh.default{constructor(i,e,t){super(),this.name=i,this.groupName=e,this._state=oe.INIT,i||(i=Date.now().toString(36)),t?Object.setPrototypeOf(this,t):t=Object.getPrototypeOf(this),e||(this.groupName=this.constructor.name);let r=t[Rh];r?this.name=r.name+"-"+r.count++:t[Rh]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let i=Object.getPrototypeOf(this),e=yh.get(i)||[],t=new Set,r=[],o=[],n=new Set,a=Object.getPrototypeOf(i);yh.has(a)&&(a.stateDiagram.forEach(d=>t.add(d)),a.allStates.forEach(d=>n.add(d))),e.forEach(({from:d,to:h,action:u})=>{typeof d=="string"?r.push({from:d,to:h,action:u}):d.length?d.forEach(p=>{r.push({from:p,to:h,action:u})}):o.push({to:h,action:u})}),r.forEach(({from:d,to:h,action:u})=>{n.add(d),n.add(h),n.add(u+"ing"),t.add(`${d} --> ${u}ing : ${u}`),t.add(`${u}ing --> ${h} : ${u} \u{1F7E2}`),t.add(`${u}ing --> ${d} : ${u} \u{1F534}`)}),o.forEach(({to:d,action:h})=>{t.add(`${h}ing --> ${d} : ${h} \u{1F7E2}`),n.forEach(u=>{u!==d&&t.add(`${u} --> ${h}ing : ${h}`)})});let c=[...t];return Object.defineProperties(i,{stateDiagram:{value:c},allStates:{value:n}}),c}static get(i){let e;return typeof i=="string"?(e=oe.instances.get(i),e||oe.instances.set(i,e=new oe(i,void 0,Object.create(oe.prototype)))):(e=oe.instances2.get(i),e||oe.instances2.set(i,e=new oe(i.constructor.name,void 0,Object.create(oe.prototype)))),e}static getState(i){var e;return(e=oe.get(i))===null||e===void 0?void 0:e.state}updateDevTools(i={}){E_(oe.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){T_.call(this,i)}};oe.STATECHANGED="stateChanged";oe.UPDATEAFSM="updateAFSM";oe.INIT="[*]";oe.ON="on";oe.OFF="off";oe.instances=new Map;oe.instances2=new WeakMap;var Nh=s=>{switch(s){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},Ia=class{constructor(i,e,t){l(this,"trackDoneOB");l(this,"startOB");l(this,"stopOB");l(this,"inputFrameCount",0);l(this,"decodedFrameCount",0);l(this,"type","auto");l(this,"config");l(this,"decoder");l(this,"_decodeSink");let{kvStatManager:r,trtc:o}=i;this.config=t.config,this.trackDoneOB=Fe(e,oe.INIT),this.stopOB=bi(this.trackDoneOB),this.startOB=bi(),t.type==="auto"?this.type="webCodecs":this.type=t.type;let n=bi(),a=c=>{let d=this.pipe(e);return n.next("STARTING"),e.log.info(`decoder type: ${this.type}`),xe(d,Nt(this.stopOB),ot(()=>{},h=>{e.log.error(h),r.addFailedEvent({key:Nh(this.type),error:h}),c>4?this.startOB.error(h):this.startOB.next(c+1)})),xe(d,So(1),rh(ea))};xe(this.startOB,Zn(0),Io(a),Nt(this.stopOB),ot(()=>{e.player.setOutput(),n.next("STARTED")},c=>{n.next("FAILED")},()=>{r.addSuccessEvent({key:Nh(this.type)}),r.addSuccessEvent({key:504702})}))}mock(i){this._decodeSink?this._decodeSink.error(i):this.startOB.next(0)}close(i){this.stopOB.next(i)}pipe(i){return es()(e=>f(this,null,function*(){this._decodeSink=e,e.defer(()=>{var r;(r=this.decoder)==null||r.close()});let{type:t}=this;try{switch(t){case"webCodecs":this.decoder=new AudioDecoder({error:r=>{i.log.error(r),e.error(4)},output:r=>{this.decodedFrameCount++,e.next(r),i.player.write(r)}});break;case"wasm":break}this.decoder.configure(this.config)}catch(r){i.log.error(r),e.error(t==="webCodecs"?2:6)}}))}decodeFrame(i){var e;this.inputFrameCount++,((e=this.decoder)==null?void 0:e.state)==="configured"&&this.decoder.decode(new EncodedAudioChunk({data:i.data,timestamp:i.timestamp,type:"key"}))}},S_={type:"object"},Aa=class{constructor(i){this.core=i;l(this,"log");l(this,"contextMap",new Map);l(this,"decodeProcessorMap",new WeakMap);this.log=i.log.createChild({id:`${this.getAlias()}`})}getAlias(){return Aa.Name}getGroup(i){return i.track.userId+i.track.streamType}getName(){return Aa.Name}getValidateRule(i){return S_}start(i){let{track:e}=i;this.decodeProcessorMap.set(e,this.decode(i)),this.core.room.audioManager.addDecodeProcessor({processor:({frame:t,track:r})=>this.decodeProcessorMap.has(r)?this.decodeProcessorMap.get(r)({frame:t,track:r}):t,type:3})}decode(i){return({frame:e,track:t})=>{if(t!==i.track)return e;if(this.contextMap.has(t))return this.contextMap.get(t).decodeFrame(e);let r=new Ia(this.core,t,i);return xe(r.trackDoneOB,So(1),ot(()=>{this.core.clearStarted(this,this.getGroup(i)),this.stop({track:t})})),this.contextMap.set(t,r),r.decodeFrame(e)}}stop({track:i}){let e=this.contextMap.get(i);!e||(e.close("stop"),this.contextMap.delete(i),this.contextMap.size===0&&this.core.room.audioManager.removeDecodeProcessor({type:3}))}update(i){let e=this.contextMap.get(i.track);if(!!e){if(i.type==="mock"){e.mock(10);return}e.close("update"),this.contextMap.set(i.track,new Ia(this.core,i.track,i))}}},hs=Aa;l(hs,"Name","AudioDecoder");var vh=0,Ca=new Set,ve=null;Ba(Ah);var I_={RtcError:P,ErrorCode:U,ErrorCodeDictionary:vt},ht=class extends Dh.EventEmitter{constructor(e,t){super();l(this,"_room");l(this,"_eventListened",new Set);l(this,"_localVideoTrack",null);l(this,"_localAudioTrack",null);l(this,"_localScreenTrack",null);l(this,"_localScreenAudioTrack",null);l(this,"_localVideoConfig",null);l(this,"_localScreenConfig",null);l(this,"_localAudioConfig",null);l(this,"_remoteVideoConfigMap",new Map);l(this,"_remoteAudioConfigMap",new Map);l(this,"_remoteAudioVolumeMap",new Map);l(this,"_remoteAudioMuteMap",new Map);l(this,"_mediaTrackMap",new WeakMap);l(this,"_log",R.createLogger({id:`t${++vh}`}));l(this,"_plugins",new Map);l(this,"_networkQuality",null);l(this,"_speakerId");l(this,"_getPCMAbortCtrl");this._room=new e(v({logger:this._log,frameWorkType:ht.frameWorkType},t)),this._log.debug(`TRTC.create() ${JSON.stringify(t,(r,o)=>r==="plugins"?o.map(n=>n.Name):o)}`),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(r){return this._room.audioManager.dump(r)}}}),t.plugins&&t.plugins.forEach(r=>{this._use(r,t.assetsPath)}),this._use(Xi,t.assetsPath),this._use(gr,t.assetsPath),this._use(hs,t.assetsPath),this._use(Er),t.enableSEI&&so&&this._use(us),this._room.on("audio-volume",r=>{!r.find(o=>o.userId==="")&&this._localAudioTrack&&r.push({userId:"",volume:Math.floor(this._localAudioTrack.getAudioLevel()*100)}),this.emit(M.AUDIO_VOLUME,{result:r.sort((o,n)=>n.volume-o.volume)})}),this._room.videoManager.on("error",r=>{this._log.error(new P({code:U.OPERATION_FAILED,extraCode:5504,message:r.message,originError:r}))}),this._listenEvents(),this._initActiveSpeaker(),Th(this,"trtc")}static create(e){}static _create(e,t){ch();let r=new ht(e,t||{});return Ca.add(r),r}get room(){return this._room}_listenEvents(){Pe(this,this._room).add("peer-join",e=>{let{userId:t}=e;this.emit(M.REMOTE_USER_ENTER,{userId:t})}).add("peer-leave",e=>{this.emit(M.REMOTE_USER_EXIT,{userId:e}),this._remoteAudioVolumeMap.delete(e)}).add("banned",e=>{this._exitRoom().then(()=>{this.emit(M.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().then(()=>{this.emit(M.ERROR,P.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(M.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let t=L(v({},e),{uplinkRTT:Math.min(e.uplinkRTT,ks),downlinkRTT:Math.min(e.downlinkRTT,ks)});this.emit(M.NETWORK_QUALITY,t)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(r=>{Pe(r,r).add("player-state-changed",o=>{let n=L(v({},o),{userId:e.userId});r.kind===m.VIDEO&&(n.streamType=vo(r.streamType)),this.emit(r.kind===m.AUDIO?M.AUDIO_PLAY_STATE_CHANGED:M.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",o=>{o.getCode()===S.PLAY_NOT_ALLOWED&&this.emit(M.AUTOPLAY_FAILED,{userId:r.userId})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(r=>{Ee(r)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:t})=>{let{userId:r}=t,o=e.audioAvailable,n=e.videoAvailable,{audioAvailable:a,videoAvailable:c}=t;a||this._remoteAudioConfigMap.delete(r),c||this._remoteVideoConfigMap.delete(`${r}_${"main"}`),t.hasAuxiliary||this._remoteVideoConfigMap.delete(`${r}_${"sub"}`),o!==a&&(this.emit(a?M.REMOTE_AUDIO_AVAILABLE:M.REMOTE_AUDIO_UNAVAILABLE,{userId:r}),a?this._onAudioAvailable({userId:r}):this._onAudioUnavailable({userId:r,muteState:t})),n!==c&&(this.emit(c?M.REMOTE_VIDEO_AVAILABLE:M.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"main"}),c?this._onVideoAvailable({userId:r,streamType:"main"}):this._onVideoUnavailable({userId:r,streamType:"main"})),e.hasAuxiliary!==t.hasAuxiliary&&(this.emit(t.hasAuxiliary?M.REMOTE_VIDEO_AVAILABLE:M.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"sub"}),t.hasAuxiliary?this._onVideoAvailable({userId:r,streamType:"sub"}):this._onVideoUnavailable({userId:r,streamType:"sub"}))}).add("sei-message",e=>{this.emit(M.SEI_MESSAGE,L(v({},e),{streamType:vo(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(M.ERROR,new P({code:U.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var o,n,a,c,d,h,u;let t={2:"big",3:"small",7:"sub"},r={rtt:Math.min(e.msg_up_stream_info.msg_network_status.uint32_rtt||((o=e.msg_down_stream_info[0])==null?void 0:o.msg_network_status.uint32_rtt)||((n=this._networkQuality)==null?void 0:n.uplinkRTT)||((a=this._networkQuality)==null?void 0:a.downlinkRTT)||0,ks),upLoss:((c=this._networkQuality)==null?void 0:c.uplinkLoss)||0,downLoss:((d=this._networkQuality)==null?void 0:d.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((h=e.msg_up_stream_info.msg_audio_status)==null?void 0:h.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((u=e.msg_up_stream_info.msg_audio_status)==null?void 0:u.uint32_audio_level)||0)/_t},video:e.msg_up_stream_info.msg_video_status.filter(p=>t[p.uint32_video_stream_type]).map(p=>({bitrate:(p.uint32_video_codec_bitrate||0)/1e3,width:p.uint32_video_width,height:p.uint32_video_height,frameRate:p.uint32_video_enc_fps,videoType:t[p.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(p=>({userId:p.msg_user_info.str_identifier,audio:{bitrate:(p.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(p.msg_audio_status.uint32_audio_level||0)/_t},video:p.msg_video_status.map(_=>({bitrate:(_.uint32_video_codec_bitrate||0)/1e3,width:_.uint32_video_width,height:_.uint32_video_height,frameRate:_.uint32_video_dec_fps,videoType:t[_.uint32_video_stream_type]}))}))};this.emit(M.STATISTICS,r)}).add("custom-message",e=>{this.emit(M.CUSTOM_MESSAGE,e)}),Pe(this,Re).add("audioInputAdded",e=>{this.emit(M.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(M.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(M.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(M.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>f(this,null,function*(){if(this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),ve&&ve.deviceId===Ms){let t=(yield Gi()).find(r=>r.deviceId===Ms);t&&ve.groupId!==t.groupId&&(ve=t,this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}})).add("audioOutputRemoved",e=>f(this,null,function*(){this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield Gi())[0];if(!t||!ve||ve.groupId===t.groupId)return;let r=ve.deviceId===e.deviceId,o=ve.deviceId===Ms&&ve.deviceId===t.deviceId;(r||o)&&(ve=t,this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}))}use(e){let t,r;"plugin"in e?(t=e.plugin,r=e.assetsPath):t=e,this._use(t,r||"https://web.sdk.qcloud.com/trtc/webrtc/v5/assets/")}_use(e,t){if(this._plugins.get(e.Name)){this._log.warn("duplicate install plugin",e.Name);return}let o=new e(Eh.call(this,{TRTC:ht,room:this._room,errorModule:I_,assetsPath:t}));this._plugins.set(e.Name,o),e.autoStart&&this.startPlugin(e.Name)}enterRoom(e){return f(this,null,function*(){var c,d;let{scene:t="rtc",enableAutoPlayDialog:r=!0,autoReceiveAudio:o=!0,autoReceiveVideo:n=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!z(e.proxy)&&e.proxy.turnServer&&((d=(c=this._room).setTurnServer)==null||d.call(c,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=r,this._room.autoReceiveAudio=o,this._room.autoReceiveVideo=n,ue(e.preferHW)&&(this._room.preferHW=e.preferHW);let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:e.role==="audience"?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language,priority:e.priority,useVp8:e.useVp8};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(a,t,ht.frameWorkType),this._checkTrackToPublish(),Xd.start()})}exitRoom(){return f(this,null,function*(){return yield this._exitRoom()})}switchRole(e,t){return f(this,null,function*(){t!=null&&t.privateMapKey&&(this._room.privateMapKey=t.privateMapKey),t!=null&&t.latencyLevel&&(this._room.latencyLevel=t.latencyLevel),yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){Ee(this),this.removeAllListeners(),this._room.destroy(),Ca.delete(this),Ca.size===0&&Xd.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),this._plugins.forEach(e=>{var t;return(t=e.destroy)==null?void 0:t.call(e)})}startLocalAudio(){return f(this,arguments,function*(e={publish:!0}){if(this._localAudioTrack){this._log.warn("local audio is already started");return}let{publish:t=!0,mute:r,option:o}=e,n=new Le(this._room.audioManager),a={},c={muted:!0};o&&(E(o.microphoneId)?E(o.audioTrack)||(a.customSource=o.audioTrack):a.deviceId=o.microphoneId,o&&K(o.captureVolume)&&n.setCaptureVolume(o.captureVolume),E(o.profile)||(z(o.profile)?Xo[o.profile]&&n.setProfile(Xo[o.profile]):n.setProfile(o.profile)),K(o.earMonitorVolume)&&(c.muted=!(o.earMonitorVolume>0),c.volume=o.earMonitorVolume),E(o.echoCancellation)||(n.profile.echoCancellation=o.echoCancellation),E(o.noiseSuppression)||(n.profile.noiseSuppression=o.noiseSuppression),E(o.autoGainControl)||(n.profile.autoGainControl=o.autoGainControl)),n.on("5",d=>{this.emit(M.ERROR,new P({code:U.DEVICE_ERROR,extraCode:5309,messageParams:{error:d}}))}),n.on("2",d=>{this.emit(M.DEVICE_CHANGED,{type:"microphone",action:"active",device:d})}),n.on("4",d=>{let h;d.error&&(h=P.convertFrom(d.error)),this.emit(M.PUBLISH_STATE_CHANGED,L(v({},d),{error:h}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId),yield n.capture(a),E(r)||n.setMute(r),Pe(n,n).add("player-state-changed",d=>{this.emit(M.AUDIO_PLAY_STATE_CHANGED,L(v({},d),{userId:""}))}),this.listeners(M.AUDIO_FRAME).length>0&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM(d=>{this.emit(ht.EVENT.AUDIO_FRAME,{data:d})})),this._getPCMAbortCtrl&&n.on("input-media-track-changed",()=>{this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("inputMediaTrackChanged"),this._getPCMAbortCtrl=this._room.audioManager.getPCM(d=>{this.emit(ht.EVENT.AUDIO_FRAME,{data:d})}))}),t&&this._room.isJoined&&this._room.publish(n).catch(()=>{}),this._localAudioTrack=n,this._localAudioConfig=L(v({},e),{publish:t}),yield this._updateAudioPlayOption({playOption:c,track:n})})}updateLocalAudio(e){return f(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:r,option:o}=e,n={};o&&(o.microphoneId?yield this._localAudioTrack.switchDevice(o.microphoneId):E(o.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(o.audioTrack)),E(o.captureVolume)||this._localAudioTrack.setCaptureVolume(o.captureVolume),E(o.earMonitorVolume)||(n.muted=!(o.earMonitorVolume>0),n.volume=o.earMonitorVolume),yield this._localAudioTrack.update3A(o)),this._room.isJoined&&!E(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),E(r)||this._localAudioTrack.setMute(r),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),fi(this._localAudioConfig,e)})}stopLocalAudio(){return f(this,null,function*(){!this._localAudioTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),Ee(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null,this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("stopLocalAudio"),delete this._getPCMAbortCtrl))})}startLocalVideo(){return f(this,arguments,function*(e={publish:!0,view:null}){if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:t,publish:r=!0,mute:o,option:n}=e,a=new me(this._room.videoManager),c={},d={};if(n&&(n.cameraId?c.deviceId=n.cameraId:E(n.useFrontCamera)?E(n.videoTrack)||(c.customSource=n.videoTrack):c.facingMode=n.useFrontCamera?m.FACING_MODE_USER:m.FACING_MODE_ENVIRONMENT,E(n.profile)||(z(n.profile)?nt[n.profile]&&a.setProfile(nt[n.profile]):a.setProfile(n.profile)),E(n.fillMode)||(d.objectFit=n.fillMode),E(n.mirror)||(d.mirror=n.mirror),E(n.small)||(to()?z(n.small)?a.small=nt[n.small]:n.small===!0?a.small=nt["120p"]:a.small=n.small:this._log.warn("small stream is not supported"))),a.on("5",h=>{this.emit(M.ERROR,new P({code:U.DEVICE_ERROR,extraCode:5308,messageParams:{error:h}}))}),a.on("2",h=>{this.emit(M.DEVICE_CHANGED,{type:"camera",action:"active",device:h})}),a.on("4",h=>{let u;h.error&&(u=P.convertFrom(h.error)),this.emit(M.PUBLISH_STATE_CHANGED,L(v({},h),{error:u}))}),this._listenOutputTrackChanged(a),yield a.capture(c),E(o)||(yield a.setMute(o)),a.mediaTrack){if(n!=null&&n.qosPreference){let h=_r(n.qosPreference);a.mediaTrack.contentHint=h}else n!=null&&n.videoTrack||(a.mediaTrack.contentHint=_r(ut.QOS_PREFERENCE_SMOOTH));a.outMediaTrack&&(a.outMediaTrack.contentHint=a.mediaTrack.contentHint)}Pe(a,a).add("player-state-changed",h=>{this.emit(M.VIDEO_PLAY_STATE_CHANGED,L(v({},h),{userId:"",streamType:"main"}))}),r&&this._room.isJoined&&this._room.publish(a).catch(()=>{}),this._localVideoTrack=a,this._localVideoConfig=L(v({},e),{view:t,publish:r}),yield this._updateVideoPlayOption({view:t,playOption:d,track:a})})}updateLocalVideo(e){return f(this,null,function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:r,mute:o,option:n}=e,a={};if(n){if(E(n.profile)||(z(n.profile)?nt[n.profile]&&this._localVideoTrack.setProfile(nt[n.profile]):this._localVideoTrack.setProfile(n.profile),(!n.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(n.cameraId))&&E(n.useFrontCamera)&&this._localVideoTrack.applyProfile()),n.cameraId?yield this._localVideoTrack.switchDevice(n.cameraId):E(n.useFrontCamera)?E(n.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(n.videoTrack)):yield this._localVideoTrack.switchDevice(n.useFrontCamera?m.FACING_MODE_USER:m.FACING_MODE_ENVIRONMENT),E(n.fillMode)||(a.objectFit=n.fillMode),E(n.mirror)||(a.mirror=n.mirror),n.qosPreference&&this._localVideoTrack.mediaTrack){let c=_r(n.qosPreference);this._localVideoTrack.mediaTrack.contentHint=c,this._localVideoTrack.outMediaTrack&&(this._localVideoTrack.outMediaTrack.contentHint=c)}if(n.small){let c=!this._localVideoTrack.small;to()?(n.small===!0?this._localVideoTrack.small=nt["120p"]:z(n.small)?this._localVideoTrack.small=nt[n.small]:this._localVideoTrack.small=n.small,this._room.videoManager.update(),c&&this._room.enableSmall(!0)):this._log.warn("small stream is not supported")}else n.small===!1&&this._localVideoTrack.small&&(delete this._localVideoTrack.small,this._room.videoManager.update(),this._room.enableSmall(!1))}this._room.isJoined&&!E(r)&&(r&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._localVideoConfig.publish&&!r&&this._room.unpublish(this._localVideoTrack).catch(()=>{})),E(o)||(yield this._localVideoTrack.setMute(o)),yield this._updateVideoPlayOption({view:t,playOption:a,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),fi(this._localVideoConfig,e)})}stopLocalVideo(){return f(this,null,function*(){!this._localVideoTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),Ee(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return f(this,arguments,function*(e={publish:!0,view:null}){if(this._localScreenTrack){this._log.warn("screen share is already started");return}let{view:t=null,publish:r=!0,option:o}=e,n=new rt(this._room.videoManager);n.on("4",u=>{let p;u.error&&(p=P.convertFrom(u.error)),this.emit(M.PUBLISH_STATE_CHANGED,L(v({},u),{error:p}))}),this._listenOutputTrackChanged(n),e.streamType==="main"&&(n.mediaType=4);let a=null,c={},d={};o&&(E(o.profile)||(z(o.profile)?Qo[o.profile]&&n.setProfile(Qo[o.profile]):n.setProfile(o.profile)),o.systemAudio&&(c.systemAudio=!0,c.echoCancellation=o.echoCancellation,c.noiseSuppression=o.noiseSuppression,c.autoGainControl=o.autoGainControl),E(o.fillMode)||(d.objectFit=o.fillMode),o.videoTrack&&(c.videoTrack=o.videoTrack),o.audioTrack&&(c.audioTrack=o.audioTrack),o.captureElement&&(c.captureElement=o.captureElement),o.preferDisplaySurface&&(c.preferDisplaySurface=o.preferDisplaySurface));let h=yield n.capture(c);if(o!=null&&o.qosPreference){let u=_r(o.qosPreference);n.mediaTrack.contentHint=u}else o!=null&&o.videoTrack||(n.mediaTrack.contentHint=_r(ut.QOS_PREFERENCE_CLEAR));if(n.mediaTrack.addEventListener(m.ENDED,()=>{this._stopScreenShare(),this.emit(M.SCREEN_SHARE_STOPPED)}),h.getAudioTracks()[0]&&(a=new Kt(this._room.audioManager),yield a.setInputMediaStreamTrack(h.getAudioTracks()[0]),this._speakerId&&a.setAudioOutput(this._speakerId)),Pe(n,n).add("player-state-changed",u=>{this.emit(M.VIDEO_PLAY_STATE_CHANGED,L(v({},u),{userId:"",streamType:"sub"}))}),r&&this._room.isJoined){let u=[n];a&&u.push(a),this._room.publish(...u).catch(()=>{})}this._localScreenTrack=n,this._localScreenAudioTrack=a,this._localScreenConfig=L(v({},e),{view:t,publish:r}),yield this._updateVideoPlayOption({view:t,playOption:d,track:n})})}updateScreenShare(e){return f(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:r,option:o}=e,n={};if(o&&(E(o.fillMode)||(n.objectFit=o.fillMode),o.qosPreference)){let a=_r(o.qosPreference);this._localScreenTrack.mediaTrack.contentHint=a}this._room.isJoined&&!E(r)&&(r&&!this._localScreenConfig.publish&&(this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch(()=>{})),this._localScreenConfig.publish&&!r&&(this._room.unpublish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.unpublish(this._localScreenAudioTrack).catch(()=>{}))),yield this._updateVideoPlayOption({view:t,playOption:n,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),fi(this._localScreenConfig,e)})}stopScreenShare(){return f(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return f(this,null,function*(){let{view:t,userId:r,streamType:o,option:n}=e,a=`${r}_${o}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${r}, streamType:${o}`);return}let c=this._room.remotePublishedUserMap.get(r);if(!c)return;let d={},h=o==="main"?c.remoteVideoTrack:c.remoteAuxiliaryTrack;this._listenOutputTrackChanged(h),n&&(E(n.fillMode)||(d.objectFit=n.fillMode),E(n.mirror)||(d.mirror=n.mirror),d.canvasRender=n.canvasRender,o==="main"&&!E(n.small)&&(c.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,h.user))),yield this._room.subscribe(h),yield this._updateVideoPlayOption({view:t,playOption:d,track:h}),this._emitTrackEvent(h),this._remoteVideoConfigMap.set(a,{config:e}),n&&!E(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:h,view:t,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:n==null?void 0:n.viewRoot})})}updateRemoteVideo(e){return f(this,null,function*(){var D,B;let{view:t,userId:r,streamType:o,option:n}=e,a=`${r}_${o}`,c=this._remoteVideoConfigMap.get(a);if(!c||!this._room.remotePublishedUserMap.has(r))return;let d={};n&&(E(n.fillMode)||(d.objectFit=n.fillMode),E(n.mirror)||(d.mirror=n.mirror));let h=null,u=this._room.remotePublishedUserMap.get(r);if(o==="main"&&(u==null?void 0:u.muteState.hasVideo)&&(h=u.remoteVideoTrack),o==="sub"&&(u==null?void 0:u.muteState.hasAuxiliary)&&(h=u.remoteAuxiliaryTrack),!h)return;let{config:p}=c;o==="main"&&n&&!E(n.small)&&this._room.changeType(n.small,h.user),yield this._updateVideoPlayOption({view:t,playOption:d,track:h,prevConfig:p}),fi(p,e);let _=E(n==null?void 0:n.receiveWhenViewVisible)?(D=p.option)==null?void 0:D.receiveWhenViewVisible:n.receiveWhenViewVisible,I=E(t)?p.view:t,C=E(n==null?void 0:n.viewRoot)?(B=p.option)==null?void 0:B.viewRoot:n.viewRoot;this._observeView({remoteTrack:h,view:I,receiveWhenViewVisible:_,viewRoot:C})})}stopRemoteVideo(e){return f(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,t=!0){return f(this,null,function*(){let r=[],o=this._room.remotePublishedUserMap.get(e.userId);if(o){let{muteState:a,remoteVideoTrack:c,remoteAuxiliaryTrack:d}=o;e.streamType==="main"&&(c.stop(),a.hasVideo&&r.push(c)),e.streamType==="sub"&&(d.stop(),a.hasAuxiliary&&r.push(d))}for(let a of r)t&&(yield this._room.unsubscribe(a),this._mediaTrackMap.get(a.outMediaTrack)===a.userId&&this._mediaTrackMap.delete(a.outMediaTrack));let n=this._remoteVideoConfigMap.get(`${e.userId}_${e.streamType}`);n&&n.observer&&n.observer.disconnect(),this._remoteVideoConfigMap.delete(`${e.userId}_${e.streamType}`)})}muteRemoteAudio(e,t){return f(this,null,function*(){if(e==="*")if(t)yield this._stopRemoteAudio({userId:e});else{let r=[...this._room.remotePublishedUserMap.values()];for(let o of r)o.muteState.hasAudio&&!this._remoteAudioConfigMap.has(o.userId)&&(yield this._startRemoteAudio({userId:o.userId}))}else t?yield this._stopRemoteAudio({userId:e}):this._remoteAudioConfigMap.has(e)||(yield this._startRemoteAudio({userId:e}));this._remoteAudioMuteMap.set(e,t)})}setRemoteAudioVolume(e,t){if(e==="*"){let r=[...this._room.remotePublishedUserMap.values()];for(let o of r)this._remoteAudioVolumeMap.set(o.userId,t),o.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:o.remoteAudioTrack})}else if(e){let r=this._room.remotePublishedUserMap.get(e);this._remoteAudioVolumeMap.set(e,t),r&&r.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:r.remoteAudioTrack})}}startPlugin(e,t){return f(this,null,function*(){return e.start(t)})}updatePlugin(e,t){return f(this,null,function*(){return e.update(t)})}stopPlugin(e,t){return f(this,null,function*(){return e.stop(t)})}enableAudioVolumeEvaluation(e=2e3,t=!1){this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,r){return this.listeners(e).includes(t)?this:(this._log.debug("on",e),super.on(e,t,r),this._eventListened.add(e),e===ht.EVENT.AUDIO_FRAME&&!this._getPCMAbortCtrl&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM(o=>{this.emit(ht.EVENT.AUDIO_FRAME,{data:o})}),this._localAudioTrack&&this._localAudioTrack.on("input-media-track-changed",()=>{this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("inputMediaTrackChanged"),this._getPCMAbortCtrl=this._room.audioManager.getPCM(o=>{this.emit(ht.EVENT.AUDIO_FRAME,{data:o})}))})),this)}emit(e,...t){try{_h.has(e)&&this._log.debug(`emit ${e} ${JSON.stringify(t)}`)}catch(r){}return super.emit(e,...t)}off(e,t,r){var o,n;return this._log.debug("off",e),e==="*"?(this._eventListened.clear(),this.removeAllListeners(),(o=this._getPCMAbortCtrl)==null||o.abort("off"),delete this._getPCMAbortCtrl):(super.off(e,t,r),e===ht.EVENT.AUDIO_FRAME&&((n=this._getPCMAbortCtrl)==null||n.abort("off"),delete this._getPCMAbortCtrl)),this}getAudioTrack(e={userId:"",streamType:"main"}){let t,r=null,o="main",n=!1;if(z(e)?t=e:(t=e.userId,n=e.processed===!0,e.streamType&&(o=e.streamType)),t){let a=this._room.remotePublishedUserMap.get(t);a&&(r=a.remoteAudioTrack)}else r=o==="sub"?this._localScreenAudioTrack:this._localAudioTrack;return r?n&&r.outMediaTrack&&r.outMediaTrack!==r.mediaTrack?r.outMediaTrack.clone():r.mediaTrack:null}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:t="",streamType:r="main",processed:o=!1}=e,n=null;if(t==="")r==="main"&&this._localVideoTrack&&(n=this._localVideoTrack),r==="sub"&&this._localScreenTrack&&(n=this._localScreenTrack);else{let a=this._room.remotePublishedUserMap.get(t);a&&(n=r==="main"?a.remoteVideoTrack:a.remoteAuxiliaryTrack)}return n?o&&n.outMediaTrack&&n.outMediaTrack!==n.mediaTrack?n.outMediaTrack.clone():n.mediaTrack:null}getVideoSnapshot(e={}){let{userId:t,streamType:r="main"}=e;if(t){let o=this._room.remotePublishedUserMap.get(t);if(r==="main"&&(o==null?void 0:o.muteState.hasVideo))return o.remoteVideoTrack.getVideoFrame();if(r==="sub"&&(o==null?void 0:o.muteState.hasAuxiliary))return o.remoteAuxiliaryTrack.getVideoFrame()}else{if(r==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(r==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(e){var t,r;this._speakerId=e,(t=this._localAudioTrack)==null||t.setAudioOutput(e),(r=this._localScreenAudioTrack)==null||r.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(o=>o.remoteAudioTrack.setAudioOutput(e))}setCurrentSpeaker(e){return f(this,null,function*(){(yield Gi()).forEach(r=>{r.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}),ve=r)}),this._log.warn('the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: https://web.sdk.qcloud.com/trtc/webrtc/v5/doc/en/TRTC.html#.setCurrentSpeaker')})}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return f(this,null,function*(){let{userId:t}=e;if(this._remoteAudioConfigMap.has(t)){this._log.warn(`remote audio has already started. userId:${t}`);return}let r=this._room.remotePublishedUserMap.get(t);if(!r)return;let o={},n=r.remoteAudioTrack;this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId);try{let a=this._remoteAudioVolumeMap.get(t),c=K(a)?a:100;o.volume=c,this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(n),xe(Fe(n,"decode-failed"),Nt(Fe(n,oe.INIT)),ot(()=>{this.startPlugin(hs.Name,{track:n,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:o,track:n})}catch(a){throw this._remoteAudioConfigMap.delete(t),a}this._emitTrackEvent(n)})}_stopRemoteAudio(e,t=!0){return f(this,null,function*(){let r=this._room.remotePublishedUserMap.get(e.userId);r&&(r.remoteAudioTrack.stop(),r.muteState.hasAudio&&t&&(yield this._room.unsubscribe(r.remoteAudioTrack)),this._mediaTrackMap.get(r.remoteAudioTrack.outMediaTrack)===e.userId&&this._mediaTrackMap.delete(r.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete(`${e.userId}`)})}_updateVideoPlayOption(n){return f(this,arguments,function*({view:e,playOption:t,track:r,prevConfig:o}){if(r.setMirror(t.mirror),E(e)&&o&&o.view&&!Tc(t)){let a=zs(o.view);a.length>0&&(yield r.play(a,t))}if(!E(e)){let a=zs(e);a.length>0?yield r.play(a,t):r.stop()}})}_updateAudioPlayOption(o){return f(this,arguments,function*({playOption:e={},track:t,prevConfig:r}){if(!t.isPlayCalled)try{yield t.play(null,e)}catch(n){}E(e.muted)||t.setPlayerMute(e.muted),E(e.volume)||t.setAudioVolume(e.volume/100)})}_listenOutputTrackChanged(e){e.listeners("output-media-track-changed").length===0&&e.on("output-media-track-changed",()=>this._emitTrackEvent(e,!1))}_emitTrackEvent(e,t=!0){let r=e.isRemote?e.userId:"";!e.outMediaTrack||t&&this._mediaTrackMap.get(e.outMediaTrack)===r||(this._mediaTrackMap.set(e.outMediaTrack,r),this.emit(M.TRACK,{userId:r,streamType:vo(e.streamType),track:e.outMediaTrack}))}_checkTrackToPublish(){var t,r,o;let e=[];if(((t=this._localAudioConfig)==null?void 0:t.publish)&&this._localAudioTrack&&e.push(this._localAudioTrack),((r=this._localVideoConfig)==null?void 0:r.publish)&&this._localVideoTrack&&e.push(this._localVideoTrack),(o=this._localScreenConfig)!=null&&o.publish&&(this._localScreenTrack&&e.push(this._localScreenTrack),this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack)),e.length!==0)return this._room.publish(...e).catch(()=>{})}_observeView({remoteTrack:e,view:t,receiveWhenViewVisible:r=!1,viewRoot:o}){if(E(t))return;let n=this._remoteVideoConfigMap.get(`${e.userId}_${vo(e.streamType)}`);if(!n)return;let a=n.observer||void 0;if(t===null||_e(t)&&t.length===0||!r){a==null||a.disconnect(),e.isSubscribed||this._room.subscribe(e).catch(()=>{});return}let d=n.visibleViewMap||new Map,h=-1;(!a||a.root!==o)&&(a==null||a.disconnect(),d.clear(),a=new IntersectionObserver(p=>{p.forEach(_=>{d.set(_.target,_.isIntersecting)}),clearTimeout(h),h=window.setTimeout(()=>{[...d.values()].find(I=>I)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:o}));let u=new Set(zs(t));d.forEach((p,_)=>{u.has(_)||(a.unobserve(_),d.delete(_))}),u.forEach(p=>{d.set(p,!0),a.observe(p)}),a.takeRecords().forEach(p=>{d.set(p.target,p.isIntersecting)}),n.visibleViewMap=d,n.observer=a}_exitRoom(){return f(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(e=>{this._stopRemoteAudio({userId:e}).catch()}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let t=e.includes("main")?"main":"sub",r=e.split(`_${t}`)[0];r&&this._stopRemoteVideo({userId:r,streamType:t}).catch()}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._remoteAudioVolumeMap.clear(),Sh(this),this._room.remotePublishedUserMap.forEach(e=>{Ee(e.remoteAudioTrack),Ee(e.remoteVideoTrack),Ee(e.remoteAuxiliaryTrack)})})}_stopScreenShare(){return f(this,null,function*(){var e;if(!!this._localScreenTrack){if(this._room.isJoined){let t=[this._localScreenTrack];this._localScreenAudioTrack&&t.push(this._localScreenAudioTrack),yield(e=this._room)==null?void 0:e.unpublish(...t).catch(()=>{})}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),Ee(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_initActiveSpeaker(){return f(this,null,function*(){if(ve&&!Yr(ve))this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:ve});else{let e=yield Gi();if(e[0]&&!Yr(e[0]))ve=e[0],this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]});else{let t=({track:r})=>{r.kind==="audio"&&(!ve||Yr(ve))&&(this._initActiveSpeaker(),T.off("102",this._initActiveSpeaker))};T.on("102",t)}}})}_onAudioAvailable({userId:e}){let t=this._remoteAudioMuteMap.has(e)?this._remoteAudioMuteMap.get(e):this._remoteAudioMuteMap.get("*");(t===!1||this._room.autoReceiveAudio&&!t)&&this._doStartRemoteAudio({userId:e}).catch(()=>{})}_onVideoAvailable({userId:e,streamType:t}){if(!this._room.autoReceiveVideo)return;let r=this._room.remotePublishedUserMap.get(e);if(r){let o=t==="main"?r.remoteVideoTrack:r.remoteAuxiliaryTrack;this._room.subscribe(o).then(()=>{this._emitTrackEvent(o)}).catch(()=>{})}}_onAudioUnavailable({userId:e,muteState:t}){t.hasAudio&&t.audioMuted||this._stopRemoteAudio({userId:e},!1).catch(()=>{})}_onVideoUnavailable({userId:e,streamType:t}){this._stopRemoteVideo({userId:e,streamType:t},!1).catch(()=>{})}sendSEIMessage(e,t){var o;let r=this._plugins.get("SEI");r&&(r.update({buffer:e,options:L(v({seiPayloadType:243},t),{small:!!((o=this._localVideoTrack)!=null&&o.small)})}),N.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,r;(r=(t=this._room).sendCustomMessage)==null||r.call(t,e),N.addCount({key:500001,useUV:!0})}static setLogLevel(e,t){R.setLogLevel(e),E(t)||(t?R.enableUploadLog():R.disableUploadLog())}static isSupported(){return kn()}static getCameraList(e=!0){return tt(e)}static getMicrophoneList(e=!0){return Xe(e)}static getSpeakerList(e=!0){return Gi(e)}static setCurrentSpeaker(e){return f(this,null,function*(){(yield Gi()).forEach(r=>{r.deviceId===e&&(Ca.forEach(o=>{o._setCurrentSpeaker(e),o.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:r})}),ve=r)})})}static _addKVStat({type:e,key:t,value:r,base:o,useUV:n,version:a}){switch(a&&(nr.version=a),e){case"count":nr.addCount({key:t,useUV:n});break;case"enum":nr.addEnum({key:t,value:r,useUV:n});break;case"number":nr.addNumber({key:t,value:r,split:o});break}}},X=ht;l(X,"_loggerManager",R),l(X,"EVENT",M),l(X,"ERROR_CODE",U),l(X,"TYPE",ut),l(X,"frameWorkType",30),b([ae({replaceArg:s=>({argIndex:0,value:{name:"plugin"in s?s.plugin.Name:s.Name,assetsPath:"assetsPath"in s?s==null?void 0:s.assetsPath:"default"}})})],X.prototype,"use",1),b([Ue(Ne.TRTC.enterRoom),ji("room",([s],[i])=>(s.roomId||s.strRoomId)===(i.roomId||i.strRoomId)&&s.userId===i.userId&&s.sdkAppId===i.sdkAppId),G(s=>function(i){return this._log.setUserId(i.userId),this._log.setSdkAppId(i.sdkAppId),s.call(this,i)}),ae()],X.prototype,"enterRoom",1),b([ae()],X.prototype,"exitRoom",1),b([Ue(Ne.TRTC.switchRole),fr("room",{merge:(s,i)=>i}),ae()],X.prototype,"switchRole",1),b([ae()],X.prototype,"destroy",1),b([Ue(Ne.TRTC.startLocalAudio),ji("audio",([s],[i])=>{var e,t;return((e=s==null?void 0:s.option)==null?void 0:e.microphoneId)===((t=i==null?void 0:i.option)==null?void 0:t.microphoneId)}),ae()],X.prototype,"startLocalAudio",1),b([Ue(Ne.TRTC.updateLocalAudio),fr("audio",{debounce:{delay:200,getKey:()=>`${vh}-localAudio`,isNeedToDebounce:s=>{var i;return!E((i=s.option)==null?void 0:i.captureVolume)}}}),ae()],X.prototype,"updateLocalAudio",1),b([qi("audio"),ae()],X.prototype,"stopLocalAudio",1),b([Ue(Ne.TRTC.startLocalVideo),ji("video",([s],[i])=>{var e,t;return((e=s==null?void 0:s.option)==null?void 0:e.cameraId)===((t=i==null?void 0:i.option)==null?void 0:t.cameraId)}),ae()],X.prototype,"startLocalVideo",1),b([Ue(Ne.TRTC.updateLocalVideo),fr("video"),ae()],X.prototype,"updateLocalVideo",1),b([qi("video"),ae()],X.prototype,"stopLocalVideo",1),b([Ue(Ne.TRTC.startScreenShare),ji("screen",()=>!0),ae()],X.prototype,"startScreenShare",1),b([Ue(Ne.TRTC.updateScreenShare),fr("screen"),ae()],X.prototype,"updateScreenShare",1),b([ae()],X.prototype,"stopScreenShare",1),b([Ue(Ne.TRTC.startRemoteVideo),ji(s=>`v${s.userId}${s.streamType}`,()=>!0),ae({getRemoteId:s=>`${s.userId}_${s.streamType}`})],X.prototype,"startRemoteVideo",1),b([Ue(Ne.TRTC.updateRemoteVideo),fr(s=>`v${s.userId}${s.streamType}`),ae({getRemoteId:s=>`${s.userId}_${s.streamType}`})],X.prototype,"updateRemoteVideo",1),b([Ue(Ne.TRTC.stopRemoteVideo),G(s=>function(i){return f(this,null,function*(){if(i.userId==="*"){let e=[];return this._room.remotePublishedUserMap.forEach(t=>{this._remoteVideoConfigMap.has(`${t.userId}_${"main"}`)&&e.push(this.stopRemoteVideo({streamType:"main",userId:t.userId}).catch(()=>{})),this._remoteVideoConfigMap.has(`${t.userId}_${"sub"}`)&&e.push(this.stopRemoteVideo({streamType:"sub",userId:t.userId}).catch(()=>{}))}),Promise.all(e)}return s.call(this,i)})}),ae({getRemoteId:s=>`${s.userId}_${s.streamType}`})],X.prototype,"stopRemoteVideo",1),b([qi(s=>`v${s.userId}${s.streamType}`)],X.prototype,"_stopRemoteVideo",1),b([Ue(...Ne.TRTC.muteRemoteAudio),ae({getRemoteId:s=>s})],X.prototype,"muteRemoteAudio",1),b([Wd(...Ne.TRTC.setRemoteAudioVolume),Ih(200,s=>s),ae({getRemoteId:s=>s})],X.prototype,"setRemoteAudioVolume",1),b([ga("start"),bt(s=>{var i;return(i=s.afterStart)==null?void 0:i.call(s)}),ji((s,i)=>s.disableRandomCall?null:s.getAlias()+s.getGroup(i)),ae({replaceArg:s=>({argIndex:0,value:s.getName()}),getKVReportKey:s=>Dc[s.getName()],ignoreLog:s=>s.getName()==="Debug"})],X.prototype,"startPlugin",1),b([ga("update"),fr((s,i)=>s.disableRandomCall?null:s.getAlias()+s.getGroup(i)),ae({replaceArg:s=>({argIndex:0,value:s.getName()}),getKVReportKey:s=>Oc[s.getName()]})],X.prototype,"updatePlugin",1),b([ga("stop"),qi((s,i)=>{if(s.disableRandomCall)return null;let e=s.getGroup(i),t=s.getAlias();return e==="*"?new RegExp(`${t}.*`):t+e}),ae({replaceArg:s=>({argIndex:0,value:s.getName()}),getKVReportKey:s=>Mc[s.getName()]})],X.prototype,"stopPlugin",1),b([Wd(...Ne.TRTC.enableAudioVolumeEvaluation)],X.prototype,"enableAudioVolumeEvaluation",1),b([ae()],X.prototype,"getVideoSnapshot",1),b([ae()],X.prototype,"_setCurrentSpeaker",1),b([ji(s=>`a${s.userId}`,()=>!0)],X.prototype,"_startRemoteAudio",1),b([G(s=>function(i){return f(this,null,function*(){return i.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(e=>this._stopRemoteAudio(L(v({},i),{userId:e.userId})).catch(()=>{}))):s.call(this,i)})}),qi(s=>`a${s.userId}`)],X.prototype,"_stopRemoteAudio",1),b([qi("room")],X.prototype,"_exitRoom",1),b([qi("screen")],X.prototype,"_stopScreenShare",1),b([Ue(...Ne.TRTC.sendSEIMessage),Hd({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...s)=>s[0].byteLength})],X.prototype,"sendSEIMessage",1),b([Ue(Ne.TRTC.sendCustomMessage),Hd({timesInSecond:30,maxSizeInSecond:8e3,getSize:s=>s.data.byteLength})],X.prototype,"sendCustomMessage",1),b([Ue(Ne.TRTC.create)],X,"_create",1);var Do=X;var sl=class{constructor(){this._set=new Set;T.on(g.LEAVE_SUCCESS,this.delete,this)}add({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,e||i.roomId,i.sdkAppId,i.useStringRoomId);this._set.add(t)}delete({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,i.roomId||e,i.sdkAppId,i.useStringRoomId);this._set.delete(t)}getKey(i,e,t,r){return`${t}_${e}_${i}_${r}`}isJoined({userId:i,roomId:e,sdkAppId:t,room:r}){return r.scene==="rtc"?!1:this._set.has(this.getKey(i,e,t,r.useStringRoomId))}};function A_(){return f(this,null,function*(){let s,i;try{let u=yield Xe();s=u&&u.length}catch(u){}try{let u=yield tt();i=u&&u.length}catch(u){}let e={microphone:s,camera:i},{isH264EncodeSupported:t,isVp8EncodeSupported:r,isH264DecodeSupported:o,isVp8DecodeSupported:n}=this.checkSystemResult.detail,a=Wt.basis(),c={webRTC:a.isWebRTCSupported,getUserMedia:a.isGetUserMediaSupported,webSocket:a.isWebSocketsSupported,screenShare:a.isScreenShareSupported,webAudio:a.isWebAudioSupported,h264Encode:t,h264Decode:o,vp8Encode:r,vp8Decode:n},d={browser:a.browser,os:a.os,trtc:c,devices:e},h={isWebCodecSupported:a.isWebCodecSupported,isMediaSessionSupported:a.isMediaSessionSupported,isWebTransportSupported:a.isWebTransportSupported};Y.uploadEvent({log:`trtcstats-${JSON.stringify(d)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(d)}`),Y.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(h)}`,userId:this.userId})})}function Oh(){return G(s=>{let i=new sl;return function(e,t,r){return f(this,null,function*(){let o=String(e.roomId||e.strRoomId);if(this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.userSig=e.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=t,e.privateMapKey=e.privateMapKey||"",this.isJoined)throw new y({code:S.INVALID_OPERATION,message:w({key:x.INVALID_JOIN})});if(this.checkDestroy(),i.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this}))throw new y({code:S.INVALID_OPERATION,message:w({key:x.REPEAT_JOIN,data:this.userId})});i.add({room:this,roomId:o}),this.role=e.role===21?"audience":"anchor",this._log.info(`Join() => joining room: ${o} useStringRoomId: ${this.useStringRoomId} scene: ${this.scene} role: ${this.role}`),T.emit(g.JOIN_START,{room:this,roomId:o,params:e});let n=Be.getEnv();n||(n=si.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(zo.OLD_CLOUD_LADDER)?n=si.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(zo.WEBRTC)&&(n=si.WEBRTC))),Y.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),Wt.checkSystemRequirementsInternal().then(a=>{this.checkSystemResult=a,A_.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Be.getEnv()&&(yield this.schedule(e,r));let a=yield s.call(this,e,t,r);return this.roomId=o,this._joinedTimestamp=Be.performanceNow(),T.emit(g.JOIN_SUCCESS,{room:this}),r===30&&!e.component&&Y.uploadEvent({log:`stat-conv-${Number(li)}-${location.hostname}`,userId:this.userId}),a}catch(a){throw i.delete({room:this,roomId:o}),T.emit(g.JOIN_FAILED,{room:this,error:a}),a}})}})}var Mh=()=>G(s=>function(...i){return f(this,null,function*(){T.emit(g.LEAVE_START,{room:this}),yield s.call(this),T.emit(g.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function kh(){return G(s=>function(...i){let e=s.apply(this,i);return i.forEach(t=>!t.isSubscribed&&t.subscribe(e)),e})}var Lh=Se(De());var pe={SETUP_SUCCESS:"1",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",RECONNECT_FAILED:"4",SETUP_FAILED:"5",DISCONNECTED:"6"};var Dt={CLIENT_BANNED:9,CHANNEL_SETUP_RESULT:19,CHANNEL_RECONNECT_RESULT:514,JOIN_ROOM_RESULT:20,PEER_JOIN:4134,PEER_LEAVE:4135,STREAM_ADDED:16,STREAM_REMOVED:18,UPLINK_NETWORK_STATS:22,UPDATE_REMOTE_MUTE_STAT:23,PUBLISH_RESULT:4098,PUBLISH_STATE_CHANGE_RESULT:4112,UNPUBLISH_RESULT:4100,SUBSCRIBE_RESULT:4102,UNSUBSCRIBE_RESULT:4104,SUBSCRIBE_CHANGE_RESULT:4106,MUTE_RESULT:4108,UPDATE_OFFER_RESULT:4128,START_PUBLISH_TENCENT_CDN_RES:1286,STOP_PUBLISH_TENCENT_CDN_RES:1288,START_PUBLISH_GIVEN_CDN_RES:777,STOP_PUBLISH_GIVEN_CDN_RES:779,START_MIX_TRANSCODE_RES:781,STOP_MIX_TRANSCODE_RES:783,START_PUBLISH_CDN_STREAM_RES:8196,UPDATE_PUBLISH_CDN_STREAM_RES:8198,STOP_PUBLISH_CDN_STREAM_RES:8200,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772,REBUILD_PEER_CONNECTION_RES:4150,SPC_PUBLISH_RESULT:4146,SPC_SUBSCRIBE_RESULT:4156,ABILITY_STATUS_REPORT_RESULT:4158,SERVER_FIRST_PACKAGE_RECEIVED:5e3,RECEIVE_CUSTOM_MSG:4140},Ph=[Dt.UPDATE_REMOTE_MUTE_STAT,Dt.UPLINK_NETWORK_STATS,Dt.USER_LIST_RES,Dt.MUTE_RESULT,Dt.SERVER_FIRST_PACKAGE_RECEIVED,Dt.RECEIVE_CUSTOM_MSG],V={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",START_PUBLISH_CDN_STREAM_RES:"start-publish-cdn-stream-res",UPDATE_PUBLISH_CDN_STREAM_RES:"update-publish-cdn-stream-res",STOP_PUBLISH_CDN_STREAM_RES:"stop-publish-cdn-stream-res",USER_LIST_RES:"user-list-res",SWITCH_ROLE_RES:"switch_role_res",MUTE_RESULT:"mute-result",UPDATE_CONSTRAINT_CONFIG_RES:"update-contraint-config-res",REBUILD_PEER_CONNECTION_RES:"rebuild-pc-res",SPC_PUBLISH_RESULT:"spc-publish-result",SPC_SUBSCRIBE_RESULT:"spc-subscribe-result",ABILITY_STATUS_REPORT_RESULT:"ability-status-report",SERVER_FIRST_PACKAGE_RECEIVED:"first-pkg-received",RECEIVE_CUSTOM_MSG:"receive-custom-msg"},W={PUBLISH_CHANGE:"publish_change",JOIN_ROOM:"join",LEAVE_ROOM:"leave",ON_QUALITY_REPORT:"quality_report",UPDATE_MUTE_STAT:"mute_uplink",PUBLISH:"publish",PUBLISH_STATE_CHANGE:"publish_state_change",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",RECEIVE_DATA_USER_LIST:"receive_data_userlist",UNSUBSCRIBE:"unsubscribe",SUBSCRIBE_CHANGE:"subscribe_change",START_PUBLISH_TENCENT_CDN:"start_publishing",STOP_PUBLISH_TENCENT_CDN:"stop_publishing",START_PUBLISH_GIVEN_CDN:"start_push_user_cdn",STOP_PUBLISH_GIVEN_CDN:"stop_push_user_cdn",START_MIX_TRANSCODE:"start_mcu_mix",STOP_MIX_TRANSCODE:"stop_mcu_mix",START_PUBLISH_CDN_STREAM:"start_publish_cdn_stream",UPDATE_PUBLISH_CDN_STREAM:"update_publish_cdn_stream",STOP_PUBLISH_CDN_STREAM:"stop_publish_cdn_stream",GET_USER_LIST:"get_user_list",SWITCH_ROLE:"change_role",UPDATE_CONSTRAINT_CONFIG:"update_constraint_config",REBUILD_PEER_CONNECTION:"rebuild_pc",READY_TO_RECEIVE_DATA:"ready_to_receive",SPC_JOIN_ROOM:"join/v2",SPC_PUBLISH:"publish/v2",SPC_SUBSCRIBE:"subscribe/v3",ABILITY_STATUS_REPORT:"ability_status_report",RECONNECT_WS:"reconnect",SEND_CUSTOM_MSG:"channel_msg"};var Ra=new Set;function xh(s){let i=[...Ra.values()].find(e=>e.room.userId===s&&!e.room.isJoined);return i||null}var ms=class extends Lh.default{constructor(e){var r,o;super();l(this,"room");l(this,"url");l(this,"backupUrl");l(this,"race");l(this,"destroyed",!1);l(this,"_socketInUse");l(this,"_socket");l(this,"_backupSocket");l(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0});l(this,"_currentState","DISCONNECTED");l(this,"_isReconnecting",!1);l(this,"_seq",0);l(this,"_log");l(this,"_lastMessageTime",-1);l(this,"_connnectStartTime",-1);l(this,"_stopConnectRetry");l(this,"bytesSent",0);l(this,"bytesReceived",0);l(this,"keepAlive",!1);l(this,"signalDomainWhenUnifiedProxy");l(this,"stopKeepAliveTimeout");l(this,"rtt",0);this.room=e.room,this.race=E(e.race)?!0:e.race,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy,(((o=(r=this.room.scheduleResult)==null?void 0:r.config)==null?void 0:o.keepAliveClient)||0)-Ra.size>0&&this.room.enableSPC&&(this.keepAlive=!0,Ra.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=R.createLogger({id:"ws",userId:this.userId,sdkAppId:this.sdkAppId}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get urlParam(){let e=`?sdkAppId=${encodeURIComponent(this.sdkAppId)}&userId=${encodeURIComponent(this.userId)}&userSig=${encodeURIComponent(this.userSig)}&keepAlive=${encodeURIComponent(Number(this.keepAlive))}`;this.signalDomainWhenUnifiedProxy&&(e+=`&signalDomain=${encodeURIComponent(this.signalDomainWhenUnifiedProxy)}`);let t=new URLSearchParams(location.search).get("clientIp");return t&&(e+=`&clientIp=${t}`),this.race?`${e}&race=1`:e}get _urlWithParam(){return`${this.url}${this.race?"/v2/ws":""}${this.urlParam}`}get _backupUrlWithParam(){return`${this.backupUrl}${this.race?"/v2/ws":""}${this.urlParam}`}get isConnected(){return this._currentState==="CONNECTED"}get isConnecting(){return this._currentState==="CONNECTING"}get sdkAppId(){return this.room.sdkAppId}get userId(){return this.room.userId}get userSig(){return this.room.userSig}get isOnline(){return this._currentState==="CONNECTED"&&Date.now()-this._lastMessageTime<12*1e3}connect(){return f(this,arguments,function*(e=10*1e3){if(this.isConnected)return Promise.resolve();this._log.info(`connect to [${this.url}, ${this.backupUrl}]${e?` timeout: ${e}`:""} keepAlive: ${Number(this.keepAlive)}`),this.emitConnectionStateChanged("CONNECTING"),this._connnectStartTime=k();let t=[this.connectWS({url:this._urlWithParam,isMain:!0,timeout:e})];this.race&&this._backupUrlWithParam!==this._urlWithParam&&t.push(this.connectWS({url:this._backupUrlWithParam,isMain:!1,timeout:e})),this._socketInUse=yield js(t),this.unbindAndCloseSocket(this._socketInUse===this._socket?m.BACKUP:m.MAIN),this.emitConnectionStateChanged("CONNECTED")})}connectWS({url:e,timeout:t,isMain:r}){let o=new WebSocket(e);this.bindSocket(o),r?this._socket=o:this._backupSocket=o;let n=-1;return new Promise((a,c)=>{o.onclose=c,o.onerror=c,o.onopen=()=>a(o),t&&(n=setTimeout(()=>{this.unbindAndCloseSocket(r?m.MAIN:m.BACKUP),c(new y({code:S.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))},t))}).finally(()=>{o.onclose=null,o.onerror=null,o.onopen=null,clearTimeout(n)})}bindSocket(e){e.addEventListener("close",this.onclose),e.addEventListener("error",this.onerror),e.addEventListener("message",this.onmessage)}unbindSocket(e){e.removeEventListener("close",this.onclose),e.removeEventListener("error",this.onerror),e.removeEventListener("message",this.onmessage)}unbindAndCloseSocket(e){if(e===m.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(t){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(t){}this._backupSocket=null}}onclose(e){e.target===this._socketInUse&&(this._log.warn(`${e.target===this._socket?"main":"backup"} is closed code:${e.code} ${e.reason}`),this.emitConnectionStateChanged("DISCONNECTED"),(!e.wasClean||e.code!==1e3)&&this.startReconnection(),this.room.isJoining&&this.emit(pe.SETUP_FAILED,new y({code:S.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onclose"})))}onerror(e){this._log.error(`${e.target===this._socket?"main":"backup"} error observed`),this.emitConnectionStateChanged("DISCONNECTED"),e.target===this._socketInUse&&(this.unbindAndCloseSocket(m.MAIN),this.unbindAndCloseSocket(m.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(pe.SETUP_FAILED,new y({code:S.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=Cn(e.data);let t=JSON.parse(e.data),{cmd:r,data:o}=t,n=Object.values(Dt),c=Object.keys(Dt)[n.indexOf(r)],d=V[c]||r;switch(Ph.includes(r)||(this._log.debug(`received ${r} msg: ${e.data}`),d&&this._log.info(`Received event: [ ${d} ]`)),r){case Dt.CHANNEL_SETUP_RESULT:{if(t.code===0)this._signalInfo.clientIp=o.clientIp,this._signalInfo.signalIp=o.signalInnerIp,o.svrTime&&Ll(o.svrTime),this._log.info(`ChannelSetup Success ${k()-this._connnectStartTime}`),N.addSuccessEvent({key:521701,cost:k()-this._connnectStartTime}),this._connnectStartTime=-1,this.emit(pe.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let h=new y({code:S.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:w({key:x.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error(`${t.code}, ${t.message}`),this.close(),N.addFailedEvent({key:521701,error:h}),this.emit(pe.SETUP_FAILED,h)}break}case Dt.JOIN_ROOM_RESULT:{t.code===0&&(this._signalInfo.relayIp=o.relayOuterIp,this._signalInfo.relayInnerIp=o.relayInnerIp,this._signalInfo.relayPort=o.relayPort,this._signalInfo.tinyId=t.tinyId,this._signalInfo.endReportExtend=o.endReportExtend,this._log.info(`signalIp:${this._signalInfo.signalIp} clientIp:${this._signalInfo.clientIp} relayIp: ${this._signalInfo.relayIp}`)),this.emit(d,{data:t});break}default:this.emit(String(d),{data:t});break}}reGetSignalChannelUrl(){return f(this,null,function*(){try{if(!this.room.joinParams)return;$t(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(e){}})}startReconnection(){if(!this._socketInUse)return;this._socketInUse.onclose=null,this._socketInUse.close(4011);let e=this._socketInUse===this._socket;this.unbindAndCloseSocket(e?m.MAIN:m.BACKUP),this._socketInUse=null,this.emitConnectionStateChanged("DISCONNECTED"),this.reconnect()}reconnect(){return f(this,null,function*(){if(!this._isReconnecting){if(!this.room.isJoined&&this.keepAlive){this.close();return}this._isReconnecting=!0;try{this._log.warn("reconnect"),yield this.connect();let{roomId:e,useStringRoomId:t}=this.room,{relayIp:r,relayInnerIp:o,relayPort:n}=this._signalInfo,{data:a}=yield this.sendWaitForResponse({command:W.RECONNECT_WS,data:{roomId:e,useStringRoomId:t,relayInnerIp:o,relayOuterIp:r,relayPort:n},responseCommand:V.CHANNEL_RECONNECT_RESULT});a.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),N.addSuccessEvent({key:521702,cost:k()-this._connnectStartTime}),this._connnectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(N.addFailedEvent({key:521702,error:a.code}),this._log.warn(`reconnect failed, ${a.code} ${a.message}`),this.room.reJoin())}catch(e){this._log.error(e),this.room.reJoin()}}})}send(e,t={}){if(this.isConnected&&!this.room.isLeft){let r={cmd:e,data:t,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},o=JSON.stringify(r);return this._socketInUse.send(o),this.bytesSent+=Cn(o),r.seq}}sendWaitForResponse({command:e,data:t,timeout:r=5e3,responseCommand:o,commandDesc:n,enableLog:a=!0,addReceiveTime:c=!1}){return new Promise((d,h)=>{let u=setTimeout(()=>{this.off(o,_);let C=new y({code:S.API_CALL_TIMEOUT,message:w({key:x.API_CALL_TIMEOUT,data:{commandDesc:n,command:e}})});a&&this._log.warn(C),h(C)},r),p=Date.now(),_=C=>{C.data.seq===I&&(clearTimeout(u),this.off(o,_),c&&(C.data.receiveTime=Date.now()),d(C))};this.on(o,_);let I=this.send(e,t)})}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:r,retries:o=0,retryTimeout:n=0}=e;return Ut({retryFunction:this.sendWaitForResponse,onError:({retry:a})=>{this.isOnline?a():(this._log.warn(`retry ${r} when connected`),this.once(pe.CONNECTED,a))},onRetrying:a=>{this._log.warn(`${t||r} timeout observed, retrying [${a}/${o}]`)},settings:{retries:o,timeout:n},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),clearTimeout(this.stopKeepAliveTimeout),Ra.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(m.MAIN),this.unbindAndCloseSocket(m.BACKUP),this.emitConnectionStateChanged("DISCONNECTED")}destroy(){this.close(),this.destroyed=!0}stopKeepAliveIn(e=3600){if(this.keepAlive){this._log.info(`stopKeepAlive in ${e}s`),this.stopKeepAliveTimeout=setTimeout(()=>{this.keepAlive=!1,this._log.info(`close due to not used ${e}s`),this.close(),this.off(V.JOIN_ROOM_RESULT,t)},e*1e3);let t=r=>{r.data.code===0&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(V.JOIN_ROOM_RESULT,t))};this.on(V.JOIN_ROOM_RESULT,t)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info(`${this._currentState} -> ${e}`),this.emit(pe.CONNECTION_STATE_CHANGED,{prevState:this._currentState,state:e}),this._currentState=e,e==="CONNECTED"?this.emit(pe.CONNECTED):e==="DISCONNECTED"&&this.emit(pe.DISCONNECTED))}};b([je({settings:{retries:1/0,timeout:2e3},onError(s,i){!this.room.isDestroyed&&!this.destroyed&&i()},onRetrying(s,i){this._log.warn(`retrying to connect ${s}`),s>=3&&s%3===0&&this.reGetSignalChannelUrl(),i&&(this._stopConnectRetry=i,(this.room.isDestroyed||this.destroyed)&&i())}})],ms.prototype,"connect",1);var wh=Se(De());var ol=0,nl=!1,ya=new Set,R_=s=>ol>2&&!nl&&ya.size===0&&s,al=!1,He=class{constructor(i){l(this,"userId");l(this,"tinyId");l(this,"_sdpSemantics");l(this,"_isUplink");l(this,"_room");l(this,"_log");l(this,"_signalChannel");l(this,"_isErrorObserved",!1);l(this,"_waitForPeerConnectionConnectedPromise");l(this,"_waitForPeerConnectionConnectedPromiseReject",null);l(this,"_peerConnection",null);l(this,"_emitter",new wh.default);l(this,"_currentState","DISCONNECTED");l(this,"_isReconnecting",!1);l(this,"_reconnectionCount",0);l(this,"_reconnectionTimer",-1);l(this,"_isFirstConnection",!0);l(this,"_prevTime",-1);l(this,"_localAddress");l(this,"_remoteAddress");this.userId=i.userId,this.tinyId=i.tinyId,this._room=i.room,this._sdpSemantics=i.room.sdpSemantics,this._isUplink=i.isUplink,this._log=R.createLogger({id:"n-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=i.signalChannel}beforeConnect(){this._prevTime<0&&(this._prevTime=k())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,N.addSuccessEvent({key:521705,cost:Math.min(k()-this._prevTime,30*1e3)})):this._isReconnecting&&N.addSuccessEvent({key:521706,cost:k()-this._prevTime}),this._prevTime=-1}catch(i){throw this._isFirstConnection?(this._isFirstConnection=!1,N.addFailedEvent({key:521705,error:i})):this._isReconnecting&&this._reconnectionCount>=3&&N.addFailedEvent({key:521706,error:i}),i}}initialize(){let i={iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"};this._peerConnection=new RTCPeerConnection(i),this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this)}close(i){this._log.info("close connection"),this._emitter.emit("closed",i),this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),ya.delete(this)}closePeerConnection(i=!1){this._peerConnection&&(this._log.info("close pc"),this._peerConnection.onconnectionstatechange=null,this._peerConnection.close(),this._peerConnection=null,i&&this.emitConnectionStateChangedEvent("DISCONNECTED")),this._waitForPeerConnectionConnectedPromiseReject&&this._waitForPeerConnectionConnectedPromiseReject(new y({code:S.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return ft;let i=null;if(this._isUplink){if(!Hi()||this._peerConnection.getSenders().length===0)return ft;i=this._peerConnection.getSenders()[0].transport}else{if(!ar()||this._peerConnection.getReceivers().length===0)return ft;i=this._peerConnection.getReceivers()[0].transport}return i?i.state:ft}onConnectionStateChange(i){let e=this._peerConnection.iceConnectionState,t=this.getDTLSTransportState();if(this._log.info(`connectionState: ${i.target.connectionState}, ICE: ${e}, DTLS: ${t}`),i.target.connectionState===ne.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),i.target.connectionState===ne.FAILED||i.target.connectionState===ne.CLOSED){let r=`connection ${i.target.connectionState}. ICE Transport state: ${e}, DTLS Transport state: ${t}`,o=new y({message:r,code:S.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",o)}(i.target.connectionState===ne.CONNECTED||i.target.connectionState===ne.COMPLETED)&&(this.logSelectedCandidate(),Y.logSuccessEvent({userId:this._room.userId,eventType:Ge.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(i){return i===this._currentState?!1:(i==="CONNECTED"?(ol=0,nl=!1,al=!0,ya.add(this)):ya.delete(this),T.emit(g.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:i,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:i}),this._currentState=i,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}logSelectedCandidate(){return f(this,null,function*(){if(!this._peerConnection)return;let i=yield this._peerConnection.getStats();for(let[,e]of i)if(Fi(e)){let t=i.get(e.localCandidateId),r=i.get(e.remoteCandidateId);t&&(this._log.info(`local candidate: ${t.candidateType} ${t.protocol}:${t.ip||t.address}:${t.port} ${t.networkType||""} ${t.candidateType==="relay"?`relayProtocol:${t.relayProtocol}`:""}`),this._localAddress=`${t.ip||t.address}:${t.port}`),r&&(this._log.info(`remote candidate: ${r.candidateType} ${r.protocol}:${r.ip||r.address}:${r.port}`),this._remoteAddress=`${r.protocol}:${r.ip||r.address}`);break}})}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise?this._waitForPeerConnectionConnectedPromise:(this._waitForPeerConnectionConnectedPromise=new Promise((i,e)=>{if(this._currentState==="CONNECTED")return i();this._waitForPeerConnectionConnectedPromiseReject=e;let t=a=>{a.state==="CONNECTED"&&(clearTimeout(n),o(),i())},r=({room:a})=>{a===this._room&&(clearTimeout(n),o(),e(new y({code:S.API_CALL_ABORTED,message:w({key:x.CONNECTION_ABORTED,data:"leave room"})})))},o=()=>{T.off(g.LEAVE_SUCCESS,r,this),this._emitter.off("connection-state-changed",t,this)},n=setTimeout(()=>{o();let a=new y({code:S.API_CALL_TIMEOUT,message:"connection timeout"});ol+=1,R_(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),nl=!0,this._emitter.emit("firewall-restriction")),e(a)},Os);T.on(g.LEAVE_SUCCESS,r,this),this._emitter.on("connection-state-changed",t,this)}),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally(()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null}),this._waitForPeerConnectionConnectedPromise)}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(pe.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=oi()){this._log.warn(`SDK has tried reconnect for ${this._reconnectionCount} times, but all failed, please check your network`),this.stopReconnection();let i=new y({code:this._isUplink?S.UPLINK_RECONNECTION_FAILED:S.DOWNLINK_RECONNECTION_FAILED,message:w({key:this._isUplink?x.UPLINK_RECONNECTION_FAILED:x.DOWNLINK_RECONNECTION_FAILED})});return this.emitConnectionStateChangedEvent("DISCONNECTED"),this._emitter.emit("error",i),-1}return this._signalChannel.isConnected?(this._reconnectionCount+=1,this._log.warn(`reconnect() trying [${this._reconnectionCount}]`),1):(this._log.warn("reconnect() signal channel is not connected, suspend reconnection until signal is connected"),this._signalChannel.once(pe.CONNECTED,this.reconnect,this),-1)}on(i,e,t){this._emitter.on(i,e,t)}off(i,e,t){this._emitter.off(i,e,t)}getIsReconnecting(){return this._isReconnecting}get isH264(){var i,e;return!!((e=(i=this._peerConnection)==null?void 0:i.remoteDescription)!=null&&e.sdp.includes("H264"))}setOffer(i){var e;return(e=this._peerConnection)==null?void 0:e.setLocalDescription(i)}setAnswer(i){var e;return(e=this._peerConnection)==null?void 0:e.setRemoteDescription(i)}};b([Qe(521712,!1)],He.prototype,"setOffer",1),b([Qe(521713,!1)],He.prototype,"setAnswer",1);var ul=Se(ll());var le=function(s){return ul.default.parse(s)},mt=function(s){return ul.default.write(s)},Wh=function(s){let i=le(s);return i.media.forEach(e=>{e.type===m.AUDIO&&e.fmtp.forEach(t=>{t.config+=";sprop-stereo=1;stereo=1"})}),mt(i)};function Jh(s){let i=le(s);return i.media.forEach(e=>{var t,r;if(e.type===m.VIDEO){let o=new Set;e.rtp.forEach(({payload:a,codec:c})=>c==="H264"&&o.add(a)),e.fmtp.forEach(({payload:a,config:c})=>{let d=c.match(/apt=(\d+)/);d&&d[1]&&o.has(Number(d[1]))&&o.add(a)});let n=({payload:a})=>!o.has(a);e.rtp=e.rtp.filter(n),e.rtcpFb=(t=e.rtcpFb)==null?void 0:t.filter(n),e.fmtp=e.fmtp.filter(n),e.payloads=(r=e.payloads)==null?void 0:r.split(" ").filter(a=>!o.has(Number(a))).join(" ")}}),mt(i)}function ba(s){return Object.keys(s).filter(i=>s[i])}var ml=class extends He{constructor(e){super(L(v({},e),{isUplink:!1}));l(this,"_flag",0);l(this,"isRobot",!1);l(this,"role","anchor");l(this,"remoteAudioTrack");l(this,"remoteVideoTrack");l(this,"remoteAuxiliaryTrack");l(this,"ssrc",{audio:0,video:0,auxiliary:0});l(this,"_isSDPExchanging",!1);this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=e.remoteAudioTrack||new yi(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new ei(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new ss(this._room,this)}get videoCodec(){var t,r;let e=(r=(t=this._peerConnection)==null?void 0:t.remoteDescription)==null?void 0:r.sdp;return e?e.includes("H264")?"h264":"vp8":"h264"}get subscribeState(){let e={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(this.remoteVideoTrack.mediaType&8?e.smallVideo=!0:e.video=!0),this.remoteAudioTrack.isSubscribed&&(e.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(e.auxiliary=!0),e}get muteState(){return 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===m.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var o,n;let t=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&t!==e&&((o=this.remoteVideoTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),r}onTrack(e){let t=e.streams[0],{track:r}=e,o=t.id===Ds?m.MAIN:m.AUXILIARY;this._log.debug(`ontrack ${o} ${r.kind}`);let n=m.AUDIO;r.kind===m.VIDEO&&(n=o===m.MAIN?m.VIDEO:m.AUXILIARY);let a=this.remoteAudioTrack;n===m.VIDEO?a=this.remoteVideoTrack:n===m.AUXILIARY&&(a=this.remoteAuxiliaryTrack),a.setInputMediaStreamTrack(r)}addRRTRLine(e){let t=e.split(`\r
54
+ ${r.stack}`),!1}},s};var as=new WeakMap;function Sh(s){let i=as.get(s);i&&(i.forEach(e=>clearTimeout(e)),as.delete(s))}function Ih(s,i){return G((e,t)=>function(...r){let o=as.get(this);o||(o=new Map,as.set(this,o));let n=i(...r),a=o.get(n);if(!a||a<=0){e.apply(this,r);let c=setTimeout(()=>{var d;(d=as.get(this))==null||d.delete(n)},s);o.set(n,c)}else{clearTimeout(a);let c=window.setTimeout(()=>{var d;e.apply(this,r),(d=as.get(this))==null||d.delete(n)},s);o.set(n,c)}})}var Ah="5.8.7-beta.7";function Ue(...s){return G((i,e)=>function(...t){try{_a.call(this,s,t,e,this._name)}catch(r){return Promise.reject(r)}return i.apply(this,t)})}function Wd(...s){return G((i,e)=>function(...t){try{_a.call(this,s,t,e,this._name)}catch(r){throw r}return i.apply(this,t)})}function _a(s,i,e,t){if(_e(s))for(let r=0;r<s.length;r++)fa.call(this,{rule:s[r],value:i[r],key:s[r].name,fnName:e,className:t});else fa.call(this,{rule:s,value:i[0],key:s.name,fnName:e,className:t})}function fa({rule:s,value:i,key:e,fnName:t,className:r}){function o(c){return{code:U.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:s,value:i}}}if(E(i)){if(s.required)throw new P(o(5001));if(E(s.defaultValue)){te(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 d=0;d<s.type.length;d++)s.type[d]===null&&i===null&&(c=!0),te(s.type[d])&&i instanceof s.type[d]&&(c=!0),z(s.type[d])&&Ae(i)===s.type[d].toLowerCase()&&(c=!0);if(!c)throw new P({code:U.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:s.type.map(d=>Xs(d)?An(d):z(d)?d:Ae(d))},value:i}})}else if(!E(s.type)&&Ae(i)!==s.type)throw new P(o(5002));if(s.allowEmpty===!1){let c=K(i)&&(i===0||Number.isNaN(i)),d=z(i)&&i.trim()==="";if(c||d)throw new P(o(5003))}if(s.notLessThanZero&&K(i)&&i<0)throw new P(o(5006));if(!E(s.min)&&K(i)&&i<s.min)throw new P(o(5007));if(!E(s.max)&&K(i)&&i>s.max)throw new P(o(5008));if(z(s.instanceOf)){if(!i||i._name!==s.instanceOf)throw new P(o(5004))}else if(te(s.instanceOf)&&!(i instanceof s.instanceOf))throw new P(o(5004));if(Array.isArray(s.values)&&!s.values.includes(i))throw new P(o(5005));let{properties:n}=s;Ze(n)&&Ct(i)&&Object.keys(n).forEach(c=>{fa.call(this,{rule:n[c],value:i&&i[c],key:`${c}`,fnName:t,className:r})});let{arrayItem:a}=s;Ze(a)&&_e(i)&&i.forEach((c,d)=>{fa.call(this,{rule:a,value:c,key:`${e}[${d}]`,fnName:t,className:r})}),te(s.validate)&&s.validate.call(this,i,e,t,r,this)}function ae(s={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t,ignoreLog:r}=s;return G((o,n)=>function(...a){var u;function c(p,_,I){if(I&&I.includes(p))return"hided";if(e){let C=e(...a);if(a[C.argIndex]===_)return C.value}if(_===a||p in a)return _;try{return _ instanceof HTMLElement?`id: ${_.id} type:${Ae(_)}`:(JSON.stringify(_),_)}catch(C){return`type:${Ae(_)}`}}let d=this._log||R;if(r!=null&&r(...a))return o.apply(this,a);a.length>0?d.info(`${n}() ${JSON.stringify(a,(p,_)=>c(p,_,["userSig","privateMapKey"]))}`):d.info(`${n}()`);let h=t?t(...a):vn[n];try{let p=o.apply(this,a),_=k();return sr(p)?p.then(I=>(d.info(`${n}() success ${i.call(this,...a)}`),N.addSuccessEvent({key:h,cost:k()-_}),I)).catch(I=>{var B;I=P.convertFrom.call(this,I,n,a.length===1?a[0]:a);let C=I.extraCode||I.code,D=(B=I.message)!=null&&B.includes(C)?"":` code:${C}`;throw d.error(`${n}() failed ${i.call(this,...a)} ${I}${D} params: ${JSON.stringify(a,c)}`),N.addFailedEvent({key:h,error:I}),I}):(N.addSuccessEvent({key:h}),p)}catch(p){p=P.convertFrom.call(this,p,n);let _=p.extraCode||p.code,I=(u=p.message)!=null&&u.includes(_)?"":` code:${_}`;throw d.error(`${n}() failed ${p}${I} params: ${JSON.stringify(a,c)}`),N.addFailedEvent({key:h,error:p}),p}})}var ga=s=>G((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 P({code:U.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});if(te(o.constructor.isSupported)&&!o.constructor.isSupported())throw this._log.error(`plugin ${String(t)} is not supported`),new P({code:U.ENV_NOT_SUPPORTED,message:`plugin ${String(t)} is not supported`,extraCode:5210,fnName:e});return _a.call(this,o.getValidateRule(s),[r],e,"TRTC"),i.call(this,o,r)})});var Ea=0,Jd=class{constructor(i,e){l(this,"player");l(this,"publisher");l(this,"mixInput");this.mixInput=new Qr(e),i.url?(this.player=new Audio(i.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(i.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(i.track),this.mixInput.connect()}updateSettings(i){!this.player||(E(i.volume)||(this.volume=i.volume),E(i.loop)||(this.loop=i.loop),E(i.playbackRate)||(this.playbackRate=i.playbackRate))}updateListener(i){if(!!this.player){if(i.onDurationChange){let{onDurationChange:e}=i;this.player.ondurationchange=t=>{e(t.target.duration)}}if(i.onTimeUpdate){let e=i.onTimeUpdate,{player:t}=this;t.ontimeupdate=()=>{e(t.currentTime,t.duration)}}i.onEnded&&(this.player.onended=i.onEnded)}}reset(){this.seek(0),this.mixInput.connect()}seek(i){!this.player||i<0&&i>this.player.duration||(this.player.currentTime=i,this.publisher.currentTime=i)}play(){var i,e;return(i=this.publisher)==null||i.play(),(e=this.player)==null?void 0:e.play()}pause(){var i,e;(i=this.player)==null||i.pause(),(e=this.publisher)==null||e.pause()}stop(){var i;(i=this.player)==null||i.pause(),this.mixInput.disconnect()}setOperation(i){i==="pause"&&this.pause(),i==="resume"&&(this.pause(),this.play()),i==="stop"&&(this.pause(),this.seek(0))}set volume(i){!this.player||!this.publisher||(this.player.volume=i,this.publisher.volume=i)}set loop(i){!this.player||!this.publisher||(this.player.loop=i,this.publisher.loop=i)}set playbackRate(i){!this.player||!this.publisher||(this.player.playbackRate=i,this.publisher.playbackRate=i)}};function cs(s,i){if(i&&typeof i!="function")throw new P({code:U.INVALID_PARAMETER,message:`start audioMixer plugin: param ${s} should be a function.`})}var ds=class{constructor(i){this.core=i;l(this,"log");l(this,"mixedMusicMap",new Map);l(this,"cacheMusicMap",new Map);Ea=Ea+1,this.log=i.log.createChild({id:`${this.getAlias()}${Ea}`}),this.log.info(`[audioMixer] created id=${this.getAlias()}${Ea}`),this.core=i}getName(){return ds.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return ds.startValidateRule;case"update":return ds.updateValidateRule;case"stop":return ds.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 Jd(i,e.audioManager),this.cacheMusicMap.set(t,o)),o.updateListener(i),o.updateSettings(i),yield o.play(),this.mixedMusicMap.set(t,o),this.log.info(`start mix audio track ${t} success.`),N.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),E(t)||n.setOperation(t),E(r)||n.seek(r),this.kvUpload(i)})}stop(e){return f(this,arguments,function*({id:i}){var t;this.mixedMusicMap.has(i)&&(this.log.info(`remove music source, music id: ${i}`),(t=this.mixedMusicMap.get(i))==null||t.stop(),this.mixedMusicMap.delete(i)),i==="*"&&this.destroyAllMusic()})}kvUpload(i){let{track:e,loop:t,volume:r,playbackRate:o,operation:n,seekFrom:a,onTimeUpdate:c,onDurationChange:d,onEnded:h}=i;e&&N.addCount({key:502711}),t&&N.addCount({key:502703}),r&&N.addCount({key:502704}),o&&N.addCount({key:502705}),n&&N.addCount({key:502706}),a&&N.addCount({key:502707}),typeof c!="function"&&N.addCount({key:502709}),typeof h!="function"&&N.addCount({key:502710}),typeof d!="function"&&N.addCount({key:502708})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((i,e)=>this.stop({id:e}))}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}},Xi=ds;l(Xi,"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"),d=r.startsWith("data");if(!(a||c||d))throw new P({code:U.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new P({code:U.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});cs("onTimeUpdate",i.onTimeUpdate),cs("onEnded",i.onEnded),cs("onDurationChange",i.onDurationChange)}}),l(Xi,"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){cs("onTimeUpdate",i.onTimeUpdate),cs("onEnded",i.onEnded),cs("onDurationChange",i.onDurationChange)}}),l(Xi,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),l(Xi,"Name","AudioMixer");var Ta=0,jd,ls=class{constructor(i){this.core=i;l(this,"log");l(this,"audioContext",qe("denoiser"));l(this,"workletNode");Ta=Ta+1,this.log=i.log.createChild({id:`${this.getAlias()}${Ta}`}),this.log.info(`[audioDenoiser] created id=${this.getAlias()}${Ta}`),i.assetsPath&&this.preload(`${i.assetsPath}/denoiser-wasm.js`)}static startValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,t,r,o){if(!i.room.audioManager.hasAudioTrack)throw new P({code:U.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return jd||(jd=this.doPreload(i)),jd}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield dr(this.audioContext,t)}finally{URL.revokeObjectURL(t)}})}getName(){return ls.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(i){switch(i){case"start":return ls.startValidateRule(this.core);case"update":return ls.updateValidateRule;case"stop":return ls.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e}=this.core;if(yield this.preload(`${i.assetsPath}/denoiser-wasm.js`),!this.workletNode){let t=String(Date.now()).slice(0,-3),{auth:r,sign:o,status:n,message:a}=yield p_(L(v({},i),{timestamp:t}));if(!r)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${r}. Message: ${a}`),new P({code:U.INVALID_PARAMETER,message:a});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(i.sdkAppId),userId:i.userId,timestamp:t,sign:o,status:n}}),this.workletNode.port.onmessage=c=>{let{data:d}=c;d.type==="cost"&&this.log.debug(`[RTCAIDenoiser] ${d.value}`)}}this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(){return 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)}},gr=ls;l(gr,"updateValidateRule",{type:"object"}),l(gr,"stopValidateRule",{type:"object"}),l(gr,"Name","AIDenoiser");function m_(s,i=m.MAIN){return`https://${Vt[i]||Sn(s,i)}/api/v1/audioAiAuth`}function p_(r){return f(this,arguments,function*({sdkAppId:s,userId:i,userSig:e,timestamp:t}){let n=`${m_(s)}?sdkAppId=${s}&userId=${i}&userSig=${e}&timestamp=${t}`,a=yield fetch(n),{data:{errCode:c,errMsg:d,sign:h,status:u}}=yield a.json();if(u==="1")return{auth:!0,sign:h,status:u,message:d};let p="Init RTCAIDenoiser failed.",_="";switch(c){case 1:_="Please check your params.";break;case 2:_="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:_="Server is invalid. Please contact our engineer. ";break;case 4:_="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:_="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:_="Your version is not supported.";break}return{auth:!1,status:u,message:d?`${p} Reason: ${d}. ${_}`:`${p}, ${_}`}})}var Ch=Se(De(),1);var qd=class extends Ch.EventEmitter{constructor(){super();this.state="nominal";this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return f(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!fe&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){Y.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)&&R.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){Y.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},f_=new qd,Xd=f_;function Qd([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 Ri(new DataView(new Uint8Array(o).buffer),!0)}function zd(s){return s.type==="empty"||s.data.byteLength===0}function Yd(s){return s.getInt32(0)===1&&s.getInt8(4)===6}function Kd(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 Zd({frame:s,seiMessageList:i}){if(!i||i.length===0||s.data.byteLength===0)return s;let e=Kd(s.data),t=9-e;if(t<=0)return s;let r=i.splice(0,t).reverse().map(Qd),o=r.reduce((h,u)=>h+u.dataView.byteLength,0),n=new ArrayBuffer(o+s.data.byteLength),a=new DataView(n),c=new DataView(s.data),d=0;for(let h=0;h<r.length;h++)for(let u=0;u<r[h].dataView.byteLength;u++)a.setInt8(d++,r[h].dataView.getInt8(u));for(let h=0;h<s.data.byteLength;h++)a.setInt8(d++,c.getInt8(h));return s.data=n,s}function el({frame:s,onSEI:i}){try{let e=new DataView(s.data);if(zd(s)||!Yd(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 d=a-r;if(o===-1?o=d:n===-1&&(n=d,t.push(new Ri(new DataView(e.buffer.slice(o,n)))),o=d,n=-1),!(e.getUint8(a+1)===6)){s.data=e.buffer.slice(d);break}}r=0}else r=0}i==null||i(t.reverse())}catch(e){}return s}var tl=0,il=class{constructor(i){this.core=i;l(this,"log");l(this,"_seiMessageList",[]);l(this,"_smallSeiMessageList",[]);l(this,"_subStreamSeiMessageList",[]);tl++,this.log=i.log.createChild({id:`${this.getAlias()}${tl}`}),this.log.info(`[sei] created id=${this.getAlias()}${tl}`),this.core=i,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 Zd({frame:i,seiMessageList:t})}catch(t){this.log.warn(t)}return i}decode({frame:i,track:e}){return el({frame:i,onSEI:t=>{t.forEach(r=>{this.core.trtc.emit(M.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:Ti?this.encode:Zd,type:1}),this.core.room.videoManager.addDecodeProcessor({processor:Ti?this.decode:el,type:1})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:1}),this.core.room.videoManager.removeDecodeProcessor({type:1})}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 il.Name}getAlias(){return"sei"}getGroup(){return"sei"}},us=il;l(us,"autoStart",!0),l(us,"Name","SEI");var g_=0,Sa,rl=class{constructor(i){this.core=i;l(this,"_core");l(this,"log");l(this,"dumpLocalVideoMap",{});l(this,"dumpRemoteVideoMap",{});l(this,"dialog");this._core=i,this.log=i.log.createChild({id:`${this.getAlias()}${++g_}`}),this.log.info("created")}getName(){return rl.Name}getAlias(){return"dm"}getGroup(){return"dm"}getValidateRule(i){switch(i){case"start":return{name:"StartDebugOptions",required:!1};case"update":return{name:"UpdateDebugOptions",required:!1};case"stop":return{name:"StopDebugOptions",required:!1}}}start(){return f(this,null,function*(){!new URLSearchParams(location.search).has("trtcDebug")||(yield this.openDebugDiaLog(),this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED&&this.addVideoProcessor())})}update(){}stop(){this.closeDebugDiaLog(),this.removeVideoProcessor()}destroy(){this.stop()}openDebugDiaLog(){return f(this,null,function*(){try{if(Sa)yield Sa;else{let i=Date.now();Sa=this.loadScript(`https://web.sdk.qcloud.com/trtc/webrtc/assets/debug/debug-dialog@${Ie}.js`),yield Sa,this.log.info(`download debug dialog script cost: ${Date.now()-i}ms`)}this.dialog=new TRTCDebugDialog(this._core,this.log,this.dumpLocalVideoMap,this.dumpRemoteVideoMap),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(i){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(i))}})}closeDebugDiaLog(){var i;(i=this.dialog)==null||i.closeDialog(),this.dialog=null}addVideoProcessor(){this._core.room.videoManager.addEncodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.encodeVideo.bind(this):this.encodeVideoDump,type:2}),this._core.room.videoManager.addDecodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.decodeVideo.bind(this):this.decodeVideoDump,type:2})}removeVideoProcessor(){this._core.room.videoManager.removeEncodeProcessor({type:2}),this._core.room.videoManager.removeDecodeProcessor({type:2})}encodeVideo({frame:i,mediaType:e}){return this.encodeVideoDump({frame:i,onDump:()=>{if(!e)return;let t=e===2?"sub":"main",r=this.dumpLocalVideoMap[t];r&&(r.data.push(i.data),r.duration>0&&Date.now()-r.startTimestamp>r.duration*1e3&&r.onDumpEnd())}})}decodeVideo({frame:i,track:e}){return this.decodeVideoDump({frame:i,onDump:()=>{if(!e)return;let t=this.dumpRemoteVideoMap[`${e.userId}-${e.streamType}`];t&&(t.data.push(i.data),t.duration>0&&Date.now()-t.startTimestamp>t.duration*1e3&&t.onDumpEnd())}})}encodeVideoDump({frame:i,onDump:e}){return e==null||e(),i}decodeVideoDump({frame:i,onDump:e}){return e==null||e(),i}loadScript(i){return new Promise((e,t)=>{this.log.info(`loading debug dialog from ${i}`);let r=document.createElement("script");r.type="text/javascript",r.onload=e,r.onerror=t,r.crossOrigin="anonymous",r.src=i,document.head.append?document.head.append(r):document.getElementsByTagName("head")[0].appendChild(r)})}},Er=rl;l(Er,"Name","Debug"),l(Er,"autoStart",!0),b([je({settings:{timeout:3e3,retries:3},onError(s,i,e){var t;(t=s==null?void 0:s.message)!=null&&t.includes("timeout")?i():e(s)}})],Er.prototype,"loadScript",1);var bh=Se(De(),1);var Rh=Symbol("instance"),dD=Symbol("abortCtrl"),lD=Symbol("cacheResult");var yh=new Map;var E_=(()=>typeof window!="undefined"&&window.__AFSM__?(e,t)=>{window.dispatchEvent(new CustomEvent(e,{detail:t}))}:typeof importScripts!="undefined"?(e,t)=>{postMessage({type:e,payload:t})}:()=>{})();function T_(s,i){let e=this._state;this._state=s;let t=s.toString();s&&this.emit(t,e),this.emit(oe.STATECHANGED,s,e,i),this.updateDevTools({value:s,old:e,err:i instanceof Error?i.message:String(i)})}var oe=class extends bh.default{constructor(i,e,t){super(),this.name=i,this.groupName=e,this._state=oe.INIT,i||(i=Date.now().toString(36)),t?Object.setPrototypeOf(this,t):t=Object.getPrototypeOf(this),e||(this.groupName=this.constructor.name);let r=t[Rh];r?this.name=r.name+"-"+r.count++:t[Rh]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let i=Object.getPrototypeOf(this),e=yh.get(i)||[],t=new Set,r=[],o=[],n=new Set,a=Object.getPrototypeOf(i);yh.has(a)&&(a.stateDiagram.forEach(d=>t.add(d)),a.allStates.forEach(d=>n.add(d))),e.forEach(({from:d,to:h,action:u})=>{typeof d=="string"?r.push({from:d,to:h,action:u}):d.length?d.forEach(p=>{r.push({from:p,to:h,action:u})}):o.push({to:h,action:u})}),r.forEach(({from:d,to:h,action:u})=>{n.add(d),n.add(h),n.add(u+"ing"),t.add(`${d} --> ${u}ing : ${u}`),t.add(`${u}ing --> ${h} : ${u} \u{1F7E2}`),t.add(`${u}ing --> ${d} : ${u} \u{1F534}`)}),o.forEach(({to:d,action:h})=>{t.add(`${h}ing --> ${d} : ${h} \u{1F7E2}`),n.forEach(u=>{u!==d&&t.add(`${u} --> ${h}ing : ${h}`)})});let c=[...t];return Object.defineProperties(i,{stateDiagram:{value:c},allStates:{value:n}}),c}static get(i){let e;return typeof i=="string"?(e=oe.instances.get(i),e||oe.instances.set(i,e=new oe(i,void 0,Object.create(oe.prototype)))):(e=oe.instances2.get(i),e||oe.instances2.set(i,e=new oe(i.constructor.name,void 0,Object.create(oe.prototype)))),e}static getState(i){var e;return(e=oe.get(i))===null||e===void 0?void 0:e.state}updateDevTools(i={}){E_(oe.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){T_.call(this,i)}};oe.STATECHANGED="stateChanged";oe.UPDATEAFSM="updateAFSM";oe.INIT="[*]";oe.ON="on";oe.OFF="off";oe.instances=new Map;oe.instances2=new WeakMap;var Nh=s=>{switch(s){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},Ia=class{constructor(i,e,t){l(this,"trackDoneOB");l(this,"startOB");l(this,"stopOB");l(this,"inputFrameCount",0);l(this,"decodedFrameCount",0);l(this,"type","auto");l(this,"config");l(this,"decoder");l(this,"_decodeSink");let{kvStatManager:r,trtc:o}=i;this.config=t.config,this.trackDoneOB=Fe(e,oe.INIT),this.stopOB=bi(this.trackDoneOB),this.startOB=bi(),t.type==="auto"?this.type="webCodecs":this.type=t.type;let n=bi(),a=c=>{let d=this.pipe(e);return n.next("STARTING"),e.log.info(`decoder type: ${this.type}`),xe(d,Nt(this.stopOB),ot(()=>{},h=>{e.log.error(h),r.addFailedEvent({key:Nh(this.type),error:h}),c>4?this.startOB.error(h):this.startOB.next(c+1)})),xe(d,So(1),rh(ea))};xe(this.startOB,Zn(0),Io(a),Nt(this.stopOB),ot(()=>{e.player.setOutput(),n.next("STARTED")},c=>{n.next("FAILED")},()=>{r.addSuccessEvent({key:Nh(this.type)}),r.addSuccessEvent({key:504702})}))}mock(i){this._decodeSink?this._decodeSink.error(i):this.startOB.next(0)}close(i){this.stopOB.next(i)}pipe(i){return es()(e=>f(this,null,function*(){this._decodeSink=e,e.defer(()=>{var r;(r=this.decoder)==null||r.close()});let{type:t}=this;try{switch(t){case"webCodecs":this.decoder=new AudioDecoder({error:r=>{i.log.error(r),e.error(4)},output:r=>{this.decodedFrameCount++,e.next(r),i.player.write(r)}});break;case"wasm":break}this.decoder.configure(this.config)}catch(r){i.log.error(r),e.error(t==="webCodecs"?2:6)}}))}decodeFrame(i){var e;this.inputFrameCount++,((e=this.decoder)==null?void 0:e.state)==="configured"&&this.decoder.decode(new EncodedAudioChunk({data:i.data,timestamp:i.timestamp,type:"key"}))}},S_={type:"object"},Aa=class{constructor(i){this.core=i;l(this,"log");l(this,"contextMap",new Map);l(this,"decodeProcessorMap",new WeakMap);this.log=i.log.createChild({id:`${this.getAlias()}`})}getAlias(){return Aa.Name}getGroup(i){return i.track.userId+i.track.streamType}getName(){return Aa.Name}getValidateRule(i){return S_}start(i){let{track:e}=i;this.decodeProcessorMap.set(e,this.decode(i)),this.core.room.audioManager.addDecodeProcessor({processor:({frame:t,track:r})=>this.decodeProcessorMap.has(r)?this.decodeProcessorMap.get(r)({frame:t,track:r}):t,type:3})}decode(i){return({frame:e,track:t})=>{if(t!==i.track)return e;if(this.contextMap.has(t))return this.contextMap.get(t).decodeFrame(e);let r=new Ia(this.core,t,i);return xe(r.trackDoneOB,So(1),ot(()=>{this.core.clearStarted(this,this.getGroup(i)),this.stop({track:t})})),this.contextMap.set(t,r),r.decodeFrame(e)}}stop({track:i}){let e=this.contextMap.get(i);!e||(e.close("stop"),this.contextMap.delete(i),this.contextMap.size===0&&this.core.room.audioManager.removeDecodeProcessor({type:3}))}update(i){let e=this.contextMap.get(i.track);if(!!e){if(i.type==="mock"){e.mock(10);return}e.close("update"),this.contextMap.set(i.track,new Ia(this.core,i.track,i))}}},hs=Aa;l(hs,"Name","AudioDecoder");var vh=0,Ca=new Set,ve=null;Ba(Ah);var I_={RtcError:P,ErrorCode:U,ErrorCodeDictionary:vt},ht=class extends Dh.EventEmitter{constructor(e,t){super();l(this,"_room");l(this,"_eventListened",new Set);l(this,"_localVideoTrack",null);l(this,"_localAudioTrack",null);l(this,"_localScreenTrack",null);l(this,"_localScreenAudioTrack",null);l(this,"_localVideoConfig",null);l(this,"_localScreenConfig",null);l(this,"_localAudioConfig",null);l(this,"_remoteVideoConfigMap",new Map);l(this,"_remoteAudioConfigMap",new Map);l(this,"_remoteAudioVolumeMap",new Map);l(this,"_remoteAudioMuteMap",new Map);l(this,"_mediaTrackMap",new WeakMap);l(this,"_log",R.createLogger({id:`t${++vh}`}));l(this,"_plugins",new Map);l(this,"_networkQuality",null);l(this,"_speakerId");l(this,"_getPCMAbortCtrl");this._room=new e(v({logger:this._log,frameWorkType:ht.frameWorkType},t)),this._log.debug(`TRTC.create() ${JSON.stringify(t,(r,o)=>r==="plugins"?o.map(n=>n.Name):o)}`),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(r){return this._room.audioManager.dump(r)}}}),t.plugins&&t.plugins.forEach(r=>{this._use(r,t.assetsPath)}),this._use(Xi,t.assetsPath),this._use(gr,t.assetsPath),this._use(hs,t.assetsPath),this._use(Er),t.enableSEI&&so&&this._use(us),this._room.on("audio-volume",r=>{!r.find(o=>o.userId==="")&&this._localAudioTrack&&r.push({userId:"",volume:Math.floor(this._localAudioTrack.getAudioLevel()*100)}),this.emit(M.AUDIO_VOLUME,{result:r.sort((o,n)=>n.volume-o.volume)})}),this._room.videoManager.on("error",r=>{this._log.error(new P({code:U.OPERATION_FAILED,extraCode:5504,message:r.message,originError:r}))}),this._listenEvents(),this._initActiveSpeaker(),Th(this,"trtc")}static create(e){}static _create(e,t){ch();let r=new ht(e,t||{});return Ca.add(r),r}get room(){return this._room}_listenEvents(){Pe(this,this._room).add("peer-join",e=>{let{userId:t}=e;this.emit(M.REMOTE_USER_ENTER,{userId:t})}).add("peer-leave",e=>{this.emit(M.REMOTE_USER_EXIT,{userId:e}),this._remoteAudioVolumeMap.delete(e)}).add("banned",e=>{this._exitRoom().then(()=>{this.emit(M.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().then(()=>{this.emit(M.ERROR,P.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(M.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let t=L(v({},e),{uplinkRTT:Math.min(e.uplinkRTT,ks),downlinkRTT:Math.min(e.downlinkRTT,ks)});this.emit(M.NETWORK_QUALITY,t)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(r=>{Pe(r,r).add("player-state-changed",o=>{let n=L(v({},o),{userId:e.userId});r.kind===m.VIDEO&&(n.streamType=vo(r.streamType)),this.emit(r.kind===m.AUDIO?M.AUDIO_PLAY_STATE_CHANGED:M.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",o=>{o.getCode()===S.PLAY_NOT_ALLOWED&&this.emit(M.AUTOPLAY_FAILED,{userId:r.userId})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(r=>{Ee(r)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:t})=>{let{userId:r}=t,o=e.audioAvailable,n=e.videoAvailable,{audioAvailable:a,videoAvailable:c}=t;a||this._remoteAudioConfigMap.delete(r),c||this._remoteVideoConfigMap.delete(`${r}_${"main"}`),t.hasAuxiliary||this._remoteVideoConfigMap.delete(`${r}_${"sub"}`),o!==a&&(this.emit(a?M.REMOTE_AUDIO_AVAILABLE:M.REMOTE_AUDIO_UNAVAILABLE,{userId:r}),a?this._onAudioAvailable({userId:r}):this._onAudioUnavailable({userId:r,muteState:t})),n!==c&&(this.emit(c?M.REMOTE_VIDEO_AVAILABLE:M.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"main"}),c?this._onVideoAvailable({userId:r,streamType:"main"}):this._onVideoUnavailable({userId:r,streamType:"main"})),e.hasAuxiliary!==t.hasAuxiliary&&(this.emit(t.hasAuxiliary?M.REMOTE_VIDEO_AVAILABLE:M.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"sub"}),t.hasAuxiliary?this._onVideoAvailable({userId:r,streamType:"sub"}):this._onVideoUnavailable({userId:r,streamType:"sub"}))}).add("sei-message",e=>{this.emit(M.SEI_MESSAGE,L(v({},e),{streamType:vo(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(M.ERROR,new P({code:U.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var o,n,a,c,d,h,u;let t={2:"big",3:"small",7:"sub"},r={rtt:Math.min(e.msg_up_stream_info.msg_network_status.uint32_rtt||((o=e.msg_down_stream_info[0])==null?void 0:o.msg_network_status.uint32_rtt)||((n=this._networkQuality)==null?void 0:n.uplinkRTT)||((a=this._networkQuality)==null?void 0:a.downlinkRTT)||0,ks),upLoss:((c=this._networkQuality)==null?void 0:c.uplinkLoss)||0,downLoss:((d=this._networkQuality)==null?void 0:d.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((h=e.msg_up_stream_info.msg_audio_status)==null?void 0:h.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((u=e.msg_up_stream_info.msg_audio_status)==null?void 0:u.uint32_audio_level)||0)/_t},video:e.msg_up_stream_info.msg_video_status.filter(p=>t[p.uint32_video_stream_type]).map(p=>({bitrate:(p.uint32_video_codec_bitrate||0)/1e3,width:p.uint32_video_width,height:p.uint32_video_height,frameRate:p.uint32_video_enc_fps,videoType:t[p.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(p=>({userId:p.msg_user_info.str_identifier,audio:{bitrate:(p.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(p.msg_audio_status.uint32_audio_level||0)/_t},video:p.msg_video_status.map(_=>({bitrate:(_.uint32_video_codec_bitrate||0)/1e3,width:_.uint32_video_width,height:_.uint32_video_height,frameRate:_.uint32_video_dec_fps,videoType:t[_.uint32_video_stream_type]}))}))};this.emit(M.STATISTICS,r)}).add("custom-message",e=>{this.emit(M.CUSTOM_MESSAGE,e)}),Pe(this,Re).add("audioInputAdded",e=>{this.emit(M.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(M.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(M.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(M.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>f(this,null,function*(){if(this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),ve&&ve.deviceId===Ms){let t=(yield Gi()).find(r=>r.deviceId===Ms);t&&ve.groupId!==t.groupId&&(ve=t,this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}})).add("audioOutputRemoved",e=>f(this,null,function*(){this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield Gi())[0];if(!t||!ve||ve.groupId===t.groupId)return;let r=ve.deviceId===e.deviceId,o=ve.deviceId===Ms&&ve.deviceId===t.deviceId;(r||o)&&(ve=t,this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}))}use(e){let t,r;"plugin"in e?(t=e.plugin,r=e.assetsPath):t=e,this._use(t,r||"https://web.sdk.qcloud.com/trtc/webrtc/v5/assets/")}_use(e,t){if(this._plugins.get(e.Name)){this._log.warn("duplicate install plugin",e.Name);return}let o=new e(Eh.call(this,{TRTC:ht,room:this._room,errorModule:I_,assetsPath:t}));this._plugins.set(e.Name,o),e.autoStart&&this.startPlugin(e.Name)}enterRoom(e){return f(this,null,function*(){var c,d;let{scene:t="rtc",enableAutoPlayDialog:r=!0,autoReceiveAudio:o=!0,autoReceiveVideo:n=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!z(e.proxy)&&e.proxy.turnServer&&((d=(c=this._room).setTurnServer)==null||d.call(c,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=r,this._room.autoReceiveAudio=o,this._room.autoReceiveVideo=n,ue(e.preferHW)&&(this._room.preferHW=e.preferHW);let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:e.role==="audience"?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language,priority:e.priority,useVp8:e.useVp8};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(a,t,ht.frameWorkType),this._checkTrackToPublish(),Xd.start()})}exitRoom(){return f(this,null,function*(){return yield this._exitRoom()})}switchRole(e,t){return f(this,null,function*(){t!=null&&t.privateMapKey&&(this._room.privateMapKey=t.privateMapKey),t!=null&&t.latencyLevel&&(this._room.latencyLevel=t.latencyLevel),yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){Ee(this),this.removeAllListeners(),this._room.destroy(),Ca.delete(this),Ca.size===0&&Xd.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),this._plugins.forEach(e=>{var t;return(t=e.destroy)==null?void 0:t.call(e)})}startLocalAudio(){return f(this,arguments,function*(e={publish:!0}){if(this._localAudioTrack){this._log.warn("local audio is already started");return}let{publish:t=!0,mute:r,option:o}=e,n=new Le(this._room.audioManager),a={},c={muted:!0};o&&(E(o.microphoneId)?E(o.audioTrack)||(a.customSource=o.audioTrack):a.deviceId=o.microphoneId,o&&K(o.captureVolume)&&n.setCaptureVolume(o.captureVolume),E(o.profile)||(z(o.profile)?Xo[o.profile]&&n.setProfile(Xo[o.profile]):n.setProfile(o.profile)),K(o.earMonitorVolume)&&(c.muted=!(o.earMonitorVolume>0),c.volume=o.earMonitorVolume),E(o.echoCancellation)||(n.profile.echoCancellation=o.echoCancellation),E(o.noiseSuppression)||(n.profile.noiseSuppression=o.noiseSuppression),E(o.autoGainControl)||(n.profile.autoGainControl=o.autoGainControl)),n.on("5",d=>{this.emit(M.ERROR,new P({code:U.DEVICE_ERROR,extraCode:5309,messageParams:{error:d}}))}),n.on("2",d=>{this.emit(M.DEVICE_CHANGED,{type:"microphone",action:"active",device:d})}),n.on("4",d=>{let h;d.error&&(h=P.convertFrom(d.error)),this.emit(M.PUBLISH_STATE_CHANGED,L(v({},d),{error:h}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId),yield n.capture(a),E(r)||n.setMute(r),Pe(n,n).add("player-state-changed",d=>{this.emit(M.AUDIO_PLAY_STATE_CHANGED,L(v({},d),{userId:""}))}),this.listeners(M.AUDIO_FRAME).length>0&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM(d=>{this.emit(ht.EVENT.AUDIO_FRAME,{data:d})})),this._getPCMAbortCtrl&&n.on("input-media-track-changed",()=>{this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("inputMediaTrackChanged"),this._getPCMAbortCtrl=this._room.audioManager.getPCM(d=>{this.emit(ht.EVENT.AUDIO_FRAME,{data:d})}))}),t&&this._room.isJoined&&this._room.publish(n).catch(()=>{}),this._localAudioTrack=n,this._localAudioConfig=L(v({},e),{publish:t}),yield this._updateAudioPlayOption({playOption:c,track:n})})}updateLocalAudio(e){return f(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:r,option:o}=e,n={};o&&(o.microphoneId?yield this._localAudioTrack.switchDevice(o.microphoneId):E(o.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(o.audioTrack)),E(o.captureVolume)||this._localAudioTrack.setCaptureVolume(o.captureVolume),E(o.earMonitorVolume)||(n.muted=!(o.earMonitorVolume>0),n.volume=o.earMonitorVolume),yield this._localAudioTrack.update3A(o)),this._room.isJoined&&!E(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),E(r)||this._localAudioTrack.setMute(r),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),fi(this._localAudioConfig,e)})}stopLocalAudio(){return f(this,null,function*(){!this._localAudioTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),Ee(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null,this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("stopLocalAudio"),delete this._getPCMAbortCtrl))})}startLocalVideo(){return f(this,arguments,function*(e={publish:!0,view:null}){if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:t,publish:r=!0,mute:o,option:n}=e,a=new me(this._room.videoManager),c={},d={};if(n&&(n.cameraId?c.deviceId=n.cameraId:E(n.useFrontCamera)?E(n.videoTrack)||(c.customSource=n.videoTrack):c.facingMode=n.useFrontCamera?m.FACING_MODE_USER:m.FACING_MODE_ENVIRONMENT,E(n.profile)||(z(n.profile)?nt[n.profile]&&a.setProfile(nt[n.profile]):a.setProfile(n.profile)),E(n.fillMode)||(d.objectFit=n.fillMode),E(n.mirror)||(d.mirror=n.mirror),E(n.small)||(to()?z(n.small)?a.small=nt[n.small]:n.small===!0?a.small=nt["120p"]:a.small=n.small:this._log.warn("small stream is not supported"))),a.on("5",h=>{this.emit(M.ERROR,new P({code:U.DEVICE_ERROR,extraCode:5308,messageParams:{error:h}}))}),a.on("2",h=>{this.emit(M.DEVICE_CHANGED,{type:"camera",action:"active",device:h})}),a.on("4",h=>{let u;h.error&&(u=P.convertFrom(h.error)),this.emit(M.PUBLISH_STATE_CHANGED,L(v({},h),{error:u}))}),this._listenOutputTrackChanged(a),yield a.capture(c),E(o)||(yield a.setMute(o)),a.mediaTrack){if(n!=null&&n.qosPreference){let h=_r(n.qosPreference);a.mediaTrack.contentHint=h}else n!=null&&n.videoTrack||(a.mediaTrack.contentHint=_r(ut.QOS_PREFERENCE_SMOOTH));a.outMediaTrack&&(a.outMediaTrack.contentHint=a.mediaTrack.contentHint)}Pe(a,a).add("player-state-changed",h=>{this.emit(M.VIDEO_PLAY_STATE_CHANGED,L(v({},h),{userId:"",streamType:"main"}))}),r&&this._room.isJoined&&this._room.publish(a).catch(()=>{}),this._localVideoTrack=a,this._localVideoConfig=L(v({},e),{view:t,publish:r}),yield this._updateVideoPlayOption({view:t,playOption:d,track:a})})}updateLocalVideo(e){return f(this,null,function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:r,mute:o,option:n}=e,a={};if(n){if(E(n.profile)||(z(n.profile)?nt[n.profile]&&this._localVideoTrack.setProfile(nt[n.profile]):this._localVideoTrack.setProfile(n.profile),(!n.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(n.cameraId))&&E(n.useFrontCamera)&&this._localVideoTrack.applyProfile()),n.cameraId?yield this._localVideoTrack.switchDevice(n.cameraId):E(n.useFrontCamera)?E(n.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(n.videoTrack)):yield this._localVideoTrack.switchDevice(n.useFrontCamera?m.FACING_MODE_USER:m.FACING_MODE_ENVIRONMENT),E(n.fillMode)||(a.objectFit=n.fillMode),E(n.mirror)||(a.mirror=n.mirror),n.qosPreference&&this._localVideoTrack.mediaTrack){let c=_r(n.qosPreference);this._localVideoTrack.mediaTrack.contentHint=c,this._localVideoTrack.outMediaTrack&&(this._localVideoTrack.outMediaTrack.contentHint=c)}if(n.small){let c=!this._localVideoTrack.small;to()?(n.small===!0?this._localVideoTrack.small=nt["120p"]:z(n.small)?this._localVideoTrack.small=nt[n.small]:this._localVideoTrack.small=n.small,this._room.videoManager.update(),c&&this._room.enableSmall(!0)):this._log.warn("small stream is not supported")}else n.small===!1&&this._localVideoTrack.small&&(delete this._localVideoTrack.small,this._room.videoManager.update(),this._room.enableSmall(!1))}this._room.isJoined&&!E(r)&&(r&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._localVideoConfig.publish&&!r&&this._room.unpublish(this._localVideoTrack).catch(()=>{})),E(o)||(yield this._localVideoTrack.setMute(o)),yield this._updateVideoPlayOption({view:t,playOption:a,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),fi(this._localVideoConfig,e)})}stopLocalVideo(){return f(this,null,function*(){!this._localVideoTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),Ee(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return f(this,arguments,function*(e={publish:!0,view:null}){if(this._localScreenTrack){this._log.warn("screen share is already started");return}let{view:t=null,publish:r=!0,option:o}=e,n=new rt(this._room.videoManager);n.on("4",u=>{let p;u.error&&(p=P.convertFrom(u.error)),this.emit(M.PUBLISH_STATE_CHANGED,L(v({},u),{error:p}))}),this._listenOutputTrackChanged(n),e.streamType==="main"&&(n.mediaType=4);let a=null,c={},d={};o&&(E(o.profile)||(z(o.profile)?Qo[o.profile]&&n.setProfile(Qo[o.profile]):n.setProfile(o.profile)),o.systemAudio&&(c.systemAudio=!0,c.echoCancellation=o.echoCancellation,c.noiseSuppression=o.noiseSuppression,c.autoGainControl=o.autoGainControl),E(o.fillMode)||(d.objectFit=o.fillMode),o.videoTrack&&(c.videoTrack=o.videoTrack),o.audioTrack&&(c.audioTrack=o.audioTrack),o.captureElement&&(c.captureElement=o.captureElement),o.preferDisplaySurface&&(c.preferDisplaySurface=o.preferDisplaySurface));let h=yield n.capture(c);if(o!=null&&o.qosPreference){let u=_r(o.qosPreference);n.mediaTrack.contentHint=u}else o!=null&&o.videoTrack||(n.mediaTrack.contentHint=_r(ut.QOS_PREFERENCE_CLEAR));if(n.mediaTrack.addEventListener(m.ENDED,()=>{this._stopScreenShare(),this.emit(M.SCREEN_SHARE_STOPPED)}),h.getAudioTracks()[0]&&(a=new Kt(this._room.audioManager),yield a.setInputMediaStreamTrack(h.getAudioTracks()[0]),this._speakerId&&a.setAudioOutput(this._speakerId)),Pe(n,n).add("player-state-changed",u=>{this.emit(M.VIDEO_PLAY_STATE_CHANGED,L(v({},u),{userId:"",streamType:"sub"}))}),r&&this._room.isJoined){let u=[n];a&&u.push(a),this._room.publish(...u).catch(()=>{})}this._localScreenTrack=n,this._localScreenAudioTrack=a,this._localScreenConfig=L(v({},e),{view:t,publish:r}),yield this._updateVideoPlayOption({view:t,playOption:d,track:n})})}updateScreenShare(e){return f(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:r,option:o}=e,n={};if(o&&(E(o.fillMode)||(n.objectFit=o.fillMode),o.qosPreference)){let a=_r(o.qosPreference);this._localScreenTrack.mediaTrack.contentHint=a}this._room.isJoined&&!E(r)&&(r&&!this._localScreenConfig.publish&&(this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch(()=>{})),this._localScreenConfig.publish&&!r&&(this._room.unpublish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.unpublish(this._localScreenAudioTrack).catch(()=>{}))),yield this._updateVideoPlayOption({view:t,playOption:n,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),fi(this._localScreenConfig,e)})}stopScreenShare(){return f(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return f(this,null,function*(){let{view:t,userId:r,streamType:o,option:n}=e,a=`${r}_${o}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${r}, streamType:${o}`);return}let c=this._room.remotePublishedUserMap.get(r);if(!c)return;let d={},h=o==="main"?c.remoteVideoTrack:c.remoteAuxiliaryTrack;this._listenOutputTrackChanged(h),n&&(E(n.fillMode)||(d.objectFit=n.fillMode),E(n.mirror)||(d.mirror=n.mirror),d.canvasRender=n.canvasRender,o==="main"&&!E(n.small)&&(c.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,h.user))),yield this._room.subscribe(h),yield this._updateVideoPlayOption({view:t,playOption:d,track:h}),this._emitTrackEvent(h),this._remoteVideoConfigMap.set(a,{config:e}),n&&!E(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:h,view:t,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:n==null?void 0:n.viewRoot})})}updateRemoteVideo(e){return f(this,null,function*(){var D,B;let{view:t,userId:r,streamType:o,option:n}=e,a=`${r}_${o}`,c=this._remoteVideoConfigMap.get(a);if(!c||!this._room.remotePublishedUserMap.has(r))return;let d={};n&&(E(n.fillMode)||(d.objectFit=n.fillMode),E(n.mirror)||(d.mirror=n.mirror));let h=null,u=this._room.remotePublishedUserMap.get(r);if(o==="main"&&(u==null?void 0:u.muteState.hasVideo)&&(h=u.remoteVideoTrack),o==="sub"&&(u==null?void 0:u.muteState.hasAuxiliary)&&(h=u.remoteAuxiliaryTrack),!h)return;let{config:p}=c;o==="main"&&n&&!E(n.small)&&this._room.changeType(n.small,h.user),yield this._updateVideoPlayOption({view:t,playOption:d,track:h,prevConfig:p}),fi(p,e);let _=E(n==null?void 0:n.receiveWhenViewVisible)?(D=p.option)==null?void 0:D.receiveWhenViewVisible:n.receiveWhenViewVisible,I=E(t)?p.view:t,C=E(n==null?void 0:n.viewRoot)?(B=p.option)==null?void 0:B.viewRoot:n.viewRoot;this._observeView({remoteTrack:h,view:I,receiveWhenViewVisible:_,viewRoot:C})})}stopRemoteVideo(e){return f(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,t=!0){return f(this,null,function*(){let r=[],o=this._room.remotePublishedUserMap.get(e.userId);if(o){let{muteState:a,remoteVideoTrack:c,remoteAuxiliaryTrack:d}=o;e.streamType==="main"&&(c.stop(),a.hasVideo&&r.push(c)),e.streamType==="sub"&&(d.stop(),a.hasAuxiliary&&r.push(d))}for(let a of r)t&&(yield this._room.unsubscribe(a),this._mediaTrackMap.get(a.outMediaTrack)===a.userId&&this._mediaTrackMap.delete(a.outMediaTrack));let n=this._remoteVideoConfigMap.get(`${e.userId}_${e.streamType}`);n&&n.observer&&n.observer.disconnect(),this._remoteVideoConfigMap.delete(`${e.userId}_${e.streamType}`)})}muteRemoteAudio(e,t){return f(this,null,function*(){if(e==="*")if(t)yield this._stopRemoteAudio({userId:e});else{let r=[...this._room.remotePublishedUserMap.values()];for(let o of r)o.muteState.hasAudio&&!this._remoteAudioConfigMap.has(o.userId)&&(yield this._startRemoteAudio({userId:o.userId}))}else t?yield this._stopRemoteAudio({userId:e}):this._remoteAudioConfigMap.has(e)||(yield this._startRemoteAudio({userId:e}));this._remoteAudioMuteMap.set(e,t)})}setRemoteAudioVolume(e,t){if(e==="*"){let r=[...this._room.remotePublishedUserMap.values()];for(let o of r)this._remoteAudioVolumeMap.set(o.userId,t),o.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:o.remoteAudioTrack})}else if(e){let r=this._room.remotePublishedUserMap.get(e);this._remoteAudioVolumeMap.set(e,t),r&&r.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:r.remoteAudioTrack})}}startPlugin(e,t){return f(this,null,function*(){return e.start(t)})}updatePlugin(e,t){return f(this,null,function*(){return e.update(t)})}stopPlugin(e,t){return f(this,null,function*(){return e.stop(t)})}enableAudioVolumeEvaluation(e=2e3,t=!1){this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,r){return this.listeners(e).includes(t)?this:(this._log.debug("on",e),super.on(e,t,r),this._eventListened.add(e),e===ht.EVENT.AUDIO_FRAME&&!this._getPCMAbortCtrl&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM(o=>{this.emit(ht.EVENT.AUDIO_FRAME,{data:o})}),this._localAudioTrack&&this._localAudioTrack.on("input-media-track-changed",()=>{this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("inputMediaTrackChanged"),this._getPCMAbortCtrl=this._room.audioManager.getPCM(o=>{this.emit(ht.EVENT.AUDIO_FRAME,{data:o})}))})),this)}emit(e,...t){try{_h.has(e)&&this._log.debug(`emit ${e} ${JSON.stringify(t)}`)}catch(r){}return super.emit(e,...t)}off(e,t,r){var o,n;return this._log.debug("off",e),e==="*"?(this._eventListened.clear(),this.removeAllListeners(),(o=this._getPCMAbortCtrl)==null||o.abort("off"),delete this._getPCMAbortCtrl):(super.off(e,t,r),e===ht.EVENT.AUDIO_FRAME&&((n=this._getPCMAbortCtrl)==null||n.abort("off"),delete this._getPCMAbortCtrl)),this}getAudioTrack(e={userId:"",streamType:"main"}){let t,r=null,o="main",n=!1;if(z(e)?t=e:(t=e.userId,n=e.processed===!0,e.streamType&&(o=e.streamType)),t){let a=this._room.remotePublishedUserMap.get(t);a&&(r=a.remoteAudioTrack)}else r=o==="sub"?this._localScreenAudioTrack:this._localAudioTrack;return r?n&&r.outMediaTrack&&r.outMediaTrack!==r.mediaTrack?r.outMediaTrack.clone():r.mediaTrack:null}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:t="",streamType:r="main",processed:o=!1}=e,n=null;if(t==="")r==="main"&&this._localVideoTrack&&(n=this._localVideoTrack),r==="sub"&&this._localScreenTrack&&(n=this._localScreenTrack);else{let a=this._room.remotePublishedUserMap.get(t);a&&(n=r==="main"?a.remoteVideoTrack:a.remoteAuxiliaryTrack)}return n?o&&n.outMediaTrack&&n.outMediaTrack!==n.mediaTrack?n.outMediaTrack.clone():n.mediaTrack:null}getVideoSnapshot(e={}){let{userId:t,streamType:r="main"}=e;if(t){let o=this._room.remotePublishedUserMap.get(t);if(r==="main"&&(o==null?void 0:o.muteState.hasVideo))return o.remoteVideoTrack.getVideoFrame();if(r==="sub"&&(o==null?void 0:o.muteState.hasAuxiliary))return o.remoteAuxiliaryTrack.getVideoFrame()}else{if(r==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(r==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(e){var t,r;this._speakerId=e,(t=this._localAudioTrack)==null||t.setAudioOutput(e),(r=this._localScreenAudioTrack)==null||r.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(o=>o.remoteAudioTrack.setAudioOutput(e))}setCurrentSpeaker(e){return f(this,null,function*(){(yield Gi()).forEach(r=>{r.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}),ve=r)}),this._log.warn('the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: https://web.sdk.qcloud.com/trtc/webrtc/v5/doc/en/TRTC.html#.setCurrentSpeaker')})}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return f(this,null,function*(){let{userId:t}=e;if(this._remoteAudioConfigMap.has(t)){this._log.warn(`remote audio has already started. userId:${t}`);return}let r=this._room.remotePublishedUserMap.get(t);if(!r)return;let o={},n=r.remoteAudioTrack;this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId);try{let a=this._remoteAudioVolumeMap.get(t),c=K(a)?a:100;o.volume=c,this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(n),xe(Fe(n,"decode-failed"),Nt(Fe(n,oe.INIT)),ot(()=>{this.startPlugin(hs.Name,{track:n,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:o,track:n})}catch(a){throw this._remoteAudioConfigMap.delete(t),a}this._emitTrackEvent(n)})}_stopRemoteAudio(e,t=!0){return f(this,null,function*(){let r=this._room.remotePublishedUserMap.get(e.userId);r&&(r.remoteAudioTrack.stop(),r.muteState.hasAudio&&t&&(yield this._room.unsubscribe(r.remoteAudioTrack)),this._mediaTrackMap.get(r.remoteAudioTrack.outMediaTrack)===e.userId&&this._mediaTrackMap.delete(r.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete(`${e.userId}`)})}_updateVideoPlayOption(n){return f(this,arguments,function*({view:e,playOption:t,track:r,prevConfig:o}){if(r.setMirror(t.mirror),E(e)&&o&&o.view&&!Tc(t)){let a=zs(o.view);a.length>0&&(yield r.play(a,t))}if(!E(e)){let a=zs(e);a.length>0?yield r.play(a,t):r.stop()}})}_updateAudioPlayOption(o){return f(this,arguments,function*({playOption:e={},track:t,prevConfig:r}){if(!t.isPlayCalled)try{yield t.play(null,e)}catch(n){}E(e.muted)||t.setPlayerMute(e.muted),E(e.volume)||t.setAudioVolume(e.volume/100)})}_listenOutputTrackChanged(e){e.listeners("output-media-track-changed").length===0&&e.on("output-media-track-changed",()=>this._emitTrackEvent(e,!1))}_emitTrackEvent(e,t=!0){let r=e.isRemote?e.userId:"";!e.outMediaTrack||t&&this._mediaTrackMap.get(e.outMediaTrack)===r||(this._mediaTrackMap.set(e.outMediaTrack,r),this.emit(M.TRACK,{userId:r,streamType:vo(e.streamType),track:e.outMediaTrack}))}_checkTrackToPublish(){var t,r,o;let e=[];if(((t=this._localAudioConfig)==null?void 0:t.publish)&&this._localAudioTrack&&e.push(this._localAudioTrack),((r=this._localVideoConfig)==null?void 0:r.publish)&&this._localVideoTrack&&e.push(this._localVideoTrack),(o=this._localScreenConfig)!=null&&o.publish&&(this._localScreenTrack&&e.push(this._localScreenTrack),this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack)),e.length!==0)return this._room.publish(...e).catch(()=>{})}_observeView({remoteTrack:e,view:t,receiveWhenViewVisible:r=!1,viewRoot:o}){if(E(t))return;let n=this._remoteVideoConfigMap.get(`${e.userId}_${vo(e.streamType)}`);if(!n)return;let a=n.observer||void 0;if(t===null||_e(t)&&t.length===0||!r){a==null||a.disconnect(),e.isSubscribed||this._room.subscribe(e).catch(()=>{});return}let d=n.visibleViewMap||new Map,h=-1;(!a||a.root!==o)&&(a==null||a.disconnect(),d.clear(),a=new IntersectionObserver(p=>{p.forEach(_=>{d.set(_.target,_.isIntersecting)}),clearTimeout(h),h=window.setTimeout(()=>{[...d.values()].find(I=>I)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:o}));let u=new Set(zs(t));d.forEach((p,_)=>{u.has(_)||(a.unobserve(_),d.delete(_))}),u.forEach(p=>{d.set(p,!0),a.observe(p)}),a.takeRecords().forEach(p=>{d.set(p.target,p.isIntersecting)}),n.visibleViewMap=d,n.observer=a}_exitRoom(){return f(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(e=>{this._stopRemoteAudio({userId:e}).catch()}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let t=e.includes("main")?"main":"sub",r=e.split(`_${t}`)[0];r&&this._stopRemoteVideo({userId:r,streamType:t}).catch()}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._remoteAudioVolumeMap.clear(),Sh(this),this._room.remotePublishedUserMap.forEach(e=>{Ee(e.remoteAudioTrack),Ee(e.remoteVideoTrack),Ee(e.remoteAuxiliaryTrack)})})}_stopScreenShare(){return f(this,null,function*(){var e;if(!!this._localScreenTrack){if(this._room.isJoined){let t=[this._localScreenTrack];this._localScreenAudioTrack&&t.push(this._localScreenAudioTrack),yield(e=this._room)==null?void 0:e.unpublish(...t).catch(()=>{})}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),Ee(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_initActiveSpeaker(){return f(this,null,function*(){if(ve&&!Yr(ve))this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:ve});else{let e=yield Gi();if(e[0]&&!Yr(e[0]))ve=e[0],this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]});else{let t=({track:r})=>{r.kind==="audio"&&(!ve||Yr(ve))&&(this._initActiveSpeaker(),T.off("102",this._initActiveSpeaker))};T.on("102",t)}}})}_onAudioAvailable({userId:e}){let t=this._remoteAudioMuteMap.has(e)?this._remoteAudioMuteMap.get(e):this._remoteAudioMuteMap.get("*");(t===!1||this._room.autoReceiveAudio&&!t)&&this._doStartRemoteAudio({userId:e}).catch(()=>{})}_onVideoAvailable({userId:e,streamType:t}){if(!this._room.autoReceiveVideo)return;let r=this._room.remotePublishedUserMap.get(e);if(r){let o=t==="main"?r.remoteVideoTrack:r.remoteAuxiliaryTrack;this._room.subscribe(o).then(()=>{this._emitTrackEvent(o)}).catch(()=>{})}}_onAudioUnavailable({userId:e,muteState:t}){t.hasAudio&&t.audioMuted||this._stopRemoteAudio({userId:e},!1).catch(()=>{})}_onVideoUnavailable({userId:e,streamType:t}){this._stopRemoteVideo({userId:e,streamType:t},!1).catch(()=>{})}sendSEIMessage(e,t){var o;let r=this._plugins.get("SEI");r&&(r.update({buffer:e,options:L(v({seiPayloadType:243},t),{small:!!((o=this._localVideoTrack)!=null&&o.small)})}),N.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,r;(r=(t=this._room).sendCustomMessage)==null||r.call(t,e),N.addCount({key:500001,useUV:!0})}static setLogLevel(e,t){R.setLogLevel(e),E(t)||(t?R.enableUploadLog():R.disableUploadLog())}static isSupported(){return kn()}static getCameraList(e=!0){return tt(e)}static getMicrophoneList(e=!0){return Xe(e)}static getSpeakerList(e=!0){return Gi(e)}static setCurrentSpeaker(e){return f(this,null,function*(){(yield Gi()).forEach(r=>{r.deviceId===e&&(Ca.forEach(o=>{o._setCurrentSpeaker(e),o.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:r})}),ve=r)})})}static _addKVStat({type:e,key:t,value:r,base:o,useUV:n,version:a}){switch(a&&(nr.version=a),e){case"count":nr.addCount({key:t,useUV:n});break;case"enum":nr.addEnum({key:t,value:r,useUV:n});break;case"number":nr.addNumber({key:t,value:r,split:o});break}}},X=ht;l(X,"_loggerManager",R),l(X,"EVENT",M),l(X,"ERROR_CODE",U),l(X,"TYPE",ut),l(X,"frameWorkType",30),b([ae({replaceArg:s=>({argIndex:0,value:{name:"plugin"in s?s.plugin.Name:s.Name,assetsPath:"assetsPath"in s?s==null?void 0:s.assetsPath:"default"}})})],X.prototype,"use",1),b([Ue(Ne.TRTC.enterRoom),ji("room",([s],[i])=>(s.roomId||s.strRoomId)===(i.roomId||i.strRoomId)&&s.userId===i.userId&&s.sdkAppId===i.sdkAppId),G(s=>function(i){return this._log.setUserId(i.userId),this._log.setSdkAppId(i.sdkAppId),s.call(this,i)}),ae()],X.prototype,"enterRoom",1),b([ae()],X.prototype,"exitRoom",1),b([Ue(Ne.TRTC.switchRole),fr("room",{merge:(s,i)=>i}),ae()],X.prototype,"switchRole",1),b([ae()],X.prototype,"destroy",1),b([Ue(Ne.TRTC.startLocalAudio),ji("audio",([s],[i])=>{var e,t;return((e=s==null?void 0:s.option)==null?void 0:e.microphoneId)===((t=i==null?void 0:i.option)==null?void 0:t.microphoneId)}),ae()],X.prototype,"startLocalAudio",1),b([Ue(Ne.TRTC.updateLocalAudio),fr("audio",{debounce:{delay:200,getKey:()=>`${vh}-localAudio`,isNeedToDebounce:s=>{var i;return!E((i=s.option)==null?void 0:i.captureVolume)}}}),ae()],X.prototype,"updateLocalAudio",1),b([qi("audio"),ae()],X.prototype,"stopLocalAudio",1),b([Ue(Ne.TRTC.startLocalVideo),ji("video",([s],[i])=>{var e,t;return((e=s==null?void 0:s.option)==null?void 0:e.cameraId)===((t=i==null?void 0:i.option)==null?void 0:t.cameraId)}),ae()],X.prototype,"startLocalVideo",1),b([Ue(Ne.TRTC.updateLocalVideo),fr("video"),ae()],X.prototype,"updateLocalVideo",1),b([qi("video"),ae()],X.prototype,"stopLocalVideo",1),b([Ue(Ne.TRTC.startScreenShare),ji("screen",()=>!0),ae()],X.prototype,"startScreenShare",1),b([Ue(Ne.TRTC.updateScreenShare),fr("screen"),ae()],X.prototype,"updateScreenShare",1),b([ae()],X.prototype,"stopScreenShare",1),b([Ue(Ne.TRTC.startRemoteVideo),ji(s=>`v${s.userId}${s.streamType}`,()=>!0),ae({getRemoteId:s=>`${s.userId}_${s.streamType}`})],X.prototype,"startRemoteVideo",1),b([Ue(Ne.TRTC.updateRemoteVideo),fr(s=>`v${s.userId}${s.streamType}`),ae({getRemoteId:s=>`${s.userId}_${s.streamType}`})],X.prototype,"updateRemoteVideo",1),b([Ue(Ne.TRTC.stopRemoteVideo),G(s=>function(i){return f(this,null,function*(){if(i.userId==="*"){let e=[];return this._room.remotePublishedUserMap.forEach(t=>{this._remoteVideoConfigMap.has(`${t.userId}_${"main"}`)&&e.push(this.stopRemoteVideo({streamType:"main",userId:t.userId}).catch(()=>{})),this._remoteVideoConfigMap.has(`${t.userId}_${"sub"}`)&&e.push(this.stopRemoteVideo({streamType:"sub",userId:t.userId}).catch(()=>{}))}),Promise.all(e)}return s.call(this,i)})}),ae({getRemoteId:s=>`${s.userId}_${s.streamType}`})],X.prototype,"stopRemoteVideo",1),b([qi(s=>`v${s.userId}${s.streamType}`)],X.prototype,"_stopRemoteVideo",1),b([Ue(...Ne.TRTC.muteRemoteAudio),ae({getRemoteId:s=>s})],X.prototype,"muteRemoteAudio",1),b([Wd(...Ne.TRTC.setRemoteAudioVolume),Ih(200,s=>s),ae({getRemoteId:s=>s})],X.prototype,"setRemoteAudioVolume",1),b([ga("start"),bt(s=>{var i;return(i=s.afterStart)==null?void 0:i.call(s)}),ji((s,i)=>s.disableRandomCall?null:s.getAlias()+s.getGroup(i)),ae({replaceArg:s=>({argIndex:0,value:s.getName()}),getKVReportKey:s=>Dc[s.getName()],ignoreLog:s=>s.getName()==="Debug"})],X.prototype,"startPlugin",1),b([ga("update"),fr((s,i)=>s.disableRandomCall?null:s.getAlias()+s.getGroup(i)),ae({replaceArg:s=>({argIndex:0,value:s.getName()}),getKVReportKey:s=>Oc[s.getName()]})],X.prototype,"updatePlugin",1),b([ga("stop"),qi((s,i)=>{if(s.disableRandomCall)return null;let e=s.getGroup(i),t=s.getAlias();return e==="*"?new RegExp(`${t}.*`):t+e}),ae({replaceArg:s=>({argIndex:0,value:s.getName()}),getKVReportKey:s=>Mc[s.getName()]})],X.prototype,"stopPlugin",1),b([Wd(...Ne.TRTC.enableAudioVolumeEvaluation)],X.prototype,"enableAudioVolumeEvaluation",1),b([ae()],X.prototype,"getVideoSnapshot",1),b([ae()],X.prototype,"_setCurrentSpeaker",1),b([ji(s=>`a${s.userId}`,()=>!0)],X.prototype,"_startRemoteAudio",1),b([G(s=>function(i){return f(this,null,function*(){return i.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(e=>this._stopRemoteAudio(L(v({},i),{userId:e.userId})).catch(()=>{}))):s.call(this,i)})}),qi(s=>`a${s.userId}`)],X.prototype,"_stopRemoteAudio",1),b([qi("room")],X.prototype,"_exitRoom",1),b([qi("screen")],X.prototype,"_stopScreenShare",1),b([Ue(...Ne.TRTC.sendSEIMessage),Hd({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...s)=>s[0].byteLength})],X.prototype,"sendSEIMessage",1),b([Ue(Ne.TRTC.sendCustomMessage),Hd({timesInSecond:30,maxSizeInSecond:8e3,getSize:s=>s.data.byteLength})],X.prototype,"sendCustomMessage",1),b([Ue(Ne.TRTC.create)],X,"_create",1);var Do=X;var sl=class{constructor(){this._set=new Set;T.on(g.LEAVE_SUCCESS,this.delete,this)}add({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,e||i.roomId,i.sdkAppId,i.useStringRoomId);this._set.add(t)}delete({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,i.roomId||e,i.sdkAppId,i.useStringRoomId);this._set.delete(t)}getKey(i,e,t,r){return`${t}_${e}_${i}_${r}`}isJoined({userId:i,roomId:e,sdkAppId:t,room:r}){return r.scene==="rtc"?!1:this._set.has(this.getKey(i,e,t,r.useStringRoomId))}};function A_(){return f(this,null,function*(){let s,i;try{let u=yield Xe();s=u&&u.length}catch(u){}try{let u=yield tt();i=u&&u.length}catch(u){}let e={microphone:s,camera:i},{isH264EncodeSupported:t,isVp8EncodeSupported:r,isH264DecodeSupported:o,isVp8DecodeSupported:n}=this.checkSystemResult.detail,a=Wt.basis(),c={webRTC:a.isWebRTCSupported,getUserMedia:a.isGetUserMediaSupported,webSocket:a.isWebSocketsSupported,screenShare:a.isScreenShareSupported,webAudio:a.isWebAudioSupported,h264Encode:t,h264Decode:o,vp8Encode:r,vp8Decode:n},d={browser:a.browser,os:a.os,trtc:c,devices:e},h={isWebCodecSupported:a.isWebCodecSupported,isMediaSessionSupported:a.isMediaSessionSupported,isWebTransportSupported:a.isWebTransportSupported};Y.uploadEvent({log:`trtcstats-${JSON.stringify(d)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(d)}`),Y.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(h)}`,userId:this.userId})})}function Oh(){return G(s=>{let i=new sl;return function(e,t,r){return f(this,null,function*(){let o=String(e.roomId||e.strRoomId);if(this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.userSig=e.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=t,e.privateMapKey=e.privateMapKey||"",this.isJoined)throw new y({code:S.INVALID_OPERATION,message:w({key:x.INVALID_JOIN})});if(this.checkDestroy(),i.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this}))throw new y({code:S.INVALID_OPERATION,message:w({key:x.REPEAT_JOIN,data:this.userId})});i.add({room:this,roomId:o}),this.role=e.role===21?"audience":"anchor",this._log.info(`Join() => joining room: ${o} useStringRoomId: ${this.useStringRoomId} scene: ${this.scene} role: ${this.role}`),T.emit(g.JOIN_START,{room:this,roomId:o,params:e});let n=Be.getEnv();n||(n=si.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(zo.OLD_CLOUD_LADDER)?n=si.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(zo.WEBRTC)&&(n=si.WEBRTC))),Y.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),Wt.checkSystemRequirementsInternal().then(a=>{this.checkSystemResult=a,A_.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Be.getEnv()&&(yield this.schedule(e,r));let a=yield s.call(this,e,t,r);return this.roomId=o,this._joinedTimestamp=Be.performanceNow(),T.emit(g.JOIN_SUCCESS,{room:this}),r===30&&!e.component&&Y.uploadEvent({log:`stat-conv-${Number(li)}-${location.hostname}`,userId:this.userId}),a}catch(a){throw i.delete({room:this,roomId:o}),T.emit(g.JOIN_FAILED,{room:this,error:a}),a}})}})}var Mh=()=>G(s=>function(...i){return f(this,null,function*(){T.emit(g.LEAVE_START,{room:this}),yield s.call(this),T.emit(g.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function kh(){return G(s=>function(...i){let e=s.apply(this,i);return i.forEach(t=>!t.isSubscribed&&t.subscribe(e)),e})}var Lh=Se(De());var pe={SETUP_SUCCESS:"1",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",RECONNECT_FAILED:"4",SETUP_FAILED:"5",DISCONNECTED:"6"};var Dt={CLIENT_BANNED:9,CHANNEL_SETUP_RESULT:19,CHANNEL_RECONNECT_RESULT:514,JOIN_ROOM_RESULT:20,PEER_JOIN:4134,PEER_LEAVE:4135,STREAM_ADDED:16,STREAM_REMOVED:18,UPLINK_NETWORK_STATS:22,UPDATE_REMOTE_MUTE_STAT:23,PUBLISH_RESULT:4098,PUBLISH_STATE_CHANGE_RESULT:4112,UNPUBLISH_RESULT:4100,SUBSCRIBE_RESULT:4102,UNSUBSCRIBE_RESULT:4104,SUBSCRIBE_CHANGE_RESULT:4106,MUTE_RESULT:4108,UPDATE_OFFER_RESULT:4128,START_PUBLISH_TENCENT_CDN_RES:1286,STOP_PUBLISH_TENCENT_CDN_RES:1288,START_PUBLISH_GIVEN_CDN_RES:777,STOP_PUBLISH_GIVEN_CDN_RES:779,START_MIX_TRANSCODE_RES:781,STOP_MIX_TRANSCODE_RES:783,START_PUBLISH_CDN_STREAM_RES:8196,UPDATE_PUBLISH_CDN_STREAM_RES:8198,STOP_PUBLISH_CDN_STREAM_RES:8200,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772,REBUILD_PEER_CONNECTION_RES:4150,SPC_PUBLISH_RESULT:4146,SPC_SUBSCRIBE_RESULT:4156,ABILITY_STATUS_REPORT_RESULT:4158,SERVER_FIRST_PACKAGE_RECEIVED:5e3,RECEIVE_CUSTOM_MSG:4140},Ph=[Dt.UPDATE_REMOTE_MUTE_STAT,Dt.UPLINK_NETWORK_STATS,Dt.USER_LIST_RES,Dt.MUTE_RESULT,Dt.SERVER_FIRST_PACKAGE_RECEIVED,Dt.RECEIVE_CUSTOM_MSG],V={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",START_PUBLISH_CDN_STREAM_RES:"start-publish-cdn-stream-res",UPDATE_PUBLISH_CDN_STREAM_RES:"update-publish-cdn-stream-res",STOP_PUBLISH_CDN_STREAM_RES:"stop-publish-cdn-stream-res",USER_LIST_RES:"user-list-res",SWITCH_ROLE_RES:"switch_role_res",MUTE_RESULT:"mute-result",UPDATE_CONSTRAINT_CONFIG_RES:"update-contraint-config-res",REBUILD_PEER_CONNECTION_RES:"rebuild-pc-res",SPC_PUBLISH_RESULT:"spc-publish-result",SPC_SUBSCRIBE_RESULT:"spc-subscribe-result",ABILITY_STATUS_REPORT_RESULT:"ability-status-report",SERVER_FIRST_PACKAGE_RECEIVED:"first-pkg-received",RECEIVE_CUSTOM_MSG:"receive-custom-msg"},W={PUBLISH_CHANGE:"publish_change",JOIN_ROOM:"join",LEAVE_ROOM:"leave",ON_QUALITY_REPORT:"quality_report",UPDATE_MUTE_STAT:"mute_uplink",PUBLISH:"publish",PUBLISH_STATE_CHANGE:"publish_state_change",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",RECEIVE_DATA_USER_LIST:"receive_data_userlist",UNSUBSCRIBE:"unsubscribe",SUBSCRIBE_CHANGE:"subscribe_change",START_PUBLISH_TENCENT_CDN:"start_publishing",STOP_PUBLISH_TENCENT_CDN:"stop_publishing",START_PUBLISH_GIVEN_CDN:"start_push_user_cdn",STOP_PUBLISH_GIVEN_CDN:"stop_push_user_cdn",START_MIX_TRANSCODE:"start_mcu_mix",STOP_MIX_TRANSCODE:"stop_mcu_mix",START_PUBLISH_CDN_STREAM:"start_publish_cdn_stream",UPDATE_PUBLISH_CDN_STREAM:"update_publish_cdn_stream",STOP_PUBLISH_CDN_STREAM:"stop_publish_cdn_stream",GET_USER_LIST:"get_user_list",SWITCH_ROLE:"change_role",UPDATE_CONSTRAINT_CONFIG:"update_constraint_config",REBUILD_PEER_CONNECTION:"rebuild_pc",READY_TO_RECEIVE_DATA:"ready_to_receive",SPC_JOIN_ROOM:"join/v2",SPC_PUBLISH:"publish/v2",SPC_SUBSCRIBE:"subscribe/v3",ABILITY_STATUS_REPORT:"ability_status_report",RECONNECT_WS:"reconnect",SEND_CUSTOM_MSG:"channel_msg"};var Ra=new Set;function xh(s){let i=[...Ra.values()].find(e=>e.room.userId===s&&!e.room.isJoined);return i||null}var ms=class extends Lh.default{constructor(e){var r,o;super();l(this,"room");l(this,"url");l(this,"backupUrl");l(this,"race");l(this,"destroyed",!1);l(this,"_socketInUse");l(this,"_socket");l(this,"_backupSocket");l(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0});l(this,"_currentState","DISCONNECTED");l(this,"_isReconnecting",!1);l(this,"_seq",0);l(this,"_log");l(this,"_lastMessageTime",-1);l(this,"_connnectStartTime",-1);l(this,"_stopConnectRetry");l(this,"bytesSent",0);l(this,"bytesReceived",0);l(this,"keepAlive",!1);l(this,"signalDomainWhenUnifiedProxy");l(this,"stopKeepAliveTimeout");l(this,"rtt",0);this.room=e.room,this.race=E(e.race)?!0:e.race,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy,(((o=(r=this.room.scheduleResult)==null?void 0:r.config)==null?void 0:o.keepAliveClient)||0)-Ra.size>0&&this.room.enableSPC&&(this.keepAlive=!0,Ra.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=R.createLogger({id:"ws",userId:this.userId,sdkAppId:this.sdkAppId}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get urlParam(){let e=`?sdkAppId=${encodeURIComponent(this.sdkAppId)}&userId=${encodeURIComponent(this.userId)}&userSig=${encodeURIComponent(this.userSig)}&keepAlive=${encodeURIComponent(Number(this.keepAlive))}`;this.signalDomainWhenUnifiedProxy&&(e+=`&signalDomain=${encodeURIComponent(this.signalDomainWhenUnifiedProxy)}`);let t=new URLSearchParams(location.search).get("clientIp");return t&&(e+=`&clientIp=${t}`),this.race?`${e}&race=1`:e}get _urlWithParam(){return`${this.url}${this.race?"/v2/ws":""}${this.urlParam}`}get _backupUrlWithParam(){return`${this.backupUrl}${this.race?"/v2/ws":""}${this.urlParam}`}get isConnected(){return this._currentState==="CONNECTED"}get isConnecting(){return this._currentState==="CONNECTING"}get sdkAppId(){return this.room.sdkAppId}get userId(){return this.room.userId}get userSig(){return this.room.userSig}get isOnline(){return this._currentState==="CONNECTED"&&Date.now()-this._lastMessageTime<12*1e3}connect(){return f(this,arguments,function*(e=10*1e3){if(this.isConnected)return Promise.resolve();this._log.info(`connect to [${this.url}, ${this.backupUrl}]${e?` timeout: ${e}`:""} keepAlive: ${Number(this.keepAlive)}`),this.emitConnectionStateChanged("CONNECTING"),this._connnectStartTime=k();let t=[this.connectWS({url:this._urlWithParam,isMain:!0,timeout:e})];this.race&&this._backupUrlWithParam!==this._urlWithParam&&t.push(this.connectWS({url:this._backupUrlWithParam,isMain:!1,timeout:e})),this._socketInUse=yield js(t),this.unbindAndCloseSocket(this._socketInUse===this._socket?m.BACKUP:m.MAIN),this.emitConnectionStateChanged("CONNECTED")})}connectWS({url:e,timeout:t,isMain:r}){let o=new WebSocket(e);this.bindSocket(o),r?this._socket=o:this._backupSocket=o;let n=-1;return new Promise((a,c)=>{o.onclose=c,o.onerror=c,o.onopen=()=>a(o),t&&(n=setTimeout(()=>{this.unbindAndCloseSocket(r?m.MAIN:m.BACKUP),c(new y({code:S.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))},t))}).finally(()=>{o.onclose=null,o.onerror=null,o.onopen=null,clearTimeout(n)})}bindSocket(e){e.addEventListener("close",this.onclose),e.addEventListener("error",this.onerror),e.addEventListener("message",this.onmessage)}unbindSocket(e){e.removeEventListener("close",this.onclose),e.removeEventListener("error",this.onerror),e.removeEventListener("message",this.onmessage)}unbindAndCloseSocket(e){if(e===m.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(t){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(t){}this._backupSocket=null}}onclose(e){e.target===this._socketInUse&&(this._log.warn(`${e.target===this._socket?"main":"backup"} is closed code:${e.code} ${e.reason}`),this.emitConnectionStateChanged("DISCONNECTED"),(!e.wasClean||e.code!==1e3)&&this.startReconnection(),this.room.isJoining&&this.emit(pe.SETUP_FAILED,new y({code:S.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onclose"})))}onerror(e){this._log.error(`${e.target===this._socket?"main":"backup"} error observed`),this.emitConnectionStateChanged("DISCONNECTED"),e.target===this._socketInUse&&(this.unbindAndCloseSocket(m.MAIN),this.unbindAndCloseSocket(m.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(pe.SETUP_FAILED,new y({code:S.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=Cn(e.data);let t=JSON.parse(e.data),{cmd:r,data:o}=t,n=Object.values(Dt),c=Object.keys(Dt)[n.indexOf(r)],d=V[c]||r;switch(Ph.includes(r)||(this._log.debug(`received ${r} msg: ${e.data}`),d&&this._log.info(`Received event: [ ${d} ]`)),r){case Dt.CHANNEL_SETUP_RESULT:{if(t.code===0)this._signalInfo.clientIp=o.clientIp,this._signalInfo.signalIp=o.signalInnerIp,o.svrTime&&Ll(o.svrTime),this._log.info(`ChannelSetup Success ${k()-this._connnectStartTime}`),N.addSuccessEvent({key:521701,cost:k()-this._connnectStartTime}),this._connnectStartTime=-1,this.emit(pe.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let h=new y({code:S.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:w({key:x.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error(`${t.code}, ${t.message}`),this.close(),N.addFailedEvent({key:521701,error:h}),this.emit(pe.SETUP_FAILED,h)}break}case Dt.JOIN_ROOM_RESULT:{t.code===0&&(this._signalInfo.relayIp=o.relayOuterIp,this._signalInfo.relayInnerIp=o.relayInnerIp,this._signalInfo.relayPort=o.relayPort,this._signalInfo.tinyId=t.tinyId,this._signalInfo.endReportExtend=o.endReportExtend,this._log.info(`signalIp:${this._signalInfo.signalIp} clientIp:${this._signalInfo.clientIp} relayIp: ${this._signalInfo.relayIp}`)),this.emit(d,{data:t});break}default:this.emit(String(d),{data:t});break}}reGetSignalChannelUrl(){return f(this,null,function*(){try{if(!this.room.joinParams)return;$t(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(e){}})}startReconnection(){if(!this._socketInUse)return;this._socketInUse.onclose=null,this._socketInUse.close(4011);let e=this._socketInUse===this._socket;this.unbindAndCloseSocket(e?m.MAIN:m.BACKUP),this._socketInUse=null,this.emitConnectionStateChanged("DISCONNECTED"),this.reconnect()}reconnect(){return f(this,null,function*(){if(!this._isReconnecting){if(!this.room.isJoined&&this.keepAlive){this.close();return}this._isReconnecting=!0;try{this._log.warn("reconnect"),yield this.connect();let{roomId:e,useStringRoomId:t}=this.room,{relayIp:r,relayInnerIp:o,relayPort:n}=this._signalInfo,{data:a}=yield this.sendWaitForResponse({command:W.RECONNECT_WS,data:{roomId:e,useStringRoomId:t,relayInnerIp:o,relayOuterIp:r,relayPort:n},responseCommand:V.CHANNEL_RECONNECT_RESULT});a.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),N.addSuccessEvent({key:521702,cost:k()-this._connnectStartTime}),this._connnectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(N.addFailedEvent({key:521702,error:a.code}),this._log.warn(`reconnect failed, ${a.code} ${a.message}`),this.room.reJoin())}catch(e){this._log.error(e),this.room.reJoin()}}})}send(e,t={}){if(this.isConnected&&!this.room.isLeft){let r={cmd:e,data:t,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},o=JSON.stringify(r);return this._socketInUse.send(o),this.bytesSent+=Cn(o),r.seq}}sendWaitForResponse({command:e,data:t,timeout:r=5e3,responseCommand:o,commandDesc:n,enableLog:a=!0,addReceiveTime:c=!1}){return new Promise((d,h)=>{let u=setTimeout(()=>{this.off(o,_);let C=new y({code:S.API_CALL_TIMEOUT,message:w({key:x.API_CALL_TIMEOUT,data:{commandDesc:n,command:e}})});a&&this._log.warn(C),h(C)},r),p=Date.now(),_=C=>{C.data.seq===I&&(clearTimeout(u),this.off(o,_),c&&(C.data.receiveTime=Date.now()),d(C))};this.on(o,_);let I=this.send(e,t)})}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:r,retries:o=0,retryTimeout:n=0}=e;return Ut({retryFunction:this.sendWaitForResponse,onError:({retry:a})=>{this.isOnline?a():(this._log.warn(`retry ${r} when connected`),this.once(pe.CONNECTED,a))},onRetrying:a=>{this._log.warn(`${t||r} timeout observed, retrying [${a}/${o}]`)},settings:{retries:o,timeout:n},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),clearTimeout(this.stopKeepAliveTimeout),Ra.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(m.MAIN),this.unbindAndCloseSocket(m.BACKUP),this.emitConnectionStateChanged("DISCONNECTED")}destroy(){this.close(),this.destroyed=!0}stopKeepAliveIn(e=3600){if(this.keepAlive){this._log.info(`stopKeepAlive in ${e}s`),this.stopKeepAliveTimeout=setTimeout(()=>{this.keepAlive=!1,this._log.info(`close due to not used ${e}s`),this.close(),this.off(V.JOIN_ROOM_RESULT,t)},e*1e3);let t=r=>{r.data.code===0&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(V.JOIN_ROOM_RESULT,t))};this.on(V.JOIN_ROOM_RESULT,t)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info(`${this._currentState} -> ${e}`),this.emit(pe.CONNECTION_STATE_CHANGED,{prevState:this._currentState,state:e}),this._currentState=e,e==="CONNECTED"?this.emit(pe.CONNECTED):e==="DISCONNECTED"&&this.emit(pe.DISCONNECTED))}};b([je({settings:{retries:1/0,timeout:2e3},onError(s,i){!this.room.isDestroyed&&!this.destroyed&&i()},onRetrying(s,i){this._log.warn(`retrying to connect ${s}`),s>=3&&s%3===0&&this.reGetSignalChannelUrl(),i&&(this._stopConnectRetry=i,(this.room.isDestroyed||this.destroyed)&&i())}})],ms.prototype,"connect",1);var wh=Se(De());var ol=0,nl=!1,ya=new Set,R_=s=>ol>2&&!nl&&ya.size===0&&s,al=!1,He=class{constructor(i){l(this,"userId");l(this,"tinyId");l(this,"_sdpSemantics");l(this,"_isUplink");l(this,"_room");l(this,"_log");l(this,"_signalChannel");l(this,"_isErrorObserved",!1);l(this,"_waitForPeerConnectionConnectedPromise");l(this,"_waitForPeerConnectionConnectedPromiseReject",null);l(this,"_peerConnection",null);l(this,"_emitter",new wh.default);l(this,"_currentState","DISCONNECTED");l(this,"_isReconnecting",!1);l(this,"_reconnectionCount",0);l(this,"_reconnectionTimer",-1);l(this,"_isFirstConnection",!0);l(this,"_prevTime",-1);l(this,"_localAddress");l(this,"_remoteAddress");this.userId=i.userId,this.tinyId=i.tinyId,this._room=i.room,this._sdpSemantics=i.room.sdpSemantics,this._isUplink=i.isUplink,this._log=R.createLogger({id:"n-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=i.signalChannel}beforeConnect(){this._prevTime<0&&(this._prevTime=k())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,N.addSuccessEvent({key:521705,cost:Math.min(k()-this._prevTime,30*1e3)})):this._isReconnecting&&N.addSuccessEvent({key:521706,cost:k()-this._prevTime}),this._prevTime=-1}catch(i){throw this._isFirstConnection?(this._isFirstConnection=!1,N.addFailedEvent({key:521705,error:i})):this._isReconnecting&&this._reconnectionCount>=3&&N.addFailedEvent({key:521706,error:i}),i}}initialize(){let i={iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"};this._peerConnection=new RTCPeerConnection(i),this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this)}close(i){this._log.info("close connection"),this._emitter.emit("closed",i),this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),ya.delete(this)}closePeerConnection(i=!1){this._peerConnection&&(this._log.info("close pc"),this._peerConnection.onconnectionstatechange=null,this._peerConnection.close(),this._peerConnection=null,i&&this.emitConnectionStateChangedEvent("DISCONNECTED")),this._waitForPeerConnectionConnectedPromiseReject&&this._waitForPeerConnectionConnectedPromiseReject(new y({code:S.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return ft;let i=null;if(this._isUplink){if(!Hi()||this._peerConnection.getSenders().length===0)return ft;i=this._peerConnection.getSenders()[0].transport}else{if(!ar()||this._peerConnection.getReceivers().length===0)return ft;i=this._peerConnection.getReceivers()[0].transport}return i?i.state:ft}onConnectionStateChange(i){let e=this._peerConnection.iceConnectionState,t=this.getDTLSTransportState();if(this._log.info(`connectionState: ${i.target.connectionState}, ICE: ${e}, DTLS: ${t}`),i.target.connectionState===ne.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),i.target.connectionState===ne.FAILED||i.target.connectionState===ne.CLOSED){let r=`connection ${i.target.connectionState}. ICE Transport state: ${e}, DTLS Transport state: ${t}`,o=new y({message:r,code:S.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",o)}(i.target.connectionState===ne.CONNECTED||i.target.connectionState===ne.COMPLETED)&&(this.logSelectedCandidate(),Y.logSuccessEvent({userId:this._room.userId,eventType:Ge.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(i){return i===this._currentState?!1:(i==="CONNECTED"?(ol=0,nl=!1,al=!0,ya.add(this)):ya.delete(this),T.emit(g.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:i,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:i}),this._currentState=i,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}logSelectedCandidate(){return f(this,null,function*(){if(!this._peerConnection)return;let i=yield this._peerConnection.getStats();for(let[,e]of i)if(Fi(e)){let t=i.get(e.localCandidateId),r=i.get(e.remoteCandidateId);t&&(this._log.info(`local candidate: ${t.candidateType} ${t.protocol}:${t.ip||t.address}:${t.port} ${t.networkType||""} ${t.candidateType==="relay"?`relayProtocol:${t.relayProtocol}`:""}`),this._localAddress=`${t.ip||t.address}:${t.port}`),r&&(this._log.info(`remote candidate: ${r.candidateType} ${r.protocol}:${r.ip||r.address}:${r.port}`),this._remoteAddress=`${r.protocol}:${r.ip||r.address}`);break}})}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise?this._waitForPeerConnectionConnectedPromise:(this._waitForPeerConnectionConnectedPromise=new Promise((i,e)=>{if(this._currentState==="CONNECTED")return i();this._waitForPeerConnectionConnectedPromiseReject=e;let t=a=>{a.state==="CONNECTED"&&(clearTimeout(n),o(),i())},r=({room:a})=>{a===this._room&&(clearTimeout(n),o(),e(new y({code:S.API_CALL_ABORTED,message:w({key:x.CONNECTION_ABORTED,data:"leave room"})})))},o=()=>{T.off(g.LEAVE_SUCCESS,r,this),this._emitter.off("connection-state-changed",t,this)},n=setTimeout(()=>{o();let a=new y({code:S.API_CALL_TIMEOUT,message:"connection timeout"});ol+=1,R_(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),nl=!0,this._emitter.emit("firewall-restriction")),e(a)},Os);T.on(g.LEAVE_SUCCESS,r,this),this._emitter.on("connection-state-changed",t,this)}),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally(()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null}),this._waitForPeerConnectionConnectedPromise)}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(pe.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=oi()){this._log.warn(`SDK has tried reconnect for ${this._reconnectionCount} times, but all failed, please check your network`),this.stopReconnection();let i=new y({code:this._isUplink?S.UPLINK_RECONNECTION_FAILED:S.DOWNLINK_RECONNECTION_FAILED,message:w({key:this._isUplink?x.UPLINK_RECONNECTION_FAILED:x.DOWNLINK_RECONNECTION_FAILED})});return this.emitConnectionStateChangedEvent("DISCONNECTED"),this._emitter.emit("error",i),-1}return this._signalChannel.isConnected?(this._reconnectionCount+=1,this._log.warn(`reconnect() trying [${this._reconnectionCount}]`),1):(this._log.warn("reconnect() signal channel is not connected, suspend reconnection until signal is connected"),this._signalChannel.once(pe.CONNECTED,this.reconnect,this),-1)}on(i,e,t){this._emitter.on(i,e,t)}off(i,e,t){this._emitter.off(i,e,t)}getIsReconnecting(){return this._isReconnecting}get isH264(){var i,e;return!!((e=(i=this._peerConnection)==null?void 0:i.remoteDescription)!=null&&e.sdp.includes("H264"))}setOffer(i){var e;return(e=this._peerConnection)==null?void 0:e.setLocalDescription(i)}setAnswer(i){var e;return(e=this._peerConnection)==null?void 0:e.setRemoteDescription(i)}};b([Qe(521712,!1)],He.prototype,"setOffer",1),b([Qe(521713,!1)],He.prototype,"setAnswer",1);var ul=Se(ll());var le=function(s){return ul.default.parse(s)},mt=function(s){return ul.default.write(s)},Wh=function(s){let i=le(s);return i.media.forEach(e=>{e.type===m.AUDIO&&e.fmtp.forEach(t=>{t.config+=";sprop-stereo=1;stereo=1"})}),mt(i)};function Jh(s){let i=le(s);return i.media.forEach(e=>{var t,r;if(e.type===m.VIDEO){let o=new Set;e.rtp.forEach(({payload:a,codec:c})=>c==="H264"&&o.add(a)),e.fmtp.forEach(({payload:a,config:c})=>{let d=c.match(/apt=(\d+)/);d&&d[1]&&o.has(Number(d[1]))&&o.add(a)});let n=({payload:a})=>!o.has(a);e.rtp=e.rtp.filter(n),e.rtcpFb=(t=e.rtcpFb)==null?void 0:t.filter(n),e.fmtp=e.fmtp.filter(n),e.payloads=(r=e.payloads)==null?void 0:r.split(" ").filter(a=>!o.has(Number(a))).join(" ")}}),mt(i)}function ba(s){return Object.keys(s).filter(i=>s[i])}var ml=class extends He{constructor(e){super(L(v({},e),{isUplink:!1}));l(this,"_flag",0);l(this,"isRobot",!1);l(this,"role","anchor");l(this,"remoteAudioTrack");l(this,"remoteVideoTrack");l(this,"remoteAuxiliaryTrack");l(this,"ssrc",{audio:0,video:0,auxiliary:0});l(this,"_isSDPExchanging",!1);this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=e.remoteAudioTrack||new yi(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new ei(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new ss(this._room,this)}get videoCodec(){var t,r;let e=(r=(t=this._peerConnection)==null?void 0:t.remoteDescription)==null?void 0:r.sdp;return e?e.includes("H264")?"h264":"vp8":"h264"}get subscribeState(){let e={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(this.remoteVideoTrack.mediaType&8?e.smallVideo=!0:e.video=!0),this.remoteAudioTrack.isSubscribed&&(e.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(e.auxiliary=!0),e}get muteState(){return 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===m.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var o,n;let t=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&t!==e&&((o=this.remoteVideoTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),r}onTrack(e){let t=e.streams[0],{track:r}=e,o=t.id===Ds?m.MAIN:m.AUXILIARY;this._log.debug(`ontrack ${o} ${r.kind}`);let n=m.AUDIO;r.kind===m.VIDEO&&(n=o===m.MAIN?m.VIDEO:m.AUXILIARY);let a=this.remoteAudioTrack;n===m.VIDEO?a=this.remoteVideoTrack:n===m.AUXILIARY&&(a=this.remoteAuxiliaryTrack),a.setInputMediaStreamTrack(r)}addRRTRLine(e){let t=e.split(`\r
55
55
  `),r=new Map;t.forEach((n,a)=>{/^a=rtcp-fb:/.test(n)&&t[a+1]&&!/^a=rtcp-fb:/.test(t[a+1])&&r.set(a+1,`${n.match(/^a=rtcp-fb:\d+/)[0]} rrtr`)});let o=[...r];for(let n=0;n<o.length;n++){let[a,c]=o[n];t.splice(a+n,0,c)}return t.join(`\r
56
56
  `)}addSPSDescription(e){let t=le(e);return t.media.forEach(r=>{r.type===m.VIDEO&&r.fmtp.forEach(o=>{o.config+=";sps-pps-idr-in-keyframe=1"})}),mt(t)}removeSDESDescription(e){let t=["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"],r=le(e);return r.media.forEach(o=>{!o.ext||(o.ext=o.ext.filter(n=>!t.includes(n.uri)))}),mt(r)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return f(this,null,function*(){var r,o;try{if((((r=this._peerConnection)==null?void 0:r.connectionState)===ne.NEW||((o=this._peerConnection)==null?void 0:o.connectionState)===ne.CONNECTING)&&(yield this.waitForPeerConnectionConnected()),this.isSubscriptionStateNotChanged(e)){this._peerConnection||(this.initialize(),yield this.connect(e));return}if(this._log.info(`subscribe ${t} ${JSON.stringify(e)}`),this._peerConnection||this._isSDPExchanging){let n="subscribe_change";Object.values(e).find(a=>a===!0)||(n="unsubscribe"),yield this.sendSubscription(n,e)}else this.initialize(),yield this.connect(e)}catch(n){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${n.message} ${JSON.stringify(this.muteState)}`),new y({code:S.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):n}})}unsubscribe(r){return f(this,arguments,function*({remoteTracks:e,streamType:t}){if(this._currentState==="CONNECTED"&&(t==="main"&&!this.isMainStreamSubscribed||t==="auxiliary"&&!this.isAuxStreamSubscribed)){this._log.info(`${t} stream already unsubscribed`);return}let o=v({},this.subscribeState);e.forEach(a=>{switch(a.mediaType){case 1:o.audio=!1;break;case 4:o.video=!1;break;case 8:o.smallVideo=!1;break;case 2:o.auxiliary=!1;break;default:break}});let n="subscribe_change";Object.values(o).find(a=>a===!0)||(n="unsubscribe"),this._log.info(`${n==="unsubscribe"?n:"subscribe"} ${t} [${ba(o)}]`),yield this.sendSubscription(n,o),n==="unsubscribe"&&(this.closePeerConnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"))})}sendSubscription(e,t=this.subscribeState){let r={srcTinyId:this.tinyId,srcUserId:this.userId},o=W.UNSUBSCRIBE,n=V.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(r={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},o=W.SUBSCRIBE_CHANGE,n=V.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:o,data:r,responseCommand:n,timeout:1e4}).then(({data:a})=>{if(a.code!==0){let c=new y({code:a.code,message:w({key:x.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(c),c}})}connect(){return f(this,arguments,function*(e=this.subscribeState){try{yield this.exchangeSDP(e),yield this.waitForPeerConnectionConnected()}catch(t){throw this.closePeerConnection(!0),t}})}exchangeSDP(e){return f(this,null,function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info("createOffer success, sending offer");let{type:t,sdp:r}=this._peerConnection.localDescription,o={type:t,sdp:r,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},n=yield this._signalChannel.sendWaitForResponse({command:W.SUBSCRIBE,commandDesc:"exchange sdp",data:o,responseCommand:V.SUBSCRIBE_RESULT,timeout:Qa});if(!this._peerConnection){let a=new y({code:S.INVALID_OPERATION,message:w({key:x.CONNECTION_CLOSED})});throw this._log.warn(a),a}yield this.onSubscribeResult(n),this._isSDPExchanging=!1}catch(t){throw this._isSDPExchanging=!1,t}})}createOffer(){return f(this,null,function*(){let e={voiceActivityDetection:!1};ct()&&this._sdpSemantics===Pi?(this._peerConnection.addTransceiver(m.AUDIO,{direction:Q.RECVONLY}),this._peerConnection.addTransceiver(m.VIDEO,{direction:Q.RECVONLY}),this._peerConnection.addTransceiver(m.VIDEO,{direction:Q.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:r}=yield Mn();r||(this._log.warn("remove h264 desc from sdp"),t.sdp=Jh(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=Wh(t.sdp),this._sdpSemantics===Pi&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this.setOffer(t)})}onSubscribeResult(e){return f(this,null,function*(){let{code:t,message:r=""}=e&&e.data||{},{type:o,sdp:n}=e&&e.data&&e.data.data||{};if(t===Zi)throw new y({code:S.NOT_SUPPORTED_H264,message:w({key:x.NOT_SUPPORTED_H264DECODE})});try{if(t!==0)throw new y({code:t,message:w({key:x.EXCHANGE_SDP_FAILED,data:{errMsg:r}})});this._log.debug(`accept remote answer: ${n}`),yield this.setAnswer({type:o,sdp:n}),this.updateSSRC(n)}catch(a){throw this._log.error(a),a}})}updateSSRC(e){try{le(e).media.forEach(r=>{if(!!r.ssrcs)if(r.type===m.AUDIO){let o=r.ssrcs.find(n=>{var a;return(a=n.value)==null?void 0:a.includes(Ds)});o&&(this.ssrc.audio=Number(o.id))}else{let o=r.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(Ds)}),n=r.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(Wa)});o&&(this.ssrc.video=Number(o.id)),n&&(this.ssrc.auxiliary=Number(n.id))}})}catch(t){}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return f(this,null,function*(){if(!(ye(ml.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch(t){let r=Ft(this._reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${r/1e3}s`),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},r)}})}getIsReconnecting(){return this._isReconnecting}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}getCurrentState(){return this._currentState}setDelay({audioDelay:e,videoDelay:t}){this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=t}get audioReceiver(){var e;return((e=this._peerConnection)==null?void 0:e.getReceivers()[0])||null}},fs=ml;b([G(s=>function(...i){return new Promise((e,t)=>{let r=o=>{this._emitter.off("closed",r),t(new y({code:S.API_CALL_ABORTED,message:w({key:x.CONNECTION_ABORTED,data:o})}))};this._emitter.on("closed",r),s.apply(this,i).then(e,t).finally(()=>{this._emitter.off("closed",r)})})})],fs.prototype,"subscribe",1),b([Qe(521717,!1)],fs.prototype,"unsubscribe",1),b([bt(He.prototype.afterConnect),Wn(He.prototype.beforeConnect)],fs.prototype,"connect",1);var hl=fs;var qh={voiceActivityDetection:!1},pl=class extends He{constructor(e){super(L(v({},e),{isUplink:!0}));l(this,"localMainAudioTrack",null);l(this,"localMainVideoTrack",null);l(this,"localAuxAudioTrack",null);l(this,"localAuxVideoTrack",null);l(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0});l(this,"_isPublishingAux",!1);l(this,"_publishingLocalAudioTrack");l(this,"_publishingLocalVideoTrack");l(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});l(this,"flag",0)}get videoCodec(){return this._mediaSettings.videoCodec.toLowerCase()||"h264"}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}get publishState(){var t,r,o,n;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(Ht()?(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===m.AUDIO?e.audio=!0:(e.bigVideo=!0,this._room.videoManager.hasSmall&&(e.smallVideo=!0)))}))}return e}initialize(){super.initialize(),this.installEvents()}reset(){this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this.uninstallEvents()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this._emitter.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this._emitter.on("connection-state-changed",this.handleConnectionStateChange,this)}uninstallEvents(){this._emitter.off("connection-state-changed",this.handleConnectionStateChange,this)}emitConnectionStateChangedEvent(e,t){var n,a,c;let r=this._currentState,o=super.emitConnectionStateChangedEvent(e);return o&&r!==e&&(t?t.emit("connection-state-changed",{prevState:r,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:r,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:r,state:e}),(c=this._publishingLocalVideoTrack)==null||c.emit("connection-state-changed",{prevState:r,state:e}))),o}publish(o){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:r}){this._peerConnection||this.initialize(),e&&(this._publishingLocalAudioTrack=e),t&&(this._publishingLocalVideoTrack=t),this._isPublishingAux=r;let n;t&&!r&&t.small&&(n=this._room.videoManager.smallTrack),this.sendMediaSettings(),ct()?yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:n,isAuxiliary:r}):yield this.publishByAddTrack({localAudioTrack:e,localVideoTrack:t,smallTrack:n}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,r?(t&&(this.localAuxVideoTrack=t),e&&(this.localAuxAudioTrack=e)):(t&&(this.localMainVideoTrack=t),e&&(this.localMainAudioTrack=e)),this.installTrackMuteEvents(e,t),this.sendMutedFlag()})}publishByTransceiver(n){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:r,isAuxiliary:o}){this._log.info("publish by transceiver");let a=new MediaStream,c=t==null?void 0:t.outMediaTrack,d=e==null?void 0:e.outMediaTrack;d&&a.addTrack(d),c&&a.addTrack(c);let h=this._peerConnection.getTransceivers();if(h.length===0)this._peerConnection.addTransceiver(d||m.AUDIO,{direction:Q.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(o?m.VIDEO:c||m.VIDEO,{direction:Q.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(r||m.VIDEO,{direction:Q.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(o?c||m.VIDEO:m.VIDEO,{direction:Q.SENDONLY,streams:[a]}),yield this.connect();else{let u=[];if(d&&(h[0].sender.track||u.push(0),yield h[0].sender.replaceTrack(d),yield this.setBandwidth({bandwidth:(e==null?void 0:e.profile.bitrate)||40,type:m.AUDIO})),c){let p=o?3:1;yield h[p].sender.replaceTrack(c),yield this.setBandwidth({bandwidth:t.profile.bitrate,type:m.VIDEO,videoType:o?m.AUXILIARY:m.BIG}),u.push(p),r&&(yield h[2].sender.replaceTrack(r),yield this.setBandwidth({bandwidth:t.small.bitrate,type:m.VIDEO,videoType:m.SMALL}),u.push(2))}yield this.setTransceiverDirection(Q.SENDONLY,u),yield this.doPublishChange(),t==null||t.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),t==null||t.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"})}})}publishByAddTrack(o){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:r}){this._log.info("publish by addtrack");let n=t==null?void 0:t.outMediaTrack,a=e==null?void 0:e.outMediaTrack;if(this._peerConnection&&this._peerConnection.connectionState!=="new"){e&&a&&(yield this.addTrack(e)),n&&(yield this.addTrack(t));return}let c=new MediaStream;if(a&&c.addTrack(a),n&&c.addTrack(n),a&&this._peerConnection.addTrack(a,c),n&&(this._peerConnection.addTrack(n,c),r)){let d=new MediaStream;d.addTrack(r),this._peerConnection.addTrack(r,d)}yield this.connect()})}enableSmall(e){return f(this,null,function*(){let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.setTransceiverDirection(Q.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(Q.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()})}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(r){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){if(!Ht()){if(e&&e.outMediaTrack&&!t&&this.localMainVideoTrack){yield this.removeTrack(e),this.localMainAudioTrack=null;return}if(t&&t.outMediaTrack&&!e&&this.localMainAudioTrack){yield this.removeTrack(t),this.localMainVideoTrack=null;return}yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),this.emitConnectionStateChangedEvent("DISCONNECTED",t);return}let o=t&&t===this.localAuxVideoTrack,n=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),c=[];e&&(o?this.localAuxAudioTrack=null:this.localMainAudioTrack=null,!this.localAuxAudioTrack&&!this.localMainAudioTrack&&(yield a[0].replaceTrack(null),c.push(0))),n&&(o?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=L(v({},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(v({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),c.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.setTransceiverDirection(Q.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.publishState,constraintConfig:this._mediaSettings},r=yield this._signalChannel.sendWaitForResponse({command:W.PUBLISH_STATE_CHANGE,data:t,responseCommand:V.PUBLISH_STATE_CHANGE_RESULT,enableLog:e});this.checkPublishResultCode(r.data.code,r.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:W.UNPUBLISH,commandDesc:"unpublish",responseCommand:V.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===S.API_CALL_TIMEOUT)return Promise.resolve();throw t})}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let r=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:o,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:o=this._publishingLocalVideoTrack),Gt){if(r&&r.outMediaTrack){let a=r.outMediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=r.profile.bitrate*1e3,this._mediaSettings.audioFs=a.sampleRate||0}if(o&&o.outMediaTrack){let a=o.outMediaTrack.getSettings();this._mediaSettings.videoWidth=a.width||0,this._mediaSettings.videoHeight=a.height||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=o.profile.bitrate*1e3,o.small&&(this._mediaSettings.smallVideoWidth=o.small.width,this._mediaSettings.smallVideoHeight=o.small.height,this._mediaSettings.smallVideoFps=o.small.frameRate,this._mediaSettings.smallVideoBps=o.small.bitrate*1e3)}if(n&&n.outMediaTrack){let a=n.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=a.width||0,this._mediaSettings.auxVideoHeight=a.height||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=n.profile.bitrate*1e3}}else r&&r.outMediaTrack&&(this._mediaSettings.audioChannel=r.profile.channelCount,this._mediaSettings.audioBps=r.profile.bitrate*1e3,this._mediaSettings.audioFs=r.profile.sampleRate),o&&o.outMediaTrack&&(this._mediaSettings.videoWidth=o.profile.width,this._mediaSettings.videoHeight=o.profile.height,this._mediaSettings.videoFps=o.profile.frameRate,this._mediaSettings.videoBps=o.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:W.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:V.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?m.AUXILIARY:m.MAIN} stream`),ct()?yield this.addTrackByTransceiver(e,t):yield this.addTrackBySender(e)})}addTrackByTransceiver(e,t){return f(this,null,function*(){var o;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===m.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?void 0:o.small)&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===Q.INACTIVE&&(yield this.setTransceiverDirection(Q.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}addTrackBySender(e){return f(this,null,function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;Ht()&&this._peerConnection.getTransceivers().findIndex(o=>o.direction==="stopped")>=0&&(this._log.warn("transceiver is stopping, negotiate sdp first"),yield this.updateOffer("remove",t));let r=this._peerConnection.getSenders().find(o=>o.track&&o.track.kind===t.kind);if(r&&r.track){this._log.warn("sender already exists, remove sender first");let o=r.track;this.removeSender(r),yield this.updateOffer("remove",o)}if(t&&this._peerConnection.addTrack(t,new MediaStream([t])),t.kind===m.VIDEO&&e instanceof me&&e.small){let o=new MediaStream,{smallTrack:n}=this._room.videoManager;o.addTrack(n),this._peerConnection.addTrack(n,o)}yield this.updateOffer("add",t)})}isNeedToResetOfferOrder(){if(this._sdpSemantics===yr||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=le(e);for(let r=0;r<t.media.length;r++)if(Number(t.media[r].mid)===0&&t.media[r].type===m.VIDEO)return!0;return!1}removeSender(e){let t=null;Ht()&&(t=this._peerConnection.getTransceivers().find(r=>r.sender&&r.sender.track===e.track)),this._peerConnection.removeTrack(e),t&&te(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return f(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${t?m.AUXILIARY:m.MAIN} stream`),ct()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)})}removeTrackByTransceiver(e,t){return f(this,null,function*(){if(!e.outMediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===m.AUDIO)yield r[0].sender.replaceTrack(null);else{let o=t?3:1;yield r[o].sender.replaceTrack(null),o===1&&e.small&&(yield r[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(Q.INACTIVE,[o])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,t){return f(this,null,function*(){if(!re)return;let r=!1,o=!1;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let n=this._peerConnection.getTransceivers();if(t.forEach(d=>{n[d].direction!==e&&(n[d].direction=e,r=!0)}),r){this._log.info("updating offer");let d=yield this._peerConnection.createOffer();yield this.setOffer(d)}let a=-1,c=this._peerConnection.remoteDescription.sdp.split(`\r
57
57
  `).map(d=>{if(d.match(new RegExp(`a=(${Q.INACTIVE}|${Q.RECVONLY}|${Q.SENDONLY})`))&&a++,t.includes(a)){if(e===Q.INACTIVE&&d.includes(`a=${Q.RECVONLY}`))return o=!0,`a=${e}`;if(e===Q.SENDONLY&&d.includes(`a=${Q.INACTIVE}`))return o=!0,`a=${Q.RECVONLY}`}return d}).join(`\r
@@ -84,4 +84,4 @@ ${e.map(d=>d.toString()).join(`
84
84
  `)};(${t})();${r}})()`,n=new Blob([o],{type:"text/javascript"}),a=URL.createObjectURL(n),c=new Worker(a);return URL.revokeObjectURL(a),c}var ii=(c=>(c.TRACK="track",c.DATA_CHANNEL_MESSAGE="data_channel_msg",c[c.CONNECTION_STATE_CHANGED="connection-state-changed"]="CONNECTION_STATE_CHANGED",c[c.FIREWALL_RESTRICTION="firewall-restriction"]="FIREWALL_RESTRICTION",c.RECONNECTED="spc-reconnected",c.RECONNECT_FAILED="spc-reconnect-failed",c.ERROR="error",c.SEI_MESSAGE="sei-message",c))(ii||{}),fm=0,_m=!1,X_=new Set,Q_=s=>fm>2&&!_m&&X_.size===0&&s,z_=1,Ot=class extends pm.default{constructor({signalChannel:e,room:t,enableCustomMessage:r}){super();l(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0});l(this,"currentState","DISCONNECTED");l(this,"_room");l(this,"_signalChannel");l(this,"_peerConnection",null);l(this,"_datachannel",null);l(this,"_enableCustomMessage");l(this,"_log");l(this,"_downlinkMIDMap",new Map);l(this,"_downlinkMIDUserIDMap",new Map);l(this,"_reconnectionTimer",-1);l(this,"reconnectionCount",0);l(this,"clientAbility");l(this,"_serverAbility",null);l(this,"addDownlinkQueue",new Set);l(this,"removeDownlinkQueue",new Set);l(this,"_parsedAnswer",null);l(this,"_updateSDPPromise",null);l(this,"_waitForPCConnectedPromise");l(this,"clearConnectTimeout");l(this,"_isSDPLogged",!1);l(this,"enableInsertableStreams",!1);l(this,"insertableStreamsAbortMap",new Map);l(this,"scriptTransformWorker");l(this,"_isRelayTried",!1);l(this,"_rttOverCount",0);this._room=t,this._enableCustomMessage=r,this._signalChannel=e,this._log=R.createLogger({id:`spc${z_++}`,userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableCodecPipeline&&(Ti?this.enableInsertableStreams=!0:this.initScriptTransformWorker()),this._room.healthDetector.on("1",this.onBadHealth,this)}get isH264EncodeSupported(){let e=this._room.checkSystemResult.detail.isH264EncodeSupported;return this._serverAbility&&(e=e&&!!this._serverAbility.video.codecs.find(t=>t.codec.toLowerCase()==="h264")),e}addAbortController(e,t){var r;(r=this.insertableStreamsAbortMap.get(e))==null||r.abort("destory"),this.insertableStreamsAbortMap.set(e,t)}get isVP8EncodeSupported(){let e=this._room.checkSystemResult.detail.isVp8EncodeSupported;return this._serverAbility&&(e=e&&this._serverAbility.video.codecs.find(t=>t.codec.toLowerCase()==="vp8")),e}get videoCodec(){var t,r;let e=(t=this._parsedAnswer)==null?void 0:t.media[1].rtp.find(o=>["h264","vp8"].includes(o.codec.toLowerCase()));return e?e.codec.toLowerCase():(r=this._serverAbility)!=null&&r.useVp8?"vp8":"h264"}get downlinkVideoCodec(){var e;return(e=this._serverAbility)!=null&&e.video.decoders.find(t=>t.codec.toLowerCase()==="h264")?"h264":"vp8"}get isUsingH264(){return this.videoCodec==="h264"}get is42001fSupported(){return this.clientAbility?!!this.clientAbility.video.codecs.find(e=>e.fmtp.includes("42001f")):!1}get uplinkSSRC(){return this._peerConnection&&this._peerConnection.localDescription?rm(this._peerConnection.localDescription.sdp):{audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0}}onBadHealth({isAux:e}){this.useHWEncoder(!1,e?7:2)}initScriptTransformWorker(){Pn&&(this.scriptTransformWorker=hm({videoEncodePipeline:this._room.videoManager.encodePipeline,videoDecodePipeline:this._room.videoManager.decodePipeline,audioEncodePipeline:this._room.audioManager.encodePipeline,audioDecodePipeline:this._room.audioManager.decodePipeline}),this.scriptTransformWorker.onmessage=e=>{e.data.type==="sei"&&this.emit("sei-message",e.data)},this.scriptTransformWorker.onerror=e=>{this._log.error("scriptTransformWorker error: ",e)})}get isReconnecting(){return this.currentState==="RECONNECTING"||this._reconnectionTimer>0||this.reconnectionCount>0}get dtlsTransport(){if(!this._peerConnection)return null;let e=this._peerConnection.getSenders();return e.length===0?null:e[0].transport}initialize(){return f(this,null,function*(){var t;let e;try{return this._peerConnection=new RTCPeerConnection({encodedInsertableStreams:this.enableInsertableStreams,offerExtmapAllowMixed:!0,iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._room.sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"}),this._peerConnection.oniceconnectionstatechange=()=>{if(!this._peerConnection)return;let r=this._peerConnection.iceConnectionState;this._log.debug(`ice state: ${r}`),r==="checking"&&this.stat.iceStartTime===0?this.stat.iceStartTime=Date.now():r==="connected"&&this.stat.iceEndTime===0?(this.stat.iceEndTime=Date.now(),N.addSuccessEvent({key:521711,cost:this.stat.iceEndTime-this.stat.iceStartTime})):r==="failed"&&N.addFailedEvent({key:521711})},this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this._peerConnection.ontrack=r=>this.emit("track",r),this._enableCustomMessage&&(this._datachannel=this._peerConnection.createDataChannel(`${this._room.userId}dc`),this._datachannel.binaryType="arraybuffer",this._datachannel.onopen=()=>{this._log.info("datachannel open")},this._datachannel.onclose=()=>{this._log.warn("datachannel close")},this._datachannel.onmessage=r=>{let o=new Rl(r.data);this.emit("data_channel_msg",{data:o})},this._datachannel.onerror=r=>{this._log.warn("datachannel error",r)}),this._peerConnection.addTransceiver(m.AUDIO,{direction:m.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(m.VIDEO,{direction:m.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(m.VIDEO,{direction:m.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(m.VIDEO,{direction:m.TRANSCEIVER_DIRECTION_SENDONLY}),e=yield this._peerConnection.createOffer(),this.clientAbility=yield om(e.sdp,((t=this._room.scheduleResult.config)==null?void 0:t.remove264FromSDP)||!1),yield this.setOffer(e),this.dtlsTransport&&(this.dtlsTransport.onstatechange=()=>{let{dtlsTransport:r}=this;!r||(this._log.debug(`dtls state: ${r.state}`),r.state==="connecting"&&this.stat.dtlsStartTime===0?this.stat.dtlsStartTime=Date.now():r.state==="connected"&&this.stat.dtlsEndTime===0&&(this.stat.dtlsEndTime=Date.now()))}),N.addSuccessEvent({key:521707}),this.clientAbility}catch(r){throw N.addFailedEvent({key:521707,error:r}),this._log.error(`initialize failed ${r}
85
85
  offer: ${e==null?void 0:e.sdp}`),r}})}setPriority(e="high"){if(!!this._peerConnection)try{this._peerConnection.getSenders().forEach(r=>{let o=r.getParameters();o.encodings[0]&&(o.encodings[0].priority=e,o.encodings[0].networkPriority=e,r.setParameters(o).catch(n=>{this._log.warn("setPriority error ",n)}))})}catch(t){this._log.warn("setPriority error ",t)}}connect(e,t=!1){return f(this,null,function*(){var r,o;try{if(this.currentState==="CONNECTED")return;let n=k(),a={type:"answer",sdp:nm({serverAbility:e,clientAbility:this.clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(a),yield this.waitForPeerConnectionConnected();let c=((r=this._room.scheduleResult.config)==null?void 0:r.priority)||((o=this._room.joinParams)==null?void 0:o.priority)||new URLSearchParams(location.search).get("priority");c&&this.setPriority(c),t||N.addSuccessEvent({key:521703,cost:k()-n})}catch(n){let a=n instanceof y&&n.code===S.API_CALL_ABORTED;throw a||this._log.error(`connect failed: ${n}`,e),this.reset(),!a&&!this.isReconnecting&&(N.addFailedEvent({key:521703,error:n}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),n}})}reconnect(){return f(this,null,function*(){if(this._reconnectionTimer!==-1){this._log.warn("reconnect() is reconnecting, ignore current reconnection");return}if(!this._signalChannel.isConnected){this._log.warn("reconnect() wait signal channel is connected"),this._signalChannel.once(pe.CONNECTED,this.reconnect,this);return}try{this.reconnectionCount++,this._log.warn(`reconnect() trying [${this.reconnectionCount}]`),this.reset();let e=yield this.initialize(),t=yield this._signalChannel.sendWaitForResponse({command:W.REBUILD_PEER_CONNECTION,responseCommand:V.REBUILD_PEER_CONNECTION_RES,data:{ability:e},enableLog:!1});if(t.data.code!==0)throw new y({code:t.data.code,message:t.data.message});yield this.connect(t.data.data.ability,!0),N.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),T.emit(g.SPC_RECONNECTED,{room:this._room}),this.emit("spc-reconnected")}catch(e){if(!this.isReconnecting)return;if(e!=null&&e.message.includes("timeout")){let t=Ft(this.reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${t/1e3}s`),yield $i(t,r=>{this._reconnectionTimer=r}),this.clearReconnectionTimer(),yield this.reconnect()}else this._log.error(`reconnect() failed ${e==null?void 0:e.code} ${e}`),N.addFailedEvent({key:521704,error:e}),this.reconnectionCount>=oi()&&this._log.warn(`SDK has tried reconnect for ${oi()} times, but all failed, please check your network`),this.stopReconnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.emit("error")}})}getPeerConnection(){return this._peerConnection}startReconnection(){return f(this,null,function*(){this.isReconnecting||(this._log.warn("start reconnect"),this._updateSDPPromise=null,this.emitConnectionStateChangedEvent("RECONNECTING"),yield this.reconnect())})}stopReconnection(){var e;this.isReconnecting&&(this._log.info("stop reconnect"),this.reconnectionCount=0,this.clearReconnectionTimer(),(e=this.clearConnectTimeout)==null||e.call(this),this._signalChannel.off(pe.CONNECTED,this.reconnect,this),this.currentState==="RECONNECTING"&&this.emitConnectionStateChangedEvent("DISCONNECTED"))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&((e=this._peerConnection)==null?void 0:e.connectionState)===ne.CLOSED&&this.startReconnection()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}onConnectionStateChange(e){let t=this._peerConnection.iceConnectionState,r=this.getDTLSTransportState();this._log.info(`connectionState: ${e.target.connectionState} ICE: ${t} DTLS: ${r}`),e.target.connectionState===ne.CONNECTING&&(this.stat.peerConnectionStartTime===0&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(e.target.connectionState===ne.FAILED||e.target.connectionState===ne.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this._room.forceRelay?this.switchRelay(!1):this.startReconnection()),(e.target.connectionState===ne.CONNECTED||e.target.connectionState===ne.COMPLETED)&&(this.stat.peerConnectionEndTime===0&&(this.stat.peerConnectionEndTime=Date.now()),T.emit(g.SINGLE_CONNECTION_STAT,{room:this._room,stat:{ice:this.stat.iceEndTime-this.stat.iceStartTime,dtls:this.stat.dtlsEndTime-this.stat.dtlsStartTime,peerConnection:this.stat.peerConnectionEndTime-this.stat.peerConnectionStartTime}}),this.logSelectedCandidate(),this.emitConnectionStateChangedEvent("CONNECTED"))}getDTLSTransportState(){if(!this._peerConnection)return ft;let e=null;return!Hi()||this._peerConnection.getSenders().length===0?ft:(e=this._peerConnection.getSenders()[0].transport,!ar()||this._peerConnection.getReceivers().length===0?ft:e?e.state:ft)}emitConnectionStateChangedEvent(e){e!==this.currentState&&(this.currentState==="RECONNECTING"&&e==="CONNECTING"||(this.emit(ii.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:e}),this.currentState=e))}logSelectedCandidate(){return f(this,null,function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[t,r]of e)if(Fi(r)){let o=e.get(r.localCandidateId),n=e.get(r.remoteCandidateId);o&&(this._log.info(`local candidate: ${o.candidateType} ${o.protocol}:${o.ip||o.address}:${o.port} ${o.networkType||""} ${o.candidateType==="relay"?`relayProtocol:${o.relayProtocol}`:""}`),o.networkType&&Ec(o.networkType)),n&&this._log.info(`remote candidate: ${n.candidateType} ${n.protocol}:${n.ip||n.address}:${n.port}`);break}})}waitForPeerConnectionConnected(){return this._waitForPCConnectedPromise?this._waitForPCConnectedPromise:(this._waitForPCConnectedPromise=new Promise((e,t)=>{if(this.currentState==="CONNECTED")return e();let r=c=>{c.state==="CONNECTED"&&(clearTimeout(a),n(),e())},o=({room:c})=>{c===this._room&&(clearTimeout(a),n(),t(new y({code:S.API_CALL_ABORTED,message:w({key:x.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{T.off(g.LEAVE_SUCCESS,o,this),this.off(ii.CONNECTION_STATE_CHANGED,r,this)},a=setTimeout(()=>{n();let c=new y({code:S.API_CALL_TIMEOUT,message:"connection timeout"});fm+=1,Q_(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),_m=!0,this.emit(ii.FIREWALL_RESTRICTION)),t(c)},Os);this.clearConnectTimeout=()=>{n(),clearTimeout(a),delete this.clearConnectTimeout},T.on(g.LEAVE_SUCCESS,o,this),this.on(ii.CONNECTION_STATE_CHANGED,r,this)}),this._waitForPCConnectedPromise=this._waitForPCConnectedPromise.finally(()=>{this._waitForPCConnectedPromise=null,delete this.clearConnectTimeout}),this._waitForPCConnectedPromise)}waitForReconnected(){return this.isReconnecting?new Promise((e,t)=>{this.once("spc-reconnected",e),this.once("error",t)}):Promise.resolve()}addDownlink(e){return f(this,null,function*(){if(this._log.info(`addDownlink(${e.userId}) trying`),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise),this.updateLocalAndRemoteSDPConfig(e),this.addDownlinkQueue.size===0)try{yield this.updateSDP(),this._log.info(`addDownlink(${e.userId}) done`)}catch(t){this._log.error(`addDownlink(${e.userId}) failed ${t}`),yield this.startReconnection()}})}updateLocalAndRemoteSDPConfig({ssrc:e,userId:t,tinyId:r}){if(!this._peerConnection)return;this._log.info(`updateLocalAndRemoteSDPConfig ${t} ${JSON.stringify(e)}`);let o=this._peerConnection.getTransceivers().slice(4).filter(p=>p.direction==="inactive").slice(0,3).map(p=>(p.direction=m.TRANSCEIVER_DIRECTION_RECVONLY,Number(p.mid)));this._parsedAnswer||(this._parsedAnswer=le(this._peerConnection.remoteDescription.sdp));let n=this._parsedAnswer.media.filter(p=>{var _;return(_=p.ssrcs)==null?void 0:_.find(I=>{var C;return(C=I.value)==null?void 0:C.includes(r)})}),a,c,d;if(n.length===3)a=n[0],c=n[1],d=n[2];else if(o.length===3)a=this._parsedAnswer.media.find(p=>Number(p.mid)===Number(o[0])),c=this._parsedAnswer.media.find(p=>Number(p.mid)===Number(o[1])),d=this._parsedAnswer.media.find(p=>Number(p.mid)===Number(o[2]));else if(o.length===0){this._peerConnection.addTransceiver(m.AUDIO,{direction:m.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(m.VIDEO,{direction:m.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(m.VIDEO,{direction:m.TRANSCEIVER_DIRECTION_RECVONLY}),a=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let p=Al({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:le(this._peerConnection.localDescription.sdp),isDownlink:!0});c=JSON.parse(JSON.stringify(p)),d=JSON.parse(JSON.stringify(p)),a.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(a),c.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(c),d.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(d)}a.direction=m.TRANSCEIVER_DIRECTION_SENDONLY;let h=`${r}-${e.audio}`;a.ssrcs=[{id:e.audio,attribute:"cname",value:`${h}`},{id:e.audio,attribute:"msid",value:`${h}-${m.MAIN} ${h}-audio`}],c.direction=m.TRANSCEIVER_DIRECTION_SENDONLY,c.ssrcs=[{id:e.video,attribute:"cname",value:`${h}`},{id:e.video,attribute:"msid",value:`${h}-${m.MAIN} ${h}-bigvideo`},{id:e.videoRtx,attribute:"cname",value:`${h}`},{id:e.videoRtx,attribute:"msid",value:`${h}-${m.MAIN} ${h}-bigvideo`}],c.ssrcGroups=[{semantics:"FID",ssrcs:`${e.video} ${e.videoRtx}`}],d.direction=m.TRANSCEIVER_DIRECTION_SENDONLY;let u=`${h}-aux`;d.ssrcs=[{id:e.auxiliary,attribute:"cname",value:u},{id:e.auxiliary,attribute:"msid",value:`${u} ${h}-aux${m.VIDEO}`},{id:e.auxiliaryRtx,attribute:"cname",value:`${u} ${h}-aux${m.VIDEO}`},{id:e.auxiliaryRtx,attribute:"msid",value:`${u} ${h}-aux${m.VIDEO}`}],d.ssrcGroups=[{semantics:"FID",ssrcs:`${e.auxiliary} ${e.auxiliaryRtx}`}],this._parsedAnswer.groups&&(this._parsedAnswer.groups[0].mids=this._parsedAnswer.media.map(p=>p.mid).join(" ")),this._downlinkMIDMap.set(t,[a.mid,c.mid,d.mid]),this._downlinkMIDUserIDMap.set(a.mid,t),this._downlinkMIDUserIDMap.set(c.mid,t),this._downlinkMIDUserIDMap.set(d.mid,t)}removeDownlink(e){return f(this,null,function*(){if(!this._downlinkMIDMap.has(e)||!this._peerConnection)return;this._log.info(`removeDownlink(${e}) trying`),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise);let t=this._downlinkMIDMap.get(e),r=!1;this._peerConnection.getTransceivers().forEach(o=>{t!=null&&t.includes(Number(o.mid))&&(r=!0,o.direction="inactive")}),this._parsedAnswer||(this._parsedAnswer=le(this._peerConnection.remoteDescription.sdp)),this._parsedAnswer.media.forEach(o=>{t!=null&&t.includes(Number(o.mid))&&(r=!0,o.direction="inactive",o.ssrcs=[],o.ssrcGroups=[])}),this.removeDownlinkQueue.size===0&&r&&(yield this.updateSDP()),this._downlinkMIDMap.delete(e),t==null||t.forEach(o=>this._downlinkMIDUserIDMap.delete(o)),this._log.info(`removeDownlink(${e}) done`)})}setBandwidth(e){return f(this,null,function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:r,smallVideo:o,auxVideo:n}=e;try{if(ro()){let a=this._peerConnection.getSenders().slice(0,4);for(let d=0;d<a.length;d++){let h=a[d],u;d===0&&t?u=t:d===1&&r?u=r:d===2&&o?u=o:d===3&&n&&(u=n),u&&(yield this.setSenderMaxBitrate(h,u))}let c=!1;r&&a[1].track&&(c=this.setStartBitrate(1,r)),n&&a[3].track&&(c=this.setStartBitrate(3,n)||c),c&&(yield this.updateSDP())}else yield this.setBandwidthBySDP(e);this._log.info(`setBandwidth ${JSON.stringify(e)}`)}catch(a){this._log.error(`failed to set bandwidth: ${a}`)}})}setStartBitrate(e,t){var r,o;return(r=this._peerConnection)!=null&&r.remoteDescription&&(this._parsedAnswer||(this._parsedAnswer=le(this._peerConnection.remoteDescription.sdp)),(o=this._parsedAnswer.media[e])!=null&&o.fmtp[0])?(this._parsedAnswer.media[e].fmtp[0].config+=`;x-google-start-bitrate=${t>5e3?5e3:t}`,!0):!1}setSenderMaxBitrate(e,t){let r=e.getParameters();return(!r.encodings||r.encodings.length===0)&&(r.encodings=[{}]),t==="unlimited"?delete r.encodings[0].maxBitrate:r.encodings[0].maxBitrate=t*1e3,e.setParameters(r)}setBandwidthBySDP({audio:e,bigVideo:t,smallVideo:r,auxVideo:o}){if(!this._peerConnection||!this._peerConnection.localDescription)return;let n=le(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=le(this._peerConnection.remoteDescription.sdp));let a=re?"TIAS":"AS";e&&(n.media[0].bandwidth=[{type:a,limit:re?e*1e3:e}],this._parsedAnswer.media[0].bandwidth=[{type:a,limit:re?e*1e3:e}]),t&&(n.media[1].bandwidth=[{type:a,limit:re?t*1e3:t}],this._parsedAnswer.media[1].bandwidth=[{type:a,limit:re?t*1e3:t}]),r&&(n.media[2].bandwidth=[{type:a,limit:re?r*1e3:r}],this._parsedAnswer.media[2].bandwidth=[{type:a,limit:re?r*1e3:r}]),o&&(n.media[3].bandwidth=[{type:a,limit:re?o*1e3:o}],this._parsedAnswer.media[3].bandwidth=[{type:a,limit:re?o*1e3:o}]);let c={type:"offer",sdp:mt(n)};return this.updateSDP({localDescription:c})}setScaleResolutionDownBy(e,t,r){let o=e.getParameters();(!o.encodings||o.encodings.length===0)&&(o.encodings=[{}]);let n=o.encodings[0].scaleResolutionDownBy;if(E(n)?t===1:t===n)return;let a=`setScaleResolutionDownBy ${r} ${t}`;return n&&(a+=` prevScale: ${n}`),this._log.warn(a),o.encodings[0].scaleResolutionDownBy=t,e.setParameters(o)}updateSDP({localDescription:e}={}){if(!this._parsedAnswer)return Promise.resolve();let t=mt(this._parsedAnswer);return this._updateSDPPromise=new Promise((r,o)=>f(this,null,function*(){var n,a;try{!e&&this._peerConnection&&(this._log.info("creating offer"),e=yield this._peerConnection.createOffer()),e&&(yield this.setOffer(e)),yield this.setAnswer({type:"answer",sdp:t}),this._updateSDPPromise=null,r()}catch(c){this._log.error(c),!this._isSDPLogged&&this._peerConnection&&(this._log.warn(`current offer: ${this.filterSDPDirection((n=this._peerConnection.localDescription)==null?void 0:n.sdp)}
86
86
  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)}
87
- 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:d,currentDirection:h,direction:u,stopped:p})=>({mid:d,currentDirection:h,direction:u,stopped:p})))}`),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(!re||!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===Q.INACTIVE&&n===Q.RECVONLY&&(this._parsedAnswer.media[o].direction=e),e===Q.SENDONLY&&n===Q.INACTIVE&&(this._parsedAnswer.media[o].direction=Q.RECVONLY)}yield this.updateSDP()})}filterSDPDirection(e=""){return le(e).media.map(r=>r.direction)}setOffer(e){return this._log.info("setting offer"),this._log.debug(e.sdp),this._peerConnection.setLocalDescription({type:"offer",sdp:am(e.sdp,this.clientAbility,this._serverAbility)})}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===m.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=[],Ir(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=[];E(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===m.VIDEO){let c;e&&this.is42001fSupported?c=this.clientAbility.video.codecs.find(d=>d.fmtp.includes("42001f")):e||(c=this._serverAbility.video.codecs.find(d=>d.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=[],Ir(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;(e=this._peerConnection)==null||e.close(),this._waitForPCConnectedPromise=null,this._parsedAnswer=null}close(){this._log.info("close pc"),this.removeRTCListener(),this.insertableStreamsAbortMap.forEach(e=>wt(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 h;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}=((h=this._room.scheduleResult.config)==null?void 0:h.useTurnTcpInfo)||{};if(!n||!a||!r||!o)return;let c=Math.floor(o/r),d=(this._isRelayTried||c>n)&&o>a;if(!d){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: ${d} 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`),N.addSuccessEvent({key:o,cost:Date.now()-n})}catch(n){this._log.warn(`switchRelay ${r} failed`,n),N.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.ontrack=null),this.dtlsTransport&&(this.dtlsTransport.onstatechange=null)}};b([qn("reconnect")],Ot.prototype,"startReconnection",1),b([Ai(s=>s.userId)],Ot.prototype,"addDownlink",1),b([Ai(s=>s)],Ot.prototype,"removeDownlink",1),b([Yt(!0)],Ot.prototype,"updateSDP",1),b([Qe(521712,!1)],Ot.prototype,"setOffer",1),b([Qe(521713,!1)],Ot.prototype,"setAnswer",1);var Cl=class{constructor(i){l(this,"tag");l(this,"len");l(this,"data");let e=new DataView(i);this.tag=e.getUint16(),this.len=e.getUint16(2),this.data=new Uint8Array(i).slice(4,2+2+this.len).buffer}},Rl=class{constructor(i){l(this,"tinyId");l(this,"data");let e=new DataView(i),t=0,r=[];for(;t<e.byteLength;){let o=e.getUint16(t+2),n=new Cl(new Uint8Array(i).slice(t,t+2+2+o).buffer);r.push(n),t+=2+2+o}r.forEach(o=>{o.tag===1?this.tinyId=new TextDecoder().decode(o.data):o.tag===2&&(this.data=o.data)})}},mm=new Set;function Ar(){let s=Math.floor(Math.random()*4294967296);return mm.has(s)?Ar():(mm.add(s),s)}var gm=Se(De());var Cr=class extends gm.default{constructor(e){super();l(this,"userId");l(this,"tinyId");l(this,"_sdpSemantics");l(this,"_isUplink");l(this,"_room");l(this,"_log");l(this,"_currentState","DISCONNECTED");l(this,"_prevTime",-1);this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=R.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:(T.emit(g.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 Bo=class extends Cr{constructor(e){super(L(v({},e),{isUplink:!0}));l(this,"localMainAudioTrack",null);l(this,"localMainVideoTrack",null);l(this,"localAuxAudioTrack",null);l(this,"localAuxVideoTrack",null);l(this,"_isPublishingAux",!1);l(this,"_publishingLocalAudioTrack");l(this,"_publishingLocalVideoTrack");l(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});l(this,"_flag",0);l(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]} ${hi()} ${rr()}`),N.addCount({key:521e3});else{this._checkPublishStateTimeoutId=ee.run(xi,()=>this.checkPublishState(!0),{delay:10*1e3,count:1});return}ee.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&&(Ht()?(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===m.AUDIO?e.audio=!0:(e.bigVideo=!0,this._room.videoManager.hasSmall&&(e.smallVideo=!0)))}))}return e}get serverPublishState(){return{audio:!!(this.flag&ki),bigVideo:!!(this.flag&Mi),smallVideo:!!(this.flag&vs),auxVideo:!!(this.flag&Ki)}}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,r;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"),(r=this.singlePC)==null||r.switchVideoEncoder("vp8")))}publish(o){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:r}){var d,h,u,p,_,I,C;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:S.NOT_SUPPORTED_H264,message:w({key:x.NOT_SUPPORTED_H264ENCODE})});fe&&di()===115&&t.profile.width*t.profile.height<=640*360&&(this._log.warn("fallback video to 480p"),t.setProfile(nt["480p_2"]),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:W.SPC_PUBLISH,responseCommand:V.SPC_PUBLISH_RESULT,data:L(v({},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;let{scaleResolutionDownBy:D}=t;yield this.singlePC.setScaleResolutionDownBy(this._peerConnection.getSenders()[r?3:1],D,t.streamType)}e&&(this[r?"localAuxAudioTrack":"localMainAudioTrack"]=e),yield this.singlePC.setBandwidth({audio:((d=this.localMainAudioTrack)==null?void 0:d.profile.bitrate)||((h=this.localAuxAudioTrack)==null?void 0:h.profile.bitrate),bigVideo:(u=this.localMainVideoTrack)==null?void 0:u.profile.bitrate,smallVideo:(_=(p=this.localMainVideoTrack)==null?void 0:p.small)==null?void 0:_.bitrate,auxVideo:(I=this.localAuxVideoTrack)==null?void 0:I.profile.bitrate}),this.sendMediaSettings(),this.installTrackMuteEvents(e,t),!r&&(this._room.preferHW||((C=this._room.scheduleResult.config)==null?void 0:C.preferHW))&&t&&t.profile.width*t.profile.height>=1280*720&&this.singlePC.useHWEncoder(!0,2)})}publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:r,isAuxiliary:o}){if(!ct())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(),d=[],h=[],u=(_,I,C)=>{var B,Me;let D=c[I].sender.replaceTrack(C);h.push(I),(B=this.singlePC)!=null&&B.enableInsertableStreams&&D.then(()=>this.createEncodedStreams(c[I].sender,_)),(Me=this.singlePC)!=null&&Me.scriptTransformWorker&&this.initSenderTransfrom(c[I].sender,_),d.push(D)};a&&u(e.mediaType,0,a),n&&u(t.mediaType,o?3:1,n),r&&u(8,2,r);let p=this.singlePC.setTransceiverDirection(Q.SENDONLY,h);return d.push(p),Promise.all(d)}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:(d,h)=>{var p;let u=this.getTrackByMediaType(t);h.enqueue(((p=this.singlePC)==null?void 0:p.isUsingH264)&&u?u.encodeFrame(d,t===8):d)}}),o):r.readable).pipeTo(r.writable,o).catch(d=>{this._log.debug("encoded stream error",d),d!=="destory"&&this._log.warn(d)})}initSenderTransfrom(e,t){if(!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker)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*(){if(!this.singlePC)return;let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.singlePC.setTransceiverDirection(Q.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(Q.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()})}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(r){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){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(v({},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(v({},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(Q.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.publishState,constraintConfig:this._mediaSettings},r=yield this._signalChannel.sendWaitForResponseWithRetry({command:W.PUBLISH_STATE_CHANGE,data:t,responseCommand:V.PUBLISH_STATE_CHANGE_RESULT,enableLog:e,retries:3});this.checkPublishResultCode(r.data.code,r.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:W.UNPUBLISH,commandDesc:"unpublish",responseCommand:V.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===S.API_CALL_TIMEOUT)return Promise.resolve();throw t})}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let r=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:o,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:o=this._publishingLocalVideoTrack),Gt){if(r&&r.outMediaTrack){let a=r.outMediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=r.profile.bitrate*1e3,this._mediaSettings.audioFs=a.sampleRate||0}if(o&&o.outMediaTrack){let a=o.outMediaTrack.getSettings();this._mediaSettings.videoWidth=a.width||0,this._mediaSettings.videoHeight=a.height||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=o.profile.bitrate*1e3,o.small&&(this._mediaSettings.smallVideoWidth=o.small.width,this._mediaSettings.smallVideoHeight=o.small.height,this._mediaSettings.smallVideoFps=o.small.frameRate,this._mediaSettings.smallVideoBps=o.small.bitrate*1e3)}if(n&&n.outMediaTrack){let a=n.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=a.width||0,this._mediaSettings.auxVideoHeight=a.height||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=n.profile.bitrate*1e3}}else r&&r.outMediaTrack&&(this._mediaSettings.audioChannel=r.profile.channelCount,this._mediaSettings.audioBps=r.profile.bitrate*1e3,this._mediaSettings.audioFs=r.profile.sampleRate),o&&o.outMediaTrack&&(this._mediaSettings.videoWidth=o.profile.width,this._mediaSettings.videoHeight=o.profile.height,this._mediaSettings.videoFps=o.profile.frameRate,this._mediaSettings.videoBps=o.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:W.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:V.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?m.AUXILIARY:m.MAIN} stream`),Ht()&&(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===m.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?void 0:o.small)&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===Q.INACTIVE&&(yield this.singlePC.setTransceiverDirection(Q.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?m.AUXILIARY:m.MAIN} stream`),Ht()&&(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===m.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(Q.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?m.AUXILIARY:m.MAIN} stream`),r.kind===m.AUDIO&&t[0]&&(yield t[0].replaceTrack(r)),r.kind===m.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===m.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:W.UPDATE_MUTE_STAT,responseCommand:V.MUTE_RESULT,data:this.muteState,retries:3}).catch(()=>{}))}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&T.emit(g.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(e=m.VIDEO){if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===m.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===m.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===m.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===m.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===Zi?(this._log.error(be.NOT_SUPPORTED_H264ENCODE),new y({code:S.NOT_SUPPORTED_H264,message:w({key:x.NOT_SUPPORTED_H264ENCODE})})):new y({code:S.UNKNOWN,message:w({key:x.SIGNAL_RESPONSE_FAILED,data:{signalResponse:V.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}))})}};b([bt(function({localVideoTrack:s}){s==null||s.once("6",this.onVideoEncodeFailed,this)})],Bo.prototype,"publish",1),b([bt(function({localVideoTrack:s}){s==null||s.off("6",this.onVideoEncodeFailed,this)})],Bo.prototype,"unpublish",1);var yl=Bo;function Em(s){return Object.keys(s).filter(i=>s[i])}var Es=class extends Cr{constructor(e){super(L(v({},e),{isUplink:!1}));l(this,"_flag",0);l(this,"isRobot",!1);l(this,"role","anchor");l(this,"remoteAudioTrack");l(this,"remoteVideoTrack");l(this,"remoteAuxiliaryTrack");l(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0});l(this,"jitterBufferTimeoutId",-1);this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=new yi(this._room,this),this.remoteVideoTrack=new ei(this._room,this),this.remoteAuxiliaryTrack=new ss(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===m.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 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=m.AUDIO;r.kind===m.VIDEO&&(c=a===m.MAIN?m.VIDEO:m.AUXILIARY);let d=this.remoteAudioTrack;c===m.VIDEO?d=this.remoteVideoTrack:c===m.AUXILIARY&&(d=this.remoteAuxiliaryTrack),(h=this.singlePC)!=null&&h.scriptTransformWorker&&this.initReceiverTransform(o,a,r.kind===m.AUDIO),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(d,o),d.setInputMediaStreamTrack(r)}createEncodedStreams(e,t){if(!this.singlePC.insertableStreamsAbortMap.has(t)){let r=t.createEncodedStreams(),o=new AbortController,n={abortController:o,enqueue:a=>{var c;return(c=this.singlePC)!=null&&c.isUsingH264?e.decodeFrame(a):a}};r.readable.pipeThrough(new TransformStream({transform:(a,c)=>{let d=n.enqueue(a);d&&c.enqueue(d)}})).pipeTo(r.writable,o).catch(a=>{a!=="destory"&&this._log.warn(a)}),this.singlePC.addAbortController(t,o)}}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*(){try{if(this._log.info(`subscribe ${t} ${Em(e)}`),this.hasSSRC){let r="subscribe_change";Object.values(e).find(o=>o===!0)||(r="unsubscribe"),yield this.sendSubscription(r,e)}else yield this.doSubscribe(e),this.checkTrackEnded(e)}catch(r){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${r.message} ${JSON.stringify(this.muteState)}`),new y({code:S.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):r}})}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"),It&&At<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=v({},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} [${Em(o)}]`),n==="unsubscribe"&&((a=this.singlePC)==null||a.removeDownlinkQueue.add(this.tinyId)),yield this.sendSubscription(n,o),n==="unsubscribe"&&(yield this.removeDownlink())})}sendSubscription(e,t=this.subscribeState){let r={srcTinyId:this.tinyId,srcUserId:this.userId},o=W.UNSUBSCRIBE,n=V.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(r={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},o=W.SUBSCRIBE_CHANGE,n=V.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:w({key:x.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(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary)&&(this._log.warn(`resubscribe ${JSON.stringify(this.subscribeState)}`),this.doSubscribe(this.subscribeState))}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:Ar(),bigVideoSsrc:Ar(),bigVideoRtxSsrc:Ar(),auxVideoSsrc:Ar(),auxVideoRtxSsrc:Ar()},{audioSsrc:o,bigVideoSsrc:n,bigVideoRtxSsrc:a,auxVideoSsrc:c,auxVideoRtxSsrc:d}=r;this.ssrc={audio:o,video:n,videoRtx:a,auxiliary:c,auxiliaryRtx:d},this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc});try{let h=yield this._signalChannel.sendWaitForResponseWithRetry({command:W.SPC_SUBSCRIBE,responseCommand:V.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(h.data.code!==0)throw new y({code:h.data.code,message:h.data.message})}catch(h){throw yield this.removeDownlink(),h}return}this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc})}finally{let r=this._room.scheduleResult.config;((r==null?void 0:r.jitterDelay)||(r==null?void 0:r.jitterDelayAux))&&this.setJitterBufferDelay({mainDelay:r.jitterDelay,auxDelay:r.jitterDelayAux})}}})}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?void 0:e.jitterDelay)||(e==null?void 0:e.jitterDelayAux))&&this.setJitterBufferDelay({mainDelay:0,auxDelay:0}),yield this.singlePC.removeDownlink(this.userId)})}setJitterBufferDelay({mainDelay:e,auxDelay:t}){if(!this.singlePC||!this._peerConnection||mi(e)&&mi(t))return Promise.resolve();this._log.info(`set jitterBuffer main: ${e} aux: ${t}`);let r=this.singlePC.getReceiversByUserId(this.userId);return K(e)&&(this.remoteAudioTrack.jitterBufferDelay=e,this.remoteVideoTrack.jitterBufferDelay=e),K(t)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=t,mi(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 u;let c=a.track===this.remoteAuxiliaryTrack.outMediaTrack||mi(e)&&a.track===this.remoteAudioTrack.outMediaTrack;if(c&&mi(t)||!c&&mi(e))return;let d=c?t||0:e,h=(a.jitterBufferTarget||0)+100;h>d||(a.jitterBufferTarget=h,this._log.debug(`set ${c?"aux ":""}${(u=a==null?void 0:a.track)==null?void 0:u.kind} jitterBuffer delay ${h} -> ${d}`))}),!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}};b([Yt(),G(s=>function(...i){return new Promise((e,t)=>{let r=o=>{this.off("closed",r),t(new y({code:S.API_CALL_ABORTED,message:w({key:x.CONNECTION_ABORTED,data:o})}))};this.on("closed",r),s.apply(this,i).then(e,t).finally(()=>{this.off("closed",r)})})})],Es.prototype,"subscribe",1),b([Yt()],Es.prototype,"unsubscribe",1),b([Ai(()=>"jitter")],Es.prototype,"setJitterBufferDelay",1);var Tm=Es;function Sm(){return G(s=>function(...i){return f(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(i=i.filter(t=>t.outMediaTrack&&t.state==="capture"),!i.length))return;T.emit("61",{room:this});let e=s.apply(this,i);return i.forEach(t=>t.publish(this,e)),e})})}function Im(){return G(s=>function(...i){let e=s.apply(this,i);return i.forEach(t=>t.unpublish()),e})}var Am=Se(De());function Y_(){return Math.floor(Math.random()*16383)}var bl=class extends Am.EventEmitter{constructor(e,t){super();this.room=e;this.signalChannel=t;l(this,"log");l(this,"cmdIdSeqMap",new Map);l(this,"messageMap",new Map);this.log=R.createLogger({id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),t.on(V.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)||Y_(),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(W.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)>bl.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),$i(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((d,h)=>d.message.seq-h.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)}},$o=bl;l($o,"SEQ_INTERVAL",300);var{isString:Cm,isUndefined:Ts,getNetworkType:K_,isEmpty:Fo}=Be,Mt=class extends ka{constructor(e){super(e);this._heartbeat=-1;this._lastHeartBeatTime=-1;this._joinTimeout=-1;this._firstPublishedList=null;this._joinReject=null;this._isRelayChanged=!1;this.signalChannel=null;this.uplinkConnection=null;this.singlePC=null;this.enableSPC=jr;this._changeBigSmallRecords=new Map;this.forceRelay=!1;this._turnServers=[];this._syncUserListInterval=-1;this._smallStreamConfig={bitrate:100,frameRate:15,height:120,width:160};this.enableSEI=!1;this._enableAudioVolumeEvaluation=!1;this._audioVolumeIntervalId=0;this._enableMultiAuxStream=!1;this._pureAudioPushMode=!1;this.preferHW=!1;this._updateAudioLevelTaskId=-1;this._stats=new ko(this,this._log),this.userManager=new da(this.userId,this._log),this._version=Ie,this.sdpSemantics=yr,Ts(e.sdpSemantics)?Wt.isUnifiedPlanDefault()&&(this.sdpSemantics=Pi):this.sdpSemantics=e.sdpSemantics,this._log.info(`sdpSemantics: ${this.sdpSemantics}, netType: ${K_()}`),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=Ts(e.enableMultiAuxStream)?!1:e.enableMultiAuxStream,this.enableSEI=e.enableSEI&&jr,!Ts(e.enableSPC)&&jr&&(this.enableSPC=e.enableSPC),this.preferHW=!!e.preferHW,this._initBusinessInfo(e),this.healthDetector=new dm(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=Ol(n,[]);T.emit(g.REMOTE_PUBLISH_STATE_CHANGED,v({room:this},o)),this.emit("remote-publish-state-changed",v({},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(h){if(h instanceof y&&h.code===S.SPC_INITIALIZED_FAILED)(a=this.signalChannel)==null||a.destroy(),yield this.initialize();else return n(h)}let d=k();yield this.doJoin(e,(c=this.singlePC)==null?void 0:c.clientAbility),N.addSuccessEvent({key:521708,cost:k()-d}),o(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(d){N.addFailedEvent({key:521708,error:d}),n(d)}this._joinReject=null}))})}initSinglePC(){return f(this,null,function*(){if(!(!this.enableSPC||this.singlePC)){this.singlePC=new Ot({signalChannel:this.signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.on("sei-message",e=>this.emit("sei-message",e)),this.singlePC.once("error",()=>this.fallbackToMPC());try{return yield this.singlePC.initialize()}catch(e){throw this.fallbackToMPC(),new y({code:S.SPC_INITIALIZED_FAILED,message:e==null?void 0:e.message})}}})}doJoin(e,t){return new Promise((r,o)=>f(this,null,function*(){var c,d,h;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this.signalChannel.once(pe.SETUP_FAILED,u=>{this.clearJoinTimeout(),T.emit(g.JOIN_SIGNAL_CONNECTION_END,{room:this,error:u}),o(u)}),ue((d=(c=this.scheduleResult)==null?void 0:c.config)==null?void 0:d.singlePC)&&jr&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2);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:mc(),netType:Gr(),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;((h=this.scheduleResult.config)==null?void 0:h.enterRoomTimeout)&&this.scheduleResult.config.enterRoomTimeout>=1&&(a=this.scheduleResult.config.enterRoomTimeout*1e3),this._joinTimeout=window.setTimeout(()=>{o(new y({code:S.JOIN_ROOM_FAILED,message:w({key:x.JOIN_ROOM_TIMEOUT})}))},a),T.emit(g.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?W.SPC_JOIN_ROOM:W.JOIN_ROOM,n),this.signalChannel.once(V.JOIN_ROOM_RESULT,u=>{this.clearJoinTimeout();let{code:p,message:_,data:I,tinyId:C}=u.data;T.emit(g.JOIN_RECEIVED_CMD_RES,{room:this,code:p}),p===0?(this._log.info("Join room success, start heartbeat"),C&&(this.tinyId=C),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=I.publishers,this.singlePC&&this.singlePC.connect(L(v({},I.ability),{useVp8:I.ability.useVp8||!!e.useVp8})).catch(()=>{}),r()):(this._log.error(`Join room failed result: ${p} error: ${_}`),o(new y({code:S.JOIN_ROOM_FAILED,extraCode:p,message:w({key:x.JOIN_ROOM_FAILED,data:{error:_,code:p}})})))})}))}reJoin(e=!0){return f(this,null,function*(){if(!this.isJoined){this._log.warn("reJoin abort");return}try{this._log.warn(`reJoin pending: ${this.joinParams.roomId}`);let t,r=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,r.push(this.initSinglePC().then(o=>(t=o,o)))),this.signalChannel&&(this.signalChannel.race=e,this.signalChannel.close(),r.push(this.signalChannel.connect())),yield Promise.all(r),yield this.doJoin(L(v({},this.joinParams),{role:this.role==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),t),this._log.warn("reJoin success"),Y.logSuccessEvent({userId:this.userId,eventType:Ge.REJOIN}),this.singlePC){let o=n=>{var a;n.state==="CONNECTED"&&((a=this.singlePC)==null||a.off(ii.CONNECTION_STATE_CHANGED,o),this.uplinkConnection instanceof yl&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach(c=>{c.installEvents(),c.onSinglePCReconnected()}))};this.singlePC.on(ii.CONNECTION_STATE_CHANGED,o),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof Mo&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(t){this._log.warn(`reJoin fail ${t}`),this.reset(),Y.logFailedEvent({userId:this.userId,eventType:Ge.REJOIN,error:t}),this.emit("error",new y({code:S.JOIN_ROOM_FAILED,message:w({key:x.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}})}initialize(){return f(this,null,function*(){let{mainUrl:e,backupUrl:t}=this.getSignalChannelUrl(),r=this.signalChannel||xh(this.userId),o=!!(r&&r.isConnected&&r.keepAlive),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):(this.signalChannel=new ms({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:e,backupUrl:t,race:this.enableSPC&&!this.proxy_ws,room:this,signalDomainWhenUnifiedProxy:this.proxy_unified?n:void 0}),this._customMessageManager=new $o(this,this.signalChannel),this._customMessageManager.on("message",a=>{this.emit("custom-message",a)})),this.networkQuality||(this.networkQuality=new zi({signalChannel:this.signalChannel,room:this}),this.networkQuality.on(zi.EVENT_NETWORK_QUALITY,a=>{var c;this.emit("network-quality",a),(c=this.singlePC)==null||c.detectTCPAndUDP(a)})),Pe(this,this.signalChannel).add(pe.CONNECTION_STATE_CHANGED,a=>{T.emit(g.SIGNAL_CONNECTION_STATE_CHANGED,v({room:this},a)),this.emit("signal-connection-state-changed",a)}).add(pe.RECONNECT_FAILED,a=>{this.reset(),this.emit("error",a)}).add(V.PEER_JOIN,a=>{let{srcTinyId:c,userId:d,role:h}=a.data.data;this.userManager.addUser({userId:d,tinyId:c,role:h})}).add(V.PEER_LEAVE,a=>{let{userId:c,reason:d=0}=a.data.data;this.userManager.deleteUser(c,d)}).add(V.UPDATE_REMOTE_MUTE_STAT,a=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=10*1e3&&this.doHeartbeat(),this.onPublishedUserList(a.data)}).add(V.CLIENT_BANNED,a=>{let c=a.data.data,{reason:d}=c;if(Y.uploadEvent({log:`stat-banned:${d}`,userId:this.userId}),d==="user_time_out"){this._log.warn(`${d} last heart beat time: ${this._lastHeartBeatTime} interval: ${Date.now()-this._lastHeartBeatTime}, visibility: ${document.visibilityState}`),this.reJoin();return}this._log[d==="kick"?"error":"info"](`user was banned because of [${d}]`),this.reset(),this.emit("banned",{reason:d})}),this.signalChannel.once(pe.SETUP_SUCCESS,a=>{this.tinyId=a.signalInfo.tinyId,T.emit(g.JOIN_SIGNAL_CONNECTION_END,{room:this})}),T.emit(g.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),o&&T.emit(g.JOIN_SIGNAL_CONNECTION_END,{room:this}),o})}setSignalChannel(e){this.signalChannel=e,e||Ee(this)}leave(){return f(this,null,function*(){var e;try{yield this.doHeartbeat()}catch(t){}this._log.info("leave() => leaving room"),T.emit(g.LEAVE_SEND_CMD,{room:this}),(e=this.signalChannel)==null||e.send(W.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=ee.run(Li,this.doHeartbeat.bind(this),{delay:2e3}))}stopHeartbeat(){this._heartbeat!==-1&&(this._log.info("stopHeartbeat"),ee.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?oh(this.userId):[],o=L(v({str_sdk_version:ys,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:v({uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:Gr()},t.msg_device_info)});if(this.heartbeatReport=o,T.emit(g.HEARTBEAT_REPORT,{room:this,report:o}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(W.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(v({},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!==Ga).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})}),T.emit(g.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 Mo&&(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?Tm:hl)({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!==S.ICE_TRANSPORT_ERROR&&(o===S.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",r))}),e.on("connection-state-changed",r=>{this.emit("media-connection-state-changed",L(v({},r),{userId:e.userId}))}),e.on("firewall-restriction",()=>{this.emit("firewall-restriction")})}startSyncUserListInterval(){this._syncUserListInterval===-1&&(this._syncUserListInterval=ee.run(Li,this.syncUserList.bind(this)))}stopSyncUserListInterval(){ee.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:W.GET_USER_LIST,responseCommand:V.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:d})=>({userId:a,tinyId:c,role:d}));throw w({key:x.SIGNAL_RESPONSE_FAILED,data:{signalResponse:V.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||!al)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)===ne.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach(r=>{if(r instanceof He&&!r.getIsReconnecting()){let o=r.getPeerConnection();o&&o.connectionState===ne.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"),Y.uploadEvent({log:"stat-fallback",userId:this.userId}),this.enableSPC=!1,(e=this.singlePC)==null||e.close(),this.singlePC=null,this.isJoined&&(yield this.reJoin(!1)),this.uplinkConnection){let t=this.uplinkConnection;this.uplinkConnection=new Mo({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 hl({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:S.INVALID_OPERATION,message:w({key:x.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners(),this.healthDetector.destroy(),ee.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:W.SWITCH_ROLE,data:{role:e==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:V.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:S.SWITCH_ROLE_FAILED,message:w({key:x.SWITCH_ROLE_FAILED,data:{message:n,code:o}})});this.role=e}).catch(r=>{throw r instanceof y&&r.getCode()===S.API_CALL_TIMEOUT&&(r=new y({code:S.SWITCH_ROLE_FAILED,message:w({key:x.SWITCH_ROLE_TIMEOUT})})),this._log.error(r),r})}publish(...e){return f(this,null,function*(){let t={},r={};e.forEach(c=>{c instanceof Le&&(c instanceof Kt?r.audio=c:t.audio=c),c instanceof me&&(c instanceof rt&&c.mediaType===2?r.video=c:t.video=c)});let o=Fo(t),n=Fo(r);(!o||!n)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new yl({userId:this.userId,tinyId:this.tinyId,room:this}):this.uplinkConnection=new Mo({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(v({},c),{userId:this.userId}))}),this.uplinkConnection.on("firewall-restriction",()=>{this.emit("firewall-restriction")}),this.uplinkConnection.on("error",c=>{let d=c.getCode();d!==S.ICE_TRANSPORT_ERROR&&(d===S.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 Le&&(o instanceof Kt?r.audio=o:t.audio=o),o instanceof me&&(o instanceof rt&&o.mediaType===2?r.video=o:t.video=o))});try{let o=e.map(n=>n.kind).join(",");Fo(t)||(this._log.info(`unpublish() => main ${o}`),yield this.uplinkConnection.unpublish({localAudioTrack:t.audio,localVideoTrack:t.video})),Fo(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||!xc()?Promise.resolve():this.uplinkConnection.replaceTrack(e).then(t=>{t&&T.emit(g.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:m.VIDEO,videoType:m.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=v({},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),T.emit(g.SUBSCRIBE_START,{room:this,streamType:o,remotePublishedUser:r,subscribeState:n}),this._log.info(`subscribe() => ${t} ${o} [${ba(n)}] prev: [${ba(r.subscribeState)}]`),yield r.subscribe(n,o),this._log.info(`subscribe ${t} ${o} done`);for(let c of e)c.mediaTrack||(yield c.waitHasMediaTrack());T.emit(g.SUBSCRIBE_SUCCESS,{room:this,streamType:o,remotePublishedUser:r})}catch(n){let a=n instanceof y?n.getCode():S.UNKNOWN,c=n;throw n instanceof y?a===S.REMOTE_STREAM_NOT_EXIST&&(c=new y({code:S.API_CALL_ABORTED,message:w({key:x.API_CALL_ABORTED,data:{message:n.message,userId:t,streamType:o}})}),this._log.warn(c)):(c=new y({code:a,message:w({key:x.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)}),T.emit(g.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,ee.clearTask(this._audioVolumeIntervalId);return}e=Math.floor(Math.max(e,100)),T.emit(g.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&ee.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=ee.run(vr,()=>{var o;Xc.isRunning?this.stopUpdateAudioLevelFromSenderStat():this.updateAudioLevelFromSenderStat(e,t);let r=[];(o=this.remotePublishedUserMap)==null||o.forEach(n=>{if(n.muteState.hasAudio){!Xc.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)},{fps:1e3/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=ee.run(vr,()=>f(this,null,function*(){let a=yield r.getStats();this._updateAudioLevelTaskId<0||a.forEach(c=>{c.type==="media-source"&&c.audioLevel&&(this.uplinkConnection.localMainAudioTrack.volume=c.audioLevel)})}),{delay:o,backgroundTask:t})})}stopUpdateAudioLevelFromSenderStat(){var e;this._updateAudioLevelTaskId!==-1&&(this._log.warn("stopUpdateAudioLevelFromSenderStat"),ee.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(!wc||!t)return;let r=(o=t.getSynchronizationSources()[0])==null?void 0:o.audioLevel;r?e.remoteAudioTrack.volume=Math.min(r*2,1):t.getStats().then(n=>{n.forEach(a=>{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(Be.getTurnServer(o))):Be.isPlainObject(e)&&r.push(Be.getTurnServer(e)),this._turnServers=r,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:W.START_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:V.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:W.STOP_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:V.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"})}sendStartPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?W.START_PUBLISH_TENCENT_CDN:W.START_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?V.START_PUBLISH_TENCENT_CDN_RES:V.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"})}sendStopPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?W.STOP_PUBLISH_TENCENT_CDN:W.STOP_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?V.STOP_PUBLISH_TENCENT_CDN_RES:V.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}sendStartPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:W.START_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:V.START_PUBLISH_CDN_STREAM_RES,commandDesc:"startPublishCDNStream"})}sendUpdatePushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:W.UPDATE_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:V.UPDATE_PUBLISH_CDN_STREAM_RES,commandDesc:"updatePublishCDNStream"})}sendStopPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:W.STOP_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:V.STOP_PUBLISH_CDN_STREAM_RES,commandDesc:"stopPublishCDNStream"})}sendAbilityStatus(e){var t;(t=this.signalChannel)==null||t.sendWaitForResponse({command:W.ABILITY_STATUS_REPORT,data:e,timeout:5e3,responseCommand:V.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch(r=>{})}getIceServers(){return this._turnServers.length===0&&this.scheduleResult.iceServers?this.scheduleResult.iceServers:this._turnServers}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=Be.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:d}=a;if(c.video&&t.video||c.smallVideo&&t.smallVideo&&o)return;let h={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:c.video,smallVideo:c.smallVideo};try{if(!o&&h.smallVideo&&(h.video=!0,h.smallVideo=!1),h.smallVideo===t.smallVideo&&h.video===t.video)return;a.isSubscribing=!0,a.reSubscribeCount=d-1,yield e.subscribe(h,"main"),e.remoteVideoTrack.setMediaType(h.smallVideo?8:4),this._log.info(`change [${r}] to ${h.smallVideo?"small":"big"} video successfully. count ${br-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount=br}catch(u){this._log.info(`change [${r}] to ${h.smallVideo?"small":"big"} video failed. count ${br-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount===0&&this._changeBigSmallRecords.delete(r)}})}changeType(e,t){let o={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:br};this._changeBigSmallRecords.set(t.userId,o),this._log.info(`set [${t.userId}] video prefer type: ${e?"small":"big"}`)}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(e){this._businessInfo=e.businessInfo;let t={};if(Cm(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!Ts(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new y({code:S.INVALID_PARAMETER,message:w({key:x.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(!Ts(e.userDefineRecordId)){let r=/^[A-Za-z0-9_-]{1,64}$/gi;if(e.userDefineRecordId.match(r)===null)throw new y({code:S.INVALID_PARAMETER,message:w({key:x.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!Ts(e.userDefinePushArgs))if(Cm(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:S.INVALID_PARAMETER,message:w({key:x.INVALID_USER_DEFINE_PUSH_ARGS})});Fo(t)||(this._businessInfo=JSON.stringify(t))}sendCustomMessage(e){var t;(t=this._customMessageManager)==null||t.send(e)}enableInsertableStreams(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&Ti)return this.singlePC.enableInsertableStreams=!0,this.singlePC.startReconnection()}sendSignalMessage(e){var t;return this.signalChannel?(t=this.signalChannel)==null?void 0:t.sendWaitForResponseWithRetry(e):Promise.reject(new y({code:S.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}};b([Sl(["left",ce.INIT],"joined"),je({settings:{retries:1,timeout:0},onRetrying(s){this._log.warn(`join retry ${s}`)},onRetryFailed(s){this._log.error("join failed",s)},onError(s,i){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),$t(!0),this.reset(),i()):this.signalChannel&&this.signalChannel.isConnected&&this.signalChannel.keepAlive?(this._log.warn("is using keepAlive ws, retry join"),this.signalChannel.close(),this.reset(),i()):(this.reset(),i())}}),Oh()],Mt.prototype,"join",1),b([Sl("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),Mh(),qn("leave room"),ho({fnName:"publish",validateArgs:!1}),ho({fnName:"unsubscribe",validateArgs:!1})],Mt.prototype,"leave",1),b([Yt(),Sm(),je({settings:{retries:oi,timeout:s=>Ft(s)},onError(s,i,e){var t;(t=s.message)!=null&&t.includes("timeout")?(this._log.warn("publish timeout"),i()):(this._log.error(`publish failed: ${s}`),e(s),T.emit(g.PUBLISH_FAILED,{room:this}))}})],Mt.prototype,"publish",1),b([ho({fnName:"publish"}),qu("api-call"),Yt(),Im(),bt(function(){var s,i;this.localTracks.size===0&&Hi()&&((i=(s=this.singlePC)==null?void 0:s.getPeerConnection())==null||i.getSenders().forEach(e=>e.track&&e.replaceTrack(null)))})],Mt.prototype,"unpublish",1),b([Ju(s=>{if(s.code!==S.API_CALL_ABORTED)throw s}),Ai(s=>s.userId)],Mt.prototype,"replaceTrack",1),b([Ai((...s)=>s[0].userId),zn(),kh(),je({settings:{retries:oi,timeout:s=>Ft(s)},onError(s,i,e,t){s.message.includes("timeout")?(this._log.warn("subscribe timeout"),i()):(this._log.error(`subscribe failed: ${s}`),e(s),T.emit(g.SUBSCRIBE_FAILED,{room:this,remoteTracks:t}))}})],Mt.prototype,"subscribe",1),b([ho({fnName:"subscribe",callback(...s){this.singlePC||s.forEach(i=>{let e=this.remotePublishedUserMap.get(i.userId);e&&!e.isMainStreamSubscribed&&!e.isAuxStreamSubscribed&&e.close("you unsubscribed")})}}),Ai((...s)=>s[0].userId)],Mt.prototype,"unsubscribe",1);Do.create=Do._create.bind(Do,Mt);var QU=Do;export{QU as default};
87
+ 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:d,currentDirection:h,direction:u,stopped:p})=>({mid:d,currentDirection:h,direction:u,stopped:p})))}`),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(!re||!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===Q.INACTIVE&&n===Q.RECVONLY&&(this._parsedAnswer.media[o].direction=e),e===Q.SENDONLY&&n===Q.INACTIVE&&(this._parsedAnswer.media[o].direction=Q.RECVONLY)}yield this.updateSDP()})}filterSDPDirection(e=""){return le(e).media.map(r=>r.direction)}setOffer(e){return this._log.info("setting offer"),this._log.debug(e.sdp),this._peerConnection.setLocalDescription({type:"offer",sdp:am(e.sdp,this.clientAbility,this._serverAbility)})}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===m.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=[],Ir(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=[];E(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===m.VIDEO){let c;e&&this.is42001fSupported?c=this.clientAbility.video.codecs.find(d=>d.fmtp.includes("42001f")):e||(c=this._serverAbility.video.codecs.find(d=>d.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=[],Ir(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;(e=this._peerConnection)==null||e.close(),this._waitForPCConnectedPromise=null,this._parsedAnswer=null}close(){this._log.info("close pc"),this.removeRTCListener(),this.insertableStreamsAbortMap.forEach(e=>wt(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 h;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}=((h=this._room.scheduleResult.config)==null?void 0:h.useTurnTcpInfo)||{};if(!n||!a||!r||!o)return;let c=Math.floor(o/r),d=(this._isRelayTried||c>n)&&o>a;if(!d){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: ${d} 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`),N.addSuccessEvent({key:o,cost:Date.now()-n})}catch(n){this._log.warn(`switchRelay ${r} failed`,n),N.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.ontrack=null),this.dtlsTransport&&(this.dtlsTransport.onstatechange=null)}};b([qn("reconnect")],Ot.prototype,"startReconnection",1),b([Ai(s=>s.userId)],Ot.prototype,"addDownlink",1),b([Ai(s=>s)],Ot.prototype,"removeDownlink",1),b([Yt(!0)],Ot.prototype,"updateSDP",1),b([Qe(521712,!1)],Ot.prototype,"setOffer",1),b([Qe(521713,!1)],Ot.prototype,"setAnswer",1);var Cl=class{constructor(i){l(this,"tag");l(this,"len");l(this,"data");let e=new DataView(i);this.tag=e.getUint16(),this.len=e.getUint16(2),this.data=new Uint8Array(i).slice(4,2+2+this.len).buffer}},Rl=class{constructor(i){l(this,"tinyId");l(this,"data");let e=new DataView(i),t=0,r=[];for(;t<e.byteLength;){let o=e.getUint16(t+2),n=new Cl(new Uint8Array(i).slice(t,t+2+2+o).buffer);r.push(n),t+=2+2+o}r.forEach(o=>{o.tag===1?this.tinyId=new TextDecoder().decode(o.data):o.tag===2&&(this.data=o.data)})}},mm=new Set;function Ar(){let s=Math.floor(Math.random()*4294967296);return mm.has(s)?Ar():(mm.add(s),s)}var gm=Se(De());var Cr=class extends gm.default{constructor(e){super();l(this,"userId");l(this,"tinyId");l(this,"_sdpSemantics");l(this,"_isUplink");l(this,"_room");l(this,"_log");l(this,"_currentState","DISCONNECTED");l(this,"_prevTime",-1);this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=R.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:(T.emit(g.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 Bo=class extends Cr{constructor(e){super(L(v({},e),{isUplink:!0}));l(this,"localMainAudioTrack",null);l(this,"localMainVideoTrack",null);l(this,"localAuxAudioTrack",null);l(this,"localAuxVideoTrack",null);l(this,"_isPublishingAux",!1);l(this,"_publishingLocalAudioTrack");l(this,"_publishingLocalVideoTrack");l(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});l(this,"_flag",0);l(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]} ${hi()} ${rr()}`),N.addCount({key:521e3});else{this._checkPublishStateTimeoutId=ee.run(xi,()=>this.checkPublishState(!0),{delay:10*1e3,count:1});return}ee.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&&(Ht()?(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===m.AUDIO?e.audio=!0:(e.bigVideo=!0,this._room.videoManager.hasSmall&&(e.smallVideo=!0)))}))}return e}get serverPublishState(){return{audio:!!(this.flag&ki),bigVideo:!!(this.flag&Mi),smallVideo:!!(this.flag&vs),auxVideo:!!(this.flag&Ki)}}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,r;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"),(r=this.singlePC)==null||r.switchVideoEncoder("vp8")))}publish(o){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:r}){var d,h,u,p,_,I,C;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:S.NOT_SUPPORTED_H264,message:w({key:x.NOT_SUPPORTED_H264ENCODE})});fe&&di()===115&&t.profile.width*t.profile.height<=640*360&&(this._log.warn("fallback video to 480p"),t.setProfile(nt["480p_2"]),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:W.SPC_PUBLISH,responseCommand:V.SPC_PUBLISH_RESULT,data:L(v({},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;let{scaleResolutionDownBy:D}=t;yield this.singlePC.setScaleResolutionDownBy(this._peerConnection.getSenders()[r?3:1],D,t.streamType)}e&&(this[r?"localAuxAudioTrack":"localMainAudioTrack"]=e),yield this.singlePC.setBandwidth({audio:((d=this.localMainAudioTrack)==null?void 0:d.profile.bitrate)||((h=this.localAuxAudioTrack)==null?void 0:h.profile.bitrate),bigVideo:(u=this.localMainVideoTrack)==null?void 0:u.profile.bitrate,smallVideo:(_=(p=this.localMainVideoTrack)==null?void 0:p.small)==null?void 0:_.bitrate,auxVideo:(I=this.localAuxVideoTrack)==null?void 0:I.profile.bitrate}),this.sendMediaSettings(),this.installTrackMuteEvents(e,t),!r&&(this._room.preferHW||((C=this._room.scheduleResult.config)==null?void 0:C.preferHW))&&t&&t.profile.width*t.profile.height>=1280*720&&this.singlePC.useHWEncoder(!0,2)})}publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:r,isAuxiliary:o}){if(!ct())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(),d=[],h=[],u=(_,I,C)=>{var B,Me;let D=c[I].sender.replaceTrack(C);h.push(I),(B=this.singlePC)!=null&&B.enableInsertableStreams&&D.then(()=>this.createEncodedStreams(c[I].sender,_)),(Me=this.singlePC)!=null&&Me.scriptTransformWorker&&this.initSenderTransfrom(c[I].sender,_),d.push(D)};a&&u(e.mediaType,0,a),n&&u(t.mediaType,o?3:1,n),r&&u(8,2,r);let p=this.singlePC.setTransceiverDirection(Q.SENDONLY,h);return d.push(p),Promise.all(d)}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:(d,h)=>{var p;let u=this.getTrackByMediaType(t);h.enqueue(((p=this.singlePC)==null?void 0:p.isUsingH264)&&u?u.encodeFrame(d,t===8):d)}}),o):r.readable).pipeTo(r.writable,o).catch(d=>{this._log.debug("encoded stream error",d),d!=="destory"&&this._log.warn(d)})}initSenderTransfrom(e,t){if(!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker)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*(){if(!this.singlePC)return;let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.singlePC.setTransceiverDirection(Q.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(Q.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()})}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(r){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){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(v({},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(v({},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(Q.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.publishState,constraintConfig:this._mediaSettings},r=yield this._signalChannel.sendWaitForResponseWithRetry({command:W.PUBLISH_STATE_CHANGE,data:t,responseCommand:V.PUBLISH_STATE_CHANGE_RESULT,enableLog:e,retries:3});this.checkPublishResultCode(r.data.code,r.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:W.UNPUBLISH,commandDesc:"unpublish",responseCommand:V.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===S.API_CALL_TIMEOUT)return Promise.resolve();throw t})}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let r=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:o,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:o=this._publishingLocalVideoTrack),Gt){if(r&&r.outMediaTrack){let a=r.outMediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=r.profile.bitrate*1e3,this._mediaSettings.audioFs=a.sampleRate||0}if(o&&o.outMediaTrack){let a=o.outMediaTrack.getSettings();this._mediaSettings.videoWidth=a.width||0,this._mediaSettings.videoHeight=a.height||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=o.profile.bitrate*1e3,o.small&&(this._mediaSettings.smallVideoWidth=o.small.width,this._mediaSettings.smallVideoHeight=o.small.height,this._mediaSettings.smallVideoFps=o.small.frameRate,this._mediaSettings.smallVideoBps=o.small.bitrate*1e3)}if(n&&n.outMediaTrack){let a=n.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=a.width||0,this._mediaSettings.auxVideoHeight=a.height||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=n.profile.bitrate*1e3}}else r&&r.outMediaTrack&&(this._mediaSettings.audioChannel=r.profile.channelCount,this._mediaSettings.audioBps=r.profile.bitrate*1e3,this._mediaSettings.audioFs=r.profile.sampleRate),o&&o.outMediaTrack&&(this._mediaSettings.videoWidth=o.profile.width,this._mediaSettings.videoHeight=o.profile.height,this._mediaSettings.videoFps=o.profile.frameRate,this._mediaSettings.videoBps=o.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:W.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:V.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?m.AUXILIARY:m.MAIN} stream`),Ht()&&(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===m.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?void 0:o.small)&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===Q.INACTIVE&&(yield this.singlePC.setTransceiverDirection(Q.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?m.AUXILIARY:m.MAIN} stream`),Ht()&&(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===m.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(Q.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?m.AUXILIARY:m.MAIN} stream`),r.kind===m.AUDIO&&t[0]&&(yield t[0].replaceTrack(r)),r.kind===m.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===m.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:W.UPDATE_MUTE_STAT,responseCommand:V.MUTE_RESULT,data:this.muteState,retries:3}).catch(()=>{}))}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&T.emit(g.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(e=m.VIDEO){if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===m.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===m.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===m.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===m.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===Zi?(this._log.error(be.NOT_SUPPORTED_H264ENCODE),new y({code:S.NOT_SUPPORTED_H264,message:w({key:x.NOT_SUPPORTED_H264ENCODE})})):new y({code:S.UNKNOWN,message:w({key:x.SIGNAL_RESPONSE_FAILED,data:{signalResponse:V.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}))})}};b([bt(function({localVideoTrack:s}){s==null||s.once("6",this.onVideoEncodeFailed,this)})],Bo.prototype,"publish",1),b([bt(function({localVideoTrack:s}){s==null||s.off("6",this.onVideoEncodeFailed,this)})],Bo.prototype,"unpublish",1);var yl=Bo;function Em(s){return Object.keys(s).filter(i=>s[i])}var Es=class extends Cr{constructor(e){super(L(v({},e),{isUplink:!1}));l(this,"_flag",0);l(this,"isRobot",!1);l(this,"role","anchor");l(this,"remoteAudioTrack");l(this,"remoteVideoTrack");l(this,"remoteAuxiliaryTrack");l(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0});l(this,"jitterBufferTimeoutId",-1);this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=new yi(this._room,this),this.remoteVideoTrack=new ei(this._room,this),this.remoteAuxiliaryTrack=new ss(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===m.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 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=m.AUDIO;r.kind===m.VIDEO&&(c=a===m.MAIN?m.VIDEO:m.AUXILIARY);let d=this.remoteAudioTrack;c===m.VIDEO?d=this.remoteVideoTrack:c===m.AUXILIARY&&(d=this.remoteAuxiliaryTrack),(h=this.singlePC)!=null&&h.scriptTransformWorker&&this.initReceiverTransform(o,a,r.kind===m.AUDIO),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(d,o),d.setInputMediaStreamTrack(r)}createEncodedStreams(e,t){if(!this.singlePC.insertableStreamsAbortMap.has(t)){let r=t.createEncodedStreams(),o=new AbortController,n={abortController:o,enqueue:a=>{var c;return(c=this.singlePC)!=null&&c.isUsingH264?e.decodeFrame(a):a}};r.readable.pipeThrough(new TransformStream({transform:(a,c)=>{let d=n.enqueue(a);d&&c.enqueue(d)}})).pipeTo(r.writable,o).catch(a=>{a!=="destory"&&this._log.warn(a)}),this.singlePC.addAbortController(t,o)}}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*(){try{if(this._log.info(`subscribe ${t} ${Em(e)}`),this.hasSSRC){let r="subscribe_change";Object.values(e).find(o=>o===!0)||(r="unsubscribe"),yield this.sendSubscription(r,e)}else yield this.doSubscribe(e),this.checkTrackEnded(e)}catch(r){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${r.message} ${JSON.stringify(this.muteState)}`),new y({code:S.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):r}})}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"),It&&At<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=v({},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} [${Em(o)}]`),n==="unsubscribe"&&((a=this.singlePC)==null||a.removeDownlinkQueue.add(this.tinyId)),yield this.sendSubscription(n,o),n==="unsubscribe"&&(yield this.removeDownlink())})}sendSubscription(e,t=this.subscribeState){let r={srcTinyId:this.tinyId,srcUserId:this.userId},o=W.UNSUBSCRIBE,n=V.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(r={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},o=W.SUBSCRIBE_CHANGE,n=V.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:w({key:x.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(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary)&&(this._log.warn(`resubscribe ${JSON.stringify(this.subscribeState)}`),this.doSubscribe(this.subscribeState))}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:Ar(),bigVideoSsrc:Ar(),bigVideoRtxSsrc:Ar(),auxVideoSsrc:Ar(),auxVideoRtxSsrc:Ar()},{audioSsrc:o,bigVideoSsrc:n,bigVideoRtxSsrc:a,auxVideoSsrc:c,auxVideoRtxSsrc:d}=r;this.ssrc={audio:o,video:n,videoRtx:a,auxiliary:c,auxiliaryRtx:d},this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc});try{let h=yield this._signalChannel.sendWaitForResponseWithRetry({command:W.SPC_SUBSCRIBE,responseCommand:V.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(h.data.code!==0)throw new y({code:h.data.code,message:h.data.message})}catch(h){throw yield this.removeDownlink(),h}return}this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc})}finally{let r=this._room.scheduleResult.config;((r==null?void 0:r.jitterDelay)||(r==null?void 0:r.jitterDelayAux))&&this.setJitterBufferDelay({mainDelay:r.jitterDelay,auxDelay:r.jitterDelayAux})}}})}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?void 0:e.jitterDelay)||(e==null?void 0:e.jitterDelayAux))&&this.setJitterBufferDelay({mainDelay:0,auxDelay:0}),yield this.singlePC.removeDownlink(this.userId)})}setJitterBufferDelay({mainDelay:e,auxDelay:t}){if(!this.singlePC||!this._peerConnection||mi(e)&&mi(t))return Promise.resolve();this._log.info(`set jitterBuffer main: ${e} aux: ${t}`);let r=this.singlePC.getReceiversByUserId(this.userId);return K(e)&&(this.remoteAudioTrack.jitterBufferDelay=e,this.remoteVideoTrack.jitterBufferDelay=e),K(t)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=t,mi(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 u;let c=a.track===this.remoteAuxiliaryTrack.outMediaTrack||mi(e)&&a.track===this.remoteAudioTrack.outMediaTrack;if(c&&mi(t)||!c&&mi(e))return;let d=c?t||0:e,h=(a.jitterBufferTarget||0)+100;h>d||(a.jitterBufferTarget=h,this._log.debug(`set ${c?"aux ":""}${(u=a==null?void 0:a.track)==null?void 0:u.kind} jitterBuffer delay ${h} -> ${d}`))}),!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}};b([Yt(),G(s=>function(...i){return new Promise((e,t)=>{let r=o=>{this.off("closed",r),t(new y({code:S.API_CALL_ABORTED,message:w({key:x.CONNECTION_ABORTED,data:o})}))};this.on("closed",r),s.apply(this,i).then(e,t).finally(()=>{this.off("closed",r)})})})],Es.prototype,"subscribe",1),b([Yt()],Es.prototype,"unsubscribe",1),b([Ai(()=>"jitter")],Es.prototype,"setJitterBufferDelay",1);var Tm=Es;function Sm(){return G(s=>function(...i){return f(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(i=i.filter(t=>t.outMediaTrack&&t.state==="capture"),!i.length))return;T.emit("61",{room:this});let e=s.apply(this,i);return i.forEach(t=>t.publish(this,e)),e})})}function Im(){return G(s=>function(...i){let e=s.apply(this,i);return i.forEach(t=>t.unpublish()),e})}var Am=Se(De());function Y_(){return Math.floor(Math.random()*16383)}var bl=class extends Am.EventEmitter{constructor(e,t){super();this.room=e;this.signalChannel=t;l(this,"log");l(this,"cmdIdSeqMap",new Map);l(this,"messageMap",new Map);this.log=R.createLogger({id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),t.on(V.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)||Y_(),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(W.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)>bl.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),$i(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((d,h)=>d.message.seq-h.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)}},$o=bl;l($o,"SEQ_INTERVAL",300);var{isString:Cm,isUndefined:Ts,getNetworkType:K_,isEmpty:Fo}=Be,Mt=class extends ka{constructor(e){super(e);this._heartbeat=-1;this._lastHeartBeatTime=-1;this._joinTimeout=-1;this._firstPublishedList=null;this._joinReject=null;this._isRelayChanged=!1;this.signalChannel=null;this.uplinkConnection=null;this.singlePC=null;this.enableSPC=jr;this._changeBigSmallRecords=new Map;this.forceRelay=!1;this._turnServers=[];this._syncUserListInterval=-1;this._smallStreamConfig={bitrate:100,frameRate:15,height:120,width:160};this.enableSEI=!1;this._enableAudioVolumeEvaluation=!1;this._audioVolumeIntervalId=0;this._enableMultiAuxStream=!1;this._pureAudioPushMode=!1;this.preferHW=!1;this._updateAudioLevelTaskId=-1;this._stats=new ko(this,this._log),this.userManager=new da(this.userId,this._log),this._version=Ie,this.sdpSemantics=yr,Ts(e.sdpSemantics)?Wt.isUnifiedPlanDefault()&&(this.sdpSemantics=Pi):this.sdpSemantics=e.sdpSemantics,this._log.info(`sdpSemantics: ${this.sdpSemantics}, netType: ${K_()}`),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=Ts(e.enableMultiAuxStream)?!1:e.enableMultiAuxStream,this.enableSEI=e.enableSEI&&jr,!Ts(e.enableSPC)&&jr&&(this.enableSPC=e.enableSPC),this.preferHW=!!e.preferHW,this._initBusinessInfo(e),this.healthDetector=new dm(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=Ol(n,[]);T.emit(g.REMOTE_PUBLISH_STATE_CHANGED,v({room:this},o)),this.emit("remote-publish-state-changed",v({},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(h){if(h instanceof y&&h.code===S.SPC_INITIALIZED_FAILED)(a=this.signalChannel)==null||a.destroy(),yield this.initialize();else return n(h)}let d=k();yield this.doJoin(e,(c=this.singlePC)==null?void 0:c.clientAbility),N.addSuccessEvent({key:521708,cost:k()-d}),o(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(d){N.addFailedEvent({key:521708,error:d}),n(d)}this._joinReject=null}))})}initSinglePC(){return f(this,null,function*(){if(!(!this.enableSPC||this.singlePC)){this.singlePC=new Ot({signalChannel:this.signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.on("sei-message",e=>this.emit("sei-message",e)),this.singlePC.once("error",()=>this.fallbackToMPC());try{return yield this.singlePC.initialize()}catch(e){throw this.fallbackToMPC(),new y({code:S.SPC_INITIALIZED_FAILED,message:e==null?void 0:e.message})}}})}doJoin(e,t){return new Promise((r,o)=>f(this,null,function*(){var c,d,h;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this.signalChannel.once(pe.SETUP_FAILED,u=>{this.clearJoinTimeout(),T.emit(g.JOIN_SIGNAL_CONNECTION_END,{room:this,error:u}),o(u)}),ue((d=(c=this.scheduleResult)==null?void 0:c.config)==null?void 0:d.singlePC)&&jr&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2);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:mc(),netType:Gr(),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;((h=this.scheduleResult.config)==null?void 0:h.enterRoomTimeout)&&this.scheduleResult.config.enterRoomTimeout>=1&&(a=this.scheduleResult.config.enterRoomTimeout*1e3),this._joinTimeout=window.setTimeout(()=>{o(new y({code:S.JOIN_ROOM_FAILED,message:w({key:x.JOIN_ROOM_TIMEOUT})}))},a),T.emit(g.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?W.SPC_JOIN_ROOM:W.JOIN_ROOM,n),this.signalChannel.once(V.JOIN_ROOM_RESULT,u=>{this.clearJoinTimeout();let{code:p,message:_,data:I,tinyId:C}=u.data;T.emit(g.JOIN_RECEIVED_CMD_RES,{room:this,code:p}),p===0?(this._log.info("Join room success, start heartbeat"),C&&(this.tinyId=C),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=I.publishers,this.singlePC&&this.singlePC.connect(L(v({},I.ability),{useVp8:I.ability.useVp8||!!e.useVp8})).catch(()=>{}),r()):(this._log.error(`Join room failed result: ${p} error: ${_}`),o(new y({code:S.JOIN_ROOM_FAILED,extraCode:p,message:w({key:x.JOIN_ROOM_FAILED,data:{error:_,code:p}})})))})}))}reJoin(e=!0){return f(this,null,function*(){if(!this.isJoined){this._log.warn("reJoin abort");return}try{this._log.warn(`reJoin pending: ${this.joinParams.roomId}`);let t,r=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,r.push(this.initSinglePC().then(o=>(t=o,o)))),this.signalChannel&&(this.signalChannel.race=e,this.signalChannel.close(),r.push(this.signalChannel.connect())),yield Promise.all(r),yield this.doJoin(L(v({},this.joinParams),{role:this.role==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),t),this._log.warn("reJoin success"),Y.logSuccessEvent({userId:this.userId,eventType:Ge.REJOIN}),this.singlePC){let o=n=>{var a;n.state==="CONNECTED"&&((a=this.singlePC)==null||a.off(ii.CONNECTION_STATE_CHANGED,o),this.uplinkConnection instanceof yl&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach(c=>{c.installEvents(),c.onSinglePCReconnected()}))};this.singlePC.on(ii.CONNECTION_STATE_CHANGED,o),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof Mo&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(t){this._log.warn(`reJoin fail ${t}`),this.reset(),Y.logFailedEvent({userId:this.userId,eventType:Ge.REJOIN,error:t}),this.emit("error",new y({code:S.JOIN_ROOM_FAILED,message:w({key:x.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}})}initialize(){return f(this,null,function*(){let{mainUrl:e,backupUrl:t}=this.getSignalChannelUrl(),r=this.signalChannel||xh(this.userId),o=!!(r&&r.isConnected&&r.keepAlive),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):(this.signalChannel=new ms({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:e,backupUrl:t,race:this.enableSPC&&!this.proxy_ws,room:this,signalDomainWhenUnifiedProxy:this.proxy_unified?n:void 0}),this._customMessageManager=new $o(this,this.signalChannel),this._customMessageManager.on("message",a=>{this.emit("custom-message",a)})),this.networkQuality||(this.networkQuality=new zi({signalChannel:this.signalChannel,room:this}),this.networkQuality.on(zi.EVENT_NETWORK_QUALITY,a=>{var c;this.emit("network-quality",a),(c=this.singlePC)==null||c.detectTCPAndUDP(a)})),Pe(this,this.signalChannel).add(pe.CONNECTION_STATE_CHANGED,a=>{T.emit(g.SIGNAL_CONNECTION_STATE_CHANGED,v({room:this},a)),this.emit("signal-connection-state-changed",a)}).add(pe.RECONNECT_FAILED,a=>{this.reset(),this.emit("error",a)}).add(V.PEER_JOIN,a=>{let{srcTinyId:c,userId:d,role:h}=a.data.data;this.userManager.addUser({userId:d,tinyId:c,role:h})}).add(V.PEER_LEAVE,a=>{let{userId:c,reason:d=0}=a.data.data;this.userManager.deleteUser(c,d)}).add(V.UPDATE_REMOTE_MUTE_STAT,a=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=10*1e3&&this.doHeartbeat(),this.onPublishedUserList(a.data)}).add(V.CLIENT_BANNED,a=>{let c=a.data.data,{reason:d}=c;if(Y.uploadEvent({log:`stat-banned:${d}`,userId:this.userId}),d==="user_time_out"){this._log.warn(`${d} last heart beat time: ${this._lastHeartBeatTime} interval: ${Date.now()-this._lastHeartBeatTime}, visibility: ${document.visibilityState}`),this.reJoin();return}this._log[d==="kick"?"error":"info"](`user was banned because of [${d}]`),this.reset(),this.emit("banned",{reason:d})}),this.signalChannel.once(pe.SETUP_SUCCESS,a=>{this.tinyId=a.signalInfo.tinyId,T.emit(g.JOIN_SIGNAL_CONNECTION_END,{room:this})}),T.emit(g.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),o&&T.emit(g.JOIN_SIGNAL_CONNECTION_END,{room:this}),o})}setSignalChannel(e){this.signalChannel=e,e||Ee(this)}leave(){return f(this,null,function*(){var e;try{yield this.doHeartbeat()}catch(t){}this._log.info("leave() => leaving room"),T.emit(g.LEAVE_SEND_CMD,{room:this}),(e=this.signalChannel)==null||e.send(W.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=ee.run(Li,this.doHeartbeat.bind(this),{delay:2e3}))}stopHeartbeat(){this._heartbeat!==-1&&(this._log.info("stopHeartbeat"),ee.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?oh(this.userId):[],o=L(v({str_sdk_version:ys,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:v({uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:Gr()},t.msg_device_info)});if(this.heartbeatReport=o,T.emit(g.HEARTBEAT_REPORT,{room:this,report:o}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(W.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(v({},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!==Ga).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})}),T.emit(g.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 Mo&&(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?Tm:hl)({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!==S.ICE_TRANSPORT_ERROR&&(o===S.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",r))}),e.on("connection-state-changed",r=>{this.emit("media-connection-state-changed",L(v({},r),{userId:e.userId}))}),e.on("firewall-restriction",()=>{this.emit("firewall-restriction")})}startSyncUserListInterval(){this._syncUserListInterval===-1&&(this._syncUserListInterval=ee.run(Li,this.syncUserList.bind(this)))}stopSyncUserListInterval(){ee.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:W.GET_USER_LIST,responseCommand:V.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:d})=>({userId:a,tinyId:c,role:d}));throw w({key:x.SIGNAL_RESPONSE_FAILED,data:{signalResponse:V.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||!al)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)===ne.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach(r=>{if(r instanceof He&&!r.getIsReconnecting()){let o=r.getPeerConnection();o&&o.connectionState===ne.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"),Y.uploadEvent({log:"stat-fallback",userId:this.userId}),this.enableSPC=!1,(e=this.singlePC)==null||e.close(),this.singlePC=null,this.isJoined&&(yield this.reJoin(!1)),this.uplinkConnection){let t=this.uplinkConnection;this.uplinkConnection=new Mo({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 hl({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:S.INVALID_OPERATION,message:w({key:x.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners(),this.healthDetector.destroy(),ee.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:W.SWITCH_ROLE,data:{role:e==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:V.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:S.SWITCH_ROLE_FAILED,message:w({key:x.SWITCH_ROLE_FAILED,data:{message:n,code:o}})});this.role=e}).catch(r=>{throw r instanceof y&&r.getCode()===S.API_CALL_TIMEOUT&&(r=new y({code:S.SWITCH_ROLE_FAILED,message:w({key:x.SWITCH_ROLE_TIMEOUT})})),this._log.error(r),r})}publish(...e){return f(this,null,function*(){let t={},r={};e.forEach(c=>{c instanceof Le&&(c instanceof Kt?r.audio=c:t.audio=c),c instanceof me&&(c instanceof rt&&c.mediaType===2?r.video=c:t.video=c)});let o=Fo(t),n=Fo(r);(!o||!n)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new yl({userId:this.userId,tinyId:this.tinyId,room:this}):this.uplinkConnection=new Mo({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(v({},c),{userId:this.userId}))}),this.uplinkConnection.on("firewall-restriction",()=>{this.emit("firewall-restriction")}),this.uplinkConnection.on("error",c=>{let d=c.getCode();d!==S.ICE_TRANSPORT_ERROR&&(d===S.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 Le&&(o instanceof Kt?r.audio=o:t.audio=o),o instanceof me&&(o instanceof rt&&o.mediaType===2?r.video=o:t.video=o))});try{let o=e.map(n=>n.kind).join(",");Fo(t)||(this._log.info(`unpublish() => main ${o}`),yield this.uplinkConnection.unpublish({localAudioTrack:t.audio,localVideoTrack:t.video})),Fo(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||!xc()?Promise.resolve():this.uplinkConnection.replaceTrack(e).then(t=>{t&&T.emit(g.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:m.VIDEO,videoType:m.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=v({},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),T.emit(g.SUBSCRIBE_START,{room:this,streamType:o,remotePublishedUser:r,subscribeState:n}),this._log.info(`subscribe() => ${t} ${o} [${ba(n)}] prev: [${ba(r.subscribeState)}]`),yield r.subscribe(n,o),this._log.info(`subscribe ${t} ${o} done`);for(let c of e)c.mediaTrack||(yield c.waitHasMediaTrack());T.emit(g.SUBSCRIBE_SUCCESS,{room:this,streamType:o,remotePublishedUser:r})}catch(n){let a=n instanceof y?n.getCode():S.UNKNOWN,c=n;throw n instanceof y?a===S.REMOTE_STREAM_NOT_EXIST&&(c=new y({code:S.API_CALL_ABORTED,message:w({key:x.API_CALL_ABORTED,data:{message:n.message,userId:t,streamType:o}})}),this._log.warn(c)):(c=new y({code:a,message:w({key:x.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)}),T.emit(g.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,ee.clearTask(this._audioVolumeIntervalId);return}e=Math.floor(Math.max(e,100)),T.emit(g.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&ee.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=ee.run(vr,()=>{var o;Xc.isRunning?this.stopUpdateAudioLevelFromSenderStat():this.updateAudioLevelFromSenderStat(e,t);let r=[];(o=this.remotePublishedUserMap)==null||o.forEach(n=>{if(n.muteState.hasAudio){!Xc.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)},{fps:1e3/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=ee.run(vr,()=>f(this,null,function*(){let a=yield r.getStats();this._updateAudioLevelTaskId<0||a.forEach(c=>{c.type==="media-source"&&c.audioLevel&&(this.uplinkConnection.localMainAudioTrack.volume=c.audioLevel)})}),{delay:o,backgroundTask:t})})}stopUpdateAudioLevelFromSenderStat(){var e;this._updateAudioLevelTaskId!==-1&&(this._log.warn("stopUpdateAudioLevelFromSenderStat"),ee.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(!wc||!t)return;let r=(o=t.getSynchronizationSources()[0])==null?void 0:o.audioLevel;r?e.remoteAudioTrack.volume=Math.min(r*2,1):t.getStats().then(n=>{n.forEach(a=>{a.type==="inbound-rtp"&&K(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(Be.getTurnServer(o))):Be.isPlainObject(e)&&r.push(Be.getTurnServer(e)),this._turnServers=r,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:W.START_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:V.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:W.STOP_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:V.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"})}sendStartPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?W.START_PUBLISH_TENCENT_CDN:W.START_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?V.START_PUBLISH_TENCENT_CDN_RES:V.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"})}sendStopPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?W.STOP_PUBLISH_TENCENT_CDN:W.STOP_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?V.STOP_PUBLISH_TENCENT_CDN_RES:V.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}sendStartPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:W.START_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:V.START_PUBLISH_CDN_STREAM_RES,commandDesc:"startPublishCDNStream"})}sendUpdatePushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:W.UPDATE_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:V.UPDATE_PUBLISH_CDN_STREAM_RES,commandDesc:"updatePublishCDNStream"})}sendStopPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:W.STOP_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:V.STOP_PUBLISH_CDN_STREAM_RES,commandDesc:"stopPublishCDNStream"})}sendAbilityStatus(e){var t;(t=this.signalChannel)==null||t.sendWaitForResponse({command:W.ABILITY_STATUS_REPORT,data:e,timeout:5e3,responseCommand:V.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch(r=>{})}getIceServers(){return this._turnServers.length===0&&this.scheduleResult.iceServers?this.scheduleResult.iceServers:this._turnServers}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=Be.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:d}=a;if(c.video&&t.video||c.smallVideo&&t.smallVideo&&o)return;let h={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:c.video,smallVideo:c.smallVideo};try{if(!o&&h.smallVideo&&(h.video=!0,h.smallVideo=!1),h.smallVideo===t.smallVideo&&h.video===t.video)return;a.isSubscribing=!0,a.reSubscribeCount=d-1,yield e.subscribe(h,"main"),e.remoteVideoTrack.setMediaType(h.smallVideo?8:4),this._log.info(`change [${r}] to ${h.smallVideo?"small":"big"} video successfully. count ${br-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount=br}catch(u){this._log.info(`change [${r}] to ${h.smallVideo?"small":"big"} video failed. count ${br-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount===0&&this._changeBigSmallRecords.delete(r)}})}changeType(e,t){let o={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:br};this._changeBigSmallRecords.set(t.userId,o),this._log.info(`set [${t.userId}] video prefer type: ${e?"small":"big"}`)}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(e){this._businessInfo=e.businessInfo;let t={};if(Cm(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!Ts(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new y({code:S.INVALID_PARAMETER,message:w({key:x.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(!Ts(e.userDefineRecordId)){let r=/^[A-Za-z0-9_-]{1,64}$/gi;if(e.userDefineRecordId.match(r)===null)throw new y({code:S.INVALID_PARAMETER,message:w({key:x.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!Ts(e.userDefinePushArgs))if(Cm(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:S.INVALID_PARAMETER,message:w({key:x.INVALID_USER_DEFINE_PUSH_ARGS})});Fo(t)||(this._businessInfo=JSON.stringify(t))}sendCustomMessage(e){var t;(t=this._customMessageManager)==null||t.send(e)}enableInsertableStreams(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&Ti)return this.singlePC.enableInsertableStreams=!0,this.singlePC.startReconnection()}sendSignalMessage(e){var t;return this.signalChannel?(t=this.signalChannel)==null?void 0:t.sendWaitForResponseWithRetry(e):Promise.reject(new y({code:S.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}};b([Sl(["left",ce.INIT],"joined"),je({settings:{retries:1,timeout:0},onRetrying(s){this._log.warn(`join retry ${s}`)},onRetryFailed(s){this._log.error("join failed",s)},onError(s,i){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),$t(!0),this.reset(),i()):this.signalChannel&&this.signalChannel.isConnected&&this.signalChannel.keepAlive?(this._log.warn("is using keepAlive ws, retry join"),this.signalChannel.close(),this.reset(),i()):(this.reset(),i())}}),Oh()],Mt.prototype,"join",1),b([Sl("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),Mh(),qn("leave room"),ho({fnName:"publish",validateArgs:!1}),ho({fnName:"unsubscribe",validateArgs:!1})],Mt.prototype,"leave",1),b([Yt(),Sm(),je({settings:{retries:oi,timeout:s=>Ft(s)},onError(s,i,e){var t;(t=s.message)!=null&&t.includes("timeout")?(this._log.warn("publish timeout"),i()):(this._log.error(`publish failed: ${s}`),e(s),T.emit(g.PUBLISH_FAILED,{room:this}))}})],Mt.prototype,"publish",1),b([ho({fnName:"publish"}),qu("api-call"),Yt(),Im(),bt(function(){var s,i;this.localTracks.size===0&&Hi()&&((i=(s=this.singlePC)==null?void 0:s.getPeerConnection())==null||i.getSenders().forEach(e=>e.track&&e.replaceTrack(null)))})],Mt.prototype,"unpublish",1),b([Ju(s=>{if(s.code!==S.API_CALL_ABORTED)throw s}),Ai(s=>s.userId)],Mt.prototype,"replaceTrack",1),b([Ai((...s)=>s[0].userId),zn(),kh(),je({settings:{retries:oi,timeout:s=>Ft(s)},onError(s,i,e,t){s.message.includes("timeout")?(this._log.warn("subscribe timeout"),i()):(this._log.error(`subscribe failed: ${s}`),e(s),T.emit(g.SUBSCRIBE_FAILED,{room:this,remoteTracks:t}))}})],Mt.prototype,"subscribe",1),b([ho({fnName:"subscribe",callback(...s){this.singlePC||s.forEach(i=>{let e=this.remotePublishedUserMap.get(i.userId);e&&!e.isMainStreamSubscribed&&!e.isAuxStreamSubscribed&&e.close("you unsubscribed")})}}),Ai((...s)=>s[0].userId)],Mt.prototype,"unsubscribe",1);Do.create=Do._create.bind(Do,Mt);var QU=Do;export{QU as default};