trtc-sdk-v5 5.8.2-beta.1 → 5.8.2-beta.2

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
@@ -62,12 +62,12 @@ void main() {
62
62
  `)))}else{if(e instanceof zi)return e;o=new zi({code:w.UNKNOWN_ERROR,fnName:t,originError:e})}return o}};function p_(r){let i;switch(r){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 k=zi;var Rl={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}}},yl={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}}},Fr={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(r,i,e){if(Y(r)&&!document.getElementById(r))throw new k({code:w.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:i}})}},bl={name:"userId",required:!0,type:"string"},Nl={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[st.AUDIO_PROFILE_STANDARD,st.AUDIO_PROFILE_STANDARD_STEREO,st.AUDIO_PROFILE_HIGH,st.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function eo(r,i){if(!r)throw new k({code:w.INVALID_OPERATION,extraCode:5101,fnName:i})}function vl(r,i,e){if(!r)throw new k({code:w.INVALID_OPERATION,extraCode:5102,fnName:i,messageParams:{value:e}})}var qy={type:"number",notLessThanZero:!0},__={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(r,i,e){if(this._room.isJoined)throw new k({code:w.INVALID_OPERATION,extraCode:5104,fnName:e});if(r.roomId){if(Y(r.roomId))throw new k({code:w.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:i}});if(!(/^[1-9]\d*$/.test(String(r.roomId))&&r.roomId<4294967295))throw new k({code:w.INVALID_PARAMETER,extraCode:5013,fnName:e,messageParams:{key:i}})}else if(r.strRoomId){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(r.strRoomId))throw new k({code:w.INVALID_PARAMETER,extraCode:5012,fnName:e,messageParams:{key:i}})}else throw new k({code:w.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:Fr,mute:{type:["boolean","string"]},publish:{type:"boolean"},option:Rl},validate(r){var i;if(!((i=r==null?void 0:r.option)!=null&&i.videoTrack)&&ii())throw new k({code:w.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:P(N({},Fr),{required:!1}),publish:{type:"boolean"},mute:{type:["boolean","string"]},option:Rl}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:Nl},validate(r){var i;if(!((i=r==null?void 0:r.option)!=null&&i.audioTrack)&&ii())throw new k({code:w.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:Nl}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:Fr,publish:{type:"boolean"},option:yl},validate(r,i,e,t,s){var o;if(!((o=r==null?void 0:r.option)!=null&&o.videoTrack)&&ii())throw new k({code:w.ENV_NOT_SUPPORTED,extraCode:5201});if(!Ls())throw new k({code:w.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:Fr,publish:{type:"boolean"},option:yl}},muteRemoteAudio:[bl,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[bl,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:Fr,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(r,i,e){eo(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(r.userId);if(vl(!!t,e,r),t&&(r.streamType==="main"&&!t.muteState.videoAvailable||r.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new k({code:w.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:r}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:P(N({},Fr),{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(r,i,e){eo(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(r.userId);if(vl(!!t,e,r),t&&(r.streamType==="main"&&!t.muteState.videoAvailable||r.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new k({code:w.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:r}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(r,i,e){if(r.userId!=="*"&&T(r.streamType))throw new k({code:w.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(r,i,e){eo(this._room.isJoining||this._room.isJoined,e)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(r,i,e,t){if(!Fi)throw new k({code:w.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new k({code:w.INVALID_OPERATION,fnName:e,extraCode:5108});if(r.byteLength>1e3)throw new k({code:w.INVALID_PARAMETER,extraCode:5018,fnName:e});if(r.byteLength===0)throw new k({code:w.INVALID_PARAMETER,extraCode:5017,messageParams:{key:i},fnName:e});eo(this._room.isJoined,e)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(r,i,e){if(!r&&!this._room.isMainStreamPublished||r&&!this._room.isAuxStreamPublished)throw new k({code:w.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(r,i,e,t){if(r.byteLength>1e3)throw new k({code:w.INVALID_PARAMETER,extraCode:5018,fnName:e});if(r.byteLength===0)throw new k({code:w.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:i}})}}},validate(r,i,e){if(eo(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new k({code:w.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:i}})}}},Ce={TRTC:__};var Me=class extends Error{};function f_(r,i){let e=yr(r);for(let t=0;t<i.length;t++)Kt(e[t],i[t]);return e}function E_(r){this._resolve=Promise.resolve(r)}function g_(r){this._reject=Promise.reject(r)}var Yi=class{constructor(i,e){this.instance=i;this.group=e;this.started=!1;this.ops=[];this.startSame=()=>!0;this.mergeUpdate=f_;let t=Yi.instances.get(i);t?t.set(e,this):Yi.instances.set(i,new Map([[e,this]]))}static get(i,e){if(!e)return;let t=Yi.instances.get(i);return t&&t.get(e)||new Yi(i,e)}static gets(i,e){let t=Yi.instances.get(i),s=[];return t&&t.forEach((o,n)=>{e.test(n)&&s.push(o)}),s}action(i,e,t){let s=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 Me("start failed")),(d=this.currentOp)==null||d.action(),a},n={type:i,action:()=>e(...n.args).then(s,o),args:t,resolve:E_,reject:g_};try{switch(this.state){case 1:if(i===0)throw new Me("already started");break;case 4:if(i===2)throw new Me("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(s,o)}cacheOp(i){if(this.ops.length===1)switch(this.state){case 0:case 2:if(i.type===0)throw new Me("already start");break;case 3:switch(i.type){case 2:throw new Me("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new Me("unknown state")}else switch(i.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let t=new Me("keep stop");if(this.ops.slice(1).forEach(s=>s.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 Me("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new Me("start not allowed after update");case 0:throw new Me("duplicate start");case 3:if(this.startSame(this.currentOp.args,i.args))throw this.ops.pop().reject(new Me("keep start")),new Me("already start")}}i.promise=new Promise((t,s)=>{i._resolve?i._resolve.then(t):i.resolve=t,i._reject?i._reject.catch(s):i.reject=s});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}},Ht=Yi;Ht.instances=new WeakMap;var Fn=new WeakMap,Hn=(r,i)=>{if(i instanceof Me){let{stack:e}=i;i=new k({code:w.OPERATION_ABORT,message:`${r} abort: ${i.message}`,fnName:r}),e&&(i.stack+=e.substr(e.indexOf(`
63
63
  `)))}throw i};function Di(r,i){return J((e,t)=>function(...s){let o=Ht.get(this,typeof r=="string"?r:r.call(this,...s));return o?(i&&(o.startSame=i.bind(this)),o.action(0,e.bind(this),s).catch(Hn.bind(null,t))):e.apply(this,s)})}function Ki(r,i){let{merge:e,debounce:t}=i||{};return J((s,o)=>function(...n){let a=Ht.get(this,typeof r=="string"?r:r.call(this,...n));if(!a)return s.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((l,p)=>{var R,C;let m=(R=Fn.get(this))==null?void 0:R.get(d(...n));if(m){let{timeoutId:v,resolve:U}=m;clearTimeout(v),U()}let f=setTimeout(()=>{if(a.state===3||a.state===4)return l();a.action(2,s.bind(this),n).catch(Hn.bind(null,o)).then(l,p)},c);Fn.has(this)?(C=Fn.get(this))==null||C.set(d(...n),{timeoutId:f,resolve:l}):Fn.set(this,new Map([[d(...n),{timeoutId:f,resolve:l}]]))})}return a.action(2,s.bind(this),n).catch(Hn.bind(null,o))})}function Oi(r){return J((i,e)=>function(...t){let s=typeof r=="function"?r.call(this,...t):r;if(s instanceof RegExp)return Promise.all(Ht.gets(this,s).map(n=>n.action(3,()=>Promise.resolve(),t))).then(()=>i.call(this,...t));let o=Ht.get(this,s);return o?o.action(3,i.bind(this),t).catch(Hn.bind(null,e)):i.apply(this,t)})}var $={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",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"};function Zi(r){return r==="sub"?"auxiliary":r==="auxiliary"?"sub":"main"}function er(r){return r===st.QOS_PREFERENCE_CLEAR?"detail":r===st.QOS_PREFERENCE_SMOOTH?"motion":""}var T_=r=>r.startsWith("data:application/octet-stream;base64,"),S_=r=>r.startsWith("file://"),Gn=class{constructor(){u(this,"_log");this._log=I.createLogger({id:"fd"})}download(i,e){return _(this,null,function*(){let{type:t="blob"}=e||{};try{let s=x(),o;if(W(fetch)?o=yield this.downloadWithFetch(i,t):o=yield this.downloadWithXHR(i,t),!o||!o.data)throw new Error("data is empty");let n=x()-s;return this._log.info(`downloaded: ${i}, return type: ${t}, cost: ${n}ms`),D.addSuccessEvent({key:522700,cost:x()-s}),o.data}catch(s){throw this._log.error(`failed to download: ${i}, error: ${s}`),D.addFailedEvent({key:522700,error:s}),s}})}downloadWithFetch(i,e){return _(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 s;return e==="arraybuffer"?s=yield t.arrayBuffer():s=yield t.blob(),{data:s}}catch(t){throw t}})}downloadWithXHR(i,e){return this._log.info(`download with xhr: ${i}, return type: ${e}`),new Promise((t,s)=>{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}):s(new Error("XHR failed"))},o.onerror=s,o.send(null)})}loadWasm(i,e){return _(this,null,function*(){this._log.info(`loadWasm ${i}, importObject: ${JSON.stringify(e)}`);let t=x(),s=null,o=null;if(W(WebAssembly.instantiateStreaming)&&!T_(i)&&!S_(i)&&W(fetch))try{let n=fetch(i);s=(yield WebAssembly.instantiateStreaming(n,e)).instance}catch(n){o=n}if(!s)try{let n=yield this.download(i,{type:"arraybuffer"});s=(yield WebAssembly.instantiate(n,e)).instance}catch(n){o=n}if(s){let n=x()-t;return this._log.info(`loadedWasm ${i}, cost: ${n}ms`),D.addSuccessEvent({key:522701,cost:n}),s}throw this._log.error(`failed to loadWasm ${i}, error: ${o}`),D.addFailedEvent({key:522701,error:o}),o})}};y([it({settings:{timeout:0,retries:3},onRetrying(r){this._log.warn(`download retrying: ${r}`)}})],Gn.prototype,"download",1);var Dl=new Gn;function Ol({TRTC:r,room:i,errorModule:e,assetsPath:t}){return{TRTC:r,room:i,assetsPath:t,fileDownloader:Dl,innerEmitter:g,constants:Ra,environment:Ar,utils:we,eventLogger:Z,log:this.room.getLogger(),loggerManager:I,errorModule:e,kvStatManager:D,rtcDectection:ft,trtc:this,clearStarted:(s,o)=>{let n=s.getAlias(),a=Ht.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)})}}}var Ml=(r,i)=>{let{emit:e}=r;return r.emit=(...t)=>{try{return e.apply(r,t)}catch(s){let o=L({key:M.CATCH_HANDLER_ERROR,data:{name:i,event:t[0]},addDocLink:!1});return I.warn(`${o}
64
64
 
65
- ${s.stack}`),!1}},r};var Wn=new WeakMap;function kl(r,i){return J((e,t)=>function(...s){var a,c;let o=(a=Wn.get(this))==null?void 0:a.get(i(...s));o&&o>0&&clearTimeout(o);let n=window.setTimeout(()=>{e.apply(this,s)},r);Wn.has(this)?(c=Wn.get(this))==null||c.set(i(...s),n):Wn.set(this,new Map([[i(...s),n]]))})}var Ll="5.8.2-beta.1";function ke(...r){return J((i,e)=>function(...t){try{jn.call(this,r,t,e,this._name)}catch(s){return Promise.reject(s)}return i.apply(this,t)})}function dd(...r){return J((i,e)=>function(...t){try{jn.call(this,r,t,e,this._name)}catch(s){throw s}return i.apply(this,t)})}function jn(r,i,e,t){if(he(r))for(let s=0;s<r.length;s++)Jn.call(this,{rule:r[s],value:i[s],key:r[s].name,fnName:e,className:t});else Jn.call(this,{rule:r,value:i[0],key:r.name,fnName:e,className:t})}function Jn({rule:r,value:i,key:e,fnName:t,className:s}){function o(c){return{code:w.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:r,value:i}}}if(T(i)){if(r.required)throw new k(o(5001));if(T(r.defaultValue)){W(r.validate)&&r.validate.call(this,i,e,t,s,this);return}i=r.defaultValue}if(Array.isArray(r.type)){let c=!1;for(let d=0;d<r.type.length;d++)r.type[d]===null&&i===null&&(c=!0),W(r.type[d])&&i instanceof r.type[d]&&(c=!0),Y(r.type[d])&&fe(i)===r.type[d].toLowerCase()&&(c=!0);if(!c)throw new k({code:w.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:r.type.map(d=>Ns(d)?zo(d):Y(d)?d:fe(d))},value:i}})}else if(!T(r.type)&&fe(i)!==r.type)throw new k(o(5002));if(r.allowEmpty===!1){let c=ee(i)&&(i===0||Number.isNaN(i)),d=Y(i)&&i.trim()==="";if(c||d)throw new k(o(5003))}if(r.notLessThanZero&&ee(i)&&i<0)throw new k(o(5006));if(!T(r.min)&&ee(i)&&i<r.min)throw new k(o(5007));if(!T(r.max)&&ee(i)&&i>r.max)throw new k(o(5008));if(Y(r.instanceOf)){if(!i||i._name!==r.instanceOf)throw new k(o(5004))}else if(W(r.instanceOf)&&!(i instanceof r.instanceOf))throw new k(o(5004));if(Array.isArray(r.values)&&!r.values.includes(i))throw new k(o(5005));let{properties:n}=r;Je(n)&&mt(i)&&Object.keys(n).forEach(c=>{Jn.call(this,{rule:n[c],value:i&&i[c],key:`${c}`,fnName:t,className:s})});let{arrayItem:a}=r;Je(a)&&he(i)&&i.forEach((c,d)=>{Jn.call(this,{rule:a,value:c,key:`${e}[${d}]`,fnName:t,className:s})}),W(r.validate)&&r.validate.call(this,i,e,t,s,this)}function oe(r={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t}=r;return J((s,o)=>function(...n){function a(l,p,m){if(m&&m.includes(l))return"hided";if(e){let f=e(...n);if(n[f.argIndex]===p)return f.value}if(p===n||l in n)return p;try{return p instanceof HTMLElement?`id: ${p.id} type:${fe(p)}`:(JSON.stringify(p),p)}catch(f){return`type:${fe(p)}`}}let c=this._log||I;n.length>0?c.info(`${o}() ${JSON.stringify(n,(l,p)=>a(l,p,["userSig","privateMapKey"]))}`):c.info(`${o}()`);let d=t?t(...n):un[o];try{let l=s.apply(this,n),p=x();return bs(l)?l.then(m=>(c.info(`${o}() success ${i.call(this,...n)}`),D.addSuccessEvent({key:d,cost:x()-p}),m)).catch(m=>{throw m=k.convertFrom.call(this,m,o,n.length===1?n[0]:n),c.error(`${o}() failed ${i.call(this,...n)} ${m} params: ${JSON.stringify(n,a)}`),D.addFailedEvent({key:d,error:m}),m}):(D.addSuccessEvent({key:d}),l)}catch(l){throw l=k.convertFrom.call(this,l,o),c.error(`${o}() failed ${l} params: ${JSON.stringify(n,a)}`),D.addFailedEvent({key:d,error:l}),l}})}var qn=r=>J((i,e)=>function(t,s){return _(this,null,function*(){let o=this._plugins.get(t);if(!o)throw this._log.error(`plugin ${String(t)} is not found`),new k({code:w.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});if(W(o.constructor.isSupported)&&!o.constructor.isSupported())throw this._log.error(`plugin ${String(t)} is not supported`),new k({code:w.ENV_NOT_SUPPORTED,message:`plugin ${String(t)} is not supported`,extraCode:5210,fnName:e});return jn.call(this,o.getValidateRule(r),[s],e,"TRTC"),i.call(this,o,s)})});var Xn=0,ud=class{constructor(i,e){u(this,"player");u(this,"publisher");u(this,"mixInput");this.mixInput=new kr(e),i.url?(this.player=new Audio(i.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(i.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(i.track),this.mixInput.connect()}updateSettings(i){!this.player||(T(i.volume)||(this.volume=i.volume),T(i.loop)||(this.loop=i.loop),T(i.playbackRate)||(this.playbackRate=i.playbackRate))}updateListener(i){if(!!this.player){if(i.onDurationChange){let{onDurationChange:e}=i;this.player.ondurationchange=t=>{e(t.target.duration)}}if(i.onTimeUpdate){let e=i.onTimeUpdate,{player:t}=this;t.ontimeupdate=()=>{e(t.currentTime,t.duration)}}i.onEnded&&(this.player.onended=i.onEnded)}}reset(){this.seek(0),this.mixInput.connect()}seek(i){!this.player||i<0&&i>this.player.duration||(this.player.currentTime=i,this.publisher.currentTime=i)}play(){var i,e;return(i=this.publisher)==null||i.play(),(e=this.player)==null?void 0:e.play()}pause(){var i,e;(i=this.player)==null||i.pause(),(e=this.publisher)==null||e.pause()}stop(){var i;(i=this.player)==null||i.pause(),this.mixInput.disconnect()}setOperation(i){i==="pause"&&this.pause(),i==="resume"&&(this.pause(),this.play()),i==="stop"&&(this.pause(),this.seek(0))}set volume(i){!this.player||!this.publisher||(this.player.volume=i,this.publisher.volume=i)}set loop(i){!this.player||!this.publisher||(this.player.loop=i,this.publisher.loop=i)}set playbackRate(i){!this.player||!this.publisher||(this.player.playbackRate=i,this.publisher.playbackRate=i)}};function Hr(r,i){if(i&&typeof i!="function")throw new k({code:w.INVALID_PARAMETER,message:`start audioMixer plugin: param ${r} should be a function.`})}var Gr=class{constructor(i){this.core=i;u(this,"log");u(this,"mixedMusicMap",new Map);u(this,"cacheMusicMap",new Map);Xn=Xn+1,this.log=i.log.createChild({id:`${this.getAlias()}${Xn}`}),this.log.info(`[audioMixer] created id=${this.getAlias()}${Xn}`),this.core=i}getName(){return Gr.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return Gr.startValidateRule;case"update":return Gr.updateValidateRule;case"stop":return Gr.stopValidateRule}}start(i){return _(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:s}=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 ud(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.`),D.addEnum({key:502700,value:3}),this.kvUpload(i)})}update(i){return _(this,null,function*(){let{id:e,operation:t,seekFrom:s,playbackRate:o}=i;this.log.info(`update music source, ${JSON.stringify(i)}`);let n=this.mixedMusicMap.get(e);if(!n){this.log.warn(`update music source failed, music id: ${e} not found.`);return}n.updateSettings(i),n.updateListener(i),T(t)||n.setOperation(t),T(s)||n.seek(s),this.kvUpload(i)})}stop(e){return _(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:s,playbackRate:o,operation:n,seekFrom:a,onTimeUpdate:c,onDurationChange:d,onEnded:l}=i;e&&D.addCount({key:502711}),t&&D.addCount({key:502703}),s&&D.addCount({key:502704}),o&&D.addCount({key:502705}),n&&D.addCount({key:502706}),a&&D.addCount({key:502707}),typeof c!="function"&&D.addCount({key:502709}),typeof l!="function"&&D.addCount({key:502710}),typeof d!="function"&&D.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()}},Mi=Gr;u(Mi,"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 s=i.url.split("?")[0],o=["mp3","ogg","wav","flac"],n=s.split(".").pop(),a=o.indexOf(n)>=0,c=s.startsWith("blob"),d=s.startsWith("data");if(!(a||c||d))throw new k({code:w.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new k({code:w.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});Hr("onTimeUpdate",i.onTimeUpdate),Hr("onEnded",i.onEnded),Hr("onDurationChange",i.onDurationChange)}}),u(Mi,"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){Hr("onTimeUpdate",i.onTimeUpdate),Hr("onEnded",i.onEnded),Hr("onDurationChange",i.onDurationChange)}}),u(Mi,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),u(Mi,"Name","AudioMixer");var A_=r=>(r=Number(r),r>0&&r<14e8),Qn=0,ld,Wr=class{constructor(i){this.core=i;u(this,"log");u(this,"audioContext",qe("denoiser"));u(this,"workletNode");Qn=Qn+1,this.log=i.log.createChild({id:`${this.getAlias()}${Qn}`}),this.log.info(`[audioDenoiser] created id=${this.getAlias()}${Qn}`),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,s,o){if(!i.room.audioManager.hasAudioTrack)throw new k({code:w.INVALID_OPERATION,extraCode:5106,fnName:s})}}}preload(i){return ld||(ld=this.doPreload(i)),ld}doPreload(i){return _(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield Gi(this.audioContext,t)}finally{URL.revokeObjectURL(t)}})}getName(){return Wr.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(i){switch(i){case"start":return Wr.startValidateRule(this.core);case"update":return Wr.updateValidateRule;case"stop":return Wr.stopValidateRule}}start(i){return _(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:s,sign:o,status:n,message:a}=yield R_(P(N({},i),{timestamp:t}));if(!s)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${s}. Message: ${a}`),new k({code:w.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 _(this,null,function*(){})}stop(){return _(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(){}},tr=Wr;u(tr,"updateValidateRule",{type:"object"}),u(tr,"stopValidateRule",{type:"object"}),u(tr,"Name","AIDenoiser");var xl={MAIN:"schedule.cloud-rtc.com",MAIN_OVERSEA:"schedule.rtc.tencentcloud.com"};function C_(r){let i;return A_(r)?i=xl.MAIN_OVERSEA:i=xl.MAIN,i}function R_(s){return _(this,arguments,function*({sdkAppId:r,userId:i,userSig:e,timestamp:t}){let n=`https://${C_(r)}/api/v1/audioAiAuth?sdkAppId=${r}&userId=${i}&userSig=${e}&timestamp=${t}`,a=yield fetch(n),{data:{errCode:c,errMsg:d,sign:l,status:p}}=yield a.json();if(p==="1")return{auth:!0,sign:l,status:p,message:d};let m="Init RTCAIDenoiser failed.",f="";switch(c){case 1:f="Please check your params.";break;case 2:f="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:f="Server is invalid. Please contact our engineer. ";break;case 4:f="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:f="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:f="Your version is not supported.";break}return{auth:!1,status:p,message:d?`${m} Reason: ${d}. ${f}`:`${m}, ${f}`}})}var Pl=Se(Ne(),1);var hd=class extends Pl.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 _(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!pe&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){Z.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let t=this.stateNum,s=e[e.length-1];this.state=s.state,(this.stateNum>3||t>3)&&I.info(`${s.source}: ${s.state}`),this.emit("state-changed",{type:s.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(t){Z.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},y_=new hd,md=y_;var pd=0,Ed=class{constructor(i){this.core=i;u(this,"log");u(this,"_seiMessageList",[]);u(this,"_smallSeiMessageList",[]);u(this,"_subStreamSeiMessageList",[]);u(this,"_seiWorker");pd++,this.log=i.log.createChild({id:`${this.getAlias()}${pd}`}),this.log.info(`[sei] created id=${this.getAlias()}${pd}`),this.core=i}encode(i,e){try{let t=e===8?this._smallSeiMessageList:e===2?this._subStreamSeiMessageList:this._seiMessageList,s=_d(i,t);s&&this.log.debug(`${s} sei sent`)}catch(t){this.log.warn(t)}return i}decode(i,e){return fd(i).forEach(t=>{this.core.trtc.emit($.SEI_MESSAGE,{seiPayloadType:t.seiPayloadType,data:t.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"})}),i}destroy(){}getValidateRule(i){switch(i){case"start":return{type:"object"};case"update":return{type:"object"};case"stop":return{type:"object"}}}start(i){yi?(this._seiWorker=b_(),this._seiWorker.onmessage=e=>{this.core.trtc.emit($.SEI_MESSAGE,P(N({},e.data),{streamType:Zi(e.data.streamType)}))},this._seiWorker.onerror=e=>{this.log.error("seiWorker error: ",e.message)},this.core.room.videoManager.enableSEI({seiWorker:this._seiWorker})):this.core.room.videoManager.enableSEI({encoder:this.encode.bind(this),decoder:this.decode.bind(this)})}stop(i){this.core.room.videoManager.disableSEI()}update({buffer:i,options:e}){var o;let t=[e.seiPayloadType,i],s=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(t):(this._seiMessageList.push(t),s&&this._smallSeiMessageList.push(t)),this.core.innerEmitter.emit("265",{room:this.core.room,data:t,isMain:!e.toSubStream}),(o=this._seiWorker)==null||o.postMessage({message:t,isMain:!e.toSubStream,small:s})}getName(){return Ed.Name}getAlias(){return"sei"}getGroup(){return"sei"}},to=Ed;u(to,"Name","SEI");function Ul([r,i]){let e=i.byteLength,t=parseInt(String(e/255),10),s=e%255,o=[];o.push(0,0,0,1,6,r);for(let a=0;a<t;a++)o.push(255);o.push(s);let n=new DataView(i);return o.push(...new Uint8Array(n.buffer)),o.push(128),new Ni(new DataView(new Uint8Array(o).buffer),!0)}function Bl(r){return r.type==="empty"||r.data.byteLength===0}function $l(r){return r.getInt32(0)===1&&r.getInt8(4)===6}function Fl(r){let i=0,e=0,t=new DataView(r);for(let s=0;s<r.byteLength;s++)switch(t.getUint8(s)){case 0:i++;break;case 1:(i===2||i===3)&&e++,i=0;break;default:i=0;break}return e}function _d(r,i){if(i.length>0&&r.data.byteLength>0){let e=Fl(r.data),t=9-e;if(t<=0)return 0;let s=i.splice(0,t).reverse().map(Ul),o=s.reduce((l,p)=>l+p.dataView.byteLength,0),n=new ArrayBuffer(o+r.data.byteLength),a=new DataView(n),c=new DataView(r.data),d=0;for(let l=0;l<s.length;l++)for(let p=0;p<s[l].dataView.byteLength;p++)a.setInt8(d++,s[l].dataView.getInt8(p));for(let l=0;l<r.data.byteLength;l++)a.setInt8(d++,c.getInt8(l));return r.data=n,s.length}return 0}function fd(r){try{let i=new DataView(r.data);if(Bl(r)||!$l(i))return[];let e=[],t=0,s=-1,o=-1;for(let n=0;n<r.data.byteLength;n++){let a=i.getUint8(n);if(a===0)t++;else if(a===1){if(t===2||t===3){let c=n-t;if(s===-1?s=c:o===-1&&(o=c,e.push(new Ni(new DataView(i.buffer.slice(s,o)))),s=c,o=-1),!(i.getUint8(n+1)===6)){r.data=i.buffer.slice(c);break}}t=0}else t=0}return e.reverse()}catch(i){return[]}}function wl(r){return new TransformStream({transform(i,e){_d(i,r),e.enqueue(i)}})}function Vl(r,i){return new TransformStream({transform(e,t){fd(e).forEach(s=>{self.postMessage({seiPayloadType:s.seiPayloadType,data:s.seiPayload.buffer,userId:r,streamType:i})}),t.enqueue(e)}})}function b_(){let r=[Ni],i=[Fl,Bl,$l,Ul,_d,fd,wl,Vl],e=()=>{let a=[],c=[],d=[];self.onmessage=l=>{l.data.isMain?(a.push(l.data.message),l.data.small&&d.push(l.data.message)):c.push(l.data.message)},self.onrtctransform=l=>{let{options:p}=l.transformer,m=p.isReceiver?Vl(p.userId,p.streamType):wl(p.isMain?p.small?d:a:c);l.transformer.readable.pipeThrough(m).pipeTo(l.transformer.writable)}},t=`(()=>{${r.map(a=>`const ${a.name}=(()=>${a.toString()})()`).join(`
65
+ ${s.stack}`),!1}},r};var Wn=new WeakMap;function kl(r,i){return J((e,t)=>function(...s){var a,c;let o=(a=Wn.get(this))==null?void 0:a.get(i(...s));o&&o>0&&clearTimeout(o);let n=window.setTimeout(()=>{e.apply(this,s)},r);Wn.has(this)?(c=Wn.get(this))==null||c.set(i(...s),n):Wn.set(this,new Map([[i(...s),n]]))})}var Ll="5.8.2-beta.2";function ke(...r){return J((i,e)=>function(...t){try{jn.call(this,r,t,e,this._name)}catch(s){return Promise.reject(s)}return i.apply(this,t)})}function dd(...r){return J((i,e)=>function(...t){try{jn.call(this,r,t,e,this._name)}catch(s){throw s}return i.apply(this,t)})}function jn(r,i,e,t){if(he(r))for(let s=0;s<r.length;s++)Jn.call(this,{rule:r[s],value:i[s],key:r[s].name,fnName:e,className:t});else Jn.call(this,{rule:r,value:i[0],key:r.name,fnName:e,className:t})}function Jn({rule:r,value:i,key:e,fnName:t,className:s}){function o(c){return{code:w.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:r,value:i}}}if(T(i)){if(r.required)throw new k(o(5001));if(T(r.defaultValue)){W(r.validate)&&r.validate.call(this,i,e,t,s,this);return}i=r.defaultValue}if(Array.isArray(r.type)){let c=!1;for(let d=0;d<r.type.length;d++)r.type[d]===null&&i===null&&(c=!0),W(r.type[d])&&i instanceof r.type[d]&&(c=!0),Y(r.type[d])&&fe(i)===r.type[d].toLowerCase()&&(c=!0);if(!c)throw new k({code:w.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:r.type.map(d=>Ns(d)?zo(d):Y(d)?d:fe(d))},value:i}})}else if(!T(r.type)&&fe(i)!==r.type)throw new k(o(5002));if(r.allowEmpty===!1){let c=ee(i)&&(i===0||Number.isNaN(i)),d=Y(i)&&i.trim()==="";if(c||d)throw new k(o(5003))}if(r.notLessThanZero&&ee(i)&&i<0)throw new k(o(5006));if(!T(r.min)&&ee(i)&&i<r.min)throw new k(o(5007));if(!T(r.max)&&ee(i)&&i>r.max)throw new k(o(5008));if(Y(r.instanceOf)){if(!i||i._name!==r.instanceOf)throw new k(o(5004))}else if(W(r.instanceOf)&&!(i instanceof r.instanceOf))throw new k(o(5004));if(Array.isArray(r.values)&&!r.values.includes(i))throw new k(o(5005));let{properties:n}=r;Je(n)&&mt(i)&&Object.keys(n).forEach(c=>{Jn.call(this,{rule:n[c],value:i&&i[c],key:`${c}`,fnName:t,className:s})});let{arrayItem:a}=r;Je(a)&&he(i)&&i.forEach((c,d)=>{Jn.call(this,{rule:a,value:c,key:`${e}[${d}]`,fnName:t,className:s})}),W(r.validate)&&r.validate.call(this,i,e,t,s,this)}function oe(r={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t}=r;return J((s,o)=>function(...n){function a(l,p,m){if(m&&m.includes(l))return"hided";if(e){let f=e(...n);if(n[f.argIndex]===p)return f.value}if(p===n||l in n)return p;try{return p instanceof HTMLElement?`id: ${p.id} type:${fe(p)}`:(JSON.stringify(p),p)}catch(f){return`type:${fe(p)}`}}let c=this._log||I;n.length>0?c.info(`${o}() ${JSON.stringify(n,(l,p)=>a(l,p,["userSig","privateMapKey"]))}`):c.info(`${o}()`);let d=t?t(...n):un[o];try{let l=s.apply(this,n),p=x();return bs(l)?l.then(m=>(c.info(`${o}() success ${i.call(this,...n)}`),D.addSuccessEvent({key:d,cost:x()-p}),m)).catch(m=>{throw m=k.convertFrom.call(this,m,o,n.length===1?n[0]:n),c.error(`${o}() failed ${i.call(this,...n)} ${m} params: ${JSON.stringify(n,a)}`),D.addFailedEvent({key:d,error:m}),m}):(D.addSuccessEvent({key:d}),l)}catch(l){throw l=k.convertFrom.call(this,l,o),c.error(`${o}() failed ${l} params: ${JSON.stringify(n,a)}`),D.addFailedEvent({key:d,error:l}),l}})}var qn=r=>J((i,e)=>function(t,s){return _(this,null,function*(){let o=this._plugins.get(t);if(!o)throw this._log.error(`plugin ${String(t)} is not found`),new k({code:w.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});if(W(o.constructor.isSupported)&&!o.constructor.isSupported())throw this._log.error(`plugin ${String(t)} is not supported`),new k({code:w.ENV_NOT_SUPPORTED,message:`plugin ${String(t)} is not supported`,extraCode:5210,fnName:e});return jn.call(this,o.getValidateRule(r),[s],e,"TRTC"),i.call(this,o,s)})});var Xn=0,ud=class{constructor(i,e){u(this,"player");u(this,"publisher");u(this,"mixInput");this.mixInput=new kr(e),i.url?(this.player=new Audio(i.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(i.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(i.track),this.mixInput.connect()}updateSettings(i){!this.player||(T(i.volume)||(this.volume=i.volume),T(i.loop)||(this.loop=i.loop),T(i.playbackRate)||(this.playbackRate=i.playbackRate))}updateListener(i){if(!!this.player){if(i.onDurationChange){let{onDurationChange:e}=i;this.player.ondurationchange=t=>{e(t.target.duration)}}if(i.onTimeUpdate){let e=i.onTimeUpdate,{player:t}=this;t.ontimeupdate=()=>{e(t.currentTime,t.duration)}}i.onEnded&&(this.player.onended=i.onEnded)}}reset(){this.seek(0),this.mixInput.connect()}seek(i){!this.player||i<0&&i>this.player.duration||(this.player.currentTime=i,this.publisher.currentTime=i)}play(){var i,e;return(i=this.publisher)==null||i.play(),(e=this.player)==null?void 0:e.play()}pause(){var i,e;(i=this.player)==null||i.pause(),(e=this.publisher)==null||e.pause()}stop(){var i;(i=this.player)==null||i.pause(),this.mixInput.disconnect()}setOperation(i){i==="pause"&&this.pause(),i==="resume"&&(this.pause(),this.play()),i==="stop"&&(this.pause(),this.seek(0))}set volume(i){!this.player||!this.publisher||(this.player.volume=i,this.publisher.volume=i)}set loop(i){!this.player||!this.publisher||(this.player.loop=i,this.publisher.loop=i)}set playbackRate(i){!this.player||!this.publisher||(this.player.playbackRate=i,this.publisher.playbackRate=i)}};function Hr(r,i){if(i&&typeof i!="function")throw new k({code:w.INVALID_PARAMETER,message:`start audioMixer plugin: param ${r} should be a function.`})}var Gr=class{constructor(i){this.core=i;u(this,"log");u(this,"mixedMusicMap",new Map);u(this,"cacheMusicMap",new Map);Xn=Xn+1,this.log=i.log.createChild({id:`${this.getAlias()}${Xn}`}),this.log.info(`[audioMixer] created id=${this.getAlias()}${Xn}`),this.core=i}getName(){return Gr.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return Gr.startValidateRule;case"update":return Gr.updateValidateRule;case"stop":return Gr.stopValidateRule}}start(i){return _(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:s}=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 ud(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.`),D.addEnum({key:502700,value:3}),this.kvUpload(i)})}update(i){return _(this,null,function*(){let{id:e,operation:t,seekFrom:s,playbackRate:o}=i;this.log.info(`update music source, ${JSON.stringify(i)}`);let n=this.mixedMusicMap.get(e);if(!n){this.log.warn(`update music source failed, music id: ${e} not found.`);return}n.updateSettings(i),n.updateListener(i),T(t)||n.setOperation(t),T(s)||n.seek(s),this.kvUpload(i)})}stop(e){return _(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:s,playbackRate:o,operation:n,seekFrom:a,onTimeUpdate:c,onDurationChange:d,onEnded:l}=i;e&&D.addCount({key:502711}),t&&D.addCount({key:502703}),s&&D.addCount({key:502704}),o&&D.addCount({key:502705}),n&&D.addCount({key:502706}),a&&D.addCount({key:502707}),typeof c!="function"&&D.addCount({key:502709}),typeof l!="function"&&D.addCount({key:502710}),typeof d!="function"&&D.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()}},Mi=Gr;u(Mi,"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 s=i.url.split("?")[0],o=["mp3","ogg","wav","flac"],n=s.split(".").pop(),a=o.indexOf(n)>=0,c=s.startsWith("blob"),d=s.startsWith("data");if(!(a||c||d))throw new k({code:w.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new k({code:w.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});Hr("onTimeUpdate",i.onTimeUpdate),Hr("onEnded",i.onEnded),Hr("onDurationChange",i.onDurationChange)}}),u(Mi,"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){Hr("onTimeUpdate",i.onTimeUpdate),Hr("onEnded",i.onEnded),Hr("onDurationChange",i.onDurationChange)}}),u(Mi,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),u(Mi,"Name","AudioMixer");var A_=r=>(r=Number(r),r>0&&r<14e8),Qn=0,ld,Wr=class{constructor(i){this.core=i;u(this,"log");u(this,"audioContext",qe("denoiser"));u(this,"workletNode");Qn=Qn+1,this.log=i.log.createChild({id:`${this.getAlias()}${Qn}`}),this.log.info(`[audioDenoiser] created id=${this.getAlias()}${Qn}`),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,s,o){if(!i.room.audioManager.hasAudioTrack)throw new k({code:w.INVALID_OPERATION,extraCode:5106,fnName:s})}}}preload(i){return ld||(ld=this.doPreload(i)),ld}doPreload(i){return _(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield Gi(this.audioContext,t)}finally{URL.revokeObjectURL(t)}})}getName(){return Wr.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(i){switch(i){case"start":return Wr.startValidateRule(this.core);case"update":return Wr.updateValidateRule;case"stop":return Wr.stopValidateRule}}start(i){return _(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:s,sign:o,status:n,message:a}=yield R_(P(N({},i),{timestamp:t}));if(!s)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${s}. Message: ${a}`),new k({code:w.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 _(this,null,function*(){})}stop(){return _(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(){}},tr=Wr;u(tr,"updateValidateRule",{type:"object"}),u(tr,"stopValidateRule",{type:"object"}),u(tr,"Name","AIDenoiser");var xl={MAIN:"schedule.cloud-rtc.com",MAIN_OVERSEA:"schedule.rtc.tencentcloud.com"};function C_(r){let i;return A_(r)?i=xl.MAIN_OVERSEA:i=xl.MAIN,i}function R_(s){return _(this,arguments,function*({sdkAppId:r,userId:i,userSig:e,timestamp:t}){let n=`https://${C_(r)}/api/v1/audioAiAuth?sdkAppId=${r}&userId=${i}&userSig=${e}&timestamp=${t}`,a=yield fetch(n),{data:{errCode:c,errMsg:d,sign:l,status:p}}=yield a.json();if(p==="1")return{auth:!0,sign:l,status:p,message:d};let m="Init RTCAIDenoiser failed.",f="";switch(c){case 1:f="Please check your params.";break;case 2:f="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:f="Server is invalid. Please contact our engineer. ";break;case 4:f="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:f="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:f="Your version is not supported.";break}return{auth:!1,status:p,message:d?`${m} Reason: ${d}. ${f}`:`${m}, ${f}`}})}var Pl=Se(Ne(),1);var hd=class extends Pl.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 _(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!pe&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){Z.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let t=this.stateNum,s=e[e.length-1];this.state=s.state,(this.stateNum>3||t>3)&&I.info(`${s.source}: ${s.state}`),this.emit("state-changed",{type:s.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(t){Z.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},y_=new hd,md=y_;var pd=0,Ed=class{constructor(i){this.core=i;u(this,"log");u(this,"_seiMessageList",[]);u(this,"_smallSeiMessageList",[]);u(this,"_subStreamSeiMessageList",[]);u(this,"_seiWorker");pd++,this.log=i.log.createChild({id:`${this.getAlias()}${pd}`}),this.log.info(`[sei] created id=${this.getAlias()}${pd}`),this.core=i}encode(i,e){try{let t=e===8?this._smallSeiMessageList:e===2?this._subStreamSeiMessageList:this._seiMessageList,s=_d(i,t);s&&this.log.debug(`${s} sei sent`)}catch(t){this.log.warn(t)}return i}decode(i,e){return fd(i).forEach(t=>{this.core.trtc.emit($.SEI_MESSAGE,{seiPayloadType:t.seiPayloadType,data:t.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"})}),i}destroy(){}getValidateRule(i){switch(i){case"start":return{type:"object"};case"update":return{type:"object"};case"stop":return{type:"object"}}}start(i){yi?(this._seiWorker=b_(),this._seiWorker.onmessage=e=>{this.core.trtc.emit($.SEI_MESSAGE,P(N({},e.data),{streamType:Zi(e.data.streamType)}))},this._seiWorker.onerror=e=>{this.log.error("seiWorker error: ",e.message)},this.core.room.videoManager.enableSEI({seiWorker:this._seiWorker})):this.core.room.videoManager.enableSEI({encoder:this.encode.bind(this),decoder:this.decode.bind(this)})}stop(i){this.core.room.videoManager.disableSEI()}update({buffer:i,options:e}){var o;let t=[e.seiPayloadType,i],s=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(t):(this._seiMessageList.push(t),s&&this._smallSeiMessageList.push(t)),this.core.innerEmitter.emit("265",{room:this.core.room,data:t,isMain:!e.toSubStream}),(o=this._seiWorker)==null||o.postMessage({message:t,isMain:!e.toSubStream,small:s})}getName(){return Ed.Name}getAlias(){return"sei"}getGroup(){return"sei"}},to=Ed;u(to,"Name","SEI");function Ul([r,i]){let e=i.byteLength,t=parseInt(String(e/255),10),s=e%255,o=[];o.push(0,0,0,1,6,r);for(let a=0;a<t;a++)o.push(255);o.push(s);let n=new DataView(i);return o.push(...new Uint8Array(n.buffer)),o.push(128),new Ni(new DataView(new Uint8Array(o).buffer),!0)}function Bl(r){return r.type==="empty"||r.data.byteLength===0}function $l(r){return r.getInt32(0)===1&&r.getInt8(4)===6}function Fl(r){let i=0,e=0,t=new DataView(r);for(let s=0;s<r.byteLength;s++)switch(t.getUint8(s)){case 0:i++;break;case 1:(i===2||i===3)&&e++,i=0;break;default:i=0;break}return e}function _d(r,i){if(i.length>0&&r.data.byteLength>0){let e=Fl(r.data),t=9-e;if(t<=0)return 0;let s=i.splice(0,t).reverse().map(Ul),o=s.reduce((l,p)=>l+p.dataView.byteLength,0),n=new ArrayBuffer(o+r.data.byteLength),a=new DataView(n),c=new DataView(r.data),d=0;for(let l=0;l<s.length;l++)for(let p=0;p<s[l].dataView.byteLength;p++)a.setInt8(d++,s[l].dataView.getInt8(p));for(let l=0;l<r.data.byteLength;l++)a.setInt8(d++,c.getInt8(l));return r.data=n,s.length}return 0}function fd(r){try{let i=new DataView(r.data);if(Bl(r)||!$l(i))return[];let e=[],t=0,s=-1,o=-1;for(let n=0;n<r.data.byteLength;n++){let a=i.getUint8(n);if(a===0)t++;else if(a===1){if(t===2||t===3){let c=n-t;if(s===-1?s=c:o===-1&&(o=c,e.push(new Ni(new DataView(i.buffer.slice(s,o)))),s=c,o=-1),!(i.getUint8(n+1)===6)){r.data=i.buffer.slice(c);break}}t=0}else t=0}return e.reverse()}catch(i){return[]}}function wl(r){return new TransformStream({transform(i,e){_d(i,r),e.enqueue(i)}})}function Vl(r,i){return new TransformStream({transform(e,t){fd(e).forEach(s=>{self.postMessage({seiPayloadType:s.seiPayloadType,data:s.seiPayload.buffer,userId:r,streamType:i})}),t.enqueue(e)}})}function b_(){let r=[Ni],i=[Fl,Bl,$l,Ul,_d,fd,wl,Vl],e=()=>{let a=[],c=[],d=[];self.onmessage=l=>{l.data.isMain?(a.push(l.data.message),l.data.small&&d.push(l.data.message)):c.push(l.data.message)},self.onrtctransform=l=>{let{options:p}=l.transformer,m=p.isReceiver?Vl(p.userId,p.streamType):wl(p.isMain?p.small?d:a:c);l.transformer.readable.pipeThrough(m).pipeTo(l.transformer.writable)}},t=`(()=>{${r.map(a=>`const ${a.name}=(()=>${a.toString()})()`).join(`
66
66
  `)}
67
67
  ${i.map(a=>a.toString()).join(`
68
68
  `)};(${e})()})()`,s=new Blob([t],{type:"text/javascript"}),o=URL.createObjectURL(s),n=new Worker(o);return URL.revokeObjectURL(o),n}var Hl=0,zn=new Set,Le=null;ha(Ll);var N_={RtcError:k,ErrorCode:w,ErrorCodeDictionary:It},Jr=class extends Gl.EventEmitter{constructor(e,t){super();u(this,"_room");u(this,"_eventListened",new Set);u(this,"_localVideoTrack",null);u(this,"_localAudioTrack",null);u(this,"_localScreenTrack",null);u(this,"_localScreenAudioTrack",null);u(this,"_localVideoConfig",null);u(this,"_localScreenConfig",null);u(this,"_localAudioConfig",null);u(this,"_remoteVideoConfigMap",new Map);u(this,"_remoteAudioConfigMap",new Map);u(this,"_remoteAudioMuteMap",new Map);u(this,"_mediaTrackMap",new WeakMap);u(this,"_log",I.createLogger({id:`t${++Hl}`}));u(this,"_plugins",new Map);u(this,"_networkQuality",null);u(this,"_speakerId");this._room=new e(N({logger:this._log,frameWorkType:Jr.frameWorkType},t)),this._log.debug(`TRTC.create() ${JSON.stringify(t,(s,o)=>s==="plugins"?o.map(n=>n.Name):o)}`),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(s){return this._room.audioManager.dump(s)}}}),t.plugins&&t.plugins.forEach(s=>{this._use(s,t.assetsPath)}),this._use(Mi,t.assetsPath),this._use(tr,t.assetsPath),t.enableSEI&&Fi&&(this._use(to),this.startPlugin("SEI")),this._room.on("audio-volume",s=>{!s.find(o=>o.userId==="")&&this._localAudioTrack&&s.push({userId:"",volume:Math.floor(this._localAudioTrack.getAudioLevel()*100)}),this.emit($.AUDIO_VOLUME,{result:s.sort((o,n)=>n.volume-o.volume)})}),this._room.videoManager.on("error",({reason:s,error:o})=>{this._log.error(new k({code:w.OPERATION_FAILED,extraCode:5504,messageParams:{reason:s,error:o}}))}),this._listenEvents(),this._initActiveSpeaker(),Ml(this,"trtc")}static create(e){}static _create(e,t){Il();let s=new Jr(e,t||{});return zn.add(s),s}get room(){return this._room}_listenEvents(){De(this,this._room).add("peer-join",e=>{let{userId:t}=e;this.emit($.REMOTE_USER_ENTER,{userId:t})}).add("peer-leave",e=>{this.emit($.REMOTE_USER_EXIT,{userId:e})}).add("banned",e=>{this._exitRoom().then(()=>{this.emit($.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().then(()=>{this.emit($.ERROR,k.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit($.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e,this.emit($.NETWORK_QUALITY,e)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(s=>{De(s,s).add("player-state-changed",o=>{let n=P(N({},o),{userId:e.userId});s.kind===h.VIDEO&&(n.streamType=Zi(s.streamType)),this.emit(s.kind===h.AUDIO?$.AUDIO_PLAY_STATE_CHANGED:$.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",o=>{o.getCode()===A.PLAY_NOT_ALLOWED&&this.emit($.AUTOPLAY_FAILED,{userId:s.userId})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(s=>{me(s)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:t})=>{let{userId:s}=t,o=e.audioAvailable,n=e.videoAvailable,{audioAvailable:a,videoAvailable:c}=t;a||this._remoteAudioConfigMap.delete(s),c||this._remoteVideoConfigMap.delete(`${s}_${"main"}`),t.hasAuxiliary||this._remoteVideoConfigMap.delete(`${s}_${"sub"}`),o!==a&&(this.emit(a?$.REMOTE_AUDIO_AVAILABLE:$.REMOTE_AUDIO_UNAVAILABLE,{userId:s}),a?this._onAudioAvailable({userId:s}):this._onAudioUnavailable({userId:s,muteState:t})),n!==c&&(this.emit(c?$.REMOTE_VIDEO_AVAILABLE:$.REMOTE_VIDEO_UNAVAILABLE,{userId:s,streamType:"main"}),c?this._onVideoAvailable({userId:s,streamType:"main"}):this._onVideoUnavailable({userId:s,streamType:"main"})),e.hasAuxiliary!==t.hasAuxiliary&&(this.emit(t.hasAuxiliary?$.REMOTE_VIDEO_AVAILABLE:$.REMOTE_VIDEO_UNAVAILABLE,{userId:s,streamType:"sub"}),t.hasAuxiliary?this._onVideoAvailable({userId:s,streamType:"sub"}):this._onVideoUnavailable({userId:s,streamType:"sub"}))}).add("sei-message",e=>{this.emit($.SEI_MESSAGE,P(N({},e),{streamType:Zi(e.streamType)}))}).add("firewall-restriction",()=>{this.emit($.ERROR,new k({code:w.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var o,n,a,c,d,l,p;let t={2:"big",3:"small",7:"sub"},s={rtt: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,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:(((l=e.msg_up_stream_info.msg_audio_status)==null?void 0:l.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((p=e.msg_up_stream_info.msg_audio_status)==null?void 0:p.uint32_audio_level)||0)/ct},video:e.msg_up_stream_info.msg_video_status.filter(m=>t[m.uint32_video_stream_type]).map(m=>({bitrate:(m.uint32_video_codec_bitrate||0)/1e3,width:m.uint32_video_width,height:m.uint32_video_height,frameRate:m.uint32_video_enc_fps,videoType:t[m.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(m=>({userId:m.msg_user_info.str_identifier,audio:{bitrate:(m.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(m.msg_audio_status.uint32_audio_level||0)/ct},video:m.msg_video_status.map(f=>({bitrate:(f.uint32_video_codec_bitrate||0)/1e3,width:f.uint32_video_width,height:f.uint32_video_height,frameRate:f.uint32_video_dec_fps,videoType:t[f.uint32_video_stream_type]}))}))};this.emit($.STATISTICS,s)}).add("custom-message",e=>{this.emit($.CUSTOM_MESSAGE,e)}),De(this,ge).add("audioInputAdded",e=>{this.emit($.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit($.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit($.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit($.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>_(this,null,function*(){if(this.emit($.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Le&&Le.deviceId===cs){let t=(yield ji()).find(s=>s.deviceId===cs);t&&Le.groupId!==t.groupId&&(Le=t,this.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}})).add("audioOutputRemoved",e=>_(this,null,function*(){this.emit($.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield ji())[0];t&&Le&&(Le.deviceId===e.deviceId||Le.deviceId===cs&&Le.groupId!==t.groupId)&&(Le=t,this.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}))}use(e){let t,s;"plugin"in e?(t=e.plugin,s=e.assetsPath):t=e,this._use(t,s||"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(Ol.call(this,{TRTC:Jr,room:this._room,errorModule:N_,assetsPath:t}));this._plugins.set(e.Name,o),e.autoStart&&(this.startPlugin(e.Name),this._log.info("auto start plugin",e.Name))}enterRoom(e){return _(this,null,function*(){var c,d;let{scene:t="rtc",enableAutoPlayDialog:s=!0,autoReceiveAudio:o=!0,autoReceiveVideo:n=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!Y(e.proxy)&&e.proxy.turnServer&&((d=(c=this._room).setTurnServer)==null||d.call(c,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=s,this._room.autoReceiveAudio=o,this._room.autoReceiveVideo=n,de(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};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(a,t,Jr.frameWorkType),this._checkTrackToPublish(),md.start()})}exitRoom(){return _(this,null,function*(){return yield this._exitRoom()})}switchRole(e,t){return _(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(){me(this),this.removeAllListeners(),this._room.destroy(),zn.delete(this),zn.size===0&&md.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 _(this,arguments,function*(e={publish:!0}){if(this._localAudioTrack){this._log.warn("local audio is already started");return}let{publish:t=!0,mute:s,option:o}=e,n=new Oe(this._room.audioManager),a={},c={muted:!0};o&&(T(o.microphoneId)?T(o.audioTrack)||(a.customSource=o.audioTrack):a.deviceId=o.microphoneId,o&&ee(o.captureVolume)&&n.setCaptureVolume(o.captureVolume),T(o.profile)||(Y(o.profile)?Ro[o.profile]&&n.setProfile(Ro[o.profile]):n.setProfile(o.profile)),ee(o.earMonitorVolume)&&(c.muted=!(o.earMonitorVolume>0),c.volume=o.earMonitorVolume),T(o.echoCancellation)||(n.profile.echoCancellation=o.echoCancellation),T(o.noiseSuppression)||(n.profile.noiseSuppression=o.noiseSuppression),T(o.autoGainControl)||(n.profile.autoGainControl=o.autoGainControl)),n.on("5",d=>{this.emit($.ERROR,new k({code:w.DEVICE_ERROR,extraCode:5309,messageParams:{error:d}}))}),n.on("2",d=>{this.emit($.DEVICE_CHANGED,{type:"microphone",action:"active",device:d})}),n.on("4",d=>{let l;d.error&&(l=k.convertFrom(d.error)),this.emit($.PUBLISH_STATE_CHANGED,P(N({},d),{error:l}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId),yield n.capture(a),T(s)||n.setMute(s),De(n,n).add("player-state-changed",d=>{this.emit($.AUDIO_PLAY_STATE_CHANGED,P(N({},d),{userId:""}))}),t&&this._room.isJoined&&this._room.publish(n).catch(()=>{}),this._localAudioTrack=n,this._localAudioConfig=P(N({},e),{publish:t}),yield this._updateAudioPlayOption({playOption:c,track:n})})}updateLocalAudio(e){return _(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:s,option:o}=e,n={};o&&(o.microphoneId?yield this._localAudioTrack.switchDevice(o.microphoneId):T(o.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(o.audioTrack)),T(o.captureVolume)||this._localAudioTrack.setCaptureVolume(o.captureVolume),T(o.earMonitorVolume)||(n.muted=!(o.earMonitorVolume>0),n.volume=o.earMonitorVolume),yield this._localAudioTrack.update3A(o)),this._room.isJoined&&!T(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),T(s)||this._localAudioTrack.setMute(s),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),Kt(this._localAudioConfig,e)})}stopLocalAudio(){return _(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),me(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)})}startLocalVideo(){return _(this,arguments,function*(e={publish:!0,view:null}){if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:t,publish:s=!0,mute:o,option:n}=e,a=new le(this._room.videoManager),c={},d={};if(n&&(n.cameraId?c.deviceId=n.cameraId:T(n.useFrontCamera)?T(n.videoTrack)||(c.customSource=n.videoTrack):c.facingMode=n.useFrontCamera?h.FACING_MODE_USER:h.FACING_MODE_ENVIRONMENT,T(n.profile)||(Y(n.profile)?Ze[n.profile]&&a.setProfile(Ze[n.profile]):a.setProfile(n.profile)),T(n.fillMode)||(d.objectFit=n.fillMode),T(n.mirror)||(d.mirror=n.mirror),T(n.small)||(xs()?Y(n.small)?a.small=Ze[n.small]:n.small===!0?a.small=Ze["120p"]:a.small=n.small:this._log.warn("small stream is not supported"))),a.on("5",l=>{this.emit($.ERROR,new k({code:w.DEVICE_ERROR,extraCode:5308,messageParams:{error:l}}))}),a.on("2",l=>{this.emit($.DEVICE_CHANGED,{type:"camera",action:"active",device:l})}),a.on("4",l=>{let p;l.error&&(p=k.convertFrom(l.error)),this.emit($.PUBLISH_STATE_CHANGED,P(N({},l),{error:p}))}),this._listenOutputTrackChanged(a),yield a.capture(c),T(o)||(yield a.setMute(o)),a.mediaTrack)if(n!=null&&n.qosPreference){let l=er(n.qosPreference);a.mediaTrack.contentHint=l}else n!=null&&n.videoTrack||(a.mediaTrack.contentHint=er(st.QOS_PREFERENCE_SMOOTH));De(a,a).add("player-state-changed",l=>{this.emit($.VIDEO_PLAY_STATE_CHANGED,P(N({},l),{userId:"",streamType:"main"}))}),s&&this._room.isJoined&&this._room.publish(a).catch(()=>{}),this._localVideoTrack=a,this._localVideoConfig=P(N({},e),{view:t,publish:s}),yield this._updateVideoPlayOption({view:t,playOption:d,track:a})})}updateLocalVideo(e){return _(this,null,function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:s,mute:o,option:n}=e,a={};if(n){if(T(n.profile)||(Y(n.profile)?Ze[n.profile]&&this._localVideoTrack.setProfile(Ze[n.profile]):this._localVideoTrack.setProfile(n.profile),(!n.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(n.cameraId))&&T(n.useFrontCamera)&&this._localVideoTrack.applyProfile()),n.cameraId?yield this._localVideoTrack.switchDevice(n.cameraId):T(n.useFrontCamera)?T(n.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(n.videoTrack)):yield this._localVideoTrack.switchDevice(n.useFrontCamera?h.FACING_MODE_USER:h.FACING_MODE_ENVIRONMENT),T(n.fillMode)||(a.objectFit=n.fillMode),T(n.mirror)||(a.mirror=n.mirror),n.qosPreference&&this._localVideoTrack.mediaTrack){let c=er(n.qosPreference);this._localVideoTrack.mediaTrack.contentHint=c}if(n.small){let c=!this._localVideoTrack.small;xs()?(n.small===!0?this._localVideoTrack.small=Ze["120p"]:Y(n.small)?this._localVideoTrack.small=Ze[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&&!T(s)&&(s&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._localVideoConfig.publish&&!s&&this._room.unpublish(this._localVideoTrack).catch(()=>{})),T(o)||(yield this._localVideoTrack.setMute(o)),yield this._updateVideoPlayOption({view:t,playOption:a,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),Kt(this._localVideoConfig,e)})}stopLocalVideo(){return _(this,null,function*(){!this._localVideoTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),me(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return _(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:s=!0,option:o}=e,n=new ze(this._room.videoManager);n.on("4",p=>{let m;p.error&&(m=k.convertFrom(p.error)),this.emit($.PUBLISH_STATE_CHANGED,P(N({},p),{error:m}))}),this._listenOutputTrackChanged(n);let a=null,c={},d={};o&&(T(o.profile)||(Y(o.profile)?yo[o.profile]&&n.setProfile(yo[o.profile]):n.setProfile(o.profile)),o.systemAudio&&(c.systemAudio=!0,c.echoCancellation=o.echoCancellation,c.noiseSuppression=o.noiseSuppression,c.autoGainControl=o.autoGainControl),T(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 l=yield n.capture(c);if(o!=null&&o.qosPreference){let p=er(o.qosPreference);n.mediaTrack.contentHint=p}else o!=null&&o.videoTrack||(n.mediaTrack.contentHint=er(st.QOS_PREFERENCE_CLEAR));if(n.mediaTrack.addEventListener(h.ENDED,()=>{this._stopScreenShare(),this.emit($.SCREEN_SHARE_STOPPED)}),l.getAudioTracks()[0]&&(a=new Ft(this._room.audioManager),a.setInputMediaStreamTrack(l.getAudioTracks()[0]),this._speakerId&&a.setAudioOutput(this._speakerId)),De(n,n).add("player-state-changed",p=>{this.emit($.VIDEO_PLAY_STATE_CHANGED,P(N({},p),{userId:"",streamType:"sub"}))}),s&&this._room.isJoined){let p=[n];a&&p.push(a),this._room.publish(...p).catch(()=>{})}this._localScreenTrack=n,this._localScreenAudioTrack=a,this._localScreenConfig=P(N({},e),{view:t,publish:s}),yield this._updateVideoPlayOption({view:t,playOption:d,track:n})})}updateScreenShare(e){return _(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:s,option:o}=e,n={};if(o&&(T(o.fillMode)||(n.objectFit=o.fillMode),o.qosPreference)){let a=er(o.qosPreference);this._localScreenTrack.mediaTrack.contentHint=a}this._room.isJoined&&!T(s)&&(s&&!this._localScreenConfig.publish&&(this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch(()=>{})),this._localScreenConfig.publish&&!s&&(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}),Kt(this._localScreenConfig,e)})}stopScreenShare(){return _(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return _(this,null,function*(){let{view:t,userId:s,streamType:o,option:n}=e,a=`${s}_${o}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${s}, streamType:${o}`);return}let c=this._room.remotePublishedUserMap.get(s);if(!c)return;let d={},l=o==="main"?c.remoteVideoTrack:c.remoteAuxiliaryTrack;this._listenOutputTrackChanged(l),n&&(T(n.fillMode)||(d.objectFit=n.fillMode),T(n.mirror)||(d.mirror=n.mirror),d.canvasRender=n.canvasRender,o==="main"&&!T(n.small)&&(c.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,l.user))),yield this._room.subscribe(l),yield this._updateVideoPlayOption({view:t,playOption:d,track:l}),this._emitTrackEvent(l),this._remoteVideoConfigMap.set(a,{config:e}),n&&!T(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:l,view:t,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:n==null?void 0:n.viewRoot})})}updateRemoteVideo(e){return _(this,null,function*(){var v,U;let{view:t,userId:s,streamType:o,option:n}=e,a=`${s}_${o}`,c=this._remoteVideoConfigMap.get(a);if(!c||!this._room.remotePublishedUserMap.has(s))return;let d={};n&&(T(n.fillMode)||(d.objectFit=n.fillMode),T(n.mirror)||(d.mirror=n.mirror));let l=null,p=this._room.remotePublishedUserMap.get(s);if(o==="main"&&(p==null?void 0:p.muteState.hasVideo)&&(l=p.remoteVideoTrack),o==="sub"&&(p==null?void 0:p.muteState.hasAuxiliary)&&(l=p.remoteAuxiliaryTrack),!l)return;let{config:m}=c;o==="main"&&n&&!T(n.small)&&this._room.changeType(n.small,l.user),yield this._updateVideoPlayOption({view:t,playOption:d,track:l,prevConfig:m}),Kt(m,e);let f=T(n==null?void 0:n.receiveWhenViewVisible)?(v=m.option)==null?void 0:v.receiveWhenViewVisible:n.receiveWhenViewVisible,R=T(t)?m.view:t,C=T(n==null?void 0:n.viewRoot)?(U=m.option)==null?void 0:U.viewRoot:n.viewRoot;this._observeView({remoteTrack:l,view:R,receiveWhenViewVisible:f,viewRoot:C})})}stopRemoteVideo(e){return _(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,t=!0){return _(this,null,function*(){let s=[],o=this._room.remotePublishedUserMap.get(e.userId);if(o){let{muteState:a,remoteVideoTrack:c,remoteAuxiliaryTrack:d}=o;e.streamType==="main"&&(c.stop(),a.hasVideo&&s.push(c)),e.streamType==="sub"&&(d.stop(),a.hasAuxiliary&&s.push(d))}for(let a of s)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 _(this,null,function*(){if(e==="*")if(t)yield this._stopRemoteAudio({userId:e});else{let s=[...this._room.remotePublishedUserMap.values()];for(let o of s)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 s=[...this._room.remotePublishedUserMap.values()];for(let o of s)this._updateAudioPlayOption({playOption:{volume:t},track:o.remoteAudioTrack})}else if(e){let s=this._room.remotePublishedUserMap.get(e);s&&this._updateAudioPlayOption({playOption:{volume:t},track:s.remoteAudioTrack})}}startPlugin(e,t){return _(this,null,function*(){return e.start(t)})}updatePlugin(e,t){return _(this,null,function*(){return e.update(t)})}stopPlugin(e,t){return _(this,null,function*(){return e.stop(t)})}enableAudioVolumeEvaluation(e=2e3,t=!1){this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,s){return this.listeners(e).includes(t)?this:(this._log.debug("on",e),super.on(e,t,s),this._eventListened.add(e),this)}off(e,t,s){return this._log.debug("off",e),e==="*"?(this._eventListened.clear(),this.removeAllListeners()):super.off(e,t,s),this}getAudioTrack(e={userId:"",streamType:"main"}){var o,n;let t,s="main";if(Y(e)?t=e:(t=e.userId,e.streamType&&(s=e.streamType)),t){let a=this._room.remotePublishedUserMap.get(t);if(a)return a.remoteAudioTrack.mediaTrack}else return s==="sub"?((o=this._localScreenAudioTrack)==null?void 0:o.mediaTrack)||null:((n=this._localAudioTrack)==null?void 0:n.mediaTrack)||null;return null}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:t="",streamType:s="main"}=e;if(t===""){if(s==="main"&&this._localVideoTrack)return this._localVideoTrack.mediaTrack;if(s==="sub"&&this._localScreenTrack)return this._localScreenTrack.mediaTrack}else{let o=this._room.remotePublishedUserMap.get(t);if(o)return s==="main"?o.remoteVideoTrack.mediaTrack:o.remoteAuxiliaryTrack.mediaTrack}return null}getVideoSnapshot(e={}){let{userId:t,streamType:s="main"}=e;if(t){let o=this._room.remotePublishedUserMap.get(t);if(s==="main"&&(o==null?void 0:o.muteState.hasVideo))return o.remoteVideoTrack.getVideoFrame();if(s==="sub"&&(o==null?void 0:o.muteState.hasAuxiliary))return o.remoteAuxiliaryTrack.getVideoFrame()}else{if(s==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(s==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}setCurrentSpeaker(e){var t,s;this._speakerId=e,(t=this._localAudioTrack)==null||t.setAudioOutput(e),(s=this._localScreenAudioTrack)==null||s.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(o=>o.remoteAudioTrack.setAudioOutput(e))}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return _(this,null,function*(){let{userId:t,option:s}=e;if(this._remoteAudioConfigMap.has(t)){this._log.warn(`remote audio has already started. userId:${t}`);return}let o=this._room.remotePublishedUserMap.get(t);if(!o)return;let n={};s&&(T(s.volume)||(n.volume=s.volume));let a=o.remoteAudioTrack;this._listenOutputTrackChanged(a),this._speakerId&&a.setAudioOutput(this._speakerId);try{this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(a),yield this._updateAudioPlayOption({playOption:n,track:a})}catch(c){throw this._remoteAudioConfigMap.delete(t),c}this._emitTrackEvent(a)})}_stopRemoteAudio(e,t=!0){return _(this,null,function*(){let s=this._room.remotePublishedUserMap.get(e.userId);s&&(s.remoteAudioTrack.stop(),s.muteState.hasAudio&&t&&(yield this._room.unsubscribe(s.remoteAudioTrack)),this._mediaTrackMap.get(s.remoteAudioTrack.outMediaTrack)===e.userId&&this._mediaTrackMap.delete(s.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete(`${e.userId}`)})}_updateVideoPlayOption(n){return _(this,arguments,function*({view:e,playOption:t,track:s,prevConfig:o}){if(s.setMirror(t.mirror),T(e)&&o&&o.view&&!Ga(t)){let a=Ds(o.view);a.length>0&&(yield s.play(a,t))}if(!T(e)){let a=Ds(e);a.length>0?yield s.play(a,t):s.stop()}})}_updateAudioPlayOption(o){return _(this,arguments,function*({playOption:e={},track:t,prevConfig:s}){if(!t.isPlayCalled)try{yield t.play(null,e)}catch(n){}T(e.muted)||t.setPlayerMute(e.muted),T(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 s=e.isRemote?e.userId:"";!e.outMediaTrack||t&&this._mediaTrackMap.get(e.outMediaTrack)===s||(this._mediaTrackMap.set(e.outMediaTrack,s),this.emit($.TRACK,{userId:s,streamType:Zi(e.streamType),track:e.outMediaTrack}))}_checkTrackToPublish(){var t,s,o;let e=[];if(((t=this._localAudioConfig)==null?void 0:t.publish)&&this._localAudioTrack&&e.push(this._localAudioTrack),((s=this._localVideoConfig)==null?void 0:s.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:s=!1,viewRoot:o}){if(T(t))return;let n=this._remoteVideoConfigMap.get(`${e.userId}_${Zi(e.streamType)}`);if(!n)return;let a=n.observer||void 0;if(t===null||he(t)&&t.length===0||!s){a==null||a.disconnect(),e.isSubscribed||this._room.subscribe(e).catch(()=>{});return}let d=n.visibleViewMap||new Map,l=-1;(!a||a.root!==o)&&(a==null||a.disconnect(),d.clear(),a=new IntersectionObserver(m=>{m.forEach(f=>{d.set(f.target,f.isIntersecting)}),clearTimeout(l),l=window.setTimeout(()=>{[...d.values()].find(R=>R)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:o}));let p=new Set(Ds(t));d.forEach((m,f)=>{p.has(f)||(a.unobserve(f),d.delete(f))}),p.forEach(m=>{d.set(m,!0),a.observe(m)}),a.takeRecords().forEach(m=>{d.set(m.target,m.isIntersecting)}),n.visibleViewMap=d,n.observer=a}_exitRoom(){return _(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",s=e.split(`_${t}`)[0];s&&this._stopRemoteVideo({userId:s,streamType:t}).catch()}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._room.remotePublishedUserMap.forEach(e=>{me(e.remoteAudioTrack),me(e.remoteVideoTrack),me(e.remoteAuxiliaryTrack)})})}_stopScreenShare(){return _(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),me(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_initActiveSpeaker(){return _(this,null,function*(){if(Le&&!Lr(Le))this.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:Le});else{let e=yield ji();if(e[0]&&!Lr(e[0]))Le=e[0],this.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]});else{let t=({track:s})=>{s.kind==="audio"&&(!Le||Lr(Le))&&(this._initActiveSpeaker(),g.off("102",this._initActiveSpeaker))};g.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 s=this._room.remotePublishedUserMap.get(e);if(s){let o=t==="main"?s.remoteVideoTrack:s.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 s=this._plugins.get("SEI");s&&(s.update({buffer:e,options:P(N({seiPayloadType:243},t),{small:!!((o=this._localVideoTrack)!=null&&o.small)})}),D.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,s;(s=(t=this._room).sendCustomMessage)==null||s.call(t,e),D.addCount({key:500001,useUV:!0})}static setLogLevel(e,t){I.setLogLevel(e),T(t)||(t?I.enableUploadLog():I.disableUploadLog())}static isSupported(){return on()}static getCameraList(e=!0){return Xe(e)}static getMicrophoneList(e=!0){return Be(e)}static getSpeakerList(e=!0){return ji(e)}static setCurrentSpeaker(e){return _(this,null,function*(){(yield ji()).forEach(s=>{s.deviceId===e&&(zn.forEach(o=>{o.setCurrentSpeaker(e),o.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:s})}),Le=s)})})}static _addKVStat({type:e,key:t,value:s,base:o,useUV:n,version:a}){switch(a&&(Hi.version=a),e){case"count":Hi.addCount({key:t,useUV:n});break;case"enum":Hi.addEnum({key:t,value:s,useUV:n});break;case"number":Hi.addNumber({key:t,value:s,split:o});break}}},Q=Jr;u(Q,"_loggerManager",I),u(Q,"EVENT",$),u(Q,"ERROR_CODE",w),u(Q,"TYPE",st),u(Q,"frameWorkType",30),y([oe({replaceArg:r=>({argIndex:0,value:{name:"plugin"in r?r.plugin.Name:r.Name,assetsPath:"assetsPath"in r?r==null?void 0:r.assetsPath:"default"}})})],Q.prototype,"use",1),y([ke(Ce.TRTC.enterRoom),Di("room",([r],[i])=>(r.roomId||r.strRoomId)===(i.roomId||i.strRoomId)&&r.userId===i.userId&&r.sdkAppId===i.sdkAppId),J(r=>function(i){return this._log.setUserId(i.userId),this._log.setSdkAppId(i.sdkAppId),r.call(this,i)}),oe()],Q.prototype,"enterRoom",1),y([oe()],Q.prototype,"exitRoom",1),y([ke(Ce.TRTC.switchRole),Ki("room",{merge:(r,i)=>i}),oe()],Q.prototype,"switchRole",1),y([oe()],Q.prototype,"destroy",1),y([ke(Ce.TRTC.startLocalAudio),Di("audio",([r],[i])=>{var e,t;return((e=r==null?void 0:r.option)==null?void 0:e.microphoneId)===((t=i==null?void 0:i.option)==null?void 0:t.microphoneId)}),oe()],Q.prototype,"startLocalAudio",1),y([ke(Ce.TRTC.updateLocalAudio),Ki("audio",{debounce:{delay:200,getKey:()=>`${Hl}-localAudio`,isNeedToDebounce:r=>{var i;return!T((i=r.option)==null?void 0:i.captureVolume)}}}),oe()],Q.prototype,"updateLocalAudio",1),y([Oi("audio"),oe()],Q.prototype,"stopLocalAudio",1),y([ke(Ce.TRTC.startLocalVideo),Di("video",([r],[i])=>{var e,t;return((e=r==null?void 0:r.option)==null?void 0:e.cameraId)===((t=i==null?void 0:i.option)==null?void 0:t.cameraId)}),oe()],Q.prototype,"startLocalVideo",1),y([ke(Ce.TRTC.updateLocalVideo),Ki("video"),oe()],Q.prototype,"updateLocalVideo",1),y([Oi("video"),oe()],Q.prototype,"stopLocalVideo",1),y([ke(Ce.TRTC.startScreenShare),Di("screen",()=>!0),oe()],Q.prototype,"startScreenShare",1),y([ke(Ce.TRTC.updateScreenShare),Ki("screen"),oe()],Q.prototype,"updateScreenShare",1),y([oe()],Q.prototype,"stopScreenShare",1),y([ke(Ce.TRTC.startRemoteVideo),Di(r=>`v${r.userId}${r.streamType}`,()=>!0),oe({getRemoteId:r=>`${r.userId}_${r.streamType}`})],Q.prototype,"startRemoteVideo",1),y([ke(Ce.TRTC.updateRemoteVideo),Ki(r=>`v${r.userId}${r.streamType}`),oe({getRemoteId:r=>`${r.userId}_${r.streamType}`})],Q.prototype,"updateRemoteVideo",1),y([ke(Ce.TRTC.stopRemoteVideo),J(r=>function(i){return _(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 r.call(this,i)})}),oe({getRemoteId:r=>`${r.userId}_${r.streamType}`})],Q.prototype,"stopRemoteVideo",1),y([Oi(r=>`v${r.userId}${r.streamType}`)],Q.prototype,"_stopRemoteVideo",1),y([ke(...Ce.TRTC.muteRemoteAudio),oe({getRemoteId:r=>r})],Q.prototype,"muteRemoteAudio",1),y([dd(...Ce.TRTC.setRemoteAudioVolume),kl(200,r=>r),oe({getRemoteId:r=>r})],Q.prototype,"setRemoteAudioVolume",1),y([qn("start"),gt(r=>{var i;return(i=r.afterStart)==null?void 0:i.call(r)}),Di((r,i)=>r.getAlias()+r.getGroup(i)),oe({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>oc[r.getName()]})],Q.prototype,"startPlugin",1),y([qn("update"),Ki((r,i)=>r.getAlias()+r.getGroup(i)),oe({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>nc[r.getName()]})],Q.prototype,"updatePlugin",1),y([qn("stop"),Oi((r,i)=>{let e=r.getGroup(i),t=r.getAlias();return e==="*"?new RegExp(`${t}.*`):t+e}),oe({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>ac[r.getName()]})],Q.prototype,"stopPlugin",1),y([dd(...Ce.TRTC.enableAudioVolumeEvaluation)],Q.prototype,"enableAudioVolumeEvaluation",1),y([oe()],Q.prototype,"getVideoSnapshot",1),y([oe()],Q.prototype,"setCurrentSpeaker",1),y([Di(r=>`a${r.userId}`,()=>!0)],Q.prototype,"_startRemoteAudio",1),y([J(r=>function(i){return _(this,null,function*(){return i.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(e=>this._stopRemoteAudio(P(N({},i),{userId:e.userId})).catch(()=>{}))):r.call(this,i)})}),Oi(r=>`a${r.userId}`)],Q.prototype,"_stopRemoteAudio",1),y([Oi("room")],Q.prototype,"_exitRoom",1),y([Oi("screen")],Q.prototype,"_stopScreenShare",1),y([ke(...Ce.TRTC.sendSEIMessage),nd({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...r)=>r[0].byteLength})],Q.prototype,"sendSEIMessage",1),y([ke(Ce.TRTC.sendCustomMessage),nd({timesInSecond:30,maxSizeInSecond:8e3,getSize:r=>r.data.byteLength})],Q.prototype,"sendCustomMessage",1),y([ke(Ce.TRTC.create)],Q,"_create",1);var io=Q;var gd=class{constructor(){this._set=new Set;g.on(E.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,s){return`${t}_${e}_${i}_${s}`}isJoined({userId:i,roomId:e,sdkAppId:t,room:s}){return s.scene==="rtc"?!1:this._set.has(this.getKey(i,e,t,s.useStringRoomId))}};function v_(){return _(this,null,function*(){let r,i;try{let p=yield Be();r=p&&p.length}catch(p){}try{let p=yield Xe();i=p&&p.length}catch(p){}let e={microphone:r,camera:i},{isH264EncodeSupported:t,isVp8EncodeSupported:s,isH264DecodeSupported:o,isVp8DecodeSupported:n}=this.checkSystemResult.detail,a=ft.basis(),c={webRTC:a.isWebRTCSupported,getUserMedia:a.isGetUserMediaSupported,webSocket:a.isWebSocketsSupported,screenShare:a.isScreenShareSupported,webAudio:a.isWebAudioSupported,h264Encode:t,h264Decode:o,vp8Encode:s,vp8Decode:n},d={browser:a.browser,os:a.os,trtc:c,devices:e},l={isWebCodecSupported:a.isWebCodecSupported,isMediaSessionSupported:a.isMediaSessionSupported,isWebTransportSupported:a.isWebTransportSupported};Z.uploadEvent({log:`trtcstats-${JSON.stringify(d)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(d)}`),Z.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(l)}`,userId:this.userId})})}function Wl(){return J(r=>{let i=new gd;return function(e,t,s){return _(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 b({code:A.INVALID_OPERATION,message:L({key:M.INVALID_JOIN})});if(this.checkDestroy(),i.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this}))throw new b({code:A.INVALID_OPERATION,message:L({key:M.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}`),g.emit(E.JOIN_START,{room:this,roomId:o,params:e}),this.checkSystemResult=yield ft.checkSystemRequirementsInternal(),this.checkDestroy();let n=we.getEnv();n||(n=jt.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(bo.OLD_CLOUD_LADDER)?n=jt.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(bo.WEBRTC)&&(n=jt.WEBRTC))),Z.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),v_.call(this);let{isH264EncodeSupported:a,isVp8EncodeSupported:c}=this.checkSystemResult.detail;if(!ft.isWebRTCSupported()||!a&&!c)throw new b({code:A.NOT_SUPPORTED,message:L({key:M.NOT_SUPPORTED_WEBRTC})});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!we.getEnv()&&(yield this.schedule(e,s));let d=yield r.call(this,e,t,s);return this.roomId=o,this._joinedTimestamp=we.performanceNow(),g.emit(E.JOIN_SUCCESS,{room:this}),s===30&&!e.component&&Z.uploadEvent({log:`stat-conv-${Number(zt)}-${location.hostname}`,userId:this.userId}),d}catch(d){throw i.delete({room:this,roomId:o}),g.emit(E.JOIN_FAILED,{room:this,error:d}),d}})}})}var Jl=()=>J(r=>function(...i){return _(this,null,function*(){g.emit(E.LEAVE_START,{room:this}),yield r.call(this),g.emit(E.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function jl(){return J(r=>function(...i){let e=r.apply(this,i);return i.forEach(t=>!t.isSubscribed&&t.subscribe(e)),e})}var Xl=Se(Ne());var _e={SETUP_SUCCESS:"1",SETUP_FAILED:"5",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",DISCONNECTED:"5",RECONNECT_FAILED:"4"};var Gt={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,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},ql=[Gt.UPDATE_REMOTE_MUTE_STAT,Gt.UPLINK_NETWORK_STATS,Gt.USER_LIST_RES,Gt.MUTE_RESULT,Gt.SERVER_FIRST_PACKAGE_RECEIVED],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",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"},q={PUBLISH_CHANGE:"publish_change",JOIN_ROOM:"join",LEAVE_ROOM:"leave",ON_QUALITY_REPORT:"quality_report",UPDATE_MUTE_STAT:"mute_uplink",PUBLISH:"publish",PUBLISH_STATE_CHANGE:"publish_state_change",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",RECEIVE_DATA_USER_LIST:"receive_data_userlist",UNSUBSCRIBE:"unsubscribe",SUBSCRIBE_CHANGE:"subscribe_change",START_PUBLISH_TENCENT_CDN:"start_publishing",STOP_PUBLISH_TENCENT_CDN:"stop_publishing",START_PUBLISH_GIVEN_CDN:"start_push_user_cdn",STOP_PUBLISH_GIVEN_CDN:"stop_push_user_cdn",START_MIX_TRANSCODE:"start_mcu_mix",STOP_MIX_TRANSCODE:"stop_mcu_mix",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 Yn=new Set;function Ql(r){let i=[...Yn.values()].find(e=>e.room.userId===r&&!e.room.isJoined);return i||null}var jr=class extends Xl.default{constructor(e){var s,o;super();u(this,"room");u(this,"url");u(this,"backupUrl");u(this,"race");u(this,"destroyed",!1);u(this,"_socketInUse");u(this,"_socket");u(this,"_backupSocket");u(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0});u(this,"_currentState","DISCONNECTED");u(this,"_isReconnecting",!1);u(this,"_seq",0);u(this,"_log");u(this,"_lastMessageTime",-1);u(this,"_connnectStartTime",-1);u(this,"_stopConnectRetry");u(this,"bytesSent",0);u(this,"bytesReceived",0);u(this,"keepAlive",!1);u(this,"signalDomainWhenUnifiedProxy");this.room=e.room,this.race=T(e.race)?!0:e.race,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy,(((o=(s=this.room.scheduleResult)==null?void 0:s.config)==null?void 0:o.keepAliveClient)||0)-Yn.size>0&&this.room.enableSPC&&(this.keepAlive=!0,Yn.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=I.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))}`;return this.signalDomainWhenUnifiedProxy&&(e+=`&signalDomain=${encodeURIComponent(this.signalDomainWhenUnifiedProxy)}`),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 _(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=x();let t=[this.connectWS({url:this._urlWithParam,isMain:!0,timeout:e})];this.race&&this._backupUrlWithParam!==this._urlWithParam&&t.push(this.connectWS({url:this._backupUrlWithParam,isMain:!1,timeout:e})),this._socketInUse=yield Rs(t),this.unbindAndCloseSocket(this._socketInUse===this._socket?h.BACKUP:h.MAIN),this.emitConnectionStateChanged("CONNECTED")})}connectWS({url:e,timeout:t,isMain:s}){let o=new WebSocket(e);this.bindSocket(o),s?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(s?h.MAIN:h.BACKUP),c(new b({code:A.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===h.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){if(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._socketInUse.onclose=null,this._socketInUse.close(4011);let t=this._socketInUse===this._socket;this.unbindAndCloseSocket(t?h.MAIN:h.BACKUP),this._socketInUse=null,this.reconnect()}}onerror(e){this._log.error(`${e.target===this._socket?"main":"backup"} error observed`),this.emitConnectionStateChanged("DISCONNECTED"),e.target===this._socketInUse&&(this.unbindAndCloseSocket(h.MAIN),this.unbindAndCloseSocket(h.BACKUP),this._socketInUse=null,this.reconnect())}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=Yo(e.data);let t=JSON.parse(e.data),{cmd:s,data:o}=t,n=Object.values(Gt),c=Object.keys(Gt)[n.indexOf(s)],d=V[c]||s;switch(ql.includes(s)||(this._log.debug(`received ${s} msg: ${e.data}`),d&&this._log.info(`Received event: [ ${d} ]`)),s){case Gt.CHANNEL_SETUP_RESULT:{if(t.code===0)this._signalInfo.clientIp=o.clientIp,this._signalInfo.signalIp=o.signalInnerIp,o.svrTime&&Qd(o.svrTime),this._log.info("ChannelSetup Success"),D.addSuccessEvent({key:521701,cost:x()-this._connnectStartTime}),this._connnectStartTime=-1,this.emit(_e.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let l=new b({code:A.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:L({key:M.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error(`${t.code}, ${t.message}`),this.close(),D.addFailedEvent({key:521701,error:l}),this.emit(_e.SETUP_FAILED,l)}break}case Gt.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._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 _(this,null,function*(){try{if(!this.room.joinParams)return;Mt(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(e){}})}reconnect(){return _(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:s,relayInnerIp:o,relayPort:n}=this._signalInfo,{data:a}=yield this.sendWaitForResponse({command:q.RECONNECT_WS,data:{roomId:e,useStringRoomId:t,relayInnerIp:o,relayOuterIp:s,relayPort:n},responseCommand:V.CHANNEL_RECONNECT_RESULT});a.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),D.addSuccessEvent({key:521702,cost:x()-this._connnectStartTime}),this._connnectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(D.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 s={cmd:e,data:t,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},o=JSON.stringify(s);return this._socketInUse.send(o),this.bytesSent+=Yo(o),s.seq}}sendWaitForResponse({command:e,data:t,timeout:s=5e3,responseCommand:o,commandDesc:n,enableLog:a=!0}){return new Promise((c,d)=>{let l=setTimeout(()=>{this.off(o,p);let f=new b({code:A.API_CALL_TIMEOUT,message:L({key:M.API_CALL_TIMEOUT,data:{commandDesc:n,command:e}})});a&&this._log.warn(f),d(f)},s),p=f=>{f.data.seq===m&&(clearTimeout(l),this.off(o,p),c(f))};this.on(o,p);let m=this.send(e,t)})}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:s,retries:o=0,retryTimeout:n=0}=e;return vt({retryFunction:this.sendWaitForResponse,onError:({retry:a})=>{this.isOnline?a():(this._log.warn(`retry ${s} when connected`),this.once(_e.CONNECTED,a))},onRetrying:a=>{this._log.warn(`${t||s} 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"),Yn.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(h.MAIN),this.unbindAndCloseSocket(h.BACKUP),this.emitConnectionStateChanged("DISCONNECTED")}destroy(){this.close(),this.destroyed=!0}stopKeepAliveIn(e=3600){if(this.keepAlive){this._log.info(`stopKeepAlive in ${e}s`);let t=setTimeout(()=>{this.keepAlive=!1,this._log.info(`close due to not used ${e}s`),this.close(),this.off(V.JOIN_ROOM_RESULT,s)},e*1e3),s=o=>{o.data.code===0&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(t),this.off(V.JOIN_ROOM_RESULT,s))};this.on(V.JOIN_ROOM_RESULT,s)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info(`${this._currentState} -> ${e}`),this.emit(_e.CONNECTION_STATE_CHANGED,{prevState:this._currentState,state:e}),this._currentState=e,e==="CONNECTED"?this.emit(_e.CONNECTED):e==="DISCONNECTED"&&this.emit(_e.DISCONNECTED))}};y([it({settings:{retries:1/0,timeout:2e3},onError(r,i){!this.room.isDestroyed&&!this.destroyed&&i()},onRetrying(r,i){this._log.warn(`retrying to connect ${r}`),r>=3&&r%3===0&&this.reGetSignalChannelUrl(),i&&(this._stopConnectRetry=i,(this.room.isDestroyed||this.destroyed)&&i())}})],jr.prototype,"connect",1);var zl=Se(Ne());var Td=0,Sd=!1,Kn=new Set,O_=r=>Td>2&&!Sd&&Kn.size===0&&r,Id=!1,Ke=class{constructor(i){u(this,"userId");u(this,"tinyId");u(this,"_sdpSemantics");u(this,"_isUplink");u(this,"_room");u(this,"_log");u(this,"_signalChannel");u(this,"_isErrorObserved",!1);u(this,"_waitForPeerConnectionConnectedPromise");u(this,"_waitForPeerConnectionConnectedPromiseReject",null);u(this,"_peerConnection",null);u(this,"_emitter",new zl.default);u(this,"_currentState","DISCONNECTED");u(this,"_isReconnecting",!1);u(this,"_reconnectionCount",0);u(this,"_reconnectionTimer",-1);u(this,"_isFirstConnection",!0);u(this,"_prevTime",-1);u(this,"_localAddress");u(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=I.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=x())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,D.addSuccessEvent({key:521705,cost:Math.min(x()-this._prevTime,30*1e3)})):this._isReconnecting&&D.addSuccessEvent({key:521706,cost:x()-this._prevTime}),this._prevTime=-1}catch(i){throw this._isFirstConnection?(this._isFirstConnection=!1,D.addFailedEvent({key:521705,error:i})):this._isReconnecting&&this._reconnectionCount>=3&&D.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(),Kn.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 b({code:A.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return nt;let i=null;if(this._isUplink){if(!Ri()||this._peerConnection.getSenders().length===0)return nt;i=this._peerConnection.getSenders()[0].transport}else{if(!$i()||this._peerConnection.getReceivers().length===0)return nt;i=this._peerConnection.getReceivers()[0].transport}return i?i.state:nt}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===se.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),i.target.connectionState===se.FAILED||i.target.connectionState===se.CLOSED){let s=`connection ${i.target.connectionState}. ICE Transport state: ${e}, DTLS Transport state: ${t}`,o=new b({message:s,code:A.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",o)}(i.target.connectionState===se.CONNECTED||i.target.connectionState===se.COMPLETED)&&(this.logSelectedCandidate(),Z.logSuccessEvent({userId:this._room.userId,eventType:Ve.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(i){return i===this._currentState?!1:(i==="CONNECTED"?(Td=0,Sd=!1,Id=!0,Kn.add(this)):Kn.delete(this),g.emit(E.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 _(this,null,function*(){if(!this._peerConnection)return;let i=yield this._peerConnection.getStats();for(let[,e]of i)if(Ci(e)){let t=i.get(e.localCandidateId),s=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}`),s&&(this._log.info(`remote candidate: ${s.candidateType} ${s.protocol}:${s.ip||s.address}:${s.port}`),this._remoteAddress=`${s.protocol}:${s.ip||s.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())},s=({room:a})=>{a===this._room&&(clearTimeout(n),o(),e(new b({code:A.API_CALL_ABORTED,message:L({key:M.CONNECTION_ABORTED,data:"leave room"})})))},o=()=>{g.off(E.LEAVE_SUCCESS,s,this),this._emitter.off("connection-state-changed",t,this)},n=setTimeout(()=>{o();let a=new b({code:A.API_CALL_TIMEOUT,message:"connection timeout"});Td+=1,O_(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),Sd=!0,this._emitter.emit("firewall-restriction")),e(a)},as);g.on(E.LEAVE_SUCCESS,s,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(_e.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=qt()){this._log.warn(`SDK has tried reconnect for ${this._reconnectionCount} times, but all failed, please check your network`),this.stopReconnection();let i=new b({code:this._isUplink?A.UPLINK_RECONNECTION_FAILED:A.DOWNLINK_RECONNECTION_FAILED,message:L({key:this._isUplink?M.UPLINK_RECONNECTION_FAILED:M.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(_e.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"))}};var yd=Se(Rd());var ce=function(r){return yd.default.parse(r)},He=function(r){return yd.default.write(r)},sh=function(r){let i=ce(r);return i.media.forEach(e=>{e.type===h.AUDIO&&e.fmtp.forEach(t=>{t.config+=";sprop-stereo=1;stereo=1"})}),He(i)};function oh(r){let i=ce(r);return i.media.forEach(e=>{var t,s;if(e.type===h.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=(s=e.payloads)==null?void 0:s.split(" ").filter(a=>!o.has(Number(a))).join(" ")}}),He(i)}function Zn(r){return Object.keys(r).filter(i=>r[i])}var Nd=class extends Ke{constructor(e){super(P(N({},e),{isUplink:!1}));u(this,"_flag",0);u(this,"role","anchor");u(this,"remoteAudioTrack");u(this,"remoteVideoTrack");u(this,"remoteAuxiliaryTrack");u(this,"ssrc",{audio:0,video:0,auxiliary:0});u(this,"_isSDPExchanging",!1);this.flag=e.flag,this.remoteAudioTrack=e.remoteAudioTrack||new oi(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new Tt(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new Vr(this._room,this)}get videoCodec(){var t,s;let e=(s=(t=this._peerConnection)==null?void 0:t.remoteDescription)==null?void 0:s.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 Ai(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,s,o;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(s=this.remoteVideoTrack)==null||s.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===h.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,s=super.emitConnectionStateChangedEvent(e);return s&&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})),s}onTrack(e){let t=e.streams[0],{track:s}=e,o=t.id===ns?h.MAIN:h.AUXILIARY;this._log.debug(`ontrack ${o} ${s.kind}`);let n=h.AUDIO;s.kind===h.VIDEO&&(n=o===h.MAIN?h.VIDEO:h.AUXILIARY);let a=this.remoteAudioTrack;n===h.VIDEO?a=this.remoteVideoTrack:n===h.AUXILIARY&&(a=this.remoteAuxiliaryTrack),a.setInputMediaStreamTrack(s)}addRRTRLine(e){let t=e.split(`\r
69
69
  `),s=new Map;t.forEach((n,a)=>{/^a=rtcp-fb:/.test(n)&&t[a+1]&&!/^a=rtcp-fb:/.test(t[a+1])&&s.set(a+1,`${n.match(/^a=rtcp-fb:\d+/)[0]} rrtr`)});let o=[...s];for(let n=0;n<o.length;n++){let[a,c]=o[n];t.splice(a+n,0,c)}return t.join(`\r
70
- `)}addSPSDescription(e){let t=ce(e);return t.media.forEach(s=>{s.type===h.VIDEO&&s.fmtp.forEach(o=>{o.config+=";sps-pps-idr-in-keyframe=1"})}),He(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"],s=ce(e);return s.media.forEach(o=>{!o.ext||(o.ext=o.ext.filter(n=>!t.includes(n.uri)))}),He(s)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return _(this,null,function*(){var s,o;try{if((((s=this._peerConnection)==null?void 0:s.connectionState)===se.NEW||((o=this._peerConnection)==null?void 0:o.connectionState)===se.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 b({code:A.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):n}})}unsubscribe(s){return _(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=N({},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} [${Zn(o)}]`),yield this.sendSubscription(n,o),n==="unsubscribe"&&(this.closePeerConnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"))})}sendSubscription(e,t=this.subscribeState){let s={srcTinyId:this.tinyId,srcUserId:this.userId},o=q.UNSUBSCRIBE,n=V.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(s={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},o=q.SUBSCRIBE_CHANGE,n=V.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:o,data:s,responseCommand:n,timeout:1e4}).then(({data:a})=>{if(a.code!==0){let c=new b({code:a.code,message:L({key:M.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(c),c}})}connect(){return _(this,arguments,function*(e=this.subscribeState){try{yield this.exchangeSDP(e),yield this.waitForPeerConnectionConnected()}catch(t){throw this.closePeerConnection(!0),t}})}exchangeSDP(e){return _(this,null,function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info("createOffer success, sending offer");let{type:t,sdp:s}=this._peerConnection.localDescription,o={type:t,sdp:s,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},n=yield this._signalChannel.sendWaitForResponse({command:q.SUBSCRIBE,commandDesc:"exchange sdp",data:o,responseCommand:V.SUBSCRIBE_RESULT,timeout:Ia});if(!this._peerConnection){let a=new b({code:A.INVALID_OPERATION,message:L({key:M.CONNECTION_CLOSED})});throw this._log.warn(a),a}yield this.onSubscribeResult(n),this._isSDPExchanging=!1}catch(t){throw this._isSDPExchanging=!1,t}})}createOffer(){return _(this,null,function*(){let e={voiceActivityDetection:!1};tt()&&this._sdpSemantics===pi?(this._peerConnection.addTransceiver(h.AUDIO,{direction:z.RECVONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:z.RECVONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:z.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:s}=yield sn();s||(this._log.warn("remove h264 desc from sdp"),t.sdp=oh(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=sh(t.sdp),this._sdpSemantics===pi&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this._peerConnection.setLocalDescription(t)})}onSubscribeResult(e){return _(this,null,function*(){let{code:t,message:s=""}=e&&e.data||{},{type:o,sdp:n}=e&&e.data&&e.data.data||{};if(t===Pi)throw new b({code:A.NOT_SUPPORTED_H264,message:L({key:M.NOT_SUPPORTED_H264DECODE})});try{if(t!==0)throw new b({code:t,message:L({key:M.EXCHANGE_SDP_FAILED,data:{errMsg:s}})});this._log.debug(`accept remote answer: ${n}`),yield this._peerConnection.setRemoteDescription({type:o,sdp:n}),this.updateSSRC(n)}catch(a){throw this._log.error(a),a}})}updateSSRC(e){try{ce(e).media.forEach(s=>{if(!!s.ssrcs)if(s.type===h.AUDIO){let o=s.ssrcs.find(n=>{var a;return(a=n.value)==null?void 0:a.includes(ns)});o&&(this.ssrc.audio=Number(o.id))}else{let o=s.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(ns)}),n=s.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(fa)});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 _(this,null,function*(){if(!(Ie(Nd.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch(t){let s=kt(this._reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${s/1e3}s`),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},s)}})}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}},oo=Nd;y([J(r=>function(...i){return new Promise((e,t)=>{let s=o=>{this._emitter.off("closed",s),t(new b({code:A.API_CALL_ABORTED,message:L({key:M.CONNECTION_ABORTED,data:o})}))};this._emitter.on("closed",s),r.apply(this,i).then(e,t).finally(()=>{this._emitter.off("closed",s)})})})],oo.prototype,"subscribe",1),y([gt(Ke.prototype.afterConnect),In(Ke.prototype.beforeConnect)],oo.prototype,"connect",1);var bd=oo;var ah={voiceActivityDetection:!1},vd=class extends Ke{constructor(e){super(P(N({},e),{isUplink:!0}));u(this,"localMainAudioTrack",null);u(this,"localMainVideoTrack",null);u(this,"localAuxAudioTrack",null);u(this,"localAuxVideoTrack",null);u(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0});u(this,"_isPublishingAux",!1);u(this,"_publishingLocalAudioTrack");u(this,"_publishingLocalVideoTrack");u(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});u(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,s,o,n;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(Lt()?(e.audio=!!((t=a[0])!=null&&t.track),e.bigVideo=!!((s=a[1])!=null&&s.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===h.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 s=this._currentState,o=super.emitConnectionStateChangedEvent(e);return o&&s!==e&&(t?t.emit("connection-state-changed",{prevState:s,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:s,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:s,state:e}),(c=this._publishingLocalVideoTrack)==null||c.emit("connection-state-changed",{prevState:s,state:e}))),o}publish(o){return _(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:s}){this._peerConnection||this.initialize(),e&&(this._publishingLocalAudioTrack=e),t&&(this._publishingLocalVideoTrack=t),this._isPublishingAux=s;let n;t&&!s&&t.small&&(n=this._room.videoManager.smallTrack),this.sendMediaSettings(),tt()?yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:n,isAuxiliary:s}):yield this.publishByAddTrack({localAudioTrack:e,localVideoTrack:t,smallTrack:n}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,s?(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 _(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:s,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 l=this._peerConnection.getTransceivers();if(l.length===0)this._peerConnection.addTransceiver(d||h.AUDIO,{direction:z.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(o?h.VIDEO:c||h.VIDEO,{direction:z.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(s||h.VIDEO,{direction:z.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(o?c||h.VIDEO:h.VIDEO,{direction:z.SENDONLY,streams:[a]}),yield this.connect();else{let p=[];if(d&&(l[0].sender.track||p.push(0),yield l[0].sender.replaceTrack(d),yield this.setBandwidth({bandwidth:(e==null?void 0:e.profile.bitrate)||40,type:h.AUDIO})),c){let m=o?3:1;yield l[m].sender.replaceTrack(c),yield this.setBandwidth({bandwidth:t.profile.bitrate,type:h.VIDEO,videoType:o?h.AUXILIARY:h.BIG}),p.push(m),s&&(yield l[2].sender.replaceTrack(s),yield this.setBandwidth({bandwidth:t.small.bitrate,type:h.VIDEO,videoType:h.SMALL}),p.push(2))}yield this.setTransceiverDirection(z.SENDONLY,p),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 _(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:s}){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),s)){let d=new MediaStream;d.addTrack(s),this._peerConnection.addTrack(s,d)}yield this.connect()})}enableSmall(e){return _(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(z.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(z.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(s){return _(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){if(!Lt()){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&&(yield a[0].replaceTrack(null),c.push(0),o?this.localAuxAudioTrack=null:this.localMainAudioTrack=null),n&&(o?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=P(N({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),c.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=P(N({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),c.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.setTransceiverDirection(z.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 _(this,null,function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},s=yield this._signalChannel.sendWaitForResponse({command:q.PUBLISH_STATE_CHANGE,data:t,responseCommand:V.PUBLISH_STATE_CHANGE_RESULT,enableLog:e});this.checkPublishResultCode(s.data.code,s.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:q.UNPUBLISH,commandDesc:"unpublish",responseCommand:V.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===A.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 s=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:o,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:o=this._publishingLocalVideoTrack),xt){if(s&&s.outMediaTrack){let a=s.outMediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=s.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 s&&s.outMediaTrack&&(this._mediaSettings.audioChannel=s.profile.channelCount,this._mediaSettings.audioBps=s.profile.bitrate*1e3,this._mediaSettings.audioFs=s.profile.sampleRate),o&&o.outMediaTrack&&(this._mediaSettings.videoWidth=o.profile.width,this._mediaSettings.videoHeight=o.profile.height,this._mediaSettings.videoFps=o.profile.frameRate,this._mediaSettings.videoBps=o.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:q.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:V.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return _(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?h.AUXILIARY:h.MAIN} stream`),tt()?yield this.addTrackByTransceiver(e,t):yield this.addTrackBySender(e)})}addTrackByTransceiver(e,t){return _(this,null,function*(){var o;if(!e.mediaTrack)return;let s=this._peerConnection.getTransceivers();if(e.kind===h.AUDIO)yield s[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield s[n].sender.replaceTrack(e.outMediaTrack),n===1&&((o=this.localMainVideoTrack)==null?void 0:o.small)&&(yield s[2].sender.replaceTrack(this._room.videoManager.smallTrack)),s[n].direction===z.INACTIVE&&(yield this.setTransceiverDirection(z.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}addTrackBySender(e){return _(this,null,function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;Lt()&&this._peerConnection.getTransceivers().findIndex(o=>o.direction==="stopped")>=0&&(this._log.warn("transceiver is stopping, negotiate sdp first"),yield this.updateOffer("remove",t));let s=this._peerConnection.getSenders().find(o=>o.track&&o.track.kind===t.kind);if(s&&s.track){this._log.warn("sender already exists, remove sender first");let o=s.track;this.removeSender(s),yield this.updateOffer("remove",o)}if(t&&this._peerConnection.addTrack(t,new MediaStream([t])),t.kind===h.VIDEO&&e instanceof le&&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===dr||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=ce(e);for(let s=0;s<t.media.length;s++)if(Number(t.media[s].mid)===0&&t.media[s].type===h.VIDEO)return!0;return!1}removeSender(e){let t=null;Lt()&&(t=this._peerConnection.getTransceivers().find(s=>s.sender&&s.sender.track===e.track)),this._peerConnection.removeTrack(e),t&&W(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return _(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?h.AUXILIARY:h.MAIN} stream`),tt()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)})}removeTrackByTransceiver(e,t){return _(this,null,function*(){if(!e.outMediaTrack)return;let s=this._peerConnection.getTransceivers();if(e.kind===h.AUDIO)yield s[0].sender.replaceTrack(null);else{let o=t?3:1;yield s[o].sender.replaceTrack(null),o===1&&e.small&&(yield s[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(z.INACTIVE,[o])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,t){return _(this,null,function*(){if(!ie)return;let s=!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,s=!0)}),s){this._log.info("updating offer");let d=yield this._peerConnection.createOffer();yield this._peerConnection.setLocalDescription(d)}let a=-1,c=this._peerConnection.remoteDescription.sdp.split(`\r
70
+ `)}addSPSDescription(e){let t=ce(e);return t.media.forEach(s=>{s.type===h.VIDEO&&s.fmtp.forEach(o=>{o.config+=";sps-pps-idr-in-keyframe=1"})}),He(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"],s=ce(e);return s.media.forEach(o=>{!o.ext||(o.ext=o.ext.filter(n=>!t.includes(n.uri)))}),He(s)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return _(this,null,function*(){var s,o;try{if((((s=this._peerConnection)==null?void 0:s.connectionState)===se.NEW||((o=this._peerConnection)==null?void 0:o.connectionState)===se.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 b({code:A.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):n}})}unsubscribe(s){return _(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=N({},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} [${Zn(o)}]`),yield this.sendSubscription(n,o),n==="unsubscribe"&&(this.closePeerConnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"))})}sendSubscription(e,t=this.subscribeState){let s={srcTinyId:this.tinyId,srcUserId:this.userId},o=q.UNSUBSCRIBE,n=V.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(s={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},o=q.SUBSCRIBE_CHANGE,n=V.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:o,data:s,responseCommand:n,timeout:1e4}).then(({data:a})=>{if(a.code!==0){let c=new b({code:a.code,message:L({key:M.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(c),c}})}connect(){return _(this,arguments,function*(e=this.subscribeState){try{yield this.exchangeSDP(e),yield this.waitForPeerConnectionConnected()}catch(t){throw this.closePeerConnection(!0),t}})}exchangeSDP(e){return _(this,null,function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info("createOffer success, sending offer");let{type:t,sdp:s}=this._peerConnection.localDescription,o={type:t,sdp:s,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},n=yield this._signalChannel.sendWaitForResponse({command:q.SUBSCRIBE,commandDesc:"exchange sdp",data:o,responseCommand:V.SUBSCRIBE_RESULT,timeout:Ia});if(!this._peerConnection){let a=new b({code:A.INVALID_OPERATION,message:L({key:M.CONNECTION_CLOSED})});throw this._log.warn(a),a}yield this.onSubscribeResult(n),this._isSDPExchanging=!1}catch(t){throw this._isSDPExchanging=!1,t}})}createOffer(){return _(this,null,function*(){let e={voiceActivityDetection:!1};tt()&&this._sdpSemantics===pi?(this._peerConnection.addTransceiver(h.AUDIO,{direction:z.RECVONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:z.RECVONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:z.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:s}=yield sn();s||(this._log.warn("remove h264 desc from sdp"),t.sdp=oh(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=sh(t.sdp),this._sdpSemantics===pi&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this._peerConnection.setLocalDescription(t)})}onSubscribeResult(e){return _(this,null,function*(){let{code:t,message:s=""}=e&&e.data||{},{type:o,sdp:n}=e&&e.data&&e.data.data||{};if(t===Pi)throw new b({code:A.NOT_SUPPORTED_H264,message:L({key:M.NOT_SUPPORTED_H264DECODE})});try{if(t!==0)throw new b({code:t,message:L({key:M.EXCHANGE_SDP_FAILED,data:{errMsg:s}})});this._log.debug(`accept remote answer: ${n}`),yield this._peerConnection.setRemoteDescription({type:o,sdp:n}),this.updateSSRC(n)}catch(a){throw this._log.error(a),a}})}updateSSRC(e){try{ce(e).media.forEach(s=>{if(!!s.ssrcs)if(s.type===h.AUDIO){let o=s.ssrcs.find(n=>{var a;return(a=n.value)==null?void 0:a.includes(ns)});o&&(this.ssrc.audio=Number(o.id))}else{let o=s.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(ns)}),n=s.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(fa)});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 _(this,null,function*(){if(!(Ie(Nd.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch(t){let s=kt(this._reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${s/1e3}s`),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},s)}})}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}},oo=Nd;y([J(r=>function(...i){return new Promise((e,t)=>{let s=o=>{this._emitter.off("closed",s),t(new b({code:A.API_CALL_ABORTED,message:L({key:M.CONNECTION_ABORTED,data:o})}))};this._emitter.on("closed",s),r.apply(this,i).then(e,t).finally(()=>{this._emitter.off("closed",s)})})})],oo.prototype,"subscribe",1),y([gt(Ke.prototype.afterConnect),In(Ke.prototype.beforeConnect)],oo.prototype,"connect",1);var bd=oo;var ah={voiceActivityDetection:!1},vd=class extends Ke{constructor(e){super(P(N({},e),{isUplink:!0}));u(this,"localMainAudioTrack",null);u(this,"localMainVideoTrack",null);u(this,"localAuxAudioTrack",null);u(this,"localAuxVideoTrack",null);u(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0});u(this,"_isPublishingAux",!1);u(this,"_publishingLocalAudioTrack");u(this,"_publishingLocalVideoTrack");u(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});u(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,s,o,n;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(Lt()?(e.audio=!!((t=a[0])!=null&&t.track),e.bigVideo=!!((s=a[1])!=null&&s.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===h.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 s=this._currentState,o=super.emitConnectionStateChangedEvent(e);return o&&s!==e&&(t?t.emit("connection-state-changed",{prevState:s,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:s,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:s,state:e}),(c=this._publishingLocalVideoTrack)==null||c.emit("connection-state-changed",{prevState:s,state:e}))),o}publish(o){return _(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:s}){this._peerConnection||this.initialize(),e&&(this._publishingLocalAudioTrack=e),t&&(this._publishingLocalVideoTrack=t),this._isPublishingAux=s;let n;t&&!s&&t.small&&(n=this._room.videoManager.smallTrack),this.sendMediaSettings(),tt()?yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:n,isAuxiliary:s}):yield this.publishByAddTrack({localAudioTrack:e,localVideoTrack:t,smallTrack:n}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,s?(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 _(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:s,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 l=this._peerConnection.getTransceivers();if(l.length===0)this._peerConnection.addTransceiver(d||h.AUDIO,{direction:z.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(o?h.VIDEO:c||h.VIDEO,{direction:z.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(s||h.VIDEO,{direction:z.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(o?c||h.VIDEO:h.VIDEO,{direction:z.SENDONLY,streams:[a]}),yield this.connect();else{let p=[];if(d&&(l[0].sender.track||p.push(0),yield l[0].sender.replaceTrack(d),yield this.setBandwidth({bandwidth:(e==null?void 0:e.profile.bitrate)||40,type:h.AUDIO})),c){let m=o?3:1;yield l[m].sender.replaceTrack(c),yield this.setBandwidth({bandwidth:t.profile.bitrate,type:h.VIDEO,videoType:o?h.AUXILIARY:h.BIG}),p.push(m),s&&(yield l[2].sender.replaceTrack(s),yield this.setBandwidth({bandwidth:t.small.bitrate,type:h.VIDEO,videoType:h.SMALL}),p.push(2))}yield this.setTransceiverDirection(z.SENDONLY,p),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 _(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:s}){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),s)){let d=new MediaStream;d.addTrack(s),this._peerConnection.addTrack(s,d)}yield this.connect()})}enableSmall(e){return _(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(z.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(z.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(s){return _(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){if(!Lt()){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=P(N({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),c.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=P(N({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),c.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.setTransceiverDirection(z.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 _(this,null,function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},s=yield this._signalChannel.sendWaitForResponse({command:q.PUBLISH_STATE_CHANGE,data:t,responseCommand:V.PUBLISH_STATE_CHANGE_RESULT,enableLog:e});this.checkPublishResultCode(s.data.code,s.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:q.UNPUBLISH,commandDesc:"unpublish",responseCommand:V.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===A.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 s=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:o,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:o=this._publishingLocalVideoTrack),xt){if(s&&s.outMediaTrack){let a=s.outMediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=s.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 s&&s.outMediaTrack&&(this._mediaSettings.audioChannel=s.profile.channelCount,this._mediaSettings.audioBps=s.profile.bitrate*1e3,this._mediaSettings.audioFs=s.profile.sampleRate),o&&o.outMediaTrack&&(this._mediaSettings.videoWidth=o.profile.width,this._mediaSettings.videoHeight=o.profile.height,this._mediaSettings.videoFps=o.profile.frameRate,this._mediaSettings.videoBps=o.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:q.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:V.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return _(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?h.AUXILIARY:h.MAIN} stream`),tt()?yield this.addTrackByTransceiver(e,t):yield this.addTrackBySender(e)})}addTrackByTransceiver(e,t){return _(this,null,function*(){var o;if(!e.mediaTrack)return;let s=this._peerConnection.getTransceivers();if(e.kind===h.AUDIO)yield s[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield s[n].sender.replaceTrack(e.outMediaTrack),n===1&&((o=this.localMainVideoTrack)==null?void 0:o.small)&&(yield s[2].sender.replaceTrack(this._room.videoManager.smallTrack)),s[n].direction===z.INACTIVE&&(yield this.setTransceiverDirection(z.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}addTrackBySender(e){return _(this,null,function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;Lt()&&this._peerConnection.getTransceivers().findIndex(o=>o.direction==="stopped")>=0&&(this._log.warn("transceiver is stopping, negotiate sdp first"),yield this.updateOffer("remove",t));let s=this._peerConnection.getSenders().find(o=>o.track&&o.track.kind===t.kind);if(s&&s.track){this._log.warn("sender already exists, remove sender first");let o=s.track;this.removeSender(s),yield this.updateOffer("remove",o)}if(t&&this._peerConnection.addTrack(t,new MediaStream([t])),t.kind===h.VIDEO&&e instanceof le&&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===dr||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=ce(e);for(let s=0;s<t.media.length;s++)if(Number(t.media[s].mid)===0&&t.media[s].type===h.VIDEO)return!0;return!1}removeSender(e){let t=null;Lt()&&(t=this._peerConnection.getTransceivers().find(s=>s.sender&&s.sender.track===e.track)),this._peerConnection.removeTrack(e),t&&W(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return _(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?h.AUXILIARY:h.MAIN} stream`),tt()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)})}removeTrackByTransceiver(e,t){return _(this,null,function*(){if(!e.outMediaTrack)return;let s=this._peerConnection.getTransceivers();if(e.kind===h.AUDIO)yield s[0].sender.replaceTrack(null);else{let o=t?3:1;yield s[o].sender.replaceTrack(null),o===1&&e.small&&(yield s[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(z.INACTIVE,[o])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,t){return _(this,null,function*(){if(!ie)return;let s=!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,s=!0)}),s){this._log.info("updating offer");let d=yield this._peerConnection.createOffer();yield this._peerConnection.setLocalDescription(d)}let a=-1,c=this._peerConnection.remoteDescription.sdp.split(`\r
71
71
  `).map(d=>{if(d.match(new RegExp(`a=(${z.INACTIVE}|${z.RECVONLY}|${z.SENDONLY})`))&&a++,t.includes(a)){if(e===z.INACTIVE&&d.includes(`a=${z.RECVONLY}`))return o=!0,`a=${e}`;if(e===z.SENDONLY&&d.includes(`a=${z.INACTIVE}`))return o=!0,`a=${z.RECVONLY}`}return d}).join(`\r
72
72
  `);o&&(this._log.info("updating answer"),yield this._peerConnection.setRemoteDescription({type:"answer",sdp:c}))})}removeTrackBySender(e){return _(this,null,function*(){if(!e.outMediaTrack)return;if(e.kind===h.VIDEO&&this.isNeedToResetOfferOrder()&&this.localMainAudioTrack){this.reset(),this.initialize(),yield this.publish({localAudioTrack:this.localMainAudioTrack,isAuxiliary:!1});return}let t=this._peerConnection.getSenders().find(s=>s.track===e.outMediaTrack);t&&(this.removeSender(t),e.kind===h.VIDEO&&e.small&&this._peerConnection.getSenders().forEach(s=>{s.track&&s.track.kind===h.VIDEO&&this.removeSender(s)})),yield this.updateOffer("remove",e.outMediaTrack)})}replaceTrack(e){return _(this,null,function*(){var n;let t=(n=this._peerConnection)==null?void 0:n.getSenders();if(!t||t.length===0||!e.mediaTrack)return!1;let s;if(tt()?s=e.kind===h.AUDIO?t[0]:t[1]:s=t.find(a=>a.track&&a.track.kind===e.kind),!s)return!1;let o=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info(`is replacing ${e.kind} track on ${o?h.AUXILIARY:h.MAIN} stream`),e.kind===h.AUDIO?yield s.replaceTrack(e.outMediaTrack):e.kind===h.VIDEO&&(o?t[3]&&(yield t[3].replaceTrack(e.outMediaTrack)):yield s.replaceTrack(e.outMediaTrack)),!0})}updateOffer(e,t){return _(this,null,function*(){try{let s=yield this._peerConnection.createOffer(ah);ie&&s.sdp&&(s.sdp=this.setSDPDirection(s.sdp,"sendrecv")),yield this._peerConnection.setLocalDescription(s);let o=this.updateMediaSettings(),n={action:e,trackId:t.id,kind:t.kind===h.VIDEO?"bigVideo":t.kind,type:"offer",sdp:this._peerConnection.localDescription.sdp,constraintConfig:o,state:this.publishState};this._log.info("createOffer success, sending updated offer to remote server"),this._log.debug(`updatedOffer: ${n.sdp}`);let a=yield this._signalChannel.sendWaitForResponse({command:q.PUBLISH_CHANGE,data:n,responseCommand:V.UPDATE_OFFER_RESULT,timeout:Sa,commandDesc:"update offer"}),{code:c,message:d}=a.data;c!==0&&this.checkPublishResultCode(c,d),yield this.acceptAnswer(a.data.data),s.sdp&&this.updateSSRC(s.sdp)}catch(s){throw this._log.error(s),s}})}setBandwidth(n){return _(this,arguments,function*({bandwidth:e,type:t,videoType:s,sdp:o}){if(!Ps())return o?t===h.VIDEO?this.updateVideoBandwidthRestriction(o,e,s):this.updateAudioBandwidthRestriction(o,e):void 0;let a,c=this._peerConnection.getSenders();if(tt()){let d=0;t===h.VIDEO&&(s===h.SMALL?d=2:s===h.AUXILIARY?d=3:d=1),a=c[d]}else a=c.find(d=>d.track&&d.track.kind===t);if(a){let d=a.getParameters();(!d.encodings||d.encodings.length===0)&&(d.encodings=[{}]),d.encodings[0].maxBitrate=e*1e3;try{return yield a.setParameters(d),this._log.info(`${s||""}${t} bandwidth ${e} kbps`),o}catch(l){if(this._log.info(`failed to set bandwidth by setting maxBitrate: ${l}`),o)return t===h.VIDEO?this.updateVideoBandwidthRestriction(o,e,s):this.updateAudioBandwidthRestriction(o,e)}}return o})}updateVideoBandwidthRestriction(e,t,s){let o="AS";ie&&(o="TIAS",t=t*1e3);let n=0,a=-1;return s===h.SMALL?n=1:s===h.AUXILIARY&&(n=2),e=e.replace(/m=video (.*)\r\nc=IN (.*)\r\n/g,c=>(a+=1,a===n?`${c}b=${o}:${t}\r
73
73
  `:c)),e}updateAudioBandwidthRestriction(e,t){let s="AS";return ie&&(s="TIAS",t=t*1e3),e=e.replace(/m=audio (.*)\r\nc=IN (.*)\r\n/,`m=audio $1\r
@@ -92,4 +92,4 @@ void main() {
92
92
  }`,ra=class extends wr{constructor(e,t){super(e,t.input,{name:"vb",create2d:!1,useDefaultProgram:!1,useFbo:!1,createTexture:!0,logger:e.log});u(this,"ready",!1);u(this,"_bgTexture");u(this,"_waterMarkTexture");u(this,"_lastMaskTexture");u(this,"_lastMaskFbo");u(this,"_textureValid",!1);u(this,"_selfieTextureValid",!1);u(this,"_selfieSegmentation");u(this,"wasm");u(this,"_prePrograme");u(this,"_segmentationMask");u(this,"_weixin",!1);t.selfieSegmentation&&(this._selfieSegmentation=t.selfieSegmentation,this._selfieSegmentation.onResults=this.onPredict.bind(this)),this.init(t).catch(()=>this.context.destroy(new Error("selfie_segmentation init faild")))}init(e){return _(this,null,function*(){var o,n;let t=e.Wasm,s=this.context.ctx;if(this.wasm=new t.AllIn1(s),this.wasm.blurRadius=e.blurRadius||3,this.wasm.mirror=!!e.mirror,this.wasm.vbMode=e.bg==="blur"?1:e.bg instanceof HTMLImageElement?2:e.bg==="green"?3:0,e.waterMark){let{x:a,y:c,width:d,height:l}=e.waterMark;this.wasm.setWaterMark(a,c,d,l)}if(e.beautyParams){let{beauty:a,brightness:c,ruddy:d}=e.beautyParams;this.wasm.setBeauty(a,c,d,(o=this.context._canvas)==null?void 0:o.width,(n=this.context._canvas)==null?void 0:n.height)}if(this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),s.uniform1i(s.getUniformLocation(this.program,"mask"),1),e.bg instanceof HTMLImageElement&&(s.uniform1i(s.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(e.bg)),e.waterMark&&(s.uniform1i(s.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(e.waterMark.image)),s.uniform1i(s.getUniformLocation(this.program,"lastMask"),4),this._weixin){let a=this.context.createShader(s.FRAGMENT_SHADER,W_),c=this.context.createShader(s.VERTEX_SHADER,G_);this._prePrograme=this.context.createProgram(c,a),s.useProgram(this._prePrograme),this.setAttributes(this.positionBuffer,this.texCoordBuffer),s.uniform1i(s.getUniformLocation(this._prePrograme,"mask"),1)}this.ready=!0})}onPredict(e){var s;let t=this.context.ctx;this._weixin&&(this._lastMaskTexture||(this._lastMaskTexture=this.createTexture(this.image),this._lastMaskFbo=this.createFramebuffer(this._lastMaskTexture))),this.useProgram(),this._weixin?this.useTexture():this==null||this._selfieSegmentation.bindTexture(),t.activeTexture(t.TEXTURE1),(s=this._selfieSegmentation)==null||s.bindTexture2d(e),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),this.useBufferFrame(),t.drawArrays(t.TRIANGLE_STRIP,0,4),this._segmentationMask=e,this.totalFrames++}render(e){var a,c,d;let t=this.context.ctx;if(W(this.image.getVideoPlaybackQuality)&&Pe){let p=this.image.getVideoPlaybackQuality().totalVideoFrames;if(this._totalFrames===p)return!1;this._totalFrames=p,this.dropFrames=this._totalFrames-this.totalFrames}let{videoWidth:s,videoHeight:o}=this.image;this.image.width=s,this.image.height=o;let n=!1;if(this.totalFrames)this._weixin?this.useTexture():this==null||this._selfieSegmentation.bindTexture(),n=this._selfieTextureValid,this._selfieTextureValid=!0;else{if(this.program)this.useTexture();else return!1;n=this._textureValid,this._textureValid=!0}return this.width!==s||this.height!==o||!n?(this.resize(s,o),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.image)):t.texSubImage2D(t.TEXTURE_2D,0,0,0,t.RGBA,t.UNSIGNED_BYTE,this.image),this.ready&&(this._weixin&&(t.useProgram(this._prePrograme),this.useTexture(),this._segmentationMask&&(t.activeTexture(t.TEXTURE1),(a=this._selfieSegmentation)==null||a.bindTexture2d(this._segmentationMask),t.bindFramebuffer(t.FRAMEBUFFER,this._lastMaskFbo||null)),t.drawArrays(t.TRIANGLE_STRIP,0,4),(c=this._selfieSegmentation)==null||c.bindTexture(),this._segmentationMask?t.copyTexSubImage2D(t.TEXTURE_2D,0,0,0,0,0,s,o):t.copyTexImage2D(t.TEXTURE_2D,0,t.RGBA,0,0,s,o,0)),(d=this._selfieSegmentation)==null||d.send(s,o)),this.totalFrames||(t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),t.drawArrays(t.TRIANGLE_STRIP,0,4)),!1}close(){var t;super.close();let e=this.context.ctx;this._bgTexture&&e.deleteTexture(this._bgTexture),this._waterMarkTexture&&e.deleteTexture(this._waterMarkTexture),this._lastMaskTexture&&e.deleteTexture(this._lastMaskTexture),this._lastMaskFbo&&e.deleteFramebuffer(this._lastMaskFbo),this._prePrograme&&e.deleteProgram(this._prePrograme),(t=this.wasm)==null||t.close()}};var sa=class extends hh.EventEmitter{constructor(e){super();this.room=e;u(this,"videoContext");u(this,"_glVideoContext");u(this,"_2dVideoContext");u(this,"destination");u(this,"smallVideoContext");u(this,"smallDestination");u(this,"smallTrackSource");u(this,"smallImageSource");u(this,"_isMirror",!1);u(this,"cameraTrack");u(this,"cameraNode");u(this,"mirrorNode");u(this,"mixNode");u(this,"screenTrack");u(this,"screenNode");u(this,"selfModel",!1);u(this,"blurRadius",3);u(this,"arTrack");u(this,"Wasm");u(this,"waterMarkNode");u(this,"_waterMarkOption");u(this,"watermarkImageList",[]);u(this,"_beautyParams");u(this,"isUsingArTrack",!1);u(this,"_isMixScreen",!1);u(this,"_virtualBackground");u(this,"virtualBackgroundInstance");u(this,"_bgAssetPath");u(this,"log",I.createLogger({id:"vm"}));u(this,"_checkId",0);u(this,"_use2d",!1);u(this,"_autoSwitchRenderMode",!0);u(this,"_selfieSegmentation");u(this,"_seiEncodeProcessor");u(this,"_seiDecodeProcessor");u(this,"seiWorker");e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new Fe({frameRate:15,logger:this.log,name:"s"}),this.enablePrintDetail()}get _hasVirtualBg(){return!!this._virtualBackground}get _hasWaterMark(){return this.watermarkImageList.length>0}get renderMode(){return this._autoSwitchRenderMode?"auto":this._use2d?"2d":"webgl"}set renderMode(e){if(this._autoSwitchRenderMode=e==="auto",this._autoSwitchRenderMode)return;let t=e==="2d";this._use2d!==t&&(this._use2d=t,this.clear(),this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.update())}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new Fe({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this.sendCreateResult("videoCtx2d",this._2dVideoContext.ctx?void 0:new Error("create 2d context failed")),this._2dVideoContext}getGlVideoContext(){if(!this._glVideoContext)this._glVideoContext=new ye({frameRate:15,logger:this.log,name:"m"});else if(this._glVideoContext.available)return this._glVideoContext;try{this._glVideoContext.create(),this.sendCreateResult(),this._glVideoContext.on("unavailable",(e,t)=>{this.emit("error",{reason:e,error:t}),this.log.warn("video context unavailable",e,t),this.sendCreateResult("videoCtxGl",t||new Error(e)),this.update()})}catch(e){this.emit("error",{reason:"create",error:e}),this.sendCreateResult("videoCtxGl",e)}return this._glVideoContext}enablePrintDetail(e=2e3){this._checkId=re.run(Vi,()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:e})}destroy(){var e,t;(e=this._2dVideoContext)==null||e.destroy(),(t=this._glVideoContext)==null||t.destroy(),this.smallVideoContext.destroy(),re.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(Ir||this._isMixScreen||this._isMirror||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}sendCreateResult(e="videoCtxGl",t){let s=e==="videoCtxGl"?512700:512701;t?D.addFailedEvent({key:s,error:t}):D.addSuccessEvent({key:s})}checkOrCreateVideoContext(){let e=this._use2d;if(this._autoSwitchRenderMode&&(this._use2d=!this._hasVirtualBg),this.videoContext)if(this.videoContext.available){let t=!this.videoContext.hasAlpha&&this.needAlpha;if(this._autoSwitchRenderMode&&e===this._hasVirtualBg)this.clear();else if(t)if(this._use2d)this.clear();else return!0;else return!0}else this.clear(),this._use2d=!0;return this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.videoContext.available}get smallTrack(){var e;return(e=this.smallDestination)==null?void 0:e.videoTrack}get hasSmall(){return!!this.smallTrack}get initialTrack(){var e;return(e=this.cameraTrack)==null?void 0:e.mediaTrack}initVirtualBackground(e){return this._selfieSegmentation=e,this._selfieSegmentation.changeModel()}_setMainOutput(e){var t;try{let s=this.cameraTrack,{small:o,settings:n,player:a}=s;o?(this.smallVideoContext.available||(this.smallVideoContext.create({alpha:!1}),this.smallDestination=new Dn(this.smallVideoContext,o)),this.smallVideoContext.frameRate=o.frameRate,this.smallDestination.resolution=o,e?(this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=e:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(e),this.smallImageSource.connect(this.smallDestination))):(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource?this.smallTrackSource.replaceTrack(this.initialTrack):(this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack,"smallTrackSource"),this.smallTrackSource.width=n.width,this.smallTrackSource.height=n.height,this.smallTrackSource.connect(this.smallDestination)))):this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource),Ir&&a.setCanvas(e);let c=e&&((t=this.destination)==null?void 0:t.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),c=this.arTrack),this._selfieSegmentation&&e&&!this._use2d&&(this._selfieSegmentation._glName||this._selfieSegmentation.setCanvas(e)),this.log.info(`set main output ${c?c.label:"no output track"}`),s.setOutputMediaStreamTrack(c)}catch(s){this.log.error("set main output failed",s)}}update(){return _(this,null,function*(){var s,o;if(!this.cameraTrack||!this.cameraTrack.mediaTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:e,profile:t}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams?(this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination",logger:this.log})),this.cameraNode?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraNodeSource"),this.cameraNode.resize(e.width,e.height))):(this.cameraNode&&this.cameraNode.close(),this.destination||(this.destination=new vn(this.videoContext,{name:"mainDestination",logger:this.log})),this.cameraNode=new ra(this.videoContext,{input:this.cameraTrack.mediaTrack,mirror:this._isMirror,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,beautyParams:this._beautyParams,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,selfieSegmentation:this._selfieSegmentation,Wasm:this.Wasm}),this.cameraNode.connect(this.destination)),this.videoContext.frameRate=t.frameRate,this._use2d){let n=this.cameraNode;n.disconnect(),this._isMirror&&(this.mirrorNode||(this.mirrorNode=new ta(this.videoContext)),n=n.connect(this.mirrorNode),n.disconnect(),this.log.info("start mirror")),this.mixNode&&this.mixNode.close(),delete this.mixNode,(this._isMixScreen||this._hasWaterMark)&&(this.mixNode=new ia(this.videoContext),n.connect(this.mixNode,{zIndex:1}),this._hasWaterMark&&!this.waterMarkNode&&this._waterMarkOption&&(this.waterMarkNode=this.videoContext.createVideoImageSource(this._waterMarkOption.image,{autoResize:!1,logger:this.log}),this.waterMarkNode.resize(this._waterMarkOption.width,this._waterMarkOption.height),this.waterMarkNode.x=this._waterMarkOption.x,this.waterMarkNode.y=this._waterMarkOption.y),(s=this.waterMarkNode)==null||s.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&!this.screenNode&&(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource")),(o=this.screenNode)==null||o.connect(this.mixNode,{zIndex:0}),n=this.mixNode,this.log.info("start mix",`${this.mixNode.width}x${this.mixNode.height}`)),n.connect(this.destination)}return this.log.info(`update ${this._use2d?"2d":"webgl"}`),this._setMainOutput(this.videoContext._canvas)})}changeInput(e){var t,s,o,n;if(e instanceof ze)return this.log.info("change screen input",(t=e.mediaTrack)==null?void 0:t.label),this.setScreenTrack(e);if(e instanceof le)return this.log.info("change video input",(s=e.mediaTrack)==null?void 0:s.label),this.setCameraTrack(e);if(e instanceof Tt){this.log.info("change remote input",(o=e.mediaTrack)==null?void 0:o.label);let a=e.mediaTrack;return this._seiDecodeProcessor&&(e.pipeline[1]=this._seiDecodeProcessor),e.setOutputMediaStreamTrack(a)}this.log.warn("change unknown input",(n=e.mediaTrack)==null?void 0:n.label)}configPipeline(e){e instanceof Tt&&this._seiDecodeProcessor&&(e.pipeline[1]=this._seiDecodeProcessor)}removeInput(e){var t;e instanceof ze?((t=this.screenNode)==null||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof le?(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof Tt&&e.source&&e.source.context.destroy()}setCameraTrack(e){return _(this,null,function*(){this.cameraTrack=e,this._seiEncodeProcessor&&(this.cameraTrack.pipeline[0]=this._seiEncodeProcessor),this.update()})}setScreenTrack(e){return this.screenTrack=e,this._seiEncodeProcessor&&(this.screenTrack.pipeline[0]=this._seiEncodeProcessor),this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)}getWatermarkImage(e,t){return _(this,null,function*(){let s=document.createElement("canvas");t&&e&&(s.height=t,s.width=e);let o=s.getContext("2d");if(!o)throw new b({code:A.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort((n,a)=>n.zIndex-a.zIndex),this.watermarkImageList.forEach(({image:n,x:a,y:c,width:d,height:l})=>{o.drawImage(n,a,c,d,l)}),Os(s.toDataURL())})}pushWaterMarkImageList(e){let{type:t}=e;this.watermarkImageList.some(o=>o.imageUrl===e.imageUrl&&o.height===e.height&&o.width===e.width&&o.x===e.x&&o.y===e.y&&o.type===e.type&&o.zIndex===e.zIndex)||((t==="mute"||t==="watermark")&&(this.watermarkImageList=this.watermarkImageList.filter(o=>o.type!==t)),this.watermarkImageList.push(e))}setBeautyParams(e){return _(this,null,function*(){this._beautyParams=e,this.update()})}stopBeauty(){return _(this,null,function*(){this._beautyParams=void 0,this.update()})}setWatermark(e){return _(this,null,function*(){let t;try{t=yield Os((e==null?void 0:e.imageElement)||e.imageUrl)}catch(l){throw new b({code:A.INVALID_PARAMETER,message:`load image failed, url: ${e.imageUrl}`})}let{x:s=0,y:o=0,width:n=t.width,height:a=t.height,type:c="watermark",zIndex:d=2}=e;this.pushWaterMarkImageList({x:s,y:o,width:n,height:a,image:t,zIndex:d,type:c,imageUrl:e.imageUrl}),yield this.freshWatermark(),this.log.info("set watermark",JSON.stringify(this.watermarkImageList))})}deleteWatermark(e="watermark"){return _(this,null,function*(){this.watermarkImageList=this.watermarkImageList.filter(t=>t.type!==e),this.log.info("delete watermark",e,JSON.stringify(this.watermarkImageList)),yield this.freshWatermark()})}freshWatermark(){return _(this,null,function*(){var t,s,o;(t=this.waterMarkNode)==null||t.close(),delete this.waterMarkNode,delete this._waterMarkOption;let e=yield this.getWatermarkImage((s=this.cameraTrack)==null?void 0:s.settings.width,(o=this.cameraTrack)==null?void 0:o.settings.height);this._waterMarkOption={x:0,y:0,width:e.width,height:e.height,image:e},this.update()})}setVirtualBackground(e){return _(this,null,function*(){if(!e)this._virtualBackground=void 0;else{if(this._use2d&&!this._autoSwitchRenderMode)return Promise.reject(new Error("not support virtual background in 2d mode"));this._bgAssetPath=e.assetPath,e.type==="image"?this._virtualBackground=yield Os(e.imageUrl):(this.blurRadius=e.blurLevel||this.blurRadius||3,this._virtualBackground=e.type)}this.log.info(`${this._virtualBackground?"start":"stop"} virtual background, ${(e==null?void 0:e.type)||""}, ${this.blurRadius||""}`),this.update()})}get mixScreen(){return this._isMixScreen}set mixScreen(e){var t;this._isMixScreen=e,this._isMixScreen||((t=this.screenNode)==null||t.close(),delete this.screenNode),this.update()}set mirror(e){var t;this._isMirror!==e&&(this._isMirror=e,this._isMirror||((t=this.mirrorNode)==null||t.close(),delete this.mirrorNode),this.update())}get mirror(){return this._isMirror}enableAr(e){this.arTrack=e,this.isUsingArTrack=!0,this.update()}updateAr(){return _(this,null,function*(){var e;!((e=this.cameraTrack)!=null&&e.mediaTrack)||(yield this.virtualBackgroundInstance.ar.updateInputTrack(this.cameraTrack.mediaTrack.clone()))})}disableAr(){var e;this.isUsingArTrack=!1,(e=this.arTrack)==null||e.stop(),this.arTrack=void 0,this.update()}clear(){var e;(e=this.videoContext)==null||e.disconnect(),delete this.destination,delete this.cameraNode,delete this.mirrorNode,delete this.screenNode,delete this.waterMarkNode}enableSEI({encoder:e,decoder:t,seiWorker:s}){s?this.seiWorker=s:(this._seiEncodeProcessor=e,this._seiDecodeProcessor=t,this.cameraTrack&&(this.cameraTrack.pipeline[0]=this._seiEncodeProcessor),this.screenTrack&&(this.screenTrack.pipeline[0]=this._seiEncodeProcessor))}disableSEI(){var e;(e=this.seiWorker)==null||e.terminate(),delete this.seiWorker,delete this._seiEncodeProcessor,delete this._seiDecodeProcessor,this.cameraTrack&&(this.cameraTrack.pipeline[0]=void 0),this.screenTrack&&(this.screenTrack.pipeline[0]=void 0)}};var J_=0;var oa=class extends F{constructor(e){super("room");this.seq=++J_;this.role="anchor";this.joinParams=null;this.localTracks=new Set;this.enableAutoPlayDialog=!0;this.autoReceiveAudio=!0;this.autoReceiveVideo=!0;this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null};this._isUsingCachedSchedule=!1;this._log=I.createLogger({id:`r${this.seq}`});this._joinedTimestamp=0;this.isDestroyed=!1;this.useStringRoomId=!!e.useStringRoomId,de(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),de(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),de(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new dh({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new uh({room:this}),this.badCaseDetector=new lh({room:this}),this.audioManager=new bn(this),this.videoManager=new sa(this)}get isMainStreamPublished(){for(let e of this.localTracks)if(e.mediaType&4)return!0;return!1}get isAuxStreamPublished(){for(let e of this.localTracks)if(e.mediaType&2)return!0;return!1}get hasAuxStream(){for(let e of this.remotePublishedUserMap.values())if(e.muteState.hasAuxiliary)return!0;return this.isAuxStreamPublished}get localMainVideoTrack(){for(let e of this.localTracks)if(e.mediaType&4)return e;return null}get localAuxVideoTrack(){for(let e of this.localTracks)if(e.mediaType&2)return e;return null}getLogger(){return this._log}get isJoining(){return this.state.toString()==="joining"}get isJoined(){return this.state==="joined"}get isLeft(){return this.state==="left"}addTrack(e){return _(this,null,function*(){return this.publish(e)})}removeTrack(e){return _(this,null,function*(){return this.unpublish(e)})}replaceTrack(e){return _(this,null,function*(){})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(Y(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(Je(e)){let{websocketProxy:t,webtransportProxy:s,loggerProxy:o,scheduleProxy:n,unifiedProxy:a}=e;this.proxy_ws=t,this.proxy_wt=s,this.proxy_unified=a,a?(Fa([a,a]),Li(`https://${a}`)):(o&&Li(o),n&&Fa(n))}g.once(E.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:Ii.main,sched_back_domain:Ii.backup,signal_domain:this.proxy_ws||this.proxy_wt||""}))}getRemoteAudioStats(){return _(this,null,function*(){let e={};return this.remotePublishedUserMap.forEach(t=>{e[t.userId]=t.remoteAudioTrack.stat}),e})}getTransportStats(){return _(this,null,function*(){var t;let e={rtt:((t=this.quality)==null?void 0:t.uplinkRTT)||0,downlinksRTT:{}};if(this.quality)for(let s of this.quality.downlinkInfo)e.downlinksRTT[s.userId]=s.rtt;return e})}getRemoteVideoStats(){return _(this,arguments,function*(e="main"){let t={};return this.remotePublishedUserMap.forEach(s=>{let o=e==="auxiliary"?s.remoteAuxiliaryTrack:s.remoteVideoTrack;t[s.userId]=o.stat}),t})}checkDestroy(){if(this.isDestroyed)throw new b({code:A.INVALID_OPERATION,message:L({key:M.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(Ae.INVALID_DESTROY),new b({code:A.INVALID_OPERATION,message:L({key:M.INVALID_DESTROY})});this._log.info("destroy room"),this.audioManager.destroy(),this.videoManager.destroy(),this.keyPointManager.destroy(),this.callDurationCalculator.destroy(),this.badCaseDetector.destroy(),this.isDestroyed=!0,g.emit(E.ROOM_DESTROY,{room:this})}schedule(e,t){return _(this,null,function*(){var o,n;let s=x();try{let{isCached:a,result:c,detailCost:d}=yield uu({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:Re,userSig:this.userSig,role:this.scene==="live"?e.role:void 0,frameWorkType:t,latencyLevel:e.latencyLevel});this._isUsingCachedSchedule=a,this._log.info(`schedule cache:${+a} ${pt(c,{keysToExclude:["username","credential"]})}`),a&&g.once(E.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=N(N({},this.scheduleResult),c),ee((o=c.config)==null?void 0:o.retryCount)&&Ta(c.config.retryCount),Y((n=c.config)==null?void 0:n.loggerDomain)&&Li(c.config.loggerDomain),g.emit(E.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:d}),D.addSuccessEvent({key:521700,cost:x()-s,split:50})}catch(a){throw D.addFailedEvent({key:521700,error:a}),a}})}};var ph=Se(Ne(),1);var mh=Symbol("instance"),CL=Symbol("abortCtrl"),xd=Symbol("cacheResult"),lo=class{constructor(i,e,t){this.oldState=i,this.newState=e,this.action=t,this.aborted=!1}abort(i){this.aborted=!0,po.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},ho=class extends Error{constructor(i,e,t){super(e),this.state=i,this.message=e,this.cause=t}};function j_(r){return typeof r=="object"&&r&&"then"in r}var mo=new Map;function Pd(r,i,e={}){return(t,s,o)=>{let n=e.action||s;if(!e.context){let c=mo.get(t)||[];mo.has(t)||mo.set(t,c),c.push({from:r,to:i,action:n})}let a=o.value;o.value=function(...c){let d=this;if(e.context&&(d=ne.get(typeof e.context=="function"?e.context.call(this,...c):e.context)),d.state===i)return d[xd];d.state instanceof lo&&d.state.action==e.abortAction&&d.state.abort(d);let l=null;if(Array.isArray(r)?r.length==0?d.state instanceof lo&&d.state.abort(d):(typeof d.state!="string"||!r.includes(d.state))&&(l=new ho(d._state,`${d.name} ${n} to ${i} failed: current state ${d._state} not in from config`)):r!==d.state&&(l=new ho(d._state,`${d.name} ${n} to ${i} failed: current state ${d._state} not from ${r}`)),l)if(e.fail)e.fail.call(this,l);else{if(e.ignoreError)return l;throw l}let p=d.state,m=new lo(p,i,n);po.call(d,m);let f=C=>{var v;return d[xd]=C,m.aborted||(po.call(d,i),(v=e.success)===null||v===void 0||v.call(this,d[xd])),C},R=C=>{let v=C instanceof Error?C.message:String(C);if(po.call(d,p,C),e.fail)e.fail.call(this,new ho(d._state,`action '${n}' failed :${v}`,C instanceof Error?C:new Error(v)));else{if(e.ignoreError)return C;throw C}};try{let C=a.apply(this,c);return j_(C)?C.then(f).catch(R):f(C)}catch(C){R(C)}}}}var q_=(()=>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 po(r,i){let e=this._state;this._state=r;let t=r.toString();r&&this.emit(t,e),this.emit(ne.STATECHANGED,r,e,i),this.updateDevTools({value:r,old:e,err:i instanceof Error?i.message:String(i)})}var ne=class extends ph.default{constructor(i,e,t){super(),this.name=i,this.groupName=e,this._state=ne.INIT,i||(i=Date.now().toString(36)),t?Object.setPrototypeOf(this,t):t=Object.getPrototypeOf(this),e||(this.groupName=this.constructor.name);let s=t[mh];s?this.name=s.name+"-"+s.count++:t[mh]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let i=Object.getPrototypeOf(this),e=mo.get(i)||[],t=new Set,s=[],o=[],n=new Set,a=Object.getPrototypeOf(i);mo.has(a)&&(a.stateDiagram.forEach(d=>t.add(d)),a.allStates.forEach(d=>n.add(d))),e.forEach(({from:d,to:l,action:p})=>{typeof d=="string"?s.push({from:d,to:l,action:p}):d.length?d.forEach(m=>{s.push({from:m,to:l,action:p})}):o.push({to:l,action:p})}),s.forEach(({from:d,to:l,action:p})=>{n.add(d),n.add(l),n.add(p+"ing"),t.add(`${d} --> ${p}ing : ${p}`),t.add(`${p}ing --> ${l} : ${p} \u{1F7E2}`),t.add(`${p}ing --> ${d} : ${p} \u{1F534}`)}),o.forEach(({to:d,action:l})=>{t.add(`${l}ing --> ${d} : ${l} \u{1F7E2}`),n.forEach(p=>{p!==d&&t.add(`${p} --> ${l}ing : ${l}`)})});let c=[...t];return Object.defineProperties(i,{stateDiagram:{value:c},allStates:{value:n}}),c}static get(i){let e;return typeof i=="string"?(e=ne.instances.get(i),e||ne.instances.set(i,e=new ne(i,void 0,Object.create(ne.prototype)))):(e=ne.instances2.get(i),e||ne.instances2.set(i,e=new ne(i.constructor.name,void 0,Object.create(ne.prototype)))),e}static getState(i){var e;return(e=ne.get(i))===null||e===void 0?void 0:e.state}updateDevTools(i={}){q_(ne.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){po.call(this,i)}};ne.STATECHANGED="stateChanged";ne.UPDATEAFSM="updateAFSM";ne.INIT="[*]";ne.ON="on";ne.OFF="off";ne.instances=new Map;ne.instances2=new WeakMap;var Ch=Se(Ne());var wd=Se(Rd());var _h=r=>{let i=ce(r),e={audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0};return i.media.forEach((t,s)=>{var o;if(t.ssrcs&&!T(t.ssrcs[0].id)){let n=Number(t.ssrcs[0].id),a=Number((o=t.ssrcs.filter(c=>c.attribute==="cname")[1])==null?void 0:o.id);switch(s){case 0:e.audioSsrc=n;break;case 1:e.bigVideoSsrc=n,e.bigVideoRtxSsrc=a;break;case 2:e.smallVideoSsrc=n,e.smallVideoRtxSsrc=a;break;case 3:e.auxVideoSsrc=n,e.auxVideoRtxSsrc=a;break}}}),e};function fh(r){var e;let i=[];for(let t=0;t<r.rtp.length;t++){if(["rtx","red","ulpfec"].includes(r.rtp[t].codec))continue;let s=r.fmtp.filter(o=>o.payload===r.rtp[t].payload)[0];i.push({payload:r.rtp[t].payload,codec:r.rtp[t].codec,fmtp:s?s.config:"",rate:r.rtp[t].rate,rtx:((e=r.rtp[t+1])==null?void 0:e.codec)==="rtx"?r.rtp[t+1].payload:0,rtcpFb:((r==null?void 0:r.rtcpFb)||[]).filter(o=>o.payload===r.rtp[t].payload).map(({type:o,subtype:n})=>({id:o,params:n?[n]:[]}))})}return i}function X_(){return _(this,null,function*(){let r=new RTCPeerConnection;r.addTransceiver(h.VIDEO,{direction:h.TRANSCEIVER_DIRECTION_RECVONLY});let i=yield r.createOffer();if(!i.sdp)return[];let e=ce(i.sdp),t=fh(e.media[0]);return r.close(),t})}var Eh=(r,i)=>_(void 0,null,function*(){var c;let e=ce(r),t={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],decoders:[],extensions:[]},useDataChannel:!1};t.ice.ufrag=String(e.media[0].iceUfrag),t.ice.password=e.media[0].icePwd||"",e.fingerprint&&(t.dtls.hash=e.fingerprint.type,t.dtls.fingerprint=e.fingerprint.hash,t.dtls.setup=e.setup||""),e.media[0].fingerprint&&(t.dtls.hash=e.media[0].fingerprint.type,t.dtls.fingerprint=e.media[0].fingerprint.hash),t.dtls.setup=e.media[0].setup||"";let s=e.media[0],o=e.media[1];s.ext&&(t.audio.extensions=s.ext.map(d=>({id:d.value,uri:d.uri}))),o.ext&&(t.video.extensions=o.ext.map(d=>({id:d.value,uri:d.uri})));let n={codec:s.rtp[0].codec,fmtp:s.fmtp[0].config,payload:s.fmtp[0].payload,rate:s.rtp[0].rate,channel:s.rtp[0].encoding,rtcpFb:[],rtx:0};(c=s.rtcpFb)==null||c.forEach(({payload:d,type:l,subtype:p})=>{if(d===n.payload){let m={id:l,params:[]};p&&m.params.push(p),n.rtcpFb.push(m)}}),t.audio.codecs.push(n);let a=["h264","vp8"];return i&&a.shift(),t.video.codecs=[...fh(o)].filter(d=>a.includes(d.codec.toLocaleLowerCase())),t.video.decoders=(yield X_()).filter(d=>["h264","vp8"].includes(d.codec.toLocaleLowerCase())),t}),gh=({serverAbility:r,clientAbility:i,offerSDP:e,enableCustomMessage:t})=>{let s=ce(e),o={extmapAllowMixed:"extmap-allow-mixed",groups:s.groups,icelite:"ice-lite",media:[],msidSemantic:{semantic:"",token:"WMS"},name:"-",origin:{address:"127.0.0.1",username:"-",sessionId:String(Date.now()),sessionVersion:1,netType:"IN",ipVer:4},timing:{start:0,stop:0},version:0},n={candidates:r.candidates.map(a=>({component:1,foundation:"1",generation:0,ip:a.ip,port:a.port,priority:a.priority,transport:a.foundation,type:a.type})),connection:{version:4,ip:"0.0.0.0"},direction:h.TRANSCEIVER_DIRECTION_RECVONLY,ext:r.audio.extensions.map(a=>({value:a.id,uri:a.uri})),fingerprint:{type:r.dtls.hash,hash:r.dtls.fingerprint},fmtp:[{payload:r.audio.codecs[0].payload,config:r.audio.codecs[0].fmtp}],icePwd:r.ice.password,iceUfrag:r.ice.ufrag,mid:"0",payloads:String(r.audio.codecs[0].payload),port:s.media[0].port,protocol:s.media[0].protocol,type:h.AUDIO,setup:r.dtls.setup,rtcpFb:r.audio.codecs[0].rtcpfb.map(a=>({payload:r.audio.codecs[0].payload,type:a.id,subtype:a.params[0]})),rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[{payload:r.audio.codecs[0].payload,codec:r.audio.codecs[0].codec,rate:r.audio.codecs[0].rate,encoding:r.audio.codecs[0].channels}]};return o.media.push(n),[1,2,3].forEach(a=>{o.media.push(Vd({mid:a,serverAbility:r,clientAbility:i,parsedOffer:s}))}),t&&o.media.push(s.media.find(a=>a.mid==="dc")),He(o)},Vd=({mid:r,serverAbility:i,clientAbility:e,parsedOffer:t,isDownlink:s=!1})=>{let o={candidates:i.candidates.map(n=>({component:1,foundation:"1",generation:0,ip:n.ip,port:n.port,priority:n.priority,transport:n.foundation,type:n.type})),connection:{version:4,ip:"0.0.0.0"},direction:h.TRANSCEIVER_DIRECTION_RECVONLY,ext:i.video.extensions.map(n=>({value:n.id,uri:n.uri})),fingerprint:{type:i.dtls.hash,hash:i.dtls.fingerprint},fmtp:[],icePwd:i.ice.password,iceUfrag:i.ice.ufrag,mid:String(r),payloads:"",port:t.media[0].port,protocol:t.media[0].protocol,type:h.VIDEO,setup:i.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(s)(i.video.decoders||i.video.codecs).forEach(n=>{or(o,n)});else{let n=i.video.codecs.findIndex(c=>c.codec.toLowerCase()===(i.useVp8?"vp8":"h264")),a=i.video.codecs[n]||e.video.codecs[0];or(o,a)}return o},or=(r,i)=>{r.payloads=`${r.payloads} ${i.payload}`.trim(),r.fmtp.push({payload:i.payload,config:i.fmtp}),r.rtcpFb=[...r.rtcpFb||[],...(i.rtcpfb||i.rtcpFb).map(e=>({payload:i.payload,type:e.id,subtype:e.params[0]}))],r.rtp.push({payload:i.payload,codec:i.codec.toUpperCase(),rate:i.rate}),i.rtx&&(r.payloads=`${r.payloads} ${i.rtx}`,r.fmtp.push({payload:i.rtx,config:`apt=${i.payload}`}),r.rtp.push({payload:i.rtx,codec:"rtx",rate:i.rate}))};function Q_(r){let i=new Set(["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.ext&&(r.ext=r.ext.filter(e=>!i.has(e.uri)))}function z_(r){if(!r.rtcpFb)return;let i=[];r.rtcpFb.forEach((e,t)=>{var s;i.push(e),r.rtcpFb&&((s=r.rtcpFb[t+1])==null?void 0:s.payload)!==e.payload&&e.type!=="rrtr"&&i.push({payload:e.payload,type:"rrtr"})}),r.rtcpFb=i}function Y_(r){r.type===h.VIDEO&&r.fmtp&&r.fmtp.forEach(i=>{i.config.includes("apt")||(i.config+=";sps-pps-idr-in-keyframe=1")})}function K_(r){r.type===h.AUDIO&&r.fmtp&&r.fmtp.forEach(i=>{i.config+=";sprop-stereo=1;stereo=1"})}var Th=(r,i,e)=>{let t=wd.default.parse(r);return t.media.forEach((s,o)=>{var n;(s.type===h.AUDIO||s.type===h.VIDEO)&&(z_(s),Y_(s),K_(s),Q_(s),s.type===h.VIDEO&&(o<4?(s.payloads="",s.fmtp=[],s.rtp=[],s.rtcpFb=[],i.video.codecs.forEach(a=>or(s,a))):e&&(s.payloads="",s.fmtp=[],s.rtp=[],s.rtcpFb=[],(e.video.decoders||e.video.codecs).forEach(a=>or(s,a))))),((n=s.payloads)==null?void 0:n.includes("datachannel"))&&t.groups&&s.mid&&(t.groups[0].mids=t.groups[0].mids.replace(s.mid,"dc"),s.mid="dc")}),wd.default.write(t)};var Sh=Se(Ne());var na=class extends Sh.EventEmitter{constructor(e){super();this.room=e;u(this,"mainFpsHealth",1);u(this,"mainBitrateHealth",1);u(this,"badMainBitrateHealthCount",0);u(this,"lastEmitBadHealthTime",0);u(this,"log");!pe&&Pe&&g.on("262",this.onVideoCodecChanged,this),this.log=e.getLogger().createChild({id:"h-d"})}onVideoCodecChanged({remoteUserId:e,streamType:t,isHWCodec:s,codec:o}){if(!(e||t===7||o!=="h264")){if(!s){this.room.off("heartbeat-report",this.onHeartbeatReport,this);return}this.room.listeners("heartbeat-report").includes(this.onHeartbeatReport)||this.room.on("heartbeat-report",this.onHeartbeatReport,this)}}onHeartbeatReport(e){Date.now()-this.lastEmitBadHealthTime<30*1e3||(e.msg_up_stream_info.msg_video_status.forEach(t=>{if(t.uint32_video_enc_fps&&t.uint32_video_capture_fps){let s=t.uint32_video_enc_fps/t.uint32_video_capture_fps;t.uint32_video_stream_type===2&&(this.mainFpsHealth=s)}if(t.uint32_video_codec_bitrate&&t.uint32_video_stream_type===2){let{localMainVideoTrack:s}=this.room;s&&(this.mainBitrateHealth=t.uint32_video_codec_bitrate/1e3/s.profile.bitrate)}}),this.log.debug(`mainBitrateHealth: ${this.mainBitrateHealth} mainFpsHealth: ${this.mainFpsHealth}`),this.mainBitrateHealth>.5&&(this.badMainBitrateHealthCount=0),this.mainFpsHealth>.9&&this.mainBitrateHealth<.5&&(this.badMainBitrateHealthCount++,this.badMainBitrateHealthCount>3&&(this.badMainBitrateHealthCount=0,this.lastEmitBadHealthTime=Date.now(),this.log.warn(`bad main bitrate health: ${this.mainBitrateHealth}`),this.emit("1",{isAux:!1}))))}destroy(){g.off("262",this.onVideoCodecChanged,this),this.room.off("heartbeat-report",this.onHeartbeatReport,this)}};u(na,"EVENT_BAD_HEALTH","bad_health");var Ih=na;var Wt=(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))(Wt||{}),Rh=0,yh=!1,Z_=new Set,ef=r=>Rh>2&&!yh&&Z_.size===0&&r,tf=1,ui=class extends Ch.default{constructor({signalChannel:e,room:t,enableCustomMessage:s}){super();u(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0});u(this,"currentState","DISCONNECTED");u(this,"_room");u(this,"_signalChannel");u(this,"_peerConnection",null);u(this,"_datachannel",null);u(this,"_enableCustomMessage");u(this,"_log");u(this,"_downlinkMIDMap",new Map);u(this,"_downlinkMIDUserIDMap",new Map);u(this,"_reconnectionTimer",-1);u(this,"reconnectionCount",0);u(this,"clientAbility");u(this,"_serverAbility",null);u(this,"addDownlinkQueue",new Set);u(this,"removeDownlinkQueue",new Set);u(this,"_parsedAnswer",null);u(this,"_updateSDPPromise",null);u(this,"_waitForPCConnectedPromise");u(this,"_waitForPCConnectedPromiseReject",null);u(this,"_isSDPLogged",!1);u(this,"enableInsertableStreams",!1);u(this,"insertableStreamsAbortMap",new Map);this._room=t,this._enableCustomMessage=s,this._signalChannel=e,this._log=I.createLogger({id:`spc${tf++}`,userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableSEI&&Or&&(this.enableInsertableStreams=!0),this._room.healthDetector.on("1",({isAux:o})=>{this.useHWEncoder(!1,o?7:2)})}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 s;(s=this.insertableStreamsAbortMap.get(e))==null||s.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,s;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():(s=this._serverAbility)!=null&&s.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?_h(this._peerConnection.localDescription.sdp):{audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0}}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 _(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 s=this._peerConnection.iceConnectionState;this._log.debug(`ice state: ${s}`),s==="checking"&&this.stat.iceStartTime===0?this.stat.iceStartTime=Date.now():s==="connected"&&this.stat.iceEndTime===0&&(this.stat.iceEndTime=Date.now())},this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this._peerConnection.ontrack=s=>this.emit("track",s),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=s=>{let o=new Bd(s.data);this.emit("data_channel_msg",{data:o})},this._datachannel.onerror=s=>{this._log.warn("datachannel error",s)}),this._peerConnection.addTransceiver(h.AUDIO,{direction:h.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:h.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:h.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:h.TRANSCEIVER_DIRECTION_SENDONLY}),e=yield this._peerConnection.createOffer(),this.clientAbility=yield Eh(e.sdp,((t=this._room.scheduleResult.config)==null?void 0:t.remove264FromSDP)||!1),yield this.setOffer(e),this.dtlsTransport&&(this.dtlsTransport.onstatechange=()=>{let{dtlsTransport:s}=this;!s||(this._log.debug(`dtls state: ${s.state}`),s.state==="connecting"&&this.stat.dtlsStartTime===0?this.stat.dtlsStartTime=Date.now():s.state==="connected"&&this.stat.dtlsEndTime===0&&(this.stat.dtlsEndTime=Date.now()))}),D.addSuccessEvent({key:521707}),this.clientAbility}catch(s){throw D.addFailedEvent({key:521707,error:s}),this._log.error(`initialize failed ${s}
93
93
  offer: ${e==null?void 0:e.sdp}`),s}})}connect(e,t=!1){return _(this,null,function*(){try{if(this.currentState==="CONNECTED")return;let s=x(),o={type:"answer",sdp:gh({serverAbility:e,clientAbility:this.clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(o),yield this.waitForPeerConnectionConnected(),t||D.addSuccessEvent({key:521703,cost:x()-s})}catch(s){let o=s instanceof b&&s.code===A.API_CALL_ABORTED;throw o||this._log.error(`connect failed: ${s}`,e),this.reset(),!o&&!this.isReconnecting&&(D.addFailedEvent({key:521703,error:s}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),s}})}reconnect(){return _(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(_e.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:q.REBUILD_PEER_CONNECTION,responseCommand:V.REBUILD_PEER_CONNECTION_RES,data:{ability:e},enableLog:!1});if(t.data.code!==0)throw new b({code:t.data.code,message:t.data.message});yield this.connect(t.data.data.ability,!0),D.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),g.emit(E.SPC_RECONNECTED,{room:this._room}),this.emit("spc-reconnected")}catch(e){if(!this.isReconnecting)return;if(e!=null&&e.message.includes("timeout")){let t=kt(this.reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${t/1e3}s`),this._reconnectionTimer=window.setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},t)}else this._log.error(`reconnect() failed ${e==null?void 0:e.code} ${e}`),D.addFailedEvent({key:521704,error:e}),this.reconnectionCount>=qt()&&this._log.warn(`SDK has tried reconnect for ${qt()} times, but all failed, please check your network`),this.stopReconnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.emit("error")}})}getPeerConnection(){return this._peerConnection}startReconnection(){return _(this,null,function*(){this._log.warn("start reconnect"),this._updateSDPPromise=null,this.emitConnectionStateChangedEvent("RECONNECTING"),yield this.reconnect()})}stopReconnection(){this.isReconnecting&&(this._log.info("stop reconnect"),this.reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(_e.CONNECTED,this.reconnect,this))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&((e=this._peerConnection)==null?void 0:e.connectionState)===se.CLOSED&&this.startReconnection()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}onConnectionStateChange(e){let t=this._peerConnection.iceConnectionState,s=this.getDTLSTransportState();this._log.info(`connectionState: ${e.target.connectionState} ICE: ${t} DTLS: ${s}`),e.target.connectionState===se.CONNECTING&&(this.stat.peerConnectionStartTime===0&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(e.target.connectionState===se.FAILED||e.target.connectionState===se.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),(e.target.connectionState===se.CONNECTED||e.target.connectionState===se.COMPLETED)&&(this.stat.peerConnectionEndTime===0&&(this.stat.peerConnectionEndTime=Date.now()),g.emit(E.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 nt;let e=null;return!Ri()||this._peerConnection.getSenders().length===0?nt:(e=this._peerConnection.getSenders()[0].transport,!$i()||this._peerConnection.getReceivers().length===0?nt:e?e.state:nt)}emitConnectionStateChangedEvent(e){e!==this.currentState&&(this.currentState==="RECONNECTING"&&e==="CONNECTING"||(this.emit(Wt.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:e}),this.currentState=e))}logSelectedCandidate(){return _(this,null,function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[t,s]of e)if(Ci(s)){let o=e.get(s.localCandidateId),n=e.get(s.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&&Ha(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();this._waitForPCConnectedPromiseReject=t;let s=c=>{c.state==="CONNECTED"&&(clearTimeout(a),n(),e())},o=({room:c})=>{c===this._room&&(clearTimeout(a),n(),t(new b({code:A.API_CALL_ABORTED,message:L({key:M.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{g.off(E.LEAVE_SUCCESS,o,this),this.off(Wt.CONNECTION_STATE_CHANGED,s,this)},a=setTimeout(()=>{n();let c=new b({code:A.API_CALL_TIMEOUT,message:"connection timeout"});Rh+=1,ef(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),yh=!0,this.emit(Wt.FIREWALL_RESTRICTION)),t(c)},as);g.on(E.LEAVE_SUCCESS,o,this),this.on(Wt.CONNECTION_STATE_CHANGED,s,this)}),this._waitForPCConnectedPromise=this._waitForPCConnectedPromise.finally(()=>{this._waitForPCConnectedPromise=null,this._waitForPCConnectedPromiseReject=null}),this._waitForPCConnectedPromise)}waitForReconnected(){return this.isReconnecting?new Promise((e,t)=>{this.once("spc-reconnected",e),this.once("error",t)}):Promise.resolve()}addDownlink(e){return _(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:s}){if(!this._peerConnection)return;this._log.info(`updateLocalAndRemoteSDPConfig ${t} ${JSON.stringify(e)}`);let o=this._peerConnection.getTransceivers().slice(4).filter(m=>m.direction==="inactive").slice(0,3).map(m=>(m.direction=h.TRANSCEIVER_DIRECTION_RECVONLY,Number(m.mid)));this._parsedAnswer||(this._parsedAnswer=ce(this._peerConnection.remoteDescription.sdp));let n=this._parsedAnswer.media.filter(m=>{var f;return(f=m.ssrcs)==null?void 0:f.find(R=>{var C;return(C=R.value)==null?void 0:C.includes(s)})}),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(m=>Number(m.mid)===Number(o[0])),c=this._parsedAnswer.media.find(m=>Number(m.mid)===Number(o[1])),d=this._parsedAnswer.media.find(m=>Number(m.mid)===Number(o[2]));else if(o.length===0){this._peerConnection.addTransceiver(h.AUDIO,{direction:h.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:h.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:h.TRANSCEIVER_DIRECTION_RECVONLY}),a=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let m=Vd({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:ce(this._peerConnection.localDescription.sdp),isDownlink:!0});c=JSON.parse(JSON.stringify(m)),d=JSON.parse(JSON.stringify(m)),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=h.TRANSCEIVER_DIRECTION_SENDONLY;let l=`${s}-${e.audio}`;a.ssrcs=[{id:e.audio,attribute:"cname",value:`${l}`},{id:e.audio,attribute:"msid",value:`${l}-${h.MAIN} ${l}-audio`}],c.direction=h.TRANSCEIVER_DIRECTION_SENDONLY,c.ssrcs=[{id:e.video,attribute:"cname",value:`${l}`},{id:e.video,attribute:"msid",value:`${l}-${h.MAIN} ${l}-bigvideo`},{id:e.videoRtx,attribute:"cname",value:`${l}`},{id:e.videoRtx,attribute:"msid",value:`${l}-${h.MAIN} ${l}-bigvideo`}],c.ssrcGroups=[{semantics:"FID",ssrcs:`${e.video} ${e.videoRtx}`}],d.direction=h.TRANSCEIVER_DIRECTION_SENDONLY;let p=`${l}-aux`;d.ssrcs=[{id:e.auxiliary,attribute:"cname",value:p},{id:e.auxiliary,attribute:"msid",value:`${p} ${l}-aux${h.VIDEO}`},{id:e.auxiliaryRtx,attribute:"cname",value:`${p} ${l}-aux${h.VIDEO}`},{id:e.auxiliaryRtx,attribute:"msid",value:`${p} ${l}-aux${h.VIDEO}`}],d.ssrcGroups=[{semantics:"FID",ssrcs:`${e.auxiliary} ${e.auxiliaryRtx}`}],this._parsedAnswer.groups&&(this._parsedAnswer.groups[0].mids=this._parsedAnswer.media.map(m=>m.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 _(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),s=!1;this._peerConnection.getTransceivers().forEach(o=>{t!=null&&t.includes(Number(o.mid))&&(s=!0,o.direction="inactive")}),this._parsedAnswer||(this._parsedAnswer=ce(this._peerConnection.remoteDescription.sdp)),this._parsedAnswer.media.forEach(o=>{t!=null&&t.includes(Number(o.mid))&&(s=!0,o.direction="inactive",o.ssrcs=[],o.ssrcGroups=[])}),this.removeDownlinkQueue.size===0&&s&&(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 _(this,null,function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:s,smallVideo:o,auxVideo:n}=e;try{if(Ps()){let a=this._peerConnection.getSenders().slice(0,4);for(let d=0;d<a.length;d++){let l=a[d],p;d===0&&t?p=t:d===1&&s?p=s:d===2&&o?p=o:d===3&&n&&(p=n),p&&(yield this.setSenderMaxBitrate(l,p))}let c=!1;s&&a[1].track&&(c=this.setStartBitrate(1,s)),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 s,o;return(s=this._peerConnection)!=null&&s.remoteDescription&&(this._parsedAnswer||(this._parsedAnswer=ce(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 s=e.getParameters();return(!s.encodings||s.encodings.length===0)&&(s.encodings=[{}]),t==="unlimited"?delete s.encodings[0].maxBitrate:s.encodings[0].maxBitrate=t*1e3,e.setParameters(s)}setBandwidthBySDP({audio:e,bigVideo:t,smallVideo:s,auxVideo:o}){if(!this._peerConnection||!this._peerConnection.localDescription)return;let n=ce(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=ce(this._peerConnection.remoteDescription.sdp));let a=ie?"TIAS":"AS";e&&(n.media[0].bandwidth=[{type:a,limit:ie?e*1e3:e}],this._parsedAnswer.media[0].bandwidth=[{type:a,limit:ie?e*1e3:e}]),t&&(n.media[1].bandwidth=[{type:a,limit:ie?t*1e3:t}],this._parsedAnswer.media[1].bandwidth=[{type:a,limit:ie?t*1e3:t}]),s&&(n.media[2].bandwidth=[{type:a,limit:ie?s*1e3:s}],this._parsedAnswer.media[2].bandwidth=[{type:a,limit:ie?s*1e3:s}]),o&&(n.media[3].bandwidth=[{type:a,limit:ie?o*1e3:o}],this._parsedAnswer.media[3].bandwidth=[{type:a,limit:ie?o*1e3:o}]);let c={type:"offer",sdp:He(n)};return this.updateSDP({localDescription:c})}setScaleResolutionDownBy(e,t){if(t===1)return;let s=e.getParameters();return(!s.encodings||s.encodings.length===0)&&(s.encodings=[{}]),s.encodings[0].scaleResolutionDownBy=t,e.setParameters(s)}updateSDP({localDescription:e}={}){if(!this._parsedAnswer)return Promise.resolve();let t=He(this._parsedAnswer);return this._updateSDPPromise=new Promise((s,o)=>_(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,s()}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)}
94
94
  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)}
95
- 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:l,direction:p,stopped:m})=>({mid:d,currentDirection:l,direction:p,stopped:m})))}`),this._log.warn(`parsedAnswer: ${JSON.stringify(this._parsedAnswer)}`),this._isSDPLogged=!0),this._updateSDPPromise=null,o(c)}})),this._updateSDPPromise}setTransceiverDirection(e,t){return _(this,null,function*(){if(!ie||!this._peerConnection||!this._parsedAnswer)return;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let s=this._peerConnection.getTransceivers();t.forEach(o=>{s[o].direction!==e&&(s[o].direction=e)});for(let o of t){let n=this._parsedAnswer.media[o].direction;e===z.INACTIVE&&n===z.RECVONLY&&(this._parsedAnswer.media[o].direction=e),e===z.SENDONLY&&n===z.INACTIVE&&(this._parsedAnswer.media[o].direction=z.RECVONLY)}yield this.updateSDP()})}filterSDPDirection(e=""){return ce(e).media.map(s=>s.direction)}setOffer(e){return this._log.info("setting offer"),this._log.debug(e.sdp),this._peerConnection.setLocalDescription({type:"offer",sdp:Th(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 _(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let t=!1;this._parsedAnswer.media.forEach(s=>{var o;if(s.type===h.VIDEO){let n=this._serverAbility.video.codecs.find(a=>a.codec.toLowerCase()===e);n&&!((o=s.payloads)!=null&&o.includes(String(n.payload)))&&(s.fmtp=[],s.payloads="",s.rtp=[],s.rtcpFb=[],or(s,n),t=!0)}}),t&&(this._log.warn(`switch video encoder to ${e}`),yield this.setOffer(this._peerConnection.localDescription),yield this.setAnswer({type:"answer",sdp:He(this._parsedAnswer)}))})}useHWEncoder(e=!0,t){return _(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let s=!1,o=[];T(t)?o=this._parsedAnswer.media.slice(1,4):t===2?o.push(this._parsedAnswer.media[1]):t===3?o.push(this._parsedAnswer.media[2]):t===7&&o.push(this._parsedAnswer.media[3]),o.forEach(n=>{var a;if(n.type===h.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=[],or(n,c),s=!0)}}),s&&(this._log.warn(`use ${e?"hw":"sw"} encoder`),yield this.setOffer(this._peerConnection.localDescription),yield this.setAnswer({type:"answer",sdp:He(this._parsedAnswer)}))})}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.insertableStreamsAbortMap.forEach(e=>Tu(e.abort)&&e.abort("destroy")),this.insertableStreamsAbortMap.clear(),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners()}getReceiversByUserId(e){if(!this._peerConnection)return[];let t=this._peerConnection.getReceivers();return(this._downlinkMIDMap.get(e)||[]).map(s=>t[s])}};y([Rn("reconnect")],ui.prototype,"startReconnection",1),y([si(r=>r.userId)],ui.prototype,"addDownlink",1),y([si(r=>r)],ui.prototype,"removeDownlink",1),y([$t(!0)],ui.prototype,"updateSDP",1);var Ud=class{constructor(i){u(this,"tag");u(this,"len");u(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}},Bd=class{constructor(i){u(this,"tinyId");u(this,"data");let e=new DataView(i),t=0,s=[];for(;t<e.byteLength;){let o=e.getUint16(t+2),n=new Ud(new Uint8Array(i).slice(t,t+2+2+o).buffer);s.push(n),t+=2+2+o}s.forEach(o=>{o.tag===1?this.tinyId=new TextDecoder().decode(o.data):o.tag===2&&(this.data=o.data)})}},Ah=new Set;function nr(){let r=Math.floor(Math.random()*4294967296);return Ah.has(r)?nr():(Ah.add(r),r)}var bh=Se(Ne());var ar=class extends bh.default{constructor(e){super();u(this,"userId");u(this,"tinyId");u(this,"_sdpSemantics");u(this,"_isUplink");u(this,"_room");u(this,"_log");u(this,"_currentState","DISCONNECTED");u(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=I.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:(g.emit(E.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 _o=class extends ar{constructor(e){super(P(N({},e),{isUplink:!0}));u(this,"localMainAudioTrack",null);u(this,"localMainVideoTrack",null);u(this,"localAuxAudioTrack",null);u(this,"localAuxVideoTrack",null);u(this,"_isPublishingAux",!1);u(this,"_publishingLocalAudioTrack");u(this,"_publishingLocalVideoTrack");u(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});u(this,"_flag",0);u(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:s,smallVideoSsrc:o,smallVideoRtxSsrc:n,auxVideoSsrc:a,auxVideoRtxSsrc:c}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:s||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:s}=this,o=Object.keys(t).find(n=>t[n]!==s[n]);if(o)if(e)this._log.warn(`publish state not matched, ${o} local:${t[o]} server:${s[o]} ${As()} ${wa()}`),D.addCount({key:521e3});else{this._checkPublishStateTimeoutId=re.run(fi,()=>this.checkPublishState(!0),{delay:10*1e3,count:1});return}re.clearTask(this._checkPublishStateTimeoutId),this._checkPublishStateTimeoutId=-1}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}get publishState(){var t,s,o,n;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(Lt()?(e.audio=!!((t=a[0])!=null&&t.track),e.bigVideo=!!((s=a[1])!=null&&s.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===h.AUDIO?e.audio=!0:(e.bigVideo=!0,this._room.videoManager.hasSmall&&(e.smallVideo=!0)))}))}return e}get serverPublishState(){return{audio:!!(this.flag&mi),bigVideo:!!(this.flag&hi),smallVideo:!!(this.flag&os),auxVideo:!!(this.flag&xi)}}get muteState(){var e,t,s;return{audio:!!((e=this.localMainAudioTrack)!=null&&e.muted),bigVideo:!!((t=this.localMainVideoTrack)!=null&&t.muted),auxVideo:!!((s=this.localAuxVideoTrack)!=null&&s.muted)}}initialize(){this.installEvents()}close(e){var s;let t=((s=this._peerConnection)==null?void 0:s.getSenders())||[];for(let o of t)o.replaceTrack(null);super.close(e),this.uninstallTrackMuteEvents(this.localMainAudioTrack,this.localMainVideoTrack,this.localAuxVideoTrack),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){var e,t;this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),(e=this.singlePC)!=null&&e.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||(t=this.singlePC)==null||t.on("spc-reconnected",this.onSinglePCReconnected,this),yi&&this._room.enableSEI&&!g.listeners(E.SEND_SEI_MESSAGE).includes(this.sendSEIByWorker)&&(this.sendSEIByWorker=this.sendSEIByWorker.bind(this),g.on(E.SEND_SEI_MESSAGE,this.sendSEIByWorker))}uninstallEvents(){var e;this.off("connection-state-changed",this.handleConnectionStateChange,this),(e=this.singlePC)==null||e.off("spc-reconnected",this.onSinglePCReconnected,this),g.off(E.SEND_SEI_MESSAGE,this.sendSEIByWorker)}emitConnectionStateChangedEvent(e,t){var n,a,c;let s=this._currentState,o=super.emitConnectionStateChangedEvent(e);return o&&s!==e&&(t?t.emit("connection-state-changed",{prevState:s,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:s,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:s,state:e}),(c=this._publishingLocalVideoTrack)==null||c.emit("connection-state-changed",{prevState:s,state:e}))),o}onVideoEncodeFailed(e){var t,s;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"),(s=this.singlePC)==null||s.switchVideoEncoder("vp8")))}publish(o){return _(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:s}){var d,l,p,m,f,R,C;if(!this.singlePC)return;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 b({code:A.NOT_SUPPORTED_H264,message:L({key:M.NOT_SUPPORTED_H264ENCODE})});pe&&Qt()===115&&t.profile.width*t.profile.height<=640*360&&(this._log.warn("fallback video to 480p"),t.setProfile(Ze["480p_2"]),yield t.applyProfile()),this._publishingLocalVideoTrack=t,s?(n.auxVideo=!0,a.auxVideo=t.muted):(n.bigVideo=!0,a.bigVideo=t.muted)}this._isPublishingAux=s;let c;if(t&&!s&&t.small&&(c=this._room.videoManager.smallTrack,n.smallVideo=!0),yield this._signalChannel.sendWaitForResponseWithRetry({command:q.SPC_PUBLISH,responseCommand:V.SPC_PUBLISH_RESULT,data:P(N({},this.singlePC.uplinkSSRC),{state:n,muteState:a}),retries:3}),yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:c,isAuxiliary:s}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,t){this[s?"localAuxVideoTrack":"localMainVideoTrack"]=t;let{scaleResolutionDownBy:v}=t;v>1&&(this._log.warn(`setScaleResolutionDownBy ${t.streamType} ${v}`),yield this.singlePC.setScaleResolutionDownBy(this._peerConnection.getSenders()[s?3:1],v))}e&&(this[s?"localAuxAudioTrack":"localMainAudioTrack"]=e),yield this.singlePC.setBandwidth({audio:((d=this.localMainAudioTrack)==null?void 0:d.profile.bitrate)||((l=this.localAuxAudioTrack)==null?void 0:l.profile.bitrate),bigVideo:(p=this.localMainVideoTrack)==null?void 0:p.profile.bitrate,smallVideo:(f=(m=this.localMainVideoTrack)==null?void 0:m.small)==null?void 0:f.bitrate,auxVideo:(R=this.localAuxVideoTrack)==null?void 0:R.profile.bitrate}),this.sendMediaSettings(),this.installTrackMuteEvents(e,t),!s&&(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:s,isAuxiliary:o}){if(!tt())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=[],l=[],p=(f,R,C)=>{var U;let v=c[R].sender.replaceTrack(C);l.push(R),(U=this.singlePC)!=null&&U.enableInsertableStreams&&v.then(()=>this.createEncodedStreams(c[R].sender,f)),d.push(v)};a&&p(e.mediaType,0,a),n&&p(t.mediaType,o?3:1,n),s&&p(8,2,s);let m=this.singlePC.setTransceiverDirection(z.SENDONLY,l);return d.push(m),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 s=e.createEncodedStreams(),o=new AbortController;(a=this.singlePC)==null||a.addAbortController(e,o),((c=this.getTrackByMediaType(t))!=null&&c.enableEncodeFrame?s.readable.pipeThrough(new TransformStream({transform:(d,l)=>{var m;let p=this.getTrackByMediaType(t);l.enqueue(((m=this.singlePC)==null?void 0:m.isUsingH264)&&p?p.encodeFrame(d,t===8):d)}}),o):s.readable).pipeTo(s.writable,o).catch(d=>{this._log.debug("encoded stream error",d),d!=="destory"&&this._log.warn(d)})}sendSEIByWorker({room:e,isMain:t}){var o;if(e!==this._room||!this._peerConnection||!this.singlePC||!this._room.videoManager.seiWorker)return;let s=this._peerConnection.getSenders()[t?1:3];if(!!s&&(s.transform||(s.transform=new RTCRtpScriptTransform(this._room.videoManager.seiWorker,{isReceiver:!1,isMain:t})),t&&((o=this.localMainVideoTrack)==null?void 0:o.small))){let n=this._peerConnection.getSenders()[2];n.transform||(n.transform=new RTCRtpScriptTransform(this._room.videoManager.seiWorker,{isReceiver:!1,isMain:t,small:!0}))}}enableSmall(e){return _(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(z.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(z.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(s){return _(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&&(yield a[0].replaceTrack(null),c.push(0),o?this.localAuxAudioTrack=null:this.localMainAudioTrack=null),n&&(o?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=P(N({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),c.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=P(N({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),c.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.singlePC.setTransceiverDirection(z.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 _(this,null,function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},s=yield this._signalChannel.sendWaitForResponseWithRetry({command:q.PUBLISH_STATE_CHANGE,data:t,responseCommand:V.PUBLISH_STATE_CHANGE_RESULT,enableLog:e,retries:3});this.checkPublishResultCode(s.data.code,s.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:q.UNPUBLISH,commandDesc:"unpublish",responseCommand:V.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===A.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 s=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:o,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:o=this._publishingLocalVideoTrack),xt){if(s&&s.outMediaTrack){let a=s.outMediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=s.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 s&&s.outMediaTrack&&(this._mediaSettings.audioChannel=s.profile.channelCount,this._mediaSettings.audioBps=s.profile.bitrate*1e3,this._mediaSettings.audioFs=s.profile.sampleRate),o&&o.outMediaTrack&&(this._mediaSettings.videoWidth=o.profile.width,this._mediaSettings.videoHeight=o.profile.height,this._mediaSettings.videoFps=o.profile.frameRate,this._mediaSettings.videoBps=o.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:q.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:V.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return _(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?h.AUXILIARY:h.MAIN} stream`),Lt()&&(yield this.addTrackByTransceiver(e,t))})}addTrackByTransceiver(e,t){return _(this,null,function*(){var o;if(!e.mediaTrack)return;let s=this._peerConnection.getTransceivers();if(e.kind===h.AUDIO)yield s[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield s[n].sender.replaceTrack(e.outMediaTrack),n===1&&((o=this.localMainVideoTrack)==null?void 0:o.small)&&(yield s[2].sender.replaceTrack(this._room.videoManager.smallTrack)),s[n].direction===z.INACTIVE&&(yield this.singlePC.setTransceiverDirection(z.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}removeTrack(e){return _(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?h.AUXILIARY:h.MAIN} stream`),Lt()&&(yield this.removeTrackByTransceiver(e,t))})}removeTrackByTransceiver(e,t){return _(this,null,function*(){if(!e.mediaTrack)return;let s=this._peerConnection.getTransceivers();if(e.kind===h.AUDIO)yield s[0].sender.replaceTrack(null);else{let o=t?3:1;yield s[o].sender.replaceTrack(null),o===1&&this._room.videoManager.hasSmall&&(yield s[2].sender.replaceTrack(null)),yield this.singlePC.setTransceiverDirection(z.INACTIVE,[o])}this.updateMediaSettings(),yield this.doPublishChange()})}replaceTrack(e){return _(this,null,function*(){var n;let t=(n=this._peerConnection)==null?void 0:n.getSenders(),s=e.outMediaTrack||e.mediaTrack;if(!t||t.length===0||!s||t.find(a=>a.track===s))return!1;let o=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info(`is replacing ${s.kind} track ${s.id} on ${o?h.AUXILIARY:h.MAIN} stream`),s.kind===h.AUDIO&&t[0]&&(yield t[0].replaceTrack(s)),s.kind===h.VIDEO&&(!o&&t[1]&&(yield t[1].replaceTrack(s)),o&&t[3]&&(yield t[3].replaceTrack(s))),!0})}setBandwidth(o){return _(this,arguments,function*({bandwidth:e,type:t,videoType:s}){if(this.singlePC){let n={};t===h.AUDIO?n.audio=e:s==="big"?n.bigVideo=e:s==="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:q.UPDATE_MUTE_STAT,responseCommand:V.MUTE_RESULT,data:this.muteState,retries:3}).catch(()=>{}))}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&g.emit(E.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(e=h.VIDEO){if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===h.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===h.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===h.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===h.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===Pi?(this._log.error(Ae.NOT_SUPPORTED_H264ENCODE),new b({code:A.NOT_SUPPORTED_H264,message:L({key:M.NOT_SUPPORTED_H264ENCODE})})):new b({code:A.UNKNOWN,message:L({key:M.SIGNAL_RESPONSE_FAILED,data:{signalResponse:V.PUBLISH_RESULT,code:e,message:t}})})}onSinglePCReconnected(){return _(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}))})}};y([gt(function({localVideoTrack:r}){r==null||r.once("6",this.onVideoEncodeFailed,this)})],_o.prototype,"publish",1),y([gt(function({localVideoTrack:r}){r==null||r.off("6",this.onVideoEncodeFailed,this)})],_o.prototype,"unpublish",1);var $d=_o;function Nh(r){return Object.keys(r).filter(i=>r[i])}var Qr=class extends ar{constructor(e){super(P(N({},e),{isUplink:!1}));u(this,"_flag",0);u(this,"role","anchor");u(this,"remoteAudioTrack");u(this,"remoteVideoTrack");u(this,"remoteAuxiliaryTrack");u(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0});this.flag=e.flag,this.remoteAudioTrack=new oi(this._room,this),this.remoteVideoTrack=new Tt(this._room,this),this.remoteAuxiliaryTrack=new Vr(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 Ai(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,s,o;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(s=this.remoteVideoTrack)==null||s.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===h.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){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,s=super.emitConnectionStateChangedEvent(e);return s&&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})),s}onTrack(e){let t=e.streams[0],{track:s,receiver:o}=e;if(!t.id.includes(this.tinyId))return;let a=t.id.includes("aux")?"auxiliary":"main";this._log.debug(`ontrack ${a} ${s.kind}`);let c=h.AUDIO;s.kind===h.VIDEO&&(c=a===h.MAIN?h.VIDEO:h.AUXILIARY);let d=this.remoteAudioTrack;c===h.VIDEO?d=this.remoteVideoTrack:c===h.AUXILIARY&&(d=this.remoteAuxiliaryTrack),this._room.enableSEI&&yi&&this.receiveSEIByWorker(o,a),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(d,o),d.setInputMediaStreamTrack(s)}createEncodedStreams(e,t){if(!this.singlePC.insertableStreamsAbortMap.has(t)){let s=t.createEncodedStreams(),o=new AbortController,n={abortController:o,enqueue:c=>{var d;return(d=this.singlePC)!=null&&d.isUsingH264?e.decodeFrame(c):c}};(e.enableDecodeFrame?s.readable.pipeThrough(new TransformStream({transform:(c,d)=>d.enqueue(n.enqueue(c))})):s.readable).pipeTo(s.writable,o).catch(c=>{c!=="destory"&&this._log.warn(c)}),this.singlePC.addAbortController(t,o)}}receiveSEIByWorker(e,t){e.track.kind===h.AUDIO||!this._peerConnection||!this.singlePC||!this._room.videoManager.seiWorker||e.transform||(e.transform=new RTCRtpScriptTransform(this._room.videoManager.seiWorker,{isReceiver:!0,userId:this.userId,streamType:t}))}subscribe(e,t){return _(this,null,function*(){try{if(this._log.info(`subscribe ${t} ${Nh(e)}`),this.hasSSRC){let s="subscribe_change";Object.values(e).find(o=>o===!0)||(s="unsubscribe"),yield this.sendSubscription(s,e)}else yield this.doSubscribe(e),this.checkTrackEnded(e)}catch(s){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${s.message} ${JSON.stringify(this.muteState)}`),new b({code:A.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):s}})}checkTrackEnded(e){var t,s,o;if((e.audio&&((t=this.remoteAudioTrack.mediaTrack)==null?void 0:t.readyState)==="ended"||e.video&&((s=this.remoteVideoTrack.mediaTrack)==null?void 0:s.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"),Pe&&ht<92)return;this.singlePC.startReconnection()}}unsubscribe(s){return _(this,arguments,function*({remoteTracks:e,streamType:t}){var a;if(t==="main"&&!this.isMainStreamSubscribed||t==="auxiliary"&&!this.isAuxStreamSubscribed){this._log.info(`${t} stream already unsubscribed`);return}let o=N({},this.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:o.audio=!1;break;case 4:o.video=!1;break;case 8:o.smallVideo=!1;break;case 2:o.auxiliary=!1;break;default:break}});let n="subscribe_change";Object.values(o).find(c=>c===!0)||(n="unsubscribe"),this._log.info(`${n==="unsubscribe"?n:"subscribe"} ${t} [${Nh(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 s={srcTinyId:this.tinyId,srcUserId:this.userId},o=q.UNSUBSCRIBE,n=V.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(s={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},o=q.SUBSCRIBE_CHANGE,n=V.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponseWithRetry({command:o,data:s,responseCommand:n,timeout:1e4,retries:3}).then(({data:a})=>{if(a.code!==0){let c=new b({code:a.code,message:L({key:M.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 _(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 s={audioSsrc:nr(),bigVideoSsrc:nr(),bigVideoRtxSsrc:nr(),auxVideoSsrc:nr(),auxVideoRtxSsrc:nr()},{audioSsrc:o,bigVideoSsrc:n,bigVideoRtxSsrc:a,auxVideoSsrc:c,auxVideoRtxSsrc:d}=s;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 l=yield this._signalChannel.sendWaitForResponseWithRetry({command:q.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:s},retries:3,retryTimeout:0});if(l.data.code!==0)throw new b({code:l.data.code,message:l.data.message})}catch(l){throw yield this.removeDownlink(),l}return}this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc})}finally{let s=this._room.scheduleResult.config;((s==null?void 0:s.jitterDelay)||(s==null?void 0:s.jitterDelayAux))&&this.setJitterBufferDelay({mainDelay:s.jitterDelay,auxDelay:s.jitterDelayAux})}}})}removeDownlink(){return _(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||Zt(e)&&Zt(t))return Promise.resolve();this._log.info(`set jitterBuffer main: ${e} aux: ${t}`);let s=this.singlePC.getReceiversByUserId(this.userId);return ee(e)&&(this.remoteAudioTrack.jitterBufferDelay=e,this.remoteVideoTrack.jitterBufferDelay=e),ee(t)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=t,Zt(e)&&(this.remoteAudioTrack.jitterBufferDelay=t)),new Promise(o=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:s,resolve:o})})}doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:s,resolve:o}){let n=-1;try{if(e===0&&t===0)return s.forEach(c=>c.jitterBufferTarget=0),o();if(s.forEach(c=>{var m;let d=c.track===this.remoteAuxiliaryTrack.outMediaTrack||Zt(e)&&c.track===this.remoteAudioTrack.outMediaTrack;if(d&&Zt(t)||!d&&Zt(e))return;let l=d?t||0:e,p=(c.jitterBufferTarget||0)+100;p>l||(c.jitterBufferTarget=p,this._log.debug(`set ${d?"aux ":""}${(m=c==null?void 0:c.track)==null?void 0:m.kind} jitterBuffer delay ${p} -> ${l}`))}),!s.find(c=>{let d=c.track===this.remoteAuxiliaryTrack.outMediaTrack?t||0:e;return c.jitterBufferTarget<d}))return this._log.info(`set jitterBuffer main: ${e} aux: ${t} done`),o();n=setTimeout(()=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:s,resolve:o})},1e3)}catch(a){this._log.warn(`set jitterBuffer delay error: ${a}`),clearTimeout(n),o()}}};y([$t(),J(r=>function(...i){return new Promise((e,t)=>{let s=o=>{this.off("closed",s),t(new b({code:A.API_CALL_ABORTED,message:L({key:M.CONNECTION_ABORTED,data:o})}))};this.on("closed",s),r.apply(this,i).then(e,t).finally(()=>{this.off("closed",s)})})})],Qr.prototype,"subscribe",1),y([$t()],Qr.prototype,"unsubscribe",1),y([si(()=>"jitter")],Qr.prototype,"setJitterBufferDelay",1);var vh=Qr;function Dh(){return J(r=>function(...i){return _(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(i=i.filter(t=>t.outMediaTrack&&t.state==="capture"),!i.length))return;g.emit("61",{room:this});let e=r.apply(this,i);return i.forEach(t=>t.publish(this,e)),e})})}function Oh(){return J(r=>function(...i){let e=r.apply(this,i);return i.forEach(t=>t.unpublish()),e})}var Mh=Se(Ne());function rf(){return Math.floor(Math.random()*16383)}var Fd=class extends Mh.EventEmitter{constructor(e,t){super();this.room=e;this.signalChannel=t;u(this,"log");u(this,"cmdIdSeqMap",new Map);u(this,"messageMap",new Map);this.log=I.createLogger({id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),t.on(V.RECEIVE_CUSTOM_MSG,this.onReceiveMsg)}send({cmdId:e,data:t}){let s=this.cmdIdSeqMap.get(e)||rf(),o={cmdId:e,msg:btoa(String.fromCharCode(...new Uint8Array(t))),ordered:!0,reliable:!0,streamSeq:s};this.cmdIdSeqMap.set(e,s+1),this.signalChannel.send(q.SEND_CUSTOM_MSG,o),this.log.debug(`send custom msg: ${JSON.stringify(o)}`)}onReceiveMsg(e){let{data:t}=e.data,s=this.room.tinyIdToUserIdMap.get(t.srcTinyId);if(s){let o={userId:s,cmdId:t.cmdId,seq:t.streamSeq,data:Uint8Array.from(atob(t.msg),n=>n.charCodeAt(0)).buffer};if(t.ordered){let n=`${s}_${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)>Fd.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)}}emitMessage(e,t=!1){var a;let s=this.messageMap.get(`${e.userId}_${e.cmdId}`),o=e;if(s){if(t){let c=[...s.cachedMessageMap.values()].sort((d,l)=>d.message.seq-l.message.seq);c[0]&&(o=c[0].message)}s.lastSeq!==0&&o.seq-s.lastSeq>1&&this.log.debug(`msg lost userId: ${o.userId} seq: ${s.lastSeq} -> ${o.seq}`),s.lastSeq=o.seq,clearTimeout((a=s.cachedMessageMap.get(o.seq))==null?void 0:a.timeoutId),s.cachedMessageMap.delete(o.seq)}this.log.debug(`receive custom msg: ${JSON.stringify(o)}`),this.emit("message",o);let n=s==null?void 0:s.cachedMessageMap.get(o.seq+1);n&&this.emitMessage(n.message)}},fo=Fd;u(fo,"SEQ_INTERVAL",300);var{isString:kh,isUndefined:zr,getNetworkType:sf,isEmpty:Eo}=we,At=class extends oa{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=Dr;this._changeBigSmallRecords=new Map;this._networkQuality=null;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._stats=new co(this,this._log),this.userManager=new Bn(this.userId,this._log),this._version=Re,this.sdpSemantics=dr,zr(e.sdpSemantics)?ft.isUnifiedPlanDefault()&&(this.sdpSemantics=pi):this.sdpSemantics=e.sdpSemantics,this._log.info(`sdpSemantics: ${this.sdpSemantics}, netType: ${sf()}`),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=zr(e.enableMultiAuxStream)?!1:e.enableMultiAuxStream,this.enableSEI=e.enableSEI&&Dr,!zr(e.enableSPC)&&Dr&&(this.enableSPC=e.enableSPC),this.preferHW=!!e.preferHW,this._initBusinessInfo(e),this.healthDetector=new Ih(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,s){return _(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=Jd(n,[]);g.emit(E.REMOTE_PUBLISH_STATE_CHANGED,N({room:this},o)),this.emit("remote-publish-state-changed",N({},o))}),this.joinParams=e,new Promise((o,n)=>_(this,null,function*(){var a,c;this._joinReject=n;try{this.checkDestroy();try{yield Promise.all([this.initialize(),this.initSinglePC()])}catch(l){if(l instanceof b&&l.code===A.SPC_INITIALIZED_FAILED)(a=this.signalChannel)==null||a.destroy(),yield this.initialize();else return n(l)}let d=x();yield this.doJoin(e,(c=this.singlePC)==null?void 0:c.clientAbility),D.addSuccessEvent({key:521708,cost:x()-d}),o(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(d){D.addFailedEvent({key:521708,error:d}),n(d)}this._joinReject=null}))})}initSinglePC(){return _(this,null,function*(){if(!(!this.enableSPC||this.singlePC)){this.singlePC=new ui({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 b({code:A.SPC_INITIALIZED_FAILED,message:e==null?void 0:e.message})}}})}doJoin(e,t){return new Promise((s,o)=>_(this,null,function*(){var c,d,l;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this.signalChannel.once(_e.SETUP_FAILED,p=>{this.clearJoinTimeout(),g.emit(E.JOIN_SIGNAL_CONNECTION_END,{room:this,error:p}),o(p)}),de((d=(c=this.scheduleResult)==null?void 0:c.config)==null?void 0:d.singlePC)&&Dr&&(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:Va(),netType:br(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig};this._log.debug(`join room signal data: ${JSON.stringify(n)}`);let a=5e3;((l=this.scheduleResult.config)==null?void 0:l.enterRoomTimeout)&&this.scheduleResult.config.enterRoomTimeout>=1&&(a=this.scheduleResult.config.enterRoomTimeout*1e3),this._joinTimeout=window.setTimeout(()=>{o(new b({code:A.JOIN_ROOM_FAILED,message:L({key:M.JOIN_ROOM_TIMEOUT})}))},a),g.emit(E.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?q.SPC_JOIN_ROOM:q.JOIN_ROOM,n),this.signalChannel.once(V.JOIN_ROOM_RESULT,p=>{this.clearJoinTimeout();let{code:m,message:f,data:R,tinyId:C}=p.data;g.emit(E.JOIN_RECEIVED_CMD_RES,{room:this,code:m}),m===0?(this._log.info("Join room success, start heartbeat"),C&&(this.tinyId=C),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=R.publishers,this.singlePC&&this.singlePC.connect(R.ability).catch(()=>{}),s()):(this._log.error(`Join room failed result: ${m} error: ${f}`),o(new b({code:A.JOIN_ROOM_FAILED,extraCode:m,message:L({key:M.JOIN_ROOM_FAILED,data:{error:f,code:m}})})))})}))}reJoin(e=!0){return _(this,null,function*(){if(!this.isJoined){this._log.warn("reJoin abort");return}try{this._log.warn(`reJoin pending: ${this.joinParams.roomId}`);let t,s=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,s.push(this.initSinglePC().then(o=>(t=o,o)))),this.signalChannel&&(this.signalChannel.race=e,this.signalChannel.close(),s.push(this.signalChannel.connect())),yield Promise.all(s),yield this.doJoin(P(N({},this.joinParams),{role:this.role==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),t),this._log.warn("reJoin success"),Z.logSuccessEvent({userId:this.userId,eventType:Ve.REJOIN}),this.singlePC){let o=n=>{var a;n.state==="CONNECTED"&&((a=this.singlePC)==null||a.off(Wt.CONNECTION_STATE_CHANGED,o),this.uplinkConnection instanceof $d&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach(c=>{c.installEvents(),c.onSinglePCReconnected()}))};this.singlePC.on(Wt.CONNECTION_STATE_CHANGED,o),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof ao&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(t){this._log.warn(`reJoin fail ${t}`),this.reset(),Z.logFailedEvent({userId:this.userId,eventType:Ve.REJOIN,error:t}),this.emit("error",new b({code:A.JOIN_ROOM_FAILED,message:L({key:M.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}})}initialize(){return _(this,null,function*(){let{mainUrl:e,backupUrl:t}=this.getSignalChannelUrl(),s=this.signalChannel||Ql(this.userId),o=!!(s&&s.isConnected&&s.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?(s.url=e,s.backupUrl=t,s.room=this,this.signalChannel=s):(this.signalChannel=new jr({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 fo(this,this.signalChannel),this._customMessageManager.on("message",a=>{this.emit("custom-message",a)})),this._networkQuality||(this._networkQuality=new rr({signalChannel:this.signalChannel,room:this}),this._networkQuality.on(rr.EVENT_NETWORK_QUALITY,a=>{this.emit("network-quality",a)})),De(this,this.signalChannel).add(_e.CONNECTION_STATE_CHANGED,a=>{g.emit(E.SIGNAL_CONNECTION_STATE_CHANGED,N({room:this},a)),this.emit("signal-connection-state-changed",a)}).add(_e.RECONNECT_FAILED,a=>{this.reset(),this.emit("error",a)}).add(V.PEER_JOIN,a=>{let{srcTinyId:c,userId:d,role:l}=a.data.data;this.userManager.addUser({userId:d,tinyId:c,role:l})}).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(Z.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(_e.SETUP_SUCCESS,a=>{this.tinyId=a.signalInfo.tinyId,g.emit(E.JOIN_SIGNAL_CONNECTION_END,{room:this})}),g.emit(E.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),o&&g.emit(E.JOIN_SIGNAL_CONNECTION_END,{room:this}),o})}setSignalChannel(e){this.signalChannel=e,e||me(this)}leave(){return _(this,null,function*(){var e;try{yield this.doHeartbeat()}catch(t){}this._log.info("leave() => leaving room"),g.emit(E.LEAVE_SEND_CMD,{room:this}),(e=this.signalChannel)==null||e.send(q.LEAVE_ROOM)})}clearNetworkQuality(){this._networkQuality&&(this._networkQuality.stop(),this._networkQuality=null)}closeConnections(){this.remotePublishedUserMap.forEach(e=>{this.closeDownLinkConnection(e.userId,"you exitRoom")})}clearJoinTimeout(){clearTimeout(this._joinTimeout),this._joinTimeout=-1}startHeartbeat(){this._heartbeat===-1&&(this._heartbeat=re.run(_i,this.doHeartbeat.bind(this),{delay:2e3}))}stopHeartbeat(){this._heartbeat!==-1&&(this._log.info("stopHeartbeat"),re.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return _(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 s=(n=this.signalChannel)!=null&&n.isConnected?gl(this.userId):[],o=P(N({str_sdk_version:is,uint64_datetime:new Date().getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_event_msg:s,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},t),{msg_device_info:N({uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:br()},t.msg_device_info)});if(this.heartbeatReport=o,g.emit(E.HEARTBEAT_REPORT,{room:this,report:o}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(q.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.emit("heartbeat-report",P(N({},o),{bytes_sent:this._stats.totalBytesSent+this.signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this.signalChannel.bytesReceived}))}!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)})}onPublishedUserList(e){if(!this.isJoined)return;let t=e.data.userList.map(({userId:s,srcTinyId:o,flag:n})=>{s===this.userId&&this.uplinkConnection&&(this.uplinkConnection.flag=n);let a=this.remotePublishedUserMap.get(s);return a&&this.checkSubscribeBigSmallVideo(a),{userId:s,tinyId:o,flag:n}});g.emit(E.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 ao&&(this.uplinkConnection=null)),this.localTracks.forEach(t=>t.unpublish()),this.localTracks.clear()}createDownlinkConnection({userId:e,tinyId:t,flag:s}){let o=new(this.singlePC?vh:bd)({userId:e,tinyId:t,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:s});this.userManager.addRemotePublishedUser(o),this.installDownlinkEvents(o,e),this.emit("remote-published",o)}closeDownLinkConnection(e,t="remote user unpublished"){let s=this.remotePublishedUserMap.get(e);s&&(s.close(t),this.emit("remote-unpublished",s))}installDownlinkEvents(e,t){e.on("error",s=>{let o=s.getCode();o!==A.ICE_TRANSPORT_ERROR&&(o===A.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",s))}),e.on("connection-state-changed",s=>{this.emit("media-connection-state-changed",P(N({},s),{userId:e.userId}))}),e.on("firewall-restriction",()=>{this.emit("firewall-restriction")})}startSyncUserListInterval(){this._syncUserListInterval===-1&&(this._syncUserListInterval=re.run(_i,this.syncUserList.bind(this)))}stopSyncUserListInterval(){re.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:q.GET_USER_LIST,responseCommand:V.USER_LIST_RES,enableLog:!1,timeout:2e3}).then(({data:t})=>{let{code:s,message:o}=t;if(s===0)return(t.data&&t.data.userList||[]).map(({userId:a,srcTinyId:c,role:d})=>({userId:a,tinyId:c,role:d}));throw L({key:M.SIGNAL_RESPONSE_FAILED,data:{signalResponse:V.USER_LIST_RES,code:s,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||!Id)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)===se.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach(s=>{if(s instanceof Ke&&!s.getIsReconnecting()){let o=s.getPeerConnection();o&&o.connectionState===se.CLOSED&&(this._log.warn(`[${s.getUserId()}] pc is closed but not reconnect`),s.startReconnection())}})}fallbackToMPC(){return _(this,null,function*(){var e;if(this._log.warn("fallback to multi pc"),Z.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 ao({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}),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()}this.remotePublishedUserMap.forEach(t=>{let s=new bd({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(s,t.userId),this.remotePublishedUserMap.set(t.userId,s),t.isMainStreamSubscribed&&s.subscribe(t.subscribeState,"main"),t.isAuxStreamSubscribed&&s.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 b({code:A.INVALID_OPERATION,message:L({key:M.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners(),this.healthDetector.destroy())}switchRole(e){return _(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:q.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(s=>{let{code:o,message:n}=s.data;if(o!==0)throw new b({code:A.SWITCH_ROLE_FAILED,message:L({key:M.SWITCH_ROLE_FAILED,data:{message:n,code:o}})});this.role=e}).catch(s=>{throw s instanceof b&&s.getCode()===A.API_CALL_TIMEOUT&&(s=new b({code:A.SWITCH_ROLE_FAILED,message:L({key:M.SWITCH_ROLE_TIMEOUT})})),this._log.error(s),s})}publish(...e){return _(this,null,function*(){let t={},s={};e.forEach(c=>{c instanceof Oe&&(c instanceof Ft?s.audio=c:t.audio=c),c instanceof le&&(c instanceof ze&&c.mediaType===2?s.video=c:t.video=c)});let o=Eo(t),n=Eo(s);(!o||!n)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new $d({userId:this.userId,tinyId:this.tinyId,room:this}):this.uplinkConnection=new ao({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}),this.uplinkConnection.on("connection-state-changed",c=>{this.emit("media-connection-state-changed",P(N({},c),{userId:this.userId}))}),this.uplinkConnection.on("firewall-restriction",()=>{this.emit("firewall-restriction")}),this.uplinkConnection.on("error",c=>{let d=c.getCode();d!==A.ICE_TRANSPORT_ERROR&&(d===A.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:s.audio,localVideoTrack:s.video,isAuxiliary:!0}),this._log.info("aux is published"))})}unpublish(...e){return _(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||!this.isMainStreamPublished&&!this.isAuxStreamPublished||!this.uplinkConnection)return;let t={},s={};e.forEach(o=>{!o.mediaTrack||!o.isPublished||(o instanceof Oe&&(o instanceof Ft?s.audio=o:t.audio=o),o instanceof le&&(o instanceof ze&&o.mediaType===2?s.video=o:t.video=o))});try{let o=e.map(n=>n.kind).join(",");Eo(t)||(this._log.info(`unpublish() => main ${o}`),yield this.uplinkConnection.unpublish({localAudioTrack:t.audio,localVideoTrack:t.video})),Eo(s)||(this._log.info(`unpublish() => aux ${o}`),yield this.uplinkConnection.unpublish({localAudioTrack:s.audio,localVideoTrack:s.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||!tc()?Promise.resolve():this.uplinkConnection.replaceTrack(e).then(t=>{t&&g.emit(E.LOCAL_TRACK_REPLACED,{track:e})})}setBandWidth(e){return _(this,null,function*(){!this.uplinkConnection||(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())})}enableSmall(e){return _(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:h.VIDEO,videoType:h.SMALL,bandwidth:this.uplinkConnection.localMainVideoTrack.small.bitrate})),yield this.uplinkConnection.enableSmall(e)})}subscribe(...e){return _(this,null,function*(){if(e=e.filter(n=>!n.isSubscribed),e.length===0)return;let{userId:t}=e[0],s=this.remotePublishedUserMap.get(t);if(!s)return;let o=e.find(n=>n.mediaType===2)?"auxiliary":"main";try{let n=N({},s.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&&s.muteState.hasSmall&&n.video&&(n.video=!1,n.smallVideo=!0),g.emit(E.SUBSCRIBE_START,{room:this,streamType:o,remotePublishedUser:s,subscribeState:n}),this._log.info(`subscribe() => ${t} ${o} [${Zn(n)}] prev: [${Zn(s.subscribeState)}]`),yield s.subscribe(n,o),this._log.info(`subscribe ${t} ${o} done`);for(let c of e)c.mediaTrack||(yield c.waitHasMediaTrack());g.emit(E.SUBSCRIBE_SUCCESS,{room:this,streamType:o,remotePublishedUser:s})}catch(n){let a=n instanceof b?n.getCode():A.UNKNOWN,c=n;throw n instanceof b?a===A.REMOTE_STREAM_NOT_EXIST&&(c=new b({code:A.API_CALL_ABORTED,message:L({key:M.API_CALL_ABORTED,data:{message:n.message,userId:t,streamType:o}})}),this._log.warn(c)):(c=new b({code:a,message:L({key:M.SUBSCRIBE_FAILED,data:{message:n.message,userId:t,streamType:o}})}),this._log.error(c)),c}})}unsubscribe(...e){return _(this,null,function*(){let{userId:t}=e[0],s=this.remotePublishedUserMap.get(t);if(!s)return;let o=e.find(n=>n.mediaType===2)?"auxiliary":"main";this._log.info(`unsubscribe() => ${t} ${o}`);try{yield s.unsubscribe({remoteTracks:e,streamType:o})}catch(n){this._log.warn(`unsubscribe() => failed ${n}`)}e.forEach(n=>{n.unsubscribe(),n.mediaType===8&&n.setMediaType(4)}),g.emit(E.UNSUBSCRIBE_SUCCESS,{room:this,streamType:o,remotePublishedUser:s})})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAudioVolumeEvaluation(e=2e3,t){if(e<=0){this._enableAudioVolumeEvaluation=!1,re.clearTask(this._audioVolumeIntervalId);return}e=Math.floor(Math.max(e,100)),g.emit(E.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&re.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=re.run(ds,()=>{var o;let s=[];(o=this.remotePublishedUserMap)==null||o.forEach(n=>{if(n.muteState.hasAudio){let a=Math.floor(n.remoteAudioTrack.getAudioLevel()*100);s.push({userId:n.userId,volume:a})}}),this.emit("audio-volume",s)},{fps:1e3/e,backgroundTask:t})}getLocalAudioStats(){return _(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 _(this,null,function*(){var t,s;let e={};return e[this.userId]=((s=(t=this.uplinkConnection)==null?void 0:t.localMainVideoTrack)==null?void 0:s.stat)||{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0},e})}getTransportStats(){return _(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 s=yield this._stats.getReceiverStats(t);e.downlinksRTT[s.userId]=s.rtt}return e})}getRemoteVideoStats(e){return _(this,null,function*(){let t={};for(let[s,o]of this.remotePublishedUserMap)e==="main"&&o.muteState.hasVideo&&(t[s]=o.remoteVideoTrack.stat),e==="auxiliary"&&o.muteState.hasAuxiliary&&(t[s]=o.remoteAuxiliaryTrack.stat);return t})}getRemoteAudioStats(){return _(this,null,function*(){let e={};for(let[t,s]of this.remotePublishedUserMap)s.muteState.hasAudio&&(e[t]=s.remoteAudioTrack.stat);return e})}setTurnServer(e,t){this._log.info(`set turn server: ${JSON.stringify(e)} ${t||""}`);let s=[];Array.isArray(e)?e.forEach(o=>s.push(we.getTurnServer(o))):we.isPlainObject(e)&&s.push(we.getTurnServer(e)),this._turnServers=s,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:q.START_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:V.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:q.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?q.START_PUBLISH_TENCENT_CDN:q.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?q.STOP_PUBLISH_TENCENT_CDN:q.STOP_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?V.STOP_PUBLISH_TENCENT_CDN_RES:V.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}sendAbilityStatus(e){var t;(t=this.signalChannel)==null||t.sendWaitForResponse({command:q.ABILITY_STATUS_REPORT,data:e,timeout:5e3,responseCommand:V.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch(s=>{})}getIceServers(){return this._turnServers.length===0&&this.scheduleResult.iceServers?this.scheduleResult.iceServers:this._turnServers}getIceTransportPolicy(){return this._iceTransportPolicy||this.scheduleResult.iceTransportPolicy||"all"}getLogger(){return this._log}enableAIVoice(){throw new Error("Method not implemented.")}getSignalChannelUrl(){let e={mainUrl:"",backupUrl:""},t=we.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 _(this,null,function*(){let{subscribeState:t,userId:s,muteState:{hasSmall:o,hasVideo:n}}=e;if(!o&&!n||!t.video&&!t.smallVideo)return;let a=this._changeBigSmallRecords.get(s);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 l={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:c.video,smallVideo:c.smallVideo};try{if(!o&&l.smallVideo&&(l.video=!0,l.smallVideo=!1),l.smallVideo===t.smallVideo&&l.video===t.video)return;a.isSubscribing=!0,a.reSubscribeCount=d-1,yield e.subscribe(l,"main"),e.remoteVideoTrack.setMediaType(l.smallVideo?8:4),this._log.info(`change [${s}] to ${l.smallVideo?"small":"big"} video successfully. count ${ur-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount=ur}catch(p){this._log.info(`change [${s}] to ${l.smallVideo?"small":"big"} video failed. count ${ur-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount===0&&this._changeBigSmallRecords.delete(s)}})}changeType(e,t){let o={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:ur};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(kh(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!zr(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new b({code:A.INVALID_PARAMETER,message:L({key:M.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(!zr(e.userDefineRecordId)){let s=/^[A-Za-z0-9_-]{1,64}$/gi;if(e.userDefineRecordId.match(s)===null)throw new b({code:A.INVALID_PARAMETER,message:L({key:M.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!zr(e.userDefinePushArgs))if(kh(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 b({code:A.INVALID_PARAMETER,message:L({key:M.INVALID_USER_DEFINE_PUSH_ARGS})});Eo(t)||(this._businessInfo=JSON.stringify(t))}sendCustomMessage(e){var t;(t=this._customMessageManager)==null||t.send(e)}enableInsertableStreams(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&Or)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 b({code:A.INVALID_OPERATION,message:"not join"}))}};y([Pd(["left",ne.INIT],"joined"),it({settings:{retries:1,timeout:0},onError(r,i,e){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),Mt(!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(),this._log.error(r),e(r))}}),Wl()],At.prototype,"join",1),y([Pd("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),Jl(),Rn("leave room"),Hs({fnName:"publish",validateArgs:!1}),Hs({fnName:"unsubscribe",validateArgs:!1})],At.prototype,"leave",1),y([$t(),Dh(),it({settings:{retries:qt,timeout:r=>kt(r)},onError(r,i,e){var t;(t=r.message)!=null&&t.includes("timeout")?(this._log.warn("publish timeout"),i()):(this._log.error(`publish failed: ${r}`),e(r),g.emit(E.PUBLISH_FAILED,{room:this}))}})],At.prototype,"publish",1),y([Hs({fnName:"publish"}),cl("api-call"),$t(),Oh(),gt(function(){var r,i;this.localTracks.size===0&&Ri()&&((i=(r=this.singlePC)==null?void 0:r.getPeerConnection())==null||i.getSenders().forEach(e=>e.track&&e.replaceTrack(null)))})],At.prototype,"unpublish",1),y([si(r=>r.userId)],At.prototype,"replaceTrack",1),y([si((...r)=>r[0].userId),Nn(),jl(),it({settings:{retries:qt,timeout:r=>kt(r)},onError(r,i,e,t){r.message.includes("timeout")?(this._log.warn("subscribe timeout"),i()):(this._log.error(`subscribe failed: ${r}`),e(r),g.emit(E.SUBSCRIBE_FAILED,{room:this,remoteTracks:t}))}})],At.prototype,"subscribe",1),y([Hs({fnName:"subscribe",callback(...r){this.singlePC||r.forEach(i=>{let e=this.remotePublishedUserMap.get(i.userId);e&&!e.isMainStreamSubscribed&&!e.isAuxStreamSubscribed&&e.close("you unsubscribed")})}}),si((...r)=>r[0].userId)],At.prototype,"unsubscribe",1);io.create=io._create.bind(io,At);var Cw=io;export{Cw as default};
95
+ 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:l,direction:p,stopped:m})=>({mid:d,currentDirection:l,direction:p,stopped:m})))}`),this._log.warn(`parsedAnswer: ${JSON.stringify(this._parsedAnswer)}`),this._isSDPLogged=!0),this._updateSDPPromise=null,o(c)}})),this._updateSDPPromise}setTransceiverDirection(e,t){return _(this,null,function*(){if(!ie||!this._peerConnection||!this._parsedAnswer)return;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let s=this._peerConnection.getTransceivers();t.forEach(o=>{s[o].direction!==e&&(s[o].direction=e)});for(let o of t){let n=this._parsedAnswer.media[o].direction;e===z.INACTIVE&&n===z.RECVONLY&&(this._parsedAnswer.media[o].direction=e),e===z.SENDONLY&&n===z.INACTIVE&&(this._parsedAnswer.media[o].direction=z.RECVONLY)}yield this.updateSDP()})}filterSDPDirection(e=""){return ce(e).media.map(s=>s.direction)}setOffer(e){return this._log.info("setting offer"),this._log.debug(e.sdp),this._peerConnection.setLocalDescription({type:"offer",sdp:Th(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 _(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let t=!1;this._parsedAnswer.media.forEach(s=>{var o;if(s.type===h.VIDEO){let n=this._serverAbility.video.codecs.find(a=>a.codec.toLowerCase()===e);n&&!((o=s.payloads)!=null&&o.includes(String(n.payload)))&&(s.fmtp=[],s.payloads="",s.rtp=[],s.rtcpFb=[],or(s,n),t=!0)}}),t&&(this._log.warn(`switch video encoder to ${e}`),yield this.setOffer(this._peerConnection.localDescription),yield this.setAnswer({type:"answer",sdp:He(this._parsedAnswer)}))})}useHWEncoder(e=!0,t){return _(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let s=!1,o=[];T(t)?o=this._parsedAnswer.media.slice(1,4):t===2?o.push(this._parsedAnswer.media[1]):t===3?o.push(this._parsedAnswer.media[2]):t===7&&o.push(this._parsedAnswer.media[3]),o.forEach(n=>{var a;if(n.type===h.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=[],or(n,c),s=!0)}}),s&&(this._log.warn(`use ${e?"hw":"sw"} encoder`),yield this.setOffer(this._peerConnection.localDescription),yield this.setAnswer({type:"answer",sdp:He(this._parsedAnswer)}))})}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.insertableStreamsAbortMap.forEach(e=>Tu(e.abort)&&e.abort("destroy")),this.insertableStreamsAbortMap.clear(),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners()}getReceiversByUserId(e){if(!this._peerConnection)return[];let t=this._peerConnection.getReceivers();return(this._downlinkMIDMap.get(e)||[]).map(s=>t[s])}};y([Rn("reconnect")],ui.prototype,"startReconnection",1),y([si(r=>r.userId)],ui.prototype,"addDownlink",1),y([si(r=>r)],ui.prototype,"removeDownlink",1),y([$t(!0)],ui.prototype,"updateSDP",1);var Ud=class{constructor(i){u(this,"tag");u(this,"len");u(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}},Bd=class{constructor(i){u(this,"tinyId");u(this,"data");let e=new DataView(i),t=0,s=[];for(;t<e.byteLength;){let o=e.getUint16(t+2),n=new Ud(new Uint8Array(i).slice(t,t+2+2+o).buffer);s.push(n),t+=2+2+o}s.forEach(o=>{o.tag===1?this.tinyId=new TextDecoder().decode(o.data):o.tag===2&&(this.data=o.data)})}},Ah=new Set;function nr(){let r=Math.floor(Math.random()*4294967296);return Ah.has(r)?nr():(Ah.add(r),r)}var bh=Se(Ne());var ar=class extends bh.default{constructor(e){super();u(this,"userId");u(this,"tinyId");u(this,"_sdpSemantics");u(this,"_isUplink");u(this,"_room");u(this,"_log");u(this,"_currentState","DISCONNECTED");u(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=I.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:(g.emit(E.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 _o=class extends ar{constructor(e){super(P(N({},e),{isUplink:!0}));u(this,"localMainAudioTrack",null);u(this,"localMainVideoTrack",null);u(this,"localAuxAudioTrack",null);u(this,"localAuxVideoTrack",null);u(this,"_isPublishingAux",!1);u(this,"_publishingLocalAudioTrack");u(this,"_publishingLocalVideoTrack");u(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});u(this,"_flag",0);u(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:s,smallVideoSsrc:o,smallVideoRtxSsrc:n,auxVideoSsrc:a,auxVideoRtxSsrc:c}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:s||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:s}=this,o=Object.keys(t).find(n=>t[n]!==s[n]);if(o)if(e)this._log.warn(`publish state not matched, ${o} local:${t[o]} server:${s[o]} ${As()} ${wa()}`),D.addCount({key:521e3});else{this._checkPublishStateTimeoutId=re.run(fi,()=>this.checkPublishState(!0),{delay:10*1e3,count:1});return}re.clearTask(this._checkPublishStateTimeoutId),this._checkPublishStateTimeoutId=-1}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}get publishState(){var t,s,o,n;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(Lt()?(e.audio=!!((t=a[0])!=null&&t.track),e.bigVideo=!!((s=a[1])!=null&&s.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===h.AUDIO?e.audio=!0:(e.bigVideo=!0,this._room.videoManager.hasSmall&&(e.smallVideo=!0)))}))}return e}get serverPublishState(){return{audio:!!(this.flag&mi),bigVideo:!!(this.flag&hi),smallVideo:!!(this.flag&os),auxVideo:!!(this.flag&xi)}}get muteState(){var e,t,s;return{audio:!!((e=this.localMainAudioTrack)!=null&&e.muted),bigVideo:!!((t=this.localMainVideoTrack)!=null&&t.muted),auxVideo:!!((s=this.localAuxVideoTrack)!=null&&s.muted)}}initialize(){this.installEvents()}close(e){var s;let t=((s=this._peerConnection)==null?void 0:s.getSenders())||[];for(let o of t)o.replaceTrack(null);super.close(e),this.uninstallTrackMuteEvents(this.localMainAudioTrack,this.localMainVideoTrack,this.localAuxVideoTrack),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){var e,t;this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),(e=this.singlePC)!=null&&e.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||(t=this.singlePC)==null||t.on("spc-reconnected",this.onSinglePCReconnected,this),yi&&this._room.enableSEI&&!g.listeners(E.SEND_SEI_MESSAGE).includes(this.sendSEIByWorker)&&(this.sendSEIByWorker=this.sendSEIByWorker.bind(this),g.on(E.SEND_SEI_MESSAGE,this.sendSEIByWorker))}uninstallEvents(){var e;this.off("connection-state-changed",this.handleConnectionStateChange,this),(e=this.singlePC)==null||e.off("spc-reconnected",this.onSinglePCReconnected,this),g.off(E.SEND_SEI_MESSAGE,this.sendSEIByWorker)}emitConnectionStateChangedEvent(e,t){var n,a,c;let s=this._currentState,o=super.emitConnectionStateChangedEvent(e);return o&&s!==e&&(t?t.emit("connection-state-changed",{prevState:s,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:s,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:s,state:e}),(c=this._publishingLocalVideoTrack)==null||c.emit("connection-state-changed",{prevState:s,state:e}))),o}onVideoEncodeFailed(e){var t,s;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"),(s=this.singlePC)==null||s.switchVideoEncoder("vp8")))}publish(o){return _(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:s}){var d,l,p,m,f,R,C;if(!this.singlePC)return;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 b({code:A.NOT_SUPPORTED_H264,message:L({key:M.NOT_SUPPORTED_H264ENCODE})});pe&&Qt()===115&&t.profile.width*t.profile.height<=640*360&&(this._log.warn("fallback video to 480p"),t.setProfile(Ze["480p_2"]),yield t.applyProfile()),this._publishingLocalVideoTrack=t,s?(n.auxVideo=!0,a.auxVideo=t.muted):(n.bigVideo=!0,a.bigVideo=t.muted)}this._isPublishingAux=s;let c;if(t&&!s&&t.small&&(c=this._room.videoManager.smallTrack,n.smallVideo=!0),yield this._signalChannel.sendWaitForResponseWithRetry({command:q.SPC_PUBLISH,responseCommand:V.SPC_PUBLISH_RESULT,data:P(N({},this.singlePC.uplinkSSRC),{state:n,muteState:a}),retries:3}),yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:c,isAuxiliary:s}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,t){this[s?"localAuxVideoTrack":"localMainVideoTrack"]=t;let{scaleResolutionDownBy:v}=t;v>1&&(this._log.warn(`setScaleResolutionDownBy ${t.streamType} ${v}`),yield this.singlePC.setScaleResolutionDownBy(this._peerConnection.getSenders()[s?3:1],v))}e&&(this[s?"localAuxAudioTrack":"localMainAudioTrack"]=e),yield this.singlePC.setBandwidth({audio:((d=this.localMainAudioTrack)==null?void 0:d.profile.bitrate)||((l=this.localAuxAudioTrack)==null?void 0:l.profile.bitrate),bigVideo:(p=this.localMainVideoTrack)==null?void 0:p.profile.bitrate,smallVideo:(f=(m=this.localMainVideoTrack)==null?void 0:m.small)==null?void 0:f.bitrate,auxVideo:(R=this.localAuxVideoTrack)==null?void 0:R.profile.bitrate}),this.sendMediaSettings(),this.installTrackMuteEvents(e,t),!s&&(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:s,isAuxiliary:o}){if(!tt())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=[],l=[],p=(f,R,C)=>{var U;let v=c[R].sender.replaceTrack(C);l.push(R),(U=this.singlePC)!=null&&U.enableInsertableStreams&&v.then(()=>this.createEncodedStreams(c[R].sender,f)),d.push(v)};a&&p(e.mediaType,0,a),n&&p(t.mediaType,o?3:1,n),s&&p(8,2,s);let m=this.singlePC.setTransceiverDirection(z.SENDONLY,l);return d.push(m),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 s=e.createEncodedStreams(),o=new AbortController;(a=this.singlePC)==null||a.addAbortController(e,o),((c=this.getTrackByMediaType(t))!=null&&c.enableEncodeFrame?s.readable.pipeThrough(new TransformStream({transform:(d,l)=>{var m;let p=this.getTrackByMediaType(t);l.enqueue(((m=this.singlePC)==null?void 0:m.isUsingH264)&&p?p.encodeFrame(d,t===8):d)}}),o):s.readable).pipeTo(s.writable,o).catch(d=>{this._log.debug("encoded stream error",d),d!=="destory"&&this._log.warn(d)})}sendSEIByWorker({room:e,isMain:t}){var o;if(e!==this._room||!this._peerConnection||!this.singlePC||!this._room.videoManager.seiWorker)return;let s=this._peerConnection.getSenders()[t?1:3];if(!!s&&(s.transform||(s.transform=new RTCRtpScriptTransform(this._room.videoManager.seiWorker,{isReceiver:!1,isMain:t})),t&&((o=this.localMainVideoTrack)==null?void 0:o.small))){let n=this._peerConnection.getSenders()[2];n.transform||(n.transform=new RTCRtpScriptTransform(this._room.videoManager.seiWorker,{isReceiver:!1,isMain:t,small:!0}))}}enableSmall(e){return _(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(z.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(z.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(s){return _(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=P(N({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),c.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=P(N({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),c.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.singlePC.setTransceiverDirection(z.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 _(this,null,function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},s=yield this._signalChannel.sendWaitForResponseWithRetry({command:q.PUBLISH_STATE_CHANGE,data:t,responseCommand:V.PUBLISH_STATE_CHANGE_RESULT,enableLog:e,retries:3});this.checkPublishResultCode(s.data.code,s.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:q.UNPUBLISH,commandDesc:"unpublish",responseCommand:V.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===A.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 s=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:o,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:o=this._publishingLocalVideoTrack),xt){if(s&&s.outMediaTrack){let a=s.outMediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=s.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 s&&s.outMediaTrack&&(this._mediaSettings.audioChannel=s.profile.channelCount,this._mediaSettings.audioBps=s.profile.bitrate*1e3,this._mediaSettings.audioFs=s.profile.sampleRate),o&&o.outMediaTrack&&(this._mediaSettings.videoWidth=o.profile.width,this._mediaSettings.videoHeight=o.profile.height,this._mediaSettings.videoFps=o.profile.frameRate,this._mediaSettings.videoBps=o.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:q.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:V.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return _(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?h.AUXILIARY:h.MAIN} stream`),Lt()&&(yield this.addTrackByTransceiver(e,t))})}addTrackByTransceiver(e,t){return _(this,null,function*(){var o;if(!e.mediaTrack)return;let s=this._peerConnection.getTransceivers();if(e.kind===h.AUDIO)yield s[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield s[n].sender.replaceTrack(e.outMediaTrack),n===1&&((o=this.localMainVideoTrack)==null?void 0:o.small)&&(yield s[2].sender.replaceTrack(this._room.videoManager.smallTrack)),s[n].direction===z.INACTIVE&&(yield this.singlePC.setTransceiverDirection(z.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}removeTrack(e){return _(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?h.AUXILIARY:h.MAIN} stream`),Lt()&&(yield this.removeTrackByTransceiver(e,t))})}removeTrackByTransceiver(e,t){return _(this,null,function*(){if(!e.mediaTrack)return;let s=this._peerConnection.getTransceivers();if(e.kind===h.AUDIO)yield s[0].sender.replaceTrack(null);else{let o=t?3:1;yield s[o].sender.replaceTrack(null),o===1&&this._room.videoManager.hasSmall&&(yield s[2].sender.replaceTrack(null)),yield this.singlePC.setTransceiverDirection(z.INACTIVE,[o])}this.updateMediaSettings(),yield this.doPublishChange()})}replaceTrack(e){return _(this,null,function*(){var n;let t=(n=this._peerConnection)==null?void 0:n.getSenders(),s=e.outMediaTrack||e.mediaTrack;if(!t||t.length===0||!s||t.find(a=>a.track===s))return!1;let o=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info(`is replacing ${s.kind} track ${s.id} on ${o?h.AUXILIARY:h.MAIN} stream`),s.kind===h.AUDIO&&t[0]&&(yield t[0].replaceTrack(s)),s.kind===h.VIDEO&&(!o&&t[1]&&(yield t[1].replaceTrack(s)),o&&t[3]&&(yield t[3].replaceTrack(s))),!0})}setBandwidth(o){return _(this,arguments,function*({bandwidth:e,type:t,videoType:s}){if(this.singlePC){let n={};t===h.AUDIO?n.audio=e:s==="big"?n.bigVideo=e:s==="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:q.UPDATE_MUTE_STAT,responseCommand:V.MUTE_RESULT,data:this.muteState,retries:3}).catch(()=>{}))}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&g.emit(E.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(e=h.VIDEO){if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===h.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===h.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===h.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===h.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===Pi?(this._log.error(Ae.NOT_SUPPORTED_H264ENCODE),new b({code:A.NOT_SUPPORTED_H264,message:L({key:M.NOT_SUPPORTED_H264ENCODE})})):new b({code:A.UNKNOWN,message:L({key:M.SIGNAL_RESPONSE_FAILED,data:{signalResponse:V.PUBLISH_RESULT,code:e,message:t}})})}onSinglePCReconnected(){return _(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}))})}};y([gt(function({localVideoTrack:r}){r==null||r.once("6",this.onVideoEncodeFailed,this)})],_o.prototype,"publish",1),y([gt(function({localVideoTrack:r}){r==null||r.off("6",this.onVideoEncodeFailed,this)})],_o.prototype,"unpublish",1);var $d=_o;function Nh(r){return Object.keys(r).filter(i=>r[i])}var Qr=class extends ar{constructor(e){super(P(N({},e),{isUplink:!1}));u(this,"_flag",0);u(this,"role","anchor");u(this,"remoteAudioTrack");u(this,"remoteVideoTrack");u(this,"remoteAuxiliaryTrack");u(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0});this.flag=e.flag,this.remoteAudioTrack=new oi(this._room,this),this.remoteVideoTrack=new Tt(this._room,this),this.remoteAuxiliaryTrack=new Vr(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 Ai(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,s,o;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(s=this.remoteVideoTrack)==null||s.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===h.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){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,s=super.emitConnectionStateChangedEvent(e);return s&&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})),s}onTrack(e){let t=e.streams[0],{track:s,receiver:o}=e;if(!t.id.includes(this.tinyId))return;let a=t.id.includes("aux")?"auxiliary":"main";this._log.debug(`ontrack ${a} ${s.kind}`);let c=h.AUDIO;s.kind===h.VIDEO&&(c=a===h.MAIN?h.VIDEO:h.AUXILIARY);let d=this.remoteAudioTrack;c===h.VIDEO?d=this.remoteVideoTrack:c===h.AUXILIARY&&(d=this.remoteAuxiliaryTrack),this._room.enableSEI&&yi&&this.receiveSEIByWorker(o,a),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(d,o),d.setInputMediaStreamTrack(s)}createEncodedStreams(e,t){if(!this.singlePC.insertableStreamsAbortMap.has(t)){let s=t.createEncodedStreams(),o=new AbortController,n={abortController:o,enqueue:c=>{var d;return(d=this.singlePC)!=null&&d.isUsingH264?e.decodeFrame(c):c}};(e.enableDecodeFrame?s.readable.pipeThrough(new TransformStream({transform:(c,d)=>d.enqueue(n.enqueue(c))})):s.readable).pipeTo(s.writable,o).catch(c=>{c!=="destory"&&this._log.warn(c)}),this.singlePC.addAbortController(t,o)}}receiveSEIByWorker(e,t){e.track.kind===h.AUDIO||!this._peerConnection||!this.singlePC||!this._room.videoManager.seiWorker||e.transform||(e.transform=new RTCRtpScriptTransform(this._room.videoManager.seiWorker,{isReceiver:!0,userId:this.userId,streamType:t}))}subscribe(e,t){return _(this,null,function*(){try{if(this._log.info(`subscribe ${t} ${Nh(e)}`),this.hasSSRC){let s="subscribe_change";Object.values(e).find(o=>o===!0)||(s="unsubscribe"),yield this.sendSubscription(s,e)}else yield this.doSubscribe(e),this.checkTrackEnded(e)}catch(s){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${s.message} ${JSON.stringify(this.muteState)}`),new b({code:A.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):s}})}checkTrackEnded(e){var t,s,o;if((e.audio&&((t=this.remoteAudioTrack.mediaTrack)==null?void 0:t.readyState)==="ended"||e.video&&((s=this.remoteVideoTrack.mediaTrack)==null?void 0:s.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"),Pe&&ht<92)return;this.singlePC.startReconnection()}}unsubscribe(s){return _(this,arguments,function*({remoteTracks:e,streamType:t}){var a;if(t==="main"&&!this.isMainStreamSubscribed||t==="auxiliary"&&!this.isAuxStreamSubscribed){this._log.info(`${t} stream already unsubscribed`);return}let o=N({},this.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:o.audio=!1;break;case 4:o.video=!1;break;case 8:o.smallVideo=!1;break;case 2:o.auxiliary=!1;break;default:break}});let n="subscribe_change";Object.values(o).find(c=>c===!0)||(n="unsubscribe"),this._log.info(`${n==="unsubscribe"?n:"subscribe"} ${t} [${Nh(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 s={srcTinyId:this.tinyId,srcUserId:this.userId},o=q.UNSUBSCRIBE,n=V.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(s={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},o=q.SUBSCRIBE_CHANGE,n=V.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponseWithRetry({command:o,data:s,responseCommand:n,timeout:1e4,retries:3}).then(({data:a})=>{if(a.code!==0){let c=new b({code:a.code,message:L({key:M.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 _(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 s={audioSsrc:nr(),bigVideoSsrc:nr(),bigVideoRtxSsrc:nr(),auxVideoSsrc:nr(),auxVideoRtxSsrc:nr()},{audioSsrc:o,bigVideoSsrc:n,bigVideoRtxSsrc:a,auxVideoSsrc:c,auxVideoRtxSsrc:d}=s;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 l=yield this._signalChannel.sendWaitForResponseWithRetry({command:q.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:s},retries:3,retryTimeout:0});if(l.data.code!==0)throw new b({code:l.data.code,message:l.data.message})}catch(l){throw yield this.removeDownlink(),l}return}this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc})}finally{let s=this._room.scheduleResult.config;((s==null?void 0:s.jitterDelay)||(s==null?void 0:s.jitterDelayAux))&&this.setJitterBufferDelay({mainDelay:s.jitterDelay,auxDelay:s.jitterDelayAux})}}})}removeDownlink(){return _(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||Zt(e)&&Zt(t))return Promise.resolve();this._log.info(`set jitterBuffer main: ${e} aux: ${t}`);let s=this.singlePC.getReceiversByUserId(this.userId);return ee(e)&&(this.remoteAudioTrack.jitterBufferDelay=e,this.remoteVideoTrack.jitterBufferDelay=e),ee(t)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=t,Zt(e)&&(this.remoteAudioTrack.jitterBufferDelay=t)),new Promise(o=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:s,resolve:o})})}doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:s,resolve:o}){let n=-1;try{if(e===0&&t===0)return s.forEach(c=>c.jitterBufferTarget=0),o();if(s.forEach(c=>{var m;let d=c.track===this.remoteAuxiliaryTrack.outMediaTrack||Zt(e)&&c.track===this.remoteAudioTrack.outMediaTrack;if(d&&Zt(t)||!d&&Zt(e))return;let l=d?t||0:e,p=(c.jitterBufferTarget||0)+100;p>l||(c.jitterBufferTarget=p,this._log.debug(`set ${d?"aux ":""}${(m=c==null?void 0:c.track)==null?void 0:m.kind} jitterBuffer delay ${p} -> ${l}`))}),!s.find(c=>{let d=c.track===this.remoteAuxiliaryTrack.outMediaTrack?t||0:e;return c.jitterBufferTarget<d}))return this._log.info(`set jitterBuffer main: ${e} aux: ${t} done`),o();n=setTimeout(()=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:s,resolve:o})},1e3)}catch(a){this._log.warn(`set jitterBuffer delay error: ${a}`),clearTimeout(n),o()}}};y([$t(),J(r=>function(...i){return new Promise((e,t)=>{let s=o=>{this.off("closed",s),t(new b({code:A.API_CALL_ABORTED,message:L({key:M.CONNECTION_ABORTED,data:o})}))};this.on("closed",s),r.apply(this,i).then(e,t).finally(()=>{this.off("closed",s)})})})],Qr.prototype,"subscribe",1),y([$t()],Qr.prototype,"unsubscribe",1),y([si(()=>"jitter")],Qr.prototype,"setJitterBufferDelay",1);var vh=Qr;function Dh(){return J(r=>function(...i){return _(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(i=i.filter(t=>t.outMediaTrack&&t.state==="capture"),!i.length))return;g.emit("61",{room:this});let e=r.apply(this,i);return i.forEach(t=>t.publish(this,e)),e})})}function Oh(){return J(r=>function(...i){let e=r.apply(this,i);return i.forEach(t=>t.unpublish()),e})}var Mh=Se(Ne());function rf(){return Math.floor(Math.random()*16383)}var Fd=class extends Mh.EventEmitter{constructor(e,t){super();this.room=e;this.signalChannel=t;u(this,"log");u(this,"cmdIdSeqMap",new Map);u(this,"messageMap",new Map);this.log=I.createLogger({id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),t.on(V.RECEIVE_CUSTOM_MSG,this.onReceiveMsg)}send({cmdId:e,data:t}){let s=this.cmdIdSeqMap.get(e)||rf(),o={cmdId:e,msg:btoa(String.fromCharCode(...new Uint8Array(t))),ordered:!0,reliable:!0,streamSeq:s};this.cmdIdSeqMap.set(e,s+1),this.signalChannel.send(q.SEND_CUSTOM_MSG,o),this.log.debug(`send custom msg: ${JSON.stringify(o)}`)}onReceiveMsg(e){let{data:t}=e.data,s=this.room.tinyIdToUserIdMap.get(t.srcTinyId);if(s){let o={userId:s,cmdId:t.cmdId,seq:t.streamSeq,data:Uint8Array.from(atob(t.msg),n=>n.charCodeAt(0)).buffer};if(t.ordered){let n=`${s}_${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)>Fd.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)}}emitMessage(e,t=!1){var a;let s=this.messageMap.get(`${e.userId}_${e.cmdId}`),o=e;if(s){if(t){let c=[...s.cachedMessageMap.values()].sort((d,l)=>d.message.seq-l.message.seq);c[0]&&(o=c[0].message)}s.lastSeq!==0&&o.seq-s.lastSeq>1&&this.log.debug(`msg lost userId: ${o.userId} seq: ${s.lastSeq} -> ${o.seq}`),s.lastSeq=o.seq,clearTimeout((a=s.cachedMessageMap.get(o.seq))==null?void 0:a.timeoutId),s.cachedMessageMap.delete(o.seq)}this.log.debug(`receive custom msg: ${JSON.stringify(o)}`),this.emit("message",o);let n=s==null?void 0:s.cachedMessageMap.get(o.seq+1);n&&this.emitMessage(n.message)}},fo=Fd;u(fo,"SEQ_INTERVAL",300);var{isString:kh,isUndefined:zr,getNetworkType:sf,isEmpty:Eo}=we,At=class extends oa{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=Dr;this._changeBigSmallRecords=new Map;this._networkQuality=null;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._stats=new co(this,this._log),this.userManager=new Bn(this.userId,this._log),this._version=Re,this.sdpSemantics=dr,zr(e.sdpSemantics)?ft.isUnifiedPlanDefault()&&(this.sdpSemantics=pi):this.sdpSemantics=e.sdpSemantics,this._log.info(`sdpSemantics: ${this.sdpSemantics}, netType: ${sf()}`),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=zr(e.enableMultiAuxStream)?!1:e.enableMultiAuxStream,this.enableSEI=e.enableSEI&&Dr,!zr(e.enableSPC)&&Dr&&(this.enableSPC=e.enableSPC),this.preferHW=!!e.preferHW,this._initBusinessInfo(e),this.healthDetector=new Ih(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,s){return _(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=Jd(n,[]);g.emit(E.REMOTE_PUBLISH_STATE_CHANGED,N({room:this},o)),this.emit("remote-publish-state-changed",N({},o))}),this.joinParams=e,new Promise((o,n)=>_(this,null,function*(){var a,c;this._joinReject=n;try{this.checkDestroy();try{yield Promise.all([this.initialize(),this.initSinglePC()])}catch(l){if(l instanceof b&&l.code===A.SPC_INITIALIZED_FAILED)(a=this.signalChannel)==null||a.destroy(),yield this.initialize();else return n(l)}let d=x();yield this.doJoin(e,(c=this.singlePC)==null?void 0:c.clientAbility),D.addSuccessEvent({key:521708,cost:x()-d}),o(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(d){D.addFailedEvent({key:521708,error:d}),n(d)}this._joinReject=null}))})}initSinglePC(){return _(this,null,function*(){if(!(!this.enableSPC||this.singlePC)){this.singlePC=new ui({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 b({code:A.SPC_INITIALIZED_FAILED,message:e==null?void 0:e.message})}}})}doJoin(e,t){return new Promise((s,o)=>_(this,null,function*(){var c,d,l;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this.signalChannel.once(_e.SETUP_FAILED,p=>{this.clearJoinTimeout(),g.emit(E.JOIN_SIGNAL_CONNECTION_END,{room:this,error:p}),o(p)}),de((d=(c=this.scheduleResult)==null?void 0:c.config)==null?void 0:d.singlePC)&&Dr&&(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:Va(),netType:br(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig};this._log.debug(`join room signal data: ${JSON.stringify(n)}`);let a=5e3;((l=this.scheduleResult.config)==null?void 0:l.enterRoomTimeout)&&this.scheduleResult.config.enterRoomTimeout>=1&&(a=this.scheduleResult.config.enterRoomTimeout*1e3),this._joinTimeout=window.setTimeout(()=>{o(new b({code:A.JOIN_ROOM_FAILED,message:L({key:M.JOIN_ROOM_TIMEOUT})}))},a),g.emit(E.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?q.SPC_JOIN_ROOM:q.JOIN_ROOM,n),this.signalChannel.once(V.JOIN_ROOM_RESULT,p=>{this.clearJoinTimeout();let{code:m,message:f,data:R,tinyId:C}=p.data;g.emit(E.JOIN_RECEIVED_CMD_RES,{room:this,code:m}),m===0?(this._log.info("Join room success, start heartbeat"),C&&(this.tinyId=C),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=R.publishers,this.singlePC&&this.singlePC.connect(R.ability).catch(()=>{}),s()):(this._log.error(`Join room failed result: ${m} error: ${f}`),o(new b({code:A.JOIN_ROOM_FAILED,extraCode:m,message:L({key:M.JOIN_ROOM_FAILED,data:{error:f,code:m}})})))})}))}reJoin(e=!0){return _(this,null,function*(){if(!this.isJoined){this._log.warn("reJoin abort");return}try{this._log.warn(`reJoin pending: ${this.joinParams.roomId}`);let t,s=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,s.push(this.initSinglePC().then(o=>(t=o,o)))),this.signalChannel&&(this.signalChannel.race=e,this.signalChannel.close(),s.push(this.signalChannel.connect())),yield Promise.all(s),yield this.doJoin(P(N({},this.joinParams),{role:this.role==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),t),this._log.warn("reJoin success"),Z.logSuccessEvent({userId:this.userId,eventType:Ve.REJOIN}),this.singlePC){let o=n=>{var a;n.state==="CONNECTED"&&((a=this.singlePC)==null||a.off(Wt.CONNECTION_STATE_CHANGED,o),this.uplinkConnection instanceof $d&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach(c=>{c.installEvents(),c.onSinglePCReconnected()}))};this.singlePC.on(Wt.CONNECTION_STATE_CHANGED,o),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof ao&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(t){this._log.warn(`reJoin fail ${t}`),this.reset(),Z.logFailedEvent({userId:this.userId,eventType:Ve.REJOIN,error:t}),this.emit("error",new b({code:A.JOIN_ROOM_FAILED,message:L({key:M.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}})}initialize(){return _(this,null,function*(){let{mainUrl:e,backupUrl:t}=this.getSignalChannelUrl(),s=this.signalChannel||Ql(this.userId),o=!!(s&&s.isConnected&&s.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?(s.url=e,s.backupUrl=t,s.room=this,this.signalChannel=s):(this.signalChannel=new jr({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 fo(this,this.signalChannel),this._customMessageManager.on("message",a=>{this.emit("custom-message",a)})),this._networkQuality||(this._networkQuality=new rr({signalChannel:this.signalChannel,room:this}),this._networkQuality.on(rr.EVENT_NETWORK_QUALITY,a=>{this.emit("network-quality",a)})),De(this,this.signalChannel).add(_e.CONNECTION_STATE_CHANGED,a=>{g.emit(E.SIGNAL_CONNECTION_STATE_CHANGED,N({room:this},a)),this.emit("signal-connection-state-changed",a)}).add(_e.RECONNECT_FAILED,a=>{this.reset(),this.emit("error",a)}).add(V.PEER_JOIN,a=>{let{srcTinyId:c,userId:d,role:l}=a.data.data;this.userManager.addUser({userId:d,tinyId:c,role:l})}).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(Z.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(_e.SETUP_SUCCESS,a=>{this.tinyId=a.signalInfo.tinyId,g.emit(E.JOIN_SIGNAL_CONNECTION_END,{room:this})}),g.emit(E.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),o&&g.emit(E.JOIN_SIGNAL_CONNECTION_END,{room:this}),o})}setSignalChannel(e){this.signalChannel=e,e||me(this)}leave(){return _(this,null,function*(){var e;try{yield this.doHeartbeat()}catch(t){}this._log.info("leave() => leaving room"),g.emit(E.LEAVE_SEND_CMD,{room:this}),(e=this.signalChannel)==null||e.send(q.LEAVE_ROOM)})}clearNetworkQuality(){this._networkQuality&&(this._networkQuality.stop(),this._networkQuality=null)}closeConnections(){this.remotePublishedUserMap.forEach(e=>{this.closeDownLinkConnection(e.userId,"you exitRoom")})}clearJoinTimeout(){clearTimeout(this._joinTimeout),this._joinTimeout=-1}startHeartbeat(){this._heartbeat===-1&&(this._heartbeat=re.run(_i,this.doHeartbeat.bind(this),{delay:2e3}))}stopHeartbeat(){this._heartbeat!==-1&&(this._log.info("stopHeartbeat"),re.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return _(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 s=(n=this.signalChannel)!=null&&n.isConnected?gl(this.userId):[],o=P(N({str_sdk_version:is,uint64_datetime:new Date().getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_event_msg:s,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},t),{msg_device_info:N({uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:br()},t.msg_device_info)});if(this.heartbeatReport=o,g.emit(E.HEARTBEAT_REPORT,{room:this,report:o}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(q.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.emit("heartbeat-report",P(N({},o),{bytes_sent:this._stats.totalBytesSent+this.signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this.signalChannel.bytesReceived}))}!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)})}onPublishedUserList(e){if(!this.isJoined)return;let t=e.data.userList.map(({userId:s,srcTinyId:o,flag:n})=>{s===this.userId&&this.uplinkConnection&&(this.uplinkConnection.flag=n);let a=this.remotePublishedUserMap.get(s);return a&&this.checkSubscribeBigSmallVideo(a),{userId:s,tinyId:o,flag:n}});g.emit(E.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 ao&&(this.uplinkConnection=null)),this.localTracks.forEach(t=>t.unpublish()),this.localTracks.clear()}createDownlinkConnection({userId:e,tinyId:t,flag:s}){let o=new(this.singlePC?vh:bd)({userId:e,tinyId:t,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:s});this.userManager.addRemotePublishedUser(o),this.installDownlinkEvents(o,e),this.emit("remote-published",o)}closeDownLinkConnection(e,t="remote user unpublished"){let s=this.remotePublishedUserMap.get(e);s&&(s.close(t),this.emit("remote-unpublished",s))}installDownlinkEvents(e,t){e.on("error",s=>{let o=s.getCode();o!==A.ICE_TRANSPORT_ERROR&&(o===A.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",s))}),e.on("connection-state-changed",s=>{this.emit("media-connection-state-changed",P(N({},s),{userId:e.userId}))}),e.on("firewall-restriction",()=>{this.emit("firewall-restriction")})}startSyncUserListInterval(){this._syncUserListInterval===-1&&(this._syncUserListInterval=re.run(_i,this.syncUserList.bind(this)))}stopSyncUserListInterval(){re.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:q.GET_USER_LIST,responseCommand:V.USER_LIST_RES,enableLog:!1,timeout:2e3}).then(({data:t})=>{let{code:s,message:o}=t;if(s===0)return(t.data&&t.data.userList||[]).map(({userId:a,srcTinyId:c,role:d})=>({userId:a,tinyId:c,role:d}));throw L({key:M.SIGNAL_RESPONSE_FAILED,data:{signalResponse:V.USER_LIST_RES,code:s,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||!Id)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)===se.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach(s=>{if(s instanceof Ke&&!s.getIsReconnecting()){let o=s.getPeerConnection();o&&o.connectionState===se.CLOSED&&(this._log.warn(`[${s.getUserId()}] pc is closed but not reconnect`),s.startReconnection())}})}fallbackToMPC(){return _(this,null,function*(){var e;if(this._log.warn("fallback to multi pc"),Z.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 ao({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}),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()}this.remotePublishedUserMap.forEach(t=>{let s=new bd({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(s,t.userId),this.remotePublishedUserMap.set(t.userId,s),t.isMainStreamSubscribed&&s.subscribe(t.subscribeState,"main"),t.isAuxStreamSubscribed&&s.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 b({code:A.INVALID_OPERATION,message:L({key:M.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners(),this.healthDetector.destroy())}switchRole(e){return _(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:q.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(s=>{let{code:o,message:n}=s.data;if(o!==0)throw new b({code:A.SWITCH_ROLE_FAILED,message:L({key:M.SWITCH_ROLE_FAILED,data:{message:n,code:o}})});this.role=e}).catch(s=>{throw s instanceof b&&s.getCode()===A.API_CALL_TIMEOUT&&(s=new b({code:A.SWITCH_ROLE_FAILED,message:L({key:M.SWITCH_ROLE_TIMEOUT})})),this._log.error(s),s})}publish(...e){return _(this,null,function*(){let t={},s={};e.forEach(c=>{c instanceof Oe&&(c instanceof Ft?s.audio=c:t.audio=c),c instanceof le&&(c instanceof ze&&c.mediaType===2?s.video=c:t.video=c)});let o=Eo(t),n=Eo(s);(!o||!n)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new $d({userId:this.userId,tinyId:this.tinyId,room:this}):this.uplinkConnection=new ao({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}),this.uplinkConnection.on("connection-state-changed",c=>{this.emit("media-connection-state-changed",P(N({},c),{userId:this.userId}))}),this.uplinkConnection.on("firewall-restriction",()=>{this.emit("firewall-restriction")}),this.uplinkConnection.on("error",c=>{let d=c.getCode();d!==A.ICE_TRANSPORT_ERROR&&(d===A.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:s.audio,localVideoTrack:s.video,isAuxiliary:!0}),this._log.info("aux is published"))})}unpublish(...e){return _(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||!this.isMainStreamPublished&&!this.isAuxStreamPublished||!this.uplinkConnection)return;let t={},s={};e.forEach(o=>{!o.mediaTrack||!o.isPublished||(o instanceof Oe&&(o instanceof Ft?s.audio=o:t.audio=o),o instanceof le&&(o instanceof ze&&o.mediaType===2?s.video=o:t.video=o))});try{let o=e.map(n=>n.kind).join(",");Eo(t)||(this._log.info(`unpublish() => main ${o}`),yield this.uplinkConnection.unpublish({localAudioTrack:t.audio,localVideoTrack:t.video})),Eo(s)||(this._log.info(`unpublish() => aux ${o}`),yield this.uplinkConnection.unpublish({localAudioTrack:s.audio,localVideoTrack:s.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||!tc()?Promise.resolve():this.uplinkConnection.replaceTrack(e).then(t=>{t&&g.emit(E.LOCAL_TRACK_REPLACED,{track:e})})}setBandWidth(e){return _(this,null,function*(){!this.uplinkConnection||(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())})}enableSmall(e){return _(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:h.VIDEO,videoType:h.SMALL,bandwidth:this.uplinkConnection.localMainVideoTrack.small.bitrate})),yield this.uplinkConnection.enableSmall(e)})}subscribe(...e){return _(this,null,function*(){if(e=e.filter(n=>!n.isSubscribed),e.length===0)return;let{userId:t}=e[0],s=this.remotePublishedUserMap.get(t);if(!s)return;let o=e.find(n=>n.mediaType===2)?"auxiliary":"main";try{let n=N({},s.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&&s.muteState.hasSmall&&n.video&&(n.video=!1,n.smallVideo=!0),g.emit(E.SUBSCRIBE_START,{room:this,streamType:o,remotePublishedUser:s,subscribeState:n}),this._log.info(`subscribe() => ${t} ${o} [${Zn(n)}] prev: [${Zn(s.subscribeState)}]`),yield s.subscribe(n,o),this._log.info(`subscribe ${t} ${o} done`);for(let c of e)c.mediaTrack||(yield c.waitHasMediaTrack());g.emit(E.SUBSCRIBE_SUCCESS,{room:this,streamType:o,remotePublishedUser:s})}catch(n){let a=n instanceof b?n.getCode():A.UNKNOWN,c=n;throw n instanceof b?a===A.REMOTE_STREAM_NOT_EXIST&&(c=new b({code:A.API_CALL_ABORTED,message:L({key:M.API_CALL_ABORTED,data:{message:n.message,userId:t,streamType:o}})}),this._log.warn(c)):(c=new b({code:a,message:L({key:M.SUBSCRIBE_FAILED,data:{message:n.message,userId:t,streamType:o}})}),this._log.error(c)),c}})}unsubscribe(...e){return _(this,null,function*(){let{userId:t}=e[0],s=this.remotePublishedUserMap.get(t);if(!s)return;let o=e.find(n=>n.mediaType===2)?"auxiliary":"main";this._log.info(`unsubscribe() => ${t} ${o}`);try{yield s.unsubscribe({remoteTracks:e,streamType:o})}catch(n){this._log.warn(`unsubscribe() => failed ${n}`)}e.forEach(n=>{n.unsubscribe(),n.mediaType===8&&n.setMediaType(4)}),g.emit(E.UNSUBSCRIBE_SUCCESS,{room:this,streamType:o,remotePublishedUser:s})})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAudioVolumeEvaluation(e=2e3,t){if(e<=0){this._enableAudioVolumeEvaluation=!1,re.clearTask(this._audioVolumeIntervalId);return}e=Math.floor(Math.max(e,100)),g.emit(E.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&re.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=re.run(ds,()=>{var o;let s=[];(o=this.remotePublishedUserMap)==null||o.forEach(n=>{if(n.muteState.hasAudio){let a=Math.floor(n.remoteAudioTrack.getAudioLevel()*100);s.push({userId:n.userId,volume:a})}}),this.emit("audio-volume",s)},{fps:1e3/e,backgroundTask:t})}getLocalAudioStats(){return _(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 _(this,null,function*(){var t,s;let e={};return e[this.userId]=((s=(t=this.uplinkConnection)==null?void 0:t.localMainVideoTrack)==null?void 0:s.stat)||{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0},e})}getTransportStats(){return _(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 s=yield this._stats.getReceiverStats(t);e.downlinksRTT[s.userId]=s.rtt}return e})}getRemoteVideoStats(e){return _(this,null,function*(){let t={};for(let[s,o]of this.remotePublishedUserMap)e==="main"&&o.muteState.hasVideo&&(t[s]=o.remoteVideoTrack.stat),e==="auxiliary"&&o.muteState.hasAuxiliary&&(t[s]=o.remoteAuxiliaryTrack.stat);return t})}getRemoteAudioStats(){return _(this,null,function*(){let e={};for(let[t,s]of this.remotePublishedUserMap)s.muteState.hasAudio&&(e[t]=s.remoteAudioTrack.stat);return e})}setTurnServer(e,t){this._log.info(`set turn server: ${JSON.stringify(e)} ${t||""}`);let s=[];Array.isArray(e)?e.forEach(o=>s.push(we.getTurnServer(o))):we.isPlainObject(e)&&s.push(we.getTurnServer(e)),this._turnServers=s,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:q.START_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:V.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:q.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?q.START_PUBLISH_TENCENT_CDN:q.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?q.STOP_PUBLISH_TENCENT_CDN:q.STOP_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?V.STOP_PUBLISH_TENCENT_CDN_RES:V.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}sendAbilityStatus(e){var t;(t=this.signalChannel)==null||t.sendWaitForResponse({command:q.ABILITY_STATUS_REPORT,data:e,timeout:5e3,responseCommand:V.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch(s=>{})}getIceServers(){return this._turnServers.length===0&&this.scheduleResult.iceServers?this.scheduleResult.iceServers:this._turnServers}getIceTransportPolicy(){return this._iceTransportPolicy||this.scheduleResult.iceTransportPolicy||"all"}getLogger(){return this._log}enableAIVoice(){throw new Error("Method not implemented.")}getSignalChannelUrl(){let e={mainUrl:"",backupUrl:""},t=we.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 _(this,null,function*(){let{subscribeState:t,userId:s,muteState:{hasSmall:o,hasVideo:n}}=e;if(!o&&!n||!t.video&&!t.smallVideo)return;let a=this._changeBigSmallRecords.get(s);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 l={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:c.video,smallVideo:c.smallVideo};try{if(!o&&l.smallVideo&&(l.video=!0,l.smallVideo=!1),l.smallVideo===t.smallVideo&&l.video===t.video)return;a.isSubscribing=!0,a.reSubscribeCount=d-1,yield e.subscribe(l,"main"),e.remoteVideoTrack.setMediaType(l.smallVideo?8:4),this._log.info(`change [${s}] to ${l.smallVideo?"small":"big"} video successfully. count ${ur-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount=ur}catch(p){this._log.info(`change [${s}] to ${l.smallVideo?"small":"big"} video failed. count ${ur-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount===0&&this._changeBigSmallRecords.delete(s)}})}changeType(e,t){let o={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:ur};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(kh(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!zr(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new b({code:A.INVALID_PARAMETER,message:L({key:M.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(!zr(e.userDefineRecordId)){let s=/^[A-Za-z0-9_-]{1,64}$/gi;if(e.userDefineRecordId.match(s)===null)throw new b({code:A.INVALID_PARAMETER,message:L({key:M.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!zr(e.userDefinePushArgs))if(kh(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 b({code:A.INVALID_PARAMETER,message:L({key:M.INVALID_USER_DEFINE_PUSH_ARGS})});Eo(t)||(this._businessInfo=JSON.stringify(t))}sendCustomMessage(e){var t;(t=this._customMessageManager)==null||t.send(e)}enableInsertableStreams(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&Or)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 b({code:A.INVALID_OPERATION,message:"not join"}))}};y([Pd(["left",ne.INIT],"joined"),it({settings:{retries:1,timeout:0},onError(r,i,e){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),Mt(!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(),this._log.error(r),e(r))}}),Wl()],At.prototype,"join",1),y([Pd("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),Jl(),Rn("leave room"),Hs({fnName:"publish",validateArgs:!1}),Hs({fnName:"unsubscribe",validateArgs:!1})],At.prototype,"leave",1),y([$t(),Dh(),it({settings:{retries:qt,timeout:r=>kt(r)},onError(r,i,e){var t;(t=r.message)!=null&&t.includes("timeout")?(this._log.warn("publish timeout"),i()):(this._log.error(`publish failed: ${r}`),e(r),g.emit(E.PUBLISH_FAILED,{room:this}))}})],At.prototype,"publish",1),y([Hs({fnName:"publish"}),cl("api-call"),$t(),Oh(),gt(function(){var r,i;this.localTracks.size===0&&Ri()&&((i=(r=this.singlePC)==null?void 0:r.getPeerConnection())==null||i.getSenders().forEach(e=>e.track&&e.replaceTrack(null)))})],At.prototype,"unpublish",1),y([si(r=>r.userId)],At.prototype,"replaceTrack",1),y([si((...r)=>r[0].userId),Nn(),jl(),it({settings:{retries:qt,timeout:r=>kt(r)},onError(r,i,e,t){r.message.includes("timeout")?(this._log.warn("subscribe timeout"),i()):(this._log.error(`subscribe failed: ${r}`),e(r),g.emit(E.SUBSCRIBE_FAILED,{room:this,remoteTracks:t}))}})],At.prototype,"subscribe",1),y([Hs({fnName:"subscribe",callback(...r){this.singlePC||r.forEach(i=>{let e=this.remotePublishedUserMap.get(i.userId);e&&!e.isMainStreamSubscribed&&!e.isAuxStreamSubscribed&&e.close("you unsubscribed")})}}),si((...r)=>r[0].userId)],At.prototype,"unsubscribe",1);io.create=io._create.bind(io,At);var Cw=io;export{Cw as default};